sched.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2005, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.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 Scheduler Routines (from cheops-NG)
  21. *
  22. * \author Mark Spencer <markster@digium.com>
  23. */
  24. #include "asterisk.h"
  25. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  26. #ifdef DEBUG_SCHEDULER
  27. #define DEBUG(a) do { \
  28. if (option_debug) \
  29. DEBUG_M(a) \
  30. } while (0)
  31. #else
  32. #define DEBUG(a)
  33. #endif
  34. #include <sys/time.h>
  35. #include "asterisk/sched.h"
  36. #include "asterisk/channel.h"
  37. #include "asterisk/lock.h"
  38. #include "asterisk/utils.h"
  39. #include "asterisk/linkedlists.h"
  40. #include "asterisk/dlinkedlists.h"
  41. #include "asterisk/hashtab.h"
  42. struct sched {
  43. AST_DLLIST_ENTRY(sched) list;
  44. int id; /*!< ID number of event */
  45. struct timeval when; /*!< Absolute time event should take place */
  46. int resched; /*!< When to reschedule */
  47. int variable; /*!< Use return value from callback to reschedule */
  48. const void *data; /*!< Data */
  49. ast_sched_cb callback; /*!< Callback */
  50. };
  51. struct sched_context {
  52. ast_mutex_t lock;
  53. unsigned int eventcnt; /*!< Number of events processed */
  54. unsigned int schedcnt; /*!< Number of outstanding schedule events */
  55. unsigned int highwater; /*!< highest count so far */
  56. AST_DLLIST_HEAD_NOLOCK(, sched) schedq; /*!< Schedule entry and main queue */
  57. struct ast_hashtab *schedq_ht; /*!< hash table for fast searching */
  58. #ifdef SCHED_MAX_CACHE
  59. AST_LIST_HEAD_NOLOCK(, sched) schedc; /*!< Cache of unused schedule structures and how many */
  60. unsigned int schedccnt;
  61. #endif
  62. };
  63. /* hash routines for sched */
  64. static int sched_cmp(const void *a, const void *b)
  65. {
  66. const struct sched *as = a;
  67. const struct sched *bs = b;
  68. return as->id != bs->id; /* return 0 on a match like strcmp would */
  69. }
  70. static unsigned int sched_hash(const void *obj)
  71. {
  72. const struct sched *s = obj;
  73. unsigned int h = s->id;
  74. return h;
  75. }
  76. struct sched_context *sched_context_create(void)
  77. {
  78. struct sched_context *tmp;
  79. if (!(tmp = ast_calloc(1, sizeof(*tmp))))
  80. return NULL;
  81. ast_mutex_init(&tmp->lock);
  82. tmp->eventcnt = 1;
  83. tmp->schedq_ht = ast_hashtab_create(23, sched_cmp, ast_hashtab_resize_java, ast_hashtab_newsize_java, sched_hash, 1);
  84. return tmp;
  85. }
  86. void sched_context_destroy(struct sched_context *con)
  87. {
  88. struct sched *s;
  89. ast_mutex_lock(&con->lock);
  90. #ifdef SCHED_MAX_CACHE
  91. /* Eliminate the cache */
  92. while ((s = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
  93. ast_free(s);
  94. #endif
  95. /* And the queue */
  96. while ((s = AST_DLLIST_REMOVE_HEAD(&con->schedq, list)))
  97. ast_free(s);
  98. ast_hashtab_destroy(con->schedq_ht, NULL);
  99. con->schedq_ht = NULL;
  100. /* And the context */
  101. ast_mutex_unlock(&con->lock);
  102. ast_mutex_destroy(&con->lock);
  103. ast_free(con);
  104. }
  105. static struct sched *sched_alloc(struct sched_context *con)
  106. {
  107. struct sched *tmp;
  108. /*
  109. * We keep a small cache of schedule entries
  110. * to minimize the number of necessary malloc()'s
  111. */
  112. #ifdef SCHED_MAX_CACHE
  113. if ((tmp = AST_LIST_REMOVE_HEAD(&con->schedc, list)))
  114. con->schedccnt--;
  115. else
  116. #endif
  117. tmp = ast_calloc(1, sizeof(*tmp));
  118. return tmp;
  119. }
  120. static void sched_release(struct sched_context *con, struct sched *tmp)
  121. {
  122. /*
  123. * Add to the cache, or just free() if we
  124. * already have too many cache entries
  125. */
  126. #ifdef SCHED_MAX_CACHE
  127. if (con->schedccnt < SCHED_MAX_CACHE) {
  128. AST_LIST_INSERT_HEAD(&con->schedc, tmp, list);
  129. con->schedccnt++;
  130. } else
  131. #endif
  132. ast_free(tmp);
  133. }
  134. /*! \brief
  135. * Return the number of milliseconds
  136. * until the next scheduled event
  137. */
  138. int ast_sched_wait(struct sched_context *con)
  139. {
  140. int ms;
  141. DEBUG(ast_debug(1, "ast_sched_wait()\n"));
  142. ast_mutex_lock(&con->lock);
  143. if (AST_DLLIST_EMPTY(&con->schedq)) {
  144. ms = -1;
  145. } else {
  146. ms = ast_tvdiff_ms(AST_DLLIST_FIRST(&con->schedq)->when, ast_tvnow());
  147. if (ms < 0)
  148. ms = 0;
  149. }
  150. ast_mutex_unlock(&con->lock);
  151. return ms;
  152. }
  153. /*! \brief
  154. * Take a sched structure and put it in the
  155. * queue, such that the soonest event is
  156. * first in the list.
  157. */
  158. static void schedule(struct sched_context *con, struct sched *s)
  159. {
  160. struct sched *cur = NULL;
  161. int ret;
  162. int df = 0;
  163. int de = 0;
  164. struct sched *first = AST_DLLIST_FIRST(&con->schedq);
  165. struct sched *last = AST_DLLIST_LAST(&con->schedq);
  166. if (first)
  167. df = ast_tvdiff_us(s->when, first->when);
  168. if (last)
  169. de = ast_tvdiff_us(s->when, last->when);
  170. if (df < 0)
  171. df = -df;
  172. if (de < 0)
  173. de = -de;
  174. if (df < de) {
  175. AST_DLLIST_TRAVERSE(&con->schedq, cur, list) {
  176. if (ast_tvcmp(s->when, cur->when) == -1) {
  177. AST_DLLIST_INSERT_BEFORE(&con->schedq, cur, s, list);
  178. break;
  179. }
  180. }
  181. if (!cur) {
  182. AST_DLLIST_INSERT_TAIL(&con->schedq, s, list);
  183. }
  184. } else {
  185. AST_DLLIST_TRAVERSE_BACKWARDS(&con->schedq, cur, list) {
  186. if (ast_tvcmp(s->when, cur->when) == 1) {
  187. AST_DLLIST_INSERT_AFTER(&con->schedq, cur, s, list);
  188. break;
  189. }
  190. }
  191. if (!cur) {
  192. AST_DLLIST_INSERT_HEAD(&con->schedq, s, list);
  193. }
  194. }
  195. ret = ast_hashtab_insert_safe(con->schedq_ht, s);
  196. if (!ret)
  197. ast_log(LOG_WARNING,"Schedule Queue entry %d is already in table!\n",s->id);
  198. con->schedcnt++;
  199. if (con->schedcnt > con->highwater)
  200. con->highwater = con->schedcnt;
  201. }
  202. /*! \brief
  203. * given the last event *tv and the offset in milliseconds 'when',
  204. * computes the next value,
  205. */
  206. static int sched_settime(struct timeval *t, int when)
  207. {
  208. struct timeval now = ast_tvnow();
  209. /*ast_debug(1, "TV -> %lu,%lu\n", tv->tv_sec, tv->tv_usec);*/
  210. if (ast_tvzero(*t)) /* not supplied, default to now */
  211. *t = now;
  212. *t = ast_tvadd(*t, ast_samp2tv(when, 1000));
  213. if (ast_tvcmp(*t, now) < 0) {
  214. *t = now;
  215. }
  216. return 0;
  217. }
  218. int ast_sched_replace_variable(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
  219. {
  220. /* 0 means the schedule item is new; do not delete */
  221. if (old_id > 0) {
  222. AST_SCHED_DEL(con, old_id);
  223. }
  224. return ast_sched_add_variable(con, when, callback, data, variable);
  225. }
  226. /*! \brief
  227. * Schedule callback(data) to happen when ms into the future
  228. */
  229. int ast_sched_add_variable(struct sched_context *con, int when, ast_sched_cb callback, const void *data, int variable)
  230. {
  231. struct sched *tmp;
  232. int res = -1;
  233. DEBUG(ast_debug(1, "ast_sched_add()\n"));
  234. ast_mutex_lock(&con->lock);
  235. if ((tmp = sched_alloc(con))) {
  236. tmp->id = con->eventcnt++;
  237. tmp->callback = callback;
  238. tmp->data = data;
  239. tmp->resched = when;
  240. tmp->variable = variable;
  241. tmp->when = ast_tv(0, 0);
  242. if (sched_settime(&tmp->when, when)) {
  243. sched_release(con, tmp);
  244. } else {
  245. schedule(con, tmp);
  246. res = tmp->id;
  247. }
  248. }
  249. #ifdef DUMP_SCHEDULER
  250. /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
  251. if (option_debug)
  252. ast_sched_dump(con);
  253. #endif
  254. ast_mutex_unlock(&con->lock);
  255. return res;
  256. }
  257. int ast_sched_replace(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
  258. {
  259. if (old_id > -1) {
  260. AST_SCHED_DEL(con, old_id);
  261. }
  262. return ast_sched_add(con, when, callback, data);
  263. }
  264. int ast_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
  265. {
  266. return ast_sched_add_variable(con, when, callback, data, 0);
  267. }
  268. const void *ast_sched_find_data(struct sched_context *con, int id)
  269. {
  270. struct sched tmp,*res;
  271. tmp.id = id;
  272. res = ast_hashtab_lookup(con->schedq_ht, &tmp);
  273. if (res)
  274. return res->data;
  275. return NULL;
  276. }
  277. /*! \brief
  278. * Delete the schedule entry with number
  279. * "id". It's nearly impossible that there
  280. * would be two or more in the list with that
  281. * id.
  282. */
  283. #ifndef AST_DEVMODE
  284. int ast_sched_del(struct sched_context *con, int id)
  285. #else
  286. int _ast_sched_del(struct sched_context *con, int id, const char *file, int line, const char *function)
  287. #endif
  288. {
  289. struct sched *s, tmp;
  290. DEBUG(ast_debug(1, "ast_sched_del(%d)\n", id));
  291. ast_mutex_lock(&con->lock);
  292. /* OK, this is the heart of the sched performance upgrade.
  293. If we have 4700 peers, we can have 4700+ entries in the
  294. schedq list. searching this would take time. So, I add a
  295. hashtab to the context to keep track of each entry, by id.
  296. I also leave the linked list alone, almost, -- I implement
  297. a doubly-linked list instead, because it would do little good
  298. to look up the id in a hashtab, and then have to run thru
  299. a couple thousand entries to remove it from the schedq list! */
  300. tmp.id = id;
  301. s = ast_hashtab_lookup(con->schedq_ht, &tmp);
  302. if (s) {
  303. struct sched *x = AST_DLLIST_REMOVE(&con->schedq, s, list);
  304. if (!x)
  305. ast_log(LOG_WARNING,"sched entry %d not in the schedq list?\n", s->id);
  306. if (!ast_hashtab_remove_this_object(con->schedq_ht, s))
  307. ast_log(LOG_WARNING,"Found sched entry %d, then couldn't remove it?\n", s->id);
  308. con->schedcnt--;
  309. sched_release(con, s);
  310. }
  311. #ifdef DUMP_SCHEDULER
  312. /* Dump contents of the context while we have the lock so nothing gets screwed up by accident. */
  313. if (option_debug)
  314. ast_sched_dump(con);
  315. #endif
  316. ast_mutex_unlock(&con->lock);
  317. if (!s) {
  318. ast_debug(1, "Attempted to delete nonexistent schedule entry %d!\n", id);
  319. #ifndef AST_DEVMODE
  320. ast_assert(s != NULL);
  321. #else
  322. _ast_assert(0, "s != NULL", file, line, function);
  323. #endif
  324. return -1;
  325. }
  326. return 0;
  327. }
  328. void ast_sched_report(struct sched_context *con, struct ast_str **buf, struct ast_cb_names *cbnames)
  329. {
  330. int i;
  331. struct sched *cur;
  332. int countlist[cbnames->numassocs + 1];
  333. memset(countlist, 0, sizeof(countlist));
  334. ast_str_set(buf, 0, " Highwater = %d\n schedcnt = %d\n", con->highwater, con->schedcnt);
  335. ast_mutex_lock(&con->lock);
  336. AST_DLLIST_TRAVERSE(&con->schedq, cur, list) {
  337. /* match the callback to the cblist */
  338. for (i = 0; i < cbnames->numassocs; i++) {
  339. if (cur->callback == cbnames->cblist[i]) {
  340. break;
  341. }
  342. }
  343. if (i < cbnames->numassocs) {
  344. countlist[i]++;
  345. } else {
  346. countlist[cbnames->numassocs]++;
  347. }
  348. }
  349. ast_mutex_unlock(&con->lock);
  350. for (i = 0; i < cbnames->numassocs; i++) {
  351. ast_str_append(buf, 0, " %s : %d\n", cbnames->list[i], countlist[i]);
  352. }
  353. ast_str_append(buf, 0, " <unknown> : %d\n", countlist[cbnames->numassocs]);
  354. }
  355. /*! \brief Dump the contents of the scheduler to LOG_DEBUG */
  356. void ast_sched_dump(struct sched_context *con)
  357. {
  358. struct sched *q;
  359. struct timeval when = ast_tvnow();
  360. #ifdef SCHED_MAX_CACHE
  361. ast_debug(1, "Asterisk Schedule Dump (%d in Q, %d Total, %d Cache, %d high-water)\n", con->schedcnt, con->eventcnt - 1, con->schedccnt, con->highwater);
  362. #else
  363. ast_debug(1, "Asterisk Schedule Dump (%d in Q, %d Total, %d high-water)\n", con->schedcnt, con->eventcnt - 1, con->highwater);
  364. #endif
  365. ast_debug(1, "=============================================================\n");
  366. ast_debug(1, "|ID Callback Data Time (sec:ms) |\n");
  367. ast_debug(1, "+-----+-----------------+-----------------+-----------------+\n");
  368. ast_mutex_lock(&con->lock);
  369. AST_DLLIST_TRAVERSE(&con->schedq, q, list) {
  370. struct timeval delta = ast_tvsub(q->when, when);
  371. ast_debug(1, "|%.4d | %-15p | %-15p | %.6ld : %.6ld |\n",
  372. q->id,
  373. q->callback,
  374. q->data,
  375. (long)delta.tv_sec,
  376. (long int)delta.tv_usec);
  377. }
  378. ast_mutex_unlock(&con->lock);
  379. ast_debug(1, "=============================================================\n");
  380. }
  381. /*! \brief
  382. * Launch all events which need to be run at this time.
  383. */
  384. int ast_sched_runq(struct sched_context *con)
  385. {
  386. struct sched *current;
  387. struct timeval when;
  388. int numevents;
  389. int res;
  390. DEBUG(ast_debug(1, "ast_sched_runq()\n"));
  391. ast_mutex_lock(&con->lock);
  392. for (numevents = 0; !AST_DLLIST_EMPTY(&con->schedq); numevents++) {
  393. /* schedule all events which are going to expire within 1ms.
  394. * We only care about millisecond accuracy anyway, so this will
  395. * help us get more than one event at one time if they are very
  396. * close together.
  397. */
  398. when = ast_tvadd(ast_tvnow(), ast_tv(0, 1000));
  399. if (ast_tvcmp(AST_DLLIST_FIRST(&con->schedq)->when, when) != -1)
  400. break;
  401. current = AST_DLLIST_REMOVE_HEAD(&con->schedq, list);
  402. if (!ast_hashtab_remove_this_object(con->schedq_ht, current))
  403. ast_log(LOG_ERROR,"Sched entry %d was in the schedq list but not in the hashtab???\n", current->id);
  404. con->schedcnt--;
  405. /*
  406. * At this point, the schedule queue is still intact. We
  407. * have removed the first event and the rest is still there,
  408. * so it's permissible for the callback to add new events, but
  409. * trying to delete itself won't work because it isn't in
  410. * the schedule queue. If that's what it wants to do, it
  411. * should return 0.
  412. */
  413. ast_mutex_unlock(&con->lock);
  414. res = current->callback(current->data);
  415. ast_mutex_lock(&con->lock);
  416. if (res) {
  417. /*
  418. * If they return non-zero, we should schedule them to be
  419. * run again.
  420. */
  421. if (sched_settime(&current->when, current->variable? res : current->resched)) {
  422. sched_release(con, current);
  423. } else
  424. schedule(con, current);
  425. } else {
  426. /* No longer needed, so release it */
  427. sched_release(con, current);
  428. }
  429. }
  430. ast_mutex_unlock(&con->lock);
  431. return numevents;
  432. }
  433. long ast_sched_when(struct sched_context *con,int id)
  434. {
  435. struct sched *s, tmp;
  436. long secs = -1;
  437. DEBUG(ast_debug(1, "ast_sched_when()\n"));
  438. ast_mutex_lock(&con->lock);
  439. /* these next 2 lines replace a lookup loop */
  440. tmp.id = id;
  441. s = ast_hashtab_lookup(con->schedq_ht, &tmp);
  442. if (s) {
  443. struct timeval now = ast_tvnow();
  444. secs = s->when.tv_sec - now.tv_sec;
  445. }
  446. ast_mutex_unlock(&con->lock);
  447. return secs;
  448. }