Lesson 8 · Files, storage, I/O, and protection

Device Drivers

A device driver is the code that turns the kernel's generic requests, such as read 4 KB, into the register writes one particular device understands, and handles the device's interrupts when the work is done.

Device Drivers concept diagramA visual explanation of the layout and operations shown in this lesson.a driver turns one generic call into register writes for one specific deviceapplicationread(fd, buf, 4096)system calluser → kernel transitionVFSdispatch via f_op->readblock layercache, merge, scheduledevice driverLBA, DMA, doorbellhardwarecontroller + flashprivilege boundaryDMA moves the bytes without the CPU · one interrupt signals completion · the top half must stay short
1

What a Device Driver Does

Device drivers are the part of the operating system that knows how one kind of hardware works. A device driver sits between the kernel's general interfaces and the device. The file-system code calls read the same way for a hard disk, an SSD or a USB stick; the driver turns that call into what its particular controller expects.

The connection is a table of function pointers. A Linux character driver fills in a file_operations structure with its own open, read, write and ioctl functions and registers it; the kernel then calls through the table. This is why a driver written years after a kernel can still be loaded into it.

  • Above the driver: one interface for every device of a kind
  • Below the driver: registers, interrupts, the device's datasheet
2

How Device Drivers Work: One Read

  1. VFS finds fd's device file and calls through its function table
  2. The block layer checks the page cache, then turns bytes into sectors: 8192 / 512 = sector 16, 4096 / 512 = 8 sectors
  3. The driver writes the start sector, count and buffer address to the controller's registers, then a read command, which starts the disk
  4. The calling process sleeps and the CPU runs other work
  5. The disk fills the buffer and raises an interrupt; the handler acknowledges it and marks the request done
  6. The process wakes, the data is copied to its buffer, and read() returns 4096

Follow read(fd, buf, 4096) on a disk at file offset 8192. The app knows nothing about the hardware; each layer below hides the one under it.

  • Registers are memory-mapped: a store to that address is a command
  • Swap the disk for an NVMe SSD and only the driver changes
3

Types of Device Drivers

The main types of device drivers follow how the device is used, and each type sits under a different part of the kernel.

