xTaskDelayUntil in FreeRTOS

How xTaskDelayUntil keeps a periodic task on a fixed grid of wake-up times, and what it does when the task overruns its period.

Periodic tasks and deadlines on FreeRTOS V11.3.3

Simulated kernel: FreeRTOS V11.3.3. 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 task should sleep until the next period instead of for a fixed time. This walkthrough reads the FreeRTOS function that does it. In the simulator, Sensor is the periodic task:

TickType_t xLastWakeTime = xTaskGetTickCount();
for( ;; )
{
    vCompute( 2 );
    xTaskDelayUntil( &xLastWakeTime, 5 );
}

xLastWakeTime belongs to the application, not to the kernel: the task keeps it on its own stack and passes its address. The task card shows it, next to the kernel’s own fields.

The starting point

TickType_t xTaskGetTickCount( void )
{
    TickType_t xTicks;

    traceENTER_xTaskGetTickCount();

    /* Critical section required if running on a 16 bit processor. */
    portTICK_TYPE_ENTER_CRITICAL();
    {
        xTicks = xTickCount;
    }
    portTICK_TYPE_EXIT_CRITICAL();

    traceRETURN_xTaskGetTickCount( xTicks );

    return xTicks;
}

tasks.c, lines 4213–4229 · FreeRTOS V11.3.3 · MIT license

The first period is counted from the moment the task reads the tick count, at tick 0 here. The critical section is only needed where the tick count is wider than the CPU can read in one go; on the 32-bit Cortex-M3 it compiles to nothing.

xTaskDelayUntil

BaseType_t xTaskDelayUntil( TickType_t * const pxPreviousWakeTime,
                            const TickType_t xTimeIncrement )
{
    TickType_t xTimeToWake;
    BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;

    traceENTER_xTaskDelayUntil( pxPreviousWakeTime, xTimeIncrement );

    configASSERT( pxPreviousWakeTime );
    configASSERT( ( xTimeIncrement > 0U ) );

    vTaskSuspendAll();
    {
        /* Minor optimisation.  The tick count cannot change in this
         * block. */
        const TickType_t xConstTickCount = xTickCount;

        configASSERT( uxSchedulerSuspended == 1U );

        /* Generate the tick time at which the task wants to wake. */
        xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;

        if( xConstTickCount < *pxPreviousWakeTime )
        {
            /* The tick count has overflowed since this function was
             * lasted called.  In this case the only time we should ever
             * actually delay is if the wake time has also  overflowed,
             * and the wake time is greater than the tick time.  When this
             * is the case it is as if neither time had overflowed. */
            if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
            {
                xShouldDelay = pdTRUE;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        else
        {
            /* The tick time has not overflowed.  In this case we will
             * delay if either the wake time has overflowed, and/or the
             * tick time is less than the wake time. */
            if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) )
            {
                xShouldDelay = pdTRUE;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }

        /* Update the wake time ready for the next call. */
        *pxPreviousWakeTime = xTimeToWake;

        if( xShouldDelay != pdFALSE )
        {
            traceTASK_DELAY_UNTIL( xTimeToWake );

            /* prvAddCurrentTaskToDelayedList() needs the block time, not
             * the time to wake, so subtract the current tick count. */
            prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE );
        }
        else
        {
            mtCOVERAGE_TEST_MARKER();
        }
    }
    xAlreadyYielded = xTaskResumeAll();

    /* Force a reschedule if xTaskResumeAll has not already done so, we may
     * have put ourselves to sleep. */
    if( xAlreadyYielded == pdFALSE )
    {
        taskYIELD_WITHIN_API();
    }
    else
    {
        mtCOVERAGE_TEST_MARKER();
    }

    traceRETURN_xTaskDelayUntil( xShouldDelay );

    return xShouldDelay;
}

tasks.c, lines 2414–2499 · FreeRTOS V11.3.3 · MIT license

At tick 2, Sensor has done its first job and calls xTaskDelayUntil():

  1. vTaskSuspendAll() keeps the scheduler from switching while the lists change, as in vTaskDelay.
  2. xTimeToWake = *pxPreviousWakeTime + xTimeIncrement = 0 + 5 = 5. This is the whole difference from vTaskDelay(), which computes xTickCount + 5. The wake-up time does not depend on when the task got here.
  3. The function decides whether to sleep at all. Normally the tick count (2) has not wrapped since the last call, and the wake-up time (5) is still ahead, so xShouldDelay becomes pdTRUE. The other branch handles a tick count that wrapped past its largest value since the last call; the comparisons are written so that the arithmetic still works across the wrap.
  4. *pxPreviousWakeTime = xTimeToWake: the next period will be counted from 5, whether or not the task sleeps now.
  5. prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ). The delayed list wants a duration, so the function turns its absolute time back into one: 5 − 2 = 3 ticks. From here on it is exactly the code of vTaskDelay().
  6. xTaskResumeAll(), then a yield, because Sensor is no longer ready.

At tick 5 the tick interrupt wakes Sensor, and the second job starts exactly one period after the first.

When the task is late

At tick 11 Burst preempts Sensor in the middle of its third job, released at 10. Sensor only finishes it at tick 16 and then calls xTaskDelayUntil() with xLastWakeTime = 10:

  • xTimeToWake = 15, but the tick count is already 16. The wake-up time is not ahead, so xShouldDelay stays pdFALSE and the task is not put in the delayed list.
  • xLastWakeTime still becomes 15.
  • The function still yields. With nothing else of priority 2 ready, Sensor keeps the CPU and starts its fourth job at once.
  • It returns pdFALSE, so a task that cares can see that it overran.

Because xLastWakeTime moved on by exactly one period, the fourth job sleeps until 20, and the grid is back. A task that overruns for several periods in a row runs its late jobs back to back until it has caught up. If that is not wanted, the task can check the return value and reset xLastWakeTime to the current tick count.

The deadline miss at tick 14 is marked by the simulator, not by FreeRTOS: the kernel has no notion of a deadline. All it sees is a call that came late, and that only when the task finally makes it.