What is the modern way of creating devices files in /dev/?

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, 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,
  • uses awk to extract the major number from that device,
  • finally passes that major number to mknod to 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?

Leave a Reply

Your email address will not be published.