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