Priority inheritance in FreeRTOS
How xTaskPriorityInherit raises a mutex holder and xTaskPriorityDisinherit lowers it again, line by line in the real kernel source.
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 priority inheritance through the FreeRTOS source. In the simulator above, set the step level to Line and use the Kernel tab of the code panel to see each of these functions execute.
The scenario: Low (priority 1) holds the mutex M. Med (priority 2) is running. At tick 2,
High (priority 3) wakes and calls xSemaphoreTake( M, portMAX_DELAY ).
A mutex is a queue
FreeRTOS builds semaphores and mutexes on its queue. A mutex is a queue that can hold one item of
size zero. “The mutex is free” means the queue holds one item (uxMessagesWaiting is 1); taking the
mutex removes it. A mutex-type queue also uses one of its fields to store the task that holds it,
xMutexHolder, which you can see in the simulator’s kernel structures panel. That field is what a
binary semaphore lacks.
Two priorities per task
With configUSE_MUTEXES set to 1, each task control block has two priority fields:
uxPriority: the priority the scheduler uses.uxBasePriority: the priority the application gave the task.
They are equal except while the task has inherited a priority. The task also counts the mutexes it
holds in uxMutexesHeld.
Raising the holder
xSemaphoreTake() is xQueueSemaphoreTake() in queue.c. When the mutex is not available and the
caller is willing to wait, it calls xTaskPriorityInherit() with the holder, before it puts the
caller to sleep.
BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder )
{
TCB_t * const pxMutexHolderTCB = pxMutexHolder;
BaseType_t xReturn = pdFALSE;
traceENTER_xTaskPriorityInherit( pxMutexHolder );
/* If the mutex is taken by an interrupt, the mutex holder is NULL. Priority
* inheritance is not applied in this scenario. */
if( pxMutexHolder != NULL )
{
/* If the holder of the mutex has a priority below the priority of
* the task attempting to obtain the mutex then it will temporarily
* inherit the priority of the task attempting to obtain the mutex. */
if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority )
{
/* Adjust the mutex holder state to account for its new
* priority. Only reset the event list item value if the value is
* not being used for anything else. */
if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == ( ( TickType_t ) 0U ) )
{
listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
/* If the task being modified is in the ready state it will need
* to be moved into a new list. */
if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE )
{
if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
{
/* It is known that the task is in its ready list so
* there is no need to check again and the port level
* reset macro can be called directly. */
portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
/* Inherit the priority before being moved into the new list. */
pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
prvAddTaskToReadyList( pxMutexHolderTCB );
#if ( configNUMBER_OF_CORES > 1 )
{
/* The priority of the task is raised. Yield for this task
* if it is not running. */
if( taskTASK_IS_RUNNING( pxMutexHolderTCB ) != pdTRUE )
{
prvYieldForTask( pxMutexHolderTCB );
}
}
#endif /* if ( configNUMBER_OF_CORES > 1 ) */
}
else
{
/* Just inherit the priority. */
pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
}
traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority );
/* Inheritance occurred. */
xReturn = pdTRUE;
}
else
{
if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority )
{
/* The base priority of the mutex holder is lower than the
* priority of the task attempting to take the mutex, but the
* current priority of the mutex holder is not lower than the
* priority of the task attempting to take the mutex.
* Therefore the mutex holder must have already inherited a
* priority, but inheritance would have occurred if that had
* not been the case. */
xReturn = pdTRUE;
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
traceRETURN_xTaskPriorityInherit( xReturn );
return xReturn;
}
tasks.c, lines 6745–6841 · FreeRTOS V11.3.3 · MIT license
Reading it from the top:
- It acts only if the holder’s priority is lower than the caller’s (
pxCurrentTCBisHigh). - It updates the holder’s event list item, which carries the priority used to sort lists of waiting tasks, unless that value is in use for something else.
- If the holder is in a ready list, it must change lists, because there is one ready list per
priority. The holder is removed from the list of its old priority, its
uxPriorityis set to the caller’s, andprvAddTaskToReadyList()appends it to the list of the new priority. This is the branch the scenario takes:Lowwas ready, preempted byMed. - If the holder is not ready (it may be delayed, or blocked on another mutex), only
uxPrioritychanges. The new priority takes effect when the task becomes ready.
uxBasePriority is not touched. After this function, High is placed on the mutex’s
xTasksWaitingToReceive list and a context switch runs Low, now the most urgent ready task.
Lowering it again
When Low calls xSemaphoreGive(), xQueueGenericSend() copies the item into the queue with
prvCopyDataToQueue(), which sees that the queue is a mutex and calls xTaskPriorityDisinherit().
BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder )
{
TCB_t * const pxTCB = pxMutexHolder;
BaseType_t xReturn = pdFALSE;
traceENTER_xTaskPriorityDisinherit( pxMutexHolder );
if( pxMutexHolder != NULL )
{
/* A task can only have an inherited priority if it holds the mutex.
* If the mutex is held by a task then it cannot be given from an
* interrupt, and if a mutex is given by the holding task then it must
* be the running state task. */
configASSERT( pxTCB == pxCurrentTCB );
configASSERT( pxTCB->uxMutexesHeld );
( pxTCB->uxMutexesHeld )--;
/* Has the holder of the mutex inherited the priority of another
* task? */
if( pxTCB->uxPriority != pxTCB->uxBasePriority )
{
/* Only disinherit if no other mutexes are held. */
if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 )
{
/* A task can only have an inherited priority if it holds
* the mutex. If the mutex is held by a task then it cannot be
* given from an interrupt, and if a mutex is given by the
* holding task then it must be the running state task. Remove
* the holding task from the ready list. */
if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
{
portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
/* Disinherit the priority before adding the task into the
* new ready list. */
traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
pxTCB->uxPriority = pxTCB->uxBasePriority;
/* Reset the event list item value. It cannot be in use for
* any other purpose if this task is running, and it must be
* running to give back the mutex. */
listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority );
prvAddTaskToReadyList( pxTCB );
#if ( configNUMBER_OF_CORES > 1 )
{
/* The priority of the task is dropped. Yield the core on
* which the task is running. */
if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE )
{
prvYieldCore( pxTCB->xTaskRunState );
}
}
#endif /* if ( configNUMBER_OF_CORES > 1 ) */
/* Return true to indicate that a context switch is required.
* This is only actually required in the corner case whereby
* multiple mutexes were held and the mutexes were given back
* in an order different to that in which they were taken.
* If a context switch did not occur when the first mutex was
* returned, even if a task was waiting on it, then a context
* switch should occur when the last mutex is returned whether
* a task is waiting on it or not. */
xReturn = pdTRUE;
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
traceRETURN_xTaskPriorityDisinherit( xReturn );
return xReturn;
}
tasks.c, lines 6848–6935 · FreeRTOS V11.3.3 · MIT license
The function decrements uxMutexesHeld and then restores uxBasePriority only if two
conditions hold: the task’s priority differs from its base priority, and it now holds no mutexes at
all.
The second condition is a deliberate simplification. If a task
holds two mutexes and inherited its priority through one of them, FreeRTOS does not work out which.
It keeps the raised priority until the last mutex is given back. The task may run at a high
priority for longer than strictly needed, but never for less. The
nested mutexes lesson shows Low keep priority 3 after it has released
the mutex that High wanted.
After the priority is restored, xQueueGenericSend() makes the most urgent waiter ready. It does
not make it the owner; see Mutex handoff.
When the waiter gives up
A task can wait for a mutex with a timeout. If the timeout runs out, the holder may be running at a
priority it inherited from a task that is no longer waiting. xQueueSemaphoreTake() handles this
on the waiter’s way out by calling vTaskPriorityDisinheritAfterTimeout() with the highest priority
among the tasks still waiting.
void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder,
UBaseType_t uxHighestPriorityWaitingTask )
{
TCB_t * const pxTCB = pxMutexHolder;
UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1;
traceENTER_vTaskPriorityDisinheritAfterTimeout( pxMutexHolder, uxHighestPriorityWaitingTask );
if( pxMutexHolder != NULL )
{
/* If pxMutexHolder is not NULL then the holder must hold at least
* one mutex. */
configASSERT( pxTCB->uxMutexesHeld );
/* Determine the priority to which the priority of the task that
* holds the mutex should be set. This will be the greater of the
* holding task's base priority and the priority of the highest
* priority task that is waiting to obtain the mutex. */
if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask )
{
uxPriorityToUse = uxHighestPriorityWaitingTask;
}
else
{
uxPriorityToUse = pxTCB->uxBasePriority;
}
/* Does the priority need to change? */
if( pxTCB->uxPriority != uxPriorityToUse )
{
/* Only disinherit if no other mutexes are held. This is a
* simplification in the priority inheritance implementation. If
* the task that holds the mutex is also holding other mutexes then
* the other mutexes may have caused the priority inheritance. */
if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld )
{
/* If a task has timed out because it already holds the
* mutex it was trying to obtain then it cannot of inherited
* its own priority. */
configASSERT( pxTCB != pxCurrentTCB );
/* Disinherit the priority, remembering the previous
* priority to facilitate determining the subject task's
* state. */
traceTASK_PRIORITY_DISINHERIT( pxTCB, uxPriorityToUse );
uxPriorityUsedOnEntry = pxTCB->uxPriority;
pxTCB->uxPriority = uxPriorityToUse;
/* Only reset the event list item value if the value is not
* being used for anything else. */
if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == ( ( TickType_t ) 0U ) )
{
listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
/* If the running task is not the task that holds the mutex
* then the task that holds the mutex could be in either the
* Ready, Blocked or Suspended states. Only remove the task
* from its current state list if it is in the Ready state as
* the task's priority is going to change and there is one
* Ready list per priority. */
if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
{
if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
{
/* It is known that the task is in its ready list so
* there is no need to check again and the port level
* reset macro can be called directly. */
portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority );
}
else
{
mtCOVERAGE_TEST_MARKER();
}
prvAddTaskToReadyList( pxTCB );
#if ( configNUMBER_OF_CORES > 1 )
{
/* The priority of the task is dropped. Yield the core on
* which the task is running. */
if( taskTASK_IS_RUNNING( pxTCB ) == pdTRUE )
{
prvYieldCore( pxTCB->xTaskRunState );
}
}
#endif /* if ( configNUMBER_OF_CORES > 1 ) */
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
}
else
{
mtCOVERAGE_TEST_MARKER();
}
traceRETURN_vTaskPriorityDisinheritAfterTimeout();
}
tasks.c, lines 6942–7055 · FreeRTOS V11.3.3 · MIT license
It lowers the holder to the greater of its base priority and that remaining waiter’s priority, and
again only if the holder holds exactly one mutex. The
mutex timeout lesson runs this path:
High gives up at tick 4 and Low drops back to priority 1 while it still holds M.
Limits worth knowing
- Inheritance is one level deep. If the holder is itself blocked on a second mutex, the holder of that one is not raised. Zephyr follows the chain; see the Zephyr walkthrough.
- Mutexes must not be used from interrupt handlers: an interrupt has no task priority to lend.
- A binary semaphore created with
xSemaphoreCreateBinary()gets none of this. UsexSemaphoreCreateMutex()for mutual exclusion.