HomeAbout UsContact Us

Fixing Zephyr Mutex PI: Debugging Inheritance Failures

By Jithin Tom
Published in Embedded OS
November 28, 2026
9 min read
Fixing Zephyr Mutex PI: Debugging Inheritance Failures

Table Of Contents

01
Symptoms That Bring Engineers Here
02
How Zephyr Priority Inheritance Works
03
Failure Mode 1: Nested Mutexes and Legacy owner_orig_prio (<= 4.4)
04
Failure Mode 2: Chain Walk Bounds (MUTEX_CHAIN_WALK_MAX_HOPS)
05
Failure Mode 3: Misconfiguring CONFIG_PRIORITY_CEILING
06
Failure Mode 4: Using k_sem Instead of k_mutex
07
Timeout Handling and Priority Drop Deferral
08
Diagnosing PI Failures: Thread Analyzer, Shell, Logs, and Tracing
09
Deadlock Detection: CONFIG_MUTEX_DEADLOCK_DETECT
10
Verification Checklist for Production Code
11
Complete Working Example: Multi-Hop Safe Locking
12
What CONFIG_PRIORITY_CEILING Actually Does (and Does Not Do)
13
SMP Considerations (CONFIG_SMP=y)
14
Summary
15
Related Reading
16
References
17
Frequently Asked Questions

Zephyr RTOS implements priority inheritance (PI) on k_mutex by default: when a higher-priority thread blocks on a mutex owned by a lower-priority thread, the kernel temporarily raises the holder’s effective priority to match the waiter (subject to CONFIG_PRIORITY_CEILING), bounding priority inversion. Yet engineers still run into cases where priority boosts fail to propagate, drop too early, remain elevated after unlock, or vanish entirely due to build configuration.

Critically, Zephyr’s mutex implementation changed significantly in Zephyr 4.5 (commit 1b60add1 in kernel/mutex.c), replacing single-mutex owner_orig_prio tracking with per-thread held_mutexes lists, transitive ownership-chain walking, and optional deadlock detection. Understanding both the legacy (<= 4.4) and modern (>= 4.5) behavior is essential when debugging production systems.

Symptoms That Bring Engineers Here

You are likely investigating one of these real-time scheduling anomalies:

  • A high-priority sensor or BLE thread misses deadlines while a lower-priority logging or storage thread runs uninterrupted
  • Thread priority drops prematurely or remains stuck at a boosted level after releasing nested mutexes (classic Zephyr <= 4.4 symptom)
  • k_mutex_lock() with K_FOREVER hangs indefinitely—or triggers an ASSERTION FAIL panic (mutex deadlock: ...) in CONFIG_ASSERT=y builds on Zephyr >= 4.5
  • Multi-hop contention chains fail to boost deeper owners (<= 4.4 has no chain walk; >= 4.5 caps walks at 16 hops)
  • An owner stays temporarily over-boosted after a blocked waiter times out with -EAGAIN

In nearly every case, the root cause traces back to one of five issues: legacy nested unlock behavior, chain-walk limits, misconfigured CONFIG_PRIORITY_CEILING, using k_sem instead of k_mutex, or timeout/SMP edge cases.

How Zephyr Priority Inheritance Works

Before examining kernel/mutex.c, keep Zephyr’s numeric priority convention in mind: numerically lower values represent higher scheduling urgency.

  • Cooperative priorities: -CONFIG_NUM_COOP_PRIORITIES to -1 (for default CONFIG_NUM_COOP_PRIORITIES=16, that is -16 down to -1, where -16 is most urgent)
  • Preemptible priorities: 0 to CONFIG_NUM_PREEMPT_PRIORITIES - 1 (for default CONFIG_NUM_PREEMPT_PRIORITIES=15, that is 0 to 14, where 0 is highest preemptible urgency)
  • Idle thread priority (K_IDLE_PRIO): CONFIG_NUM_PREEMPT_PRIORITIES (15 by default)—a positive integer, not -128

Single-Hop (<= 4.4) vs. Chained (>= 4.5) Inheritance

In Zephyr <= 4.4, k_mutex tracked priority inheritance locally per mutex via mutex->owner_orig_prio. Locking an uncontended mutex saved _current->base.prio in mutex->owner_orig_prio. When a higher-priority thread blocked, only that mutex’s immediate owner was boosted; if the owner was itself blocked on another mutex, the boost did not propagate further.

In Zephyr >= 4.5, each k_thread carries three PI fields (compiled in whenever Z_MUTEX_PI_ENABLED is true):

  • held_mutexes: a sys_slist_t linking every k_mutex currently owned by the thread
  • mutex_pended_on: pointer to the k_mutex the thread is currently blocked on (or NULL)
  • orig_prio: the thread’s true pre-inheritance priority, captured once when held_mutexes transitions from empty to non-empty

When thread H (high priority) blocks on mutex M1 held by thread L1, and L1 is blocked on M2 held by L2:

  1. H records _current->mutex_pended_on = &M1.
  2. The kernel computes boost_prio via new_prio_for_inheritance(_current->base.prio, M1.owner->base.prio), which applies z_get_new_prio_with_ceiling().
  3. The kernel walks the mutex_pended_on -> owner chain, raising each owner whose base.prio is lower urgency than boost_prio.
  4. When any thread unlocks a mutex, the kernel removes it from _current->held_mutexes and scans all remaining held mutexes to compute the highest waiting priority floored at _current->orig_prio.
+------------------------------------------------------------------------+
| PRIORITY INHERITANCE CHAIN WALK (ZEPHYR >= 4.5) |
+------------------------------------------------------------------------+
| |
| Thread H (prio -8, cooperative) |
| | |
| | calls k_mutex_lock(&M1, K_FOREVER) -> blocks |
| | H->mutex_pended_on = &M1 |
| v |
| Mutex M1 <---owned by--- Thread L1 (orig_prio 4) |
| | |
| | L1->mutex_pended_on = &M2 |
| v |
| Mutex M2 <---owned by--- Thread L2 (orig_prio 8) |
| |
| Chain walk result: L1 boosted (4 -> -8), L2 boosted (8 -> -8) |
| Walk stops at end of chain, deadlock cycle, or 16 hops |
| (MUTEX_CHAIN_WALK_MAX_HOPS = 16 in kernel/mutex.c) |
| |
+------------------------------------------------------------------------+

The Priority Boost Loop in kernel/mutex.c

In Zephyr >= 4.5, the contention path inside z_impl_k_mutex_lock() executes under a global k_spinlock (mutex_lock):

/* Simplified from Zephyr >= 4.5 kernel/mutex.c */
#if Z_MUTEX_PI_ENABLED
_current->mutex_pended_on = mutex;
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;
while (chain_owner != NULL) {
if (z_is_prio_higher(boost_prio, chain_owner->base.prio)) {
resched = adjust_owner_prio(chain_mutex, boost_prio) || resched;
}
if (chain_owner->mutex_pended_on == NULL ||
!z_is_thread_pending(chain_owner)) {
break;
}
chain_mutex = chain_owner->mutex_pended_on;
if (chain_mutex == mutex || ++hops >= MUTEX_CHAIN_WALK_MAX_HOPS) {
break;
}
chain_owner = chain_mutex->owner;
}
#endif

Notice two subtle safeguards in that loop:

  1. !z_is_thread_pending(chain_owner) prevents the walk from following a stale mutex_pended_on pointer if chain_owner just timed out on a finite wait (K_MSEC(...)) and has been unpended, but has not yet re-acquired mutex_lock to clear mutex_pended_on.
  2. ++hops >= MUTEX_CHAIN_WALK_MAX_HOPS bounds worst-case spinlock hold time under mutex_lock to 16 owner adjustments per lock attempt (stopping even if an uninvolved cycle exists deeper in the chain).

Failure Mode 1: Nested Mutexes and Legacy owner_orig_prio (<= 4.4)

If your firmware runs on Zephyr <= 4.4 (including Zephyr 3.7 LTS and 4.0–4.4 releases), the single most common priority inheritance bug is violating strict LIFO acquisition/unlocking on nested mutexes.

Why Non-LIFO Unlocking Breaks on Zephyr <= 4.4

In Zephyr <= 4.4, struct k_mutex stored only one integer per mutex (mutex->owner_orig_prio), and k_mutex_unlock() unconditionally called:

/* Zephyr <= 4.4 kernel/mutex.c */
adjust_owner_prio(mutex, mutex->owner_orig_prio);

This single-slot design causes two distinct failures when mutexes are not strictly nested and released in reverse order:

  1. Premature Priority Drop: Thread L (base priority 4) locks mutex_a (A.owner_orig_prio = 4), then locks mutex_b (B.owner_orig_prio = 4). High-priority thread H1 (-8) blocks on mutex_a (boosting L to -8), and H2 (-4) blocks on mutex_b. If L unlocks mutex_a first, k_mutex_unlock(&mutex_a) immediately resets L to A.owner_orig_prio (4), dropping L’s priority below H2 (-4) even though L still holds mutex_b!
  2. Stuck Elevated Priority: Thread L (base priority 4) locks mutex_a (A.owner_orig_prio = 4). H1 (-8) blocks on mutex_a, boosting L to -8. Next, L locks mutex_b, which records B.owner_orig_prio = -8 (the already-boosted priority!). L unlocks mutex_a (dropping to 4), then unlocks mutex_b—which “restores” L to B.owner_orig_prio (-8)! L now runs permanently at priority -8 with no mutexes held.
+------------------------------------------------------------------------+
| ZEPHYR <= 4.4 STUCK ELEVATED PRIORITY (LEGACY owner_orig_prio) |
+------------------------------------------------------------------------+
| |
| 1. L (prio 4) locks M_A --> M_A.owner_orig_prio = 4, L prio = 4 |
| 2. H (-8) blocks on M_A --> L boosted to prio -8 |
| 3. L (now -8!) locks M_B --> M_B.owner_orig_prio = -8 (CAPTURED!) |
| 4. L unlocks M_A first --> L restored to M_A.owner_orig_prio (4)|
| 5. L unlocks M_B second --> L set to M_B.owner_orig_prio (-8!) |
| |
| RESULT: L holds zero mutexes, yet stays stuck at priority -8 |
| |
+------------------------------------------------------------------------+

Even in LIFO order, acquiring mutex_b before mutex_a’s boost occurs and having H2 block on mutex_b only works cleanly if release happens in exact reverse order:

/* Safe across ALL Zephyr versions: strict LIFO unlock order */
void safe_nested_locking(void)
{
k_mutex_lock(&mutex_a, K_FOREVER);
k_mutex_lock(&mutex_b, K_FOREVER);
/* ... critical section ... */
k_mutex_unlock(&mutex_b); /* Release inner mutex first */
k_mutex_unlock(&mutex_a); /* Release outer mutex second */
}

How Zephyr >= 4.5 Fixes Nested Unlocking

In Zephyr >= 4.5, z_impl_k_mutex_unlock() no longer relies on per-mutex owner_orig_prio. Instead, it removes the released mutex from _current->held_mutexes first, then scans every remaining held mutex:

