Sparse Holes, O_TRUNC & O_APPEND

Pre-filling multi-gigabyte partition images with literal zero writes wears out flash media and exhausts disk blocks, while calling lseek(fd, 0, SEEK_SET) before write() on an O_APPEND descriptor fails silently to update byte 0. You will build sparse hole files, compare st_size against st_blocks * 512, and prove O_TRUNC and O_APPEND semantics.

20 minfree previewLinux 6.12C11glibc 2.39→ module 3 lab
What you'll learn
  • Construct sparse hole files by seeking past EOF with lseek() and verify VFS 0x00 synthesis across unallocated extents.
  • Measure logical st_size vs allocated 512-byte sectors (st_blocks * 512) via fstat() and reclaim extents via O_TRUNC.
  • Verify O_RDWR | O_APPEND cursor asymmetry proving lseek() governs read() while write() jumps f_pos to EOF.

Why Literal Zero-Fills Exhaust Flash & O_APPEND Ignores lseek() on Writes

Imagine two storage bugs that pass casual functional checks yet fail dramatically on embedded targets. First, a factory provisioning utility builds a 4 GiB raw partition image containing a 64 KiB bootloader at offset 0 and a 64 B trailer at 4 GiB - 64 by calling write() in a 4 KiB zero-fill loop—stalling production flashing for minutes, burning 4 GiB of eMMC write endurance, and failing with ENOSPC on a 2 GiB /tmp RAM disk! Second, a telemetry journal opens its file with O_RDWR | O_APPEND, calls lseek(fd, 0, SEEK_SET) + write(fd, &super_hdr, 64) to update a header counter at byte 0, and discovers after reboot that byte 0 still holds the old header while 64 unexpected bytes were appended to the tail of the log!

Both defects vanish once you understand how the Linux kernel decouples logical file length (st_size) from physically allocated extents (st_blocks), and how O_TRUNC and O_APPEND manipulate inode->i_size and struct file.f_pos asymmetrically.

note: Think of a numbered loose-leaf binder versus a bound ledger stamped APPEND-ONLY. In the binder you can insert page 1,000 without buying paper for pages 2 through 999, whereas on the append-only ledger you may flip back to read page 1 anytime, yet every pen stroke is forced onto the bottom line.

Where it stops working: Unlike an empty gap in a ring binder, reading across an unallocated Linux sparse hole returns clean 0x00 bytes synthesized by VFS rather than an error.

definition (Sparse Extent Holes, POSIX 512-Byte st_blocks & O_APPEND Asymmetry): Sparse Extent Hole: When lseek() positions f_pos past current EOF (i_size) and a subsequent write() commits data, POSIX filesystems (ext4, XFS, Btrfs, tmpfs) record an unallocated extent gap (hole) for [old_eof .. seek_offset), allocating physical blocks only for written pages while VFS synthesizes 0x00 bytes on read(). struct stat.st_blocks: Defined in POSIX.1 in fixed 512-byte sector units (historically Seventh Edition Unix disk sectors, never st_blksize!) so physical byte allocation always equals st_blocks * 512. O_APPEND Asymmetry: On an O_RDWR | O_APPEND description, lseek() governs read() normally, whereas every write() atomically resets f_pos = i_size under inode->i_rwsem.

One Layer Down: Extent Trees, Sector Accounting Math & O_APPEND Locking

Inside ext4 or XFS, an inode's extent tree maps logical block numbers (4 KiB units) to physical device blocks ([logical_blk, len -> phys_blk]). Seeking from 0 to 4,194,240 (4 MiB - 64 B) and writing 64 bytes allocates only the final 4 KiB block (logical_blk = 1023, 1 physical 4 KiB block = 8 POSIX 512-byte sectors). Comparing fstat() fields quantifies exact space efficiency via bytes_logical = st.st_size and bytes_physical = (long long)st.st_blocks * 512LL. For our 4 MiB (4,194,304-byte) sparse image with one 4 KiB tail block (st_blocks = 8), bytes_physical = 8 * 512 = 4,096 B (99.90% physical block savings!). Notice why multiplying st_blocks * st_blksize (8 * 4096 = 32,768) is a classic bug: st_blksize (4,096) is merely the preferred I/O buffer hint, whereas st_blocks is unconditionally denominated in 512-byte units.

