Skip to content

Operating Systems 09 files io

Mugundan edited this page Nov 27, 2026 · 1 revision

Files, Storage and I/O

Relevant source files

The following references were used as context for generating this wiki page:

A file system turns a disk, which is just a long row of numbered blocks, into named files and folders with permissions. Underneath, the OS talks to devices using interrupts and DMA, and decides the order in which disk requests are served. Interviews ask about inodes, hard versus soft links, journaling, file descriptors, disk scheduling and polling versus interrupts.

All disk-scheduling totals on this page were computed with a short script.

Purpose and Scope

This page covers files and file descriptors, directories and inodes, hard and symbolic links, block allocation, journaling, the page cache, disk scheduling (FCFS, SSTF, SCAN, LOOK, C-SCAN, C-LOOK) with a worked example, and I/O methods (polling, interrupts, DMA). System calls are on Kernel and System Calls.

The Library Catalogue Analogy

Library File system
Shelves of numbered slots Disk blocks
A catalogue card: author, size, which slots hold the book An inode
The alphabetical index: title → card number A directory: name → inode number
Two index entries pointing to the same card A hard link
A note saying "see the entry for X" A symbolic link
A librarian's log of changes in progress A journal

Files and File Descriptors

To a program a file is a sequence of bytes. It opens a file and gets back a small integer, the file descriptor (fd).

// illustrative
int fd = open("notes.txt", O_RDONLY);   // e.g. returns 3
char buf[100];
ssize_t n = read(fd, buf, sizeof buf);  // read up to 100 bytes
close(fd);
flowchart LR
    subgraph P["Process"]
        FD["fd table<br/>0 stdin, 1 stdout, 2 stderr, 3 →"]
    end
    FD -->|"3"| OF["Open-file entry<br/>current offset, mode"]
    OF --> IN["Inode<br/>size, owner, block pointers"]
    IN --> B["Data blocks on disk"]
Loading

Three levels: the per-process fd table, a system-wide open-file table (holding the current read/write offset), and the inode. After fork, parent and child share the same open-file entries, so they share the file offset.

Inodes and Directories

On Unix-like file systems each file has an inode holding everything about it except its name:

In the inode Not in the inode
Type, permissions, owner, size, timestamps The file name
Link count
Pointers to the data blocks

A directory is a special file that maps names to inode numbers. Looking up /home/ana/notes.txt reads the root directory, finds home, reads that directory, finds ana, and so on.

flowchart LR
    R["/ (inode 2)"] -->|"home"| H["home (inode 11)"]
    H -->|"ana"| A["ana (inode 340)"]
    A -->|"notes.txt"| N["inode 812<br/>size, owner, blocks"]
    N --> D["data blocks"]
Loading

Block Pointers in a Classic Inode

flowchart LR
    I["Inode"] --> D1["12 direct pointers → data blocks"]
    I --> S["single indirect → block of pointers → data"]
    I --> DB["double indirect → pointers → pointers → data"]
    I --> T["triple indirect → three levels → data"]
Loading

Small files need only direct pointers (fast); big files use the indirect levels. Modern file systems such as ext4 use extents instead: (start block, length) runs.

Sources: Wikipedia: Inode, Wikipedia: File system

Hard Links and Symbolic Links

Hard link Symbolic (soft) link
What it is Another directory entry for the same inode A small file containing a path
Command ln a b ln -s a b
Delete the original name File still exists (link count > 0) Link becomes dangling
Across file systems No Yes
To a directory Usually not allowed Yes
flowchart TD
    subgraph Hard["Hard link"]
        n1["name: a"] --> i1["inode 812 (links = 2)"]
        n2["name: b"] --> i1
    end
    subgraph Soft["Symbolic link"]
        s1["name: c (inode 900)<br/>contents: 'a'"] -.->|"path lookup"| n3["name: a"] --> i2["inode 812"]
    end
Loading

A file's data is freed only when its link count reaches 0 and no process still has it open.

Allocating Blocks

Method Idea Good Bad
Contiguous Each file in one run of blocks Fast sequential and random access External fragmentation; hard to grow
Linked Each block points to the next (FAT keeps the chain in a table) No fragmentation Slow random access
Indexed An index block (or inode) lists all blocks Fast random access Index overhead
Extents List of (start, length) runs Compact, fast More complex

Free space is tracked with a bitmap (one bit per block) or a free list.

Journaling and Crash Consistency

Creating a file touches several blocks: the inode, the directory, the free-space bitmap. If power fails halfway, the file system can be left inconsistent.

sequenceDiagram
    participant FS as File system
    participant J as Journal (log)
    participant D as Main disk area
    FS->>J: 1. write intended changes
    FS->>J: 2. write "commit" record
    FS->>D: 3. apply changes in place (checkpoint)
    FS->>J: 4. mark transaction done
    Note over FS,D: crash before 2: ignore it. Crash after 2: replay from journal
Loading
Journal mode (ext4 names) What is logged Trade-off
journal Metadata and data Safest, slowest
ordered (default) Metadata only; data written before its metadata commits Good balance
writeback Metadata only, no ordering Fastest; files may contain stale data after a crash

Without a journal, recovery needs a full scan (fsck). Copy-on-write file systems (btrfs, ZFS) avoid in-place updates altogether.

