Welcome to Linux Systems C

Porting bare-metal firmware habits into a hosted Linux C daemon triggers immediate segmentation faults or burns microseconds in avoidable CPU privilege switches. In this opening lesson of GL-C01, you will map the hardware privilege boundary, trace how system calls and the vDSO bridge Ring 3 and Ring 0, and benchmark a strict ISO C11 probe.

20 minfree previewLinux 6.12C11glibc 2.39→ module 1 lab
What you'll learn
  • Compare bare-metal MMIO firmware, Ring 0 struct file_operations drivers, and Ring 3 C processes across fault isolation.
  • Map the seven Linux kernel subsystems and the linux-vdso.so.1 zero-trap fastpath across GL-C01 through GL-C04.
  • Compile and execute a strict ISO C11 sanity binary while separating Ring 3 RAM loops from Ring 0 syscall traps.

Why Systems C Needs a Hardware Kernel Boundary

Suppose an engineer ports a bare-metal microcontroller routine *(volatile uint32_t *)0x0209C000 = 1U; directly into main() of a Linux telemetry daemon to toggle a status pin. On a microcontroller without a Memory Management Unit (MMU), that store hits a physical Memory-Mapped Input/Output (MMIO) peripheral register—and one corrupted pointer in a string parser silently overwrites motor-control or flash-erase registers across the entire board. Under the Linux kernel, executing that identical store inside main() terminates the process within nanoseconds with SIGSEGV (Segmentation fault) while every sibling service and hardware peripheral keeps running unharmed.

Naive C code fails at this boundary for two complementary reasons. First, treating user-space pointers as physical bus addresses violates hardware virtual-memory protection. Second, going to the opposite extreme—issuing a 1-byte kernel write call inside a tight loop—stalls the processor in privilege-switch overhead that costs hundreds of CPU cycles per byte. Production systems engineers must know exactly which instructions execute freely in user Random-Access Memory (RAM), which operations cross the synchronous kernel trap gate, and which read-only kernel queries bypass traps altogether.

Welcome to GL-C01 (Linux Systems I/O & Buffering in C), the foundational first course of our four-course Linux Systems Programming in C series:

  1. GL-C01 (This Course): ISO C11 toolchain discipline, Application Binary Interface (ABI) mechanics, unbuffered Portable Operating System Interface (POSIX) file descriptors, Virtual File System (VFS) open-file tables, atomic positional operations, stdio buffering, and crash-consistent Write-Ahead Log (WAL) storage.
  2. GL-C02: Filesystem metadata, directory traversal, signals, multi-process lifecycles, and POSIX threads (pthreads).
  3. GL-C03: Non-blocking I/O, poll/epoll event multiplexing, Inter-Process Communication (IPC), and TCP/UDP network sockets.
  4. GL-C04: User-space embedded Linux peripherals (sysfs, evdev, I2C/SPI/UART, DRM display, V4L2 camera, and ALSA audio).

note: Think of an airport security checkpoint separating the public terminal from the active runway tarmac. Travelers organize itineraries freely inside the public hall, but loading cargo onto an aircraft requires handing parcels through a guarded counter to badged ground crew.

Where it stops working: Unlike a physical counter staffed by separate people, a CPU system call switches privilege levels on the exact same processor core in nanoseconds via architectural trap registers.