Meanwhile, inspect how O_TRUNC and O_APPEND act at different lifecycle moments inside VFS:

Open Flag CombinationAction During open()lseek() + read() Behaviorlseek() + write() Behavior
O_RDWR (no O_APPEND)Preserves i_size, sets f_pos = 0Reads from f_pos, advances f_posWrites at f_pos (in-place overwrite)
`O_WRONLY \O_TRUNC`Frees all extents/holes, sets i_size = 0Rejects read() with EBADFWrites sequentially from 0
`O_RDWR \O_APPEND`Preserves i_size, sets f_pos = 0Honors lseek() at any offset!Ignores lseek(); jumps f_pos to i_size!
`O_WRONLY \O_APPEND \O_TRUNC`Frees old extents once at open()Rejects read() with EBADFAtomically appends every write() at new EOF
fig_m03_l03_arch.svg — Logical st_size versus physical st_blocks * 512 on a…

Figure 3.3. Logical st_size versus physical st_blocks * 512 on a sparse hole file, O_TRUNC extent reclamation, and O_RDWR | O_APPEND write-cursor override.

step_m03_l03.svg — Sparse holes decouple logical st_size from physical…step 1/4
  1. Step 1. Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.
  2. Step 2. Writing a 4 KiB tail block sets st_size = 69,632 while physical usage st_blocks * 512LL equals 4,096 B.
  3. Step 3. Reading across unallocated hole extents synthesizes clean 0x00 bytes in VFS; O_TRUNC frees all extents.
  4. Step 4. On O_RDWR | O_APPEND, lseek(0) works for read(), whereas write() locks i_rwsem and jumps atomically to EOF.

Figure 3.3b. Sparse holes decouple logical st_size from physical st_blocks * 512 allocation, while O_APPEND forces writes—never reads—to current i_size.

fstat(2) Inspection Contract & Sparse-Filesystem Notes

Include <sys/stat.h>, <sys/types.h>, <fcntl.h>, and <unistd.h> under #define _FILE_OFFSET_BITS 64 and #define _POSIX_C_SOURCE 200809L. Both ext4, XFS, Btrfs, and Linux tmpfs (shmem) track sparse holes per 4 KiB page, so st.st_blocks * 512LL < st.st_size holds across workstation disks, /tmp tmpfs mounts, and embedded root filesystems alike (whereas legacy FAT32 SD partitions lack sparse-extent metadata and zero-fill gaps physically).

Probing Sparse Holes, O_TRUNC Reclamation & O_RDWR | O_APPEND