Sources: Wikipedia: Journaling file system

The Page Cache

The kernel keeps recently used file data in otherwise free RAM. read often copies from RAM without touching the disk; write usually just updates the cache and marks pages dirty, and they are written back later. fsync(fd) forces them to disk. That is why a crash can lose data that write already "returned" for.

Disk Scheduling

For a hard disk the slow part is moving the head (seek). The OS reorders pending requests to cut total head movement.

Worked example. Cylinders 0-199, head at 53, pending requests:

98, 183, 37, 122, 14, 124, 65, 67
Algorithm Rule Order served Total head movement
FCFS In arrival order 98, 183, 37, 122, 14, 124, 65, 67 640
SSTF Nearest request next 65, 67, 37, 14, 98, 122, 124, 183 236
SCAN (elevator), moving toward 0 Sweep to the end of the disk, then reverse 37, 14, (0), 65, 67, 98, 122, 124, 183 236
LOOK, moving toward 0 Like SCAN but turn at the last request 37, 14, 65, 67, 98, 122, 124, 183 208
C-SCAN, moving toward 199 Sweep up to the end, jump to 0, sweep up again 65, 67, 98, 122, 124, 183, (199), (0), 14, 37 382 counting the 199 → 0 return; 183 if the return is not counted
C-LOOK, moving toward 199 Up to the last request, jump to the lowest request 65, 67, 98, 122, 124, 183, 14, 37 322 counting the jump
flowchart LR
    S["head 53"] --> A["37"] --> B["14"] --> C["turn at 14"] --> D["65"] --> E["67"] --> F["98"] --> G["122"] --> H["124"] --> I["183"]
Loading

(The diagram shows LOOK: 53 − 14 = 39, then 183 − 14 = 169, total 208.)

Algorithm Pros Cons
FCFS Fair Lots of movement
SSTF Low movement Can starve far requests
SCAN / LOOK No starvation, low movement Middle cylinders get better service
C-SCAN / C-LOOK More uniform waiting time Return sweep costs movement

SSDs have no head, so modern Linux uses simple or deadline-based I/O schedulers (none, mq-deadline, bfq) that focus on merging and fairness instead.

Trap: always state the starting direction, whether SCAN goes to the physical end, and whether you count the C-SCAN return jump; answers differ by convention.

Sources: Wikipedia: I/O scheduling

How the OS Talks to Devices

flowchart TD
    Q["How does the CPU learn the device is ready?"] --> PO["Polling<br/>CPU keeps checking a status register"]
    Q --> IN["Interrupts<br/>device signals the CPU when done"]
    IN --> DMA["DMA<br/>device copies the data to memory itself,<br/>interrupts once at the end"]
Loading
Method CPU work Best for
Polling (busy waiting) CPU loops checking status Very fast devices or very short waits (high-speed NICs and NVMe can poll)
Interrupt-driven CPU does other work; handler runs when the device interrupts Slow or unpredictable devices (keyboard, network)
DMA CPU only sets up the transfer; the DMA engine moves the data Large transfers (disk, network buffers)

Interrupt Handling

sequenceDiagram
    participant D as Device
    participant C as CPU
    participant K as Kernel
    D->>C: interrupt line raised
    C->>K: finish current instruction, save state, jump to handler
    K->>K: top half: acknowledge device, grab data quickly
    K->>K: schedule bottom half (softirq / work queue) for slower work
    K->>C: restore state, return to interrupted code
Loading

Handlers are split in two because interrupts must be handled fast; slow work is deferred.

Sources: Wikipedia: Interrupt, Wikipedia: Direct memory access

Common Traps

  • The file name is in the directory, not the inode.
  • Deleting a file (unlink) removes a name; the data stays while other links or open fds exist.
  • write returning does not mean the data is on disk; use fsync.
  • Disk scheduling answers depend on direction and end-of-disk conventions; say which you use.

Interview Questions

  1. What is an inode? A structure holding a file's metadata (type, permissions, owner, size, timestamps, link count) and the locations of its data blocks, but not its name.
  2. Hard link vs soft link? A hard link is another name for the same inode; a soft link is a file containing a path, which can dangle or cross file systems.
  3. What does journaling do? Writes intended metadata changes to a log and commits them before applying in place, so after a crash the file system can replay or discard incomplete operations instead of running a full check.
  4. What is a file descriptor? A per-process integer index into the open-file table; 0, 1 and 2 are stdin, stdout and stderr.
  5. Solve SSTF for head 53 and requests 98, 183, 37, 122, 14, 124, 65, 67. Order 65, 67, 37, 14, 98, 122, 124, 183; total 236.
  6. Polling vs interrupts vs DMA? Polling wastes CPU but has low latency; interrupts free the CPU until the device is ready; DMA lets the device move data itself with one interrupt at the end.

Key Points

  • Directories map names to inodes; inodes hold metadata and block pointers; hard links share an inode, soft links store a path.
  • Journaling makes multi-block updates crash-safe; the page cache delays writes until fsync or write-back.
  • Disk schedulers (SSTF, SCAN, LOOK, C-SCAN) cut seek distance; devices are driven by polling, interrupts and DMA.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally