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.
What you'll learn
- Construct sparse hole files by seeking past EOF with
lseek()and verify VFS0x00synthesis across unallocated extents. - Measure logical
st_sizevs allocated 512-byte sectors (st_blocks * 512) viafstat()and reclaim extents viaO_TRUNC. - Verify
O_RDWR | O_APPENDcursor asymmetry provinglseek()governsread()whilewrite()jumpsf_posto 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 Combination | Action During open() | lseek() + read() Behavior | lseek() + write() Behavior | ||
|---|---|---|---|---|---|
O_RDWR (no O_APPEND) | Preserves i_size, sets f_pos = 0 | Reads from f_pos, advances f_pos | Writes at f_pos (in-place overwrite) | ||
| `O_WRONLY \ | O_TRUNC` | Frees all extents/holes, sets i_size = 0 | Rejects read() with EBADF | Writes sequentially from 0 | |
| `O_RDWR \ | O_APPEND` | Preserves i_size, sets f_pos = 0 | Honors 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 EBADF | Atomically appends every write() at new EOF |
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 1. Seeking past EOF via lseek(hfd, 65536, SEEK_SET) advances f_pos in RAM without writing physical zero blocks.
- Step 2. Writing a 4 KiB tail block sets st_size = 69,632 while physical usage st_blocks * 512LL equals 4,096 B.
- Step 3. Reading across unallocated hole extents synthesizes clean 0x00 bytes in VFS; O_TRUNC frees all extents.
- 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$ 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; }- Seeking to 65536 past EOF and writing 4096 bytes leaves [0..65535] unallocated (0 disk sectors for the 64 KiB hole).
- O_TRUNC resets st_size to 0 and releases allocated extents back to the filesystem during open().
- 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-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→ open standalone lab workbench
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
- Construct a
4 MiB(4,194,304-byte) sparse partition image usinglseek(fd, 4194240, SEEK_SET)so unallocated interior extents consume0physical disk blocks. - Measure and verify logical length (
st.st_size == 4194304) against physical sector allocation ((long long)st.st_blocks * 512LL < 131072) viafstat(), while proving VFS synthesizes0x00bytes on reads inside the hole. - Demonstrate
O_RDWR | O_APPENDasymmetry by provinglseek(afd, 0, SEEK_SET)positionsread()at byte0("KSA_SPARSE_SB_V1") while forcingwrite()atomically toEOF(4194304 + tag_len).
3. Environment Requirements
- Host Execution Environment (Tested): Linux
6.12LTS (x86_64,glibc2.39+) on sparse-capable POSIX filesystems (ext4,XFS,Btrfs, ortmpfs). - Target Board Portability (
ARMv7Cortex-A7):#define _FILE_OFFSET_BITS 64ensuresoff_tandstruct stat(fstat64) handle>= 2 GiBsparse images identically on 32-bitARMv7ext4/f2fsroot partitions (note:VFATboot 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$ 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)
- Physical zero-fill loop: Calls
write(fd, zero, 4096)1,024times, allocating4,194,304physical bytes (8,192512-byte sectors) and failingphys_bytes < 131072. - Missing
O_TRUNC&O_CLOEXEC: Re-running over an existing larger image leaves trailing garbage intact, and descriptors leak onexecve(). - Missing trailer, hole verification, and
O_APPENDproof: Never writes the superblock/trailer markers or testsO_RDWR | O_APPEND.
Warning-Clean Reference (files/sparse_img.c)
- Sparse Construction: Opens
<img_path>withO_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC(0644), writes64-byte"KSA_SPARSE_SB_V1"(0x5A-padded) at0, callslseek(fd, 4194240, SEEK_SET)across the unallocated[64 .. 4194239]gap, and writes64-byte"KSA_SPARSE_TR_V1"(0xA5-padded) at4194240. - Hole & Sector Verification: Queries
fstat(fd, &st), computesphys_bytes = (long long)st.st_blocks * 512LL(8,192bytes = two4 KiBblocks!), seeks to2097152(2 MiB), pre-fillshole_bufwith0xFF, and provesread_full()overwrites all64bytes with VFS-synthesized0x00. O_APPENDAsymmetry Proof: Reopens withO_RDWR | O_APPEND | O_CLOEXEC, seeks to0to read"KSA_SPARSE_SB_V1", seeks to0again beforewrite_all(afd, append_tag, tag_len), and verifies byte0stayed"KSA_SPARSE_SB_V1"whilest_sizegrew to4194304 + tag_len!
7. Expected Output
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/58. 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
- Extent Enumeration (
filefrag/SEEK_DATA): Runfilefrag -v /tmp/ksa_part.img(or addlseek(fd, 0, SEEK_HOLE)/lseek(fd, 4096, SEEK_DATA)) to inspect the exact physical extent ranges[0..4095]and[4190208..4194303]. - Naive
cpInflation Test: Comparecp --sparse=never /tmp/ksa_part.img /tmp/dense.img(du -hjumps to4.0M!) againstcp --sparse=always /tmp/ksa_part.img /tmp/sparse_copy.img(du -hstays12K!). - Punching Holes Dynamically (
fallocate): On Linux (#define _GNU_SOURCE), testfallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, 4096)to deallocate block0back into a sparse hole without changingst_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):
| Metric | Sparse 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() syscalls | 2 (3 with --append-tag) | 1,024 | 2 (3 with --append-tag) |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
phys_bytes equals 4194304 or 33554432 | Wrote literal zero buffers, or multiplied st_blocks * st_blksize (4096) instead of 512 | Use lseek() across holes and multiply st.st_blocks * 512LL | ||
superblock_ok=0 after --append-tag | Opened afd without O_APPEND, allowing lseek(0) + write() to clobber byte 0 | Pass `O_RDWR \ | O_APPEND \ | O_CLOEXEC` |
EOVERFLOW on > 2 GiB sparse offsets on 32-bit builds | Missing #define _FILE_OFFSET_BITS 64 before #include | Place #define _FILE_OFFSET_BITS 64 on line 1 |
12. Guided Questions
- Why does
lseek(fd, 4194304, SEEK_SET)followed immediately byclose(fd)(with NOwrite()) leavest_size == 0instead of4194304?
- *Hint 1:* Which kernel structure does
lseek()mutate (struct file.f_posvsstruct inode.i_size)? - *Hint 2:* Which syscall resizes
inode->i_sizeto4194304without writing trailing payload bytes if your image ends with a sparse hole?
- Why did appending an
8-byte tag at offset4,194,304increasephys_bytesby4,096bytes (8st_blocksunits) instead of8bytes?
- *Hint 1:* Offset
4,194,304(4 MiB) sits at exact4 KiBblock index1024(4194304 / 4096 == 1024). - *Hint 2:* What is the minimum physical allocation unit of an
ext4/tmpfspage-backed filesystem?
13. Independent Challenges
- Near Transfer — Multi-Partition GPT-Style Sparse Table Builder: Extend
sparse_img.cto accept<boot_bin>and<rootfs_bin>payloads placed at1 MiB(1,048,576) and64 MiB(67,108,864) inside a512 MiBlogical image, verifying viaSEEK_DATA/SEEK_HOLEthat exactly the non-zero regions are allocated. - Far Transfer — Sparse Archive Serializer (
--pack/--unpack): Build a sparse-aware archiver that scans any sparse image withSEEK_DATA/SEEK_HOLE, emits compact[uint64_t offset, uint64_t length, data...]records, and reconstructs an identical sparse target (st_sizeandst_blocks * 512preserved).
14. Solutions & Explanations
- Guided Question 1:
lseek()updates onlystruct file.f_posin RAM without touchingstruct inode.i_size; only a subsequentwrite()pasti_size(or an explicitftruncate(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 byte0of block1024allocates that entire4 KiBblock (phys_bytesrises from8,192to12,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:
- Step 1 (Detect all-zero
4 KiBbuffers orSEEK_DATAextents): Write a helperstatic int is_all_zero(const uint8_t *buf, size_t n)(or useSEEK_DATA/SEEK_HOLEfromm02-l03). - Step 2 (Preserve trailing holes at
EOF): When skipping a4 KiBzero chunk ondst_fdvialseek(dst_fd, 4096, SEEK_CUR), remember thatlseek()pastEOFalone does not extendst_sizeif the file ends with a hole—callftruncate(dst_fd, src_st.st_size)(covered in depth in Module 4) or verifySEEK_ENDwhen 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
Key takeaways
- Seeking past
EOFwithlseek()and callingwrite()creates a sparse hole file:read()across unallocated holes returns VFS-synthesized0x00bytes without consuming physical disk blocks. fstat()separates logical byte lengthst.st_size(ls -lh) from physical allocation(long long)st.st_blocks * 512LL(du -h, unconditionally counted in512-byte POSIX units).O_TRUNC(paired withO_WRONLYorO_RDWR) resetsst_sizeto0and reclaims allocated extents duringopen().O_APPENDleavesread()seekable vialseek(), yet forces everywrite()inside the Linux kernel to jump atomically toi_sizeregardless of priorlseek()calls.- With VFS tables,
errnounwinding, and sparse extents in place, Module 4 tackles descriptor sharing (dup2/dup3), atomicO_EXCL& statelesspread/pwrite, and runtimefcntl/ioctlcontrol.