Topics / Linux Kernel & Device Drivers / Q23
What are wait queues and completions?
Short answer: A wait queue lets a task sleep until a condition becomes true: the sleeper calls wait_event_interruptible(wq, condition), and the code that changes the condition (often an interrupt handler) calls wake_up_interruptible(&wq); the condition is re-checked after every wake-up, so spurious wake-ups are harmless. A completion is a simpler wrapper for the common case "wait until this one thing has finished" (wait_for_completion_timeout() and complete()), e.g. waiting for a DMA transfer or a firmware response.
Blocking read using a wait queue
static ssize_t mydev_read(struct file *f, char __user *ubuf, size_t n, loff_t *pos)
{
struct mydev *d = f->private_data;
u32 val;
if (f->f_flags & O_NONBLOCK) {
if (!READ_ONCE(d->data_ready)) return -EAGAIN;
} else if (wait_event_interruptible(d->wq, READ_ONCE(d->data_ready))) {
return -ERESTARTSYS; /* interrupted by a signal */
}
spin_lock_irq(&d->lock);
val = d->sample;
d->data_ready = false;
spin_unlock_irq(&d->lock);
if (n < sizeof(val)) return -EINVAL;
return copy_to_user(ubuf, &val, sizeof(val)) ? -EFAULT : sizeof(val);
}
/* in the IRQ handler */
spin_lock(&d->lock);
d->sample = readl(d->base + DATA);
d->data_ready = true;
spin_unlock(&d->lock);
wake_up_interruptible(&d->wq);
Completion for a DMA transfer
reinit_completion(&d->dma_done);
start_dma(d);
if (!wait_for_completion_timeout(&d->dma_done, msecs_to_jiffies(100))) {
dmaengine_terminate_sync(d->chan);
return -ETIMEDOUT;
}
/* DMA callback: complete(&d->dma_done); */
Points
- Always use a timeout for hardware events, and handle signals (
-ERESTARTSYS). wait_event_killableonly lets fatal signals interrupt the wait.- Never wait in atomic context.
- Wait queues also back
poll()(next question).