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

File Allocation Methods

Three ways to record which disk blocks hold a file. They differ most in one thing: what it costs to reach a block in the middle of the file.

File Allocation Methods concept diagramFile F, six blocks long, stored three ways while reading block index 5. Contiguous: the directory holds start 20 and length 6, so the block is 20 plus 5, block 25, with no extra reads. Linked: the directory holds first block 20 and the chain 20, 33, 47, 48, 61, 72 must be walked, five extra reads. Indexed: the directory points at index block 19, whose slot 5 names block 72, one extra read.directory entrydisk blocks of F · target: block index 5 (byte 20480)contiguousstart 20 · len 620212223242520 + 5 = 250 extra readslinkedfirst 20203347486172walk chain5 extra readsindexedindex block 19020133247348461572block 19, one pointer per slot72index[5] = 721 extra read
1

Blocks, Not Bytes

  1. Contiguous – the file occupies one run of consecutive blocks.
  2. Linked – each block stores the number of the next block.
  3. Indexed – an index block lists all of the file's blocks in order.

A user sees a file as one stream of bytes. The disk offers fixed-size blocks, often 4 KB, that may be anywhere. File allocation methods are the operating system's rules for recording which blocks belong to a file and in what order.

Each method answers one question: given a byte offset in a file, which disk block holds it? Divide the offset by the block size to get the block index, then the method maps that index to a disk block. The methods differ in what that mapping costs, in how much space is wasted, and in whether a file can grow.

Allocation is not the same as file access methods. Allocation is how the OS places blocks on disk; access is how a program moves through the file's records. The two meet in one place: linked allocation makes direct access slow.

  • Block index = byte offset ÷ block size
  • Judge each method on random access, sequential access, wasted space and growth
  • The directory entry holds whatever the method needs to start the lookup
2

Contiguous Allocation

Contiguous allocation stores a file in consecutive blocks. The directory entry needs two numbers: the start block and the length. Block index i is at start + i, computed without reading anything, and sequential reads are as fast as a disk allows because the head hardly moves.

The problem is free space. As files are created and deleted, the free blocks split into short runs, and a new file may not fit in any of them even when the total free space is large. This is external fragmentation, the same problem contiguous memory allocation has, with the same costly cure: compaction, which on disk means copying whole files.

Growth is the second problem. A file that outgrows its run must be copied to a longer one, so the size has to be known or guessed when the file is created. Read-only media such as CD-ROMs, where files never grow, still use it. Modern file systems such as ext4, NTFS and XFS keep the idea as extents: a file is a short list of contiguous runs, which keeps most of the speed without the rigid size.

  • Good: O(1) random access, computed rather than looked up
  • Good: fastest sequential reads
  • Bad: external fragmentation, plus internal waste in the last block
  • Bad: the file cannot grow in place; its size must be guessed at creation
3

Linked Allocation

Linked allocation turns the file into a linked list on disk. Each block keeps a few bytes for the number of the next block, and the directory stores the first block (and often the last, so appending is quick).

Any free block can be used, so there is no external fragmentation, and a file grows by linking one more block. Reading from start to end works well.

Random access does not. The pointer to block i is stored inside block i − 1, so reaching block index i means reading the i blocks before it. Block 5,000 of a file costs 5,000 reads. The pointers also take space in every block (4 bytes of a 512-byte block is 0.78%), and one damaged pointer cuts off the rest of the file.

  • Good: no external fragmentation; files grow freely
  • Bad: random access is O(n) disk reads
  • Bad: a little space lost in every block; grouping blocks into clusters reduces it
  • Bad: one bad pointer loses everything after it
Key reference

Terms, operations, and practical uses

Key terms

  • ExtentA run of contiguous blocks; a file is a short list of extents.
  • ClusterA group of blocks allocated together, to cut pointer and table overhead.
  • Index blockHolds the disk block number of each block of one file.
  • FAT entryThe block after this one, an end marker, or 0 for free.
Implementation

Finding byte 20480 of file F

BLOCK_SIZE = 4096
POINTERS_PER_BLOCK = BLOCK_SIZE // 4


def contiguous(start, length, offset):
    """Arithmetic only - no lookup, no extra read."""
    block_index = offset // BLOCK_SIZE
    if block_index >= length:
        raise IndexError("past end of file")
    return start + block_index, 0


def linked(chain, offset):
    """Every block must be read to find the next one."""
    block_index = offset // BLOCK_SIZE
    reads = 0
    block = chain[0]
    for _ in range(block_index):
        reads += 1
        block = chain[chain.index(block) + 1]
    return block, reads


def indexed(index_block, offset):
    """One read of the index block, then straight to the data."""
    block_index = offset // BLOCK_SIZE
    return index_block[block_index], 1


