# OSTEP - Notes on the Persistence Part

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/ostep-note-persistence/>). I am continuously working to improve the translation.

# Chapter 36 I/O Devices

The main purpose of this chapter is to **establish a basic model for how the OS interacts with devices**.

## System Architecture of Modern Computers

- The CPU and memory are interconnected via a very fast memory bus;
- Graphics cards, network cards, and high-performance storage may be attached to a faster general-purpose I/O bus, such as PCIe;
- Keyboards, mice, ordinary disks, and USB devices may be attached to slower peripheral buses.

The rationale: high-performance devices are placed close to the CPU, while slow devices hang off the periphery.

## Abstraction of a Standard Device

- **Interface**: the side that the OS can see and operate on.
- **Internals**: how the device concretely does its work inside.

The interface manifests as a set of registers:

- **status register**: the status register, used to check whether the device is busy, has finished, or has errors.
- **command register**: the command register, used to tell the device what to do.
- **data register**: the data register, used to pass data in or out.

The OS mainly interacts with the device through the interface it exposes, and **does not care about its internals**.

A naive device protocol (**polling + PIO**):

```C
while (STATUS == BUSY)
    ; // wait until device is not busy

Write data to DATA register;
Write command to COMMAND register;

while (STATUS == BUSY)
    ; // wait until device is done
```

First wait until it is not `BUSY`, then write to the `DATA` register (this step is called **PIO (Programmed I/O)**); then write to the `COMMAND` register, and finally poll `STATUS` again.

- Advantage: simple;
- Disadvantage: wastes a large amount of CPU time waiting for slow devices.

## Using Interrupts to Reduce CPU Waiting

Unlike polling, where the OS keeps "actively" asking the I/O device whether it is done, the interrupt approach is:

> OS: Take your time, call me when you're done  
> Device: Raise an interrupt when done  
> OS: Enter the interrupt handler

The flow is roughly:

1. The OS issues a request to the device.
2. The process that issued the request sleeps.
3. The OS switches to running other processes.
4. After the device finishes the I/O, it raises a hardware interrupt.
5. The CPU enters the OS's interrupt handler.
6. The OS finishes the cleanup work and wakes up the process waiting for the I/O.

However, polling is not necessarily worse than interrupts: because interrupts have a **fixed overhead**: context switch, interrupt handling, and switching back.

Sometimes a compromise is used: poll for a while first, then switch to interrupts.

## DMA

The flaw of using PIO is that the CPU itself needs to write data from memory into device registers, wasting CPU resources.

DMA is introduced, whose role is to **let a dedicated controller handle moving data between memory and the device, while the CPU only handles initiation and completion**.

The flow:

1. The OS tells the DMA controller: where the data is in memory, how long it is, and which device to send it to.
2. The DMA controller starts moving the data.
3. The CPU does not need to do the copying itself and can run other processes.
4. When the DMA finishes, it raises an interrupt to notify the OS.

## Communication Between the OS and Device Registers

Two approaches:

- Explicit I/O instructions, such as `in` and `out` on x86, which are privileged instructions that only the OS can use;
- Memory-mapped I/O, where the hardware maps device registers to a special range of physical addresses, and then `load` and `store` are used to access them.

## Device Drivers

Role: encapsulate the complex protocols of specific devices and provide a unified interface to the upper layers of the OS.

# Chapter 37  Disk Drives

This chapter mainly covers the structure of disks.

## The Interface Provided to the Outside

From the OS's perspective, a disk looks like a huge one-dimensional array (similar to memory in this respect), divided into a number of **sectors**; each sector is usually 512 B.

**The disk only guarantees that writes to a single sector are atomic**; larger writes may only be partially completed.

## Basic Structure of a Disk

For a mechanical hard drive:

- **platter**: the circular disk that actually stores data;
- **surface**: each platter has two sides;
- **spindle**: spins the platters at high speed;
- **track**: the concentric circles on a surface;
- **sector**: the small blocks into which a track is divided;
- **disk head**: responsible for reading and writing;
- **disk arm**: moves the head to the specified track.

