Skip to content
systemcoding.dev
Kernels

Defer Work to Process Context With Workqueues

Move sleeping work out of an interrupt handler with INIT_WORK, schedule_work and a worker function on Linux 6.12, including delayed work and safe teardown.

6 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Linux, C and FreeBSD logos.

An interrupt handler cannot sleep, but the work that follows an interrupt often must: read a sensor over I2C, take a mutex, allocate memory with GFP_KERNEL. The workqueue API is the standard way to hand that work to a kernel thread. You declare a struct work_struct, give it a function, and queue it; some time later, a worker thread runs the function in process context where sleeping is legal. This post builds that pattern in Linux 6.12 from the smallest example, adds delayed work and a retry loop, and shows the teardown that prevents the most common crash.

The three pieces

A work item has a function, a data structure, and a queue.

c
struct work_struct {
	atomic_long_t data;
	struct list_head entry;
	work_func_t func;
};

You rarely touch the fields. You embed a work_struct in your own device structure, initialize it with INIT_WORK() to point at your function, and queue it with schedule_work() (to the system workqueue) or queue_work() (to a queue you chose). The kernel's worker pool picks it up. The function receives a pointer to the work_struct, and container_of() gets you back to your structure:

sensor.cc
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/i2c.h>
#include <linux/mutex.h>

struct sensor {
	struct i2c_client *client;
	struct work_struct work;
	struct mutex lock;
	int last_temp;
};

static void sensor_work(struct work_struct *w)
{
	struct sensor *s = container_of(w, struct sensor, work);
	int raw;

	mutex_lock(&s->lock);			/* may sleep: fine here */
	raw = i2c_smbus_read_word_swapped(s->client, 0x00);
	if (raw >= 0)
		s->last_temp = raw >> 4;
	mutex_unlock(&s->lock);
}

static irqreturn_t sensor_isr(int irq, void *dev_id)
{
	struct sensor *s = dev_id;

	schedule_work(&s->work);
	return IRQ_HANDLED;
}

static int sensor_setup(struct sensor *s)
{
	mutex_init(&s->lock);
	INIT_WORK(&s->work, sensor_work);
	return 0;
}

The interrupt handler does nothing but queue the work. The I2C read, which waits for a bus transfer and therefore sleeps, happens in sensor_work(). i2c_smbus_read_word_swapped() is an existing SMBus helper declared in linux/i2c.h; it returns the 16-bit value or a negative errno.

What schedule_work returns, and what it does not guarantee

schedule_work() returns true if the item was queued and false if it was already pending. This is a guarantee in disguise: while an item is queued but not yet running, calling schedule_work() again does nothing. If the interrupt fires three times before the worker gets to run, the function executes once. That is correct when the work reads the current device state, which is the case above, and wrong when each interrupt carries unique data.

For per-event data, pass it through a queue the work function drains:

c
struct event { struct list_head node; u32 status; };

/* in the handler: */
ev = kmalloc(sizeof(*ev), GFP_ATOMIC);
if (ev) {
	ev->status = status;
	spin_lock(&s->lock);
	list_add_tail(&ev->node, &s->events);
	spin_unlock(&s->lock);
	schedule_work(&s->work);
}

The work function then pops every entry in a loop, so a coalesced run still sees all events. The kmalloc uses GFP_ATOMIC because the handler cannot sleep, and the check for failure matters, since that allocation fails sooner under pressure than a sleeping one.

Delayed work

When you need work to run after a delay, use struct delayed_work, which wraps a work item with a timer:

c
struct sensor {
	/* ... */
	struct delayed_work poll;
};

static void sensor_poll(struct work_struct *w)
{
	struct sensor *s = container_of(to_delayed_work(w), struct sensor, poll);

	/* read the device, then run again in 500 ms */
	schedule_delayed_work(&s->poll, msecs_to_jiffies(500));
}

/* setup */
INIT_DELAYED_WORK(&s->poll, sensor_poll);
schedule_delayed_work(&s->poll, msecs_to_jiffies(500));

