The tick and vTaskDelay in FreeRTOS

How vTaskDelay puts a task in a delayed list and how xTaskIncrementTick wakes it, line by line in the FreeRTOS source.

Blocking and the idle task 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.

This page follows a delay through the FreeRTOS source: what vTaskDelay() does when a task asks to sleep, and what the tick interrupt does to wake it. The scheduling lesson explains the idea; here we read the code. In the simulator above, set the step level to Line and open the Kernel tab of the code panel.

The scenario has two tasks. Sensor (priority 2) works for one tick and calls vTaskDelay(4), twice. Logger (priority 1) works for two ticks, calls vTaskDelay(6), and works for two more.

vTaskDelay: leave the ready list

void vTaskDelay( const TickType_t xTicksToDelay )
{
    BaseType_t xAlreadyYielded = pdFALSE;

    traceENTER_vTaskDelay( xTicksToDelay );

    /* A delay time of zero just forces a reschedule. */
    if( xTicksToDelay > ( TickType_t ) 0U )
    {
        vTaskSuspendAll();
        {
            configASSERT( uxSchedulerSuspended == 1U );

            traceTASK_DELAY();

            /* A task that is removed from the event list while the
             * scheduler is suspended will not get placed in the ready
             * list or removed from the blocked list until the scheduler
             * is resumed.
             *
             * This task cannot be in an event list as it is the currently
             * executing task. */
            prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE );
        }
        xAlreadyYielded = xTaskResumeAll();
    }
    else
    {
        mtCOVERAGE_TEST_MARKER();
    }

    /* 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_vTaskDelay();
}

tasks.c, lines 2506–2549 · FreeRTOS V11.3.3 · MIT license

The function is short because the work is done elsewhere. It suspends the scheduler with vTaskSuspendAll(), calls prvAddCurrentTaskToDelayedList(), resumes the scheduler and then yields, because the calling task is no longer ready and something else must run.

Suspending the scheduler is not the same as disabling interrupts. Interrupts still arrive, and the tick interrupt still counts. But while uxSchedulerSuspended is not zero, xTaskIncrementTick() only adds to xPendedTicks and leaves the lists alone, and no context switch happens. xTaskResumeAll() processes the pended ticks afterwards. In the simulator a tick never arrives inside a kernel call, so you will see uxSchedulerSuspended go to 1 and back to 0, but no pended tick.

Into the delayed list

STATIC void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
                                            const BaseType_t xCanBlockIndefinitely )
{
    TickType_t xTimeToWake;
    const TickType_t xConstTickCount = xTickCount;
    List_t * const pxDelayedList = pxDelayedTaskList;
    List_t * const pxOverflowDelayedList = pxOverflowDelayedTaskList;

    #if ( INCLUDE_xTaskAbortDelay == 1 )
    {
        /* About to enter a delayed list, so ensure the ucDelayAborted flag is
         * reset to pdFALSE so it can be detected as having been set to pdTRUE
         * when the task leaves the Blocked state. */
        pxCurrentTCB->ucDelayAborted = ( uint8_t ) pdFALSE;
    }
    #endif

    /* Remove the task from the ready list before adding it to the blocked list
     * as the same list item is used for both lists. */
    if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
    {
        /* The current task must be in a ready list, so there is no need to
         * check, and the port reset macro can be called directly. */
        portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
    }
    else
    {
        mtCOVERAGE_TEST_MARKER();
    }

    #if ( INCLUDE_vTaskSuspend == 1 )
    {
        if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) )
        {
            /* Add the task to the suspended task list instead of a delayed task
             * list to ensure it is not woken by a timing event.  It will block
             * indefinitely. */
            listINSERT_END( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) );
        }
        else
        {
            /* Calculate the time at which the task should be woken if the event
             * does not occur.  This may overflow but this doesn't matter, the
             * kernel will manage it correctly. */
            xTimeToWake = xConstTickCount + xTicksToWait;

            /* The list item will be inserted in wake time order. */
            listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );

            if( xTimeToWake < xConstTickCount )
            {
                /* Wake time has overflowed.  Place this item in the overflow
                 * list. */
                traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST();
                vListInsert( pxOverflowDelayedList, &( pxCurrentTCB->xStateListItem ) );
            }
            else
            {
                /* The wake time has not overflowed, so the current block list
                 * is used. */
                traceMOVED_TASK_TO_DELAYED_LIST();
                vListInsert( pxDelayedList, &( pxCurrentTCB->xStateListItem ) );

                /* If the task entering the blocked state was placed at the
                 * head of the list of blocked tasks then xNextTaskUnblockTime
                 * needs to be updated too. */
                if( xTimeToWake < xNextTaskUnblockTime )
                {
                    xNextTaskUnblockTime = xTimeToWake;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
        }
    }
    #else /* INCLUDE_vTaskSuspend */
    {
        /* Calculate the time at which the task should be woken if the event
         * does not occur.  This may overflow but this doesn't matter, the kernel
         * will manage it correctly. */
        xTimeToWake = xConstTickCount + xTicksToWait;

        /* The list item will be inserted in wake time order. */
        listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );

        if( xTimeToWake < xConstTickCount )
        {
            traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST();
            /* Wake time has overflowed.  Place this item in the overflow list. */
            vListInsert( pxOverflowDelayedList, &( pxCurrentTCB->xStateListItem ) );
        }
        else
        {
            traceMOVED_TASK_TO_DELAYED_LIST();
            /* The wake time has not overflowed, so the current block list is used. */
            vListInsert( pxDelayedList, &( pxCurrentTCB->xStateListItem ) );

            /* If the task entering the blocked state was placed at the head of the
             * list of blocked tasks then xNextTaskUnblockTime needs to be updated
             * too. */
            if( xTimeToWake < xNextTaskUnblockTime )
            {
                xNextTaskUnblockTime = xTimeToWake;
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }

        /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
        ( void ) xCanBlockIndefinitely;
    }
    #endif /* INCLUDE_vTaskSuspend */
}