def main():
    length = 6
    start = 20
    chain = [20, 33, 47, 48, 61, 72]

    print(f"{'offset':>8} {'contig':>8} {'linked':>16} {'indexed':>14}")
    for offset in (0, 4096, 20480):
        c_block, c_reads = contiguous(start, length, offset)
        l_block, l_reads = linked(chain, offset)
        i_block, i_reads = indexed(chain, offset)
        print(f"{offset:>8} {c_block:>4} ({c_reads})"
              f" {l_block:>10} ({l_reads})"
              f" {i_block:>10} ({i_reads})")

    print(f"\nextra reads to reach the last block:")
    print(f"  contiguous  0")
    print(f"  linked      {linked(chain, 20480)[1]}")
    print(f"  indexed     1")
    print(f"  one index block addresses {POINTERS_PER_BLOCK} blocks"
          f" = {POINTERS_PER_BLOCK * BLOCK_SIZE // (1024 * 1024)} MB")


if __name__ == "__main__":
    main()
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <vector>

constexpr int BLOCK_SIZE = 4096;
constexpr int POINTERS_PER_BLOCK = BLOCK_SIZE / 4;

// Arithmetic only - no lookup, no extra read.
std::pair<int, int> contiguous(int start, int length, int offset) {
    const int blockIndex = offset / BLOCK_SIZE;
    if (blockIndex >= length) throw std::out_of_range("past end of file");
    return {start + blockIndex, 0};
}

// Every block must be read to find the next one.
std::pair<int, int> linked(const std::vector<int>& chain, int offset) {
    const int blockIndex = offset / BLOCK_SIZE;
    int reads = 0;
    int at = 0;
    for (int i = 0; i < blockIndex; ++i) {
        ++reads;
        ++at;
    }
    return {chain[at], reads};
}

// One read of the index block, then straight to the data.
std::pair<int, int> indexed(const std::vector<int>& indexBlock, int offset) {
    return {indexBlock[offset / BLOCK_SIZE], 1};
}

int main() {
    const int length = 6;
    const int start = 20;
    const std::vector<int> chain = {20, 33, 47, 48, 61, 72};

    std::cout << std::setw(8) << "offset" << std::setw(9) << "contig"
              << std::setw(17) << "linked" << std::setw(15) << "indexed" << "\n";
    for (int offset : {0, 4096, 20480}) {
        auto [cB, cR] = contiguous(start, length, offset);
        auto [lB, lR] = linked(chain, offset);
        auto [iB, iR] = indexed(chain, offset);
        std::cout << std::setw(8) << offset
                  << std::setw(5) << cB << " (" << cR << ")"
                  << std::setw(11) << lB << " (" << lR << ")"
                  << std::setw(11) << iB << " (" << iR << ")\n";
    }

    std::cout << "\nextra reads to reach the last block:\n";
    std::cout << "  contiguous  0\n";
    std::cout << "  linked      " << linked(chain, 20480).second << "\n";
    std::cout << "  indexed     1\n";
    std::cout << "  one index block addresses " << POINTERS_PER_BLOCK
              << " blocks = "
              << static_cast<long>(POINTERS_PER_BLOCK) * BLOCK_SIZE / (1024 * 1024)
              << " MB\n";
    return 0;
}
public class Main {
    private static final int BLOCK_SIZE = 4096;
    private static final int POINTERS_PER_BLOCK = BLOCK_SIZE / 4;

    // Arithmetic only - no lookup, no extra read.
    private static int[] contiguous(int start, int length, int offset) {
        int blockIndex = offset / BLOCK_SIZE;
        if (blockIndex >= length) throw new IndexOutOfBoundsException("past end of file");
        return new int[] {start + blockIndex, 0};
    }

    // Every block must be read to find the next one.
    private static int[] linked(int[] chain, int offset) {
        int blockIndex = offset / BLOCK_SIZE;
        int reads = 0;
        int at = 0;
        for (int i = 0; i < blockIndex; i++) {
            reads++;
            at++;
        }
        return new int[] {chain[at], reads};
    }

    // One read of the index block, then straight to the data.
    private static int[] indexed(int[] indexBlock, int offset) {
        return new int[] {indexBlock[offset / BLOCK_SIZE], 1};
    }

    public static void main(String[] args) {
        int length = 6;
        int start = 20;
        int[] chain = {20, 33, 47, 48, 61, 72};

        System.out.printf("%8s %8s %16s %14s%n", "offset", "contig", "linked", "indexed");
        for (int offset : new int[] {0, 4096, 20480}) {
            int[] c = contiguous(start, length, offset);
            int[] l = linked(chain, offset);
            int[] i = indexed(chain, offset);
            System.out.printf("%8d %4d (%d) %10d (%d) %10d (%d)%n",
                    offset, c[0], c[1], l[0], l[1], i[0], i[1]);
        }

        System.out.println("\nextra reads to reach the last block:");
        System.out.println("  contiguous  0");
        System.out.println("  linked      " + linked(chain, 20480)[1]);
        System.out.println("  indexed     1");
        System.out.printf("  one index block addresses %d blocks = %d MB%n",
                POINTERS_PER_BLOCK, (long) POINTERS_PER_BLOCK * BLOCK_SIZE / (1024 * 1024));
    }
}
Watch it run

Step through it

Running on file F of 6 blocks (4 KB each); read byte 20480 = block index 5

