Skip to content

10 filesystem

misazhu edited this page Dec 3, 2026 · 2 revisions

10 Filesystems and Storage Devices

Language: English | 中文

Goal: understand how data becomes bytes in a program from magnetic bits on an SD card. Covers three layers: the SD card hardware driver → ext2 filesystem parsing → the VFS virtual filesystem. Terminology (VFS/inode/ext2/sector/block/superblock/mount…) is in the glossary.

10.1 The Three Layers of Storage Abstraction

┌────────────────────────────────────────────────┐
│ What apps see:  paths and files like            │  ← VFS (the vfsd process)
│                 /etc/passwd                     │
├────────────────────────────────────────────────┤
│ The filesystem: inodes, directories,            │  ← ext2/ext3 (the sdfsd process)
│                 blocks (4KB)                    │
├────────────────────────────────────────────────┤
│ The block dev:  an SD card read/written         │  ← the SD card driver
│                 in 512-byte sectors             │
└────────────────────────────────────────────────┘

Each layer depends only on the interface of the layer below. That way, swapping the filesystem or the storage medium doesn't affect the other layers.

10.2 How an SD Card Is Read and Written

An SD card is essentially a strip of storage readable and writable by sector (512 bytes), attached to the Pi's SD controller (SDHOST/EMMC on the Pi2/Pi3). The driver is still the Ch. 03 routine — writing MMIO registers:

send a command (CMD17 = read single block / CMD18 = read multiple blocks)
    → wait for the status register to say "done"
    → ferry the 512 bytes out of the data register

The Pi implementation is in bsp/sd.c and bcm283x/src/sd.c (with tedious details like the init sequence and clock negotiation; beginners may skip the internals and just remember the interface):

int32_t sd_read(uint32_t block, void* buf, uint32_t buf_size);
int32_t sd_write(uint32_t block, const void* buf, uint32_t buf_size);

Microkernel tidbit: in early boot the kernel must read the SD card itself (to read the config and init), so the kernel carries an SD driver; once the system is up, the userland sdfsd maps the SD controller's registers into its own memory via SYS_MEM_MAP_NOCACHE and implements a userland driver. Two codebases serving two different stages.

10.3 ext2: How Files Are Organized on Top of Sectors

Bare sectors only have numbers (0, 1, 2, ...); the concept of a "file" needs data structures to express. EwokOS uses the classic ext2 (the SD image is generated by mke2fs). Below we explain it exactly "as it really looks on the disk".

① The Overall Layout: Superblock + Block Groups

SD card partition
├── superblock                 global metadata: block size, inode/block counts, magic 0xEF53
├── block group 0
│   ├── block bitmap           which data blocks are taken (1=taken, 0=free)
│   ├── inode bitmap           which inodes are taken
│   ├── inode table            a row of inodes ("dossiers"), each a fixed 128 bytes
│   └── data blocks            the actual file contents
├── block group 1 ...          (the structure repeats, easing recovery from local damage)

Corresponding to the three core structures in ext2head.h:

typedef struct ext2_super_block {   // the superblock: the whole disk's "manual"
    uint32_t s_inodes_count;        // how many inodes in total
    uint32_t s_blocks_count;        // how many blocks in total
    uint32_t s_log_block_size;      // block size = 1024 << this value
    uint16_t s_magic;               // 0xEF53, proving its identity
    ...
} SUPER;

typedef struct ext2_inode {         // an inode: a single file's "dossier"
    uint16_t i_mode;                // type + permissions (directory/file/read-write…)
    uint32_t i_size;                // file size in bytes
    uint32_t i_block[15];           // ★the data-block pointer array (see below)
    ...
} INODE;

typedef struct ext2_dir_entry_2 {   // a directory entry: "filename → inode number"
    uint32_t inode;
    uint8_t  name_len;
    char     name[255];
} DIR;

② How an Inode Points at Data: Direct + Indirect

i_block[15] does not all point at data blocks directly — it's layered:

i_block[0..11]  → point directly at 12 data blocks (small files stop here)
i_block[12]     → single indirect: points at a "block full of block numbers" (~1024 more blocks)
i_block[13]     → double indirect (very large files)
i_block[14]     → triple indirect (rarely used)

A small file needs just one inode; a large file follows the indirect pointers layer by layer. This is the secret of "a file can be arbitrarily large and need not be physically contiguous".

③ A Directory = a Special File

A directory's "content" is just a string of directory entries. Reading /etc/passwd is really a three-step chained lookup:

read the "/" directory (root = inode 2) → scan entries, find the inode number for "etc"
read the /etc directory                 → scan entries, find the inode number for "passwd"
read that inode                         → read the data blocks block by block via the i_block pointers

④ The Kernel's Read-File Algorithm

The kernel carries a read-only ext2 implementation (kernel/lib/ext2/), used at boot to read the config and /sbin/init. Look at the key function chain in ext2read.c:

sd_read_ext2(fname, &size)          ← entry: given a path, want the content
  └─ ext2_init: read the superblock, verify the magic, compute the number
     of block groups, load all block-group descriptors
  └─ ext2_readfile
      └─ ext2_ino_by_fname          ← turn the path into an inode number
          └─ split_fname("/etc/passwd") → ["etc","passwd"]
          └─ search() level by level: read the current directory, linearly
             scan entries to match the filename
      └─ get_node_by_ino            ← locate and read the INODE by inode number
      └─ ext2_read(node, buf, n, off) ← read block by block into buf via i_block

