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 #include "gcc_extensions.h"
35 /****************************************************************************
37 * See notes below on implementing processor-specific portions! *
38 ***************************************************************************/
40 /* Define THREAD_EXTRA_CHECKS as 1 to enable additional state checks */
42 #define THREAD_EXTRA_CHECKS 1 /* Always 1 for DEBUG */
44 #define THREAD_EXTRA_CHECKS 0
48 * General locking order to guarantee progress. Order must be observed but
49 * all stages are not nescessarily obligatory. Going from 1) to 3) is
53 * This is first because of the likelyhood of having an interrupt occur that
54 * also accesses one of the objects farther down the list. Any non-blocking
55 * synchronization done may already have a lock on something during normal
56 * execution and if an interrupt handler running on the same processor as
57 * the one that has the resource locked were to attempt to access the
58 * resource, the interrupt handler would wait forever waiting for an unlock
59 * that will never happen. There is no danger if the interrupt occurs on
60 * a different processor because the one that has the lock will eventually
61 * unlock and the other processor's handler may proceed at that time. Not
62 * nescessary when the resource in question is definitely not available to
66 * 1) May be needed beforehand if the kernel object allows dual-use such as
67 * event queues. The kernel object must have a scheme to protect itself from
68 * access by another processor and is responsible for serializing the calls
69 * to block_thread(_w_tmo) and wakeup_thread both to themselves and to each
70 * other. Objects' queues are also protected here.
73 * This locks access to the thread's slot such that its state cannot be
74 * altered by another processor when a state change is in progress such as
75 * when it is in the process of going on a blocked list. An attempt to wake
76 * a thread while it is still blocking will likely desync its state with
77 * the other resources used for that state.
80 * These lists are specific to a particular processor core and are accessible
81 * by all processor cores and interrupt handlers. The running (rtr) list is
82 * the prime example where a thread may be added by any means.
85 /*---------------------------------------------------------------------------
86 * Processor specific: core_sleep/core_wake/misc. notes
89 * FIQ is not dealt with by the scheduler code and is simply restored if it
90 * must by masked for some reason - because threading modifies a register
91 * that FIQ may also modify and there's no way to accomplish it atomically.
92 * s3c2440 is such a case.
94 * Audio interrupts are generally treated at a higher priority than others
95 * usage of scheduler code with interrupts higher than HIGHEST_IRQ_LEVEL
96 * are not in general safe. Special cases may be constructed on a per-
97 * source basis and blocking operations are not available.
99 * core_sleep procedure to implement for any CPU to ensure an asychronous
100 * wakup never results in requiring a wait until the next tick (up to
101 * 10000uS!). May require assembly and careful instruction ordering.
103 * 1) On multicore, stay awake if directed to do so by another. If so, goto
105 * 2) If processor requires, atomically reenable interrupts and perform step
107 * 3) Sleep the CPU core. If wakeup itself enables interrupts (stop #0x2000
108 * on Coldfire) goto step 5.
109 * 4) Enable interrupts.
112 * core_wake and multprocessor notes for sleep/wake coordination:
113 * If possible, to wake up another processor, the forcing of an interrupt on
114 * the woken core by the waker core is the easiest way to ensure a non-
115 * delayed wake and immediate execution of any woken threads. If that isn't
116 * available then some careful non-blocking synchonization is needed (as on
117 * PP targets at the moment).
118 *---------------------------------------------------------------------------
121 /* Cast to the the machine pointer size, whose size could be < 4 or > 32
123 #define DEADBEEF ((uintptr_t)0xdeadbeefdeadbeefull)
124 static struct core_entry cores
[NUM_CORES
] IBSS_ATTR
;
125 struct thread_entry threads
[MAXTHREADS
] IBSS_ATTR
;
127 static const char main_thread_name
[] = "main";
128 #if (CONFIG_PLATFORM & PLATFORM_NATIVE)
129 extern uintptr_t stackbegin
[];
130 extern uintptr_t stackend
[];
132 extern uintptr_t *stackbegin
;
133 extern uintptr_t *stackend
;
136 static inline void core_sleep(IF_COP_VOID(unsigned int core
))
137 __attribute__((always_inline
));
139 void check_tmo_threads(void)
140 __attribute__((noinline
));
142 static inline void block_thread_on_l(struct thread_entry
*thread
, unsigned state
)
143 __attribute__((always_inline
));
145 static void add_to_list_tmo(struct thread_entry
*thread
)
146 __attribute__((noinline
));
148 static void core_schedule_wakeup(struct thread_entry
*thread
)
149 __attribute__((noinline
));
152 static inline void run_blocking_ops(
153 unsigned int core
, struct thread_entry
*thread
)
154 __attribute__((always_inline
));
157 static void thread_stkov(struct thread_entry
*thread
)
158 __attribute__((noinline
));
160 static inline void store_context(void* addr
)
161 __attribute__((always_inline
));
163 static inline void load_context(const void* addr
)
164 __attribute__((always_inline
));
167 static void thread_final_exit_do(struct thread_entry
*current
)
168 __attribute__((noinline
)) NORETURN_ATTR USED_ATTR
;
170 static inline void thread_final_exit(struct thread_entry
*current
)
171 __attribute__((always_inline
)) NORETURN_ATTR
;
174 void switch_thread(void)
175 __attribute__((noinline
));
177 /****************************************************************************
178 * Processor/OS-specific section - include necessary core support
181 #if defined(HAVE_WIN32_FIBER_THREADS)
182 #include "thread-win32.c"
183 #elif defined(HAVE_SIGALTSTACK_THREADS)
184 #include "thread-unix.c"
185 #elif defined(CPU_ARM)
186 #include "thread-arm.c"
188 #include "thread-pp.c"
190 #elif defined(CPU_COLDFIRE)
191 #include "thread-coldfire.c"
192 #elif CONFIG_CPU == SH7034
193 #include "thread-sh.c"
194 #elif defined(CPU_MIPS) && CPU_MIPS == 32
195 #include "thread-mips32.c"
197 /* Wouldn't compile anyway */
198 #error Processor not implemented.
199 #endif /* CONFIG_CPU == */
201 #ifndef IF_NO_SKIP_YIELD
202 #define IF_NO_SKIP_YIELD(...)
206 * End Processor-specific section
207 ***************************************************************************/
209 #if THREAD_EXTRA_CHECKS
210 static void thread_panicf(const char *msg
, struct thread_entry
*thread
)
212 IF_COP( const unsigned int core
= thread
->core
; )
213 static char name
[32];
214 thread_get_name(name
, 32, thread
);
215 panicf ("%s %s" IF_COP(" (%d)"), msg
, name
IF_COP(, core
));
217 static void thread_stkov(struct thread_entry
*thread
)
219 thread_panicf("Stkov", thread
);
221 #define THREAD_PANICF(msg, thread) \
222 thread_panicf(msg, thread)
223 #define THREAD_ASSERT(exp, msg, thread) \
224 ({ if (!({ exp; })) thread_panicf((msg), (thread)); })
226 static void thread_stkov(struct thread_entry
*thread
)
228 IF_COP( const unsigned int core
= thread
->core
; )
229 static char name
[32];
230 thread_get_name(name
, 32, thread
);
231 panicf("Stkov %s" IF_COP(" (%d)"), name
IF_COP(, core
));
233 #define THREAD_PANICF(msg, thread)
234 #define THREAD_ASSERT(exp, msg, thread)
235 #endif /* THREAD_EXTRA_CHECKS */
239 #define LOCK_THREAD(thread) \
240 ({ corelock_lock(&(thread)->slot_cl); })
241 #define TRY_LOCK_THREAD(thread) \
242 ({ corelock_try_lock(&(thread)->slot_cl); })
243 #define UNLOCK_THREAD(thread) \
244 ({ corelock_unlock(&(thread)->slot_cl); })
245 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
246 ({ unsigned int _core = (thread)->core; \
247 cores[_core].blk_ops.flags |= TBOP_UNLOCK_CORELOCK; \
248 cores[_core].blk_ops.cl_p = &(thread)->slot_cl; })
250 #define LOCK_THREAD(thread) \
252 #define TRY_LOCK_THREAD(thread) \
254 #define UNLOCK_THREAD(thread) \
256 #define UNLOCK_THREAD_AT_TASK_SWITCH(thread) \
261 #define RTR_LOCK(core) \
262 ({ corelock_lock(&cores[core].rtr_cl); })
263 #define RTR_UNLOCK(core) \
264 ({ corelock_unlock(&cores[core].rtr_cl); })
266 #ifdef HAVE_PRIORITY_SCHEDULING
267 #define rtr_add_entry(core, priority) \
268 prio_add_entry(&cores[core].rtr, (priority))
270 #define rtr_subtract_entry(core, priority) \
271 prio_subtract_entry(&cores[core].rtr, (priority))
273 #define rtr_move_entry(core, from, to) \
274 prio_move_entry(&cores[core].rtr, (from), (to))
276 #define rtr_add_entry(core, priority)
277 #define rtr_add_entry_inl(core, priority)
278 #define rtr_subtract_entry(core, priority)
279 #define rtr_subtract_entry_inl(core, priotity)
280 #define rtr_move_entry(core, from, to)
281 #define rtr_move_entry_inl(core, from, to)
284 /*---------------------------------------------------------------------------
285 * Thread list structure - circular:
286 * +------------------------------+
288 * +--+---+<-+---+<-+---+<-+---+<-+
289 * Head->| T | | T | | T | | T |
290 * +->+---+->+---+->+---+->+---+--+
292 * +------------------------------+
293 *---------------------------------------------------------------------------
296 /*---------------------------------------------------------------------------
297 * Adds a thread to a list of threads using "insert last". Uses the "l"
299 *---------------------------------------------------------------------------
301 static void add_to_list_l(struct thread_entry
**list
,
302 struct thread_entry
*thread
)
304 struct thread_entry
*l
= *list
;
308 /* Insert into unoccupied list */
309 thread
->l
.prev
= thread
;
310 thread
->l
.next
= thread
;
316 thread
->l
.prev
= l
->l
.prev
;
318 l
->l
.prev
->l
.next
= thread
;
322 /*---------------------------------------------------------------------------
323 * Removes a thread from a list of threads. Uses the "l" links.
324 *---------------------------------------------------------------------------
326 static void remove_from_list_l(struct thread_entry
**list
,
327 struct thread_entry
*thread
)
329 struct thread_entry
*prev
, *next
;
331 next
= thread
->l
.next
;
342 /* List becomes next item */
346 prev
= thread
->l
.prev
;
348 /* Fix links to jump over the removed entry. */
353 /*---------------------------------------------------------------------------
354 * Timeout list structure - circular reverse (to make "remove item" O(1)),
355 * NULL-terminated forward (to ease the far more common forward traversal):
356 * +------------------------------+
358 * +--+---+<-+---+<-+---+<-+---+<-+
359 * Head->| T | | T | | T | | T |
360 * +---+->+---+->+---+->+---+-X
361 *---------------------------------------------------------------------------
364 /*---------------------------------------------------------------------------
365 * Add a thread from the core's timout list by linking the pointers in its
367 *---------------------------------------------------------------------------
369 static void add_to_list_tmo(struct thread_entry
*thread
)
371 struct thread_entry
*tmo
= cores
[IF_COP_CORE(thread
->core
)].timeout
;
372 THREAD_ASSERT(thread
->tmo
.prev
== NULL
,
373 "add_to_list_tmo->already listed", thread
);
375 thread
->tmo
.next
= NULL
;
379 /* Insert into unoccupied list */
380 thread
->tmo
.prev
= thread
;
381 cores
[IF_COP_CORE(thread
->core
)].timeout
= thread
;
386 thread
->tmo
.prev
= tmo
->tmo
.prev
;
387 tmo
->tmo
.prev
->tmo
.next
= thread
;
388 tmo
->tmo
.prev
= thread
;
391 /*---------------------------------------------------------------------------
392 * Remove a thread from the core's timout list by unlinking the pointers in
393 * its tmo structure. Sets thread->tmo.prev to NULL to indicate the timeout
395 *---------------------------------------------------------------------------
397 static void remove_from_list_tmo(struct thread_entry
*thread
)
399 struct thread_entry
**list
= &cores
[IF_COP_CORE(thread
->core
)].timeout
;
400 struct thread_entry
*prev
= thread
->tmo
.prev
;
401 struct thread_entry
*next
= thread
->tmo
.next
;
403 THREAD_ASSERT(prev
!= NULL
, "remove_from_list_tmo->not listed", thread
);
406 next
->tmo
.prev
= prev
;
410 /* List becomes next item and empty if next == NULL */
412 /* Mark as unlisted */
413 thread
->tmo
.prev
= NULL
;
418 (*list
)->tmo
.prev
= prev
;
419 prev
->tmo
.next
= next
;
420 /* Mark as unlisted */
421 thread
->tmo
.prev
= NULL
;
426 #ifdef HAVE_PRIORITY_SCHEDULING
427 /*---------------------------------------------------------------------------
428 * Priority distribution structure (one category for each possible priority):
430 * +----+----+----+ ... +-----+
431 * hist: | F0 | F1 | F2 | | F31 |
432 * +----+----+----+ ... +-----+
433 * mask: | b0 | b1 | b2 | | b31 |
434 * +----+----+----+ ... +-----+
436 * F = count of threads at priority category n (frequency)
437 * b = bitmask of non-zero priority categories (occupancy)
443 *---------------------------------------------------------------------------
444 * Basic priority inheritance priotocol (PIP):
446 * Mn = mutex n, Tn = thread n
448 * A lower priority thread inherits the priority of the highest priority
449 * thread blocked waiting for it to complete an action (such as release a
450 * mutex or respond to a message via queue_send):
454 * T1 owns M1, T2 is waiting for M1 to realease M1. If T2 has a higher
455 * priority than T1 then T1 inherits the priority of T2.
461 * Situation is like 1) but T2 and T3 are both queued waiting for M1 and so
462 * T1 inherits the higher of T2 and T3.
464 * 3) T3->M2->T2->M1->T1
466 * T1 owns M1, T2 owns M2. If T3 has a higher priority than both T1 and T2,
467 * then T1 inherits the priority of T3 through T2.
469 * Blocking chains can grow arbitrarily complex (though it's best that they
470 * not form at all very often :) and build-up from these units.
471 *---------------------------------------------------------------------------
474 /*---------------------------------------------------------------------------
475 * Increment frequency at category "priority"
476 *---------------------------------------------------------------------------
478 static inline unsigned int prio_add_entry(
479 struct priority_distribution
*pd
, int priority
)
482 /* Enough size/instruction count difference for ARM makes it worth it to
483 * use different code (192 bytes for ARM). Only thing better is ASM. */
485 count
= pd
->hist
[priority
];
487 pd
->mask
|= 1 << priority
;
488 pd
->hist
[priority
] = count
;
489 #else /* This one's better for Coldfire */
490 if ((count
= ++pd
->hist
[priority
]) == 1)
491 pd
->mask
|= 1 << priority
;
497 /*---------------------------------------------------------------------------
498 * Decrement frequency at category "priority"
499 *---------------------------------------------------------------------------
501 static inline unsigned int prio_subtract_entry(
502 struct priority_distribution
*pd
, int priority
)
507 count
= pd
->hist
[priority
];
509 pd
->mask
&= ~(1 << priority
);
510 pd
->hist
[priority
] = count
;
512 if ((count
= --pd
->hist
[priority
]) == 0)
513 pd
->mask
&= ~(1 << priority
);
519 /*---------------------------------------------------------------------------
520 * Remove from one category and add to another
521 *---------------------------------------------------------------------------
523 static inline void prio_move_entry(
524 struct priority_distribution
*pd
, int from
, int to
)
526 uint32_t mask
= pd
->mask
;
531 count
= pd
->hist
[from
];
533 mask
&= ~(1 << from
);
534 pd
->hist
[from
] = count
;
536 count
= pd
->hist
[to
];
539 pd
->hist
[to
] = count
;
541 if (--pd
->hist
[from
] == 0)
542 mask
&= ~(1 << from
);
544 if (++pd
->hist
[to
] == 1)
551 /*---------------------------------------------------------------------------
552 * Change the priority and rtr entry for a running thread
553 *---------------------------------------------------------------------------
555 static inline void set_running_thread_priority(
556 struct thread_entry
*thread
, int priority
)
558 const unsigned int core
= IF_COP_CORE(thread
->core
);
560 rtr_move_entry(core
, thread
->priority
, priority
);
561 thread
->priority
= priority
;
565 /*---------------------------------------------------------------------------
566 * Finds the highest priority thread in a list of threads. If the list is
567 * empty, the PRIORITY_IDLE is returned.
569 * It is possible to use the struct priority_distribution within an object
570 * instead of scanning the remaining threads in the list but as a compromise,
571 * the resulting per-object memory overhead is saved at a slight speed
572 * penalty under high contention.
573 *---------------------------------------------------------------------------
575 static int find_highest_priority_in_list_l(
576 struct thread_entry
* const thread
)
578 if (LIKELY(thread
!= NULL
))
580 /* Go though list until the ending up at the initial thread */
581 int highest_priority
= thread
->priority
;
582 struct thread_entry
*curr
= thread
;
586 int priority
= curr
->priority
;
588 if (priority
< highest_priority
)
589 highest_priority
= priority
;
593 while (curr
!= thread
);
595 return highest_priority
;
598 return PRIORITY_IDLE
;
601 /*---------------------------------------------------------------------------
602 * Register priority with blocking system and bubble it down the chain if
603 * any until we reach the end or something is already equal or higher.
605 * NOTE: A simultaneous circular wait could spin deadlock on multiprocessor
606 * targets but that same action also guarantees a circular block anyway and
607 * those are prevented, right? :-)
608 *---------------------------------------------------------------------------
610 static struct thread_entry
*
611 blocker_inherit_priority(struct thread_entry
*current
)
613 const int priority
= current
->priority
;
614 struct blocker
*bl
= current
->blocker
;
615 struct thread_entry
* const tstart
= current
;
616 struct thread_entry
*bl_t
= bl
->thread
;
618 /* Blocker cannot change since the object protection is held */
623 struct thread_entry
*next
;
624 int bl_pr
= bl
->priority
;
626 if (priority
>= bl_pr
)
627 break; /* Object priority already high enough */
629 bl
->priority
= priority
;
632 prio_add_entry(&bl_t
->pdist
, priority
);
634 if (bl_pr
< PRIORITY_IDLE
)
636 /* Not first waiter - subtract old one */
637 prio_subtract_entry(&bl_t
->pdist
, bl_pr
);
640 if (priority
>= bl_t
->priority
)
641 break; /* Thread priority high enough */
643 if (bl_t
->state
== STATE_RUNNING
)
645 /* Blocking thread is a running thread therefore there are no
646 * further blockers. Change the "run queue" on which it
648 set_running_thread_priority(bl_t
, priority
);
652 bl_t
->priority
= priority
;
654 /* If blocking thread has a blocker, apply transitive inheritance */
658 break; /* End of chain or object doesn't support inheritance */
662 if (UNLIKELY(next
== tstart
))
663 break; /* Full-circle - deadlock! */
665 UNLOCK_THREAD(current
);
672 /* Blocker could change - retest condition */
673 if (LIKELY(bl
->thread
== next
))
689 /*---------------------------------------------------------------------------
690 * Readjust priorities when waking a thread blocked waiting for another
691 * in essence "releasing" the thread's effect on the object owner. Can be
692 * performed from any context.
693 *---------------------------------------------------------------------------
695 struct thread_entry
*
696 wakeup_priority_protocol_release(struct thread_entry
*thread
)
698 const int priority
= thread
->priority
;
699 struct blocker
*bl
= thread
->blocker
;
700 struct thread_entry
* const tstart
= thread
;
701 struct thread_entry
*bl_t
= bl
->thread
;
703 /* Blocker cannot change since object will be locked */
706 thread
->blocker
= NULL
; /* Thread not blocked */
710 struct thread_entry
*next
;
711 int bl_pr
= bl
->priority
;
713 if (priority
> bl_pr
)
714 break; /* Object priority higher */
720 /* No more threads in queue */
721 prio_subtract_entry(&bl_t
->pdist
, bl_pr
);
722 bl
->priority
= PRIORITY_IDLE
;
726 /* Check list for highest remaining priority */
727 int queue_pr
= find_highest_priority_in_list_l(next
);
729 if (queue_pr
== bl_pr
)
730 break; /* Object priority not changing */
732 /* Change queue priority */
733 prio_move_entry(&bl_t
->pdist
, bl_pr
, queue_pr
);
734 bl
->priority
= queue_pr
;
737 if (bl_pr
> bl_t
->priority
)
738 break; /* thread priority is higher */
740 bl_pr
= find_first_set_bit(bl_t
->pdist
.mask
);
742 if (bl_pr
== bl_t
->priority
)
743 break; /* Thread priority not changing */
745 if (bl_t
->state
== STATE_RUNNING
)
747 /* No further blockers */
748 set_running_thread_priority(bl_t
, bl_pr
);
752 bl_t
->priority
= bl_pr
;
754 /* If blocking thread has a blocker, apply transitive inheritance */
758 break; /* End of chain or object doesn't support inheritance */
762 if (UNLIKELY(next
== tstart
))
763 break; /* Full-circle - deadlock! */
765 UNLOCK_THREAD(thread
);
772 /* Blocker could change - retest condition */
773 if (LIKELY(bl
->thread
== next
))
787 if (UNLIKELY(thread
!= tstart
))
789 /* Relock original if it changed */
794 return cores
[CURRENT_CORE
].running
;
797 /*---------------------------------------------------------------------------
798 * Transfer ownership to a thread waiting for an objects and transfer
799 * inherited priority boost from other waiters. This algorithm knows that
800 * blocking chains may only unblock from the very end.
802 * Only the owning thread itself may call this and so the assumption that
803 * it is the running thread is made.
804 *---------------------------------------------------------------------------
806 struct thread_entry
*
807 wakeup_priority_protocol_transfer(struct thread_entry
*thread
)
809 /* Waking thread inherits priority boost from object owner */
810 struct blocker
*bl
= thread
->blocker
;
811 struct thread_entry
*bl_t
= bl
->thread
;
812 struct thread_entry
*next
;
815 THREAD_ASSERT(cores
[CURRENT_CORE
].running
== bl_t
,
816 "UPPT->wrong thread", cores
[CURRENT_CORE
].running
);
820 bl_pr
= bl
->priority
;
822 /* Remove the object's boost from the owning thread */
823 if (prio_subtract_entry(&bl_t
->pdist
, bl_pr
) == 0 &&
824 bl_pr
<= bl_t
->priority
)
826 /* No more threads at this priority are waiting and the old level is
827 * at least the thread level */
828 int priority
= find_first_set_bit(bl_t
->pdist
.mask
);
830 if (priority
!= bl_t
->priority
)
832 /* Adjust this thread's priority */
833 set_running_thread_priority(bl_t
, priority
);
839 if (LIKELY(next
== NULL
))
841 /* Expected shortcut - no more waiters */
842 bl_pr
= PRIORITY_IDLE
;
846 if (thread
->priority
<= bl_pr
)
848 /* Need to scan threads remaining in queue */
849 bl_pr
= find_highest_priority_in_list_l(next
);
852 if (prio_add_entry(&thread
->pdist
, bl_pr
) == 1 &&
853 bl_pr
< thread
->priority
)
855 /* Thread priority must be raised */
856 thread
->priority
= bl_pr
;
860 bl
->thread
= thread
; /* This thread pwns */
861 bl
->priority
= bl_pr
; /* Save highest blocked priority */
862 thread
->blocker
= NULL
; /* Thread not blocked */
869 /*---------------------------------------------------------------------------
870 * No threads must be blocked waiting for this thread except for it to exit.
871 * The alternative is more elaborate cleanup and object registration code.
872 * Check this for risk of silent data corruption when objects with
873 * inheritable blocking are abandoned by the owner - not precise but may
875 *---------------------------------------------------------------------------
877 static void __attribute__((noinline
)) check_for_obj_waiters(
878 const char *function
, struct thread_entry
*thread
)
880 /* Only one bit in the mask should be set with a frequency on 1 which
881 * represents the thread's own base priority */
882 uint32_t mask
= thread
->pdist
.mask
;
883 if ((mask
& (mask
- 1)) != 0 ||
884 thread
->pdist
.hist
[find_first_set_bit(mask
)] > 1)
886 unsigned char name
[32];
887 thread_get_name(name
, 32, thread
);
888 panicf("%s->%s with obj. waiters", function
, name
);
891 #endif /* HAVE_PRIORITY_SCHEDULING */
893 /*---------------------------------------------------------------------------
894 * Move a thread back to a running state on its core.
895 *---------------------------------------------------------------------------
897 static void core_schedule_wakeup(struct thread_entry
*thread
)
899 const unsigned int core
= IF_COP_CORE(thread
->core
);
903 thread
->state
= STATE_RUNNING
;
905 add_to_list_l(&cores
[core
].running
, thread
);
906 rtr_add_entry(core
, thread
->priority
);
911 if (core
!= CURRENT_CORE
)
916 /*---------------------------------------------------------------------------
917 * Check the core's timeout list when at least one thread is due to wake.
918 * Filtering for the condition is done before making the call. Resets the
919 * tick when the next check will occur.
920 *---------------------------------------------------------------------------
922 void check_tmo_threads(void)
924 const unsigned int core
= CURRENT_CORE
;
925 const long tick
= current_tick
; /* snapshot the current tick */
926 long next_tmo_check
= tick
+ 60*HZ
; /* minimum duration: once/minute */
927 struct thread_entry
*next
= cores
[core
].timeout
;
929 /* If there are no processes waiting for a timeout, just keep the check
930 tick from falling into the past. */
932 /* Break the loop once we have walked through the list of all
933 * sleeping processes or have removed them all. */
936 /* Check sleeping threads. Allow interrupts between checks. */
939 struct thread_entry
*curr
= next
;
941 next
= curr
->tmo
.next
;
943 /* Lock thread slot against explicit wakeup */
947 unsigned state
= curr
->state
;
949 if (state
< TIMEOUT_STATE_FIRST
)
951 /* Cleanup threads no longer on a timeout but still on the
953 remove_from_list_tmo(curr
);
955 else if (LIKELY(TIME_BEFORE(tick
, curr
->tmo_tick
)))
957 /* Timeout still pending - this will be the usual case */
958 if (TIME_BEFORE(curr
->tmo_tick
, next_tmo_check
))
960 /* Earliest timeout found so far - move the next check up
962 next_tmo_check
= curr
->tmo_tick
;
967 /* Sleep timeout has been reached so bring the thread back to
969 if (state
== STATE_BLOCKED_W_TMO
)
971 #ifdef HAVE_CORELOCK_OBJECT
972 /* Lock the waiting thread's kernel object */
973 struct corelock
*ocl
= curr
->obj_cl
;
975 if (UNLIKELY(corelock_try_lock(ocl
) == 0))
977 /* Need to retry in the correct order though the need is
983 if (UNLIKELY(curr
->state
!= STATE_BLOCKED_W_TMO
))
985 /* Thread was woken or removed explicitely while slot
987 corelock_unlock(ocl
);
988 remove_from_list_tmo(curr
);
993 #endif /* NUM_CORES */
995 remove_from_list_l(curr
->bqp
, curr
);
997 #ifdef HAVE_WAKEUP_EXT_CB
998 if (curr
->wakeup_ext_cb
!= NULL
)
999 curr
->wakeup_ext_cb(curr
);
1002 #ifdef HAVE_PRIORITY_SCHEDULING
1003 if (curr
->blocker
!= NULL
)
1004 wakeup_priority_protocol_release(curr
);
1006 corelock_unlock(ocl
);
1008 /* else state == STATE_SLEEPING */
1010 remove_from_list_tmo(curr
);
1014 curr
->state
= STATE_RUNNING
;
1016 add_to_list_l(&cores
[core
].running
, curr
);
1017 rtr_add_entry(core
, curr
->priority
);
1022 UNLOCK_THREAD(curr
);
1025 cores
[core
].next_tmo_check
= next_tmo_check
;
1028 /*---------------------------------------------------------------------------
1029 * Performs operations that must be done before blocking a thread but after
1030 * the state is saved.
1031 *---------------------------------------------------------------------------
1034 static inline void run_blocking_ops(
1035 unsigned int core
, struct thread_entry
*thread
)
1037 struct thread_blk_ops
*ops
= &cores
[core
].blk_ops
;
1038 const unsigned flags
= ops
->flags
;
1040 if (LIKELY(flags
== TBOP_CLEAR
))
1045 case TBOP_SWITCH_CORE
:
1046 core_switch_blk_op(core
, thread
);
1048 case TBOP_UNLOCK_CORELOCK
:
1049 corelock_unlock(ops
->cl_p
);
1053 ops
->flags
= TBOP_CLEAR
;
1055 #endif /* NUM_CORES > 1 */
1058 void profile_thread(void)
1060 profstart(cores
[CURRENT_CORE
].running
- threads
);
1064 /*---------------------------------------------------------------------------
1065 * Prepares a thread to block on an object's list and/or for a specified
1066 * duration - expects object and slot to be appropriately locked if needed
1067 * and interrupts to be masked.
1068 *---------------------------------------------------------------------------
1070 static inline void block_thread_on_l(struct thread_entry
*thread
,
1073 /* If inlined, unreachable branches will be pruned with no size penalty
1074 because state is passed as a constant parameter. */
1075 const unsigned int core
= IF_COP_CORE(thread
->core
);
1077 /* Remove the thread from the list of running threads. */
1079 remove_from_list_l(&cores
[core
].running
, thread
);
1080 rtr_subtract_entry(core
, thread
->priority
);
1083 /* Add a timeout to the block if not infinite */
1087 case STATE_BLOCKED_W_TMO
:
1088 /* Put the thread into a new list of inactive threads. */
1089 add_to_list_l(thread
->bqp
, thread
);
1091 if (state
== STATE_BLOCKED
)
1095 case STATE_SLEEPING
:
1096 /* If this thread times out sooner than any other thread, update
1097 next_tmo_check to its timeout */
1098 if (TIME_BEFORE(thread
->tmo_tick
, cores
[core
].next_tmo_check
))
1100 cores
[core
].next_tmo_check
= thread
->tmo_tick
;
1103 if (thread
->tmo
.prev
== NULL
)
1105 add_to_list_tmo(thread
);
1107 /* else thread was never removed from list - just keep it there */
1111 /* Remember the the next thread about to block. */
1112 cores
[core
].block_task
= thread
;
1114 /* Report new state. */
1115 thread
->state
= state
;
1118 /*---------------------------------------------------------------------------
1119 * Switch thread in round robin fashion for any given priority. Any thread
1120 * that removed itself from the running list first must specify itself in
1123 * INTERNAL: Intended for use by kernel and not for programs.
1124 *---------------------------------------------------------------------------
1126 void switch_thread(void)
1129 const unsigned int core
= CURRENT_CORE
;
1130 struct thread_entry
*block
= cores
[core
].block_task
;
1131 struct thread_entry
*thread
= cores
[core
].running
;
1133 /* Get context to save - next thread to run is unknown until all wakeups
1137 cores
[core
].block_task
= NULL
;
1140 if (UNLIKELY(thread
== block
))
1142 /* This was the last thread running and another core woke us before
1143 * reaching here. Force next thread selection to give tmo threads or
1144 * other threads woken before this block a first chance. */
1150 /* Blocking task is the old one */
1157 _profile_thread_stopped(thread
->id
& THREAD_ID_SLOT_MASK
);
1159 profile_thread_stopped(thread
->id
& THREAD_ID_SLOT_MASK
);
1163 /* Begin task switching by saving our current context so that we can
1164 * restore the state of the current thread later to the point prior
1166 store_context(&thread
->context
);
1168 /* Check if the current thread stack is overflown */
1169 if (UNLIKELY(thread
->stack
[0] != DEADBEEF
) && thread
->stack_size
> 0)
1170 thread_stkov(thread
);
1173 /* Run any blocking operations requested before switching/sleeping */
1174 run_blocking_ops(core
, thread
);
1177 #ifdef HAVE_PRIORITY_SCHEDULING
1178 IF_NO_SKIP_YIELD( if (thread
->skip_count
!= -1) )
1179 /* Reset the value of thread's skip count */
1180 thread
->skip_count
= 0;
1185 /* If there are threads on a timeout and the earliest wakeup is due,
1186 * check the list and wake any threads that need to start running
1188 if (!TIME_BEFORE(current_tick
, cores
[core
].next_tmo_check
))
1190 check_tmo_threads();
1196 thread
= cores
[core
].running
;
1198 if (UNLIKELY(thread
== NULL
))
1200 /* Enter sleep mode to reduce power usage - woken up on interrupt
1201 * or wakeup request from another core - expected to enable
1204 core_sleep(IF_COP(core
));
1208 #ifdef HAVE_PRIORITY_SCHEDULING
1209 /* Select the new task based on priorities and the last time a
1210 * process got CPU time relative to the highest priority runnable
1212 struct priority_distribution
*pd
= &cores
[core
].rtr
;
1213 int max
= find_first_set_bit(pd
->mask
);
1217 /* Not switching on a block, tentatively select next thread */
1218 thread
= thread
->l
.next
;
1223 int priority
= thread
->priority
;
1226 /* This ridiculously simple method of aging seems to work
1227 * suspiciously well. It does tend to reward CPU hogs (under
1228 * yielding) but that's generally not desirable at all. On
1229 * the plus side, it, relatively to other threads, penalizes
1230 * excess yielding which is good if some high priority thread
1231 * is performing no useful work such as polling for a device
1232 * to be ready. Of course, aging is only employed when higher
1233 * and lower priority threads are runnable. The highest
1234 * priority runnable thread(s) are never skipped unless a
1235 * lower-priority process has aged sufficiently. Priorities
1236 * of REALTIME class are run strictly according to priority
1237 * thus are not subject to switchout due to lower-priority
1238 * processes aging; they must give up the processor by going
1239 * off the run list. */
1240 if (LIKELY(priority
<= max
) ||
1241 IF_NO_SKIP_YIELD( thread
->skip_count
== -1 || )
1242 (priority
> PRIORITY_REALTIME
&&
1243 (diff
= priority
- max
,
1244 ++thread
->skip_count
> diff
*diff
)))
1246 cores
[core
].running
= thread
;
1250 thread
= thread
->l
.next
;
1253 /* Without priority use a simple FCFS algorithm */
1256 /* Not switching on a block, select next thread */
1257 thread
= thread
->l
.next
;
1258 cores
[core
].running
= thread
;
1260 #endif /* HAVE_PRIORITY_SCHEDULING */
1268 /* And finally give control to the next thread. */
1269 load_context(&thread
->context
);
1272 profile_thread_started(thread
->id
& THREAD_ID_SLOT_MASK
);
1277 /*---------------------------------------------------------------------------
1278 * Sleeps a thread for at least a specified number of ticks with zero being
1279 * a wait until the next tick.
1281 * INTERNAL: Intended for use by kernel and not for programs.
1282 *---------------------------------------------------------------------------
1284 void sleep_thread(int ticks
)
1286 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
1288 LOCK_THREAD(current
);
1290 /* Set our timeout, remove from run list and join timeout list. */
1291 current
->tmo_tick
= current_tick
+ ticks
+ 1;
1292 block_thread_on_l(current
, STATE_SLEEPING
);
1294 UNLOCK_THREAD(current
);
1297 /*---------------------------------------------------------------------------
1298 * Indefinitely block a thread on a blocking queue for explicit wakeup.
1300 * INTERNAL: Intended for use by kernel objects and not for programs.
1301 *---------------------------------------------------------------------------
1303 void block_thread(struct thread_entry
*current
)
1305 /* Set the state to blocked and take us off of the run queue until we
1306 * are explicitly woken */
1307 LOCK_THREAD(current
);
1309 /* Set the list for explicit wakeup */
1310 block_thread_on_l(current
, STATE_BLOCKED
);
1312 #ifdef HAVE_PRIORITY_SCHEDULING
1313 if (current
->blocker
!= NULL
)
1315 /* Object supports PIP */
1316 current
= blocker_inherit_priority(current
);
1320 UNLOCK_THREAD(current
);
1323 /*---------------------------------------------------------------------------
1324 * Block a thread on a blocking queue for a specified time interval or until
1325 * explicitly woken - whichever happens first.
1327 * INTERNAL: Intended for use by kernel objects and not for programs.
1328 *---------------------------------------------------------------------------
1330 void block_thread_w_tmo(struct thread_entry
*current
, int timeout
)
1332 /* Get the entry for the current running thread. */
1333 LOCK_THREAD(current
);
1335 /* Set the state to blocked with the specified timeout */
1336 current
->tmo_tick
= current_tick
+ timeout
;
1338 /* Set the list for explicit wakeup */
1339 block_thread_on_l(current
, STATE_BLOCKED_W_TMO
);
1341 #ifdef HAVE_PRIORITY_SCHEDULING
1342 if (current
->blocker
!= NULL
)
1344 /* Object supports PIP */
1345 current
= blocker_inherit_priority(current
);
1349 UNLOCK_THREAD(current
);
1352 /*---------------------------------------------------------------------------
1353 * Explicitly wakeup a thread on a blocking queue. Only effects threads of
1354 * STATE_BLOCKED and STATE_BLOCKED_W_TMO.
1356 * This code should be considered a critical section by the caller meaning
1357 * that the object's corelock should be held.
1359 * INTERNAL: Intended for use by kernel objects and not for programs.
1360 *---------------------------------------------------------------------------
1362 unsigned int wakeup_thread(struct thread_entry
**list
)
1364 struct thread_entry
*thread
= *list
;
1365 unsigned int result
= THREAD_NONE
;
1367 /* Check if there is a blocked thread at all. */
1371 LOCK_THREAD(thread
);
1373 /* Determine thread's current state. */
1374 switch (thread
->state
)
1377 case STATE_BLOCKED_W_TMO
:
1378 remove_from_list_l(list
, thread
);
1382 #ifdef HAVE_PRIORITY_SCHEDULING
1383 struct thread_entry
*current
;
1384 struct blocker
*bl
= thread
->blocker
;
1388 /* No inheritance - just boost the thread by aging */
1389 IF_NO_SKIP_YIELD( if (thread
->skip_count
!= -1) )
1390 thread
->skip_count
= thread
->priority
;
1391 current
= cores
[CURRENT_CORE
].running
;
1395 /* Call the specified unblocking PIP */
1396 current
= bl
->wakeup_protocol(thread
);
1399 if (current
!= NULL
&&
1400 find_first_set_bit(cores
[IF_COP_CORE(current
->core
)].rtr
.mask
)
1401 < current
->priority
)
1403 /* There is a thread ready to run of higher or same priority on
1404 * the same core as the current one; recommend a task switch.
1405 * Knowing if this is an interrupt call would be helpful here. */
1406 result
|= THREAD_SWITCH
;
1408 #endif /* HAVE_PRIORITY_SCHEDULING */
1410 core_schedule_wakeup(thread
);
1413 /* Nothing to do. State is not blocked. */
1414 #if THREAD_EXTRA_CHECKS
1416 THREAD_PANICF("wakeup_thread->block invalid", thread
);
1423 UNLOCK_THREAD(thread
);
1427 /*---------------------------------------------------------------------------
1428 * Wakeup an entire queue of threads - returns bitwise-or of return bitmask
1429 * from each operation or THREAD_NONE of nothing was awakened. Object owning
1430 * the queue must be locked first.
1432 * INTERNAL: Intended for use by kernel objects and not for programs.
1433 *---------------------------------------------------------------------------
1435 unsigned int thread_queue_wake(struct thread_entry
**list
)
1437 unsigned result
= THREAD_NONE
;
1441 unsigned int rc
= wakeup_thread(list
);
1443 if (rc
== THREAD_NONE
)
1444 break; /* No more threads */
1452 /*---------------------------------------------------------------------------
1453 * Assign the thread slot a new ID. Version is 1-255.
1454 *---------------------------------------------------------------------------
1456 static void new_thread_id(unsigned int slot_num
,
1457 struct thread_entry
*thread
)
1459 unsigned int version
=
1460 (thread
->id
+ (1u << THREAD_ID_VERSION_SHIFT
))
1461 & THREAD_ID_VERSION_MASK
;
1463 /* If wrapped to 0, make it 1 */
1465 version
= 1u << THREAD_ID_VERSION_SHIFT
;
1467 thread
->id
= version
| (slot_num
& THREAD_ID_SLOT_MASK
);
1470 /*---------------------------------------------------------------------------
1471 * Find an empty thread slot or MAXTHREADS if none found. The slot returned
1472 * will be locked on multicore.
1473 *---------------------------------------------------------------------------
1475 static struct thread_entry
* find_empty_thread_slot(void)
1477 /* Any slot could be on an interrupt-accessible list */
1478 IF_COP( int oldlevel
= disable_irq_save(); )
1479 struct thread_entry
*thread
= NULL
;
1482 for (n
= 0; n
< MAXTHREADS
; n
++)
1484 /* Obtain current slot state - lock it on multicore */
1485 struct thread_entry
*t
= &threads
[n
];
1488 if (t
->state
== STATE_KILLED
IF_COP( && t
->name
!= THREAD_DESTRUCT
))
1490 /* Slot is empty - leave it locked and caller will unlock */
1495 /* Finished examining slot - no longer busy - unlock on multicore */
1499 IF_COP( restore_irq(oldlevel
); ) /* Reenable interrups - this slot is
1500 not accesible to them yet */
1504 /*---------------------------------------------------------------------------
1505 * Return the thread_entry pointer for a thread_id. Return the current
1506 * thread if the ID is (unsigned int)-1 (alias for current).
1507 *---------------------------------------------------------------------------
1509 struct thread_entry
* thread_id_entry(unsigned int thread_id
)
1511 return &threads
[thread_id
& THREAD_ID_SLOT_MASK
];
1514 /*---------------------------------------------------------------------------
1515 * Return the thread id of the calling thread
1516 * --------------------------------------------------------------------------
1518 unsigned int thread_self(void)
1520 return cores
[CURRENT_CORE
].running
->id
;
1523 /*---------------------------------------------------------------------------
1524 * Return the thread entry of the calling thread.
1526 * INTERNAL: Intended for use by kernel and not for programs.
1527 *---------------------------------------------------------------------------
1529 struct thread_entry
* thread_self_entry(void)
1531 return cores
[CURRENT_CORE
].running
;
1534 /*---------------------------------------------------------------------------
1535 * Place the current core in idle mode - woken up on interrupt or wake
1536 * request from another core.
1537 *---------------------------------------------------------------------------
1539 void core_idle(void)
1541 IF_COP( const unsigned int core
= CURRENT_CORE
; )
1543 core_sleep(IF_COP(core
));
1546 /*---------------------------------------------------------------------------
1547 * Create a thread. If using a dual core architecture, specify which core to
1548 * start the thread on.
1550 * Return ID if context area could be allocated, else NULL.
1551 *---------------------------------------------------------------------------
1553 unsigned int create_thread(void (*function
)(void),
1554 void* stack
, size_t stack_size
,
1555 unsigned flags
, const char *name
1556 IF_PRIO(, int priority
)
1557 IF_COP(, unsigned int core
))
1560 unsigned int stack_words
;
1561 uintptr_t stackptr
, stackend
;
1562 struct thread_entry
*thread
;
1566 thread
= find_empty_thread_slot();
1572 oldlevel
= disable_irq_save();
1574 /* Munge the stack to make it easy to spot stack overflows */
1575 stackptr
= ALIGN_UP((uintptr_t)stack
, sizeof (uintptr_t));
1576 stackend
= ALIGN_DOWN((uintptr_t)stack
+ stack_size
, sizeof (uintptr_t));
1577 stack_size
= stackend
- stackptr
;
1578 stack_words
= stack_size
/ sizeof (uintptr_t);
1580 for (i
= 0; i
< stack_words
; i
++)
1582 ((uintptr_t *)stackptr
)[i
] = DEADBEEF
;
1585 /* Store interesting information */
1586 thread
->name
= name
;
1587 thread
->stack
= (uintptr_t *)stackptr
;
1588 thread
->stack_size
= stack_size
;
1589 thread
->queue
= NULL
;
1590 #ifdef HAVE_WAKEUP_EXT_CB
1591 thread
->wakeup_ext_cb
= NULL
;
1593 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1594 thread
->cpu_boost
= 0;
1596 #ifdef HAVE_PRIORITY_SCHEDULING
1597 memset(&thread
->pdist
, 0, sizeof(thread
->pdist
));
1598 thread
->blocker
= NULL
;
1599 thread
->base_priority
= priority
;
1600 thread
->priority
= priority
;
1601 thread
->skip_count
= priority
;
1602 prio_add_entry(&thread
->pdist
, priority
);
1605 #ifdef HAVE_IO_PRIORITY
1606 /* Default to high (foreground) priority */
1607 thread
->io_priority
= IO_PRIORITY_IMMEDIATE
;
1611 thread
->core
= core
;
1613 /* Writeback stack munging or anything else before starting */
1614 if (core
!= CURRENT_CORE
)
1616 commit_discard_idcache();
1620 /* Thread is not on any timeout list but be a bit paranoid */
1621 thread
->tmo
.prev
= NULL
;
1623 state
= (flags
& CREATE_THREAD_FROZEN
) ?
1624 STATE_FROZEN
: STATE_RUNNING
;
1626 thread
->context
.sp
= (typeof (thread
->context
.sp
))stackend
;
1628 /* Load the thread's context structure with needed startup information */
1629 THREAD_STARTUP_INIT(core
, thread
, function
);
1631 thread
->state
= state
;
1632 i
= thread
->id
; /* Snapshot while locked */
1634 if (state
== STATE_RUNNING
)
1635 core_schedule_wakeup(thread
);
1637 UNLOCK_THREAD(thread
);
1638 restore_irq(oldlevel
);
1643 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1644 /*---------------------------------------------------------------------------
1645 * Change the boost state of a thread boosting or unboosting the CPU
1647 *---------------------------------------------------------------------------
1649 static inline void boost_thread(struct thread_entry
*thread
, bool boost
)
1651 if ((thread
->cpu_boost
!= 0) != boost
)
1653 thread
->cpu_boost
= boost
;
1658 void trigger_cpu_boost(void)
1660 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
1661 boost_thread(current
, true);
1664 void cancel_cpu_boost(void)
1666 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
1667 boost_thread(current
, false);
1669 #endif /* HAVE_SCHEDULER_BOOSTCTRL */
1671 /*---------------------------------------------------------------------------
1672 * Block the current thread until another thread terminates. A thread may
1673 * wait on itself to terminate which prevents it from running again and it
1674 * will need to be killed externally.
1675 * Parameter is the ID as returned from create_thread().
1676 *---------------------------------------------------------------------------
1678 void thread_wait(unsigned int thread_id
)
1680 struct thread_entry
*current
= cores
[CURRENT_CORE
].running
;
1681 struct thread_entry
*thread
= thread_id_entry(thread_id
);
1683 /* Lock thread-as-waitable-object lock */
1684 corelock_lock(&thread
->waiter_cl
);
1686 /* Be sure it hasn't been killed yet */
1687 if (thread
->id
== thread_id
&& thread
->state
!= STATE_KILLED
)
1689 IF_COP( current
->obj_cl
= &thread
->waiter_cl
; )
1690 current
->bqp
= &thread
->queue
;
1693 block_thread(current
);
1695 corelock_unlock(&thread
->waiter_cl
);
1701 corelock_unlock(&thread
->waiter_cl
);
1704 /*---------------------------------------------------------------------------
1705 * Exit the current thread. The Right Way to Do Things (TM).
1706 *---------------------------------------------------------------------------
1708 /* This is done to foil optimizations that may require the current stack,
1709 * such as optimizing subexpressions that put variables on the stack that
1710 * get used after switching stacks. */
1712 /* Called by ASM stub */
1713 static void thread_final_exit_do(struct thread_entry
*current
)
1715 /* No special procedure is required before calling */
1716 static inline void thread_final_exit(struct thread_entry
*current
)
1719 /* At this point, this thread isn't using resources allocated for
1720 * execution except the slot itself. */
1722 /* Signal this thread */
1723 thread_queue_wake(¤t
->queue
);
1724 corelock_unlock(¤t
->waiter_cl
);
1726 /* This should never and must never be reached - if it is, the
1727 * state is corrupted */
1728 THREAD_PANICF("thread_exit->K:*R", current
);
1732 void thread_exit(void)
1734 register struct thread_entry
* current
= cores
[CURRENT_CORE
].running
;
1736 /* Cancel CPU boost if any */
1741 corelock_lock(¤t
->waiter_cl
);
1742 LOCK_THREAD(current
);
1744 #if defined (ALLOW_REMOVE_THREAD) && NUM_CORES > 1
1745 if (current
->name
== THREAD_DESTRUCT
)
1747 /* Thread being killed - become a waiter */
1748 unsigned int id
= current
->id
;
1749 UNLOCK_THREAD(current
);
1750 corelock_unlock(¤t
->waiter_cl
);
1752 THREAD_PANICF("thread_exit->WK:*R", current
);
1756 #ifdef HAVE_PRIORITY_SCHEDULING
1757 check_for_obj_waiters("thread_exit", current
);
1760 if (current
->tmo
.prev
!= NULL
)
1762 /* Cancel pending timeout list removal */
1763 remove_from_list_tmo(current
);
1766 /* Switch tasks and never return */
1767 block_thread_on_l(current
, STATE_KILLED
);
1769 /* Slot must be unusable until thread is really gone */
1770 UNLOCK_THREAD_AT_TASK_SWITCH(current
);
1772 /* Update ID for this slot */
1773 new_thread_id(current
->id
, current
);
1774 current
->name
= NULL
;
1776 /* Do final cleanup and remove the thread */
1777 thread_final_exit(current
);
1780 #ifdef ALLOW_REMOVE_THREAD
1781 /*---------------------------------------------------------------------------
1782 * Remove a thread from the scheduler. Not The Right Way to Do Things in
1785 * Parameter is the ID as returned from create_thread().
1787 * Use with care on threads that are not under careful control as this may
1788 * leave various objects in an undefined state.
1789 *---------------------------------------------------------------------------
1791 void remove_thread(unsigned int thread_id
)
1793 #ifdef HAVE_CORELOCK_OBJECT
1794 /* core is not constant here because of core switching */
1795 unsigned int core
= CURRENT_CORE
;
1796 unsigned int old_core
= NUM_CORES
;
1797 struct corelock
*ocl
= NULL
;
1799 const unsigned int core
= CURRENT_CORE
;
1801 struct thread_entry
*current
= cores
[core
].running
;
1802 struct thread_entry
*thread
= thread_id_entry(thread_id
);
1807 if (thread
== current
)
1808 thread_exit(); /* Current thread - do normal exit */
1810 oldlevel
= disable_irq_save();
1812 corelock_lock(&thread
->waiter_cl
);
1813 LOCK_THREAD(thread
);
1815 state
= thread
->state
;
1817 if (thread
->id
!= thread_id
|| state
== STATE_KILLED
)
1821 if (thread
->name
== THREAD_DESTRUCT
)
1823 /* Thread being killed - become a waiter */
1824 UNLOCK_THREAD(thread
);
1825 corelock_unlock(&thread
->waiter_cl
);
1826 restore_irq(oldlevel
);
1827 thread_wait(thread_id
);
1831 thread
->name
= THREAD_DESTRUCT
; /* Slot can't be used for now */
1833 #ifdef HAVE_PRIORITY_SCHEDULING
1834 check_for_obj_waiters("remove_thread", thread
);
1837 if (thread
->core
!= core
)
1839 /* Switch cores and safely extract the thread there */
1840 /* Slot HAS to be unlocked or a deadlock could occur which means other
1841 * threads have to be guided into becoming thread waiters if they
1842 * attempt to remove it. */
1843 unsigned int new_core
= thread
->core
;
1845 corelock_unlock(&thread
->waiter_cl
);
1847 UNLOCK_THREAD(thread
);
1848 restore_irq(oldlevel
);
1850 old_core
= switch_core(new_core
);
1852 oldlevel
= disable_irq_save();
1854 corelock_lock(&thread
->waiter_cl
);
1855 LOCK_THREAD(thread
);
1857 state
= thread
->state
;
1859 /* Perform the extraction and switch ourselves back to the original
1862 #endif /* NUM_CORES > 1 */
1864 if (thread
->tmo
.prev
!= NULL
)
1866 /* Clean thread off the timeout list if a timeout check hasn't
1868 remove_from_list_tmo(thread
);
1871 #ifdef HAVE_SCHEDULER_BOOSTCTRL
1872 /* Cancel CPU boost if any */
1873 boost_thread(thread
, false);
1876 IF_COP( retry_state
: )
1882 /* Remove thread from ready to run tasks */
1883 remove_from_list_l(&cores
[core
].running
, thread
);
1884 rtr_subtract_entry(core
, thread
->priority
);
1888 case STATE_BLOCKED_W_TMO
:
1889 /* Remove thread from the queue it's blocked on - including its
1890 * own if waiting there */
1892 if (&thread
->waiter_cl
!= thread
->obj_cl
)
1894 ocl
= thread
->obj_cl
;
1896 if (UNLIKELY(corelock_try_lock(ocl
) == 0))
1898 UNLOCK_THREAD(thread
);
1900 LOCK_THREAD(thread
);
1902 if (UNLIKELY(thread
->state
!= state
))
1904 /* Something woke the thread */
1905 state
= thread
->state
;
1906 corelock_unlock(ocl
);
1912 remove_from_list_l(thread
->bqp
, thread
);
1914 #ifdef HAVE_WAKEUP_EXT_CB
1915 if (thread
->wakeup_ext_cb
!= NULL
)
1916 thread
->wakeup_ext_cb(thread
);
1919 #ifdef HAVE_PRIORITY_SCHEDULING
1920 if (thread
->blocker
!= NULL
)
1922 /* Remove thread's priority influence from its chain */
1923 wakeup_priority_protocol_release(thread
);
1929 corelock_unlock(ocl
);
1932 /* Otherwise thread is frozen and hasn't run yet */
1935 new_thread_id(thread_id
, thread
);
1936 thread
->state
= STATE_KILLED
;
1938 /* If thread was waiting on itself, it will have been removed above.
1939 * The wrong order would result in waking the thread first and deadlocking
1940 * since the slot is already locked. */
1941 thread_queue_wake(&thread
->queue
);
1943 thread
->name
= NULL
;
1945 thread_killed
: /* Thread was already killed */
1946 /* Removal complete - safe to unlock and reenable interrupts */
1947 corelock_unlock(&thread
->waiter_cl
);
1948 UNLOCK_THREAD(thread
);
1949 restore_irq(oldlevel
);
1952 if (old_core
< NUM_CORES
)
1954 /* Did a removal on another processor's thread - switch back to
1956 switch_core(old_core
);
1960 #endif /* ALLOW_REMOVE_THREAD */
1962 #ifdef HAVE_PRIORITY_SCHEDULING
1963 /*---------------------------------------------------------------------------
1964 * Sets the thread's relative base priority for the core it runs on. Any
1965 * needed inheritance changes also may happen.
1966 *---------------------------------------------------------------------------
1968 int thread_set_priority(unsigned int thread_id
, int priority
)
1970 int old_base_priority
= -1;
1971 struct thread_entry
*thread
= thread_id_entry(thread_id
);
1973 /* A little safety measure */
1974 if (priority
< HIGHEST_PRIORITY
|| priority
> LOWEST_PRIORITY
)
1977 /* Thread could be on any list and therefore on an interrupt accessible
1978 one - disable interrupts */
1979 int oldlevel
= disable_irq_save();
1981 LOCK_THREAD(thread
);
1983 /* Make sure it's not killed */
1984 if (thread
->id
== thread_id
&& thread
->state
!= STATE_KILLED
)
1986 int old_priority
= thread
->priority
;
1988 old_base_priority
= thread
->base_priority
;
1989 thread
->base_priority
= priority
;
1991 prio_move_entry(&thread
->pdist
, old_base_priority
, priority
);
1992 priority
= find_first_set_bit(thread
->pdist
.mask
);
1994 if (old_priority
== priority
)
1996 /* No priority change - do nothing */
1998 else if (thread
->state
== STATE_RUNNING
)
2000 /* This thread is running - change location on the run
2001 * queue. No transitive inheritance needed. */
2002 set_running_thread_priority(thread
, priority
);
2006 thread
->priority
= priority
;
2008 if (thread
->blocker
!= NULL
)
2010 /* Bubble new priority down the chain */
2011 struct blocker
*bl
= thread
->blocker
; /* Blocker struct */
2012 struct thread_entry
*bl_t
= bl
->thread
; /* Blocking thread */
2013 struct thread_entry
* const tstart
= thread
; /* Initial thread */
2014 const int highest
= MIN(priority
, old_priority
); /* Higher of new or old */
2018 struct thread_entry
*next
; /* Next thread to check */
2019 int bl_pr
; /* Highest blocked thread */
2020 int queue_pr
; /* New highest blocked thread */
2022 /* Owner can change but thread cannot be dislodged - thread
2023 * may not be the first in the queue which allows other
2024 * threads ahead in the list to be given ownership during the
2025 * operation. If thread is next then the waker will have to
2026 * wait for us and the owner of the object will remain fixed.
2027 * If we successfully grab the owner -- which at some point
2028 * is guaranteed -- then the queue remains fixed until we
2034 /* Double-check the owner - retry if it changed */
2035 if (LIKELY(bl
->thread
== bl_t
))
2038 UNLOCK_THREAD(bl_t
);
2042 bl_pr
= bl
->priority
;
2044 if (highest
> bl_pr
)
2045 break; /* Object priority won't change */
2047 /* This will include the thread being set */
2048 queue_pr
= find_highest_priority_in_list_l(*thread
->bqp
);
2050 if (queue_pr
== bl_pr
)
2051 break; /* Object priority not changing */
2053 /* Update thread boost for this object */
2054 bl
->priority
= queue_pr
;
2055 prio_move_entry(&bl_t
->pdist
, bl_pr
, queue_pr
);
2056 bl_pr
= find_first_set_bit(bl_t
->pdist
.mask
);
2058 if (bl_t
->priority
== bl_pr
)
2059 break; /* Blocking thread priority not changing */
2061 if (bl_t
->state
== STATE_RUNNING
)
2063 /* Thread not blocked - we're done */
2064 set_running_thread_priority(bl_t
, bl_pr
);
2068 bl_t
->priority
= bl_pr
;
2069 bl
= bl_t
->blocker
; /* Blocking thread has a blocker? */
2072 break; /* End of chain */
2076 if (UNLIKELY(next
== tstart
))
2077 break; /* Full-circle */
2079 UNLOCK_THREAD(thread
);
2085 UNLOCK_THREAD(bl_t
);
2090 UNLOCK_THREAD(thread
);
2092 restore_irq(oldlevel
);
2094 return old_base_priority
;
2097 /*---------------------------------------------------------------------------
2098 * Returns the current base priority for a thread.
2099 *---------------------------------------------------------------------------
2101 int thread_get_priority(unsigned int thread_id
)
2103 struct thread_entry
*thread
= thread_id_entry(thread_id
);
2104 int base_priority
= thread
->base_priority
;
2106 /* Simply check without locking slot. It may or may not be valid by the
2107 * time the function returns anyway. If all tests pass, it is the
2108 * correct value for when it was valid. */
2109 if (thread
->id
!= thread_id
|| thread
->state
== STATE_KILLED
)
2112 return base_priority
;
2114 #endif /* HAVE_PRIORITY_SCHEDULING */
2116 #ifdef HAVE_IO_PRIORITY
2117 int thread_get_io_priority(unsigned int thread_id
)
2119 struct thread_entry
*thread
= thread_id_entry(thread_id
);
2120 return thread
->io_priority
;
2123 void thread_set_io_priority(unsigned int thread_id
,int io_priority
)
2125 struct thread_entry
*thread
= thread_id_entry(thread_id
);
2126 thread
->io_priority
= io_priority
;
2130 /*---------------------------------------------------------------------------
2131 * Starts a frozen thread - similar semantics to wakeup_thread except that
2132 * the thread is on no scheduler or wakeup queue at all. It exists simply by
2133 * virtue of the slot having a state of STATE_FROZEN.
2134 *---------------------------------------------------------------------------
2136 void thread_thaw(unsigned int thread_id
)
2138 struct thread_entry
*thread
= thread_id_entry(thread_id
);
2139 int oldlevel
= disable_irq_save();
2141 LOCK_THREAD(thread
);
2143 /* If thread is the current one, it cannot be frozen, therefore
2144 * there is no need to check that. */
2145 if (thread
->id
== thread_id
&& thread
->state
== STATE_FROZEN
)
2146 core_schedule_wakeup(thread
);
2148 UNLOCK_THREAD(thread
);
2149 restore_irq(oldlevel
);
2153 /*---------------------------------------------------------------------------
2154 * Switch the processor that the currently executing thread runs on.
2155 *---------------------------------------------------------------------------
2157 unsigned int switch_core(unsigned int new_core
)
2159 const unsigned int core
= CURRENT_CORE
;
2160 struct thread_entry
*current
= cores
[core
].running
;
2162 if (core
== new_core
)
2164 /* No change - just return same core */
2168 int oldlevel
= disable_irq_save();
2169 LOCK_THREAD(current
);
2171 if (current
->name
== THREAD_DESTRUCT
)
2173 /* Thread being killed - deactivate and let process complete */
2174 unsigned int id
= current
->id
;
2175 UNLOCK_THREAD(current
);
2176 restore_irq(oldlevel
);
2178 /* Should never be reached */
2179 THREAD_PANICF("switch_core->D:*R", current
);
2182 /* Get us off the running list for the current core */
2184 remove_from_list_l(&cores
[core
].running
, current
);
2185 rtr_subtract_entry(core
, current
->priority
);
2188 /* Stash return value (old core) in a safe place */
2189 current
->retval
= core
;
2191 /* If a timeout hadn't yet been cleaned-up it must be removed now or
2192 * the other core will likely attempt a removal from the wrong list! */
2193 if (current
->tmo
.prev
!= NULL
)
2195 remove_from_list_tmo(current
);
2198 /* Change the core number for this thread slot */
2199 current
->core
= new_core
;
2201 /* Do not use core_schedule_wakeup here since this will result in
2202 * the thread starting to run on the other core before being finished on
2203 * this one. Delay the list unlock to keep the other core stuck
2204 * until this thread is ready. */
2207 rtr_add_entry(new_core
, current
->priority
);
2208 add_to_list_l(&cores
[new_core
].running
, current
);
2210 /* Make a callback into device-specific code, unlock the wakeup list so
2211 * that execution may resume on the new core, unlock our slot and finally
2212 * restore the interrupt level */
2213 cores
[core
].blk_ops
.flags
= TBOP_SWITCH_CORE
;
2214 cores
[core
].blk_ops
.cl_p
= &cores
[new_core
].rtr_cl
;
2215 cores
[core
].block_task
= current
;
2217 UNLOCK_THREAD(current
);
2219 /* Alert other core to activity */
2220 core_wake(new_core
);
2222 /* Do the stack switching, cache_maintenence and switch_thread call -
2223 requires native code */
2224 switch_thread_core(core
, current
);
2226 /* Finally return the old core to caller */
2227 return current
->retval
;
2229 #endif /* NUM_CORES > 1 */
2231 /*---------------------------------------------------------------------------
2232 * Initialize threading API. This assumes interrupts are not yet enabled. On
2233 * multicore setups, no core is allowed to proceed until create_thread calls
2234 * are safe to perform.
2235 *---------------------------------------------------------------------------
2237 void init_threads(void)
2239 const unsigned int core
= CURRENT_CORE
;
2240 struct thread_entry
*thread
;
2244 /* Initialize core locks and IDs in all slots */
2246 for (n
= 0; n
< MAXTHREADS
; n
++)
2248 thread
= &threads
[n
];
2249 corelock_init(&thread
->waiter_cl
);
2250 corelock_init(&thread
->slot_cl
);
2251 thread
->id
= THREAD_ID_INIT(n
);
2255 /* CPU will initialize first and then sleep */
2256 thread
= find_empty_thread_slot();
2260 /* WTF? There really must be a slot available at this stage.
2261 * This can fail if, for example, .bss isn't zero'ed out by the loader
2262 * or threads is in the wrong section. */
2263 THREAD_PANICF("init_threads->no slot", NULL
);
2266 /* Initialize initially non-zero members of core */
2267 cores
[core
].next_tmo_check
= current_tick
; /* Something not in the past */
2269 /* Initialize initially non-zero members of slot */
2270 UNLOCK_THREAD(thread
); /* No sync worries yet */
2271 thread
->name
= main_thread_name
;
2272 thread
->state
= STATE_RUNNING
;
2273 IF_COP( thread
->core
= core
; )
2274 #ifdef HAVE_PRIORITY_SCHEDULING
2275 corelock_init(&cores
[core
].rtr_cl
);
2276 thread
->base_priority
= PRIORITY_USER_INTERFACE
;
2277 prio_add_entry(&thread
->pdist
, PRIORITY_USER_INTERFACE
);
2278 thread
->priority
= PRIORITY_USER_INTERFACE
;
2279 rtr_add_entry(core
, PRIORITY_USER_INTERFACE
);
2282 add_to_list_l(&cores
[core
].running
, thread
);
2286 thread
->stack
= stackbegin
;
2287 thread
->stack_size
= (uintptr_t)stackend
- (uintptr_t)stackbegin
;
2288 #if NUM_CORES > 1 /* This code path will not be run on single core targets */
2289 /* Wait for other processors to finish their inits since create_thread
2290 * isn't safe to call until the kernel inits are done. The first
2291 * threads created in the system must of course be created by CPU.
2292 * Another possible approach is to initialize all cores and slots
2293 * for each core by CPU, let the remainder proceed in parallel and
2294 * signal CPU when all are finished. */
2295 core_thread_init(CPU
);
2299 /* Initial stack is the idle stack */
2300 thread
->stack
= idle_stacks
[core
];
2301 thread
->stack_size
= IDLE_STACK_SIZE
;
2302 /* After last processor completes, it should signal all others to
2303 * proceed or may signal the next and call thread_exit(). The last one
2304 * to finish will signal CPU. */
2305 core_thread_init(core
);
2306 /* Other cores do not have a main thread - go idle inside switch_thread
2307 * until a thread can run on the core. */
2309 #endif /* NUM_CORES */
2311 #ifdef INIT_MAIN_THREAD
2312 init_main_thread(&thread
->context
);
2316 /* Shared stack scan helper for thread_stack_usage and idle_stack_usage */
2318 static inline int stack_usage(uintptr_t *stackptr
, size_t stack_size
)
2320 static int stack_usage(uintptr_t *stackptr
, size_t stack_size
)
2323 unsigned int stack_words
= stack_size
/ sizeof (uintptr_t);
2327 for (i
= 0; i
< stack_words
; i
++)
2329 if (stackptr
[i
] != DEADBEEF
)
2331 usage
= ((stack_words
- i
) * 100) / stack_words
;
2339 /*---------------------------------------------------------------------------
2340 * Returns the maximum percentage of stack a thread ever used while running.
2341 * NOTE: Some large buffer allocations that don't use enough the buffer to
2342 * overwrite stackptr[0] will not be seen.
2343 *---------------------------------------------------------------------------
2345 int thread_stack_usage(const struct thread_entry
*thread
)
2347 if (LIKELY(thread
->stack_size
> 0))
2348 return stack_usage(thread
->stack
, thread
->stack_size
);
2353 /*---------------------------------------------------------------------------
2354 * Returns the maximum percentage of the core's idle stack ever used during
2356 *---------------------------------------------------------------------------
2358 int idle_stack_usage(unsigned int core
)
2360 return stack_usage(idle_stacks
[core
], IDLE_STACK_SIZE
);
2364 /*---------------------------------------------------------------------------
2365 * Fills in the buffer with the specified thread's name. If the name is NULL,
2366 * empty, or the thread is in destruct state a formatted ID is written
2368 *---------------------------------------------------------------------------
2370 void thread_get_name(char *buffer
, int size
,
2371 struct thread_entry
*thread
)
2380 /* Display thread name if one or ID if none */
2381 const char *name
= thread
->name
;
2382 const char *fmt
= "%s";
2383 if (name
== NULL
IF_COP(|| name
== THREAD_DESTRUCT
) || *name
== '\0')
2385 name
= (const char *)(uintptr_t)thread
->id
;
2388 snprintf(buffer
, size
, fmt
, name
);