thread.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. /* Thread management routine
  2. * Copyright (C) 1998, 2000 Kunihiro Ishiguro <kunihiro@zebra.org>
  3. *
  4. * This file is part of GNU Zebra.
  5. *
  6. * GNU Zebra is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the
  8. * Free Software Foundation; either version 2, or (at your option) any
  9. * later version.
  10. *
  11. * GNU Zebra is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with GNU Zebra; see the file COPYING. If not, write to the Free
  18. * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  19. * 02111-1307, USA.
  20. */
  21. /* #define DEBUG */
  22. #include <zebra.h>
  23. #include "thread.h"
  24. #include "memory.h"
  25. #include "log.h"
  26. #include "hash.h"
  27. #include "command.h"
  28. #include "sigevent.h"
  29. /* Recent absolute time of day */
  30. struct timeval recent_time;
  31. static struct timeval last_recent_time;
  32. /* Relative time, since startup */
  33. static struct timeval relative_time;
  34. static struct timeval relative_time_base;
  35. /* init flag */
  36. static unsigned short timers_inited;
  37. static struct hash *cpu_record = NULL;
  38. /* Struct timeval's tv_usec one second value. */
  39. #define TIMER_SECOND_MICRO 1000000L
  40. /* Adjust so that tv_usec is in the range [0,TIMER_SECOND_MICRO).
  41. And change negative values to 0. */
  42. static struct timeval
  43. timeval_adjust (struct timeval a)
  44. {
  45. while (a.tv_usec >= TIMER_SECOND_MICRO)
  46. {
  47. a.tv_usec -= TIMER_SECOND_MICRO;
  48. a.tv_sec++;
  49. }
  50. while (a.tv_usec < 0)
  51. {
  52. a.tv_usec += TIMER_SECOND_MICRO;
  53. a.tv_sec--;
  54. }
  55. if (a.tv_sec < 0)
  56. /* Change negative timeouts to 0. */
  57. a.tv_sec = a.tv_usec = 0;
  58. return a;
  59. }
  60. static struct timeval
  61. timeval_subtract (struct timeval a, struct timeval b)
  62. {
  63. struct timeval ret;
  64. ret.tv_usec = a.tv_usec - b.tv_usec;
  65. ret.tv_sec = a.tv_sec - b.tv_sec;
  66. return timeval_adjust (ret);
  67. }
  68. static long
  69. timeval_cmp (struct timeval a, struct timeval b)
  70. {
  71. return (a.tv_sec == b.tv_sec
  72. ? a.tv_usec - b.tv_usec : a.tv_sec - b.tv_sec);
  73. }
  74. static unsigned long
  75. timeval_elapsed (struct timeval a, struct timeval b)
  76. {
  77. return (((a.tv_sec - b.tv_sec) * TIMER_SECOND_MICRO)
  78. + (a.tv_usec - b.tv_usec));
  79. }
  80. #ifndef HAVE_CLOCK_MONOTONIC
  81. static void
  82. quagga_gettimeofday_relative_adjust (void)
  83. {
  84. struct timeval diff;
  85. if (timeval_cmp (recent_time, last_recent_time) < 0)
  86. {
  87. relative_time.tv_sec++;
  88. relative_time.tv_usec = 0;
  89. }
  90. else
  91. {
  92. diff = timeval_subtract (recent_time, last_recent_time);
  93. relative_time.tv_sec += diff.tv_sec;
  94. relative_time.tv_usec += diff.tv_usec;
  95. relative_time = timeval_adjust (relative_time);
  96. }
  97. last_recent_time = recent_time;
  98. }
  99. #endif /* !HAVE_CLOCK_MONOTONIC */
  100. /* gettimeofday wrapper, to keep recent_time updated */
  101. static int
  102. quagga_gettimeofday (struct timeval *tv)
  103. {
  104. int ret;
  105. assert (tv);
  106. if (!(ret = gettimeofday (&recent_time, NULL)))
  107. {
  108. /* init... */
  109. if (!timers_inited)
  110. {
  111. relative_time_base = last_recent_time = recent_time;
  112. timers_inited = 1;
  113. }
  114. /* avoid copy if user passed recent_time pointer.. */
  115. if (tv != &recent_time)
  116. *tv = recent_time;
  117. return 0;
  118. }
  119. return ret;
  120. }
  121. static int
  122. quagga_get_relative (struct timeval *tv)
  123. {
  124. int ret;
  125. #ifdef HAVE_CLOCK_MONOTONIC
  126. {
  127. struct timespec tp;
  128. if (!(ret = clock_gettime (CLOCK_MONOTONIC, &tp)))
  129. {
  130. relative_time.tv_sec = tp.tv_sec;
  131. relative_time.tv_usec = tp.tv_nsec / 1000;
  132. }
  133. }
  134. #else /* !HAVE_CLOCK_MONOTONIC */
  135. if (!(ret = quagga_gettimeofday (&recent_time)))
  136. quagga_gettimeofday_relative_adjust();
  137. #endif /* HAVE_CLOCK_MONOTONIC */
  138. if (tv)
  139. *tv = relative_time;
  140. return ret;
  141. }
  142. /* Get absolute time stamp, but in terms of the internal timer
  143. * Could be wrong, but at least won't go back.
  144. */
  145. static void
  146. quagga_real_stabilised (struct timeval *tv)
  147. {
  148. *tv = relative_time_base;
  149. tv->tv_sec += relative_time.tv_sec;
  150. tv->tv_usec += relative_time.tv_usec;
  151. *tv = timeval_adjust (*tv);
  152. }
  153. /* Exported Quagga timestamp function.
  154. * Modelled on POSIX clock_gettime.
  155. */
  156. int
  157. quagga_gettime (enum quagga_clkid clkid, struct timeval *tv)
  158. {
  159. switch (clkid)
  160. {
  161. case QUAGGA_CLK_REALTIME:
  162. return quagga_gettimeofday (tv);
  163. case QUAGGA_CLK_MONOTONIC:
  164. return quagga_get_relative (tv);
  165. case QUAGGA_CLK_REALTIME_STABILISED:
  166. quagga_real_stabilised (tv);
  167. return 0;
  168. default:
  169. errno = EINVAL;
  170. return -1;
  171. }
  172. }
  173. /* time_t value in terms of stabilised absolute time.
  174. * replacement for POSIX time()
  175. */
  176. time_t
  177. quagga_time (time_t *t)
  178. {
  179. struct timeval tv;
  180. quagga_real_stabilised (&tv);
  181. if (t)
  182. *t = tv.tv_sec;
  183. return tv.tv_sec;
  184. }
  185. /* Public export of recent_relative_time by value */
  186. struct timeval
  187. recent_relative_time (void)
  188. {
  189. return relative_time;
  190. }
  191. static unsigned int
  192. cpu_record_hash_key (struct cpu_thread_history *a)
  193. {
  194. return (uintptr_t) a->func;
  195. }
  196. static int
  197. cpu_record_hash_cmp (const struct cpu_thread_history *a,
  198. const struct cpu_thread_history *b)
  199. {
  200. return a->func == b->func;
  201. }
  202. static void *
  203. cpu_record_hash_alloc (struct cpu_thread_history *a)
  204. {
  205. struct cpu_thread_history *new;
  206. new = XCALLOC (MTYPE_THREAD_STATS, sizeof (struct cpu_thread_history));
  207. new->func = a->func;
  208. new->funcname = XSTRDUP(MTYPE_THREAD_FUNCNAME, a->funcname);
  209. return new;
  210. }
  211. static void
  212. cpu_record_hash_free (void *a)
  213. {
  214. struct cpu_thread_history *hist = a;
  215. XFREE (MTYPE_THREAD_FUNCNAME, hist->funcname);
  216. XFREE (MTYPE_THREAD_STATS, hist);
  217. }
  218. static inline void
  219. vty_out_cpu_thread_history(struct vty* vty,
  220. struct cpu_thread_history *a)
  221. {
  222. #ifdef HAVE_RUSAGE
  223. vty_out(vty, "%7ld.%03ld %9d %8ld %9ld %8ld %9ld",
  224. a->cpu.total/1000, a->cpu.total%1000, a->total_calls,
  225. a->cpu.total/a->total_calls, a->cpu.max,
  226. a->real.total/a->total_calls, a->real.max);
  227. #else
  228. vty_out(vty, "%7ld.%03ld %9d %8ld %9ld",
  229. a->real.total/1000, a->real.total%1000, a->total_calls,
  230. a->real.total/a->total_calls, a->real.max);
  231. #endif
  232. vty_out(vty, " %c%c%c%c%c%c %s%s",
  233. a->types & (1 << THREAD_READ) ? 'R':' ',
  234. a->types & (1 << THREAD_WRITE) ? 'W':' ',
  235. a->types & (1 << THREAD_TIMER) ? 'T':' ',
  236. a->types & (1 << THREAD_EVENT) ? 'E':' ',
  237. a->types & (1 << THREAD_EXECUTE) ? 'X':' ',
  238. a->types & (1 << THREAD_BACKGROUND) ? 'B' : ' ',
  239. a->funcname, VTY_NEWLINE);
  240. }
  241. static void
  242. cpu_record_hash_print(struct hash_backet *bucket,
  243. void *args[])
  244. {
  245. struct cpu_thread_history *totals = args[0];
  246. struct vty *vty = args[1];
  247. thread_type *filter = args[2];
  248. struct cpu_thread_history *a = bucket->data;
  249. a = bucket->data;
  250. if ( !(a->types & *filter) )
  251. return;
  252. vty_out_cpu_thread_history(vty,a);
  253. totals->total_calls += a->total_calls;
  254. totals->real.total += a->real.total;
  255. if (totals->real.max < a->real.max)
  256. totals->real.max = a->real.max;
  257. #ifdef HAVE_RUSAGE
  258. totals->cpu.total += a->cpu.total;
  259. if (totals->cpu.max < a->cpu.max)
  260. totals->cpu.max = a->cpu.max;
  261. #endif
  262. }
  263. static void
  264. cpu_record_print(struct vty *vty, thread_type filter)
  265. {
  266. struct cpu_thread_history tmp;
  267. void *args[3] = {&tmp, vty, &filter};
  268. memset(&tmp, 0, sizeof tmp);
  269. tmp.funcname = (char *)"TOTAL";
  270. tmp.types = filter;
  271. #ifdef HAVE_RUSAGE
  272. vty_out(vty, "%21s %18s %18s%s",
  273. "", "CPU (user+system):", "Real (wall-clock):", VTY_NEWLINE);
  274. #endif
  275. vty_out(vty, "Runtime(ms) Invoked Avg uSec Max uSecs");
  276. #ifdef HAVE_RUSAGE
  277. vty_out(vty, " Avg uSec Max uSecs");
  278. #endif
  279. vty_out(vty, " Type Thread%s", VTY_NEWLINE);
  280. hash_iterate(cpu_record,
  281. (void(*)(struct hash_backet*,void*))cpu_record_hash_print,
  282. args);
  283. if (tmp.total_calls > 0)
  284. vty_out_cpu_thread_history(vty, &tmp);
  285. }
  286. DEFUN(show_thread_cpu,
  287. show_thread_cpu_cmd,
  288. "show thread cpu [FILTER]",
  289. SHOW_STR
  290. "Thread information\n"
  291. "Thread CPU usage\n"
  292. "Display filter (rwtexb)\n")
  293. {
  294. int i = 0;
  295. thread_type filter = (thread_type) -1U;
  296. if (argc > 0)
  297. {
  298. filter = 0;
  299. while (argv[0][i] != '\0')
  300. {
  301. switch ( argv[0][i] )
  302. {
  303. case 'r':
  304. case 'R':
  305. filter |= (1 << THREAD_READ);
  306. break;
  307. case 'w':
  308. case 'W':
  309. filter |= (1 << THREAD_WRITE);
  310. break;
  311. case 't':
  312. case 'T':
  313. filter |= (1 << THREAD_TIMER);
  314. break;
  315. case 'e':
  316. case 'E':
  317. filter |= (1 << THREAD_EVENT);
  318. break;
  319. case 'x':
  320. case 'X':
  321. filter |= (1 << THREAD_EXECUTE);
  322. break;
  323. case 'b':
  324. case 'B':
  325. filter |= (1 << THREAD_BACKGROUND);
  326. break;
  327. default:
  328. break;
  329. }
  330. ++i;
  331. }
  332. if (filter == 0)
  333. {
  334. vty_out(vty, "Invalid filter \"%s\" specified,"
  335. " must contain at least one of 'RWTEXB'%s",
  336. argv[0], VTY_NEWLINE);
  337. return CMD_WARNING;
  338. }
  339. }
  340. cpu_record_print(vty, filter);
  341. return CMD_SUCCESS;
  342. }
  343. static void
  344. cpu_record_hash_clear (struct hash_backet *bucket,
  345. void *args)
  346. {
  347. thread_type *filter = args;
  348. struct cpu_thread_history *a = bucket->data;
  349. a = bucket->data;
  350. if ( !(a->types & *filter) )
  351. return;
  352. hash_release (cpu_record, bucket->data);
  353. }
  354. static void
  355. cpu_record_clear (thread_type filter)
  356. {
  357. thread_type *tmp = &filter;
  358. hash_iterate (cpu_record,
  359. (void (*) (struct hash_backet*,void*)) cpu_record_hash_clear,
  360. tmp);
  361. }
  362. DEFUN(clear_thread_cpu,
  363. clear_thread_cpu_cmd,
  364. "clear thread cpu [FILTER]",
  365. "Clear stored data\n"
  366. "Thread information\n"
  367. "Thread CPU usage\n"
  368. "Display filter (rwtexb)\n")
  369. {
  370. int i = 0;
  371. thread_type filter = (thread_type) -1U;
  372. if (argc > 0)
  373. {
  374. filter = 0;
  375. while (argv[0][i] != '\0')
  376. {
  377. switch ( argv[0][i] )
  378. {
  379. case 'r':
  380. case 'R':
  381. filter |= (1 << THREAD_READ);
  382. break;
  383. case 'w':
  384. case 'W':
  385. filter |= (1 << THREAD_WRITE);
  386. break;
  387. case 't':
  388. case 'T':
  389. filter |= (1 << THREAD_TIMER);
  390. break;
  391. case 'e':
  392. case 'E':
  393. filter |= (1 << THREAD_EVENT);
  394. break;
  395. case 'x':
  396. case 'X':
  397. filter |= (1 << THREAD_EXECUTE);
  398. break;
  399. case 'b':
  400. case 'B':
  401. filter |= (1 << THREAD_BACKGROUND);
  402. break;
  403. default:
  404. break;
  405. }
  406. ++i;
  407. }
  408. if (filter == 0)
  409. {
  410. vty_out(vty, "Invalid filter \"%s\" specified,"
  411. " must contain at least one of 'RWTEXB'%s",
  412. argv[0], VTY_NEWLINE);
  413. return CMD_WARNING;
  414. }
  415. }
  416. cpu_record_clear (filter);
  417. return CMD_SUCCESS;
  418. }
  419. /* List allocation and head/tail print out. */
  420. static void
  421. thread_list_debug (struct thread_list *list)
  422. {
  423. printf ("count [%d] head [%p] tail [%p]\n",
  424. list->count, list->head, list->tail);
  425. }
  426. /* Debug print for thread_master. */
  427. static void __attribute__ ((unused))
  428. thread_master_debug (struct thread_master *m)
  429. {
  430. printf ("-----------\n");
  431. printf ("readlist : ");
  432. thread_list_debug (&m->read);
  433. printf ("writelist : ");
  434. thread_list_debug (&m->write);
  435. printf ("timerlist : ");
  436. thread_list_debug (&m->timer);
  437. printf ("eventlist : ");
  438. thread_list_debug (&m->event);
  439. printf ("unuselist : ");
  440. thread_list_debug (&m->unuse);
  441. printf ("bgndlist : ");
  442. thread_list_debug (&m->background);
  443. printf ("total alloc: [%ld]\n", m->alloc);
  444. printf ("-----------\n");
  445. }
  446. /* Allocate new thread master. */
  447. struct thread_master *
  448. thread_master_create ()
  449. {
  450. if (cpu_record == NULL)
  451. cpu_record
  452. = hash_create_size (1011, (unsigned int (*) (void *))cpu_record_hash_key,
  453. (int (*) (const void *, const void *))cpu_record_hash_cmp);
  454. return (struct thread_master *) XCALLOC (MTYPE_THREAD_MASTER,
  455. sizeof (struct thread_master));
  456. }
  457. /* Add a new thread to the list. */
  458. static void
  459. thread_list_add (struct thread_list *list, struct thread *thread)
  460. {
  461. thread->next = NULL;
  462. thread->prev = list->tail;
  463. if (list->tail)
  464. list->tail->next = thread;
  465. else
  466. list->head = thread;
  467. list->tail = thread;
  468. list->count++;
  469. }
  470. /* Add a new thread just before the point. */
  471. static void
  472. thread_list_add_before (struct thread_list *list,
  473. struct thread *point,
  474. struct thread *thread)
  475. {
  476. thread->next = point;
  477. thread->prev = point->prev;
  478. if (point->prev)
  479. point->prev->next = thread;
  480. else
  481. list->head = thread;
  482. point->prev = thread;
  483. list->count++;
  484. }
  485. /* Delete a thread from the list. */
  486. static struct thread *
  487. thread_list_delete (struct thread_list *list, struct thread *thread)
  488. {
  489. if (thread->next)
  490. thread->next->prev = thread->prev;
  491. else
  492. list->tail = thread->prev;
  493. if (thread->prev)
  494. thread->prev->next = thread->next;
  495. else
  496. list->head = thread->next;
  497. thread->next = thread->prev = NULL;
  498. list->count--;
  499. return thread;
  500. }
  501. /* Move thread to unuse list. */
  502. static void
  503. thread_add_unuse (struct thread_master *m, struct thread *thread)
  504. {
  505. assert (m != NULL && thread != NULL);
  506. assert (thread->next == NULL);
  507. assert (thread->prev == NULL);
  508. assert (thread->type == THREAD_UNUSED);
  509. thread_list_add (&m->unuse, thread);
  510. /* XXX: Should we deallocate funcname here? */
  511. }
  512. /* Free all unused thread. */
  513. static void
  514. thread_list_free (struct thread_master *m, struct thread_list *list)
  515. {
  516. struct thread *t;
  517. struct thread *next;
  518. for (t = list->head; t; t = next)
  519. {
  520. next = t->next;
  521. if (t->funcname)
  522. XFREE (MTYPE_THREAD_FUNCNAME, t->funcname);
  523. XFREE (MTYPE_THREAD, t);
  524. list->count--;
  525. m->alloc--;
  526. }
  527. }
  528. /* Stop thread scheduler. */
  529. void
  530. thread_master_free (struct thread_master *m)
  531. {
  532. thread_list_free (m, &m->read);
  533. thread_list_free (m, &m->write);
  534. thread_list_free (m, &m->timer);
  535. thread_list_free (m, &m->event);
  536. thread_list_free (m, &m->ready);
  537. thread_list_free (m, &m->unuse);
  538. thread_list_free (m, &m->background);
  539. XFREE (MTYPE_THREAD_MASTER, m);
  540. if (cpu_record)
  541. {
  542. hash_clean (cpu_record, cpu_record_hash_free);
  543. hash_free (cpu_record);
  544. cpu_record = NULL;
  545. }
  546. }
  547. /* Thread list is empty or not. */
  548. static inline int
  549. thread_empty (struct thread_list *list)
  550. {
  551. return list->head ? 0 : 1;
  552. }
  553. /* Delete top of the list and return it. */
  554. static struct thread *
  555. thread_trim_head (struct thread_list *list)
  556. {
  557. if (!thread_empty (list))
  558. return thread_list_delete (list, list->head);
  559. return NULL;
  560. }
  561. /* Return remain time in second. */
  562. unsigned long
  563. thread_timer_remain_second (struct thread *thread)
  564. {
  565. quagga_get_relative (NULL);
  566. if (thread->u.sands.tv_sec - relative_time.tv_sec > 0)
  567. return thread->u.sands.tv_sec - relative_time.tv_sec;
  568. else
  569. return 0;
  570. }
  571. /* Trim blankspace and "()"s */
  572. static char *
  573. strip_funcname (const char *funcname)
  574. {
  575. char buff[100];
  576. char tmp, *ret, *e, *b = buff;
  577. strncpy(buff, funcname, sizeof(buff));
  578. buff[ sizeof(buff) -1] = '\0';
  579. e = buff +strlen(buff) -1;
  580. /* Wont work for funcname == "Word (explanation)" */
  581. while (*b == ' ' || *b == '(')
  582. ++b;
  583. while (*e == ' ' || *e == ')')
  584. --e;
  585. e++;
  586. tmp = *e;
  587. *e = '\0';
  588. ret = XSTRDUP (MTYPE_THREAD_FUNCNAME, b);
  589. *e = tmp;
  590. return ret;
  591. }
  592. /* Get new thread. */
  593. static struct thread *
  594. thread_get (struct thread_master *m, u_char type,
  595. int (*func) (struct thread *), void *arg, const char* funcname)
  596. {
  597. struct thread *thread;
  598. if (!thread_empty (&m->unuse))
  599. {
  600. thread = thread_trim_head (&m->unuse);
  601. if (thread->funcname)
  602. XFREE(MTYPE_THREAD_FUNCNAME, thread->funcname);
  603. }
  604. else
  605. {
  606. thread = XCALLOC (MTYPE_THREAD, sizeof (struct thread));
  607. m->alloc++;
  608. }
  609. thread->type = type;
  610. thread->add_type = type;
  611. thread->master = m;
  612. thread->func = func;
  613. thread->arg = arg;
  614. thread->funcname = strip_funcname(funcname);
  615. return thread;
  616. }
  617. /* Add new read thread. */
  618. struct thread *
  619. funcname_thread_add_read (struct thread_master *m,
  620. int (*func) (struct thread *), void *arg, int fd, const char* funcname)
  621. {
  622. struct thread *thread;
  623. assert (m != NULL);
  624. if (FD_ISSET (fd, &m->readfd))
  625. {
  626. zlog (NULL, LOG_WARNING, "There is already read fd [%d]", fd);
  627. return NULL;
  628. }
  629. thread = thread_get (m, THREAD_READ, func, arg, funcname);
  630. FD_SET (fd, &m->readfd);
  631. thread->u.fd = fd;
  632. thread_list_add (&m->read, thread);
  633. return thread;
  634. }
  635. /* Add new write thread. */
  636. struct thread *
  637. funcname_thread_add_write (struct thread_master *m,
  638. int (*func) (struct thread *), void *arg, int fd, const char* funcname)
  639. {
  640. struct thread *thread;
  641. assert (m != NULL);
  642. if (FD_ISSET (fd, &m->writefd))
  643. {
  644. zlog (NULL, LOG_WARNING, "There is already write fd [%d]", fd);
  645. return NULL;
  646. }
  647. thread = thread_get (m, THREAD_WRITE, func, arg, funcname);
  648. FD_SET (fd, &m->writefd);
  649. thread->u.fd = fd;
  650. thread_list_add (&m->write, thread);
  651. return thread;
  652. }
  653. static struct thread *
  654. funcname_thread_add_timer_timeval (struct thread_master *m,
  655. int (*func) (struct thread *),
  656. int type,
  657. void *arg,
  658. struct timeval *time_relative,
  659. const char* funcname)
  660. {
  661. struct thread *thread;
  662. struct thread_list *list;
  663. struct timeval alarm_time;
  664. struct thread *tt;
  665. assert (m != NULL);
  666. assert (type == THREAD_TIMER || type == THREAD_BACKGROUND);
  667. assert (time_relative);
  668. list = ((type == THREAD_TIMER) ? &m->timer : &m->background);
  669. thread = thread_get (m, type, func, arg, funcname);
  670. /* Do we need jitter here? */
  671. quagga_get_relative (NULL);
  672. alarm_time.tv_sec = relative_time.tv_sec + time_relative->tv_sec;
  673. alarm_time.tv_usec = relative_time.tv_usec + time_relative->tv_usec;
  674. thread->u.sands = timeval_adjust(alarm_time);
  675. /* Sort by timeval. */
  676. for (tt = list->head; tt; tt = tt->next)
  677. if (timeval_cmp (thread->u.sands, tt->u.sands) <= 0)
  678. break;
  679. if (tt)
  680. thread_list_add_before (list, tt, thread);
  681. else
  682. thread_list_add (list, thread);
  683. return thread;
  684. }
  685. /* Add timer event thread. */
  686. struct thread *
  687. funcname_thread_add_timer (struct thread_master *m,
  688. int (*func) (struct thread *),
  689. void *arg, long timer, const char* funcname)
  690. {
  691. struct timeval trel;
  692. assert (m != NULL);
  693. trel.tv_sec = timer;
  694. trel.tv_usec = 0;
  695. return funcname_thread_add_timer_timeval (m, func, THREAD_TIMER, arg,
  696. &trel, funcname);
  697. }
  698. /* Add timer event thread with "millisecond" resolution */
  699. struct thread *
  700. funcname_thread_add_timer_msec (struct thread_master *m,
  701. int (*func) (struct thread *),
  702. void *arg, long timer, const char* funcname)
  703. {
  704. struct timeval trel;
  705. assert (m != NULL);
  706. trel.tv_sec = timer / 1000;
  707. trel.tv_usec = 1000*(timer % 1000);
  708. return funcname_thread_add_timer_timeval (m, func, THREAD_TIMER,
  709. arg, &trel, funcname);
  710. }
  711. /* Add a background thread, with an optional millisec delay */
  712. struct thread *
  713. funcname_thread_add_background (struct thread_master *m,
  714. int (*func) (struct thread *),
  715. void *arg, long delay,
  716. const char *funcname)
  717. {
  718. struct timeval trel;
  719. assert (m != NULL);
  720. if (delay)
  721. {
  722. trel.tv_sec = delay / 1000;
  723. trel.tv_usec = 1000*(delay % 1000);
  724. }
  725. else
  726. {
  727. trel.tv_sec = 0;
  728. trel.tv_usec = 0;
  729. }
  730. return funcname_thread_add_timer_timeval (m, func, THREAD_BACKGROUND,
  731. arg, &trel, funcname);
  732. }
  733. /* Add simple event thread. */
  734. struct thread *
  735. funcname_thread_add_event (struct thread_master *m,
  736. int (*func) (struct thread *), void *arg, int val, const char* funcname)
  737. {
  738. struct thread *thread;
  739. assert (m != NULL);
  740. thread = thread_get (m, THREAD_EVENT, func, arg, funcname);
  741. thread->u.val = val;
  742. thread_list_add (&m->event, thread);
  743. return thread;
  744. }
  745. /* Cancel thread from scheduler. */
  746. void
  747. thread_cancel (struct thread *thread)
  748. {
  749. struct thread_list *list;
  750. switch (thread->type)
  751. {
  752. case THREAD_READ:
  753. assert (FD_ISSET (thread->u.fd, &thread->master->readfd));
  754. FD_CLR (thread->u.fd, &thread->master->readfd);
  755. list = &thread->master->read;
  756. break;
  757. case THREAD_WRITE:
  758. assert (FD_ISSET (thread->u.fd, &thread->master->writefd));
  759. FD_CLR (thread->u.fd, &thread->master->writefd);
  760. list = &thread->master->write;
  761. break;
  762. case THREAD_TIMER:
  763. list = &thread->master->timer;
  764. break;
  765. case THREAD_EVENT:
  766. list = &thread->master->event;
  767. break;
  768. case THREAD_READY:
  769. list = &thread->master->ready;
  770. break;
  771. case THREAD_BACKGROUND:
  772. list = &thread->master->background;
  773. break;
  774. default:
  775. return;
  776. break;
  777. }
  778. thread_list_delete (list, thread);
  779. thread->type = THREAD_UNUSED;
  780. thread_add_unuse (thread->master, thread);
  781. }
  782. /* Delete all events which has argument value arg. */
  783. unsigned int
  784. thread_cancel_event (struct thread_master *m, void *arg)
  785. {
  786. unsigned int ret = 0;
  787. struct thread *thread;
  788. thread = m->event.head;
  789. while (thread)
  790. {
  791. struct thread *t;
  792. t = thread;
  793. thread = t->next;
  794. if (t->arg == arg)
  795. {
  796. ret++;
  797. thread_list_delete (&m->event, t);
  798. t->type = THREAD_UNUSED;
  799. thread_add_unuse (m, t);
  800. }
  801. }
  802. return ret;
  803. }
  804. static struct timeval *
  805. thread_timer_wait (struct thread_list *tlist, struct timeval *timer_val)
  806. {
  807. if (!thread_empty (tlist))
  808. {
  809. *timer_val = timeval_subtract (tlist->head->u.sands, relative_time);
  810. return timer_val;
  811. }
  812. return NULL;
  813. }
  814. static struct thread *
  815. thread_run (struct thread_master *m, struct thread *thread,
  816. struct thread *fetch)
  817. {
  818. *fetch = *thread;
  819. thread->type = THREAD_UNUSED;
  820. thread->funcname = NULL; /* thread_call will free fetch's copied pointer */
  821. thread_add_unuse (m, thread);
  822. return fetch;
  823. }
  824. static int
  825. thread_process_fd (struct thread_list *list, fd_set *fdset, fd_set *mfdset)
  826. {
  827. struct thread *thread;
  828. struct thread *next;
  829. int ready = 0;
  830. assert (list);
  831. for (thread = list->head; thread; thread = next)
  832. {
  833. next = thread->next;
  834. if (FD_ISSET (THREAD_FD (thread), fdset))
  835. {
  836. assert (FD_ISSET (THREAD_FD (thread), mfdset));
  837. FD_CLR(THREAD_FD (thread), mfdset);
  838. thread_list_delete (list, thread);
  839. thread_list_add (&thread->master->ready, thread);
  840. thread->type = THREAD_READY;
  841. ready++;
  842. }
  843. }
  844. return ready;
  845. }
  846. /* Add all timers that have popped to the ready list. */
  847. static unsigned int
  848. thread_timer_process (struct thread_list *list, struct timeval *timenow)
  849. {
  850. struct thread *thread;
  851. unsigned int ready = 0;
  852. for (thread = list->head; thread; thread = thread->next)
  853. {
  854. if (timeval_cmp (*timenow, thread->u.sands) < 0)
  855. return ready;
  856. thread_list_delete (list, thread);
  857. thread->type = THREAD_READY;
  858. thread_list_add (&thread->master->ready, thread);
  859. ready++;
  860. }
  861. return ready;
  862. }
  863. /* process a list en masse, e.g. for event thread lists */
  864. static unsigned int
  865. thread_process (struct thread_list *list)
  866. {
  867. struct thread *thread;
  868. unsigned int ready = 0;
  869. for (thread = list->head; thread; thread = thread->next)
  870. {
  871. thread_list_delete (list, thread);
  872. thread->type = THREAD_READY;
  873. thread_list_add (&thread->master->ready, thread);
  874. ready++;
  875. }
  876. return ready;
  877. }
  878. /* Fetch next ready thread. */
  879. struct thread *
  880. thread_fetch (struct thread_master *m, struct thread *fetch)
  881. {
  882. struct thread *thread;
  883. fd_set readfd;
  884. fd_set writefd;
  885. fd_set exceptfd;
  886. struct timeval timer_val = { .tv_sec = 0, .tv_usec = 0 };
  887. struct timeval timer_val_bg;
  888. struct timeval *timer_wait = &timer_val;
  889. struct timeval *timer_wait_bg;
  890. while (1)
  891. {
  892. int num = 0;
  893. /* Signals pre-empt everything */
  894. quagga_sigevent_process ();
  895. /* Drain the ready queue of already scheduled jobs, before scheduling
  896. * more.
  897. */
  898. if ((thread = thread_trim_head (&m->ready)) != NULL)
  899. return thread_run (m, thread, fetch);
  900. /* To be fair to all kinds of threads, and avoid starvation, we
  901. * need to be careful to consider all thread types for scheduling
  902. * in each quanta. I.e. we should not return early from here on.
  903. */
  904. /* Normal event are the next highest priority. */
  905. thread_process (&m->event);
  906. /* Structure copy. */
  907. readfd = m->readfd;
  908. writefd = m->writefd;
  909. exceptfd = m->exceptfd;
  910. /* Calculate select wait timer if nothing else to do */
  911. if (m->ready.count == 0)
  912. {
  913. quagga_get_relative (NULL);
  914. timer_wait = thread_timer_wait (&m->timer, &timer_val);
  915. timer_wait_bg = thread_timer_wait (&m->background, &timer_val_bg);
  916. if (timer_wait_bg &&
  917. (!timer_wait || (timeval_cmp (*timer_wait, *timer_wait_bg) > 0)))
  918. timer_wait = timer_wait_bg;
  919. }
  920. num = select (FD_SETSIZE, &readfd, &writefd, &exceptfd, timer_wait);
  921. /* Signals should get quick treatment */
  922. if (num < 0)
  923. {
  924. if (errno == EINTR)
  925. continue; /* signal received - process it */
  926. zlog_warn ("select() error: %s", safe_strerror (errno));
  927. return NULL;
  928. }
  929. /* Check foreground timers. Historically, they have had higher
  930. priority than I/O threads, so let's push them onto the ready
  931. list in front of the I/O threads. */
  932. quagga_get_relative (NULL);
  933. thread_timer_process (&m->timer, &relative_time);
  934. /* Got IO, process it */
  935. if (num > 0)
  936. {
  937. /* Normal priority read thead. */
  938. thread_process_fd (&m->read, &readfd, &m->readfd);
  939. /* Write thead. */
  940. thread_process_fd (&m->write, &writefd, &m->writefd);
  941. }
  942. #if 0
  943. /* If any threads were made ready above (I/O or foreground timer),
  944. perhaps we should avoid adding background timers to the ready
  945. list at this time. If this is code is uncommented, then background
  946. timer threads will not run unless there is nothing else to do. */
  947. if ((thread = thread_trim_head (&m->ready)) != NULL)
  948. return thread_run (m, thread, fetch);
  949. #endif
  950. /* Background timer/events, lowest priority */
  951. thread_timer_process (&m->background, &relative_time);
  952. if ((thread = thread_trim_head (&m->ready)) != NULL)
  953. return thread_run (m, thread, fetch);
  954. }
  955. }
  956. unsigned long
  957. thread_consumed_time (RUSAGE_T *now, RUSAGE_T *start, unsigned long *cputime)
  958. {
  959. #ifdef HAVE_RUSAGE
  960. /* This is 'user + sys' time. */
  961. *cputime = timeval_elapsed (now->cpu.ru_utime, start->cpu.ru_utime) +
  962. timeval_elapsed (now->cpu.ru_stime, start->cpu.ru_stime);
  963. #else
  964. *cputime = 0;
  965. #endif /* HAVE_RUSAGE */
  966. return timeval_elapsed (now->real, start->real);
  967. }
  968. /* We should aim to yield after THREAD_YIELD_TIME_SLOT milliseconds.
  969. Note: we are using real (wall clock) time for this calculation.
  970. It could be argued that CPU time may make more sense in certain
  971. contexts. The things to consider are whether the thread may have
  972. blocked (in which case wall time increases, but CPU time does not),
  973. or whether the system is heavily loaded with other processes competing
  974. for CPU time. On balance, wall clock time seems to make sense.
  975. Plus it has the added benefit that gettimeofday should be faster
  976. than calling getrusage. */
  977. int
  978. thread_should_yield (struct thread *thread)
  979. {
  980. quagga_get_relative (NULL);
  981. return (timeval_elapsed(relative_time, thread->ru.real) >
  982. THREAD_YIELD_TIME_SLOT);
  983. }
  984. void
  985. thread_getrusage (RUSAGE_T *r)
  986. {
  987. quagga_get_relative (NULL);
  988. #ifdef HAVE_RUSAGE
  989. getrusage(RUSAGE_SELF, &(r->cpu));
  990. #endif
  991. r->real = relative_time;
  992. #ifdef HAVE_CLOCK_MONOTONIC
  993. /* quagga_get_relative() only updates recent_time if gettimeofday
  994. * based, not when using CLOCK_MONOTONIC. As we export recent_time
  995. * and guarantee to update it before threads are run...
  996. */
  997. quagga_gettimeofday(&recent_time);
  998. #endif /* HAVE_CLOCK_MONOTONIC */
  999. }
  1000. /* We check thread consumed time. If the system has getrusage, we'll
  1001. use that to get in-depth stats on the performance of the thread in addition
  1002. to wall clock time stats from gettimeofday. */
  1003. void
  1004. thread_call (struct thread *thread)
  1005. {
  1006. unsigned long realtime, cputime;
  1007. RUSAGE_T ru;
  1008. /* Cache a pointer to the relevant cpu history thread, if the thread
  1009. * does not have it yet.
  1010. *
  1011. * Callers submitting 'dummy threads' hence must take care that
  1012. * thread->cpu is NULL
  1013. */
  1014. if (!thread->hist)
  1015. {
  1016. struct cpu_thread_history tmp;
  1017. tmp.func = thread->func;
  1018. tmp.funcname = thread->funcname;
  1019. thread->hist = hash_get (cpu_record, &tmp,
  1020. (void * (*) (void *))cpu_record_hash_alloc);
  1021. }
  1022. GETRUSAGE (&thread->ru);
  1023. (*thread->func) (thread);
  1024. GETRUSAGE (&ru);
  1025. realtime = thread_consumed_time (&ru, &thread->ru, &cputime);
  1026. thread->hist->real.total += realtime;
  1027. if (thread->hist->real.max < realtime)
  1028. thread->hist->real.max = realtime;
  1029. #ifdef HAVE_RUSAGE
  1030. thread->hist->cpu.total += cputime;
  1031. if (thread->hist->cpu.max < cputime)
  1032. thread->hist->cpu.max = cputime;
  1033. #endif
  1034. ++(thread->hist->total_calls);
  1035. thread->hist->types |= (1 << thread->add_type);
  1036. #ifdef CONSUMED_TIME_CHECK
  1037. if (realtime > CONSUMED_TIME_CHECK)
  1038. {
  1039. /*
  1040. * We have a CPU Hog on our hands.
  1041. * Whinge about it now, so we're aware this is yet another task
  1042. * to fix.
  1043. */
  1044. zlog_warn ("SLOW THREAD: task %s (%lx) ran for %lums (cpu time %lums)",
  1045. thread->funcname,
  1046. (unsigned long) thread->func,
  1047. realtime/1000, cputime/1000);
  1048. }
  1049. #endif /* CONSUMED_TIME_CHECK */
  1050. XFREE (MTYPE_THREAD_FUNCNAME, thread->funcname);
  1051. }
  1052. /* Execute thread */
  1053. struct thread *
  1054. funcname_thread_execute (struct thread_master *m,
  1055. int (*func)(struct thread *),
  1056. void *arg,
  1057. int val,
  1058. const char* funcname)
  1059. {
  1060. struct thread dummy;
  1061. memset (&dummy, 0, sizeof (struct thread));
  1062. dummy.type = THREAD_EVENT;
  1063. dummy.add_type = THREAD_EXECUTE;
  1064. dummy.master = NULL;
  1065. dummy.func = func;
  1066. dummy.arg = arg;
  1067. dummy.u.val = val;
  1068. dummy.funcname = strip_funcname (funcname);
  1069. thread_call (&dummy);
  1070. XFREE (MTYPE_THREAD_FUNCNAME, dummy.funcname);
  1071. return NULL;
  1072. }