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

Inodes

Everything about a file except its name and its data. The name lives in the directory, and that split is what makes hard links possible.

Inodes concept diagramTwo directory entries, report.txt and backup.txt, both point at inode 4012, which records mode, owner, size and a link count of 2 but no name. Its twelve direct pointers lead straight to data blocks 512 to 523, covering 48 KB. The single indirect pointer goes through one block of pointers, the double through two, and the triple through three before reaching data, so each level adds one extra read and reaches about 4 MB, 4 GB and 4 TB.directoryreport.txt4012backup.txt4012two names, one inode:a hard linkinode 4012moderw-r--r--owner1000size5 GBlinks2no filenameblock pointersdirect 0512direct 1513direct 11523single900datadouble120018449012tripleptrptrptrdata⋮⋮48 KB0 extra reads+4 MB+1 read+4 GB+2 reads+4 TB+3 readsgreen = data blockgrey = block of 1024 pointerscost follows size: a file under 48 KB never reads a pointer block
1

Metadata Without a Name

  1. Type and mode – regular file, directory, device or link, plus the permission bits.
  2. Owner – user ID and group ID.
  3. Size – length in bytes.
  4. Timestamps – last access (atime), last data change (mtime), last inode change (ctime).
  5. Link count – how many directory entries point at this inode.
  6. Block pointers – where the data blocks are.

What is an inode? It is the fixed-size record a Unix-style file system keeps for each file, holding everything it knows about the file except the name and the contents. The word is short for index node.

Every file, directory, device file and symbolic link has one inode, identified by an inode number that is unique within its file system. ls -i prints it. The name is kept in a directory entry, which pairs a name with an inode number; a directory is just a file full of those pairs. The inode structure has the same fixed fields for every file:

  • Inode = metadata + block pointers, never the name
  • Directory entry = (name, inode number)
  • stat and ls -l read only the inode, not the data
2

From Path to Inode

To open /home/a/report.txt, the kernel starts at the root directory's inode, whose number is fixed (2 on ext2, ext3 and ext4). It reads that directory's data, finds home and its inode number, reads that inode, then its data to find a, and so on until it reaches the inode of report.txt.

Each path component costs at least an inode read and a directory read, which is why the kernel caches recent lookups in the directory entry cache. Once the file is open, the process holds the inode, and the path is never consulted again; renaming the file at that point does not disturb the program reading it.

  • Lookup alternates: inode → directory data → next inode
  • The root directory's inode number is fixed
  • Renaming or moving a file changes directory entries only; the inode number stays
3

Direct and Indirect Blocks

  1. 12 direct pointers – name data blocks 0 to 11 directly: 12 × 4 KB = 48 KB, no extra read.
  2. Single indirect (pointer 12) – names a block of 1,024 pointers: 4 MB more, 1 extra read.
  3. Double indirect (pointer 13) – a block of pointers to pointer blocks: 1,024² blocks = 4 GB, 2 extra reads.
  4. Triple indirect (pointer 14) – one more level: 1,024³ blocks = 4 TB, 3 extra reads.

The inode is a fixed size, but files range from a few bytes to terabytes. The classic Unix answer (ext2 and ext3) is 15 pointers of increasing reach, assuming 4 KB blocks and 4-byte block numbers, so one block holds 4,096 ÷ 4 = 1,024 pointers.

Cost follows size. Small files pay nothing extra, and only the far end of a huge file pays three extra reads. This is the combined scheme from file allocation methods, and the same trade as a multilevel page table. Pointers for blocks never written stay empty, which is how sparse files use less disk than their size. ext4 replaces indirect blocks with extents, each recording a start block and a length, so a large contiguous file needs only a few entries.

  • Most files are small, so most reads use direct pointers
  • Each indirect level adds one read and multiplies the reach by 1,024
  • Unwritten blocks have empty pointers (sparse files)
Key reference

Terms, operations, and practical uses

Key terms

  • Inode numberIdentifies an inode within one file system; shown by ls -i.
  • Link countHow many directory entries name the inode.
  • Indirect blockA data block that holds block numbers instead of file data.
  • ExtentA start block plus a length; ext4's replacement for indirect blocks.
Implementation

One inode, from lookup to deletion

BLOCK_SIZE = 4096
POINTER_SIZE = 4
PER_BLOCK = BLOCK_SIZE // POINTER_SIZE   # 1024 pointers in one block
DIRECT = 12


def reach(block_index):
    """Which pointer class covers this block, and what it costs to read."""
    if block_index < DIRECT:
        return "direct", 0

    block_index -= DIRECT
    if block_index < PER_BLOCK:
        return "single indirect", 1

    block_index -= PER_BLOCK
    if block_index < PER_BLOCK ** 2:
        return "double indirect", 2

    block_index -= PER_BLOCK ** 2
    if block_index < PER_BLOCK ** 3:
        return "triple indirect", 3

    raise IndexError("beyond triple indirect")


