Revert thread_stkov change
[kugel-rb.git] / firmware / thread.c
blobb3d8ec39700a3efab66737b4e28eaf84abbec75a
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 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
127 extern uintptr_t stackbegin[];
128 extern uintptr_t stackend[];
129 #else
130 extern uintptr_t *stackbegin;
131 extern uintptr_t *stackend;
132 #endif
134 static inline void core_sleep(IF_COP_VOID(unsigned int core))
135 __attribute__((always_inline));
137 void check_tmo_threads(void)
138 __attribute__((noinline));
140 static inline void block_thread_on_l(struct thread_entry *thread, unsigned state)
141 __attribute__((always_inline));
143 static void add_to_list_tmo(struct thread_entry *thread)
144 __attribute__((noinline));
146 static void core_schedule_wakeup(struct thread_entry *thread)
147 __attribute__((noinline));
149 #if NUM_CORES > 1
150 static inline void run_blocking_ops(
151 unsigned int core, struct thread_entry *thread)
152 __attribute__((always_inline));
153 #endif
155 static void thread_stkov(struct thread_entry *thread)
156 __attribute__((noinline));
158 static inline void store_context(void* addr)
159 __attribute__((always_inline));
161 static inline void load_context(const void* addr)
162 __attribute__((always_inline));
164 #if NUM_CORES > 1
165 static void thread_final_exit_do(struct thread_entry *current)
166 __attribute__((noinline, noreturn, used));
167 #else
168 static inline void thread_final_exit(struct thread_entry *current)
169 __attribute__((always_inline, noreturn));
170 #endif
172 void switch_thread(void)
173 __attribute__((noinline));
175 /****************************************************************************
176 * Processor-specific section - include necessary core support
178 #if defined(ANDROID)
179 #include "thread-android-arm.c"
180 #elif defined(CPU_ARM)
181 #include "thread-arm.c"
182 #if defined (CPU_PP)
183 #include "thread-pp.c"
184 #endif /* CPU_PP */
185 #elif defined(CPU_COLDFIRE)
186 #include "thread-coldfire.c"
187 #elif CONFIG_CPU == SH7034
188 #include "thread-sh.c"
189 #elif defined(CPU_MIPS) && CPU_MIPS == 32
190 #include "thread-mips32.c"
191 #else
192 /* Wouldn't compile anyway */
193 #error Processor not implemented.
194 #endif /* CONFIG_CPU == */
196 #ifndef IF_NO_SKIP_YIELD
197 #define IF_NO_SKIP_YIELD(...)
198 #endif
201 * End Processor-specific section
202 ***************************************************************************/
204 #if THREAD_EXTRA_CHECKS
205 static void thread_panicf(const char *msg, struct thread_entry *thread)
207 IF_COP( const unsigned int core = thread->core; )
208 static char name[32];
209 thread_get_name(name, 32, thread);
210 panicf ("%s %s" IF_COP(" (%d)"), msg, name IF_COP(, core));
212 static void thread_stkov(struct thread_entry *thread)
214 thread_panicf("Stkov", thread);
216 #define THREAD_PANICF(msg, thread) \
217 thread_panicf(msg, thread)
218 #define THREAD_ASSERT(exp, msg, thread) \
219 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
220 #else
221 static void thread_stkov(struct thread_entry *thread)
223 IF_COP( const unsigned int core = thread->core; )
224 static char name[32];
225 thread_get_name(name, 32, thread);
226 panicf("Stkov %s" IF_COP(" (%d)"), name IF_COP(, core));
228 #define THREAD_PANICF(msg, thread)
229 #define THREAD_ASSERT(exp, msg, thread)
230 #endif /* THREAD_EXTRA_CHECKS */
232 /* Thread locking */
233 #if NUM_CORES > 1
234 #define LOCK_THREAD(thread) \
235 ({ corelock_lock(&(thread)->slot_cl); })
236 #define TRY_LOCK_THREAD(thread) \
237 ({ corelock_try_lock(&(thread)->slot_cl); })
238 #define UNLOCK_THREAD(thread) \
239 ({ corelock_unlock(&(thread)->slot_cl); })
240 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
241 ({ unsigned int _core = (thread)->core; \
242 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
243 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
244 #else
245 #define LOCK_THREAD(thread) \
246 ({ })
247 #define TRY_LOCK_THREAD(thread) \
248 ({ })
249 #define UNLOCK_THREAD(thread) \
250 ({ })
251 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
252 ({ })
253 #endif
255 /* RTR list */
256 #define RTR_LOCK(core) \
257 ({ corelock_lock(&cores[core].rtr_cl); })
258 #define RTR_UNLOCK(core) \
259 ({ corelock_unlock(&cores[core].rtr_cl); })
261 #ifdef HAVE_PRIORITY_SCHEDULING
262 #define rtr_add_entry(core, priority) \
263 prio_add_entry(&cores[core].rtr, (priority))
265 #define rtr_subtract_entry(core, priority) \
266 prio_subtract_entry(&cores[core].rtr, (priority))
268 #define rtr_move_entry(core, from, to) \
269 prio_move_entry(&cores[core].rtr, (from), (to))
270 #else
271 #define rtr_add_entry(core, priority)
272 #define rtr_add_entry_inl(core, priority)
273 #define rtr_subtract_entry(core, priority)
274 #define rtr_subtract_entry_inl(core, priotity)
275 #define rtr_move_entry(core, from, to)
276 #define rtr_move_entry_inl(core, from, to)
277 #endif
279 /*---------------------------------------------------------------------------
280 * Thread list structure - circular:
281 * +------------------------------+
282 * | |
283 * +--+---+<-+---+<-+---+<-+---+<-+
284 * Head->| T | | T | | T | | T |
285 * +->+---+->+---+->+---+->+---+--+
286 * | |
287 * +------------------------------+
288 *---------------------------------------------------------------------------
291 /*---------------------------------------------------------------------------
292 * Adds a thread to a list of threads using "insert last". Uses the "l"
293 * links.
294 *---------------------------------------------------------------------------
296 static void add_to_list_l(struct thread_entry **list,
297 struct thread_entry *thread)
299 struct thread_entry *l = *list;
301 if (l == NULL)
303 /* Insert into unoccupied list */
304 thread->l.prev = thread;
305 thread->l.next = thread;
306 *list = thread;
307 return;
310 /* Insert last */
311 thread->l.prev = l->l.prev;
312 thread->l.next = l;
313 l->l.prev->l.next = thread;
314 l->l.prev = thread;
317 /*---------------------------------------------------------------------------
318 * Removes a thread from a list of threads. Uses the "l" links.
319 *---------------------------------------------------------------------------
321 static void remove_from_list_l(struct thread_entry **list,
322 struct thread_entry *thread)
324 struct thread_entry *prev, *next;
326 next = thread->l.next;
328 if (thread == next)
330 /* The only item */
331 *list = NULL;
332 return;
335 if (thread == *list)
337 /* List becomes next item */
338 *list = next;
341 prev = thread->l.prev;
343 /* Fix links to jump over the removed entry. */
344 next->l.prev = prev;
345 prev->l.next = next;
348 /*---------------------------------------------------------------------------
349 * Timeout list structure - circular reverse (to make "remove item" O(1)),
350 * NULL-terminated forward (to ease the far more common forward traversal):
351 * +------------------------------+
352 * | |
353 * +--+---+<-+---+<-+---+<-+---+<-+
354 * Head->| T | | T | | T | | T |
355 * +---+->+---+->+---+->+---+-X
356 *---------------------------------------------------------------------------
359 /*---------------------------------------------------------------------------
360 * Add a thread from the core's timout list by linking the pointers in its
361 * tmo structure.
362 *---------------------------------------------------------------------------
364 static void add_to_list_tmo(struct thread_entry *thread)
366 struct thread_entry *tmo = cores[IF_COP_CORE(thread->core)].timeout;
367 THREAD_ASSERT(thread->tmo.prev == NULL,
368 "add_to_list_tmo->already listed", thread);
370 thread->tmo.next = NULL;
372 if (tmo == NULL)
374 /* Insert into unoccupied list */
375 thread->tmo.prev = thread;
376 cores[IF_COP_CORE(thread->core)].timeout = thread;
377 return;
380 /* Insert Last */
381 thread->tmo.prev = tmo->tmo.prev;
382 tmo->tmo.prev->tmo.next = thread;
383 tmo->tmo.prev = thread;
386 /*---------------------------------------------------------------------------
387 * Remove a thread from the core's timout list by unlinking the pointers in
388 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
389 * is cancelled.
390 *---------------------------------------------------------------------------
392 static void remove_from_list_tmo(struct thread_entry *thread)
394 struct thread_entry **list = &cores[IF_COP_CORE(thread->core)].timeout;
395 struct thread_entry *prev = thread->tmo.prev;
396 struct thread_entry *next = thread->tmo.next;
398 THREAD_ASSERT(prev != NULL, "remove_from_list_tmo->not listed", thread);
400 if (next != NULL)
401 next->tmo.prev = prev;
403 if (thread == *list)
405 /* List becomes next item and empty if next == NULL */
406 *list = next;
407 /* Mark as unlisted */
408 thread->tmo.prev = NULL;
410 else
412 if (next == NULL)
413 (*list)->tmo.prev = prev;
414 prev->tmo.next = next;
415 /* Mark as unlisted */
416 thread->tmo.prev = NULL;
421 #ifdef HAVE_PRIORITY_SCHEDULING
422 /*---------------------------------------------------------------------------
423 * Priority distribution structure (one category for each possible priority):
425 * +----+----+----+ ... +-----+
426 * hist: | F0 | F1 | F2 | | F31 |
427 * +----+----+----+ ... +-----+
428 * mask: | b0 | b1 | b2 | | b31 |
429 * +----+----+----+ ... +-----+
431 * F = count of threads at priority category n (frequency)
432 * b = bitmask of non-zero priority categories (occupancy)
434 * / if H[n] != 0 : 1
435 * b[n] = |
436 * \ else : 0
438 *---------------------------------------------------------------------------
439 * Basic priority inheritance priotocol (PIP):
441 * Mn = mutex n, Tn = thread n
443 * A lower priority thread inherits the priority of the highest priority
444 * thread blocked waiting for it to complete an action (such as release a
445 * mutex or respond to a message via queue_send):
447 * 1) T2->M1->T1
449 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
450 * priority than T1 then T1 inherits the priority of T2.
452 * 2) T3
453 * \/
454 * T2->M1->T1
456 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
457 * T1 inherits the higher of T2 and T3.
459 * 3) T3->M2->T2->M1->T1
461 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
462 * then T1 inherits the priority of T3 through T2.
464 * Blocking chains can grow arbitrarily complex (though it's best that they
465 * not form at all very often :) and build-up from these units.
466 *---------------------------------------------------------------------------
469 /*---------------------------------------------------------------------------
470 * Increment frequency at category "priority"
471 *---------------------------------------------------------------------------
473 static inline unsigned int prio_add_entry(
474 struct priority_distribution *pd, int priority)
476 unsigned int count;
477 /* Enough size/instruction count difference for ARM makes it worth it to
478 * use different code (192 bytes for ARM). Only thing better is ASM. */
479 #ifdef CPU_ARM
480 count = pd->hist[priority];
481 if (++count == 1)
482 pd->mask |= 1 << priority;
483 pd->hist[priority] = count;
484 #else /* This one's better for Coldfire */
485 if ((count = ++pd->hist[priority]) == 1)
486 pd->mask |= 1 << priority;
487 #endif
489 return count;
492 /*---------------------------------------------------------------------------
493 * Decrement frequency at category "priority"
494 *---------------------------------------------------------------------------
496 static inline unsigned int prio_subtract_entry(
497 struct priority_distribution *pd, int priority)
499 unsigned int count;
501 #ifdef CPU_ARM
502 count = pd->hist[priority];
503 if (--count == 0)
504 pd->mask &= ~(1 << priority);
505 pd->hist[priority] = count;
506 #else
507 if ((count = --pd->hist[priority]) == 0)
508 pd->mask &= ~(1 << priority);
509 #endif
511 return count;
514 /*---------------------------------------------------------------------------
515 * Remove from one category and add to another
516 *---------------------------------------------------------------------------
518 static inline void prio_move_entry(
519 struct priority_distribution *pd, int from, int to)
521 uint32_t mask = pd->mask;
523 #ifdef CPU_ARM
524 unsigned int count;
526 count = pd->hist[from];
527 if (--count == 0)
528 mask &= ~(1 << from);
529 pd->hist[from] = count;
531 count = pd->hist[to];
532 if (++count == 1)
533 mask |= 1 << to;
534 pd->hist[to] = count;
535 #else
536 if (--pd->hist[from] == 0)
537 mask &= ~(1 << from);
539 if (++pd->hist[to] == 1)
540 mask |= 1 << to;
541 #endif
543 pd->mask = mask;
546 /*---------------------------------------------------------------------------
547 * Change the priority and rtr entry for a running thread
548 *---------------------------------------------------------------------------
550 static inline void set_running_thread_priority(
551 struct thread_entry *thread, int priority)
553 const unsigned int core = IF_COP_CORE(thread->core);
554 RTR_LOCK(core);
555 rtr_move_entry(core, thread->priority, priority);
556 thread->priority = priority;
557 RTR_UNLOCK(core);
560 /*---------------------------------------------------------------------------
561 * Finds the highest priority thread in a list of threads. If the list is
562 * empty, the PRIORITY_IDLE is returned.
564 * It is possible to use the struct priority_distribution within an object
565 * instead of scanning the remaining threads in the list but as a compromise,
566 * the resulting per-object memory overhead is saved at a slight speed
567 * penalty under high contention.
568 *---------------------------------------------------------------------------
570 static int find_highest_priority_in_list_l(
571 struct thread_entry * const thread)
573 if (LIKELY(thread != NULL))
575 /* Go though list until the ending up at the initial thread */
576 int highest_priority = thread->priority;
577 struct thread_entry *curr = thread;
581 int priority = curr->priority;
583 if (priority < highest_priority)
584 highest_priority = priority;
586 curr = curr->l.next;
588 while (curr != thread);
590 return highest_priority;
593 return PRIORITY_IDLE;
596 /*---------------------------------------------------------------------------
597 * Register priority with blocking system and bubble it down the chain if
598 * any until we reach the end or something is already equal or higher.
600 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
601 * targets but that same action also guarantees a circular block anyway and
602 * those are prevented, right? :-)
603 *---------------------------------------------------------------------------
605 static struct thread_entry *
606 blocker_inherit_priority(struct thread_entry *current)
608 const int priority = current->priority;
609 struct blocker *bl = current->blocker;
610 struct thread_entry * const tstart = current;
611 struct thread_entry *bl_t = bl->thread;
613 /* Blocker cannot change since the object protection is held */
614 LOCK_THREAD(bl_t);
616 for (;;)
618 struct thread_entry *next;
619 int bl_pr = bl->priority;
621 if (priority >= bl_pr)
622 break; /* Object priority already high enough */
624 bl->priority = priority;
626 /* Add this one */
627 prio_add_entry(&bl_t->pdist, priority);
629 if (bl_pr < PRIORITY_IDLE)
631 /* Not first waiter - subtract old one */
632 prio_subtract_entry(&bl_t->pdist, bl_pr);
635 if (priority >= bl_t->priority)
636 break; /* Thread priority high enough */
638 if (bl_t->state == STATE_RUNNING)
640 /* Blocking thread is a running thread therefore there are no
641 * further blockers. Change the "run queue" on which it
642 * resides. */
643 set_running_thread_priority(bl_t, priority);
644 break;
647 bl_t->priority = priority;
649 /* If blocking thread has a blocker, apply transitive inheritance */
650 bl = bl_t->blocker;
652 if (bl == NULL)
653 break; /* End of chain or object doesn't support inheritance */
655 next = bl->thread;
657 if (UNLIKELY(next == tstart))
658 break; /* Full-circle - deadlock! */
660 UNLOCK_THREAD(current);
662 #if NUM_CORES > 1
663 for (;;)
665 LOCK_THREAD(next);
667 /* Blocker could change - retest condition */
668 if (LIKELY(bl->thread == next))
669 break;
671 UNLOCK_THREAD(next);
672 next = bl->thread;
674 #endif
675 current = bl_t;
676 bl_t = next;
679 UNLOCK_THREAD(bl_t);
681 return current;
684 /*---------------------------------------------------------------------------
685 * Readjust priorities when waking a thread blocked waiting for another
686 * in essence "releasing" the thread's effect on the object owner. Can be
687 * performed from any context.
688 *---------------------------------------------------------------------------
690 struct thread_entry *
691 wakeup_priority_protocol_release(struct thread_entry *thread)
693 const int priority = thread->priority;
694 struct blocker *bl = thread->blocker;
695 struct thread_entry * const tstart = thread;
696 struct thread_entry *bl_t = bl->thread;
698 /* Blocker cannot change since object will be locked */
699 LOCK_THREAD(bl_t);
701 thread->blocker = NULL; /* Thread not blocked */
703 for (;;)
705 struct thread_entry *next;
706 int bl_pr = bl->priority;
708 if (priority > bl_pr)
709 break; /* Object priority higher */
711 next = *thread->bqp;
713 if (next == NULL)
715 /* No more threads in queue */
716 prio_subtract_entry(&bl_t->pdist, bl_pr);
717 bl->priority = PRIORITY_IDLE;
719 else
721 /* Check list for highest remaining priority */
722 int queue_pr = find_highest_priority_in_list_l(next);
724 if (queue_pr == bl_pr)
725 break; /* Object priority not changing */
727 /* Change queue priority */
728 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
729 bl->priority = queue_pr;
732 if (bl_pr > bl_t->priority)
733 break; /* thread priority is higher */
735 bl_pr = find_first_set_bit(bl_t->pdist.mask);
737 if (bl_pr == bl_t->priority)
738 break; /* Thread priority not changing */
740 if (bl_t->state == STATE_RUNNING)
742 /* No further blockers */
743 set_running_thread_priority(bl_t, bl_pr);
744 break;
747 bl_t->priority = bl_pr;
749 /* If blocking thread has a blocker, apply transitive inheritance */
750 bl = bl_t->blocker;
752 if (bl == NULL)
753 break; /* End of chain or object doesn't support inheritance */
755 next = bl->thread;
757 if (UNLIKELY(next == tstart))
758 break; /* Full-circle - deadlock! */
760 UNLOCK_THREAD(thread);
762 #if NUM_CORES > 1
763 for (;;)
765 LOCK_THREAD(next);
767 /* Blocker could change - retest condition */
768 if (LIKELY(bl->thread == next))
769 break;
771 UNLOCK_THREAD(next);
772 next = bl->thread;
774 #endif
775 thread = bl_t;
776 bl_t = next;
779 UNLOCK_THREAD(bl_t);
781 #if NUM_CORES > 1
782 if (UNLIKELY(thread != tstart))
784 /* Relock original if it changed */
785 LOCK_THREAD(tstart);
787 #endif
789 return cores[CURRENT_CORE].running;
792 /*---------------------------------------------------------------------------
793 * Transfer ownership to a thread waiting for an objects and transfer
794 * inherited priority boost from other waiters. This algorithm knows that
795 * blocking chains may only unblock from the very end.
797 * Only the owning thread itself may call this and so the assumption that
798 * it is the running thread is made.
799 *---------------------------------------------------------------------------
801 struct thread_entry *
802 wakeup_priority_protocol_transfer(struct thread_entry *thread)
804 /* Waking thread inherits priority boost from object owner */
805 struct blocker *bl = thread->blocker;
806 struct thread_entry *bl_t = bl->thread;
807 struct thread_entry *next;
808 int bl_pr;
810 THREAD_ASSERT(cores[CURRENT_CORE].running == bl_t,
811 "UPPT->wrong thread", cores[CURRENT_CORE].running);
813 LOCK_THREAD(bl_t);
815 bl_pr = bl->priority;
817 /* Remove the object's boost from the owning thread */
818 if (prio_subtract_entry(&bl_t->pdist, bl_pr) == 0 &&
819 bl_pr <= bl_t->priority)
821 /* No more threads at this priority are waiting and the old level is
822 * at least the thread level */
823 int priority = find_first_set_bit(bl_t->pdist.mask);
825 if (priority != bl_t->priority)
827 /* Adjust this thread's priority */
828 set_running_thread_priority(bl_t, priority);
832 next = *thread->bqp;
834 if (LIKELY(next == NULL))
836 /* Expected shortcut - no more waiters */
837 bl_pr = PRIORITY_IDLE;
839 else
841 if (thread->priority <= bl_pr)
843 /* Need to scan threads remaining in queue */
844 bl_pr = find_highest_priority_in_list_l(next);
847 if (prio_add_entry(&thread->pdist, bl_pr) == 1 &&
848 bl_pr < thread->priority)
850 /* Thread priority must be raised */
851 thread->priority = bl_pr;
855 bl->thread = thread; /* This thread pwns */
856 bl->priority = bl_pr; /* Save highest blocked priority */
857 thread->blocker = NULL; /* Thread not blocked */
859 UNLOCK_THREAD(bl_t);
861 return bl_t;
864 /*---------------------------------------------------------------------------
865 * No threads must be blocked waiting for this thread except for it to exit.
866 * The alternative is more elaborate cleanup and object registration code.
867 * Check this for risk of silent data corruption when objects with
868 * inheritable blocking are abandoned by the owner - not precise but may
869 * catch something.
870 *---------------------------------------------------------------------------
872 static void __attribute__((noinline)) check_for_obj_waiters(
873 const char *function, struct thread_entry *thread)
875 /* Only one bit in the mask should be set with a frequency on 1 which
876 * represents the thread's own base priority */
877 uint32_t mask = thread->pdist.mask;
878 if ((mask & (mask - 1)) != 0 ||
879 thread->pdist.hist[find_first_set_bit(mask)] > 1)
881 unsigned char name[32];
882 thread_get_name(name, 32, thread);
883 panicf("%s->%s with obj. waiters", function, name);
886 #endif /* HAVE_PRIORITY_SCHEDULING */
888 /*---------------------------------------------------------------------------
889 * Move a thread back to a running state on its core.
890 *---------------------------------------------------------------------------
892 static void core_schedule_wakeup(struct thread_entry *thread)
894 const unsigned int core = IF_COP_CORE(thread->core);
896 RTR_LOCK(core);
898 thread->state = STATE_RUNNING;
900 add_to_list_l(&cores[core].running, thread);
901 rtr_add_entry(core, thread->priority);
903 RTR_UNLOCK(core);
905 #if NUM_CORES > 1
906 if (core != CURRENT_CORE)
907 core_wake(core);
908 #endif
911 /*---------------------------------------------------------------------------
912 * Check the core's timeout list when at least one thread is due to wake.
913 * Filtering for the condition is done before making the call. Resets the
914 * tick when the next check will occur.
915 *---------------------------------------------------------------------------
917 void check_tmo_threads(void)
919 const unsigned int core = CURRENT_CORE;
920 const long tick = current_tick; /* snapshot the current tick */
921 long next_tmo_check = tick + 60*HZ; /* minimum duration: once/minute */
922 struct thread_entry *next = cores[core].timeout;
924 /* If there are no processes waiting for a timeout, just keep the check
925 tick from falling into the past. */
927 /* Break the loop once we have walked through the list of all
928 * sleeping processes or have removed them all. */
929 while (next != NULL)
931 /* Check sleeping threads. Allow interrupts between checks. */
932 enable_irq();
934 struct thread_entry *curr = next;
936 next = curr->tmo.next;
938 /* Lock thread slot against explicit wakeup */
939 disable_irq();
940 LOCK_THREAD(curr);
942 unsigned state = curr->state;
944 if (state < TIMEOUT_STATE_FIRST)
946 /* Cleanup threads no longer on a timeout but still on the
947 * list. */
948 remove_from_list_tmo(curr);
950 else if (LIKELY(TIME_BEFORE(tick, curr->tmo_tick)))
952 /* Timeout still pending - this will be the usual case */
953 if (TIME_BEFORE(curr->tmo_tick, next_tmo_check))
955 /* Earliest timeout found so far - move the next check up
956 to its time */
957 next_tmo_check = curr->tmo_tick;
960 else
962 /* Sleep timeout has been reached so bring the thread back to
963 * life again. */
964 if (state == STATE_BLOCKED_W_TMO)
966 #if NUM_CORES > 1
967 /* Lock the waiting thread's kernel object */
968 struct corelock *ocl = curr->obj_cl;
970 if (UNLIKELY(corelock_try_lock(ocl) == 0))
972 /* Need to retry in the correct order though the need is
973 * unlikely */
974 UNLOCK_THREAD(curr);
975 corelock_lock(ocl);
976 LOCK_THREAD(curr);
978 if (UNLIKELY(curr->state != STATE_BLOCKED_W_TMO))
980 /* Thread was woken or removed explicitely while slot
981 * was unlocked */
982 corelock_unlock(ocl);
983 remove_from_list_tmo(curr);
984 UNLOCK_THREAD(curr);
985 continue;
988 #endif /* NUM_CORES */
990 remove_from_list_l(curr->bqp, curr);
992 #ifdef HAVE_WAKEUP_EXT_CB
993 if (curr->wakeup_ext_cb != NULL)
994 curr->wakeup_ext_cb(curr);
995 #endif
997 #ifdef HAVE_PRIORITY_SCHEDULING
998 if (curr->blocker != NULL)
999 wakeup_priority_protocol_release(curr);
1000 #endif
1001 corelock_unlock(ocl);
1003 /* else state == STATE_SLEEPING */
1005 remove_from_list_tmo(curr);
1007 RTR_LOCK(core);
1009 curr->state = STATE_RUNNING;
1011 add_to_list_l(&cores[core].running, curr);
1012 rtr_add_entry(core, curr->priority);
1014 RTR_UNLOCK(core);
1017 UNLOCK_THREAD(curr);
1020 cores[core].next_tmo_check = next_tmo_check;
1023 /*---------------------------------------------------------------------------
1024 * Performs operations that must be done before blocking a thread but after
1025 * the state is saved.
1026 *---------------------------------------------------------------------------
1028 #if NUM_CORES > 1
1029 static inline void run_blocking_ops(
1030 unsigned int core, struct thread_entry *thread)
1032 struct thread_blk_ops *ops = &cores[core].blk_ops;
1033 const unsigned flags = ops->flags;
1035 if (LIKELY(flags == TBOP_CLEAR))
1036 return;
1038 switch (flags)
1040 case TBOP_SWITCH_CORE:
1041 core_switch_blk_op(core, thread);
1042 /* Fall-through */
1043 case TBOP_UNLOCK_CORELOCK:
1044 corelock_unlock(ops->cl_p);
1045 break;
1048 ops->flags = TBOP_CLEAR;
1050 #endif /* NUM_CORES > 1 */
1052 #ifdef RB_PROFILE
1053 void profile_thread(void)
1055 profstart(cores[CURRENT_CORE].running - threads);
1057 #endif
1059 /*---------------------------------------------------------------------------
1060 * Prepares a thread to block on an object's list and/or for a specified
1061 * duration - expects object and slot to be appropriately locked if needed
1062 * and interrupts to be masked.
1063 *---------------------------------------------------------------------------
1065 static inline void block_thread_on_l(struct thread_entry *thread,
1066 unsigned state)
1068 /* If inlined, unreachable branches will be pruned with no size penalty
1069 because state is passed as a constant parameter. */
1070 const unsigned int core = IF_COP_CORE(thread->core);
1072 /* Remove the thread from the list of running threads. */
1073 RTR_LOCK(core);
1074 remove_from_list_l(&cores[core].running, thread);
1075 rtr_subtract_entry(core, thread->priority);
1076 RTR_UNLOCK(core);
1078 /* Add a timeout to the block if not infinite */
1079 switch (state)
1081 case STATE_BLOCKED:
1082 case STATE_BLOCKED_W_TMO:
1083 /* Put the thread into a new list of inactive threads. */
1084 add_to_list_l(thread->bqp, thread);
1086 if (state == STATE_BLOCKED)
1087 break;
1089 /* Fall-through */
1090 case STATE_SLEEPING:
1091 /* If this thread times out sooner than any other thread, update
1092 next_tmo_check to its timeout */
1093 if (TIME_BEFORE(thread->tmo_tick, cores[core].next_tmo_check))
1095 cores[core].next_tmo_check = thread->tmo_tick;
1098 if (thread->tmo.prev == NULL)
1100 add_to_list_tmo(thread);
1102 /* else thread was never removed from list - just keep it there */
1103 break;
1106 /* Remember the the next thread about to block. */
1107 cores[core].block_task = thread;
1109 /* Report new state. */
1110 thread->state = state;
1113 /*---------------------------------------------------------------------------
1114 * Switch thread in round robin fashion for any given priority. Any thread
1115 * that removed itself from the running list first must specify itself in
1116 * the paramter.
1118 * INTERNAL: Intended for use by kernel and not for programs.
1119 *---------------------------------------------------------------------------
1121 void switch_thread(void)
1124 const unsigned int core = CURRENT_CORE;
1125 struct thread_entry *block = cores[core].block_task;
1126 struct thread_entry *thread = cores[core].running;
1128 /* Get context to save - next thread to run is unknown until all wakeups
1129 * are evaluated */
1130 if (block != NULL)
1132 cores[core].block_task = NULL;
1134 #if NUM_CORES > 1
1135 if (UNLIKELY(thread == block))
1137 /* This was the last thread running and another core woke us before
1138 * reaching here. Force next thread selection to give tmo threads or
1139 * other threads woken before this block a first chance. */
1140 block = NULL;
1142 else
1143 #endif
1145 /* Blocking task is the old one */
1146 thread = block;
1150 #ifdef RB_PROFILE
1151 profile_thread_stopped(thread->id & THREAD_ID_SLOT_MASK);
1152 #endif
1154 /* Begin task switching by saving our current context so that we can
1155 * restore the state of the current thread later to the point prior
1156 * to this call. */
1157 store_context(&thread->context);
1159 /* Check if the current thread stack is overflown */
1160 if (UNLIKELY(thread->stack[0] != DEADBEEF) && thread->stack_size > 0)
1161 thread_stkov(thread);
1163 #if NUM_CORES > 1
1164 /* Run any blocking operations requested before switching/sleeping */
1165 run_blocking_ops(core, thread);
1166 #endif
1168 #ifdef HAVE_PRIORITY_SCHEDULING
1169 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1170 /* Reset the value of thread's skip count */
1171 thread->skip_count = 0;
1172 #endif
1174 for (;;)
1176 /* If there are threads on a timeout and the earliest wakeup is due,
1177 * check the list and wake any threads that need to start running
1178 * again. */
1179 if (!TIME_BEFORE(current_tick, cores[core].next_tmo_check))
1181 check_tmo_threads();
1184 disable_irq();
1185 RTR_LOCK(core);
1187 thread = cores[core].running;
1189 if (UNLIKELY(thread == NULL))
1191 /* Enter sleep mode to reduce power usage - woken up on interrupt
1192 * or wakeup request from another core - expected to enable
1193 * interrupts. */
1194 RTR_UNLOCK(core);
1195 core_sleep(IF_COP(core));
1197 else
1199 #ifdef HAVE_PRIORITY_SCHEDULING
1200 /* Select the new task based on priorities and the last time a
1201 * process got CPU time relative to the highest priority runnable
1202 * task. */
1203 struct priority_distribution *pd = &cores[core].rtr;
1204 int max = find_first_set_bit(pd->mask);
1206 if (block == NULL)
1208 /* Not switching on a block, tentatively select next thread */
1209 thread = thread->l.next;
1212 for (;;)
1214 int priority = thread->priority;
1215 int diff;
1217 /* This ridiculously simple method of aging seems to work
1218 * suspiciously well. It does tend to reward CPU hogs (under
1219 * yielding) but that's generally not desirable at all. On
1220 * the plus side, it, relatively to other threads, penalizes
1221 * excess yielding which is good if some high priority thread
1222 * is performing no useful work such as polling for a device
1223 * to be ready. Of course, aging is only employed when higher
1224 * and lower priority threads are runnable. The highest
1225 * priority runnable thread(s) are never skipped unless a
1226 * lower-priority process has aged sufficiently. Priorities
1227 * of REALTIME class are run strictly according to priority
1228 * thus are not subject to switchout due to lower-priority
1229 * processes aging; they must give up the processor by going
1230 * off the run list. */
1231 if (LIKELY(priority <= max) ||
1232 IF_NO_SKIP_YIELD( thread->skip_count == -1 || )
1233 (priority > PRIORITY_REALTIME &&
1234 (diff = priority - max,
1235 ++thread->skip_count > diff*diff)))
1237 cores[core].running = thread;
1238 break;
1241 thread = thread->l.next;
1243 #else
1244 /* Without priority use a simple FCFS algorithm */
1245 if (block == NULL)
1247 /* Not switching on a block, select next thread */
1248 thread = thread->l.next;
1249 cores[core].running = thread;
1251 #endif /* HAVE_PRIORITY_SCHEDULING */
1253 RTR_UNLOCK(core);
1254 enable_irq();
1255 break;
1259 /* And finally give control to the next thread. */
1260 load_context(&thread->context);
1262 #ifdef RB_PROFILE
1263 profile_thread_started(thread->id & THREAD_ID_SLOT_MASK);
1264 #endif
1268 /*---------------------------------------------------------------------------
1269 * Sleeps a thread for at least a specified number of ticks with zero being
1270 * a wait until the next tick.
1272 * INTERNAL: Intended for use by kernel and not for programs.
1273 *---------------------------------------------------------------------------
1275 void sleep_thread(int ticks)
1277 struct thread_entry *current = cores[CURRENT_CORE].running;
1279 LOCK_THREAD(current);
1281 /* Set our timeout, remove from run list and join timeout list. */
1282 current->tmo_tick = current_tick + ticks + 1;
1283 block_thread_on_l(current, STATE_SLEEPING);
1285 UNLOCK_THREAD(current);
1288 /*---------------------------------------------------------------------------
1289 * Indefinitely block a thread on a blocking queue for explicit wakeup.
1291 * INTERNAL: Intended for use by kernel objects and not for programs.
1292 *---------------------------------------------------------------------------
1294 void block_thread(struct thread_entry *current)
1296 /* Set the state to blocked and take us off of the run queue until we
1297 * are explicitly woken */
1298 LOCK_THREAD(current);
1300 /* Set the list for explicit wakeup */
1301 block_thread_on_l(current, STATE_BLOCKED);
1303 #ifdef HAVE_PRIORITY_SCHEDULING
1304 if (current->blocker != NULL)
1306 /* Object supports PIP */
1307 current = blocker_inherit_priority(current);
1309 #endif
1311 UNLOCK_THREAD(current);
1314 /*---------------------------------------------------------------------------
1315 * Block a thread on a blocking queue for a specified time interval or until
1316 * explicitly woken - whichever happens first.
1318 * INTERNAL: Intended for use by kernel objects and not for programs.
1319 *---------------------------------------------------------------------------
1321 void block_thread_w_tmo(struct thread_entry *current, int timeout)
1323 /* Get the entry for the current running thread. */
1324 LOCK_THREAD(current);
1326 /* Set the state to blocked with the specified timeout */
1327 current->tmo_tick = current_tick + timeout;
1329 /* Set the list for explicit wakeup */
1330 block_thread_on_l(current, STATE_BLOCKED_W_TMO);
1332 #ifdef HAVE_PRIORITY_SCHEDULING
1333 if (current->blocker != NULL)
1335 /* Object supports PIP */
1336 current = blocker_inherit_priority(current);
1338 #endif
1340 UNLOCK_THREAD(current);
1343 /*---------------------------------------------------------------------------
1344 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
1345 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
1347 * This code should be considered a critical section by the caller meaning
1348 * that the object's corelock should be held.
1350 * INTERNAL: Intended for use by kernel objects and not for programs.
1351 *---------------------------------------------------------------------------
1353 unsigned int wakeup_thread(struct thread_entry **list)
1355 struct thread_entry *thread = *list;
1356 unsigned int result = THREAD_NONE;
1358 /* Check if there is a blocked thread at all. */
1359 if (thread == NULL)
1360 return result;
1362 LOCK_THREAD(thread);
1364 /* Determine thread's current state. */
1365 switch (thread->state)
1367 case STATE_BLOCKED:
1368 case STATE_BLOCKED_W_TMO:
1369 remove_from_list_l(list, thread);
1371 result = THREAD_OK;
1373 #ifdef HAVE_PRIORITY_SCHEDULING
1374 struct thread_entry *current;
1375 struct blocker *bl = thread->blocker;
1377 if (bl == NULL)
1379 /* No inheritance - just boost the thread by aging */
1380 IF_NO_SKIP_YIELD( if (thread->skip_count != -1) )
1381 thread->skip_count = thread->priority;
1382 current = cores[CURRENT_CORE].running;
1384 else
1386 /* Call the specified unblocking PIP */
1387 current = bl->wakeup_protocol(thread);
1390 if (current != NULL &&
1391 find_first_set_bit(cores[IF_COP_CORE(current->core)].rtr.mask)
1392 < current->priority)
1394 /* There is a thread ready to run of higher or same priority on
1395 * the same core as the current one; recommend a task switch.
1396 * Knowing if this is an interrupt call would be helpful here. */
1397 result |= THREAD_SWITCH;
1399 #endif /* HAVE_PRIORITY_SCHEDULING */
1401 core_schedule_wakeup(thread);
1402 break;
1404 /* Nothing to do. State is not blocked. */
1405 #if THREAD_EXTRA_CHECKS
1406 default:
1407 THREAD_PANICF("wakeup_thread->block invalid", thread);
1408 case STATE_RUNNING:
1409 case STATE_KILLED:
1410 break;
1411 #endif
1414 UNLOCK_THREAD(thread);
1415 return result;
1418 /*---------------------------------------------------------------------------
1419 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
1420 * from each operation or THREAD_NONE of nothing was awakened. Object owning
1421 * the queue must be locked first.
1423 * INTERNAL: Intended for use by kernel objects and not for programs.
1424 *---------------------------------------------------------------------------
1426 unsigned int thread_queue_wake(struct thread_entry **list)
1428 unsigned result = THREAD_NONE;
1430 for (;;)
1432 unsigned int rc = wakeup_thread(list);
1434 if (rc == THREAD_NONE)
1435 break; /* No more threads */
1437 result |= rc;
1440 return result;
1443 /*---------------------------------------------------------------------------
1444 * Assign the thread slot a new ID. Version is 1-255.
1445 *---------------------------------------------------------------------------
1447 static void new_thread_id(unsigned int slot_num,
1448 struct thread_entry *thread)
1450 unsigned int version =
1451 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
1452 & THREAD_ID_VERSION_MASK;
1454 /* If wrapped to 0, make it 1 */
1455 if (version == 0)
1456 version = 1u << THREAD_ID_VERSION_SHIFT;
1458 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
1461 /*---------------------------------------------------------------------------
1462 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
1463 * will be locked on multicore.
1464 *---------------------------------------------------------------------------
1466 static struct thread_entry * find_empty_thread_slot(void)
1468 /* Any slot could be on an interrupt-accessible list */
1469 IF_COP( int oldlevel = disable_irq_save(); )
1470 struct thread_entry *thread = NULL;
1471 int n;
1473 for (n = 0; n < MAXTHREADS; n++)
1475 /* Obtain current slot state - lock it on multicore */
1476 struct thread_entry *t = &threads[n];
1477 LOCK_THREAD(t);
1479 if (t->state == STATE_KILLED IF_COP( && t->name != THREAD_DESTRUCT ))
1481 /* Slot is empty - leave it locked and caller will unlock */
1482 thread = t;
1483 break;
1486 /* Finished examining slot - no longer busy - unlock on multicore */
1487 UNLOCK_THREAD(t);
1490 IF_COP( restore_irq(oldlevel); ) /* Reenable interrups - this slot is
1491 not accesible to them yet */
1492 return thread;
1495 /*---------------------------------------------------------------------------
1496 * Return the thread_entry pointer for a thread_id. Return the current
1497 * thread if the ID is 0 (alias for current).
1498 *---------------------------------------------------------------------------
1500 struct thread_entry * thread_id_entry(unsigned int thread_id)
1502 return (thread_id == THREAD_ID_CURRENT) ?
1503 cores[CURRENT_CORE].running :
1504 &threads[thread_id & THREAD_ID_SLOT_MASK];
1507 /*---------------------------------------------------------------------------
1508 * Place the current core in idle mode - woken up on interrupt or wake
1509 * request from another core.
1510 *---------------------------------------------------------------------------
1512 void core_idle(void)
1514 IF_COP( const unsigned int core = CURRENT_CORE; )
1515 disable_irq();
1516 core_sleep(IF_COP(core));
1519 /*---------------------------------------------------------------------------
1520 * Create a thread. If using a dual core architecture, specify which core to
1521 * start the thread on.
1523 * Return ID if context area could be allocated, else NULL.
1524 *---------------------------------------------------------------------------
1526 unsigned int create_thread(void (*function)(void),
1527 void* stack, size_t stack_size,
1528 unsigned flags, const char *name
1529 IF_PRIO(, int priority)
1530 IF_COP(, unsigned int core))
1532 unsigned int i;
1533 unsigned int stack_words;
1534 uintptr_t stackptr, stackend;
1535 struct thread_entry *thread;
1536 unsigned state;
1537 int oldlevel;
1539 thread = find_empty_thread_slot();
1540 if (thread == NULL)
1542 return 0;
1545 oldlevel = disable_irq_save();
1547 /* Munge the stack to make it easy to spot stack overflows */
1548 stackptr = ALIGN_UP((uintptr_t)stack, sizeof (uintptr_t));
1549 stackend = ALIGN_DOWN((uintptr_t)stack + stack_size, sizeof (uintptr_t));
1550 stack_size = stackend - stackptr;
1551 stack_words = stack_size / sizeof (uintptr_t);
1553 for (i = 0; i < stack_words; i++)
1555 ((uintptr_t *)stackptr)[i] = DEADBEEF;
1558 /* Store interesting information */
1559 thread->name = name;
1560 thread->stack = (uintptr_t *)stackptr;
1561 thread->stack_size = stack_size;
1562 thread->queue = NULL;
1563 #ifdef HAVE_WAKEUP_EXT_CB
1564 thread->wakeup_ext_cb = NULL;
1565 #endif
1566 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1567 thread->cpu_boost = 0;
1568 #endif
1569 #ifdef HAVE_PRIORITY_SCHEDULING
1570 memset(&thread->pdist, 0, sizeof(thread->pdist));
1571 thread->blocker = NULL;
1572 thread->base_priority = priority;
1573 thread->priority = priority;
1574 thread->skip_count = priority;
1575 prio_add_entry(&thread->pdist, priority);
1576 #endif
1578 #ifdef HAVE_IO_PRIORITY
1579 /* Default to high (foreground) priority */
1580 thread->io_priority = IO_PRIORITY_IMMEDIATE;
1581 #endif
1583 #if NUM_CORES > 1
1584 thread->core = core;
1586 /* Writeback stack munging or anything else before starting */
1587 if (core != CURRENT_CORE)
1589 cpucache_flush();
1591 #endif
1593 /* Thread is not on any timeout list but be a bit paranoid */
1594 thread->tmo.prev = NULL;
1596 state = (flags & CREATE_THREAD_FROZEN) ?
1597 STATE_FROZEN : STATE_RUNNING;
1599 thread->context.sp = (typeof (thread->context.sp))stackend;
1601 /* Load the thread's context structure with needed startup information */
1602 THREAD_STARTUP_INIT(core, thread, function);
1604 thread->state = state;
1605 i = thread->id; /* Snapshot while locked */
1607 if (state == STATE_RUNNING)
1608 core_schedule_wakeup(thread);
1610 UNLOCK_THREAD(thread);
1611 restore_irq(oldlevel);
1613 return i;
1616 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1617 /*---------------------------------------------------------------------------
1618 * Change the boost state of a thread boosting or unboosting the CPU
1619 * as required.
1620 *---------------------------------------------------------------------------
1622 static inline void boost_thread(struct thread_entry *thread, bool boost)
1624 if ((thread->cpu_boost != 0) != boost)
1626 thread->cpu_boost = boost;
1627 cpu_boost(boost);
1631 void trigger_cpu_boost(void)
1633 struct thread_entry *current = cores[CURRENT_CORE].running;
1634 boost_thread(current, true);
1637 void cancel_cpu_boost(void)
1639 struct thread_entry *current = cores[CURRENT_CORE].running;
1640 boost_thread(current, false);
1642 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
1644 /*---------------------------------------------------------------------------
1645 * Block the current thread until another thread terminates. A thread may
1646 * wait on itself to terminate which prevents it from running again and it
1647 * will need to be killed externally.
1648 * Parameter is the ID as returned from create_thread().
1649 *---------------------------------------------------------------------------
1651 void thread_wait(unsigned int thread_id)
1653 struct thread_entry *current = cores[CURRENT_CORE].running;
1654 struct thread_entry *thread = thread_id_entry(thread_id);
1656 /* Lock thread-as-waitable-object lock */
1657 corelock_lock(&thread->waiter_cl);
1659 /* Be sure it hasn't been killed yet */
1660 if (thread_id == THREAD_ID_CURRENT ||
1661 (thread->id == thread_id && thread->state != STATE_KILLED))
1663 IF_COP( current->obj_cl = &thread->waiter_cl; )
1664 current->bqp = &thread->queue;
1666 disable_irq();
1667 block_thread(current);
1669 corelock_unlock(&thread->waiter_cl);
1671 switch_thread();
1672 return;
1675 corelock_unlock(&thread->waiter_cl);
1678 /*---------------------------------------------------------------------------
1679 * Exit the current thread. The Right Way to Do Things (TM).
1680 *---------------------------------------------------------------------------
1682 /* This is done to foil optimizations that may require the current stack,
1683 * such as optimizing subexpressions that put variables on the stack that
1684 * get used after switching stacks. */
1685 #if NUM_CORES > 1
1686 /* Called by ASM stub */
1687 static void thread_final_exit_do(struct thread_entry *current)
1688 #else
1689 /* No special procedure is required before calling */
1690 static inline void thread_final_exit(struct thread_entry *current)
1691 #endif
1693 /* At this point, this thread isn't using resources allocated for
1694 * execution except the slot itself. */
1696 /* Signal this thread */
1697 thread_queue_wake(&current->queue);
1698 corelock_unlock(&current->waiter_cl);
1699 switch_thread();
1700 /* This should never and must never be reached - if it is, the
1701 * state is corrupted */
1702 THREAD_PANICF("thread_exit->K:*R", current);
1703 while (1);
1706 void thread_exit(void)
1708 register struct thread_entry * current = cores[CURRENT_CORE].running;
1710 /* Cancel CPU boost if any */
1711 cancel_cpu_boost();
1713 disable_irq();
1715 corelock_lock(&current->waiter_cl);
1716 LOCK_THREAD(current);
1718 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
1719 if (current->name == THREAD_DESTRUCT)
1721 /* Thread being killed - become a waiter */
1722 unsigned int id = current->id;
1723 UNLOCK_THREAD(current);
1724 corelock_unlock(&current->waiter_cl);
1725 thread_wait(id);
1726 THREAD_PANICF("thread_exit->WK:*R", current);
1728 #endif
1730 #ifdef HAVE_PRIORITY_SCHEDULING
1731 check_for_obj_waiters("thread_exit", current);
1732 #endif
1734 if (current->tmo.prev != NULL)
1736 /* Cancel pending timeout list removal */
1737 remove_from_list_tmo(current);
1740 /* Switch tasks and never return */
1741 block_thread_on_l(current, STATE_KILLED);
1743 /* Slot must be unusable until thread is really gone */
1744 UNLOCK_THREAD_AT_TASK_SWITCH(current);
1746 /* Update ID for this slot */
1747 new_thread_id(current->id, current);
1748 current->name = NULL;
1750 /* Do final cleanup and remove the thread */
1751 thread_final_exit(current);
1754 #ifdef ALLOW_REMOVE_THREAD
1755 /*---------------------------------------------------------------------------
1756 * Remove a thread from the scheduler. Not The Right Way to Do Things in
1757 * normal programs.
1759 * Parameter is the ID as returned from create_thread().
1761 * Use with care on threads that are not under careful control as this may
1762 * leave various objects in an undefined state.
1763 *---------------------------------------------------------------------------
1765 void remove_thread(unsigned int thread_id)
1767 #if NUM_CORES > 1
1768 /* core is not constant here because of core switching */
1769 unsigned int core = CURRENT_CORE;
1770 unsigned int old_core = NUM_CORES;
1771 struct corelock *ocl = NULL;
1772 #else
1773 const unsigned int core = CURRENT_CORE;
1774 #endif
1775 struct thread_entry *current = cores[core].running;
1776 struct thread_entry *thread = thread_id_entry(thread_id);
1778 unsigned state;
1779 int oldlevel;
1781 if (thread == current)
1782 thread_exit(); /* Current thread - do normal exit */
1784 oldlevel = disable_irq_save();
1786 corelock_lock(&thread->waiter_cl);
1787 LOCK_THREAD(thread);
1789 state = thread->state;
1791 if (thread->id != thread_id || state == STATE_KILLED)
1792 goto thread_killed;
1794 #if NUM_CORES > 1
1795 if (thread->name == THREAD_DESTRUCT)
1797 /* Thread being killed - become a waiter */
1798 UNLOCK_THREAD(thread);
1799 corelock_unlock(&thread->waiter_cl);
1800 restore_irq(oldlevel);
1801 thread_wait(thread_id);
1802 return;
1805 thread->name = THREAD_DESTRUCT; /* Slot can't be used for now */
1807 #ifdef HAVE_PRIORITY_SCHEDULING
1808 check_for_obj_waiters("remove_thread", thread);
1809 #endif
1811 if (thread->core != core)
1813 /* Switch cores and safely extract the thread there */
1814 /* Slot HAS to be unlocked or a deadlock could occur which means other
1815 * threads have to be guided into becoming thread waiters if they
1816 * attempt to remove it. */
1817 unsigned int new_core = thread->core;
1819 corelock_unlock(&thread->waiter_cl);
1821 UNLOCK_THREAD(thread);
1822 restore_irq(oldlevel);
1824 old_core = switch_core(new_core);
1826 oldlevel = disable_irq_save();
1828 corelock_lock(&thread->waiter_cl);
1829 LOCK_THREAD(thread);
1831 state = thread->state;
1832 core = new_core;
1833 /* Perform the extraction and switch ourselves back to the original
1834 processor */
1836 #endif /* NUM_CORES > 1 */
1838 if (thread->tmo.prev != NULL)
1840 /* Clean thread off the timeout list if a timeout check hasn't
1841 * run yet */
1842 remove_from_list_tmo(thread);
1845 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1846 /* Cancel CPU boost if any */
1847 boost_thread(thread, false);
1848 #endif
1850 IF_COP( retry_state: )
1852 switch (state)
1854 case STATE_RUNNING:
1855 RTR_LOCK(core);
1856 /* Remove thread from ready to run tasks */
1857 remove_from_list_l(&cores[core].running, thread);
1858 rtr_subtract_entry(core, thread->priority);
1859 RTR_UNLOCK(core);
1860 break;
1861 case STATE_BLOCKED:
1862 case STATE_BLOCKED_W_TMO:
1863 /* Remove thread from the queue it's blocked on - including its
1864 * own if waiting there */
1865 #if NUM_CORES > 1
1866 if (&thread->waiter_cl != thread->obj_cl)
1868 ocl = thread->obj_cl;
1870 if (UNLIKELY(corelock_try_lock(ocl) == 0))
1872 UNLOCK_THREAD(thread);
1873 corelock_lock(ocl);
1874 LOCK_THREAD(thread);
1876 if (UNLIKELY(thread->state != state))
1878 /* Something woke the thread */
1879 state = thread->state;
1880 corelock_unlock(ocl);
1881 goto retry_state;
1885 #endif
1886 remove_from_list_l(thread->bqp, thread);
1888 #ifdef HAVE_WAKEUP_EXT_CB
1889 if (thread->wakeup_ext_cb != NULL)
1890 thread->wakeup_ext_cb(thread);
1891 #endif
1893 #ifdef HAVE_PRIORITY_SCHEDULING
1894 if (thread->blocker != NULL)
1896 /* Remove thread's priority influence from its chain */
1897 wakeup_priority_protocol_release(thread);
1899 #endif
1901 #if NUM_CORES > 1
1902 if (ocl != NULL)
1903 corelock_unlock(ocl);
1904 #endif
1905 break;
1906 /* Otherwise thread is frozen and hasn't run yet */
1909 new_thread_id(thread_id, thread);
1910 thread->state = STATE_KILLED;
1912 /* If thread was waiting on itself, it will have been removed above.
1913 * The wrong order would result in waking the thread first and deadlocking
1914 * since the slot is already locked. */
1915 thread_queue_wake(&thread->queue);
1917 thread->name = NULL;
1919 thread_killed: /* Thread was already killed */
1920 /* Removal complete - safe to unlock and reenable interrupts */
1921 corelock_unlock(&thread->waiter_cl);
1922 UNLOCK_THREAD(thread);
1923 restore_irq(oldlevel);
1925 #if NUM_CORES > 1
1926 if (old_core < NUM_CORES)
1928 /* Did a removal on another processor's thread - switch back to
1929 native core */
1930 switch_core(old_core);
1932 #endif
1934 #endif /* ALLOW_REMOVE_THREAD */
1936 #ifdef HAVE_PRIORITY_SCHEDULING
1937 /*---------------------------------------------------------------------------
1938 * Sets the thread's relative base priority for the core it runs on. Any
1939 * needed inheritance changes also may happen.
1940 *---------------------------------------------------------------------------
1942 int thread_set_priority(unsigned int thread_id, int priority)
1944 int old_base_priority = -1;
1945 struct thread_entry *thread = thread_id_entry(thread_id);
1947 /* A little safety measure */
1948 if (priority < HIGHEST_PRIORITY || priority > LOWEST_PRIORITY)
1949 return -1;
1951 /* Thread could be on any list and therefore on an interrupt accessible
1952 one - disable interrupts */
1953 int oldlevel = disable_irq_save();
1955 LOCK_THREAD(thread);
1957 /* Make sure it's not killed */
1958 if (thread_id == THREAD_ID_CURRENT ||
1959 (thread->id == thread_id && thread->state != STATE_KILLED))
1961 int old_priority = thread->priority;
1963 old_base_priority = thread->base_priority;
1964 thread->base_priority = priority;
1966 prio_move_entry(&thread->pdist, old_base_priority, priority);
1967 priority = find_first_set_bit(thread->pdist.mask);
1969 if (old_priority == priority)
1971 /* No priority change - do nothing */
1973 else if (thread->state == STATE_RUNNING)
1975 /* This thread is running - change location on the run
1976 * queue. No transitive inheritance needed. */
1977 set_running_thread_priority(thread, priority);
1979 else
1981 thread->priority = priority;
1983 if (thread->blocker != NULL)
1985 /* Bubble new priority down the chain */
1986 struct blocker *bl = thread->blocker; /* Blocker struct */
1987 struct thread_entry *bl_t = bl->thread; /* Blocking thread */
1988 struct thread_entry * const tstart = thread; /* Initial thread */
1989 const int highest = MIN(priority, old_priority); /* Higher of new or old */
1991 for (;;)
1993 struct thread_entry *next; /* Next thread to check */
1994 int bl_pr; /* Highest blocked thread */
1995 int queue_pr; /* New highest blocked thread */
1996 #if NUM_CORES > 1
1997 /* Owner can change but thread cannot be dislodged - thread
1998 * may not be the first in the queue which allows other
1999 * threads ahead in the list to be given ownership during the
2000 * operation. If thread is next then the waker will have to
2001 * wait for us and the owner of the object will remain fixed.
2002 * If we successfully grab the owner -- which at some point
2003 * is guaranteed -- then the queue remains fixed until we
2004 * pass by. */
2005 for (;;)
2007 LOCK_THREAD(bl_t);
2009 /* Double-check the owner - retry if it changed */
2010 if (LIKELY(bl->thread == bl_t))
2011 break;
2013 UNLOCK_THREAD(bl_t);
2014 bl_t = bl->thread;
2016 #endif
2017 bl_pr = bl->priority;
2019 if (highest > bl_pr)
2020 break; /* Object priority won't change */
2022 /* This will include the thread being set */
2023 queue_pr = find_highest_priority_in_list_l(*thread->bqp);
2025 if (queue_pr == bl_pr)
2026 break; /* Object priority not changing */
2028 /* Update thread boost for this object */
2029 bl->priority = queue_pr;
2030 prio_move_entry(&bl_t->pdist, bl_pr, queue_pr);
2031 bl_pr = find_first_set_bit(bl_t->pdist.mask);
2033 if (bl_t->priority == bl_pr)
2034 break; /* Blocking thread priority not changing */
2036 if (bl_t->state == STATE_RUNNING)
2038 /* Thread not blocked - we're done */
2039 set_running_thread_priority(bl_t, bl_pr);
2040 break;
2043 bl_t->priority = bl_pr;
2044 bl = bl_t->blocker; /* Blocking thread has a blocker? */
2046 if (bl == NULL)
2047 break; /* End of chain */
2049 next = bl->thread;
2051 if (UNLIKELY(next == tstart))
2052 break; /* Full-circle */
2054 UNLOCK_THREAD(thread);
2056 thread = bl_t;
2057 bl_t = next;
2058 } /* for (;;) */
2060 UNLOCK_THREAD(bl_t);
2065 UNLOCK_THREAD(thread);
2067 restore_irq(oldlevel);
2069 return old_base_priority;
2072 /*---------------------------------------------------------------------------
2073 * Returns the current base priority for a thread.
2074 *---------------------------------------------------------------------------
2076 int thread_get_priority(unsigned int thread_id)
2078 struct thread_entry *thread = thread_id_entry(thread_id);
2079 int base_priority = thread->base_priority;
2081 /* Simply check without locking slot. It may or may not be valid by the
2082 * time the function returns anyway. If all tests pass, it is the
2083 * correct value for when it was valid. */
2084 if (thread_id != THREAD_ID_CURRENT &&
2085 (thread->id != thread_id || thread->state == STATE_KILLED))
2086 base_priority = -1;
2088 return base_priority;
2090 #endif /* HAVE_PRIORITY_SCHEDULING */
2092 #ifdef HAVE_IO_PRIORITY
2093 int thread_get_io_priority(unsigned int thread_id)
2095 struct thread_entry *thread = thread_id_entry(thread_id);
2096 return thread->io_priority;
2099 void thread_set_io_priority(unsigned int thread_id,int io_priority)
2101 struct thread_entry *thread = thread_id_entry(thread_id);
2102 thread->io_priority = io_priority;
2104 #endif
2106 /*---------------------------------------------------------------------------
2107 * Starts a frozen thread - similar semantics to wakeup_thread except that
2108 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2109 * virtue of the slot having a state of STATE_FROZEN.
2110 *---------------------------------------------------------------------------
2112 void thread_thaw(unsigned int thread_id)
2114 struct thread_entry *thread = thread_id_entry(thread_id);
2115 int oldlevel = disable_irq_save();
2117 LOCK_THREAD(thread);
2119 /* If thread is the current one, it cannot be frozen, therefore
2120 * there is no need to check that. */
2121 if (thread->id == thread_id && thread->state == STATE_FROZEN)
2122 core_schedule_wakeup(thread);
2124 UNLOCK_THREAD(thread);
2125 restore_irq(oldlevel);
2128 /*---------------------------------------------------------------------------
2129 * Return the ID of the currently executing thread.
2130 *---------------------------------------------------------------------------
2132 unsigned int thread_get_current(void)
2134 return cores[CURRENT_CORE].running->id;
2137 #if NUM_CORES > 1
2138 /*---------------------------------------------------------------------------
2139 * Switch the processor that the currently executing thread runs on.
2140 *---------------------------------------------------------------------------
2142 unsigned int switch_core(unsigned int new_core)
2144 const unsigned int core = CURRENT_CORE;
2145 struct thread_entry *current = cores[core].running;
2147 if (core == new_core)
2149 /* No change - just return same core */
2150 return core;
2153 int oldlevel = disable_irq_save();
2154 LOCK_THREAD(current);
2156 if (current->name == THREAD_DESTRUCT)
2158 /* Thread being killed - deactivate and let process complete */
2159 unsigned int id = current->id;
2160 UNLOCK_THREAD(current);
2161 restore_irq(oldlevel);
2162 thread_wait(id);
2163 /* Should never be reached */
2164 THREAD_PANICF("switch_core->D:*R", current);
2167 /* Get us off the running list for the current core */
2168 RTR_LOCK(core);
2169 remove_from_list_l(&cores[core].running, current);
2170 rtr_subtract_entry(core, current->priority);
2171 RTR_UNLOCK(core);
2173 /* Stash return value (old core) in a safe place */
2174 current->retval = core;
2176 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2177 * the other core will likely attempt a removal from the wrong list! */
2178 if (current->tmo.prev != NULL)
2180 remove_from_list_tmo(current);
2183 /* Change the core number for this thread slot */
2184 current->core = new_core;
2186 /* Do not use core_schedule_wakeup here since this will result in
2187 * the thread starting to run on the other core before being finished on
2188 * this one. Delay the list unlock to keep the other core stuck
2189 * until this thread is ready. */
2190 RTR_LOCK(new_core);
2192 rtr_add_entry(new_core, current->priority);
2193 add_to_list_l(&cores[new_core].running, current);
2195 /* Make a callback into device-specific code, unlock the wakeup list so
2196 * that execution may resume on the new core, unlock our slot and finally
2197 * restore the interrupt level */
2198 cores[core].blk_ops.flags = TBOP_SWITCH_CORE;
2199 cores[core].blk_ops.cl_p = &cores[new_core].rtr_cl;
2200 cores[core].block_task = current;
2202 UNLOCK_THREAD(current);
2204 /* Alert other core to activity */
2205 core_wake(new_core);
2207 /* Do the stack switching, cache_maintenence and switch_thread call -
2208 requires native code */
2209 switch_thread_core(core, current);
2211 /* Finally return the old core to caller */
2212 return current->retval;
2214 #endif /* NUM_CORES > 1 */
2216 /*---------------------------------------------------------------------------
2217 * Initialize threading API. This assumes interrupts are not yet enabled. On
2218 * multicore setups, no core is allowed to proceed until create_thread calls
2219 * are safe to perform.
2220 *---------------------------------------------------------------------------
2222 void init_threads(void)
2224 const unsigned int core = CURRENT_CORE;
2225 struct thread_entry *thread;
2227 if (core == CPU)
2229 /* Initialize core locks and IDs in all slots */
2230 int n;
2231 for (n = 0; n < MAXTHREADS; n++)
2233 thread = &threads[n];
2234 corelock_init(&thread->waiter_cl);
2235 corelock_init(&thread->slot_cl);
2236 thread->id = THREAD_ID_INIT(n);
2240 /* CPU will initialize first and then sleep */
2241 thread = find_empty_thread_slot();
2243 if (thread == NULL)
2245 /* WTF? There really must be a slot available at this stage.
2246 * This can fail if, for example, .bss isn't zero'ed out by the loader
2247 * or threads is in the wrong section. */
2248 THREAD_PANICF("init_threads->no slot", NULL);
2251 /* Initialize initially non-zero members of core */
2252 cores[core].next_tmo_check = current_tick; /* Something not in the past */
2254 /* Initialize initially non-zero members of slot */
2255 UNLOCK_THREAD(thread); /* No sync worries yet */
2256 thread->name = main_thread_name;
2257 thread->state = STATE_RUNNING;
2258 IF_COP( thread->core = core; )
2259 #ifdef HAVE_PRIORITY_SCHEDULING
2260 corelock_init(&cores[core].rtr_cl);
2261 thread->base_priority = PRIORITY_USER_INTERFACE;
2262 prio_add_entry(&thread->pdist, PRIORITY_USER_INTERFACE);
2263 thread->priority = PRIORITY_USER_INTERFACE;
2264 rtr_add_entry(core, PRIORITY_USER_INTERFACE);
2265 #endif
2267 add_to_list_l(&cores[core].running, thread);
2269 if (core == CPU)
2271 thread->stack = stackbegin;
2272 thread->stack_size = (uintptr_t)stackend - (uintptr_t)stackbegin;
2273 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2274 /* Wait for other processors to finish their inits since create_thread
2275 * isn't safe to call until the kernel inits are done. The first
2276 * threads created in the system must of course be created by CPU.
2277 * Another possible approach is to initialize all cores and slots
2278 * for each core by CPU, let the remainder proceed in parallel and
2279 * signal CPU when all are finished. */
2280 core_thread_init(CPU);
2282 else
2284 /* Initial stack is the idle stack */
2285 thread->stack = idle_stacks[core];
2286 thread->stack_size = IDLE_STACK_SIZE;
2287 /* After last processor completes, it should signal all others to
2288 * proceed or may signal the next and call thread_exit(). The last one
2289 * to finish will signal CPU. */
2290 core_thread_init(core);
2291 /* Other cores do not have a main thread - go idle inside switch_thread
2292 * until a thread can run on the core. */
2293 thread_exit();
2294 #endif /* NUM_CORES */
2298 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
2299 #if NUM_CORES == 1
2300 static inline int stack_usage(uintptr_t *stackptr, size_t stack_size)
2301 #else
2302 static int stack_usage(uintptr_t *stackptr, size_t stack_size)
2303 #endif
2305 unsigned int stack_words = stack_size / sizeof (uintptr_t);
2306 unsigned int i;
2307 int usage = 0;
2309 for (i = 0; i < stack_words; i++)
2311 if (stackptr[i] != DEADBEEF)
2313 usage = ((stack_words - i) * 100) / stack_words;
2314 break;
2318 return usage;
2321 /*---------------------------------------------------------------------------
2322 * Returns the maximum percentage of stack a thread ever used while running.
2323 * NOTE: Some large buffer allocations that don't use enough the buffer to
2324 * overwrite stackptr[0] will not be seen.
2325 *---------------------------------------------------------------------------
2327 int thread_stack_usage(const struct thread_entry *thread)
2329 if (LIKELY(thread->stack_size > 0))
2330 return stack_usage(thread->stack, thread->stack_size);
2331 return 0;
2334 #if NUM_CORES > 1
2335 /*---------------------------------------------------------------------------
2336 * Returns the maximum percentage of the core's idle stack ever used during
2337 * runtime.
2338 *---------------------------------------------------------------------------
2340 int idle_stack_usage(unsigned int core)
2342 return stack_usage(idle_stacks[core], IDLE_STACK_SIZE);
2344 #endif
2346 /*---------------------------------------------------------------------------
2347 * Fills in the buffer with the specified thread's name. If the name is NULL,
2348 * empty, or the thread is in destruct state a formatted ID is written
2349 * instead.
2350 *---------------------------------------------------------------------------
2352 void thread_get_name(char *buffer, int size,
2353 struct thread_entry *thread)
2355 if (size <= 0)
2356 return;
2358 *buffer = '\0';
2360 if (thread)
2362 /* Display thread name if one or ID if none */
2363 const char *name = thread->name;
2364 const char *fmt = "%s";
2365 if (name == NULL IF_COP(|| name == THREAD_DESTRUCT) || *name == '\0')
2367 name = (const char *)thread;
2368 fmt = "%08lX";
2370 snprintf(buffer, size, fmt, name);