Save hole_append_probe.c below. First, it creates /tmp/ksa_hole_demo.bin, seeks straight to offset 65536 (64 KiB, leaving [0..65535] unallocated), writes one 4,096-byte 0xFF block (st_size == 69632 while st_blocks * 512 < 69632), rewinds to 0 to prove VFS synthesizes 0x00 bytes across the hole, and reopens with O_WRONLY | O_TRUNC (trunc_size == 0, trunc_blocks == 0). Second, it seeds {0x11, 0x22, 0x33, 0x44}, reopens with O_RDWR | O_APPEND, proves lseek(0) + read() reads 0x11 at offset 0, and proves lseek(0) + write() ignores offset 0 and appends 0x55 at offset 4!

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03$ bat -H 20 -H 44 -H 65 hole_append_probe.c File: hole_append_probe.c    #define _FILE_OFFSET_BITS 64    #define _POSIX_C_SOURCE 200809L    #include <errno.h>    #include <fcntl.h>    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/stat.h>    #include <sys/types.h>    #include <unistd.h>        int main(void) {        const char *hpath = "/tmp/ksa_hole_demo.bin";        const char *apath = "/tmp/ksa_append_demo.bin";        (void)unlink(hpath);        (void)unlink(apath);            int hfd = open(hpath, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);      if (hfd == -1 || lseek(hfd, 65536, SEEK_SET) == (off_t)-1) {            return EXIT_FAILURE;        }        uint8_t block[4096];        memset(block, 0xFFU, sizeof(block));        if (write(hfd, block, sizeof(block)) != (ssize_t)sizeof(block)) {            return EXIT_FAILURE;        }        struct stat hst;        if (fstat(hfd, &hst) == -1 || lseek(hfd, 0, SEEK_SET) == (off_t)-1) {            return EXIT_FAILURE;        }        uint8_t hole_sample[16];        memset(hole_sample, 0xAAU, sizeof(hole_sample));        if (read(hfd, hole_sample, sizeof(hole_sample)) !=            (ssize_t)sizeof(hole_sample)) {            return EXIT_FAILURE;        }        int hole_zero = 1;        for (size_t i = 0; i < sizeof(hole_sample); i++) {            if (hole_sample[i] != 0x00U) hole_zero = 0;        }        (void)close(hfd);          int tfd = open(hpath, O_WRONLY | O_TRUNC | O_CLOEXEC);        struct stat tst;        if (tfd == -1 || fstat(tfd, &tst) == -1) return EXIT_FAILURE;        (void)close(tfd);        (void)unlink(hpath);            int sfd = open(apath, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);        const uint8_t init4[4] = {0x11U, 0x22U, 0x33U, 0x44U};        if (sfd == -1 || write(sfd, init4, 4U) != 4) return EXIT_FAILURE;        (void)close(sfd);            int afd = open(apath, O_RDWR | O_APPEND | O_CLOEXEC);        uint8_t rbyte = 0U;        const uint8_t tag4[4] = {0x55U, 0x55U, 0x55U, 0x55U};        if (afd == -1 || lseek(afd, 0, SEEK_SET) == (off_t)-1 ||            read(afd, &rbyte, 1U) != 1) {            return EXIT_FAILURE;        }        if (lseek(afd, 0, SEEK_SET) == (off_t)-1 ||            write(afd, tag4, 4U) != 4) {            return EXIT_FAILURE;      }        uint8_t all8[8] = {0};        if (lseek(afd, 0, SEEK_SET) == (off_t)-1 ||            read(afd, all8, 8U) != 8) {            return EXIT_FAILURE;        }        (void)close(afd);        (void)unlink(apath);            long long phys = (long long)hst.st_blocks * 512LL;        printf("hole_logical=%lld hole_phys_lt=%d hole_zero=%d trunc_sz=%lld\n",               (long long)hst.st_size, phys < (long long)hst.st_size,               hole_zero, (long long)tst.st_size);        printf("append_read0=0x%02x byte0_kept=0x%02x eof_byte4=0x%02x\n",               rbyte, all8[0], all8[4]);        return EXIT_SUCCESS;    }
  1. Seeking to 65536 past EOF and writing 4096 bytes leaves [0..65535] unallocated (0 disk sectors for the 64 KiB hole).
  2. O_TRUNC resets st_size to 0 and releases allocated extents back to the filesystem during open().
  3. On O_RDWR | O_APPEND, lseek(0) works for read(), but write() atomically jumps f_pos to EOF (offset 4).

Verifying Sparse Sector Counts, O_APPEND Asymmetry & Lab 3

Compile and run hole_append_probe, confirm hole_logical=69632 with hole_phys_lt=1 and trunc_sz=0, verify byte0_kept=0x11 and eof_byte4=0x55 on O_RDWR | O_APPEND, and complete lab_m03_sparse_image.

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03gcc -fdiagnostics-color=always -std=c11 -Wall -Wextra -Werror hole_append_probe.c -o hole_append_probelearner@ksa:~/gl-c01/m03-l03./hole_append_probehole_logical=69632 hole_phys_lt=1 hole_zero=1 trunc_sz=0append_read0=0x11 byte0_kept=0x11 eof_byte4=0x55learner@ksa:~/gl-c01/m03-l03strace -e trace=openat ./hole_append_probe 2>&1 | grep -c 'O_APPEND'1learner@ksa:~/gl-c01/m03-l03rm -f hole_append_probelearner@ksa:~/gl-c01/m03-l03

