D2/Touchscreen keymap improvements: onscreen keyboard is now usable; PLAY/pause now...
[kugel-rb.git] / firmware / thread.c
blob4e22c516899d2bba2fffa2657668002585af3c5b
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)
781 static inline void core_sleep(void)
783 /* Single core only for now. Use the generic ARMv5 wait for IRQ */
784 asm volatile (
785 "mov r0, #0 \n"
786 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
787 : : : "r0"
789 enable_irq();
791 #elif CONFIG_CPU == IMX31L
792 static inline void core_sleep(void)
794 asm volatile (
795 "mov r0, #0 \n"
796 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
797 : : : "r0"
799 enable_irq();
801 #elif CONFIG_CPU == DM320
802 static inline void core_sleep(void)
804 asm volatile (
805 "mov r0, #0 \n"
806 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
807 : : : "r0"
809 enable_irq();
811 #else
812 static inline void core_sleep(void)
814 #warning core_sleep not implemented, battery life will be decreased
815 enable_irq();
817 #endif /* CONFIG_CPU == */
819 #elif defined(CPU_COLDFIRE)
820 /*---------------------------------------------------------------------------
821 * Start the thread running and terminate it if it returns
822 *---------------------------------------------------------------------------
824 void start_thread(void); /* Provide C access to ASM label */
825 static void __attribute__((used)) __start_thread(void)
827 /* a0=macsr, a1=context */
828 asm volatile (
829 "start_thread: \n" /* Start here - no naked attribute */
830 "move.l %a0, %macsr \n" /* Set initial mac status reg */
831 "lea.l 48(%a1), %a1 \n"
832 "move.l (%a1)+, %sp \n" /* Set initial stack */
833 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
834 "clr.l (%a1) \n" /* Mark thread running */
835 "jsr (%a2) \n" /* Call thread function */
837 thread_exit();
840 /* Set EMAC unit to fractional mode with saturation for each new thread,
841 * since that's what'll be the most useful for most things which the dsp
842 * will do. Codecs should still initialize their preferred modes
843 * explicitly. Context pointer is placed in d2 slot and start_thread
844 * pointer in d3 slot. thread function pointer is placed in context.start.
845 * See load_context for what happens when thread is initially going to
846 * run.
848 #define THREAD_STARTUP_INIT(core, thread, function) \
849 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
850 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
851 (thread)->context.d[1] = (uint32_t)start_thread, \
852 (thread)->context.start = (uint32_t)(function); })
854 /*---------------------------------------------------------------------------
855 * Store non-volatile context.
856 *---------------------------------------------------------------------------
858 static inline void store_context(void* addr)
860 asm volatile (
861 "move.l %%macsr,%%d0 \n"
862 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
863 : : "a" (addr) : "d0" /* only! */
867 /*---------------------------------------------------------------------------
868 * Load non-volatile context.
869 *---------------------------------------------------------------------------
871 static inline void load_context(const void* addr)
873 asm volatile (
874 "move.l 52(%0), %%d0 \n" /* Get start address */
875 "beq.b 1f \n" /* NULL -> already running */
876 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
877 "jmp (%%a2) \n" /* Start the thread */
878 "1: \n"
879 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
880 "move.l %%d0, %%macsr \n"
881 : : "a" (addr) : "d0" /* only! */
885 /*---------------------------------------------------------------------------
886 * Put core in a power-saving state if waking list wasn't repopulated.
887 *---------------------------------------------------------------------------
889 static inline void core_sleep(void)
891 /* Supervisor mode, interrupts enabled upon wakeup */
892 asm volatile ("stop #0x2000");
895 #elif CONFIG_CPU == SH7034
896 /*---------------------------------------------------------------------------
897 * Start the thread running and terminate it if it returns
898 *---------------------------------------------------------------------------
900 void start_thread(void); /* Provide C access to ASM label */
901 static void __attribute__((used)) __start_thread(void)
903 /* r8 = context */
904 asm volatile (
905 "_start_thread: \n" /* Start here - no naked attribute */
906 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
907 "mov.l @(28, r8), r15 \n" /* Set initial sp */
908 "mov #0, r1 \n" /* Start the thread */
909 "jsr @r0 \n"
910 "mov.l r1, @(36, r8) \n" /* Clear start address */
912 thread_exit();
915 /* Place context pointer in r8 slot, function pointer in r9 slot, and
916 * start_thread pointer in context_start */
917 #define THREAD_STARTUP_INIT(core, thread, function) \
918 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
919 (thread)->context.r[1] = (uint32_t)(function), \
920 (thread)->context.start = (uint32_t)start_thread; })
922 /*---------------------------------------------------------------------------
923 * Store non-volatile context.
924 *---------------------------------------------------------------------------
926 static inline void store_context(void* addr)
928 asm volatile (
929 "add #36, %0 \n" /* Start at last reg. By the time routine */
930 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
931 "mov.l r15,@-%0 \n"
932 "mov.l r14,@-%0 \n"
933 "mov.l r13,@-%0 \n"
934 "mov.l r12,@-%0 \n"
935 "mov.l r11,@-%0 \n"
936 "mov.l r10,@-%0 \n"
937 "mov.l r9, @-%0 \n"
938 "mov.l r8, @-%0 \n"
939 : : "r" (addr)
943 /*---------------------------------------------------------------------------
944 * Load non-volatile context.
945 *---------------------------------------------------------------------------
947 static inline void load_context(const void* addr)
949 asm volatile (
950 "mov.l @(36, %0), r0 \n" /* Get start address */
951 "tst r0, r0 \n"
952 "bt .running \n" /* NULL -> already running */
953 "jmp @r0 \n" /* r8 = context */
954 ".running: \n"
955 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
956 "mov.l @%0+, r9 \n"
957 "mov.l @%0+, r10 \n"
958 "mov.l @%0+, r11 \n"
959 "mov.l @%0+, r12 \n"
960 "mov.l @%0+, r13 \n"
961 "mov.l @%0+, r14 \n"
962 "mov.l @%0+, r15 \n"
963 "lds.l @%0+, pr \n"
964 : : "r" (addr) : "r0" /* only! */
968 /*---------------------------------------------------------------------------
969 * Put core in a power-saving state.
970 *---------------------------------------------------------------------------
972 static inline void core_sleep(void)
974 asm volatile (
975 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
976 "mov #0, r1 \n" /* Enable interrupts */
977 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
978 "sleep \n" /* Execute standby */
979 : : "z"(&SBYCR-GBR) : "r1");
982 #elif CPU_MIPS == 32
984 /*---------------------------------------------------------------------------
985 * Start the thread running and terminate it if it returns
986 *---------------------------------------------------------------------------
989 void start_thread(void); /* Provide C access to ASM label */
990 static void __attribute__((used)) _start_thread(void)
993 /* $t1 = context */
994 asm volatile (
995 "start_thread: \n"
996 ".set noreorder \n"
997 ".set noat \n"
998 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = $t0, $9 = $t1) */
999 "lw $29, 40($9) \n" /* Set initial sp(=$29) */
1000 "sw $0, 48($9) \n" /* Clear start address */
1001 "jalr $8 \n" /* Start the thread */
1002 "nop \n"
1003 ".set at \n"
1004 ".set reorder \n"
1006 thread_exit();
1010 /* Place context pointer in $s0 slot, function pointer in $s1 slot, and
1011 * start_thread pointer in context_start */
1012 #define THREAD_STARTUP_INIT(core, thread, function) \
1013 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
1014 (thread)->context.r[1] = (uint32_t)(function), \
1015 (thread)->context.start = (uint32_t)start_thread; })
1017 /*---------------------------------------------------------------------------
1018 * Store non-volatile context.
1019 *---------------------------------------------------------------------------
1021 static inline void store_context(void* addr)
1023 asm volatile (
1024 ".set noreorder \n"
1025 ".set noat \n"
1026 "move $8, %0 \n"
1027 "sw $16, 0($8) \n" /* $s0 */
1028 "sw $17, 4($8) \n" /* $s1 */
1029 "sw $18, 8($8) \n" /* $s2 */
1030 "sw $19, 12($8) \n" /* $s3 */
1031 "sw $20, 16($8) \n" /* $s4 */
1032 "sw $21, 20($8) \n" /* $s5 */
1033 "sw $22, 24($8) \n" /* $s6 */
1034 "sw $23, 28($8) \n" /* $s7 */
1035 "sw $28, 32($8) \n" /* gp */
1036 "sw $30, 36($8) \n" /* fp */
1037 "sw $29, 40($8) \n" /* sp */
1038 "sw $31, 44($8) \n" /* ra */
1039 ".set at \n"
1040 ".set reorder \n"
1041 : : "r" (addr) : "t0"
1045 /*---------------------------------------------------------------------------
1046 * Load non-volatile context.
1047 *---------------------------------------------------------------------------
1049 static inline void load_context(const void* addr)
1051 asm volatile (
1052 ".set noat \n"
1053 ".set noreorder \n"
1054 "lw $8, 48(%0) \n" /* Get start address ($8 = $t0) */
1055 "beqz $8, running \n" /* NULL -> already running */
1056 "nop \n"
1057 "move $9, %0 \n" /* $t1 = context */
1058 "jr $8 \n"
1059 "nop \n"
1060 "running: \n"
1061 "move $8, %0 \n"
1062 "lw $16, 0($8) \n" /* $s0 */
1063 "lw $17, 4($8) \n" /* $s1 */
1064 "lw $18, 8($8) \n" /* $s2 */
1065 "lw $19, 12($8) \n" /* $s3 */
1066 "lw $20, 16($8) \n" /* $s4 */
1067 "lw $21, 20($8) \n" /* $s5 */
1068 "lw $22, 24($8) \n" /* $s6 */
1069 "lw $23, 28($8) \n" /* $s7 */
1070 "lw $28, 32($8) \n" /* gp */
1071 "lw $30, 36($8) \n" /* fp */
1072 "lw $29, 40($8) \n" /* sp */
1073 "lw $31, 44($8) \n" /* ra */
1074 ".set at \n"
1075 ".set reorder \n"
1076 : : "r" (addr) : "t0" /* only! */
1080 /*---------------------------------------------------------------------------
1081 * Put core in a power-saving state.
1082 *---------------------------------------------------------------------------
1084 static inline void core_sleep(void)
1086 #if CONFIG_CPU == JZ4732
1087 REG_CPM_LCR &= ~CPM_LCR_LPM_MASK;
1088 REG_CPM_LCR |= CPM_LCR_LPM_SLEEP;
1089 #endif
1090 asm volatile(".set mips32r2 \n"
1091 "mfc0 $8, $12 \n" /* mfc $t0, $12 */
1092 "move $9, $8 \n" /* move $t1, $t0 */
1093 "la $10, 0x8000000 \n" /* la $t2, 0x8000000 */
1094 "or $8, $8, $10 \n" /* Enable reduced power mode */
1095 "mtc0 $8, $12 \n"
1096 "wait \n"
1097 "mtc0 $9, $12 \n"
1098 ".set mips0 \n"
1099 ::: "t0", "t1", "t2"
1101 #if CONFIG_CPU == JZ4732
1102 REG_CPM_LCR &= ~CPM_LCR_LPM_MASK;
1103 REG_CPM_LCR |= CPM_LCR_LPM_IDLE;
1104 #endif
1108 #endif /* CONFIG_CPU == */
1111 * End Processor-specific section
1112 ***************************************************************************/
1114 #if THREAD_EXTRA_CHECKS
1115 static void thread_panicf(const char *msg, struct thread_entry *thread)
1117 IF_COP( const unsigned int core = thread->core; )
1118 static char name[32];
1119 thread_get_name(name, 32, thread);
1120 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1122 static void thread_stkov(struct thread_entry *thread)
1124 thread_panicf("Stkov", thread);
1126 #define THREAD_PANICF(msg, thread) \
1127 thread_panicf(msg, thread)
1128 #define THREAD_ASSERT(exp, msg, thread) \
1129 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1130 #else
1131 static void thread_stkov(struct thread_entry *thread)
1133 IF_COP( const unsigned int core = thread->core; )
1134 static char name[32];
1135 thread_get_name(name, 32, thread);
1136 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1138 #define THREAD_PANICF(msg, thread)
1139 #define THREAD_ASSERT(exp, msg, thread)
1140 #endif /* THREAD_EXTRA_CHECKS */
1142 /* Thread locking */
1143 #if NUM_CORES > 1
1144 #define LOCK_THREAD(thread) \
1145 ({ corelock_lock(&(thread)->slot_cl); })
1146 #define TRY_LOCK_THREAD(thread) \
1147 ({ corelock_try_lock(&thread->slot_cl); })
1148 #define UNLOCK_THREAD(thread) \
1149 ({ corelock_unlock(&(thread)->slot_cl); })
1150 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1151 ({ unsigned int _core = (thread)->core; \
1152 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1153 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1154 #else
1155 #define LOCK_THREAD(thread) \
1156 ({ })
1157 #define TRY_LOCK_THREAD(thread) \
1158 ({ })
1159 #define UNLOCK_THREAD(thread) \
1160 ({ })
1161 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1162 ({ })
1163 #endif
1165 /* RTR list */
1166 #define RTR_LOCK(core) \
1167 ({ corelock_lock(&cores[core].rtr_cl); })
1168 #define RTR_UNLOCK(core) \
1169 ({ corelock_unlock(&cores[core].rtr_cl); })
1171 #ifdef HAVE_PRIORITY_SCHEDULING
1172 #define rtr_add_entry(core, priority) \
1173 prio_add_entry(&cores[core].rtr, (priority))
1175 #define rtr_subtract_entry(core, priority) \
1176 prio_subtract_entry(&cores[core].rtr, (priority))
1178 #define rtr_move_entry(core, from, to) \
1179 prio_move_entry(&cores[core].rtr, (from), (to))
1180 #else
1181 #define rtr_add_entry(core, priority)
1182 #define rtr_add_entry_inl(core, priority)
1183 #define rtr_subtract_entry(core, priority)
1184 #define rtr_subtract_entry_inl(core, priotity)
1185 #define rtr_move_entry(core, from, to)
1186 #define rtr_move_entry_inl(core, from, to)
1187 #endif
1189 /*---------------------------------------------------------------------------
1190 * Thread list structure - circular:
1191 * +------------------------------+
1192 * | |
1193 * +--+---+<-+---+<-+---+<-+---+<-+
1194 * Head->| T | | T | | T | | T |
1195 * +->+---+->+---+->+---+->+---+--+
1196 * | |
1197 * +------------------------------+
1198 *---------------------------------------------------------------------------
1201 /*---------------------------------------------------------------------------
1202 * Adds a thread to a list of threads using "insert last". Uses the "l"
1203 * links.
1204 *---------------------------------------------------------------------------
1206 static void add_to_list_l(struct thread_entry **list,
1207 struct thread_entry *thread)
1209 struct thread_entry *l = *list;
1211 if (l == NULL)
1213 /* Insert into unoccupied list */
1214 thread->l.prev = thread;
1215 thread->l.next = thread;
1216 *list = thread;
1217 return;
1220 /* Insert last */
1221 thread->l.prev = l->l.prev;
1222 thread->l.next = l;
1223 l->l.prev->l.next = thread;
1224 l->l.prev = thread;
1227 /*---------------------------------------------------------------------------
1228 * Removes a thread from a list of threads. Uses the "l" links.
1229 *---------------------------------------------------------------------------
1231 static void remove_from_list_l(struct thread_entry **list,
1232 struct thread_entry *thread)
1234 struct thread_entry *prev, *next;
1236 next = thread->l.next;
1238 if (thread == next)
1240 /* The only item */
1241 *list = NULL;
1242 return;
1245 if (thread == *list)
1247 /* List becomes next item */
1248 *list = next;
1251 prev = thread->l.prev;
1253 /* Fix links to jump over the removed entry. */
1254 next->l.prev = prev;
1255 prev->l.next = next;
1258 /*---------------------------------------------------------------------------
1259 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1260 * NULL-terminated forward (to ease the far more common forward traversal):
1261 * +------------------------------+
1262 * | |
1263 * +--+---+<-+---+<-+---+<-+---+<-+
1264 * Head->| T | | T | | T | | T |
1265 * +---+->+---+->+---+->+---+-X
1266 *---------------------------------------------------------------------------
1269 /*---------------------------------------------------------------------------
1270 * Add a thread from the core's timout list by linking the pointers in its
1271 * tmo structure.
1272 *---------------------------------------------------------------------------
1274 static void add_to_list_tmo(struct thread_entry *thread)
1276 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1277 THREAD_ASSERT(thread->tmo.prev == NULL,
1278 "add_to_list_tmo->already listed", thread);
1280 thread->tmo.next = NULL;
1282 if (tmo == NULL)
1284 /* Insert into unoccupied list */
1285 thread->tmo.prev = thread;
1286 cores[IF_COP_CORE(thread->core)].timeout = thread;
1287 return;
1290 /* Insert Last */
1291 thread->tmo.prev = tmo->tmo.prev;
1292 tmo->tmo.prev->tmo.next = thread;
1293 tmo->tmo.prev = thread;
1296 /*---------------------------------------------------------------------------
1297 * Remove a thread from the core's timout list by unlinking the pointers in
1298 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1299 * is cancelled.
1300 *---------------------------------------------------------------------------
1302 static void remove_from_list_tmo(struct thread_entry *thread)
1304 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1305 struct thread_entry *prev = thread->tmo.prev;
1306 struct thread_entry *next = thread->tmo.next;
1308 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1310 if (next != NULL)
1311 next->tmo.prev = prev;
1313 if (thread == *list)
1315 /* List becomes next item and empty if next == NULL */
1316 *list = next;
1317 /* Mark as unlisted */
1318 thread->tmo.prev = NULL;
1320 else
1322 if (next == NULL)
1323 (*list)->tmo.prev = prev;
1324 prev->tmo.next = next;
1325 /* Mark as unlisted */
1326 thread->tmo.prev = NULL;
1331 #ifdef HAVE_PRIORITY_SCHEDULING
1332 /*---------------------------------------------------------------------------
1333 * Priority distribution structure (one category for each possible priority):
1335 * +----+----+----+ ... +-----+
1336 * hist: | F0 | F1 | F2 | | F31 |
1337 * +----+----+----+ ... +-----+
1338 * mask: | b0 | b1 | b2 | | b31 |
1339 * +----+----+----+ ... +-----+
1341 * F = count of threads at priority category n (frequency)
1342 * b = bitmask of non-zero priority categories (occupancy)
1344 * / if H[n] != 0 : 1
1345 * b[n] = |
1346 * \ else : 0
1348 *---------------------------------------------------------------------------
1349 * Basic priority inheritance priotocol (PIP):
1351 * Mn = mutex n, Tn = thread n
1353 * A lower priority thread inherits the priority of the highest priority
1354 * thread blocked waiting for it to complete an action (such as release a
1355 * mutex or respond to a message via queue_send):
1357 * 1) T2->M1->T1
1359 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1360 * priority than T1 then T1 inherits the priority of T2.
1362 * 2) T3
1363 * \/
1364 * T2->M1->T1
1366 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1367 * T1 inherits the higher of T2 and T3.
1369 * 3) T3->M2->T2->M1->T1
1371 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1372 * then T1 inherits the priority of T3 through T2.
1374 * Blocking chains can grow arbitrarily complex (though it's best that they
1375 * not form at all very often :) and build-up from these units.
1376 *---------------------------------------------------------------------------
1379 /*---------------------------------------------------------------------------
1380 * Increment frequency at category "priority"
1381 *---------------------------------------------------------------------------
1383 static inline unsigned int prio_add_entry(
1384 struct priority_distribution *pd, int priority)
1386 unsigned int count;
1387 /* Enough size/instruction count difference for ARM makes it worth it to
1388 * use different code (192 bytes for ARM). Only thing better is ASM. */
1389 #ifdef CPU_ARM
1390 count = pd->hist[priority];
1391 if (++count == 1)
1392 pd->mask |= 1 << priority;
1393 pd->hist[priority] = count;
1394 #else /* This one's better for Coldfire */
1395 if ((count = ++pd->hist[priority]) == 1)
1396 pd->mask |= 1 << priority;
1397 #endif
1399 return count;
1402 /*---------------------------------------------------------------------------
1403 * Decrement frequency at category "priority"
1404 *---------------------------------------------------------------------------
1406 static inline unsigned int prio_subtract_entry(
1407 struct priority_distribution *pd, int priority)
1409 unsigned int count;
1411 #ifdef CPU_ARM
1412 count = pd->hist[priority];
1413 if (--count == 0)
1414 pd->mask &= ~(1 << priority);
1415 pd->hist[priority] = count;
1416 #else
1417 if ((count = --pd->hist[priority]) == 0)
1418 pd->mask &= ~(1 << priority);
1419 #endif
1421 return count;
1424 /*---------------------------------------------------------------------------
1425 * Remove from one category and add to another
1426 *---------------------------------------------------------------------------
1428 static inline void prio_move_entry(
1429 struct priority_distribution *pd, int from, int to)
1431 uint32_t mask = pd->mask;
1433 #ifdef CPU_ARM
1434 unsigned int count;
1436 count = pd->hist[from];
1437 if (--count == 0)
1438 mask &= ~(1 << from);
1439 pd->hist[from] = count;
1441 count = pd->hist[to];
1442 if (++count == 1)
1443 mask |= 1 << to;
1444 pd->hist[to] = count;
1445 #else
1446 if (--pd->hist[from] == 0)
1447 mask &= ~(1 << from);
1449 if (++pd->hist[to] == 1)
1450 mask |= 1 << to;
1451 #endif
1453 pd->mask = mask;
1456 /*---------------------------------------------------------------------------
1457 * Change the priority and rtr entry for a running thread
1458 *---------------------------------------------------------------------------
1460 static inline void set_running_thread_priority(
1461 struct thread_entry *thread, int priority)
1463 const unsigned int core = IF_COP_CORE(thread->core);
1464 RTR_LOCK(core);
1465 rtr_move_entry(core, thread->priority, priority);
1466 thread->priority = priority;
1467 RTR_UNLOCK(core);
1470 /*---------------------------------------------------------------------------
1471 * Finds the highest priority thread in a list of threads. If the list is
1472 * empty, the PRIORITY_IDLE is returned.
1474 * It is possible to use the struct priority_distribution within an object
1475 * instead of scanning the remaining threads in the list but as a compromise,
1476 * the resulting per-object memory overhead is saved at a slight speed
1477 * penalty under high contention.
1478 *---------------------------------------------------------------------------
1480 static int find_highest_priority_in_list_l(
1481 struct thread_entry * const thread)
1483 if (thread != NULL)
1485 /* Go though list until the ending up at the initial thread */
1486 int highest_priority = thread->priority;
1487 struct thread_entry *curr = thread;
1491 int priority = curr->priority;
1493 if (priority < highest_priority)
1494 highest_priority = priority;
1496 curr = curr->l.next;
1498 while (curr != thread);
1500 return highest_priority;
1503 return PRIORITY_IDLE;
1506 /*---------------------------------------------------------------------------
1507 * Register priority with blocking system and bubble it down the chain if
1508 * any until we reach the end or something is already equal or higher.
1510 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1511 * targets but that same action also guarantees a circular block anyway and
1512 * those are prevented, right? :-)
1513 *---------------------------------------------------------------------------
1515 static struct thread_entry *
1516 blocker_inherit_priority(struct thread_entry *current)
1518 const int priority = current->priority;
1519 struct blocker *bl = current->blocker;
1520 struct thread_entry * const tstart = current;
1521 struct thread_entry *bl_t = bl->thread;
1523 /* Blocker cannot change since the object protection is held */
1524 LOCK_THREAD(bl_t);
1526 for (;;)
1528 struct thread_entry *next;
1529 int bl_pr = bl->priority;
1531 if (priority >= bl_pr)
1532 break; /* Object priority already high enough */
1534 bl->priority = priority;
1536 /* Add this one */
1537 prio_add_entry(&bl_t->pdist, priority);
1539 if (bl_pr < PRIORITY_IDLE)
1541 /* Not first waiter - subtract old one */
1542 prio_subtract_entry(&bl_t->pdist, bl_pr);
1545 if (priority >= bl_t->priority)
1546 break; /* Thread priority high enough */
1548 if (bl_t->state == STATE_RUNNING)
1550 /* Blocking thread is a running thread therefore there are no
1551 * further blockers. Change the "run queue" on which it
1552 * resides. */
1553 set_running_thread_priority(bl_t, priority);
1554 break;
1557 bl_t->priority = priority;
1559 /* If blocking thread has a blocker, apply transitive inheritance */
1560 bl = bl_t->blocker;
1562 if (bl == NULL)
1563 break; /* End of chain or object doesn't support inheritance */
1565 next = bl->thread;
1567 if (next == tstart)
1568 break; /* Full-circle - deadlock! */
1570 UNLOCK_THREAD(current);
1572 #if NUM_CORES > 1
1573 for (;;)
1575 LOCK_THREAD(next);
1577 /* Blocker could change - retest condition */
1578 if (bl->thread == next)
1579 break;
1581 UNLOCK_THREAD(next);
1582 next = bl->thread;
1584 #endif
1585 current = bl_t;
1586 bl_t = next;
1589 UNLOCK_THREAD(bl_t);
1591 return current;
1594 /*---------------------------------------------------------------------------
1595 * Readjust priorities when waking a thread blocked waiting for another
1596 * in essence "releasing" the thread's effect on the object owner. Can be
1597 * performed from any context.
1598 *---------------------------------------------------------------------------
1600 struct thread_entry *
1601 wakeup_priority_protocol_release(struct thread_entry *thread)
1603 const int priority = thread->priority;
1604 struct blocker *bl = thread->blocker;
1605 struct thread_entry * const tstart = thread;
1606 struct thread_entry *bl_t = bl->thread;
1608 /* Blocker cannot change since object will be locked */
1609 LOCK_THREAD(bl_t);
1611 thread->blocker = NULL; /* Thread not blocked */
1613 for (;;)
1615 struct thread_entry *next;
1616 int bl_pr = bl->priority;
1618 if (priority > bl_pr)
1619 break; /* Object priority higher */
1621 next = *thread->bqp;
1623 if (next == NULL)
1625 /* No more threads in queue */
1626 prio_subtract_entry(&bl_t->pdist, bl_pr);
1627 bl->priority = PRIORITY_IDLE;
1629 else
1631 /* Check list for highest remaining priority */
1632 int queue_pr = find_highest_priority_in_list_l(next);
1634 if (queue_pr == bl_pr)
1635 break; /* Object priority not changing */
1637 /* Change queue priority */
1638 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1639 bl->priority = queue_pr;
1642 if (bl_pr > bl_t->priority)
1643 break; /* thread priority is higher */
1645 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1647 if (bl_pr == bl_t->priority)
1648 break; /* Thread priority not changing */
1650 if (bl_t->state == STATE_RUNNING)
1652 /* No further blockers */
1653 set_running_thread_priority(bl_t, bl_pr);
1654 break;
1657 bl_t->priority = bl_pr;
1659 /* If blocking thread has a blocker, apply transitive inheritance */
1660 bl = bl_t->blocker;
1662 if (bl == NULL)
1663 break; /* End of chain or object doesn't support inheritance */
1665 next = bl->thread;
1667 if (next == tstart)
1668 break; /* Full-circle - deadlock! */
1670 UNLOCK_THREAD(thread);
1672 #if NUM_CORES > 1
1673 for (;;)
1675 LOCK_THREAD(next);
1677 /* Blocker could change - retest condition */
1678 if (bl->thread == next)
1679 break;
1681 UNLOCK_THREAD(next);
1682 next = bl->thread;
1684 #endif
1685 thread = bl_t;
1686 bl_t = next;
1689 UNLOCK_THREAD(bl_t);
1691 #if NUM_CORES > 1
1692 if (thread != tstart)
1694 /* Relock original if it changed */
1695 LOCK_THREAD(tstart);
1697 #endif
1699 return cores[CURRENT_CORE].running;
1702 /*---------------------------------------------------------------------------
1703 * Transfer ownership to a thread waiting for an objects and transfer
1704 * inherited priority boost from other waiters. This algorithm knows that
1705 * blocking chains may only unblock from the very end.
1707 * Only the owning thread itself may call this and so the assumption that
1708 * it is the running thread is made.
1709 *---------------------------------------------------------------------------
1711 struct thread_entry *
1712 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1714 /* Waking thread inherits priority boost from object owner */
1715 struct blocker *bl = thread->blocker;
1716 struct thread_entry *bl_t = bl->thread;
1717 struct thread_entry *next;
1718 int bl_pr;
1720 THREAD_ASSERT(thread_get_current() == bl_t,
1721 "UPPT->wrong thread", thread_get_current());
1723 LOCK_THREAD(bl_t);
1725 bl_pr = bl->priority;
1727 /* Remove the object's boost from the owning thread */
1728 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1729 bl_pr <= bl_t->priority)
1731 /* No more threads at this priority are waiting and the old level is
1732 * at least the thread level */
1733 int priority = find_first_set_bit(bl_t->pdist.mask);
1735 if (priority != bl_t->priority)
1737 /* Adjust this thread's priority */
1738 set_running_thread_priority(bl_t, priority);
1742 next = *thread->bqp;
1744 if (next == NULL)
1746 /* Expected shortcut - no more waiters */
1747 bl_pr = PRIORITY_IDLE;
1749 else
1751 if (thread->priority <= bl_pr)
1753 /* Need to scan threads remaining in queue */
1754 bl_pr = find_highest_priority_in_list_l(next);
1757 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1758 bl_pr < thread->priority)
1760 /* Thread priority must be raised */
1761 thread->priority = bl_pr;
1765 bl->thread = thread; /* This thread pwns */
1766 bl->priority = bl_pr; /* Save highest blocked priority */
1767 thread->blocker = NULL; /* Thread not blocked */
1769 UNLOCK_THREAD(bl_t);
1771 return bl_t;
1774 /*---------------------------------------------------------------------------
1775 * No threads must be blocked waiting for this thread except for it to exit.
1776 * The alternative is more elaborate cleanup and object registration code.
1777 * Check this for risk of silent data corruption when objects with
1778 * inheritable blocking are abandoned by the owner - not precise but may
1779 * catch something.
1780 *---------------------------------------------------------------------------
1782 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1784 /* Only one bit in the mask should be set with a frequency on 1 which
1785 * represents the thread's own base priority */
1786 uint32_t mask = thread->pdist.mask;
1787 if ((mask & (mask - 1)) != 0 ||
1788 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1790 unsigned char name[32];
1791 thread_get_name(name, 32, thread);
1792 panicf("%s->%s with obj. waiters", function, name);
1795 #endif /* HAVE_PRIORITY_SCHEDULING */
1797 /*---------------------------------------------------------------------------
1798 * Move a thread back to a running state on its core.
1799 *---------------------------------------------------------------------------
1801 static void core_schedule_wakeup(struct thread_entry *thread)
1803 const unsigned int core = IF_COP_CORE(thread->core);
1805 RTR_LOCK(core);
1807 thread->state = STATE_RUNNING;
1809 add_to_list_l(&cores[core].running, thread);
1810 rtr_add_entry(core, thread->priority);
1812 RTR_UNLOCK(core);
1814 #if NUM_CORES > 1
1815 if (core != CURRENT_CORE)
1816 core_wake(core);
1817 #endif
1820 /*---------------------------------------------------------------------------
1821 * Check the core's timeout list when at least one thread is due to wake.
1822 * Filtering for the condition is done before making the call. Resets the
1823 * tick when the next check will occur.
1824 *---------------------------------------------------------------------------
1826 void check_tmo_threads(void)
1828 const unsigned int core = CURRENT_CORE;
1829 const long tick = current_tick; /* snapshot the current tick */
1830 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1831 struct thread_entry *next = cores[core].timeout;
1833 /* If there are no processes waiting for a timeout, just keep the check
1834 tick from falling into the past. */
1836 /* Break the loop once we have walked through the list of all
1837 * sleeping processes or have removed them all. */
1838 while (next != NULL)
1840 /* Check sleeping threads. Allow interrupts between checks. */
1841 enable_irq();
1843 struct thread_entry *curr = next;
1845 next = curr->tmo.next;
1847 /* Lock thread slot against explicit wakeup */
1848 disable_irq();
1849 LOCK_THREAD(curr);
1851 unsigned state = curr->state;
1853 if (state < TIMEOUT_STATE_FIRST)
1855 /* Cleanup threads no longer on a timeout but still on the
1856 * list. */
1857 remove_from_list_tmo(curr);
1859 else if (TIME_BEFORE(tick, curr->tmo_tick))
1861 /* Timeout still pending - this will be the usual case */
1862 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1864 /* Earliest timeout found so far - move the next check up
1865 to its time */
1866 next_tmo_check = curr->tmo_tick;
1869 else
1871 /* Sleep timeout has been reached so bring the thread back to
1872 * life again. */
1873 if (state == STATE_BLOCKED_W_TMO)
1875 #if NUM_CORES > 1
1876 /* Lock the waiting thread's kernel object */
1877 struct corelock *ocl = curr->obj_cl;
1879 if (corelock_try_lock(ocl) == 0)
1881 /* Need to retry in the correct order though the need is
1882 * unlikely */
1883 UNLOCK_THREAD(curr);
1884 corelock_lock(ocl);
1885 LOCK_THREAD(curr);
1887 if (curr->state != STATE_BLOCKED_W_TMO)
1889 /* Thread was woken or removed explicitely while slot
1890 * was unlocked */
1891 corelock_unlock(ocl);
1892 remove_from_list_tmo(curr);
1893 UNLOCK_THREAD(curr);
1894 continue;
1897 #endif /* NUM_CORES */
1899 remove_from_list_l(curr->bqp, curr);
1901 #ifdef HAVE_WAKEUP_EXT_CB
1902 if (curr->wakeup_ext_cb != NULL)
1903 curr->wakeup_ext_cb(curr);
1904 #endif
1906 #ifdef HAVE_PRIORITY_SCHEDULING
1907 if (curr->blocker != NULL)
1908 wakeup_priority_protocol_release(curr);
1909 #endif
1910 corelock_unlock(ocl);
1912 /* else state == STATE_SLEEPING */
1914 remove_from_list_tmo(curr);
1916 RTR_LOCK(core);
1918 curr->state = STATE_RUNNING;
1920 add_to_list_l(&cores[core].running, curr);
1921 rtr_add_entry(core, curr->priority);
1923 RTR_UNLOCK(core);
1926 UNLOCK_THREAD(curr);
1929 cores[core].next_tmo_check = next_tmo_check;
1932 /*---------------------------------------------------------------------------
1933 * Performs operations that must be done before blocking a thread but after
1934 * the state is saved.
1935 *---------------------------------------------------------------------------
1937 #if NUM_CORES > 1
1938 static inline void run_blocking_ops(
1939 unsigned int core, struct thread_entry *thread)
1941 struct thread_blk_ops *ops = &cores[core].blk_ops;
1942 const unsigned flags = ops->flags;
1944 if (flags == TBOP_CLEAR)
1945 return;
1947 switch (flags)
1949 case TBOP_SWITCH_CORE:
1950 core_switch_blk_op(core, thread);
1951 /* Fall-through */
1952 case TBOP_UNLOCK_CORELOCK:
1953 corelock_unlock(ops->cl_p);
1954 break;
1957 ops->flags = TBOP_CLEAR;
1959 #endif /* NUM_CORES > 1 */
1961 #ifdef RB_PROFILE
1962 void profile_thread(void)
1964 profstart(cores[CURRENT_CORE].running - threads);
1966 #endif
1968 /*---------------------------------------------------------------------------
1969 * Prepares a thread to block on an object's list and/or for a specified
1970 * duration - expects object and slot to be appropriately locked if needed
1971 * and interrupts to be masked.
1972 *---------------------------------------------------------------------------
1974 static inline void block_thread_on_l(struct thread_entry *thread,
1975 unsigned state)
1977 /* If inlined, unreachable branches will be pruned with no size penalty
1978 because state is passed as a constant parameter. */
1979 const unsigned int core = IF_COP_CORE(thread->core);
1981 /* Remove the thread from the list of running threads. */
1982 RTR_LOCK(core);
1983 remove_from_list_l(&cores[core].running, thread);
1984 rtr_subtract_entry(core, thread->priority);
1985 RTR_UNLOCK(core);
1987 /* Add a timeout to the block if not infinite */
1988 switch (state)
1990 case STATE_BLOCKED:
1991 case STATE_BLOCKED_W_TMO:
1992 /* Put the thread into a new list of inactive threads. */
1993 add_to_list_l(thread->bqp, thread);
1995 if (state == STATE_BLOCKED)
1996 break;
1998 /* Fall-through */
1999 case STATE_SLEEPING:
2000 /* If this thread times out sooner than any other thread, update
2001 next_tmo_check to its timeout */
2002 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
2004 cores[core].next_tmo_check = thread->tmo_tick;
2007 if (thread->tmo.prev == NULL)
2009 add_to_list_tmo(thread);
2011 /* else thread was never removed from list - just keep it there */
2012 break;
2015 /* Remember the the next thread about to block. */
2016 cores[core].block_task = thread;
2018 /* Report new state. */
2019 thread->state = state;
2022 /*---------------------------------------------------------------------------
2023 * Switch thread in round robin fashion for any given priority. Any thread
2024 * that removed itself from the running list first must specify itself in
2025 * the paramter.
2027 * INTERNAL: Intended for use by kernel and not for programs.
2028 *---------------------------------------------------------------------------
2030 void switch_thread(void)
2033 const unsigned int core = CURRENT_CORE;
2034 struct thread_entry *block = cores[core].block_task;
2035 struct thread_entry *thread = cores[core].running;
2037 /* Get context to save - next thread to run is unknown until all wakeups
2038 * are evaluated */
2039 if (block != NULL)
2041 cores[core].block_task = NULL;
2043 #if NUM_CORES > 1
2044 if (thread == block)
2046 /* This was the last thread running and another core woke us before
2047 * reaching here. Force next thread selection to give tmo threads or
2048 * other threads woken before this block a first chance. */
2049 block = NULL;
2051 else
2052 #endif
2054 /* Blocking task is the old one */
2055 thread = block;
2059 #ifdef RB_PROFILE
2060 profile_thread_stopped(thread - threads);
2061 #endif
2063 /* Begin task switching by saving our current context so that we can
2064 * restore the state of the current thread later to the point prior
2065 * to this call. */
2066 store_context(&thread->context);
2068 /* Check if the current thread stack is overflown */
2069 if (thread->stack[0] != DEADBEEF)
2070 thread_stkov(thread);
2072 #if NUM_CORES > 1
2073 /* Run any blocking operations requested before switching/sleeping */
2074 run_blocking_ops(core, thread);
2075 #endif
2077 #ifdef HAVE_PRIORITY_SCHEDULING
2078 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2079 /* Reset the value of thread's skip count */
2080 thread->skip_count = 0;
2081 #endif
2083 for (;;)
2085 /* If there are threads on a timeout and the earliest wakeup is due,
2086 * check the list and wake any threads that need to start running
2087 * again. */
2088 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2090 check_tmo_threads();
2093 disable_irq();
2094 RTR_LOCK(core);
2096 thread = cores[core].running;
2098 if (thread == NULL)
2100 /* Enter sleep mode to reduce power usage - woken up on interrupt
2101 * or wakeup request from another core - expected to enable
2102 * interrupts. */
2103 RTR_UNLOCK(core);
2104 core_sleep(IF_COP(core));
2106 else
2108 #ifdef HAVE_PRIORITY_SCHEDULING
2109 /* Select the new task based on priorities and the last time a
2110 * process got CPU time relative to the highest priority runnable
2111 * task. */
2112 struct priority_distribution *pd = &cores[core].rtr;
2113 int max = find_first_set_bit(pd->mask);
2115 if (block == NULL)
2117 /* Not switching on a block, tentatively select next thread */
2118 thread = thread->l.next;
2121 for (;;)
2123 int priority = thread->priority;
2124 int diff;
2126 /* This ridiculously simple method of aging seems to work
2127 * suspiciously well. It does tend to reward CPU hogs (under
2128 * yielding) but that's generally not desirable at all. On the
2129 * plus side, it, relatively to other threads, penalizes excess
2130 * yielding which is good if some high priority thread is
2131 * performing no useful work such as polling for a device to be
2132 * ready. Of course, aging is only employed when higher and lower
2133 * priority threads are runnable. The highest priority runnable
2134 * thread(s) are never skipped. */
2135 if (priority <= max ||
2136 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2137 (diff = priority - max, ++thread->skip_count > diff*diff))
2139 cores[core].running = thread;
2140 break;
2143 thread = thread->l.next;
2145 #else
2146 /* Without priority use a simple FCFS algorithm */
2147 if (block == NULL)
2149 /* Not switching on a block, select next thread */
2150 thread = thread->l.next;
2151 cores[core].running = thread;
2153 #endif /* HAVE_PRIORITY_SCHEDULING */
2155 RTR_UNLOCK(core);
2156 enable_irq();
2157 break;
2161 /* And finally give control to the next thread. */
2162 load_context(&thread->context);
2164 #ifdef RB_PROFILE
2165 profile_thread_started(thread - threads);
2166 #endif
2170 /*---------------------------------------------------------------------------
2171 * Sleeps a thread for at least a specified number of ticks with zero being
2172 * a wait until the next tick.
2174 * INTERNAL: Intended for use by kernel and not for programs.
2175 *---------------------------------------------------------------------------
2177 void sleep_thread(int ticks)
2179 struct thread_entry *current = cores[CURRENT_CORE].running;
2181 LOCK_THREAD(current);
2183 /* Set our timeout, remove from run list and join timeout list. */
2184 current->tmo_tick = current_tick + ticks + 1;
2185 block_thread_on_l(current, STATE_SLEEPING);
2187 UNLOCK_THREAD(current);
2190 /*---------------------------------------------------------------------------
2191 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2193 * INTERNAL: Intended for use by kernel objects and not for programs.
2194 *---------------------------------------------------------------------------
2196 void block_thread(struct thread_entry *current)
2198 /* Set the state to blocked and take us off of the run queue until we
2199 * are explicitly woken */
2200 LOCK_THREAD(current);
2202 /* Set the list for explicit wakeup */
2203 block_thread_on_l(current, STATE_BLOCKED);
2205 #ifdef HAVE_PRIORITY_SCHEDULING
2206 if (current->blocker != NULL)
2208 /* Object supports PIP */
2209 current = blocker_inherit_priority(current);
2211 #endif
2213 UNLOCK_THREAD(current);
2216 /*---------------------------------------------------------------------------
2217 * Block a thread on a blocking queue for a specified time interval or until
2218 * explicitly woken - whichever happens first.
2220 * INTERNAL: Intended for use by kernel objects and not for programs.
2221 *---------------------------------------------------------------------------
2223 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2225 /* Get the entry for the current running thread. */
2226 LOCK_THREAD(current);
2228 /* Set the state to blocked with the specified timeout */
2229 current->tmo_tick = current_tick + timeout;
2231 /* Set the list for explicit wakeup */
2232 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2234 #ifdef HAVE_PRIORITY_SCHEDULING
2235 if (current->blocker != NULL)
2237 /* Object supports PIP */
2238 current = blocker_inherit_priority(current);
2240 #endif
2242 UNLOCK_THREAD(current);
2245 /*---------------------------------------------------------------------------
2246 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2247 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2249 * This code should be considered a critical section by the caller meaning
2250 * that the object's corelock should be held.
2252 * INTERNAL: Intended for use by kernel objects and not for programs.
2253 *---------------------------------------------------------------------------
2255 unsigned int wakeup_thread(struct thread_entry **list)
2257 struct thread_entry *thread = *list;
2258 unsigned int result = THREAD_NONE;
2260 /* Check if there is a blocked thread at all. */
2261 if (thread == NULL)
2262 return result;
2264 LOCK_THREAD(thread);
2266 /* Determine thread's current state. */
2267 switch (thread->state)
2269 case STATE_BLOCKED:
2270 case STATE_BLOCKED_W_TMO:
2271 remove_from_list_l(list, thread);
2273 result = THREAD_OK;
2275 #ifdef HAVE_PRIORITY_SCHEDULING
2276 struct thread_entry *current;
2277 struct blocker *bl = thread->blocker;
2279 if (bl == NULL)
2281 /* No inheritance - just boost the thread by aging */
2282 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2283 thread->skip_count = thread->priority;
2284 current = cores[CURRENT_CORE].running;
2286 else
2288 /* Call the specified unblocking PIP */
2289 current = bl->wakeup_protocol(thread);
2292 if (current != NULL && thread->priority < current->priority
2293 IF_COP( && thread->core == current->core ))
2295 /* Woken thread is higher priority and exists on the same CPU core;
2296 * recommend a task switch. Knowing if this is an interrupt call
2297 * would be helpful here. */
2298 result |= THREAD_SWITCH;
2300 #endif /* HAVE_PRIORITY_SCHEDULING */
2302 core_schedule_wakeup(thread);
2303 break;
2305 /* Nothing to do. State is not blocked. */
2306 #if THREAD_EXTRA_CHECKS
2307 default:
2308 THREAD_PANICF("wakeup_thread->block invalid", thread);
2309 case STATE_RUNNING:
2310 case STATE_KILLED:
2311 break;
2312 #endif
2315 UNLOCK_THREAD(thread);
2316 return result;
2319 /*---------------------------------------------------------------------------
2320 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2321 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2322 * the queue must be locked first.
2324 * INTERNAL: Intended for use by kernel objects and not for programs.
2325 *---------------------------------------------------------------------------
2327 unsigned int thread_queue_wake(struct thread_entry **list)
2329 unsigned result = THREAD_NONE;
2331 for (;;)
2333 unsigned int rc = wakeup_thread(list);
2335 if (rc == THREAD_NONE)
2336 break; /* No more threads */
2338 result |= rc;
2341 return result;
2344 /*---------------------------------------------------------------------------
2345 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2346 * will be locked on multicore.
2347 *---------------------------------------------------------------------------
2349 static struct thread_entry * find_empty_thread_slot(void)
2351 /* Any slot could be on an interrupt-accessible list */
2352 IF_COP( int oldlevel = disable_irq_save(); )
2353 struct thread_entry *thread = NULL;
2354 int n;
2356 for (n = 0; n < MAXTHREADS; n++)
2358 /* Obtain current slot state - lock it on multicore */
2359 struct thread_entry *t = &threads[n];
2360 LOCK_THREAD(t);
2362 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2364 /* Slot is empty - leave it locked and caller will unlock */
2365 thread = t;
2366 break;
2369 /* Finished examining slot - no longer busy - unlock on multicore */
2370 UNLOCK_THREAD(t);
2373 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2374 not accesible to them yet */
2375 return thread;
2379 /*---------------------------------------------------------------------------
2380 * Place the current core in idle mode - woken up on interrupt or wake
2381 * request from another core.
2382 *---------------------------------------------------------------------------
2384 void core_idle(void)
2386 IF_COP( const unsigned int core = CURRENT_CORE; )
2387 disable_irq();
2388 core_sleep(IF_COP(core));
2391 /*---------------------------------------------------------------------------
2392 * Create a thread. If using a dual core architecture, specify which core to
2393 * start the thread on.
2395 * Return ID if context area could be allocated, else NULL.
2396 *---------------------------------------------------------------------------
2398 struct thread_entry*
2399 create_thread(void (*function)(void), void* stack, size_t stack_size,
2400 unsigned flags, const char *name
2401 IF_PRIO(, int priority)
2402 IF_COP(, unsigned int core))
2404 unsigned int i;
2405 unsigned int stack_words;
2406 uintptr_t stackptr, stackend;
2407 struct thread_entry *thread;
2408 unsigned state;
2409 int oldlevel;
2411 thread = find_empty_thread_slot();
2412 if (thread == NULL)
2414 return NULL;
2417 oldlevel = disable_irq_save();
2419 /* Munge the stack to make it easy to spot stack overflows */
2420 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2421 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2422 stack_size = stackend - stackptr;
2423 stack_words = stack_size / sizeof (uintptr_t);
2425 for (i = 0; i < stack_words; i++)
2427 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2430 /* Store interesting information */
2431 thread->name = name;
2432 thread->stack = (uintptr_t *)stackptr;
2433 thread->stack_size = stack_size;
2434 thread->queue = NULL;
2435 #ifdef HAVE_WAKEUP_EXT_CB
2436 thread->wakeup_ext_cb = NULL;
2437 #endif
2438 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2439 thread->cpu_boost = 0;
2440 #endif
2441 #ifdef HAVE_PRIORITY_SCHEDULING
2442 memset(&thread->pdist, 0, sizeof(thread->pdist));
2443 thread->blocker = NULL;
2444 thread->base_priority = priority;
2445 thread->priority = priority;
2446 thread->skip_count = priority;
2447 prio_add_entry(&thread->pdist, priority);
2448 #endif
2450 #if NUM_CORES > 1
2451 thread->core = core;
2453 /* Writeback stack munging or anything else before starting */
2454 if (core != CURRENT_CORE)
2456 flush_icache();
2458 #endif
2460 /* Thread is not on any timeout list but be a bit paranoid */
2461 thread->tmo.prev = NULL;
2463 state = (flags & CREATE_THREAD_FROZEN) ?
2464 STATE_FROZEN : STATE_RUNNING;
2466 thread->context.sp = (typeof (thread->context.sp))stackend;
2468 /* Load the thread's context structure with needed startup information */
2469 THREAD_STARTUP_INIT(core, thread, function);
2471 thread->state = state;
2473 if (state == STATE_RUNNING)
2474 core_schedule_wakeup(thread);
2476 UNLOCK_THREAD(thread);
2478 restore_irq(oldlevel);
2480 return thread;
2483 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2484 /*---------------------------------------------------------------------------
2485 * Change the boost state of a thread boosting or unboosting the CPU
2486 * as required.
2487 *---------------------------------------------------------------------------
2489 static inline void boost_thread(struct thread_entry *thread, bool boost)
2491 if ((thread->cpu_boost != 0) != boost)
2493 thread->cpu_boost = boost;
2494 cpu_boost(boost);
2498 void trigger_cpu_boost(void)
2500 struct thread_entry *current = cores[CURRENT_CORE].running;
2501 boost_thread(current, true);
2504 void cancel_cpu_boost(void)
2506 struct thread_entry *current = cores[CURRENT_CORE].running;
2507 boost_thread(current, false);
2509 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2511 /*---------------------------------------------------------------------------
2512 * Block the current thread until another thread terminates. A thread may
2513 * wait on itself to terminate which prevents it from running again and it
2514 * will need to be killed externally.
2515 * Parameter is the ID as returned from create_thread().
2516 *---------------------------------------------------------------------------
2518 void thread_wait(struct thread_entry *thread)
2520 struct thread_entry *current = cores[CURRENT_CORE].running;
2522 if (thread == NULL)
2523 thread = current;
2525 /* Lock thread-as-waitable-object lock */
2526 corelock_lock(&thread->waiter_cl);
2528 /* Be sure it hasn't been killed yet */
2529 if (thread->state != STATE_KILLED)
2531 IF_COP( current->obj_cl = &thread->waiter_cl; )
2532 current->bqp = &thread->queue;
2534 disable_irq();
2535 block_thread(current);
2537 corelock_unlock(&thread->waiter_cl);
2539 switch_thread();
2540 return;
2543 corelock_unlock(&thread->waiter_cl);
2546 /*---------------------------------------------------------------------------
2547 * Exit the current thread. The Right Way to Do Things (TM).
2548 *---------------------------------------------------------------------------
2550 void thread_exit(void)
2552 const unsigned int core = CURRENT_CORE;
2553 struct thread_entry *current = cores[core].running;
2555 /* Cancel CPU boost if any */
2556 cancel_cpu_boost();
2558 disable_irq();
2560 corelock_lock(&current->waiter_cl);
2561 LOCK_THREAD(current);
2563 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2564 if (current->name == THREAD_DESTRUCT)
2566 /* Thread being killed - become a waiter */
2567 UNLOCK_THREAD(current);
2568 corelock_unlock(&current->waiter_cl);
2569 thread_wait(current);
2570 THREAD_PANICF("thread_exit->WK:*R", current);
2572 #endif
2574 #ifdef HAVE_PRIORITY_SCHEDULING
2575 check_for_obj_waiters("thread_exit", current);
2576 #endif
2578 if (current->tmo.prev != NULL)
2580 /* Cancel pending timeout list removal */
2581 remove_from_list_tmo(current);
2584 /* Switch tasks and never return */
2585 block_thread_on_l(current, STATE_KILLED);
2587 #if NUM_CORES > 1
2588 /* Switch to the idle stack if not on the main core (where "main"
2589 * runs) - we can hope gcc doesn't need the old stack beyond this
2590 * point. */
2591 if (core != CPU)
2593 switch_to_idle_stack(core);
2596 flush_icache();
2597 #endif
2598 current->name = NULL;
2600 /* Signal this thread */
2601 thread_queue_wake(&current->queue);
2602 corelock_unlock(&current->waiter_cl);
2603 /* Slot must be unusable until thread is really gone */
2604 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2605 switch_thread();
2606 /* This should never and must never be reached - if it is, the
2607 * state is corrupted */
2608 THREAD_PANICF("thread_exit->K:*R", current);
2611 #ifdef ALLOW_REMOVE_THREAD
2612 /*---------------------------------------------------------------------------
2613 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2614 * normal programs.
2616 * Parameter is the ID as returned from create_thread().
2618 * Use with care on threads that are not under careful control as this may
2619 * leave various objects in an undefined state.
2620 *---------------------------------------------------------------------------
2622 void remove_thread(struct thread_entry *thread)
2624 #if NUM_CORES > 1
2625 /* core is not constant here because of core switching */
2626 unsigned int core = CURRENT_CORE;
2627 unsigned int old_core = NUM_CORES;
2628 struct corelock *ocl = NULL;
2629 #else
2630 const unsigned int core = CURRENT_CORE;
2631 #endif
2632 struct thread_entry *current = cores[core].running;
2634 unsigned state;
2635 int oldlevel;
2637 if (thread == NULL)
2638 thread = current;
2640 if (thread == current)
2641 thread_exit(); /* Current thread - do normal exit */
2643 oldlevel = disable_irq_save();
2645 corelock_lock(&thread->waiter_cl);
2646 LOCK_THREAD(thread);
2648 state = thread->state;
2650 if (state == STATE_KILLED)
2652 goto thread_killed;
2655 #if NUM_CORES > 1
2656 if (thread->name == THREAD_DESTRUCT)
2658 /* Thread being killed - become a waiter */
2659 UNLOCK_THREAD(thread);
2660 corelock_unlock(&thread->waiter_cl);
2661 restore_irq(oldlevel);
2662 thread_wait(thread);
2663 return;
2666 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2668 #ifdef HAVE_PRIORITY_SCHEDULING
2669 check_for_obj_waiters("remove_thread", thread);
2670 #endif
2672 if (thread->core != core)
2674 /* Switch cores and safely extract the thread there */
2675 /* Slot HAS to be unlocked or a deadlock could occur which means other
2676 * threads have to be guided into becoming thread waiters if they
2677 * attempt to remove it. */
2678 unsigned int new_core = thread->core;
2680 corelock_unlock(&thread->waiter_cl);
2682 UNLOCK_THREAD(thread);
2683 restore_irq(oldlevel);
2685 old_core = switch_core(new_core);
2687 oldlevel = disable_irq_save();
2689 corelock_lock(&thread->waiter_cl);
2690 LOCK_THREAD(thread);
2692 state = thread->state;
2693 core = new_core;
2694 /* Perform the extraction and switch ourselves back to the original
2695 processor */
2697 #endif /* NUM_CORES > 1 */
2699 if (thread->tmo.prev != NULL)
2701 /* Clean thread off the timeout list if a timeout check hasn't
2702 * run yet */
2703 remove_from_list_tmo(thread);
2706 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2707 /* Cancel CPU boost if any */
2708 boost_thread(thread, false);
2709 #endif
2711 IF_COP( retry_state: )
2713 switch (state)
2715 case STATE_RUNNING:
2716 RTR_LOCK(core);
2717 /* Remove thread from ready to run tasks */
2718 remove_from_list_l(&cores[core].running, thread);
2719 rtr_subtract_entry(core, thread->priority);
2720 RTR_UNLOCK(core);
2721 break;
2722 case STATE_BLOCKED:
2723 case STATE_BLOCKED_W_TMO:
2724 /* Remove thread from the queue it's blocked on - including its
2725 * own if waiting there */
2726 #if NUM_CORES > 1
2727 if (&thread->waiter_cl != thread->obj_cl)
2729 ocl = thread->obj_cl;
2731 if (corelock_try_lock(ocl) == 0)
2733 UNLOCK_THREAD(thread);
2734 corelock_lock(ocl);
2735 LOCK_THREAD(thread);
2737 if (thread->state != state)
2739 /* Something woke the thread */
2740 state = thread->state;
2741 corelock_unlock(ocl);
2742 goto retry_state;
2746 #endif
2747 remove_from_list_l(thread->bqp, thread);
2749 #ifdef HAVE_WAKEUP_EXT_CB
2750 if (thread->wakeup_ext_cb != NULL)
2751 thread->wakeup_ext_cb(thread);
2752 #endif
2754 #ifdef HAVE_PRIORITY_SCHEDULING
2755 if (thread->blocker != NULL)
2757 /* Remove thread's priority influence from its chain */
2758 wakeup_priority_protocol_release(thread);
2760 #endif
2762 #if NUM_CORES > 1
2763 if (ocl != NULL)
2764 corelock_unlock(ocl);
2765 #endif
2766 break;
2767 /* Otherwise thread is frozen and hasn't run yet */
2770 thread->state = STATE_KILLED;
2772 /* If thread was waiting on itself, it will have been removed above.
2773 * The wrong order would result in waking the thread first and deadlocking
2774 * since the slot is already locked. */
2775 thread_queue_wake(&thread->queue);
2777 thread->name = NULL;
2779 thread_killed: /* Thread was already killed */
2780 /* Removal complete - safe to unlock and reenable interrupts */
2781 corelock_unlock(&thread->waiter_cl);
2782 UNLOCK_THREAD(thread);
2783 restore_irq(oldlevel);
2785 #if NUM_CORES > 1
2786 if (old_core < NUM_CORES)
2788 /* Did a removal on another processor's thread - switch back to
2789 native core */
2790 switch_core(old_core);
2792 #endif
2794 #endif /* ALLOW_REMOVE_THREAD */
2796 #ifdef HAVE_PRIORITY_SCHEDULING
2797 /*---------------------------------------------------------------------------
2798 * Sets the thread's relative base priority for the core it runs on. Any
2799 * needed inheritance changes also may happen.
2800 *---------------------------------------------------------------------------
2802 int thread_set_priority(struct thread_entry *thread, int priority)
2804 int old_base_priority = -1;
2806 /* A little safety measure */
2807 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2808 return -1;
2810 if (thread == NULL)
2811 thread = cores[CURRENT_CORE].running;
2813 /* Thread could be on any list and therefore on an interrupt accessible
2814 one - disable interrupts */
2815 int oldlevel = disable_irq_save();
2817 LOCK_THREAD(thread);
2819 /* Make sure it's not killed */
2820 if (thread->state != STATE_KILLED)
2822 int old_priority = thread->priority;
2824 old_base_priority = thread->base_priority;
2825 thread->base_priority = priority;
2827 prio_move_entry(&thread->pdist, old_base_priority, priority);
2828 priority = find_first_set_bit(thread->pdist.mask);
2830 if (old_priority == priority)
2832 /* No priority change - do nothing */
2834 else if (thread->state == STATE_RUNNING)
2836 /* This thread is running - change location on the run
2837 * queue. No transitive inheritance needed. */
2838 set_running_thread_priority(thread, priority);
2840 else
2842 thread->priority = priority;
2844 if (thread->blocker != NULL)
2846 /* Bubble new priority down the chain */
2847 struct blocker *bl = thread->blocker; /* Blocker struct */
2848 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2849 struct thread_entry * const tstart = thread; /* Initial thread */
2850 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2852 for (;;)
2854 struct thread_entry *next; /* Next thread to check */
2855 int bl_pr; /* Highest blocked thread */
2856 int queue_pr; /* New highest blocked thread */
2857 #if NUM_CORES > 1
2858 /* Owner can change but thread cannot be dislodged - thread
2859 * may not be the first in the queue which allows other
2860 * threads ahead in the list to be given ownership during the
2861 * operation. If thread is next then the waker will have to
2862 * wait for us and the owner of the object will remain fixed.
2863 * If we successfully grab the owner -- which at some point
2864 * is guaranteed -- then the queue remains fixed until we
2865 * pass by. */
2866 for (;;)
2868 LOCK_THREAD(bl_t);
2870 /* Double-check the owner - retry if it changed */
2871 if (bl->thread == bl_t)
2872 break;
2874 UNLOCK_THREAD(bl_t);
2875 bl_t = bl->thread;
2877 #endif
2878 bl_pr = bl->priority;
2880 if (highest > bl_pr)
2881 break; /* Object priority won't change */
2883 /* This will include the thread being set */
2884 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2886 if (queue_pr == bl_pr)
2887 break; /* Object priority not changing */
2889 /* Update thread boost for this object */
2890 bl->priority = queue_pr;
2891 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2892 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2894 if (bl_t->priority == bl_pr)
2895 break; /* Blocking thread priority not changing */
2897 if (bl_t->state == STATE_RUNNING)
2899 /* Thread not blocked - we're done */
2900 set_running_thread_priority(bl_t, bl_pr);
2901 break;
2904 bl_t->priority = bl_pr;
2905 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2907 if (bl == NULL)
2908 break; /* End of chain */
2910 next = bl->thread;
2912 if (next == tstart)
2913 break; /* Full-circle */
2915 UNLOCK_THREAD(thread);
2917 thread = bl_t;
2918 bl_t = next;
2919 } /* for (;;) */
2921 UNLOCK_THREAD(bl_t);
2926 UNLOCK_THREAD(thread);
2928 restore_irq(oldlevel);
2930 return old_base_priority;
2933 /*---------------------------------------------------------------------------
2934 * Returns the current base priority for a thread.
2935 *---------------------------------------------------------------------------
2937 int thread_get_priority(struct thread_entry *thread)
2939 /* Simple, quick probe. */
2940 if (thread == NULL)
2941 thread = cores[CURRENT_CORE].running;
2943 return thread->base_priority;
2945 #endif /* HAVE_PRIORITY_SCHEDULING */
2947 /*---------------------------------------------------------------------------
2948 * Starts a frozen thread - similar semantics to wakeup_thread except that
2949 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2950 * virtue of the slot having a state of STATE_FROZEN.
2951 *---------------------------------------------------------------------------
2953 void thread_thaw(struct thread_entry *thread)
2955 int oldlevel = disable_irq_save();
2956 LOCK_THREAD(thread);
2958 if (thread->state == STATE_FROZEN)
2959 core_schedule_wakeup(thread);
2961 UNLOCK_THREAD(thread);
2962 restore_irq(oldlevel);
2965 /*---------------------------------------------------------------------------
2966 * Return the ID of the currently executing thread.
2967 *---------------------------------------------------------------------------
2969 struct thread_entry * thread_get_current(void)
2971 return cores[CURRENT_CORE].running;
2974 #if NUM_CORES > 1
2975 /*---------------------------------------------------------------------------
2976 * Switch the processor that the currently executing thread runs on.
2977 *---------------------------------------------------------------------------
2979 unsigned int switch_core(unsigned int new_core)
2981 const unsigned int core = CURRENT_CORE;
2982 struct thread_entry *current = cores[core].running;
2984 if (core == new_core)
2986 /* No change - just return same core */
2987 return core;
2990 int oldlevel = disable_irq_save();
2991 LOCK_THREAD(current);
2993 if (current->name == THREAD_DESTRUCT)
2995 /* Thread being killed - deactivate and let process complete */
2996 UNLOCK_THREAD(current);
2997 restore_irq(oldlevel);
2998 thread_wait(current);
2999 /* Should never be reached */
3000 THREAD_PANICF("switch_core->D:*R", current);
3003 /* Get us off the running list for the current core */
3004 RTR_LOCK(core);
3005 remove_from_list_l(&cores[core].running, current);
3006 rtr_subtract_entry(core, current->priority);
3007 RTR_UNLOCK(core);
3009 /* Stash return value (old core) in a safe place */
3010 current->retval = core;
3012 /* If a timeout hadn't yet been cleaned-up it must be removed now or
3013 * the other core will likely attempt a removal from the wrong list! */
3014 if (current->tmo.prev != NULL)
3016 remove_from_list_tmo(current);
3019 /* Change the core number for this thread slot */
3020 current->core = new_core;
3022 /* Do not use core_schedule_wakeup here since this will result in
3023 * the thread starting to run on the other core before being finished on
3024 * this one. Delay the list unlock to keep the other core stuck
3025 * until this thread is ready. */
3026 RTR_LOCK(new_core);
3028 rtr_add_entry(new_core, current->priority);
3029 add_to_list_l(&cores[new_core].running, current);
3031 /* Make a callback into device-specific code, unlock the wakeup list so
3032 * that execution may resume on the new core, unlock our slot and finally
3033 * restore the interrupt level */
3034 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3035 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3036 cores[core].block_task = current;
3038 UNLOCK_THREAD(current);
3040 /* Alert other core to activity */
3041 core_wake(new_core);
3043 /* Do the stack switching, cache_maintenence and switch_thread call -
3044 requires native code */
3045 switch_thread_core(core, current);
3047 /* Finally return the old core to caller */
3048 return current->retval;
3050 #endif /* NUM_CORES > 1 */
3052 /*---------------------------------------------------------------------------
3053 * Initialize threading API. This assumes interrupts are not yet enabled. On
3054 * multicore setups, no core is allowed to proceed until create_thread calls
3055 * are safe to perform.
3056 *---------------------------------------------------------------------------
3058 void init_threads(void)
3060 const unsigned int core = CURRENT_CORE;
3061 struct thread_entry *thread;
3063 /* CPU will initialize first and then sleep */
3064 thread = find_empty_thread_slot();
3066 if (thread == NULL)
3068 /* WTF? There really must be a slot available at this stage.
3069 * This can fail if, for example, .bss isn't zero'ed out by the loader
3070 * or threads is in the wrong section. */
3071 THREAD_PANICF("init_threads->no slot", NULL);
3074 /* Initialize initially non-zero members of core */
3075 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3077 /* Initialize initially non-zero members of slot */
3078 UNLOCK_THREAD(thread); /* No sync worries yet */
3079 thread->name = main_thread_name;
3080 thread->state = STATE_RUNNING;
3081 IF_COP( thread->core = core; )
3082 #ifdef HAVE_PRIORITY_SCHEDULING
3083 corelock_init(&cores[core].rtr_cl);
3084 thread->base_priority = PRIORITY_USER_INTERFACE;
3085 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3086 thread->priority = PRIORITY_USER_INTERFACE;
3087 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3088 #endif
3089 corelock_init(&thread->waiter_cl);
3090 corelock_init(&thread->slot_cl);
3092 add_to_list_l(&cores[core].running, thread);
3094 if (core == CPU)
3096 thread->stack = stackbegin;
3097 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3098 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3099 /* Wait for other processors to finish their inits since create_thread
3100 * isn't safe to call until the kernel inits are done. The first
3101 * threads created in the system must of course be created by CPU. */
3102 core_thread_init(CPU);
3104 else
3106 /* Initial stack is the idle stack */
3107 thread->stack = idle_stacks[core];
3108 thread->stack_size = IDLE_STACK_SIZE;
3109 /* After last processor completes, it should signal all others to
3110 * proceed or may signal the next and call thread_exit(). The last one
3111 * to finish will signal CPU. */
3112 core_thread_init(core);
3113 /* Other cores do not have a main thread - go idle inside switch_thread
3114 * until a thread can run on the core. */
3115 thread_exit();
3116 #endif /* NUM_CORES */
3120 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3121 #if NUM_CORES == 1
3122 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3123 #else
3124 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3125 #endif
3127 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3128 unsigned int i;
3129 int usage = 0;
3131 for (i = 0; i < stack_words; i++)
3133 if (stackptr[i] != DEADBEEF)
3135 usage = ((stack_words - i) * 100) / stack_words;
3136 break;
3140 return usage;
3143 /*---------------------------------------------------------------------------
3144 * Returns the maximum percentage of stack a thread ever used while running.
3145 * NOTE: Some large buffer allocations that don't use enough the buffer to
3146 * overwrite stackptr[0] will not be seen.
3147 *---------------------------------------------------------------------------
3149 int thread_stack_usage(const struct thread_entry *thread)
3151 return stack_usage(thread->stack, thread->stack_size);
3154 #if NUM_CORES > 1
3155 /*---------------------------------------------------------------------------
3156 * Returns the maximum percentage of the core's idle stack ever used during
3157 * runtime.
3158 *---------------------------------------------------------------------------
3160 int idle_stack_usage(unsigned int core)
3162 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3164 #endif
3166 /*---------------------------------------------------------------------------
3167 * Fills in the buffer with the specified thread's name. If the name is NULL,
3168 * empty, or the thread is in destruct state a formatted ID is written
3169 * instead.
3170 *---------------------------------------------------------------------------
3172 void thread_get_name(char *buffer, int size,
3173 struct thread_entry *thread)
3175 if (size <= 0)
3176 return;
3178 *buffer = '\0';
3180 if (thread)
3182 /* Display thread name if one or ID if none */
3183 const char *name = thread->name;
3184 const char *fmt = "%s";
3185 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3187 name = (const char *)thread;
3188 fmt = "%08lX";
3190 snprintf(buffer, size, fmt, name);