Timers in Zephyr

How a k_timer is a timeout in the same list as every sleeping thread, how its expiry function runs inside the tick interrupt, and how its period is kept from drifting.

Software timers 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 walkthrough follows the software timers lesson through Zephyr’s kernel/timer.c. Where FreeRTOS gives timers a task of their own, a Zephyr timer is only an entry in the kernel’s timeout list, the same list that wakes sleeping threads. Set the step level to Line to follow it.

What a timer is

K_TIMER_DEFINE(Blink, Blink_expiry, NULL) defines a struct k_timer at build time. The fields that matter here are on the timer card in the kernel panel:

  • timeout: a struct _timeout, the entry it puts in the timeout list.
  • period: how long until the next expiry after one has happened; K_NO_WAIT for a one-shot timer.
  • status: how many times it has expired since it was started (or since k_timer_status_get() last read it).
  • expiry_fn and stop_fn: the functions called when it expires and when it is stopped. Here stop_fn is NULL.
  • wait_q: threads blocked in k_timer_status_sync() until the next expiry. Nobody waits here.

Starting it

main() calls k_timer_start(&Blink, K_TICKS(4), K_TICKS(4)): the first expiry 4 ticks from now, then every 4 ticks. Zephyr’s main thread runs main() after it has started the static threads, at tick 0.

void z_impl_k_timer_start(struct k_timer *timer, k_timeout_t duration,
			  k_timeout_t period)
{
	SYS_PORT_TRACING_OBJ_FUNC(k_timer, start, timer, duration, period);

	if (K_TIMEOUT_EQ(duration, K_FOREVER)) {
		return;
	}

	/* Hold the timer lock across abort + add to serialize against a
	 * concurrent k_timer_start on the same timer. An in-flight handler
	 * (z_try_abort_timeout() returning non-zero) is flagged superseded
	 * and will bail; the re-arm below also re-links the node, which
	 * makes a not-yet-committed handler bail too. Either way we do not
	 * wait for it.
	 */
	k_spinlock_key_t key = k_spin_lock(&timer_lock);

	(void)z_try_abort_timeout(&timer->timeout);

	timer->period = period;
	timer->status = 0U;

	z_add_timeout(&timer->timeout, z_timer_expiration_handler, duration);

	z_timer_observer_on_start(timer, duration, period);

	k_spin_unlock(&timer_lock, key);
}

kernel/timer.c, lines 252–280 · Zephyr v4.5.0 · Apache-2.0 license

A timer that is running is first taken out of the timeout list by z_try_abort_timeout(), so starting it again restarts it. Then z_add_timeout() puts its timeout in the list, exactly as a thread’s k_sleep() does:

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 duration is relative and the call comes from a thread, which may be anywhere inside the current tick, so one tick is added to make the wait at least 4 full ticks: the timer is due at 0 + 4 + 1 = 5. The timeout list in the kernel panel shows Blink beside the threads that sleep, each entry with the ticks it waits after the entry before it (dticks).

Expiring

At tick 5 the timer interrupt calls sys_clock_announce(). It moves the tick count on and calls the handler of every timeout that is now due:

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

For a timer the handler is z_timer_expiration_handler(), and it runs right there, in the interrupt:

void z_timer_expiration_handler(struct _timeout *t)
{
	struct k_timer *timer = CONTAINER_OF(t, struct k_timer, timeout);
	struct k_thread *thread;
	k_spinlock_key_t key = k_spin_lock(&timer_lock);

	/* A same-CPU IRQ may have raced with our dispatch between
	 * sys_clock_announce() popping us off the queue and us taking
	 * timer.c::lock. Two cases:
	 *  - The timer was restarted (z_add_timeout re-queued the timeout):
	 *    it is active again, and the new schedule fires later.
	 *  - The timer was stopped (z_try_abort_timeout marked the
	 *    in-flight slot superseded): bail without firing expiry_fn.
	 */
	if (!z_is_inactive_timeout(t) ||
	    z_timeout_inflight_superseded(t)) {
		k_spin_unlock(&timer_lock, key);
		return;
	}

	/*
	 * if the timer is periodic, start it again; don't add _TICK_ALIGN
	 * since we're already aligned to a tick boundary
	 */
	if (!K_TIMEOUT_EQ(timer->period, K_NO_WAIT) &&
	    !K_TIMEOUT_EQ(timer->period, K_FOREVER)) {
		k_timeout_t next = timer->period;

#ifdef CONFIG_TIMEOUT_64BIT
		/* Exploit the fact that uptime during a kernel
		 * timeout handler reflects the time of the scheduled
		 * event and not real time to get some inexpensive
		 * protection against late interrupts.  If we're
		 * delayed for any reason, we still end up calculating
		 * the next expiration as a regular stride from where
		 * we "should" have run.  Requires absolute timeouts.
		 */
		next = K_TIMEOUT_ABS_TICKS(k_uptime_ticks() + next.ticks);
#endif /* CONFIG_TIMEOUT_64BIT */
		z_add_timeout(&timer->timeout, z_timer_expiration_handler,
			      next);
	}

	/* update timer's status */
	timer->status += 1U;

	z_timer_observer_on_expiry(timer);

	/* invoke timer expiry function */
	if (timer->expiry_fn != NULL) {
		k_timer_expiry_t expiry_fn = timer->expiry_fn;

		/* Unlock for user handler. */
		k_spin_unlock(&timer_lock, key);

		SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_timer, expiry, timer);

		expiry_fn(timer);

		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_timer, expiry, timer);

		key = k_spin_lock(&timer_lock);
	}

	if (!IS_ENABLED(CONFIG_MULTITHREADING)) {
		k_spin_unlock(&timer_lock, key);
		return;
	}

	LOCK_SCHED_SPINLOCK {
		thread = z_waitq_head_locked(&timer->wait_q);

		if (thread != NULL) {
			unpend_thread_no_timeout(thread);
			arch_thread_return_value_set(thread, 0);
			z_sched_ready_locked(thread);
		}
	}

	k_spin_unlock(&timer_lock, key);

}

