Commit fs#9959 by Jack Halpin. Removes delays from the Sansa e200v2 button driver...
[kugel-rb.git] / firmware / thread.c
blob6efe8252e7122b08e7df568f937c45a2a80ea07a
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-r12, 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-r12, 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, 40($9) \n" /* Set initial sp(=$29) */
947 "jalr $8 \n" /* Start the thread */
948 "sw $0, 48($9) \n" /* Clear start address */
949 ".set at \n"
950 ".set reorder \n"
951 ::: "t0"
953 thread_exit();
956 /* Place context pointer in s0 slot, function pointer in s1 slot, and
957 * start_thread pointer in context_start */
958 #define THREAD_STARTUP_INIT(core, thread, function) \
959 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
960 (thread)->context.r[1] = (uint32_t)(function), \
961 (thread)->context.start = (uint32_t)start_thread; })
963 /*---------------------------------------------------------------------------
964 * Store non-volatile context.
965 *---------------------------------------------------------------------------
967 static inline void store_context(void* addr)
969 asm volatile (
970 ".set noreorder \n"
971 ".set noat \n"
972 "sw $16, 0(%0) \n" /* s0 */
973 "sw $17, 4(%0) \n" /* s1 */
974 "sw $18, 8(%0) \n" /* s2 */
975 "sw $19, 12(%0) \n" /* s3 */
976 "sw $20, 16(%0) \n" /* s4 */
977 "sw $21, 20(%0) \n" /* s5 */
978 "sw $22, 24(%0) \n" /* s6 */
979 "sw $23, 28(%0) \n" /* s7 */
980 "sw $28, 32(%0) \n" /* gp */
981 "sw $30, 36(%0) \n" /* fp */
982 "sw $29, 40(%0) \n" /* sp */
983 "sw $31, 44(%0) \n" /* ra */
984 ".set at \n"
985 ".set reorder \n"
986 : : "r" (addr)
990 /*---------------------------------------------------------------------------
991 * Load non-volatile context.
992 *---------------------------------------------------------------------------
994 static inline void load_context(const void* addr)
996 asm volatile (
997 ".set noat \n"
998 ".set noreorder \n"
999 "lw $8, 48(%0) \n" /* Get start address ($8 = t0) */
1000 "beqz $8, running \n" /* NULL -> already running */
1001 "nop \n"
1002 "jr $8 \n"
1003 "move $9, %0 \n" /* t1 = context */
1004 "running: \n"
1005 "lw $16, 0(%0) \n" /* s0 */
1006 "lw $17, 4(%0) \n" /* s1 */
1007 "lw $18, 8(%0) \n" /* s2 */
1008 "lw $19, 12(%0) \n" /* s3 */
1009 "lw $20, 16(%0) \n" /* s4 */
1010 "lw $21, 20(%0) \n" /* s5 */
1011 "lw $22, 24(%0) \n" /* s6 */
1012 "lw $23, 28(%0) \n" /* s7 */
1013 "lw $28, 32(%0) \n" /* gp */
1014 "lw $30, 36(%0) \n" /* fp */
1015 "lw $29, 40(%0) \n" /* sp */
1016 "lw $31, 44(%0) \n" /* ra */
1017 ".set at \n"
1018 ".set reorder \n"
1019 : : "r" (addr) : "t0", "t1"
1023 /*---------------------------------------------------------------------------
1024 * Put core in a power-saving state.
1025 *---------------------------------------------------------------------------
1027 static inline void core_sleep(void)
1029 #if CONFIG_CPU == JZ4732
1030 __cpm_idle_mode();
1031 #endif
1032 asm volatile(".set mips32r2 \n"
1033 "mfc0 $8, $12 \n" /* mfc t0, $12 */
1034 "move $9, $8 \n" /* move t1, t0 */
1035 "la $10, 0x8000000 \n" /* la t2, 0x8000000 */
1036 "or $8, $8, $10 \n" /* Enable reduced power mode */
1037 "mtc0 $8, $12 \n"
1038 "wait \n"
1039 "mtc0 $9, $12 \n"
1040 ".set mips0 \n"
1041 ::: "t0", "t1", "t2"
1043 enable_irq();
1047 #endif /* CONFIG_CPU == */
1050 * End Processor-specific section
1051 ***************************************************************************/
1053 #if THREAD_EXTRA_CHECKS
1054 static void thread_panicf(const char *msg, struct thread_entry *thread)
1056 IF_COP( const unsigned int core = thread->core; )
1057 static char name[32];
1058 thread_get_name(name, 32, thread);
1059 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1061 static void thread_stkov(struct thread_entry *thread)
1063 thread_panicf("Stkov", thread);
1065 #define THREAD_PANICF(msg, thread) \
1066 thread_panicf(msg, thread)
1067 #define THREAD_ASSERT(exp, msg, thread) \
1068 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1069 #else
1070 static void thread_stkov(struct thread_entry *thread)
1072 IF_COP( const unsigned int core = thread->core; )
1073 static char name[32];
1074 thread_get_name(name, 32, thread);
1075 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1077 #define THREAD_PANICF(msg, thread)
1078 #define THREAD_ASSERT(exp, msg, thread)
1079 #endif /* THREAD_EXTRA_CHECKS */
1081 /* Thread locking */
1082 #if NUM_CORES > 1
1083 #define LOCK_THREAD(thread) \
1084 ({ corelock_lock(&(thread)->slot_cl); })
1085 #define TRY_LOCK_THREAD(thread) \
1086 ({ corelock_try_lock(&thread->slot_cl); })
1087 #define UNLOCK_THREAD(thread) \
1088 ({ corelock_unlock(&(thread)->slot_cl); })
1089 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1090 ({ unsigned int _core = (thread)->core; \
1091 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1092 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1093 #else
1094 #define LOCK_THREAD(thread) \
1095 ({ })
1096 #define TRY_LOCK_THREAD(thread) \
1097 ({ })
1098 #define UNLOCK_THREAD(thread) \
1099 ({ })
1100 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1101 ({ })
1102 #endif
1104 /* RTR list */
1105 #define RTR_LOCK(core) \
1106 ({ corelock_lock(&cores[core].rtr_cl); })
1107 #define RTR_UNLOCK(core) \
1108 ({ corelock_unlock(&cores[core].rtr_cl); })
1110 #ifdef HAVE_PRIORITY_SCHEDULING
1111 #define rtr_add_entry(core, priority) \
1112 prio_add_entry(&cores[core].rtr, (priority))
1114 #define rtr_subtract_entry(core, priority) \
1115 prio_subtract_entry(&cores[core].rtr, (priority))
1117 #define rtr_move_entry(core, from, to) \
1118 prio_move_entry(&cores[core].rtr, (from), (to))
1119 #else
1120 #define rtr_add_entry(core, priority)
1121 #define rtr_add_entry_inl(core, priority)
1122 #define rtr_subtract_entry(core, priority)
1123 #define rtr_subtract_entry_inl(core, priotity)
1124 #define rtr_move_entry(core, from, to)
1125 #define rtr_move_entry_inl(core, from, to)
1126 #endif
1128 /*---------------------------------------------------------------------------
1129 * Thread list structure - circular:
1130 * +------------------------------+
1131 * | |
1132 * +--+---+<-+---+<-+---+<-+---+<-+
1133 * Head->| T | | T | | T | | T |
1134 * +->+---+->+---+->+---+->+---+--+
1135 * | |
1136 * +------------------------------+
1137 *---------------------------------------------------------------------------
1140 /*---------------------------------------------------------------------------
1141 * Adds a thread to a list of threads using "insert last". Uses the "l"
1142 * links.
1143 *---------------------------------------------------------------------------
1145 static void add_to_list_l(struct thread_entry **list,
1146 struct thread_entry *thread)
1148 struct thread_entry *l = *list;
1150 if (l == NULL)
1152 /* Insert into unoccupied list */
1153 thread->l.prev = thread;
1154 thread->l.next = thread;
1155 *list = thread;
1156 return;
1159 /* Insert last */
1160 thread->l.prev = l->l.prev;
1161 thread->l.next = l;
1162 l->l.prev->l.next = thread;
1163 l->l.prev = thread;
1166 /*---------------------------------------------------------------------------
1167 * Removes a thread from a list of threads. Uses the "l" links.
1168 *---------------------------------------------------------------------------
1170 static void remove_from_list_l(struct thread_entry **list,
1171 struct thread_entry *thread)
1173 struct thread_entry *prev, *next;
1175 next = thread->l.next;
1177 if (thread == next)
1179 /* The only item */
1180 *list = NULL;
1181 return;
1184 if (thread == *list)
1186 /* List becomes next item */
1187 *list = next;
1190 prev = thread->l.prev;
1192 /* Fix links to jump over the removed entry. */
1193 next->l.prev = prev;
1194 prev->l.next = next;
1197 /*---------------------------------------------------------------------------
1198 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1199 * NULL-terminated forward (to ease the far more common forward traversal):
1200 * +------------------------------+
1201 * | |
1202 * +--+---+<-+---+<-+---+<-+---+<-+
1203 * Head->| T | | T | | T | | T |
1204 * +---+->+---+->+---+->+---+-X
1205 *---------------------------------------------------------------------------
1208 /*---------------------------------------------------------------------------
1209 * Add a thread from the core's timout list by linking the pointers in its
1210 * tmo structure.
1211 *---------------------------------------------------------------------------
1213 static void add_to_list_tmo(struct thread_entry *thread)
1215 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1216 THREAD_ASSERT(thread->tmo.prev == NULL,
1217 "add_to_list_tmo->already listed", thread);
1219 thread->tmo.next = NULL;
1221 if (tmo == NULL)
1223 /* Insert into unoccupied list */
1224 thread->tmo.prev = thread;
1225 cores[IF_COP_CORE(thread->core)].timeout = thread;
1226 return;
1229 /* Insert Last */
1230 thread->tmo.prev = tmo->tmo.prev;
1231 tmo->tmo.prev->tmo.next = thread;
1232 tmo->tmo.prev = thread;
1235 /*---------------------------------------------------------------------------
1236 * Remove a thread from the core's timout list by unlinking the pointers in
1237 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1238 * is cancelled.
1239 *---------------------------------------------------------------------------
1241 static void remove_from_list_tmo(struct thread_entry *thread)
1243 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1244 struct thread_entry *prev = thread->tmo.prev;
1245 struct thread_entry *next = thread->tmo.next;
1247 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1249 if (next != NULL)
1250 next->tmo.prev = prev;
1252 if (thread == *list)
1254 /* List becomes next item and empty if next == NULL */
1255 *list = next;
1256 /* Mark as unlisted */
1257 thread->tmo.prev = NULL;
1259 else
1261 if (next == NULL)
1262 (*list)->tmo.prev = prev;
1263 prev->tmo.next = next;
1264 /* Mark as unlisted */
1265 thread->tmo.prev = NULL;
1270 #ifdef HAVE_PRIORITY_SCHEDULING
1271 /*---------------------------------------------------------------------------
1272 * Priority distribution structure (one category for each possible priority):
1274 * +----+----+----+ ... +-----+
1275 * hist: | F0 | F1 | F2 | | F31 |
1276 * +----+----+----+ ... +-----+
1277 * mask: | b0 | b1 | b2 | | b31 |
1278 * +----+----+----+ ... +-----+
1280 * F = count of threads at priority category n (frequency)
1281 * b = bitmask of non-zero priority categories (occupancy)
1283 * / if H[n] != 0 : 1
1284 * b[n] = |
1285 * \ else : 0
1287 *---------------------------------------------------------------------------
1288 * Basic priority inheritance priotocol (PIP):
1290 * Mn = mutex n, Tn = thread n
1292 * A lower priority thread inherits the priority of the highest priority
1293 * thread blocked waiting for it to complete an action (such as release a
1294 * mutex or respond to a message via queue_send):
1296 * 1) T2->M1->T1
1298 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1299 * priority than T1 then T1 inherits the priority of T2.
1301 * 2) T3
1302 * \/
1303 * T2->M1->T1
1305 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1306 * T1 inherits the higher of T2 and T3.
1308 * 3) T3->M2->T2->M1->T1
1310 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1311 * then T1 inherits the priority of T3 through T2.
1313 * Blocking chains can grow arbitrarily complex (though it's best that they
1314 * not form at all very often :) and build-up from these units.
1315 *---------------------------------------------------------------------------
1318 /*---------------------------------------------------------------------------
1319 * Increment frequency at category "priority"
1320 *---------------------------------------------------------------------------
1322 static inline unsigned int prio_add_entry(
1323 struct priority_distribution *pd, int priority)
1325 unsigned int count;
1326 /* Enough size/instruction count difference for ARM makes it worth it to
1327 * use different code (192 bytes for ARM). Only thing better is ASM. */
1328 #ifdef CPU_ARM
1329 count = pd->hist[priority];
1330 if (++count == 1)
1331 pd->mask |= 1 << priority;
1332 pd->hist[priority] = count;
1333 #else /* This one's better for Coldfire */
1334 if ((count = ++pd->hist[priority]) == 1)
1335 pd->mask |= 1 << priority;
1336 #endif
1338 return count;
1341 /*---------------------------------------------------------------------------
1342 * Decrement frequency at category "priority"
1343 *---------------------------------------------------------------------------
1345 static inline unsigned int prio_subtract_entry(
1346 struct priority_distribution *pd, int priority)
1348 unsigned int count;
1350 #ifdef CPU_ARM
1351 count = pd->hist[priority];
1352 if (--count == 0)
1353 pd->mask &= ~(1 << priority);
1354 pd->hist[priority] = count;
1355 #else
1356 if ((count = --pd->hist[priority]) == 0)
1357 pd->mask &= ~(1 << priority);
1358 #endif
1360 return count;
1363 /*---------------------------------------------------------------------------
1364 * Remove from one category and add to another
1365 *---------------------------------------------------------------------------
1367 static inline void prio_move_entry(
1368 struct priority_distribution *pd, int from, int to)
1370 uint32_t mask = pd->mask;
1372 #ifdef CPU_ARM
1373 unsigned int count;
1375 count = pd->hist[from];
1376 if (--count == 0)
1377 mask &= ~(1 << from);
1378 pd->hist[from] = count;
1380 count = pd->hist[to];
1381 if (++count == 1)
1382 mask |= 1 << to;
1383 pd->hist[to] = count;
1384 #else
1385 if (--pd->hist[from] == 0)
1386 mask &= ~(1 << from);
1388 if (++pd->hist[to] == 1)
1389 mask |= 1 << to;
1390 #endif
1392 pd->mask = mask;
1395 /*---------------------------------------------------------------------------
1396 * Change the priority and rtr entry for a running thread
1397 *---------------------------------------------------------------------------
1399 static inline void set_running_thread_priority(
1400 struct thread_entry *thread, int priority)
1402 const unsigned int core = IF_COP_CORE(thread->core);
1403 RTR_LOCK(core);
1404 rtr_move_entry(core, thread->priority, priority);
1405 thread->priority = priority;
1406 RTR_UNLOCK(core);
1409 /*---------------------------------------------------------------------------
1410 * Finds the highest priority thread in a list of threads. If the list is
1411 * empty, the PRIORITY_IDLE is returned.
1413 * It is possible to use the struct priority_distribution within an object
1414 * instead of scanning the remaining threads in the list but as a compromise,
1415 * the resulting per-object memory overhead is saved at a slight speed
1416 * penalty under high contention.
1417 *---------------------------------------------------------------------------
1419 static int find_highest_priority_in_list_l(
1420 struct thread_entry * const thread)
1422 if (LIKELY(thread != NULL))
1424 /* Go though list until the ending up at the initial thread */
1425 int highest_priority = thread->priority;
1426 struct thread_entry *curr = thread;
1430 int priority = curr->priority;
1432 if (priority < highest_priority)
1433 highest_priority = priority;
1435 curr = curr->l.next;
1437 while (curr != thread);
1439 return highest_priority;
1442 return PRIORITY_IDLE;
1445 /*---------------------------------------------------------------------------
1446 * Register priority with blocking system and bubble it down the chain if
1447 * any until we reach the end or something is already equal or higher.
1449 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1450 * targets but that same action also guarantees a circular block anyway and
1451 * those are prevented, right? :-)
1452 *---------------------------------------------------------------------------
1454 static struct thread_entry *
1455 blocker_inherit_priority(struct thread_entry *current)
1457 const int priority = current->priority;
1458 struct blocker *bl = current->blocker;
1459 struct thread_entry * const tstart = current;
1460 struct thread_entry *bl_t = bl->thread;
1462 /* Blocker cannot change since the object protection is held */
1463 LOCK_THREAD(bl_t);
1465 for (;;)
1467 struct thread_entry *next;
1468 int bl_pr = bl->priority;
1470 if (priority >= bl_pr)
1471 break; /* Object priority already high enough */
1473 bl->priority = priority;
1475 /* Add this one */
1476 prio_add_entry(&bl_t->pdist, priority);
1478 if (bl_pr < PRIORITY_IDLE)
1480 /* Not first waiter - subtract old one */
1481 prio_subtract_entry(&bl_t->pdist, bl_pr);
1484 if (priority >= bl_t->priority)
1485 break; /* Thread priority high enough */
1487 if (bl_t->state == STATE_RUNNING)
1489 /* Blocking thread is a running thread therefore there are no
1490 * further blockers. Change the "run queue" on which it
1491 * resides. */
1492 set_running_thread_priority(bl_t, priority);
1493 break;
1496 bl_t->priority = priority;
1498 /* If blocking thread has a blocker, apply transitive inheritance */
1499 bl = bl_t->blocker;
1501 if (bl == NULL)
1502 break; /* End of chain or object doesn't support inheritance */
1504 next = bl->thread;
1506 if (UNLIKELY(next == tstart))
1507 break; /* Full-circle - deadlock! */
1509 UNLOCK_THREAD(current);
1511 #if NUM_CORES > 1
1512 for (;;)
1514 LOCK_THREAD(next);
1516 /* Blocker could change - retest condition */
1517 if (LIKELY(bl->thread == next))
1518 break;
1520 UNLOCK_THREAD(next);
1521 next = bl->thread;
1523 #endif
1524 current = bl_t;
1525 bl_t = next;
1528 UNLOCK_THREAD(bl_t);
1530 return current;
1533 /*---------------------------------------------------------------------------
1534 * Readjust priorities when waking a thread blocked waiting for another
1535 * in essence "releasing" the thread's effect on the object owner. Can be
1536 * performed from any context.
1537 *---------------------------------------------------------------------------
1539 struct thread_entry *
1540 wakeup_priority_protocol_release(struct thread_entry *thread)
1542 const int priority = thread->priority;
1543 struct blocker *bl = thread->blocker;
1544 struct thread_entry * const tstart = thread;
1545 struct thread_entry *bl_t = bl->thread;
1547 /* Blocker cannot change since object will be locked */
1548 LOCK_THREAD(bl_t);
1550 thread->blocker = NULL; /* Thread not blocked */
1552 for (;;)
1554 struct thread_entry *next;
1555 int bl_pr = bl->priority;
1557 if (priority > bl_pr)
1558 break; /* Object priority higher */
1560 next = *thread->bqp;
1562 if (next == NULL)
1564 /* No more threads in queue */
1565 prio_subtract_entry(&bl_t->pdist, bl_pr);
1566 bl->priority = PRIORITY_IDLE;
1568 else
1570 /* Check list for highest remaining priority */
1571 int queue_pr = find_highest_priority_in_list_l(next);
1573 if (queue_pr == bl_pr)
1574 break; /* Object priority not changing */
1576 /* Change queue priority */
1577 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1578 bl->priority = queue_pr;
1581 if (bl_pr > bl_t->priority)
1582 break; /* thread priority is higher */
1584 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1586 if (bl_pr == bl_t->priority)
1587 break; /* Thread priority not changing */
1589 if (bl_t->state == STATE_RUNNING)
1591 /* No further blockers */
1592 set_running_thread_priority(bl_t, bl_pr);
1593 break;
1596 bl_t->priority = bl_pr;
1598 /* If blocking thread has a blocker, apply transitive inheritance */
1599 bl = bl_t->blocker;
1601 if (bl == NULL)
1602 break; /* End of chain or object doesn't support inheritance */
1604 next = bl->thread;
1606 if (UNLIKELY(next == tstart))
1607 break; /* Full-circle - deadlock! */
1609 UNLOCK_THREAD(thread);
1611 #if NUM_CORES > 1
1612 for (;;)
1614 LOCK_THREAD(next);
1616 /* Blocker could change - retest condition */
1617 if (LIKELY(bl->thread == next))
1618 break;
1620 UNLOCK_THREAD(next);
1621 next = bl->thread;
1623 #endif
1624 thread = bl_t;
1625 bl_t = next;
1628 UNLOCK_THREAD(bl_t);
1630 #if NUM_CORES > 1
1631 if (UNLIKELY(thread != tstart))
1633 /* Relock original if it changed */
1634 LOCK_THREAD(tstart);
1636 #endif
1638 return cores[CURRENT_CORE].running;
1641 /*---------------------------------------------------------------------------
1642 * Transfer ownership to a thread waiting for an objects and transfer
1643 * inherited priority boost from other waiters. This algorithm knows that
1644 * blocking chains may only unblock from the very end.
1646 * Only the owning thread itself may call this and so the assumption that
1647 * it is the running thread is made.
1648 *---------------------------------------------------------------------------
1650 struct thread_entry *
1651 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1653 /* Waking thread inherits priority boost from object owner */
1654 struct blocker *bl = thread->blocker;
1655 struct thread_entry *bl_t = bl->thread;
1656 struct thread_entry *next;
1657 int bl_pr;
1659 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
1660 "UPPT->wrong thread", cores[CURRENT_CORE].running);
1662 LOCK_THREAD(bl_t);
1664 bl_pr = bl->priority;
1666 /* Remove the object's boost from the owning thread */
1667 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1668 bl_pr <= bl_t->priority)
1670 /* No more threads at this priority are waiting and the old level is
1671 * at least the thread level */
1672 int priority = find_first_set_bit(bl_t->pdist.mask);
1674 if (priority != bl_t->priority)
1676 /* Adjust this thread's priority */
1677 set_running_thread_priority(bl_t, priority);
1681 next = *thread->bqp;
1683 if (LIKELY(next == NULL))
1685 /* Expected shortcut - no more waiters */
1686 bl_pr = PRIORITY_IDLE;
1688 else
1690 if (thread->priority <= bl_pr)
1692 /* Need to scan threads remaining in queue */
1693 bl_pr = find_highest_priority_in_list_l(next);
1696 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1697 bl_pr < thread->priority)
1699 /* Thread priority must be raised */
1700 thread->priority = bl_pr;
1704 bl->thread = thread; /* This thread pwns */
1705 bl->priority = bl_pr; /* Save highest blocked priority */
1706 thread->blocker = NULL; /* Thread not blocked */
1708 UNLOCK_THREAD(bl_t);
1710 return bl_t;
1713 /*---------------------------------------------------------------------------
1714 * No threads must be blocked waiting for this thread except for it to exit.
1715 * The alternative is more elaborate cleanup and object registration code.
1716 * Check this for risk of silent data corruption when objects with
1717 * inheritable blocking are abandoned by the owner - not precise but may
1718 * catch something.
1719 *---------------------------------------------------------------------------
1721 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1723 /* Only one bit in the mask should be set with a frequency on 1 which
1724 * represents the thread's own base priority */
1725 uint32_t mask = thread->pdist.mask;
1726 if ((mask & (mask - 1)) != 0 ||
1727 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1729 unsigned char name[32];
1730 thread_get_name(name, 32, thread);
1731 panicf("%s->%s with obj. waiters", function, name);
1734 #endif /* HAVE_PRIORITY_SCHEDULING */
1736 /*---------------------------------------------------------------------------
1737 * Move a thread back to a running state on its core.
1738 *---------------------------------------------------------------------------
1740 static void core_schedule_wakeup(struct thread_entry *thread)
1742 const unsigned int core = IF_COP_CORE(thread->core);
1744 RTR_LOCK(core);
1746 thread->state = STATE_RUNNING;
1748 add_to_list_l(&cores[core].running, thread);
1749 rtr_add_entry(core, thread->priority);
1751 RTR_UNLOCK(core);
1753 #if NUM_CORES > 1
1754 if (core != CURRENT_CORE)
1755 core_wake(core);
1756 #endif
1759 /*---------------------------------------------------------------------------
1760 * Check the core's timeout list when at least one thread is due to wake.
1761 * Filtering for the condition is done before making the call. Resets the
1762 * tick when the next check will occur.
1763 *---------------------------------------------------------------------------
1765 void check_tmo_threads(void)
1767 const unsigned int core = CURRENT_CORE;
1768 const long tick = current_tick; /* snapshot the current tick */
1769 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1770 struct thread_entry *next = cores[core].timeout;
1772 /* If there are no processes waiting for a timeout, just keep the check
1773 tick from falling into the past. */
1775 /* Break the loop once we have walked through the list of all
1776 * sleeping processes or have removed them all. */
1777 while (next != NULL)
1779 /* Check sleeping threads. Allow interrupts between checks. */
1780 enable_irq();
1782 struct thread_entry *curr = next;
1784 next = curr->tmo.next;
1786 /* Lock thread slot against explicit wakeup */
1787 disable_irq();
1788 LOCK_THREAD(curr);
1790 unsigned state = curr->state;
1792 if (state < TIMEOUT_STATE_FIRST)
1794 /* Cleanup threads no longer on a timeout but still on the
1795 * list. */
1796 remove_from_list_tmo(curr);
1798 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
1800 /* Timeout still pending - this will be the usual case */
1801 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1803 /* Earliest timeout found so far - move the next check up
1804 to its time */
1805 next_tmo_check = curr->tmo_tick;
1808 else
1810 /* Sleep timeout has been reached so bring the thread back to
1811 * life again. */
1812 if (state == STATE_BLOCKED_W_TMO)
1814 #if NUM_CORES > 1
1815 /* Lock the waiting thread's kernel object */
1816 struct corelock *ocl = curr->obj_cl;
1818 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1820 /* Need to retry in the correct order though the need is
1821 * unlikely */
1822 UNLOCK_THREAD(curr);
1823 corelock_lock(ocl);
1824 LOCK_THREAD(curr);
1826 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
1828 /* Thread was woken or removed explicitely while slot
1829 * was unlocked */
1830 corelock_unlock(ocl);
1831 remove_from_list_tmo(curr);
1832 UNLOCK_THREAD(curr);
1833 continue;
1836 #endif /* NUM_CORES */
1838 remove_from_list_l(curr->bqp, curr);
1840 #ifdef HAVE_WAKEUP_EXT_CB
1841 if (curr->wakeup_ext_cb != NULL)
1842 curr->wakeup_ext_cb(curr);
1843 #endif
1845 #ifdef HAVE_PRIORITY_SCHEDULING
1846 if (curr->blocker != NULL)
1847 wakeup_priority_protocol_release(curr);
1848 #endif
1849 corelock_unlock(ocl);
1851 /* else state == STATE_SLEEPING */
1853 remove_from_list_tmo(curr);
1855 RTR_LOCK(core);
1857 curr->state = STATE_RUNNING;
1859 add_to_list_l(&cores[core].running, curr);
1860 rtr_add_entry(core, curr->priority);
1862 RTR_UNLOCK(core);
1865 UNLOCK_THREAD(curr);
1868 cores[core].next_tmo_check = next_tmo_check;
1871 /*---------------------------------------------------------------------------
1872 * Performs operations that must be done before blocking a thread but after
1873 * the state is saved.
1874 *---------------------------------------------------------------------------
1876 #if NUM_CORES > 1
1877 static inline void run_blocking_ops(
1878 unsigned int core, struct thread_entry *thread)
1880 struct thread_blk_ops *ops = &cores[core].blk_ops;
1881 const unsigned flags = ops->flags;
1883 if (LIKELY(flags == TBOP_CLEAR))
1884 return;
1886 switch (flags)
1888 case TBOP_SWITCH_CORE:
1889 core_switch_blk_op(core, thread);
1890 /* Fall-through */
1891 case TBOP_UNLOCK_CORELOCK:
1892 corelock_unlock(ops->cl_p);
1893 break;
1896 ops->flags = TBOP_CLEAR;
1898 #endif /* NUM_CORES > 1 */
1900 #ifdef RB_PROFILE
1901 void profile_thread(void)
1903 profstart(cores[CURRENT_CORE].running - threads);
1905 #endif
1907 /*---------------------------------------------------------------------------
1908 * Prepares a thread to block on an object's list and/or for a specified
1909 * duration - expects object and slot to be appropriately locked if needed
1910 * and interrupts to be masked.
1911 *---------------------------------------------------------------------------
1913 static inline void block_thread_on_l(struct thread_entry *thread,
1914 unsigned state)
1916 /* If inlined, unreachable branches will be pruned with no size penalty
1917 because state is passed as a constant parameter. */
1918 const unsigned int core = IF_COP_CORE(thread->core);
1920 /* Remove the thread from the list of running threads. */
1921 RTR_LOCK(core);
1922 remove_from_list_l(&cores[core].running, thread);
1923 rtr_subtract_entry(core, thread->priority);
1924 RTR_UNLOCK(core);
1926 /* Add a timeout to the block if not infinite */
1927 switch (state)
1929 case STATE_BLOCKED:
1930 case STATE_BLOCKED_W_TMO:
1931 /* Put the thread into a new list of inactive threads. */
1932 add_to_list_l(thread->bqp, thread);
1934 if (state == STATE_BLOCKED)
1935 break;
1937 /* Fall-through */
1938 case STATE_SLEEPING:
1939 /* If this thread times out sooner than any other thread, update
1940 next_tmo_check to its timeout */
1941 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1943 cores[core].next_tmo_check = thread->tmo_tick;
1946 if (thread->tmo.prev == NULL)
1948 add_to_list_tmo(thread);
1950 /* else thread was never removed from list - just keep it there */
1951 break;
1954 /* Remember the the next thread about to block. */
1955 cores[core].block_task = thread;
1957 /* Report new state. */
1958 thread->state = state;
1961 /*---------------------------------------------------------------------------
1962 * Switch thread in round robin fashion for any given priority. Any thread
1963 * that removed itself from the running list first must specify itself in
1964 * the paramter.
1966 * INTERNAL: Intended for use by kernel and not for programs.
1967 *---------------------------------------------------------------------------
1969 void switch_thread(void)
1972 const unsigned int core = CURRENT_CORE;
1973 struct thread_entry *block = cores[core].block_task;
1974 struct thread_entry *thread = cores[core].running;
1976 /* Get context to save - next thread to run is unknown until all wakeups
1977 * are evaluated */
1978 if (block != NULL)
1980 cores[core].block_task = NULL;
1982 #if NUM_CORES > 1
1983 if (UNLIKELY(thread == block))
1985 /* This was the last thread running and another core woke us before
1986 * reaching here. Force next thread selection to give tmo threads or
1987 * other threads woken before this block a first chance. */
1988 block = NULL;
1990 else
1991 #endif
1993 /* Blocking task is the old one */
1994 thread = block;
1998 #ifdef RB_PROFILE
1999 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
2000 #endif
2002 /* Begin task switching by saving our current context so that we can
2003 * restore the state of the current thread later to the point prior
2004 * to this call. */
2005 store_context(&thread->context);
2007 /* Check if the current thread stack is overflown */
2008 if (UNLIKELY(thread->stack[0] != DEADBEEF))
2009 thread_stkov(thread);
2011 #if NUM_CORES > 1
2012 /* Run any blocking operations requested before switching/sleeping */
2013 run_blocking_ops(core, thread);
2014 #endif
2016 #ifdef HAVE_PRIORITY_SCHEDULING
2017 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2018 /* Reset the value of thread's skip count */
2019 thread->skip_count = 0;
2020 #endif
2022 for (;;)
2024 /* If there are threads on a timeout and the earliest wakeup is due,
2025 * check the list and wake any threads that need to start running
2026 * again. */
2027 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2029 check_tmo_threads();
2032 disable_irq();
2033 RTR_LOCK(core);
2035 thread = cores[core].running;
2037 if (UNLIKELY(thread == NULL))
2039 /* Enter sleep mode to reduce power usage - woken up on interrupt
2040 * or wakeup request from another core - expected to enable
2041 * interrupts. */
2042 RTR_UNLOCK(core);
2043 core_sleep(IF_COP(core));
2045 else
2047 #ifdef HAVE_PRIORITY_SCHEDULING
2048 /* Select the new task based on priorities and the last time a
2049 * process got CPU time relative to the highest priority runnable
2050 * task. */
2051 struct priority_distribution *pd = &cores[core].rtr;
2052 int max = find_first_set_bit(pd->mask);
2054 if (block == NULL)
2056 /* Not switching on a block, tentatively select next thread */
2057 thread = thread->l.next;
2060 for (;;)
2062 int priority = thread->priority;
2063 int diff;
2065 /* This ridiculously simple method of aging seems to work
2066 * suspiciously well. It does tend to reward CPU hogs (under
2067 * yielding) but that's generally not desirable at all. On the
2068 * plus side, it, relatively to other threads, penalizes excess
2069 * yielding which is good if some high priority thread is
2070 * performing no useful work such as polling for a device to be
2071 * ready. Of course, aging is only employed when higher and lower
2072 * priority threads are runnable. The highest priority runnable
2073 * thread(s) are never skipped. */
2074 if (LIKELY(priority <= max) ||
2075 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2076 (diff = priority - max, ++thread->skip_count > diff*diff))
2078 cores[core].running = thread;
2079 break;
2082 thread = thread->l.next;
2084 #else
2085 /* Without priority use a simple FCFS algorithm */
2086 if (block == NULL)
2088 /* Not switching on a block, select next thread */
2089 thread = thread->l.next;
2090 cores[core].running = thread;
2092 #endif /* HAVE_PRIORITY_SCHEDULING */
2094 RTR_UNLOCK(core);
2095 enable_irq();
2096 break;
2100 /* And finally give control to the next thread. */
2101 load_context(&thread->context);
2103 #ifdef RB_PROFILE
2104 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
2105 #endif
2109 /*---------------------------------------------------------------------------
2110 * Sleeps a thread for at least a specified number of ticks with zero being
2111 * a wait until the next tick.
2113 * INTERNAL: Intended for use by kernel and not for programs.
2114 *---------------------------------------------------------------------------
2116 void sleep_thread(int ticks)
2118 struct thread_entry *current = cores[CURRENT_CORE].running;
2120 LOCK_THREAD(current);
2122 /* Set our timeout, remove from run list and join timeout list. */
2123 current->tmo_tick = current_tick + ticks + 1;
2124 block_thread_on_l(current, STATE_SLEEPING);
2126 UNLOCK_THREAD(current);
2129 /*---------------------------------------------------------------------------
2130 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2132 * INTERNAL: Intended for use by kernel objects and not for programs.
2133 *---------------------------------------------------------------------------
2135 void block_thread(struct thread_entry *current)
2137 /* Set the state to blocked and take us off of the run queue until we
2138 * are explicitly woken */
2139 LOCK_THREAD(current);
2141 /* Set the list for explicit wakeup */
2142 block_thread_on_l(current, STATE_BLOCKED);
2144 #ifdef HAVE_PRIORITY_SCHEDULING
2145 if (current->blocker != NULL)
2147 /* Object supports PIP */
2148 current = blocker_inherit_priority(current);
2150 #endif
2152 UNLOCK_THREAD(current);
2155 /*---------------------------------------------------------------------------
2156 * Block a thread on a blocking queue for a specified time interval or until
2157 * explicitly woken - whichever happens first.
2159 * INTERNAL: Intended for use by kernel objects and not for programs.
2160 *---------------------------------------------------------------------------
2162 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2164 /* Get the entry for the current running thread. */
2165 LOCK_THREAD(current);
2167 /* Set the state to blocked with the specified timeout */
2168 current->tmo_tick = current_tick + timeout;
2170 /* Set the list for explicit wakeup */
2171 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2173 #ifdef HAVE_PRIORITY_SCHEDULING
2174 if (current->blocker != NULL)
2176 /* Object supports PIP */
2177 current = blocker_inherit_priority(current);
2179 #endif
2181 UNLOCK_THREAD(current);
2184 /*---------------------------------------------------------------------------
2185 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2186 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2188 * This code should be considered a critical section by the caller meaning
2189 * that the object's corelock should be held.
2191 * INTERNAL: Intended for use by kernel objects and not for programs.
2192 *---------------------------------------------------------------------------
2194 unsigned int wakeup_thread(struct thread_entry **list)
2196 struct thread_entry *thread = *list;
2197 unsigned int result = THREAD_NONE;
2199 /* Check if there is a blocked thread at all. */
2200 if (thread == NULL)
2201 return result;
2203 LOCK_THREAD(thread);
2205 /* Determine thread's current state. */
2206 switch (thread->state)
2208 case STATE_BLOCKED:
2209 case STATE_BLOCKED_W_TMO:
2210 remove_from_list_l(list, thread);
2212 result = THREAD_OK;
2214 #ifdef HAVE_PRIORITY_SCHEDULING
2215 struct thread_entry *current;
2216 struct blocker *bl = thread->blocker;
2218 if (bl == NULL)
2220 /* No inheritance - just boost the thread by aging */
2221 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2222 thread->skip_count = thread->priority;
2223 current = cores[CURRENT_CORE].running;
2225 else
2227 /* Call the specified unblocking PIP */
2228 current = bl->wakeup_protocol(thread);
2231 if (current != NULL && thread->priority < current->priority
2232 IF_COP( && thread->core == current->core ))
2234 /* Woken thread is higher priority and exists on the same CPU core;
2235 * recommend a task switch. Knowing if this is an interrupt call
2236 * would be helpful here. */
2237 result |= THREAD_SWITCH;
2239 #endif /* HAVE_PRIORITY_SCHEDULING */
2241 core_schedule_wakeup(thread);
2242 break;
2244 /* Nothing to do. State is not blocked. */
2245 #if THREAD_EXTRA_CHECKS
2246 default:
2247 THREAD_PANICF("wakeup_thread->block invalid", thread);
2248 case STATE_RUNNING:
2249 case STATE_KILLED:
2250 break;
2251 #endif
2254 UNLOCK_THREAD(thread);
2255 return result;
2258 /*---------------------------------------------------------------------------
2259 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2260 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2261 * the queue must be locked first.
2263 * INTERNAL: Intended for use by kernel objects and not for programs.
2264 *---------------------------------------------------------------------------
2266 unsigned int thread_queue_wake(struct thread_entry **list)
2268 unsigned result = THREAD_NONE;
2270 for (;;)
2272 unsigned int rc = wakeup_thread(list);
2274 if (rc == THREAD_NONE)
2275 break; /* No more threads */
2277 result |= rc;
2280 return result;
2283 /*---------------------------------------------------------------------------
2284 * Assign the thread slot a new ID. Version is 1-255.
2285 *---------------------------------------------------------------------------
2287 static void new_thread_id(unsigned int slot_num,
2288 struct thread_entry *thread)
2290 unsigned int version =
2291 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
2292 & THREAD_ID_VERSION_MASK;
2294 /* If wrapped to 0, make it 1 */
2295 if (version == 0)
2296 version = 1u << THREAD_ID_VERSION_SHIFT;
2298 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
2301 /*---------------------------------------------------------------------------
2302 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2303 * will be locked on multicore.
2304 *---------------------------------------------------------------------------
2306 static struct thread_entry * find_empty_thread_slot(void)
2308 /* Any slot could be on an interrupt-accessible list */
2309 IF_COP( int oldlevel = disable_irq_save(); )
2310 struct thread_entry *thread = NULL;
2311 int n;
2313 for (n = 0; n < MAXTHREADS; n++)
2315 /* Obtain current slot state - lock it on multicore */
2316 struct thread_entry *t = &threads[n];
2317 LOCK_THREAD(t);
2319 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2321 /* Slot is empty - leave it locked and caller will unlock */
2322 thread = t;
2323 break;
2326 /* Finished examining slot - no longer busy - unlock on multicore */
2327 UNLOCK_THREAD(t);
2330 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2331 not accesible to them yet */
2332 return thread;
2335 /*---------------------------------------------------------------------------
2336 * Return the thread_entry pointer for a thread_id. Return the current
2337 * thread if the ID is 0 (alias for current).
2338 *---------------------------------------------------------------------------
2340 struct thread_entry * thread_id_entry(unsigned int thread_id)
2342 return (thread_id == THREAD_ID_CURRENT) ?
2343 cores[CURRENT_CORE].running :
2344 &threads[thread_id & THREAD_ID_SLOT_MASK];
2347 /*---------------------------------------------------------------------------
2348 * Place the current core in idle mode - woken up on interrupt or wake
2349 * request from another core.
2350 *---------------------------------------------------------------------------
2352 void core_idle(void)
2354 IF_COP( const unsigned int core = CURRENT_CORE; )
2355 disable_irq();
2356 core_sleep(IF_COP(core));
2359 /*---------------------------------------------------------------------------
2360 * Create a thread. If using a dual core architecture, specify which core to
2361 * start the thread on.
2363 * Return ID if context area could be allocated, else NULL.
2364 *---------------------------------------------------------------------------
2366 unsigned int create_thread(void (*function)(void),
2367 void* stack, size_t stack_size,
2368 unsigned flags, const char *name
2369 IF_PRIO(, int priority)
2370 IF_COP(, unsigned int core))
2372 unsigned int i;
2373 unsigned int stack_words;
2374 uintptr_t stackptr, stackend;
2375 struct thread_entry *thread;
2376 unsigned state;
2377 int oldlevel;
2379 thread = find_empty_thread_slot();
2380 if (thread == NULL)
2382 return 0;
2385 oldlevel = disable_irq_save();
2387 /* Munge the stack to make it easy to spot stack overflows */
2388 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2389 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2390 stack_size = stackend - stackptr;
2391 stack_words = stack_size / sizeof (uintptr_t);
2393 for (i = 0; i < stack_words; i++)
2395 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2398 /* Store interesting information */
2399 thread->name = name;
2400 thread->stack = (uintptr_t *)stackptr;
2401 thread->stack_size = stack_size;
2402 thread->queue = NULL;
2403 #ifdef HAVE_WAKEUP_EXT_CB
2404 thread->wakeup_ext_cb = NULL;
2405 #endif
2406 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2407 thread->cpu_boost = 0;
2408 #endif
2409 #ifdef HAVE_PRIORITY_SCHEDULING
2410 memset(&thread->pdist, 0, sizeof(thread->pdist));
2411 thread->blocker = NULL;
2412 thread->base_priority = priority;
2413 thread->priority = priority;
2414 thread->skip_count = priority;
2415 prio_add_entry(&thread->pdist, priority);
2416 #endif
2418 #if NUM_CORES > 1
2419 thread->core = core;
2421 /* Writeback stack munging or anything else before starting */
2422 if (core != CURRENT_CORE)
2424 cpucache_flush();
2426 #endif
2428 /* Thread is not on any timeout list but be a bit paranoid */
2429 thread->tmo.prev = NULL;
2431 state = (flags & CREATE_THREAD_FROZEN) ?
2432 STATE_FROZEN : STATE_RUNNING;
2434 thread->context.sp = (typeof (thread->context.sp))stackend;
2436 /* Load the thread's context structure with needed startup information */
2437 THREAD_STARTUP_INIT(core, thread, function);
2439 thread->state = state;
2440 i = thread->id; /* Snapshot while locked */
2442 if (state == STATE_RUNNING)
2443 core_schedule_wakeup(thread);
2445 UNLOCK_THREAD(thread);
2446 restore_irq(oldlevel);
2448 return i;
2451 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2452 /*---------------------------------------------------------------------------
2453 * Change the boost state of a thread boosting or unboosting the CPU
2454 * as required.
2455 *---------------------------------------------------------------------------
2457 static inline void boost_thread(struct thread_entry *thread, bool boost)
2459 if ((thread->cpu_boost != 0) != boost)
2461 thread->cpu_boost = boost;
2462 cpu_boost(boost);
2466 void trigger_cpu_boost(void)
2468 struct thread_entry *current = cores[CURRENT_CORE].running;
2469 boost_thread(current, true);
2472 void cancel_cpu_boost(void)
2474 struct thread_entry *current = cores[CURRENT_CORE].running;
2475 boost_thread(current, false);
2477 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2479 /*---------------------------------------------------------------------------
2480 * Block the current thread until another thread terminates. A thread may
2481 * wait on itself to terminate which prevents it from running again and it
2482 * will need to be killed externally.
2483 * Parameter is the ID as returned from create_thread().
2484 *---------------------------------------------------------------------------
2486 void thread_wait(unsigned int thread_id)
2488 struct thread_entry *current = cores[CURRENT_CORE].running;
2489 struct thread_entry *thread = thread_id_entry(thread_id);
2491 /* Lock thread-as-waitable-object lock */
2492 corelock_lock(&thread->waiter_cl);
2494 /* Be sure it hasn't been killed yet */
2495 if (thread_id == THREAD_ID_CURRENT ||
2496 (thread->id == thread_id && thread->state != STATE_KILLED))
2498 IF_COP( current->obj_cl = &thread->waiter_cl; )
2499 current->bqp = &thread->queue;
2501 disable_irq();
2502 block_thread(current);
2504 corelock_unlock(&thread->waiter_cl);
2506 switch_thread();
2507 return;
2510 corelock_unlock(&thread->waiter_cl);
2513 /*---------------------------------------------------------------------------
2514 * Exit the current thread. The Right Way to Do Things (TM).
2515 *---------------------------------------------------------------------------
2517 void thread_exit(void)
2519 const unsigned int core = CURRENT_CORE;
2520 struct thread_entry *current = cores[core].running;
2522 /* Cancel CPU boost if any */
2523 cancel_cpu_boost();
2525 disable_irq();
2527 corelock_lock(&current->waiter_cl);
2528 LOCK_THREAD(current);
2530 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2531 if (current->name == THREAD_DESTRUCT)
2533 /* Thread being killed - become a waiter */
2534 unsigned int id = current->id;
2535 UNLOCK_THREAD(current);
2536 corelock_unlock(&current->waiter_cl);
2537 thread_wait(id);
2538 THREAD_PANICF("thread_exit->WK:*R", current);
2540 #endif
2542 #ifdef HAVE_PRIORITY_SCHEDULING
2543 check_for_obj_waiters("thread_exit", current);
2544 #endif
2546 if (current->tmo.prev != NULL)
2548 /* Cancel pending timeout list removal */
2549 remove_from_list_tmo(current);
2552 /* Switch tasks and never return */
2553 block_thread_on_l(current, STATE_KILLED);
2555 #if NUM_CORES > 1
2556 /* Switch to the idle stack if not on the main core (where "main"
2557 * runs) - we can hope gcc doesn't need the old stack beyond this
2558 * point. */
2559 if (core != CPU)
2561 switch_to_idle_stack(core);
2564 cpucache_flush();
2566 /* At this point, this thread isn't using resources allocated for
2567 * execution except the slot itself. */
2568 #endif
2570 /* Update ID for this slot */
2571 new_thread_id(current->id, current);
2572 current->name = NULL;
2574 /* Signal this thread */
2575 thread_queue_wake(&current->queue);
2576 corelock_unlock(&current->waiter_cl);
2577 /* Slot must be unusable until thread is really gone */
2578 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2579 switch_thread();
2580 /* This should never and must never be reached - if it is, the
2581 * state is corrupted */
2582 THREAD_PANICF("thread_exit->K:*R", current);
2585 #ifdef ALLOW_REMOVE_THREAD
2586 /*---------------------------------------------------------------------------
2587 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2588 * normal programs.
2590 * Parameter is the ID as returned from create_thread().
2592 * Use with care on threads that are not under careful control as this may
2593 * leave various objects in an undefined state.
2594 *---------------------------------------------------------------------------
2596 void remove_thread(unsigned int thread_id)
2598 #if NUM_CORES > 1
2599 /* core is not constant here because of core switching */
2600 unsigned int core = CURRENT_CORE;
2601 unsigned int old_core = NUM_CORES;
2602 struct corelock *ocl = NULL;
2603 #else
2604 const unsigned int core = CURRENT_CORE;
2605 #endif
2606 struct thread_entry *current = cores[core].running;
2607 struct thread_entry *thread = thread_id_entry(thread_id);
2609 unsigned state;
2610 int oldlevel;
2612 if (thread == current)
2613 thread_exit(); /* Current thread - do normal exit */
2615 oldlevel = disable_irq_save();
2617 corelock_lock(&thread->waiter_cl);
2618 LOCK_THREAD(thread);
2620 state = thread->state;
2622 if (thread->id != thread_id || state == STATE_KILLED)
2623 goto thread_killed;
2625 #if NUM_CORES > 1
2626 if (thread->name == THREAD_DESTRUCT)
2628 /* Thread being killed - become a waiter */
2629 UNLOCK_THREAD(thread);
2630 corelock_unlock(&thread->waiter_cl);
2631 restore_irq(oldlevel);
2632 thread_wait(thread_id);
2633 return;
2636 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2638 #ifdef HAVE_PRIORITY_SCHEDULING
2639 check_for_obj_waiters("remove_thread", thread);
2640 #endif
2642 if (thread->core != core)
2644 /* Switch cores and safely extract the thread there */
2645 /* Slot HAS to be unlocked or a deadlock could occur which means other
2646 * threads have to be guided into becoming thread waiters if they
2647 * attempt to remove it. */
2648 unsigned int new_core = thread->core;
2650 corelock_unlock(&thread->waiter_cl);
2652 UNLOCK_THREAD(thread);
2653 restore_irq(oldlevel);
2655 old_core = switch_core(new_core);
2657 oldlevel = disable_irq_save();
2659 corelock_lock(&thread->waiter_cl);
2660 LOCK_THREAD(thread);
2662 state = thread->state;
2663 core = new_core;
2664 /* Perform the extraction and switch ourselves back to the original
2665 processor */
2667 #endif /* NUM_CORES > 1 */
2669 if (thread->tmo.prev != NULL)
2671 /* Clean thread off the timeout list if a timeout check hasn't
2672 * run yet */
2673 remove_from_list_tmo(thread);
2676 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2677 /* Cancel CPU boost if any */
2678 boost_thread(thread, false);
2679 #endif
2681 IF_COP( retry_state: )
2683 switch (state)
2685 case STATE_RUNNING:
2686 RTR_LOCK(core);
2687 /* Remove thread from ready to run tasks */
2688 remove_from_list_l(&cores[core].running, thread);
2689 rtr_subtract_entry(core, thread->priority);
2690 RTR_UNLOCK(core);
2691 break;
2692 case STATE_BLOCKED:
2693 case STATE_BLOCKED_W_TMO:
2694 /* Remove thread from the queue it's blocked on - including its
2695 * own if waiting there */
2696 #if NUM_CORES > 1
2697 if (&thread->waiter_cl != thread->obj_cl)
2699 ocl = thread->obj_cl;
2701 if (UNLIKELY(corelock_try_lock(ocl) == 0))
2703 UNLOCK_THREAD(thread);
2704 corelock_lock(ocl);
2705 LOCK_THREAD(thread);
2707 if (UNLIKELY(thread->state != state))
2709 /* Something woke the thread */
2710 state = thread->state;
2711 corelock_unlock(ocl);
2712 goto retry_state;
2716 #endif
2717 remove_from_list_l(thread->bqp, thread);
2719 #ifdef HAVE_WAKEUP_EXT_CB
2720 if (thread->wakeup_ext_cb != NULL)
2721 thread->wakeup_ext_cb(thread);
2722 #endif
2724 #ifdef HAVE_PRIORITY_SCHEDULING
2725 if (thread->blocker != NULL)
2727 /* Remove thread's priority influence from its chain */
2728 wakeup_priority_protocol_release(thread);
2730 #endif
2732 #if NUM_CORES > 1
2733 if (ocl != NULL)
2734 corelock_unlock(ocl);
2735 #endif
2736 break;
2737 /* Otherwise thread is frozen and hasn't run yet */
2740 new_thread_id(thread_id, thread);
2741 thread->state = STATE_KILLED;
2743 /* If thread was waiting on itself, it will have been removed above.
2744 * The wrong order would result in waking the thread first and deadlocking
2745 * since the slot is already locked. */
2746 thread_queue_wake(&thread->queue);
2748 thread->name = NULL;
2750 thread_killed: /* Thread was already killed */
2751 /* Removal complete - safe to unlock and reenable interrupts */
2752 corelock_unlock(&thread->waiter_cl);
2753 UNLOCK_THREAD(thread);
2754 restore_irq(oldlevel);
2756 #if NUM_CORES > 1
2757 if (old_core < NUM_CORES)
2759 /* Did a removal on another processor's thread - switch back to
2760 native core */
2761 switch_core(old_core);
2763 #endif
2765 #endif /* ALLOW_REMOVE_THREAD */
2767 #ifdef HAVE_PRIORITY_SCHEDULING
2768 /*---------------------------------------------------------------------------
2769 * Sets the thread's relative base priority for the core it runs on. Any
2770 * needed inheritance changes also may happen.
2771 *---------------------------------------------------------------------------
2773 int thread_set_priority(unsigned int thread_id, int priority)
2775 int old_base_priority = -1;
2776 struct thread_entry *thread = thread_id_entry(thread_id);
2778 /* A little safety measure */
2779 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2780 return -1;
2782 /* Thread could be on any list and therefore on an interrupt accessible
2783 one - disable interrupts */
2784 int oldlevel = disable_irq_save();
2786 LOCK_THREAD(thread);
2788 /* Make sure it's not killed */
2789 if (thread_id == THREAD_ID_CURRENT ||
2790 (thread->id == thread_id && thread->state != STATE_KILLED))
2792 int old_priority = thread->priority;
2794 old_base_priority = thread->base_priority;
2795 thread->base_priority = priority;
2797 prio_move_entry(&thread->pdist, old_base_priority, priority);
2798 priority = find_first_set_bit(thread->pdist.mask);
2800 if (old_priority == priority)
2802 /* No priority change - do nothing */
2804 else if (thread->state == STATE_RUNNING)
2806 /* This thread is running - change location on the run
2807 * queue. No transitive inheritance needed. */
2808 set_running_thread_priority(thread, priority);
2810 else
2812 thread->priority = priority;
2814 if (thread->blocker != NULL)
2816 /* Bubble new priority down the chain */
2817 struct blocker *bl = thread->blocker; /* Blocker struct */
2818 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2819 struct thread_entry * const tstart = thread; /* Initial thread */
2820 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2822 for (;;)
2824 struct thread_entry *next; /* Next thread to check */
2825 int bl_pr; /* Highest blocked thread */
2826 int queue_pr; /* New highest blocked thread */
2827 #if NUM_CORES > 1
2828 /* Owner can change but thread cannot be dislodged - thread
2829 * may not be the first in the queue which allows other
2830 * threads ahead in the list to be given ownership during the
2831 * operation. If thread is next then the waker will have to
2832 * wait for us and the owner of the object will remain fixed.
2833 * If we successfully grab the owner -- which at some point
2834 * is guaranteed -- then the queue remains fixed until we
2835 * pass by. */
2836 for (;;)
2838 LOCK_THREAD(bl_t);
2840 /* Double-check the owner - retry if it changed */
2841 if (LIKELY(bl->thread == bl_t))
2842 break;
2844 UNLOCK_THREAD(bl_t);
2845 bl_t = bl->thread;
2847 #endif
2848 bl_pr = bl->priority;
2850 if (highest > bl_pr)
2851 break; /* Object priority won't change */
2853 /* This will include the thread being set */
2854 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2856 if (queue_pr == bl_pr)
2857 break; /* Object priority not changing */
2859 /* Update thread boost for this object */
2860 bl->priority = queue_pr;
2861 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2862 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2864 if (bl_t->priority == bl_pr)
2865 break; /* Blocking thread priority not changing */
2867 if (bl_t->state == STATE_RUNNING)
2869 /* Thread not blocked - we're done */
2870 set_running_thread_priority(bl_t, bl_pr);
2871 break;
2874 bl_t->priority = bl_pr;
2875 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2877 if (bl == NULL)
2878 break; /* End of chain */
2880 next = bl->thread;
2882 if (UNLIKELY(next == tstart))
2883 break; /* Full-circle */
2885 UNLOCK_THREAD(thread);
2887 thread = bl_t;
2888 bl_t = next;
2889 } /* for (;;) */
2891 UNLOCK_THREAD(bl_t);
2896 UNLOCK_THREAD(thread);
2898 restore_irq(oldlevel);
2900 return old_base_priority;
2903 /*---------------------------------------------------------------------------
2904 * Returns the current base priority for a thread.
2905 *---------------------------------------------------------------------------
2907 int thread_get_priority(unsigned int thread_id)
2909 struct thread_entry *thread = thread_id_entry(thread_id);
2910 int base_priority = thread->base_priority;
2912 /* Simply check without locking slot. It may or may not be valid by the
2913 * time the function returns anyway. If all tests pass, it is the
2914 * correct value for when it was valid. */
2915 if (thread_id != THREAD_ID_CURRENT &&
2916 (thread->id != thread_id || thread->state == STATE_KILLED))
2917 base_priority = -1;
2919 return base_priority;
2921 #endif /* HAVE_PRIORITY_SCHEDULING */
2923 /*---------------------------------------------------------------------------
2924 * Starts a frozen thread - similar semantics to wakeup_thread except that
2925 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2926 * virtue of the slot having a state of STATE_FROZEN.
2927 *---------------------------------------------------------------------------
2929 void thread_thaw(unsigned int thread_id)
2931 struct thread_entry *thread = thread_id_entry(thread_id);
2932 int oldlevel = disable_irq_save();
2934 LOCK_THREAD(thread);
2936 /* If thread is the current one, it cannot be frozen, therefore
2937 * there is no need to check that. */
2938 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2939 core_schedule_wakeup(thread);
2941 UNLOCK_THREAD(thread);
2942 restore_irq(oldlevel);
2945 /*---------------------------------------------------------------------------
2946 * Return the ID of the currently executing thread.
2947 *---------------------------------------------------------------------------
2949 unsigned int thread_get_current(void)
2951 return cores[CURRENT_CORE].running->id;
2954 #if NUM_CORES > 1
2955 /*---------------------------------------------------------------------------
2956 * Switch the processor that the currently executing thread runs on.
2957 *---------------------------------------------------------------------------
2959 unsigned int switch_core(unsigned int new_core)
2961 const unsigned int core = CURRENT_CORE;
2962 struct thread_entry *current = cores[core].running;
2964 if (core == new_core)
2966 /* No change - just return same core */
2967 return core;
2970 int oldlevel = disable_irq_save();
2971 LOCK_THREAD(current);
2973 if (current->name == THREAD_DESTRUCT)
2975 /* Thread being killed - deactivate and let process complete */
2976 unsigned int id = current->id;
2977 UNLOCK_THREAD(current);
2978 restore_irq(oldlevel);
2979 thread_wait(id);
2980 /* Should never be reached */
2981 THREAD_PANICF("switch_core->D:*R", current);
2984 /* Get us off the running list for the current core */
2985 RTR_LOCK(core);
2986 remove_from_list_l(&cores[core].running, current);
2987 rtr_subtract_entry(core, current->priority);
2988 RTR_UNLOCK(core);
2990 /* Stash return value (old core) in a safe place */
2991 current->retval = core;
2993 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2994 * the other core will likely attempt a removal from the wrong list! */
2995 if (current->tmo.prev != NULL)
2997 remove_from_list_tmo(current);
3000 /* Change the core number for this thread slot */
3001 current->core = new_core;
3003 /* Do not use core_schedule_wakeup here since this will result in
3004 * the thread starting to run on the other core before being finished on
3005 * this one. Delay the list unlock to keep the other core stuck
3006 * until this thread is ready. */
3007 RTR_LOCK(new_core);
3009 rtr_add_entry(new_core, current->priority);
3010 add_to_list_l(&cores[new_core].running, current);
3012 /* Make a callback into device-specific code, unlock the wakeup list so
3013 * that execution may resume on the new core, unlock our slot and finally
3014 * restore the interrupt level */
3015 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3016 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3017 cores[core].block_task = current;
3019 UNLOCK_THREAD(current);
3021 /* Alert other core to activity */
3022 core_wake(new_core);
3024 /* Do the stack switching, cache_maintenence and switch_thread call -
3025 requires native code */
3026 switch_thread_core(core, current);
3028 /* Finally return the old core to caller */
3029 return current->retval;
3031 #endif /* NUM_CORES > 1 */
3033 /*---------------------------------------------------------------------------
3034 * Initialize threading API. This assumes interrupts are not yet enabled. On
3035 * multicore setups, no core is allowed to proceed until create_thread calls
3036 * are safe to perform.
3037 *---------------------------------------------------------------------------
3039 void init_threads(void)
3041 const unsigned int core = CURRENT_CORE;
3042 struct thread_entry *thread;
3044 if (core == CPU)
3046 /* Initialize core locks and IDs in all slots */
3047 int n;
3048 for (n = 0; n < MAXTHREADS; n++)
3050 thread = &threads[n];
3051 corelock_init(&thread->waiter_cl);
3052 corelock_init(&thread->slot_cl);
3053 thread->id = THREAD_ID_INIT(n);
3057 /* CPU will initialize first and then sleep */
3058 thread = find_empty_thread_slot();
3060 if (thread == NULL)
3062 /* WTF? There really must be a slot available at this stage.
3063 * This can fail if, for example, .bss isn't zero'ed out by the loader
3064 * or threads is in the wrong section. */
3065 THREAD_PANICF("init_threads->no slot", NULL);
3068 /* Initialize initially non-zero members of core */
3069 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3071 /* Initialize initially non-zero members of slot */
3072 UNLOCK_THREAD(thread); /* No sync worries yet */
3073 thread->name = main_thread_name;
3074 thread->state = STATE_RUNNING;
3075 IF_COP( thread->core = core; )
3076 #ifdef HAVE_PRIORITY_SCHEDULING
3077 corelock_init(&cores[core].rtr_cl);
3078 thread->base_priority = PRIORITY_USER_INTERFACE;
3079 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3080 thread->priority = PRIORITY_USER_INTERFACE;
3081 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3082 #endif
3084 add_to_list_l(&cores[core].running, thread);
3086 if (core == CPU)
3088 thread->stack = stackbegin;
3089 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3090 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3091 /* Wait for other processors to finish their inits since create_thread
3092 * isn't safe to call until the kernel inits are done. The first
3093 * threads created in the system must of course be created by CPU.
3094 * Another possible approach is to initialize all cores and slots
3095 * for each core by CPU, let the remainder proceed in parallel and
3096 * signal CPU when all are finished. */
3097 core_thread_init(CPU);
3099 else
3101 /* Initial stack is the idle stack */
3102 thread->stack = idle_stacks[core];
3103 thread->stack_size = IDLE_STACK_SIZE;
3104 /* After last processor completes, it should signal all others to
3105 * proceed or may signal the next and call thread_exit(). The last one
3106 * to finish will signal CPU. */
3107 core_thread_init(core);
3108 /* Other cores do not have a main thread - go idle inside switch_thread
3109 * until a thread can run on the core. */
3110 thread_exit();
3111 #endif /* NUM_CORES */
3115 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3116 #if NUM_CORES == 1
3117 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3118 #else
3119 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3120 #endif
3122 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3123 unsigned int i;
3124 int usage = 0;
3126 for (i = 0; i < stack_words; i++)
3128 if (stackptr[i] != DEADBEEF)
3130 usage = ((stack_words - i) * 100) / stack_words;
3131 break;
3135 return usage;
3138 /*---------------------------------------------------------------------------
3139 * Returns the maximum percentage of stack a thread ever used while running.
3140 * NOTE: Some large buffer allocations that don't use enough the buffer to
3141 * overwrite stackptr[0] will not be seen.
3142 *---------------------------------------------------------------------------
3144 int thread_stack_usage(const struct thread_entry *thread)
3146 return stack_usage(thread->stack, thread->stack_size);
3149 #if NUM_CORES > 1
3150 /*---------------------------------------------------------------------------
3151 * Returns the maximum percentage of the core's idle stack ever used during
3152 * runtime.
3153 *---------------------------------------------------------------------------
3155 int idle_stack_usage(unsigned int core)
3157 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3159 #endif
3161 /*---------------------------------------------------------------------------
3162 * Fills in the buffer with the specified thread's name. If the name is NULL,
3163 * empty, or the thread is in destruct state a formatted ID is written
3164 * instead.
3165 *---------------------------------------------------------------------------
3167 void thread_get_name(char *buffer, int size,
3168 struct thread_entry *thread)
3170 if (size <= 0)
3171 return;
3173 *buffer = '\0';
3175 if (thread)
3177 /* Display thread name if one or ID if none */
3178 const char *name = thread->name;
3179 const char *fmt = "%s";
3180 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3182 name = (const char *)thread;
3183 fmt = "%08lX";
3185 snprintf(buffer, size, fmt, name);