Adding a device from a kernel module the udev way (pi, a device that prints out the value of pi)
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:
Hope that helps someone out there.
source files
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 < 0) {
printk ("Failed to register device %s with error %d\n", DEVICE_NAME, pi_Major);
return pi_Major;
}
/* create /dev/pi
* we use udev to make the file
*/
pi_class = class_create(THIS_MODULE,DEVICE_NAME);
err_dev = device_create(pi_class, NULL, MKDEV(pi_Major,0),NULL,DEVICE_NAME);
return 0;
}
/* remove the module
*/
static void pi_exit(void)
{
/* free our memory, then destroy the device
* then unregister the class and destroy it (unregister before destroy....important
*/
kfree(msg);
device_destroy(pi_class,MKDEV(pi_Major,0));
class_unregister(pi_class);
class_destroy(pi_class);
unregister_chrdev(pi_Major, DEVICE_NAME);
}



February 25th, 2009 at 3:38 pm
Is this the official way to do it, or just a workaround ? Thanks.
February 25th, 2009 at 3:42 pm
Do I still need to write my own udev rules ?
February 25th, 2009 at 7:01 pm
You can if you want, but the device will be created automatically with this setup.
February 25th, 2009 at 7:02 pm
This is what I figured out by reading the kernel source and some modules.
May 29th, 2009 at 12:32 pm
short and clear description, appreciated !