Skip to the content ForoHackers
Log inJoin

How does read() on /dev/hello actually reach my driver function?

Device driversKernelsLinux
#1188 · k3rn3l_k1tt3n · · Report

I am finally writing my first kernel module, a tiny misc device that returns a string. It works, and I want to understand why it works.

#include <linux/module.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/uaccess.h>

static ssize_t hello_read(struct file *f, char __user *buf,
                          size_t len, loff_t *off)
{
    static const char msg[] = "hello\n";
    return simple_read_from_buffer(buf, len, off, msg, sizeof(msg) - 1);
}

static const struct file_operations hello_fops = {
    .owner = THIS_MODULE,
    .read  = hello_read,
};

static struct miscdevice hello_dev = {
    .minor = MISC_DYNAMIC_MINOR,
    .name  = "hello",
    .fops  = &hello_fops,
};

module_misc_device(hello_dev);
MODULE_LICENSE("GPL");

cat /dev/hello prints hello. But where does the kernel decide "this read() goes to hello_read"? And what is that off pointer for? I tried returning len every time and cat printed forever.

#2056 · hexdump_hermit · · Report

Chain: open() finds the inode of /dev/hello, the misc layer looks up your miscdevice by minor number and puts your file_operations into file->f_op. After that, read() goes ksys_read -> vfs_read -> file->f_op->read. The pointer is chosen once, at open.

#2057 · k3rn3l_k1tt3n · · Report

So f_op is per open file, not per device node. That explains why two cats do not step on each other's position. Thanks. And off?

#2058 · null_terminated_hopes · · Report

off is the file position for this open file. read() returning 0 means end of file; anything else means "call me again". If you always return len and never move the offset, cat reads forever and your terminal becomes a lava lamp. simple_read_from_buffer copies from your buffer starting at *off, advances *off, and returns 0 once you are past the end. Which is the entire contract.

#2059 · yak_shaving_daily · · Report

To watch it happen, run strace cat /dev/hello and look at the last lines: a read returning 6, then another returning 0. And if you want the kernel's side, trace-cmd or ftrace with the function graph tracer on vfs_read will show your hello_read nested inside. Fair warning: I came here to write a driver and ended up learning ftrace for three days.

#2060 · k3rn3l_k1tt3n · · Report

Got it. strace shows exactly read(3, "hello\n", 131072) = 6 and then = 0. Seeing the 0 made the whole thing click. Next: implementing write, and being careful with copy_from_user this time.

Log in or join to reply.