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 
122 int32_t z_sched_prio_cmp(struct k_thread *thread_1, struct k_thread *thread_2);
123 
_is_valid_prio(int prio,void * entry_point)124 static inline bool _is_valid_prio(int prio, void *entry_point)
125 {
126 	if ((prio == K_IDLE_PRIO) && z_is_idle_thread_entry(entry_point)) {
127 		return true;
128 	}
129 
130 	if (!z_is_prio_higher_or_equal(prio,
131 				       K_LOWEST_APPLICATION_THREAD_PRIO)) {
132 		return false;
133 	}
134 
135 	if (!z_is_prio_lower_or_equal(prio,
136 				      K_HIGHEST_APPLICATION_THREAD_PRIO)) {
137 		return false;
138 	}
139 
140 	return true;
141 }
142 
z_sched_lock(void)143 static inline void z_sched_lock(void)
144 {
145 	__ASSERT(!arch_is_in_isr(), "");
146 	__ASSERT(arch_current_thread()->base.sched_locked != 1U, "");
147 
148 	--arch_current_thread()->base.sched_locked;
149 
150 	compiler_barrier();
151 }
152 
pended_on_thread(struct k_thread * thread)153 static ALWAYS_INLINE _wait_q_t *pended_on_thread(struct k_thread *thread)
154 {
155 	__ASSERT_NO_MSG(thread->base.pended_on);
156 
157 	return thread->base.pended_on;
158 }
159 
160 
unpend_thread_no_timeout(struct k_thread * thread)161 static inline void unpend_thread_no_timeout(struct k_thread *thread)
162 {
163 	_priq_wait_remove(&pended_on_thread(thread)->waitq, thread);
164 	z_mark_thread_as_not_pending(thread);
165 	thread->base.pended_on = NULL;
166 }
167 
168 /*
169  * In a multiprocessor system, z_unpend_first_thread() must lock the scheduler
170  * spinlock _sched_spinlock. However, in a uniprocessor system, that is not
171  * necessary as the caller has already taken precautions (in the form of
172  * locking interrupts).
173  */
z_unpend_first_thread(_wait_q_t * wait_q)174 static ALWAYS_INLINE struct k_thread *z_unpend_first_thread(_wait_q_t *wait_q)
175 {
176 	struct k_thread *thread = NULL;
177 
178 	__ASSERT_EVAL(, int key = arch_irq_lock(); arch_irq_unlock(key),
179 		      !arch_irq_unlocked(key), "");
180 
181 	LOCK_SCHED_SPINLOCK {
182 		thread = _priq_wait_best(&wait_q->waitq);
183 		if (unlikely(thread != NULL)) {
184 			unpend_thread_no_timeout(thread);
185 			(void)z_abort_thread_timeout(thread);
186 		}
187 	}
188 
189 	return thread;
190 }
191 
192 /*
193  * APIs for working with the Zephyr kernel scheduler. Intended for use in
194  * management of IPC objects, either in the core kernel or other IPC
195  * implemented by OS compatibility layers, providing basic wait/wake operations
196  * with spinlocks used for synchronization.
197  *
198  * These APIs are public and will be treated as contract, even if the
199  * underlying scheduler implementation changes.
200  */
201 
202 /**
203  * Wake up a thread pending on the provided wait queue
204  *
205  * Given a wait_q, wake up the highest priority thread on the queue. If the
206  * queue was empty just return false.
207  *
208  * Otherwise, do the following, in order,  holding _sched_spinlock the entire
209  * time so that the thread state is guaranteed not to change:
210  * - Set the thread's swap return values to swap_retval and swap_data
211  * - un-pend and ready the thread, but do not invoke the scheduler.
212  *
213  * Repeated calls to this function until it returns false is a suitable
214  * way to wake all threads on the queue.
215  *
216  * It is up to the caller to implement locking such that the return value of
217  * this function (whether a thread was woken up or not) does not immediately
218  * become stale. Calls to wait and wake on the same wait_q object must have
219  * synchronization. Calling this without holding any spinlock is a sign that
220  * this API is not being used properly.
221  *
222  * @param wait_q Wait queue to wake up the highest prio thread
223  * @param swap_retval Swap return value for woken thread
224  * @param swap_data Data return value to supplement swap_retval. May be NULL.
225  * @retval true If a thread was woken up
226  * @retval false If the wait_q was empty
227  */
228 bool z_sched_wake(_wait_q_t *wait_q, int swap_retval, void *swap_data);
229 
230 /**
231  * Wakes the specified thread.
232  *
233  * Given a specific thread, wake it up. This routine assumes that the given
234  * thread is not on the timeout queue.
235  *
236  * @param thread Given thread to wake up.
237  * @param is_timeout True if called from the timer ISR; false otherwise.
238  *
239  */
240 void z_sched_wake_thread(struct k_thread *thread, bool is_timeout);
241 
242 /**
243  * Wake up all threads pending on the provided wait queue
244  *
245  * Convenience function to invoke z_sched_wake() on all threads in the queue
246  * until there are no more to wake up.
247  *
248  * @param wait_q Wait queue to wake up the highest prio thread
249  * @param swap_retval Swap return value for woken thread
250  * @param swap_data Data return value to supplement swap_retval. May be NULL.
251  * @retval true If any threads were woken up
252  * @retval false If the wait_q was empty
253  */
z_sched_wake_all(_wait_q_t * wait_q,int swap_retval,void * swap_data)254 static inline bool z_sched_wake_all(_wait_q_t *wait_q, int swap_retval,
255 				    void *swap_data)
256 {
257 	bool woken = false;
258 
259 	while (z_sched_wake(wait_q, swap_retval, swap_data)) {
260 		woken = true;
261 	}
262 
263 	/* True if we woke at least one thread up */
264 	return woken;
265 }
266 
267 /**
268  * Atomically put the current thread to sleep on a wait queue, with timeout
269  *
270  * The thread will be added to the provided waitqueue. The lock, which should
271  * be held by the caller with the provided key, will be released once this is
272  * completely done and we have swapped out.
273  *
274  * The return value and data pointer is set by whoever woke us up via
275  * z_sched_wake.
276  *
277  * @param lock Address of spinlock to release when we swap out
278  * @param key Key to the provided spinlock when it was locked
279  * @param wait_q Wait queue to go to sleep on
280  * @param timeout Waiting period to be woken up, or K_FOREVER to wait
281  *                indefinitely.
282  * @param data Storage location for data pointer set when thread was woken up.
283  *             May be NULL if not used.
284  * @retval Return value set by whatever woke us up, or -EAGAIN if the timeout
285  *         expired without being woken up.
286  */
287 int z_sched_wait(struct k_spinlock *lock, k_spinlock_key_t key,
288 		 _wait_q_t *wait_q, k_timeout_t timeout, void **data);
289 
290 /**
291  * @brief Walks the wait queue invoking the callback on each waiting thread
292  *
293  * This function walks the wait queue invoking the callback function on each
294  * waiting thread while holding _sched_spinlock. This can be useful for routines
295  * that need to operate on multiple waiting threads.
296  *
297  * CAUTION! As a wait queue is of indeterminate length, the scheduler will be
298  * locked for an indeterminate amount of time. This may impact system
299  * performance. As such, care must be taken when using both this function and
300  * the specified callback.
301  *
302  * @param wait_q Identifies the wait queue to walk
303  * @param func   Callback to invoke on each waiting thread
304  * @param data   Custom data passed to the callback
305  *
306  * @retval non-zero if walk is terminated by the callback; otherwise 0
307  */
308 int z_sched_waitq_walk(_wait_q_t *wait_q,
309 		       int (*func)(struct k_thread *, void *), void *data);
310 
311 /** @brief Halt thread cycle usage accounting.
312  *
313  * Halts the accumulation of thread cycle usage and adds the current
314  * total to the thread's counter.  Called on context switch.
315  *
316  * Note that this function is idempotent.  The core kernel code calls
317  * it at the end of interrupt handlers (because that is where we have
318  * a portable hook) where we are context switching, which will include
319  * any cycles spent in the ISR in the per-thread accounting.  But
320  * architecture code can also call it earlier out of interrupt entry
321  * to improve measurement fidelity.
322  *
323  * This function assumes local interrupts are masked (so that the
324  * current CPU pointer and current thread are safe to modify), but
325  * requires no other synchronization.  Architecture layers don't need
326  * to do anything more.
327  */
328 void z_sched_usage_stop(void);
329 
330 void z_sched_usage_start(struct k_thread *thread);
331 
332 /**
333  * @brief Retrieves CPU cycle usage data for specified core
334  */
335 void z_sched_cpu_usage(uint8_t core_id, struct k_thread_runtime_stats *stats);
336 
337 /**
338  * @brief Retrieves thread cycle usage data for specified thread
339  */
340 void z_sched_thread_usage(struct k_thread *thread,
341 			  struct k_thread_runtime_stats *stats);
342 
z_sched_usage_switch(struct k_thread * thread)343 static inline void z_sched_usage_switch(struct k_thread *thread)
344 {
345 	ARG_UNUSED(thread);
346 #ifdef CONFIG_SCHED_THREAD_USAGE
347 	z_sched_usage_stop();
348 	z_sched_usage_start(thread);
349 #endif /* CONFIG_SCHED_THREAD_USAGE */
350 }
351 
352 #endif /* ZEPHYR_KERNEL_INCLUDE_KSCHED_H_ */
353