9.4. Block I/O Scheduling and Control
Storage requests queue up like tasks do, and the block layer schedules that queue: it may merge adjacent requests, reorder them for the head of a spinning disk, throttle a cgroup to a fixed rate, or pass everything through untouched. Which behaviour you get depends on the device's scheduler (or lack of one), on the I/O priority attached to each request, and on the cgroup limits systemd configures. This section works those three layers in order, on a real - if virtual - disk.
The exercises write real data, so they use a second, disposable disk
attached to the example machine, /dev/vdb. Everything on it will be
destroyed; if you are following along, use any disk whose contents you do
not need. A directory on your root filesystem also works for the file-based
exercises, at the cost of the observations being entangled with real
workload. Prepare the disk - in the root shell:
# mkfs.ext4 -L io-lab /dev/vdb
mke2fs 1.47.2 (1-Jan-2025)
Discarding device blocks: 0/524288 done
Creating filesystem with 524288 4k blocks and 131072 inodes
Filesystem UUID: 9742e21e-0b5f-48b5-b86b-eaa684cfb642
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912
Allocating group tables: 0/16 done
Writing inode tables: 0/16 done
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: 0/16 done
That is mkfs.ext4 writing a fresh filesystem (Chapter 12
covers ext4 administration; Chapter 11 covers
partitioning whole disks). Mount it and make a workspace john can write to:
# mkdir -p /mnt/io-lab
# mount /dev/vdb /mnt/io-lab
# mkdir /mnt/io-lab/workspace
# chown john:john /mnt/io-lab/workspace
# findmnt /mnt/io-lab
TARGET SOURCE FSTYPE OPTIONS
/mnt/io-lab /dev/vdb ext4 rw,relatime
The first four commands produce no output; findmnt verifies the result:
/dev/vdb is mounted at /mnt/io-lab, read-write, ext4. Keep the disk
mounted for the rest of the chapter's I/O work - the D-state
demonstration in Section 9.7.1 writes to it too - and run
umount /mnt/io-lab only when all of it is finished.
9.4.1. Inspecting Block Queues and Available and Selected Schedulers
The kernel exposes each block device's queue under /sys/block/<name>/queue/,
and the most interesting file there is scheduler: it lists the schedulers
compiled or loaded for this device and marks the selected one with square
brackets. On a freshly booted system the list can be short, because Debian
builds BFQ as a module:
# modprobe bfq
# cat /sys/block/vdb/queue/scheduler
[none] mq-deadline bfq
modprobe bfq loads the BFQ module (Chapter 7 covered
module loading), and its name immediately appears in the list for every
block device - scheduler availability is per-kernel, the choice is
per-device. Here none is selected (the brackets), with mq-deadline and
now bfq as alternatives. The trailing space belongs to the file's format.
Other files in the same directory describe the queue: rotational (1 or 0),
nr_requests (queue depth), and scheduler-specific tunables under
iosched/ when a scheduler that has them is selected.
9.4.2. none, mq-deadline, BFQ, and Kyber Where Supported
The four schedulers a Debian 13 kernel can offer answer different needs:
| Scheduler | Designed for | Behaviour |
|---|---|---|
none |
Fast devices, virtual disks | No scheduling; requests pass in submission order with the least overhead. |
mq-deadline |
General use, slower devices | Keeps read and write queues with soft deadlines so no request starves; still merges and sorts. |
bfq |
Interactive systems on slow disks | Proportional share per task/cgroup with latency targets; the heaviest, most featureful option. |
kyber |
Fast NVMe under heavy load | Regulates queue depth toward latency targets; much lighter than BFQ. |
none is exactly what it says: the multi-queue block layer dispatches
requests as they arrive, which is the right default when the device itself
queues deeply (NVMe) or when another layer already does the scheduling (a
hypervisor under a virtual disk). mq-deadline keeps two sorted lists per
CPU with deadlines - reads get half a second by default, writes five - and
dispatches whichever request is closest to missing its deadline, batching
adjacent sectors along the way. BFQ treats each process (and cgroup) as a
client with a budget, giving latency guarantees to interactive tasks and
proportional bandwidth to bulk ones. Kyber, built for fast devices,
throttles dispatch to keep completion latencies bounded - its knobs are
latency targets, not budgets.
Selecting is one echo into the queue's scheduler file, with the next
cat as verification:
# echo bfq > /sys/block/vdb/queue/scheduler
# cat /sys/block/vdb/queue/scheduler
none mq-deadline [bfq]
# echo mq-deadline > /sys/block/vdb/queue/scheduler
# cat /sys/block/vdb/queue/scheduler
none [mq-deadline] bfq
The change takes effect immediately, for new requests. Kyber has one naming
trap: the scheduler is called kyber in the list, but the module providing
it is named kyber-iosched - modprobe kyber reports no module by that
name. Debian builds it as a module, like BFQ
(CONFIG_MQ_IOSCHED_KYBER=m):
# modprobe kyber-iosched
# cat /sys/block/vdb/queue/scheduler
none [mq-deadline] bfq kyber
The list gains kyber for every device, and it selects like the others:
# echo kyber > /sys/block/vdb/queue/scheduler
# cat /sys/block/vdb/queue/scheduler
none mq-deadline bfq [kyber]
Return the disk to mq-deadline and unload the module again; rmmod
refuses while a device still uses the scheduler, so switch away first:
# echo mq-deadline > /sys/block/vdb/queue/scheduler
# rmmod kyber_iosched
# cat /sys/block/vdb/queue/scheduler
none [mq-deadline] bfq
The two silent steps are the echo, which selects as before, and rmmod,
which prints nothing on success; the final cat shows the list back to
three. Kyber's description above comes from the kernel's own documentation;
its dispatch behaviour was not measured on this virtual disk - the
comparisons later in this section run on mq-deadline. Check
cat /sys/block/<dev>/queue/scheduler on your system to see what is
actually available.
9.4.3. HDD, SSD, NVMe, Device-Mapper, and Virtual-Disk Considerations
Which scheduler deserves which device? The costs that scheduling can reduce are seek time (HDDs), per-request overhead (everything), and interference between workloads (everything). Some guidance:
| Device type | Typical choice | Reason |
|---|---|---|
Spinning HDD (sd with rotational=1) |
mq-deadline or bfq |
Seek merging and request ordering pay off; BFQ additionally protects interactive latency. |
| SATA/SAS SSD | none or mq-deadline |
No seeks; deadline logic rarely adds value but costs little. |
| NVMe | none |
The device parallelism is high and the host scheduler only adds latency. |
| device-mapper (LVM, LUKS, md) | Whatever the underlying device uses | Scheduling happens on the physical device's queue; the mapper layer passes requests down. |
| Virtual guest disk (virtio) | Usually none |
The hypervisor's host already schedules the real device; guest-side scheduling duplicates work. |
Look at the example machine's inventory:
# lsblk -d -o NAME,SIZE,TYPE,ROTA /dev/vda /dev/vdb
NAME SIZE TYPE ROTA
vda 100G disk 1
vdb 2G disk 1
Both disks report ROTA 1 - "rotational" - although neither spins: virtio
disks do not report the property and the attribute defaults to 1. That is
worth knowing twice over. First, do not tune a guest as if ROTA 1 meant a
mechanical disk. Second, the same mislabeling happens elsewhere - always
check what the device actually is (lsblk --help lists more columns;
Chapter 11 covers device identification). On the
example machine both disks run none, which matches the virtual-disk row
of the table. Device-mapper stacks (Chapter 13) and
the host side of virtual disks (Chapter 24) have
their scheduling elsewhere - the guest's choice only affects the guest.
9.4.4. Changing a Scheduler Temporarily and Persisting Device-Specific Choices
The echo of the previous subsection is the temporary form: immediate, and
gone at the next reboot, because /sys is rebuilt at boot. For a choice
that sticks, make udev apply it whenever the device appears. First the
temporary form once more, as a clean baseline:
# echo mq-deadline > /sys/block/vdb/queue/scheduler
# cat /sys/block/vdb/queue/scheduler
none [mq-deadline] bfq
The persistent form is a udev rule matching the device and setting the
attribute. Create /etc/udev/rules.d/60-io-scheduler.rules with this
content:
ACTION=="add|change", KERNEL=="vdb", ATTR{queue/scheduler}="mq-deadline"
Read it as: when a block device named vdb is added or changed, set its
queue/scheduler sysfs attribute to mq-deadline. KERNEL matches the
device's name, and ATTR{...} writes into the device's sysfs entry - the
same file you wrote by hand. Load the rule and apply it without rebooting,
then prove it took effect - first reset the live value so the rule has
something to do:
# echo none > /sys/block/vdb/queue/scheduler
# udevadm control --reload
# udevadm trigger --subsystem-match=block --action=change
# sleep 1
# cat /sys/block/vdb/queue/scheduler
none [mq-deadline] bfq
udevadm control --reload makes the daemon re-read its rules; it prints
nothing. udevadm trigger --subsystem-match=block --action=change emits a
change event for every block device, which makes the new rule run against
vdb right now - the same event that would run it at boot when the device
appears. The final cat shows the rule's work: mq-deadline is selected
again. To remove the persistent choice, delete the rule and reload:
# rm /etc/udev/rules.d/60-io-scheduler.rules
# udevadm control --reload
# echo none > /sys/block/vdb/queue/scheduler
All three are silent; the last line returns the live setting to the kernel's default for the rest of the section's examples.
9.4.5. ionice Classes, Priorities, and Scheduler-Dependent Effects
The CPU side had nice values; the block side has I/O priorities, recorded
with each request. ionice sets them, with three classes:
| Class | Name | Priority data | Meaning |
|---|---|---|---|
| 1 | real-time | 0-7 | Served before everything else; needs root, starves other I/O if abused. |
| 2 | best-effort | 0-7 (0 highest) | The default class; the level orders requests within it. |
| 3 | idle | none | Served only when no other I/O is waiting. |
Ask a running process for its priority with ionice -p; the answer is one
word or class and level. Start a large direct write (see Section 9.4.7 for
what direct means) in the idle class and check it while it runs:
$ ionice -c 3 dd if=/dev/zero of=/mnt/io-lab/workspace/idle.bin bs=1M count=1024 oflag=direct status=none &
$ echo $! > ionice.pid
$ sleep 0.3
$ ionice -p $(cat ionice.pid)
idle
$ wait
The dd writes 1 GiB in 1 MiB direct-I/O requests; the background start and
PID file are silent, ionice -p prints the class - idle - and wait
blocks until the write completes. Remove the file afterwards
(rm /mnt/io-lab/workspace/idle.bin). The best-effort class takes a level:
$ ionice -c 2 -n 7 sleep 120 &
$ echo $! > ionice-be.pid
$ sleep 0.2
$ ionice -p $(cat ionice-be.pid)
best-effort: prio 7
$ kill -TERM $(cat ionice-be.pid)
Level 7 is the lowest best-effort priority, not the highest - 0 wins. Now
the caveat that makes ionice honest: a priority is only a request, and
whether it does anything depends on the scheduler serving the queue. With
none selected, the priority is recorded but unused:
# echo none > /sys/block/vdb/queue/scheduler
# cat /sys/block/vdb/queue/scheduler
[none] mq-deadline bfq
# ionice -c 3 sleep 5 &
# p=$!
# sleep 0.2
# ionice -p $p
idle
# wait
The kernel's I/O-priority documentation is explicit that support is
scheduler-dependent: BFQ implements the full model - classes, levels, and
per-task budgets derived from them; mq-deadline orders dispatch by class
(real-time before best-effort before idle) but does not distinguish the
levels within a class, and ages lower classes so they are not starved
forever; none uses none of it. Before promising a caller "your backup
will stay out of the way", check which scheduler the target disk runs.
9.4.6. Cgroup and Systemd I/O Weights, Bandwidth Limits, and IOPS Limits
Per-process priorities are advisory; cgroup limits are arithmetic. The
kernel's I/O controller enforces, per device, either a weight (relative
share under contention) or io.max caps (absolute bandwidth and
operations-per-second ceilings), and systemd maps unit properties onto
them. In the root shell:
# systemd-run --unit=handbook-io --slice=handbook.slice -p IOWeight=50 -p IOReadBandwidthMax="/dev/vdb 8M" -p IOWriteBandwidthMax="/dev/vdb 8M" -p IOReadIOPSMax="/dev/vdb 100" sleep 60
Running as unit: handbook-io.service; invocation ID: e82072ec76634ca486f436b3bff55c31
The same transient-unit pattern as Section 9.3.6, with I/O properties: the
unit gets weight 50 and, for /dev/vdb specifically, an 8 MiB/s read
ceiling, an 8 MiB/s write ceiling, and a 100 operations/s read ceiling.
Read them back:
# systemctl show handbook-io -p IOWeight -p IOReadBandwidthMax -p IOWriteBandwidthMax -p IOReadIOPSMax -p IOWriteIOPSMax
IOWeight=50
IOReadBandwidthMax=/dev/vdb 8000000
IOWriteBandwidthMax=/dev/vdb 8000000
IOReadIOPSMax=/dev/vdb 100
The values normalize to bytes per second and keep their device. The kernel
view is the cgroup's io.max file, indexed by device number:
# cat /sys/fs/cgroup/handbook.slice/handbook-io.service/io.max
254:16 rbps=8000000 wbps=8000000 riops=100 wiops=max
254:16 is /dev/vdb's major:minor device number (lsblk -o
NAME,MAJ:MIN prints both columns for any device). The file shows the read
bandwidth cap (rbps), write bandwidth cap (wbps), read IOPS cap
(riops), and wiops=max - no write-IOPS limit was set, so none applies.
The unit stops itself when its sleep 60 ends; systemctl stop handbook-io
ends it sooner.
Two practical rules fall out of the mapping. First, IOWeight (the
cgroup's io.weight) only works with a weight-aware scheduler - BFQ;
under none or mq-deadline a weight is recorded without effect, exactly
like ionice. Second, the io.max caps are enforced by the block layer's
throttle before any scheduler sees the request, so they hold whatever
scheduler runs. When you need a guarantee, use a cap; when you need
proportional fairness and run BFQ, weights are the mechanism.
9.4.7. Page Cache, Buffered Writes, Writeback, and Direct-I/O Measurement Limits
Where does a write actually go? Figure 9.4 shows the two paths. A normal
buffered write copies data into the page cache - RAM - and returns to
the program immediately; the kernel flushes dirty pages to disk later
through writeback threads, on a timer or when memory pressure asks for
clean pages. A direct write (O_DIRECT, dd oflag=direct) bypasses the
cache and goes to the block layer at once. Neither is "faster"; they
measure different things, as this subsection shows rather than asserts.
Figure 9.4. Conceptual view of the write path. Buffered writes land in the page cache and return; writeback and fsync move them to the block layer, where the scheduler, ionice priorities, and cgroup limits act. Direct I/O skips the cache entirely.
Write 128 MiB of zeros and look at the memory counters before and after a
sync:
$ dd if=/dev/zero of=/mnt/io-lab/workspace/buffered.bin bs=1M count=128 status=none
The dd itself prints nothing (status=none suppresses its summary); the
data is in the page cache now, dirty:
$ grep -E "^(Dirty|Writeback):" /proc/meminfo
Dirty: 115932 kB
Writeback: 8232 kB
Dirty counts cached pages written by programs but not yet flushed; 128
MiB was written, and 115932 kB of it is still waiting, with 8232 kB already
in flight under the writeback threads (Writeback). Force the flush and
wait for it:
$ sync
sync is silent - it returns only when all dirty pages the system had are
written back:
$ grep -E "^(Dirty|Writeback):" /proc/meminfo
Dirty: 0 kB
Writeback: 0 kB
Both counters are zero: nothing is pending, nothing is in flight. That
round trip is the page-cache story in three commands. How much may sit
dirty, and for how long, is governed by the vm.dirty_* sysctls
(Chapter 7 covers persistent sysctl configuration).
Now the timing caveat, demonstrated honestly. Time a buffered write of the same size:
$ time dd if=/dev/zero of=/mnt/io-lab/workspace/buffered-2.bin bs=1M count=128 status=none
real 0m0.303s
user 0m0.004s
sys 0m0.297s
time reports on standard error; the write "took" 0.303 s - but that is
the time to copy into the page cache, most of it in the kernel (sys),
not the time the data reached the disk. A direct write of the same size:
$ time dd if=/dev/zero of=/mnt/io-lab/workspace/direct.bin bs=1M count=128 oflag=direct status=none
real 0m0.269s
user 0m0.000s
sys 0m0.032s
The direct write reports 0.269 s - not comparable to the buffered figure,
and the two must not be quoted as a speed comparison. Zero-filled blocks,
the sparse qcow2 image behind the virtual disk, whatever the host was
doing during each run, and the cache state left by previous steps all
dominate; the honest statement is that both writes completed in a fraction
of a second on this virtual stack, and neither number says anything about
the media. What does say something about media and durability is a
forced flush: dd conv=fsync (or oflag=dsync) makes each write end with
an fsync, so the reported time includes the wait for the device. For
storage measurement beyond demonstrations, use fio - already installed
with the chapter's tools - whose job is exactly to control cache state,
queue depth, and flush points and report latencies; man 1 fio is the
reference. Clean up the three files:
$ rm /mnt/io-lab/workspace/buffered.bin /mnt/io-lab/workspace/buffered-2.bin /mnt/io-lab/workspace/direct.bin
Silent, as removals are.
9.4.8. Comparing Latency, Throughput, and Fairness Under Competing I/O
The remaining question is what competition looks like, and the honest way
to run it. Make sure mq-deadline is serving the disk, then race two
direct writers of 256 MiB each - one best-effort level 0, one idle - and
time how long both need. In the root shell:
# echo mq-deadline > /sys/block/vdb/queue/scheduler
# cd /mnt/io-lab/workspace
# rm -f race-a.bin race-b.bin
# start=$(date +%s%N)
# ionice -c 2 -n 0 dd if=/dev/zero of=race-a.bin bs=1M count=256 oflag=direct status=none &
# a=$!
# ionice -c 3 dd if=/dev/zero of=race-b.bin bs=1M count=256 oflag=direct status=none &
# b=$!
# wait $a $b
# end=$(date +%s%N)
# echo "both-writers-elapsed-ms=$(( (end - start) / 1000000 ))"
both-writers-elapsed-ms=2999
# ls -l race-a.bin race-b.bin
-rw-r--r-- 1 root root 268435456 Nov 19 19:44 race-a.bin
-rw-r--r-- 1 root root 268435456 Nov 19 19:44 race-b.bin
# rm -f race-a.bin race-b.bin
The timing uses date +%s%N - a nanosecond timestamp before and after the
wait, subtracted and divided down to milliseconds. Both files completed:
256 MiB each, and 2999 ms of wall time for both writers together. On this
virtual disk, repeated runs of the same race ranged from roughly 1.2 to
8.0 seconds - the variance itself is the observation: behind the guest's
queue sits the hypervisor and the host's storage, and neither is under the
guest's control. What the race does not establish is fairness for either
scheduler class; with mq-deadline the idle writer is served when the
best-effort queue is momentarily empty, and on a fast virtual device those
moments are frequent.
The tool for watching such a race is iostat from the sysstat package -
its extended report gives per-device rates, latencies, queue depth, and
busy time. Run the same two writers again from john's shell while sampling
the device once per second:
$ cd /mnt/io-lab/workspace
$ rm -f race-a.bin race-b.bin
$ ionice -c 2 -n 0 dd if=/dev/zero of=race-a.bin bs=1M count=256 oflag=direct status=none &
$ a=$!
$ ionice -c 3 dd if=/dev/zero of=race-b.bin bs=1M count=256 oflag=direct status=none &
$ b=$!
$ iostat -x 1 4 vdb
Linux 6.12.86+deb13-amd64 (proc) 11/19/26 _x86_64_ (2 CPU)
avg-cpu: %user %nice %system %iowait %steal %idle
2.22 0.00 0.62 5.52 0.11 91.53
Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz w/s wkB/s wrqm/s %wrqm w_await wareq-sz d/s dkB/s drqm/s %drqm d_await dareq-sz f/s f_await aqu-sz %util
vdb 0.33 3.01 0.00 1.20 0.43 9.14 2.79 2798.52 0.64 18.72 23.39 1001.86 0.00 2805.30 0.00 0.00 0.07 699052.00 0.06 727.70 0.11 4.80
avg-cpu: %user %nice %system %iowait %steal %idle
0.00 0.00 3.61 71.13 1.03 24.23
Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz w/s wkB/s wrqm/s %wrqm w_await wareq-sz d/s dkB/s drqm/s %drqm d_await dareq-sz f/s f_await aqu-sz %util
vdb 0.00 0.00 0.00 0.00 0.00 0.00 505.94 518083.17 0.00 0.00 2.84 1024.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.44 95.05
avg-cpu: %user %nice %system %iowait %steal %idle
0.00 0.00 0.00 0.50 0.00 99.50
Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz w/s wkB/s wrqm/s %wrqm w_await wareq-sz d/s dkB/s drqm/s %drqm d_await dareq-sz f/s f_await aqu-sz %util
vdb 0.00 0.00 0.00 0.00 0.00 0.00 1.01 1034.34 0.00 0.00 2.00 1024.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.40
avg-cpu: %user %nice %system %iowait %steal %idle
0.00 0.00 0.00 0.00 0.00 100.00
Device r/s rkB/s rrqm/s %rrqm r_await rareq-sz w/s wkB/s wrqm/s %wrqm w_await wareq-sz d/s dkB/s drqm/s %drqm d_await dareq-sz f/s f_await aqu-sz %util
vdb 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
$ wait $a $b
$ rm -f race-a.bin race-b.bin
Everything except the iostat report is silent setup, sampling, and
cleanup. Read the four samples in order. The first is averages since boot -
iostat's first report always covers the period since the machine started, so
its nonzero baseline is the earlier exercises in this chapter, not the race. Sample 2 is the race
at full speed: about 506 writes/s and 506 MB/s in total (wkB/s 518083),
average write latency w_await 2.84 ms, average queue size aqu-sz 1.44,
and iowait up at 71.13% because a CPU sat idle while its tasks waited on
the writes. Sample 3 caught the tail of the race (1 write/s finishing the
last megabytes), and sample 4 the idle disk afterwards, every counter at
zero.
The columns worth knowing by name:
| Column | Meaning |
|---|---|
w/s, wkB/s |
Write requests and kilobytes per second (reads: r/s, rkB/s). |
w_await |
Average milliseconds a write waited for completion. |
aqu-sz |
Average number of requests in flight - queue depth. |
%util |
Fraction of wall time the device had at least one request in flight. |
%util deserves its warning here: on a device that executes many requests
in parallel it reaches 100% long before the device saturates. On this
sampled run it peaked at 95.05 while the writers were flat out - treat it as
"never idle", not "95% of capacity". Latency (w_await), rate (wkB/s),
and depth (aqu-sz) together describe contention; fairness - whether one
cgroup's requests waited systematically longer than another's - needs
per-cgroup or per-process counters: pidstat -d reports per-process rates
from /proc/<pid>/io (Section 9.6.3 reads those counters directly), and
the cgroup's own io.stat file accumulates per-device service bytes and
latencies for exactly this comparison.
The method, then, is the takeaway: one controlled variable at a time (scheduler, priority, or cgroup cap), the same work on both sides, the device watched while it happens, and conclusions no broader than what the sampled counters support. Chapter 28 applies this method continuously to production systems.
With the race files gone, the data-disk exercises are over; change back to
the processes workspace with cd ~/debian-handbook/processes, which the
remaining sections use.