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