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/lock.h"
22 #include "asterisk/linkedlists.h"
27 * \page AstObj2 Object Model implementing objects and containers.
29 This module implements an abstraction for objects (with locks and
30 reference counts), and containers for these user-defined objects,
31 also supporting locking, reference counting and callbacks.
33 The internal implementation of objects and containers is opaque to the user,
34 so we can use different data structures as needs arise.
36 \section AstObj2_UsageObjects USAGE - OBJECTS
38 An ao2 object is a block of memory that the user code can access,
39 and for which the system keeps track (with a bit of help from the
40 programmer) of the number of references around. When an object has
41 no more references (refcount == 0), it is destroyed, by first
42 invoking whatever 'destructor' function the programmer specifies
43 (it can be NULL if none is necessary), and then freeing the memory.
44 This way objects can be shared without worrying who is in charge
46 As an additional feature, ao2 objects are associated to individual
49 Creating an object requires the size of the object and
50 a pointer to the destructor function:
54 o = ao2_alloc(sizeof(struct foo), my_destructor_fn);
56 The value returned points to the user-visible portion of the objects
57 (user-data), but is also used as an identifier for all object-related
58 operations such as refcount and lock manipulations.
60 On return from ao2_alloc():
62 - the object has a refcount = 1;
63 - the memory for the object is allocated dynamically and zeroed;
64 - we cannot realloc() the object itself;
65 - we cannot call free(o) to dispose of the object. Rather, we
66 tell the system that we do not need the reference anymore:
70 causing the destructor to be called (and then memory freed) when
71 the refcount goes to 0.
73 - ao2_ref(o, +1) can be used to modify the refcount on the
74 object in case we want to pass it around.
76 - ao2_lock(obj), ao2_unlock(obj), ao2_trylock(obj) can be used
77 to manipulate the lock associated with the object.
80 \section AstObj2_UsageContainers USAGE - CONTAINERS
82 An ao2 container is an abstract data structure where we can store
83 ao2 objects, search them (hopefully in an efficient way), and iterate
84 or apply a callback function to them. A container is just an ao2 object
87 A container must first be allocated, specifying the initial
88 parameters. At the moment, this is done as follows:
93 struct ao2_container *c;
95 c = ao2_container_alloc(MAX_BUCKETS, my_hash_fn, my_cmp_fn);
100 - MAX_BUCKETS is the number of buckets in the hash table,
101 - my_hash_fn() is the (user-supplied) function that returns a
102 hash key for the object (further reduced modulo MAX_BUCKETS
103 by the container's code);
104 - my_cmp_fn() is the default comparison function used when doing
105 searches on the container,
107 A container knows little or nothing about the objects it stores,
108 other than the fact that they have been created by ao2_alloc().
109 All knowledge of the (user-defined) internals of the objects
110 is left to the (user-supplied) functions passed as arguments
111 to ao2_container_alloc().
113 If we want to insert an object in a container, we should
114 initialize its fields -- especially, those used by my_hash_fn() --
115 to compute the bucket to use.
116 Once done, we can link an object to a container with
120 The function returns NULL in case of errors (and the object
121 is not inserted in the container). Other values mean success
122 (we are not supposed to use the value as a pointer to anything).
123 Linking an object to a container increases its refcount by 1
126 \note While an object o is in a container, we expect that
127 my_hash_fn(o) will always return the same value. The function
128 does not lock the object to be computed, so modifications of
129 those fields that affect the computation of the hash should
130 be done by extracting the object from the container, and
131 re-inserting it after the change (this is not terribly expensive).
133 \note A container with a single buckets is effectively a linked
134 list. However there is no ordering among elements.
136 - \ref AstObj2_Containers
137 - \ref astobj2.h All documentation for functions and data structures
142 \note DEBUGGING REF COUNTS BIBLE:
143 An interface to help debug refcounting is provided
144 in this package. It is dependent on the refdebug being enabled in
147 Each of the reference manipulations will generate one line of output in in the refs
148 log file. These lines look like this:
150 0x8756f00,+1,1234,chan_sip.c,22240,load_module,**constructor**,allocate users
151 0x86e3408,+1,1234,chan_sip.c,22241,load_module,**constructor**,allocate peers
152 0x86dd380,+1,1234,chan_sip.c,22242,load_module,**constructor**,allocate peers_by_ip
153 0x822d020,+1,1234,chan_sip.c,22243,load_module,**constructor**,allocate dialogs
154 0x8930fd8,+1,1234,chan_sip.c,20025,build_peer,**constructor**,allocate a peer struct
155 0x8930fd8,+1,1234,chan_sip.c,21467,reload_config,1,link peer into peer table
156 0x8930fd8,-1,1234,chan_sip.c,2370,unref_peer,2,unref_peer: from reload_config
157 0x89318b0,1,5678,chan_sip.c,20025,build_peer,**constructor**,allocate a peer struct
158 0x89318b0,+1,5678,chan_sip.c,21467,reload_config,1,link peer into peer table
159 0x89318b0,-1,1234,chan_sip.c,2370,unref_peer,2,unref_peer: from reload_config
160 0x8930218,+1,1234,chan_sip.c,20025,build_peer,**constructor**,allocate a peer struct
161 0x8930218,+1,1234,chan_sip.c,21539,reload_config,1,link peer into peers table
162 0x868c040,-1,1234,chan_sip.c,2424,dialog_unlink_all,2,unset the relatedpeer->call field in tandem with relatedpeer field itself
163 0x868c040,-1,1234,chan_sip.c,2443,dialog_unlink_all,1,Let's unbump the count in the unlink so the poor pvt can disappear if it is time
164 0x868c040,-1,1234,chan_sip.c,2443,dialog_unlink_all,**destructor**,Let's unbump the count in the unlink so the poor pvt can disappear if it is time
165 0x8cc07e8,-1,1234,chan_sip.c,2370,unref_peer,3,unsetting a dialog relatedpeer field in sip_destroy
166 0x8cc07e8,+1,1234,chan_sip.c,3876,find_peer,2,ao2_find in peers table
167 0x8cc07e8,-1,1234,chan_sip.c,2370,unref_peer,3,unref_peer, from sip_devicestate, release ref from find_peer
170 This uses a comma delineated format. The columns in the format are as
172 - The first column is the object address.
173 - The second column reflects how the operation affected the ref count
174 for that object. A change in the ref count is reflected either as
175 an increment (+) or decrement (-), as well as the amount it changed
177 - The third column is the ID of the thread that modified the reference
179 - The fourth column is the source file that the change in reference was
181 - The fifth column is the line number of the source file that the ref
182 change was issued from.
183 - The sixth column is the name of the function that the ref change was
185 - The seventh column indicates either (a) construction of the object via
186 the special tag **constructor**; (b) destruction of the object via
187 the special tag **destructor**; (c) the previous reference count
188 prior to this reference change.
189 - The eighth column is a special tag added by the developer to provide
190 context for the ref change. Note that any subsequent columns are
191 considered to be part of this tag.
193 Sometimes you have some helper functions to do object create/ref/unref
194 operations. Using these normally hides the place where these
195 functions were called. To get the location where these functions
196 were called to appear in refs log, you can do this sort of thing:
198 #define my_t_alloc(data,tag) my_alloc_debug((data), tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
199 #define my_alloc(data) my_t_alloc((data), "")
201 static struct mydata *my_alloc_debug(void *data,
202 const char *tag, const char *file, int line, const char *func)
206 p = __ao2_alloc(sizeof(*p), NULL, AO2_ALLOC_OPT_LOCK_MUTEX, tag, file, line, func);
213 To find out why objects are not destroyed (a common bug), you can
214 enable refdebug in asterisk.conf. Run asterisk, exit with "core stop gracefully".
215 This should result in every object being destroyed.
217 Then, you can "sort -k 1 {AST_LOG_DIR}/refs > x1" to get a sorted list of
218 all the objects, or you can use "contrib/script/refcounter.py" to scan
219 the file for you and output any problems it finds.
221 The above may seem astronomically more work than it is worth to debug
222 reference counts, which may be true in "simple" situations, but for
223 more complex situations, it is easily worth 100 times this effort to
226 To debug, pair all calls so that each call that increments the
227 refcount is paired with a corresponding call that decrements the
228 count for the same reason. Hopefully, you will be left with one
229 or more unpaired calls. This is where you start your search!
231 For instance, here is an example of this for a dialog object in
232 chan_sip, that was not getting destroyed, after I moved the lines around
235 0x83787a0,+1,1234,chan_sip.c,5733,sip_alloc,**constructor**,(allocate a dialog(pvt) struct)
236 0x83787a0,-1,1234,chan_sip.c,19173,sip_poke_peer,4,(unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope)
238 0x83787a0,+1,1234,chan_sip.c,5854,sip_alloc,1,(link pvt into dialogs table)
239 0x83787a0,-1,1234,chan_sip.c,19150,sip_poke_peer,3,(About to change the callid -- remove the old name)
240 0x83787a0,+1,1234,chan_sip.c,19152,sip_poke_peer,2,(Linking in under new name)
241 0x83787a0,-1,1234,chan_sip.c,2399,dialog_unlink_all,5,(unlinking dialog via ao2_unlink)
243 0x83787a0,+1,1234,chan_sip.c,19130,sip_poke_peer,2,(copy sip alloc from p to peer->call)
246 0x83787a0,+1,1234,chan_sip.c,2996,__sip_reliable_xmit,3,(__sip_reliable_xmit: setting pkt->owner)
247 0x83787a0,-1,1234,chan_sip.c,2425,dialog_unlink_all,4,(remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy)
249 0x83787a0,+1,1234,chan_sip.c,22356,unload_module,4,(iterate thru dialogs)
250 0x83787a0,-1,1234,chan_sip.c,22359,unload_module,5,(toss dialog ptr from iterator_next)
253 0x83787a0,+1,1234,chan_sip.c,22373,unload_module,3,(iterate thru dialogs)
254 0x83787a0,-1,1234,chan_sip.c,22375,unload_module,2,(throw away iterator result)
256 0x83787a0,+1,1234,chan_sip.c,2397,dialog_unlink_all,4,(Let's bump the count in the unlink so it doesn't accidentally become dead before we are done)
257 0x83787a0,-1,1234,chan_sip.c,2436,dialog_unlink_all,3,(Let's unbump the count in the unlink so the poor pvt can disappear if it is time)
259 As you can see, only one unbalanced operation is in the list, a ref count increment when
260 the peer->call was set, but no corresponding decrement was made...
262 Hopefully this helps you narrow your search and find those bugs.
264 THE ART OF REFERENCE COUNTING
266 SOME TIPS for complicated code, and ref counting:
268 1. Theoretically, passing a refcounted object pointer into a function
269 call is an act of copying the reference, and could be refcounted.
270 But, upon examination, this sort of refcounting will explode the amount
271 of code you have to enter, and for no tangible benefit, beyond
272 creating more possible failure points/bugs. It will even
273 complicate your code and make debugging harder, slow down your program
274 doing useless increments and decrements of the ref counts.
276 2. It is better to track places where a ref counted pointer
277 is copied into a structure or stored. Make sure to decrement the refcount
278 of any previous pointer that might have been there, if setting
279 this field might erase a previous pointer. ao2_find and iterate_next
280 internally increment the ref count when they return a pointer, so
281 you need to decrement the count before the pointer goes out of scope.
283 3. Any time you decrement a ref count, it may be possible that the
284 object will be destroyed (freed) immediately by that call. If you
285 are destroying a series of fields in a refcounted object, and
286 any of the unref calls might possibly result in immediate destruction,
287 you can first increment the count to prevent such behavior, then
288 after the last test, decrement the pointer to allow the object
289 to be destroyed, if the refcount would be zero.
293 dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
295 ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
297 *//* Unlink us from the owner (channel) if we have one *//*
300 ast_channel_lock(dialog->owner);
302 ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
303 dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
305 ast_channel_unlock(dialog->owner);
308 if (dialog->registry) {
309 if (dialog->registry->call == dialog) {
310 dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
312 dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
315 dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
317 In the above code, the ao2_t_unlink could end up destroying the dialog
318 object; if this happens, then the subsequent usages of the dialog
319 pointer could result in a core dump. So, we 'bump' the
320 count upwards before beginning, and then decrementing the count when
321 we are finished. This is analogous to 'locking' or 'protecting' operations
324 4. One of the most insidious problems I've run into when converting
325 code to do ref counted automatic destruction, is in the destruction
326 routines. Where a "destroy" routine had previously been called to
327 get rid of an object in non-refcounted code, the new regime demands
328 that you tear that "destroy" routine into two pieces, one that will
329 tear down the links and 'unref' them, and the other to actually free
330 and reset fields. A destroy routine that does any reference deletion
331 for its own object, will never be called. Another insidious problem
332 occurs in mutually referenced structures. As an example, a dialog contains
333 a pointer to a peer, and a peer contains a pointer to a dialog. Watch
334 out that the destruction of one doesn't depend on the destruction of the
335 other, as in this case a dependency loop will result in neither being
338 Given the above, you should be ready to do a good job!
347 * \brief Typedef for an object destructor.
349 * \param vdoomed Object to destroy.
352 * This is called just before freeing the memory for the object.
353 * It is passed a pointer to the user-defined data of the
358 typedef void (*ao2_destructor_fn)(void *vdoomed);
360 /*! \brief Options available when allocating an ao2 object. */
361 enum ao2_alloc_opts {
362 /*! The ao2 object has a recursive mutex lock associated with it. */
363 AO2_ALLOC_OPT_LOCK_MUTEX = (0 << 0),
364 /*! The ao2 object has a non-recursive read/write lock associated with it. */
365 AO2_ALLOC_OPT_LOCK_RWLOCK = (1 << 0),
366 /*! The ao2 object has no lock associated with it. */
367 AO2_ALLOC_OPT_LOCK_NOLOCK = (2 << 0),
368 /*! The ao2 object locking option field mask. */
369 AO2_ALLOC_OPT_LOCK_MASK = (3 << 0),
373 * \brief Allocate and initialize an object.
375 * \param data_size The sizeof() of the user-defined structure.
376 * \param destructor_fn The destructor function (can be NULL)
377 * \param options The ao2 object options (See enum ao2_alloc_opts)
378 * \param debug_msg An ao2 object debug tracing message.
379 * \return A pointer to user-data.
382 * Allocates a struct astobj2 with sufficient space for the
383 * user-defined structure.
385 * - storage is zeroed; XXX maybe we want a flag to enable/disable this.
386 * - the refcount of the object just created is 1
387 * - the returned pointer cannot be free()'d or realloc()'ed;
388 * rather, we just call ao2_ref(o, -1);
390 * \note refdebug logging is skipped if debug_msg is NULL
395 #define ao2_t_alloc_options(data_size, destructor_fn, options, debug_msg) \
396 __ao2_alloc((data_size), (destructor_fn), (options), (debug_msg), __FILE__, __LINE__, __PRETTY_FUNCTION__)
397 #define ao2_alloc_options(data_size, destructor_fn, options) \
398 __ao2_alloc((data_size), (destructor_fn), (options), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
400 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
401 __ao2_alloc((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, (debug_msg), __FILE__, __LINE__, __PRETTY_FUNCTION__)
402 #define ao2_alloc(data_size, destructor_fn) \
403 __ao2_alloc((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
405 void *__ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn, unsigned int options,
406 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
411 * Reference/unreference an object and return the old refcount.
413 * \param o A pointer to the object
414 * \param delta Value to add to the reference counter.
415 * \param tag used for debugging
416 * \return The value of the reference counter before the operation.
418 * Increase/decrease the reference counter according
419 * the value of delta.
421 * If the refcount goes to zero, the object is destroyed.
423 * \note The object must not be locked by the caller of this function, as
424 * it is invalid to try to unlock it after releasing the reference.
426 * \note if we know the pointer to an object, it is because we
427 * have a reference count to it, so the only case when the object
428 * can go away is when we release our reference, and it is
429 * the last one in existence.
431 * \note refdebug logging is skipped if tag is NULL
435 #define ao2_t_ref(o,delta,tag) __ao2_ref((o), (delta), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
436 #define ao2_ref(o,delta) __ao2_ref((o), (delta), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
439 * \brief Retrieve the ao2 options used to create the object.
440 * \param obj pointer to the (user-defined part) of an object.
441 * \return options from enum ao2_alloc_opts.
443 unsigned int ao2_options_get(void *obj);
447 * \brief Bump refcount on an AO2 object by one, returning the object.
449 * This is useful for inlining a ref bump, and you don't care about the ref
450 * count. Also \c NULL safe, for even more convenience.
452 * \param obj AO2 object to bump the refcount on.
453 * \retval The given \a obj pointer.
455 #define ao2_t_bump(obj, tag) \
457 typeof(obj) __obj_ ## __LINE__ = (obj); \
458 if (__obj_ ## __LINE__) { \
459 ao2_t_ref(__obj_ ## __LINE__, +1, (tag)); \
461 __obj_ ## __LINE__; \
463 #define ao2_bump(obj) \
464 ao2_t_bump((obj), "")
466 int __ao2_ref(void *o, int delta, const char *tag, const char *file, int line, const char *func);
470 * \brief Replace one object reference with another cleaning up the original.
472 * \param dst Pointer to the object that will be cleaned up.
473 * \param src Pointer to the object replacing it.
475 #define ao2_t_replace(dst, src, tag) \
477 typeof(dst) *__dst_ ## __LINE__ = &dst; \
478 typeof(src) __src_ ## __LINE__ = src; \
479 if (__src_ ## __LINE__ != *__dst_ ## __LINE__) { \
480 if (__src_ ## __LINE__) {\
481 ao2_t_ref(__src_ ## __LINE__, +1, (tag)); \
483 if (*__dst_ ## __LINE__) {\
484 ao2_t_ref(*__dst_ ## __LINE__, -1, (tag)); \
486 *__dst_ ## __LINE__ = __src_ ## __LINE__; \
489 #define ao2_replace(dst, src) \
490 ao2_t_replace((dst), (src), "")
494 /*! \brief ao2_weakproxy
498 struct ao2_weakproxy_notification;
499 typedef void (*ao2_weakproxy_notification_cb)(void *weakproxy, void *data);
501 /*! \brief This struct should be opaque, but it's size is needed. */
502 struct ao2_weakproxy {
503 AST_LIST_HEAD_NOLOCK(, ao2_weakproxy_notification) destroyed_cb;
506 /*! \brief Macro which must be used at the beginning of weakproxy capable objects.
508 * \note The primary purpose of user defined fields on weakproxy objects is to hold
509 * immutable container keys for the real object.
511 #define AO2_WEAKPROXY() struct ao2_weakproxy __weakproxy##__LINE__
515 * \brief Allocate an ao2_weakproxy object
517 * \param data_size The sizeof() of the user-defined structure.
518 * \param destructor_fn The destructor function (can be NULL)
520 * \note "struct ao2_weakproxy" must be the first field of any object.
521 * This can be done by using AO2_WEAKPROXY to declare your structure.
523 void *__ao2_weakproxy_alloc(size_t data_size, ao2_destructor_fn destructor_fn,
524 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
526 #define ao2_weakproxy_alloc(data_size, destructor_fn) \
527 __ao2_weakproxy_alloc(data_size, destructor_fn, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
529 #define ao2_t_weakproxy_alloc(data_size, destructor_fn, tag) \
530 __ao2_weakproxy_alloc(data_size, destructor_fn, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
534 * \brief Associate weakproxy with obj.
536 * \param weakproxy An object created by ao2_weakproxy_alloc.
537 * \param obj An ao2 object not created by ao2_weakproxy_alloc.
538 * \param flags OBJ_NOLOCK to avoid locking weakproxy.
543 * \note obj must be newly created, this procedure is not thread safe
544 * if any other code can reach obj before this procedure ends.
546 * \note weakproxy may be previously existing, but must not currently
547 * have an object set.
549 * \note The only way to unset an object is for it to be destroyed.
550 * Any call to this function while an object is already set will fail.
552 int __ao2_weakproxy_set_object(void *weakproxy, void *obj, int flags,
553 const char *tag, const char *file, int line, const char *func);
555 #define ao2_weakproxy_set_object(weakproxy, obj, flags) \
556 __ao2_weakproxy_set_object(weakproxy, obj, flags, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
558 #define ao2_t_weakproxy_set_object(weakproxy, obj, flags, tag) \
559 __ao2_weakproxy_set_object(weakproxy, obj, flags, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
563 * \brief Run ao2_t_ref on the object associated with weakproxy.
565 * \param weakproxy The weakproxy to read from.
566 * \param delta Value to add to the reference counter.
567 * \param flags OBJ_NOLOCK to avoid locking weakproxy.
569 * \retval -2 weakproxy is not a valid ao2_weakproxy.
570 * \retval -1 weakproxy has no associated object.
572 * \return The value of the reference counter before the operation.
574 int __ao2_weakproxy_ref_object(void *weakproxy, int delta, int flags,
575 const char *tag, const char *file, int line, const char *func);
577 #define ao2_t_weakproxy_ref_object(weakproxy, delta, flags, tag) \
578 __ao2_weakproxy_ref_object(weakproxy, delta, flags, \
579 tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
581 #define ao2_weakproxy_ref_object(weakproxy, delta, flags) \
582 ao2_t_weakproxy_ref_object(weakproxy, delta, flags, "")
586 * \brief Get the object associated with weakproxy.
588 * \param weakproxy The weakproxy to read from.
589 * \param flags OBJ_NOLOCK to avoid locking weakproxy.
591 * \return A reference to the object previously set by ao2_weakproxy_set_object.
592 * \retval NULL Either no object was set or the previously set object has been freed.
594 void *__ao2_weakproxy_get_object(void *weakproxy, int flags,
595 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
597 #define ao2_weakproxy_get_object(weakproxy, flags) \
598 __ao2_weakproxy_get_object(weakproxy, flags, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
600 #define ao2_t_weakproxy_get_object(weakproxy, flags, tag) \
601 __ao2_weakproxy_get_object(weakproxy, flags, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
605 * \brief Request notification when weakproxy points to NULL.
607 * \param weakproxy The weak object
608 * \param cb Procedure to call when no real object is associated
609 * \param data Passed to cb
610 * \param flags OBJ_NOLOCK to avoid locking weakproxy.
615 * \note Callbacks are run in the reverse order of subscriptions.
617 * \note This procedure will allow the same cb / data pair to be added to
618 * the same weakproxy multiple times.
620 * \note It is the caller's responsibility to ensure that *data is valid
621 * until after cb() is run or ao2_weakproxy_unsubscribe is called.
623 * \note If the weakproxy currently points to NULL the callback will be run immediately,
624 * without being added to the subscriber list.
626 int ao2_weakproxy_subscribe(void *weakproxy, ao2_weakproxy_notification_cb cb, void *data, int flags);
630 * \brief Remove notification of real object destruction.
632 * \param weakproxy The weak object
633 * \param cb Callback to remove from destroy notification list
634 * \param data Data pointer to match
635 * \param flags OBJ_NOLOCK to avoid locking weakproxy.
636 * OBJ_MULTIPLE to remove all copies of the same cb / data pair.
638 * \return The number of subscriptions removed.
639 * \retval 0 cb / data pair not found, nothing removed.
640 * \retval -1 Failure due to invalid parameters.
642 * \note Unless flags includes OBJ_MULTIPLE, this will only remove a single copy
643 * of the cb / data pair. If it was subscribed multiple times it must be
644 * unsubscribed as many times. The OBJ_MULTIPLE flag can be used to remove
645 * matching subscriptions.
647 int ao2_weakproxy_unsubscribe(void *weakproxy, ao2_weakproxy_notification_cb cb, void *data, int flags);
651 * \brief Get the weakproxy attached to obj
653 * \param obj The object to retreive a weakproxy from
655 * \return The weakproxy object
657 void *__ao2_get_weakproxy(void *obj,
658 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
660 #define ao2_get_weakproxy(obj) \
661 __ao2_get_weakproxy(obj, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
663 #define ao2_t_get_weakproxy(obj, tag) \
664 __ao2_get_weakproxy(obj, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
668 /*! \brief Which lock to request. */
670 /*! Request the mutex lock be acquired. */
672 /*! Request the read lock be acquired. */
674 /*! Request the write lock be acquired. */
681 * \param a A pointer to the object we want to lock.
682 * \param lock_how, file, func, line, var
683 * \return 0 on success, other values on error.
685 int __ao2_lock(void *a, enum ao2_lock_req lock_how, const char *file, const char *func, int line, const char *var);
686 #define ao2_lock(a) __ao2_lock(a, AO2_LOCK_REQ_MUTEX, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
687 #define ao2_rdlock(a) __ao2_lock(a, AO2_LOCK_REQ_RDLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
688 #define ao2_wrlock(a) __ao2_lock(a, AO2_LOCK_REQ_WRLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
693 * \param a A pointer to the object we want unlock.
694 * \param file, func, line, var
695 * \return 0 on success, other values on error.
697 int __ao2_unlock(void *a, const char *file, const char *func, int line, const char *var);
698 #define ao2_unlock(a) __ao2_unlock(a, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
701 * Try locking-- (don't block if fail)
703 * \param a A pointer to the object we want to lock.
704 * \param lock_how, file, func, line, var
705 * \return 0 on success, other values on error.
707 int __ao2_trylock(void *a, enum ao2_lock_req lock_how, const char *file, const char *func, int line, const char *var);
708 #define ao2_trylock(a) __ao2_trylock(a, AO2_LOCK_REQ_MUTEX, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
709 #define ao2_tryrdlock(a) __ao2_trylock(a, AO2_LOCK_REQ_RDLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
710 #define ao2_trywrlock(a) __ao2_trylock(a, AO2_LOCK_REQ_WRLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
713 * \brief Return the mutex lock address of an object
715 * \param[in] obj A pointer to the object we want.
716 * \return the address of the mutex lock, else NULL.
718 * This function comes in handy mainly for debugging locking
719 * situations, where the locking trace code reports the
720 * lock address, this allows you to correlate against
721 * object address, to match objects to reported locks.
725 void *ao2_object_get_lockaddr(void *obj);
728 /*! Global ao2 object holder structure. */
729 struct ao2_global_obj {
730 /*! Access lock to the held ao2 object. */
732 /*! Global ao2 object. */
737 * \brief Define a global object holder to be used to hold an ao2 object, statically initialized.
740 * \param name This will be the name of the object holder.
743 * This macro creates a global object holder that can be used to
744 * hold an ao2 object accessible using the API. The structure is
745 * allocated and initialized to be empty.
749 * static AO2_GLOBAL_OBJ_STATIC(global_cfg);
752 * This defines global_cfg, intended to hold an ao2 object
753 * accessible using an API.
755 #ifndef HAVE_PTHREAD_RWLOCK_INITIALIZER
756 #define AO2_GLOBAL_OBJ_STATIC(name) \
757 struct ao2_global_obj name; \
758 static void __attribute__((constructor)) __init_##name(void) \
760 ast_rwlock_init(&name.lock); \
763 static void __attribute__((destructor)) __fini_##name(void) \
766 ao2_ref(name.obj, -1); \
769 ast_rwlock_destroy(&name.lock); \
771 struct __dummy_##name
773 #define AO2_GLOBAL_OBJ_STATIC(name) \
774 struct ao2_global_obj name = { \
775 .lock = AST_RWLOCK_INIT_VALUE, \
780 * \brief Release the ao2 object held in the global holder.
783 * \param holder Global ao2 object holder.
784 * \param tag used for debugging
788 #define ao2_t_global_obj_release(holder, tag) \
789 __ao2_global_obj_release(&holder, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
790 #define ao2_global_obj_release(holder) \
791 __ao2_global_obj_release(&holder, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
793 void __ao2_global_obj_release(struct ao2_global_obj *holder, const char *tag, const char *file, int line, const char *func, const char *name);
796 * \brief Replace an ao2 object in the global holder.
799 * \param holder Global ao2 object holder.
800 * \param obj Object to put into the holder. Can be NULL.
801 * \param tag used for debugging
803 * \note This function automatically increases the reference
804 * count to account for the reference that the global holder now
805 * holds to the object.
807 * \retval Reference to previous global ao2 object stored.
808 * \retval NULL if no object available.
810 #define ao2_t_global_obj_replace(holder, obj, tag) \
811 __ao2_global_obj_replace(&holder, (obj), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
812 #define ao2_global_obj_replace(holder, obj) \
813 __ao2_global_obj_replace(&holder, (obj), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
815 void *__ao2_global_obj_replace(struct ao2_global_obj *holder, void *obj, const char *tag, const char *file, int line, const char *func, const char *name) attribute_warn_unused_result;
818 * \brief Replace an ao2 object in the global holder, throwing away any old object.
821 * \param holder Global ao2 object holder.
822 * \param obj Object to put into the holder. Can be NULL.
823 * \param tag used for debugging
825 * \note This function automatically increases the reference
826 * count to account for the reference that the global holder now
827 * holds to the object. It also decreases the reference count
828 * of any object being replaced.
830 * \retval 0 The global object was previously empty
831 * \retval 1 The global object was not previously empty
833 #define ao2_t_global_obj_replace_unref(holder, obj, tag) \
834 __ao2_global_obj_replace_unref(&holder, (obj), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
835 #define ao2_global_obj_replace_unref(holder, obj) \
836 __ao2_global_obj_replace_unref(&holder, (obj), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
838 int __ao2_global_obj_replace_unref(struct ao2_global_obj *holder, void *obj, const char *tag, const char *file, int line, const char *func, const char *name);
841 * \brief Get a reference to the object stored in the global holder.
844 * \param holder Global ao2 object holder.
845 * \param tag used for debugging
847 * \retval Reference to current ao2 object stored in the holder.
848 * \retval NULL if no object available.
850 #define ao2_t_global_obj_ref(holder, tag) \
851 __ao2_global_obj_ref(&holder, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
852 #define ao2_global_obj_ref(holder) \
853 __ao2_global_obj_ref(&holder, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
855 void *__ao2_global_obj_ref(struct ao2_global_obj *holder, const char *tag, const char *file, int line, const char *func, const char *name) attribute_warn_unused_result;
859 \page AstObj2_Containers AstObj2 Containers
861 Containers are data structures meant to store several objects,
862 and perform various operations on them.
863 Internally, objects are stored in lists, hash tables or other
864 data structures depending on the needs.
866 \note NOTA BENE: at the moment the only container we support is the
867 hash table and its degenerate form, the list.
869 Operations on container include:
871 - c = \b ao2_container_alloc(size, hash_fn, cmp_fn)
872 allocate a container with desired size and default compare
874 -The compare function returns an int, which
875 can be 0 for not found, CMP_STOP to stop end a traversal,
876 or CMP_MATCH if they are equal
877 -The hash function returns an int. The hash function
878 takes two argument, the object pointer and a flags field,
880 - \b ao2_find(c, arg, flags)
881 returns zero or more elements matching a given criteria
882 (specified as arg). 'c' is the container pointer. Flags
884 OBJ_UNLINK - to remove the object, once found, from the container.
885 OBJ_NODATA - don't return the object if found (no ref count change)
886 OBJ_MULTIPLE - don't stop at first match
887 OBJ_SEARCH_OBJECT - if set, 'arg' is an object pointer, and a hash table
888 search will be done. If not, a traversal is done.
889 OBJ_SEARCH_KEY - if set, 'arg', is a search key item that is not an object.
890 Similar to OBJ_SEARCH_OBJECT and mutually exclusive.
891 OBJ_SEARCH_PARTIAL_KEY - if set, 'arg', is a partial search key item that is not an object.
892 Similar to OBJ_SEARCH_KEY and mutually exclusive.
894 - \b ao2_callback(c, flags, fn, arg)
895 apply fn(obj, arg) to all objects in the container.
896 Similar to find. fn() can tell when to stop, and
897 do anything with the object including unlinking it.
898 - c is the container;
900 OBJ_UNLINK - to remove the object, once found, from the container.
901 OBJ_NODATA - don't return the object if found (no ref count change)
902 OBJ_MULTIPLE - don't stop at first match
903 OBJ_SEARCH_OBJECT - if set, 'arg' is an object pointer, and a hash table
904 search will be done. If not, a traversal is done through
905 all the hash table 'buckets'..
906 OBJ_SEARCH_KEY - if set, 'arg', is a search key item that is not an object.
907 Similar to OBJ_SEARCH_OBJECT and mutually exclusive.
908 OBJ_SEARCH_PARTIAL_KEY - if set, 'arg', is a partial search key item that is not an object.
909 Similar to OBJ_SEARCH_KEY and mutually exclusive.
910 - fn is a func that returns int, and takes 3 args:
911 (void *obj, void *arg, int flags);
913 arg is the same as arg passed into ao2_callback
914 flags is the same as flags passed into ao2_callback
916 0: no match, keep going
917 CMP_STOP: stop search, no match
918 CMP_MATCH: This object is matched.
920 Note that the entire operation is run with the container
921 locked, so nobody else can change its content while we work on it.
922 However, we pay this with the fact that doing
923 anything blocking in the callback keeps the container
925 The mechanism is very flexible because the callback function fn()
926 can do basically anything e.g. counting, deleting records, etc.
927 possibly using arg to store the results.
929 - \b iterate on a container
930 this is done with the following sequence
934 struct ao2_container *c = ... // our container
935 struct ao2_iterator i;
938 i = ao2_iterator_init(c, flags);
940 while ((o = ao2_iterator_next(&i))) {
941 ... do something on o ...
945 ao2_iterator_destroy(&i);
948 The difference with the callback is that the control
949 on how to iterate is left to us.
952 dropping a reference to a container destroys it, very simple!
954 Containers are ao2 objects themselves, and this is why their
955 implementation is simple too.
957 Before declaring containers, we need to declare the types of the
958 arguments passed to the constructor - in turn, this requires
959 to define callback and hash functions and their arguments.
966 * A callback function will return a combination of CMP_MATCH and CMP_STOP.
967 * The latter will terminate the search in a container.
970 CMP_MATCH = 0x1, /*!< the object matches the request */
971 CMP_STOP = 0x2, /*!< stop the search now */
975 * \brief Flags passed to ao2_callback_fn(), ao2_hash_fn(), and ao2_sort_fn() to modify behaviour.
979 * Unlink the object for which the callback function returned
982 OBJ_UNLINK = (1 << 0),
984 * On match, don't return the object hence do not increase its
987 OBJ_NODATA = (1 << 1),
989 * Don't stop at the first match in ao2_callback() unless the
990 * result of of the callback function has the CMP_STOP bit set.
992 OBJ_MULTIPLE = (1 << 2),
994 * \brief Assume that the ao2_container is already locked.
996 * \note For ao2_containers that have mutexes, no locking will
999 * \note For ao2_containers that have RWLOCKs, the lock will be
1000 * promoted to write mode as needed. The lock will be returned
1001 * to the original locked state.
1003 * \note Only use this flag if the ao2_container is manually
1006 OBJ_NOLOCK = (1 << 4),
1009 * \brief Search option field mask.
1011 * \todo Eventually OBJ_SEARCH_MASK will shrink to a two bit
1012 * field when the codebase is made to use the search field
1013 * values as a field instead of independent bits.
1015 OBJ_SEARCH_MASK = (0x07 << 5),
1016 /*! \brief The arg parameter has no meaning to the astobj2 code. */
1017 OBJ_SEARCH_NONE = (0 << 5),
1019 * \brief The arg parameter is an object of the same type.
1022 * The arg parameter is an object of the same type as the one
1023 * being searched for, so use the object's ao2_hash_fn and/or
1024 * ao2_sort_fn functions for optimized searching.
1026 * \note The supplied ao2_callback_fn is called after the
1027 * container nodes have been filtered by the ao2_hash_fn and/or
1028 * ao2_sort_fn functions.
1030 OBJ_SEARCH_OBJECT = (1 << 5),
1032 * \brief The arg parameter is a search key, but is not an object.
1035 * This can be used when you want to be able to pass custom data
1036 * to the container's stored ao2_hash_fn, ao2_sort_fn, and
1037 * ao2_find ao2_callback_fn functions that is not a full object,
1038 * but perhaps just a string.
1040 * \note The supplied ao2_callback_fn is called after the
1041 * container nodes have been filtered by the ao2_hash_fn and/or
1042 * ao2_sort_fn functions.
1044 OBJ_SEARCH_KEY = (2 << 5),
1046 * \brief The arg parameter is a partial search key similar to OBJ_SEARCH_KEY.
1049 * The partial key can be used by the ao2_sort_fn to guide the
1050 * search to find a contiguous subset of a sorted container.
1051 * For example, a sorted container holds: "A", "B", "Bert",
1052 * "Beth", "Earnie". Doing a partial key search with "B" will
1053 * find the sorted subset of all held objects starting with "B".
1055 * \note The supplied ao2_callback_fn is called after the
1056 * container nodes have been filtered by the ao2_sort_fn
1059 OBJ_SEARCH_PARTIAL_KEY = (4 << 5),
1061 /*! \brief Traverse order option field mask. */
1062 OBJ_ORDER_MASK = (0x03 << 8),
1063 /*! \brief Traverse in ascending order (First to last container object) */
1064 OBJ_ORDER_ASCENDING = (0 << 8),
1065 /*! \brief Traverse in descending order (Last to first container object) */
1066 OBJ_ORDER_DESCENDING = (1 << 8),
1068 * \brief Traverse in pre-order (Node then children, for tree container)
1070 * \note For non-tree containers, it is up to the container type
1071 * to make the best interpretation of the order. For list and
1072 * hash containers, this also means ascending order because a
1073 * binary tree can degenerate into a list.
1075 OBJ_ORDER_PRE = (2 << 8),
1077 * \brief Traverse in post-order (Children then node, for tree container)
1079 * \note For non-tree containers, it is up to the container type
1080 * to make the best interpretation of the order. For list and
1081 * hash containers, this also means descending order because a
1082 * binary tree can degenerate into a list.
1084 OBJ_ORDER_POST = (3 << 8),
1088 * Deprecated backward compatible flag names.
1090 * Note: OBJ_POINTER, OBJ_KEY, and OBJ_PARTIAL_KEY are mutually
1093 #define OBJ_POINTER OBJ_SEARCH_OBJECT /*!< Deprecated name */
1094 #define OBJ_KEY OBJ_SEARCH_KEY /*!< Deprecated name */
1095 #define OBJ_PARTIAL_KEY OBJ_SEARCH_PARTIAL_KEY /*!< Deprecated name */
1098 * \brief Options available when allocating an ao2 container object.
1100 * \note Each option is open to some interpretation by the
1101 * container type as long as it makes sense with the option
1104 enum ao2_container_opts {
1106 * \brief Insert objects at the beginning of the container.
1107 * (Otherwise it is the opposite; insert at the end.)
1109 * \note If an ao2_sort_fn is provided, the object is inserted
1110 * before any objects with duplicate keys.
1112 * \note Hash containers insert the object in the computed hash
1113 * bucket in the indicated manner.
1115 AO2_CONTAINER_ALLOC_OPT_INSERT_BEGIN = (1 << 0),
1118 * \brief The ao2 container objects with duplicate keys option field mask.
1120 AO2_CONTAINER_ALLOC_OPT_DUPS_MASK = (3 << 1),
1122 * \brief Allow objects with duplicate keys in container.
1124 AO2_CONTAINER_ALLOC_OPT_DUPS_ALLOW = (0 << 1),
1126 * \brief Reject objects with duplicate keys in container.
1128 * \note The container must be sorted. i.e. have an
1131 AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT = (1 << 1),
1133 * \brief Reject duplicate objects in container.
1135 * \details Don't link the same object into the container twice.
1136 * However, you can link a different object with the same key.
1138 * \note The container must be sorted. i.e. have an
1141 * \note It is assumed that the objects are located where the
1142 * search key says they should be located.
1144 AO2_CONTAINER_ALLOC_OPT_DUPS_OBJ_REJECT = (2 << 1),
1146 * \brief Replace objects with duplicate keys in container.
1148 * \details The existing duplicate object is removed and the new
1149 * object takes the old object's place.
1151 * \note The container must be sorted. i.e. have an
1154 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE = (3 << 1),
1158 * \brief Type of a generic callback function
1159 * \param obj pointer to the (user-defined part) of an object.
1160 * \param arg callback argument from ao2_callback()
1161 * \param flags flags from ao2_callback()
1162 * OBJ_SEARCH_OBJECT - if set, 'arg', is an object.
1163 * OBJ_SEARCH_KEY - if set, 'arg', is a search key item that is not an object.
1164 * OBJ_SEARCH_PARTIAL_KEY - if set, 'arg', is a partial search key item that is not an object.
1166 * The return values are a combination of enum _cb_results.
1167 * Callback functions are used to search or manipulate objects in a container.
1169 typedef int (ao2_callback_fn)(void *obj, void *arg, int flags);
1171 /*! \brief A common ao2_callback is one that matches by address. */
1172 int ao2_match_by_addr(void *obj, void *arg, int flags);
1175 * \brief Type of a generic callback function
1176 * \param obj pointer to the (user-defined part) of an object.
1177 * \param arg callback argument from ao2_callback()
1178 * \param data arbitrary data from ao2_callback()
1179 * \param flags flags from ao2_callback()
1180 * OBJ_SEARCH_OBJECT - if set, 'arg', is an object.
1181 * OBJ_SEARCH_KEY - if set, 'arg', is a search key item that is not an object.
1182 * OBJ_SEARCH_PARTIAL_KEY - if set, 'arg', is a partial search key item that is not an object.
1184 * The return values are a combination of enum _cb_results.
1185 * Callback functions are used to search or manipulate objects in a container.
1187 typedef int (ao2_callback_data_fn)(void *obj, void *arg, void *data, int flags);
1190 * Type of a generic function to generate a hash value from an object.
1192 * \param obj pointer to the (user-defined part) of an object.
1193 * \param flags flags from ao2_callback()
1194 * OBJ_SEARCH_OBJECT - if set, 'obj', is an object.
1195 * OBJ_SEARCH_KEY - if set, 'obj', is a search key item that is not an object.
1197 * \note This function must be idempotent.
1199 * \return Computed hash value.
1201 typedef int (ao2_hash_fn)(const void *obj, int flags);
1204 * \brief Type of generic container sort function.
1206 * \param obj_left pointer to the (user-defined part) of an object.
1207 * \param obj_right pointer to the (user-defined part) of an object.
1208 * \param flags flags from ao2_callback()
1209 * OBJ_SEARCH_OBJECT - if set, 'obj_right', is an object.
1210 * OBJ_SEARCH_KEY - if set, 'obj_right', is a search key item that is not an object.
1211 * OBJ_SEARCH_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
1213 * \note This function must be idempotent.
1215 * \retval <0 if obj_left < obj_right
1216 * \retval =0 if obj_left == obj_right
1217 * \retval >0 if obj_left > obj_right
1219 typedef int (ao2_sort_fn)(const void *obj_left, const void *obj_right, int flags);
1221 /*! \name Object Containers
1222 * Here start declarations of containers.
1225 struct ao2_container;
1228 * \brief Allocate and initialize a hash container with the desired number of buckets.
1231 * We allocate space for a struct astobj_container, struct container
1232 * and the buckets[] array.
1234 * \param options Container ao2 object options (See enum ao2_alloc_opts)
1235 * \param n_buckets Number of buckets for hash
1236 * \param hash_fn Pointer to a function computing a hash value. (NULL if everyting goes in first bucket.)
1237 * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
1238 * \param tag used for debugging.
1240 * \return A pointer to a struct container.
1242 * \note Destructor is set implicitly.
1243 * \note This is legacy container creation that is mapped to the new method.
1246 #define ao2_t_container_alloc_options(options, n_buckets, hash_fn, cmp_fn, tag) \
1247 ao2_t_container_alloc_hash((options), 0, (n_buckets), (hash_fn), NULL, (cmp_fn), (tag))
1248 #define ao2_container_alloc_options(options, n_buckets, hash_fn, cmp_fn) \
1249 ao2_container_alloc_hash((options), 0, (n_buckets), (hash_fn), NULL, (cmp_fn))
1251 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
1252 ao2_t_container_alloc_options(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn), (tag))
1253 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
1254 ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn))
1257 * \brief Allocate and initialize a hash container with the desired number of buckets.
1260 * We allocate space for a struct astobj_container, struct container
1261 * and the buckets[] array.
1263 * \param ao2_options Container ao2 object options (See enum ao2_alloc_opts)
1264 * \param container_options Container behaviour options (See enum ao2_container_opts)
1265 * \param n_buckets Number of buckets for hash
1266 * \param hash_fn Pointer to a function computing a hash value. (NULL if everyting goes in first bucket.)
1267 * \param sort_fn Pointer to a sort function. (NULL to not sort the buckets.)
1268 * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
1269 * \param tag used for debugging.
1271 * \return A pointer to a struct container.
1273 * \note Destructor is set implicitly.
1276 #define ao2_t_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn, tag) \
1277 __ao2_container_alloc_hash((ao2_options), (container_options), (n_buckets), (hash_fn), (sort_fn), (cmp_fn), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1278 #define ao2_container_alloc_hash(ao2_options, container_options, n_buckets, hash_fn, sort_fn, cmp_fn) \
1279 __ao2_container_alloc_hash((ao2_options), (container_options), (n_buckets), (hash_fn), (sort_fn), (cmp_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1281 struct ao2_container *__ao2_container_alloc_hash(unsigned int ao2_options,
1282 unsigned int container_options, unsigned int n_buckets, ao2_hash_fn *hash_fn,
1283 ao2_sort_fn *sort_fn, ao2_callback_fn *cmp_fn,
1284 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
1287 * \brief Allocate and initialize a list container.
1289 * \param ao2_options Container ao2 object options (See enum ao2_alloc_opts)
1290 * \param container_options Container behaviour options (See enum ao2_container_opts)
1291 * \param sort_fn Pointer to a sort function. (NULL if list not sorted.)
1292 * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
1293 * \param tag used for debugging.
1295 * \return A pointer to a struct container.
1297 * \note Destructor is set implicitly.
1298 * \note Implemented as a degenerate hash table.
1301 #define ao2_t_container_alloc_list(ao2_options, container_options, sort_fn, cmp_fn, tag) \
1302 __ao2_container_alloc_list((ao2_options), (container_options), (sort_fn), (cmp_fn), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1303 #define ao2_container_alloc_list(ao2_options, container_options, sort_fn, cmp_fn) \
1304 __ao2_container_alloc_list((ao2_options), (container_options), (sort_fn), (cmp_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1306 struct ao2_container *__ao2_container_alloc_list(unsigned int ao2_options,
1307 unsigned int container_options, ao2_sort_fn *sort_fn, ao2_callback_fn *cmp_fn,
1308 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
1311 * \brief Allocate and initialize a red-black tree container.
1313 * \param ao2_options Container ao2 object options (See enum ao2_alloc_opts)
1314 * \param container_options Container behaviour options (See enum ao2_container_opts)
1315 * \param sort_fn Pointer to a sort function.
1316 * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
1317 * \param tag used for debugging.
1319 * \return A pointer to a struct container.
1321 * \note Destructor is set implicitly.
1324 #define ao2_t_container_alloc_rbtree(ao2_options, container_options, sort_fn, cmp_fn, tag) \
1325 __ao2_container_alloc_rbtree((ao2_options), (container_options), (sort_fn), (cmp_fn), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1326 #define ao2_container_alloc_rbtree(ao2_options, container_options, sort_fn, cmp_fn) \
1327 __ao2_container_alloc_rbtree((ao2_options), (container_options), (sort_fn), (cmp_fn), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1329 struct ao2_container *__ao2_container_alloc_rbtree(unsigned int ao2_options, unsigned int container_options,
1330 ao2_sort_fn *sort_fn, ao2_callback_fn *cmp_fn,
1331 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
1334 * Returns the number of elements in a container.
1336 int ao2_container_count(struct ao2_container *c);
1339 * \brief Copy all object references in the src container into the dest container.
1342 * \param dest Container to copy src object references into.
1343 * \param src Container to copy all object references from.
1344 * \param flags OBJ_NOLOCK if a lock is already held on both containers.
1345 * Otherwise, the src container is locked first.
1347 * \pre The dest container must be empty. If the duplication fails, the
1348 * dest container will be returned empty.
1350 * \note This can potentially be expensive because a malloc is
1351 * needed for every object in the src container.
1353 * \retval 0 on success.
1354 * \retval -1 on error.
1356 int ao2_container_dup(struct ao2_container *dest, struct ao2_container *src, enum search_flags flags);
1359 * \brief Create a clone/copy of the given container.
1362 * \param orig Container to copy all object references from.
1363 * \param flags OBJ_NOLOCK if a lock is already held on the container.
1365 * \note This can potentially be expensive because a malloc is
1366 * needed for every object in the orig container.
1368 * \retval Clone container on success.
1369 * \retval NULL on error.
1371 struct ao2_container *__ao2_container_clone(struct ao2_container *orig, enum search_flags flags,
1372 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
1374 #define ao2_t_container_clone(orig, flags, tag) \
1375 __ao2_container_clone(orig, flags, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1376 #define ao2_container_clone(orig, flags) \
1377 __ao2_container_clone(orig, flags, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1380 * \brief Print output.
1383 * \param where User data pointer needed to determine where to put output.
1384 * \param fmt printf type format string.
1388 typedef void (ao2_prnt_fn)(void *where, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
1391 * \brief Print object key.
1394 * \param v_obj A pointer to the object we want the key printed.
1395 * \param where User data needed by prnt to determine where to put output.
1396 * \param prnt Print output callback function to use.
1400 typedef void (ao2_prnt_obj_fn)(void *v_obj, void *where, ao2_prnt_fn *prnt);
1403 * \brief Display contents of the specified container.
1406 * \param self Container to dump.
1407 * \param flags OBJ_NOLOCK if a lock is already held on the container.
1408 * \param name Container name. (NULL if anonymous)
1409 * \param where User data needed by prnt to determine where to put output.
1410 * \param prnt Print output callback function to use.
1411 * \param prnt_obj Callback function to print the given object's key. (NULL if not available)
1415 void ao2_container_dump(struct ao2_container *self, enum search_flags flags, const char *name, void *where, ao2_prnt_fn *prnt, ao2_prnt_obj_fn *prnt_obj);
1418 * \brief Display statistics of the specified container.
1421 * \param self Container to display statistics.
1422 * \param flags OBJ_NOLOCK if a lock is already held on the container.
1423 * \param name Container name. (NULL if anonymous)
1424 * \param where User data needed by prnt to determine where to put output.
1425 * \param prnt Print output callback function to use.
1429 void ao2_container_stats(struct ao2_container *self, enum search_flags flags, const char *name, void *where, ao2_prnt_fn *prnt);
1432 * \brief Perform an integrity check on the specified container.
1435 * \param self Container to check integrity.
1436 * \param flags OBJ_NOLOCK if a lock is already held on the container.
1438 * \retval 0 on success.
1439 * \retval -1 on error.
1441 int ao2_container_check(struct ao2_container *self, enum search_flags flags);
1444 * \brief Register a container for CLI stats and integrity check.
1447 * \param name Name to register the container under.
1448 * \param self Container to register.
1449 * \param prnt_obj Callback function to print the given object's key. (NULL if not available)
1451 * \retval 0 on success.
1452 * \retval -1 on error.
1454 int ao2_container_register(const char *name, struct ao2_container *self, ao2_prnt_obj_fn *prnt_obj);
1457 * \brief Unregister a container for CLI stats and integrity check.
1460 * \param name Name the container is registered under.
1464 void ao2_container_unregister(const char *name);
1468 /*! \name Object Management
1469 * Here we have functions to manage objects.
1471 * We can use the functions below on any kind of
1472 * object defined by the user.
1477 * \brief Add an object to a container.
1479 * \param container The container to operate on.
1480 * \param obj The object to be added.
1481 * \param tag used for debugging.
1483 * \retval 0 on errors.
1484 * \retval 1 on success.
1486 * This function inserts an object in a container according its key.
1488 * \note Remember to set the key before calling this function.
1490 * \note This function automatically increases the reference count to account
1491 * for the reference that the container now holds to the object.
1493 #define ao2_t_link(container, obj, tag) \
1494 __ao2_link((container), (obj), 0, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1495 #define ao2_link(container, obj) \
1496 __ao2_link((container), (obj), 0, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1499 * \brief Add an object to a container.
1501 * \param container The container to operate on.
1502 * \param obj The object to be added.
1503 * \param flags search_flags to control linking the object. (OBJ_NOLOCK)
1504 * \param tag used for debugging.
1506 * \retval 0 on errors.
1507 * \retval 1 on success.
1509 * This function inserts an object in a container according its key.
1511 * \note Remember to set the key before calling this function.
1513 * \note This function automatically increases the reference count to account
1514 * for the reference that the container now holds to the object.
1516 #define ao2_t_link_flags(container, obj, flags, tag) \
1517 __ao2_link((container), (obj), (flags), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1518 #define ao2_link_flags(container, obj, flags) \
1519 __ao2_link((container), (obj), (flags), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1521 int __ao2_link(struct ao2_container *c, void *obj_new, int flags,
1522 const char *tag, const char *file, int line, const char *func);
1525 * \brief Remove an object from a container
1527 * \param container The container to operate on.
1528 * \param obj The object to unlink.
1529 * \param tag used for debugging.
1531 * \retval NULL, always
1533 * \note The object requested to be unlinked must be valid. However, if it turns
1534 * out that it is not in the container, this function is still safe to
1537 * \note If the object gets unlinked from the container, the container's
1538 * reference to the object will be automatically released. (The
1539 * refcount will be decremented).
1542 #define ao2_t_unlink(container, obj, tag) \
1543 __ao2_unlink((container), (obj), 0, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1544 #define ao2_unlink(container, obj) \
1545 __ao2_unlink((container), (obj), 0, "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1548 * \brief Remove an object from a container
1550 * \param container The container to operate on.
1551 * \param obj The object to unlink.
1552 * \param flags search_flags to control unlinking the object. (OBJ_NOLOCK)
1553 * \param tag used for debugging.
1555 * \retval NULL, always
1557 * \note The object requested to be unlinked must be valid. However, if it turns
1558 * out that it is not in the container, this function is still safe to
1561 * \note If the object gets unlinked from the container, the container's
1562 * reference to the object will be automatically released. (The
1563 * refcount will be decremented).
1566 #define ao2_t_unlink_flags(container, obj, flags, tag) \
1567 __ao2_unlink((container), (obj), (flags), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1568 #define ao2_unlink_flags(container, obj, flags) \
1569 __ao2_unlink((container), (obj), (flags), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1571 void *__ao2_unlink(struct ao2_container *c, void *obj, int flags,
1572 const char *tag, const char *file, int line, const char *func);
1578 * ao2_callback() is a generic function that applies cb_fn() to all objects
1579 * in a container, as described below.
1581 * \param c A pointer to the container to operate on.
1582 * \param flags A set of flags specifying the operation to perform,
1583 * partially used by the container code, but also passed to
1585 * - If OBJ_NODATA is set, ao2_callback will return NULL. No refcounts
1586 * of any of the traversed objects will be incremented.
1587 * On the converse, if it is NOT set (the default), the ref count
1588 * of the first matching object will be incremented and returned.
1589 * - If OBJ_MULTIPLE is set, the ref count of all matching objects will
1590 * be incremented in an iterator for a temporary container and returned.
1591 * - If OBJ_SEARCH_OBJECT is set, the traversed items will be restricted
1592 * to the objects in the bucket that the object key hashes to.
1593 * - If OBJ_SEARCH_KEY is set, the traversed items will be restricted
1594 * to the objects in the bucket that the object key hashes to.
1595 * \param cb_fn A function pointer, that will be called on all
1596 * objects, to see if they match. This function returns CMP_MATCH
1597 * if the object is matches the criteria; CMP_STOP if the traversal
1598 * should immediately stop, or both (via bitwise ORing), if you find a
1599 * match and want to end the traversal, and 0 if the object is not a match,
1600 * but the traversal should continue. This is the function that is applied
1601 * to each object traversed. Its arguments are:
1602 * (void *obj, void *arg, int flags), where:
1604 * arg is the same as arg passed into ao2_callback
1605 * flags is the same as flags passed into ao2_callback (flags are
1606 * also used by ao2_callback).
1607 * \param arg passed to the callback.
1608 * \param tag used for debugging.
1610 * \retval NULL on failure or no matching object found.
1612 * \retval object found if OBJ_MULTIPLE is not set in the flags
1615 * \retval ao2_iterator pointer if OBJ_MULTIPLE is set in the
1616 * flags parameter. The iterator must be destroyed with
1617 * ao2_iterator_destroy() when the caller no longer needs it.
1619 * If the function returns any objects, their refcount is incremented,
1620 * and the caller is in charge of decrementing them once done.
1622 * Typically, ao2_callback() is used for two purposes:
1623 * - to perform some action (including removal from the container) on one
1624 * or more objects; in this case, cb_fn() can modify the object itself,
1625 * and to perform deletion should set CMP_MATCH on the matching objects,
1626 * and have OBJ_UNLINK set in flags.
1627 * - to look for a specific object in a container; in this case, cb_fn()
1628 * should not modify the object, but just return a combination of
1629 * CMP_MATCH and CMP_STOP on the desired object.
1630 * Other usages are also possible, of course.
1632 * This function searches through a container and performs operations
1633 * on objects according on flags passed.
1634 * XXX describe better
1635 * The comparison is done calling the compare function set implicitly.
1636 * The arg pointer can be a pointer to an object or to a key,
1637 * we can say this looking at flags value.
1638 * If arg points to an object we will search for the object pointed
1639 * by this value, otherwise we search for a key value.
1640 * If the key is not unique we only find the first matching value.
1642 * The use of flags argument is the follow:
1644 * OBJ_UNLINK unlinks the object found
1645 * OBJ_NODATA on match, do return an object
1646 * Callbacks use OBJ_NODATA as a default
1647 * functions such as find() do
1648 * OBJ_MULTIPLE return multiple matches
1650 * OBJ_SEARCH_OBJECT the pointer is to an object
1651 * OBJ_SEARCH_KEY the pointer is to a search key
1652 * OBJ_SEARCH_PARTIAL_KEY the pointer is to a partial search key
1654 * \note When the returned object is no longer in use, ao2_ref() should
1655 * be used to free the additional reference possibly created by this function.
1660 #define ao2_t_callback(c, flags, cb_fn, arg, tag) \
1661 __ao2_callback((c), (flags), (cb_fn), (arg), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1662 #define ao2_callback(c, flags, cb_fn, arg) \
1663 __ao2_callback((c), (flags), (cb_fn), (arg), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1665 void *__ao2_callback(struct ao2_container *c, enum search_flags flags,
1666 ao2_callback_fn *cb_fn, void *arg, const char *tag, const char *file, int line,
1672 * ao2_callback_data() is a generic function that applies cb_fn() to all objects
1673 * in a container. It is functionally identical to ao2_callback() except that
1674 * instead of taking an ao2_callback_fn *, it takes an ao2_callback_data_fn *, and
1675 * allows the caller to pass in arbitrary data.
1677 * This call would be used instead of ao2_callback() when the caller needs to pass
1678 * OBJ_SEARCH_OBJECT, OBJ_SEARCH_KEY, or OBJ_SEARCH_PARTIAL_KEY as part of the flags
1679 * argument (which in turn requires passing in a known pointer type for 'arg') and
1680 * also needs access to other non-global data to complete it's comparison or task.
1682 * See the documentation for ao2_callback() for argument descriptions.
1684 * \see ao2_callback()
1687 #define ao2_t_callback_data(container, flags, cb_fn, arg, data, tag) \
1688 __ao2_callback_data((container), (flags), (cb_fn), (arg), (data), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1689 #define ao2_callback_data(container, flags, cb_fn, arg, data) \
1690 __ao2_callback_data((container), (flags), (cb_fn), (arg), (data), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1692 void *__ao2_callback_data(struct ao2_container *c, enum search_flags flags,
1693 ao2_callback_data_fn *cb_fn, void *arg, void *data, const char *tag, const char *file,
1694 int line, const char *func);
1696 /*! ao2_find() is a short hand for ao2_callback(c, flags, c->cmp_fn, arg)
1697 * XXX possibly change order of arguments ?
1700 #define ao2_t_find(container, arg, flags, tag) \
1701 __ao2_find((container), (arg), (flags), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1702 #define ao2_find(container, arg, flags) \
1703 __ao2_find((container), (arg), (flags), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1705 void *__ao2_find(struct ao2_container *c, const void *arg, enum search_flags flags,
1706 const char *tag, const char *file, int line, const char *func);
1711 * When we need to walk through a container, we use an
1712 * ao2_iterator to keep track of the current position.
1714 * Because the navigation is typically done without holding the
1715 * lock on the container across the loop, objects can be
1716 * inserted or deleted or moved while we work. As a
1717 * consequence, there is no guarantee that we manage to touch
1718 * all the elements in the container, and it is possible that we
1719 * touch the same object multiple times.
1721 * An iterator must be first initialized with
1722 * ao2_iterator_init(), then we can use o = ao2_iterator_next()
1723 * to move from one element to the next. Remember that the
1724 * object returned by ao2_iterator_next() has its refcount
1725 * incremented, and the reference must be explicitly released
1726 * when done with it.
1728 * In addition, ao2_iterator_init() will hold a reference to the
1729 * container being iterated and the last container node found.
1730 * Thes objects will be unreffed when ao2_iterator_destroy() is
1731 * called to free up the resources used by the iterator (if
1738 * struct ao2_container *c = ... // the container we want to iterate on
1739 * struct ao2_iterator i;
1742 * i = ao2_iterator_init(c, flags);
1744 * while ((o = ao2_iterator_next(&i))) {
1745 * ... do something on o ...
1749 * ao2_iterator_restart(&i);
1750 * while ((o = ao2_iterator_next(&i))) {
1751 * ... do something on o ...
1755 * ao2_iterator_destroy(&i);
1762 * \brief The astobj2 iterator
1764 * \note You are not supposed to know the internals of an iterator!
1765 * We would like the iterator to be opaque, unfortunately
1766 * its size needs to be known if we want to store it around
1767 * without too much trouble.
1769 * The iterator has a pointer to the container, and a flags
1770 * field specifying various things e.g. whether the container
1771 * should be locked or not while navigating on it.
1772 * The iterator "points" to the current container node.
1774 * Details are in the implementation of ao2_iterator_next()
1776 struct ao2_iterator {
1777 /*! The container (Has a reference) */
1778 struct ao2_container *c;
1779 /*! Last container node (Has a reference) */
1781 /*! Nonzero if the iteration has completed. */
1783 /*! operation flags (enum ao2_iterator_flags) */
1787 /*! Flags that can be passed to ao2_iterator_init() to modify the behavior
1790 enum ao2_iterator_flags {
1792 * \brief Assume that the ao2_container is already locked.
1794 * \note For ao2_containers that have mutexes, no locking will
1797 * \note For ao2_containers that have RWLOCKs, the lock will be
1798 * promoted to write mode as needed. The lock will be returned
1799 * to the original locked state.
1801 * \note Only use this flag if the ao2_container is manually
1802 * locked already. You should hold the lock until after
1803 * ao2_iterator_destroy(). If you must release the lock then
1804 * you must at least hold the lock whenever you call an
1805 * ao2_iterator_xxx function with this iterator.
1807 AO2_ITERATOR_DONTLOCK = (1 << 0),
1809 * Indicates that the iterator was dynamically allocated by
1810 * astobj2 API and should be freed by ao2_iterator_destroy().
1812 AO2_ITERATOR_MALLOCD = (1 << 1),
1814 * Indicates that before the iterator returns an object from
1815 * the container being iterated, the object should be unlinked
1816 * from the container.
1818 AO2_ITERATOR_UNLINK = (1 << 2),
1820 * Iterate in descending order (Last to first container object)
1821 * (Otherwise ascending order)
1823 * \note Other traversal orders such as pre-order and post-order
1824 * do not make sense because they require the container
1825 * structure to be static during the traversal. Iterators just
1826 * about guarantee that is not going to happen because the
1827 * container is allowed to change by other threads during the
1830 AO2_ITERATOR_DESCENDING = (1 << 3),
1834 * \brief Create an iterator for a container
1836 * \param c the container
1837 * \param flags one or more flags from ao2_iterator_flags.
1839 * \retval the constructed iterator
1841 * \note This function does \b not take a pointer to an iterator;
1842 * rather, it returns an iterator structure that should be
1843 * assigned to (overwriting) an existing iterator structure
1844 * allocated on the stack or on the heap.
1846 * This function will take a reference on the container being iterated.
1848 struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result;
1851 * \brief Destroy a container iterator
1853 * \param iter the iterator to destroy
1857 * This function will release the container reference held by the iterator
1858 * and any other resources it may be holding.
1860 #if defined(TEST_FRAMEWORK)
1861 void ao2_iterator_destroy(struct ao2_iterator *iter) __attribute__((noinline));
1863 void ao2_iterator_destroy(struct ao2_iterator *iter);
1864 #endif /* defined(TEST_FRAMEWORK) */
1866 #define ao2_t_iterator_next(iter, tag) \
1867 __ao2_iterator_next((iter), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1868 #define ao2_iterator_next(iter) \
1869 __ao2_iterator_next((iter), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1871 void *__ao2_iterator_next(struct ao2_iterator *iter,
1872 const char *tag, const char *file, int line, const char *func) attribute_warn_unused_result;
1875 * \brief Restart an iteration.
1877 * \param iter the iterator to restart
1879 * \note A restart is not going to have any effect if the
1880 * iterator was created with the AO2_ITERATOR_UNLINK flag. Any
1881 * previous objects returned were removed from the container.
1885 void ao2_iterator_restart(struct ao2_iterator *iter);
1887 /*! gcc __attribute__(cleanup()) functions
1888 * \note they must be able to handle NULL parameters because most of the
1889 * allocation/find functions can fail and we don't want to try to tear
1891 void __ao2_cleanup(void *obj);
1892 void __ao2_cleanup_debug(void *obj, const char *tag, const char *file, int line, const char *function);
1893 #define ao2_cleanup(obj) __ao2_cleanup_debug((obj), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
1894 #define ao2_t_cleanup(obj, tag) __ao2_cleanup_debug((obj), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
1895 void ao2_iterator_cleanup(struct ao2_iterator *iter);
1898 * \brief Get a count of the iterated container objects.
1900 * \param iter the iterator to query
1902 * \retval The number of objects in the iterated container
1904 int ao2_iterator_count(struct ao2_iterator *iter);
1906 #endif /* _ASTERISK_ASTOBJ2_H */