Imagine a CD player: the platter keeps spinning, waiting for the target sector to move under the head before reading or writing.

## Three Core Times

$$
T_{IO} = T_{seek} + T_{rotation} + T_{transfer}
$$

- **Seek time** is the time for the disk arm to move to the target track. It is very expensive because it involves mechanical movement;
- **Rotational delay** is the time spent waiting for the target sector to rotate under the head;
- **Transfer time** is the time actually spent reading or writing data.

The first two involve mechanical time, while the latter is often very small.

Therefore:

- For random I/O, most of the time is wasted on seek and rotation;
- For sequential I/O, once the initial seek and rotation are done, data can be transferred continuously, which is efficient;
- The gap between the two is extremely, extremely large.
## Disk Scheduling

By rearranging the order of I/O requests, the cost of seek and rotation is reduced.

### SSTF / NBF

The idea of **SSTF (Shortest Seek Time First)** is: prioritize serving the track request closest to the current head position.

The actual implementation is generally **NBF (Nearest Block First)**: prioritize requests whose block addresses are closer to the current address.

Disadvantage: **starvation** can occur — if nearby requests keep coming endlessly, distant requests may never get served.

### SCAN: The Elevator Algorithm

The head moves in one direction, serving requests along the way; when it reaches the end, it moves in the opposite direction.

**C-SCAN (Circular SCAN)** only sweeps in one direction, e.g., from outer to inner, and after finishing, returns to the outer side and starts over. It is somewhat fairer than ordinary SCAN, because ordinary SCAN tends to favor the middle region.

**F-SCAN** freezes the current request queue at the start of a sweep, and newly arriving requests are handled in the next round, which prevents new requests from constantly cutting in line.

### SPTF

The purpose of SSTF is mainly to reduce seek time, while **SPTF (Shortest Positioning Time First)** further takes rotation into account.

It chooses the request that can start transferring earliest, but the problem is that the OS usually does not know the disk's precise internal geometry, so this scheduling is often done inside the hardware itself.

## Some Details

Modern disks: the OS selects requests and sends them to the disk, and the disk internally reorders them based on the real geometry.

This makes the disk's internal scheduling closer to SPTF.

**I/O merging** is combining adjacent requests into one larger request, for example, taking:

```text
read block 33
read block 8
read block 34
```

and merging the 33 and 34 into a single 2-block read.

**Anticipatory scheduling**: a request is not executed immediately, because it may be worth waiting for a request that better matches the principle of locality, thereby reducing seek time overall.

# Chapter 38 RAID

**RAID (Redundant Array of Inexpensive Disks)** is a technique that combines multiple disks so that they behave like a single disk.

Key point: **transparency**: to the upper-layer OS, it still appears as one whole linear array.

> [!caution]
>
> I feel this chapter isn't really useful for understanding the OS, so I skipped it for now.

# Chapter 39  Interlude: Files and Directories 

This chapter mainly covers the UNIX system's abstraction over the raw disk.

### Files and Directories

**File**: a readable and writable array of bytes. Each file has an associated inode number at its underlying level.

**Directory**: essentially also a file, but with special content — it stores the files beneath it. For example, if `a` contains `b` `c` `d` (assume their numbers are 1 2 3 respectively), then the content of `a` would be `{(b, 1), (c, 2), (d, 3)}`. Nesting layer by layer forms the file tree.

### Creating and Opening Files

```c
int fd = open("foo", O_CREAT | O_WRONLY | O_TRUNC,
              S_IRUSR | S_IWUSR);
```

The meanings of the flags are:

- `O_CREAT`: create the file if it does not exist.
- `O_WRONLY`: open for writing only.
- `O_TRUNC`: if the file already exists, truncate its length to 0.
- The third parameter sets permissions; here it means the owner can read and write.

The return value is `fd`, i.e., the file descriptor, which is **the handle a process uses to access an already opened file**. Each process has its own fd table.

It usually starts from `3`, because:

- 0: stdin
- 1: stdout
- 2: stderr

