TExcelTAD
Home › Operating Systems: Linux & Windows › Kernel Modules & Drivers

Kernel Modules & Drivers

The Linux kernel source contains drivers for tens of thousands of devices: network cards, GPUs, sound chips, webcams, file systems, USB gadgets. Building all of them into one kernel image would make it huge and slow to boot, and most of them would never be used on a given machine. Instead, distributions build most drivers as loadable kernel modules: separate .ko ("kernel object") files that are loaded into the running kernel only when matching hardware or a feature is needed, and can be unloaded again.

A loaded module is not a separate process. It is code linked into the kernel's address space, running in kernel mode with full privileges. A bug in a module can crash the whole system, which is why Linux remains a monolithic kernel even though it is modular (compare Kernel Designs).

Where modules live

text
/lib/modules/6.8.0-45-generic/          one directory per installed kernel version
├── kernel/
│   ├── drivers/net/ethernet/intel/e1000e/e1000e.ko.zst
│   ├── drivers/gpu/drm/i915/i915.ko.zst
│   ├── fs/btrfs/btrfs.ko.zst
│   └── net/bluetooth/bluetooth.ko.zst
├── updates/dkms/nvidia.ko.zst          modules built outside the kernel tree
├── modules.dep                         which module needs which (generated by depmod)
├── modules.alias                       hardware IDs -> module name
└── modules.builtin                     drivers compiled into the kernel image itself

Modules must match the kernel exactly: a module built for 6.8.0-45 will not load into 6.8.0-41, because the kernel's internal interfaces are not stable between builds. That is why /lib/modules has one directory per kernel and why every kernel update brings its own set. (The sandbox is a container, so it has no /lib/modules at all: its "kernel" is the host's.)

Working with modules

These commands need a real machine and mostly root, so here is a sample session (yours will differ):

bash
ada@ubuntu:~$ lsmod | head -n 6
Module                  Size  Used by
btrfs                2015232  1
xor                    20480  1 btrfs
raid6_pq              122880  1 btrfs
snd_hda_intel          61440  3
snd_hda_codec         204800  2 snd_hda_intel,snd_hda_codec_realtek
ada@ubuntu:~$ modinfo e1000e | grep -E '^(filename|description|license|depends|alias)' | head -n 6
filename:       /lib/modules/6.8.0-45-generic/kernel/drivers/net/ethernet/intel/e1000e/e1000e.ko.zst
description:    Intel(R) PRO/1000 Network Driver
license:        GPL v2
alias:          pci:v00008086d0000550Fsv*sd*bc*sc*i*
alias:          pci:v00008086d0000550Esv*sd*bc*sc*i*
depends:
ada@ubuntu:~$ sudo modprobe vfat          # load it plus everything it depends on
ada@ubuntu:~$ sudo modprobe -r vfat       # unload it, and dependencies nobody else uses
ada@ubuntu:~$ sudo dmesg | tail -n 2
[ 8823.104512] e1000e 0000:00:1f.6 eth0: NIC Link is Up 1000 Mbps Full Duplex, Flow Control: Rx/Tx
[ 8823.104580] IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
Command Does
lsmod List loaded modules (a formatted /proc/modules)
modinfo NAME Show a module's file, description, parameters, dependencies, aliases
modprobe NAME Load a module with its dependencies, using modules.dep
modprobe -r NAME Unload it and unused dependencies
insmod file.ko / rmmod NAME Low-level load/unload of one file, no dependency handling
depmod -a Regenerate modules.dep and modules.alias
lspci -k, lsusb -t Which driver is bound to each PCI / USB device

lsmod's "Used by" column is a reference count: a module cannot be unloaded while something uses it. Because lsmod output is plain text, it is easy to analyse with the usual tools. This script finds modules that others depend on:

bash · try it yourself
cat > lsmod.txt <<'EOF'
Module                  Size  Used by
vfat                   24576  1
fat                   102400  1 vfat
btrfs                2015232  1
xor                    20480  1 btrfs
raid6_pq              122880  1 btrfs
snd_hda_codec_realtek 192512  1
snd_hda_codec         204800  2 snd_hda_intel,snd_hda_codec_realtek
snd_hda_intel          61440  3
EOF
awk 'NR > 1 && $4 != "" { printf "%-14s needed by %s\n", $1, $4 }' lsmod.txt
awk 'NR > 1 { kb += $2 / 1024 } END { printf "total: %d modules, %.0f KiB\n", NR - 1, kb }' lsmod.txt
fat            needed by vfat
xor            needed by btrfs
raid6_pq       needed by btrfs
snd_hda_codec  needed by snd_hda_intel,snd_hda_codec_realtek
total: 8 modules, 2680 KiB

