This is basically a complete rollback of r155401, as it was determined that
[asterisk/asterisk.git] / main / astobj2.c
1 /*
2  * astobj2 - replacement containers for asterisk data structures.
3  *
4  * Copyright (C) 2006 Marta Carbone, Luigi Rizzo - Univ. di Pisa, Italy
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*
18  * Function implementing astobj2 objects.
19  */
20 #include "asterisk.h"
21
22 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
23
24 #include "asterisk/_private.h"
25 #include "asterisk/astobj2.h"
26 #include "asterisk/utils.h"
27 #include "asterisk/cli.h"
28 #define REF_FILE "/tmp/refs"
29
30 /*!
31  * astobj2 objects are always preceded by this data structure,
32  * which contains a lock, a reference counter,
33  * the flags and a pointer to a destructor.
34  * The refcount is used to decide when it is time to
35  * invoke the destructor.
36  * The magic number is used for consistency check.
37  * XXX the lock is not always needed, and its initialization may be
38  * expensive. Consider making it external.
39  */
40 struct __priv_data {
41         ast_mutex_t lock;
42         int ref_counter;
43         ao2_destructor_fn destructor_fn;
44         /*! for stats */
45         size_t data_size;
46         /*! magic number.  This is used to verify that a pointer passed in is a
47          *  valid astobj2 */
48         uint32_t magic;
49 };
50
51 #define AO2_MAGIC       0xa570b123
52
53 /*!
54  * What an astobj2 object looks like: fixed-size private data
55  * followed by variable-size user data.
56  */
57 struct astobj2 {
58         struct __priv_data priv_data;
59         void *user_data[0];
60 };
61
62 #ifdef AST_DEVMODE
63 #define AO2_DEBUG 1
64 #endif
65
66 #ifdef AO2_DEBUG
67 struct ao2_stats {
68         volatile int total_objects;
69         volatile int total_mem;
70         volatile int total_containers;
71         volatile int total_refs;
72         volatile int total_locked;
73 };
74
75 static struct ao2_stats ao2;
76 #endif
77
78 #ifndef HAVE_BKTR       /* backtrace support */
79 void ao2_bt(void) {}
80 #else
81 #include <execinfo.h>    /* for backtrace */
82
83 void ao2_bt(void)
84 {
85         int c, i;
86 #define N1      20
87         void *addresses[N1];
88         char **strings;
89
90         c = backtrace(addresses, N1);
91         strings = backtrace_symbols(addresses,c);
92         ast_verbose("backtrace returned: %d\n", c);
93         for(i = 0; i < c; i++) {
94                 ast_verbose("%d: %p %s\n", i, addresses[i], strings[i]);
95         }
96         free(strings);
97 }
98 #endif
99
100 /*!
101  * \brief convert from a pointer _p to a user-defined object
102  *
103  * \return the pointer to the astobj2 structure
104  */
105 static inline struct astobj2 *INTERNAL_OBJ(void *user_data)
106 {
107         struct astobj2 *p;
108
109         if (!user_data) {
110                 ast_log(LOG_ERROR, "user_data is NULL\n");
111                 return NULL;
112         }
113
114         p = (struct astobj2 *) ((char *) user_data - sizeof(*p));
115         if (AO2_MAGIC != (p->priv_data.magic) ) {
116                 ast_log(LOG_ERROR, "bad magic number 0x%x for %p\n", p->priv_data.magic, p);
117                 p = NULL;
118         }
119
120         return p;
121 }
122
123 enum ao2_callback_type {
124         DEFAULT,
125         WITH_DATA,
126 };
127
128 /*!
129  * \brief convert from a pointer _p to an astobj2 object
130  *
131  * \return the pointer to the user-defined portion.
132  */
133 #define EXTERNAL_OBJ(_p)        ((_p) == NULL ? NULL : (_p)->user_data)
134
135 /* the underlying functions common to debug and non-debug versions */
136
137 static int __ao2_ref(void *user_data, const int delta);
138 static void *__ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn);
139 static struct ao2_container *__ao2_container_alloc(struct ao2_container *c, const uint n_buckets, ao2_hash_fn *hash_fn,
140                                                                                         ao2_callback_fn *cmp_fn);
141 static struct bucket_list *__ao2_link(struct ao2_container *c, void *user_data);
142 static void *__ao2_callback(struct ao2_container *c,
143         const enum search_flags flags, void *cb_fn, void *arg, void *data, enum ao2_callback_type type,
144                                          char *tag, char *file, int line, const char *funcname);
145 static void * __ao2_iterator_next(struct ao2_iterator *a, struct bucket_list **q);
146
147 #ifndef DEBUG_THREADS
148 int ao2_lock(void *user_data)
149 #else
150 int _ao2_lock(void *user_data, const char *file, const char *func, int line, const char *var)
151 #endif
152 {
153         struct astobj2 *p = INTERNAL_OBJ(user_data);
154
155         if (p == NULL)
156                 return -1;
157
158 #ifdef AO2_DEBUG
159         ast_atomic_fetchadd_int(&ao2.total_locked, 1);
160 #endif
161
162 #ifndef DEBUG_THREADS
163         return ast_mutex_lock(&p->priv_data.lock);
164 #else
165         return __ast_pthread_mutex_lock(file, line, func, var, &p->priv_data.lock);
166 #endif
167 }
168
169 #ifndef DEBUG_THREADS
170 int ao2_unlock(void *user_data)
171 #else
172 int _ao2_unlock(void *user_data, const char *file, const char *func, int line, const char *var)
173 #endif
174 {
175         struct astobj2 *p = INTERNAL_OBJ(user_data);
176
177         if (p == NULL)
178                 return -1;
179
180 #ifdef AO2_DEBUG
181         ast_atomic_fetchadd_int(&ao2.total_locked, -1);
182 #endif
183
184 #ifndef DEBUG_THREADS
185         return ast_mutex_unlock(&p->priv_data.lock);
186 #else
187         return __ast_pthread_mutex_unlock(file, line, func, var, &p->priv_data.lock);
188 #endif
189 }
190
191 int ao2_trylock(void *user_data)
192 {
193         struct astobj2 *p = INTERNAL_OBJ(user_data);
194         int ret;
195         
196         if (p == NULL)
197                 return -1;
198         ret =  ast_mutex_trylock(&p->priv_data.lock);
199 #ifdef AO2_DEBUG
200         if (!ret)
201                 ast_atomic_fetchadd_int(&ao2.total_locked, 1);
202 #endif
203         return ret;
204 }
205
206 void *ao2_object_get_lockaddr(void *obj)
207 {
208         struct astobj2 *p = INTERNAL_OBJ(obj);
209         
210         if (p == NULL)
211                 return NULL;
212
213         return &p->priv_data.lock;
214 }
215
216 /*
217  * The argument is a pointer to the user portion.
218  */
219
220
221 int _ao2_ref_debug(void *user_data, const int delta, char *tag, char *file, int line, const char *funcname)
222 {
223         struct astobj2 *obj = INTERNAL_OBJ(user_data);
224         
225         if (obj == NULL)
226                 return -1;
227
228         if (delta != 0) {
229                 FILE *refo = fopen(REF_FILE,"a");
230                 fprintf(refo, "%p %s%d   %s:%d:%s (%s) [@%d]\n", user_data, (delta<0? "":"+"), delta, file, line, funcname, tag, obj->priv_data.ref_counter);
231                 fclose(refo);
232         }
233         if (obj->priv_data.ref_counter + delta == 0 && obj->priv_data.destructor_fn != NULL) { /* this isn't protected with lock; just for o/p */
234                         FILE *refo = fopen(REF_FILE,"a");        
235                         fprintf(refo, "%p **call destructor** %s:%d:%s (%s)\n", user_data, file, line, funcname, tag);   
236                         fclose(refo);
237         }
238         return __ao2_ref(user_data, delta);
239 }
240
241 int _ao2_ref(void *user_data, const int delta)
242 {
243         struct astobj2 *obj = INTERNAL_OBJ(user_data);
244
245         if (obj == NULL)
246                 return -1;
247
248         return __ao2_ref(user_data, delta);
249 }
250
251 static int __ao2_ref(void *user_data, const int delta)
252 {
253         struct astobj2 *obj = INTERNAL_OBJ(user_data);
254         int current_value;
255         int ret;
256
257         /* if delta is 0, just return the refcount */
258         if (delta == 0)
259                 return (obj->priv_data.ref_counter);
260
261         /* we modify with an atomic operation the reference counter */
262         ret = ast_atomic_fetchadd_int(&obj->priv_data.ref_counter, delta);
263         current_value = ret + delta;
264
265 #ifdef AO2_DEBUG        
266         ast_atomic_fetchadd_int(&ao2.total_refs, delta);
267 #endif
268
269         /* this case must never happen */
270         if (current_value < 0)
271                 ast_log(LOG_ERROR, "refcount %d on object %p\n", current_value, user_data);
272
273         if (current_value <= 0) { /* last reference, destroy the object */
274                 if (obj->priv_data.destructor_fn != NULL) {
275                         obj->priv_data.destructor_fn(user_data);
276                 }
277
278                 ast_mutex_destroy(&obj->priv_data.lock);
279 #ifdef AO2_DEBUG
280                 ast_atomic_fetchadd_int(&ao2.total_mem, - obj->priv_data.data_size);
281                 ast_atomic_fetchadd_int(&ao2.total_objects, -1);
282 #endif
283                 /* for safety, zero-out the astobj2 header and also the
284                  * first word of the user-data, which we make sure is always
285                  * allocated. */
286                 memset(obj, '\0', sizeof(struct astobj2 *) + sizeof(void *) );
287                 free(obj);
288         }
289
290         return ret;
291 }
292
293 /*
294  * We always alloc at least the size of a void *,
295  * for debugging purposes.
296  */
297 static void *__ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn)
298 {
299         /* allocation */
300         struct astobj2 *obj;
301
302         if (data_size < sizeof(void *))
303                 data_size = sizeof(void *);
304
305         obj = ast_calloc(1, sizeof(*obj) + data_size);
306
307         if (obj == NULL)
308                 return NULL;
309
310         ast_mutex_init(&obj->priv_data.lock);
311         obj->priv_data.magic = AO2_MAGIC;
312         obj->priv_data.data_size = data_size;
313         obj->priv_data.ref_counter = 1;
314         obj->priv_data.destructor_fn = destructor_fn;   /* can be NULL */
315
316 #ifdef AO2_DEBUG
317         ast_atomic_fetchadd_int(&ao2.total_objects, 1);
318         ast_atomic_fetchadd_int(&ao2.total_mem, data_size);
319         ast_atomic_fetchadd_int(&ao2.total_refs, 1);
320 #endif
321
322         /* return a pointer to the user data */
323         return EXTERNAL_OBJ(obj);
324 }
325
326 void *_ao2_alloc_debug(size_t data_size, ao2_destructor_fn destructor_fn, char *tag, char *file, int line, const char *funcname)
327 {
328         /* allocation */
329         void *obj;
330         FILE *refo = fopen(REF_FILE,"a");
331
332         obj = __ao2_alloc(data_size, destructor_fn);
333
334         if (obj == NULL)
335                 return NULL;
336         
337         if (refo) {
338                 fprintf(refo, "%p =1   %s:%d:%s (%s)\n", obj, file, line, funcname, tag);
339                 fclose(refo);
340         }
341
342         /* return a pointer to the user data */
343         return obj;
344 }
345
346 void *_ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn)
347 {
348         return __ao2_alloc(data_size, destructor_fn);
349 }
350
351
352 /* internal callback to destroy a container. */
353 static void container_destruct(void *c);
354
355 /* internal callback to destroy a container. */
356 static void container_destruct_debug(void *c);
357
358 /* each bucket in the container is a tailq. */
359 AST_LIST_HEAD_NOLOCK(bucket, bucket_list);
360
361 /*!
362  * A container; stores the hash and callback functions, information on
363  * the size, the hash bucket heads, and a version number, starting at 0
364  * (for a newly created, empty container)
365  * and incremented every time an object is inserted or deleted.
366  * The assumption is that an object is never moved in a container,
367  * but removed and readded with the new number.
368  * The version number is especially useful when implementing iterators.
369  * In fact, we can associate a unique, monotonically increasing number to
370  * each object, which means that, within an iterator, we can store the
371  * version number of the current object, and easily look for the next one,
372  * which is the next one in the list with a higher number.
373  * Since all objects have a version >0, we can use 0 as a marker for
374  * 'we need the first object in the bucket'.
375  *
376  * \todo Linking and unlink objects is typically expensive, as it
377  * involves a malloc() of a small object which is very inefficient.
378  * To optimize this, we allocate larger arrays of bucket_list's
379  * when we run out of them, and then manage our own freelist.
380  * This will be more efficient as we can do the freelist management while
381  * we hold the lock (that we need anyways).
382  */
383 struct ao2_container {
384         ao2_hash_fn *hash_fn;
385         ao2_callback_fn *cmp_fn;
386         int n_buckets;
387         /*! Number of elements in the container */
388         int elements;
389         /*! described above */
390         int version;
391         /*! variable size */
392         struct bucket buckets[0];
393 };
394  
395 /*!
396  * \brief always zero hash function
397  *
398  * it is convenient to have a hash function that always returns 0.
399  * This is basically used when we want to have a container that is
400  * a simple linked list.
401  *
402  * \returns 0
403  */
404 static int hash_zero(const void *user_obj, const int flags)
405 {
406         return 0;
407 }
408
409 /*
410  * A container is just an object, after all!
411  */
412 static struct ao2_container *__ao2_container_alloc(struct ao2_container *c, const uint n_buckets, ao2_hash_fn *hash_fn,
413                                                                                         ao2_callback_fn *cmp_fn)
414 {
415         /* XXX maybe consistency check on arguments ? */
416         /* compute the container size */
417
418         if (!c)
419                 return NULL;
420         
421         c->version = 1; /* 0 is a reserved value here */
422         c->n_buckets = n_buckets;
423         c->hash_fn = hash_fn ? hash_fn : hash_zero;
424         c->cmp_fn = cmp_fn;
425
426 #ifdef AO2_DEBUG
427         ast_atomic_fetchadd_int(&ao2.total_containers, 1);
428 #endif
429
430         return c;
431 }
432
433 struct ao2_container *_ao2_container_alloc_debug(const uint n_buckets, ao2_hash_fn *hash_fn,
434                 ao2_callback_fn *cmp_fn, char *tag, char *file, int line, const char *funcname)
435 {
436         /* XXX maybe consistency check on arguments ? */
437         /* compute the container size */
438         size_t container_size = sizeof(struct ao2_container) + n_buckets * sizeof(struct bucket);
439         struct ao2_container *c = _ao2_alloc_debug(container_size, container_destruct_debug, tag, file, line, funcname);
440
441         return __ao2_container_alloc(c, n_buckets, hash_fn, cmp_fn);
442 }
443
444 struct ao2_container *
445 _ao2_container_alloc(const uint n_buckets, ao2_hash_fn *hash_fn,
446                 ao2_callback_fn *cmp_fn)
447 {
448         /* XXX maybe consistency check on arguments ? */
449         /* compute the container size */
450
451         size_t container_size = sizeof(struct ao2_container) + n_buckets * sizeof(struct bucket);
452         struct ao2_container *c = _ao2_alloc(container_size, container_destruct);
453
454         return __ao2_container_alloc(c, n_buckets, hash_fn, cmp_fn);
455 }
456
457 /*!
458  * return the number of elements in the container
459  */
460 int ao2_container_count(struct ao2_container *c)
461 {
462         return c->elements;
463 }
464
465 /*!
466  * A structure to create a linked list of entries,
467  * used within a bucket.
468  * XXX \todo this should be private to the container code
469  */
470 struct bucket_list {
471         AST_LIST_ENTRY(bucket_list) entry;
472         int version;
473         struct astobj2 *astobj;         /* pointer to internal data */
474 }; 
475
476 /*
477  * link an object to a container
478  */
479
480 static struct bucket_list *__ao2_link(struct ao2_container *c, void *user_data)
481 {
482         int i;
483         /* create a new list entry */
484         struct bucket_list *p;
485         struct astobj2 *obj = INTERNAL_OBJ(user_data);
486         
487         if (!obj)
488                 return NULL;
489
490         if (INTERNAL_OBJ(c) == NULL)
491                 return NULL;
492
493         p = ast_calloc(1, sizeof(*p));
494         if (!p)
495                 return NULL;
496
497         i = c->hash_fn(user_data, OBJ_POINTER);
498
499         ao2_lock(c);
500         i %= c->n_buckets;
501         p->astobj = obj;
502         p->version = ast_atomic_fetchadd_int(&c->version, 1);
503         AST_LIST_INSERT_TAIL(&c->buckets[i], p, entry);
504         ast_atomic_fetchadd_int(&c->elements, 1);
505
506         /* the last two operations (ao2_ref, ao2_unlock) must be done by the calling func */
507         return p;
508 }
509
510 void *_ao2_link_debug(struct ao2_container *c, void *user_data, char *tag, char *file, int line, const char *funcname)
511 {
512         struct bucket_list *p = __ao2_link(c, user_data);
513         
514         if (p) {
515                 _ao2_ref_debug(user_data, +1, tag, file, line, funcname);
516                 ao2_unlock(c);
517         }
518         return p;
519 }
520
521 void *_ao2_link(struct ao2_container *c, void *user_data)
522 {
523         struct bucket_list *p = __ao2_link(c, user_data);
524         
525         if (p) {
526                 _ao2_ref(user_data, +1);
527                 ao2_unlock(c);
528         }
529         return p;
530 }
531
532 /*!
533  * \brief another convenience function is a callback that matches on address
534  */
535 int ao2_match_by_addr(void *user_data, void *arg, int flags)
536 {
537         return (user_data == arg) ? (CMP_MATCH | CMP_STOP) : 0;
538 }
539
540 /*
541  * Unlink an object from the container
542  * and destroy the associated * ao2_bucket_list structure.
543  */
544 void *_ao2_unlink_debug(struct ao2_container *c, void *user_data, char *tag,
545                                            char *file, int line, const char *funcname)
546 {
547         if (INTERNAL_OBJ(user_data) == NULL)    /* safety check on the argument */
548                 return NULL;
549
550         _ao2_callback_debug(c, OBJ_UNLINK | OBJ_POINTER | OBJ_NODATA, ao2_match_by_addr, user_data, tag, file, line, funcname);
551
552         return NULL;
553 }
554
555 void *_ao2_unlink(struct ao2_container *c, void *user_data)
556 {
557         if (INTERNAL_OBJ(user_data) == NULL)    /* safety check on the argument */
558                 return NULL;
559
560         _ao2_callback(c, OBJ_UNLINK | OBJ_POINTER | OBJ_NODATA, ao2_match_by_addr, user_data);
561
562         return NULL;
563 }
564
565 /*! 
566  * \brief special callback that matches all 
567  */ 
568 static int cb_true(void *user_data, void *arg, int flags)
569 {
570         ast_log(LOG_ERROR, "Using default callback (cb_true).  If you see this, something is strange!\n");
571         return CMP_MATCH;
572 }
573
574 /*!
575  * \brief similar to cb_true, but is an ao2_callback_data_fn instead
576  */
577 static int cb_true_data(void *user_data, void *arg, void *data, int flags)
578 {
579         ast_log(LOG_ERROR, "Using default callback (cb_true_data).  If you see this, something is strange!\n");
580         return CMP_MATCH;
581 }
582
583 /*!
584  * Browse the container using different stategies accoding the flags.
585  * \return Is a pointer to an object or to a list of object if OBJ_MULTIPLE is 
586  * specified.
587  * Luckily, for debug purposes, the added args (tag, file, line, funcname)
588  * aren't an excessive load to the system, as the callback should not be
589  * called as often as, say, the ao2_ref func is called.
590  */
591 static void *__ao2_callback(struct ao2_container *c,
592         const enum search_flags flags, void *cb_fn, void *arg, void *data, enum ao2_callback_type type,
593         char *tag, char *file, int line, const char *funcname)
594 {
595         int i, last;    /* search boundaries */
596         void *ret = NULL;
597         ao2_callback_fn *cb_default = NULL;
598         ao2_callback_data_fn *cb_withdata = NULL;
599
600         if (INTERNAL_OBJ(c) == NULL)    /* safety check on the argument */
601                 return NULL;
602
603         if ((flags & (OBJ_MULTIPLE | OBJ_NODATA)) == OBJ_MULTIPLE) {
604                 ast_log(LOG_WARNING, "multiple data return not implemented yet (flags %x)\n", flags);
605                 return NULL;
606         }
607
608         /* override the match function if necessary */
609         if (cb_fn == NULL) { /* if NULL, match everything */
610                 if (type == WITH_DATA) {
611                         cb_withdata = cb_true_data;
612                 } else {
613                         cb_default = cb_true;
614                 }
615         } else {
616                 /* We do this here to avoid the per object casting penalty (even though
617                    that is probably optimized away anyway. */
618                 if (type == WITH_DATA) {
619                         cb_withdata = cb_fn;
620                 } else {
621                         cb_default = cb_fn;
622                 }
623         }
624
625         /*
626          * XXX this can be optimized.
627          * If we have a hash function and lookup by pointer,
628          * run the hash function. Otherwise, scan the whole container
629          * (this only for the time being. We need to optimize this.)
630          */
631         if ((flags & OBJ_POINTER))      /* we know hash can handle this case */
632                 i = c->hash_fn(arg, flags & OBJ_POINTER) % c->n_buckets;
633         else                    /* don't know, let's scan all buckets */
634                 i = -1;         /* XXX this must be fixed later. */
635
636         /* determine the search boundaries: i..last-1 */
637         if (i < 0) {
638                 i = 0;
639                 last = c->n_buckets;
640         } else {
641                 last = i + 1;
642         }
643
644         ao2_lock(c);    /* avoid modifications to the content */
645
646         for (; i < last ; i++) {
647                 /* scan the list with prev-cur pointers */
648                 struct bucket_list *cur;
649
650                 AST_LIST_TRAVERSE_SAFE_BEGIN(&c->buckets[i], cur, entry) {
651                         int match = (CMP_MATCH | CMP_STOP);
652
653                         if (type == WITH_DATA) {
654                                 match &= cb_withdata(EXTERNAL_OBJ(cur->astobj), arg, data, flags);
655                         } else {
656                                 match &= cb_default(EXTERNAL_OBJ(cur->astobj), arg, flags);
657                         }
658
659                         /* we found the object, performing operations according flags */
660                         if (match == 0) {       /* no match, no stop, continue */
661                                 continue;
662                         } else if (match == CMP_STOP) { /* no match but stop, we are done */
663                                 i = last;
664                                 break;
665                         }
666                         /* we have a match (CMP_MATCH) here */
667                         if (!(flags & OBJ_NODATA)) {    /* if must return the object, record the value */
668                                 /* it is important to handle this case before the unlink */
669                                 ret = EXTERNAL_OBJ(cur->astobj);
670                                 if (tag)
671                                         _ao2_ref_debug(ret, 1, tag, file, line, funcname);
672                                 else
673                                         _ao2_ref(ret, 1);
674                         }
675
676                         if (flags & OBJ_UNLINK) {       /* must unlink */
677                                 struct bucket_list *x = cur;
678
679                                 /* we are going to modify the container, so update version */
680                                 ast_atomic_fetchadd_int(&c->version, 1);
681                                 AST_LIST_REMOVE_CURRENT(entry);
682                                 /* update number of elements and version */
683                                 ast_atomic_fetchadd_int(&c->elements, -1);
684                                 if (tag)
685                                         _ao2_ref_debug(EXTERNAL_OBJ(x->astobj), -1, tag, file, line, funcname);
686                                 else
687                                         _ao2_ref(EXTERNAL_OBJ(x->astobj), -1);
688                                 free(x);        /* free the link record */
689                         }
690
691                         if ((match & CMP_STOP) || (flags & OBJ_MULTIPLE) == 0) {
692                                 /* We found the only match we need */
693                                 i = last;       /* force exit from outer loop */
694                                 break;
695                         }
696                         if (!(flags & OBJ_NODATA)) {
697 #if 0   /* XXX to be completed */
698                                 /*
699                                  * This is the multiple-return case. We need to link
700                                  * the object in a list. The refcount is already increased.
701                                  */
702 #endif
703                         }
704                 }
705                 AST_LIST_TRAVERSE_SAFE_END;
706         }
707         ao2_unlock(c);
708         return ret;
709 }
710
711 void *_ao2_callback_debug(struct ao2_container *c,
712                                                  const enum search_flags flags,
713                                                  ao2_callback_fn *cb_fn, void *arg,
714                                                  char *tag, char *file, int line, const char *funcname)
715 {
716         return __ao2_callback(c,flags, cb_fn, arg, NULL, DEFAULT, tag, file, line, funcname);
717 }
718
719 void *_ao2_callback(struct ao2_container *c, const enum search_flags flags,
720                     ao2_callback_fn *cb_fn, void *arg)
721 {
722         return __ao2_callback(c,flags, cb_fn, arg, NULL, DEFAULT, NULL, NULL, 0, NULL);
723 }
724
725 void *_ao2_callback_data_debug(struct ao2_container *c,
726                                                  const enum search_flags flags,
727                                                  ao2_callback_data_fn *cb_fn, void *arg, void *data,
728                                                  char *tag, char *file, int line, const char *funcname)
729 {
730         return __ao2_callback(c, flags, cb_fn, arg, data, WITH_DATA, tag, file, line, funcname);
731 }
732
733 void *_ao2_callback_data(struct ao2_container *c, const enum search_flags flags,
734                                         ao2_callback_data_fn *cb_fn, void *arg, void *data)
735 {
736         return __ao2_callback(c, flags, cb_fn, arg, data, WITH_DATA, NULL, NULL, 0, NULL);
737 }
738
739 /*!
740  * the find function just invokes the default callback with some reasonable flags.
741  */
742 void *_ao2_find_debug(struct ao2_container *c, void *arg, enum search_flags flags, char *tag, char *file, int line, const char *funcname)
743 {
744         return _ao2_callback_debug(c, flags, c->cmp_fn, arg, tag, file, line, funcname);
745 }
746
747 void *_ao2_find(struct ao2_container *c, void *arg, enum search_flags flags)
748 {
749         return _ao2_callback(c, flags, c->cmp_fn, arg);
750 }
751
752 /*!
753  * initialize an iterator so we start from the first object
754  */
755 struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags)
756 {
757         struct ao2_iterator a = {
758                 .c = c,
759                 .flags = flags
760         };
761         
762         return a;
763 }
764
765 /*
766  * move to the next element in the container.
767  */
768 static void * __ao2_iterator_next(struct ao2_iterator *a, struct bucket_list **q)
769 {
770         int lim;
771         struct bucket_list *p = NULL;
772         void *ret = NULL;
773
774         *q = NULL;
775         
776         if (INTERNAL_OBJ(a->c) == NULL)
777                 return NULL;
778
779         if (!(a->flags & F_AO2I_DONTLOCK))
780                 ao2_lock(a->c);
781
782         /* optimization. If the container is unchanged and
783          * we have a pointer, try follow it
784          */
785         if (a->c->version == a->c_version && (p = a->obj) ) {
786                 if ( (p = AST_LIST_NEXT(p, entry)) )
787                         goto found;
788                 /* nope, start from the next bucket */
789                 a->bucket++;
790                 a->version = 0;
791                 a->obj = NULL;
792         }
793
794         lim = a->c->n_buckets;
795
796         /* Browse the buckets array, moving to the next
797          * buckets if we don't find the entry in the current one.
798          * Stop when we find an element with version number greater
799          * than the current one (we reset the version to 0 when we
800          * switch buckets).
801          */
802         for (; a->bucket < lim; a->bucket++, a->version = 0) {
803                 /* scan the current bucket */
804                 AST_LIST_TRAVERSE(&a->c->buckets[a->bucket], p, entry) {
805                         if (p->version > a->version)
806                                 goto found;
807                 }
808         }
809
810 found:
811         if (p) {
812                 a->version = p->version;
813                 a->obj = p;
814                 a->c_version = a->c->version;
815                 ret = EXTERNAL_OBJ(p->astobj);
816                 /* inc refcount of returned object */
817                 *q = p;
818         }
819
820         return ret;
821 }
822
823 void * _ao2_iterator_next_debug(struct ao2_iterator *a, char *tag, char *file, int line, const char *funcname)
824 {
825         struct bucket_list *p;
826         void *ret = NULL;
827
828         ret = __ao2_iterator_next(a, &p);
829         
830         if (p) {
831                 /* inc refcount of returned object */
832                 _ao2_ref_debug(ret, 1, tag, file, line, funcname);
833         }
834
835         if (!(a->flags & F_AO2I_DONTLOCK))
836                 ao2_unlock(a->c);
837
838         return ret;
839 }
840
841 void * _ao2_iterator_next(struct ao2_iterator *a)
842 {
843         struct bucket_list *p = NULL;
844         void *ret = NULL;
845
846         ret = __ao2_iterator_next(a, &p);
847         
848         if (p) {
849                 /* inc refcount of returned object */
850                 _ao2_ref(ret, 1);
851         }
852
853         if (!(a->flags & F_AO2I_DONTLOCK))
854                 ao2_unlock(a->c);
855
856         return ret;
857 }
858
859 /* callback for destroying container.
860  * we can make it simple as we know what it does
861  */
862 static int cd_cb(void *obj, void *arg, int flag)
863 {
864         _ao2_ref(obj, -1);
865         return 0;
866 }
867         
868 static int cd_cb_debug(void *obj, void *arg, int flag)
869 {
870         _ao2_ref_debug(obj, -1, "deref object via container destroy",  __FILE__, __LINE__, __PRETTY_FUNCTION__);
871         return 0;
872 }
873         
874 static void container_destruct(void *_c)
875 {
876         struct ao2_container *c = _c;
877         int i;
878
879         _ao2_callback(c, OBJ_UNLINK, cd_cb, NULL);
880
881         for (i = 0; i < c->n_buckets; i++) {
882                 struct bucket_list *current;
883
884                 while ((current = AST_LIST_REMOVE_HEAD(&c->buckets[i], entry))) {
885                         ast_free(current);
886                 }
887         }
888
889 #ifdef AO2_DEBUG
890         ast_atomic_fetchadd_int(&ao2.total_containers, -1);
891 #endif
892 }
893
894 static void container_destruct_debug(void *_c)
895 {
896         struct ao2_container *c = _c;
897         int i;
898
899         _ao2_callback_debug(c, OBJ_UNLINK, cd_cb_debug, NULL, "container_destruct_debug called", __FILE__, __LINE__, __PRETTY_FUNCTION__);
900
901         for (i = 0; i < c->n_buckets; i++) {
902                 struct bucket_list *current;
903
904                 while ((current = AST_LIST_REMOVE_HEAD(&c->buckets[i], entry))) {
905                         ast_free(current);
906                 }
907         }
908
909 #ifdef AO2_DEBUG
910         ast_atomic_fetchadd_int(&ao2.total_containers, -1);
911 #endif
912 }
913
914 #ifdef AO2_DEBUG
915 static int print_cb(void *obj, void *arg, int flag)
916 {
917         int *fd = arg;
918         char *s = (char *)obj;
919
920         ast_cli(*fd, "string <%s>\n", s);
921         return 0;
922 }
923
924 /*
925  * Print stats
926  */
927 static char *handle_astobj2_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
928 {
929         switch (cmd) {
930         case CLI_INIT:
931                 e->command = "astobj2 show stats";
932                 e->usage = "Usage: astobj2 show stats\n"
933                            "       Show astobj2 show stats\n";
934                 return NULL;
935         case CLI_GENERATE:
936                 return NULL;
937         }
938         ast_cli(a->fd, "Objects    : %d\n", ao2.total_objects);
939         ast_cli(a->fd, "Containers : %d\n", ao2.total_containers);
940         ast_cli(a->fd, "Memory     : %d\n", ao2.total_mem);
941         ast_cli(a->fd, "Locked     : %d\n", ao2.total_locked);
942         ast_cli(a->fd, "Refs       : %d\n", ao2.total_refs);
943         return CLI_SUCCESS;
944 }
945
946 /*
947  * This is testing code for astobj
948  */
949 static char *handle_astobj2_test(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
950 {
951         struct ao2_container *c1;
952         int i, lim;
953         char *obj;
954         static int prof_id = -1;
955         struct ast_cli_args fake_args = { a->fd, 0, NULL };
956
957         switch (cmd) {
958         case CLI_INIT:
959                 e->command = "astobj2 test";
960                 e->usage = "Usage: astobj2 test <num>\n"
961                            "       Runs astobj2 test. Creates 'num' objects,\n"
962                            "       and test iterators, callbacks and may be other stuff\n";
963                 return NULL;
964         case CLI_GENERATE:
965                 return NULL;
966         }
967
968         if (a->argc != 3) {
969                 return CLI_SHOWUSAGE;
970         }
971
972         if (prof_id == -1)
973                 prof_id = ast_add_profile("ao2_alloc", 0);
974
975         ast_cli(a->fd, "argc %d argv %s %s %s\n", a->argc, a->argv[0], a->argv[1], a->argv[2]);
976         lim = atoi(a->argv[2]);
977         ast_cli(a->fd, "called astobj_test\n");
978
979         handle_astobj2_stats(e, CLI_HANDLER, &fake_args);
980         /*
981          * allocate a container with no default callback, and no hash function.
982          * No hash means everything goes in the same bucket.
983          */
984         c1 = ao2_t_container_alloc(100, NULL /* no callback */, NULL /* no hash */,"test");
985         ast_cli(a->fd, "container allocated as %p\n", c1);
986
987         /*
988          * fill the container with objects.
989          * ao2_alloc() gives us a reference which we pass to the
990          * container when we do the insert.
991          */
992         for (i = 0; i < lim; i++) {
993                 ast_mark(prof_id, 1 /* start */);
994                 obj = ao2_t_alloc(80, NULL,"test");
995                 ast_mark(prof_id, 0 /* stop */);
996                 ast_cli(a->fd, "object %d allocated as %p\n", i, obj);
997                 sprintf(obj, "-- this is obj %d --", i);
998                 ao2_link(c1, obj);
999                 /* At this point, the refcount on obj is 2 due to the allocation
1000                  * and linking. We can go ahead and reduce the refcount by 1
1001                  * right here so that when the container is unreffed later, the
1002                  * objects will be freed
1003                  */
1004                 ao2_t_ref(obj, -1, "test");
1005         }
1006         ast_cli(a->fd, "testing callbacks\n");
1007         ao2_t_callback(c1, 0, print_cb, &a->fd, "test callback");
1008         ast_cli(a->fd, "testing iterators, remove every second object\n");
1009         {
1010                 struct ao2_iterator ai;
1011                 int x = 0;
1012
1013                 ai = ao2_iterator_init(c1, 0);
1014                 while ( (obj = ao2_t_iterator_next(&ai,"test")) ) {
1015                         ast_cli(a->fd, "iterator on <%s>\n", obj);
1016                         if (x++ & 1)
1017                                 ao2_t_unlink(c1, obj,"test");
1018                         ao2_t_ref(obj, -1,"test");
1019                 }
1020                 ast_cli(a->fd, "testing iterators again\n");
1021                 ai = ao2_iterator_init(c1, 0);
1022                 while ( (obj = ao2_t_iterator_next(&ai,"test")) ) {
1023                         ast_cli(a->fd, "iterator on <%s>\n", obj);
1024                         ao2_t_ref(obj, -1,"test");
1025                 }
1026         }
1027         ast_cli(a->fd, "testing callbacks again\n");
1028         ao2_t_callback(c1, 0, print_cb, &a->fd, "test callback");
1029
1030         ast_verbose("now you should see an error message:\n");
1031         ao2_t_ref(&i, -1, "");  /* i is not a valid object so we print an error here */
1032
1033         ast_cli(a->fd, "destroy container\n");
1034         ao2_t_ref(c1, -1, "");  /* destroy container */
1035         handle_astobj2_stats(e, CLI_HANDLER, &fake_args);
1036         return CLI_SUCCESS;
1037 }
1038
1039 static struct ast_cli_entry cli_astobj2[] = {
1040         AST_CLI_DEFINE(handle_astobj2_stats, "Print astobj2 statistics"),
1041         AST_CLI_DEFINE(handle_astobj2_test, "Test astobj2"),
1042 };
1043 #endif /* AO2_DEBUG */
1044
1045 int astobj2_init(void)
1046 {
1047 #ifdef AO2_DEBUG
1048         ast_cli_register_multiple(cli_astobj2, ARRAY_LEN(cli_astobj2));
1049 #endif
1050
1051         return 0;
1052 }