as3525 PCM: implement locking like done for the gigabeats in r26341
[kugel-rb.git] / firmware / thread.c
blob54d966ffe5628307928f483a49a3a366ce760402
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 <stdio.h>
24 #include "thread.h"
25 #include "panic.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 static struct core_entry cores[NUM_CORES] IBSS_ATTR;
123 struct thread_entry threads[MAXTHREADS] IBSS_ATTR;
125 static const char main_thread_name[] = "main";
126 extern uintptr_t stackbegin[];
127 extern uintptr_t stackend[];
129 static inline void core_sleep(IF_COP_VOID(unsigned int core))
130 __attribute__((always_inline));
132 void check_tmo_threads(void)
133 __attribute__((noinline));
135 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
136 __attribute__((always_inline));
138 static void add_to_list_tmo(struct thread_entry *thread)
139 __attribute__((noinline));
141 static void core_schedule_wakeup(struct thread_entry *thread)
142 __attribute__((noinline));
144 #if NUM_CORES > 1
145 static inline void run_blocking_ops(
146 unsigned int core, struct thread_entry *thread)
147 __attribute__((always_inline));
148 #endif
150 static void thread_stkov(struct thread_entry *thread)
151 __attribute__((noinline));
153 static inline void store_context(void* addr)
154 __attribute__((always_inline));
156 static inline void load_context(const void* addr)
157 __attribute__((always_inline));
159 void switch_thread(void)
160 __attribute__((noinline));
162 /****************************************************************************
163 * Processor-specific section
166 #if defined(MAX_PHYS_SECTOR_SIZE) && MEM == 64
167 /* Support a special workaround object for large-sector disks */
168 #define IF_NO_SKIP_YIELD(...) __VA_ARGS__
169 #else
170 #define IF_NO_SKIP_YIELD(...)
171 #endif
173 #if defined(CPU_ARM)
174 /*---------------------------------------------------------------------------
175 * Start the thread running and terminate it if it returns
176 *---------------------------------------------------------------------------
178 static void __attribute__((naked,used)) start_thread(void)
180 /* r0 = context */
181 asm volatile (
182 "ldr sp, [r0, #32] \n" /* Load initial sp */
183 "ldr r4, [r0, #40] \n" /* start in r4 since it's non-volatile */
184 "mov r1, #0 \n" /* Mark thread as running */
185 "str r1, [r0, #40] \n"
186 #if NUM_CORES > 1
187 "ldr r0, =cpucache_invalidate \n" /* Invalidate this core's cache. */
188 "mov lr, pc \n" /* This could be the first entry into */
189 "bx r0 \n" /* plugin or codec code for this core. */
190 #endif
191 "mov lr, pc \n" /* Call thread function */
192 "bx r4 \n"
193 ); /* No clobber list - new thread doesn't care */
194 thread_exit();
195 //asm volatile (".ltorg"); /* Dump constant pool */
198 /* For startup, place context pointer in r4 slot, start_thread pointer in r5
199 * slot, and thread function pointer in context.start. See load_context for
200 * what happens when thread is initially going to run. */
201 #define THREAD_STARTUP_INIT(core, thread, function) \
202 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
203 (thread)->context.r[1] = (uint32_t)start_thread, \
204 (thread)->context.start = (uint32_t)function; })
206 /*---------------------------------------------------------------------------
207 * Store non-volatile context.
208 *---------------------------------------------------------------------------
210 static inline void store_context(void* addr)
212 asm volatile(
213 "stmia %0, { r4-r11, sp, lr } \n"
214 : : "r" (addr)
218 /*---------------------------------------------------------------------------
219 * Load non-volatile context.
220 *---------------------------------------------------------------------------
222 static inline void load_context(const void* addr)
224 asm volatile(
225 "ldr r0, [%0, #40] \n" /* Load start pointer */
226 "cmp r0, #0 \n" /* Check for NULL */
227 "ldmneia %0, { r0, pc } \n" /* If not already running, jump to start */
228 "ldmia %0, { r4-r11, sp, lr } \n" /* Load regs r4 to r14 from context */
229 : : "r" (addr) : "r0" /* only! */
233 #if defined (CPU_PP)
235 #if NUM_CORES > 1
236 extern uintptr_t cpu_idlestackbegin[];
237 extern uintptr_t cpu_idlestackend[];
238 extern uintptr_t cop_idlestackbegin[];
239 extern uintptr_t cop_idlestackend[];
240 static uintptr_t * const idle_stacks[NUM_CORES] =
242 [CPU] = cpu_idlestackbegin,
243 [COP] = cop_idlestackbegin
246 #if CONFIG_CPU == PP5002
247 /* Bytes to emulate the PP502x mailbox bits */
248 struct core_semaphores
250 volatile uint8_t intend_wake; /* 00h */
251 volatile uint8_t stay_awake; /* 01h */
252 volatile uint8_t intend_sleep; /* 02h */
253 volatile uint8_t unused; /* 03h */
256 static struct core_semaphores core_semaphores[NUM_CORES] IBSS_ATTR;
257 #endif /* CONFIG_CPU == PP5002 */
259 #endif /* NUM_CORES */
261 #if CONFIG_CORELOCK == SW_CORELOCK
262 /* Software core locks using Peterson's mutual exclusion algorithm */
264 /*---------------------------------------------------------------------------
265 * Initialize the corelock structure.
266 *---------------------------------------------------------------------------
268 void corelock_init(struct corelock *cl)
270 memset(cl, 0, sizeof (*cl));
273 #if 1 /* Assembly locks to minimize overhead */
274 /*---------------------------------------------------------------------------
275 * Wait for the corelock to become free and acquire it when it does.
276 *---------------------------------------------------------------------------
278 void corelock_lock(struct corelock *cl) __attribute__((naked));
279 void corelock_lock(struct corelock *cl)
281 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
282 asm volatile (
283 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
284 "ldrb r1, [r1] \n"
285 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
286 "eor r2, r1, #0xff \n" /* r2 = othercore */
287 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
288 "1: \n"
289 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
290 "cmp r3, #0 \n" /* yes? lock acquired */
291 "bxeq lr \n"
292 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
293 "cmp r3, r1 \n"
294 "bxeq lr \n" /* yes? lock acquired */
295 "b 1b \n" /* keep trying */
296 : : "i"(&PROCESSOR_ID)
298 (void)cl;
301 /*---------------------------------------------------------------------------
302 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
303 *---------------------------------------------------------------------------
305 int corelock_try_lock(struct corelock *cl) __attribute__((naked));
306 int corelock_try_lock(struct corelock *cl)
308 /* Relies on the fact that core IDs are complementary bitmasks (0x55,0xaa) */
309 asm volatile (
310 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
311 "ldrb r1, [r1] \n"
312 "mov r3, r0 \n"
313 "strb r1, [r0, r1, lsr #7] \n" /* cl->myl[core] = core */
314 "eor r2, r1, #0xff \n" /* r2 = othercore */
315 "strb r2, [r0, #2] \n" /* cl->turn = othercore */
316 "ldrb r0, [r3, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
317 "eors r0, r0, r2 \n" /* yes? lock acquired */
318 "bxne lr \n"
319 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
320 "ands r0, r0, r1 \n"
321 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
322 "bx lr \n" /* return result */
323 : : "i"(&PROCESSOR_ID)
326 return 0;
327 (void)cl;
330 /*---------------------------------------------------------------------------
331 * Release ownership of the corelock
332 *---------------------------------------------------------------------------
334 void corelock_unlock(struct corelock *cl) __attribute__((naked));
335 void corelock_unlock(struct corelock *cl)
337 asm volatile (
338 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
339 "ldrb r1, [r1] \n"
340 "mov r2, #0 \n" /* cl->myl[core] = 0 */
341 "strb r2, [r0, r1, lsr #7] \n"
342 "bx lr \n"
343 : : "i"(&PROCESSOR_ID)
345 (void)cl;
347 #else /* C versions for reference */
348 /*---------------------------------------------------------------------------
349 * Wait for the corelock to become free and aquire it when it does.
350 *---------------------------------------------------------------------------
352 void corelock_lock(struct corelock *cl)
354 const unsigned int core = CURRENT_CORE;
355 const unsigned int othercore = 1 - core;
357 cl->myl[core] = core;
358 cl->turn = othercore;
360 for (;;)
362 if (cl->myl[othercore] == 0 || cl->turn == core)
363 break;
367 /*---------------------------------------------------------------------------
368 * Try to aquire the corelock. If free, caller gets it, otherwise return 0.
369 *---------------------------------------------------------------------------
371 int corelock_try_lock(struct corelock *cl)
373 const unsigned int core = CURRENT_CORE;
374 const unsigned int othercore = 1 - core;
376 cl->myl[core] = core;
377 cl->turn = othercore;
379 if (cl->myl[othercore] == 0 || cl->turn == core)
381 return 1;
384 cl->myl[core] = 0;
385 return 0;
388 /*---------------------------------------------------------------------------
389 * Release ownership of the corelock
390 *---------------------------------------------------------------------------
392 void corelock_unlock(struct corelock *cl)
394 cl->myl[CURRENT_CORE] = 0;
396 #endif /* ASM / C selection */
398 #endif /* CONFIG_CORELOCK == SW_CORELOCK */
400 /*---------------------------------------------------------------------------
401 * Put core in a power-saving state if waking list wasn't repopulated and if
402 * no other core requested a wakeup for it to perform a task.
403 *---------------------------------------------------------------------------
405 #ifdef CPU_PP502x
406 #if NUM_CORES == 1
407 static inline void core_sleep(void)
409 sleep_core(CURRENT_CORE);
410 enable_irq();
412 #else
413 static inline void core_sleep(unsigned int core)
415 #if 1
416 asm volatile (
417 "mov r0, #4 \n" /* r0 = 0x4 << core */
418 "mov r0, r0, lsl %[c] \n"
419 "str r0, [%[mbx], #4] \n" /* signal intent to sleep */
420 "ldr r1, [%[mbx], #0] \n" /* && !(MBX_MSG_STAT & (0x10<<core)) ? */
421 "tst r1, r0, lsl #2 \n"
422 "moveq r1, #0x80000000 \n" /* Then sleep */
423 "streq r1, [%[ctl], %[c], lsl #2] \n"
424 "moveq r1, #0 \n" /* Clear control reg */
425 "streq r1, [%[ctl], %[c], lsl #2] \n"
426 "orr r1, r0, r0, lsl #2 \n" /* Signal intent to wake - clear wake flag */
427 "str r1, [%[mbx], #8] \n"
428 "1: \n" /* Wait for wake procedure to finish */
429 "ldr r1, [%[mbx], #0] \n"
430 "tst r1, r0, lsr #2 \n"
431 "bne 1b \n"
433 : [ctl]"r"(&CPU_CTL), [mbx]"r"(MBX_BASE), [c]"r"(core)
434 : "r0", "r1");
435 #else /* C version for reference */
436 /* Signal intent to sleep */
437 MBX_MSG_SET = 0x4 << core;
439 /* Something waking or other processor intends to wake us? */
440 if ((MBX_MSG_STAT & (0x10 << core)) == 0)
442 sleep_core(core);
443 wake_core(core);
446 /* Signal wake - clear wake flag */
447 MBX_MSG_CLR = 0x14 << core;
449 /* Wait for other processor to finish wake procedure */
450 while (MBX_MSG_STAT & (0x1 << core));
451 #endif /* ASM/C selection */
452 enable_irq();
454 #endif /* NUM_CORES */
455 #elif CONFIG_CPU == PP5002
456 #if NUM_CORES == 1
457 static inline void core_sleep(void)
459 sleep_core(CURRENT_CORE);
460 enable_irq();
462 #else
463 /* PP5002 has no mailboxes - emulate using bytes */
464 static inline void core_sleep(unsigned int core)
466 #if 1
467 asm volatile (
468 "mov r0, #1 \n" /* Signal intent to sleep */
469 "strb r0, [%[sem], #2] \n"
470 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
471 "cmp r0, #0 \n"
472 "bne 2f \n"
473 /* Sleep: PP5002 crashes if the instruction that puts it to sleep is
474 * located at 0xNNNNNNN0. 4/8/C works. This sequence makes sure
475 * that the correct alternative is executed. Don't change the order
476 * of the next 4 instructions! */
477 "tst pc, #0x0c \n"
478 "mov r0, #0xca \n"
479 "strne r0, [%[ctl], %[c], lsl #2] \n"
480 "streq r0, [%[ctl], %[c], lsl #2] \n"
481 "nop \n" /* nop's needed because of pipeline */
482 "nop \n"
483 "nop \n"
484 "2: \n"
485 "mov r0, #0 \n" /* Clear stay_awake and sleep intent */
486 "strb r0, [%[sem], #1] \n"
487 "strb r0, [%[sem], #2] \n"
488 "1: \n" /* Wait for wake procedure to finish */
489 "ldrb r0, [%[sem], #0] \n"
490 "cmp r0, #0 \n"
491 "bne 1b \n"
493 : [sem]"r"(&core_semaphores[core]), [c]"r"(core),
494 [ctl]"r"(&CPU_CTL)
495 : "r0"
497 #else /* C version for reference */
498 /* Signal intent to sleep */
499 core_semaphores[core].intend_sleep = 1;
501 /* Something waking or other processor intends to wake us? */
502 if (core_semaphores[core].stay_awake == 0)
504 sleep_core(core);
507 /* Signal wake - clear wake flag */
508 core_semaphores[core].stay_awake = 0;
509 core_semaphores[core].intend_sleep = 0;
511 /* Wait for other processor to finish wake procedure */
512 while (core_semaphores[core].intend_wake != 0);
514 /* Enable IRQ */
515 #endif /* ASM/C selection */
516 enable_irq();
518 #endif /* NUM_CORES */
519 #endif /* PP CPU type */
521 /*---------------------------------------------------------------------------
522 * Wake another processor core that is sleeping or prevent it from doing so
523 * if it was already destined. FIQ, IRQ should be disabled before calling.
524 *---------------------------------------------------------------------------
526 #if NUM_CORES == 1
527 /* Shared single-core build debugging version */
528 void core_wake(void)
530 /* No wakey - core already wakey */
532 #elif defined (CPU_PP502x)
533 void core_wake(unsigned int othercore)
535 #if 1
536 /* avoid r0 since that contains othercore */
537 asm volatile (
538 "mrs r3, cpsr \n" /* Disable IRQ */
539 "orr r1, r3, #0x80 \n"
540 "msr cpsr_c, r1 \n"
541 "mov r2, #0x11 \n" /* r2 = (0x11 << othercore) */
542 "mov r2, r2, lsl %[oc] \n" /* Signal intent to wake othercore */
543 "str r2, [%[mbx], #4] \n"
544 "1: \n" /* If it intends to sleep, let it first */
545 "ldr r1, [%[mbx], #0] \n" /* (MSG_MSG_STAT & (0x4 << othercore)) != 0 ? */
546 "eor r1, r1, #0xc \n"
547 "tst r1, r2, lsr #2 \n"
548 "ldr r1, [%[ctl], %[oc], lsl #2] \n" /* && (PROC_CTL(othercore) & PROC_SLEEP) == 0 ? */
549 "tsteq r1, #0x80000000 \n"
550 "beq 1b \n" /* Wait for sleep or wake */
551 "tst r1, #0x80000000 \n" /* If sleeping, wake it */
552 "movne r1, #0x0 \n"
553 "strne r1, [%[ctl], %[oc], lsl #2] \n"
554 "mov r1, r2, lsr #4 \n"
555 "str r1, [%[mbx], #8] \n" /* Done with wake procedure */
556 "msr cpsr_c, r3 \n" /* Restore IRQ */
558 : [ctl]"r"(&PROC_CTL(CPU)), [mbx]"r"(MBX_BASE),
559 [oc]"r"(othercore)
560 : "r1", "r2", "r3");
561 #else /* C version for reference */
562 /* Disable interrupts - avoid reentrancy from the tick */
563 int oldlevel = disable_irq_save();
565 /* Signal intent to wake other processor - set stay awake */
566 MBX_MSG_SET = 0x11 << othercore;
568 /* If it intends to sleep, wait until it does or aborts */
569 while ((MBX_MSG_STAT & (0x4 << othercore)) != 0 &&
570 (PROC_CTL(othercore) & PROC_SLEEP) == 0);
572 /* If sleeping, wake it up */
573 if (PROC_CTL(othercore) & PROC_SLEEP)
574 PROC_CTL(othercore) = 0;
576 /* Done with wake procedure */
577 MBX_MSG_CLR = 0x1 << othercore;
578 restore_irq(oldlevel);
579 #endif /* ASM/C selection */
581 #elif CONFIG_CPU == PP5002
582 /* PP5002 has no mailboxes - emulate using bytes */
583 void core_wake(unsigned int othercore)
585 #if 1
586 /* avoid r0 since that contains othercore */
587 asm volatile (
588 "mrs r3, cpsr \n" /* Disable IRQ */
589 "orr r1, r3, #0x80 \n"
590 "msr cpsr_c, r1 \n"
591 "mov r1, #1 \n" /* Signal intent to wake other core */
592 "orr r1, r1, r1, lsl #8 \n" /* and set stay_awake */
593 "strh r1, [%[sem], #0] \n"
594 "mov r2, #0x8000 \n"
595 "1: \n" /* If it intends to sleep, let it first */
596 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
597 "cmp r1, #1 \n"
598 "ldr r1, [%[st]] \n" /* && not sleeping ? */
599 "tsteq r1, r2, lsr %[oc] \n"
600 "beq 1b \n" /* Wait for sleep or wake */
601 "tst r1, r2, lsr %[oc] \n"
602 "ldrne r2, =0xcf004054 \n" /* If sleeping, wake it */
603 "movne r1, #0xce \n"
604 "strne r1, [r2, %[oc], lsl #2] \n"
605 "mov r1, #0 \n" /* Done with wake procedure */
606 "strb r1, [%[sem], #0] \n"
607 "msr cpsr_c, r3 \n" /* Restore IRQ */
609 : [sem]"r"(&core_semaphores[othercore]),
610 [st]"r"(&PROC_STAT),
611 [oc]"r"(othercore)
612 : "r1", "r2", "r3"
614 #else /* C version for reference */
615 /* Disable interrupts - avoid reentrancy from the tick */
616 int oldlevel = disable_irq_save();
618 /* Signal intent to wake other processor - set stay awake */
619 core_semaphores[othercore].intend_wake = 1;
620 core_semaphores[othercore].stay_awake = 1;
622 /* If it intends to sleep, wait until it does or aborts */
623 while (core_semaphores[othercore].intend_sleep != 0 &&
624 (PROC_STAT & PROC_SLEEPING(othercore)) == 0);
626 /* If sleeping, wake it up */
627 if (PROC_STAT & PROC_SLEEPING(othercore))
628 wake_core(othercore);
630 /* Done with wake procedure */
631 core_semaphores[othercore].intend_wake = 0;
632 restore_irq(oldlevel);
633 #endif /* ASM/C selection */
635 #endif /* CPU type */
637 #if NUM_CORES > 1
638 /*---------------------------------------------------------------------------
639 * Switches to a stack that always resides in the Rockbox core.
641 * Needed when a thread suicides on a core other than the main CPU since the
642 * stack used when idling is the stack of the last thread to run. This stack
643 * may not reside in the core firmware in which case the core will continue
644 * to use a stack from an unloaded module until another thread runs on it.
645 *---------------------------------------------------------------------------
647 static inline void switch_to_idle_stack(const unsigned int core)
649 asm volatile (
650 "str sp, [%0] \n" /* save original stack pointer on idle stack */
651 "mov sp, %0 \n" /* switch stacks */
652 : : "r"(&idle_stacks[core][IDLE_STACK_WORDS-1]));
653 (void)core;
656 /*---------------------------------------------------------------------------
657 * Perform core switch steps that need to take place inside switch_thread.
659 * These steps must take place while before changing the processor and after
660 * having entered switch_thread since switch_thread may not do a normal return
661 * because the stack being used for anything the compiler saved will not belong
662 * to the thread's destination core and it may have been recycled for other
663 * purposes by the time a normal context load has taken place. switch_thread
664 * will also clobber anything stashed in the thread's context or stored in the
665 * nonvolatile registers if it is saved there before the call since the
666 * compiler's order of operations cannot be known for certain.
668 static void core_switch_blk_op(unsigned int core, struct thread_entry *thread)
670 /* Flush our data to ram */
671 cpucache_flush();
672 /* Stash thread in r4 slot */
673 thread->context.r[0] = (uint32_t)thread;
674 /* Stash restart address in r5 slot */
675 thread->context.r[1] = thread->context.start;
676 /* Save sp in context.sp while still running on old core */
677 thread->context.sp = idle_stacks[core][IDLE_STACK_WORDS-1];
680 /*---------------------------------------------------------------------------
681 * Machine-specific helper function for switching the processor a thread is
682 * running on. Basically, the thread suicides on the departing core and is
683 * reborn on the destination. Were it not for gcc's ill-behavior regarding
684 * naked functions written in C where it actually clobbers non-volatile
685 * registers before the intended prologue code, this would all be much
686 * simpler. Generic setup is done in switch_core itself.
689 /*---------------------------------------------------------------------------
690 * This actually performs the core switch.
692 static void __attribute__((naked))
693 switch_thread_core(unsigned int core, struct thread_entry *thread)
695 /* Pure asm for this because compiler behavior isn't sufficiently predictable.
696 * Stack access also isn't permitted until restoring the original stack and
697 * context. */
698 asm volatile (
699 "stmfd sp!, { r4-r11, lr } \n" /* Stack all non-volatile context on current core */
700 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
701 "ldr r2, [r2, r0, lsl #2] \n"
702 "add r2, r2, %0*4 \n"
703 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
704 "mov sp, r2 \n" /* switch stacks */
705 "adr r2, 1f \n" /* r2 = new core restart address */
706 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
707 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
708 "1: \n"
709 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
710 "mov r1, #0 \n" /* Clear start address */
711 "str r1, [r0, #40] \n"
712 "ldr r0, =cpucache_invalidate \n" /* Invalidate new core's cache */
713 "mov lr, pc \n"
714 "bx r0 \n"
715 "ldmfd sp!, { r4-r11, 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) INIT_ATTR;
728 static void core_thread_init(unsigned int core)
730 if (core == CPU)
732 /* Wake up coprocessor and let it initialize kernel and threads */
733 #ifdef CPU_PP502x
734 MBX_MSG_CLR = 0x3f;
735 #endif
736 wake_core(COP);
737 /* Sleep until COP has finished */
738 sleep_core(CPU);
740 else
742 /* Wake the CPU and return */
743 wake_core(CPU);
746 #endif /* NUM_CORES */
748 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X) /* Single core only for now */ \
749 || CONFIG_CPU == IMX31L || CONFIG_CPU == DM320 || CONFIG_CPU == AS3525 \
750 || CONFIG_CPU == S3C2440 || CONFIG_CPU == S5L8701 || CONFIG_CPU == AS3525v2
751 /* Use the generic ARMv4/v5/v6 wait for IRQ */
752 static inline void core_sleep(void)
754 asm volatile (
755 "mcr p15, 0, %0, c7, c0, 4 \n" /* Wait for interrupt */
756 #if CONFIG_CPU == IMX31L
757 "nop\n nop\n nop\n nop\n nop\n" /* Clean out the pipes */
758 #endif
759 : : "r"(0)
761 enable_irq();
763 #else
764 static inline void core_sleep(void)
766 #warning core_sleep not implemented, battery life will be decreased
767 enable_irq();
769 #endif /* CONFIG_CPU == */
771 #elif defined(CPU_COLDFIRE)
772 /*---------------------------------------------------------------------------
773 * Start the thread running and terminate it if it returns
774 *---------------------------------------------------------------------------
776 void start_thread(void); /* Provide C access to ASM label */
777 static void __attribute__((used)) __start_thread(void)
779 /* a0=macsr, a1=context */
780 asm volatile (
781 "start_thread: \n" /* Start here - no naked attribute */
782 "move.l %a0, %macsr \n" /* Set initial mac status reg */
783 "lea.l 48(%a1), %a1 \n"
784 "move.l (%a1)+, %sp \n" /* Set initial stack */
785 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
786 "clr.l (%a1) \n" /* Mark thread running */
787 "jsr (%a2) \n" /* Call thread function */
789 thread_exit();
792 /* Set EMAC unit to fractional mode with saturation for each new thread,
793 * since that's what'll be the most useful for most things which the dsp
794 * will do. Codecs should still initialize their preferred modes
795 * explicitly. Context pointer is placed in d2 slot and start_thread
796 * pointer in d3 slot. thread function pointer is placed in context.start.
797 * See load_context for what happens when thread is initially going to
798 * run.
800 #define THREAD_STARTUP_INIT(core, thread, function) \
801 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
802 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
803 (thread)->context.d[1] = (uint32_t)start_thread, \
804 (thread)->context.start = (uint32_t)(function); })
806 /*---------------------------------------------------------------------------
807 * Store non-volatile context.
808 *---------------------------------------------------------------------------
810 static inline void store_context(void* addr)
812 asm volatile (
813 "move.l %%macsr,%%d0 \n"
814 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
815 : : "a" (addr) : "d0" /* only! */
819 /*---------------------------------------------------------------------------
820 * Load non-volatile context.
821 *---------------------------------------------------------------------------
823 static inline void load_context(const void* addr)
825 asm volatile (
826 "move.l 52(%0), %%d0 \n" /* Get start address */
827 "beq.b 1f \n" /* NULL -> already running */
828 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
829 "jmp (%%a2) \n" /* Start the thread */
830 "1: \n"
831 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
832 "move.l %%d0, %%macsr \n"
833 : : "a" (addr) : "d0" /* only! */
837 /*---------------------------------------------------------------------------
838 * Put core in a power-saving state if waking list wasn't repopulated.
839 *---------------------------------------------------------------------------
841 static inline void core_sleep(void)
843 /* Supervisor mode, interrupts enabled upon wakeup */
844 asm volatile ("stop #0x2000");
847 #elif CONFIG_CPU == SH7034
848 /*---------------------------------------------------------------------------
849 * Start the thread running and terminate it if it returns
850 *---------------------------------------------------------------------------
852 void start_thread(void); /* Provide C access to ASM label */
853 static void __attribute__((used)) __start_thread(void)
855 /* r8 = context */
856 asm volatile (
857 "_start_thread: \n" /* Start here - no naked attribute */
858 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
859 "mov.l @(28, r8), r15 \n" /* Set initial sp */
860 "mov #0, r1 \n" /* Start the thread */
861 "jsr @r0 \n"
862 "mov.l r1, @(36, r8) \n" /* Clear start address */
864 thread_exit();
867 /* Place context pointer in r8 slot, function pointer in r9 slot, and
868 * start_thread pointer in context_start */
869 #define THREAD_STARTUP_INIT(core, thread, function) \
870 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
871 (thread)->context.r[1] = (uint32_t)(function), \
872 (thread)->context.start = (uint32_t)start_thread; })
874 /*---------------------------------------------------------------------------
875 * Store non-volatile context.
876 *---------------------------------------------------------------------------
878 static inline void store_context(void* addr)
880 asm volatile (
881 "add #36, %0 \n" /* Start at last reg. By the time routine */
882 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
883 "mov.l r15,@-%0 \n"
884 "mov.l r14,@-%0 \n"
885 "mov.l r13,@-%0 \n"
886 "mov.l r12,@-%0 \n"
887 "mov.l r11,@-%0 \n"
888 "mov.l r10,@-%0 \n"
889 "mov.l r9, @-%0 \n"
890 "mov.l r8, @-%0 \n"
891 : : "r" (addr)
895 /*---------------------------------------------------------------------------
896 * Load non-volatile context.
897 *---------------------------------------------------------------------------
899 static inline void load_context(const void* addr)
901 asm volatile (
902 "mov.l @(36, %0), r0 \n" /* Get start address */
903 "tst r0, r0 \n"
904 "bt .running \n" /* NULL -> already running */
905 "jmp @r0 \n" /* r8 = context */
906 ".running: \n"
907 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
908 "mov.l @%0+, r9 \n"
909 "mov.l @%0+, r10 \n"
910 "mov.l @%0+, r11 \n"
911 "mov.l @%0+, r12 \n"
912 "mov.l @%0+, r13 \n"
913 "mov.l @%0+, r14 \n"
914 "mov.l @%0+, r15 \n"
915 "lds.l @%0+, pr \n"
916 : : "r" (addr) : "r0" /* only! */
920 /*---------------------------------------------------------------------------
921 * Put core in a power-saving state.
922 *---------------------------------------------------------------------------
924 static inline void core_sleep(void)
926 asm volatile (
927 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
928 "mov #0, r1 \n" /* Enable interrupts */
929 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
930 "sleep \n" /* Execute standby */
931 : : "z"(&SBYCR-GBR) : "r1");
934 #elif defined(CPU_MIPS) && CPU_MIPS == 32
936 /*---------------------------------------------------------------------------
937 * Start the thread running and terminate it if it returns
938 *---------------------------------------------------------------------------
941 void start_thread(void); /* Provide C access to ASM label */
942 static void __attribute__((used)) _start_thread(void)
944 /* t1 = context */
945 asm volatile (
946 "start_thread: \n"
947 ".set noreorder \n"
948 ".set noat \n"
949 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = t0, $9 = t1) */
950 "lw $29, 36($9) \n" /* Set initial sp(=$29) */
951 "jalr $8 \n" /* Start the thread */
952 "sw $0, 44($9) \n" /* Clear start address */
953 ".set at \n"
954 ".set reorder \n"
956 thread_exit();
959 /* Place context pointer in s0 slot, function pointer in s1 slot, and
960 * start_thread pointer in context_start */
961 #define THREAD_STARTUP_INIT(core, thread, function) \
962 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
963 (thread)->context.r[1] = (uint32_t)(function), \
964 (thread)->context.start = (uint32_t)start_thread; })
966 /*---------------------------------------------------------------------------
967 * Store non-volatile context.
968 *---------------------------------------------------------------------------
970 static inline void store_context(void* addr)
972 asm volatile (
973 ".set noreorder \n"
974 ".set noat \n"
975 "sw $16, 0(%0) \n" /* s0 */
976 "sw $17, 4(%0) \n" /* s1 */
977 "sw $18, 8(%0) \n" /* s2 */
978 "sw $19, 12(%0) \n" /* s3 */
979 "sw $20, 16(%0) \n" /* s4 */
980 "sw $21, 20(%0) \n" /* s5 */
981 "sw $22, 24(%0) \n" /* s6 */
982 "sw $23, 28(%0) \n" /* s7 */
983 "sw $30, 32(%0) \n" /* fp */
984 "sw $29, 36(%0) \n" /* sp */
985 "sw $31, 40(%0) \n" /* ra */
986 ".set at \n"
987 ".set reorder \n"
988 : : "r" (addr)
992 /*---------------------------------------------------------------------------
993 * Load non-volatile context.
994 *---------------------------------------------------------------------------
996 static inline void load_context(const void* addr)
998 asm volatile (
999 ".set noat \n"
1000 ".set noreorder \n"
1001 "lw $8, 44(%0) \n" /* Get start address ($8 = t0) */
1002 "beqz $8, running \n" /* NULL -> already running */
1003 "nop \n"
1004 "jr $8 \n"
1005 "move $9, %0 \n" /* t1 = context */
1006 "running: \n"
1007 "lw $16, 0(%0) \n" /* s0 */
1008 "lw $17, 4(%0) \n" /* s1 */
1009 "lw $18, 8(%0) \n" /* s2 */
1010 "lw $19, 12(%0) \n" /* s3 */
1011 "lw $20, 16(%0) \n" /* s4 */
1012 "lw $21, 20(%0) \n" /* s5 */
1013 "lw $22, 24(%0) \n" /* s6 */
1014 "lw $23, 28(%0) \n" /* s7 */
1015 "lw $30, 32(%0) \n" /* fp */
1016 "lw $29, 36(%0) \n" /* sp */
1017 "lw $31, 40(%0) \n" /* ra */
1018 ".set at \n"
1019 ".set reorder \n"
1020 : : "r" (addr) : "t0", "t1"
1024 /*---------------------------------------------------------------------------
1025 * Put core in a power-saving state.
1026 *---------------------------------------------------------------------------
1028 static inline void core_sleep(void)
1030 #if CONFIG_CPU == JZ4732
1031 __cpm_idle_mode();
1032 #endif
1033 asm volatile(".set mips32r2 \n"
1034 "mfc0 $8, $12 \n" /* mfc t0, $12 */
1035 "move $9, $8 \n" /* move t1, t0 */
1036 "la $10, 0x8000000 \n" /* la t2, 0x8000000 */
1037 "or $8, $8, $10 \n" /* Enable reduced power mode */
1038 "mtc0 $8, $12 \n" /* mtc t0, $12 */
1039 "wait \n"
1040 "mtc0 $9, $12 \n" /* mtc t1, $12 */
1041 ".set mips0 \n"
1042 ::: "t0", "t1", "t2"
1044 enable_irq();
1048 #endif /* CONFIG_CPU == */
1051 * End Processor-specific section
1052 ***************************************************************************/
1054 #if THREAD_EXTRA_CHECKS
1055 static void thread_panicf(const char *msg, struct thread_entry *thread)
1057 IF_COP( const unsigned int core = thread->core; )
1058 static char name[32];
1059 thread_get_name(name, 32, thread);
1060 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
1062 static void thread_stkov(struct thread_entry *thread)
1064 thread_panicf("Stkov", thread);
1066 #define THREAD_PANICF(msg, thread) \
1067 thread_panicf(msg, thread)
1068 #define THREAD_ASSERT(exp, msg, thread) \
1069 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1070 #else
1071 static void thread_stkov(struct thread_entry *thread)
1073 IF_COP( const unsigned int core = thread->core; )
1074 static char name[32];
1075 thread_get_name(name, 32, thread);
1076 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
1078 #define THREAD_PANICF(msg, thread)
1079 #define THREAD_ASSERT(exp, msg, thread)
1080 #endif /* THREAD_EXTRA_CHECKS */
1082 /* Thread locking */
1083 #if NUM_CORES > 1
1084 #define LOCK_THREAD(thread) \
1085 ({ corelock_lock(&(thread)->slot_cl); })
1086 #define TRY_LOCK_THREAD(thread) \
1087 ({ corelock_try_lock(&thread->slot_cl); })
1088 #define UNLOCK_THREAD(thread) \
1089 ({ corelock_unlock(&(thread)->slot_cl); })
1090 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1091 ({ unsigned int _core = (thread)->core; \
1092 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1093 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1094 #else
1095 #define LOCK_THREAD(thread) \
1096 ({ })
1097 #define TRY_LOCK_THREAD(thread) \
1098 ({ })
1099 #define UNLOCK_THREAD(thread) \
1100 ({ })
1101 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1102 ({ })
1103 #endif
1105 /* RTR list */
1106 #define RTR_LOCK(core) \
1107 ({ corelock_lock(&cores[core].rtr_cl); })
1108 #define RTR_UNLOCK(core) \
1109 ({ corelock_unlock(&cores[core].rtr_cl); })
1111 #ifdef HAVE_PRIORITY_SCHEDULING
1112 #define rtr_add_entry(core, priority) \
1113 prio_add_entry(&cores[core].rtr, (priority))
1115 #define rtr_subtract_entry(core, priority) \
1116 prio_subtract_entry(&cores[core].rtr, (priority))
1118 #define rtr_move_entry(core, from, to) \
1119 prio_move_entry(&cores[core].rtr, (from), (to))
1120 #else
1121 #define rtr_add_entry(core, priority)
1122 #define rtr_add_entry_inl(core, priority)
1123 #define rtr_subtract_entry(core, priority)
1124 #define rtr_subtract_entry_inl(core, priotity)
1125 #define rtr_move_entry(core, from, to)
1126 #define rtr_move_entry_inl(core, from, to)
1127 #endif
1129 /*---------------------------------------------------------------------------
1130 * Thread list structure - circular:
1131 * +------------------------------+
1132 * | |
1133 * +--+---+<-+---+<-+---+<-+---+<-+
1134 * Head->| T | | T | | T | | T |
1135 * +->+---+->+---+->+---+->+---+--+
1136 * | |
1137 * +------------------------------+
1138 *---------------------------------------------------------------------------
1141 /*---------------------------------------------------------------------------
1142 * Adds a thread to a list of threads using "insert last". Uses the "l"
1143 * links.
1144 *---------------------------------------------------------------------------
1146 static void add_to_list_l(struct thread_entry **list,
1147 struct thread_entry *thread)
1149 struct thread_entry *l = *list;
1151 if (l == NULL)
1153 /* Insert into unoccupied list */
1154 thread->l.prev = thread;
1155 thread->l.next = thread;
1156 *list = thread;
1157 return;
1160 /* Insert last */
1161 thread->l.prev = l->l.prev;
1162 thread->l.next = l;
1163 l->l.prev->l.next = thread;
1164 l->l.prev = thread;
1167 /*---------------------------------------------------------------------------
1168 * Removes a thread from a list of threads. Uses the "l" links.
1169 *---------------------------------------------------------------------------
1171 static void remove_from_list_l(struct thread_entry **list,
1172 struct thread_entry *thread)
1174 struct thread_entry *prev, *next;
1176 next = thread->l.next;
1178 if (thread == next)
1180 /* The only item */
1181 *list = NULL;
1182 return;
1185 if (thread == *list)
1187 /* List becomes next item */
1188 *list = next;
1191 prev = thread->l.prev;
1193 /* Fix links to jump over the removed entry. */
1194 next->l.prev = prev;
1195 prev->l.next = next;
1198 /*---------------------------------------------------------------------------
1199 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1200 * NULL-terminated forward (to ease the far more common forward traversal):
1201 * +------------------------------+
1202 * | |
1203 * +--+---+<-+---+<-+---+<-+---+<-+
1204 * Head->| T | | T | | T | | T |
1205 * +---+->+---+->+---+->+---+-X
1206 *---------------------------------------------------------------------------
1209 /*---------------------------------------------------------------------------
1210 * Add a thread from the core's timout list by linking the pointers in its
1211 * tmo structure.
1212 *---------------------------------------------------------------------------
1214 static void add_to_list_tmo(struct thread_entry *thread)
1216 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
1217 THREAD_ASSERT(thread->tmo.prev == NULL,
1218 "add_to_list_tmo->already listed", thread);
1220 thread->tmo.next = NULL;
1222 if (tmo == NULL)
1224 /* Insert into unoccupied list */
1225 thread->tmo.prev = thread;
1226 cores[IF_COP_CORE(thread->core)].timeout = thread;
1227 return;
1230 /* Insert Last */
1231 thread->tmo.prev = tmo->tmo.prev;
1232 tmo->tmo.prev->tmo.next = thread;
1233 tmo->tmo.prev = thread;
1236 /*---------------------------------------------------------------------------
1237 * Remove a thread from the core's timout list by unlinking the pointers in
1238 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1239 * is cancelled.
1240 *---------------------------------------------------------------------------
1242 static void remove_from_list_tmo(struct thread_entry *thread)
1244 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
1245 struct thread_entry *prev = thread->tmo.prev;
1246 struct thread_entry *next = thread->tmo.next;
1248 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
1250 if (next != NULL)
1251 next->tmo.prev = prev;
1253 if (thread == *list)
1255 /* List becomes next item and empty if next == NULL */
1256 *list = next;
1257 /* Mark as unlisted */
1258 thread->tmo.prev = NULL;
1260 else
1262 if (next == NULL)
1263 (*list)->tmo.prev = prev;
1264 prev->tmo.next = next;
1265 /* Mark as unlisted */
1266 thread->tmo.prev = NULL;
1271 #ifdef HAVE_PRIORITY_SCHEDULING
1272 /*---------------------------------------------------------------------------
1273 * Priority distribution structure (one category for each possible priority):
1275 * +----+----+----+ ... +-----+
1276 * hist: | F0 | F1 | F2 | | F31 |
1277 * +----+----+----+ ... +-----+
1278 * mask: | b0 | b1 | b2 | | b31 |
1279 * +----+----+----+ ... +-----+
1281 * F = count of threads at priority category n (frequency)
1282 * b = bitmask of non-zero priority categories (occupancy)
1284 * / if H[n] != 0 : 1
1285 * b[n] = |
1286 * \ else : 0
1288 *---------------------------------------------------------------------------
1289 * Basic priority inheritance priotocol (PIP):
1291 * Mn = mutex n, Tn = thread n
1293 * A lower priority thread inherits the priority of the highest priority
1294 * thread blocked waiting for it to complete an action (such as release a
1295 * mutex or respond to a message via queue_send):
1297 * 1) T2->M1->T1
1299 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1300 * priority than T1 then T1 inherits the priority of T2.
1302 * 2) T3
1303 * \/
1304 * T2->M1->T1
1306 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1307 * T1 inherits the higher of T2 and T3.
1309 * 3) T3->M2->T2->M1->T1
1311 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1312 * then T1 inherits the priority of T3 through T2.
1314 * Blocking chains can grow arbitrarily complex (though it's best that they
1315 * not form at all very often :) and build-up from these units.
1316 *---------------------------------------------------------------------------
1319 /*---------------------------------------------------------------------------
1320 * Increment frequency at category "priority"
1321 *---------------------------------------------------------------------------
1323 static inline unsigned int prio_add_entry(
1324 struct priority_distribution *pd, int priority)
1326 unsigned int count;
1327 /* Enough size/instruction count difference for ARM makes it worth it to
1328 * use different code (192 bytes for ARM). Only thing better is ASM. */
1329 #ifdef CPU_ARM
1330 count = pd->hist[priority];
1331 if (++count == 1)
1332 pd->mask |= 1 << priority;
1333 pd->hist[priority] = count;
1334 #else /* This one's better for Coldfire */
1335 if ((count = ++pd->hist[priority]) == 1)
1336 pd->mask |= 1 << priority;
1337 #endif
1339 return count;
1342 /*---------------------------------------------------------------------------
1343 * Decrement frequency at category "priority"
1344 *---------------------------------------------------------------------------
1346 static inline unsigned int prio_subtract_entry(
1347 struct priority_distribution *pd, int priority)
1349 unsigned int count;
1351 #ifdef CPU_ARM
1352 count = pd->hist[priority];
1353 if (--count == 0)
1354 pd->mask &= ~(1 << priority);
1355 pd->hist[priority] = count;
1356 #else
1357 if ((count = --pd->hist[priority]) == 0)
1358 pd->mask &= ~(1 << priority);
1359 #endif
1361 return count;
1364 /*---------------------------------------------------------------------------
1365 * Remove from one category and add to another
1366 *---------------------------------------------------------------------------
1368 static inline void prio_move_entry(
1369 struct priority_distribution *pd, int from, int to)
1371 uint32_t mask = pd->mask;
1373 #ifdef CPU_ARM
1374 unsigned int count;
1376 count = pd->hist[from];
1377 if (--count == 0)
1378 mask &= ~(1 << from);
1379 pd->hist[from] = count;
1381 count = pd->hist[to];
1382 if (++count == 1)
1383 mask |= 1 << to;
1384 pd->hist[to] = count;
1385 #else
1386 if (--pd->hist[from] == 0)
1387 mask &= ~(1 << from);
1389 if (++pd->hist[to] == 1)
1390 mask |= 1 << to;
1391 #endif
1393 pd->mask = mask;
1396 /*---------------------------------------------------------------------------
1397 * Change the priority and rtr entry for a running thread
1398 *---------------------------------------------------------------------------
1400 static inline void set_running_thread_priority(
1401 struct thread_entry *thread, int priority)
1403 const unsigned int core = IF_COP_CORE(thread->core);
1404 RTR_LOCK(core);
1405 rtr_move_entry(core, thread->priority, priority);
1406 thread->priority = priority;
1407 RTR_UNLOCK(core);
1410 /*---------------------------------------------------------------------------
1411 * Finds the highest priority thread in a list of threads. If the list is
1412 * empty, the PRIORITY_IDLE is returned.
1414 * It is possible to use the struct priority_distribution within an object
1415 * instead of scanning the remaining threads in the list but as a compromise,
1416 * the resulting per-object memory overhead is saved at a slight speed
1417 * penalty under high contention.
1418 *---------------------------------------------------------------------------
1420 static int find_highest_priority_in_list_l(
1421 struct thread_entry * const thread)
1423 if (LIKELY(thread != NULL))
1425 /* Go though list until the ending up at the initial thread */
1426 int highest_priority = thread->priority;
1427 struct thread_entry *curr = thread;
1431 int priority = curr->priority;
1433 if (priority < highest_priority)
1434 highest_priority = priority;
1436 curr = curr->l.next;
1438 while (curr != thread);
1440 return highest_priority;
1443 return PRIORITY_IDLE;
1446 /*---------------------------------------------------------------------------
1447 * Register priority with blocking system and bubble it down the chain if
1448 * any until we reach the end or something is already equal or higher.
1450 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1451 * targets but that same action also guarantees a circular block anyway and
1452 * those are prevented, right? :-)
1453 *---------------------------------------------------------------------------
1455 static struct thread_entry *
1456 blocker_inherit_priority(struct thread_entry *current)
1458 const int priority = current->priority;
1459 struct blocker *bl = current->blocker;
1460 struct thread_entry * const tstart = current;
1461 struct thread_entry *bl_t = bl->thread;
1463 /* Blocker cannot change since the object protection is held */
1464 LOCK_THREAD(bl_t);
1466 for (;;)
1468 struct thread_entry *next;
1469 int bl_pr = bl->priority;
1471 if (priority >= bl_pr)
1472 break; /* Object priority already high enough */
1474 bl->priority = priority;
1476 /* Add this one */
1477 prio_add_entry(&bl_t->pdist, priority);
1479 if (bl_pr < PRIORITY_IDLE)
1481 /* Not first waiter - subtract old one */
1482 prio_subtract_entry(&bl_t->pdist, bl_pr);
1485 if (priority >= bl_t->priority)
1486 break; /* Thread priority high enough */
1488 if (bl_t->state == STATE_RUNNING)
1490 /* Blocking thread is a running thread therefore there are no
1491 * further blockers. Change the "run queue" on which it
1492 * resides. */
1493 set_running_thread_priority(bl_t, priority);
1494 break;
1497 bl_t->priority = priority;
1499 /* If blocking thread has a blocker, apply transitive inheritance */
1500 bl = bl_t->blocker;
1502 if (bl == NULL)
1503 break; /* End of chain or object doesn't support inheritance */
1505 next = bl->thread;
1507 if (UNLIKELY(next == tstart))
1508 break; /* Full-circle - deadlock! */
1510 UNLOCK_THREAD(current);
1512 #if NUM_CORES > 1
1513 for (;;)
1515 LOCK_THREAD(next);
1517 /* Blocker could change - retest condition */
1518 if (LIKELY(bl->thread == next))
1519 break;
1521 UNLOCK_THREAD(next);
1522 next = bl->thread;
1524 #endif
1525 current = bl_t;
1526 bl_t = next;
1529 UNLOCK_THREAD(bl_t);
1531 return current;
1534 /*---------------------------------------------------------------------------
1535 * Readjust priorities when waking a thread blocked waiting for another
1536 * in essence "releasing" the thread's effect on the object owner. Can be
1537 * performed from any context.
1538 *---------------------------------------------------------------------------
1540 struct thread_entry *
1541 wakeup_priority_protocol_release(struct thread_entry *thread)
1543 const int priority = thread->priority;
1544 struct blocker *bl = thread->blocker;
1545 struct thread_entry * const tstart = thread;
1546 struct thread_entry *bl_t = bl->thread;
1548 /* Blocker cannot change since object will be locked */
1549 LOCK_THREAD(bl_t);
1551 thread->blocker = NULL; /* Thread not blocked */
1553 for (;;)
1555 struct thread_entry *next;
1556 int bl_pr = bl->priority;
1558 if (priority > bl_pr)
1559 break; /* Object priority higher */
1561 next = *thread->bqp;
1563 if (next == NULL)
1565 /* No more threads in queue */
1566 prio_subtract_entry(&bl_t->pdist, bl_pr);
1567 bl->priority = PRIORITY_IDLE;
1569 else
1571 /* Check list for highest remaining priority */
1572 int queue_pr = find_highest_priority_in_list_l(next);
1574 if (queue_pr == bl_pr)
1575 break; /* Object priority not changing */
1577 /* Change queue priority */
1578 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
1579 bl->priority = queue_pr;
1582 if (bl_pr > bl_t->priority)
1583 break; /* thread priority is higher */
1585 bl_pr = find_first_set_bit(bl_t->pdist.mask);
1587 if (bl_pr == bl_t->priority)
1588 break; /* Thread priority not changing */
1590 if (bl_t->state == STATE_RUNNING)
1592 /* No further blockers */
1593 set_running_thread_priority(bl_t, bl_pr);
1594 break;
1597 bl_t->priority = bl_pr;
1599 /* If blocking thread has a blocker, apply transitive inheritance */
1600 bl = bl_t->blocker;
1602 if (bl == NULL)
1603 break; /* End of chain or object doesn't support inheritance */
1605 next = bl->thread;
1607 if (UNLIKELY(next == tstart))
1608 break; /* Full-circle - deadlock! */
1610 UNLOCK_THREAD(thread);
1612 #if NUM_CORES > 1
1613 for (;;)
1615 LOCK_THREAD(next);
1617 /* Blocker could change - retest condition */
1618 if (LIKELY(bl->thread == next))
1619 break;
1621 UNLOCK_THREAD(next);
1622 next = bl->thread;
1624 #endif
1625 thread = bl_t;
1626 bl_t = next;
1629 UNLOCK_THREAD(bl_t);
1631 #if NUM_CORES > 1
1632 if (UNLIKELY(thread != tstart))
1634 /* Relock original if it changed */
1635 LOCK_THREAD(tstart);
1637 #endif
1639 return cores[CURRENT_CORE].running;
1642 /*---------------------------------------------------------------------------
1643 * Transfer ownership to a thread waiting for an objects and transfer
1644 * inherited priority boost from other waiters. This algorithm knows that
1645 * blocking chains may only unblock from the very end.
1647 * Only the owning thread itself may call this and so the assumption that
1648 * it is the running thread is made.
1649 *---------------------------------------------------------------------------
1651 struct thread_entry *
1652 wakeup_priority_protocol_transfer(struct thread_entry *thread)
1654 /* Waking thread inherits priority boost from object owner */
1655 struct blocker *bl = thread->blocker;
1656 struct thread_entry *bl_t = bl->thread;
1657 struct thread_entry *next;
1658 int bl_pr;
1660 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
1661 "UPPT->wrong thread", cores[CURRENT_CORE].running);
1663 LOCK_THREAD(bl_t);
1665 bl_pr = bl->priority;
1667 /* Remove the object's boost from the owning thread */
1668 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
1669 bl_pr <= bl_t->priority)
1671 /* No more threads at this priority are waiting and the old level is
1672 * at least the thread level */
1673 int priority = find_first_set_bit(bl_t->pdist.mask);
1675 if (priority != bl_t->priority)
1677 /* Adjust this thread's priority */
1678 set_running_thread_priority(bl_t, priority);
1682 next = *thread->bqp;
1684 if (LIKELY(next == NULL))
1686 /* Expected shortcut - no more waiters */
1687 bl_pr = PRIORITY_IDLE;
1689 else
1691 if (thread->priority <= bl_pr)
1693 /* Need to scan threads remaining in queue */
1694 bl_pr = find_highest_priority_in_list_l(next);
1697 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
1698 bl_pr < thread->priority)
1700 /* Thread priority must be raised */
1701 thread->priority = bl_pr;
1705 bl->thread = thread; /* This thread pwns */
1706 bl->priority = bl_pr; /* Save highest blocked priority */
1707 thread->blocker = NULL; /* Thread not blocked */
1709 UNLOCK_THREAD(bl_t);
1711 return bl_t;
1714 /*---------------------------------------------------------------------------
1715 * No threads must be blocked waiting for this thread except for it to exit.
1716 * The alternative is more elaborate cleanup and object registration code.
1717 * Check this for risk of silent data corruption when objects with
1718 * inheritable blocking are abandoned by the owner - not precise but may
1719 * catch something.
1720 *---------------------------------------------------------------------------
1722 static void check_for_obj_waiters(const char *function, struct thread_entry *thread)
1724 /* Only one bit in the mask should be set with a frequency on 1 which
1725 * represents the thread's own base priority */
1726 uint32_t mask = thread->pdist.mask;
1727 if ((mask & (mask - 1)) != 0 ||
1728 thread->pdist.hist[find_first_set_bit(mask)] > 1)
1730 unsigned char name[32];
1731 thread_get_name(name, 32, thread);
1732 panicf("%s->%s with obj. waiters", function, name);
1735 #endif /* HAVE_PRIORITY_SCHEDULING */
1737 /*---------------------------------------------------------------------------
1738 * Move a thread back to a running state on its core.
1739 *---------------------------------------------------------------------------
1741 static void core_schedule_wakeup(struct thread_entry *thread)
1743 const unsigned int core = IF_COP_CORE(thread->core);
1745 RTR_LOCK(core);
1747 thread->state = STATE_RUNNING;
1749 add_to_list_l(&cores[core].running, thread);
1750 rtr_add_entry(core, thread->priority);
1752 RTR_UNLOCK(core);
1754 #if NUM_CORES > 1
1755 if (core != CURRENT_CORE)
1756 core_wake(core);
1757 #endif
1760 /*---------------------------------------------------------------------------
1761 * Check the core's timeout list when at least one thread is due to wake.
1762 * Filtering for the condition is done before making the call. Resets the
1763 * tick when the next check will occur.
1764 *---------------------------------------------------------------------------
1766 void check_tmo_threads(void)
1768 const unsigned int core = CURRENT_CORE;
1769 const long tick = current_tick; /* snapshot the current tick */
1770 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
1771 struct thread_entry *next = cores[core].timeout;
1773 /* If there are no processes waiting for a timeout, just keep the check
1774 tick from falling into the past. */
1776 /* Break the loop once we have walked through the list of all
1777 * sleeping processes or have removed them all. */
1778 while (next != NULL)
1780 /* Check sleeping threads. Allow interrupts between checks. */
1781 enable_irq();
1783 struct thread_entry *curr = next;
1785 next = curr->tmo.next;
1787 /* Lock thread slot against explicit wakeup */
1788 disable_irq();
1789 LOCK_THREAD(curr);
1791 unsigned state = curr->state;
1793 if (state < TIMEOUT_STATE_FIRST)
1795 /* Cleanup threads no longer on a timeout but still on the
1796 * list. */
1797 remove_from_list_tmo(curr);
1799 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
1801 /* Timeout still pending - this will be the usual case */
1802 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
1804 /* Earliest timeout found so far - move the next check up
1805 to its time */
1806 next_tmo_check = curr->tmo_tick;
1809 else
1811 /* Sleep timeout has been reached so bring the thread back to
1812 * life again. */
1813 if (state == STATE_BLOCKED_W_TMO)
1815 #if NUM_CORES > 1
1816 /* Lock the waiting thread's kernel object */
1817 struct corelock *ocl = curr->obj_cl;
1819 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1821 /* Need to retry in the correct order though the need is
1822 * unlikely */
1823 UNLOCK_THREAD(curr);
1824 corelock_lock(ocl);
1825 LOCK_THREAD(curr);
1827 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
1829 /* Thread was woken or removed explicitely while slot
1830 * was unlocked */
1831 corelock_unlock(ocl);
1832 remove_from_list_tmo(curr);
1833 UNLOCK_THREAD(curr);
1834 continue;
1837 #endif /* NUM_CORES */
1839 remove_from_list_l(curr->bqp, curr);
1841 #ifdef HAVE_WAKEUP_EXT_CB
1842 if (curr->wakeup_ext_cb != NULL)
1843 curr->wakeup_ext_cb(curr);
1844 #endif
1846 #ifdef HAVE_PRIORITY_SCHEDULING
1847 if (curr->blocker != NULL)
1848 wakeup_priority_protocol_release(curr);
1849 #endif
1850 corelock_unlock(ocl);
1852 /* else state == STATE_SLEEPING */
1854 remove_from_list_tmo(curr);
1856 RTR_LOCK(core);
1858 curr->state = STATE_RUNNING;
1860 add_to_list_l(&cores[core].running, curr);
1861 rtr_add_entry(core, curr->priority);
1863 RTR_UNLOCK(core);
1866 UNLOCK_THREAD(curr);
1869 cores[core].next_tmo_check = next_tmo_check;
1872 /*---------------------------------------------------------------------------
1873 * Performs operations that must be done before blocking a thread but after
1874 * the state is saved.
1875 *---------------------------------------------------------------------------
1877 #if NUM_CORES > 1
1878 static inline void run_blocking_ops(
1879 unsigned int core, struct thread_entry *thread)
1881 struct thread_blk_ops *ops = &cores[core].blk_ops;
1882 const unsigned flags = ops->flags;
1884 if (LIKELY(flags == TBOP_CLEAR))
1885 return;
1887 switch (flags)
1889 case TBOP_SWITCH_CORE:
1890 core_switch_blk_op(core, thread);
1891 /* Fall-through */
1892 case TBOP_UNLOCK_CORELOCK:
1893 corelock_unlock(ops->cl_p);
1894 break;
1897 ops->flags = TBOP_CLEAR;
1899 #endif /* NUM_CORES > 1 */
1901 #ifdef RB_PROFILE
1902 void profile_thread(void)
1904 profstart(cores[CURRENT_CORE].running - threads);
1906 #endif
1908 /*---------------------------------------------------------------------------
1909 * Prepares a thread to block on an object's list and/or for a specified
1910 * duration - expects object and slot to be appropriately locked if needed
1911 * and interrupts to be masked.
1912 *---------------------------------------------------------------------------
1914 static inline void block_thread_on_l(struct thread_entry *thread,
1915 unsigned state)
1917 /* If inlined, unreachable branches will be pruned with no size penalty
1918 because state is passed as a constant parameter. */
1919 const unsigned int core = IF_COP_CORE(thread->core);
1921 /* Remove the thread from the list of running threads. */
1922 RTR_LOCK(core);
1923 remove_from_list_l(&cores[core].running, thread);
1924 rtr_subtract_entry(core, thread->priority);
1925 RTR_UNLOCK(core);
1927 /* Add a timeout to the block if not infinite */
1928 switch (state)
1930 case STATE_BLOCKED:
1931 case STATE_BLOCKED_W_TMO:
1932 /* Put the thread into a new list of inactive threads. */
1933 add_to_list_l(thread->bqp, thread);
1935 if (state == STATE_BLOCKED)
1936 break;
1938 /* Fall-through */
1939 case STATE_SLEEPING:
1940 /* If this thread times out sooner than any other thread, update
1941 next_tmo_check to its timeout */
1942 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1944 cores[core].next_tmo_check = thread->tmo_tick;
1947 if (thread->tmo.prev == NULL)
1949 add_to_list_tmo(thread);
1951 /* else thread was never removed from list - just keep it there */
1952 break;
1955 /* Remember the the next thread about to block. */
1956 cores[core].block_task = thread;
1958 /* Report new state. */
1959 thread->state = state;
1962 /*---------------------------------------------------------------------------
1963 * Switch thread in round robin fashion for any given priority. Any thread
1964 * that removed itself from the running list first must specify itself in
1965 * the paramter.
1967 * INTERNAL: Intended for use by kernel and not for programs.
1968 *---------------------------------------------------------------------------
1970 void switch_thread(void)
1973 const unsigned int core = CURRENT_CORE;
1974 struct thread_entry *block = cores[core].block_task;
1975 struct thread_entry *thread = cores[core].running;
1977 /* Get context to save - next thread to run is unknown until all wakeups
1978 * are evaluated */
1979 if (block != NULL)
1981 cores[core].block_task = NULL;
1983 #if NUM_CORES > 1
1984 if (UNLIKELY(thread == block))
1986 /* This was the last thread running and another core woke us before
1987 * reaching here. Force next thread selection to give tmo threads or
1988 * other threads woken before this block a first chance. */
1989 block = NULL;
1991 else
1992 #endif
1994 /* Blocking task is the old one */
1995 thread = block;
1999 #ifdef RB_PROFILE
2000 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
2001 #endif
2003 /* Begin task switching by saving our current context so that we can
2004 * restore the state of the current thread later to the point prior
2005 * to this call. */
2006 store_context(&thread->context);
2008 /* Check if the current thread stack is overflown */
2009 if (UNLIKELY(thread->stack[0] != DEADBEEF))
2010 thread_stkov(thread);
2012 #if NUM_CORES > 1
2013 /* Run any blocking operations requested before switching/sleeping */
2014 run_blocking_ops(core, thread);
2015 #endif
2017 #ifdef HAVE_PRIORITY_SCHEDULING
2018 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2019 /* Reset the value of thread's skip count */
2020 thread->skip_count = 0;
2021 #endif
2023 for (;;)
2025 /* If there are threads on a timeout and the earliest wakeup is due,
2026 * check the list and wake any threads that need to start running
2027 * again. */
2028 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
2030 check_tmo_threads();
2033 disable_irq();
2034 RTR_LOCK(core);
2036 thread = cores[core].running;
2038 if (UNLIKELY(thread == NULL))
2040 /* Enter sleep mode to reduce power usage - woken up on interrupt
2041 * or wakeup request from another core - expected to enable
2042 * interrupts. */
2043 RTR_UNLOCK(core);
2044 core_sleep(IF_COP(core));
2046 else
2048 #ifdef HAVE_PRIORITY_SCHEDULING
2049 /* Select the new task based on priorities and the last time a
2050 * process got CPU time relative to the highest priority runnable
2051 * task. */
2052 struct priority_distribution *pd = &cores[core].rtr;
2053 int max = find_first_set_bit(pd->mask);
2055 if (block == NULL)
2057 /* Not switching on a block, tentatively select next thread */
2058 thread = thread->l.next;
2061 for (;;)
2063 int priority = thread->priority;
2064 int diff;
2066 /* This ridiculously simple method of aging seems to work
2067 * suspiciously well. It does tend to reward CPU hogs (under
2068 * yielding) but that's generally not desirable at all. On
2069 * the plus side, it, relatively to other threads, penalizes
2070 * excess yielding which is good if some high priority thread
2071 * is performing no useful work such as polling for a device
2072 * to be ready. Of course, aging is only employed when higher
2073 * and lower priority threads are runnable. The highest
2074 * priority runnable thread(s) are never skipped unless a
2075 * lower-priority process has aged sufficiently. Priorities
2076 * of REALTIME class are run strictly according to priority
2077 * thus are not subject to switchout due to lower-priority
2078 * processes aging; they must give up the processor by going
2079 * off the run list. */
2080 if (LIKELY(priority <= max) ||
2081 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
2082 (priority > PRIORITY_REALTIME &&
2083 (diff = priority - max,
2084 ++thread->skip_count > diff*diff)))
2086 cores[core].running = thread;
2087 break;
2090 thread = thread->l.next;
2092 #else
2093 /* Without priority use a simple FCFS algorithm */
2094 if (block == NULL)
2096 /* Not switching on a block, select next thread */
2097 thread = thread->l.next;
2098 cores[core].running = thread;
2100 #endif /* HAVE_PRIORITY_SCHEDULING */
2102 RTR_UNLOCK(core);
2103 enable_irq();
2104 break;
2108 /* And finally give control to the next thread. */
2109 load_context(&thread->context);
2111 #ifdef RB_PROFILE
2112 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
2113 #endif
2117 /*---------------------------------------------------------------------------
2118 * Sleeps a thread for at least a specified number of ticks with zero being
2119 * a wait until the next tick.
2121 * INTERNAL: Intended for use by kernel and not for programs.
2122 *---------------------------------------------------------------------------
2124 void sleep_thread(int ticks)
2126 struct thread_entry *current = cores[CURRENT_CORE].running;
2128 LOCK_THREAD(current);
2130 /* Set our timeout, remove from run list and join timeout list. */
2131 current->tmo_tick = current_tick + ticks + 1;
2132 block_thread_on_l(current, STATE_SLEEPING);
2134 UNLOCK_THREAD(current);
2137 /*---------------------------------------------------------------------------
2138 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2140 * INTERNAL: Intended for use by kernel objects and not for programs.
2141 *---------------------------------------------------------------------------
2143 void block_thread(struct thread_entry *current)
2145 /* Set the state to blocked and take us off of the run queue until we
2146 * are explicitly woken */
2147 LOCK_THREAD(current);
2149 /* Set the list for explicit wakeup */
2150 block_thread_on_l(current, STATE_BLOCKED);
2152 #ifdef HAVE_PRIORITY_SCHEDULING
2153 if (current->blocker != NULL)
2155 /* Object supports PIP */
2156 current = blocker_inherit_priority(current);
2158 #endif
2160 UNLOCK_THREAD(current);
2163 /*---------------------------------------------------------------------------
2164 * Block a thread on a blocking queue for a specified time interval or until
2165 * explicitly woken - whichever happens first.
2167 * INTERNAL: Intended for use by kernel objects and not for programs.
2168 *---------------------------------------------------------------------------
2170 void block_thread_w_tmo(struct thread_entry *current, int timeout)
2172 /* Get the entry for the current running thread. */
2173 LOCK_THREAD(current);
2175 /* Set the state to blocked with the specified timeout */
2176 current->tmo_tick = current_tick + timeout;
2178 /* Set the list for explicit wakeup */
2179 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
2181 #ifdef HAVE_PRIORITY_SCHEDULING
2182 if (current->blocker != NULL)
2184 /* Object supports PIP */
2185 current = blocker_inherit_priority(current);
2187 #endif
2189 UNLOCK_THREAD(current);
2192 /*---------------------------------------------------------------------------
2193 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2194 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2196 * This code should be considered a critical section by the caller meaning
2197 * that the object's corelock should be held.
2199 * INTERNAL: Intended for use by kernel objects and not for programs.
2200 *---------------------------------------------------------------------------
2202 unsigned int wakeup_thread(struct thread_entry **list)
2204 struct thread_entry *thread = *list;
2205 unsigned int result = THREAD_NONE;
2207 /* Check if there is a blocked thread at all. */
2208 if (thread == NULL)
2209 return result;
2211 LOCK_THREAD(thread);
2213 /* Determine thread's current state. */
2214 switch (thread->state)
2216 case STATE_BLOCKED:
2217 case STATE_BLOCKED_W_TMO:
2218 remove_from_list_l(list, thread);
2220 result = THREAD_OK;
2222 #ifdef HAVE_PRIORITY_SCHEDULING
2223 struct thread_entry *current;
2224 struct blocker *bl = thread->blocker;
2226 if (bl == NULL)
2228 /* No inheritance - just boost the thread by aging */
2229 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
2230 thread->skip_count = thread->priority;
2231 current = cores[CURRENT_CORE].running;
2233 else
2235 /* Call the specified unblocking PIP */
2236 current = bl->wakeup_protocol(thread);
2239 if (current != NULL &&
2240 find_first_set_bit(cores[IF_COP_CORE(current->core)].rtr.mask)
2241 < current->priority)
2243 /* There is a thread ready to run of higher or same priority on
2244 * the same core as the current one; recommend a task switch.
2245 * Knowing if this is an interrupt call would be helpful here. */
2246 result |= THREAD_SWITCH;
2248 #endif /* HAVE_PRIORITY_SCHEDULING */
2250 core_schedule_wakeup(thread);
2251 break;
2253 /* Nothing to do. State is not blocked. */
2254 #if THREAD_EXTRA_CHECKS
2255 default:
2256 THREAD_PANICF("wakeup_thread->block invalid", thread);
2257 case STATE_RUNNING:
2258 case STATE_KILLED:
2259 break;
2260 #endif
2263 UNLOCK_THREAD(thread);
2264 return result;
2267 /*---------------------------------------------------------------------------
2268 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2269 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2270 * the queue must be locked first.
2272 * INTERNAL: Intended for use by kernel objects and not for programs.
2273 *---------------------------------------------------------------------------
2275 unsigned int thread_queue_wake(struct thread_entry **list)
2277 unsigned result = THREAD_NONE;
2279 for (;;)
2281 unsigned int rc = wakeup_thread(list);
2283 if (rc == THREAD_NONE)
2284 break; /* No more threads */
2286 result |= rc;
2289 return result;
2292 /*---------------------------------------------------------------------------
2293 * Assign the thread slot a new ID. Version is 1-255.
2294 *---------------------------------------------------------------------------
2296 static void new_thread_id(unsigned int slot_num,
2297 struct thread_entry *thread)
2299 unsigned int version =
2300 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
2301 & THREAD_ID_VERSION_MASK;
2303 /* If wrapped to 0, make it 1 */
2304 if (version == 0)
2305 version = 1u << THREAD_ID_VERSION_SHIFT;
2307 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
2310 /*---------------------------------------------------------------------------
2311 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2312 * will be locked on multicore.
2313 *---------------------------------------------------------------------------
2315 static struct thread_entry * find_empty_thread_slot(void)
2317 /* Any slot could be on an interrupt-accessible list */
2318 IF_COP( int oldlevel = disable_irq_save(); )
2319 struct thread_entry *thread = NULL;
2320 int n;
2322 for (n = 0; n < MAXTHREADS; n++)
2324 /* Obtain current slot state - lock it on multicore */
2325 struct thread_entry *t = &threads[n];
2326 LOCK_THREAD(t);
2328 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
2330 /* Slot is empty - leave it locked and caller will unlock */
2331 thread = t;
2332 break;
2335 /* Finished examining slot - no longer busy - unlock on multicore */
2336 UNLOCK_THREAD(t);
2339 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
2340 not accesible to them yet */
2341 return thread;
2344 /*---------------------------------------------------------------------------
2345 * Return the thread_entry pointer for a thread_id. Return the current
2346 * thread if the ID is 0 (alias for current).
2347 *---------------------------------------------------------------------------
2349 struct thread_entry * thread_id_entry(unsigned int thread_id)
2351 return (thread_id == THREAD_ID_CURRENT) ?
2352 cores[CURRENT_CORE].running :
2353 &threads[thread_id & THREAD_ID_SLOT_MASK];
2356 /*---------------------------------------------------------------------------
2357 * Place the current core in idle mode - woken up on interrupt or wake
2358 * request from another core.
2359 *---------------------------------------------------------------------------
2361 void core_idle(void)
2363 IF_COP( const unsigned int core = CURRENT_CORE; )
2364 disable_irq();
2365 core_sleep(IF_COP(core));
2368 /*---------------------------------------------------------------------------
2369 * Create a thread. If using a dual core architecture, specify which core to
2370 * start the thread on.
2372 * Return ID if context area could be allocated, else NULL.
2373 *---------------------------------------------------------------------------
2375 unsigned int create_thread(void (*function)(void),
2376 void* stack, size_t stack_size,
2377 unsigned flags, const char *name
2378 IF_PRIO(, int priority)
2379 IF_COP(, unsigned int core))
2381 unsigned int i;
2382 unsigned int stack_words;
2383 uintptr_t stackptr, stackend;
2384 struct thread_entry *thread;
2385 unsigned state;
2386 int oldlevel;
2388 thread = find_empty_thread_slot();
2389 if (thread == NULL)
2391 return 0;
2394 oldlevel = disable_irq_save();
2396 /* Munge the stack to make it easy to spot stack overflows */
2397 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
2398 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
2399 stack_size = stackend - stackptr;
2400 stack_words = stack_size / sizeof (uintptr_t);
2402 for (i = 0; i < stack_words; i++)
2404 ((uintptr_t *)stackptr)[i] = DEADBEEF;
2407 /* Store interesting information */
2408 thread->name = name;
2409 thread->stack = (uintptr_t *)stackptr;
2410 thread->stack_size = stack_size;
2411 thread->queue = NULL;
2412 #ifdef HAVE_WAKEUP_EXT_CB
2413 thread->wakeup_ext_cb = NULL;
2414 #endif
2415 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2416 thread->cpu_boost = 0;
2417 #endif
2418 #ifdef HAVE_PRIORITY_SCHEDULING
2419 memset(&thread->pdist, 0, sizeof(thread->pdist));
2420 thread->blocker = NULL;
2421 thread->base_priority = priority;
2422 thread->priority = priority;
2423 thread->skip_count = priority;
2424 prio_add_entry(&thread->pdist, priority);
2425 #endif
2427 #ifdef HAVE_IO_PRIORITY
2428 /* Default to high (foreground) priority */
2429 thread->io_priority = IO_PRIORITY_IMMEDIATE;
2430 #endif
2432 #if NUM_CORES > 1
2433 thread->core = core;
2435 /* Writeback stack munging or anything else before starting */
2436 if (core != CURRENT_CORE)
2438 cpucache_flush();
2440 #endif
2442 /* Thread is not on any timeout list but be a bit paranoid */
2443 thread->tmo.prev = NULL;
2445 state = (flags & CREATE_THREAD_FROZEN) ?
2446 STATE_FROZEN : STATE_RUNNING;
2448 thread->context.sp = (typeof (thread->context.sp))stackend;
2450 /* Load the thread's context structure with needed startup information */
2451 THREAD_STARTUP_INIT(core, thread, function);
2453 thread->state = state;
2454 i = thread->id; /* Snapshot while locked */
2456 if (state == STATE_RUNNING)
2457 core_schedule_wakeup(thread);
2459 UNLOCK_THREAD(thread);
2460 restore_irq(oldlevel);
2462 return i;
2465 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2466 /*---------------------------------------------------------------------------
2467 * Change the boost state of a thread boosting or unboosting the CPU
2468 * as required.
2469 *---------------------------------------------------------------------------
2471 static inline void boost_thread(struct thread_entry *thread, bool boost)
2473 if ((thread->cpu_boost != 0) != boost)
2475 thread->cpu_boost = boost;
2476 cpu_boost(boost);
2480 void trigger_cpu_boost(void)
2482 struct thread_entry *current = cores[CURRENT_CORE].running;
2483 boost_thread(current, true);
2486 void cancel_cpu_boost(void)
2488 struct thread_entry *current = cores[CURRENT_CORE].running;
2489 boost_thread(current, false);
2491 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2493 /*---------------------------------------------------------------------------
2494 * Block the current thread until another thread terminates. A thread may
2495 * wait on itself to terminate which prevents it from running again and it
2496 * will need to be killed externally.
2497 * Parameter is the ID as returned from create_thread().
2498 *---------------------------------------------------------------------------
2500 void thread_wait(unsigned int thread_id)
2502 struct thread_entry *current = cores[CURRENT_CORE].running;
2503 struct thread_entry *thread = thread_id_entry(thread_id);
2505 /* Lock thread-as-waitable-object lock */
2506 corelock_lock(&thread->waiter_cl);
2508 /* Be sure it hasn't been killed yet */
2509 if (thread_id == THREAD_ID_CURRENT ||
2510 (thread->id == thread_id && thread->state != STATE_KILLED))
2512 IF_COP( current->obj_cl = &thread->waiter_cl; )
2513 current->bqp = &thread->queue;
2515 disable_irq();
2516 block_thread(current);
2518 corelock_unlock(&thread->waiter_cl);
2520 switch_thread();
2521 return;
2524 corelock_unlock(&thread->waiter_cl);
2527 /*---------------------------------------------------------------------------
2528 * Exit the current thread. The Right Way to Do Things (TM).
2529 *---------------------------------------------------------------------------
2531 void thread_exit(void)
2533 const unsigned int core = CURRENT_CORE;
2534 struct thread_entry *current = cores[core].running;
2536 /* Cancel CPU boost if any */
2537 cancel_cpu_boost();
2539 disable_irq();
2541 corelock_lock(&current->waiter_cl);
2542 LOCK_THREAD(current);
2544 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2545 if (current->name == THREAD_DESTRUCT)
2547 /* Thread being killed - become a waiter */
2548 unsigned int id = current->id;
2549 UNLOCK_THREAD(current);
2550 corelock_unlock(&current->waiter_cl);
2551 thread_wait(id);
2552 THREAD_PANICF("thread_exit->WK:*R", current);
2554 #endif
2556 #ifdef HAVE_PRIORITY_SCHEDULING
2557 check_for_obj_waiters("thread_exit", current);
2558 #endif
2560 if (current->tmo.prev != NULL)
2562 /* Cancel pending timeout list removal */
2563 remove_from_list_tmo(current);
2566 /* Switch tasks and never return */
2567 block_thread_on_l(current, STATE_KILLED);
2569 #if NUM_CORES > 1
2570 /* Switch to the idle stack if not on the main core (where "main"
2571 * runs) - we can hope gcc doesn't need the old stack beyond this
2572 * point. */
2573 if (core != CPU)
2575 switch_to_idle_stack(core);
2578 cpucache_flush();
2580 /* At this point, this thread isn't using resources allocated for
2581 * execution except the slot itself. */
2582 #endif
2584 /* Update ID for this slot */
2585 new_thread_id(current->id, current);
2586 current->name = NULL;
2588 /* Signal this thread */
2589 thread_queue_wake(&current->queue);
2590 corelock_unlock(&current->waiter_cl);
2591 /* Slot must be unusable until thread is really gone */
2592 UNLOCK_THREAD_AT_TASK_SWITCH(current);
2593 switch_thread();
2594 /* This should never and must never be reached - if it is, the
2595 * state is corrupted */
2596 THREAD_PANICF("thread_exit->K:*R", current);
2599 #ifdef ALLOW_REMOVE_THREAD
2600 /*---------------------------------------------------------------------------
2601 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2602 * normal programs.
2604 * Parameter is the ID as returned from create_thread().
2606 * Use with care on threads that are not under careful control as this may
2607 * leave various objects in an undefined state.
2608 *---------------------------------------------------------------------------
2610 void remove_thread(unsigned int thread_id)
2612 #if NUM_CORES > 1
2613 /* core is not constant here because of core switching */
2614 unsigned int core = CURRENT_CORE;
2615 unsigned int old_core = NUM_CORES;
2616 struct corelock *ocl = NULL;
2617 #else
2618 const unsigned int core = CURRENT_CORE;
2619 #endif
2620 struct thread_entry *current = cores[core].running;
2621 struct thread_entry *thread = thread_id_entry(thread_id);
2623 unsigned state;
2624 int oldlevel;
2626 if (thread == current)
2627 thread_exit(); /* Current thread - do normal exit */
2629 oldlevel = disable_irq_save();
2631 corelock_lock(&thread->waiter_cl);
2632 LOCK_THREAD(thread);
2634 state = thread->state;
2636 if (thread->id != thread_id || state == STATE_KILLED)
2637 goto thread_killed;
2639 #if NUM_CORES > 1
2640 if (thread->name == THREAD_DESTRUCT)
2642 /* Thread being killed - become a waiter */
2643 UNLOCK_THREAD(thread);
2644 corelock_unlock(&thread->waiter_cl);
2645 restore_irq(oldlevel);
2646 thread_wait(thread_id);
2647 return;
2650 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
2652 #ifdef HAVE_PRIORITY_SCHEDULING
2653 check_for_obj_waiters("remove_thread", thread);
2654 #endif
2656 if (thread->core != core)
2658 /* Switch cores and safely extract the thread there */
2659 /* Slot HAS to be unlocked or a deadlock could occur which means other
2660 * threads have to be guided into becoming thread waiters if they
2661 * attempt to remove it. */
2662 unsigned int new_core = thread->core;
2664 corelock_unlock(&thread->waiter_cl);
2666 UNLOCK_THREAD(thread);
2667 restore_irq(oldlevel);
2669 old_core = switch_core(new_core);
2671 oldlevel = disable_irq_save();
2673 corelock_lock(&thread->waiter_cl);
2674 LOCK_THREAD(thread);
2676 state = thread->state;
2677 core = new_core;
2678 /* Perform the extraction and switch ourselves back to the original
2679 processor */
2681 #endif /* NUM_CORES > 1 */
2683 if (thread->tmo.prev != NULL)
2685 /* Clean thread off the timeout list if a timeout check hasn't
2686 * run yet */
2687 remove_from_list_tmo(thread);
2690 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2691 /* Cancel CPU boost if any */
2692 boost_thread(thread, false);
2693 #endif
2695 IF_COP( retry_state: )
2697 switch (state)
2699 case STATE_RUNNING:
2700 RTR_LOCK(core);
2701 /* Remove thread from ready to run tasks */
2702 remove_from_list_l(&cores[core].running, thread);
2703 rtr_subtract_entry(core, thread->priority);
2704 RTR_UNLOCK(core);
2705 break;
2706 case STATE_BLOCKED:
2707 case STATE_BLOCKED_W_TMO:
2708 /* Remove thread from the queue it's blocked on - including its
2709 * own if waiting there */
2710 #if NUM_CORES > 1
2711 if (&thread->waiter_cl != thread->obj_cl)
2713 ocl = thread->obj_cl;
2715 if (UNLIKELY(corelock_try_lock(ocl) == 0))
2717 UNLOCK_THREAD(thread);
2718 corelock_lock(ocl);
2719 LOCK_THREAD(thread);
2721 if (UNLIKELY(thread->state != state))
2723 /* Something woke the thread */
2724 state = thread->state;
2725 corelock_unlock(ocl);
2726 goto retry_state;
2730 #endif
2731 remove_from_list_l(thread->bqp, thread);
2733 #ifdef HAVE_WAKEUP_EXT_CB
2734 if (thread->wakeup_ext_cb != NULL)
2735 thread->wakeup_ext_cb(thread);
2736 #endif
2738 #ifdef HAVE_PRIORITY_SCHEDULING
2739 if (thread->blocker != NULL)
2741 /* Remove thread's priority influence from its chain */
2742 wakeup_priority_protocol_release(thread);
2744 #endif
2746 #if NUM_CORES > 1
2747 if (ocl != NULL)
2748 corelock_unlock(ocl);
2749 #endif
2750 break;
2751 /* Otherwise thread is frozen and hasn't run yet */
2754 new_thread_id(thread_id, thread);
2755 thread->state = STATE_KILLED;
2757 /* If thread was waiting on itself, it will have been removed above.
2758 * The wrong order would result in waking the thread first and deadlocking
2759 * since the slot is already locked. */
2760 thread_queue_wake(&thread->queue);
2762 thread->name = NULL;
2764 thread_killed: /* Thread was already killed */
2765 /* Removal complete - safe to unlock and reenable interrupts */
2766 corelock_unlock(&thread->waiter_cl);
2767 UNLOCK_THREAD(thread);
2768 restore_irq(oldlevel);
2770 #if NUM_CORES > 1
2771 if (old_core < NUM_CORES)
2773 /* Did a removal on another processor's thread - switch back to
2774 native core */
2775 switch_core(old_core);
2777 #endif
2779 #endif /* ALLOW_REMOVE_THREAD */
2781 #ifdef HAVE_PRIORITY_SCHEDULING
2782 /*---------------------------------------------------------------------------
2783 * Sets the thread's relative base priority for the core it runs on. Any
2784 * needed inheritance changes also may happen.
2785 *---------------------------------------------------------------------------
2787 int thread_set_priority(unsigned int thread_id, int priority)
2789 int old_base_priority = -1;
2790 struct thread_entry *thread = thread_id_entry(thread_id);
2792 /* A little safety measure */
2793 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
2794 return -1;
2796 /* Thread could be on any list and therefore on an interrupt accessible
2797 one - disable interrupts */
2798 int oldlevel = disable_irq_save();
2800 LOCK_THREAD(thread);
2802 /* Make sure it's not killed */
2803 if (thread_id == THREAD_ID_CURRENT ||
2804 (thread->id == thread_id && thread->state != STATE_KILLED))
2806 int old_priority = thread->priority;
2808 old_base_priority = thread->base_priority;
2809 thread->base_priority = priority;
2811 prio_move_entry(&thread->pdist, old_base_priority, priority);
2812 priority = find_first_set_bit(thread->pdist.mask);
2814 if (old_priority == priority)
2816 /* No priority change - do nothing */
2818 else if (thread->state == STATE_RUNNING)
2820 /* This thread is running - change location on the run
2821 * queue. No transitive inheritance needed. */
2822 set_running_thread_priority(thread, priority);
2824 else
2826 thread->priority = priority;
2828 if (thread->blocker != NULL)
2830 /* Bubble new priority down the chain */
2831 struct blocker *bl = thread->blocker; /* Blocker struct */
2832 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
2833 struct thread_entry * const tstart = thread; /* Initial thread */
2834 const int highest = MIN(priority, old_priority); /* Higher of new or old */
2836 for (;;)
2838 struct thread_entry *next; /* Next thread to check */
2839 int bl_pr; /* Highest blocked thread */
2840 int queue_pr; /* New highest blocked thread */
2841 #if NUM_CORES > 1
2842 /* Owner can change but thread cannot be dislodged - thread
2843 * may not be the first in the queue which allows other
2844 * threads ahead in the list to be given ownership during the
2845 * operation. If thread is next then the waker will have to
2846 * wait for us and the owner of the object will remain fixed.
2847 * If we successfully grab the owner -- which at some point
2848 * is guaranteed -- then the queue remains fixed until we
2849 * pass by. */
2850 for (;;)
2852 LOCK_THREAD(bl_t);
2854 /* Double-check the owner - retry if it changed */
2855 if (LIKELY(bl->thread == bl_t))
2856 break;
2858 UNLOCK_THREAD(bl_t);
2859 bl_t = bl->thread;
2861 #endif
2862 bl_pr = bl->priority;
2864 if (highest > bl_pr)
2865 break; /* Object priority won't change */
2867 /* This will include the thread being set */
2868 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2870 if (queue_pr == bl_pr)
2871 break; /* Object priority not changing */
2873 /* Update thread boost for this object */
2874 bl->priority = queue_pr;
2875 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2876 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2878 if (bl_t->priority == bl_pr)
2879 break; /* Blocking thread priority not changing */
2881 if (bl_t->state == STATE_RUNNING)
2883 /* Thread not blocked - we're done */
2884 set_running_thread_priority(bl_t, bl_pr);
2885 break;
2888 bl_t->priority = bl_pr;
2889 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2891 if (bl == NULL)
2892 break; /* End of chain */
2894 next = bl->thread;
2896 if (UNLIKELY(next == tstart))
2897 break; /* Full-circle */
2899 UNLOCK_THREAD(thread);
2901 thread = bl_t;
2902 bl_t = next;
2903 } /* for (;;) */
2905 UNLOCK_THREAD(bl_t);
2910 UNLOCK_THREAD(thread);
2912 restore_irq(oldlevel);
2914 return old_base_priority;
2917 /*---------------------------------------------------------------------------
2918 * Returns the current base priority for a thread.
2919 *---------------------------------------------------------------------------
2921 int thread_get_priority(unsigned int thread_id)
2923 struct thread_entry *thread = thread_id_entry(thread_id);
2924 int base_priority = thread->base_priority;
2926 /* Simply check without locking slot. It may or may not be valid by the
2927 * time the function returns anyway. If all tests pass, it is the
2928 * correct value for when it was valid. */
2929 if (thread_id != THREAD_ID_CURRENT &&
2930 (thread->id != thread_id || thread->state == STATE_KILLED))
2931 base_priority = -1;
2933 return base_priority;
2935 #endif /* HAVE_PRIORITY_SCHEDULING */
2937 #ifdef HAVE_IO_PRIORITY
2938 int thread_get_io_priority(unsigned int thread_id)
2940 struct thread_entry *thread = thread_id_entry(thread_id);
2941 return thread->io_priority;
2944 void thread_set_io_priority(unsigned int thread_id,int io_priority)
2946 struct thread_entry *thread = thread_id_entry(thread_id);
2947 thread->io_priority = io_priority;
2949 #endif
2951 /*---------------------------------------------------------------------------
2952 * Starts a frozen thread - similar semantics to wakeup_thread except that
2953 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2954 * virtue of the slot having a state of STATE_FROZEN.
2955 *---------------------------------------------------------------------------
2957 void thread_thaw(unsigned int thread_id)
2959 struct thread_entry *thread = thread_id_entry(thread_id);
2960 int oldlevel = disable_irq_save();
2962 LOCK_THREAD(thread);
2964 /* If thread is the current one, it cannot be frozen, therefore
2965 * there is no need to check that. */
2966 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2967 core_schedule_wakeup(thread);
2969 UNLOCK_THREAD(thread);
2970 restore_irq(oldlevel);
2973 /*---------------------------------------------------------------------------
2974 * Return the ID of the currently executing thread.
2975 *---------------------------------------------------------------------------
2977 unsigned int thread_get_current(void)
2979 return cores[CURRENT_CORE].running->id;
2982 #if NUM_CORES > 1
2983 /*---------------------------------------------------------------------------
2984 * Switch the processor that the currently executing thread runs on.
2985 *---------------------------------------------------------------------------
2987 unsigned int switch_core(unsigned int new_core)
2989 const unsigned int core = CURRENT_CORE;
2990 struct thread_entry *current = cores[core].running;
2992 if (core == new_core)
2994 /* No change - just return same core */
2995 return core;
2998 int oldlevel = disable_irq_save();
2999 LOCK_THREAD(current);
3001 if (current->name == THREAD_DESTRUCT)
3003 /* Thread being killed - deactivate and let process complete */
3004 unsigned int id = current->id;
3005 UNLOCK_THREAD(current);
3006 restore_irq(oldlevel);
3007 thread_wait(id);
3008 /* Should never be reached */
3009 THREAD_PANICF("switch_core->D:*R", current);
3012 /* Get us off the running list for the current core */
3013 RTR_LOCK(core);
3014 remove_from_list_l(&cores[core].running, current);
3015 rtr_subtract_entry(core, current->priority);
3016 RTR_UNLOCK(core);
3018 /* Stash return value (old core) in a safe place */
3019 current->retval = core;
3021 /* If a timeout hadn't yet been cleaned-up it must be removed now or
3022 * the other core will likely attempt a removal from the wrong list! */
3023 if (current->tmo.prev != NULL)
3025 remove_from_list_tmo(current);
3028 /* Change the core number for this thread slot */
3029 current->core = new_core;
3031 /* Do not use core_schedule_wakeup here since this will result in
3032 * the thread starting to run on the other core before being finished on
3033 * this one. Delay the list unlock to keep the other core stuck
3034 * until this thread is ready. */
3035 RTR_LOCK(new_core);
3037 rtr_add_entry(new_core, current->priority);
3038 add_to_list_l(&cores[new_core].running, current);
3040 /* Make a callback into device-specific code, unlock the wakeup list so
3041 * that execution may resume on the new core, unlock our slot and finally
3042 * restore the interrupt level */
3043 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
3044 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
3045 cores[core].block_task = current;
3047 UNLOCK_THREAD(current);
3049 /* Alert other core to activity */
3050 core_wake(new_core);
3052 /* Do the stack switching, cache_maintenence and switch_thread call -
3053 requires native code */
3054 switch_thread_core(core, current);
3056 /* Finally return the old core to caller */
3057 return current->retval;
3059 #endif /* NUM_CORES > 1 */
3061 /*---------------------------------------------------------------------------
3062 * Initialize threading API. This assumes interrupts are not yet enabled. On
3063 * multicore setups, no core is allowed to proceed until create_thread calls
3064 * are safe to perform.
3065 *---------------------------------------------------------------------------
3067 void init_threads(void)
3069 const unsigned int core = CURRENT_CORE;
3070 struct thread_entry *thread;
3072 if (core == CPU)
3074 /* Initialize core locks and IDs in all slots */
3075 int n;
3076 for (n = 0; n < MAXTHREADS; n++)
3078 thread = &threads[n];
3079 corelock_init(&thread->waiter_cl);
3080 corelock_init(&thread->slot_cl);
3081 thread->id = THREAD_ID_INIT(n);
3085 /* CPU will initialize first and then sleep */
3086 thread = find_empty_thread_slot();
3088 if (thread == NULL)
3090 /* WTF? There really must be a slot available at this stage.
3091 * This can fail if, for example, .bss isn't zero'ed out by the loader
3092 * or threads is in the wrong section. */
3093 THREAD_PANICF("init_threads->no slot", NULL);
3096 /* Initialize initially non-zero members of core */
3097 cores[core].next_tmo_check = current_tick; /* Something not in the past */
3099 /* Initialize initially non-zero members of slot */
3100 UNLOCK_THREAD(thread); /* No sync worries yet */
3101 thread->name = main_thread_name;
3102 thread->state = STATE_RUNNING;
3103 IF_COP( thread->core = core; )
3104 #ifdef HAVE_PRIORITY_SCHEDULING
3105 corelock_init(&cores[core].rtr_cl);
3106 thread->base_priority = PRIORITY_USER_INTERFACE;
3107 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
3108 thread->priority = PRIORITY_USER_INTERFACE;
3109 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
3110 #endif
3112 add_to_list_l(&cores[core].running, thread);
3114 if (core == CPU)
3116 thread->stack = stackbegin;
3117 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
3118 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3119 /* Wait for other processors to finish their inits since create_thread
3120 * isn't safe to call until the kernel inits are done. The first
3121 * threads created in the system must of course be created by CPU.
3122 * Another possible approach is to initialize all cores and slots
3123 * for each core by CPU, let the remainder proceed in parallel and
3124 * signal CPU when all are finished. */
3125 core_thread_init(CPU);
3127 else
3129 /* Initial stack is the idle stack */
3130 thread->stack = idle_stacks[core];
3131 thread->stack_size = IDLE_STACK_SIZE;
3132 /* After last processor completes, it should signal all others to
3133 * proceed or may signal the next and call thread_exit(). The last one
3134 * to finish will signal CPU. */
3135 core_thread_init(core);
3136 /* Other cores do not have a main thread - go idle inside switch_thread
3137 * until a thread can run on the core. */
3138 thread_exit();
3139 #endif /* NUM_CORES */
3143 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3144 #if NUM_CORES == 1
3145 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
3146 #else
3147 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
3148 #endif
3150 unsigned int stack_words = stack_size / sizeof (uintptr_t);
3151 unsigned int i;
3152 int usage = 0;
3154 for (i = 0; i < stack_words; i++)
3156 if (stackptr[i] != DEADBEEF)
3158 usage = ((stack_words - i) * 100) / stack_words;
3159 break;
3163 return usage;
3166 /*---------------------------------------------------------------------------
3167 * Returns the maximum percentage of stack a thread ever used while running.
3168 * NOTE: Some large buffer allocations that don't use enough the buffer to
3169 * overwrite stackptr[0] will not be seen.
3170 *---------------------------------------------------------------------------
3172 int thread_stack_usage(const struct thread_entry *thread)
3174 return stack_usage(thread->stack, thread->stack_size);
3177 #if NUM_CORES > 1
3178 /*---------------------------------------------------------------------------
3179 * Returns the maximum percentage of the core's idle stack ever used during
3180 * runtime.
3181 *---------------------------------------------------------------------------
3183 int idle_stack_usage(unsigned int core)
3185 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
3187 #endif
3189 /*---------------------------------------------------------------------------
3190 * Fills in the buffer with the specified thread's name. If the name is NULL,
3191 * empty, or the thread is in destruct state a formatted ID is written
3192 * instead.
3193 *---------------------------------------------------------------------------
3195 void thread_get_name(char *buffer, int size,
3196 struct thread_entry *thread)
3198 if (size <= 0)
3199 return;
3201 *buffer = '\0';
3203 if (thread)
3205 /* Display thread name if one or ID if none */
3206 const char *name = thread->name;
3207 const char *fmt = "%s";
3208 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
3210 name = (const char *)thread;
3211 fmt = "%08lX";
3213 snprintf(buffer, size, fmt, name);