/* Actual logic from Zephyr >= 4.5 kernel/mutex.c (z_impl_k_mutex_unlock) */
#if Z_MUTEX_PI_ENABLED
sys_slist_find_and_remove(&_current->held_mutexes, &mutex->held_node);
if (_current->base.prio != _current->orig_prio) {
int32_t new_prio = held_mutexes_highest_waiter_prio(
_current, _current->orig_prio);
/* mutex->owner is still _current until wait_q handoff below */
adjust_owner_prio(mutex, new_prio);
}
#endif

Because held_mutexes_highest_waiter_prio() traverses all remaining locks in _current->held_mutexes and falls back to _current->orig_prio (which was captured before any boost occurred), unlocking mutex_a before mutex_b on Zephyr >= 4.5 preserves any boost justified by waiters on mutex_b and cleanly restores orig_prio once the final mutex is released.

Failure Mode 2: Chain Walk Bounds (MUTEX_CHAIN_WALK_MAX_HOPS)

Multi-hop priority inheritance behaves very differently depending on your Zephyr version:

  • Zephyr <= 4.4: There is no chain walk. A boost stops at hop 1 (the immediate owner of the contended mutex). If that owner is blocked on a second mutex held by a third thread, the third thread is never boosted.
  • Zephyr >= 4.5: The kernel walks the ownership chain up to MUTEX_CHAIN_WALK_MAX_HOPS, which is hardcoded in kernel/mutex.c as:
#define MUTEX_CHAIN_WALK_MAX_HOPS 16

Important correction: MUTEX_CHAIN_WALK_MAX_HOPS is a #define internal to kernel/mutex.c, not a Kconfig option (CONFIG_MUTEX_CHAIN_WALK_MAX_HOPS does not exist in Zephyr).

If a thread chain exceeds 16 hops, owners beyond the 16th hop keep their pre-boost priority during that lock attempt:

/* Scenario on Zephyr >= 4.5: 17-hop chain hits MUTEX_CHAIN_WALK_MAX_HOPS (16) */
Thread T0 (prio -8) blocks on M1 held by T1 (prio 0) /* hop 0: T1 boosted to -8 */
T1 blocks on M2 held by T2 (prio 1) /* hop 1: T2 boosted to -8 */
...
T15 blocks on M16 held by T16 (prio 13) /* hop 15: T16 boosted to -8; ++hops == 16 -> break */
T16 blocks on M17 held by T17 (prio 14) /* T17 NOT boosted! */

Because T17 remains at priority 14, any unrelated ready thread at priority 13 or higher preempts T17 and stalls the entire chain.

Solutions:

  1. Flatten lock nesting: Refactor layered drivers or middleware so threads rarely hold one mutex while acquiring another, keeping dependency chains shallow (ideally <= 2 hops).
  2. Replace cross-layer locks with message queues: Pass ownership of buffers via k_msgq or k_fifo instead of holding a producer lock across a consumer mutex.
  3. Upgrade if on Zephyr <= 4.4: Moving to Zephyr >= 4.5 enables transitive chain walking up to 16 hops out of the box.
  4. Patch kernel/mutex.c only if truly justified: Raising MUTEX_CHAIN_WALK_MAX_HOPS requires modifying kernel/mutex.c directly and increases worst-case k_spin_lock(&mutex_lock) duration (blocking interrupts on UP and contending across all cores on SMP).

Auditing Held Mutex Depth in Your Application (Zephyr >= 4.5)

To verify that no thread holds excessive concurrent mutexes in debug builds on Zephyr >= 4.5, you can iterate threads with k_thread_foreach() (requires CONFIG_THREAD_MONITOR=y):

#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
#include <zephyr/sys/slist.h>
#if defined(CONFIG_THREAD_MONITOR) && Z_MUTEX_PI_ENABLED
static int count_held_mutexes(struct k_thread *thread)
{
int count = 0;
sys_snode_t *node;
/* held_mutexes is an internal field defined when Z_MUTEX_PI_ENABLED is 1 */
SYS_SLIST_FOR_EACH_NODE(&thread->held_mutexes, node) {
count++;
}
return count;
}
static void audit_thread_cb(const struct k_thread *cthread, void *user_data)
{
struct k_thread *thread = (struct k_thread *)cthread;
ARG_UNUSED(user_data);
int depth = count_held_mutexes(thread);
if (depth > 4) {
const char *name = k_thread_name_get(thread);
printk("WARN: Thread %p (%s) holds %d mutexes\n",
(void *)thread,
(name != NULL && name[0] != '\0') ? name : "unnamed",
depth);
}
}
/* Call from a periodic diagnostic thread */
void mutex_depth_audit_once(void)
{
/* k_thread_foreach() locks interrupts during traversal on single-core */
k_thread_foreach(audit_thread_cb, NULL);
}
#endif

Note that thread->held_mutexes is an internal kernel field guarded by mutex_lock; on SMP builds (CONFIG_SMP=y), another core can modify held_mutexes concurrently with k_thread_foreach(), so run this audit only on single-core builds or during controlled diagnostic pauses.

Failure Mode 3: Misconfiguring CONFIG_PRIORITY_CEILING

One of the most misunderstood Kconfig symbols in Zephyr is CONFIG_PRIORITY_CEILING:

config PRIORITY_CEILING
int "Priority inheritance ceiling"
default -128
range -128 127

