func_lock.c 13 KB

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