When the kernel detects a new device, it runs the program modprobe
and passes it a name that identifies the device. Most devices are identified through registered numbers for a vendor and model, e.g. PCI or USB identifiers. The modprobe
program consults the module alias table /lib/modules/VERSION/modules.alias
to find the name of the file that contains the driver for that particular device. A similar principle applies to drivers for things that are not hardware devices, such as filesystems and cryptographic algorithms. For more details, see Debian does not detect serial PCI card after reboot
Once modprobe has identified which module file (.ko
) contains the requested driver, it loads the module file into the kernel: the module code is dynamically loaded into the kernel. If the module is loaded successfully, it will then appear in the listing from lsmod
.
The automatic loading of modules happen when the kernel detects new hotpluggable hardware, e.g. when you connect a USB peripheral. The operating system also does a pass of enumerating all the hardware that's present on the system early during startup, in order to load drivers for peripherals that are present at boot time.
It's also possible to manually request the loading of a module with the modprobe
or insmod
command. Most distributions include a startup script that loads the modules listed in /etc/modules
. Another way for modules to be loaded is if they're a dependency of a module: if module A depends on module B, then modprobe A
loads B before loading A.
Once a module is loaded, it remains loaded until explicitly unloaded, even if all devices using that driver have been disconnected. A long time ago, there was a mechanism to automatically unload unused modules, but it was removed, if I remember correctly, when udev came onto the scene. I suspect that automatic module unloading is not a common feature because the systems that would tend to need it are mostly desktop PCs that have lots of memory anyway (on the scale of driver code).