How an RTOS scheduler decides what runs

Task states, the ready list, the tick and the idle task, shown on two tasks that take turns sleeping.

Blocking and the idle task on FreeRTOS V11.3.3

Simulated kernel: FreeRTOS V11.3.3 and 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 real-time kernel follows one rule: the most urgent task that is able to run is the one that runs. The rest of the scheduler exists to keep track of which tasks are able to run, and to apply the rule again whenever that changes.

The simulator above runs two tasks. Sensor is the more urgent one: it works for one tick, sleeps for four, and does that again. Logger works for two ticks, sleeps for six, then works for two more. Step through it and watch the task cards and the kernel’s lists.

Task states

At any moment a task is in one of a few states.

  • Running: the CPU is executing its code. With one core, exactly one task is running.
  • Ready: it could run, but a more urgent task (or an equally urgent one whose turn it is) has the CPU.
  • Delayed: it asked to sleep until a certain tick.
  • Blocked: it waits for something another task must do, such as releasing a mutex.

A task leaves the running state in two ways. It can give the CPU up by itself, by sleeping or waiting. Or the kernel can take the CPU away because a more urgent task became ready; that is preemption.

The ready list

The kernel keeps the ready tasks in a structure it can search quickly.

FreeRTOS has an array of lists, one per priority, called pxReadyTasksLists, and a variable uxTopReadyPriority that remembers the highest priority that has a ready task. To choose a task it walks down from that priority to the first list that is not empty and takes the next task in it:

    #define taskSELECT_HIGHEST_PRIORITY_TASK()                                       \
do {                                                                                 \
    UBaseType_t uxTopPriority = uxTopReadyPriority;                                  \
                                                                                     \
    /* Find the highest priority queue that contains ready tasks. */                 \
    while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) != pdFALSE ) \
    {                                                                                \
        configASSERT( uxTopPriority );                                               \
        --uxTopPriority;                                                             \
    }                                                                                \
                                                                                     \
    /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \
     * the  same priority get an equal share of the processor time. */                    \
    listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \
    uxTopReadyPriority = uxTopPriority;                                                   \
} while( 0 ) /* taskSELECT_HIGHEST_PRIORITY_TASK */

tasks.c, lines 197–212 · FreeRTOS V11.3.3 · MIT license

Zephyr, in the configuration simulated here, keeps one run queue sorted by priority. The first thread in the queue is the best candidate, and the kernel caches the answer in _kernel.ready_q.cache so the context switch code does not have to search:

