Linux Kernel – How Device Major and Minor Numbers Are Determined

driverslinux-kerneludev

As far as I know, the kernel detects hardware, adds information to sysfs creates a device in /dev and then generates a udev event. My question is, do device drivers do all of this or it is the kernel itself? If drivers do it, then they would know the device major and minor number to create the file in devtmps.

I also understand (maybe wrongly) that it is udev who calls modprobe to load the drivers that handle a device.

I was told that they do so with the contents of the MODALIAS uevent environment variable, thus loading all modules whose aliases match this string (the correct driver). In short: what are the steps of hardware detection in linux and WHO performs each step: the kernel itself, the driver inside the kernel or udev in userspace. Thanks.

Best Answer

The kernel knows device numbers because it decides device numbers. Each driver registers the device numbers that it manages. The numbers are either hard-coded in the source code, or, in some cases, allocated dynamically. The sysfs filesystem allows applications such as udev to discover the devices supported by the kernel. See How does udev get device numbers for the devices it creates? for more details.

The driver's initialization code probes for the hardware, and registers devices based on what hardware it found during probing. Some types of hardware don't support probing; for example, the ISA bus (a largely outdated bus on PC-type computers) provides no way to list connected hardware, so the driver can only try to communicate and pray that there isn't a different peripheral attached at the same address. On some platforms, the bootloader includes a device tree describing the available peripherals and where they are mapped, and the Linux kernel activates drivers based on this information. There are three ways a driver may be loaded for a peripheral.

  • The driver may be included as part of the kernel image.
  • The driver may be compiled as a module, and loaded explicitly (e.g. by including it in /etc/modules or in an initramfs).
  • There is a mechanism for automatically loading certain drivers based on information reported by bus types that can list connected peripherals together with a universal identification number, such as PCI (the main bus in modern PC) and USB. The kernel runs modprobe and passes it a symbolic name that encodes the peripheral's identification, which is an alias for the “real” name of the driver module. See Are driver modules loaded and unloaded automatically?
Related Question