🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Automatic Device Node Creation
Learn automatic device node creation in the Linux kernel: how class_create(), device_create(), sysfs and udev make /dev/mydevice appear and vanish by themselves. A hands-on lecture from our free linux device drivers course.
Programs explained line by line
Kernel APIs in detail
Original ep_ demo driver
What You Will Learn
Until now a character device needed a hand-made node: you read the major number from /proc/devices and ran mknod. In this lecture you remove that manual step completely. Your driver describes the device to the kernel, the kernel announces it, and the node in /dev is created and removed automatically.
- Why the old static
/devdirectory was replaced by udev and devtmpfs. - The Linux device model objects involved: sysfs, class, device and
dev_t. - Every API used:
class_create,class_destroy,device_create,device_destroy,alloc_chrdev_region,MKDEV/MAJOR/MINOR,printk,module_init/module_exit. - How to read
udevadm monitoroutput and tie each event to a line of driver code. - Three progressive programs (
1_char.c,2_char.c,3_char.c) explained line by line, with their real output. - The bugs hiding in the rough drafts and the production-style fix in the original
ep_autonodedriver.
Prerequisites
- You can build and load a hello-world kernel module (
insmod,rmmod,dmesg). - You know what a character device, a major number and a minor number are.
- Kernel headers for your running kernel:
sudo apt install linux-headers-$(uname -r). - A Linux machine or VM where you have
sudo. Use a test VM; you are loading code into the kernel. - Two terminals side by side: one for
udevadm monitor, one for loading modules.
This lecture belongs to our free linux device drivers course, which is part of the wider free linux kernel development course on EmbeddedPathashala.
Why Static /dev Failed
Traditionally every device node lived in the /dev directory as an ordinary special file. A node existed for every possible device, whether or not the hardware was present in the machine. The directory therefore took a lot of space and listing it told you nothing about which devices actually existed.
A device node is a file whose inode says “character (or block) device with major M and minor m”. It holds no data. When an application calls open(), the virtual file system uses the (M, m) pair to find the driver that registered those numbers. So a node is only a named pointer to a driver.
That model breaks down in modern systems for three reasons:
- Hot-pluggable hardware. USB serial adapters, Bluetooth dongles, SD cards and PCIe devices come and go at run time. A fixed list of nodes can never be correct.
- Dynamic major numbers. When a driver uses
alloc_chrdev_region()the kernel picks a free major, and it can differ between boots. A node you made yesterday withmknodmay point to a different driver today. - Hard-coded policy. Names and permissions were fixed by hand instead of being rules an administrator can change.
How udev Changed Device Nodes
udev introduces a new way of creating device nodes: it uses the information published in sysfs and creates nodes only for devices that really exist. It can be tuned with configuration files (rules) that control the device file names, their permissions, their types and more.
The consequence for you as a driver author is simple: the driver only has to populate the correct sysfs entries using the Linux device model, declared in <linux/device.h>. Everything else is handled by udev.
| Aspect | Old static /dev | udev + sysfs (modern) |
|---|---|---|
| Who creates the node | Administrator or install script (mknod) | Automatic, triggered by a kernel event (uevent) |
| Which nodes exist | All possible devices | Only devices that are actually registered |
| Source of information | A fixed list | sysfs entries under /sys |
| Names, permissions, owner | Hard-coded | Controlled by udev rules |
| Removal | Manual | Automatic when the device is removed (or on rmmod) |
udev and devtmpfs: who really makes the file?
On a modern distribution /dev is a devtmpfs mount (check with mount | grep devtmpfs). With devtmpfs the kernel itself creates a basic node the moment device_create() registers the device. The udev daemon (systemd-udevd) then receives the uevent, applies rules, and adjusts name, owner, group, mode and symlinks. Either way you never call mknod.
This is also the reason your nodes appear as crw------- root root: devtmpfs creates nodes with mode 0600 owned by root, and no rule on your system changes that. We fix this in the permissions section.
Device Model Basics: sysfs, Class, Device
sysfs is a virtual filesystem mounted on /sys. It exports the kernel’s object tree: every directory is a kernel object (a kobject) and every file is an attribute you can read or write. Devices, drivers, buses, classes and loaded modules all appear there.
A class groups devices by function rather than by the bus they sit on. A keyboard on USB and a keyboard on PS/2 both belong to the input class. Classes are visible under /sys/class/. The following listing is from the author’s own laptop and shows how many classes already exist before our module adds one:
$ ls /sys/class
accel drm_dp_aux_dev mdio_bus ppdev spi_master
ata_device extcon mei ppp spi_slave
bluetooth hwmon net rfkill thermal
block i2c-dev nvme rtc tty
input leds pci_bus sound watchdog
... (about 70 entries; the exact list depends on your hardware)
The name you pass to class_create() becomes a new directory in this list. A device registered with that class gets its own directory with a few standard files. The diagram shows what our programs build:
sysfs objects created by class_create() and device_create()
The real device directory is under /sys/devices/.... The entry under /sys/class/myclass/ is just a symlink so tools can list “all devices of this function” in one place. The device appears below /sys/devices/virtual/ because we pass NULL as the parent: a device with no parent is not attached to a real bus such as PCI or USB. If you pass a parent struct device *, the new device appears as its child instead.
The file named dev is the key. It contains major:minor, exactly the numbers the node must carry. After running Program 2 you can confirm it:
$ cat /sys/class/myclass/mydevice1/dev
200:1
$ cat /sys/class/myclass/mydevice1/uevent
MAJOR=200
MINOR=1
DEVNAME=mydevice1
The Automatic Device Node Creation Flow
Putting the pieces together, automatic device node creation is a pipeline with seven steps. Follow it once and every output line in this lecture will make sense:
From insmod to /dev/mydevice
Who does what
| Actor | Responsibility | Example in our programs |
|---|---|---|
| Your driver | Reserve the device number, create the class, register each device | alloc_chrdev_region, class_create, device_create |
| Kernel driver core | Build sysfs directories and attributes, link class and device, send uevents, create the devtmpfs node | /sys/class/myclass, the dev file |
| udev daemon | Apply rules: naming, permissions, owner, symlinks, run programs | Final mode and owner of /dev/mydevice1 |
| Administrator | Writes rules when the defaults are not right | /etc/udev/rules.d/99-mydevice.rules |
Use this table when debugging. If /sys/class/myclass/mydevice exists but /dev/mydevice does not, your driver did its job and the problem is on the udev or devtmpfs side. If neither exists, the problem is inside your driver, usually a class_create or device_create call that failed unnoticed.
Device Numbers: dev_t, Major and Minor
Every device is identified by a dev_t, a 32-bit value split into a major number (which driver handles the device) and a minor number (which instance the driver should address). Today 12 bits hold the major and 20 bits hold the minor.
Layout of dev_t
| Macro | Header | Purpose | Example |
|---|---|---|---|
MKDEV(ma, mi) | <linux/kdev_t.h> | Build a dev_t from major and minor | MKDEV(200,1) |
MAJOR(dev) | <linux/kdev_t.h> | Extract the major number | MAJOR(devicenumber) |
MINOR(dev) | <linux/kdev_t.h> | Extract the minor number | MINOR(devicenumber) |
Always use the macros. The 12/20 split is an implementation detail and may change. In ls -l output the major and minor replace the file size, for example 200, 1.
Kernel API Reference for Automatic Device Node Creation
Here is every API the three programs use, with all parameters, the return value and the effect you can observe. Signatures follow recent kernels; differences for older kernels are marked.
Module skeleton: module_init, module_exit, MODULE_LICENSE, printk
| API | Meaning | Notes |
|---|---|---|
module_init(fn) | Registers fn as the function run at insmod. | fn is int fn(void). Return 0 for success or a negative errno. On failure the module is not loaded and exit is not called, so init must clean up its own partial work. |
module_exit(fn) | Registers fn to run at rmmod. | void fn(void). Must undo everything init did, in reverse order. |
MODULE_LICENSE("GPL") | Declares the licence of the module. | Needed to use GPL-only exported symbols. Without it the kernel is tainted and linking may fail with “Unknown symbol”. |
printk(fmt, ...) | Kernel version of printf; writes to the kernel log buffer. | Read with dmesg. Can be prefixed with a level such as KERN_INFO. Modern code uses pr_info() and pr_err(). End messages with \n. |
class_create()
/* Linux 6.4 and newer (what your code uses) */
struct class *class_create(const char *name);
/* Linux 6.3 and older (older books and notes) */
struct class *class_create(struct module *owner, const char *name);
/* usage: class_create(THIS_MODULE, "myclass"); */
| Item | Meaning |
|---|---|
owner (old API only) | Module that owns the class, normally THIS_MODULE. Removed in Linux 6.4. |
name | Name of the class. It becomes the directory /sys/class/<name> and must be unique system-wide. |
| Return value | A valid struct class *, or an error encoded in the pointer with ERR_PTR(-errno). It is never NULL; test it with IS_ERR(). |
| Header | <linux/device.h> |
The class is only a container. By itself it creates no device node; it is the handle you later pass to device_create(). Calling class_create("myclass") twice fails because the sysfs directory already exists (the kernel logs sysfs: cannot create duplicate filename '/class/myclass'). If you compile on a newer kernel with the old two-argument call, or the reverse, the compiler reports the wrong number of arguments. Use the form that matches uname -r.
class_destroy()
void class_destroy(const struct class *cls); /* older kernels: struct class *cls */
cls is the pointer returned by class_create(). The call removes /sys/class/myclass and the kernel emits a remove /class/myclass (class) event. Destroy every device of the class first with device_destroy(), then the class. Call it in module_exit() and in the error paths of init.
device_create()
struct device *device_create(const struct class *class, /* older: struct class * */
struct device *parent,
dev_t devt,
void *drvdata,
const char *fmt, ...);
| Parameter | Meaning | In our programs |
|---|---|---|
class | The class to register the device in, the value returned by class_create(). | class |
parent | Parent struct device, if any. NULL places the device under /sys/devices/virtual/<class>/; a real pointer makes it a child of that device. | NULL |
devt | The dev_t (major and minor) of the character device. It is written to the dev file and used for the node. | dev1, dev2, devicenumber |
drvdata | Private pointer stored in the device; retrieve it later with dev_get_drvdata(). | NULL |
fmt, ... | printf-style device name; it becomes the name of /dev/<name>. | "mydevice%d", 1 gives mydevice1 |
| Return value | struct device * or ERR_PTR(-errno). Check with IS_ERR(). | Not checked in the drafts |
Conceptually the call allocates and initialises a struct device, sets its name from fmt, fills in class, parent, devt and drvdata, registers it, creates the sysfs directory with the attributes dev, uevent and subsystem, creates the symlink in /sys/class/<class>/, emits the add uevent and (with devtmpfs) creates the node. It is the helper for character-device classes.
Important: device_create() does not create a struct cdev. Without cdev_add() the node exists but open() fails with ENXIO (“No such device or address”). Attaching a real driver to the node is the topic of the next lecture.
device_destroy()
void device_destroy(const struct class *class, dev_t devt);
There is no device pointer parameter: the kernel finds the device by the pair (class, devt). That is why dev1 and dev2 are global variables in Program 2, because exit still needs them. Each device_create() needs exactly one matching device_destroy(), and all of them must run before class_destroy(). The effect is a remove uevent, removal of the sysfs entries and removal of the node.
alloc_chrdev_region() and unregister_chrdev_region()
int alloc_chrdev_region(dev_t *dev, unsigned baseminor,
unsigned count, const char *name);
void unregister_chrdev_region(dev_t first, unsigned count);
| Parameter | Meaning | Value in 3_char.c |
|---|---|---|
dev | Output. Receives the first allocated dev_t. | &devicenumber |
baseminor | First minor number requested. | base_minor = 0 |
count | How many consecutive minor numbers to reserve. | count = 1 |
name | Name shown next to the major in /proc/devices. | "mychardev" |
| Return value | 0 on success, a negative errno on failure. | if(!alloc_chrdev_region(...)) means success |
The static alternative, register_chrdev_region(MKDEV(200,0), n, name), asks for one specific major and fails if another driver owns it. alloc_chrdev_region() lets the kernel choose a free major, which avoids collisions; the price is that the major is unknown until run time. That is exactly why automatic node creation exists: you can no longer type a fixed number into mknod. The reserved range must be returned with unregister_chrdev_region() in exit and in init error paths.
IS_ERR(), PTR_ERR() and ERR_PTR()
Many kernel functions that return pointers encode a failure inside the pointer value. IS_ERR(ptr) tells you whether the pointer is an error, and PTR_ERR(ptr) converts it back to a negative errno you can return from init. class_create() and device_create() both work this way. Using such a pointer without checking can crash the kernel later. Our three rough-draft programs skip the check to stay short; the ep_autonode demo does it properly.
Observing Events with udevadm monitor
udevadm monitor lets you tap into udev in real time and see what it sees when devices appear. It prints events from two sources: KERNEL, the raw uevent sent by the kernel, and UDEV, the event udev sends out after finishing rule processing. Start it in the first terminal before loading any module.
$ udevadm monitor # both sources
$ udevadm monitor --kernel # only KERNEL events
$ udevadm monitor --udev # only UDEV events
$ udevadm monitor --property # also show variables (ACTION, DEVPATH, MAJOR, MINOR, DEVNAME ...)
$ udevadm monitor --subsystem-match=myclass
Each output line has the same anatomy:
Anatomy of one udevadm monitor line
Three rules of thumb help reading any capture. First, every KERNEL line normally has a UDEV twin about 2 ms later. Second, the KERNEL column shows the real order in which your driver ran. Third, the UDEV column can be reordered because udevd processes events in parallel; you will see an example in Program 3. Events with unrelated paths are just noise, for instance the change ... power_supply/BAT0 line that your laptop battery produces.
The Makefile Explained Line by Line
obj-m := 3_char.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
| Line | Code | What it does |
|---|---|---|
| 2 | obj-m := 3_char.o | Kbuild syntax: build 3_char.c into a loadable module (m); the output is 3_char.ko. The module name seen later in events (/module/3_char) comes from this file name. Change it to 1_char.o or 2_char.o for the other programs, or list all three. |
| 4 | KDIR := /lib/modules/$(shell uname -r)/build | Path of the kernel build tree for the running kernel: headers plus the Kbuild system. $(shell uname -r) runs the command and inserts the kernel version. Needs the linux-headers package. |
| 5 | PWD := $(shell pwd) | Absolute path of the current directory, the folder that holds your source (the “external module” directory). |
| 7 | all: | Default target, run when you type just make. |
| 8 | $(MAKE) -C $(KDIR) M=$(PWD) modules | -C $(KDIR) changes into the kernel tree so its rules are used. M=$(PWD) tells Kbuild where your module lives. modules is the target to build. This line must start with a TAB, not spaces. |
| 10 | clean: | Target run with make clean. |
| 11 | $(MAKE) -C $(KDIR) M=$(PWD) clean | Same trick with the clean target; removes .o, .ko, .mod*, Module.symvers and other build products. |
A successful make produces 3_char.o, 3_char.mod.c, 3_char.mod.o, 3_char.ko, modules.order and Module.symvers. The .ko is built for one specific kernel; inserting it into a different kernel gives “Invalid module format”. Compare modinfo 3_char.ko | grep vermagic with uname -r to check.
Common workflow for every program below:
# Terminal A
$ udevadm monitor
# Terminal B
$ make
$ sudo insmod 1_char.ko # use 2_char.ko or 3_char.ko for the other programs
$ dmesg | tail
$ ls /sys/class/myclass
$ ls -al /dev/mydevice*
$ sudo rmmod 1_char
$ make clean
All three programs create a class named myclass, so load only one at a time and always rmmod before loading the next.
Program 1: Create and Destroy a Class
The first program uses the smallest possible part of the device model. It creates a class and removes it again. There is no device and no device number, so the experiment shows that a class alone never produces a node in /dev. Set obj-m := 1_char.o in the Makefile and build.
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/delay.h>
#include<linux/device.h>
MODULE_LICENSE("GPL");
static struct class *class;
static int test_hello_init(void)
{
class = class_create("myclass");
return 0;
}
static void test_hello_exit(void)
{
class_destroy(class);
}
module_init(test_hello_init);
module_exit(test_hello_exit);
Program 1: line-by-line explanation
| Line | Code | What it does |
|---|---|---|
| 1 | #include<linux/kernel.h> | Core kernel declarations: printk and its log levels and general helper macros. Program 1 does not print anything, but this header is standard in every module. |
| 2 | #include<linux/module.h> | Module infrastructure: module_init, module_exit, MODULE_LICENSE, struct module and THIS_MODULE. Mandatory for any loadable module. |
| 3 | #include<linux/delay.h> | Delay helpers such as msleep() and udelay(). Unused here; it can be removed. |
| 4 | #include<linux/device.h> | The device model API: struct class, struct device, class_create, class_destroy, device_create and device_destroy. This is the header the whole lecture is about. |
| 6 | MODULE_LICENSE("GPL"); | Tells the kernel the module is GPL. This allows use of GPL-only exported symbols (the device-model functions) and avoids tainting the kernel. |
| 7 | static struct class *class; | A pointer to a struct class. static limits it to this file so it cannot clash with symbols from other modules, and it starts as NULL because statics are zero-initialised. It is a global so that exit can hand the same pointer to class_destroy(). (class is a legal variable name in C but a keyword in C++; myclass is a safer name.) |
| 9 | static int test_hello_init(void) | The init function. It runs once, inside insmod. It returns int: 0 means success, a negative errno aborts the load. static keeps the name private to the file. |
| 10, 13 | { ... } | Function body braces. |
| 11 | class = class_create("myclass"); | Allocates a struct class, registers it with the driver core and creates the directory /sys/class/myclass. The kernel emits the uevent add /class/myclass (class). The returned pointer is either valid or an ERR_PTR; the draft stores it without checking. |
| 12 | return 0; | Reports success. The module stays loaded and the class stays alive until exit runs. |
| 15 | static void test_hello_exit(void) | The exit function. It runs inside rmmod, takes no arguments and returns nothing. |
| 17 | class_destroy(class); | Removes /sys/class/myclass and emits remove /class/myclass (class). Every resource init created is released here, so a later insmod starts clean. |
| 19 | module_init(test_hello_init); | Registers test_hello_init as the entry point the kernel calls at load time. |
| 20 | module_exit(test_hello_exit); | Registers test_hello_exit as the function the kernel calls at unload time. |
Program 1: output explained
KERNEL[4538.037922] add /class/myclass (class)
KERNEL[4538.038091] add /module/1_char (module)
UDEV [4538.040125] add /class/myclass (class)
UDEV [4538.040305] add /module/1_char (module)
... module stays loaded for about 123 seconds ...
KERNEL[4661.510051] remove /class/myclass (class)
UDEV [4661.511128] remove /class/myclass (class)
KERNEL[4661.522124] remove /module/1_char (module)
UDEV [4661.522637] remove /module/1_char (module)
| Event | Caused by | Meaning |
|---|---|---|
add /class/myclass (class) | Line 11, class_create("myclass") | The directory /sys/class/myclass exists now. |
add /module/1_char (module) | insmod 1_char.ko | The module object /sys/module/1_char is registered. Its name comes from the .ko file name. |
remove /class/myclass (class) | Line 17, class_destroy(class) | Class directory removed during exit. |
remove /module/1_char (module) | End of rmmod | Module object removed after exit has returned. |
What to notice. No event contains /devices/... and nothing appears in /dev, because device_create() was never called. While the module is loaded, ls /sys/class/myclass shows an empty directory. The two add KERNEL events are only 0.17 ms apart because both happen inside one insmod. The module stayed loaded about 123.5 seconds (4661.51 minus 4538.04), the time between your two commands. On removal the class goes first and the module object about 12 ms later, since the module is freed only after its exit function returns. The UDEV lines trail each KERNEL line by roughly 2 ms.
Program 2: Create Two Device Nodes
Program 2 adds device_create(). Two devices are registered in the same class with hard-coded device numbers, and this is the first time nodes appear in /dev without mknod. Set obj-m := 2_char.o, build and load.
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/delay.h>
#include<linux/device.h>
#include<linux/cdev.h>
MODULE_LICENSE("GPL");
static struct class *class;
static struct device *device1, *device2;
dev_t dev1, dev2;
static int test_hello_init(void)
{
dev1 = MKDEV(200,1);
dev2 = MKDEV(200, 2);
class = class_create("myclass");
device1 = device_create(class, NULL, dev1, NULL, "mydevice%d", 1);
device2 = device_create(class, NULL, dev2, NULL, "mydevice%d",2);
return 0;
}
static void test_hello_exit(void)
{
device_destroy(class, dev1);
device_destroy(class, dev2);
class_destroy(class);
}
module_init(test_hello_init);
module_exit(test_hello_exit);
Program 2: line-by-line explanation
| Line | Code | What it does |
|---|---|---|
| 1-4 | #include<linux/kernel.h> ... device.h | Same four headers as Program 1: kernel helpers, module macros, delay helpers (unused) and the device model API. |
| 5 | #include<linux/cdev.h> | Declares struct cdev and cdev_add(), used to attach a driver to a device number. Not used yet; it is there for the next step. |
| 7 | MODULE_LICENSE("GPL"); | GPL licence declaration, as before. |
| 8 | static struct class *class; | Handle to the class, kept for exit. |
| 9 | static struct device *device1, *device2; | Two pointers that receive the return values of the two device_create() calls. They are stored but never used or checked in this draft. |
| 10 | dev_t dev1, dev2; | Two global dev_t values. They are globals because exit needs the same numbers for device_destroy(). |
| 11 | static int test_hello_init(void) | Init function, runs at insmod. |
| 13 | dev1 = MKDEV(200,1); | Builds a device number with major 200 and minor 1. Major 200 is simply assumed to be free; nothing reserves it (see the pitfalls section). |
| 14 | dev2 = MKDEV(200, 2); | Same major 200, minor 2: a second instance served by the same major. |
| 16 | class = class_create("myclass"); | Creates /sys/class/myclass. Must happen first because the devices below are registered in this class. |
| 17 | device1 = device_create(class, NULL, dev1, NULL, "mydevice%d", 1); | Registers device 1: class = class, no parent (so it goes under /sys/devices/virtual/), number = dev1 (200:1), no driver data, name = "mydevice%d" with 1, giving mydevice1. Result: sysfs entry, add uevent and the node /dev/mydevice1. |
| 18 | device2 = device_create(class, NULL, dev2, NULL, "mydevice%d",2); | Same call for device 2 with number 200:2, giving /dev/mydevice2. |
| 19 | return 0; | Success; the module stays loaded. |
| 22 | static void test_hello_exit(void) | Exit function, runs at rmmod. |
| 24 | device_destroy(class, dev1); | Undoes line 17. The device is found by (class, dev1); its sysfs entries and node are removed. |
| 25 | device_destroy(class, dev2); | Undoes line 18. |
| 26 | class_destroy(class); | Undoes line 16. It must come after both device_destroy() calls. |
| 29-30 | module_init(...); module_exit(...); | Register the init and exit functions with the module loader. |
Program 2: output explained (insmod)
KERNEL[5506.276381] add /class/myclass (class)
KERNEL[5506.276430] add /devices/virtual/myclass/mydevice1 (myclass)
KERNEL[5506.276455] add /devices/virtual/myclass/mydevice2 (myclass)
KERNEL[5506.276464] add /module/2_char (module)
UDEV [5506.278545] add /class/myclass (class)
UDEV [5506.280089] add /devices/virtual/myclass/mydevice1 (myclass)
UDEV [5506.280922] add /devices/virtual/myclass/mydevice2 (myclass)
UDEV [5506.281038] add /module/2_char (module)
| Event | Caused by | Explanation |
|---|---|---|
add /class/myclass (class) | Line 16 | The class directory is created first. |
add /devices/virtual/myclass/mydevice1 (myclass) | Line 17 | virtual because the parent is NULL; (myclass) is the subsystem, which is the class name. |
add /devices/virtual/myclass/mydevice2 (myclass) | Line 18 | Second device in the same class. |
add /module/2_char (module) | insmod | Module object registered after init finished. |
The KERNEL order (class, device1, device2, module) is exactly the order of the statements in init. All four KERNEL events fall inside 83 microseconds, and udev needs about 4.7 ms in total to finish all four. The only difference from Program 1 is the two /devices/... events, and they are what makes the nodes appear.
Program 2: the nodes created automatically
$ ls /dev/mydevice* -al
crw------- 1 root root 200, 1 Nov 23 20:59 /dev/mydevice1
crw------- 1 root root 200, 2 Nov 23 20:59 /dev/mydevice2
| Field | Value | Meaning |
|---|---|---|
| Type | c | character device (a block device would show b). |
| Mode | rw------- | Octal 0600: only the owner may read and write. This is the default when no udev rule sets another mode. |
| Link count | 1 | Hard-link count of the node. |
| Owner and group | root root | System-created nodes are owned by root. |
| Major, minor | 200, 1 and 200, 2 | Exactly the numbers from MKDEV(200,1) and MKDEV(200,2). They replace the file size column. |
| Date and name | Nov 23 20:59, /dev/mydevice1 | Creation time and the name built from "mydevice%d". |
Program 2: output explained (rmmod)
KERNEL[5620.192381] remove /devices/virtual/myclass/mydevice1 (myclass)
KERNEL[5620.192432] remove /devices/virtual/myclass/mydevice2 (myclass)
KERNEL[5620.192453] remove /class/myclass (class)
UDEV [5620.194695] remove /devices/virtual/myclass/mydevice1 (myclass)
UDEV [5620.195431] remove /devices/virtual/myclass/mydevice2 (myclass)
UDEV [5620.195652] remove /class/myclass (class)
KERNEL[5620.206275] remove /module/2_char (module)
UDEV [5620.206790] remove /module/2_char (module)
Removal runs device1, device2, class and finally the module object. This is the exact order of lines 24 to 26 in the exit function, and the rule behind it is last in, first out: whatever was created last is destroyed first. The three removals fall within 72 microseconds, the module object follows about 14 ms later, and the module had been loaded for roughly 114 seconds. After rmmod, ls /dev/mydevice* reports “No such file or directory”. If you try sudo cat /dev/mydevice1 while loaded you get “No such device or address”, which proves the node exists but no driver (cdev) is attached to 200:1 yet.
Program 3: Dynamic Major Number and Device Node
Program 3 is the real-world pattern. The driver asks the kernel for a free device number with alloc_chrdev_region() and registers a device with that number. Because the major is unknown until run time, nobody could have created the node by hand ahead of time. Set obj-m := 3_char.o, as in the Makefile above.
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/kdev_t.h>
#include<linux/fs.h>
#include<linux/device.h>
int base_minor=0;
char *device_name = "mychardev";
int count =1;
dev_t devicenumber;
static struct class *class;
static struct device *device;
MODULE_LICENSE("GPL");
static int test_hello_init(void)
{
class = class_create("myclass");
if(!alloc_chrdev_region(&devicenumber, base_minor, count, device_name)) {
printk("DEVICE NUMBER REGISTERD \n");
printk("Major number received %d\n", MAJOR(devicenumber));
device=device_create(class, NULL, devicenumber, NULL, "mydevice");
}
else
{
printk("Device number registration fialed \n");
}
return 0;
}
static void test_hello_exit(void){
printk("module exied \n");
}
module_init(test_hello_init);
module_exit(test_hello_exit);
Program 3: line-by-line explanation
| Line | Code | What it does |
|---|---|---|
| 1-2 | #include<linux/kernel.h>, module.h | Kernel helpers (printk) and module macros. |
| 3 | #include<linux/kdev_t.h> | Provides MAJOR(), MINOR() and MKDEV(). Program 3 uses MAJOR(). |
| 4 | #include<linux/fs.h> | Declares alloc_chrdev_region() and unregister_chrdev_region(). |
| 5 | #include<linux/device.h> | Class and device API. |
| 7 | int base_minor=0; | First minor number to request. 0 is the usual choice. Passed as baseminor to the allocation. |
| 8 | char *device_name = "mychardev"; | The name registered with the number. It appears next to the major in /proc/devices. |
| 9 | int count =1; | Number of consecutive minors to reserve: one device, so one minor. |
| 10 | dev_t devicenumber; | Output variable. alloc_chrdev_region() writes the allocated major and minor here. |
| 11 | static struct class *class; | Handle to the class. |
| 12 | static struct device *device; | Receives the result of device_create(). |
| 14 | MODULE_LICENSE("GPL"); | GPL licence declaration. |
| 15 | static int test_hello_init(void) | Init function, runs at insmod. |
| 17 | class = class_create("myclass"); | Creates /sys/class/myclass. Note that this happens before the number is allocated, which matters if the allocation fails. |
| 18 | if(!alloc_chrdev_region(&devicenumber, base_minor, count, device_name)) { | Asks the kernel to reserve one free character device number, first minor 0, under the name mychardev. The function returns 0 on success, so !0 is true and the block runs on success. |
| 19 | printk("DEVICE NUMBER REGISTERD \n"); | Writes a success message to the kernel log. Read it with dmesg. (“REGISTERD” is a typo for “REGISTERED”.) |
| 20 | printk("Major number received %d\n", MAJOR(devicenumber)); | Prints the major number the kernel granted. The value differs between machines and boots, which is the whole point of dynamic allocation. |
| 21 | device=device_create(class, NULL, devicenumber, NULL, "mydevice"); | Registers the device with the allocated number and the fixed name mydevice (no %d). Results: /sys/devices/virtual/myclass/mydevice, an add uevent and the node /dev/mydevice with minor 0. |
| 23-26 | else { printk("Device number registration fialed \n"); } | Failure branch: print an error. (“fialed” should be “failed”.) The class created on line 17 is not undone here. |
| 27 | return 0; | Always reports success, even when the allocation failed. It should return the negative errno in that case. |
| 30-32 | static void test_hello_exit(void){ printk("module exied \n"); } | Exit only prints a message. It does not call device_destroy(), class_destroy() or unregister_chrdev_region(), so everything init created is left behind. |
| 34-35 | module_init(...); module_exit(...); | Register the init and exit functions. |
Program 3: output explained
KERNEL[6575.405151] add /class/myclass (class)
KERNEL[6575.405225] add /devices/virtual/myclass/mydevice (myclass)
KERNEL[6575.405232] add /module/3_char (module)
UDEV [6575.406602] add /class/myclass (class)
UDEV [6575.407185] add /module/3_char (module)
UDEV [6575.407321] add /devices/virtual/myclass/mydevice (myclass)
One class, one device (mydevice, without a number) and one module event. The KERNEL order follows the code: class, device, module, all within 81 microseconds. The UDEV column shows the module before the device. That is harmless: udevd hands each event to a worker and the quick module event finished before the slower device event. Never rely on cross-device ordering in the UDEV column.
Check the rest yourself. These results follow directly from the code, so treat them as expected output and confirm them on your machine:
$ dmesg | tail -3
DEVICE NUMBER REGISTERD
Major number received 240 # your major will differ
$ grep mychardev /proc/devices
240 mychardev
$ ls -l /dev/mydevice
crw------- 1 root root 240, 0 ... /dev/mydevice
$ cat /sys/class/myclass/mydevice/dev
240:0
Now remove the module with sudo rmmod 3_char. Because exit has no cleanup, you should see only remove /module/3_char (module) in udevadm monitor. There is no remove /class/myclass and no device removal, and /dev/mydevice stays. The next section explains why that is a problem.
Comparing the Three Programs
| Feature | 1_char.c | 2_char.c | 3_char.c |
|---|---|---|---|
| Purpose | Understand the class | Understand device_create with two nodes | Dynamic device number |
| Device number | None | Hard-coded MKDEV(200,1) and MKDEV(200,2) | alloc_chrdev_region (dynamic) |
| APIs | class_create, class_destroy | Adds device_create x2, device_destroy x2, MKDEV | class_create, alloc_chrdev_region, device_create, MAJOR |
| Nodes in /dev | None | mydevice1, mydevice2 | mydevice |
| Appears in /proc/devices | No | No (major 200 never registered) | Yes (mychardev) |
| Exit cleanup | Complete | Devices and class | None |
| Module event | /module/1_char | /module/2_char | /module/3_char |
Original Demo: ep_autonode Driver
The three programs teach one concept each. The ep_autonode driver below combines them in the style used in real drivers: the number is allocated dynamically, several nodes are created in a loop, every return value is checked, and cleanup mirrors setup in both the error path and the exit function. Save it as ep_autonode.c.
// SPDX-License-Identifier: GPL-2.0
/*
* ep_autonode.c - automatic device node creation demo
* Creates EP_NODE_COUNT nodes: /dev/ep_node0 .. /dev/ep_node2
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/err.h>
#define EP_NODE_COUNT 3
#define EP_CLASS_NAME "ep_class"
#define EP_REGION_NAME "ep_autonode"
static dev_t ep_base;
static struct class *ep_class;
static int __init ep_autonode_init(void)
{
struct device *dev;
int ret, i;
/* Step 1: ask the kernel for 3 consecutive device numbers */
ret = alloc_chrdev_region(&ep_base, 0, EP_NODE_COUNT, EP_REGION_NAME);
if (ret) {
pr_err("alloc_chrdev_region failed: %d\n", ret);
return ret;
}
/* Step 2: create /sys/class/ep_class */
ep_class = class_create(EP_CLASS_NAME);
if (IS_ERR(ep_class)) {
ret = PTR_ERR(ep_class);
pr_err("class_create failed: %d\n", ret);
goto err_region;
}
/* Step 3: one device (and therefore one /dev node) per minor */
for (i = 0; i < EP_NODE_COUNT; i++) {
dev = device_create(ep_class, NULL,
MKDEV(MAJOR(ep_base), MINOR(ep_base) + i),
NULL, "ep_node%d", i);
if (IS_ERR(dev)) {
ret = PTR_ERR(dev);
pr_err("device_create(%d) failed: %d\n", i, ret);
goto err_devices;
}
}
pr_info("ready: major=%d, minors %d..%d\n", MAJOR(ep_base),
MINOR(ep_base), MINOR(ep_base) + EP_NODE_COUNT - 1);
return 0;
err_devices:
while (--i >= 0)
device_destroy(ep_class, MKDEV(MAJOR(ep_base), MINOR(ep_base) + i));
class_destroy(ep_class);
err_region:
unregister_chrdev_region(ep_base, EP_NODE_COUNT);
return ret;
}
static void __exit ep_autonode_exit(void)
{
int i;
for (i = EP_NODE_COUNT - 1; i >= 0; i--)
device_destroy(ep_class, MKDEV(MAJOR(ep_base), MINOR(ep_base) + i));
class_destroy(ep_class);
unregister_chrdev_region(ep_base, EP_NODE_COUNT);
pr_info("removed\n");
}
module_init(ep_autonode_init);
module_exit(ep_autonode_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("EmbeddedPathashala");
MODULE_DESCRIPTION("Automatic device node creation demo");
ep_autonode: line-by-line explanation
| Line | Code | What it does |
|---|---|---|
| 1 | // SPDX-License-Identifier: GPL-2.0 | Machine-readable licence tag; standard first line of kernel source files. |
| 2-5 | /* ... */ | Comment describing the file and the nodes it creates. |
| 6 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt | Makes every pr_info()/pr_err() message start with the module name automatically. It must appear before the includes. |
| 8-12 | #include <linux/module.h> ... err.h | Module macros, kernel helpers, device model, alloc_chrdev_region and the IS_ERR/PTR_ERR helpers. |
| 14 | #define EP_NODE_COUNT 3 | How many devices to create. One constant drives the allocation, the loops and the log message. |
| 15-16 | #define EP_CLASS_NAME / EP_REGION_NAME | Names of the class (/sys/class/ep_class) and of the number region (/proc/devices). A unique class name avoids a clash with the earlier demos. |
| 18 | static dev_t ep_base; | First device number of the allocated range. Later numbers are base minor plus i. |
| 19 | static struct class *ep_class; | Class handle, needed by init, error paths and exit. |
| 21 | static int __init ep_autonode_init(void) | __init tells the kernel this code can be freed after loading (built-in drivers). |
| 23 | struct device *dev; | Local variable that receives each device_create() result for checking. |
| 24 | int ret, i; | ret carries error codes; i is the loop and unwind counter. |
| 27-31 | ret = alloc_chrdev_region(...); if (ret) {...} | Step 1: reserve 3 consecutive numbers starting at minor 0. If it fails, nothing exists yet, so just log and return the error. Returning non-zero makes insmod fail cleanly. |
| 34-39 | ep_class = class_create(EP_CLASS_NAME); if (IS_ERR(...)) | Step 2: create the class. On failure convert the pointer with PTR_ERR and jump to err_region to give the number range back. |
| 42-51 | for (i = 0; i < EP_NODE_COUNT; i++) { dev = device_create(...); ... } | Step 3: create one device per minor. MKDEV(MAJOR(ep_base), MINOR(ep_base) + i) builds the number for device i; "ep_node%d", i names it ep_node0, ep_node1, ep_node2. On failure jump to err_devices. |
| 53-54 | pr_info("ready: ...") | Prints the major and the minor range so you can compare with ls -l /dev. |
| 55 | return 0; | Success. |
| 57-60 | err_devices: while (--i >= 0) device_destroy(...); class_destroy(...); | Error unwinding: destroy only the devices that were created (indexes below the failing one), then the class. Execution then falls through to the next label. |
| 61-63 | err_region: unregister_chrdev_region(...); return ret; | Return the number range and propagate the error code. Labels are in reverse order of setup, so each label undoes exactly one step. |
| 66-75 | static void __exit ep_autonode_exit(void) | Exit: destroy devices in reverse order (last created first), then the class, then the number range, then log. This is the same sequence as the error path. |
| 77-78 | module_init(...); module_exit(...); | Register init and exit. |
| 80-82 | MODULE_LICENSE / AUTHOR / DESCRIPTION | Metadata shown by modinfo; the GPL licence is required for the device-model symbols. |
Build and run ep_autonode
obj-m := ep_autonode.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
all:
$(MAKE) -C $(KDIR) M=$(PWD) modules
clean:
$(MAKE) -C $(KDIR) M=$(PWD) clean
$ make
$ sudo insmod ep_autonode.ko
$ dmesg | tail -2
$ ls -l /dev/ep_node*
$ ls /sys/class/ep_class
$ grep ep_autonode /proc/devices
$ sudo rmmod ep_autonode
$ ls /dev/ep_node*
Expected result (the major number will differ on your machine; this driver was written to the API signatures described above, so build it once on your own kernel to confirm):
[ 1234.567890] ep_autonode: ready: major=240, minors 0..2
crw------- 1 root root 240, 0 Nov 23 21:30 /dev/ep_node0
crw------- 1 root root 240, 1 Nov 23 21:30 /dev/ep_node1
crw------- 1 root root 240, 2 Nov 23 21:30 /dev/ep_node2
ep_node0 ep_node1 ep_node2
240 ep_autonode
[ 1290.123456] ep_autonode: removed
ls: cannot access '/dev/ep_node*': No such file or directory
Fixing Node Permissions with udev Rules
The kernel and devtmpfs create nodes with mode 0600 owned by root. udev lets you change that without touching driver code. Rules live in /usr/lib/udev/rules.d/ (the distribution) and /etc/udev/rules.d/ (the administrator, which wins on a conflict). The numeric prefix of the file name sets the processing order.
# /etc/udev/rules.d/99-ep.rules
SUBSYSTEM=="ep_class", KERNEL=="ep_node*", MODE="0660", GROUP="dialout", SYMLINK+="ep_link%n"
| Rule piece | Meaning |
|---|---|
SUBSYSTEM=="ep_class" | Match devices that belong to our class. |
KERNEL=="ep_node*" | Match by kernel device name with a wildcard. |
MODE="0660" | Permissions: owner and group may read and write, others nothing. |
GROUP="dialout" | Group that owns the node; users in that group get access. |
SYMLINK+="ep_link%n" | Add an extra name; %n expands to the kernel number (0, 1, 2). |
$ sudo udevadm control --reload-rules
$ sudo rmmod ep_autonode; sudo insmod ep_autonode.ko # or: sudo udevadm trigger
$ ls -l /dev/ep_node* /dev/ep_link*
# helpers
$ udevadm info -a -n /dev/ep_node0 # attributes you can match in rules
$ udevadm test /sys/devices/virtual/ep_class/ep_node0 # dry-run the rules
Prefer a group with mode 0660 on real systems. A world-writable node (0666) is only acceptable on a throw-away lab machine.
Common Mistakes and Troubleshooting
Problems in the rough-draft programs
| # | Where | Problem | Impact | Fix |
|---|---|---|---|---|
| 1 | 3_char exit | No device_destroy, class_destroy or unregister_chrdev_region | Class, device and major leak; you lose the pointers and cannot clean up without a reboot. A second insmod fails to create myclass but still loads. | Mirror init in exit (see ep_autonode) |
| 2 | 3_char init | Returns 0 when allocation fails | Module loads although it is broken | Return the negative errno |
| 3 | All programs | No IS_ERR() check after class_create and device_create | Silent failures and later crashes | Check and use goto unwinding |
| 4 | 3_char init | Class is created before the number allocation and not undone on failure | Leak on the error path | Allocate first, unwind in reverse order |
| 5 | 2_char | Major 200 hard-coded and never reserved | Possible clash with another driver | Use alloc_chrdev_region(&dev, 0, 2, name) |
| 6 | 2_char, 3_char | No cdev_add() or file_operations | open() fails with ENXIO | Covered in the next lecture |
| 7 | Makefile | obj-m is hard-coded to 3_char.o | Must edit for each program | obj-m := 1_char.o 2_char.o 3_char.o |
| 8 | All programs | Unused includes, message typos, printk without a level, variable named class | Cosmetic | Use pr_info/pr_err, clean names |
Troubleshooting table
| Symptom | Likely cause | What to do |
|---|---|---|
make: ... /build: No such file or directory | Kernel headers not installed | sudo apt install linux-headers-$(uname -r) |
Compile error: wrong number of arguments to class_create | Kernel API changed in 6.4 | Linux 6.4+: one argument. Older: THIS_MODULE, name. |
insmod: Invalid module format | Module built for another kernel | Compare modinfo x.ko | grep vermagic with uname -r and rebuild. |
Unknown symbol in module | Missing GPL licence | Add MODULE_LICENSE("GPL") and check dmesg. |
dmesg: cannot create duplicate filename /class/myclass | Another module, or a leaked 3_char, already owns the class | Run lsmod, remove the other module, fix the cleanup, reboot if it leaked. |
Entry in /sys/class/... but no /dev node | udev or devtmpfs side | Watch udevadm monitor; check that systemd-udevd is running. |
| No sysfs entry and no node | device_create failed unnoticed | Add IS_ERR checks and print the error. |
Permission denied when opening | Mode 0600, owner root | Use sudo or add a udev rule. |
No such device or address when opening | No cdev registered for that major and minor | Register a cdev with file_operations. |
Diagnose from the outside in: does the module load (lsmod, dmesg), did the driver publish the device (/sys/class), did udev create the node (/dev), and can a process open it (permissions, then cdev).
Best Practices for Automatic Device Node Creation
- Set up in a fixed order and tear down in the reverse order: number region, class, devices on the way in; devices, class, number region on the way out.
- Check every pointer-returning call with
IS_ERR()and returnPTR_ERR()from init. - Prefer
alloc_chrdev_region()over a hard-coded major. Use a static major only when a number has been officially assigned. - Use
gotolabels for error unwinding; each label undoes exactly one step. - Choose unique, meaningful names. The class name is global in sysfs and the device name is global in
/dev. - Use
pr_info()andpr_err()with apr_fmtprefix instead of bareprintk. - Keep policy out of the driver. Permissions and extra names belong in udev rules, not in the module.
Performance considerations
Creating one node is cheap: in the captures above the kernel work takes well under a millisecond and udev needs a few milliseconds. A driver that creates hundreds of devices at once produces a burst of uevents, and udev workers process them in parallel. If a script must use a node right after loading the module, wait with udevadm settle instead of a fixed sleep.
Security considerations
A new node is root-only by default, which is the safe default. Do not weaken it with MODE="0666" on production systems; grant access through a group or a user tag. Remember that a node is an attack surface: once you add file_operations, validate every size and pointer that arrives from user space. Finally, never leave nodes behind after unload; a stale node or class is exactly what an incomplete exit function produces.
Real-World Uses of Automatic Device Node Creation
Every time hardware appears, this mechanism runs. Plugging in a USB serial adapter creates /dev/ttyUSB0. A webcam registered through V4L2 creates /dev/video0. A new keyboard or mouse produces /dev/input/eventN, and a hardware watchdog driver exposes /dev/watchdog. In each case a driver calls the same device-model functions you used here, usually through a subsystem wrapper, and udev rules give the node its final name and permissions. Writing your own driver for custom hardware on an embedded board follows exactly the same steps.
Summary and Key Takeaways
- Static
/devwas replaced by udev and devtmpfs, which create nodes from kernel events for devices that really exist. - The driver only populates sysfs through the device model:
class_create()thendevice_create(). class_create()makes/sys/class/<name>only;device_create()makes the device, thedevfile, the uevent and the/devnode.alloc_chrdev_region()gives a collision-free number; read it withMAJOR(). It returns 0 on success.- Always undo in reverse:
device_destroy(),class_destroy(),unregister_chrdev_region(). - Observe everything with
udevadm monitor,ls /sys/class,ls -l /devand/proc/devices. - Nodes are root-only by default; udev rules change names and permissions without touching the driver.
Conclusion. You started with a class that creates nothing visible, added two devices to see nodes appear, and then switched to a dynamic device number, which is how real drivers work. Along the way you saw that the kernel never creates a node on its own initiative: it publishes a device, announces it with a uevent, and the user-space side finishes the job. You also saw why cleanup matters: Program 3 loads fine but cannot be unloaded cleanly. The ep_autonode driver shows the safe pattern. This lecture is one step in our free linux device drivers course; the node you created has no driver behind it yet, so the next lecture attaches struct cdev and file_operations to make open(), read() and write() reach your code.
Frequently Asked Questions
Do I still need mknod to create a device node?
No. When a driver registers a device with device_create(), the kernel publishes it in sysfs and sends a uevent, and the node in /dev is created automatically (by devtmpfs and udev). You only use mknod for quick experiments or on systems without udev or devtmpfs.
What is the difference between class_create() and device_create()?
class_create() creates only the class directory under /sys/class and no node. device_create() registers one device inside a class, creates its sysfs entries including the dev file, sends the add uevent and results in a node in /dev. You need a class before you can create devices in it.
Why does my device appear under /sys/devices/virtual?
Because the parent argument of device_create() was NULL. A device without a parent is not attached to a real bus such as PCI or USB, so the kernel places it in the virtual hierarchy. Pass a parent struct device pointer to make it a child of a real device.
Why is my node owned by root with mode crw——-?
devtmpfs creates nodes with mode 0600 owned by root, and no udev rule changed that. Add a rule in /etc/udev/rules.d that sets MODE, OWNER or GROUP, then reload the rules and reload the module.
Why does class_create() give a compile error about arguments?
The signature changed in Linux 6.4. Kernels 6.4 and newer take only the name, class_create("myclass"). Older kernels take two arguments, class_create(THIS_MODULE, "myclass"). Use the form that matches uname -r.
The node exists but open() fails with No such device or address. Why?
device_create() only creates the node. Without a struct cdev added by cdev_add() for that major and minor, the kernel has no driver to connect it to, so open() returns ENXIO. Registering the cdev and file operations is covered in the next lecture.
Can I load 1_char, 2_char and 3_char at the same time?
No. All three create a class named myclass, and the class name must be unique in sysfs. Remove one module with rmmod before inserting the next. Also remember that 3_char has no cleanup, so it leaves its class behind until you reboot.
Who actually creates the file in /dev, the kernel or udev?
With devtmpfs (the normal case) the kernel creates the basic node when device_create() runs, and udev then applies rules for names, permissions and symlinks. On systems without devtmpfs, udev creates the node from the uevent. Your driver never calls mknod in either case.
Keep Learning for Free
Continue with the next lecture and attach a real driver to your device node. EmbeddedPathashala offers a free embedded systems course, a free linux development course and a free linux kernel development course for students.
Next Lecture View Full Course