From 1ef647f396d8c26475807b6424b3269455c41411 Mon Sep 17 00:00:00 2001 From: Jordan Yates Date: Sat, 26 Mar 2022 09:55:23 +1000 Subject: [PATCH] kernel: add `k_can_yield` helper function Implements a function that application and driver code can use to check whether it is valid to yield (or block) in the current context. This check is required for functions that can feasibly be run from multiple contexts. The primary intended use case is power management transition functions, which can be run by application code explicitly or automatically in the idle thread by system PM. Signed-off-by: Jordan Yates --- include/zephyr/kernel.h | 13 +++++++++++++ kernel/sched.c | 6 ++++++ 2 files changed, 19 insertions(+) diff --git a/include/zephyr/kernel.h b/include/zephyr/kernel.h index 2bfa9af5a09..db5b3cd4d6d 100644 --- a/include/zephyr/kernel.h +++ b/include/zephyr/kernel.h @@ -464,6 +464,19 @@ __syscall int32_t k_usleep(int32_t us); */ __syscall void k_busy_wait(uint32_t usec_to_wait); +/** + * @brief Check whether it is possible to yield in the current context. + * + * This routine checks whether the kernel is in a state where it is possible to + * yield or call blocking API's. It should be used by code that needs to yield + * to perform correctly, but can feasibly be called from contexts where that + * is not possible. For example in the PRE_KERNEL initialization step, or when + * being run from the idle thread. + * + * @return True if it is possible to yield in the current context, false otherwise. + */ +bool k_can_yield(void); + /** * @brief Yield the current thread. * diff --git a/kernel/sched.c b/kernel/sched.c index af51bd907d1..9454117c579 100644 --- a/kernel/sched.c +++ b/kernel/sched.c @@ -1362,6 +1362,12 @@ static inline void z_vrfy_k_thread_deadline_set(k_tid_t tid, int deadline) #endif #endif +bool k_can_yield(void) +{ + return !(k_is_pre_kernel() || k_is_in_isr() || + z_is_idle_thread_object(_current)); +} + void z_impl_k_yield(void) { __ASSERT(!arch_is_in_isr(), "");