2 * astobj2 - replacement containers for asterisk data structures.
4 * Copyright (C) 2006 Marta Carbone, Luigi Rizzo - Univ. di Pisa, Italy
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.
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.
17 #ifndef _ASTERISK_ASTOBJ2_H
18 #define _ASTERISK_ASTOBJ2_H
20 #include "asterisk/compat.h"
21 #include "asterisk/linkedlists.h"
26 * \page AstObj2 Object Model implementing objects and containers.
28 This module implements an abstraction for objects (with locks and
29 reference counts), and containers for these user-defined objects,
30 also supporting locking, reference counting and callbacks.
32 The internal implementation of objects and containers is opaque to the user,
33 so we can use different data structures as needs arise.
35 \section AstObj2_UsageObjects USAGE - OBJECTS
37 An ao2 object is a block of memory that the user code can access,
38 and for which the system keeps track (with a bit of help from the
39 programmer) of the number of references around. When an object has
40 no more references (refcount == 0), it is destroyed, by first
41 invoking whatever 'destructor' function the programmer specifies
42 (it can be NULL if none is necessary), and then freeing the memory.
43 This way objects can be shared without worrying who is in charge
45 As an additional feature, ao2 objects are associated to individual
48 Creating an object requires the size of the object and
49 a pointer to the destructor function:
53 o = ao2_alloc(sizeof(struct foo), my_destructor_fn);
55 The value returned points to the user-visible portion of the objects
56 (user-data), but is also used as an identifier for all object-related
57 operations such as refcount and lock manipulations.
59 On return from ao2_alloc():
61 - the object has a refcount = 1;
62 - the memory for the object is allocated dynamically and zeroed;
63 - we cannot realloc() the object itself;
64 - we cannot call free(o) to dispose of the object. Rather, we
65 tell the system that we do not need the reference anymore:
69 causing the destructor to be called (and then memory freed) when
70 the refcount goes to 0.
72 - ao2_ref(o, +1) can be used to modify the refcount on the
73 object in case we want to pass it around.
75 - ao2_lock(obj), ao2_unlock(obj), ao2_trylock(obj) can be used
76 to manipulate the lock associated with the object.
79 \section AstObj2_UsageContainers USAGE - CONTAINERS
81 An ao2 container is an abstract data structure where we can store
82 ao2 objects, search them (hopefully in an efficient way), and iterate
83 or apply a callback function to them. A container is just an ao2 object
86 A container must first be allocated, specifying the initial
87 parameters. At the moment, this is done as follows:
92 struct ao2_container *c;
94 c = ao2_container_alloc(MAX_BUCKETS, my_hash_fn, my_cmp_fn);
99 - MAX_BUCKETS is the number of buckets in the hash table,
100 - my_hash_fn() is the (user-supplied) function that returns a
101 hash key for the object (further reduced modulo MAX_BUCKETS
102 by the container's code);
103 - my_cmp_fn() is the default comparison function used when doing
104 searches on the container,
106 A container knows little or nothing about the objects it stores,
107 other than the fact that they have been created by ao2_alloc().
108 All knowledge of the (user-defined) internals of the objects
109 is left to the (user-supplied) functions passed as arguments
110 to ao2_container_alloc().
112 If we want to insert an object in a container, we should
113 initialize its fields -- especially, those used by my_hash_fn() --
114 to compute the bucket to use.
115 Once done, we can link an object to a container with
119 The function returns NULL in case of errors (and the object
120 is not inserted in the container). Other values mean success
121 (we are not supposed to use the value as a pointer to anything).
122 Linking an object to a container increases its refcount by 1
125 \note While an object o is in a container, we expect that
126 my_hash_fn(o) will always return the same value. The function
127 does not lock the object to be computed, so modifications of
128 those fields that affect the computation of the hash should
129 be done by extracting the object from the container, and
130 re-inserting it after the change (this is not terribly expensive).
132 \note A container with a single buckets is effectively a linked
133 list. However there is no ordering among elements.
135 - \ref AstObj2_Containers
136 - \ref astobj2.h All documentation for functions and data structures
141 \note DEBUGGING REF COUNTS BIBLE:
142 An interface to help debug refcounting is provided
143 in this package. It is dependent on the REF_DEBUG macro being
144 defined in a source file, before the #include of astobj2.h,
145 and in using variants of the normal ao2_xxx functions
146 that are named ao2_t_xxx instead, with an extra argument, a string,
147 that will be printed out into /tmp/refs when the refcount for an
150 these ao2_t_xxx variants are provided:
152 ao2_t_alloc(arg1, arg2, arg3)
153 ao2_t_ref(arg1,arg2,arg3)
154 ao2_t_container_alloc(arg1,arg2,arg3,arg4)
155 ao2_t_link(arg1, arg2, arg3)
156 ao2_t_unlink(arg1, arg2, arg3)
157 ao2_t_callback(arg1,arg2,arg3,arg4,arg5)
158 ao2_t_find(arg1,arg2,arg3,arg4)
159 ao2_t_iterator_next(arg1, arg2)
161 If you study each argument list, you will see that these functions all have
162 one extra argument than their ao2_xxx counterpart. The last argument in
163 each case is supposed to be a string pointer, a "tag", that should contain
164 enough of an explanation, that you can pair operations that increment the
165 ref count, with operations that are meant to decrement the refcount.
167 Each of these calls will generate at least one line of output in /tmp/refs.
168 These lines look like this:
170 0x8756f00 =1 chan_sip.c:22240:load_module (allocate users)
171 0x86e3408 =1 chan_sip.c:22241:load_module (allocate peers)
172 0x86dd380 =1 chan_sip.c:22242:load_module (allocate peers_by_ip)
173 0x822d020 =1 chan_sip.c:22243:load_module (allocate dialogs)
174 0x8930fd8 =1 chan_sip.c:20025:build_peer (allocate a peer struct)
175 0x8930fd8 +1 chan_sip.c:21467:reload_config (link peer into peer table) [@1]
176 0x8930fd8 -1 chan_sip.c:2370:unref_peer (unref_peer: from reload_config) [@2]
177 0x89318b0 =1 chan_sip.c:20025:build_peer (allocate a peer struct)
178 0x89318b0 +1 chan_sip.c:21467:reload_config (link peer into peer table) [@1]
179 0x89318b0 -1 chan_sip.c:2370:unref_peer (unref_peer: from reload_config) [@2]
180 0x8930218 =1 chan_sip.c:20025:build_peer (allocate a peer struct)
181 0x8930218 +1 chan_sip.c:21539:reload_config (link peer into peers table) [@1]
182 0x868c040 -1 chan_sip.c:2424:dialog_unlink_all (unset the relatedpeer->call field in tandem with relatedpeer field itself) [@2]
183 0x868c040 -1 chan_sip.c:2443:dialog_unlink_all (Let's unbump the count in the unlink so the poor pvt can disappear if it is time) [@1]
184 0x868c040 **call destructor** chan_sip.c:2443:dialog_unlink_all (Let's unbump the count in the unlink so the poor pvt can disappear if it is time)
185 0x8cc07e8 -1 chan_sip.c:2370:unref_peer (unsetting a dialog relatedpeer field in sip_destroy) [@3]
186 0x8cc07e8 +1 chan_sip.c:3876:find_peer (ao2_find in peers table) [@2]
187 0x8cc07e8 -1 chan_sip.c:2370:unref_peer (unref_peer, from sip_devicestate, release ref from find_peer) [@3]
190 The first column is the object address.
191 The second column reflects how the operation affected the ref count
192 for that object. Creation sets the ref count to 1 (=1).
193 increment or decrement and amount are specified (-1/+1).
194 The remainder of the line specifies where in the file the call was made,
195 and the function name, and the tag supplied in the function call.
197 The **call destructor** is specified when the destroy routine is
198 run for an object. It does not affect the ref count, but is important
199 in debugging, because it is possible to have the astobj2 system run it
200 multiple times on the same object, commonly fatal to asterisk.
202 Sometimes you have some helper functions to do object ref/unref
203 operations. Using these normally hides the place where these
204 functions were called. To get the location where these functions
205 were called to appear in /tmp/refs, you can do this sort of thing:
208 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
209 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
210 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, const char *file, int line, const char *func)
213 ao2_ref_debug(p, 1, tag, file, line, func);
215 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
220 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, const char *file, int line, const char *func)
223 ao2_ref_debug(p, -1, tag, file, line, func);
228 static struct sip_pvt *dialog_ref(struct sip_pvt *p, const char *tag)
233 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
238 static struct sip_pvt *dialog_unref(struct sip_pvt *p, const char *tag)
247 In the above code, note that the "normal" helper funcs call ao2_ref() as
248 normal, and the "helper" functions call ao2_ref_debug directly with the
249 file, function, and line number info provided. You might find this
250 well worth the effort to help track these function calls in the code.
252 To find out why objects are not destroyed (a common bug), you can
253 edit the source file to use the ao2_t_* variants, add the #define REF_DEBUG 1
254 before the #include "asterisk/astobj2.h" line, and add a descriptive
255 tag to each call. Recompile, and run Asterisk, exit asterisk with
256 "stop gracefully", which should result in every object being destroyed.
257 Then, you can "sort -k 1 /tmp/refs > x1" to get a sorted list of
258 all the objects, or you can use "util/refcounter" to scan the file
259 for you and output any problems it finds.
261 The above may seem astronomically more work than it is worth to debug
262 reference counts, which may be true in "simple" situations, but for
263 more complex situations, it is easily worth 100 times this effort to
266 To debug, pair all calls so that each call that increments the
267 refcount is paired with a corresponding call that decrements the
268 count for the same reason. Hopefully, you will be left with one
269 or more unpaired calls. This is where you start your search!
271 For instance, here is an example of this for a dialog object in
272 chan_sip, that was not getting destroyed, after I moved the lines around
275 0x83787a0 =1 chan_sip.c:5733:sip_alloc (allocate a dialog(pvt) struct)
276 0x83787a0 -1 chan_sip.c:19173:sip_poke_peer (unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope) [@4]
278 0x83787a0 +1 chan_sip.c:5854:sip_alloc (link pvt into dialogs table) [@1]
279 0x83787a0 -1 chan_sip.c:19150:sip_poke_peer (About to change the callid -- remove the old name) [@3]
280 0x83787a0 +1 chan_sip.c:19152:sip_poke_peer (Linking in under new name) [@2]
281 0x83787a0 -1 chan_sip.c:2399:dialog_unlink_all (unlinking dialog via ao2_unlink) [@5]
283 0x83787a0 +1 chan_sip.c:19130:sip_poke_peer (copy sip alloc from p to peer->call) [@2]
286 0x83787a0 +1 chan_sip.c:2996:__sip_reliable_xmit (__sip_reliable_xmit: setting pkt->owner) [@3]
287 0x83787a0 -1 chan_sip.c:2425:dialog_unlink_all (remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy) [@4]
289 0x83787a0 +1 chan_sip.c:22356:unload_module (iterate thru dialogs) [@4]
290 0x83787a0 -1 chan_sip.c:22359:unload_module (toss dialog ptr from iterator_next) [@5]
293 0x83787a0 +1 chan_sip.c:22373:unload_module (iterate thru dialogs) [@3]
294 0x83787a0 -1 chan_sip.c:22375:unload_module (throw away iterator result) [@2]
296 0x83787a0 +1 chan_sip.c:2397:dialog_unlink_all (Let's bump the count in the unlink so it doesn't accidentally become dead before we are done) [@4]
297 0x83787a0 -1 chan_sip.c:2436:dialog_unlink_all (Let's unbump the count in the unlink so the poor pvt can disappear if it is time) [@3]
299 As you can see, only one unbalanced operation is in the list, a ref count increment when
300 the peer->call was set, but no corresponding decrement was made...
302 Hopefully this helps you narrow your search and find those bugs.
304 THE ART OF REFERENCE COUNTING
306 SOME TIPS for complicated code, and ref counting:
308 1. Theoretically, passing a refcounted object pointer into a function
309 call is an act of copying the reference, and could be refcounted.
310 But, upon examination, this sort of refcounting will explode the amount
311 of code you have to enter, and for no tangible benefit, beyond
312 creating more possible failure points/bugs. It will even
313 complicate your code and make debugging harder, slow down your program
314 doing useless increments and decrements of the ref counts.
316 2. It is better to track places where a ref counted pointer
317 is copied into a structure or stored. Make sure to decrement the refcount
318 of any previous pointer that might have been there, if setting
319 this field might erase a previous pointer. ao2_find and iterate_next
320 internally increment the ref count when they return a pointer, so
321 you need to decrement the count before the pointer goes out of scope.
323 3. Any time you decrement a ref count, it may be possible that the
324 object will be destroyed (freed) immediately by that call. If you
325 are destroying a series of fields in a refcounted object, and
326 any of the unref calls might possibly result in immediate destruction,
327 you can first increment the count to prevent such behavior, then
328 after the last test, decrement the pointer to allow the object
329 to be destroyed, if the refcount would be zero.
333 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
335 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
337 *//* Unlink us from the owner (channel) if we have one *//*
340 ast_channel_lock(dialog->owner);
342 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
343 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
345 ast_channel_unlock(dialog->owner);
348 if (dialog->registry) {
349 if (dialog->registry->call == dialog) {
350 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
352 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
355 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
357 In the above code, the ao2_t_unlink could end up destroying the dialog
358 object; if this happens, then the subsequent usages of the dialog
359 pointer could result in a core dump. So, we 'bump' the
360 count upwards before beginning, and then decrementing the count when
361 we are finished. This is analogous to 'locking' or 'protecting' operations
364 4. One of the most insidious problems I've run into when converting
365 code to do ref counted automatic destruction, is in the destruction
366 routines. Where a "destroy" routine had previously been called to
367 get rid of an object in non-refcounted code, the new regime demands
368 that you tear that "destroy" routine into two pieces, one that will
369 tear down the links and 'unref' them, and the other to actually free
370 and reset fields. A destroy routine that does any reference deletion
371 for its own object, will never be called. Another insidious problem
372 occurs in mutually referenced structures. As an example, a dialog contains
373 a pointer to a peer, and a peer contains a pointer to a dialog. Watch
374 out that the destruction of one doesn't depend on the destruction of the
375 other, as in this case a dependency loop will result in neither being
378 Given the above, you should be ready to do a good job!
387 * Typedef for an object destructor. This is called just before freeing
388 * the memory for the object. It is passed a pointer to the user-defined
389 * data of the object.
391 typedef void (*ao2_destructor_fn)(void *);
395 * \brief Allocate and initialize an object.
397 * \param data_size The sizeof() of the user-defined structure.
398 * \param destructor_fn The destructor function (can be NULL)
399 * \param debug_msg Ao2 object debug tracing message.
400 * \return A pointer to user-data.
403 * Allocates a struct astobj2 with sufficient space for the
404 * user-defined structure.
406 * - storage is zeroed; XXX maybe we want a flag to enable/disable this.
407 * - the refcount of the object just created is 1
408 * - the returned pointer cannot be free()'d or realloc()'ed;
409 * rather, we just call ao2_ref(o, -1);
414 #if defined(REF_DEBUG)
416 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
417 __ao2_alloc_debug((data_size), (destructor_fn), (debug_msg), __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
418 #define ao2_alloc(data_size, destructor_fn) \
419 __ao2_alloc_debug((data_size), (destructor_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
421 #elif defined(__AST_DEBUG_MALLOC)
423 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
424 __ao2_alloc_debug((data_size), (destructor_fn), (debug_msg), __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
425 #define ao2_alloc(data_size, destructor_fn) \
426 __ao2_alloc_debug((data_size), (destructor_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
430 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
431 __ao2_alloc((data_size), (destructor_fn))
432 #define ao2_alloc(data_size, destructor_fn) \
433 __ao2_alloc((data_size), (destructor_fn))
437 void *__ao2_alloc_debug(size_t data_size, ao2_destructor_fn destructor_fn, const char *tag,
438 const char *file, int line, const char *funcname, int ref_debug);
439 void *__ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn);
444 * Reference/unreference an object and return the old refcount.
446 * \param o A pointer to the object
447 * \param delta Value to add to the reference counter.
448 * \param tag used for debugging
449 * \return The value of the reference counter before the operation.
451 * Increase/decrease the reference counter according
452 * the value of delta.
454 * If the refcount goes to zero, the object is destroyed.
456 * \note The object must not be locked by the caller of this function, as
457 * it is invalid to try to unlock it after releasing the reference.
459 * \note if we know the pointer to an object, it is because we
460 * have a reference count to it, so the only case when the object
461 * can go away is when we release our reference, and it is
462 * the last one in existence.
469 #define ao2_t_ref(o,delta,tag) __ao2_ref_debug((o), (delta), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
470 #define ao2_ref(o,delta) __ao2_ref_debug((o), (delta), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
474 #define ao2_t_ref(o,delta,tag) __ao2_ref((o), (delta))
475 #define ao2_ref(o,delta) __ao2_ref((o), (delta))
479 int __ao2_ref_debug(void *o, int delta, const char *tag, char *file, int line, const char *funcname);
480 int __ao2_ref(void *o, int delta);
487 * \param a A pointer to the object we want to lock.
488 * \return 0 on success, other values on error.
490 int __ao2_lock(void *a, const char *file, const char *func, int line, const char *var);
491 #define ao2_lock(a) __ao2_lock(a, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
496 * \param a A pointer to the object we want unlock.
497 * \return 0 on success, other values on error.
499 int __ao2_unlock(void *a, const char *file, const char *func, int line, const char *var);
500 #define ao2_unlock(a) __ao2_unlock(a, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
503 * Try locking-- (don't block if fail)
505 * \param a A pointer to the object we want to lock.
506 * \return 0 on success, other values on error.
508 int __ao2_trylock(void *a, const char *file, const char *func, int line, const char *var);
509 #define ao2_trylock(a) __ao2_trylock(a, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
512 * \brief Return the mutex lock address of an object
514 * \param[in] obj A pointer to the object we want.
515 * \return the address of the mutex lock, else NULL.
517 * This function comes in handy mainly for debugging locking
518 * situations, where the locking trace code reports the
519 * lock address, this allows you to correlate against
520 * object address, to match objects to reported locks.
524 void *ao2_object_get_lockaddr(void *obj);
527 \page AstObj2_Containers AstObj2 Containers
529 Containers are data structures meant to store several objects,
530 and perform various operations on them.
531 Internally, objects are stored in lists, hash tables or other
532 data structures depending on the needs.
534 \note NOTA BENE: at the moment the only container we support is the
535 hash table and its degenerate form, the list.
537 Operations on container include:
539 - c = \b ao2_container_alloc(size, hash_fn, cmp_fn)
540 allocate a container with desired size and default compare
542 -The compare function returns an int, which
543 can be 0 for not found, CMP_STOP to stop end a traversal,
544 or CMP_MATCH if they are equal
545 -The hash function returns an int. The hash function
546 takes two argument, the object pointer and a flags field,
548 - \b ao2_find(c, arg, flags)
549 returns zero or more elements matching a given criteria
550 (specified as arg). 'c' is the container pointer. Flags
552 OBJ_UNLINK - to remove the object, once found, from the container.
553 OBJ_NODATA - don't return the object if found (no ref count change)
554 OBJ_MULTIPLE - don't stop at first match
555 OBJ_POINTER - if set, 'arg' is an object pointer, and a hash table
556 search will be done. If not, a traversal is done.
557 OBJ_KEY - if set, 'arg', is a hashable item that is not an object.
558 Similar to OBJ_POINTER and mutually exclusive.
560 - \b ao2_callback(c, flags, fn, arg)
561 apply fn(obj, arg) to all objects in the container.
562 Similar to find. fn() can tell when to stop, and
563 do anything with the object including unlinking it.
564 - c is the container;
566 OBJ_UNLINK - to remove the object, once found, from the container.
567 OBJ_NODATA - don't return the object if found (no ref count change)
568 OBJ_MULTIPLE - don't stop at first match
569 OBJ_POINTER - if set, 'arg' is an object pointer, and a hash table
570 search will be done. If not, a traversal is done through
571 all the hash table 'buckets'..
572 OBJ_KEY - if set, 'arg', is a hashable item that is not an object.
573 Similar to OBJ_POINTER and mutually exclusive.
574 - fn is a func that returns int, and takes 3 args:
575 (void *obj, void *arg, int flags);
577 arg is the same as arg passed into ao2_callback
578 flags is the same as flags passed into ao2_callback
580 0: no match, keep going
581 CMP_STOP: stop search, no match
582 CMP_MATCH: This object is matched.
584 Note that the entire operation is run with the container
585 locked, so nobody else can change its content while we work on it.
586 However, we pay this with the fact that doing
587 anything blocking in the callback keeps the container
589 The mechanism is very flexible because the callback function fn()
590 can do basically anything e.g. counting, deleting records, etc.
591 possibly using arg to store the results.
593 - \b iterate on a container
594 this is done with the following sequence
598 struct ao2_container *c = ... // our container
599 struct ao2_iterator i;
602 i = ao2_iterator_init(c, flags);
604 while ((o = ao2_iterator_next(&i))) {
605 ... do something on o ...
609 ao2_iterator_destroy(&i);
612 The difference with the callback is that the control
613 on how to iterate is left to us.
616 dropping a reference to a container destroys it, very simple!
618 Containers are ao2 objects themselves, and this is why their
619 implementation is simple too.
621 Before declaring containers, we need to declare the types of the
622 arguments passed to the constructor - in turn, this requires
623 to define callback and hash functions and their arguments.
630 * Type of a generic callback function
631 * \param obj pointer to the (user-defined part) of an object.
632 * \param arg callback argument from ao2_callback()
633 * \param flags flags from ao2_callback()
635 * The return values are a combination of enum _cb_results.
636 * Callback functions are used to search or manipulate objects in a container.
638 typedef int (ao2_callback_fn)(void *obj, void *arg, int flags);
641 * Type of a generic callback function
642 * \param obj pointer to the (user-defined part) of an object.
643 * \param arg callback argument from ao2_callback()
644 * \param data arbitrary data from ao2_callback()
645 * \param flags flags from ao2_callback()
647 * The return values are a combination of enum _cb_results.
648 * Callback functions are used to search or manipulate objects in a container.
650 typedef int (ao2_callback_data_fn)(void *obj, void *arg, void *data, int flags);
652 /*! \brief a very common callback is one that matches by address. */
653 ao2_callback_fn ao2_match_by_addr;
656 * A callback function will return a combination of CMP_MATCH and CMP_STOP.
657 * The latter will terminate the search in a container.
660 CMP_MATCH = 0x1, /*!< the object matches the request */
661 CMP_STOP = 0x2, /*!< stop the search now */
665 * Flags passed to ao2_callback() and ao2_hash_fn() to modify its behaviour.
668 /*! Unlink the object for which the callback function
669 * returned CMP_MATCH.
671 OBJ_UNLINK = (1 << 0),
672 /*! On match, don't return the object hence do not increase
675 OBJ_NODATA = (1 << 1),
676 /*! Don't stop at the first match in ao2_callback() unless the result of
677 * of the callback function == (CMP_STOP | CMP_MATCH).
679 OBJ_MULTIPLE = (1 << 2),
680 /*! obj is an object of the same type as the one being searched for,
681 * so use the object's hash function for optimized searching.
682 * The search function is unaffected (i.e. use the one passed as
683 * argument, or match_by_addr if none specified).
685 OBJ_POINTER = (1 << 3),
687 * \brief Continue if a match is not found in the hashed out bucket
689 * This flag is to be used in combination with OBJ_POINTER. This tells
690 * the ao2_callback() core to keep searching through the rest of the
691 * buckets if a match is not found in the starting bucket defined by
692 * the hash value on the argument.
694 OBJ_CONTINUE = (1 << 4),
696 * \brief By using this flag, the ao2_container being searched will _NOT_
697 * be locked. Only use this flag if the ao2_container is being protected
698 * by another mechanism other that the internal ao2_lock.
700 OBJ_NOLOCK = (1 << 5),
702 * \brief The data is hashable, but is not an object.
705 * This can be used when you want to be able to pass custom data
706 * to the container's stored ao2_hash_fn and ao2_find
707 * ao2_callback_fn functions that is not a full object, but
708 * perhaps just a string.
710 * \note OBJ_KEY and OBJ_POINTER are mutually exclusive options.
716 * Type of a generic function to generate a hash value from an object.
717 * flags is ignored at the moment. Eventually, it will include the
718 * value of OBJ_POINTER passed to ao2_callback().
720 typedef int (ao2_hash_fn)(const void *obj, const int flags);
722 /*! \name Object Containers
723 * Here start declarations of containers.
726 struct ao2_container;
729 * \brief Allocate and initialize a hash container with the desired number of buckets.
732 * We allocate space for a struct astobj_container, struct container
733 * and the buckets[] array.
735 * \param n_buckets Number of buckets for hash
736 * \param hash_fn Pointer to a function computing a hash value.
737 * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
738 * \param tag used for debugging.
740 * \return A pointer to a struct container.
742 * \note Destructor is set implicitly.
745 #if defined(REF_DEBUG)
747 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
748 __ao2_container_alloc_debug((n_buckets), (hash_fn), (cmp_fn), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
749 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
750 __ao2_container_alloc_debug((n_buckets), (hash_fn), (cmp_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
752 #elif defined(__AST_DEBUG_MALLOC)
754 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
755 __ao2_container_alloc_debug((n_buckets), (hash_fn), (cmp_fn), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
756 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
757 __ao2_container_alloc_debug((n_buckets), (hash_fn), (cmp_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
761 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
762 __ao2_container_alloc((n_buckets), (hash_fn), (cmp_fn))
763 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
764 __ao2_container_alloc((n_buckets), (hash_fn), (cmp_fn))
768 struct ao2_container *__ao2_container_alloc(unsigned int n_buckets, ao2_hash_fn *hash_fn,
769 ao2_callback_fn *cmp_fn);
770 struct ao2_container *__ao2_container_alloc_debug(unsigned int n_buckets,
771 ao2_hash_fn *hash_fn, ao2_callback_fn *cmp_fn,
772 const char *tag, char *file, int line, const char *funcname, int ref_debug);
775 * Returns the number of elements in a container.
777 int ao2_container_count(struct ao2_container *c);
781 /*! \name Object Management
782 * Here we have functions to manage objects.
784 * We can use the functions below on any kind of
785 * object defined by the user.
790 * \brief Add an object to a container.
792 * \param container The container to operate on.
793 * \param obj The object to be added.
794 * \param tag used for debugging.
796 * \retval NULL on errors.
797 * \retval newobj on success.
799 * This function inserts an object in a container according its key.
801 * \note Remember to set the key before calling this function.
803 * \note This function automatically increases the reference count to account
804 * for the reference that the container now holds to the object.
808 #define ao2_t_link(container, obj, tag) __ao2_link_debug((container), (obj), 0, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
809 #define ao2_link(container, obj) __ao2_link_debug((container), (obj), 0, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
811 #define ao2_t_link_nolock(container, obj, tag) __ao2_link_debug((container), (obj), OBJ_NOLOCK, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
812 #define ao2_link_nolock(container, obj) __ao2_link_debug((container), (obj), OBJ_NOLOCK, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
816 #define ao2_t_link(container, obj, tag) __ao2_link((container), (obj), 0)
817 #define ao2_link(container, obj) __ao2_link((container), (obj), 0)
819 #define ao2_t_link_nolock(container, obj, tag) __ao2_link((container), (obj), OBJ_NOLOCK)
820 #define ao2_link_nolock(container, obj) __ao2_link((container), (obj), OBJ_NOLOCK)
824 void *__ao2_link_debug(struct ao2_container *c, void *new_obj, int flags, const char *tag, char *file, int line, const char *funcname);
825 void *__ao2_link(struct ao2_container *c, void *newobj, int flags);
828 * \brief Remove an object from a container
830 * \param container The container to operate on.
831 * \param obj The object to unlink.
832 * \param tag used for debugging.
834 * \retval NULL, always
836 * \note The object requested to be unlinked must be valid. However, if it turns
837 * out that it is not in the container, this function is still safe to
840 * \note If the object gets unlinked from the container, the container's
841 * reference to the object will be automatically released. (The
842 * refcount will be decremented).
846 #define ao2_t_unlink(container, obj, tag) __ao2_unlink_debug((container), (obj), 0, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
847 #define ao2_unlink(container, obj) __ao2_unlink_debug((container), (obj), 0, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
849 #define ao2_t_unlink_nolock(container, obj, tag) __ao2_unlink_debug((container), (obj), OBJ_NOLOCK, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
850 #define ao2_unlink_nolock(container, obj) __ao2_unlink_debug((container), (obj), OBJ_NOLOCK, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
854 #define ao2_t_unlink(container, obj, tag) __ao2_unlink((container), (obj), 0)
855 #define ao2_unlink(container, obj) __ao2_unlink((container), (obj), 0)
857 #define ao2_t_unlink_nolock(container, obj, tag) __ao2_unlink((container), (obj), OBJ_NOLOCK)
858 #define ao2_unlink_nolock(container, obj) __ao2_unlink((container), (obj), OBJ_NOLOCK)
862 void *__ao2_unlink_debug(struct ao2_container *c, void *obj, int flags, const char *tag, char *file, int line, const char *funcname);
863 void *__ao2_unlink(struct ao2_container *c, void *obj, int flags);
869 * ao2_callback() is a generic function that applies cb_fn() to all objects
870 * in a container, as described below.
872 * \param c A pointer to the container to operate on.
873 * \param flags A set of flags specifying the operation to perform,
874 * partially used by the container code, but also passed to
876 * - If OBJ_NODATA is set, ao2_callback will return NULL. No refcounts
877 * of any of the traversed objects will be incremented.
878 * On the converse, if it is NOT set (the default), The ref count
879 * of each object for which CMP_MATCH was set will be incremented,
880 * and you will have no way of knowing which those are, until
881 * the multiple-object-return functionality is implemented.
882 * - If OBJ_POINTER is set, the traversed items will be restricted
883 * to the objects in the bucket that the object key hashes to.
884 * \param cb_fn A function pointer, that will be called on all
885 * objects, to see if they match. This function returns CMP_MATCH
886 * if the object is matches the criteria; CMP_STOP if the traversal
887 * should immediately stop, or both (via bitwise ORing), if you find a
888 * match and want to end the traversal, and 0 if the object is not a match,
889 * but the traversal should continue. This is the function that is applied
890 * to each object traversed. Its arguments are:
891 * (void *obj, void *arg, int flags), where:
893 * arg is the same as arg passed into ao2_callback
894 * flags is the same as flags passed into ao2_callback (flags are
895 * also used by ao2_callback).
896 * \param arg passed to the callback.
897 * \param tag used for debugging.
898 * \return when OBJ_MULTIPLE is not included in the flags parameter,
899 * the return value will be either the object found or NULL if no
900 * no matching object was found. if OBJ_MULTIPLE is included,
901 * the return value will be a pointer to an ao2_iterator object,
902 * which must be destroyed with ao2_iterator_destroy() when the
903 * caller no longer needs it.
905 * If the function returns any objects, their refcount is incremented,
906 * and the caller is in charge of decrementing them once done.
908 * Typically, ao2_callback() is used for two purposes:
909 * - to perform some action (including removal from the container) on one
910 * or more objects; in this case, cb_fn() can modify the object itself,
911 * and to perform deletion should set CMP_MATCH on the matching objects,
912 * and have OBJ_UNLINK set in flags.
913 * - to look for a specific object in a container; in this case, cb_fn()
914 * should not modify the object, but just return a combination of
915 * CMP_MATCH and CMP_STOP on the desired object.
916 * Other usages are also possible, of course.
918 * This function searches through a container and performs operations
919 * on objects according on flags passed.
920 * XXX describe better
921 * The comparison is done calling the compare function set implicitly.
922 * The p pointer can be a pointer to an object or to a key,
923 * we can say this looking at flags value.
924 * If p points to an object we will search for the object pointed
925 * by this value, otherwise we search for a key value.
926 * If the key is not unique we only find the first matching valued.
928 * The use of flags argument is the follow:
930 * OBJ_UNLINK unlinks the object found
931 * OBJ_NODATA on match, do return an object
932 * Callbacks use OBJ_NODATA as a default
933 * functions such as find() do
934 * OBJ_MULTIPLE return multiple matches
936 * OBJ_POINTER the pointer is an object pointer
937 * OBJ_KEY the pointer is to a hashable key
939 * \note When the returned object is no longer in use, ao2_ref() should
940 * be used to free the additional reference possibly created by this function.
946 #define ao2_t_callback(c, flags, cb_fn, arg, tag) \
947 __ao2_callback_debug((c), (flags), (cb_fn), (arg), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
948 #define ao2_callback(c, flags, cb_fn, arg) \
949 __ao2_callback_debug((c), (flags), (cb_fn), (arg), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
953 #define ao2_t_callback(c, flags, cb_fn, arg, tag) \
954 __ao2_callback((c), (flags), (cb_fn), (arg))
955 #define ao2_callback(c, flags, cb_fn, arg) \
956 __ao2_callback((c), (flags), (cb_fn), (arg))
960 void *__ao2_callback_debug(struct ao2_container *c, enum search_flags flags,
961 ao2_callback_fn *cb_fn, void *arg, const char *tag, char *file, int line,
962 const char *funcname);
963 void *__ao2_callback(struct ao2_container *c, enum search_flags flags, ao2_callback_fn *cb_fn, void *arg);
968 * ao2_callback_data() is a generic function that applies cb_fn() to all objects
969 * in a container. It is functionally identical to ao2_callback() except that
970 * instead of taking an ao2_callback_fn *, it takes an ao2_callback_data_fn *, and
971 * allows the caller to pass in arbitrary data.
973 * This call would be used instead of ao2_callback() when the caller needs to pass
974 * OBJ_POINTER as part of the flags argument (which in turn requires passing in a
975 * prototype ao2 object for 'arg') and also needs access to other non-global data
976 * to complete it's comparison or task.
978 * See the documentation for ao2_callback() for argument descriptions.
980 * \see ao2_callback()
984 #define ao2_t_callback_data(container, flags, cb_fn, arg, data, tag) \
985 __ao2_callback_data_debug((container), (flags), (cb_fn), (arg), (data), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
986 #define ao2_callback_data(container, flags, cb_fn, arg, data) \
987 __ao2_callback_data_debug((container), (flags), (cb_fn), (arg), (data), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
991 #define ao2_t_callback_data(container, flags, cb_fn, arg, data, tag) \
992 __ao2_callback_data((container), (flags), (cb_fn), (arg), (data))
993 #define ao2_callback_data(container, flags, cb_fn, arg, data) \
994 __ao2_callback_data((container), (flags), (cb_fn), (arg), (data))
998 void *__ao2_callback_data_debug(struct ao2_container *c, enum search_flags flags,
999 ao2_callback_data_fn *cb_fn, void *arg, void *data, const char *tag, char *file,
1000 int line, const char *funcname);
1001 void *__ao2_callback_data(struct ao2_container *c, enum search_flags flags,
1002 ao2_callback_data_fn *cb_fn, void *arg, void *data);
1004 /*! ao2_find() is a short hand for ao2_callback(c, flags, c->cmp_fn, arg)
1005 * XXX possibly change order of arguments ?
1009 #define ao2_t_find(container, arg, flags, tag) \
1010 __ao2_find_debug((container), (arg), (flags), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1011 #define ao2_find(container, arg, flags) \
1012 __ao2_find_debug((container), (arg), (flags), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1016 #define ao2_t_find(container, arg, flags, tag) \
1017 __ao2_find((container), (arg), (flags))
1018 #define ao2_find(container, arg, flags) \
1019 __ao2_find((container), (arg), (flags))
1023 void *__ao2_find_debug(struct ao2_container *c, const void *arg, enum search_flags flags,
1024 const char *tag, char *file, int line, const char *funcname);
1025 void *__ao2_find(struct ao2_container *c, const void *arg, enum search_flags flags);
1030 * When we need to walk through a container, we use an
1031 * ao2_iterator to keep track of the current position.
1033 * Because the navigation is typically done without holding the
1034 * lock on the container across the loop, objects can be inserted or deleted
1035 * or moved while we work. As a consequence, there is no guarantee that
1036 * we manage to touch all the elements in the container, and it is possible
1037 * that we touch the same object multiple times.
1039 * However, within the current hash table container, the following is true:
1040 * - It is not possible to miss an object in the container while iterating
1041 * unless it gets added after the iteration begins and is added to a bucket
1042 * that is before the one the current object is in. In this case, even if
1043 * you locked the container around the entire iteration loop, you still would
1044 * not see this object, because it would still be waiting on the container
1045 * lock so that it can be added.
1046 * - It would be extremely rare to see an object twice. The only way this can
1047 * happen is if an object got unlinked from the container and added again
1048 * during the same iteration. Furthermore, when the object gets added back,
1049 * it has to be in the current or later bucket for it to be seen again.
1051 * An iterator must be first initialized with ao2_iterator_init(),
1052 * then we can use o = ao2_iterator_next() to move from one
1053 * element to the next. Remember that the object returned by
1054 * ao2_iterator_next() has its refcount incremented,
1055 * and the reference must be explicitly released when done with it.
1057 * In addition, ao2_iterator_init() will hold a reference to the container
1058 * being iterated, which will be freed when ao2_iterator_destroy() is called
1059 * to free up the resources used by the iterator (if any).
1065 * struct ao2_container *c = ... // the container we want to iterate on
1066 * struct ao2_iterator i;
1069 * i = ao2_iterator_init(c, flags);
1071 * while ((o = ao2_iterator_next(&i))) {
1072 * ... do something on o ...
1076 * ao2_iterator_destroy(&i);
1083 * The astobj2 iterator
1085 * \note You are not supposed to know the internals of an iterator!
1086 * We would like the iterator to be opaque, unfortunately
1087 * its size needs to be known if we want to store it around
1088 * without too much trouble.
1090 * The iterator has a pointer to the container, and a flags
1091 * field specifying various things e.g. whether the container
1092 * should be locked or not while navigating on it.
1093 * The iterator "points" to the current object, which is identified
1096 * - a bucket number;
1097 * - the object_id, which is also the container version number
1098 * when the object was inserted. This identifies the object
1099 * uniquely, however reaching the desired object requires
1101 * - a pointer, and a container version when we saved the pointer.
1102 * If the container has not changed its version number, then we
1103 * can safely follow the pointer to reach the object in constant time.
1105 * Details are in the implementation of ao2_iterator_next()
1106 * A freshly-initialized iterator has bucket=0, version=0.
1108 struct ao2_iterator {
1109 /*! the container */
1110 struct ao2_container *c;
1111 /*! operation flags */
1113 /*! current bucket */
1115 /*! container version */
1116 unsigned int c_version;
1117 /*! pointer to the current object */
1119 /*! container version when the object was created */
1120 unsigned int version;
1123 /*! Flags that can be passed to ao2_iterator_init() to modify the behavior
1126 enum ao2_iterator_flags {
1127 /*! Prevents ao2_iterator_next() from locking the container
1128 * while retrieving the next object from it.
1130 AO2_ITERATOR_DONTLOCK = (1 << 0),
1131 /*! Indicates that the iterator was dynamically allocated by
1132 * astobj2 API and should be freed by ao2_iterator_destroy().
1134 AO2_ITERATOR_MALLOCD = (1 << 1),
1135 /*! Indicates that before the iterator returns an object from
1136 * the container being iterated, the object should be unlinked
1137 * from the container.
1139 AO2_ITERATOR_UNLINK = (1 << 2),
1143 * \brief Create an iterator for a container
1145 * \param c the container
1146 * \param flags one or more flags from ao2_iterator_flags
1148 * \retval the constructed iterator
1150 * \note This function does \b not take a pointer to an iterator;
1151 * rather, it returns an iterator structure that should be
1152 * assigned to (overwriting) an existing iterator structure
1153 * allocated on the stack or on the heap.
1155 * This function will take a reference on the container being iterated.
1158 struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags);
1161 * \brief Destroy a container iterator
1163 * \param i the iterator to destroy
1167 * This function will release the container reference held by the iterator
1168 * and any other resources it may be holding.
1171 void ao2_iterator_destroy(struct ao2_iterator *i);
1175 #define ao2_t_iterator_next(iter, tag) __ao2_iterator_next_debug((iter), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1176 #define ao2_iterator_next(iter) __ao2_iterator_next_debug((iter), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1180 #define ao2_t_iterator_next(iter, tag) __ao2_iterator_next((iter))
1181 #define ao2_iterator_next(iter) __ao2_iterator_next((iter))
1185 void *__ao2_iterator_next_debug(struct ao2_iterator *a, const char *tag, char *file, int line, const char *funcname);
1186 void *__ao2_iterator_next(struct ao2_iterator *a);
1188 /* extra functions */
1189 void ao2_bt(void); /* backtrace */
1191 #endif /* _ASTERISK_ASTOBJ2_H */