Hard time in understanding MODULE_DEVICE_TABLE(usb, id_table) usage

It is usually used to support hot-plugging, by loading/inserting the driver for a device if not already loaded.

There is a similar question here: Detect the presence of a device when it's hot plugged in Linux

(From my ans)

It works as follows:

  1. Each driver in the code exposes its vendor/device id using:

      MODULE_DEVICE_TABLE(of, omap_mcspi_of_match);
    
  2. At compilation time the build process extracts this infomation from all the drivers and prepares a device table.

  3. When you insert the device, the device table is referred by the kernel and if an entry is found matching the device/vendor id of the added device, then its module is loaded and initialized.


According to Linux Device Drivers:

  1. MODULE_DEVICE_TABLE is used to generate map files by depmod program;
  2. When device is hot-plugged, bus driver generates hotplug event. Kernel calls /sbin/hotplug with appropriate environmental variables set;
  3. Given map files and information from environment, /sbin/hotplug decides which module to load and actually loads it. If the module is already loaded, it's OK.

I should mention again that this mechanism just ensures that needed module is in-place when device is plugged. That doesn't link module with that device or anything else. Just loads module.

To check if driver is OK for specific device, match() function from bus_type is used.


Here is how I understands the things [Xbuntu 14.04 compatible].

Once we wrote a module, we can either load it manually, or automatically.

  • Manually -> insmod modulename.ko or modprob modulename.ko
  • Automatically-> There are multiple ways.

    1. copy to /lib/modules/`uname -r`/kernel/modulename.ko and update /etc/modules. System will load the module while booting.

    2. Write a script/command to load the module.ko for an specific harware add/change/remove event in a udev rule /etc/udev/rules.d/10-local.rules. You can do both load/unload using this method.

    3. Code your module with MODULE_DEVICE_TABLE registration. Then load your modulename.ko once and run depmod command [sudo depmod -a] to add the new module to /lib/modules/3.16.0-34-generic/modules.alias /lib/modules/3.16.0-34-generic/modules.dep files. As I know, system will load only if the module is not loaded.

You can monitor module loading/unloading using udev events using :

udevadm monitor

command.