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

RAID Levels

RAID combines several disks into one logical drive, trading capacity for speed, for redundancy, or for a balance of both through parity.

RAID Levels concept diagramThree panels. RAID 0 stripes blocks A1 to A6 across two disks with no redundancy. RAID 1 mirrors the same blocks on two identical disks. RAID 5 stripes them across three disks with one parity block per stripe, rotating between disks.RAID 0 — stripingdisk 0A1A3A5disk 1A2A4A6capacity 100%survives 0 failuresRAID 1 — mirroringdisk 0A1A2A3disk 1A1A2A3capacity 50%survives 1 failureRAID 5 — striping + paritydisk 0A1A3P3disk 1A2P2A5disk 2P1A4A6capacity (n − 1)/nsurvives 1 failureP1 = A1 ⊕ A2, P2 = A3 ⊕ A4, P3 = A5 ⊕ A6: any one lost block is the XOR of the others in its stripe
1

What Is RAID?

  1. Striping – blocks alternate across disks: speed, no redundancy.
  2. Mirroring – every block written twice: redundancy at half the capacity.
  3. Parity – one XOR block per stripe: redundancy for the cost of one disk.

RAID (Redundant Array of Independent Disks) combines several physical disks into one logical disk that the operating system reads and writes like any other. Depending on the RAID level, the array is faster than one disk, survives a disk failure, or both.

Every RAID level is built from three techniques. Striping splits data into blocks and places consecutive blocks on different disks, so large transfers use every disk at once. Mirroring writes identical copies to two disks. Parity stores a computed block from which any one missing block of a stripe can be rebuilt.

RAID is implemented either in a dedicated hardware controller, which presents the array to the OS as one disk, or in software by the OS itself, as Linux mdadm or Windows Storage Spaces do. The levels behave the same either way.

  • Several physical disks appear to the OS as one
  • Levels differ in speed, capacity and fault tolerance
  • Hardware RAID lives in a controller; software RAID lives in the OS
2

RAID Levels Compared

Five types of RAID matter in practice: 0, 1, 5, 6 and 10. The table compares them for an array of n equal disks. Levels 2, 3 and 4 are obsolete but still examined, and are covered further down.

The pattern to remember is that redundancy always costs capacity or write speed. RAID 0 gives both away for speed. RAID 1 pays half the capacity. RAID 5 and 6 pay one or two disks of capacity and a slower write path.

RAID levels for n disks of equal size
LevelTechniqueMin disksUsable capacitySurvivesBest at
RAID 0striping2n disks (100%)0 failuresspeed, scratch data
RAID 1mirroring21 disk (50% for 2)n − 1 failuressmall critical volumes
RAID 5striping + distributed parity3n − 1 disks1 failureread-heavy storage
RAID 6striping + double parity4n − 2 disks2 failureslarge arrays
RAID 10mirrored pairs, striped4n/2 disks1 per mirror pairdatabases, heavy writes
  • Capacity lost = the disks spent on mirror copies or parity
  • Failures survived = how many missing blocks per stripe the redundancy can solve for
  • Pick RAID 10 for heavy writes, RAID 6 for large arrays, RAID 0 only for data you can regenerate
3

How RAID 5 Parity Works

RAID 5 computes parity with XOR (⊕), bit by bit across the data blocks of a stripe. XOR has the property that makes recovery possible: any value XORed with itself is 0. If P = D0 ⊕ D1 ⊕ D2, then D1 = D0 ⊕ D2 ⊕ P. Any one block of the stripe, data or parity, equals the XOR of all the others.

  • One stripe – D0 = 0011, D1 = 1010, D2 = 0110.
  • Parity – P = 0011 ⊕ 1010 ⊕ 0110 = 1111.
  • Disk holding D1 fails – D1 = D0 ⊕ D2 ⊕ P = 0011 ⊕ 0110 ⊕ 1111 = 1010.

The parity block rotates from disk to disk with each stripe. That is the difference from RAID 4, which keeps all parity on one disk. Because every write updates parity, a dedicated parity disk would be written on every single write and become the bottleneck.

