thread.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. /*
  2. * Copyright (c) 2008-2009 Travis Geiselbrecht
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files
  6. * (the "Software"), to deal in the Software without restriction,
  7. * including without limitation the rights to use, copy, modify, merge,
  8. * publish, distribute, sublicense, and/or sell copies of the Software,
  9. * and to permit persons to whom the Software is furnished to do so,
  10. * subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be
  13. * included in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  18. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  19. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  20. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  21. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. /**
  24. * @file
  25. * @brief Kernel threading
  26. *
  27. * This file is the core kernel threading interface.
  28. *
  29. * @defgroup thread Threads
  30. * @{
  31. */
  32. #include <debug.h>
  33. #include <list.h>
  34. #include <malloc.h>
  35. #include <string.h>
  36. #include <err.h>
  37. #include <kernel/thread.h>
  38. #include <kernel/timer.h>
  39. #include <kernel/dpc.h>
  40. #include <platform.h>
  41. #if DEBUGLEVEL > 1
  42. #define THREAD_CHECKS 1
  43. #endif
  44. #if THREAD_STATS
  45. struct thread_stats thread_stats;
  46. #endif
  47. /* global thread list */
  48. static struct list_node thread_list;
  49. /* the current thread */
  50. thread_t *current_thread;
  51. /* the global critical section count */
  52. int critical_section_count = 1;
  53. /* the run queue */
  54. static struct list_node run_queue[NUM_PRIORITIES];
  55. static uint32_t run_queue_bitmap;
  56. /* the bootstrap thread (statically allocated) */
  57. static thread_t bootstrap_thread;
  58. /* the idle thread */
  59. thread_t *idle_thread;
  60. /* local routines */
  61. static void thread_resched(void);
  62. static void idle_thread_routine(void) __NO_RETURN;
  63. #ifdef ENABLE_IO_THREAD
  64. static const int quantum = 1;
  65. static const time_t tmo_ms = 1; // Timeout in ms.
  66. #else
  67. static const int quantum = 5;
  68. static const time_t tmo_ms = 10; // Timeout in ms.
  69. #endif // ENABLE_IO_THREAD
  70. #if PLATFORM_HAS_DYNAMIC_TIMER
  71. /* preemption timer */
  72. static timer_t preempt_timer;
  73. #endif
  74. /* run queue manipulation */
  75. static void insert_in_run_queue_head(thread_t *t)
  76. {
  77. #if THREAD_CHECKS
  78. ASSERT(t->magic == THREAD_MAGIC);
  79. ASSERT(t->state == THREAD_READY);
  80. ASSERT(!list_in_list(&t->queue_node));
  81. ASSERT(in_critical_section());
  82. #endif
  83. list_add_head(&run_queue[t->priority], &t->queue_node);
  84. run_queue_bitmap |= (1<<t->priority);
  85. }
  86. static void insert_in_run_queue_tail(thread_t *t)
  87. {
  88. #if THREAD_CHECKS
  89. ASSERT(t->magic == THREAD_MAGIC);
  90. ASSERT(t->state == THREAD_READY);
  91. ASSERT(!list_in_list(&t->queue_node));
  92. ASSERT(in_critical_section());
  93. #endif
  94. list_add_tail(&run_queue[t->priority], &t->queue_node);
  95. run_queue_bitmap |= (1<<t->priority);
  96. }
  97. static void init_thread_struct(thread_t *t, const char *name)
  98. {
  99. memset(t, 0, sizeof(thread_t));
  100. t->magic = THREAD_MAGIC;
  101. strlcpy(t->name, name, sizeof(t->name));
  102. }
  103. /**
  104. * @brief Create a new thread
  105. *
  106. * This function creates a new thread. The thread is initially suspended, so you
  107. * need to call thread_resume() to execute it.
  108. *
  109. * @param name Name of thread
  110. * @param entry Entry point of thread
  111. * @param arg Arbitrary argument passed to entry()
  112. * @param priority Execution priority for the thread.
  113. * @param stack_size Stack size for the thread.
  114. *
  115. * Thread priority is an integer from 0 (lowest) to 31 (highest). Some standard
  116. * prioritys are defined in <kernel/thread.h>:
  117. *
  118. * HIGHEST_PRIORITY
  119. * DPC_PRIORITY
  120. * HIGH_PRIORITY
  121. * DEFAULT_PRIORITY
  122. * LOW_PRIORITY
  123. * IDLE_PRIORITY
  124. * LOWEST_PRIORITY
  125. *
  126. * Stack size is typically set to DEFAULT_STACK_SIZE
  127. *
  128. * @return Pointer to thread object, or NULL on failure.
  129. */
  130. thread_t *thread_create(const char *name, thread_start_routine entry, void *arg, int priority, size_t stack_size)
  131. {
  132. thread_t *t;
  133. t = malloc(sizeof(thread_t));
  134. if (!t)
  135. return NULL;
  136. init_thread_struct(t, name);
  137. t->entry = entry;
  138. t->arg = arg;
  139. t->priority = priority;
  140. t->saved_critical_section_count = 1; /* we always start inside a critical section */
  141. t->state = THREAD_SUSPENDED;
  142. t->blocking_wait_queue = NULL;
  143. t->wait_queue_block_ret = NO_ERROR;
  144. /* create the stack */
  145. t->stack = malloc(stack_size);
  146. if (!t->stack) {
  147. free(t);
  148. return NULL;
  149. }
  150. t->stack_size = stack_size;
  151. /* inheirit thread local storage from the parent */
  152. int i;
  153. for (i=0; i < MAX_TLS_ENTRY; i++)
  154. t->tls[i] = current_thread->tls[i];
  155. /* set up the initial stack frame */
  156. arch_thread_initialize(t);
  157. /* add it to the global thread list */
  158. enter_critical_section();
  159. list_add_head(&thread_list, &t->thread_list_node);
  160. exit_critical_section();
  161. return t;
  162. }
  163. /**
  164. * @brief Make a suspended thread executable.
  165. *
  166. * This function is typically called to start a thread which has just been
  167. * created with thread_create()
  168. *
  169. * @param t Thread to resume
  170. *
  171. * @return NO_ERROR on success, ERR_NOT_SUSPENDED if thread was not suspended.
  172. */
  173. status_t thread_resume(thread_t *t)
  174. {
  175. #if THREAD_CHECKS
  176. ASSERT(t->magic == THREAD_MAGIC);
  177. ASSERT(t->state != THREAD_DEATH);
  178. #endif
  179. if (t->state == THREAD_READY || t->state == THREAD_RUNNING)
  180. return ERR_NOT_SUSPENDED;
  181. enter_critical_section();
  182. t->state = THREAD_READY;
  183. insert_in_run_queue_head(t);
  184. thread_yield();
  185. exit_critical_section();
  186. return NO_ERROR;
  187. }
  188. static void thread_cleanup_dpc(void *thread)
  189. {
  190. thread_t *t = (thread_t *)thread;
  191. // dprintf(SPEW, "thread_cleanup_dpc: thread %p (%s)\n", t, t->name);
  192. #if THREAD_CHECKS
  193. ASSERT(t->state == THREAD_DEATH);
  194. ASSERT(t->blocking_wait_queue == NULL);
  195. ASSERT(!list_in_list(&t->queue_node));
  196. #endif
  197. /* remove it from the master thread list */
  198. enter_critical_section();
  199. list_delete(&t->thread_list_node);
  200. exit_critical_section();
  201. /* free its stack and the thread structure itself */
  202. if (t->stack)
  203. free(t->stack);
  204. free(t);
  205. }
  206. /**
  207. * @brief Terminate the current thread
  208. *
  209. * Current thread exits with the specified return code.
  210. *
  211. * This function does not return.
  212. */
  213. void thread_exit(int retcode)
  214. {
  215. #if THREAD_CHECKS
  216. ASSERT(current_thread->magic == THREAD_MAGIC);
  217. ASSERT(current_thread->state == THREAD_RUNNING);
  218. #endif
  219. // dprintf("thread_exit: current %p\n", current_thread);
  220. enter_critical_section();
  221. /* enter the dead state */
  222. current_thread->state = THREAD_DEATH;
  223. current_thread->retcode = retcode;
  224. /* schedule a dpc to clean ourselves up */
  225. dpc_queue(thread_cleanup_dpc, (void *)current_thread, DPC_FLAG_NORESCHED);
  226. /* reschedule */
  227. thread_resched();
  228. panic("somehow fell through thread_exit()\n");
  229. }
  230. static void idle_thread_routine(void)
  231. {
  232. for(;;)
  233. arch_idle();
  234. }
  235. /**
  236. * @brief Cause another thread to be executed.
  237. *
  238. * Internal reschedule routine. The current thread needs to already be in whatever
  239. * state and queues it needs to be in. This routine simply picks the next thread and
  240. * switches to it.
  241. *
  242. * This is probably not the function you're looking for. See
  243. * thread_yield() instead.
  244. */
  245. void thread_resched(void)
  246. {
  247. thread_t *oldthread;
  248. thread_t *newthread;
  249. // dprintf("thread_resched: current %p: ", current_thread);
  250. // dump_thread(current_thread);
  251. #if THREAD_CHECKS
  252. ASSERT(in_critical_section());
  253. #endif
  254. #if THREAD_STATS
  255. thread_stats.reschedules++;
  256. #endif
  257. oldthread = current_thread;
  258. // at the moment, can't deal with more than 32 priority levels
  259. ASSERT(NUM_PRIORITIES <= 32);
  260. // should at least find the idle thread
  261. #if THREAD_CHECKS
  262. ASSERT(run_queue_bitmap != 0);
  263. #endif
  264. int next_queue = HIGHEST_PRIORITY - __builtin_clz(run_queue_bitmap) - (32 - NUM_PRIORITIES);
  265. //dprintf(SPEW, "bitmap 0x%x, next %d\n", run_queue_bitmap, next_queue);
  266. newthread = list_remove_head_type(&run_queue[next_queue], thread_t, queue_node);
  267. #if THREAD_CHECKS
  268. ASSERT(newthread);
  269. #endif
  270. if (list_is_empty(&run_queue[next_queue]))
  271. run_queue_bitmap &= ~(1<<next_queue);
  272. #if 0
  273. // XXX make this more efficient
  274. newthread = NULL;
  275. for (i=HIGHEST_PRIORITY; i >= LOWEST_PRIORITY; i--) {
  276. newthread = list_remove_head_type(&run_queue[i], thread_t, queue_node);
  277. if (newthread)
  278. break;
  279. }
  280. #endif
  281. // dprintf("newthread: ");
  282. // dump_thread(newthread);
  283. newthread->state = THREAD_RUNNING;
  284. if (newthread == oldthread)
  285. return;
  286. /* set up quantum for the new thread if it was consumed */
  287. if (newthread->remaining_quantum <= 0) {
  288. newthread->remaining_quantum = quantum; // XXX make this smarter
  289. }
  290. #if THREAD_STATS
  291. thread_stats.context_switches++;
  292. if (oldthread == idle_thread) {
  293. bigtime_t now = current_time_hires();
  294. thread_stats.idle_time += now - thread_stats.last_idle_timestamp;
  295. }
  296. if (newthread == idle_thread) {
  297. thread_stats.last_idle_timestamp = current_time_hires();
  298. }
  299. #endif
  300. #if THREAD_CHECKS
  301. ASSERT(critical_section_count > 0);
  302. ASSERT(newthread->saved_critical_section_count > 0);
  303. #endif
  304. #if PLATFORM_HAS_DYNAMIC_TIMER
  305. /* if we're switching from idle to a real thread, set up a periodic
  306. * timer to run our preemption tick.
  307. */
  308. if (oldthread == idle_thread) {
  309. timer_set_periodic(&preempt_timer, tmo_ms, (timer_callback)thread_timer_tick, NULL);
  310. } else if (newthread == idle_thread) {
  311. timer_cancel(&preempt_timer);
  312. }
  313. #endif
  314. /* do the switch */
  315. oldthread->saved_critical_section_count = critical_section_count;
  316. current_thread = newthread;
  317. critical_section_count = newthread->saved_critical_section_count;
  318. arch_context_switch(oldthread, newthread);
  319. }
  320. /**
  321. * @brief Yield the cpu to another thread
  322. *
  323. * This function places the current thread at the end of the run queue
  324. * and yields the cpu to another waiting thread (if any.)
  325. *
  326. * This function will return at some later time. Possibly immediately if
  327. * no other threads are waiting to execute.
  328. */
  329. void thread_yield(void)
  330. {
  331. #if THREAD_CHECKS
  332. ASSERT(current_thread->magic == THREAD_MAGIC);
  333. ASSERT(current_thread->state == THREAD_RUNNING);
  334. #endif
  335. enter_critical_section();
  336. #if THREAD_STATS
  337. thread_stats.yields++;
  338. #endif
  339. /* we are yielding the cpu, so stick ourselves into the tail of the run queue and reschedule */
  340. current_thread->state = THREAD_READY;
  341. current_thread->remaining_quantum = 0;
  342. insert_in_run_queue_tail(current_thread);
  343. thread_resched();
  344. exit_critical_section();
  345. }
  346. /**
  347. * @brief Briefly yield cpu to another thread
  348. *
  349. * This function is similar to thread_yield(), except that it will
  350. * restart more quickly.
  351. *
  352. * This function places the current thread at the head of the run
  353. * queue and then yields the cpu to another thread.
  354. *
  355. * Exception: If the time slice for this thread has expired, then
  356. * the thread goes to the end of the run queue.
  357. *
  358. * This function will return at some later time. Possibly immediately if
  359. * no other threads are waiting to execute.
  360. */
  361. void thread_preempt(void)
  362. {
  363. #if THREAD_CHECKS
  364. ASSERT(current_thread->magic == THREAD_MAGIC);
  365. ASSERT(current_thread->state == THREAD_RUNNING);
  366. #endif
  367. enter_critical_section();
  368. #if THREAD_STATS
  369. if (current_thread != idle_thread)
  370. thread_stats.preempts++; /* only track when a meaningful preempt happens */
  371. #endif
  372. /* we are being preempted, so we get to go back into the front of the run queue if we have quantum left */
  373. current_thread->state = THREAD_READY;
  374. if (current_thread->remaining_quantum > 0)
  375. insert_in_run_queue_head(current_thread);
  376. else
  377. insert_in_run_queue_tail(current_thread); /* if we're out of quantum, go to the tail of the queue */
  378. thread_resched();
  379. exit_critical_section();
  380. }
  381. /**
  382. * @brief Suspend thread until woken.
  383. *
  384. * This function schedules another thread to execute. This function does not
  385. * return until the thread is made runable again by some other module.
  386. *
  387. * You probably don't want to call this function directly; it's meant to be called
  388. * from other modules, such as mutex, which will presumably set the thread's
  389. * state to blocked and add it to some queue or another.
  390. */
  391. void thread_block(void)
  392. {
  393. #if THREAD_CHECKS
  394. ASSERT(current_thread->magic == THREAD_MAGIC);
  395. ASSERT(current_thread->state == THREAD_BLOCKED);
  396. #endif
  397. enter_critical_section();
  398. /* we are blocking on something. the blocking code should have already stuck us on a queue */
  399. thread_resched();
  400. exit_critical_section();
  401. }
  402. enum handler_return thread_timer_tick(void)
  403. {
  404. if (current_thread == idle_thread)
  405. return INT_NO_RESCHEDULE;
  406. current_thread->remaining_quantum--;
  407. if (current_thread->remaining_quantum <= 0)
  408. return INT_RESCHEDULE;
  409. else
  410. return INT_NO_RESCHEDULE;
  411. }
  412. /* timer callback to wake up a sleeping thread */
  413. static enum handler_return thread_sleep_handler(timer_t *timer, time_t now, void *arg)
  414. {
  415. thread_t *t = (thread_t *)arg;
  416. #if THREAD_CHECKS
  417. ASSERT(t->magic == THREAD_MAGIC);
  418. ASSERT(t->state == THREAD_SLEEPING);
  419. #endif
  420. t->state = THREAD_READY;
  421. insert_in_run_queue_head(t);
  422. return INT_RESCHEDULE;
  423. }
  424. /**
  425. * @brief Put thread to sleep; delay specified in ms
  426. *
  427. * This function puts the current thread to sleep until the specified
  428. * delay in ms has expired.
  429. *
  430. * Note that this function could sleep for longer than the specified delay if
  431. * other threads are running. When the timer expires, this thread will
  432. * be placed at the head of the run queue.
  433. */
  434. void thread_sleep(time_t delay)
  435. {
  436. timer_t timer;
  437. #if THREAD_CHECKS
  438. ASSERT(current_thread->magic == THREAD_MAGIC);
  439. ASSERT(current_thread->state == THREAD_RUNNING);
  440. #endif
  441. timer_initialize(&timer);
  442. enter_critical_section();
  443. timer_set_oneshot(&timer, delay, thread_sleep_handler, (void *)current_thread);
  444. current_thread->state = THREAD_SLEEPING;
  445. thread_resched();
  446. exit_critical_section();
  447. }
  448. /**
  449. * @brief Initialize threading system
  450. *
  451. * This function is called once, from kmain()
  452. */
  453. void thread_init_early(void)
  454. {
  455. int i;
  456. /* initialize the run queues */
  457. for (i=0; i < NUM_PRIORITIES; i++)
  458. list_initialize(&run_queue[i]);
  459. /* initialize the thread list */
  460. list_initialize(&thread_list);
  461. /* create a thread to cover the current running state */
  462. thread_t *t = &bootstrap_thread;
  463. init_thread_struct(t, "bootstrap");
  464. /* half construct this thread, since we're already running */
  465. t->priority = HIGHEST_PRIORITY;
  466. t->state = THREAD_RUNNING;
  467. t->saved_critical_section_count = 1;
  468. list_add_head(&thread_list, &t->thread_list_node);
  469. current_thread = t;
  470. }
  471. /**
  472. * @brief Complete thread initialization
  473. *
  474. * This function is called once at boot time
  475. */
  476. void thread_init(void)
  477. {
  478. #if PLATFORM_HAS_DYNAMIC_TIMER
  479. timer_initialize(&preempt_timer);
  480. #endif
  481. }
  482. /**
  483. * @brief Change name of current thread
  484. */
  485. void thread_set_name(const char *name)
  486. {
  487. strlcpy(current_thread->name, name, sizeof(current_thread->name));
  488. }
  489. /**
  490. * @brief Change priority of current thread
  491. *
  492. * See thread_create() for a discussion of priority values.
  493. */
  494. void thread_set_priority(int priority)
  495. {
  496. if (priority < LOWEST_PRIORITY)
  497. priority = LOWEST_PRIORITY;
  498. if (priority > HIGHEST_PRIORITY)
  499. priority = HIGHEST_PRIORITY;
  500. current_thread->priority = priority;
  501. }
  502. /**
  503. * @brief Become an idle thread
  504. *
  505. * This function marks the current thread as the idle thread -- the one which
  506. * executes when there is nothing else to do. This function does not return.
  507. * This function is called once at boot time.
  508. */
  509. void thread_become_idle(void)
  510. {
  511. thread_set_name("idle");
  512. idle_thread = current_thread;
  513. thread_set_priority(IDLE_PRIORITY);
  514. thread_yield();
  515. idle_thread_routine();
  516. }
  517. /**
  518. * @brief Dump debugging info about the specified thread.
  519. */
  520. void dump_thread(thread_t *t)
  521. {
  522. dprintf(INFO, "dump_thread: t %p (%s)\n", t, t->name);
  523. dprintf(INFO, "\tstate %d, priority %d, remaining quantum %d, critical section %d\n", t->state, t->priority, t->remaining_quantum, t->saved_critical_section_count);
  524. dprintf(INFO, "\tstack %p, stack_size %zd\n", t->stack, t->stack_size);
  525. dprintf(INFO, "\tentry %p, arg %p\n", t->entry, t->arg);
  526. dprintf(INFO, "\twait queue %p, wait queue ret %d\n", t->blocking_wait_queue, t->wait_queue_block_ret);
  527. dprintf(INFO, "\ttls:");
  528. int i;
  529. for (i=0; i < MAX_TLS_ENTRY; i++) {
  530. dprintf(INFO, " 0x%x", t->tls[i]);
  531. }
  532. dprintf(INFO, "\n");
  533. }
  534. /**
  535. * @brief Dump debugging info about all threads
  536. */
  537. void dump_all_threads(void)
  538. {
  539. thread_t *t;
  540. enter_critical_section();
  541. list_for_every_entry(&thread_list, t, thread_t, thread_list_node) {
  542. dump_thread(t);
  543. }
  544. exit_critical_section();
  545. }
  546. /**
  547. * @brief Dump debugging info about target threads
  548. */
  549. void dump_target_threads_stack(void)
  550. {
  551. thread_t *t;
  552. unsigned long dump_len, dump_ahead = 64;
  553. enter_critical_section();
  554. list_for_every_entry(&thread_list, t, thread_t, thread_list_node) {
  555. if (t->stack_size > 0)
  556. dump_len = (unsigned long)(t->stack + t->stack_size - t->arch.sp) + dump_ahead;
  557. else
  558. dump_len = 384;
  559. dprintf(CRITICAL, "top of stack at 0x%08x: thread name:%s\n", (unsigned int)t->arch.sp, t->name);
  560. hexdump((void*)((char*)t->arch.sp - dump_ahead), dump_len);
  561. }
  562. exit_critical_section();
  563. }
  564. /** @} */
  565. /**
  566. * @defgroup wait Wait Queue
  567. * @{
  568. */
  569. /**
  570. * @brief Initialize a wait queue
  571. */
  572. void wait_queue_init(wait_queue_t *wait)
  573. {
  574. wait->magic = WAIT_QUEUE_MAGIC;
  575. list_initialize(&wait->list);
  576. wait->count = 0;
  577. }
  578. static enum handler_return wait_queue_timeout_handler(timer_t *timer, time_t now, void *arg)
  579. {
  580. thread_t *thread = (thread_t *)arg;
  581. #if THREAD_CHECKS
  582. ASSERT(thread->magic == THREAD_MAGIC);
  583. #endif
  584. if (thread_unblock_from_wait_queue(thread, false, ERR_TIMED_OUT) >= NO_ERROR)
  585. return INT_RESCHEDULE;
  586. return INT_NO_RESCHEDULE;
  587. }
  588. /**
  589. * @brief Block until a wait queue is notified.
  590. *
  591. * This function puts the current thread at the end of a wait
  592. * queue and then blocks until some other thread wakes the queue
  593. * up again.
  594. *
  595. * @param wait The wait queue to enter
  596. * @param timeout The maximum time, in ms, to wait
  597. *
  598. * If the timeout is zero, this function returns immediately with
  599. * ERR_TIMED_OUT. If the timeout is INFINITE_TIME, this function
  600. * waits indefinitely. Otherwise, this function returns with
  601. * ERR_TIMED_OUT at the end of the timeout period.
  602. *
  603. * @return ERR_TIMED_OUT on timeout, else returns the return
  604. * value specified when the queue was woken by wait_queue_wake_one().
  605. */
  606. status_t wait_queue_block(wait_queue_t *wait, time_t timeout)
  607. {
  608. timer_t timer;
  609. #if THREAD_CHECKS
  610. ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
  611. ASSERT(current_thread->state == THREAD_RUNNING);
  612. ASSERT(in_critical_section());
  613. #endif
  614. if (timeout == 0)
  615. return ERR_TIMED_OUT;
  616. list_add_tail(&wait->list, &current_thread->queue_node);
  617. wait->count++;
  618. current_thread->state = THREAD_BLOCKED;
  619. current_thread->blocking_wait_queue = wait;
  620. current_thread->wait_queue_block_ret = NO_ERROR;
  621. /* if the timeout is nonzero or noninfinite, set a callback to yank us out of the queue */
  622. if (timeout != INFINITE_TIME) {
  623. timer_initialize(&timer);
  624. timer_set_oneshot(&timer, timeout, wait_queue_timeout_handler, (void *)current_thread);
  625. }
  626. thread_block();
  627. /* we don't really know if the timer fired or not, so it's better safe to try to cancel it */
  628. if (timeout != INFINITE_TIME) {
  629. timer_cancel(&timer);
  630. }
  631. return current_thread->wait_queue_block_ret;
  632. }
  633. /**
  634. * @brief Wake up one thread sleeping on a wait queue
  635. *
  636. * This function removes one thread (if any) from the head of the wait queue and
  637. * makes it executable. The new thread will be placed at the head of the
  638. * run queue.
  639. *
  640. * @param wait The wait queue to wake
  641. * @param reschedule If true, the newly-woken thread will run immediately.
  642. * @param wait_queue_error The return value which the new thread will receive
  643. * from wait_queue_block().
  644. *
  645. * @return The number of threads woken (zero or one)
  646. */
  647. int wait_queue_wake_one(wait_queue_t *wait, bool reschedule, status_t wait_queue_error)
  648. {
  649. thread_t *t;
  650. int ret = 0;
  651. #if THREAD_CHECKS
  652. ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
  653. ASSERT(in_critical_section());
  654. #endif
  655. t = list_remove_head_type(&wait->list, thread_t, queue_node);
  656. if (t) {
  657. wait->count--;
  658. #if THREAD_CHECKS
  659. ASSERT(t->state == THREAD_BLOCKED);
  660. #endif
  661. t->state = THREAD_READY;
  662. t->wait_queue_block_ret = wait_queue_error;
  663. t->blocking_wait_queue = NULL;
  664. /* if we're instructed to reschedule, stick the current thread on the head
  665. * of the run queue first, so that the newly awakened thread gets a chance to run
  666. * before the current one, but the current one doesn't get unnecessarilly punished.
  667. */
  668. if (reschedule) {
  669. current_thread->state = THREAD_READY;
  670. insert_in_run_queue_head(current_thread);
  671. }
  672. insert_in_run_queue_head(t);
  673. if (reschedule)
  674. thread_resched();
  675. ret = 1;
  676. }
  677. return ret;
  678. }
  679. /**
  680. * @brief Wake all threads sleeping on a wait queue
  681. *
  682. * This function removes all threads (if any) from the wait queue and
  683. * makes them executable. The new threads will be placed at the head of the
  684. * run queue.
  685. *
  686. * @param wait The wait queue to wake
  687. * @param reschedule If true, the newly-woken threads will run immediately.
  688. * @param wait_queue_error The return value which the new thread will receive
  689. * from wait_queue_block().
  690. *
  691. * @return The number of threads woken (zero or one)
  692. */
  693. int wait_queue_wake_all(wait_queue_t *wait, bool reschedule, status_t wait_queue_error)
  694. {
  695. thread_t *t;
  696. int ret = 0;
  697. #if THREAD_CHECKS
  698. ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
  699. ASSERT(in_critical_section());
  700. #endif
  701. if (reschedule && wait->count > 0) {
  702. /* if we're instructed to reschedule, stick the current thread on the head
  703. * of the run queue first, so that the newly awakened threads get a chance to run
  704. * before the current one, but the current one doesn't get unnecessarilly punished.
  705. */
  706. current_thread->state = THREAD_READY;
  707. insert_in_run_queue_head(current_thread);
  708. }
  709. /* pop all the threads off the wait queue into the run queue */
  710. while ((t = list_remove_head_type(&wait->list, thread_t, queue_node))) {
  711. wait->count--;
  712. #if THREAD_CHECKS
  713. ASSERT(t->state == THREAD_BLOCKED);
  714. #endif
  715. t->state = THREAD_READY;
  716. t->wait_queue_block_ret = wait_queue_error;
  717. t->blocking_wait_queue = NULL;
  718. insert_in_run_queue_head(t);
  719. ret++;
  720. }
  721. #if THREAD_CHECKS
  722. ASSERT(wait->count == 0);
  723. #endif
  724. if (reschedule && ret > 0)
  725. thread_resched();
  726. return ret;
  727. }
  728. /**
  729. * @brief Free all resources allocated in wait_queue_init()
  730. *
  731. * If any threads were waiting on this queue, they are all woken.
  732. */
  733. void wait_queue_destroy(wait_queue_t *wait, bool reschedule)
  734. {
  735. #if THREAD_CHECKS
  736. ASSERT(wait->magic == WAIT_QUEUE_MAGIC);
  737. ASSERT(in_critical_section());
  738. #endif
  739. wait_queue_wake_all(wait, reschedule, ERR_OBJECT_DESTROYED);
  740. wait->magic = 0;
  741. }
  742. /**
  743. * @brief Wake a specific thread in a wait queue
  744. *
  745. * This function extracts a specific thread from a wait queue, wakes it, and
  746. * puts it at the head of the run queue.
  747. *
  748. * @param t The thread to wake
  749. * @param reschedule If true, the newly-woken threads will run immediately.
  750. * @param wait_queue_error The return value which the new thread will receive
  751. * from wait_queue_block().
  752. *
  753. * @return ERR_NOT_BLOCKED if thread was not in any wait queue.
  754. */
  755. status_t thread_unblock_from_wait_queue(thread_t *t, bool reschedule, status_t wait_queue_error)
  756. {
  757. enter_critical_section();
  758. #if THREAD_CHECKS
  759. ASSERT(t->magic == THREAD_MAGIC);
  760. #endif
  761. if (t->state != THREAD_BLOCKED)
  762. return ERR_NOT_BLOCKED;
  763. #if THREAD_CHECKS
  764. ASSERT(t->blocking_wait_queue != NULL);
  765. ASSERT(t->blocking_wait_queue->magic == WAIT_QUEUE_MAGIC);
  766. ASSERT(list_in_list(&t->queue_node));
  767. #endif
  768. list_delete(&t->queue_node);
  769. t->blocking_wait_queue->count--;
  770. t->blocking_wait_queue = NULL;
  771. t->state = THREAD_READY;
  772. t->wait_queue_block_ret = wait_queue_error;
  773. insert_in_run_queue_head(t);
  774. if (reschedule)
  775. thread_resched();
  776. exit_critical_section();
  777. return NO_ERROR;
  778. }