How modprobe resolves dependencies

modules.dep lists, for each module, the modules that must be loaded first. modprobe loads them depth-first so each module finds the symbols it needs already in the kernel, and on removal it walks the same graph backwards, skipping anything still in use:

python · try it yourself
deps = {          # a slice of modules.dep (paths shortened)
    "vfat":     ["fat"],
    "fat":      [],
    "btrfs":    ["xor", "raid6_pq", "libcrc32c"],
    "xor":      [],
    "raid6_pq": [],
    "libcrc32c": [],
    "nf_tables": ["libcrc32c"],
}
loaded = {}       # name -> reference count (how many loaded modules use it)

def modprobe(name, depth=0):
    if name in loaded:
        return
    for d in deps[name]:
        modprobe(d, depth + 1)
        loaded[d] += 1
    loaded[name] = 0
    print("  " * depth + f"insmod {name}")

def modprobe_r(name):
    if loaded[name] > 0:
        print(f"rmmod {name}: ERROR: Module {name} is in use")
        return
    del loaded[name]
    print(f"rmmod {name}")
    for d in deps[name]:
        loaded[d] -= 1
        if loaded[d] == 0:
            modprobe_r(d)
        else:
            print(f"  keep {d} (still used by {loaded[d]})")

modprobe("btrfs")
modprobe("nf_tables")
print("loaded:", loaded)
modprobe_r("libcrc32c")
modprobe_r("btrfs")
print("loaded:", loaded)
  insmod xor
  insmod raid6_pq
  insmod libcrc32c
insmod btrfs
insmod nf_tables
loaded: {'xor': 1, 'raid6_pq': 1, 'libcrc32c': 2, 'btrfs': 0, 'nf_tables': 0}
rmmod libcrc32c: ERROR: Module libcrc32c is in use
rmmod btrfs
rmmod xor
rmmod raid6_pq
  keep libcrc32c (still used by 1)
loaded: {'libcrc32c': 1, 'nf_tables': 0}

How the right driver gets loaded automatically

You rarely type modprobe yourself. When the kernel discovers a device (at boot, or when you plug in a USB stick), it publishes a modalias string built from the device's IDs, for example pci:v00008086d0000550F… (vendor 8086 = Intel, device 550F). The udev daemon receives that event and runs modprobe <modalias>; modprobe looks the string up in modules.alias, whose entries are wildcard patterns, and loads the module that matches:

python · try it yourself
from fnmatch import fnmatch

modules_alias = [                       # pattern -> module (simplified modules.alias)
    ("pci:v00008086d0000550F*", "e1000e"),
    ("pci:v000010DEd*bc03*", "nouveau"),
    ("usb:v046Dp085E*", "uvcvideo"),
    ("usb:v*p*d*dc*dsc*dp*ic08isc06ip50*", "usb_storage"),
    ("fs-vfat", "vfat"),
]

def udev_event(modalias):
    for pattern, module in modules_alias:
        if fnmatch(modalias, pattern):
            return f"{modalias[:40]:42} -> modprobe {module}"
    return f"{modalias[:40]:42} -> no driver found"

events = [
    "pci:v00008086d0000550Fsv000017AAsd00002257bc02sc00i00",   # Intel Ethernet
    "pci:v000010DEd00002882sv00001458sd00004166bc03sc00i00",   # NVIDIA GPU (class 03 = display)
    "usb:v0781p5583d0100dc00dsc00dp00ic08isc06ip50in00",       # SanDisk USB stick
    "usb:v1234p5678d0100dcFFdscFFdpFFicFFiscFFipFFin00",       # vendor-specific gadget
    "fs-vfat",                                                 # mount -t vfat asked for a file system
]
for e in events:
    print(udev_event(e))
pci:v00008086d0000550Fsv000017AAsd000022   -> modprobe e1000e
pci:v000010DEd00002882sv00001458sd000041   -> modprobe nouveau
usb:v0781p5583d0100dc00dsc00dp00ic08isc0   -> modprobe usb_storage
usb:v1234p5678d0100dcFFdscFFdpFFicFFiscF   -> no driver found
fs-vfat                                    -> modprobe vfat

