func_lock.c 14 KB

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