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