I'm writing a kernel module. I can easily create a character device in /dev/ but I want to have 3 devices available to my user and it would be nice to put them all under a /dev/ subdirectory.

Possible example (exists on my openSUSE box):

# ls -l /dev/bsg
total 0
crw-rw---- 1 root root 252, 0 Jul 17 14:28 0:0:0:0
crw-rw---- 1 root root 252, 1 Jul 17 14:28 0:0:1:0
crw-rw---- 1 root root 252, 2 Jul 17 14:28 0:0:2:0
crw-rw---- 1 root root 252, 3 Jul 17 14:28 0:0:3:0
crw-rw---- 1 root root 252, 4 Jul 17 14:28 0:0:4:0
crw-rw---- 1 root root 252, 5 Jul 17 14:28 1:0:0:0

(I have looked at the bsg.c code but am at a loss to what "parent" the character devices are added to).

How can I do something similar?


I found a way that works for me, one that doesn't use udev rules (I'd rather do it programmatically). This is easier than I thought earlier.

  1. alloc_chrdev_region for number of devices.
  2. Create classes for each device (each with different names)
  3. Set the classes' devnode field with your custom function ex: return kasprintf(GFP_KERNEL, "name/%d", global++);. This is where the naming happens. Udev should honor this function.
  4. Create cdevs with cdev_init && cdev_add and set their fops.
  5. Create devices with device_create (parent is NULL)

Note that there is no device hierarchy here, just independent devices which happen to be in the same /dev/ directory. The names specified in steps 2-5 will end up in /sys/.

  • 1
    There is no need to create a class for each device. Just use one main class and prefix the device's name given the devnode function. But I will give you a +1 for pointing me towards devnode. Also, when calling create_device or one of its extensions, you can specify the name as a path directly.
    – Twifty
    Aug 28 '19 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.