learner@ksa:~/gl-e00$
>_ Kernel Systems Academy
Linux Host Workbench, POSIX Shell, Network Boot & Embedded C Style
Engineers transitioning from bare-metal MCUs or desktop software to Linux host toolchains, embedded board bring-up, and kernel C development
Outcome: Provision, audit, and troubleshoot a deterministic Linux embedded engineering host, multi-NIC TFTP/NFS boot bench, kernel-style C11 codebase, and ARMv7-A cross-ABI deployment pipeline.
- m01/ Host Virtualization Bridges, PTY Streams & Shell Pipelines
- m02/ Filesystem Hierarchy, Permissions, Archives & Partition Guards
- m03/ APT Package Graphs, Dual-NIC Routing & TFTP/NFS Boot Bench
- m04/ Linux Kernel & Embedded C11 Coding Style & Defensive Hygiene
- m05/ Serial Consoles, Boot Straps, UUU Flashing & Bring-Up Triage
- m06/ Cross-ABI ELF Auditing, Module Vermagic & Workbench Capstone
m01/
>_ Kernel Systems Academy
# Host Virtualization Bridges, PTY Streams & Shell Pipelines
Provision hardware-virtualized Linux network bridges, deterministic udev USB device permissions, POSIX file-descriptor redirection pipelines, sudo-safe cross-compiler PATH environments, and modal tree-search workflows verified by an ISO C11 workbench auditor.
- 1.1 Linux Host & Hypervisor Bridges, USB Passthrough & udev Rules
- 1.2 Pseudoterminals (PTY), File-Descriptor Redirection & sudo PATH Isolation
- 1.3 Modal Text Editing, Tree Search Pipelines & Workbench Audit Studio
lab → Linux Workbench udev, dup2 Redirection & PATH Security Auditor
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Linux Host & Hypervisor Bridges, USB Passthrough & udev Rules
What you'll learn
- Configure a dual-NIC hypervisor topology separating NAT internet access from a wired Layer-2 bench bridge.
- Diagnose why Wi-Fi 802.11 client stations reject spoofed guest MAC frames and why NAT blocks unsolicited board TFTP requests.
- Author deterministic udev rules for CH340 USB-UART consoles (1a86:7523) and i.MX6ULL SDP Boot ROM recovery devices (15a2:0080).
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Embedded Benches Break Inside Default Virtual Machine Settings
- Desktop software engineers rarely notice whether their Linux virtual machine sits behind hypervisor Network…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Embedded Benches Break Inside Default Virtual Machine Settings
- Switching the single virtual adapter to automatic
Bridgedmode creates a subtle trap on laptops.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Embedded Benches Break Inside Default Virtual Machine Settings
Figure 1.1a: Hardware EPT paging plus isolated NAT (WAN) and wired L2 Bridge (bench) paths eliminate MAC drops and USB re-enumeration permission loss.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of a hypervisor network and USB layer like a laboratory building's mailroom and badge desk: NAT acts like an outbound corporate mailroom where staff can mail letters out, yet couriers arriving from the hardware lab bench with no employee extension number are turned away at the lobby. A dedicated wired Bridge opens a direct loading-dock bay straight into the bench subnet, while udev acts as permanent badge-provisioning rules keyed to a device's manufacturer serial (idVendor:idProduct) rather than a visitor sticker (chmod) that falls off every time the device walks out and re-enters.
Where it stops working: Unlike physical doors, 802.11 Wi-Fi station interfaces enforce strict MAC-address framing at the radio link layer, and Linux udev evaluates keys across a hierarchy of parent sysfs kobjects where mixing ATTR and ATTRS from two distinct parent levels fails to match.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Extended Page Tables (EPT) and Netlink uevent
definition: Extended Page Tables (EPT on Intel VT-x, Rapid Virtualization Indexing on AMD-V) add a second hardware MMU translation stage mapping guest-physical addresses (gPA) to host-physical RAM (hPA), allowing KVM or VMware guests to compile the Linux kernel without trapping on guest page-table updates. When a USB device enumerates inside the guest, the Linux kernel emits a AF_NETLINK (NETLINK_KOBJECT_UEVENT) message to user-space systemd-udevd, which evaluates /etc/udev/rules.d/*.rules in lexical order before exposing the /dev character node.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Why Embedded Benches Break Inside Default Virtual Machine Settings
Verify hardware virtualization flags and assign two distinct virtual NICs: NAT for internet and a wired-only Bridge for the target board.
Separate NAT WAN from wired L2 bridges and bind USB permissions via udev == matchers.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inside KVM/VMware L2 Bridging and udev Operator Semantics
- At the CPU and memory boundary, a Type-1/2 hypervisor (
KVM/QEMUorVMware Workstation) executes guest…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inside KVM/VMware L2 Bridging and udev Operator Semantics
- At the I/O boundary,
udevrule syntax is unforgiving because C-like operators carry distinct state-machin…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Inside KVM/VMware L2 Bridging and udev Operator Semantics
Figure 1.1b: Exact operator distinction (== predicate vs = / += assignment) prevents silent wildcard matches and world-writable 0666 hazards.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# 99-embedded-bench.rules
learner@ksa:~/gl-e00/m01-l01$ bat 99-embedded-bench.rules───────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── │ File: 99-embedded-bench.rules───────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ # /etc/udev/rules.d/99-embedded-bench.rules 2 │ # 1. USB-UART serial console (CH340 1a86:7523 & CP2102 10c4:ea60) -> /dev/ttyBENCH0 3 │ SUBSYSTEM=="tty", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", MODE="0660", GROUP="dialout", SYMLINK+="ttyBENCH0" 4 │ SUBSYSTEM=="tty", ATTRS{idVendor}=="10c4", ATTRS{idProduct}=="ea60", MODE="0660", GROUP="dialout", SYMLINK+="ttyBENCH0" 5 │ 6 │ # 2. i.MX6ULL Boot ROM USB OTG Serial Download Protocol (SDP HID 15a2:0080) for UUU 7 │ SUBSYSTEM=="usb", ATTR{idVendor}=="15a2", ATTR{idProduct}=="0080", MODE="0660", GROUP="plugdev", TAG+="uaccess"───────┴────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# udev
udev(7) GL-E00 Quick Reference udev(7) NAME udev, udevadm - Linux kernel dynamic device management and rule verifier SYNOPSIS udevadm info -a -n /dev/ttyUSB0 sudo udevadm control --reload-rules && sudo udevadm trigger udevadm test $(udevadm info -q path -n /dev/ttyUSB0) OPERATORS == Compare key for equality (predicate; MUST be used on SUBSYSTEM/ATTR/ATTRS). != Compare key for inequality. = Assign value to key (MODE="0660", GROUP="dialout"), overwriting prior rules. += Append value to multi-string key (SYMLINK+="ttyBENCH0", TAG+="uaccess"). Kernel Systems Academy m01-l01 udev(7) GL-E00 quick reference · full manual page: man 7 udev GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Auditing VM Bridge Selection and udev Rules in Host C11
- Before deploying workstation onboarding scripts across an engineering team, we can validate both hypervisor…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Auditing VM Bridge Selection and udev Rules in Host C11
- Pay close attention to how
audit_udev_line()distinguishes==match predicates from=assignments and…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m01-l01$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <ctype.h> 3 │ #include <stdio.h> 4 │ #include <stdlib.h> 5 │ #include <string.h> 6 │ 7 │ typedef struct { 8 │ const char *name; 9 │ int has_nat_wan; 10 │ int has_wired_bridge; 11 │ int bridges_wifi; 12 │ } vm_net_cfg_t; 13 │ 14 │ static int verify_vm_topology(const vm_net_cfg_t *cfg) {───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Verifying Rule Diagnostics and System Call Output
- Compile
verify.cunder strict-std=c11 -Wall -Wextra -Werrorand inspect both stdout and thestraces…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Verifying Rule Diagnostics and System Call Output
learner@ksa:~/gl-e00/m01-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l01$ ./verifyvm_check: auto_wifi=-1 dual_nic_wired=0udev_check: ch340_0660=0 (mode=0660) single_eq=-10 mode_0666=-12learner@ksa:~/gl-e00/m01-l01$ GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Verifying Rule Diagnostics and System Call Output
learner@ksa:~/gl-e00/m01-l01$ strace -e trace=write,exit_group ./verifywrite(1, "vm_check: auto_wifi=-1 dual_nic_"..., 105) = 105exit_group(0) = ?+++ exited with 0 +++GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Common Virtualization & USB Hotplug Failure Modes
- A reliable embedded Linux workstation separates network planes and eliminates manual root interventions on…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: udevadm test reports zero matching rules even though both ATTRS{idVendor} and an interface-level ATTRS{bInterfaceNumber} exist in udevadm info -a.
- Root Cause: systemd-udevd requires all ATTRS{...} predicates within a single rule to match on the same parent sysfs device node rather than cherry-picking attributes from two different ancestor levels.
- Fix: Match SUBSYSTEM=="tty" at the leaf node and keep ATTRS{idVendor} plus ATTRS{idProduct} on the single usb-serial or usb_device parent, or use ENV{ID_VENDOR_ID}=="1a86" populated by usb_id.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: After running sudo minicom -s or sudo uuu, subsequent non-root runs fail to save configuration files or build artifacts in $HOME with Permission denied.
- Root Cause: Invoking interactive tools under sudo preserves $HOME on many distributions while running as UID 0, creating root-owned dotfiles (~/.minirc.dfl) and masking missing dialout/plugdev group membership.
- Fix: Fix /etc/udev/rules.d/ permissions to 0660 with GROUP="dialout" or GROUP="plugdev", add your user via sudo usermod -aG dialout,plugdev $USER, re-login so id -Gn shows the new groups, and chown any root-owned $HOME files back.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
verify.cto parse an optionalSYMLINK+="ttyBENCH0"token and reject rules that use `SYMLINK="tty…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a two-rule udev snippet and matching C11 unit test for a dual-channel
FT2232H(0403:6010) JTAG +…
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? Your Linux VM uses a single network adapter set to 'Bridged (Automatic)' on a laptop connected to corporate Wi-Fi and a USB-Ethernet dongle wired to an i.MX6ULL board. U-Boot prints ARP Retry count exceeded. What is the root cause?
Select an option or press R to reveal.
Correct: B
Hypervisor Auto-Bridging frequently selects the primary host route (Wi-Fi) rather than an unrouted USB-Ethernet bench dongle, and 802.11 client stations cannot bridge spoofed guest MAC addresses.
Common misconception: Assuming 'Bridged (Automatic)' bridges all physical host adapters simultaneously or works transparently over 802.11 client Wi-Fi.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? An engineer writes SUBSYSTEM=="usb", ATTR{idVendor}="15a2", ATTR{idProduct}=="0080", MODE="0660", GROUP="plugdev" in /etc/udev/rules.d/99-sdp.rules, reloads udev, and finds UUU still gets LIBUSB_ERROR_ACCESS. Why?
Select an option or press R to reveal.
Correct: A
In udev syntax, == tests equality while = attempts to write to a sysfs attribute or property; idVendor is a read-only USB descriptor field requiring == and bare 4-digit lowercase hex without 0x.
Common misconception: Treating single = and double == as interchangeable or misremembering lexical rule order (99-* runs AFTER 50-*).
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? After adding yourself to dialout via sudo usermod -aG dialout $USER and reloading udev, opening /dev/ttyUSB0 (crw-rw---- 1 root dialout) in your existing terminal still fails with Permission denied. What is the fastest causal check?
Select an option or press R to reveal.
Correct: D
Process credentials (cred->group_info) are inherited from parent to child at fork() time; usermod edits /etc/group on disk without mutating already-running shell processes.
Common misconception: Believing /etc/group is consulted dynamically by the kernel VFS on every open(2) call.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Summary
- Hardware virtualization pairs VT-x or AMD-V guest execution modes with Extended Page Tables (EPT) so guest virtual-to-host-physical translations resolve in silicon without per-fault hypervisor traps.
- A dual-adapter VM layout uses Adapter 1 in NAT mode for outbound WAN package traffic and Adapter 2 bridged exclusively to a wired USB-Ethernet bench NIC for L2 ARP, TFTP, and NFS traffic.
- Declarative /etc/udev/rules.d/ rules match SUBSYSTEM and hexadecimal idVendor/idProduct attributes with == to assign 0660 dialout or plugdev group ownership across every USB hotplug cycle.
- USB Boot ROM recovery tools re-enumerate target silicon from SDP HID mode (15a2:0080) into Fastboot endpoints, requiring persistent udev rules and hypervisor vendor-ID filters instead of one-shot chmod 666 hacks.
GL-E00 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Key takeaways
- A dual-adapter VM layout uses Adapter 1 in NAT mode for outbound WAN package traffic and Adapter 2 bridged exclusively to a wired USB-Ethernet bench NIC for L2 ARP, TFTP, and NFS traffic.
- Declarative /etc/udev/rules.d/ rules match SUBSYSTEM and hexadecimal idVendor/idProduct attributes with == to assign 0660 dialout or plugdev group ownership across every USB hotplug cycle.
- USB Boot ROM recovery tools re-enumerate target silicon from SDP HID mode (15a2:0080) into Fastboot endpoints, requiring persistent udev rules and hypervisor vendor-ID filters instead of one-shot chmod 666 hacks.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Pseudoterminals (PTY), File-Descriptor Redirection & sudo PATH Isolation
What you'll learn
- Contrast kernel n_tty signal/canonical processing on /dev/pts/N against raw 8N1 serial byte streams on /dev/ttyUSB0.
- Trace exact file-descriptor table mutations across dup2(1, 2) redirection orders and pipefail shell pipelines.
- Prevent sudo secure_path cross-compiler loss by separating unprivileged compilation from staged root installation.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Where Bytes and Signals Actually Go Inside a Terminal Window
- When you open an SSH session or a desktop terminal tab (
Ctrl-Shift-T) and runps -ef, theTTYcolumn…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Where Bytes and Signals Actually Go Inside a Terminal Window
- Pressing
Ctrl-Csends byte0x03;n_ttyintercepts it underISIGmode and deliversSIGINTto the l…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Where Bytes and Signals Actually Go Inside a Terminal Window
- Two daily build failures stem directly from how shells wire descriptors and environments around child proce…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Where Bytes and Signals Actually Go Inside a Terminal Window
Figure 1.2a: Redirection operators mutate the child file-descriptor table sequentially from left to right; 2>&1 copies the current target of fd 1, not its future target.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Mental model
note: Picture fd 1 (stdout) and fd 2 (stderr) as two clipboards holding room numbers—both initially say Room pts/0. Writing 2>&1 does not glue the two clipboards together forever; it tells the clerk: copy whatever room number is written on Clipboard 1 right now onto Clipboard 2. If you copy Clipboard 1 onto Clipboard 2 first (2>&1, both say pts/0) and then erase Clipboard 1 to write build.log (>build.log), Clipboard 2 still says pts/0!
Where it stops working: The clipboard metaphor shows pointer assignment order, whereas in the Linux kernel dup2(1, 2) increments the reference count on a shared struct file description—meaning fd 1 and fd 2 also share a single atomic f_pos file offset rather than overwriting each other at byte 0.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Open File Description Sharing (dup2) and sudo secure_path
definition: POSIX separates a process-private file descriptor integer (0, 1, 2) from the kernel-wide open file description (struct file holding f_pos and O_APPEND flags). Calling dup2(1, 2) closes fd 2 and points slot 2 at the exact struct file currently referenced by slot 1. Separately, sudo enforces privilege-escalation hygiene via Defaults env_reset and Defaults secure_path in /etc/sudoers, discarding caller PATH and LD_LIBRARY_PATH variables so an unprivileged user cannot trick a root command into executing a trojan ls or gcc placed in /tmp.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Where Bytes and Signals Actually Go Inside a Terminal Window
Enable set -euo pipefail at the top of build and deployment scripts so downstream loggers like tee cannot mask compiler failures.
Order >log before 2>&1, set pipefail on build pipes, and never compile under sudo.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
- Inside
fs/file.c, each task holdscurrent->files->fdt->fd[], an array mapping small integers (0,1,…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
- When chaining processes with
|(make -j8 2>&1 | tee build.log), the shell creates an anonymous `pipe2()…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
- Finally,
/etc/sudoerscompilesDefaults secure_path="/usr/local/sbin:...:/bin".
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Kernel File Table Mechanics, Pipeline Exit Codes & sudoers Scrubbing
Figure 1.2b: Sharing one struct file via dup2(1, 2) serializes f_pos offsets, while pipefail preserves left-hand compiler failures.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# safe_cross_build.sh
learner@ksa:~/gl-e00/m01-l02$ #!/usr/bin/env bashset -euo pipefail export PATH="/opt/toolchains/arm-gnu-toolchain/bin:${PATH}"STAGE_DIR="${PWD}/_rootfs_stage"LOG_FILE="${PWD}/build_kernel.log" # 1. Unprivileged cross-build: stdout + stderr share pipe into tee; pipefail guards rcmake ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- -j"$(nproc)" zImage modules dtbs 2>&1 | tee "${LOG_FILE}" # 2. Stage modules without sudo (preserves CROSS_COMPILE in PATH and user file ownership)make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- INSTALL_MOD_PATH="${STAGE_DIR}" modules_install >"${STAGE_DIR}.log" 2>&1learner@ksa:~/gl-e00/m01-l02$ GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# dup2
dup2(2) GL-E00 Quick Reference dup2(2) NAME dup2, pts, sudoers - duplicate file descriptors, PTY pairs, and sudo PATH policy SYNOPSIS #include <unistd.h> int dup2(int oldfd, int newfd); DESCRIPTION dup2() makes newfd refer to the same open file description (struct file) as oldfd. In POSIX sh: >file 2>&1 opens file on fd 1, then calls dup2(1, 2). 2>&1 >file calls dup2(1, 2) while fd 1 is still /dev/pts/N, then reopens fd 1. NOTES ON SUDOERS Kernel Systems Academy m01-l02 dup2(2) GL-E00 quick reference · full manual page: man 2 dup2 GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Proving dup2() Redirection Order With Real Kernel Pipes in C11
- Rather than memorizing shell folklore, we can execute the exact kernel
pipe()anddup2()sequences in I…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Proving dup2() Redirection Order With Real Kernel Pipes in C11
- We also test
sudosecure_pathscrubbing by verifying whether/opt/toolchains/arm/binsurvives a reset…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m01-l02$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdio.h> 3 │ #include <string.h> 4 │ #include <unistd.h> 5 │ 6 │ static int drain_pipe(int rfd, char *buf, size_t cap) { 7 │ ssize_t n = read(rfd, buf, cap - 1); 8 │ if (n < 0) n = 0; 9 │ buf[n] = '\0'; 10 │ return (int)n; 11 │ } 12 │ 13 │ static int run_redirection_case(int log_before_dup, char *pts_out, char *log_out) { 14 │ int pts_p[2], log_p[2];───────┴────────────────────────────────────────────────────────────────────────────────────GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Inspecting Real pipe2() and dup2() Syscalls Under strace
- Examine the captured shell output and
stracetrace below.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Inspecting Real pipe2() and dup2() Syscalls Under strace
learner@ksa:~/gl-e00/m01-l02$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l02$ ./verifycase_gt_log_2gt1: pts_bytes=0 log=[OUT+ERR] (8B)case_2gt1_gt_log: pts=[ERR] (4B) log=[OUT] (4B)cross_cc_visible: user_shell=1 sudo_secure_path=0learner@ksa:~/gl-e00/m01-l02$ GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Inspecting Real pipe2() and dup2() Syscalls Under strace
learner@ksa:~/gl-e00/m01-l02$ strace -e trace=pipe2,dup2,write,read,close \> ./verifyclose(3) = 0read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832close(3) = 0pipe2([3, 4], 0) = 0pipe2([5, 6], 0) = 0dup2(4, 1) = 1dup2(4, 2) = 2dup2(6, 1) = 1dup2(1, 2) = 2write(1, "OUT\n", 4) = 4write(2, "ERR\n", 4) = 4dup2(7, 1) = 1dup2(8, 2) = 2GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Subtle Redirection, PTY Signal & sudo Build Traps
- Understanding descriptor tables and line disciplines eliminates mysterious terminal behavior across both ho…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: While logged into a target board over a naive script (cat /dev/ttyUSB0), pressing Ctrl-C kills the local cat command on the host instead of stopping ping on the board.
- Root Cause: The host shell's /dev/pts/N n_tty line discipline still has ISIG enabled, so 0x03 generates SIGINT locally on the host before ever reaching /dev/ttyUSB0.
- Fix: Use a dedicated serial terminal (picocom -b 115200 /dev/ttyBENCH0 or minicom) that puts the local PTY into cfmakeraw() (~ISIG & ~ICANON & ~ECHO), forwarding 0x03 verbatim over UART and reserving an escape chord (Ctrl-A Ctrl-X) for host exit.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Subsequent normal make invocations fail with Fatal error: can't create scripts/basic/.fixdep.d: Permission denied.
- Root Cause: A single sudo make left .o, .cmd, and include/config/ directories owned by UID 0:0 inside your working tree, blocking unprivileged compiler updates.
- Fix: Reclaim ownership once via sudo chown -R "$(id -u):$(id -g)" ., and never invoke sudo for menuconfig, zImage, dtbs, or modules builds.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Guided Practice
- Modify
verify.cto add a third helperrun_dual_open_case()that opens a temporary file twice (`fd_a = o…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Independent Practice
- Write a POSIX C11 wrapper using
fork(),pipe(),dup2(), andwaitpid()that runs two child stages (`…
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? A CI script runs ./build_uboot.sh 2>&1 >/tmp/uboot.log. When compilation fails with an undefined symbol error, /tmp/uboot.log contains Makefile echo lines but zero linker error messages. Why?
Select an option or press R to reveal.
Correct: A
Redirections execute strictly left to right: 2>&1 duplicates whatever fd 1 points to at that moment, so >/tmp/uboot.log must appear BEFORE 2>&1.
Common misconception: Thinking 2>&1 creates a permanent symbolic alias to 'whatever fd 1 eventually becomes' rather than an immediate dup2(1, 2) call.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? Why does sudo -E make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- still fail to find arm-linux-gnueabihf-gcc installed in /opt/arm-gcc/bin on Ubuntu and Debian hosts?
Select an option or press R to reveal.
Correct: D
When /etc/sudoers defines secure_path, sudo replaces PATH unconditionally for security against untrusted user directories, regardless of -E.
Common misconception: Assuming sudo -E bypasses /etc/sudoers secure_path enforcement.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? Without set -o pipefail, what exit code ($?) does make -j8 zImage 2>&1 | tee build.log return when gcc aborts with a syntax error?
Select an option or press R to reveal.
Correct: C
By default, POSIX shells set $? to the exit status of the last command in a pipeline (tee), completely hiding failures in upstream compilation stages unless pipefail is enabled.
Common misconception: Assuming a shell pipeline automatically fails when its first command exits non-zero.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Summary
- A pseudoterminal pairs a /dev/ptmx master descriptor owned by the terminal emulator with a /dev/pts/N replica governed by the Linux kernel n_tty line discipline.
- Shell redirections execute strictly left to right via dup2(oldfd, newfd): >build.log 2>&1 sends both streams to build.log, whereas 2>&1 >build.log leaves stderr pointing at the terminal.
- Enabling set -euo pipefail causes a pipeline such as make 2>&1 | tee build.log to return the non-zero exit code of the failing build stage instead of tee's zero exit status.
- Default /etc/sudoers env_reset and secure_path policies replace user PATH variables during sudo execution, hiding user-installed ARM cross-toolchains unless builds run unprivileged with DESTDIR or INSTALL_MOD_PATH.
GL-E00 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Key takeaways
- Shell redirections execute strictly left to right via dup2(oldfd, newfd): >build.log 2>&1 sends both streams to build.log, whereas 2>&1 >build.log leaves stderr pointing at the terminal.
- Enabling set -euo pipefail causes a pipeline such as make 2>&1 | tee build.log to return the non-zero exit code of the failing build stage instead of tee's zero exit status.
- Default /etc/sudoers env_reset and secure_path policies replace user PATH variables during sudo execution, hiding user-installed ARM cross-toolchains unless builds run unprivileged with DESTDIR or INSTALL_MOD_PATH.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Modal Text Editing, Tree Search Pipelines & Workbench Audit Studio
What you'll learn
- Operate Vim across Normal, Insert, and Ex modes while auditing hard tabs with :set list in Makefiles and kernel configs.
- Construct NUL-delimited find -print0 | xargs -0 and grep -rn pipelines to locate Device Tree bindings and driver symbols safely.
- Implement a C11 workbench auditor verifying udev rules, dup2 redirection states, and colon-delimited PATH security invariants.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Surviving Headless Bring-Up Servers and 80,000-File Source Trees
- Sooner or later every embedded engineer SSHes into a build server, a stripped Docker container, or a target…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Surviving Headless Bring-Up Servers and 80,000-File Source Trees
- Pressing
i,a, oroentersInsertmode for raw text,Escreturns toNormalmode, and:enters…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Surviving Headless Bring-Up Servers and 80,000-File Source Trees
- Equally critical is searching huge trees (
Linux kernel6.12 exceeds82,000files) and auditingPATHs…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Surviving Headless Bring-Up Servers and 80,000-File Source Trees
Figure 1.3a: NUL (0x00) is the sole byte value illegal inside POSIX path components, making -print0 | xargs -0 immune to spaces and quotes.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Mental model
note: Using newline-delimited find | xargs on arbitrary trees is like shipping parts in a crate where commas separate item names, even though product labels themselves can contain commas! Switching to find -print0 | xargs -0 seals each path with 0x00—a physical bulkhead byte that the Linux kernel VFS forbids inside any filename—while scanning PATH with strchr instead of strtok inspects every empty crate slot (::) rather than skipping past empty compartments.
Where it stops working: For interactive human queries in clean Git repositories, grep -rn --include='*.[ch]' or git grep -n avoids spawning find + xargs altogether by walking directory dentries inside a single process without building giant argv[] vectors.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Empty PATH Segment (Implicit '.') and Vim Swap Recovery
definition: Under historical POSIX.1 shell lookup rules, an empty colon-separated field in PATH—whether leading (:/usr/bin), adjacent (usr/bin::/bin), or trailing (/usr/bin:)—is interpreted as . (the current working directory). Writing export PATH="/opt/arm/bin:$PATH" when $PATH was unset expands to "/opt/arm/bin:", letting an untrusted source archive hijack make or ls! Meanwhile, vim protects active edits via .filename.swp journals; if an SSH link drops, inspect differences with vim -r filename before removing stale swap files.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Surviving Headless Bring-Up Servers and 80,000-File Source Trees
Open target files directly at the diagnostic line (+42), run :set list in Ex mode to distinguish ^I tabs from spaces, and write atomically.
Use :set list for tabs, -print0 | xargs -0 for paths, and strchr to audit PATH.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning
- In
Linux kernelfs/namei.c, path resolution splits strings solely on'/'(0x2F) and terminates C st…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning
- Notice the classic C11 bug waiting inside our workbench
PATHauditor: if an engineer uses `strtok(buf, ":…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Inside Vim State Transitions, VFS Filename Bytes & C11 PATH Scanning
Figure 1.3b: Explicit colon-pointer scanning catches leading ':', interior '::', and trailing ':' hazards that C strtok() silently skips.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# tree_and_path_audit.sh
learner@ksa:~/gl-e00/m01-l03$ #!/usr/bin/env bashset -euo pipefail # 1. Safe parameter expansion: appends :$PATH only when PATH is non-emptyTOOLCHAIN_BIN="/opt/toolchains/arm-gnu-toolchain/bin"export PATH="${TOOLCHAIN_BIN}${PATH:+:${PATH}}" # 2. Reject any empty PATH segment (leading ':', '::', or trailing ':')case ":${PATH}:" in *::*) echo "FATAL: empty PATH segment (implicit CWD '.') detected" >&2; exit 1 ;;esac # 3. NUL-delimited search across Device Tree bindings and C headersfind . -type f \( -name "*.dts*" -o -name "*.h" \) -print0 | xargs -0 -r grep -n "compatible"learner@ksa:~/gl-e00/m01-l03$ GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# xargs
xargs(1) GL-E00 Quick Reference xargs(1) NAME find, xargs, grep, vim - tree search pipelines and modal file editing SYNOPSIS find <dir> -type f -name "*.c" -print0 | xargs -0 -r grep -n "<pattern>" grep -rn --include="*.[ch]" "<pattern>" <dir>/ vim +<line> <file> (Normal: Esc, /pat, n, u, dd | Insert: i, a, o | Ex: :set list, :wq, :q!) FLAGS -print0 / -0 Use NUL (0x00) instead of whitespace/quotes as record separator. -r (--no-run-if-empty) Do not invoke command when input stream is empty. :set list Render hard tabs as ^I and end-of-line as $ inside vim. Kernel Systems Academy m01-l03 xargs(1) GL-E00 quick reference · full manual page: man 1 xargs GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying NUL-Delimited Streams and Colon-Exact PATH Parsing in C11
- In
verify.c, we test both halves of Lesson 1.3 directly in ISOC11.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying NUL-Delimited Streams and Colon-Exact PATH Parsing in C11
- Second, we contrast
audit_path_strchr()againstcount_strtok_segments()on"/usr/bin::/bin".
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m01-l03$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <fcntl.h> 3 │ #include <stdio.h> 4 │ #include <stdlib.h> 5 │ #include <string.h> 6 │ #include <unistd.h> 7 │ 8 │ static int audit_path_strchr(const char *path_str, int *seg_count) { 9 │ if (!path_str || path_str[0] == '\0') return -1; 10 │ *seg_count = 0; 11 │ const char *p = path_str; 12 │ for (;;) { 13 │ const char *colon = strchr(p, ':'); 14 │ size_t len = colon ? (size_t)(colon - p) : strlen(p);───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming NUL Framing and strtok Blindness Under strace
- Check both the program output and the
stracecapture.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming NUL Framing and strtok Blindness Under strace
learner@ksa:~/gl-e00/m01-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m01-l03$ ./verifyprint0_stream: bytes=65 nul_records=3 second_record='boards/rev B/pin mux.c'path_audit: clean_rc=0(segs=3) double_colon_rc=-2 strtok_blind_segs=2learner@ksa:~/gl-e00/m01-l03$ GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Confirming NUL Framing and strtok Blindness Under strace
learner@ksa:~/gl-e00/m01-l03$ strace -e trace=openat,read,write,unlinkat \> ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\243\2\0\0\0\0\0"..., 832) = 832openat(AT_FDCWD, "/tmp/ksa_print0_0GSgQx", O_RDWR|O_CREAT|O_EXCL, 0600) = 3write(3, "drivers/tty/serial.c\0boards/rev "..., 65) = 65read(3, "drivers/tty/serial.c\0boards/rev "..., 128) = 65write(1, "print0_stream: bytes=65 nul_reco"..., 147) = 147+++ exited with 0 +++GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Modal Editing and Tree-Pipeline Pitfalls
- Fluency with modal editing, NUL-delimited search streams, and strict environment hygiene turns any headless…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: make aborts immediately on line 12 with Makefile:12: *** missing separator. Stop. even though indentation looks aligned.
- Root Cause: Terminal mouse selection converted the leading 0x09 hard tab (\t) into 4 or 8 ASCII spaces (0x20), which GNU make rejects on recipe lines.
- Fix: Open the Makefile in vim, run :set list to verify whether lines begin with ^I (tab) or spaces, and replace leading spaces on recipe lines with a literal Tab (:set noexpandtab).
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: vim warns Swap file ".board.dts.swp" already exists! and an engineer reflexively presses D (Delete) or runs rm .*.swp, losing an hour of unsaved Device Tree edits.
- Root Cause: Either a second terminal window currently has board.dts open (ps aux | grep vim), or a dropped SSH session left unsaved buffer deltas inside .board.dts.swp.
- Fix: First check whether another live vim PID owns the file; if none exists, open with vim -r board.dts, save to a recovery copy (:w board.dts.recovered), diff with diff -u, and only then remove .board.dts.swp.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Guided Practice
- Extend
audit_path_strchr()inverify.cto accept an array ofmode_tdirectory permission values corre…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Independent Practice
- Now open
labs/lab_m01_shell_env_audit/and repair all three defects instarter/core.csosh check.sh…
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? Why does find . -name '*.c' -print0 | xargs -0 grep -n 'clk_prepare_enable' succeed on paths containing spaces and quotes where find . -name '*.c' | xargs grep -n ... fails?
Select an option or press R to reveal.
Correct: D
Because / and \0 are the only two bytes prohibited inside POSIX filenames, 0x00 is the single unambiguous delimiter for arbitrary file paths.
Common misconception: Thinking newline (0x0A) or quotes are safe filename delimiters in POSIX user space.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? In ISO C11, why is strtok(path_copy, ":") unsafe for auditing a PATH environment variable for current-working-directory (.) security hazards?
Select an option or press R to reveal.
Correct: C
strtok() scans past any run of delimiter characters before starting the next token, making "/usr/bin::/bin" indistinguishable from "/usr/bin:/bin".
Common misconception: Assuming C strtok() behaves like Python str.split(':') on adjacent delimiters.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? You open a broken Makefile in vim over SSH. Which command sequence enters Ex mode and makes hard tabs visible as ^I versus spaces?
Select an option or press R to reveal.
Correct: B
Esc transitions the Vim FSM from Insert/Visual back to Normal mode, from which : enters Ex command-line mode and set list renders 0x09 tabs as ^I and EOL as $.
Common misconception: Typing :commands while still inside Insert mode, which inserts literal characters into the file.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Lab: lab_m01_shell_env_audit
- Onboarding scripts for embedded Linux teams routinely break because one typo in
/etc/udev/rules.d/grants…
Verify: ./check.sh exits 0.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Summary
- Vim separates Normal navigation/operator mode, Insert text-entry mode, and Command-line Ex mode (:w, :q!, :set list) so headless SSH repairs never depend on a graphical desktop.
- In Makefile recipes and Linux kernel Kconfig/C sources, :set list reveals 8-column hard tab characters (^I) versus spaces, preventing 'missing separator' build failures.
- Pairing find -print0 with xargs -0 delimits file paths with NUL (0x00) bytes—the only byte value forbidden alongside '/' inside Linux VFS filenames—preventing whitespace splitting and E2BIG.
- A secure build PATH contains only absolute ('/...') non-world-writable directories and zero empty ('::', leading ':', or trailing ':') segments that implicitly search the current working directory.
GL-E00 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Key takeaways
- In Makefile recipes and Linux kernel Kconfig/C sources, :set list reveals 8-column hard tab characters (^I) versus spaces, preventing 'missing separator' build failures.
- Pairing find -print0 with xargs -0 delimits file paths with NUL (0x00) bytes—the only byte value forbidden alongside '/' inside Linux VFS filenames—preventing whitespace splitting and E2BIG.
- A secure build PATH contains only absolute ('/...') non-world-writable directories and zero empty ('::', leading ':', or trailing ':') segments that implicitly search the current working directory.
m02/
>_ Kernel Systems Academy
# Filesystem Hierarchy, Permissions, Archives & Partition Guards
Master FHS 3.0 directory roles, VFS hard vs symbolic link semantics, character and block device major:minor nodes, octal permission/umask/sticky invariants, MBR 1 KiB raw IVT boot offsets, removable-disk safety guards, and numeric-owner rootfs tar archives.
- 2.1 Linux Filesystem Hierarchy (FHS 3.0), Inode Links & Device Nodes
- 2.2 UID/GID Identity, Octal Mode Bits, Sticky Directories & Profile Safety
- 2.3 MBR/GPT Sector Offsets, Removable-Disk Guards & Numeric-Owner Rootfs Archives
lab → SD/eMMC Partition-Offset, Sticky Unlink & ustar Rootfs Verifier
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Linux Filesystem Hierarchy (FHS 3.0), Inode Links & Device Nodes
What you'll learn
- Map FHS 3.0 directories (/bin, /sbin, /usr, /etc, /var, /run, /proc, /sys) to read-only flash, tmpfs RAM, and kernel pseudo-filesystems.
- Contrast hard-link inode sharing (link, st_nlink, EXDEV) against symbolic-link path indirection (symlink, lstat vs stat) inside staged rootfs trees.
- Decode character and block device nodes via makedev, major, and minor numbers for serial UARTs and MMC storage partitions.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Everything in Linux Looks Like a File Yet Lives in Different Worlds
- When an
ARMv7-Aboard mounts its root filesystem (/) at the end ofLinux kernelboot, user space expe…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Everything in Linux Looks Like a File Yet Lives in Different Worlds
- Understanding how the Virtual Filesystem (
VFS) binds names to inodes prevents two classic rootfs bugs.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Everything in Linux Looks Like a File Yet Lives in Different Worlds
Figure 2.1a: VFS unifies flash files, RAM tmpfs (/run), kernel pseudo-filesystems (/proc, /sys), and major:minor device nodes under one namespace.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of an inode (st_ino) as a numbered warehouse vault and directory entries (dentries) as catalog cards: a hard link prints a second catalog card stamped with the exact same vault number #4092 (the vault is emptied only after the last card is shredded and the last worker steps out of the vault), whereas a symbolic link is a sticky note on an empty box saying *'walk one aisle left to ../bin/busybox'*—if that note says *'go to the factory in Chicago'*, it breaks the moment you ship the crate to the lab!
Where it stops working: Vault numbers (ino_t) are unique only within one filesystem (st_dev)—both / (ext4) and /proc (procfs) can legitimately have an inode #2—which is why link(2) returns EXDEV (Invalid cross-device link) across mount points.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Inode Reference Count (st_nlink) and Device ID (dev_t st_rdev)
definition: Every POSIX file object is represented by a struct inode identified by (st_dev, st_ino). Regular files reclaim disk blocks only when both on-disk st_nlink == 0 and in-RAM open struct file count reach 0—explaining why deleting a huge log file (unlink) while a daemon still holds it open leaves df -h 100% full! For S_IFCHR and S_IFBLK device inodes, st_size is unused and st_rdev packs major (driver class, e.g., 179 mmcblk) and minor (partition index) via makedev(maj, min).
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Everything in Linux Looks Like a File Yet Lives in Different Worlds
Inspect live mount types with findmnt so runtime logs and sockets go to /run (tmpfs) rather than wearing out raw flash.
Keep rootfs symlinks relative, check st_dev+st_ino for hard links, and read st_rdev on /dev.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers
- Inside an embedded
ARMv7-Arootfs, FHS 3.0 gives every top-level directory a strict lifecycle contract: `…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers
- At the VFS syscall layer,
stat(path, &sb)follows symlinks to the terminal target (returning-1with `E…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# FHS 3.0 Layout, VFS Link Rules & Character/Block Major:Minor Numbers
Figure 2.1b: lstat() inspects the S_IFLNK inode directly instead of dereferencing host paths, catching broken rootfs links before flashing.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# stage_fhs_rootfs.sh
learner@ksa:~/gl-e00/m02-l01$ #!/usr/bin/env bashset -euo pipefail STAGE="${PWD}/_stage_rootfs"mkdir -p "${STAGE}"/{bin,sbin,etc,lib,proc,sys,run,tmp,usr/bin,var/log} # 1. Portable relative symlink: sbin/init -> ../bin/busybox (survives host stage & target /)ln -snf ../bin/busybox "${STAGE}/sbin/init" # 2. Audit staged tree: fail build if any symlink points into host $HOME or build directorywhile IFS= read -r -d '' lnk; do tgt="$(readlink "${lnk}")" case "${tgt}" in "${HOME}"*|"${PWD}"*) echo "FATAL: host path in symlink ${lnk} -> ${tgt}" >&2; exit 1 ;; esacdone < <(find "${STAGE}" -type l -print0)learner@ksa:~/gl-e00/m02-l01$ GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# lstat
lstat(2) GL-E00 Quick Reference lstat(2) NAME stat, lstat, link, symlink, makedev - VFS inode metadata, links, and device IDs SYNOPSIS #include <sys/stat.h> #include <sys/sysmacros.h> int stat(const char *pathname, struct stat *statbuf); int lstat(const char *pathname, struct stat *statbuf); dev_t makedev(unsigned int maj, unsigned int min); DESCRIPTION stat() dereferences symbolic links; if a symlink dangles, stat() fails with ENOENT. lstat() inspects the link inode itself (S_ISLNK(statbuf->st_mode) != 0). major(statbuf->st_rdev) and minor(statbuf->st_rdev) decode S_IFCHR / S_IFBLK drivers. Kernel Systems Academy m02-l01 lstat(2) GL-E00 quick reference · full manual page: man 2 lstat GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Proving Hard Links, Dangling Symlinks & dev_t Encoding in C11
- Let us verify these exact VFS behaviors on the Linux host in ISO
C11.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Proving Hard Links, Dangling Symlinks & dev_t Encoding in C11
- Notice how
stat()on the dangling symlink fails witherrno == ENOENTwhilelstat()succeeds and repor…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m02-l01$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _DEFAULT_SOURCE 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <string.h> 7 │ #include <sys/stat.h> 8 │ #include <sys/sysmacros.h> 9 │ #include <unistd.h> 10 │ 11 │ int main(void) { 12 │ char root[] = "/tmp/ksa_vfs_XXXXXX"; 13 │ if (!mkdtemp(root)) return 1;───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Tracing linkat, symlinkat, and newfstatat Flags in strace
- Inspect the
stracecapture closely: glibc translatesstat()andlstat()into the samenewfstatat()…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Tracing linkat, symlinkat, and newfstatat Flags in strace
learner@ksa:~/gl-e00/m02-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l01$ ./verifyhard_link: same_ino=1 nlink=2rel_symlink: is_lnk=1 target_follows_bb=1dangling_link: stat_rc=-1(ENOENT=1) lstat_rc=0(len=14)dev_t_encode: mmcblk1p2 major=179 minor=2learner@ksa:~/gl-e00/m02-l01$ GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Tracing linkat, symlinkat, and newfstatat Flags in strace
learner@ksa:~/gl-e00/m02-l01$ strace -e \> trace=linkat,symlinkat,newfstatat,unlinkat ./verifynewfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/bin/busybox", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/bin/sh", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/init", {st_mode=S_IFLNK|0777, st_size=14, ...}, AT_SYMLINK_NOFOLLOW) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/init", {st_mode=S_IFREG|0755, st_size=7, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/broken", 0x7ffc811ebe90, 0) = -1 ENOENT (No such file or directory)newfstatat(AT_FDCWD, "/tmp/ksa_vfs_OjbTMI/sbin/broken", {st_mode=S_IFLNK|0777, st_size=14, ...}, AT_SYMLINK_NOFOLLOW) = 0+++ exited with 0 +++GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Rootfs Staging, Open-Unlinked Disk Leaks & Pseudo-FS Pitfalls
- Mastering FHS lifecycles, relative symlinks, and
dev_tsemantics prepares you to build clean minimal root…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: df -h reports 0 B free on /var, you run rm /var/log/daemon.log (2 GiB), ls shows the file is gone, yet df -h still reports 0 B free!
- Root Cause: rm calls unlink(2), decrementing st_nlink from 1 to 0, but the running daemon still holds an open struct file descriptor (fd 3), so ext4 cannot free the blocks.
- Fix: Identify the holder with lsof +L1 (open files with nlink < 1), then either truncate in place (: > /var/log/daemon.log before unlinking) or reload/restart the daemon (SIGHUP / systemctl kill -s HUP) so it closes fd 3.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Copying a rootfs directory with cp -r turns /dev/null into a multi-megabyte regular file and converts 300 BusyBox symlinks into 300 full 1 MiB binary copies (300 MiB flash bloat!).
- Root Cause: Plain cp -r dereferences symlinks and reads from character device nodes instead of preserving S_IFLNK and S_IFCHR metadata.
- Fix: Always copy rootfs staging directories with cp -a (-dR --preserve=all) or rsync -aHAX, and keep /proc, /sys, /dev, and /run as empty mount-point directories in the image.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
verify.cto openbb_pathread-only (fd_hold = open(bb_path, O_RDONLY)), unlink both `hlink_pat…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a C11 directory scanner using
opendir(),readdir(),lstat(), andreadlink()that walks a stag…
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? While staging an embedded BusyBox rootfs at /home/eng/rootfs, why does ln -s /home/eng/rootfs/bin/busybox /home/eng/rootfs/sbin/init cause a kernel panic on the ARMv7-A target?
Select an option or press R to reveal.
Correct: A
Kernel symlink resolution replays the literal stored path string relative to the live root (/), so internal rootfs links must be relative (../bin/busybox) or target-rooted (/bin/busybox).
Common misconception: Thinking ln -s automatically strips the staging prefix directory from an absolute target path.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? Why does ln /var/log/messages /home/backup/messages fail with Invalid cross-device link (EXDEV) when /var and /home are separate partitions?
Select an option or press R to reveal.
Correct: D
Each mounted filesystem maintains its own independent inode table starting from inode 1/2, so a directory entry on filesystem B cannot reference an inode index in filesystem A's superblock.
Common misconception: Assuming ino_t inode numbers are globally unique across all mounted disks on a Linux machine.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? What do the numbers 179, 2 represent in brw-rw---- 1 root disk 179, 2 Nov 24 01:00 /dev/mmcblk0p2?
Select an option or press R to reveal.
Correct: C
On S_IFBLK (b) and S_IFCHR (c) device nodes, ls -l prints major(st_rdev), minor(st_rdev) in place of st_size.
Common misconception: Reading the major, minor column of ls -l /dev as byte size.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Summary
- FHS 3.0 separates essential boot binaries (/bin, /sbin, /lib) and static configuration (/etc) from volatile tmpfs runtime state (/run) and RAM-backed kernel pseudo-filesystems (/proc, /sys).
- A hard link creates an additional directory entry pointing to the exact same inode number (st_ino) within a single mounted filesystem (st_dev) and increments st_nlink without duplicating data blocks.
- A symbolic link allocates a distinct S_IFLNK inode storing a target path string, allowing cross-filesystem and directory links that must remain relative inside staged target root filesystems.
- Character (S_IFCHR) and block (S_IFBLK) device inodes store no file payload blocks; their st_rdev field encodes major(dev) to select a Linux kernel driver and minor(dev) to select the instance or partition.
GL-E00 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Key takeaways
- A hard link creates an additional directory entry pointing to the exact same inode number (st_ino) within a single mounted filesystem (st_dev) and increments st_nlink without duplicating data blocks.
- A symbolic link allocates a distinct S_IFLNK inode storing a target path string, allowing cross-filesystem and directory links that must remain relative inside staged target root filesystems.
- Character (S_IFCHR) and block (S_IFBLK) device inodes store no file payload blocks; their st_rdev field encodes major(dev) to select a Linux kernel driver and minor(dev) to select the instance or partition.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# UID/GID Identity, Octal Mode Bits, Sticky Directories & Profile Safety
What you'll learn
- Evaluate Linux VFS permission checks across UID/GID classes, directory traverse (x) vs list (r) bits, and sticky (01000) shared directories.
- Calculate effective file and directory modes under process umask values and explain why chmod -R 777 disables sudo and OpenSSH.
- Author syntax-checked, idempotent /etc/profile.d/ environment scripts without causing desktop or SSH login loops.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations
- Two reflexes account for more reinstalled Ubuntu workstations in embedded courses than any other mistake.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations
- Second, when adding an
ARMcross-compiler permanently, an engineer edits/etc/profileand writes `expor…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations
Figure 2.2a: VFS checks owner, group, and other classes mutually exclusively (first match wins, never union!) alongside 04000/02000/01000 high bits.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Mental model
note: Think of a directory as a locked filing-cabinet room containing sealed envelopes (files): r (04) turns on the room light so you can read the index sheet of envelope names, x (01) unlocks the door so you can walk in and grab an envelope whose exact name you already know (even in the dark when r is off!), and w (02) lets you toss envelopes into the shredder—regardless of whose seal is on the envelope—unless the room guard (01000 sticky bit) checks that your badge matches the envelope's owner!
Where it stops working: Unlike physical rooms where holding both an employee badge and a visitor badge gives you the best of both, POSIX VFS permission matching is strictly mutually exclusive: if euid == st_uid and owner bits are 000 (---rwxrwx), open() returns EACCES even when group and world have rwx!
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Sticky Bit (S_ISVTX / 01000) and Set-Group-ID Directory (S_ISGID / 02000)
definition: Historically named because early Unix kept a program's text segment 'stuck' in swap space, on modern Linux kernel directories S_ISVTX (01000, rendered as t in drwxrwxrwt when o+x is set, or T when o+x is clear) modifies may_delete() in fs/namei.c: unlinking or renaming a child requires w+x on the directory plus euid == 0 || euid == dir_uid || euid == file_uid. Meanwhile, S_ISGID (02000, drwxrwsr-x) on a shared team build directory makes newly created files and subdirectories inherit the directory's st_gid automatically.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Why 'chmod -R 777' and Naive /etc/profile Edits Destroy Workstations
Query numeric and symbolic mode bits with stat -c '%a %A' to audit special high bits (4=setuid, 2=setgid, 1=sticky).
Avoid chmod 777; dir w+x + 01000 governs unlink; syntax-check profile.d via sh -n.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# 12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety
- Inside
generic_permission()(fs/namei.c), theLinux kernelevaluates a 12-bit mode word (4octal di…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# 12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety
- Look closely at directory deletion:
unlink("/shared/report.pdf")mutates/shared's directory entries, *…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# 12-Bit Mode Masks, First-Match Credential Evaluation & visudo Safety
Figure 2.2b: Unlinking a file checks w+x (03) on the parent directory plus the 01000 sticky owner invariant—never the victim file's mode bits.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# 90-arm-toolchain.sh
learner@ksa:~/gl-e00/m02-l02$ # /etc/profile.d/90-arm-toolchain.sh (mode 0644, root:root)# Sourced by /etc/profile using POSIX sh — NEVER use bash-only arrays here!if [ -d "/opt/toolchains/arm-gnu-toolchain/bin" ]; then case ":${PATH:-}:" in *":/opt/toolchains/arm-gnu-toolchain/bin:"*) ;; *) PATH="/opt/toolchains/arm-gnu-toolchain/bin${PATH:+:${PATH}}" ;; esac export PATHfilearner@ksa:~/gl-e00/m02-l02$ GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# chmod
chmod(2) GL-E00 Quick Reference chmod(2) NAME chmod, umask, visudo - POSIX file mode bits, creation mask, and sudoers editor SYNOPSIS chmod 1777 /tmp # Sticky shared directory (drwxrwxrwt) chmod 2775 /srv/builds # Setgid shared team directory (drwxrwsr-x) sudo visudo -c # Validate /etc/sudoers syntax & 0440 permissions sh -n /etc/profile.d/custom.sh # Parse-check POSIX login script without executing OCTAL SUMMARY 4000 setuid | 2000 setgid | 1000 sticky 400 u+r | 200 u+w | 100 u+x (dir traverse) 040 g+r | 020 g+w | 010 g+x 004 o+r | 002 o+w | 001 o+x Kernel Systems Academy m02-l02 chmod(2) GL-E00 quick reference · full manual page: man 2 chmod GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying umask, First-Match Triads & Sticky Unlink Rules in C11
- In
verify.c, we test both theLinux kernel's VFS permission logic and real host filesystemumask()sy…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Verifying umask, First-Match Triads & Sticky Unlink Rules in C11
- Second, we temporarily set
umask(0027), create a real scratch file withopen(..., 0666)and scratch dir…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m02-l02$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <fcntl.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <sys/stat.h> 7 │ #include <unistd.h> 8 │ 9 │ static int vfs_triad_bits(uint32_t mode, uint32_t obj_uid, uint32_t obj_gid, 10 │ uint32_t actor_uid, uint32_t actor_gid) { 11 │ if (actor_uid == obj_uid) return (int)((mode >> 6) & 7U); 12 │ if (actor_gid == obj_gid) return (int)((mode >> 3) & 7U); 13 │ return (int)(mode & 7U); 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Kernel umask Masking in strace
- Observe the
straceoutput:umask(027)returns the caller's previous mask,openat(..., 0666)and `mkdi…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Kernel umask Masking in strace
- Notice one subtle contrast between
openat()creation and explicitchmod()/fchmodat():umaskfilters…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Kernel umask Masking in strace
learner@ksa:~/gl-e00/m02-l02$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l02$ ./verifyumask_0027: open_0666=0640 mkdir_0777=0750unlink_check: dir_0777=1 tmp_01777_stranger=0 tmp_01777_owner=1first_match_0077_owner_bits: 00learner@ksa:~/gl-e00/m02-l02$ GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Confirming Kernel umask Masking in strace
learner@ksa:~/gl-e00/m02-l02$ strace -e \> trace=umask,openat,mkdirat,newfstatat,unlinkat ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3umask(027) = 002openat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3umask(002) = 027newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/secret.conf", {st_mode=S_IFREG|0640, st_size=0, ...}, 0) = 0newfstatat(AT_FDCWD, "/tmp/ksa_perm_IsTEc8/sub", {st_mode=S_IFDIR|0750, st_size=4096, ...}, 0) = 0+++ exited with 0 +++GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Desktop Login Loops, Bashisms in /etc/profile & sudo Lockouts
- Respecting octal mode invariants keeps multi-user build servers and embedded root filesystems secure withou…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: You enter your correct password on the Ubuntu GUI login screen, the screen flashes black for one second, and returns straight to the password prompt.
- Root Cause: gdm3/lightdm Xsession sources /etc/profile and /etc/profile.d/*.sh using /bin/sh (dash), which aborts the entire session startup on non-POSIX bashisms ([[ ... ]], source, arrays) or a clobbered PATH.
- Fix: Switch to a text virtual console with Ctrl-Alt-F3 (or SSH in), inspect ~/.xsession-errors or journalctl -b, validate /etc/profile.d/*.sh with dash -n, and ensure PATH retains /usr/bin:/bin.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: ls dir/ lists filenames mixed with ls: cannot access 'dir/foo': Permission denied and ?????????? stat columns, and cat dir/foo fails even though dir/foo is 0644!
- Root Cause: Read (r, 04) on a directory permits getdents64() to read raw filename strings, but without execute/search (x, 01) the VFS refuses inode lookup (stat/open) on every child inside dir/.
- Fix: Directories practically always pair r with x (0755 or 0750); use chmod -R a+X (capital X adds +x only to directories and already-executable files, leaving regular 0644 data files non-executable!).
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Guided Practice
- Test the difference between lowercase
chmod -R a+xand uppercasechmod -R a+Xon a scratch directory in…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Independent Practice
- Extend
verify.cwith a `check_ssh_strict_modes(uint32_t home_mode, uint32_t ssh_dir_mode, uint32_t auth_k…
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? User bob (UID 1001, GID 1001) finds a file /srv/drop/calib.bin owned by root:root with mode 0400 (-r--------). The parent directory /srv/drop is 0777 (drwxrwxrwx, no sticky bit). What happens if bob runs rm -f /srv/drop/calib.bin?
Select an option or press R to reveal.
Correct: D
Removing a filename mutates the parent directory's dentry list rather than the file's data blocks; without 01000 (S_ISVTX) on /srv/drop, w+x on the directory suffices to unlink any child.
Common misconception: Thinking read-only mode 0400 on a file protects that filename from deletion inside a non-sticky writable directory.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? With umask 0027, what octal permissions are assigned to a newly created regular log file (open(..., O_CREAT, 0666)) and a newly created directory (mkdir(..., 0777))?
Select an option or press R to reveal.
Correct: C
0666 & ~0027 = 0666 & 0750 = 0640 (regular open() passes 0666, never 0777), and 0777 & ~0027 = 0750.
Common misconception: Subtracting umask in decimal or forgetting that open() starts from 0666 (no execute bits) rather than 0777.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? A file secret.key has permissions 0070 (----rwx---) and ownership alice:engineers. alice is a member of engineers. What happens when alice runs cat secret.key?
Select an option or press R to reveal.
Correct: B
POSIX credential evaluation is a strict if (uid) else if (gid) else ladder, never a union across owner, group, and other.
Common misconception: Believing group permissions act as a fallback when owner permissions are more restrictive.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Summary
- Directory permissions govern namespace operations rather than file contents: read (04) allows listing names via getdents64, execute (01) allows traversing into known child inodes, and write (02) allows creating or unlinking entries.
- The sticky bit (S_ISVTX, octal 01000) on shared writable directories like /tmp (01777) restricts unlink and rename to UID 0, the directory owner, or the individual file owner.
- Kernel file creation masks effective_mode = base_mode & ~umask (0666 for regular files, 0777 for directories), and recursive chmod -R 777 breaks sudo (/etc/sudoers must remain 0440) and SSH StrictModes.
- Shell startup scripts in /etc/profile and /etc/profile.d/*.sh must preserve existing PATH entries and pass sh -n syntax validation while keeping a rescue root PTY open to prevent login loops.
GL-E00 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Key takeaways
- The sticky bit (S_ISVTX, octal 01000) on shared writable directories like /tmp (01777) restricts unlink and rename to UID 0, the directory owner, or the individual file owner.
- Kernel file creation masks effective_mode = base_mode & ~umask (0666 for regular files, 0777 for directories), and recursive chmod -R 777 breaks sudo (/etc/sudoers must remain 0440) and SSH StrictModes.
- Shell startup scripts in /etc/profile and /etc/profile.d/*.sh must preserve existing PATH entries and pass sh -n syntax validation while keeping a rescue root PTY open to prevent login loops.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# MBR/GPT Sector Offsets, Removable-Disk Guards & Numeric-Owner Rootfs Archives
What you'll learn
- Audit target block devices via /sys/block/<dev>/removable, size, and mount tables before executing raw dd or sfdisk commands.
- Calculate exact byte and 512-byte LBA boundaries across MBR (0x000), i.MX6ULL IVT + U-Boot (0x400), Partition 1 FAT32 (LBA 2048), and Partition 2 ext4.
- Construct and verify POSIX ustar --numeric-owner rootfs tarballs and complete the Module 2 partition/permission guard studio.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Three Ways SD Card Flashing Goes Catastrophically Wrong
ddis affectionately nicknamed disk destroyer by kernel engineers for good reason: block devices (`/dev…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Three Ways SD Card Flashing Goes Catastrophically Wrong
- Even when you select the right USB SD reader (
/dev/sdb), omittingbs=1K seek=1writesu-boot.imxat b…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Three Ways SD Card Flashing Goes Catastrophically Wrong
- Once Partition 1 (
FAT32holdingzImage+.dtb) and Partition 2 (ext4rootfs) are formatted, a third…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Three Ways SD Card Flashing Goes Catastrophically Wrong
Figure 2.3a: Leaving LBA 2..2047 (1,023 KiB from 0x400 to 0xFFFFF) unpartitioned lets raw U-Boot coexist cleanly alongside standard MBR partitions.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Mental model
note: An i.MX6ULL SD card is laid out like a hardcover reference book: page 0 (LBA 0, 0x000) is the Table of Contents (MBR listing where Chapter 1 and Chapter 2 begin), pages 2..2047 (0x400..0xFFFFF) are a dedicated preface reserved for the silicon Boot ROM's IVT and U-Boot binary, and Chapter 1 (Partition 1 FAT32) begins strictly at page 2048 (1 MiB). Forgetting seek=1 glues the preface right over the Table of Contents, while starting Chapter 1 on page 63 lets a 700 KiB preface bleed straight across Chapter 1's opening pages!
Where it stops working: Not all SoCs sample LBA 2 (1 KiB): i.MX8M moves the Boot ROM offset to 32 KiB or 33 KiB so a full 34-sector (17 KiB) GUID Partition Table (GPT header at LBA 1 + 128 partition entries across LBA 2..33) can sit below U-Boot—whereas on i.MX6ULL, standard GPT entries at LBA 2 collide directly with 0x400 unless GPT entry array LBA is relocated or classic MBR is used!
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Image Vector Table (IVT @ 0x400) and POSIX ustar Numeric-Owner Header
definition: On power-on reset in SD/eMMC boot mode, the i.MX6ULL internal Boot ROM reads byte offset 0x400 (LBA 2), checking for a 32-byte Image Vector Table (IVT) header starting with tag byte 0xD1 (0x402000D1 or 0x412000D1) followed by DCD DDR3 init commands and U-Boot. Separately, every file in a POSIX.1-1988 ustar .tar archive carries a 512-byte header containing octal ASCII uid (offset 108) and gid (offset 116) plus string uname (offset 265) and gname (offset 297). By default, GNU tar prefers uname/gname strings; passing --numeric-owner forces tar to ignore string names and honor raw 0:0 integers.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Three Ways SD Card Flashing Goes Catastrophically Wrong
Gate every raw flash script on /sys/block/<dev>/removable == 1 and zero active /proc/mounts entries.
Check removable==1, start p1 >= LBA 2048, flash with bs=1K seek=1, and --numeric-owner.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums
- Let us verify the exact byte arithmetic on an
i.MX6ULLbootable SD card.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums
LBA 1(0x200..0x3FF) is unused on MBR, whereas standardGPTplaces its header atLBA 1and partitio…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums
- Inside a
.tarrootfs archive, each512-byteustarblock storesmagic"ustar"atoffset 257, `ui…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Exact MBR + IVT Byte Offsets, GPT LBA-2 Collision & ustar Checksums
Figure 2.3b: Byte-exact arithmetic proves 0x400 + uboot_bytes <= p1_lba_start * 512 and ustar uid/gid == 0 before hardware flashing.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# flash_sdcard_safe.sh
learner@ksa:~/gl-e00/m02-l03$ #!/usr/bin/env bashset -euo pipefail DEV_NAME="${1:?Usage: $0 sdX (e.g. sdb)}"SYS_BLK="/sys/block/${DEV_NAME}" # 1. Mandatory host-disk destruction guards[[ "$(cat "${SYS_BLK}/removable")" == "1" ]] || { echo "FATAL: ${DEV_NAME} is NOT removable!" >&2; exit 1; }! grep -Eq "^/dev/${DEV_NAME}[0-9p]*" /proc/mounts || { echo "FATAL: /dev/${DEV_NAME} has mounted partitions!" >&2; exit 1; } # 2. Partition starting at LBA 2048 (1 MiB) and flash U-Boot at 1 KiB (0x400)sfdisk "/dev/${DEV_NAME}" <<'EOF'label: dosstart=2048, size=131072, type=c, bootablelearner@ksa:~/gl-e00/m02-l03$ GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# dd
dd(1) GL-E00 Quick Reference dd(1) NAME dd, sfdisk, tar - raw sector flashing, MBR partitioning, and numeric-owner archives SYNOPSIS dd if=u-boot-dtb.imx of=/dev/sdX bs=1K seek=1 conv=fsync tar --numeric-owner --owner=0 --group=0 -cpJf rootfs.tar.xz -C _stage . sudo tar --numeric-owner -xpf rootfs.tar.xz -C /mnt/p2 && sync CRITICAL FLAGS seek=N Skip N output blocks (bs=1K seek=1 -> byte 0x400 = LBA 2 on i.MX6ULL). conv=fsync Flush kernel block page cache to physical SD/USB media before dd exits. --numeric-owner Ignore uname/gname strings; store/restore raw numeric UID/GID. Kernel Systems Academy m02-l03 dd(1) GL-E00 quick reference · full manual page: man 1 dd GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Auditing MBR/IVT Overlap and ustar Numeric-Owner Headers in C11
- In
verify.c, we synthesize a byte-accurate512-byte MBR (0x55AAsignature + Partition 1 starting LBA…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m02-l03$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdint.h> 3 │ #include <stdio.h> 4 │ #include <stdlib.h> 5 │ #include <string.h> 6 │ 7 │ static int check_mbr_uboot_fit(const unsigned char mbr[512], int is_removable, 8 │ uint32_t uboot_bytes) { 9 │ if (!is_removable) return -1; 10 │ if (mbr[510] != 0x55U || mbr[511] != 0xAAU) return -2; 11 │ uint32_t p1_lba = (uint32_t)mbr[0x1C6] | 12 │ ((uint32_t)mbr[0x1C7] << 8) | 13 │ ((uint32_t)mbr[0x1C8] << 16) | 14 │ ((uint32_t)mbr[0x1C9] << 24);───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Confirming Sector Boundary & ustar Header Rejections
- Review the execution output: fixed non-removable disks (
sda) fail immediately (-1), legacyLBA 63par…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Confirming Sector Boundary & ustar Header Rejections
learner@ksa:~/gl-e00/m02-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m02-l03$ ./verifysdcard_guard: fixed_sda=-1 lba63_overlap=-3 lba2048_ok=0ustar_guard: numeric_uid0=0 host_uid1000_leak=-3learner@ksa:~/gl-e00/m02-l03$ GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Confirming Sector Boundary & ustar Header Rejections
learner@ksa:~/gl-e00/m02-l03$ strace -e trace=write,exit_group ./verifywrite(1, "sdcard_guard: fixed_sda=-1 lba63"..., 106) = 106exit_group(0) = ?+++ exited with 0 +++GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Page-Cache Eject Corruption & GPT-vs-IVT Collisions
- With removable-disk sysfs checks,
LBA 2048alignment,dd bs=1K seek=1 conv=fsync, and `tar --numeric-ow…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: dd prints 680240 bytes copied and returns to the shell prompt in 0.02 s, you pull the USB SD reader out, and the board refuses to boot or prints EXT4-fs error: bad magic.
- Root Cause: Without conv=fsync (or oflag=direct / sync), write(2) copies sectors into the Linux kernel dirty page cache in host RAM while USB mass-storage writeback is still in flight!
- Fix: Always append conv=fsync to raw dd invocations, and after copying files to mounted FAT32/ext4 partitions run sync && sudo umount /dev/sdX* and wait for umount to return before unplugging.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Partitioning succeeds in gdisk, then running dd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1 causes fdisk -l to report GPT PMBR size mismatch / corrupt primary GPT table!
- Root Cause: Standard GPT places its Primary Header at LBA 1 (0x200) and its 128-entry Partition Array across LBA 2..33 (0x400..0x43FF)—the exact 0x400 byte offset where i.MX6ULL requires its IVT!
- Fix: Use MBR (label: dos in sfdisk) on i.MX6ULL SD/eMMC boot media, or if GPT is mandatory, relocate the GPT partition entry array (--move-main-table in sgdisk -j 2048) past U-Boot.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Guided Practice
- Calculate the maximum
u-boot-dtb.imxfile size (in bytes and KiB) that fits between byte0x400(1 KiB…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Independent Practice
- Complete
labs/lab_m02_perm_partition_guard/by repairingstarter/core.cso all5TAP version 13che…
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? Why must dd if=u-boot-dtb.imx of=/dev/sdb bs=1K seek=1 conv=fsync include bs=1K seek=1 when flashing an i.MX6ULL SD card?
Select an option or press R to reveal.
Correct: C
Byte 0x000..0x1FF holds the MBR partition table and 0x400 (1024 bytes = 1 KiB) is the hardware-fixed i.MX6ULL SD/MMC IVT boot offset.
Common misconception: Confusing seek= (skipping output blocks on of=) with skip= (skipping input blocks on if=).
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? An unprivileged engineer stages a target rootfs in /home/alex/rootfs (UID 1000:1000) and packs it with plain tar -cpJf rootfs.tar.xz -C /home/alex/rootfs .. What goes wrong on the target board?
Select an option or press R to reveal.
Correct: B
Without --numeric-owner --owner=0 --group=0 (or fakeroot), tar records the host user's UID 1000 and username string inside every ustar header.
Common misconception: Assuming tar -p magically converts UID 1000 files to root:root (0:0) during archiving.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? Why does formatting an i.MX6ULL boot SD card with a default GPT partition table break as soon as dd bs=1K seek=1 writes u-boot-dtb.imx?
Select an option or press R to reveal.
Correct: A
While MBR occupies only LBA 0 (0x000..0x1FF), standard GPT occupies LBA 1..33 (0x200..0x43FF), overlapping 0x400 unless the GPT entry table LBA is moved.
Common misconception: Assuming GPT fits inside the first 512 bytes like MBR.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Lab: lab_m02_perm_partition_guard
- Automated BSP image-creation pipelines must guarantee three non-negotiable safety invariants: never write r…
Verify: ./check.sh exits 0.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Summary
- Before raw SD card writes, scripts must verify /sys/block/<dev>/removable == 1, zero mounted partitions in /proc/mounts, and sane capacity bounds so dd never targets host /dev/sda or /dev/nvme0n1.
- On i.MX6ULL SD/eMMC boot media, LBA 0 (0x000..0x1FF) holds the 512-byte MBR, LBA 2 (byte 0x400, 1 KiB) holds the raw Boot ROM IVT + U-Boot image (dd bs=1K seek=1), and Partition 1 starts at LBA 2048 (1 MiB).
- Partition 1 (FAT32, 0x0C) stores zImage and Device Tree .dtb files read by U-Boot, while Partition 2 (ext4, 0x83) stores the persistent Linux root filesystem.
- Packing and extracting target rootfs archives with tar --numeric-owner --owner=0 --group=0 -cpf preserves raw UID/GID 0:0 integers in POSIX ustar headers without host /etc/passwd name contamination.
GL-E00 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Key takeaways
- On i.MX6ULL SD/eMMC boot media, LBA 0 (0x000..0x1FF) holds the 512-byte MBR, LBA 2 (byte 0x400, 1 KiB) holds the raw Boot ROM IVT + U-Boot image (dd bs=1K seek=1), and Partition 1 starts at LBA 2048 (1 MiB).
- Partition 1 (FAT32, 0x0C) stores zImage and Device Tree .dtb files read by U-Boot, while Partition 2 (ext4, 0x83) stores the persistent Linux root filesystem.
- Packing and extracting target rootfs archives with tar --numeric-owner --owner=0 --group=0 -cpf preserves raw UID/GID 0:0 integers in POSIX ustar headers without host /etc/passwd name contamination.
m03/
>_ Kernel Systems Academy
# APT Package Graphs, Dual-NIC Routing & TFTP/NFS Boot Bench
Operate signed APT/dpkg package state machines, isolate ARMv7 cross-compilation pkg-config sysroots from host x86_64 headers, route multi-homed WAN + static bench Ethernet subnets without dual-gateway blackholes, and verify RFC 1350 TFTP plus NFSv3 rootfs network boot.
- 3.1 dpkg State Databases, Signed APT Repositories & Sysroot pkg-config Isolation
- 3.2 Multi-Homed Subnet Routing & RFC 1350 TFTP Kernel Delivery
- 3.3 NFSv3/NFSv4 Root Filesystem Exports, Firmware Staging & Network Boot Studio
lab → Dual-NIC FIB Router, RFC 1350 TFTP Framing & NFSv3 Bootargs Verifier
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# dpkg State Databases, Signed APT Repositories & Sysroot pkg-config Isolation
What you'll learn
- Trace package ownership and state transitions using dpkg -L, dpkg -S, /var/lib/dpkg/status, and signed APT DEB822 repositories.
- Diagnose /var/lib/dpkg/lock-frontend flock contention via fuser/lsof and recover interrupted unpacks with dpkg --configure -a.
- Isolate ARMv7-A cross-compilation from host x86_64 headers and libraries using PKG_CONFIG_LIBDIR and PKG_CONFIG_SYSROOT_DIR.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation
- Setting up a fresh Ubuntu 22.04/24.04 LTS or Debian 12 workstation for
Linux kernelandU-Bootdevelopm…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation
- Two traps hit embedded engineers immediately.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation
Figure 3.1a: PKG_CONFIG_LIBDIR replaces the default x86_64 search path (unlike PKG_CONFIG_PATH, which only prepends!), while PKG_CONFIG_SYSROOT_DIR prefixes -I and -L.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of dpkg as a warehouse inventory clerk who bolts crates onto shelves and writes every bolt's shelf coordinate into /var/lib/dpkg/status, while apt is the procurement planner who checks supplier wax seals (GPG -> SHA-256) and orders every prerequisite bracket first. Ripping the Occupied sign off the warehouse door (rm lock-frontend) while a clerk is still inside causes two clerks to overwrite the same ledger page! And setting PKG_CONFIG_PATH instead of PKG_CONFIG_LIBDIR tells the clerk *'check the ARM shelf first, and if a part is missing, silently grab an x86 truck bolt off the host shelf!'*
Where it stops working: flock(2) locks the kernel open file description (struct file / inode), not the directory pathname: unlinking /var/lib/dpkg/lock-frontend allows a second apt process to create a brand-new inode and acquire a second flock concurrently with the first!
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Advisory Inode Lock (flock) and PKG_CONFIG_LIBDIR vs PKG_CONFIG_PATH
definition: When apt starts, it opens /var/lib/dpkg/lock-frontend and issues flock(fd, LOCK_EX | LOCK_NB). If the process crashes (SIGKILL or power loss), the Linux kernel closes fd automatically and releases the lock—leaving the zero-byte file on disk harmlessly! Only package state iU (unpacked, unconfigured) remains, which sudo dpkg --configure -a completes. In pkg-config, PKG_CONFIG_PATH prepends to /usr/lib/x86_64-linux-gnu/pkgconfig, whereas PKG_CONFIG_LIBDIR replaces the compiled-in host search list completely.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation
Use dpkg -S to identify which package owns a header or binary and dpkg -L to inspect installed utilities like mkimage.
Never rm dpkg locks; use fuser + dpkg --configure -a and PKG_CONFIG_LIBDIR.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting
- A
.debpackage is a standard Unixararchive (ar t foo.deb) containing three members in fixed order:…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting
- Now trace what happens when cross-compiling an
ALSAorDRMapplication forARMv7-Aagainst a staged s…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting
Figure 3.1b: Combining PKG_CONFIG_LIBDIR (search isolation) with PKG_CONFIG_SYSROOT_DIR (prefix rewriting) guarantees 100% EM_ARM header/library purity.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# arm-pkg-config
learner@ksa:~/gl-e00/m03-l01$ #!/usr/bin/env bashset -euo pipefail : "${KSA_ARM_SYSROOT:?Set KSA_ARM_SYSROOT to your staged ARMv7 rootfs path}" unset PKG_CONFIG_PATHexport PKG_CONFIG_DIR=""export PKG_CONFIG_LIBDIR="${KSA_ARM_SYSROOT}/usr/lib/arm-linux-gnueabihf/pkgconfig:${KSA_ARM_SYSROOT}/usr/lib/pkgconfig:${KSA_ARM_SYSROOT}/usr/share/pkgconfig"export PKG_CONFIG_SYSROOT_DIR="${KSA_ARM_SYSROOT}" exec pkg-config "$@"learner@ksa:~/gl-e00/m03-l01$ GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# dpkg
dpkg(1) GL-E00 Quick Reference dpkg(1) NAME dpkg, apt-get, pkg-config - Debian package ledger, signed repo solver, and sysroot flags SYNOPSIS dpkg -L <pkg> # List all files installed by <pkg> dpkg -S /usr/bin/mkimage # Find which installed package owns a file sudo fuser -v /var/lib/dpkg/lock-frontend sudo dpkg --configure -a # Finish interrupted iU package configuration CROSS-COMPILATION ENVIRONMENT PKG_CONFIG_DIR="" PKG_CONFIG_LIBDIR="$SYSROOT/usr/lib/arm-linux-gnueabihf/pkgconfig:$SYSROOT/usr/share/pkgconfig" PKG_CONFIG_SYSROOT_DIR="$SYSROOT" Kernel Systems Academy m03-l01 dpkg(1) GL-E00 quick reference · full manual page: man 1 dpkg GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Testing Kernel flock() Contention and Sysroot Flag Isolation in C11
- In
verify.c, we exercise realLinux kernelflock()advisory locking on two independent open file desc…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Testing Kernel flock() Contention and Sysroot Flag Isolation in C11
- Next,
rewrite_and_audit_cflags()modelsPKG_CONFIG_SYSROOT_DIRrewriting and inspects compiler/linker t…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m03-l01$ bat verify.c───────┬─────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼─────────────────────────────────────────────────────────────────────────────────── 1 │ #define _DEFAULT_SOURCE 2 │ #include <errno.h> 3 │ #include <fcntl.h> 4 │ #include <stdio.h> 5 │ #include <stdlib.h> 6 │ #include <string.h> 7 │ #include <sys/file.h> 8 │ #include <unistd.h> 9 │ 10 │ static int audit_cross_flags(const char *flags) { 11 │ char buf[320]; 12 │ snprintf(buf, sizeof(buf), "%s", flags); 13 │ char *save = NULL; 14 │ for (char *t = strtok_r(buf, " ", &save); t; t = strtok_r(NULL, " ", &save)) {───────┴───────────────────────────────────────────────────────────────────────────────────GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace
- Look right inside the
stracecapture:flock(3, LOCK_EX|LOCK_NB) = 0, followed by `flock(4, LOCK_EX|LOCK…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace
learner@ksa:~/gl-e00/m03-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l01$ ./verifydpkg_flock: acquire1=0 contend_eblock=1 acquire_after_close=0pkgconfig_audit: host_leak_rc=-1 sysroot_clean_rc=0rewritten_flags: -I/opt/sysroots/armhf/usr/include/alsa -L/opt/sysroots/armhf/usr/lib/arm-linux-gnueabihf -lasoundlearner@ksa:~/gl-e00/m03-l01$ GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace
learner@ksa:~/gl-e00/m03-l01$ strace -e \> trace=openat,flock,close,unlinkat,write ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3) = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3close(3) = 0openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR|O_CREAT|O_EXCL, 0600) = 3openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR) = 4flock(3, LOCK_EX|LOCK_NB) = 0flock(4, LOCK_EX|LOCK_NB) = -1 EAGAIN (Resource temporarily unavailable)close(3) = 0flock(4, LOCK_EX|LOCK_NB) = 0close(4) = 0write(1, "dpkg_flock: acquire1=0 contend_e"..., 229) = 229+++ exited with 0 +++GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Multiarch Conflicts and Deprecated apt-key Anti-Patterns
- Keeping host package management clean and cross-build
pkg-configstrictly fenced inside$SYSROOTpreven…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: apt update prints Key is stored in legacy trusted.gpg keyring or accepts unsigned Packages files over plain HTTP.
- Root Cause: [trusted=yes] disables GPG verification completely, while /etc/apt/trusted.gpg trusts a third-party vendor's key to sign packages for every repository on the system (including linux-image-generic!).
- Fix: Place the dearmored .gpg key in /etc/apt/keyrings/<vendor>.gpg (0644) and scope it strictly inside that single .sources entry using Signed-By: /etc/apt/keyrings/<vendor>.gpg.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: You pass --host=arm-linux-gnueabihf to ./configure, yet the build still pulls /usr/include from the x86_64 host.
- Root Cause: Autotools looks for arm-linux-gnueabihf-pkg-config first; if no prefixed wrapper exists on PATH, it falls back to bare host pkg-config with default host PKG_CONFIG_LIBDIR!
- Fix: Either save our arm-pkg-config wrapper onto PATH named arm-linux-gnueabihf-pkg-config (chmod 0755), or export PKG_CONFIG=/path/to/arm-pkg-config explicitly.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Guided Practice
- Modify
verify.cto openlpatha third time (fd3) after unlinkinglpathwhilefd2still holds…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a C11 parser for
/var/lib/dpkg/statusstanzas (Package:,Status:,Architecture:) that flags a…
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? Why does running sudo rm /var/lib/dpkg/lock-frontend when apt says Could not get lock risk corrupting /var/lib/dpkg/status?
Select an option or press R to reveal.
Correct: D
Because unlink() only removes the directory entry while the first process keeps writing under its open struct file, a new process opening the same path creates a second inode with its own independent flock!
Common misconception: Thinking presence of the file /var/lib/dpkg/lock-frontend itself is the lock rather than an active process holding flock(fd, LOCK_EX).
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? When cross-compiling an ARMv7-A user-space daemon against $SYSROOT, why must you set PKG_CONFIG_LIBDIR instead of only PKG_CONFIG_PATH?
Select an option or press R to reveal.
Correct: C
Replacing the default compiled-in x86_64 directory list via PKG_CONFIG_LIBDIR ensures missing target dependencies fail cleanly at configure time rather than poisoning the build with host .pc files.
Common misconception: Assuming PKG_CONFIG_PATH disables the built-in host /usr/lib/<arch>/pkgconfig fallback.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? Which command identifies the exact installed Debian/Ubuntu package that placed /usr/bin/mkimage onto your workstation?
Select an option or press R to reveal.
Correct: B
dpkg -S (--search) scans /var/lib/dpkg/info/*.list to map a filesystem path back to its owning package (u-boot-tools: /usr/bin/mkimage), whereas dpkg -L expects a package name.
Common misconception: Swapping dpkg -S <path> (owner lookup) and dpkg -L <pkg> (package file listing).
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Summary
- Debian and Ubuntu split package management into dpkg (/var/lib/dpkg/status local archive installer and file-ownership ledger) and apt (cryptographically signed InRelease dependency solver).
- APT verifies a three-link trust chain—GPG signed-by keyring on InRelease, SHA-256 of Packages.xz, and SHA-256 of each .deb—while serializing mutations via kernel flock() on /var/lib/dpkg/lock-frontend.
- Cross-compiling against an ARMv7 target sysroot requires setting PKG_CONFIG_DIR='', PKG_CONFIG_LIBDIR to the sysroot pkgconfig directories, and PKG_CONFIG_SYSROOT_DIR so host /usr/include paths never leak.
- When an interrupted dpkg run leaves half-configured packages (state iU) and zero live apt/dpkg processes hold the flock, dpkg --configure -a replays idempotent postinst scripts safely without deleting lock files.
GL-E00 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Key takeaways
- APT verifies a three-link trust chain—GPG signed-by keyring on InRelease, SHA-256 of Packages.xz, and SHA-256 of each .deb—while serializing mutations via kernel flock() on /var/lib/dpkg/lock-frontend.
- Cross-compiling against an ARMv7 target sysroot requires setting PKG_CONFIG_DIR='', PKG_CONFIG_LIBDIR to the sysroot pkgconfig directories, and PKG_CONFIG_SYSROOT_DIR so host /usr/include paths never leak.
- When an interrupted dpkg run leaves half-configured packages (state iU) and zero live apt/dpkg processes hold the flock, dpkg --configure -a replays idempotent postinst scripts safely without deleting lock files.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Multi-Homed Subnet Routing & RFC 1350 TFTP Kernel Delivery
What you'll learn
- Configure a multi-homed Netplan/iproute2 host table keeping 0.0.0.0/0 on WAN while serving 192.168.10.0/24 on-link to the target board.
- Trace RFC 1350 TFTP opcodes (RRQ=1, WRQ=2, DATA=3, ACK=4, ERROR=5), ephemeral UDP TIDs, and exact-512B-multiple 0-byte EOF packets.
- Verify non-overlapping U-Boot DDR3 load addresses (0x80800000 zImage, 0x83000000 .dtb) before executing bootz.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
- Watch what happens on almost every engineer's first embedded network-boot setup: the laptop or VM has worki…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
- Why?
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
- Adding a fake gateway on the wired bench dongle installs
default via 192.168.10.1 metric 100, routing all…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
Figure 3.2a: An isolated point-to-point or bench-switch subnet needs only an on-link /24 prefix (ARP), never a default gateway.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Mental model
note: A default gateway (0.0.0.0/0) is the highway on-ramp sign for *'All Other Cities'*. If you bolt a private cul-de-sac driveway (192.168.10.0/24) onto the back of your lab and hang an *'All Other Cities — Express Lane'* (metric 100) sign over that dead-end driveway, every delivery truck bound for New York drives straight into your workbench wall! Labelling the driveway strictly *'192.168.10.1–.254 Only'* (scope link) sends board traffic down the cable and everything else onto the real highway.
Where it stops working: If two NICs accidentally share the same IPv4 subnet (for instance corporate Wi-Fi is already 192.168.10.0/24 and you assign 192.168.10.10/24 to the bench dongle), even omitting gateway fails because both interfaces own /24 prefixes of equal length—pick a dedicated RFC 1918 bench subnet like 192.168.77.0/24 or 10.77.0.0/24!
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# RFC 1350 Trivial File Transfer Protocol (TFTP) Lockstep Framing
definition: Designed in 1981 (RFC 1350) to fit inside tiny 4 KiB boot ROMs and U-Boot without a TCP state machine, TFTP runs over UDP. Every packet starts with a 16-bit big-endian opcode: 1 = RRQ (Read Request to UDP/69 carrying NUL-terminated filename + "octet\0"), 2 = WRQ, 3 = DATA (2 B opcode + 2 B 1-based block number + 0..512 B payload), 4 = ACK (2 B opcode + 2 B block number), and 5 = ERROR. Because DATA headers carry no length field, UDP datagram payload length determines end-of-file: 512 B means more blocks follow, whereas 0..511 B terminates the transfer immediately.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Why Plugging In Your Board's Ethernet Cable Suddenly Breaks Host Internet
Assign a /24 address without a gateway to the wired bench interface and verify routing with ip route get 8.8.8.8 and ip route get 192.168.10.50.
Omit gateway on bench NICs, pass bare names to --secure tftpd, and separate DTB by 40 MiB.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map
- Examine RFC 1350's wire framing closely because you will implement its verifier in the Module 3 studio.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map
- What if
board.dtbis exactly32,768bytes (64 * 512,size % 512 == 0)?
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# RFC 1350 Wire Bytes, Exact-512B EOF Edge Case & DDR3 Load Map
Figure 3.2b: Exact-multiple-of-512 files require N/512 + 1 DATA blocks (a final 0-byte DATA packet) to close an RFC 1350 session cleanly.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# 99-bench-dual-nic.yaml
learner@ksa:~/gl-e00/m03-l02$ bat 99-bench-dual-nic.yaml───────┬─────────────────────────────────────────────────────────────────────────────────────────────── │ File: 99-bench-dual-nic.yaml───────┼─────────────────────────────────────────────────────────────────────────────────────────────── 1 │ # /etc/netplan/99-bench-dual-nic.yaml (chmod 0600 root:root -> sudo netplan apply) 2 │ network: 3 │ version: 2 4 │ ethernets: 5 │ enp0s3: # Adapter 1 (WAN / NAT): owns sole 0.0.0.0/0 default gateway 6 │ dhcp4: true 7 │ enx00e04c680102: # Adapter 2 (USB-Ethernet to i.MX6ULL): ON-LINK ONLY, NO routes/gateway4! 8 │ dhcp4: false 9 │ addresses: 10 │ - 192.168.10.10/24───────┴───────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# in.tftpd
in.tftpd(8) GL-E00 Quick Reference in.tftpd(8) NAME in.tftpd, ip-route, bootz - RFC 1350 TFTP server, FIB routing, and U-Boot ARMv7 boot SYNOPSIS ip route show # Verify sole 0.0.0.0/0 WAN route ip route get 192.168.10.50 # Confirm on-link bench NIC selection sudo systemctl status tftpd-hpa && ss -ulnp | grep :69 U-Boot COMMANDS (i.MX6ULL DDR3 @ 0x80000000) setenv ipaddr 192.168.10.50; setenv serverip 192.168.10.10 tftp 0x80800000 zImage tftp 0x83000000 imx6ull-board.dtb bootz 0x80800000 - 0x83000000 Kernel Systems Academy m03-l02 in.tftpd(8) GL-E00 quick reference · full manual page: man 8 in.tftpd GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Simulating Kernel FIB Longest-Prefix Lookup and RFC 1350 Framing in C11
- In
verify.c, we build two deterministic verifiers in ISOC11.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Simulating Kernel FIB Longest-Prefix Lookup and RFC 1350 Framing in C11
- Second,
run_tftp_codec()encodes a real big-endian RFC 1350RRQ+DATA/ACKtransfer for a1,024-b…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m03-l02$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdint.h> 3 │ #include <stdio.h> 4 │ #include <string.h> 5 │ 6 │ typedef struct { 7 │ const char *dev; 8 │ uint32_t prefix; 9 │ int prefix_len; 10 │ uint32_t gateway; 11 │ int metric; 12 │ } fib_route_t; 13 │ 14 │ static uint32_t mask_from_len(int plen) {───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation
- Confirm all three lines of output from
./verify: inbroken_tbl,8.8.8.8routes mistakenly outenx0…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation
learner@ksa:~/gl-e00/m03-l02$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l02$ ./verifyfib_routing: broken_8888=enx0 clean_8888=wlan0 clean_board=enx0tftp_1024B: blocks=3 final_eof_bytes=0ddr3_gap: dtb_0x83000000=0 dtb_0x81000000_collision=-1learner@ksa:~/gl-e00/m03-l02$ GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Verifying FIB Selection, 0-Byte TFTP EOF & DDR3 Separation
learner@ksa:~/gl-e00/m03-l02$ strace -e trace=write,exit_group ./verifywrite(1, "fib_routing: broken_8888=enx0 cl"..., 158) = 158exit_group(0) = ?+++ exited with 0 +++GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Firewall Ephemeral UDP Drops & bootm vs bootz Confusion
- With clean dual-NIC routing and
TFTPdeliveringzImageand.dtbintoDDR3in under two seconds, the…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: tcpdump shows RRQ arriving on UDP/69 and in.tftpd sending DATA block 1 from UDP/53104, yet ACK block 1 from the board is dropped by the host (ICMP port unreachable).
- Root Cause: Because RFC 1350 switches from UDP/69 to an ephemeral server port (TID) on the first reply, a stateless firewall rule allowing only port 69 drops incoming ACK packets to 53104 unless nf_conntrack_tftp or an interface-level allow rule is present.
- Fix: Trust the isolated dedicated bench interface (sudo ufw allow in on enx00e04c680102) or load the TFTP connection-tracking helper (sudo modprobe nf_conntrack_tftp).
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: tftp 0x80800000 zImage succeeds, then bootm 0x80800000 - 0x83000000 fails with Wrong Image Format for bootm command / ERROR: can't get kernel image!.
- Root Cause: bootm expects a legacy 64-byte mkimage uImage header (0x27051956 magic) or FIT image, whereas Kbuild make zImage produces a self-decompressing ARMv7 zImage (0x016F2818 magic at 0x24).
- Fix: Use bootz 0x80800000 - 0x83000000 for ARMv7-A zImage (booti is for 64-bit ARM64 Image, and bootm is for uImage / FIT .itb images).
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Guided Practice
- Extend
simulate_tftp_blocks()inverify.cto parse the RFC 1350blksizeoption extension (RFC 2348, e…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Independent Practice
- Add a check to
fib_lookup()that scans the entire routing table before lookup and returns an error if two…
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? Your workstation connects to internet Wi-Fi (wlan0, DHCP 192.168.1.44/24, metric 600) and a wired bench adapter (enx0, static 192.168.10.10/24). Why must enx0 NOT define gateway4: 192.168.10.1?
Select an option or press R to reveal.
Correct: C
Because 0.0.0.0/0 has prefix length 0 on both NICs, the kernel FIB picks the lower metric (100 wired over 600 Wi-Fi), sending WAN packets toward a nonexistent router on the bench wire.
Common misconception: Thinking every static IPv4 interface requires a gateway field even when no router exists on that cable.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? Under RFC 1350 TFTP (512-byte standard blocks), how many DATA packets (opcode 3) are transmitted for a Device Tree blob that is exactly 32,768 bytes (64 * 512)?
Select an option or press R to reveal.
Correct: B
RFC 1350 DATA packets have no length field and signal EOF solely via payload length < 512 bytes; therefore any exact multiple of 512 requires a trailing 0-byte packet.
Common misconception: Computing ceil(size / 512) instead of (size / 512) + 1 for TFTP block counts.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? With TFTP_DIRECTORY="/srv/tftp" and TFTP_OPTIONS="--secure" in /etc/default/tftpd-hpa, which U-Boot command fetches /srv/tftp/zImage into DDR3?
Select an option or press R to reveal.
Correct: A
--secure (-s) chroots in.tftpd into /srv/tftp, so requesting /srv/tftp/zImage looks for /srv/tftp/srv/tftp/zImage and fails with File not found.
Common misconception: Passing the full host filesystem path to a --secure chrooted TFTP server.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Summary
- On a dual-NIC workstation, the WAN interface (Wi-Fi/LAN DHCP) owns the sole 0.0.0.0/0 default route while the static bench NIC (e.g., 192.168.10.10/24) configures NO default gateway, using on-link ARP only.
- Setting a gateway on an isolated wired bench NIC installs a lower-metric 0.0.0.0/0 route (metric 100 wired vs 600 Wi-Fi) in the Linux kernel FIB, blackholing internet traffic onto the board cable.
- RFC 1350 TFTP initiates via RRQ (opcode 1) on UDP port 69 and transfers 512-byte DATA blocks (opcode 3) in lockstep with ACK packets (opcode 4), signaling EOF with a final DATA block strictly under 512 bytes (0 bytes if image_size % 512 == 0).
- In i.MX6ULL DDR3 RAM (base 0x80000000), U-Boot loads zImage at 0x80800000 and the flattened Device Tree (.dtb) at 0x83000000 (~40 MiB higher) so kernel self-decompression never overwrites the Device Tree.
GL-E00 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Key takeaways
- Setting a gateway on an isolated wired bench NIC installs a lower-metric 0.0.0.0/0 route (metric 100 wired vs 600 Wi-Fi) in the Linux kernel FIB, blackholing internet traffic onto the board cable.
- RFC 1350 TFTP initiates via RRQ (opcode 1) on UDP port 69 and transfers 512-byte DATA blocks (opcode 3) in lockstep with ACK packets (opcode 4), signaling EOF with a final DATA block strictly under 512 bytes (0 bytes if image_size % 512 == 0).
- In i.MX6ULL DDR3 RAM (base 0x80000000), U-Boot loads zImage at 0x80800000 and the flattened Device Tree (.dtb) at 0x83000000 (~40 MiB higher) so kernel self-decompression never overwrites the Device Tree.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# NFSv3/NFSv4 Root Filesystem Exports, Firmware Staging & Network Boot Studio
What you'll learn
- Author whitespace-safe /etc/exports entries with no_root_squash and enable NFSv3 TCP support in /etc/nfs.conf on modern Ubuntu/Debian hosts.
- Construct exact U-Boot Linux kernel bootargs (root=/dev/nfs, nfsroot=<srv>:<path>,vers=3,tcp, and static ip= tuple) matching host exports.
- Compare TFTP+NFS network boot, SSH/rsync delta sync, and raw flash image deployment, and complete the Module 3 network boot studio.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot
- Re-partitioning or reflashing an SD card every time you tweak one line in a character driver wastes ten min…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot
- Two notorious bugs trip up engineers on Ubuntu 22.04 and 24.04 LTS.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot
Figure 3.3a: Both sides of the wire must agree on protocol version (vers=3,tcp), subnet CIDR without spaces, and UID 0 preservation (no_root_squash).
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Mental model
note: Mounting / over NFS is like running a restaurant kitchen (ARMv7-A board) whose walk-in pantry door opens directly into the central commissary (host /srv/nfs/rootfs): whenever the commissary places a fresh spice jar (driver.ko) on the shelf, the chef grabs it immediately without waiting for a delivery van (SD card). root_squash is a cautious commissary guard who strips the Head Chef (UID 0) of master keys and treats them as an untrusted visitor (UID 65534), while a space before ( in /etc/exports hangs the *'Master Keys Granted'* sign on the public street door instead of the kitchen door!
Where it stops working: no_root_squash grants any machine on the allowed subnet genuine UID 0 write access inside /srv/nfs/rootfs—never export / or /home with no_root_squash, and always restrict /srv/nfs/rootfs strictly to the isolated wired bench CIDR (192.168.10.0/24)!
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Kernel IP Autoconfiguration (ip= 7-Tuple) and NFS Root Squashing
definition: Because user-space tools (ip, NetworkManager, dhclient) live inside the root filesystem that has not been mounted yet, the Linux kernel brings up eth0 in Ring 0 using the ip= bootargs 7-tuple: ip=<client-ip>:<server-ip>:<gw-ip>:<netmask>:<hostname>:<device>:<autoconf> (for example ip=192.168.10.50:192.168.10.10::255.255.255.0:board:eth0:off, leaving <gw-ip> empty on an isolated bench!). Once TCP/IP is live, fs/nfs/nfsroot.c contacts the host NFS server; no_root_squash disables default UID 0 -> 65534 (nobody) credential remapping inside /srv/nfs/rootfs.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Three-Second Driver Turnaround—and Why Modern Ubuntu Rejects Default nfsroot
Extract your target rootfs archive into /srv/nfs/rootfs using sudo tar --numeric-owner so UID 0 ownership is intact on disk.
Enable [nfsd] vers3=y, write cidr(rw,no_root_squash), and pin nfsroot=...,vers=3,tcp.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs
- Why do embedded kernels prefer
NFSv3overNFSv4forroot=/dev/nfs?
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs
- Choosing the right transport across the engineering lifecycle is equally straightforward: use **TFTP + NFSv…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside /etc/exports Parsing, bootargs Tokenization & Deployment Trade-Offs
Figure 3.3b: Cross-checking /etc/exports against U-Boot bootargs catches path mismatches, missing vers=3,tcp, and subnet typos before power-on.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# nfs_bench_setup.conf
learner@ksa:~/gl-e00/m03-l03$ bat nfs_bench_setup.conf───────┬────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── │ File: nfs_bench_setup.conf───────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ # 1. /etc/nfs.conf (Ubuntu 22.04 / 24.04 LTS: re-enable NFSv3 for embedded U-Boot/kernel) 2 │ [nfsd] 3 │ vers3=y 4 │ tcp=y 5 │ 6 │ # 2. /etc/exports (ZERO space between 192.168.10.0/24 and '('!) 7 │ /srv/nfs/rootfs 192.168.10.0/24(rw,sync,no_root_squash,no_subtree_check) 8 │ 9 │ # 3. Matching U-Boot environment script 10 │ setenv bootargs 'console=ttymxc0,115200 root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=192.168.10.50:192.168.10.10::255.255.255.0:imx6ull:eth0:off'───────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# exports
exports(5) GL-E00 Quick Reference exports(5) NAME exports, exportfs, nfs.conf - NFS server export table and kernel nfsroot bootargs SYNOPSIS sudo exportfs -rav # Reload /etc/exports and print active options cat /proc/fs/nfsd/versions # Confirm +3 is active in rpc.nfsd showmount -e 192.168.10.10 # Query rpc.mountd export list EXPORTS & BOOTARGS CONTRACT /srv/nfs/rootfs 192.168.10.0/24(rw,sync,no_root_squash,no_subtree_check) root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=192.168.10.50:192.168.10.10::255.255.255.0:board:eth0:off Kernel Systems Academy m03-l03 exports(5) GL-E00 quick reference · full manual page: man 5 exports GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Cross-Checking /etc/exports Against Kernel nfsroot= bootargs in C11
- Before rebooting a board only to watch
VFS: Unable to mount root fs via NFSscroll across UART, we can cr…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Cross-Checking /etc/exports Against Kernel nfsroot= bootargs in C11
- Notice how bitwise subnet verification (
(srv_ip & mask) == (net_ip & mask)) converts dotted-quad IPv4 str…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m03-l03$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdint.h> 3 │ #include <stdio.h> 4 │ #include <stdlib.h> 5 │ #include <string.h> 6 │ 7 │ static int parse_ipv4(const char *s, uint32_t *out) { 8 │ unsigned int a, b, c, d; 9 │ char tail; 10 │ if (sscanf(s, "%u.%u.%u.%u%c", &a, &b, &c, &d, &tail) != 4) return -1; 11 │ if (a > 255U || b > 255U || c > 255U || d > 255U) return -1; 12 │ *out = (a << 24) | (b << 16) | (c << 8) | d; 13 │ return 0; 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Confirming /etc/exports Whitespace & vers=3,tcp Rejections
- Inspect the execution output: the matched
/etc/exports+vers=3,tcpbootargscontract returns `valid=…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Confirming /etc/exports Whitespace & vers=3,tcp Rejections
- While this host C11 verifier proves lexical and subnet consistency across host and
U-Bootconfiguration f…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Confirming /etc/exports Whitespace & vers=3,tcp Rejections
learner@ksa:~/gl-e00/m03-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l03$ ./verifynfs_audit: valid=0 exports_space_bug=-2 missing_vers3_tcp=-8learner@ksa:~/gl-e00/m03-l03$ GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Confirming /etc/exports Whitespace & vers=3,tcp Rejections
learner@ksa:~/gl-e00/m03-l03$ strace -e trace=write,exit_group ./verifywrite(1, "nfs_audit: valid=0 exports_space"..., 61) = 61exit_group(0) = ?+++ exited with 0 +++GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Host NetworkManager Conflicts & Target connman/systemd-networkd Drops
- You now control the complete host-to-target network boot pipeline—from signed APT/sysroot isolation through…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Kernel prints VFS: Mounted root (nfs filesystem) on device 0:15, /sbin/init starts services, and two seconds later the console freezes with nfs: server 192.168.10.10 not responding, still trying!
- Root Cause: A user-space network daemon inside the target rootfs (connman, NetworkManager, or ifupdown DHCP on eth0) flushed eth0's IP address to run DHCP, severing the live TCP connection backing / itself!
- Fix: When booting root=/dev/nfs, configure target user-space network managers to ignore eth0 (ConnMan -I eth0 or CriticalConnection=true / KeepConfiguration=yes in systemd-networkd).
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: You opened TCP/2049 (nfs) in ufw, yet U-Boot TFTP succeeds and kernel NFSv3 root mount times out.
- Root Cause: Unlike NFSv4 (single port 2049), NFSv3 first queries rpcbind (portmapper on TCP/UDP 111) to discover rpc.mountd's port (MOUNTv3 handshake) before opening TCP/2049!
- Fix: Allow all traffic from the dedicated wired bench interface (sudo ufw allow in on enx_bench from 192.168.10.0/24) or pin a static rpc.mountd port in /etc/nfs.conf ([mountd] port=20048) alongside 111 and 2049.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Guided Practice
- Extend
audit_nfs_contract()inverify.cto parse theip=7-tuple (ip=<client>:<srv>:<gw>:<mask>:...…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m03_tftp_nfs_bootargs/and fix all three bugs instarter/core.csosh check.shpasses `…
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? What does /srv/nfs/rootfs 192.168.10.0/24 (rw,sync,no_root_squash) (notice the space before () actually configure in /etc/exports?
Select an option or press R to reveal.
Correct: B
In /etc/exports whitespace separates distinct client specifications; a bare (rw,...) token with no hostname prefix means wildcard * (everyone), while 192.168.10.0/24 gets default (ro,root_squash)!
Common misconception: Treating /etc/exports parenthesized options like C function arguments where spaces before ( are harmless.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? An i.MX6ULL board boots Linux kernel 6.12 via TFTP, prints VFS: Mounted root (nfs filesystem), starts systemd, and immediately hangs printing nfs: server 192.168.10.10 not responding. What happened?
Select an option or press R to reveal.
Correct: A
When / resides over eth0, re-initializing eth0 in user space drops the underlying transport needed to read libraries and binaries from / (KeepConfiguration=yes or -I eth0 prevents this).
Common misconception: Blaming the host NFS daemon when target user-space scripts reset the interface backing root=/dev/nfs.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? Why does booting an embedded target with nfsroot=192.168.10.10:/srv/nfs/rootfs (without ,vers=3,tcp) commonly fail against an out-of-the-box Ubuntu 24.04 LTS host?
Select an option or press R to reveal.
Correct: D
Pinning ,vers=3,tcp in bootargs and enabling vers3=y in /etc/nfs.conf aligns kernel fs/nfs/nfsroot.c with modern rpc.nfsd.
Common misconception: Assuming host nfs-kernel-server still enables legacy NFSv2 over UDP on modern LTS releases.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Lab: lab_m03_tftp_nfs_bootargs
- A broken network-boot bench silently wastes hours of board bring-up: one stray
gateway4on the USB-Ethern…
Verify: ./check.sh exits 0.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Summary
- Exporting a target root filesystem in /etc/exports requires path cidr(rw,sync,no_root_squash,no_subtree_check) with ZERO whitespace between the CIDR subnet and '(' so options bind to that subnet rather than '*'.
- Without no_root_squash, the host NFS server maps target UID 0 requests to nobody (65534), causing /sbin/init, systemd, and device/module operations on the board to fail with EACCES.
- On Ubuntu 22.04+ and 24.04 LTS hosts, /etc/nfs.conf must enable [nfsd] vers3=y and tcp=y to match Linux kernel bootargs root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=...
- Embedded workflows use TFTP + NFS root during rapid kernel/driver iteration, rsync/scp over SSH for incremental user-space updates on booted targets, and UUU/SD partition images for standalone release.
GL-E00 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Key takeaways
- Without no_root_squash, the host NFS server maps target UID 0 requests to nobody (65534), causing /sbin/init, systemd, and device/module operations on the board to fail with EACCES.
- On Ubuntu 22.04+ and 24.04 LTS hosts, /etc/nfs.conf must enable [nfsd] vers3=y and tcp=y to match Linux kernel bootargs root=/dev/nfs nfsroot=192.168.10.10:/srv/nfs/rootfs,vers=3,tcp rw ip=...
- Embedded workflows use TFTP + NFS root during rapid kernel/driver iteration, rsync/scp over SSH for incremental user-space updates on booted targets, and UUU/SD partition images for standalone release.
m04/
>_ Kernel Systems Academy
# Linux Kernel & Embedded C11 Coding Style & Defensive Hygiene
Enforce Linux kernel C11 formatting, internal static symbol hygiene, centralized LIFO goto error unwinding, and single-evaluation macro safety verified by a host static-rule and unwind auditor.
- 4.1 Indentation, Braces, Operator Spacing & Why-Not-How Comments
- 4.2 Snake-Case Naming, Antonym Symmetry, Static Linkage & Centralized goto Unwind
- 4.3 Single-Purpose Variables, Fixed-Width Types & Defensive do-while(0) Macros
lab → Kernel C11 Macro Safety, Static Linkage & LIFO Unwind Auditor
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Indentation, Braces, Operator Spacing & Why-Not-How Comments
What you'll learn
- Audit embedded C11 source lines for 8-column tab visual width, K&R control braces, and aligned switch/case fallthrough annotations.
- Analyze pointer-declarator binding and operator-spacing defects that disguise non-pointer declarations or visual precedence traps.
- Evaluate multi-line block comments to replace line-by-line syntax narration with hardware and concurrency invariant contracts.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Visual Nesting Alarms and Asymmetric Brace Placement
- Code inside a bootloader or
Linux kerneldriver is written once and audited hundreds of times during brin…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Visual Nesting Alarms and Asymmetric Brace Placement
- The
Linux kernelCodingStyleuses8-column hard tabs ('\t') deliberately as a structural complexity…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Visual Nesting Alarms and Asymmetric Brace Placement
Figure 4.1a: 8-column tabs expose excessive cyclomatic nesting early so drivers refactor into flat guard clauses.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of kernel C formatting like standardized aircraft cockpit switch guards and color bands: every pilot reads control state in milliseconds without mentally translating personal layout quirks during an emergency.
Where it stops working: Formatting rules never prove algorithmic correctness on their own; clean indentation makes deeply nested bugs visible so engineers refactor control flow before shipping.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# 8-Column Tab Complexity Alarm
definition: Named from the Linux kernel CodingStyle chapter 1 rule equating one ASCII HT (0x09) character to eight terminal columns, the 8-column tab complexity alarm pairs wide visual steps with an 80-column soft margin so deeply nested conditionals physically run out of horizontal space, compelling the author to flatten control flow with guard clauses.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Visual Nesting Alarms and Asymmetric Brace Placement
Hard tabs advance to multiples of 8 columns, making >3 nested levels immediately obvious.
Use 8-col tabs, K&R control braces, identifier-bound *stars, and why-not-how comments.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Brace Geometry, Operator Spacing, and Fallthrough Discipline
- Every token spacing rule in
CodingStyleeliminates a concrete visual ambiguity.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Brace Geometry, Operator Spacing, and Fallthrough Discipline
- In C grammar, the pointer
*modifier binds to the declarator, not the type specifier.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Brace Geometry, Operator Spacing, and Fallthrough Discipline
Figure 4.1b: Declarator-bound stars and compiler-checked fallthrough attributes turn style rules into bug prevention.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# coding_style_irq.c
learner@ksa:~/gl-e00/m04-l01$ bat coding_style_irq.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: coding_style_irq.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ // SPDX-License-Identifier: GPL-2.0 2 │ #include <stdint.h> 3 │ 4 │ #define UART_SR_RXRDY (1U << 0) 5 │ #define UART_SR_OVERRUN (1U << 3) 6 │ 7 │ struct uart_port_ctx { 8 │ volatile uint32_t *sr_reg; 9 │ uint32_t rx_drops; 10 │ uint32_t rx_frames; 11 │ }; 12 │ 13 │ /* 14 │ * Why: Clearing OVERRUN on i.MX6ULL USR2 requires acknowledging the status───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# checkpatch.pl / CodingStyle
checkpatch.pl / CodingStyle(7) GL-E00 Quick Reference checkpatch.pl / CodingStyle(7) SYNOPSIS ./scripts/checkpatch.pl --no-tree --strict -f driver_file.c gcc -std=c11 -Wall -Wextra -Wimplicit-fallthrough -Wmisleading-indentation -Werror -c file.c KEY RULES (Linux kernel Documentation/process/coding-style.rst) Tabs & Width Hard tab ('\t') = 8 columns; preferred limit 80 cols (100 cols max when readability wins). Braces Functions open '{' on column 1 of next line; if/for/while/switch/struct open '{' on same line. Multi-branch If any branch of if/else needs braces, place braces on EVERY branch of that construct. Operators Space after if/for/while/switch/return; NO space after sizeof/alignof/typeof or unary ! ~ ++ --. Comments Use /* ... */ block comments explaining invariants (why), never restating C syntax (how). Kernel Systems Academy m04-l01 checkpatch.pl / CodingStyle(7) GL-E00 quick reference · full manual page: man 7 checkpatch.pl / CodingStyle GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Host C11 Style Scanner for Tabs, Stars, and Fallthroughs
- Before running
scripts/checkpatch.plagainst a full driver tree, understanding how each lexical check wor…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Host C11 Style Scanner for Tabs, Stars, and Fallthroughs
- This host verification binary runs in unprivileged user space under
gcc -std=c11 -Wall -Wextra -Werroran…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m04-l01$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <string.h> 6 │ 7 │ struct line_metrics { 8 │ int tab_depth; 9 │ int visual_cols; 10 │ bool leading_spaces; 11 │ bool bad_sizeof_space; 12 │ bool bad_type_star; 13 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Compiler Diagnostics and Tab-Stop Telemetry
- Compiling
verify.cundergcc -std=c11 -Wall -Wextra -Werrorexercises GCC's built-in `-Wmisleading-inde…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Compiler Diagnostics and Tab-Stop Telemetry
- Simultaneously,
FLAWED_LINEflags leading-space indentation,sizeof (spacing, and type-attached `char*…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Compiler Diagnostics and Tab-Stop Telemetry
learner@ksa:~/gl-e00/m04-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l01$ ./verifyCLEAN_LINE tabs=2 cols=55 violations=0FLAWED_LINE spaces=1 sizeof_sp=1 type_star=1DEEP_NEST_ALARM tabs=5 visual_col_start=40 (>3 refactor!)learner@ksa:~/gl-e00/m04-l01$ GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Verifying Compiler Diagnostics and Tab-Stop Telemetry
learner@ksa:~/gl-e00/m04-l01$ strace -e trace=write,exit_group ./verifywrite(1, "CLEAN_LINE tabs=2 cols=55 violat"..., 142) = 142exit_group(0) = ?+++ exited with 0 +++GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Formatting Traps That Disguise Control-Flow and Type Bugs
- Treat style conformance as a zero-noise baseline for code review.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Formatting Traps That Disguise Control-Flow and Type Bugs
- Pair
.editorconfig/.clang-format(UseTab: Always,IndentWidth: 8,TabWidth: 8) with compiler wa…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Adding a pr_debug() trace line to an else clause causes the subsequent operational statement to execute unconditionally on both true and false paths.
- Root Cause: Leaving one branch of an if/else unbraced when the sibling branch spans multiple lines invites human edit errors that GCC only catches if indentation happens to remain consistent.
- Fix: Place K&R { ... } braces around every branch of an if/else if/else chain whenever any single branch requires more than one line or statement.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Declaration uint8_t* rx_buf, tx_buf; fails with invalid type conversion or truncates a 32-bit buffer address into an 8-bit byte when assigning tx_buf.
- Root Cause: C grammar binds * to the individual declarator (*rx_buf), not the base type (uint8_t), so tx_buf is silently allocated as a scalar uint8_t.
- Fix: Always attach * to the variable identifier (uint8_t *rx_buf, *tx_buf;) and prefer one initialized pointer declaration per line.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
scan_style_line()inverify.cto flag lines whose expandedvisual_colsexceed80characters…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice
- Recompile with
gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifyand test two inputs: a92-column a…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a multi-line scanner function
check_switch_fallthrough(const char **lines, size_t n)that inspects…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Independent Practice
- Verify your scanner against three synthetic
switchblocks: a cleanbreak;-terminated case, an empty sta…
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? Why does Linux kernel CodingStyle specify 8-column hard tabs rather than 2-space indentation?
Select an option or press R to reveal.
Correct: C
Tabs affect source readability, not machine code; 8-column visual steps expose excessive cyclomatic complexity before functions become unmaintainable.
Common misconception: Thinking 8-column tabs are an arbitrary legacy quirk rather than a deliberate nesting-depth guardrail.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? Which allocation pattern follows Linux kernel CodingStyle and survives changing the struct type of struct sai_priv *priv without introducing a heap size mismatch?
Select an option or press R to reveal.
Correct: B
sizeof(*priv) omits space before (, avoids redundant void-pointer casts in C, and computes the exact pointee struct size even if priv's type is later renamed.
Common misconception: Using sizeof(priv) (which allocates only 4 or 8 pointer bytes!) or hardcoding the struct tag in sizeof (struct ...).
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? Why does CodingStyle permit a single-line pr_err("...") string literal to exceed 80 columns rather than breaking it into concatenated fragments?
Select an option or press R to reveal.
Correct: A
C11 concatenates adjacent string literals automatically at compile time, so the rule exists purely for grep discoverability during production fault triage.
Common misconception: Splitting error messages across lines to satisfy an 80-column counter, breaking grep lookup during bring-up.
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Summary
- Linux kernel CodingStyle mandates 8-column hard tabs and an 80-to-100 column line budget so functions exceeding 3 indentation levels force helper extraction.
- Control statements place opening braces on the same K&R line while function definitions place opening braces at column 1, and switch/case labels align vertically with explicit fallthrough annotations.
- Pointer asterisks bind to the identifier (
char *buf) rather than the base type, while function-like operators (sizeof(struct file)) omit space before the opening parenthesis. - C89/C11 block comments (
/* ... */) document hardware timing, lock order, and ownership invariants (why) rather than restating C syntax mechanics (how).
GL-E00 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Key takeaways
- Control statements place opening braces on the same K&R line while function definitions place opening braces at column 1, and switch/case labels align vertically with explicit fallthrough annotations.
- Pointer asterisks bind to the identifier (
char *buf) rather than the base type, while function-like operators (sizeof(struct file)) omit space before the opening parenthesis. - C89/C11 block comments (
/* ... */) document hardware timing, lock order, and ownership invariants (why) rather than restating C syntax mechanics (how).
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Snake-Case Naming, Antonym Symmetry, Static Linkage & Centralized goto Unwind
What you'll learn
- Enforce
staticinternal linkage (STB_LOCAL) and subsystem-prefixedsnake_caseantonym pairs across module boundaries. - Analyze partial-initialization failure paths in multi-resource
probe()routines to eliminate resource leaks and double-frees. - Construct a centralized forward-only
goto err_*cleanup tail that releases acquired resources in strict reverseLIFOorder.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Symbol Namespace Isolation and Antonym Lifecycle Symmetry
- In a monolithic
Linux kernelimage or multi-file embedded firmware archive, all non-staticfunctions an…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Symbol Namespace Isolation and Antonym Lifecycle Symmetry
- Equally critical is antonym symmetry across resource pairs:
allocpairs withfree,registerwith `unr…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Symbol Namespace Isolation and Antonym Lifecycle Symmetry
Figure 4.2a: Forward-only goto labels unwind strictly the prefix of resources that succeeded before the error.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mental model
note: Think of centralized goto unwinding like a mountaineering rope team retreating down pitched anchors: if climber 3 slips before reaching the summit, you unclip anchor 2 then anchor 1 in exact reverse order rather than cutting the rope mid-cliff.
Where it stops working: Backward or spaghetti goto jumps across loop bodies destroy control-flow reducibility; kernel C restricts goto strictly to forward jumps into a linear LIFO cleanup tail at function end.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Centralized LIFO goto Unwind
definition: Originating in systems C where ISO C lacks C++ RAII destructors, centralized LIFO goto unwind places a single reverse-ordered cascade of err_<action>_<resource>: labels at the bottom of a function so each failure after acquisition k jumps to the exact entry point that releases resources k .. 1 in Last-In, First-Out order.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Symbol Namespace Isolation and Antonym Lifecycle Symmetry
STB_LOCAL symbols never collide across driver objects and let GCC inline single-caller helpers.
Mark internal helpers static (STB_LOCAL) and unwind partial probes in strict LIFO order.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# ELF Symbol Tables and Reverse-Cascade Error Labels
- Inspecting a compiled object with
nmorreadelf -sreveals the binary consequence ofstatic: global f…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# ELF Symbol Tables and Reverse-Cascade Error Labels
- Inside
probe(), name each unwind label after the action it performs (err_free_ring:, `err_unmap_io:…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# ELF Symbol Tables and Reverse-Cascade Error Labels
Figure 4.2b: Action-named labels (err_free_ring) verify at the jump site which live resource unrolls first.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# probe_lifo_unwind.c
learner@ksa:~/gl-e00/m04-l02$ bat probe_lifo_unwind.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: probe_lifo_unwind.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ // SPDX-License-Identifier: GPL-2.0 2 │ #include <errno.h> 3 │ #include <stdint.h> 4 │ 5 │ struct spi_adc_dev { 6 │ int clk_on; 7 │ void *mmio_base; 8 │ uint8_t *rx_ring; 9 │ int irq_registered; 10 │ }; 11 │ 12 │ int spi_adc_clk_enable(struct spi_adc_dev *d); 13 │ void spi_adc_clk_disable(struct spi_adc_dev *d); 14 │ void *spi_adc_iomap(void);───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# nm(1) / CodingStyle Ch.4,6,7
nm(1) / CodingStyle Ch.4,6,7(1) GL-E00 Quick Reference nm(1) / CodingStyle Ch.4,6,7(1) SYNOPSIS nm --defined-only driver.o # 't'/'b'/'d' = static STB_LOCAL; 'T'/'B'/'D' = global STB_GLOBAL gcc -std=c11 -Wall -Wextra -Wmissing-prototypes -Werror -c driver.c NAMING & UNWIND RULES snake_case Lowercase words_with_underscores for variables/functions; UPPER_SNAKE_CASE for macros/enums. Antonyms Pair alloc/free, enable/disable, map/unmap, lock/unlock, register/unregister consistently. static Mandatory on every file-scope function and variable not declared in a shared header. goto err_* Forward-only jumps to action-named labels unwinding resources in strict LIFO order. Kernel Systems Academy m04-l02 nm(1) / CodingStyle Ch.4,6,7(1) GL-E00 quick reference · full manual page: man 1 nm(1) / CodingStyle Ch.4,6,7 GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Fault-Injecting LIFO Unwind Versus Early-Return Leaks in C11
- The fastest way to prove a
probe()cleanup spine has zero leaks and zero out-of-order releases is determi…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Fault-Injecting LIFO Unwind Versus Early-Return Leaks in C11
- We sweep
fail_stepfrom1through4plus the0(no-fault) path, contrasting a naive early-return fu…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m04-l02$ bat verify.c───────┬─────────────────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼─────────────────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum res_bit { RES_CLK = 1U << 0, RES_MMIO = 1U << 1, RES_RING = 1U << 2, RES_IRQ = 1U << 3 }; 7 │ 8 │ struct sim_bus { 9 │ uint32_t live_mask; 10 │ int order_violations; 11 │ int release_log[4]; 12 │ int release_cnt; 13 │ };───────┴───────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Confirming Zero Leaks Across All Four Fault Injection Points
- Notice
-Wmissing-prototypeson thegcccommand line: because bothrecord_relandprobe_lifoare dec…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Confirming Zero Leaks Across All Four Fault Injection Points
- In the execution output,
FAULT_STEP=1..4releases0, 1, 2, 3resources respectively, always terminating…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Confirming Zero Leaks Across All Four Fault Injection Points
learner@ksa:~/gl-e00/m04-l02$ gcc -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes verify.c -o verifylearner@ksa:~/gl-e00/m04-l02$ ./verifyFAULT_STEP=1 rc=-5 released=0 live_mask=0x0 violations=0FAULT_STEP=2 rc=-12 released=1 live_mask=0x0 violations=0FAULT_STEP=3 rc=-12 released=2 live_mask=0x0 violations=0FAULT_STEP=4 rc=-16 released=3 live_mask=0x0 violations=0PROBE_OK live_mask=0xf (all 4 resources active, STB_LOCAL clean)learner@ksa:~/gl-e00/m04-l02$ GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Confirming Zero Leaks Across All Four Fault Injection Points
learner@ksa:~/gl-e00/m04-l02$ strace -e trace=write,exit_group ./verifywrite(1, "FAULT_STEP=1 rc=-5 released=0 li"..., 296) = 296exit_group(0) = ?+++ exited with 0 +++GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Classic Unwind Ordering and Missing-Return Disasters
- A driver's
remove()callback must mirror the exact sameLIFOorder asprobe()'serr_*tail, plu…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Classic Unwind Ordering and Missing-Return Disasters
- In modern
Linux kernel6.12 code,devm_*managed APIs and<linux/cleanup.h>(guard(mutex)) automate…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: probe() initializes hardware cleanly and returns 0, yet the device immediately faults or hangs on first open() because clocks are off and buffers are freed.
- Root Cause: Omitting return 0; before err_free_ring: causes the happy path (where rc == 0 from the last helper call!) to fall straight through the cleanup cascade and still return rc (0)!
- Fix: Always place an explicit return 0; separated by a blank line directly above the top err_* label, and verify happy-path live_mask state in unit tests.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Unloading a module or failing late in probe() triggers an imprecise external abort on ARMv7-A or a use-after-free inside the interrupt handler.
- Root Cause: Disabling peripheral clocks before unmapping/stopping registers, or freeing rx_ring before calling free_irq(), lets a pending IRQ or bus write access dead memory/clocks.
- Fix: Write cleanup labels in exact reverse order of acquisition: stop IRQ/device entry points first, free buffers second, unmap MMIO third, and gate clocks last.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice
- Add a fifth resource
RES_DEVNODE = 1U << 4(cdev_add) at the end ofprobe_lifo()inverify.c, along…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice
- Verify that
fail_step = 5jumps to a newerr_unreg_irq:label aboveerr_free_ring:, releasing4res…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Independent Practice
- Temporarily remove
staticfromprobe_lifoinverify.cand run `gcc -std=c11 -Wall -Wextra -Wmissing-p…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Independent Practice
- Confirm that
record_relandprobe_lifocarry lowercaset(STB_LOCAL) while onlymaincarries uppe…
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? In probe() acquiring (1) clk_enable -> (2) ioremap -> (3) dma_alloc -> (4) request_irq, which label must a failure in request_irq() jump to?
Select an option or press R to reveal.
Correct: B
Because request_irq() failed, IRQ (4) was NOT acquired; cleanup starts at the most recently acquired resource (3: dma_alloc) and cascades through (2) and (1).
Common misconception: Calling free_* on the step that just failed, or tearing down resources in FIFO order.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? What is the binary effect in the ELF object file when you mark a file-private C helper static?
Select an option or press R to reveal.
Correct: A
On a function definition, static specifies internal linkage (STB_LOCAL), isolating the symbol to the current translation unit.
Common misconception: Confusing static storage duration on local variables with static internal linkage on functions.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 4.1: Why should err_* labels be named err_free_ring: rather than numbered err1:, err2:?
Select an option or press R to reveal.
Correct: D
Inserting a new acquisition mid-function invalidates err1/err2 mental numbering silently, whereas goto err_free_ring; remains self-documenting.
Common misconception: Naming error labels by step number (err1, err2), which silently misroutes jumps when a middle step is added.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Summary
- Kernel C11 uses lowercase
snake_caseidentifiers with symmetric lifecycle antonyms (alloc/free,register/unregister,enable/disable,lock/unlock) and rejects Hungarian type prefixes. - Every file-private function and module variable must be declared
staticso the compiler emitsELFSTB_LOCALlinkage, preventing global symbol collisions and enabling dead-code inlining. - Multi-resource initialization functions unwind partial failures by jumping forward to centralized
err_*labels arranged in strict Last-In, First-Out (LIFO) order. - Returning directly from the middle of a multi-step
probe()after acquiring clocks, mappings, or IRQs leaks earlier resources and leaves hardware clocks or locks wedged.
GL-E00 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Key takeaways
- Every file-private function and module variable must be declared
staticso the compiler emitsELFSTB_LOCALlinkage, preventing global symbol collisions and enabling dead-code inlining. - Multi-resource initialization functions unwind partial failures by jumping forward to centralized
err_*labels arranged in strict Last-In, First-Out (LIFO) order. - Returning directly from the middle of a multi-step
probe()after acquiring clocks, mappings, or IRQs leaks earlier resources and leaves hardware clocks or locks wedged.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Single-Purpose Variables, Fixed-Width Types & Defensive do-while(0) Macros
What you'll learn
- Replace multi-purpose
tempvariables andlong-sized hardware fields with single-purpose<stdint.h>declarations. - Analyze preprocessor token-pasting and precedence hazards to choose between
static inlinefunctions and fully parenthesized macros. - Implement a C11 static-hygiene and
LIFOunwind auditor verifying macro parenthesization,do { ... } while (0)wrapping, and zero hidden control-flow jumps.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety
- Two habits ported from tiny
8-bit microcontrollers cause severe defects in32/64-bit Linux systems C.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety
- Second,
unsigned longchanges width between yourx86_64workstation (LP64:8bytes) and your `ARMv7…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety
Figure 4.3a: Textual macro substitution occurs before C parsing; parentheses and do-while(0) preserve AST structure.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Mental model
note: Think of a do { ... } while (0) macro wrapper like shipping a multi-piece circuit subassembly inside one sealed IC package: no matter where the board layout places it, neighboring traces cannot accidentally short into only half of its internal pins.
Where it stops working: do { ... } while (0) protects statement grouping and trailing semicolons, but it STILL evaluates macro arguments each time they appear inside the body — only static inline functions guarantee single evaluation without GNU statement expressions.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# do { ... } while (0) Macro Idiom
definition: A standard C preprocessor idiom that wraps multiple statements inside a do { ... } while (0) loop executing exactly once; unlike a bare { ... } compound block, it requires a trailing semicolon at the invocation site (MACRO(x);), preventing a syntax error before else inside unbraced if (cond) MACRO(x); else ... constructs while optimizing away completely.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Single-Purpose Locals, LP64/ILP32 Widths, and Inline Type Safety
_Static_assert(sizeof(struct desc) == 8, ...) catches accidental LP64 pointer/long fields at compile time.
Use uint32_t for register structs, static inline for functions, and do-while(0) for multi-stmt macros.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Anatomy of Preprocessor Substitution Hazards
- The C preprocessor (
cpp) knows nothing about C expressions, statements, or types — it performs blind toke…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Anatomy of Preprocessor Substitution Hazards
- Now consider
#define ACK_BOTH(a, b) *(a) = 1; *(b) = 1;used insideif (irq) ACK_BOTH(r1, r2);: after e…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Anatomy of Preprocessor Substitution Hazards
Figure 4.3b: Host x86_64 LP64 makes sizeof(long)==8 while ARMv7-A ILP32 makes sizeof(long)==4; uint32_t stays 4 everywhere.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# mmio_defensive_macros.h
learner@ksa:~/gl-e00/m04-l03$ bat mmio_defensive_macros.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: mmio_defensive_macros.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ /* SPDX-License-Identifier: GPL-2.0 */ 2 │ #ifndef KSA_MMIO_DEFENSIVE_MACROS_H 3 │ #define KSA_MMIO_DEFENSIVE_MACROS_H 4 │ 5 │ #include <stdint.h> 6 │ 7 │ enum ccm_gate_mode { 8 │ CCM_GATE_OFF = 0x0U, 9 │ CCM_GATE_RUN_ONLY = 0x1U, 10 │ CCM_GATE_ALWAYS = 0x3U, 11 │ }; 12 │ 13 │ struct dma_bd_hw { 14 │ uint16_t length;───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# stdint.h(0p) / C11 _Static_assert
stdint.h(0p) / C11 _Static_assert(3) GL-E00 Quick Reference stdint.h(0p) / C11 _Static_assert(3) SYNOPSIS #include <stdint.h> _Static_assert(constant-expression, "diagnostic string"); DEFENSIVE MACRO & TYPE CHECKLIST Fixed-width Use uint8_t, uint16_t, uint32_t, uint64_t, uintptr_t for HW registers & binary protocols. static inline Prefer over #define for typed, single-evaluation helpers (safe with ptr++ or FIFO reads). Parentheses Wrap EVERY macro arg (x) and the ENTIRE outer expression ((x) + 1U). do-while(0) Wrap multi-statement macros in 'do { ... } while (0)' (no trailing semicolon). Control flow NEVER put 'return', 'goto', or 'break' inside a macro body. Kernel Systems Academy m04-l03 stdint.h(0p) / C11 _Static_assert(3) GL-E00 quick reference · full manual page: man 3 stdint.h(0p) / C11 _Static_assert GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Proving Macro Precedence, Side-Effect, and Width Invariants in C11
- In
verify.c, we verify all four defensive rules quantitatively on our workstation: `sizeof(unsigned long)…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Proving Macro Precedence, Side-Effect, and Width Invariants in C11
- Passing these assertions sets up
lab_m04_c_style_auditor, where you will build a reusable C11 static-…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m04-l03$ bat verify.c───────┬────────────────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼────────────────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdint.h> 3 │ #include <stdio.h> 4 │ 5 │ struct hw_desc_fixed { 6 │ uint32_t ctrl; 7 │ uint32_t buf_addr; 8 │ }; 9 │ _Static_assert(sizeof(struct hw_desc_fixed) == 8U, "Fixed-width descriptor must be 8 bytes"); 10 │ 11 │ #define BAD_SHIFT(n) 1U << n 12 │ #define SAFE_SHIFT(n) ((1U) << (n)) 13 │ 14 │ #define SAFE_LATCH(pa, pb, v) \───────┴──────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Inspecting LP64 Host Widths and Precedence Bitmasks
- Observe the recorded host output: on
x86_64Linux,sizeof(unsigned long)is8bytes while `sizeof(str…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Inspecting LP64 Host Widths and Precedence Bitmasks
- Equally stark is
MACRO_PARENS:~BAD_SHIFT(3)silently cleared bits0..2(0xFFFFFFF0) instead of cle…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Inspecting LP64 Host Widths and Precedence Bitmasks
learner@ksa:~/gl-e00/m04-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m04-l03$ ./verifyLP64_CHECK sizeof_ulong=8 sizeof_fixed_desc=8MACRO_PARENS broken_not=0xFFFFFFF0 safe_not=0xFFFFFFF7INLINE_ONCE result=4 post_counter=5 do_while_else_reg_a=99 reg_b=0learner@ksa:~/gl-e00/m04-l03$ GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Inspecting LP64 Host Widths and Precedence Bitmasks
learner@ksa:~/gl-e00/m04-l03$ strace -e trace=write,exit_group ./verifywrite(1, "LP64_CHECK sizeof_ulong=8 sizeof"..., 168) = 168exit_group(0) = ?+++ exited with 0 +++GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Hidden Macro Control Flow and Side-Effect Double Reads
- Before moving into
lab_m04_c_style_auditor, lock in the hierarchy of C11 abstractions: useenumfor int…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Hidden Macro Control Flow and Side-Effect Double Reads
- Whenever a macro must exist, audit three things mechanically: inner
(param)parentheses, outer(...)or…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Reading an I2C or UART receive FIFO inside CLAMP(*rx_fifo_reg, 0, 127) drops every second byte on the wire without setting any hardware overrun flag.
- Root Cause: A naive #define CLAMP(x, lo, hi) mentions (x) two or three times in its ternary expansion, issuing multiple volatile MMIO read cycles that pop distinct bytes from the hardware FIFO.
- Fix: Replace value macros with a static inline C11 function, or read the volatile register once into a single-purpose uint32_t sample local variable first.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: After an intermittent I2C NAK error, every subsequent thread opening the device hangs forever inside mutex_lock() (D uninterruptible sleep in ps).
- Root Cause: Calling CHECK_RET(i2c_xfer(...)); between mutex_lock(&dev->lock) and mutex_unlock(&dev->lock) executed a hidden return rc; inside the macro, bypassing goto err_unlock;.
- Fix: Delete return-hiding macros completely; write explicit if (rc < 0) goto err_unlock; statements so every exit path through held locks is visible.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice
- In
verify.c, add a second broken macro#define BAD_ADD_OFFSET(x) (x) + 0x10U(note inner parameter pare…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice
- Verify that
BAD_ADD_OFFSET(4U) * 2Uevaluates to4 + 32 = 36instead of(4 + 16) * 2 = 40, confirming…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m04_c_style_auditor/and inspectstarter/core.calongsidetests.c.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Independent Practice
- Run
sh check.shto confirm5/5TAP version 13checks pass, then run./files/lab_cli --benchto reco…
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Why does #define ACK_IRQ(a, b) { *(a) = 1; *(b) = 1; } fail to compile inside if (pending) ACK_IRQ(r0, r1); else count++;?
Select an option or press R to reveal.
Correct: A
Expanding { ... }; else parses as a block statement followed by a null statement ;, making the subsequent else token a syntax error; do { ... } while (0) absorbs the ;.
Common misconception: Assuming bare { ... } braces around a multi-statement macro behave identically to do { ... } while (0) inside if/else.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Why is unsigned long unsafe inside a shared DMA buffer-descriptor struct compiled in both x86_64 host tests and ARMv7-A firmware?
Select an option or press R to reveal.
Correct: D
Both x86_64 and ARMv7-A Linux run little-endian, but LP64 widens long and pointers to 64 bits while uint32_t stays exactly 4 bytes on both.
Common misconception: Assuming long is always 32 bits on Linux the way it is on 32-bit MCUs or LLP64 Windows.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 4.2: Why are macros like #define TRY_CALL(expr) if ((expr) < 0) return -EIO banned in Linux kernel C?
Select an option or press R to reveal.
Correct: C
Every control-flow exit in C must remain explicit at the call site so reviewers can trace lock/resource invariants down to the err_* tail.
Common misconception: Using Rust-like TRY() return macros in plain C functions that hold manual locks or raw allocations.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Lab: lab_m04_c_style_auditor
- Production kernel patches fail review immediately when macros hide
returnjumps, private helpers omit `st…
Verify: ./check.sh exits 0.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Summary
- Hardware register layouts and wire headers must use
<stdint.h>fixed-width types (uint8_t,uint16_t,uint32_t,uint64_t) becauseunsigned longis64bits onx86_64(LP64) and32bits onARMv7-A(ILP32). - Typed
constvalues,enumconstants, andstatic inlinefunctions are preferred over#definemacros because they enforce parameter types and evaluate side-effecting arguments (i++) exactly once. - Every expression macro must parenthesize each parameter use and the outer expression (
#define OFF(x) (((x) * 4U) + 8U)), while multi-statement macros wrap their body indo { ... } while (0)without a trailing semicolon. - Macros must never hide control-flow exits (
return,goto,break) because invisible jumps bypass caller spinlocks and centralizedgotocleanup spines.
GL-E00 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Key takeaways
- Typed
constvalues,enumconstants, andstatic inlinefunctions are preferred over#definemacros because they enforce parameter types and evaluate side-effecting arguments (i++) exactly once. - Every expression macro must parenthesize each parameter use and the outer expression (
#define OFF(x) (((x) * 4U) + 8U)), while multi-statement macros wrap their body indo { ... } while (0)without a trailing semicolon. - Macros must never hide control-flow exits (
return,goto,break) because invisible jumps bypass caller spinlocks and centralizedgotocleanup spines.
m05/
>_ Kernel Systems Academy
# Serial Consoles, Boot Straps, UUU Flashing & Bring-Up Triage
Calculate 115200 8N1 UART bit timing, eliminate RTS/CTS flow-control console deadlocks, decode i.MX6ULL BOOT_MODE/BOOT_CFG straps and UUU SDP-to-Fastboot provisioning, and triage bare-metal AAPCS32/.bss, U-Boot PHY/bootargs, and kernel VFS rootfs faults.
- 5.1 UART Console Framing (115200 8N1), Flow-Control Deadlocks & Boot-Mode Straps
- 5.2 SD, eMMC & Raw NAND Storage Topologies and UUU Provisioning
- 5.3 Bare-Metal & Bootloader Bring-Up Fault Triage
lab → i.MX6ULL Boot-Strap Decoder, AAPCS32/.bss Guard & VFS Panic Triage Engine
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# UART Console Framing (115200 8N1), Flow-Control Deadlocks & Boot-Mode Straps
What you'll learn
- Calculate
115200 8N1bit-cell duration (8.68 us), frame throughput, and receiver oversampling clock-drift tolerance. - Diagnose asymmetric
RX-works /TX-dead serial console hangs caused byCRTSCTSorIXONflags in POSIXtermios. - Decode
i.MX6ULLSRC_SBMR2(BOOT_MODE[1:0]) andSRC_SBMR1(BOOT_CFG1) register bitmasks to selectUSBSDP,SD,eMMC, orNANDboot.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap
- Your single umbilical cord during early board bring-up — long before Ethernet,
USB, orLCDdrivers exis…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap
- Nearly every engineer hits the same baffling symptom on day one:
U-Bootprints its countdown (`Hit any ke…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap
Figure 5.1a: 3-wire debug consoles omit RTS#/CTS#; enabling CRTSCTS blocks only host TX while target RX keeps streaming.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Mental model
note: Think of RTS/CTS enabled on a 3-wire UART cable like a polite speaker waiting at a disconnected green talk-light button: you hear everyone in the room (RX) clearly, yet your microphone stays muted forever (TX) waiting for a wire nobody soldered.
Where it stops working: Disabling CRTSCTS fixes 3-wire debug consoles, whereas high-baud (3 Mbps) Bluetooth or cellular UART links genuinely require physical RTS#/CTS# traces to prevent FIFO overruns.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# BOOT_MODE & BOOT_CFG Strap Pins
definition: Dual-purpose SoC pads (such as BOOT_MODE0/1 and LCD_DATA00..23 on the i.MX6ULL) whose weak pull-up/pull-down resistor or DIP-switch logic levels are latched once by the System Reset Controller into SRC_SBMR1 and SRC_SBMR2 on the rising edge of POR_B, telling the mask Boot ROM which boot media or USB recovery protocol to execute before pinmuxing.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Asynchronous 8N1 Timing and the Classic Frozen-Keyboard Trap
Missing dialout membership returns EACCES on /dev/ttyUSB0 before baud configuration even runs.
Disable CRTSCTS on 3-wire 115200 8N1 consoles; set BOOT_MODE=01 for USB SDP or 10 for flash boot.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)
- When
POR_Bdeasserts, thei.MX6ULLCortex-A7 starts at0x00000000inside on-chip mask Boot ROM (`96 K…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)
- During development, boards expose
BOOT_MODE[1:0]on a 2-pole DIP switch rather than burning one-time-prog…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# i.MX6ULL Reset Strap Latches (SRC_SBMR1 and SRC_SBMR2)
Figure 5.1b: External LCD pins act as boot straps only during POR_B assertion; if an attached LCD pulls them high, Internal Boot misroutes!
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# imx6ull_sbmr_uart.h
learner@ksa:~/gl-e00/m05-l01$ bat imx6ull_sbmr_uart.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: imx6ull_sbmr_uart.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ /* SPDX-License-Identifier: GPL-2.0 */ 2 │ #ifndef KSA_IMX6ULL_SBMR_UART_H 3 │ #define KSA_IMX6ULL_SBMR_UART_H 4 │ 5 │ #include <stdint.h> 6 │ #include <termios.h> 7 │ 8 │ #define IMX6ULL_SRC_SBMR1_ADDR 0x020D8004UL 9 │ #define IMX6ULL_SRC_SBMR2_ADDR 0x020D801CUL 10 │ 11 │ #define SBMR2_BMOD_SHIFT 24U 12 │ #define SBMR2_BMOD_MASK (0x3U << SBMR2_BMOD_SHIFT) 13 │ #define BMOD_FUSES 0x0U 14 │ #define BMOD_SERIAL_DOWNLOADER 0x1U───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# picocom(1) / termios(3)
picocom(1) / termios(3)(1) GL-E00 Quick Reference picocom(1) / termios(3)(1) SYNOPSIS picocom -b 115200 -d 8 -p n -y n --flow n /dev/ttyUSB0 minicom -D /dev/ttyUSB0 -b 115200 # Ctrl-A Z -> O -> Serial port setup -> F (Hardware Flow: No!) KEY DIAGNOSTICS RX prints, TX dead Hardware Flow Control (CRTSCTS) is ON over a 3-wire cable, or Ctrl-S (XOFF) paused TX. Garbled characters Baud rate mismatch (e.g., 9600 vs 115200) or missing common GND reference wire. Zero output at POR BOOT_MODE=01 (waiting silently on USB SDP!), blank flash, or TX/RX crossed backwards. Exit picocom Press Ctrl-A followed by Ctrl-X. Kernel Systems Academy m05-l01 picocom(1) / termios(3)(1) GL-E00 quick reference · full manual page: man 1 picocom(1) / termios(3) GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Calculating 8N1 Timing Margins and Decoding SRC Strap Registers in C11
- In
verify.c, we compute exact115200 8N1bit and frame durations in integer nanoseconds, verify the `16…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Calculating 8N1 Timing Margins and Decoding SRC Strap Registers in C11
- Running this model on our host proves exact bitmask extraction and
termiosflag invariants before probing…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m05-l01$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ static const char *decode_imx_boot(uint32_t sbmr1, uint32_t sbmr2) 7 │ { 8 │ uint32_t bmod = (sbmr2 >> 24U) & 0x3U; 9 │ uint32_t cfg1_hi = (sbmr1 >> 4U) & 0xFU; 10 │ uint32_t port = (sbmr1 >> 11U) & 0x1U; 11 │ 12 │ if (bmod == 0x1U) 13 │ return "USB_OTG1_SDP"; 14 │ if (bmod == 0x0U)───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Validating Bit Timing and Strap Override Precedence
- Look closely at the fourth
decode_imx_boot()call inSTRAPS: even whenSRC_SBMR1still holds `0x00000…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Validating Bit Timing and Strap Override Precedence
UART_8N1also confirms why dumping1 MiBof hex over115200UARTtakes over90seconds (`11,520 B…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Validating Bit Timing and Strap Override Precedence
learner@ksa:~/gl-e00/m05-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l01$ ./verifyUART_8N1 bit_us=8.68 frame_us=86.81 max_Bps=11520 3wire_crtscts_tx_blocked=1STRAPS sd=USDHC1_SD emmc=USDHC2_EMMC nand=GPMI_RAW_NAND recovery=USB_OTG1_SDPlearner@ksa:~/gl-e00/m05-l01$ GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Validating Bit Timing and Strap Override Precedence
learner@ksa:~/gl-e00/m05-l01$ strace -e trace=write,exit_group ./verifywrite(1, "UART_8N1 bit_us=8.68 frame_us=86"..., 155) = 155exit_group(0) = ?+++ exited with 0 +++GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Boot-Strap Contention and Serial Console Failure Modes
- Whenever a newly powered board shows a completely blank
115200 8N1terminal, check four physical facts in…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Boot-Strap Contention and Serial Console Failure Modes
- If
RXprints normally whileTXignores keystrokes, clearCRTSCTSandIXONfirst.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Flashing U-Boot to eMMC via UUU succeeds 100%, yet pressing the reset button produces zero characters on UART1.
- Root Cause: With BOOT_MODE[1:0] still set to 01 (Serial Downloader), the i.MX6ULL Boot ROM never reads eMMC and outputs nothing on UART1 — it silently enumerates USB_OTG1 waiting for another SDP host command.
- Fix: Switch BOOT_MODE[1:0] back to 10 (Internal Boot), verify BOOT_CFG selects eMMC/NAND/SD, and trigger a full POR_B power-on reset.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Board boots reliably from SD card when bare, then stops booting completely the instant an external RGB LCD panel or peripheral hat is plugged into the LCD_DATA header.
- Root Cause: The i.MX6ULL multiplexes BOOT_CFG1/2/4 onto LCD_DATA00..23 during POR_B; external pull-ups or powered back-feeding on the LCD cable override weak 10 kOhm board strap resistors and select a non-existent boot device.
- Fix: Isolate LCD_DATA peripheral loads until POR_B deasserts, strengthen strap resistors per hardware design guidelines, or burn BT_FUSE_SEL + boot fuses for production boards.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
verify.cto compute receiver sampling drift at bit9.5(middle of the Stop bit,9.5bit period…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice
- Print the cumulative drift in microseconds and verify that
5.20% > 4.76%(0.5 / 10.5) triggers a Stop-b…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Independent Practice
- Write a C11 helper
check_termios_3wire_safe(uint32_t c_cflag, uint32_t c_iflag)using<termios.h>const…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Independent Practice
- Test it on a
cfmakeraw(&tio)struct before and after maskingCRTSCTSto verify whethercfmakerawalon…
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? During bring-up over a 3-wire (TX, RX, GND) USB-TTL adapter, U-Boot prints its boot banner cleanly, yet pressing keys on your laptop never interrupts autoboot. What is the first host setting to check?
Select an option or press R to reveal.
Correct: B
Wrong baud produces garbled RX characters; swapped TX/RX or BOOT_MODE=01 produces zero RX output. Clean RX paired with dead TX is the signature of flow-control blocking (or a broken host TX wire).
Common misconception: Assuming both RX and TX must fail together whenever UART settings are wrong.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? How long does a single byte take on the wire at 115200 8N1, and what is the maximum continuous byte rate?
Select an option or press R to reveal.
Correct: A
8N1 adds 1 Start bit and 1 Stop bit (0 parity bits) around each 8-bit payload byte = 10 bit cells per byte (115200 / 10 = 11,520 B/s).
Common misconception: Dividing baud rate by 8 instead of 10 by forgetting Start and Stop framing bits.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? You flip the i.MX6ULL BOOT_MODE[1:0] DIP switch from 10 to 01 while the board is running Linux, then run reboot from the shell. Why does the board boot eMMC again instead of entering USB SDP?
Select an option or press R to reveal.
Correct: D
Software reboot triggers a warm WDOG reset that preserves latched SRC shadow state; cold power-cycling or asserting physical POR_B re-samples the DIP switches.
Common misconception: Expecting Linux reboot to re-latch external hardware boot-mode pins.
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Summary
- At
115200 8N1, each asynchronous frame carries10bit cells (1Start,8LSB-first data,0parity,1Stop) at8.68 us/bit(86.81 us/frame,11,520 bytes/smax). - Leaving hardware flow control (
CRTSCTS) enabled inminicomorpicocomon a3-wire (TX/RX/GND) USB-TTL bridge blocks host keyboardTXwaiting on unassertedCTS#while targetRXprints normally. - At
POR_Breset release, thei.MX6ULLBoot ROM samplesBOOT_MODE[1:0](SRC_SBMR2[25:24]):10selects Internal Boot viaBOOT_CFGstraps,01entersUSB_OTG1Serial Downloader (SDP), and00boots from eFUSEs. - Under Internal Boot (
BOOT_MODE = 10),BOOT_CFG1[7:4](SRC_SBMR1[7:4]sampled fromLCD_DATApins) selectsSD(USDHC1),eMMC(USDHC2), or rawNAND(GPMI).
GL-E00 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Key takeaways
- Leaving hardware flow control (
CRTSCTS) enabled inminicomorpicocomon a3-wire (TX/RX/GND) USB-TTL bridge blocks host keyboardTXwaiting on unassertedCTS#while targetRXprints normally. - At
POR_Breset release, thei.MX6ULLBoot ROM samplesBOOT_MODE[1:0](SRC_SBMR2[25:24]):10selects Internal Boot viaBOOT_CFGstraps,01entersUSB_OTG1Serial Downloader (SDP), and00boots from eFUSEs. - Under Internal Boot (
BOOT_MODE = 10),BOOT_CFG1[7:4](SRC_SBMR1[7:4]sampled fromLCD_DATApins) selectsSD(USDHC1),eMMC(USDHC2), or rawNAND(GPMI).
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# SD, eMMC & Raw NAND Storage Topologies and UUU Provisioning
What you'll learn
- Contrast
SD/eMMC512-byteLBA+boot0hardware partitions against rawSLC NANDeraseblock, page/OOB,MTD, andUBI/UBIFSgeometry. - Analyze why placing
FAT32orext4directly onto rawNANDfails immediately due to factory bad blocks and missing wear leveling. - Trace
UUUprovisioning scripts fromSDP:Boot ROMDCD+DDR3download intoFB:U-BootFastbootflash commands.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Managed FTL Block Flash Versus Raw SLC NAND Geometry
- Embedded
i.MX6ULLboards ship in two primary non-volatile storage variants:8 GiBeMMC(USDHC2) and…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Managed FTL Block Flash Versus Raw SLC NAND Geometry
SDcards andeMMCpackages integrate a dedicated controller running a Flash Translation Layer (FTL).
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Managed FTL Block Flash Versus Raw SLC NAND Geometry
- Raw
SLC NANDhas zero internal controller: thei.MX6ULLGPMIandBCHengines drive raw2 KiB…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Managed FTL Block Flash Versus Raw SLC NAND Geometry
Figure 5.2a: Boot ROM SDP only knows how to initialize DDR3 via DCD and jump to RAM U-Boot; U-Boot Fastboot writes the flash.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Mental model
note: Managed SD/eMMC flash is like checking luggage at an airport desk that hides conveyor routing behind clean claim-tag numbers (LBA), whereas raw SLC NAND hands you the warehouse forklift directly — you must track worn floor bays (BBT) and erase entire shelves (128 KiB PEBs) before stacking a 2 KiB box.
Where it stops working: An internal eMMC FTL handles wear leveling and bad blocks, yet sudden power loss during metadata updates can still corrupt FAT32 or FTL tables without ext4 journaling or read-only squashfs.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# UBI (Unsorted Block Images)
definition: A Linux kernel volume-management layer sitting directly above raw MTD flash devices that maps contiguous, bad-block-free Logical Eraseblocks (LEBs) onto Physical Eraseblocks (PEBs), maintaining erase-counter headers across the entire NAND chip and transparently relocating data away from newly failing blocks for UBIFS.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Managed FTL Block Flash Versus Raw SLC NAND Geometry
Even a brand-new board with completely erased eMMC/NAND boots U-Boot into DDR3 in < 1 second via SDP.
Keep LBA 2..2047 clear on SD, use boot0 on eMMC, use UBI/UBIFS on raw NAND, and stream via UUU SDP->FB.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing
- Compare exact byte layouts on both media types so partition math never collides with the Boot ROM!
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing
- On
512 MiBSLC NAND(4,096PEBsx128 KiB,64pages/block x2,048 B+64 BOOB), block0…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# eMMC Partition Offsets Versus NAND FCB, MTD, and LEB Sizing
Figure 5.2b: UBI consumes 2 NAND pages (EC + VID headers = 4 KiB on 2 KiB-page SLC NAND) per 128 KiB physical eraseblock.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# emmc_nand_provision.uuu
learner@ksa:~/gl-e00/m05-l02$ uuu_version 1.4.182 # Stage 1: Stream U-Boot (+ IVT/DCD) over USB OTG1 HID SDP into DDR3 RAMSDP: boot -f u-boot-imx6ull-14x14-evk-emmc.imx # Stage 2: RAM U-Boot runs USB Fastboot gadget on OTG1FB: ucmd setenv fastboot_dev mmcFB: ucmd setenv mmcdev 1FB: ucmd mmc dev 1 # Program U-Boot into dedicated eMMC boot0 hardware partition & enable boot0FB: flash bootloader u-boot-imx6ull-14x14-evk-emmc.imxFB: ucmd mmc partconf 1 1 1 0learner@ksa:~/gl-e00/m05-l02$ GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# uuu(1) / ubiattach(8)
uuu(1) / ubiattach(8)(1) GL-E00 Quick Reference uuu(1) / ubiattach(8)(1) SYNOPSIS sudo uuu -lsusb # Verify board enumerates as 15a2:0080 (SE Blank 6ULL) in BOOT_MODE=01 sudo uuu -b emmc_all u-boot.imx rootfs.sdcard sudo uuu emmc_nand_provision.uuu KEY STORAGE COMMANDS (Target Linux / U-Boot) dd if=u-boot.imx of=/dev/sdX bs=1K seek=1 conv=fsync # SD card 1 KiB (0x400) IVT offset ubiformat /dev/mtd4 -f rootfs.ubi # Preserves UBI erase counters (never raw nandwrite over UBI!) ubiattach -p /dev/mtd4 && mount -t ubifs ubi0:rootfs /mnt Kernel Systems Academy m05-l02 uuu(1) / ubiattach(8)(1) GL-E00 quick reference · full manual page: man 1 uuu(1) / ubiattach(8) GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Verifying LBA Headroom, UBI LEB Overhead, and UUU Ordering in C11
- Storage-layout arithmetic bugs wipe partition tables or underestimate
UBIFSimage limits when `mkfs.ubifs…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Verifying LBA Headroom, UBI LEB Overhead, and UUU Ordering in C11
- All geometry math executes deterministically in host C11; actual
USBSDPenumeration andGPMIBCHE…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m05-l02$ bat verify.c───────┬────────────────────────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼────────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <string.h> 6 │ 7 │ struct nand_ubi_geom { 8 │ uint32_t total_pebs; 9 │ uint32_t leb_bytes; 10 │ uint32_t reserved_bad_pebs; 11 │ uint32_t usable_lebs; 12 │ }; 13 │ 14 │ static struct nand_ubi_geom calc_ubi_geom(uint32_t mtd_pebs, uint32_t peb_bytes, uint32_t page_bytes)───────┴──────────────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Checking Partition Headroom and mkfs.ubifs Parameters
- Notice the
126,976-byte (124 KiB)leb_Bfigure inNAND_UBI: that exact integer is what you pass to…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Checking Partition Headroom and mkfs.ubifs Parameters
- Notice also why
reserved_bad_pebsequals80(20/1024of the entire4,096-PEB512 MiBchip, no…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Checking Partition Headroom and mkfs.ubifs Parameters
learner@ksa:~/gl-e00/m05-l02$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l02$ ./verifySD_LAYOUT ivt=0x400 uboot_end=656384 part1_start=1048576 headroom_B=392192NAND_UBI leb_B=126976 bad_rsv_pebs=80 usable_lebs=3756 usable_MiB=454.8UUU_SEQ valid_sdp_then_fb=1 reversed_fb_first_rejected=1learner@ksa:~/gl-e00/m05-l02$ GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Checking Partition Headroom and mkfs.ubifs Parameters
learner@ksa:~/gl-e00/m05-l02$ strace -e trace=write,exit_group ./verifywrite(1, "SD_LAYOUT ivt=0x400 uboot_end=65"..., 204) = 204exit_group(0) = ?+++ exited with 0 +++GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Provisioning and Flash-Wear Hazards on eMMC and NAND
- Keep your host
udevrules from Module 1 updated for bothUUUUSB IDs (15a2:0080NXPSDPHID and `05…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Provisioning and Flash-Wear Hazards on eMMC and NAND
- And when updating an existing
UBIpartition in the field, always useubiformatorubiupdatevol— neve…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: SDP: boot -f u-boot.imx reaches 100%, then uuu stalls indefinitely waiting for FB: Fastboot enumeration.
- Root Cause: Either the flashed u-boot.imx lacks CONFIG_USB_FUNCTION_FASTBOOT / DCD matching the board's DDR3 size, OR a Linux VM (VirtualBox/VMware) captured 15a2:0080 (SDP) but failed to auto-capture the new 0525:a4a5 (Fastboot) USB VID:PID on re-enumeration!
- Fix: Add both NXP SDP (15a2:0080) and U-Boot Fastboot (0525:a4a5) USB filters to your VM configuration and /etc/udev/rules.d/.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Running dd if=u-boot.imx of=/dev/sdb boots U-Boot, yet lsblk and Linux kernel report the SD card's MBR partition table is completely gone!
- Root Cause: Omitting seek=1 bs=1K (seek=2 bs=512) writes u-boot.imx at byte 0x000 (LBA 0), overwriting the 512-byte MBR AND placing the IVT at 0x000 instead of 0x400!
- Fix: Always include bs=1K seek=1 conv=fsync (preserving bytes 0..1023, including LBA 0 MBR), and verify Partition 1 starts at >= LBA 2048.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice
- Modify
verify.cto test what happens when an oversizedU-Boot+ environment blob grows to1,100 KiBw…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice
- Compute the minimum
4 MiB-aligned starting sector (LBA 8192) required to giveU-Bootand redundant `U…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Independent Practice
- Write a C11 parser
parse_mtdparts(const char *spec)for `mtdparts=gpmi-nand:4m(boot),8m(kernel),1m(dtb),-…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Independent Practice
- Confirm that
4 + 8 + 1 = 13 MiBleaves499 MiB(3,992PEBs) forrootfswith zero unalignedPEB…
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? Why does Linux kernel mount UBIFS over UBI + MTD on raw 512 MiB SLC NAND instead of formatting /dev/mtdblock4 directly as ext4?
Select an option or press R to reveal.
Correct: A
Unlike SD/eMMC (which hide bad blocks and wear leveling inside an on-chip FTL MCU), raw NAND requires MTD + UBI to manage bad blocks and erase counters.
Common misconception: Treating /dev/mtdblockN as a wear-leveled block device suitable for read-write ext4 or FAT32.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? During UUU provisioning of a completely blank board (BOOT_MODE = 01), why are two distinct USB protocols (SDP: followed by FB:) used?
Select an option or press R to reveal.
Correct: D
The 96 KiB mask Boot ROM does not contain full Fastboot, sparse ext4, or UBI flashing stacks — bootstrapping U-Boot into DDR3 gives UUU full storage drivers in RAM.
Common misconception: Thinking the mask Boot ROM itself writes ext4 partitions directly during SDP:.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 5.1: On an SD card (USDHC1), why do we write u-boot.imx with dd if=u-boot.imx of=/dev/sdX bs=1K seek=1 and start Partition 1 at LBA 2048?
Select an option or press R to reveal.
Correct: C
Standard SD cards lack eMMC's separate boot0 hardware area, so MBR (0x000), u-boot.imx (0x400), and Partition 1 (0x100000) share one LBA space without overlap.
Common misconception: Confusing SD card single-area layout with eMMC's dedicated mmcblkXboot0 hardware partition.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Summary
SD(USDHC1) andeMMC(USDHC2) embed an on-chip Flash Translation Layer (FTL) exposing512-byteLBAsectors, withi.MX6ULLIVTplaced at byte0x400(LBA 2) andeMMCproviding dedicatedboot0/boot1hardware partitions.- Raw
SLC NAND(GPMI+BCHECC) exposes physical eraseblocks (128 KiB) and factory/wear bad blocks directly without anFTL, requiringLinux kernelMTD, Bad Block Tables (BBT), andUBI/UBIFSrather thanFAT32/ext4. - With
BOOT_MODE[1:0] = 01,UUUStage 1 (SDP: boot -f u-boot.imx) uses the Boot ROM'sUSB_OTG1HID protocol to executeDCDDDR3init and runU-Bootdirectly in RAM. UUUStage 2 (FB:) speaksUSBFastbootto the RAM-residentU-Bootgadget to partition and programeMMC(boot0+GPT/MBR) orNAND(MTD/UBI) unattended.
GL-E00 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Key takeaways
- Raw
SLC NAND(GPMI+BCHECC) exposes physical eraseblocks (128 KiB) and factory/wear bad blocks directly without anFTL, requiringLinux kernelMTD, Bad Block Tables (BBT), andUBI/UBIFSrather thanFAT32/ext4. - With
BOOT_MODE[1:0] = 01,UUUStage 1 (SDP: boot -f u-boot.imx) uses the Boot ROM'sUSB_OTG1HID protocol to executeDCDDDR3init and runU-Bootdirectly in RAM. UUUStage 2 (FB:) speaksUSBFastbootto the RAM-residentU-Bootgadget to partition and programeMMC(boot0+GPT/MBR) orNAND(MTD/UBI) unattended.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Bare-Metal & Bootloader Bring-Up Fault Triage
What you'll learn
- Diagnose warm-vs-cold reset nondeterminism and
printf("%lld")/LDRDData Abortcrashes caused by unzeroed.bssor4-byte-misalignedARMv7-Astack pointers. - Triage
U-BootRMII Ethernet PHY reset timing,NULLphydevData Aborttraps, and truncatedbootargsenvironment strings. - Implement a C11 bring-up fault-triage engine (
lab_m05_boot_fault_triage) decoding straps,AAPCS32/.bssstartup bounds, andVFSrootfs panic signatures.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Silent C Runtime Preconditions That Linux User Space Hid From You
- When you run
./verifyon an Ubuntu host,Linux kernelexecve()andglibc_startquietly prepare a…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Silent C Runtime Preconditions That Linux User Space Hid From You
- Two classic bring-up ghosts follow immediately.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Silent C Runtime Preconditions That Linux User Space Hid From You
Figure 5.3a: Every bring-up hang localizes cleanly to one boundary: POR straps, start.S ABI, U-Boot env/PHY, or Kernel VFS.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Mental model
note: Bringing up bare-metal C or U-Boot without zeroing .bss and 8-byte-aligning SP is like moving into a lab bench without sweeping last week's loose wire clippings off the ESD mat: trivial 1-wire probes work by luck until a wide connector shorts across residual debris.
Where it stops working: Fixing startup assembly and bootargs resolves deterministic software contract bugs; unstable DDR3 calibration or brownout rails on VDD_SOC_IN require oscilloscope eye/rail checks.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# AAPCS32 8-Byte Stack Alignment
definition: Defined by the Procedure Call Standard for the ARM Architecture (AAPCS32, section 6.2.1.2), this ABI rule requires SP mod 8 == 0 at every public function call interface so 64-bit integers (uint64_t), double floats, variadic va_list 8-byte arguments, and LDRD/STRD instructions execute at naturally aligned doubleword addresses without alignment traps.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Silent C Runtime Preconditions That Linux User Space Hid From You
bic sp, sp, #7 guarantees 8-byte alignment even if a symbol or linker expression shifts by 4 bytes.
Zero .bss, enforce SP % 8 == 0 (bic sp,sp,#7), check bootargs length, and add rootwait on mmcblk.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures
- Once
U-Bootreaches its console, two subtle configuration traps dominate network and kernel bring-up.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures
- When
Linux kernel6.12 panics withVFS: Unable to mount root fs on <dev>, read the(major, minor)pai…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Decoding U-Boot Data Aborts and Kernel VFS Panic Signatures
Figure 5.3b: Major number 179 identifies MMC/SD block devices; (0,0) indicates no block device matched root=.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# armv7_bringup_guard.h
learner@ksa:~/gl-e00/m05-l03$ bat armv7_bringup_guard.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: armv7_bringup_guard.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ /* SPDX-License-Identifier: GPL-2.0 */ 2 │ #ifndef KSA_ARMV7_BRINGUP_GUARD_H 3 │ #define KSA_ARMV7_BRINGUP_GUARD_H 4 │ 5 │ #include <stdbool.h> 6 │ #include <stdint.h> 7 │ 8 │ /* 9 │ * Reference ARMv7-A CRT0 startup sequence (start.S): 10 │ * ldr sp, =_stack_top 11 │ * bic sp, sp, #7 @ Enforce AAPCS32 8-byte stack alignment 12 │ * ldr r0, =__bss_start 13 │ * ldr r1, =__bss_end 14 │ * mov r2, #0───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# bootz(U-Boot) / kernel-parameters(7)
bootz(U-Boot) / kernel-parameters(7)(7) GL-E00 Quick Reference bootz(U-Boot) / kernel-parameters(7)(7) U-Boot & Linux 6.12 ROOTFS BOOTARGS TEMPLATES # eMMC / SD ext4 boot (note mandatory 'rootwait'!) setenv bootargs 'console=ttymxc0,115200 root=/dev/mmcblk1p2 rootfstype=ext4 rw rootwait' # Raw SLC NAND UBIFS boot (note quotes protecting ';' in mtdparts if present!) setenv bootargs 'console=ttymxc0,115200 ubi.mtd=4 root=ubi0:rootfs rootfstype=ubifs rw' # NFSv3 network rootfs boot (requires CONFIG_ROOT_NFS=y and static Bench NIC!) setenv bootargs 'console=ttymxc0,115200 root=/dev/nfs nfsroot=192.168.10.1:/srv/nfs/rootfs,v3,tcp ip=192.168.10.50:192.168.10.1:192.168.10.1:255.255.255.0::eth0:off rw' Kernel Systems Academy m05-l03 bootz(U-Boot) / kernel-parameters(7)(7) GL-E00 quick reference · full manual page: man 7 bootz(U-Boot) / kernel-parameters(7) GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Modeling AAPCS32 Stack Alignment and VFS Panic Triage in Host C11
- In
verify.c, we prove mathematically why an odd-wordSP(0x80200004) corruptsAAPCS3264-bit stac…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Modeling AAPCS32 Stack Alignment and VFS Panic Triage in Host C11
- Completing this walkthrough prepares you directly for
lab_m05_boot_fault_triage, where you will repai…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m05-l03$ bat verify.c───────┬─────────────────────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼─────────────────────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <string.h> 6 │ 7 │ static uint32_t aapcs32_u64_stack_addr(uint32_t sp_at_call, uint32_t slot_off) 8 │ { 9 │ /* AAPCS32 aligns 8-byte stack args to 8-byte offset RELATIVE to SP (assumed % 8 == 0)! */ 10 │ uint32_t rel_aligned = (slot_off + 7U) & ~7U; 11 │ return sp_at_call + rel_aligned; 12 │ } 13 │ 14 │ static const char *classify_vfs_panic(const char *bootargs, uint32_t major)───────┴───────────────────────────────────────────────────────────────────────────────────────────────────GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Confirming 64-Bit Slot Misalignment and VFS Cause Isolation
- Look at
AAPCS32in the execution capture: the compiler carefully roundedslot_off = 4up to+8assumi…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Confirming 64-Bit Slot Misalignment and VFS Cause Isolation
VFS_TRIAGElikewise separates truncatedbootargs,NFSkernel-config/IP omissions, and missing `rootwa…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Confirming 64-Bit Slot Misalignment and VFS Cause Isolation
learner@ksa:~/gl-e00/m05-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m05-l03$ ./verifyAAPCS32 bad_sp=0x80200004 u64_addr=0x8020000C(mod8=4) fixed_sp=0x80200000 u64_addr=0x80200008(mod8=0)VFS_TRIAGE case1=TRUNCATED_OR_MISSING_ROOT_ARG case2=MISSING_CONFIG_ROOT_NFS_OR_IP_ARG case3=ASYNC_MMC_MISSING_ROOTWAITlearner@ksa:~/gl-e00/m05-l03$ GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Confirming 64-Bit Slot Misalignment and VFS Cause Isolation
learner@ksa:~/gl-e00/m05-l03$ strace -e trace=write,exit_group ./verifywrite(1, "AAPCS32 bad_sp=0x80200004 u64_ad"..., 222) = 222exit_group(0) = ?+++ exited with 0 +++GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Subtle Linker, U-Boot Semicolon, and DTB Address Collisions
- Keep one habit across every bring-up session in
GL-E01..GL-E07: whenever boot fails, scroll up from t…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Subtle Linker, U-Boot Semicolon, and DTB Address Collisions
- Comparing
Kernel command line:indmesgagainst what you thoughtsetenv bootargsset catches90%…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Running setenv bootargs console=ttymxc0,115200 mtdparts=gpmi-nand:4m(boot); root=ubi0:rootfs prints Unknown command 'root=ubi0:rootfs' or silently drops root=!
- Root Cause: U-Boot's Hush shell treats an unquoted ; as a command separator, ending setenv bootargs early and trying to execute the remainder as a shell command.
- Fix: Always wrap the entire bootargs value in single quotes (setenv bootargs '...') and verify the full stored value with printenv bootargs.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Adding a single static char flag; at the end of .bss causes start.S to corrupt 3 bytes of the section immediately following __bss_end.
- Root Cause: A 4-byte strlo r2, [r0], #4 loop writes a full 32-bit word on its final iteration if __bss_end - __bss_start is not a multiple of 4 bytes.
- Fix: Enforce . = ALIGN(4); __bss_end = .; inside the linker script .bss output section and verify ((bss_start | bss_end) & 3) == 0.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice
- Add a
U-Bootmemory-overlap check `check_bootz_overlap(uint32_t zimg_addr, uint32_t zimg_len, uint32_t dt…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice
- Verify your overlap check catches
zimg_addr + zimg_len > dtb_addrbeforebootzjumps into a corrupted `…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m05_boot_fault_triage/and inspectstarter/core.c.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Independent Practice
- Run
sh check.shto pass all5/5TAP version 13checks and run./files/lab_cli --benchto inspect `C…
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? A bare-metal ARMv7-A program initializes ldr sp, =0x80200004 in start.S. Simple GPIO LED loops run fine, yet calling snprintf(buf, sizeof(buf), "%llu", counter64) triggers a Data Abort or prints garbage. Why?
Select an option or press R to reveal.
Correct: D
0x80200000+ is valid DDR3 RAM on i.MX6ULL, and 32-bit LDR/STR work at +4, so the SP % 8 != 0 bug stays dormant until 64-bit LDRD/va_arg runs.
Common misconception: Assuming 4-byte stack alignment suffices on 32-bit ARMv7-A just because registers are 32 bits wide.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Linux kernel 6.12 boots from eMMC and prints VFS: Unable to mount root fs on unknown-block(179,2), followed 40 ms later by mmc1: new high speed MMC card at address 0001. What is missing from U-Boot bootargs?
Select an option or press R to reveal.
Correct: C
Modern Linux kernel USDHC probing is asynchronous so boot doesn't stall; without rootwait, VFS tries to open major 179 (mmcblk1p2) before the partition exists!
Common misconception: Reformatting the eMMC card repeatedly when the kernel log shows mmc1 simply probed a few milliseconds after VFS.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 4.2: When an ENET driver's probe() fails because the RMII PHY never responds on MDIO after clk_prepare_enable() and devm_platform_ioremap_resource(), what must its cleanup path ensure?
Select an option or press R to reveal.
Correct: B
Clean error return + LIFO clock teardown keeps hardware in a safe low-power state and prevents NULL dereference Data Aborts on later network operations.
Common misconception: Ignoring failed PHY attach during probe() and deferring NULL crashes into ndo_open().
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Lab: lab_m05_boot_fault_triage
- Early board bring-up failures rarely print polite stack traces: wrong
BOOT_MODEswitches produce total si…
Verify: ./check.sh exits 0.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Summary
- Bare-metal
ARMv7-Astart.Smust explicitly zero[__bss_start, __bss_end)before branching tomain()becauseDDR3powers up with random bit states that corrupt uninitialized C globals. - The
ARMv7-AAAPCS32ABI mandates8-byte stack alignment (SP mod 8 == 0, enforced viabic sp, sp, #7) at public call boundaries so64-bitLDRD/STRDandprintf("%lld")va_argslots do not fault or misalign. U-BootENETTFTPfailures andbootargstruncations stem from missing RMII PHY reset pulse/settle timing (>= 10 ms) or unescaped multi-linesetenv bootargsstrings exceeding console buffer limits.Kernel panic - not syncing: VFS: Unable to mount root fsencodes the exact failure stage:unknown-block(0,0)indicates missing/truncatedroot=orCONFIG_ROOT_NFS, whereasmmcblkerror -2withoutrootwaitindicates asynchronousUSDHCprobe race.
GL-E00 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Key takeaways
- The
ARMv7-AAAPCS32ABI mandates8-byte stack alignment (SP mod 8 == 0, enforced viabic sp, sp, #7) at public call boundaries so64-bitLDRD/STRDandprintf("%lld")va_argslots do not fault or misalign. U-BootENETTFTPfailures andbootargstruncations stem from missing RMII PHY reset pulse/settle timing (>= 10 ms) or unescaped multi-linesetenv bootargsstrings exceeding console buffer limits.Kernel panic - not syncing: VFS: Unable to mount root fsencodes the exact failure stage:unknown-block(0,0)indicates missing/truncatedroot=orCONFIG_ROOT_NFS, whereasmmcblkerror -2withoutrootwaitindicates asynchronousUSDHCprobe race.
m06/
>_ Kernel Systems Academy
# Cross-ABI ELF Auditing, Module Vermagic & Workbench Capstone
Audit 32-bit ARMv7-A hard-float ELF binaries (EM_ARM, EF_ARM_ABI_FLOAT_HARD, PT_INTERP, DT_NEEDED), diagnose Linux 6.12 .modinfo vermagic/CRC module rejections, and unify host pre-deployment verification in the GL-E00 Workbench Preflight Capstone.
- 6.1 ELF32 Cross-ABI Auditing, VFP Hard-Float Traps & Missing PT_INTERP ENOENT
- 6.2 Kernel Module vermagic, modversions CRCs & Timestamped dmesg Triage
- 6.3 End-to-End Embedded Workbench Preflight Capstone
lab → GL-E00 Capstone: Cross-ABI ELF32, PT_INTERP, Vermagic & Boot-Blob Preflight Gate
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# ELF32 Cross-ABI Auditing, VFP Hard-Float Traps & Missing PT_INTERP ENOENT
What you'll learn
- Audit
52-byteElf32_Ehdrheaders ande_flagsbitmasks (0x05000400EABI5 hard-float vs0x05000200soft-float) before copying binaries to/srv/nfs/rootfs. - Diagnose why
./app: No such file or directory(ENOENT) occurs on an existing, executableARMbinary whenPT_INTERPis absent from the target rootfs. - Verify
DT_NEEDEDshared-library presence andGLIBC_2.xxversion ceilings against the target rootfs sysroot.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# The Most Misleading Error Message in Embedded Linux Bring-Up
- Picture this rite of passage: you cross-compile
hello.con your workstation, copyhellointo `/srv/nfs/…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# The Most Misleading Error Message in Embedded Linux Bring-Up
- Tracing
Linux kernelfs/binfmt_elf.cexplains every byte of what happened.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# The Most Misleading Error Message in Embedded Linux Bring-Up
Figure 6.1a: execve() returns ENOEXEC when e_machine != EM_ARM, and returns ENOENT when PT_INTERP is missing in rootfs!
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Mental model
note: PT_INTERP inside a dynamically linked ELF executable works like a #! /bin/sh shebang line at the top of a script: if /bin/sh itself is missing from the rootfs, the kernel reports No such file or directory even though your script file is right there!
Where it stops working: Unlike text shebangs read as ASCII lines, PT_INTERP is a binary program-header table slice parsed only after fs/binfmt_elf.c validates e_machine (EM_ARM) and ELFCLASS32.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# PT_INTERP Program Header
definition: An ELF program-header entry (p_type = 3) in dynamically linked executables storing the NUL-terminated filesystem path of the user-space runtime dynamic linker (such as /lib/ld-linux-armhf.so.3 on 32-bit ARM hard-float Linux) that the kernel maps and transfers initial control to before the application's own _start entry point runs.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# The Most Misleading Error Message in Embedded Linux Bring-Up
Catching EM_X86_64 (62) or soft-float (0x200) on the host takes 5 milliseconds with readelf -h.
Verify EM_ARM(40), e_flags 0x400 (hard-float), PT_INTERP in rootfs/lib, and matching sysroot glibc.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention
- Every
32-bitARMexecutable starts with a fixed52-byteElf32_Ehdrstructure that you can parse dir…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention
- Why are
armel(0x200soft-float) andarmhf(0x400hard-float) mutually incompatible at the binary i…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Inside the 52-Byte Elf32_Ehdr and VFPv3 Calling Convention
Figure 6.1b: Byte offsets 0x00..0x27 of Elf32_Ehdr expose architecture, endianness, EABI version, and VFP float ABI.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# elf32_armhf_contract.h
learner@ksa:~/gl-e00/m06-l01$ bat elf32_armhf_contract.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: elf32_armhf_contract.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ /* SPDX-License-Identifier: GPL-2.0 */ 2 │ #ifndef KSA_ELF32_ARMHF_CONTRACT_H 3 │ #define KSA_ELF32_ARMHF_CONTRACT_H 4 │ 5 │ #include <stdint.h> 6 │ 7 │ #define KSA_ELFCLASS32 1U 8 │ #define KSA_ELFDATA2LSB 1U 9 │ #define KSA_ET_REL 1U 10 │ #define KSA_ET_EXEC 2U 11 │ #define KSA_ET_DYN 3U 12 │ #define KSA_EM_ARM 40U 13 │ #define KSA_EM_X86_64 62U 14 │ #define KSA_PT_INTERP 3U───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# elf(5) / readelf(1)
elf(5) / readelf(1)(5) GL-E00 Quick Reference elf(5) / readelf(1)(5) SYNOPSIS arm-linux-gnueabihf-readelf -h -l -d -V target_app file target_app DIAGNOSTIC COMMANDS readelf -h app Verify Class: ELF32, Machine: ARM, Flags: Version5 EABI, hard-float ABI. readelf -l app Inspect INTERP header -> [Requesting program interpreter: /lib/ld-linux-armhf.so.3]. readelf -d app List direct (NEEDED) shared libraries without running host ldd! cp -a sysroot/lib/* Always use -a (archive/no-dereference) when populating rootfs/lib symlinks! Kernel Systems Academy m06-l01 elf(5) / readelf(1)(5) GL-E00 quick reference · full manual page: man 5 elf(5) / readelf(1) GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Simulating fs/binfmt_elf.c Architecture and PT_INTERP Checks in C11
- In
verify.c, we synthesize three compact binaryELFimages in memory — anEM_X86_64accidental host b…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Simulating fs/binfmt_elf.c Architecture and PT_INTERP Checks in C11
- Watching
-ENOEXEC(-8) vs-ENOENT(-2) emerge from50lines of C11 makes the `No such file or dir…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m06-l01$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <string.h> 6 │ 7 │ struct mini_ehdr { 8 │ uint8_t ident[16]; 9 │ uint16_t type; 10 │ uint16_t machine; 11 │ uint32_t version, entry, phoff, shoff, flags; 12 │ uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstrndx; 13 │ };───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)
- Notice how cleanly
BINFMT_ELFseparates-8(-ENOEXEC,Exec format error) on theEM_X86_64image f…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)
- Whenever a target shell reports
not foundorNo such file or directoryon a binary you know exists, run…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)
learner@ksa:~/gl-e00/m06-l01$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l01$ ./verifyBINFMT_ELF x86_64_rc=-8(ENOEXEC) armel_rc=-2(ENOENT_missing_interp) armhf_rc=0(OK)learner@ksa:~/gl-e00/m06-l01$ GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Tracing Exact Return Codes (-ENOEXEC vs -ENOENT)
learner@ksa:~/gl-e00/m06-l01$ strace -e trace=write,exit_group ./verifywrite(1, "BINFMT_ELF x86_64_rc=-8(ENOEXEC)"..., 83) = 83exit_group(0) = ?+++ exited with 0 +++GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Symlink Dereferencing and Cross-ldd Security/Diagnostic Traps
- When building minimal BusyBox root filesystems (
GL-E03), copy shared libraries from your cross-toolchain'…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Symlink Dereferencing and Cross-ldd Security/Diagnostic Traps
- Keep one tiny
-staticdiagnostic binary on/binduring early bring-up so you can always test kernel `ex…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: Running ldd ./arm_app on Ubuntu prints not a dynamic executable even though file ./arm_app says dynamically linked!
- Root Cause: ldd works by invoking the host's dynamic linker (ld-linux-x86-64.so.2) with LD_TRACE_LOADED_OBJECTS=1, which cannot load 32-bit EM_ARM binaries (and is unsafe on untrusted ELFs).
- Fix: Never use host ldd on cross-binaries; always use arm-linux-gnueabihf-readelf -d ./arm_app and readelf -l ./arm_app.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: ls /srv/nfs/rootfs/lib/ld-linux-armhf.so.3 appears in directory listings, yet ./app on the target STILL fails with No such file or directory (ENOENT)!
- Root Cause: On toolchains where ld-linux-armhf.so.3 is a symbolic link pointing to ld-2.35.so (or /usr/arm-linux-gnueabihf/lib/... absolute host path!), a dangling symlink causes open_exec() inside the target's root namespace to return -ENOENT.
- Fix: Inspect ls -la rootfs/lib/ to verify every symlink is relative (-> ld-2.35.so) and its target regular file exists inside rootfs/lib/.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice
- Extend
sim_arm_binfmt_elf()inverify.cto validate buffer-overflow-safePT_INTERPNUL termination (`…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice
- Verify that
strcmp(req, ...)without a boundedmemchrcheck reads pastimg + len, and test your fix w…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Independent Practice
- Inspect your host's own
./verifybinary by writing a35-line C11 programdump_self_elf.cthat opens `…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Independent Practice
- Verify that on
x86_64Linux it printsEI_CLASS=2 (ELF64)ande_machine=62 (EM_X86_64), contrasting di…
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? On your ARMv7-A target console, ls -l /root/sensor_daemon shows -rwxr-xr-x 1 root root 18420, yet running /root/sensor_daemon prints -sh: /root/sensor_daemon: No such file or directory (ENOENT). What is the primary root cause?
Select an option or press R to reveal.
Correct: A
An x86_64 binary fails earlier with ENOEXEC (Exec format error); ENOENT on an existing executable is fs/binfmt_elf.c failing open_exec() on PT_INTERP!
Common misconception: Assuming No such file or directory from execve() can only refer to the executable path itself, rather than its PT_INTERP interpreter.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? What distinguishes EF_ARM_ABI_FLOAT_HARD (0x400, armhf) from EF_ARM_ABI_FLOAT_SOFT (0x200, armel) at function call boundaries?
Select an option or press R to reveal.
Correct: D
Because armhf and armel place float/double parameters in completely different register banks, mixing them corrupts arguments immediately — so Linux separates their ABIs and dynamic linkers.
Common misconception: Thinking -mfloat-abi=hard only changes internal arithmetic instructions without changing the public function-call register ABI.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? Why should you inspect an ARM cross-binary's shared-library dependencies with arm-linux-gnueabihf-readelf -d app rather than host ldd app?
Select an option or press R to reveal.
Correct: C
readelf is pure static binary inspection — architecture-independent, deterministic, and safe inside automated build/CI preflight gates.
Common misconception: Expecting host ldd to work cross-architecture.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Summary
- A valid
ARMv7-ALinux user-space binary carriesELFmagic0x7F 'E' 'L' 'F',EI_CLASS = ELFCLASS32 (1),e_machine = EM_ARM (40), ande_flagsbitEF_ARM_ABI_FLOAT_HARD (0x400). - Executing an
EM_ARM (40)binary on anx86_64host failself_check_arch()withENOEXEC(Exec format error), whereas executing anarmhfbinary on anARMrootfs missing itsPT_INTERP(/lib/ld-linux-armhf.so.3) makesexecve()returnENOENT(No such file or directory). - Mixing soft-float (
EF_ARM_ABI_FLOAT_SOFT = 0x200,r0..r3float passing) with hard-float (0x400,VFPv3s0..s15/d0..d7registers) breaks calling conventions and requests incompatible/lib/ld-linux.so.3vs/lib/ld-linux-armhf.so.3loaders. DT_NEEDEDentries and.gnu.version_rtags (GLIBC_2.xx) bind binaries to the sysroot's minimumglibcversion; compiling with a newer host cross-toolchain than the target rootfs fails inld.soat launch.
GL-E00 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Key takeaways
- Executing an
EM_ARM (40)binary on anx86_64host failself_check_arch()withENOEXEC(Exec format error), whereas executing anarmhfbinary on anARMrootfs missing itsPT_INTERP(/lib/ld-linux-armhf.so.3) makesexecve()returnENOENT(No such file or directory). - Mixing soft-float (
EF_ARM_ABI_FLOAT_SOFT = 0x200,r0..r3float passing) with hard-float (0x400,VFPv3s0..s15/d0..d7registers) breaks calling conventions and requests incompatible/lib/ld-linux.so.3vs/lib/ld-linux-armhf.so.3loaders. DT_NEEDEDentries and.gnu.version_rtags (GLIBC_2.xx) bind binaries to the sysroot's minimumglibcversion; compiling with a newer host cross-toolchain than the target rootfs fails inld.soat launch.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Kernel Module vermagic, modversions CRCs & Timestamped dmesg Triage
What you'll learn
- Inspect
.ko.modinfosections (modinfo drv.ko) to verifyvermagicrelease,SMP/preempt,ARMv7,p2v8, andlicense=GPLfields. - Differentiate
insmod-ENOEXEC(Invalid module format) from-ENOENT(Unknown symbol in module) usingCONFIG_PRINTK_TIME=ydmesglogs. - Audit out-of-tree Kbuild
Makefilesto prevent host-uname -rKDIRcontamination andCONFIG_LOCALVERSION_AUTO-dirtyversion skew.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds
- A
Hello Worlduser-spaceARMbinary compiled ten years ago still runs unmodified onLinux kernel6.12…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds
- Enabling
CONFIG_PREEMPT_RTorCONFIG_DEBUG_SPINLOCKchanges the byte size ofspinlock_tinside every…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds
Figure 6.2a: insmod prints only a generic errno string; the exact mismatched vermagic token or symbol prints in dmesg!
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Mental model
note: A user-space binary talks to the kernel across a standardized wall socket (syscall ABI lasts decades), whereas a .ko kernel module plugs directly onto the live CPU backplane bus — if a single struct pin shifted by 4 bytes, vermagic refuses insertion before privileged memory explodes.
Where it stops working: Matching vermagic strings proves build-configuration identity, NOT driver bug freedom; force-removing vermagic checks (modprobe --force) risks immediate Oops kernel memory corruption!
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Module vermagic (.modinfo)
definition: A NUL-terminated key-value entry (vermagic=...) generated by scripts/mod/modpost into a loadable .ko module's .modinfo ELF section that concatenates UTS_RELEASE with ABI-critical Kconfig tokens (SMP, preempt, mod_unload, modversions, ARMv7, p2v8) so finit_module() can verify structural binary compatibility with the running kernel.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Kernel Modules Carry Zero Binary Compatibility Across Kernel Builds
Never let an embedded driver Makefile fall back silently to /lib/modules/$(shell uname -r)/build!
Pin KDIR + ARCH=arm + CROSS_COMPILE, verify modinfo vermagic == target uname -r, and read timestamped dmesg.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps
- Open any
.kofile in a hex viewer orobjdump -s -j .modinfo drv.koand you will find a flat array of NU…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps
- When
CONFIG_MODVERSIONS=yis enabled,genksymshashes the expanded C AST of everyEXPORT_SYMBOLfunct…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Inside .modinfo NUL Records, __versions CRCs, and KDIR Traps
Figure 6.2b: Every .modinfo tag is a simple NUL-terminated ASCII key=value string readable on any host without ARM hardware.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# modinfo_vermagic_layout.c
learner@ksa:~/gl-e00/m06-l02$ bat modinfo_vermagic_layout.c───────┬────────────────────────────────────────────────────────────────────────────────── │ File: modinfo_vermagic_layout.c───────┼────────────────────────────────────────────────────────────────────────────────── 1 │ // SPDX-License-Identifier: GPL-2.0 2 │ /* 3 │ * Out-of-tree Kbuild invocation contract (never fallback to host uname -r!): 4 │ * make -C $(KDIR) M=$(PWD) ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- modules 5 │ * 6 │ * Inside the resulting .ko, modpost emits .modinfo and optional __versions: 7 │ */ 8 │ #include <stdint.h> 9 │ 10 │ struct ksa_modversion_info { 11 │ uint32_t crc; 12 │ char name[64 - sizeof(uint32_t)]; 13 │ };───────┴──────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# modinfo(8) / finit_module(2) / depmod(8)
modinfo(8) / finit_module(2) / depmod(8)(8) GL-E00 Quick Reference modinfo(8) / finit_module(2) / depmod(8)(8) SYNOPSIS /sbin/modinfo drv.ko # Inspect vermagic, license, depends, parm on x86_64 host! depmod -a -b /srv/nfs/rootfs 6.12.0-ksa # Build /lib/modules/6.12.0-ksa/modules.dep on host dmesg -T | tail -n 15 # Or monotonic [sec.usec] via CONFIG_PRINTK_TIME=y RETURN ERRORS (finit_module) ENOEXEC (Invalid module format) ELF arch mismatch, vermagic string mismatch, or __versions CRC mismatch. ENOENT (Unknown symbol/param) Unloaded dependency .ko, disabled CONFIG_*, bad module param, or GPL block. Kernel Systems Academy m06-l02 modinfo(8) / finit_module(2) / depmod(8)(8) GL-E00 quick reference · full manual page: man 8 modinfo(8) / finit_module(2) / depmod(8) GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Parsing .modinfo NUL Blobs and Symbol CRCs in Host C11
- Because
.modinfois simply a contiguous byte slice of NUL-terminatedkey=valuestrings inside the.ko…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Parsing .modinfo NUL Blobs and Symbol CRCs in Host C11
- This exact
.modinfoscanner becomes the second pillar of our Module 6 preflight capstone.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m06-l02$ bat verify.c───────┬─────────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼─────────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <errno.h> 3 │ #include <stdbool.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ static const char *find_modinfo_val(const char *blob, size_t len, const char *key) 9 │ { 10 │ size_t klen = strlen(key); 11 │ size_t pos = 0U; 12 │ 13 │ while (pos < len) { 14 │ const char *entry = blob + pos;───────┴───────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Observing Token-Boundary Release Checks and Errno Separation
- Notice line 33 of
verify.c:strncmp(vm, uts_rel, rlen) == 0 && vm[rlen] == ' '!
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Observing Token-Boundary Release Checks and Errno Separation
- Notice also the
[ 142.810412]prefix format: enablingCONFIG_PRINTK_TIME=yin your kernel config gives…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Observing Token-Boundary Release Checks and Errno Separation
learner@ksa:~/gl-e00/m06-l02$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l02$ ./verify[ 142.810412] MOD_CHECK ok=0 dirty=-8(ENOEXEC) bad_crc=-8(ENOEXEC) non_gpl=-2(ENOENT)learner@ksa:~/gl-e00/m06-l02$ GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Observing Token-Boundary Release Checks and Errno Separation
learner@ksa:~/gl-e00/m06-l02$ strace -e trace=write,exit_group ./verifywrite(1, "[ 142.810412] MOD_CHECK ok=0 di"..., 87) = 87exit_group(0) = ?+++ exited with 0 +++GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Makefile KDIR Defaults and insmod-vs-modprobe Confusion
- Adopt two permanent rules for every driver
Makefileyou write inGL-E04..GL-E07.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Makefile KDIR Defaults and insmod-vs-modprobe Confusion
- Second, install modules via
make -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=/srv/nfs/rootfs modules_installso…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: You tweak 1 line in an .dts file inside KDIR, copy the new .dtb, then build a new .ko — and insmod rejects the .ko with version magic '6.12.0-dirty ...' should be '6.12.0 ...'!
- Root Cause: With CONFIG_LOCALVERSION_AUTO=y, scripts/setlocalversion inspects git status in KDIR; modifying any tracked file appends -dirty to include/config/kernel.release used by .ko builds while the running zImage on the board was built when the tree was clean!
- Fix: Either commit changes cleanly, disable CONFIG_LOCALVERSION_AUTO (# CONFIG_LOCALVERSION_AUTO is not set) during iterative bring-up, or redeploy zImage alongside modules.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: insmod ./ap3216c.ko fails with Unknown symbol __iio_device_register (err -2) even though industrialio.ko exists under /lib/modules/.
- Root Cause: insmod loads only the single file path passed to it and never reads modules.dep to load prerequisite modules first.
- Fix: Run depmod -a once after installing .ko files and load modules by name with modprobe ap3216c (which loads industrialio.ko automatically).
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice
- Extend
verify.cto extract and parse the comma-separateddepends=field from a.modinfoblob (e.g., `…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice
- Test your parser on both an empty
"depends=\0"module (0prerequisites) and a2-dependency sensor mod…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Independent Practice
- Write a
12-line out-of-tree KbuildMakefilesnippet guarded byifeq ($(KERNELRELEASE),)that aborts w…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Independent Practice
- Verify with
make -non a dummy directory containinginclude/config/kernel.releasethat missingKDIRf…
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? insmod ./led_drv.ko fails on your i.MX6ULL board with insmod: ERROR: could not insert module ./led_drv.ko: Invalid module format (ENOEXEC). Where is the exact mismatched field printed, and what is the most common cause?
Select an option or press R to reveal.
Correct: D
Kernel modules are read via file descriptor (open + finit_module), never execve()d, so +x permissions and PT_INTERP are irrelevant; dmesg logs the exact vermagic or CRC rejection.
Common misconception: Running chmod +x on .ko files or guessing blindly without checking dmesg | tail.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Why does omitting MODULE_LICENSE("GPL") cause insmod to fail with Unknown symbol gpiod_get (err -2) (-ENOENT) in a Linux kernel 6.12 GPIO driver?
Select an option or press R to reveal.
Correct: C
Core modern driver subsystems (gpiod, regmap, platform_driver, devm_*) use EXPORT_SYMBOL_GPL; dmesg explicitly logs module_name: module license 'unspecified' taints kernel and Unknown symbol ... (err -2).
Common misconception: Assuming Unknown symbol always means a Kconfig option is disabled, overlooking missing MODULE_LICENSE("GPL").
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 6.1: Can /sbin/modinfo ./drv.ko on your x86_64 Linux workstation inspect an ARMv7-A (EM_ARM) kernel module?
Select an option or press R to reveal.
Correct: B
Just like readelf, modinfo is a pure file parser that reads .modinfo strings directly on the host — making pre-deployment vermagic checks trivial in CI/Makefiles!
Common misconception: Waiting until a .ko is copied to the board to discover its vermagic does not match uname -r.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Summary
- During
finit_module(),Linux kernelcheck_modinfo()compares.modinfovermagic=<release> SMP preempt mod_unload ARMv7 p2v8againstutsname()->releaseand compile-time kernel tokens. - When
insmodfails with-ENOEXEC(Invalid module format), timestampeddmesg(CONFIG_PRINTK_TIME=y) reveals exactversion magicrelease/flag drift (such as-dirtyor wrong hostKDIR) orCONFIG_MODVERSIONSsymbolCRCdisagreement. - When
insmodfails with-ENOENT(Unknown symbol in module, or unknown parameter), an exported dependency.kois unloaded (resolved viadepmod -a+modprobe), aCONFIG_*subsystem is disabled, orMODULE_LICENSE("GPL")was omitted for anEXPORT_SYMBOL_GPLsymbol. - Out-of-tree driver
Makefilesmust pointKDIRat the exact configured/builtARMv7-ALinux kernel6.12 tree (ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-), never/lib/modules/$(uname -r)/build.
GL-E00 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Key takeaways
- When
insmodfails with-ENOEXEC(Invalid module format), timestampeddmesg(CONFIG_PRINTK_TIME=y) reveals exactversion magicrelease/flag drift (such as-dirtyor wrong hostKDIR) orCONFIG_MODVERSIONSsymbolCRCdisagreement. - When
insmodfails with-ENOENT(Unknown symbol in module, or unknown parameter), an exported dependency.kois unloaded (resolved viadepmod -a+modprobe), aCONFIG_*subsystem is disabled, orMODULE_LICENSE("GPL")was omitted for anEXPORT_SYMBOL_GPLsymbol. - Out-of-tree driver
Makefilesmust pointKDIRat the exact configured/builtARMv7-ALinux kernel6.12 tree (ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-), never/lib/modules/$(uname -r)/build.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# End-to-End Embedded Workbench Preflight Capstone
What you'll learn
- Verify
ARMzImage(0x016F2818at offset0x24, little-endian) and FlattenedDevice Tree.dtb(0xD00DFEEDat offset0x00, big-endian) binary headers prior toTFTPexport. - Integrate
ELF32armhfPT_INTERProotfs checks and.modinfovermagictoken-boundary audits into a single zero-false-positive pipeline. - Complete the GL-E00 Capstone Studio (
lab_m06_workbench_preflight_capstone) and measureCLOCK_MONOTONIChost preflight throughput.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Closing the Loop Across All Six GL-E00 Workbench Foundations
- Over six modules, you have dismantled every host-side failure mode that trips up embedded Linux engineers b…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Closing the Loop Across All Six GL-E00 Workbench Foundations
- Production BSP teams never rely on human memory to check all of these before copying files into
/srv/tftp…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Closing the Loop Across All Six GL-E00 Workbench Foundations
Figure 6.3a: Every artifact entering /srv/tftp and /srv/nfs/rootfs is header-verified on the host before the board reboots.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mental model
note: A host preflight gate works like an avionics pre-takeoff checklist at the hangar door: catching a mismatched fuel grade, unlocked hatch, or missing chart in 2 milliseconds on the ground beats debugging a flameout 30 seconds after liftoff over a 115200 radio.
Where it stops working: Host preflight auditing proves binary ABI, magic headers, PT_INTERP closure, and vermagic alignment 100%, whereas electrical pinmux contention, IRQ latency, and bus waveforms still require live verification on the i.MX6ULL board.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Flattened Device Tree (FDT) Magic (0xD00DFEED)
definition: The mandatory big-endian 32-bit magic number (0xD0, 0x0D, 0xFE, 0xED at byte offset 0x00 of struct fdt_header) emitted by the Device Tree compiler (dtc -I dts -O dtb) that U-Boot's bootz command and Linux kernel early boot inspect before parsing board hardware topology.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Closing the Loop Across All Six GL-E00 Workbench Foundations
Note the endianness contrast: ARM zImage magic is little-endian, whereas FDT .dtb headers are big-endian!
Audit zImage (0x016F2818), FDT (0xD00DFEED), ELF32 armhf PT_INTERP, and .ko vermagic before boot!
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko
- Notice a subtle endianness detail when inspecting
/srv/tftpboot artifacts in C11 on a little-endian `x86…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko
- Reading
uint32_tendianness explicitly via byte shifts (((uint32_t)b[0] << 24) | ...for big-endian FDT…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Binary Magic Signatures Across zImage, FDT .dtb, ELF32, and .ko
Figure 6.3b: Byte-shift endian readers parse zImage (LE), FDT .dtb (BE), and ELF32 (LE) without alignment Undefined Behavior.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# workbench_preflight_manifest.h
learner@ksa:~/gl-e00/m06-l03$ bat workbench_preflight_manifest.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: workbench_preflight_manifest.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ /* SPDX-License-Identifier: GPL-2.0 */ 2 │ #ifndef KSA_WORKBENCH_PREFLIGHT_MANIFEST_H 3 │ #define KSA_WORKBENCH_PREFLIGHT_MANIFEST_H 4 │ 5 │ #include <stdint.h> 6 │ 7 │ #define ARM_ZIMAGE_MAGIC_OFFSET 0x24U 8 │ #define ARM_ZIMAGE_MAGIC_LE 0x016F2818U 9 │ #define FDT_MAGIC_BE 0xD00DFEEDU 10 │ 11 │ static inline uint32_t ksa_read_le32(const uint8_t *p) 12 │ { 13 │ return (uint32_t)p[0] | 14 │ ((uint32_t)p[1] << 8U) |───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# dtc(1) / mkimage(1) / file(1)
dtc(1) / mkimage(1) / file(1)(1) GL-E00 Quick Reference dtc(1) / mkimage(1) / file(1)(1) SYNOPSIS dtc -I dts -O dtb -o imx6ull-board.dtb imx6ull-board.dts dtc -I dtb -O dts imx6ull-board.dtb | head -n 25 # Decompile binary .dtb back to readable DTS! file /srv/tftp/zImage /srv/tftp/imx6ull-board.dtb PRE-DEPLOYMENT CHECKLIST (GL-E00 -> GL-E01..E07) 1. /srv/tftp/zImage 'ARM OpenFirmware FORTH' / 'Linux kernel ARM boot executable zImage (little-endian)' 2. /srv/tftp/*.dtb 'Device Tree Blob version 17' (0xD00DFEED big-endian) 3. /srv/nfs/rootfs UID 0:0 ownership, /etc/exports has (rw,sync,no_root_squash,no_subtree_check) 4. Staged ELFs & .ko EM_ARM(40) + hard-float(0x400) + /lib/ld-linux-armhf.so.3 + matching vermagic Kernel Systems Academy m06-l03 dtc(1) / mkimage(1) / file(1)(1) GL-E00 quick reference · full manual page: man 1 dtc(1) / mkimage(1) / file(1) GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Running the Unified Boot-Blob, ELF32, and Vermagic Gate in C11
- In
verify.c, we assemble a mini end-to-end staging check validatingARMzImage(0x016F2818LE at `0…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Running the Unified Boot-Blob, ELF32, and Vermagic Gate in C11
- Then step into
lab_m06_workbench_preflight_capstoneto complete your full C11 pre-deployment auditor…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# verify.c
learner@ksa:~/gl-e00/m06-l03$ bat verify.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: verify.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #define _POSIX_C_SOURCE 200809L 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ #include <string.h> 6 │ 7 │ static uint32_t rd_le32(const uint8_t *p) 8 │ { 9 │ return (uint32_t)p[0] | ((uint32_t)p[1] << 8U) | 10 │ ((uint32_t)p[2] << 16U) | ((uint32_t)p[3] << 24U); 11 │ } 12 │ 13 │ static uint32_t rd_be32(const uint8_t *p) 14 │ {───────┴────────────────────────────────────────────────────────────────────────────────GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Confirming Little-Endian zImage and Big-Endian FDT Validation
- Notice how
check_zimage_dtb()rejectsdts_textinstantaneously because ASCII"/dts"(0x2F647473) !=…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Confirming Little-Endian zImage and Big-Endian FDT Validation
- Combined with
ELF32armhfPT_INTERPand.kovermagicchecks in the Capstone Lab, your host build…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Confirming Little-Endian zImage and Big-Endian FDT Validation
learner@ksa:~/gl-e00/m06-l03$ gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m06-l03$ ./verifyPREFLIGHT_BLOBS zimage_magic=0x016F2818 fdt_magic=0xD00DFEED valid_pair=1 dts_text_rejected=1learner@ksa:~/gl-e00/m06-l03$ GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Confirming Little-Endian zImage and Big-Endian FDT Validation
learner@ksa:~/gl-e00/m06-l03$ strace -e trace=write,exit_group ./verifywrite(1, "PREFLIGHT_BLOBS zimage_magic=0x0"..., 94) = 94exit_group(0) = ?+++ exited with 0 +++GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Common Deployment Mismatches Between bootz, bootm, and FDT
- With
GL-E00complete, you own a repeatable, first-principles Linux embedded engineering workbench: isolat…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Common Deployment Mismatches Between bootz, bootm, and FDT
- Carry this preflight mindset straight into
GL-E01(imx6ull-baremetal-core), where you will write `A…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: U-Boot prints Wrong Image Format for bootm command / ERROR: can't get kernel image! right after tftp 80800000 zImage succeeds.
- Root Cause: bootm expects a legacy 64-byte uImage header (0x27051956 magic from mkimage) or FIT image, whereas bootz boots a raw ARM zImage (0x016F2818 at 0x24) directly!
- Fix: Always pair ARM 32-bit zImage with bootz 0x80800000 - 0x83000000 (note the - placeholder when no separate initramfs is used).
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: - Symptom: You modify a Device Tree .dts file and run make dtbs, yet /proc/device-tree/ on the booted board shows zero changes!
- Root Cause: Linux kernel 6.12 organizes ARM vendor DTs under arch/arm/boot/dts/nxp/imx/; copying from a stale top-level build directory or editing an .dtsi not #included by your board's .dts deploys the old blob.
- Fix: Run dtc -I dtb -O dts /srv/tftp/board.dtb | grep -A4 your_node on the staged /srv/tftp file before rebooting the board!
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice
- Extend
check_zimage_dtb()inverify.cto also reject legacyuImageheaders (0x27051956big-endian a…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice
- Test all three cases (
zImage,uImage, and truncated.dtbwherefdt_size = 4096on a512-byte file…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Independent Practice
- Open
labs/lab_m06_workbench_preflight_capstone/and examinestarter/core.c.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Independent Practice
- Run
sh check.sh(5/5TAP version 13checks passing) and./files/lab_cli --benchto complete the **G…
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? Why must a C11 preflight tool read ARM zImage magic (0x016F2818 at 0x24) as little-endian while reading .dtb magic (0xD00DFEED at 0x00) as big-endian?
Select an option or press R to reveal.
Correct: C
File format endianness is an intrinsic property of the binary specification: ARM Linux zImage/ELF32 are little-endian; FDT .dtb headers/cells are always big-endian.
Common misconception: Casting *(uint32_t *)dtb_buf == 0xD00DFEED directly on a little-endian x86_64 host (which sees 0xEDFE0DD0!).
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? In bootz 0x80800000 - 0x83000000, what does the middle hyphen (-) represent to U-Boot?
Select an option or press R to reveal.
Correct: B
bootz <kernel_addr> [<initrd_addr>[:<size>] | -] [<fdt_addr>] uses - to omit initrd when fdt_addr is supplied.
Common misconception: Omitting the - (bootz 0x80800000 0x83000000), which makes U-Boot mistake your .dtb for a corrupted initrd!
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval check from Lesson 6.2: Why must a preflight vermagic checker verify vm[strlen(expected_rel)] == ' ' in addition to strncmp(vm, expected_rel, strlen(expected_rel)) == 0?
Select an option or press R to reveal.
Correct: A
Prefix-only strncmp("6.12.0-ksa-dirty ...", "6.12.0-ksa", 10) returns 0, letting -dirty skew slip right past an incomplete preflight script!
Common misconception: Using strncmp with strlen(prefix) when testing exact token equality.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Lab: lab_m06_workbench_preflight_capstone
- Deploying unverified cross-build outputs into
/srv/tftpand/srv/nfs/rootfsturns single-line build mis…
Verify: ./check.sh exits 0.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Summary
- A complete embedded workbench preflight gate validates boot blobs (
ARMzImagemagic0x016F2818at0x24and big-endianDevice Tree.dtbmagic0xD00DFEEDat0x00), user-spaceELF32armhfbinaries, and.kovermagicbefore target deployment. - Every staged target executable must satisfy
ELFCLASS32,EM_ARM (40),EF_ARM_ABI_FLOAT_HARD (0x400), and physical existence of itsPT_INTERPloader andDT_NEEDEDlibraries inside/srv/nfs/rootfs. - Every staged
.komodule under/srv/nfs/rootfs/lib/modules/<release>/must carrylicense=GPL*and avermagicmatching<release>on an exact token boundary plusARMv7 p2v8. - Executing deterministic binary preflight checks on the Linux host turns
30-second reboot-and-panic mysteries into sub-millisecond build-time diagnostics with zero target flash wear.
GL-E00 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Key takeaways
- Every staged target executable must satisfy
ELFCLASS32,EM_ARM (40),EF_ARM_ABI_FLOAT_HARD (0x400), and physical existence of itsPT_INTERPloader andDT_NEEDEDlibraries inside/srv/nfs/rootfs. - Every staged
.komodule under/srv/nfs/rootfs/lib/modules/<release>/must carrylicense=GPL*and avermagicmatching<release>on an exact token boundary plusARMv7 p2v8. - Executing deterministic binary preflight checks on the Linux host turns
30-second reboot-and-panic mysteries into sub-millisecond build-time diagnostics with zero target flash wear.