Asterisk - The Open Source Telephony Project GIT-master-8924258
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Modules Pages
func_lock.c
Go to the documentation of this file.
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"
43#include "asterisk/astobj2.h"
44#include "asterisk/utils.h"
45#include "asterisk/cli.h"
46
47/*** DOCUMENTATION
48 <function name="LOCK" language="en_US">
49 <since>
50 <version>1.6.0</version>
51 </since>
52 <synopsis>
53 Attempt to obtain a named mutex.
54 </synopsis>
55 <syntax>
56 <parameter name="lockname" required="true" />
57 </syntax>
58 <description>
59 <para>Attempts to grab a named lock exclusively, and prevents other channels from
60 obtaining the same lock. LOCK will wait for the lock to become available.
61 Returns <literal>1</literal> if the lock was obtained or <literal>0</literal> on error.</para>
62 <note><para>To avoid the possibility of a deadlock, LOCK will only attempt to
63 obtain the lock for 3 seconds if the channel already has another lock.</para></note>
64 <note>
65 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
66 is set to <literal>no</literal>, this function can only be executed from the
67 dialplan, and not directly from external protocols.</para>
68 </note>
69 </description>
70 <see-also>
71 <ref type="function">TRYLOCK</ref>
72 <ref type="function">UNLOCK</ref>
73 </see-also>
74 </function>
75 <function name="TRYLOCK" language="en_US">
76 <since>
77 <version>1.6.0</version>
78 </since>
79 <synopsis>
80 Attempt to obtain a named mutex.
81 </synopsis>
82 <syntax>
83 <parameter name="lockname" required="true" />
84 </syntax>
85 <description>
86 <para>Attempts to grab a named lock exclusively, and prevents other channels
87 from obtaining the same lock. Returns <literal>1</literal> if the lock was
88 available or <literal>0</literal> otherwise.</para>
89 <note>
90 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
91 is set to <literal>no</literal>, this function can only be executed from the
92 dialplan, and not directly from external protocols.</para>
93 </note>
94 </description>
95 <see-also>
96 <ref type="function">LOCK</ref>
97 <ref type="function">UNLOCK</ref>
98 </see-also>
99 </function>
100 <function name="UNLOCK" language="en_US">
101 <since>
102 <version>1.6.0</version>
103 </since>
104 <synopsis>
105 Unlocks a named mutex.
106 </synopsis>
107 <syntax>
108 <parameter name="lockname" required="true" />
109 </syntax>
110 <description>
111 <para>Unlocks a previously locked mutex. Returns <literal>1</literal> if the channel
112 had a lock or <literal>0</literal> otherwise.</para>
113 <note><para>It is generally unnecessary to unlock in a hangup routine, as any locks
114 held are automatically freed when the channel is destroyed.</para></note>
115 <note>
116 <para>If <literal>live_dangerously</literal> in <literal>asterisk.conf</literal>
117 is set to <literal>no</literal>, this function can only be executed from the
118 dialplan, and not directly from external protocols.</para>
119 </note>
120 </description>
121 <see-also>
122 <ref type="function">LOCK</ref>
123 <ref type="function">TRYLOCK</ref>
124 </see-also>
125 </function>
126 ***/
127
128
129
131
132static void lock_free(void *data);
133static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan);
134static int unloading = 0;
135
136static const struct ast_datastore_info lock_info = {
137 .type = "MUTEX",
138 .destroy = lock_free,
139 .chan_fixup = lock_fixup,
140};
141
146 /*! count is needed so if a recursive mutex exits early, we know how many times to unlock it. */
147 unsigned int count;
148 /*! Count of waiting of requesters for the named lock */
149 unsigned int requesters;
150 /*! who owns us */
152 /*! name of the lock */
153 char name[0];
154};
155
158 /*! Need to save channel pointer here, because during destruction, we won't have it. */
161};
162
163static void lock_free(void *data)
164{
165 AST_LIST_HEAD(, channel_lock_frame) *oldlist = data;
166 struct channel_lock_frame *clframe;
167 AST_LIST_LOCK(oldlist);
168 while ((clframe = AST_LIST_REMOVE_HEAD(oldlist, list))) {
169 /* Only unlock if we own the lock */
170 if (clframe->channel == clframe->lock_frame->owner) {
171 ast_mutex_lock(&clframe->lock_frame->mutex);
172 clframe->lock_frame->count = 0;
173 clframe->lock_frame->owner = NULL;
174 ast_cond_signal(&clframe->lock_frame->cond);
176 }
177 ast_free(clframe);
178 }
179 AST_LIST_UNLOCK(oldlist);
180 AST_LIST_HEAD_DESTROY(oldlist);
181 ast_free(oldlist);
182
184}
185
186static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan)
187{
188 struct ast_datastore *lock_store = ast_channel_datastore_find(oldchan, &lock_info, NULL);
190 struct channel_lock_frame *clframe = NULL;
191
192 if (!lock_store) {
193 return;
194 }
195 list = lock_store->data;
196
198 AST_LIST_TRAVERSE(list, clframe, list) {
199 if (clframe->lock_frame->owner == oldchan) {
200 clframe->lock_frame->owner = newchan;
201 }
202 clframe->channel = newchan;
203 }
205}
206
207static int get_lock(struct ast_channel *chan, char *lockname, int trylock)
208{
209 struct ast_datastore *lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
210 struct lock_frame *current;
211 struct channel_lock_frame *clframe = NULL;
213 int res = 0;
214 struct timespec timeout = { 0, };
215 struct timeval now;
216
217 if (!lock_store) {
218 if (unloading) {
219 ast_log(LOG_ERROR, "%sLOCK has no datastore and func_lock is unloading, failing.\n",
220 trylock ? "TRY" : "");
221 return -1;
222 }
223
224 lock_store = ast_datastore_alloc(&lock_info, NULL);
225 if (!lock_store) {
226 ast_log(LOG_ERROR, "Unable to allocate new datastore. No locks will be obtained.\n");
227 return -1;
228 }
229
230 list = ast_calloc(1, sizeof(*list));
231 if (!list) {
233 "Unable to allocate datastore list head. %sLOCK will fail.\n",
234 trylock ? "TRY" : "");
235 ast_datastore_free(lock_store);
236 return -1;
237 }
238
239 lock_store->data = list;
240 AST_LIST_HEAD_INIT(list);
241 ast_channel_datastore_add(chan, lock_store);
242
243 /* We cannot unload until this channel has released the lock_store */
245 } else
246 list = lock_store->data;
247
248 /* Lock already exists? */
251 if (strcmp(current->name, lockname) == 0) {
252 break;
253 }
254 }
255
256 if (!current) {
257 if (unloading) {
259 "Lock doesn't exist whilst unloading. %sLOCK will fail.\n",
260 trylock ? "TRY" : "");
261 /* Don't bother */
263 return -1;
264 }
265
266 /* Create new lock entry */
267 current = ast_calloc(1, sizeof(*current) + strlen(lockname) + 1);
268 if (!current) {
270 return -1;
271 }
272
273 strcpy(current->name, lockname); /* SAFE */
274 if ((res = ast_mutex_init(&current->mutex))) {
275 ast_log(LOG_ERROR, "Unable to initialize mutex: %s\n", strerror(res));
278 return -1;
279 }
280 if ((res = ast_cond_init(&current->cond, NULL))) {
281 ast_log(LOG_ERROR, "Unable to initialize condition variable: %s\n", strerror(res));
282 ast_mutex_destroy(&current->mutex);
285 return -1;
286 }
288 }
289 /* Add to requester list */
290 ast_mutex_lock(&current->mutex);
291 current->requesters++;
292 ast_mutex_unlock(&current->mutex);
294
295 /* Found lock or created one - now find or create the corresponding link in the channel */
296 AST_LIST_LOCK(list);
297 AST_LIST_TRAVERSE(list, clframe, list) {
298 if (clframe->lock_frame == current) {
299 break;
300 }
301 }
302
303 if (!clframe) {
304 if (unloading) {
306 "Busy unloading. %sLOCK will fail.\n",
307 trylock ? "TRY" : "");
308 /* Don't bother */
309 ast_mutex_lock(&current->mutex);
310 current->requesters--;
311 ast_mutex_unlock(&current->mutex);
312 AST_LIST_UNLOCK(list);
313 return -1;
314 }
315
316 if (!(clframe = ast_calloc(1, sizeof(*clframe)))) {
318 "Unable to allocate channel lock frame. %sLOCK will fail.\n",
319 trylock ? "TRY" : "");
320 ast_mutex_lock(&current->mutex);
321 current->requesters--;
322 ast_mutex_unlock(&current->mutex);
323 AST_LIST_UNLOCK(list);
324 return -1;
325 }
326
327 clframe->lock_frame = current;
328 clframe->channel = chan;
329 AST_LIST_INSERT_TAIL(list, clframe, list);
330 }
331 AST_LIST_UNLOCK(list);
332
333 /* If we already own the lock, then we're being called recursively.
334 * Keep track of how many times that is, because we need to unlock
335 * the same amount, before we'll release this one.
336 */
337 if (current->owner == chan) {
338 /* We're not a requester, we already have it */
339 ast_mutex_lock(&current->mutex);
340 current->requesters--;
341 ast_mutex_unlock(&current->mutex);
342 current->count++;
343 return 0;
344 }
345
346 /* Wait up to three seconds from now for LOCK. */
347 now = ast_tvnow();
348 timeout.tv_sec = now.tv_sec + 3;
349 timeout.tv_nsec = now.tv_usec * 1000;
350
351 ast_mutex_lock(&current->mutex);
352
353 res = 0;
354 while (!trylock && !res && current->owner) {
355 res = ast_cond_timedwait(&current->cond, &current->mutex, &timeout);
356 }
357 if (current->owner) {
358 /* timeout;
359 * trylock; or
360 * cond_timedwait failed.
361 *
362 * either way, we fail to obtain the lock.
363 */
364 res = -1;
365 } else {
366 current->owner = chan;
367 current->count++;
368 res = 0;
369 }
370 /* Remove from requester list */
371 current->requesters--;
372 if (res && unloading)
373 ast_cond_signal(&current->cond);
374 ast_mutex_unlock(&current->mutex);
375
376 return res;
377}
378
379static int unlock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
380{
381 struct ast_datastore *lock_store;
382 struct channel_lock_frame *clframe;
384
385 if (!chan) {
386 return -1;
387 }
388
389 lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
390 if (!lock_store) {
391 ast_log(LOG_WARNING, "No datastore for dialplan locks. Nothing was ever locked!\n");
392 ast_copy_string(buf, "0", len);
393 return 0;
394 }
395
396 if (!(list = lock_store->data)) {
397 ast_debug(1, "This should NEVER happen\n");
398 ast_copy_string(buf, "0", len);
399 return 0;
400 }
401
402 /* Find item in the channel list */
404 AST_LIST_TRAVERSE(list, clframe, list) {
405 if (clframe->lock_frame && clframe->lock_frame->owner == chan && strcmp(clframe->lock_frame->name, data) == 0) {
406 break;
407 }
408 }
409 /* We never destroy anything until channel destruction, which will never
410 * happen while this routine is executing, so we don't need to hold the
411 * lock beyond this point. */
413
414 if (!clframe) {
415 /* We didn't have this lock in the first place */
416 ast_copy_string(buf, "0", len);
417 return 0;
418 }
419
420 if (--clframe->lock_frame->count == 0) {
421 ast_mutex_lock(&clframe->lock_frame->mutex);
422 clframe->lock_frame->owner = NULL;
423 ast_cond_signal(&clframe->lock_frame->cond);
425 }
426
427 ast_copy_string(buf, "1", len);
428 return 0;
429}
430
431static int lock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
432{
433 if (!chan) {
434 return -1;
435 }
437 ast_copy_string(buf, get_lock(chan, data, 0) ? "0" : "1", len);
439
440 return 0;
441}
442
443static int trylock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
444{
445 if (!chan) {
446 return -1;
447 }
449 ast_copy_string(buf, get_lock(chan, data, 1) ? "0" : "1", len);
451
452 return 0;
453}
454
455static char *handle_cli_locks_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
456{
457 int c = 0;
458 struct lock_frame* current;
459 switch (cmd) {
460 case CLI_INIT:
461 e->command = "dialplan locks show";
462 e->usage =
463 "Usage: dialplan locks show\n"
464 " List all locks known to func_lock, along with their current status.\n";
465 return NULL;
466 case CLI_GENERATE:
467 return NULL;
468 }
469
470 ast_cli(a->fd, "func_lock locks:\n");
471 ast_cli(a->fd, "%-40s Requesters Owner\n", "Name");
474 ast_mutex_lock(&current->mutex);
475 ast_cli(a->fd, "%-40s %-10d %s\n", current->name, current->requesters,
476 current->owner ? ast_channel_name(current->owner) : "(unlocked)");
477 ast_mutex_unlock(&current->mutex);
478 c++;
479 }
481 ast_cli(a->fd, "%d total locks listed.\n", c);
482
483 return 0;
484}
485
487 .name = "LOCK",
488 .read = lock_read,
489 .read_max = 2,
490};
491
493 .name = "TRYLOCK",
494 .read = trylock_read,
495 .read_max = 2,
496};
497
499 .name = "UNLOCK",
500 .read = unlock_read,
501 .read_max = 2,
502};
503
504static struct ast_cli_entry cli_locks_show = AST_CLI_DEFINE(handle_cli_locks_show, "List func_lock locks.");
505
506static int unload_module(void)
507{
508 struct lock_frame *current;
509
510 /* Module flag */
511 unloading = 1;
512
513 /* Make it impossible for new requesters to be added
514 * NOTE: channels could already be in get_lock() */
517
519
522 int warned = 0;
523 ast_mutex_lock(&current->mutex);
524 while (current->owner || current->requesters) {
525 if (!warned) {
526 ast_log(LOG_WARNING, "Waiting for %d requesters for %s lock %s.\n",
527 current->requesters, current->owner ? "locked" : "unlocked",
528 current->name);
529 warned = 1;
530 }
531 /* either the mutex is locked, or other parties are currently in get_lock,
532 * we need to wait for all of those to clear first */
533 ast_cond_wait(&current->cond, &current->mutex);
534 }
535 ast_mutex_unlock(&current->mutex);
536 /* At this point we know:
537 * 1. the lock has been released,
538 * 2. there are no requesters (nor should any be able to sneak in).
539 */
540 ast_mutex_destroy(&current->mutex);
543 }
546
547 /* At this point we can safely stop access to UNLOCK */
549
550 return 0;
551}
552
553static int load_module(void)
554{
559
560 return res;
561}
562
Asterisk main include file. File version handling, generic pbx functions.
#define ast_free(a)
Definition: astmm.h:180
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:202
#define ast_log
Definition: astobj2.c:42
General Asterisk PBX channel definitions.
const char * ast_channel_name(const struct ast_channel *chan)
int ast_autoservice_stop(struct ast_channel *chan)
Stop servicing a channel for us...
Definition: autoservice.c:266
int ast_channel_datastore_add(struct ast_channel *chan, struct ast_datastore *datastore)
Add a datastore to a channel.
Definition: channel.c:2414
int ast_autoservice_start(struct ast_channel *chan)
Automatically service a channel for us...
Definition: autoservice.c:200
struct ast_datastore * ast_channel_datastore_find(struct ast_channel *chan, const struct ast_datastore_info *info, const char *uid)
Find a datastore on a channel.
Definition: channel.c:2428
Standard Command Line Interface.
int ast_cli_unregister(struct ast_cli_entry *e)
Unregisters a command or an array of commands.
Definition: main/cli.c:2439
#define ast_cli_register(e)
Registers a command or an array of commands.
Definition: cli.h:256
#define AST_CLI_DEFINE(fn, txt,...)
Definition: cli.h:197
void ast_cli(int fd, const char *fmt,...)
Definition: clicompat.c:6
@ CLI_INIT
Definition: cli.h:152
@ CLI_GENERATE
Definition: cli.h:153
#define ast_datastore_alloc(info, uid)
Definition: datastore.h:85
int ast_datastore_free(struct ast_datastore *datastore)
Free a data store object.
Definition: datastore.c:68
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
Generic File Format Support. Should be included by clients of the file handling routines....
static struct ast_custom_function trylock_function
Definition: func_lock.c:492
static struct ast_custom_function lock_function
Definition: func_lock.c:486
static struct ast_cli_entry cli_locks_show
Definition: func_lock.c:504
static const struct ast_datastore_info lock_info
Definition: func_lock.c:136
static void lock_free(void *data)
Definition: func_lock.c:163
static struct ast_custom_function unlock_function
Definition: func_lock.c:498
static int unlock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_lock.c:379
static int unloading
Definition: func_lock.c:134
static int trylock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_lock.c:443
static int lock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
Definition: func_lock.c:431
static void lock_fixup(void *data, struct ast_channel *oldchan, struct ast_channel *newchan)
Definition: func_lock.c:186
static int get_lock(struct ast_channel *chan, char *lockname, int trylock)
Definition: func_lock.c:207
static int load_module(void)
Definition: func_lock.c:553
static char * handle_cli_locks_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
Definition: func_lock.c:455
static int unload_module(void)
Definition: func_lock.c:506
static int len(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t buflen)
#define ast_debug(level,...)
Log a DEBUG message.
#define LOG_ERROR
#define LOG_WARNING
A set of macros to manage forward-linked lists.
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:291
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
Definition: linkedlists.h:491
#define AST_LIST_HEAD_DESTROY(head)
Destroys a list head structure.
Definition: linkedlists.h:653
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:731
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:410
#define AST_LIST_HEAD_INIT(head)
Initializes a list head structure.
Definition: linkedlists.h:626
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:40
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
Definition: linkedlists.h:833
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:140
#define AST_LIST_HEAD(name, type)
Defines a structure to be used to hold a list of specified type.
Definition: linkedlists.h:173
Asterisk locking-related definitions:
#define ast_cond_destroy(cond)
Definition: lock.h:206
#define ast_cond_wait(cond, mutex)
Definition: lock.h:209
#define ast_cond_init(cond, attr)
Definition: lock.h:205
#define ast_cond_timedwait(cond, mutex, time)
Definition: lock.h:210
#define ast_mutex_init(pmutex)
Definition: lock.h:190
#define ast_mutex_unlock(a)
Definition: lock.h:194
pthread_cond_t ast_cond_t
Definition: lock.h:182
#define ast_mutex_destroy(a)
Definition: lock.h:192
#define ast_mutex_lock(a)
Definition: lock.h:193
#define ast_cond_signal(cond)
Definition: lock.h:207
size_t current
Definition: main/cli.c:113
Asterisk module definitions.
#define ast_module_unref(mod)
Release a reference to the module.
Definition: module.h:483
#define AST_MODULE_INFO_STANDARD(keystr, desc)
Definition: module.h:581
#define ast_module_ref(mod)
Hold a reference to the module.
Definition: module.h:457
#define ASTERISK_GPL_KEY
The text the key() function should return.
Definition: module.h:46
Core PBX routines and definitions.
#define ast_custom_function_register_escalating(acf, escalation)
Register a custom function which requires escalated privileges.
Definition: pbx.h:1568
int ast_custom_function_unregister(struct ast_custom_function *acf)
Unregister a custom function.
@ AST_CFE_READ
Definition: pbx.h:1551
#define NULL
Definition: resample.c:96
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:425
Main Channel structure associated with a channel.
descriptor for a cli entry.
Definition: cli.h:171
char * command
Definition: cli.h:186
const char * usage
Definition: cli.h:177
Data structure associated with a custom dialplan function.
Definition: pbx.h:118
const char * name
Definition: pbx.h:119
Structure for a data store type.
Definition: datastore.h:31
const char * type
Definition: datastore.h:32
Structure for a data store object.
Definition: datastore.h:64
void * data
Definition: datastore.h:66
struct ast_module * self
Definition: module.h:356
Structure for mutex and tracking information.
Definition: lock.h:139
struct channel_lock_frame::@174 list
struct ast_channel * channel
Definition: func_lock.c:159
struct lock_frame * lock_frame
Definition: func_lock.c:160
unsigned int requesters
Definition: func_lock.c:149
unsigned int count
Definition: func_lock.c:147
ast_cond_t cond
Definition: func_lock.c:145
ast_mutex_t mutex
Definition: func_lock.c:144
struct lock_frame::@173 entries
struct ast_channel * owner
Definition: func_lock.c:151
char name[0]
Definition: func_lock.c:153
static struct test_val a
static struct test_val c
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
Definition: time.h:159
Utility functions.