Character Devices

Registering a block device in the kernel requires two steps:

□ Register or allocate a range of device numbers. If the driver wants to use a specified range of device numbers, register_chrdev_region must be employed, while alloc_chrdev_region lets the kernel choose an apt range. The prototypes are as follows:

int register_chrdev_region(dev_t from, unsigned count, const char *name) int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name);

When a new range is allocated with alloc_chrdev_region, the smallest minor number and the size of the desired range have to be specified in baseminor and count. The selected major number is returned in dev. Note that struct cdev is not required to register or allocate device numbers.

□ After a device number range has been obtained, the device needs to be activated by adding it to the character device database. This requires initializing an instance of struct cdev with cdev_init, followed by a call to cdev_add. The prototypes of the functions are defined as follows:

void cdev_init(struct cdev *cdev, const struct file_operations *fops); int cdev_add(struct cdev *p, dev_t dev, unsigned count);

fops in cdev_init contains pointers to the operations that handle the actual communication with the device. count in cdev_add denotes how many minors the device provides.

Observe, for instance, how the FireWire video driver activates a character device (the driver has already registered the major number ieee1394_video1394_dev with 16 minor numbers before).

drivers/ieee1394/video1394.c static struct cdev videol394_cdev;

cdev_init(&videol3 94_cdev, &videol3 94_fops);

ret = cdev_add(&videol394_cdev, IEEEl3 94_VIDEOl3 94_DEV, 16);

After cdev_add returns successfully, the device is alive and active.

Since all registration functions discussed above manipulate the database data structures in a straightforward way, I do not bother to discuss their code explicitly.

In ancient times long long ago, the standard registration function for character devices used to be register_chrdev. It is still supported for backward compatibility, and quite a number of drivers have not been updated to the new interface as described above. New code, however, should not employ it!5 The function does also not work for device numbers larger than 255.

Continue reading here: Block Devices

Was this article helpful?

0 0