CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 4 of 7 · 2 min read

Drivers

Think of a universal remote control with the same buttons for every television. Behind the buttons, the code for each make is different. The analogy stops in one place: a remote has a fixed set of buttons, and a driver can also offer special commands through ioctl.

In plain words: A device driver is kernel code that knows one kind of device. It offers the kernel a fixed set of operations, such as open, read, write, close and ioctl (a catch-all call for device-specific commands). The kernel and the programs use only those operations, so a program can read a file, a pipe or a terminal with the same read call. A driver has two parts. The top half runs when a program calls it, and it starts the device. The bottom half runs at an interrupt, and it must be quick. Heavier work after an interrupt is put off to a later time, to keep interrupts short.

A worked example. A program that copies standard input to standard output, cat, works for a file, a pipe or a keyboard, because each of them answers read and write. The same program can run as cat /dev/zero | head -c 10 | od -c, and it needs no change. The driver of each device supplies its own code behind the same calls.

The key lines. The uniform interface has a price. Some devices do not fit it well, such as a graphics card or a sound card, and they use ioctl or their own libraries. Also, a driver runs in kernel mode (Level 0, page 2), so a bug in a driver can crash the machine. This is one reason why microkernels run drivers outside the kernel.

Device driver

A device driver is the part of the OS that knows how to operate one kind of device. It converts the standard operations of the kernel, such as read and write, into commands for the controller, and it handles the interrupts of that device.

Example: the virtblk driver turns block requests into commands for a virtual disk.

Interview angle

A common question is "What is a device driver, and why can a driver bug crash the system?" A good answer says that drivers run in kernel mode in most systems, so they share the address space of the kernel and can overwrite its data. Microkernels move drivers to user mode for this reason.

Check yourself: 1. Why can cat read a file and a terminal with the same code? 2. What is ioctl for? 3. Why must the bottom half of a driver be quick?