Lab 3: Sparse Partition Image Builder & Hole Inspector

env: host

1. Motivation

Embedded Board Support Package (BSP) build scripts routinely assemble 4 MiB to 32 GiB raw flash/SD partition images containing a small bootloader header at byte 0 and a backup GPT/trailer table at the end of the image. Writing physical 0x00 buffers across every empty megabyte wastes gigabytes of CI disk space, hammers SSD/eMMC write amplification, and slows image generation by 100x. Simultaneously, engineers who attach audit tags using O_RDWR | O_APPEND frequently assume lseek(fd, 0, SEEK_SET) lets write() patch the superblock at byte 0. In this lab, you will build sparse_img to master sparse extent holes, st_size vs st_blocks * 512 accounting, and O_RDWR | O_APPEND cursor asymmetry.

2. Learning Objectives

  1. Construct a 4 MiB (4,194,304-byte) sparse partition image using lseek(fd, 4194240, SEEK_SET) so unallocated interior extents consume 0 physical disk blocks.
  2. Measure and verify logical length (st.st_size == 4194304) against physical sector allocation ((long long)st.st_blocks * 512LL < 131072) via fstat(), while proving VFS synthesizes 0x00 bytes on reads inside the hole.
  3. Demonstrate O_RDWR | O_APPEND asymmetry by proving lseek(afd, 0, SEEK_SET) positions read() at byte 0 ("KSA_SPARSE_SB_V1") while forcing write() atomically to EOF (4194304 + tag_len).

3. Environment Requirements

  • Host Execution Environment (Tested): Linux 6.12 LTS (x86_64, glibc 2.39+) on sparse-capable POSIX filesystems (ext4, XFS, Btrfs, or tmpfs).
  • Target Board Portability (ARMv7 Cortex-A7): #define _FILE_OFFSET_BITS 64 ensures off_t and struct stat (fstat64) handle >= 2 GiB sparse images identically on 32-bit ARMv7 ext4/f2fs root partitions (note: VFAT boot partitions do not support sparse holes and allocate physical zero clusters).

4. Required Software & Hardware

  • Software Toolchain: gcc (-std=c11 -Wall -Wextra -Werror), stat, ls, du, strace, and /bin/sh.
  • Hardware: Standard Linux host environment.

5. Complete Executable Commands

Run from labs/lab_m03_sparse_image/:

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03$ bat script.sh File: script.sh    # 1. Compile the warning-clean sparse partition builder    gcc -std=c11 -O2 -Wall -Wextra -Werror files/sparse_img.c -o /tmp/sparse_img        # 2. Build a 4 MiB sparse image and append an 8-byte audit trailer via O_RDWR | O_APPEND    /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01        # 3. Contrast logical EOF size (ls -lh) against physical allocated blocks (du -h & stat)    ls -lh /tmp/ksa_part.img    du -h /tmp/ksa_part.img    stat -c 'logical=%s blocks_512=%b phys_bytes=%B_unit_check' /tmp/ksa_part.img        # 4. Verify only 3 write() syscalls ran (vs 1,024 in the broken starter!)    strace -e trace=write,lseek /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01        # 5. Clean up and execute the full TAP 13 test suite    rm -f /tmp/sparse_img /tmp/ksa_part.img    sh check.sh

*Why each command runs:* ls -lh reads st_size (4.1M), whereas du -h sums st_blocks * 512 (8.0K or 12K—two or three 4 KiB blocks total!); strace proves lseek() skipped the 4 MiB gap in 1 metadata call with zero zero-fill writes; and sh check.sh validates starter failure and reference compliance.

6. Annotated Source Code (starter/ Flaws vs files/ Reference)

Flawed Baseline (starter/sparse_img.c)

  1. Physical zero-fill loop: Calls write(fd, zero, 4096) 1,024 times, allocating 4,194,304 physical bytes (8,192 512-byte sectors) and failing phys_bytes < 131072.
  2. Missing O_TRUNC & O_CLOEXEC: Re-running over an existing larger image leaves trailing garbage intact, and descriptors leak on execve().
  3. Missing trailer, hole verification, and O_APPEND proof: Never writes the superblock/trailer markers or tests O_RDWR | O_APPEND.

