The context switch in Zephyr
How Zephyr decides that another thread should run, where it actually switches, and what arch_swap does on the native_sim board, in the real kernel source.
Simulated kernel: Zephyr v4.5.0. This scenario and every other one are in the scheduler playground. The simulator and its data files are not covered by the site's CC BY-SA license; see their license notices.
A context switch stops one thread and resumes another where it
left off. Zephyr splits the job into two parts that happen at different times: deciding which
thread should run, and switching to it. This page reads both in the Zephyr v4.5.0 source. In the
simulator above, set the step level to Line, open the Kernel tab, and watch two variables
under the kernel structures: _current and _kernel.ready_q.cache.
The scenario: Low (priority 14) computes for eight ticks. High (priority 13, more urgent) first
sleeps for three ticks, then computes for two and ends.
Deciding: the cache
_current is the thread the CPU is executing. _kernel.ready_q.cache is the thread that should
be executing. The scheduler code that changes the run queue (a thread
made ready, a thread taken out, a thread moved behind its equals) ends with a call to
update_cache():
static ALWAYS_INLINE void update_cache(int preempt_ok)
{
#ifndef CONFIG_SMP
struct k_thread *thread = next_up();
if (should_preempt(thread, preempt_ok)) {
#ifdef CONFIG_TIMESLICING
if (thread != _current) {
z_time_slice_reset(thread);
}
#endif /* CONFIG_TIMESLICING */
update_metairq_preempt(thread);
_kernel.ready_q.cache = thread;
} else {
_kernel.ready_q.cache = _current;
}
#else
/* The way this works is that the CPU record keeps its
* "cooperative swapping is OK" flag until the next reschedule
* call or context switch. It doesn't need to be tracked per
* thread because if the thread gets preempted for whatever
* reason the scheduler will make the same decision anyway.
*/
_current_cpu->swap_ok = preempt_ok;
#endif /* CONFIG_SMP */
}
kernel/sched.c, lines 167–193 · Zephyr v4.5.0 · Apache-2.0 license
It asks next_up() for the best thread in the run queue (see
how Zephyr chooses the next thread) and then asks
should_preempt() whether that thread may take the CPU from _current:
static ALWAYS_INLINE bool should_preempt(const struct k_thread *thread,
int preempt_ok)
{
/* Preemption is OK if it's being explicitly allowed by
* software state (e.g. the thread called k_yield())
*/
if (preempt_ok != 0) {
return true;
}
__ASSERT(_current != NULL, "");
/* Or if we're pended/suspended/dummy (duh) */
if (z_is_thread_prevented_from_running(_current)) {
return true;
}
/* Otherwise we have to be running a preemptible thread or
* switching to a metairq
*/
if (thread_is_preemptible(_current) || thread_is_metairq(thread)) {
return true;
}
/* Edge case on ARM where a thread can be pended out of an
* interrupt handler before the "synchronous" swap starts
* context switching. Platforms with atomic swap can never
* hit this.
*/
if (IS_ENABLED(CONFIG_SWAP_NONATOMIC)
&& z_is_thread_timeout_active(thread)) {
return true;
}
return false;
}
kernel/include/kthread.h, lines 225–260 · Zephyr v4.5.0 · Apache-2.0 license
The answer is yes if:
- the caller says so (
preempt_ok): the current thread is giving up the CPU itself, by sleeping, waiting, yielding or ending; - the current thread cannot run anyway (it is pending, suspended or dead);
- the current thread is preemptible: not a cooperative thread, and not holding a scheduler lock.
If the answer is yes, the cache gets the new thread (and, with time slicing on, the new thread gets a
fresh slice). If not, the cache keeps _current. Nothing has switched yet. The cache is only a
note: “when you next get the chance, run this one”.
Switching: at a reschedule point
The switch happens at the next reschedule point, where the kernel compares the cache with
_current. There are three kinds in this run.
A thread gives up the CPU. At tick 0, High calls
k_sleep(K_TICKS(3)). z_impl_k_sleep_ticks() takes it out of the run queue (the cache becomes
Low), adds its timeout, and calls z_swap_locked(). A thread that blocks always switches, there
and then.
An interrupt made another thread ready. At tick 4, the tick wakes
High. ready_thread() puts it in the run queue and calls update_cache(): High is more urgent and
Low is preemptible, so the cache becomes High. But the tick is an interrupt, and Zephyr never
switches threads in the middle of an interrupt handler. The switch waits for the way out:
void posix_irq_handler(void)
{
uint64_t irq_lock;
int irq_nbr;
static int may_swap;
irq_lock = hw_irq_ctrl_get_current_lock();
if (irq_lock) {
/* "spurious" wakes can happen with interrupts locked */
return;
}
irq_nbr = hw_irq_ctrl_get_highest_prio_irq();
if (irq_nbr == -1) {
/* This is a phony interrupt during a busy wait, no need for more */
return;
}
if (_kernel.cpus[0].nested == 0) {
may_swap = 0;
}
_kernel.cpus[0].nested++;
do {
int last_current_running_prio = hw_irq_ctrl_get_cur_prio();
int last_running_irq = currently_running_irq;
hw_irq_ctrl_set_cur_prio(hw_irq_ctrl_get_prio(irq_nbr));
hw_irq_ctrl_clear_irq(irq_nbr);
currently_running_irq = irq_nbr;
vector_to_irq(irq_nbr, &may_swap);
currently_running_irq = last_running_irq;
hw_irq_ctrl_set_cur_prio(last_current_running_prio);
} while ((irq_nbr = hw_irq_ctrl_get_highest_prio_irq()) != -1);
_kernel.cpus[0].nested--;
/* Call swap if all the following is true:
* 1) may_swap was enabled
* 2) We are not nesting irq_handler calls (interrupts)
* 3) Next thread to run in the ready queue is not this thread
*/
if (may_swap
&& (hw_irq_ctrl_get_cur_prio() == 256)
&& (_kernel.ready_q.cache) && (_kernel.ready_q.cache != _current)) {
(void)z_swap_irqlock(irq_lock);
}
}
boards/native/native_sim/irq_handler.c, lines 67–120 · Zephyr v4.5.0 · Apache-2.0 license
This is the native_sim board’s model of the interrupt controller. After the handlers have run
(vector_to_irq()), and only if no other interrupt is still being handled, it checks
_kernel.ready_q.cache != _current and calls z_swap_irqlock().
That is where Low stops, in the middle of its work. This is
preemption. On a Cortex-M board the same check happens on interrupt exit
through the PendSV exception, much as in FreeRTOS.
A thread ends. At tick 6, High’s entry function returns, the
kernel aborts the thread, and z_thread_halt() switches to Low, the thread in the cache.
A fourth kind does not switch in this run, but it is the most common in real programs. A kernel call
that makes another thread ready from thread context, such as k_sem_give() or k_mutex_unlock(),
ends with z_reschedule(), which is another name for reschedule():
static void reschedule(struct k_spinlock *lock, k_spinlock_key_t key)
{
if (resched(key.key) && need_swap()) {
z_swap(lock, key);
} else {
signal_pending_ipi();
k_spin_unlock(lock, key);
}
}
kernel/sched.c, lines 403–411 · Zephyr v4.5.0 · Apache-2.0 license
resched() checks that interrupts were enabled when the caller locked them and that the code is not
in an interrupt; need_swap() compares the cache with _current. If both are true, the caller is
switched out right there, inside its own k_sem_give(). Called from an interrupt handler,
resched() is false and the switch is left to the interrupt’s exit, as above. At start-up you can
see one reschedule() that does not switch: when the main thread unlocks the scheduler, it is still
the most urgent thread, so it continues.
arch_swap on native_sim
Every switch ends in the architecture’s arch_swap(). On native_sim, the board the simulator
models and the conformance harness runs on, each Zephyr thread is a thread of the host operating
system, and only one of them is allowed to run at a time:
int arch_swap(unsigned int key)
{
/*
* struct k_thread * _current is the currently running thread
* struct k_thread * _kernel.ready_q.cache contains the next thread to
* run (cannot be NULL)
*
* Here a "real" arch would save all processor registers, stack pointer
* and so forth. But we do not need to do so because we use posix
* threads => those are all nicely kept by the native OS kernel
*/
#if CONFIG_INSTRUMENT_THREAD_SWITCHING
z_thread_mark_switched_out();
#endif
_current->callee_saved.key = key;
_current->callee_saved.retval = -EAGAIN;
/* retval may be modified with a call to
* arch_thread_return_value_set()
*/
posix_thread_status_t *ready_thread_ptr =
(posix_thread_status_t *)
_kernel.ready_q.cache->callee_saved.thread_status;
posix_thread_status_t *this_thread_ptr =
(posix_thread_status_t *)
_current->callee_saved.thread_status;
z_current_thread_set(_kernel.ready_q.cache);
#if CONFIG_INSTRUMENT_THREAD_SWITCHING
z_thread_mark_switched_in();
#endif
/*
* Here a "real" arch would load all processor registers for the thread
* to run. In this arch case, we just block this thread until allowed
* to run later, and signal to whomever is allowed to run to
* continue.
*/
posix_swap(ready_thread_ptr->thread_idx,
this_thread_ptr->thread_idx);
/* When we continue, _kernel->current points back to this thread */
irq_unlock(_current->callee_saved.key);
return _current->callee_saved.retval;
}
arch/posix/core/swap.c, lines 22–71 · Zephyr v4.5.0 · Apache-2.0 license
- It stores the interrupt key and a default return value,
-EAGAIN, in the outgoing thread. z_current_thread_set()makes the cached thread_current. The simulator raises the ContextSwitch event on this line.posix_swap()lets the incoming thread’s host thread continue and blocks the outgoing one. There are no registers to save: as the comment says, the host operating system keeps each thread’s registers and stack. On real hardware this is where they would be saved and restored.- When the outgoing thread is chosen again, possibly much later,
posix_swap()returns in that thread. It unlocks interrupts and returns the stored value.
The return value is how a waiting thread learns why it woke. A thread that sleeps or waits gets
-EAGAIN unless whoever woke it set something else: k_sem_give() wakes a waiter with the value 0,
so the waiter’s k_sem_take() returns 0; a timeout leaves -EAGAIN, and k_sem_take() returns
that.
Decide early, switch late
In FreeRTOS, vTaskSwitchContext() chooses the next task inside the switch itself. Zephyr has
already chosen by the time it switches: arch_swap() only reads the cache. That keeps the
interrupt-exit path short (one comparison) and means that any number of changes inside one interrupt
cost one switch at most. Compare the context switch in FreeRTOS,
where every switch goes through the PendSV handler.
What to try
- Step through tick 4 at the Line level and watch the two variables: the cache becomes
Highinupdate_cache(), several lines before_currentdoes inarch_swap(). - Set the step level to Event. Switches 2 and 4 come from
High’s own calls; switch 3 comes from the interrupt exit.