def capacity():
    direct = DIRECT * BLOCK_SIZE
    single = PER_BLOCK * BLOCK_SIZE
    double = PER_BLOCK ** 2 * BLOCK_SIZE
    triple = PER_BLOCK ** 3 * BLOCK_SIZE
    return direct, single, double, triple


def main():
    for offset in (0, 40960, 100_000, 10_000_000, 10_000_000_000):
        index = offset // BLOCK_SIZE
        kind, reads = reach(index)
        print(f"offset {offset:>14,}  block {index:>10,}  {kind:<16} {reads} extra read(s)")

    direct, single, double, triple = capacity()
    print(f"\ndirect          {direct // 1024:>10} KB")
    print(f"+ single        {single // 1024:>10} KB")
    print(f"+ double        {double // (1024 ** 3):>10} GB")
    print(f"+ triple        {triple // (1024 ** 4):>10} TB")


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

constexpr long BLOCK_SIZE = 4096;
constexpr long POINTER_SIZE = 4;
constexpr long PER_BLOCK = BLOCK_SIZE / POINTER_SIZE;  // 1024 pointers
constexpr long DIRECT = 12;

// Which pointer class covers this block, and what it costs to read.
std::pair<std::string, int> reach(long blockIndex) {
    if (blockIndex < DIRECT) return {"direct", 0};

    blockIndex -= DIRECT;
    if (blockIndex < PER_BLOCK) return {"single indirect", 1};

    blockIndex -= PER_BLOCK;
    if (blockIndex < PER_BLOCK * PER_BLOCK) return {"double indirect", 2};

    blockIndex -= PER_BLOCK * PER_BLOCK;
    if (blockIndex < PER_BLOCK * PER_BLOCK * PER_BLOCK) return {"triple indirect", 3};

    throw std::out_of_range("beyond triple indirect");
}

std::string commas(long n) {
    std::string s = std::to_string(n);
    for (int i = (int)s.size() - 3; i > 0; i -= 3) s.insert(i, ",");
    return s;
}

int main() {
    for (long offset : {0L, 40960L, 100000L, 10000000L, 10000000000L}) {
        const long index = offset / BLOCK_SIZE;
        auto [kind, reads] = reach(index);
        std::cout << "offset " << std::setw(14) << commas(offset)
                  << "  block " << std::setw(10) << commas(index)
                  << "  " << std::left << std::setw(17) << kind << std::right
                  << reads << " extra read(s)\n";
    }

    const long direct = DIRECT * BLOCK_SIZE;
    const long single = PER_BLOCK * BLOCK_SIZE;
    const long dbl = PER_BLOCK * PER_BLOCK * BLOCK_SIZE;
    const long triple = PER_BLOCK * PER_BLOCK * PER_BLOCK * BLOCK_SIZE;

    std::cout << "\ndirect          " << std::setw(10) << direct / 1024 << " KB\n";
    std::cout << "+ single        " << std::setw(10) << single / 1024 << " KB\n";
    std::cout << "+ double        " << std::setw(10) << dbl / (1024L * 1024 * 1024) << " GB\n";
    std::cout << "+ triple        " << std::setw(10)
              << triple / (1024L * 1024 * 1024 * 1024) << " TB\n";
    return 0;
}
public class Main {
    private static final long BLOCK_SIZE = 4096;
    private static final long POINTER_SIZE = 4;
    private static final long PER_BLOCK = BLOCK_SIZE / POINTER_SIZE;  // 1024
    private static final long DIRECT = 12;

    // Which pointer class covers this block, and what it costs to read.
    private static Object[] reach(long blockIndex) {
        if (blockIndex < DIRECT) return new Object[] {"direct", 0};

        blockIndex -= DIRECT;
        if (blockIndex < PER_BLOCK) return new Object[] {"single indirect", 1};

        blockIndex -= PER_BLOCK;
        if (blockIndex < PER_BLOCK * PER_BLOCK) return new Object[] {"double indirect", 2};

        blockIndex -= PER_BLOCK * PER_BLOCK;
        if (blockIndex < PER_BLOCK * PER_BLOCK * PER_BLOCK) {
            return new Object[] {"triple indirect", 3};
        }
        throw new IndexOutOfBoundsException("beyond triple indirect");
    }

