Sat Apr 26 2014 22:01:29

Asterisk developer's documentation


astobj2.h
Go to the documentation of this file.
00001 /*
00002  * astobj2 - replacement containers for asterisk data structures.
00003  *
00004  * Copyright (C) 2006 Marta Carbone, Luigi Rizzo - Univ. di Pisa, Italy
00005  *
00006  * See http://www.asterisk.org for more information about
00007  * the Asterisk project. Please do not directly contact
00008  * any of the maintainers of this project for assistance;
00009  * the project provides a web site, mailing lists and IRC
00010  * channels for your use.
00011  *
00012  * This program is free software, distributed under the terms of
00013  * the GNU General Public License Version 2. See the LICENSE file
00014  * at the top of the source tree.
00015  */
00016 
00017 #ifndef _ASTERISK_ASTOBJ2_H
00018 #define _ASTERISK_ASTOBJ2_H
00019 
00020 #include "asterisk/compat.h"
00021 #include "asterisk/lock.h"
00022 
00023 /*! \file
00024  * \ref AstObj2
00025  *
00026  * \page AstObj2 Object Model implementing objects and containers.
00027 
00028 This module implements an abstraction for objects (with locks and
00029 reference counts), and containers for these user-defined objects,
00030 also supporting locking, reference counting and callbacks.
00031 
00032 The internal implementation of objects and containers is opaque to the user,
00033 so we can use different data structures as needs arise.
00034 
00035 \section AstObj2_UsageObjects USAGE - OBJECTS
00036 
00037 An ao2 object is a block of memory that the user code can access,
00038 and for which the system keeps track (with a bit of help from the
00039 programmer) of the number of references around.  When an object has
00040 no more references (refcount == 0), it is destroyed, by first
00041 invoking whatever 'destructor' function the programmer specifies
00042 (it can be NULL if none is necessary), and then freeing the memory.
00043 This way objects can be shared without worrying who is in charge
00044 of freeing them.
00045 As an additional feature, ao2 objects are associated to individual
00046 locks.
00047 
00048 Creating an object requires the size of the object and
00049 a pointer to the destructor function:
00050 
00051     struct foo *o;
00052 
00053     o = ao2_alloc(sizeof(struct foo), my_destructor_fn);
00054 
00055 The value returned points to the user-visible portion of the objects
00056 (user-data), but is also used as an identifier for all object-related
00057 operations such as refcount and lock manipulations.
00058 
00059 On return from ao2_alloc():
00060 
00061  - the object has a refcount = 1;
00062  - the memory for the object is allocated dynamically and zeroed;
00063  - we cannot realloc() the object itself;
00064  - we cannot call free(o) to dispose of the object. Rather, we
00065    tell the system that we do not need the reference anymore:
00066 
00067     ao2_ref(o, -1)
00068 
00069   causing the destructor to be called (and then memory freed) when
00070   the refcount goes to 0.
00071 
00072 - ao2_ref(o, +1) can be used to modify the refcount on the
00073   object in case we want to pass it around.
00074 
00075 - ao2_lock(obj), ao2_unlock(obj), ao2_trylock(obj) can be used
00076   to manipulate the lock associated with the object.
00077 
00078 
00079 \section AstObj2_UsageContainers USAGE - CONTAINERS
00080 
00081 An ao2 container is an abstract data structure where we can store
00082 ao2 objects, search them (hopefully in an efficient way), and iterate
00083 or apply a callback function to them. A container is just an ao2 object
00084 itself.
00085 
00086 A container must first be allocated, specifying the initial
00087 parameters. At the moment, this is done as follows:
00088 
00089     <b>Sample Usage:</b>
00090     \code
00091 
00092     struct ao2_container *c;
00093 
00094     c = ao2_container_alloc(MAX_BUCKETS, my_hash_fn, my_cmp_fn);
00095     \endcode
00096 
00097 where
00098 
00099 - MAX_BUCKETS is the number of buckets in the hash table,
00100 - my_hash_fn() is the (user-supplied) function that returns a
00101   hash key for the object (further reduced modulo MAX_BUCKETS
00102   by the container's code);
00103 - my_cmp_fn() is the default comparison function used when doing
00104   searches on the container,
00105 
00106 A container knows little or nothing about the objects it stores,
00107 other than the fact that they have been created by ao2_alloc().
00108 All knowledge of the (user-defined) internals of the objects
00109 is left to the (user-supplied) functions passed as arguments
00110 to ao2_container_alloc().
00111 
00112 If we want to insert an object in a container, we should
00113 initialize its fields -- especially, those used by my_hash_fn() --
00114 to compute the bucket to use.
00115 Once done, we can link an object to a container with
00116 
00117     ao2_link(c, o);
00118 
00119 The function returns NULL in case of errors (and the object
00120 is not inserted in the container). Other values mean success
00121 (we are not supposed to use the value as a pointer to anything).
00122 Linking an object to a container increases its refcount by 1
00123 automatically.
00124 
00125 \note While an object o is in a container, we expect that
00126 my_hash_fn(o) will always return the same value. The function
00127 does not lock the object to be computed, so modifications of
00128 those fields that affect the computation of the hash should
00129 be done by extracting the object from the container, and
00130 re-inserting it after the change (this is not terribly expensive).
00131 
00132 \note A container with a single buckets is effectively a linked
00133 list. However there is no ordering among elements.
00134 
00135 - \ref AstObj2_Containers
00136 - \ref astobj2.h All documentation for functions and data structures
00137 
00138  */
00139 
00140 /*
00141 \note DEBUGGING REF COUNTS BIBLE:
00142 An interface to help debug refcounting is provided
00143 in this package. It is dependent on the REF_DEBUG macro being
00144 defined in a source file, before the #include of astobj2.h,
00145 and in using variants of the normal ao2_xxx functions
00146 that are named ao2_t_xxx instead, with an extra argument, a string,
00147 that will be printed out into /tmp/refs when the refcount for an
00148 object is changed.
00149 
00150   these ao2_t_xxx variants are provided:
00151 
00152 ao2_t_alloc(arg1, arg2, arg3)
00153 ao2_t_ref(arg1,arg2,arg3)
00154 ao2_t_container_alloc(arg1,arg2,arg3,arg4)
00155 ao2_t_link(arg1, arg2, arg3)
00156 ao2_t_unlink(arg1, arg2, arg3)
00157 ao2_t_callback(arg1,arg2,arg3,arg4,arg5)
00158 ao2_t_find(arg1,arg2,arg3,arg4)
00159 ao2_t_iterator_next(arg1, arg2)
00160 
00161 If you study each argument list, you will see that these functions all have
00162 one extra argument than their ao2_xxx counterpart. The last argument in
00163 each case is supposed to be a string pointer, a "tag", that should contain
00164 enough of an explanation, that you can pair operations that increment the
00165 ref count, with operations that are meant to decrement the refcount.
00166 
00167 Each of these calls will generate at least one line of output in /tmp/refs.
00168 These lines look like this:
00169 ...
00170 0x8756f00 =1   chan_sip.c:22240:load_module (allocate users)
00171 0x86e3408 =1   chan_sip.c:22241:load_module (allocate peers)
00172 0x86dd380 =1   chan_sip.c:22242:load_module (allocate peers_by_ip)
00173 0x822d020 =1   chan_sip.c:22243:load_module (allocate dialogs)
00174 0x8930fd8 =1   chan_sip.c:20025:build_peer (allocate a peer struct)
00175 0x8930fd8 +1   chan_sip.c:21467:reload_config (link peer into peer table) [@1]
00176 0x8930fd8 -1   chan_sip.c:2370:unref_peer (unref_peer: from reload_config) [@2]
00177 0x89318b0 =1   chan_sip.c:20025:build_peer (allocate a peer struct)
00178 0x89318b0 +1   chan_sip.c:21467:reload_config (link peer into peer table) [@1]
00179 0x89318b0 -1   chan_sip.c:2370:unref_peer (unref_peer: from reload_config) [@2]
00180 0x8930218 =1   chan_sip.c:20025:build_peer (allocate a peer struct)
00181 0x8930218 +1   chan_sip.c:21539:reload_config (link peer into peers table) [@1]
00182 0x868c040 -1   chan_sip.c:2424:dialog_unlink_all (unset the relatedpeer->call field in tandem with relatedpeer field itself) [@2]
00183 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]
00184 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)
00185 0x8cc07e8 -1   chan_sip.c:2370:unref_peer (unsetting a dialog relatedpeer field in sip_destroy) [@3]
00186 0x8cc07e8 +1   chan_sip.c:3876:find_peer (ao2_find in peers table) [@2]
00187 0x8cc07e8 -1   chan_sip.c:2370:unref_peer (unref_peer, from sip_devicestate, release ref from find_peer) [@3]
00188 ...
00189 
00190 The first column is the object address.
00191 The second column reflects how the operation affected the ref count
00192     for that object. Creation sets the ref count to 1 (=1).
00193     increment or decrement and amount are specified (-1/+1).
00194 The remainder of the line specifies where in the file the call was made,
00195     and the function name, and the tag supplied in the function call.
00196 
00197 The **call destructor** is specified when the destroy routine is
00198 run for an object. It does not affect the ref count, but is important
00199 in debugging, because it is possible to have the astobj2 system run it
00200 multiple times on the same object, commonly fatal to asterisk.
00201 
00202 Sometimes you have some helper functions to do object ref/unref
00203 operations. Using these normally hides the place where these
00204 functions were called. To get the location where these functions
00205 were called to appear in /tmp/refs, you can do this sort of thing:
00206 
00207 #ifdef REF_DEBUG
00208 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00209 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
00210 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, const char *file, int line, const char *func)
00211 {
00212    if (p) {
00213       ao2_ref_debug(p, 1, tag, file, line, func);
00214    } else {
00215       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
00216    }
00217    return p;
00218 }
00219 
00220 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, const char *file, int line, const char *func)
00221 {
00222    if (p) {
00223       ao2_ref_debug(p, -1, tag, file, line, func);
00224    }
00225    return NULL;
00226 }
00227 #else
00228 static struct sip_pvt *dialog_ref(struct sip_pvt *p, const char *tag)
00229 {
00230    if (p) {
00231       ao2_ref(p, 1);
00232    } else {
00233       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
00234    }
00235    return p;
00236 }
00237 
00238 static struct sip_pvt *dialog_unref(struct sip_pvt *p, const char *tag)
00239 {
00240    if (p) {
00241       ao2_ref(p, -1);
00242    }
00243    return NULL;
00244 }
00245 #endif
00246 
00247 In the above code, note that the "normal" helper funcs call ao2_ref() as
00248 normal, and the "helper" functions call ao2_ref_debug directly with the
00249 file, function, and line number info provided. You might find this
00250 well worth the effort to help track these function calls in the code.
00251 
00252 To find out why objects are not destroyed (a common bug), you can
00253 edit the source file to use the ao2_t_* variants, add the #define REF_DEBUG 1
00254 before the #include "asterisk/astobj2.h" line, and add a descriptive
00255 tag to each call. Recompile, and run Asterisk, exit asterisk with
00256 "stop gracefully", which should result in every object being destroyed.
00257 Then, you can "sort -k 1 /tmp/refs > x1" to get a sorted list of
00258 all the objects, or you can use "util/refcounter" to scan the file
00259 for you and output any problems it finds.
00260 
00261 The above may seem astronomically more work than it is worth to debug
00262 reference counts, which may be true in "simple" situations, but for
00263 more complex situations, it is easily worth 100 times this effort to
00264 help find problems.
00265 
00266 To debug, pair all calls so that each call that increments the
00267 refcount is paired with a corresponding call that decrements the
00268 count for the same reason. Hopefully, you will be left with one
00269 or more unpaired calls. This is where you start your search!
00270 
00271 For instance, here is an example of this for a dialog object in
00272 chan_sip, that was not getting destroyed, after I moved the lines around
00273 to pair operations:
00274 
00275    0x83787a0 =1   chan_sip.c:5733:sip_alloc (allocate a dialog(pvt) struct)
00276    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]
00277 
00278    0x83787a0 +1   chan_sip.c:5854:sip_alloc (link pvt into dialogs table) [@1]
00279    0x83787a0 -1   chan_sip.c:19150:sip_poke_peer (About to change the callid -- remove the old name) [@3]
00280    0x83787a0 +1   chan_sip.c:19152:sip_poke_peer (Linking in under new name) [@2]
00281    0x83787a0 -1   chan_sip.c:2399:dialog_unlink_all (unlinking dialog via ao2_unlink) [@5]
00282 
00283    0x83787a0 +1   chan_sip.c:19130:sip_poke_peer (copy sip alloc from p to peer->call) [@2]
00284 
00285 
00286    0x83787a0 +1   chan_sip.c:2996:__sip_reliable_xmit (__sip_reliable_xmit: setting pkt->owner) [@3]
00287    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]
00288 
00289    0x83787a0 +1   chan_sip.c:22356:unload_module (iterate thru dialogs) [@4]
00290    0x83787a0 -1   chan_sip.c:22359:unload_module (toss dialog ptr from iterator_next) [@5]
00291 
00292 
00293    0x83787a0 +1   chan_sip.c:22373:unload_module (iterate thru dialogs) [@3]
00294    0x83787a0 -1   chan_sip.c:22375:unload_module (throw away iterator result) [@2]
00295 
00296    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]
00297    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]
00298 
00299 As you can see, only one unbalanced operation is in the list, a ref count increment when
00300 the peer->call was set, but no corresponding decrement was made...
00301 
00302 Hopefully this helps you narrow your search and find those bugs.
00303 
00304 THE ART OF REFERENCE COUNTING
00305 (by Steve Murphy)
00306 SOME TIPS for complicated code, and ref counting:
00307 
00308 1. Theoretically, passing a refcounted object pointer into a function
00309 call is an act of copying the reference, and could be refcounted.
00310 But, upon examination, this sort of refcounting will explode the amount
00311 of code you have to enter, and for no tangible benefit, beyond
00312 creating more possible failure points/bugs. It will even
00313 complicate your code and make debugging harder, slow down your program
00314 doing useless increments and decrements of the ref counts.
00315 
00316 2. It is better to track places where a ref counted pointer
00317 is copied into a structure or stored. Make sure to decrement the refcount
00318 of any previous pointer that might have been there, if setting
00319 this field might erase a previous pointer. ao2_find and iterate_next
00320 internally increment the ref count when they return a pointer, so
00321 you need to decrement the count before the pointer goes out of scope.
00322 
00323 3. Any time you decrement a ref count, it may be possible that the
00324 object will be destroyed (freed) immediately by that call. If you
00325 are destroying a series of fields in a refcounted object, and
00326 any of the unref calls might possibly result in immediate destruction,
00327 you can first increment the count to prevent such behavior, then
00328 after the last test, decrement the pointer to allow the object
00329 to be destroyed, if the refcount would be zero.
00330 
00331 Example:
00332 
00333    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
00334 
00335    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
00336 
00337    *//* Unlink us from the owner (channel) if we have one *//*
00338    if (dialog->owner) {
00339       if (lockowner) {
00340          ast_channel_lock(dialog->owner);
00341       }
00342       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
00343       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
00344       if (lockowner) {
00345          ast_channel_unlock(dialog->owner);
00346       }
00347    }
00348    if (dialog->registry) {
00349       if (dialog->registry->call == dialog) {
00350          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
00351       }
00352       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
00353    }
00354    ...
00355    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
00356 
00357 In the above code, the ao2_t_unlink could end up destroying the dialog
00358 object; if this happens, then the subsequent usages of the dialog
00359 pointer could result in a core dump. So, we 'bump' the
00360 count upwards before beginning, and then decrementing the count when
00361 we are finished. This is analogous to 'locking' or 'protecting' operations
00362 for a short while.
00363 
00364 4. One of the most insidious problems I've run into when converting
00365 code to do ref counted automatic destruction, is in the destruction
00366 routines. Where a "destroy" routine had previously been called to
00367 get rid of an object in non-refcounted code, the new regime demands
00368 that you tear that "destroy" routine into two pieces, one that will
00369 tear down the links and 'unref' them, and the other to actually free
00370 and reset fields. A destroy routine that does any reference deletion
00371 for its own object, will never be called. Another insidious problem
00372 occurs in mutually referenced structures. As an example, a dialog contains
00373 a pointer to a peer, and a peer contains a pointer to a dialog. Watch
00374 out that the destruction of one doesn't depend on the destruction of the
00375 other, as in this case a dependency loop will result in neither being
00376 destroyed!
00377 
00378 Given the above, you should be ready to do a good job!
00379 
00380 murf
00381 
00382 */
00383 
00384 
00385 
00386 /*! \brief
00387  * Typedef for an object destructor. This is called just before freeing
00388  * the memory for the object. It is passed a pointer to the user-defined
00389  * data of the object.
00390  */
00391 typedef void (*ao2_destructor_fn)(void *);
00392 
00393 /*! \brief Options available when allocating an ao2 object. */
00394 enum ao2_alloc_opts {
00395    /*! The ao2 object has a recursive mutex lock associated with it. */
00396    AO2_ALLOC_OPT_LOCK_MUTEX = (0 << 0),
00397    /*! The ao2 object has a non-recursive read/write lock associated with it. */
00398    AO2_ALLOC_OPT_LOCK_RWLOCK = (1 << 0),
00399    /*! The ao2 object has no lock associated with it. */
00400    AO2_ALLOC_OPT_LOCK_NOLOCK = (2 << 0),
00401    /*! The ao2 object locking option field mask. */
00402    AO2_ALLOC_OPT_LOCK_MASK = (3 << 0),
00403 };
00404 
00405 /*!
00406  * \brief Allocate and initialize an object.
00407  *
00408  * \param data_size The sizeof() of the user-defined structure.
00409  * \param destructor_fn The destructor function (can be NULL)
00410  * \param options The ao2 object options (See enum ao2_alloc_opts)
00411  * \param debug_msg An ao2 object debug tracing message.
00412  * \return A pointer to user-data.
00413  *
00414  * \details
00415  * Allocates a struct astobj2 with sufficient space for the
00416  * user-defined structure.
00417  * \note
00418  * - storage is zeroed; XXX maybe we want a flag to enable/disable this.
00419  * - the refcount of the object just created is 1
00420  * - the returned pointer cannot be free()'d or realloc()'ed;
00421  *   rather, we just call ao2_ref(o, -1);
00422  *
00423  * @{
00424  */
00425 
00426 #if defined(REF_DEBUG)
00427 
00428 #define ao2_t_alloc_options(data_size, destructor_fn, options, debug_msg) \
00429    __ao2_alloc_debug((data_size), (destructor_fn), (options), (debug_msg),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00430 #define ao2_alloc_options(data_size, destructor_fn, options) \
00431    __ao2_alloc_debug((data_size), (destructor_fn), (options), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00432 
00433 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
00434    __ao2_alloc_debug((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, (debug_msg),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00435 #define ao2_alloc(data_size, destructor_fn) \
00436    __ao2_alloc_debug((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00437 
00438 #elif defined(__AST_DEBUG_MALLOC)
00439 
00440 #define ao2_t_alloc_options(data_size, destructor_fn, options, debug_msg) \
00441    __ao2_alloc_debug((data_size), (destructor_fn), (options), (debug_msg),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00442 #define ao2_alloc_options(data_size, destructor_fn, options) \
00443    __ao2_alloc_debug((data_size), (destructor_fn), (options), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00444 
00445 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
00446    __ao2_alloc_debug((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, (debug_msg),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00447 #define ao2_alloc(data_size, destructor_fn) \
00448    __ao2_alloc_debug((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX, "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00449 
00450 #else
00451 
00452 #define ao2_t_alloc_options(data_size, destructor_fn, options, debug_msg) \
00453    __ao2_alloc((data_size), (destructor_fn), (options))
00454 #define ao2_alloc_options(data_size, destructor_fn, options) \
00455    __ao2_alloc((data_size), (destructor_fn), (options))
00456 
00457 #define ao2_t_alloc(data_size, destructor_fn, debug_msg) \
00458    __ao2_alloc((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX)
00459 #define ao2_alloc(data_size, destructor_fn) \
00460    __ao2_alloc((data_size), (destructor_fn), AO2_ALLOC_OPT_LOCK_MUTEX)
00461 
00462 #endif
00463 
00464 void *__ao2_alloc_debug(size_t data_size, ao2_destructor_fn destructor_fn, unsigned int options, const char *tag,
00465    const char *file, int line, const char *func, int ref_debug);
00466 void *__ao2_alloc(size_t data_size, ao2_destructor_fn destructor_fn, unsigned int options);
00467 
00468 /*! @} */
00469 
00470 /*! \brief
00471  * Reference/unreference an object and return the old refcount.
00472  *
00473  * \param o A pointer to the object
00474  * \param delta Value to add to the reference counter.
00475  * \param tag used for debugging
00476  * \return The value of the reference counter before the operation.
00477  *
00478  * Increase/decrease the reference counter according
00479  * the value of delta.
00480  *
00481  * If the refcount goes to zero, the object is destroyed.
00482  *
00483  * \note The object must not be locked by the caller of this function, as
00484  *       it is invalid to try to unlock it after releasing the reference.
00485  *
00486  * \note if we know the pointer to an object, it is because we
00487  * have a reference count to it, so the only case when the object
00488  * can go away is when we release our reference, and it is
00489  * the last one in existence.
00490  *
00491  * @{
00492  */
00493 
00494 #ifdef REF_DEBUG
00495 
00496 #define ao2_t_ref(o,delta,tag) __ao2_ref_debug((o), (delta), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
00497 #define ao2_ref(o,delta)       __ao2_ref_debug((o), (delta), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
00498 
00499 #else
00500 
00501 #define ao2_t_ref(o,delta,tag) __ao2_ref((o), (delta))
00502 #define ao2_ref(o,delta)       __ao2_ref((o), (delta))
00503 
00504 #endif
00505 
00506 int __ao2_ref_debug(void *o, int delta, const char *tag, const char *file, int line, const char *func);
00507 int __ao2_ref(void *o, int delta);
00508 
00509 /*! @} */
00510 
00511 /*! \brief Which lock to request. */
00512 enum ao2_lock_req {
00513    /*! Request the mutex lock be acquired. */
00514    AO2_LOCK_REQ_MUTEX,
00515    /*! Request the read lock be acquired. */
00516    AO2_LOCK_REQ_RDLOCK,
00517    /*! Request the write lock be acquired. */
00518    AO2_LOCK_REQ_WRLOCK,
00519 };
00520 
00521 /*! \brief
00522  * Lock an object.
00523  *
00524  * \param a A pointer to the object we want to lock.
00525  * \return 0 on success, other values on error.
00526  */
00527 int __ao2_lock(void *a, enum ao2_lock_req lock_how, const char *file, const char *func, int line, const char *var);
00528 #define ao2_lock(a) __ao2_lock(a, AO2_LOCK_REQ_MUTEX, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00529 #define ao2_rdlock(a) __ao2_lock(a, AO2_LOCK_REQ_RDLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00530 #define ao2_wrlock(a) __ao2_lock(a, AO2_LOCK_REQ_WRLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00531 
00532 /*! \brief
00533  * Unlock an object.
00534  *
00535  * \param a A pointer to the object we want unlock.
00536  * \return 0 on success, other values on error.
00537  */
00538 int __ao2_unlock(void *a, const char *file, const char *func, int line, const char *var);
00539 #define ao2_unlock(a) __ao2_unlock(a, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00540 
00541 /*! \brief
00542  * Try locking-- (don't block if fail)
00543  *
00544  * \param a A pointer to the object we want to lock.
00545  * \return 0 on success, other values on error.
00546  */
00547 int __ao2_trylock(void *a, enum ao2_lock_req lock_how, const char *file, const char *func, int line, const char *var);
00548 #define ao2_trylock(a) __ao2_trylock(a, AO2_LOCK_REQ_MUTEX, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00549 #define ao2_tryrdlock(a) __ao2_trylock(a, AO2_LOCK_REQ_RDLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00550 #define ao2_trywrlock(a) __ao2_trylock(a, AO2_LOCK_REQ_WRLOCK, __FILE__, __PRETTY_FUNCTION__, __LINE__, #a)
00551 
00552 /*!
00553  * \brief Return the mutex lock address of an object
00554  *
00555  * \param[in] obj A pointer to the object we want.
00556  * \return the address of the mutex lock, else NULL.
00557  *
00558  * This function comes in handy mainly for debugging locking
00559  * situations, where the locking trace code reports the
00560  * lock address, this allows you to correlate against
00561  * object address, to match objects to reported locks.
00562  *
00563  * \since 1.6.1
00564  */
00565 void *ao2_object_get_lockaddr(void *obj);
00566 
00567 
00568 /*! Global ao2 object holder structure. */
00569 struct ao2_global_obj {
00570    /*! Access lock to the held ao2 object. */
00571    ast_rwlock_t lock;
00572    /*! Global ao2 object. */
00573    void *obj;
00574 };
00575 
00576 /*!
00577  * \brief Define a global object holder to be used to hold an ao2 object, statically initialized.
00578  * \since 11.0
00579  *
00580  * \param name This will be the name of the object holder.
00581  *
00582  * \details
00583  * This macro creates a global object holder that can be used to
00584  * hold an ao2 object accessible using the API.  The structure is
00585  * allocated and initialized to be empty.
00586  *
00587  * Example usage:
00588  * \code
00589  * static AO2_GLOBAL_OBJ_STATIC(global_cfg);
00590  * \endcode
00591  *
00592  * This defines global_cfg, intended to hold an ao2 object
00593  * accessible using an API.
00594  */
00595 #ifndef HAVE_PTHREAD_RWLOCK_INITIALIZER
00596 #define AO2_GLOBAL_OBJ_STATIC(name)                            \
00597    struct ao2_global_obj name;                                 \
00598    static void  __attribute__((constructor)) __init_##name(void)     \
00599    {                                                  \
00600       ast_rwlock_init(&name.lock);                          \
00601       name.obj = NULL;                                   \
00602    }                                                  \
00603    static void  __attribute__((destructor)) __fini_##name(void)      \
00604    {                                                  \
00605       if (name.obj) {                                       \
00606          ao2_ref(name.obj, -1);                             \
00607          name.obj = NULL;                                \
00608       }                                               \
00609       ast_rwlock_destroy(&name.lock);                          \
00610    }                                                  \
00611    struct __dummy_##name
00612 #else
00613 #define AO2_GLOBAL_OBJ_STATIC(name)                            \
00614    struct ao2_global_obj name = {                              \
00615       .lock = AST_RWLOCK_INIT_VALUE,                           \
00616    }
00617 #endif
00618 
00619 /*!
00620  * \brief Release the ao2 object held in the global holder.
00621  * \since 11.0
00622  *
00623  * \param holder Global ao2 object holder.
00624  * \param tag used for debugging
00625  *
00626  * \return Nothing
00627  */
00628 #ifdef REF_DEBUG
00629 #define ao2_t_global_obj_release(holder, tag)   \
00630    __ao2_global_obj_release(&holder, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00631 #define ao2_global_obj_release(holder) \
00632    __ao2_global_obj_release(&holder, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00633 
00634 #else
00635 
00636 #define ao2_t_global_obj_release(holder, tag)   \
00637    __ao2_global_obj_release(&holder, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00638 #define ao2_global_obj_release(holder) \
00639    __ao2_global_obj_release(&holder, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00640 #endif
00641 
00642 void __ao2_global_obj_release(struct ao2_global_obj *holder, const char *tag, const char *file, int line, const char *func, const char *name);
00643 
00644 /*!
00645  * \brief Replace an ao2 object in the global holder.
00646  * \since 11.0
00647  *
00648  * \param holder Global ao2 object holder.
00649  * \param obj Object to put into the holder.  Can be NULL.
00650  * \param tag used for debugging
00651  *
00652  * \note This function automatically increases the reference
00653  * count to account for the reference that the global holder now
00654  * holds to the object.
00655  *
00656  * \retval Reference to previous global ao2 object stored.
00657  * \retval NULL if no object available.
00658  */
00659 #ifdef REF_DEBUG
00660 #define ao2_t_global_obj_replace(holder, obj, tag) \
00661    __ao2_global_obj_replace(&holder, (obj), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00662 #define ao2_global_obj_replace(holder, obj)  \
00663    __ao2_global_obj_replace(&holder, (obj), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00664 
00665 #else
00666 
00667 #define ao2_t_global_obj_replace(holder, obj, tag) \
00668    __ao2_global_obj_replace(&holder, (obj), NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00669 #define ao2_global_obj_replace(holder, obj)  \
00670    __ao2_global_obj_replace(&holder, (obj), NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00671 #endif
00672 
00673 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);
00674 
00675 /*!
00676  * \brief Replace an ao2 object in the global holder, throwing away any old object.
00677  * \since 11.0
00678  *
00679  * \param holder Global ao2 object holder.
00680  * \param obj Object to put into the holder.  Can be NULL.
00681  * \param tag used for debugging
00682  *
00683  * \note This function automatically increases the reference
00684  * count to account for the reference that the global holder now
00685  * holds to the object.  It also decreases the reference count
00686  * of any object being replaced.
00687  *
00688  * \retval 0 The global object was previously empty
00689  * \retval 1 The global object was not previously empty
00690  */
00691 #ifdef REF_DEBUG
00692 #define ao2_t_global_obj_replace_unref(holder, obj, tag) \
00693    __ao2_global_obj_replace_unref(&holder, (obj), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00694 #define ao2_global_obj_replace_unref(holder, obj)  \
00695    __ao2_global_obj_replace_unref(&holder, (obj), "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00696 
00697 #else
00698 
00699 #define ao2_t_global_obj_replace_unref(holder, obj, tag) \
00700    __ao2_global_obj_replace_unref(&holder, (obj), NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00701 #define ao2_global_obj_replace_unref(holder, obj)  \
00702    __ao2_global_obj_replace_unref(&holder, (obj), NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00703 #endif
00704 
00705 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);
00706 
00707 /*!
00708  * \brief Get a reference to the object stored in the global holder.
00709  * \since 11.0
00710  *
00711  * \param holder Global ao2 object holder.
00712  * \param tag used for debugging
00713  *
00714  * \retval Reference to current ao2 object stored in the holder.
00715  * \retval NULL if no object available.
00716  */
00717 #ifdef REF_DEBUG
00718 #define ao2_t_global_obj_ref(holder, tag) \
00719    __ao2_global_obj_ref(&holder, (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00720 #define ao2_global_obj_ref(holder)  \
00721    __ao2_global_obj_ref(&holder, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00722 
00723 #else
00724 
00725 #define ao2_t_global_obj_ref(holder, tag) \
00726    __ao2_global_obj_ref(&holder, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00727 #define ao2_global_obj_ref(holder)  \
00728    __ao2_global_obj_ref(&holder, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, #holder)
00729 #endif
00730 
00731 void *__ao2_global_obj_ref(struct ao2_global_obj *holder, const char *tag, const char *file, int line, const char *func, const char *name);
00732 
00733 
00734 /*!
00735  \page AstObj2_Containers AstObj2 Containers
00736 
00737 Containers are data structures meant to store several objects,
00738 and perform various operations on them.
00739 Internally, objects are stored in lists, hash tables or other
00740 data structures depending on the needs.
00741 
00742 \note NOTA BENE: at the moment the only container we support is the
00743     hash table and its degenerate form, the list.
00744 
00745 Operations on container include:
00746 
00747   -  c = \b ao2_container_alloc(size, hash_fn, cmp_fn)
00748     allocate a container with desired size and default compare
00749     and hash function
00750          -The compare function returns an int, which
00751          can be 0 for not found, CMP_STOP to stop end a traversal,
00752          or CMP_MATCH if they are equal
00753          -The hash function returns an int. The hash function
00754          takes two argument, the object pointer and a flags field,
00755 
00756   -  \b ao2_find(c, arg, flags)
00757     returns zero or more elements matching a given criteria
00758     (specified as arg). 'c' is the container pointer. Flags
00759     can be:
00760     OBJ_UNLINK - to remove the object, once found, from the container.
00761     OBJ_NODATA - don't return the object if found (no ref count change)
00762     OBJ_MULTIPLE - don't stop at first match
00763     OBJ_POINTER - if set, 'arg' is an object pointer, and a hash table
00764                   search will be done. If not, a traversal is done.
00765     OBJ_KEY - if set, 'arg', is a hashable item that is not an object.
00766               Similar to OBJ_POINTER and mutually exclusive.
00767 
00768   -  \b ao2_callback(c, flags, fn, arg)
00769     apply fn(obj, arg) to all objects in the container.
00770     Similar to find. fn() can tell when to stop, and
00771     do anything with the object including unlinking it.
00772       - c is the container;
00773       - flags can be
00774          OBJ_UNLINK   - to remove the object, once found, from the container.
00775          OBJ_NODATA   - don't return the object if found (no ref count change)
00776          OBJ_MULTIPLE - don't stop at first match
00777          OBJ_POINTER  - if set, 'arg' is an object pointer, and a hash table
00778                         search will be done. If not, a traversal is done through
00779                         all the hash table 'buckets'..
00780          OBJ_KEY      - if set, 'arg', is a hashable item that is not an object.
00781                         Similar to OBJ_POINTER and mutually exclusive.
00782       - fn is a func that returns int, and takes 3 args:
00783         (void *obj, void *arg, int flags);
00784           obj is an object
00785           arg is the same as arg passed into ao2_callback
00786           flags is the same as flags passed into ao2_callback
00787          fn returns:
00788            0: no match, keep going
00789            CMP_STOP: stop search, no match
00790            CMP_MATCH: This object is matched.
00791 
00792     Note that the entire operation is run with the container
00793     locked, so nobody else can change its content while we work on it.
00794     However, we pay this with the fact that doing
00795     anything blocking in the callback keeps the container
00796     blocked.
00797     The mechanism is very flexible because the callback function fn()
00798     can do basically anything e.g. counting, deleting records, etc.
00799     possibly using arg to store the results.
00800 
00801   -  \b iterate on a container
00802     this is done with the following sequence
00803 
00804 \code
00805 
00806         struct ao2_container *c = ... // our container
00807         struct ao2_iterator i;
00808         void *o;
00809 
00810         i = ao2_iterator_init(c, flags);
00811 
00812         while ((o = ao2_iterator_next(&i))) {
00813             ... do something on o ...
00814             ao2_ref(o, -1);
00815         }
00816 
00817         ao2_iterator_destroy(&i);
00818 \endcode
00819 
00820     The difference with the callback is that the control
00821     on how to iterate is left to us.
00822 
00823     - \b ao2_ref(c, -1)
00824     dropping a reference to a container destroys it, very simple!
00825 
00826 Containers are ao2 objects themselves, and this is why their
00827 implementation is simple too.
00828 
00829 Before declaring containers, we need to declare the types of the
00830 arguments passed to the constructor - in turn, this requires
00831 to define callback and hash functions and their arguments.
00832 
00833 - \ref AstObj2
00834 - \ref astobj2.h
00835  */
00836 
00837 /*! \brief
00838  * Type of a generic callback function
00839  * \param obj  pointer to the (user-defined part) of an object.
00840  * \param arg callback argument from ao2_callback()
00841  * \param flags flags from ao2_callback()
00842  *
00843  * The return values are a combination of enum _cb_results.
00844  * Callback functions are used to search or manipulate objects in a container.
00845  */
00846 typedef int (ao2_callback_fn)(void *obj, void *arg, int flags);
00847 
00848 /*! \brief
00849  * Type of a generic callback function
00850  * \param obj pointer to the (user-defined part) of an object.
00851  * \param arg callback argument from ao2_callback()
00852  * \param data arbitrary data from ao2_callback()
00853  * \param flags flags from ao2_callback()
00854  *
00855  * The return values are a combination of enum _cb_results.
00856  * Callback functions are used to search or manipulate objects in a container.
00857  */
00858 typedef int (ao2_callback_data_fn)(void *obj, void *arg, void *data, int flags);
00859 
00860 /*! \brief A common ao2_callback is one that matches by address. */
00861 int ao2_match_by_addr(void *obj, void *arg, int flags);
00862 
00863 /*! \brief
00864  * A callback function will return a combination of CMP_MATCH and CMP_STOP.
00865  * The latter will terminate the search in a container.
00866  */
00867 enum _cb_results {
00868    CMP_MATCH   = 0x1,   /*!< the object matches the request */
00869    CMP_STOP = 0x2,   /*!< stop the search now */
00870 };
00871 
00872 /*! \brief
00873  * Flags passed to ao2_callback() and ao2_hash_fn() to modify its behaviour.
00874  */
00875 enum search_flags {
00876    /*!
00877     * Unlink the object for which the callback function returned
00878     * CMP_MATCH.
00879     */
00880    OBJ_UNLINK = (1 << 0),
00881    /*!
00882     * On match, don't return the object hence do not increase its
00883     * refcount.
00884     */
00885    OBJ_NODATA = (1 << 1),
00886    /*!
00887     * Don't stop at the first match in ao2_callback() unless the
00888     * result of of the callback function has the CMP_STOP bit set.
00889     */
00890    OBJ_MULTIPLE = (1 << 2),
00891    /*!
00892     * The given obj is an object of the same type as the one being
00893     * searched for, so use the object's hash function for optimized
00894     * searching.
00895     *
00896     * The matching function is unaffected (i.e. The cb_fn argument
00897     * to ao2_callback).
00898     */
00899    OBJ_POINTER = (1 << 3),
00900    /*!
00901     * \brief Continue if a match is not found in the hashed out bucket
00902     *
00903     * This flag is to be used in combination with OBJ_POINTER.  This tells
00904     * the ao2_callback() core to keep searching through the rest of the
00905     * buckets if a match is not found in the starting bucket defined by
00906     * the hash value on the argument.
00907     */
00908    OBJ_CONTINUE = (1 << 4),
00909    /*!
00910     * \brief Assume that the ao2_container is already locked.
00911     *
00912     * \note For ao2_containers that have mutexes, no locking will
00913     * be done.
00914     *
00915     * \note For ao2_containers that have RWLOCKs, the lock will be
00916     * promoted to write mode as needed.  The lock will be returned
00917     * to the original locked state.
00918     *
00919     * \note Only use this flag if the ao2_container is manually
00920     * locked already.
00921     */
00922    OBJ_NOLOCK = (1 << 5),
00923    /*!
00924     * \brief The data is hashable, but is not an object.
00925     *
00926     * \details
00927     * This can be used when you want to be able to pass custom data
00928     * to the container's stored ao2_hash_fn and ao2_find
00929     * ao2_callback_fn functions that is not a full object, but
00930     * perhaps just a string.
00931     *
00932     * \note OBJ_KEY and OBJ_POINTER are mutually exclusive options.
00933     */
00934    OBJ_KEY = (1 << 6),
00935 };
00936 
00937 /*!
00938  * Type of a generic function to generate a hash value from an object.
00939  * flags is ignored at the moment. Eventually, it will include the
00940  * value of OBJ_POINTER passed to ao2_callback().
00941  */
00942 typedef int (ao2_hash_fn)(const void *obj, int flags);
00943 
00944 /*! \name Object Containers
00945  * Here start declarations of containers.
00946  */
00947 /*@{ */
00948 struct ao2_container;
00949 
00950 /*!
00951  * \brief Allocate and initialize a hash container with the desired number of buckets.
00952  *
00953  * \details
00954  * We allocate space for a struct astobj_container, struct container
00955  * and the buckets[] array.
00956  *
00957  * \param options Container ao2 object options (See enum ao2_alloc_opts)
00958  * \param n_buckets Number of buckets for hash
00959  * \param hash_fn Pointer to a function computing a hash value. (NULL if everyting goes in first bucket.)
00960  * \param cmp_fn Pointer to a compare function used by ao2_find. (NULL to match everything)
00961  * \param tag used for debugging.
00962  *
00963  * \return A pointer to a struct container.
00964  *
00965  * \note Destructor is set implicitly.
00966  */
00967 
00968 #if defined(REF_DEBUG)
00969 
00970 #define ao2_t_container_alloc_options(options, n_buckets, hash_fn, cmp_fn, tag) \
00971    __ao2_container_alloc_debug((options), (n_buckets), (hash_fn), (cmp_fn), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00972 #define ao2_container_alloc_options(options, n_buckets, hash_fn, cmp_fn) \
00973    __ao2_container_alloc_debug((options), (n_buckets), (hash_fn), (cmp_fn), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00974 
00975 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
00976    __ao2_container_alloc_debug(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00977 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
00978    __ao2_container_alloc_debug(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
00979 
00980 #elif defined(__AST_DEBUG_MALLOC)
00981 
00982 #define ao2_t_container_alloc_options(options, n_buckets, hash_fn, cmp_fn, tag) \
00983    __ao2_container_alloc_debug((options), (n_buckets), (hash_fn), (cmp_fn), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00984 #define ao2_container_alloc_options(options, n_buckets, hash_fn, cmp_fn) \
00985    __ao2_container_alloc_debug((options), (n_buckets), (hash_fn), (cmp_fn), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00986 
00987 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
00988    __ao2_container_alloc_debug(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00989 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
00990    __ao2_container_alloc_debug(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
00991 
00992 #else
00993 
00994 #define ao2_t_container_alloc_options(options, n_buckets, hash_fn, cmp_fn, tag) \
00995    __ao2_container_alloc((options), (n_buckets), (hash_fn), (cmp_fn))
00996 #define ao2_container_alloc_options(options, n_buckets, hash_fn, cmp_fn) \
00997    __ao2_container_alloc((options), (n_buckets), (hash_fn), (cmp_fn))
00998 
00999 #define ao2_t_container_alloc(n_buckets, hash_fn, cmp_fn, tag) \
01000    __ao2_container_alloc(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn))
01001 #define ao2_container_alloc(n_buckets, hash_fn, cmp_fn) \
01002    __ao2_container_alloc(AO2_ALLOC_OPT_LOCK_MUTEX, (n_buckets), (hash_fn), (cmp_fn))
01003 
01004 #endif
01005 
01006 struct ao2_container *__ao2_container_alloc(unsigned int options,
01007    unsigned int n_buckets, ao2_hash_fn *hash_fn, ao2_callback_fn *cmp_fn);
01008 struct ao2_container *__ao2_container_alloc_debug(unsigned int options,
01009    unsigned int n_buckets, ao2_hash_fn *hash_fn, ao2_callback_fn *cmp_fn,
01010    const char *tag, const char *file, int line, const char *func, int ref_debug);
01011 
01012 /*! \brief
01013  * Returns the number of elements in a container.
01014  */
01015 int ao2_container_count(struct ao2_container *c);
01016 
01017 /*!
01018  * \brief Copy all object references in the src container into the dest container.
01019  * \since 11.0
01020  *
01021  * \param dest Container to copy src object references into.
01022  * \param src Container to copy all object references from.
01023  * \param flags OBJ_NOLOCK if a lock is already held on both containers.
01024  *    Otherwise, the src container is locked first.
01025  *
01026  * \pre The dest container must be empty.  If the duplication fails, the
01027  * dest container will be returned empty.
01028  *
01029  * \note This can potentially be expensive because a malloc is
01030  * needed for every object in the src container.
01031  *
01032  * \retval 0 on success.
01033  * \retval -1 on error.
01034  */
01035 int ao2_container_dup(struct ao2_container *dest, struct ao2_container *src, enum search_flags flags);
01036 
01037 /*!
01038  * \brief Create a clone/copy of the given container.
01039  * \since 11.0
01040  *
01041  * \param orig Container to copy all object references from.
01042  * \param flags OBJ_NOLOCK if a lock is already held on the container.
01043  *
01044  * \note This can potentially be expensive because a malloc is
01045  * needed for every object in the orig container.
01046  *
01047  * \retval Clone container on success.
01048  * \retval NULL on error.
01049  */
01050 struct ao2_container *__ao2_container_clone(struct ao2_container *orig, enum search_flags flags);
01051 struct ao2_container *__ao2_container_clone_debug(struct ao2_container *orig, enum search_flags flags, const char *tag, const char *file, int line, const char *func, int ref_debug);
01052 #if defined(REF_DEBUG)
01053 
01054 #define ao2_t_container_clone(orig, flags, tag) __ao2_container_clone_debug(orig, flags, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
01055 #define ao2_container_clone(orig, flags)     __ao2_container_clone_debug(orig, flags, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 1)
01056 
01057 #elif defined(__AST_DEBUG_MALLOC)
01058 
01059 #define ao2_t_container_clone(orig, flags, tag) __ao2_container_clone_debug(orig, flags, tag, __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
01060 #define ao2_container_clone(orig, flags)     __ao2_container_clone_debug(orig, flags, "", __FILE__, __LINE__, __PRETTY_FUNCTION__, 0)
01061 
01062 #else
01063 
01064 #define ao2_t_container_clone(orig, flags, tag) __ao2_container_clone(orig, flags)
01065 #define ao2_container_clone(orig, flags)     __ao2_container_clone(orig, flags)
01066 
01067 #endif
01068 
01069 /*@} */
01070 
01071 /*! \name Object Management
01072  * Here we have functions to manage objects.
01073  *
01074  * We can use the functions below on any kind of
01075  * object defined by the user.
01076  */
01077 /*@{ */
01078 
01079 /*!
01080  * \brief Add an object to a container.
01081  *
01082  * \param container The container to operate on.
01083  * \param obj The object to be added.
01084  * \param flags search_flags to control linking the object.  (OBJ_NOLOCK)
01085  * \param tag used for debugging.
01086  *
01087  * \retval NULL on errors.
01088  * \retval !NULL on success.
01089  *
01090  * This function inserts an object in a container according its key.
01091  *
01092  * \note Remember to set the key before calling this function.
01093  *
01094  * \note This function automatically increases the reference count to account
01095  *       for the reference that the container now holds to the object.
01096  */
01097 #ifdef REF_DEBUG
01098 
01099 #define ao2_t_link(container, obj, tag)               __ao2_link_debug((container), (obj), 0, (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01100 #define ao2_link(container, obj)                __ao2_link_debug((container), (obj), 0, "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01101 
01102 #define ao2_t_link_flags(container, obj, flags, tag)  __ao2_link_debug((container), (obj), (flags), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01103 #define ao2_link_flags(container, obj, flags)         __ao2_link_debug((container), (obj), (flags), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01104 
01105 #else
01106 
01107 #define ao2_t_link(container, obj, tag)               __ao2_link((container), (obj), 0)
01108 #define ao2_link(container, obj)                __ao2_link((container), (obj), 0)
01109 
01110 #define ao2_t_link_flags(container, obj, flags, tag)  __ao2_link((container), (obj), (flags))
01111 #define ao2_link_flags(container, obj, flags)         __ao2_link((container), (obj), (flags))
01112 
01113 #endif
01114 
01115 void *__ao2_link_debug(struct ao2_container *c, void *obj_new, int flags, const char *tag, const char *file, int line, const char *func);
01116 void *__ao2_link(struct ao2_container *c, void *obj_new, int flags);
01117 
01118 /*!
01119  * \brief Remove an object from a container
01120  *
01121  * \param container The container to operate on.
01122  * \param obj The object to unlink.
01123  * \param flags search_flags to control unlinking the object.  (OBJ_NOLOCK)
01124  * \param tag used for debugging.
01125  *
01126  * \retval NULL, always
01127  *
01128  * \note The object requested to be unlinked must be valid.  However, if it turns
01129  *       out that it is not in the container, this function is still safe to
01130  *       be called.
01131  *
01132  * \note If the object gets unlinked from the container, the container's
01133  *       reference to the object will be automatically released. (The
01134  *       refcount will be decremented).
01135  */
01136 #ifdef REF_DEBUG
01137 
01138 #define ao2_t_unlink(container, obj, tag)          __ao2_unlink_debug((container), (obj), 0, (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01139 #define ao2_unlink(container, obj)                 __ao2_unlink_debug((container), (obj), 0, "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01140 
01141 #define ao2_t_unlink_flags(container, obj, flags, tag)   __ao2_unlink_debug((container), (obj), (flags), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01142 #define ao2_unlink_flags(container, obj, flags)       __ao2_unlink_debug((container), (obj), (flags), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01143 
01144 #else
01145 
01146 #define ao2_t_unlink(container, obj, tag)          __ao2_unlink((container), (obj), 0)
01147 #define ao2_unlink(container, obj)                 __ao2_unlink((container), (obj), 0)
01148 
01149 #define ao2_t_unlink_flags(container, obj, flags, tag)   __ao2_unlink((container), (obj), (flags))
01150 #define ao2_unlink_flags(container, obj, flags)       __ao2_unlink((container), (obj), (flags))
01151 
01152 #endif
01153 
01154 void *__ao2_unlink_debug(struct ao2_container *c, void *obj, int flags, const char *tag, const char *file, int line, const char *func);
01155 void *__ao2_unlink(struct ao2_container *c, void *obj, int flags);
01156 
01157 
01158 /*@} */
01159 
01160 /*! \brief
01161  * ao2_callback() is a generic function that applies cb_fn() to all objects
01162  * in a container, as described below.
01163  *
01164  * \param c A pointer to the container to operate on.
01165  * \param flags A set of flags specifying the operation to perform,
01166  *  partially used by the container code, but also passed to
01167  *  the callback.
01168  *   - If OBJ_NODATA is set, ao2_callback will return NULL. No refcounts
01169  *     of any of the traversed objects will be incremented.
01170  *     On the converse, if it is NOT set (the default), the ref count
01171  *     of the first matching object will be incremented and returned.  If
01172  *     OBJ_MULTIPLE is set, the ref count of all matching objects will
01173  *     be incremented in an iterator for a temporary container and returned.
01174  *   - If OBJ_POINTER is set, the traversed items will be restricted
01175  *     to the objects in the bucket that the object key hashes to.
01176  * \param cb_fn A function pointer, that will be called on all
01177  *  objects, to see if they match. This function returns CMP_MATCH
01178  *  if the object is matches the criteria; CMP_STOP if the traversal
01179  *  should immediately stop, or both (via bitwise ORing), if you find a
01180  *  match and want to end the traversal, and 0 if the object is not a match,
01181  *  but the traversal should continue. This is the function that is applied
01182  *  to each object traversed. Its arguments are:
01183  *      (void *obj, void *arg, int flags), where:
01184  *        obj is an object
01185  *        arg is the same as arg passed into ao2_callback
01186  *        flags is the same as flags passed into ao2_callback (flags are
01187  *         also used by ao2_callback).
01188  * \param arg passed to the callback.
01189  * \param tag used for debugging.
01190  *
01191  * \retval NULL on failure or no matching object found.
01192  *
01193  * \retval object found if OBJ_MULTIPLE is not set in the flags
01194  * parameter.
01195  *
01196  * \retval ao2_iterator pointer if OBJ_MULTIPLE is set in the
01197  * flags parameter.  The iterator must be destroyed with
01198  * ao2_iterator_destroy() when the caller no longer needs it.
01199  *
01200  * If the function returns any objects, their refcount is incremented,
01201  * and the caller is in charge of decrementing them once done.
01202  *
01203  * Typically, ao2_callback() is used for two purposes:
01204  * - to perform some action (including removal from the container) on one
01205  *   or more objects; in this case, cb_fn() can modify the object itself,
01206  *   and to perform deletion should set CMP_MATCH on the matching objects,
01207  *   and have OBJ_UNLINK set in flags.
01208  * - to look for a specific object in a container; in this case, cb_fn()
01209  *   should not modify the object, but just return a combination of
01210  *   CMP_MATCH and CMP_STOP on the desired object.
01211  * Other usages are also possible, of course.
01212  *
01213  * This function searches through a container and performs operations
01214  * on objects according on flags passed.
01215  * XXX describe better
01216  * The comparison is done calling the compare function set implicitly.
01217  * The arg pointer can be a pointer to an object or to a key,
01218  * we can say this looking at flags value.
01219  * If arg points to an object we will search for the object pointed
01220  * by this value, otherwise we search for a key value.
01221  * If the key is not unique we only find the first matching value.
01222  *
01223  * The use of flags argument is the follow:
01224  *
01225  *      OBJ_UNLINK              unlinks the object found
01226  *      OBJ_NODATA              on match, do return an object
01227  *                              Callbacks use OBJ_NODATA as a default
01228  *                              functions such as find() do
01229  *      OBJ_MULTIPLE            return multiple matches
01230  *                              Default is no.
01231  *      OBJ_POINTER             the pointer is an object pointer
01232  *      OBJ_KEY                 the pointer is to a hashable key
01233  *
01234  * \note When the returned object is no longer in use, ao2_ref() should
01235  * be used to free the additional reference possibly created by this function.
01236  *
01237  * @{
01238  */
01239 #ifdef REF_DEBUG
01240 
01241 #define ao2_t_callback(c, flags, cb_fn, arg, tag) \
01242    __ao2_callback_debug((c), (flags), (cb_fn), (arg), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01243 #define ao2_callback(c, flags, cb_fn, arg) \
01244    __ao2_callback_debug((c), (flags), (cb_fn), (arg), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
01245 
01246 #else
01247 
01248 #define ao2_t_callback(c, flags, cb_fn, arg, tag) \
01249    __ao2_callback((c), (flags), (cb_fn), (arg))
01250 #define ao2_callback(c, flags, cb_fn, arg) \
01251    __ao2_callback((c), (flags), (cb_fn), (arg))
01252 
01253 #endif
01254 
01255 void *__ao2_callback_debug(struct ao2_container *c, enum search_flags flags,
01256    ao2_callback_fn *cb_fn, void *arg, const char *tag, const char *file, int line,
01257    const char *func);
01258 void *__ao2_callback(struct ao2_container *c, enum search_flags flags, ao2_callback_fn *cb_fn, void *arg);
01259 
01260 /*! @} */
01261 
01262 /*! \brief
01263  * ao2_callback_data() is a generic function that applies cb_fn() to all objects
01264  * in a container.  It is functionally identical to ao2_callback() except that
01265  * instead of taking an ao2_callback_fn *, it takes an ao2_callback_data_fn *, and
01266  * allows the caller to pass in arbitrary data.
01267  *
01268  * This call would be used instead of ao2_callback() when the caller needs to pass
01269  * OBJ_POINTER as part of the flags argument (which in turn requires passing in a
01270  * prototype ao2 object for 'arg') and also needs access to other non-global data
01271  * to complete it's comparison or task.
01272  *
01273  * See the documentation for ao2_callback() for argument descriptions.
01274  *
01275  * \see ao2_callback()
01276  */
01277 #ifdef REF_DEBUG
01278 
01279 #define ao2_t_callback_data(container, flags, cb_fn, arg, data, tag) \
01280    __ao2_callback_data_debug((container), (flags), (cb_fn), (arg), (data), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01281 #define ao2_callback_data(container, flags, cb_fn, arg, data) \
01282    __ao2_callback_data_debug((container), (flags), (cb_fn), (arg), (data), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
01283 
01284 #else
01285 
01286 #define ao2_t_callback_data(container, flags, cb_fn, arg, data, tag) \
01287    __ao2_callback_data((container), (flags), (cb_fn), (arg), (data))
01288 #define ao2_callback_data(container, flags, cb_fn, arg, data) \
01289    __ao2_callback_data((container), (flags), (cb_fn), (arg), (data))
01290 
01291 #endif
01292 
01293 void *__ao2_callback_data_debug(struct ao2_container *c, enum search_flags flags,
01294    ao2_callback_data_fn *cb_fn, void *arg, void *data, const char *tag, const char *file,
01295    int line, const char *func);
01296 void *__ao2_callback_data(struct ao2_container *c, enum search_flags flags,
01297    ao2_callback_data_fn *cb_fn, void *arg, void *data);
01298 
01299 /*! ao2_find() is a short hand for ao2_callback(c, flags, c->cmp_fn, arg)
01300  * XXX possibly change order of arguments ?
01301  */
01302 #ifdef REF_DEBUG
01303 
01304 #define ao2_t_find(container, arg, flags, tag) \
01305    __ao2_find_debug((container), (arg), (flags), (tag), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01306 #define ao2_find(container, arg, flags) \
01307    __ao2_find_debug((container), (arg), (flags), "", __FILE__, __LINE__, __PRETTY_FUNCTION__)
01308 
01309 #else
01310 
01311 #define ao2_t_find(container, arg, flags, tag) \
01312    __ao2_find((container), (arg), (flags))
01313 #define ao2_find(container, arg, flags) \
01314    __ao2_find((container), (arg), (flags))
01315 
01316 #endif
01317 
01318 void *__ao2_find_debug(struct ao2_container *c, const void *arg, enum search_flags flags,
01319    const char *tag, const char *file, int line, const char *func);
01320 void *__ao2_find(struct ao2_container *c, const void *arg, enum search_flags flags);
01321 
01322 /*! \brief
01323  *
01324  *
01325  * When we need to walk through a container, we use an
01326  * ao2_iterator to keep track of the current position.
01327  *
01328  * Because the navigation is typically done without holding the
01329  * lock on the container across the loop, objects can be inserted or deleted
01330  * or moved while we work. As a consequence, there is no guarantee that
01331  * we manage to touch all the elements in the container, and it is possible
01332  * that we touch the same object multiple times.
01333  *
01334  * However, within the current hash table container, the following is true:
01335  *  - It is not possible to miss an object in the container while iterating
01336  *    unless it gets added after the iteration begins and is added to a bucket
01337  *    that is before the one the current object is in.  In this case, even if
01338  *    you locked the container around the entire iteration loop, you still would
01339  *    not see this object, because it would still be waiting on the container
01340  *    lock so that it can be added.
01341  *  - It would be extremely rare to see an object twice.  The only way this can
01342  *    happen is if an object got unlinked from the container and added again
01343  *    during the same iteration.  Furthermore, when the object gets added back,
01344  *    it has to be in the current or later bucket for it to be seen again.
01345  *
01346  * An iterator must be first initialized with ao2_iterator_init(),
01347  * then we can use o = ao2_iterator_next() to move from one
01348  * element to the next. Remember that the object returned by
01349  * ao2_iterator_next() has its refcount incremented,
01350  * and the reference must be explicitly released when done with it.
01351  *
01352  * In addition, ao2_iterator_init() will hold a reference to the container
01353  * being iterated, which will be freed when ao2_iterator_destroy() is called
01354  * to free up the resources used by the iterator (if any).
01355  *
01356  * Example:
01357  *
01358  *  \code
01359  *
01360  *  struct ao2_container *c = ... // the container we want to iterate on
01361  *  struct ao2_iterator i;
01362  *  struct my_obj *o;
01363  *
01364  *  i = ao2_iterator_init(c, flags);
01365  *
01366  *  while ((o = ao2_iterator_next(&i))) {
01367  *     ... do something on o ...
01368  *     ao2_ref(o, -1);
01369  *  }
01370  *
01371  *  ao2_iterator_destroy(&i);
01372  *
01373  *  \endcode
01374  *
01375  */
01376 
01377 /*! \brief
01378  * The astobj2 iterator
01379  *
01380  * \note You are not supposed to know the internals of an iterator!
01381  * We would like the iterator to be opaque, unfortunately
01382  * its size needs to be known if we want to store it around
01383  * without too much trouble.
01384  * Anyways...
01385  * The iterator has a pointer to the container, and a flags
01386  * field specifying various things e.g. whether the container
01387  * should be locked or not while navigating on it.
01388  * The iterator "points" to the current object, which is identified
01389  * by three values:
01390  *
01391  * - a bucket number;
01392  * - the object_id, which is also the container version number
01393  *   when the object was inserted. This identifies the object
01394  *   uniquely, however reaching the desired object requires
01395  *   scanning a list.
01396  * - a pointer, and a container version when we saved the pointer.
01397  *   If the container has not changed its version number, then we
01398  *   can safely follow the pointer to reach the object in constant time.
01399  *
01400  * Details are in the implementation of ao2_iterator_next()
01401  * A freshly-initialized iterator has bucket=0, version=0.
01402  */
01403 struct ao2_iterator {
01404    /*! the container */
01405    struct ao2_container *c;
01406    /*! operation flags */
01407    int flags;
01408    /*! current bucket */
01409    int bucket;
01410    /*! container version */
01411    unsigned int c_version;
01412    /*! pointer to the current object */
01413    void *obj;
01414    /*! container version when the object was created */
01415    unsigned int version;
01416 };
01417 
01418 /*! Flags that can be passed to ao2_iterator_init() to modify the behavior
01419  * of the iterator.
01420  */
01421 enum ao2_iterator_flags {
01422    /*!
01423     * \brief Assume that the ao2_container is already locked.
01424     *
01425     * \note For ao2_containers that have mutexes, no locking will
01426     * be done.
01427     *
01428     * \note For ao2_containers that have RWLOCKs, the lock will be
01429     * promoted to write mode as needed.  The lock will be returned
01430     * to the original locked state.
01431     *
01432     * \note Only use this flag if the ao2_container is manually
01433     * locked already.
01434     */
01435    AO2_ITERATOR_DONTLOCK = (1 << 0),
01436    /*!
01437     * Indicates that the iterator was dynamically allocated by
01438     * astobj2 API and should be freed by ao2_iterator_destroy().
01439     */
01440    AO2_ITERATOR_MALLOCD = (1 << 1),
01441    /*!
01442     * Indicates that before the iterator returns an object from
01443     * the container being iterated, the object should be unlinked
01444     * from the container.
01445     */
01446    AO2_ITERATOR_UNLINK = (1 << 2),
01447 };
01448 
01449 /*!
01450  * \brief Create an iterator for a container
01451  *
01452  * \param c the container
01453  * \param flags one or more flags from ao2_iterator_flags
01454  *
01455  * \retval the constructed iterator
01456  *
01457  * \note This function does \b not take a pointer to an iterator;
01458  *       rather, it returns an iterator structure that should be
01459  *       assigned to (overwriting) an existing iterator structure
01460  *       allocated on the stack or on the heap.
01461  *
01462  * This function will take a reference on the container being iterated.
01463  *
01464  */
01465 struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags);
01466 
01467 /*!
01468  * \brief Destroy a container iterator
01469  *
01470  * \param iter the iterator to destroy
01471  *
01472  * \retval none
01473  *
01474  * This function will release the container reference held by the iterator
01475  * and any other resources it may be holding.
01476  *
01477  */
01478 #if defined(TEST_FRAMEWORK)
01479 void ao2_iterator_destroy(struct ao2_iterator *iter) __attribute__((noinline));
01480 #else
01481 void ao2_iterator_destroy(struct ao2_iterator *iter);
01482 #endif
01483 #ifdef REF_DEBUG
01484 
01485 #define ao2_t_iterator_next(iter, tag) __ao2_iterator_next_debug((iter), (tag),  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01486 #define ao2_iterator_next(iter)        __ao2_iterator_next_debug((iter), "",  __FILE__, __LINE__, __PRETTY_FUNCTION__)
01487 
01488 #else
01489 
01490 #define ao2_t_iterator_next(iter, tag) __ao2_iterator_next((iter))
01491 #define ao2_iterator_next(iter)        __ao2_iterator_next((iter))
01492 
01493 #endif
01494 
01495 void *__ao2_iterator_next_debug(struct ao2_iterator *iter, const char *tag, const char *file, int line, const char *func);
01496 void *__ao2_iterator_next(struct ao2_iterator *iter);
01497 
01498 /* extra functions */
01499 void ao2_bt(void);   /* backtrace */
01500 
01501 /*! gcc __attribute__(cleanup()) functions
01502  * \note they must be able to handle NULL parameters because most of the
01503  * allocation/find functions can fail and we don't want to try to tear
01504  * down a NULL */
01505 void __ao2_cleanup(void *obj);
01506 void __ao2_cleanup_debug(void *obj, const char *file, int line, const char *function);
01507 #ifdef REF_DEBUG
01508 #define ao2_cleanup(obj) __ao2_cleanup_debug((obj), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01509 #else
01510 #define ao2_cleanup(obj) __ao2_cleanup(obj)
01511 #endif
01512 void ao2_iterator_cleanup(struct ao2_iterator *iter);
01513 #endif /* _ASTERISK_ASTOBJ2_H */