Warning-Clean Reference (files/sparse_img.c)

  • Sparse Construction: Opens <img_path> with O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC (0644), writes 64-byte "KSA_SPARSE_SB_V1" (0x5A-padded) at 0, calls lseek(fd, 4194240, SEEK_SET) across the unallocated [64 .. 4194239] gap, and writes 64-byte "KSA_SPARSE_TR_V1" (0xA5-padded) at 4194240.
  • Hole & Sector Verification: Queries fstat(fd, &st), computes phys_bytes = (long long)st.st_blocks * 512LL (8,192 bytes = two 4 KiB blocks!), seeks to 2097152 (2 MiB), pre-fills hole_buf with 0xFF, and proves read_full() overwrites all 64 bytes with VFS-synthesized 0x00.
  • O_APPEND Asymmetry Proof: Reopens with O_RDWR | O_APPEND | O_CLOEXEC, seeks to 0 to read "KSA_SPARSE_SB_V1", seeks to 0 again before write_all(afd, append_tag, tag_len), and verifies byte 0 stayed "KSA_SPARSE_SB_V1" while st_size grew to 4194304 + tag_len!

7. Expected Output

learner@ksa: ~/gl-c01/m03-l03
learner@ksa:~/gl-c01/m03-l03$ bat listing.txt File: listing.txt    $ /tmp/sparse_img /tmp/ksa_part.img --append-tag AUDIT_01    logical_size=4194312 phys_bytes=12288 hole_zero_ok=1 superblock_ok=1 append_eof_ok=1        $ sh check.sh    TAP version 13    1..5    ok 1 - compiles cleanly with -std=c11 -Wall -Wextra -Werror    ok 2 - creates 4 MiB logical image using < 128 KiB physical disk blocks    ok 3 - synthesizes 0x00 bytes when reading across unallocated sparse hole    ok 4 - preserves superblock at offset 0 while O_APPEND forces write to EOF    ok 5 - reclaims stale blocks via O_TRUNC on rebuild    # pass 5/5

8. Explanation of Observed Behavior

Writing [0..63] allocates logical block 0 (4,096 bytes); seeking to 4,194,240 and writing [4194240..4194303] allocates logical block 1023 (4,096 bytes), leaving blocks 1..1022 (1,022 * 4 KiB = 4,186,112 bytes) unmapped in the inode's extent tree (phys_bytes = 8,192 before --append-tag, 12,288 after appending 8 bytes into logical block 1024). During --append-tag, lseek(afd, 0, SEEK_SET) sets struct file.f_pos = 0 for read(), then vfs_write() sees O_APPEND in f_flags and resets kiocb.ki_pos = i_size (4,194,304) atomically under inode->i_rwsem.

