Lesson 10 · Files, storage, I/O, and protection

Disk Management

Before a disk can hold a single file it must be divided into sectors, split into partitions, given a file system and a boot block, and watched for sectors that go bad. That work is disk management.

Disk Management concept diagramLeft: a platter seen from above with concentric tracks, one highlighted track and one sector on it. Right: three platters seen side on around a spindle, with a read-write head above and below each platter on a shared arm and a dashed cylinder through the same track on every surface.one surface, from abovetracksectorspindleplatters, side oncylinder: the same track on every surfacearm + heads
1

Disk Structure: Platters, Tracks, Sectors and Cylinders

  1. Platter – a rotating disk coated with magnetic material, usually on both surfaces.
  2. Track – one concentric ring on a surface.
  3. Sector – the smallest addressable unit on a track, traditionally 512 bytes, now often 4 KB.
  4. Cylinder – the set of tracks at the same radius on every surface, reachable without moving the arm.
  5. Head – one read-write head per surface, all mounted on one arm that moves together.

Disk management is the part of the operating system that prepares a storage device for use and keeps it usable: formatting, partitioning, booting, bad-block handling and swap space. It starts from the disk's physical layout, shown in the hero diagram.

Early systems addressed a sector by its geometry, CHS: cylinder, head, sector. Modern disks expose a flat sequence of logical block addresses (LBA) numbered from 0, and the drive's controller maps each LBA to a physical location. The OS sees only the LBA array; the drive hides zones, spare sectors and remapping.

Solid-state drives have no platters or heads, but they present the same LBA interface, so formatting, partitioning and booting work the same way. Their internal flash translation layer plays the part of the bad-block and remapping logic.

  • CHS = (cylinder, head, sector); LBA = one flat number
  • The OS works in LBAs; the controller maps them to physical sectors
  • A cylinder is readable without a seek
  • SSDs expose the same LBA interface
2

Disk Formatting: Low-Level and Logical

  1. Low-level (physical) formatting – divides each track into sectors, each with a header, a data area and an ECC trailer. Done by the manufacturer.
  2. Partitioning – divides the disk into one or more partitions, each treated as a separate logical disk, and records them in a partition table.
  3. Logical formatting – creates a file system in a partition: the boot sector, free-space structures, the root directory and the inode or FAT tables.

Formatting happens in these three stages, and exam questions usually ask for all three in order.

The error-correcting code (ECC) written with every sector during low-level formatting is what later detects, and for a few bits corrects, damaged data. A sector whose ECC reports more errors than it can fix is a bad block.

A partition can also be left raw, with no file system. Databases sometimes do this to control block layout themselves, and swap space often uses a raw partition. See file systems for what logical formatting builds, and file allocation methods for how it then places files.

  • Physical format: sectors = header + data + ECC
  • Partition table: MBR (up to 4 primary, 2 TB) or GPT (128 partitions, huge disks)
  • Logical format: build a file system in a partition
  • Raw partitions skip the file system entirely
3

Boot Block and the Boot Process

At power-on the CPU runs a tiny program stored in firmware (BIOS or UEFI). It knows nothing about file systems, so it loads code from a fixed place on the disk, the boot block.

On a BIOS system with an MBR disk, sector 0 holds 446 bytes of bootstrap code, a 64-byte partition table and a 2-byte signature. The code finds the partition marked active and loads that partition's first sector, the volume boot record, which loads a boot loader able to read the file system, which finally loads the kernel. Each stage knows just enough to find the next, which is why this is called chain loading.

UEFI firmware can read a small FAT file system itself, the EFI System Partition, and loads the boot loader as an ordinary file, usually from a GPT disk. The full sequence is covered in the operating system boot process.

MBR vs GPT
MBRGPT
LocationLBA 0LBA 1, with a backup at the end of the disk
Partitions4 primary (more via extended)128 by default
Maximum disk size2 TiB with 512-byte sectorsEffectively unlimited (64-bit LBAs)
FirmwareBIOSUEFI
IntegrityNoneCRC32 checksums
  • Boot block = the fixed first sector firmware reads
  • MBR: bootstrap code + partition table in LBA 0
  • Chain: firmware → MBR → boot sector → loader → kernel
  • UEFI + GPT is the modern replacement
Key reference

Terms, operations, and practical uses

Key terms

  • LBALogical block address: sectors numbered 0 to n − 1 across the whole disk.
  • ECCError-correcting code stored with each sector; detects and fixes a few bit errors.
  • MBRMaster Boot Record in LBA 0: bootstrap code and partition table.
  • Volume boot recordThe first sector of a partition; loads the OS boot loader.

Bad block methods

  • Bad-block listSoftware method: the file system never allocates listed blocks.
  • Sector sparingController remaps the bad LBA to a spare sector.
  • Sector slippingController shifts the following sectors down to use a spare on the same track.
Implementation

The life of a disk, sector by sector

HEADS = 16
SECTORS_PER_TRACK = 63
SECTOR_BYTES = 512