Remember Zephyr’s priority ordering: numerically lower = logically higher urgency.

  • -128 is the logically highest value in the range -128 to 127. Because it is numerically lower than every valid thread priority (>= -CONFIG_NUM_COOP_PRIORITIES), the default -128 means unlimited priority inheritance—PI is enabled by default.
  • K_IDLE_PRIO (K_LOWEST_THREAD_PRIO) equals CONFIG_NUM_PREEMPT_PRIORITIES (15 in a default build).

In include/zephyr/kernel/thread.h, Zephyr enables or compiles out all mutex priority inheritance using this exact preprocessor predicate:

#define Z_MUTEX_PI_ENABLED (CONFIG_PRIORITY_CEILING < CONFIG_NUM_PREEMPT_PRIORITIES)

(In Zephyr <= 4.4, kernel/mutex.c checks #if (CONFIG_PRIORITY_CEILING < K_LOWEST_THREAD_PRIO) directly, which is equivalent.)

Look at what happens with different prj.conf values when CONFIG_NUM_PREEMPT_PRIORITIES=15:

# Default: -128 < 15 -> PI ENABLED with no cap (cooperative & preemptible boosts allowed)
CONFIG_PRIORITY_CEILING=-128
# Capped: 0 < 15 -> PI ENABLED, but boosts stop at preemptible priority 0
# (Prevents preemptible mutex holders from inheriting negative cooperative priorities)
CONFIG_PRIORITY_CEILING=0
# Disabled: 15 >= 15 (at or numerically above K_IDLE_PRIO) -> PI COMPLETELY DISABLED!
CONFIG_PRIORITY_CEILING=15

If an engineer mistakenly assumes larger positive numbers mean “higher” priority and sets CONFIG_PRIORITY_CEILING=15 (or 127), or lowers CONFIG_NUM_PREEMPT_PRIORITIES below a positive ceiling value, Z_MUTEX_PI_ENABLED evaluates to 0 at compile time. All priority boosting, held_mutexes tracking, chain walking, and CONFIG_MUTEX_DEADLOCK_DETECT compile out silently.

Enforcing PI at Compile Time

Instead of waiting for missed deadlines in production, add a compile-time assertion right in your application (#include <zephyr/kernel.h>):

#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
BUILD_ASSERT(CONFIG_PRIORITY_CEILING < CONFIG_NUM_PREEMPT_PRIORITIES,
"CONFIG_PRIORITY_CEILING disables k_mutex priority inheritance");
void print_pi_config(void)
{
printk("k_mutex PI enabled: ceiling=%d, idle_prio=%d\n",
CONFIG_PRIORITY_CEILING, CONFIG_NUM_PREEMPT_PRIORITIES);
}

Because BUILD_ASSERT checks the exact condition used by Z_MUTEX_PI_ENABLED, any prj.conf override that disables PI fails the build immediately.

Failure Mode 4: Using k_sem Instead of k_mutex

A binary semaphore (k_sem initialized with initial count 1 and limit 1) provides mutual exclusion, but zero priority inheritance. Unlike k_mutex, k_sem has no owner thread field—any thread or ISR can call k_sem_give(), so the kernel has no thread to boost when a high-priority waiter blocks on k_sem_take().

/* WRONG: Binary semaphore used as a lock (unbounded priority inversion) */
K_SEM_DEFINE(sensor_lock, 1, 1);
void read_sensor_wrong(void)
{
k_sem_take(&sensor_lock, K_FOREVER); /* No ownership, no PI */
/* ... access shared bus ... */
k_sem_give(&sensor_lock);
}

Fix: Always use k_mutex for mutual exclusion between threads, and reserve k_sem for producer/consumer or ISR-to-thread signaling:

/* CORRECT: Mutex with ownership and priority inheritance */
K_MUTEX_DEFINE(sensor_mutex);
void read_sensor_safe(void)
{
k_mutex_lock(&sensor_mutex, K_FOREVER); /* PI active */
/* ... access shared bus ... */
k_mutex_unlock(&sensor_mutex);
}

Quick Audit: Find Binary Semaphores Used as Mutexes

# Search application and driver code for binary semaphores used as locks
grep -rn "k_sem_init.*1,\s*1" --include="*.c" --include="*.h" .
grep -rn "K_SEM_DEFINE.*1,\s*1" --include="*.c" --include="*.h" .
grep -rn "k_sem_take.*K_FOREVER" --include="*.c" --include="*.h" .

Any binary semaphore protecting shared state between threads (where k_sem_take() and k_sem_give() bracket a critical section in the same thread) should be converted to k_mutex.

Timeout Handling and Priority Drop Deferral

When a waiting thread calls k_mutex_lock(&m, K_MSEC(100)) and times out before the mutex is unlocked, the owner’s priority cannot be lowered inside the system timer ISR. Instead, priority restoration is deferred to the waiter’s thread context once z_pend_curr() returns -EAGAIN:

/* Actual timeout recovery path in Zephyr >= 4.5 kernel/mutex.c */
key = k_spin_lock(&mutex_lock);
_current->mutex_pended_on = NULL;
if (likely(mutex->owner != NULL)) {
int32_t new_prio = held_mutexes_highest_waiter_prio(
mutex->owner,
mutex->owner->orig_prio);
resched = adjust_owner_prio(mutex, new_prio) || resched;
}

Kernel comments in kernel/mutex.c document two important consequences of this design:

  1. ISR safety and lock-order preservation: Updating owner priorities from the timer handler would require acquiring mutex_lock from ISR context. On single-core targets, k_spin_lock(&mutex_lock) masks interrupts; on SMP targets, acquiring mutex_lock while the timer handler holds _sched_spinlock would invert the mutex_lock -> _sched_spinlock ordering used in k_mutex_unlock() and deadlock. Deferring the drop until the waiter resumes means the owner can briefly execute at an elevated priority between timeout expiry and the waiter thread running.
  2. No multi-hop priority-down propagation on timeout (>= 4.5): When a waiter times out in a multi-hop ownership chain, kernel/mutex.c recalculates only the immediate mutex->owner’s priority. Deeper owners in the chain stay over-boosted until they unlock their own mutexes (because walking the chain down inside the timeout recovery or ISR would require scanning all waiters across arbitrary chain depths).

For hard real-time threads sensitive to priority-drop jitter, avoid finite lock timeouts on contended paths when possible—or structure tasks to use lock-free/queue-based handoff instead of timed mutex polling.

Diagnosing PI Failures: Thread Analyzer, Shell, Logs, and Tracing

Zephyr offers four complementary ways to observe whether priority inheritance is firing at runtime.

1. Thread Analyzer (CONFIG_THREAD_ANALYZER)

Enable Thread Analyzer in prj.conf—and make sure to include CONFIG_THREAD_ANALYZER_PRINT_THREAD_PRIORITY=y (priority printing is off by default) and CONFIG_THREAD_NAME=y:

CONFIG_THREAD_NAME=y
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_AUTO=y
# Auto-print interval in seconds (valid range: 5 to 3600, default 60)
CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5
CONFIG_THREAD_ANALYZER_PRINT_THREAD_PRIORITY=y

With those options enabled, subsys/debug/thread_analyzer/thread_analyzer.c prints each thread’s stack metrics, CPU utilization, and current effective priority (thread->base.prio):

Thread analyze:
sensor_rx : STACK: unused 612 usage 412 / 1024 ( 40 %); CPU: 12 %
: Total CPU cycles used: 184320
: PRIORITY: -8
log_writer : STACK: unused 540 usage 484 / 1024 ( 47 %); CPU: 24 %
: Total CPU cycles used: 369100
: PRIORITY: -8

Notice that Thread Analyzer prints the thread’s current effective PRIORITY: at the time of the scan (not thread state, mutex pointer, or original priority). Seeing log_writer temporarily print PRIORITY: -8 instead of its configured base priority 4 confirms PI is boosting it.

2. Zephyr Shell (kernel thread list) and Kernel Mutex Debug Logs

To inspect thread state (pending, ready, etc.) alongside priority interactively, enable the kernel shell:

CONFIG_SHELL=y
CONFIG_KERNEL_SHELL=y
CONFIG_THREAD_MONITOR=y
CONFIG_THREAD_NAME=y

Running kernel thread list in the shell prints priority: <prio> and state: <state> for every thread. Alternatively, for immediate log evidence of every boost and restore event in kernel/mutex.c, enable kernel debug logging (CONFIG_LOG=y and CONFIG_KERNEL_LOG_LEVEL_DBG=y), which emits LOG_DBG lines directly from adjust_owner_prio():

<dbg> os: adjust_owner_prio: 0x20001480 (ready (y/n): y) prio changed to -8 (was 4)

3. SEGGER SystemView, Percepio Tracealyzer, or CTF Timeline Tracing

Periodic polling can miss short millisecond-long mutex contentions. Continuous event tracing captures every priority change deterministically because z_thread_prio_set() calls SYS_PORT_TRACING_OBJ_FUNC(k_thread, sched_priority_set, thread, prio) inside kernel/sched.c alongside k_mutex_lock and k_mutex_unlock hooks:

# SEGGER SystemView over RTT (or use: west build -S rtt-tracing)
CONFIG_TRACING=y
CONFIG_SEGGER_SYSTEMVIEW=y
# Enable if capturing startup before the SystemView host attaches
CONFIG_SEGGER_SYSTEMVIEW_BOOT_ENABLE=y
# Alternative: Percepio Tracealyzer (requires Percepio module)
# CONFIG_TRACING=y
# CONFIG_PERCEPIO_TRACERECORDER=y
# Alternative: Common Trace Format (CTF)
# CONFIG_TRACING=y
# CONFIG_TRACING_CTF=y

Build with the Zephyr rtt-tracing snippet or explicit Kconfig flags, copy the Zephyr API description file so SystemView decodes kernel calls properly, and record in the SEGGER SystemView application:

# Build with SEGGER SystemView tracing enabled
west build -b your_board -S rtt-tracing
# Ensure SystemView uses Zephyr's current event table (Linux/macOS example)
cp "$ZEPHYR_BASE/subsys/tracing/sysview/SYSVIEW_Zephyr.txt" ~/.config/SEGGER/

In a healthy PI trace, k_mutex_lock blocking on a contended mutex is immediately accompanied by a sched_priority_set event raising the owner before the waiter pends, followed by a matching sched_priority_set restoration when the owner calls k_mutex_unlock:

Time | Thread | Trace Event
--------+---------------+---------------------------------------------
1002 ms | sensor_rx | k_mutex_lock(&M1) -> blocking (owner=log_writer)
1002 ms | log_writer | sched_priority_set: 4 -> -8
1005 ms | log_writer | k_mutex_unlock(&M1)
1005 ms | log_writer | sched_priority_set: -8 -> 4
1005 ms | sensor_rx | k_mutex_lock(&M1) -> acquired (0)

For post-mortem crash captures after a missed deadline or watchdog reset, enable CONFIG_SEGGER_SYSVIEW_POST_MORTEM_MODE=y and attach with west attach to load the retained RTT ring buffer into SystemView.

Deadlock Detection: CONFIG_MUTEX_DEADLOCK_DETECT

Added in Zephyr 4.5, CONFIG_MUTEX_DEADLOCK_DETECT (default y, depends on ASSERT) detects circular wait deadlocks during the priority-inheritance chain walk:

/* Thread 1 holds mutex_a and blocks forever on mutex_b;
* Thread 2 holds mutex_b and calls: */
k_mutex_lock(&mutex_a, K_FOREVER); /* Triggers __ASSERT(false, "mutex deadlock: ...") */

Key constraints of CONFIG_MUTEX_DEADLOCK_DETECT:

  1. Disabled in release builds without CONFIG_ASSERT=y: Because it depends on ASSERT, turning assertions off silently removes deadlock detection.
  2. Triggers an assertion panic, not -EDEADLK: k_mutex_lock() returns only 0, -EBUSY (on K_NO_WAIT), or -EAGAIN (on timeout). When a cycle is detected, kernel/mutex.c invokes __ASSERT(false, "mutex deadlock: thread %p waiting on mutex %p (owner %p)", ...).
  3. Only flags all-K_FOREVER cycles: The detector tracks all_forever across every hop in the cycle (z_is_inactive_timeout(&chain_owner->base.timeout)). Any finite timeout (K_MSEC(...)) along the cycle suppresses the assertion because that waiter will recover with -EAGAIN.
  4. Coupled to Z_MUTEX_PI_ENABLED: Because deadlock detection runs inside the PI chain walk, setting CONFIG_PRIORITY_CEILING >= CONFIG_NUM_PREEMPT_PRIORITIES disables deadlock detection too.

Verification Checklist for Production Code

CheckHow to Verify
Priority inheritance enabledVerify CONFIG_PRIORITY_CEILING < CONFIG_NUM_PREEMPT_PRIORITIES in build/zephyr/.config or via BUILD_ASSERT (default -128 is enabled)
No k_sem used as mutexAudit k_sem_init(..., 1, 1) / K_SEM_DEFINE(..., 1, 1) and convert shared-resource locks to k_mutex
Consistent global lock orderVerify all threads acquire multi-lock sets in the same global order; enforce reverse (LIFO) unlock order (mandatory on Zephyr <= 4.4)
Chain depth within boundsKeep transitive blocking chains shallow (<= 16 hops on Zephyr >= 4.5; avoid chained blocking on <= 4.4 where no chain walk exists)
Deadlock detection in CI/debugBuild test targets with CONFIG_ASSERT=y and CONFIG_MUTEX_DEADLOCK_DETECT=y (Zephyr >= 4.5)
Runtime boost verifiedCapture SystemView (CONFIG_TRACING=y, CONFIG_SEGGER_SYSTEMVIEW=y) or CONFIG_KERNEL_LOG_LEVEL_DBG=y confirming boost and restore

Complete Working Example: Multi-Hop Safe Locking

This self-contained Zephyr example uses K_MUTEX_DEFINE (preventing startup initialization races with K_THREAD_DEFINE threads), enforces a strict global lock order (sensor_mutex -> log_mutex -> ble_mutex) with LIFO unlocking, and validates PI at compile time:

/* sensor_mutex.c - Deterministic Zephyr mutex PI pattern */
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>
/* Fail the build immediately if k_mutex PI is disabled or priority counts are too narrow */
BUILD_ASSERT(CONFIG_PRIORITY_CEILING < CONFIG_NUM_PREEMPT_PRIORITIES,
"CONFIG_PRIORITY_CEILING disables k_mutex priority inheritance");
BUILD_ASSERT(CONFIG_NUM_COOP_PRIORITIES > 8,
"K_PRIO_COOP(8) requires at least 9 cooperative priorities");
BUILD_ASSERT(CONFIG_NUM_PREEMPT_PRIORITIES > 8,
"K_PRIO_PREEMPT(8) requires at least 9 preemptible priorities");
/* Compile-time initialized mutexes; global lock order: SENSOR -> LOG -> BLE */
K_MUTEX_DEFINE(sensor_mutex);
K_MUTEX_DEFINE(log_mutex);
K_MUTEX_DEFINE(ble_mutex);
/* High-priority cooperative sensor RX thread (prio -8 under default 16 coop prios) */
void sensor_rx_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
while (1) {
k_mutex_lock(&sensor_mutex, K_FOREVER);
k_mutex_lock(&log_mutex, K_FOREVER);
printk("sensor_rx: copying frame to log buffer\n");
/* Reverse (LIFO) unlock order ensures safe behavior even on Zephyr <= 4.4 */
k_mutex_unlock(&log_mutex);
k_mutex_unlock(&sensor_mutex);
k_msleep(100);
}
}
/* Medium-priority preemptible log writer */
void log_writer_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
while (1) {
k_mutex_lock(&log_mutex, K_FOREVER);
k_mutex_lock(&ble_mutex, K_FOREVER);
/* Short simulated work inside lock */
k_busy_wait(2000);
printk("log_writer: queuing log record for BLE\n");
k_mutex_unlock(&ble_mutex);
k_mutex_unlock(&log_mutex);
k_msleep(200);
}
}
/* Low-priority preemptible BLE TX thread */
void ble_tx_thread(void *p1, void *p2, void *p3)
{
ARG_UNUSED(p1);
ARG_UNUSED(p2);
ARG_UNUSED(p3);
while (1) {
k_mutex_lock(&ble_mutex, K_FOREVER);
/* 30 ms CPU work allows log_writer (t=10 ms) and sensor_rx (t=20 ms)
* to preempt and form a 2-hop contention chain */
k_busy_wait(30000);
printk("ble_tx: transmitting packet\n");
k_mutex_unlock(&ble_mutex);
k_msleep(500);
}
}
K_THREAD_DEFINE(ble_tx_id, 1024, ble_tx_thread, NULL, NULL, NULL,
K_PRIO_PREEMPT(8), 0, 0);
K_THREAD_DEFINE(log_writer_id, 1024, log_writer_thread, NULL, NULL, NULL,
K_PRIO_PREEMPT(4), 0, 10);
K_THREAD_DEFINE(sensor_rx_id, 1024, sensor_rx_thread, NULL, NULL, NULL,
K_PRIO_COOP(8), 0, 20);
int main(void)
{
printk("Zephyr PI demo started (CONFIG_PRIORITY_CEILING=%d)\n",
CONFIG_PRIORITY_CEILING);
return 0;
}

