The device in Chapter 02 returns zero at the end of its message. This chapter implements an ongoing event stream. A blocking read waits when the FIFO is empty. An application that opens the device with O_NONBLOCK gets EAGAIN if it reads an empty FIFO.
1. Create the Makefile
obj-m := demo_events.o
2. Create demo_events.c
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/kfifo.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/uaccess.h>
#include <linux/wait.h>
#define FIFO_CAPACITY 256
#define MAX_WRITE_SIZE 128
static DEFINE_KFIFO(event_fifo, unsigned char, FIFO_CAPACITY);
static DEFINE_MUTEX(event_lock);
static DECLARE_WAIT_QUEUE_HEAD(event_wait);
/*
* Update readiness while holding event_lock. The wait condition and poll
* can then check readiness without taking the mutex.
*/
static bool data_ready;
static ssize_t event_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
unsigned int copied;
int ret;
if (!count)
return 0;
for (;;) {
ret = mutex_lock_interruptible(&event_lock);
if (ret)
return ret;
if (!kfifo_is_empty(&event_fifo))
break;
mutex_unlock(&event_lock);
if (file->f_flags & O_NONBLOCK)
return -EAGAIN;
ret = wait_event_interruptible(event_wait, READ_ONCE(data_ready));
if (ret)
return ret;
}
ret = kfifo_to_user(&event_fifo, buf,
min_t(size_t, count, FIFO_CAPACITY), &copied);
WRITE_ONCE(data_ready, !kfifo_is_empty(&event_fifo));
mutex_unlock(&event_lock);
if (copied)
return copied;
return ret;
}
static ssize_t event_write(struct file *file, const char __user *buf,
size_t count, loff_t *pos)
{
unsigned char incoming[MAX_WRITE_SIZE];
unsigned int queued;
if (!count)
return 0;
if (count > sizeof(incoming))
return -EMSGSIZE;
if (copy_from_user(incoming, buf, count))
return -EFAULT;
mutex_lock(&event_lock);
if (kfifo_avail(&event_fifo) < count) {
mutex_unlock(&event_lock);
return -EAGAIN;
}
queued = kfifo_in(&event_fifo, incoming, count);
WRITE_ONCE(data_ready, true);
mutex_unlock(&event_lock);
wake_up_interruptible(&event_wait);
return queued;
}
static __poll_t event_poll(struct file *file, poll_table *wait)
{
poll_wait(file, &event_wait, wait);
if (READ_ONCE(data_ready))
return EPOLLIN | EPOLLRDNORM;
return 0;
}
static const struct file_operations event_fops = {
.owner = THIS_MODULE,
.open = nonseekable_open,
.read = event_read,
.write = event_write,
.poll = event_poll,
};
static struct miscdevice event_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "demo-events",
.fops = &event_fops,
};
static int __init event_init(void)
{
return misc_register(&event_device);
}
static void __exit event_exit(void)
{
misc_deregister(&event_device);
}
module_init(event_init);
module_exit(event_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Blocking read and poll lab");
3. Verify blocking reads using two terminals
Build and load the module in the QEMU guest.
make -C "/lib/modules/$(uname -r)/build" M="$PWD" modules
sudo insmod ./demo_events.ko
ls -l /dev/demo-events
In Terminal A, use dd to request one block. The command waits while the FIFO is empty.
sudo dd if=/dev/demo-events bs=128 count=1 status=none
In Terminal B, write a simulated button event.
printf 'BUTTON_PRESS\n' | sudo tee /dev/demo-events >/dev/null
Terminal A should print BUTTON_PRESS and exit. Run the same command again to check that it waits for another event. Send another event from Terminal B to let it finish before the next test.
4. Verify O_NONBLOCK and poll()
Save this program as poll_events.py. Start with an empty queue.
import os
import select
fd = os.open("/dev/demo-events", os.O_RDONLY | os.O_NONBLOCK)
try:
try:
os.read(fd, 128)
except BlockingIOError:
print("Queue is empty. Immediate read returned EAGAIN.", flush=True)
else:
raise SystemExit("Queue must be empty when the test starts.")
poller = select.poll()
poller.register(fd, select.POLLIN)
print("Waiting for an event...", flush=True)
for _, flags in poller.poll():
if flags & select.POLLIN:
data = os.read(fd, 128)
print(data.decode("utf-8", errors="replace"), end="")
finally:
os.close(fd)
In Terminal A, run the program.
sudo python3 poll_events.py
Once you see Waiting for an event..., write from Terminal B.
printf 'BUTTON_RELEASE\n' | sudo tee /dev/demo-events >/dev/null
Terminal A should report the initial EAGAIN, wait until poll() reports readability, and print BUTTON_RELEASE. After both readers exit, unload the module.
sudo rmmod demo_events
5. Trace the wake-up
| Code | Purpose |
|---|---|
kfifo |
Stores unread bytes |
wait_event_interruptible() |
Lets the reader sleep until the condition becomes true or a signal arrives |
wake_up_interruptible() |
Wakes waiting readers after the writer enqueues data |
poll_wait() |
Registers the wait queue before the readiness check |
event_lock |
Serializes FIFO access across readers and writers |
A woken reader reacquires the mutex and checks the FIFO again. If another reader already took the data, it waits again. The writer enqueues data, updates readiness, and then wakes readers.
The FIFO is a byte stream. Several reads can consume one write, so the examples use a newline as a delimiter. If there is insufficient room for a write, the entire request returns EAGAIN.
Next lab
Chapter 04 replaces the terminal writer with a threaded GPIO IRQ. The threaded handler can use the same mutex. A hard IRQ handler requires synchronization suitable for atomic context or must defer work that can sleep.