1 /*
2  * Copyright (c) 2016-2017 Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_KERNEL_INCLUDE_KSCHED_H_
8 #define ZEPHYR_KERNEL_INCLUDE_KSCHED_H_
9 
10 #include <zephyr/kernel_structs.h>
11 #include <kernel_internal.h>
12 #include <zephyr/timeout_q.h>
13 #include <zephyr/tracing/tracing.h>
14 #include <stdbool.h>
15 
16 BUILD_ASSERT(K_LOWEST_APPLICATION_THREAD_PRIO
17 	     >= K_HIGHEST_APPLICATION_THREAD_PRIO);
18 
19 #ifdef CONFIG_MULTITHREADING
20 #define Z_VALID_PRIO(prio, entry_point)				     \
21 	(((prio) == K_IDLE_PRIO && z_is_idle_thread_entry(entry_point)) || \
22 	 ((K_LOWEST_APPLICATION_THREAD_PRIO			     \
23 	   >= K_HIGHEST_APPLICATION_THREAD_PRIO)		     \
24 	  && (prio) >= K_HIGHEST_APPLICATION_THREAD_PRIO	     \
25 	  && (prio) <= K_LOWEST_APPLICATION_THREAD_PRIO))
26 
27 #define Z_ASSERT_VALID_PRIO(prio, entry_point) do { \
28 	__ASSERT(Z_VALID_PRIO((prio), (entry_point)), \
29 		 "invalid priority (%d); allowed range: %d to %d", \
30 		 (prio), \
31 		 K_LOWEST_APPLICATION_THREAD_PRIO, \
32 		 K_HIGHEST_APPLICATION_THREAD_PRIO); \
33 	} while (false)
34 #else
35 #define Z_VALID_PRIO(prio, entry_point) ((prio) == -1)
36 #define Z_ASSERT_VALID_PRIO(prio, entry_point) __ASSERT((prio) == -1, "")
37 #endif
38 
39 void z_sched_init(void);
40 void z_move_thread_to_end_of_prio_q(struct k_thread *thread);
41 int z_is_thread_time_slicing(struct k_thread *thread);
42 void z_unpend_thread_no_timeout(struct k_thread *thread);
43 struct k_thread *z_unpend1_no_timeout(_wait_q_t *wait_q);
44 int z_pend_curr(struct k_spinlock *lock, k_spinlock_key_t key,
45 	       _wait_q_t *wait_q, k_timeout_t timeout);
46 int z_pend_curr_irqlock(uint32_t key, _wait_q_t *wait_q, k_timeout_t timeout);
47 void z_pend_thread(struct k_thread *thread, _wait_q_t *wait_q,
48 		   k_timeout_t timeout);
49 void z_reschedule(struct k_spinlock *lock, k_spinlock_key_t key);
50 void z_reschedule_irqlock(uint32_t key);
51 struct k_thread *z_unpend_first_thread(_wait_q_t *wait_q);
52 void z_unpend_thread(struct k_thread *thread);
53 int z_unpend_all(_wait_q_t *wait_q);
54 void z_thread_priority_set(struct k_thread *thread, int prio);
55 bool z_set_prio(struct k_thread *thread, int prio);
56 void *z_get_next_switch_handle(void *interrupted);
57 void idle(void *unused1, void *unused2, void *unused3);
58 void z_time_slice(void);
59 void z_reset_time_slice(struct k_thread *curr);
60 void z_sched_abort(struct k_thread *thread);
61 void z_sched_ipi(void);
62 void z_sched_start(struct k_thread *thread);
63 void z_ready_thread(struct k_thread *thread);
64 void z_requeue_current(struct k_thread *curr);
65 struct k_thread *z_swap_next_thread(void);
66 void z_thread_abort(struct k_thread *thread);
67 
z_pend_curr_unlocked(_wait_q_t * wait_q,k_timeout_t timeout)68 static inline void z_pend_curr_unlocked(_wait_q_t *wait_q, k_timeout_t timeout)
69 {
70 	(void) z_pend_curr_irqlock(arch_irq_lock(), wait_q, timeout);
71 }
72 
z_reschedule_unlocked(void)73 static inline void z_reschedule_unlocked(void)
74 {
75 	(void) z_reschedule_irqlock(arch_irq_lock());
76 }
77 
z_is_idle_thread_entry(void * entry_point)78 static inline bool z_is_idle_thread_entry(void *entry_point)
79 {
80 	return entry_point == idle;
81 }
82 
z_is_idle_thread_object(struct k_thread * thread)83 static inline bool z_is_idle_thread_object(struct k_thread *thread)
84 {
85 #ifdef CONFIG_MULTITHREADING
86 #ifdef CONFIG_SMP
87 	return thread->base.is_idle;
88 #else
89 	return thread == &z_idle_threads[0];
90 #endif
91 #else
92 	return false;
93 #endif /* CONFIG_MULTITHREADING */
94 }
95 
z_is_thread_suspended(struct k_thread * thread)96 static inline bool z_is_thread_suspended(struct k_thread *thread)
97 {
98 	return (thread->base.thread_state & _THREAD_SUSPENDED) != 0U;
99 }
100 
z_is_thread_pending(struct k_thread * thread)101 static inline bool z_is_thread_pending(struct k_thread *thread)
102 {
103 	return (thread->base.thread_state & _THREAD_PENDING) != 0U;
104 }
105 
z_is_thread_prevented_from_running(struct k_thread * thread)106 static inline bool z_is_thread_prevented_from_running(struct k_thread *thread)
107 {
108 	uint8_t state = thread->base.thread_state;
109 
110 	return (state & (_THREAD_PENDING | _THREAD_PRESTART | _THREAD_DEAD |
111 			 _THREAD_DUMMY | _THREAD_SUSPENDED)) != 0U;
112 
113 }
114 
z_is_thread_timeout_active(struct k_thread * thread)115 static inline bool z_is_thread_timeout_active(struct k_thread *thread)
116 {
117 	return !z_is_inactive_timeout(&thread->base.timeout);
118 }
119 
z_is_thread_ready(struct k_thread * thread)120 static inline bool z_is_thread_ready(struct k_thread *thread)
121 {
122 	return !((z_is_thread_prevented_from_running(thread)) != 0U ||
123 		 z_is_thread_timeout_active(thread));
124 }
125 
z_has_thread_started(struct k_thread * thread)126 static inline bool z_has_thread_started(struct k_thread *thread)
127 {
128 	return (thread->base.thread_state & _THREAD_PRESTART) == 0U;
129 }
130 
z_is_thread_state_set(struct k_thread * thread,uint32_t state)131 static inline bool z_is_thread_state_set(struct k_thread *thread, uint32_t state)
132 {
133 	return (thread->base.thread_state & state) != 0U;
134 }
135 
z_is_thread_queued(struct k_thread * thread)136 static inline bool z_is_thread_queued(struct k_thread *thread)
137 {
138 	return z_is_thread_state_set(thread, _THREAD_QUEUED);
139 }
140 
z_mark_thread_as_suspended(struct k_thread * thread)141 static inline void z_mark_thread_as_suspended(struct k_thread *thread)
142 {
143 	thread->base.thread_state |= _THREAD_SUSPENDED;
144 
145 	SYS_PORT_TRACING_FUNC(k_thread, sched_suspend, thread);
146 }
147 
z_mark_thread_as_not_suspended(struct k_thread * thread)148 static inline void z_mark_thread_as_not_suspended(struct k_thread *thread)
149 {
150 	thread->base.thread_state &= ~_THREAD_SUSPENDED;
151 
152 	SYS_PORT_TRACING_FUNC(k_thread, sched_resume, thread);
153 }
154 
z_mark_thread_as_started(struct k_thread * thread)155 static inline void z_mark_thread_as_started(struct k_thread *thread)
156 {
157 	thread->base.thread_state &= ~_THREAD_PRESTART;
158 }
159 
z_mark_thread_as_pending(struct k_thread * thread)160 static inline void z_mark_thread_as_pending(struct k_thread *thread)
161 {
162 	thread->base.thread_state |= _THREAD_PENDING;
163 }
164 
z_mark_thread_as_not_pending(struct k_thread * thread)165 static inline void z_mark_thread_as_not_pending(struct k_thread *thread)
166 {
167 	thread->base.thread_state &= ~_THREAD_PENDING;
168 }
169 
z_set_thread_states(struct k_thread * thread,uint32_t states)170 static inline void z_set_thread_states(struct k_thread *thread, uint32_t states)
171 {
172 	thread->base.thread_state |= states;
173 }
174 
z_reset_thread_states(struct k_thread * thread,uint32_t states)175 static inline void z_reset_thread_states(struct k_thread *thread,
176 					uint32_t states)
177 {
178 	thread->base.thread_state &= ~states;
179 }
180 
z_is_under_prio_ceiling(int prio)181 static inline bool z_is_under_prio_ceiling(int prio)
182 {
183 	return prio >= CONFIG_PRIORITY_CEILING;
184 }
185 
z_get_new_prio_with_ceiling(int prio)186 static inline int z_get_new_prio_with_ceiling(int prio)
187 {
188 	return z_is_under_prio_ceiling(prio) ? prio : CONFIG_PRIORITY_CEILING;
189 }
190 
z_is_prio1_higher_than_or_equal_to_prio2(int prio1,int prio2)191 static inline bool z_is_prio1_higher_than_or_equal_to_prio2(int prio1, int prio2)
192 {
193 	return prio1 <= prio2;
194 }
195 
z_is_prio_higher_or_equal(int prio1,int prio2)196 static inline bool z_is_prio_higher_or_equal(int prio1, int prio2)
197 {
198 	return z_is_prio1_higher_than_or_equal_to_prio2(prio1, prio2);
199 }
200 
z_is_prio1_lower_than_or_equal_to_prio2(int prio1,int prio2)201 static inline bool z_is_prio1_lower_than_or_equal_to_prio2(int prio1, int prio2)
202 {
203 	return prio1 >= prio2;
204 }
205 
z_is_prio1_higher_than_prio2(int prio1,int prio2)206 static inline bool z_is_prio1_higher_than_prio2(int prio1, int prio2)
207 {
208 	return prio1 < prio2;
209 }
210 
z_is_prio_higher(int prio,int test_prio)211 static inline bool z_is_prio_higher(int prio, int test_prio)
212 {
213 	return z_is_prio1_higher_than_prio2(prio, test_prio);
214 }
215 
z_is_prio_lower_or_equal(int prio1,int prio2)216 static inline bool z_is_prio_lower_or_equal(int prio1, int prio2)
217 {
218 	return z_is_prio1_lower_than_or_equal_to_prio2(prio1, prio2);
219 }
220 
221 int32_t z_sched_prio_cmp(struct k_thread *thread_1, struct k_thread *thread_2);
222 
_is_valid_prio(int prio,void * entry_point)223 static inline bool _is_valid_prio(int prio, void *entry_point)
224 {
225 	if (prio == K_IDLE_PRIO && z_is_idle_thread_entry(entry_point)) {
226 		return true;
227 	}
228 
229 	if (!z_is_prio_higher_or_equal(prio,
230 				       K_LOWEST_APPLICATION_THREAD_PRIO)) {
231 		return false;
232 	}
233 
234 	if (!z_is_prio_lower_or_equal(prio,
235 				      K_HIGHEST_APPLICATION_THREAD_PRIO)) {
236 		return false;
237 	}
238 
239 	return true;
240 }
241 
_ready_one_thread(_wait_q_t * wq)242 static inline void _ready_one_thread(_wait_q_t *wq)
243 {
244 	struct k_thread *thread = z_unpend_first_thread(wq);
245 
246 	if (thread != NULL) {
247 		z_ready_thread(thread);
248 	}
249 }
250 
z_sched_lock(void)251 static inline void z_sched_lock(void)
252 {
253 	__ASSERT(!arch_is_in_isr(), "");
254 	__ASSERT(_current->base.sched_locked != 1U, "");
255 
256 	--_current->base.sched_locked;
257 
258 	compiler_barrier();
259 }
260 
z_sched_unlock_no_reschedule(void)261 static ALWAYS_INLINE void z_sched_unlock_no_reschedule(void)
262 {
263 	__ASSERT(!arch_is_in_isr(), "");
264 	__ASSERT(_current->base.sched_locked != 0U, "");
265 
266 	compiler_barrier();
267 
268 	++_current->base.sched_locked;
269 }
270 
z_is_thread_timeout_expired(struct k_thread * thread)271 static ALWAYS_INLINE bool z_is_thread_timeout_expired(struct k_thread *thread)
272 {
273 #ifdef CONFIG_SYS_CLOCK_EXISTS
274 	return thread->base.timeout.dticks == _EXPIRED;
275 #else
276 	return 0;
277 #endif
278 }
279 
280 /*
281  * APIs for working with the Zephyr kernel scheduler. Intended for use in
282  * management of IPC objects, either in the core kernel or other IPC
283  * implemented by OS compatibility layers, providing basic wait/wake operations
284  * with spinlocks used for synchronization.
285  *
286  * These APIs are public and will be treated as contract, even if the
287  * underlying scheduler implementation changes.
288  */
289 
290 /**
291  * Wake up a thread pending on the provided wait queue
292  *
293  * Given a wait_q, wake up the highest priority thread on the queue. If the
294  * queue was empty just return false.
295  *
296  * Otherwise, do the following, in order,  holding sched_spinlock the entire
297  * time so that the thread state is guaranteed not to change:
298  * - Set the thread's swap return values to swap_retval and swap_data
299  * - un-pend and ready the thread, but do not invoke the scheduler.
300  *
301  * Repeated calls to this function until it returns false is a suitable
302  * way to wake all threads on the queue.
303  *
304  * It is up to the caller to implement locking such that the return value of
305  * this function (whether a thread was woken up or not) does not immediately
306  * become stale. Calls to wait and wake on the same wait_q object must have
307  * synchronization. Calling this without holding any spinlock is a sign that
308  * this API is not being used properly.
309  *
310  * @param wait_q Wait queue to wake up the highest prio thread
311  * @param swap_retval Swap return value for woken thread
312  * @param swap_data Data return value to supplement swap_retval. May be NULL.
313  * @retval true If a thread was woken up
314  * @retval false If the wait_q was empty
315  */
316 bool z_sched_wake(_wait_q_t *wait_q, int swap_retval, void *swap_data);
317 
318 /**
319  * Wakes the specified thread.
320  *
321  * Given a specific thread, wake it up. This routine assumes that the given
322  * thread is not on the timeout queue.
323  *
324  * @param thread Given thread to wake up.
325  * @param is_timeout True if called from the timer ISR; false otherwise.
326  *
327  */
328 void z_sched_wake_thread(struct k_thread *thread, bool is_timeout);
329 
330 /**
331  * Wake up all threads pending on the provided wait queue
332  *
333  * Convenience function to invoke z_sched_wake() on all threads in the queue
334  * until there are no more to wake up.
335  *
336  * @param wait_q Wait queue to wake up the highest prio thread
337  * @param swap_retval Swap return value for woken thread
338  * @param swap_data Data return value to supplement swap_retval. May be NULL.
339  * @retval true If any threads were woken up
340  * @retval false If the wait_q was empty
341  */
z_sched_wake_all(_wait_q_t * wait_q,int swap_retval,void * swap_data)342 static inline bool z_sched_wake_all(_wait_q_t *wait_q, int swap_retval,
343 				    void *swap_data)
344 {
345 	bool woken = false;
346 
347 	while (z_sched_wake(wait_q, swap_retval, swap_data)) {
348 		woken = true;
349 	}
350 
351 	/* True if we woke at least one thread up */
352 	return woken;
353 }
354 
355 /**
356  * Atomically put the current thread to sleep on a wait queue, with timeout
357  *
358  * The thread will be added to the provided waitqueue. The lock, which should
359  * be held by the caller with the provided key, will be released once this is
360  * completely done and we have swapped out.
361  *
362  * The return value and data pointer is set by whoever woke us up via
363  * z_sched_wake.
364  *
365  * @param lock Address of spinlock to release when we swap out
366  * @param key Key to the provided spinlock when it was locked
367  * @param wait_q Wait queue to go to sleep on
368  * @param timeout Waiting period to be woken up, or K_FOREVER to wait
369  *                indefinitely.
370  * @param data Storage location for data pointer set when thread was woken up.
371  *             May be NULL if not used.
372  * @retval Return value set by whatever woke us up, or -EAGAIN if the timeout
373  *         expired without being woken up.
374  */
375 int z_sched_wait(struct k_spinlock *lock, k_spinlock_key_t key,
376 		 _wait_q_t *wait_q, k_timeout_t timeout, void **data);
377 
378 /**
379  * @brief Walks the wait queue invoking the callback on each waiting thread
380  *
381  * This function walks the wait queue invoking the callback function on each
382  * waiting thread while holding sched_spinlock. This can be useful for routines
383  * that need to operate on multiple waiting threads.
384  *
385  * CAUTION! As a wait queue is of indeterminant length, the scheduler will be
386  * locked for an indeterminant amount of time. This may impact system
387  * performance. As such, care must be taken when using both this function and
388  * the specified callback.
389  *
390  * @param wait_q Identifies the wait queue to walk
391  * @param func   Callback to invoke on each waiting thread
392  * @param data   Custom data passed to the callback
393  *
394  * @retval non-zero if walk is terminated by the callback; otherwise 0
395  */
396 int z_sched_waitq_walk(_wait_q_t *wait_q,
397 		       int (*func)(struct k_thread *, void *), void *data);
398 
399 /** @brief Halt thread cycle usage accounting.
400  *
401  * Halts the accumulation of thread cycle usage and adds the current
402  * total to the thread's counter.  Called on context switch.
403  *
404  * Note that this function is idempotent.  The core kernel code calls
405  * it at the end of interrupt handlers (because that is where we have
406  * a portable hook) where we are context switching, which will include
407  * any cycles spent in the ISR in the per-thread accounting.  But
408  * architecture code can also call it earlier out of interrupt entry
409  * to improve measurement fidelity.
410  *
411  * This function assumes local interrupts are masked (so that the
412  * current CPU pointer and current thread are safe to modify), but
413  * requires no other synchronizaton.  Architecture layers don't need
414  * to do anything more.
415  */
416 void z_sched_usage_stop(void);
417 
418 void z_sched_usage_start(struct k_thread *thread);
419 
420 /**
421  * @brief Retrieves CPU cycle usage data for specified core
422  */
423 void z_sched_cpu_usage(uint8_t core_id, struct k_thread_runtime_stats *stats);
424 
425 /**
426  * @brief Retrieves thread cycle usage data for specified thread
427  */
428 void z_sched_thread_usage(struct k_thread *thread,
429 			  struct k_thread_runtime_stats *stats);
430 
z_sched_usage_switch(struct k_thread * thread)431 static inline void z_sched_usage_switch(struct k_thread *thread)
432 {
433 	ARG_UNUSED(thread);
434 #ifdef CONFIG_SCHED_THREAD_USAGE
435 	z_sched_usage_stop();
436 	z_sched_usage_start(thread);
437 #endif
438 }
439 
440 #endif /* ZEPHYR_KERNEL_INCLUDE_KSCHED_H_ */
441