file F: 6 blocks of 4 KBother files G and H already use some blocks19H20212223242526G27G33474861G72…………byte 20480 ÷ 4096 = block index 5where on disk is it?
Step 1

One question for every method

File F is 6 blocks of 4 KB. A program asks for byte 20480. Dividing by the block size gives block index 5, the sixth block of F. Each allocation method must turn 'block index 5 of F' into a disk block number, and the cost of doing that is what separates them.

Output
1 / 13
4

The File Allocation Table

The file allocation table (FAT), used by MS-DOS and still by USB drives and SD cards, keeps linked allocation but moves every next-block number out of the data blocks into one table at the start of the volume. Entry b holds the number of the block after b, a special value marks the end of a file, and 0 marks a free block.

Once the table is cached in memory, following a chain needs no disk reads, so random access becomes fast again. The cost is the table itself: it has one entry per cluster, so it grows with the disk. A 1 TB disk with 4 KB clusters has 2^28 clusters, about 1 GB of FAT at 4 bytes per entry. FAT32 also limits a single file to 4 GB, because the directory entry stores the size in 32 bits.

  • Same chain as linked allocation, kept in one table
  • Cached table: chain walks cost no disk reads
  • Free space is just the entries marked 0
  • Table size grows with the disk
5

Indexed Allocation

Indexed allocation gives each file an index block: an array whose entry i holds the disk block of the file's block i. The directory points at the index block.

Reaching any block costs one extra read, for the index block, then the data block. Random access is O(1) for every offset, and like linked allocation there is no external fragmentation.

Small files pay for this: a 1 KB file still needs a whole index block. Large files hit a ceiling: a 4 KB index block of 4-byte block numbers holds 1,024 entries, so it can describe at most 1,024 × 4 KB = 4 MB.

  • Good: O(1) random access with one extra read
  • Good: no external fragmentation; files grow by filling index entries
  • Bad: a full index block even for a tiny file
  • Bad: one index block caps the file size
6

Indexing Schemes for Large Files

  1. Linked scheme – the last entry of each index block points to the next index block. Simple, but reaching the tenth index block means reading the nine before it.
  2. Multi-level index – an outer index block points to inner index blocks, the same idea as multilevel paging.
  3. Combined scheme – a few direct pointers, then single, double and triple indirect pointers for larger files.

Three schemes lift the one-index-block limit. They differ in what it costs to reach a block far into the file.

A two-level index of 4 KB blocks reaches 1,024 × 1,024 blocks, which is 4 GB, at two extra reads for any block. The combined scheme is the one Unix uses: small files never touch an indirect block, so they pay nothing extra. Its full layout is in inodes.

  • Linked index blocks: cost grows with the offset
  • Multi-level: the same cost for every offset
  • Combined: no extra cost for small files
7

Worked Example: Disk I/O to Add or Remove a Block

A standard exam question asks how many disk reads and writes each method needs to change the file. Count them one by one.

  • File – 100 blocks long.
  • In memory – the directory entry (and, for indexed, the index block) and the data of any new block.
  • Contiguous – there is room to grow at the end of the file, but not before it.
  • Linked – the directory keeps both the first and the last block.

Add at the start. Contiguous must shift all 100 blocks one place (100 reads and 100 writes) and write the new block: 201. Linked writes the new block pointing at the old first block: 1. Indexed writes the block and updates the index in memory: 1.

Add in the middle (after block 50). Contiguous shifts blocks 51 to 100 (50 reads, 50 writes) and writes the new one: 101. Linked reads blocks 1 to 50 to reach block 50, writes the new block, and rewrites block 50 with the new pointer: 52.

Add at the end. Contiguous writes 1 block. Linked reads the last block, writes the new block, and rewrites the old last block to point at it: 3.

Remove the last block. Contiguous and indexed just change the length: 0. Linked must find the second-to-last block by reading blocks 1 to 99, then rewrite it as the new end: 100.

Disk I/O operations on a 100-block file
OperationContiguousLinkedIndexed
Add a block at the start20111
Add a block in the middle101521
Add a block at the end131
Remove the first block010
Remove the middle block (51)98520
Remove the last block01000
  • Contiguous pays to shift blocks; linked pays to walk the chain
  • Indexed pays one write at most once the index is in memory
  • Removing the first block: contiguous moves its start, linked reads block 1 for the new first
8

Contiguous vs Linked vs Indexed

No real file system uses one pure method. FAT is linked allocation with the pointers in a table, Unix file systems use the inode's combined index, and ext4, NTFS and XFS store runs of contiguous blocks as extents.

The three file allocation methods compared
ContiguousLinkedIndexed
Reach block istart + i, 0 readsi reads1 read (index block)
Sequential readsFastestGoodGood
External fragmentationYesNoNo
File can growOnly into free space after itYesYes, until the index is full
Space overheadNoneA pointer per blockAn index block per file
  • Read-only or fixed-size files: contiguous
  • Mostly sequential, simple devices: linked via a FAT
  • General-purpose disks: indexed (inodes) or extents