The first three `fd`s are occupied by these three **files**.

> [!important]
>
> The philosophy of UNIX is "**everything is a file**"

### Reading and Writing Files

```c
read(fd, buffer, size);
write(fd, buffer, size);
```

Here, the system-level fd table entry records an `offset`, indicating where the current read position is.

For example, open an empty file, then:

```c
write(fd, "Hello", 5);
write(fd, "World", 5);
```

The initial `offset` is 0, so `Hello` is written; after writing, the `offset` becomes 5, and then `Hello` continues to be written after it.

> [!note]
>
> About the so-called "**entry**"
>
> 1. Every time a file is `open`ed, the OS creates an entry in the system-level open file table and then returns an fd
> 2. The recorded information includes the inode, offset, open mode (readable/write-only, etc.), locks, and so on

### `lseek()`: Changing the offset in Memory

```c
off_t lseek(int fd, off_t offset, int whence);
```

The third parameter:

- `SEEK_SET`: counted from the beginning
- `SEEK_CUR`: counted from the current position
- `SEEK_END`: counted from the end

For example, if `whence == SEEK_SET`, then after the operation the `offset` in the table entry becomes the second parameter.

### `dup()` and `fork()`

Usually each `open()` produces a new open file table entry, so different fds have different offsets. For example, the same process opening the same file twice:

```c
fd1 = open("file", O_RDONLY);
fd2 = open("file", O_RDONLY);
```

But there are special cases where fds are shared:

After `fork()`, the fds of the parent and child processes may point to the same open file table entry. Therefore, if the child process calls `lseek(fd, 10, SEEK_SET)`, the offset subsequently seen by the parent process will also be 10.

`dup(fd)` creates a new fd within the same process, but the new fd and the old fd point to the same `open file table entry` (pointing to the same underlying open file object, and therefore sharing the offset):

```c
int fd = open("README", O_RDONLY);
int fd2 = dup(fd);
```

### `fsync()`

After `write()`, the data is not immediately written to disk; instead, it is first cached in memory.

To force writing to disk, use `fsync(fd)` to immediately sync the dirty data in memory.

However, if you created a new file, sometimes `fsync(file)` alone is not enough — you also need to `fsync()` the containing directory, to ensure "this file name has been durably recorded in the directory".

### Metadata, Directories, and Deletion

The **metadata** stored by the file system can be viewed with `stat()`:

- inode number
- file size
- permissions
- link count
- owner/group
- access/modification times

The system call for deleting a file is `unlink()`; calling `rm` invokes this.

The API for operating on directories differs from the API for operating on ordinary files, e.g., `rmdir` and the like.

### Hard Links

Why is the system call for deletion `unlink()`?

First understand `link()` (used in the CLI as `ln`):

```c
link(old file directory, new file directory)
```

This is essentially a way to create another reference to the same file — the other name points to the same inode number.

The process of creating a file:

1. Create an inode number, which tracks all the metadata of this file
2. Link a human-readable name to this inode number.

So, `unlink()` simply decrements the file's **reference count**. Only when the reference count reaches 0 is the file's content actually freed.

### Symbolic Links (Soft Links)

Limitations of hard links:

- Cannot create hard links to directories (it would form a cycle in the file tree, and the file tree must be a DAG)
- Cannot link to files on other disk partitions

Soft links are created with `ln -s`; the usage looks the same, but the underlying implementation is completely different: a soft link essentially points directly to a **path name**.

- The first difference is that the symbolic link itself is actually a file of a different type. We have already discussed regular files and directories. A symbolic link is a third type known to the file system. Running `stat` on a symbolic link will show a different type;

- The output of `ll` is different;

- It may lead to dangling references, if the original file is deleted.

### Permissions, ACLs, and Mounting

UNIX basic permissions are represented by 9 bits:

```text
owner: rwx
group: rwx
other: rwx
```

More complex systems also support **ACLs (access control lists)**, which can specify more finely who can access what.

`mount` mounts a new file system at a point in the directory tree.

# Chapter 40  File System Implementation
