Repository navigation
Operating Systems 09 files io
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: File system
- Wikipedia: Inode
- Wikipedia: Journaling file system
- Wikipedia: I/O scheduling
- Wikipedia: Interrupt
- Wikipedia: Direct memory access
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapters 11-14
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.
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.
| 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 |
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"]
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.
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"]
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"]
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 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
A file's data is freed only when its link count reaches 0 and no process still has it open.
| 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.
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
| 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 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.
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"]
(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
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"]
| 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) |
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
Handlers are split in two because interrupts must be handled fast; slow work is deferred.
Sources: Wikipedia: Interrupt, Wikipedia: Direct memory access
- 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. -
writereturning does not mean the data is on disk; usefsync. - Disk scheduling answers depend on direction and end-of-disk conventions; say which you use.
- 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.
- 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.
- 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.
- What is a file descriptor? A per-process integer index into the open-file table; 0, 1 and 2 are stdin, stdout and stderr.
- 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.
- 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.
- 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
fsyncor write-back. - Disk schedulers (SSTF, SCAN, LOOK, C-SCAN) cut seek distance; devices are driven by polling, interrupts and DMA.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look