func_lock.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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_hash_cb(const void *obj, const int flags)
  197. {
  198. const struct ast_channel *chan = obj;
  199. return ast_str_case_hash(ast_channel_name(chan));
  200. }
  201. static int ast_channel_cmp_cb(void *obj, void *arg, int flags)
  202. {
  203. struct ast_channel *chan = obj, *cmp_args = arg;
  204. return strcasecmp(ast_channel_name(chan), ast_channel_name(cmp_args)) ? 0 : CMP_MATCH;
  205. }
  206. static int get_lock(struct ast_channel *chan, char *lockname, int trylock)
  207. {
  208. struct ast_datastore *lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
  209. struct lock_frame *current;
  210. struct channel_lock_frame *clframe = NULL;
  211. AST_LIST_HEAD(, channel_lock_frame) *list;
  212. int res = 0;
  213. struct timespec timeout = { 0, };
  214. struct timeval now;
  215. if (!lock_store) {
  216. ast_debug(1, "Channel %s has no lock datastore, so we're allocating one.\n", ast_channel_name(chan));
  217. lock_store = ast_datastore_alloc(&lock_info, NULL);
  218. if (!lock_store) {
  219. ast_log(LOG_ERROR, "Unable to allocate new datastore. No locks will be obtained.\n");
  220. return -1;
  221. }
  222. list = ast_calloc(1, sizeof(*list));
  223. if (!list) {
  224. ast_log(LOG_ERROR,
  225. "Unable to allocate datastore list head. %sLOCK will fail.\n",
  226. trylock ? "TRY" : "");
  227. ast_datastore_free(lock_store);
  228. return -1;
  229. }
  230. lock_store->data = list;
  231. AST_LIST_HEAD_INIT(list);
  232. ast_channel_datastore_add(chan, lock_store);
  233. } else
  234. list = lock_store->data;
  235. /* Lock already exists? */
  236. AST_LIST_LOCK(&locklist);
  237. AST_LIST_TRAVERSE(&locklist, current, entries) {
  238. if (strcmp(current->name, lockname) == 0) {
  239. break;
  240. }
  241. }
  242. if (!current) {
  243. if (unloading) {
  244. /* Don't bother */
  245. AST_LIST_UNLOCK(&locklist);
  246. return -1;
  247. }
  248. /* Create new lock entry */
  249. current = ast_calloc(1, sizeof(*current) + strlen(lockname) + 1);
  250. if (!current) {
  251. AST_LIST_UNLOCK(&locklist);
  252. return -1;
  253. }
  254. strcpy(current->name, lockname); /* SAFE */
  255. if ((res = ast_mutex_init(&current->mutex))) {
  256. ast_log(LOG_ERROR, "Unable to initialize mutex: %s\n", strerror(res));
  257. ast_free(current);
  258. AST_LIST_UNLOCK(&locklist);
  259. return -1;
  260. }
  261. if ((res = ast_cond_init(&current->cond, NULL))) {
  262. ast_log(LOG_ERROR, "Unable to initialize condition variable: %s\n", strerror(res));
  263. ast_mutex_destroy(&current->mutex);
  264. ast_free(current);
  265. AST_LIST_UNLOCK(&locklist);
  266. return -1;
  267. }
  268. if (!(current->requesters = ao2_container_alloc(1, ast_channel_hash_cb, ast_channel_cmp_cb))) {
  269. ast_mutex_destroy(&current->mutex);
  270. ast_cond_destroy(&current->cond);
  271. ast_free(current);
  272. AST_LIST_UNLOCK(&locklist);
  273. return -1;
  274. }
  275. AST_LIST_INSERT_TAIL(&locklist, current, entries);
  276. }
  277. AST_LIST_UNLOCK(&locklist);
  278. /* Found lock or created one - now find or create the corresponding link in the channel */
  279. AST_LIST_LOCK(list);
  280. AST_LIST_TRAVERSE(list, clframe, list) {
  281. if (clframe->lock_frame == current) {
  282. break;
  283. }
  284. }
  285. if (!clframe) {
  286. if (unloading) {
  287. /* Don't bother */
  288. AST_LIST_UNLOCK(list);
  289. return -1;
  290. }
  291. if (!(clframe = ast_calloc(1, sizeof(*clframe)))) {
  292. ast_log(LOG_ERROR,
  293. "Unable to allocate channel lock frame. %sLOCK will fail.\n",
  294. trylock ? "TRY" : "");
  295. AST_LIST_UNLOCK(list);
  296. return -1;
  297. }
  298. clframe->lock_frame = current;
  299. clframe->channel = chan;
  300. AST_LIST_INSERT_TAIL(list, clframe, list);
  301. }
  302. AST_LIST_UNLOCK(list);
  303. /* If we already own the lock, then we're being called recursively.
  304. * Keep track of how many times that is, because we need to unlock
  305. * the same amount, before we'll release this one.
  306. */
  307. if (current->owner == chan) {
  308. current->count++;
  309. return 0;
  310. }
  311. /* Okay, we have both frames, so now we need to try to lock.
  312. *
  313. * Locking order: always lock locklist first. We need the
  314. * locklist lock because the broker thread counts whether
  315. * there are requesters with the locklist lock held, and we
  316. * need to hold it, so that when we send our signal, below,
  317. * to wake up the broker thread, it definitely will see that
  318. * a requester exists at that point in time. Otherwise, we
  319. * could add to the requesters after it has already seen that
  320. * that lock is unoccupied and wait forever for another signal.
  321. */
  322. AST_LIST_LOCK(&locklist);
  323. ast_mutex_lock(&current->mutex);
  324. /* Add to requester list */
  325. ao2_link(current->requesters, chan);
  326. pthread_kill(broker_tid, SIGURG);
  327. AST_LIST_UNLOCK(&locklist);
  328. /* Wait up to three seconds from now for LOCK. */
  329. now = ast_tvnow();
  330. timeout.tv_sec = now.tv_sec + 3;
  331. timeout.tv_nsec = now.tv_usec * 1000;
  332. if (!current->owner
  333. || (!trylock
  334. && !(res = ast_cond_timedwait(&current->cond, &current->mutex, &timeout)))) {
  335. res = 0;
  336. current->owner = chan;
  337. current->count++;
  338. } else {
  339. res = -1;
  340. }
  341. /* Remove from requester list */
  342. ao2_unlink(current->requesters, chan);
  343. ast_mutex_unlock(&current->mutex);
  344. return res;
  345. }
  346. static int unlock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  347. {
  348. struct ast_datastore *lock_store;
  349. struct channel_lock_frame *clframe;
  350. AST_LIST_HEAD(, channel_lock_frame) *list;
  351. if (!chan) {
  352. return -1;
  353. }
  354. lock_store = ast_channel_datastore_find(chan, &lock_info, NULL);
  355. if (!lock_store) {
  356. ast_log(LOG_WARNING, "No datastore for dialplan locks. Nothing was ever locked!\n");
  357. ast_copy_string(buf, "0", len);
  358. return 0;
  359. }
  360. if (!(list = lock_store->data)) {
  361. ast_debug(1, "This should NEVER happen\n");
  362. ast_copy_string(buf, "0", len);
  363. return 0;
  364. }
  365. /* Find item in the channel list */
  366. AST_LIST_LOCK(list);
  367. AST_LIST_TRAVERSE(list, clframe, list) {
  368. if (clframe->lock_frame && clframe->lock_frame->owner == chan && strcmp(clframe->lock_frame->name, data) == 0) {
  369. break;
  370. }
  371. }
  372. /* We never destroy anything until channel destruction, which will never
  373. * happen while this routine is executing, so we don't need to hold the
  374. * lock beyond this point. */
  375. AST_LIST_UNLOCK(list);
  376. if (!clframe) {
  377. /* We didn't have this lock in the first place */
  378. ast_copy_string(buf, "0", len);
  379. return 0;
  380. }
  381. if (--clframe->lock_frame->count == 0) {
  382. clframe->lock_frame->owner = NULL;
  383. }
  384. ast_copy_string(buf, "1", len);
  385. return 0;
  386. }
  387. static int lock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  388. {
  389. if (!chan) {
  390. return -1;
  391. }
  392. ast_autoservice_start(chan);
  393. ast_copy_string(buf, get_lock(chan, data, 0) ? "0" : "1", len);
  394. ast_autoservice_stop(chan);
  395. return 0;
  396. }
  397. static int trylock_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
  398. {
  399. if (!chan) {
  400. return -1;
  401. }
  402. ast_autoservice_start(chan);
  403. ast_copy_string(buf, get_lock(chan, data, 1) ? "0" : "1", len);
  404. ast_autoservice_stop(chan);
  405. return 0;
  406. }
  407. static struct ast_custom_function lock_function = {
  408. .name = "LOCK",
  409. .read = lock_read,
  410. .read_max = 2,
  411. };
  412. static struct ast_custom_function trylock_function = {
  413. .name = "TRYLOCK",
  414. .read = trylock_read,
  415. .read_max = 2,
  416. };
  417. static struct ast_custom_function unlock_function = {
  418. .name = "UNLOCK",
  419. .read = unlock_read,
  420. .read_max = 2,
  421. };
  422. static int unload_module(void)
  423. {
  424. struct lock_frame *current;
  425. /* Module flag */
  426. unloading = 1;
  427. AST_LIST_LOCK(&locklist);
  428. while ((current = AST_LIST_REMOVE_HEAD(&locklist, entries))) {
  429. /* If any locks are currently in use, then we cannot unload this module */
  430. if (current->owner || ao2_container_count(current->requesters)) {
  431. /* Put it back */
  432. AST_LIST_INSERT_HEAD(&locklist, current, entries);
  433. AST_LIST_UNLOCK(&locklist);
  434. unloading = 0;
  435. return -1;
  436. }
  437. ast_mutex_destroy(&current->mutex);
  438. ao2_ref(current->requesters, -1);
  439. ast_free(current);
  440. }
  441. /* No locks left, unregister functions */
  442. ast_custom_function_unregister(&lock_function);
  443. ast_custom_function_unregister(&trylock_function);
  444. ast_custom_function_unregister(&unlock_function);
  445. if (broker_tid != AST_PTHREADT_NULL) {
  446. pthread_cancel(broker_tid);
  447. pthread_kill(broker_tid, SIGURG);
  448. pthread_join(broker_tid, NULL);
  449. }
  450. AST_LIST_UNLOCK(&locklist);
  451. return 0;
  452. }
  453. static int load_module(void)
  454. {
  455. int res = ast_custom_function_register_escalating(&lock_function, AST_CFE_READ);
  456. res |= ast_custom_function_register_escalating(&trylock_function, AST_CFE_READ);
  457. res |= ast_custom_function_register_escalating(&unlock_function, AST_CFE_READ);
  458. if (ast_pthread_create_background(&broker_tid, NULL, lock_broker, NULL)) {
  459. ast_log(LOG_ERROR, "Failed to start lock broker thread. Unloading func_lock module.\n");
  460. broker_tid = AST_PTHREADT_NULL;
  461. unload_module();
  462. return AST_MODULE_LOAD_DECLINE;
  463. }
  464. return res;
  465. }
  466. AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan mutexes");