</>EmbeddedInterview

How does user space wait for events from a driver (poll/select)?

MediumLinux Kernel & Device Drivers

Short answer: Implement .poll in file_operations. It calls poll_wait() to add the caller to the driver's wait queue (this does not sleep) and returns a mask of the events that are ready now (EPOLLIN | EPOLLRDNORM for readable, EPOLLOUT | EPOLLWRNORM for writable, EPOLLERR/EPOLLHUP). When data arrives, the driver calls wake_up_interruptible(&wq), which makes poll, select and epoll callers re-check.

static __poll_t mydev_poll(struct file *f, poll_table *wait)
{
    struct mydev *d = f->private_data;
    __poll_t mask = 0;

    poll_wait(f, &d->wq, wait);                 /* registers; the VFS does the sleeping */
    if (READ_ONCE(d->data_ready))
        mask |= EPOLLIN | EPOLLRDNORM;
    if (fifo_has_space(d))
        mask |= EPOLLOUT | EPOLLWRNORM;
    if (d->disconnected)
        mask |= EPOLLHUP;
    return mask;
}

User space

struct pollfd p = { .fd = fd, .events = POLLIN };
int r = poll(&p, 1, 1000);                      /* 1 s timeout */
if (r > 0 && (p.revents & POLLIN)) read(fd, &val, sizeof val);

How it works internally: the VFS calls your .poll; if no requested event is ready, it sleeps; your wake_up wakes it, and it calls .poll again to get the new mask. That is why .poll must be cheap and must not block.

Other notification mechanisms

  • fasync / SIGIO (kill_fasync): asynchronous signal to user space; rarely used now.
  • eventfd: a simple counter file descriptor, used by KVM/VFIO/vhost to signal interrupts.
  • sysfs sysfs_notify() wakes user programs polling a sysfs attribute (used by GPIO and IIO events).
  • uevents (kobject_uevent) for device state changes handled by udev.