Why this pattern works cleanly:

  • Static K_MUTEX_DEFINE() guarantees all three mutexes are ready before ble_tx_id (0 ms delay), log_writer_id (10 ms), or sensor_rx_id (20 ms) begins executing.
  • Global acquisition order (sensor_mutex -> log_mutex -> ble_mutex) prevents AB-BA deadlocks across all threads.
  • Reverse unlocking (ble_mutex then log_mutex, log_mutex then sensor_mutex) prevents premature drops and stuck priorities on Zephyr <= 4.4 while keeping lock lifetimes minimal on >= 4.5.
  • Because ble_tx_thread (prio 8) starts at t = 0 ms and holds ble_mutex for 30 ms, log_writer_thread (prio 4) preempts it at t = 10 ms, acquires log_mutex, and blocks on ble_mutex (boosting ble_tx to 4). At t = 20 ms, sensor_rx_thread (prio -8) preempts ble_tx, acquires sensor_mutex, and blocks on log_mutex—causing Zephyr >= 4.5 to walk the chain and boost both log_writer and ble_tx to -8.

What CONFIG_PRIORITY_CEILING Actually Does (and Does Not Do)

Do not confuse Zephyr’s CONFIG_PRIORITY_CEILING with the Immediate Priority Ceiling Protocol (IPCP) found in OSEK or POSIX PTHREAD_PRIO_PROTECT mutexes.

  • What it does NOT do: Setting CONFIG_PRIORITY_CEILING=0 or -16 does not boost a thread immediately upon locking an uncontended mutex, and it does not eliminate chain walks.
  • What it ACTUALLY does: z_get_new_prio_with_ceiling() clamps any priority inheritance boost so no thread is ever boosted to a priority numerically lower (higher urgency) than CONFIG_PRIORITY_CEILING.

The practical use case for raising CONFIG_PRIORITY_CEILING (for example, CONFIG_PRIORITY_CEILING=0) is protecting cooperative threads:

# Keep PI active for all preemptible priorities (0..14),
# but prevent preemptible threads from inheriting cooperative priorities (< 0)
CONFIG_PRIORITY_CEILING=0

If you need strictly bounded, zero-chain-walk synchronization latency, redesign around single-owner actor threads communicating over k_msgq or non-nested single locks rather than attempting to emulate IPCP with CONFIG_PRIORITY_CEILING.

SMP Considerations (CONFIG_SMP=y)

On multi-core Zephyr targets (CONFIG_SMP=y), mutex priority inheritance carries additional synchronization costs:

  • Global mutex_lock spinlock: kernel/mutex.c serializes all PI chain walks, held_mutexes updates, and mutex handoffs behind a single global k_spinlock (mutex_lock), because chain walks read and modify fields belonging to multiple mutexes and threads.
  • Lock hierarchy and ready queues: Inside adjust_owner_prio(), z_thread_prio_set() acquires _sched_spinlock inside mutex_lock (mutex_lock -> _sched_spinlock). By default (!CONFIG_SCHED_CPU_MASK_PIN_ONLY), SMP uses a shared global _kernel.ready_q; per-CPU ready queues exist only when CONFIG_SCHED_CPU_MASK_PIN_ONLY=y.
  • Cross-core IPIs: When z_thread_prio_set() raises a ready thread’s priority (or lowers a thread actively executing on another core), it calls flag_ipi() to notify remote CPUs to reschedule.

