
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.
You are likely investigating one of these real-time scheduling anomalies:
<= 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<= 4.4 has no chain walk; >= 4.5 caps walks at 16 hops)-EAGAINIn 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.
Before examining kernel/mutex.c, keep Zephyr’s numeric priority convention in mind: numerically lower values represent higher scheduling urgency.
-CONFIG_NUM_COOP_PRIORITIES to -1 (for default CONFIG_NUM_COOP_PRIORITIES=16, that is -16 down to -1, where -16 is most urgent)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)K_IDLE_PRIO): CONFIG_NUM_PREEMPT_PRIORITIES (15 by default)—a positive integer, not -128<= 4.4) vs. Chained (>= 4.5) InheritanceIn 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 threadmutex_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-emptyWhen thread H (high priority) blocks on mutex M1 held by thread L1, and L1 is blocked on M2 held by L2:
H records _current->mutex_pended_on = &M1.boost_prio via new_prio_for_inheritance(_current->base.prio, M1.owner->base.prio), which applies z_get_new_prio_with_ceiling().mutex_pended_on -> owner chain, raising each owner whose base.prio is lower urgency than boost_prio._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) || |+------------------------------------------------------------------------+
kernel/mutex.cIn 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:
!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.++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).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.
<= 4.4In 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:
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!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 */}
>= 4.5 Fixes Nested UnlockingIn 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_ENABLEDsys_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.
MUTEX_CHAIN_WALK_MAX_HOPS)Multi-hop priority inheritance behaves very differently depending on your Zephyr version:
<= 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.>= 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:
<= 2 hops).k_msgq or k_fifo instead of holding a producer lock across a consumer mutex.<= 4.4: Moving to Zephyr >= 4.5 enables transitive chain walking up to 16 hops out of the box.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).>= 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_ENABLEDstatic 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.
CONFIG_PRIORITY_CEILINGOne of the most misunderstood Kconfig symbols in Zephyr is CONFIG_PRIORITY_CEILING:
config PRIORITY_CEILINGint "Priority inheritance ceiling"default -128range -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.
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.
k_sem Instead of k_mutexA 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);}
# Search application and driver code for binary semaphores used as locksgrep -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.
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:
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.>= 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.
Zephyr offers four complementary ways to observe whether priority inheritance is firing at runtime.
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=yCONFIG_THREAD_ANALYZER=yCONFIG_THREAD_ANALYZER_AUTO=y# Auto-print interval in seconds (valid range: 5 to 3600, default 60)CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5CONFIG_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: -8log_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.
kernel thread list) and Kernel Mutex Debug LogsTo inspect thread state (pending, ready, etc.) alongside priority interactively, enable the kernel shell:
CONFIG_SHELL=yCONFIG_KERNEL_SHELL=yCONFIG_THREAD_MONITOR=yCONFIG_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)
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=yCONFIG_SEGGER_SYSTEMVIEW=y# Enable if capturing startup before the SystemView host attachesCONFIG_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 enabledwest 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 -> -81005 ms | log_writer | k_mutex_unlock(&M1)1005 ms | log_writer | sched_priority_set: -8 -> 41005 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.
CONFIG_MUTEX_DEADLOCK_DETECTAdded 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:
CONFIG_ASSERT=y: Because it depends on ASSERT, turning assertions off silently removes deadlock detection.-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)", ...).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.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.| Check | How to Verify |
|---|---|
| Priority inheritance enabled | Verify CONFIG_PRIORITY_CEILING < CONFIG_NUM_PREEMPT_PRIORITIES in build/zephyr/.config or via BUILD_ASSERT (default -128 is enabled) |
No k_sem used as mutex | Audit k_sem_init(..., 1, 1) / K_SEM_DEFINE(..., 1, 1) and convert shared-resource locks to k_mutex |
| Consistent global lock order | Verify all threads acquire multi-lock sets in the same global order; enforce reverse (LIFO) unlock order (mandatory on Zephyr <= 4.4) |
| Chain depth within bounds | Keep 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/debug | Build test targets with CONFIG_ASSERT=y and CONFIG_MUTEX_DEADLOCK_DETECT=y (Zephyr >= 4.5) |
| Runtime boost verified | Capture SystemView (CONFIG_TRACING=y, CONFIG_SEGGER_SYSTEMVIEW=y) or CONFIG_KERNEL_LOG_LEVEL_DBG=y confirming boost and restore |
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:
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.sensor_mutex -> log_mutex -> ble_mutex) prevents AB-BA deadlocks across all threads.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.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.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.
CONFIG_PRIORITY_CEILING=0 or -16 does not boost a thread immediately upon locking an uncontended mutex, and it does not eliminate chain walks.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.
CONFIG_SMP=y)On multi-core Zephyr targets (CONFIG_SMP=y), mutex priority inheritance carries additional synchronization costs:
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.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.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:
mutex_lock simultaneously<= 2 hops) to minimize global mutex_lock hold time during chain walksk_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)Reliable Zephyr mutex priority inheritance requires matching your locking design and configuration to your kernel version:
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.<= 4.4 to avoid owner_orig_prio drops and stuck priorities, and best practice on >= 4.5.<= 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.k_sem for k_mutex — semaphores lack ownership tracking and provide zero priority inheritance.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.kernel/mutex.c, https://github.com/zephyrproject-rtos/zephyr/blob/main/kernel/mutex.cQuick Links
Legal Stuff





