The tick and k_sleep in Zephyr

How k_sleep puts a thread on Zephyr's timeout list, why it wakes one tick later than asked, and how the tick announcement wakes it, in the real kernel source.

Blocking and the idle task on Zephyr v4.5.0

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 page follows a sleep through the Zephyr source, as it is in v4.5.0: what k_sleep() does when a thread asks to sleep, and what the tick does to wake it. The scheduling lesson explains the idea. In the simulator above, set the step level to Line and open the Kernel tab of the code panel.

The scenario has two threads. Sensor (priority 13) works for one tick and calls k_sleep(K_TICKS(4)), twice. Logger (priority 14) works for two ticks, sleeps for six and works for two more. In Zephyr a lower number is a more urgent priority.

One list for every kind of waiting

FreeRTOS has delayed lists for tasks. Zephyr has something more general: a single timeout list of struct _timeout entries, each with a function to call when it expires. A sleeping thread is one entry (its function is z_thread_timeout()). A thread waiting for a mutex with a time limit is another. The time slice timer is another, and so are k_timer objects. The simulator’s kernel structures panel shows this list as timeout_list, with the slice timer as slice_timeout.

k_sleep

k_sleep() is an inline function that calls the system call k_sleep_ticks(), which ends up here:

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

At tick 1, Sensor calls it. Reading from the top, past the K_NO_WAIT case (which is a yield):

  1. z_sched_unready_locked(_current) takes Sensor out of the run queue. Taking the running thread out is a reschedule point, so the scheduler also picks the next thread here: Logger. It is recorded as the next to run in _kernel.ready_q.cache; the switch itself comes at the end. Because a different thread will run, Logger gets a fresh time slice, which means the slice timer is removed from the timeout list and added again.
  2. z_add_thread_timeout() adds Sensor’s own entry to the timeout list.
  3. z_mark_thread_as_sleeping() sets a state flag. A sleeping thread is in no list at all except the timeout list; you can see the flag in thread_state on its task card.
  4. z_swap_locked() switches to Logger. For Sensor the call returns when it runs again, and the function works out how many ticks were left (zero unless something woke it early with k_wakeup()).

The extra tick

Every relative timeout goes through 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

The line that matters is the one that computes dticks:

dticks = timeout.ticks + ticks_elapsed + (this_cpu_announcing() ? 0 : 1);

A thread calls k_sleep() at some moment inside a tick. If the kernel counted from the next tick edge, a sleep of 4 could last only a little more than 3 tick periods. Zephyr promises at least the time asked for, so it adds one tick. Sensor asked for 4 at tick 1 and will wake at 1 + 4 + 1 = 6. FreeRTOS does not add the tick, so the same program wakes at tick 5 there; see the FreeRTOS version of this page. In the simulator each call is made right after a tick, so on Zephyr the sleep lasts exactly five periods.

The exception is a timeout added while the tick is being processed. Then “now” is exactly on a tick edge and nothing is added. You will see both cases in the simulator’s notes on the round-up line: Sensor’s slice, set up while the tick wakes it at 6, gets no extra tick; a slice set up from a thread gets one. A slice that z_time_slice() starts again after the timeouts have run gets the extra tick too, but slice_reset() asks for one tick less to cancel it, so it also lasts exactly one tick.

The timeout list stores differences

static inline bool z_timeout_q_insert(struct _timeout *to, k_ticks_t dticks)
{
	struct _timeout *t;

	to->dticks = dticks;
	for (t = z_timeout_q_first(); t != NULL; t = z_timeout_q_next(t)) {
		if (t->dticks > to->dticks) {
			t->dticks -= to->dticks;
			sys_dlist_insert(&t->node, &to->node);
			return z_timeout_q_first() == to;
		}
		to->dticks -= t->dticks;
	}

	sys_dlist_append(&timeout_list, &to->node);
	return z_timeout_q_first() == to;
}

kernel/timeout/list.h, lines 44–60 · Zephyr v4.5.0 · Apache-2.0 license

The list is sorted by expiry, but no entry stores its expiry tick. Each stores dticks, the number of ticks after the entry before it. Insertion walks the list subtracting each entry’s dticks from the new one until it finds a later entry, inserts there, and takes its own remainder off that entry.

At tick 3, Logger goes to sleep for 6 ticks, until tick 10. The list then holds Sensor (expires at 6, dticks 3) and Logger (expires at 10, dticks 4): 3 + 4 = 7 ticks from tick 3. The simulator shows the expiry tick for reading and the stored dticks next to it.

The point of storing differences is the tick: only the first entry has to change.

The tick announcement

On native_sim the system timer interrupt is delivered through posix_irq_handler(). The timer driver’s handler takes the timeout lock and tells the kernel how many ticks have passed (always one here, because the simulated kernel is not tickless):