When one disk fails, the array runs in degraded mode: reads of blocks on the dead disk are reconstructed on the fly from the rest of the stripe. Replacing the disk triggers a rebuild that recomputes every block it should hold.

  • P = XOR of the data blocks in the stripe
  • Lost block = XOR of every surviving block in the stripe
  • Parity rotates across disks to avoid a write bottleneck
  • Degraded mode keeps the array online after one failure
Key reference

Terms, operations, and practical uses

Core vocabulary

  • StripeOne row of blocks across all disks, including its parity block.
  • ParityThe XOR of a stripe's data blocks; it can stand in for any one lost block.
  • Degraded modeRunning with a failed disk, reconstructing its blocks on every read.
  • RebuildRecomputing a replaced disk's contents from the survivors.

Numbers to remember

  • RAID 5 capacity(n − 1)/n of the raw space; 3 of 4 disks.
  • RAID 6 capacity(n − 2)/n; survives two failures.
  • RAID 10 capacityn/2, whatever n is.
  • RAID 5 write penalty4 operations per small write.
Implementation

RAID 5 parity, failure and rebuild

from functools import reduce

DISKS = 4


def xor_all(blocks):
    return reduce(lambda a, b: a ^ b, blocks, 0)


class Raid5:
    def __init__(self, disks):
        self.n = disks
        self.disks = [[] for _ in range(disks)]  # disks[k][stripe] -> block
        self.failed = set()

    def parity_disk(self, stripe):
        # Rotate parity so no single disk takes every parity write.
        return self.n - 1 - stripe % self.n

    def write_stripe(self, data):
        stripe = len(self.disks[0])
        p = self.parity_disk(stripe)
        blocks = iter(data)
        for k in range(self.n):
            self.disks[k].append(xor_all(data) if k == p else next(blocks))

    def locate(self, index):
        stripe, offset = divmod(index, self.n - 1)
        data_disks = [k for k in range(self.n) if k != self.parity_disk(stripe)]
        return stripe, data_disks[offset]

    def read(self, index):
        stripe, disk = self.locate(index)
        if disk not in self.failed:
            return self.disks[disk][stripe]
        # Degraded read: the lost block is the XOR of every other block.
        survivors = [self.disks[k][stripe] for k in range(self.n) if k != disk]
        if any(k in self.failed for k in range(self.n) if k != disk):
            raise IOError(f"stripe {stripe} has two missing blocks: data lost")
        return xor_all(survivors)

    def update(self, index, value):
        # Read-modify-write: 2 reads and 2 writes, the RAID 5 write penalty.
        stripe, disk = self.locate(index)
        p = self.parity_disk(stripe)
        old = self.disks[disk][stripe]
        self.disks[p][stripe] ^= old ^ value
        self.disks[disk][stripe] = value

    def fail(self, disk):
        self.failed.add(disk)
        self.disks[disk] = [None] * len(self.disks[disk])

    def rebuild(self, disk):
        stripes = len(self.disks[(disk + 1) % self.n])
        self.failed.discard(disk)
        for s in range(stripes):
            others = [self.disks[k][s] for k in range(self.n) if k != disk]
            self.disks[disk][s] = xor_all(others)


def show(value):
    return format(value, "04b")


data = [0b1011, 0b0110, 0b1100, 0b0101, 0b1110, 0b0011, 0b1001, 0b0111, 0b0010]
array = Raid5(DISKS)
for i in range(0, len(data), DISKS - 1):
    array.write_stripe(data[i : i + DISKS - 1])

for s in range(3):
    row = [show(array.disks[k][s]) for k in range(DISKS)]
    print(f"stripe {s}: {' '.join(row)}  (parity on disk {array.parity_disk(s)})")

array.fail(1)
print("Disk 1 failed. D1 =", show(array.read(1)), " D4 =", show(array.read(4)))
print("All nine blocks readable:", [array.read(i) for i in range(9)] == data)

array.rebuild(1)
print("Rebuilt disk 1:", " ".join(show(b) for b in array.disks[1]))

