Onda's: add touchscreen boot menu for targets without/not much physical buttons ...
[kugel-rb.git] / firmware / thread.c
blob3754f55867470e48e5a8898156da30adf1d8787e
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "config.h"
22 #include <stdbool.h>
23 #include "thread.h"
24 #include "panic.h"
25 #include "sprintf.h"
26 #include "system.h"
27 #include "kernel.h"
28 #include "cpu.h"
29 #include "string.h"
30 #ifdef RB_PROFILE
31 #include <profile.h>
32 #endif
33 /****************************************************************************
34 * ATTENTION!! *
35 * See notes below on implementing processor-specific portions! *
36 ***************************************************************************/
38 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
39 #ifdef DEBUG
40 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
41 #else
42 #define THREAD_EXTRA_CHECKS 0
43 #endif
45 /**
46 * General locking order to guarantee progress. Order must be observed but
47 * all stages are not nescessarily obligatory. Going from 1) to 3) is
48 * perfectly legal.
50 * 1) IRQ
51 * This is first because of the likelyhood of having an interrupt occur that
52 * also accesses one of the objects farther down the list. Any non-blocking
53 * synchronization done may already have a lock on something during normal
54 * execution and if an interrupt handler running on the same processor as
55 * the one that has the resource locked were to attempt to access the
56 * resource, the interrupt handler would wait forever waiting for an unlock
57 * that will never happen. There is no danger if the interrupt occurs on
58 * a different processor because the one that has the lock will eventually
59 * unlock and the other processor's handler may proceed at that time. Not
60 * nescessary when the resource in question is definitely not available to
61 * interrupt handlers.
63 * 2) Kernel Object
64 * 1) May be needed beforehand if the kernel object allows dual-use such as
65 * event queues. The kernel object must have a scheme to protect itself from
66 * access by another processor and is responsible for serializing the calls
67 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
68 * other. Objects' queues are also protected here.
70 * 3) Thread Slot
71 * This locks access to the thread's slot such that its state cannot be
72 * altered by another processor when a state change is in progress such as
73 * when it is in the process of going on a blocked list. An attempt to wake
74 * a thread while it is still blocking will likely desync its state with
75 * the other resources used for that state.
77 * 4) Core Lists
78 * These lists are specific to a particular processor core and are accessible
79 * by all processor cores and interrupt handlers. The running (rtr) list is
80 * the prime example where a thread may be added by any means.
83 /*---------------------------------------------------------------------------
84 * Processor specific: core_sleep/core_wake/misc. notes
86 * ARM notes:
87 * FIQ is not dealt with by the scheduler code and is simply restored if it
88 * must by masked for some reason - because threading modifies a register
89 * that FIQ may also modify and there's no way to accomplish it atomically.
90 * s3c2440 is such a case.
92 * Audio interrupts are generally treated at a higher priority than others
93 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
94 * are not in general safe. Special cases may be constructed on a per-
95 * source basis and blocking operations are not available.
97 * core_sleep procedure to implement for any CPU to ensure an asychronous
98 * wakup never results in requiring a wait until the next tick (up to
99 * 10000uS!). May require assembly and careful instruction ordering.
101 * 1) On multicore, stay awake if directed to do so by another. If so, goto
102 * step 4.
103 * 2) If processor requires, atomically reenable interrupts and perform step
104 * 3.
105 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
106 * on Coldfire) goto step 5.
107 * 4) Enable interrupts.
108 * 5) Exit procedure.
110 * core_wake and multprocessor notes for sleep/wake coordination:
111 * If possible, to wake up another processor, the forcing of an interrupt on
112 * the woken core by the waker core is the easiest way to ensure a non-
113 * delayed wake and immediate execution of any woken threads. If that isn't
114 * available then some careful non-blocking synchonization is needed (as on
115 * PP targets at the moment).
116 *---------------------------------------------------------------------------
119 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
120 * (someday :). */
121 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
122 struct core_entry cores[NUM_CORES] IBSS_ATTR;
123 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
125 static const char main_thread_name[] = "main";
126 extern uintptr_t stackbegin[];
127 extern uintptr_t stackend[];
129 static inline void core_sleep(IF_COP_VOID(unsigned int core))
130 __attribute__((always_inline));
132 void check_tmo_threads(void)
133 __attribute__((noinline));
135 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
136 __attribute__((always_inline));
138 static void add_to_list_tmo(struct thread_entry *thread)
139 __attribute__((noinline));
141 static void core_schedule_wakeup(struct thread_entry *thread)
142 __attribute__((noinline));
144 #if NUM_CORES > 1
145 static inline void run_blocking_ops(
146 unsigned int core, struct thread_entry *thread)
147 __attribute__((always_inline));
148 #endif
150 static void thread_stkov(struct thread_entry *thread)
151 __attribute__((noinline));
153 static inline void store_context(void* addr)
154 __attribute__((always_inline));
156 static inline void load_context(const void* addr)
157 __attribute__((always_inline));
159 void switch_thread(void)
160 __attribute__((noinline));
162 /****************************************************************************
163 * Processor-specific section
166 #if defined(MAX_PHYS_SECTOR_SIZE) && MEM == 64
167 /* Support a special workaround object for large-sector disks */
168 #define IF_NO_SKIP_YIELD(...) __VA_ARGS__
169 #else
170 #define IF_NO_SKIP_YIELD(...)
171 #endif
173 #if defined(CPU_ARM)
174 /*---------------------------------------------------------------------------
175 * Start the thread running and terminate it if it returns
176 *---------------------------------------------------------------------------
178 static void __attribute__((naked,used)) start_thread(void)
180 /* r0 = context */
181 asm volatile (
182 "ldr sp, [r0, #32] \n" /* Load initial sp */
183 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
184 "mov r1, #0 \n" /* Mark thread as running */
185 "str r1, [r0, #40] \n"
186 #if NUM_CORES > 1
187 "ldr r0, =cpucache_invalidate \n" /* Invalidate this core's cache. */
188 "mov lr, pc \n" /* This could be the first entry into */
189 "bx r0 \n" /* plugin or codec code for this core. */
190 #endif
191 "mov lr, pc \n" /* Call thread function */
192 "bx r4 \n"
193 ); /* No clobber list - new thread doesn't care */
194 thread_exit();
195 //asm volatile (".ltorg"); /* Dump constant pool */
198 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
199 * slot, and thread function pointer in context.start. See load_context for
200 * what happens when thread is initially going to run. */
201 #define THREAD_STARTUP_INIT(core, thread, function) \
202 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
203 (thread)->context.r[1] = (uint32_t)start_thread, \
204 (thread)->context.start = (uint32_t)function; })
206 /*---------------------------------------------------------------------------
207 * Store non-volatile context.
208 *---------------------------------------------------------------------------
210 static inline void store_context(void* addr)
212 asm volatile(
213 "stmia %0, { r4-r11, sp, lr } \n"
214 : : "r" (addr)
218 /*---------------------------------------------------------------------------
219 * Load non-volatile context.
220 *---------------------------------------------------------------------------
222 static inline void load_context(const void* addr)
224 asm volatile(
225 "ldr r0, [%0, #40] \n" /* Load start pointer */
226 "cmp r0, #0 \n" /* Check for NULL */
227 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
228 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
229 : : "r" (addr) : "r0" /* only! */
233 #if defined (CPU_PP)
235 #if NUM_CORES > 1
236 extern uintptr_t cpu_idlestackbegin[];
237 extern uintptr_t cpu_idlestackend[];
238 extern uintptr_t cop_idlestackbegin[];
239 extern uintptr_t cop_idlestackend[];
240 static uintptr_t * const idle_stacks[NUM_CORES] =
242 [CPU] = cpu_idlestackbegin,
243 [COP] = cop_idlestackbegin
246 #if CONFIG_CPU == PP5002
247 /* Bytes to emulate the PP502x mailbox bits */
248 struct core_semaphores
250 volatile uint8_t intend_wake; /* 00h */
251 volatile uint8_t stay_awake; /* 01h */
252 volatile uint8_t intend_sleep; /* 02h */
253 volatile uint8_t unused; /* 03h */
256 static struct core_semaphores core_semaphores[NUM_CORES] IBSS_ATTR;
257 #endif /* CONFIG_CPU == PP5002 */
259 #endif /* NUM_CORES */
261 #if CONFIG_CORELOCK == SW_CORELOCK
262 /* Software core locks using Peterson's mutual exclusion algorithm */
264 /*---------------------------------------------------------------------------
265 * Initialize the corelock structure.
266 *---------------------------------------------------------------------------
268 void corelock_init(struct corelock *cl)
270 memset(cl, 0, sizeof (*cl));
273 #if 1 /* Assembly locks to minimize overhead */
274 /*---------------------------------------------------------------------------
275 * Wait for the corelock to become free and acquire it when it does.
276 *---------------------------------------------------------------------------
278 void corelock_lock(struct corelock *cl) __attribute__((naked));
279 void corelock_lock(struct corelock *cl)
281 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
282 asm volatile (
283 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
284 "ldrb r1, [r1] \n"
285 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
286 "eor r2, r1, #0xff \n" /* r2 = othercore */
287 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
288 "1: \n"
289 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
290 "cmp r3, #0 \n" /* yes? lock acquired */
291 "bxeq lr \n"
292 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
293 "cmp r3, r1 \n"
294 "bxeq lr \n" /* yes? lock acquired */
295 "b 1b \n" /* keep trying */
296 : : "i"(&PROCESSOR_ID)
298 (void)cl;
301 /*---------------------------------------------------------------------------
302 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
303 *---------------------------------------------------------------------------
305 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
306 int corelock_try_lock(struct corelock *cl)
308 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
309 asm volatile (
310 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
311 "ldrb r1, [r1] \n"
312 "mov r3, r0 \n"
313 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
314 "eor r2, r1, #0xff \n" /* r2 = othercore */
315 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
316 "ldrb r0, [r3, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
317 "eors r0, r0, r2 \n" /* yes? lock acquired */
318 "bxne lr \n"
319 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
320 "ands r0, r0, r1 \n"
321 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
322 "bx lr \n" /* return result */
323 : : "i"(&PROCESSOR_ID)
326 return 0;
327 (void)cl;
330 /*---------------------------------------------------------------------------
331 * Release ownership of the corelock
332 *---------------------------------------------------------------------------
334 void corelock_unlock(struct corelock *cl) __attribute__((naked));
335 void corelock_unlock(struct corelock *cl)
337 asm volatile (
338 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
339 "ldrb r1, [r1] \n"
340 "mov r2, #0 \n" /* cl->myl[core] = 0 */
341 "strb r2, [r0, r1, lsr #7] \n"
342 "bx lr \n"
343 : : "i"(&PROCESSOR_ID)
345 (void)cl;
347 #else /* C versions for reference */
348 /*---------------------------------------------------------------------------
349 * Wait for the corelock to become free and aquire it when it does.
350 *---------------------------------------------------------------------------
352 void corelock_lock(struct corelock *cl)
354 const unsigned int core = CURRENT_CORE;
355 const unsigned int othercore = 1 - core;
357 cl->myl[core] = core;
358 cl->turn = othercore;
360 for (;;)
362 if (cl->myl[othercore] == 0 || cl->turn == core)
363 break;
367 /*---------------------------------------------------------------------------
368 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
369 *---------------------------------------------------------------------------
371 int corelock_try_lock(struct corelock *cl)
373 const unsigned int core = CURRENT_CORE;
374 const unsigned int othercore = 1 - core;
376 cl->myl[core] = core;
377 cl->turn = othercore;
379 if (cl->myl[othercore] == 0 || cl->turn == core)
381 return 1;
384 cl->myl[core] = 0;
385 return 0;
388 /*---------------------------------------------------------------------------
389 * Release ownership of the corelock
390 *---------------------------------------------------------------------------
392 void corelock_unlock(struct corelock *cl)
394 cl->myl[CURRENT_CORE] = 0;
396 #endif /* ASM / C selection */
398 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
400 /*---------------------------------------------------------------------------
401 * Put core in a power-saving state if waking list wasn't repopulated and if
402 * no other core requested a wakeup for it to perform a task.
403 *---------------------------------------------------------------------------
405 #ifdef CPU_PP502x
406 #if NUM_CORES == 1
407 static inline void core_sleep(void)
409 sleep_core(CURRENT_CORE);
410 enable_irq();
412 #else
413 static inline void core_sleep(unsigned int core)
415 #if 1
416 asm volatile (
417 "mov r0, #4 \n" /* r0 = 0x4 << core */
418 "mov r0, r0, lsl %[c] \n"
419 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
420 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
421 "tst r1, r0, lsl #2 \n"
422 "moveq r1, #0x80000000 \n" /* Then sleep */
423 "streq r1, [%[ctl], %[c], lsl #2] \n"
424 "moveq r1, #0 \n" /* Clear control reg */
425 "streq r1, [%[ctl], %[c], lsl #2] \n"
426 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
427 "str r1, [%[mbx], #8] \n"
428 "1: \n" /* Wait for wake procedure to finish */
429 "ldr r1, [%[mbx], #0] \n"
430 "tst r1, r0, lsr #2 \n"
431 "bne 1b \n"
433 : [ctl]"r"(&CPU_CTL), [mbx]"r"(MBX_BASE), [c]"r"(core)
434 : "r0", "r1");
435 #else /* C version for reference */
436 /* Signal intent to sleep */
437 MBX_MSG_SET = 0x4 << core;
439 /* Something waking or other processor intends to wake us? */
440 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
442 sleep_core(core);
443 wake_core(core);
446 /* Signal wake - clear wake flag */
447 MBX_MSG_CLR = 0x14 << core;
449 /* Wait for other processor to finish wake procedure */
450 while (MBX_MSG_STAT & (0x1 << core));
451 #endif /* ASM/C selection */
452 enable_irq();
454 #endif /* NUM_CORES */
455 #elif CONFIG_CPU == PP5002
456 #if NUM_CORES == 1
457 static inline void core_sleep(void)
459 sleep_core(CURRENT_CORE);
460 enable_irq();
462 #else
463 /* PP5002 has no mailboxes - emulate using bytes */
464 static inline void core_sleep(unsigned int core)
466 #if 1
467 asm volatile (
468 "mov r0, #1 \n" /* Signal intent to sleep */
469 "strb r0, [%[sem], #2] \n"
470 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
471 "cmp r0, #0 \n"
472 "bne 2f \n"
473 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
474 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
475 * that the correct alternative is executed. Don't change the order
476 * of the next 4 instructions! */
477 "tst pc, #0x0c \n"
478 "mov r0, #0xca \n"
479 "strne r0, [%[ctl], %[c], lsl #2] \n"
480 "streq r0, [%[ctl], %[c], lsl #2] \n"
481 "nop \n" /* nop's needed because of pipeline */
482 "nop \n"
483 "nop \n"
484 "2: \n"
485 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
486 "strb r0, [%[sem], #1] \n"
487 "strb r0, [%[sem], #2] \n"
488 "1: \n" /* Wait for wake procedure to finish */
489 "ldrb r0, [%[sem], #0] \n"
490 "cmp r0, #0 \n"
491 "bne 1b \n"
493 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
494 [ctl]"r"(&CPU_CTL)
495 : "r0"
497 #else /* C version for reference */
498 /* Signal intent to sleep */
499 core_semaphores[core].intend_sleep = 1;
501 /* Something waking or other processor intends to wake us? */
502 if (core_semaphores[core].stay_awake == 0)
504 sleep_core(core);
507 /* Signal wake - clear wake flag */
508 core_semaphores[core].stay_awake = 0;
509 core_semaphores[core].intend_sleep = 0;
511 /* Wait for other processor to finish wake procedure */
512 while (core_semaphores[core].intend_wake != 0);
514 /* Enable IRQ */
515 #endif /* ASM/C selection */
516 enable_irq();
518 #endif /* NUM_CORES */
519 #endif /* PP CPU type */
521 /*---------------------------------------------------------------------------
522 * Wake another processor core that is sleeping or prevent it from doing so
523 * if it was already destined. FIQ, IRQ should be disabled before calling.
524 *---------------------------------------------------------------------------
526 #if NUM_CORES == 1
527 /* Shared single-core build debugging version */
528 void core_wake(void)
530 /* No wakey - core already wakey */
532 #elif defined (CPU_PP502x)
533 void core_wake(unsigned int othercore)
535 #if 1
536 /* avoid r0 since that contains othercore */
537 asm volatile (
538 "mrs r3, cpsr \n" /* Disable IRQ */
539 "orr r1, r3, #0x80 \n"
540 "msr cpsr_c, r1 \n"
541 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
542 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
543 "str r2, [%[mbx], #4] \n"
544 "1: \n" /* If it intends to sleep, let it first */
545 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
546 "eor r1, r1, #0xc \n"
547 "tst r1, r2, lsr #2 \n"
548 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
549 "tsteq r1, #0x80000000 \n"
550 "beq 1b \n" /* Wait for sleep or wake */
551 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
552 "movne r1, #0x0 \n"
553 "strne r1, [%[ctl], %[oc], lsl #2] \n"
554 "mov r1, r2, lsr #4 \n"
555 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
556 "msr cpsr_c, r3 \n" /* Restore IRQ */
558 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
559 [oc]"r"(othercore)
560 : "r1", "r2", "r3");
561 #else /* C version for reference */
562 /* Disable interrupts - avoid reentrancy from the tick */
563 int oldlevel = disable_irq_save();
565 /* Signal intent to wake other processor - set stay awake */
566 MBX_MSG_SET = 0x11 << othercore;
568 /* If it intends to sleep, wait until it does or aborts */
569 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
570 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
572 /* If sleeping, wake it up */
573 if (PROC_CTL(othercore) & PROC_SLEEP)
574 PROC_CTL(othercore) = 0;
576 /* Done with wake procedure */
577 MBX_MSG_CLR = 0x1 << othercore;
578 restore_irq(oldlevel);
579 #endif /* ASM/C selection */
581 #elif CONFIG_CPU == PP5002
582 /* PP5002 has no mailboxes - emulate using bytes */
583 void core_wake(unsigned int othercore)
585 #if 1
586 /* avoid r0 since that contains othercore */
587 asm volatile (
588 "mrs r3, cpsr \n" /* Disable IRQ */
589 "orr r1, r3, #0x80 \n"
590 "msr cpsr_c, r1 \n"
591 "mov r1, #1 \n" /* Signal intent to wake other core */
592 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
593 "strh r1, [%[sem], #0] \n"
594 "mov r2, #0x8000 \n"
595 "1: \n" /* If it intends to sleep, let it first */
596 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
597 "cmp r1, #1 \n"
598 "ldr r1, [%[st]] \n" /* && not sleeping ? */
599 "tsteq r1, r2, lsr %[oc] \n"
600 "beq 1b \n" /* Wait for sleep or wake */
601 "tst r1, r2, lsr %[oc] \n"
602 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
603 "movne r1, #0xce \n"
604 "strne r1, [r2, %[oc], lsl #2] \n"
605 "mov r1, #0 \n" /* Done with wake procedure */
606 "strb r1, [%[sem], #0] \n"
607 "msr cpsr_c, r3 \n" /* Restore IRQ */
609 : [sem]"r"(&core_semaphores[othercore]),
610 [st]"r"(&PROC_STAT),
611 [oc]"r"(othercore)
612 : "r1", "r2", "r3"
614 #else /* C version for reference */
615 /* Disable interrupts - avoid reentrancy from the tick */
616 int oldlevel = disable_irq_save();
618 /* Signal intent to wake other processor - set stay awake */
619 core_semaphores[othercore].intend_wake = 1;
620 core_semaphores[othercore].stay_awake = 1;
622 /* If it intends to sleep, wait until it does or aborts */
623 while (core_semaphores[othercore].intend_sleep != 0 &&
624 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
626 /* If sleeping, wake it up */
627 if (PROC_STAT & PROC_SLEEPING(othercore))
628 wake_core(othercore);
630 /* Done with wake procedure */
631 core_semaphores[othercore].intend_wake = 0;
632 restore_irq(oldlevel);
633 #endif /* ASM/C selection */
635 #endif /* CPU type */
637 #if NUM_CORES > 1
638 /*---------------------------------------------------------------------------
639 * Switches to a stack that always resides in the Rockbox core.
641 * Needed when a thread suicides on a core other than the main CPU since the
642 * stack used when idling is the stack of the last thread to run. This stack
643 * may not reside in the core firmware in which case the core will continue
644 * to use a stack from an unloaded module until another thread runs on it.
645 *---------------------------------------------------------------------------
647 static inline void switch_to_idle_stack(const unsigned int core)
649 asm volatile (
650 "str sp, [%0] \n" /* save original stack pointer on idle stack */
651 "mov sp, %0 \n" /* switch stacks */
652 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
653 (void)core;
656 /*---------------------------------------------------------------------------
657 * Perform core switch steps that need to take place inside switch_thread.
659 * These steps must take place while before changing the processor and after
660 * having entered switch_thread since switch_thread may not do a normal return
661 * because the stack being used for anything the compiler saved will not belong
662 * to the thread's destination core and it may have been recycled for other
663 * purposes by the time a normal context load has taken place. switch_thread
664 * will also clobber anything stashed in the thread's context or stored in the
665 * nonvolatile registers if it is saved there before the call since the
666 * compiler's order of operations cannot be known for certain.
668 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
670 /* Flush our data to ram */
671 cpucache_flush();
672 /* Stash thread in r4 slot */
673 thread->context.r[0] = (uint32_t)thread;
674 /* Stash restart address in r5 slot */
675 thread->context.r[1] = thread->context.start;
676 /* Save sp in context.sp while still running on old core */
677 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
680 /*---------------------------------------------------------------------------
681 * Machine-specific helper function for switching the processor a thread is
682 * running on. Basically, the thread suicides on the departing core and is
683 * reborn on the destination. Were it not for gcc's ill-behavior regarding
684 * naked functions written in C where it actually clobbers non-volatile
685 * registers before the intended prologue code, this would all be much
686 * simpler. Generic setup is done in switch_core itself.
689 /*---------------------------------------------------------------------------
690 * This actually performs the core switch.
692 static void __attribute__((naked))
693 switch_thread_core(unsigned int core, struct thread_entry *thread)
695 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
696 * Stack access also isn't permitted until restoring the original stack and
697 * context. */
698 asm volatile (
699 "stmfd sp!, { r4-r11, lr } \n" /* Stack all non-volatile context on current core */
700 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
701 "ldr r2, [r2, r0, lsl #2] \n"
702 "add r2, r2, %0*4 \n"
703 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
704 "mov sp, r2 \n" /* switch stacks */
705 "adr r2, 1f \n" /* r2 = new core restart address */
706 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
707 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
708 "1: \n"
709 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
710 "mov r1, #0 \n" /* Clear start address */
711 "str r1, [r0, #40] \n"
712 "ldr r0, =cpucache_invalidate \n" /* Invalidate new core's cache */
713 "mov lr, pc \n"
714 "bx r0 \n"
715 "ldmfd sp!, { r4-r11, pc } \n" /* Restore non-volatile context to new core and return */
716 ".ltorg \n" /* Dump constant pool */
717 : : "i"(IDLE_STACK_WORDS)
719 (void)core; (void)thread;
722 /*---------------------------------------------------------------------------
723 * Do any device-specific inits for the threads and synchronize the kernel
724 * initializations.
725 *---------------------------------------------------------------------------
727 static void core_thread_init(unsigned int core)
729 if (core == CPU)
731 /* Wake up coprocessor and let it initialize kernel and threads */
732 #ifdef CPU_PP502x
733 MBX_MSG_CLR = 0x3f;
734 #endif
735 wake_core(COP);
736 /* Sleep until COP has finished */
737 sleep_core(CPU);
739 else
741 /* Wake the CPU and return */
742 wake_core(CPU);
745 #endif /* NUM_CORES */
747 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X) /* Single core only for now */ \
748 || CONFIG_CPU == IMX31L || CONFIG_CPU == DM320 || CONFIG_CPU == AS3525 \
749 || CONFIG_CPU == S3C2440
750 /* Use the generic ARMv4/v5/v6 wait for IRQ */
751 static inline void core_sleep(void)
753 asm volatile (
754 "mcr p15, 0, %0, c7, c0, 4" /* Wait for interrupt */
755 : : "r"(0)
757 enable_irq();
759 #else
760 static inline void core_sleep(void)
762 #warning core_sleep not implemented, battery life will be decreased
763 enable_irq();
765 #endif /* CONFIG_CPU == */
767 #elif defined(CPU_COLDFIRE)
768 /*---------------------------------------------------------------------------
769 * Start the thread running and terminate it if it returns
770 *---------------------------------------------------------------------------
772 void start_thread(void); /* Provide C access to ASM label */
773 static void __attribute__((used)) __start_thread(void)
775 /* a0=macsr, a1=context */
776 asm volatile (
777 "start_thread: \n" /* Start here - no naked attribute */
778 "move.l %a0, %macsr \n" /* Set initial mac status reg */
779 "lea.l 48(%a1), %a1 \n"
780 "move.l (%a1)+, %sp \n" /* Set initial stack */
781 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
782 "clr.l (%a1) \n" /* Mark thread running */
783 "jsr (%a2) \n" /* Call thread function */
785 thread_exit();
788 /* Set EMAC unit to fractional mode with saturation for each new thread,
789 * since that's what'll be the most useful for most things which the dsp
790 * will do. Codecs should still initialize their preferred modes
791 * explicitly. Context pointer is placed in d2 slot and start_thread
792 * pointer in d3 slot. thread function pointer is placed in context.start.
793 * See load_context for what happens when thread is initially going to
794 * run.
796 #define THREAD_STARTUP_INIT(core, thread, function) \
797 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
798 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
799 (thread)->context.d[1] = (uint32_t)start_thread, \
800 (thread)->context.start = (uint32_t)(function); })
802 /*---------------------------------------------------------------------------
803 * Store non-volatile context.
804 *---------------------------------------------------------------------------
806 static inline void store_context(void* addr)
808 asm volatile (
809 "move.l %%macsr,%%d0 \n"
810 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
811 : : "a" (addr) : "d0" /* only! */
815 /*---------------------------------------------------------------------------
816 * Load non-volatile context.
817 *---------------------------------------------------------------------------
819 static inline void load_context(const void* addr)
821 asm volatile (
822 "move.l 52(%0), %%d0 \n" /* Get start address */
823 "beq.b 1f \n" /* NULL -> already running */
824 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
825 "jmp (%%a2) \n" /* Start the thread */
826 "1: \n"
827 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
828 "move.l %%d0, %%macsr \n"
829 : : "a" (addr) : "d0" /* only! */
833 /*---------------------------------------------------------------------------
834 * Put core in a power-saving state if waking list wasn't repopulated.
835 *---------------------------------------------------------------------------
837 static inline void core_sleep(void)
839 /* Supervisor mode, interrupts enabled upon wakeup */
840 asm volatile ("stop #0x2000");
843 #elif CONFIG_CPU == SH7034
844 /*---------------------------------------------------------------------------
845 * Start the thread running and terminate it if it returns
846 *---------------------------------------------------------------------------
848 void start_thread(void); /* Provide C access to ASM label */
849 static void __attribute__((used)) __start_thread(void)
851 /* r8 = context */
852 asm volatile (
853 "_start_thread: \n" /* Start here - no naked attribute */
854 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
855 "mov.l @(28, r8), r15 \n" /* Set initial sp */
856 "mov #0, r1 \n" /* Start the thread */
857 "jsr @r0 \n"
858 "mov.l r1, @(36, r8) \n" /* Clear start address */
860 thread_exit();
863 /* Place context pointer in r8 slot, function pointer in r9 slot, and
864 * start_thread pointer in context_start */
865 #define THREAD_STARTUP_INIT(core, thread, function) \
866 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
867 (thread)->context.r[1] = (uint32_t)(function), \
868 (thread)->context.start = (uint32_t)start_thread; })
870 /*---------------------------------------------------------------------------
871 * Store non-volatile context.
872 *---------------------------------------------------------------------------
874 static inline void store_context(void* addr)
876 asm volatile (
877 "add #36, %0 \n" /* Start at last reg. By the time routine */
878 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
879 "mov.l r15,@-%0 \n"
880 "mov.l r14,@-%0 \n"
881 "mov.l r13,@-%0 \n"
882 "mov.l r12,@-%0 \n"
883 "mov.l r11,@-%0 \n"
884 "mov.l r10,@-%0 \n"
885 "mov.l r9, @-%0 \n"
886 "mov.l r8, @-%0 \n"
887 : : "r" (addr)
891 /*---------------------------------------------------------------------------
892 * Load non-volatile context.
893 *---------------------------------------------------------------------------
895 static inline void load_context(const void* addr)
897 asm volatile (
898 "mov.l @(36, %0), r0 \n" /* Get start address */
899 "tst r0, r0 \n"
900 "bt .running \n" /* NULL -> already running */
901 "jmp @r0 \n" /* r8 = context */
902 ".running: \n"
903 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
904 "mov.l @%0+, r9 \n"
905 "mov.l @%0+, r10 \n"
906 "mov.l @%0+, r11 \n"
907 "mov.l @%0+, r12 \n"
908 "mov.l @%0+, r13 \n"
909 "mov.l @%0+, r14 \n"
910 "mov.l @%0+, r15 \n"
911 "lds.l @%0+, pr \n"
912 : : "r" (addr) : "r0" /* only! */
916 /*---------------------------------------------------------------------------
917 * Put core in a power-saving state.
918 *---------------------------------------------------------------------------
920 static inline void core_sleep(void)
922 asm volatile (
923 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
924 "mov #0, r1 \n" /* Enable interrupts */
925 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
926 "sleep \n" /* Execute standby */
927 : : "z"(&SBYCR-GBR) : "r1");
930 #elif CPU_MIPS == 32
932 /*---------------------------------------------------------------------------
933 * Start the thread running and terminate it if it returns
934 *---------------------------------------------------------------------------
937 void start_thread(void); /* Provide C access to ASM label */
938 static void __attribute__((used)) _start_thread(void)
940 /* t1 = context */
941 asm volatile (
942 "start_thread: \n"
943 ".set noreorder \n"
944 ".set noat \n"
945 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = t0, $9 = t1) */
946 "lw $29, 36($9) \n" /* Set initial sp(=$29) */
947 "jalr $8 \n" /* Start the thread */
948 "sw $0, 44($9) \n" /* Clear start address */
949 ".set at \n"
950 ".set reorder \n"
952 thread_exit();
955 /* Place context pointer in s0 slot, function pointer in s1 slot, and
956 * start_thread pointer in context_start */
957 #define THREAD_STARTUP_INIT(core, thread, function) \
958 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
959 (thread)->context.r[1] = (uint32_t)(function), \
960 (thread)->context.start = (uint32_t)start_thread; })
962 /*---------------------------------------------------------------------------
963 * Store non-volatile context.
964 *---------------------------------------------------------------------------
966 static inline void store_context(void* addr)
968 asm volatile (
969 ".set noreorder \n"
970 ".set noat \n"
971 "sw $16, 0(%0) \n" /* s0 */
972 "sw $17, 4(%0) \n" /* s1 */
973 "sw $18, 8(%0) \n" /* s2 */
974 "sw $19, 12(%0) \n" /* s3 */
975 "sw $20, 16(%0) \n" /* s4 */
976 "sw $21, 20(%0) \n" /* s5 */
977 "sw $22, 24(%0) \n" /* s6 */
978 "sw $23, 28(%0) \n" /* s7 */
979 "sw $30, 32(%0) \n" /* fp */
980 "sw $29, 36(%0) \n" /* sp */
981 "sw $31, 40(%0) \n" /* ra */
982 ".set at \n"
983 ".set reorder \n"
984 : : "r" (addr)
988 /*---------------------------------------------------------------------------
989 * Load non-volatile context.
990 *---------------------------------------------------------------------------
992 static inline void load_context(const void* addr)
994 asm volatile (
995 ".set noat \n"
996 ".set noreorder \n"
997 "lw $8, 44(%0) \n" /* Get start address ($8 = t0) */
998 "beqz $8, running \n" /* NULL -> already running */
999 "nop \n"
1000 "jr $8 \n"
1001 "move $9, %0 \n" /* t1 = context */
1002 "running: \n"
1003 "lw $16, 0(%0) \n" /* s0 */
1004 "lw $17, 4(%0) \n" /* s1 */
1005 "lw $18, 8(%0) \n" /* s2 */
1006 "lw $19, 12(%0) \n" /* s3 */
1007 "lw $20, 16(%0) \n" /* s4 */
1008 "lw $21, 20(%0) \n" /* s5 */
1009 "lw $22, 24(%0) \n" /* s6 */
1010 "lw $23, 28(%0) \n" /* s7 */
1011 "lw $30, 32(%0) \n" /* fp */
1012 "lw $29, 36(%0) \n" /* sp */
1013 "lw $31, 40(%0) \n" /* ra */
1014 ".set at \n"
1015 ".set reorder \n"
1016 : : "r" (addr) : "t0", "t1"
1020 /*---------------------------------------------------------------------------
1021 * Put core in a power-saving state.
1022 *---------------------------------------------------------------------------
1024 static inline void core_sleep(void)
1026 #if CONFIG_CPU == JZ4732
1027 __cpm_idle_mode();
1028 #endif
1029 asm volatile(".set mips32r2 \n"
1030 "mfc0 $8, $12 \n" /* mfc t0, $12 */
1031 "move $9, $8 \n" /* move t1, t0 */
1032 "la $10, 0x8000000 \n" /* la t2, 0x8000000 */
1033 "or $8, $8, $10 \n" /* Enable reduced power mode */
1034 "mtc0 $8, $12 \n" /* mtc t0, $12 */
1035 "wait \n"
1036 "mtc0 $9, $12 \n" /* mtc t1, $12 */
1037 ".set mips0 \n"
1038 ::: "t0", "t1", "t2"
1040 enable_irq();
1044 #endif /* CONFIG_CPU == */
1047 * End Processor-specific section
1048 ***************************************************************************/
1050 #if THREAD_EXTRA_CHECKS
1051 static void thread_panicf(const char *msg, struct thread_entry *thread)
1053 IF_COP( const unsigned int core = thread->core; )
1054 static char name[32];
1055 thread_get_name(name, 32, thread);
1056 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1058 static void thread_stkov(struct thread_entry *thread)
1060 thread_panicf("Stkov", thread);
1062 #define THREAD_PANICF(msg, thread) \
1063 thread_panicf(msg, thread)
1064 #define THREAD_ASSERT(exp, msg, thread) \
1065 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1066 #else
1067 static void thread_stkov(struct thread_entry *thread)
1069 IF_COP( const unsigned int core = thread->core; )
1070 static char name[32];
1071 thread_get_name(name, 32, thread);
1072 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1074 #define THREAD_PANICF(msg, thread)
1075 #define THREAD_ASSERT(exp, msg, thread)
1076 #endif /* THREAD_EXTRA_CHECKS */
1078 /* Thread locking */
1079 #if NUM_CORES > 1
1080 #define LOCK_THREAD(thread) \
1081 ({ corelock_lock(&(thread)->slot_cl); })
1082 #define TRY_LOCK_THREAD(thread) \
1083 ({ corelock_try_lock(&thread->slot_cl); })
1084 #define UNLOCK_THREAD(thread) \
1085 ({ corelock_unlock(&(thread)->slot_cl); })
1086 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1087 ({ unsigned int _core = (thread)->core; \
1088 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1089 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1090 #else
1091 #define LOCK_THREAD(thread) \
1092 ({ })
1093 #define TRY_LOCK_THREAD(thread) \
1094 ({ })
1095 #define UNLOCK_THREAD(thread) \
1096 ({ })
1097 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1098 ({ })
1099 #endif
1101 /* RTR list */
1102 #define RTR_LOCK(core) \
1103 ({ corelock_lock(&cores[core].rtr_cl); })
1104 #define RTR_UNLOCK(core) \
1105 ({ corelock_unlock(&cores[core].rtr_cl); })
1107 #ifdef HAVE_PRIORITY_SCHEDULING
1108 #define rtr_add_entry(core, priority) \
1109 prio_add_entry(&cores[core].rtr, (priority))
1111 #define rtr_subtract_entry(core, priority) \
1112 prio_subtract_entry(&cores[core].rtr, (priority))
1114 #define rtr_move_entry(core, from, to) \
1115 prio_move_entry(&cores[core].rtr, (from), (to))
1116 #else
1117 #define rtr_add_entry(core, priority)
1118 #define rtr_add_entry_inl(core, priority)
1119 #define rtr_subtract_entry(core, priority)
1120 #define rtr_subtract_entry_inl(core, priotity)
1121 #define rtr_move_entry(core, from, to)
1122 #define rtr_move_entry_inl(core, from, to)
1123 #endif
1125 /*---------------------------------------------------------------------------
1126 * Thread list structure - circular:
1127 * +------------------------------+
1128 * | |
1129 * +--+---+<-+---+<-+---+<-+---+<-+
1130 * Head->| T | | T | | T | | T |
1131 * +->+---+->+---+->+---+->+---+--+
1132 * | |
1133 * +------------------------------+
1134 *---------------------------------------------------------------------------
1137 /*---------------------------------------------------------------------------
1138 * Adds a thread to a list of threads using "insert last". Uses the "l"
1139 * links.
1140 *---------------------------------------------------------------------------
1142 static void add_to_list_l(struct thread_entry **list,
1143 struct thread_entry *thread)
1145 struct thread_entry *l = *list;
1147 if (l == NULL)
1149 /* Insert into unoccupied list */
1150 thread->l.prev = thread;
1151 thread->l.next = thread;
1152 *list = thread;
1153 return;
1156 /* Insert last */
1157 thread->l.prev = l->l.prev;
1158 thread->l.next = l;
1159 l->l.prev->l.next = thread;
1160 l->l.prev = thread;
1163 /*---------------------------------------------------------------------------
1164 * Removes a thread from a list of threads. Uses the "l" links.
1165 *---------------------------------------------------------------------------
1167 static void remove_from_list_l(struct thread_entry **list,
1168 struct thread_entry *thread)
1170 struct thread_entry *prev, *next;
1172 next = thread->l.next;
1174 if (thread == next)
1176 /* The only item */
1177 *list = NULL;
1178 return;
1181 if (thread == *list)
1183 /* List becomes next item */
1184 *list = next;
1187 prev = thread->l.prev;
1189 /* Fix links to jump over the removed entry. */
1190 next->l.prev = prev;
1191 prev->l.next = next;
1194 /*---------------------------------------------------------------------------
1195 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1196 * NULL-terminated forward (to ease the far more common forward traversal):
1197 * +------------------------------+
1198 * | |
1199 * +--+---+<-+---+<-+---+<-+---+<-+
1200 * Head->| T | | T | | T | | T |
1201 * +---+->+---+->+---+->+---+-X
1202 *---------------------------------------------------------------------------
1205 /*---------------------------------------------------------------------------
1206 * Add a thread from the core's timout list by linking the pointers in its
1207 * tmo structure.
1208 *---------------------------------------------------------------------------
1210 static void add_to_list_tmo(struct thread_entry *thread)
1212 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1213 THREAD_ASSERT(thread->tmo.prev == NULL,
1214 "add_to_list_tmo->already listed", thread);
1216 thread->tmo.next = NULL;
1218 if (tmo == NULL)
1220 /* Insert into unoccupied list */
1221 thread->tmo.prev = thread;
1222 cores[IF_COP_CORE(thread->core)].timeout = thread;
1223 return;
1226 /* Insert Last */
1227 thread->tmo.prev = tmo->tmo.prev;
1228 tmo->tmo.prev->tmo.next = thread;
1229 tmo->tmo.prev = thread;
1232 /*---------------------------------------------------------------------------
1233 * Remove a thread from the core's timout list by unlinking the pointers in
1234 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1235 * is cancelled.
1236 *---------------------------------------------------------------------------
1238 static void remove_from_list_tmo(struct thread_entry *thread)
1240 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1241 struct thread_entry *prev = thread->tmo.prev;
1242 struct thread_entry *next = thread->tmo.next;
1244 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1246 if (next != NULL)
1247 next->tmo.prev = prev;
1249 if (thread == *list)
1251 /* List becomes next item and empty if next == NULL */
1252 *list = next;
1253 /* Mark as unlisted */
1254 thread->tmo.prev = NULL;
1256 else
1258 if (next == NULL)
1259 (*list)->tmo.prev = prev;
1260 prev->tmo.next = next;
1261 /* Mark as unlisted */
1262 thread->tmo.prev = NULL;
1267 #ifdef HAVE_PRIORITY_SCHEDULING
1268 /*---------------------------------------------------------------------------
1269 * Priority distribution structure (one category for each possible priority):
1271 * +----+----+----+ ... +-----+
1272 * hist: | F0 | F1 | F2 | | F31 |
1273 * +----+----+----+ ... +-----+
1274 * mask: | b0 | b1 | b2 | | b31 |
1275 * +----+----+----+ ... +-----+
1277 * F = count of threads at priority category n (frequency)
1278 * b = bitmask of non-zero priority categories (occupancy)
1280 * / if H[n] != 0 : 1
1281 * b[n] = |
1282 * \ else : 0
1284 *---------------------------------------------------------------------------
1285 * Basic priority inheritance priotocol (PIP):
1287 * Mn = mutex n, Tn = thread n
1289 * A lower priority thread inherits the priority of the highest priority
1290 * thread blocked waiting for it to complete an action (such as release a
1291 * mutex or respond to a message via queue_send):
1293 * 1) T2->M1->T1
1295 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1296 * priority than T1 then T1 inherits the priority of T2.
1298 * 2) T3
1299 * \/
1300 * T2->M1->T1
1302 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1303 * T1 inherits the higher of T2 and T3.
1305 * 3) T3->M2->T2->M1->T1
1307 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1308 * then T1 inherits the priority of T3 through T2.
1310 * Blocking chains can grow arbitrarily complex (though it's best that they
1311 * not form at all very often :) and build-up from these units.
1312 *---------------------------------------------------------------------------
1315 /*---------------------------------------------------------------------------
1316 * Increment frequency at category "priority"
1317 *---------------------------------------------------------------------------
1319 static inline unsigned int prio_add_entry(
1320 struct priority_distribution *pd, int priority)
1322 unsigned int count;
1323 /* Enough size/instruction count difference for ARM makes it worth it to
1324 * use different code (192 bytes for ARM). Only thing better is ASM. */
1325 #ifdef CPU_ARM
1326 count = pd->hist[priority];
1327 if (++count == 1)
1328 pd->mask |= 1 << priority;
1329 pd->hist[priority] = count;
1330 #else /* This one's better for Coldfire */
1331 if ((count = ++pd->hist[priority]) == 1)
1332 pd->mask |= 1 << priority;
1333 #endif
1335 return count;
1338 /*---------------------------------------------------------------------------
1339 * Decrement frequency at category "priority"
1340 *---------------------------------------------------------------------------
1342 static inline unsigned int prio_subtract_entry(
1343 struct priority_distribution *pd, int priority)
1345 unsigned int count;
1347 #ifdef CPU_ARM
1348 count = pd->hist[priority];
1349 if (--count == 0)
1350 pd->mask &= ~(1 << priority);
1351 pd->hist[priority] = count;
1352 #else
1353 if ((count = --pd->hist[priority]) == 0)
1354 pd->mask &= ~(1 << priority);
1355 #endif
1357 return count;
1360 /*---------------------------------------------------------------------------
1361 * Remove from one category and add to another
1362 *---------------------------------------------------------------------------
1364 static inline void prio_move_entry(
1365 struct priority_distribution *pd, int from, int to)
1367 uint32_t mask = pd->mask;
1369 #ifdef CPU_ARM
1370 unsigned int count;
1372 count = pd->hist[from];
1373 if (--count == 0)
1374 mask &= ~(1 << from);
1375 pd->hist[from] = count;
1377 count = pd->hist[to];
1378 if (++count == 1)
1379 mask |= 1 << to;
1380 pd->hist[to] = count;
1381 #else
1382 if (--pd->hist[from] == 0)
1383 mask &= ~(1 << from);
1385 if (++pd->hist[to] == 1)
1386 mask |= 1 << to;
1387 #endif
1389 pd->mask = mask;
1392 /*---------------------------------------------------------------------------
1393 * Change the priority and rtr entry for a running thread
1394 *---------------------------------------------------------------------------
1396 static inline void set_running_thread_priority(
1397 struct thread_entry *thread, int priority)
1399 const unsigned int core = IF_COP_CORE(thread->core);
1400 RTR_LOCK(core);
1401 rtr_move_entry(core, thread->priority, priority);
1402 thread->priority = priority;
1403 RTR_UNLOCK(core);
1406 /*---------------------------------------------------------------------------
1407 * Finds the highest priority thread in a list of threads. If the list is
1408 * empty, the PRIORITY_IDLE is returned.
1410 * It is possible to use the struct priority_distribution within an object
1411 * instead of scanning the remaining threads in the list but as a compromise,
1412 * the resulting per-object memory overhead is saved at a slight speed
1413 * penalty under high contention.
1414 *---------------------------------------------------------------------------
1416 static int find_highest_priority_in_list_l(
1417 struct thread_entry * const thread)
1419 if (LIKELY(thread != NULL))
1421 /* Go though list until the ending up at the initial thread */
1422 int highest_priority = thread->priority;
1423 struct thread_entry *curr = thread;
1427 int priority = curr->priority;
1429 if (priority < highest_priority)
1430 highest_priority = priority;
1432 curr = curr->l.next;
1434 while (curr != thread);
1436 return highest_priority;
1439 return PRIORITY_IDLE;
1442 /*---------------------------------------------------------------------------
1443 * Register priority with blocking system and bubble it down the chain if
1444 * any until we reach the end or something is already equal or higher.
1446 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1447 * targets but that same action also guarantees a circular block anyway and
1448 * those are prevented, right? :-)
1449 *---------------------------------------------------------------------------
1451 static struct thread_entry *
1452 blocker_inherit_priority(struct thread_entry *current)
1454 const int priority = current->priority;
1455 struct blocker *bl = current->blocker;
1456 struct thread_entry * const tstart = current;
1457 struct thread_entry *bl_t = bl->thread;
1459 /* Blocker cannot change since the object protection is held */
1460 LOCK_THREAD(bl_t);
1462 for (;;)
1464 struct thread_entry *next;
1465 int bl_pr = bl->priority;
1467 if (priority >= bl_pr)
1468 break; /* Object priority already high enough */
1470 bl->priority = priority;
1472 /* Add this one */
1473 prio_add_entry(&bl_t->pdist, priority);
1475 if (bl_pr < PRIORITY_IDLE)
1477 /* Not first waiter - subtract old one */
1478 prio_subtract_entry(&bl_t->pdist, bl_pr);
1481 if (priority >= bl_t->priority)
1482 break; /* Thread priority high enough */
1484 if (bl_t->state == STATE_RUNNING)
1486 /* Blocking thread is a running thread therefore there are no
1487 * further blockers. Change the "run queue" on which it
1488 * resides. */
1489 set_running_thread_priority(bl_t, priority);
1490 break;
1493 bl_t->priority = priority;
1495 /* If blocking thread has a blocker, apply transitive inheritance */
1496 bl = bl_t->blocker;
1498 if (bl == NULL)
1499 break; /* End of chain or object doesn't support inheritance */
1501 next = bl->thread;
1503 if (UNLIKELY(next == tstart))
1504 break; /* Full-circle - deadlock! */
1506 UNLOCK_THREAD(current);
1508 #if NUM_CORES > 1
1509 for (;;)
1511 LOCK_THREAD(next);
1513 /* Blocker could change - retest condition */
1514 if (LIKELY(bl->thread == next))
1515 break;
1517 UNLOCK_THREAD(next);
1518 next = bl->thread;
1520 #endif
1521 current = bl_t;
1522 bl_t = next;
1525 UNLOCK_THREAD(bl_t);
1527 return current;
1530 /*---------------------------------------------------------------------------
1531 * Readjust priorities when waking a thread blocked waiting for another
1532 * in essence "releasing" the thread's effect on the object owner. Can be
1533 * performed from any context.
1534 *---------------------------------------------------------------------------
1536 struct thread_entry *
1537 wakeup_priority_protocol_release(struct thread_entry *thread)
1539 const int priority = thread->priority;
1540 struct blocker *bl = thread->blocker;
1541 struct thread_entry * const tstart = thread;
1542 struct thread_entry *bl_t = bl->thread;
1544 /* Blocker cannot change since object will be locked */
1545 LOCK_THREAD(bl_t);
1547 thread->blocker = NULL; /* Thread not blocked */
1549 for (;;)
1551 struct thread_entry *next;
1552 int bl_pr = bl->priority;
1554 if (priority > bl_pr)
1555 break; /* Object priority higher */
1557 next = *thread->bqp;
1559 if (next == NULL)
1561 /* No more threads in queue */
1562 prio_subtract_entry(&bl_t->pdist, bl_pr);
1563 bl->priority = PRIORITY_IDLE;
1565 else
1567 /* Check list for highest remaining priority */
1568 int queue_pr = find_highest_priority_in_list_l(next);
1570 if (queue_pr == bl_pr)
1571 break; /* Object priority not changing */
1573 /* Change queue priority */
1574 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1575 bl->priority = queue_pr;
1578 if (bl_pr > bl_t->priority)
1579 break; /* thread priority is higher */
1581 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1583 if (bl_pr == bl_t->priority)
1584 break; /* Thread priority not changing */
1586 if (bl_t->state == STATE_RUNNING)
1588 /* No further blockers */
1589 set_running_thread_priority(bl_t, bl_pr);
1590 break;
1593 bl_t->priority = bl_pr;
1595 /* If blocking thread has a blocker, apply transitive inheritance */
1596 bl = bl_t->blocker;
1598 if (bl == NULL)
1599 break; /* End of chain or object doesn't support inheritance */
1601 next = bl->thread;
1603 if (UNLIKELY(next == tstart))
1604 break; /* Full-circle - deadlock! */
1606 UNLOCK_THREAD(thread);
1608 #if NUM_CORES > 1
1609 for (;;)
1611 LOCK_THREAD(next);
1613 /* Blocker could change - retest condition */
1614 if (LIKELY(bl->thread == next))
1615 break;
1617 UNLOCK_THREAD(next);
1618 next = bl->thread;
1620 #endif
1621 thread = bl_t;
1622 bl_t = next;
1625 UNLOCK_THREAD(bl_t);
1627 #if NUM_CORES > 1
1628 if (UNLIKELY(thread != tstart))
1630 /* Relock original if it changed */
1631 LOCK_THREAD(tstart);
1633 #endif
1635 return cores[CURRENT_CORE].running;
1638 /*---------------------------------------------------------------------------
1639 * Transfer ownership to a thread waiting for an objects and transfer
1640 * inherited priority boost from other waiters. This algorithm knows that
1641 * blocking chains may only unblock from the very end.
1643 * Only the owning thread itself may call this and so the assumption that
1644 * it is the running thread is made.
1645 *---------------------------------------------------------------------------
1647 struct thread_entry *
1648 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1650 /* Waking thread inherits priority boost from object owner */
1651 struct blocker *bl = thread->blocker;
1652 struct thread_entry *bl_t = bl->thread;
1653 struct thread_entry *next;
1654 int bl_pr;
1656 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
1657 "UPPT->wrong thread", cores[CURRENT_CORE].running);
1659 LOCK_THREAD(bl_t);
1661 bl_pr = bl->priority;
1663 /* Remove the object's boost from the owning thread */
1664 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1665 bl_pr <= bl_t->priority)
1667 /* No more threads at this priority are waiting and the old level is
1668 * at least the thread level */
1669 int priority = find_first_set_bit(bl_t->pdist.mask);
1671 if (priority != bl_t->priority)
1673 /* Adjust this thread's priority */
1674 set_running_thread_priority(bl_t, priority);
1678 next = *thread->bqp;
1680 if (LIKELY(next == NULL))
1682 /* Expected shortcut - no more waiters */
1683 bl_pr = PRIORITY_IDLE;
1685 else
1687 if (thread->priority <= bl_pr)
1689 /* Need to scan threads remaining in queue */
1690 bl_pr = find_highest_priority_in_list_l(next);
1693 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1694 bl_pr < thread->priority)
1696 /* Thread priority must be raised */
1697 thread->priority = bl_pr;
1701 bl->thread = thread; /* This thread pwns */
1702 bl->priority = bl_pr; /* Save highest blocked priority */
1703 thread->blocker = NULL; /* Thread not blocked */
1705 UNLOCK_THREAD(bl_t);
1707 return bl_t;
1710 /*---------------------------------------------------------------------------
1711 * No threads must be blocked waiting for this thread except for it to exit.
1712 * The alternative is more elaborate cleanup and object registration code.
1713 * Check this for risk of silent data corruption when objects with
1714 * inheritable blocking are abandoned by the owner - not precise but may
1715 * catch something.
1716 *---------------------------------------------------------------------------
1718 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1720 /* Only one bit in the mask should be set with a frequency on 1 which
1721 * represents the thread's own base priority */
1722 uint32_t mask = thread->pdist.mask;
1723 if ((mask & (mask - 1)) != 0 ||
1724 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1726 unsigned char name[32];
1727 thread_get_name(name, 32, thread);
1728 panicf("%s->%s with obj. waiters", function, name);
1731 #endif /* HAVE_PRIORITY_SCHEDULING */
1733 /*---------------------------------------------------------------------------
1734 * Move a thread back to a running state on its core.
1735 *---------------------------------------------------------------------------
1737 static void core_schedule_wakeup(struct thread_entry *thread)
1739 const unsigned int core = IF_COP_CORE(thread->core);
1741 RTR_LOCK(core);
1743 thread->state = STATE_RUNNING;
1745 add_to_list_l(&cores[core].running, thread);
1746 rtr_add_entry(core, thread->priority);
1748 RTR_UNLOCK(core);
1750 #if NUM_CORES > 1
1751 if (core != CURRENT_CORE)
1752 core_wake(core);
1753 #endif
1756 /*---------------------------------------------------------------------------
1757 * Check the core's timeout list when at least one thread is due to wake.
1758 * Filtering for the condition is done before making the call. Resets the
1759 * tick when the next check will occur.
1760 *---------------------------------------------------------------------------
1762 void check_tmo_threads(void)
1764 const unsigned int core = CURRENT_CORE;
1765 const long tick = current_tick; /* snapshot the current tick */
1766 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1767 struct thread_entry *next = cores[core].timeout;
1769 /* If there are no processes waiting for a timeout, just keep the check
1770 tick from falling into the past. */
1772 /* Break the loop once we have walked through the list of all
1773 * sleeping processes or have removed them all. */
1774 while (next != NULL)
1776 /* Check sleeping threads. Allow interrupts between checks. */
1777 enable_irq();
1779 struct thread_entry *curr = next;
1781 next = curr->tmo.next;
1783 /* Lock thread slot against explicit wakeup */
1784 disable_irq();
1785 LOCK_THREAD(curr);
1787 unsigned state = curr->state;
1789 if (state < TIMEOUT_STATE_FIRST)
1791 /* Cleanup threads no longer on a timeout but still on the
1792 * list. */
1793 remove_from_list_tmo(curr);
1795 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
1797 /* Timeout still pending - this will be the usual case */
1798 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1800 /* Earliest timeout found so far - move the next check up
1801 to its time */
1802 next_tmo_check = curr->tmo_tick;
1805 else
1807 /* Sleep timeout has been reached so bring the thread back to
1808 * life again. */
1809 if (state == STATE_BLOCKED_W_TMO)
1811 #if NUM_CORES > 1
1812 /* Lock the waiting thread's kernel object */
1813 struct corelock *ocl = curr->obj_cl;
1815 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1817 /* Need to retry in the correct order though the need is
1818 * unlikely */
1819 UNLOCK_THREAD(curr);
1820 corelock_lock(ocl);
1821 LOCK_THREAD(curr);
1823 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
1825 /* Thread was woken or removed explicitely while slot
1826 * was unlocked */
1827 corelock_unlock(ocl);
1828 remove_from_list_tmo(curr);
1829 UNLOCK_THREAD(curr);
1830 continue;
1833 #endif /* NUM_CORES */
1835 remove_from_list_l(curr->bqp, curr);
1837 #ifdef HAVE_WAKEUP_EXT_CB
1838 if (curr->wakeup_ext_cb != NULL)
1839 curr->wakeup_ext_cb(curr);
1840 #endif
1842 #ifdef HAVE_PRIORITY_SCHEDULING
1843 if (curr->blocker != NULL)
1844 wakeup_priority_protocol_release(curr);
1845 #endif
1846 corelock_unlock(ocl);
1848 /* else state == STATE_SLEEPING */
1850 remove_from_list_tmo(curr);
1852 RTR_LOCK(core);
1854 curr->state = STATE_RUNNING;
1856 add_to_list_l(&cores[core].running, curr);
1857 rtr_add_entry(core, curr->priority);
1859 RTR_UNLOCK(core);
1862 UNLOCK_THREAD(curr);
1865 cores[core].next_tmo_check = next_tmo_check;
1868 /*---------------------------------------------------------------------------
1869 * Performs operations that must be done before blocking a thread but after
1870 * the state is saved.
1871 *---------------------------------------------------------------------------
1873 #if NUM_CORES > 1
1874 static inline void run_blocking_ops(
1875 unsigned int core, struct thread_entry *thread)
1877 struct thread_blk_ops *ops = &cores[core].blk_ops;
1878 const unsigned flags = ops->flags;
1880 if (LIKELY(flags == TBOP_CLEAR))
1881 return;
1883 switch (flags)
1885 case TBOP_SWITCH_CORE:
1886 core_switch_blk_op(core, thread);
1887 /* Fall-through */
1888 case TBOP_UNLOCK_CORELOCK:
1889 corelock_unlock(ops->cl_p);
1890 break;
1893 ops->flags = TBOP_CLEAR;
1895 #endif /* NUM_CORES > 1 */
1897 #ifdef RB_PROFILE
1898 void profile_thread(void)
1900 profstart(cores[CURRENT_CORE].running - threads);
1902 #endif
1904 /*---------------------------------------------------------------------------
1905 * Prepares a thread to block on an object's list and/or for a specified
1906 * duration - expects object and slot to be appropriately locked if needed
1907 * and interrupts to be masked.
1908 *---------------------------------------------------------------------------
1910 static inline void block_thread_on_l(struct thread_entry *thread,
1911 unsigned state)
1913 /* If inlined, unreachable branches will be pruned with no size penalty
1914 because state is passed as a constant parameter. */
1915 const unsigned int core = IF_COP_CORE(thread->core);
1917 /* Remove the thread from the list of running threads. */
1918 RTR_LOCK(core);
1919 remove_from_list_l(&cores[core].running, thread);
1920 rtr_subtract_entry(core, thread->priority);
1921 RTR_UNLOCK(core);
1923 /* Add a timeout to the block if not infinite */
1924 switch (state)
1926 case STATE_BLOCKED:
1927 case STATE_BLOCKED_W_TMO:
1928 /* Put the thread into a new list of inactive threads. */
1929 add_to_list_l(thread->bqp, thread);
1931 if (state == STATE_BLOCKED)
1932 break;
1934 /* Fall-through */
1935 case STATE_SLEEPING:
1936 /* If this thread times out sooner than any other thread, update
1937 next_tmo_check to its timeout */
1938 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1940 cores[core].next_tmo_check = thread->tmo_tick;
1943 if (thread->tmo.prev == NULL)
1945 add_to_list_tmo(thread);
1947 /* else thread was never removed from list - just keep it there */
1948 break;
1951 /* Remember the the next thread about to block. */
1952 cores[core].block_task = thread;
1954 /* Report new state. */
1955 thread->state = state;
1958 /*---------------------------------------------------------------------------
1959 * Switch thread in round robin fashion for any given priority. Any thread
1960 * that removed itself from the running list first must specify itself in
1961 * the paramter.
1963 * INTERNAL: Intended for use by kernel and not for programs.
1964 *---------------------------------------------------------------------------
1966 void switch_thread(void)
1969 const unsigned int core = CURRENT_CORE;
1970 struct thread_entry *block = cores[core].block_task;
1971 struct thread_entry *thread = cores[core].running;
1973 /* Get context to save - next thread to run is unknown until all wakeups
1974 * are evaluated */
1975 if (block != NULL)
1977 cores[core].block_task = NULL;
1979 #if NUM_CORES > 1
1980 if (UNLIKELY(thread == block))
1982 /* This was the last thread running and another core woke us before
1983 * reaching here. Force next thread selection to give tmo threads or
1984 * other threads woken before this block a first chance. */
1985 block = NULL;
1987 else
1988 #endif
1990 /* Blocking task is the old one */
1991 thread = block;
1995 #ifdef RB_PROFILE
1996 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
1997 #endif
1999 /* Begin task switching by saving our current context so that we can
2000 * restore the state of the current thread later to the point prior
2001 * to this call. */
2002 store_context(&thread->context);
2004 /* Check if the current thread stack is overflown */
2005 if (UNLIKELY(thread->stack[0] != DEADBEEF))
2006 thread_stkov(thread);
2008 #if NUM_CORES > 1
2009 /* Run any blocking operations requested before switching/sleeping */
2010 run_blocking_ops(core, thread);
2011 #endif
2013 #ifdef HAVE_PRIORITY_SCHEDULING
2014 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2015 /* Reset the value of thread's skip count */
2016 thread->skip_count = 0;
2017 #endif
2019 for (;;)
2021 /* If there are threads on a timeout and the earliest wakeup is due,
2022 * check the list and wake any threads that need to start running
2023 * again. */
2024 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2026 check_tmo_threads();
2029 disable_irq();
2030 RTR_LOCK(core);
2032 thread = cores[core].running;
2034 if (UNLIKELY(thread == NULL))
2036 /* Enter sleep mode to reduce power usage - woken up on interrupt
2037 * or wakeup request from another core - expected to enable
2038 * interrupts. */
2039 RTR_UNLOCK(core);
2040 core_sleep(IF_COP(core));
2042 else
2044 #ifdef HAVE_PRIORITY_SCHEDULING
2045 /* Select the new task based on priorities and the last time a
2046 * process got CPU time relative to the highest priority runnable
2047 * task. */
2048 struct priority_distribution *pd = &cores[core].rtr;
2049 int max = find_first_set_bit(pd->mask);
2051 if (block == NULL)
2053 /* Not switching on a block, tentatively select next thread */
2054 thread = thread->l.next;
2057 for (;;)
2059 int priority = thread->priority;
2060 int diff;
2062 /* This ridiculously simple method of aging seems to work
2063 * suspiciously well. It does tend to reward CPU hogs (under
2064 * yielding) but that's generally not desirable at all. On the
2065 * plus side, it, relatively to other threads, penalizes excess
2066 * yielding which is good if some high priority thread is
2067 * performing no useful work such as polling for a device to be
2068 * ready. Of course, aging is only employed when higher and lower
2069 * priority threads are runnable. The highest priority runnable
2070 * thread(s) are never skipped. */
2071 if (LIKELY(priority <= max) ||
2072 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2073 (diff = priority - max, ++thread->skip_count > diff*diff))
2075 cores[core].running = thread;
2076 break;
2079 thread = thread->l.next;
2081 #else
2082 /* Without priority use a simple FCFS algorithm */
2083 if (block == NULL)
2085 /* Not switching on a block, select next thread */
2086 thread = thread->l.next;
2087 cores[core].running = thread;
2089 #endif /* HAVE_PRIORITY_SCHEDULING */
2091 RTR_UNLOCK(core);
2092 enable_irq();
2093 break;
2097 /* And finally give control to the next thread. */
2098 load_context(&thread->context);
2100 #ifdef RB_PROFILE
2101 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
2102 #endif
2106 /*---------------------------------------------------------------------------
2107 * Sleeps a thread for at least a specified number of ticks with zero being
2108 * a wait until the next tick.
2110 * INTERNAL: Intended for use by kernel and not for programs.
2111 *---------------------------------------------------------------------------
2113 void sleep_thread(int ticks)
2115 struct thread_entry *current = cores[CURRENT_CORE].running;
2117 LOCK_THREAD(current);
2119 /* Set our timeout, remove from run list and join timeout list. */
2120 current->tmo_tick = current_tick + ticks + 1;
2121 block_thread_on_l(current, STATE_SLEEPING);
2123 UNLOCK_THREAD(current);
2126 /*---------------------------------------------------------------------------
2127 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2129 * INTERNAL: Intended for use by kernel objects and not for programs.
2130 *---------------------------------------------------------------------------
2132 void block_thread(struct thread_entry *current)
2134 /* Set the state to blocked and take us off of the run queue until we
2135 * are explicitly woken */
2136 LOCK_THREAD(current);
2138 /* Set the list for explicit wakeup */
2139 block_thread_on_l(current, STATE_BLOCKED);
2141 #ifdef HAVE_PRIORITY_SCHEDULING
2142 if (current->blocker != NULL)
2144 /* Object supports PIP */
2145 current = blocker_inherit_priority(current);
2147 #endif
2149 UNLOCK_THREAD(current);
2152 /*---------------------------------------------------------------------------
2153 * Block a thread on a blocking queue for a specified time interval or until
2154 * explicitly woken - whichever happens first.
2156 * INTERNAL: Intended for use by kernel objects and not for programs.
2157 *---------------------------------------------------------------------------
2159 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2161 /* Get the entry for the current running thread. */
2162 LOCK_THREAD(current);
2164 /* Set the state to blocked with the specified timeout */
2165 current->tmo_tick = current_tick + timeout;
2167 /* Set the list for explicit wakeup */
2168 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2170 #ifdef HAVE_PRIORITY_SCHEDULING
2171 if (current->blocker != NULL)
2173 /* Object supports PIP */
2174 current = blocker_inherit_priority(current);
2176 #endif
2178 UNLOCK_THREAD(current);
2181 /*---------------------------------------------------------------------------
2182 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2183 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2185 * This code should be considered a critical section by the caller meaning
2186 * that the object's corelock should be held.
2188 * INTERNAL: Intended for use by kernel objects and not for programs.
2189 *---------------------------------------------------------------------------
2191 unsigned int wakeup_thread(struct thread_entry **list)
2193 struct thread_entry *thread = *list;
2194 unsigned int result = THREAD_NONE;
2196 /* Check if there is a blocked thread at all. */
2197 if (thread == NULL)
2198 return result;
2200 LOCK_THREAD(thread);
2202 /* Determine thread's current state. */
2203 switch (thread->state)
2205 case STATE_BLOCKED:
2206 case STATE_BLOCKED_W_TMO:
2207 remove_from_list_l(list, thread);
2209 result = THREAD_OK;
2211 #ifdef HAVE_PRIORITY_SCHEDULING
2212 struct thread_entry *current;
2213 struct blocker *bl = thread->blocker;
2215 if (bl == NULL)
2217 /* No inheritance - just boost the thread by aging */
2218 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2219 thread->skip_count = thread->priority;
2220 current = cores[CURRENT_CORE].running;
2222 else
2224 /* Call the specified unblocking PIP */
2225 current = bl->wakeup_protocol(thread);
2228 if (current != NULL && thread->priority < current->priority
2229 IF_COP( && thread->core == current->core ))
2231 /* Woken thread is higher priority and exists on the same CPU core;
2232 * recommend a task switch. Knowing if this is an interrupt call
2233 * would be helpful here. */
2234 result |= THREAD_SWITCH;
2236 #endif /* HAVE_PRIORITY_SCHEDULING */
2238 core_schedule_wakeup(thread);
2239 break;
2241 /* Nothing to do. State is not blocked. */
2242 #if THREAD_EXTRA_CHECKS
2243 default:
2244 THREAD_PANICF("wakeup_thread->block invalid", thread);
2245 case STATE_RUNNING:
2246 case STATE_KILLED:
2247 break;
2248 #endif
2251 UNLOCK_THREAD(thread);
2252 return result;
2255 /*---------------------------------------------------------------------------
2256 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2257 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2258 * the queue must be locked first.
2260 * INTERNAL: Intended for use by kernel objects and not for programs.
2261 *---------------------------------------------------------------------------
2263 unsigned int thread_queue_wake(struct thread_entry **list)
2265 unsigned result = THREAD_NONE;
2267 for (;;)
2269 unsigned int rc = wakeup_thread(list);
2271 if (rc == THREAD_NONE)
2272 break; /* No more threads */
2274 result |= rc;
2277 return result;
2280 /*---------------------------------------------------------------------------
2281 * Assign the thread slot a new ID. Version is 1-255.
2282 *---------------------------------------------------------------------------
2284 static void new_thread_id(unsigned int slot_num,
2285 struct thread_entry *thread)
2287 unsigned int version =
2288 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
2289 & THREAD_ID_VERSION_MASK;
2291 /* If wrapped to 0, make it 1 */
2292 if (version == 0)
2293 version = 1u << THREAD_ID_VERSION_SHIFT;
2295 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
2298 /*---------------------------------------------------------------------------
2299 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2300 * will be locked on multicore.
2301 *---------------------------------------------------------------------------
2303 static struct thread_entry * find_empty_thread_slot(void)
2305 /* Any slot could be on an interrupt-accessible list */
2306 IF_COP( int oldlevel = disable_irq_save(); )
2307 struct thread_entry *thread = NULL;
2308 int n;
2310 for (n = 0; n < MAXTHREADS; n++)
2312 /* Obtain current slot state - lock it on multicore */
2313 struct thread_entry *t = &threads[n];
2314 LOCK_THREAD(t);
2316 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2318 /* Slot is empty - leave it locked and caller will unlock */
2319 thread = t;
2320 break;
2323 /* Finished examining slot - no longer busy - unlock on multicore */
2324 UNLOCK_THREAD(t);
2327 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2328 not accesible to them yet */
2329 return thread;
2332 /*---------------------------------------------------------------------------
2333 * Return the thread_entry pointer for a thread_id. Return the current
2334 * thread if the ID is 0 (alias for current).
2335 *---------------------------------------------------------------------------
2337 struct thread_entry * thread_id_entry(unsigned int thread_id)
2339 return (thread_id == THREAD_ID_CURRENT) ?
2340 cores[CURRENT_CORE].running :
2341 &threads[thread_id & THREAD_ID_SLOT_MASK];
2344 /*---------------------------------------------------------------------------
2345 * Place the current core in idle mode - woken up on interrupt or wake
2346 * request from another core.
2347 *---------------------------------------------------------------------------
2349 void core_idle(void)
2351 IF_COP( const unsigned int core = CURRENT_CORE; )
2352 disable_irq();
2353 core_sleep(IF_COP(core));
2356 /*---------------------------------------------------------------------------
2357 * Create a thread. If using a dual core architecture, specify which core to
2358 * start the thread on.
2360 * Return ID if context area could be allocated, else NULL.
2361 *---------------------------------------------------------------------------
2363 unsigned int create_thread(void (*function)(void),
2364 void* stack, size_t stack_size,
2365 unsigned flags, const char *name
2366 IF_PRIO(, int priority)
2367 IF_COP(, unsigned int core))
2369 unsigned int i;
2370 unsigned int stack_words;
2371 uintptr_t stackptr, stackend;
2372 struct thread_entry *thread;
2373 unsigned state;
2374 int oldlevel;
2376 thread = find_empty_thread_slot();
2377 if (thread == NULL)
2379 return 0;
2382 oldlevel = disable_irq_save();
2384 /* Munge the stack to make it easy to spot stack overflows */
2385 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2386 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2387 stack_size = stackend - stackptr;
2388 stack_words = stack_size / sizeof (uintptr_t);
2390 for (i = 0; i < stack_words; i++)
2392 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2395 /* Store interesting information */
2396 thread->name = name;
2397 thread->stack = (uintptr_t *)stackptr;
2398 thread->stack_size = stack_size;
2399 thread->queue = NULL;
2400 #ifdef HAVE_WAKEUP_EXT_CB
2401 thread->wakeup_ext_cb = NULL;
2402 #endif
2403 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2404 thread->cpu_boost = 0;
2405 #endif
2406 #ifdef HAVE_PRIORITY_SCHEDULING
2407 memset(&thread->pdist, 0, sizeof(thread->pdist));
2408 thread->blocker = NULL;
2409 thread->base_priority = priority;
2410 thread->priority = priority;
2411 thread->skip_count = priority;
2412 prio_add_entry(&thread->pdist, priority);
2413 #endif
2415 #if NUM_CORES > 1
2416 thread->core = core;
2418 /* Writeback stack munging or anything else before starting */
2419 if (core != CURRENT_CORE)
2421 cpucache_flush();
2423 #endif
2425 /* Thread is not on any timeout list but be a bit paranoid */
2426 thread->tmo.prev = NULL;
2428 state = (flags & CREATE_THREAD_FROZEN) ?
2429 STATE_FROZEN : STATE_RUNNING;
2431 thread->context.sp = (typeof (thread->context.sp))stackend;
2433 /* Load the thread's context structure with needed startup information */
2434 THREAD_STARTUP_INIT(core, thread, function);
2436 thread->state = state;
2437 i = thread->id; /* Snapshot while locked */
2439 if (state == STATE_RUNNING)
2440 core_schedule_wakeup(thread);
2442 UNLOCK_THREAD(thread);
2443 restore_irq(oldlevel);
2445 return i;
2448 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2449 /*---------------------------------------------------------------------------
2450 * Change the boost state of a thread boosting or unboosting the CPU
2451 * as required.
2452 *---------------------------------------------------------------------------
2454 static inline void boost_thread(struct thread_entry *thread, bool boost)
2456 if ((thread->cpu_boost != 0) != boost)
2458 thread->cpu_boost = boost;
2459 cpu_boost(boost);
2463 void trigger_cpu_boost(void)
2465 struct thread_entry *current = cores[CURRENT_CORE].running;
2466 boost_thread(current, true);
2469 void cancel_cpu_boost(void)
2471 struct thread_entry *current = cores[CURRENT_CORE].running;
2472 boost_thread(current, false);
2474 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2476 /*---------------------------------------------------------------------------
2477 * Block the current thread until another thread terminates. A thread may
2478 * wait on itself to terminate which prevents it from running again and it
2479 * will need to be killed externally.
2480 * Parameter is the ID as returned from create_thread().
2481 *---------------------------------------------------------------------------
2483 void thread_wait(unsigned int thread_id)
2485 struct thread_entry *current = cores[CURRENT_CORE].running;
2486 struct thread_entry *thread = thread_id_entry(thread_id);
2488 /* Lock thread-as-waitable-object lock */
2489 corelock_lock(&thread->waiter_cl);
2491 /* Be sure it hasn't been killed yet */
2492 if (thread_id == THREAD_ID_CURRENT ||
2493 (thread->id == thread_id && thread->state != STATE_KILLED))
2495 IF_COP( current->obj_cl = &thread->waiter_cl; )
2496 current->bqp = &thread->queue;
2498 disable_irq();
2499 block_thread(current);
2501 corelock_unlock(&thread->waiter_cl);
2503 switch_thread();
2504 return;
2507 corelock_unlock(&thread->waiter_cl);
2510 /*---------------------------------------------------------------------------
2511 * Exit the current thread. The Right Way to Do Things (TM).
2512 *---------------------------------------------------------------------------
2514 void thread_exit(void)
2516 const unsigned int core = CURRENT_CORE;
2517 struct thread_entry *current = cores[core].running;
2519 /* Cancel CPU boost if any */
2520 cancel_cpu_boost();
2522 disable_irq();
2524 corelock_lock(&current->waiter_cl);
2525 LOCK_THREAD(current);
2527 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2528 if (current->name == THREAD_DESTRUCT)
2530 /* Thread being killed - become a waiter */
2531 unsigned int id = current->id;
2532 UNLOCK_THREAD(current);
2533 corelock_unlock(&current->waiter_cl);
2534 thread_wait(id);
2535 THREAD_PANICF("thread_exit->WK:*R", current);
2537 #endif
2539 #ifdef HAVE_PRIORITY_SCHEDULING
2540 check_for_obj_waiters("thread_exit", current);
2541 #endif
2543 if (current->tmo.prev != NULL)
2545 /* Cancel pending timeout list removal */
2546 remove_from_list_tmo(current);
2549 /* Switch tasks and never return */
2550 block_thread_on_l(current, STATE_KILLED);
2552 #if NUM_CORES > 1
2553 /* Switch to the idle stack if not on the main core (where "main"
2554 * runs) - we can hope gcc doesn't need the old stack beyond this
2555 * point. */
2556 if (core != CPU)
2558 switch_to_idle_stack(core);
2561 cpucache_flush();
2563 /* At this point, this thread isn't using resources allocated for
2564 * execution except the slot itself. */
2565 #endif
2567 /* Update ID for this slot */
2568 new_thread_id(current->id, current);
2569 current->name = NULL;
2571 /* Signal this thread */
2572 thread_queue_wake(&current->queue);
2573 corelock_unlock(&current->waiter_cl);
2574 /* Slot must be unusable until thread is really gone */
2575 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2576 switch_thread();
2577 /* This should never and must never be reached - if it is, the
2578 * state is corrupted */
2579 THREAD_PANICF("thread_exit->K:*R", current);
2582 #ifdef ALLOW_REMOVE_THREAD
2583 /*---------------------------------------------------------------------------
2584 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2585 * normal programs.
2587 * Parameter is the ID as returned from create_thread().
2589 * Use with care on threads that are not under careful control as this may
2590 * leave various objects in an undefined state.
2591 *---------------------------------------------------------------------------
2593 void remove_thread(unsigned int thread_id)
2595 #if NUM_CORES > 1
2596 /* core is not constant here because of core switching */
2597 unsigned int core = CURRENT_CORE;
2598 unsigned int old_core = NUM_CORES;
2599 struct corelock *ocl = NULL;
2600 #else
2601 const unsigned int core = CURRENT_CORE;
2602 #endif
2603 struct thread_entry *current = cores[core].running;
2604 struct thread_entry *thread = thread_id_entry(thread_id);
2606 unsigned state;
2607 int oldlevel;
2609 if (thread == current)
2610 thread_exit(); /* Current thread - do normal exit */
2612 oldlevel = disable_irq_save();
2614 corelock_lock(&thread->waiter_cl);
2615 LOCK_THREAD(thread);
2617 state = thread->state;
2619 if (thread->id != thread_id || state == STATE_KILLED)
2620 goto thread_killed;
2622 #if NUM_CORES > 1
2623 if (thread->name == THREAD_DESTRUCT)
2625 /* Thread being killed - become a waiter */
2626 UNLOCK_THREAD(thread);
2627 corelock_unlock(&thread->waiter_cl);
2628 restore_irq(oldlevel);
2629 thread_wait(thread_id);
2630 return;
2633 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2635 #ifdef HAVE_PRIORITY_SCHEDULING
2636 check_for_obj_waiters("remove_thread", thread);
2637 #endif
2639 if (thread->core != core)
2641 /* Switch cores and safely extract the thread there */
2642 /* Slot HAS to be unlocked or a deadlock could occur which means other
2643 * threads have to be guided into becoming thread waiters if they
2644 * attempt to remove it. */
2645 unsigned int new_core = thread->core;
2647 corelock_unlock(&thread->waiter_cl);
2649 UNLOCK_THREAD(thread);
2650 restore_irq(oldlevel);
2652 old_core = switch_core(new_core);
2654 oldlevel = disable_irq_save();
2656 corelock_lock(&thread->waiter_cl);
2657 LOCK_THREAD(thread);
2659 state = thread->state;
2660 core = new_core;
2661 /* Perform the extraction and switch ourselves back to the original
2662 processor */
2664 #endif /* NUM_CORES > 1 */
2666 if (thread->tmo.prev != NULL)
2668 /* Clean thread off the timeout list if a timeout check hasn't
2669 * run yet */
2670 remove_from_list_tmo(thread);
2673 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2674 /* Cancel CPU boost if any */
2675 boost_thread(thread, false);
2676 #endif
2678 IF_COP( retry_state: )
2680 switch (state)
2682 case STATE_RUNNING:
2683 RTR_LOCK(core);
2684 /* Remove thread from ready to run tasks */
2685 remove_from_list_l(&cores[core].running, thread);
2686 rtr_subtract_entry(core, thread->priority);
2687 RTR_UNLOCK(core);
2688 break;
2689 case STATE_BLOCKED:
2690 case STATE_BLOCKED_W_TMO:
2691 /* Remove thread from the queue it's blocked on - including its
2692 * own if waiting there */
2693 #if NUM_CORES > 1
2694 if (&thread->waiter_cl != thread->obj_cl)
2696 ocl = thread->obj_cl;
2698 if (UNLIKELY(corelock_try_lock(ocl) == 0))
2700 UNLOCK_THREAD(thread);
2701 corelock_lock(ocl);
2702 LOCK_THREAD(thread);
2704 if (UNLIKELY(thread->state != state))
2706 /* Something woke the thread */
2707 state = thread->state;
2708 corelock_unlock(ocl);
2709 goto retry_state;
2713 #endif
2714 remove_from_list_l(thread->bqp, thread);
2716 #ifdef HAVE_WAKEUP_EXT_CB
2717 if (thread->wakeup_ext_cb != NULL)
2718 thread->wakeup_ext_cb(thread);
2719 #endif
2721 #ifdef HAVE_PRIORITY_SCHEDULING
2722 if (thread->blocker != NULL)
2724 /* Remove thread's priority influence from its chain */
2725 wakeup_priority_protocol_release(thread);
2727 #endif
2729 #if NUM_CORES > 1
2730 if (ocl != NULL)
2731 corelock_unlock(ocl);
2732 #endif
2733 break;
2734 /* Otherwise thread is frozen and hasn't run yet */
2737 new_thread_id(thread_id, thread);
2738 thread->state = STATE_KILLED;
2740 /* If thread was waiting on itself, it will have been removed above.
2741 * The wrong order would result in waking the thread first and deadlocking
2742 * since the slot is already locked. */
2743 thread_queue_wake(&thread->queue);
2745 thread->name = NULL;
2747 thread_killed: /* Thread was already killed */
2748 /* Removal complete - safe to unlock and reenable interrupts */
2749 corelock_unlock(&thread->waiter_cl);
2750 UNLOCK_THREAD(thread);
2751 restore_irq(oldlevel);
2753 #if NUM_CORES > 1
2754 if (old_core < NUM_CORES)
2756 /* Did a removal on another processor's thread - switch back to
2757 native core */
2758 switch_core(old_core);
2760 #endif
2762 #endif /* ALLOW_REMOVE_THREAD */
2764 #ifdef HAVE_PRIORITY_SCHEDULING
2765 /*---------------------------------------------------------------------------
2766 * Sets the thread's relative base priority for the core it runs on. Any
2767 * needed inheritance changes also may happen.
2768 *---------------------------------------------------------------------------
2770 int thread_set_priority(unsigned int thread_id, int priority)
2772 int old_base_priority = -1;
2773 struct thread_entry *thread = thread_id_entry(thread_id);
2775 /* A little safety measure */
2776 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2777 return -1;
2779 /* Thread could be on any list and therefore on an interrupt accessible
2780 one - disable interrupts */
2781 int oldlevel = disable_irq_save();
2783 LOCK_THREAD(thread);
2785 /* Make sure it's not killed */
2786 if (thread_id == THREAD_ID_CURRENT ||
2787 (thread->id == thread_id && thread->state != STATE_KILLED))
2789 int old_priority = thread->priority;
2791 old_base_priority = thread->base_priority;
2792 thread->base_priority = priority;
2794 prio_move_entry(&thread->pdist, old_base_priority, priority);
2795 priority = find_first_set_bit(thread->pdist.mask);
2797 if (old_priority == priority)
2799 /* No priority change - do nothing */
2801 else if (thread->state == STATE_RUNNING)
2803 /* This thread is running - change location on the run
2804 * queue. No transitive inheritance needed. */
2805 set_running_thread_priority(thread, priority);
2807 else
2809 thread->priority = priority;
2811 if (thread->blocker != NULL)
2813 /* Bubble new priority down the chain */
2814 struct blocker *bl = thread->blocker; /* Blocker struct */
2815 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2816 struct thread_entry * const tstart = thread; /* Initial thread */
2817 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2819 for (;;)
2821 struct thread_entry *next; /* Next thread to check */
2822 int bl_pr; /* Highest blocked thread */
2823 int queue_pr; /* New highest blocked thread */
2824 #if NUM_CORES > 1
2825 /* Owner can change but thread cannot be dislodged - thread
2826 * may not be the first in the queue which allows other
2827 * threads ahead in the list to be given ownership during the
2828 * operation. If thread is next then the waker will have to
2829 * wait for us and the owner of the object will remain fixed.
2830 * If we successfully grab the owner -- which at some point
2831 * is guaranteed -- then the queue remains fixed until we
2832 * pass by. */
2833 for (;;)
2835 LOCK_THREAD(bl_t);
2837 /* Double-check the owner - retry if it changed */
2838 if (LIKELY(bl->thread == bl_t))
2839 break;
2841 UNLOCK_THREAD(bl_t);
2842 bl_t = bl->thread;
2844 #endif
2845 bl_pr = bl->priority;
2847 if (highest > bl_pr)
2848 break; /* Object priority won't change */
2850 /* This will include the thread being set */
2851 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2853 if (queue_pr == bl_pr)
2854 break; /* Object priority not changing */
2856 /* Update thread boost for this object */
2857 bl->priority = queue_pr;
2858 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2859 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2861 if (bl_t->priority == bl_pr)
2862 break; /* Blocking thread priority not changing */
2864 if (bl_t->state == STATE_RUNNING)
2866 /* Thread not blocked - we're done */
2867 set_running_thread_priority(bl_t, bl_pr);
2868 break;
2871 bl_t->priority = bl_pr;
2872 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2874 if (bl == NULL)
2875 break; /* End of chain */
2877 next = bl->thread;
2879 if (UNLIKELY(next == tstart))
2880 break; /* Full-circle */
2882 UNLOCK_THREAD(thread);
2884 thread = bl_t;
2885 bl_t = next;
2886 } /* for (;;) */
2888 UNLOCK_THREAD(bl_t);
2893 UNLOCK_THREAD(thread);
2895 restore_irq(oldlevel);
2897 return old_base_priority;
2900 /*---------------------------------------------------------------------------
2901 * Returns the current base priority for a thread.
2902 *---------------------------------------------------------------------------
2904 int thread_get_priority(unsigned int thread_id)
2906 struct thread_entry *thread = thread_id_entry(thread_id);
2907 int base_priority = thread->base_priority;
2909 /* Simply check without locking slot. It may or may not be valid by the
2910 * time the function returns anyway. If all tests pass, it is the
2911 * correct value for when it was valid. */
2912 if (thread_id != THREAD_ID_CURRENT &&
2913 (thread->id != thread_id || thread->state == STATE_KILLED))
2914 base_priority = -1;
2916 return base_priority;
2918 #endif /* HAVE_PRIORITY_SCHEDULING */
2920 /*---------------------------------------------------------------------------
2921 * Starts a frozen thread - similar semantics to wakeup_thread except that
2922 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2923 * virtue of the slot having a state of STATE_FROZEN.
2924 *---------------------------------------------------------------------------
2926 void thread_thaw(unsigned int thread_id)
2928 struct thread_entry *thread = thread_id_entry(thread_id);
2929 int oldlevel = disable_irq_save();
2931 LOCK_THREAD(thread);
2933 /* If thread is the current one, it cannot be frozen, therefore
2934 * there is no need to check that. */
2935 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2936 core_schedule_wakeup(thread);
2938 UNLOCK_THREAD(thread);
2939 restore_irq(oldlevel);
2942 /*---------------------------------------------------------------------------
2943 * Return the ID of the currently executing thread.
2944 *---------------------------------------------------------------------------
2946 unsigned int thread_get_current(void)
2948 return cores[CURRENT_CORE].running->id;
2951 #if NUM_CORES > 1
2952 /*---------------------------------------------------------------------------
2953 * Switch the processor that the currently executing thread runs on.
2954 *---------------------------------------------------------------------------
2956 unsigned int switch_core(unsigned int new_core)
2958 const unsigned int core = CURRENT_CORE;
2959 struct thread_entry *current = cores[core].running;
2961 if (core == new_core)
2963 /* No change - just return same core */
2964 return core;
2967 int oldlevel = disable_irq_save();
2968 LOCK_THREAD(current);
2970 if (current->name == THREAD_DESTRUCT)
2972 /* Thread being killed - deactivate and let process complete */
2973 unsigned int id = current->id;
2974 UNLOCK_THREAD(current);
2975 restore_irq(oldlevel);
2976 thread_wait(id);
2977 /* Should never be reached */
2978 THREAD_PANICF("switch_core->D:*R", current);
2981 /* Get us off the running list for the current core */
2982 RTR_LOCK(core);
2983 remove_from_list_l(&cores[core].running, current);
2984 rtr_subtract_entry(core, current->priority);
2985 RTR_UNLOCK(core);
2987 /* Stash return value (old core) in a safe place */
2988 current->retval = core;
2990 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2991 * the other core will likely attempt a removal from the wrong list! */
2992 if (current->tmo.prev != NULL)
2994 remove_from_list_tmo(current);
2997 /* Change the core number for this thread slot */
2998 current->core = new_core;
3000 /* Do not use core_schedule_wakeup here since this will result in
3001 * the thread starting to run on the other core before being finished on
3002 * this one. Delay the list unlock to keep the other core stuck
3003 * until this thread is ready. */
3004 RTR_LOCK(new_core);
3006 rtr_add_entry(new_core, current->priority);
3007 add_to_list_l(&cores[new_core].running, current);
3009 /* Make a callback into device-specific code, unlock the wakeup list so
3010 * that execution may resume on the new core, unlock our slot and finally
3011 * restore the interrupt level */
3012 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3013 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3014 cores[core].block_task = current;
3016 UNLOCK_THREAD(current);
3018 /* Alert other core to activity */
3019 core_wake(new_core);
3021 /* Do the stack switching, cache_maintenence and switch_thread call -
3022 requires native code */
3023 switch_thread_core(core, current);
3025 /* Finally return the old core to caller */
3026 return current->retval;
3028 #endif /* NUM_CORES > 1 */
3030 /*---------------------------------------------------------------------------
3031 * Initialize threading API. This assumes interrupts are not yet enabled. On
3032 * multicore setups, no core is allowed to proceed until create_thread calls
3033 * are safe to perform.
3034 *---------------------------------------------------------------------------
3036 void init_threads(void)
3038 const unsigned int core = CURRENT_CORE;
3039 struct thread_entry *thread;
3041 if (core == CPU)
3043 /* Initialize core locks and IDs in all slots */
3044 int n;
3045 for (n = 0; n < MAXTHREADS; n++)
3047 thread = &threads[n];
3048 corelock_init(&thread->waiter_cl);
3049 corelock_init(&thread->slot_cl);
3050 thread->id = THREAD_ID_INIT(n);
3054 /* CPU will initialize first and then sleep */
3055 thread = find_empty_thread_slot();
3057 if (thread == NULL)
3059 /* WTF? There really must be a slot available at this stage.
3060 * This can fail if, for example, .bss isn't zero'ed out by the loader
3061 * or threads is in the wrong section. */
3062 THREAD_PANICF("init_threads->no slot", NULL);
3065 /* Initialize initially non-zero members of core */
3066 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3068 /* Initialize initially non-zero members of slot */
3069 UNLOCK_THREAD(thread); /* No sync worries yet */
3070 thread->name = main_thread_name;
3071 thread->state = STATE_RUNNING;
3072 IF_COP( thread->core = core; )
3073 #ifdef HAVE_PRIORITY_SCHEDULING
3074 corelock_init(&cores[core].rtr_cl);
3075 thread->base_priority = PRIORITY_USER_INTERFACE;
3076 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3077 thread->priority = PRIORITY_USER_INTERFACE;
3078 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3079 #endif
3081 add_to_list_l(&cores[core].running, thread);
3083 if (core == CPU)
3085 thread->stack = stackbegin;
3086 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3087 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3088 /* Wait for other processors to finish their inits since create_thread
3089 * isn't safe to call until the kernel inits are done. The first
3090 * threads created in the system must of course be created by CPU.
3091 * Another possible approach is to initialize all cores and slots
3092 * for each core by CPU, let the remainder proceed in parallel and
3093 * signal CPU when all are finished. */
3094 core_thread_init(CPU);
3096 else
3098 /* Initial stack is the idle stack */
3099 thread->stack = idle_stacks[core];
3100 thread->stack_size = IDLE_STACK_SIZE;
3101 /* After last processor completes, it should signal all others to
3102 * proceed or may signal the next and call thread_exit(). The last one
3103 * to finish will signal CPU. */
3104 core_thread_init(core);
3105 /* Other cores do not have a main thread - go idle inside switch_thread
3106 * until a thread can run on the core. */
3107 thread_exit();
3108 #endif /* NUM_CORES */
3112 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3113 #if NUM_CORES == 1
3114 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3115 #else
3116 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3117 #endif
3119 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3120 unsigned int i;
3121 int usage = 0;
3123 for (i = 0; i < stack_words; i++)
3125 if (stackptr[i] != DEADBEEF)
3127 usage = ((stack_words - i) * 100) / stack_words;
3128 break;
3132 return usage;
3135 /*---------------------------------------------------------------------------
3136 * Returns the maximum percentage of stack a thread ever used while running.
3137 * NOTE: Some large buffer allocations that don't use enough the buffer to
3138 * overwrite stackptr[0] will not be seen.
3139 *---------------------------------------------------------------------------
3141 int thread_stack_usage(const struct thread_entry *thread)
3143 return stack_usage(thread->stack, thread->stack_size);
3146 #if NUM_CORES > 1
3147 /*---------------------------------------------------------------------------
3148 * Returns the maximum percentage of the core's idle stack ever used during
3149 * runtime.
3150 *---------------------------------------------------------------------------
3152 int idle_stack_usage(unsigned int core)
3154 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3156 #endif
3158 /*---------------------------------------------------------------------------
3159 * Fills in the buffer with the specified thread's name. If the name is NULL,
3160 * empty, or the thread is in destruct state a formatted ID is written
3161 * instead.
3162 *---------------------------------------------------------------------------
3164 void thread_get_name(char *buffer, int size,
3165 struct thread_entry *thread)
3167 if (size <= 0)
3168 return;
3170 *buffer = '\0';
3172 if (thread)
3174 /* Display thread name if one or ID if none */
3175 const char *name = thread->name;
3176 const char *fmt = "%s";
3177 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3179 name = (const char *)thread;
3180 fmt = "%08lX";
3182 snprintf(buffer, size, fmt, name);