kernel/timer.c, lines 72–153 · Zephyr v4.5.0 · Apache-2.0 license

  1. The period is not K_NO_WAIT, so the timer is started again first. With CONFIG_TIMEOUT_64BIT the next expiry is an absolute tick: the uptime plus the period. Inside the tick’s processing, the uptime is exactly the tick the timer was due (5), so the next expiry is tick 9, with no extra tick. If the interrupt itself came late, the timer would still keep its rhythm.
  2. status counts the expiry.
  3. expiry_fn runs: Blink_expiry() gives S. It is an interrupt handler, so k_sem_give() readies Handler and hands it the semaphore, but does not switch threads.
  4. Any thread in k_timer_status_sync() would be woken now.

The switch to Handler comes when the interrupt returns, in posix_irq_handler(), as for any interrupt. At tick 9 the same happens while Worker runs, and Handler, less urgent, waits for it.

So the first expiry gets the extra tick, because the timer was started from a thread, and the later ones do not: Blink expires at 5, 9 and 13, every 4 ticks after the first. On FreeRTOS the same program expires at 4, 8 and 12.

Stopping it

Keys sleeps until tick 13 (plus the extra tick: it wakes at 14) and calls k_timer_stop():

void z_impl_k_timer_stop(struct k_timer *timer)
{
	SYS_PORT_TRACING_OBJ_FUNC(k_timer, stop, timer);

	k_spinlock_key_t key = k_spin_lock(&timer_lock);

	if (z_try_abort_timeout(&timer->timeout) != 0) {
		/* Not removed from the queue: either the timer was not
		 * active, or its handler is in flight. In the latter case
		 * z_try_abort_timeout() has flagged it superseded so the
		 * handler bails; we do not wait for it. Nothing to stop here.
		 */
		k_spin_unlock(&timer_lock, key);
		return;
	}

	z_timer_observer_on_stop(timer);

	if (timer->stop_fn != NULL) {
		SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_timer, stop_fn_expiry, timer);
		k_spin_unlock(&timer_lock, key);

		timer->stop_fn(timer);

		key = k_spin_lock(&timer_lock);

		SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_timer, stop_fn_expiry, timer);
	}

	if (!IS_ENABLED(CONFIG_MULTITHREADING)) {
		k_spin_unlock(&timer_lock, key);
		return;

	}

	struct k_thread *pending_thread = z_unpend1_no_timeout(&timer->wait_q);

	if (pending_thread != NULL) {
		z_ready_thread(pending_thread);
		z_reschedule(&timer_lock, key);
	} else {
		k_spin_unlock(&timer_lock, key);
	}
}

kernel/timer.c, lines 293–336 · Zephyr v4.5.0 · Apache-2.0 license

z_try_abort_timeout() takes the timeout out of the list, and the expiry that was due at tick 17 is gone. A timer that was not running is left alone. With a stop_fn, it would be called now, in the stopping thread; then any thread in k_timer_status_sync() is woken, since the timer will not expire again.

What it costs, and what it buys

A timer costs one struct k_timer and no thread. Its expiry function runs in the timer interrupt, so it runs on time whatever the threads are doing, and nothing is queued or delayed behind a busy task. The price is that it runs with the restrictions of an interrupt handler: it must not block, and it delays every thread and every other timeout due on that tick. Work that takes time belongs in a thread, which the expiry function wakes, as Blink_expiry() does by giving S. For work that must run in a thread, Zephyr also has the system work queue: k_work_schedule() runs a function after a delay in the work queue’s thread, which is close to what FreeRTOS’s timer service task does.