How to associate a device in / dev / with the actual driver

I am trying to understand how a device driver works on Linux.

  • I have a node device as follows (base number 89, i2c-0 device name)

    crw-r--r-- 1 0 0 89, 0 Sep 29 01:36 /dev/i2c-0 
  • I have an i2c driver named i2c.ko , and during startup I will do insmod i2c.ko

  • And in the driver during initialization, the following function will be called:

     register_chrdev(89, "i2c", &i2chtv_fops)<0 // not "i2c-0" 

My question is: when the user calls open("/dev/i2c-0", O_RDWR) , how does the kernel know which driver to use? I noticed that the device name is i2c-0 , but the registered device name is i2c . Is it because they use the same basic number that the kernel can use the correct driver?

+4
source share
2 answers

Yes, the main numbers select the driver, and the lower numbers select the "units" (whatever it is: for the console driver, these are different screens).

-0 you see "one" (if you have more than one i2c bus in your system).

+3
source

The main number tells you which driver processes the device file. An invalid number is used only by the driver itself to distinguish which device it is running on, just in case the driver is processing multiple devices.

Adding a driver to your system means registering it with the kernel. This is synonymous with assigning a large number during module initialization. You do this using the register_chrdev function defined by linux / fs.h.

  int register_chrdev(unsigned int major, const char *name, struct file_operations *fops); 

where unsigned int major is the main number you want to request, const char * name is the name of the device that will be displayed in / proc / devices and struct file_operations * fops is a pointer to the file_operations table for your driver. A negative return value means that registration failed. Please note that we did not pass the register_chrdev minor number. This is because the kernel does not care about the lowest number; only our driver uses it.

From here

+4
source

All Articles