Merged revisions 82339 via svnmerge from
[asterisk/asterisk.git] / main / astobj2.c
1 /*
2  * astobj2 - replacement containers for asterisk data structures.
3  *
4  * Copyright (C) 2006 Marta Carbone, Luigi Rizzo - Univ. di Pisa, Italy
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*
18  * Function implementing astobj2 objects.
19  */
20 #include "asterisk.h"
21
22 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
23
24 #include "asterisk/astobj2.h"
25 #include "asterisk/utils.h"
26 #include "asterisk/cli.h"
27
28 /*!
29  * astobj2 objects are always preceded by this data structure,
30  * which contains a lock, a reference counter,
31  * the flags and a pointer to a destructor.
32  * The refcount is used to decide when it is time to
33  * invoke the destructor.
34  * The magic number is used for consistency check.
35  * XXX the lock is not always needed, and its initialization may be
36  * expensive. Consider making it external.
37  */
38 struct __priv_data {
39         ast_mutex_t lock;
40         int ref_counter;
41         ao2_destructor_fn destructor_fn;
42         /*! for stats */
43         size_t data_size;
44         /*! magic number.  This is used to verify that a pointer passed in is a
45          *  valid astobj2 */
46         uint32_t magic;
47 };
48
49 #define AO2_MAGIC       0xa570b123
50
51 /*!
52  * What an astobj2 object looks like: fixed-size private data
53  * followed by variable-size user data.
54  */
55 struct astobj2 {
56         struct __priv_data priv_data;
57         void *user_data[0];
58 };
59
60 #ifdef AST_DEVMODE
61 #define AO2_DEBUG 1
62 #endif
63
64 #ifdef AO2_DEBUG
65 struct ao2_stats {
66         volatile int total_objects;
67         volatile int total_mem;
68         volatile int total_containers;
69         volatile int total_refs;
70         volatile int total_locked;
71 };
72
73 static struct ao2_stats ao2;
74 #endif
75
76 #ifndef HAVE_BKTR       /* backtrace support */
77 void ao2_bt(void) {}
78 #else
79 #include <execinfo.h>    /* for backtrace */
80
81 void ao2_bt(void)
82 {
83     int c, i;
84 #define N1      20
85     void *addresses[N1];
86     char **strings;
87
88     c = backtrace(addresses, N1);
89     strings = backtrace_symbols(addresses,c);
90     ast_verbose("backtrace returned: %d\n", c);
91     for(i = 0; i < c; i++) {
92         ast_verbose("%d: %p %s\n", i, addresses[i], strings[i]);
93     }
94     free(strings);
95 }
96 #endif
97
98 /*!
99  * \brief convert from a pointer _p to a user-defined object
100  *
101  * \return the pointer to the astobj2 structure
102  */
103 static inline struct astobj2 *INTERNAL_OBJ(void *user_data)
104 {
105         struct astobj2 *p;
106
107         if (!user_data) {
108                 ast_log(LOG_ERROR, "user_data is NULL\n");
109                 return NULL;
110         }
111
112         p = (struct astobj2 *) ((char *) user_data - sizeof(*p));
113         if (AO2_MAGIC != (p->priv_data.magic) ) {
114                 ast_log(LOG_ERROR, "bad magic number 0x%x for %p\n", p->priv_data.magic, p);
115                 p = NULL;
116         }
117
118         return p;
119 }
120
121 /*!
122  * \brief convert from a pointer _p to an astobj2 object
123  *
124  * \return the pointer to the user-defined portion.
125  */
126 #define EXTERNAL_OBJ(_p)        ((_p) == NULL ? NULL : (_p)->user_data)
127
128 int ao2_lock(void *user_data)
129 {
130         struct astobj2 *p = INTERNAL_OBJ(user_data);
131
132         if (p == NULL)
133                 return -1;
134
135 #ifdef AO2_DEBUG
136         ast_atomic_fetchadd_int(&ao2.total_locked, 1);
137 #endif
138
139         return ast_mutex_lock(&p->priv_data.lock);
140 }
141
142 int ao2_unlock(void *user_data)
143 {
144         struct astobj2 *p = INTERNAL_OBJ(user_data);
145
146         if (p == NULL)
147                 return -1;
148
149 #ifdef AO2_DEBUG
150         ast_atomic_fetchadd_int(&ao2.total_locked, -1);
151 #endif
152
153         return ast_mutex_unlock(&p->priv_data.lock);
154 }
155
156 /*
157  * The argument is a pointer to the user portion.
158  */
159 int ao2_ref(void *user_data, const int delta)
160 {
161         int current_value;
162         int ret;
163         struct astobj2 *obj = INTERNAL_OBJ(user_data);
164
165         if (obj == NULL)
166                 return -1;
167
168         /* if delta is 0, just return the refcount */
169         if (delta == 0)
170                 return (obj->priv_data.ref_counter);
171
172         /* we modify with an atomic operation the reference counter */
173         ret = ast_atomic_fetchadd_int(&obj->priv_data.ref_counter, delta);
174         current_value = ret + delta;
175
176 #ifdef AO2_DEBUG        
177         ast_atomic_fetchadd_int(&ao2.total_refs, delta);
178 #endif
179
180         /* this case must never happen */
181         if (current_value < 0)
182                 ast_log(LOG_ERROR, "refcount %d on object %p\n", current_value, user_data);
183
184         if (current_value <= 0) { /* last reference, destroy the object */
185                 if (obj->priv_data.destructor_fn != NULL) 
186                         obj->priv_data.destructor_fn(user_data);
187
188                 ast_mutex_destroy(&obj->priv_data.lock);
189 #ifdef AO2_DEBUG
190                 ast_atomic_fetchadd_int(&ao2.total_mem, - obj->priv_data.data_size);
191                 ast_atomic_fetchadd_int(&ao2.total_objects, -1);
192 #endif
193                 /* for safety, zero-out the astobj2 header and also the
194                  * first word of the user-data, which we make sure is always
195                  * allocated. */
196                 bzero(obj, sizeof(struct astobj2 *) + sizeof(void *) );
197                 free(obj);
198         }
199
200         return ret;
201 }
202
203 /*
204  * We always alloc at least the size of a void *,
205  * for debugging purposes.
206  */
207 void *ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn)
208 {
209         /* allocation */
210         struct astobj2 *obj;
211
212         if (data_size < sizeof(void *))
213                 data_size = sizeof(void *);
214
215         obj = ast_calloc(1, sizeof(*obj) + data_size);
216
217         if (obj == NULL)
218                 return NULL;
219
220         ast_mutex_init(&obj->priv_data.lock);
221         obj->priv_data.magic = AO2_MAGIC;
222         obj->priv_data.data_size = data_size;
223         obj->priv_data.ref_counter = 1;
224         obj->priv_data.destructor_fn = destructor_fn;   /* can be NULL */
225
226 #ifdef AO2_DEBUG
227         ast_atomic_fetchadd_int(&ao2.total_objects, 1);
228         ast_atomic_fetchadd_int(&ao2.total_mem, data_size);
229         ast_atomic_fetchadd_int(&ao2.total_refs, 1);
230 #endif
231
232         /* return a pointer to the user data */
233         return EXTERNAL_OBJ(obj);
234 }
235
236 /* internal callback to destroy a container. */
237 static void container_destruct(void *c);
238
239 /* each bucket in the container is a tailq. */
240 AST_LIST_HEAD_NOLOCK(bucket, bucket_list);
241
242 /*!
243  * A container; stores the hash and callback functions, information on
244  * the size, the hash bucket heads, and a version number, starting at 0
245  * (for a newly created, empty container)
246  * and incremented every time an object is inserted or deleted.
247  * The assumption is that an object is never moved in a container,
248  * but removed and readded with the new number.
249  * The version number is especially useful when implementing iterators.
250  * In fact, we can associate a unique, monotonically increasing number to
251  * each object, which means that, within an iterator, we can store the
252  * version number of the current object, and easily look for the next one,
253  * which is the next one in the list with a higher number.
254  * Since all objects have a version >0, we can use 0 as a marker for
255  * 'we need the first object in the bucket'.
256  *
257  * \todo Linking and unlink objects is typically expensive, as it
258  * involves a malloc() of a small object which is very inefficient.
259  * To optimize this, we allocate larger arrays of bucket_list's
260  * when we run out of them, and then manage our own freelist.
261  * This will be more efficient as we can do the freelist management while
262  * we hold the lock (that we need anyways).
263  */
264 struct ao2_container {
265         ao2_hash_fn *hash_fn;
266         ao2_callback_fn *cmp_fn;
267         int n_buckets;
268         /*! Number of elements in the container */
269         int elements;
270         /*! described above */
271         int version;
272         /*! variable size */
273         struct bucket buckets[0];
274 };
275  
276 /*!
277  * \brief always zero hash function
278  *
279  * it is convenient to have a hash function that always returns 0.
280  * This is basically used when we want to have a container that is
281  * a simple linked list.
282  *
283  * \returns 0
284  */
285 static int hash_zero(const void *user_obj, const int flags)
286 {
287         return 0;
288 }
289
290 /*
291  * A container is just an object, after all!
292  */
293 struct ao2_container *
294 ao2_container_alloc(const uint n_buckets, ao2_hash_fn *hash_fn,
295                 ao2_callback_fn *cmp_fn)
296 {
297         /* XXX maybe consistency check on arguments ? */
298         /* compute the container size */
299         size_t container_size = sizeof(struct ao2_container) + n_buckets * sizeof(struct bucket);
300
301         struct ao2_container *c = ao2_alloc(container_size, container_destruct);
302
303         if (!c)
304                 return NULL;
305         
306         c->version = 1; /* 0 is a reserved value here */
307         c->n_buckets = n_buckets;
308         c->hash_fn = hash_fn ? hash_fn : hash_zero;
309         c->cmp_fn = cmp_fn;
310
311 #ifdef AO2_DEBUG
312         ast_atomic_fetchadd_int(&ao2.total_containers, 1);
313 #endif
314
315         return c;
316 }
317
318 /*!
319  * return the number of elements in the container
320  */
321 int ao2_container_count(struct ao2_container *c)
322 {
323         return c->elements;
324 }
325
326 /*!
327  * A structure to create a linked list of entries,
328  * used within a bucket.
329  * XXX \todo this should be private to the container code
330  */
331 struct bucket_list {
332         AST_LIST_ENTRY(bucket_list) entry;
333         int version;
334         struct astobj2 *astobj;         /* pointer to internal data */
335 }; 
336
337 /*
338  * link an object to a container
339  */
340 void *ao2_link(struct ao2_container *c, void *user_data)
341 {
342         int i;
343         /* create a new list entry */
344         struct bucket_list *p;
345         struct astobj2 *obj = INTERNAL_OBJ(user_data);
346         
347         if (!obj)
348                 return NULL;
349
350         if (INTERNAL_OBJ(c) == NULL)
351                 return NULL;
352
353         p = ast_calloc(1, sizeof(*p));
354         if (!p)
355                 return NULL;
356
357         i = c->hash_fn(user_data, OBJ_POINTER);
358
359         ao2_lock(c);
360         i %= c->n_buckets;
361         p->astobj = obj;
362         p->version = ast_atomic_fetchadd_int(&c->version, 1);
363         AST_LIST_INSERT_TAIL(&c->buckets[i], p, entry);
364         ast_atomic_fetchadd_int(&c->elements, 1);
365         ao2_unlock(c);
366         
367         return p;
368 }
369
370 /*!
371  * \brief another convenience function is a callback that matches on address
372  */
373 int ao2_match_by_addr(void *user_data, void *arg, int flags)
374 {
375         return (user_data == arg) ? (CMP_MATCH | CMP_STOP) : 0;
376 }
377
378 /*
379  * Unlink an object from the container
380  * and destroy the associated * ao2_bucket_list structure.
381  */
382 void *ao2_unlink(struct ao2_container *c, void *user_data)
383 {
384         if (INTERNAL_OBJ(user_data) == NULL)    /* safety check on the argument */
385                 return NULL;
386
387         ao2_callback(c, OBJ_UNLINK | OBJ_POINTER | OBJ_NODATA, ao2_match_by_addr, user_data);
388
389         return NULL;
390 }
391
392 /*! 
393  * \brief special callback that matches all 
394  */ 
395 static int cb_true(void *user_data, void *arg, int flags)
396 {
397         return CMP_MATCH;
398 }
399
400 /*!
401  * Browse the container using different stategies accoding the flags.
402  * \return Is a pointer to an object or to a list of object if OBJ_MULTIPLE is 
403  * specified.
404  */
405 void *ao2_callback(struct ao2_container *c,
406         const enum search_flags flags,
407         ao2_callback_fn *cb_fn, void *arg)
408 {
409         int i, last;    /* search boundaries */
410         void *ret = NULL;
411
412         if (INTERNAL_OBJ(c) == NULL)    /* safety check on the argument */
413                 return NULL;
414
415         if ((flags & (OBJ_MULTIPLE | OBJ_NODATA)) == OBJ_MULTIPLE) {
416                 ast_log(LOG_WARNING, "multiple data return not implemented yet (flags %x)\n", flags);
417                 return NULL;
418         }
419
420         /* override the match function if necessary */
421         if (cb_fn == NULL)      /* if NULL, match everything */
422                 cb_fn = cb_true;
423         /*
424          * XXX this can be optimized.
425          * If we have a hash function and lookup by pointer,
426          * run the hash function. Otherwise, scan the whole container
427          * (this only for the time being. We need to optimize this.)
428          */
429         if ((flags & OBJ_POINTER))      /* we know hash can handle this case */
430                 i = c->hash_fn(arg, flags & OBJ_POINTER) % c->n_buckets;
431         else                    /* don't know, let's scan all buckets */
432                 i = -1;         /* XXX this must be fixed later. */
433
434         /* determine the search boundaries: i..last-1 */
435         if (i < 0) {
436                 i = 0;
437                 last = c->n_buckets;
438         } else {
439                 last = i + 1;
440         }
441
442         ao2_lock(c);    /* avoid modifications to the content */
443
444         for (; i < last ; i++) {
445                 /* scan the list with prev-cur pointers */
446                 struct bucket_list *cur;
447
448                 AST_LIST_TRAVERSE_SAFE_BEGIN(&c->buckets[i], cur, entry) {
449                         int match = cb_fn(EXTERNAL_OBJ(cur->astobj), arg, flags) & (CMP_MATCH | CMP_STOP);
450
451                         /* we found the object, performing operations according flags */
452                         if (match == 0) {       /* no match, no stop, continue */
453                                 continue;
454                         } else if (match == CMP_STOP) { /* no match but stop, we are done */
455                                 i = last;
456                                 break;
457                         }
458                         /* we have a match (CMP_MATCH) here */
459                         if (!(flags & OBJ_NODATA)) {    /* if must return the object, record the value */
460                                 /* it is important to handle this case before the unlink */
461                                 ret = EXTERNAL_OBJ(cur->astobj);
462                                 ao2_ref(ret, 1);
463                         }
464
465                         if (flags & OBJ_UNLINK) {       /* must unlink */
466                                 struct bucket_list *x = cur;
467
468                                 /* we are going to modify the container, so update version */
469                                 ast_atomic_fetchadd_int(&c->version, 1);
470                                 AST_LIST_REMOVE_CURRENT(&c->buckets[i], entry);
471                                 /* update number of elements and version */
472                                 ast_atomic_fetchadd_int(&c->elements, -1);
473                                 ao2_ref(EXTERNAL_OBJ(x->astobj), -1);
474                                 free(x);        /* free the link record */
475                         }
476
477                         if ((match & CMP_STOP) || (flags & OBJ_MULTIPLE) == 0) {
478                                 /* We found the only match we need */
479                                 i = last;       /* force exit from outer loop */
480                                 break;
481                         }
482                         if (!(flags & OBJ_NODATA)) {
483 #if 0   /* XXX to be completed */
484                                 /*
485                                  * This is the multiple-return case. We need to link
486                                  * the object in a list. The refcount is already increased.
487                                  */
488 #endif
489                         }
490                 }
491                 AST_LIST_TRAVERSE_SAFE_END
492         }
493         ao2_unlock(c);
494         return ret;
495 }
496
497 /*!
498  * the find function just invokes the default callback with some reasonable flags.
499  */
500 void *ao2_find(struct ao2_container *c, void *arg, enum search_flags flags)
501 {
502         return ao2_callback(c, flags, c->cmp_fn, arg);
503 }
504
505 /*!
506  * initialize an iterator so we start from the first object
507  */
508 struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags)
509 {
510         struct ao2_iterator a = {
511                 .c = c,
512                 .flags = flags
513         };
514         
515         return a;
516 }
517
518 /*
519  * move to the next element in the container.
520  */
521 void * ao2_iterator_next(struct ao2_iterator *a)
522 {
523         int lim;
524         struct bucket_list *p = NULL;
525         void *ret = NULL;
526
527         if (INTERNAL_OBJ(a->c) == NULL)
528                 return NULL;
529
530         if (!(a->flags & F_AO2I_DONTLOCK))
531                 ao2_lock(a->c);
532
533         /* optimization. If the container is unchanged and
534          * we have a pointer, try follow it
535          */
536         if (a->c->version == a->c_version && (p = a->obj) ) {
537                 if ( (p = AST_LIST_NEXT(p, entry)) )
538                         goto found;
539                 /* nope, start from the next bucket */
540                 a->bucket++;
541                 a->version = 0;
542                 a->obj = NULL;
543         }
544
545         lim = a->c->n_buckets;
546
547         /* Browse the buckets array, moving to the next
548          * buckets if we don't find the entry in the current one.
549          * Stop when we find an element with version number greater
550          * than the current one (we reset the version to 0 when we
551          * switch buckets).
552          */
553         for (; a->bucket < lim; a->bucket++, a->version = 0) {
554                 /* scan the current bucket */
555                 AST_LIST_TRAVERSE(&a->c->buckets[a->bucket], p, entry) {
556                         if (p->version > a->version)
557                                 goto found;
558                 }
559         }
560
561 found:
562         if (p) {
563                 a->version = p->version;
564                 a->obj = p;
565                 a->c_version = a->c->version;
566                 ret = EXTERNAL_OBJ(p->astobj);
567                 /* inc refcount of returned object */
568                 ao2_ref(ret, 1);
569         }
570
571         if (!(a->flags & F_AO2I_DONTLOCK))
572                 ao2_unlock(a->c);
573
574         return ret;
575 }
576
577 /* callback for destroying container.
578  * we can make it simple as we know what it does
579  */
580 static int cd_cb(void *obj, void *arg, int flag)
581 {
582         ao2_ref(obj, -1);
583         return 0;
584 }
585         
586 static void container_destruct(void *_c)
587 {
588         struct ao2_container *c = _c;
589
590         ao2_callback(c, OBJ_UNLINK, cd_cb, NULL);
591
592 #ifdef AO2_DEBUG
593         ast_atomic_fetchadd_int(&ao2.total_containers, -1);
594 #endif
595 }
596
597 #ifdef AO2_DEBUG
598 static int print_cb(void *obj, void *arg, int flag)
599 {
600         int *fd = arg;
601         char *s = (char *)obj;
602
603         ast_cli(*fd, "string <%s>\n", s);
604         return 0;
605 }
606
607 /*
608  * Print stats
609  */
610 static int handle_astobj2_stats(int fd, int argc, char *argv[])
611 {
612         ast_cli(fd, "Objects    : %d\n", ao2.total_objects);
613         ast_cli(fd, "Containers : %d\n", ao2.total_containers);
614         ast_cli(fd, "Memory     : %d\n", ao2.total_mem);
615         ast_cli(fd, "Locked     : %d\n", ao2.total_locked);
616         ast_cli(fd, "Refs       : %d\n", ao2.total_refs);
617         return 0;
618 }
619
620 /*
621  * This is testing code for astobj
622  */
623 static int handle_astobj2_test(int fd, int argc, char *argv[])
624 {
625         struct ao2_container *c1;
626         int i, lim;
627         char *obj;
628         static int prof_id = -1;
629
630         if (prof_id == -1)
631                 prof_id = ast_add_profile("ao2_alloc", 0);
632
633         ast_cli(fd, "argc %d argv %s %s %s\n", argc, argv[0], argv[1], argv[2]);
634         lim = atoi(argv[2]);
635         ast_cli(fd, "called astobj_test\n");
636
637         handle_astobj2_stats(fd, 0, NULL);
638         /*
639          * allocate a container with no default callback, and no hash function.
640          * No hash means everything goes in the same bucket.
641          */
642         c1 = ao2_container_alloc(100, NULL /* no callback */, NULL /* no hash */);
643         ast_cli(fd, "container allocated as %p\n", c1);
644
645         /*
646          * fill the container with objects.
647          * ao2_alloc() gives us a reference which we pass to the
648          * container when we do the insert.
649          */
650         for (i = 0; i < lim; i++) {
651                 ast_mark(prof_id, 1 /* start */);
652                 obj = ao2_alloc(80, NULL);
653                 ast_mark(prof_id, 0 /* stop */);
654                 ast_cli(fd, "object %d allocated as %p\n", i, obj);
655                 sprintf(obj, "-- this is obj %d --", i);
656                 ao2_link(c1, obj);
657         }
658         ast_cli(fd, "testing callbacks\n");
659         ao2_callback(c1, 0, print_cb, &fd);
660
661         ast_cli(fd, "testing iterators, remove every second object\n");
662         {
663                 struct ao2_iterator ai;
664                 int x = 0;
665
666                 ai = ao2_iterator_init(c1, 0);
667                 while ( (obj = ao2_iterator_next(&ai)) ) {
668                         ast_cli(fd, "iterator on <%s>\n", obj);
669                         if (x++ & 1)
670                                 ao2_unlink(c1, obj);
671                         ao2_ref(obj, -1);
672                 }
673                 ast_cli(fd, "testing iterators again\n");
674                 ai = ao2_iterator_init(c1, 0);
675                 while ( (obj = ao2_iterator_next(&ai)) ) {
676                         ast_cli(fd, "iterator on <%s>\n", obj);
677                         ao2_ref(obj, -1);
678                 }
679         }
680         ast_cli(fd, "testing callbacks again\n");
681         ao2_callback(c1, 0, print_cb, &fd);
682
683         ast_verbose("now you should see an error message:\n");
684         ao2_ref(&i, -1);        /* i is not a valid object so we print an error here */
685
686         ast_cli(fd, "destroy container\n");
687         ao2_ref(c1, -1);        /* destroy container */
688         handle_astobj2_stats(fd, 0, NULL);
689         return 0;
690 }
691
692 static struct ast_cli_entry cli_astobj2[] = {
693         { { "astobj2", "stats", NULL },
694         handle_astobj2_stats, "Print astobj2 statistics", },
695         { { "astobj2", "test", NULL } , handle_astobj2_test, "Test astobj2", },
696 };
697 #endif /* AO2_DEBUG */
698
699 int astobj2_init(void)
700 {
701 #ifdef AO2_DEBUG
702         ast_cli_register_multiple(cli_astobj2, ARRAY_LEN(cli_astobj2));
703 #endif
704
705         return 0;
706 }