To minimize cross-core contention under SMP:

  • Keep mutex critical sections short so two cores rarely contend on mutex_lock simultaneously
  • Keep nested locking chains shallow (<= 2 hops) to minimize global mutex_lock hold time during chain walks
  • Use k_thread_cpu_pin() where core isolation and cache locality reduce cross-core wakeups (remembering k_thread_cpu_pin() requires the target thread not to be runnable when called, unless pinning before start)

Summary

Reliable Zephyr mutex priority inheritance requires matching your locking design and configuration to your kernel version:

  1. Keep CONFIG_PRIORITY_CEILING below CONFIG_NUM_PREEMPT_PRIORITIES — default -128 enables unlimited PI; setting it at or numerically above K_IDLE_PRIO disables PI and deadlock detection silently.
  2. Acquire in global order and unlock in reverse (LIFO) order — mandatory on Zephyr <= 4.4 to avoid owner_orig_prio drops and stuck priorities, and best practice on >= 4.5.
  3. Know your chain limits — Zephyr <= 4.4 only boosts hop 1; Zephyr >= 4.5 walks up to MUTEX_CHAIN_WALK_MAX_HOPS (16, hardcoded in kernel/mutex.c), and timeouts do not propagate priority reductions down multi-hop chains.
  4. Never substitute k_sem for k_mutex — semaphores lack ownership tracking and provide zero priority inheritance.
  5. Verify with real runtime evidence — enable CONFIG_THREAD_ANALYZER_PRINT_THREAD_PRIORITY=y, CONFIG_KERNEL_LOG_LEVEL_DBG=y, or CONFIG_TRACING=y + CONFIG_SEGGER_SYSTEMVIEW=y to confirm sched_priority_set boosts and restores under load.

