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 <timeout_q.h>
13 #include <kthread.h>
14 #include <zephyr/tracing/tracing.h>
15 #include <stdbool.h>
16 #include <priority_q.h>
17 
18 BUILD_ASSERT(K_LOWEST_APPLICATION_THREAD_PRIO
19 	     >= K_HIGHEST_APPLICATION_THREAD_PRIO);
20 
21 #ifdef CONFIG_MULTITHREADING
22 #define Z_VALID_PRIO(prio, entry_point)				     \
23 	(((prio) == K_IDLE_PRIO && z_is_idle_thread_entry(entry_point)) || \
24 	 ((K_LOWEST_APPLICATION_THREAD_PRIO			     \
25 	   >= K_HIGHEST_APPLICATION_THREAD_PRIO)		     \
26 	  && (prio) >= K_HIGHEST_APPLICATION_THREAD_PRIO	     \
27 	  && (prio) <= K_LOWEST_APPLICATION_THREAD_PRIO))
28 
29 #define Z_ASSERT_VALID_PRIO(prio, entry_point) do { \
30 	__ASSERT(Z_VALID_PRIO((prio), (entry_point)), \
31 		 "invalid priority (%d); allowed range: %d to %d", \
32 		 (prio), \
33 		 K_LOWEST_APPLICATION_THREAD_PRIO, \
34 		 K_HIGHEST_APPLICATION_THREAD_PRIO); \
35 	} while (false)
36 #else
37 #define Z_VALID_PRIO(prio, entry_point) ((prio) == -1)
38 #define Z_ASSERT_VALID_PRIO(prio, entry_point) __ASSERT((prio) == -1, "")
39 #endif /* CONFIG_MULTITHREADING */
40 
41 #if (CONFIG_MP_MAX_NUM_CPUS == 1)
42 #define LOCK_SCHED_SPINLOCK
43 #else
44 #define LOCK_SCHED_SPINLOCK   K_SPINLOCK(&_sched_spinlock)
45 #endif
46 
47 extern struct k_spinlock _sched_spinlock;
48 
49 extern struct k_thread _thread_dummy;
50 
51 void z_sched_init(void);
52 void z_move_thread_to_end_of_prio_q(struct k_thread *thread);
53 void z_unpend_thread_no_timeout(struct k_thread *thread);
54 struct k_thread *z_unpend1_no_timeout(_wait_q_t *wait_q);
55 int z_pend_curr(struct k_spinlock *lock, k_spinlock_key_t key,
56 	       _wait_q_t *wait_q, k_timeout_t timeout);
57 void z_pend_thread(struct k_thread *thread, _wait_q_t *wait_q,
58 		   k_timeout_t timeout);
59 void z_reschedule(struct k_spinlock *lock, k_spinlock_key_t key);
60 void z_reschedule_irqlock(uint32_t key);
61 void z_unpend_thread(struct k_thread *thread);
62 int z_unpend_all(_wait_q_t *wait_q);
63 bool z_thread_prio_set(struct k_thread *thread, int prio);
64 void *z_get_next_switch_handle(void *interrupted);
65 
66 void z_time_slice(void);
67 void z_reset_time_slice(struct k_thread *curr);
68 void z_sched_ipi(void);
69 void z_sched_start(struct k_thread *thread);
70 void z_ready_thread(struct k_thread *thread);
71 void z_requeue_current(struct k_thread *curr);
72 struct k_thread *z_swap_next_thread(void);
73 void z_thread_abort(struct k_thread *thread);
74 void move_thread_to_end_of_prio_q(struct k_thread *thread);
75 bool thread_is_sliceable(struct k_thread *thread);
76 
z_reschedule_unlocked(void)77 static inline void z_reschedule_unlocked(void)
78 {
79 	(void) z_reschedule_irqlock(arch_irq_lock());
80 }
81 
z_is_under_prio_ceiling(int prio)82 static inline bool z_is_under_prio_ceiling(int prio)
83 {
84 	return prio >= CONFIG_PRIORITY_CEILING;
85 }
86 
z_get_new_prio_with_ceiling(int prio)87 static inline int z_get_new_prio_with_ceiling(int prio)
88 {
89 	return z_is_under_prio_ceiling(prio) ? prio : CONFIG_PRIORITY_CEILING;
90 }
91 
z_is_prio1_higher_than_or_equal_to_prio2(int prio1,int prio2)92 static inline bool z_is_prio1_higher_than_or_equal_to_prio2(int prio1, int prio2)
93 {
94 	return prio1 <= prio2;
95 }
96 
z_is_prio_higher_or_equal(int prio1,int prio2)97 static inline bool z_is_prio_higher_or_equal(int prio1, int prio2)
98 {
99 	return z_is_prio1_higher_than_or_equal_to_prio2(prio1, prio2);
100 }
101 
z_is_prio1_lower_than_or_equal_to_prio2(int prio1,int prio2)102 static inline bool z_is_prio1_lower_than_or_equal_to_prio2(int prio1, int prio2)
103 {
104 	return prio1 >= prio2;
105 }
106 
z_is_prio1_higher_than_prio2(int prio1,int prio2)107 static inline bool z_is_prio1_higher_than_prio2(int prio1, int prio2)
108 {
109 	return prio1 < prio2;
110 }
111 
z_is_prio_higher(int prio,int test_prio)112 static inline bool z_is_prio_higher(int prio, int test_prio)
113 {
114 	return z_is_prio1_higher_than_prio2(prio, test_prio);
115 }
116 
z_is_prio_lower_or_equal(int prio1,int prio2)117 static inline bool z_is_prio_lower_or_equal(int prio1, int prio2)
118 {
119 	return z_is_prio1_lower_than_or_equal_to_prio2(prio1, prio2);
120 }
121 
_is_valid_prio(int prio,k_thread_entry_t entry_point)122 static inline bool _is_valid_prio(int prio, k_thread_entry_t entry_point)
123 {
124 	if ((prio == K_IDLE_PRIO) && z_is_idle_thread_entry(entry_point)) {
125 		return true;
126 	}
127 
128 	if (!z_is_prio_higher_or_equal(prio,
129 				       K_LOWEST_APPLICATION_THREAD_PRIO)) {
130 		return false;
131 	}
132 
133 	if (!z_is_prio_lower_or_equal(prio,
134 				      K_HIGHEST_APPLICATION_THREAD_PRIO)) {
135 		return false;
136 	}
137 
138 	return true;
139 }
140 
pended_on_thread(struct k_thread * thread)141 static ALWAYS_INLINE _wait_q_t *pended_on_thread(struct k_thread *thread)
142 {
143 	__ASSERT_NO_MSG(thread->base.pended_on);
144 
145 	return thread->base.pended_on;
146 }
147 
148 
unpend_thread_no_timeout(struct k_thread * thread)149 static inline void unpend_thread_no_timeout(struct k_thread *thread)
150 {
151 	_priq_wait_remove(&pended_on_thread(thread)->waitq, thread);
152 	z_mark_thread_as_not_pending(thread);
153 	thread->base.pended_on = NULL;
154 }
155 
156 /*
157  * In a multiprocessor system, z_unpend_first_thread() must lock the scheduler
158  * spinlock _sched_spinlock. However, in a uniprocessor system, that is not
159  * necessary as the caller has already taken precautions (in the form of
160  * locking interrupts).
161  */
z_unpend_first_thread(_wait_q_t * wait_q)162 static ALWAYS_INLINE struct k_thread *z_unpend_first_thread(_wait_q_t *wait_q)
163 {
164 	struct k_thread *thread = NULL;
165 
166 	__ASSERT_EVAL(, int key = arch_irq_lock(); arch_irq_unlock(key),
167 		      !arch_irq_unlocked(key), "");
168 
169 	LOCK_SCHED_SPINLOCK {
170 		thread = _priq_wait_best(&wait_q->waitq);
171 		if (unlikely(thread != NULL)) {
172 			unpend_thread_no_timeout(thread);
173 			z_abort_thread_timeout(thread);
174 		}
175 	}
176 
177 	return thread;
178 }
179 
180 /*
181  * APIs for working with the Zephyr kernel scheduler. Intended for use in
182  * management of IPC objects, either in the core kernel or other IPC
183  * implemented by OS compatibility layers, providing basic wait/wake operations
184  * with spinlocks used for synchronization.
185  *
186  * These APIs are public and will be treated as contract, even if the
187  * underlying scheduler implementation changes.
188  */
189 
190 /**
191  * Wake up a thread pending on the provided wait queue
192  *
193  * Given a wait_q, wake up the highest priority thread on the queue. If the
194  * queue was empty just return false.
195  *
196  * Otherwise, do the following, in order,  holding _sched_spinlock the entire
197  * time so that the thread state is guaranteed not to change:
198  * - Set the thread's swap return values to swap_retval and swap_data
199  * - un-pend and ready the thread, but do not invoke the scheduler.
200  *
201  * Repeated calls to this function until it returns false is a suitable
202  * way to wake all threads on the queue.
203  *
204  * It is up to the caller to implement locking such that the return value of
205  * this function (whether a thread was woken up or not) does not immediately
206  * become stale. Calls to wait and wake on the same wait_q object must have
207  * synchronization. Calling this without holding any spinlock is a sign that
208  * this API is not being used properly.
209  *
210  * @param wait_q Wait queue to wake up the highest prio thread
211  * @param swap_retval Swap return value for woken thread
212  * @param swap_data Data return value to supplement swap_retval. May be NULL.
213  * @retval true If a thread was woken up
214  * @retval false If the wait_q was empty
215  */
216 bool z_sched_wake(_wait_q_t *wait_q, int swap_retval, void *swap_data);
217 
218 /**
219  * Wakes the specified thread.
220  *
221  * Given a specific thread, wake it up. This routine assumes that the given
222  * thread is not on the timeout queue.
223  *
224  * @param thread Given thread to wake up.
225  * @param is_timeout True if called from the timer ISR; false otherwise.
226  *
227  */
228 void z_sched_wake_thread(struct k_thread *thread, bool is_timeout);
229 
230 /**
231  * Wake up all threads pending on the provided wait queue
232  *
233  * Convenience function to invoke z_sched_wake() on all threads in the queue
234  * until there are no more to wake up.
235  *
236  * @param wait_q Wait queue to wake up the highest prio thread
237  * @param swap_retval Swap return value for woken thread
238  * @param swap_data Data return value to supplement swap_retval. May be NULL.
239  * @retval true If any threads were woken up
240  * @retval false If the wait_q was empty
241  */
z_sched_wake_all(_wait_q_t * wait_q,int swap_retval,void * swap_data)242 static inline bool z_sched_wake_all(_wait_q_t *wait_q, int swap_retval,
243 				    void *swap_data)
244 {
245 	bool woken = false;
246 
247 	while (z_sched_wake(wait_q, swap_retval, swap_data)) {
248 		woken = true;
249 	}
250 
251 	/* True if we woke at least one thread up */
252 	return woken;
253 }
254 
255 /**
256  * Atomically put the current thread to sleep on a wait queue, with timeout
257  *
258  * The thread will be added to the provided waitqueue. The lock, which should
259  * be held by the caller with the provided key, will be released once this is
260  * completely done and we have swapped out.
261  *
262  * The return value and data pointer is set by whoever woke us up via
263  * z_sched_wake.
264  *
265  * @param lock Address of spinlock to release when we swap out
266  * @param key Key to the provided spinlock when it was locked
267  * @param wait_q Wait queue to go to sleep on
268  * @param timeout Waiting period to be woken up, or K_FOREVER to wait
269  *                indefinitely.
270  * @param data Storage location for data pointer set when thread was woken up.
271  *             May be NULL if not used.
272  * @retval Return value set by whatever woke us up, or -EAGAIN if the timeout
273  *         expired without being woken up.
274  */
275 int z_sched_wait(struct k_spinlock *lock, k_spinlock_key_t key,
276 		 _wait_q_t *wait_q, k_timeout_t timeout, void **data);
277 
278 /**
279  * @brief Walks the wait queue invoking the callback on each waiting thread
280  *
281  * This function walks the wait queue invoking the callback function on each
282  * waiting thread while holding _sched_spinlock. This can be useful for routines
283  * that need to operate on multiple waiting threads.
284  *
285  * CAUTION! As a wait queue is of indeterminate length, the scheduler will be
286  * locked for an indeterminate amount of time. This may impact system
287  * performance. As such, care must be taken when using both this function and
288  * the specified callback.
289  *
290  * @param wait_q Identifies the wait queue to walk
291  * @param func   Callback to invoke on each waiting thread
292  * @param data   Custom data passed to the callback
293  *
294  * @retval non-zero if walk is terminated by the callback; otherwise 0
295  */
296 int z_sched_waitq_walk(_wait_q_t *wait_q,
297 		       int (*func)(struct k_thread *, void *), void *data);
298 
299 /** @brief Halt thread cycle usage accounting.
300  *
301  * Halts the accumulation of thread cycle usage and adds the current
302  * total to the thread's counter.  Called on context switch.
303  *
304  * Note that this function is idempotent.  The core kernel code calls
305  * it at the end of interrupt handlers (because that is where we have
306  * a portable hook) where we are context switching, which will include
307  * any cycles spent in the ISR in the per-thread accounting.  But
308  * architecture code can also call it earlier out of interrupt entry
309  * to improve measurement fidelity.
310  *
311  * This function assumes local interrupts are masked (so that the
312  * current CPU pointer and current thread are safe to modify), but
313  * requires no other synchronization.  Architecture layers don't need
314  * to do anything more.
315  */
316 void z_sched_usage_stop(void);
317 
318 void z_sched_usage_start(struct k_thread *thread);
319 
320 /**
321  * @brief Retrieves CPU cycle usage data for specified core
322  */
323 void z_sched_cpu_usage(uint8_t core_id, struct k_thread_runtime_stats *stats);
324 
325 /**
326  * @brief Retrieves thread cycle usage data for specified thread
327  */
328 void z_sched_thread_usage(struct k_thread *thread,
329 			  struct k_thread_runtime_stats *stats);
330 
z_sched_usage_switch(struct k_thread * thread)331 static inline void z_sched_usage_switch(struct k_thread *thread)
332 {
333 	ARG_UNUSED(thread);
334 #ifdef CONFIG_SCHED_THREAD_USAGE
335 	z_sched_usage_stop();
336 	z_sched_usage_start(thread);
337 #endif /* CONFIG_SCHED_THREAD_USAGE */
338 }
339 
340 #endif /* ZEPHYR_KERNEL_INCLUDE_KSCHED_H_ */
341