Periodic sleep in Zephyr
How k_sleep with an absolute timeout keeps a periodic thread on a fixed grid, why it gets no extra tick, and what happens when the end of the period has already passed.
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.
The periodic tasks lesson shows why a periodic thread should sleep until
the next period instead of for a fixed time. Zephyr has no xTaskDelayUntil(); the application
keeps the time itself and sleeps to an absolute timeout. In the simulator, Sensor is the
periodic thread:
int64_t next = k_uptime_ticks();
for (;;) {
compute(2);
next += 5;
k_sleep(K_TIMEOUT_ABS_TICKS(next));
}
next is the application’s own variable; the thread’s card shows it. Absolute timeouts need
CONFIG_TIMEOUT_64BIT, which is on by default: ticks are counted in 64 bits and never wrap in
practice.
The starting point
int64_t sys_clock_tick_get(void)
{
uint64_t t = 0U;
K_SPINLOCK(&timeout_lock) {
t = curr_tick + elapsed();
}
return t;
}
kernel/timeout.c, lines 438–446 · Zephyr v4.5.0 · Apache-2.0 license
k_uptime_ticks() returns curr_tick plus the time since the last announced tick, which is zero
when the kernel is not tickless. Sensor reads 0.
The same sleep, a different timeout
At tick 2 Sensor sleeps until tick 5. k_sleep() does exactly what it does
for a relative sleep, described in the tick walkthrough: take the
thread out of the run queue, add a timeout, mark it sleeping, switch.
k_ticks_t z_impl_k_sleep_ticks(k_timeout_t timeout)
{
uint32_t expected_wakeup_ticks;
__ASSERT(!arch_is_in_isr(), "");
SYS_PORT_TRACING_FUNC_ENTER(k_thread, sleep_ticks, timeout);
/* K_NO_WAIT is treated as a 'yield' */
if (K_TIMEOUT_EQ(timeout, K_NO_WAIT)) {
k_yield();
SYS_PORT_TRACING_FUNC_EXIT(k_thread, sleep_ticks, timeout, 0);
return 0;
}
k_spinlock_key_t key = z_sched_spinlock_lock();
#if defined(CONFIG_TIMESLICING) && defined(CONFIG_SWAP_NONATOMIC)
pending_current = _current;
#endif /* CONFIG_TIMESLICING && CONFIG_SWAP_NONATOMIC */
z_sched_unready_locked(_current);
expected_wakeup_ticks = (uint32_t)z_add_thread_timeout(_current, timeout);
z_mark_thread_as_sleeping(_current);
(void)z_swap_locked(key);
/* There is no meaningful remainder to report for K_FOREVER: reaching
* this point at all means a k_wakeup() cut the sleep short.
*/
if (K_TIMEOUT_EQ(timeout, K_FOREVER)) {
SYS_PORT_TRACING_FUNC_EXIT(k_thread, sleep_ticks, timeout, K_TICKS_FOREVER);
return K_TICKS_FOREVER;
}
/* We require a 32 bit unsigned subtraction to handle a wraparound.
* A normal timeout-driven wakeup leaves zero (or a slightly negative)
* remainder; only an early k_wakeup() yields a positive value.
*/
uint32_t left_ticks = expected_wakeup_ticks - sys_clock_tick_get_32();
/* Use signed comparison so past-due wakeups (negative remainder) return 0.
* k_ticks_t may be uint32_t (!CONFIG_TIMEOUT_64BIT), so comparing ticks > 0
* directly would be an unsigned comparison and would misinterpret a negative
* remainder as a large positive value.
*/
int32_t signed_left = (int32_t)left_ticks;
if (signed_left < 0) {
signed_left = 0;
}
SYS_PORT_TRACING_FUNC_EXIT(k_thread, sleep_ticks, timeout, signed_left);
return (k_ticks_t)signed_left;
}
kernel/sleep.c, lines 50–103 · Zephyr v4.5.0 · Apache-2.0 license
The difference is all in z_add_timeout():
k_ticks_t z_add_timeout(struct _timeout *to, _timeout_func_t fn, k_timeout_t timeout)
{
k_ticks_t ticks = 0;
if (K_TIMEOUT_EQ(timeout, K_FOREVER)) {
return 0;
}
#ifdef CONFIG_KERNEL_COHERENCE
__ASSERT_NO_MSG(sys_cache_is_mem_coherent(to));
#endif /* CONFIG_KERNEL_COHERENCE */
__ASSERT(z_is_inactive_timeout(to), "");
to->fn = fn;
K_SPINLOCK(&timeout_lock) {
uint32_t ticks_elapsed = 0;
bool has_elapsed = false;
k_ticks_t dticks;
if (Z_IS_TIMEOUT_RELATIVE(timeout)) {
ticks_elapsed = elapsed();
has_elapsed = true;
/*
* In the general case, "now" may be anywhere within
* the current tick. Rounding up by one tick guarantees
* "at least N ticks" semantics -- otherwise a request
* made partway through a tick would fire on the next
* tick edge, yielding less than N full ticks.
*
* The one moment we know *this* CPU is at a tick edge
* is while it is processing timeouts inside its own
* sys_clock_announce_locked() loop. Periodic timers
* rely on this when rescheduling themselves from the
* timer ISR: the round-up would otherwise accumulate
* and make every period one tick late. The check is
* per-CPU: a thread on another CPU running while we
* announce is *not* at a tick edge and still needs
* the round-up.
*/
dticks = timeout.ticks + ticks_elapsed +
(this_cpu_announcing() ? 0 : 1);
ticks = curr_tick + dticks;
} else {
dticks = Z_TICK_ABS(timeout.ticks) - curr_tick;
dticks = max(1, dticks);
ticks = timeout.ticks;
}
if (z_timeout_q_insert(to, dticks) && !any_cpu_announcing()) {
if (!has_elapsed) {
/* In case of absolute timeout that is first to expire
* elapsed need to be read from the system clock.
*/
ticks_elapsed = elapsed();
}
sys_clock_set_timeout(next_timeout(ticks_elapsed), false);
}
}
return ticks;
}
kernel/timeout.c, lines 176–237 · Zephyr v4.5.0 · Apache-2.0 license
- A relative timeout takes the
Z_IS_TIMEOUT_RELATIVEbranch. Outside the tick’s own processing, “now” may be anywhere inside the current tick, so the kernel adds one tick to make sure the thread sleeps at least the time it asked for. That is the extra tick ofk_sleep(K_TICKS(5)). - An absolute timeout takes the
elsebranch:dticks = Z_TICK_ABS(timeout.ticks) - curr_tick, 5 − 2 = 3. Nothing is added. A point in time is a tick edge, not a length of time, so there is nothing to round.
So Sensor wakes at 5, 10, 15… exactly, while Poll, which sleeps with k_sleep(K_TICKS(5)), gets
6 ticks every time and drifts more than it does on FreeRTOS. Watch the timeout list: Sensor’s
entry stores the 3 ticks of dticks, which is all the list ever keeps.
When the end of the period has passed
Burst wakes at tick 12 and runs until 16. Sensor’s third job, released at 10, has done its work
by tick 12 but is preempted before it reaches its sleep, and the job
misses its deadline at tick 14. At tick 16 it calls
k_sleep(K_TIMEOUT_ABS_TICKS(15)):
dticks= 15 − 16 = −1.dticks = max(1, dticks)makes it 1. A timeout cannot fire in the past or at the current tick, which has already been announced, so it fires on the next tick.Sensorsleeps until tick 17 and starts its fourth job there.
FreeRTOS’s xTaskDelayUntil() would not have slept at all. On Zephyr the thread always gives up the
CPU for at least one tick, which lets the threads it held back run in between, at the price of one
more tick of lateness. Either way the grid survives: the application added exactly one period to
next, so the following wake-ups are 20, 25 and 30.
The kernel does not see the missed deadline: it only sees a timeout in the past. A thread that
needs to know can compare k_uptime_ticks() with next before it sleeps. Zephyr also has
k_timer, a kernel timer that can wake a thread periodically; see
timers in Zephyr.