linuxlinux-kernellinux-device-driver

Diffrences between cdev_add and device_create function?


I am newbie on linux device driver development. I can't understand what cdev_add actually do.I viewed some simple char device driver code and I saw, cdev_add and device_create function used together. For instance:

/* Create device class, visible in /sys/class */
dummy_class = class_create(THIS_MODULE, "dummy_char_class");
if (IS_ERR(dummy_class)) {
    pr_err("Error creating dummy char class.\n");
    unregister_chrdev_region(MKDEV(major, 0), 1);
    return PTR_ERR(dummy_class);
}

/* Initialize the char device and tie a file_operations to it */
cdev_init(&dummy_cdev, &dummy_fops);
dummy_cdev.owner = THIS_MODULE;
/* Now make the device live for the users to access */
cdev_add(&dummy_cdev, devt, 1);

dummy_device = device_create(dummy_class,
                            NULL,   /* no parent device */
                            devt,    /* associated dev_t */
                            NULL,   /* no additional data */
                            "dummy_char");  /* device name */

What cdev_add and device_create do in this code?


Solution

  • To use a character driver, first you should register it with the system. Then you should expose it to the user space.

    cdev_init and cdev_add functions perform the character device registration. cdev_add adds the character device to the system. When cdev_add function successfully completes, the device is live and the kernel can invoke its operations.

    In order to access this device from user space, you should create a device node in /dev. You do this by creating a virtual device class using class_create, then creating a device and registering it with sysfs using the device_create function. device_create will create a device file in /dev.

    Read Linux Device Drivers, Third Edition, chapter 3 (Char Drivers) for a good description of the process (class_create and device_create are not covered in the book).