Preemption

How a kernel takes the CPU from a running task the moment a more urgent one becomes ready.

Preemption 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.

Preemption means the kernel stops the running task, without its cooperation, because a more urgent task has become ready. It is what makes a kernel “real-time”: the response time of an urgent task does not depend on how long the less urgent ones take.

In the simulator above, Low has eight ticks of work and starts at once. High is more urgent and sleeps for the first three ticks.

What happens

On FreeRTOS:

  1. Low runs during ticks 0, 1 and 2.
  2. The tick interrupt at tick 3 finds that High is due. It moves High from the delayed list to its ready list.
  3. High has a higher priority than the running task, so the tick handler asks for a context switch.
  4. High runs during ticks 3 and 4, then ends.
  5. Low carries on from where it was stopped and runs its remaining five ticks.

Low never called the kernel. It was interrupted between two of its own instructions, and when it runs again it cannot tell that anything happened, apart from the time that has passed.

Where the decision is made

The decision is made inside the tick interrupt, not in a task.

In FreeRTOS, xTaskIncrementTick() wakes the task and compares priorities. If the woken task is more urgent than pxCurrentTCB, the function returns true, and the port’s tick handler sets the PendSV interrupt pending. PendSV runs when the tick interrupt is finished: it saves the registers of Low, calls vTaskSwitchContext() to pick the new pxCurrentTCB, and restores the registers of High.

void xPortSysTickHandler( void )
{
    /* The SysTick runs at the lowest interrupt priority, so when this interrupt
     * executes all interrupts must be unmasked.  There is therefore no need to
     * save and then restore the interrupt mask value as its value is already
     * known. */
    portDISABLE_INTERRUPTS();
    traceISR_ENTER();
    {
        /* Increment the RTOS tick. */
        if( xTaskIncrementTick() != pdFALSE )
        {
            traceISR_EXIT_TO_SCHEDULER();

            /* A context switch is required.  Context switching is performed in
             * the PendSV interrupt.  Pend the PendSV interrupt. */
            portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
        }
        else
        {
            traceISR_EXIT();
        }
    }
    portENABLE_INTERRUPTS();
}

portable/GCC/ARM_CM3/port.c, lines 491–515 · FreeRTOS V11.3.3 · MIT license

In Zephyr, waking the thread puts it in the run queue and calls update_cache(), which asks should_preempt() whether the new best thread may replace the current one. The switch itself happens when the interrupt returns.

static ALWAYS_INLINE bool should_preempt(const struct k_thread *thread,
					 int preempt_ok)
{
	/* Preemption is OK if it's being explicitly allowed by
	 * software state (e.g. the thread called k_yield())
	 */
	if (preempt_ok != 0) {
		return true;
	}

	__ASSERT(_current != NULL, "");

	/* Or if we're pended/suspended/dummy (duh) */
	if (z_is_thread_prevented_from_running(_current)) {
		return true;
	}

	/* Otherwise we have to be running a preemptible thread or
	 * switching to a metairq
	 */
	if (thread_is_preemptible(_current) || thread_is_metairq(thread)) {
		return true;
	}

	/* Edge case on ARM where a thread can be pended out of an
	 * interrupt handler before the "synchronous" swap starts
	 * context switching.  Platforms with atomic swap can never
	 * hit this.
	 */
	if (IS_ENABLED(CONFIG_SWAP_NONATOMIC)
	    && z_is_thread_timeout_active(thread)) {
		return true;
	}

	return false;
}

kernel/include/kthread.h, lines 225–260 · Zephyr v4.5.0 · Apache-2.0 license

The third test in that function is worth a look: thread_is_preemptible(_current). A Zephyr thread with a negative priority is cooperative, so for it the test fails and should_preempt() says no (unless the thread itself asked to give up the CPU, the preempt_ok test at the top). It keeps the CPU until it sleeps or yields, whatever else becomes ready. The cooperative threads lesson shows it.

One tick later on Zephyr

Switch the simulator to Zephyr. High now wakes at tick 4 instead of tick 3, for the reason given in the scheduling lesson: a Zephyr sleep lasts at least the ticks asked for, so one tick is added. The preemption itself is the same.

Turning preemption off

FreeRTOS can be built with configUSE_PREEMPTION set to 0. Select FreeRTOS and untick Preemption in the simulator. The tick interrupt still wakes High at tick 3, but no switch is requested. High sits in its ready list until Low gives up the CPU, which here is when Low ends. A cooperative system is simpler to reason about, because a task can only lose the CPU at the points where it calls the kernel, but its worst response time is the longest stretch any task runs without such a call.

Zephyr has no global switch like this. It decides per thread, by the sign of the priority, so the parameter is not offered when Zephyr is selected.

What to try

  • Raise the urgency of Low to 2, the same as High. High still gets the CPU at tick 3, but not by preemption: an equal priority is not a higher one. The tick finds two ready tasks of the running priority, and time slicing takes turns between them.
  • Change the start tick of High and see that the preemption always lands on a tick edge.