sbtools/elftosb1: implement key file loading
[maemo-rb.git] / firmware / thread.c
blobce9252ccc68551bc6bcbcb73708a827a35ae62a4
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "config.h"
23 #ifdef HAVE_SIGALTSTACK_THREADS
25 * The sp check in glibc __longjmp_chk() will cause
26 * a fatal error when switching threads via longjmp().
28 #undef _FORTIFY_SOURCE
29 #endif
31 #include <stdbool.h>
32 #include <stdio.h>
33 #include "thread.h"
34 #include "panic.h"
35 #include "system.h"
36 #include "kernel.h"
37 #include "cpu.h"
38 #include "string.h"
39 #ifdef RB_PROFILE
40 #include <profile.h>
41 #endif
42 #include "gcc_extensions.h"
44 /****************************************************************************
45 * ATTENTION!! *
46 * See notes below on implementing processor-specific portions! *
47 ***************************************************************************/
49 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
50 #ifdef DEBUG
51 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
52 #else
53 #define THREAD_EXTRA_CHECKS 0
54 #endif
56 /**
57 * General locking order to guarantee progress. Order must be observed but
58 * all stages are not nescessarily obligatory. Going from 1) to 3) is
59 * perfectly legal.
61 * 1) IRQ
62 * This is first because of the likelyhood of having an interrupt occur that
63 * also accesses one of the objects farther down the list. Any non-blocking
64 * synchronization done may already have a lock on something during normal
65 * execution and if an interrupt handler running on the same processor as
66 * the one that has the resource locked were to attempt to access the
67 * resource, the interrupt handler would wait forever waiting for an unlock
68 * that will never happen. There is no danger if the interrupt occurs on
69 * a different processor because the one that has the lock will eventually
70 * unlock and the other processor's handler may proceed at that time. Not
71 * nescessary when the resource in question is definitely not available to
72 * interrupt handlers.
74 * 2) Kernel Object
75 * 1) May be needed beforehand if the kernel object allows dual-use such as
76 * event queues. The kernel object must have a scheme to protect itself from
77 * access by another processor and is responsible for serializing the calls
78 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
79 * other. Objects' queues are also protected here.
81 * 3) Thread Slot
82 * This locks access to the thread's slot such that its state cannot be
83 * altered by another processor when a state change is in progress such as
84 * when it is in the process of going on a blocked list. An attempt to wake
85 * a thread while it is still blocking will likely desync its state with
86 * the other resources used for that state.
88 * 4) Core Lists
89 * These lists are specific to a particular processor core and are accessible
90 * by all processor cores and interrupt handlers. The running (rtr) list is
91 * the prime example where a thread may be added by any means.
94 /*---------------------------------------------------------------------------
95 * Processor specific: core_sleep/core_wake/misc. notes
97 * ARM notes:
98 * FIQ is not dealt with by the scheduler code and is simply restored if it
99 * must by masked for some reason - because threading modifies a register
100 * that FIQ may also modify and there's no way to accomplish it atomically.
101 * s3c2440 is such a case.
103 * Audio interrupts are generally treated at a higher priority than others
104 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
105 * are not in general safe. Special cases may be constructed on a per-
106 * source basis and blocking operations are not available.
108 * core_sleep procedure to implement for any CPU to ensure an asychronous
109 * wakup never results in requiring a wait until the next tick (up to
110 * 10000uS!). May require assembly and careful instruction ordering.
112 * 1) On multicore, stay awake if directed to do so by another. If so, goto
113 * step 4.
114 * 2) If processor requires, atomically reenable interrupts and perform step
115 * 3.
116 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
117 * on Coldfire) goto step 5.
118 * 4) Enable interrupts.
119 * 5) Exit procedure.
121 * core_wake and multprocessor notes for sleep/wake coordination:
122 * If possible, to wake up another processor, the forcing of an interrupt on
123 * the woken core by the waker core is the easiest way to ensure a non-
124 * delayed wake and immediate execution of any woken threads. If that isn't
125 * available then some careful non-blocking synchonization is needed (as on
126 * PP targets at the moment).
127 *---------------------------------------------------------------------------
130 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
131 * (someday :). */
132 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
133 static struct core_entry cores[NUM_CORES] IBSS_ATTR;
134 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
136 static const char main_thread_name[] = "main";
137 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
138 extern uintptr_t stackbegin[];
139 extern uintptr_t stackend[];
140 #else
141 extern uintptr_t *stackbegin;
142 extern uintptr_t *stackend;
143 #endif
145 static inline void core_sleep(IF_COP_VOID(unsigned int core))
146 __attribute__((always_inline));
148 void check_tmo_threads(void)
149 __attribute__((noinline));
151 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
152 __attribute__((always_inline));
154 static void add_to_list_tmo(struct thread_entry *thread)
155 __attribute__((noinline));
157 static void core_schedule_wakeup(struct thread_entry *thread)
158 __attribute__((noinline));
160 #if NUM_CORES > 1
161 static inline void run_blocking_ops(
162 unsigned int core, struct thread_entry *thread)
163 __attribute__((always_inline));
164 #endif
166 static void thread_stkov(struct thread_entry *thread)
167 __attribute__((noinline));
169 static inline void store_context(void* addr)
170 __attribute__((always_inline));
172 static inline void load_context(const void* addr)
173 __attribute__((always_inline));
175 #if NUM_CORES > 1
176 static void thread_final_exit_do(struct thread_entry *current)
177 __attribute__((noinline)) NORETURN_ATTR USED_ATTR;
178 #else
179 static inline void thread_final_exit(struct thread_entry *current)
180 __attribute__((always_inline)) NORETURN_ATTR;
181 #endif
183 void switch_thread(void)
184 __attribute__((noinline));
186 /****************************************************************************
187 * Processor/OS-specific section - include necessary core support
191 #include "asm/thread.c"
193 #if defined (CPU_PP)
194 #include "thread-pp.c"
195 #endif /* CPU_PP */
197 #ifndef IF_NO_SKIP_YIELD
198 #define IF_NO_SKIP_YIELD(...)
199 #endif
202 * End Processor-specific section
203 ***************************************************************************/
205 #if THREAD_EXTRA_CHECKS
206 static void thread_panicf(const char *msg, struct thread_entry *thread)
208 IF_COP( const unsigned int core = thread->core; )
209 static char name[32];
210 thread_get_name(name, 32, thread);
211 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
213 static void thread_stkov(struct thread_entry *thread)
215 thread_panicf("Stkov", thread);
217 #define THREAD_PANICF(msg, thread) \
218 thread_panicf(msg, thread)
219 #define THREAD_ASSERT(exp, msg, thread) \
220 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
221 #else
222 static void thread_stkov(struct thread_entry *thread)
224 IF_COP( const unsigned int core = thread->core; )
225 static char name[32];
226 thread_get_name(name, 32, thread);
227 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
229 #define THREAD_PANICF(msg, thread)
230 #define THREAD_ASSERT(exp, msg, thread)
231 #endif /* THREAD_EXTRA_CHECKS */
233 /* Thread locking */
234 #if NUM_CORES > 1
235 #define LOCK_THREAD(thread) \
236 ({ corelock_lock(&(thread)->slot_cl); })
237 #define TRY_LOCK_THREAD(thread) \
238 ({ corelock_try_lock(&(thread)->slot_cl); })
239 #define UNLOCK_THREAD(thread) \
240 ({ corelock_unlock(&(thread)->slot_cl); })
241 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
242 ({ unsigned int _core = (thread)->core; \
243 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
244 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
245 #else
246 #define LOCK_THREAD(thread) \
247 ({ })
248 #define TRY_LOCK_THREAD(thread) \
249 ({ })
250 #define UNLOCK_THREAD(thread) \
251 ({ })
252 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
253 ({ })
254 #endif
256 /* RTR list */
257 #define RTR_LOCK(core) \
258 ({ corelock_lock(&cores[core].rtr_cl); })
259 #define RTR_UNLOCK(core) \
260 ({ corelock_unlock(&cores[core].rtr_cl); })
262 #ifdef HAVE_PRIORITY_SCHEDULING
263 #define rtr_add_entry(core, priority) \
264 prio_add_entry(&cores[core].rtr, (priority))
266 #define rtr_subtract_entry(core, priority) \
267 prio_subtract_entry(&cores[core].rtr, (priority))
269 #define rtr_move_entry(core, from, to) \
270 prio_move_entry(&cores[core].rtr, (from), (to))
271 #else
272 #define rtr_add_entry(core, priority)
273 #define rtr_add_entry_inl(core, priority)
274 #define rtr_subtract_entry(core, priority)
275 #define rtr_subtract_entry_inl(core, priotity)
276 #define rtr_move_entry(core, from, to)
277 #define rtr_move_entry_inl(core, from, to)
278 #endif
280 /*---------------------------------------------------------------------------
281 * Thread list structure - circular:
282 * +------------------------------+
283 * | |
284 * +--+---+<-+---+<-+---+<-+---+<-+
285 * Head->| T | | T | | T | | T |
286 * +->+---+->+---+->+---+->+---+--+
287 * | |
288 * +------------------------------+
289 *---------------------------------------------------------------------------
292 /*---------------------------------------------------------------------------
293 * Adds a thread to a list of threads using "insert last". Uses the "l"
294 * links.
295 *---------------------------------------------------------------------------
297 static void add_to_list_l(struct thread_entry **list,
298 struct thread_entry *thread)
300 struct thread_entry *l = *list;
302 if (l == NULL)
304 /* Insert into unoccupied list */
305 thread->l.prev = thread;
306 thread->l.next = thread;
307 *list = thread;
308 return;
311 /* Insert last */
312 thread->l.prev = l->l.prev;
313 thread->l.next = l;
314 l->l.prev->l.next = thread;
315 l->l.prev = thread;
318 /*---------------------------------------------------------------------------
319 * Removes a thread from a list of threads. Uses the "l" links.
320 *---------------------------------------------------------------------------
322 static void remove_from_list_l(struct thread_entry **list,
323 struct thread_entry *thread)
325 struct thread_entry *prev, *next;
327 next = thread->l.next;
329 if (thread == next)
331 /* The only item */
332 *list = NULL;
333 return;
336 if (thread == *list)
338 /* List becomes next item */
339 *list = next;
342 prev = thread->l.prev;
344 /* Fix links to jump over the removed entry. */
345 next->l.prev = prev;
346 prev->l.next = next;
349 /*---------------------------------------------------------------------------
350 * Timeout list structure - circular reverse (to make "remove item" O(1)),
351 * NULL-terminated forward (to ease the far more common forward traversal):
352 * +------------------------------+
353 * | |
354 * +--+---+<-+---+<-+---+<-+---+<-+
355 * Head->| T | | T | | T | | T |
356 * +---+->+---+->+---+->+---+-X
357 *---------------------------------------------------------------------------
360 /*---------------------------------------------------------------------------
361 * Add a thread from the core's timout list by linking the pointers in its
362 * tmo structure.
363 *---------------------------------------------------------------------------
365 static void add_to_list_tmo(struct thread_entry *thread)
367 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
368 THREAD_ASSERT(thread->tmo.prev == NULL,
369 "add_to_list_tmo->already listed", thread);
371 thread->tmo.next = NULL;
373 if (tmo == NULL)
375 /* Insert into unoccupied list */
376 thread->tmo.prev = thread;
377 cores[IF_COP_CORE(thread->core)].timeout = thread;
378 return;
381 /* Insert Last */
382 thread->tmo.prev = tmo->tmo.prev;
383 tmo->tmo.prev->tmo.next = thread;
384 tmo->tmo.prev = thread;
387 /*---------------------------------------------------------------------------
388 * Remove a thread from the core's timout list by unlinking the pointers in
389 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
390 * is cancelled.
391 *---------------------------------------------------------------------------
393 static void remove_from_list_tmo(struct thread_entry *thread)
395 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
396 struct thread_entry *prev = thread->tmo.prev;
397 struct thread_entry *next = thread->tmo.next;
399 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
401 if (next != NULL)
402 next->tmo.prev = prev;
404 if (thread == *list)
406 /* List becomes next item and empty if next == NULL */
407 *list = next;
408 /* Mark as unlisted */
409 thread->tmo.prev = NULL;
411 else
413 if (next == NULL)
414 (*list)->tmo.prev = prev;
415 prev->tmo.next = next;
416 /* Mark as unlisted */
417 thread->tmo.prev = NULL;
422 #ifdef HAVE_PRIORITY_SCHEDULING
423 /*---------------------------------------------------------------------------
424 * Priority distribution structure (one category for each possible priority):
426 * +----+----+----+ ... +-----+
427 * hist: | F0 | F1 | F2 | | F31 |
428 * +----+----+----+ ... +-----+
429 * mask: | b0 | b1 | b2 | | b31 |
430 * +----+----+----+ ... +-----+
432 * F = count of threads at priority category n (frequency)
433 * b = bitmask of non-zero priority categories (occupancy)
435 * / if H[n] != 0 : 1
436 * b[n] = |
437 * \ else : 0
439 *---------------------------------------------------------------------------
440 * Basic priority inheritance priotocol (PIP):
442 * Mn = mutex n, Tn = thread n
444 * A lower priority thread inherits the priority of the highest priority
445 * thread blocked waiting for it to complete an action (such as release a
446 * mutex or respond to a message via queue_send):
448 * 1) T2->M1->T1
450 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
451 * priority than T1 then T1 inherits the priority of T2.
453 * 2) T3
454 * \/
455 * T2->M1->T1
457 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
458 * T1 inherits the higher of T2 and T3.
460 * 3) T3->M2->T2->M1->T1
462 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
463 * then T1 inherits the priority of T3 through T2.
465 * Blocking chains can grow arbitrarily complex (though it's best that they
466 * not form at all very often :) and build-up from these units.
467 *---------------------------------------------------------------------------
470 /*---------------------------------------------------------------------------
471 * Increment frequency at category "priority"
472 *---------------------------------------------------------------------------
474 static inline unsigned int prio_add_entry(
475 struct priority_distribution *pd, int priority)
477 unsigned int count;
478 /* Enough size/instruction count difference for ARM makes it worth it to
479 * use different code (192 bytes for ARM). Only thing better is ASM. */
480 #ifdef CPU_ARM
481 count = pd->hist[priority];
482 if (++count == 1)
483 pd->mask |= 1 << priority;
484 pd->hist[priority] = count;
485 #else /* This one's better for Coldfire */
486 if ((count = ++pd->hist[priority]) == 1)
487 pd->mask |= 1 << priority;
488 #endif
490 return count;
493 /*---------------------------------------------------------------------------
494 * Decrement frequency at category "priority"
495 *---------------------------------------------------------------------------
497 static inline unsigned int prio_subtract_entry(
498 struct priority_distribution *pd, int priority)
500 unsigned int count;
502 #ifdef CPU_ARM
503 count = pd->hist[priority];
504 if (--count == 0)
505 pd->mask &= ~(1 << priority);
506 pd->hist[priority] = count;
507 #else
508 if ((count = --pd->hist[priority]) == 0)
509 pd->mask &= ~(1 << priority);
510 #endif
512 return count;
515 /*---------------------------------------------------------------------------
516 * Remove from one category and add to another
517 *---------------------------------------------------------------------------
519 static inline void prio_move_entry(
520 struct priority_distribution *pd, int from, int to)
522 uint32_t mask = pd->mask;
524 #ifdef CPU_ARM
525 unsigned int count;
527 count = pd->hist[from];
528 if (--count == 0)
529 mask &= ~(1 << from);
530 pd->hist[from] = count;
532 count = pd->hist[to];
533 if (++count == 1)
534 mask |= 1 << to;
535 pd->hist[to] = count;
536 #else
537 if (--pd->hist[from] == 0)
538 mask &= ~(1 << from);
540 if (++pd->hist[to] == 1)
541 mask |= 1 << to;
542 #endif
544 pd->mask = mask;
547 /*---------------------------------------------------------------------------
548 * Change the priority and rtr entry for a running thread
549 *---------------------------------------------------------------------------
551 static inline void set_running_thread_priority(
552 struct thread_entry *thread, int priority)
554 const unsigned int core = IF_COP_CORE(thread->core);
555 RTR_LOCK(core);
556 rtr_move_entry(core, thread->priority, priority);
557 thread->priority = priority;
558 RTR_UNLOCK(core);
561 /*---------------------------------------------------------------------------
562 * Finds the highest priority thread in a list of threads. If the list is
563 * empty, the PRIORITY_IDLE is returned.
565 * It is possible to use the struct priority_distribution within an object
566 * instead of scanning the remaining threads in the list but as a compromise,
567 * the resulting per-object memory overhead is saved at a slight speed
568 * penalty under high contention.
569 *---------------------------------------------------------------------------
571 static int find_highest_priority_in_list_l(
572 struct thread_entry * const thread)
574 if (LIKELY(thread != NULL))
576 /* Go though list until the ending up at the initial thread */
577 int highest_priority = thread->priority;
578 struct thread_entry *curr = thread;
582 int priority = curr->priority;
584 if (priority < highest_priority)
585 highest_priority = priority;
587 curr = curr->l.next;
589 while (curr != thread);
591 return highest_priority;
594 return PRIORITY_IDLE;
597 /*---------------------------------------------------------------------------
598 * Register priority with blocking system and bubble it down the chain if
599 * any until we reach the end or something is already equal or higher.
601 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
602 * targets but that same action also guarantees a circular block anyway and
603 * those are prevented, right? :-)
604 *---------------------------------------------------------------------------
606 static struct thread_entry *
607 blocker_inherit_priority(struct thread_entry *current)
609 const int priority = current->priority;
610 struct blocker *bl = current->blocker;
611 struct thread_entry * const tstart = current;
612 struct thread_entry *bl_t = bl->thread;
614 /* Blocker cannot change since the object protection is held */
615 LOCK_THREAD(bl_t);
617 for (;;)
619 struct thread_entry *next;
620 int bl_pr = bl->priority;
622 if (priority >= bl_pr)
623 break; /* Object priority already high enough */
625 bl->priority = priority;
627 /* Add this one */
628 prio_add_entry(&bl_t->pdist, priority);
630 if (bl_pr < PRIORITY_IDLE)
632 /* Not first waiter - subtract old one */
633 prio_subtract_entry(&bl_t->pdist, bl_pr);
636 if (priority >= bl_t->priority)
637 break; /* Thread priority high enough */
639 if (bl_t->state == STATE_RUNNING)
641 /* Blocking thread is a running thread therefore there are no
642 * further blockers. Change the "run queue" on which it
643 * resides. */
644 set_running_thread_priority(bl_t, priority);
645 break;
648 bl_t->priority = priority;
650 /* If blocking thread has a blocker, apply transitive inheritance */
651 bl = bl_t->blocker;
653 if (bl == NULL)
654 break; /* End of chain or object doesn't support inheritance */
656 next = bl->thread;
658 if (UNLIKELY(next == tstart))
659 break; /* Full-circle - deadlock! */
661 UNLOCK_THREAD(current);
663 #if NUM_CORES > 1
664 for (;;)
666 LOCK_THREAD(next);
668 /* Blocker could change - retest condition */
669 if (LIKELY(bl->thread == next))
670 break;
672 UNLOCK_THREAD(next);
673 next = bl->thread;
675 #endif
676 current = bl_t;
677 bl_t = next;
680 UNLOCK_THREAD(bl_t);
682 return current;
685 /*---------------------------------------------------------------------------
686 * Readjust priorities when waking a thread blocked waiting for another
687 * in essence "releasing" the thread's effect on the object owner. Can be
688 * performed from any context.
689 *---------------------------------------------------------------------------
691 struct thread_entry *
692 wakeup_priority_protocol_release(struct thread_entry *thread)
694 const int priority = thread->priority;
695 struct blocker *bl = thread->blocker;
696 struct thread_entry * const tstart = thread;
697 struct thread_entry *bl_t = bl->thread;
699 /* Blocker cannot change since object will be locked */
700 LOCK_THREAD(bl_t);
702 thread->blocker = NULL; /* Thread not blocked */
704 for (;;)
706 struct thread_entry *next;
707 int bl_pr = bl->priority;
709 if (priority > bl_pr)
710 break; /* Object priority higher */
712 next = *thread->bqp;
714 if (next == NULL)
716 /* No more threads in queue */
717 prio_subtract_entry(&bl_t->pdist, bl_pr);
718 bl->priority = PRIORITY_IDLE;
720 else
722 /* Check list for highest remaining priority */
723 int queue_pr = find_highest_priority_in_list_l(next);
725 if (queue_pr == bl_pr)
726 break; /* Object priority not changing */
728 /* Change queue priority */
729 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
730 bl->priority = queue_pr;
733 if (bl_pr > bl_t->priority)
734 break; /* thread priority is higher */
736 bl_pr = find_first_set_bit(bl_t->pdist.mask);
738 if (bl_pr == bl_t->priority)
739 break; /* Thread priority not changing */
741 if (bl_t->state == STATE_RUNNING)
743 /* No further blockers */
744 set_running_thread_priority(bl_t, bl_pr);
745 break;
748 bl_t->priority = bl_pr;
750 /* If blocking thread has a blocker, apply transitive inheritance */
751 bl = bl_t->blocker;
753 if (bl == NULL)
754 break; /* End of chain or object doesn't support inheritance */
756 next = bl->thread;
758 if (UNLIKELY(next == tstart))
759 break; /* Full-circle - deadlock! */
761 UNLOCK_THREAD(thread);
763 #if NUM_CORES > 1
764 for (;;)
766 LOCK_THREAD(next);
768 /* Blocker could change - retest condition */
769 if (LIKELY(bl->thread == next))
770 break;
772 UNLOCK_THREAD(next);
773 next = bl->thread;
775 #endif
776 thread = bl_t;
777 bl_t = next;
780 UNLOCK_THREAD(bl_t);
782 #if NUM_CORES > 1
783 if (UNLIKELY(thread != tstart))
785 /* Relock original if it changed */
786 LOCK_THREAD(tstart);
788 #endif
790 return cores[CURRENT_CORE].running;
793 /*---------------------------------------------------------------------------
794 * Transfer ownership to a thread waiting for an objects and transfer
795 * inherited priority boost from other waiters. This algorithm knows that
796 * blocking chains may only unblock from the very end.
798 * Only the owning thread itself may call this and so the assumption that
799 * it is the running thread is made.
800 *---------------------------------------------------------------------------
802 struct thread_entry *
803 wakeup_priority_protocol_transfer(struct thread_entry *thread)
805 /* Waking thread inherits priority boost from object owner */
806 struct blocker *bl = thread->blocker;
807 struct thread_entry *bl_t = bl->thread;
808 struct thread_entry *next;
809 int bl_pr;
811 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
812 "UPPT->wrong thread", cores[CURRENT_CORE].running);
814 LOCK_THREAD(bl_t);
816 bl_pr = bl->priority;
818 /* Remove the object's boost from the owning thread */
819 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
820 bl_pr <= bl_t->priority)
822 /* No more threads at this priority are waiting and the old level is
823 * at least the thread level */
824 int priority = find_first_set_bit(bl_t->pdist.mask);
826 if (priority != bl_t->priority)
828 /* Adjust this thread's priority */
829 set_running_thread_priority(bl_t, priority);
833 next = *thread->bqp;
835 if (LIKELY(next == NULL))
837 /* Expected shortcut - no more waiters */
838 bl_pr = PRIORITY_IDLE;
840 else
842 if (thread->priority <= bl_pr)
844 /* Need to scan threads remaining in queue */
845 bl_pr = find_highest_priority_in_list_l(next);
848 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
849 bl_pr < thread->priority)
851 /* Thread priority must be raised */
852 thread->priority = bl_pr;
856 bl->thread = thread; /* This thread pwns */
857 bl->priority = bl_pr; /* Save highest blocked priority */
858 thread->blocker = NULL; /* Thread not blocked */
860 UNLOCK_THREAD(bl_t);
862 return bl_t;
865 /*---------------------------------------------------------------------------
866 * No threads must be blocked waiting for this thread except for it to exit.
867 * The alternative is more elaborate cleanup and object registration code.
868 * Check this for risk of silent data corruption when objects with
869 * inheritable blocking are abandoned by the owner - not precise but may
870 * catch something.
871 *---------------------------------------------------------------------------
873 static void __attribute__((noinline)) check_for_obj_waiters(
874 const char *function, struct thread_entry *thread)
876 /* Only one bit in the mask should be set with a frequency on 1 which
877 * represents the thread's own base priority */
878 uint32_t mask = thread->pdist.mask;
879 if ((mask & (mask - 1)) != 0 ||
880 thread->pdist.hist[find_first_set_bit(mask)] > 1)
882 unsigned char name[32];
883 thread_get_name(name, 32, thread);
884 panicf("%s->%s with obj. waiters", function, name);
887 #endif /* HAVE_PRIORITY_SCHEDULING */
889 /*---------------------------------------------------------------------------
890 * Move a thread back to a running state on its core.
891 *---------------------------------------------------------------------------
893 static void core_schedule_wakeup(struct thread_entry *thread)
895 const unsigned int core = IF_COP_CORE(thread->core);
897 RTR_LOCK(core);
899 thread->state = STATE_RUNNING;
901 add_to_list_l(&cores[core].running, thread);
902 rtr_add_entry(core, thread->priority);
904 RTR_UNLOCK(core);
906 #if NUM_CORES > 1
907 if (core != CURRENT_CORE)
908 core_wake(core);
909 #endif
912 /*---------------------------------------------------------------------------
913 * Check the core's timeout list when at least one thread is due to wake.
914 * Filtering for the condition is done before making the call. Resets the
915 * tick when the next check will occur.
916 *---------------------------------------------------------------------------
918 void check_tmo_threads(void)
920 const unsigned int core = CURRENT_CORE;
921 const long tick = current_tick; /* snapshot the current tick */
922 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
923 struct thread_entry *next = cores[core].timeout;
925 /* If there are no processes waiting for a timeout, just keep the check
926 tick from falling into the past. */
928 /* Break the loop once we have walked through the list of all
929 * sleeping processes or have removed them all. */
930 while (next != NULL)
932 /* Check sleeping threads. Allow interrupts between checks. */
933 enable_irq();
935 struct thread_entry *curr = next;
937 next = curr->tmo.next;
939 /* Lock thread slot against explicit wakeup */
940 disable_irq();
941 LOCK_THREAD(curr);
943 unsigned state = curr->state;
945 if (state < TIMEOUT_STATE_FIRST)
947 /* Cleanup threads no longer on a timeout but still on the
948 * list. */
949 remove_from_list_tmo(curr);
951 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
953 /* Timeout still pending - this will be the usual case */
954 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
956 /* Earliest timeout found so far - move the next check up
957 to its time */
958 next_tmo_check = curr->tmo_tick;
961 else
963 /* Sleep timeout has been reached so bring the thread back to
964 * life again. */
965 if (state == STATE_BLOCKED_W_TMO)
967 #ifdef HAVE_CORELOCK_OBJECT
968 /* Lock the waiting thread's kernel object */
969 struct corelock *ocl = curr->obj_cl;
971 if (UNLIKELY(corelock_try_lock(ocl) == 0))
973 /* Need to retry in the correct order though the need is
974 * unlikely */
975 UNLOCK_THREAD(curr);
976 corelock_lock(ocl);
977 LOCK_THREAD(curr);
979 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
981 /* Thread was woken or removed explicitely while slot
982 * was unlocked */
983 corelock_unlock(ocl);
984 remove_from_list_tmo(curr);
985 UNLOCK_THREAD(curr);
986 continue;
989 #endif /* NUM_CORES */
991 remove_from_list_l(curr->bqp, curr);
993 #ifdef HAVE_WAKEUP_EXT_CB
994 if (curr->wakeup_ext_cb != NULL)
995 curr->wakeup_ext_cb(curr);
996 #endif
998 #ifdef HAVE_PRIORITY_SCHEDULING
999 if (curr->blocker != NULL)
1000 wakeup_priority_protocol_release(curr);
1001 #endif
1002 corelock_unlock(ocl);
1004 /* else state == STATE_SLEEPING */
1006 remove_from_list_tmo(curr);
1008 RTR_LOCK(core);
1010 curr->state = STATE_RUNNING;
1012 add_to_list_l(&cores[core].running, curr);
1013 rtr_add_entry(core, curr->priority);
1015 RTR_UNLOCK(core);
1018 UNLOCK_THREAD(curr);
1021 cores[core].next_tmo_check = next_tmo_check;
1024 /*---------------------------------------------------------------------------
1025 * Performs operations that must be done before blocking a thread but after
1026 * the state is saved.
1027 *---------------------------------------------------------------------------
1029 #if NUM_CORES > 1
1030 static inline void run_blocking_ops(
1031 unsigned int core, struct thread_entry *thread)
1033 struct thread_blk_ops *ops = &cores[core].blk_ops;
1034 const unsigned flags = ops->flags;
1036 if (LIKELY(flags == TBOP_CLEAR))
1037 return;
1039 switch (flags)
1041 case TBOP_SWITCH_CORE:
1042 core_switch_blk_op(core, thread);
1043 /* Fall-through */
1044 case TBOP_UNLOCK_CORELOCK:
1045 corelock_unlock(ops->cl_p);
1046 break;
1049 ops->flags = TBOP_CLEAR;
1051 #endif /* NUM_CORES > 1 */
1053 #ifdef RB_PROFILE
1054 void profile_thread(void)
1056 profstart(cores[CURRENT_CORE].running - threads);
1058 #endif
1060 /*---------------------------------------------------------------------------
1061 * Prepares a thread to block on an object's list and/or for a specified
1062 * duration - expects object and slot to be appropriately locked if needed
1063 * and interrupts to be masked.
1064 *---------------------------------------------------------------------------
1066 static inline void block_thread_on_l(struct thread_entry *thread,
1067 unsigned state)
1069 /* If inlined, unreachable branches will be pruned with no size penalty
1070 because state is passed as a constant parameter. */
1071 const unsigned int core = IF_COP_CORE(thread->core);
1073 /* Remove the thread from the list of running threads. */
1074 RTR_LOCK(core);
1075 remove_from_list_l(&cores[core].running, thread);
1076 rtr_subtract_entry(core, thread->priority);
1077 RTR_UNLOCK(core);
1079 /* Add a timeout to the block if not infinite */
1080 switch (state)
1082 case STATE_BLOCKED:
1083 case STATE_BLOCKED_W_TMO:
1084 /* Put the thread into a new list of inactive threads. */
1085 add_to_list_l(thread->bqp, thread);
1087 if (state == STATE_BLOCKED)
1088 break;
1090 /* Fall-through */
1091 case STATE_SLEEPING:
1092 /* If this thread times out sooner than any other thread, update
1093 next_tmo_check to its timeout */
1094 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1096 cores[core].next_tmo_check = thread->tmo_tick;
1099 if (thread->tmo.prev == NULL)
1101 add_to_list_tmo(thread);
1103 /* else thread was never removed from list - just keep it there */
1104 break;
1107 /* Remember the the next thread about to block. */
1108 cores[core].block_task = thread;
1110 /* Report new state. */
1111 thread->state = state;
1114 /*---------------------------------------------------------------------------
1115 * Switch thread in round robin fashion for any given priority. Any thread
1116 * that removed itself from the running list first must specify itself in
1117 * the paramter.
1119 * INTERNAL: Intended for use by kernel and not for programs.
1120 *---------------------------------------------------------------------------
1122 void switch_thread(void)
1125 const unsigned int core = CURRENT_CORE;
1126 struct thread_entry *block = cores[core].block_task;
1127 struct thread_entry *thread = cores[core].running;
1129 /* Get context to save - next thread to run is unknown until all wakeups
1130 * are evaluated */
1131 if (block != NULL)
1133 cores[core].block_task = NULL;
1135 #if NUM_CORES > 1
1136 if (UNLIKELY(thread == block))
1138 /* This was the last thread running and another core woke us before
1139 * reaching here. Force next thread selection to give tmo threads or
1140 * other threads woken before this block a first chance. */
1141 block = NULL;
1143 else
1144 #endif
1146 /* Blocking task is the old one */
1147 thread = block;
1151 #ifdef RB_PROFILE
1152 #ifdef CPU_COLDFIRE
1153 _profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
1154 #else
1155 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
1156 #endif
1157 #endif
1159 /* Begin task switching by saving our current context so that we can
1160 * restore the state of the current thread later to the point prior
1161 * to this call. */
1162 store_context(&thread->context);
1164 /* Check if the current thread stack is overflown */
1165 if (UNLIKELY(thread->stack[0] != DEADBEEF) && thread->stack_size > 0)
1166 thread_stkov(thread);
1168 #if NUM_CORES > 1
1169 /* Run any blocking operations requested before switching/sleeping */
1170 run_blocking_ops(core, thread);
1171 #endif
1173 #ifdef HAVE_PRIORITY_SCHEDULING
1174 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1175 /* Reset the value of thread's skip count */
1176 thread->skip_count = 0;
1177 #endif
1179 for (;;)
1181 /* If there are threads on a timeout and the earliest wakeup is due,
1182 * check the list and wake any threads that need to start running
1183 * again. */
1184 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
1186 check_tmo_threads();
1189 disable_irq();
1190 RTR_LOCK(core);
1192 thread = cores[core].running;
1194 if (UNLIKELY(thread == NULL))
1196 /* Enter sleep mode to reduce power usage - woken up on interrupt
1197 * or wakeup request from another core - expected to enable
1198 * interrupts. */
1199 RTR_UNLOCK(core);
1200 core_sleep(IF_COP(core));
1202 else
1204 #ifdef HAVE_PRIORITY_SCHEDULING
1205 /* Select the new task based on priorities and the last time a
1206 * process got CPU time relative to the highest priority runnable
1207 * task. */
1208 struct priority_distribution *pd = &cores[core].rtr;
1209 int max = find_first_set_bit(pd->mask);
1211 if (block == NULL)
1213 /* Not switching on a block, tentatively select next thread */
1214 thread = thread->l.next;
1217 for (;;)
1219 int priority = thread->priority;
1220 int diff;
1222 /* This ridiculously simple method of aging seems to work
1223 * suspiciously well. It does tend to reward CPU hogs (under
1224 * yielding) but that's generally not desirable at all. On
1225 * the plus side, it, relatively to other threads, penalizes
1226 * excess yielding which is good if some high priority thread
1227 * is performing no useful work such as polling for a device
1228 * to be ready. Of course, aging is only employed when higher
1229 * and lower priority threads are runnable. The highest
1230 * priority runnable thread(s) are never skipped unless a
1231 * lower-priority process has aged sufficiently. Priorities
1232 * of REALTIME class are run strictly according to priority
1233 * thus are not subject to switchout due to lower-priority
1234 * processes aging; they must give up the processor by going
1235 * off the run list. */
1236 if (LIKELY(priority <= max) ||
1237 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
1238 (priority > PRIORITY_REALTIME &&
1239 (diff = priority - max,
1240 ++thread->skip_count > diff*diff)))
1242 cores[core].running = thread;
1243 break;
1246 thread = thread->l.next;
1248 #else
1249 /* Without priority use a simple FCFS algorithm */
1250 if (block == NULL)
1252 /* Not switching on a block, select next thread */
1253 thread = thread->l.next;
1254 cores[core].running = thread;
1256 #endif /* HAVE_PRIORITY_SCHEDULING */
1258 RTR_UNLOCK(core);
1259 enable_irq();
1260 break;
1264 /* And finally give control to the next thread. */
1265 load_context(&thread->context);
1267 #ifdef RB_PROFILE
1268 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
1269 #endif
1273 /*---------------------------------------------------------------------------
1274 * Sleeps a thread for at least a specified number of ticks with zero being
1275 * a wait until the next tick.
1277 * INTERNAL: Intended for use by kernel and not for programs.
1278 *---------------------------------------------------------------------------
1280 void sleep_thread(int ticks)
1282 struct thread_entry *current = cores[CURRENT_CORE].running;
1284 LOCK_THREAD(current);
1286 /* Set our timeout, remove from run list and join timeout list. */
1287 current->tmo_tick = current_tick + ticks + 1;
1288 block_thread_on_l(current, STATE_SLEEPING);
1290 UNLOCK_THREAD(current);
1293 /*---------------------------------------------------------------------------
1294 * Indefinitely block a thread on a blocking queue for explicit wakeup.
1296 * INTERNAL: Intended for use by kernel objects and not for programs.
1297 *---------------------------------------------------------------------------
1299 void block_thread(struct thread_entry *current)
1301 /* Set the state to blocked and take us off of the run queue until we
1302 * are explicitly woken */
1303 LOCK_THREAD(current);
1305 /* Set the list for explicit wakeup */
1306 block_thread_on_l(current, STATE_BLOCKED);
1308 #ifdef HAVE_PRIORITY_SCHEDULING
1309 if (current->blocker != NULL)
1311 /* Object supports PIP */
1312 current = blocker_inherit_priority(current);
1314 #endif
1316 UNLOCK_THREAD(current);
1319 /*---------------------------------------------------------------------------
1320 * Block a thread on a blocking queue for a specified time interval or until
1321 * explicitly woken - whichever happens first.
1323 * INTERNAL: Intended for use by kernel objects and not for programs.
1324 *---------------------------------------------------------------------------
1326 void block_thread_w_tmo(struct thread_entry *current, int timeout)
1328 /* Get the entry for the current running thread. */
1329 LOCK_THREAD(current);
1331 /* Set the state to blocked with the specified timeout */
1332 current->tmo_tick = current_tick + timeout;
1334 /* Set the list for explicit wakeup */
1335 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
1337 #ifdef HAVE_PRIORITY_SCHEDULING
1338 if (current->blocker != NULL)
1340 /* Object supports PIP */
1341 current = blocker_inherit_priority(current);
1343 #endif
1345 UNLOCK_THREAD(current);
1348 /*---------------------------------------------------------------------------
1349 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
1350 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
1352 * This code should be considered a critical section by the caller meaning
1353 * that the object's corelock should be held.
1355 * INTERNAL: Intended for use by kernel objects and not for programs.
1356 *---------------------------------------------------------------------------
1358 unsigned int wakeup_thread(struct thread_entry **list)
1360 struct thread_entry *thread = *list;
1361 unsigned int result = THREAD_NONE;
1363 /* Check if there is a blocked thread at all. */
1364 if (thread == NULL)
1365 return result;
1367 LOCK_THREAD(thread);
1369 /* Determine thread's current state. */
1370 switch (thread->state)
1372 case STATE_BLOCKED:
1373 case STATE_BLOCKED_W_TMO:
1374 remove_from_list_l(list, thread);
1376 result = THREAD_OK;
1378 #ifdef HAVE_PRIORITY_SCHEDULING
1379 struct thread_entry *current;
1380 struct blocker *bl = thread->blocker;
1382 if (bl == NULL)
1384 /* No inheritance - just boost the thread by aging */
1385 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1386 thread->skip_count = thread->priority;
1387 current = cores[CURRENT_CORE].running;
1389 else
1391 /* Call the specified unblocking PIP */
1392 current = bl->wakeup_protocol(thread);
1395 if (current != NULL &&
1396 find_first_set_bit(cores[IF_COP_CORE(current->core)].rtr.mask)
1397 < current->priority)
1399 /* There is a thread ready to run of higher or same priority on
1400 * the same core as the current one; recommend a task switch.
1401 * Knowing if this is an interrupt call would be helpful here. */
1402 result |= THREAD_SWITCH;
1404 #endif /* HAVE_PRIORITY_SCHEDULING */
1406 core_schedule_wakeup(thread);
1407 break;
1409 /* Nothing to do. State is not blocked. */
1410 #if THREAD_EXTRA_CHECKS
1411 default:
1412 THREAD_PANICF("wakeup_thread->block invalid", thread);
1413 case STATE_RUNNING:
1414 case STATE_KILLED:
1415 break;
1416 #endif
1419 UNLOCK_THREAD(thread);
1420 return result;
1423 /*---------------------------------------------------------------------------
1424 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
1425 * from each operation or THREAD_NONE of nothing was awakened. Object owning
1426 * the queue must be locked first.
1428 * INTERNAL: Intended for use by kernel objects and not for programs.
1429 *---------------------------------------------------------------------------
1431 unsigned int thread_queue_wake(struct thread_entry **list)
1433 unsigned result = THREAD_NONE;
1435 for (;;)
1437 unsigned int rc = wakeup_thread(list);
1439 if (rc == THREAD_NONE)
1440 break; /* No more threads */
1442 result |= rc;
1445 return result;
1448 /*---------------------------------------------------------------------------
1449 * Assign the thread slot a new ID. Version is 1-255.
1450 *---------------------------------------------------------------------------
1452 static void new_thread_id(unsigned int slot_num,
1453 struct thread_entry *thread)
1455 unsigned int version =
1456 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
1457 & THREAD_ID_VERSION_MASK;
1459 /* If wrapped to 0, make it 1 */
1460 if (version == 0)
1461 version = 1u << THREAD_ID_VERSION_SHIFT;
1463 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
1466 /*---------------------------------------------------------------------------
1467 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
1468 * will be locked on multicore.
1469 *---------------------------------------------------------------------------
1471 static struct thread_entry * find_empty_thread_slot(void)
1473 /* Any slot could be on an interrupt-accessible list */
1474 IF_COP( int oldlevel = disable_irq_save(); )
1475 struct thread_entry *thread = NULL;
1476 int n;
1478 for (n = 0; n < MAXTHREADS; n++)
1480 /* Obtain current slot state - lock it on multicore */
1481 struct thread_entry *t = &threads[n];
1482 LOCK_THREAD(t);
1484 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
1486 /* Slot is empty - leave it locked and caller will unlock */
1487 thread = t;
1488 break;
1491 /* Finished examining slot - no longer busy - unlock on multicore */
1492 UNLOCK_THREAD(t);
1495 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
1496 not accesible to them yet */
1497 return thread;
1500 /*---------------------------------------------------------------------------
1501 * Return the thread_entry pointer for a thread_id. Return the current
1502 * thread if the ID is (unsigned int)-1 (alias for current).
1503 *---------------------------------------------------------------------------
1505 struct thread_entry * thread_id_entry(unsigned int thread_id)
1507 return &threads[thread_id & THREAD_ID_SLOT_MASK];
1510 /*---------------------------------------------------------------------------
1511 * Return the thread id of the calling thread
1512 * --------------------------------------------------------------------------
1514 unsigned int thread_self(void)
1516 return cores[CURRENT_CORE].running->id;
1519 /*---------------------------------------------------------------------------
1520 * Return the thread entry of the calling thread.
1522 * INTERNAL: Intended for use by kernel and not for programs.
1523 *---------------------------------------------------------------------------
1525 struct thread_entry* thread_self_entry(void)
1527 return cores[CURRENT_CORE].running;
1530 /*---------------------------------------------------------------------------
1531 * Place the current core in idle mode - woken up on interrupt or wake
1532 * request from another core.
1533 *---------------------------------------------------------------------------
1535 void core_idle(void)
1537 IF_COP( const unsigned int core = CURRENT_CORE; )
1538 disable_irq();
1539 core_sleep(IF_COP(core));
1542 /*---------------------------------------------------------------------------
1543 * Create a thread. If using a dual core architecture, specify which core to
1544 * start the thread on.
1546 * Return ID if context area could be allocated, else NULL.
1547 *---------------------------------------------------------------------------
1549 unsigned int create_thread(void (*function)(void),
1550 void* stack, size_t stack_size,
1551 unsigned flags, const char *name
1552 IF_PRIO(, int priority)
1553 IF_COP(, unsigned int core))
1555 unsigned int i;
1556 unsigned int stack_words;
1557 uintptr_t stackptr, stackend;
1558 struct thread_entry *thread;
1559 unsigned state;
1560 int oldlevel;
1562 thread = find_empty_thread_slot();
1563 if (thread == NULL)
1565 return 0;
1568 oldlevel = disable_irq_save();
1570 /* Munge the stack to make it easy to spot stack overflows */
1571 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
1572 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
1573 stack_size = stackend - stackptr;
1574 stack_words = stack_size / sizeof (uintptr_t);
1576 for (i = 0; i < stack_words; i++)
1578 ((uintptr_t *)stackptr)[i] = DEADBEEF;
1581 /* Store interesting information */
1582 thread->name = name;
1583 thread->stack = (uintptr_t *)stackptr;
1584 thread->stack_size = stack_size;
1585 thread->queue = NULL;
1586 #ifdef HAVE_WAKEUP_EXT_CB
1587 thread->wakeup_ext_cb = NULL;
1588 #endif
1589 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1590 thread->cpu_boost = 0;
1591 #endif
1592 #ifdef HAVE_PRIORITY_SCHEDULING
1593 memset(&thread->pdist, 0, sizeof(thread->pdist));
1594 thread->blocker = NULL;
1595 thread->base_priority = priority;
1596 thread->priority = priority;
1597 thread->skip_count = priority;
1598 prio_add_entry(&thread->pdist, priority);
1599 #endif
1601 #ifdef HAVE_IO_PRIORITY
1602 /* Default to high (foreground) priority */
1603 thread->io_priority = IO_PRIORITY_IMMEDIATE;
1604 #endif
1606 #if NUM_CORES > 1
1607 thread->core = core;
1609 /* Writeback stack munging or anything else before starting */
1610 if (core != CURRENT_CORE)
1612 commit_dcache();
1614 #endif
1616 /* Thread is not on any timeout list but be a bit paranoid */
1617 thread->tmo.prev = NULL;
1619 state = (flags & CREATE_THREAD_FROZEN) ?
1620 STATE_FROZEN : STATE_RUNNING;
1622 thread->context.sp = (typeof (thread->context.sp))stackend;
1624 /* Load the thread's context structure with needed startup information */
1625 THREAD_STARTUP_INIT(core, thread, function);
1627 thread->state = state;
1628 i = thread->id; /* Snapshot while locked */
1630 if (state == STATE_RUNNING)
1631 core_schedule_wakeup(thread);
1633 UNLOCK_THREAD(thread);
1634 restore_irq(oldlevel);
1636 return i;
1639 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1640 /*---------------------------------------------------------------------------
1641 * Change the boost state of a thread boosting or unboosting the CPU
1642 * as required.
1643 *---------------------------------------------------------------------------
1645 static inline void boost_thread(struct thread_entry *thread, bool boost)
1647 if ((thread->cpu_boost != 0) != boost)
1649 thread->cpu_boost = boost;
1650 cpu_boost(boost);
1654 void trigger_cpu_boost(void)
1656 struct thread_entry *current = cores[CURRENT_CORE].running;
1657 boost_thread(current, true);
1660 void cancel_cpu_boost(void)
1662 struct thread_entry *current = cores[CURRENT_CORE].running;
1663 boost_thread(current, false);
1665 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
1667 /*---------------------------------------------------------------------------
1668 * Block the current thread until another thread terminates. A thread may
1669 * wait on itself to terminate which prevents it from running again and it
1670 * will need to be killed externally.
1671 * Parameter is the ID as returned from create_thread().
1672 *---------------------------------------------------------------------------
1674 void thread_wait(unsigned int thread_id)
1676 struct thread_entry *current = cores[CURRENT_CORE].running;
1677 struct thread_entry *thread = thread_id_entry(thread_id);
1679 /* Lock thread-as-waitable-object lock */
1680 corelock_lock(&thread->waiter_cl);
1682 /* Be sure it hasn't been killed yet */
1683 if (thread->id == thread_id && thread->state != STATE_KILLED)
1685 IF_COP( current->obj_cl = &thread->waiter_cl; )
1686 current->bqp = &thread->queue;
1688 disable_irq();
1689 block_thread(current);
1691 corelock_unlock(&thread->waiter_cl);
1693 switch_thread();
1694 return;
1697 corelock_unlock(&thread->waiter_cl);
1700 /*---------------------------------------------------------------------------
1701 * Exit the current thread. The Right Way to Do Things (TM).
1702 *---------------------------------------------------------------------------
1704 /* This is done to foil optimizations that may require the current stack,
1705 * such as optimizing subexpressions that put variables on the stack that
1706 * get used after switching stacks. */
1707 #if NUM_CORES > 1
1708 /* Called by ASM stub */
1709 static void thread_final_exit_do(struct thread_entry *current)
1710 #else
1711 /* No special procedure is required before calling */
1712 static inline void thread_final_exit(struct thread_entry *current)
1713 #endif
1715 /* At this point, this thread isn't using resources allocated for
1716 * execution except the slot itself. */
1718 /* Signal this thread */
1719 thread_queue_wake(&current->queue);
1720 corelock_unlock(&current->waiter_cl);
1721 switch_thread();
1722 /* This should never and must never be reached - if it is, the
1723 * state is corrupted */
1724 THREAD_PANICF("thread_exit->K:*R", current);
1725 while (1);
1728 void thread_exit(void)
1730 register struct thread_entry * current = cores[CURRENT_CORE].running;
1732 /* Cancel CPU boost if any */
1733 cancel_cpu_boost();
1735 disable_irq();
1737 corelock_lock(&current->waiter_cl);
1738 LOCK_THREAD(current);
1740 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
1741 if (current->name == THREAD_DESTRUCT)
1743 /* Thread being killed - become a waiter */
1744 unsigned int id = current->id;
1745 UNLOCK_THREAD(current);
1746 corelock_unlock(&current->waiter_cl);
1747 thread_wait(id);
1748 THREAD_PANICF("thread_exit->WK:*R", current);
1750 #endif
1752 #ifdef HAVE_PRIORITY_SCHEDULING
1753 check_for_obj_waiters("thread_exit", current);
1754 #endif
1756 if (current->tmo.prev != NULL)
1758 /* Cancel pending timeout list removal */
1759 remove_from_list_tmo(current);
1762 /* Switch tasks and never return */
1763 block_thread_on_l(current, STATE_KILLED);
1765 /* Slot must be unusable until thread is really gone */
1766 UNLOCK_THREAD_AT_TASK_SWITCH(current);
1768 /* Update ID for this slot */
1769 new_thread_id(current->id, current);
1770 current->name = NULL;
1772 /* Do final cleanup and remove the thread */
1773 thread_final_exit(current);
1776 #ifdef ALLOW_REMOVE_THREAD
1777 /*---------------------------------------------------------------------------
1778 * Remove a thread from the scheduler. Not The Right Way to Do Things in
1779 * normal programs.
1781 * Parameter is the ID as returned from create_thread().
1783 * Use with care on threads that are not under careful control as this may
1784 * leave various objects in an undefined state.
1785 *---------------------------------------------------------------------------
1787 void remove_thread(unsigned int thread_id)
1789 #ifdef HAVE_CORELOCK_OBJECT
1790 /* core is not constant here because of core switching */
1791 unsigned int core = CURRENT_CORE;
1792 unsigned int old_core = NUM_CORES;
1793 struct corelock *ocl = NULL;
1794 #else
1795 const unsigned int core = CURRENT_CORE;
1796 #endif
1797 struct thread_entry *current = cores[core].running;
1798 struct thread_entry *thread = thread_id_entry(thread_id);
1800 unsigned state;
1801 int oldlevel;
1803 if (thread == current)
1804 thread_exit(); /* Current thread - do normal exit */
1806 oldlevel = disable_irq_save();
1808 corelock_lock(&thread->waiter_cl);
1809 LOCK_THREAD(thread);
1811 state = thread->state;
1813 if (thread->id != thread_id || state == STATE_KILLED)
1814 goto thread_killed;
1816 #if NUM_CORES > 1
1817 if (thread->name == THREAD_DESTRUCT)
1819 /* Thread being killed - become a waiter */
1820 UNLOCK_THREAD(thread);
1821 corelock_unlock(&thread->waiter_cl);
1822 restore_irq(oldlevel);
1823 thread_wait(thread_id);
1824 return;
1827 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
1829 #ifdef HAVE_PRIORITY_SCHEDULING
1830 check_for_obj_waiters("remove_thread", thread);
1831 #endif
1833 if (thread->core != core)
1835 /* Switch cores and safely extract the thread there */
1836 /* Slot HAS to be unlocked or a deadlock could occur which means other
1837 * threads have to be guided into becoming thread waiters if they
1838 * attempt to remove it. */
1839 unsigned int new_core = thread->core;
1841 corelock_unlock(&thread->waiter_cl);
1843 UNLOCK_THREAD(thread);
1844 restore_irq(oldlevel);
1846 old_core = switch_core(new_core);
1848 oldlevel = disable_irq_save();
1850 corelock_lock(&thread->waiter_cl);
1851 LOCK_THREAD(thread);
1853 state = thread->state;
1854 core = new_core;
1855 /* Perform the extraction and switch ourselves back to the original
1856 processor */
1858 #endif /* NUM_CORES > 1 */
1860 if (thread->tmo.prev != NULL)
1862 /* Clean thread off the timeout list if a timeout check hasn't
1863 * run yet */
1864 remove_from_list_tmo(thread);
1867 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1868 /* Cancel CPU boost if any */
1869 boost_thread(thread, false);
1870 #endif
1872 IF_COP( retry_state: )
1874 switch (state)
1876 case STATE_RUNNING:
1877 RTR_LOCK(core);
1878 /* Remove thread from ready to run tasks */
1879 remove_from_list_l(&cores[core].running, thread);
1880 rtr_subtract_entry(core, thread->priority);
1881 RTR_UNLOCK(core);
1882 break;
1883 case STATE_BLOCKED:
1884 case STATE_BLOCKED_W_TMO:
1885 /* Remove thread from the queue it's blocked on - including its
1886 * own if waiting there */
1887 #if NUM_CORES > 1
1888 if (&thread->waiter_cl != thread->obj_cl)
1890 ocl = thread->obj_cl;
1892 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1894 UNLOCK_THREAD(thread);
1895 corelock_lock(ocl);
1896 LOCK_THREAD(thread);
1898 if (UNLIKELY(thread->state != state))
1900 /* Something woke the thread */
1901 state = thread->state;
1902 corelock_unlock(ocl);
1903 goto retry_state;
1907 #endif
1908 remove_from_list_l(thread->bqp, thread);
1910 #ifdef HAVE_WAKEUP_EXT_CB
1911 if (thread->wakeup_ext_cb != NULL)
1912 thread->wakeup_ext_cb(thread);
1913 #endif
1915 #ifdef HAVE_PRIORITY_SCHEDULING
1916 if (thread->blocker != NULL)
1918 /* Remove thread's priority influence from its chain */
1919 wakeup_priority_protocol_release(thread);
1921 #endif
1923 #if NUM_CORES > 1
1924 if (ocl != NULL)
1925 corelock_unlock(ocl);
1926 #endif
1927 break;
1928 /* Otherwise thread is frozen and hasn't run yet */
1931 new_thread_id(thread_id, thread);
1932 thread->state = STATE_KILLED;
1934 /* If thread was waiting on itself, it will have been removed above.
1935 * The wrong order would result in waking the thread first and deadlocking
1936 * since the slot is already locked. */
1937 thread_queue_wake(&thread->queue);
1939 thread->name = NULL;
1941 thread_killed: /* Thread was already killed */
1942 /* Removal complete - safe to unlock and reenable interrupts */
1943 corelock_unlock(&thread->waiter_cl);
1944 UNLOCK_THREAD(thread);
1945 restore_irq(oldlevel);
1947 #if NUM_CORES > 1
1948 if (old_core < NUM_CORES)
1950 /* Did a removal on another processor's thread - switch back to
1951 native core */
1952 switch_core(old_core);
1954 #endif
1956 #endif /* ALLOW_REMOVE_THREAD */
1958 #ifdef HAVE_PRIORITY_SCHEDULING
1959 /*---------------------------------------------------------------------------
1960 * Sets the thread's relative base priority for the core it runs on. Any
1961 * needed inheritance changes also may happen.
1962 *---------------------------------------------------------------------------
1964 int thread_set_priority(unsigned int thread_id, int priority)
1966 int old_base_priority = -1;
1967 struct thread_entry *thread = thread_id_entry(thread_id);
1969 /* A little safety measure */
1970 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
1971 return -1;
1973 /* Thread could be on any list and therefore on an interrupt accessible
1974 one - disable interrupts */
1975 int oldlevel = disable_irq_save();
1977 LOCK_THREAD(thread);
1979 /* Make sure it's not killed */
1980 if (thread->id == thread_id && thread->state != STATE_KILLED)
1982 int old_priority = thread->priority;
1984 old_base_priority = thread->base_priority;
1985 thread->base_priority = priority;
1987 prio_move_entry(&thread->pdist, old_base_priority, priority);
1988 priority = find_first_set_bit(thread->pdist.mask);
1990 if (old_priority == priority)
1992 /* No priority change - do nothing */
1994 else if (thread->state == STATE_RUNNING)
1996 /* This thread is running - change location on the run
1997 * queue. No transitive inheritance needed. */
1998 set_running_thread_priority(thread, priority);
2000 else
2002 thread->priority = priority;
2004 if (thread->blocker != NULL)
2006 /* Bubble new priority down the chain */
2007 struct blocker *bl = thread->blocker; /* Blocker struct */
2008 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2009 struct thread_entry * const tstart = thread; /* Initial thread */
2010 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2012 for (;;)
2014 struct thread_entry *next; /* Next thread to check */
2015 int bl_pr; /* Highest blocked thread */
2016 int queue_pr; /* New highest blocked thread */
2017 #if NUM_CORES > 1
2018 /* Owner can change but thread cannot be dislodged - thread
2019 * may not be the first in the queue which allows other
2020 * threads ahead in the list to be given ownership during the
2021 * operation. If thread is next then the waker will have to
2022 * wait for us and the owner of the object will remain fixed.
2023 * If we successfully grab the owner -- which at some point
2024 * is guaranteed -- then the queue remains fixed until we
2025 * pass by. */
2026 for (;;)
2028 LOCK_THREAD(bl_t);
2030 /* Double-check the owner - retry if it changed */
2031 if (LIKELY(bl->thread == bl_t))
2032 break;
2034 UNLOCK_THREAD(bl_t);
2035 bl_t = bl->thread;
2037 #endif
2038 bl_pr = bl->priority;
2040 if (highest > bl_pr)
2041 break; /* Object priority won't change */
2043 /* This will include the thread being set */
2044 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2046 if (queue_pr == bl_pr)
2047 break; /* Object priority not changing */
2049 /* Update thread boost for this object */
2050 bl->priority = queue_pr;
2051 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2052 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2054 if (bl_t->priority == bl_pr)
2055 break; /* Blocking thread priority not changing */
2057 if (bl_t->state == STATE_RUNNING)
2059 /* Thread not blocked - we're done */
2060 set_running_thread_priority(bl_t, bl_pr);
2061 break;
2064 bl_t->priority = bl_pr;
2065 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2067 if (bl == NULL)
2068 break; /* End of chain */
2070 next = bl->thread;
2072 if (UNLIKELY(next == tstart))
2073 break; /* Full-circle */
2075 UNLOCK_THREAD(thread);
2077 thread = bl_t;
2078 bl_t = next;
2079 } /* for (;;) */
2081 UNLOCK_THREAD(bl_t);
2086 UNLOCK_THREAD(thread);
2088 restore_irq(oldlevel);
2090 return old_base_priority;
2093 /*---------------------------------------------------------------------------
2094 * Returns the current base priority for a thread.
2095 *---------------------------------------------------------------------------
2097 int thread_get_priority(unsigned int thread_id)
2099 struct thread_entry *thread = thread_id_entry(thread_id);
2100 int base_priority = thread->base_priority;
2102 /* Simply check without locking slot. It may or may not be valid by the
2103 * time the function returns anyway. If all tests pass, it is the
2104 * correct value for when it was valid. */
2105 if (thread->id != thread_id || thread->state == STATE_KILLED)
2106 base_priority = -1;
2108 return base_priority;
2110 #endif /* HAVE_PRIORITY_SCHEDULING */
2112 #ifdef HAVE_IO_PRIORITY
2113 int thread_get_io_priority(unsigned int thread_id)
2115 struct thread_entry *thread = thread_id_entry(thread_id);
2116 return thread->io_priority;
2119 void thread_set_io_priority(unsigned int thread_id,int io_priority)
2121 struct thread_entry *thread = thread_id_entry(thread_id);
2122 thread->io_priority = io_priority;
2124 #endif
2126 /*---------------------------------------------------------------------------
2127 * Starts a frozen thread - similar semantics to wakeup_thread except that
2128 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2129 * virtue of the slot having a state of STATE_FROZEN.
2130 *---------------------------------------------------------------------------
2132 void thread_thaw(unsigned int thread_id)
2134 struct thread_entry *thread = thread_id_entry(thread_id);
2135 int oldlevel = disable_irq_save();
2137 LOCK_THREAD(thread);
2139 /* If thread is the current one, it cannot be frozen, therefore
2140 * there is no need to check that. */
2141 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2142 core_schedule_wakeup(thread);
2144 UNLOCK_THREAD(thread);
2145 restore_irq(oldlevel);
2148 #if NUM_CORES > 1
2149 /*---------------------------------------------------------------------------
2150 * Switch the processor that the currently executing thread runs on.
2151 *---------------------------------------------------------------------------
2153 unsigned int switch_core(unsigned int new_core)
2155 const unsigned int core = CURRENT_CORE;
2156 struct thread_entry *current = cores[core].running;
2158 if (core == new_core)
2160 /* No change - just return same core */
2161 return core;
2164 int oldlevel = disable_irq_save();
2165 LOCK_THREAD(current);
2167 if (current->name == THREAD_DESTRUCT)
2169 /* Thread being killed - deactivate and let process complete */
2170 unsigned int id = current->id;
2171 UNLOCK_THREAD(current);
2172 restore_irq(oldlevel);
2173 thread_wait(id);
2174 /* Should never be reached */
2175 THREAD_PANICF("switch_core->D:*R", current);
2178 /* Get us off the running list for the current core */
2179 RTR_LOCK(core);
2180 remove_from_list_l(&cores[core].running, current);
2181 rtr_subtract_entry(core, current->priority);
2182 RTR_UNLOCK(core);
2184 /* Stash return value (old core) in a safe place */
2185 current->retval = core;
2187 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2188 * the other core will likely attempt a removal from the wrong list! */
2189 if (current->tmo.prev != NULL)
2191 remove_from_list_tmo(current);
2194 /* Change the core number for this thread slot */
2195 current->core = new_core;
2197 /* Do not use core_schedule_wakeup here since this will result in
2198 * the thread starting to run on the other core before being finished on
2199 * this one. Delay the list unlock to keep the other core stuck
2200 * until this thread is ready. */
2201 RTR_LOCK(new_core);
2203 rtr_add_entry(new_core, current->priority);
2204 add_to_list_l(&cores[new_core].running, current);
2206 /* Make a callback into device-specific code, unlock the wakeup list so
2207 * that execution may resume on the new core, unlock our slot and finally
2208 * restore the interrupt level */
2209 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
2210 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
2211 cores[core].block_task = current;
2213 UNLOCK_THREAD(current);
2215 /* Alert other core to activity */
2216 core_wake(new_core);
2218 /* Do the stack switching, cache_maintenence and switch_thread call -
2219 requires native code */
2220 switch_thread_core(core, current);
2222 /* Finally return the old core to caller */
2223 return current->retval;
2225 #endif /* NUM_CORES > 1 */
2227 /*---------------------------------------------------------------------------
2228 * Initialize threading API. This assumes interrupts are not yet enabled. On
2229 * multicore setups, no core is allowed to proceed until create_thread calls
2230 * are safe to perform.
2231 *---------------------------------------------------------------------------
2233 void init_threads(void)
2235 const unsigned int core = CURRENT_CORE;
2236 struct thread_entry *thread;
2238 if (core == CPU)
2240 /* Initialize core locks and IDs in all slots */
2241 int n;
2242 for (n = 0; n < MAXTHREADS; n++)
2244 thread = &threads[n];
2245 corelock_init(&thread->waiter_cl);
2246 corelock_init(&thread->slot_cl);
2247 thread->id = THREAD_ID_INIT(n);
2251 /* CPU will initialize first and then sleep */
2252 thread = find_empty_thread_slot();
2254 if (thread == NULL)
2256 /* WTF? There really must be a slot available at this stage.
2257 * This can fail if, for example, .bss isn't zero'ed out by the loader
2258 * or threads is in the wrong section. */
2259 THREAD_PANICF("init_threads->no slot", NULL);
2262 /* Initialize initially non-zero members of core */
2263 cores[core].next_tmo_check = current_tick; /* Something not in the past */
2265 /* Initialize initially non-zero members of slot */
2266 UNLOCK_THREAD(thread); /* No sync worries yet */
2267 thread->name = main_thread_name;
2268 thread->state = STATE_RUNNING;
2269 IF_COP( thread->core = core; )
2270 #ifdef HAVE_PRIORITY_SCHEDULING
2271 corelock_init(&cores[core].rtr_cl);
2272 thread->base_priority = PRIORITY_USER_INTERFACE;
2273 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
2274 thread->priority = PRIORITY_USER_INTERFACE;
2275 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
2276 #endif
2278 add_to_list_l(&cores[core].running, thread);
2280 if (core == CPU)
2282 thread->stack = stackbegin;
2283 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
2284 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2285 /* Wait for other processors to finish their inits since create_thread
2286 * isn't safe to call until the kernel inits are done. The first
2287 * threads created in the system must of course be created by CPU.
2288 * Another possible approach is to initialize all cores and slots
2289 * for each core by CPU, let the remainder proceed in parallel and
2290 * signal CPU when all are finished. */
2291 core_thread_init(CPU);
2293 else
2295 /* Initial stack is the idle stack */
2296 thread->stack = idle_stacks[core];
2297 thread->stack_size = IDLE_STACK_SIZE;
2298 /* After last processor completes, it should signal all others to
2299 * proceed or may signal the next and call thread_exit(). The last one
2300 * to finish will signal CPU. */
2301 core_thread_init(core);
2302 /* Other cores do not have a main thread - go idle inside switch_thread
2303 * until a thread can run on the core. */
2304 thread_exit();
2305 #endif /* NUM_CORES */
2307 #ifdef INIT_MAIN_THREAD
2308 init_main_thread(&thread->context);
2309 #endif
2312 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
2313 #if NUM_CORES == 1
2314 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
2315 #else
2316 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
2317 #endif
2319 unsigned int stack_words = stack_size / sizeof (uintptr_t);
2320 unsigned int i;
2321 int usage = 0;
2323 for (i = 0; i < stack_words; i++)
2325 if (stackptr[i] != DEADBEEF)
2327 usage = ((stack_words - i) * 100) / stack_words;
2328 break;
2332 return usage;
2335 /*---------------------------------------------------------------------------
2336 * Returns the maximum percentage of stack a thread ever used while running.
2337 * NOTE: Some large buffer allocations that don't use enough the buffer to
2338 * overwrite stackptr[0] will not be seen.
2339 *---------------------------------------------------------------------------
2341 int thread_stack_usage(const struct thread_entry *thread)
2343 if (LIKELY(thread->stack_size > 0))
2344 return stack_usage(thread->stack, thread->stack_size);
2345 return 0;
2348 #if NUM_CORES > 1
2349 /*---------------------------------------------------------------------------
2350 * Returns the maximum percentage of the core's idle stack ever used during
2351 * runtime.
2352 *---------------------------------------------------------------------------
2354 int idle_stack_usage(unsigned int core)
2356 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
2358 #endif
2360 /*---------------------------------------------------------------------------
2361 * Fills in the buffer with the specified thread's name. If the name is NULL,
2362 * empty, or the thread is in destruct state a formatted ID is written
2363 * instead.
2364 *---------------------------------------------------------------------------
2366 void thread_get_name(char *buffer, int size,
2367 struct thread_entry *thread)
2369 if (size <= 0)
2370 return;
2372 *buffer = '\0';
2374 if (thread)
2376 /* Display thread name if one or ID if none */
2377 const char *name = thread->name;
2378 const char *fmt = "%s";
2379 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
2381 name = (const char *)(uintptr_t)thread->id;
2382 fmt = "%04lX";
2384 snprintf(buffer, size, fmt, name);