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