Adding a device from a kernel module the udev way (pi, a device that prints out the value of pi)

It seems like the interface for creating modules has changed a bit, and udev is the way to go. Here is a short, quick and dirty module that creates /dev/pi with anonymous major and minor using udev.

The module creates the device (not the file) with register_chrdev, which returns the value of the major number that was assigned. We then use class_create to create a udev class to contain the device, finally you call device_create to actually make the device file.

To remove the device, you call device_destroy to remove the device from the class, then class_unregister to remove the class from sysfs. class_destroy is called to delete the class and finally unregister_chrdev to remove the device from the kernel (the device not the file).

The relevant init and exit sections are: static int pi_init(void) { struct device *err_dev; msg = kmalloc(sizeof(char)*DIGITS, GFP_ATOMIC); // register pi as a device pi_Major = register_chrdev(0, DEVICE_NAME, &fops); if (pi_Major Hope that helps someone out there. source files

Wordpress category: 

Comments

Is this the official way to do it, or just a workaround ? Thanks.

Do I still need to write my own udev rules ?

You can if you want, but the device will be created automatically with this setup.

This is what I figured out by reading the kernel source and some modules.

short and clear description, appreciated !

Very concise. I cleaned up one of my modules thanks to your summary. Good job.

Is there another way to do device_create/destroy for Non-GPL kernel driver? Or is going GPL the only way for drivers wanting to use UDEV/SYSFS?

Great summary! The great LDD3 book is a bit outdated nowadays so this post helped me a lot!

Great help! Thanks!

Can you check and let me know how to create a device file for block device in case someone wahts udev service for block device ?

Add new comment

Markdown

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.