The USB stick is matched not by its vendor but by its interface class (ic08 = mass storage, isc06 = SCSI commands, ip50 = bulk-only transport), so one driver handles every brand. The last line shows that even mounting a FAT file system can trigger module loading.

Configuring and blocking modules

File Purpose Example line
/etc/modules-load.d/*.conf Load at every boot br_netfilter
/etc/modprobe.d/*.conf Options, aliases, blacklists options snd_hda_intel power_save=1
Prevent auto-loading blacklist nouveau
Forbid loading completely install pcspkr /bin/false
/sys/module/<name>/parameters/ Current parameter values of a loaded module cat …/power_save

After blacklisting a driver that the initramfs also contains (typical for nouveau when installing NVIDIA's driver), rebuild the initramfs (update-initramfs -u or dracut --force), or it will still load early in boot (The Linux Boot Process).

Out-of-tree modules, DKMS and signing

Drivers that are not part of the official kernel (NVIDIA's proprietary driver, VirtualBox, some Wi-Fi chips, ZFS) must be compiled against each new kernel. DKMS (Dynamic Kernel Module Support) automates that: it keeps the driver's source and rebuilds it whenever a kernel package is installed (sample session):

bash
ada@ubuntu:~$ dkms status
nvidia/550.120, 6.8.0-45-generic, x86_64: installed
virtualbox/7.0.16, 6.8.0-45-generic, x86_64: installed

With Secure Boot on, the kernel only accepts signed modules, so DKMS signs them with a Machine Owner Key that you enrol once. A non-GPL or unsigned module also sets a taint flag (/proc/sys/kernel/tainted), which tells kernel developers that a bug report may involve code they cannot see.

Drivers on Windows

Windows uses the same idea: drivers are .sys files in C:\Windows\System32\drivers, loaded into kernel mode. Each comes with an .inf file that lists the hardware IDs it supports (the equivalent of modules.alias), and the Plug and Play manager matches devices to drivers like udev does. Since 64-bit Windows Vista, kernel drivers must be signed (since Windows 10, by Microsoft itself), which is stricter than Linux's default (sample session):

cmd
C:\Users\ada>driverquery /fo table | findstr /i "e1d nvlddmkm usbstor"
e1dexpress   Intel(R) Gigabit Ethernet  Kernel        3/14/2024 9:12:44 AM
nvlddmkm     nvlddmkm                   Kernel        9/18/2024 4:05:12 PM
USBSTOR      USB Mass Storage Driver    Kernel        4/1/2024 12:00:00 AM

C:\Users\ada>pnputil /enum-drivers /class Display
Published Name:     oem42.inf
Original Name:      nv_dispi.inf
Provider Name:      NVIDIA
Class Name:         Display adapters
Driver Version:     09/18/2024 32.0.15.6094
Signer Name:        Microsoft Windows Hardware Compatibility Publisher
Linux Windows
Driver file .ko in /lib/modules/<version>/ .sys in System32\drivers
Hardware ID matching modules.alias + udev .inf files + Plug and Play manager
List loaded lsmod driverquery, Device Manager
Load / unload modprobe, modprobe -r Automatic; pnputil /add-driver, sc start/stop for some
Signing Required only with Secure Boot / lockdown Required on 64-bit Windows
Rebuild on kernel update Yes (DKMS) No: a stable driver ABI per Windows version
User-mode drivers FUSE, UIO, libusb UMDF (printers, many USB devices)

That last line matters for stability: when a driver can run in user mode (a FUSE file system such as sshfs, a UMDF printer driver), its crash kills only its own process, not the system.

Learn more: Linux Architecture · Devices & I/O · /proc & /sys

Test yourself

What is the difference between insmod and modprobe?

  1. None
  2. modprobe also loads the module's dependencies using modules.dep; insmod loads exactly one file
  3. insmod is for Windows
  4. modprobe only lists modules

Why does a module built for kernel 6.8.0-41 fail to load into 6.8.0-45?

  1. Modules expire
  2. The kernel's internal interfaces are not stable between builds, so modules must match the exact kernel
  3. Only one module may be loaded per version
  4. Secure Boot forbids old modules

When you plug in a USB stick, how does Linux pick the usb_storage driver?

  1. The user runs modprobe
  2. udev receives the device's modalias and modprobe matches it against patterns in modules.alias
  3. The stick contains the driver
  4. The kernel tries every driver