array.update(0, 0b0000)
print("After writing D0 = 0000, P0 =", show(array.disks[3][0]))

array.fail(1)
array.fail(2)
try:
    array.read(1)
except IOError as error:
    print("Two disks failed:", error)
#include <bitset>
#include <iostream>
#include <optional>
#include <set>
#include <stdexcept>
#include <vector>

class Raid5 {
public:
    explicit Raid5(int disks) : n(disks), disks(disks) {}

    int parityDisk(int stripe) const {
        // Rotate parity so no single disk takes every parity write.
        return n - 1 - stripe % n;
    }

    void writeStripe(const std::vector<int>& data) {
        int stripe = disks[0].size(), p = parityDisk(stripe), next = 0, parity = 0;
        for (int v : data) parity ^= v;
        for (int k = 0; k < n; k++) disks[k].push_back(k == p ? parity : data[next++]);
    }

    int read(int index) const {
        auto [stripe, disk] = locate(index);
        if (!failed.count(disk)) return disks[disk][stripe];
        // Degraded read: the lost block is the XOR of every other block.
        int value = 0;
        for (int k = 0; k < n; k++) {
            if (k == disk) continue;
            if (failed.count(k)) {
                throw std::runtime_error("stripe " + std::to_string(stripe) +
                                         " has two missing blocks: data lost");
            }
            value ^= disks[k][stripe];
        }
        return value;
    }

    void update(int index, int value) {
        // Read-modify-write: 2 reads and 2 writes, the RAID 5 write penalty.
        auto [stripe, disk] = locate(index);
        int p = parityDisk(stripe);
        disks[p][stripe] ^= disks[disk][stripe] ^ value;
        disks[disk][stripe] = value;
    }

    void fail(int disk) {
        failed.insert(disk);
        for (int& b : disks[disk]) b = -1;
    }

    void rebuild(int disk) {
        failed.erase(disk);
        for (size_t s = 0; s < disks[disk].size(); s++) {
            int value = 0;
            for (int k = 0; k < n; k++) {
                if (k != disk) value ^= disks[k][s];
            }
            disks[disk][s] = value;
        }
    }

    int block(int disk, int stripe) const { return disks[disk][stripe]; }

private:
    int n;
    std::vector<std::vector<int>> disks;  // disks[k][stripe] -> block
    std::set<int> failed;

    std::pair<int, int> locate(int index) const {
        int stripe = index / (n - 1), offset = index % (n - 1);
        for (int k = 0; k < n; k++) {
            if (k == parityDisk(stripe)) continue;
            if (offset-- == 0) return {stripe, k};
        }
        return {stripe, -1};
    }
};

std::string show(int v) { return std::bitset<4>(v).to_string(); }