tasks.c, lines 8685–8801 · FreeRTOS V11.3.3 · MIT license

At tick 1, Sensor calls vTaskDelay(4). Reading the function from the top:

  1. uxListRemove() takes the task out of its ready list. A task has one xStateListItem, which is in exactly one of the ready, delayed or suspended lists, so it must leave one before it joins another.
  2. The wake-up time is the current tick count plus the delay: xTimeToWake = 1 + 4 = 5. It is stored as the list item’s value.
  3. vListInsert() puts the item into the delayed list, sorted by that value. The earliest wake-up is always at the head.
  4. If this task now wakes earlier than any other, xNextTaskUnblockTime is set to its wake-up time.

xNextTaskUnblockTime is the reason a tick costs almost nothing when nothing is due. Watch it in the variables under the kernel structures: it is portMAX_DELAY when no task sleeps, and 5 after Sensor’s call.

The overflow branch is for a wake-up time that wraps past the largest tick value. FreeRTOS keeps two delayed lists, xDelayedTaskList1 and xDelayedTaskList2. pxDelayedTaskList points at the one for the current lap of the tick counter, pxOverflowDelayedTaskList at the one for the next lap. A sorted list cannot hold “tick 3 after the wrap” after “tick 4 billion before it”, so those go in the other list, and the two swap when the count reaches 0. The tick overflow walkthrough shows the swap.

At tick 3, Logger delays for 6 and gets wake-up tick 9. It is inserted behind Sensor, whose wake-up (5) is earlier. xNextTaskUnblockTime stays 5.

Notice what does not change when a task leaves its ready list: uxTopReadyPriority. With the generic task selection used here, it is only an upper bound, “the highest priority that may have a ready task”. It is lowered lazily by the next search; see choosing the next task.

The tick interrupt

On the Cortex-M3 port the tick comes from the SysTick timer. Its handler is small:

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

It calls xTaskIncrementTick(), and if that returns pdTRUE it does not switch tasks itself: it sets the PendSV pending bit, and the context switch happens in the PendSV exception after this interrupt returns.

xTaskIncrementTick

BaseType_t xTaskIncrementTick( void )
{
    TCB_t * pxTCB;
    TickType_t xItemValue;
    BaseType_t xSwitchRequired = pdFALSE;

    traceENTER_xTaskIncrementTick();

    /* Called by the portable layer each time a tick interrupt occurs.
     * Increments the tick then checks to see if the new tick value will cause any
     * tasks to be unblocked. */
    traceTASK_INCREMENT_TICK( xTickCount );

    /* Tick increment should occur on every kernel timer event. Core 0 has the
     * responsibility to increment the tick, or increment the pended ticks if the
     * scheduler is suspended.  If pended ticks is greater than zero, the core that
     * calls xTaskResumeAll has the responsibility to increment the tick. */
    if( uxSchedulerSuspended == ( UBaseType_t ) 0U )
    {
        /* Minor optimisation.  The tick count cannot change in this
         * block. */
        const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1;

        /* Increment the RTOS tick, switching the delayed and overflowed
         * delayed lists if it wraps to 0. */
        xTickCount = xConstTickCount;

        if( xConstTickCount == ( TickType_t ) 0U )
        {
            taskSWITCH_DELAYED_LISTS();
        }
        else
        {
            mtCOVERAGE_TEST_MARKER();
        }

        /* See if this tick has made a timeout expire.  Tasks are stored in
         * the  queue in the order of their wake time - meaning once one task
         * has been found whose block time has not expired there is no need to
         * look any further down the list. */
        if( xConstTickCount >= xNextTaskUnblockTime )
        {
            for( ; ; )
            {
                if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
                {
                    /* The delayed list is empty.  Set xNextTaskUnblockTime
                     * to the maximum possible value so it is extremely
                     * unlikely that the
                     * if( xTickCount >= xNextTaskUnblockTime ) test will pass
                     * next time through. */
                    xNextTaskUnblockTime = portMAX_DELAY;
                    break;
                }
                else
                {
                    /* The delayed list is not empty, get the value of the
                     * item at the head of the delayed list.  This is the time
                     * at which the task at the head of the delayed list must
                     * be removed from the Blocked state. */
                    /* MISRA Ref 11.5.3 [Void pointer assignment] */
                    /* More details at: https://github.com/FreeRTOS/FreeRTOS-Kernel/blob/main/MISRA.md#rule-115 */
                    /* coverity[misra_c_2012_rule_11_5_violation] */
                    pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList );
                    xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) );

                    if( xConstTickCount < xItemValue )
                    {
                        /* It is not time to unblock this item yet, but the
                         * item value is the time at which the task at the head
                         * of the blocked list must be removed from the Blocked
                         * state -  so record the item value in
                         * xNextTaskUnblockTime. */
                        xNextTaskUnblockTime = xItemValue;
                        break;
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }

                    /* It is time to remove the item from the Blocked state. */
                    listREMOVE_ITEM( &( pxTCB->xStateListItem ) );

                    /* Is the task waiting on an event also?  If so remove
                     * it from the event list. */
                    if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
                    {
                        listREMOVE_ITEM( &( pxTCB->xEventListItem ) );
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }

                    /* Place the unblocked task into the appropriate ready
                     * list. */
                    prvAddTaskToReadyList( pxTCB );

                    /* A task being unblocked cannot cause an immediate
                     * context switch if preemption is turned off. */
                    #if ( configUSE_PREEMPTION == 1 )
                    {
                        #if ( configNUMBER_OF_CORES == 1 )
                        {
                            /* Preemption is on, but a context switch should
                             * only be performed if the unblocked task's
                             * priority is higher than the currently executing
                             * task.
                             * The case of equal priority tasks sharing
                             * processing time (which happens when both
                             * preemption and time slicing are on) is
                             * handled below.*/
                            if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
                            {
                                xSwitchRequired = pdTRUE;
                            }
                            else
                            {
                                mtCOVERAGE_TEST_MARKER();
                            }
                        }
                        #else /* #if( configNUMBER_OF_CORES == 1 ) */
                        {
                            prvYieldForTask( pxTCB );
                        }
                        #endif /* #if( configNUMBER_OF_CORES == 1 ) */
                    }
                    #endif /* #if ( configUSE_PREEMPTION == 1 ) */
                }
            }
        }

        /* Tasks of equal priority to the currently running task will share
         * processing time (time slice) if preemption is on, and the application
         * writer has not explicitly turned time slicing off. */
        #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) )
        {
            #if ( configNUMBER_OF_CORES == 1 )
            {
                if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > 1U )
                {
                    xSwitchRequired = pdTRUE;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            #else /* #if ( configNUMBER_OF_CORES == 1 ) */
            {
                BaseType_t xCoreID;

                for( xCoreID = 0; xCoreID < ( ( BaseType_t ) configNUMBER_OF_CORES ); xCoreID++ )
                {
                    if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCBs[ xCoreID ]->uxPriority ] ) ) > 1U )
                    {
                        xYieldPendings[ xCoreID ] = pdTRUE;
                    }
                    else
                    {
                        mtCOVERAGE_TEST_MARKER();
                    }
                }
            }
            #endif /* #if ( configNUMBER_OF_CORES == 1 ) */
        }
        #endif /* #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */

        #if ( configUSE_TICK_HOOK == 1 )
        {
            /* Guard against the tick hook being called when the pended tick
             * count is being unwound (when the scheduler is being unlocked). */
            if( xPendedTicks == ( TickType_t ) 0 )
            {
                vApplicationTickHook();
            }
            else
            {
                mtCOVERAGE_TEST_MARKER();
            }
        }
        #endif /* configUSE_TICK_HOOK */

        #if ( configUSE_PREEMPTION == 1 )
        {
            #if ( configNUMBER_OF_CORES == 1 )
            {
                /* For single core the core ID is always 0. */
                if( xYieldPendings[ 0 ] != pdFALSE )
                {
                    xSwitchRequired = pdTRUE;
                }
                else
                {
                    mtCOVERAGE_TEST_MARKER();
                }
            }
            #else /* #if ( configNUMBER_OF_CORES == 1 ) */
            {
                BaseType_t xCoreID, xCurrentCoreID;
                xCurrentCoreID = ( BaseType_t ) portGET_CORE_ID();

                for( xCoreID = 0; xCoreID < ( BaseType_t ) configNUMBER_OF_CORES; xCoreID++ )
                {
                    #if ( configUSE_TASK_PREEMPTION_DISABLE == 1 )
                        if( pxCurrentTCBs[ xCoreID ]->xPreemptionDisable == pdFALSE )
                    #endif
                    {
                        if( xYieldPendings[ xCoreID ] != pdFALSE )
                        {
                            if( xCoreID == xCurrentCoreID )
                            {
                                xSwitchRequired = pdTRUE;
                            }
                            else
                            {
                                prvYieldCore( xCoreID );
                            }
                        }
                        else
                        {
                            mtCOVERAGE_TEST_MARKER();
                        }
                    }
                }
            }
            #endif /* #if ( configNUMBER_OF_CORES == 1 ) */
        }
        #endif /* #if ( configUSE_PREEMPTION == 1 ) */
    }
    else
    {
        xPendedTicks += 1U;

        /* The tick hook gets called at regular intervals, even if the
         * scheduler is locked. */
        #if ( configUSE_TICK_HOOK == 1 )
        {
            vApplicationTickHook();
        }
        #endif
    }

    traceRETURN_xTaskIncrementTick( xSwitchRequired );

    return xSwitchRequired;
}

tasks.c, lines 4831–5078 · FreeRTOS V11.3.3 · MIT license

The function, with the parts the configuration compiles out set aside:

  1. Count. xTickCount becomes xConstTickCount, the old value plus one. If it wrapped to 0, taskSWITCH_DELAYED_LISTS() swaps the two delayed lists.
  2. Anything due? if( xConstTickCount >= xNextTaskUnblockTime ). On most ticks the answer is no, and the delayed list is not even looked at. Tick 2 is such a tick: four lines and the handler returns.
  3. The unblocking loop. It looks at the head of the delayed list. If the head is not due yet, its wake-up time becomes the new xNextTaskUnblockTime and the loop stops: the list is sorted, so nothing behind it can be due either. If the list is empty, xNextTaskUnblockTime goes back to portMAX_DELAY. Otherwise the head task is removed from the delayed list (and from an event list, if it was also waiting for a semaphore or a queue with a timeout), and prvAddTaskToReadyList() puts it at the end of the ready list for its priority.
  4. Preemption check. If the woken task’s priority is higher than the running task’s, xSwitchRequired becomes pdTRUE. Equal is not enough here.
  5. Time-slice check. If the running task’s ready list holds more than one task, xSwitchRequired becomes pdTRUE so the next task of that priority gets a turn. This is time slicing, and it is checked on every tick.
  6. A yield left pending. xYieldPendings[ 0 ] is set whenever the kernel wakes a task more urgent than the running one but does not switch at once: an interrupt handler that did not call portYIELD_FROM_ISR(), or a switch asked for while the scheduler was suspended. The tick honours it now. The interrupts walkthrough shows it happen.

At tick 5 all of it runs. The count reaches xNextTaskUnblockTime, the loop removes Sensor and makes it ready, and because Sensor (2) is more urgent than the idle task (0) a switch is requested. The loop goes round once more, finds Logger at the head with wake-up tick 9, stores 9 in xNextTaskUnblockTime and stops. The handler pends PendSV and Sensor runs, returning from vTaskDelay().

Why vTaskDelay(n) wakes at tick + n

The wake-up time is the tick count at the call plus n, and the task is woken by the tick interrupt that makes the count equal to it. FreeRTOS counts tick interrupts, not time. If the task calls vTaskDelay(4) just before a tick interrupt, the first of its four ticks comes almost at once, so the delay lasts between three and four tick periods. Code that needs at least a certain time must ask for one tick more.

In this simulator a task’s work is counted in whole ticks, so every call is made right after a tick interrupt and the delay is exactly n periods. On Zephyr the same program wakes one tick later, because Zephyr adds the extra tick itself: see the Zephyr version of this page.

What to try

  • Step through tick 9: Logger wakes, and Sensor’s second wake-up (10) becomes xNextTaskUnblockTime.
  • Give Logger an urgency of 3. It now runs first, delays at tick 2 until tick 8, and at tick 8 the preemption check takes the CPU from Sensor, which is running. Every wake-up time after that moves.