thread.c 33 KB

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