Fix a bug when shutting down the player with the charger plugged in with the flashed...
[kugel-rb.git] / firmware / thread.c
blobc500fc4818d6aad121239dc78d98ae4474c52240
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "config.h"
22 #include <stdbool.h>
23 #include "thread.h"
24 #include "panic.h"
25 #include "sprintf.h"
26 #include "system.h"
27 #include "kernel.h"
28 #include "cpu.h"
29 #include "string.h"
30 #ifdef RB_PROFILE
31 #include <profile.h>
32 #endif
33 /****************************************************************************
34 * ATTENTION!! *
35 * See notes below on implementing processor-specific portions! *
36 ***************************************************************************/
38 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
39 #ifdef DEBUG
40 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
41 #else
42 #define THREAD_EXTRA_CHECKS 0
43 #endif
45 /**
46 * General locking order to guarantee progress. Order must be observed but
47 * all stages are not nescessarily obligatory. Going from 1) to 3) is
48 * perfectly legal.
50 * 1) IRQ
51 * This is first because of the likelyhood of having an interrupt occur that
52 * also accesses one of the objects farther down the list. Any non-blocking
53 * synchronization done may already have a lock on something during normal
54 * execution and if an interrupt handler running on the same processor as
55 * the one that has the resource locked were to attempt to access the
56 * resource, the interrupt handler would wait forever waiting for an unlock
57 * that will never happen. There is no danger if the interrupt occurs on
58 * a different processor because the one that has the lock will eventually
59 * unlock and the other processor's handler may proceed at that time. Not
60 * nescessary when the resource in question is definitely not available to
61 * interrupt handlers.
63 * 2) Kernel Object
64 * 1) May be needed beforehand if the kernel object allows dual-use such as
65 * event queues. The kernel object must have a scheme to protect itself from
66 * access by another processor and is responsible for serializing the calls
67 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
68 * other. Objects' queues are also protected here.
70 * 3) Thread Slot
71 * This locks access to the thread's slot such that its state cannot be
72 * altered by another processor when a state change is in progress such as
73 * when it is in the process of going on a blocked list. An attempt to wake
74 * a thread while it is still blocking will likely desync its state with
75 * the other resources used for that state.
77 * 4) Core Lists
78 * These lists are specific to a particular processor core and are accessible
79 * by all processor cores and interrupt handlers. The running (rtr) list is
80 * the prime example where a thread may be added by any means.
83 /*---------------------------------------------------------------------------
84 * Processor specific: core_sleep/core_wake/misc. notes
86 * ARM notes:
87 * FIQ is not dealt with by the scheduler code and is simply restored if it
88 * must by masked for some reason - because threading modifies a register
89 * that FIQ may also modify and there's no way to accomplish it atomically.
90 * s3c2440 is such a case.
92 * Audio interrupts are generally treated at a higher priority than others
93 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
94 * are not in general safe. Special cases may be constructed on a per-
95 * source basis and blocking operations are not available.
97 * core_sleep procedure to implement for any CPU to ensure an asychronous
98 * wakup never results in requiring a wait until the next tick (up to
99 * 10000uS!). May require assembly and careful instruction ordering.
101 * 1) On multicore, stay awake if directed to do so by another. If so, goto
102 * step 4.
103 * 2) If processor requires, atomically reenable interrupts and perform step
104 * 3.
105 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
106 * on Coldfire) goto step 5.
107 * 4) Enable interrupts.
108 * 5) Exit procedure.
110 * core_wake and multprocessor notes for sleep/wake coordination:
111 * If possible, to wake up another processor, the forcing of an interrupt on
112 * the woken core by the waker core is the easiest way to ensure a non-
113 * delayed wake and immediate execution of any woken threads. If that isn't
114 * available then some careful non-blocking synchonization is needed (as on
115 * PP targets at the moment).
116 *---------------------------------------------------------------------------
119 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
120 * (someday :). */
121 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
122 struct core_entry cores[NUM_CORES] IBSS_ATTR;
123 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
125 static const char main_thread_name[] = "main";
126 extern uintptr_t stackbegin[];
127 extern uintptr_t stackend[];
129 static inline void core_sleep(IF_COP_VOID(unsigned int core))
130 __attribute__((always_inline));
132 void check_tmo_threads(void)
133 __attribute__((noinline));
135 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
136 __attribute__((always_inline));
138 static void add_to_list_tmo(struct thread_entry *thread)
139 __attribute__((noinline));
141 static void core_schedule_wakeup(struct thread_entry *thread)
142 __attribute__((noinline));
144 #if NUM_CORES > 1
145 static inline void run_blocking_ops(
146 unsigned int core, struct thread_entry *thread)
147 __attribute__((always_inline));
148 #endif
150 static void thread_stkov(struct thread_entry *thread)
151 __attribute__((noinline));
153 static inline void store_context(void* addr)
154 __attribute__((always_inline));
156 static inline void load_context(const void* addr)
157 __attribute__((always_inline));
159 void switch_thread(void)
160 __attribute__((noinline));
162 /****************************************************************************
163 * Processor-specific section
166 #if defined(MAX_PHYS_SECTOR_SIZE) && MEM == 64
167 /* Support a special workaround object for large-sector disks */
168 #define IF_NO_SKIP_YIELD(...) __VA_ARGS__
169 #else
170 #define IF_NO_SKIP_YIELD(...)
171 #endif
173 #if defined(CPU_ARM)
174 /*---------------------------------------------------------------------------
175 * Start the thread running and terminate it if it returns
176 *---------------------------------------------------------------------------
178 static void __attribute__((naked,used)) start_thread(void)
180 /* r0 = context */
181 asm volatile (
182 "ldr sp, [r0, #32] \n" /* Load initial sp */
183 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
184 "mov r1, #0 \n" /* Mark thread as running */
185 "str r1, [r0, #40] \n"
186 #if NUM_CORES > 1
187 "ldr r0, =invalidate_icache \n" /* Invalidate this core's cache. */
188 "mov lr, pc \n" /* This could be the first entry into */
189 "bx r0 \n" /* plugin or codec code for this core. */
190 #endif
191 "mov lr, pc \n" /* Call thread function */
192 "bx r4 \n"
193 ); /* No clobber list - new thread doesn't care */
194 thread_exit();
195 //asm volatile (".ltorg"); /* Dump constant pool */
198 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
199 * slot, and thread function pointer in context.start. See load_context for
200 * what happens when thread is initially going to run. */
201 #define THREAD_STARTUP_INIT(core, thread, function) \
202 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
203 (thread)->context.r[1] = (uint32_t)start_thread, \
204 (thread)->context.start = (uint32_t)function; })
206 /*---------------------------------------------------------------------------
207 * Store non-volatile context.
208 *---------------------------------------------------------------------------
210 static inline void store_context(void* addr)
212 asm volatile(
213 "stmia %0, { r4-r11, sp, lr } \n"
214 : : "r" (addr)
218 /*---------------------------------------------------------------------------
219 * Load non-volatile context.
220 *---------------------------------------------------------------------------
222 static inline void load_context(const void* addr)
224 asm volatile(
225 "ldr r0, [%0, #40] \n" /* Load start pointer */
226 "cmp r0, #0 \n" /* Check for NULL */
227 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
228 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
229 : : "r" (addr) : "r0" /* only! */
233 #if defined (CPU_PP)
235 #if NUM_CORES > 1
236 extern uintptr_t cpu_idlestackbegin[];
237 extern uintptr_t cpu_idlestackend[];
238 extern uintptr_t cop_idlestackbegin[];
239 extern uintptr_t cop_idlestackend[];
240 static uintptr_t * const idle_stacks[NUM_CORES] =
242 [CPU] = cpu_idlestackbegin,
243 [COP] = cop_idlestackbegin
246 #if CONFIG_CPU == PP5002
247 /* Bytes to emulate the PP502x mailbox bits */
248 struct core_semaphores
250 volatile uint8_t intend_wake; /* 00h */
251 volatile uint8_t stay_awake; /* 01h */
252 volatile uint8_t intend_sleep; /* 02h */
253 volatile uint8_t unused; /* 03h */
256 static struct core_semaphores core_semaphores[NUM_CORES] IBSS_ATTR;
257 #endif /* CONFIG_CPU == PP5002 */
259 #endif /* NUM_CORES */
261 #if CONFIG_CORELOCK == SW_CORELOCK
262 /* Software core locks using Peterson's mutual exclusion algorithm */
264 /*---------------------------------------------------------------------------
265 * Initialize the corelock structure.
266 *---------------------------------------------------------------------------
268 void corelock_init(struct corelock *cl)
270 memset(cl, 0, sizeof (*cl));
273 #if 1 /* Assembly locks to minimize overhead */
274 /*---------------------------------------------------------------------------
275 * Wait for the corelock to become free and acquire it when it does.
276 *---------------------------------------------------------------------------
278 void corelock_lock(struct corelock *cl) __attribute__((naked));
279 void corelock_lock(struct corelock *cl)
281 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
282 asm volatile (
283 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
284 "ldrb r1, [r1] \n"
285 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
286 "eor r2, r1, #0xff \n" /* r2 = othercore */
287 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
288 "1: \n"
289 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
290 "cmp r3, #0 \n" /* yes? lock acquired */
291 "bxeq lr \n"
292 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
293 "cmp r3, r1 \n"
294 "bxeq lr \n" /* yes? lock acquired */
295 "b 1b \n" /* keep trying */
296 : : "i"(&PROCESSOR_ID)
298 (void)cl;
301 /*---------------------------------------------------------------------------
302 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
303 *---------------------------------------------------------------------------
305 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
306 int corelock_try_lock(struct corelock *cl)
308 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
309 asm volatile (
310 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
311 "ldrb r1, [r1] \n"
312 "mov r3, r0 \n"
313 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
314 "eor r2, r1, #0xff \n" /* r2 = othercore */
315 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
316 "ldrb r0, [r3, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
317 "eors r0, r0, r2 \n" /* yes? lock acquired */
318 "bxne lr \n"
319 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
320 "ands r0, r0, r1 \n"
321 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
322 "bx lr \n" /* return result */
323 : : "i"(&PROCESSOR_ID)
326 return 0;
327 (void)cl;
330 /*---------------------------------------------------------------------------
331 * Release ownership of the corelock
332 *---------------------------------------------------------------------------
334 void corelock_unlock(struct corelock *cl) __attribute__((naked));
335 void corelock_unlock(struct corelock *cl)
337 asm volatile (
338 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
339 "ldrb r1, [r1] \n"
340 "mov r2, #0 \n" /* cl->myl[core] = 0 */
341 "strb r2, [r0, r1, lsr #7] \n"
342 "bx lr \n"
343 : : "i"(&PROCESSOR_ID)
345 (void)cl;
347 #else /* C versions for reference */
348 /*---------------------------------------------------------------------------
349 * Wait for the corelock to become free and aquire it when it does.
350 *---------------------------------------------------------------------------
352 void corelock_lock(struct corelock *cl)
354 const unsigned int core = CURRENT_CORE;
355 const unsigned int othercore = 1 - core;
357 cl->myl[core] = core;
358 cl->turn = othercore;
360 for (;;)
362 if (cl->myl[othercore] == 0 || cl->turn == core)
363 break;
367 /*---------------------------------------------------------------------------
368 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
369 *---------------------------------------------------------------------------
371 int corelock_try_lock(struct corelock *cl)
373 const unsigned int core = CURRENT_CORE;
374 const unsigned int othercore = 1 - core;
376 cl->myl[core] = core;
377 cl->turn = othercore;
379 if (cl->myl[othercore] == 0 || cl->turn == core)
381 return 1;
384 cl->myl[core] = 0;
385 return 0;
388 /*---------------------------------------------------------------------------
389 * Release ownership of the corelock
390 *---------------------------------------------------------------------------
392 void corelock_unlock(struct corelock *cl)
394 cl->myl[CURRENT_CORE] = 0;
396 #endif /* ASM / C selection */
398 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
400 /*---------------------------------------------------------------------------
401 * Put core in a power-saving state if waking list wasn't repopulated and if
402 * no other core requested a wakeup for it to perform a task.
403 *---------------------------------------------------------------------------
405 #ifdef CPU_PP502x
406 #if NUM_CORES == 1
407 static inline void core_sleep(void)
409 sleep_core(CURRENT_CORE);
410 enable_irq();
412 #else
413 static inline void core_sleep(unsigned int core)
415 #if 1
416 asm volatile (
417 "mov r0, #4 \n" /* r0 = 0x4 << core */
418 "mov r0, r0, lsl %[c] \n"
419 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
420 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
421 "tst r1, r0, lsl #2 \n"
422 "moveq r1, #0x80000000 \n" /* Then sleep */
423 "streq r1, [%[ctl], %[c], lsl #2] \n"
424 "moveq r1, #0 \n" /* Clear control reg */
425 "streq r1, [%[ctl], %[c], lsl #2] \n"
426 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
427 "str r1, [%[mbx], #8] \n"
428 "1: \n" /* Wait for wake procedure to finish */
429 "ldr r1, [%[mbx], #0] \n"
430 "tst r1, r0, lsr #2 \n"
431 "bne 1b \n"
433 : [ctl]"r"(&CPU_CTL), [mbx]"r"(MBX_BASE), [c]"r"(core)
434 : "r0", "r1");
435 #else /* C version for reference */
436 /* Signal intent to sleep */
437 MBX_MSG_SET = 0x4 << core;
439 /* Something waking or other processor intends to wake us? */
440 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
442 sleep_core(core);
443 wake_core(core);
446 /* Signal wake - clear wake flag */
447 MBX_MSG_CLR = 0x14 << core;
449 /* Wait for other processor to finish wake procedure */
450 while (MBX_MSG_STAT & (0x1 << core));
451 #endif /* ASM/C selection */
452 enable_irq();
454 #endif /* NUM_CORES */
455 #elif CONFIG_CPU == PP5002
456 #if NUM_CORES == 1
457 static inline void core_sleep(void)
459 sleep_core(CURRENT_CORE);
460 enable_irq();
462 #else
463 /* PP5002 has no mailboxes - emulate using bytes */
464 static inline void core_sleep(unsigned int core)
466 #if 1
467 asm volatile (
468 "mov r0, #1 \n" /* Signal intent to sleep */
469 "strb r0, [%[sem], #2] \n"
470 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
471 "cmp r0, #0 \n"
472 "bne 2f \n"
473 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
474 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
475 * that the correct alternative is executed. Don't change the order
476 * of the next 4 instructions! */
477 "tst pc, #0x0c \n"
478 "mov r0, #0xca \n"
479 "strne r0, [%[ctl], %[c], lsl #2] \n"
480 "streq r0, [%[ctl], %[c], lsl #2] \n"
481 "nop \n" /* nop's needed because of pipeline */
482 "nop \n"
483 "nop \n"
484 "2: \n"
485 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
486 "strb r0, [%[sem], #1] \n"
487 "strb r0, [%[sem], #2] \n"
488 "1: \n" /* Wait for wake procedure to finish */
489 "ldrb r0, [%[sem], #0] \n"
490 "cmp r0, #0 \n"
491 "bne 1b \n"
493 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
494 [ctl]"r"(&CPU_CTL)
495 : "r0"
497 #else /* C version for reference */
498 /* Signal intent to sleep */
499 core_semaphores[core].intend_sleep = 1;
501 /* Something waking or other processor intends to wake us? */
502 if (core_semaphores[core].stay_awake == 0)
504 sleep_core(core);
507 /* Signal wake - clear wake flag */
508 core_semaphores[core].stay_awake = 0;
509 core_semaphores[core].intend_sleep = 0;
511 /* Wait for other processor to finish wake procedure */
512 while (core_semaphores[core].intend_wake != 0);
514 /* Enable IRQ */
515 #endif /* ASM/C selection */
516 enable_irq();
518 #endif /* NUM_CORES */
519 #endif /* PP CPU type */
521 /*---------------------------------------------------------------------------
522 * Wake another processor core that is sleeping or prevent it from doing so
523 * if it was already destined. FIQ, IRQ should be disabled before calling.
524 *---------------------------------------------------------------------------
526 #if NUM_CORES == 1
527 /* Shared single-core build debugging version */
528 void core_wake(void)
530 /* No wakey - core already wakey */
532 #elif defined (CPU_PP502x)
533 void core_wake(unsigned int othercore)
535 #if 1
536 /* avoid r0 since that contains othercore */
537 asm volatile (
538 "mrs r3, cpsr \n" /* Disable IRQ */
539 "orr r1, r3, #0x80 \n"
540 "msr cpsr_c, r1 \n"
541 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
542 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
543 "str r2, [%[mbx], #4] \n"
544 "1: \n" /* If it intends to sleep, let it first */
545 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
546 "eor r1, r1, #0xc \n"
547 "tst r1, r2, lsr #2 \n"
548 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
549 "tsteq r1, #0x80000000 \n"
550 "beq 1b \n" /* Wait for sleep or wake */
551 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
552 "movne r1, #0x0 \n"
553 "strne r1, [%[ctl], %[oc], lsl #2] \n"
554 "mov r1, r2, lsr #4 \n"
555 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
556 "msr cpsr_c, r3 \n" /* Restore IRQ */
558 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
559 [oc]"r"(othercore)
560 : "r1", "r2", "r3");
561 #else /* C version for reference */
562 /* Disable interrupts - avoid reentrancy from the tick */
563 int oldlevel = disable_irq_save();
565 /* Signal intent to wake other processor - set stay awake */
566 MBX_MSG_SET = 0x11 << othercore;
568 /* If it intends to sleep, wait until it does or aborts */
569 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
570 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
572 /* If sleeping, wake it up */
573 if (PROC_CTL(othercore) & PROC_SLEEP)
574 PROC_CTL(othercore) = 0;
576 /* Done with wake procedure */
577 MBX_MSG_CLR = 0x1 << othercore;
578 restore_irq(oldlevel);
579 #endif /* ASM/C selection */
581 #elif CONFIG_CPU == PP5002
582 /* PP5002 has no mailboxes - emulate using bytes */
583 void core_wake(unsigned int othercore)
585 #if 1
586 /* avoid r0 since that contains othercore */
587 asm volatile (
588 "mrs r3, cpsr \n" /* Disable IRQ */
589 "orr r1, r3, #0x80 \n"
590 "msr cpsr_c, r1 \n"
591 "mov r1, #1 \n" /* Signal intent to wake other core */
592 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
593 "strh r1, [%[sem], #0] \n"
594 "mov r2, #0x8000 \n"
595 "1: \n" /* If it intends to sleep, let it first */
596 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
597 "cmp r1, #1 \n"
598 "ldr r1, [%[st]] \n" /* && not sleeping ? */
599 "tsteq r1, r2, lsr %[oc] \n"
600 "beq 1b \n" /* Wait for sleep or wake */
601 "tst r1, r2, lsr %[oc] \n"
602 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
603 "movne r1, #0xce \n"
604 "strne r1, [r2, %[oc], lsl #2] \n"
605 "mov r1, #0 \n" /* Done with wake procedure */
606 "strb r1, [%[sem], #0] \n"
607 "msr cpsr_c, r3 \n" /* Restore IRQ */
609 : [sem]"r"(&core_semaphores[othercore]),
610 [st]"r"(&PROC_STAT),
611 [oc]"r"(othercore)
612 : "r1", "r2", "r3"
614 #else /* C version for reference */
615 /* Disable interrupts - avoid reentrancy from the tick */
616 int oldlevel = disable_irq_save();
618 /* Signal intent to wake other processor - set stay awake */
619 core_semaphores[othercore].intend_wake = 1;
620 core_semaphores[othercore].stay_awake = 1;
622 /* If it intends to sleep, wait until it does or aborts */
623 while (core_semaphores[othercore].intend_sleep != 0 &&
624 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
626 /* If sleeping, wake it up */
627 if (PROC_STAT & PROC_SLEEPING(othercore))
628 wake_core(othercore);
630 /* Done with wake procedure */
631 core_semaphores[othercore].intend_wake = 0;
632 restore_irq(oldlevel);
633 #endif /* ASM/C selection */
635 #endif /* CPU type */
637 #if NUM_CORES > 1
638 /*---------------------------------------------------------------------------
639 * Switches to a stack that always resides in the Rockbox core.
641 * Needed when a thread suicides on a core other than the main CPU since the
642 * stack used when idling is the stack of the last thread to run. This stack
643 * may not reside in the core firmware in which case the core will continue
644 * to use a stack from an unloaded module until another thread runs on it.
645 *---------------------------------------------------------------------------
647 static inline void switch_to_idle_stack(const unsigned int core)
649 asm volatile (
650 "str sp, [%0] \n" /* save original stack pointer on idle stack */
651 "mov sp, %0 \n" /* switch stacks */
652 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
653 (void)core;
656 /*---------------------------------------------------------------------------
657 * Perform core switch steps that need to take place inside switch_thread.
659 * These steps must take place while before changing the processor and after
660 * having entered switch_thread since switch_thread may not do a normal return
661 * because the stack being used for anything the compiler saved will not belong
662 * to the thread's destination core and it may have been recycled for other
663 * purposes by the time a normal context load has taken place. switch_thread
664 * will also clobber anything stashed in the thread's context or stored in the
665 * nonvolatile registers if it is saved there before the call since the
666 * compiler's order of operations cannot be known for certain.
668 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
670 /* Flush our data to ram */
671 flush_icache();
672 /* Stash thread in r4 slot */
673 thread->context.r[0] = (uint32_t)thread;
674 /* Stash restart address in r5 slot */
675 thread->context.r[1] = thread->context.start;
676 /* Save sp in context.sp while still running on old core */
677 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
680 /*---------------------------------------------------------------------------
681 * Machine-specific helper function for switching the processor a thread is
682 * running on. Basically, the thread suicides on the departing core and is
683 * reborn on the destination. Were it not for gcc's ill-behavior regarding
684 * naked functions written in C where it actually clobbers non-volatile
685 * registers before the intended prologue code, this would all be much
686 * simpler. Generic setup is done in switch_core itself.
689 /*---------------------------------------------------------------------------
690 * This actually performs the core switch.
692 static void __attribute__((naked))
693 switch_thread_core(unsigned int core, struct thread_entry *thread)
695 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
696 * Stack access also isn't permitted until restoring the original stack and
697 * context. */
698 asm volatile (
699 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
700 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
701 "ldr r2, [r2, r0, lsl #2] \n"
702 "add r2, r2, %0*4 \n"
703 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
704 "mov sp, r2 \n" /* switch stacks */
705 "adr r2, 1f \n" /* r2 = new core restart address */
706 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
707 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
708 "1: \n"
709 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
710 "mov r1, #0 \n" /* Clear start address */
711 "str r1, [r0, #40] \n"
712 "ldr r0, =invalidate_icache \n" /* Invalidate new core's cache */
713 "mov lr, pc \n"
714 "bx r0 \n"
715 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
716 ".ltorg \n" /* Dump constant pool */
717 : : "i"(IDLE_STACK_WORDS)
719 (void)core; (void)thread;
722 /*---------------------------------------------------------------------------
723 * Do any device-specific inits for the threads and synchronize the kernel
724 * initializations.
725 *---------------------------------------------------------------------------
727 static void core_thread_init(unsigned int core)
729 if (core == CPU)
731 /* Wake up coprocessor and let it initialize kernel and threads */
732 #ifdef CPU_PP502x
733 MBX_MSG_CLR = 0x3f;
734 #endif
735 wake_core(COP);
736 /* Sleep until COP has finished */
737 sleep_core(CPU);
739 else
741 /* Wake the CPU and return */
742 wake_core(CPU);
745 #endif /* NUM_CORES */
747 #elif CONFIG_CPU == S3C2440
749 /*---------------------------------------------------------------------------
750 * Put core in a power-saving state if waking list wasn't repopulated.
751 *---------------------------------------------------------------------------
753 static inline void core_sleep(void)
755 /* FIQ also changes the CLKCON register so FIQ must be disabled
756 when changing it here */
757 asm volatile (
758 "mrs r0, cpsr \n"
759 "orr r2, r0, #0x40 \n" /* Disable FIQ */
760 "bic r0, r0, #0x80 \n" /* Prepare IRQ enable */
761 "msr cpsr_c, r2 \n"
762 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
763 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
764 "orr r2, r2, #4 \n"
765 "str r2, [r1, #0xc] \n"
766 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
767 "mov r2, #0 \n" /* wait for IDLE */
768 "1: \n"
769 "add r2, r2, #1 \n"
770 "cmp r2, #10 \n"
771 "bne 1b \n"
772 "orr r2, r0, #0xc0 \n" /* Disable IRQ, FIQ */
773 "msr cpsr_c, r2 \n"
774 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
775 "bic r2, r2, #4 \n"
776 "str r2, [r1, #0xc] \n"
777 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
778 : : : "r0", "r1", "r2");
780 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X) /* Single core only for now */ \
781 || CONFIG_CPU == IMX31L || CONFIG_CPU == DM320 || CONFIG_CPU == AS3525
782 /* Use the generic ARMv4/v5 wait for IRQ */
783 static inline void core_sleep(void)
785 asm volatile (
786 "mov r0, #0 \n"
787 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
788 : : : "r0"
790 enable_irq();
792 #else
793 static inline void core_sleep(void)
795 #warning core_sleep not implemented, battery life will be decreased
796 enable_irq();
798 #endif /* CONFIG_CPU == */
800 #elif defined(CPU_COLDFIRE)
801 /*---------------------------------------------------------------------------
802 * Start the thread running and terminate it if it returns
803 *---------------------------------------------------------------------------
805 void start_thread(void); /* Provide C access to ASM label */
806 static void __attribute__((used)) __start_thread(void)
808 /* a0=macsr, a1=context */
809 asm volatile (
810 "start_thread: \n" /* Start here - no naked attribute */
811 "move.l %a0, %macsr \n" /* Set initial mac status reg */
812 "lea.l 48(%a1), %a1 \n"
813 "move.l (%a1)+, %sp \n" /* Set initial stack */
814 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
815 "clr.l (%a1) \n" /* Mark thread running */
816 "jsr (%a2) \n" /* Call thread function */
818 thread_exit();
821 /* Set EMAC unit to fractional mode with saturation for each new thread,
822 * since that's what'll be the most useful for most things which the dsp
823 * will do. Codecs should still initialize their preferred modes
824 * explicitly. Context pointer is placed in d2 slot and start_thread
825 * pointer in d3 slot. thread function pointer is placed in context.start.
826 * See load_context for what happens when thread is initially going to
827 * run.
829 #define THREAD_STARTUP_INIT(core, thread, function) \
830 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
831 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
832 (thread)->context.d[1] = (uint32_t)start_thread, \
833 (thread)->context.start = (uint32_t)(function); })
835 /*---------------------------------------------------------------------------
836 * Store non-volatile context.
837 *---------------------------------------------------------------------------
839 static inline void store_context(void* addr)
841 asm volatile (
842 "move.l %%macsr,%%d0 \n"
843 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
844 : : "a" (addr) : "d0" /* only! */
848 /*---------------------------------------------------------------------------
849 * Load non-volatile context.
850 *---------------------------------------------------------------------------
852 static inline void load_context(const void* addr)
854 asm volatile (
855 "move.l 52(%0), %%d0 \n" /* Get start address */
856 "beq.b 1f \n" /* NULL -> already running */
857 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
858 "jmp (%%a2) \n" /* Start the thread */
859 "1: \n"
860 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
861 "move.l %%d0, %%macsr \n"
862 : : "a" (addr) : "d0" /* only! */
866 /*---------------------------------------------------------------------------
867 * Put core in a power-saving state if waking list wasn't repopulated.
868 *---------------------------------------------------------------------------
870 static inline void core_sleep(void)
872 /* Supervisor mode, interrupts enabled upon wakeup */
873 asm volatile ("stop #0x2000");
876 #elif CONFIG_CPU == SH7034
877 /*---------------------------------------------------------------------------
878 * Start the thread running and terminate it if it returns
879 *---------------------------------------------------------------------------
881 void start_thread(void); /* Provide C access to ASM label */
882 static void __attribute__((used)) __start_thread(void)
884 /* r8 = context */
885 asm volatile (
886 "_start_thread: \n" /* Start here - no naked attribute */
887 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
888 "mov.l @(28, r8), r15 \n" /* Set initial sp */
889 "mov #0, r1 \n" /* Start the thread */
890 "jsr @r0 \n"
891 "mov.l r1, @(36, r8) \n" /* Clear start address */
893 thread_exit();
896 /* Place context pointer in r8 slot, function pointer in r9 slot, and
897 * start_thread pointer in context_start */
898 #define THREAD_STARTUP_INIT(core, thread, function) \
899 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
900 (thread)->context.r[1] = (uint32_t)(function), \
901 (thread)->context.start = (uint32_t)start_thread; })
903 /*---------------------------------------------------------------------------
904 * Store non-volatile context.
905 *---------------------------------------------------------------------------
907 static inline void store_context(void* addr)
909 asm volatile (
910 "add #36, %0 \n" /* Start at last reg. By the time routine */
911 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
912 "mov.l r15,@-%0 \n"
913 "mov.l r14,@-%0 \n"
914 "mov.l r13,@-%0 \n"
915 "mov.l r12,@-%0 \n"
916 "mov.l r11,@-%0 \n"
917 "mov.l r10,@-%0 \n"
918 "mov.l r9, @-%0 \n"
919 "mov.l r8, @-%0 \n"
920 : : "r" (addr)
924 /*---------------------------------------------------------------------------
925 * Load non-volatile context.
926 *---------------------------------------------------------------------------
928 static inline void load_context(const void* addr)
930 asm volatile (
931 "mov.l @(36, %0), r0 \n" /* Get start address */
932 "tst r0, r0 \n"
933 "bt .running \n" /* NULL -> already running */
934 "jmp @r0 \n" /* r8 = context */
935 ".running: \n"
936 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
937 "mov.l @%0+, r9 \n"
938 "mov.l @%0+, r10 \n"
939 "mov.l @%0+, r11 \n"
940 "mov.l @%0+, r12 \n"
941 "mov.l @%0+, r13 \n"
942 "mov.l @%0+, r14 \n"
943 "mov.l @%0+, r15 \n"
944 "lds.l @%0+, pr \n"
945 : : "r" (addr) : "r0" /* only! */
949 /*---------------------------------------------------------------------------
950 * Put core in a power-saving state.
951 *---------------------------------------------------------------------------
953 static inline void core_sleep(void)
955 asm volatile (
956 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
957 "mov #0, r1 \n" /* Enable interrupts */
958 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
959 "sleep \n" /* Execute standby */
960 : : "z"(&SBYCR-GBR) : "r1");
963 #elif CPU_MIPS == 32
965 /*---------------------------------------------------------------------------
966 * Start the thread running and terminate it if it returns
967 *---------------------------------------------------------------------------
970 void start_thread(void); /* Provide C access to ASM label */
971 static void __attribute__((used)) _start_thread(void)
973 /* $t1 = context */
974 asm volatile (
975 "start_thread: \n"
976 ".set noreorder \n"
977 ".set noat \n"
978 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = $t0, $9 = $t1) */
979 "lw $29, 40($9) \n" /* Set initial sp(=$29) */
980 "sw $0, 48($9) \n" /* Clear start address */
981 "jr $8 \n" /* Start the thread */
982 "nop \n"
983 ".set at \n"
984 ".set reorder \n"
986 thread_exit();
989 /* Place context pointer in $s0 slot, function pointer in $s1 slot, and
990 * start_thread pointer in context_start */
991 #define THREAD_STARTUP_INIT(core, thread, function) \
992 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
993 (thread)->context.r[1] = (uint32_t)(function), \
994 (thread)->context.start = (uint32_t)start_thread; })
996 /*---------------------------------------------------------------------------
997 * Store non-volatile context.
998 *---------------------------------------------------------------------------
1000 static inline void store_context(void* addr)
1002 asm volatile (
1003 ".set noreorder \n"
1004 ".set noat \n"
1005 "move $8, %0 \n"
1006 "sw $16, 0($8) \n" /* $s0 */
1007 "sw $17, 4($8) \n" /* $s1 */
1008 "sw $18, 8($8) \n" /* $s2 */
1009 "sw $19, 12($8) \n" /* $s3 */
1010 "sw $20, 16($8) \n" /* $s4 */
1011 "sw $21, 20($8) \n" /* $s5 */
1012 "sw $22, 24($8) \n" /* $s6 */
1013 "sw $23, 28($8) \n" /* $s7 */
1014 "sw $28, 32($8) \n" /* gp */
1015 "sw $30, 36($8) \n" /* fp */
1016 "sw $29, 40($8) \n" /* sp */
1017 "sw $31, 44($8) \n" /* ra */
1018 ".set at \n"
1019 ".set reorder \n"
1020 : : "r" (addr) : "t0"
1024 /*---------------------------------------------------------------------------
1025 * Load non-volatile context.
1026 *---------------------------------------------------------------------------
1028 static inline void load_context(const void* addr)
1030 asm volatile (
1031 ".set noat \n"
1032 ".set noreorder \n"
1033 "lw $8, 48(%0) \n" /* Get start address ($8 = $t0) */
1034 "beqz $8, running \n" /* NULL -> already running */
1035 "nop \n"
1036 "move $9, %0 \n" /* $t1 = context */
1037 "jr $8 \n"
1038 "nop \n"
1039 "running: \n"
1040 "move $8, %0 \n"
1041 "lw $16, 0($8) \n" /* $s0 */
1042 "lw $17, 4($8) \n" /* $s1 */
1043 "lw $18, 8($8) \n" /* $s2 */
1044 "lw $19, 12($8) \n" /* $s3 */
1045 "lw $20, 16($8) \n" /* $s4 */
1046 "lw $21, 20($8) \n" /* $s5 */
1047 "lw $22, 24($8) \n" /* $s6 */
1048 "lw $23, 28($8) \n" /* $s7 */
1049 "lw $28, 32($8) \n" /* gp */
1050 "lw $30, 36($8) \n" /* fp */
1051 "lw $29, 40($8) \n" /* sp */
1052 "lw $31, 44($8) \n" /* ra */
1053 ".set at \n"
1054 ".set reorder \n"
1055 : : "r" (addr) : "t0" /* only! */
1059 /*---------------------------------------------------------------------------
1060 * Put core in a power-saving state.
1061 *---------------------------------------------------------------------------
1063 static inline void core_sleep(void)
1065 #if CONFIG_CPU == JZ4732
1066 __cpm_idle_mode();
1067 #endif
1068 asm volatile(".set mips32r2 \n"
1069 "mfc0 $8, $12 \n" /* mfc $t0, $12 */
1070 "move $9, $8 \n" /* move $t1, $t0 */
1071 "la $10, 0x8000000 \n" /* la $t2, 0x8000000 */
1072 "or $8, $8, $10 \n" /* Enable reduced power mode */
1073 "mtc0 $8, $12 \n"
1074 "wait \n"
1075 "mtc0 $9, $12 \n"
1076 ".set mips0 \n"
1077 ::: "t0", "t1", "t2"
1082 #endif /* CONFIG_CPU == */
1085 * End Processor-specific section
1086 ***************************************************************************/
1088 #if THREAD_EXTRA_CHECKS
1089 static void thread_panicf(const char *msg, struct thread_entry *thread)
1091 IF_COP( const unsigned int core = thread->core; )
1092 static char name[32];
1093 thread_get_name(name, 32, thread);
1094 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1096 static void thread_stkov(struct thread_entry *thread)
1098 thread_panicf("Stkov", thread);
1100 #define THREAD_PANICF(msg, thread) \
1101 thread_panicf(msg, thread)
1102 #define THREAD_ASSERT(exp, msg, thread) \
1103 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1104 #else
1105 static void thread_stkov(struct thread_entry *thread)
1107 IF_COP( const unsigned int core = thread->core; )
1108 static char name[32];
1109 thread_get_name(name, 32, thread);
1110 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1112 #define THREAD_PANICF(msg, thread)
1113 #define THREAD_ASSERT(exp, msg, thread)
1114 #endif /* THREAD_EXTRA_CHECKS */
1116 /* Thread locking */
1117 #if NUM_CORES > 1
1118 #define LOCK_THREAD(thread) \
1119 ({ corelock_lock(&(thread)->slot_cl); })
1120 #define TRY_LOCK_THREAD(thread) \
1121 ({ corelock_try_lock(&thread->slot_cl); })
1122 #define UNLOCK_THREAD(thread) \
1123 ({ corelock_unlock(&(thread)->slot_cl); })
1124 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1125 ({ unsigned int _core = (thread)->core; \
1126 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1127 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1128 #else
1129 #define LOCK_THREAD(thread) \
1130 ({ })
1131 #define TRY_LOCK_THREAD(thread) \
1132 ({ })
1133 #define UNLOCK_THREAD(thread) \
1134 ({ })
1135 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1136 ({ })
1137 #endif
1139 /* RTR list */
1140 #define RTR_LOCK(core) \
1141 ({ corelock_lock(&cores[core].rtr_cl); })
1142 #define RTR_UNLOCK(core) \
1143 ({ corelock_unlock(&cores[core].rtr_cl); })
1145 #ifdef HAVE_PRIORITY_SCHEDULING
1146 #define rtr_add_entry(core, priority) \
1147 prio_add_entry(&cores[core].rtr, (priority))
1149 #define rtr_subtract_entry(core, priority) \
1150 prio_subtract_entry(&cores[core].rtr, (priority))
1152 #define rtr_move_entry(core, from, to) \
1153 prio_move_entry(&cores[core].rtr, (from), (to))
1154 #else
1155 #define rtr_add_entry(core, priority)
1156 #define rtr_add_entry_inl(core, priority)
1157 #define rtr_subtract_entry(core, priority)
1158 #define rtr_subtract_entry_inl(core, priotity)
1159 #define rtr_move_entry(core, from, to)
1160 #define rtr_move_entry_inl(core, from, to)
1161 #endif
1163 /*---------------------------------------------------------------------------
1164 * Thread list structure - circular:
1165 * +------------------------------+
1166 * | |
1167 * +--+---+<-+---+<-+---+<-+---+<-+
1168 * Head->| T | | T | | T | | T |
1169 * +->+---+->+---+->+---+->+---+--+
1170 * | |
1171 * +------------------------------+
1172 *---------------------------------------------------------------------------
1175 /*---------------------------------------------------------------------------
1176 * Adds a thread to a list of threads using "insert last". Uses the "l"
1177 * links.
1178 *---------------------------------------------------------------------------
1180 static void add_to_list_l(struct thread_entry **list,
1181 struct thread_entry *thread)
1183 struct thread_entry *l = *list;
1185 if (l == NULL)
1187 /* Insert into unoccupied list */
1188 thread->l.prev = thread;
1189 thread->l.next = thread;
1190 *list = thread;
1191 return;
1194 /* Insert last */
1195 thread->l.prev = l->l.prev;
1196 thread->l.next = l;
1197 l->l.prev->l.next = thread;
1198 l->l.prev = thread;
1201 /*---------------------------------------------------------------------------
1202 * Removes a thread from a list of threads. Uses the "l" links.
1203 *---------------------------------------------------------------------------
1205 static void remove_from_list_l(struct thread_entry **list,
1206 struct thread_entry *thread)
1208 struct thread_entry *prev, *next;
1210 next = thread->l.next;
1212 if (thread == next)
1214 /* The only item */
1215 *list = NULL;
1216 return;
1219 if (thread == *list)
1221 /* List becomes next item */
1222 *list = next;
1225 prev = thread->l.prev;
1227 /* Fix links to jump over the removed entry. */
1228 next->l.prev = prev;
1229 prev->l.next = next;
1232 /*---------------------------------------------------------------------------
1233 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1234 * NULL-terminated forward (to ease the far more common forward traversal):
1235 * +------------------------------+
1236 * | |
1237 * +--+---+<-+---+<-+---+<-+---+<-+
1238 * Head->| T | | T | | T | | T |
1239 * +---+->+---+->+---+->+---+-X
1240 *---------------------------------------------------------------------------
1243 /*---------------------------------------------------------------------------
1244 * Add a thread from the core's timout list by linking the pointers in its
1245 * tmo structure.
1246 *---------------------------------------------------------------------------
1248 static void add_to_list_tmo(struct thread_entry *thread)
1250 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1251 THREAD_ASSERT(thread->tmo.prev == NULL,
1252 "add_to_list_tmo->already listed", thread);
1254 thread->tmo.next = NULL;
1256 if (tmo == NULL)
1258 /* Insert into unoccupied list */
1259 thread->tmo.prev = thread;
1260 cores[IF_COP_CORE(thread->core)].timeout = thread;
1261 return;
1264 /* Insert Last */
1265 thread->tmo.prev = tmo->tmo.prev;
1266 tmo->tmo.prev->tmo.next = thread;
1267 tmo->tmo.prev = thread;
1270 /*---------------------------------------------------------------------------
1271 * Remove a thread from the core's timout list by unlinking the pointers in
1272 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1273 * is cancelled.
1274 *---------------------------------------------------------------------------
1276 static void remove_from_list_tmo(struct thread_entry *thread)
1278 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1279 struct thread_entry *prev = thread->tmo.prev;
1280 struct thread_entry *next = thread->tmo.next;
1282 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1284 if (next != NULL)
1285 next->tmo.prev = prev;
1287 if (thread == *list)
1289 /* List becomes next item and empty if next == NULL */
1290 *list = next;
1291 /* Mark as unlisted */
1292 thread->tmo.prev = NULL;
1294 else
1296 if (next == NULL)
1297 (*list)->tmo.prev = prev;
1298 prev->tmo.next = next;
1299 /* Mark as unlisted */
1300 thread->tmo.prev = NULL;
1305 #ifdef HAVE_PRIORITY_SCHEDULING
1306 /*---------------------------------------------------------------------------
1307 * Priority distribution structure (one category for each possible priority):
1309 * +----+----+----+ ... +-----+
1310 * hist: | F0 | F1 | F2 | | F31 |
1311 * +----+----+----+ ... +-----+
1312 * mask: | b0 | b1 | b2 | | b31 |
1313 * +----+----+----+ ... +-----+
1315 * F = count of threads at priority category n (frequency)
1316 * b = bitmask of non-zero priority categories (occupancy)
1318 * / if H[n] != 0 : 1
1319 * b[n] = |
1320 * \ else : 0
1322 *---------------------------------------------------------------------------
1323 * Basic priority inheritance priotocol (PIP):
1325 * Mn = mutex n, Tn = thread n
1327 * A lower priority thread inherits the priority of the highest priority
1328 * thread blocked waiting for it to complete an action (such as release a
1329 * mutex or respond to a message via queue_send):
1331 * 1) T2->M1->T1
1333 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1334 * priority than T1 then T1 inherits the priority of T2.
1336 * 2) T3
1337 * \/
1338 * T2->M1->T1
1340 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1341 * T1 inherits the higher of T2 and T3.
1343 * 3) T3->M2->T2->M1->T1
1345 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1346 * then T1 inherits the priority of T3 through T2.
1348 * Blocking chains can grow arbitrarily complex (though it's best that they
1349 * not form at all very often :) and build-up from these units.
1350 *---------------------------------------------------------------------------
1353 /*---------------------------------------------------------------------------
1354 * Increment frequency at category "priority"
1355 *---------------------------------------------------------------------------
1357 static inline unsigned int prio_add_entry(
1358 struct priority_distribution *pd, int priority)
1360 unsigned int count;
1361 /* Enough size/instruction count difference for ARM makes it worth it to
1362 * use different code (192 bytes for ARM). Only thing better is ASM. */
1363 #ifdef CPU_ARM
1364 count = pd->hist[priority];
1365 if (++count == 1)
1366 pd->mask |= 1 << priority;
1367 pd->hist[priority] = count;
1368 #else /* This one's better for Coldfire */
1369 if ((count = ++pd->hist[priority]) == 1)
1370 pd->mask |= 1 << priority;
1371 #endif
1373 return count;
1376 /*---------------------------------------------------------------------------
1377 * Decrement frequency at category "priority"
1378 *---------------------------------------------------------------------------
1380 static inline unsigned int prio_subtract_entry(
1381 struct priority_distribution *pd, int priority)
1383 unsigned int count;
1385 #ifdef CPU_ARM
1386 count = pd->hist[priority];
1387 if (--count == 0)
1388 pd->mask &= ~(1 << priority);
1389 pd->hist[priority] = count;
1390 #else
1391 if ((count = --pd->hist[priority]) == 0)
1392 pd->mask &= ~(1 << priority);
1393 #endif
1395 return count;
1398 /*---------------------------------------------------------------------------
1399 * Remove from one category and add to another
1400 *---------------------------------------------------------------------------
1402 static inline void prio_move_entry(
1403 struct priority_distribution *pd, int from, int to)
1405 uint32_t mask = pd->mask;
1407 #ifdef CPU_ARM
1408 unsigned int count;
1410 count = pd->hist[from];
1411 if (--count == 0)
1412 mask &= ~(1 << from);
1413 pd->hist[from] = count;
1415 count = pd->hist[to];
1416 if (++count == 1)
1417 mask |= 1 << to;
1418 pd->hist[to] = count;
1419 #else
1420 if (--pd->hist[from] == 0)
1421 mask &= ~(1 << from);
1423 if (++pd->hist[to] == 1)
1424 mask |= 1 << to;
1425 #endif
1427 pd->mask = mask;
1430 /*---------------------------------------------------------------------------
1431 * Change the priority and rtr entry for a running thread
1432 *---------------------------------------------------------------------------
1434 static inline void set_running_thread_priority(
1435 struct thread_entry *thread, int priority)
1437 const unsigned int core = IF_COP_CORE(thread->core);
1438 RTR_LOCK(core);
1439 rtr_move_entry(core, thread->priority, priority);
1440 thread->priority = priority;
1441 RTR_UNLOCK(core);
1444 /*---------------------------------------------------------------------------
1445 * Finds the highest priority thread in a list of threads. If the list is
1446 * empty, the PRIORITY_IDLE is returned.
1448 * It is possible to use the struct priority_distribution within an object
1449 * instead of scanning the remaining threads in the list but as a compromise,
1450 * the resulting per-object memory overhead is saved at a slight speed
1451 * penalty under high contention.
1452 *---------------------------------------------------------------------------
1454 static int find_highest_priority_in_list_l(
1455 struct thread_entry * const thread)
1457 if (thread != NULL)
1459 /* Go though list until the ending up at the initial thread */
1460 int highest_priority = thread->priority;
1461 struct thread_entry *curr = thread;
1465 int priority = curr->priority;
1467 if (priority < highest_priority)
1468 highest_priority = priority;
1470 curr = curr->l.next;
1472 while (curr != thread);
1474 return highest_priority;
1477 return PRIORITY_IDLE;
1480 /*---------------------------------------------------------------------------
1481 * Register priority with blocking system and bubble it down the chain if
1482 * any until we reach the end or something is already equal or higher.
1484 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1485 * targets but that same action also guarantees a circular block anyway and
1486 * those are prevented, right? :-)
1487 *---------------------------------------------------------------------------
1489 static struct thread_entry *
1490 blocker_inherit_priority(struct thread_entry *current)
1492 const int priority = current->priority;
1493 struct blocker *bl = current->blocker;
1494 struct thread_entry * const tstart = current;
1495 struct thread_entry *bl_t = bl->thread;
1497 /* Blocker cannot change since the object protection is held */
1498 LOCK_THREAD(bl_t);
1500 for (;;)
1502 struct thread_entry *next;
1503 int bl_pr = bl->priority;
1505 if (priority >= bl_pr)
1506 break; /* Object priority already high enough */
1508 bl->priority = priority;
1510 /* Add this one */
1511 prio_add_entry(&bl_t->pdist, priority);
1513 if (bl_pr < PRIORITY_IDLE)
1515 /* Not first waiter - subtract old one */
1516 prio_subtract_entry(&bl_t->pdist, bl_pr);
1519 if (priority >= bl_t->priority)
1520 break; /* Thread priority high enough */
1522 if (bl_t->state == STATE_RUNNING)
1524 /* Blocking thread is a running thread therefore there are no
1525 * further blockers. Change the "run queue" on which it
1526 * resides. */
1527 set_running_thread_priority(bl_t, priority);
1528 break;
1531 bl_t->priority = priority;
1533 /* If blocking thread has a blocker, apply transitive inheritance */
1534 bl = bl_t->blocker;
1536 if (bl == NULL)
1537 break; /* End of chain or object doesn't support inheritance */
1539 next = bl->thread;
1541 if (next == tstart)
1542 break; /* Full-circle - deadlock! */
1544 UNLOCK_THREAD(current);
1546 #if NUM_CORES > 1
1547 for (;;)
1549 LOCK_THREAD(next);
1551 /* Blocker could change - retest condition */
1552 if (bl->thread == next)
1553 break;
1555 UNLOCK_THREAD(next);
1556 next = bl->thread;
1558 #endif
1559 current = bl_t;
1560 bl_t = next;
1563 UNLOCK_THREAD(bl_t);
1565 return current;
1568 /*---------------------------------------------------------------------------
1569 * Readjust priorities when waking a thread blocked waiting for another
1570 * in essence "releasing" the thread's effect on the object owner. Can be
1571 * performed from any context.
1572 *---------------------------------------------------------------------------
1574 struct thread_entry *
1575 wakeup_priority_protocol_release(struct thread_entry *thread)
1577 const int priority = thread->priority;
1578 struct blocker *bl = thread->blocker;
1579 struct thread_entry * const tstart = thread;
1580 struct thread_entry *bl_t = bl->thread;
1582 /* Blocker cannot change since object will be locked */
1583 LOCK_THREAD(bl_t);
1585 thread->blocker = NULL; /* Thread not blocked */
1587 for (;;)
1589 struct thread_entry *next;
1590 int bl_pr = bl->priority;
1592 if (priority > bl_pr)
1593 break; /* Object priority higher */
1595 next = *thread->bqp;
1597 if (next == NULL)
1599 /* No more threads in queue */
1600 prio_subtract_entry(&bl_t->pdist, bl_pr);
1601 bl->priority = PRIORITY_IDLE;
1603 else
1605 /* Check list for highest remaining priority */
1606 int queue_pr = find_highest_priority_in_list_l(next);
1608 if (queue_pr == bl_pr)
1609 break; /* Object priority not changing */
1611 /* Change queue priority */
1612 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1613 bl->priority = queue_pr;
1616 if (bl_pr > bl_t->priority)
1617 break; /* thread priority is higher */
1619 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1621 if (bl_pr == bl_t->priority)
1622 break; /* Thread priority not changing */
1624 if (bl_t->state == STATE_RUNNING)
1626 /* No further blockers */
1627 set_running_thread_priority(bl_t, bl_pr);
1628 break;
1631 bl_t->priority = bl_pr;
1633 /* If blocking thread has a blocker, apply transitive inheritance */
1634 bl = bl_t->blocker;
1636 if (bl == NULL)
1637 break; /* End of chain or object doesn't support inheritance */
1639 next = bl->thread;
1641 if (next == tstart)
1642 break; /* Full-circle - deadlock! */
1644 UNLOCK_THREAD(thread);
1646 #if NUM_CORES > 1
1647 for (;;)
1649 LOCK_THREAD(next);
1651 /* Blocker could change - retest condition */
1652 if (bl->thread == next)
1653 break;
1655 UNLOCK_THREAD(next);
1656 next = bl->thread;
1658 #endif
1659 thread = bl_t;
1660 bl_t = next;
1663 UNLOCK_THREAD(bl_t);
1665 #if NUM_CORES > 1
1666 if (thread != tstart)
1668 /* Relock original if it changed */
1669 LOCK_THREAD(tstart);
1671 #endif
1673 return cores[CURRENT_CORE].running;
1676 /*---------------------------------------------------------------------------
1677 * Transfer ownership to a thread waiting for an objects and transfer
1678 * inherited priority boost from other waiters. This algorithm knows that
1679 * blocking chains may only unblock from the very end.
1681 * Only the owning thread itself may call this and so the assumption that
1682 * it is the running thread is made.
1683 *---------------------------------------------------------------------------
1685 struct thread_entry *
1686 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1688 /* Waking thread inherits priority boost from object owner */
1689 struct blocker *bl = thread->blocker;
1690 struct thread_entry *bl_t = bl->thread;
1691 struct thread_entry *next;
1692 int bl_pr;
1694 THREAD_ASSERT(thread_get_current() == bl_t,
1695 "UPPT->wrong thread", thread_get_current());
1697 LOCK_THREAD(bl_t);
1699 bl_pr = bl->priority;
1701 /* Remove the object's boost from the owning thread */
1702 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1703 bl_pr <= bl_t->priority)
1705 /* No more threads at this priority are waiting and the old level is
1706 * at least the thread level */
1707 int priority = find_first_set_bit(bl_t->pdist.mask);
1709 if (priority != bl_t->priority)
1711 /* Adjust this thread's priority */
1712 set_running_thread_priority(bl_t, priority);
1716 next = *thread->bqp;
1718 if (next == NULL)
1720 /* Expected shortcut - no more waiters */
1721 bl_pr = PRIORITY_IDLE;
1723 else
1725 if (thread->priority <= bl_pr)
1727 /* Need to scan threads remaining in queue */
1728 bl_pr = find_highest_priority_in_list_l(next);
1731 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1732 bl_pr < thread->priority)
1734 /* Thread priority must be raised */
1735 thread->priority = bl_pr;
1739 bl->thread = thread; /* This thread pwns */
1740 bl->priority = bl_pr; /* Save highest blocked priority */
1741 thread->blocker = NULL; /* Thread not blocked */
1743 UNLOCK_THREAD(bl_t);
1745 return bl_t;
1748 /*---------------------------------------------------------------------------
1749 * No threads must be blocked waiting for this thread except for it to exit.
1750 * The alternative is more elaborate cleanup and object registration code.
1751 * Check this for risk of silent data corruption when objects with
1752 * inheritable blocking are abandoned by the owner - not precise but may
1753 * catch something.
1754 *---------------------------------------------------------------------------
1756 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1758 /* Only one bit in the mask should be set with a frequency on 1 which
1759 * represents the thread's own base priority */
1760 uint32_t mask = thread->pdist.mask;
1761 if ((mask & (mask - 1)) != 0 ||
1762 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1764 unsigned char name[32];
1765 thread_get_name(name, 32, thread);
1766 panicf("%s->%s with obj. waiters", function, name);
1769 #endif /* HAVE_PRIORITY_SCHEDULING */
1771 /*---------------------------------------------------------------------------
1772 * Move a thread back to a running state on its core.
1773 *---------------------------------------------------------------------------
1775 static void core_schedule_wakeup(struct thread_entry *thread)
1777 const unsigned int core = IF_COP_CORE(thread->core);
1779 RTR_LOCK(core);
1781 thread->state = STATE_RUNNING;
1783 add_to_list_l(&cores[core].running, thread);
1784 rtr_add_entry(core, thread->priority);
1786 RTR_UNLOCK(core);
1788 #if NUM_CORES > 1
1789 if (core != CURRENT_CORE)
1790 core_wake(core);
1791 #endif
1794 /*---------------------------------------------------------------------------
1795 * Check the core's timeout list when at least one thread is due to wake.
1796 * Filtering for the condition is done before making the call. Resets the
1797 * tick when the next check will occur.
1798 *---------------------------------------------------------------------------
1800 void check_tmo_threads(void)
1802 const unsigned int core = CURRENT_CORE;
1803 const long tick = current_tick; /* snapshot the current tick */
1804 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1805 struct thread_entry *next = cores[core].timeout;
1807 /* If there are no processes waiting for a timeout, just keep the check
1808 tick from falling into the past. */
1810 /* Break the loop once we have walked through the list of all
1811 * sleeping processes or have removed them all. */
1812 while (next != NULL)
1814 /* Check sleeping threads. Allow interrupts between checks. */
1815 enable_irq();
1817 struct thread_entry *curr = next;
1819 next = curr->tmo.next;
1821 /* Lock thread slot against explicit wakeup */
1822 disable_irq();
1823 LOCK_THREAD(curr);
1825 unsigned state = curr->state;
1827 if (state < TIMEOUT_STATE_FIRST)
1829 /* Cleanup threads no longer on a timeout but still on the
1830 * list. */
1831 remove_from_list_tmo(curr);
1833 else if (TIME_BEFORE(tick, curr->tmo_tick))
1835 /* Timeout still pending - this will be the usual case */
1836 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1838 /* Earliest timeout found so far - move the next check up
1839 to its time */
1840 next_tmo_check = curr->tmo_tick;
1843 else
1845 /* Sleep timeout has been reached so bring the thread back to
1846 * life again. */
1847 if (state == STATE_BLOCKED_W_TMO)
1849 #if NUM_CORES > 1
1850 /* Lock the waiting thread's kernel object */
1851 struct corelock *ocl = curr->obj_cl;
1853 if (corelock_try_lock(ocl) == 0)
1855 /* Need to retry in the correct order though the need is
1856 * unlikely */
1857 UNLOCK_THREAD(curr);
1858 corelock_lock(ocl);
1859 LOCK_THREAD(curr);
1861 if (curr->state != STATE_BLOCKED_W_TMO)
1863 /* Thread was woken or removed explicitely while slot
1864 * was unlocked */
1865 corelock_unlock(ocl);
1866 remove_from_list_tmo(curr);
1867 UNLOCK_THREAD(curr);
1868 continue;
1871 #endif /* NUM_CORES */
1873 remove_from_list_l(curr->bqp, curr);
1875 #ifdef HAVE_WAKEUP_EXT_CB
1876 if (curr->wakeup_ext_cb != NULL)
1877 curr->wakeup_ext_cb(curr);
1878 #endif
1880 #ifdef HAVE_PRIORITY_SCHEDULING
1881 if (curr->blocker != NULL)
1882 wakeup_priority_protocol_release(curr);
1883 #endif
1884 corelock_unlock(ocl);
1886 /* else state == STATE_SLEEPING */
1888 remove_from_list_tmo(curr);
1890 RTR_LOCK(core);
1892 curr->state = STATE_RUNNING;
1894 add_to_list_l(&cores[core].running, curr);
1895 rtr_add_entry(core, curr->priority);
1897 RTR_UNLOCK(core);
1900 UNLOCK_THREAD(curr);
1903 cores[core].next_tmo_check = next_tmo_check;
1906 /*---------------------------------------------------------------------------
1907 * Performs operations that must be done before blocking a thread but after
1908 * the state is saved.
1909 *---------------------------------------------------------------------------
1911 #if NUM_CORES > 1
1912 static inline void run_blocking_ops(
1913 unsigned int core, struct thread_entry *thread)
1915 struct thread_blk_ops *ops = &cores[core].blk_ops;
1916 const unsigned flags = ops->flags;
1918 if (flags == TBOP_CLEAR)
1919 return;
1921 switch (flags)
1923 case TBOP_SWITCH_CORE:
1924 core_switch_blk_op(core, thread);
1925 /* Fall-through */
1926 case TBOP_UNLOCK_CORELOCK:
1927 corelock_unlock(ops->cl_p);
1928 break;
1931 ops->flags = TBOP_CLEAR;
1933 #endif /* NUM_CORES > 1 */
1935 #ifdef RB_PROFILE
1936 void profile_thread(void)
1938 profstart(cores[CURRENT_CORE].running - threads);
1940 #endif
1942 /*---------------------------------------------------------------------------
1943 * Prepares a thread to block on an object's list and/or for a specified
1944 * duration - expects object and slot to be appropriately locked if needed
1945 * and interrupts to be masked.
1946 *---------------------------------------------------------------------------
1948 static inline void block_thread_on_l(struct thread_entry *thread,
1949 unsigned state)
1951 /* If inlined, unreachable branches will be pruned with no size penalty
1952 because state is passed as a constant parameter. */
1953 const unsigned int core = IF_COP_CORE(thread->core);
1955 /* Remove the thread from the list of running threads. */
1956 RTR_LOCK(core);
1957 remove_from_list_l(&cores[core].running, thread);
1958 rtr_subtract_entry(core, thread->priority);
1959 RTR_UNLOCK(core);
1961 /* Add a timeout to the block if not infinite */
1962 switch (state)
1964 case STATE_BLOCKED:
1965 case STATE_BLOCKED_W_TMO:
1966 /* Put the thread into a new list of inactive threads. */
1967 add_to_list_l(thread->bqp, thread);
1969 if (state == STATE_BLOCKED)
1970 break;
1972 /* Fall-through */
1973 case STATE_SLEEPING:
1974 /* If this thread times out sooner than any other thread, update
1975 next_tmo_check to its timeout */
1976 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1978 cores[core].next_tmo_check = thread->tmo_tick;
1981 if (thread->tmo.prev == NULL)
1983 add_to_list_tmo(thread);
1985 /* else thread was never removed from list - just keep it there */
1986 break;
1989 /* Remember the the next thread about to block. */
1990 cores[core].block_task = thread;
1992 /* Report new state. */
1993 thread->state = state;
1996 /*---------------------------------------------------------------------------
1997 * Switch thread in round robin fashion for any given priority. Any thread
1998 * that removed itself from the running list first must specify itself in
1999 * the paramter.
2001 * INTERNAL: Intended for use by kernel and not for programs.
2002 *---------------------------------------------------------------------------
2004 void switch_thread(void)
2007 const unsigned int core = CURRENT_CORE;
2008 struct thread_entry *block = cores[core].block_task;
2009 struct thread_entry *thread = cores[core].running;
2011 /* Get context to save - next thread to run is unknown until all wakeups
2012 * are evaluated */
2013 if (block != NULL)
2015 cores[core].block_task = NULL;
2017 #if NUM_CORES > 1
2018 if (thread == block)
2020 /* This was the last thread running and another core woke us before
2021 * reaching here. Force next thread selection to give tmo threads or
2022 * other threads woken before this block a first chance. */
2023 block = NULL;
2025 else
2026 #endif
2028 /* Blocking task is the old one */
2029 thread = block;
2033 #ifdef RB_PROFILE
2034 profile_thread_stopped(thread - threads);
2035 #endif
2037 /* Begin task switching by saving our current context so that we can
2038 * restore the state of the current thread later to the point prior
2039 * to this call. */
2040 store_context(&thread->context);
2042 /* Check if the current thread stack is overflown */
2043 if (thread->stack[0] != DEADBEEF)
2044 thread_stkov(thread);
2046 #if NUM_CORES > 1
2047 /* Run any blocking operations requested before switching/sleeping */
2048 run_blocking_ops(core, thread);
2049 #endif
2051 #ifdef HAVE_PRIORITY_SCHEDULING
2052 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2053 /* Reset the value of thread's skip count */
2054 thread->skip_count = 0;
2055 #endif
2057 for (;;)
2059 /* If there are threads on a timeout and the earliest wakeup is due,
2060 * check the list and wake any threads that need to start running
2061 * again. */
2062 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2064 check_tmo_threads();
2067 disable_irq();
2068 RTR_LOCK(core);
2070 thread = cores[core].running;
2072 if (thread == NULL)
2074 /* Enter sleep mode to reduce power usage - woken up on interrupt
2075 * or wakeup request from another core - expected to enable
2076 * interrupts. */
2077 RTR_UNLOCK(core);
2078 core_sleep(IF_COP(core));
2080 else
2082 #ifdef HAVE_PRIORITY_SCHEDULING
2083 /* Select the new task based on priorities and the last time a
2084 * process got CPU time relative to the highest priority runnable
2085 * task. */
2086 struct priority_distribution *pd = &cores[core].rtr;
2087 int max = find_first_set_bit(pd->mask);
2089 if (block == NULL)
2091 /* Not switching on a block, tentatively select next thread */
2092 thread = thread->l.next;
2095 for (;;)
2097 int priority = thread->priority;
2098 int diff;
2100 /* This ridiculously simple method of aging seems to work
2101 * suspiciously well. It does tend to reward CPU hogs (under
2102 * yielding) but that's generally not desirable at all. On the
2103 * plus side, it, relatively to other threads, penalizes excess
2104 * yielding which is good if some high priority thread is
2105 * performing no useful work such as polling for a device to be
2106 * ready. Of course, aging is only employed when higher and lower
2107 * priority threads are runnable. The highest priority runnable
2108 * thread(s) are never skipped. */
2109 if (priority <= max ||
2110 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2111 (diff = priority - max, ++thread->skip_count > diff*diff))
2113 cores[core].running = thread;
2114 break;
2117 thread = thread->l.next;
2119 #else
2120 /* Without priority use a simple FCFS algorithm */
2121 if (block == NULL)
2123 /* Not switching on a block, select next thread */
2124 thread = thread->l.next;
2125 cores[core].running = thread;
2127 #endif /* HAVE_PRIORITY_SCHEDULING */
2129 RTR_UNLOCK(core);
2130 enable_irq();
2131 break;
2135 /* And finally give control to the next thread. */
2136 load_context(&thread->context);
2138 #ifdef RB_PROFILE
2139 profile_thread_started(thread - threads);
2140 #endif
2144 /*---------------------------------------------------------------------------
2145 * Sleeps a thread for at least a specified number of ticks with zero being
2146 * a wait until the next tick.
2148 * INTERNAL: Intended for use by kernel and not for programs.
2149 *---------------------------------------------------------------------------
2151 void sleep_thread(int ticks)
2153 struct thread_entry *current = cores[CURRENT_CORE].running;
2155 LOCK_THREAD(current);
2157 /* Set our timeout, remove from run list and join timeout list. */
2158 current->tmo_tick = current_tick + ticks + 1;
2159 block_thread_on_l(current, STATE_SLEEPING);
2161 UNLOCK_THREAD(current);
2164 /*---------------------------------------------------------------------------
2165 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2167 * INTERNAL: Intended for use by kernel objects and not for programs.
2168 *---------------------------------------------------------------------------
2170 void block_thread(struct thread_entry *current)
2172 /* Set the state to blocked and take us off of the run queue until we
2173 * are explicitly woken */
2174 LOCK_THREAD(current);
2176 /* Set the list for explicit wakeup */
2177 block_thread_on_l(current, STATE_BLOCKED);
2179 #ifdef HAVE_PRIORITY_SCHEDULING
2180 if (current->blocker != NULL)
2182 /* Object supports PIP */
2183 current = blocker_inherit_priority(current);
2185 #endif
2187 UNLOCK_THREAD(current);
2190 /*---------------------------------------------------------------------------
2191 * Block a thread on a blocking queue for a specified time interval or until
2192 * explicitly woken - whichever happens first.
2194 * INTERNAL: Intended for use by kernel objects and not for programs.
2195 *---------------------------------------------------------------------------
2197 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2199 /* Get the entry for the current running thread. */
2200 LOCK_THREAD(current);
2202 /* Set the state to blocked with the specified timeout */
2203 current->tmo_tick = current_tick + timeout;
2205 /* Set the list for explicit wakeup */
2206 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2208 #ifdef HAVE_PRIORITY_SCHEDULING
2209 if (current->blocker != NULL)
2211 /* Object supports PIP */
2212 current = blocker_inherit_priority(current);
2214 #endif
2216 UNLOCK_THREAD(current);
2219 /*---------------------------------------------------------------------------
2220 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2221 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2223 * This code should be considered a critical section by the caller meaning
2224 * that the object's corelock should be held.
2226 * INTERNAL: Intended for use by kernel objects and not for programs.
2227 *---------------------------------------------------------------------------
2229 unsigned int wakeup_thread(struct thread_entry **list)
2231 struct thread_entry *thread = *list;
2232 unsigned int result = THREAD_NONE;
2234 /* Check if there is a blocked thread at all. */
2235 if (thread == NULL)
2236 return result;
2238 LOCK_THREAD(thread);
2240 /* Determine thread's current state. */
2241 switch (thread->state)
2243 case STATE_BLOCKED:
2244 case STATE_BLOCKED_W_TMO:
2245 remove_from_list_l(list, thread);
2247 result = THREAD_OK;
2249 #ifdef HAVE_PRIORITY_SCHEDULING
2250 struct thread_entry *current;
2251 struct blocker *bl = thread->blocker;
2253 if (bl == NULL)
2255 /* No inheritance - just boost the thread by aging */
2256 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2257 thread->skip_count = thread->priority;
2258 current = cores[CURRENT_CORE].running;
2260 else
2262 /* Call the specified unblocking PIP */
2263 current = bl->wakeup_protocol(thread);
2266 if (current != NULL && thread->priority < current->priority
2267 IF_COP( && thread->core == current->core ))
2269 /* Woken thread is higher priority and exists on the same CPU core;
2270 * recommend a task switch. Knowing if this is an interrupt call
2271 * would be helpful here. */
2272 result |= THREAD_SWITCH;
2274 #endif /* HAVE_PRIORITY_SCHEDULING */
2276 core_schedule_wakeup(thread);
2277 break;
2279 /* Nothing to do. State is not blocked. */
2280 #if THREAD_EXTRA_CHECKS
2281 default:
2282 THREAD_PANICF("wakeup_thread->block invalid", thread);
2283 case STATE_RUNNING:
2284 case STATE_KILLED:
2285 break;
2286 #endif
2289 UNLOCK_THREAD(thread);
2290 return result;
2293 /*---------------------------------------------------------------------------
2294 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2295 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2296 * the queue must be locked first.
2298 * INTERNAL: Intended for use by kernel objects and not for programs.
2299 *---------------------------------------------------------------------------
2301 unsigned int thread_queue_wake(struct thread_entry **list)
2303 unsigned result = THREAD_NONE;
2305 for (;;)
2307 unsigned int rc = wakeup_thread(list);
2309 if (rc == THREAD_NONE)
2310 break; /* No more threads */
2312 result |= rc;
2315 return result;
2318 /*---------------------------------------------------------------------------
2319 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2320 * will be locked on multicore.
2321 *---------------------------------------------------------------------------
2323 static struct thread_entry * find_empty_thread_slot(void)
2325 /* Any slot could be on an interrupt-accessible list */
2326 IF_COP( int oldlevel = disable_irq_save(); )
2327 struct thread_entry *thread = NULL;
2328 int n;
2330 for (n = 0; n < MAXTHREADS; n++)
2332 /* Obtain current slot state - lock it on multicore */
2333 struct thread_entry *t = &threads[n];
2334 LOCK_THREAD(t);
2336 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2338 /* Slot is empty - leave it locked and caller will unlock */
2339 thread = t;
2340 break;
2343 /* Finished examining slot - no longer busy - unlock on multicore */
2344 UNLOCK_THREAD(t);
2347 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2348 not accesible to them yet */
2349 return thread;
2353 /*---------------------------------------------------------------------------
2354 * Place the current core in idle mode - woken up on interrupt or wake
2355 * request from another core.
2356 *---------------------------------------------------------------------------
2358 void core_idle(void)
2360 IF_COP( const unsigned int core = CURRENT_CORE; )
2361 disable_irq();
2362 core_sleep(IF_COP(core));
2365 /*---------------------------------------------------------------------------
2366 * Create a thread. If using a dual core architecture, specify which core to
2367 * start the thread on.
2369 * Return ID if context area could be allocated, else NULL.
2370 *---------------------------------------------------------------------------
2372 struct thread_entry*
2373 create_thread(void (*function)(void), void* stack, size_t stack_size,
2374 unsigned flags, const char *name
2375 IF_PRIO(, int priority)
2376 IF_COP(, unsigned int core))
2378 unsigned int i;
2379 unsigned int stack_words;
2380 uintptr_t stackptr, stackend;
2381 struct thread_entry *thread;
2382 unsigned state;
2383 int oldlevel;
2385 thread = find_empty_thread_slot();
2386 if (thread == NULL)
2388 return NULL;
2391 oldlevel = disable_irq_save();
2393 /* Munge the stack to make it easy to spot stack overflows */
2394 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2395 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2396 stack_size = stackend - stackptr;
2397 stack_words = stack_size / sizeof (uintptr_t);
2399 for (i = 0; i < stack_words; i++)
2401 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2404 /* Store interesting information */
2405 thread->name = name;
2406 thread->stack = (uintptr_t *)stackptr;
2407 thread->stack_size = stack_size;
2408 thread->queue = NULL;
2409 #ifdef HAVE_WAKEUP_EXT_CB
2410 thread->wakeup_ext_cb = NULL;
2411 #endif
2412 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2413 thread->cpu_boost = 0;
2414 #endif
2415 #ifdef HAVE_PRIORITY_SCHEDULING
2416 memset(&thread->pdist, 0, sizeof(thread->pdist));
2417 thread->blocker = NULL;
2418 thread->base_priority = priority;
2419 thread->priority = priority;
2420 thread->skip_count = priority;
2421 prio_add_entry(&thread->pdist, priority);
2422 #endif
2424 #if NUM_CORES > 1
2425 thread->core = core;
2427 /* Writeback stack munging or anything else before starting */
2428 if (core != CURRENT_CORE)
2430 flush_icache();
2432 #endif
2434 /* Thread is not on any timeout list but be a bit paranoid */
2435 thread->tmo.prev = NULL;
2437 state = (flags & CREATE_THREAD_FROZEN) ?
2438 STATE_FROZEN : STATE_RUNNING;
2440 thread->context.sp = (typeof (thread->context.sp))stackend;
2442 /* Load the thread's context structure with needed startup information */
2443 THREAD_STARTUP_INIT(core, thread, function);
2445 thread->state = state;
2447 if (state == STATE_RUNNING)
2448 core_schedule_wakeup(thread);
2450 UNLOCK_THREAD(thread);
2452 restore_irq(oldlevel);
2454 return thread;
2457 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2458 /*---------------------------------------------------------------------------
2459 * Change the boost state of a thread boosting or unboosting the CPU
2460 * as required.
2461 *---------------------------------------------------------------------------
2463 static inline void boost_thread(struct thread_entry *thread, bool boost)
2465 if ((thread->cpu_boost != 0) != boost)
2467 thread->cpu_boost = boost;
2468 cpu_boost(boost);
2472 void trigger_cpu_boost(void)
2474 struct thread_entry *current = cores[CURRENT_CORE].running;
2475 boost_thread(current, true);
2478 void cancel_cpu_boost(void)
2480 struct thread_entry *current = cores[CURRENT_CORE].running;
2481 boost_thread(current, false);
2483 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2485 /*---------------------------------------------------------------------------
2486 * Block the current thread until another thread terminates. A thread may
2487 * wait on itself to terminate which prevents it from running again and it
2488 * will need to be killed externally.
2489 * Parameter is the ID as returned from create_thread().
2490 *---------------------------------------------------------------------------
2492 void thread_wait(struct thread_entry *thread)
2494 struct thread_entry *current = cores[CURRENT_CORE].running;
2496 if (thread == NULL)
2497 thread = current;
2499 /* Lock thread-as-waitable-object lock */
2500 corelock_lock(&thread->waiter_cl);
2502 /* Be sure it hasn't been killed yet */
2503 if (thread->state != STATE_KILLED)
2505 IF_COP( current->obj_cl = &thread->waiter_cl; )
2506 current->bqp = &thread->queue;
2508 disable_irq();
2509 block_thread(current);
2511 corelock_unlock(&thread->waiter_cl);
2513 switch_thread();
2514 return;
2517 corelock_unlock(&thread->waiter_cl);
2520 /*---------------------------------------------------------------------------
2521 * Exit the current thread. The Right Way to Do Things (TM).
2522 *---------------------------------------------------------------------------
2524 void thread_exit(void)
2526 const unsigned int core = CURRENT_CORE;
2527 struct thread_entry *current = cores[core].running;
2529 /* Cancel CPU boost if any */
2530 cancel_cpu_boost();
2532 disable_irq();
2534 corelock_lock(&current->waiter_cl);
2535 LOCK_THREAD(current);
2537 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2538 if (current->name == THREAD_DESTRUCT)
2540 /* Thread being killed - become a waiter */
2541 UNLOCK_THREAD(current);
2542 corelock_unlock(&current->waiter_cl);
2543 thread_wait(current);
2544 THREAD_PANICF("thread_exit->WK:*R", current);
2546 #endif
2548 #ifdef HAVE_PRIORITY_SCHEDULING
2549 check_for_obj_waiters("thread_exit", current);
2550 #endif
2552 if (current->tmo.prev != NULL)
2554 /* Cancel pending timeout list removal */
2555 remove_from_list_tmo(current);
2558 /* Switch tasks and never return */
2559 block_thread_on_l(current, STATE_KILLED);
2561 #if NUM_CORES > 1
2562 /* Switch to the idle stack if not on the main core (where "main"
2563 * runs) - we can hope gcc doesn't need the old stack beyond this
2564 * point. */
2565 if (core != CPU)
2567 switch_to_idle_stack(core);
2570 flush_icache();
2571 #endif
2572 current->name = NULL;
2574 /* Signal this thread */
2575 thread_queue_wake(&current->queue);
2576 corelock_unlock(&current->waiter_cl);
2577 /* Slot must be unusable until thread is really gone */
2578 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2579 switch_thread();
2580 /* This should never and must never be reached - if it is, the
2581 * state is corrupted */
2582 THREAD_PANICF("thread_exit->K:*R", current);
2585 #ifdef ALLOW_REMOVE_THREAD
2586 /*---------------------------------------------------------------------------
2587 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2588 * normal programs.
2590 * Parameter is the ID as returned from create_thread().
2592 * Use with care on threads that are not under careful control as this may
2593 * leave various objects in an undefined state.
2594 *---------------------------------------------------------------------------
2596 void remove_thread(struct thread_entry *thread)
2598 #if NUM_CORES > 1
2599 /* core is not constant here because of core switching */
2600 unsigned int core = CURRENT_CORE;
2601 unsigned int old_core = NUM_CORES;
2602 struct corelock *ocl = NULL;
2603 #else
2604 const unsigned int core = CURRENT_CORE;
2605 #endif
2606 struct thread_entry *current = cores[core].running;
2608 unsigned state;
2609 int oldlevel;
2611 if (thread == NULL)
2612 thread = current;
2614 if (thread == current)
2615 thread_exit(); /* Current thread - do normal exit */
2617 oldlevel = disable_irq_save();
2619 corelock_lock(&thread->waiter_cl);
2620 LOCK_THREAD(thread);
2622 state = thread->state;
2624 if (state == STATE_KILLED)
2626 goto thread_killed;
2629 #if NUM_CORES > 1
2630 if (thread->name == THREAD_DESTRUCT)
2632 /* Thread being killed - become a waiter */
2633 UNLOCK_THREAD(thread);
2634 corelock_unlock(&thread->waiter_cl);
2635 restore_irq(oldlevel);
2636 thread_wait(thread);
2637 return;
2640 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2642 #ifdef HAVE_PRIORITY_SCHEDULING
2643 check_for_obj_waiters("remove_thread", thread);
2644 #endif
2646 if (thread->core != core)
2648 /* Switch cores and safely extract the thread there */
2649 /* Slot HAS to be unlocked or a deadlock could occur which means other
2650 * threads have to be guided into becoming thread waiters if they
2651 * attempt to remove it. */
2652 unsigned int new_core = thread->core;
2654 corelock_unlock(&thread->waiter_cl);
2656 UNLOCK_THREAD(thread);
2657 restore_irq(oldlevel);
2659 old_core = switch_core(new_core);
2661 oldlevel = disable_irq_save();
2663 corelock_lock(&thread->waiter_cl);
2664 LOCK_THREAD(thread);
2666 state = thread->state;
2667 core = new_core;
2668 /* Perform the extraction and switch ourselves back to the original
2669 processor */
2671 #endif /* NUM_CORES > 1 */
2673 if (thread->tmo.prev != NULL)
2675 /* Clean thread off the timeout list if a timeout check hasn't
2676 * run yet */
2677 remove_from_list_tmo(thread);
2680 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2681 /* Cancel CPU boost if any */
2682 boost_thread(thread, false);
2683 #endif
2685 IF_COP( retry_state: )
2687 switch (state)
2689 case STATE_RUNNING:
2690 RTR_LOCK(core);
2691 /* Remove thread from ready to run tasks */
2692 remove_from_list_l(&cores[core].running, thread);
2693 rtr_subtract_entry(core, thread->priority);
2694 RTR_UNLOCK(core);
2695 break;
2696 case STATE_BLOCKED:
2697 case STATE_BLOCKED_W_TMO:
2698 /* Remove thread from the queue it's blocked on - including its
2699 * own if waiting there */
2700 #if NUM_CORES > 1
2701 if (&thread->waiter_cl != thread->obj_cl)
2703 ocl = thread->obj_cl;
2705 if (corelock_try_lock(ocl) == 0)
2707 UNLOCK_THREAD(thread);
2708 corelock_lock(ocl);
2709 LOCK_THREAD(thread);
2711 if (thread->state != state)
2713 /* Something woke the thread */
2714 state = thread->state;
2715 corelock_unlock(ocl);
2716 goto retry_state;
2720 #endif
2721 remove_from_list_l(thread->bqp, thread);
2723 #ifdef HAVE_WAKEUP_EXT_CB
2724 if (thread->wakeup_ext_cb != NULL)
2725 thread->wakeup_ext_cb(thread);
2726 #endif
2728 #ifdef HAVE_PRIORITY_SCHEDULING
2729 if (thread->blocker != NULL)
2731 /* Remove thread's priority influence from its chain */
2732 wakeup_priority_protocol_release(thread);
2734 #endif
2736 #if NUM_CORES > 1
2737 if (ocl != NULL)
2738 corelock_unlock(ocl);
2739 #endif
2740 break;
2741 /* Otherwise thread is frozen and hasn't run yet */
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(struct thread_entry *thread, int priority)
2778 int old_base_priority = -1;
2780 /* A little safety measure */
2781 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2782 return -1;
2784 if (thread == NULL)
2785 thread = cores[CURRENT_CORE].running;
2787 /* Thread could be on any list and therefore on an interrupt accessible
2788 one - disable interrupts */
2789 int oldlevel = disable_irq_save();
2791 LOCK_THREAD(thread);
2793 /* Make sure it's not killed */
2794 if (thread->state != STATE_KILLED)
2796 int old_priority = thread->priority;
2798 old_base_priority = thread->base_priority;
2799 thread->base_priority = priority;
2801 prio_move_entry(&thread->pdist, old_base_priority, priority);
2802 priority = find_first_set_bit(thread->pdist.mask);
2804 if (old_priority == priority)
2806 /* No priority change - do nothing */
2808 else if (thread->state == STATE_RUNNING)
2810 /* This thread is running - change location on the run
2811 * queue. No transitive inheritance needed. */
2812 set_running_thread_priority(thread, priority);
2814 else
2816 thread->priority = priority;
2818 if (thread->blocker != NULL)
2820 /* Bubble new priority down the chain */
2821 struct blocker *bl = thread->blocker; /* Blocker struct */
2822 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2823 struct thread_entry * const tstart = thread; /* Initial thread */
2824 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2826 for (;;)
2828 struct thread_entry *next; /* Next thread to check */
2829 int bl_pr; /* Highest blocked thread */
2830 int queue_pr; /* New highest blocked thread */
2831 #if NUM_CORES > 1
2832 /* Owner can change but thread cannot be dislodged - thread
2833 * may not be the first in the queue which allows other
2834 * threads ahead in the list to be given ownership during the
2835 * operation. If thread is next then the waker will have to
2836 * wait for us and the owner of the object will remain fixed.
2837 * If we successfully grab the owner -- which at some point
2838 * is guaranteed -- then the queue remains fixed until we
2839 * pass by. */
2840 for (;;)
2842 LOCK_THREAD(bl_t);
2844 /* Double-check the owner - retry if it changed */
2845 if (bl->thread == bl_t)
2846 break;
2848 UNLOCK_THREAD(bl_t);
2849 bl_t = bl->thread;
2851 #endif
2852 bl_pr = bl->priority;
2854 if (highest > bl_pr)
2855 break; /* Object priority won't change */
2857 /* This will include the thread being set */
2858 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2860 if (queue_pr == bl_pr)
2861 break; /* Object priority not changing */
2863 /* Update thread boost for this object */
2864 bl->priority = queue_pr;
2865 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2866 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2868 if (bl_t->priority == bl_pr)
2869 break; /* Blocking thread priority not changing */
2871 if (bl_t->state == STATE_RUNNING)
2873 /* Thread not blocked - we're done */
2874 set_running_thread_priority(bl_t, bl_pr);
2875 break;
2878 bl_t->priority = bl_pr;
2879 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2881 if (bl == NULL)
2882 break; /* End of chain */
2884 next = bl->thread;
2886 if (next == tstart)
2887 break; /* Full-circle */
2889 UNLOCK_THREAD(thread);
2891 thread = bl_t;
2892 bl_t = next;
2893 } /* for (;;) */
2895 UNLOCK_THREAD(bl_t);
2900 UNLOCK_THREAD(thread);
2902 restore_irq(oldlevel);
2904 return old_base_priority;
2907 /*---------------------------------------------------------------------------
2908 * Returns the current base priority for a thread.
2909 *---------------------------------------------------------------------------
2911 int thread_get_priority(struct thread_entry *thread)
2913 /* Simple, quick probe. */
2914 if (thread == NULL)
2915 thread = cores[CURRENT_CORE].running;
2917 return thread->base_priority;
2919 #endif /* HAVE_PRIORITY_SCHEDULING */
2921 /*---------------------------------------------------------------------------
2922 * Starts a frozen thread - similar semantics to wakeup_thread except that
2923 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2924 * virtue of the slot having a state of STATE_FROZEN.
2925 *---------------------------------------------------------------------------
2927 void thread_thaw(struct thread_entry *thread)
2929 int oldlevel = disable_irq_save();
2930 LOCK_THREAD(thread);
2932 if (thread->state == STATE_FROZEN)
2933 core_schedule_wakeup(thread);
2935 UNLOCK_THREAD(thread);
2936 restore_irq(oldlevel);
2939 /*---------------------------------------------------------------------------
2940 * Return the ID of the currently executing thread.
2941 *---------------------------------------------------------------------------
2943 struct thread_entry * thread_get_current(void)
2945 return cores[CURRENT_CORE].running;
2948 #if NUM_CORES > 1
2949 /*---------------------------------------------------------------------------
2950 * Switch the processor that the currently executing thread runs on.
2951 *---------------------------------------------------------------------------
2953 unsigned int switch_core(unsigned int new_core)
2955 const unsigned int core = CURRENT_CORE;
2956 struct thread_entry *current = cores[core].running;
2958 if (core == new_core)
2960 /* No change - just return same core */
2961 return core;
2964 int oldlevel = disable_irq_save();
2965 LOCK_THREAD(current);
2967 if (current->name == THREAD_DESTRUCT)
2969 /* Thread being killed - deactivate and let process complete */
2970 UNLOCK_THREAD(current);
2971 restore_irq(oldlevel);
2972 thread_wait(current);
2973 /* Should never be reached */
2974 THREAD_PANICF("switch_core->D:*R", current);
2977 /* Get us off the running list for the current core */
2978 RTR_LOCK(core);
2979 remove_from_list_l(&cores[core].running, current);
2980 rtr_subtract_entry(core, current->priority);
2981 RTR_UNLOCK(core);
2983 /* Stash return value (old core) in a safe place */
2984 current->retval = core;
2986 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2987 * the other core will likely attempt a removal from the wrong list! */
2988 if (current->tmo.prev != NULL)
2990 remove_from_list_tmo(current);
2993 /* Change the core number for this thread slot */
2994 current->core = new_core;
2996 /* Do not use core_schedule_wakeup here since this will result in
2997 * the thread starting to run on the other core before being finished on
2998 * this one. Delay the list unlock to keep the other core stuck
2999 * until this thread is ready. */
3000 RTR_LOCK(new_core);
3002 rtr_add_entry(new_core, current->priority);
3003 add_to_list_l(&cores[new_core].running, current);
3005 /* Make a callback into device-specific code, unlock the wakeup list so
3006 * that execution may resume on the new core, unlock our slot and finally
3007 * restore the interrupt level */
3008 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3009 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3010 cores[core].block_task = current;
3012 UNLOCK_THREAD(current);
3014 /* Alert other core to activity */
3015 core_wake(new_core);
3017 /* Do the stack switching, cache_maintenence and switch_thread call -
3018 requires native code */
3019 switch_thread_core(core, current);
3021 /* Finally return the old core to caller */
3022 return current->retval;
3024 #endif /* NUM_CORES > 1 */
3026 /*---------------------------------------------------------------------------
3027 * Initialize threading API. This assumes interrupts are not yet enabled. On
3028 * multicore setups, no core is allowed to proceed until create_thread calls
3029 * are safe to perform.
3030 *---------------------------------------------------------------------------
3032 void init_threads(void)
3034 const unsigned int core = CURRENT_CORE;
3035 struct thread_entry *thread;
3037 /* CPU will initialize first and then sleep */
3038 thread = find_empty_thread_slot();
3040 if (thread == NULL)
3042 /* WTF? There really must be a slot available at this stage.
3043 * This can fail if, for example, .bss isn't zero'ed out by the loader
3044 * or threads is in the wrong section. */
3045 THREAD_PANICF("init_threads->no slot", NULL);
3048 /* Initialize initially non-zero members of core */
3049 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3051 /* Initialize initially non-zero members of slot */
3052 UNLOCK_THREAD(thread); /* No sync worries yet */
3053 thread->name = main_thread_name;
3054 thread->state = STATE_RUNNING;
3055 IF_COP( thread->core = core; )
3056 #ifdef HAVE_PRIORITY_SCHEDULING
3057 corelock_init(&cores[core].rtr_cl);
3058 thread->base_priority = PRIORITY_USER_INTERFACE;
3059 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3060 thread->priority = PRIORITY_USER_INTERFACE;
3061 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3062 #endif
3063 corelock_init(&thread->waiter_cl);
3064 corelock_init(&thread->slot_cl);
3066 add_to_list_l(&cores[core].running, thread);
3068 if (core == CPU)
3070 thread->stack = stackbegin;
3071 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3072 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3073 /* Wait for other processors to finish their inits since create_thread
3074 * isn't safe to call until the kernel inits are done. The first
3075 * threads created in the system must of course be created by CPU. */
3076 core_thread_init(CPU);
3078 else
3080 /* Initial stack is the idle stack */
3081 thread->stack = idle_stacks[core];
3082 thread->stack_size = IDLE_STACK_SIZE;
3083 /* After last processor completes, it should signal all others to
3084 * proceed or may signal the next and call thread_exit(). The last one
3085 * to finish will signal CPU. */
3086 core_thread_init(core);
3087 /* Other cores do not have a main thread - go idle inside switch_thread
3088 * until a thread can run on the core. */
3089 thread_exit();
3090 #endif /* NUM_CORES */
3094 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3095 #if NUM_CORES == 1
3096 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3097 #else
3098 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3099 #endif
3101 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3102 unsigned int i;
3103 int usage = 0;
3105 for (i = 0; i < stack_words; i++)
3107 if (stackptr[i] != DEADBEEF)
3109 usage = ((stack_words - i) * 100) / stack_words;
3110 break;
3114 return usage;
3117 /*---------------------------------------------------------------------------
3118 * Returns the maximum percentage of stack a thread ever used while running.
3119 * NOTE: Some large buffer allocations that don't use enough the buffer to
3120 * overwrite stackptr[0] will not be seen.
3121 *---------------------------------------------------------------------------
3123 int thread_stack_usage(const struct thread_entry *thread)
3125 return stack_usage(thread->stack, thread->stack_size);
3128 #if NUM_CORES > 1
3129 /*---------------------------------------------------------------------------
3130 * Returns the maximum percentage of the core's idle stack ever used during
3131 * runtime.
3132 *---------------------------------------------------------------------------
3134 int idle_stack_usage(unsigned int core)
3136 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3138 #endif
3140 /*---------------------------------------------------------------------------
3141 * Fills in the buffer with the specified thread's name. If the name is NULL,
3142 * empty, or the thread is in destruct state a formatted ID is written
3143 * instead.
3144 *---------------------------------------------------------------------------
3146 void thread_get_name(char *buffer, int size,
3147 struct thread_entry *thread)
3149 if (size <= 0)
3150 return;
3152 *buffer = '\0';
3154 if (thread)
3156 /* Display thread name if one or ID if none */
3157 const char *name = thread->name;
3158 const char *fmt = "%s";
3159 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3161 name = (const char *)thread;
3162 fmt = "%08lX";
3164 snprintf(buffer, size, fmt, name);