void sys_clock_announce_locked(uint32_t ticks, k_spinlock_key_t key)
{
	/* We release the lock around the callbacks below, so on SMP
	 * systems someone might be already running the loop.  Don't
	 * race (which will cause parallel execution of "sequential"
	 * timeouts and confuse apps), just increment the tick count
	 * and return.
	 */
	if (IS_ENABLED(CONFIG_SMP) && any_cpu_announcing()) {
		announce_remaining += ticks;
		k_spin_unlock(&timeout_lock, key);
		return;
	}

	announce_remaining = ticks;
	announcing_cpu = CPU_ID;

#ifdef _TIMEOUT_BACKEND_OWNS_ANNOUNCE
	/* The backend (timer wheel) runs the firing loop itself: its per-tick
	 * advance is a bitmap jump over empty ticks and its sift is a
	 * time-driven event with no single timeout to drive a generic loop.
	 * It advances curr_tick / announce_remaining and fires handlers via
	 * the same inflight_timeout dance as below.
	 */
	key = z_timeout_q_announce(key);
#else
	while (announce_remaining > 0) {
		struct _timeout *t;
		int32_t dt = z_timeout_q_next_gap();

		if ((uint32_t)dt > announce_remaining) {
			/* Next event is past this announce window: advance the
			 * backend by the residual ticks without firing anything.
			 */
			dt = (int32_t)announce_remaining;
		}

		/* Advance curr_tick and decrement announce_remaining together
		 * under the lock so non-announcing CPUs observe a consistent
		 * (curr_tick + announce_remaining + sys_clock_elapsed()) ==
		 * T_real even while we drop the lock around handlers. The "we
		 * are announcing" state is carried by announcing_cpu, so
		 * announce_remaining reaching 0 mid-loop is harmless: same-tick
		 * handlers' z_add_timeout() still anchors via
		 * this_cpu_announcing(), and another CPU's announce still folds
		 * into ours via any_cpu_announcing() in the SMP early-return.
		 */
		z_timeout_q_advance(dt);
		curr_tick += dt;
		announce_remaining -= dt;

		/* Drain everything due at the new curr_tick. */
		while ((t = z_timeout_q_pop_due()) != NULL) {
			_timeout_func_t handler = t->fn;

			inflight_timeout = t;

			k_spin_unlock(&timeout_lock, key);
			handler(t);
			key = k_spin_lock(&timeout_lock);
			inflight_timeout = NULL;
		}
	}
#endif /* _TIMEOUT_BACKEND_OWNS_ANNOUNCE */

	announcing_cpu = -1;

	reprogram_next(0);

	k_spin_unlock(&timeout_lock, key);

#ifdef CONFIG_TIMESLICING
	z_time_slice();
#endif /* CONFIG_TIMESLICING */
}

kernel/timeout.c, lines 343–417 · Zephyr v4.5.0 · Apache-2.0 license

The loop advances time towards the next event. z_timeout_q_advance() takes the elapsed ticks off the first entry’s dticks, and curr_tick grows. Then every entry whose dticks is now 0 is removed and its function is called, with the timeout lock released so that the function may add new timeouts. After the loop, z_time_slice() checks whether the running thread’s time slice has run out.

At tick 4 nothing is due: Sensor’s entry goes from dticks 3 to dticks 2 and that is all. Zephyr’s tick count, curr_tick, is 64 bits wide here (CONFIG_TIMEOUT_64BIT), so unlike FreeRTOS it needs no second list for the wrap; see the tick overflow walkthrough.

Waking up

At tick 6, Sensor’s entry reaches 0. Its function runs:

void z_thread_timeout(struct _timeout *timeout)
{
	struct k_thread *thread = CONTAINER_OF(timeout,
					       struct k_thread, base.timeout);

	Z_SCHED_SPINLOCK {
		/* A concurrent waker (e.g. a sem give on another CPU) may
		 * have unpended and readied the thread, after which the
		 * thread could run and re-pend elsewhere -- possibly with no
		 * timeout. Such a waker aborts this timeout, flagging it
		 * superseded; bail so we don't wake the thread from its new
		 * wait.
		 */
		if (!z_timeout_inflight_superseded(timeout)) {
			z_sched_wake_thread_locked(thread);
		}
	}
}

kernel/sched.c, lines 502–519 · Zephyr v4.5.0 · Apache-2.0 license

void z_sched_wake_thread_locked(struct k_thread *thread)
{
	/* No K_SPINLOCK: caller must hold the scheduler's spinlock when calling */
	bool killed = (thread->base.thread_state &
			(_THREAD_DEAD | _THREAD_ABORTING));

	if (!killed) {
		/* The thread is not being killed */
		if (thread->base.pended_on != NULL) {
			unpend_thread_no_timeout(thread);
		}
		z_mark_thread_as_not_sleeping(thread);
		ready_thread(thread);
	}
}

kernel/sched.c, lines 484–498 · Zephyr v4.5.0 · Apache-2.0 license

z_sched_wake_thread_locked() is shared by every kind of timeout on a thread. If the thread was waiting for an object, it is first taken off that object’s wait queue (it gave up waiting). Then it is no longer sleeping, and ready_thread() puts it into the run queue and updates the cache. Sensor is more urgent than the idle thread, so it becomes the next to run; it also gets a new time slice, added from inside the tick and so due one tick later, at 7.

The interrupt handler does the switch on its way out: it compares _kernel.ready_q.cache with _current and calls z_swap_irqlock(). See the context switch in Zephyr.

The time slice timer

Between the sleeps you can watch the other kind of entry. At tick 3, before Logger sleeps, its slice timer is due. slice_timeout() only sets the flag slice_expired; z_time_slice() then finds no other thread of priority 14 to give the CPU to and starts a new slice. The Zephyr scheduler walkthrough follows a slice that does move a thread.

What to try

  • Set the step level to Tick and step from tick 3 to tick 6: the first entry’s dticks counts down, the second never changes.
  • Compare the wake-up ticks with the FreeRTOS page: each wake-up here is one tick later, and so everything after it shifts.