Add DM320 I²C driver, although not (yet) enabled in the sources.
[Rockbox.git] / firmware / thread.c
blob0049df3e90f6e1163a5341b8e53d19fd7593c50a
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 #ifdef MAX_PHYS_SECTOR_SIZE
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 PROC_CTL(CURRENT_CORE) = PROC_SLEEP;
408 nop; nop; nop;
409 enable_irq();
411 #else
412 static inline void core_sleep(unsigned int core)
414 #if 1
415 asm volatile (
416 "mov r0, #4 \n" /* r0 = 0x4 << core */
417 "mov r0, r0, lsl %[c] \n"
418 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
419 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
420 "tst r1, r0, lsl #2 \n"
421 "moveq r1, #0x80000000 \n" /* Then sleep */
422 "streq r1, [%[ctl], %[c], lsl #2] \n"
423 "moveq r1, #0 \n" /* Clear control reg */
424 "streq r1, [%[ctl], %[c], lsl #2] \n"
425 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
426 "str r1, [%[mbx], #8] \n"
427 "1: \n" /* Wait for wake procedure to finish */
428 "ldr r1, [%[mbx], #0] \n"
429 "tst r1, r0, lsr #2 \n"
430 "bne 1b \n"
432 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE), [c]"r"(core)
433 : "r0", "r1");
434 #else /* C version for reference */
435 /* Signal intent to sleep */
436 MBX_MSG_SET = 0x4 << core;
438 /* Something waking or other processor intends to wake us? */
439 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
441 PROC_CTL(core) = PROC_SLEEP; nop; /* Snooze */
442 PROC_CTL(core) = 0; /* Clear control reg */
445 /* Signal wake - clear wake flag */
446 MBX_MSG_CLR = 0x14 << core;
448 /* Wait for other processor to finish wake procedure */
449 while (MBX_MSG_STAT & (0x1 << core));
450 #endif /* ASM/C selection */
451 enable_irq();
453 #endif /* NUM_CORES */
454 #elif CONFIG_CPU == PP5002
455 #if NUM_CORES == 1
456 static inline void core_sleep(void)
458 asm volatile (
459 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
460 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
461 * that the correct alternative is executed. Don't change the order
462 * of the next 4 instructions! */
463 "tst pc, #0x0c \n"
464 "mov r0, #0xca \n"
465 "strne r0, [%[ctl]] \n"
466 "streq r0, [%[ctl]] \n"
467 "nop \n" /* nop's needed because of pipeline */
468 "nop \n"
469 "nop \n"
471 : [ctl]"r"(&PROC_CTL(CURRENT_CORE))
472 : "r0"
474 enable_irq();
476 #else
477 /* PP5002 has no mailboxes - emulate using bytes */
478 static inline void core_sleep(unsigned int core)
480 #if 1
481 asm volatile (
482 "mov r0, #1 \n" /* Signal intent to sleep */
483 "strb r0, [%[sem], #2] \n"
484 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
485 "cmp r0, #0 \n"
486 "bne 2f \n"
487 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
488 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
489 * that the correct alternative is executed. Don't change the order
490 * of the next 4 instructions! */
491 "tst pc, #0x0c \n"
492 "mov r0, #0xca \n"
493 "strne r0, [%[ctl], %[c], lsl #2] \n"
494 "streq r0, [%[ctl], %[c], lsl #2] \n"
495 "nop \n" /* nop's needed because of pipeline */
496 "nop \n"
497 "nop \n"
498 "2: \n"
499 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
500 "strb r0, [%[sem], #1] \n"
501 "strb r0, [%[sem], #2] \n"
502 "1: \n" /* Wait for wake procedure to finish */
503 "ldrb r0, [%[sem], #0] \n"
504 "cmp r0, #0 \n"
505 "bne 1b \n"
507 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
508 [ctl]"r"(&PROC_CTL(CPU))
509 : "r0"
511 #else /* C version for reference */
512 /* Signal intent to sleep */
513 core_semaphores[core].intend_sleep = 1;
515 /* Something waking or other processor intends to wake us? */
516 if (core_semaphores[core].stay_awake == 0)
518 PROC_CTL(core) = PROC_SLEEP; /* Snooze */
519 nop; nop; nop;
522 /* Signal wake - clear wake flag */
523 core_semaphores[core].stay_awake = 0;
524 core_semaphores[core].intend_sleep = 0;
526 /* Wait for other processor to finish wake procedure */
527 while (core_semaphores[core].intend_wake != 0);
529 /* Enable IRQ */
530 #endif /* ASM/C selection */
531 enable_irq();
533 #endif /* NUM_CORES */
534 #endif /* PP CPU type */
536 /*---------------------------------------------------------------------------
537 * Wake another processor core that is sleeping or prevent it from doing so
538 * if it was already destined. FIQ, IRQ should be disabled before calling.
539 *---------------------------------------------------------------------------
541 #if NUM_CORES == 1
542 /* Shared single-core build debugging version */
543 void core_wake(void)
545 /* No wakey - core already wakey */
547 #elif defined (CPU_PP502x)
548 void core_wake(unsigned int othercore)
550 #if 1
551 /* avoid r0 since that contains othercore */
552 asm volatile (
553 "mrs r3, cpsr \n" /* Disable IRQ */
554 "orr r1, r3, #0x80 \n"
555 "msr cpsr_c, r1 \n"
556 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
557 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
558 "str r2, [%[mbx], #4] \n"
559 "1: \n" /* If it intends to sleep, let it first */
560 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
561 "eor r1, r1, #0xc \n"
562 "tst r1, r2, lsr #2 \n"
563 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
564 "tsteq r1, #0x80000000 \n"
565 "beq 1b \n" /* Wait for sleep or wake */
566 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
567 "movne r1, #0x0 \n"
568 "strne r1, [%[ctl], %[oc], lsl #2] \n"
569 "mov r1, r2, lsr #4 \n"
570 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
571 "msr cpsr_c, r3 \n" /* Restore IRQ */
573 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
574 [oc]"r"(othercore)
575 : "r1", "r2", "r3");
576 #else /* C version for reference */
577 /* Disable interrupts - avoid reentrancy from the tick */
578 int oldlevel = disable_irq_save();
580 /* Signal intent to wake other processor - set stay awake */
581 MBX_MSG_SET = 0x11 << othercore;
583 /* If it intends to sleep, wait until it does or aborts */
584 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
585 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
587 /* If sleeping, wake it up */
588 if (PROC_CTL(othercore) & PROC_SLEEP)
589 PROC_CTL(othercore) = 0;
591 /* Done with wake procedure */
592 MBX_MSG_CLR = 0x1 << othercore;
593 restore_irq(oldlevel);
594 #endif /* ASM/C selection */
596 #elif CONFIG_CPU == PP5002
597 /* PP5002 has no mailboxes - emulate using bytes */
598 void core_wake(unsigned int othercore)
600 #if 1
601 /* avoid r0 since that contains othercore */
602 asm volatile (
603 "mrs r3, cpsr \n" /* Disable IRQ */
604 "orr r1, r3, #0x80 \n"
605 "msr cpsr_c, r1 \n"
606 "mov r1, #1 \n" /* Signal intent to wake other core */
607 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
608 "strh r1, [%[sem], #0] \n"
609 "mov r2, #0x8000 \n"
610 "1: \n" /* If it intends to sleep, let it first */
611 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
612 "cmp r1, #1 \n"
613 "ldr r1, [%[st]] \n" /* && not sleeping ? */
614 "tsteq r1, r2, lsr %[oc] \n"
615 "beq 1b \n" /* Wait for sleep or wake */
616 "tst r1, r2, lsr %[oc] \n"
617 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
618 "movne r1, #0xce \n"
619 "strne r1, [r2, %[oc], lsl #2] \n"
620 "mov r1, #0 \n" /* Done with wake procedure */
621 "strb r1, [%[sem], #0] \n"
622 "msr cpsr_c, r3 \n" /* Restore IRQ */
624 : [sem]"r"(&core_semaphores[othercore]),
625 [st]"r"(&PROC_STAT),
626 [oc]"r"(othercore)
627 : "r1", "r2", "r3"
629 #else /* C version for reference */
630 /* Disable interrupts - avoid reentrancy from the tick */
631 int oldlevel = disable_irq_save();
633 /* Signal intent to wake other processor - set stay awake */
634 core_semaphores[othercore].intend_wake = 1;
635 core_semaphores[othercore].stay_awake = 1;
637 /* If it intends to sleep, wait until it does or aborts */
638 while (core_semaphores[othercore].intend_sleep != 0 &&
639 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
641 /* If sleeping, wake it up */
642 if (PROC_STAT & PROC_SLEEPING(othercore))
643 PROC_CTL(othercore) = PROC_WAKE;
645 /* Done with wake procedure */
646 core_semaphores[othercore].intend_wake = 0;
647 restore_irq(oldlevel);
648 #endif /* ASM/C selection */
650 #endif /* CPU type */
652 #if NUM_CORES > 1
653 /*---------------------------------------------------------------------------
654 * Switches to a stack that always resides in the Rockbox core.
656 * Needed when a thread suicides on a core other than the main CPU since the
657 * stack used when idling is the stack of the last thread to run. This stack
658 * may not reside in the core firmware in which case the core will continue
659 * to use a stack from an unloaded module until another thread runs on it.
660 *---------------------------------------------------------------------------
662 static inline void switch_to_idle_stack(const unsigned int core)
664 asm volatile (
665 "str sp, [%0] \n" /* save original stack pointer on idle stack */
666 "mov sp, %0 \n" /* switch stacks */
667 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
668 (void)core;
671 /*---------------------------------------------------------------------------
672 * Perform core switch steps that need to take place inside switch_thread.
674 * These steps must take place while before changing the processor and after
675 * having entered switch_thread since switch_thread may not do a normal return
676 * because the stack being used for anything the compiler saved will not belong
677 * to the thread's destination core and it may have been recycled for other
678 * purposes by the time a normal context load has taken place. switch_thread
679 * will also clobber anything stashed in the thread's context or stored in the
680 * nonvolatile registers if it is saved there before the call since the
681 * compiler's order of operations cannot be known for certain.
683 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
685 /* Flush our data to ram */
686 flush_icache();
687 /* Stash thread in r4 slot */
688 thread->context.r[0] = (uint32_t)thread;
689 /* Stash restart address in r5 slot */
690 thread->context.r[1] = thread->context.start;
691 /* Save sp in context.sp while still running on old core */
692 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
695 /*---------------------------------------------------------------------------
696 * Machine-specific helper function for switching the processor a thread is
697 * running on. Basically, the thread suicides on the departing core and is
698 * reborn on the destination. Were it not for gcc's ill-behavior regarding
699 * naked functions written in C where it actually clobbers non-volatile
700 * registers before the intended prologue code, this would all be much
701 * simpler. Generic setup is done in switch_core itself.
704 /*---------------------------------------------------------------------------
705 * This actually performs the core switch.
707 static void __attribute__((naked))
708 switch_thread_core(unsigned int core, struct thread_entry *thread)
710 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
711 * Stack access also isn't permitted until restoring the original stack and
712 * context. */
713 asm volatile (
714 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
715 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
716 "ldr r2, [r2, r0, lsl #2] \n"
717 "add r2, r2, %0*4 \n"
718 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
719 "mov sp, r2 \n" /* switch stacks */
720 "adr r2, 1f \n" /* r2 = new core restart address */
721 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
722 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
723 "1: \n"
724 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
725 "mov r1, #0 \n" /* Clear start address */
726 "str r1, [r0, #40] \n"
727 "ldr r0, =invalidate_icache \n" /* Invalidate new core's cache */
728 "mov lr, pc \n"
729 "bx r0 \n"
730 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
731 ".ltorg \n" /* Dump constant pool */
732 : : "i"(IDLE_STACK_WORDS)
734 (void)core; (void)thread;
737 /*---------------------------------------------------------------------------
738 * Do any device-specific inits for the threads and synchronize the kernel
739 * initializations.
740 *---------------------------------------------------------------------------
742 static void core_thread_init(unsigned int core)
744 if (core == CPU)
746 /* Wake up coprocessor and let it initialize kernel and threads */
747 #ifdef CPU_PP502x
748 MBX_MSG_CLR = 0x3f;
749 #endif
750 COP_CTL = PROC_WAKE;
751 /* Sleep until COP has finished */
752 CPU_CTL = PROC_SLEEP;
753 nop; nop; nop;
755 else
757 /* Wake the CPU and return */
758 CPU_CTL = PROC_WAKE;
761 #endif /* NUM_CORES */
763 #elif CONFIG_CPU == S3C2440
765 /*---------------------------------------------------------------------------
766 * Put core in a power-saving state if waking list wasn't repopulated.
767 *---------------------------------------------------------------------------
769 static inline void core_sleep(void)
771 /* FIQ also changes the CLKCON register so FIQ must be disabled
772 when changing it here */
773 asm volatile (
774 "mrs r0, cpsr \n"
775 "orr r2, r0, #0x40 \n" /* Disable FIQ */
776 "bic r0, r0, #0x80 \n" /* Prepare IRQ enable */
777 "msr cpsr_c, r2 \n"
778 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
779 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
780 "orr r2, r2, #4 \n"
781 "str r2, [r1, #0xc] \n"
782 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
783 "mov r2, #0 \n" /* wait for IDLE */
784 "1: \n"
785 "add r2, r2, #1 \n"
786 "cmp r2, #10 \n"
787 "bne 1b \n"
788 "orr r2, r0, #0xc0 \n" /* Disable IRQ, FIQ */
789 "msr cpsr_c, r2 \n"
790 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
791 "bic r2, r2, #4 \n"
792 "str r2, [r1, #0xc] \n"
793 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
794 : : : "r0", "r1", "r2");
796 #elif defined(CPU_TCC77X)
797 static inline void core_sleep(void)
799 #warning TODO: Implement core_sleep
800 enable_irq();
802 #elif defined(CPU_TCC780X)
803 static inline void core_sleep(void)
805 /* Single core only for now. Use the generic ARMv5 wait for IRQ */
806 asm volatile (
807 "mov r0, #0 \n"
808 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
809 : : : "r0"
811 enable_irq();
813 #elif CONFIG_CPU == IMX31L
814 static inline void core_sleep(void)
816 asm volatile (
817 "mov r0, #0 \n"
818 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
819 : : : "r0"
821 enable_irq();
823 #else
824 static inline void core_sleep(void)
826 #warning core_sleep not implemented, battery life will be decreased
827 enable_irq();
829 #endif /* CONFIG_CPU == */
831 #elif defined(CPU_COLDFIRE)
832 /*---------------------------------------------------------------------------
833 * Start the thread running and terminate it if it returns
834 *---------------------------------------------------------------------------
836 void start_thread(void); /* Provide C access to ASM label */
837 static void __attribute__((used)) __start_thread(void)
839 /* a0=macsr, a1=context */
840 asm volatile (
841 "start_thread: \n" /* Start here - no naked attribute */
842 "move.l %a0, %macsr \n" /* Set initial mac status reg */
843 "lea.l 48(%a1), %a1 \n"
844 "move.l (%a1)+, %sp \n" /* Set initial stack */
845 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
846 "clr.l (%a1) \n" /* Mark thread running */
847 "jsr (%a2) \n" /* Call thread function */
849 thread_exit();
852 /* Set EMAC unit to fractional mode with saturation for each new thread,
853 * since that's what'll be the most useful for most things which the dsp
854 * will do. Codecs should still initialize their preferred modes
855 * explicitly. Context pointer is placed in d2 slot and start_thread
856 * pointer in d3 slot. thread function pointer is placed in context.start.
857 * See load_context for what happens when thread is initially going to
858 * run.
860 #define THREAD_STARTUP_INIT(core, thread, function) \
861 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
862 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
863 (thread)->context.d[1] = (uint32_t)start_thread, \
864 (thread)->context.start = (uint32_t)(function); })
866 /*---------------------------------------------------------------------------
867 * Store non-volatile context.
868 *---------------------------------------------------------------------------
870 static inline void store_context(void* addr)
872 asm volatile (
873 "move.l %%macsr,%%d0 \n"
874 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
875 : : "a" (addr) : "d0" /* only! */
879 /*---------------------------------------------------------------------------
880 * Load non-volatile context.
881 *---------------------------------------------------------------------------
883 static inline void load_context(const void* addr)
885 asm volatile (
886 "move.l 52(%0), %%d0 \n" /* Get start address */
887 "beq.b 1f \n" /* NULL -> already running */
888 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
889 "jmp (%%a2) \n" /* Start the thread */
890 "1: \n"
891 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
892 "move.l %%d0, %%macsr \n"
893 : : "a" (addr) : "d0" /* only! */
897 /*---------------------------------------------------------------------------
898 * Put core in a power-saving state if waking list wasn't repopulated.
899 *---------------------------------------------------------------------------
901 static inline void core_sleep(void)
903 /* Supervisor mode, interrupts enabled upon wakeup */
904 asm volatile ("stop #0x2000");
907 #elif CONFIG_CPU == SH7034
908 /*---------------------------------------------------------------------------
909 * Start the thread running and terminate it if it returns
910 *---------------------------------------------------------------------------
912 void start_thread(void); /* Provide C access to ASM label */
913 static void __attribute__((used)) __start_thread(void)
915 /* r8 = context */
916 asm volatile (
917 "_start_thread: \n" /* Start here - no naked attribute */
918 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
919 "mov.l @(28, r8), r15 \n" /* Set initial sp */
920 "mov #0, r1 \n" /* Start the thread */
921 "jsr @r0 \n"
922 "mov.l r1, @(36, r8) \n" /* Clear start address */
924 thread_exit();
927 /* Place context pointer in r8 slot, function pointer in r9 slot, and
928 * start_thread pointer in context_start */
929 #define THREAD_STARTUP_INIT(core, thread, function) \
930 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
931 (thread)->context.r[1] = (uint32_t)(function), \
932 (thread)->context.start = (uint32_t)start_thread; })
934 /*---------------------------------------------------------------------------
935 * Store non-volatile context.
936 *---------------------------------------------------------------------------
938 static inline void store_context(void* addr)
940 asm volatile (
941 "add #36, %0 \n" /* Start at last reg. By the time routine */
942 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
943 "mov.l r15,@-%0 \n"
944 "mov.l r14,@-%0 \n"
945 "mov.l r13,@-%0 \n"
946 "mov.l r12,@-%0 \n"
947 "mov.l r11,@-%0 \n"
948 "mov.l r10,@-%0 \n"
949 "mov.l r9, @-%0 \n"
950 "mov.l r8, @-%0 \n"
951 : : "r" (addr)
955 /*---------------------------------------------------------------------------
956 * Load non-volatile context.
957 *---------------------------------------------------------------------------
959 static inline void load_context(const void* addr)
961 asm volatile (
962 "mov.l @(36, %0), r0 \n" /* Get start address */
963 "tst r0, r0 \n"
964 "bt .running \n" /* NULL -> already running */
965 "jmp @r0 \n" /* r8 = context */
966 ".running: \n"
967 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
968 "mov.l @%0+, r9 \n"
969 "mov.l @%0+, r10 \n"
970 "mov.l @%0+, r11 \n"
971 "mov.l @%0+, r12 \n"
972 "mov.l @%0+, r13 \n"
973 "mov.l @%0+, r14 \n"
974 "mov.l @%0+, r15 \n"
975 "lds.l @%0+, pr \n"
976 : : "r" (addr) : "r0" /* only! */
980 /*---------------------------------------------------------------------------
981 * Put core in a power-saving state.
982 *---------------------------------------------------------------------------
984 static inline void core_sleep(void)
986 asm volatile (
987 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
988 "mov #0, r1 \n" /* Enable interrupts */
989 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
990 "sleep \n" /* Execute standby */
991 : : "z"(&SBYCR-GBR) : "r1");
994 #endif /* CONFIG_CPU == */
997 * End Processor-specific section
998 ***************************************************************************/
1000 #if THREAD_EXTRA_CHECKS
1001 static void thread_panicf(const char *msg, struct thread_entry *thread)
1003 IF_COP( const unsigned int core = thread->core; )
1004 static char name[32];
1005 thread_get_name(name, 32, thread);
1006 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1008 static void thread_stkov(struct thread_entry *thread)
1010 thread_panicf("Stkov", thread);
1012 #define THREAD_PANICF(msg, thread) \
1013 thread_panicf(msg, thread)
1014 #define THREAD_ASSERT(exp, msg, thread) \
1015 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1016 #else
1017 static void thread_stkov(struct thread_entry *thread)
1019 IF_COP( const unsigned int core = thread->core; )
1020 static char name[32];
1021 thread_get_name(name, 32, thread);
1022 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1024 #define THREAD_PANICF(msg, thread)
1025 #define THREAD_ASSERT(exp, msg, thread)
1026 #endif /* THREAD_EXTRA_CHECKS */
1028 /* Thread locking */
1029 #if NUM_CORES > 1
1030 #define LOCK_THREAD(thread) \
1031 ({ corelock_lock(&(thread)->slot_cl); })
1032 #define TRY_LOCK_THREAD(thread) \
1033 ({ corelock_try_lock(&thread->slot_cl); })
1034 #define UNLOCK_THREAD(thread) \
1035 ({ corelock_unlock(&(thread)->slot_cl); })
1036 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1037 ({ unsigned int _core = (thread)->core; \
1038 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1039 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1040 #else
1041 #define LOCK_THREAD(thread) \
1042 ({ })
1043 #define TRY_LOCK_THREAD(thread) \
1044 ({ })
1045 #define UNLOCK_THREAD(thread) \
1046 ({ })
1047 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1048 ({ })
1049 #endif
1051 /* RTR list */
1052 #define RTR_LOCK(core) \
1053 ({ corelock_lock(&cores[core].rtr_cl); })
1054 #define RTR_UNLOCK(core) \
1055 ({ corelock_unlock(&cores[core].rtr_cl); })
1057 #ifdef HAVE_PRIORITY_SCHEDULING
1058 #define rtr_add_entry(core, priority) \
1059 prio_add_entry(&cores[core].rtr, (priority))
1061 #define rtr_subtract_entry(core, priority) \
1062 prio_subtract_entry(&cores[core].rtr, (priority))
1064 #define rtr_move_entry(core, from, to) \
1065 prio_move_entry(&cores[core].rtr, (from), (to))
1066 #else
1067 #define rtr_add_entry(core, priority)
1068 #define rtr_add_entry_inl(core, priority)
1069 #define rtr_subtract_entry(core, priority)
1070 #define rtr_subtract_entry_inl(core, priotity)
1071 #define rtr_move_entry(core, from, to)
1072 #define rtr_move_entry_inl(core, from, to)
1073 #endif
1075 /*---------------------------------------------------------------------------
1076 * Thread list structure - circular:
1077 * +------------------------------+
1078 * | |
1079 * +--+---+<-+---+<-+---+<-+---+<-+
1080 * Head->| T | | T | | T | | T |
1081 * +->+---+->+---+->+---+->+---+--+
1082 * | |
1083 * +------------------------------+
1084 *---------------------------------------------------------------------------
1087 /*---------------------------------------------------------------------------
1088 * Adds a thread to a list of threads using "insert last". Uses the "l"
1089 * links.
1090 *---------------------------------------------------------------------------
1092 static void add_to_list_l(struct thread_entry **list,
1093 struct thread_entry *thread)
1095 struct thread_entry *l = *list;
1097 if (l == NULL)
1099 /* Insert into unoccupied list */
1100 thread->l.prev = thread;
1101 thread->l.next = thread;
1102 *list = thread;
1103 return;
1106 /* Insert last */
1107 thread->l.prev = l->l.prev;
1108 thread->l.next = l;
1109 l->l.prev->l.next = thread;
1110 l->l.prev = thread;
1113 /*---------------------------------------------------------------------------
1114 * Removes a thread from a list of threads. Uses the "l" links.
1115 *---------------------------------------------------------------------------
1117 static void remove_from_list_l(struct thread_entry **list,
1118 struct thread_entry *thread)
1120 struct thread_entry *prev, *next;
1122 next = thread->l.next;
1124 if (thread == next)
1126 /* The only item */
1127 *list = NULL;
1128 return;
1131 if (thread == *list)
1133 /* List becomes next item */
1134 *list = next;
1137 prev = thread->l.prev;
1139 /* Fix links to jump over the removed entry. */
1140 next->l.prev = prev;
1141 prev->l.next = next;
1144 /*---------------------------------------------------------------------------
1145 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1146 * NULL-terminated forward (to ease the far more common forward traversal):
1147 * +------------------------------+
1148 * | |
1149 * +--+---+<-+---+<-+---+<-+---+<-+
1150 * Head->| T | | T | | T | | T |
1151 * +---+->+---+->+---+->+---+-X
1152 *---------------------------------------------------------------------------
1155 /*---------------------------------------------------------------------------
1156 * Add a thread from the core's timout list by linking the pointers in its
1157 * tmo structure.
1158 *---------------------------------------------------------------------------
1160 static void add_to_list_tmo(struct thread_entry *thread)
1162 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1163 THREAD_ASSERT(thread->tmo.prev == NULL,
1164 "add_to_list_tmo->already listed", thread);
1166 thread->tmo.next = NULL;
1168 if (tmo == NULL)
1170 /* Insert into unoccupied list */
1171 thread->tmo.prev = thread;
1172 cores[IF_COP_CORE(thread->core)].timeout = thread;
1173 return;
1176 /* Insert Last */
1177 thread->tmo.prev = tmo->tmo.prev;
1178 tmo->tmo.prev->tmo.next = thread;
1179 tmo->tmo.prev = thread;
1182 /*---------------------------------------------------------------------------
1183 * Remove a thread from the core's timout list by unlinking the pointers in
1184 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1185 * is cancelled.
1186 *---------------------------------------------------------------------------
1188 static void remove_from_list_tmo(struct thread_entry *thread)
1190 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1191 struct thread_entry *prev = thread->tmo.prev;
1192 struct thread_entry *next = thread->tmo.next;
1194 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1196 if (next != NULL)
1197 next->tmo.prev = prev;
1199 if (thread == *list)
1201 /* List becomes next item and empty if next == NULL */
1202 *list = next;
1203 /* Mark as unlisted */
1204 thread->tmo.prev = NULL;
1206 else
1208 if (next == NULL)
1209 (*list)->tmo.prev = prev;
1210 prev->tmo.next = next;
1211 /* Mark as unlisted */
1212 thread->tmo.prev = NULL;
1217 #ifdef HAVE_PRIORITY_SCHEDULING
1218 /*---------------------------------------------------------------------------
1219 * Priority distribution structure (one category for each possible priority):
1221 * +----+----+----+ ... +-----+
1222 * hist: | F0 | F1 | F2 | | F31 |
1223 * +----+----+----+ ... +-----+
1224 * mask: | b0 | b1 | b2 | | b31 |
1225 * +----+----+----+ ... +-----+
1227 * F = count of threads at priority category n (frequency)
1228 * b = bitmask of non-zero priority categories (occupancy)
1230 * / if H[n] != 0 : 1
1231 * b[n] = |
1232 * \ else : 0
1234 *---------------------------------------------------------------------------
1235 * Basic priority inheritance priotocol (PIP):
1237 * Mn = mutex n, Tn = thread n
1239 * A lower priority thread inherits the priority of the highest priority
1240 * thread blocked waiting for it to complete an action (such as release a
1241 * mutex or respond to a message via queue_send):
1243 * 1) T2->M1->T1
1245 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1246 * priority than T1 then T1 inherits the priority of T2.
1248 * 2) T3
1249 * \/
1250 * T2->M1->T1
1252 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1253 * T1 inherits the higher of T2 and T3.
1255 * 3) T3->M2->T2->M1->T1
1257 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1258 * then T1 inherits the priority of T3 through T2.
1260 * Blocking chains can grow arbitrarily complex (though it's best that they
1261 * not form at all very often :) and build-up from these units.
1262 *---------------------------------------------------------------------------
1265 /*---------------------------------------------------------------------------
1266 * Increment frequency at category "priority"
1267 *---------------------------------------------------------------------------
1269 static inline unsigned int prio_add_entry(
1270 struct priority_distribution *pd, int priority)
1272 unsigned int count;
1273 /* Enough size/instruction count difference for ARM makes it worth it to
1274 * use different code (192 bytes for ARM). Only thing better is ASM. */
1275 #ifdef CPU_ARM
1276 count = pd->hist[priority];
1277 if (++count == 1)
1278 pd->mask |= 1 << priority;
1279 pd->hist[priority] = count;
1280 #else /* This one's better for Coldfire */
1281 if ((count = ++pd->hist[priority]) == 1)
1282 pd->mask |= 1 << priority;
1283 #endif
1285 return count;
1288 /*---------------------------------------------------------------------------
1289 * Decrement frequency at category "priority"
1290 *---------------------------------------------------------------------------
1292 static inline unsigned int prio_subtract_entry(
1293 struct priority_distribution *pd, int priority)
1295 unsigned int count;
1297 #ifdef CPU_ARM
1298 count = pd->hist[priority];
1299 if (--count == 0)
1300 pd->mask &= ~(1 << priority);
1301 pd->hist[priority] = count;
1302 #else
1303 if ((count = --pd->hist[priority]) == 0)
1304 pd->mask &= ~(1 << priority);
1305 #endif
1307 return count;
1310 /*---------------------------------------------------------------------------
1311 * Remove from one category and add to another
1312 *---------------------------------------------------------------------------
1314 static inline void prio_move_entry(
1315 struct priority_distribution *pd, int from, int to)
1317 uint32_t mask = pd->mask;
1319 #ifdef CPU_ARM
1320 unsigned int count;
1322 count = pd->hist[from];
1323 if (--count == 0)
1324 mask &= ~(1 << from);
1325 pd->hist[from] = count;
1327 count = pd->hist[to];
1328 if (++count == 1)
1329 mask |= 1 << to;
1330 pd->hist[to] = count;
1331 #else
1332 if (--pd->hist[from] == 0)
1333 mask &= ~(1 << from);
1335 if (++pd->hist[to] == 1)
1336 mask |= 1 << to;
1337 #endif
1339 pd->mask = mask;
1342 /*---------------------------------------------------------------------------
1343 * Change the priority and rtr entry for a running thread
1344 *---------------------------------------------------------------------------
1346 static inline void set_running_thread_priority(
1347 struct thread_entry *thread, int priority)
1349 const unsigned int core = IF_COP_CORE(thread->core);
1350 RTR_LOCK(core);
1351 rtr_move_entry(core, thread->priority, priority);
1352 thread->priority = priority;
1353 RTR_UNLOCK(core);
1356 /*---------------------------------------------------------------------------
1357 * Finds the highest priority thread in a list of threads. If the list is
1358 * empty, the PRIORITY_IDLE is returned.
1360 * It is possible to use the struct priority_distribution within an object
1361 * instead of scanning the remaining threads in the list but as a compromise,
1362 * the resulting per-object memory overhead is saved at a slight speed
1363 * penalty under high contention.
1364 *---------------------------------------------------------------------------
1366 static int find_highest_priority_in_list_l(
1367 struct thread_entry * const thread)
1369 if (thread != NULL)
1371 /* Go though list until the ending up at the initial thread */
1372 int highest_priority = thread->priority;
1373 struct thread_entry *curr = thread;
1377 int priority = curr->priority;
1379 if (priority < highest_priority)
1380 highest_priority = priority;
1382 curr = curr->l.next;
1384 while (curr != thread);
1386 return highest_priority;
1389 return PRIORITY_IDLE;
1392 /*---------------------------------------------------------------------------
1393 * Register priority with blocking system and bubble it down the chain if
1394 * any until we reach the end or something is already equal or higher.
1396 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1397 * targets but that same action also guarantees a circular block anyway and
1398 * those are prevented, right? :-)
1399 *---------------------------------------------------------------------------
1401 static struct thread_entry *
1402 blocker_inherit_priority(struct thread_entry *current)
1404 const int priority = current->priority;
1405 struct blocker *bl = current->blocker;
1406 struct thread_entry * const tstart = current;
1407 struct thread_entry *bl_t = bl->thread;
1409 /* Blocker cannot change since the object protection is held */
1410 LOCK_THREAD(bl_t);
1412 for (;;)
1414 struct thread_entry *next;
1415 int bl_pr = bl->priority;
1417 if (priority >= bl_pr)
1418 break; /* Object priority already high enough */
1420 bl->priority = priority;
1422 /* Add this one */
1423 prio_add_entry(&bl_t->pdist, priority);
1425 if (bl_pr < PRIORITY_IDLE)
1427 /* Not first waiter - subtract old one */
1428 prio_subtract_entry(&bl_t->pdist, bl_pr);
1431 if (priority >= bl_t->priority)
1432 break; /* Thread priority high enough */
1434 if (bl_t->state == STATE_RUNNING)
1436 /* Blocking thread is a running thread therefore there are no
1437 * further blockers. Change the "run queue" on which it
1438 * resides. */
1439 set_running_thread_priority(bl_t, priority);
1440 break;
1443 bl_t->priority = priority;
1445 /* If blocking thread has a blocker, apply transitive inheritance */
1446 bl = bl_t->blocker;
1448 if (bl == NULL)
1449 break; /* End of chain or object doesn't support inheritance */
1451 next = bl->thread;
1453 if (next == tstart)
1454 break; /* Full-circle - deadlock! */
1456 UNLOCK_THREAD(current);
1458 #if NUM_CORES > 1
1459 for (;;)
1461 LOCK_THREAD(next);
1463 /* Blocker could change - retest condition */
1464 if (bl->thread == next)
1465 break;
1467 UNLOCK_THREAD(next);
1468 next = bl->thread;
1470 #endif
1471 current = bl_t;
1472 bl_t = next;
1475 UNLOCK_THREAD(bl_t);
1477 return current;
1480 /*---------------------------------------------------------------------------
1481 * Readjust priorities when waking a thread blocked waiting for another
1482 * in essence "releasing" the thread's effect on the object owner. Can be
1483 * performed from any context.
1484 *---------------------------------------------------------------------------
1486 struct thread_entry *
1487 wakeup_priority_protocol_release(struct thread_entry *thread)
1489 const int priority = thread->priority;
1490 struct blocker *bl = thread->blocker;
1491 struct thread_entry * const tstart = thread;
1492 struct thread_entry *bl_t = bl->thread;
1494 /* Blocker cannot change since object will be locked */
1495 LOCK_THREAD(bl_t);
1497 thread->blocker = NULL; /* Thread not blocked */
1499 for (;;)
1501 struct thread_entry *next;
1502 int bl_pr = bl->priority;
1504 if (priority > bl_pr)
1505 break; /* Object priority higher */
1507 next = *thread->bqp;
1509 if (next == NULL)
1511 /* No more threads in queue */
1512 prio_subtract_entry(&bl_t->pdist, bl_pr);
1513 bl->priority = PRIORITY_IDLE;
1515 else
1517 /* Check list for highest remaining priority */
1518 int queue_pr = find_highest_priority_in_list_l(next);
1520 if (queue_pr == bl_pr)
1521 break; /* Object priority not changing */
1523 /* Change queue priority */
1524 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1525 bl->priority = queue_pr;
1528 if (bl_pr > bl_t->priority)
1529 break; /* thread priority is higher */
1531 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1533 if (bl_pr == bl_t->priority)
1534 break; /* Thread priority not changing */
1536 if (bl_t->state == STATE_RUNNING)
1538 /* No further blockers */
1539 set_running_thread_priority(bl_t, bl_pr);
1540 break;
1543 bl_t->priority = bl_pr;
1545 /* If blocking thread has a blocker, apply transitive inheritance */
1546 bl = bl_t->blocker;
1548 if (bl == NULL)
1549 break; /* End of chain or object doesn't support inheritance */
1551 next = bl->thread;
1553 if (next == tstart)
1554 break; /* Full-circle - deadlock! */
1556 UNLOCK_THREAD(thread);
1558 #if NUM_CORES > 1
1559 for (;;)
1561 LOCK_THREAD(next);
1563 /* Blocker could change - retest condition */
1564 if (bl->thread == next)
1565 break;
1567 UNLOCK_THREAD(next);
1568 next = bl->thread;
1570 #endif
1571 thread = bl_t;
1572 bl_t = next;
1575 UNLOCK_THREAD(bl_t);
1577 #if NUM_CORES > 1
1578 if (thread != tstart)
1580 /* Relock original if it changed */
1581 LOCK_THREAD(tstart);
1583 #endif
1585 return cores[CURRENT_CORE].running;
1588 /*---------------------------------------------------------------------------
1589 * Transfer ownership to a thread waiting for an objects and transfer
1590 * inherited priority boost from other waiters. This algorithm knows that
1591 * blocking chains may only unblock from the very end.
1593 * Only the owning thread itself may call this and so the assumption that
1594 * it is the running thread is made.
1595 *---------------------------------------------------------------------------
1597 struct thread_entry *
1598 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1600 /* Waking thread inherits priority boost from object owner */
1601 struct blocker *bl = thread->blocker;
1602 struct thread_entry *bl_t = bl->thread;
1603 struct thread_entry *next;
1604 int bl_pr;
1606 THREAD_ASSERT(thread_get_current() == bl_t,
1607 "UPPT->wrong thread", thread_get_current());
1609 LOCK_THREAD(bl_t);
1611 bl_pr = bl->priority;
1613 /* Remove the object's boost from the owning thread */
1614 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1615 bl_pr <= bl_t->priority)
1617 /* No more threads at this priority are waiting and the old level is
1618 * at least the thread level */
1619 int priority = find_first_set_bit(bl_t->pdist.mask);
1621 if (priority != bl_t->priority)
1623 /* Adjust this thread's priority */
1624 set_running_thread_priority(bl_t, priority);
1628 next = *thread->bqp;
1630 if (next == NULL)
1632 /* Expected shortcut - no more waiters */
1633 bl_pr = PRIORITY_IDLE;
1635 else
1637 if (thread->priority <= bl_pr)
1639 /* Need to scan threads remaining in queue */
1640 bl_pr = find_highest_priority_in_list_l(next);
1643 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1644 bl_pr < thread->priority)
1646 /* Thread priority must be raised */
1647 thread->priority = bl_pr;
1651 bl->thread = thread; /* This thread pwns */
1652 bl->priority = bl_pr; /* Save highest blocked priority */
1653 thread->blocker = NULL; /* Thread not blocked */
1655 UNLOCK_THREAD(bl_t);
1657 return bl_t;
1660 /*---------------------------------------------------------------------------
1661 * No threads must be blocked waiting for this thread except for it to exit.
1662 * The alternative is more elaborate cleanup and object registration code.
1663 * Check this for risk of silent data corruption when objects with
1664 * inheritable blocking are abandoned by the owner - not precise but may
1665 * catch something.
1666 *---------------------------------------------------------------------------
1668 void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1670 /* Only one bit in the mask should be set with a frequency on 1 which
1671 * represents the thread's own base priority */
1672 uint32_t mask = thread->pdist.mask;
1673 if ((mask & (mask - 1)) != 0 ||
1674 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1676 unsigned char name[32];
1677 thread_get_name(name, 32, thread);
1678 panicf("%s->%s with obj. waiters", function, name);
1681 #endif /* HAVE_PRIORITY_SCHEDULING */
1683 /*---------------------------------------------------------------------------
1684 * Move a thread back to a running state on its core.
1685 *---------------------------------------------------------------------------
1687 static void core_schedule_wakeup(struct thread_entry *thread)
1689 const unsigned int core = IF_COP_CORE(thread->core);
1691 RTR_LOCK(core);
1693 thread->state = STATE_RUNNING;
1695 add_to_list_l(&cores[core].running, thread);
1696 rtr_add_entry(core, thread->priority);
1698 RTR_UNLOCK(core);
1700 #if NUM_CORES > 1
1701 if (core != CURRENT_CORE)
1702 core_wake(core);
1703 #endif
1706 /*---------------------------------------------------------------------------
1707 * Check the core's timeout list when at least one thread is due to wake.
1708 * Filtering for the condition is done before making the call. Resets the
1709 * tick when the next check will occur.
1710 *---------------------------------------------------------------------------
1712 void check_tmo_threads(void)
1714 const unsigned int core = CURRENT_CORE;
1715 const long tick = current_tick; /* snapshot the current tick */
1716 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1717 struct thread_entry *next = cores[core].timeout;
1719 /* If there are no processes waiting for a timeout, just keep the check
1720 tick from falling into the past. */
1722 /* Break the loop once we have walked through the list of all
1723 * sleeping processes or have removed them all. */
1724 while (next != NULL)
1726 /* Check sleeping threads. Allow interrupts between checks. */
1727 enable_irq();
1729 struct thread_entry *curr = next;
1731 next = curr->tmo.next;
1733 /* Lock thread slot against explicit wakeup */
1734 disable_irq();
1735 LOCK_THREAD(curr);
1737 unsigned state = curr->state;
1739 if (state < TIMEOUT_STATE_FIRST)
1741 /* Cleanup threads no longer on a timeout but still on the
1742 * list. */
1743 remove_from_list_tmo(curr);
1745 else if (TIME_BEFORE(tick, curr->tmo_tick))
1747 /* Timeout still pending - this will be the usual case */
1748 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1750 /* Earliest timeout found so far - move the next check up
1751 to its time */
1752 next_tmo_check = curr->tmo_tick;
1755 else
1757 /* Sleep timeout has been reached so bring the thread back to
1758 * life again. */
1759 if (state == STATE_BLOCKED_W_TMO)
1761 #if NUM_CORES > 1
1762 /* Lock the waiting thread's kernel object */
1763 struct corelock *ocl = curr->obj_cl;
1765 if (corelock_try_lock(ocl) == 0)
1767 /* Need to retry in the correct order though the need is
1768 * unlikely */
1769 UNLOCK_THREAD(curr);
1770 corelock_lock(ocl);
1771 LOCK_THREAD(curr);
1773 if (curr->state != STATE_BLOCKED_W_TMO)
1775 /* Thread was woken or removed explicitely while slot
1776 * was unlocked */
1777 corelock_unlock(ocl);
1778 remove_from_list_tmo(curr);
1779 UNLOCK_THREAD(curr);
1780 continue;
1783 #endif /* NUM_CORES */
1785 remove_from_list_l(curr->bqp, curr);
1787 #ifdef HAVE_WAKEUP_EXT_CB
1788 if (curr->wakeup_ext_cb != NULL)
1789 curr->wakeup_ext_cb(curr);
1790 #endif
1792 #ifdef HAVE_PRIORITY_SCHEDULING
1793 if (curr->blocker != NULL)
1794 wakeup_priority_protocol_release(curr);
1795 #endif
1796 corelock_unlock(ocl);
1798 /* else state == STATE_SLEEPING */
1800 remove_from_list_tmo(curr);
1802 RTR_LOCK(core);
1804 curr->state = STATE_RUNNING;
1806 add_to_list_l(&cores[core].running, curr);
1807 rtr_add_entry(core, curr->priority);
1809 RTR_UNLOCK(core);
1812 UNLOCK_THREAD(curr);
1815 cores[core].next_tmo_check = next_tmo_check;
1818 /*---------------------------------------------------------------------------
1819 * Performs operations that must be done before blocking a thread but after
1820 * the state is saved.
1821 *---------------------------------------------------------------------------
1823 #if NUM_CORES > 1
1824 static inline void run_blocking_ops(
1825 unsigned int core, struct thread_entry *thread)
1827 struct thread_blk_ops *ops = &cores[core].blk_ops;
1828 const unsigned flags = ops->flags;
1830 if (flags == TBOP_CLEAR)
1831 return;
1833 switch (flags)
1835 case TBOP_SWITCH_CORE:
1836 core_switch_blk_op(core, thread);
1837 /* Fall-through */
1838 case TBOP_UNLOCK_CORELOCK:
1839 corelock_unlock(ops->cl_p);
1840 break;
1843 ops->flags = TBOP_CLEAR;
1845 #endif /* NUM_CORES > 1 */
1847 #ifdef RB_PROFILE
1848 void profile_thread(void)
1850 profstart(cores[CURRENT_CORE].running - threads);
1852 #endif
1854 /*---------------------------------------------------------------------------
1855 * Prepares a thread to block on an object's list and/or for a specified
1856 * duration - expects object and slot to be appropriately locked if needed
1857 * and interrupts to be masked.
1858 *---------------------------------------------------------------------------
1860 static inline void block_thread_on_l(struct thread_entry *thread,
1861 unsigned state)
1863 /* If inlined, unreachable branches will be pruned with no size penalty
1864 because state is passed as a constant parameter. */
1865 const unsigned int core = IF_COP_CORE(thread->core);
1867 /* Remove the thread from the list of running threads. */
1868 RTR_LOCK(core);
1869 remove_from_list_l(&cores[core].running, thread);
1870 rtr_subtract_entry(core, thread->priority);
1871 RTR_UNLOCK(core);
1873 /* Add a timeout to the block if not infinite */
1874 switch (state)
1876 case STATE_BLOCKED:
1877 case STATE_BLOCKED_W_TMO:
1878 /* Put the thread into a new list of inactive threads. */
1879 add_to_list_l(thread->bqp, thread);
1881 if (state == STATE_BLOCKED)
1882 break;
1884 /* Fall-through */
1885 case STATE_SLEEPING:
1886 /* If this thread times out sooner than any other thread, update
1887 next_tmo_check to its timeout */
1888 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1890 cores[core].next_tmo_check = thread->tmo_tick;
1893 if (thread->tmo.prev == NULL)
1895 add_to_list_tmo(thread);
1897 /* else thread was never removed from list - just keep it there */
1898 break;
1901 /* Remember the the next thread about to block. */
1902 cores[core].block_task = thread;
1904 /* Report new state. */
1905 thread->state = state;
1908 /*---------------------------------------------------------------------------
1909 * Switch thread in round robin fashion for any given priority. Any thread
1910 * that removed itself from the running list first must specify itself in
1911 * the paramter.
1913 * INTERNAL: Intended for use by kernel and not for programs.
1914 *---------------------------------------------------------------------------
1916 void switch_thread(void)
1918 const unsigned int core = CURRENT_CORE;
1919 struct thread_entry *block = cores[core].block_task;
1920 struct thread_entry *thread = cores[core].running;
1922 /* Get context to save - next thread to run is unknown until all wakeups
1923 * are evaluated */
1924 if (block != NULL)
1926 cores[core].block_task = NULL;
1928 #if NUM_CORES > 1
1929 if (thread == block)
1931 /* This was the last thread running and another core woke us before
1932 * reaching here. Force next thread selection to give tmo threads or
1933 * other threads woken before this block a first chance. */
1934 block = NULL;
1936 else
1937 #endif
1939 /* Blocking task is the old one */
1940 thread = block;
1944 #ifdef RB_PROFILE
1945 profile_thread_stopped(thread - threads);
1946 #endif
1948 /* Begin task switching by saving our current context so that we can
1949 * restore the state of the current thread later to the point prior
1950 * to this call. */
1951 store_context(&thread->context);
1953 /* Check if the current thread stack is overflown */
1954 if (thread->stack[0] != DEADBEEF)
1955 thread_stkov(thread);
1957 #if NUM_CORES > 1
1958 /* Run any blocking operations requested before switching/sleeping */
1959 run_blocking_ops(core, thread);
1960 #endif
1962 #ifdef HAVE_PRIORITY_SCHEDULING
1963 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1964 /* Reset the value of thread's skip count */
1965 thread->skip_count = 0;
1966 #endif
1968 for (;;)
1970 /* If there are threads on a timeout and the earliest wakeup is due,
1971 * check the list and wake any threads that need to start running
1972 * again. */
1973 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
1975 check_tmo_threads();
1978 disable_irq();
1979 RTR_LOCK(core);
1981 thread = cores[core].running;
1983 if (thread == NULL)
1985 /* Enter sleep mode to reduce power usage - woken up on interrupt
1986 * or wakeup request from another core - expected to enable
1987 * interrupts. */
1988 RTR_UNLOCK(core);
1989 core_sleep(IF_COP(core));
1991 else
1993 #ifdef HAVE_PRIORITY_SCHEDULING
1994 /* Select the new task based on priorities and the last time a
1995 * process got CPU time relative to the highest priority runnable
1996 * task. */
1997 struct priority_distribution *pd = &cores[core].rtr;
1998 int max = find_first_set_bit(pd->mask);
2000 if (block == NULL)
2002 /* Not switching on a block, tentatively select next thread */
2003 thread = thread->l.next;
2006 for (;;)
2008 int priority = thread->priority;
2009 int diff;
2011 /* This ridiculously simple method of aging seems to work
2012 * suspiciously well. It does tend to reward CPU hogs (under
2013 * yielding) but that's generally not desirable at all. On the
2014 * plus side, it, relatively to other threads, penalizes excess
2015 * yielding which is good if some high priority thread is
2016 * performing no useful work such as polling for a device to be
2017 * ready. Of course, aging is only employed when higher and lower
2018 * priority threads are runnable. The highest priority runnable
2019 * thread(s) are never skipped. */
2020 if (priority <= max ||
2021 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2022 (diff = priority - max, ++thread->skip_count > diff*diff))
2024 cores[core].running = thread;
2025 break;
2028 thread = thread->l.next;
2030 #else
2031 /* Without priority use a simple FCFS algorithm */
2032 if (block == NULL)
2034 /* Not switching on a block, select next thread */
2035 thread = thread->l.next;
2036 cores[core].running = thread;
2038 #endif /* HAVE_PRIORITY_SCHEDULING */
2040 RTR_UNLOCK(core);
2041 enable_irq();
2042 break;
2046 /* And finally give control to the next thread. */
2047 load_context(&thread->context);
2049 #ifdef RB_PROFILE
2050 profile_thread_started(thread - threads);
2051 #endif
2054 /*---------------------------------------------------------------------------
2055 * Sleeps a thread for at least a specified number of ticks with zero being
2056 * a wait until the next tick.
2058 * INTERNAL: Intended for use by kernel and not for programs.
2059 *---------------------------------------------------------------------------
2061 void sleep_thread(int ticks)
2063 struct thread_entry *current = cores[CURRENT_CORE].running;
2065 LOCK_THREAD(current);
2067 /* Set our timeout, remove from run list and join timeout list. */
2068 current->tmo_tick = current_tick + ticks + 1;
2069 block_thread_on_l(current, STATE_SLEEPING);
2071 UNLOCK_THREAD(current);
2074 /*---------------------------------------------------------------------------
2075 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2077 * INTERNAL: Intended for use by kernel objects and not for programs.
2078 *---------------------------------------------------------------------------
2080 void block_thread(struct thread_entry *current)
2082 /* Set the state to blocked and take us off of the run queue until we
2083 * are explicitly woken */
2084 LOCK_THREAD(current);
2086 /* Set the list for explicit wakeup */
2087 block_thread_on_l(current, STATE_BLOCKED);
2089 #ifdef HAVE_PRIORITY_SCHEDULING
2090 if (current->blocker != NULL)
2092 /* Object supports PIP */
2093 current = blocker_inherit_priority(current);
2095 #endif
2097 UNLOCK_THREAD(current);
2100 /*---------------------------------------------------------------------------
2101 * Block a thread on a blocking queue for a specified time interval or until
2102 * explicitly woken - whichever happens first.
2104 * INTERNAL: Intended for use by kernel objects and not for programs.
2105 *---------------------------------------------------------------------------
2107 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2109 /* Get the entry for the current running thread. */
2110 LOCK_THREAD(current);
2112 /* Set the state to blocked with the specified timeout */
2113 current->tmo_tick = current_tick + timeout;
2115 /* Set the list for explicit wakeup */
2116 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2118 #ifdef HAVE_PRIORITY_SCHEDULING
2119 if (current->blocker != NULL)
2121 /* Object supports PIP */
2122 current = blocker_inherit_priority(current);
2124 #endif
2126 UNLOCK_THREAD(current);
2129 /*---------------------------------------------------------------------------
2130 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2131 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2133 * This code should be considered a critical section by the caller meaning
2134 * that the object's corelock should be held.
2136 * INTERNAL: Intended for use by kernel objects and not for programs.
2137 *---------------------------------------------------------------------------
2139 unsigned int wakeup_thread(struct thread_entry **list)
2141 struct thread_entry *thread = *list;
2142 unsigned int result = THREAD_NONE;
2144 /* Check if there is a blocked thread at all. */
2145 if (thread == NULL)
2146 return result;
2148 LOCK_THREAD(thread);
2150 /* Determine thread's current state. */
2151 switch (thread->state)
2153 case STATE_BLOCKED:
2154 case STATE_BLOCKED_W_TMO:
2155 remove_from_list_l(list, thread);
2157 result = THREAD_OK;
2159 #ifdef HAVE_PRIORITY_SCHEDULING
2160 struct thread_entry *current;
2161 struct blocker *bl = thread->blocker;
2163 if (bl == NULL)
2165 /* No inheritance - just boost the thread by aging */
2166 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2167 thread->skip_count = thread->priority;
2168 current = cores[CURRENT_CORE].running;
2170 else
2172 /* Call the specified unblocking PIP */
2173 current = bl->wakeup_protocol(thread);
2176 if (current != NULL && thread->priority < current->priority
2177 IF_COP( && thread->core == current->core ))
2179 /* Woken thread is higher priority and exists on the same CPU core;
2180 * recommend a task switch. Knowing if this is an interrupt call
2181 * would be helpful here. */
2182 result |= THREAD_SWITCH;
2184 #endif /* HAVE_PRIORITY_SCHEDULING */
2186 core_schedule_wakeup(thread);
2187 break;
2189 /* Nothing to do. State is not blocked. */
2190 #if THREAD_EXTRA_CHECKS
2191 default:
2192 THREAD_PANICF("wakeup_thread->block invalid", thread);
2193 case STATE_RUNNING:
2194 case STATE_KILLED:
2195 break;
2196 #endif
2199 UNLOCK_THREAD(thread);
2200 return result;
2203 /*---------------------------------------------------------------------------
2204 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2205 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2206 * the queue must be locked first.
2208 * INTERNAL: Intended for use by kernel objects and not for programs.
2209 *---------------------------------------------------------------------------
2211 unsigned int thread_queue_wake(struct thread_entry **list)
2213 unsigned result = THREAD_NONE;
2215 for (;;)
2217 unsigned int rc = wakeup_thread(list);
2219 if (rc == THREAD_NONE)
2220 break; /* No more threads */
2222 result |= rc;
2225 return result;
2228 /*---------------------------------------------------------------------------
2229 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2230 * will be locked on multicore.
2231 *---------------------------------------------------------------------------
2233 static struct thread_entry * find_empty_thread_slot(void)
2235 /* Any slot could be on an interrupt-accessible list */
2236 IF_COP( int oldlevel = disable_irq_save(); )
2237 struct thread_entry *thread = NULL;
2238 int n;
2240 for (n = 0; n < MAXTHREADS; n++)
2242 /* Obtain current slot state - lock it on multicore */
2243 struct thread_entry *t = &threads[n];
2244 LOCK_THREAD(t);
2246 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2248 /* Slot is empty - leave it locked and caller will unlock */
2249 thread = t;
2250 break;
2253 /* Finished examining slot - no longer busy - unlock on multicore */
2254 UNLOCK_THREAD(t);
2257 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2258 not accesible to them yet */
2259 return thread;
2263 /*---------------------------------------------------------------------------
2264 * Place the current core in idle mode - woken up on interrupt or wake
2265 * request from another core.
2266 *---------------------------------------------------------------------------
2268 void core_idle(void)
2270 IF_COP( const unsigned int core = CURRENT_CORE; )
2271 disable_irq();
2272 core_sleep(IF_COP(core));
2275 /*---------------------------------------------------------------------------
2276 * Create a thread. If using a dual core architecture, specify which core to
2277 * start the thread on.
2279 * Return ID if context area could be allocated, else NULL.
2280 *---------------------------------------------------------------------------
2282 struct thread_entry*
2283 create_thread(void (*function)(void), void* stack, size_t stack_size,
2284 unsigned flags, const char *name
2285 IF_PRIO(, int priority)
2286 IF_COP(, unsigned int core))
2288 unsigned int i;
2289 unsigned int stack_words;
2290 uintptr_t stackptr, stackend;
2291 struct thread_entry *thread;
2292 unsigned state;
2293 int oldlevel;
2295 thread = find_empty_thread_slot();
2296 if (thread == NULL)
2298 return NULL;
2301 oldlevel = disable_irq_save();
2303 /* Munge the stack to make it easy to spot stack overflows */
2304 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2305 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2306 stack_size = stackend - stackptr;
2307 stack_words = stack_size / sizeof (uintptr_t);
2309 for (i = 0; i < stack_words; i++)
2311 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2314 /* Store interesting information */
2315 thread->name = name;
2316 thread->stack = (uintptr_t *)stackptr;
2317 thread->stack_size = stack_size;
2318 thread->queue = NULL;
2319 #ifdef HAVE_WAKEUP_EXT_CB
2320 thread->wakeup_ext_cb = NULL;
2321 #endif
2322 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2323 thread->cpu_boost = 0;
2324 #endif
2325 #ifdef HAVE_PRIORITY_SCHEDULING
2326 memset(&thread->pdist, 0, sizeof(thread->pdist));
2327 thread->blocker = NULL;
2328 thread->base_priority = priority;
2329 thread->priority = priority;
2330 thread->skip_count = priority;
2331 prio_add_entry(&thread->pdist, priority);
2332 #endif
2334 #if NUM_CORES > 1
2335 thread->core = core;
2337 /* Writeback stack munging or anything else before starting */
2338 if (core != CURRENT_CORE)
2340 flush_icache();
2342 #endif
2344 /* Thread is not on any timeout list but be a bit paranoid */
2345 thread->tmo.prev = NULL;
2347 state = (flags & CREATE_THREAD_FROZEN) ?
2348 STATE_FROZEN : STATE_RUNNING;
2350 thread->context.sp = (typeof (thread->context.sp))stackend;
2352 /* Load the thread's context structure with needed startup information */
2353 THREAD_STARTUP_INIT(core, thread, function);
2355 thread->state = state;
2357 if (state == STATE_RUNNING)
2358 core_schedule_wakeup(thread);
2360 UNLOCK_THREAD(thread);
2362 restore_irq(oldlevel);
2364 return thread;
2367 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2368 /*---------------------------------------------------------------------------
2369 * Change the boost state of a thread boosting or unboosting the CPU
2370 * as required.
2371 *---------------------------------------------------------------------------
2373 static inline void boost_thread(struct thread_entry *thread, bool boost)
2375 if ((thread->cpu_boost != 0) != boost)
2377 thread->cpu_boost = boost;
2378 cpu_boost(boost);
2382 void trigger_cpu_boost(void)
2384 struct thread_entry *current = cores[CURRENT_CORE].running;
2385 boost_thread(current, true);
2388 void cancel_cpu_boost(void)
2390 struct thread_entry *current = cores[CURRENT_CORE].running;
2391 boost_thread(current, false);
2393 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2395 /*---------------------------------------------------------------------------
2396 * Block the current thread until another thread terminates. A thread may
2397 * wait on itself to terminate which prevents it from running again and it
2398 * will need to be killed externally.
2399 * Parameter is the ID as returned from create_thread().
2400 *---------------------------------------------------------------------------
2402 void thread_wait(struct thread_entry *thread)
2404 struct thread_entry *current = cores[CURRENT_CORE].running;
2406 if (thread == NULL)
2407 thread = current;
2409 /* Lock thread-as-waitable-object lock */
2410 corelock_lock(&thread->waiter_cl);
2412 /* Be sure it hasn't been killed yet */
2413 if (thread->state != STATE_KILLED)
2415 IF_COP( current->obj_cl = &thread->waiter_cl; )
2416 current->bqp = &thread->queue;
2418 disable_irq();
2419 block_thread(current);
2421 corelock_unlock(&thread->waiter_cl);
2423 switch_thread();
2424 return;
2427 corelock_unlock(&thread->waiter_cl);
2430 /*---------------------------------------------------------------------------
2431 * Exit the current thread. The Right Way to Do Things (TM).
2432 *---------------------------------------------------------------------------
2434 void thread_exit(void)
2436 const unsigned int core = CURRENT_CORE;
2437 struct thread_entry *current = cores[core].running;
2439 /* Cancel CPU boost if any */
2440 cancel_cpu_boost();
2442 disable_irq();
2444 corelock_lock(&current->waiter_cl);
2445 LOCK_THREAD(current);
2447 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2448 if (current->name == THREAD_DESTRUCT)
2450 /* Thread being killed - become a waiter */
2451 UNLOCK_THREAD(current);
2452 corelock_unlock(&current->waiter_cl);
2453 thread_wait(current);
2454 THREAD_PANICF("thread_exit->WK:*R", current);
2456 #endif
2458 #ifdef HAVE_PRIORITY_SCHEDULING
2459 check_for_obj_waiters("thread_exit", current);
2460 #endif
2462 if (current->tmo.prev != NULL)
2464 /* Cancel pending timeout list removal */
2465 remove_from_list_tmo(current);
2468 /* Switch tasks and never return */
2469 block_thread_on_l(current, STATE_KILLED);
2471 #if NUM_CORES > 1
2472 /* Switch to the idle stack if not on the main core (where "main"
2473 * runs) - we can hope gcc doesn't need the old stack beyond this
2474 * point. */
2475 if (core != CPU)
2477 switch_to_idle_stack(core);
2480 flush_icache();
2481 #endif
2482 current->name = NULL;
2484 /* Signal this thread */
2485 thread_queue_wake(&current->queue);
2486 corelock_unlock(&current->waiter_cl);
2487 /* Slot must be unusable until thread is really gone */
2488 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2489 switch_thread();
2490 /* This should never and must never be reached - if it is, the
2491 * state is corrupted */
2492 THREAD_PANICF("thread_exit->K:*R", current);
2495 #ifdef ALLOW_REMOVE_THREAD
2496 /*---------------------------------------------------------------------------
2497 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2498 * normal programs.
2500 * Parameter is the ID as returned from create_thread().
2502 * Use with care on threads that are not under careful control as this may
2503 * leave various objects in an undefined state.
2504 *---------------------------------------------------------------------------
2506 void remove_thread(struct thread_entry *thread)
2508 #if NUM_CORES > 1
2509 /* core is not constant here because of core switching */
2510 unsigned int core = CURRENT_CORE;
2511 unsigned int old_core = NUM_CORES;
2512 struct corelock *ocl = NULL;
2513 #else
2514 const unsigned int core = CURRENT_CORE;
2515 #endif
2516 struct thread_entry *current = cores[core].running;
2518 unsigned state;
2519 int oldlevel;
2521 if (thread == NULL)
2522 thread = current;
2524 if (thread == current)
2525 thread_exit(); /* Current thread - do normal exit */
2527 oldlevel = disable_irq_save();
2529 corelock_lock(&thread->waiter_cl);
2530 LOCK_THREAD(thread);
2532 state = thread->state;
2534 if (state == STATE_KILLED)
2536 goto thread_killed;
2539 #if NUM_CORES > 1
2540 if (thread->name == THREAD_DESTRUCT)
2542 /* Thread being killed - become a waiter */
2543 UNLOCK_THREAD(thread);
2544 corelock_unlock(&thread->waiter_cl);
2545 restore_irq(oldlevel);
2546 thread_wait(thread);
2547 return;
2550 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2552 #ifdef HAVE_PRIORITY_SCHEDULING
2553 check_for_obj_waiters("remove_thread", thread);
2554 #endif
2556 if (thread->core != core)
2558 /* Switch cores and safely extract the thread there */
2559 /* Slot HAS to be unlocked or a deadlock could occur which means other
2560 * threads have to be guided into becoming thread waiters if they
2561 * attempt to remove it. */
2562 unsigned int new_core = thread->core;
2564 corelock_unlock(&thread->waiter_cl);
2566 UNLOCK_THREAD(thread);
2567 restore_irq(oldlevel);
2569 old_core = switch_core(new_core);
2571 oldlevel = disable_irq_save();
2573 corelock_lock(&thread->waiter_cl);
2574 LOCK_THREAD(thread);
2576 state = thread->state;
2577 core = new_core;
2578 /* Perform the extraction and switch ourselves back to the original
2579 processor */
2581 #endif /* NUM_CORES > 1 */
2583 if (thread->tmo.prev != NULL)
2585 /* Clean thread off the timeout list if a timeout check hasn't
2586 * run yet */
2587 remove_from_list_tmo(thread);
2590 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2591 /* Cancel CPU boost if any */
2592 boost_thread(thread, false);
2593 #endif
2595 IF_COP( retry_state: )
2597 switch (state)
2599 case STATE_RUNNING:
2600 RTR_LOCK(core);
2601 /* Remove thread from ready to run tasks */
2602 remove_from_list_l(&cores[core].running, thread);
2603 rtr_subtract_entry(core, thread->priority);
2604 RTR_UNLOCK(core);
2605 break;
2606 case STATE_BLOCKED:
2607 case STATE_BLOCKED_W_TMO:
2608 /* Remove thread from the queue it's blocked on - including its
2609 * own if waiting there */
2610 #if NUM_CORES > 1
2611 if (&thread->waiter_cl != thread->obj_cl)
2613 ocl = thread->obj_cl;
2615 if (corelock_try_lock(ocl) == 0)
2617 UNLOCK_THREAD(thread);
2618 corelock_lock(ocl);
2619 LOCK_THREAD(thread);
2621 if (thread->state != state)
2623 /* Something woke the thread */
2624 state = thread->state;
2625 corelock_unlock(ocl);
2626 goto retry_state;
2630 #endif
2631 remove_from_list_l(thread->bqp, thread);
2633 #ifdef HAVE_WAKEUP_EXT_CB
2634 if (thread->wakeup_ext_cb != NULL)
2635 thread->wakeup_ext_cb(thread);
2636 #endif
2638 #ifdef HAVE_PRIORITY_SCHEDULING
2639 if (thread->blocker != NULL)
2641 /* Remove thread's priority influence from its chain */
2642 wakeup_priority_protocol_release(thread);
2644 #endif
2646 #if NUM_CORES > 1
2647 if (ocl != NULL)
2648 corelock_unlock(ocl);
2649 #endif
2650 break;
2651 /* Otherwise thread is frozen and hasn't run yet */
2654 thread->state = STATE_KILLED;
2656 /* If thread was waiting on itself, it will have been removed above.
2657 * The wrong order would result in waking the thread first and deadlocking
2658 * since the slot is already locked. */
2659 thread_queue_wake(&thread->queue);
2661 thread->name = NULL;
2663 thread_killed: /* Thread was already killed */
2664 /* Removal complete - safe to unlock and reenable interrupts */
2665 corelock_unlock(&thread->waiter_cl);
2666 UNLOCK_THREAD(thread);
2667 restore_irq(oldlevel);
2669 #if NUM_CORES > 1
2670 if (old_core < NUM_CORES)
2672 /* Did a removal on another processor's thread - switch back to
2673 native core */
2674 switch_core(old_core);
2676 #endif
2678 #endif /* ALLOW_REMOVE_THREAD */
2680 #ifdef HAVE_PRIORITY_SCHEDULING
2681 /*---------------------------------------------------------------------------
2682 * Sets the thread's relative base priority for the core it runs on. Any
2683 * needed inheritance changes also may happen.
2684 *---------------------------------------------------------------------------
2686 int thread_set_priority(struct thread_entry *thread, int priority)
2688 int old_base_priority = -1;
2690 /* A little safety measure */
2691 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2692 return -1;
2694 if (thread == NULL)
2695 thread = cores[CURRENT_CORE].running;
2697 /* Thread could be on any list and therefore on an interrupt accessible
2698 one - disable interrupts */
2699 int oldlevel = disable_irq_save();
2701 LOCK_THREAD(thread);
2703 /* Make sure it's not killed */
2704 if (thread->state != STATE_KILLED)
2706 int old_priority = thread->priority;
2708 old_base_priority = thread->base_priority;
2709 thread->base_priority = priority;
2711 prio_move_entry(&thread->pdist, old_base_priority, priority);
2712 priority = find_first_set_bit(thread->pdist.mask);
2714 if (old_priority == priority)
2716 /* No priority change - do nothing */
2718 else if (thread->state == STATE_RUNNING)
2720 /* This thread is running - change location on the run
2721 * queue. No transitive inheritance needed. */
2722 set_running_thread_priority(thread, priority);
2724 else
2726 thread->priority = priority;
2728 if (thread->blocker != NULL)
2730 /* Bubble new priority down the chain */
2731 struct blocker *bl = thread->blocker; /* Blocker struct */
2732 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2733 struct thread_entry * const tstart = thread; /* Initial thread */
2734 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2736 for (;;)
2738 struct thread_entry *next; /* Next thread to check */
2739 int bl_pr; /* Highest blocked thread */
2740 int queue_pr; /* New highest blocked thread */
2741 #if NUM_CORES > 1
2742 /* Owner can change but thread cannot be dislodged - thread
2743 * may not be the first in the queue which allows other
2744 * threads ahead in the list to be given ownership during the
2745 * operation. If thread is next then the waker will have to
2746 * wait for us and the owner of the object will remain fixed.
2747 * If we successfully grab the owner -- which at some point
2748 * is guaranteed -- then the queue remains fixed until we
2749 * pass by. */
2750 for (;;)
2752 LOCK_THREAD(bl_t);
2754 /* Double-check the owner - retry if it changed */
2755 if (bl->thread == bl_t)
2756 break;
2758 UNLOCK_THREAD(bl_t);
2759 bl_t = bl->thread;
2761 #endif
2762 bl_pr = bl->priority;
2764 if (highest > bl_pr)
2765 break; /* Object priority won't change */
2767 /* This will include the thread being set */
2768 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2770 if (queue_pr == bl_pr)
2771 break; /* Object priority not changing */
2773 /* Update thread boost for this object */
2774 bl->priority = queue_pr;
2775 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2776 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2778 if (bl_t->priority == bl_pr)
2779 break; /* Blocking thread priority not changing */
2781 if (bl_t->state == STATE_RUNNING)
2783 /* Thread not blocked - we're done */
2784 set_running_thread_priority(bl_t, bl_pr);
2785 break;
2788 bl_t->priority = bl_pr;
2789 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2791 if (bl == NULL)
2792 break; /* End of chain */
2794 next = bl->thread;
2796 if (next == tstart)
2797 break; /* Full-circle */
2799 UNLOCK_THREAD(thread);
2801 thread = bl_t;
2802 bl_t = next;
2803 } /* for (;;) */
2805 UNLOCK_THREAD(bl_t);
2810 UNLOCK_THREAD(thread);
2812 restore_irq(oldlevel);
2814 return old_base_priority;
2817 /*---------------------------------------------------------------------------
2818 * Returns the current base priority for a thread.
2819 *---------------------------------------------------------------------------
2821 int thread_get_priority(struct thread_entry *thread)
2823 /* Simple, quick probe. */
2824 if (thread == NULL)
2825 thread = cores[CURRENT_CORE].running;
2827 return thread->base_priority;
2829 #endif /* HAVE_PRIORITY_SCHEDULING */
2831 /*---------------------------------------------------------------------------
2832 * Starts a frozen thread - similar semantics to wakeup_thread except that
2833 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2834 * virtue of the slot having a state of STATE_FROZEN.
2835 *---------------------------------------------------------------------------
2837 void thread_thaw(struct thread_entry *thread)
2839 int oldlevel = disable_irq_save();
2840 LOCK_THREAD(thread);
2842 if (thread->state == STATE_FROZEN)
2843 core_schedule_wakeup(thread);
2845 UNLOCK_THREAD(thread);
2846 restore_irq(oldlevel);
2849 /*---------------------------------------------------------------------------
2850 * Return the ID of the currently executing thread.
2851 *---------------------------------------------------------------------------
2853 struct thread_entry * thread_get_current(void)
2855 return cores[CURRENT_CORE].running;
2858 #if NUM_CORES > 1
2859 /*---------------------------------------------------------------------------
2860 * Switch the processor that the currently executing thread runs on.
2861 *---------------------------------------------------------------------------
2863 unsigned int switch_core(unsigned int new_core)
2865 const unsigned int core = CURRENT_CORE;
2866 struct thread_entry *current = cores[core].running;
2868 if (core == new_core)
2870 /* No change - just return same core */
2871 return core;
2874 int oldlevel = disable_irq_save();
2875 LOCK_THREAD(current);
2877 if (current->name == THREAD_DESTRUCT)
2879 /* Thread being killed - deactivate and let process complete */
2880 UNLOCK_THREAD(current);
2881 restore_irq(oldlevel);
2882 thread_wait(current);
2883 /* Should never be reached */
2884 THREAD_PANICF("switch_core->D:*R", current);
2887 /* Get us off the running list for the current core */
2888 RTR_LOCK(core);
2889 remove_from_list_l(&cores[core].running, current);
2890 rtr_subtract_entry(core, current->priority);
2891 RTR_UNLOCK(core);
2893 /* Stash return value (old core) in a safe place */
2894 current->retval = core;
2896 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2897 * the other core will likely attempt a removal from the wrong list! */
2898 if (current->tmo.prev != NULL)
2900 remove_from_list_tmo(current);
2903 /* Change the core number for this thread slot */
2904 current->core = new_core;
2906 /* Do not use core_schedule_wakeup here since this will result in
2907 * the thread starting to run on the other core before being finished on
2908 * this one. Delay the list unlock to keep the other core stuck
2909 * until this thread is ready. */
2910 RTR_LOCK(new_core);
2912 rtr_add_entry(new_core, current->priority);
2913 add_to_list_l(&cores[new_core].running, current);
2915 /* Make a callback into device-specific code, unlock the wakeup list so
2916 * that execution may resume on the new core, unlock our slot and finally
2917 * restore the interrupt level */
2918 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
2919 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
2920 cores[core].block_task = current;
2922 UNLOCK_THREAD(current);
2924 /* Alert other core to activity */
2925 core_wake(new_core);
2927 /* Do the stack switching, cache_maintenence and switch_thread call -
2928 requires native code */
2929 switch_thread_core(core, current);
2931 /* Finally return the old core to caller */
2932 return current->retval;
2934 #endif /* NUM_CORES > 1 */
2936 /*---------------------------------------------------------------------------
2937 * Initialize threading API. This assumes interrupts are not yet enabled. On
2938 * multicore setups, no core is allowed to proceed until create_thread calls
2939 * are safe to perform.
2940 *---------------------------------------------------------------------------
2942 void init_threads(void)
2944 const unsigned int core = CURRENT_CORE;
2945 struct thread_entry *thread;
2947 /* CPU will initialize first and then sleep */
2948 thread = find_empty_thread_slot();
2950 if (thread == NULL)
2952 /* WTF? There really must be a slot available at this stage.
2953 * This can fail if, for example, .bss isn't zero'ed out by the loader
2954 * or threads is in the wrong section. */
2955 THREAD_PANICF("init_threads->no slot", NULL);
2958 /* Initialize initially non-zero members of core */
2959 cores[core].next_tmo_check = current_tick; /* Something not in the past */
2961 /* Initialize initially non-zero members of slot */
2962 UNLOCK_THREAD(thread); /* No sync worries yet */
2963 thread->name = main_thread_name;
2964 thread->state = STATE_RUNNING;
2965 IF_COP( thread->core = core; )
2966 #ifdef HAVE_PRIORITY_SCHEDULING
2967 corelock_init(&cores[core].rtr_cl);
2968 thread->base_priority = PRIORITY_USER_INTERFACE;
2969 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
2970 thread->priority = PRIORITY_USER_INTERFACE;
2971 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
2972 #endif
2973 corelock_init(&thread->waiter_cl);
2974 corelock_init(&thread->slot_cl);
2976 add_to_list_l(&cores[core].running, thread);
2978 if (core == CPU)
2980 thread->stack = stackbegin;
2981 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
2982 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2983 /* Wait for other processors to finish their inits since create_thread
2984 * isn't safe to call until the kernel inits are done. The first
2985 * threads created in the system must of course be created by CPU. */
2986 core_thread_init(CPU);
2988 else
2990 /* Initial stack is the idle stack */
2991 thread->stack = idle_stacks[core];
2992 thread->stack_size = IDLE_STACK_SIZE;
2993 /* After last processor completes, it should signal all others to
2994 * proceed or may signal the next and call thread_exit(). The last one
2995 * to finish will signal CPU. */
2996 core_thread_init(core);
2997 /* Other cores do not have a main thread - go idle inside switch_thread
2998 * until a thread can run on the core. */
2999 thread_exit();
3000 #endif /* NUM_CORES */
3004 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3005 #if NUM_CORES == 1
3006 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3007 #else
3008 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3009 #endif
3011 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3012 unsigned int i;
3013 int usage = 0;
3015 for (i = 0; i < stack_words; i++)
3017 if (stackptr[i] != DEADBEEF)
3019 usage = ((stack_words - i) * 100) / stack_words;
3020 break;
3024 return usage;
3027 /*---------------------------------------------------------------------------
3028 * Returns the maximum percentage of stack a thread ever used while running.
3029 * NOTE: Some large buffer allocations that don't use enough the buffer to
3030 * overwrite stackptr[0] will not be seen.
3031 *---------------------------------------------------------------------------
3033 int thread_stack_usage(const struct thread_entry *thread)
3035 return stack_usage(thread->stack, thread->stack_size);
3038 #if NUM_CORES > 1
3039 /*---------------------------------------------------------------------------
3040 * Returns the maximum percentage of the core's idle stack ever used during
3041 * runtime.
3042 *---------------------------------------------------------------------------
3044 int idle_stack_usage(unsigned int core)
3046 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3048 #endif
3050 /*---------------------------------------------------------------------------
3051 * Fills in the buffer with the specified thread's name. If the name is NULL,
3052 * empty, or the thread is in destruct state a formatted ID is written
3053 * instead.
3054 *---------------------------------------------------------------------------
3056 void thread_get_name(char *buffer, int size,
3057 struct thread_entry *thread)
3059 if (size <= 0)
3060 return;
3062 *buffer = '\0';
3064 if (thread)
3066 /* Display thread name if one or ID if none */
3067 const char *name = thread->name;
3068 const char *fmt = "%s";
3069 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3071 name = (const char *)thread;
3072 fmt = "%08lX";
3074 snprintf(buffer, size, fmt, name);