Section 6.36

Zephyr workqueue

Definition

A Zephyr workqueue is a kernel object that runs deferred work on a dedicated thread. Code submits a work item, a small structure that names a handler function, and the workqueue’s thread later calls that handler. Items wait in first-in, first-out §14.14 (FIFO) order, so the thread runs their handlers one at a time. Any code may submit, including an interrupt handler §6.12. Zephyr §6.33 provides one system workqueue that all code shares, and applications can start their own. A delayable work item enters the queue only after a delay.

The idea

An interrupt handler learns that a sensor has new data. Reading and filtering the data takes 2 ms, far too long for an interrupt handler, which delays every thread while it runs and must never wait. A thread per job would cost a separate stack, often a kilobyte or more, for each job. A workqueue gives many jobs one thread: the interrupt handler submits a work item in a few microseconds and returns, and the workqueue’s thread runs the 2 ms job later, where waiting is allowed.

The core idea is a to-do list served by one worker, like a counter with one clerk and numbered tickets. Deferral does not make the work smaller or faster; it moves the work to a place where it is allowed to run. Because one worker serves the whole list, every item waits for the items ahead of it, and one slow item delays all the items behind it. A shared workqueue therefore moves contention to the queue rather than removing it. The ticket picture stops at repeats: a customer who takes a second ticket gets a second turn, but a work item submitted again while it is still queued keeps its single place and is handled once.

How it works

The parts:

An item goes through these steps.

  1. Submit. k_work_submit() puts the item at the back of the queue unless it is already queued. It returns 1 if the item was idle and is now queued. It returns 0 if the item was already queued; nothing changes, and the queue still holds one entry for the item. It returns 2 if the item was running and has now been queued again, on the workqueue that is running it. A negative value means the submission was refused, for example because the item is being canceled.

  2. Wait. The item waits until every item ahead of it has been handled and the scheduler gives the workqueue thread the processor.

  3. Run. The thread takes the item off the queue, marks it as running, and calls the handler. From this moment a new submission queues the item again.

  4. Return. When the handler returns, the thread takes the next item, or sleeps if the queue is empty.

Three rules follow. First, a handler may call any kernel function that a thread may call, including ones that wait, but while it waits, its workqueue runs nothing else. Second, the kernel keeps using the item’s memory while the item is scheduled, queued or running, so that memory must stay valid and must not be reinitialized until the item is idle; any data that the handler reads must likewise stay valid until the handler has read it. Third, k_work_busy_get() reports a state that may already have changed by the time the caller looks at it. To wait for a safe point, use k_work_cancel_sync(), which cancels the item and waits until it is idle, or k_work_flush(), which waits until the submission already made has been handled. A delayable item needs its own versions: k_work_cancel_delayable_sync(), which also stops the item’s timer, and k_work_flush_delayable(), which submits the item at once if its timer is still running and then waits as k_work_flush() does. The plain versions must not be used on a delayable item.

Worked example

Waiting behind a slow item. A delayable item D is scheduled at time 0 ms with a delay of 10 ms, and its handler needs 1 ms. At time 2 ms another handler on the same workqueue starts a job that keeps the thread busy until 100 ms.

The time from scheduling to completion is 101 ms, not the 10+1=1110 + 1 = 11 ms that the delay and the handler time suggest. The 10 ms delay is a lower bound on when the handler starts, never an upper bound.

Merged submissions. Button interrupts at 20, 40 and 60 ms each call k_work_submit() on the same item B while the long job is still running. The first call returns 1 and queues B behind D; the second and third return 0 and change nothing. B’s handler runs once, from 101 ms, although three presses occurred. A handler that must count presses needs its own counter: each interrupt adds 1 to the counter with an atomic operation §9.8, an update that cannot be interrupted halfway, and the handler atomically reads the counter and resets it to 0, here reading 3.