definition (Hardware Privilege Rings, Syscall Gate & vDSO): Privilege Rings (Ring 3 / EL0 vs Ring 0 / EL1): Originating in Multics protection rings and enforced by the x86-64 Current Privilege Level (CPL) or ARM Exception Level (EL), user C processes execute in unprivileged Ring 3 (EL0) inside isolated virtual address spaces, whereas the Linux kernel executes in Ring 0 (EL1) with full MMU, interrupt, and MMIO authority. A System Call Gate (syscall on x86-64 System V ABI; svc #0 on ARMv7 AAPCS) switches privilege synchronously on the active core, while the Virtual Dynamic Shared Object (vDSO, linux-vdso.so.1) maps read-only kernel timekeeper pages into Ring 3 so clock_gettime() reads monotonic clocks with zero traps.

fig_m01_l01_arch.svg — Hardware privilege boundary — Ring 3 C helpers and…

Figure 1.1a. Hardware privilege boundary — Ring 3 C helpers and linux-vdso.so.1 execute in user space, while system calls cross the ABI trap gate into the seven Ring 0 Linux kernel subsystems.

Virtual vs Physical Memory: How the MMU Isolates Processes & Guards Silicon

Why did *(volatile uint32_t *)0x0209C000 = 1U; crash main() with SIGSEGV instead of toggling a GPIO pin, and how can two C programs run simultaneously without overwriting each other's variables? Because on a Linux system, no user-space C pointer ever holds a physical RAM or bus address. Every pointer (&b, malloc(), function addresses) holds a Virtual Address (VA) translated on every single load, store, and instruction fetch by silicon inside the CPU called the Memory Management Unit (MMU). Follow the three columns of Figure 1.1b:

  1. Per-Process Virtual Address Spaces (Left Column): When Process A (PID 410) and Process B (PID 411) run the same binary, both can hold the exact same virtual address 0x00404010! Each virtual address splits into an upper Virtual Page Number (VPN) and a lower 12-bit Page Offset ([11:0], 0..4095 inside a 4 KiB page).
  2. Hardware Page Tables & TLB Lookup (Center Column): A privileged CPU register (CR3 on x86-64; TTBR0 on ARMv7-A) points the MMU at the currently scheduled process's kernel-managed page table (cached in nanoseconds inside the Translation Lookaside Buffer, TLB). PID 410's page table maps VPN 0x00404 to physical frame 0x82140 (U=1 user-accessible, RW), while PID 411's table maps the same VPN 0x00404 to a completely disjoint physical DDR frame 0x9A030!
  3. Protected Physical MMIO Silicon (Right Column): Physical peripheral registers such as GPIO1 (0x0209C000) and CCM clocks (0x020C4000) have no valid user-space page-table entry (V=0 / U=0). The instant Ring 3 code dereferences 0x0209C000, the MMU aborts the bus cycle in hardware and traps into the kernel page-fault handler (SIGSEGV), whereas Ring 0 kernel drivers map 0x0209C000 into kernel-only virtual memory via ioremap() with uncached Device attributes!
fig_m01_l01_vmem_mmu.svg — Virtual vs physical memory — the CPU MMU translates…

Figure 1.1b. Virtual vs physical memory — the CPU MMU translates identical virtual addresses in PID 410 and PID 411 to separate 4 KiB physical RAM frames while blocking raw Ring-3 MMIO pointers with SIGSEGV.

One Layer Down: ABI Trap Registers, Seven Subsystems, and Latency Math

When a user-space C program invokes a system call, the CPU does not jump to an arbitrary kernel address. On x86-64 System V ABI, the wrapper loads the syscall number into %rax and up to six arguments into %rdi, %rsi, %rdx, %r10, %r8, and %r9, then executes syscall; the hardware saves the user instruction pointer into %rcx, masks flags via IA32_FMASK, switches to the per-thread kernel stack, and enters entry_SYSCALL_64. On 32-bit ARMv7 (Cortex-A7 EABI), the syscall number goes into r7, arguments occupy r0..r5, and svc #0 vector-traps into Supervisor (SVC) mode. Inside Ring 0, the Linux kernel mediates hardware and shared resources across seven core subsystems: system calls, VFS, virtual memory (MMU), process scheduling, IPC, networking, and device drivers (struct file_operations callbacks using copy_from_user() and copy_to_user()).

Quantifying transition cost explains why systems C separates Ring 3 computation from Ring 0 traps. On modern x86-64 and ARMv7 cores with kernel page-table isolation and Spectre/Meltdown mitigations, one null getpid() syscall trap costs roughly t_trap = 120..350 ns, whereas a pure Ring 3 function call (strlen()) or a vDSO clock_gettime(CLOCK_MONOTONIC, &ts) read of the kernel's seqcount page via AT_SYSINFO_EHDR costs t_vdso = 15..25 ns. Emitting N = 1,000,000 four-byte records via unbuffered write() burns N * t_trap = ~250 ms in pure mode-switch overhead before counting storage latency; batching into 8 KiB (8,192-byte) chunks cuts trap count to ceil(4,000,000 / 8,192) = 489 calls (~0.12 ms), a more than 2,000x reduction in trap overhead!

Execution PathCPU Privilege & Address SpaceEntry MechanismTypical LatencyFailure Blast Radius & strace Visibility
Bare-metal MCU firmwareUnprotected flat physical busDirect *(volatile uint32_t *)2..10 nsCorrupts any peripheral; halts entire board
Pure Ring 3 C helperRing 3 / EL0 virtual RAMStandard ABI call / bl1..5 nsProcess SIGSEGV only; 0 strace lines
linux-vdso.so.1 fastpathRing 3 / EL0 read-only shared pageAT_SYSINFO_EHDR call (clock_gettime)15..25 nsRead-only isolation; 0 strace lines
User-to-kernel syscallRing 3 -> Ring 0 VFS gatesyscall (x86-64) / svc #0 (ARMv7)120..350 nsKernel validates copy_from_user(); 1:1 strace
Kernel character driverRing 0 / EL1 kernel virtual spacestruct file_operations vtableHardware-boundKernel oops or panic (GL-E04 scope)
step_m01_l01.svg — User-space C logic and kernel drivers meet strictly…step 1/4
  1. Step 1. Raw MMIO dereferences in Ring 3 fault immediately in the MMU (SIGSEGV), protecting sibling processes and silicon.
  2. Step 2. Pure Ring 3 C helpers and linux-vdso.so.1 clock_gettime() execute in user virtual memory with zero kernel traps.
  3. Step 3. System calls issue a synchronous syscall / svc #0 CPU trap across the ABI gate into Ring 0.
  4. Step 4. VFS dispatches file and /dev operations to driver struct file_operations callbacks using copy_from_user().

Figure 1.1c. User-space C logic and kernel drivers meet strictly across the VFS system call boundary.

Benchmarking Ring 3 + vDSO vs Syscall Traps in ISO C11

Because POSIX abstracts files, pipes, sockets, and /dev nodes behind uniform integer descriptors, standard user-space C code compiles cleanly across x86-64 workstations and embedded ARMv7 targets under -std=c11 -Wall -Wextra -Werror. Save hello_systems.c below: it verifies fixed-width <stdint.h> layout, inspects its isolated Ring 3 stack virtual address, and times 2,000 clock_gettime(CLOCK_MONOTONIC) vDSO reads against 2,000 real getpid() kernel traps via syscall(SYS_getpid).

learner@ksa: ~/gl-c01/m01-l01
learner@ksa:~/gl-c01/m01-l01$ bat -H 17 -H 25 -H 31 hello_systems.c File: hello_systems.c    #define _GNU_SOURCE    #include <stdint.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/syscall.h>    #include <time.h>    #include <unistd.h>        struct course_banner {        char code[8];        uint32_t magic;        uint16_t modules;    };        static uint64_t ns_since(struct timespec a, struct timespec b) {      return (uint64_t)(b.tv_sec - a.tv_sec) * 1000000000ULL +               (uint64_t)(b.tv_nsec - a.tv_nsec);    }        int main(void) {        struct course_banner b = {"GL-C01", 0x4B534131U, 6U};        size_t code_len = strlen(b.code);        uintptr_t vaddr = (uintptr_t)(const void *)&b;      struct timespec t0, t1, t2, probe;        volatile long sink = 0;            clock_gettime(CLOCK_MONOTONIC, &t0);        for (int i = 0; i < 2000; i++) {            clock_gettime(CLOCK_MONOTONIC, &probe);      }        clock_gettime(CLOCK_MONOTONIC, &t1);        for (int i = 0; i < 2000; i++) {            sink += syscall(SYS_getpid);        }        clock_gettime(CLOCK_MONOTONIC, &t2);        (void)sink;            uint64_t vdso_ns = ns_since(t0, t1);        uint64_t trap_ns = ns_since(t1, t2);        printf("course=%s code_len=%zu modules=%u u32_bytes=%zu vmem_ok=%d\n",               b.code, code_len, (unsigned int)b.modules,               sizeof(b.magic), vaddr > 4096U && trap_ns > vdso_ns);        return EXIT_SUCCESS;    }
  1. Define _GNU_SOURCE before headers so <time.h> and <sys/syscall.h> expose CLOCK_MONOTONIC and raw syscall(SYS_getpid).
  2. clock_gettime(CLOCK_MONOTONIC) reads the kernel timekeeper page mapped in linux-vdso.so.1 without trapping into Ring 0.
  3. syscall(SYS_getpid) forces a real CPU privilege switch on every iteration so we can contrast trap cost against vDSO reads.
learner@ksa: ~/gl-c01/m01-l01
learner@ksa:~/gl-c01/m01-l01gcc -fdiagnostics-color=always -std=c11 -O2 -Wall -Wextra -Werror hello_systems.c -o hello_systemslearner@ksa:~/gl-c01/m01-l01./hello_systemscourse=GL-C01 code_len=6 modules=6 u32_bytes=4 vmem_ok=1learner@ksa:~/gl-c01/m01-l01grep -q 'vdso' /proc/self/maps && echo vdso_mapped=1vdso_mapped=1learner@ksa:~/gl-c01/m01-l01sh -c 'strace -e trace=clock_gettime ./hello_systems 2>&1 >/dev/null | grep -c "^clock_gettime" || true'0learner@ksa:~/gl-c01/m01-l01strace -e trace=getpid ./hello_systems 2>&1 >/dev/null | grep -c '^getpid('2000learner@ksa:~/gl-c01/m01-l01rm -f hello_systemslearner@ksa:~/gl-c01/m01-l01

Tracing the Execution Split, Pitfalls & Practice

Look closely at what ./hello_systems and strace just proved on Linux 6.12. Initializing struct course_banner and calling strlen(b.code) ran strictly inside unprivileged Ring 3 against virtual stack pages above 0x1000 (vaddr > 4096U). Next, 2,000 calls to clock_gettime(CLOCK_MONOTONIC, &probe) read the shared linux-vdso.so.1 kernel page directly in Ring 3, recording vdso_traps=0 under strace, whereas 2,000 raw syscall(SYS_getpid) calls crossed the hardware trap gate 2,000 times (getpid_traps=2000) and consumed substantially higher wall-clock time (trap_ns > vdso_ns).

Common Production Pitfalls

warning: Symptom: An engineer runs strace ./daemon to verify whether monotonic timestamping is firing, sees zero clock_gettime lines, and falsely concludes the timer code was compiled out. Root Cause: On x86-64 and ARMv7 Linux, glibc resolves clock_gettime() and gettimeofday() through linux-vdso.so.1 (AT_SYSINFO_EHDR) in Ring 3 without executing syscall or svc #0, and strace only intercepts kernel privilege switches. Fix: Trace user-space library calls with ltrace or gdb breakpoints rather than strace whenever inspecting vDSO-accelerated routines.

warning: Symptom: A legacy hardware diagnostic ported from bare-metal C dereferences (volatile uint32_t *)0x0209C000 inside main() and crashes immediately with SIGSEGV (exit code 139). Root Cause: Every pointer in a Linux user process is a Ring 3 virtual address translated by per-process page tables; unmapped physical bus addresses fault in the MMU before touching interconnect wires. Fix: Access hardware strictly through VFS character device nodes (/dev/gpiochip*, /dev/spidev*, /dev/i2c-*) backed by Ring 0 kernel drivers (Later: user-space peripheral buses are covered in GL-C04, and Ring 0 struct file_operations driver authoring is covered in GL-E04).

Guided Practice: Predicting Trap Counts Across Mixed Loops

Suppose you extend hello_systems.c with a loop of 500 iterations where each iteration calls memcpy(dst, src, 32), clock_gettime(CLOCK_MONOTONIC, &ts), and write(STDOUT_FILENO, "ok\n", 3) on an unbuffered descriptor. Before testing:

  1. Step 1 (Classify each call's ring boundary): Identify which of the three calls touches only Ring 3 stack/heap RAM, which reads the vDSO shared page, and which issues a syscall / svc #0 trap—review the execution-path table above if unsure.
  2. Step 2 (Compute exact strace line counts): Predict the exact integer count printed by strace -c for memcpy, clock_gettime, and write (0, 0, and 500), then verify by adding a 10-iteration write(STDOUT_FILENO, ...) loop to a scratch copy of hello_systems.c.

Independent Practice: Trap-Amortization Breakeven Estimator

Write a standalone C11 program trap_budget.c compiled with -std=c11 -O2 -Wall -Wextra -Werror that measures the median per-call latency (across N = 10,000 iterations using CLOCK_MONOTONIC) of (a) a pure Ring 3 byte-accumulation function over a 64-byte array, (b) clock_gettime(CLOCK_MONOTONIC), and (c) syscall(SYS_getpid). Print the measured ratio trap_ns / vdso_ns, and calculate how many 16-byte sensor records must be batched into one 4,096-byte buffer so privilege-switch time stays below 1% of a 1 ms sampling budget.

Knowledge Check

quiz · 1 of 4

An embedded firmware engineer porting bare-metal MCU LED code to a Linux user-space daemon attempts to dereference physical GPIO register 0x0209C000 directly inside main(). What happens when the process runs?

quiz · 2 of 4

How do user-space C applications and Linux kernel character drivers cooperate when controlling a /dev/led0 device node?

quiz · 3 of 4

Why does GL-C01 open the four-course Linux Systems C series with VFS file descriptors and stdio buffering before IPC/sockets (GL-C03) or embedded peripherals (GL-C04)?

quiz · 4 of 4

A latency benchmark calls clock_gettime(CLOCK_MONOTONIC, &ts) two thousand times, yet strace -e trace=clock_gettime ./bench prints 0 syscall lines when you review the trace. Which mechanism accounts for this observation?

Key takeaways

  • GL-C01 opens the 4-course Linux Systems Programming in C series by establishing the toolchain, VFS descriptor, and stdio buffering foundation used across filesystems, IPC, sockets, and /dev peripherals.
  • Bare-metal firmware mixes user logic and raw MMIO register writes in one flat address space, whereas Linux isolates Ring 3 / EL0 user processes from Ring 0 / EL1 struct file_operations drivers via the MMU.
  • Standard system calls cross from Ring 3 / EL0 user mode into Ring 0 / EL1 Linux kernel mode via synchronous CPU traps across seven core subsystems, while linux-vdso.so.1 (AT_SYSINFO_EHDR) serves clock_gettime() from a read-only shared page with zero traps.
  • Standard user-space C code compiles cleanly across x86-64 workstations and embedded ARMv7 targets when built with strict -std=c11 -Wall -Wextra -Werror discipline.
  • Next, before invoking raw Linux kernel descriptors directly, we will dissect the four-stage GCC and static-archive build pipeline, POSIX feature-test macros, boundary integer types, and ISO C11 Undefined Behavior defenses.
Progress is saved on this device.

search — fzf

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

keyboard shortcuts — less

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

figure