Minor quickscreen and pitchscreen fixes
[kugel-rb.git] / firmware / thread.c
blobf779ca3ae061ee9d5f53773a99d0a69844512f66
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, =invalidate_icache \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 flush_icache();
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, =invalidate_icache \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 CONFIG_CPU == S3C2440
749 /*---------------------------------------------------------------------------
750 * Put core in a power-saving state if waking list wasn't repopulated.
751 *---------------------------------------------------------------------------
753 static inline void core_sleep(void)
755 /* FIQ also changes the CLKCON register so FIQ must be disabled
756 when changing it here */
757 asm volatile (
758 "mrs r0, cpsr \n"
759 "orr r2, r0, #0x40 \n" /* Disable FIQ */
760 "bic r0, r0, #0x80 \n" /* Prepare IRQ enable */
761 "msr cpsr_c, r2 \n"
762 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
763 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
764 "orr r2, r2, #4 \n"
765 "str r2, [r1, #0xc] \n"
766 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
767 "mov r2, #0 \n" /* wait for IDLE */
768 "1: \n"
769 "add r2, r2, #1 \n"
770 "cmp r2, #10 \n"
771 "bne 1b \n"
772 "orr r2, r0, #0xc0 \n" /* Disable IRQ, FIQ */
773 "msr cpsr_c, r2 \n"
774 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
775 "bic r2, r2, #4 \n"
776 "str r2, [r1, #0xc] \n"
777 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
778 : : : "r0", "r1", "r2");
780 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X) /* Single core only for now */ \
781 || CONFIG_CPU == IMX31L || CONFIG_CPU == DM320 || CONFIG_CPU == AS3525
782 /* Use the generic ARMv4/v5 wait for IRQ */
783 static inline void core_sleep(void)
785 asm volatile (
786 "mov r0, #0 \n"
787 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
788 : : : "r0"
790 enable_irq();
792 #else
793 static inline void core_sleep(void)
795 #warning core_sleep not implemented, battery life will be decreased
796 enable_irq();
798 #endif /* CONFIG_CPU == */
800 #elif defined(CPU_COLDFIRE)
801 /*---------------------------------------------------------------------------
802 * Start the thread running and terminate it if it returns
803 *---------------------------------------------------------------------------
805 void start_thread(void); /* Provide C access to ASM label */
806 static void __attribute__((used)) __start_thread(void)
808 /* a0=macsr, a1=context */
809 asm volatile (
810 "start_thread: \n" /* Start here - no naked attribute */
811 "move.l %a0, %macsr \n" /* Set initial mac status reg */
812 "lea.l 48(%a1), %a1 \n"
813 "move.l (%a1)+, %sp \n" /* Set initial stack */
814 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
815 "clr.l (%a1) \n" /* Mark thread running */
816 "jsr (%a2) \n" /* Call thread function */
818 thread_exit();
821 /* Set EMAC unit to fractional mode with saturation for each new thread,
822 * since that's what'll be the most useful for most things which the dsp
823 * will do. Codecs should still initialize their preferred modes
824 * explicitly. Context pointer is placed in d2 slot and start_thread
825 * pointer in d3 slot. thread function pointer is placed in context.start.
826 * See load_context for what happens when thread is initially going to
827 * run.
829 #define THREAD_STARTUP_INIT(core, thread, function) \
830 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
831 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
832 (thread)->context.d[1] = (uint32_t)start_thread, \
833 (thread)->context.start = (uint32_t)(function); })
835 /*---------------------------------------------------------------------------
836 * Store non-volatile context.
837 *---------------------------------------------------------------------------
839 static inline void store_context(void* addr)
841 asm volatile (
842 "move.l %%macsr,%%d0 \n"
843 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
844 : : "a" (addr) : "d0" /* only! */
848 /*---------------------------------------------------------------------------
849 * Load non-volatile context.
850 *---------------------------------------------------------------------------
852 static inline void load_context(const void* addr)
854 asm volatile (
855 "move.l 52(%0), %%d0 \n" /* Get start address */
856 "beq.b 1f \n" /* NULL -> already running */
857 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
858 "jmp (%%a2) \n" /* Start the thread */
859 "1: \n"
860 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
861 "move.l %%d0, %%macsr \n"
862 : : "a" (addr) : "d0" /* only! */
866 /*---------------------------------------------------------------------------
867 * Put core in a power-saving state if waking list wasn't repopulated.
868 *---------------------------------------------------------------------------
870 static inline void core_sleep(void)
872 /* Supervisor mode, interrupts enabled upon wakeup */
873 asm volatile ("stop #0x2000");
876 #elif CONFIG_CPU == SH7034
877 /*---------------------------------------------------------------------------
878 * Start the thread running and terminate it if it returns
879 *---------------------------------------------------------------------------
881 void start_thread(void); /* Provide C access to ASM label */
882 static void __attribute__((used)) __start_thread(void)
884 /* r8 = context */
885 asm volatile (
886 "_start_thread: \n" /* Start here - no naked attribute */
887 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
888 "mov.l @(28, r8), r15 \n" /* Set initial sp */
889 "mov #0, r1 \n" /* Start the thread */
890 "jsr @r0 \n"
891 "mov.l r1, @(36, r8) \n" /* Clear start address */
893 thread_exit();
896 /* Place context pointer in r8 slot, function pointer in r9 slot, and
897 * start_thread pointer in context_start */
898 #define THREAD_STARTUP_INIT(core, thread, function) \
899 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
900 (thread)->context.r[1] = (uint32_t)(function), \
901 (thread)->context.start = (uint32_t)start_thread; })
903 /*---------------------------------------------------------------------------
904 * Store non-volatile context.
905 *---------------------------------------------------------------------------
907 static inline void store_context(void* addr)
909 asm volatile (
910 "add #36, %0 \n" /* Start at last reg. By the time routine */
911 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
912 "mov.l r15,@-%0 \n"
913 "mov.l r14,@-%0 \n"
914 "mov.l r13,@-%0 \n"
915 "mov.l r12,@-%0 \n"
916 "mov.l r11,@-%0 \n"
917 "mov.l r10,@-%0 \n"
918 "mov.l r9, @-%0 \n"
919 "mov.l r8, @-%0 \n"
920 : : "r" (addr)
924 /*---------------------------------------------------------------------------
925 * Load non-volatile context.
926 *---------------------------------------------------------------------------
928 static inline void load_context(const void* addr)
930 asm volatile (
931 "mov.l @(36, %0), r0 \n" /* Get start address */
932 "tst r0, r0 \n"
933 "bt .running \n" /* NULL -> already running */
934 "jmp @r0 \n" /* r8 = context */
935 ".running: \n"
936 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
937 "mov.l @%0+, r9 \n"
938 "mov.l @%0+, r10 \n"
939 "mov.l @%0+, r11 \n"
940 "mov.l @%0+, r12 \n"
941 "mov.l @%0+, r13 \n"
942 "mov.l @%0+, r14 \n"
943 "mov.l @%0+, r15 \n"
944 "lds.l @%0+, pr \n"
945 : : "r" (addr) : "r0" /* only! */
949 /*---------------------------------------------------------------------------
950 * Put core in a power-saving state.
951 *---------------------------------------------------------------------------
953 static inline void core_sleep(void)
955 asm volatile (
956 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
957 "mov #0, r1 \n" /* Enable interrupts */
958 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
959 "sleep \n" /* Execute standby */
960 : : "z"(&SBYCR-GBR) : "r1");
963 #elif CPU_MIPS == 32
965 /*---------------------------------------------------------------------------
966 * Start the thread running and terminate it if it returns
967 *---------------------------------------------------------------------------
970 void start_thread(void); /* Provide C access to ASM label */
971 static void __attribute__((used)) _start_thread(void)
973 /* $t1 = context */
974 asm volatile (
975 "start_thread: \n"
976 ".set noreorder \n"
977 ".set noat \n"
978 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = $t0, $9 = $t1) */
979 "lw $29, 40($9) \n" /* Set initial sp(=$29) */
980 "sw $0, 48($9) \n" /* Clear start address */
981 "jr $8 \n" /* Start the thread */
982 "nop \n"
983 ".set at \n"
984 ".set reorder \n"
986 thread_exit();
989 /* Place context pointer in $s0 slot, function pointer in $s1 slot, and
990 * start_thread pointer in context_start */
991 #define THREAD_STARTUP_INIT(core, thread, function) \
992 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
993 (thread)->context.r[1] = (uint32_t)(function), \
994 (thread)->context.start = (uint32_t)start_thread; })
996 /*---------------------------------------------------------------------------
997 * Store non-volatile context.
998 *---------------------------------------------------------------------------
1000 static inline void store_context(void* addr)
1002 asm volatile (
1003 ".set noreorder \n"
1004 ".set noat \n"
1005 "move $8, %0 \n"
1006 "sw $16, 0($8) \n" /* $s0 */
1007 "sw $17, 4($8) \n" /* $s1 */
1008 "sw $18, 8($8) \n" /* $s2 */
1009 "sw $19, 12($8) \n" /* $s3 */
1010 "sw $20, 16($8) \n" /* $s4 */
1011 "sw $21, 20($8) \n" /* $s5 */
1012 "sw $22, 24($8) \n" /* $s6 */
1013 "sw $23, 28($8) \n" /* $s7 */
1014 "sw $28, 32($8) \n" /* gp */
1015 "sw $30, 36($8) \n" /* fp */
1016 "sw $29, 40($8) \n" /* sp */
1017 "sw $31, 44($8) \n" /* ra */
1018 ".set at \n"
1019 ".set reorder \n"
1020 : : "r" (addr) : "t0"
1024 /*---------------------------------------------------------------------------
1025 * Load non-volatile context.
1026 *---------------------------------------------------------------------------
1028 static inline void load_context(const void* addr)
1030 asm volatile (
1031 ".set noat \n"
1032 ".set noreorder \n"
1033 "lw $8, 48(%0) \n" /* Get start address ($8 = $t0) */
1034 "beqz $8, running \n" /* NULL -> already running */
1035 "nop \n"
1036 "move $9, %0 \n" /* $t1 = context */
1037 "jr $8 \n"
1038 "nop \n"
1039 "running: \n"
1040 "move $8, %0 \n"
1041 "lw $16, 0($8) \n" /* $s0 */
1042 "lw $17, 4($8) \n" /* $s1 */
1043 "lw $18, 8($8) \n" /* $s2 */
1044 "lw $19, 12($8) \n" /* $s3 */
1045 "lw $20, 16($8) \n" /* $s4 */
1046 "lw $21, 20($8) \n" /* $s5 */
1047 "lw $22, 24($8) \n" /* $s6 */
1048 "lw $23, 28($8) \n" /* $s7 */
1049 "lw $28, 32($8) \n" /* gp */
1050 "lw $30, 36($8) \n" /* fp */
1051 "lw $29, 40($8) \n" /* sp */
1052 "lw $31, 44($8) \n" /* ra */
1053 ".set at \n"
1054 ".set reorder \n"
1055 : : "r" (addr) : "t0" /* only! */
1059 /*---------------------------------------------------------------------------
1060 * Put core in a power-saving state.
1061 *---------------------------------------------------------------------------
1063 static inline void core_sleep(void)
1065 #if CONFIG_CPU == JZ4732
1066 __cpm_idle_mode();
1067 #endif
1068 asm volatile(".set mips32r2 \n"
1069 "mfc0 $8, $12 \n" /* mfc $t0, $12 */
1070 "move $9, $8 \n" /* move $t1, $t0 */
1071 "la $10, 0x8000000 \n" /* la $t2, 0x8000000 */
1072 "or $8, $8, $10 \n" /* Enable reduced power mode */
1073 "mtc0 $8, $12 \n"
1074 "wait \n"
1075 "mtc0 $9, $12 \n"
1076 ".set mips0 \n"
1077 ::: "t0", "t1", "t2"
1079 enable_irq();
1083 #endif /* CONFIG_CPU == */
1086 * End Processor-specific section
1087 ***************************************************************************/
1089 #if THREAD_EXTRA_CHECKS
1090 static void thread_panicf(const char *msg, struct thread_entry *thread)
1092 IF_COP( const unsigned int core = thread->core; )
1093 static char name[32];
1094 thread_get_name(name, 32, thread);
1095 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1097 static void thread_stkov(struct thread_entry *thread)
1099 thread_panicf("Stkov", thread);
1101 #define THREAD_PANICF(msg, thread) \
1102 thread_panicf(msg, thread)
1103 #define THREAD_ASSERT(exp, msg, thread) \
1104 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1105 #else
1106 static void thread_stkov(struct thread_entry *thread)
1108 IF_COP( const unsigned int core = thread->core; )
1109 static char name[32];
1110 thread_get_name(name, 32, thread);
1111 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1113 #define THREAD_PANICF(msg, thread)
1114 #define THREAD_ASSERT(exp, msg, thread)
1115 #endif /* THREAD_EXTRA_CHECKS */
1117 /* Thread locking */
1118 #if NUM_CORES > 1
1119 #define LOCK_THREAD(thread) \
1120 ({ corelock_lock(&(thread)->slot_cl); })
1121 #define TRY_LOCK_THREAD(thread) \
1122 ({ corelock_try_lock(&thread->slot_cl); })
1123 #define UNLOCK_THREAD(thread) \
1124 ({ corelock_unlock(&(thread)->slot_cl); })
1125 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1126 ({ unsigned int _core = (thread)->core; \
1127 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1128 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1129 #else
1130 #define LOCK_THREAD(thread) \
1131 ({ })
1132 #define TRY_LOCK_THREAD(thread) \
1133 ({ })
1134 #define UNLOCK_THREAD(thread) \
1135 ({ })
1136 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1137 ({ })
1138 #endif
1140 /* RTR list */
1141 #define RTR_LOCK(core) \
1142 ({ corelock_lock(&cores[core].rtr_cl); })
1143 #define RTR_UNLOCK(core) \
1144 ({ corelock_unlock(&cores[core].rtr_cl); })
1146 #ifdef HAVE_PRIORITY_SCHEDULING
1147 #define rtr_add_entry(core, priority) \
1148 prio_add_entry(&cores[core].rtr, (priority))
1150 #define rtr_subtract_entry(core, priority) \
1151 prio_subtract_entry(&cores[core].rtr, (priority))
1153 #define rtr_move_entry(core, from, to) \
1154 prio_move_entry(&cores[core].rtr, (from), (to))
1155 #else
1156 #define rtr_add_entry(core, priority)
1157 #define rtr_add_entry_inl(core, priority)
1158 #define rtr_subtract_entry(core, priority)
1159 #define rtr_subtract_entry_inl(core, priotity)
1160 #define rtr_move_entry(core, from, to)
1161 #define rtr_move_entry_inl(core, from, to)
1162 #endif
1164 /*---------------------------------------------------------------------------
1165 * Thread list structure - circular:
1166 * +------------------------------+
1167 * | |
1168 * +--+---+<-+---+<-+---+<-+---+<-+
1169 * Head->| T | | T | | T | | T |
1170 * +->+---+->+---+->+---+->+---+--+
1171 * | |
1172 * +------------------------------+
1173 *---------------------------------------------------------------------------
1176 /*---------------------------------------------------------------------------
1177 * Adds a thread to a list of threads using "insert last". Uses the "l"
1178 * links.
1179 *---------------------------------------------------------------------------
1181 static void add_to_list_l(struct thread_entry **list,
1182 struct thread_entry *thread)
1184 struct thread_entry *l = *list;
1186 if (l == NULL)
1188 /* Insert into unoccupied list */
1189 thread->l.prev = thread;
1190 thread->l.next = thread;
1191 *list = thread;
1192 return;
1195 /* Insert last */
1196 thread->l.prev = l->l.prev;
1197 thread->l.next = l;
1198 l->l.prev->l.next = thread;
1199 l->l.prev = thread;
1202 /*---------------------------------------------------------------------------
1203 * Removes a thread from a list of threads. Uses the "l" links.
1204 *---------------------------------------------------------------------------
1206 static void remove_from_list_l(struct thread_entry **list,
1207 struct thread_entry *thread)
1209 struct thread_entry *prev, *next;
1211 next = thread->l.next;
1213 if (thread == next)
1215 /* The only item */
1216 *list = NULL;
1217 return;
1220 if (thread == *list)
1222 /* List becomes next item */
1223 *list = next;
1226 prev = thread->l.prev;
1228 /* Fix links to jump over the removed entry. */
1229 next->l.prev = prev;
1230 prev->l.next = next;
1233 /*---------------------------------------------------------------------------
1234 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1235 * NULL-terminated forward (to ease the far more common forward traversal):
1236 * +------------------------------+
1237 * | |
1238 * +--+---+<-+---+<-+---+<-+---+<-+
1239 * Head->| T | | T | | T | | T |
1240 * +---+->+---+->+---+->+---+-X
1241 *---------------------------------------------------------------------------
1244 /*---------------------------------------------------------------------------
1245 * Add a thread from the core's timout list by linking the pointers in its
1246 * tmo structure.
1247 *---------------------------------------------------------------------------
1249 static void add_to_list_tmo(struct thread_entry *thread)
1251 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1252 THREAD_ASSERT(thread->tmo.prev == NULL,
1253 "add_to_list_tmo->already listed", thread);
1255 thread->tmo.next = NULL;
1257 if (tmo == NULL)
1259 /* Insert into unoccupied list */
1260 thread->tmo.prev = thread;
1261 cores[IF_COP_CORE(thread->core)].timeout = thread;
1262 return;
1265 /* Insert Last */
1266 thread->tmo.prev = tmo->tmo.prev;
1267 tmo->tmo.prev->tmo.next = thread;
1268 tmo->tmo.prev = thread;
1271 /*---------------------------------------------------------------------------
1272 * Remove a thread from the core's timout list by unlinking the pointers in
1273 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1274 * is cancelled.
1275 *---------------------------------------------------------------------------
1277 static void remove_from_list_tmo(struct thread_entry *thread)
1279 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1280 struct thread_entry *prev = thread->tmo.prev;
1281 struct thread_entry *next = thread->tmo.next;
1283 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1285 if (next != NULL)
1286 next->tmo.prev = prev;
1288 if (thread == *list)
1290 /* List becomes next item and empty if next == NULL */
1291 *list = next;
1292 /* Mark as unlisted */
1293 thread->tmo.prev = NULL;
1295 else
1297 if (next == NULL)
1298 (*list)->tmo.prev = prev;
1299 prev->tmo.next = next;
1300 /* Mark as unlisted */
1301 thread->tmo.prev = NULL;
1306 #ifdef HAVE_PRIORITY_SCHEDULING
1307 /*---------------------------------------------------------------------------
1308 * Priority distribution structure (one category for each possible priority):
1310 * +----+----+----+ ... +-----+
1311 * hist: | F0 | F1 | F2 | | F31 |
1312 * +----+----+----+ ... +-----+
1313 * mask: | b0 | b1 | b2 | | b31 |
1314 * +----+----+----+ ... +-----+
1316 * F = count of threads at priority category n (frequency)
1317 * b = bitmask of non-zero priority categories (occupancy)
1319 * / if H[n] != 0 : 1
1320 * b[n] = |
1321 * \ else : 0
1323 *---------------------------------------------------------------------------
1324 * Basic priority inheritance priotocol (PIP):
1326 * Mn = mutex n, Tn = thread n
1328 * A lower priority thread inherits the priority of the highest priority
1329 * thread blocked waiting for it to complete an action (such as release a
1330 * mutex or respond to a message via queue_send):
1332 * 1) T2->M1->T1
1334 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1335 * priority than T1 then T1 inherits the priority of T2.
1337 * 2) T3
1338 * \/
1339 * T2->M1->T1
1341 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1342 * T1 inherits the higher of T2 and T3.
1344 * 3) T3->M2->T2->M1->T1
1346 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1347 * then T1 inherits the priority of T3 through T2.
1349 * Blocking chains can grow arbitrarily complex (though it's best that they
1350 * not form at all very often :) and build-up from these units.
1351 *---------------------------------------------------------------------------
1354 /*---------------------------------------------------------------------------
1355 * Increment frequency at category "priority"
1356 *---------------------------------------------------------------------------
1358 static inline unsigned int prio_add_entry(
1359 struct priority_distribution *pd, int priority)
1361 unsigned int count;
1362 /* Enough size/instruction count difference for ARM makes it worth it to
1363 * use different code (192 bytes for ARM). Only thing better is ASM. */
1364 #ifdef CPU_ARM
1365 count = pd->hist[priority];
1366 if (++count == 1)
1367 pd->mask |= 1 << priority;
1368 pd->hist[priority] = count;
1369 #else /* This one's better for Coldfire */
1370 if ((count = ++pd->hist[priority]) == 1)
1371 pd->mask |= 1 << priority;
1372 #endif
1374 return count;
1377 /*---------------------------------------------------------------------------
1378 * Decrement frequency at category "priority"
1379 *---------------------------------------------------------------------------
1381 static inline unsigned int prio_subtract_entry(
1382 struct priority_distribution *pd, int priority)
1384 unsigned int count;
1386 #ifdef CPU_ARM
1387 count = pd->hist[priority];
1388 if (--count == 0)
1389 pd->mask &= ~(1 << priority);
1390 pd->hist[priority] = count;
1391 #else
1392 if ((count = --pd->hist[priority]) == 0)
1393 pd->mask &= ~(1 << priority);
1394 #endif
1396 return count;
1399 /*---------------------------------------------------------------------------
1400 * Remove from one category and add to another
1401 *---------------------------------------------------------------------------
1403 static inline void prio_move_entry(
1404 struct priority_distribution *pd, int from, int to)
1406 uint32_t mask = pd->mask;
1408 #ifdef CPU_ARM
1409 unsigned int count;
1411 count = pd->hist[from];
1412 if (--count == 0)
1413 mask &= ~(1 << from);
1414 pd->hist[from] = count;
1416 count = pd->hist[to];
1417 if (++count == 1)
1418 mask |= 1 << to;
1419 pd->hist[to] = count;
1420 #else
1421 if (--pd->hist[from] == 0)
1422 mask &= ~(1 << from);
1424 if (++pd->hist[to] == 1)
1425 mask |= 1 << to;
1426 #endif
1428 pd->mask = mask;
1431 /*---------------------------------------------------------------------------
1432 * Change the priority and rtr entry for a running thread
1433 *---------------------------------------------------------------------------
1435 static inline void set_running_thread_priority(
1436 struct thread_entry *thread, int priority)
1438 const unsigned int core = IF_COP_CORE(thread->core);
1439 RTR_LOCK(core);
1440 rtr_move_entry(core, thread->priority, priority);
1441 thread->priority = priority;
1442 RTR_UNLOCK(core);
1445 /*---------------------------------------------------------------------------
1446 * Finds the highest priority thread in a list of threads. If the list is
1447 * empty, the PRIORITY_IDLE is returned.
1449 * It is possible to use the struct priority_distribution within an object
1450 * instead of scanning the remaining threads in the list but as a compromise,
1451 * the resulting per-object memory overhead is saved at a slight speed
1452 * penalty under high contention.
1453 *---------------------------------------------------------------------------
1455 static int find_highest_priority_in_list_l(
1456 struct thread_entry * const thread)
1458 if (LIKELY(thread != NULL))
1460 /* Go though list until the ending up at the initial thread */
1461 int highest_priority = thread->priority;
1462 struct thread_entry *curr = thread;
1466 int priority = curr->priority;
1468 if (priority < highest_priority)
1469 highest_priority = priority;
1471 curr = curr->l.next;
1473 while (curr != thread);
1475 return highest_priority;
1478 return PRIORITY_IDLE;
1481 /*---------------------------------------------------------------------------
1482 * Register priority with blocking system and bubble it down the chain if
1483 * any until we reach the end or something is already equal or higher.
1485 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1486 * targets but that same action also guarantees a circular block anyway and
1487 * those are prevented, right? :-)
1488 *---------------------------------------------------------------------------
1490 static struct thread_entry *
1491 blocker_inherit_priority(struct thread_entry *current)
1493 const int priority = current->priority;
1494 struct blocker *bl = current->blocker;
1495 struct thread_entry * const tstart = current;
1496 struct thread_entry *bl_t = bl->thread;
1498 /* Blocker cannot change since the object protection is held */
1499 LOCK_THREAD(bl_t);
1501 for (;;)
1503 struct thread_entry *next;
1504 int bl_pr = bl->priority;
1506 if (priority >= bl_pr)
1507 break; /* Object priority already high enough */
1509 bl->priority = priority;
1511 /* Add this one */
1512 prio_add_entry(&bl_t->pdist, priority);
1514 if (bl_pr < PRIORITY_IDLE)
1516 /* Not first waiter - subtract old one */
1517 prio_subtract_entry(&bl_t->pdist, bl_pr);
1520 if (priority >= bl_t->priority)
1521 break; /* Thread priority high enough */
1523 if (bl_t->state == STATE_RUNNING)
1525 /* Blocking thread is a running thread therefore there are no
1526 * further blockers. Change the "run queue" on which it
1527 * resides. */
1528 set_running_thread_priority(bl_t, priority);
1529 break;
1532 bl_t->priority = priority;
1534 /* If blocking thread has a blocker, apply transitive inheritance */
1535 bl = bl_t->blocker;
1537 if (bl == NULL)
1538 break; /* End of chain or object doesn't support inheritance */
1540 next = bl->thread;
1542 if (UNLIKELY(next == tstart))
1543 break; /* Full-circle - deadlock! */
1545 UNLOCK_THREAD(current);
1547 #if NUM_CORES > 1
1548 for (;;)
1550 LOCK_THREAD(next);
1552 /* Blocker could change - retest condition */
1553 if (LIKELY(bl->thread == next))
1554 break;
1556 UNLOCK_THREAD(next);
1557 next = bl->thread;
1559 #endif
1560 current = bl_t;
1561 bl_t = next;
1564 UNLOCK_THREAD(bl_t);
1566 return current;
1569 /*---------------------------------------------------------------------------
1570 * Readjust priorities when waking a thread blocked waiting for another
1571 * in essence "releasing" the thread's effect on the object owner. Can be
1572 * performed from any context.
1573 *---------------------------------------------------------------------------
1575 struct thread_entry *
1576 wakeup_priority_protocol_release(struct thread_entry *thread)
1578 const int priority = thread->priority;
1579 struct blocker *bl = thread->blocker;
1580 struct thread_entry * const tstart = thread;
1581 struct thread_entry *bl_t = bl->thread;
1583 /* Blocker cannot change since object will be locked */
1584 LOCK_THREAD(bl_t);
1586 thread->blocker = NULL; /* Thread not blocked */
1588 for (;;)
1590 struct thread_entry *next;
1591 int bl_pr = bl->priority;
1593 if (priority > bl_pr)
1594 break; /* Object priority higher */
1596 next = *thread->bqp;
1598 if (next == NULL)
1600 /* No more threads in queue */
1601 prio_subtract_entry(&bl_t->pdist, bl_pr);
1602 bl->priority = PRIORITY_IDLE;
1604 else
1606 /* Check list for highest remaining priority */
1607 int queue_pr = find_highest_priority_in_list_l(next);
1609 if (queue_pr == bl_pr)
1610 break; /* Object priority not changing */
1612 /* Change queue priority */
1613 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1614 bl->priority = queue_pr;
1617 if (bl_pr > bl_t->priority)
1618 break; /* thread priority is higher */
1620 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1622 if (bl_pr == bl_t->priority)
1623 break; /* Thread priority not changing */
1625 if (bl_t->state == STATE_RUNNING)
1627 /* No further blockers */
1628 set_running_thread_priority(bl_t, bl_pr);
1629 break;
1632 bl_t->priority = bl_pr;
1634 /* If blocking thread has a blocker, apply transitive inheritance */
1635 bl = bl_t->blocker;
1637 if (bl == NULL)
1638 break; /* End of chain or object doesn't support inheritance */
1640 next = bl->thread;
1642 if (UNLIKELY(next == tstart))
1643 break; /* Full-circle - deadlock! */
1645 UNLOCK_THREAD(thread);
1647 #if NUM_CORES > 1
1648 for (;;)
1650 LOCK_THREAD(next);
1652 /* Blocker could change - retest condition */
1653 if (LIKELY(bl->thread == next))
1654 break;
1656 UNLOCK_THREAD(next);
1657 next = bl->thread;
1659 #endif
1660 thread = bl_t;
1661 bl_t = next;
1664 UNLOCK_THREAD(bl_t);
1666 #if NUM_CORES > 1
1667 if (UNLIKELY(thread != tstart))
1669 /* Relock original if it changed */
1670 LOCK_THREAD(tstart);
1672 #endif
1674 return cores[CURRENT_CORE].running;
1677 /*---------------------------------------------------------------------------
1678 * Transfer ownership to a thread waiting for an objects and transfer
1679 * inherited priority boost from other waiters. This algorithm knows that
1680 * blocking chains may only unblock from the very end.
1682 * Only the owning thread itself may call this and so the assumption that
1683 * it is the running thread is made.
1684 *---------------------------------------------------------------------------
1686 struct thread_entry *
1687 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1689 /* Waking thread inherits priority boost from object owner */
1690 struct blocker *bl = thread->blocker;
1691 struct thread_entry *bl_t = bl->thread;
1692 struct thread_entry *next;
1693 int bl_pr;
1695 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
1696 "UPPT->wrong thread", cores[CURRENT_CORE].running);
1698 LOCK_THREAD(bl_t);
1700 bl_pr = bl->priority;
1702 /* Remove the object's boost from the owning thread */
1703 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1704 bl_pr <= bl_t->priority)
1706 /* No more threads at this priority are waiting and the old level is
1707 * at least the thread level */
1708 int priority = find_first_set_bit(bl_t->pdist.mask);
1710 if (priority != bl_t->priority)
1712 /* Adjust this thread's priority */
1713 set_running_thread_priority(bl_t, priority);
1717 next = *thread->bqp;
1719 if (LIKELY(next == NULL))
1721 /* Expected shortcut - no more waiters */
1722 bl_pr = PRIORITY_IDLE;
1724 else
1726 if (thread->priority <= bl_pr)
1728 /* Need to scan threads remaining in queue */
1729 bl_pr = find_highest_priority_in_list_l(next);
1732 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1733 bl_pr < thread->priority)
1735 /* Thread priority must be raised */
1736 thread->priority = bl_pr;
1740 bl->thread = thread; /* This thread pwns */
1741 bl->priority = bl_pr; /* Save highest blocked priority */
1742 thread->blocker = NULL; /* Thread not blocked */
1744 UNLOCK_THREAD(bl_t);
1746 return bl_t;
1749 /*---------------------------------------------------------------------------
1750 * No threads must be blocked waiting for this thread except for it to exit.
1751 * The alternative is more elaborate cleanup and object registration code.
1752 * Check this for risk of silent data corruption when objects with
1753 * inheritable blocking are abandoned by the owner - not precise but may
1754 * catch something.
1755 *---------------------------------------------------------------------------
1757 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1759 /* Only one bit in the mask should be set with a frequency on 1 which
1760 * represents the thread's own base priority */
1761 uint32_t mask = thread->pdist.mask;
1762 if ((mask & (mask - 1)) != 0 ||
1763 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1765 unsigned char name[32];
1766 thread_get_name(name, 32, thread);
1767 panicf("%s->%s with obj. waiters", function, name);
1770 #endif /* HAVE_PRIORITY_SCHEDULING */
1772 /*---------------------------------------------------------------------------
1773 * Move a thread back to a running state on its core.
1774 *---------------------------------------------------------------------------
1776 static void core_schedule_wakeup(struct thread_entry *thread)
1778 const unsigned int core = IF_COP_CORE(thread->core);
1780 RTR_LOCK(core);
1782 thread->state = STATE_RUNNING;
1784 add_to_list_l(&cores[core].running, thread);
1785 rtr_add_entry(core, thread->priority);
1787 RTR_UNLOCK(core);
1789 #if NUM_CORES > 1
1790 if (core != CURRENT_CORE)
1791 core_wake(core);
1792 #endif
1795 /*---------------------------------------------------------------------------
1796 * Check the core's timeout list when at least one thread is due to wake.
1797 * Filtering for the condition is done before making the call. Resets the
1798 * tick when the next check will occur.
1799 *---------------------------------------------------------------------------
1801 void check_tmo_threads(void)
1803 const unsigned int core = CURRENT_CORE;
1804 const long tick = current_tick; /* snapshot the current tick */
1805 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1806 struct thread_entry *next = cores[core].timeout;
1808 /* If there are no processes waiting for a timeout, just keep the check
1809 tick from falling into the past. */
1811 /* Break the loop once we have walked through the list of all
1812 * sleeping processes or have removed them all. */
1813 while (next != NULL)
1815 /* Check sleeping threads. Allow interrupts between checks. */
1816 enable_irq();
1818 struct thread_entry *curr = next;
1820 next = curr->tmo.next;
1822 /* Lock thread slot against explicit wakeup */
1823 disable_irq();
1824 LOCK_THREAD(curr);
1826 unsigned state = curr->state;
1828 if (state < TIMEOUT_STATE_FIRST)
1830 /* Cleanup threads no longer on a timeout but still on the
1831 * list. */
1832 remove_from_list_tmo(curr);
1834 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
1836 /* Timeout still pending - this will be the usual case */
1837 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1839 /* Earliest timeout found so far - move the next check up
1840 to its time */
1841 next_tmo_check = curr->tmo_tick;
1844 else
1846 /* Sleep timeout has been reached so bring the thread back to
1847 * life again. */
1848 if (state == STATE_BLOCKED_W_TMO)
1850 #if NUM_CORES > 1
1851 /* Lock the waiting thread's kernel object */
1852 struct corelock *ocl = curr->obj_cl;
1854 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1856 /* Need to retry in the correct order though the need is
1857 * unlikely */
1858 UNLOCK_THREAD(curr);
1859 corelock_lock(ocl);
1860 LOCK_THREAD(curr);
1862 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
1864 /* Thread was woken or removed explicitely while slot
1865 * was unlocked */
1866 corelock_unlock(ocl);
1867 remove_from_list_tmo(curr);
1868 UNLOCK_THREAD(curr);
1869 continue;
1872 #endif /* NUM_CORES */
1874 remove_from_list_l(curr->bqp, curr);
1876 #ifdef HAVE_WAKEUP_EXT_CB
1877 if (curr->wakeup_ext_cb != NULL)
1878 curr->wakeup_ext_cb(curr);
1879 #endif
1881 #ifdef HAVE_PRIORITY_SCHEDULING
1882 if (curr->blocker != NULL)
1883 wakeup_priority_protocol_release(curr);
1884 #endif
1885 corelock_unlock(ocl);
1887 /* else state == STATE_SLEEPING */
1889 remove_from_list_tmo(curr);
1891 RTR_LOCK(core);
1893 curr->state = STATE_RUNNING;
1895 add_to_list_l(&cores[core].running, curr);
1896 rtr_add_entry(core, curr->priority);
1898 RTR_UNLOCK(core);
1901 UNLOCK_THREAD(curr);
1904 cores[core].next_tmo_check = next_tmo_check;
1907 /*---------------------------------------------------------------------------
1908 * Performs operations that must be done before blocking a thread but after
1909 * the state is saved.
1910 *---------------------------------------------------------------------------
1912 #if NUM_CORES > 1
1913 static inline void run_blocking_ops(
1914 unsigned int core, struct thread_entry *thread)
1916 struct thread_blk_ops *ops = &cores[core].blk_ops;
1917 const unsigned flags = ops->flags;
1919 if (LIKELY(flags == TBOP_CLEAR))
1920 return;
1922 switch (flags)
1924 case TBOP_SWITCH_CORE:
1925 core_switch_blk_op(core, thread);
1926 /* Fall-through */
1927 case TBOP_UNLOCK_CORELOCK:
1928 corelock_unlock(ops->cl_p);
1929 break;
1932 ops->flags = TBOP_CLEAR;
1934 #endif /* NUM_CORES > 1 */
1936 #ifdef RB_PROFILE
1937 void profile_thread(void)
1939 profstart(cores[CURRENT_CORE].running - threads);
1941 #endif
1943 /*---------------------------------------------------------------------------
1944 * Prepares a thread to block on an object's list and/or for a specified
1945 * duration - expects object and slot to be appropriately locked if needed
1946 * and interrupts to be masked.
1947 *---------------------------------------------------------------------------
1949 static inline void block_thread_on_l(struct thread_entry *thread,
1950 unsigned state)
1952 /* If inlined, unreachable branches will be pruned with no size penalty
1953 because state is passed as a constant parameter. */
1954 const unsigned int core = IF_COP_CORE(thread->core);
1956 /* Remove the thread from the list of running threads. */
1957 RTR_LOCK(core);
1958 remove_from_list_l(&cores[core].running, thread);
1959 rtr_subtract_entry(core, thread->priority);
1960 RTR_UNLOCK(core);
1962 /* Add a timeout to the block if not infinite */
1963 switch (state)
1965 case STATE_BLOCKED:
1966 case STATE_BLOCKED_W_TMO:
1967 /* Put the thread into a new list of inactive threads. */
1968 add_to_list_l(thread->bqp, thread);
1970 if (state == STATE_BLOCKED)
1971 break;
1973 /* Fall-through */
1974 case STATE_SLEEPING:
1975 /* If this thread times out sooner than any other thread, update
1976 next_tmo_check to its timeout */
1977 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1979 cores[core].next_tmo_check = thread->tmo_tick;
1982 if (thread->tmo.prev == NULL)
1984 add_to_list_tmo(thread);
1986 /* else thread was never removed from list - just keep it there */
1987 break;
1990 /* Remember the the next thread about to block. */
1991 cores[core].block_task = thread;
1993 /* Report new state. */
1994 thread->state = state;
1997 /*---------------------------------------------------------------------------
1998 * Switch thread in round robin fashion for any given priority. Any thread
1999 * that removed itself from the running list first must specify itself in
2000 * the paramter.
2002 * INTERNAL: Intended for use by kernel and not for programs.
2003 *---------------------------------------------------------------------------
2005 void switch_thread(void)
2008 const unsigned int core = CURRENT_CORE;
2009 struct thread_entry *block = cores[core].block_task;
2010 struct thread_entry *thread = cores[core].running;
2012 /* Get context to save - next thread to run is unknown until all wakeups
2013 * are evaluated */
2014 if (block != NULL)
2016 cores[core].block_task = NULL;
2018 #if NUM_CORES > 1
2019 if (UNLIKELY(thread == block))
2021 /* This was the last thread running and another core woke us before
2022 * reaching here. Force next thread selection to give tmo threads or
2023 * other threads woken before this block a first chance. */
2024 block = NULL;
2026 else
2027 #endif
2029 /* Blocking task is the old one */
2030 thread = block;
2034 #ifdef RB_PROFILE
2035 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
2036 #endif
2038 /* Begin task switching by saving our current context so that we can
2039 * restore the state of the current thread later to the point prior
2040 * to this call. */
2041 store_context(&thread->context);
2043 /* Check if the current thread stack is overflown */
2044 if (UNLIKELY(thread->stack[0] != DEADBEEF))
2045 thread_stkov(thread);
2047 #if NUM_CORES > 1
2048 /* Run any blocking operations requested before switching/sleeping */
2049 run_blocking_ops(core, thread);
2050 #endif
2052 #ifdef HAVE_PRIORITY_SCHEDULING
2053 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2054 /* Reset the value of thread's skip count */
2055 thread->skip_count = 0;
2056 #endif
2058 for (;;)
2060 /* If there are threads on a timeout and the earliest wakeup is due,
2061 * check the list and wake any threads that need to start running
2062 * again. */
2063 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2065 check_tmo_threads();
2068 disable_irq();
2069 RTR_LOCK(core);
2071 thread = cores[core].running;
2073 if (UNLIKELY(thread == NULL))
2075 /* Enter sleep mode to reduce power usage - woken up on interrupt
2076 * or wakeup request from another core - expected to enable
2077 * interrupts. */
2078 RTR_UNLOCK(core);
2079 core_sleep(IF_COP(core));
2081 else
2083 #ifdef HAVE_PRIORITY_SCHEDULING
2084 /* Select the new task based on priorities and the last time a
2085 * process got CPU time relative to the highest priority runnable
2086 * task. */
2087 struct priority_distribution *pd = &cores[core].rtr;
2088 int max = find_first_set_bit(pd->mask);
2090 if (block == NULL)
2092 /* Not switching on a block, tentatively select next thread */
2093 thread = thread->l.next;
2096 for (;;)
2098 int priority = thread->priority;
2099 int diff;
2101 /* This ridiculously simple method of aging seems to work
2102 * suspiciously well. It does tend to reward CPU hogs (under
2103 * yielding) but that's generally not desirable at all. On the
2104 * plus side, it, relatively to other threads, penalizes excess
2105 * yielding which is good if some high priority thread is
2106 * performing no useful work such as polling for a device to be
2107 * ready. Of course, aging is only employed when higher and lower
2108 * priority threads are runnable. The highest priority runnable
2109 * thread(s) are never skipped. */
2110 if (LIKELY(priority <= max) ||
2111 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2112 (diff = priority - max, ++thread->skip_count > diff*diff))
2114 cores[core].running = thread;
2115 break;
2118 thread = thread->l.next;
2120 #else
2121 /* Without priority use a simple FCFS algorithm */
2122 if (block == NULL)
2124 /* Not switching on a block, select next thread */
2125 thread = thread->l.next;
2126 cores[core].running = thread;
2128 #endif /* HAVE_PRIORITY_SCHEDULING */
2130 RTR_UNLOCK(core);
2131 enable_irq();
2132 break;
2136 /* And finally give control to the next thread. */
2137 load_context(&thread->context);
2139 #ifdef RB_PROFILE
2140 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
2141 #endif
2145 /*---------------------------------------------------------------------------
2146 * Sleeps a thread for at least a specified number of ticks with zero being
2147 * a wait until the next tick.
2149 * INTERNAL: Intended for use by kernel and not for programs.
2150 *---------------------------------------------------------------------------
2152 void sleep_thread(int ticks)
2154 struct thread_entry *current = cores[CURRENT_CORE].running;
2156 LOCK_THREAD(current);
2158 /* Set our timeout, remove from run list and join timeout list. */
2159 current->tmo_tick = current_tick + ticks + 1;
2160 block_thread_on_l(current, STATE_SLEEPING);
2162 UNLOCK_THREAD(current);
2165 /*---------------------------------------------------------------------------
2166 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2168 * INTERNAL: Intended for use by kernel objects and not for programs.
2169 *---------------------------------------------------------------------------
2171 void block_thread(struct thread_entry *current)
2173 /* Set the state to blocked and take us off of the run queue until we
2174 * are explicitly woken */
2175 LOCK_THREAD(current);
2177 /* Set the list for explicit wakeup */
2178 block_thread_on_l(current, STATE_BLOCKED);
2180 #ifdef HAVE_PRIORITY_SCHEDULING
2181 if (current->blocker != NULL)
2183 /* Object supports PIP */
2184 current = blocker_inherit_priority(current);
2186 #endif
2188 UNLOCK_THREAD(current);
2191 /*---------------------------------------------------------------------------
2192 * Block a thread on a blocking queue for a specified time interval or until
2193 * explicitly woken - whichever happens first.
2195 * INTERNAL: Intended for use by kernel objects and not for programs.
2196 *---------------------------------------------------------------------------
2198 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2200 /* Get the entry for the current running thread. */
2201 LOCK_THREAD(current);
2203 /* Set the state to blocked with the specified timeout */
2204 current->tmo_tick = current_tick + timeout;
2206 /* Set the list for explicit wakeup */
2207 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2209 #ifdef HAVE_PRIORITY_SCHEDULING
2210 if (current->blocker != NULL)
2212 /* Object supports PIP */
2213 current = blocker_inherit_priority(current);
2215 #endif
2217 UNLOCK_THREAD(current);
2220 /*---------------------------------------------------------------------------
2221 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2222 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2224 * This code should be considered a critical section by the caller meaning
2225 * that the object's corelock should be held.
2227 * INTERNAL: Intended for use by kernel objects and not for programs.
2228 *---------------------------------------------------------------------------
2230 unsigned int wakeup_thread(struct thread_entry **list)
2232 struct thread_entry *thread = *list;
2233 unsigned int result = THREAD_NONE;
2235 /* Check if there is a blocked thread at all. */
2236 if (thread == NULL)
2237 return result;
2239 LOCK_THREAD(thread);
2241 /* Determine thread's current state. */
2242 switch (thread->state)
2244 case STATE_BLOCKED:
2245 case STATE_BLOCKED_W_TMO:
2246 remove_from_list_l(list, thread);
2248 result = THREAD_OK;
2250 #ifdef HAVE_PRIORITY_SCHEDULING
2251 struct thread_entry *current;
2252 struct blocker *bl = thread->blocker;
2254 if (bl == NULL)
2256 /* No inheritance - just boost the thread by aging */
2257 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2258 thread->skip_count = thread->priority;
2259 current = cores[CURRENT_CORE].running;
2261 else
2263 /* Call the specified unblocking PIP */
2264 current = bl->wakeup_protocol(thread);
2267 if (current != NULL && thread->priority < current->priority
2268 IF_COP( && thread->core == current->core ))
2270 /* Woken thread is higher priority and exists on the same CPU core;
2271 * recommend a task switch. Knowing if this is an interrupt call
2272 * would be helpful here. */
2273 result |= THREAD_SWITCH;
2275 #endif /* HAVE_PRIORITY_SCHEDULING */
2277 core_schedule_wakeup(thread);
2278 break;
2280 /* Nothing to do. State is not blocked. */
2281 #if THREAD_EXTRA_CHECKS
2282 default:
2283 THREAD_PANICF("wakeup_thread->block invalid", thread);
2284 case STATE_RUNNING:
2285 case STATE_KILLED:
2286 break;
2287 #endif
2290 UNLOCK_THREAD(thread);
2291 return result;
2294 /*---------------------------------------------------------------------------
2295 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2296 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2297 * the queue must be locked first.
2299 * INTERNAL: Intended for use by kernel objects and not for programs.
2300 *---------------------------------------------------------------------------
2302 unsigned int thread_queue_wake(struct thread_entry **list)
2304 unsigned result = THREAD_NONE;
2306 for (;;)
2308 unsigned int rc = wakeup_thread(list);
2310 if (rc == THREAD_NONE)
2311 break; /* No more threads */
2313 result |= rc;
2316 return result;
2319 /*---------------------------------------------------------------------------
2320 * Assign the thread slot a new ID. Version is 1-255.
2321 *---------------------------------------------------------------------------
2323 static void new_thread_id(unsigned int slot_num,
2324 struct thread_entry *thread)
2326 unsigned int version =
2327 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
2328 & THREAD_ID_VERSION_MASK;
2330 /* If wrapped to 0, make it 1 */
2331 if (version == 0)
2332 version = 1u << THREAD_ID_VERSION_SHIFT;
2334 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
2337 /*---------------------------------------------------------------------------
2338 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2339 * will be locked on multicore.
2340 *---------------------------------------------------------------------------
2342 static struct thread_entry * find_empty_thread_slot(void)
2344 /* Any slot could be on an interrupt-accessible list */
2345 IF_COP( int oldlevel = disable_irq_save(); )
2346 struct thread_entry *thread = NULL;
2347 int n;
2349 for (n = 0; n < MAXTHREADS; n++)
2351 /* Obtain current slot state - lock it on multicore */
2352 struct thread_entry *t = &threads[n];
2353 LOCK_THREAD(t);
2355 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2357 /* Slot is empty - leave it locked and caller will unlock */
2358 thread = t;
2359 break;
2362 /* Finished examining slot - no longer busy - unlock on multicore */
2363 UNLOCK_THREAD(t);
2366 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2367 not accesible to them yet */
2368 return thread;
2371 /*---------------------------------------------------------------------------
2372 * Return the thread_entry pointer for a thread_id. Return the current
2373 * thread if the ID is 0 (alias for current).
2374 *---------------------------------------------------------------------------
2376 struct thread_entry * thread_id_entry(unsigned int thread_id)
2378 return (thread_id == THREAD_ID_CURRENT) ?
2379 cores[CURRENT_CORE].running :
2380 &threads[thread_id & THREAD_ID_SLOT_MASK];
2383 /*---------------------------------------------------------------------------
2384 * Place the current core in idle mode - woken up on interrupt or wake
2385 * request from another core.
2386 *---------------------------------------------------------------------------
2388 void core_idle(void)
2390 IF_COP( const unsigned int core = CURRENT_CORE; )
2391 disable_irq();
2392 core_sleep(IF_COP(core));
2395 /*---------------------------------------------------------------------------
2396 * Create a thread. If using a dual core architecture, specify which core to
2397 * start the thread on.
2399 * Return ID if context area could be allocated, else NULL.
2400 *---------------------------------------------------------------------------
2402 unsigned int create_thread(void (*function)(void),
2403 void* stack, size_t stack_size,
2404 unsigned flags, const char *name
2405 IF_PRIO(, int priority)
2406 IF_COP(, unsigned int core))
2408 unsigned int i;
2409 unsigned int stack_words;
2410 uintptr_t stackptr, stackend;
2411 struct thread_entry *thread;
2412 unsigned state;
2413 int oldlevel;
2415 thread = find_empty_thread_slot();
2416 if (thread == NULL)
2418 return 0;
2421 oldlevel = disable_irq_save();
2423 /* Munge the stack to make it easy to spot stack overflows */
2424 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2425 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2426 stack_size = stackend - stackptr;
2427 stack_words = stack_size / sizeof (uintptr_t);
2429 for (i = 0; i < stack_words; i++)
2431 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2434 /* Store interesting information */
2435 thread->name = name;
2436 thread->stack = (uintptr_t *)stackptr;
2437 thread->stack_size = stack_size;
2438 thread->queue = NULL;
2439 #ifdef HAVE_WAKEUP_EXT_CB
2440 thread->wakeup_ext_cb = NULL;
2441 #endif
2442 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2443 thread->cpu_boost = 0;
2444 #endif
2445 #ifdef HAVE_PRIORITY_SCHEDULING
2446 memset(&thread->pdist, 0, sizeof(thread->pdist));
2447 thread->blocker = NULL;
2448 thread->base_priority = priority;
2449 thread->priority = priority;
2450 thread->skip_count = priority;
2451 prio_add_entry(&thread->pdist, priority);
2452 #endif
2454 #if NUM_CORES > 1
2455 thread->core = core;
2457 /* Writeback stack munging or anything else before starting */
2458 if (core != CURRENT_CORE)
2460 flush_icache();
2462 #endif
2464 /* Thread is not on any timeout list but be a bit paranoid */
2465 thread->tmo.prev = NULL;
2467 state = (flags & CREATE_THREAD_FROZEN) ?
2468 STATE_FROZEN : STATE_RUNNING;
2470 thread->context.sp = (typeof (thread->context.sp))stackend;
2472 /* Load the thread's context structure with needed startup information */
2473 THREAD_STARTUP_INIT(core, thread, function);
2475 thread->state = state;
2476 i = thread->id; /* Snapshot while locked */
2478 if (state == STATE_RUNNING)
2479 core_schedule_wakeup(thread);
2481 UNLOCK_THREAD(thread);
2482 restore_irq(oldlevel);
2484 return i;
2487 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2488 /*---------------------------------------------------------------------------
2489 * Change the boost state of a thread boosting or unboosting the CPU
2490 * as required.
2491 *---------------------------------------------------------------------------
2493 static inline void boost_thread(struct thread_entry *thread, bool boost)
2495 if ((thread->cpu_boost != 0) != boost)
2497 thread->cpu_boost = boost;
2498 cpu_boost(boost);
2502 void trigger_cpu_boost(void)
2504 struct thread_entry *current = cores[CURRENT_CORE].running;
2505 boost_thread(current, true);
2508 void cancel_cpu_boost(void)
2510 struct thread_entry *current = cores[CURRENT_CORE].running;
2511 boost_thread(current, false);
2513 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2515 /*---------------------------------------------------------------------------
2516 * Block the current thread until another thread terminates. A thread may
2517 * wait on itself to terminate which prevents it from running again and it
2518 * will need to be killed externally.
2519 * Parameter is the ID as returned from create_thread().
2520 *---------------------------------------------------------------------------
2522 void thread_wait(unsigned int thread_id)
2524 struct thread_entry *current = cores[CURRENT_CORE].running;
2525 struct thread_entry *thread = thread_id_entry(thread_id);
2527 /* Lock thread-as-waitable-object lock */
2528 corelock_lock(&thread->waiter_cl);
2530 /* Be sure it hasn't been killed yet */
2531 if (thread_id == THREAD_ID_CURRENT ||
2532 (thread->id == thread_id && thread->state != STATE_KILLED))
2534 IF_COP( current->obj_cl = &thread->waiter_cl; )
2535 current->bqp = &thread->queue;
2537 disable_irq();
2538 block_thread(current);
2540 corelock_unlock(&thread->waiter_cl);
2542 switch_thread();
2543 return;
2546 corelock_unlock(&thread->waiter_cl);
2549 /*---------------------------------------------------------------------------
2550 * Exit the current thread. The Right Way to Do Things (TM).
2551 *---------------------------------------------------------------------------
2553 void thread_exit(void)
2555 const unsigned int core = CURRENT_CORE;
2556 struct thread_entry *current = cores[core].running;
2558 /* Cancel CPU boost if any */
2559 cancel_cpu_boost();
2561 disable_irq();
2563 corelock_lock(&current->waiter_cl);
2564 LOCK_THREAD(current);
2566 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2567 if (current->name == THREAD_DESTRUCT)
2569 /* Thread being killed - become a waiter */
2570 unsigned int id = current->id;
2571 UNLOCK_THREAD(current);
2572 corelock_unlock(&current->waiter_cl);
2573 thread_wait(id);
2574 THREAD_PANICF("thread_exit->WK:*R", current);
2576 #endif
2578 #ifdef HAVE_PRIORITY_SCHEDULING
2579 check_for_obj_waiters("thread_exit", current);
2580 #endif
2582 if (current->tmo.prev != NULL)
2584 /* Cancel pending timeout list removal */
2585 remove_from_list_tmo(current);
2588 /* Switch tasks and never return */
2589 block_thread_on_l(current, STATE_KILLED);
2591 #if NUM_CORES > 1
2592 /* Switch to the idle stack if not on the main core (where "main"
2593 * runs) - we can hope gcc doesn't need the old stack beyond this
2594 * point. */
2595 if (core != CPU)
2597 switch_to_idle_stack(core);
2600 flush_icache();
2602 /* At this point, this thread isn't using resources allocated for
2603 * execution except the slot itself. */
2604 #endif
2606 /* Update ID for this slot */
2607 new_thread_id(current->id, current);
2608 current->name = NULL;
2610 /* Signal this thread */
2611 thread_queue_wake(&current->queue);
2612 corelock_unlock(&current->waiter_cl);
2613 /* Slot must be unusable until thread is really gone */
2614 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2615 switch_thread();
2616 /* This should never and must never be reached - if it is, the
2617 * state is corrupted */
2618 THREAD_PANICF("thread_exit->K:*R", current);
2621 #ifdef ALLOW_REMOVE_THREAD
2622 /*---------------------------------------------------------------------------
2623 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2624 * normal programs.
2626 * Parameter is the ID as returned from create_thread().
2628 * Use with care on threads that are not under careful control as this may
2629 * leave various objects in an undefined state.
2630 *---------------------------------------------------------------------------
2632 void remove_thread(unsigned int thread_id)
2634 #if NUM_CORES > 1
2635 /* core is not constant here because of core switching */
2636 unsigned int core = CURRENT_CORE;
2637 unsigned int old_core = NUM_CORES;
2638 struct corelock *ocl = NULL;
2639 #else
2640 const unsigned int core = CURRENT_CORE;
2641 #endif
2642 struct thread_entry *current = cores[core].running;
2643 struct thread_entry *thread = thread_id_entry(thread_id);
2645 unsigned state;
2646 int oldlevel;
2648 if (thread == current)
2649 thread_exit(); /* Current thread - do normal exit */
2651 oldlevel = disable_irq_save();
2653 corelock_lock(&thread->waiter_cl);
2654 LOCK_THREAD(thread);
2656 state = thread->state;
2658 if (thread->id != thread_id || state == STATE_KILLED)
2659 goto thread_killed;
2661 #if NUM_CORES > 1
2662 if (thread->name == THREAD_DESTRUCT)
2664 /* Thread being killed - become a waiter */
2665 UNLOCK_THREAD(thread);
2666 corelock_unlock(&thread->waiter_cl);
2667 restore_irq(oldlevel);
2668 thread_wait(thread_id);
2669 return;
2672 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2674 #ifdef HAVE_PRIORITY_SCHEDULING
2675 check_for_obj_waiters("remove_thread", thread);
2676 #endif
2678 if (thread->core != core)
2680 /* Switch cores and safely extract the thread there */
2681 /* Slot HAS to be unlocked or a deadlock could occur which means other
2682 * threads have to be guided into becoming thread waiters if they
2683 * attempt to remove it. */
2684 unsigned int new_core = thread->core;
2686 corelock_unlock(&thread->waiter_cl);
2688 UNLOCK_THREAD(thread);
2689 restore_irq(oldlevel);
2691 old_core = switch_core(new_core);
2693 oldlevel = disable_irq_save();
2695 corelock_lock(&thread->waiter_cl);
2696 LOCK_THREAD(thread);
2698 state = thread->state;
2699 core = new_core;
2700 /* Perform the extraction and switch ourselves back to the original
2701 processor */
2703 #endif /* NUM_CORES > 1 */
2705 if (thread->tmo.prev != NULL)
2707 /* Clean thread off the timeout list if a timeout check hasn't
2708 * run yet */
2709 remove_from_list_tmo(thread);
2712 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2713 /* Cancel CPU boost if any */
2714 boost_thread(thread, false);
2715 #endif
2717 IF_COP( retry_state: )
2719 switch (state)
2721 case STATE_RUNNING:
2722 RTR_LOCK(core);
2723 /* Remove thread from ready to run tasks */
2724 remove_from_list_l(&cores[core].running, thread);
2725 rtr_subtract_entry(core, thread->priority);
2726 RTR_UNLOCK(core);
2727 break;
2728 case STATE_BLOCKED:
2729 case STATE_BLOCKED_W_TMO:
2730 /* Remove thread from the queue it's blocked on - including its
2731 * own if waiting there */
2732 #if NUM_CORES > 1
2733 if (&thread->waiter_cl != thread->obj_cl)
2735 ocl = thread->obj_cl;
2737 if (UNLIKELY(corelock_try_lock(ocl) == 0))
2739 UNLOCK_THREAD(thread);
2740 corelock_lock(ocl);
2741 LOCK_THREAD(thread);
2743 if (UNLIKELY(thread->state != state))
2745 /* Something woke the thread */
2746 state = thread->state;
2747 corelock_unlock(ocl);
2748 goto retry_state;
2752 #endif
2753 remove_from_list_l(thread->bqp, thread);
2755 #ifdef HAVE_WAKEUP_EXT_CB
2756 if (thread->wakeup_ext_cb != NULL)
2757 thread->wakeup_ext_cb(thread);
2758 #endif
2760 #ifdef HAVE_PRIORITY_SCHEDULING
2761 if (thread->blocker != NULL)
2763 /* Remove thread's priority influence from its chain */
2764 wakeup_priority_protocol_release(thread);
2766 #endif
2768 #if NUM_CORES > 1
2769 if (ocl != NULL)
2770 corelock_unlock(ocl);
2771 #endif
2772 break;
2773 /* Otherwise thread is frozen and hasn't run yet */
2776 new_thread_id(thread_id, thread);
2777 thread->state = STATE_KILLED;
2779 /* If thread was waiting on itself, it will have been removed above.
2780 * The wrong order would result in waking the thread first and deadlocking
2781 * since the slot is already locked. */
2782 thread_queue_wake(&thread->queue);
2784 thread->name = NULL;
2786 thread_killed: /* Thread was already killed */
2787 /* Removal complete - safe to unlock and reenable interrupts */
2788 corelock_unlock(&thread->waiter_cl);
2789 UNLOCK_THREAD(thread);
2790 restore_irq(oldlevel);
2792 #if NUM_CORES > 1
2793 if (old_core < NUM_CORES)
2795 /* Did a removal on another processor's thread - switch back to
2796 native core */
2797 switch_core(old_core);
2799 #endif
2801 #endif /* ALLOW_REMOVE_THREAD */
2803 #ifdef HAVE_PRIORITY_SCHEDULING
2804 /*---------------------------------------------------------------------------
2805 * Sets the thread's relative base priority for the core it runs on. Any
2806 * needed inheritance changes also may happen.
2807 *---------------------------------------------------------------------------
2809 int thread_set_priority(unsigned int thread_id, int priority)
2811 int old_base_priority = -1;
2812 struct thread_entry *thread = thread_id_entry(thread_id);
2814 /* A little safety measure */
2815 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2816 return -1;
2818 /* Thread could be on any list and therefore on an interrupt accessible
2819 one - disable interrupts */
2820 int oldlevel = disable_irq_save();
2822 LOCK_THREAD(thread);
2824 /* Make sure it's not killed */
2825 if (thread_id == THREAD_ID_CURRENT ||
2826 (thread->id == thread_id && thread->state != STATE_KILLED))
2828 int old_priority = thread->priority;
2830 old_base_priority = thread->base_priority;
2831 thread->base_priority = priority;
2833 prio_move_entry(&thread->pdist, old_base_priority, priority);
2834 priority = find_first_set_bit(thread->pdist.mask);
2836 if (old_priority == priority)
2838 /* No priority change - do nothing */
2840 else if (thread->state == STATE_RUNNING)
2842 /* This thread is running - change location on the run
2843 * queue. No transitive inheritance needed. */
2844 set_running_thread_priority(thread, priority);
2846 else
2848 thread->priority = priority;
2850 if (thread->blocker != NULL)
2852 /* Bubble new priority down the chain */
2853 struct blocker *bl = thread->blocker; /* Blocker struct */
2854 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2855 struct thread_entry * const tstart = thread; /* Initial thread */
2856 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2858 for (;;)
2860 struct thread_entry *next; /* Next thread to check */
2861 int bl_pr; /* Highest blocked thread */
2862 int queue_pr; /* New highest blocked thread */
2863 #if NUM_CORES > 1
2864 /* Owner can change but thread cannot be dislodged - thread
2865 * may not be the first in the queue which allows other
2866 * threads ahead in the list to be given ownership during the
2867 * operation. If thread is next then the waker will have to
2868 * wait for us and the owner of the object will remain fixed.
2869 * If we successfully grab the owner -- which at some point
2870 * is guaranteed -- then the queue remains fixed until we
2871 * pass by. */
2872 for (;;)
2874 LOCK_THREAD(bl_t);
2876 /* Double-check the owner - retry if it changed */
2877 if (LIKELY(bl->thread == bl_t))
2878 break;
2880 UNLOCK_THREAD(bl_t);
2881 bl_t = bl->thread;
2883 #endif
2884 bl_pr = bl->priority;
2886 if (highest > bl_pr)
2887 break; /* Object priority won't change */
2889 /* This will include the thread being set */
2890 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2892 if (queue_pr == bl_pr)
2893 break; /* Object priority not changing */
2895 /* Update thread boost for this object */
2896 bl->priority = queue_pr;
2897 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2898 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2900 if (bl_t->priority == bl_pr)
2901 break; /* Blocking thread priority not changing */
2903 if (bl_t->state == STATE_RUNNING)
2905 /* Thread not blocked - we're done */
2906 set_running_thread_priority(bl_t, bl_pr);
2907 break;
2910 bl_t->priority = bl_pr;
2911 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2913 if (bl == NULL)
2914 break; /* End of chain */
2916 next = bl->thread;
2918 if (UNLIKELY(next == tstart))
2919 break; /* Full-circle */
2921 UNLOCK_THREAD(thread);
2923 thread = bl_t;
2924 bl_t = next;
2925 } /* for (;;) */
2927 UNLOCK_THREAD(bl_t);
2932 UNLOCK_THREAD(thread);
2934 restore_irq(oldlevel);
2936 return old_base_priority;
2939 /*---------------------------------------------------------------------------
2940 * Returns the current base priority for a thread.
2941 *---------------------------------------------------------------------------
2943 int thread_get_priority(unsigned int thread_id)
2945 struct thread_entry *thread = thread_id_entry(thread_id);
2946 int base_priority = thread->base_priority;
2948 /* Simply check without locking slot. It may or may not be valid by the
2949 * time the function returns anyway. If all tests pass, it is the
2950 * correct value for when it was valid. */
2951 if (thread_id != THREAD_ID_CURRENT &&
2952 (thread->id != thread_id || thread->state == STATE_KILLED))
2953 base_priority = -1;
2955 return base_priority;
2957 #endif /* HAVE_PRIORITY_SCHEDULING */
2959 /*---------------------------------------------------------------------------
2960 * Starts a frozen thread - similar semantics to wakeup_thread except that
2961 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2962 * virtue of the slot having a state of STATE_FROZEN.
2963 *---------------------------------------------------------------------------
2965 void thread_thaw(unsigned int thread_id)
2967 struct thread_entry *thread = thread_id_entry(thread_id);
2968 int oldlevel = disable_irq_save();
2970 LOCK_THREAD(thread);
2972 /* If thread is the current one, it cannot be frozen, therefore
2973 * there is no need to check that. */
2974 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2975 core_schedule_wakeup(thread);
2977 UNLOCK_THREAD(thread);
2978 restore_irq(oldlevel);
2981 /*---------------------------------------------------------------------------
2982 * Return the ID of the currently executing thread.
2983 *---------------------------------------------------------------------------
2985 unsigned int thread_get_current(void)
2987 return cores[CURRENT_CORE].running->id;
2990 #if NUM_CORES > 1
2991 /*---------------------------------------------------------------------------
2992 * Switch the processor that the currently executing thread runs on.
2993 *---------------------------------------------------------------------------
2995 unsigned int switch_core(unsigned int new_core)
2997 const unsigned int core = CURRENT_CORE;
2998 struct thread_entry *current = cores[core].running;
3000 if (core == new_core)
3002 /* No change - just return same core */
3003 return core;
3006 int oldlevel = disable_irq_save();
3007 LOCK_THREAD(current);
3009 if (current->name == THREAD_DESTRUCT)
3011 /* Thread being killed - deactivate and let process complete */
3012 unsigned int id = current->id;
3013 UNLOCK_THREAD(current);
3014 restore_irq(oldlevel);
3015 thread_wait(id);
3016 /* Should never be reached */
3017 THREAD_PANICF("switch_core->D:*R", current);
3020 /* Get us off the running list for the current core */
3021 RTR_LOCK(core);
3022 remove_from_list_l(&cores[core].running, current);
3023 rtr_subtract_entry(core, current->priority);
3024 RTR_UNLOCK(core);
3026 /* Stash return value (old core) in a safe place */
3027 current->retval = core;
3029 /* If a timeout hadn't yet been cleaned-up it must be removed now or
3030 * the other core will likely attempt a removal from the wrong list! */
3031 if (current->tmo.prev != NULL)
3033 remove_from_list_tmo(current);
3036 /* Change the core number for this thread slot */
3037 current->core = new_core;
3039 /* Do not use core_schedule_wakeup here since this will result in
3040 * the thread starting to run on the other core before being finished on
3041 * this one. Delay the list unlock to keep the other core stuck
3042 * until this thread is ready. */
3043 RTR_LOCK(new_core);
3045 rtr_add_entry(new_core, current->priority);
3046 add_to_list_l(&cores[new_core].running, current);
3048 /* Make a callback into device-specific code, unlock the wakeup list so
3049 * that execution may resume on the new core, unlock our slot and finally
3050 * restore the interrupt level */
3051 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3052 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3053 cores[core].block_task = current;
3055 UNLOCK_THREAD(current);
3057 /* Alert other core to activity */
3058 core_wake(new_core);
3060 /* Do the stack switching, cache_maintenence and switch_thread call -
3061 requires native code */
3062 switch_thread_core(core, current);
3064 /* Finally return the old core to caller */
3065 return current->retval;
3067 #endif /* NUM_CORES > 1 */
3069 /*---------------------------------------------------------------------------
3070 * Initialize threading API. This assumes interrupts are not yet enabled. On
3071 * multicore setups, no core is allowed to proceed until create_thread calls
3072 * are safe to perform.
3073 *---------------------------------------------------------------------------
3075 void init_threads(void)
3077 const unsigned int core = CURRENT_CORE;
3078 struct thread_entry *thread;
3080 if (core == CPU)
3082 /* Initialize core locks and IDs in all slots */
3083 int n;
3084 for (n = 0; n < MAXTHREADS; n++)
3086 thread = &threads[n];
3087 corelock_init(&thread->waiter_cl);
3088 corelock_init(&thread->slot_cl);
3089 thread->id = THREAD_ID_INIT(n);
3093 /* CPU will initialize first and then sleep */
3094 thread = find_empty_thread_slot();
3096 if (thread == NULL)
3098 /* WTF? There really must be a slot available at this stage.
3099 * This can fail if, for example, .bss isn't zero'ed out by the loader
3100 * or threads is in the wrong section. */
3101 THREAD_PANICF("init_threads->no slot", NULL);
3104 /* Initialize initially non-zero members of core */
3105 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3107 /* Initialize initially non-zero members of slot */
3108 UNLOCK_THREAD(thread); /* No sync worries yet */
3109 thread->name = main_thread_name;
3110 thread->state = STATE_RUNNING;
3111 IF_COP( thread->core = core; )
3112 #ifdef HAVE_PRIORITY_SCHEDULING
3113 corelock_init(&cores[core].rtr_cl);
3114 thread->base_priority = PRIORITY_USER_INTERFACE;
3115 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3116 thread->priority = PRIORITY_USER_INTERFACE;
3117 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3118 #endif
3120 add_to_list_l(&cores[core].running, thread);
3122 if (core == CPU)
3124 thread->stack = stackbegin;
3125 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3126 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3127 /* Wait for other processors to finish their inits since create_thread
3128 * isn't safe to call until the kernel inits are done. The first
3129 * threads created in the system must of course be created by CPU.
3130 * Another possible approach is to initialize all cores and slots
3131 * for each core by CPU, let the remainder proceed in parallel and
3132 * signal CPU when all are finished. */
3133 core_thread_init(CPU);
3135 else
3137 /* Initial stack is the idle stack */
3138 thread->stack = idle_stacks[core];
3139 thread->stack_size = IDLE_STACK_SIZE;
3140 /* After last processor completes, it should signal all others to
3141 * proceed or may signal the next and call thread_exit(). The last one
3142 * to finish will signal CPU. */
3143 core_thread_init(core);
3144 /* Other cores do not have a main thread - go idle inside switch_thread
3145 * until a thread can run on the core. */
3146 thread_exit();
3147 #endif /* NUM_CORES */
3151 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3152 #if NUM_CORES == 1
3153 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3154 #else
3155 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3156 #endif
3158 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3159 unsigned int i;
3160 int usage = 0;
3162 for (i = 0; i < stack_words; i++)
3164 if (stackptr[i] != DEADBEEF)
3166 usage = ((stack_words - i) * 100) / stack_words;
3167 break;
3171 return usage;
3174 /*---------------------------------------------------------------------------
3175 * Returns the maximum percentage of stack a thread ever used while running.
3176 * NOTE: Some large buffer allocations that don't use enough the buffer to
3177 * overwrite stackptr[0] will not be seen.
3178 *---------------------------------------------------------------------------
3180 int thread_stack_usage(const struct thread_entry *thread)
3182 return stack_usage(thread->stack, thread->stack_size);
3185 #if NUM_CORES > 1
3186 /*---------------------------------------------------------------------------
3187 * Returns the maximum percentage of the core's idle stack ever used during
3188 * runtime.
3189 *---------------------------------------------------------------------------
3191 int idle_stack_usage(unsigned int core)
3193 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3195 #endif
3197 /*---------------------------------------------------------------------------
3198 * Fills in the buffer with the specified thread's name. If the name is NULL,
3199 * empty, or the thread is in destruct state a formatted ID is written
3200 * instead.
3201 *---------------------------------------------------------------------------
3203 void thread_get_name(char *buffer, int size,
3204 struct thread_entry *thread)
3206 if (size <= 0)
3207 return;
3209 *buffer = '\0';
3211 if (thread)
3213 /* Display thread name if one or ID if none */
3214 const char *name = thread->name;
3215 const char *fmt = "%s";
3216 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3218 name = (const char *)thread;
3219 fmt = "%08lX";
3221 snprintf(buffer, size, fmt, name);