Devices & I/O
The CPU is fast; disks, network cards, keyboards and GPUs work at their own pace. A large part of any operating system exists to talk to these devices efficiently and safely: drivers, interrupts, DMA, buffering, and a uniform interface so that a program can write to an SSD, a USB stick or a network share with the same calls. This lesson covers how that works, and how Linux and Windows organise it.
How the CPU talks to a device
A device is controlled through its registers: a status register (busy? done? error?), a command register and data registers. The CPU reaches them either through special I/O instructions (in/out on x86, port-mapped I/O) or, almost always today, through ordinary memory addresses that are wired to the device (memory-mapped I/O, MMIO). PCI Express devices expose their registers in MMIO regions called BARs.
There are three ways to move data and learn when an operation is done:
| Technique | How it works | Good for |
|---|---|---|
| Polling (programmed I/O) | the CPU repeatedly reads the status register until "done", then copies each word itself | very fast devices with tiny latency (NVMe and network busy polling), or early boot |
| Interrupts | the device raises an interrupt when it needs attention; the CPU does other work meanwhile | keyboards, mice, timers, anything slow or rare |
| DMA (direct memory access) | the driver gives the device a memory address and length; the device copies the whole buffer itself and interrupts once at the end | disks, SSDs, network cards, GPUs: all bulk data |
This model compares the CPU time spent reading a 64 KiB block with each technique (the costs per step are illustrative):
BLOCK = 64 * 1024 # bytes to read
WORD = 4 # bytes moved per programmed I/O read
DEVICE_US = 200 # the device needs 200 us to fetch the data
POLL_CHECK_US = 0.5 # one status-register read
COPY_WORD_US = 0.01 # CPU copies one word
INTERRUPT_US = 3 # enter handler, acknowledge, return
SETUP_DMA_US = 2 # write address/length into the device
words = BLOCK // WORD
polling = DEVICE_US + words * COPY_WORD_US # spins the whole time
interrupt = INTERRUPT_US + words * COPY_WORD_US # CPU free while waiting, then copies
dma = SETUP_DMA_US + INTERRUPT_US # device copies, one interrupt
print(f"{'technique':<20}{'CPU busy (us)':>14}{'vs polling':>12}")
for name, busy in [("polling", polling), ("interrupt + copy", interrupt), ("DMA + 1 interrupt", dma)]:
print(f"{name:<20}{busy:>14.1f}{busy / polling:>12.1%}")technique CPU busy (us) vs polling
polling 363.8 100.0%
interrupt + copy 166.8 45.9%
DMA + 1 interrupt 5.0 1.4%
With DMA the CPU spends a few microseconds instead of hundreds per block, which is why every storage and network device uses it. An IOMMU (Intel VT-d, AMD-Vi) restricts which memory each device may DMA into, so a faulty or malicious device (or one passed through to a VM) can't overwrite the kernel.
Interrupts: do the minimum, defer the rest
When an interrupt arrives, the CPU stops the current thread and jumps to the kernel's interrupt handler. Interrupts of the same or lower priority are held off while it runs, so handlers must be short. Both systems split the work in two:
| Linux | Windows | |
|---|---|---|
| Urgent part, in interrupt context | top half: the hard IRQ handler | ISR (Interrupt Service Routine) at device IRQL |
| Deferred part | bottom half: softirq, tasklet, threaded IRQ, workqueue | DPC (Deferred Procedure Call) at DISPATCH_LEVEL, work items |
| Priority scheme | IRQ lines, softirq vectors | IRQL levels (PASSIVE < APC < DISPATCH < device IRQLs < HIGH) |
Modern PCIe devices signal with MSI/MSI-X (a memory write instead of a physical wire), and a network card can have one interrupt vector per queue, spread over CPU cores.
from collections import deque
events = [(0, "nic", "packet 1"), (1, "disk", "read done"), (1, "nic", "packet 2"),
(2, "keyboard", "key 'a'"), (5, "nic", "packet 3")]
dpc_queue = deque()
log = []
for t in range(7):
for when, dev, what in events:
if when == t: # hardware raises the interrupt
log.append(f"t={t} ISR {dev:<8} ack device, queue DPC for {what}")
dpc_queue.append((dev, what))
if dpc_queue: # one deferred item per tick
dev, what = dpc_queue.popleft()
log.append(f"t={t} DPC {dev:<8} process {what}, wake waiting thread")
print("\n".join(log))
print("left in queue:", len(dpc_queue))t=0 ISR nic ack device, queue DPC for packet 1
t=0 DPC nic process packet 1, wake waiting thread
t=1 ISR disk ack device, queue DPC for read done
t=1 ISR nic ack device, queue DPC for packet 2
t=1 DPC disk process read done, wake waiting thread
t=2 ISR keyboard ack device, queue DPC for key 'a'
t=2 DPC nic process packet 2, wake waiting thread
t=3 DPC keyboard process key 'a', wake waiting thread
t=5 ISR nic ack device, queue DPC for packet 3
t=5 DPC nic process packet 3, wake waiting thread
left in queue: 0
The ISR only acknowledges the device and queues work; the slower processing (parsing a packet, completing a read) runs a moment later with interrupts enabled.
Device types and the Linux /dev
Linux sorts devices into three kinds:
- Character devices: a byte stream, no seeking required (terminals,
/dev/null, serial ports,/dev/random). - Block devices: fixed-size blocks with random access, cached by the kernel (
/dev/nvme0n1,/dev/sda). - Network interfaces: no file in
/devat all; reached through sockets (eth0,wlan0).
Each device file carries a major number (which driver) and a minor number (which instance). udev creates and names the files when devices appear. In the sandbox:
for d in /dev/null /dev/zero /dev/urandom /dev/tty; do
stat -c '%-13n %F, major %t minor %T' "$d"
done
head -c 8 /dev/zero | od -An -tx1
echo "gone" > /dev/null && echo "write to /dev/null succeeded"/dev/null character special file, major 1 minor 3
/dev/zero character special file, major 1 minor 5
/dev/urandom character special file, major 1 minor 9
/dev/tty character special file, major 5 minor 0
00 00 00 00 00 00 00 00
write to /dev/null succeeded
stat prints the numbers in hexadecimal: /dev/null is minor 3 and /dev/zero minor 5 of the mem driver (major 1). On a real machine lsblk, lspci and lsusb list the hardware (sample output — yours will differ):
ada@ubuntu:~$ lsblk -o NAME,MAJ:MIN,SIZE,TYPE,MOUNTPOINTS
NAME MAJ:MIN SIZE TYPE MOUNTPOINTS
nvme0n1 259:0 476.9G disk
├─nvme0n1p1 259:1 1G part /boot/efi
└─nvme0n1p2 259:2 475.9G part /Drivers and the Windows device stack
Windows has no /dev directory. Devices are kernel objects such as \Device\HarddiskVolume3, reached through symbolic links (C: → \Device\HarddiskVolume3). Drivers are layered into a device stack: a bus driver (PCI, USB) discovers the device, a function driver knows how to run it, and optional filter drivers sit above or below to add features (encryption, antivirus scanning, quotas). The Plug and Play manager builds these stacks as hardware appears; Device Manager (devmgmt.msc) and Get-PnpDevice show them.
Every request travels down the stack as an IRP (I/O Request Packet). Each driver may handle it, change it, or pass it to the next lower driver; on the way back up, drivers can look at the result:
stack = [
("bitlocker filter", "encrypt" ),
("volsnap filter", "copy-on-write for shadow copies"),
("partmgr/disk", "translate volume offset to disk LBA"),
("stornvme", "build NVMe command, start DMA"),
]
def send_irp(op, offset):
irp = {"op": op, "offset": offset, "trace": []}
for name, job in stack: # down the stack
irp["trace"].append(f"down {name:<17} {job}")
irp["status"] = "STATUS_SUCCESS"
for name, _ in reversed(stack): # completion routines, back up
irp["trace"].append(f"up {name:<17} completion")
return irp
irp = send_irp("IRP_MJ_WRITE", 4096)
print(irp["op"], "at offset", irp["offset"])
print("\n".join(irp["trace"]))
print(irp["status"])IRP_MJ_WRITE at offset 4096
down bitlocker filter encrypt
down volsnap filter copy-on-write for shadow copies
down partmgr/disk translate volume offset to disk LBA
down stornvme build NVMe command, start DMA
up stornvme completion
up partmgr/disk completion
up volsnap filter completion
up bitlocker filter completion
STATUS_SUCCESS
Linux block I/O follows a similar path through layers (file system → device mapper targets such as dm-crypt or LVM → the blk-mq block layer with its I/O scheduler → the NVMe driver), but passes bio structures instead of IRPs.
Buffering, caching and asynchronous I/O
Between programs and devices, both kernels keep a page cache: recently read file data stays in RAM, and writes land there first and are flushed later (fsync / FlushFileBuffers force them out). Programs can bypass it with O_DIRECT (Linux) or FILE_FLAG_NO_BUFFERING (Windows), as databases often do.
Waiting for each I/O to finish wastes threads, so both systems offer asynchronous I/O for servers:
| Linux | Windows | |
|---|---|---|
| Readiness ("can I read now?") | select, poll, epoll |
select, WSAPoll |
| Completion ("tell me when done") | io_uring (shared submission/completion rings) |
I/O completion ports (IOCP), overlapped I/O, IoRing |
| Used by | nginx, Node.js (libuv), databases | IIS, .NET, SQL Server, Node.js (libuv) |
Learn more: Kernel Modules & Drivers · The Network Stack · File System Concepts
Test yourself
Why do disks and network cards use DMA?
- It makes the device itself faster
- The device copies whole buffers to memory by itself, so the CPU only sets up the transfer and handles one interrupt
- DMA avoids the need for drivers
- DMA encrypts data
What is the Windows counterpart of a Linux interrupt *bottom half*?
- ISR
- DPC (Deferred Procedure Call)
- IRP
- MSI-X
On Linux, what do the major and minor numbers of /dev/zero identify?
- Its size and block count
- The driver (major) and the device instance (minor)
- The owner's UID and GID
- The read and write speed