I/O Scheduling Algorithms

Learn classic HDD scheduling models and how current Linux block-device scheduler choices depend on the kernel and device.

published: reading time: 27 min read author: Geek Workbench updated: November 18, 2026
Quick Summary

Learn classic HDD scheduling models and how current Linux block-device scheduler choices depend on the kernel and device.

Introduction

An application read or write does not always reach a local disk. A read may come from the page cache, and a database or web service may use network storage. When I/O reaches a local block device, the kernel may apply a scheduler to that device’s request queue. Whether it does, and which scheduler is available, depends on the kernel, driver, device, and storage stack.

The problem seems simple: given a queue of disk requests, in what order should they be serviced? In practice, this becomes a nuanced optimization problem involving physical constraints (mechanical latency in HDDs), fairness (preventing request starvation), and throughput (keeping the disk busy).

FCFS, SSTF, SCAN, and C-SCAN are useful teaching models for rotating disks, where head movement affects service time. They do not describe how every SSD or modern Linux block device schedules requests.

When to Use / When Not to Use

When I/O Scheduling Algorithms Matter

  • Rotating storage (HDD): Seek distance can affect service time, so request ordering is useful to study. Any benefit depends on the request pattern and device.
  • Mixed local workloads: A block scheduler may affect how requests to one device wait behind each other. It cannot control work satisfied from cache or handled by another storage layer.
  • Database workloads: Only I/O that reaches a block-device queue is affected by that device’s scheduler. Measure the actual storage stack before changing it.
  • Virtual machines: I/O can be queued in both guest and host layers. A guest scheduler may not control how the host device dispatches requests.

When Scheduling Matters Less

  • SSD and NVMe workloads: These devices have no moving disk head and can process requests across multiple queues. Classic seek-order models do not describe their behavior, though a Linux scheduler may still affect queueing or fairness.
  • Direct attached storage with single application: If one application owns the disk, scheduling complexity provides diminishing returns
  • Latency targets: A scheduler choice alone cannot guarantee end-to-end latency; the filesystem, device, workload, and other queues also matter.
  • Write-heavy workloads with battery backup: Battery-backed RAID controllers can reorder writes aggressively because data is protected

Check Linux scheduler availability

Linux exposes scheduler choices per block-device queue. Names such as mq-deadline, bfq, kyber, and none may be available, but the list varies by kernel and device. Read the sysfs entries to see the choices on this system; the active scheduler appears in brackets:

for file in /sys/block/*/queue/scheduler; do
    [ -r "$file" ] || continue
    printf '%s: ' "${file#/sys/block/}"
    cat "$file"
done

This check is read-only. Consult the Linux kernel scheduler documentation before changing a device’s setting.

Architecture or Flow Diagram

This diagram is a simplified view of one possible block-I/O path. A device queue may have no scheduler, and not every application request reaches a local block device.

flowchart TB
    subgraph "Application Layer"
        A1["App 1\nwrite"]
        A2["App 2\nread"]
        A3["App 3\nwrite"]
    end

    subgraph "Kernel Block Layer"
        Q["Block-device Request Queue"]
        S["Optional I/O Scheduler"]
        D["Dispatch Queue\n(per-hardware queue)"]
    end

    subgraph "Hardware"
        H1["NVMe Queue 0"]
        H2["NVMe Queue 1"]
        HN["Disk\nController"]
    end

    A1 --> Q
    A2 --> Q
    A3 --> Q
    Q --> S
    S --> D
    D --> H1
    D --> H2
    H1 --> HN
    H2 --> HN

    style Q stroke:#00fff9
    style S stroke:#ff00ff
    style D stroke:#00fff9

In Linux, block-layer requests may pass through a scheduler before dispatch to hardware queues. The scheduler is optional, and the specific queueing and dispatch path depends on the device and kernel. The head-seek ordering shown in the classic algorithms below is a model for rotating disks.

Core Concepts

The next four algorithms are educational models for rotating disks. Their seek-distance comparisons do not carry over directly to SSD or NVMe devices, where there is no moving head and requests may be served through multiple queues.

First-Come, First-Served (FCFS)

The simplest possible scheduler—requests are processed in arrival order. No optimization whatsoever.

// Conceptual FCFS implementation
void fcfs_add_request(struct request_queue *q, struct request *req)
{
    list_add_tail(&req->queuelist, &q->queue_head);
}

struct request *fcfs_next_request(struct request_queue *q)
{
    if (list_empty(&q->queue_head))
        return NULL;
    return list_first_entry(&q->queue_head, struct request, queuelist);
}

In this model, FCFS serves requests in arrival order. On a rotating disk, random request locations can increase head movement; on other devices, the result depends on their queueing and parallelism.

Shortest Seek Time First (SSTF)

SSTF services the request closest to the current head position, minimizing total seek distance.

struct request *sstf_next_request(struct request_queue *q)
{
    struct request *req, *best = NULL;
    sector_t head = disk_head_position(q);
    sector_t best_dist = ULONG_MAX;

    list_for_each_entry(req, &q->queue_head, queuelist) {
        sector_t dist = abs(req->sector - head);
        if (dist < best_dist) {
            best_dist = dist;
            best = req;
        }
    }

    if (best) {
        list_del(&best->queuelist);
    }
    return best;
}

For the rotating-disk model, SSTF can reduce seek distance for a fixed request set. It can also defer requests far from the current head if closer requests keep arriving. These properties do not predict SSD or NVMe latency.

SCAN Algorithm (Elevator)

The SCAN algorithm moves the head in one direction (say, from innermost to outermost cylinder) servicing all requests along the way, then reverses direction. Like an elevator, it serves floors in order.

struct request *scan_next_request(struct request_queue *q)
{
    struct request *req;
    sector_t head = disk_head_position(q);
    enum direction dir = current_direction(q);  // IN or OUT

    // Find closest request in current direction
    list_for_each_entry(req, &q->queue_head, queuelist) {
        if (req->sector >= head && dir == OUT)
            goto found;
        if (req->sector <= head && dir == IN)
            goto found;
    }

    // No request in current direction, reverse
    reverse_direction(q);
    return scan_next_request(q);  // Recurse once

found:
    list_del(&req->queuelist);
    return req;
}

In the rotating-disk model, SCAN bounds how long a queued request waits for the head to sweep its direction, though requests just missed by the head may wait for another pass.

C-SCAN (Circular SCAN)

SCAN sweeps back and forth across the disk, servicing requests in both directions. C-SCAN (circular SCAN) restricts service to one direction only. After the head finishes at the outermost cylinder, it hops back to the innermost cylinder without processing any requests on the way back. Every cylinder gets the same service time because the head always travels inner to outer.

That jump-back is the whole point. When the head reaches the outer edge, C-SCAN races back to cylinder 0 at full speed, ignoring everything in between. This costs seek time, but it eliminates the asymmetry that makes SCAN unfair—cylinders near the center get swept twice per cycle while edge cylinders wait longer.

In the rotating-disk model, C-SCAN gives queued requests a more uniform sweep interval, at the cost of the return movement. It is a textbook policy; current Linux schedulers such as mq-deadline are separate implementations, not aliases for C-SCAN.

SCAN pattern:  ←←←←←←←←←←←  →→→→→→→→→→→  ←←←←←←←←←←
                 service      return (no service)    service

C-SCAN pattern: ←←←←←←←←←←←  ==================  ←←←←←←←←
                 service      fast return (empty)   service

Deadline Scheduler

This deadline-style pseudocode is a teaching model: it prioritizes expired requests while otherwise using a location-based order. Actual Linux schedulers and tunables vary; do not assume fixed read or write deadlines across kernels and devices.

struct request *deadline_next_request(struct request_queue *q)
{
    struct request *req;

    // Check read FIFO for expired deadlines
    req = read_fifo_peek(q);
    if (req && deadline_expired(req)) {
        return read_fifo_pop(q);  // Force service
    }

    // Check write FIFO
    req = write_fifo_peek(q);
    if (req && deadline_expired(req)) {
        return write_fifo_pop(q);
    }

    // Normal dispatch: closest request (elevator)
    return elevator_dispatch(q);
}

Linux’s mq-deadline is one scheduler for the multi-queue block layer. Whether it is available depends on the device and kernel; use the read-only sysfs check above rather than assuming it is present.

Completely Fair Queueing (CFQ)

CFQ allocates disk time slices fairly across processes, giving each process its own queue. This prevents a single aggressive process from monopolizing the disk.

// Per-process queue structure
struct cfq_queue {
    pid_t pid;
    unsigned int sector_weight;  // Based on ioprio
    unsigned int time_slice;
    struct list_head cfq_list;  // In service tree
};

// Dispatch: pick queue with oldest slice, service its requests
struct cfq_queue *cfq_pick_queue(struct cfq_data *cfqd)
{
    // Find non-empty queue with lowest virtual runtime
    return rb_first(&cfqd->service_tree);
}

CFQ is a historical Linux scheduler. Current Linux scheduler choices vary by kernel and device; consult the per-device queue and kernel documentation before applying an old example to a current system.

Production Failure Scenarios

Scenario 1: Starvation in SSTF Causing Application Hang

What happened: A backup application continuously wrote large files in sequential order from cylinder 0 upward. Meanwhile, an interactive database application issued small reads scattered across the outer cylinders. The database’s requests were always farther from the backup stream’s current position, so they were perpetually deferred. Database queries began timing out.

Detection: Application monitoring showed I/O latency spikes exceeding 10 seconds. iostat showed disk utilization at 100% but with very low transaction rates.

Mitigation: SSTF is a teaching model, not a scheduler option you can select on a typical current Linux device. Inspect that device’s available schedulers, then measure any candidate under the real workload. If mq-deadline is listed and an administrator approves a live change, the command is:

echo mq-deadline | sudo tee /sys/block/sda/queue/scheduler

Replace sda with the target device. Changing its scheduler affects live I/O and does not guarantee database query latency.

Scenario 2: Write starvation under a historical CFQ setup

What happened: A web server handling mostly read requests gave writes such low priority that write buffers filled and application blocked on write(), causing apparent hangs despite low disk utilization.

Detection: iotop showed minimal write I/O but free showed swap usage increasing—writeback couldn’t keep up.

Mitigation: CFQ is a historical scheduler, not a choice available on every current Linux device. Check the device’s scheduler list first. If mq-deadline is available and a live change is appropriate, it can be compared against the current setting:

echo mq-deadline | sudo tee /sys/block/nvme0n1/queue/scheduler

Scenario 3: Limited queue depth on NVMe

What happened: An application submitted one request at a time, limiting the parallel I/O available to an NVMe storage stack. The queue depth and performance impact depend on the device, driver, and software path; there is no single expected IOPS figure.

Detection: A block trace or application profiler showed no requests outstanding while the application waited for each completion.

Mitigation: If the application and storage API support it, submit a bounded number of independent requests asynchronously. Benchmark with a safe test workload; increasing concurrency does not guarantee higher throughput or lower latency.

These Linux examples are device-specific. The sysfs write requires administrative privileges and changes the scheduler immediately; only use a name shown by the read-only check above.

Trade-off Table

The classic algorithm comparisons below describe request ordering for rotating disks. They do not predict SSD or NVMe throughput.

The values are qualitative teaching comparisons for HDD workloads. Deadline and CFQ are historical policy models here, not guarantees about a current Linux queue.

Algorithm Avg Seek Distance Starvation Risk Throughput Complexity
FCFS Very High (random access) None (trivially fair) Low Trivial
SSTF Minimal High (far requests ignored) Highest (HDD) Low
SCAN Moderate Low (guaranteed service) High Medium
C-SCAN Moderate-High Very Low (uniform guarantee) High Medium
Deadline Moderate Very Low (deadline guarantee) High Medium
CFQ (historical) Variable Very Low (fair queuing) Moderate High

Implementation Snippets

Simulating SCAN Scheduling

#!/usr/bin/env python3
"""
Simulates the SCAN (elevator) disk scheduling algorithm.
"""
from dataclasses import dataclass
from typing import List, Optional


@dataclass
class Request:
    sector: int
    pid: int = 0
    arrival_time: float = 0.0


class SCANScheduler:
    def __init__(self, disk_size: int = 10000, head_start: int = 0):
        self.disk_size = disk_size
        self.head = head_start
        self.direction = 1  # 1 = toward end, -1 = toward start
        self.queue: List[Request] = []
        self.total_seek = 0

    def add_request(self, req: Request):
        self.queue.append(req)

    def _sort_key(self, req: Request) -> tuple:
        """Sort by direction-aware distance from head."""
        if self.direction == 1:
            # Moving toward end: prioritize requests ahead of head
            if req.sector >= self.head:
                return (0, req.sector)  # In direction, sort by sector
            else:
                return (1, self.disk_size - req.sector)  # Behind, sort by reverse distance
        else:
            # Moving toward start
            if req.sector <= self.head:
                return (0, -req.sector)  # In direction, sort by reverse sector
            else:
                return (1, req.sector)  # Ahead, sort by distance

    def run(self) -> List[tuple]:
        """Run SCAN until queue empty, return list of (sector, seek_distance)."""
        serviced = []

        while self.queue:
            # Sort by direction-aware distance
            self.queue.sort(key=self._sort_key)
            req = self.queue.pop(0)

            seek = abs(req.sector - self.head)
            self.total_seek += seek
            serviced.append((req.sector, seek))
            self.head = req.sector

            # At disk edge, reverse direction
            if self.head >= self.disk_size - 1:
                self.direction = -1
            elif self.head <= 0:
                self.direction = 1

        return serviced


if __name__ == "__main__":
    import random
    random.seed(42)

    scheduler = SCANScheduler(disk_size=10000, head_start=5000)

    # Add random requests
    for i in range(20):
        scheduler.add_request(Request(sector=random.randint(0, 9999)))

    print(f"Initial head position: 5000")
    print(f"Running SCAN scheduler...\n")

    serviced = scheduler.run()
    for i, (sector, seek) in enumerate(serviced):
        print(f"  Step {i+1:2d}: Service sector {sector:5d} (seek={seek:5d})")

    print(f"\nTotal seek distance: {scheduler.total_seek}")
    print(f"Average seek: {scheduler.total_seek / len(serviced):.1f}")

Check the active scheduler before benchmarking

#!/bin/bash
# Read-only; the active scheduler appears in brackets.
echo "=== Current scheduler ==="
cat /sys/block/sda/queue/scheduler

echo ""
echo "=== Tunable parameters ==="
# These files exist only when the selected scheduler exposes these tunables.
cat /sys/block/sda/queue/iosched/read_expire_ms
cat /sys/block/sda/queue/iosched/write_expire_ms
cat /sys/block/sda/queue/iosched/fifo_batch

echo ""
echo "=== Benchmark with fio ==="
sudo fio --name=randread --filename=/dev/sda --ioengine=libaio \
    --rw=randread --bs=4k --numjobs=4 --runtime=30 --time_based=1 \
    --readonly --iodepth=32 2>/dev/null | grep -E "IOPS|lat"

Observability Checklist

Linux Block Layer Metrics

# View queue depth and scheduler behavior
cat /sys/block/sda/queue/nr_requests     # Queue depth
cat /sys/block/sda/queue/read_expire_ms   # Deadline read timeout
cat /sys/block/sda/queue/write_expire_ms  # Deadline write timeout

# iostat for throughput and queue length
iostat -xz 1                              # Per-device utilization and queue
iostat -xdy 1                             # Per-partition detailed stats

# blktrace for request-level tracing
sudo blktrace -d /dev/sda -o - | blkparse -i -

Key Metrics to Monitor

Metric Healthy Range Alert Threshold Indicates
avgqu-sz < 4 > 16 Queue saturation
util < 70% > 90% Disk bottleneck
rkB/s + wkB/s Workload dependent Sudden drops Controller or disk issue
await < 10ms HDD, < 1ms SSD > 100ms Latency issues
svctm < 10ms HDD > 20ms Device service degradation

Common Pitfalls / Anti-Patterns

I/O Scheduling Security Implications

  1. Timing Attacks: Predictable scheduling can leak information through access patterns. Adversaries measuring I/O timing might infer what data other processes access.

  2. Denial of Service: A malicious process could submit enormous numbers of tiny requests, monopolizing scheduler time and starving legitimate processes. Use cgroups I/O controllers to enforce fairness:

    # Limit cgroup to 50MB/s write bandwidth
    echo "8:0 52428800" > /sys/fs/cgroup/blkio/user.slice/io.max
  3. Data Lifetime: Scheduling decisions affect when data reaches stable storage. Synchronous writes must bypass caches—verify sync() calls actually flush before returning.

  4. Scheduler Selection Risks: A scheduler may be absent from a device’s available list, and a choice that helps one workload may hurt another. Check the per-device options and measure on the actual storage stack.

Coding Anti-Patterns

Anti-pattern Why It’s Bad Correct Approach
Treating SSTF as a current device setting SSTF is a teaching model for rotating disks Inspect the device’s supported schedulers
Assuming NVMe needs no scheduler Queueing and fairness behavior varies by stack Measure available choices on the target device
Submitting requests synchronously Underutilizes hardware queues Batch async submissions
Not aligning to physical block size Causes read-modify-write cycles Use fdisk alignment, verify alignment
Mixing SSD and HDD scheduling logic Assumes seek time matters on flash Different schedulers per device type

Quick Recap Checklist

  • Classic HDD algorithms model how request order affects seek distance and waiting time
  • FCFS is fair but performs poorly; SSTF minimizes seeks but risks starvation
  • SCAN (elevator) sweeps across the disk; C-SCAN provides uniform service times
  • Linux scheduler options depend on the kernel and each block device; read the sysfs queue entry before changing one
  • NVMe multi-queue devices have different trade-offs from rotating disks; none means no elevator scheduler, not no device-side ordering
  • Monitor iostat -x for queue depth, utilization, and latency metrics
  • Use cgroups I/O controllers for multi-tenant fairness guarantees
  • Measure scheduler effects with the workload and storage stack that matter

Interview Questions

1. What is the "elevator algorithm" and what problem does it solve?

In the classic rotating-disk model, SCAN orders requests by cylinder as the head sweeps in one direction and then returns. This can reduce head movement compared with arbitrary FCFS order. The elevator analogy describes the model; it is not a claim that current SSD or NVMe schedulers use SCAN.

2. Why did Linux deprecate CFQ (Completely Fair Queueing)?

CFQ is a historical Linux scheduler from the single-queue era. Current kernels and devices expose different scheduler choices, so it is not useful to describe mq-deadline or BFQ as universal replacements. Check the target device's queue and consult current kernel documentation.

3. What is request starvation and which algorithms prevent it?

Starvation occurs when a request is perpetually deferred because others keep getting priority—typically with SSTF, where requests far from the current head position never get serviced if new closer requests keep arriving. FCFS has no starvation (trivially fair). SCAN prevents starvation because every request in the sweep direction gets serviced before the head reverses. Deadline prevents starvation by enforcing maximum wait times—expired requests jump the queue. CFQ/BFQ prevent starvation by giving each process bounded time slices.

4. How does the deadline scheduler prevent write starvation?

The pseudocode above illustrates a deadline-style policy: it checks for expired requests before using a location-based order. Real schedulers use kernel- and device-specific tunables, and they cannot guarantee end-to-end application latency. Inspect the current scheduler and its documentation before relying on a particular timeout.

5. Why does NVMe make I/O scheduling less important?

NVMe has no moving disk head and can expose multiple hardware queues, so seek-order algorithms such as SSTF do not apply. The Linux block layer may still use a scheduler for a device, or expose none; the choices vary. none means no I/O elevator is selected, not that the device lacks internal queueing. Check the target queue and measure latency, throughput, and fairness for the workload.

6. What is anticipatory scheduling and why was it deprecated in favor of deadline and CFQ?

Anticipatory scheduling was based on the observation that after a read completes, the process that issued it typically issues another read nearby (sequential pattern). The scheduler would "anticipate" this and wait a few milliseconds after a read completes to see if the same process issues another read nearby, maximizing sequential reads. This improved throughput for sequential-heavy workloads but introduced latency for random I/O because requests waited while the scheduler anticipated. When the workload changed (more random reads, more mixed workloads), anticipatory scheduling caused performance degradation. The Linux kernel deprecated anticipatory scheduling and removed it from mainline in favor of CFQ (which provided fairness) and deadline (which provided latency guarantees). Anticipatory scheduling illustrated that optimizing purely for throughput can harm fairness and latency.

7. How does the Linux block layer multi-queue design improve performance on modern storage devices?

Linux's block multi-queue layer supports parallel submission and dispatch paths for devices with multiple hardware queues. An I/O scheduler may sit in that path, but it is not required on every queue. The scheduler names and available behavior vary by kernel configuration and device; check the sysfs entry and current kernel documentation.

8. What is the NOOP (Noop) scheduler and when is it appropriate?

noop is a historical Linux elevator name. Current kernels may expose none for a block device, which means no I/O elevator is selected. This does not guarantee that it is the best choice: available options and results depend on the device, kernel, and workload. Inspect the per-device scheduler list before drawing a comparison.

9. How does elevator merging work in the Linux block layer and why does it reduce I/O overhead?

Elevator merging combines adjacent I/O requests into a single larger request before submission to the hardware. If two read requests are for consecutive sectors (e.g., sector 100 and sector 101), the scheduler merges them into one request spanning sectors 100-101. This reduces the number of I/O operations the device must process, which is especially important for HDDs where each operation has seek overhead. Merging is particularly effective for sequential write patterns where multiple small writes are combined into larger, more efficient writes. The deadline scheduler includes merge logic before applying deadline constraints. Without merging, a process writing one byte at a time would generate one I/O operation per byte—a disaster on rotating media. Even on SSDs, merging reduces command processing overhead.

10. What is the relationship between I/O scheduler decisions and filesystem fragmentation?

I/O scheduler decisions directly affect filesystem fragmentation. When the scheduler groups and reorders requests, it changes the order in which file blocks are written to disk. An SCAN-style scheduler that sweeps across the disk tends to write file blocks in roughly sequential order, producing less fragmentation. An SSTF-based scheduler (if not properly deadline-constrained) might interleave blocks from different files, increasing fragmentation over time. Filesystems like ext4 use extent-based allocation to reduce fragmentation sensitivity, but heavy random-write workloads will eventually fragment even extent-based filesystems. The relationship is: more intelligent I/O scheduling leads to more sequential writes, which leads to lower fragmentation, which in turn improves performance because reads are more sequential. This is a feedback loop—better scheduling reduces fragmentation, which reduces the need for seeking, which improves effective throughput.

11. How does the Linux kernel handle I/O scheduling for network storage (NAS, NFS) versus local block devices?

Network storage doesn't go through the block I/O scheduler because network protocols (NFS, CIFS) use the network stack, not the block layer. The OS-level I/O scheduler only applies to block devices (disks, SSDs, RAID arrays). For NFS, the network packet scheduler (qdisc) in the network stack handles ordering, and NFS client readahead/writethrough caching determines when data is sent over the network. For NAS, the "scheduling" effectively happens at the NFS server level—the client sends requests and the server orders them on its attached storage. This means that choosing `deadline` versus `cfq` on a Linux NFS client has no effect on the actual storage performance—only on local caching behavior and how requests are batched before being sent. For local storage, the scheduler matters. For remote storage, you tune the network qdisc and NFS mount options.

12. What is the blk-mq (block multi-queue) architecture and why was it necessary for NVMe?

Linux's block multi-queue layer supports parallel submission and dispatch paths for devices with multiple hardware queues. An I/O scheduler may sit in that path, but it is not required on every queue. The scheduler names and available behavior vary by kernel configuration and device; check the sysfs entry and current kernel documentation.

13. What is the relationship between I/O scheduler latency and quality of service (QoS) guarantees?

An I/O scheduler can affect how requests wait in a block-device queue, but it does not guarantee application-level latency or bandwidth. Linux also has cgroup I/O controls, which are separate from the scheduler. Which mechanisms are available depends on the kernel and device; measure them with the real workload before promising a QoS bound.

14. How does the elevator algorithm's request merging affect the effective bandwidth of a disk?

Request merging combines adjacent requests, reducing the total number of I/O operations issued to the disk. For an HDD, fewer operations means fewer seeks—each seek takes 5-15ms, so merging adjacent requests can eliminate seeks entirely, dramatically increasing effective bandwidth. If the scheduler merges 8 requests for consecutive sectors into 1 request, the disk handles 1 seek instead of 8, potentially cutting latency by an order of magnitude. For SSDs, merging reduces command processing overhead and allows the drive's internal NAND to handle larger, more efficient write operations. The effective bandwidth improvement from merging depends on the workload: sequential workloads benefit most (nearly all requests are mergeable), while random I/O workloads see little merging benefit. The block layer's merge logic is fundamental to all I/O schedulers.

15. What is the blkcg (block cgroup) infrastructure and how does it enable per-cgroup I/O throttling?

blkcg provides I/O control via cgroups, allowing disk I/O bandwidth and IOPS limits per cgroup. The `io.max` interface in cgroups v2 limits a cgroup to specific bandwidth (bytes per second) or IOPS. Unlike the `blkio` cgroup v1 throttling which operated at the scheduler level, `io.max` works at the device level and is scheduler-agnostic—it works with deadline, mq-deadline, BFQ, or even no scheduler. The throttling happens before the scheduler, making it effective even for NVMe where the scheduler matters less. This enables true per-cgroup guarantees in multi-tenant environments. For example, in Kubernetes, you can set `storage.io.throttle.read_bps` to guarantee that a specific pod cannot exceed a certain read rate. Without blkcg, a noisy neighbor pod could monopolize disk bandwidth.

16. How does the SCAN algorithm's direction reversal (elevator reversal) affect request latency variance?

SCAN reverses direction at each end of the disk—moving from innermost to outermost, then back. This creates a pattern where requests at the edges of the disk have higher latency because they wait for the full sweep before being serviced. After SCAN processes all inner requests and reaches the innermost cylinder, it reverses and starts processing outer requests. If a request arrives at the outermost cylinder after the sweep has passed, it must wait for the full sweep back. This creates asymmetric latency: requests near the center of the disk tend to be serviced more frequently than those at the extremes. C-SCAN addresses this by servicing requests only in one direction and then jumping back to the start (not servicing requests on the return trip), giving every cylinder equal service time. The tradeoff is slightly higher total seek distance (no benefit from the return sweep).

17. What is the difference between I/O throughput and I/O latency, and why does the scheduler prioritize them differently for different workloads?

Throughput is the amount of data transferred per second; latency is the time from request to completion. A scheduler can change queue wait time, but workload, cache, device, and other layers also affect both measures. SSTF, deadline-style policies, and BFQ illustrate different trade-offs; none gives a universal throughput or latency guarantee. Check which schedulers are available and measure the target workload.

18. How does I/O scheduler selection interact with storage encryption (LUKS, BitLocker) and what overhead does encryption add?

Full-disk encryption (LUKS, BitLocker) operates below the filesystem layer in the block device layer, encrypting each disk sector on write and decrypting on read. This happens in the bio path after the I/O scheduler has merged and ordered requests but before the data reaches the storage medium. The encryption overhead is CPU-bound and pipelineable—modern CPUs with AES-NI can encrypt at several GB/s with negligible overhead. The key interaction with the I/O scheduler is that encryption does not change request ordering or merging behavior—the scheduler operates on logical block addresses, which are encrypted to physical addresses transparently. However, encrypted storage has higher CPU overhead per I/O operation, which can become a bottleneck at very high IOPS when the CPU's crypto unit becomes saturated. Hardware encryption accelerators (Intel QAT, AMD PSP) offload this to dedicated silicon, eliminating the bottleneck.

19. What is the impact of physical block size (512e vs 4Kn) on I/O scheduler performance?

Many modern HDDs and some SSDs report 4KB physical sectors internally while exposing 512-byte logical sectors to the OS (512e). A write that is not aligned to the physical block size triggers read-modify-write cycles: the device must read the full 4KB block, modify the 512-byte portion, and write the block back. The I/O scheduler can reduce the occurrence of these misaligned operations by merging adjacent requests and ensuring that requests are aligned to physical boundaries. An 512-byte write at sector 7 will cause a 4KB read-modify-write cycle at the physical block level; merging it with adjacent writes to reach 4KB alignment can eliminate this overhead. Modern storage devices with native 4KB sectors (4Kn) avoid this complexity. The scheduler's merge logic is particularly important for 512e drives because it can reduce the penalty of misaligned writes.

20. How does the kernel's I/O latency histogram (available in blktrace and btt) help diagnose scheduler problems?

The kernel can record I/O latency at the block layer using the blktrace infrastructure, capturing timestamps for each request from submission through dispatch to completion. The btt (blktrace analysis tool) converts this into histograms showing latency distribution. If the histogram shows a long tail (99th percentile latency much higher than median), the scheduler might be prioritizing throughput over latency, or the disk might be heavily seek-bound. A bimodal distribution (requests clustered at low and high latency) suggests request-dependent behavior—some requests are being serviced while others wait excessively. Comparing latency histograms across different schedulers (deadline vs mq-deadline vs BFQ) reveals which scheduler best controls tail latency for your workload. You can also identify "I/O storms"—periods where latency spikes dramatically, often correlating with specific workloads or cron jobs.

Further Reading

Conclusion

Classic FCFS, SSTF, SCAN, and C-SCAN models show how request order can trade head movement against waiting time on rotating disks. Current Linux I/O scheduling depends on the device queue, kernel, and workload; many application operations do not reach a local disk scheduler at all.

To inspect a Linux system, read the scheduler entry for the device you care about, then use the current kernel documentation to interpret its options. Compare choices on the target storage stack instead of mapping a textbook algorithm directly to an SSD or NVMe scheduler.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science