References

  1. Zephyr Project Documentation, “Mutexes — Priority Inheritance”, https://docs.zephyrproject.org/latest/kernel/services/synchronization/mutexes.html#priority-inheritance
  2. Zephyr Project Documentation, “Kconfig: CONFIG_PRIORITY_CEILING”, https://docs.zephyrproject.org/latest/kconfig.html#CONFIG_PRIORITY_CEILING
  3. Zephyr Project Documentation, “Kconfig: CONFIG_MUTEX_DEADLOCK_DETECT”, https://docs.zephyrproject.org/latest/kconfig.html#CONFIG_MUTEX_DEADLOCK_DETECT
  4. Zephyr Project Documentation, “Thread Analyzer” and API Reference, https://docs.zephyrproject.org/latest/services/debugging/thread-analyzer.html and https://docs.zephyrproject.org/apidoc/latest/thread__analyzer_8h.html
  5. Zephyr Project Documentation, “Tracing (SEGGER SystemView, Percepio Tracealyzer, CTF)“, https://docs.zephyrproject.org/latest/services/tracing/index.html
  6. Zephyr Project Blog, “RTOS Debugging: When the Important Stuff Has to Wait”, https://zephyrproject.org/rtos-debugging-when-the-important-stuff-has-to-wait/
  7. Zephyr Kernel Source, kernel/mutex.c, https://github.com/zephyrproject-rtos/zephyr/blob/main/kernel/mutex.c

Frequently Asked Questions

Why does Zephyr mutex priority inheritance sometimes not work as expected?

On Zephyr 4.4 and earlier, struct k_mutex only tracks a single owner_orig_prio field, so releasing nested mutexes out of LIFO order or acquiring a mutex while boosted causes premature priority drops or stuck elevated priorities, and boosts do not propagate across multi-hop chains. On Zephyr 4.5 and later, per-thread held_mutexes tracking fixes non-LIFO unlocking and enables transitive chain walking, but chain propagation stops at MUTEX_CHAIN_WALK_MAX_HOPS (16 in kernel/mutex.c), and waiter timeouts do not propagate priority reductions past the immediate owner. Across all versions, setting CONFIG_PRIORITY_CEILING >= CONFIG_NUM_PREEMPT_PRIORITIES disables priority inheritance completely.

How can I verify priority inheritance is actually working on my Zephyr system?

Enable CONFIG_THREAD_ANALYZER=y, CONFIG_THREAD_ANALYZER_AUTO=y, and CONFIG_THREAD_ANALYZER_PRINT_THREAD_PRIORITY=y (or use the Zephyr shell 'kernel thread list' command with CONFIG_KERNEL_SHELL=y) to inspect effective thread priorities at runtime. For kernel-level logs, enable CONFIG_LOG=y and CONFIG_KERNEL_LOG_LEVEL_DBG=y. For timeline capture of priority boosts during contention, enable CONFIG_TRACING=y with CONFIG_SEGGER_SYSTEMVIEW=y or CONFIG_PERCEPIO_TRACERECORDER=y.

What is the difference between k_mutex and k_sem for mutual exclusion in Zephyr?

k_mutex tracks the owning k_thread, supports reentrant locking via lock_count, can only be used in thread context, and implements priority inheritance. k_sem is a counting semaphore with no ownership tracking and zero priority inheritance; using a binary semaphore for mutual exclusion is a common cause of unbounded priority inversion.

How do I fix priority inheritance failures caused by nested mutexes?

Prefer holding at most one mutex at a time. When multiple mutexes are unavoidable, acquire them in a consistent global order (to prevent AB-BA deadlocks) and release them in exact reverse (LIFO) order, which is mandatory on Zephyr 4.4 and earlier due to single-slot owner_orig_prio tracking. If possible, upgrade to Zephyr 4.5 or later, which tracks held_mutexes per thread and scans remaining locks on every unlock.

What kernel configuration options affect mutex priority inheritance behavior?

CONFIG_PRIORITY_CEILING (default -128, range -128 to 127) sets the numerically lowest (logically highest) priority a thread can inherit; -128 permits unlimited inheritance, while setting it at or numerically above CONFIG_NUM_PREEMPT_PRIORITIES (at or lower urgency than the idle thread) disables priority inheritance completely. CONFIG_MUTEX_DEADLOCK_DETECT (default y, depends on CONFIG_ASSERT, added in Zephyr 4.5) triggers an assertion on K_FOREVER deadlock cycles when PI is active. MUTEX_CHAIN_WALK_MAX_HOPS (16 in kernel/mutex.c, added in Zephyr 4.5) is a hardcoded macro, not a Kconfig symbol, that bounds chain traversal.

Tags

zephyrrtosmutexpriority-inheritancedebuggingscheduling

Share


Previous Article
Fixing Function Pointer Corruption from Buffer Overruns in C
Jithin Tom

Jithin Tom

A Closer Look at C/C++, RTOS, and Embedded Systems

Related Posts

Fixing FreeRTOS Timer Task Stall When Command Queue Is Full
Fixing FreeRTOS Timer Task Stall When Command Queue Is Full
November 17, 2026
13 min
© 2026, All Rights Reserved.
Powered By Netlyft

Quick Links

Advertise with usAbout UsContact Us

Social Media