The lowest-level block read goes through the read_block function pointer — during kernel boot it means "call the SD driver to read 512-byte sectors". See loadinit.c:

int32_t load_init_proc(void) {
    const char* prog = "/sbin/init";
    char* elf = read_fs(prog, &sz);        // ★find the file in the SD card's ext2
    if(elf != NULL) {
        proc_t *proc = proc_create(TASK_TYPE_PROC, NULL);
        proc->info.uid = -1;               // uid=-1 marks "loaded by the kernel itself"
        proc_load_elf(proc, elf, sz);      // parse the ELF to build the process (Ch. 07)
        ...
    }
}

This is the last time the kernel touches the filesystem in person — afterwards, every file operation is handed to userland.

10.4 VFS: the Unified Entrance Where Everything Is a File

The userland filesystem architecture:

         ┌──────────────┐
apps ──► │    vfsd       │ mount table:  /      → sdfsd (SD card ext2)
         │ (the router)  │               /tmp   → ramfsd (RAM disk)
         └──┬───────┬───┘               /dev/* → the device driver processes
            │       │
        ┌───▼──┐ ┌──▼───┐
        │ sdfsd │ │ramfsd│ ...   each mount point is an independent IPC service
        └──────┘ └──────┘
  • vfsd (vfsd.c): maintains the mount table, parses paths, and forwards requests to the service of the corresponding mount point. It implements no filesystem itself;
  • sdfsd: the complete ext2/ext3 implementation (read and write);
  • ramfsd: an in-memory filesystem (/tmp);
  • Devices as files: /dev/tty0 (serial), /dev/timer, /dev/log… each is a virtual file provided by a driver process. printf ultimately becomes a write to some /dev/* — this is the microkernel edition of the Unix "everything is a file" philosophy.

What the Mount Table Looks Like

The mount table inside vfsd is an array; each row is a mount_t (fsinfo.h):

typedef struct {
    int32_t pid;                  // which service process serves this mount point
    ewokos_addr_t org_node;       // the "root node" handle inside that filesystem
    char org_name[FS_FULL_NAME_MAX];  // the mount path, e.g. "/", "/tmp"
} mount_t;

When the path /tmp/a.txt arrives, vfsd finds the longest matching prefix /tmp, forwards the request to ramfsd (its pid), and passes /a.txt as the path "relative to that mount point". Each node in a path also has an fsinfo structure recording its type (directory / file / character device / block device), the mount service it belongs to, its state, and so on.

File Operations = a Fixed Set of Command Numbers

All file operations converge into an enum FS_CMD_*, traveling over Ch. 09's IPC:

enum {
    FS_CMD_NONE = 0,
    FS_CMD_OPEN,        // open
    FS_CMD_STAT,        // query attributes
    FS_CMD_CREATE,      // create
    FS_CMD_CLOSE,       // close
    FS_CMD_READ,        // read
    FS_CMD_WRITE,       // write
    FS_CMD_SEEK,        // move the read/write position
    FS_CMD_UNLINK,      // delete
    FS_CMD_FLUSH,       // flush buffers
    ...
};

So read(fd, buf, n) at the bottom is:

libc → ipc_call(the mount point service's pid, FS_CMD_READ, packed {fd, n})
     → the service process reads the data → stuffs the bytes into a proto_t and returns
     → libc unpacks into buf

The filesystem's "API" has been compressed into a table of command numbers — any language, any process can use it by sending IPC. Device files work the same way — FS_CMD_DEV_CNTL can even send "vendor-defined commands" to a driver (like ejecting a USB stick).

10.5 Follow Along: Observing the Filesystem

After booting the system:

> ls /                  # look at the root directory
> cat /etc/passwd       # read a file: goes vfsd → sdfsd → the SD card
> echo hi > /tmp/a.txt  # write a file: goes vfsd → ramfsd → memory
> cat /tmp/a.txt
> df                    # view the mount table

Behind every command are multiple IPC calls. You can use svcinfo to see the service process list and match commands against the mount table.

10.6 Exercises

  1. Use df to view the mount table and draw this system's "mount tree";
  2. Read the mount-table structure in vfsd.c and understand how the path /tmp/a.txt is split into "mount point + remaining path";
  3. Food for thought: why does /dev/null (the null device) also get its own process? Is there a thriftier way? (Hint: nulld is extremely simple, but a microkernel would rather have one more process than break the consistency of "device = independent service".)

10.7 Summary

  • Three storage layers: block device (sectors) → filesystem (inodes/directories) → VFS (paths);
  • The SD card driver is just operating the controller's registers per the manual;
  • ext2 organizes files with inodes + directories; the kernel only reads it during boot (to load the config and init);
  • At runtime, every file operation is an IPC chain of app → vfsd → the concrete filesystem process;
  • Devices are files too — behind every /dev/* is a driver process.

Next chapter: how the system brings these services up in the right order — init and the boot scripts.

EwokOS OS Tutorial / EwokOS 操作系统教学

English Home · 中文首页

Part 1: Getting Started / 第 1 部分:起步

Part 2: The Kernel / 第 2 部分:内核

Part 3: Userland / 第 3 部分:用户态

Part 4: The Full System / 第 4 部分:完整系统

Part 5: The ewokos Series (Libraries) / 第 5 部分:ewokos 系列(库生态)

Part 6: GPU & Compute / 第 6 部分:GPU 与计算

Appendix / 附录

Clone this wiki locally