Tick count overflow in FreeRTOS
How FreeRTOS keeps delays working when its 32-bit tick count wraps round to zero, with two delayed lists that swap roles.
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.
FreeRTOS counts time in a variable called xTickCount. In the simulated configuration, as on most
32-bit microcontrollers, it is a 32-bit unsigned number. At 1000 ticks per second it reaches its
largest value, 0xFFFFFFFF, after 49.7 days, and the next tick sets it back to 0. A device that runs
for two months will see that happen, so the kernel must handle it, and so must any application code
that compares tick values.
This page shows how the kernel does it. Waiting 49 days in the simulator would be tedious, so the
scenario starts the count at 0xFFFFFFFA, six ticks before the wrap, with the configuration option
configINITIAL_TICK_COUNT. The tick numbers in the text below count ticks since the start of the run
(tick 0 is the first column of the timeline), with the kernel’s own count next to them, as the
controls show it.
Why a wrap is a problem
A task that delays is put into a delayed list sorted by the tick at which it must wake. On every tick the kernel looks at the front of that list and wakes the tasks whose time has come. See tick and delay for the details.
Now suppose the count is 0xFFFFFFFC and a task calls vTaskDelay( 6 ). The wake-up tick is
0xFFFFFFFC + 6, which does not fit in 32 bits and wraps to 2. In a single list sorted by value,
2 would come first, before tasks that wake at 0xFFFFFFFD, and the kernel would think that it is
long overdue.
Two lists
FreeRTOS keeps two delayed lists, xDelayedTaskList1 and xDelayedTaskList2, and two pointers to
them:
pxDelayedTaskListholds the tasks that wake before the count wraps;pxOverflowDelayedTaskListholds the tasks that wake after it.
prvAddCurrentTaskToDelayedList() chooses between them. It adds the delay to the current count; if
the sum is smaller than the count, the addition wrapped, and the task goes into the overflow 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
Only the INCLUDE_vTaskSuspend == 1 half is compiled in the simulated configuration. Its first branch
is for waits without a timeout (portMAX_DELAY), which go to the suspended list instead. Note that
xNextTaskUnblockTime, the cached time of the next wake-up, is only updated for the current list: an
entry in the overflow list cannot be due before the wrap.
What happens
The two tasks: Early (priority 2) works one tick, sleeps two, and works one more. Late
(priority 1) works one tick, sleeps six, and works one more.
- Tick 0, count
0xFFFFFFFA:Earlyruns. - Tick 1, count
0xFFFFFFFB:EarlycallsvTaskDelay( 2 ). It wakes at0xFFFFFFFD, which does not wrap, so it goes into the current list.Lateruns. - Tick 2, count
0xFFFFFFFC:LatecallsvTaskDelay( 6 ). The wake-up tick wraps to 2, soLategoes into the overflow list. Both tasks are delayed and the idle task runs. The kernel structures panel shows one task in each list. - Tick 3, count
0xFFFFFFFD:Earlywakes, runs its last tick and ends. - Tick 5, count
0xFFFFFFFF: the last tick before the wrap. Nothing is due. - Tick 6:
xTaskIncrementTick()adds one and the count becomes 0. Right after storing it, the function checks for exactly this case and callstaskSWITCH_DELAYED_LISTS(). - Tick 8, count 2:
Lateis at the front of what is now the current list, its time has come, and it wakes and runs.
Step through tick 6 with the step level set to Line to watch the two lists change names.
The swap
#define taskSWITCH_DELAYED_LISTS() \
do { \
List_t * pxTemp; \
\
/* The delayed tasks list should be empty when the lists are switched. */ \
configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \
\
pxTemp = pxDelayedTaskList; \
pxDelayedTaskList = pxOverflowDelayedTaskList; \
pxOverflowDelayedTaskList = pxTemp; \
xNumOfOverflows = ( BaseType_t ) ( xNumOfOverflows + 1 ); \
prvResetNextTaskUnblockTime(); \
} while( 0 )
tasks.c, lines 267–279 · FreeRTOS V11.3.3 · MIT license
The macro swaps the two pointers. Nothing is copied: the list that was the overflow list, with Late
in it, becomes the current list, and the old current list, now empty, becomes the overflow list for
the next round. The configASSERT states why that is safe. Every task in the current list wakes at
some tick no later than 0xFFFFFFFF, and that tick has just passed, so the list must be empty.
xNumOfOverflows counts the wraps. xTaskCheckForTimeOut() uses it to tell “the count is smaller
because time has wrapped” from “the count is smaller because the timeout has not started”, which is
how a timeout on a mutex or a queue survives the wrap too.
Finally prvResetNextTaskUnblockTime() reads the wake-up tick of the new current list’s first task,
2, into xNextTaskUnblockTime:
STATIC void prvResetNextTaskUnblockTime( void )
{
if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
{
/* The new current delayed list is empty. Set xNextTaskUnblockTime to
* the maximum possible value so it is extremely unlikely that the
* if( xTickCount >= xNextTaskUnblockTime ) test will pass until
* there is an item in the delayed list. */
xNextTaskUnblockTime = portMAX_DELAY;
}
else
{
/* The new current 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 should be removed
* from the Blocked state. */
xNextTaskUnblockTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxDelayedTaskList );
}
}
tasks.c, lines 6621–6639 · FreeRTOS V11.3.3 · MIT license
In your own code
The kernel handles the wrap, but code that measures time with xTaskGetTickCount() has to as well.
Subtract, and compare the difference:
TickType_t start = xTaskGetTickCount();
/* ... */
if( ( xTaskGetTickCount() - start ) >= xTimeout ) /* correct across the wrap */
Unsigned subtraction wraps the same way the count does, so the difference is right as long as the
interval is shorter than 2^32 ticks. Comparing the counts themselves (now >= start + xTimeout)
breaks near the wrap, and such bugs show up only after 49.7 days of uptime. FreeRTOS V11 can also be
built with a 64-bit tick type (configTICK_TYPE_WIDTH_IN_BITS), at the cost of slower tick handling
on a 32-bit CPU.
Zephyr has no equivalent
Zephyr counts ticks in a 64-bit number. At 1000 ticks per second it would wrap after about 292 million years. Its timeout list does not store absolute wake-up ticks either: each entry holds the number of ticks after the entry before it (see tick and delay in Zephyr). So there is nothing to swap, and the scenario runs on FreeRTOS only.
What to try
- Set Late urgency to 3.
Latenow runs first and goes into the overflow list at tick 1, while the current list is still empty;Earlyfollows into the current list. The order of events changes, but each task lands in the same list as before, because the list depends only on whether its wake-up tick wraps.