Enable program flow prediction in the system control coprocessor setup in the bootloader.
[kugel-rb.git] / firmware / thread.c
blob7ece27f4a6a60987d16666e5d14bf985e8f6fe52
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include "config.h"
20 #include <stdbool.h>
21 #include "thread.h"
22 #include "panic.h"
23 #include "sprintf.h"
24 #include "system.h"
25 #include "kernel.h"
26 #include "cpu.h"
27 #include "string.h"
28 #ifdef RB_PROFILE
29 #include <profile.h>
30 #endif
31 /****************************************************************************
32 * ATTENTION!! *
33 * See notes below on implementing processor-specific portions! *
34 ***************************************************************************/
36 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
37 #ifdef DEBUG
38 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
39 #else
40 #define THREAD_EXTRA_CHECKS 0
41 #endif
43 /**
44 * General locking order to guarantee progress. Order must be observed but
45 * all stages are not nescessarily obligatory. Going from 1) to 3) is
46 * perfectly legal.
48 * 1) IRQ
49 * This is first because of the likelyhood of having an interrupt occur that
50 * also accesses one of the objects farther down the list. Any non-blocking
51 * synchronization done may already have a lock on something during normal
52 * execution and if an interrupt handler running on the same processor as
53 * the one that has the resource locked were to attempt to access the
54 * resource, the interrupt handler would wait forever waiting for an unlock
55 * that will never happen. There is no danger if the interrupt occurs on
56 * a different processor because the one that has the lock will eventually
57 * unlock and the other processor's handler may proceed at that time. Not
58 * nescessary when the resource in question is definitely not available to
59 * interrupt handlers.
61 * 2) Kernel Object
62 * 1) May be needed beforehand if the kernel object allows dual-use such as
63 * event queues. The kernel object must have a scheme to protect itself from
64 * access by another processor and is responsible for serializing the calls
65 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
66 * other. Objects' queues are also protected here.
68 * 3) Thread Slot
69 * This locks access to the thread's slot such that its state cannot be
70 * altered by another processor when a state change is in progress such as
71 * when it is in the process of going on a blocked list. An attempt to wake
72 * a thread while it is still blocking will likely desync its state with
73 * the other resources used for that state.
75 * 4) Core Lists
76 * These lists are specific to a particular processor core and are accessible
77 * by all processor cores and interrupt handlers. The running (rtr) list is
78 * the prime example where a thread may be added by any means.
81 /*---------------------------------------------------------------------------
82 * Processor specific: core_sleep/core_wake/misc. notes
84 * ARM notes:
85 * FIQ is not dealt with by the scheduler code and is simply restored if it
86 * must by masked for some reason - because threading modifies a register
87 * that FIQ may also modify and there's no way to accomplish it atomically.
88 * s3c2440 is such a case.
90 * Audio interrupts are generally treated at a higher priority than others
91 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
92 * are not in general safe. Special cases may be constructed on a per-
93 * source basis and blocking operations are not available.
95 * core_sleep procedure to implement for any CPU to ensure an asychronous
96 * wakup never results in requiring a wait until the next tick (up to
97 * 10000uS!). May require assembly and careful instruction ordering.
99 * 1) On multicore, stay awake if directed to do so by another. If so, goto
100 * step 4.
101 * 2) If processor requires, atomically reenable interrupts and perform step
102 * 3.
103 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
104 * on Coldfire) goto step 5.
105 * 4) Enable interrupts.
106 * 5) Exit procedure.
108 * core_wake and multprocessor notes for sleep/wake coordination:
109 * If possible, to wake up another processor, the forcing of an interrupt on
110 * the woken core by the waker core is the easiest way to ensure a non-
111 * delayed wake and immediate execution of any woken threads. If that isn't
112 * available then some careful non-blocking synchonization is needed (as on
113 * PP targets at the moment).
114 *---------------------------------------------------------------------------
117 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
118 * (someday :). */
119 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
120 struct core_entry cores[NUM_CORES] IBSS_ATTR;
121 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
123 static const char main_thread_name[] = "main";
124 extern uintptr_t stackbegin[];
125 extern uintptr_t stackend[];
127 static inline void core_sleep(IF_COP_VOID(unsigned int core))
128 __attribute__((always_inline));
130 void check_tmo_threads(void)
131 __attribute__((noinline));
133 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
134 __attribute__((always_inline));
136 static void add_to_list_tmo(struct thread_entry *thread)
137 __attribute__((noinline));
139 static void core_schedule_wakeup(struct thread_entry *thread)
140 __attribute__((noinline));
142 #if NUM_CORES > 1
143 static inline void run_blocking_ops(
144 unsigned int core, struct thread_entry *thread)
145 __attribute__((always_inline));
146 #endif
148 static void thread_stkov(struct thread_entry *thread)
149 __attribute__((noinline));
151 static inline void store_context(void* addr)
152 __attribute__((always_inline));
154 static inline void load_context(const void* addr)
155 __attribute__((always_inline));
157 void switch_thread(void)
158 __attribute__((noinline));
160 /****************************************************************************
161 * Processor-specific section
164 #if defined(MAX_PHYS_SECTOR_SIZE) && MEM == 64
165 /* Support a special workaround object for large-sector disks */
166 #define IF_NO_SKIP_YIELD(...) __VA_ARGS__
167 #else
168 #define IF_NO_SKIP_YIELD(...)
169 #endif
171 #if defined(CPU_ARM)
172 /*---------------------------------------------------------------------------
173 * Start the thread running and terminate it if it returns
174 *---------------------------------------------------------------------------
176 static void __attribute__((naked,used)) start_thread(void)
178 /* r0 = context */
179 asm volatile (
180 "ldr sp, [r0, #32] \n" /* Load initial sp */
181 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
182 "mov r1, #0 \n" /* Mark thread as running */
183 "str r1, [r0, #40] \n"
184 #if NUM_CORES > 1
185 "ldr r0, =invalidate_icache \n" /* Invalidate this core's cache. */
186 "mov lr, pc \n" /* This could be the first entry into */
187 "bx r0 \n" /* plugin or codec code for this core. */
188 #endif
189 "mov lr, pc \n" /* Call thread function */
190 "bx r4 \n"
191 ); /* No clobber list - new thread doesn't care */
192 thread_exit();
193 //asm volatile (".ltorg"); /* Dump constant pool */
196 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
197 * slot, and thread function pointer in context.start. See load_context for
198 * what happens when thread is initially going to run. */
199 #define THREAD_STARTUP_INIT(core, thread, function) \
200 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
201 (thread)->context.r[1] = (uint32_t)start_thread, \
202 (thread)->context.start = (uint32_t)function; })
204 /*---------------------------------------------------------------------------
205 * Store non-volatile context.
206 *---------------------------------------------------------------------------
208 static inline void store_context(void* addr)
210 asm volatile(
211 "stmia %0, { r4-r11, sp, lr } \n"
212 : : "r" (addr)
216 /*---------------------------------------------------------------------------
217 * Load non-volatile context.
218 *---------------------------------------------------------------------------
220 static inline void load_context(const void* addr)
222 asm volatile(
223 "ldr r0, [%0, #40] \n" /* Load start pointer */
224 "cmp r0, #0 \n" /* Check for NULL */
225 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
226 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
227 : : "r" (addr) : "r0" /* only! */
231 #if defined (CPU_PP)
233 #if NUM_CORES > 1
234 extern uintptr_t cpu_idlestackbegin[];
235 extern uintptr_t cpu_idlestackend[];
236 extern uintptr_t cop_idlestackbegin[];
237 extern uintptr_t cop_idlestackend[];
238 static uintptr_t * const idle_stacks[NUM_CORES] =
240 [CPU] = cpu_idlestackbegin,
241 [COP] = cop_idlestackbegin
244 #if CONFIG_CPU == PP5002
245 /* Bytes to emulate the PP502x mailbox bits */
246 struct core_semaphores
248 volatile uint8_t intend_wake; /* 00h */
249 volatile uint8_t stay_awake; /* 01h */
250 volatile uint8_t intend_sleep; /* 02h */
251 volatile uint8_t unused; /* 03h */
254 static struct core_semaphores core_semaphores[NUM_CORES] IBSS_ATTR;
255 #endif /* CONFIG_CPU == PP5002 */
257 #endif /* NUM_CORES */
259 #if CONFIG_CORELOCK == SW_CORELOCK
260 /* Software core locks using Peterson's mutual exclusion algorithm */
262 /*---------------------------------------------------------------------------
263 * Initialize the corelock structure.
264 *---------------------------------------------------------------------------
266 void corelock_init(struct corelock *cl)
268 memset(cl, 0, sizeof (*cl));
271 #if 1 /* Assembly locks to minimize overhead */
272 /*---------------------------------------------------------------------------
273 * Wait for the corelock to become free and acquire it when it does.
274 *---------------------------------------------------------------------------
276 void corelock_lock(struct corelock *cl) __attribute__((naked));
277 void corelock_lock(struct corelock *cl)
279 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
280 asm volatile (
281 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
282 "ldrb r1, [r1] \n"
283 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
284 "eor r2, r1, #0xff \n" /* r2 = othercore */
285 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
286 "1: \n"
287 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
288 "cmp r3, #0 \n" /* yes? lock acquired */
289 "bxeq lr \n"
290 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
291 "cmp r3, r1 \n"
292 "bxeq lr \n" /* yes? lock acquired */
293 "b 1b \n" /* keep trying */
294 : : "i"(&PROCESSOR_ID)
296 (void)cl;
299 /*---------------------------------------------------------------------------
300 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
301 *---------------------------------------------------------------------------
303 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
304 int corelock_try_lock(struct corelock *cl)
306 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
307 asm volatile (
308 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
309 "ldrb r1, [r1] \n"
310 "mov r3, r0 \n"
311 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
312 "eor r2, r1, #0xff \n" /* r2 = othercore */
313 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
314 "ldrb r0, [r3, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
315 "eors r0, r0, r2 \n" /* yes? lock acquired */
316 "bxne lr \n"
317 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
318 "ands r0, r0, r1 \n"
319 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
320 "bx lr \n" /* return result */
321 : : "i"(&PROCESSOR_ID)
324 return 0;
325 (void)cl;
328 /*---------------------------------------------------------------------------
329 * Release ownership of the corelock
330 *---------------------------------------------------------------------------
332 void corelock_unlock(struct corelock *cl) __attribute__((naked));
333 void corelock_unlock(struct corelock *cl)
335 asm volatile (
336 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
337 "ldrb r1, [r1] \n"
338 "mov r2, #0 \n" /* cl->myl[core] = 0 */
339 "strb r2, [r0, r1, lsr #7] \n"
340 "bx lr \n"
341 : : "i"(&PROCESSOR_ID)
343 (void)cl;
345 #else /* C versions for reference */
346 /*---------------------------------------------------------------------------
347 * Wait for the corelock to become free and aquire it when it does.
348 *---------------------------------------------------------------------------
350 void corelock_lock(struct corelock *cl)
352 const unsigned int core = CURRENT_CORE;
353 const unsigned int othercore = 1 - core;
355 cl->myl[core] = core;
356 cl->turn = othercore;
358 for (;;)
360 if (cl->myl[othercore] == 0 || cl->turn == core)
361 break;
365 /*---------------------------------------------------------------------------
366 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
367 *---------------------------------------------------------------------------
369 int corelock_try_lock(struct corelock *cl)
371 const unsigned int core = CURRENT_CORE;
372 const unsigned int othercore = 1 - core;
374 cl->myl[core] = core;
375 cl->turn = othercore;
377 if (cl->myl[othercore] == 0 || cl->turn == core)
379 return 1;
382 cl->myl[core] = 0;
383 return 0;
386 /*---------------------------------------------------------------------------
387 * Release ownership of the corelock
388 *---------------------------------------------------------------------------
390 void corelock_unlock(struct corelock *cl)
392 cl->myl[CURRENT_CORE] = 0;
394 #endif /* ASM / C selection */
396 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
398 /*---------------------------------------------------------------------------
399 * Put core in a power-saving state if waking list wasn't repopulated and if
400 * no other core requested a wakeup for it to perform a task.
401 *---------------------------------------------------------------------------
403 #ifdef CPU_PP502x
404 #if NUM_CORES == 1
405 static inline void core_sleep(void)
407 sleep_core(CURRENT_CORE);
408 enable_irq();
410 #else
411 static inline void core_sleep(unsigned int core)
413 #if 1
414 asm volatile (
415 "mov r0, #4 \n" /* r0 = 0x4 << core */
416 "mov r0, r0, lsl %[c] \n"
417 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
418 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
419 "tst r1, r0, lsl #2 \n"
420 "moveq r1, #0x80000000 \n" /* Then sleep */
421 "streq r1, [%[ctl], %[c], lsl #2] \n"
422 "moveq r1, #0 \n" /* Clear control reg */
423 "streq r1, [%[ctl], %[c], lsl #2] \n"
424 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
425 "str r1, [%[mbx], #8] \n"
426 "1: \n" /* Wait for wake procedure to finish */
427 "ldr r1, [%[mbx], #0] \n"
428 "tst r1, r0, lsr #2 \n"
429 "bne 1b \n"
431 : [ctl]"r"(&CPU_CTL), [mbx]"r"(MBX_BASE), [c]"r"(core)
432 : "r0", "r1");
433 #else /* C version for reference */
434 /* Signal intent to sleep */
435 MBX_MSG_SET = 0x4 << core;
437 /* Something waking or other processor intends to wake us? */
438 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
440 sleep_core(core);
441 wake_core(core);
444 /* Signal wake - clear wake flag */
445 MBX_MSG_CLR = 0x14 << core;
447 /* Wait for other processor to finish wake procedure */
448 while (MBX_MSG_STAT & (0x1 << core));
449 #endif /* ASM/C selection */
450 enable_irq();
452 #endif /* NUM_CORES */
453 #elif CONFIG_CPU == PP5002
454 #if NUM_CORES == 1
455 static inline void core_sleep(void)
457 sleep_core(CURRENT_CORE);
458 enable_irq();
460 #else
461 /* PP5002 has no mailboxes - emulate using bytes */
462 static inline void core_sleep(unsigned int core)
464 #if 1
465 asm volatile (
466 "mov r0, #1 \n" /* Signal intent to sleep */
467 "strb r0, [%[sem], #2] \n"
468 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
469 "cmp r0, #0 \n"
470 "bne 2f \n"
471 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
472 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
473 * that the correct alternative is executed. Don't change the order
474 * of the next 4 instructions! */
475 "tst pc, #0x0c \n"
476 "mov r0, #0xca \n"
477 "strne r0, [%[ctl], %[c], lsl #2] \n"
478 "streq r0, [%[ctl], %[c], lsl #2] \n"
479 "nop \n" /* nop's needed because of pipeline */
480 "nop \n"
481 "nop \n"
482 "2: \n"
483 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
484 "strb r0, [%[sem], #1] \n"
485 "strb r0, [%[sem], #2] \n"
486 "1: \n" /* Wait for wake procedure to finish */
487 "ldrb r0, [%[sem], #0] \n"
488 "cmp r0, #0 \n"
489 "bne 1b \n"
491 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
492 [ctl]"r"(&CPU_CTL)
493 : "r0"
495 #else /* C version for reference */
496 /* Signal intent to sleep */
497 core_semaphores[core].intend_sleep = 1;
499 /* Something waking or other processor intends to wake us? */
500 if (core_semaphores[core].stay_awake == 0)
502 sleep_core(core);
505 /* Signal wake - clear wake flag */
506 core_semaphores[core].stay_awake = 0;
507 core_semaphores[core].intend_sleep = 0;
509 /* Wait for other processor to finish wake procedure */
510 while (core_semaphores[core].intend_wake != 0);
512 /* Enable IRQ */
513 #endif /* ASM/C selection */
514 enable_irq();
516 #endif /* NUM_CORES */
517 #endif /* PP CPU type */
519 /*---------------------------------------------------------------------------
520 * Wake another processor core that is sleeping or prevent it from doing so
521 * if it was already destined. FIQ, IRQ should be disabled before calling.
522 *---------------------------------------------------------------------------
524 #if NUM_CORES == 1
525 /* Shared single-core build debugging version */
526 void core_wake(void)
528 /* No wakey - core already wakey */
530 #elif defined (CPU_PP502x)
531 void core_wake(unsigned int othercore)
533 #if 1
534 /* avoid r0 since that contains othercore */
535 asm volatile (
536 "mrs r3, cpsr \n" /* Disable IRQ */
537 "orr r1, r3, #0x80 \n"
538 "msr cpsr_c, r1 \n"
539 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
540 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
541 "str r2, [%[mbx], #4] \n"
542 "1: \n" /* If it intends to sleep, let it first */
543 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
544 "eor r1, r1, #0xc \n"
545 "tst r1, r2, lsr #2 \n"
546 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
547 "tsteq r1, #0x80000000 \n"
548 "beq 1b \n" /* Wait for sleep or wake */
549 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
550 "movne r1, #0x0 \n"
551 "strne r1, [%[ctl], %[oc], lsl #2] \n"
552 "mov r1, r2, lsr #4 \n"
553 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
554 "msr cpsr_c, r3 \n" /* Restore IRQ */
556 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
557 [oc]"r"(othercore)
558 : "r1", "r2", "r3");
559 #else /* C version for reference */
560 /* Disable interrupts - avoid reentrancy from the tick */
561 int oldlevel = disable_irq_save();
563 /* Signal intent to wake other processor - set stay awake */
564 MBX_MSG_SET = 0x11 << othercore;
566 /* If it intends to sleep, wait until it does or aborts */
567 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
568 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
570 /* If sleeping, wake it up */
571 if (PROC_CTL(othercore) & PROC_SLEEP)
572 PROC_CTL(othercore) = 0;
574 /* Done with wake procedure */
575 MBX_MSG_CLR = 0x1 << othercore;
576 restore_irq(oldlevel);
577 #endif /* ASM/C selection */
579 #elif CONFIG_CPU == PP5002
580 /* PP5002 has no mailboxes - emulate using bytes */
581 void core_wake(unsigned int othercore)
583 #if 1
584 /* avoid r0 since that contains othercore */
585 asm volatile (
586 "mrs r3, cpsr \n" /* Disable IRQ */
587 "orr r1, r3, #0x80 \n"
588 "msr cpsr_c, r1 \n"
589 "mov r1, #1 \n" /* Signal intent to wake other core */
590 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
591 "strh r1, [%[sem], #0] \n"
592 "mov r2, #0x8000 \n"
593 "1: \n" /* If it intends to sleep, let it first */
594 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
595 "cmp r1, #1 \n"
596 "ldr r1, [%[st]] \n" /* && not sleeping ? */
597 "tsteq r1, r2, lsr %[oc] \n"
598 "beq 1b \n" /* Wait for sleep or wake */
599 "tst r1, r2, lsr %[oc] \n"
600 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
601 "movne r1, #0xce \n"
602 "strne r1, [r2, %[oc], lsl #2] \n"
603 "mov r1, #0 \n" /* Done with wake procedure */
604 "strb r1, [%[sem], #0] \n"
605 "msr cpsr_c, r3 \n" /* Restore IRQ */
607 : [sem]"r"(&core_semaphores[othercore]),
608 [st]"r"(&PROC_STAT),
609 [oc]"r"(othercore)
610 : "r1", "r2", "r3"
612 #else /* C version for reference */
613 /* Disable interrupts - avoid reentrancy from the tick */
614 int oldlevel = disable_irq_save();
616 /* Signal intent to wake other processor - set stay awake */
617 core_semaphores[othercore].intend_wake = 1;
618 core_semaphores[othercore].stay_awake = 1;
620 /* If it intends to sleep, wait until it does or aborts */
621 while (core_semaphores[othercore].intend_sleep != 0 &&
622 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
624 /* If sleeping, wake it up */
625 if (PROC_STAT & PROC_SLEEPING(othercore))
626 wake_core(othercore);
628 /* Done with wake procedure */
629 core_semaphores[othercore].intend_wake = 0;
630 restore_irq(oldlevel);
631 #endif /* ASM/C selection */
633 #endif /* CPU type */
635 #if NUM_CORES > 1
636 /*---------------------------------------------------------------------------
637 * Switches to a stack that always resides in the Rockbox core.
639 * Needed when a thread suicides on a core other than the main CPU since the
640 * stack used when idling is the stack of the last thread to run. This stack
641 * may not reside in the core firmware in which case the core will continue
642 * to use a stack from an unloaded module until another thread runs on it.
643 *---------------------------------------------------------------------------
645 static inline void switch_to_idle_stack(const unsigned int core)
647 asm volatile (
648 "str sp, [%0] \n" /* save original stack pointer on idle stack */
649 "mov sp, %0 \n" /* switch stacks */
650 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
651 (void)core;
654 /*---------------------------------------------------------------------------
655 * Perform core switch steps that need to take place inside switch_thread.
657 * These steps must take place while before changing the processor and after
658 * having entered switch_thread since switch_thread may not do a normal return
659 * because the stack being used for anything the compiler saved will not belong
660 * to the thread's destination core and it may have been recycled for other
661 * purposes by the time a normal context load has taken place. switch_thread
662 * will also clobber anything stashed in the thread's context or stored in the
663 * nonvolatile registers if it is saved there before the call since the
664 * compiler's order of operations cannot be known for certain.
666 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
668 /* Flush our data to ram */
669 flush_icache();
670 /* Stash thread in r4 slot */
671 thread->context.r[0] = (uint32_t)thread;
672 /* Stash restart address in r5 slot */
673 thread->context.r[1] = thread->context.start;
674 /* Save sp in context.sp while still running on old core */
675 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
678 /*---------------------------------------------------------------------------
679 * Machine-specific helper function for switching the processor a thread is
680 * running on. Basically, the thread suicides on the departing core and is
681 * reborn on the destination. Were it not for gcc's ill-behavior regarding
682 * naked functions written in C where it actually clobbers non-volatile
683 * registers before the intended prologue code, this would all be much
684 * simpler. Generic setup is done in switch_core itself.
687 /*---------------------------------------------------------------------------
688 * This actually performs the core switch.
690 static void __attribute__((naked))
691 switch_thread_core(unsigned int core, struct thread_entry *thread)
693 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
694 * Stack access also isn't permitted until restoring the original stack and
695 * context. */
696 asm volatile (
697 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
698 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
699 "ldr r2, [r2, r0, lsl #2] \n"
700 "add r2, r2, %0*4 \n"
701 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
702 "mov sp, r2 \n" /* switch stacks */
703 "adr r2, 1f \n" /* r2 = new core restart address */
704 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
705 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
706 "1: \n"
707 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
708 "mov r1, #0 \n" /* Clear start address */
709 "str r1, [r0, #40] \n"
710 "ldr r0, =invalidate_icache \n" /* Invalidate new core's cache */
711 "mov lr, pc \n"
712 "bx r0 \n"
713 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
714 ".ltorg \n" /* Dump constant pool */
715 : : "i"(IDLE_STACK_WORDS)
717 (void)core; (void)thread;
720 /*---------------------------------------------------------------------------
721 * Do any device-specific inits for the threads and synchronize the kernel
722 * initializations.
723 *---------------------------------------------------------------------------
725 static void core_thread_init(unsigned int core)
727 if (core == CPU)
729 /* Wake up coprocessor and let it initialize kernel and threads */
730 #ifdef CPU_PP502x
731 MBX_MSG_CLR = 0x3f;
732 #endif
733 wake_core(COP);
734 /* Sleep until COP has finished */
735 sleep_core(CPU);
737 else
739 /* Wake the CPU and return */
740 wake_core(CPU);
743 #endif /* NUM_CORES */
745 #elif CONFIG_CPU == S3C2440
747 /*---------------------------------------------------------------------------
748 * Put core in a power-saving state if waking list wasn't repopulated.
749 *---------------------------------------------------------------------------
751 static inline void core_sleep(void)
753 /* FIQ also changes the CLKCON register so FIQ must be disabled
754 when changing it here */
755 asm volatile (
756 "mrs r0, cpsr \n"
757 "orr r2, r0, #0x40 \n" /* Disable FIQ */
758 "bic r0, r0, #0x80 \n" /* Prepare IRQ enable */
759 "msr cpsr_c, r2 \n"
760 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
761 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
762 "orr r2, r2, #4 \n"
763 "str r2, [r1, #0xc] \n"
764 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
765 "mov r2, #0 \n" /* wait for IDLE */
766 "1: \n"
767 "add r2, r2, #1 \n"
768 "cmp r2, #10 \n"
769 "bne 1b \n"
770 "orr r2, r0, #0xc0 \n" /* Disable IRQ, FIQ */
771 "msr cpsr_c, r2 \n"
772 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
773 "bic r2, r2, #4 \n"
774 "str r2, [r1, #0xc] \n"
775 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
776 : : : "r0", "r1", "r2");
778 #elif defined(CPU_TCC77X)
779 static inline void core_sleep(void)
781 #warning TODO: Implement core_sleep
782 enable_irq();
784 #elif defined(CPU_TCC780X)
785 static inline void core_sleep(void)
787 /* Single core only for now. Use the generic ARMv5 wait for IRQ */
788 asm volatile (
789 "mov r0, #0 \n"
790 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
791 : : : "r0"
793 enable_irq();
795 #elif CONFIG_CPU == IMX31L
796 static inline void core_sleep(void)
798 asm volatile (
799 "mov r0, #0 \n"
800 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
801 : : : "r0"
803 enable_irq();
805 #else
806 static inline void core_sleep(void)
808 #warning core_sleep not implemented, battery life will be decreased
809 enable_irq();
811 #endif /* CONFIG_CPU == */
813 #elif defined(CPU_COLDFIRE)
814 /*---------------------------------------------------------------------------
815 * Start the thread running and terminate it if it returns
816 *---------------------------------------------------------------------------
818 void start_thread(void); /* Provide C access to ASM label */
819 static void __attribute__((used)) __start_thread(void)
821 /* a0=macsr, a1=context */
822 asm volatile (
823 "start_thread: \n" /* Start here - no naked attribute */
824 "move.l %a0, %macsr \n" /* Set initial mac status reg */
825 "lea.l 48(%a1), %a1 \n"
826 "move.l (%a1)+, %sp \n" /* Set initial stack */
827 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
828 "clr.l (%a1) \n" /* Mark thread running */
829 "jsr (%a2) \n" /* Call thread function */
831 thread_exit();
834 /* Set EMAC unit to fractional mode with saturation for each new thread,
835 * since that's what'll be the most useful for most things which the dsp
836 * will do. Codecs should still initialize their preferred modes
837 * explicitly. Context pointer is placed in d2 slot and start_thread
838 * pointer in d3 slot. thread function pointer is placed in context.start.
839 * See load_context for what happens when thread is initially going to
840 * run.
842 #define THREAD_STARTUP_INIT(core, thread, function) \
843 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
844 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
845 (thread)->context.d[1] = (uint32_t)start_thread, \
846 (thread)->context.start = (uint32_t)(function); })
848 /*---------------------------------------------------------------------------
849 * Store non-volatile context.
850 *---------------------------------------------------------------------------
852 static inline void store_context(void* addr)
854 asm volatile (
855 "move.l %%macsr,%%d0 \n"
856 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
857 : : "a" (addr) : "d0" /* only! */
861 /*---------------------------------------------------------------------------
862 * Load non-volatile context.
863 *---------------------------------------------------------------------------
865 static inline void load_context(const void* addr)
867 asm volatile (
868 "move.l 52(%0), %%d0 \n" /* Get start address */
869 "beq.b 1f \n" /* NULL -> already running */
870 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
871 "jmp (%%a2) \n" /* Start the thread */
872 "1: \n"
873 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
874 "move.l %%d0, %%macsr \n"
875 : : "a" (addr) : "d0" /* only! */
879 /*---------------------------------------------------------------------------
880 * Put core in a power-saving state if waking list wasn't repopulated.
881 *---------------------------------------------------------------------------
883 static inline void core_sleep(void)
885 /* Supervisor mode, interrupts enabled upon wakeup */
886 asm volatile ("stop #0x2000");
889 #elif CONFIG_CPU == SH7034
890 /*---------------------------------------------------------------------------
891 * Start the thread running and terminate it if it returns
892 *---------------------------------------------------------------------------
894 void start_thread(void); /* Provide C access to ASM label */
895 static void __attribute__((used)) __start_thread(void)
897 /* r8 = context */
898 asm volatile (
899 "_start_thread: \n" /* Start here - no naked attribute */
900 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
901 "mov.l @(28, r8), r15 \n" /* Set initial sp */
902 "mov #0, r1 \n" /* Start the thread */
903 "jsr @r0 \n"
904 "mov.l r1, @(36, r8) \n" /* Clear start address */
906 thread_exit();
909 /* Place context pointer in r8 slot, function pointer in r9 slot, and
910 * start_thread pointer in context_start */
911 #define THREAD_STARTUP_INIT(core, thread, function) \
912 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
913 (thread)->context.r[1] = (uint32_t)(function), \
914 (thread)->context.start = (uint32_t)start_thread; })
916 /*---------------------------------------------------------------------------
917 * Store non-volatile context.
918 *---------------------------------------------------------------------------
920 static inline void store_context(void* addr)
922 asm volatile (
923 "add #36, %0 \n" /* Start at last reg. By the time routine */
924 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
925 "mov.l r15,@-%0 \n"
926 "mov.l r14,@-%0 \n"
927 "mov.l r13,@-%0 \n"
928 "mov.l r12,@-%0 \n"
929 "mov.l r11,@-%0 \n"
930 "mov.l r10,@-%0 \n"
931 "mov.l r9, @-%0 \n"
932 "mov.l r8, @-%0 \n"
933 : : "r" (addr)
937 /*---------------------------------------------------------------------------
938 * Load non-volatile context.
939 *---------------------------------------------------------------------------
941 static inline void load_context(const void* addr)
943 asm volatile (
944 "mov.l @(36, %0), r0 \n" /* Get start address */
945 "tst r0, r0 \n"
946 "bt .running \n" /* NULL -> already running */
947 "jmp @r0 \n" /* r8 = context */
948 ".running: \n"
949 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
950 "mov.l @%0+, r9 \n"
951 "mov.l @%0+, r10 \n"
952 "mov.l @%0+, r11 \n"
953 "mov.l @%0+, r12 \n"
954 "mov.l @%0+, r13 \n"
955 "mov.l @%0+, r14 \n"
956 "mov.l @%0+, r15 \n"
957 "lds.l @%0+, pr \n"
958 : : "r" (addr) : "r0" /* only! */
962 /*---------------------------------------------------------------------------
963 * Put core in a power-saving state.
964 *---------------------------------------------------------------------------
966 static inline void core_sleep(void)
968 asm volatile (
969 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
970 "mov #0, r1 \n" /* Enable interrupts */
971 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
972 "sleep \n" /* Execute standby */
973 : : "z"(&SBYCR-GBR) : "r1");
976 #endif /* CONFIG_CPU == */
979 * End Processor-specific section
980 ***************************************************************************/
982 #if THREAD_EXTRA_CHECKS
983 static void thread_panicf(const char *msg, struct thread_entry *thread)
985 IF_COP( const unsigned int core = thread->core; )
986 static char name[32];
987 thread_get_name(name, 32, thread);
988 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
990 static void thread_stkov(struct thread_entry *thread)
992 thread_panicf("Stkov", thread);
994 #define THREAD_PANICF(msg, thread) \
995 thread_panicf(msg, thread)
996 #define THREAD_ASSERT(exp, msg, thread) \
997 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
998 #else
999 static void thread_stkov(struct thread_entry *thread)
1001 IF_COP( const unsigned int core = thread->core; )
1002 static char name[32];
1003 thread_get_name(name, 32, thread);
1004 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1006 #define THREAD_PANICF(msg, thread)
1007 #define THREAD_ASSERT(exp, msg, thread)
1008 #endif /* THREAD_EXTRA_CHECKS */
1010 /* Thread locking */
1011 #if NUM_CORES > 1
1012 #define LOCK_THREAD(thread) \
1013 ({ corelock_lock(&(thread)->slot_cl); })
1014 #define TRY_LOCK_THREAD(thread) \
1015 ({ corelock_try_lock(&thread->slot_cl); })
1016 #define UNLOCK_THREAD(thread) \
1017 ({ corelock_unlock(&(thread)->slot_cl); })
1018 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1019 ({ unsigned int _core = (thread)->core; \
1020 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1021 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1022 #else
1023 #define LOCK_THREAD(thread) \
1024 ({ })
1025 #define TRY_LOCK_THREAD(thread) \
1026 ({ })
1027 #define UNLOCK_THREAD(thread) \
1028 ({ })
1029 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1030 ({ })
1031 #endif
1033 /* RTR list */
1034 #define RTR_LOCK(core) \
1035 ({ corelock_lock(&cores[core].rtr_cl); })
1036 #define RTR_UNLOCK(core) \
1037 ({ corelock_unlock(&cores[core].rtr_cl); })
1039 #ifdef HAVE_PRIORITY_SCHEDULING
1040 #define rtr_add_entry(core, priority) \
1041 prio_add_entry(&cores[core].rtr, (priority))
1043 #define rtr_subtract_entry(core, priority) \
1044 prio_subtract_entry(&cores[core].rtr, (priority))
1046 #define rtr_move_entry(core, from, to) \
1047 prio_move_entry(&cores[core].rtr, (from), (to))
1048 #else
1049 #define rtr_add_entry(core, priority)
1050 #define rtr_add_entry_inl(core, priority)
1051 #define rtr_subtract_entry(core, priority)
1052 #define rtr_subtract_entry_inl(core, priotity)
1053 #define rtr_move_entry(core, from, to)
1054 #define rtr_move_entry_inl(core, from, to)
1055 #endif
1057 /*---------------------------------------------------------------------------
1058 * Thread list structure - circular:
1059 * +------------------------------+
1060 * | |
1061 * +--+---+<-+---+<-+---+<-+---+<-+
1062 * Head->| T | | T | | T | | T |
1063 * +->+---+->+---+->+---+->+---+--+
1064 * | |
1065 * +------------------------------+
1066 *---------------------------------------------------------------------------
1069 /*---------------------------------------------------------------------------
1070 * Adds a thread to a list of threads using "insert last". Uses the "l"
1071 * links.
1072 *---------------------------------------------------------------------------
1074 static void add_to_list_l(struct thread_entry **list,
1075 struct thread_entry *thread)
1077 struct thread_entry *l = *list;
1079 if (l == NULL)
1081 /* Insert into unoccupied list */
1082 thread->l.prev = thread;
1083 thread->l.next = thread;
1084 *list = thread;
1085 return;
1088 /* Insert last */
1089 thread->l.prev = l->l.prev;
1090 thread->l.next = l;
1091 l->l.prev->l.next = thread;
1092 l->l.prev = thread;
1095 /*---------------------------------------------------------------------------
1096 * Removes a thread from a list of threads. Uses the "l" links.
1097 *---------------------------------------------------------------------------
1099 static void remove_from_list_l(struct thread_entry **list,
1100 struct thread_entry *thread)
1102 struct thread_entry *prev, *next;
1104 next = thread->l.next;
1106 if (thread == next)
1108 /* The only item */
1109 *list = NULL;
1110 return;
1113 if (thread == *list)
1115 /* List becomes next item */
1116 *list = next;
1119 prev = thread->l.prev;
1121 /* Fix links to jump over the removed entry. */
1122 next->l.prev = prev;
1123 prev->l.next = next;
1126 /*---------------------------------------------------------------------------
1127 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1128 * NULL-terminated forward (to ease the far more common forward traversal):
1129 * +------------------------------+
1130 * | |
1131 * +--+---+<-+---+<-+---+<-+---+<-+
1132 * Head->| T | | T | | T | | T |
1133 * +---+->+---+->+---+->+---+-X
1134 *---------------------------------------------------------------------------
1137 /*---------------------------------------------------------------------------
1138 * Add a thread from the core's timout list by linking the pointers in its
1139 * tmo structure.
1140 *---------------------------------------------------------------------------
1142 static void add_to_list_tmo(struct thread_entry *thread)
1144 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1145 THREAD_ASSERT(thread->tmo.prev == NULL,
1146 "add_to_list_tmo->already listed", thread);
1148 thread->tmo.next = NULL;
1150 if (tmo == NULL)
1152 /* Insert into unoccupied list */
1153 thread->tmo.prev = thread;
1154 cores[IF_COP_CORE(thread->core)].timeout = thread;
1155 return;
1158 /* Insert Last */
1159 thread->tmo.prev = tmo->tmo.prev;
1160 tmo->tmo.prev->tmo.next = thread;
1161 tmo->tmo.prev = thread;
1164 /*---------------------------------------------------------------------------
1165 * Remove a thread from the core's timout list by unlinking the pointers in
1166 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1167 * is cancelled.
1168 *---------------------------------------------------------------------------
1170 static void remove_from_list_tmo(struct thread_entry *thread)
1172 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1173 struct thread_entry *prev = thread->tmo.prev;
1174 struct thread_entry *next = thread->tmo.next;
1176 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1178 if (next != NULL)
1179 next->tmo.prev = prev;
1181 if (thread == *list)
1183 /* List becomes next item and empty if next == NULL */
1184 *list = next;
1185 /* Mark as unlisted */
1186 thread->tmo.prev = NULL;
1188 else
1190 if (next == NULL)
1191 (*list)->tmo.prev = prev;
1192 prev->tmo.next = next;
1193 /* Mark as unlisted */
1194 thread->tmo.prev = NULL;
1199 #ifdef HAVE_PRIORITY_SCHEDULING
1200 /*---------------------------------------------------------------------------
1201 * Priority distribution structure (one category for each possible priority):
1203 * +----+----+----+ ... +-----+
1204 * hist: | F0 | F1 | F2 | | F31 |
1205 * +----+----+----+ ... +-----+
1206 * mask: | b0 | b1 | b2 | | b31 |
1207 * +----+----+----+ ... +-----+
1209 * F = count of threads at priority category n (frequency)
1210 * b = bitmask of non-zero priority categories (occupancy)
1212 * / if H[n] != 0 : 1
1213 * b[n] = |
1214 * \ else : 0
1216 *---------------------------------------------------------------------------
1217 * Basic priority inheritance priotocol (PIP):
1219 * Mn = mutex n, Tn = thread n
1221 * A lower priority thread inherits the priority of the highest priority
1222 * thread blocked waiting for it to complete an action (such as release a
1223 * mutex or respond to a message via queue_send):
1225 * 1) T2->M1->T1
1227 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1228 * priority than T1 then T1 inherits the priority of T2.
1230 * 2) T3
1231 * \/
1232 * T2->M1->T1
1234 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1235 * T1 inherits the higher of T2 and T3.
1237 * 3) T3->M2->T2->M1->T1
1239 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1240 * then T1 inherits the priority of T3 through T2.
1242 * Blocking chains can grow arbitrarily complex (though it's best that they
1243 * not form at all very often :) and build-up from these units.
1244 *---------------------------------------------------------------------------
1247 /*---------------------------------------------------------------------------
1248 * Increment frequency at category "priority"
1249 *---------------------------------------------------------------------------
1251 static inline unsigned int prio_add_entry(
1252 struct priority_distribution *pd, int priority)
1254 unsigned int count;
1255 /* Enough size/instruction count difference for ARM makes it worth it to
1256 * use different code (192 bytes for ARM). Only thing better is ASM. */
1257 #ifdef CPU_ARM
1258 count = pd->hist[priority];
1259 if (++count == 1)
1260 pd->mask |= 1 << priority;
1261 pd->hist[priority] = count;
1262 #else /* This one's better for Coldfire */
1263 if ((count = ++pd->hist[priority]) == 1)
1264 pd->mask |= 1 << priority;
1265 #endif
1267 return count;
1270 /*---------------------------------------------------------------------------
1271 * Decrement frequency at category "priority"
1272 *---------------------------------------------------------------------------
1274 static inline unsigned int prio_subtract_entry(
1275 struct priority_distribution *pd, int priority)
1277 unsigned int count;
1279 #ifdef CPU_ARM
1280 count = pd->hist[priority];
1281 if (--count == 0)
1282 pd->mask &= ~(1 << priority);
1283 pd->hist[priority] = count;
1284 #else
1285 if ((count = --pd->hist[priority]) == 0)
1286 pd->mask &= ~(1 << priority);
1287 #endif
1289 return count;
1292 /*---------------------------------------------------------------------------
1293 * Remove from one category and add to another
1294 *---------------------------------------------------------------------------
1296 static inline void prio_move_entry(
1297 struct priority_distribution *pd, int from, int to)
1299 uint32_t mask = pd->mask;
1301 #ifdef CPU_ARM
1302 unsigned int count;
1304 count = pd->hist[from];
1305 if (--count == 0)
1306 mask &= ~(1 << from);
1307 pd->hist[from] = count;
1309 count = pd->hist[to];
1310 if (++count == 1)
1311 mask |= 1 << to;
1312 pd->hist[to] = count;
1313 #else
1314 if (--pd->hist[from] == 0)
1315 mask &= ~(1 << from);
1317 if (++pd->hist[to] == 1)
1318 mask |= 1 << to;
1319 #endif
1321 pd->mask = mask;
1324 /*---------------------------------------------------------------------------
1325 * Change the priority and rtr entry for a running thread
1326 *---------------------------------------------------------------------------
1328 static inline void set_running_thread_priority(
1329 struct thread_entry *thread, int priority)
1331 const unsigned int core = IF_COP_CORE(thread->core);
1332 RTR_LOCK(core);
1333 rtr_move_entry(core, thread->priority, priority);
1334 thread->priority = priority;
1335 RTR_UNLOCK(core);
1338 /*---------------------------------------------------------------------------
1339 * Finds the highest priority thread in a list of threads. If the list is
1340 * empty, the PRIORITY_IDLE is returned.
1342 * It is possible to use the struct priority_distribution within an object
1343 * instead of scanning the remaining threads in the list but as a compromise,
1344 * the resulting per-object memory overhead is saved at a slight speed
1345 * penalty under high contention.
1346 *---------------------------------------------------------------------------
1348 static int find_highest_priority_in_list_l(
1349 struct thread_entry * const thread)
1351 if (thread != NULL)
1353 /* Go though list until the ending up at the initial thread */
1354 int highest_priority = thread->priority;
1355 struct thread_entry *curr = thread;
1359 int priority = curr->priority;
1361 if (priority < highest_priority)
1362 highest_priority = priority;
1364 curr = curr->l.next;
1366 while (curr != thread);
1368 return highest_priority;
1371 return PRIORITY_IDLE;
1374 /*---------------------------------------------------------------------------
1375 * Register priority with blocking system and bubble it down the chain if
1376 * any until we reach the end or something is already equal or higher.
1378 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1379 * targets but that same action also guarantees a circular block anyway and
1380 * those are prevented, right? :-)
1381 *---------------------------------------------------------------------------
1383 static struct thread_entry *
1384 blocker_inherit_priority(struct thread_entry *current)
1386 const int priority = current->priority;
1387 struct blocker *bl = current->blocker;
1388 struct thread_entry * const tstart = current;
1389 struct thread_entry *bl_t = bl->thread;
1391 /* Blocker cannot change since the object protection is held */
1392 LOCK_THREAD(bl_t);
1394 for (;;)
1396 struct thread_entry *next;
1397 int bl_pr = bl->priority;
1399 if (priority >= bl_pr)
1400 break; /* Object priority already high enough */
1402 bl->priority = priority;
1404 /* Add this one */
1405 prio_add_entry(&bl_t->pdist, priority);
1407 if (bl_pr < PRIORITY_IDLE)
1409 /* Not first waiter - subtract old one */
1410 prio_subtract_entry(&bl_t->pdist, bl_pr);
1413 if (priority >= bl_t->priority)
1414 break; /* Thread priority high enough */
1416 if (bl_t->state == STATE_RUNNING)
1418 /* Blocking thread is a running thread therefore there are no
1419 * further blockers. Change the "run queue" on which it
1420 * resides. */
1421 set_running_thread_priority(bl_t, priority);
1422 break;
1425 bl_t->priority = priority;
1427 /* If blocking thread has a blocker, apply transitive inheritance */
1428 bl = bl_t->blocker;
1430 if (bl == NULL)
1431 break; /* End of chain or object doesn't support inheritance */
1433 next = bl->thread;
1435 if (next == tstart)
1436 break; /* Full-circle - deadlock! */
1438 UNLOCK_THREAD(current);
1440 #if NUM_CORES > 1
1441 for (;;)
1443 LOCK_THREAD(next);
1445 /* Blocker could change - retest condition */
1446 if (bl->thread == next)
1447 break;
1449 UNLOCK_THREAD(next);
1450 next = bl->thread;
1452 #endif
1453 current = bl_t;
1454 bl_t = next;
1457 UNLOCK_THREAD(bl_t);
1459 return current;
1462 /*---------------------------------------------------------------------------
1463 * Readjust priorities when waking a thread blocked waiting for another
1464 * in essence "releasing" the thread's effect on the object owner. Can be
1465 * performed from any context.
1466 *---------------------------------------------------------------------------
1468 struct thread_entry *
1469 wakeup_priority_protocol_release(struct thread_entry *thread)
1471 const int priority = thread->priority;
1472 struct blocker *bl = thread->blocker;
1473 struct thread_entry * const tstart = thread;
1474 struct thread_entry *bl_t = bl->thread;
1476 /* Blocker cannot change since object will be locked */
1477 LOCK_THREAD(bl_t);
1479 thread->blocker = NULL; /* Thread not blocked */
1481 for (;;)
1483 struct thread_entry *next;
1484 int bl_pr = bl->priority;
1486 if (priority > bl_pr)
1487 break; /* Object priority higher */
1489 next = *thread->bqp;
1491 if (next == NULL)
1493 /* No more threads in queue */
1494 prio_subtract_entry(&bl_t->pdist, bl_pr);
1495 bl->priority = PRIORITY_IDLE;
1497 else
1499 /* Check list for highest remaining priority */
1500 int queue_pr = find_highest_priority_in_list_l(next);
1502 if (queue_pr == bl_pr)
1503 break; /* Object priority not changing */
1505 /* Change queue priority */
1506 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1507 bl->priority = queue_pr;
1510 if (bl_pr > bl_t->priority)
1511 break; /* thread priority is higher */
1513 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1515 if (bl_pr == bl_t->priority)
1516 break; /* Thread priority not changing */
1518 if (bl_t->state == STATE_RUNNING)
1520 /* No further blockers */
1521 set_running_thread_priority(bl_t, bl_pr);
1522 break;
1525 bl_t->priority = bl_pr;
1527 /* If blocking thread has a blocker, apply transitive inheritance */
1528 bl = bl_t->blocker;
1530 if (bl == NULL)
1531 break; /* End of chain or object doesn't support inheritance */
1533 next = bl->thread;
1535 if (next == tstart)
1536 break; /* Full-circle - deadlock! */
1538 UNLOCK_THREAD(thread);
1540 #if NUM_CORES > 1
1541 for (;;)
1543 LOCK_THREAD(next);
1545 /* Blocker could change - retest condition */
1546 if (bl->thread == next)
1547 break;
1549 UNLOCK_THREAD(next);
1550 next = bl->thread;
1552 #endif
1553 thread = bl_t;
1554 bl_t = next;
1557 UNLOCK_THREAD(bl_t);
1559 #if NUM_CORES > 1
1560 if (thread != tstart)
1562 /* Relock original if it changed */
1563 LOCK_THREAD(tstart);
1565 #endif
1567 return cores[CURRENT_CORE].running;
1570 /*---------------------------------------------------------------------------
1571 * Transfer ownership to a thread waiting for an objects and transfer
1572 * inherited priority boost from other waiters. This algorithm knows that
1573 * blocking chains may only unblock from the very end.
1575 * Only the owning thread itself may call this and so the assumption that
1576 * it is the running thread is made.
1577 *---------------------------------------------------------------------------
1579 struct thread_entry *
1580 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1582 /* Waking thread inherits priority boost from object owner */
1583 struct blocker *bl = thread->blocker;
1584 struct thread_entry *bl_t = bl->thread;
1585 struct thread_entry *next;
1586 int bl_pr;
1588 THREAD_ASSERT(thread_get_current() == bl_t,
1589 "UPPT->wrong thread", thread_get_current());
1591 LOCK_THREAD(bl_t);
1593 bl_pr = bl->priority;
1595 /* Remove the object's boost from the owning thread */
1596 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1597 bl_pr <= bl_t->priority)
1599 /* No more threads at this priority are waiting and the old level is
1600 * at least the thread level */
1601 int priority = find_first_set_bit(bl_t->pdist.mask);
1603 if (priority != bl_t->priority)
1605 /* Adjust this thread's priority */
1606 set_running_thread_priority(bl_t, priority);
1610 next = *thread->bqp;
1612 if (next == NULL)
1614 /* Expected shortcut - no more waiters */
1615 bl_pr = PRIORITY_IDLE;
1617 else
1619 if (thread->priority <= bl_pr)
1621 /* Need to scan threads remaining in queue */
1622 bl_pr = find_highest_priority_in_list_l(next);
1625 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1626 bl_pr < thread->priority)
1628 /* Thread priority must be raised */
1629 thread->priority = bl_pr;
1633 bl->thread = thread; /* This thread pwns */
1634 bl->priority = bl_pr; /* Save highest blocked priority */
1635 thread->blocker = NULL; /* Thread not blocked */
1637 UNLOCK_THREAD(bl_t);
1639 return bl_t;
1642 /*---------------------------------------------------------------------------
1643 * No threads must be blocked waiting for this thread except for it to exit.
1644 * The alternative is more elaborate cleanup and object registration code.
1645 * Check this for risk of silent data corruption when objects with
1646 * inheritable blocking are abandoned by the owner - not precise but may
1647 * catch something.
1648 *---------------------------------------------------------------------------
1650 void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1652 /* Only one bit in the mask should be set with a frequency on 1 which
1653 * represents the thread's own base priority */
1654 uint32_t mask = thread->pdist.mask;
1655 if ((mask & (mask - 1)) != 0 ||
1656 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1658 unsigned char name[32];
1659 thread_get_name(name, 32, thread);
1660 panicf("%s->%s with obj. waiters", function, name);
1663 #endif /* HAVE_PRIORITY_SCHEDULING */
1665 /*---------------------------------------------------------------------------
1666 * Move a thread back to a running state on its core.
1667 *---------------------------------------------------------------------------
1669 static void core_schedule_wakeup(struct thread_entry *thread)
1671 const unsigned int core = IF_COP_CORE(thread->core);
1673 RTR_LOCK(core);
1675 thread->state = STATE_RUNNING;
1677 add_to_list_l(&cores[core].running, thread);
1678 rtr_add_entry(core, thread->priority);
1680 RTR_UNLOCK(core);
1682 #if NUM_CORES > 1
1683 if (core != CURRENT_CORE)
1684 core_wake(core);
1685 #endif
1688 /*---------------------------------------------------------------------------
1689 * Check the core's timeout list when at least one thread is due to wake.
1690 * Filtering for the condition is done before making the call. Resets the
1691 * tick when the next check will occur.
1692 *---------------------------------------------------------------------------
1694 void check_tmo_threads(void)
1696 const unsigned int core = CURRENT_CORE;
1697 const long tick = current_tick; /* snapshot the current tick */
1698 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1699 struct thread_entry *next = cores[core].timeout;
1701 /* If there are no processes waiting for a timeout, just keep the check
1702 tick from falling into the past. */
1704 /* Break the loop once we have walked through the list of all
1705 * sleeping processes or have removed them all. */
1706 while (next != NULL)
1708 /* Check sleeping threads. Allow interrupts between checks. */
1709 enable_irq();
1711 struct thread_entry *curr = next;
1713 next = curr->tmo.next;
1715 /* Lock thread slot against explicit wakeup */
1716 disable_irq();
1717 LOCK_THREAD(curr);
1719 unsigned state = curr->state;
1721 if (state < TIMEOUT_STATE_FIRST)
1723 /* Cleanup threads no longer on a timeout but still on the
1724 * list. */
1725 remove_from_list_tmo(curr);
1727 else if (TIME_BEFORE(tick, curr->tmo_tick))
1729 /* Timeout still pending - this will be the usual case */
1730 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1732 /* Earliest timeout found so far - move the next check up
1733 to its time */
1734 next_tmo_check = curr->tmo_tick;
1737 else
1739 /* Sleep timeout has been reached so bring the thread back to
1740 * life again. */
1741 if (state == STATE_BLOCKED_W_TMO)
1743 #if NUM_CORES > 1
1744 /* Lock the waiting thread's kernel object */
1745 struct corelock *ocl = curr->obj_cl;
1747 if (corelock_try_lock(ocl) == 0)
1749 /* Need to retry in the correct order though the need is
1750 * unlikely */
1751 UNLOCK_THREAD(curr);
1752 corelock_lock(ocl);
1753 LOCK_THREAD(curr);
1755 if (curr->state != STATE_BLOCKED_W_TMO)
1757 /* Thread was woken or removed explicitely while slot
1758 * was unlocked */
1759 corelock_unlock(ocl);
1760 remove_from_list_tmo(curr);
1761 UNLOCK_THREAD(curr);
1762 continue;
1765 #endif /* NUM_CORES */
1767 remove_from_list_l(curr->bqp, curr);
1769 #ifdef HAVE_WAKEUP_EXT_CB
1770 if (curr->wakeup_ext_cb != NULL)
1771 curr->wakeup_ext_cb(curr);
1772 #endif
1774 #ifdef HAVE_PRIORITY_SCHEDULING
1775 if (curr->blocker != NULL)
1776 wakeup_priority_protocol_release(curr);
1777 #endif
1778 corelock_unlock(ocl);
1780 /* else state == STATE_SLEEPING */
1782 remove_from_list_tmo(curr);
1784 RTR_LOCK(core);
1786 curr->state = STATE_RUNNING;
1788 add_to_list_l(&cores[core].running, curr);
1789 rtr_add_entry(core, curr->priority);
1791 RTR_UNLOCK(core);
1794 UNLOCK_THREAD(curr);
1797 cores[core].next_tmo_check = next_tmo_check;
1800 /*---------------------------------------------------------------------------
1801 * Performs operations that must be done before blocking a thread but after
1802 * the state is saved.
1803 *---------------------------------------------------------------------------
1805 #if NUM_CORES > 1
1806 static inline void run_blocking_ops(
1807 unsigned int core, struct thread_entry *thread)
1809 struct thread_blk_ops *ops = &cores[core].blk_ops;
1810 const unsigned flags = ops->flags;
1812 if (flags == TBOP_CLEAR)
1813 return;
1815 switch (flags)
1817 case TBOP_SWITCH_CORE:
1818 core_switch_blk_op(core, thread);
1819 /* Fall-through */
1820 case TBOP_UNLOCK_CORELOCK:
1821 corelock_unlock(ops->cl_p);
1822 break;
1825 ops->flags = TBOP_CLEAR;
1827 #endif /* NUM_CORES > 1 */
1829 #ifdef RB_PROFILE
1830 void profile_thread(void)
1832 profstart(cores[CURRENT_CORE].running - threads);
1834 #endif
1836 /*---------------------------------------------------------------------------
1837 * Prepares a thread to block on an object's list and/or for a specified
1838 * duration - expects object and slot to be appropriately locked if needed
1839 * and interrupts to be masked.
1840 *---------------------------------------------------------------------------
1842 static inline void block_thread_on_l(struct thread_entry *thread,
1843 unsigned state)
1845 /* If inlined, unreachable branches will be pruned with no size penalty
1846 because state is passed as a constant parameter. */
1847 const unsigned int core = IF_COP_CORE(thread->core);
1849 /* Remove the thread from the list of running threads. */
1850 RTR_LOCK(core);
1851 remove_from_list_l(&cores[core].running, thread);
1852 rtr_subtract_entry(core, thread->priority);
1853 RTR_UNLOCK(core);
1855 /* Add a timeout to the block if not infinite */
1856 switch (state)
1858 case STATE_BLOCKED:
1859 case STATE_BLOCKED_W_TMO:
1860 /* Put the thread into a new list of inactive threads. */
1861 add_to_list_l(thread->bqp, thread);
1863 if (state == STATE_BLOCKED)
1864 break;
1866 /* Fall-through */
1867 case STATE_SLEEPING:
1868 /* If this thread times out sooner than any other thread, update
1869 next_tmo_check to its timeout */
1870 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1872 cores[core].next_tmo_check = thread->tmo_tick;
1875 if (thread->tmo.prev == NULL)
1877 add_to_list_tmo(thread);
1879 /* else thread was never removed from list - just keep it there */
1880 break;
1883 /* Remember the the next thread about to block. */
1884 cores[core].block_task = thread;
1886 /* Report new state. */
1887 thread->state = state;
1890 /*---------------------------------------------------------------------------
1891 * Switch thread in round robin fashion for any given priority. Any thread
1892 * that removed itself from the running list first must specify itself in
1893 * the paramter.
1895 * INTERNAL: Intended for use by kernel and not for programs.
1896 *---------------------------------------------------------------------------
1898 void switch_thread(void)
1900 const unsigned int core = CURRENT_CORE;
1901 struct thread_entry *block = cores[core].block_task;
1902 struct thread_entry *thread = cores[core].running;
1904 /* Get context to save - next thread to run is unknown until all wakeups
1905 * are evaluated */
1906 if (block != NULL)
1908 cores[core].block_task = NULL;
1910 #if NUM_CORES > 1
1911 if (thread == block)
1913 /* This was the last thread running and another core woke us before
1914 * reaching here. Force next thread selection to give tmo threads or
1915 * other threads woken before this block a first chance. */
1916 block = NULL;
1918 else
1919 #endif
1921 /* Blocking task is the old one */
1922 thread = block;
1926 #ifdef RB_PROFILE
1927 profile_thread_stopped(thread - threads);
1928 #endif
1930 /* Begin task switching by saving our current context so that we can
1931 * restore the state of the current thread later to the point prior
1932 * to this call. */
1933 store_context(&thread->context);
1935 /* Check if the current thread stack is overflown */
1936 if (thread->stack[0] != DEADBEEF)
1937 thread_stkov(thread);
1939 #if NUM_CORES > 1
1940 /* Run any blocking operations requested before switching/sleeping */
1941 run_blocking_ops(core, thread);
1942 #endif
1944 #ifdef HAVE_PRIORITY_SCHEDULING
1945 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1946 /* Reset the value of thread's skip count */
1947 thread->skip_count = 0;
1948 #endif
1950 for (;;)
1952 /* If there are threads on a timeout and the earliest wakeup is due,
1953 * check the list and wake any threads that need to start running
1954 * again. */
1955 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
1957 check_tmo_threads();
1960 disable_irq();
1961 RTR_LOCK(core);
1963 thread = cores[core].running;
1965 if (thread == NULL)
1967 /* Enter sleep mode to reduce power usage - woken up on interrupt
1968 * or wakeup request from another core - expected to enable
1969 * interrupts. */
1970 RTR_UNLOCK(core);
1971 core_sleep(IF_COP(core));
1973 else
1975 #ifdef HAVE_PRIORITY_SCHEDULING
1976 /* Select the new task based on priorities and the last time a
1977 * process got CPU time relative to the highest priority runnable
1978 * task. */
1979 struct priority_distribution *pd = &cores[core].rtr;
1980 int max = find_first_set_bit(pd->mask);
1982 if (block == NULL)
1984 /* Not switching on a block, tentatively select next thread */
1985 thread = thread->l.next;
1988 for (;;)
1990 int priority = thread->priority;
1991 int diff;
1993 /* This ridiculously simple method of aging seems to work
1994 * suspiciously well. It does tend to reward CPU hogs (under
1995 * yielding) but that's generally not desirable at all. On the
1996 * plus side, it, relatively to other threads, penalizes excess
1997 * yielding which is good if some high priority thread is
1998 * performing no useful work such as polling for a device to be
1999 * ready. Of course, aging is only employed when higher and lower
2000 * priority threads are runnable. The highest priority runnable
2001 * thread(s) are never skipped. */
2002 if (priority <= max ||
2003 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2004 (diff = priority - max, ++thread->skip_count > diff*diff))
2006 cores[core].running = thread;
2007 break;
2010 thread = thread->l.next;
2012 #else
2013 /* Without priority use a simple FCFS algorithm */
2014 if (block == NULL)
2016 /* Not switching on a block, select next thread */
2017 thread = thread->l.next;
2018 cores[core].running = thread;
2020 #endif /* HAVE_PRIORITY_SCHEDULING */
2022 RTR_UNLOCK(core);
2023 enable_irq();
2024 break;
2028 /* And finally give control to the next thread. */
2029 load_context(&thread->context);
2031 #ifdef RB_PROFILE
2032 profile_thread_started(thread - threads);
2033 #endif
2036 /*---------------------------------------------------------------------------
2037 * Sleeps a thread for at least a specified number of ticks with zero being
2038 * a wait until the next tick.
2040 * INTERNAL: Intended for use by kernel and not for programs.
2041 *---------------------------------------------------------------------------
2043 void sleep_thread(int ticks)
2045 struct thread_entry *current = cores[CURRENT_CORE].running;
2047 LOCK_THREAD(current);
2049 /* Set our timeout, remove from run list and join timeout list. */
2050 current->tmo_tick = current_tick + ticks + 1;
2051 block_thread_on_l(current, STATE_SLEEPING);
2053 UNLOCK_THREAD(current);
2056 /*---------------------------------------------------------------------------
2057 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2059 * INTERNAL: Intended for use by kernel objects and not for programs.
2060 *---------------------------------------------------------------------------
2062 void block_thread(struct thread_entry *current)
2064 /* Set the state to blocked and take us off of the run queue until we
2065 * are explicitly woken */
2066 LOCK_THREAD(current);
2068 /* Set the list for explicit wakeup */
2069 block_thread_on_l(current, STATE_BLOCKED);
2071 #ifdef HAVE_PRIORITY_SCHEDULING
2072 if (current->blocker != NULL)
2074 /* Object supports PIP */
2075 current = blocker_inherit_priority(current);
2077 #endif
2079 UNLOCK_THREAD(current);
2082 /*---------------------------------------------------------------------------
2083 * Block a thread on a blocking queue for a specified time interval or until
2084 * explicitly woken - whichever happens first.
2086 * INTERNAL: Intended for use by kernel objects and not for programs.
2087 *---------------------------------------------------------------------------
2089 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2091 /* Get the entry for the current running thread. */
2092 LOCK_THREAD(current);
2094 /* Set the state to blocked with the specified timeout */
2095 current->tmo_tick = current_tick + timeout;
2097 /* Set the list for explicit wakeup */
2098 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2100 #ifdef HAVE_PRIORITY_SCHEDULING
2101 if (current->blocker != NULL)
2103 /* Object supports PIP */
2104 current = blocker_inherit_priority(current);
2106 #endif
2108 UNLOCK_THREAD(current);
2111 /*---------------------------------------------------------------------------
2112 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2113 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2115 * This code should be considered a critical section by the caller meaning
2116 * that the object's corelock should be held.
2118 * INTERNAL: Intended for use by kernel objects and not for programs.
2119 *---------------------------------------------------------------------------
2121 unsigned int wakeup_thread(struct thread_entry **list)
2123 struct thread_entry *thread = *list;
2124 unsigned int result = THREAD_NONE;
2126 /* Check if there is a blocked thread at all. */
2127 if (thread == NULL)
2128 return result;
2130 LOCK_THREAD(thread);
2132 /* Determine thread's current state. */
2133 switch (thread->state)
2135 case STATE_BLOCKED:
2136 case STATE_BLOCKED_W_TMO:
2137 remove_from_list_l(list, thread);
2139 result = THREAD_OK;
2141 #ifdef HAVE_PRIORITY_SCHEDULING
2142 struct thread_entry *current;
2143 struct blocker *bl = thread->blocker;
2145 if (bl == NULL)
2147 /* No inheritance - just boost the thread by aging */
2148 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2149 thread->skip_count = thread->priority;
2150 current = cores[CURRENT_CORE].running;
2152 else
2154 /* Call the specified unblocking PIP */
2155 current = bl->wakeup_protocol(thread);
2158 if (current != NULL && thread->priority < current->priority
2159 IF_COP( && thread->core == current->core ))
2161 /* Woken thread is higher priority and exists on the same CPU core;
2162 * recommend a task switch. Knowing if this is an interrupt call
2163 * would be helpful here. */
2164 result |= THREAD_SWITCH;
2166 #endif /* HAVE_PRIORITY_SCHEDULING */
2168 core_schedule_wakeup(thread);
2169 break;
2171 /* Nothing to do. State is not blocked. */
2172 #if THREAD_EXTRA_CHECKS
2173 default:
2174 THREAD_PANICF("wakeup_thread->block invalid", thread);
2175 case STATE_RUNNING:
2176 case STATE_KILLED:
2177 break;
2178 #endif
2181 UNLOCK_THREAD(thread);
2182 return result;
2185 /*---------------------------------------------------------------------------
2186 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2187 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2188 * the queue must be locked first.
2190 * INTERNAL: Intended for use by kernel objects and not for programs.
2191 *---------------------------------------------------------------------------
2193 unsigned int thread_queue_wake(struct thread_entry **list)
2195 unsigned result = THREAD_NONE;
2197 for (;;)
2199 unsigned int rc = wakeup_thread(list);
2201 if (rc == THREAD_NONE)
2202 break; /* No more threads */
2204 result |= rc;
2207 return result;
2210 /*---------------------------------------------------------------------------
2211 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2212 * will be locked on multicore.
2213 *---------------------------------------------------------------------------
2215 static struct thread_entry * find_empty_thread_slot(void)
2217 /* Any slot could be on an interrupt-accessible list */
2218 IF_COP( int oldlevel = disable_irq_save(); )
2219 struct thread_entry *thread = NULL;
2220 int n;
2222 for (n = 0; n < MAXTHREADS; n++)
2224 /* Obtain current slot state - lock it on multicore */
2225 struct thread_entry *t = &threads[n];
2226 LOCK_THREAD(t);
2228 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2230 /* Slot is empty - leave it locked and caller will unlock */
2231 thread = t;
2232 break;
2235 /* Finished examining slot - no longer busy - unlock on multicore */
2236 UNLOCK_THREAD(t);
2239 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2240 not accesible to them yet */
2241 return thread;
2245 /*---------------------------------------------------------------------------
2246 * Place the current core in idle mode - woken up on interrupt or wake
2247 * request from another core.
2248 *---------------------------------------------------------------------------
2250 void core_idle(void)
2252 IF_COP( const unsigned int core = CURRENT_CORE; )
2253 disable_irq();
2254 core_sleep(IF_COP(core));
2257 /*---------------------------------------------------------------------------
2258 * Create a thread. If using a dual core architecture, specify which core to
2259 * start the thread on.
2261 * Return ID if context area could be allocated, else NULL.
2262 *---------------------------------------------------------------------------
2264 struct thread_entry*
2265 create_thread(void (*function)(void), void* stack, size_t stack_size,
2266 unsigned flags, const char *name
2267 IF_PRIO(, int priority)
2268 IF_COP(, unsigned int core))
2270 unsigned int i;
2271 unsigned int stack_words;
2272 uintptr_t stackptr, stackend;
2273 struct thread_entry *thread;
2274 unsigned state;
2275 int oldlevel;
2277 thread = find_empty_thread_slot();
2278 if (thread == NULL)
2280 return NULL;
2283 oldlevel = disable_irq_save();
2285 /* Munge the stack to make it easy to spot stack overflows */
2286 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2287 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2288 stack_size = stackend - stackptr;
2289 stack_words = stack_size / sizeof (uintptr_t);
2291 for (i = 0; i < stack_words; i++)
2293 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2296 /* Store interesting information */
2297 thread->name = name;
2298 thread->stack = (uintptr_t *)stackptr;
2299 thread->stack_size = stack_size;
2300 thread->queue = NULL;
2301 #ifdef HAVE_WAKEUP_EXT_CB
2302 thread->wakeup_ext_cb = NULL;
2303 #endif
2304 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2305 thread->cpu_boost = 0;
2306 #endif
2307 #ifdef HAVE_PRIORITY_SCHEDULING
2308 memset(&thread->pdist, 0, sizeof(thread->pdist));
2309 thread->blocker = NULL;
2310 thread->base_priority = priority;
2311 thread->priority = priority;
2312 thread->skip_count = priority;
2313 prio_add_entry(&thread->pdist, priority);
2314 #endif
2316 #if NUM_CORES > 1
2317 thread->core = core;
2319 /* Writeback stack munging or anything else before starting */
2320 if (core != CURRENT_CORE)
2322 flush_icache();
2324 #endif
2326 /* Thread is not on any timeout list but be a bit paranoid */
2327 thread->tmo.prev = NULL;
2329 state = (flags & CREATE_THREAD_FROZEN) ?
2330 STATE_FROZEN : STATE_RUNNING;
2332 thread->context.sp = (typeof (thread->context.sp))stackend;
2334 /* Load the thread's context structure with needed startup information */
2335 THREAD_STARTUP_INIT(core, thread, function);
2337 thread->state = state;
2339 if (state == STATE_RUNNING)
2340 core_schedule_wakeup(thread);
2342 UNLOCK_THREAD(thread);
2344 restore_irq(oldlevel);
2346 return thread;
2349 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2350 /*---------------------------------------------------------------------------
2351 * Change the boost state of a thread boosting or unboosting the CPU
2352 * as required.
2353 *---------------------------------------------------------------------------
2355 static inline void boost_thread(struct thread_entry *thread, bool boost)
2357 if ((thread->cpu_boost != 0) != boost)
2359 thread->cpu_boost = boost;
2360 cpu_boost(boost);
2364 void trigger_cpu_boost(void)
2366 struct thread_entry *current = cores[CURRENT_CORE].running;
2367 boost_thread(current, true);
2370 void cancel_cpu_boost(void)
2372 struct thread_entry *current = cores[CURRENT_CORE].running;
2373 boost_thread(current, false);
2375 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2377 /*---------------------------------------------------------------------------
2378 * Block the current thread until another thread terminates. A thread may
2379 * wait on itself to terminate which prevents it from running again and it
2380 * will need to be killed externally.
2381 * Parameter is the ID as returned from create_thread().
2382 *---------------------------------------------------------------------------
2384 void thread_wait(struct thread_entry *thread)
2386 struct thread_entry *current = cores[CURRENT_CORE].running;
2388 if (thread == NULL)
2389 thread = current;
2391 /* Lock thread-as-waitable-object lock */
2392 corelock_lock(&thread->waiter_cl);
2394 /* Be sure it hasn't been killed yet */
2395 if (thread->state != STATE_KILLED)
2397 IF_COP( current->obj_cl = &thread->waiter_cl; )
2398 current->bqp = &thread->queue;
2400 disable_irq();
2401 block_thread(current);
2403 corelock_unlock(&thread->waiter_cl);
2405 switch_thread();
2406 return;
2409 corelock_unlock(&thread->waiter_cl);
2412 /*---------------------------------------------------------------------------
2413 * Exit the current thread. The Right Way to Do Things (TM).
2414 *---------------------------------------------------------------------------
2416 void thread_exit(void)
2418 const unsigned int core = CURRENT_CORE;
2419 struct thread_entry *current = cores[core].running;
2421 /* Cancel CPU boost if any */
2422 cancel_cpu_boost();
2424 disable_irq();
2426 corelock_lock(&current->waiter_cl);
2427 LOCK_THREAD(current);
2429 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2430 if (current->name == THREAD_DESTRUCT)
2432 /* Thread being killed - become a waiter */
2433 UNLOCK_THREAD(current);
2434 corelock_unlock(&current->waiter_cl);
2435 thread_wait(current);
2436 THREAD_PANICF("thread_exit->WK:*R", current);
2438 #endif
2440 #ifdef HAVE_PRIORITY_SCHEDULING
2441 check_for_obj_waiters("thread_exit", current);
2442 #endif
2444 if (current->tmo.prev != NULL)
2446 /* Cancel pending timeout list removal */
2447 remove_from_list_tmo(current);
2450 /* Switch tasks and never return */
2451 block_thread_on_l(current, STATE_KILLED);
2453 #if NUM_CORES > 1
2454 /* Switch to the idle stack if not on the main core (where "main"
2455 * runs) - we can hope gcc doesn't need the old stack beyond this
2456 * point. */
2457 if (core != CPU)
2459 switch_to_idle_stack(core);
2462 flush_icache();
2463 #endif
2464 current->name = NULL;
2466 /* Signal this thread */
2467 thread_queue_wake(&current->queue);
2468 corelock_unlock(&current->waiter_cl);
2469 /* Slot must be unusable until thread is really gone */
2470 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2471 switch_thread();
2472 /* This should never and must never be reached - if it is, the
2473 * state is corrupted */
2474 THREAD_PANICF("thread_exit->K:*R", current);
2477 #ifdef ALLOW_REMOVE_THREAD
2478 /*---------------------------------------------------------------------------
2479 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2480 * normal programs.
2482 * Parameter is the ID as returned from create_thread().
2484 * Use with care on threads that are not under careful control as this may
2485 * leave various objects in an undefined state.
2486 *---------------------------------------------------------------------------
2488 void remove_thread(struct thread_entry *thread)
2490 #if NUM_CORES > 1
2491 /* core is not constant here because of core switching */
2492 unsigned int core = CURRENT_CORE;
2493 unsigned int old_core = NUM_CORES;
2494 struct corelock *ocl = NULL;
2495 #else
2496 const unsigned int core = CURRENT_CORE;
2497 #endif
2498 struct thread_entry *current = cores[core].running;
2500 unsigned state;
2501 int oldlevel;
2503 if (thread == NULL)
2504 thread = current;
2506 if (thread == current)
2507 thread_exit(); /* Current thread - do normal exit */
2509 oldlevel = disable_irq_save();
2511 corelock_lock(&thread->waiter_cl);
2512 LOCK_THREAD(thread);
2514 state = thread->state;
2516 if (state == STATE_KILLED)
2518 goto thread_killed;
2521 #if NUM_CORES > 1
2522 if (thread->name == THREAD_DESTRUCT)
2524 /* Thread being killed - become a waiter */
2525 UNLOCK_THREAD(thread);
2526 corelock_unlock(&thread->waiter_cl);
2527 restore_irq(oldlevel);
2528 thread_wait(thread);
2529 return;
2532 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2534 #ifdef HAVE_PRIORITY_SCHEDULING
2535 check_for_obj_waiters("remove_thread", thread);
2536 #endif
2538 if (thread->core != core)
2540 /* Switch cores and safely extract the thread there */
2541 /* Slot HAS to be unlocked or a deadlock could occur which means other
2542 * threads have to be guided into becoming thread waiters if they
2543 * attempt to remove it. */
2544 unsigned int new_core = thread->core;
2546 corelock_unlock(&thread->waiter_cl);
2548 UNLOCK_THREAD(thread);
2549 restore_irq(oldlevel);
2551 old_core = switch_core(new_core);
2553 oldlevel = disable_irq_save();
2555 corelock_lock(&thread->waiter_cl);
2556 LOCK_THREAD(thread);
2558 state = thread->state;
2559 core = new_core;
2560 /* Perform the extraction and switch ourselves back to the original
2561 processor */
2563 #endif /* NUM_CORES > 1 */
2565 if (thread->tmo.prev != NULL)
2567 /* Clean thread off the timeout list if a timeout check hasn't
2568 * run yet */
2569 remove_from_list_tmo(thread);
2572 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2573 /* Cancel CPU boost if any */
2574 boost_thread(thread, false);
2575 #endif
2577 IF_COP( retry_state: )
2579 switch (state)
2581 case STATE_RUNNING:
2582 RTR_LOCK(core);
2583 /* Remove thread from ready to run tasks */
2584 remove_from_list_l(&cores[core].running, thread);
2585 rtr_subtract_entry(core, thread->priority);
2586 RTR_UNLOCK(core);
2587 break;
2588 case STATE_BLOCKED:
2589 case STATE_BLOCKED_W_TMO:
2590 /* Remove thread from the queue it's blocked on - including its
2591 * own if waiting there */
2592 #if NUM_CORES > 1
2593 if (&thread->waiter_cl != thread->obj_cl)
2595 ocl = thread->obj_cl;
2597 if (corelock_try_lock(ocl) == 0)
2599 UNLOCK_THREAD(thread);
2600 corelock_lock(ocl);
2601 LOCK_THREAD(thread);
2603 if (thread->state != state)
2605 /* Something woke the thread */
2606 state = thread->state;
2607 corelock_unlock(ocl);
2608 goto retry_state;
2612 #endif
2613 remove_from_list_l(thread->bqp, thread);
2615 #ifdef HAVE_WAKEUP_EXT_CB
2616 if (thread->wakeup_ext_cb != NULL)
2617 thread->wakeup_ext_cb(thread);
2618 #endif
2620 #ifdef HAVE_PRIORITY_SCHEDULING
2621 if (thread->blocker != NULL)
2623 /* Remove thread's priority influence from its chain */
2624 wakeup_priority_protocol_release(thread);
2626 #endif
2628 #if NUM_CORES > 1
2629 if (ocl != NULL)
2630 corelock_unlock(ocl);
2631 #endif
2632 break;
2633 /* Otherwise thread is frozen and hasn't run yet */
2636 thread->state = STATE_KILLED;
2638 /* If thread was waiting on itself, it will have been removed above.
2639 * The wrong order would result in waking the thread first and deadlocking
2640 * since the slot is already locked. */
2641 thread_queue_wake(&thread->queue);
2643 thread->name = NULL;
2645 thread_killed: /* Thread was already killed */
2646 /* Removal complete - safe to unlock and reenable interrupts */
2647 corelock_unlock(&thread->waiter_cl);
2648 UNLOCK_THREAD(thread);
2649 restore_irq(oldlevel);
2651 #if NUM_CORES > 1
2652 if (old_core < NUM_CORES)
2654 /* Did a removal on another processor's thread - switch back to
2655 native core */
2656 switch_core(old_core);
2658 #endif
2660 #endif /* ALLOW_REMOVE_THREAD */
2662 #ifdef HAVE_PRIORITY_SCHEDULING
2663 /*---------------------------------------------------------------------------
2664 * Sets the thread's relative base priority for the core it runs on. Any
2665 * needed inheritance changes also may happen.
2666 *---------------------------------------------------------------------------
2668 int thread_set_priority(struct thread_entry *thread, int priority)
2670 int old_base_priority = -1;
2672 /* A little safety measure */
2673 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2674 return -1;
2676 if (thread == NULL)
2677 thread = cores[CURRENT_CORE].running;
2679 /* Thread could be on any list and therefore on an interrupt accessible
2680 one - disable interrupts */
2681 int oldlevel = disable_irq_save();
2683 LOCK_THREAD(thread);
2685 /* Make sure it's not killed */
2686 if (thread->state != STATE_KILLED)
2688 int old_priority = thread->priority;
2690 old_base_priority = thread->base_priority;
2691 thread->base_priority = priority;
2693 prio_move_entry(&thread->pdist, old_base_priority, priority);
2694 priority = find_first_set_bit(thread->pdist.mask);
2696 if (old_priority == priority)
2698 /* No priority change - do nothing */
2700 else if (thread->state == STATE_RUNNING)
2702 /* This thread is running - change location on the run
2703 * queue. No transitive inheritance needed. */
2704 set_running_thread_priority(thread, priority);
2706 else
2708 thread->priority = priority;
2710 if (thread->blocker != NULL)
2712 /* Bubble new priority down the chain */
2713 struct blocker *bl = thread->blocker; /* Blocker struct */
2714 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2715 struct thread_entry * const tstart = thread; /* Initial thread */
2716 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2718 for (;;)
2720 struct thread_entry *next; /* Next thread to check */
2721 int bl_pr; /* Highest blocked thread */
2722 int queue_pr; /* New highest blocked thread */
2723 #if NUM_CORES > 1
2724 /* Owner can change but thread cannot be dislodged - thread
2725 * may not be the first in the queue which allows other
2726 * threads ahead in the list to be given ownership during the
2727 * operation. If thread is next then the waker will have to
2728 * wait for us and the owner of the object will remain fixed.
2729 * If we successfully grab the owner -- which at some point
2730 * is guaranteed -- then the queue remains fixed until we
2731 * pass by. */
2732 for (;;)
2734 LOCK_THREAD(bl_t);
2736 /* Double-check the owner - retry if it changed */
2737 if (bl->thread == bl_t)
2738 break;
2740 UNLOCK_THREAD(bl_t);
2741 bl_t = bl->thread;
2743 #endif
2744 bl_pr = bl->priority;
2746 if (highest > bl_pr)
2747 break; /* Object priority won't change */
2749 /* This will include the thread being set */
2750 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2752 if (queue_pr == bl_pr)
2753 break; /* Object priority not changing */
2755 /* Update thread boost for this object */
2756 bl->priority = queue_pr;
2757 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2758 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2760 if (bl_t->priority == bl_pr)
2761 break; /* Blocking thread priority not changing */
2763 if (bl_t->state == STATE_RUNNING)
2765 /* Thread not blocked - we're done */
2766 set_running_thread_priority(bl_t, bl_pr);
2767 break;
2770 bl_t->priority = bl_pr;
2771 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2773 if (bl == NULL)
2774 break; /* End of chain */
2776 next = bl->thread;
2778 if (next == tstart)
2779 break; /* Full-circle */
2781 UNLOCK_THREAD(thread);
2783 thread = bl_t;
2784 bl_t = next;
2785 } /* for (;;) */
2787 UNLOCK_THREAD(bl_t);
2792 UNLOCK_THREAD(thread);
2794 restore_irq(oldlevel);
2796 return old_base_priority;
2799 /*---------------------------------------------------------------------------
2800 * Returns the current base priority for a thread.
2801 *---------------------------------------------------------------------------
2803 int thread_get_priority(struct thread_entry *thread)
2805 /* Simple, quick probe. */
2806 if (thread == NULL)
2807 thread = cores[CURRENT_CORE].running;
2809 return thread->base_priority;
2811 #endif /* HAVE_PRIORITY_SCHEDULING */
2813 /*---------------------------------------------------------------------------
2814 * Starts a frozen thread - similar semantics to wakeup_thread except that
2815 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2816 * virtue of the slot having a state of STATE_FROZEN.
2817 *---------------------------------------------------------------------------
2819 void thread_thaw(struct thread_entry *thread)
2821 int oldlevel = disable_irq_save();
2822 LOCK_THREAD(thread);
2824 if (thread->state == STATE_FROZEN)
2825 core_schedule_wakeup(thread);
2827 UNLOCK_THREAD(thread);
2828 restore_irq(oldlevel);
2831 /*---------------------------------------------------------------------------
2832 * Return the ID of the currently executing thread.
2833 *---------------------------------------------------------------------------
2835 struct thread_entry * thread_get_current(void)
2837 return cores[CURRENT_CORE].running;
2840 #if NUM_CORES > 1
2841 /*---------------------------------------------------------------------------
2842 * Switch the processor that the currently executing thread runs on.
2843 *---------------------------------------------------------------------------
2845 unsigned int switch_core(unsigned int new_core)
2847 const unsigned int core = CURRENT_CORE;
2848 struct thread_entry *current = cores[core].running;
2850 if (core == new_core)
2852 /* No change - just return same core */
2853 return core;
2856 int oldlevel = disable_irq_save();
2857 LOCK_THREAD(current);
2859 if (current->name == THREAD_DESTRUCT)
2861 /* Thread being killed - deactivate and let process complete */
2862 UNLOCK_THREAD(current);
2863 restore_irq(oldlevel);
2864 thread_wait(current);
2865 /* Should never be reached */
2866 THREAD_PANICF("switch_core->D:*R", current);
2869 /* Get us off the running list for the current core */
2870 RTR_LOCK(core);
2871 remove_from_list_l(&cores[core].running, current);
2872 rtr_subtract_entry(core, current->priority);
2873 RTR_UNLOCK(core);
2875 /* Stash return value (old core) in a safe place */
2876 current->retval = core;
2878 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2879 * the other core will likely attempt a removal from the wrong list! */
2880 if (current->tmo.prev != NULL)
2882 remove_from_list_tmo(current);
2885 /* Change the core number for this thread slot */
2886 current->core = new_core;
2888 /* Do not use core_schedule_wakeup here since this will result in
2889 * the thread starting to run on the other core before being finished on
2890 * this one. Delay the list unlock to keep the other core stuck
2891 * until this thread is ready. */
2892 RTR_LOCK(new_core);
2894 rtr_add_entry(new_core, current->priority);
2895 add_to_list_l(&cores[new_core].running, current);
2897 /* Make a callback into device-specific code, unlock the wakeup list so
2898 * that execution may resume on the new core, unlock our slot and finally
2899 * restore the interrupt level */
2900 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
2901 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
2902 cores[core].block_task = current;
2904 UNLOCK_THREAD(current);
2906 /* Alert other core to activity */
2907 core_wake(new_core);
2909 /* Do the stack switching, cache_maintenence and switch_thread call -
2910 requires native code */
2911 switch_thread_core(core, current);
2913 /* Finally return the old core to caller */
2914 return current->retval;
2916 #endif /* NUM_CORES > 1 */
2918 /*---------------------------------------------------------------------------
2919 * Initialize threading API. This assumes interrupts are not yet enabled. On
2920 * multicore setups, no core is allowed to proceed until create_thread calls
2921 * are safe to perform.
2922 *---------------------------------------------------------------------------
2924 void init_threads(void)
2926 const unsigned int core = CURRENT_CORE;
2927 struct thread_entry *thread;
2929 /* CPU will initialize first and then sleep */
2930 thread = find_empty_thread_slot();
2932 if (thread == NULL)
2934 /* WTF? There really must be a slot available at this stage.
2935 * This can fail if, for example, .bss isn't zero'ed out by the loader
2936 * or threads is in the wrong section. */
2937 THREAD_PANICF("init_threads->no slot", NULL);
2940 /* Initialize initially non-zero members of core */
2941 cores[core].next_tmo_check = current_tick; /* Something not in the past */
2943 /* Initialize initially non-zero members of slot */
2944 UNLOCK_THREAD(thread); /* No sync worries yet */
2945 thread->name = main_thread_name;
2946 thread->state = STATE_RUNNING;
2947 IF_COP( thread->core = core; )
2948 #ifdef HAVE_PRIORITY_SCHEDULING
2949 corelock_init(&cores[core].rtr_cl);
2950 thread->base_priority = PRIORITY_USER_INTERFACE;
2951 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
2952 thread->priority = PRIORITY_USER_INTERFACE;
2953 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
2954 #endif
2955 corelock_init(&thread->waiter_cl);
2956 corelock_init(&thread->slot_cl);
2958 add_to_list_l(&cores[core].running, thread);
2960 if (core == CPU)
2962 thread->stack = stackbegin;
2963 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
2964 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2965 /* Wait for other processors to finish their inits since create_thread
2966 * isn't safe to call until the kernel inits are done. The first
2967 * threads created in the system must of course be created by CPU. */
2968 core_thread_init(CPU);
2970 else
2972 /* Initial stack is the idle stack */
2973 thread->stack = idle_stacks[core];
2974 thread->stack_size = IDLE_STACK_SIZE;
2975 /* After last processor completes, it should signal all others to
2976 * proceed or may signal the next and call thread_exit(). The last one
2977 * to finish will signal CPU. */
2978 core_thread_init(core);
2979 /* Other cores do not have a main thread - go idle inside switch_thread
2980 * until a thread can run on the core. */
2981 thread_exit();
2982 #endif /* NUM_CORES */
2986 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
2987 #if NUM_CORES == 1
2988 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
2989 #else
2990 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
2991 #endif
2993 unsigned int stack_words = stack_size / sizeof (uintptr_t);
2994 unsigned int i;
2995 int usage = 0;
2997 for (i = 0; i < stack_words; i++)
2999 if (stackptr[i] != DEADBEEF)
3001 usage = ((stack_words - i) * 100) / stack_words;
3002 break;
3006 return usage;
3009 /*---------------------------------------------------------------------------
3010 * Returns the maximum percentage of stack a thread ever used while running.
3011 * NOTE: Some large buffer allocations that don't use enough the buffer to
3012 * overwrite stackptr[0] will not be seen.
3013 *---------------------------------------------------------------------------
3015 int thread_stack_usage(const struct thread_entry *thread)
3017 return stack_usage(thread->stack, thread->stack_size);
3020 #if NUM_CORES > 1
3021 /*---------------------------------------------------------------------------
3022 * Returns the maximum percentage of the core's idle stack ever used during
3023 * runtime.
3024 *---------------------------------------------------------------------------
3026 int idle_stack_usage(unsigned int core)
3028 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3030 #endif
3032 /*---------------------------------------------------------------------------
3033 * Fills in the buffer with the specified thread's name. If the name is NULL,
3034 * empty, or the thread is in destruct state a formatted ID is written
3035 * instead.
3036 *---------------------------------------------------------------------------
3038 void thread_get_name(char *buffer, int size,
3039 struct thread_entry *thread)
3041 if (size <= 0)
3042 return;
3044 *buffer = '\0';
3046 if (thread)
3048 /* Display thread name if one or ID if none */
3049 const char *name = thread->name;
3050 const char *fmt = "%s";
3051 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3053 name = (const char *)thread;
3054 fmt = "%08lX";
3056 snprintf(buffer, size, fmt, name);