def chs_to_lba(cylinder, head, sector):
    # Sectors are numbered from 1 on each track; LBAs start at 0.
    return (cylinder * HEADS + head) * SECTORS_PER_TRACK + (sector - 1)


def lba_to_chs(lba):
    cylinder, rest = divmod(lba, HEADS * SECTORS_PER_TRACK)
    head, sector = divmod(rest, SECTORS_PER_TRACK)
    return cylinder, head, sector + 1


class Disk:
    def __init__(self, sectors, spares):
        self.visible = sectors - spares  # the OS never sees the spare sectors
        self.free_spares = list(range(self.visible, sectors))
        self.remap = {}  # bad LBA -> spare sector, kept by the controller

    def mark_bad(self, lba):
        # Sector sparing: point the bad sector at a spare, invisibly to the OS.
        self.remap[lba] = self.free_spares.pop(0)

    def physical(self, lba):
        return self.remap.get(lba, lba)


print("CHS (2, 5, 10) -> LBA", chs_to_lba(2, 5, 10))
print("LBA 2340 -> CHS", lba_to_chs(2340))
capacity = 1024 * HEADS * SECTORS_PER_TRACK * SECTOR_BYTES
print(f"1024 cylinders give {capacity:,} bytes = {capacity / 2**20:.0f} MiB")

disk = Disk(sectors=32, spares=2)
disk.mark_bad(12)
for lba in (9, 12, 13):
    print(f"read LBA {lba} -> physical sector {disk.physical(lba)}")
print("spares left:", len(disk.free_spares))
#include <cstdio>
#include <deque>
#include <map>
#include <tuple>
using namespace std;

const long HEADS = 16, SECTORS_PER_TRACK = 63, SECTOR_BYTES = 512;

// Sectors are numbered from 1 on each track; LBAs start at 0.
long chsToLba(long cylinder, long head, long sector) {
    return (cylinder * HEADS + head) * SECTORS_PER_TRACK + (sector - 1);
}

tuple<long, long, long> lbaToChs(long lba) {
    long cylinder = lba / (HEADS * SECTORS_PER_TRACK), rest = lba % (HEADS * SECTORS_PER_TRACK);
    return {cylinder, rest / SECTORS_PER_TRACK, rest % SECTORS_PER_TRACK + 1};
}

class Disk {
    deque<int> freeSpares;
    map<int, int> remap;  // bad LBA -> spare sector, kept by the controller

public:
    Disk(int sectors, int spares) {
        for (int s = sectors - spares; s < sectors; s++) freeSpares.push_back(s);  // hidden from the OS
    }

    // Sector sparing: point the bad sector at a spare, invisibly to the OS.
    void markBad(int lba) {
        remap[lba] = freeSpares.front();
        freeSpares.pop_front();
    }

    int physical(int lba) const {
        auto it = remap.find(lba);
        return it == remap.end() ? lba : it->second;
    }

    size_t sparesLeft() const { return freeSpares.size(); }
};

int main() {
    printf("CHS (2, 5, 10) -> LBA %ld\n", chsToLba(2, 5, 10));
    auto [c, h, s] = lbaToChs(2340);
    printf("LBA 2340 -> CHS (%ld, %ld, %ld)\n", c, h, s);
    long capacity = 1024 * HEADS * SECTORS_PER_TRACK * SECTOR_BYTES;
    printf("1024 cylinders give %ld,%03ld,%03ld bytes = %ld MiB\n", capacity / 1000000, capacity / 1000 % 1000,
           capacity % 1000, capacity >> 20);

    Disk disk(32, 2);
    disk.markBad(12);
    for (int lba : {9, 12, 13}) printf("read LBA %d -> physical sector %d\n", lba, disk.physical(lba));
    printf("spares left: %zu\n", disk.sparesLeft());
}
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;

public class Main {
    static final long HEADS = 16, SECTORS_PER_TRACK = 63, SECTOR_BYTES = 512;

    // Sectors are numbered from 1 on each track; LBAs start at 0.
    static long chsToLba(long cylinder, long head, long sector) {
        return (cylinder * HEADS + head) * SECTORS_PER_TRACK + (sector - 1);
    }

    static String lbaToChs(long lba) {
        long cylinder = lba / (HEADS * SECTORS_PER_TRACK), rest = lba % (HEADS * SECTORS_PER_TRACK);
        return "(" + cylinder + ", " + rest / SECTORS_PER_TRACK + ", " + (rest % SECTORS_PER_TRACK + 1) + ")";
    }

    static class Disk {
        final ArrayDeque<Integer> freeSpares = new ArrayDeque<>();
        final Map<Integer, Integer> remap = new HashMap<>(); // bad LBA -> spare sector, kept by the controller

        Disk(int sectors, int spares) {
            for (int s = sectors - spares; s < sectors; s++) freeSpares.add(s); // hidden from the OS
        }