9. Experiment Variations

  1. Extent Enumeration (filefrag / SEEK_DATA): Run filefrag -v /tmp/ksa_part.img (or add lseek(fd, 0, SEEK_HOLE) / lseek(fd, 4096, SEEK_DATA)) to inspect the exact physical extent ranges [0..4095] and [4190208..4194303].
  2. Naive cp Inflation Test: Compare cp --sparse=never /tmp/ksa_part.img /tmp/dense.img (du -h jumps to 4.0M!) against cp --sparse=always /tmp/ksa_part.img /tmp/sparse_copy.img (du -h stays 12K!).
  3. Punching Holes Dynamically (fallocate): On Linux (#define _GNU_SOURCE), test fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, 4096) to deallocate block 0 back into a sparse hole without changing st_size!

10. Performance Measurements

Measured on Host x86_64 Linux 6.12 LTS (CLOCK_MONOTONIC, 5 warmup runs, N = 35 runs creating 4 MiB image + --append-tag AUDIT_01):

MetricSparse lseek Reference (files/)Dense Zero-Fill Starter (starter/)Target ARMv7 Cortex-A7 eMMC Expectation
End-to-end build latency (p50 / p95 / p99)2,999.4 us / 3,335.8 us / 3,341.4 us~6,800+ us (RAM cache) / >80 ms synced~12 ms sparse vs >250 ms dense eMMC writes
Physical storage allocated (st_blocks * 512)8,192 B (12,288 B with tag; 99.7% saved)4,194,304 B (0% saved)Identical ext4 4 KiB block allocation
Kernel write() syscalls2 (3 with --append-tag)1,0242 (3 with --append-tag)

11. Troubleshooting

SymptomRoot CauseFix
phys_bytes equals 4194304 or 33554432Wrote literal zero buffers, or multiplied st_blocks * st_blksize (4096) instead of 512Use lseek() across holes and multiply st.st_blocks * 512LL
superblock_ok=0 after --append-tagOpened afd without O_APPEND, allowing lseek(0) + write() to clobber byte 0Pass `O_RDWR \O_APPEND \O_CLOEXEC`
EOVERFLOW on > 2 GiB sparse offsets on 32-bit buildsMissing #define _FILE_OFFSET_BITS 64 before #includePlace #define _FILE_OFFSET_BITS 64 on line 1

12. Guided Questions

  1. Why does lseek(fd, 4194304, SEEK_SET) followed immediately by close(fd) (with NO write()) leave st_size == 0 instead of 4194304?
  • *Hint 1:* Which kernel structure does lseek() mutate (struct file.f_pos vs struct inode.i_size)?
  • *Hint 2:* Which syscall resizes inode->i_size to 4194304 without writing trailing payload bytes if your image ends with a sparse hole?
  1. Why did appending an 8-byte tag at offset 4,194,304 increase phys_bytes by 4,096 bytes (8 st_blocks units) instead of 8 bytes?
  • *Hint 1:* Offset 4,194,304 (4 MiB) sits at exact 4 KiB block index 1024 (4194304 / 4096 == 1024).
  • *Hint 2:* What is the minimum physical allocation unit of an ext4 / tmpfs page-backed filesystem?

13. Independent Challenges

  1. Near Transfer — Multi-Partition GPT-Style Sparse Table Builder: Extend sparse_img.c to accept <boot_bin> and <rootfs_bin> payloads placed at 1 MiB (1,048,576) and 64 MiB (67,108,864) inside a 512 MiB logical image, verifying via SEEK_DATA/SEEK_HOLE that exactly the non-zero regions are allocated.
  2. Far Transfer — Sparse Archive Serializer (--pack / --unpack): Build a sparse-aware archiver that scans any sparse image with SEEK_DATA/SEEK_HOLE, emits compact [uint64_t offset, uint64_t length, data...] records, and reconstructs an identical sparse target (st_size and st_blocks * 512 preserved).

14. Solutions & Explanations

  • Guided Question 1: lseek() updates only struct file.f_pos in RAM without touching struct inode.i_size; only a subsequent write() past i_size (or an explicit ftruncate(fd, 4194304)) extends the inode's logical EOF!
  • Guided Question 2: Filesystems allocate storage in whole 4 KiB (4,096-byte = 8 * 512B) blocks/folios; writing byte 0 of block 1024 allocates that entire 4 KiB block (phys_bytes rises from 8,192 to 12,288).

Run locally in your terminal and check off each verification milestone.

Not started

Kernel-Locked O_APPEND Sets Up Module 4 File Sharing

Inside fs/read_write.c, O_APPEND works because the kernel acquires inode->i_rwsem, sets kiocb.ki_pos = i_size_read(inode), and copies user bytes into the page cache before releasing the lock—making O_APPEND atomic across cooperating processes! Module 4 builds directly on that insight: what happens when a process opens one file twice versus duplicating a descriptor with dup2()/dup3(), and how do pread() and pwrite() perform random-access updates without touching f_pos at all?

Guided Practice: Sparse-Aware File Copier Loop

A naive cp implementation copies a sparse image by calling read() and write() unconditionally, inflating a 64 KiB-allocated 1 GiB image into 1 GiB of physical zero blocks:

  1. Step 1 (Detect all-zero 4 KiB buffers or SEEK_DATA extents): Write a helper static int is_all_zero(const uint8_t *buf, size_t n) (or use SEEK_DATA/SEEK_HOLE from m02-l03).
  2. Step 2 (Preserve trailing holes at EOF): When skipping a 4 KiB zero chunk on dst_fd via lseek(dst_fd, 4096, SEEK_CUR), remember that lseek() past EOF alone does not extend st_size if the file ends with a hole—call ftruncate(dst_fd, src_st.st_size) (covered in depth in Module 4) or verify SEEK_END when finalizing!

Independent Practice: Extent Map & Sparsity Ratio Reporter

Write a C11 CLI sparse_stat.c (#define _GNU_SOURCE, #define _FILE_OFFSET_BITS 64, -Wall -Wextra -Werror) that creates a 16 MiB test file containing three 4 KiB data islands at 0, 4 MiB, and 12 MiB, walks every [data_start, hole_start) extent using SEEK_DATA and SEEK_HOLE, and prints logical bytes (st_size), physical bytes (st_blocks * 512), extent count (3), and exact sparsity percentage.

Common Production Pitfalls

warning: Symptom: A storage engine opens its file with O_RDWR | O_APPEND, executes lseek(fd, 0, SEEK_SET) + write(fd, &hdr, 64) to update a superblock checksum in place, and discovers byte 0 never changed while st_size grew by 64 bytes! Root Cause: O_APPEND overrides f_pos to i_size on every write() regardless of prior lseek() calls. Fix: Open descriptors requiring in-place header overwrites without O_APPEND (or use stateless pwrite() on a non-append descriptor).

warning: Symptom: Multiplying st.st_blocks * st.st_blksize to compute physical disk consumption over-reports storage usage by 8x on standard 4 KiB ext4 filesystems! Root Cause: POSIX fixes st_blocks in 512-byte units regardless of st_blksize (4,096 or 65,536). Fix: Always compute physical bytes as (long long)st.st_blocks * 512LL.

Knowledge Check

quiz · 1 of 4

A program creates an empty file on ext4, calls lseek(fd, 1048576, SEEK_SET) (1 MiB), and writes 64 bytes. What do st.st_size and (long long)st.st_blocks * 512LL report via fstat()?

quiz · 2 of 4

(Review from earlier lesson) An existing 4-byte file {0x10, 0x20, 0x30, 0x40} is opened with open(path, O_RDWR | O_APPEND | O_CLOEXEC). The caller runs lseek(fd, 1, SEEK_SET), read(fd, &r, 1), lseek(fd, 0, SEEK_SET), and write(fd, &w, 1) where w = 0x99. What byte does read() fetch, and at what offset does 0x99 land?

quiz · 3 of 4

(Review from previous module) What happens when an existing 8 KiB log file is opened via open(path, O_WRONLY | O_APPEND | O_TRUNC | O_CLOEXEC) and the process writes two 16-byte records?

quiz · 4 of 4

On an XFS partition formatted with a 64 KiB (65,536-byte) block size (st.st_blksize == 65536), fstat() on a small file reports st.st_blocks == 128. How many physical bytes are allocated on disk?

Key takeaways

  • Seeking past EOF with lseek() and calling write() creates a sparse hole file: read() across unallocated holes returns VFS-synthesized 0x00 bytes without consuming physical disk blocks.
  • fstat() separates logical byte length st.st_size (ls -lh) from physical allocation (long long)st.st_blocks * 512LL (du -h, unconditionally counted in 512-byte POSIX units).
  • O_TRUNC (paired with O_WRONLY or O_RDWR) resets st_size to 0 and reclaims allocated extents during open().
  • O_APPEND leaves read() seekable via lseek(), yet forces every write() inside the Linux kernel to jump atomically to i_size regardless of prior lseek() calls.
  • With VFS tables, errno unwinding, and sparse extents in place, Module 4 tackles descriptor sharing (dup2/dup3), atomic O_EXCL & stateless pread/pwrite, and runtime fcntl/ioctl control.
Progress is saved on this device.
up next · module 3 labLab: Sparse Partition Image Builder & Hole Inspector (50 min)
→ module 3 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure