tl;dr
If I want my module do adhere to modern practices, should I create devices in /dev/ via mknod in a shell script or via class_create and device_create C functions directly in the module source code? What are the advantages of one approach over the other?
In detail
In Chapter 3 of Linux Device Drivers, Third Edition, page 45 the function register_chrdev_region is presented as the function to use for registering a character device if the device numbers are known.
However, since device numbers unused today could become used by the kernel tomorrow, the usage of this function is discouraged almost immediately, at page 46, in favor of alloc_chrdev_region, which allows a dynamic allocation of major numbers.
At this point, though, the authors make the point that one can't create device nodes in /dev/ in advance because to create them the major number has to be known, and it isn't known before alloc_chrdev_region returns.
The presented solution is a shell script, which:
- loads the module with
insmod,- which calls the module's init function,
- which calls
alloc_chrdev_region,- which results in a new device in
/proc/devices,
- which results in a new device in
- which calls
- which calls the module's init function,
- uses
awkto extract the major number from that device, - finally passes that major number to
mknodto create device files in/dev/(the minor number is encoded in the name of the device files).
However, The Linux Kernel Module Programming Guide makes use of functions class_create and device_create, I believe to accomplish the same task.
What makes me nervous about it is that, despite the book being still updated nowawdays, it has some aspect that makes it older than Linux Device Drivers, Third Edition.
For instance, it makes use of register_chrdev, even though it suggests preferring register_chrdev_region or alloc_chrdev_region, whereas Linux Device Drivers, Third Edition is more categorical in calling register_chrdev The Older Way, relegating its explanation to barely more than half of page 57.
On the other hand, The Linux Kernel Module Programming Guide is not the only source that I've found that uses class_create and device_create C functions, rather than mknod shell function, to create device files. Here's another one, blog post written in early 2018.
So how are things meant to be done today?
drivers/char, but there, for instance inmem.cI find all ofregister_chrdev,class_register, anddevice_createused.