Mutex handoff: who gets a mutex when it is unlocked
FreeRTOS frees the mutex and lets tasks compete for it; Zephyr gives it straight to the most urgent waiter. One program, two outcomes.
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.
When a task unlocks a mutex that other tasks are waiting for, the kernel has two choices.
- Free the mutex and wake a waiter. The woken task still has to take the mutex when it gets the CPU. If another task takes it first, the woken task waits again.
- Hand the mutex over. The kernel makes the most urgent waiter the owner inside the unlock call. The mutex is never free in between.
FreeRTOS does the first, Zephyr the second. Most programs cannot tell. The one above can.
The program
High takes the mutex M and then sleeps for two ticks while holding it. That is bad practice, and
here it is done on purpose, to let the other two tasks reach the mutex. Med and Low both try to
take M and block.
Then High wakes up, works for one tick, unlocks M and locks it again at once, for two more
ticks of work. Releasing a lock and taking it again in a loop is a common pattern, for example in a
task that handles one item per pass.
On FreeRTOS
- Tick 3:
HighgivesM. InxQueueGenericSend()the mutex becomes free, and the most urgent waiter,Med, is moved from the mutex’s waiting list to its ready list. Medis ready, butHighhas a higher priority and keeps running.HighcallsxSemaphoreTake()again. The mutex is free, so it succeeds immediately.Highworks during ticks 3 and 4, givesMat tick 5 and ends.- Only now does
Medrun. It takesMat tick 5, two ticks after it was “woken”.
The waiter is taken off the waiting list by this function, which does not touch the mutex itself:
BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
{
TCB_t * pxUnblockedTCB;
BaseType_t xReturn;
traceENTER_xTaskRemoveFromEventList( pxEventList );
/* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be
* called from a critical section within an ISR. */
/* The event list is sorted in priority order, so the first in the list can
* be removed as it is known to be the highest priority. Remove the TCB from
* the delayed list, and add it to the ready list.
*
* If an event is for a queue that is locked then this function will never
* get called - the lock count on the queue will get modified instead. This
* means exclusive access to the event list is guaranteed here.
*
* This function assumes that a check has already been made to ensure that
* pxEventList is not empty. */
/* 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] */
pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
configASSERT( pxUnblockedTCB );
listREMOVE_ITEM( &( pxUnblockedTCB->xEventListItem ) );
if( uxSchedulerSuspended == ( UBaseType_t ) 0U )
{
listREMOVE_ITEM( &( pxUnblockedTCB->xStateListItem ) );
prvAddTaskToReadyList( pxUnblockedTCB );
#if ( configUSE_TICKLESS_IDLE != 0 )
{
/* If a task is blocked on a kernel object then xNextTaskUnblockTime
* might be set to the blocked task's time out time. If the task is
* unblocked for a reason other than a timeout xNextTaskUnblockTime is
* normally left unchanged, because it is automatically reset to a new
* value when the tick count equals xNextTaskUnblockTime. However if
* tickless idling is used it might be more important to enter sleep mode
* at the earliest possible time - so reset xNextTaskUnblockTime here to
* ensure it is updated at the earliest possible time. */
prvResetNextTaskUnblockTime();
}
#endif
}
else
{
/* The delayed and ready lists cannot be accessed, so hold this task
* pending until the scheduler is resumed. */
listINSERT_END( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
}
#if ( configNUMBER_OF_CORES == 1 )
{
if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
{
/* Return true if the task removed from the event list has a higher
* priority than the calling task. This allows the calling task to know if
* it should force a context switch now. */
xReturn = pdTRUE;
/* Mark that a yield is pending in case the user is not using the
* "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
xYieldPendings[ 0 ] = pdTRUE;
}
else
{
xReturn = pdFALSE;
}
}
#else /* #if ( configNUMBER_OF_CORES == 1 ) */
{
xReturn = pdFALSE;
#if ( configUSE_PREEMPTION == 1 )
{
prvYieldForTask( pxUnblockedTCB );
if( xYieldPendings[ portGET_CORE_ID() ] != pdFALSE )
{
xReturn = pdTRUE;
}
}
#endif /* #if ( configUSE_PREEMPTION == 1 ) */
}
#endif /* #if ( configNUMBER_OF_CORES == 1 ) */
traceRETURN_xTaskRemoveFromEventList( xReturn );
return xReturn;
}
tasks.c, lines 5500–5590 · FreeRTOS V11.3.3 · MIT license
Had Med found the mutex taken when it finally ran, it would have gone round the loop in
xQueueSemaphoreTake() and blocked again. In a loop that gives and takes, a task of higher (or,
without time slicing, equal) priority can keep the others out for as long as it likes.
On Zephyr
- Tick 4 (Zephyr’s sleeps are one tick longer):
Highcallsk_mutex_unlock(). The kernel takesMedoff the wait queue and writes it intomutex->owner. The simulator showsMheld byMedalthoughMedhas not run yet. Highis still the most urgent thread and keeps running. It callsk_mutex_lock().- The mutex has an owner, so
Highblocks, andMedinherits its priority (13 → 12). Medworks during ticks 4 and 5 and unlocks.Mis handed toHigh, the most urgent waiter, ahead ofLow.Highworks during ticks 6 and 7.
int z_impl_k_mutex_unlock(struct k_mutex *mutex)
{
struct k_thread *new_owner = NULL;
__ASSERT(!arch_is_in_isr(), "mutexes cannot be used inside ISRs");
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mutex, unlock, mutex);
CHECKIF(mutex->owner == NULL) {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, -EINVAL);
return -EINVAL;
}
/*
* The current thread does not own the mutex.
*/
CHECKIF(mutex->owner != _current) {
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, -EPERM);
return -EPERM;
}
/*
* Attempt to unlock a mutex which is unlocked. mutex->lock_count
* cannot be zero if the current thread is equal to mutex->owner,
* therefore no underflow check is required. Use assert to catch
* undefined behavior.
*/
__ASSERT_NO_MSG(mutex->lock_count > 0U);
LOG_DBG("mutex %p lock_count: %d", mutex, mutex->lock_count);
/*
* If we are the owner and count is greater than 1, then decrement
* the count and return and keep current thread as the owner.
*/
if (mutex->lock_count > 1U) {
mutex->lock_count--;
goto k_mutex_unlock_return;
}
k_spinlock_key_t key = k_spin_lock(&mutex_lock);
#if Z_MUTEX_PI_ENABLED
/* Remove this mutex from the owner's list of held mutexes */
sys_slist_find_and_remove(&_current->held_mutexes, &mutex->held_node);
/*
* If the thread's priority was boosted, recalculate it by scanning
* the remaining held mutexes. The released mutex has already been
* removed from held_mutexes, so it is not included in the scan.
*/
if (_current->base.prio != _current->orig_prio) {
int32_t new_prio = held_mutexes_highest_waiter_prio(
_current, _current->orig_prio);
adjust_owner_prio(mutex, new_prio);
}
#endif
/* Pick the new owner (if any) and complete the wake atomically
* under the scheduler's spinlock, so a racing in-flight timeout
* handler cannot observe a half-initialized wake-up.
*/
LOCK_SCHED_SPINLOCK {
new_owner = z_unpend_first_thread_locked(&mutex->wait_q);
mutex->owner = new_owner;
LOG_DBG("new owner of mutex %p: %p (prio: %d)",
mutex, new_owner, new_owner ? new_owner->base.prio : -1000);
if (unlikely(new_owner != NULL)) {
/*
* new owner is already of higher or equal prio than first
* waiter since the wait queue is priority-based: no need to
* adjust its priority
*/
#if Z_MUTEX_PI_ENABLED
if (sys_slist_is_empty(&new_owner->held_mutexes)) {
new_owner->orig_prio = new_owner->base.prio;
}
sys_slist_append(&new_owner->held_mutexes, &mutex->held_node);
new_owner->mutex_pended_on = NULL;
#endif
arch_thread_return_value_set(new_owner, 0);
z_sched_ready_locked(new_owner);
} else {
mutex->lock_count = 0U;
}
}
if (unlikely(new_owner != NULL)) {
z_reschedule(&mutex_lock, key);
} else {
k_spin_unlock(&mutex_lock, key);
}
k_mutex_unlock_return:
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, unlock, mutex, 0);
return 0;
}
kernel/mutex.c, lines 411–513 · Zephyr v4.5.0 · Apache-2.0 license
The lines to look at are the ones that set mutex->owner = new_owner and make the new owner ready
in the same locked section.
Which is better
Neither. They optimise for different things.
| FreeRTOS: free and compete | Zephyr: hand over | |
|---|---|---|
| The most urgent task | is never delayed by a less urgent waiter | can wait for a waiter’s whole critical section |
| A waiter | can be passed over repeatedly | gets the mutex in priority order, once per unlock |
Med owns the mutex |
2 ticks after High first unlocks it |
at the moment High unlocks it |
High finishes its second section |
2 ticks after its first unlock | 4 ticks after its first unlock |
FreeRTOS keeps the highest-priority task moving, which is the strict reading of “the most urgent
ready task runs”. Zephyr guarantees progress to waiters, at the price of making High wait for
Med, with priority inheritance keeping that wait short.
If your code relies on one behaviour, say so in a comment. Code that unlocks and relocks in a loop to “let others in” works on Zephyr and does nothing of the kind on FreeRTOS unless the task also yields or the others have a higher priority.
What to try
- Step by Event to the first unlock on one kernel, then on the other, and compare which task
the kernel structures panel shows as the holder of
M. - Step by Line through the unlock on each kernel and watch the mutex’s owner field.