
Zephyr’s second-generation workqueue (kernel/work.c) is the backbone of deferred execution in countless embedded projects. Since its introduction in Zephyr 2.6.0, it has replaced the legacy workqueue API with a design built around the kernel’s unified timeout subsystem. But a subtle SMP race condition has lurked in k_work_delayable handling: when a timeout expires and its callback is in-flight, a concurrent k_work_reschedule_for_queue() or k_work_cancel_delayable_sync() can proceed without waiting. The result — duplicate work submission, lost work items, or a kernel use-after-free (CVE-2026-12365, GHSA-rhmh-r93p-6g99).
This article dissects the race window, shows why the documented “safe” cancellation APIs fail, and walks through the exact fix merged in Zephyr 4.5.0 so you can backport it or verify your vendor SDK has it.
A k_work_delayable item goes through two distinct states during its lifecycle:
+------------------------------------------------------------------+| k_work_delayable STATE MACHINE |+------------------------------------------------------------------+| || IDLE --(k_work_schedule)--> DELAYED (K_WORK_DELAYED_BIT) || ^ | || | v || | +------------------+ || +-------------------------| timeout expires | || | z_abort_timeout | || | returns 0 / -EINVAL || +------------------+ || || DELAYED --(k_work_cancel_sync)--> IDLE (if abort succeeds) || || DELAYED --(timeout callback)--> SUBMITTED to workqueue || |+------------------------------------------------------------------+
The critical window opens when sys_clock_announce() processes an expired timeout. The timeout subsystem removes the timeout from its queue, releases the timeout queue lock, and then invokes the callback. This lock release is intentional — it prevents holding a spinlock across a potentially long-running callback — but it creates a window where the timeout is logically “expired” but not yet “handled.”
/* kernel/timeout.c - simplified */void sys_clock_announce(int32_t ticks){k_spinlock_key_t key = k_spin_lock(&timeout_q_lock);struct timeout *to = z_timeout_q_remove(&timeout_q);k_spin_unlock(&timeout_q_lock, key); /* LOCK RELEASED HERE */if (to->fn) {to->fn(to); /* Callback runs WITHOUT the timeout_q_lock */}}
The timeout callback for delayable work is work_timeout(). In affected versions, it checks the K_WORK_DELAYED_BIT flag and submits the work to the workqueue if the flag is set:
/* kernel/work.c - simplified, pre-fix */static void work_timeout(struct timeout *to){struct k_work_delayable *dwork = CONTAINER_OF(to, struct k_work_delayable, timeout);struct k_work *work = &dwork->work;if (atomic_test_and_clear_bit(&work->flags, K_WORK_DELAYED_BIT)) {/* Submit to workqueue */k_work_submit_to_queue(dwork->queue, work);}}
The race manifests most clearly when a delayable work item is rescheduled while its previous timeout is in the process of expiring. Consider this timeline on an SMP system:
+------------------------------------------------------------------+| RACE CONDITION TIMELINE (SMP) |+------------------------------------------------------------------+| || CPU 0 (timeout path) CPU 1 (reschedule/cancel) || ------------ ------------------- || || 1. sys_clock_announce() || - removes timeout from queue || - releases timeout_q_lock || || 2. k_work_reschedule_for_queue() || - calls unschedule_locked() || - z_abort_timeout() returns -EINVAL || (timeout no longer in queue!) || - unschedule_locked() returns TRUE || - schedule_for_queue_locked() adds NEW timeout || - K_WORK_DELAYED_BIT set again || || 3. work_timeout() runs (callback) || - sees K_WORK_DELAYED_BIT SET || - submits work to queue (DUPLICATE!) || || RESULT: Work item in queue TWICE + timeout still armed || Next timeout fires -> double-submit -> lost work items || |+------------------------------------------------------------------+
Here’s what happens step by step. CPU 0 processes the timer interrupt and calls sys_clock_announce(). The expired timeout is removed from the timeout queue, but before the callback can run, CPU 1 calls k_work_reschedule_for_queue() on the same work item. This function calls unschedule_locked(), which clears K_WORK_DELAYED_BIT and calls z_abort_timeout(). Because the timeout was already removed from the queue by CPU 0, z_abort_timeout() returns -EINVAL — but the pre-fix code ignores this return value and returns true anyway, indicating success.
The reschedule proceeds to call schedule_for_queue_locked(), which adds a new timeout to the queue and sets K_WORK_DELAYED_BIT again. Now CPU 0’s callback (work_timeout()) runs, sees the bit is set, and submits the work to the workqueue. The result: the work item is now in the workqueue twice, and the new timeout is still armed. When that timeout fires, the work gets submitted again, and items that were queued after the first submission can be lost entirely due to the way work_timeout() manipulates the workqueue’s linked list.
An even more dangerous variant occurs when the caller attempts to cancel and free a delayable work item:
+------------------------------------------------------------------+| USE-AFTER-FREE SCENARIO (SMP) |+------------------------------------------------------------------+| || CPU 0 (timeout path) CPU 1 (cleanup path) || ------------ --------------- || || 1. sys_clock_announce() || - removes timeout, releases lock || - work_timeout() about to run || || 2. k_work_cancel_delayable_sync() || - calls unschedule_locked() || - z_abort_timeout() returns -EINVAL || - cancel_sync_locked() sees work as IDLE || - returns SUCCESS (caller thinks it's safe to free) || || 3. work_timeout() runs || - reads freed dwork->timeout.dticks via || z_is_timeout_handler_canceled() || - if slot reused, K_WORK_DELAYED_BIT check passes || - writes to freed wp->flags (UAF write) || - submits against stale dwork->queue pointer || || RESULT: Kernel memory corruption / crash || |+------------------------------------------------------------------+
In this scenario, CPU 1 calls k_work_cancel_delayable_sync(), which is documented as the safe way to cancel a delayable work item before freeing it. The function calls unschedule_locked(), which again ignores the -EINVAL from z_abort_timeout(). Then cancel_sync_locked() checks if the work is running (via K_WORK_CANCELING_BIT) — but the work isn’t running yet, the timeout handler is just about to run. So cancel_sync_locked() returns success, and the caller proceeds to free the k_work_delayable object.
Moments later, CPU 0’s work_timeout() callback executes. It reads dwork->timeout.dticks through z_is_timeout_handler_canceled(). If the freed memory has been reallocated for another purpose, this reads garbage. The K_WORK_DELAYED_BIT check might pass by chance, causing the callback to write to the freed object’s flags field and submit work against a stale dwork->queue pointer. This is a classic use-after-free with potential for kernel memory corruption or crash.
unschedule_locked() Ignores z_abort_timeout() Return CodeThe pre-fix unschedule_locked() (v4.4.0 and earlier) is the direct source of the problem:
/* kernel/work.c - v4.4.0 */static inline bool unschedule_locked(struct k_work_delayable *dwork){bool ret = false;struct k_work *work = &dwork->work;if (flag_test_and_clear(&work->flags, K_WORK_DELAYED_BIT)) {z_abort_timeout(&dwork->timeout); /* Return value IGNORED */ret = true;}return ret;}
The function z_abort_timeout() returns:
0 — timeout was in queue, successfully removed-EINVAL — timeout NOT in queue (already expired, handler in-flight, or never scheduled)By ignoring -EINVAL, unschedule_locked() falsely reports success. Callers (k_work_reschedule_for_queue, k_work_cancel_delayable_sync, k_work_flush_delayable) proceed as if the old schedule is gone, while the callback is still about to run.
The deeper issue is that z_abort_timeout() in the timeout subsystem cannot distinguish between “timeout never existed” and “timeout was dequeued and handler is in-flight.” Both return -EINVAL. The timeout subsystem tracks an ANNOUNCING state for this exact case, but z_abort_timeout() doesn’t expose it — it just returns -EINVAL.
The fix merged in Zephyr 4.5.0 (commit 59cf34bf212e on main, backported to v4.4 branch as PR #112961) has two complementary parts that together close the race window completely.
unschedule_locked() Waits for In-Flight Handler/* kernel/work.c - v4.5.0+ */static inline bool unschedule_locked(struct k_work_delayable *dwork){bool ret = false;struct k_work *work = &dwork->work;if (flag_test_and_clear(&work->flags, K_WORK_DELAYED_BIT)) {/** If z_try_abort_timeout() returns -EAGAIN, the timeout handler* has been dequeued and is in-flight (or about to run).* We must wait for it to complete before returning.*/int err;do {err = z_try_abort_timeout(&dwork->timeout);if (err == -EAGAIN) {/* Release workqueue lock, let handler run, re-acquire */k_spin_unlock(&workqueue_lock, key);k_spin_lock(&workqueue_lock, &key);}} while (err == -EAGAIN);ret = (err == 0);}return ret;}
Key changes:
z_try_abort_timeout() instead of z_abort_timeout() — the former returns -EAGAIN when the handler is in-flight (state ANNOUNCING)-EAGAIN by releasing and re-acquiring the workqueue spinlock, giving the in-flight handler CPU time to completetrue when z_try_abort_timeout() returns 0 (successfully aborted)The new function z_try_abort_timeout() was added to the timeout subsystem specifically to expose the ANNOUNCING state. It returns:
0 — timeout was in queue, successfully removed-EAGAIN — timeout was dequeued, handler is in-flight (state ANNOUNCING)-EINVAL — timeout never existed or already completedBy spinning on -EAGAIN, unschedule_locked() effectively waits for the in-flight handler to finish. The spin releases the workqueue lock between attempts, allowing the handler (which needs the workqueue lock to submit the work) to make progress. This is a classic spinlock handoff pattern.
K_WORK_DELAYED_BIT Ownership in work_timeout()/* kernel/work.c - v4.5.0+ */static void work_timeout(struct timeout *to){struct k_work_delayable *dwork = CONTAINER_OF(to, struct k_work_delayable, timeout);struct k_work *work = &dwork->work;/* Atomic test-and-clear: only ONE path can claim the bit */if (atomic_test_and_clear_bit(&work->flags, K_WORK_DELAYED_BIT)) {k_work_submit_to_queue(dwork->queue, work);}/* If bit already cleared by unschedule_locked(), handler exits cleanly */}
Now work_timeout() uses atomic_test_and_clear_bit() instead of a non-atomic check. This ensures:
unschedule_locked() cleared the bit first (after waiting for handler), the timeout callback becomes a no-opunschedule_locked() sees the bit already clear and returns false (correctly indicating the work was already submitted)The atomic operation provides a clear ownership transfer: exactly one of the two paths (reschedule/cancel vs. timeout handler) will “win” the K_WORK_DELAYED_BIT. The loser sees the bit already cleared and takes the appropriate fallback action.
If you’re on an affected Zephyr version (2.6.0 – 4.4.x) and cannot upgrade immediately, you need application-level workarounds. The core problem is that k_work_cancel_delayable_sync() returns success even when the timeout handler is in-flight, creating a false sense of safety for freeing the object.
This pattern adds explicit reference counting to track in-flight handlers:
#include <zephyr/kernel.h>struct my_delayed_work {struct k_work_delayable dwork;struct k_sem free_sem; /* Protects free */atomic_t refcount; /* Tracks in-flight handlers */};void my_work_handler(struct k_work *work){struct my_delayed_work *dw = CONTAINER_OF(work, struct my_delayed_work, dwork.work);/* Do actual work here */if (atomic_dec(&dw->refcount) == 1) {k_sem_give(&dw->free_sem); /* Last reference, wake waiter */}}int my_work_init(struct my_delayed_work *dw){k_work_init_delayable(&dw->dwork, my_work_handler);k_sem_init(&dw->free_sem, 0, 1);atomic_set(&dw->refcount, 0);return 0;}int my_work_schedule(struct my_delayed_work *dw, k_timeout_t delay){atomic_inc(&dw->refcount);return k_work_schedule_for_queue(&system_work_q, &dw->dwork, delay);}void my_work_cancel_and_free(struct my_delayed_work *dw){/* Cancel returns true only if timeout was aborted */if (k_work_cancel_delayable_sync(&dw->dwork)) {if (atomic_dec(&dw->refcount) == 1) {k_sem_give(&dw->free_sem);}return;}/* Cancel failed (handler in-flight), wait for handler to finish */k_sem_take(&dw->free_sem, K_FOREVER);k_work_free(&dw->dwork.work);}
The key insight: every successful schedule increments the refcount, and the handler decrements it on completion. If k_work_cancel_delayable_sync() returns true (timeout aborted), we decrement the refcount ourselves. If it returns false (handler in-flight), we wait on the semaphore that the handler will signal when done. This guarantees the object isn’t freed until all in-flight handlers complete.
For simpler cases where you can tolerate a small delay before freeing:
#include <zephyr/kernel.h>/* Simple deferred free for delayable work items */struct deferred_free {struct k_work_delayable *dwork;struct k_work free_work;struct k_work_q *free_q;};static void deferred_free_handler(struct k_work *work){struct deferred_free *df = CONTAINER_OF(work, struct deferred_free, free_work);k_free(df->dwork);k_free(df);}void safe_cancel_and_deferred_free(struct k_work_delayable *dwork, struct k_work_q *q){struct deferred_free *df = k_malloc(sizeof(*df));df->dwork = dwork;k_work_init(&df->free_work, deferred_free_handler);df->free_q = q;/* Try sync cancel first */if (k_work_cancel_delayable_sync(dwork)) {k_work_submit_to_queue(q, &df->free_work);return;}/* Handler in-flight: schedule free after a grace period */k_work_schedule_for_queue(q, &df->free_work, K_MSEC(100));}
This pattern uses a grace period (100ms here, tune for your system) to let any in-flight handler complete before freeing. The trade-off is a small memory leak window if the system is under heavy load, but it’s much simpler than reference counting.
For systems with bounded workloads, pre-allocate a pool of delayable work items and never free them:
#include <zephyr/kernel.h>#define MAX_DELAYED_WORKS 16static struct k_work_delayable work_pool[MAX_DELAYED_WORKS];static atomic_t pool_in_use[MAX_DELAYED_WORKS];struct k_work_delayable *alloc_delayed_work(k_work_handler_t handler){for (int i = 0; i < MAX_DELAYED_WORKS; i++) {if (atomic_cas(&pool_in_use[i], 0, 1)) {k_work_init_delayable(&work_pool[i], handler);return &work_pool[i];}}return NULL; /* Pool exhausted */}void free_delayed_work(struct k_work_delayable *dwork){int idx = (dwork - work_pool) / sizeof(struct k_work_delayable);if (idx >= 0 && idx < MAX_DELAYED_WORKS) {/* Must ensure no in-flight handler! Use Pattern 1 or 2 */k_work_cancel_delayable_sync(dwork);atomic_set(&pool_in_use[idx], 0);}}
This eliminates the free-after-cancel problem entirely by never freeing the object. The pool size must be sized for peak concurrent delayed work items.
# In your Zephyr treegit log --oneline -1 -- kernel/work.c# Look for: "kernel/work: Fix race under with delayed work item cancellation"# Commit: d00f9b594b60 (or 59cf34bf212e on main)
#include <zephyr/kernel.h>#include <zephyr/sys/atomic.h>#include <zephyr/ztest.h>#define NUM_ITERATIONS 10000#define NUM_CPUS 2static struct k_work_delayable test_dwork;static atomic_t submit_count;static atomic_t handler_count;static void test_handler(struct k_work *work){atomic_inc(&handler_count);k_busy_wait(100); /* Simulate work, widen race window */}static void reschedule_thread(void *p1, void *p2, void *p3){for (int i = 0; i < NUM_ITERATIONS; i++) {k_work_reschedule_for_queue(&system_work_q, &test_dwork, K_MSEC(1));k_busy_wait(50);}}static void cancel_thread(void *p1, void *p2, void *p3){for (int i = 0; i < NUM_ITERATIONS; i++) {k_work_cancel_delayable_sync(&test_dwork);k_busy_wait(50);}}ZTEST(workqueue_race, test_reschedule_race){k_work_init_delayable(&test_dwork, test_handler);atomic_set(&submit_count, 0);atomic_set(&handler_count, 0);k_tid_t t1 = k_thread_create(&thread1_data, thread1_stack, STACK_SIZE,reschedule_thread, NULL, NULL, NULL,K_PRIO_PREEMPT(10), 0, K_NO_WAIT);k_tid_t t2 = k_thread_create(&thread2_data, thread2_stack, STACK_SIZE,cancel_thread, NULL, NULL, NULL,K_PRIO_PREEMPT(10), 0, K_NO_WAIT);k_thread_start(t1);k_thread_start(t2);k_thread_join(t1, K_FOREVER);k_thread_join(t2, K_FOREVER);/* On fixed kernel: handler_count <= NUM_ITERATIONS * 2 (bounded) *//* On buggy kernel: handler_count can exceed due to double-submit */printk("Handler executions: %d (expected <= %d)\n",atomic_get(&handler_count), NUM_ITERATIONS * 2);zassert_true(atomic_get(&handler_count) <= NUM_ITERATIONS * 2,"Race condition detected: excessive handler executions");}
Run with west twister -T tests/kernel/workqueue/race_test on SMP-enabled board (e.g., qemu_x86_64 with CONFIG_SMP=y).
z_try_abort_timeout Usagegrep -n "z_try_abort_timeout" kernel/work.c# Should show the spin loop in unschedule_locked()grep -n "atomic_test_and_clear_bit.*K_WORK_DELAYED_BIT" kernel/work.c# Should show in work_timeout()
If you’re on Zephyr 3.x or 4.3/4.4 LTS and need the fix:
--- a/kernel/work.c+++ b/kernel/work.c@@ -915,10 +915,18 @@ static inline bool unschedule_locked(struct k_work_delayable *dwork)bool ret = false;struct k_work *work = &dwork->work;- if (flag_test_and_clear(&work->flags, K_WORK_DELAYED_BIT)) {- z_abort_timeout(&dwork->timeout);- ret = true;+ if (flag_test_and_clear(&work->flags, K_WORK_DELAYED_BIT)) {+ int err;+ do {+ err = z_try_abort_timeout(&dwork->timeout);+ if (err == -EAGAIN) {+ k_spin_unlock(&workqueue_lock, key);+ k_spin_lock(&workqueue_lock, &key);+ }+ } while (err == -EAGAIN);++ ret = (err == 0);}return ret;@@ -980,7 +988,7 @@ static void work_timeout(struct timeout *to)struct k_work *work = &dwork->work;- if (atomic_test_and_clear_bit(&work->flags, K_WORK_DELAYED_BIT)) {+ if (atomic_test_and_clear_bit(&work->flags, K_WORK_DELAYED_BIT)) {k_work_submit_to_queue(dwork->queue, work);}}
Note: This backport requires z_try_abort_timeout() to exist (added in the same PR). For pre-v4.4 versions, the timeout subsystem lacks the ANNOUNCING state tracking, making a correct backport significantly more involved. Upgrade to v4.4+ or v3.7 LTS with vendor patches.
| Scenario | Pre-Fix Behavior | Post-Fix Behavior |
|---|---|---|
| High-frequency timer reschedule (BLE, 802.15.4) | Lost packets, duplicate processing | Deterministic, no duplicates |
| Connection churn driving subsystem timers | Kernel crash (UAF) after hours/days | Stable, handler waits for completion |
| Workqueue flush during shutdown | Use-after-free on delayed items | Clean drain, no memory corruption |
k_work_cancel_delayable_sync() + immediate k_free() | Heap corruption, random crashes | Safe: waits for in-flight handler |
The Zephyr k_work_delayable reschedule race condition (CVE-2026-12365) is a textbook SMP timing bug: the timeout subsystem releases its lock before invoking the callback, creating a window where z_abort_timeout() sees the timeout as “not in queue” (-EINVAL) while the handler is still in-flight. The pre-fix code ignored this return code, leading to duplicate submissions, lost work items, and use-after-free crashes.
Key takeaways:
k_work_cancel_delayable_sync() return value on affected versions — it can return success while the handler is about to runCONFIG_ASSERT — the double-linked timeout list corruption triggers an assert in debug buildsThe fix is elegant: unschedule_locked() now spins on z_try_abort_timeout() returning -EAGAIN, releasing the workqueue lock between attempts to let the in-flight handler complete. Combined with atomic K_WORK_DELAYED_BIT ownership in work_timeout(), the race window is closed completely.
Quick Links
Legal Stuff





