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