ENع
←Device drivers
Lesson 48 · I/O, virtualisation and isolation

Device drivers and the I/O stack

14 min12 steps5 questionsAdvanced
About this lesson

When a program calls read(), nothing in it knows what kind of disk the bytes are on. The request goes down a stack of kernel layers: the file system turns a file and an offset into a disk block, the block layer queues the request, and the device driver, the only code that knows this device, writes its registers. Then the program sleeps, the SSD copies the block into memory by itself with DMA, and an interrupt brings the answer back up. Follow one 4096-byte read from a C program all the way down and back. The Hardware lesson Interrupts and I/O: how devices get the CPU's attention covers polling, interrupts and DMA from the hardware side, System calls: crossing into the kernel shows how read() enters the kernel, and File systems on SSDs shows what sits just above the block layer.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 48 · Interactive
01 / 12

A stack of layers

A program never talks to a disk. Its read() goes down a stack of kernel layers: the file system, the block layer, then the device driver. Each layer talks only to the one below it, and only the driver touches the device.

user      your program        read(fd, buf, 4096)
--------- system call -----------------------------
kernel    file system (VFS)   files and offsets
          block layer         block requests, queues
          device driver       this device's registers
--------- hardware --------------------------------
device    SSD controller      does the work, then interrupts
Loading figure…
or ← →
Read the lesson step by step
  1. A stack of layers

    A program never talks to a disk. Its read() goes down a stack of kernel layers: the file system, the block layer, then the device driver. Each layer talks only to the one below it, and only the driver touches the device.

    user      your program        read(fd, buf, 4096)
    --------- system call -----------------------------
    kernel    file system (VFS)   files and offsets
              block layer         block requests, queues
              device driver       this device's registers
    --------- hardware --------------------------------
    device    SSD controller      does the work, then interrupts
  2. What a driver is

    A device driver is the kernel code that knows one kind of device. It writes the device's registers to give orders and handles its interrupts. Above it, the kernel uses one standard interface for every disk.

    a driver (MIT xv6 book, ch. 5):
      configures the device hardware
      tells the device to perform operations
      handles the resulting interrupts
      interacts with processes waiting for I/O
    
    canonical device registers (OSTEP ch. 36):
      STATUS   is it busy or done?
      COMMAND  what to do
      DATA     data in or out (or, with DMA, where in RAM)
    
    in Linux, over 70% of the code is drivers (OSTEP)
  3. Line 1: open the file

    open() is a system call. The file system looks up the name a.txt, checks you may read it, and gives back a small number, the file descriptor. 0, 1 and 2 are taken, so it returns 3.

    the whole program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <fcntl.h>
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void) {
        static char buf[4096];
        int fd;
        ssize_t n;
        fd = open("a.txt", O_RDONLY);
        n = read(fd, buf, 4096);
        printf("%d %zd\n", fd, n);
        close(fd);
        return 0;
    }
    
    line 1   fd = open("a.txt", O_RDONLY);
             fd = 3   (0, 1, 2 = stdin, stdout, stderr)
  4. Line 2: read, cache miss

    read() traps into the kernel, asking for 4096 bytes. The file system first checks the page cache, kernel memory holding recently read blocks. This part of a.txt is not there yet: a miss. It has to come from the device.

    line 2   n = read(fd, buf, 4096);
    ask      fd 3, offset 0, 4096 bytes
    page cache   lookup ... not there (miss)
                 (a later read of the same bytes would hit
                  and never reach the device)
  5. From file to block

    The file system knows where files live on the disk. Byte 0 of a.txt is in block 8200, so it asks the block layer for that block, 4096 bytes. From here down, nobody knows about files.

    file     a.txt, bytes 0 .. 4095
    block    8200   (example number; 4096 bytes = 8 sectors of 512)
    request  read block 8200 into a page of the page cache
    
    Linux: the page cache calls the file system's
           read_folio / readahead, which builds a bio
  6. The block layer queues it

    The block layer works for every disk the same way. It puts the request in a queue, may merge it with neighbouring blocks or reorder it, then hands it to the driver for this SSD.

    Linux blk-mq:
      bio -> request, into a per-CPU staging queue
      may merge adjacent sectors, may be reordered
      by an I/O scheduler (or not: "none")
      -> hardware dispatch queue
      -> driver's queue_rq(request), with a tag
  7. The driver gives orders

    Only the driver knows this device's registers. It writes the block number 8200 and the RAM address to copy into, then one final write, READ, tells the device to start.

    driver writes the device registers:
      BLOCK  = 8200
      ADDR   = the page cache page in RAM
      CMD    = READ        <- this write starts the device
    
    writes are privileged: only the kernel may do them
    (port I/O instructions or memory-mapped registers)
  8. Sleep, not spin

    The device needs time. Instead of checking it over and over (polling), the kernel puts your program to sleep and lets the CPU run another program meanwhile.

    polling      CPU asks "done yet?" in a loop: wasted
    interrupts   program sleeps (blocked), CPU runs others
    
    CPU   1 1 1 2 2 2 2 2 2 1 1     (OSTEP timeline)
    SSD         1 1 1 1 1
    1 = your program, 2 = the other program
  9. DMA: the device copies

    The SSD reads block 8200 from its flash and copies the 4096 bytes straight into the page cache in RAM. This is direct memory access, DMA: the CPU does not move a single byte.

    device   reads block 8200 from flash
    DMA      4096 bytes -> RAM at ADDR (the page cache)
    CPU      still running the other program
    
    without DMA (programmed I/O) the CPU would copy
    every word itself
  10. The interrupt

    Done, the SSD raises an interrupt. The CPU pauses the other program and jumps to the driver's interrupt handler. It checks the status, marks the request complete and wakes your sleeping program.

    device   STATUS = DONE, raises its interrupt line
    CPU      traps to the kernel, calls the driver's handler
    handler  reads STATUS: ok
             completes the request (by its tag)
             wakes the process waiting for it
    
    top half    the read() path that started the I/O
    bottom half the handler that finishes it
  11. Copy out and return

    When your program runs again, the kernel copies the 4096 bytes from the page cache into buf, in the program's own memory. read() returns 4096, the number of bytes read.

    copy     page cache -> buf   4096 bytes
    return   n = 4096   (read returns the bytes read)
    
    compiled and run with a 4096-byte a.txt, prints:
    3 4096
  12. Why layers?

    Read it again and the page cache answers: the device is never touched. Because each layer hides the one below, the same read() works on any disk, and a new device needs only a new driver.

    the stack as a Python simulation:
    
    disk = {8200: bytes(4096)}       # the device's storage
    cache = {}                       # page cache: block -> data
    regs = {}                        # the device's registers
    
    def device_start():              # the device works alone
        cache[regs["BLOCK"]] = disk[regs["BLOCK"]]   # DMA
        interrupt()
    
    def interrupt():                 # driver, at interrupt time
        print("irq: block", regs["BLOCK"], "done")
    
    def driver(block):               # only code that knows regs
        regs["BLOCK"] = block
        regs["CMD"] = "READ"         # this write starts it
        device_start()
    
    def file_system(offset):
        block = 8200 + offset // 4096
        if block not in cache:
            print("miss: block", block)
            driver(block)            # via the block layer
        return cache[block]
    
    def read(count):                 # the system call
        return len(file_system(0)[:count])
    
    print("read returned", read(4096))
    print("again:", read(4096))
    
    prints:
    miss: block 8200
    irq: block 8200 done
    read returned 4096
    again: 4096

Quiz Unlocks after the last step.