f97b3f91ad882323a017b06197a89c4c02a152a3
[asterisk/asterisk.git] / include / asterisk / lock.h
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  * \brief Asterisk locking-related definitions:
21  * - ast_mutext_t, ast_rwlock_t and related functions;
22  * - atomic arithmetic instructions;
23  * - wrappers for channel locking.
24  *
25  * - See \ref LockDef
26  */
27
28 /*! \page LockDef Asterisk thread locking models
29  *
30  * This file provides different implementation of the functions,
31  * depending on the platform, the use of DEBUG_THREADS, and the way
32  * module-level mutexes are initialized.
33  *
34  *  - \b static: the mutex is assigned the value AST_MUTEX_INIT_VALUE
35  *        this is done at compile time, and is the way used on Linux.
36  *        This method is not applicable to all platforms e.g. when the
37  *        initialization needs that some code is run.
38  *
39  *  - \b through constructors: for each mutex, a constructor function is
40  *        defined, which then runs when the program (or the module)
41  *        starts. The problem with this approach is that there is a
42  *        lot of code duplication (a new block of code is created for
43  *        each mutex). Also, it does not prevent a user from declaring
44  *        a global mutex without going through the wrapper macros,
45  *        so sane programming practices are still required.
46  */
47
48 #ifndef _ASTERISK_LOCK_H
49 #define _ASTERISK_LOCK_H
50
51 #include <pthread.h>
52 #include <sys/param.h>
53 #ifdef HAVE_BKTR
54 #include <execinfo.h>
55 #endif
56 #include "asterisk/logger.h"
57
58 /* internal macro to profile mutexes. Only computes the delay on
59  * non-blocking calls.
60  */
61 #ifndef HAVE_MTX_PROFILE
62 #define __MTX_PROF(a)   return pthread_mutex_lock((a))
63 #else
64 #define __MTX_PROF(a)   do {                    \
65         int i;                                  \
66         /* profile only non-blocking events */  \
67         ast_mark(mtx_prof, 1);                  \
68         i = pthread_mutex_trylock((a));         \
69         ast_mark(mtx_prof, 0);                  \
70         if (!i)                                 \
71                 return i;                       \
72         else                                    \
73                 return pthread_mutex_lock((a)); \
74         } while (0)
75 #endif  /* HAVE_MTX_PROFILE */
76
77 #define AST_PTHREADT_NULL (pthread_t) -1
78 #define AST_PTHREADT_STOP (pthread_t) -2
79
80 #if defined(SOLARIS) || defined(BSD)
81 #define AST_MUTEX_INIT_W_CONSTRUCTORS
82 #endif /* SOLARIS || BSD */
83
84 /* Asterisk REQUIRES recursive (not error checking) mutexes
85    and will not run without them. */
86 #if defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) && defined(HAVE_PTHREAD_MUTEX_RECURSIVE_NP)
87 #define PTHREAD_MUTEX_INIT_VALUE        PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
88 #define AST_MUTEX_KIND                  PTHREAD_MUTEX_RECURSIVE_NP
89 #else
90 #define PTHREAD_MUTEX_INIT_VALUE        PTHREAD_MUTEX_INITIALIZER
91 #define AST_MUTEX_KIND                  PTHREAD_MUTEX_RECURSIVE
92 #endif /* PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
93
94 /*
95  * Definition of ast_mutex_t, ast_cont_d and related functions with/without debugging
96  * (search for DEBUG_THREADS to find the start/end of the sections).
97  *
98  * The non-debug code contains just wrappers for the corresponding pthread functions.
99  * The debug code tracks usage and tries to identify deadlock situations.
100  */
101 #ifdef DEBUG_THREADS
102
103 #define __ast_mutex_logger(...)  do { if (canlog) ast_log(LOG_ERROR, __VA_ARGS__); else fprintf(stderr, __VA_ARGS__); } while (0)
104
105 #ifdef THREAD_CRASH
106 #define DO_THREAD_CRASH do { *((int *)(0)) = 1; } while(0)
107 #else
108 #define DO_THREAD_CRASH do { } while (0)
109 #endif
110
111 #include <errno.h>
112
113 #ifdef HAVE_BKTR
114 #define AST_LOCK_TRACK_INIT_VALUE { { NULL }, { 0 }, 0, { NULL }, { 0 }, {{{ 0 }}}, PTHREAD_MUTEX_INIT_VALUE }
115
116 #else
117 #define AST_LOCK_TRACK_INIT_VALUE { { NULL }, { 0 }, 0, { NULL }, { 0 }, PTHREAD_MUTEX_INIT_VALUE }
118 #endif
119
120 #define AST_MUTEX_INIT_VALUE { AST_LOCK_TRACK_INIT_VALUE, 1, PTHREAD_MUTEX_INIT_VALUE }
121 #define AST_MUTEX_INIT_VALUE_NOTRACKING { AST_LOCK_TRACK_INIT_VALUE, 0, PTHREAD_MUTEX_INIT_VALUE }
122
123 #define AST_MAX_REENTRANCY 10
124
125 struct ast_channel;
126
127 struct ast_lock_track {
128         const char *file[AST_MAX_REENTRANCY];
129         int lineno[AST_MAX_REENTRANCY];
130         int reentrancy;
131         const char *func[AST_MAX_REENTRANCY];
132         pthread_t thread[AST_MAX_REENTRANCY];
133 #ifdef HAVE_BKTR
134         struct ast_bt backtrace[AST_MAX_REENTRANCY];
135 #endif
136         pthread_mutex_t reentr_mutex;
137 };
138
139 struct ast_mutex_info {
140         /*! Track which thread holds this mutex */
141         struct ast_lock_track track;    
142         unsigned int tracking:1;
143         pthread_mutex_t mutex;
144 };
145
146 typedef struct ast_mutex_info ast_mutex_t;
147
148 typedef pthread_cond_t ast_cond_t;
149
150 enum ast_lock_type {
151         AST_MUTEX,
152         AST_RDLOCK,
153         AST_WRLOCK,
154 };
155
156 /*!
157  * \brief Store lock info for the current thread
158  *
159  * This function gets called in ast_mutex_lock() and ast_mutex_trylock() so
160  * that information about this lock can be stored in this thread's
161  * lock info struct.  The lock is marked as pending as the thread is waiting
162  * on the lock.  ast_mark_lock_acquired() will mark it as held by this thread.
163  */
164 #if !defined(LOW_MEMORY)
165 #ifdef HAVE_BKTR
166 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
167         int line_num, const char *func, const char *lock_name, void *lock_addr, struct ast_bt *bt);
168 #else
169 void ast_store_lock_info(enum ast_lock_type type, const char *filename,
170         int line_num, const char *func, const char *lock_name, void *lock_addr);
171 #endif /* HAVE_BKTR */
172
173 #else
174
175 #ifdef HAVE_BKTR
176 #define ast_store_lock_info(I,DONT,CARE,ABOUT,THE,PARAMETERS,BUD)
177 #else
178 #define ast_store_lock_info(I,DONT,CARE,ABOUT,THE,PARAMETERS)
179 #endif /* HAVE_BKTR */
180 #endif /* !defined(LOW_MEMORY) */
181
182 /*!
183  * \brief Mark the last lock as acquired
184  */
185 #if !defined(LOW_MEMORY)
186 void ast_mark_lock_acquired(void *lock_addr);
187 #else
188 #define ast_mark_lock_acquired(ignore)
189 #endif
190
191 /*!
192  * \brief Mark the last lock as failed (trylock)
193  */
194 #if !defined(LOW_MEMORY)
195 void ast_mark_lock_failed(void *lock_addr);
196 #else
197 #define ast_mark_lock_failed(ignore)
198 #endif
199
200 /*!
201  * \brief remove lock info for the current thread
202  *
203  * this gets called by ast_mutex_unlock so that information on the lock can
204  * be removed from the current thread's lock info struct.
205  */
206 #if !defined(LOW_MEMORY)
207 #ifdef HAVE_BKTR
208 void ast_remove_lock_info(void *lock_addr, struct ast_bt *bt);
209 #else
210 void ast_remove_lock_info(void *lock_addr);
211 #endif /* HAVE_BKTR */
212 #else
213 #ifdef HAVE_BKTR
214 #define ast_remove_lock_info(ignore,me)
215 #else
216 #define ast_remove_lock_info(ignore)
217 #endif /* HAVE_BKTR */
218 #endif /* !defined(LOW_MEMORY) */
219
220 #ifdef HAVE_BKTR
221 static inline void __dump_backtrace(struct ast_bt *bt, int canlog)
222 {
223         char **strings;
224
225         ssize_t i;
226
227         strings = backtrace_symbols(bt->addresses, bt->num_frames);
228
229         for (i = 0; i < bt->num_frames; i++)
230                 __ast_mutex_logger("%s\n", strings[i]);
231
232         free(strings);
233 }
234 #endif
235
236 /*!
237  * \brief log info for the current lock with ast_log().
238  *
239  * this function would be mostly for debug. If you come across a lock
240  * that is unexpectedly but momentarily locked, and you wonder who
241  * are fighting with for the lock, this routine could be called, IF
242  * you have the thread debugging stuff turned on.
243  */
244 void log_show_lock(void *this_lock_addr);
245
246 /*!
247  * \brief retrieve lock info for the specified mutex
248  *
249  * this gets called during deadlock avoidance, so that the information may
250  * be preserved as to what location originally acquired the lock.
251  */
252 #if !defined(LOW_MEMORY)
253 int ast_find_lock_info(void *lock_addr, const char **filename, int *lineno, const char **func, const char **mutex_name);
254 #else
255 #define ast_find_lock_info(a,b,c,d,e) -1
256 #endif
257
258 /*!
259  * \brief Unlock a lock briefly
260  *
261  * used during deadlock avoidance, to preserve the original location where
262  * a lock was originally acquired.
263  */
264 #define CHANNEL_DEADLOCK_AVOIDANCE(chan) \
265         do { \
266                 const char *__filename, *__func, *__mutex_name; \
267                 int __lineno; \
268                 int __res = ast_find_lock_info(&chan->lock_dont_use, &__filename, &__lineno, &__func, &__mutex_name); \
269                 ast_channel_unlock(chan); \
270                 usleep(1); \
271                 if (__res < 0) { /* Shouldn't ever happen, but just in case... */ \
272                         ast_channel_lock(chan); \
273                 } else { \
274                         __ast_pthread_mutex_lock(__filename, __lineno, __func, __mutex_name, &chan->lock_dont_use); \
275                 } \
276         } while (0)
277
278 #define DEADLOCK_AVOIDANCE(lock) \
279         do { \
280                 const char *__filename, *__func, *__mutex_name; \
281                 int __lineno; \
282                 int __res = ast_find_lock_info(lock, &__filename, &__lineno, &__func, &__mutex_name); \
283                 ast_mutex_unlock(lock); \
284                 usleep(1); \
285                 if (__res < 0) { /* Shouldn't ever happen, but just in case... */ \
286                         ast_mutex_lock(lock); \
287                 } else { \
288                         __ast_pthread_mutex_lock(__filename, __lineno, __func, __mutex_name, lock); \
289                 } \
290         } while (0)
291
292 #define DLA_UNLOCK(lock) \
293         do { \
294                 const char *__filename, *__func, *__mutex_name; \
295                 int __lineno; \
296                 int __res = ast_find_lock_info(lock, &__filename, &__lineno, &__func, &__mutex_name); \
297                 ast_mutex_unlock(lock);
298
299 #define DLA_LOCK(lock) \
300                 if (__res < 0) { /* Shouldn't ever happen, but just in case... */ \
301                         ast_mutex_lock(lock); \
302                 } else { \
303                         __ast_pthread_mutex_lock(__filename, __lineno, __func, __mutex_name, lock); \
304                 } \
305         } while (0)
306
307 static inline void ast_reentrancy_lock(struct ast_lock_track *lt)
308 {
309         pthread_mutex_lock(&lt->reentr_mutex);
310 }
311
312 static inline void ast_reentrancy_unlock(struct ast_lock_track *lt)
313 {
314         pthread_mutex_unlock(&lt->reentr_mutex);
315 }
316
317 static inline void ast_reentrancy_init(struct ast_lock_track *lt)
318 {
319         int i;
320         pthread_mutexattr_t reentr_attr;
321
322         for (i = 0; i < AST_MAX_REENTRANCY; i++) {
323                 lt->file[i] = NULL;
324                 lt->lineno[i] = 0;
325                 lt->func[i] = NULL;
326                 lt->thread[i] = 0;
327 #ifdef HAVE_BKTR
328                 memset(&lt->backtrace[i], 0, sizeof(lt->backtrace[i]));
329 #endif
330         }
331
332         lt->reentrancy = 0;
333
334         pthread_mutexattr_init(&reentr_attr);
335         pthread_mutexattr_settype(&reentr_attr, AST_MUTEX_KIND);
336         pthread_mutex_init(&lt->reentr_mutex, &reentr_attr);
337         pthread_mutexattr_destroy(&reentr_attr);
338 }
339
340 static inline void delete_reentrancy_cs(struct ast_lock_track *lt)
341 {
342         pthread_mutex_destroy(&lt->reentr_mutex);
343 }
344
345 static inline int __ast_pthread_mutex_init(int tracking, const char *filename, int lineno, const char *func,
346                                                 const char *mutex_name, ast_mutex_t *t) 
347 {
348         int res;
349         pthread_mutexattr_t  attr;
350
351 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
352
353         if ((t->mutex) != ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
354 /*
355                 int canlog = strcmp(filename, "logger.c") & track;
356                 __ast_mutex_logger("%s line %d (%s): NOTICE: mutex '%s' is already initialized.\n",
357                                    filename, lineno, func, mutex_name);
358                 DO_THREAD_CRASH;
359 */
360                 return 0;
361         }
362
363 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
364
365         ast_reentrancy_init(&t->track);
366         t->tracking = tracking;
367
368         pthread_mutexattr_init(&attr);
369         pthread_mutexattr_settype(&attr, AST_MUTEX_KIND);
370
371         res = pthread_mutex_init(&t->mutex, &attr);
372         pthread_mutexattr_destroy(&attr);
373         return res;
374 }
375
376 #define ast_mutex_init(pmutex) __ast_pthread_mutex_init(1, __FILE__, __LINE__, __PRETTY_FUNCTION__, #pmutex, pmutex)
377 #define ast_mutex_init_notracking(pmutex) \
378         __ast_pthread_mutex_init(0, __FILE__, __LINE__, __PRETTY_FUNCTION__, #pmutex, pmutex)
379
380 static inline int __ast_pthread_mutex_destroy(const char *filename, int lineno, const char *func,
381                                                 const char *mutex_name, ast_mutex_t *t)
382 {
383         int res;
384         struct ast_lock_track *lt;
385         int canlog = strcmp(filename, "logger.c") & t->tracking;
386
387 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
388         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
389                 /* Don't try to uninitialize non initialized mutex
390                  * This may no effect on linux
391                  * And always ganerate core on *BSD with 
392                  * linked libpthread
393                  * This not error condition if the mutex created on the fly.
394                  */
395                 __ast_mutex_logger("%s line %d (%s): NOTICE: mutex '%s' is uninitialized.\n",
396                                    filename, lineno, func, mutex_name);
397                 return 0;
398         }
399 #endif
400
401         lt = &t->track;
402
403         res = pthread_mutex_trylock(&t->mutex);
404         switch (res) {
405         case 0:
406                 pthread_mutex_unlock(&t->mutex);
407                 break;
408         case EINVAL:
409                 __ast_mutex_logger("%s line %d (%s): Error: attempt to destroy invalid mutex '%s'.\n",
410                                   filename, lineno, func, mutex_name);
411                 break;
412         case EBUSY:
413                 __ast_mutex_logger("%s line %d (%s): Error: attempt to destroy locked mutex '%s'.\n",
414                                    filename, lineno, func, mutex_name);
415                 ast_reentrancy_lock(lt);
416                 __ast_mutex_logger("%s line %d (%s): Error: '%s' was locked here.\n",
417                             lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1], lt->func[lt->reentrancy-1], mutex_name);
418 #ifdef HAVE_BKTR
419                 __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
420 #endif
421                 ast_reentrancy_unlock(lt);
422                 break;
423         }
424
425
426         if ((res = pthread_mutex_destroy(&t->mutex))) {
427                 __ast_mutex_logger("%s line %d (%s): Error destroying mutex %s: %s\n",
428                                    filename, lineno, func, mutex_name, strerror(res));
429         }
430 #ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
431         else
432                 t->mutex = PTHREAD_MUTEX_INIT_VALUE;
433 #endif
434         ast_reentrancy_lock(lt);
435         lt->file[0] = filename;
436         lt->lineno[0] = lineno;
437         lt->func[0] = func;
438         lt->reentrancy = 0;
439         lt->thread[0] = 0;
440 #ifdef HAVE_BKTR
441         memset(&lt->backtrace[0], 0, sizeof(lt->backtrace[0]));
442 #endif
443         ast_reentrancy_unlock(lt);
444         delete_reentrancy_cs(lt);
445
446         return res;
447 }
448
449 static inline int __ast_pthread_mutex_lock(const char *filename, int lineno, const char *func,
450                                            const char* mutex_name, ast_mutex_t *t)
451 {
452         int res;
453         struct ast_lock_track *lt = &t->track;
454         int canlog = strcmp(filename, "logger.c") & t->tracking;
455 #ifdef HAVE_BKTR
456         struct ast_bt *bt = NULL;
457 #endif
458
459 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
460         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
461                 /* Don't warn abount uninitialized mutex.
462                  * Simple try to initialize it.
463                  * May be not needed in linux system.
464                  */
465                 res = __ast_pthread_mutex_init(t->tracking, filename, lineno, func, mutex_name, t);
466                 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
467                         __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized and unable to initialize.\n",
468                                          filename, lineno, func, mutex_name);
469                         return res;
470                 }               
471         }
472 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
473
474         if (t->tracking) {
475 #ifdef HAVE_BKTR
476                 ast_reentrancy_lock(lt);
477                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
478                 bt = &lt->backtrace[lt->reentrancy];
479                 ast_reentrancy_unlock(lt);
480                 ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex, bt);
481 #else
482                 ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex);
483 #endif
484         }
485
486 #ifdef DETECT_DEADLOCKS
487         {
488                 time_t seconds = time(NULL);
489                 time_t wait_time, reported_wait = 0;
490                 do {
491 #ifdef  HAVE_MTX_PROFILE
492                         ast_mark(mtx_prof, 1);
493 #endif
494                         res = pthread_mutex_trylock(&t->mutex);
495 #ifdef  HAVE_MTX_PROFILE
496                         ast_mark(mtx_prof, 0);
497 #endif
498                         if (res == EBUSY) {
499                                 wait_time = time(NULL) - seconds;
500                                 if (wait_time > reported_wait && (wait_time % 5) == 0) {
501                                         __ast_mutex_logger("%s line %d (%s): Deadlock? waited %d sec for mutex '%s'?\n",
502                                                            filename, lineno, func, (int) wait_time, mutex_name);
503                                         ast_reentrancy_lock(lt);
504 #ifdef HAVE_BKTR
505                                         __dump_backtrace(&lt->backtrace[lt->reentrancy], canlog);
506 #endif
507                                         __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
508                                                            lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1],
509                                                            lt->func[lt->reentrancy-1], mutex_name);
510 #ifdef HAVE_BKTR
511                                         __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
512 #endif
513                                         ast_reentrancy_unlock(lt);
514                                         reported_wait = wait_time;
515                                 }
516                                 usleep(200);
517                         }
518                 } while (res == EBUSY);
519         }
520 #else
521 #ifdef  HAVE_MTX_PROFILE
522         ast_mark(mtx_prof, 1);
523         res = pthread_mutex_trylock(&t->mutex);
524         ast_mark(mtx_prof, 0);
525         if (res)
526 #endif
527         res = pthread_mutex_lock(&t->mutex);
528 #endif /* DETECT_DEADLOCKS */
529
530         if (!res) {
531                 ast_reentrancy_lock(lt);
532                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
533                         lt->file[lt->reentrancy] = filename;
534                         lt->lineno[lt->reentrancy] = lineno;
535                         lt->func[lt->reentrancy] = func;
536                         lt->thread[lt->reentrancy] = pthread_self();
537                         lt->reentrancy++;
538                 } else {
539                         __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
540                                                            filename, lineno, func, mutex_name);
541                 }
542                 ast_reentrancy_unlock(lt);
543                 if (t->tracking) {
544                         ast_mark_lock_acquired(&t->mutex);
545                 }
546         } else {
547 #ifdef HAVE_BKTR
548                 if (lt->reentrancy) {
549                         ast_reentrancy_lock(lt);
550                         bt = &lt->backtrace[lt->reentrancy-1];
551                         ast_reentrancy_unlock(lt);
552                 } else {
553                         bt = NULL;
554                 }
555                 if (t->tracking) {
556                         ast_remove_lock_info(&t->mutex, bt);
557                 }
558 #else
559                 if (t->tracking) {
560                         ast_remove_lock_info(&t->mutex);
561                 }
562 #endif
563                 __ast_mutex_logger("%s line %d (%s): Error obtaining mutex: %s\n",
564                                    filename, lineno, func, strerror(res));
565                 DO_THREAD_CRASH;
566         }
567
568         return res;
569 }
570
571 static inline int __ast_pthread_mutex_trylock(const char *filename, int lineno, const char *func,
572                                               const char* mutex_name, ast_mutex_t *t)
573 {
574         int res;
575         struct ast_lock_track *lt= &t->track;
576         int canlog = strcmp(filename, "logger.c") & t->tracking;
577 #ifdef HAVE_BKTR
578         struct ast_bt *bt = NULL;
579 #endif
580
581 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
582         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
583                 /* Don't warn abount uninitialized mutex.
584                  * Simple try to initialize it.
585                  * May be not needed in linux system.
586                  */
587                 res = __ast_pthread_mutex_init(t->tracking, filename, lineno, func, mutex_name, t);
588                 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
589                         __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized and unable to initialize.\n",
590                                          filename, lineno, func, mutex_name);
591                         return res;
592                 }               
593         }
594 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
595
596         if (t->tracking) {
597 #ifdef HAVE_BKTR
598                 ast_reentrancy_lock(lt);
599                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
600                 bt = &lt->backtrace[lt->reentrancy];
601                 ast_reentrancy_unlock(lt);
602                 ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex, bt);
603 #else
604                 ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex);
605 #endif
606         }
607
608         if (!(res = pthread_mutex_trylock(&t->mutex))) {
609                 ast_reentrancy_lock(lt);
610                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
611                         lt->file[lt->reentrancy] = filename;
612                         lt->lineno[lt->reentrancy] = lineno;
613                         lt->func[lt->reentrancy] = func;
614                         lt->thread[lt->reentrancy] = pthread_self();
615                         lt->reentrancy++;
616                 } else {
617                         __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
618                                            filename, lineno, func, mutex_name);
619                 }
620                 ast_reentrancy_unlock(lt);
621                 if (t->tracking) {
622                         ast_mark_lock_acquired(&t->mutex);
623                 }
624         } else if (t->tracking) {
625                 ast_mark_lock_failed(&t->mutex);
626         }
627
628         return res;
629 }
630
631 static inline int __ast_pthread_mutex_unlock(const char *filename, int lineno, const char *func,
632                                              const char *mutex_name, ast_mutex_t *t)
633 {
634         int res;
635         struct ast_lock_track *lt = &t->track;
636         int canlog = strcmp(filename, "logger.c") & t->tracking;
637 #ifdef HAVE_BKTR
638         struct ast_bt *bt = NULL;
639 #endif
640
641 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
642         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
643                 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
644                                    filename, lineno, func, mutex_name);
645                 res = __ast_pthread_mutex_init(t->tracking, filename, lineno, func, mutex_name, t);
646                 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
647                         __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized and unable to initialize.\n",
648                                          filename, lineno, func, mutex_name);
649                 }
650                 return res;
651         }
652 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
653
654         ast_reentrancy_lock(lt);
655         if (lt->reentrancy && (lt->thread[lt->reentrancy-1] != pthread_self())) {
656                 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
657                                    filename, lineno, func, mutex_name);
658                 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
659                                    lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1], lt->func[lt->reentrancy-1], mutex_name);
660 #ifdef HAVE_BKTR
661                 __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
662 #endif
663                 DO_THREAD_CRASH;
664         }
665
666         if (--lt->reentrancy < 0) {
667                 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
668                                    filename, lineno, func, mutex_name);
669                 lt->reentrancy = 0;
670         }
671
672         if (lt->reentrancy < AST_MAX_REENTRANCY) {
673                 lt->file[lt->reentrancy] = NULL;
674                 lt->lineno[lt->reentrancy] = 0;
675                 lt->func[lt->reentrancy] = NULL;
676                 lt->thread[lt->reentrancy] = 0;
677         }
678
679 #ifdef HAVE_BKTR
680         if (lt->reentrancy) {
681                 bt = &lt->backtrace[lt->reentrancy - 1];
682         }
683 #endif
684         ast_reentrancy_unlock(lt);
685
686         if (t->tracking) {
687 #ifdef HAVE_BKTR
688                 ast_remove_lock_info(&t->mutex, bt);
689 #else
690                 ast_remove_lock_info(&t->mutex);
691 #endif
692         }
693
694         if ((res = pthread_mutex_unlock(&t->mutex))) {
695                 __ast_mutex_logger("%s line %d (%s): Error releasing mutex: %s\n", 
696                                    filename, lineno, func, strerror(res));
697                 DO_THREAD_CRASH;
698         }
699
700         return res;
701 }
702
703 static inline int __ast_cond_init(const char *filename, int lineno, const char *func,
704                                   const char *cond_name, ast_cond_t *cond, pthread_condattr_t *cond_attr)
705 {
706         return pthread_cond_init(cond, cond_attr);
707 }
708
709 static inline int __ast_cond_signal(const char *filename, int lineno, const char *func,
710                                     const char *cond_name, ast_cond_t *cond)
711 {
712         return pthread_cond_signal(cond);
713 }
714
715 static inline int __ast_cond_broadcast(const char *filename, int lineno, const char *func,
716                                        const char *cond_name, ast_cond_t *cond)
717 {
718         return pthread_cond_broadcast(cond);
719 }
720
721 static inline int __ast_cond_destroy(const char *filename, int lineno, const char *func,
722                                      const char *cond_name, ast_cond_t *cond)
723 {
724         return pthread_cond_destroy(cond);
725 }
726
727 static inline int __ast_cond_wait(const char *filename, int lineno, const char *func,
728                                   const char *cond_name, const char *mutex_name,
729                                   ast_cond_t *cond, ast_mutex_t *t)
730 {
731         int res;
732         struct ast_lock_track *lt= &t->track;
733         int canlog = strcmp(filename, "logger.c") & t->tracking;
734 #ifdef HAVE_BKTR
735         struct ast_bt *bt = NULL;
736 #endif
737
738 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
739         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
740                 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
741                                    filename, lineno, func, mutex_name);
742                 res = __ast_pthread_mutex_init(t->tracking, filename, lineno, func, mutex_name, t);
743                 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
744                         __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized and unable to initialize.\n",
745                                          filename, lineno, func, mutex_name);
746                 }
747                 return res;
748         }
749 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
750
751         ast_reentrancy_lock(lt);
752         if (lt->reentrancy && (lt->thread[lt->reentrancy-1] != pthread_self())) {
753                 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
754                                    filename, lineno, func, mutex_name);
755                 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
756                                    lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1], lt->func[lt->reentrancy-1], mutex_name);
757 #ifdef HAVE_BKTR
758                 __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
759 #endif
760                 DO_THREAD_CRASH;
761         }
762
763         if (--lt->reentrancy < 0) {
764                 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
765                                    filename, lineno, func, mutex_name);
766                 lt->reentrancy = 0;
767         }
768
769         if (lt->reentrancy < AST_MAX_REENTRANCY) {
770                 lt->file[lt->reentrancy] = NULL;
771                 lt->lineno[lt->reentrancy] = 0;
772                 lt->func[lt->reentrancy] = NULL;
773                 lt->thread[lt->reentrancy] = 0;
774         }
775
776 #ifdef HAVE_BKTR
777         if (lt->reentrancy) {
778                 bt = &lt->backtrace[lt->reentrancy - 1];
779         }
780 #endif
781         ast_reentrancy_unlock(lt);
782
783         if (t->tracking) {
784 #ifdef HAVE_BKTR
785                 ast_remove_lock_info(&t->mutex, bt);
786 #else
787                 ast_remove_lock_info(&t->mutex);
788 #endif
789         }
790
791         if ((res = pthread_cond_wait(cond, &t->mutex))) {
792                 __ast_mutex_logger("%s line %d (%s): Error waiting on condition mutex '%s'\n", 
793                                    filename, lineno, func, strerror(res));
794                 DO_THREAD_CRASH;
795         } else {
796                 ast_reentrancy_lock(lt);
797                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
798                         lt->file[lt->reentrancy] = filename;
799                         lt->lineno[lt->reentrancy] = lineno;
800                         lt->func[lt->reentrancy] = func;
801                         lt->thread[lt->reentrancy] = pthread_self();
802 #ifdef HAVE_BKTR
803                         ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
804                         bt = &lt->backtrace[lt->reentrancy];
805 #endif
806                         lt->reentrancy++;
807                 } else {
808                         __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
809                                                            filename, lineno, func, mutex_name);
810                 }
811                 ast_reentrancy_unlock(lt);
812
813                 if (t->tracking) {
814 #ifdef HAVE_BKTR
815                         ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex, bt);
816 #else
817                         ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex);
818 #endif
819                 }
820         }
821
822         return res;
823 }
824
825 static inline int __ast_cond_timedwait(const char *filename, int lineno, const char *func,
826                                        const char *cond_name, const char *mutex_name, ast_cond_t *cond,
827                                        ast_mutex_t *t, const struct timespec *abstime)
828 {
829         int res;
830         struct ast_lock_track *lt = &t->track;
831         int canlog = strcmp(filename, "logger.c") & t->tracking;
832 #ifdef HAVE_BKTR
833         struct ast_bt *bt = NULL;
834 #endif
835
836 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
837         if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
838                 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
839                                    filename, lineno, func, mutex_name);
840                 res = __ast_pthread_mutex_init(t->tracking, filename, lineno, func, mutex_name, t);
841                 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
842                         __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized and unable to initialize.\n",
843                                          filename, lineno, func, mutex_name);
844                 }
845                 return res;
846         }
847 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
848
849         ast_reentrancy_lock(lt);
850         if (lt->reentrancy && (lt->thread[lt->reentrancy-1] != pthread_self())) {
851                 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
852                                    filename, lineno, func, mutex_name);
853                 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
854                                    lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1], lt->func[lt->reentrancy-1], mutex_name);
855 #ifdef HAVE_BKTR
856                 __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
857 #endif
858                 DO_THREAD_CRASH;
859         }
860
861         if (--lt->reentrancy < 0) {
862                 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
863                                    filename, lineno, func, mutex_name);
864                 lt->reentrancy = 0;
865         }
866
867         if (lt->reentrancy < AST_MAX_REENTRANCY) {
868                 lt->file[lt->reentrancy] = NULL;
869                 lt->lineno[lt->reentrancy] = 0;
870                 lt->func[lt->reentrancy] = NULL;
871                 lt->thread[lt->reentrancy] = 0;
872         }
873 #ifdef HAVE_BKTR
874         if (lt->reentrancy) {
875                 bt = &lt->backtrace[lt->reentrancy - 1];
876         }
877 #endif
878         ast_reentrancy_unlock(lt);
879
880         if (t->tracking) {
881 #ifdef HAVE_BKTR
882                 ast_remove_lock_info(&t->mutex, bt);
883 #else
884                 ast_remove_lock_info(&t->mutex);
885 #endif
886         }
887         
888         if ((res = pthread_cond_timedwait(cond, &t->mutex, abstime)) && (res != ETIMEDOUT)) {
889                 __ast_mutex_logger("%s line %d (%s): Error waiting on condition mutex '%s'\n", 
890                                    filename, lineno, func, strerror(res));
891                 DO_THREAD_CRASH;
892         } else {
893                 ast_reentrancy_lock(lt);
894                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
895                         lt->file[lt->reentrancy] = filename;
896                         lt->lineno[lt->reentrancy] = lineno;
897                         lt->func[lt->reentrancy] = func;
898                         lt->thread[lt->reentrancy] = pthread_self();
899 #ifdef HAVE_BKTR
900                         ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
901                         bt = &lt->backtrace[lt->reentrancy];
902 #endif
903                         lt->reentrancy++;
904                 } else {
905                         __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
906                                                            filename, lineno, func, mutex_name);
907                 }
908                 ast_reentrancy_unlock(lt);
909
910                 if (t->tracking) {
911 #ifdef HAVE_BKTR
912                         ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex, bt);
913 #else
914                         ast_store_lock_info(AST_MUTEX, filename, lineno, func, mutex_name, &t->mutex);
915 #endif
916                 }
917         }
918
919         return res;
920 }
921
922 #define ast_mutex_destroy(a)                    __ast_pthread_mutex_destroy(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
923 #define ast_mutex_lock(a)                       __ast_pthread_mutex_lock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
924 #define ast_mutex_unlock(a)                     __ast_pthread_mutex_unlock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
925 #define ast_mutex_trylock(a)                    __ast_pthread_mutex_trylock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
926 #define ast_cond_init(cond, attr)               __ast_cond_init(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond, attr)
927 #define ast_cond_destroy(cond)                  __ast_cond_destroy(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
928 #define ast_cond_signal(cond)                   __ast_cond_signal(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
929 #define ast_cond_broadcast(cond)                __ast_cond_broadcast(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
930 #define ast_cond_wait(cond, mutex)              __ast_cond_wait(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, #mutex, cond, mutex)
931 #define ast_cond_timedwait(cond, mutex, time)   __ast_cond_timedwait(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, #mutex, cond, mutex, time)
932
933 struct ast_rwlock_info {
934         /*! Track which thread holds this lock */
935         struct ast_lock_track track;
936         unsigned int tracking:1;
937         pthread_rwlock_t lock;
938 };
939
940 typedef struct ast_rwlock_info ast_rwlock_t;
941
942 #define ast_rwlock_init(rwlock) __ast_rwlock_init(1, __FILE__, __LINE__, __PRETTY_FUNCTION__, #rwlock, rwlock)
943 #define ast_rwlock_init_notracking(rwlock) __ast_rwlock_init(0, __FILE__, __LINE__, __PRETTY_FUNCTION__, #rwlock, rwlock)
944
945 #define ast_rwlock_destroy(rwlock)      __ast_rwlock_destroy(__FILE__, __LINE__, __PRETTY_FUNCTION__, #rwlock, rwlock)
946 #define ast_rwlock_unlock(a)            _ast_rwlock_unlock(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
947 #define ast_rwlock_rdlock(a)            _ast_rwlock_rdlock(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
948 #define ast_rwlock_wrlock(a)            _ast_rwlock_wrlock(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
949 #define ast_rwlock_tryrdlock(a)         _ast_rwlock_tryrdlock(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
950 #define ast_rwlock_trywrlock(a) _ast_rwlock_trywrlock(a, # a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
951
952
953 #ifdef HAVE_PTHREAD_RWLOCK_INITIALIZER
954 #define __AST_RWLOCK_INIT_VALUE PTHREAD_RWLOCK_INITIALIZER
955 #else  /* HAVE_PTHREAD_RWLOCK_INITIALIZER */
956 #define __AST_RWLOCK_INIT_VALUE {0} 
957 #endif /* HAVE_PTHREAD_RWLOCK_INITIALIZER */
958
959 #define AST_RWLOCK_INIT_VALUE \
960         { AST_LOCK_TRACK_INIT_VALUE, 1, __AST_RWLOCK_INIT_VALUE }
961 #define AST_RWLOCK_INIT_VALUE_NOTRACKING \
962         { AST_LOCK_TRACK_INIT_VALUE, 0, __AST_RWLOCK_INIT_VALUE }
963
964 static inline int __ast_rwlock_init(int tracking, const char *filename, int lineno, const char *func, const char *rwlock_name, ast_rwlock_t *t)
965 {
966         int res;
967         struct ast_lock_track *lt= &t->track;
968         pthread_rwlockattr_t attr;
969
970 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
971         int canlog = strcmp(filename, "logger.c") & t->tracking;
972
973         if (t->lock != ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
974                 __ast_mutex_logger("%s line %d (%s): Warning: rwlock '%s' is already initialized.\n",
975                                 filename, lineno, func, rwlock_name);
976                 return 0;
977         }
978 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
979
980         ast_reentrancy_init(lt);
981         t->tracking = tracking;
982         pthread_rwlockattr_init(&attr);
983
984 #ifdef HAVE_PTHREAD_RWLOCK_PREFER_WRITER_NP
985         pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NP);
986 #endif
987
988         res = pthread_rwlock_init(&t->lock, &attr);
989         pthread_rwlockattr_destroy(&attr);
990         return res;
991 }
992
993 static inline int __ast_rwlock_destroy(const char *filename, int lineno, const char *func, const char *rwlock_name, ast_rwlock_t *t)
994 {
995         int res;
996         struct ast_lock_track *lt = &t->track;
997         int canlog = strcmp(filename, "logger.c") & t->tracking;
998
999 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1000         if (t->lock == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1001                 __ast_mutex_logger("%s line %d (%s): Warning: rwlock '%s' is uninitialized.\n",
1002                                    filename, lineno, func, rwlock_name);
1003                 return 0;
1004         }
1005 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1006         
1007         if ((res = pthread_rwlock_destroy(&t->lock))) {
1008                 __ast_mutex_logger("%s line %d (%s): Error destroying rwlock %s: %s\n",
1009                                 filename, lineno, func, rwlock_name, strerror(res));
1010         }
1011         ast_reentrancy_lock(lt);
1012         lt->file[0] = filename;
1013         lt->lineno[0] = lineno;
1014         lt->func[0] = func;
1015         lt->reentrancy = 0;
1016         lt->thread[0] = 0;
1017 #ifdef HAVE_BKTR
1018         memset(&lt->backtrace[0], 0, sizeof(lt->backtrace[0]));
1019 #endif
1020         ast_reentrancy_unlock(lt);
1021         delete_reentrancy_cs(lt);
1022
1023         return res;
1024 }
1025
1026 static inline int _ast_rwlock_unlock(ast_rwlock_t *t, const char *name,
1027         const char *filename, int line, const char *func)
1028 {
1029         int res;
1030         struct ast_lock_track *lt = &t->track;
1031         int canlog = strcmp(filename, "logger.c") & t->tracking;
1032 #ifdef HAVE_BKTR
1033         struct ast_bt *bt = NULL;
1034 #endif
1035
1036
1037 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1038         if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1039                 __ast_mutex_logger("%s line %d (%s): Warning: rwlock '%s' is uninitialized.\n",
1040                                    filename, line, func, name);
1041                 res = __ast_rwlock_init(t->tracking, filename, line, func, name, t);
1042                 if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1043                         __ast_mutex_logger("%s line %d (%s): Error: rwlock '%s' is uninitialized and unable to initialize.\n",
1044                                         filename, line, func, name);
1045                 }
1046                 return res;
1047         }
1048 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1049         
1050         ast_reentrancy_lock(lt);
1051         if (lt->reentrancy) {
1052                 int lock_found = 0;
1053                 int i;
1054                 for (i = lt->reentrancy-1; i >= 0; --i) {
1055                         if (lt->thread[i] == pthread_self()) {
1056                                 lock_found = 1;
1057                                 if (i != lt->reentrancy-1) {
1058                                         lt->file[i] = lt->file[lt->reentrancy-1];
1059                                         lt->lineno[i] = lt->lineno[lt->reentrancy-1];
1060                                         lt->func[i] = lt->func[lt->reentrancy-1];
1061                                         lt->thread[i] = lt->thread[lt->reentrancy-1];
1062                                 }
1063                                 break;
1064                         }
1065                 }
1066                 if (!lock_found) {
1067                         __ast_mutex_logger("%s line %d (%s): attempted unlock rwlock '%s' without owning it!\n",
1068                                                 filename, line, func, name);
1069                         __ast_mutex_logger("%s line %d (%s): '%s' was last locked here.\n",
1070                                         lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1], lt->func[lt->reentrancy-1], name);
1071 #ifdef HAVE_BKTR
1072                 __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
1073 #endif
1074                 DO_THREAD_CRASH;
1075                 }
1076         }
1077
1078         if (--lt->reentrancy < 0) {
1079                 __ast_mutex_logger("%s line %d (%s): rwlock '%s' freed more times than we've locked!\n",
1080                                 filename, line, func, name);
1081                 lt->reentrancy = 0;
1082         }
1083
1084 #ifdef HAVE_BKTR
1085         if (lt->reentrancy) {
1086                 bt = &lt->backtrace[lt->reentrancy - 1];
1087         }
1088 #endif
1089         ast_reentrancy_unlock(lt);
1090
1091         if (t->tracking) {
1092 #ifdef HAVE_BKTR
1093                 ast_remove_lock_info(&t->lock, bt);
1094 #else
1095                 ast_remove_lock_info(&t->lock);
1096 #endif
1097         }
1098
1099         if ((res = pthread_rwlock_unlock(&t->lock))) {
1100                 __ast_mutex_logger("%s line %d (%s): Error releasing rwlock: %s\n",
1101                                 filename, line, func, strerror(res));
1102                 DO_THREAD_CRASH;
1103         }
1104
1105         return res;
1106 }
1107
1108 static inline int _ast_rwlock_rdlock(ast_rwlock_t *t, const char *name,
1109         const char *filename, int line, const char *func)
1110 {
1111         int res;
1112         struct ast_lock_track *lt = &t->track;
1113         int canlog = strcmp(filename, "logger.c") & t->tracking;
1114 #ifdef HAVE_BKTR
1115         struct ast_bt *bt = NULL;
1116 #endif
1117
1118 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1119         if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1120                  /* Don't warn abount uninitialized lock.
1121                   * Simple try to initialize it.
1122                   * May be not needed in linux system.
1123                   */
1124                 res = __ast_rwlock_init(t->tracking, filename, line, func, name, t);
1125                 if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1126                         __ast_mutex_logger("%s line %d (%s): Error: rwlock '%s' is uninitialized and unable to initialize.\n",
1127                                         filename, line, func, name);
1128                         return res;
1129                 }
1130         }
1131 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1132
1133         if (t->tracking) {
1134 #ifdef HAVE_BKTR
1135                 ast_reentrancy_lock(lt);
1136                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
1137                 bt = &lt->backtrace[lt->reentrancy];
1138                 ast_reentrancy_unlock(lt);      
1139                 ast_store_lock_info(AST_RDLOCK, filename, line, func, name, &t->lock, bt);
1140 #else
1141                 ast_store_lock_info(AST_RDLOCK, filename, line, func, name, &t->lock);
1142 #endif
1143         }
1144         
1145 #ifdef DETECT_DEADLOCKS
1146         {
1147                 time_t seconds = time(NULL);
1148                 time_t wait_time, reported_wait = 0;
1149                 do {
1150                         res = pthread_rwlock_tryrdlock(&t->lock);
1151                         if (res == EBUSY) {
1152                                 wait_time = time(NULL) - seconds;
1153                                 if (wait_time > reported_wait && (wait_time % 5) == 0) {
1154                                         __ast_mutex_logger("%s line %d (%s): Deadlock? waited %d sec for readlock '%s'?\n",
1155                                                 filename, line, func, (int)wait_time, name);
1156                                         ast_reentrancy_lock(lt);
1157 #ifdef HAVE_BKTR
1158                                         __dump_backtrace(&lt->backtrace[lt->reentrancy], canlog);
1159 #endif
1160                                         __ast_mutex_logger("%s line %d (%s): '%s' was locked  here.\n",
1161                                                         lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1],
1162                                                         lt->func[lt->reentrancy-1], name);
1163 #ifdef HAVE_BKTR
1164                                         __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
1165 #endif
1166                                         ast_reentrancy_unlock(lt);
1167                                         reported_wait = wait_time;
1168                                 }
1169                                 usleep(200);
1170                         }
1171                 } while (res == EBUSY);
1172         }
1173 #else /* !DETECT_DEADLOCKS */
1174         res = pthread_rwlock_rdlock(&t->lock);
1175 #endif /* !DETECT_DEADLOCKS */
1176         
1177         if (!res) {
1178                 ast_reentrancy_lock(lt);
1179                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
1180                         lt->file[lt->reentrancy] = filename;
1181                         lt->lineno[lt->reentrancy] = line;
1182                         lt->func[lt->reentrancy] = func;
1183                         lt->thread[lt->reentrancy] = pthread_self();
1184                         lt->reentrancy++;
1185                 } else {
1186                         __ast_mutex_logger("%s line %d (%s): read lock '%s' really deep reentrancy!\n",
1187                                         filename, line, func, name);
1188                 }
1189                 ast_reentrancy_unlock(lt);
1190                 if (t->tracking) {
1191                         ast_mark_lock_acquired(&t->lock);
1192                 }
1193         } else {
1194 #ifdef HAVE_BKTR
1195                 if (lt->reentrancy) {
1196                         ast_reentrancy_lock(lt);
1197                         bt = &lt->backtrace[lt->reentrancy-1];
1198                         ast_reentrancy_unlock(lt);
1199                 } else {
1200                         bt = NULL;
1201                 }
1202                 if (t->tracking) {
1203                         ast_remove_lock_info(&t->lock, bt);
1204                 }
1205 #else
1206                 if (t->tracking) {
1207                         ast_remove_lock_info(&t->lock);
1208                 }
1209 #endif
1210                 __ast_mutex_logger("%s line %d (%s): Error obtaining read lock: %s\n",
1211                                 filename, line, func, strerror(res));
1212                 DO_THREAD_CRASH;
1213         }
1214         return res;
1215 }
1216
1217 static inline int _ast_rwlock_wrlock(ast_rwlock_t *t, const char *name,
1218         const char *filename, int line, const char *func)
1219 {
1220         int res;
1221         struct ast_lock_track *lt = &t->track;
1222         int canlog = strcmp(filename, "logger.c") & t->tracking;
1223 #ifdef HAVE_BKTR
1224         struct ast_bt *bt = NULL;
1225 #endif
1226
1227 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1228         if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1229                  /* Don't warn abount uninitialized lock.
1230                   * Simple try to initialize it.
1231                   * May be not needed in linux system.
1232                   */
1233                 res = __ast_rwlock_init(t->tracking, filename, line, func, name, t);
1234                 if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1235                         __ast_mutex_logger("%s line %d (%s): Error: rwlock '%s' is uninitialized and unable to initialize.\n",
1236                                         filename, line, func, name);
1237                         return res;
1238                 }
1239         }
1240 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1241
1242         if (t->tracking) {
1243 #ifdef HAVE_BKTR
1244                 ast_reentrancy_lock(lt);
1245                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
1246                 bt = &lt->backtrace[lt->reentrancy];
1247                 ast_reentrancy_unlock(lt);
1248                 ast_store_lock_info(AST_WRLOCK, filename, line, func, name, &t->lock, bt);
1249 #else
1250                 ast_store_lock_info(AST_WRLOCK, filename, line, func, name, &t->lock);
1251 #endif
1252         }
1253 #ifdef DETECT_DEADLOCKS
1254         {
1255                 time_t seconds = time(NULL);
1256                 time_t wait_time, reported_wait = 0;
1257                 do {
1258                         res = pthread_rwlock_trywrlock(&t->lock);
1259                         if (res == EBUSY) {
1260                                 wait_time = time(NULL) - seconds;
1261                                 if (wait_time > reported_wait && (wait_time % 5) == 0) {
1262                                         __ast_mutex_logger("%s line %d (%s): Deadlock? waited %d sec for writelock '%s'?\n",
1263                                                 filename, line, func, (int)wait_time, name);
1264                                         ast_reentrancy_lock(lt);
1265 #ifdef HAVE_BKTR
1266                                         __dump_backtrace(&lt->backtrace[lt->reentrancy], canlog);
1267 #endif
1268                                         __ast_mutex_logger("%s line %d (%s): '%s' was locked  here.\n",
1269                                                         lt->file[lt->reentrancy-1], lt->lineno[lt->reentrancy-1],
1270                                                         lt->func[lt->reentrancy-1], name);
1271 #ifdef HAVE_BKTR
1272                                         __dump_backtrace(&lt->backtrace[lt->reentrancy-1], canlog);
1273 #endif
1274                                         ast_reentrancy_unlock(lt);
1275                                         reported_wait = wait_time;
1276                                 }
1277                                 usleep(200);
1278                         }
1279                 } while (res == EBUSY);
1280         }
1281 #else /* !DETECT_DEADLOCKS */
1282         res = pthread_rwlock_wrlock(&t->lock);
1283 #endif /* !DETECT_DEADLOCKS */
1284
1285         if (!res) {
1286                 ast_reentrancy_lock(lt);
1287                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
1288                         lt->file[lt->reentrancy] = filename;
1289                         lt->lineno[lt->reentrancy] = line;
1290                         lt->func[lt->reentrancy] = func;
1291                         lt->thread[lt->reentrancy] = pthread_self();
1292                         lt->reentrancy++;
1293                 } else {
1294                         __ast_mutex_logger("%s line %d (%s): write lock '%s' really deep reentrancy!\n",
1295                                         filename, line, func, name);
1296                 }
1297                 ast_reentrancy_unlock(lt);
1298                 if (t->tracking) {
1299                         ast_mark_lock_acquired(&t->lock);
1300                 }
1301         } else {
1302 #ifdef HAVE_BKTR
1303                 if (lt->reentrancy) {
1304                         ast_reentrancy_lock(lt);
1305                         bt = &lt->backtrace[lt->reentrancy-1];
1306                 } else {
1307                         bt = NULL;
1308                 }
1309                 if (t->tracking) {
1310                         ast_remove_lock_info(&t->lock, bt);
1311                 }
1312 #else
1313                 if (t->tracking) {
1314                         ast_remove_lock_info(&t->lock);
1315                 }
1316 #endif
1317                 __ast_mutex_logger("%s line %d (%s): Error obtaining write lock: %s\n",
1318                                 filename, line, func, strerror(res));
1319                 DO_THREAD_CRASH;
1320         }
1321         return res;
1322 }
1323
1324 static inline int _ast_rwlock_tryrdlock(ast_rwlock_t *t, const char *name,
1325         const char *filename, int line, const char *func)
1326 {
1327         int res;
1328         struct ast_lock_track *lt = &t->track;
1329         int canlog = strcmp(filename, "logger.c") & t->tracking;
1330 #ifdef HAVE_BKTR
1331         struct ast_bt *bt = NULL;
1332 #endif
1333
1334
1335 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1336         if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1337                  /* Don't warn abount uninitialized lock.
1338                   * Simple try to initialize it.
1339                   * May be not needed in linux system.
1340                   */
1341                 res = __ast_rwlock_init(t->tracking, filename, line, func, name, t);
1342                 if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1343                         __ast_mutex_logger("%s line %d (%s): Error: rwlock '%s' is uninitialized and unable to initialize.\n",
1344                                         filename, line, func, name);
1345                         return res;
1346                 }
1347         }
1348 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1349         
1350         if (t->tracking) {
1351 #ifdef HAVE_BKTR
1352                 ast_reentrancy_lock(lt);
1353                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
1354                 bt = &lt->backtrace[lt->reentrancy];
1355                 ast_reentrancy_unlock(lt);
1356                 ast_store_lock_info(AST_RDLOCK, filename, line, func, name, &t->lock, bt);
1357 #else
1358                 ast_store_lock_info(AST_RDLOCK, filename, line, func, name, &t->lock);
1359 #endif
1360         }
1361         
1362         if (!(res = pthread_rwlock_tryrdlock(&t->lock))) {
1363                 ast_reentrancy_lock(lt);
1364                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
1365                         lt->file[lt->reentrancy] = filename;
1366                         lt->lineno[lt->reentrancy] = line;
1367                         lt->func[lt->reentrancy] = func;
1368                         lt->thread[lt->reentrancy] = pthread_self();
1369                         lt->reentrancy++;
1370                 } else {
1371                         __ast_mutex_logger("%s line %d (%s): read lock '%s' really deep reentrancy!\n",
1372                                         filename, line, func, name);
1373                 }
1374                 ast_reentrancy_unlock(lt);
1375                 if (t->tracking) {
1376                         ast_mark_lock_acquired(&t->lock);
1377                 }
1378         } else if (t->tracking) {
1379                 ast_mark_lock_failed(&t->lock);
1380         }
1381         return res;
1382 }
1383
1384 static inline int _ast_rwlock_trywrlock(ast_rwlock_t *t, const char *name,
1385         const char *filename, int line, const char *func)
1386 {
1387         int res;
1388         struct ast_lock_track *lt= &t->track;
1389         int canlog = strcmp(filename, "logger.c") & t->tracking;
1390 #ifdef HAVE_BKTR
1391         struct ast_bt *bt = NULL;
1392 #endif
1393
1394
1395 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1396         if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1397                  /* Don't warn abount uninitialized lock.
1398                   * Simple try to initialize it.
1399                   * May be not needed in linux system.
1400                   */
1401                 res = __ast_rwlock_init(t->tracking, filename, line, func, name, t);
1402                 if ((t->lock) == ((pthread_rwlock_t) __AST_RWLOCK_INIT_VALUE)) {
1403                         __ast_mutex_logger("%s line %d (%s): Error: rwlock '%s' is uninitialized and unable to initialize.\n",
1404                                         filename, line, func, name);
1405                         return res;
1406                 }
1407         }
1408 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1409
1410         if (t->tracking) {
1411 #ifdef HAVE_BKTR
1412                 ast_reentrancy_lock(lt);
1413                 ast_bt_get_addresses(&lt->backtrace[lt->reentrancy]);
1414                 bt = &lt->backtrace[lt->reentrancy];
1415                 ast_reentrancy_unlock(lt);
1416                 ast_store_lock_info(AST_WRLOCK, filename, line, func, name, &t->lock, bt);
1417 #else
1418                 ast_store_lock_info(AST_WRLOCK, filename, line, func, name, &t->lock);
1419 #endif
1420         }
1421         
1422         if (!(res = pthread_rwlock_trywrlock(&t->lock))) {
1423                 ast_reentrancy_lock(lt);
1424                 if (lt->reentrancy < AST_MAX_REENTRANCY) {
1425                         lt->file[lt->reentrancy] = filename;
1426                         lt->lineno[lt->reentrancy] = line;
1427                         lt->func[lt->reentrancy] = func;
1428                         lt->thread[lt->reentrancy] = pthread_self();
1429                         lt->reentrancy++;
1430                 } else {
1431                         __ast_mutex_logger("%s line %d (%s): write lock '%s' really deep reentrancy!\n",
1432                                         filename, line, func, name);
1433                 }
1434                 ast_reentrancy_unlock(lt);
1435                 if (t->tracking) {
1436                         ast_mark_lock_acquired(&t->lock);
1437                 }
1438         } else if (t->tracking) {
1439                 ast_mark_lock_failed(&t->lock);
1440         }
1441         return res;
1442 }
1443
1444 #else /* !DEBUG_THREADS */
1445
1446 #define CHANNEL_DEADLOCK_AVOIDANCE(chan) \
1447         ast_channel_lock(chan); \
1448         usleep(1); \
1449         ast_channel_unlock(chan);
1450
1451 #define DEADLOCK_AVOIDANCE(lock) \
1452         ast_mutex_lock(lock); \
1453         usleep(1); \
1454         ast_mutex_unlock(lock);
1455
1456 #define DLA_UNLOCK(lock)        ast_mutex_unlock(lock)
1457
1458 #define DLA_LOCK(lock)  ast_mutex_lock(lock)
1459
1460 typedef pthread_mutex_t ast_mutex_t;
1461
1462 #define AST_MUTEX_INIT_VALUE                    ((ast_mutex_t) PTHREAD_MUTEX_INIT_VALUE)
1463 #define AST_MUTEX_INIT_VALUE_NOTRACKING         ((ast_mutex_t) PTHREAD_MUTEX_INIT_VALUE)
1464
1465 #define ast_mutex_init_notracking(m)            ast_mutex_init(m)
1466
1467 static inline int ast_mutex_init(ast_mutex_t *pmutex)
1468 {
1469         int res;
1470         pthread_mutexattr_t attr;
1471
1472         pthread_mutexattr_init(&attr);
1473         pthread_mutexattr_settype(&attr, AST_MUTEX_KIND);
1474
1475         res = pthread_mutex_init(pmutex, &attr);
1476         pthread_mutexattr_destroy(&attr);
1477         return res;
1478 }
1479
1480 #define ast_pthread_mutex_init(pmutex,a) pthread_mutex_init(pmutex,a)
1481
1482 static inline int ast_mutex_unlock(ast_mutex_t *pmutex)
1483 {
1484         return pthread_mutex_unlock(pmutex);
1485 }
1486
1487 static inline int ast_mutex_destroy(ast_mutex_t *pmutex)
1488 {
1489         return pthread_mutex_destroy(pmutex);
1490 }
1491
1492 static inline int ast_mutex_lock(ast_mutex_t *pmutex)
1493 {
1494         __MTX_PROF(pmutex);
1495 }
1496
1497 static inline int ast_mutex_trylock(ast_mutex_t *pmutex)
1498 {
1499         return pthread_mutex_trylock(pmutex);
1500 }
1501
1502 typedef pthread_cond_t ast_cond_t;
1503
1504 static inline int ast_cond_init(ast_cond_t *cond, pthread_condattr_t *cond_attr)
1505 {
1506         return pthread_cond_init(cond, cond_attr);
1507 }
1508
1509 static inline int ast_cond_signal(ast_cond_t *cond)
1510 {
1511         return pthread_cond_signal(cond);
1512 }
1513
1514 static inline int ast_cond_broadcast(ast_cond_t *cond)
1515 {
1516         return pthread_cond_broadcast(cond);
1517 }
1518
1519 static inline int ast_cond_destroy(ast_cond_t *cond)
1520 {
1521         return pthread_cond_destroy(cond);
1522 }
1523
1524 static inline int ast_cond_wait(ast_cond_t *cond, ast_mutex_t *t)
1525 {
1526         return pthread_cond_wait(cond, t);
1527 }
1528
1529 static inline int ast_cond_timedwait(ast_cond_t *cond, ast_mutex_t *t, const struct timespec *abstime)
1530 {
1531         return pthread_cond_timedwait(cond, t, abstime);
1532 }
1533
1534
1535 typedef pthread_rwlock_t ast_rwlock_t;
1536
1537 #ifdef HAVE_PTHREAD_RWLOCK_INITIALIZER
1538 #define AST_RWLOCK_INIT_VALUE PTHREAD_RWLOCK_INITIALIZER
1539 #else
1540 #define AST_RWLOCK_INIT_VALUE { 0 }
1541 #endif
1542
1543 #define ast_rwlock_init_notracking(a) ast_rwlock_init(a)
1544
1545 static inline int ast_rwlock_init(ast_rwlock_t *prwlock)
1546 {
1547         int res;
1548         pthread_rwlockattr_t attr;
1549
1550         pthread_rwlockattr_init(&attr);
1551
1552 #ifdef HAVE_PTHREAD_RWLOCK_PREFER_WRITER_NP
1553         pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NP);
1554 #endif
1555
1556         res = pthread_rwlock_init(prwlock, &attr);
1557         pthread_rwlockattr_destroy(&attr);
1558         return res;
1559 }
1560
1561 static inline int ast_rwlock_destroy(ast_rwlock_t *prwlock)
1562 {
1563         return pthread_rwlock_destroy(prwlock);
1564 }
1565
1566 static inline int ast_rwlock_unlock(ast_rwlock_t *prwlock)
1567 {
1568         return pthread_rwlock_unlock(prwlock);
1569 }
1570
1571 static inline int ast_rwlock_rdlock(ast_rwlock_t *prwlock)
1572 {
1573         return pthread_rwlock_rdlock(prwlock);
1574 }
1575
1576 static inline int ast_rwlock_tryrdlock(ast_rwlock_t *prwlock)
1577 {
1578         return pthread_rwlock_tryrdlock(prwlock);
1579 }
1580
1581 static inline int ast_rwlock_wrlock(ast_rwlock_t *prwlock)
1582 {
1583         return pthread_rwlock_wrlock(prwlock);
1584 }
1585
1586 static inline int ast_rwlock_trywrlock(ast_rwlock_t *prwlock)
1587 {
1588         return pthread_rwlock_trywrlock(prwlock);
1589 }
1590
1591 #endif /* !DEBUG_THREADS */
1592
1593 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
1594 /*
1595  * If AST_MUTEX_INIT_W_CONSTRUCTORS is defined, use file scope constructors
1596  * and destructors to create/destroy global mutexes.
1597  */
1598 #define __AST_MUTEX_DEFINE(scope, mutex, init_val, track)       \
1599         scope ast_mutex_t mutex = init_val;                     \
1600 static void  __attribute__ ((constructor)) init_##mutex(void)   \
1601 {                                                               \
1602         if (track)                                              \
1603                 ast_mutex_init(&mutex);                         \
1604         else                                                    \
1605                 ast_mutex_init_notracking(&mutex);              \
1606 }                                                               \
1607                                                                 \
1608 static void  __attribute__ ((destructor)) fini_##mutex(void)    \
1609 {                                                               \
1610         ast_mutex_destroy(&mutex);                              \
1611 }
1612 #else /* !AST_MUTEX_INIT_W_CONSTRUCTORS */
1613 /* By default, use static initialization of mutexes. */ 
1614 #define __AST_MUTEX_DEFINE(scope, mutex, init_val, track)       scope ast_mutex_t mutex = init_val
1615 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1616
1617 #ifndef __CYGWIN__      /* temporary disabled for cygwin */
1618 #define pthread_mutex_t         use_ast_mutex_t_instead_of_pthread_mutex_t
1619 #define pthread_cond_t          use_ast_cond_t_instead_of_pthread_cond_t
1620 #endif
1621 #define pthread_mutex_lock      use_ast_mutex_lock_instead_of_pthread_mutex_lock
1622 #define pthread_mutex_unlock    use_ast_mutex_unlock_instead_of_pthread_mutex_unlock
1623 #define pthread_mutex_trylock   use_ast_mutex_trylock_instead_of_pthread_mutex_trylock
1624 #define pthread_mutex_init      use_ast_mutex_init_instead_of_pthread_mutex_init
1625 #define pthread_mutex_destroy   use_ast_mutex_destroy_instead_of_pthread_mutex_destroy
1626 #define pthread_cond_init       use_ast_cond_init_instead_of_pthread_cond_init
1627 #define pthread_cond_destroy    use_ast_cond_destroy_instead_of_pthread_cond_destroy
1628 #define pthread_cond_signal     use_ast_cond_signal_instead_of_pthread_cond_signal
1629 #define pthread_cond_broadcast  use_ast_cond_broadcast_instead_of_pthread_cond_broadcast
1630 #define pthread_cond_wait       use_ast_cond_wait_instead_of_pthread_cond_wait
1631 #define pthread_cond_timedwait  use_ast_cond_timedwait_instead_of_pthread_cond_timedwait
1632
1633 #define AST_MUTEX_DEFINE_STATIC(mutex)                  __AST_MUTEX_DEFINE(static, mutex, AST_MUTEX_INIT_VALUE, 1)
1634 #define AST_MUTEX_DEFINE_STATIC_NOTRACKING(mutex)       __AST_MUTEX_DEFINE(static, mutex, AST_MUTEX_INIT_VALUE_NOTRACKING, 0)
1635
1636 #define AST_MUTEX_INITIALIZER __use_AST_MUTEX_DEFINE_STATIC_rather_than_AST_MUTEX_INITIALIZER__
1637
1638 #define gethostbyname __gethostbyname__is__not__reentrant__use__ast_gethostbyname__instead__
1639
1640 #ifndef __linux__
1641 #define pthread_create __use_ast_pthread_create_instead__
1642 #endif
1643
1644 /* Statically declared read/write locks */
1645
1646 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1647 #define __AST_RWLOCK_DEFINE(scope, rwlock, init_val, track) \
1648         scope ast_rwlock_t rwlock = init_val; \
1649 static void  __attribute__ ((constructor)) init_##rwlock(void) \
1650 { \
1651         if (track) \
1652                 ast_rwlock_init(&rwlock); \
1653         else \
1654                 ast_rwlock_init_notracking(&rwlock); \
1655 } \
1656 static void  __attribute__ ((destructor)) fini_##rwlock(void) \
1657 { \
1658         ast_rwlock_destroy(&rwlock); \
1659 }
1660 #else
1661 #define __AST_RWLOCK_DEFINE(scope, rwlock, init_val, track) \
1662         scope ast_rwlock_t rwlock = init_val
1663 #endif
1664
1665 #define AST_RWLOCK_DEFINE_STATIC(rwlock) __AST_RWLOCK_DEFINE(static, rwlock, AST_RWLOCK_INIT_VALUE, 1)
1666 #define AST_RWLOCK_DEFINE_STATIC_NOTRACKING(rwlock) __AST_RWLOCK_DEFINE(static, rwlock, AST_RWLOCK_INIT_VALUE_NOTRACKING, 0)
1667
1668 /*
1669  * Support for atomic instructions.
1670  * For platforms that have it, use the native cpu instruction to
1671  * implement them. For other platforms, resort to a 'slow' version
1672  * (defined in utils.c) that protects the atomic instruction with
1673  * a single lock.
1674  * The slow versions is always available, for testing purposes,
1675  * as ast_atomic_fetchadd_int_slow()
1676  */
1677
1678 int ast_atomic_fetchadd_int_slow(volatile int *p, int v);
1679
1680 #include "asterisk/inline_api.h"
1681
1682 #if defined(HAVE_OSX_ATOMICS)
1683 #include "libkern/OSAtomic.h"
1684 #endif
1685
1686 /*! \brief Atomically add v to *p and return * the previous value of *p.
1687  * This can be used to handle reference counts, and the return value
1688  * can be used to generate unique identifiers.
1689  */
1690
1691 #if defined(HAVE_GCC_ATOMICS)
1692 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1693 {
1694         return __sync_fetch_and_add(p, v);
1695 })
1696 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 4)
1697 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1698 {
1699         return OSAtomicAdd32(v, (int32_t *) p) - v;
1700 })
1701 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 8)
1702 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1703 {
1704         return OSAtomicAdd64(v, (int64_t *) p) - v;
1705 #elif defined (__i386__) || defined(__x86_64__)
1706 #ifdef sun
1707 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1708 {
1709         __asm __volatile (
1710         "       lock;  xaddl   %0, %1 ;        "
1711         : "+r" (v),                     /* 0 (result) */   
1712           "=m" (*p)                     /* 1 */
1713         : "m" (*p));                    /* 2 */
1714         return (v);
1715 })
1716 #else /* ifndef sun */
1717 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1718 {
1719         __asm __volatile (
1720         "       lock   xaddl   %0, %1 ;        "
1721         : "+r" (v),                     /* 0 (result) */   
1722           "=m" (*p)                     /* 1 */
1723         : "m" (*p));                    /* 2 */
1724         return (v);
1725 })
1726 #endif
1727 #else   /* low performance version in utils.c */
1728 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1729 {
1730         return ast_atomic_fetchadd_int_slow(p, v);
1731 })
1732 #endif
1733
1734 /*! \brief decrement *p by 1 and return true if the variable has reached 0.
1735  * Useful e.g. to check if a refcount has reached 0.
1736  */
1737 #if defined(HAVE_GCC_ATOMICS)
1738 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1739 {
1740         return __sync_sub_and_fetch(p, 1) == 0;
1741 })
1742 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 4)
1743 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1744 {
1745         return OSAtomicAdd32( -1, (int32_t *) p) == 0;
1746 })
1747 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 8)
1748 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1749 {
1750         return OSAtomicAdd64( -1, (int64_t *) p) == 0;
1751 #else
1752 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1753 {
1754         int a = ast_atomic_fetchadd_int(p, -1);
1755         return a == 1; /* true if the value is 0 now (so it was 1 previously) */
1756 })
1757 #endif
1758
1759 #ifndef DEBUG_CHANNEL_LOCKS
1760 /*! \brief Lock a channel. If DEBUG_CHANNEL_LOCKS is defined 
1761         in the Makefile, print relevant output for debugging */
1762 #define ast_channel_lock(x)             ast_mutex_lock(&x->lock_dont_use)
1763 /*! \brief Unlock a channel. If DEBUG_CHANNEL_LOCKS is defined 
1764         in the Makefile, print relevant output for debugging */
1765 #define ast_channel_unlock(x)           ast_mutex_unlock(&x->lock_dont_use)
1766 /*! \brief Try locking a channel. If DEBUG_CHANNEL_LOCKS is defined 
1767         in the Makefile, print relevant output for debugging */
1768 #define ast_channel_trylock(x)          ast_mutex_trylock(&x->lock_dont_use)
1769 #else
1770
1771 #define ast_channel_lock(a) __ast_channel_lock(a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1772 /*! \brief Lock AST channel (and print debugging output)
1773 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
1774 int __ast_channel_lock(struct ast_channel *chan, const char *file, int lineno, const char *func);
1775
1776 #define ast_channel_unlock(a) __ast_channel_unlock(a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1777 /*! \brief Unlock AST channel (and print debugging output)
1778 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
1779 */
1780 int __ast_channel_unlock(struct ast_channel *chan, const char *file, int lineno, const char *func);
1781
1782 #define ast_channel_trylock(a) __ast_channel_trylock(a, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1783 /*! \brief Lock AST channel (and print debugging output)
1784 \note   You need to enable DEBUG_CHANNEL_LOCKS for this function */
1785 int __ast_channel_trylock(struct ast_channel *chan, const char *file, int lineno, const char *func);
1786 #endif
1787
1788 #endif /* _ASTERISK_LOCK_H */