int main() {
    const int DISKS = 4;
    std::vector<int> data = {0b1011, 0b0110, 0b1100, 0b0101, 0b1110,
                             0b0011, 0b1001, 0b0111, 0b0010};
    Raid5 array(DISKS);
    for (size_t i = 0; i < data.size(); i += DISKS - 1) {
        array.writeStripe(std::vector<int>(data.begin() + i, data.begin() + i + DISKS - 1));
    }

    for (int s = 0; s < 3; s++) {
        std::cout << "stripe " << s << ":";
        for (int k = 0; k < DISKS; k++) std::cout << ' ' << show(array.block(k, s));
        std::cout << "  (parity on disk " << array.parityDisk(s) << ")\n";
    }

    array.fail(1);
    std::cout << "Disk 1 failed. D1 = " << show(array.read(1)) << "  D4 = " << show(array.read(4))
              << '\n';
    bool all = true;
    for (size_t i = 0; i < data.size(); i++) all = all && array.read(i) == data[i];
    std::cout << "All nine blocks readable: " << (all ? "True" : "False") << '\n';

    array.rebuild(1);
    std::cout << "Rebuilt disk 1:";
    for (int s = 0; s < 3; s++) std::cout << ' ' << show(array.block(1, s));
    std::cout << '\n';

    array.update(0, 0b0000);
    std::cout << "After writing D0 = 0000, P0 = " << show(array.block(3, 0)) << '\n';

    array.fail(1);
    array.fail(2);
    try {
        array.read(1);
    } catch (const std::runtime_error& error) {
        std::cout << "Two disks failed: " << error.what() << '\n';
    }
}
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    static class Raid5 {
        final int n;
        final List<List<Integer>> disks = new ArrayList<>(); // disks.get(k).get(stripe) -> block
        final Set<Integer> failed = new HashSet<>();

        Raid5(int n) {
            this.n = n;
            for (int k = 0; k < n; k++) disks.add(new ArrayList<>());
        }

        int parityDisk(int stripe) {
            // Rotate parity so no single disk takes every parity write.
            return n - 1 - stripe % n;
        }

        void writeStripe(List<Integer> data) {
            int stripe = disks.get(0).size(), p = parityDisk(stripe), next = 0, parity = 0;
            for (int v : data) parity ^= v;
            for (int k = 0; k < n; k++) disks.get(k).add(k == p ? parity : data.get(next++));
        }

        int[] locate(int index) {
            int stripe = index / (n - 1), offset = index % (n - 1);
            for (int k = 0; k < n; k++) {
                if (k == parityDisk(stripe)) continue;
                if (offset-- == 0) return new int[] {stripe, k};
            }
            return new int[] {stripe, -1};
        }

        int read(int index) {
            int[] at = locate(index);
            int stripe = at[0], disk = at[1];
            if (!failed.contains(disk)) return disks.get(disk).get(stripe);
            // Degraded read: the lost block is the XOR of every other block.
            int value = 0;
            for (int k = 0; k < n; k++) {
                if (k == disk) continue;
                if (failed.contains(k)) {
                    throw new IllegalStateException("stripe " + stripe + " has two missing blocks: data lost");
                }
                value ^= disks.get(k).get(stripe);
            }
            return value;
        }

        void update(int index, int value) {
            // Read-modify-write: 2 reads and 2 writes, the RAID 5 write penalty.
            int[] at = locate(index);
            int stripe = at[0], disk = at[1], p = parityDisk(stripe);
            int old = disks.get(disk).get(stripe);
            disks.get(p).set(stripe, disks.get(p).get(stripe) ^ old ^ value);
            disks.get(disk).set(stripe, value);
        }

        void fail(int disk) {
            failed.add(disk);
            List<Integer> d = disks.get(disk);
            for (int s = 0; s < d.size(); s++) d.set(s, -1);
        }

        void rebuild(int disk) {
            failed.remove(disk);
            List<Integer> d = disks.get(disk);
            for (int s = 0; s < d.size(); s++) {
                int value = 0;
                for (int k = 0; k < n; k++) {
                    if (k != disk) value ^= disks.get(k).get(s);
                }
                d.set(s, value);
            }
        }
    }

    static String show(int v) {
        return String.format("%4s", Integer.toBinaryString(v)).replace(' ', '0');
    }

    public static void main(String[] args) {
        final int DISKS = 4;
        List<Integer> data = List.of(0b1011, 0b0110, 0b1100, 0b0101, 0b1110, 0b0011, 0b1001, 0b0111, 0b0010);
        Raid5 array = new Raid5(DISKS);
        for (int i = 0; i < data.size(); i += DISKS - 1) array.writeStripe(data.subList(i, i + DISKS - 1));

        for (int s = 0; s < 3; s++) {
            StringBuilder row = new StringBuilder();
            for (int k = 0; k < DISKS; k++) row.append(' ').append(show(array.disks.get(k).get(s)));
            System.out.println("stripe " + s + ":" + row + "  (parity on disk " + array.parityDisk(s) + ")");
        }

        array.fail(1);
        System.out.println("Disk 1 failed. D1 = " + show(array.read(1)) + "  D4 = " + show(array.read(4)));
        boolean all = true;
        for (int i = 0; i < data.size(); i++) all &= array.read(i) == data.get(i);
        System.out.println("All nine blocks readable: " + (all ? "True" : "False"));

        array.rebuild(1);
        StringBuilder rebuilt = new StringBuilder();
        for (int s = 0; s < 3; s++) rebuilt.append(' ').append(show(array.disks.get(1).get(s)));
        System.out.println("Rebuilt disk 1:" + rebuilt);

        array.update(0, 0b0000);
        System.out.println("After writing D0 = 0000, P0 = " + show(array.disks.get(3).get(0)));

        array.fail(1);
        array.fail(2);
        try {
            array.read(1);
        } catch (IllegalStateException error) {
            System.out.println("Two disks failed: " + error.getMessage());
        }
    }
}
Watch it run

