No bufclosing of handles after track change
[Rockbox.git] / firmware / thread.c
blob896cc0fb3dc4de80babbb2002be8a96485b29254
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2002 by Ulf Ralberg
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include "config.h"
20 #include <stdbool.h>
21 #include "thread.h"
22 #include "panic.h"
23 #include "sprintf.h"
24 #include "system.h"
25 #include "kernel.h"
26 #include "cpu.h"
27 #include "string.h"
28 #ifdef RB_PROFILE
29 #include <profile.h>
30 #endif
32 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
33 #ifdef DEBUG
34 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
35 #else
36 #define THREAD_EXTRA_CHECKS 0
37 #endif
39 /**
40 * General locking order to guarantee progress. Order must be observed but
41 * all stages are not nescessarily obligatory. Going from 1) to 3) is
42 * perfectly legal.
44 * 1) IRQ
45 * This is first because of the likelyhood of having an interrupt occur that
46 * also accesses one of the objects farther down the list. Any non-blocking
47 * synchronization done may already have a lock on something during normal
48 * execution and if an interrupt handler running on the same processor as
49 * the one that has the resource locked were to attempt to access the
50 * resource, the interrupt handler would wait forever waiting for an unlock
51 * that will never happen. There is no danger if the interrupt occurs on
52 * a different processor because the one that has the lock will eventually
53 * unlock and the other processor's handler may proceed at that time. Not
54 * nescessary when the resource in question is definitely not available to
55 * interrupt handlers.
57 * 2) Kernel Object
58 * 1) May be needed beforehand if the kernel object allows dual-use such as
59 * event queues. The kernel object must have a scheme to protect itself from
60 * access by another processor and is responsible for serializing the calls
61 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
62 * other. If a thread blocks on an object it must fill-in the blk_ops members
63 * for its core to unlock _after_ the thread's context has been saved and the
64 * unlocking will be done in reverse from this heirarchy.
66 * 3) Thread Slot
67 * This locks access to the thread's slot such that its state cannot be
68 * altered by another processor when a state change is in progress such as
69 * when it is in the process of going on a blocked list. An attempt to wake
70 * a thread while it is still blocking will likely desync its state with
71 * the other resources used for that state.
73 * 4) Lists
74 * Usually referring to a list (aka. queue) that a thread will be blocking
75 * on that belongs to some object and is shareable amongst multiple
76 * processors. Parts of the scheduler may have access to them without actually
77 * locking the kernel object such as when a thread is blocked with a timeout
78 * (such as calling queue_wait_w_tmo). Of course the kernel object also gets
79 * it lists locked when the thread blocks so that all object list access is
80 * synchronized. Failure to do so would corrupt the list links.
82 * 5) Core Lists
83 * These lists are specific to a particular processor core and are accessible
84 * by all processor cores and interrupt handlers. They are used when an
85 * operation may only be performed by the thread's own core in a normal
86 * execution context. The wakeup list is the prime example where a thread
87 * may be added by any means and the thread's own core will remove it from
88 * the wakeup list and put it on the running list (which is only ever
89 * accessible by its own processor).
91 #define DEADBEEF ((unsigned int)0xdeadbeef)
92 /* Cast to the the machine int type, whose size could be < 4. */
93 struct core_entry cores[NUM_CORES] IBSS_ATTR;
94 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
95 #ifdef HAVE_SCHEDULER_BOOSTCTRL
96 static int boosted_threads IBSS_ATTR;
97 #endif
99 static const char main_thread_name[] = "main";
100 extern int stackbegin[];
101 extern int stackend[];
103 /* core_sleep procedure to implement for any CPU to ensure an asychronous wakup
104 * never results in requiring a wait until the next tick (up to 10000uS!). Likely
105 * requires assembly and careful instruction ordering. Multicore requires
106 * carefully timed sections in order to have synchronization without locking of
107 * any sort.
109 * 1) Disable all interrupts (FIQ and IRQ for ARM for instance)
110 * 2) Check *waking == NULL.
111 * 3) *waking not NULL? Goto step 7.
112 * 4) On multicore, stay awake if directed to do so by another. If so, goto step 7.
113 * 5) If processor requires, atomically reenable interrupts and perform step 6.
114 * 6) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000 on Coldfire)
115 * goto step 8.
116 * 7) Reenable interrupts.
117 * 8) Exit procedure.
119 static inline void core_sleep(
120 IF_COP(unsigned int core,) struct thread_entry **waking)
121 __attribute__((always_inline));
123 static void check_tmo_threads(void)
124 __attribute__((noinline));
126 static inline void block_thread_on_l(
127 struct thread_queue *list, struct thread_entry *thread, unsigned state)
128 __attribute__((always_inline));
130 static inline void block_thread_on_l_no_listlock(
131 struct thread_entry **list, struct thread_entry *thread, unsigned state)
132 __attribute__((always_inline));
134 static inline void _block_thread_on_l(
135 struct thread_queue *list, struct thread_entry *thread,
136 unsigned state IF_SWCL(, const bool single))
137 __attribute__((always_inline));
139 IF_SWCL(static inline) struct thread_entry * _wakeup_thread(
140 struct thread_queue *list IF_SWCL(, const bool nolock))
141 __attribute__((IFN_SWCL(noinline) IF_SWCL(always_inline)));
143 IF_SWCL(static inline) void _block_thread(
144 struct thread_queue *list IF_SWCL(, const bool nolock))
145 __attribute__((IFN_SWCL(noinline) IF_SWCL(always_inline)));
147 static void add_to_list_tmo(struct thread_entry *thread)
148 __attribute__((noinline));
150 static void core_schedule_wakeup(struct thread_entry *thread)
151 __attribute__((noinline));
153 static inline void core_perform_wakeup(IF_COP_VOID(unsigned int core))
154 __attribute__((always_inline));
156 static inline void run_blocking_ops(
157 IF_COP_VOID(unsigned int core, struct thread_entry *thread))
158 __attribute__((always_inline));
160 static void thread_stkov(struct thread_entry *thread)
161 __attribute__((noinline));
163 static inline void store_context(void* addr)
164 __attribute__((always_inline));
166 static inline void load_context(const void* addr)
167 __attribute__((always_inline));
169 void switch_thread(struct thread_entry *old)
170 __attribute__((noinline));
173 /****************************************************************************
174 * Processor-specific section
177 #if defined(CPU_ARM)
178 /*---------------------------------------------------------------------------
179 * Start the thread running and terminate it if it returns
180 *---------------------------------------------------------------------------
182 static void start_thread(void) __attribute__((naked,used));
183 static void start_thread(void)
185 /* r0 = context */
186 asm volatile (
187 "ldr sp, [r0, #32] \n" /* Load initial sp */
188 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
189 "mov r1, #0 \n" /* Mark thread as running */
190 "str r1, [r0, #40] \n"
191 #if NUM_CORES > 1
192 "ldr r0, =invalidate_icache \n" /* Invalidate this core's cache. */
193 "mov lr, pc \n" /* This could be the first entry into */
194 "bx r0 \n" /* plugin or codec code for this core. */
195 #endif
196 "mov lr, pc \n" /* Call thread function */
197 "bx r4 \n"
198 "mov r0, #0 \n" /* remove_thread(NULL) */
199 "ldr pc, =remove_thread \n"
200 ".ltorg \n" /* Dump constant pool */
201 ); /* No clobber list - new thread doesn't care */
204 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
205 * slot, and thread function pointer in context.start. See load_context for
206 * what happens when thread is initially going to run. */
207 #define THREAD_STARTUP_INIT(core, thread, function) \
208 ({ (thread)->context.r[0] = (unsigned int)&(thread)->context, \
209 (thread)->context.r[1] = (unsigned int)start_thread, \
210 (thread)->context.start = (void *)function; })
212 /*---------------------------------------------------------------------------
213 * Store non-volatile context.
214 *---------------------------------------------------------------------------
216 static inline void store_context(void* addr)
218 asm volatile(
219 "stmia %0, { r4-r11, sp, lr } \n"
220 : : "r" (addr)
224 /*---------------------------------------------------------------------------
225 * Load non-volatile context.
226 *---------------------------------------------------------------------------
228 static inline void load_context(const void* addr)
230 asm volatile(
231 "ldr r0, [%0, #40] \n" /* Load start pointer */
232 "cmp r0, #0 \n" /* Check for NULL */
233 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
234 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
235 : : "r" (addr) : "r0" /* only! */
239 #if defined (CPU_PP)
241 #if NUM_CORES > 1
242 extern int cpu_idlestackbegin[];
243 extern int cpu_idlestackend[];
244 extern int cop_idlestackbegin[];
245 extern int cop_idlestackend[];
246 static int * const idle_stacks[NUM_CORES] NOCACHEDATA_ATTR =
248 [CPU] = cpu_idlestackbegin,
249 [COP] = cop_idlestackbegin
251 #endif /* NUM_CORES */
253 #if CONFIG_CORELOCK == SW_CORELOCK
254 /* Software core locks using Peterson's mutual exclusion algorithm */
256 /*---------------------------------------------------------------------------
257 * Initialize the corelock structure.
258 *---------------------------------------------------------------------------
260 void corelock_init(struct corelock *cl)
262 memset(cl, 0, sizeof (*cl));
265 #if 1 /* Assembly locks to minimize overhead */
266 /*---------------------------------------------------------------------------
267 * Wait for the corelock to become free and acquire it when it does.
268 *---------------------------------------------------------------------------
270 void corelock_lock(struct corelock *cl) __attribute__((naked));
271 void corelock_lock(struct corelock *cl)
273 asm volatile (
274 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
275 "ldrb r1, [r1] \n"
276 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
277 "and r2, r1, #1 \n" /* r2 = othercore */
278 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
279 "1: \n"
280 "ldrb r3, [r0, r2] \n" /* cl->myl[othercore] == 0 ? */
281 "cmp r3, #0 \n"
282 "ldrneb r3, [r0, #2] \n" /* || cl->turn == core ? */
283 "cmpne r3, r1, lsr #7 \n"
284 "bxeq lr \n" /* yes? lock acquired */
285 "b 1b \n" /* keep trying */
286 : : "i"(&PROCESSOR_ID)
288 (void)cl;
291 /*---------------------------------------------------------------------------
292 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
293 *---------------------------------------------------------------------------
295 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
296 int corelock_try_lock(struct corelock *cl)
298 asm volatile (
299 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
300 "ldrb r1, [r1] \n"
301 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
302 "and r2, r1, #1 \n" /* r2 = othercore */
303 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
304 "1: \n"
305 "ldrb r3, [r0, r2] \n" /* cl->myl[othercore] == 0 ? */
306 "cmp r3, #0 \n"
307 "ldrneb r3, [r0, #2] \n" /* || cl->turn == core? */
308 "cmpne r3, r1, lsr #7 \n"
309 "moveq r0, #1 \n" /* yes? lock acquired */
310 "bxeq lr \n"
311 "mov r2, #0 \n" /* cl->myl[core] = 0 */
312 "strb r2, [r0, r1, lsr #7] \n"
313 "mov r0, r2 \n"
314 "bx lr \n" /* acquisition failed */
315 : : "i"(&PROCESSOR_ID)
318 return 0;
319 (void)cl;
322 /*---------------------------------------------------------------------------
323 * Release ownership of the corelock
324 *---------------------------------------------------------------------------
326 void corelock_unlock(struct corelock *cl) __attribute__((naked));
327 void corelock_unlock(struct corelock *cl)
329 asm volatile (
330 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
331 "ldrb r1, [r1] \n"
332 "mov r2, #0 \n" /* cl->myl[core] = 0 */
333 "strb r2, [r0, r1, lsr #7] \n"
334 "bx lr \n"
335 : : "i"(&PROCESSOR_ID)
337 (void)cl;
339 #else /* C versions for reference */
340 /*---------------------------------------------------------------------------
341 * Wait for the corelock to become free and aquire it when it does.
342 *---------------------------------------------------------------------------
344 void corelock_lock(struct corelock *cl)
346 const unsigned int core = CURRENT_CORE;
347 const unsigned int othercore = 1 - core;
349 cl->myl[core] = core;
350 cl->turn = othercore;
352 for (;;)
354 if (cl->myl[othercore] == 0 || cl->turn == core)
355 break;
359 /*---------------------------------------------------------------------------
360 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
361 *---------------------------------------------------------------------------
363 int corelock_try_lock(struct corelock *cl)
365 const unsigned int core = CURRENT_CORE;
366 const unsigned int othercore = 1 - core;
368 cl->myl[core] = core;
369 cl->turn = othercore;
371 if (cl->myl[othercore] == 0 || cl->turn == core)
373 return 1;
376 cl->myl[core] = 0;
377 return 0;
380 /*---------------------------------------------------------------------------
381 * Release ownership of the corelock
382 *---------------------------------------------------------------------------
384 void corelock_unlock(struct corelock *cl)
386 cl->myl[CURRENT_CORE] = 0;
388 #endif /* ASM / C selection */
390 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
392 /*---------------------------------------------------------------------------
393 * Put core in a power-saving state if waking list wasn't repopulated and if
394 * no other core requested a wakeup for it to perform a task.
395 *---------------------------------------------------------------------------
397 static inline void core_sleep(IF_COP(unsigned int core,) struct thread_entry **waking)
399 #if NUM_CORES > 1
400 #ifdef CPU_PP502x
401 #if 1
402 /* Disabling IRQ and FIQ is important to making the fixed-time sequence
403 * non-interruptable */
404 asm volatile (
405 "mrs r2, cpsr \n" /* Disable IRQ, FIQ */
406 "orr r2, r2, #0xc0 \n"
407 "msr cpsr_c, r2 \n"
408 "mov r0, #4 \n" /* r0 = 0x4 << core */
409 "mov r0, r0, lsl %[c] \n"
410 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
411 "ldr r1, [%[waking]] \n" /* *waking == NULL ? */
412 "cmp r1, #0 \n"
413 "ldreq r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
414 "tsteq r1, r0, lsl #2 \n"
415 "moveq r1, #0x80000000 \n" /* Then sleep */
416 "streq r1, [%[ctl], %[c], lsl #2] \n"
417 "moveq r1, #0 \n" /* Clear control reg */
418 "streq r1, [%[ctl], %[c], lsl #2] \n"
419 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
420 "str r1, [%[mbx], #8] \n"
421 "1: \n" /* Wait for wake procedure to finish */
422 "ldr r1, [%[mbx], #0] \n"
423 "tst r1, r0, lsr #2 \n"
424 "bne 1b \n"
425 "bic r2, r2, #0xc0 \n" /* Enable interrupts */
426 "msr cpsr_c, r2 \n"
428 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
429 [waking]"r"(waking), [c]"r"(core)
430 : "r0", "r1", "r2");
431 #else /* C version for reference */
432 /* Disable IRQ, FIQ */
433 set_interrupt_status(IRQ_FIQ_DISABLED, IRQ_FIQ_STATUS);
435 /* Signal intent to sleep */
436 MBX_MSG_SET = 0x4 << core;
438 /* Something waking or other processor intends to wake us? */
439 if (*waking == NULL && (MBX_MSG_STAT & (0x10 << core)) == 0)
441 PROC_CTL(core) = PROC_SLEEP; nop; /* Snooze */
442 PROC_CTL(core) = 0; /* Clear control reg */
445 /* Signal wake - clear wake flag */
446 MBX_MSG_CLR = 0x14 << core;
448 /* Wait for other processor to finish wake procedure */
449 while (MBX_MSG_STAT & (0x1 << core));
451 /* Enable IRQ, FIQ */
452 set_interrupt_status(IRQ_FIQ_ENABLED, IRQ_FIQ_STATUS);
453 #endif /* ASM/C selection */
454 #else
455 /* TODO: PP5002 */
456 #endif /* CONFIG_CPU == */
457 #else
458 set_interrupt_status(IRQ_FIQ_DISABLED, IRQ_FIQ_STATUS);
459 if (*waking == NULL)
461 PROC_CTL(IF_COP_CORE(core)) = PROC_SLEEP;
463 set_interrupt_status(IRQ_FIQ_ENABLED, IRQ_FIQ_STATUS);
464 #endif /* NUM_CORES */
467 /*---------------------------------------------------------------------------
468 * Wake another processor core that is sleeping or prevent it from doing so
469 * if it was already destined. FIQ, IRQ should be disabled before calling.
470 *---------------------------------------------------------------------------
472 void core_wake(IF_COP_VOID(unsigned int othercore))
474 #if NUM_CORES == 1
475 /* No wakey - core already wakey */
476 #elif defined (CPU_PP502x)
477 #if 1
478 /* avoid r0 since that contains othercore */
479 asm volatile (
480 "mrs r3, cpsr \n" /* Disable IRQ */
481 "orr r1, r3, #0x80 \n"
482 "msr cpsr_c, r1 \n"
483 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
484 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
485 "str r2, [%[mbx], #4] \n"
486 "1: \n" /* If it intends to sleep, let it first */
487 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
488 "eor r1, r1, #0xc \n"
489 "tst r1, r2, lsr #2 \n"
490 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
491 "tsteq r1, #0x80000000 \n"
492 "beq 1b \n" /* Wait for sleep or wake */
493 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
494 "movne r1, #0x0 \n"
495 "strne r1, [%[ctl], %[oc], lsl #2] \n"
496 "mov r1, r2, lsr #4 \n"
497 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
498 "msr cpsr_c, r3 \n" /* Restore int status */
500 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE), [oc]"r" (othercore)
501 : "r1", "r2", "r3");
502 #else /* C version for reference */
503 /* Disable interrupts - avoid reentrancy from the tick */
504 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
506 /* Signal intent to wake other processor - set stay awake */
507 MBX_MSG_SET = 0x11 << othercore;
509 /* If it intends to sleep, wait until it does or aborts */
510 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
511 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
513 /* If sleeping, wake it up */
514 if (PROC_CTL(othercore) & PROC_SLEEP)
516 PROC_CTL(othercore) = 0;
519 /* Done with wake procedure */
520 MBX_MSG_CLR = 0x1 << othercore;
521 set_irq_level(oldlevel);
522 #endif /* ASM/C selection */
523 #else
524 PROC_CTL(othercore) = PROC_WAKE;
525 #endif
528 #if NUM_CORES > 1
529 /*---------------------------------------------------------------------------
530 * Switches to a stack that always resides in the Rockbox core.
532 * Needed when a thread suicides on a core other than the main CPU since the
533 * stack used when idling is the stack of the last thread to run. This stack
534 * may not reside in the core in which case the core will continue to use a
535 * stack from an unloaded module until another thread runs on it.
536 *---------------------------------------------------------------------------
538 static inline void switch_to_idle_stack(const unsigned int core)
540 asm volatile (
541 "str sp, [%0] \n" /* save original stack pointer on idle stack */
542 "mov sp, %0 \n" /* switch stacks */
543 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
544 (void)core;
547 /*---------------------------------------------------------------------------
548 * Perform core switch steps that need to take place inside switch_thread.
550 * These steps must take place while before changing the processor and after
551 * having entered switch_thread since switch_thread may not do a normal return
552 * because the stack being used for anything the compiler saved will not belong
553 * to the thread's destination core and it may have been recycled for other
554 * purposes by the time a normal context load has taken place. switch_thread
555 * will also clobber anything stashed in the thread's context or stored in the
556 * nonvolatile registers if it is saved there before the call since the
557 * compiler's order of operations cannot be known for certain.
559 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
561 /* Flush our data to ram */
562 flush_icache();
563 /* Stash thread in r4 slot */
564 thread->context.r[0] = (unsigned int)thread;
565 /* Stash restart address in r5 slot */
566 thread->context.r[1] = (unsigned int)thread->context.start;
567 /* Save sp in context.sp while still running on old core */
568 thread->context.sp = (void*)idle_stacks[core][IDLE_STACK_WORDS-1];
571 /*---------------------------------------------------------------------------
572 * Machine-specific helper function for switching the processor a thread is
573 * running on. Basically, the thread suicides on the departing core and is
574 * reborn on the destination. Were it not for gcc's ill-behavior regarding
575 * naked functions written in C where it actually clobbers non-volatile
576 * registers before the intended prologue code, this would all be much
577 * simpler. Generic setup is done in switch_core itself.
580 /*---------------------------------------------------------------------------
581 * This actually performs the core switch.
583 static void switch_thread_core(unsigned int core, struct thread_entry *thread)
584 __attribute__((naked));
585 static void switch_thread_core(unsigned int core, struct thread_entry *thread)
587 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
588 * Stack access also isn't permitted until restoring the original stack and
589 * context. */
590 asm volatile (
591 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
592 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
593 "ldr r2, [r2, r0, lsl #2] \n"
594 "add r2, r2, %0*4 \n"
595 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
596 "mov sp, r2 \n" /* switch stacks */
597 "adr r2, 1f \n" /* r2 = new core restart address */
598 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
599 "mov r0, r1 \n" /* switch_thread(thread) */
600 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
601 "1: \n"
602 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
603 "mov r1, #0 \n" /* Clear start address */
604 "str r1, [r0, #40] \n"
605 "ldr r0, =invalidate_icache \n" /* Invalidate new core's cache */
606 "mov lr, pc \n"
607 "bx r0 \n"
608 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
609 ".ltorg \n" /* Dump constant pool */
610 : : "i"(IDLE_STACK_WORDS)
612 (void)core; (void)thread;
614 #endif /* NUM_CORES */
616 #elif CONFIG_CPU == S3C2440
618 /*---------------------------------------------------------------------------
619 * Put core in a power-saving state if waking list wasn't repopulated.
620 *---------------------------------------------------------------------------
622 static inline void core_sleep(struct thread_entry **waking)
624 /* FIQ also changes the CLKCON register so FIQ must be disabled
625 when changing it here */
626 asm volatile (
627 "mrs r0, cpsr \n" /* Disable IRQ, FIQ */
628 "orr r0, r0, #0xc0 \n"
629 "msr cpsr_c, r0 \n"
630 "ldr r1, [%0] \n" /* Check *waking */
631 "cmp r1, #0 \n"
632 "bne 2f \n" /* != NULL -> exit */
633 "bic r0, r0, #0xc0 \n" /* Prepare IRQ, FIQ enable */
634 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
635 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
636 "orr r2, r2, #4 \n"
637 "str r2, [r1, #0xc] \n"
638 "msr cpsr_c, r0 \n" /* Enable IRQ, FIQ */
639 "mov r3, #0 \n" /* wait for IDLE */
640 "1: \n"
641 "add r3, r3, #1 \n"
642 "cmp r3, #10 \n"
643 "bne 1b \n"
644 "orr r0, r0, #0xc0 \n" /* Disable IRQ, FIQ */
645 "msr cpsr_c, r0 \n"
646 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
647 "bic r2, r2, #4 \n"
648 "str r2, [r1, #0xc] \n"
649 "2: \n"
650 "bic r0, r0, #0xc0 \n" /* Enable IRQ, FIQ */
651 "msr cpsr_c, r0 \n"
652 : : "r"(waking) : "r0", "r1", "r2", "r3");
654 #else
655 static inline void core_sleep(struct thread_entry **waking)
657 (void) waking;
658 #warning core_sleep not implemented, battery life will be decreased
660 #endif /* CONFIG_CPU == */
662 #elif defined(CPU_COLDFIRE)
663 /*---------------------------------------------------------------------------
664 * Start the thread running and terminate it if it returns
665 *---------------------------------------------------------------------------
667 void start_thread(void); /* Provide C access to ASM label */
668 static void __start_thread(void) __attribute__((used));
669 static void __start_thread(void)
671 /* a0=macsr, a1=context */
672 asm volatile (
673 "start_thread: \n" /* Start here - no naked attribute */
674 "move.l %a0, %macsr \n" /* Set initial mac status reg */
675 "lea.l 48(%a1), %a1 \n"
676 "move.l (%a1)+, %sp \n" /* Set initial stack */
677 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
678 "clr.l (%a1) \n" /* Mark thread running */
679 "jsr (%a2) \n" /* Call thread function */
680 "clr.l -(%sp) \n" /* remove_thread(NULL) */
681 "jsr remove_thread \n"
685 /* Set EMAC unit to fractional mode with saturation for each new thread,
686 * since that's what'll be the most useful for most things which the dsp
687 * will do. Codecs should still initialize their preferred modes
688 * explicitly. Context pointer is placed in d2 slot and start_thread
689 * pointer in d3 slot. thread function pointer is placed in context.start.
690 * See load_context for what happens when thread is initially going to
691 * run.
693 #define THREAD_STARTUP_INIT(core, thread, function) \
694 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
695 (thread)->context.d[0] = (unsigned int)&(thread)->context, \
696 (thread)->context.d[1] = (unsigned int)start_thread, \
697 (thread)->context.start = (void *)(function); })
699 /*---------------------------------------------------------------------------
700 * Store non-volatile context.
701 *---------------------------------------------------------------------------
703 static inline void store_context(void* addr)
705 asm volatile (
706 "move.l %%macsr,%%d0 \n"
707 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
708 : : "a" (addr) : "d0" /* only! */
712 /*---------------------------------------------------------------------------
713 * Load non-volatile context.
714 *---------------------------------------------------------------------------
716 static inline void load_context(const void* addr)
718 asm volatile (
719 "move.l 52(%0), %%d0 \n" /* Get start address */
720 "beq.b 1f \n" /* NULL -> already running */
721 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
722 "jmp (%%a2) \n" /* Start the thread */
723 "1: \n"
724 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
725 "move.l %%d0, %%macsr \n"
726 : : "a" (addr) : "d0" /* only! */
730 /*---------------------------------------------------------------------------
731 * Put core in a power-saving state if waking list wasn't repopulated.
732 *---------------------------------------------------------------------------
734 static inline void core_sleep(struct thread_entry **waking)
736 asm volatile (
737 "moveq.l %1, %%d0 \n" /* Disable interrupts (not audio DMA) */
738 "lsl.l #8, %%d0 \n"
739 "move.w %%d0, %%sr \n"
740 "tst.l (%0) \n" /* Check *waking */
741 "beq.b 1f \n" /* != NULL -> exit */
742 "moveq.l #0x20, %%d0 \n" /* Enable interrupts */
743 "lsl.l #8, %%d0 \n"
744 "move.w %%d0, %%sr \n"
745 ".word 0x51fb \n" /* tpf.l - eat stop instruction */
746 "1: \n"
747 "stop #0x2000 \n" /* Supervisor mode, interrupts enabled
748 upon wakeup */
749 : : "a"(waking), "i"((0x2000 | HIGHEST_IRQ_LEVEL) >> 8) : "d0"
753 #elif CONFIG_CPU == SH7034
754 /*---------------------------------------------------------------------------
755 * Start the thread running and terminate it if it returns
756 *---------------------------------------------------------------------------
758 void start_thread(void); /* Provide C access to ASM label */
759 static void __start_thread(void) __attribute__((used));
760 static void __start_thread(void)
762 /* r8 = context */
763 asm volatile (
764 "_start_thread: \n" /* Start here - no naked attribute */
765 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
766 "mov.l @(28, r8), r15 \n" /* Set initial sp */
767 "mov #0, r1 \n" /* Start the thread */
768 "jsr @r0 \n"
769 "mov.l r1, @(36, r8) \n" /* Clear start address */
770 "mov.l 1f, r0 \n" /* remove_thread(NULL) */
771 "jmp @r0 \n"
772 "mov #0, r4 \n"
773 "1: \n"
774 ".long _remove_thread \n"
778 /* Place context pointer in r8 slot, function pointer in r9 slot, and
779 * start_thread pointer in context_start */
780 #define THREAD_STARTUP_INIT(core, thread, function) \
781 ({ (thread)->context.r[0] = (unsigned int)&(thread)->context, \
782 (thread)->context.r[1] = (unsigned int)(function), \
783 (thread)->context.start = (void*)start_thread; })
785 /*---------------------------------------------------------------------------
786 * Store non-volatile context.
787 *---------------------------------------------------------------------------
789 static inline void store_context(void* addr)
791 asm volatile (
792 "add #36, %0 \n" /* Start at last reg. By the time routine */
793 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
794 "mov.l r15,@-%0 \n"
795 "mov.l r14,@-%0 \n"
796 "mov.l r13,@-%0 \n"
797 "mov.l r12,@-%0 \n"
798 "mov.l r11,@-%0 \n"
799 "mov.l r10,@-%0 \n"
800 "mov.l r9, @-%0 \n"
801 "mov.l r8, @-%0 \n"
802 : : "r" (addr)
806 /*---------------------------------------------------------------------------
807 * Load non-volatile context.
808 *---------------------------------------------------------------------------
810 static inline void load_context(const void* addr)
812 asm volatile (
813 "mov.l @(36, %0), r0 \n" /* Get start address */
814 "tst r0, r0 \n"
815 "bt .running \n" /* NULL -> already running */
816 "jmp @r0 \n" /* r8 = context */
817 ".running: \n"
818 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
819 "mov.l @%0+, r9 \n"
820 "mov.l @%0+, r10 \n"
821 "mov.l @%0+, r11 \n"
822 "mov.l @%0+, r12 \n"
823 "mov.l @%0+, r13 \n"
824 "mov.l @%0+, r14 \n"
825 "mov.l @%0+, r15 \n"
826 "lds.l @%0+, pr \n"
827 : : "r" (addr) : "r0" /* only! */
831 /*---------------------------------------------------------------------------
832 * Put core in a power-saving state if waking list wasn't repopulated.
833 *---------------------------------------------------------------------------
835 static inline void core_sleep(struct thread_entry **waking)
837 asm volatile (
838 "mov %2, r1 \n" /* Disable interrupts */
839 "ldc r1, sr \n"
840 "mov.l @%1, r1 \n" /* Check *waking */
841 "tst r1, r1 \n"
842 "bf 1f \n" /* *waking != NULL ? exit */
843 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
844 "mov #0, r1 \n" /* Enable interrupts */
845 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
846 "bra 2f \n" /* bra and sleep are executed at once */
847 "sleep \n" /* Execute standby */
848 "1: \n"
849 "mov #0, r1 \n" /* Enable interrupts */
850 "ldc r1, sr \n"
851 "2: \n"
853 : "z"(&SBYCR-GBR), "r"(waking), "i"(HIGHEST_IRQ_LEVEL)
854 : "r1");
857 #endif /* CONFIG_CPU == */
860 * End Processor-specific section
861 ***************************************************************************/
863 #if THREAD_EXTRA_CHECKS
864 static void thread_panicf(const char *msg, struct thread_entry *thread)
866 #if NUM_CORES > 1
867 const unsigned int core = thread->core;
868 #endif
869 static char name[32];
870 thread_get_name(name, 32, thread);
871 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
873 static void thread_stkov(struct thread_entry *thread)
875 thread_panicf("Stkov", thread);
877 #define THREAD_PANICF(msg, thread) \
878 thread_panicf(msg, thread)
879 #define THREAD_ASSERT(exp, msg, thread) \
880 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
881 #else
882 static void thread_stkov(struct thread_entry *thread)
884 #if NUM_CORES > 1
885 const unsigned int core = thread->core;
886 #endif
887 static char name[32];
888 thread_get_name(name, 32, thread);
889 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
891 #define THREAD_PANICF(msg, thread)
892 #define THREAD_ASSERT(exp, msg, thread)
893 #endif /* THREAD_EXTRA_CHECKS */
895 /*---------------------------------------------------------------------------
896 * Lock a list pointer and returns its value
897 *---------------------------------------------------------------------------
899 #if CONFIG_CORELOCK == SW_CORELOCK
900 /* Separate locking function versions */
902 /* Thread locking */
903 #define GET_THREAD_STATE(thread) \
904 ({ corelock_lock(&(thread)->cl); (thread)->state; })
905 #define TRY_GET_THREAD_STATE(thread) \
906 ({ corelock_try_lock(&thread->cl) ? thread->state : STATE_BUSY; })
907 #define UNLOCK_THREAD(thread, state) \
908 ({ corelock_unlock(&(thread)->cl); })
909 #define UNLOCK_THREAD_SET_STATE(thread, _state) \
910 ({ (thread)->state = (_state); corelock_unlock(&(thread)->cl); })
912 /* List locking */
913 #define LOCK_LIST(tqp) \
914 ({ corelock_lock(&(tqp)->cl); (tqp)->queue; })
915 #define UNLOCK_LIST(tqp, mod) \
916 ({ corelock_unlock(&(tqp)->cl); })
917 #define UNLOCK_LIST_SET_PTR(tqp, mod) \
918 ({ (tqp)->queue = (mod); corelock_unlock(&(tqp)->cl); })
920 /* Select the queue pointer directly */
921 #define ADD_TO_LIST_L_SELECT(tc, tqp, thread) \
922 ({ add_to_list_l(&(tqp)->queue, (thread)); })
923 #define REMOVE_FROM_LIST_L_SELECT(tc, tqp, thread) \
924 ({ remove_from_list_l(&(tqp)->queue, (thread)); })
926 #elif CONFIG_CORELOCK == CORELOCK_SWAP
927 /* Native swap/exchange versions */
929 /* Thread locking */
930 #define GET_THREAD_STATE(thread) \
931 ({ unsigned _s; \
932 while ((_s = xchg8(&(thread)->state, STATE_BUSY)) == STATE_BUSY); \
933 _s; })
934 #define TRY_GET_THREAD_STATE(thread) \
935 ({ xchg8(&(thread)->state, STATE_BUSY); })
936 #define UNLOCK_THREAD(thread, _state) \
937 ({ (thread)->state = (_state); })
938 #define UNLOCK_THREAD_SET_STATE(thread, _state) \
939 ({ (thread)->state = (_state); })
941 /* List locking */
942 #define LOCK_LIST(tqp) \
943 ({ struct thread_entry *_l; \
944 while((_l = xchgptr(&(tqp)->queue, STATE_BUSYuptr)) == STATE_BUSYuptr); \
945 _l; })
946 #define UNLOCK_LIST(tqp, mod) \
947 ({ (tqp)->queue = (mod); })
948 #define UNLOCK_LIST_SET_PTR(tqp, mod) \
949 ({ (tqp)->queue = (mod); })
951 /* Select the local queue pointer copy returned from LOCK_LIST */
952 #define ADD_TO_LIST_L_SELECT(tc, tqp, thread) \
953 ({ add_to_list_l(&(tc), (thread)); })
954 #define REMOVE_FROM_LIST_L_SELECT(tc, tqp, thread) \
955 ({ remove_from_list_l(&(tc), (thread)); })
957 #else
958 /* Single-core/non-locked versions */
960 /* Threads */
961 #define GET_THREAD_STATE(thread) \
962 ({ (thread)->state; })
963 #define UNLOCK_THREAD(thread, _state)
964 #define UNLOCK_THREAD_SET_STATE(thread, _state) \
965 ({ (thread)->state = (_state); })
967 /* Lists */
968 #define LOCK_LIST(tqp) \
969 ({ (tqp)->queue; })
970 #define UNLOCK_LIST(tqp, mod)
971 #define UNLOCK_LIST_SET_PTR(tqp, mod) \
972 ({ (tqp)->queue = (mod); })
974 /* Select the queue pointer directly */
975 #define ADD_TO_LIST_L_SELECT(tc, tqp, thread) \
976 ({ add_to_list_l(&(tqp)->queue, (thread)); })
977 #define REMOVE_FROM_LIST_L_SELECT(tc, tqp, thread) \
978 ({ remove_from_list_l(&(tqp)->queue, (thread)); })
980 #endif /* locking selection */
982 #if THREAD_EXTRA_CHECKS
983 /*---------------------------------------------------------------------------
984 * Lock the thread slot to obtain the state and then unlock it. Waits for
985 * it not to be busy. Used for debugging.
986 *---------------------------------------------------------------------------
988 static unsigned peek_thread_state(struct thread_entry *thread)
990 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
991 unsigned state = GET_THREAD_STATE(thread);
992 UNLOCK_THREAD(thread, state);
993 set_irq_level(oldlevel);
994 return state;
996 #endif /* THREAD_EXTRA_CHECKS */
998 /*---------------------------------------------------------------------------
999 * Adds a thread to a list of threads using "intert last". Uses the "l"
1000 * links.
1001 *---------------------------------------------------------------------------
1003 static void add_to_list_l(struct thread_entry **list,
1004 struct thread_entry *thread)
1006 struct thread_entry *l = *list;
1008 if (l == NULL)
1010 /* Insert into unoccupied list */
1011 thread->l.next = thread;
1012 thread->l.prev = thread;
1013 *list = thread;
1014 return;
1017 /* Insert last */
1018 thread->l.next = l;
1019 thread->l.prev = l->l.prev;
1020 thread->l.prev->l.next = thread;
1021 l->l.prev = thread;
1023 /* Insert next
1024 thread->l.next = l->l.next;
1025 thread->l.prev = l;
1026 thread->l.next->l.prev = thread;
1027 l->l.next = thread;
1031 /*---------------------------------------------------------------------------
1032 * Locks a list, adds the thread entry and unlocks the list on multicore.
1033 * Defined as add_to_list_l on single-core.
1034 *---------------------------------------------------------------------------
1036 #if NUM_CORES > 1
1037 static void add_to_list_l_locked(struct thread_queue *tq,
1038 struct thread_entry *thread)
1040 struct thread_entry *t = LOCK_LIST(tq);
1041 ADD_TO_LIST_L_SELECT(t, tq, thread);
1042 UNLOCK_LIST(tq, t);
1043 (void)t;
1045 #else
1046 #define add_to_list_l_locked(tq, thread) \
1047 add_to_list_l(&(tq)->queue, (thread))
1048 #endif
1050 /*---------------------------------------------------------------------------
1051 * Removes a thread from a list of threads. Uses the "l" links.
1052 *---------------------------------------------------------------------------
1054 static void remove_from_list_l(struct thread_entry **list,
1055 struct thread_entry *thread)
1057 struct thread_entry *prev, *next;
1059 next = thread->l.next;
1061 if (thread == next)
1063 /* The only item */
1064 *list = NULL;
1065 return;
1068 if (thread == *list)
1070 /* List becomes next item */
1071 *list = next;
1074 prev = thread->l.prev;
1076 /* Fix links to jump over the removed entry. */
1077 prev->l.next = next;
1078 next->l.prev = prev;
1081 /*---------------------------------------------------------------------------
1082 * Locks a list, removes the thread entry and unlocks the list on multicore.
1083 * Defined as remove_from_list_l on single-core.
1084 *---------------------------------------------------------------------------
1086 #if NUM_CORES > 1
1087 static void remove_from_list_l_locked(struct thread_queue *tq,
1088 struct thread_entry *thread)
1090 struct thread_entry *t = LOCK_LIST(tq);
1091 REMOVE_FROM_LIST_L_SELECT(t, tq, thread);
1092 UNLOCK_LIST(tq, t);
1093 (void)t;
1095 #else
1096 #define remove_from_list_l_locked(tq, thread) \
1097 remove_from_list_l(&(tq)->queue, (thread))
1098 #endif
1100 /*---------------------------------------------------------------------------
1101 * Add a thread from the core's timout list by linking the pointers in its
1102 * tmo structure.
1103 *---------------------------------------------------------------------------
1105 static void add_to_list_tmo(struct thread_entry *thread)
1107 /* Insert first */
1108 struct thread_entry *t = cores[IF_COP_CORE(thread->core)].timeout;
1110 thread->tmo.prev = thread;
1111 thread->tmo.next = t;
1113 if (t != NULL)
1115 /* Fix second item's prev pointer to point to this thread */
1116 t->tmo.prev = thread;
1119 cores[IF_COP_CORE(thread->core)].timeout = thread;
1122 /*---------------------------------------------------------------------------
1123 * Remove a thread from the core's timout list by unlinking the pointers in
1124 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1125 * is cancelled.
1126 *---------------------------------------------------------------------------
1128 static void remove_from_list_tmo(struct thread_entry *thread)
1130 struct thread_entry *next = thread->tmo.next;
1131 struct thread_entry *prev;
1133 if (thread == cores[IF_COP_CORE(thread->core)].timeout)
1135 /* Next item becomes list head */
1136 cores[IF_COP_CORE(thread->core)].timeout = next;
1138 if (next != NULL)
1140 /* Fix new list head's prev to point to itself. */
1141 next->tmo.prev = next;
1144 thread->tmo.prev = NULL;
1145 return;
1148 prev = thread->tmo.prev;
1150 if (next != NULL)
1152 next->tmo.prev = prev;
1155 prev->tmo.next = next;
1156 thread->tmo.prev = NULL;
1159 /*---------------------------------------------------------------------------
1160 * Schedules a thread wakeup on the specified core. Threads will be made
1161 * ready to run when the next task switch occurs. Note that this does not
1162 * introduce an on-core delay since the soonest the next thread may run is
1163 * no sooner than that. Other cores and on-core interrupts may only ever
1164 * add to the list.
1165 *---------------------------------------------------------------------------
1167 static void core_schedule_wakeup(struct thread_entry *thread)
1169 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
1170 const unsigned int core = IF_COP_CORE(thread->core);
1171 add_to_list_l_locked(&cores[core].waking, thread);
1172 #if NUM_CORES > 1
1173 if (core != CURRENT_CORE)
1175 core_wake(core);
1177 #endif
1178 set_irq_level(oldlevel);
1181 /*---------------------------------------------------------------------------
1182 * If the waking list was populated, move all threads on it onto the running
1183 * list so they may be run ASAP.
1184 *---------------------------------------------------------------------------
1186 static inline void core_perform_wakeup(IF_COP_VOID(unsigned int core))
1188 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
1189 struct thread_entry *w = LOCK_LIST(&cores[IF_COP_CORE(core)].waking);
1190 struct thread_entry *r = cores[IF_COP_CORE(core)].running;
1192 /* Tranfer all threads on waking list to running list in one
1193 swoop */
1194 if (r != NULL)
1196 /* Place waking threads at the end of the running list. */
1197 struct thread_entry *tmp;
1198 w->l.prev->l.next = r;
1199 r->l.prev->l.next = w;
1200 tmp = r->l.prev;
1201 r->l.prev = w->l.prev;
1202 w->l.prev = tmp;
1204 else
1206 /* Just transfer the list as-is */
1207 cores[IF_COP_CORE(core)].running = w;
1209 /* Just leave any timeout threads on the timeout list. If a timeout check
1210 * is due, they will be removed there. If they do a timeout again before
1211 * being removed, they will just stay on the list with a new expiration
1212 * tick. */
1214 /* Waking list is clear - NULL and unlock it */
1215 UNLOCK_LIST_SET_PTR(&cores[IF_COP_CORE(core)].waking, NULL);
1216 set_irq_level(oldlevel);
1219 /*---------------------------------------------------------------------------
1220 * Check the core's timeout list when at least one thread is due to wake.
1221 * Filtering for the condition is done before making the call. Resets the
1222 * tick when the next check will occur.
1223 *---------------------------------------------------------------------------
1225 static void check_tmo_threads(void)
1227 const unsigned int core = CURRENT_CORE;
1228 const long tick = current_tick; /* snapshot the current tick */
1229 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1230 struct thread_entry *next = cores[core].timeout;
1232 /* If there are no processes waiting for a timeout, just keep the check
1233 tick from falling into the past. */
1234 if (next != NULL)
1236 /* Check sleeping threads. */
1237 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
1241 /* Must make sure noone else is examining the state, wait until
1242 slot is no longer busy */
1243 struct thread_entry *curr = next;
1244 next = curr->tmo.next;
1246 unsigned state = GET_THREAD_STATE(curr);
1248 if (state < TIMEOUT_STATE_FIRST)
1250 /* Cleanup threads no longer on a timeout but still on the
1251 * list. */
1252 remove_from_list_tmo(curr);
1253 UNLOCK_THREAD(curr, state); /* Unlock thread slot */
1255 else if (TIME_BEFORE(tick, curr->tmo_tick))
1257 /* Timeout still pending - this will be the usual case */
1258 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1260 /* Earliest timeout found so far - move the next check up
1261 to its time */
1262 next_tmo_check = curr->tmo_tick;
1264 UNLOCK_THREAD(curr, state); /* Unlock thread slot */
1266 else
1268 /* Sleep timeout has been reached so bring the thread back to
1269 * life again. */
1270 if (state == STATE_BLOCKED_W_TMO)
1272 remove_from_list_l_locked(curr->bqp, curr);
1275 remove_from_list_tmo(curr);
1276 add_to_list_l(&cores[core].running, curr);
1277 UNLOCK_THREAD_SET_STATE(curr, STATE_RUNNING);
1280 /* Break the loop once we have walked through the list of all
1281 * sleeping processes or have removed them all. */
1283 while (next != NULL);
1285 set_irq_level(oldlevel);
1288 cores[core].next_tmo_check = next_tmo_check;
1291 /*---------------------------------------------------------------------------
1292 * Performs operations that must be done before blocking a thread but after
1293 * the state is saved - follows reverse of locking order. blk_ops.flags is
1294 * assumed to be nonzero.
1295 *---------------------------------------------------------------------------
1297 static inline void run_blocking_ops(
1298 IF_COP_VOID(unsigned int core, struct thread_entry *thread))
1300 #if NUM_CORES > 1
1301 struct thread_blk_ops *ops = &cores[IF_COP_CORE(core)].blk_ops;
1302 const unsigned flags = ops->flags;
1304 if (flags == 0)
1305 return;
1307 if (flags & TBOP_SWITCH_CORE)
1309 core_switch_blk_op(core, thread);
1312 #if CONFIG_CORELOCK == SW_CORELOCK
1313 if (flags & TBOP_UNLOCK_LIST)
1315 UNLOCK_LIST(ops->list_p, NULL);
1318 if (flags & TBOP_UNLOCK_CORELOCK)
1320 corelock_unlock(ops->cl_p);
1323 if (flags & TBOP_UNLOCK_THREAD)
1325 UNLOCK_THREAD(ops->thread, 0);
1327 #elif CONFIG_CORELOCK == CORELOCK_SWAP
1328 /* Write updated variable value into memory location */
1329 switch (flags & TBOP_VAR_TYPE_MASK)
1331 case TBOP_UNLOCK_LIST:
1332 UNLOCK_LIST(ops->list_p, ops->list_v);
1333 break;
1334 case TBOP_SET_VARi:
1335 *ops->var_ip = ops->var_iv;
1336 break;
1337 case TBOP_SET_VARu8:
1338 *ops->var_u8p = ops->var_u8v;
1339 break;
1341 #endif /* CONFIG_CORELOCK == */
1343 /* Unlock thread's slot */
1344 if (flags & TBOP_UNLOCK_CURRENT)
1346 UNLOCK_THREAD(thread, ops->state);
1349 /* Reset the IRQ level */
1350 if (flags & TBOP_IRQ_LEVEL)
1352 set_irq_level(ops->irq_level);
1355 ops->flags = 0;
1356 #else
1357 int level = cores[CURRENT_CORE].irq_level;
1358 if (level == STAY_IRQ_LEVEL)
1359 return;
1361 cores[CURRENT_CORE].irq_level = STAY_IRQ_LEVEL;
1362 set_irq_level(level);
1363 #endif /* NUM_CORES */
1367 /*---------------------------------------------------------------------------
1368 * Runs any operations that may cause threads to be ready to run and then
1369 * sleeps the processor core until the next interrupt if none are.
1370 *---------------------------------------------------------------------------
1372 static inline struct thread_entry * sleep_core(IF_COP_VOID(unsigned int core))
1374 for (;;)
1376 /* We want to do these ASAP as it may change the decision to sleep
1377 * the core or a core has woken because an interrupt occurred
1378 * and posted a message to a queue. */
1379 if (cores[IF_COP_CORE(core)].waking.queue != NULL)
1381 core_perform_wakeup(IF_COP(core));
1384 /* If there are threads on a timeout and the earliest wakeup is due,
1385 * check the list and wake any threads that need to start running
1386 * again. */
1387 if (!TIME_BEFORE(current_tick, cores[IF_COP_CORE(core)].next_tmo_check))
1389 check_tmo_threads();
1392 /* If there is a ready to run task, return its ID and keep core
1393 * awake. */
1394 if (cores[IF_COP_CORE(core)].running != NULL)
1396 return cores[IF_COP_CORE(core)].running;
1399 /* Enter sleep mode to reduce power usage - woken up on interrupt or
1400 * wakeup request from another core. May abort if the waking list
1401 * became populated (again). See beginning of this file for the
1402 * algorithm to atomically determine this. */
1403 core_sleep(IF_COP(core, ) &cores[IF_COP_CORE(core)].waking.queue);
1407 #ifdef RB_PROFILE
1408 void profile_thread(void)
1410 profstart(cores[CURRENT_CORE].running - threads);
1412 #endif
1414 /*---------------------------------------------------------------------------
1415 * Prepares a thread to block on an object's list and/or for a specified
1416 * duration - expects object and slot to be appropriately locked if needed.
1417 *---------------------------------------------------------------------------
1419 static inline void _block_thread_on_l(struct thread_queue *list,
1420 struct thread_entry *thread,
1421 unsigned state
1422 IF_SWCL(, const bool nolock))
1424 /* If inlined, unreachable branches will be pruned with no size penalty
1425 because constant params are used for state and nolock. */
1426 const unsigned int core = IF_COP_CORE(thread->core);
1428 /* Remove the thread from the list of running threads. */
1429 remove_from_list_l(&cores[core].running, thread);
1431 /* Add a timeout to the block if not infinite */
1432 switch (state)
1434 case STATE_BLOCKED:
1435 /* Put the thread into a new list of inactive threads. */
1436 #if CONFIG_CORELOCK == SW_CORELOCK
1437 if (nolock)
1439 thread->bqp = NULL; /* Indicate nolock list */
1440 thread->bqnlp = (struct thread_entry **)list;
1441 add_to_list_l((struct thread_entry **)list, thread);
1443 else
1444 #endif
1446 thread->bqp = list;
1447 add_to_list_l_locked(list, thread);
1449 break;
1450 case STATE_BLOCKED_W_TMO:
1451 /* Put the thread into a new list of inactive threads. */
1452 #if CONFIG_CORELOCK == SW_CORELOCK
1453 if (nolock)
1455 thread->bqp = NULL; /* Indicate nolock list */
1456 thread->bqnlp = (struct thread_entry **)list;
1457 add_to_list_l((struct thread_entry **)list, thread);
1459 else
1460 #endif
1462 thread->bqp = list;
1463 add_to_list_l_locked(list, thread);
1465 /* Fall-through */
1466 case STATE_SLEEPING:
1467 /* If this thread times out sooner than any other thread, update
1468 next_tmo_check to its timeout */
1469 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1471 cores[core].next_tmo_check = thread->tmo_tick;
1474 if (thread->tmo.prev == NULL)
1476 add_to_list_tmo(thread);
1478 /* else thread was never removed from list - just keep it there */
1479 break;
1482 #ifdef HAVE_PRIORITY_SCHEDULING
1483 /* Reset priorities */
1484 if (thread->priority == cores[core].highest_priority)
1485 cores[core].highest_priority = LOWEST_PRIORITY;
1486 #endif
1488 #if NUM_CORES == 1 || CONFIG_CORELOCK == SW_CORELOCK
1489 /* Safe to set state now */
1490 thread->state = state;
1491 #elif CONFIG_CORELOCK == CORELOCK_SWAP
1492 cores[core].blk_ops.state = state;
1493 #endif
1495 #if NUM_CORES > 1
1496 /* Delay slot unlock until task switch */
1497 cores[core].blk_ops.flags |= TBOP_UNLOCK_CURRENT;
1498 #endif
1501 static inline void block_thread_on_l(
1502 struct thread_queue *list, struct thread_entry *thread, unsigned state)
1504 _block_thread_on_l(list, thread, state IF_SWCL(, false));
1507 static inline void block_thread_on_l_no_listlock(
1508 struct thread_entry **list, struct thread_entry *thread, unsigned state)
1510 _block_thread_on_l((struct thread_queue *)list, thread, state IF_SWCL(, true));
1513 /*---------------------------------------------------------------------------
1514 * Switch thread in round robin fashion for any given priority. Any thread
1515 * that removed itself from the running list first must specify itself in
1516 * the paramter.
1518 * INTERNAL: Intended for use by kernel and not for programs.
1519 *---------------------------------------------------------------------------
1521 void switch_thread(struct thread_entry *old)
1523 const unsigned int core = CURRENT_CORE;
1524 struct thread_entry *thread = cores[core].running;
1526 if (old == NULL)
1528 /* Move to next thread */
1529 old = thread;
1530 cores[core].running = old->l.next;
1532 /* else running list is already at next thread */
1534 #ifdef RB_PROFILE
1535 profile_thread_stopped(old - threads);
1536 #endif
1538 /* Begin task switching by saving our current context so that we can
1539 * restore the state of the current thread later to the point prior
1540 * to this call. */
1541 store_context(&old->context);
1543 /* Check if the current thread stack is overflown */
1544 if(((unsigned int *)old->stack)[0] != DEADBEEF)
1545 thread_stkov(old);
1547 /* Run any blocking operations requested before switching/sleeping */
1548 run_blocking_ops(IF_COP(core, old));
1550 /* Go through the list of sleeping task to check if we need to wake up
1551 * any of them due to timeout. Also puts core into sleep state until
1552 * there is at least one running process again. */
1553 thread = sleep_core(IF_COP(core));
1555 #ifdef HAVE_PRIORITY_SCHEDULING
1556 /* Select the new task based on priorities and the last time a process
1557 * got CPU time. */
1558 for (;;)
1560 int priority = MIN(thread->priority, thread->priority_x);
1562 if (priority < cores[core].highest_priority)
1563 cores[core].highest_priority = priority;
1565 if (priority == cores[core].highest_priority ||
1566 (current_tick - thread->last_run > priority * 8))
1568 cores[core].running = thread;
1569 break;
1572 thread = thread->l.next;
1575 /* Reset the value of thread's last running time to the current time. */
1576 thread->last_run = current_tick;
1577 #endif /* HAVE_PRIORITY_SCHEDULING */
1579 /* And finally give control to the next thread. */
1580 load_context(&thread->context);
1582 #ifdef RB_PROFILE
1583 profile_thread_started(thread - threads);
1584 #endif
1587 /*---------------------------------------------------------------------------
1588 * Removes the boost flag from a thread and unboosts the CPU if thread count
1589 * of boosted threads reaches zero. Requires thread slot to be locked first.
1590 *---------------------------------------------------------------------------
1592 static inline void unboost_thread(struct thread_entry *thread)
1594 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1595 if (thread->boosted != 0)
1597 thread->boosted = 0;
1598 if (--boosted_threads == 0)
1600 cpu_boost(false);
1603 #endif
1604 (void)thread;
1607 /*---------------------------------------------------------------------------
1608 * Sleeps a thread for a specified number of ticks and unboost the thread if
1609 * if it is boosted. If ticks is zero, it does not delay but instead switches
1610 * tasks.
1612 * INTERNAL: Intended for use by kernel and not for programs.
1613 *---------------------------------------------------------------------------
1615 void sleep_thread(int ticks)
1617 /* Get the entry for the current running thread. */
1618 struct thread_entry *current = cores[CURRENT_CORE].running;
1620 #if NUM_CORES > 1
1621 /* Lock thread slot */
1622 GET_THREAD_STATE(current);
1623 #endif
1625 /* Remove our boosted status if any */
1626 unboost_thread(current);
1628 /* Set our timeout, change lists, and finally switch threads.
1629 * Unlock during switch on mulicore. */
1630 current->tmo_tick = current_tick + ticks + 1;
1631 block_thread_on_l(NULL, current, STATE_SLEEPING);
1632 switch_thread(current);
1634 /* Our status should be STATE_RUNNING */
1635 THREAD_ASSERT(peek_thread_state(current) == STATE_RUNNING,
1636 "S:R->!*R", current);
1639 /*---------------------------------------------------------------------------
1640 * Indefinitely block a thread on a blocking queue for explicit wakeup.
1641 * Caller with interrupt-accessible lists should disable interrupts first
1642 * and request a BOP_IRQ_LEVEL blocking operation to reset it.
1644 * INTERNAL: Intended for use by kernel objects and not for programs.
1645 *---------------------------------------------------------------------------
1647 IF_SWCL(static inline) void _block_thread(struct thread_queue *list
1648 IF_SWCL(, const bool nolock))
1650 /* Get the entry for the current running thread. */
1651 struct thread_entry *current = cores[CURRENT_CORE].running;
1653 /* Set the state to blocked and ask the scheduler to switch tasks,
1654 * this takes us off of the run queue until we are explicitly woken */
1656 #if NUM_CORES > 1
1657 /* Lock thread slot */
1658 GET_THREAD_STATE(current);
1659 #endif
1661 #if CONFIG_CORELOCK == SW_CORELOCK
1662 /* One branch optimized away during inlining */
1663 if (nolock)
1665 block_thread_on_l_no_listlock((struct thread_entry **)list,
1666 current, STATE_BLOCKED);
1668 else
1669 #endif
1671 block_thread_on_l(list, current, STATE_BLOCKED);
1674 switch_thread(current);
1676 /* Our status should be STATE_RUNNING */
1677 THREAD_ASSERT(peek_thread_state(current) == STATE_RUNNING,
1678 "B:R->!*R", current);
1681 #if CONFIG_CORELOCK == SW_CORELOCK
1682 /* Inline lock/nolock version of _block_thread into these functions */
1683 void block_thread(struct thread_queue *tq)
1685 _block_thread(tq, false);
1688 void block_thread_no_listlock(struct thread_entry **list)
1690 _block_thread((struct thread_queue *)list, true);
1692 #endif /* CONFIG_CORELOCK */
1694 /*---------------------------------------------------------------------------
1695 * Block a thread on a blocking queue for a specified time interval or until
1696 * explicitly woken - whichever happens first.
1697 * Caller with interrupt-accessible lists should disable interrupts first
1698 * and request that interrupt level be restored after switching out the
1699 * current thread.
1701 * INTERNAL: Intended for use by kernel objects and not for programs.
1702 *---------------------------------------------------------------------------
1704 void block_thread_w_tmo(struct thread_queue *list, int timeout)
1706 /* Get the entry for the current running thread. */
1707 struct thread_entry *current = cores[CURRENT_CORE].running;
1709 #if NUM_CORES > 1
1710 /* Lock thread slot */
1711 GET_THREAD_STATE(current);
1712 #endif
1714 /* A block with a timeout is a sleep situation, whatever we are waiting
1715 * for _may or may not_ happen, regardless of boost state, (user input
1716 * for instance), so this thread no longer needs to boost */
1717 unboost_thread(current);
1719 /* Set the state to blocked with the specified timeout */
1720 current->tmo_tick = current_tick + timeout;
1721 /* Set the list for explicit wakeup */
1722 block_thread_on_l(list, current, STATE_BLOCKED_W_TMO);
1724 /* Now force a task switch and block until we have been woken up
1725 * by another thread or timeout is reached - whichever happens first */
1726 switch_thread(current);
1728 /* Our status should be STATE_RUNNING */
1729 THREAD_ASSERT(peek_thread_state(current) == STATE_RUNNING,
1730 "T:R->!*R", current);
1733 /*---------------------------------------------------------------------------
1734 * Explicitly wakeup a thread on a blocking queue. Has no effect on threads
1735 * that called sleep().
1736 * Caller with interrupt-accessible lists should disable interrupts first.
1737 * This code should be considered a critical section by the caller.
1739 * INTERNAL: Intended for use by kernel objects and not for programs.
1740 *---------------------------------------------------------------------------
1742 IF_SWCL(static inline) struct thread_entry * _wakeup_thread(
1743 struct thread_queue *list IF_SWCL(, const bool nolock))
1745 struct thread_entry *t;
1746 struct thread_entry *thread;
1747 unsigned state;
1749 /* Wake up the last thread first. */
1750 #if CONFIG_CORELOCK == SW_CORELOCK
1751 /* One branch optimized away during inlining */
1752 if (nolock)
1754 t = list->queue;
1756 else
1757 #endif
1759 t = LOCK_LIST(list);
1762 /* Check if there is a blocked thread at all. */
1763 if (t == NULL)
1765 #if CONFIG_CORELOCK == SW_CORELOCK
1766 if (!nolock)
1767 #endif
1769 UNLOCK_LIST(list, NULL);
1771 return NULL;
1774 thread = t;
1776 #if NUM_CORES > 1
1777 #if CONFIG_CORELOCK == SW_CORELOCK
1778 if (nolock)
1780 /* Lock thread only, not list */
1781 state = GET_THREAD_STATE(thread);
1783 else
1784 #endif
1786 /* This locks in reverse order from other routines so a retry in the
1787 correct order may be needed */
1788 state = TRY_GET_THREAD_STATE(thread);
1789 if (state == STATE_BUSY)
1791 /* Unlock list and retry slot, then list */
1792 UNLOCK_LIST(list, t);
1793 state = GET_THREAD_STATE(thread);
1794 t = LOCK_LIST(list);
1795 /* Be sure thread still exists here - it couldn't have re-added
1796 itself if it was woken elsewhere because this function is
1797 serialized within the object that owns the list. */
1798 if (thread != t)
1800 /* Thread disappeared :( */
1801 UNLOCK_LIST(list, t);
1802 UNLOCK_THREAD(thread, state);
1803 return THREAD_WAKEUP_MISSING; /* Indicate disappearance */
1807 #else /* NUM_CORES == 1 */
1808 state = GET_THREAD_STATE(thread);
1809 #endif /* NUM_CORES */
1811 /* Determine thread's current state. */
1812 switch (state)
1814 case STATE_BLOCKED:
1815 case STATE_BLOCKED_W_TMO:
1816 /* Remove thread from object's blocked list - select t or list depending
1817 on locking type at compile time */
1818 REMOVE_FROM_LIST_L_SELECT(t, list, thread);
1819 #if CONFIG_CORELOCK == SW_CORELOCK
1820 /* Statment optimized away during inlining if nolock != false */
1821 if (!nolock)
1822 #endif
1824 UNLOCK_LIST(list, t); /* Unlock list - removal complete */
1827 #ifdef HAVE_PRIORITY_SCHEDULING
1828 /* Give the task a kick to avoid a stall after wakeup.
1829 Not really proper treatment - TODO later. */
1830 thread->last_run = current_tick - 8*LOWEST_PRIORITY;
1831 #endif
1832 core_schedule_wakeup(thread);
1833 UNLOCK_THREAD_SET_STATE(thread, STATE_RUNNING);
1834 return thread;
1835 default:
1836 /* Nothing to do. State is not blocked. */
1837 #if THREAD_EXTRA_CHECKS
1838 THREAD_PANICF("wakeup_thread->block invalid", thread);
1839 case STATE_RUNNING:
1840 case STATE_KILLED:
1841 #endif
1842 #if CONFIG_CORELOCK == SW_CORELOCK
1843 /* Statement optimized away during inlining if nolock != false */
1844 if (!nolock)
1845 #endif
1847 UNLOCK_LIST(list, t); /* Unlock the object's list */
1849 UNLOCK_THREAD(thread, state); /* Unlock thread slot */
1850 return NULL;
1854 #if CONFIG_CORELOCK == SW_CORELOCK
1855 /* Inline lock/nolock version of _wakeup_thread into these functions */
1856 struct thread_entry * wakeup_thread(struct thread_queue *tq)
1858 return _wakeup_thread(tq, false);
1861 struct thread_entry * wakeup_thread_no_listlock(struct thread_entry **list)
1863 return _wakeup_thread((struct thread_queue *)list, true);
1865 #endif /* CONFIG_CORELOCK */
1867 /*---------------------------------------------------------------------------
1868 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
1869 * will be locked on multicore.
1870 *---------------------------------------------------------------------------
1872 static int find_empty_thread_slot(void)
1874 #if NUM_CORES > 1
1875 /* Any slot could be on an IRQ-accessible list */
1876 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
1877 #endif
1878 /* Thread slots are not locked on single core */
1880 int n;
1882 for (n = 0; n < MAXTHREADS; n++)
1884 /* Obtain current slot state - lock it on multicore */
1885 unsigned state = GET_THREAD_STATE(&threads[n]);
1887 if (state == STATE_KILLED
1888 #if NUM_CORES > 1
1889 && threads[n].name != THREAD_DESTRUCT
1890 #endif
1893 /* Slot is empty - leave it locked and caller will unlock */
1894 break;
1897 /* Finished examining slot - no longer busy - unlock on multicore */
1898 UNLOCK_THREAD(&threads[n], state);
1901 #if NUM_CORES > 1
1902 set_irq_level(oldlevel); /* Reenable interrups - this slot is
1903 not accesible to them yet */
1904 #endif
1906 return n;
1910 /*---------------------------------------------------------------------------
1911 * Place the current core in idle mode - woken up on interrupt or wake
1912 * request from another core.
1913 *---------------------------------------------------------------------------
1915 void core_idle(void)
1917 const unsigned int core = CURRENT_CORE;
1918 core_sleep(IF_COP(core,) &cores[core].waking.queue);
1921 /*---------------------------------------------------------------------------
1922 * Create a thread
1923 * If using a dual core architecture, specify which core to start the thread
1924 * on, and whether to fall back to the other core if it can't be created
1925 * Return ID if context area could be allocated, else NULL.
1926 *---------------------------------------------------------------------------
1928 struct thread_entry*
1929 create_thread(void (*function)(void), void* stack, int stack_size,
1930 unsigned flags, const char *name
1931 IF_PRIO(, int priority)
1932 IF_COP(, unsigned int core))
1934 unsigned int i;
1935 unsigned int stacklen;
1936 unsigned int *stackptr;
1937 int slot;
1938 struct thread_entry *thread;
1939 unsigned state;
1941 slot = find_empty_thread_slot();
1942 if (slot >= MAXTHREADS)
1944 return NULL;
1947 /* Munge the stack to make it easy to spot stack overflows */
1948 stacklen = stack_size / sizeof(int);
1949 stackptr = stack;
1950 for(i = 0;i < stacklen;i++)
1952 stackptr[i] = DEADBEEF;
1955 /* Store interesting information */
1956 thread = &threads[slot];
1957 thread->name = name;
1958 thread->stack = stack;
1959 thread->stack_size = stack_size;
1960 thread->bqp = NULL;
1961 #if CONFIG_CORELOCK == SW_CORELOCK
1962 thread->bqnlp = NULL;
1963 #endif
1964 thread->queue = NULL;
1965 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1966 thread->boosted = 0;
1967 #endif
1968 #ifdef HAVE_PRIORITY_SCHEDULING
1969 thread->priority_x = LOWEST_PRIORITY;
1970 thread->priority = priority;
1971 thread->last_run = current_tick - priority * 8;
1972 cores[IF_COP_CORE(core)].highest_priority = LOWEST_PRIORITY;
1973 #endif
1975 #if NUM_CORES > 1
1976 thread->core = core;
1978 /* Writeback stack munging or anything else before starting */
1979 if (core != CURRENT_CORE)
1981 flush_icache();
1983 #endif
1985 /* Thread is not on any timeout list but be a bit paranoid */
1986 thread->tmo.prev = NULL;
1988 state = (flags & CREATE_THREAD_FROZEN) ?
1989 STATE_FROZEN : STATE_RUNNING;
1991 /* Align stack to an even 32 bit boundary */
1992 thread->context.sp = (void*)(((unsigned int)stack + stack_size) & ~3);
1994 /* Load the thread's context structure with needed startup information */
1995 THREAD_STARTUP_INIT(core, thread, function);
1997 if (state == STATE_RUNNING)
1999 #if NUM_CORES > 1
2000 if (core != CURRENT_CORE)
2002 /* Next task switch on other core moves thread to running list */
2003 core_schedule_wakeup(thread);
2005 else
2006 #endif
2008 /* Place on running list immediately */
2009 add_to_list_l(&cores[IF_COP_CORE(core)].running, thread);
2013 /* remove lock and set state */
2014 UNLOCK_THREAD_SET_STATE(thread, state);
2016 return thread;
2019 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2020 void trigger_cpu_boost(void)
2022 /* No IRQ disable nescessary since the current thread cannot be blocked
2023 on an IRQ-accessible list */
2024 struct thread_entry *current = cores[CURRENT_CORE].running;
2025 unsigned state;
2027 state = GET_THREAD_STATE(current);
2029 if (current->boosted == 0)
2031 current->boosted = 1;
2032 if (++boosted_threads == 1)
2034 cpu_boost(true);
2038 UNLOCK_THREAD(current, state);
2039 (void)state;
2041 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2043 /*---------------------------------------------------------------------------
2044 * Remove a thread from the scheduler.
2045 * Parameter is the ID as returned from create_thread().
2047 * Use with care on threads that are not under careful control as this may
2048 * leave various objects in an undefined state. When trying to kill a thread
2049 * on another processor, be sure you know what it's doing and won't be
2050 * switching around itself.
2051 *---------------------------------------------------------------------------
2053 void remove_thread(struct thread_entry *thread)
2055 #if NUM_CORES > 1
2056 /* core is not constant here because of core switching */
2057 unsigned int core = CURRENT_CORE;
2058 unsigned int old_core = NUM_CORES;
2059 #else
2060 const unsigned int core = CURRENT_CORE;
2061 #endif
2062 unsigned state;
2063 int oldlevel;
2065 if (thread == NULL)
2066 thread = cores[core].running;
2068 oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2069 state = GET_THREAD_STATE(thread);
2071 if (state == STATE_KILLED)
2073 goto thread_killed;
2076 #if NUM_CORES > 1
2077 if (thread->core != core)
2079 /* Switch cores and safely extract the thread there */
2080 /* Slot HAS to be unlocked or a deadlock could occur - potential livelock
2081 condition if the thread runs away to another processor. */
2082 unsigned int new_core = thread->core;
2083 const char *old_name = thread->name;
2085 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2086 UNLOCK_THREAD(thread, state);
2087 set_irq_level(oldlevel);
2089 old_core = switch_core(new_core);
2091 oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2092 state = GET_THREAD_STATE(thread);
2094 core = new_core;
2096 if (state == STATE_KILLED)
2098 /* Thread suicided before we could kill it */
2099 goto thread_killed;
2102 /* Reopen slot - it's locked again anyway */
2103 thread->name = old_name;
2105 if (thread->core != core)
2107 /* We won't play thread tag - just forget it */
2108 UNLOCK_THREAD(thread, state);
2109 set_irq_level(oldlevel);
2110 goto thread_kill_abort;
2113 /* Perform the extraction and switch ourselves back to the original
2114 processor */
2116 #endif /* NUM_CORES > 1 */
2118 #ifdef HAVE_PRIORITY_SCHEDULING
2119 cores[IF_COP_CORE(core)].highest_priority = LOWEST_PRIORITY;
2120 #endif
2121 if (thread->tmo.prev != NULL)
2123 /* Clean thread off the timeout list if a timeout check hasn't
2124 * run yet */
2125 remove_from_list_tmo(thread);
2128 if (thread == cores[core].running)
2130 /* Suicide - thread has unconditional rights to do this */
2131 /* Maintain locks until switch-out */
2132 #if NUM_CORES > 1
2133 cores[core].blk_ops.flags = TBOP_IRQ_LEVEL;
2134 cores[core].blk_ops.irq_level = oldlevel;
2135 #else
2136 cores[core].irq_level = oldlevel;
2137 #endif
2138 block_thread_on_l(NULL, thread, STATE_KILLED);
2140 #if NUM_CORES > 1
2141 /* Switch to the idle stack if not on the main core (where "main"
2142 * runs) */
2143 if (core != CPU)
2145 switch_to_idle_stack(core);
2148 flush_icache();
2149 #endif
2150 /* Signal this thread */
2151 thread_queue_wake_no_listlock(&thread->queue);
2152 /* Switch tasks and never return */
2153 switch_thread(thread);
2154 /* This should never and must never be reached - if it is, the
2155 * state is corrupted */
2156 THREAD_PANICF("remove_thread->K:*R", thread);
2159 #if NUM_CORES > 1
2160 if (thread->name == THREAD_DESTRUCT)
2162 /* Another core is doing this operation already */
2163 UNLOCK_THREAD(thread, state);
2164 set_irq_level(oldlevel);
2165 return;
2167 #endif
2168 if (cores[core].waking.queue != NULL)
2170 /* Get any threads off the waking list and onto the running
2171 * list first - waking and running cannot be distinguished by
2172 * state */
2173 core_perform_wakeup(IF_COP(core));
2176 switch (state)
2178 case STATE_RUNNING:
2179 /* Remove thread from ready to run tasks */
2180 remove_from_list_l(&cores[core].running, thread);
2181 break;
2182 case STATE_BLOCKED:
2183 case STATE_BLOCKED_W_TMO:
2184 /* Remove thread from the queue it's blocked on - including its
2185 * own if waiting there */
2186 #if CONFIG_CORELOCK == SW_CORELOCK
2187 /* One or the other will be valid */
2188 if (thread->bqp == NULL)
2190 remove_from_list_l(thread->bqnlp, thread);
2192 else
2193 #endif /* CONFIG_CORELOCK */
2195 remove_from_list_l_locked(thread->bqp, thread);
2197 break;
2198 /* Otherwise thread is killed or is frozen and hasn't run yet */
2201 /* If thread was waiting on itself, it will have been removed above.
2202 * The wrong order would result in waking the thread first and deadlocking
2203 * since the slot is already locked. */
2204 thread_queue_wake_no_listlock(&thread->queue);
2206 thread_killed: /* Thread was already killed */
2207 /* Removal complete - safe to unlock state and reenable interrupts */
2208 UNLOCK_THREAD_SET_STATE(thread, STATE_KILLED);
2209 set_irq_level(oldlevel);
2211 #if NUM_CORES > 1
2212 thread_kill_abort: /* Something stopped us from killing the thread */
2213 if (old_core < NUM_CORES)
2215 /* Did a removal on another processor's thread - switch back to
2216 native core */
2217 switch_core(old_core);
2219 #endif
2222 /*---------------------------------------------------------------------------
2223 * Block the current thread until another thread terminates. A thread may
2224 * wait on itself to terminate which prevents it from running again and it
2225 * will need to be killed externally.
2226 * Parameter is the ID as returned from create_thread().
2227 *---------------------------------------------------------------------------
2229 void thread_wait(struct thread_entry *thread)
2231 const unsigned int core = CURRENT_CORE;
2232 struct thread_entry *current = cores[core].running;
2233 unsigned thread_state;
2234 #if NUM_CORES > 1
2235 int oldlevel;
2236 unsigned current_state;
2237 #endif
2239 if (thread == NULL)
2240 thread = current;
2242 #if NUM_CORES > 1
2243 oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2244 #endif
2246 thread_state = GET_THREAD_STATE(thread);
2248 #if NUM_CORES > 1
2249 /* We can't lock the same slot twice. The waitee will also lock itself
2250 first then the thread slots that will be locked and woken in turn.
2251 The same order must be observed here as well. */
2252 if (thread == current)
2254 current_state = thread_state;
2256 else
2258 current_state = GET_THREAD_STATE(current);
2260 #endif
2262 if (thread_state != STATE_KILLED)
2264 #if NUM_CORES > 1
2265 cores[core].blk_ops.flags = TBOP_IRQ_LEVEL;
2266 cores[core].blk_ops.irq_level = oldlevel;
2267 #endif
2268 /* Unlock the waitee state at task switch - not done for self-wait
2269 because the would double-unlock the state and potentially
2270 corrupt another's busy assert on the slot */
2271 if (thread != current)
2273 #if CONFIG_CORELOCK == SW_CORELOCK
2274 cores[core].blk_ops.flags |= TBOP_UNLOCK_THREAD;
2275 cores[core].blk_ops.thread = thread;
2276 #elif CONFIG_CORELOCK == CORELOCK_SWAP
2277 cores[core].blk_ops.flags |= TBOP_SET_VARu8;
2278 cores[core].blk_ops.var_u8p = &thread->state;
2279 cores[core].blk_ops.var_u8v = thread_state;
2280 #endif
2282 block_thread_on_l_no_listlock(&thread->queue, current, STATE_BLOCKED);
2283 switch_thread(current);
2284 return;
2287 /* Unlock both slots - obviously the current thread can't have
2288 STATE_KILLED so the above if clause will always catch a thread
2289 waiting on itself */
2290 #if NUM_CORES > 1
2291 UNLOCK_THREAD(current, current_state);
2292 UNLOCK_THREAD(thread, thread_state);
2293 set_irq_level(oldlevel);
2294 #endif
2297 #ifdef HAVE_PRIORITY_SCHEDULING
2298 /*---------------------------------------------------------------------------
2299 * Sets the thread's relative priority for the core it runs on.
2300 *---------------------------------------------------------------------------
2302 int thread_set_priority(struct thread_entry *thread, int priority)
2304 unsigned old_priority = (unsigned)-1;
2306 if (thread == NULL)
2307 thread = cores[CURRENT_CORE].running;
2309 #if NUM_CORES > 1
2310 /* Thread could be on any list and therefore on an interrupt accessible
2311 one - disable interrupts */
2312 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2313 #endif
2314 unsigned state = GET_THREAD_STATE(thread);
2316 /* Make sure it's not killed */
2317 if (state != STATE_KILLED)
2319 old_priority = thread->priority;
2320 thread->priority = priority;
2321 cores[IF_COP_CORE(thread->core)].highest_priority = LOWEST_PRIORITY;
2324 #if NUM_CORES > 1
2325 UNLOCK_THREAD(thread, state);
2326 set_irq_level(oldlevel);
2327 #endif
2328 return old_priority;
2331 /*---------------------------------------------------------------------------
2332 * Returns the current priority for a thread.
2333 *---------------------------------------------------------------------------
2335 int thread_get_priority(struct thread_entry *thread)
2337 /* Simple, quick probe. */
2338 if (thread == NULL)
2339 thread = cores[CURRENT_CORE].running;
2341 return (unsigned)thread->priority;
2344 /*---------------------------------------------------------------------------
2345 * Yield that guarantees thread execution once per round regardless of
2346 * thread's scheduler priority - basically a transient realtime boost
2347 * without altering the scheduler's thread precedence.
2349 * HACK ALERT! Search for "priority inheritance" for proper treatment.
2350 *---------------------------------------------------------------------------
2352 void priority_yield(void)
2354 const unsigned int core = CURRENT_CORE;
2355 struct thread_entry *thread = cores[core].running;
2356 thread->priority_x = HIGHEST_PRIORITY;
2357 switch_thread(NULL);
2358 thread->priority_x = LOWEST_PRIORITY;
2359 cores[core].highest_priority = LOWEST_PRIORITY;
2361 #endif /* HAVE_PRIORITY_SCHEDULING */
2363 /* Resumes a frozen thread - similar logic to wakeup_thread except that
2364 the thread is on no scheduler list at all. It exists simply by virtue of
2365 the slot having a state of STATE_FROZEN. */
2366 void thread_thaw(struct thread_entry *thread)
2368 #if NUM_CORES > 1
2369 /* Thread could be on any list and therefore on an interrupt accessible
2370 one - disable interrupts */
2371 int oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2372 #endif
2373 unsigned state = GET_THREAD_STATE(thread);
2375 if (state == STATE_FROZEN)
2377 const unsigned int core = CURRENT_CORE;
2378 #if NUM_CORES > 1
2379 if (thread->core != core)
2381 core_schedule_wakeup(thread);
2383 else
2384 #endif
2386 add_to_list_l(&cores[core].running, thread);
2389 UNLOCK_THREAD_SET_STATE(thread, STATE_RUNNING);
2390 #if NUM_CORES > 1
2391 set_irq_level(oldlevel);
2392 #endif
2393 return;
2396 #if NUM_CORES > 1
2397 UNLOCK_THREAD(thread, state);
2398 set_irq_level(oldlevel);
2399 #endif
2402 /*---------------------------------------------------------------------------
2403 * Return the ID of the currently executing thread.
2404 *---------------------------------------------------------------------------
2406 struct thread_entry * thread_get_current(void)
2408 return cores[CURRENT_CORE].running;
2411 #if NUM_CORES > 1
2412 /*---------------------------------------------------------------------------
2413 * Switch the processor that the currently executing thread runs on.
2414 *---------------------------------------------------------------------------
2416 unsigned int switch_core(unsigned int new_core)
2418 const unsigned int core = CURRENT_CORE;
2419 struct thread_entry *current = cores[core].running;
2420 struct thread_entry *w;
2421 int oldlevel;
2423 /* Interrupts can access the lists that will be used - disable them */
2424 unsigned state = GET_THREAD_STATE(current);
2426 if (core == new_core)
2428 /* No change - just unlock everything and return same core */
2429 UNLOCK_THREAD(current, state);
2430 return core;
2433 /* Get us off the running list for the current core */
2434 remove_from_list_l(&cores[core].running, current);
2436 /* Stash return value (old core) in a safe place */
2437 current->retval = core;
2439 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2440 * the other core will likely attempt a removal from the wrong list! */
2441 if (current->tmo.prev != NULL)
2443 remove_from_list_tmo(current);
2446 /* Change the core number for this thread slot */
2447 current->core = new_core;
2449 /* Do not use core_schedule_wakeup here since this will result in
2450 * the thread starting to run on the other core before being finished on
2451 * this one. Delay the wakeup list unlock to keep the other core stuck
2452 * until this thread is ready. */
2453 oldlevel = set_irq_level(HIGHEST_IRQ_LEVEL);
2454 w = LOCK_LIST(&cores[new_core].waking);
2455 ADD_TO_LIST_L_SELECT(w, &cores[new_core].waking, current);
2457 /* Make a callback into device-specific code, unlock the wakeup list so
2458 * that execution may resume on the new core, unlock our slot and finally
2459 * restore the interrupt level */
2460 cores[core].blk_ops.flags = TBOP_SWITCH_CORE | TBOP_UNLOCK_CURRENT |
2461 TBOP_UNLOCK_LIST | TBOP_IRQ_LEVEL;
2462 cores[core].blk_ops.irq_level = oldlevel;
2463 cores[core].blk_ops.list_p = &cores[new_core].waking;
2464 #if CONFIG_CORELOCK == CORELOCK_SWAP
2465 cores[core].blk_ops.state = STATE_RUNNING;
2466 cores[core].blk_ops.list_v = w;
2467 #endif
2469 #ifdef HAVE_PRIORITY_SCHEDULING
2470 current->priority_x = HIGHEST_PRIORITY;
2471 cores[core].highest_priority = LOWEST_PRIORITY;
2472 #endif
2473 /* Do the stack switching, cache_maintenence and switch_thread call -
2474 requires native code */
2475 switch_thread_core(core, current);
2477 #ifdef HAVE_PRIORITY_SCHEDULING
2478 current->priority_x = LOWEST_PRIORITY;
2479 cores[current->core].highest_priority = LOWEST_PRIORITY;
2480 #endif
2482 /* Finally return the old core to caller */
2483 return current->retval;
2484 (void)state;
2486 #endif /* NUM_CORES > 1 */
2488 /*---------------------------------------------------------------------------
2489 * Initialize threading API. This assumes interrupts are not yet enabled. On
2490 * multicore setups, no core is allowed to proceed until create_thread calls
2491 * are safe to perform.
2492 *---------------------------------------------------------------------------
2494 void init_threads(void)
2496 const unsigned int core = CURRENT_CORE;
2497 struct thread_entry *thread;
2498 int slot;
2500 /* CPU will initialize first and then sleep */
2501 slot = find_empty_thread_slot();
2503 if (slot >= MAXTHREADS)
2505 /* WTF? There really must be a slot available at this stage.
2506 * This can fail if, for example, .bss isn't zero'ed out by the loader
2507 * or threads is in the wrong section. */
2508 THREAD_PANICF("init_threads->no slot", NULL);
2511 /* Initialize initially non-zero members of core */
2512 thread_queue_init(&cores[core].waking);
2513 cores[core].next_tmo_check = current_tick; /* Something not in the past */
2514 #if NUM_CORES == 1
2515 cores[core].irq_level = STAY_IRQ_LEVEL;
2516 #endif
2517 #ifdef HAVE_PRIORITY_SCHEDULING
2518 cores[core].highest_priority = LOWEST_PRIORITY;
2519 #endif
2521 /* Initialize initially non-zero members of slot */
2522 thread = &threads[slot];
2523 thread->name = main_thread_name;
2524 UNLOCK_THREAD_SET_STATE(thread, STATE_RUNNING); /* No sync worries yet */
2525 #if NUM_CORES > 1
2526 thread->core = core;
2527 #endif
2528 #ifdef HAVE_PRIORITY_SCHEDULING
2529 thread->priority = PRIORITY_USER_INTERFACE;
2530 thread->priority_x = LOWEST_PRIORITY;
2531 #endif
2532 #if CONFIG_CORELOCK == SW_CORELOCK
2533 corelock_init(&thread->cl);
2534 #endif
2536 add_to_list_l(&cores[core].running, thread);
2538 if (core == CPU)
2540 thread->stack = stackbegin;
2541 thread->stack_size = (int)stackend - (int)stackbegin;
2542 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2543 /* TODO: HAL interface for this */
2544 /* Wake up coprocessor and let it initialize kernel and threads */
2545 MBX_MSG_CLR = 0x3f;
2546 COP_CTL = PROC_WAKE;
2547 /* Sleep until finished */
2548 CPU_CTL = PROC_SLEEP;
2550 else
2552 /* Initial stack is the COP idle stack */
2553 thread->stack = cop_idlestackbegin;
2554 thread->stack_size = IDLE_STACK_SIZE;
2555 /* Get COP safely primed inside switch_thread where it will remain
2556 * until a thread actually exists on it */
2557 CPU_CTL = PROC_WAKE;
2558 remove_thread(NULL);
2559 #endif /* NUM_CORES */
2563 /*---------------------------------------------------------------------------
2564 * Returns the maximum percentage of stack a thread ever used while running.
2565 * NOTE: Some large buffer allocations that don't use enough the buffer to
2566 * overwrite stackptr[0] will not be seen.
2567 *---------------------------------------------------------------------------
2569 int thread_stack_usage(const struct thread_entry *thread)
2571 unsigned int *stackptr = thread->stack;
2572 int stack_words = thread->stack_size / sizeof (int);
2573 int i, usage = 0;
2575 for (i = 0; i < stack_words; i++)
2577 if (stackptr[i] != DEADBEEF)
2579 usage = ((stack_words - i) * 100) / stack_words;
2580 break;
2584 return usage;
2587 #if NUM_CORES > 1
2588 /*---------------------------------------------------------------------------
2589 * Returns the maximum percentage of the core's idle stack ever used during
2590 * runtime.
2591 *---------------------------------------------------------------------------
2593 int idle_stack_usage(unsigned int core)
2595 unsigned int *stackptr = idle_stacks[core];
2596 int i, usage = 0;
2598 for (i = 0; i < IDLE_STACK_WORDS; i++)
2600 if (stackptr[i] != DEADBEEF)
2602 usage = ((IDLE_STACK_WORDS - i) * 100) / IDLE_STACK_WORDS;
2603 break;
2607 return usage;
2609 #endif
2611 /*---------------------------------------------------------------------------
2612 * Returns the current thread status. This is a snapshot for debugging and
2613 * does not do any slot synchronization so it could return STATE_BUSY.
2614 *---------------------------------------------------------------------------
2616 unsigned thread_get_status(const struct thread_entry *thread)
2618 return thread->state;
2621 /*---------------------------------------------------------------------------
2622 * Fills in the buffer with the specified thread's name. If the name is NULL,
2623 * empty, or the thread is in destruct state a formatted ID is written
2624 * instead.
2625 *---------------------------------------------------------------------------
2627 void thread_get_name(char *buffer, int size,
2628 struct thread_entry *thread)
2630 if (size <= 0)
2631 return;
2633 *buffer = '\0';
2635 if (thread)
2637 /* Display thread name if one or ID if none */
2638 const char *name = thread->name;
2639 const char *fmt = "%s";
2640 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
2642 name = (const char *)thread;
2643 fmt = "%08lX";
2645 snprintf(buffer, size, fmt, name);