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