Without further ado, let's look at the code to write a simple skeleton character misc device driver! (Well, snippets of the actual code; as always, I strongly advise you to git clone the book's GitHub repository, view it in detail, and try out the code yourself.)
Let's go through it step by step: in the init code of our first device driver (using the LKM framework), we must first register our driver with the appropriate Linux kernel's framework; in this case, with the misc framework. This is done via the misc_register() API. It takes one parameter, a pointer to a data structure of type miscdevice, which describes the miscellaneous device we are setting up:
// ch1/miscdrv/miscdrv.c
#define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__
[...]
#include <linux/miscdevice.h>
#include <linux/fs.h> /* the fops, file data structures */
[...]
static struct miscdevice llkd_miscdev = {
.minor = MISC_DYNAMIC_MINOR, /* kernel dynamically assigns a free minor# */
.name = "llkd_miscdrv", /* when misc_register() is invoked, the kernel
* will auto-create a device file as /dev/llkd_miscdrv ;
* also populated within /sys/class/misc/ and /sys/devices/virtual/misc/ */
.mode = 0666, /* ... dev node perms set as specified here */
.fops = &llkd_misc_fops, /* connect to this driver's 'functionality' */
};
static int __init miscdrv_init(void)
{
int ret;
struct device *dev;
ret = misc_register(&llkd_miscdev);
if (ret != 0) {
pr_notice("misc device registration failed, aborting\n");
return ret;
}
[ ... ]
In the miscdevice structure instance, we do the following:
- We set the minor field to MISC_DYNAMIC_MINOR. This has the effect of requesting the kernel to dynamically assign us an available minor number (once registration is successful, this minor field gets populated with the actual minor number assigned).
- We initialize the name field. On successful registration, this has the kernel framework automatically create a device node (of the form /dev/<name>) on our behalf! As expected, the type will be character, the major number will be 10, and the minor number will be a dynamically assigned value. This is (part of) the advantage of using a kernel framework; else, we might have had to devise a way to create the device node ourselves; by the way, the mknod(1) utility can create a device file when invoked with root privilege (or you have the CAP_MKNOD capability); it works by invoking the mknod(2) system call!
- The permissions of the device node will be set to whatever you initialize the mode field to (here, we've deliberately kept it permissive and readable-writeable by all via the 0666 octal value).
- We shall postpone the discussion of the file operations (fops) structure member to the section following this one.
All misc drivers are of the character type and use the same major number (10), but of course require unique minor numbers.