static ALWAYS_INLINE struct k_thread *next_up(void)
{
#ifdef CONFIG_SMP
	bool ipi_idle_target_rebound = false;
	struct k_thread *ipi_idle_target = ipi_idle_reserved_take();

	if (z_is_thread_halting(_current)) {
		/* NULL key: scheduler context, no retry possible. _current
		 * cannot have an in-flight timeout (a running thread's
		 * timeout already fired and its handler returned), so the
		 * abort inside halt_thread won't see -EAGAIN.
		 */
		halt_thread(_current, z_is_thread_aborting(_current) ?
				      _THREAD_DEAD : _THREAD_SUSPENDED, NULL);
	}
#endif /* CONFIG_SMP */

	struct k_thread *thread = runq_best();

	thread = metairq_preempt_recover(thread);

#ifndef CONFIG_SMP
	/* In uniprocessor mode, we can leave the current thread in
	 * the queue (actually we have to, otherwise the assembly
	 * context switch code for all architectures would be
	 * responsible for putting it back in z_swap and ISR return!),
	 * which makes this choice simple.
	 */
	return (thread != NULL) ? thread : _current_cpu->idle_thread;
#else
	/* Under SMP, the "cache" mechanism for selecting the next
	 * thread doesn't work, so we have more work to do to test
	 * _current against the best choice from the queue.  Here, the
	 * thread selected above represents "the best thread that is
	 * not current".
	 *
	 * Subtle note on "queued": in SMP mode, neither _current nor
	 * metairq_premepted live in the queue, so this isn't exactly the
	 * same thing as "ready", it means "the thread already been
	 * added back to the queue such that we don't want to re-add it".
	 */
	bool queued = z_is_thread_queued(_current);
	bool active = z_is_thread_ready(_current);

	if (thread == NULL) {
		thread = _current_cpu->idle_thread;
	}

	if (active) {
		int32_t cmp = z_sched_prio_cmp(_current, thread);

		/* Ties only switch if state says we yielded */
		if ((cmp > 0) || ((cmp == 0) && !_current_cpu->swap_ok)) {
			thread = _current;
		}

		if (!should_preempt(thread, _current_cpu->swap_ok)) {
			thread = _current;
		}
	}

	if (thread != _current) {
		update_metairq_preempt(thread);
		/*
		 * Put _current back into the queue unless it is ..
		 * 1. not active (i.e., blocked, suspended, dead), or
		 * 2. already queued, or
		 * 3. the idle thread, or
		 * 4. preempted by a MetaIRQ thread
		 */
		if (active && !queued && !z_is_idle_thread_object(_current)
		    && metairq_current_requeue_allowed()) {
			queue_thread(_current);
		}
	}

	/* Take the new _current out of the queue */
	if (z_is_thread_queued(thread)) {
		/* Remove or transfer the selected thread's idle CPU coverage. */
		if (ipi_idle_target != NULL &&
		    thread != ipi_idle_target &&
		    z_is_thread_queued(ipi_idle_target)) {
			ipi_idle_target_rebound =
				ipi_idle_thread_rebind(thread, ipi_idle_target);
		} else {
			ipi_idle_thread_unreserve(thread);
		}
		dequeue_thread(thread);
	}

	_current_cpu->swap_ok = false;

	/* If this CPU consumed a different thread, preserve coverage for the
	 * runnable thread covered by this CPU's reservation.
	 */
	if (!ipi_idle_target_rebound &&
	    ipi_idle_target != NULL && z_is_thread_queued(ipi_idle_target)) {
		flag_ipi(ipi_mask_create(ipi_idle_target));
	}
	return thread;
#endif /* CONFIG_SMP */
}

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

One detail to keep in mind when you read the numbers on the task cards: in FreeRTOS a higher number is a more urgent priority, in Zephyr a lower number is. Sensor is priority 2 in FreeRTOS and priority 13 in Zephyr; in both it is the more urgent task.

The tick

A hardware timer interrupts the CPU at a fixed rate, 1000 times per second in the simulated configuration. Each interrupt is a tick. The tick handler adds one to the tick count and checks whether any sleeping task is due to wake. If one is, it goes back to the ready list, and the rule from the top of this page is applied again.

In the run above on FreeRTOS, Sensor calls vTaskDelay(4) at tick 1. The kernel removes it from its ready list and puts it in the delayed list with wake-up tick 5. At tick 5 the tick handler moves it back, and because it is more urgent than whatever is running, it runs at once.

Switch the simulator to Zephyr and the same program wakes at tick 6, not 5. Zephyr promises that k_sleep() lasts at least the time asked for. The call can arrive anywhere inside the current tick, so the kernel adds one tick to be sure. FreeRTOS counts tick edges instead, so vTaskDelay(4) lasts between three and four tick periods.

The idle task

At tick 3 both tasks are asleep. The CPU still has to execute something, so every kernel has an idle task (an idle thread in Zephyr) at the lowest priority. It is always ready, so the ready list is never empty and the scheduler never needs a special case for “nothing to run”.

In the timeline, the idle task runs in exactly the ticks where both other lanes are blue. In FreeRTOS the idle task also has a job: it frees the memory of tasks that have deleted themselves. On a real product this is also where the CPU is put to sleep to save power.

What to try

  • Give Logger an urgency of 3. It now preempts Sensor whenever both are ready.
  • Change the step level to Line and step through one tick interrupt to see every line the kernel executes for it.

Next: what happens at the moment a more urgent task wakes up, in Preemption.