A separate workqueue. Moving D to its own workqueue removes the wait behind the long job only if the scheduler lets D’s thread run first. If both workqueue threads are cooperative on one processor and the long job computes without waiting, D’s thread still starts at 100 ms. If D’s thread has the higher priority and the long job’s thread is preemptive, D’s handler starts at 10 ms and finishes at 11 ms, and the long job finishes 1 ms later than before.

Stated precisely

Let tst_s be the time at which an item is submitted; for a delayable item, tst_s is the moment its timer expires. The handler starts at tstart=ts+Wq+Wc,t_{\text{start}} = t_s + W_q + W_c, where WqW_q, the queue wait, is the time from tst_s until every handler ahead of the item has returned, and WcW_c is the further time until the workqueue thread actually gets the processor, spent in interrupt handlers and in threads that run ahead of it. In the first trace, ts=10t_s = 10, Wq=100−10=90W_q = 100 - 10 = 90 and Wc=0W_c = 0, so tstart=10+90+0=100t_{\text{start}} = 10 + 90 + 0 = 100 ms. A bound on tstartt_{\text{start}} therefore needs a bound on the run time of every handler that can be queued ahead of the item, not only on the delay.

Submission contract: a work item has at most one entry in a queue at any moment, and each entry produces exactly one call of the handler unless the item is canceled first. The number of handler calls is therefore at most the number of successful submissions, and it can be smaller: any number of submissions while the item is queued give one call. The handlers on one workqueue never run at the same time as each other, and because a running item that is submitted again is queued on the workqueue that runs it, one item’s handler never runs on two threads at once.

Limits and common mistakes

Offloading moves work; it does not remove it. The work still uses the same processor, the same locks and the same devices.

On a shared workqueue, one slow or waiting handler delays every later item of every user. This is head-of-line blocking §9.19: a slow item at the front holds up everything behind it. A handler on the system workqueue must not wait long, and must never wait without a time limit.

A handler that waits for another item on the same workqueue never finishes, because the other item cannot start until the waiting handler returns: a callback dependency deadlock §19.4.9.

Submissions merge, so a work item is not a message queue. When every event must be handled, keep the events in a counter or in a bounded queue §9.31 that the handler drains.

A timer expiry or a successful submission is not completion; the handler may not even have started. And freeing or reusing a work item, or the data its handler reads, while the item is scheduled, queued or running is a use-after-free §4.6. Freeing or reusing safely takes two steps. First stop all code that could submit or schedule the item again, because a cancellation §9.29 does not prevent a later submission. Then cancel the item with k_work_cancel_sync(), or with k_work_cancel_delayable_sync() for a delayable item. Both calls can wait, so make them from a thread, never from an interrupt handler or from the item’s own handler.

Names and return values of the work functions have changed between Zephyr releases. Check the documentation of the release in use.

Questions answered

Does offloading work remove contention or move it to a shared queue?

Offloading work to a Zephyr workqueue moves the contention to the queue; it does not remove it. The caller, for example an interrupt handler, submits a work item and returns at once, which is the real benefit. But the work still runs on the workqueue’s single thread, after every item ahead of it and before every item behind it. On the shared system workqueue, a handler that runs or waits for a long time delays the work of every other user, so the delay that the caller avoided reappears as queue wait. The work also still competes for the same processor, locks and devices.

A dedicated workqueue removes the wait behind other users’ items, at the cost of a thread and its stack. It still shares the processor with every other thread, and it helps only if the scheduler lets it run, for example because it outranks a preemptive thread §6.37 that does the slow work. To claim that offloading reduced a delay, bound the run time of every handler that can be queued ahead of the item.

Related entries: Head-of-line blocking (§9.19), Cancellation (§9.29), Response time versus execution time (§9.32), Callback dependency deadlock across a workqueue (§19.4.9), Zephyr thread (§6.35), Cooperative and preemptive scheduling (§6.37), Bounded queue (§9.31), Atomic operation (§9.8). Further reading: [15].