Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to register struct cdev in driver code

This may be a novice question, but please help me to understand it.

Why exactly do we need to register the struct cdev in our character driver?

like image 247
sandy Avatar asked Feb 05 '13 10:02

sandy


People also ask

What is struct Cdev?

struct cdev is the kernel's internal structure that represents char devices; this field contains a pointer to that structure when the inode refers to a char device file.

What is struct File_operations?

The file_operations Structure. The file_operations structure is defined in linux/fs. h, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.

How can we allocate device number dynamically?

Dynamically Allocatingdev is an output-only parameter that will, on successful completion, hold the first number in your allocated range. firstminor should be the requested first minor number to use; it is usually 0. count is the total number of contiguous device numbers you are requesting.

What is Cdev_alloc?

cdev_alloc() dynamically allocates my_dev , so it will call kfree(pointer) when cdev_del() . cdev_init() will not free the pointer. Most importantly, the lifetime of the structure my_cdev is different.


1 Answers

struct cdev represent a character device within the kernel.

All streaming devices(ex: uart, keyboard) falls under the character device category and is available in user-space as a device node file (ex: /dev/ttyS0). User applications accesses the device by using the standard File I/O operations.

enter image description here

Inside kernel, character driver comes in between the device file and the streaming device, and this driver layer takes care of translating the File I/O operation to Device operations and vice-versa.

In character device driver development struct file_operations is the most important data structure used. This structure is used to implement the basic file i/o - open(), read(), write(), close(), ioctl(), etc... functionality for the the device.

struct cdev structure encapsulates the file_operations structure and some other important driver information(major/minor no). It is the new way of registering character driver with kernel.

The cdev structure is accessed by the kernel through the following API's:

cdev_init() - used to initialize struct cdev with the defined file_operations
cdev_add()  - used to add a character device to the system. 
cdev_del()  - used to remove a character device from the system

After a call to cdev_add(), your device is immediately alive. All functions you defined (through the file_operations structure) can be called.

like image 148
Praveen Felix Avatar answered Oct 14 '22 05:10

Praveen Felix