    public static void main(String[] args) {
        for (long offset : new long[] {0L, 40960L, 100000L, 10000000L, 10000000000L}) {
            long index = offset / BLOCK_SIZE;
            Object[] r = reach(index);
            System.out.printf("offset %,14d  block %,10d  %-16s %d extra read(s)%n",
                    offset, index, r[0], (Integer) r[1]);
        }

        long direct = DIRECT * BLOCK_SIZE;
        long single = PER_BLOCK * BLOCK_SIZE;
        long dbl = PER_BLOCK * PER_BLOCK * BLOCK_SIZE;
        long triple = PER_BLOCK * PER_BLOCK * PER_BLOCK * BLOCK_SIZE;

        System.out.printf("%ndirect          %10d KB%n", direct / 1024);
        System.out.printf("+ single        %10d KB%n", single / 1024);
        System.out.printf("+ double        %10d GB%n", dbl / (1024L * 1024 * 1024));
        System.out.printf("+ triple        %10d TB%n", triple / (1024L * 1024 * 1024 * 1024));
    }
}
Watch it run

Step through it

Running on inode 12 of /home/a/report.txt; 4 KB blocks, 4-byte pointers, 12 direct

open("/home/a/report.txt")directory /home/a: name → inodereport.txt12notes.md15inode 12type · modefile · rw-r--r--owneruid 1000size10 GBtimesatime mtime ctimelinks1open by0 processesblock pointers (no file name here)[0]…[11] direct[12] single[13] double[14] tripledirectory entry: report.txt → 12the inode holds everything else
Step 1

The name lives in the directory

Opening /home/a/report.txt starts in the directory, which is a file of (name, inode number) pairs. report.txt maps to inode 12. The name is used once, to find that number, and is never stored in the inode.

Output
1 / 12
4

Worked Example: Which Pointer Holds a Byte

Maximum file size. Add the blocks each pointer can reach and multiply by the block size: (12 + 1,024 + 1,024² + 1,024³) × 4,096 = 49,152 + 4,194,304 + 4,294,967,296 + 4,398,046,511,104 = 4,402,345,721,856 bytes, just over 4 TB. The triple indirect pointer contributes almost all of it.

  • Block size – 4 KB (4,096 bytes); block numbers are 4 bytes, so 1,024 per block.
  • Inode – 12 direct, 1 single, 1 double and 1 triple indirect pointer.
  • Questions – the largest possible file, and the path to byte 10,000,000.

Byte 10,000,000. Block index = ⌊10,000,000 ÷ 4,096⌋ = 2,441. That is past the 12 direct blocks and the 1,024 single-indirect blocks, so subtract both: 2,441 − 12 − 1,024 = 1,405 blocks into the double range. Each entry of the outer block covers 1,024 blocks, so 1,405 = 1 × 1,024 + 381: entry 1 of the outer block, then entry 381 of that inner block. The read costs the inode, two pointer blocks and the data block: 2 extra reads.

With 1 KB blocks the same method gives 256 pointers per block and a maximum of (12 + 256 + 256² + 256³) × 1 KB ≈ 16 GB, which is why larger blocks were needed for large files.

  • Pointers per block = block size ÷ pointer size
  • Subtract the earlier ranges, then divide by 1,024 per level
  • Max size = (direct + p + p² + p³) × block size
5

Hard Links and the Link Count

Because the name lives in the directory, two directory entries can hold the same inode number. That is a hard link: two names for one file, with no copy and no original. The inode's link count records how many names it has.

rm calls unlink, which removes one name and lowers the count. The data is freed only when the count is 0 and no process has the file open. That is why deleting a large log that a server is still writing frees no space until the server closes it.

A symbolic link is different: it has its own inode, whose data is a path. It can point across file systems and to directories, and it dangles if the target is removed. A hard link cannot cross file systems, because an inode number means nothing outside its own file system, and most systems forbid hard links to directories so the tree cannot gain cycles. See file systems for links in the wider directory tree.

  • Hard link = another directory entry, same inode
  • Freed only when link count = 0 and open count = 0
  • Symlink = own inode holding a path; can dangle and cross file systems
6

Running Out of Inodes

  1. ls -i – the inode number of each file.
  2. stat file – every field of the inode.
  3. df -i – inodes used and free per file system.
  4. find . -inum N – every name for inode N, which is how hard links are found.

ext2, ext3 and ext4 create the inode table when the file system is formatted, by default one 256-byte inode for every 16 KB of disk, about 1.5% of the space. That fixes the maximum number of files for the life of the file system.

A directory of millions of tiny files, such as a mail spool or a cache, can use every inode while most blocks are still free. Creating a file then fails with "No space left on device" even though df -h shows free space; df -i shows the real cause. The fix is deleting files or reformatting with more inodes (mkfs.ext4 -i). XFS and Btrfs allocate inodes on demand and do not have this limit.

The superblock records the inode and block counts, the block size and where the inode table starts. Losing it would make the file system unreadable, so ext file systems keep backup copies across the disk.

  • Inode count is fixed at format time on ext file systems
  • Many tiny files can exhaust inodes before blocks
  • The superblock is copied across the disk for safety