Priority inheritance in Zephyr
How k_mutex_lock raises a chain of mutex owners and k_mutex_unlock works the priority out again, in the real kernel source.
Simulated kernel: 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.
This page follows priority inheritance through the Zephyr source, as it is in v4.5.0. In the simulator above, set the step level to Line and use the Kernel tab of the code panel to see each function execute.
The scenario: Low (priority 14) holds the mutex M. Med (priority 13) is running. At tick 3,
High (priority 12) wakes and calls k_mutex_lock(&M, K_FOREVER). In Zephyr a lower number is a
more urgent priority.
What the kernel records
A k_mutex has an owner, a lock_count (the same thread may lock it more than once) and a wait
queue sorted by priority. For inheritance, each thread carries three more things:
orig_prio: its priority before any inheritance, recorded when it takes its first mutex.held_mutexes: a list of the mutexes it holds.mutex_pended_on: the mutex it is waiting for, if any.
The simulator shows orig_prio on the task card while a thread holds a mutex.
Locking: raise the chain of owners
int z_impl_k_mutex_lock(struct k_mutex *mutex, k_timeout_t timeout)
{
k_spinlock_key_t key;
#if Z_MUTEX_PI_ENABLED
bool resched = false;
#endif
__ASSERT(!arch_is_in_isr(), "mutexes cannot be used inside ISRs");
SYS_PORT_TRACING_OBJ_FUNC_ENTER(k_mutex, lock, mutex, timeout);
key = k_spin_lock(&mutex_lock);
if (likely((mutex->lock_count == 0U) || (mutex->owner == _current))) {
mutex->lock_count++;
mutex->owner = _current;
#if Z_MUTEX_PI_ENABLED
LOG_DBG("%p took mutex %p, count: %d, orig prio: %d",
_current, mutex, mutex->lock_count,
_current->orig_prio);
/* Add to held list on first acquisition; recursive locks skip this. */
if (mutex->lock_count == 1U) {
/* Capture the thread's true pre-inheritance priority
* the first time it acquires any mutex.
*/
if (sys_slist_is_empty(&_current->held_mutexes)) {
_current->orig_prio = _current->base.prio;
}
sys_slist_append(&_current->held_mutexes, &mutex->held_node);
}
#else
LOG_DBG("%p took mutex %p, count: %d",
_current, mutex, mutex->lock_count);
#endif
k_spin_unlock(&mutex_lock, key);
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, 0);
return 0;
}
if (unlikely(K_TIMEOUT_EQ(timeout, K_NO_WAIT))) {
k_spin_unlock(&mutex_lock, key);
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, -EBUSY);
return -EBUSY;
}
SYS_PORT_TRACING_OBJ_FUNC_BLOCKING(k_mutex, lock, mutex, timeout);
#if Z_MUTEX_PI_ENABLED
/* Record the mutex this thread is blocking on for priority inheritance. */
_current->mutex_pended_on = mutex;
/*
* Walk the ownership chain, boosting each owner's priority to match
* the highest-priority waiter. Detects deadlock cycles along the way.
*/
{
int32_t boost_prio = new_prio_for_inheritance(
_current->base.prio,
mutex->owner->base.prio);
struct k_mutex *chain_mutex = mutex;
struct k_thread *chain_owner = mutex->owner;
int hops = 0;
#if defined(CONFIG_MUTEX_DEADLOCK_DETECT)
bool all_forever = K_TIMEOUT_EQ(timeout, K_FOREVER);
#endif
LOG_DBG("chain boosting prio on mutex %p", mutex);
while (chain_owner != NULL) {
#if defined(CONFIG_MUTEX_DEADLOCK_DETECT)
/*
* Deadlock detection: only when _current and every
* chain member visited so far wait forever. all_forever
* is updated on every hop, so a finite timeout anywhere
* in the chain -- not just at the hop that closes the
* cycle -- correctly rules out a false positive.
* z_is_thread_pending() guards against a stale
* mutex_pended_on in a thread that timed out but has
* not yet cleared the field.
*/
all_forever = all_forever &&
z_is_inactive_timeout(&chain_owner->base.timeout);
if (all_forever &&
chain_owner->mutex_pended_on != NULL &&
z_is_thread_pending(chain_owner) &&
chain_owner->mutex_pended_on->owner == _current) {
__ASSERT(false,
"mutex deadlock: thread %p waiting on "
"mutex %p (owner %p)",
_current, mutex, mutex->owner);
break;
}
#endif /* CONFIG_MUTEX_DEADLOCK_DETECT */
if (z_is_prio_higher(boost_prio, chain_owner->base.prio)) {
resched = adjust_owner_prio(chain_mutex, boost_prio)
|| resched;
}
/*
* Stop the chain walk if the owner is not actually
* pending — its mutex_pended_on may be stale (e.g. it
* just timed out but has not yet cleared the field).
* Always boost the current owner first, then decide
* whether to continue.
*/
if (chain_owner->mutex_pended_on == NULL ||
!z_is_thread_pending(chain_owner)) {
break;
}
chain_mutex = chain_owner->mutex_pended_on;
/*
* Cap the walk to prevent spinning on a cycle that
* does not pass through the starting mutex.
* MUTEX_CHAIN_WALK_MAX_HOPS bounds walk cost under
* mutex_lock; it is not a real limit on chain length.
* The chain_mutex == mutex check is a fast path for
* the common 2-hop cycle through the starting mutex.
*/
if (chain_mutex == mutex ||
++hops >= MUTEX_CHAIN_WALK_MAX_HOPS) {
break;
}
chain_owner = chain_mutex->owner;
}
}
#endif
int got_mutex = z_pend_curr(&mutex_lock, key, &mutex->wait_q, timeout);
LOG_DBG("on mutex %p got_mutex value: %d", mutex, got_mutex);
LOG_DBG("%p got mutex %p (y/n): %c", _current, mutex,
got_mutex ? 'y' : 'n');
#if Z_MUTEX_PI_ENABLED
if (got_mutex == 0) {
/* Lock granted; clear the pending mutex pointer. */
_current->mutex_pended_on = NULL;
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, 0);
return 0;
}
/* timed out */
LOG_DBG("%p timeout on mutex %p", _current, mutex);
key = k_spin_lock(&mutex_lock);
/*
* Clear mutex_pended_on under mutex_lock so no concurrent chain walk
* can observe the stale pointer and detect a false deadlock cycle.
*/
_current->mutex_pended_on = NULL;
/*
* Check if mutex was unlocked after this thread was unpended.
* If so, skip adjusting owner's priority down.
*/
if (likely(mutex->owner != NULL)) {
/*
* Recalculate the owner's priority across all mutexes it still
* holds; another held mutex may still justify a partial boost.
*/
int32_t new_prio = held_mutexes_highest_waiter_prio(
mutex->owner,
mutex->owner->orig_prio);
LOG_DBG("adjusting prio down on mutex %p", mutex);
resched = adjust_owner_prio(mutex, new_prio) || resched;
}
if (resched) {
z_reschedule(&mutex_lock, key);
} else {
k_spin_unlock(&mutex_lock, key);
}
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, -EAGAIN);
return -EAGAIN;
#else
SYS_PORT_TRACING_OBJ_FUNC_EXIT(k_mutex, lock, mutex, timeout, got_mutex);
return got_mutex;
#endif
}
kernel/mutex.c, lines 202–399 · Zephyr v4.5.0 · Apache-2.0 license
The first branch is the uncontended case: the mutex is free (or already ours), so the caller
becomes the owner and the mutex is added to its held_mutexes.
Otherwise the caller is going to wait. It records the mutex in mutex_pended_on and works out the
priority the owner should have:
static int32_t new_prio_for_inheritance(int32_t target, int32_t limit)
{
int new_prio = z_is_prio_higher(target, limit) ? target : limit;
new_prio = z_get_new_prio_with_ceiling(new_prio);
return new_prio;
}
kernel/mutex.c, lines 150–157 · Zephyr v4.5.0 · Apache-2.0 license
That is the more urgent of the caller’s and the owner’s priorities, limited by
CONFIG_PRIORITY_CEILING.
Then comes a loop that FreeRTOS does not have. It raises the owner, and if that owner is itself waiting for another mutex, it moves on to the owner of that mutex and raises it too, and so on along the chain. Without this, a high-priority thread could still be held up by a medium one two locks away. The loop stops when it reaches an owner that is not waiting, comes back to the mutex it started from, or has made a fixed number of hops.
The priority change itself goes through adjust_owner_prio():
static bool adjust_owner_prio(struct k_mutex *mutex, int32_t new_prio)
{
if (mutex->owner->base.prio != new_prio) {
LOG_DBG("%p (ready (y/n): %c) prio changed to %d (was %d)",
mutex->owner, z_is_thread_ready(mutex->owner) ?
'y' : 'n',
new_prio, mutex->owner->base.prio);
return z_thread_prio_set(mutex->owner, new_prio);
}
return false;
}
kernel/mutex.c, lines 159–171 · Zephyr v4.5.0 · Apache-2.0 license
z_thread_prio_set() takes the thread out of the run queue, changes its priority and puts it back
in its new position. In the scenario you can see Low move ahead of Med in
_kernel.ready_q.runq. Finally z_pend_curr() puts the caller on the mutex’s wait queue and
switches to the next thread, which is now Low.
Unlocking: work the priority out again
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 unlocking thread removes the mutex from its held_mutexes. If it is running at a priority
other than orig_prio, it does not simply go back to orig_prio. It asks what the mutexes it
still holds require:
static int32_t held_mutexes_highest_waiter_prio(struct k_thread *thread,
int32_t floor_prio)
{
sys_snode_t *node;
int32_t prio = floor_prio;
LOCK_SCHED_SPINLOCK {
SYS_SLIST_FOR_EACH_NODE(&thread->held_mutexes, node) {
struct k_mutex *m =
CONTAINER_OF(node, struct k_mutex, held_node);
struct k_thread *waiter = z_waitq_head_locked(&m->wait_q);
if (waiter != NULL) {
int32_t wprio = z_get_new_prio_with_ceiling(waiter->base.prio);
if (z_is_prio_higher(wprio, prio)) {
prio = wprio;
}
}
}
}
return prio;
}
kernel/mutex.c, lines 177–199 · Zephyr v4.5.0 · Apache-2.0 license
The function looks at the first waiter of every mutex the thread still holds and returns the most
urgent priority among them, or orig_prio if nobody waits. So a thread that holds two mutexes
drops exactly as far as it can when it releases one. FreeRTOS, by contrast, keeps the raised
priority until the last mutex is released. Compare both in the
nested mutexes lesson.
One consequence was confirmed on the real kernel while this simulator was built: a priority set with
k_thread_priority_set() on a thread that holds a mutex is lost when it unlocks, because the
unlock path restores from orig_prio, which was recorded earlier.
Handing the mutex over
The last part of k_mutex_unlock() takes the first thread off the wait queue and writes it into
mutex->owner directly. The mutex is never free in between, and the new owner has not run yet.
Mutex handoff shows where this differs from FreeRTOS.
When the waiter gives up
If k_mutex_lock() was called with a timeout and it runs out, z_pend_curr() returns an error and
the function continues after it. It recomputes the owner’s priority with the same
held_mutexes_highest_waiter_prio() and lowers the owner if no remaining waiter justifies the
boost. Only the direct owner is lowered. Owners further along a chain keep their raised priority
until they unlock; the kernel documents this as a known limitation. The
mutex timeout lesson runs this path.
Deadlock detection
The same chain walk can notice a cycle. With CONFIG_MUTEX_DEADLOCK_DETECT it asserts when the
chain leads back to the caller and every wait in it is K_FOREVER. The excerpt of
k_mutex_lock() above contains those lines, but the simulated configuration has the option off: it
is on by default only when assertions are enabled. See Deadlock.