1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
33 /****************************************************************************
35 * See notes below on implementing processor-specific portions! *
36 ***************************************************************************/
38 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
40 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
42 #define THREAD_EXTRA_CHECKS 0
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
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
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.
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.
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
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
103 * 2) If processor requires, atomically reenable interrupts and perform step
105 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
106 * on Coldfire) goto step 5.
107 * 4) Enable interrupts.
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
121 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
122 struct core_entry cores
[NUM_CORES
] IBSS_ATTR
;
123 struct thread_entry threads
[MAXTHREADS
] IBSS_ATTR
;
125 static const char main_thread_name
[] = "main";
126 extern uintptr_t stackbegin
[];
127 extern uintptr_t stackend
[];
129 static inline void core_sleep(IF_COP_VOID(unsigned int core
))
130 __attribute__((always_inline
));
132 void check_tmo_threads(void)
133 __attribute__((noinline
));
135 static inline void block_thread_on_l(struct thread_entry
*thread
, unsigned state
)
136 __attribute__((always_inline
));
138 static void add_to_list_tmo(struct thread_entry
*thread
)
139 __attribute__((noinline
));
141 static void core_schedule_wakeup(struct thread_entry
*thread
)
142 __attribute__((noinline
));
145 static inline void run_blocking_ops(
146 unsigned int core
, struct thread_entry
*thread
)
147 __attribute__((always_inline
));
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__
170 #define IF_NO_SKIP_YIELD(...)
174 /*---------------------------------------------------------------------------
175 * Start the thread running and terminate it if it returns
176 *---------------------------------------------------------------------------
178 static void __attribute__((naked
,used
)) start_thread(void)
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"
187 "ldr r0, =invalidate_icache \n" /* Invalidate this core's cache. */
188 "mov lr, pc \n" /* This could be the first entry into */
189 "bx r0 \n" /* plugin or codec code for this core. */
191 "mov lr, pc \n" /* Call thread function */
193 ); /* No clobber list - new thread doesn't care */
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
)
213 "stmia %0, { r4-r11, sp, lr } \n"
218 /*---------------------------------------------------------------------------
219 * Load non-volatile context.
220 *---------------------------------------------------------------------------
222 static inline void load_context(const void* addr
)
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! */
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) */
283 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
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 */
289 "ldrb r3, [r0, r2, lsr #7] \n" /* cl->myl[othercore] == 0 ? */
290 "cmp r3, #0 \n" /* yes? lock acquired */
292 "ldrb r3, [r0, #2] \n" /* || cl->turn == core ? */
294 "bxeq lr \n" /* yes? lock acquired */
295 "b 1b \n" /* keep trying */
296 : : "i"(&PROCESSOR_ID
)
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) */
310 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
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 */
319 "ldrb r0, [r3, #2] \n" /* || cl->turn == core? */
321 "streqb r0, [r3, r1, lsr #7] \n" /* if not, cl->myl[core] = 0 */
322 "bx lr \n" /* return result */
323 : : "i"(&PROCESSOR_ID
)
330 /*---------------------------------------------------------------------------
331 * Release ownership of the corelock
332 *---------------------------------------------------------------------------
334 void corelock_unlock(struct corelock
*cl
) __attribute__((naked
));
335 void corelock_unlock(struct corelock
*cl
)
338 "mov r1, %0 \n" /* r1 = PROCESSOR_ID */
340 "mov r2, #0 \n" /* cl->myl[core] = 0 */
341 "strb r2, [r0, r1, lsr #7] \n"
343 : : "i"(&PROCESSOR_ID
)
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
;
362 if (cl
->myl
[othercore
] == 0 || cl
->turn
== core
)
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
)
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 *---------------------------------------------------------------------------
407 static inline void core_sleep(void)
409 sleep_core(CURRENT_CORE
);
413 static inline void core_sleep(unsigned int core
)
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"
433 : [ctl
]"r"(&CPU_CTL
), [mbx
]"r"(MBX_BASE
), [c
]"r"(core
)
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)
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 */
454 #endif /* NUM_CORES */
455 #elif CONFIG_CPU == PP5002
457 static inline void core_sleep(void)
459 sleep_core(CURRENT_CORE
);
463 /* PP5002 has no mailboxes - emulate using bytes */
464 static inline void core_sleep(unsigned int core
)
468 "mov r0, #1 \n" /* Signal intent to sleep */
469 "strb r0, [%[sem], #2] \n"
470 "ldrb r0, [%[sem], #1] \n" /* && stay_awake == 0? */
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! */
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 */
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"
493 : [sem
]"r"(&core_semaphores
[core
]), [c
]"r"(core
),
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)
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);
515 #endif /* ASM/C selection */
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 *---------------------------------------------------------------------------
527 /* Shared single-core build debugging version */
530 /* No wakey - core already wakey */
532 #elif defined (CPU_PP502x)
533 void core_wake(unsigned int othercore
)
536 /* avoid r0 since that contains othercore */
538 "mrs r3, cpsr \n" /* Disable IRQ */
539 "orr r1, r3, #0x80 \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 */
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
),
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
)
586 /* avoid r0 since that contains othercore */
588 "mrs r3, cpsr \n" /* Disable IRQ */
589 "orr r1, r3, #0x80 \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"
595 "1: \n" /* If it intends to sleep, let it first */
596 "ldrb r1, [%[sem], #2] \n" /* intend_sleep != 0 ? */
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 */
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
]),
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 */
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
)
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]));
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 */
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
699 "stmfd sp!, { r4-r12, lr } \n" /* Stack all non-volatile context on current core */
700 "ldr r2, =idle_stacks \n" /* r2 = &idle_stacks[core][IDLE_STACK_WORDS] */
701 "ldr r2, [r2, r0, lsl #2] \n"
702 "add r2, r2, %0*4 \n"
703 "stmfd r2!, { sp } \n" /* save original stack pointer on idle stack */
704 "mov sp, r2 \n" /* switch stacks */
705 "adr r2, 1f \n" /* r2 = new core restart address */
706 "str r2, [r1, #40] \n" /* thread->context.start = r2 */
707 "ldr pc, =switch_thread \n" /* r0 = thread after call - see load_context */
709 "ldr sp, [r0, #32] \n" /* Reload original sp from context structure */
710 "mov r1, #0 \n" /* Clear start address */
711 "str r1, [r0, #40] \n"
712 "ldr r0, =invalidate_icache \n" /* Invalidate new core's cache */
715 "ldmfd sp!, { r4-r12, pc } \n" /* Restore non-volatile context to new core and return */
716 ".ltorg \n" /* Dump constant pool */
717 : : "i"(IDLE_STACK_WORDS
)
719 (void)core
; (void)thread
;
722 /*---------------------------------------------------------------------------
723 * Do any device-specific inits for the threads and synchronize the kernel
725 *---------------------------------------------------------------------------
727 static void core_thread_init(unsigned int core
)
731 /* Wake up coprocessor and let it initialize kernel and threads */
736 /* Sleep until COP has finished */
741 /* Wake the CPU and return */
745 #endif /* NUM_CORES */
747 #elif CONFIG_CPU == S3C2440
749 /*---------------------------------------------------------------------------
750 * Put core in a power-saving state if waking list wasn't repopulated.
751 *---------------------------------------------------------------------------
753 static inline void core_sleep(void)
755 /* FIQ also changes the CLKCON register so FIQ must be disabled
756 when changing it here */
759 "orr r2, r0, #0x40 \n" /* Disable FIQ */
760 "bic r0, r0, #0x80 \n" /* Prepare IRQ enable */
762 "mov r1, #0x4c000000 \n" /* CLKCON = 0x4c00000c */
763 "ldr r2, [r1, #0xc] \n" /* Set IDLE bit */
765 "str r2, [r1, #0xc] \n"
766 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
767 "mov r2, #0 \n" /* wait for IDLE */
772 "orr r2, r0, #0xc0 \n" /* Disable IRQ, FIQ */
774 "ldr r2, [r1, #0xc] \n" /* Reset IDLE bit */
776 "str r2, [r1, #0xc] \n"
777 "msr cpsr_c, r0 \n" /* Enable IRQ, restore FIQ */
778 : : : "r0", "r1", "r2");
780 #elif defined(CPU_TCC780X) || defined(CPU_TCC77X)
781 static inline void core_sleep(void)
783 /* Single core only for now. Use the generic ARMv5 wait for IRQ */
786 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
791 #elif CONFIG_CPU == IMX31L
792 static inline void core_sleep(void)
796 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
801 #elif CONFIG_CPU == DM320
802 static inline void core_sleep(void)
806 "mcr p15, 0, r0, c7, c0, 4 \n" /* Wait for interrupt */
812 static inline void core_sleep(void)
814 #warning core_sleep not implemented, battery life will be decreased
817 #endif /* CONFIG_CPU == */
819 #elif defined(CPU_COLDFIRE)
820 /*---------------------------------------------------------------------------
821 * Start the thread running and terminate it if it returns
822 *---------------------------------------------------------------------------
824 void start_thread(void); /* Provide C access to ASM label */
825 static void __attribute__((used
)) __start_thread(void)
827 /* a0=macsr, a1=context */
829 "start_thread: \n" /* Start here - no naked attribute */
830 "move.l %a0, %macsr \n" /* Set initial mac status reg */
831 "lea.l 48(%a1), %a1 \n"
832 "move.l (%a1)+, %sp \n" /* Set initial stack */
833 "move.l (%a1), %a2 \n" /* Fetch thread function pointer */
834 "clr.l (%a1) \n" /* Mark thread running */
835 "jsr (%a2) \n" /* Call thread function */
840 /* Set EMAC unit to fractional mode with saturation for each new thread,
841 * since that's what'll be the most useful for most things which the dsp
842 * will do. Codecs should still initialize their preferred modes
843 * explicitly. Context pointer is placed in d2 slot and start_thread
844 * pointer in d3 slot. thread function pointer is placed in context.start.
845 * See load_context for what happens when thread is initially going to
848 #define THREAD_STARTUP_INIT(core, thread, function) \
849 ({ (thread)->context.macsr = EMAC_FRACTIONAL | EMAC_SATURATE, \
850 (thread)->context.d[0] = (uint32_t)&(thread)->context, \
851 (thread)->context.d[1] = (uint32_t)start_thread, \
852 (thread)->context.start = (uint32_t)(function); })
854 /*---------------------------------------------------------------------------
855 * Store non-volatile context.
856 *---------------------------------------------------------------------------
858 static inline void store_context(void* addr
)
861 "move.l %%macsr,%%d0 \n"
862 "movem.l %%d0/%%d2-%%d7/%%a2-%%a7,(%0) \n"
863 : : "a" (addr
) : "d0" /* only! */
867 /*---------------------------------------------------------------------------
868 * Load non-volatile context.
869 *---------------------------------------------------------------------------
871 static inline void load_context(const void* addr
)
874 "move.l 52(%0), %%d0 \n" /* Get start address */
875 "beq.b 1f \n" /* NULL -> already running */
876 "movem.l (%0), %%a0-%%a2 \n" /* a0=macsr, a1=context, a2=start_thread */
877 "jmp (%%a2) \n" /* Start the thread */
879 "movem.l (%0), %%d0/%%d2-%%d7/%%a2-%%a7 \n" /* Load context */
880 "move.l %%d0, %%macsr \n"
881 : : "a" (addr
) : "d0" /* only! */
885 /*---------------------------------------------------------------------------
886 * Put core in a power-saving state if waking list wasn't repopulated.
887 *---------------------------------------------------------------------------
889 static inline void core_sleep(void)
891 /* Supervisor mode, interrupts enabled upon wakeup */
892 asm volatile ("stop #0x2000");
895 #elif CONFIG_CPU == SH7034
896 /*---------------------------------------------------------------------------
897 * Start the thread running and terminate it if it returns
898 *---------------------------------------------------------------------------
900 void start_thread(void); /* Provide C access to ASM label */
901 static void __attribute__((used
)) __start_thread(void)
905 "_start_thread: \n" /* Start here - no naked attribute */
906 "mov.l @(4, r8), r0 \n" /* Fetch thread function pointer */
907 "mov.l @(28, r8), r15 \n" /* Set initial sp */
908 "mov #0, r1 \n" /* Start the thread */
910 "mov.l r1, @(36, r8) \n" /* Clear start address */
915 /* Place context pointer in r8 slot, function pointer in r9 slot, and
916 * start_thread pointer in context_start */
917 #define THREAD_STARTUP_INIT(core, thread, function) \
918 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
919 (thread)->context.r[1] = (uint32_t)(function), \
920 (thread)->context.start = (uint32_t)start_thread; })
922 /*---------------------------------------------------------------------------
923 * Store non-volatile context.
924 *---------------------------------------------------------------------------
926 static inline void store_context(void* addr
)
929 "add #36, %0 \n" /* Start at last reg. By the time routine */
930 "sts.l pr, @-%0 \n" /* is done, %0 will have the original value */
943 /*---------------------------------------------------------------------------
944 * Load non-volatile context.
945 *---------------------------------------------------------------------------
947 static inline void load_context(const void* addr
)
950 "mov.l @(36, %0), r0 \n" /* Get start address */
952 "bt .running \n" /* NULL -> already running */
953 "jmp @r0 \n" /* r8 = context */
955 "mov.l @%0+, r8 \n" /* Executes in delay slot and outside it */
964 : : "r" (addr
) : "r0" /* only! */
968 /*---------------------------------------------------------------------------
969 * Put core in a power-saving state.
970 *---------------------------------------------------------------------------
972 static inline void core_sleep(void)
975 "and.b #0x7f, @(r0, gbr) \n" /* Clear SBY (bit 7) in SBYCR */
976 "mov #0, r1 \n" /* Enable interrupts */
977 "ldc r1, sr \n" /* Following instruction cannot be interrupted */
978 "sleep \n" /* Execute standby */
979 : : "z"(&SBYCR
-GBR
) : "r1");
984 /*---------------------------------------------------------------------------
985 * Start the thread running and terminate it if it returns
986 *---------------------------------------------------------------------------
989 void start_thread(void); /* Provide C access to ASM label */
990 static void __attribute__((used
)) _start_thread(void)
997 "lw $8, 4($9) \n" /* Fetch thread function pointer ($8 = $t0, $9 = $t1) */
998 "lw $29, 40($9) \n" /* Set initial sp(=$29) */
999 "sw $0, 48($9) \n" /* Clear start address */
1000 "jalr $8 \n" /* Start the thread */
1008 /* Place context pointer in $s0 slot, function pointer in $s1 slot, and
1009 * start_thread pointer in context_start */
1010 #define THREAD_STARTUP_INIT(core, thread, function) \
1011 ({ (thread)->context.r[0] = (uint32_t)&(thread)->context, \
1012 (thread)->context.r[1] = (uint32_t)(function), \
1013 (thread)->context.start = (uint32_t)start_thread; })
1015 /*---------------------------------------------------------------------------
1016 * Store non-volatile context.
1017 *---------------------------------------------------------------------------
1019 static inline void store_context(void* addr
)
1025 "sw $16, 0($8) \n" /* $s0 */
1026 "sw $17, 4($8) \n" /* $s1 */
1027 "sw $18, 8($8) \n" /* $s2 */
1028 "sw $19, 12($8) \n" /* $s3 */
1029 "sw $20, 16($8) \n" /* $s4 */
1030 "sw $21, 20($8) \n" /* $s5 */
1031 "sw $22, 24($8) \n" /* $s6 */
1032 "sw $23, 28($8) \n" /* $s7 */
1033 "sw $28, 32($8) \n" /* gp */
1034 "sw $30, 36($8) \n" /* fp */
1035 "sw $29, 40($8) \n" /* sp */
1036 "sw $31, 44($8) \n" /* ra */
1039 : : "r" (addr
) : "t0"
1043 /*---------------------------------------------------------------------------
1044 * Load non-volatile context.
1045 *---------------------------------------------------------------------------
1047 static inline void load_context(const void* addr
)
1052 "lw $8, 48(%0) \n" /* Get start address ($8 = $t0) */
1053 "beqz $8, running \n" /* NULL -> already running */
1055 "move $9, %0 \n" /* $t1 = context */
1060 "lw $16, 0($8) \n" /* $s0 */
1061 "lw $17, 4($8) \n" /* $s1 */
1062 "lw $18, 8($8) \n" /* $s2 */
1063 "lw $19, 12($8) \n" /* $s3 */
1064 "lw $20, 16($8) \n" /* $s4 */
1065 "lw $21, 20($8) \n" /* $s5 */
1066 "lw $22, 24($8) \n" /* $s6 */
1067 "lw $23, 28($8) \n" /* $s7 */
1068 "lw $28, 32($8) \n" /* gp */
1069 "lw $30, 36($8) \n" /* fp */
1070 "lw $29, 40($8) \n" /* sp */
1071 "lw $31, 44($8) \n" /* ra */
1074 : : "r" (addr
) : "t0" /* only! */
1078 /*---------------------------------------------------------------------------
1079 * Put core in a power-saving state.
1080 *---------------------------------------------------------------------------
1082 static inline void core_sleep(void)
1084 #if CONFIG_CPU == JZ4732
1087 asm volatile(".set mips32r2 \n"
1088 "mfc0 $8, $12 \n" /* mfc $t0, $12 */
1089 "move $9, $8 \n" /* move $t1, $t0 */
1090 "la $10, 0x8000000 \n" /* la $t2, 0x8000000 */
1091 "or $8, $8, $10 \n" /* Enable reduced power mode */
1096 ::: "t0", "t1", "t2"
1101 #endif /* CONFIG_CPU == */
1104 * End Processor-specific section
1105 ***************************************************************************/
1107 #if THREAD_EXTRA_CHECKS
1108 static void thread_panicf(const char *msg
, struct thread_entry
*thread
)
1110 IF_COP( const unsigned int core
= thread
->core
; )
1111 static char name
[32];
1112 thread_get_name(name
, 32, thread
);
1113 panicf ("%s %s" IF_COP(" (%d)"), msg
, name
IF_COP(, core
));
1115 static void thread_stkov(struct thread_entry
*thread
)
1117 thread_panicf("Stkov", thread
);
1119 #define THREAD_PANICF(msg, thread) \
1120 thread_panicf(msg, thread)
1121 #define THREAD_ASSERT(exp, msg, thread) \
1122 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
1124 static void thread_stkov(struct thread_entry
*thread
)
1126 IF_COP( const unsigned int core
= thread
->core
; )
1127 static char name
[32];
1128 thread_get_name(name
, 32, thread
);
1129 panicf("Stkov %s" IF_COP(" (%d)"), name
IF_COP(, core
));
1131 #define THREAD_PANICF(msg, thread)
1132 #define THREAD_ASSERT(exp, msg, thread)
1133 #endif /* THREAD_EXTRA_CHECKS */
1135 /* Thread locking */
1137 #define LOCK_THREAD(thread) \
1138 ({ corelock_lock(&(thread)->slot_cl); })
1139 #define TRY_LOCK_THREAD(thread) \
1140 ({ corelock_try_lock(&thread->slot_cl); })
1141 #define UNLOCK_THREAD(thread) \
1142 ({ corelock_unlock(&(thread)->slot_cl); })
1143 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1144 ({ unsigned int _core = (thread)->core; \
1145 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
1146 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
1148 #define LOCK_THREAD(thread) \
1150 #define TRY_LOCK_THREAD(thread) \
1152 #define UNLOCK_THREAD(thread) \
1154 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
1159 #define RTR_LOCK(core) \
1160 ({ corelock_lock(&cores[core].rtr_cl); })
1161 #define RTR_UNLOCK(core) \
1162 ({ corelock_unlock(&cores[core].rtr_cl); })
1164 #ifdef HAVE_PRIORITY_SCHEDULING
1165 #define rtr_add_entry(core, priority) \
1166 prio_add_entry(&cores[core].rtr, (priority))
1168 #define rtr_subtract_entry(core, priority) \
1169 prio_subtract_entry(&cores[core].rtr, (priority))
1171 #define rtr_move_entry(core, from, to) \
1172 prio_move_entry(&cores[core].rtr, (from), (to))
1174 #define rtr_add_entry(core, priority)
1175 #define rtr_add_entry_inl(core, priority)
1176 #define rtr_subtract_entry(core, priority)
1177 #define rtr_subtract_entry_inl(core, priotity)
1178 #define rtr_move_entry(core, from, to)
1179 #define rtr_move_entry_inl(core, from, to)
1182 /*---------------------------------------------------------------------------
1183 * Thread list structure - circular:
1184 * +------------------------------+
1186 * +--+---+<-+---+<-+---+<-+---+<-+
1187 * Head->| T | | T | | T | | T |
1188 * +->+---+->+---+->+---+->+---+--+
1190 * +------------------------------+
1191 *---------------------------------------------------------------------------
1194 /*---------------------------------------------------------------------------
1195 * Adds a thread to a list of threads using "insert last". Uses the "l"
1197 *---------------------------------------------------------------------------
1199 static void add_to_list_l(struct thread_entry
**list
,
1200 struct thread_entry
*thread
)
1202 struct thread_entry
*l
= *list
;
1206 /* Insert into unoccupied list */
1207 thread
->l
.prev
= thread
;
1208 thread
->l
.next
= thread
;
1214 thread
->l
.prev
= l
->l
.prev
;
1216 l
->l
.prev
->l
.next
= thread
;
1220 /*---------------------------------------------------------------------------
1221 * Removes a thread from a list of threads. Uses the "l" links.
1222 *---------------------------------------------------------------------------
1224 static void remove_from_list_l(struct thread_entry
**list
,
1225 struct thread_entry
*thread
)
1227 struct thread_entry
*prev
, *next
;
1229 next
= thread
->l
.next
;
1238 if (thread
== *list
)
1240 /* List becomes next item */
1244 prev
= thread
->l
.prev
;
1246 /* Fix links to jump over the removed entry. */
1247 next
->l
.prev
= prev
;
1248 prev
->l
.next
= next
;
1251 /*---------------------------------------------------------------------------
1252 * Timeout list structure - circular reverse (to make "remove item" O(1)),
1253 * NULL-terminated forward (to ease the far more common forward traversal):
1254 * +------------------------------+
1256 * +--+---+<-+---+<-+---+<-+---+<-+
1257 * Head->| T | | T | | T | | T |
1258 * +---+->+---+->+---+->+---+-X
1259 *---------------------------------------------------------------------------
1262 /*---------------------------------------------------------------------------
1263 * Add a thread from the core's timout list by linking the pointers in its
1265 *---------------------------------------------------------------------------
1267 static void add_to_list_tmo(struct thread_entry
*thread
)
1269 struct thread_entry
*tmo
= cores
[IF_COP_CORE(thread
->core
)].timeout
;
1270 THREAD_ASSERT(thread
->tmo
.prev
== NULL
,
1271 "add_to_list_tmo->already listed", thread
);
1273 thread
->tmo
.next
= NULL
;
1277 /* Insert into unoccupied list */
1278 thread
->tmo
.prev
= thread
;
1279 cores
[IF_COP_CORE(thread
->core
)].timeout
= thread
;
1284 thread
->tmo
.prev
= tmo
->tmo
.prev
;
1285 tmo
->tmo
.prev
->tmo
.next
= thread
;
1286 tmo
->tmo
.prev
= thread
;
1289 /*---------------------------------------------------------------------------
1290 * Remove a thread from the core's timout list by unlinking the pointers in
1291 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
1293 *---------------------------------------------------------------------------
1295 static void remove_from_list_tmo(struct thread_entry
*thread
)
1297 struct thread_entry
**list
= &cores
[IF_COP_CORE(thread
->core
)].timeout
;
1298 struct thread_entry
*prev
= thread
->tmo
.prev
;
1299 struct thread_entry
*next
= thread
->tmo
.next
;
1301 THREAD_ASSERT(prev
!= NULL
, "remove_from_list_tmo->not listed", thread
);
1304 next
->tmo
.prev
= prev
;
1306 if (thread
== *list
)
1308 /* List becomes next item and empty if next == NULL */
1310 /* Mark as unlisted */
1311 thread
->tmo
.prev
= NULL
;
1316 (*list
)->tmo
.prev
= prev
;
1317 prev
->tmo
.next
= next
;
1318 /* Mark as unlisted */
1319 thread
->tmo
.prev
= NULL
;
1324 #ifdef HAVE_PRIORITY_SCHEDULING
1325 /*---------------------------------------------------------------------------
1326 * Priority distribution structure (one category for each possible priority):
1328 * +----+----+----+ ... +-----+
1329 * hist: | F0 | F1 | F2 | | F31 |
1330 * +----+----+----+ ... +-----+
1331 * mask: | b0 | b1 | b2 | | b31 |
1332 * +----+----+----+ ... +-----+
1334 * F = count of threads at priority category n (frequency)
1335 * b = bitmask of non-zero priority categories (occupancy)
1337 * / if H[n] != 0 : 1
1341 *---------------------------------------------------------------------------
1342 * Basic priority inheritance priotocol (PIP):
1344 * Mn = mutex n, Tn = thread n
1346 * A lower priority thread inherits the priority of the highest priority
1347 * thread blocked waiting for it to complete an action (such as release a
1348 * mutex or respond to a message via queue_send):
1352 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
1353 * priority than T1 then T1 inherits the priority of T2.
1359 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
1360 * T1 inherits the higher of T2 and T3.
1362 * 3) T3->M2->T2->M1->T1
1364 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
1365 * then T1 inherits the priority of T3 through T2.
1367 * Blocking chains can grow arbitrarily complex (though it's best that they
1368 * not form at all very often :) and build-up from these units.
1369 *---------------------------------------------------------------------------
1372 /*---------------------------------------------------------------------------
1373 * Increment frequency at category "priority"
1374 *---------------------------------------------------------------------------
1376 static inline unsigned int prio_add_entry(
1377 struct priority_distribution
*pd
, int priority
)
1380 /* Enough size/instruction count difference for ARM makes it worth it to
1381 * use different code (192 bytes for ARM). Only thing better is ASM. */
1383 count
= pd
->hist
[priority
];
1385 pd
->mask
|= 1 << priority
;
1386 pd
->hist
[priority
] = count
;
1387 #else /* This one's better for Coldfire */
1388 if ((count
= ++pd
->hist
[priority
]) == 1)
1389 pd
->mask
|= 1 << priority
;
1395 /*---------------------------------------------------------------------------
1396 * Decrement frequency at category "priority"
1397 *---------------------------------------------------------------------------
1399 static inline unsigned int prio_subtract_entry(
1400 struct priority_distribution
*pd
, int priority
)
1405 count
= pd
->hist
[priority
];
1407 pd
->mask
&= ~(1 << priority
);
1408 pd
->hist
[priority
] = count
;
1410 if ((count
= --pd
->hist
[priority
]) == 0)
1411 pd
->mask
&= ~(1 << priority
);
1417 /*---------------------------------------------------------------------------
1418 * Remove from one category and add to another
1419 *---------------------------------------------------------------------------
1421 static inline void prio_move_entry(
1422 struct priority_distribution
*pd
, int from
, int to
)
1424 uint32_t mask
= pd
->mask
;
1429 count
= pd
->hist
[from
];
1431 mask
&= ~(1 << from
);
1432 pd
->hist
[from
] = count
;
1434 count
= pd
->hist
[to
];
1437 pd
->hist
[to
] = count
;
1439 if (--pd
->hist
[from
] == 0)
1440 mask
&= ~(1 << from
);
1442 if (++pd
->hist
[to
] == 1)
1449 /*---------------------------------------------------------------------------
1450 * Change the priority and rtr entry for a running thread
1451 *---------------------------------------------------------------------------
1453 static inline void set_running_thread_priority(
1454 struct thread_entry
*thread
, int priority
)
1456 const unsigned int core
= IF_COP_CORE(thread
->core
);
1458 rtr_move_entry(core
, thread
->priority
, priority
);
1459 thread
->priority
= priority
;
1463 /*---------------------------------------------------------------------------
1464 * Finds the highest priority thread in a list of threads. If the list is
1465 * empty, the PRIORITY_IDLE is returned.
1467 * It is possible to use the struct priority_distribution within an object
1468 * instead of scanning the remaining threads in the list but as a compromise,
1469 * the resulting per-object memory overhead is saved at a slight speed
1470 * penalty under high contention.
1471 *---------------------------------------------------------------------------
1473 static int find_highest_priority_in_list_l(
1474 struct thread_entry
* const thread
)
1478 /* Go though list until the ending up at the initial thread */
1479 int highest_priority
= thread
->priority
;
1480 struct thread_entry
*curr
= thread
;
1484 int priority
= curr
->priority
;
1486 if (priority
< highest_priority
)
1487 highest_priority
= priority
;
1489 curr
= curr
->l
.next
;
1491 while (curr
!= thread
);
1493 return highest_priority
;
1496 return PRIORITY_IDLE
;
1499 /*---------------------------------------------------------------------------
1500 * Register priority with blocking system and bubble it down the chain if
1501 * any until we reach the end or something is already equal or higher.
1503 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
1504 * targets but that same action also guarantees a circular block anyway and
1505 * those are prevented, right? :-)
1506 *---------------------------------------------------------------------------
1508 static struct thread_entry
*
1509 blocker_inherit_priority(struct thread_entry
*current
)
1511 const int priority
= current
->priority
;
1512 struct blocker
*bl
= current
->blocker
;
1513 struct thread_entry
* const tstart
= current
;
1514 struct thread_entry
*bl_t
= bl
->thread
;
1516 /* Blocker cannot change since the object protection is held */
1521 struct thread_entry
*next
;
1522 int bl_pr
= bl
->priority
;
1524 if (priority
>= bl_pr
)
1525 break; /* Object priority already high enough */
1527 bl
->priority
= priority
;
1530 prio_add_entry(&bl_t
->pdist
, priority
);
1532 if (bl_pr
< PRIORITY_IDLE
)
1534 /* Not first waiter - subtract old one */
1535 prio_subtract_entry(&bl_t
->pdist
, bl_pr
);
1538 if (priority
>= bl_t
->priority
)
1539 break; /* Thread priority high enough */
1541 if (bl_t
->state
== STATE_RUNNING
)
1543 /* Blocking thread is a running thread therefore there are no
1544 * further blockers. Change the "run queue" on which it
1546 set_running_thread_priority(bl_t
, priority
);
1550 bl_t
->priority
= priority
;
1552 /* If blocking thread has a blocker, apply transitive inheritance */
1556 break; /* End of chain or object doesn't support inheritance */
1561 break; /* Full-circle - deadlock! */
1563 UNLOCK_THREAD(current
);
1570 /* Blocker could change - retest condition */
1571 if (bl
->thread
== next
)
1574 UNLOCK_THREAD(next
);
1582 UNLOCK_THREAD(bl_t
);
1587 /*---------------------------------------------------------------------------
1588 * Readjust priorities when waking a thread blocked waiting for another
1589 * in essence "releasing" the thread's effect on the object owner. Can be
1590 * performed from any context.
1591 *---------------------------------------------------------------------------
1593 struct thread_entry
*
1594 wakeup_priority_protocol_release(struct thread_entry
*thread
)
1596 const int priority
= thread
->priority
;
1597 struct blocker
*bl
= thread
->blocker
;
1598 struct thread_entry
* const tstart
= thread
;
1599 struct thread_entry
*bl_t
= bl
->thread
;
1601 /* Blocker cannot change since object will be locked */
1604 thread
->blocker
= NULL
; /* Thread not blocked */
1608 struct thread_entry
*next
;
1609 int bl_pr
= bl
->priority
;
1611 if (priority
> bl_pr
)
1612 break; /* Object priority higher */
1614 next
= *thread
->bqp
;
1618 /* No more threads in queue */
1619 prio_subtract_entry(&bl_t
->pdist
, bl_pr
);
1620 bl
->priority
= PRIORITY_IDLE
;
1624 /* Check list for highest remaining priority */
1625 int queue_pr
= find_highest_priority_in_list_l(next
);
1627 if (queue_pr
== bl_pr
)
1628 break; /* Object priority not changing */
1630 /* Change queue priority */
1631 prio_move_entry(&bl_t
->pdist
, bl_pr
, queue_pr
);
1632 bl
->priority
= queue_pr
;
1635 if (bl_pr
> bl_t
->priority
)
1636 break; /* thread priority is higher */
1638 bl_pr
= find_first_set_bit(bl_t
->pdist
.mask
);
1640 if (bl_pr
== bl_t
->priority
)
1641 break; /* Thread priority not changing */
1643 if (bl_t
->state
== STATE_RUNNING
)
1645 /* No further blockers */
1646 set_running_thread_priority(bl_t
, bl_pr
);
1650 bl_t
->priority
= bl_pr
;
1652 /* If blocking thread has a blocker, apply transitive inheritance */
1656 break; /* End of chain or object doesn't support inheritance */
1661 break; /* Full-circle - deadlock! */
1663 UNLOCK_THREAD(thread
);
1670 /* Blocker could change - retest condition */
1671 if (bl
->thread
== next
)
1674 UNLOCK_THREAD(next
);
1682 UNLOCK_THREAD(bl_t
);
1685 if (thread
!= tstart
)
1687 /* Relock original if it changed */
1688 LOCK_THREAD(tstart
);
1692 return cores
[CURRENT_CORE
].running
;
1695 /*---------------------------------------------------------------------------
1696 * Transfer ownership to a thread waiting for an objects and transfer
1697 * inherited priority boost from other waiters. This algorithm knows that
1698 * blocking chains may only unblock from the very end.
1700 * Only the owning thread itself may call this and so the assumption that
1701 * it is the running thread is made.
1702 *---------------------------------------------------------------------------
1704 struct thread_entry
*
1705 wakeup_priority_protocol_transfer(struct thread_entry
*thread
)
1707 /* Waking thread inherits priority boost from object owner */
1708 struct blocker
*bl
= thread
->blocker
;
1709 struct thread_entry
*bl_t
= bl
->thread
;
1710 struct thread_entry
*next
;
1713 THREAD_ASSERT(thread_get_current() == bl_t
,
1714 "UPPT->wrong thread", thread_get_current());
1718 bl_pr
= bl
->priority
;
1720 /* Remove the object's boost from the owning thread */
1721 if (prio_subtract_entry(&bl_t
->pdist
, bl_pr
) == 0 &&
1722 bl_pr
<= bl_t
->priority
)
1724 /* No more threads at this priority are waiting and the old level is
1725 * at least the thread level */
1726 int priority
= find_first_set_bit(bl_t
->pdist
.mask
);
1728 if (priority
!= bl_t
->priority
)
1730 /* Adjust this thread's priority */
1731 set_running_thread_priority(bl_t
, priority
);
1735 next
= *thread
->bqp
;
1739 /* Expected shortcut - no more waiters */
1740 bl_pr
= PRIORITY_IDLE
;
1744 if (thread
->priority
<= bl_pr
)
1746 /* Need to scan threads remaining in queue */
1747 bl_pr
= find_highest_priority_in_list_l(next
);
1750 if (prio_add_entry(&thread
->pdist
, bl_pr
) == 1 &&
1751 bl_pr
< thread
->priority
)
1753 /* Thread priority must be raised */
1754 thread
->priority
= bl_pr
;
1758 bl
->thread
= thread
; /* This thread pwns */
1759 bl
->priority
= bl_pr
; /* Save highest blocked priority */
1760 thread
->blocker
= NULL
; /* Thread not blocked */
1762 UNLOCK_THREAD(bl_t
);
1767 /*---------------------------------------------------------------------------
1768 * No threads must be blocked waiting for this thread except for it to exit.
1769 * The alternative is more elaborate cleanup and object registration code.
1770 * Check this for risk of silent data corruption when objects with
1771 * inheritable blocking are abandoned by the owner - not precise but may
1773 *---------------------------------------------------------------------------
1775 static void check_for_obj_waiters(const char *function
, struct thread_entry
*thread
)
1777 /* Only one bit in the mask should be set with a frequency on 1 which
1778 * represents the thread's own base priority */
1779 uint32_t mask
= thread
->pdist
.mask
;
1780 if ((mask
& (mask
- 1)) != 0 ||
1781 thread
->pdist
.hist
[find_first_set_bit(mask
)] > 1)
1783 unsigned char name
[32];
1784 thread_get_name(name
, 32, thread
);
1785 panicf("%s->%s with obj. waiters", function
, name
);
1788 #endif /* HAVE_PRIORITY_SCHEDULING */
1790 /*---------------------------------------------------------------------------
1791 * Move a thread back to a running state on its core.
1792 *---------------------------------------------------------------------------
1794 static void core_schedule_wakeup(struct thread_entry
*thread
)
1796 const unsigned int core
= IF_COP_CORE(thread
->core
);
1800 thread
->state
= STATE_RUNNING
;
1802 add_to_list_l(&cores
[core
].running
, thread
);
1803 rtr_add_entry(core
, thread
->priority
);
1808 if (core
!= CURRENT_CORE
)
1813 /*---------------------------------------------------------------------------
1814 * Check the core's timeout list when at least one thread is due to wake.
1815 * Filtering for the condition is done before making the call. Resets the
1816 * tick when the next check will occur.
1817 *---------------------------------------------------------------------------
1819 void check_tmo_threads(void)
1821 const unsigned int core
= CURRENT_CORE
;
1822 const long tick
= current_tick
; /* snapshot the current tick */
1823 long next_tmo_check
= tick
+ 60*HZ
; /* minimum duration: once/minute */
1824 struct thread_entry
*next
= cores
[core
].timeout
;
1826 /* If there are no processes waiting for a timeout, just keep the check
1827 tick from falling into the past. */
1829 /* Break the loop once we have walked through the list of all
1830 * sleeping processes or have removed them all. */
1831 while (next
!= NULL
)
1833 /* Check sleeping threads. Allow interrupts between checks. */
1836 struct thread_entry
*curr
= next
;
1838 next
= curr
->tmo
.next
;
1840 /* Lock thread slot against explicit wakeup */
1844 unsigned state
= curr
->state
;
1846 if (state
< TIMEOUT_STATE_FIRST
)
1848 /* Cleanup threads no longer on a timeout but still on the
1850 remove_from_list_tmo(curr
);
1852 else if (TIME_BEFORE(tick
, curr
->tmo_tick
))
1854 /* Timeout still pending - this will be the usual case */
1855 if (TIME_BEFORE(curr
->tmo_tick
, next_tmo_check
))
1857 /* Earliest timeout found so far - move the next check up
1859 next_tmo_check
= curr
->tmo_tick
;
1864 /* Sleep timeout has been reached so bring the thread back to
1866 if (state
== STATE_BLOCKED_W_TMO
)
1869 /* Lock the waiting thread's kernel object */
1870 struct corelock
*ocl
= curr
->obj_cl
;
1872 if (corelock_try_lock(ocl
) == 0)
1874 /* Need to retry in the correct order though the need is
1876 UNLOCK_THREAD(curr
);
1880 if (curr
->state
!= STATE_BLOCKED_W_TMO
)
1882 /* Thread was woken or removed explicitely while slot
1884 corelock_unlock(ocl
);
1885 remove_from_list_tmo(curr
);
1886 UNLOCK_THREAD(curr
);
1890 #endif /* NUM_CORES */
1892 remove_from_list_l(curr
->bqp
, curr
);
1894 #ifdef HAVE_WAKEUP_EXT_CB
1895 if (curr
->wakeup_ext_cb
!= NULL
)
1896 curr
->wakeup_ext_cb(curr
);
1899 #ifdef HAVE_PRIORITY_SCHEDULING
1900 if (curr
->blocker
!= NULL
)
1901 wakeup_priority_protocol_release(curr
);
1903 corelock_unlock(ocl
);
1905 /* else state == STATE_SLEEPING */
1907 remove_from_list_tmo(curr
);
1911 curr
->state
= STATE_RUNNING
;
1913 add_to_list_l(&cores
[core
].running
, curr
);
1914 rtr_add_entry(core
, curr
->priority
);
1919 UNLOCK_THREAD(curr
);
1922 cores
[core
].next_tmo_check
= next_tmo_check
;
1925 /*---------------------------------------------------------------------------
1926 * Performs operations that must be done before blocking a thread but after
1927 * the state is saved.
1928 *---------------------------------------------------------------------------
1931 static inline void run_blocking_ops(
1932 unsigned int core
, struct thread_entry
*thread
)
1934 struct thread_blk_ops
*ops
= &cores
[core
].blk_ops
;
1935 const unsigned flags
= ops
->flags
;
1937 if (flags
== TBOP_CLEAR
)
1942 case TBOP_SWITCH_CORE
:
1943 core_switch_blk_op(core
, thread
);
1945 case TBOP_UNLOCK_CORELOCK
:
1946 corelock_unlock(ops
->cl_p
);
1950 ops
->flags
= TBOP_CLEAR
;
1952 #endif /* NUM_CORES > 1 */
1955 void profile_thread(void)
1957 profstart(cores
[CURRENT_CORE
].running
- threads
);
1961 /*---------------------------------------------------------------------------
1962 * Prepares a thread to block on an object's list and/or for a specified
1963 * duration - expects object and slot to be appropriately locked if needed
1964 * and interrupts to be masked.
1965 *---------------------------------------------------------------------------
1967 static inline void block_thread_on_l(struct thread_entry
*thread
,
1970 /* If inlined, unreachable branches will be pruned with no size penalty
1971 because state is passed as a constant parameter. */
1972 const unsigned int core
= IF_COP_CORE(thread
->core
);
1974 /* Remove the thread from the list of running threads. */
1976 remove_from_list_l(&cores
[core
].running
, thread
);
1977 rtr_subtract_entry(core
, thread
->priority
);
1980 /* Add a timeout to the block if not infinite */
1984 case STATE_BLOCKED_W_TMO
:
1985 /* Put the thread into a new list of inactive threads. */
1986 add_to_list_l(thread
->bqp
, thread
);
1988 if (state
== STATE_BLOCKED
)
1992 case STATE_SLEEPING
:
1993 /* If this thread times out sooner than any other thread, update
1994 next_tmo_check to its timeout */
1995 if (TIME_BEFORE(thread
->tmo_tick
, cores
[core
].next_tmo_check
))
1997 cores
[core
].next_tmo_check
= thread
->tmo_tick
;
2000 if (thread
->tmo
.prev
== NULL
)
2002 add_to_list_tmo(thread
);
2004 /* else thread was never removed from list - just keep it there */
2008 /* Remember the the next thread about to block. */
2009 cores
[core
].block_task
= thread
;
2011 /* Report new state. */
2012 thread
->state
= state
;
2015 /*---------------------------------------------------------------------------
2016 * Switch thread in round robin fashion for any given priority. Any thread
2017 * that removed itself from the running list first must specify itself in
2020 * INTERNAL: Intended for use by kernel and not for programs.
2021 *---------------------------------------------------------------------------
2023 void switch_thread(void)
2026 const unsigned int core
= CURRENT_CORE
;
2027 struct thread_entry
*block
= cores
[core
].block_task
;
2028 struct thread_entry
*thread
= cores
[core
].running
;
2030 /* Get context to save - next thread to run is unknown until all wakeups
2034 cores
[core
].block_task
= NULL
;
2037 if (thread
== block
)
2039 /* This was the last thread running and another core woke us before
2040 * reaching here. Force next thread selection to give tmo threads or
2041 * other threads woken before this block a first chance. */
2047 /* Blocking task is the old one */
2053 profile_thread_stopped(thread
- threads
);
2056 /* Begin task switching by saving our current context so that we can
2057 * restore the state of the current thread later to the point prior
2059 store_context(&thread
->context
);
2061 /* Check if the current thread stack is overflown */
2062 if (thread
->stack
[0] != DEADBEEF
)
2063 thread_stkov(thread
);
2066 /* Run any blocking operations requested before switching/sleeping */
2067 run_blocking_ops(core
, thread
);
2070 #ifdef HAVE_PRIORITY_SCHEDULING
2071 IF_NO_SKIP_YIELD( if (thread
->skip_count
!= -1) )
2072 /* Reset the value of thread's skip count */
2073 thread
->skip_count
= 0;
2078 /* If there are threads on a timeout and the earliest wakeup is due,
2079 * check the list and wake any threads that need to start running
2081 if (!TIME_BEFORE(current_tick
, cores
[core
].next_tmo_check
))
2083 check_tmo_threads();
2089 thread
= cores
[core
].running
;
2093 /* Enter sleep mode to reduce power usage - woken up on interrupt
2094 * or wakeup request from another core - expected to enable
2097 core_sleep(IF_COP(core
));
2101 #ifdef HAVE_PRIORITY_SCHEDULING
2102 /* Select the new task based on priorities and the last time a
2103 * process got CPU time relative to the highest priority runnable
2105 struct priority_distribution
*pd
= &cores
[core
].rtr
;
2106 int max
= find_first_set_bit(pd
->mask
);
2110 /* Not switching on a block, tentatively select next thread */
2111 thread
= thread
->l
.next
;
2116 int priority
= thread
->priority
;
2119 /* This ridiculously simple method of aging seems to work
2120 * suspiciously well. It does tend to reward CPU hogs (under
2121 * yielding) but that's generally not desirable at all. On the
2122 * plus side, it, relatively to other threads, penalizes excess
2123 * yielding which is good if some high priority thread is
2124 * performing no useful work such as polling for a device to be
2125 * ready. Of course, aging is only employed when higher and lower
2126 * priority threads are runnable. The highest priority runnable
2127 * thread(s) are never skipped. */
2128 if (priority
<= max
||
2129 IF_NO_SKIP_YIELD( thread
->skip_count
== -1 || )
2130 (diff
= priority
- max
, ++thread
->skip_count
> diff
*diff
))
2132 cores
[core
].running
= thread
;
2136 thread
= thread
->l
.next
;
2139 /* Without priority use a simple FCFS algorithm */
2142 /* Not switching on a block, select next thread */
2143 thread
= thread
->l
.next
;
2144 cores
[core
].running
= thread
;
2146 #endif /* HAVE_PRIORITY_SCHEDULING */
2154 /* And finally give control to the next thread. */
2155 load_context(&thread
->context
);
2158 profile_thread_started(thread
- threads
);
2163 /*---------------------------------------------------------------------------
2164 * Sleeps a thread for at least a specified number of ticks with zero being
2165 * a wait until the next tick.
2167 * INTERNAL: Intended for use by kernel and not for programs.
2168 *---------------------------------------------------------------------------
2170 void sleep_thread(int ticks
)
2172 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
2174 LOCK_THREAD(current
);
2176 /* Set our timeout, remove from run list and join timeout list. */
2177 current
->tmo_tick
= current_tick
+ ticks
+ 1;
2178 block_thread_on_l(current
, STATE_SLEEPING
);
2180 UNLOCK_THREAD(current
);
2183 /*---------------------------------------------------------------------------
2184 * Indefinitely block a thread on a blocking queue for explicit wakeup.
2186 * INTERNAL: Intended for use by kernel objects and not for programs.
2187 *---------------------------------------------------------------------------
2189 void block_thread(struct thread_entry
*current
)
2191 /* Set the state to blocked and take us off of the run queue until we
2192 * are explicitly woken */
2193 LOCK_THREAD(current
);
2195 /* Set the list for explicit wakeup */
2196 block_thread_on_l(current
, STATE_BLOCKED
);
2198 #ifdef HAVE_PRIORITY_SCHEDULING
2199 if (current
->blocker
!= NULL
)
2201 /* Object supports PIP */
2202 current
= blocker_inherit_priority(current
);
2206 UNLOCK_THREAD(current
);
2209 /*---------------------------------------------------------------------------
2210 * Block a thread on a blocking queue for a specified time interval or until
2211 * explicitly woken - whichever happens first.
2213 * INTERNAL: Intended for use by kernel objects and not for programs.
2214 *---------------------------------------------------------------------------
2216 void block_thread_w_tmo(struct thread_entry
*current
, int timeout
)
2218 /* Get the entry for the current running thread. */
2219 LOCK_THREAD(current
);
2221 /* Set the state to blocked with the specified timeout */
2222 current
->tmo_tick
= current_tick
+ timeout
;
2224 /* Set the list for explicit wakeup */
2225 block_thread_on_l(current
, STATE_BLOCKED_W_TMO
);
2227 #ifdef HAVE_PRIORITY_SCHEDULING
2228 if (current
->blocker
!= NULL
)
2230 /* Object supports PIP */
2231 current
= blocker_inherit_priority(current
);
2235 UNLOCK_THREAD(current
);
2238 /*---------------------------------------------------------------------------
2239 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
2240 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
2242 * This code should be considered a critical section by the caller meaning
2243 * that the object's corelock should be held.
2245 * INTERNAL: Intended for use by kernel objects and not for programs.
2246 *---------------------------------------------------------------------------
2248 unsigned int wakeup_thread(struct thread_entry
**list
)
2250 struct thread_entry
*thread
= *list
;
2251 unsigned int result
= THREAD_NONE
;
2253 /* Check if there is a blocked thread at all. */
2257 LOCK_THREAD(thread
);
2259 /* Determine thread's current state. */
2260 switch (thread
->state
)
2263 case STATE_BLOCKED_W_TMO
:
2264 remove_from_list_l(list
, thread
);
2268 #ifdef HAVE_PRIORITY_SCHEDULING
2269 struct thread_entry
*current
;
2270 struct blocker
*bl
= thread
->blocker
;
2274 /* No inheritance - just boost the thread by aging */
2275 IF_NO_SKIP_YIELD( if (thread
->skip_count
!= -1) )
2276 thread
->skip_count
= thread
->priority
;
2277 current
= cores
[CURRENT_CORE
].running
;
2281 /* Call the specified unblocking PIP */
2282 current
= bl
->wakeup_protocol(thread
);
2285 if (current
!= NULL
&& thread
->priority
< current
->priority
2286 IF_COP( && thread
->core
== current
->core
))
2288 /* Woken thread is higher priority and exists on the same CPU core;
2289 * recommend a task switch. Knowing if this is an interrupt call
2290 * would be helpful here. */
2291 result
|= THREAD_SWITCH
;
2293 #endif /* HAVE_PRIORITY_SCHEDULING */
2295 core_schedule_wakeup(thread
);
2298 /* Nothing to do. State is not blocked. */
2299 #if THREAD_EXTRA_CHECKS
2301 THREAD_PANICF("wakeup_thread->block invalid", thread
);
2308 UNLOCK_THREAD(thread
);
2312 /*---------------------------------------------------------------------------
2313 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
2314 * from each operation or THREAD_NONE of nothing was awakened. Object owning
2315 * the queue must be locked first.
2317 * INTERNAL: Intended for use by kernel objects and not for programs.
2318 *---------------------------------------------------------------------------
2320 unsigned int thread_queue_wake(struct thread_entry
**list
)
2322 unsigned result
= THREAD_NONE
;
2326 unsigned int rc
= wakeup_thread(list
);
2328 if (rc
== THREAD_NONE
)
2329 break; /* No more threads */
2337 /*---------------------------------------------------------------------------
2338 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
2339 * will be locked on multicore.
2340 *---------------------------------------------------------------------------
2342 static struct thread_entry
* find_empty_thread_slot(void)
2344 /* Any slot could be on an interrupt-accessible list */
2345 IF_COP( int oldlevel
= disable_irq_save(); )
2346 struct thread_entry
*thread
= NULL
;
2349 for (n
= 0; n
< MAXTHREADS
; n
++)
2351 /* Obtain current slot state - lock it on multicore */
2352 struct thread_entry
*t
= &threads
[n
];
2355 if (t
->state
== STATE_KILLED
IF_COP( && t
->name
!= THREAD_DESTRUCT
))
2357 /* Slot is empty - leave it locked and caller will unlock */
2362 /* Finished examining slot - no longer busy - unlock on multicore */
2366 IF_COP( restore_irq(oldlevel
); ) /* Reenable interrups - this slot is
2367 not accesible to them yet */
2372 /*---------------------------------------------------------------------------
2373 * Place the current core in idle mode - woken up on interrupt or wake
2374 * request from another core.
2375 *---------------------------------------------------------------------------
2377 void core_idle(void)
2379 IF_COP( const unsigned int core
= CURRENT_CORE
; )
2381 core_sleep(IF_COP(core
));
2384 /*---------------------------------------------------------------------------
2385 * Create a thread. If using a dual core architecture, specify which core to
2386 * start the thread on.
2388 * Return ID if context area could be allocated, else NULL.
2389 *---------------------------------------------------------------------------
2391 struct thread_entry
*
2392 create_thread(void (*function
)(void), void* stack
, size_t stack_size
,
2393 unsigned flags
, const char *name
2394 IF_PRIO(, int priority
)
2395 IF_COP(, unsigned int core
))
2398 unsigned int stack_words
;
2399 uintptr_t stackptr
, stackend
;
2400 struct thread_entry
*thread
;
2404 thread
= find_empty_thread_slot();
2410 oldlevel
= disable_irq_save();
2412 /* Munge the stack to make it easy to spot stack overflows */
2413 stackptr
= ALIGN_UP((uintptr_t)stack
, sizeof (uintptr_t));
2414 stackend
= ALIGN_DOWN((uintptr_t)stack
+ stack_size
, sizeof (uintptr_t));
2415 stack_size
= stackend
- stackptr
;
2416 stack_words
= stack_size
/ sizeof (uintptr_t);
2418 for (i
= 0; i
< stack_words
; i
++)
2420 ((uintptr_t *)stackptr
)[i
] = DEADBEEF
;
2423 /* Store interesting information */
2424 thread
->name
= name
;
2425 thread
->stack
= (uintptr_t *)stackptr
;
2426 thread
->stack_size
= stack_size
;
2427 thread
->queue
= NULL
;
2428 #ifdef HAVE_WAKEUP_EXT_CB
2429 thread
->wakeup_ext_cb
= NULL
;
2431 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2432 thread
->cpu_boost
= 0;
2434 #ifdef HAVE_PRIORITY_SCHEDULING
2435 memset(&thread
->pdist
, 0, sizeof(thread
->pdist
));
2436 thread
->blocker
= NULL
;
2437 thread
->base_priority
= priority
;
2438 thread
->priority
= priority
;
2439 thread
->skip_count
= priority
;
2440 prio_add_entry(&thread
->pdist
, priority
);
2444 thread
->core
= core
;
2446 /* Writeback stack munging or anything else before starting */
2447 if (core
!= CURRENT_CORE
)
2453 /* Thread is not on any timeout list but be a bit paranoid */
2454 thread
->tmo
.prev
= NULL
;
2456 state
= (flags
& CREATE_THREAD_FROZEN
) ?
2457 STATE_FROZEN
: STATE_RUNNING
;
2459 thread
->context
.sp
= (typeof (thread
->context
.sp
))stackend
;
2461 /* Load the thread's context structure with needed startup information */
2462 THREAD_STARTUP_INIT(core
, thread
, function
);
2464 thread
->state
= state
;
2466 if (state
== STATE_RUNNING
)
2467 core_schedule_wakeup(thread
);
2469 UNLOCK_THREAD(thread
);
2471 restore_irq(oldlevel
);
2476 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2477 /*---------------------------------------------------------------------------
2478 * Change the boost state of a thread boosting or unboosting the CPU
2480 *---------------------------------------------------------------------------
2482 static inline void boost_thread(struct thread_entry
*thread
, bool boost
)
2484 if ((thread
->cpu_boost
!= 0) != boost
)
2486 thread
->cpu_boost
= boost
;
2491 void trigger_cpu_boost(void)
2493 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
2494 boost_thread(current
, true);
2497 void cancel_cpu_boost(void)
2499 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
2500 boost_thread(current
, false);
2502 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
2504 /*---------------------------------------------------------------------------
2505 * Block the current thread until another thread terminates. A thread may
2506 * wait on itself to terminate which prevents it from running again and it
2507 * will need to be killed externally.
2508 * Parameter is the ID as returned from create_thread().
2509 *---------------------------------------------------------------------------
2511 void thread_wait(struct thread_entry
*thread
)
2513 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
2518 /* Lock thread-as-waitable-object lock */
2519 corelock_lock(&thread
->waiter_cl
);
2521 /* Be sure it hasn't been killed yet */
2522 if (thread
->state
!= STATE_KILLED
)
2524 IF_COP( current
->obj_cl
= &thread
->waiter_cl
; )
2525 current
->bqp
= &thread
->queue
;
2528 block_thread(current
);
2530 corelock_unlock(&thread
->waiter_cl
);
2536 corelock_unlock(&thread
->waiter_cl
);
2539 /*---------------------------------------------------------------------------
2540 * Exit the current thread. The Right Way to Do Things (TM).
2541 *---------------------------------------------------------------------------
2543 void thread_exit(void)
2545 const unsigned int core
= CURRENT_CORE
;
2546 struct thread_entry
*current
= cores
[core
].running
;
2548 /* Cancel CPU boost if any */
2553 corelock_lock(¤t
->waiter_cl
);
2554 LOCK_THREAD(current
);
2556 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
2557 if (current
->name
== THREAD_DESTRUCT
)
2559 /* Thread being killed - become a waiter */
2560 UNLOCK_THREAD(current
);
2561 corelock_unlock(¤t
->waiter_cl
);
2562 thread_wait(current
);
2563 THREAD_PANICF("thread_exit->WK:*R", current
);
2567 #ifdef HAVE_PRIORITY_SCHEDULING
2568 check_for_obj_waiters("thread_exit", current
);
2571 if (current
->tmo
.prev
!= NULL
)
2573 /* Cancel pending timeout list removal */
2574 remove_from_list_tmo(current
);
2577 /* Switch tasks and never return */
2578 block_thread_on_l(current
, STATE_KILLED
);
2581 /* Switch to the idle stack if not on the main core (where "main"
2582 * runs) - we can hope gcc doesn't need the old stack beyond this
2586 switch_to_idle_stack(core
);
2591 current
->name
= NULL
;
2593 /* Signal this thread */
2594 thread_queue_wake(¤t
->queue
);
2595 corelock_unlock(¤t
->waiter_cl
);
2596 /* Slot must be unusable until thread is really gone */
2597 UNLOCK_THREAD_AT_TASK_SWITCH(current
);
2599 /* This should never and must never be reached - if it is, the
2600 * state is corrupted */
2601 THREAD_PANICF("thread_exit->K:*R", current
);
2604 #ifdef ALLOW_REMOVE_THREAD
2605 /*---------------------------------------------------------------------------
2606 * Remove a thread from the scheduler. Not The Right Way to Do Things in
2609 * Parameter is the ID as returned from create_thread().
2611 * Use with care on threads that are not under careful control as this may
2612 * leave various objects in an undefined state.
2613 *---------------------------------------------------------------------------
2615 void remove_thread(struct thread_entry
*thread
)
2618 /* core is not constant here because of core switching */
2619 unsigned int core
= CURRENT_CORE
;
2620 unsigned int old_core
= NUM_CORES
;
2621 struct corelock
*ocl
= NULL
;
2623 const unsigned int core
= CURRENT_CORE
;
2625 struct thread_entry
*current
= cores
[core
].running
;
2633 if (thread
== current
)
2634 thread_exit(); /* Current thread - do normal exit */
2636 oldlevel
= disable_irq_save();
2638 corelock_lock(&thread
->waiter_cl
);
2639 LOCK_THREAD(thread
);
2641 state
= thread
->state
;
2643 if (state
== STATE_KILLED
)
2649 if (thread
->name
== THREAD_DESTRUCT
)
2651 /* Thread being killed - become a waiter */
2652 UNLOCK_THREAD(thread
);
2653 corelock_unlock(&thread
->waiter_cl
);
2654 restore_irq(oldlevel
);
2655 thread_wait(thread
);
2659 thread
->name
= THREAD_DESTRUCT
; /* Slot can't be used for now */
2661 #ifdef HAVE_PRIORITY_SCHEDULING
2662 check_for_obj_waiters("remove_thread", thread
);
2665 if (thread
->core
!= core
)
2667 /* Switch cores and safely extract the thread there */
2668 /* Slot HAS to be unlocked or a deadlock could occur which means other
2669 * threads have to be guided into becoming thread waiters if they
2670 * attempt to remove it. */
2671 unsigned int new_core
= thread
->core
;
2673 corelock_unlock(&thread
->waiter_cl
);
2675 UNLOCK_THREAD(thread
);
2676 restore_irq(oldlevel
);
2678 old_core
= switch_core(new_core
);
2680 oldlevel
= disable_irq_save();
2682 corelock_lock(&thread
->waiter_cl
);
2683 LOCK_THREAD(thread
);
2685 state
= thread
->state
;
2687 /* Perform the extraction and switch ourselves back to the original
2690 #endif /* NUM_CORES > 1 */
2692 if (thread
->tmo
.prev
!= NULL
)
2694 /* Clean thread off the timeout list if a timeout check hasn't
2696 remove_from_list_tmo(thread
);
2699 #ifdef HAVE_SCHEDULER_BOOSTCTRL
2700 /* Cancel CPU boost if any */
2701 boost_thread(thread
, false);
2704 IF_COP( retry_state
: )
2710 /* Remove thread from ready to run tasks */
2711 remove_from_list_l(&cores
[core
].running
, thread
);
2712 rtr_subtract_entry(core
, thread
->priority
);
2716 case STATE_BLOCKED_W_TMO
:
2717 /* Remove thread from the queue it's blocked on - including its
2718 * own if waiting there */
2720 if (&thread
->waiter_cl
!= thread
->obj_cl
)
2722 ocl
= thread
->obj_cl
;
2724 if (corelock_try_lock(ocl
) == 0)
2726 UNLOCK_THREAD(thread
);
2728 LOCK_THREAD(thread
);
2730 if (thread
->state
!= state
)
2732 /* Something woke the thread */
2733 state
= thread
->state
;
2734 corelock_unlock(ocl
);
2740 remove_from_list_l(thread
->bqp
, thread
);
2742 #ifdef HAVE_WAKEUP_EXT_CB
2743 if (thread
->wakeup_ext_cb
!= NULL
)
2744 thread
->wakeup_ext_cb(thread
);
2747 #ifdef HAVE_PRIORITY_SCHEDULING
2748 if (thread
->blocker
!= NULL
)
2750 /* Remove thread's priority influence from its chain */
2751 wakeup_priority_protocol_release(thread
);
2757 corelock_unlock(ocl
);
2760 /* Otherwise thread is frozen and hasn't run yet */
2763 thread
->state
= STATE_KILLED
;
2765 /* If thread was waiting on itself, it will have been removed above.
2766 * The wrong order would result in waking the thread first and deadlocking
2767 * since the slot is already locked. */
2768 thread_queue_wake(&thread
->queue
);
2770 thread
->name
= NULL
;
2772 thread_killed
: /* Thread was already killed */
2773 /* Removal complete - safe to unlock and reenable interrupts */
2774 corelock_unlock(&thread
->waiter_cl
);
2775 UNLOCK_THREAD(thread
);
2776 restore_irq(oldlevel
);
2779 if (old_core
< NUM_CORES
)
2781 /* Did a removal on another processor's thread - switch back to
2783 switch_core(old_core
);
2787 #endif /* ALLOW_REMOVE_THREAD */
2789 #ifdef HAVE_PRIORITY_SCHEDULING
2790 /*---------------------------------------------------------------------------
2791 * Sets the thread's relative base priority for the core it runs on. Any
2792 * needed inheritance changes also may happen.
2793 *---------------------------------------------------------------------------
2795 int thread_set_priority(struct thread_entry
*thread
, int priority
)
2797 int old_base_priority
= -1;
2799 /* A little safety measure */
2800 if (priority
< HIGHEST_PRIORITY
|| priority
> LOWEST_PRIORITY
)
2804 thread
= cores
[CURRENT_CORE
].running
;
2806 /* Thread could be on any list and therefore on an interrupt accessible
2807 one - disable interrupts */
2808 int oldlevel
= disable_irq_save();
2810 LOCK_THREAD(thread
);
2812 /* Make sure it's not killed */
2813 if (thread
->state
!= STATE_KILLED
)
2815 int old_priority
= thread
->priority
;
2817 old_base_priority
= thread
->base_priority
;
2818 thread
->base_priority
= priority
;
2820 prio_move_entry(&thread
->pdist
, old_base_priority
, priority
);
2821 priority
= find_first_set_bit(thread
->pdist
.mask
);
2823 if (old_priority
== priority
)
2825 /* No priority change - do nothing */
2827 else if (thread
->state
== STATE_RUNNING
)
2829 /* This thread is running - change location on the run
2830 * queue. No transitive inheritance needed. */
2831 set_running_thread_priority(thread
, priority
);
2835 thread
->priority
= priority
;
2837 if (thread
->blocker
!= NULL
)
2839 /* Bubble new priority down the chain */
2840 struct blocker
*bl
= thread
->blocker
; /* Blocker struct */
2841 struct thread_entry
*bl_t
= bl
->thread
; /* Blocking thread */
2842 struct thread_entry
* const tstart
= thread
; /* Initial thread */
2843 const int highest
= MIN(priority
, old_priority
); /* Higher of new or old */
2847 struct thread_entry
*next
; /* Next thread to check */
2848 int bl_pr
; /* Highest blocked thread */
2849 int queue_pr
; /* New highest blocked thread */
2851 /* Owner can change but thread cannot be dislodged - thread
2852 * may not be the first in the queue which allows other
2853 * threads ahead in the list to be given ownership during the
2854 * operation. If thread is next then the waker will have to
2855 * wait for us and the owner of the object will remain fixed.
2856 * If we successfully grab the owner -- which at some point
2857 * is guaranteed -- then the queue remains fixed until we
2863 /* Double-check the owner - retry if it changed */
2864 if (bl
->thread
== bl_t
)
2867 UNLOCK_THREAD(bl_t
);
2871 bl_pr
= bl
->priority
;
2873 if (highest
> bl_pr
)
2874 break; /* Object priority won't change */
2876 /* This will include the thread being set */
2877 queue_pr
= find_highest_priority_in_list_l(*thread
->bqp
);
2879 if (queue_pr
== bl_pr
)
2880 break; /* Object priority not changing */
2882 /* Update thread boost for this object */
2883 bl
->priority
= queue_pr
;
2884 prio_move_entry(&bl_t
->pdist
, bl_pr
, queue_pr
);
2885 bl_pr
= find_first_set_bit(bl_t
->pdist
.mask
);
2887 if (bl_t
->priority
== bl_pr
)
2888 break; /* Blocking thread priority not changing */
2890 if (bl_t
->state
== STATE_RUNNING
)
2892 /* Thread not blocked - we're done */
2893 set_running_thread_priority(bl_t
, bl_pr
);
2897 bl_t
->priority
= bl_pr
;
2898 bl
= bl_t
->blocker
; /* Blocking thread has a blocker? */
2901 break; /* End of chain */
2906 break; /* Full-circle */
2908 UNLOCK_THREAD(thread
);
2914 UNLOCK_THREAD(bl_t
);
2919 UNLOCK_THREAD(thread
);
2921 restore_irq(oldlevel
);
2923 return old_base_priority
;
2926 /*---------------------------------------------------------------------------
2927 * Returns the current base priority for a thread.
2928 *---------------------------------------------------------------------------
2930 int thread_get_priority(struct thread_entry
*thread
)
2932 /* Simple, quick probe. */
2934 thread
= cores
[CURRENT_CORE
].running
;
2936 return thread
->base_priority
;
2938 #endif /* HAVE_PRIORITY_SCHEDULING */
2940 /*---------------------------------------------------------------------------
2941 * Starts a frozen thread - similar semantics to wakeup_thread except that
2942 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2943 * virtue of the slot having a state of STATE_FROZEN.
2944 *---------------------------------------------------------------------------
2946 void thread_thaw(struct thread_entry
*thread
)
2948 int oldlevel
= disable_irq_save();
2949 LOCK_THREAD(thread
);
2951 if (thread
->state
== STATE_FROZEN
)
2952 core_schedule_wakeup(thread
);
2954 UNLOCK_THREAD(thread
);
2955 restore_irq(oldlevel
);
2958 /*---------------------------------------------------------------------------
2959 * Return the ID of the currently executing thread.
2960 *---------------------------------------------------------------------------
2962 struct thread_entry
* thread_get_current(void)
2964 return cores
[CURRENT_CORE
].running
;
2968 /*---------------------------------------------------------------------------
2969 * Switch the processor that the currently executing thread runs on.
2970 *---------------------------------------------------------------------------
2972 unsigned int switch_core(unsigned int new_core
)
2974 const unsigned int core
= CURRENT_CORE
;
2975 struct thread_entry
*current
= cores
[core
].running
;
2977 if (core
== new_core
)
2979 /* No change - just return same core */
2983 int oldlevel
= disable_irq_save();
2984 LOCK_THREAD(current
);
2986 if (current
->name
== THREAD_DESTRUCT
)
2988 /* Thread being killed - deactivate and let process complete */
2989 UNLOCK_THREAD(current
);
2990 restore_irq(oldlevel
);
2991 thread_wait(current
);
2992 /* Should never be reached */
2993 THREAD_PANICF("switch_core->D:*R", current
);
2996 /* Get us off the running list for the current core */
2998 remove_from_list_l(&cores
[core
].running
, current
);
2999 rtr_subtract_entry(core
, current
->priority
);
3002 /* Stash return value (old core) in a safe place */
3003 current
->retval
= core
;
3005 /* If a timeout hadn't yet been cleaned-up it must be removed now or
3006 * the other core will likely attempt a removal from the wrong list! */
3007 if (current
->tmo
.prev
!= NULL
)
3009 remove_from_list_tmo(current
);
3012 /* Change the core number for this thread slot */
3013 current
->core
= new_core
;
3015 /* Do not use core_schedule_wakeup here since this will result in
3016 * the thread starting to run on the other core before being finished on
3017 * this one. Delay the list unlock to keep the other core stuck
3018 * until this thread is ready. */
3021 rtr_add_entry(new_core
, current
->priority
);
3022 add_to_list_l(&cores
[new_core
].running
, current
);
3024 /* Make a callback into device-specific code, unlock the wakeup list so
3025 * that execution may resume on the new core, unlock our slot and finally
3026 * restore the interrupt level */
3027 cores
[core
].blk_ops
.flags
= TBOP_SWITCH_CORE
;
3028 cores
[core
].blk_ops
.cl_p
= &cores
[new_core
].rtr_cl
;
3029 cores
[core
].block_task
= current
;
3031 UNLOCK_THREAD(current
);
3033 /* Alert other core to activity */
3034 core_wake(new_core
);
3036 /* Do the stack switching, cache_maintenence and switch_thread call -
3037 requires native code */
3038 switch_thread_core(core
, current
);
3040 /* Finally return the old core to caller */
3041 return current
->retval
;
3043 #endif /* NUM_CORES > 1 */
3045 /*---------------------------------------------------------------------------
3046 * Initialize threading API. This assumes interrupts are not yet enabled. On
3047 * multicore setups, no core is allowed to proceed until create_thread calls
3048 * are safe to perform.
3049 *---------------------------------------------------------------------------
3051 void init_threads(void)
3053 const unsigned int core
= CURRENT_CORE
;
3054 struct thread_entry
*thread
;
3056 /* CPU will initialize first and then sleep */
3057 thread
= find_empty_thread_slot();
3061 /* WTF? There really must be a slot available at this stage.
3062 * This can fail if, for example, .bss isn't zero'ed out by the loader
3063 * or threads is in the wrong section. */
3064 THREAD_PANICF("init_threads->no slot", NULL
);
3067 /* Initialize initially non-zero members of core */
3068 cores
[core
].next_tmo_check
= current_tick
; /* Something not in the past */
3070 /* Initialize initially non-zero members of slot */
3071 UNLOCK_THREAD(thread
); /* No sync worries yet */
3072 thread
->name
= main_thread_name
;
3073 thread
->state
= STATE_RUNNING
;
3074 IF_COP( thread
->core
= core
; )
3075 #ifdef HAVE_PRIORITY_SCHEDULING
3076 corelock_init(&cores
[core
].rtr_cl
);
3077 thread
->base_priority
= PRIORITY_USER_INTERFACE
;
3078 prio_add_entry(&thread
->pdist
, PRIORITY_USER_INTERFACE
);
3079 thread
->priority
= PRIORITY_USER_INTERFACE
;
3080 rtr_add_entry(core
, PRIORITY_USER_INTERFACE
);
3082 corelock_init(&thread
->waiter_cl
);
3083 corelock_init(&thread
->slot_cl
);
3085 add_to_list_l(&cores
[core
].running
, thread
);
3089 thread
->stack
= stackbegin
;
3090 thread
->stack_size
= (uintptr_t)stackend
- (uintptr_t)stackbegin
;
3091 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
3092 /* Wait for other processors to finish their inits since create_thread
3093 * isn't safe to call until the kernel inits are done. The first
3094 * threads created in the system must of course be created by CPU. */
3095 core_thread_init(CPU
);
3099 /* Initial stack is the idle stack */
3100 thread
->stack
= idle_stacks
[core
];
3101 thread
->stack_size
= IDLE_STACK_SIZE
;
3102 /* After last processor completes, it should signal all others to
3103 * proceed or may signal the next and call thread_exit(). The last one
3104 * to finish will signal CPU. */
3105 core_thread_init(core
);
3106 /* Other cores do not have a main thread - go idle inside switch_thread
3107 * until a thread can run on the core. */
3109 #endif /* NUM_CORES */
3113 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
3115 static inline int stack_usage(uintptr_t *stackptr
, size_t stack_size
)
3117 static int stack_usage(uintptr_t *stackptr
, size_t stack_size
)
3120 unsigned int stack_words
= stack_size
/ sizeof (uintptr_t);
3124 for (i
= 0; i
< stack_words
; i
++)
3126 if (stackptr
[i
] != DEADBEEF
)
3128 usage
= ((stack_words
- i
) * 100) / stack_words
;
3136 /*---------------------------------------------------------------------------
3137 * Returns the maximum percentage of stack a thread ever used while running.
3138 * NOTE: Some large buffer allocations that don't use enough the buffer to
3139 * overwrite stackptr[0] will not be seen.
3140 *---------------------------------------------------------------------------
3142 int thread_stack_usage(const struct thread_entry
*thread
)
3144 return stack_usage(thread
->stack
, thread
->stack_size
);
3148 /*---------------------------------------------------------------------------
3149 * Returns the maximum percentage of the core's idle stack ever used during
3151 *---------------------------------------------------------------------------
3153 int idle_stack_usage(unsigned int core
)
3155 return stack_usage(idle_stacks
[core
], IDLE_STACK_SIZE
);
3159 /*---------------------------------------------------------------------------
3160 * Fills in the buffer with the specified thread's name. If the name is NULL,
3161 * empty, or the thread is in destruct state a formatted ID is written
3163 *---------------------------------------------------------------------------
3165 void thread_get_name(char *buffer
, int size
,
3166 struct thread_entry
*thread
)
3175 /* Display thread name if one or ID if none */
3176 const char *name
= thread
->name
;
3177 const char *fmt
= "%s";
3178 if (name
== NULL
IF_COP(|| name
== THREAD_DESTRUCT
) || *name
== '\0')
3180 name
= (const char *)thread
;
3183 snprintf(buffer
, size
, fmt
, name
);