Step through it

Running on 4 disks, 9 data blocks of 4 bits, rotating parity

Disk 0D0····D3····D6····Disk 1D1····D4····P2····Disk 2D2····P1····D7····Disk 3P0····D5····D8····usable capacity = (n − 1) disks = 3 of 4
Step 1

Four disks, three stripes, RAID 5

RAID 5 splits data into blocks, spreads them across disks in stripes, and adds one parity block per stripe. Four disks give the capacity of three: 25% goes to parity, whatever the disk size.

Output
1 / 11
4

RAID 0 and RAID 1: Striping vs Mirroring

RAID 0 stripes blocks across all n disks with no redundancy. Reads and writes use every disk in parallel, so throughput scales with n and all capacity is usable. But the array fails if any disk fails, so it is about n times as likely to fail as one disk. It suits temporary data that can be regenerated.

RAID 1 writes every block to two (or more) disks. Reads can be served by whichever copy is less busy, so read performance improves; writes go to both, so they run at single-disk speed. Half the capacity is lost for two disks, but recovery is trivial: the surviving disk is the data, with no computation.

  • RAID 0 multiplies speed and multiplies the risk
  • RAID 1 halves capacity and needs no parity maths
  • Neither alone balances capacity, speed and safety; RAID 5 and 10 try to
5

RAID 6 and RAID 10

RAID 6 keeps two independent parity blocks per stripe. The first is plain XOR; the second is computed with Reed–Solomon arithmetic so that the two equations can solve for two unknowns. It survives any two simultaneous disk failures and costs two disks of capacity and a write penalty of 6.

The second parity matters because of rebuild time. Rebuilding a large disk reads every surviving disk end to end, which can take a day, and a second failure or an unreadable sector during that window destroys a RAID 5 array. RAID 6 stays protected throughout.

RAID 10 (RAID 1+0) mirrors disks in pairs and then stripes across the pairs. It has no parity, so writes cost only 2 operations and rebuilds are a plain copy. It survives one failure per mirror pair, and it costs half the raw capacity, which is why databases favour it.

  • RAID 6: two parity blocks, two failures, capacity n − 2
  • RAID 10: stripe over mirrors, no parity, capacity n/2
  • RAID 10 is not RAID 01: mirroring stripes survives fewer failure combinations
6

RAID 2, RAID 3 and RAID 4

These levels appear in operating-systems syllabuses but are no longer deployed. Each was overtaken by a level that removed its bottleneck.

  • RAID 3 and RAID 4 differ only in the stripe unit: a byte against a block
  • RAID 4 and RAID 5 differ only in where parity lives: one disk against all of them
7

Write Penalty, Rebuilds and Why RAID Is Not a Backup

A small write to RAID 5 cannot just write the block: the stripe's parity must change too. The controller reads the old data and old parity, computes new P = old P ⊕ old D ⊕ new D, then writes the new data and new parity. One logical write becomes four disk operations, the write penalty. RAID 6 needs six, RAID 1 and 10 need two, and RAID 0 needs one.

RAID protects against one thing: a disk failing. It does nothing against a file being deleted, overwritten by a bug, encrypted by ransomware, or lost in a fire, because the array faithfully applies that change to every disk. Backups are separate copies kept elsewhere; RAID is availability, not backup.

  • RAID 5 small write: 2 reads + 2 writes
  • Full-stripe writes avoid the penalty: parity is computed from the new data alone
  • Rebuilds are slow and stress the surviving disks
  • RAID keeps the system running; backups keep the data