to_delayed_work() converts the work_struct pointer to the enclosing delayed_work, and container_of() takes you to your own structure. The function re-arms itself, which gives you a periodic poll that, unlike a timer callback, may sleep. Because the delay is in jiffies, resolution depends on CONFIG_HZ; use msecs_to_jiffies() instead of arithmetic on HZ. Delayed work is the right tool for "retry in 100 ms" after a transient bus error.

Which queue does schedule_work use?

schedule_work() queues to system_wq, the per-CPU bound queue shared by the entire kernel. Items queued from CPU 2 run on CPU 2's worker pool unless that pool is unavailable. Other predefined queues exist:

QueueUse
system_wqDefault, short non-blocking-heavy work
system_highpri_wqHigher-priority workers
system_long_wqWork that may run for a long time
system_unbound_wqNot bound to a CPU; the scheduler places it
system_freezable_wqFrozen during suspend
system_bh_wqRuns in softirq context, no sleeping (Linux 6.9 and later)

Sharing system_wq means your work competes with every other user of it. If your work item sleeps for a long time, for example waiting on a slow bus transaction, it ties up a worker, and the pool spawns more to keep other items moving, but a long item can still delay others in a heavily loaded system. For that case, a dedicated queue from alloc_workqueue() is the right tool; the next post in this series shows it.

Tearing down without a crash

The most common workqueue bug is a work item that runs after its memory is gone. Consider module removal: the handler queued work, the structure is freed, and the worker then runs against freed memory, which on a KASAN kernel shows as a slab-use-after-free in the work function.

The tools, in order of use:

c
cancel_work_sync(&s->work);	/* cancel if pending, wait if running */
cancel_delayed_work_sync(&s->poll);
flush_work(&s->work);		/* wait for completion, do not cancel */

cancel_work_sync() guarantees that after it returns, the work is neither queued nor running. But it only cancels what was queued before the call, so you must first stop the sources that can queue more: free the interrupt, stop the timer, mark the device as going away. The right order in remove():

c
static void sensor_remove(struct platform_device *pdev)
{
	struct sensor *s = platform_get_drvdata(pdev);

	disable_irq(s->irq);			/* no new queueing from the handler */
	cancel_work_sync(&s->work);
	cancel_delayed_work_sync(&s->poll);
	/* safe to free s now */
}

A self-re-arming delayed work needs one more precaution. If the work function can re-queue itself, cancel_delayed_work_sync() handles that case: it cancels the timer, waits for a running instance and guards against the re-queue race in its implementation. Do not roll your own flag unless you have a reason.

Observing work

Workers are kernel threads named kworker/<cpu>:<id>, with H appended for high-priority pools and u<n> for unbound pools. ps shows them. For tracing, the workqueue:workqueue_queue_work, workqueue_execute_start and workqueue_execute_end events record each item, and trace-cmd or perf trace shows how long your function takes:

Shell
sudo trace-cmd record -e workqueue:workqueue_execute_start -e workqueue:workqueue_execute_end sleep 1
trace-cmd report | grep sensor_work
Text
kworker/2:1-142  [002]  8123.440120: workqueue_execute_start: work struct 0xffff88810a7c5240: function sensor_work
kworker/2:1-142  [002]  8123.440612: workqueue_execute_end:   work struct 0xffff88810a7c5240: function sensor_work

The timestamps differ by 492 microseconds in the illustration; on your machine they reflect your bus. /sys/kernel/debug/workqueue (kernel 6.x with debugfs) is not a stable interface, but the workqueue section in /sys/devices/virtual/workqueue/ shows attributes of queues created with WQ_SYSFS.

When a plain workqueue is the wrong choice

For a work item that must run immediately after the interrupt with the lowest possible latency, and does not sleep, a BH workqueue (system_bh_wq) avoids the thread scheduling delay. For work that is entirely tied to one interrupt, request_threaded_irq() creates a dedicated thread and handles the masking for you, and for periodic non-sleeping work, a timer is cheaper. For very heavy jobs, a dedicated thread with kthread_run() gives you control of priority and CPU affinity, at the price of managing its lifecycle yourself.

Also inHardware
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.