Merge "jansson-bundled: Patch for off-nominal crash."
[asterisk/asterisk.git] / funcs / func_lock.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007, Tilghman Lesher
5  *
6  * Tilghman Lesher <func_lock_2007@the-tilghman.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Dialplan mutexes
22  *
23  * \author Tilghman Lesher <func_lock_2007@the-tilghman.com>
24  *
25  * \ingroup functions
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 #include <signal.h>
36
37 #include "asterisk/lock.h"
38 #include "asterisk/file.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/module.h"
42 #include "asterisk/linkedlists.h"
43 #include "asterisk/astobj2.h"
44 #include "asterisk/utils.h"
45
46 /*** DOCUMENTATION
47         <function name="LOCK" language="en_US">
48                 <synopsis>
49                         Attempt to obtain a named mutex.
50                 </synopsis>
51                 <syntax>
52                         <parameter name="lockname" required="true" />
53                 </syntax>
54                 <description>
55                         <para>Attempts to grab a named lock exclusively, and prevents other channels from
56                         obtaining the same lock.  LOCK will wait for the lock to become available.
57                         Returns <literal>1</literal> if the lock was obtained or <literal>0</literal> on error.</para>
58                         <note><para>To avoid the possibility of a deadlock, LOCK will only attempt to
59                         obtain the lock for 3 seconds if the channel already has another lock.</para></note>
60                         <note>
61                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
62                                 is set to <literal>no</literal>, this function can only be executed from the
63                                 dialplan, and not directly from external protocols.</para>
64                         </note>
65                 </description>
66         </function>
67         <function name="TRYLOCK" language="en_US">
68                 <synopsis>
69                         Attempt to obtain a named mutex.
70                 </synopsis>
71                 <syntax>
72                         <parameter name="lockname" required="true" />
73                 </syntax>
74                 <description>
75                         <para>Attempts to grab a named lock exclusively, and prevents other channels
76                         from obtaining the same lock.  Returns <literal>1</literal> if the lock was
77                         available or <literal>0</literal> otherwise.</para>
78                         <note>
79                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
80                                 is set to <literal>no</literal>, this function can only be executed from the
81                                 dialplan, and not directly from external protocols.</para>
82                         </note>
83                 </description>
84         </function>
85         <function name="UNLOCK" language="en_US">
86                 <synopsis>
87                         Unlocks a named mutex.
88                 </synopsis>
89                 <syntax>
90                         <parameter name="lockname" required="true" />
91                 </syntax>
92                 <description>
93                         <para>Unlocks a previously locked mutex. Returns <literal>1</literal> if the channel
94                         had a lock or <literal>0</literal> otherwise.</para>
95                         <note><para>It is generally unnecessary to unlock in a hangup routine, as any locks
96                         held are automatically freed when the channel is destroyed.</para></note>
97                         <note>
98                                 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
99                                 is set to <literal>no</literal>, this function can only be executed from the
100                                 dialplan, and not directly from external protocols.</para>
101                         </note>
102                 </description>
103         </function>
104  ***/
105
106
107
108 static AST_LIST_HEAD_STATIC(locklist, lock_frame);
109
110 static void lock_free(void *data);
111 static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan);
112 static int unloading = 0;
113 static pthread_t broker_tid = AST_PTHREADT_NULL;
114
115 static const struct ast_datastore_info lock_info = {
116         .type = "MUTEX",
117         .destroy = lock_free,
118         .chan_fixup = lock_fixup,
119 };
120
121 struct lock_frame {
122         AST_LIST_ENTRY(lock_frame) entries;
123         ast_mutex_t mutex;
124         ast_cond_t cond;
125         /*! count is needed so if a recursive mutex exits early, we know how many times to unlock it. */
126         unsigned int count;
127         /*! Container of requesters for the named lock */
128         struct ao2_container *requesters;
129         /*! who owns us */
130         struct ast_channel *owner;
131         /*! name of the lock */
132         char name[0];
133 };
134
135 struct channel_lock_frame {
136         AST_LIST_ENTRY(channel_lock_frame) list;
137         /*! Need to save channel pointer here, because during destruction, we won't have it. */
138         struct ast_channel *channel;
139         struct lock_frame *lock_frame;
140 };
141
142 static void lock_free(void *data)
143 {
144         AST_LIST_HEAD(, channel_lock_frame) *oldlist = data;
145         struct channel_lock_frame *clframe;
146         AST_LIST_LOCK(oldlist);
147         while ((clframe = AST_LIST_REMOVE_HEAD(oldlist, list))) {
148                 /* Only unlock if we own the lock */
149                 if (clframe->channel == clframe->lock_frame->owner) {
150                         clframe->lock_frame->count = 0;
151                         clframe->lock_frame->owner = NULL;
152                 }
153                 ast_free(clframe);
154         }
155         AST_LIST_UNLOCK(oldlist);
156         AST_LIST_HEAD_DESTROY(oldlist);
157         ast_free(oldlist);
158 }
159
160 static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan)
161 {
162         struct ast_datastore *lock_store = ast_channel_datastore_find(oldchan, &lock_info, NULL);
163         AST_LIST_HEAD(, channel_lock_frame) *list;
164         struct channel_lock_frame *clframe = NULL;
165
166         if (!lock_store) {
167                 return;
168         }
169         list = lock_store->data;
170
171         AST_LIST_LOCK(list);
172         AST_LIST_TRAVERSE(list, clframe, list) {
173                 if (clframe->lock_frame->owner == oldchan) {
174                         clframe->lock_frame->owner = newchan;
175                 }
176                 /* We don't move requesters, because the thread stack is different */
177                 clframe->channel = newchan;
178         }
179         AST_LIST_UNLOCK(list);
180 }
181
182 static void *lock_broker(void *unused)
183 {
184         struct lock_frame *frame;
185         struct timespec forever = { 1000000, 0 };
186         for (;;) {
187                 int found_requester = 0;
188
189                 /* Test for cancel outside of the lock */
190                 pthread_testcancel();
191                 AST_LIST_LOCK(&locklist);
192
193                 AST_LIST_TRAVERSE(&locklist, frame, entries) {
194                         if (ao2_container_count(frame->requesters)) {
195                                 found_requester++;
196                                 ast_mutex_lock(&frame->mutex);
197                                 if (!frame->owner) {
198                                         ast_cond_signal(&frame->cond);
199                                 }
200                                 ast_mutex_unlock(&frame->mutex);
201                         }
202                 }
203
204                 AST_LIST_UNLOCK(&locklist);
205                 pthread_testcancel();
206
207                 /* If there are no requesters, then wait for a signal */
208                 if (!found_requester) {
209                         nanosleep(&forever, NULL);
210                 } else {
211                         sched_yield();
212                 }
213         }
214         /* Not reached */
215         return NULL;
216 }
217
218 static int ast_channel_hash_cb(const void *obj, const int flags)
219 {
220         const struct ast_channel *chan = obj;
221         return ast_str_case_hash(ast_channel_name(chan));
222 }
223
224 static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
225 {
226         struct ast_channel *chan = obj, *cmp_args = arg;
227         return strcasecmp(ast_channel_name(chan), ast_channel_name(cmp_args)) ? 0 : CMP_MATCH;
228 }
229
230 static int get_lock(struct ast_channel *chan, char *lockname, int trylock)
231 {
232         struct ast_datastore *lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
233         struct lock_frame *current;
234         struct channel_lock_frame *clframe = NULL;
235         AST_LIST_HEAD(, channel_lock_frame) *list;
236         int res = 0;
237         struct timespec timeout = { 0, };
238         struct timeval now;
239
240         if (!lock_store) {
241                 ast_debug(1, "Channel %s has no lock datastore, so we're allocating one.\n", ast_channel_name(chan));
242                 lock_store = ast_datastore_alloc(&lock_info, NULL);
243                 if (!lock_store) {
244                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  No locks will be obtained.\n");
245                         return -1;
246                 }
247
248                 list = ast_calloc(1, sizeof(*list));
249                 if (!list) {
250                         ast_log(LOG_ERROR,
251                                 "Unable to allocate datastore list head.  %sLOCK will fail.\n",
252                                 trylock ? "TRY" : "");
253                         ast_datastore_free(lock_store);
254                         return -1;
255                 }
256
257                 lock_store->data = list;
258                 AST_LIST_HEAD_INIT(list);
259                 ast_channel_datastore_add(chan, lock_store);
260         } else
261                 list = lock_store->data;
262
263         /* Lock already exists? */
264         AST_LIST_LOCK(&locklist);
265         AST_LIST_TRAVERSE(&locklist, current, entries) {
266                 if (strcmp(current->name, lockname) == 0) {
267                         break;
268                 }
269         }
270
271         if (!current) {
272                 if (unloading) {
273                         /* Don't bother */
274                         AST_LIST_UNLOCK(&locklist);
275                         return -1;
276                 }
277
278                 /* Create new lock entry */
279                 current = ast_calloc(1, sizeof(*current) + strlen(lockname) + 1);
280                 if (!current) {
281                         AST_LIST_UNLOCK(&locklist);
282                         return -1;
283                 }
284
285                 strcpy(current->name, lockname); /* SAFE */
286                 if ((res = ast_mutex_init(&current->mutex))) {
287                         ast_log(LOG_ERROR, "Unable to initialize mutex: %s\n", strerror(res));
288                         ast_free(current);
289                         AST_LIST_UNLOCK(&locklist);
290                         return -1;
291                 }
292                 if ((res = ast_cond_init(&current->cond, NULL))) {
293                         ast_log(LOG_ERROR, "Unable to initialize condition variable: %s\n", strerror(res));
294                         ast_mutex_destroy(&current->mutex);
295                         ast_free(current);
296                         AST_LIST_UNLOCK(&locklist);
297                         return -1;
298                 }
299                 if (!(current->requesters = ao2_container_alloc(1, ast_channel_hash_cb, ast_channel_cmp_cb))) {
300                         ast_mutex_destroy(&current->mutex);
301                         ast_cond_destroy(&current->cond);
302                         ast_free(current);
303                         AST_LIST_UNLOCK(&locklist);
304                         return -1;
305                 }
306                 AST_LIST_INSERT_TAIL(&locklist, current, entries);
307         }
308         AST_LIST_UNLOCK(&locklist);
309
310         /* Found lock or created one - now find or create the corresponding link in the channel */
311         AST_LIST_LOCK(list);
312         AST_LIST_TRAVERSE(list, clframe, list) {
313                 if (clframe->lock_frame == current) {
314                         break;
315                 }
316         }
317
318         if (!clframe) {
319                 if (unloading) {
320                         /* Don't bother */
321                         AST_LIST_UNLOCK(list);
322                         return -1;
323                 }
324
325                 if (!(clframe = ast_calloc(1, sizeof(*clframe)))) {
326                         ast_log(LOG_ERROR,
327                                 "Unable to allocate channel lock frame.  %sLOCK will fail.\n",
328                                 trylock ? "TRY" : "");
329                         AST_LIST_UNLOCK(list);
330                         return -1;
331                 }
332
333                 clframe->lock_frame = current;
334                 clframe->channel = chan;
335                 AST_LIST_INSERT_TAIL(list, clframe, list);
336         }
337         AST_LIST_UNLOCK(list);
338
339         /* If we already own the lock, then we're being called recursively.
340          * Keep track of how many times that is, because we need to unlock
341          * the same amount, before we'll release this one.
342          */
343         if (current->owner == chan) {
344                 current->count++;
345                 return 0;
346         }
347
348         /* Okay, we have both frames, so now we need to try to lock.
349          *
350          * Locking order: always lock locklist first.  We need the
351          * locklist lock because the broker thread counts whether
352          * there are requesters with the locklist lock held, and we
353          * need to hold it, so that when we send our signal, below,
354          * to wake up the broker thread, it definitely will see that
355          * a requester exists at that point in time.  Otherwise, we
356          * could add to the requesters after it has already seen that
357          * that lock is unoccupied and wait forever for another signal.
358          */
359         AST_LIST_LOCK(&locklist);
360         ast_mutex_lock(&current->mutex);
361         /* Add to requester list */
362         ao2_link(current->requesters, chan);
363         pthread_kill(broker_tid, SIGURG);
364         AST_LIST_UNLOCK(&locklist);
365
366         /* Wait up to three seconds from now for LOCK. */
367         now = ast_tvnow();
368         timeout.tv_sec = now.tv_sec + 3;
369         timeout.tv_nsec = now.tv_usec * 1000;
370
371         if (!current->owner
372                 || (!trylock
373                         && !(res = ast_cond_timedwait(&current->cond, &current->mutex, &timeout)))) {
374                 res = 0;
375                 current->owner = chan;
376                 current->count++;
377         } else {
378                 res = -1;
379         }
380         /* Remove from requester list */
381         ao2_unlink(current->requesters, chan);
382         ast_mutex_unlock(&current->mutex);
383
384         return res;
385 }
386
387 static int unlock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
388 {
389         struct ast_datastore *lock_store;
390         struct channel_lock_frame *clframe;
391         AST_LIST_HEAD(, channel_lock_frame) *list;
392
393         if (!chan) {
394                 return -1;
395         }
396
397         lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
398         if (!lock_store) {
399                 ast_log(LOG_WARNING, "No datastore for dialplan locks.  Nothing was ever locked!\n");
400                 ast_copy_string(buf, "0", len);
401                 return 0;
402         }
403
404         if (!(list = lock_store->data)) {
405                 ast_debug(1, "This should NEVER happen\n");
406                 ast_copy_string(buf, "0", len);
407                 return 0;
408         }
409
410         /* Find item in the channel list */
411         AST_LIST_LOCK(list);
412         AST_LIST_TRAVERSE(list, clframe, list) {
413                 if (clframe->lock_frame && clframe->lock_frame->owner == chan && strcmp(clframe->lock_frame->name, data) == 0) {
414                         break;
415                 }
416         }
417         /* We never destroy anything until channel destruction, which will never
418          * happen while this routine is executing, so we don't need to hold the
419          * lock beyond this point. */
420         AST_LIST_UNLOCK(list);
421
422         if (!clframe) {
423                 /* We didn't have this lock in the first place */
424                 ast_copy_string(buf, "0", len);
425                 return 0;
426         }
427
428         if (--clframe->lock_frame->count == 0) {
429                 clframe->lock_frame->owner = NULL;
430         }
431
432         ast_copy_string(buf, "1", len);
433         return 0;
434 }
435
436 static int lock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
437 {
438         if (!chan) {
439                 return -1;
440         }
441         ast_autoservice_start(chan);
442         ast_copy_string(buf, get_lock(chan, data, 0) ? "0" : "1", len);
443         ast_autoservice_stop(chan);
444
445         return 0;
446 }
447
448 static int trylock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
449 {
450         if (!chan) {
451                 return -1;
452         }
453         ast_autoservice_start(chan);
454         ast_copy_string(buf, get_lock(chan, data, 1) ? "0" : "1", len);
455         ast_autoservice_stop(chan);
456
457         return 0;
458 }
459
460 static struct ast_custom_function lock_function = {
461         .name = "LOCK",
462         .read = lock_read,
463         .read_max = 2,
464 };
465
466 static struct ast_custom_function trylock_function = {
467         .name = "TRYLOCK",
468         .read = trylock_read,
469         .read_max = 2,
470 };
471
472 static struct ast_custom_function unlock_function = {
473         .name = "UNLOCK",
474         .read = unlock_read,
475         .read_max = 2,
476 };
477
478 static int unload_module(void)
479 {
480         struct lock_frame *current;
481
482         /* Module flag */
483         unloading = 1;
484
485         AST_LIST_LOCK(&locklist);
486         while ((current = AST_LIST_REMOVE_HEAD(&locklist, entries))) {
487                 /* If any locks are currently in use, then we cannot unload this module */
488                 if (current->owner || ao2_container_count(current->requesters)) {
489                         /* Put it back */
490                         AST_LIST_INSERT_HEAD(&locklist, current, entries);
491                         AST_LIST_UNLOCK(&locklist);
492                         unloading = 0;
493                         return -1;
494                 }
495                 ast_mutex_destroy(&current->mutex);
496                 ao2_ref(current->requesters, -1);
497                 ast_free(current);
498         }
499
500         /* No locks left, unregister functions */
501         ast_custom_function_unregister(&lock_function);
502         ast_custom_function_unregister(&trylock_function);
503         ast_custom_function_unregister(&unlock_function);
504
505         if (broker_tid != AST_PTHREADT_NULL) {
506                 pthread_cancel(broker_tid);
507                 pthread_kill(broker_tid, SIGURG);
508                 pthread_join(broker_tid, NULL);
509         }
510
511         AST_LIST_UNLOCK(&locklist);
512
513         return 0;
514 }
515
516 static int load_module(void)
517 {
518         int res = ast_custom_function_register_escalating(&lock_function, AST_CFE_READ);
519         res |= ast_custom_function_register_escalating(&trylock_function, AST_CFE_READ);
520         res |= ast_custom_function_register_escalating(&unlock_function, AST_CFE_READ);
521
522         if (ast_pthread_create_background(&broker_tid, NULL, lock_broker, NULL)) {
523                 ast_log(LOG_ERROR, "Failed to start lock broker thread. Unloading func_lock module.\n");
524                 broker_tid = AST_PTHREADT_NULL;
525                 unload_module();
526                 return AST_MODULE_LOAD_DECLINE;
527         }
528
529         return res;
530 }
531
532 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan mutexes");