Block, character and network drivers
BlockCharacterNetwork
Data unitFixed-size blocks (sectors)A stream of bytesPackets
Random accessYesUsually noNo
Layer above itPage cache, block layer, I/O schedulerVFS directlyNetwork stack
Device file/dev/sda, /dev/nvme0n1/dev/ttyS0, /dev/input/*None (eth0 is an interface)
ExamplesDisks, SSDs, USB storageSerial ports, keyboards, /dev/randomEthernet, Wi-Fi
  • Kernel-mode drivers: most drivers in Linux and Windows
  • User-mode drivers: FUSE file systems, VFIO devices, microkernel drivers
Implementation

One read() through a device driver

SECTOR = 512


class DiskDriver:
    def __init__(self):
        self.registers = {}
        self.pending = False

    def submit(self, lba, count):
        self.registers.update(LBA=lba, COUNT=count)
        self.registers["COMMAND"] = "READ"  # this write starts the device
        self.pending = True

    def interrupt(self, acknowledge=True):
        if acknowledge:
            self.pending = False
        return self.registers["COUNT"] * SECTOR


class SerialDriver:
    def __init__(self, arrived):
        self.arrived = arrived

    def read(self, length):
        data, self.arrived = self.arrived[:length], self.arrived[length:]
        return len(data)


def block_read(driver, offset, length):
    lba, count = offset // SECTOR, length // SECTOR
    driver.submit(lba, count)
    print(f"block layer: offset {offset} -> sector {lba}, {count} sectors")
    print("registers:", " ".join(f"{k}={v}" for k, v in driver.registers.items()))
    return driver.interrupt()


disk = DiskDriver()
table = {"/dev/sda": lambda n: block_read(disk, 8192, n), "/dev/ttyS0": SerialDriver(b"hello").read}

print(f"read(/dev/sda, 4096) = {table['/dev/sda'](4096)}")
print(f"read(/dev/ttyS0, 4096) = {table['/dev/ttyS0'](4096)} (only the bytes that arrived)")

disk.submit(16, 8)
storm = 0
while disk.pending and storm < 100000:
    disk.interrupt(acknowledge=False)
    storm += 1
print(f"handler never acknowledges: {storm} interrupts and still pending")
#include <cstdio>
#include <functional>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;

const int SECTOR = 512;

struct DiskDriver {
    vector<pair<string, string>> registers;
    int count = 0;
    bool pending = false;
    void submit(int lba, int n) {
        count = n;
        registers = {{"LBA", to_string(lba)}, {"COUNT", to_string(n)}};
        registers.push_back({"COMMAND", "READ"});  // this write starts the device
        pending = true;
    }
    int interrupt(bool acknowledge = true) {
        if (acknowledge) pending = false;
        return count * SECTOR;
    }
};

struct SerialDriver {
    string arrived;
    int read(int length) {
        string data = arrived.substr(0, length);
        arrived = arrived.substr(data.size());
        return (int)data.size();
    }
};

int blockRead(DiskDriver& d, int offset, int length) {
    int lba = offset / SECTOR, n = length / SECTOR;
    d.submit(lba, n);
    printf("block layer: offset %d -> sector %d, %d sectors\n", offset, lba, n);
    printf("registers:");
    for (auto& [k, v] : d.registers) printf(" %s=%s", k.c_str(), v.c_str());
    printf("\n");
    return d.interrupt();
}

int main() {
    DiskDriver disk;
    SerialDriver serial{"hello"};
    map<string, function<int(int)>> table = {
        {"/dev/sda", [&](int n) { return blockRead(disk, 8192, n); }},
        {"/dev/ttyS0", [&](int n) { return serial.read(n); }},
    };
    int a = table["/dev/sda"](4096);
    printf("read(/dev/sda, 4096) = %d\n", a);
    int b = table["/dev/ttyS0"](4096);
    printf("read(/dev/ttyS0, 4096) = %d (only the bytes that arrived)\n", b);

    disk.submit(16, 8);
    int storm = 0;
    while (disk.pending && storm < 100000) { disk.interrupt(false); storm++; }
    printf("handler never acknowledges: %d interrupts and still pending\n", storm);
}
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.IntUnaryOperator;

public class Main {
    static final int SECTOR = 512;

    static class DiskDriver {
        Map<String, String> registers = new LinkedHashMap<>();
        int count = 0;
        boolean pending = false;

        void submit(int lba, int n) {
            count = n;
            registers.clear();
            registers.put("LBA", String.valueOf(lba));
            registers.put("COUNT", String.valueOf(n));
            registers.put("COMMAND", "READ");  // this write starts the device
            pending = true;
        }

        int interrupt(boolean acknowledge) {
            if (acknowledge) pending = false;
            return count * SECTOR;
        }
    }

    static class SerialDriver {
        String arrived;
        SerialDriver(String arrived) { this.arrived = arrived; }

        int read(int length) {
            String data = arrived.substring(0, Math.min(length, arrived.length()));
            arrived = arrived.substring(data.length());
            return data.length();
        }
    }

    static int blockRead(DiskDriver d, int offset, int length) {
        int lba = offset / SECTOR, n = length / SECTOR;
        d.submit(lba, n);
        System.out.println("block layer: offset " + offset + " -> sector " + lba + ", " + n + " sectors");
        StringBuilder sb = new StringBuilder("registers:");
        d.registers.forEach((k, v) -> sb.append(" ").append(k).append("=").append(v));
        System.out.println(sb);
        return d.interrupt(true);
    }

    public static void main(String[] args) {
        DiskDriver disk = new DiskDriver();
        SerialDriver serial = new SerialDriver("hello");
        Map<String, IntUnaryOperator> table = new LinkedHashMap<>();
        table.put("/dev/sda", n -> blockRead(disk, 8192, n));
        table.put("/dev/ttyS0", serial::read);
        int a = table.get("/dev/sda").applyAsInt(4096);
        System.out.println("read(/dev/sda, 4096) = " + a);
        int b = table.get("/dev/ttyS0").applyAsInt(4096);
        System.out.println("read(/dev/ttyS0, 4096) = " + b + " (only the bytes that arrived)");

        disk.submit(16, 8);
        int storm = 0;
        while (disk.pending && storm < 100000) { disk.interrupt(false); storm++; }
        System.out.println("handler never acknowledges: " + storm + " interrupts and still pending");
    }
}
Watch it run

Step through it

Running on read(fd, buf, 4096) on /dev/sda at offset 8192

read(fd, buf, 4096) at offset 8192appVFSblock layerdisk driverATA diskuserkernelhardwarewhat the app knowsfd 3 is open on /dev/sdait wants bytes 8192 to 12287nothing about sectors, registers or interruptsone call for every device
Step 1

The app asks for 4 KB

The program calls read(fd, buf, 4096) with the file position at byte 8192. It does not know whether fd is a SATA disk, an SSD, a USB stick or a serial port. Hiding that difference is the reason drivers exist: the same call works for every device that has one.

Output
1 / 10
4

Polling, Interrupts and Bulk Transfers

A driver can wait for a device in two ways. Polling reads a status register in a loop until the device is ready; at one read per microsecond, a 5 ms disk read wastes about 5,000 reads and a whole CPU. Interrupts let the process sleep until the device signals completion, which is the normal choice; the details are in interrupts in OS.

Interrupt handlers run with other work held off, so drivers split them: a short top half acknowledges the device and records the result, and a bottom half (softirq, tasklet or workqueue in Linux) does the rest later. For bulk data, the controller copies blocks into memory itself and interrupts once at the end, covered in disk scheduling and I/O. The driver must then make sure the CPU's cache does not hold stale copies of that memory.

Polling still wins when the device answers faster than an interrupt can be handled. Very fast NVMe drives under heavy load and DPDK network stacks poll on purpose.

  • Polling: simple, wastes the CPU on slow devices
  • Interrupts: the CPU is free while the device works
  • Top half short, bottom half deferred
5

Where Drivers Go Wrong

Drivers hold more bugs than any other kernel code. Studies starting with Chou and colleagues in 2001 found error rates in Linux drivers three to seven times higher than in the rest of the kernel, and in a monolithic kernel a driver bug runs with full privilege. A handler that forgets to acknowledge a level-triggered interrupt makes the CPU take the same interrupt again and again; Linux disables a line after 99,900 of 100,000 interrupts on it go unhandled and logs "irq N: nobody cared".

The fixes move drivers away from full privilege or make bugs harder to write. Microkernels run every driver as a user process. Linux offers FUSE for file systems in user space and VFIO, which gives a user process a device while the IOMMU stops that device from writing outside its allowed memory. Rust is now accepted for new drivers in both Linux and Windows.

  • Driver bugs: several times the kernel average
  • User-space options: FUSE, VFIO, microkernel drivers