Make the mips compiler not complain when bitwise operations do not have parenthesis.
[kugel-rb.git] / firmware / thread.c
blob453fbf510a92f0f895ddce4275e2e03d4b9f6836
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "config.h"
22 #include <stdbool.h>
23 #include "thread.h"
24 #include "panic.h"
25 #include "sprintf.h"
26 #include "system.h"
27 #include "kernel.h"
28 #include "cpu.h"
29 #include "string.h"
30 #ifdef RB_PROFILE
31 #include <profile.h>
32 #endif
33 /****************************************************************************
34 * ATTENTION!! *
35 * See notes below on implementing processor-specific portions! *
36 ***************************************************************************/
38 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
39 #ifdef DEBUG
40 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
41 #else
42 #define THREAD_EXTRA_CHECKS 0
43 #endif
45 /**
46 * General locking order to guarantee progress. Order must be observed but
47 * all stages are not nescessarily obligatory. Going from 1) to 3) is
48 * perfectly legal.
50 * 1) IRQ
51 * This is first because of the likelyhood of having an interrupt occur that
52 * also accesses one of the objects farther down the list. Any non-blocking
53 * synchronization done may already have a lock on something during normal
54 * execution and if an interrupt handler running on the same processor as
55 * the one that has the resource locked were to attempt to access the
56 * resource, the interrupt handler would wait forever waiting for an unlock
57 * that will never happen. There is no danger if the interrupt occurs on
58 * a different processor because the one that has the lock will eventually
59 * unlock and the other processor's handler may proceed at that time. Not
60 * nescessary when the resource in question is definitely not available to
61 * interrupt handlers.
63 * 2) Kernel Object
64 * 1) May be needed beforehand if the kernel object allows dual-use such as
65 * event queues. The kernel object must have a scheme to protect itself from
66 * access by another processor and is responsible for serializing the calls
67 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
68 * other. Objects' queues are also protected here.
70 * 3) Thread Slot
71 * This locks access to the thread's slot such that its state cannot be
72 * altered by another processor when a state change is in progress such as
73 * when it is in the process of going on a blocked list. An attempt to wake
74 * a thread while it is still blocking will likely desync its state with
75 * the other resources used for that state.
77 * 4) Core Lists
78 * These lists are specific to a particular processor core and are accessible
79 * by all processor cores and interrupt handlers. The running (rtr) list is
80 * the prime example where a thread may be added by any means.
83 /*---------------------------------------------------------------------------
84 * Processor specific: core_sleep/core_wake/misc. notes
86 * ARM notes:
87 * FIQ is not dealt with by the scheduler code and is simply restored if it
88 * must by masked for some reason - because threading modifies a register
89 * that FIQ may also modify and there's no way to accomplish it atomically.
90 * s3c2440 is such a case.
92 * Audio interrupts are generally treated at a higher priority than others
93 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
94 * are not in general safe. Special cases may be constructed on a per-
95 * source basis and blocking operations are not available.
97 * core_sleep procedure to implement for any CPU to ensure an asychronous
98 * wakup never results in requiring a wait until the next tick (up to
99 * 10000uS!). May require assembly and careful instruction ordering.
101 * 1) On multicore, stay awake if directed to do so by another. If so, goto
102 * step 4.
103 * 2) If processor requires, atomically reenable interrupts and perform step
104 * 3.
105 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
106 * on Coldfire) goto step 5.
107 * 4) Enable interrupts.
108 * 5) Exit procedure.
110 * core_wake and multprocessor notes for sleep/wake coordination:
111 * If possible, to wake up another processor, the forcing of an interrupt on
112 * the woken core by the waker core is the easiest way to ensure a non-
113 * delayed wake and immediate execution of any woken threads. If that isn't
114 * available then some careful non-blocking synchonization is needed (as on
115 * PP targets at the moment).
116 *---------------------------------------------------------------------------
119 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
120 * (someday :). */
121 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
122 struct core_entry cores[NUM_CORES] IBSS_ATTR;
123 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
125 static const char main_thread_name[] = "main";
126 extern uintptr_t stackbegin[];
127 extern uintptr_t stackend[];
129 static inline void core_sleep(IF_COP_VOID(unsigned int core))
130 __attribute__((always_inline));
132 void check_tmo_threads(void)
133 __attribute__((noinline));
135 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
136 __attribute__((always_inline));
138 static void add_to_list_tmo(struct thread_entry *thread)
139 __attribute__((noinline));
141 static void core_schedule_wakeup(struct thread_entry *thread)
142 __attribute__((noinline));
144 #if NUM_CORES > 1
145 static inline void run_blocking_ops(
146 unsigned int core, struct thread_entry *thread)
147 __attribute__((always_inline));
148 #endif
150 static void thread_stkov(struct thread_entry *thread)
151 __attribute__((noinline));
153 static inline void store_context(void* addr)
154 __attribute__((always_inline));
156 static inline void load_context(const void* addr)
157 __attribute__((always_inline));
159 void switch_thread(void)
160 __attribute__((noinline));
162 /****************************************************************************
163 * Processor-specific section
166 #if defined(MAX_PHYS_SECTOR_SIZE) && MEM == 64
167 /* Support a special workaround object for large-sector disks */
168 #define IF_NO_SKIP_YIELD(...) __VA_ARGS__
169 #else
170 #define IF_NO_SKIP_YIELD(...)
171 #endif
173 #if defined(CPU_ARM)
174 /*---------------------------------------------------------------------------
175 * Start the thread running and terminate it if it returns
176 *---------------------------------------------------------------------------
178 static void __attribute__((naked,used)) start_thread(void)
180 /* r0 = context */
181 asm volatile (
182 "ldr sp, [r0, #32] \n" /* Load initial sp */
183 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
184 "mov r1, #0 \n" /* Mark thread as running */
185 "str r1, [r0, #40] \n"
186 #if NUM_CORES > 1
187 "ldr r0, =cpucache_invalidate \n" /* Invalidate this core's cache. */
188 "mov lr, pc \n" /* This could be the first entry into */
189 "bx r0 \n" /* plugin or codec code for this core. */
190 #endif
191 "mov lr, pc \n" /* Call thread function */
192 "bx r4 \n"
193 ); /* No clobber list - new thread doesn't care */
194 thread_exit();
195 //asm volatile (".ltorg"); /* Dump constant pool */
198 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
199 * slot, and thread function pointer in context.start. See load_context for
200 * what happens when thread is initially going to run. */
201 #define THREAD_STARTUP_INIT(core, thread, function) \
202 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
203 (thread)->context.r[1] = (uint32_t)start_thread, \
204 (thread)->context.start = (uint32_t)function; })
206 /*---------------------------------------------------------------------------
207 * Store non-volatile context.
208 *---------------------------------------------------------------------------
210 static inline void store_context(void* addr)
212 asm volatile(
213 "stmia %0, { r4-r11, sp, lr } \n"
214 : : "r" (addr)
218 /*---------------------------------------------------------------------------
219 * Load non-volatile context.
220 *---------------------------------------------------------------------------
222 static inline void load_context(const void* addr)
224 asm volatile(
225 "ldr r0, [%0, #40] \n" /* Load start pointer */
226 "cmp r0, #0 \n" /* Check for NULL */
227 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
228 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
229 : : "r" (addr) : "r0" /* only! */
233 #if defined (CPU_PP)
235 #if NUM_CORES > 1
236 extern uintptr_t cpu_idlestackbegin[];
237 extern uintptr_t cpu_idlestackend[];
238 extern uintptr_t cop_idlestackbegin[];
239 extern uintptr_t cop_idlestackend[];
240 static uintptr_t * const idle_stacks[NUM_CORES] =
242 [CPU] = cpu_idlestackbegin,
243 [COP] = cop_idlestackbegin
246 #if CONFIG_CPU == PP5002
247 /* Bytes to emulate the PP502x mailbox bits */
248 struct core_semaphores
250 volatile uint8_t intend_wake; /* 00h */
251 volatile uint8_t stay_awake; /* 01h */
252 volatile uint8_t intend_sleep; /* 02h */
253 volatile uint8_t unused; /* 03h */
256 static struct core_semaphores core_semaphores[NUM_CORES] IBSS_ATTR;
257 #endif /* CONFIG_CPU == PP5002 */
259 #endif /* NUM_CORES */
261 #if CONFIG_CORELOCK == SW_CORELOCK
262 /* Software core locks using Peterson's mutual exclusion algorithm */
264 /*---------------------------------------------------------------------------
265 * Initialize the corelock structure.
266 *---------------------------------------------------------------------------
268 void corelock_init(struct corelock *cl)
270 memset(cl, 0, sizeof (*cl));
273 #if 1 /* Assembly locks to minimize overhead */
274 /*---------------------------------------------------------------------------
275 * Wait for the corelock to become free and acquire it when it does.
276 *---------------------------------------------------------------------------
278 void corelock_lock(struct corelock *cl) __attribute__((naked));
279 void corelock_lock(struct corelock *cl)
281 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
282 asm volatile (
283 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
284 "ldrb r1, [r1] \n"
285 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
286 "eor r2, r1, #0xff \n" /* r2 = othercore */
287 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
288 "1: \n"
289 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
290 "cmp r3, #0 \n" /* yes? lock acquired */
291 "bxeq lr \n"
292 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
293 "cmp r3, r1 \n"
294 "bxeq lr \n" /* yes? lock acquired */
295 "b 1b \n" /* keep trying */
296 : : "i"(&PROCESSOR_ID)
298 (void)cl;
301 /*---------------------------------------------------------------------------
302 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
303 *---------------------------------------------------------------------------
305 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
306 int corelock_try_lock(struct corelock *cl)
308 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
309 asm volatile (
310 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
311 "ldrb r1, [r1] \n"
312 "mov r3, r0 \n"
313 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
314 "eor r2, r1, #0xff \n" /* r2 = othercore */
315 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
316 "ldrb r0, [r3, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
317 "eors r0, r0, r2 \n" /* yes? lock acquired */
318 "bxne lr \n"
319 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
320 "ands r0, r0, r1 \n"
321 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
322 "bx lr \n" /* return result */
323 : : "i"(&PROCESSOR_ID)
326 return 0;
327 (void)cl;
330 /*---------------------------------------------------------------------------
331 * Release ownership of the corelock
332 *---------------------------------------------------------------------------
334 void corelock_unlock(struct corelock *cl) __attribute__((naked));
335 void corelock_unlock(struct corelock *cl)
337 asm volatile (
338 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
339 "ldrb r1, [r1] \n"
340 "mov r2, #0 \n" /* cl->myl[core] = 0 */
341 "strb r2, [r0, r1, lsr #7] \n"
342 "bx lr \n"
343 : : "i"(&PROCESSOR_ID)
345 (void)cl;
347 #else /* C versions for reference */
348 /*---------------------------------------------------------------------------
349 * Wait for the corelock to become free and aquire it when it does.
350 *---------------------------------------------------------------------------
352 void corelock_lock(struct corelock *cl)
354 const unsigned int core = CURRENT_CORE;
355 const unsigned int othercore = 1 - core;
357 cl->myl[core] = core;
358 cl->turn = othercore;
360 for (;;)
362 if (cl->myl[othercore] == 0 || cl->turn == core)
363 break;
367 /*---------------------------------------------------------------------------
368 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
369 *---------------------------------------------------------------------------
371 int corelock_try_lock(struct corelock *cl)
373 const unsigned int core = CURRENT_CORE;
374 const unsigned int othercore = 1 - core;
376 cl->myl[core] = core;
377 cl->turn = othercore;
379 if (cl->myl[othercore] == 0 || cl->turn == core)
381 return 1;
384 cl->myl[core] = 0;
385 return 0;
388 /*---------------------------------------------------------------------------
389 * Release ownership of the corelock
390 *---------------------------------------------------------------------------
392 void corelock_unlock(struct corelock *cl)
394 cl->myl[CURRENT_CORE] = 0;
396 #endif /* ASM / C selection */
398 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
400 /*---------------------------------------------------------------------------
401 * Put core in a power-saving state if waking list wasn't repopulated and if
402 * no other core requested a wakeup for it to perform a task.
403 *---------------------------------------------------------------------------
405 #ifdef CPU_PP502x
406 #if NUM_CORES == 1
407 static inline void core_sleep(void)
409 sleep_core(CURRENT_CORE);
410 enable_irq();
412 #else
413 static inline void core_sleep(unsigned int core)
415 #if 1
416 asm volatile (
417 "mov r0, #4 \n" /* r0 = 0x4 << core */
418 "mov r0, r0, lsl %[c] \n"
419 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
420 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
421 "tst r1, r0, lsl #2 \n"
422 "moveq r1, #0x80000000 \n" /* Then sleep */
423 "streq r1, [%[ctl], %[c], lsl #2] \n"
424 "moveq r1, #0 \n" /* Clear control reg */
425 "streq r1, [%[ctl], %[c], lsl #2] \n"
426 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
427 "str r1, [%[mbx], #8] \n"
428 "1: \n" /* Wait for wake procedure to finish */
429 "ldr r1, [%[mbx], #0] \n"
430 "tst r1, r0, lsr #2 \n"
431 "bne 1b \n"
433 : [ctl]"r"(&CPU_CTL), [mbx]"r"(MBX_BASE), [c]"r"(core)
434 : "r0", "r1");
435 #else /* C version for reference */
436 /* Signal intent to sleep */
437 MBX_MSG_SET = 0x4 << core;
439 /* Something waking or other processor intends to wake us? */
440 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
442 sleep_core(core);
443 wake_core(core);
446 /* Signal wake - clear wake flag */
447 MBX_MSG_CLR = 0x14 << core;
449 /* Wait for other processor to finish wake procedure */
450 while (MBX_MSG_STAT & (0x1 << core));
451 #endif /* ASM/C selection */
452 enable_irq();
454 #endif /* NUM_CORES */
455 #elif CONFIG_CPU == PP5002
456 #if NUM_CORES == 1
457 static inline void core_sleep(void)
459 sleep_core(CURRENT_CORE);
460 enable_irq();
462 #else
463 /* PP5002 has no mailboxes - emulate using bytes */
464 static inline void core_sleep(unsigned int core)
466 #if 1
467 asm volatile (
468 "mov r0, #1 \n" /* Signal intent to sleep */
469 "strb r0, [%[sem], #2] \n"
470 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
471 "cmp r0, #0 \n"
472 "bne 2f \n"
473 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
474 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
475 * that the correct alternative is executed. Don't change the order
476 * of the next 4 instructions! */
477 "tst pc, #0x0c \n"
478 "mov r0, #0xca \n"
479 "strne r0, [%[ctl], %[c], lsl #2] \n"
480 "streq r0, [%[ctl], %[c], lsl #2] \n"
481 "nop \n" /* nop's needed because of pipeline */
482 "nop \n"
483 "nop \n"
484 "2: \n"
485 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
486 "strb r0, [%[sem], #1] \n"
487 "strb r0, [%[sem], #2] \n"
488 "1: \n" /* Wait for wake procedure to finish */
489 "ldrb r0, [%[sem], #0] \n"
490 "cmp r0, #0 \n"
491 "bne 1b \n"
493 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
494 [ctl]"r"(&CPU_CTL)
495 : "r0"
497 #else /* C version for reference */
498 /* Signal intent to sleep */
499 core_semaphores[core].intend_sleep = 1;
501 /* Something waking or other processor intends to wake us? */
502 if (core_semaphores[core].stay_awake == 0)
504 sleep_core(core);
507 /* Signal wake - clear wake flag */
508 core_semaphores[core].stay_awake = 0;
509 core_semaphores[core].intend_sleep = 0;
511 /* Wait for other processor to finish wake procedure */
512 while (core_semaphores[core].intend_wake != 0);
514 /* Enable IRQ */
515 #endif /* ASM/C selection */
516 enable_irq();
518 #endif /* NUM_CORES */
519 #endif /* PP CPU type */
521 /*---------------------------------------------------------------------------
522 * Wake another processor core that is sleeping or prevent it from doing so
523 * if it was already destined. FIQ, IRQ should be disabled before calling.
524 *---------------------------------------------------------------------------
526 #if NUM_CORES == 1
527 /* Shared single-core build debugging version */
528 void core_wake(void)
530 /* No wakey - core already wakey */
532 #elif defined (CPU_PP502x)
533 void core_wake(unsigned int othercore)
535 #if 1
536 /* avoid r0 since that contains othercore */
537 asm volatile (
538 "mrs r3, cpsr \n" /* Disable IRQ */
539 "orr r1, r3, #0x80 \n"
540 "msr cpsr_c, r1 \n"
541 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
542 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
543 "str r2, [%[mbx], #4] \n"
544 "1: \n" /* If it intends to sleep, let it first */
545 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
546 "eor r1, r1, #0xc \n"
547 "tst r1, r2, lsr #2 \n"
548 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
549 "tsteq r1, #0x80000000 \n"
550 "beq 1b \n" /* Wait for sleep or wake */
551 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
552 "movne r1, #0x0 \n"
553 "strne r1, [%[ctl], %[oc], lsl #2] \n"
554 "mov r1, r2, lsr #4 \n"
555 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
556 "msr cpsr_c, r3 \n" /* Restore IRQ */
558 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
559 [oc]"r"(othercore)
560 : "r1", "r2", "r3");
561 #else /* C version for reference */
562 /* Disable interrupts - avoid reentrancy from the tick */
563 int oldlevel = disable_irq_save();
565 /* Signal intent to wake other processor - set stay awake */
566 MBX_MSG_SET = 0x11 << othercore;
568 /* If it intends to sleep, wait until it does or aborts */
569 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
570 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
572 /* If sleeping, wake it up */
573 if (PROC_CTL(othercore) & PROC_SLEEP)
574 PROC_CTL(othercore) = 0;
576 /* Done with wake procedure */
577 MBX_MSG_CLR = 0x1 << othercore;
578 restore_irq(oldlevel);
579 #endif /* ASM/C selection */
581 #elif CONFIG_CPU == PP5002
582 /* PP5002 has no mailboxes - emulate using bytes */
583 void core_wake(unsigned int othercore)
585 #if 1
586 /* avoid r0 since that contains othercore */
587 asm volatile (
588 "mrs r3, cpsr \n" /* Disable IRQ */
589 "orr r1, r3, #0x80 \n"
590 "msr cpsr_c, r1 \n"
591 "mov r1, #1 \n" /* Signal intent to wake other core */
592 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
593 "strh r1, [%[sem], #0] \n"
594 "mov r2, #0x8000 \n"
595 "1: \n" /* If it intends to sleep, let it first */
596 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
597 "cmp r1, #1 \n"
598 "ldr r1, [%[st]] \n" /* && not sleeping ? */
599 "tsteq r1, r2, lsr %[oc] \n"
600 "beq 1b \n" /* Wait for sleep or wake */
601 "tst r1, r2, lsr %[oc] \n"
602 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
603 "movne r1, #0xce \n"
604 "strne r1, [r2, %[oc], lsl #2] \n"
605 "mov r1, #0 \n" /* Done with wake procedure */
606 "strb r1, [%[sem], #0] \n"
607 "msr cpsr_c, r3 \n" /* Restore IRQ */
609 : [sem]"r"(&core_semaphores[othercore]),
610 [st]"r"(&PROC_STAT),
611 [oc]"r"(othercore)
612 : "r1", "r2", "r3"
614 #else /* C version for reference */
615 /* Disable interrupts - avoid reentrancy from the tick */
616 int oldlevel = disable_irq_save();
618 /* Signal intent to wake other processor - set stay awake */
619 core_semaphores[othercore].intend_wake = 1;
620 core_semaphores[othercore].stay_awake = 1;
622 /* If it intends to sleep, wait until it does or aborts */
623 while (core_semaphores[othercore].intend_sleep != 0 &&
624 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
626 /* If sleeping, wake it up */
627 if (PROC_STAT & PROC_SLEEPING(othercore))
628 wake_core(othercore);
630 /* Done with wake procedure */
631 core_semaphores[othercore].intend_wake = 0;
632 restore_irq(oldlevel);
633 #endif /* ASM/C selection */
635 #endif /* CPU type */
637 #if NUM_CORES > 1
638 /*---------------------------------------------------------------------------
639 * Switches to a stack that always resides in the Rockbox core.
641 * Needed when a thread suicides on a core other than the main CPU since the
642 * stack used when idling is the stack of the last thread to run. This stack
643 * may not reside in the core firmware in which case the core will continue
644 * to use a stack from an unloaded module until another thread runs on it.
645 *---------------------------------------------------------------------------
647 static inline void switch_to_idle_stack(const unsigned int core)
649 asm volatile (
650 "str sp, [%0] \n" /* save original stack pointer on idle stack */
651 "mov sp, %0 \n" /* switch stacks */
652 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
653 (void)core;
656 /*---------------------------------------------------------------------------
657 * Perform core switch steps that need to take place inside switch_thread.
659 * These steps must take place while before changing the processor and after
660 * having entered switch_thread since switch_thread may not do a normal return
661 * because the stack being used for anything the compiler saved will not belong
662 * to the thread's destination core and it may have been recycled for other
663 * purposes by the time a normal context load has taken place. switch_thread
664 * will also clobber anything stashed in the thread's context or stored in the
665 * nonvolatile registers if it is saved there before the call since the
666 * compiler's order of operations cannot be known for certain.
668 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
670 /* Flush our data to ram */
671 cpucache_flush();
672 /* Stash thread in r4 slot */
673 thread->context.r[0] = (uint32_t)thread;
674 /* Stash restart address in r5 slot */
675 thread->context.r[1] = thread->context.start;
676 /* Save sp in context.sp while still running on old core */
677 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
680 /*---------------------------------------------------------------------------
681 * Machine-specific helper function for switching the processor a thread is
682 * running on. Basically, the thread suicides on the departing core and is
683 * reborn on the destination. Were it not for gcc's ill-behavior regarding
684 * naked functions written in C where it actually clobbers non-volatile
685 * registers before the intended prologue code, this would all be much
686 * simpler. Generic setup is done in switch_core itself.
689 /*---------------------------------------------------------------------------
690 * This actually performs the core switch.
692 static void __attribute__((naked))
693 switch_thread_core(unsigned int core, struct thread_entry *thread)
695 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
696 * Stack access also isn't permitted until restoring the original stack and
697 * context. */
698 asm volatile (
699 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
700 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
701 "ldr r2, [r2, r0, lsl #2] \n"
702 "add r2, r2, %0*4 \n"
703 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
704 "mov sp, r2 \n" /* switch stacks */
705 "adr r2, 1f \n" /* r2 = new core restart address */
706 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
707 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
708 "1: \n"
709 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
710 "mov r1, #0 \n" /* Clear start address */
711 "str r1, [r0, #40] \n"
712 "ldr r0, =cpucache_invalidate \n" /* Invalidate new core's cache */
713 "mov lr, pc \n"
714 "bx r0 \n"
715 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
716 ".ltorg \n" /* Dump constant pool */
717 : : "i"(IDLE_STACK_WORDS)
719 (void)core; (void)thread;
722 /*---------------------------------------------------------------------------
723 * Do any device-specific inits for the threads and synchronize the kernel
724 * initializations.
725 *---------------------------------------------------------------------------
727 static void core_thread_init(unsigned int core)
729 if (core == CPU)
731 /* Wake up coprocessor and let it initialize kernel and threads */
732 #ifdef CPU_PP502x
733 MBX_MSG_CLR = 0x3f;
734 #endif
735 wake_core(COP);
736 /* Sleep until COP has finished */
737 sleep_core(CPU);
739 else
741 /* Wake the CPU and return */
742 wake_core(CPU);
745 #endif /* NUM_CORES */
747 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X) /* Single core only for now */ \
748 || CONFIG_CPU == IMX31L || CONFIG_CPU == DM320 || CONFIG_CPU == AS3525 \
749 || CONFIG_CPU == S3C2440
750 /* Use the generic ARMv4/v5/v6 wait for IRQ */
751 static inline void core_sleep(void)
753 asm volatile (
754 "mcr p15, 0, %0, c7, c0, 4" /* Wait for interrupt */
755 : : "r"(0)
757 enable_irq();
759 #else
760 static inline void core_sleep(void)
762 #warning core_sleep not implemented, battery life will be decreased
763 enable_irq();
765 #endif /* CONFIG_CPU == */
767 #elif defined(CPU_COLDFIRE)
768 /*---------------------------------------------------------------------------
769 * Start the thread running and terminate it if it returns
770 *---------------------------------------------------------------------------
772 void start_thread(void); /* Provide C access to ASM label */
773 static void __attribute__((used)) __start_thread(void)
775 /* a0=macsr, a1=context */
776 asm volatile (
777 "start_thread: \n" /* Start here - no naked attribute */
778 "move.l %a0, %macsr \n" /* Set initial mac status reg */
779 "lea.l 48(%a1), %a1 \n"
780 "move.l (%a1)+, %sp \n" /* Set initial stack */
781 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
782 "clr.l (%a1) \n" /* Mark thread running */
783 "jsr (%a2) \n" /* Call thread function */
785 thread_exit();
788 /* Set EMAC unit to fractional mode with saturation for each new thread,
789 * since that's what'll be the most useful for most things which the dsp
790 * will do. Codecs should still initialize their preferred modes
791 * explicitly. Context pointer is placed in d2 slot and start_thread
792 * pointer in d3 slot. thread function pointer is placed in context.start.
793 * See load_context for what happens when thread is initially going to
794 * run.
796 #define THREAD_STARTUP_INIT(core, thread, function) \
797 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
798 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
799 (thread)->context.d[1] = (uint32_t)start_thread, \
800 (thread)->context.start = (uint32_t)(function); })
802 /*---------------------------------------------------------------------------
803 * Store non-volatile context.
804 *---------------------------------------------------------------------------
806 static inline void store_context(void* addr)
808 asm volatile (
809 "move.l %%macsr,%%d0 \n"
810 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
811 : : "a" (addr) : "d0" /* only! */
815 /*---------------------------------------------------------------------------
816 * Load non-volatile context.
817 *---------------------------------------------------------------------------
819 static inline void load_context(const void* addr)
821 asm volatile (
822 "move.l 52(%0), %%d0 \n" /* Get start address */
823 "beq.b 1f \n" /* NULL -> already running */
824 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
825 "jmp (%%a2) \n" /* Start the thread */
826 "1: \n"
827 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
828 "move.l %%d0, %%macsr \n"
829 : : "a" (addr) : "d0" /* only! */
833 /*---------------------------------------------------------------------------
834 * Put core in a power-saving state if waking list wasn't repopulated.
835 *---------------------------------------------------------------------------
837 static inline void core_sleep(void)
839 /* Supervisor mode, interrupts enabled upon wakeup */
840 asm volatile ("stop #0x2000");
843 #elif CONFIG_CPU == SH7034
844 /*---------------------------------------------------------------------------
845 * Start the thread running and terminate it if it returns
846 *---------------------------------------------------------------------------
848 void start_thread(void); /* Provide C access to ASM label */
849 static void __attribute__((used)) __start_thread(void)
851 /* r8 = context */
852 asm volatile (
853 "_start_thread: \n" /* Start here - no naked attribute */
854 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
855 "mov.l @(28, r8), r15 \n" /* Set initial sp */
856 "mov #0, r1 \n" /* Start the thread */
857 "jsr @r0 \n"
858 "mov.l r1, @(36, r8) \n" /* Clear start address */
860 thread_exit();
863 /* Place context pointer in r8 slot, function pointer in r9 slot, and
864 * start_thread pointer in context_start */
865 #define THREAD_STARTUP_INIT(core, thread, function) \
866 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
867 (thread)->context.r[1] = (uint32_t)(function), \
868 (thread)->context.start = (uint32_t)start_thread; })
870 /*---------------------------------------------------------------------------
871 * Store non-volatile context.
872 *---------------------------------------------------------------------------
874 static inline void store_context(void* addr)
876 asm volatile (
877 "add #36, %0 \n" /* Start at last reg. By the time routine */
878 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
879 "mov.l r15,@-%0 \n"
880 "mov.l r14,@-%0 \n"
881 "mov.l r13,@-%0 \n"
882 "mov.l r12,@-%0 \n"
883 "mov.l r11,@-%0 \n"
884 "mov.l r10,@-%0 \n"
885 "mov.l r9, @-%0 \n"
886 "mov.l r8, @-%0 \n"
887 : : "r" (addr)
891 /*---------------------------------------------------------------------------
892 * Load non-volatile context.
893 *---------------------------------------------------------------------------
895 static inline void load_context(const void* addr)
897 asm volatile (
898 "mov.l @(36, %0), r0 \n" /* Get start address */
899 "tst r0, r0 \n"
900 "bt .running \n" /* NULL -> already running */
901 "jmp @r0 \n" /* r8 = context */
902 ".running: \n"
903 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
904 "mov.l @%0+, r9 \n"
905 "mov.l @%0+, r10 \n"
906 "mov.l @%0+, r11 \n"
907 "mov.l @%0+, r12 \n"
908 "mov.l @%0+, r13 \n"
909 "mov.l @%0+, r14 \n"
910 "mov.l @%0+, r15 \n"
911 "lds.l @%0+, pr \n"
912 : : "r" (addr) : "r0" /* only! */
916 /*---------------------------------------------------------------------------
917 * Put core in a power-saving state.
918 *---------------------------------------------------------------------------
920 static inline void core_sleep(void)
922 asm volatile (
923 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
924 "mov #0, r1 \n" /* Enable interrupts */
925 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
926 "sleep \n" /* Execute standby */
927 : : "z"(&SBYCR-GBR) : "r1");
930 #elif CPU_MIPS == 32
932 /*---------------------------------------------------------------------------
933 * Start the thread running and terminate it if it returns
934 *---------------------------------------------------------------------------
937 void start_thread(void); /* Provide C access to ASM label */
938 static void __attribute__((used)) _start_thread(void)
940 /* $t1 = context */
941 asm volatile (
942 "start_thread: \n"
943 ".set noreorder \n"
944 ".set noat \n"
945 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = $t0, $9 = $t1) */
946 "lw $29, 40($9) \n" /* Set initial sp(=$29) */
947 "sw $0, 48($9) \n" /* Clear start address */
948 "jr $8 \n" /* Start the thread */
949 "nop \n"
950 ".set at \n"
951 ".set reorder \n"
953 thread_exit();
956 /* Place context pointer in $s0 slot, function pointer in $s1 slot, and
957 * start_thread pointer in context_start */
958 #define THREAD_STARTUP_INIT(core, thread, function) \
959 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
960 (thread)->context.r[1] = (uint32_t)(function), \
961 (thread)->context.start = (uint32_t)start_thread; })
963 /*---------------------------------------------------------------------------
964 * Store non-volatile context.
965 *---------------------------------------------------------------------------
967 static inline void store_context(void* addr)
969 asm volatile (
970 ".set noreorder \n"
971 ".set noat \n"
972 "move $8, %0 \n"
973 "sw $16, 0($8) \n" /* $s0 */
974 "sw $17, 4($8) \n" /* $s1 */
975 "sw $18, 8($8) \n" /* $s2 */
976 "sw $19, 12($8) \n" /* $s3 */
977 "sw $20, 16($8) \n" /* $s4 */
978 "sw $21, 20($8) \n" /* $s5 */
979 "sw $22, 24($8) \n" /* $s6 */
980 "sw $23, 28($8) \n" /* $s7 */
981 "sw $28, 32($8) \n" /* gp */
982 "sw $30, 36($8) \n" /* fp */
983 "sw $29, 40($8) \n" /* sp */
984 "sw $31, 44($8) \n" /* ra */
985 ".set at \n"
986 ".set reorder \n"
987 : : "r" (addr) : "t0"
991 /*---------------------------------------------------------------------------
992 * Load non-volatile context.
993 *---------------------------------------------------------------------------
995 static inline void load_context(const void* addr)
997 asm volatile (
998 ".set noat \n"
999 ".set noreorder \n"
1000 "lw $8, 48(%0) \n" /* Get start address ($8 = $t0) */
1001 "beqz $8, running \n" /* NULL -> already running */
1002 "nop \n"
1003 "move $9, %0 \n" /* $t1 = context */
1004 "jr $8 \n"
1005 "nop \n"
1006 "running: \n"
1007 "move $8, %0 \n"
1008 "lw $16, 0($8) \n" /* $s0 */
1009 "lw $17, 4($8) \n" /* $s1 */
1010 "lw $18, 8($8) \n" /* $s2 */
1011 "lw $19, 12($8) \n" /* $s3 */
1012 "lw $20, 16($8) \n" /* $s4 */
1013 "lw $21, 20($8) \n" /* $s5 */
1014 "lw $22, 24($8) \n" /* $s6 */
1015 "lw $23, 28($8) \n" /* $s7 */
1016 "lw $28, 32($8) \n" /* gp */
1017 "lw $30, 36($8) \n" /* fp */
1018 "lw $29, 40($8) \n" /* sp */
1019 "lw $31, 44($8) \n" /* ra */
1020 ".set at \n"
1021 ".set reorder \n"
1022 : : "r" (addr) : "t0" /* only! */
1026 /*---------------------------------------------------------------------------
1027 * Put core in a power-saving state.
1028 *---------------------------------------------------------------------------
1030 static inline void core_sleep(void)
1032 #if CONFIG_CPU == JZ4732
1033 __cpm_idle_mode();
1034 #endif
1035 asm volatile(".set mips32r2 \n"
1036 "mfc0 $8, $12 \n" /* mfc $t0, $12 */
1037 "move $9, $8 \n" /* move $t1, $t0 */
1038 "la $10, 0x8000000 \n" /* la $t2, 0x8000000 */
1039 "or $8, $8, $10 \n" /* Enable reduced power mode */
1040 "mtc0 $8, $12 \n"
1041 "wait \n"
1042 "mtc0 $9, $12 \n"
1043 ".set mips0 \n"
1044 ::: "t0", "t1", "t2"
1046 enable_irq();
1050 #endif /* CONFIG_CPU == */
1053 * End Processor-specific section
1054 ***************************************************************************/
1056 #if THREAD_EXTRA_CHECKS
1057 static void thread_panicf(const char *msg, struct thread_entry *thread)
1059 IF_COP( const unsigned int core = thread->core; )
1060 static char name[32];
1061 thread_get_name(name, 32, thread);
1062 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1064 static void thread_stkov(struct thread_entry *thread)
1066 thread_panicf("Stkov", thread);
1068 #define THREAD_PANICF(msg, thread) \
1069 thread_panicf(msg, thread)
1070 #define THREAD_ASSERT(exp, msg, thread) \
1071 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1072 #else
1073 static void thread_stkov(struct thread_entry *thread)
1075 IF_COP( const unsigned int core = thread->core; )
1076 static char name[32];
1077 thread_get_name(name, 32, thread);
1078 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1080 #define THREAD_PANICF(msg, thread)
1081 #define THREAD_ASSERT(exp, msg, thread)
1082 #endif /* THREAD_EXTRA_CHECKS */
1084 /* Thread locking */
1085 #if NUM_CORES > 1
1086 #define LOCK_THREAD(thread) \
1087 ({ corelock_lock(&(thread)->slot_cl); })
1088 #define TRY_LOCK_THREAD(thread) \
1089 ({ corelock_try_lock(&thread->slot_cl); })
1090 #define UNLOCK_THREAD(thread) \
1091 ({ corelock_unlock(&(thread)->slot_cl); })
1092 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1093 ({ unsigned int _core = (thread)->core; \
1094 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1095 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1096 #else
1097 #define LOCK_THREAD(thread) \
1098 ({ })
1099 #define TRY_LOCK_THREAD(thread) \
1100 ({ })
1101 #define UNLOCK_THREAD(thread) \
1102 ({ })
1103 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1104 ({ })
1105 #endif
1107 /* RTR list */
1108 #define RTR_LOCK(core) \
1109 ({ corelock_lock(&cores[core].rtr_cl); })
1110 #define RTR_UNLOCK(core) \
1111 ({ corelock_unlock(&cores[core].rtr_cl); })
1113 #ifdef HAVE_PRIORITY_SCHEDULING
1114 #define rtr_add_entry(core, priority) \
1115 prio_add_entry(&cores[core].rtr, (priority))
1117 #define rtr_subtract_entry(core, priority) \
1118 prio_subtract_entry(&cores[core].rtr, (priority))
1120 #define rtr_move_entry(core, from, to) \
1121 prio_move_entry(&cores[core].rtr, (from), (to))
1122 #else
1123 #define rtr_add_entry(core, priority)
1124 #define rtr_add_entry_inl(core, priority)
1125 #define rtr_subtract_entry(core, priority)
1126 #define rtr_subtract_entry_inl(core, priotity)
1127 #define rtr_move_entry(core, from, to)
1128 #define rtr_move_entry_inl(core, from, to)
1129 #endif
1131 /*---------------------------------------------------------------------------
1132 * Thread list structure - circular:
1133 * +------------------------------+
1134 * | |
1135 * +--+---+<-+---+<-+---+<-+---+<-+
1136 * Head->| T | | T | | T | | T |
1137 * +->+---+->+---+->+---+->+---+--+
1138 * | |
1139 * +------------------------------+
1140 *---------------------------------------------------------------------------
1143 /*---------------------------------------------------------------------------
1144 * Adds a thread to a list of threads using "insert last". Uses the "l"
1145 * links.
1146 *---------------------------------------------------------------------------
1148 static void add_to_list_l(struct thread_entry **list,
1149 struct thread_entry *thread)
1151 struct thread_entry *l = *list;
1153 if (l == NULL)
1155 /* Insert into unoccupied list */
1156 thread->l.prev = thread;
1157 thread->l.next = thread;
1158 *list = thread;
1159 return;
1162 /* Insert last */
1163 thread->l.prev = l->l.prev;
1164 thread->l.next = l;
1165 l->l.prev->l.next = thread;
1166 l->l.prev = thread;
1169 /*---------------------------------------------------------------------------
1170 * Removes a thread from a list of threads. Uses the "l" links.
1171 *---------------------------------------------------------------------------
1173 static void remove_from_list_l(struct thread_entry **list,
1174 struct thread_entry *thread)
1176 struct thread_entry *prev, *next;
1178 next = thread->l.next;
1180 if (thread == next)
1182 /* The only item */
1183 *list = NULL;
1184 return;
1187 if (thread == *list)
1189 /* List becomes next item */
1190 *list = next;
1193 prev = thread->l.prev;
1195 /* Fix links to jump over the removed entry. */
1196 next->l.prev = prev;
1197 prev->l.next = next;
1200 /*---------------------------------------------------------------------------
1201 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1202 * NULL-terminated forward (to ease the far more common forward traversal):
1203 * +------------------------------+
1204 * | |
1205 * +--+---+<-+---+<-+---+<-+---+<-+
1206 * Head->| T | | T | | T | | T |
1207 * +---+->+---+->+---+->+---+-X
1208 *---------------------------------------------------------------------------
1211 /*---------------------------------------------------------------------------
1212 * Add a thread from the core's timout list by linking the pointers in its
1213 * tmo structure.
1214 *---------------------------------------------------------------------------
1216 static void add_to_list_tmo(struct thread_entry *thread)
1218 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1219 THREAD_ASSERT(thread->tmo.prev == NULL,
1220 "add_to_list_tmo->already listed", thread);
1222 thread->tmo.next = NULL;
1224 if (tmo == NULL)
1226 /* Insert into unoccupied list */
1227 thread->tmo.prev = thread;
1228 cores[IF_COP_CORE(thread->core)].timeout = thread;
1229 return;
1232 /* Insert Last */
1233 thread->tmo.prev = tmo->tmo.prev;
1234 tmo->tmo.prev->tmo.next = thread;
1235 tmo->tmo.prev = thread;
1238 /*---------------------------------------------------------------------------
1239 * Remove a thread from the core's timout list by unlinking the pointers in
1240 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1241 * is cancelled.
1242 *---------------------------------------------------------------------------
1244 static void remove_from_list_tmo(struct thread_entry *thread)
1246 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1247 struct thread_entry *prev = thread->tmo.prev;
1248 struct thread_entry *next = thread->tmo.next;
1250 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1252 if (next != NULL)
1253 next->tmo.prev = prev;
1255 if (thread == *list)
1257 /* List becomes next item and empty if next == NULL */
1258 *list = next;
1259 /* Mark as unlisted */
1260 thread->tmo.prev = NULL;
1262 else
1264 if (next == NULL)
1265 (*list)->tmo.prev = prev;
1266 prev->tmo.next = next;
1267 /* Mark as unlisted */
1268 thread->tmo.prev = NULL;
1273 #ifdef HAVE_PRIORITY_SCHEDULING
1274 /*---------------------------------------------------------------------------
1275 * Priority distribution structure (one category for each possible priority):
1277 * +----+----+----+ ... +-----+
1278 * hist: | F0 | F1 | F2 | | F31 |
1279 * +----+----+----+ ... +-----+
1280 * mask: | b0 | b1 | b2 | | b31 |
1281 * +----+----+----+ ... +-----+
1283 * F = count of threads at priority category n (frequency)
1284 * b = bitmask of non-zero priority categories (occupancy)
1286 * / if H[n] != 0 : 1
1287 * b[n] = |
1288 * \ else : 0
1290 *---------------------------------------------------------------------------
1291 * Basic priority inheritance priotocol (PIP):
1293 * Mn = mutex n, Tn = thread n
1295 * A lower priority thread inherits the priority of the highest priority
1296 * thread blocked waiting for it to complete an action (such as release a
1297 * mutex or respond to a message via queue_send):
1299 * 1) T2->M1->T1
1301 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1302 * priority than T1 then T1 inherits the priority of T2.
1304 * 2) T3
1305 * \/
1306 * T2->M1->T1
1308 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1309 * T1 inherits the higher of T2 and T3.
1311 * 3) T3->M2->T2->M1->T1
1313 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1314 * then T1 inherits the priority of T3 through T2.
1316 * Blocking chains can grow arbitrarily complex (though it's best that they
1317 * not form at all very often :) and build-up from these units.
1318 *---------------------------------------------------------------------------
1321 /*---------------------------------------------------------------------------
1322 * Increment frequency at category "priority"
1323 *---------------------------------------------------------------------------
1325 static inline unsigned int prio_add_entry(
1326 struct priority_distribution *pd, int priority)
1328 unsigned int count;
1329 /* Enough size/instruction count difference for ARM makes it worth it to
1330 * use different code (192 bytes for ARM). Only thing better is ASM. */
1331 #ifdef CPU_ARM
1332 count = pd->hist[priority];
1333 if (++count == 1)
1334 pd->mask |= 1 << priority;
1335 pd->hist[priority] = count;
1336 #else /* This one's better for Coldfire */
1337 if ((count = ++pd->hist[priority]) == 1)
1338 pd->mask |= 1 << priority;
1339 #endif
1341 return count;
1344 /*---------------------------------------------------------------------------
1345 * Decrement frequency at category "priority"
1346 *---------------------------------------------------------------------------
1348 static inline unsigned int prio_subtract_entry(
1349 struct priority_distribution *pd, int priority)
1351 unsigned int count;
1353 #ifdef CPU_ARM
1354 count = pd->hist[priority];
1355 if (--count == 0)
1356 pd->mask &= ~(1 << priority);
1357 pd->hist[priority] = count;
1358 #else
1359 if ((count = --pd->hist[priority]) == 0)
1360 pd->mask &= ~(1 << priority);
1361 #endif
1363 return count;
1366 /*---------------------------------------------------------------------------
1367 * Remove from one category and add to another
1368 *---------------------------------------------------------------------------
1370 static inline void prio_move_entry(
1371 struct priority_distribution *pd, int from, int to)
1373 uint32_t mask = pd->mask;
1375 #ifdef CPU_ARM
1376 unsigned int count;
1378 count = pd->hist[from];
1379 if (--count == 0)
1380 mask &= ~(1 << from);
1381 pd->hist[from] = count;
1383 count = pd->hist[to];
1384 if (++count == 1)
1385 mask |= 1 << to;
1386 pd->hist[to] = count;
1387 #else
1388 if (--pd->hist[from] == 0)
1389 mask &= ~(1 << from);
1391 if (++pd->hist[to] == 1)
1392 mask |= 1 << to;
1393 #endif
1395 pd->mask = mask;
1398 /*---------------------------------------------------------------------------
1399 * Change the priority and rtr entry for a running thread
1400 *---------------------------------------------------------------------------
1402 static inline void set_running_thread_priority(
1403 struct thread_entry *thread, int priority)
1405 const unsigned int core = IF_COP_CORE(thread->core);
1406 RTR_LOCK(core);
1407 rtr_move_entry(core, thread->priority, priority);
1408 thread->priority = priority;
1409 RTR_UNLOCK(core);
1412 /*---------------------------------------------------------------------------
1413 * Finds the highest priority thread in a list of threads. If the list is
1414 * empty, the PRIORITY_IDLE is returned.
1416 * It is possible to use the struct priority_distribution within an object
1417 * instead of scanning the remaining threads in the list but as a compromise,
1418 * the resulting per-object memory overhead is saved at a slight speed
1419 * penalty under high contention.
1420 *---------------------------------------------------------------------------
1422 static int find_highest_priority_in_list_l(
1423 struct thread_entry * const thread)
1425 if (LIKELY(thread != NULL))
1427 /* Go though list until the ending up at the initial thread */
1428 int highest_priority = thread->priority;
1429 struct thread_entry *curr = thread;
1433 int priority = curr->priority;
1435 if (priority < highest_priority)
1436 highest_priority = priority;
1438 curr = curr->l.next;
1440 while (curr != thread);
1442 return highest_priority;
1445 return PRIORITY_IDLE;
1448 /*---------------------------------------------------------------------------
1449 * Register priority with blocking system and bubble it down the chain if
1450 * any until we reach the end or something is already equal or higher.
1452 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1453 * targets but that same action also guarantees a circular block anyway and
1454 * those are prevented, right? :-)
1455 *---------------------------------------------------------------------------
1457 static struct thread_entry *
1458 blocker_inherit_priority(struct thread_entry *current)
1460 const int priority = current->priority;
1461 struct blocker *bl = current->blocker;
1462 struct thread_entry * const tstart = current;
1463 struct thread_entry *bl_t = bl->thread;
1465 /* Blocker cannot change since the object protection is held */
1466 LOCK_THREAD(bl_t);
1468 for (;;)
1470 struct thread_entry *next;
1471 int bl_pr = bl->priority;
1473 if (priority >= bl_pr)
1474 break; /* Object priority already high enough */
1476 bl->priority = priority;
1478 /* Add this one */
1479 prio_add_entry(&bl_t->pdist, priority);
1481 if (bl_pr < PRIORITY_IDLE)
1483 /* Not first waiter - subtract old one */
1484 prio_subtract_entry(&bl_t->pdist, bl_pr);
1487 if (priority >= bl_t->priority)
1488 break; /* Thread priority high enough */
1490 if (bl_t->state == STATE_RUNNING)
1492 /* Blocking thread is a running thread therefore there are no
1493 * further blockers. Change the "run queue" on which it
1494 * resides. */
1495 set_running_thread_priority(bl_t, priority);
1496 break;
1499 bl_t->priority = priority;
1501 /* If blocking thread has a blocker, apply transitive inheritance */
1502 bl = bl_t->blocker;
1504 if (bl == NULL)
1505 break; /* End of chain or object doesn't support inheritance */
1507 next = bl->thread;
1509 if (UNLIKELY(next == tstart))
1510 break; /* Full-circle - deadlock! */
1512 UNLOCK_THREAD(current);
1514 #if NUM_CORES > 1
1515 for (;;)
1517 LOCK_THREAD(next);
1519 /* Blocker could change - retest condition */
1520 if (LIKELY(bl->thread == next))
1521 break;
1523 UNLOCK_THREAD(next);
1524 next = bl->thread;
1526 #endif
1527 current = bl_t;
1528 bl_t = next;
1531 UNLOCK_THREAD(bl_t);
1533 return current;
1536 /*---------------------------------------------------------------------------
1537 * Readjust priorities when waking a thread blocked waiting for another
1538 * in essence "releasing" the thread's effect on the object owner. Can be
1539 * performed from any context.
1540 *---------------------------------------------------------------------------
1542 struct thread_entry *
1543 wakeup_priority_protocol_release(struct thread_entry *thread)
1545 const int priority = thread->priority;
1546 struct blocker *bl = thread->blocker;
1547 struct thread_entry * const tstart = thread;
1548 struct thread_entry *bl_t = bl->thread;
1550 /* Blocker cannot change since object will be locked */
1551 LOCK_THREAD(bl_t);
1553 thread->blocker = NULL; /* Thread not blocked */
1555 for (;;)
1557 struct thread_entry *next;
1558 int bl_pr = bl->priority;
1560 if (priority > bl_pr)
1561 break; /* Object priority higher */
1563 next = *thread->bqp;
1565 if (next == NULL)
1567 /* No more threads in queue */
1568 prio_subtract_entry(&bl_t->pdist, bl_pr);
1569 bl->priority = PRIORITY_IDLE;
1571 else
1573 /* Check list for highest remaining priority */
1574 int queue_pr = find_highest_priority_in_list_l(next);
1576 if (queue_pr == bl_pr)
1577 break; /* Object priority not changing */
1579 /* Change queue priority */
1580 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1581 bl->priority = queue_pr;
1584 if (bl_pr > bl_t->priority)
1585 break; /* thread priority is higher */
1587 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1589 if (bl_pr == bl_t->priority)
1590 break; /* Thread priority not changing */
1592 if (bl_t->state == STATE_RUNNING)
1594 /* No further blockers */
1595 set_running_thread_priority(bl_t, bl_pr);
1596 break;
1599 bl_t->priority = bl_pr;
1601 /* If blocking thread has a blocker, apply transitive inheritance */
1602 bl = bl_t->blocker;
1604 if (bl == NULL)
1605 break; /* End of chain or object doesn't support inheritance */
1607 next = bl->thread;
1609 if (UNLIKELY(next == tstart))
1610 break; /* Full-circle - deadlock! */
1612 UNLOCK_THREAD(thread);
1614 #if NUM_CORES > 1
1615 for (;;)
1617 LOCK_THREAD(next);
1619 /* Blocker could change - retest condition */
1620 if (LIKELY(bl->thread == next))
1621 break;
1623 UNLOCK_THREAD(next);
1624 next = bl->thread;
1626 #endif
1627 thread = bl_t;
1628 bl_t = next;
1631 UNLOCK_THREAD(bl_t);
1633 #if NUM_CORES > 1
1634 if (UNLIKELY(thread != tstart))
1636 /* Relock original if it changed */
1637 LOCK_THREAD(tstart);
1639 #endif
1641 return cores[CURRENT_CORE].running;
1644 /*---------------------------------------------------------------------------
1645 * Transfer ownership to a thread waiting for an objects and transfer
1646 * inherited priority boost from other waiters. This algorithm knows that
1647 * blocking chains may only unblock from the very end.
1649 * Only the owning thread itself may call this and so the assumption that
1650 * it is the running thread is made.
1651 *---------------------------------------------------------------------------
1653 struct thread_entry *
1654 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1656 /* Waking thread inherits priority boost from object owner */
1657 struct blocker *bl = thread->blocker;
1658 struct thread_entry *bl_t = bl->thread;
1659 struct thread_entry *next;
1660 int bl_pr;
1662 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
1663 "UPPT->wrong thread", cores[CURRENT_CORE].running);
1665 LOCK_THREAD(bl_t);
1667 bl_pr = bl->priority;
1669 /* Remove the object's boost from the owning thread */
1670 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1671 bl_pr <= bl_t->priority)
1673 /* No more threads at this priority are waiting and the old level is
1674 * at least the thread level */
1675 int priority = find_first_set_bit(bl_t->pdist.mask);
1677 if (priority != bl_t->priority)
1679 /* Adjust this thread's priority */
1680 set_running_thread_priority(bl_t, priority);
1684 next = *thread->bqp;
1686 if (LIKELY(next == NULL))
1688 /* Expected shortcut - no more waiters */
1689 bl_pr = PRIORITY_IDLE;
1691 else
1693 if (thread->priority <= bl_pr)
1695 /* Need to scan threads remaining in queue */
1696 bl_pr = find_highest_priority_in_list_l(next);
1699 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1700 bl_pr < thread->priority)
1702 /* Thread priority must be raised */
1703 thread->priority = bl_pr;
1707 bl->thread = thread; /* This thread pwns */
1708 bl->priority = bl_pr; /* Save highest blocked priority */
1709 thread->blocker = NULL; /* Thread not blocked */
1711 UNLOCK_THREAD(bl_t);
1713 return bl_t;
1716 /*---------------------------------------------------------------------------
1717 * No threads must be blocked waiting for this thread except for it to exit.
1718 * The alternative is more elaborate cleanup and object registration code.
1719 * Check this for risk of silent data corruption when objects with
1720 * inheritable blocking are abandoned by the owner - not precise but may
1721 * catch something.
1722 *---------------------------------------------------------------------------
1724 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1726 /* Only one bit in the mask should be set with a frequency on 1 which
1727 * represents the thread's own base priority */
1728 uint32_t mask = thread->pdist.mask;
1729 if ((mask & (mask - 1)) != 0 ||
1730 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1732 unsigned char name[32];
1733 thread_get_name(name, 32, thread);
1734 panicf("%s->%s with obj. waiters", function, name);
1737 #endif /* HAVE_PRIORITY_SCHEDULING */
1739 /*---------------------------------------------------------------------------
1740 * Move a thread back to a running state on its core.
1741 *---------------------------------------------------------------------------
1743 static void core_schedule_wakeup(struct thread_entry *thread)
1745 const unsigned int core = IF_COP_CORE(thread->core);
1747 RTR_LOCK(core);
1749 thread->state = STATE_RUNNING;
1751 add_to_list_l(&cores[core].running, thread);
1752 rtr_add_entry(core, thread->priority);
1754 RTR_UNLOCK(core);
1756 #if NUM_CORES > 1
1757 if (core != CURRENT_CORE)
1758 core_wake(core);
1759 #endif
1762 /*---------------------------------------------------------------------------
1763 * Check the core's timeout list when at least one thread is due to wake.
1764 * Filtering for the condition is done before making the call. Resets the
1765 * tick when the next check will occur.
1766 *---------------------------------------------------------------------------
1768 void check_tmo_threads(void)
1770 const unsigned int core = CURRENT_CORE;
1771 const long tick = current_tick; /* snapshot the current tick */
1772 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1773 struct thread_entry *next = cores[core].timeout;
1775 /* If there are no processes waiting for a timeout, just keep the check
1776 tick from falling into the past. */
1778 /* Break the loop once we have walked through the list of all
1779 * sleeping processes or have removed them all. */
1780 while (next != NULL)
1782 /* Check sleeping threads. Allow interrupts between checks. */
1783 enable_irq();
1785 struct thread_entry *curr = next;
1787 next = curr->tmo.next;
1789 /* Lock thread slot against explicit wakeup */
1790 disable_irq();
1791 LOCK_THREAD(curr);
1793 unsigned state = curr->state;
1795 if (state < TIMEOUT_STATE_FIRST)
1797 /* Cleanup threads no longer on a timeout but still on the
1798 * list. */
1799 remove_from_list_tmo(curr);
1801 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
1803 /* Timeout still pending - this will be the usual case */
1804 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1806 /* Earliest timeout found so far - move the next check up
1807 to its time */
1808 next_tmo_check = curr->tmo_tick;
1811 else
1813 /* Sleep timeout has been reached so bring the thread back to
1814 * life again. */
1815 if (state == STATE_BLOCKED_W_TMO)
1817 #if NUM_CORES > 1
1818 /* Lock the waiting thread's kernel object */
1819 struct corelock *ocl = curr->obj_cl;
1821 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1823 /* Need to retry in the correct order though the need is
1824 * unlikely */
1825 UNLOCK_THREAD(curr);
1826 corelock_lock(ocl);
1827 LOCK_THREAD(curr);
1829 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
1831 /* Thread was woken or removed explicitely while slot
1832 * was unlocked */
1833 corelock_unlock(ocl);
1834 remove_from_list_tmo(curr);
1835 UNLOCK_THREAD(curr);
1836 continue;
1839 #endif /* NUM_CORES */
1841 remove_from_list_l(curr->bqp, curr);
1843 #ifdef HAVE_WAKEUP_EXT_CB
1844 if (curr->wakeup_ext_cb != NULL)
1845 curr->wakeup_ext_cb(curr);
1846 #endif
1848 #ifdef HAVE_PRIORITY_SCHEDULING
1849 if (curr->blocker != NULL)
1850 wakeup_priority_protocol_release(curr);
1851 #endif
1852 corelock_unlock(ocl);
1854 /* else state == STATE_SLEEPING */
1856 remove_from_list_tmo(curr);
1858 RTR_LOCK(core);
1860 curr->state = STATE_RUNNING;
1862 add_to_list_l(&cores[core].running, curr);
1863 rtr_add_entry(core, curr->priority);
1865 RTR_UNLOCK(core);
1868 UNLOCK_THREAD(curr);
1871 cores[core].next_tmo_check = next_tmo_check;
1874 /*---------------------------------------------------------------------------
1875 * Performs operations that must be done before blocking a thread but after
1876 * the state is saved.
1877 *---------------------------------------------------------------------------
1879 #if NUM_CORES > 1
1880 static inline void run_blocking_ops(
1881 unsigned int core, struct thread_entry *thread)
1883 struct thread_blk_ops *ops = &cores[core].blk_ops;
1884 const unsigned flags = ops->flags;
1886 if (LIKELY(flags == TBOP_CLEAR))
1887 return;
1889 switch (flags)
1891 case TBOP_SWITCH_CORE:
1892 core_switch_blk_op(core, thread);
1893 /* Fall-through */
1894 case TBOP_UNLOCK_CORELOCK:
1895 corelock_unlock(ops->cl_p);
1896 break;
1899 ops->flags = TBOP_CLEAR;
1901 #endif /* NUM_CORES > 1 */
1903 #ifdef RB_PROFILE
1904 void profile_thread(void)
1906 profstart(cores[CURRENT_CORE].running - threads);
1908 #endif
1910 /*---------------------------------------------------------------------------
1911 * Prepares a thread to block on an object's list and/or for a specified
1912 * duration - expects object and slot to be appropriately locked if needed
1913 * and interrupts to be masked.
1914 *---------------------------------------------------------------------------
1916 static inline void block_thread_on_l(struct thread_entry *thread,
1917 unsigned state)
1919 /* If inlined, unreachable branches will be pruned with no size penalty
1920 because state is passed as a constant parameter. */
1921 const unsigned int core = IF_COP_CORE(thread->core);
1923 /* Remove the thread from the list of running threads. */
1924 RTR_LOCK(core);
1925 remove_from_list_l(&cores[core].running, thread);
1926 rtr_subtract_entry(core, thread->priority);
1927 RTR_UNLOCK(core);
1929 /* Add a timeout to the block if not infinite */
1930 switch (state)
1932 case STATE_BLOCKED:
1933 case STATE_BLOCKED_W_TMO:
1934 /* Put the thread into a new list of inactive threads. */
1935 add_to_list_l(thread->bqp, thread);
1937 if (state == STATE_BLOCKED)
1938 break;
1940 /* Fall-through */
1941 case STATE_SLEEPING:
1942 /* If this thread times out sooner than any other thread, update
1943 next_tmo_check to its timeout */
1944 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1946 cores[core].next_tmo_check = thread->tmo_tick;
1949 if (thread->tmo.prev == NULL)
1951 add_to_list_tmo(thread);
1953 /* else thread was never removed from list - just keep it there */
1954 break;
1957 /* Remember the the next thread about to block. */
1958 cores[core].block_task = thread;
1960 /* Report new state. */
1961 thread->state = state;
1964 /*---------------------------------------------------------------------------
1965 * Switch thread in round robin fashion for any given priority. Any thread
1966 * that removed itself from the running list first must specify itself in
1967 * the paramter.
1969 * INTERNAL: Intended for use by kernel and not for programs.
1970 *---------------------------------------------------------------------------
1972 void switch_thread(void)
1975 const unsigned int core = CURRENT_CORE;
1976 struct thread_entry *block = cores[core].block_task;
1977 struct thread_entry *thread = cores[core].running;
1979 /* Get context to save - next thread to run is unknown until all wakeups
1980 * are evaluated */
1981 if (block != NULL)
1983 cores[core].block_task = NULL;
1985 #if NUM_CORES > 1
1986 if (UNLIKELY(thread == block))
1988 /* This was the last thread running and another core woke us before
1989 * reaching here. Force next thread selection to give tmo threads or
1990 * other threads woken before this block a first chance. */
1991 block = NULL;
1993 else
1994 #endif
1996 /* Blocking task is the old one */
1997 thread = block;
2001 #ifdef RB_PROFILE
2002 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
2003 #endif
2005 /* Begin task switching by saving our current context so that we can
2006 * restore the state of the current thread later to the point prior
2007 * to this call. */
2008 store_context(&thread->context);
2010 /* Check if the current thread stack is overflown */
2011 if (UNLIKELY(thread->stack[0] != DEADBEEF))
2012 thread_stkov(thread);
2014 #if NUM_CORES > 1
2015 /* Run any blocking operations requested before switching/sleeping */
2016 run_blocking_ops(core, thread);
2017 #endif
2019 #ifdef HAVE_PRIORITY_SCHEDULING
2020 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2021 /* Reset the value of thread's skip count */
2022 thread->skip_count = 0;
2023 #endif
2025 for (;;)
2027 /* If there are threads on a timeout and the earliest wakeup is due,
2028 * check the list and wake any threads that need to start running
2029 * again. */
2030 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2032 check_tmo_threads();
2035 disable_irq();
2036 RTR_LOCK(core);
2038 thread = cores[core].running;
2040 if (UNLIKELY(thread == NULL))
2042 /* Enter sleep mode to reduce power usage - woken up on interrupt
2043 * or wakeup request from another core - expected to enable
2044 * interrupts. */
2045 RTR_UNLOCK(core);
2046 core_sleep(IF_COP(core));
2048 else
2050 #ifdef HAVE_PRIORITY_SCHEDULING
2051 /* Select the new task based on priorities and the last time a
2052 * process got CPU time relative to the highest priority runnable
2053 * task. */
2054 struct priority_distribution *pd = &cores[core].rtr;
2055 int max = find_first_set_bit(pd->mask);
2057 if (block == NULL)
2059 /* Not switching on a block, tentatively select next thread */
2060 thread = thread->l.next;
2063 for (;;)
2065 int priority = thread->priority;
2066 int diff;
2068 /* This ridiculously simple method of aging seems to work
2069 * suspiciously well. It does tend to reward CPU hogs (under
2070 * yielding) but that's generally not desirable at all. On the
2071 * plus side, it, relatively to other threads, penalizes excess
2072 * yielding which is good if some high priority thread is
2073 * performing no useful work such as polling for a device to be
2074 * ready. Of course, aging is only employed when higher and lower
2075 * priority threads are runnable. The highest priority runnable
2076 * thread(s) are never skipped. */
2077 if (LIKELY(priority <= max) ||
2078 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2079 (diff = priority - max, ++thread->skip_count > diff*diff))
2081 cores[core].running = thread;
2082 break;
2085 thread = thread->l.next;
2087 #else
2088 /* Without priority use a simple FCFS algorithm */
2089 if (block == NULL)
2091 /* Not switching on a block, select next thread */
2092 thread = thread->l.next;
2093 cores[core].running = thread;
2095 #endif /* HAVE_PRIORITY_SCHEDULING */
2097 RTR_UNLOCK(core);
2098 enable_irq();
2099 break;
2103 /* And finally give control to the next thread. */
2104 load_context(&thread->context);
2106 #ifdef RB_PROFILE
2107 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
2108 #endif
2112 /*---------------------------------------------------------------------------
2113 * Sleeps a thread for at least a specified number of ticks with zero being
2114 * a wait until the next tick.
2116 * INTERNAL: Intended for use by kernel and not for programs.
2117 *---------------------------------------------------------------------------
2119 void sleep_thread(int ticks)
2121 struct thread_entry *current = cores[CURRENT_CORE].running;
2123 LOCK_THREAD(current);
2125 /* Set our timeout, remove from run list and join timeout list. */
2126 current->tmo_tick = current_tick + ticks + 1;
2127 block_thread_on_l(current, STATE_SLEEPING);
2129 UNLOCK_THREAD(current);
2132 /*---------------------------------------------------------------------------
2133 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2135 * INTERNAL: Intended for use by kernel objects and not for programs.
2136 *---------------------------------------------------------------------------
2138 void block_thread(struct thread_entry *current)
2140 /* Set the state to blocked and take us off of the run queue until we
2141 * are explicitly woken */
2142 LOCK_THREAD(current);
2144 /* Set the list for explicit wakeup */
2145 block_thread_on_l(current, STATE_BLOCKED);
2147 #ifdef HAVE_PRIORITY_SCHEDULING
2148 if (current->blocker != NULL)
2150 /* Object supports PIP */
2151 current = blocker_inherit_priority(current);
2153 #endif
2155 UNLOCK_THREAD(current);
2158 /*---------------------------------------------------------------------------
2159 * Block a thread on a blocking queue for a specified time interval or until
2160 * explicitly woken - whichever happens first.
2162 * INTERNAL: Intended for use by kernel objects and not for programs.
2163 *---------------------------------------------------------------------------
2165 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2167 /* Get the entry for the current running thread. */
2168 LOCK_THREAD(current);
2170 /* Set the state to blocked with the specified timeout */
2171 current->tmo_tick = current_tick + timeout;
2173 /* Set the list for explicit wakeup */
2174 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2176 #ifdef HAVE_PRIORITY_SCHEDULING
2177 if (current->blocker != NULL)
2179 /* Object supports PIP */
2180 current = blocker_inherit_priority(current);
2182 #endif
2184 UNLOCK_THREAD(current);
2187 /*---------------------------------------------------------------------------
2188 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2189 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2191 * This code should be considered a critical section by the caller meaning
2192 * that the object's corelock should be held.
2194 * INTERNAL: Intended for use by kernel objects and not for programs.
2195 *---------------------------------------------------------------------------
2197 unsigned int wakeup_thread(struct thread_entry **list)
2199 struct thread_entry *thread = *list;
2200 unsigned int result = THREAD_NONE;
2202 /* Check if there is a blocked thread at all. */
2203 if (thread == NULL)
2204 return result;
2206 LOCK_THREAD(thread);
2208 /* Determine thread's current state. */
2209 switch (thread->state)
2211 case STATE_BLOCKED:
2212 case STATE_BLOCKED_W_TMO:
2213 remove_from_list_l(list, thread);
2215 result = THREAD_OK;
2217 #ifdef HAVE_PRIORITY_SCHEDULING
2218 struct thread_entry *current;
2219 struct blocker *bl = thread->blocker;
2221 if (bl == NULL)
2223 /* No inheritance - just boost the thread by aging */
2224 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2225 thread->skip_count = thread->priority;
2226 current = cores[CURRENT_CORE].running;
2228 else
2230 /* Call the specified unblocking PIP */
2231 current = bl->wakeup_protocol(thread);
2234 if (current != NULL && thread->priority < current->priority
2235 IF_COP( && thread->core == current->core ))
2237 /* Woken thread is higher priority and exists on the same CPU core;
2238 * recommend a task switch. Knowing if this is an interrupt call
2239 * would be helpful here. */
2240 result |= THREAD_SWITCH;
2242 #endif /* HAVE_PRIORITY_SCHEDULING */
2244 core_schedule_wakeup(thread);
2245 break;
2247 /* Nothing to do. State is not blocked. */
2248 #if THREAD_EXTRA_CHECKS
2249 default:
2250 THREAD_PANICF("wakeup_thread->block invalid", thread);
2251 case STATE_RUNNING:
2252 case STATE_KILLED:
2253 break;
2254 #endif
2257 UNLOCK_THREAD(thread);
2258 return result;
2261 /*---------------------------------------------------------------------------
2262 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2263 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2264 * the queue must be locked first.
2266 * INTERNAL: Intended for use by kernel objects and not for programs.
2267 *---------------------------------------------------------------------------
2269 unsigned int thread_queue_wake(struct thread_entry **list)
2271 unsigned result = THREAD_NONE;
2273 for (;;)
2275 unsigned int rc = wakeup_thread(list);
2277 if (rc == THREAD_NONE)
2278 break; /* No more threads */
2280 result |= rc;
2283 return result;
2286 /*---------------------------------------------------------------------------
2287 * Assign the thread slot a new ID. Version is 1-255.
2288 *---------------------------------------------------------------------------
2290 static void new_thread_id(unsigned int slot_num,
2291 struct thread_entry *thread)
2293 unsigned int version =
2294 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
2295 & THREAD_ID_VERSION_MASK;
2297 /* If wrapped to 0, make it 1 */
2298 if (version == 0)
2299 version = 1u << THREAD_ID_VERSION_SHIFT;
2301 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
2304 /*---------------------------------------------------------------------------
2305 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2306 * will be locked on multicore.
2307 *---------------------------------------------------------------------------
2309 static struct thread_entry * find_empty_thread_slot(void)
2311 /* Any slot could be on an interrupt-accessible list */
2312 IF_COP( int oldlevel = disable_irq_save(); )
2313 struct thread_entry *thread = NULL;
2314 int n;
2316 for (n = 0; n < MAXTHREADS; n++)
2318 /* Obtain current slot state - lock it on multicore */
2319 struct thread_entry *t = &threads[n];
2320 LOCK_THREAD(t);
2322 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2324 /* Slot is empty - leave it locked and caller will unlock */
2325 thread = t;
2326 break;
2329 /* Finished examining slot - no longer busy - unlock on multicore */
2330 UNLOCK_THREAD(t);
2333 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2334 not accesible to them yet */
2335 return thread;
2338 /*---------------------------------------------------------------------------
2339 * Return the thread_entry pointer for a thread_id. Return the current
2340 * thread if the ID is 0 (alias for current).
2341 *---------------------------------------------------------------------------
2343 struct thread_entry * thread_id_entry(unsigned int thread_id)
2345 return (thread_id == THREAD_ID_CURRENT) ?
2346 cores[CURRENT_CORE].running :
2347 &threads[thread_id & THREAD_ID_SLOT_MASK];
2350 /*---------------------------------------------------------------------------
2351 * Place the current core in idle mode - woken up on interrupt or wake
2352 * request from another core.
2353 *---------------------------------------------------------------------------
2355 void core_idle(void)
2357 IF_COP( const unsigned int core = CURRENT_CORE; )
2358 disable_irq();
2359 core_sleep(IF_COP(core));
2362 /*---------------------------------------------------------------------------
2363 * Create a thread. If using a dual core architecture, specify which core to
2364 * start the thread on.
2366 * Return ID if context area could be allocated, else NULL.
2367 *---------------------------------------------------------------------------
2369 unsigned int create_thread(void (*function)(void),
2370 void* stack, size_t stack_size,
2371 unsigned flags, const char *name
2372 IF_PRIO(, int priority)
2373 IF_COP(, unsigned int core))
2375 unsigned int i;
2376 unsigned int stack_words;
2377 uintptr_t stackptr, stackend;
2378 struct thread_entry *thread;
2379 unsigned state;
2380 int oldlevel;
2382 thread = find_empty_thread_slot();
2383 if (thread == NULL)
2385 return 0;
2388 oldlevel = disable_irq_save();
2390 /* Munge the stack to make it easy to spot stack overflows */
2391 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2392 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2393 stack_size = stackend - stackptr;
2394 stack_words = stack_size / sizeof (uintptr_t);
2396 for (i = 0; i < stack_words; i++)
2398 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2401 /* Store interesting information */
2402 thread->name = name;
2403 thread->stack = (uintptr_t *)stackptr;
2404 thread->stack_size = stack_size;
2405 thread->queue = NULL;
2406 #ifdef HAVE_WAKEUP_EXT_CB
2407 thread->wakeup_ext_cb = NULL;
2408 #endif
2409 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2410 thread->cpu_boost = 0;
2411 #endif
2412 #ifdef HAVE_PRIORITY_SCHEDULING
2413 memset(&thread->pdist, 0, sizeof(thread->pdist));
2414 thread->blocker = NULL;
2415 thread->base_priority = priority;
2416 thread->priority = priority;
2417 thread->skip_count = priority;
2418 prio_add_entry(&thread->pdist, priority);
2419 #endif
2421 #if NUM_CORES > 1
2422 thread->core = core;
2424 /* Writeback stack munging or anything else before starting */
2425 if (core != CURRENT_CORE)
2427 cpucache_flush();
2429 #endif
2431 /* Thread is not on any timeout list but be a bit paranoid */
2432 thread->tmo.prev = NULL;
2434 state = (flags & CREATE_THREAD_FROZEN) ?
2435 STATE_FROZEN : STATE_RUNNING;
2437 thread->context.sp = (typeof (thread->context.sp))stackend;
2439 /* Load the thread's context structure with needed startup information */
2440 THREAD_STARTUP_INIT(core, thread, function);
2442 thread->state = state;
2443 i = thread->id; /* Snapshot while locked */
2445 if (state == STATE_RUNNING)
2446 core_schedule_wakeup(thread);
2448 UNLOCK_THREAD(thread);
2449 restore_irq(oldlevel);
2451 return i;
2454 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2455 /*---------------------------------------------------------------------------
2456 * Change the boost state of a thread boosting or unboosting the CPU
2457 * as required.
2458 *---------------------------------------------------------------------------
2460 static inline void boost_thread(struct thread_entry *thread, bool boost)
2462 if ((thread->cpu_boost != 0) != boost)
2464 thread->cpu_boost = boost;
2465 cpu_boost(boost);
2469 void trigger_cpu_boost(void)
2471 struct thread_entry *current = cores[CURRENT_CORE].running;
2472 boost_thread(current, true);
2475 void cancel_cpu_boost(void)
2477 struct thread_entry *current = cores[CURRENT_CORE].running;
2478 boost_thread(current, false);
2480 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2482 /*---------------------------------------------------------------------------
2483 * Block the current thread until another thread terminates. A thread may
2484 * wait on itself to terminate which prevents it from running again and it
2485 * will need to be killed externally.
2486 * Parameter is the ID as returned from create_thread().
2487 *---------------------------------------------------------------------------
2489 void thread_wait(unsigned int thread_id)
2491 struct thread_entry *current = cores[CURRENT_CORE].running;
2492 struct thread_entry *thread = thread_id_entry(thread_id);
2494 /* Lock thread-as-waitable-object lock */
2495 corelock_lock(&thread->waiter_cl);
2497 /* Be sure it hasn't been killed yet */
2498 if (thread_id == THREAD_ID_CURRENT ||
2499 (thread->id == thread_id && thread->state != STATE_KILLED))
2501 IF_COP( current->obj_cl = &thread->waiter_cl; )
2502 current->bqp = &thread->queue;
2504 disable_irq();
2505 block_thread(current);
2507 corelock_unlock(&thread->waiter_cl);
2509 switch_thread();
2510 return;
2513 corelock_unlock(&thread->waiter_cl);
2516 /*---------------------------------------------------------------------------
2517 * Exit the current thread. The Right Way to Do Things (TM).
2518 *---------------------------------------------------------------------------
2520 void thread_exit(void)
2522 const unsigned int core = CURRENT_CORE;
2523 struct thread_entry *current = cores[core].running;
2525 /* Cancel CPU boost if any */
2526 cancel_cpu_boost();
2528 disable_irq();
2530 corelock_lock(&current->waiter_cl);
2531 LOCK_THREAD(current);
2533 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2534 if (current->name == THREAD_DESTRUCT)
2536 /* Thread being killed - become a waiter */
2537 unsigned int id = current->id;
2538 UNLOCK_THREAD(current);
2539 corelock_unlock(&current->waiter_cl);
2540 thread_wait(id);
2541 THREAD_PANICF("thread_exit->WK:*R", current);
2543 #endif
2545 #ifdef HAVE_PRIORITY_SCHEDULING
2546 check_for_obj_waiters("thread_exit", current);
2547 #endif
2549 if (current->tmo.prev != NULL)
2551 /* Cancel pending timeout list removal */
2552 remove_from_list_tmo(current);
2555 /* Switch tasks and never return */
2556 block_thread_on_l(current, STATE_KILLED);
2558 #if NUM_CORES > 1
2559 /* Switch to the idle stack if not on the main core (where "main"
2560 * runs) - we can hope gcc doesn't need the old stack beyond this
2561 * point. */
2562 if (core != CPU)
2564 switch_to_idle_stack(core);
2567 cpucache_flush();
2569 /* At this point, this thread isn't using resources allocated for
2570 * execution except the slot itself. */
2571 #endif
2573 /* Update ID for this slot */
2574 new_thread_id(current->id, current);
2575 current->name = NULL;
2577 /* Signal this thread */
2578 thread_queue_wake(&current->queue);
2579 corelock_unlock(&current->waiter_cl);
2580 /* Slot must be unusable until thread is really gone */
2581 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2582 switch_thread();
2583 /* This should never and must never be reached - if it is, the
2584 * state is corrupted */
2585 THREAD_PANICF("thread_exit->K:*R", current);
2588 #ifdef ALLOW_REMOVE_THREAD
2589 /*---------------------------------------------------------------------------
2590 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2591 * normal programs.
2593 * Parameter is the ID as returned from create_thread().
2595 * Use with care on threads that are not under careful control as this may
2596 * leave various objects in an undefined state.
2597 *---------------------------------------------------------------------------
2599 void remove_thread(unsigned int thread_id)
2601 #if NUM_CORES > 1
2602 /* core is not constant here because of core switching */
2603 unsigned int core = CURRENT_CORE;
2604 unsigned int old_core = NUM_CORES;
2605 struct corelock *ocl = NULL;
2606 #else
2607 const unsigned int core = CURRENT_CORE;
2608 #endif
2609 struct thread_entry *current = cores[core].running;
2610 struct thread_entry *thread = thread_id_entry(thread_id);
2612 unsigned state;
2613 int oldlevel;
2615 if (thread == current)
2616 thread_exit(); /* Current thread - do normal exit */
2618 oldlevel = disable_irq_save();
2620 corelock_lock(&thread->waiter_cl);
2621 LOCK_THREAD(thread);
2623 state = thread->state;
2625 if (thread->id != thread_id || state == STATE_KILLED)
2626 goto thread_killed;
2628 #if NUM_CORES > 1
2629 if (thread->name == THREAD_DESTRUCT)
2631 /* Thread being killed - become a waiter */
2632 UNLOCK_THREAD(thread);
2633 corelock_unlock(&thread->waiter_cl);
2634 restore_irq(oldlevel);
2635 thread_wait(thread_id);
2636 return;
2639 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2641 #ifdef HAVE_PRIORITY_SCHEDULING
2642 check_for_obj_waiters("remove_thread", thread);
2643 #endif
2645 if (thread->core != core)
2647 /* Switch cores and safely extract the thread there */
2648 /* Slot HAS to be unlocked or a deadlock could occur which means other
2649 * threads have to be guided into becoming thread waiters if they
2650 * attempt to remove it. */
2651 unsigned int new_core = thread->core;
2653 corelock_unlock(&thread->waiter_cl);
2655 UNLOCK_THREAD(thread);
2656 restore_irq(oldlevel);
2658 old_core = switch_core(new_core);
2660 oldlevel = disable_irq_save();
2662 corelock_lock(&thread->waiter_cl);
2663 LOCK_THREAD(thread);
2665 state = thread->state;
2666 core = new_core;
2667 /* Perform the extraction and switch ourselves back to the original
2668 processor */
2670 #endif /* NUM_CORES > 1 */
2672 if (thread->tmo.prev != NULL)
2674 /* Clean thread off the timeout list if a timeout check hasn't
2675 * run yet */
2676 remove_from_list_tmo(thread);
2679 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2680 /* Cancel CPU boost if any */
2681 boost_thread(thread, false);
2682 #endif
2684 IF_COP( retry_state: )
2686 switch (state)
2688 case STATE_RUNNING:
2689 RTR_LOCK(core);
2690 /* Remove thread from ready to run tasks */
2691 remove_from_list_l(&cores[core].running, thread);
2692 rtr_subtract_entry(core, thread->priority);
2693 RTR_UNLOCK(core);
2694 break;
2695 case STATE_BLOCKED:
2696 case STATE_BLOCKED_W_TMO:
2697 /* Remove thread from the queue it's blocked on - including its
2698 * own if waiting there */
2699 #if NUM_CORES > 1
2700 if (&thread->waiter_cl != thread->obj_cl)
2702 ocl = thread->obj_cl;
2704 if (UNLIKELY(corelock_try_lock(ocl) == 0))
2706 UNLOCK_THREAD(thread);
2707 corelock_lock(ocl);
2708 LOCK_THREAD(thread);
2710 if (UNLIKELY(thread->state != state))
2712 /* Something woke the thread */
2713 state = thread->state;
2714 corelock_unlock(ocl);
2715 goto retry_state;
2719 #endif
2720 remove_from_list_l(thread->bqp, thread);
2722 #ifdef HAVE_WAKEUP_EXT_CB
2723 if (thread->wakeup_ext_cb != NULL)
2724 thread->wakeup_ext_cb(thread);
2725 #endif
2727 #ifdef HAVE_PRIORITY_SCHEDULING
2728 if (thread->blocker != NULL)
2730 /* Remove thread's priority influence from its chain */
2731 wakeup_priority_protocol_release(thread);
2733 #endif
2735 #if NUM_CORES > 1
2736 if (ocl != NULL)
2737 corelock_unlock(ocl);
2738 #endif
2739 break;
2740 /* Otherwise thread is frozen and hasn't run yet */
2743 new_thread_id(thread_id, thread);
2744 thread->state = STATE_KILLED;
2746 /* If thread was waiting on itself, it will have been removed above.
2747 * The wrong order would result in waking the thread first and deadlocking
2748 * since the slot is already locked. */
2749 thread_queue_wake(&thread->queue);
2751 thread->name = NULL;
2753 thread_killed: /* Thread was already killed */
2754 /* Removal complete - safe to unlock and reenable interrupts */
2755 corelock_unlock(&thread->waiter_cl);
2756 UNLOCK_THREAD(thread);
2757 restore_irq(oldlevel);
2759 #if NUM_CORES > 1
2760 if (old_core < NUM_CORES)
2762 /* Did a removal on another processor's thread - switch back to
2763 native core */
2764 switch_core(old_core);
2766 #endif
2768 #endif /* ALLOW_REMOVE_THREAD */
2770 #ifdef HAVE_PRIORITY_SCHEDULING
2771 /*---------------------------------------------------------------------------
2772 * Sets the thread's relative base priority for the core it runs on. Any
2773 * needed inheritance changes also may happen.
2774 *---------------------------------------------------------------------------
2776 int thread_set_priority(unsigned int thread_id, int priority)
2778 int old_base_priority = -1;
2779 struct thread_entry *thread = thread_id_entry(thread_id);
2781 /* A little safety measure */
2782 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2783 return -1;
2785 /* Thread could be on any list and therefore on an interrupt accessible
2786 one - disable interrupts */
2787 int oldlevel = disable_irq_save();
2789 LOCK_THREAD(thread);
2791 /* Make sure it's not killed */
2792 if (thread_id == THREAD_ID_CURRENT ||
2793 (thread->id == thread_id && thread->state != STATE_KILLED))
2795 int old_priority = thread->priority;
2797 old_base_priority = thread->base_priority;
2798 thread->base_priority = priority;
2800 prio_move_entry(&thread->pdist, old_base_priority, priority);
2801 priority = find_first_set_bit(thread->pdist.mask);
2803 if (old_priority == priority)
2805 /* No priority change - do nothing */
2807 else if (thread->state == STATE_RUNNING)
2809 /* This thread is running - change location on the run
2810 * queue. No transitive inheritance needed. */
2811 set_running_thread_priority(thread, priority);
2813 else
2815 thread->priority = priority;
2817 if (thread->blocker != NULL)
2819 /* Bubble new priority down the chain */
2820 struct blocker *bl = thread->blocker; /* Blocker struct */
2821 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2822 struct thread_entry * const tstart = thread; /* Initial thread */
2823 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2825 for (;;)
2827 struct thread_entry *next; /* Next thread to check */
2828 int bl_pr; /* Highest blocked thread */
2829 int queue_pr; /* New highest blocked thread */
2830 #if NUM_CORES > 1
2831 /* Owner can change but thread cannot be dislodged - thread
2832 * may not be the first in the queue which allows other
2833 * threads ahead in the list to be given ownership during the
2834 * operation. If thread is next then the waker will have to
2835 * wait for us and the owner of the object will remain fixed.
2836 * If we successfully grab the owner -- which at some point
2837 * is guaranteed -- then the queue remains fixed until we
2838 * pass by. */
2839 for (;;)
2841 LOCK_THREAD(bl_t);
2843 /* Double-check the owner - retry if it changed */
2844 if (LIKELY(bl->thread == bl_t))
2845 break;
2847 UNLOCK_THREAD(bl_t);
2848 bl_t = bl->thread;
2850 #endif
2851 bl_pr = bl->priority;
2853 if (highest > bl_pr)
2854 break; /* Object priority won't change */
2856 /* This will include the thread being set */
2857 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2859 if (queue_pr == bl_pr)
2860 break; /* Object priority not changing */
2862 /* Update thread boost for this object */
2863 bl->priority = queue_pr;
2864 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2865 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2867 if (bl_t->priority == bl_pr)
2868 break; /* Blocking thread priority not changing */
2870 if (bl_t->state == STATE_RUNNING)
2872 /* Thread not blocked - we're done */
2873 set_running_thread_priority(bl_t, bl_pr);
2874 break;
2877 bl_t->priority = bl_pr;
2878 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2880 if (bl == NULL)
2881 break; /* End of chain */
2883 next = bl->thread;
2885 if (UNLIKELY(next == tstart))
2886 break; /* Full-circle */
2888 UNLOCK_THREAD(thread);
2890 thread = bl_t;
2891 bl_t = next;
2892 } /* for (;;) */
2894 UNLOCK_THREAD(bl_t);
2899 UNLOCK_THREAD(thread);
2901 restore_irq(oldlevel);
2903 return old_base_priority;
2906 /*---------------------------------------------------------------------------
2907 * Returns the current base priority for a thread.
2908 *---------------------------------------------------------------------------
2910 int thread_get_priority(unsigned int thread_id)
2912 struct thread_entry *thread = thread_id_entry(thread_id);
2913 int base_priority = thread->base_priority;
2915 /* Simply check without locking slot. It may or may not be valid by the
2916 * time the function returns anyway. If all tests pass, it is the
2917 * correct value for when it was valid. */
2918 if (thread_id != THREAD_ID_CURRENT &&
2919 (thread->id != thread_id || thread->state == STATE_KILLED))
2920 base_priority = -1;
2922 return base_priority;
2924 #endif /* HAVE_PRIORITY_SCHEDULING */
2926 /*---------------------------------------------------------------------------
2927 * Starts a frozen thread - similar semantics to wakeup_thread except that
2928 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2929 * virtue of the slot having a state of STATE_FROZEN.
2930 *---------------------------------------------------------------------------
2932 void thread_thaw(unsigned int thread_id)
2934 struct thread_entry *thread = thread_id_entry(thread_id);
2935 int oldlevel = disable_irq_save();
2937 LOCK_THREAD(thread);
2939 /* If thread is the current one, it cannot be frozen, therefore
2940 * there is no need to check that. */
2941 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2942 core_schedule_wakeup(thread);
2944 UNLOCK_THREAD(thread);
2945 restore_irq(oldlevel);
2948 /*---------------------------------------------------------------------------
2949 * Return the ID of the currently executing thread.
2950 *---------------------------------------------------------------------------
2952 unsigned int thread_get_current(void)
2954 return cores[CURRENT_CORE].running->id;
2957 #if NUM_CORES > 1
2958 /*---------------------------------------------------------------------------
2959 * Switch the processor that the currently executing thread runs on.
2960 *---------------------------------------------------------------------------
2962 unsigned int switch_core(unsigned int new_core)
2964 const unsigned int core = CURRENT_CORE;
2965 struct thread_entry *current = cores[core].running;
2967 if (core == new_core)
2969 /* No change - just return same core */
2970 return core;
2973 int oldlevel = disable_irq_save();
2974 LOCK_THREAD(current);
2976 if (current->name == THREAD_DESTRUCT)
2978 /* Thread being killed - deactivate and let process complete */
2979 unsigned int id = current->id;
2980 UNLOCK_THREAD(current);
2981 restore_irq(oldlevel);
2982 thread_wait(id);
2983 /* Should never be reached */
2984 THREAD_PANICF("switch_core->D:*R", current);
2987 /* Get us off the running list for the current core */
2988 RTR_LOCK(core);
2989 remove_from_list_l(&cores[core].running, current);
2990 rtr_subtract_entry(core, current->priority);
2991 RTR_UNLOCK(core);
2993 /* Stash return value (old core) in a safe place */
2994 current->retval = core;
2996 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2997 * the other core will likely attempt a removal from the wrong list! */
2998 if (current->tmo.prev != NULL)
3000 remove_from_list_tmo(current);
3003 /* Change the core number for this thread slot */
3004 current->core = new_core;
3006 /* Do not use core_schedule_wakeup here since this will result in
3007 * the thread starting to run on the other core before being finished on
3008 * this one. Delay the list unlock to keep the other core stuck
3009 * until this thread is ready. */
3010 RTR_LOCK(new_core);
3012 rtr_add_entry(new_core, current->priority);
3013 add_to_list_l(&cores[new_core].running, current);
3015 /* Make a callback into device-specific code, unlock the wakeup list so
3016 * that execution may resume on the new core, unlock our slot and finally
3017 * restore the interrupt level */
3018 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3019 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3020 cores[core].block_task = current;
3022 UNLOCK_THREAD(current);
3024 /* Alert other core to activity */
3025 core_wake(new_core);
3027 /* Do the stack switching, cache_maintenence and switch_thread call -
3028 requires native code */
3029 switch_thread_core(core, current);
3031 /* Finally return the old core to caller */
3032 return current->retval;
3034 #endif /* NUM_CORES > 1 */
3036 /*---------------------------------------------------------------------------
3037 * Initialize threading API. This assumes interrupts are not yet enabled. On
3038 * multicore setups, no core is allowed to proceed until create_thread calls
3039 * are safe to perform.
3040 *---------------------------------------------------------------------------
3042 void init_threads(void)
3044 const unsigned int core = CURRENT_CORE;
3045 struct thread_entry *thread;
3047 if (core == CPU)
3049 /* Initialize core locks and IDs in all slots */
3050 int n;
3051 for (n = 0; n < MAXTHREADS; n++)
3053 thread = &threads[n];
3054 corelock_init(&thread->waiter_cl);
3055 corelock_init(&thread->slot_cl);
3056 thread->id = THREAD_ID_INIT(n);
3060 /* CPU will initialize first and then sleep */
3061 thread = find_empty_thread_slot();
3063 if (thread == NULL)
3065 /* WTF? There really must be a slot available at this stage.
3066 * This can fail if, for example, .bss isn't zero'ed out by the loader
3067 * or threads is in the wrong section. */
3068 THREAD_PANICF("init_threads->no slot", NULL);
3071 /* Initialize initially non-zero members of core */
3072 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3074 /* Initialize initially non-zero members of slot */
3075 UNLOCK_THREAD(thread); /* No sync worries yet */
3076 thread->name = main_thread_name;
3077 thread->state = STATE_RUNNING;
3078 IF_COP( thread->core = core; )
3079 #ifdef HAVE_PRIORITY_SCHEDULING
3080 corelock_init(&cores[core].rtr_cl);
3081 thread->base_priority = PRIORITY_USER_INTERFACE;
3082 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3083 thread->priority = PRIORITY_USER_INTERFACE;
3084 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3085 #endif
3087 add_to_list_l(&cores[core].running, thread);
3089 if (core == CPU)
3091 thread->stack = stackbegin;
3092 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3093 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3094 /* Wait for other processors to finish their inits since create_thread
3095 * isn't safe to call until the kernel inits are done. The first
3096 * threads created in the system must of course be created by CPU.
3097 * Another possible approach is to initialize all cores and slots
3098 * for each core by CPU, let the remainder proceed in parallel and
3099 * signal CPU when all are finished. */
3100 core_thread_init(CPU);
3102 else
3104 /* Initial stack is the idle stack */
3105 thread->stack = idle_stacks[core];
3106 thread->stack_size = IDLE_STACK_SIZE;
3107 /* After last processor completes, it should signal all others to
3108 * proceed or may signal the next and call thread_exit(). The last one
3109 * to finish will signal CPU. */
3110 core_thread_init(core);
3111 /* Other cores do not have a main thread - go idle inside switch_thread
3112 * until a thread can run on the core. */
3113 thread_exit();
3114 #endif /* NUM_CORES */
3118 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3119 #if NUM_CORES == 1
3120 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3121 #else
3122 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3123 #endif
3125 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3126 unsigned int i;
3127 int usage = 0;
3129 for (i = 0; i < stack_words; i++)
3131 if (stackptr[i] != DEADBEEF)
3133 usage = ((stack_words - i) * 100) / stack_words;
3134 break;
3138 return usage;
3141 /*---------------------------------------------------------------------------
3142 * Returns the maximum percentage of stack a thread ever used while running.
3143 * NOTE: Some large buffer allocations that don't use enough the buffer to
3144 * overwrite stackptr[0] will not be seen.
3145 *---------------------------------------------------------------------------
3147 int thread_stack_usage(const struct thread_entry *thread)
3149 return stack_usage(thread->stack, thread->stack_size);
3152 #if NUM_CORES > 1
3153 /*---------------------------------------------------------------------------
3154 * Returns the maximum percentage of the core's idle stack ever used during
3155 * runtime.
3156 *---------------------------------------------------------------------------
3158 int idle_stack_usage(unsigned int core)
3160 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3162 #endif
3164 /*---------------------------------------------------------------------------
3165 * Fills in the buffer with the specified thread's name. If the name is NULL,
3166 * empty, or the thread is in destruct state a formatted ID is written
3167 * instead.
3168 *---------------------------------------------------------------------------
3170 void thread_get_name(char *buffer, int size,
3171 struct thread_entry *thread)
3173 if (size <= 0)
3174 return;
3176 *buffer = '\0';
3178 if (thread)
3180 /* Display thread name if one or ID if none */
3181 const char *name = thread->name;
3182 const char *fmt = "%s";
3183 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3185 name = (const char *)thread;
3186 fmt = "%08lX";
3188 snprintf(buffer, size, fmt, name);