        // Sector sparing: point the bad sector at a spare, invisibly to the OS.
        void markBad(int lba) {
            remap.put(lba, freeSpares.poll());
        }

        int physical(int lba) {
            return remap.getOrDefault(lba, lba);
        }
    }

    public static void main(String[] args) {
        System.out.println("CHS (2, 5, 10) -> LBA " + chsToLba(2, 5, 10));
        System.out.println("LBA 2340 -> CHS " + lbaToChs(2340));
        long capacity = 1024 * HEADS * SECTORS_PER_TRACK * SECTOR_BYTES;
        System.out.printf("1024 cylinders give %,d bytes = %d MiB%n", capacity, capacity >> 20);

        Disk disk = new Disk(32, 2);
        disk.markBad(12);
        for (int lba : new int[] {9, 12, 13}) {
            System.out.println("read LBA " + lba + " -> physical sector " + disk.physical(lba));
        }
        System.out.println("spares left: " + disk.freeSpares.size());
    }
}
Watch it run

Step through it

Running on 32 sectors: 30 visible, 2 spares; 2 partitions; LBA 12 goes bad

·0·1·2·3·4·5·6·7·8·9·10·11·12·13·14·15·16·17·18·19·20·21·22·23·24·25·26·27·28·29·30·31unformatted disk32 sector-sized slots, all unusable
Step 1

A new disk: magnetic surface, no sectors yet

Straight off the production line the platters are bare magnetic material. There are no sectors, headers or error-correcting codes, so nothing can be stored. This demo shrinks the disk to 32 sectors so every region is visible.

Output
1 / 11
4

Bad Blocks: Detection, Sparing and Slipping

Disks have moving parts and flash cells wear out, so some sectors fail. A bad block is detected when a read fails its ECC check, or during formatting and surface scans.

Older systems handled bad blocks in software: a utility found them and the file system marked them unusable in a bad-block list. Modern drives handle them in the controller, invisibly to the OS, using spare sectors reserved during low-level formatting.

Sector sparing (forwarding) remaps the bad LBA to a spare sector; the tracer shows LBA 12 moved to spare sector 30. It is simple but may add a seek if the spare is on another track. Sector slipping keeps the order instead: every sector after the bad one moves down a place so a spare at the end of the same track absorbs the shift, avoiding the extra seek at the cost of rewriting several sectors.

Sector sparing vs sector slipping
Sector sparingSector slipping
What movesOnly the bad sector's dataEvery sector after the bad one on the track
Extra seek laterPossible, if the spare is elsewhereNone
Work at remap timeOne sector copiedSeveral sectors shifted
Visible to the OSNoNo
  • Detected by ECC failure or surface scans
  • Software: mark blocks unusable in the file system
  • Controller: remap to spares, invisibly
  • Sparing is simpler; slipping avoids extra seeks
5

Worked Example: CHS to LBA and Disk Capacity

Sectors are numbered from 1 within a track, but LBAs and cylinders and heads from 0. That off-by-one is the usual trap.

  • Geometry – 1,024 cylinders, 16 heads, 63 sectors per track, 512-byte sectors.
  • Convert – the CHS address (2, 5, 10) to an LBA, then back.
  • Compute – the total capacity this geometry can address.

CHS to LBA. LBA = (C × heads + H) × sectors per track + (S − 1) = (2 × 16 + 5) × 63 + (10 − 1) = 37 × 63 + 9 = 2,340.

LBA to CHS. One cylinder holds 16 × 63 = 1,008 sectors. C = ⌊2340 / 1008⌋ = 2, remainder 324. H = ⌊324 / 63⌋ = 5, remainder 9. S = 9 + 1 = 10. Back to (2, 5, 10).

Capacity. 1,024 × 16 × 63 × 512 = 528,482,304 bytes ≈ 504 MiB. This is the historical 504 MB barrier: BIOS CHS addressing could not reach beyond it, which is one reason every modern system uses LBA.

  • LBA = (C × heads + H) × spt + (S − 1)
  • Sectors count from 1; cylinders and heads from 0
  • Capacity = cylinders × heads × sectors × bytes per sector
  • The 504 MB limit pushed the industry to LBA
6

Swap Space Management

Swap space is disk space used by virtual memory and swapping to hold pages that do not fit in RAM. Because a page fault waits for it, swap is managed for speed, not for the flexibility a file system provides.

It can live in an ordinary file inside a file system, which is easy to resize but pays file-system overhead on every access, or in a dedicated raw partition, which a swap-space manager lays out for contiguous, fast page I/O. Linux supports both; the tracer gives partition 2 to swap.

Allocation policy matters too. Some systems reserve swap for every page when a process starts; others allocate it only when a page is actually evicted. Text (code) pages need no swap at all: they can be re-read from the program file. See demand paging and thrashing for what happens when swap is used heavily.

  • Swap file: flexible, slower. Swap partition: fixed, faster
  • Code pages are reloaded from the executable, not swapped
  • Swap is sized for the working set that does not fit in RAM
  • Heavy swapping leads to thrashing