Suspending, resuming and ending a thread in Zephyr
How k_thread_suspend and k_thread_resume set and clear one bit of a thread's state, why a suspended thread keeps its timeout, and how a thread whose entry function returns is halted at once.
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.
This walkthrough follows Worker through Zephyr’s kernel/thread.c and kernel/sched.c while
Supervisor suspends it, resumes it, and both threads end. The
task states lesson explains what the states mean. Here we look at how
the kernel records them. Set the step level to Line and open the Kernel tab of the code
panel.
The two threads:
Worker(priority 14) works for three ticks, sleeps for two, waits for the semaphoreS, and works one more tick.Supervisor(priority 13) sleeps for one tick and works for one. Then it callsk_thread_suspend()onWorker, works one more tick and callsk_thread_resume(). Then it sleeps for five ticks, givesSand works a last tick.
A state is a set of bits
FreeRTOS knows a task’s state by the list its xStateListItem is in. Zephyr keeps the state in the
thread itself, as bits of base.thread_state. The task card shows them as thread_state, without
the _THREAD_ prefix. The ones that matter here:
_THREAD_QUEUED: the thread is in the run queue._THREAD_SLEEPING: it waits for its timeout, as ink_sleep()._THREAD_PENDING: it waits in an object’s wait queue._THREAD_SUSPENDED: it was suspended._THREAD_DEAD: it has ended.
A thread may run only if none of the last four is set. z_is_thread_prevented_from_running() tests
them all in one mask. The bits are independent of each other, so a thread can be asleep and
suspended at the same time. That turns out to matter.
Suspending another thread
At tick 3, Supervisor calls k_thread_suspend(Worker). Worker is
ready. Supervisor preempted it at tick 2, with one tick of its work left.
void z_impl_k_thread_suspend(k_tid_t thread)
{
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, suspend, thread);
/* Special case "suspend the current thread" as it doesn't
* need the async complexity below.
*/
if (!IS_ENABLED(CONFIG_SMP) &&
likely((thread == _current) && !arch_is_in_isr())) {
z_thread_suspend_current(thread);
return;
}
k_spinlock_key_t key = z_sched_spinlock_lock();
if (unlikely(z_is_thread_suspended(thread))) {
/* The target thread is already suspended. Nothing to do. */
z_sched_spinlock_unlock(key);
return;
}
z_thread_halt(thread, key, false);
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, suspend, thread);
}
kernel/thread.c, lines 1683–1709 · Zephyr v4.5.0 · Apache-2.0 license
Read it from the top:
- A thread that suspends itself takes a shortcut (below).
Workeris not the caller. - A thread that is already suspended is left alone.
- Everything else goes to
z_thread_halt(thread, key, false). That is the function that also ends a thread.falsemeans “suspend, don’t terminate”.
On one CPU, z_thread_halt() calls halt_thread() with the new state _THREAD_SUSPENDED:
static ALWAYS_INLINE void halt_thread(struct k_thread *thread, uint8_t new_state,
k_spinlock_key_t *key)
{
bool dummify = false;
/* We hold the lock, and the thread is known not to be running
* anywhere.
*/
if ((thread->base.thread_state & new_state) == 0U) {
thread->base.thread_state |= new_state;
if (z_is_thread_queued(thread)) {
/* Clear idle CPU coverage before removing the thread from the run queue. */
ipi_idle_thread_unreserve(thread);
dequeue_thread(thread);
}
if (new_state == _THREAD_DEAD) {
if (thread->base.pended_on != NULL) {
unpend_thread_no_timeout(thread);
}
/* Wait for any in-flight handler to complete before
* we proceed: the caller may free this thread's
* storage (dynamic threads), and an in-flight handler
* would UAF when it eventually runs z_thread_timeout()
* and dereferences thread->base. _THREAD_DEAD is
* already set, so once the handler runs it bails via
* z_sched_wake_thread_locked()'s killed check.
*
* NULL key is the next_up() self-halt path on a
* running _current that has no linked timeout; there
* is nothing to do here. That path is always reached
* via z_thread_halt()'s IF branch, which spins on
* z_try_abort_thread_timeout(thread) outside any lock
* after the halt-queue wait completes, closing any
* remaining in-flight window before the caller of
* z_thread_halt() returns.
*/
if (key != NULL) {
while (z_try_abort_thread_timeout(thread) == -EAGAIN) {
z_sched_spinlock_unlock(*key);
*key = z_sched_spinlock_lock();
}
}
unpend_all(&thread->join_queue);
/* Edge case: aborting _current from within an
* ISR that preempted it requires clearing the
* _current pointer so the upcoming context
* switch doesn't clobber the now-freed
* memory
*/
if (thread == _current && arch_is_in_isr()) {
dummify = true;
}
}
#ifdef CONFIG_SMP
unpend_all(&thread->halt_queue);
#endif /* CONFIG_SMP */
update_cache(1);
if (new_state == _THREAD_SUSPENDED) {
clear_halting(thread);
return;
}
arch_coprocessors_disable(thread);
SYS_PORT_TRACING_FUNC(k_thread, sched_abort, thread);
z_thread_monitor_exit(thread);
#ifdef CONFIG_THREAD_ABORT_HOOK
thread_abort_hook(thread);
#endif /* CONFIG_THREAD_ABORT_HOOK */
#ifdef CONFIG_OBJ_CORE_THREAD
#ifdef CONFIG_OBJ_CORE_STATS_THREAD
k_obj_core_stats_deregister(K_OBJ_CORE(thread));
#endif /* CONFIG_OBJ_CORE_STATS_THREAD */
k_obj_core_unlink(K_OBJ_CORE(thread));
#endif /* CONFIG_OBJ_CORE_THREAD */
#ifdef CONFIG_USERSPACE
z_mem_domain_exit_thread(thread);
k_thread_perms_all_clear(thread);
k_object_uninit(thread->stack_obj);
k_object_uninit(thread);
#endif /* CONFIG_USERSPACE */
#ifdef CONFIG_THREAD_ABORT_NEED_CLEANUP
k_thread_abort_cleanup(thread);
#endif /* CONFIG_THREAD_ABORT_NEED_CLEANUP */
/* Do this "set _current to dummy" step last so that
* subsystems above can rely on _current being
* unchanged. Disabled for posix as that arch
* continues to use the _current pointer in its swap
* code. Note that we must leave a non-null switch
* handle for any threads spinning in join() (this can
* never be used, as our thread is flagged dead, but
* it must not be NULL otherwise join can deadlock).
* Use 1 as a clearly invalid but non-NULL value.
*/
if (dummify && !IS_ENABLED(CONFIG_ARCH_POSIX)) {
#ifdef CONFIG_USE_SWITCH
_current->switch_handle = (void *)1;
#endif
#ifdef CONFIG_SPIN_VALIDATE
/* On arches where exceptions run as ISRs (e.g. Xtensa),
* the dying thread's lock tracking is never cleared via the
* normal abort path. Reset it here before _thread_dummy
* takes over. Sentinel-gated so genuine bugs still assert.
*/
if (thread->base.swap_data ==
(void *)&z_spinlock_abort_sentinel) {
z_spin_validate_reset(true);
}
#endif
z_dummy_thread_init(&_thread_dummy);
}
/* Finally update the halting thread state, on which
* other CPUs might be spinning (see
* thread_halt_spin()).
*/
clear_halting(thread);
}
}
kernel/sched.c, lines 856–983 · Zephyr v4.5.0 · Apache-2.0 license
For a suspend, only the first lines run. The function sets the bit and calls dequeue_thread()
because Worker is in the run queue. Then update_cache(1) picks the next thread to run, and the
function returns at the _THREAD_SUSPENDED test. Everything after that is for threads that end.
Back in z_thread_halt(), Worker is not the running thread, so nothing switches. Supervisor
carries on.
Note what a suspend does not do. It does not cancel the thread’s timeout, and it does not take
the thread out of a wait queue. If Worker had been asleep, its timeout would still fire. The
timeout handler clears _THREAD_SLEEPING and calls ready_thread(). ready_thread() sees the
suspended bit and leaves the thread out of the run queue. The same happens if a thread is suspended
while it waits for an object: it can still be given the object, but it does not run until it is
resumed. FreeRTOS’s vTaskSuspend() is different. It removes the task from the delayed list and
from any event list and puts it in xSuspendedTaskList, so the delay or the wait is cancelled. See
the FreeRTOS walkthrough.
Suspending yourself
A thread that suspends itself goes through a shorter path:
void z_thread_suspend_current(struct k_thread *thread)
{
k_spinlock_key_t key = z_sched_spinlock_lock();
z_mark_thread_as_suspended(thread);
z_metairq_preempted_clear(thread);
dequeue_thread(thread);
update_cache(1);
z_swap_locked(key);
}
kernel/sched.c, lines 985–994 · Zephyr v4.5.0 · Apache-2.0 license
The running thread is in no wait queue and runs on no other CPU, so the function only marks it, takes it out of the run queue, picks the next thread and switches. The shortcut is taken only outside interrupts and on a single CPU. Nothing in this scenario suspends itself.
Resuming
At tick 4, Supervisor calls k_thread_resume(Worker):
void z_impl_k_thread_resume(k_tid_t thread)
{
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_thread, resume, thread);
k_spinlock_key_t key = z_sched_spinlock_lock();
/* Do not try to resume a thread that was not suspended */
if (unlikely(!z_is_thread_suspended(thread))) {
z_sched_spinlock_unlock(key);
return;
}
z_mark_thread_as_not_suspended(thread);
z_sched_ready_locked(thread);
z_reschedule_locked(key);
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_thread, resume, thread);
}
kernel/thread.c, lines 1720–1738 · Zephyr v4.5.0 · Apache-2.0 license
It clears the bit and calls z_sched_ready_locked(), another name for ready_thread():
static inline void ready_thread(struct k_thread *thread)
{
#ifdef CONFIG_KERNEL_COHERENCE
__ASSERT_NO_MSG(sys_cache_is_mem_coherent(thread));
#endif /* CONFIG_KERNEL_COHERENCE */
/* If thread is queued already, do not try and added it to the
* run queue again
*/
if (!z_is_thread_queued(thread) && z_is_thread_ready(thread)) {
SYS_PORT_TRACING_OBJ_FUNC(k_thread, sched_ready, thread);
queue_thread(thread);
update_cache(0);
flag_ipi(ipi_mask_create(thread));
}
}
kernel/sched.c, lines 218–235 · Zephyr v4.5.0 · Apache-2.0 license
ready_thread() only queues a thread that is not queued and that z_is_thread_ready() accepts. A
thread resumed while it still sleeps or waits stays out of the run queue until that ends too.
Worker has no other bit set, so it goes to the end of the run queue for priority 14.
z_reschedule_locked() then asks whether to switch. Worker is less urgent than Supervisor, so
the answer is no. A resumed thread is only ready. It runs when it is the most urgent. Here that
is later in the same tick, when Supervisor calls k_sleep(). Worker then does its last tick
of work (tick 4) from where it was stopped, as if nothing had happened.
Ending a thread
The simulator’s threads end the usual Zephyr way: their entry function returns. A thread does not
start in its entry function. It starts in z_thread_entry(), which calls the entry function and
handles the return:
FUNC_NORETURN void z_thread_entry(k_thread_entry_t entry,
void *p1, void *p2, void *p3)
{
/*
* Inform the unwinder that the current return address is undefined.
*
* This is typically used at points in the code where execution does not
* return like a normal function (for example, thread entry routines).
* Marking the return address as undefined prevents stack unwinding or
* backtrace tools from following a bogus return address, which could
* otherwise lead to reading invalid memory and cause faults during
* unwinding or debugging.
*/
ARCH_CFI_UNDEFINED_RETURN_ADDRESS();
#ifdef CONFIG_CURRENT_THREAD_USE_TLS
z_tls_current = k_sched_current_thread_query();
#endif
#ifdef CONFIG_STACK_CANARIES_TLS
uintptr_t stack_guard;
sys_rand_get((uint8_t *)&stack_guard, sizeof(stack_guard));
__stack_chk_guard = stack_guard;
__stack_chk_guard <<= 8;
#endif /* CONFIG_STACK_CANARIES_TLS */
entry(p1, p2, p3);
k_thread_abort(k_current_get());
/*
* Compiler can't tell that k_thread_abort() won't return and issues a
* warning unless we tell it that control never gets this far.
*/
CODE_UNREACHABLE; /* LCOV_EXCL_LINE */
}
kernel/sys/thread_entry.c, lines 36–70 · Zephyr v4.5.0 · Apache-2.0 license
k_thread_abort() on the running thread ends up in z_thread_abort():
void z_thread_abort(struct k_thread *thread)
{
bool essential = z_is_thread_essential(thread);
k_spinlock_key_t key = z_sched_spinlock_lock();
if (z_is_thread_dead(thread)) {
z_sched_spinlock_unlock(key);
return;
}
z_thread_halt(thread, key, true);
if (essential) {
__ASSERT(!essential, "aborted essential thread %p", thread);
k_panic();
}
}
kernel/thread.c, lines 1774–1790 · Zephyr v4.5.0 · Apache-2.0 license
It returns at once if the thread is already dead. Otherwise it calls z_thread_halt(), this time
with true:
void z_thread_halt(struct k_thread *thread, k_spinlock_key_t key,
bool terminate)
{
_wait_q_t *wq = &thread->join_queue;
#ifdef CONFIG_SMP
wq = terminate ? wq : &thread->halt_queue;
#endif
z_metairq_preempted_clear(thread);
/* If the target is a thread running on another CPU, flag and
* poke (note that we might spin to wait, so a true
* synchronous IPI is needed here, not deferred!), it will
* halt itself in the IPI. Otherwise it's unscheduled, so we
* can clean it up directly.
*/
struct _cpu *cpu = thread_active_elsewhere(thread);
if (cpu != NULL) {
thread->base.thread_state |= (terminate ? _THREAD_ABORTING
: _THREAD_SUSPENDING);
#if defined(CONFIG_SMP) && defined(CONFIG_SCHED_IPI_SUPPORTED)
#ifdef CONFIG_ARCH_HAS_DIRECTED_IPIS
arch_sched_directed_ipi(IPI_CPU_MASK(cpu->id));
#else
arch_sched_broadcast_ipi();
#endif /* CONFIG_ARCH_HAS_DIRECTED_IPIS */
#endif /* CONFIG_SMP && CONFIG_SCHED_IPI_SUPPORTED */
if (arch_is_in_isr()) {
thread_halt_spin(thread, key);
} else {
add_to_waitq_locked(_current, wq);
z_swap_locked(key);
}
/* The target's next_up self-halt path passed NULL to
* halt_thread() and could not retry on -EAGAIN; an
* in-flight handler on a third CPU may not have run yet
* (it is blocked on the scheduler spinlock and will only
* acquire it after we drop it via the swap/spin above). Wait
* now, outside any lock, before the caller may free the thread
* storage. The handler, when it runs, sees _THREAD_DEAD /
* _THREAD_SUSPENDED and either bails (killed check) or
* no-ops in ready_thread() (z_is_thread_ready() rejects
* suspended threads). After this loop returns, no further
* dereference of thread->base will occur.
*/
while (z_try_abort_thread_timeout(thread) == -EAGAIN) {
}
} else {
halt_thread(thread, terminate ? _THREAD_DEAD : _THREAD_SUSPENDED, &key);
if ((thread == _current) && !arch_is_in_isr()) {
if (z_is_thread_essential(thread)) {
z_sched_spinlock_unlock(key);
k_panic();
key = z_sched_spinlock_lock();
}
z_swap_locked(key);
__ASSERT(!terminate, "aborted _current back from dead");
} else {
z_sched_spinlock_unlock(key);
}
}
/* NOTE: the scheduler lock has been released. Don't put
* logic here, it's likely to be racy/deadlocky even if you
* re-take the lock!
*/
}
kernel/sched.c, lines 307–374 · Zephyr v4.5.0 · Apache-2.0 license
The cpu != NULL branch is for a thread that runs on another CPU. With one CPU, halt_thread()
runs with _THREAD_DEAD. This time it goes all the way through:
- It sets the bit and takes the thread out of the run queue.
- If the thread was waiting in an object’s wait queue, it takes it out (not the case here). It cancels its timeout.
unpend_all(&thread->join_queue)wakes every thread waiting ink_thread_join()for this one. Nobody joins here.update_cache(1)picks the next thread. The rest is bookkeeping for optional features: thread monitoring, object cores, user-mode permissions.
Back in z_thread_halt(), the dead thread is the running one, so z_swap_locked() switches away.
It never returns: the __ASSERT after it says so.
The first time is tick 11. Supervisor returns from its entry function
and Worker runs. Supervisor had given S at tick 10, and k_sem_give() had already handed the
semaphore to Worker, so Worker’s k_sem_take() returns 0 at once. Worker works one tick and
ends at tick 12, the same way. The idle thread runs.
No cleanup afterwards
That is all. The kernel never frees a thread: its struct k_thread and its stack belong to the
application, statically with K_THREAD_DEFINE() or passed in to k_thread_create(). Once
k_thread_join() has returned, the application may reuse or free them. There is no later step and
no list of threads waiting to be cleaned up. The one exception is MMU systems with
CONFIG_THREAD_STACK_MEM_MAPPED. There, a thread that aborts itself has its stack unmapped later,
at the next abort.
FreeRTOS works the other way. A task that deletes itself cannot free the stack it is running on.
vTaskDelete() moves it to xTasksWaitingTermination, and the idle task frees its TCB and stack
later. That is why a FreeRTOS program that deletes tasks must let the idle task run.
One tick later than FreeRTOS
Switch to FreeRTOS and compare the timeline. There, Supervisor wakes at tick 1, suspends Worker
at 2 and resumes it at 3, and the threads end at 9 and 10. Zephyr adds a tick to every relative
sleep so that it lasts at least as long as asked (see scheduling).
Supervisor sleeps once before the suspend and once more before it gives S. So the suspend
comes one tick later on Zephyr, and the end two ticks later.
What to try
- Set Supervisor urgency to 1, the same as
Worker.Supervisorcan no longer preempt, so the two take turns by time slice.Supervisoronly reachesk_thread_suspend()at tick 4, afterWorkerhas done all three ticks of its work. Everything after that comes a tick later, and both threads end at tick 13. - Set Supervisor starts at tick to 3.
Workeris asleep until tick 6 whenSupervisorsuspends it at tick 5, and its card showssleeping | suspended. Step by Line through tick 6.Worker’s timeout still fires, but the kernel leaves it out of the run queue because it is suspended.Supervisor’sk_thread_resume(), later in the same tick, puts it back.