learner@ksa:~/gl-e01$
>_ Kernel Systems Academy
ARMv7-A Cortex-A7 Architecture, Boot ROM & Bare-Metal BSP
Embedded C, BSP, firmware, and Linux bring-up engineers
Outcome: Construct an inspected ARMv7-A bare-metal image, establish its C runtime, and test a modular GPIO BSP without confusing host-model evidence with board proof.
- m01/ Cross-compilation workbench, ARM EABI, and schematics
- m02/ Cortex-A7 modes, CP15, and ARMv7 assembly
- m03/ IOMUXC muxing, pad electrical policy, and GPIO MMIO
- m04/ Boot ROM selection, IVT geometry, and DCD command streams
- m05/ C runtime startup, linker placement, and peripheral headers
- m06/ Modular BSP, transistor-switched buzzer, and polled key capstone
m01/
>_ Kernel Systems Academy
# Cross-compilation workbench, ARM EABI, and schematics
- 1.1 Host–Target Workbench and the i.MX6ULL SoC
- 1.2 ARM Hard-Float EABI, ELF Sections, and Object Inspection
- 1.3 Schematics, Active-Low Circuits, and Register Maps
lab → lab_m01_eabi_workbench
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host–Target Workbench and the i.MX6ULL SoC
What you'll learn
- Trace host, transport, RAM, and CPU boundaries in a bring-up experiment.
- Diagnose serial, TFTP, and NFS failures without conflating their layers.
- Record reproducible build evidence while identifying untested target behavior.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
- When you compile and run
./helloon a desktop workstation, one computer performs every role: your `x86_64…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
- What physically sits inside that
i.MX6ULLpackage alongside theCortex-A7CPU?
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
- 1.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
- Because every hardware block along that chain can fail independently, the
Cortex-A7core can fetch and ex…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
Figure 1.1a: Host-to-target workbench architecture — separating x86_64 LP64 compilation, three independent transport channels, and the internal silicon blocks of the i.MX6ULL SoC.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Mental model
note: Bringing up a bare-metal board from a workstation is like machining turbine blades in a CNC shop (build host), shipping the crate (TFTP transport), staging it on the plant floor (target RAM), and spinning the rotor (Cortex-A7 execution): a signed shipping receipt proves the bytes arrived intact, never that the rotor balanced or generated power.
Where it stops working: Unlike physical freight, host LP64 and target ILP32 compilers disagree on pointer and long widths before shipping, and writing to the wrong target RAM address can silently overwrite the live bootloader receiving the transfer.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Cross-Compilation Host, Freestanding Target & Bring-Up Planes
definition: A cross compiler executes on the build host (x86_64 LP64 workstation) while emitting machine instructions and binary data layouts for a distinct execution target (32-bit ARMv7-A ILP32 Cortex-A7). In a freestanding target image (-ffreestanding -nostdlib), no OS loader maps virtual addresses, zeroes .bss, or implements POSIX system calls. During bring-up, asynchronous UART serial (115200 8N1 character observation), TFTP (UDP block transfer into target RAM under U-Boot), and NFS (remote VFS filesystem mount under a running Linux kernel) operate on separate hardware and protocol layers with independent failure modes.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
- Step through the four workbench boundaries below to see exactly what each observation proves—and what remai…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Host vs Target Machines and the i.MX6ULL Silicon Graph
Step 1 (Build Host): C11 host verifiers prove math and struct layout; the cross toolchain emits EM_ARM ELF32 and raw binary artifacts.
Identify which hardware or software boundary each workbench observation actually tests.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Isolating UART, TFTP, and NFS Transport Planes
- Why do bring-up engineers wire both a
3.3 VUSB-to-UARTadapter and an isolated lab Ethernet cable to…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Isolating UART, TFTP, and NFS Transport Planes
UARTSerial Console (115200 8N1,3.3 VTTL): A two-wire (TX,RX+GND) asynchronous character stream. Always verify the schematic's logic voltage (3.3 Vvs1.8 V—never RS-232+/-12 V!) and ground continuity before connecting. Silence onUART1means the console port, baud rate,IOMUXCpad mux,UARTclock gate, or early boot path failed; it says nothing** about Ethernet health.TFTPImage Download (UDPport69inU-Boot2025.x): Once a network-capable bootloader (U-Boot) is running in initializedDDR3RAM with a workingENETdriver,tftpboot ${loadaddr} bsp.bincopies raw file bytes from the hostTFTPexport directory into physical target RAM** at${loadaddr}(0x87800000).TFTPcannot run on a blank bare-metal CPU without a network stack, and a passingcrc32proves only byte-identical delivery—not a validARMentry point or stack!NFSRoot Filesystem (RPC/TCPport2049): Mounts an exported host folder into a runningLinux kernel** Virtual Filesystem (nfsroot=).NFSdoes not transfer bare-metal.binimages intoOCRAMorDDR3; restrict exports strictly to your isolated lab subnet (192.0.2.0/24) rather than disabling host firewalls globally.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Isolating UART, TFTP, and NFS Transport Planes
- Study the
U-Boot2025.x transfer sequence below from the target's perspective.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# workbench.uboot
learner@ksa:~/gl-e01/m01-l01$ bat workbench.uboot───────┬──────────────────────────────────────────────────────────────────────────────── │ File: workbench.uboot───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ # Example isolated lab assignments; adapt to your lab network. 2 │ setenv ipaddr 192.0.2.20 3 │ setenv serverip 192.0.2.10 4 │ setenv loadaddr 0x87800000 5 │ printenv ipaddr serverip loadaddr 6 │ # Run only after checking target RAM ownership and server policy. 7 │ tftpboot ${loadaddr} bsp.bin 8 │ crc32 ${loadaddr} ${filesize} 9 │ # Downloading is not permission to jump to an uninspected image.───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Locking LP64 vs ILP32 Struct Widths and Window Bounds in C11
- Throughout
GL-E01, every lesson pairs realARMv7-Atarget code with a native **strictISO C11host ve…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Locking LP64 vs ILP32 Struct Widths and Window Bounds in C11
- 1.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Locking LP64 vs ILP32 Struct Widths and Window Bounds in C11
Figure 1.1b: Locking 16-byte cross-ABI descriptor layout with uint32_t (top) and preventing 32-bit modular wraparound across the i.MX6ULL physical address map (bottom).
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# abi_workbench_audit.c
learner@ksa:~/gl-e01/m01-l01$ bat abi_workbench_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: abi_workbench_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdalign.h> 4 │ #include <stddef.h> 5 │ #include <stdint.h> 6 │ #include <stdio.h> 7 │ 8 │ struct armv7_load_desc { 9 │ uint32_t load_addr; 10 │ uint32_t entry_addr; 11 │ uint32_t byte_len; 12 │ uint32_t crc32_val; 13 │ }; 14 │ _Static_assert(sizeof(struct armv7_load_desc) == 16U, "descriptor size");───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Executing the ABI and Placement Verifier
- Compile and run
abi_workbench_audit.cunder-std=c11 -Wall -Wextra -Werror -pedantic.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Executing the ABI and Placement Verifier
learner@ksa:~/gl-e01/m01-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic abi_workbench_audit.c -o abi_workbench_auditlearner@ksa:~/gl-e01/m01-l01$ ./abi_workbench_auditabi_desc=16B align=4B host_ptr=8B arm32_ptr=4B le=1 window=oklearner@ksa:~/gl-e01/m01-l01$ GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Executing the ABI and Placement Verifier
learner@ksa:~/gl-e01/m01-l01$ strace -e trace=write,exit_group \> ./abi_workbench_auditwrite(1, "abi_desc=16B align=4B host_ptr=8"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Evidence Boundaries, Wraparound Proofs, and Channel Trade-Offs
- Look at the
stracetrace above (write(1, ..., 62)followed byexit_group(0)on anx86_64host): tha…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Evidence Boundaries, Wraparound Proofs, and Channel Trade-Offs
- Later: Lesson
m01-l02opens the compiled binary itself to inspect howARMAAPCS32passes integer and…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A binary image header written by an x86_64 C host utility passes desktop unit tests, yet Cortex-A7 boot code reads 0x00000000 for entry_addr and jumps into upper zero padding. Root Cause: The host struct used unsigned long or size_t (8 bytes on LP64) instead of uint32_t (4 bytes on ILP32), doubling field offsets in the serialized byte stream. Fix: Declare every cross-target wire or image field with <stdint.h> fixed-width types (uint32_t, uint16_t) and enforce total byte size via _Static_assert.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: tftpboot ${loadaddr} bsp.bin prints Bytes transferred = 262144 cleanly, yet U-Boot freezes or resets before you even type go ${loadaddr}. Root Cause: loadaddr overlapped U-Boot's own relocated code, malloc heap, stack, or active page tables near the top of DDR3 because the address was picked without inspecting bdinfo. Fix: Run bdinfo on the U-Boot console first, select a non-overlapping payload window such as 0x87800000, and verify filesize fits before transferring.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Guided Practice: Auditing a Mixed-Width Header & OCRAM Span
- Step 1 (Stride Calculation): On
x86_64(LP64), computeoffsetof(struct bad_hdr, entry)and `sizeo…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Independent Practice: Multi-Region Target Memory Map Auditor (memmap_audit.c)
- Write a standalone
ISO C11programmemmap_audit.cencoding thei.MX6ULLbring-up map: Boot ROM worksp…
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? In U-Boot, tftpboot 0x87800000 bsp.bin and crc32 succeed, but the serial console stays completely silent after jumping to 0x87800000. Which engineering conclusion is justified?
Select an option or press R to reveal.
Correct: A
tftpboot + crc32 prove only that the expected bytes landed in DDR3; they prove nothing about whether those bytes form valid ARMv7-A code with a valid stack and console setup.
Common misconception: Confusing transport byte-delivery completion with valid target CPU execution.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? Why does ram_window_fits(base, size, start, length) check start >= base first and then test length <= size - (start - base) instead of start + length <= base + size?
Select an option or press R to reveal.
Correct: C
Unsigned uint32_t addition wraps modulo 2^32 without trapping; subtracting offset = start - base after confirming start >= base eliminates wraparound across the entire 4 GiB address space.
Common misconception: Assuming well-defined C11 unsigned modular arithmetic preserves monotonic address ordering.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: what does a 0 exit code from the native x86_64 abi_workbench_audit binary prove?
Select an option or press R to reveal.
Correct: B
Host C11 verifiers prove deterministic layout and arithmetic invariants in workstation RAM; physical bus, clock, and pad readiness require target evidence.
Common misconception: Treating a passing host simulation or unit test as a physical hardware measurement.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Summary
- Cross-compilation separates an
LP64build host (8-byte pointers/longs) from a32-bitILP32freestandingCortex-A7target (4-byte pointers/longs, zero OS loader); lock shared binary structs touint32_t. - Inside the
i.MX6ULLSoC,Boot ROMand128 KiBOCRAM(0x00900000) work immediately at reset, whereas externalDDR3(0x80000000+),CCMclocks, andIOMUXCpads require explicit initialization. UARTserial (115200 8N1console),U-BootTFTP(UDPRAM download), andLinux kernelNFS(VFSmount) test distinct layers with independent failure modes.- Guard
32-bit RAM placement windows by validatingstart >= basebefore comparinglength <= size - (start - base), and distinguish hostC11proofs from target silicon execution.
GL-E01 · 1.1 (m01-l01)
>_ Kernel Systems Academy
# Key takeaways
- A cross compiler runs on the build host and emits instructions for a different execution target.
- Serial console, TFTP file transfer, and NFS filesystem access are distinct paths with separate failure modes.
- The tested arithmetic satisfies the explicit RAM-window fixture.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# ARM Hard-Float EABI, ELF Sections, and Object Inspection
What you'll learn
- Identify ARM machine and floating-point ABI evidence in an ELF object.
- Trace argument, return-value, and preserved-register obligations across an AAPCS call.
- Classify initialized data and zero-initialized storage without confusing file and RAM size.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
- Once a C compiler translates
float gain(float a, float b);into32-bitARMv7-Amachine instructions,…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
- Trace both halves of the
Cortex-A7register contract in Figure 1.2a before reading a line of assembly:
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
- 1.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
Figure 1.2a: AAPCS32 register ownership — integer caller/callee split (left) vs VFPv4 hard-float register passing and its bare-metal CPACR/FPEXC reset precondition (right).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Mental model
note: Two independently machined hydraulic manifolds can share an identical bolt pattern (matching C prototypes) yet route pressure into different ports (r0 vs s0), starving the actuator with zero external compiler warning.
Where it stops working: Unlike mechanical ports, ELF .ARM.attributes let linkers and readelf audit register conventions statically, yet even a perfectly matched hard-float binary will fault at runtime until privileged startup enables the VFP coprocessor in CP15.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# AAPCS32, Hard-Float EABI & ELF32 Section/Segment Roles
definition: AAPCS32 places the first four 32-bit integer/pointer arguments in r0..r3, requires callees to preserve r4..r11 and 8-byte-aligned SP, and under the hard-float variant (.eabi_attribute 28, 1, Tag_ABI_VFP_args: VFP registers) passes eligible floating-point values in s0..s15 / d0..d7. An Executable and Linkable Format (ELF32) object records EM_ARM (40) and .ARM.attributes metadata alongside .text (machine code), .rodata (constants), .data (initialized globals stored in the file), and SHT_NOBITS .bss (zero-initialized globals occupying zero file bytes whose p_memsz - p_filesz RAM extent startup code must explicitly zero).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
- Walk through the four-stage contract from C call site to runtime RAM layout below:
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Why Binary Objects Need a Hardware Calling Convention
Step 1 (C Call Site): Word arguments enter in r0..r3; hard-float variants pass eligible floats in VFPv4 registers s0..s15.
Never trust a .o or .bin filename: inspect ELF32 machine class, VFP ABI attributes, and NOBITS .bss expansion before execution.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Inspecting AAPCS32 Leaf Assembly, VFPv4 Attributes, and ELF Headers
- Why does an
ELFfile have both Section Headers (.text,.rodata,.data,.bss, `.ARM.attribut…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Inspecting AAPCS32 Leaf Assembly, VFPv4 Attributes, and ELF Headers
- Examine the two
Cortex-A7leaf functions intarget.Sbelow.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m01-l02$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .fpu neon-vfpv4 4 │ .eabi_attribute 28, 1 5 │ .arm 6 │ .text 7 │ .global add_words 8 │ .type add_words, %function 9 │ add_words: 10 │ add r0, r0, r1 11 │ bx lr 12 │ .size add_words, .-add_words 13 │ .global add_floats 14 │ .type add_floats, %function───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Auditing 32-Bit ELF Headers and NOBITS Segment Expansion in C11
- Compare the exact byte offsets in Figure 1.2b against
elf32_phdr_audit.cbelow.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Auditing 32-Bit ELF Headers and NOBITS Segment Expansion in C11
Figure 1.2b: Exact Elf32_Ehdr / Elf32_Phdr byte offsets (top) and why runtime p_memsz (216 B) exceeds file-backed p_filesz (152 B) by the 64-byte SHT_NOBITS .bss tail (bottom).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# elf32_phdr_audit.c
learner@ksa:~/gl-e01/m01-l02$ bat elf32_phdr_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: elf32_phdr_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ 7 │ static uint16_t rd_le16(const unsigned char *p) 8 │ { 9 │ return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8)); 10 │ } 11 │ static uint32_t rd_le32(const unsigned char *p) 12 │ { 13 │ return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | 14 │ ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Cross-Assembling for Cortex-A7 and Verifying ELF Metadata
- Run the native
elf32_phdr_auditverifier first, then cross-assembletarget.Swith `clang --target=armv7…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Cross-Assembling for Cortex-A7 and Verifying ELF Metadata
learner@ksa:~/gl-e01/m01-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic elf32_phdr_audit.c -o elf32_phdr_auditlearner@ksa:~/gl-e01/m01-l02$ ./elf32_phdr_auditELF32 EM_ARM=40 ehdr=52B phdr=32B filesz=152 memsz=216 bss=64learner@ksa:~/gl-e01/m01-l02$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m01-l02$ readelf -h -A target.oELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: REL (Relocatable file) Machine: ARMlearner@ksa:~/gl-e01/m01-l02$ GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Cross-Assembling for Cortex-A7 and Verifying ELF Metadata
learner@ksa:~/gl-e01/m01-l02$ strace -e trace=write,exit_group \> ./elf32_phdr_auditwrite(1, "ELF32 EM_ARM=40 ehdr=52B phdr=32"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# File Payload vs Runtime RAM Footprint and Float-ABI Trade-Offs
- Always archive the linked
.elfand linker.mapfile beside anyobjcopy -O binaryoutput!
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# File Payload vs Runtime RAM Footprint and Float-ABI Trade-Offs
- Later: Lesson
m01-l03moves from binary contracts to hardware schematics, deriving active-low CMOS sink c…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Bare-metal C code compiled with arm-linux-gnueabihf-gcc -O2 crashes with an Undefined Instruction exception inside main() even though the C source contains zero float or double variables! Root Cause: With -mfloat-abi=hard and -mfpu=neon-vfpv4 enabled by default on gnueabihf toolchains, the optimizer auto-vectorizes struct copies and memset loops using 64/128-bit vldr/vstr VFP/NEON instructions before _start enables CPACR (CP10/CP11) and FPEXC.EN. Fix: Compile early bare-metal boot/BSP code with -mfloat-abi=soft -mno-unaligned-access (or explicitly enable CP10/CP11 + FPEXC.EN in assembly before calling C).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A custom bootloader reserves p_filesz bytes (152 B) in OCRAM for an ELF32 PT_LOAD segment, and running the loaded firmware immediately corrupts the stack or descriptor placed at p_vaddr + 152. Root Cause: The loader allocated runtime memory from p_filesz instead of p_memsz (216 B), forgetting the 64-byte SHT_NOBITS .bss region that occupies zero file bytes. Fix: Always reserve p_memsz bytes in target RAM, copy p_filesz bytes from p_offset, and zero [p_vaddr + p_filesz, p_vaddr + p_memsz).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Guided Practice: Decoding a Bare-Metal OCRAM Segment Header
- Step 1 (Little-Endian Decode): Given
Elf32_Phdrslicesph[8..11] = {0x00, 0x70, 0x90, 0x00}, `ph[16…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Independent Practice: Multi-Segment ELF32 Overlap & Entry Verifier (elf32_image_check.c)
- Extend
elf32_phdr_audit.cintoelf32_image_check.cacceptinge_entry(Elf32_Ehdr + 24) and an array…
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? Caller control.o places a 32-bit float argument in r0, while callee pid.o reads its first float parameter from s0. What caused this silent numerical failure?
Select an option or press R to reveal.
Correct: C
Identical C prototypes compile to incompatible register assignments (r0 vs s0) when -mfloat-abi=soft and -mfloat-abi=hard objects are mixed.
Common misconception: Assuming matching C function declarations guarantee binary ABI compatibility across .o files.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? Why does adding static uint8_t dma_desc[64]; (uninitialized) increase Elf32_Phdr.p_memsz by 64 bytes while leaving p_filesz unchanged?
Select an option or press R to reveal.
Correct: B
SHT_NOBITS sections carry zero file payload (p_filesz unchanged) while expanding p_memsz so loaders and _start reserve and zero the RAM span.
Common misconception: Equating an ELF segment's file byte count (p_filesz) with its runtime RAM footprint (p_memsz).
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: before transferring an object or executable to an ARMv7-A board, what proves it targets 32-bit ARM with the expected floating-point ABI?
Select an option or press R to reveal.
Correct: A
Only ELF header fields and .ARM.attributes encode verifiable machine architecture and register-passing metadata.
Common misconception: Relying on file extensions or transport success instead of binary header inspection.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Summary
AAPCS32passes the first four32-bit word arguments in caller-savedr0..r3, requires callees to preserver4..r11and8-byte-alignedSP, and returns32-bit scalars inr0.- The
VFPv4hard-float EABI (-mfloat-abi=hard,.eabi_attribute 28, 1) passes floats ins0..s15/d0..d7, but faults on bare-metalCortex-A7reset untilCPACR(CP10/CP11) andFPEXC.ENare enabled. ELF32stores code and constants in.text/.rodataand initialized variables in.data(p_fileszbytes), whileSHT_NOBITS.bssaddsp_memsz - p_fileszzero-initialized RAM bytes with zero file bloat.- Always retain
.elfartifacts alongside stripped.binimages and verifyELFCLASS32,EM_ARM(40), and.ARM.attributeswithreadelf -h -A.
GL-E01 · 1.2 (m01-l02)
>_ Kernel Systems Academy
# Key takeaways
- AAPCS assigns ordinary word-sized arguments to r0–r3 and requires preserved-register obligations across calls.
- The hard-float procedure-call variant can pass eligible floating-point arguments in VFP registers.
- Inspect ELF class, machine metadata, and relevant ABI attributes.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Schematics, Active-Low Circuits, and Register Maps
What you'll learn
- Trace a carrier net through a core connector to its SoC pad.
- Derive active-low output behavior from an LED current path.
- Calculate register addresses and masks without altering sibling pins.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
- Beginners often assume "writing
1to aGPIOpin turns an LED on, and writing0turns it off." On indu…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
- 1.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
Figure 1.3a: Physical CMOS pad stage — why active-low sink circuits conduct I = (V_DD - V_F - V_OL) / R when DR = 0 (left) vs active-high sourcing when DR = 1 (right).
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
- Why do board designers prefer active-low sinking for status LEDs?
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Mental model
note: A schematic net label (LED0) is like a highway route number crossing county lines: the name can change at a border bridge (SOM-to-carrier connector), and the route name tells you connectivity—never which direction current flows or the pad's current limit.
Where it stops working: Unlike road traffic, electrical current requires a closed voltage loop (V_DD > V_F + V_OL), and shifting a signed 32-bit C integer into bit 31 invokes undefined behavior before a single electron moves.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Schematic Net Continuity, Active-Low Sink & Peripheral Offset Geometry
definition: A schematic net label joins electrically connected nodes on a drawing; tracing a signal from a carrier board load into a System-on-Module (SOM) requires following mating connector pin numbers (LED0 -> J1.14 -> P1.14 -> ball GPIO1_IO03), never guessing from text names. In an active-low sink circuit, logical assertion (on = true) drives the output bit to 0 (level_high = (on != active_low)). Each 32-bit MMIO register sits at physical address Base + Offset (GPIO1_DR = 0x0209C000 + 0x00, GPIO1_GDIR = 0x0209C000 + 0x04), where single-pin writes must preserve all 31 sibling bits.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
- Trace the complete four-stage path from external LED load to
32-bit register bitmask below:
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
Never guess polarity or GPIO numbers from net names: trace Load -> Connector Pin -> SoC Ball -> Masked Base+Offset.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Tracing Carrier Nets Across Connectors to Physical GPIO Registers
- Most production
i.MX6ULLhardware splits into two schematics: a compact Core SOM (housing theSoC,…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Tracing Carrier Nets Across Connectors to Physical GPIO Registers
Figure 1.3b: Four-column schematic trace across board-to-board connectors (top) and 32-bit GPIO1 masked update geometry preserving all 31 sibling pins (bottom).
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Tracing Carrier Nets Across Connectors to Physical GPIO Registers
- Once
GPIO1_IO03maps to BankGPIO1(0x0209C000), local bit3, examine howschematic_gpio.ctr…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Tracing Carrier Nets Across Connectors to Physical GPIO Registers
- 1.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# schematic_gpio.c
learner@ksa:~/gl-e01/m01-l03$ bat schematic_gpio.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: schematic_gpio.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdint.h> 2 │ #include <stdbool.h> 3 │ static volatile uint32_t *const gpio1_dr = 4 │ (volatile uint32_t *)(uintptr_t)0x0209c000U; 5 │ bool led_write(unsigned pin, bool on, bool active_low) 6 │ { 7 │ if (pin >= 32U) return false; 8 │ const uint32_t mask = UINT32_C(1) << pin; 9 │ const bool high = on != active_low; 10 │ uint32_t value = *gpio1_dr; /* exclusive bank ownership required */ 11 │ value = high ? value | mask : value & ~mask; 12 │ *gpio1_dr = value; 13 │ return true; 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Verifying KVL Sink Headroom, Polarity XOR, and Shift Safety in C11
- Never dereference
(volatile uint32_t *)0x0209c000Uin a host process (where0x0209C000is an unmapped v…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# sink_drive_audit.c
learner@ksa:~/gl-e01/m01-l03$ bat sink_drive_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: sink_drive_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ 7 │ static bool sink_current_ua(uint32_t vdd_mv, uint32_t vf_mv, uint32_t vol_mv, 8 │ uint32_t r_ohm, uint32_t max_ua, uint32_t *out_ua) 9 │ { 10 │ if (r_ohm == 0U || vdd_mv <= vf_mv + vol_mv) return false; 11 │ uint32_t headroom_mv = vdd_mv - vf_mv - vol_mv; 12 │ uint32_t ua = (headroom_mv * 1000U) / r_ohm; 13 │ if (ua == 0U || ua > max_ua) return false; 14 │ *out_ua = ua;───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Running the Circuit Current and Mask Verifier
- Execute
sink_drive_auditon the workstation and cross-compileschematic_gpio.cinto freestanding `ARMv7…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Running the Circuit Current and Mask Verifier
learner@ksa:~/gl-e01/m01-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic sink_drive_audit.c -o sink_drive_auditlearner@ksa:~/gl-e01/m01-l03$ ./sink_drive_auditsink_ua=1100 gdir=0x0209C004 dr_active_low_on=0xA5A5A5A5learner@ksa:~/gl-e01/m01-l03$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c schematic_gpio.c -o target.olearner@ksa:~/gl-e01/m01-l03$ GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Running the Circuit Current and Mask Verifier
learner@ksa:~/gl-e01/m01-l03$ strace -e trace=write,exit_group \> ./sink_drive_auditwrite(1, "sink_ua=1100 gdir=0x0209C004 dr_"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# End-to-End Signal Provenance and Drive Topology Trade-Offs
- Compare the four drive and register patterns in the matrix below.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# End-to-End Signal Provenance and Drive Topology Trade-Offs
- Later: Module 2 (
m02-l01..m02-l03) dives inside theCortex-A7core itself—processor modes, banked regis…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Searching the core SOM schematic for carrier net name LED0 yields zero matches, leading an engineer to guess GPIO1_IO00 and toggle an unrelated board net. Root Cause: Net names are local to a schematic sheet or hierarchy unless linked by ports; across a SOM-to-carrier header (J1 pin 14 -> P1 pin 14), the same electrical conductor is renamed GPIO1_IO03. Fix: Always trace signals by physical connector pin numbers from load terminal to SoC ball before writing software.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Calling set_pin_level(&dr, 31U, true, false) triggers a signed-overflow sanitizer abort when the mask is written 1 << pin instead of UINT32_C(1) << pin. Root Cause: Integer literal 1 has type signed int, and left-shifting 1 into sign bit 31 overflows INT32_MAX (Undefined Behavior in ISO C11). Fix: Reject pin >= 32U first and form every 32-bit register mask from unsigned UINT32_C(1) << pin.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Guided Practice: Sizing a 1.8 V Rail Indicator & Pin 31 Masking
- Step 1 (1.8 V Headroom): A board revision moves an active-low indicator onto a
1800 mV(1.8 V) bank…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Independent Practice: Worst-Case Tolerance & Netlist Auditor (board_led_spec.c)
- Write a standalone
ISO C11verifierboard_led_spec.cevaluatingstruct led_circuitacross supply tole…
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? An indicator branch runs from 3.3 V through a 1 kOhm resistor to an LED anode, with the LED cathode wired to GPIO1_IO03. Which register state illuminates the LED?
Select an option or press R to reveal.
Correct: B
Current flows from 3.3 V through the resistor and forward-biased LED only when the GPIO cathode is pulled near 0 V (V_OL).
Common misconception: Assuming logical "on" always corresponds to driving an output pin electrically high (1).
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? A helper computes uint32_t mask = 1U << pin; if (pin >= 32U) return false;. Why is this C11 code defective?
Select an option or press R to reveal.
Correct: A
Shifting a 32-bit unsigned integer by >= 32 is Undefined Behavior in C11; the compiler may even optimize away the subsequent if (pin >= 32U) check!
Common misconception: Assuming unsigned modular wraparound applies to bit-shift counts >= 32.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: does computing 0x0209C000U + 0x04U == 0x0209C004U in a host C11 program map GPIO1_GDIR into the workstation process?
Select an option or press R to reveal.
Correct: C
Numeric address arithmetic verifies target register offsets safely as integers; actual MMIO loads/stores execute only on the target SoC (or via kernel ioremap once an OS runs).
Common misconception: Confusing a volatile integer-to-pointer cast with physical bus accessibility in host virtual memory.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Lab: lab_m01_eabi_workbench
- Complete the module studio lab
lab_m01_eabi_workbench: repair theELF32EM_ARMheader inspector, over…
Verify: ./check.sh exits 0.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Summary
- Schematic net labels denote electrical conductors on a sheet; always trace across mating SOM-to-carrier connector pin numbers to identify the exact
SoCball andGPIObank/bit. - Active-low sink circuits (
V_DD -> R -> LED -> GPIO) conductI = (V_DD - V_F - V_OL) / RwhenDRdrives0(level_high = (on != active_low)). - Peripheral registers sit at
Base + Offset(GPIO1_DR = 0x0209C000,GPIO1_GDIR = 0x0209C004); never dereference physicalSoCaddresses inside host user space. - Guard
pin < 32Ubefore evaluatingUINT32_C(1) << pinand use masked read-modify-write under exclusive ownership so all31sibling pins remain intact.
GL-E01 · 1.3 (m01-l03)
>_ Kernel Systems Academy
# Key takeaways
- A schematic net label names electrical connectivity rather than a software GPIO number.
- An active-low LED connected from a supply through resistance to a GPIO conducts when the GPIO sinks current.
- No; it identifies a target address, not a host mapping.
m02/
>_ Kernel Systems Academy
# Cortex-A7 modes, CP15, and ARMv7 assembly
- 2.1 Processor Modes, Register Banks, and CP15 Control
- 2.2 ARM Load/Store Addressing, Shifts, and Conditions
- 2.3 Branches, Full-Descending Stacks, and Calling C
lab → lab_m02_armv7_isa_sim
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Processor Modes, Register Banks, and CP15 Control
What you'll learn
- Classify all nine Cortex-A7 processor modes and their privilege boundaries.
- Trace which register bank an exception handler actually modifies.
- Decode CPSR controls and identify an MRC or MCR access to SCTLR.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
- Ask a fundamental CPU design question: **what happens on the exact clock edge an external Ethernet or timer…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
ARMv7-A(AArch32onCortex-A7) solves both problems simultaneously using **nine architectural process…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
- 1.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
Figure 2.1a: Physical Cortex-A7 register banking across all nine modes — private SP/LR/SPSR protect exception entry, while shared r0..r7 (and r8..r12 outside FIQ) still require software stack saves.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Mental model
note: Switching processor modes on Cortex-A7 is like turning a master key on a control console: the top-bench tools (r0..r7) remain shared in plain sight, while the bottom emergency drawers (SP, LR, SPSR) physically mux in a private compartment for IRQ or SVC without copying a byte.
Where it stops working: Unlike mechanical drawers, unprivileged User mode cannot turn the mode key itself, User and System modes share the exact same drawer with zero SPSR, and changing CP15 system switches requires pipeline synchronization barriers to take effect cleanly.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# CPSR, Saved Program Status (SPSR) & CP15 System Control (SCTLR)
definition: In AArch32, CPSR holds arithmetic flags N, Z, C, V ([31:28]), async abort mask A ([8]), IRQ mask I ([7]), FIQ mask F ([6]), Thumb state T ([5]), and mode M[4:0] ([4:0]). Entering an exception copies CPSR into that mode's SPSR_<mode> (USR and SYS have no SPSR). Architectural caches, MMU, alignment faults, and vector bases live in Coprocessor 15 (CP15) registers—such as SCTLR (c1, c0, 0), accessed at >= PL1 via MRC (read) and MCR (write) bracketed by dsb sy and isb.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
- Step through the four-stage resolution of mode, register bank,
SPSR, andCP15state below:
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Why Silicon Separates Processor Modes and Banked Register Storage
Step 1 (Current State): Decode CPSR M[4:0] and preserve NZCV [31:28] plus I/F/T [7:5] via ~0x1FU masking.
Always resolve active CPSR mode, physical register bank, and I/F masks before touching SP or CP15.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Decoding CPSR Control Lanes and Synchronizing CP15 SCTLR Writes
- Inspect Figure 2.1b to see every bit slice inside
CPSRandCP15SCTLR(p15, 0, Rt, c1, c0, 0).
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Decoding CPSR Control Lanes and Synchronizing CP15 SCTLR Writes
Figure 2.1b: Exact 32-bit bitfields for CPSR (top) and CP15 SCTLR (bottom) with barrier-ordered control updates.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Decoding CPSR Control Lanes and Synchronizing CP15 SCTLR Writes
- Why does
SCTLRuse special coprocessor instructions (mrc/mcr) plusdsb syandisbinstead of a…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m02-l01$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .text 5 │ .global read_sctlr 6 │ read_sctlr: 7 │ mrc p15, 0, r0, c1, c0, 0 8 │ bx lr 9 │ .global enable_alignment_check 10 │ enable_alignment_check: 11 │ mrc p15, 0, r0, c1, c0, 0 12 │ orr r0, r0, #2 13 │ dsb sy 14 │ mcr p15, 0, r0, c1, c0, 0───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Modeling CPSR Mode Validity and Physical Bank Aliasing in C11
- In
cpsr_bank_decoder.c, we turn the architectural tables into an executable verifier.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# cpsr_bank_decoder.c
learner@ksa:~/gl-e01/m02-l01$ bat cpsr_bank_decoder.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: cpsr_bank_decoder.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum { 7 │ MODE_USR = 0x10U, MODE_FIQ = 0x11U, MODE_IRQ = 0x12U, 8 │ MODE_SVC = 0x13U, MODE_MON = 0x16U, MODE_ABT = 0x17U, 9 │ MODE_HYP = 0x1aU, MODE_UND = 0x1bU, MODE_SYS = 0x1fU 10 │ }; 11 │ 12 │ static bool decode_cpsr(uint32_t cpsr, bool *priv, bool *has_spsr, 13 │ bool *irq_m, bool *fiq_m, bool *thumb) 14 │ {───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Running the Mode Decoder and Cross-Assembling CP15 Accessors
- Compile and run
cpsr_bank_decoder.c, then cross-assembletarget.SforCortex-A7.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Running the Mode Decoder and Cross-Assembling CP15 Accessors
learner@ksa:~/gl-e01/m02-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic cpsr_bank_decoder.c -o cpsr_bank_decoderlearner@ksa:~/gl-e01/m02-l01$ ./cpsr_bank_decoderCPSR=0xA00000D3 mode=0x13 I=1 F=1 T=0 SCTLR.A=1learner@ksa:~/gl-e01/m02-l01$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l01$ GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Running the Mode Decoder and Cross-Assembling CP15 Accessors
learner@ksa:~/gl-e01/m02-l01$ strace -e trace=write,exit_group \> ./cpsr_bank_decoderwrite(1, "CPSR=0xA00000D3 mode=0x13 I=1 F="..., 48) = 48exit_group(0) = ?+++ exited with 0 +++GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Hardware Banking vs AAPCS Software Preservation
- Keep hardware mode banking (
CPSR.M[4:0]selecting privateSP/LR) strictly separate from **softwar…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Hardware Banking vs AAPCS Software Preservation
- Later: Lesson
m02-l02examines howSCTLR.VandCP15VBARcompute exception vector addresses alongsi…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Early _start assembly executes msr cpsr_c, #0x13 to enter Supervisor mode, and a pending timer or GPIO interrupt immediately crashes the Cortex-A7 before SP_irq or VBAR is initialized. Root Cause: Writing literal 0x13 (0001_0011_2) into CPSR[7:0] cleared I (bit 7) and F (bit 6) to 0, unmasking IRQ and FIQ prematurely. Fix: Keep mask bits 0xC0 set during startup (0xD3 = I | F | MODE_SVC, or cpsid if, #0x13) until all exception stacks and vectors are ready.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Boot code clears SCTLR.C (bit 2, data cache enable) via mcr p15, 0, r0, c1, c0, 0 without cache maintenance, and global structs modified moments earlier silently revert to old DDR3 values. Root Cause: Clearing SCTLR.C stops cache lookups without writing dirty lines sitting inside L1/L2 data caches out to DDR3, and omitting dsb sy / isb leaves memory and pipeline state unsynchronized. Fix: Clean and invalidate affected data-cache levels first, issue dsb sy, write SCTLR, and execute isb.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Guided Practice: Decoding CPSR 0x80000192 & Multi-Mode SP Setup
- Step 1 (Bitfield Decode): Decode
CPSR = 0x80000192Uinto flags, masks, ISA state, mode, privilege, an…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Independent Practice: IRQ Entry & SPSR Return Simulator (mode_transition_sim.c)
- Write a standalone
ISO C11verifiermode_transition_sim.cmodeling a31-word physicalCortex-A7reg…
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? An IRQ (0x12) assembly handler overwrites r0 without pushing it first. Why does this corrupt the interrupted User (0x10) program upon return?
Select an option or press R to reveal.
Correct: C
Only SP, LR, and SPSR are banked in IRQ mode (FIQ additionally banks r8..r12); r0..r7 are shared across all nine modes.
Common misconception: Assuming banked SP_irq implies a completely banked r0..r15 general-purpose register file.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? Which masked update switches CPSR mode bits M[4:0] held in r0 to Supervisor (0x13) without disturbing NZCV flags or I/F/T control bits?
Select an option or press R to reveal.
Correct: B
Clearing 0x1F first removes old mode bits (such as 0x1F SYS) while preserving NZCV [31:28] and I/F/T [7:5].
Common misconception: Using plain bitwise OR or whole-register overwrite to update a multi-bit CPSR subfield.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: during an ordinary BL subroutine call in Supervisor mode, what protects a caller's value in r4?
Select an option or press R to reveal.
Correct: A
Subroutine calls (BL) do not change processor mode or hardware banks; r4..r11 survive because compiled callees obey AAPCS32.
Common misconception: Confusing software AAPCS32 callee-saved rules with hardware exception register banking.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Summary
Cortex-A7provides nine modes (UseratPL0;FIQ,IRQ,Supervisor,Abort,Undefined,System, and SecureMonitoratPL1;HypatPL2) encoded inCPSR.M[4:0].r0..r7are physically shared across every mode (FIQprivately banksr8..r14, other exception modes bankSPandLR, andSystemsharesUser'sr0..r14).CPSRholds liveNZCVflags,A/I/Fmasks,Tstate, andM[4:0]; exception modes save interruptedCPSRintoSPSR_<mode>, whereasUserandSystemhave noSPSR.- Privileged
CP15registers likeSCTLR(c1, c0, 0) are read viaMRC p15and updated via masked RMW +dsb sy+MCR p15+isb.
GL-E01 · 2.1 (m02-l01)
>_ Kernel Systems Academy
# Key takeaways
- The Cortex-A7 architectural modes are User, FIQ, IRQ, Supervisor, Monitor, Abort, Hyp, Undefined, and System.
- User and System share general-purpose register storage; exception-mode banking does not preserve every general-purpose register.
- The callee saves and restores r4 under the call convention.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# ARM Load/Store Addressing, Shifts, and Conditions
What you'll learn
- Compute pre-indexed and post-indexed effective addresses and writeback values.
- Derive field replacement with BIC and ORR without corrupting adjacent bits.
- Distinguish unsigned carry conditions from signed overflow conditions.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
- Why does
ARMv7-Aforbid CISC-style instructions likeorl $8, 0x0209C000that modify memory in a single…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
- 1.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
Figure 2.2a: Separating accessed Effective Address from base writeback (top) and inline barrel-shifted BIC/ORR field replacement (bottom).
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Mental model
note: Pre-indexed ([r1, #4]!) versus post-indexed ([r1], #4) addressing is like stepping forward on a tiled floor either before or after taking a core sample: your boots stop on 0x1004 either way, yet you sampled two different locations (0x1004 vs 0x1000).
Where it stops working: Unlike floor tiles, ARMv7-A memory accesses also check alignment and MMIO side effects, and comparing 32-bit pointers above 0x80000000 with signed condition codes treats valid DDR3 RAM as negative numbers.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Effective Address,BIC/ORR Field Masking & Unsigned vs Signed CMP Flags
definition: An ARMv7-A load/store computes an Effective Address (EA) separately from base writeback: pre-indexed [Rn, #off]! accesses Rn + off and updates Rn, while post-indexed [Rn], #off accesses Rn then updates Rn <- Rn + off. BIC clears mask bits (Rn & ~mask) ahead of ORR insertion. CMP Rn, Rm computes Rn + ~Rm + 1 and sets CPSR flags without storing a difference: unsigned conditions test carry C == 1 (BHS = no borrow, Rn >= Rm) and C == 0 (BLO, Rn < Rm), whereas signed two's-complement conditions test N == V (BGE) and N != V (BLT).
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
- Trace the four independent computations—base/offset, effective address, shifted mask, and flag interpretati…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
Step 1 (Base & Offset): Separate base pointer Rn from byte offset; VBAR exception bases also require 32-byte alignment.
Track accessed address, final base register, field width mask, and unsigned vs signed flags as four separate facts.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Exception Vector Base Routing and Unsigned vs Signed Flag Divergence
- Why does signed versus unsigned branching bite
i.MX6ULLfirmware engineers on Day 1?
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Exception Vector Base Routing and Unsigned vs Signed Flag Divergence
Figure 2.2b: Exception vector base routing via SCTLR.V and 32-byte-aligned VBAR (left) and why DDR3 addresses (>= 0x80000000) require unsigned BHS/BLO carry conditions rather than signed BGE/BLT (right).
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Exception Vector Base Routing and Unsigned vs Signed Flag Divergence
- Now inspect the left panel of Figure 2.2b (
Exception Vector Base Routing) andreplace_nibblein `ta…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m02-l02$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .text 5 │ .global replace_nibble 6 │ .type replace_nibble, %function 7 │ replace_nibble: 8 │ ldr r2, [r0], #4 9 │ bic r2, r2, #0x00000f00 10 │ and r1, r1, #15 11 │ orr r2, r2, r1, lsl #8 12 │ str r2, [r0, #-4] 13 │ bx lr 14 │ .size replace_nibble, .-replace_nibble───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Auditing Vector Alignment, Pre/Post Indexing, and Nibble Masking in C11
sctlr_vbar_addr_audit.cverifies all four mechanisms in strictISO C11:vector_entry_addr()rejects r…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# sctlr_vbar_addr_audit.c
learner@ksa:~/gl-e01/m02-l02$ bat sctlr_vbar_addr_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: sctlr_vbar_addr_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum { VEC_RESET = 0U, VEC_UNDEF = 1U, VEC_SVC = 2U, VEC_PABT = 3U, 7 │ VEC_DABT = 4U, VEC_IRQ = 6U, VEC_FIQ = 7U }; 8 │ 9 │ static bool vector_entry_addr(uint32_t sctlr, uint32_t vbar, 10 │ unsigned slot, uint32_t *addr_out) 11 │ { 12 │ if (slot > 7U || slot == 5U) return false; 13 │ bool high_vecs = ((sctlr >> 13) & 1U) != 0U; 14 │ if (!high_vecs && (vbar & 0x1fU) != 0U) return false;───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Executing the Addressing and Vector Verifier
- Build and run
sctlr_vbar_addr_audit.con the workstation and cross-assembletarget.SforCortex-A7.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Executing the Addressing and Vector Verifier
learner@ksa:~/gl-e01/m02-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic sctlr_vbar_addr_audit.c -o sctlr_vbar_addr_auditlearner@ksa:~/gl-e01/m02-l02$ ./sctlr_vbar_addr_auditIRQ_vec=0x87800018 hi_vec=0xFFFF0018 post=0x1000 pre=0x1004 nib=0xA5A5F2FFlearner@ksa:~/gl-e01/m02-l02$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l02$ GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Executing the Addressing and Vector Verifier
learner@ksa:~/gl-e01/m02-l02$ strace -e trace=write,exit_group \> ./sctlr_vbar_addr_auditwrite(1, "IRQ_vec=0x87800018 hi_vec=0xFFFF"..., 75) = 75exit_group(0) = ?+++ exited with 0 +++GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Comparing ARMv7-A Addressing Modes and Condition Suffixes
- Review the side-by-side summary table below before writing startup copy/zero loops in Module 5.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Comparing ARMv7-A Addressing Modes and Condition Suffixes
- Later: Lesson
m02-l03combines load/store writeback with control flow—building8-byte-aligned full-desc…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A .bss zeroing loop in DDR3 at 0x87800000 compares cmp r0, r1 and branches with signed blt (or bge), either aborting after 0 iterations or overrunning RAM when comparing against lower regions. Root Cause: Any 32-bit address >= 0x80000000 has sign bit 31 == 1 (negative in two's-complement!), inverting signed BLT/BGE/BGT/BLE predicates. Fix: Always compare memory addresses, sizes, and cycle counters with unsigned condition codes (BLO for <, BHS for >=, BHI for >, BLS for <=).
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Bare-metal startup writes 0x87800000 to CP15 VBAR (mcr p15, 0, r0, c12, c0, 0), yet the first IRQ jumps to 0xFFFF0018 instead of 0x87800018. Root Cause: Either SCTLR.V (bit 13) remained 1 from the Boot ROM environment (forcing high vectors at 0xFFFF0000), or .vectors lacked .balign 32 (VBAR[4:0] == 0). Fix: Align .vectors to 32 bytes, clear SCTLR bit 13 (bic r0, r0, #(1 << 13)), write VBAR, and execute isb.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Guided Practice: Scaled Barrel-Shift Indexing & CMP Flag Trace
- Step 1 (Scaled Register Offset): Given
r0 = 0x020C4068(CCM_CCGR0) andr1 = 3, computeEAand f…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Independent Practice: Exact AArch32 ALU Subtraction Flag Simulator (cmp_flags_audit.c)
- Write a standalone
ISO C11verifiercmp_flags_audit.cimplementing `void arm_cmp32(uint32_t a, uint32_t…
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? Starting from r1 = 0x1000, both ldr r0, [r1, #4]! and ldr r0, [r1], #4 leave r1 == 0x1004. What distinguishes their memory behavior?
Select an option or press R to reveal.
Correct: B
Pre-indexing adds the offset before accessing memory (0x1004), whereas post-indexing accesses r1 (0x1000) first and updates r1 afterward.
Common misconception: Treating identical final pointer values (0x1004) as proof that both instructions accessed the same address.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? In replace_nibble, why execute and r1, r1, #15 before orr r2, r2, r1, lsl #8 even after bic r2, r2, #0x0f00 cleared bits [11:8]?
Select an option or press R to reveal.
Correct: A
BIC clears only destination bits [11:8]; clamping r1 to 4 bits prevents caller bits [23:4] from spilling into [31:12] during ORR.
Common misconception: Assuming LSL #8 automatically truncates a wider source value to fit a 4-bit field.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: after cmp r0, r1 with r0 = 0xFFFFFFFF and r1 = 0x00000001, why does bhi (unsigned >) branch while blt (signed <) also branches on the exact same CPSR flags?
Select an option or press R to reveal.
Correct: C
Hardware computes one set of NZCV flags; the branch condition suffix chooses whether to interpret carry (C) for unsigned order or N vs V for signed order.
Common misconception: Attributing signedness to raw 32-bit register storage rather than to the condition code consuming NZCV.
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Summary
ARMv7-AseparatesALU/barrel-shifter register operations fromLDR/STRmemory transfers, and separates accessed Effective Address (EA) from base writeback.- Pre-indexed
[Rn, #off]!accessesRn + offand writesRn + offback; post-indexed[Rn], #offaccesses originalRnfirst and writesRn + offback afterward. - Replace multi-bit subfields by clearing the field mask with
BIC, clamping the new value's bit-width withAND, and inserting via shiftedORR. - After
CMP, unsigned comparisons test carry (BHSC==1,BLOC==0—mandatory forDDR3addresses>= 0x80000000!), whereas signed comparisons testN == V(BGE) andN != V(BLT).
GL-E01 · 2.2 (m02-l02)
>_ Kernel Systems Academy
# Key takeaways
- ARM load/store instructions compute an effective address separately from arithmetic on the transferred value.
- Pre-indexed writeback updates the base using the offset before the access; post-indexing accesses the original base then updates it.
- The conditions interpret carry and signed flags differently.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Branches, Full-Descending Stacks, and Calling C
What you'll learn
- Trace B, BL, and BX without confusing subroutine and exception returns.
- Construct an eight-byte-aligned full-descending frame around a nested call.
- Verify saved-register order and restore the caller-visible state.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
- On
x86_64, executingcall helperautomatically decrements%rspand writes an8-byte return address…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
- How does
ARMv7-Aorganize that stack in RAM, and why can pushing{lr}alone (4bytes) crash a C program?
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
- 1.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
Figure 2.3a: Full-descending stack frame layout and 16-bit register bitmask ordering (left) vs why public C calls require 8-byte SP alignment (right).
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Mental model
note: Holding a return address in LR is like keeping a finger on page 104 while reading a footnote (leaf call): before jumping from that footnote to a second index table (nested BL), you must tuck an 8-byte bookmark pair ({r4, lr}) onto the stack.
Where it stops working: Unlike paper bookmarks, STMFD orders registers strictly by hardware register number rather than assembly text order, public C calls mandate 8-byte SP alignment, and hardware exception returns (subs pc, lr, #4) must never be used to return from BL subroutines.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# B / BL / BX Control Transfer, Full-Descending Stack & 8-Byte AAPCS32 Frame
definition: In ARMv7-A, B jumps without touching LR; BL writes the subroutine return address into LR before branching; and BX Rm branches to Rm & ~1U while setting CPSR.T = Rm[0] (1 = Thumb, 0 = ARM interworking). STMFD sp!, {reglist} (STMDB) allocates 4 * k bytes below SP and stores registers in ascending register-number order (r0..r15) from lowest to highest address; LDMFD sp!, {..., pc} (LDMIA) pops the frame and returns. Every public AAPCS32 call site must satisfy SP mod 8 == 0.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
- Step through the four phases of a non-leaf assembly-to-C call frame below:
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.
Every non-leaf assembly routine calling C must save outer LR and keep SP 8-byte aligned across all exit paths.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Tracing Nested Calls and Separating Subroutine vs Exception Returns
- Follow the exact register and stack values across
sum_then_doublein Figure 2.3b andtarget.Sbelow…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Tracing Nested Calls and Separating Subroutine vs Exception Returns
- Look at Panel 2 of Figure 2.3b: never confuse
bx lrwithsubs pc, lr, #4! HardwareIRQexcept…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Tracing Nested Calls and Separating Subroutine vs Exception Returns
Figure 2.3b: Return-address lifetime across nested BL calls (top) and why BX LR / LDMFD subroutine returns differ fundamentally from subs pc, lr, #4 exception returns (bottom).
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m02-l03$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .text 5 │ .global sum_then_double 6 │ .type sum_then_double, %function 7 │ sum_then_double: 8 │ stmfd sp!, {r4, lr} 9 │ bl add_words 10 │ lsl r0, r0, #1 11 │ ldmfd sp!, {r4, pc} 12 │ .size sum_then_double, .-sum_then_double 13 │ .type add_words, %function 14 │ add_words:───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Proving AAPCS32 Stack Alignment and Callee Preservation in C11
aapcs32_frame_verifier.csimulates the16-wordARMv7-Aregister file and a16-word full-descending…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# aapcs32_frame_verifier.c
learner@ksa:~/gl-e01/m02-l03$ bat aapcs32_frame_verifier.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: aapcs32_frame_verifier.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ struct aapcs_ctx { 7 │ uint32_t r[16]; /* r13 = SP word index, r14 = LR, r15 = PC */ 8 │ uint32_t stack[16]; 9 │ }; 10 │ 11 │ static bool push_pair_fd(struct aapcs_ctx *c, unsigned reg_lo, unsigned reg_hi) 12 │ { 13 │ if (reg_lo >= reg_hi || c->r[13] < 2U || ((c->r[13] * 4U) & 7U) != 0U) 14 │ return false;───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Running the Frame Verifier and Checking Target Encodings
- Compile and run
aapcs32_frame_verifier.c, then cross-assembletarget.S.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Running the Frame Verifier and Checking Target Encodings
learner@ksa:~/gl-e01/m02-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic aapcs32_frame_verifier.c -o aapcs32_frame_verifierlearner@ksa:~/gl-e01/m02-l03$ ./aapcs32_frame_verifierAAPCS32 frame=8B sp_word=8 r0=32 r4=0x40000004 ret_pc=0x87800104learner@ksa:~/gl-e01/m02-l03$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l03$ GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Running the Frame Verifier and Checking Target Encodings
learner@ksa:~/gl-e01/m02-l03$ strace -e trace=write,exit_group \> ./aapcs32_frame_verifierwrite(1, "AAPCS32 frame=8B sp_word=8 r0=32"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Control-Transfer Matrix and Balanced Exit Paths
- Audit every early-return branch in hand-written assembly: if an error path jumps to
bx lrafter `stmfd sp…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Control-Transfer Matrix and Balanced Exit Paths
- Later: Module 3 (
m03-l01..m03-l03) appliesBIC,ORR,DSB SY, andAAPCS32-callable assembly routin…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: An assembly startup stub pushes {lr} (4 bytes) from an 8-byte-aligned stack and calls a C diagnostic function using uint64_t or LDRD, triggering an Alignment Data Abort or printing garbled 64-bit numbers. Root Cause: Subtracting 4 bytes left SP mod 8 == 4 at a public AAPCS32 C interface where the compiler assumes SP mod 8 == 0. Fix: Push an even number of registers (stmfd sp!, {r4, lr}) so SP moves in multiples of 8 bytes.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A leaf assembly function called via bl delay_ticks ends with subs pc, lr, #4 instead of bx lr, hanging in an infinite loop re-executing bl delay_ticks (or trapping). Root Cause: subs pc, lr, #4 is the hardware IRQ exception return (restoring SPSR and subtracting the +4 pipeline bias), whereas bl stores the exact return address in lr. Fix: Return from BL subroutines exclusively via bx lr (leaf) or ldmfd sp!, {..., pc} (non-leaf).
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Guided Practice: Five-Argument Stack Passing & Register-List Ordering
- Step 1 (5th Argument Frame): To call `uint32_t pack5(uint32_t a, uint32_t b, uint32_t c, uint32_t d, ui…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Independent Practice: General 16-Bit Bitmask STMFD/LDMFD Verifier (stmfd_abi_audit.c)
- Extend
aapcs32_frame_verifier.cintostmfd_abi_audit.cimplementingexec_stmfd()andexec_ldmfd()f…
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? Non-leaf function outer_fn is entered via BL and immediately executes bl inner_fn without saving LR. What happens when outer_fn later executes bx lr?
Select an option or press R to reveal.
Correct: A
Cortex-A7 has a single LR in the current mode; bl inner_fn overwrites LR with the return address inside outer_fn.
Common misconception: Treating LR as a multi-entry hardware return stack rather than a single 32-bit register.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? With SP = 0x87820000 (8-byte aligned), an assembly wrapper executes stmfd sp!, {lr} (4 bytes) and calls a C function. How must this prologue be fixed?
Select an option or press R to reveal.
Correct: C
AAPCS32 mandates 8-byte stack alignment at public interfaces; pushing two 32-bit registers (8 bytes) preserves alignment cleanly.
Common misconception: Assuming 4-byte word alignment suffices at public ARMv7-A C call boundaries.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: when stmfd sp!, {lr, r4} executes at SP = 0x1000, which word lands at the lower address 0x0FF8?
Select an option or press R to reveal.
Correct: B
STMFD (STMDB) decrements SP to 0x0FF8 first and stores set bitmask registers in ascending numerical order (r4 at 0x0FF8, r14 at 0x0FFC).
Common misconception: Believing assembly text order inside {...} controls memory layout in STMFD/LDMFD.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Lab: lab_m02_armv7_isa_sim
- Complete the module studio lab
lab_m02_armv7_isa_sim: repairCPSRmode-field preservation, width-bounde…
Verify: ./check.sh exits 0.
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Summary
Bjumps without touchingLR,BLrecords the subroutine return address inLR(clobbering any unsavedLR), andBX Rmbranches while selecting ARM/Thumb state fromRm[0].STMFD sp!, {...}(STMDB) grows a full-descending stack downward and stores registers strictly in ascending register-number order (r0..r15), placing the lowest register at the lowest address.AAPCS32requires8-byte stack alignment (SP mod 8 == 0) at every public call site and requires callees to preserver4..r11andSP.- Never use
subs pc, lr, #4(anIRQexception return) to return from an ordinaryBLsubroutine; usebx lr(leaf) orldmfd sp!, {..., pc}(non-leaf).
GL-E01 · 2.3 (m02-l03)
>_ Kernel Systems Academy
# Key takeaways
- B branches without creating a subroutine return address, while BL records a return address in LR.
- BX branches to a register target and uses the architectural instruction-state convention encoded in that target.
- At the lower address of the newly allocated two-word frame.
m03/
>_ Kernel Systems Academy
# IOMUXC muxing, pad electrical policy, and GPIO MMIO
- 3.1 CCM Clock Gates, Pad Mux Modes, and SION
- 3.2 Pad Electrical Fields: Pulls, Drive, Slew, and Open-Drain
- 3.3 GPIO DR, GDIR, PSR, Interrupt Status, and Assembly LED Control
lab → lab_m03_iomuxc_gpio_mmio
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# CCM Clock Gates, Pad Mux Modes, and SION
What you'll learn
- Locate CCGR0–CCGR6 fields without enabling every peripheral.
- Derive a legal pad mux value from the selected pad's function table.
- Explain what SION forces and what it does not connect.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
- Why can't you just write
*gpio1_dr = 0immediately after reset and watchGPIO1_IO03pull low?
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
- 1.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
Figure 3.1a: End-to-end silicon signal graph — CCM clock gate (CG13), peripheral block, IOMUXC MUX_MODE + SION loopback, and SELECT_INPUT daisy routing.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Mental model
note: Driving a package ball requires both powering the pump (CCM_CCGR clock gate) and turning the manifold selector (IOMUXC MUX_MODE): running an unrouted peripheral or routing an unclocked peripheral leaves the external pin dead.
Where it stops working: Unlike plumbing valves, reading or writing a clock-gated peripheral register can stall or fault on the internal IPG bus immediately, and forcing SION=1 only activates that ball's input buffer rather than wiring arbitrary peripherals together.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# CCM Clock Gates (CCGR0..6), IOMUXC MUX_MODE, SION & SELECT_INPUT
definition: CCM_CCGR0..CCGR6 (0x020C4068..0x020C4080) divide each 32-bit word into 16 two-bit CGk fields (bits [2k+1 : 2k]; GPIO1 is CCGR1 CG13 at [27:26]). Per-ball IOMUXC_SW_MUX_CTL_PAD_* (0x020E0068 for GPIO1_IO03) selects one of that pad's implemented functions in MUX_MODE[3:0] (ALT5 = 5 for GPIO1_IO03) and provides SION (bit 4, 0x10), which forces that ball's input receiver path active even when an output function drives the pin. When multiple balls can feed one peripheral input (UART_RX, I2C_SDA), a separate *_SELECT_INPUT (DAISY) register selects which ball reaches the receiver.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
- Step through the four hardware dependencies in order before writing register code:
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
Step 1 (CCM Policy): Update only CCGR1[27:26] = 0b11 (mask 0x0C000000) and issue DSB SY before touching GPIO1.
Enable the peripheral clock first, then select a pad-supported ALT mode, SION policy, and SELECT_INPUT daisy source.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# What SION and Daisy-Chain Input Muxes Physically Connect
- Demystify two
IOMUXCfeatures that trip up experienced engineers—both drawn in Figure 3.1a and bit-ma…
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# What SION and Daisy-Chain Input Muxes Physically Connect
Figure 3.1b: Exact 32-bit bitfields for CCM_CCGR1 (top) and IOMUXC_SW_MUX_CTL_PAD_GPIO1_IO03 + SELECT_INPUT (bottom).
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# What SION and Daisy-Chain Input Muxes Physically Connect
- Trace
gpio1_clock_and_muxintarget.Sbelow: first it updatesCCM_CCGR1(0x020C406C) bits[27:26]…
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m03-l01$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .text 5 │ .global gpio1_clock_and_mux 6 │ gpio1_clock_and_mux: 7 │ ldr r0, =0x020c406c 8 │ ldr r1, [r0] 9 │ bic r1, r1, #(3 << 26) 10 │ orr r1, r1, #(3 << 26) 11 │ str r1, [r0] 12 │ dsb sy 13 │ ldr r0, =0x020e0068 14 │ ldr r1, [r0]───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Validating CCGR Slots, Per-Ball ALT Tables, and Daisy Bounds in C11
- In
iomuxc_mux_daisy_audit.c, notice how we validate hardware capability, not just bit width!
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# iomuxc_mux_daisy_audit.c
learner@ksa:~/gl-e01/m03-l01$ bat iomuxc_mux_daisy_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: iomuxc_mux_daisy_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ static bool ccgr_set_gate(uint32_t *ccgr, unsigned index, unsigned mode) 7 │ { 8 │ if (index >= 16U || mode > 3U || mode == 2U) return false; 9 │ uint32_t shift = index * 2U, mask = UINT32_C(3) << shift; 10 │ *ccgr = (*ccgr & ~mask) | ((uint32_t)mode << shift); 11 │ return true; 12 │ } 13 │ 14 │ static bool iomuxc_set_mux(uint32_t *mux_ctl, unsigned alt, bool sion,───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Running the Clock-Gate and Pinmux Verifier
- Compile and run
iomuxc_mux_daisy_audit.con the workstation and cross-assembletarget.Sintotarget.o.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Running the Clock-Gate and Pinmux Verifier
learner@ksa:~/gl-e01/m03-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic iomuxc_mux_daisy_audit.c -o iomuxc_mux_daisy_auditlearner@ksa:~/gl-e01/m03-l01$ ./iomuxc_mux_daisy_auditCCGR1_CG13=0x0C000000 MUX_ALT5_SION=0x15 MUX_ALT5=0x05 DAISY=1learner@ksa:~/gl-e01/m03-l01$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m03-l01$ GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Running the Clock-Gate and Pinmux Verifier
learner@ksa:~/gl-e01/m03-l01$ strace -e trace=write,exit_group \> ./iomuxc_mux_daisy_auditwrite(1, "CCGR1_CG13=0x0C000000 MUX_ALT5_S"..., 63) = 63exit_group(0) = ?+++ exited with 0 +++GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Clock-Gate and Pin-Routing Policy Matrix
- Compare narrow field updates against blanket register writes below.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Clock-Gate and Pin-Routing Policy Matrix
- Later: Lesson
m03-l02opens the electrical pad cell right behindSW_MUX_CTL—decoding Schmitt hysteresis…
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: UART1 or I2C1 transmits clean waveforms on an oscilloscope, yet its receive FIFO stays completely empty even though SW_MUX_CTL_PAD_* selected the documented ALT mode and RX pulses arrive at the SoC ball. Root Cause: Multiple package balls can supply that RX line, and the peripheral's IOMUXC_*_SELECT_INPUT (DAISY) register still points at a different default pad. Fix: Always check whether an input signal has a SELECT_INPUT register and program its DAISY index alongside SW_MUX_CTL_PAD_*.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Firmware writes GPIO1_DR and GPIO1_GDIR before enabling CCM_CCGR1[27:26], triggering a synchronous external Data Abort or leaving GPIO1 latches stuck at reset values. Root Cause: Without IPG clock edges (CG13 == 0b00), the peripheral's bus slave logic cannot complete or latch register transactions. Fix: Enable the peripheral's CCM_CCGRx CG field and execute dsb sy before reading or writing any register inside that peripheral.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Guided Practice: Deriving GPIO5 Clock Gates & SION Masks
- Step 1 (CCGR1 CG15): Given
CCM_CCGR0at0x020C4068, verifyCCM_CCGR1is0x020C406Cand compute…
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Independent Practice: Board Pinmux & Daisy-Chain Conflict Linter (pinmux_table_audit.c)
- Write a standalone
ISO C11verifierpinmux_table_audit.cauditing an array ofstruct pin_cfgboard en…
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? CCM_CCGR1[27:26] is 0b11 and GPIO1_DR / GPIO1_GDIR toggle bit 3 in debugger readbacks, yet ball GPIO1_IO03 still outputs I2C1 activity instead of GPIO. What is missing?
Select an option or press R to reveal.
Correct: B
Clock gating (CCM) and pad multiplexing (IOMUXC) are independent; GPIO1 can update its internal latch while the ball mux routes ALT0 (I2C1).
Common misconception: Assuming an enabled GPIO bank clock and toggling DR latch automatically route GPIO to the physical ball.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? Why must iomuxc_set_mux() reject ALT8 (8) on GPIO1_IO03 even though MUX_MODE[3:0] is 4 bits wide (0..15)?
Select an option or press R to reveal.
Correct: A
A 4-bit register field's numeric range (0..15) is wider than the physical silicon mux inputs wired to a specific ball.
Common misconception: Treating bitfield width (<= 15) as proof that hardware implements that ALT function on the chosen pad.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: what does setting SION (bit 4 = 1) in IOMUXC_SW_MUX_CTL_PAD_* physically accomplish?
Select an option or press R to reveal.
Correct: C
SION overrides only the pad's input-enable gate; CCM clocks, SELECT_INPUT daisy muxes, and GPIO direction remain independent.
Common misconception: Mistaking SION input-buffer override for an arbitrary internal peripheral loopback switch.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Summary
CCM_CCGR0..CCGR6(0x020C4068..0x020C4080) gate peripheral clocks using16two-bitCGfields per word (00off,01RUN,11RUN+WAIT); enable the clock +dsb sybefore accessing peripheral MMIO.- Peripheral clocking (
CCM) and ball signal routing (IOMUXC_SW_MUX_CTL_PAD_*) are independent hardware requirements. MUX_MODE[3:0]must select anALTfunction actually implemented on that exact SoC ball (ALT5forGPIO1_IO03).SION(bit 4) forces the pad's input receiver active for pin loopback/monitoring, while*_SELECT_INPUT(DAISY) chooses which ball drives a multi-pad peripheral RX input.
GL-E01 · 3.1 (m03-l01)
>_ Kernel Systems Academy
# Key takeaways
- The i.MX6ULL CCM exposes CCGR0 through CCGR6 for peripheral clock-gating policy.
- A peripheral's clock-gate field and its pad mux route are independent configuration requirements.
- It forces the selected pad input path on, not arbitrary wiring.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Pad Electrical Fields: Pulls, Drive, Slew, and Open-Drain
What you'll learn
- Decode HYS, PUS, PUE, PKE, ODE, SPEED, DSE, and SRE fields.
- Diagnose why selecting PUS alone does not necessarily enable a pull resistor.
- Choose a conservative pad policy and state which electrical claims still require measurement.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
- Open almost any vendor BSP file and you will spot magic constants like
*pad_ctl = 0x10B0;with a misleadi…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
- 1.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
Figure 3.2a: Inside an i.MX6ULL CMOS pad cell — output DSE slices and ODE open-drain release (left), PKE -> PUE -> PUS keeper vs pull hierarchy (center), and HYS Schmitt receiver (right).
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Mental model
note: If SW_MUX_CTL routes which peripheral track reaches the station, SW_PAD_CTL configures the electrical overhead wire (PKE/PUE/PUS), regenerative holding brake (Keeper), locomotive traction motors (DSE), and throttle ramp (SRE).
Where it stops working: Unlike rail switches, setting pull-strength bits (PUS) has zero physical effect when the mode switch (PUE) selects bus-keeper mode or the master breaker (PKE) is open, and actual signal rise times depend on external trace capacitance and pull-up resistors.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# IOMUXC SW_PAD_CTL Electrical Policy Bitfields
definition: In standard i.MX6ULL IOMUXC_SW_PAD_CTL_PAD_* registers (0x020E02F4 for GPIO1_IO03, active field mask 0x0001F8F9U), HYS[16] enables Schmitt input hysteresis; PKE[12] powers the bias cell; PUE[13] selects resistive pull (1) over bus keeper (0); PUS[15:14] selects 100K down (0), 47K up (1), 100K up (2), or 22K up (3) only when PKE=1 and PUE=1; ODE[11] enables open-drain output; and SPEED[7:6], DSE[5:3] (0=Hi-Z, 1..7 = R0/1..R0/7), and SRE[0] govern output impedance and edge slew.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
- Step through the four-stage electrical design checklist below:
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
Step 1 (Input Path): Enable HYS[16] = 1 for Schmitt noise immunity on slow digital edges (still debounce switches in software!).
Decode PKE -> PUE -> PUS and DSE != 0 explicitly instead of copying opaque hex constants.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Decoding 32-Bit SW_PAD_CTL Words and Preserving Reserved Gaps
- Inspect Figure 3.2b to compare the exact
32-bit bitfield layout (0x0001F8F9Uactive mask, leaving `…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Decoding 32-Bit SW_PAD_CTL Words and Preserving Reserved Gaps
Figure 3.2b: Exact 32-bit SW_PAD_CTL bitfields under mask 0x0001F8F9 (top) and three verified electrical profiles (bottom).
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# pad_policy.c
learner@ksa:~/gl-e01/m03-l02$ bat pad_policy.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: pad_policy.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdint.h> 2 │ static volatile uint32_t *const pad_gpio1_io03 = 3 │ (volatile uint32_t *)(uintptr_t)0x020e02f4U; 4 │ void configure_input_pullup(void) 5 │ { 6 │ const uint32_t mask = 0x0001f8f9U; 7 │ const uint32_t policy = (1U << 16) | (2U << 14) | 8 │ (1U << 13) | (1U << 12); 9 │ uint32_t old = *pad_gpio1_io03; 10 │ *pad_gpio1_io03 = (old & ~mask) | (policy & mask); 11 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Encoding and Auditing Hierarchical Pad Policies in C11
iomuxc_pad_ctl_builder.cencodes all eight fields with range checks (pus <= 3,speed <= 3,dse <= 7…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# iomuxc_pad_ctl_builder.c
learner@ksa:~/gl-e01/m03-l02$ bat iomuxc_pad_ctl_builder.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: iomuxc_pad_ctl_builder.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum bias_kind { BIAS_DISABLED = 0, BIAS_KEEPER = 1, BIAS_PULL = 2 }; 7 │ 8 │ struct pad_cfg { 9 │ bool hys, pue, pke, ode, sre; 10 │ unsigned pus, speed, dse; 11 │ }; 12 │ 13 │ static bool build_pad_ctl(const struct pad_cfg *c, uint32_t *word_out) 14 │ {───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Running the Pad-Control Builder and Cross-Compiling Target Policy
- Execute
iomuxc_pad_ctl_builderon the workstation and cross-compilepad_policy.cfor freestanding `Cort…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Running the Pad-Control Builder and Cross-Compiling Target Policy
learner@ksa:~/gl-e01/m03-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic iomuxc_pad_ctl_builder.c -o iomuxc_pad_ctl_builderlearner@ksa:~/gl-e01/m03-l02$ ./iomuxc_pad_ctl_builder0x10B0=keeper(DSE=6,SPD=2) pullup=0x1B000 od_i2c=0x1B8B0learner@ksa:~/gl-e01/m03-l02$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c pad_policy.c -o target.olearner@ksa:~/gl-e01/m03-l02$ GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Running the Pad-Control Builder and Cross-Compiling Target Policy
learner@ksa:~/gl-e01/m03-l02$ strace -e trace=write,exit_group \> ./iomuxc_pad_ctl_builderwrite(1, "0x10B0=keeper(DSE=6,SPD=2) pullu"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Pad Electrical Role Comparison Matrix
- Match every board trace to the electrical profile its external circuit requires:
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Pad Electrical Role Comparison Matrix
- Later: Lesson
m03-l03completes theGPIOchain inside0x0209C000—preload-safeDR/GDIRsequencing,…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A push-button pin configured with (2U << 14) | (1U << 12) (PUS = 100K_UP, PKE = 1, forgetting PUE = 1U << 13) reads 0 permanently after the very first button press to ground. Root Cause: With PUE == 0, the bias cell operates as a bus keeper that latches whichever logic level last appeared on the wire (0 after ground contact) instead of pulling back to 3.3 V. Fix: Set both PKE (bit 12) and PUE (bit 13) whenever PUS (bits 15:14) must act as a pull-up or pull-down resistor.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: CCM_CCGR1, MUX_MODE = ALT5, GPIO1_GDIR = (1U << 3), and GPIO1_DR are all configured, yet the physical output pin stays completely high-impedance (0 mA drive). Root Cause: SW_PAD_CTL was left at 0x0001B000 (an input policy with DSE[5:3] == 0), disconnecting all seven output transistor fingers (Hi-Z). Fix: Program a non-zero DSE drive strength (such as DSE = 6, 6U << 3) on every push-pull or open-drain output pad.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Guided Practice: Decoding 0x000178B1 & Encoding Custom Output Pads
- Step 1 (Decode): Decode
0x000178B1Ufield by field (HYS=1,PUS=147Kpull-up,PUE=1,PKE=1,…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Independent Practice: Pad-Role Consistency Linter (pad_role_lint.c)
- Write a standalone
ISO C11verifierpad_role_lint.cimplementing `int audit_pad_policy(uint32_t mux_ctl…
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? In SW_PAD_CTL, PUS[15:14] = 2 (100K_UP), PKE[12] = 1, and PUE[13] = 0. Which electrical bias circuit is actually connected to the ball?
Select an option or press R to reveal.
Correct: A
PKE = 1 enables the bias cell, and PUE = 0 routes the keeper latch instead of the PUS resistor bank.
Common misconception: Reading PUS[15:14] without checking both PKE (bit 12) and PUE (bit 13).
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? When ODE (bit 11) is 1 (open-drain enabled), what happens electrically at the ball when software writes logical 1 to the output latch?
Select an option or press R to reveal.
Correct: C
Open-drain actively sinks 0 via NMOS and releases (Hi-Z) on 1, relying on a pull-up network (tau = R * C) to establish a high level.
Common misconception: Assuming logical 1 always actively sources current from V_DD even in open-drain mode.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: does writing 0x0001B000 (HYS=1, 100K pull-up) to SW_PAD_CTL_PAD_GPIO1_IO03 (0x020E02F4) route ball GPIO1_IO03 to the GPIO1 controller?
Select an option or press R to reveal.
Correct: B
IOMUXC separates signal routing (SW_MUX_CTL) from electrical pad characteristics (SW_PAD_CTL) in distinct registers.
Common misconception: Confusing pad electrical configuration (SW_PAD_CTL) with alternate-function pin multiplexing (SW_MUX_CTL).
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Summary
- Standard
i.MX6ULLSW_PAD_CTLwords packHYS[16],PUS[15:14],PUE[13],PKE[12],ODE[11],SPEED[7:6],DSE[5:3], andSRE[0]inside mask0x0001F8F9U. PKE(bit 12) powers the bias block, andPUE(bit 13) chooses resistive pull (1, usingPUS) versus bus keeper (0, ignoringPUS).ODE(bit 11 = 1) releases high-sidePMOSdrive on logical1;DSE[5:3]sets output impedance (R0/1..R0/7, with0 = Hi-Zdisabled!).0x000010B0enables bus keeper (PKE=1, PUE=0) withDSE=6andSPEED=2—not an active100 kOhmpull-down.
GL-E01 · 3.2 (m03-l02)
>_ Kernel Systems Academy
# Key takeaways
- For the general pad-control example, HYS is bit 16, PUS is bits 15:14, PUE is bit 13, and PKE is bit 12.
- PKE enables the pull/keeper function, while PUE selects pull operation rather than keeper operation.
- No; the mux route remains a separate configuration choice.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# GPIO DR, GDIR, PSR, Interrupt Status, and Assembly LED Control
What you'll learn
- Distinguish DR output state, GDIR direction, and PSR pad sampling.
- Derive ICR1 and ICR2 fields from a bank-local GPIO index.
- Acknowledge one W1C interrupt bit without clearing sibling events.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
- Why does an
i.MX6ULLGPIOcontroller (GPIO1at0x0209C000) expose both a Data Register (DR,…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
- 1.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
Figure 3.3a: Inside GPIO1 @ 0x0209C000 — separating DR request, GDIR tri-state enable, PSR wire sampling, and the ICR -> ISR (W1C) -> IMR interrupt pipeline.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Mental model
note: Operating a GPIO bank is like running a manifold with a setpoint dial (DR), an actuator clutch (GDIR), a live line-pressure gauge (PSR), and push-to-reset fault lamps (W1C ISR): set the dial safe before engaging the clutch, and push only the single fault lamp you just serviced.
Where it stops working: Unlike mechanical gauges, reading PSR while driving an output may require SION=1 on some mux paths, and GPIO interrupts still require GICv2 distributor routing and CPSR.I=0 before vectoring the Cortex-A7 CPU.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# GPIO Bank Register Map, Half-Bank ICR & Write-One-to-Clear (W1C)
definition: Each 32-pin i.MX6ULL GPIO bank (GPIO1 0x0209C000 .. GPIO5 0x020AC000) exposes DR (+0x00), GDIR (+0x04), read-only PSR (+0x08), ICR1 (+0x0C, pins 0..15), ICR2 (+0x10, pins 16..31), IMR (+0x14), ISR (+0x18), and EDGE_SEL (+0x1C). Pin p's 2-bit trigger field sits in ICR1 (p < 16) or ICR2 (p >= 16) at shift 2 * (p % 16). GPIOx_ISR uses W1C acknowledgment: software writes (UINT32_C(1) << p) directly (0 loads!) so sibling pending bits survive.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
- Step through all four
GPIOregister roles in the interactive sequence below:
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
Step 1 (Output Latch): Preload inactive high DR[3] = 1 (+0x00) + DSB SY before enabling output direction.
Match every GPIO operation to its exact register contract: preload DR -> enable GDIR -> sample PSR -> direct-mask W1C ISR.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Half-Bank ICR Shifts, W1C Assembly Stores, and Active-Low LED Routines
- Compare the two register traps in Figure 3.3b against our
Cortex-A7assembly listingtarget.Sbelow…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Half-Bank ICR Shifts, W1C Assembly Stores, and Active-Low LED Routines
Figure 3.3b: ICR1 / ICR2 half-bank bit-pair split (top) and why direct W1C mask stores preserve concurrent sibling interrupts that RMW wipes out (bottom).
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m03-l03$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .text 5 │ .global led_prepare_inactive 6 │ led_prepare_inactive: 7 │ ldr r0, =0x0209c000 8 │ ldr r1, [r0] 9 │ orr r1, r1, #8 10 │ str r1, [r0] 11 │ dsb sy 12 │ ldr r1, [r0, #4] 13 │ orr r1, r1, #8 14 │ str r1, [r0, #4]───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Simulating GPIO Bank Registers and W1C Race Loss in C11
gpio_w1c_bank_sim.cmodels all seven coreGPIOregisters in a deterministicC11harness: it verifies…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# gpio_w1c_bank_sim.c
learner@ksa:~/gl-e01/m03-l03$ bat gpio_w1c_bank_sim.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: gpio_w1c_bank_sim.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ struct gpio_bank_sim { 7 │ uint32_t dr, gdir, psr, icr1, icr2, imr, isr; 8 │ }; 9 │ 10 │ static bool gpio_cfg_icr(struct gpio_bank_sim *b, unsigned pin, unsigned trig) 11 │ { 12 │ if (pin >= 32U || trig > 3U) return false; 13 │ uint32_t *icr = (pin < 16U) ? &b->icr1 : &b->icr2; 14 │ unsigned shift = (pin % 16U) * 2U;───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Executing the GPIO Bank Simulator and Assembly Check
- Build and run
gpio_w1c_bank_simon the host and cross-assembletarget.SforCortex-A7.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Executing the GPIO Bank Simulator and Assembly Check
learner@ksa:~/gl-e01/m03-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic gpio_w1c_bank_sim.c -o gpio_w1c_bank_simlearner@ksa:~/gl-e01/m03-l03$ ./gpio_w1c_bank_simDR=0x08 PSR=0x00 ICR1_15=3 ICR2_16=2 W1C_rem=0x02 RMW_rem=0x00learner@ksa:~/gl-e01/m03-l03$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m03-l03$ GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Executing the GPIO Bank Simulator and Assembly Check
learner@ksa:~/gl-e01/m03-l03$ strace -e trace=write,exit_group \> ./gpio_w1c_bank_simwrite(1, "DR=0x08 PSR=0x00 ICR1_15=3 ICR2_"..., 63) = 63exit_group(0) = ?+++ exited with 0 +++GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# GPIO Register Access Semantics Comparison
- Never hide
DRandISRbehind one genericset_bit(addr, mask)macro—their hardware write contracts are…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# GPIO Register Access Semantics Comparison
- Later: Module 4 (
m04-l01..m04-l03) shows how thei.MX6ULLinternalBoot ROMactually loads your assem…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: When two safety switches on GPIO1_IO18 and GPIO1_IO19 trip microseconds apart, firmware services IO18 and completely misses IO19. Root Cause: The ISR acknowledged IO18 with GPIO1->ISR |= (1U << 18);, reading 0x000C0000 (bits 18 and 19 both 1) and writing 0x000C0000 back to the W1C port—clearing both pending events! Fix: Acknowledge W1C status flags exclusively with a direct mask assignment: GPIO1->ISR = (UINT32_C(1) << 18);.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Configuring falling-edge detection on GPIO1_IO18 (pin = 18) via GPIO1->ICR1 |= (3U << (2 * pin)) triggers C11 Undefined Behavior or corrupts ICR1 while leaving IO18 on low-level sensitivity. Root Cause: 2 * 18 = 36 overflows 32-bit ICR1 (pins 0..15) instead of indexing ICR2 (+0x10, pins 16..31) at shift (18 % 16) * 2 = 4. Fix: Select ICR1 vs ICR2 with pin < 16U and compute local shift as (pin % 16U) * 2U.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Guided Practice: Configuring GPIO1_IO18 (UART1_CTS_B Button) Interrupts
- Step 1 (ICR2 Address & Mask): For
GPIO1(0x0209C000) pin18, compute theICRphysical address,…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Independent Practice: Full 8-Register GPIO Edge & Dispatch Simulator (gpio_edge_sim.c)
- Extend
gpio_w1c_bank_sim.cintogpio_edge_sim.caddingedge_sel(+0x1C) and `gpio_apply_pad_transit…
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? GPIO1_ISR (+0x18, W1C) currently reads 0x0A (bits 3 and 1 pending), and your handler has serviced only pin 3. What value must software write to GPIO1_ISR?
Select an option or press R to reveal.
Correct: C
In W1C hardware (ISR_next = ISR_curr & ~W_val), writing 0 is a no-op and writing 1 clears that bit; 0x08 clears bit 3 and preserves 0x02 (whereas writing 0x02 would clear bit 1 and leave bit 3!).
Common misconception: Applying ordinary read-modify-write (|= or &= ~) expressions to a Write-One-to-Clear (W1C) status register.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? Where does GPIO1 pin 16's two-bit interrupt trigger configuration live?
Select an option or press R to reveal.
Correct: B
ICR1 covers pins 0..15 (shift = 2 * pin), and ICR2 covers pins 16..31 starting at shift = 2 * (16 - 16) = 0.
Common misconception: Using the bank-wide pin number (16) directly as a shift offset inside ICR2 without subtracting 16.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: why can GPIO1_DR bit 3 read 1 while GPIO1_PSR bit 3 simultaneously reads 0?
Select an option or press R to reveal.
Correct: A
DR (requested latch) and PSR (observed pad state) tap opposite sides of the output buffer and pad mux.
Common misconception: Treating a readback of GPIOx_DR as proof of the physical voltage present on the board trace.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Lab: lab_m03_iomuxc_gpio_mmio
- Complete the module studio lab
lab_m03_iomuxc_gpio_mmio: repair isolatedCCM_CCGRandIOMUXCfield re…
Verify: ./check.sh exits 0.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Summary
GPIOx_DR(+0x00) holds the output latch,GPIOx_GDIR(+0x04) enables output direction (1= out,0= in), and read-onlyGPIOx_PSR(+0x08) samples physical pad state; preloadDRinactive before settingGDIRon active-low loads.GPIOx_ICR1(+0x0C) configures2-bit triggers for pins0..15andGPIOx_ICR2(+0x10) configures pins16..31at local shift2 * (pin % 16).GPIOx_IMR(+0x14) masks interrupt propagation whileGPIOx_ISR(+0x18) latches trigger events.GPIOx_ISRis Write-One-to-Clear (W1C): write(UINT32_C(1) << pin)directly with zero RMW so sibling pending interrupts are never wiped out.
GL-E01 · 3.3 (m03-l03)
>_ Kernel Systems Academy
# Key takeaways
- GPIO DR is the data register, GDIR selects direction, and PSR reports pad state.
- ICR1 configures pins 0–15 and ICR2 configures pins 16–31 using two-bit trigger fields.
- The latch request and sampled electrical pad are different views.
m04/
>_ Kernel Systems Academy
# Boot ROM selection, IVT geometry, and DCD command streams
- 4.1 Boot Straps, eFUSE Selection, and Internal OCRAM
- 4.2 IVT, Boot Data, and SD/eMMC Offset Geometry
- 4.3 DCD Commands and a Checked C11 .imx Packer
lab → lab_m04_ivt_dcd_image
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Boot Straps, eFUSE Selection, and Internal OCRAM
What you'll learn
- Decode all BOOT_MODE values without treating a reserved value as a recovery mode.
- Distinguish strap-selected media policy from fuse-selected policy.
- Place pre-DDR work in an explicitly reserved OCRAM region rather than uninitialized external RAM.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
- When power stabilizes on an
i.MX6ULLboard and the external power-on-reset pin (POR_B) rises from0 V…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
- As Figure 4.1a illustrates, the
i.MX6ULLSystem Reset Controller (SRC,0x020D8000) wires26…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
- 1.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
Figure 4.1a: POR_B rising-edge strap capture circuit (top) and the four BMOD[1:0] Boot ROM selection paths governed by BT_FUSE_SEL (bottom).
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Mental model
note: Reset-time boot selection works like an automated rail-yard switch tower that photographs a train's routing placard at the exact instant it crosses the entry sensor (POR_B): repainting the placard down the track (IOMUXC reuse or live DIP flips) never reroutes the train already on the spur.
Where it stops working: Unlike a mechanical rail placard, Boot ROM routing is also governed by permanent silicon eFUSE bits and active ROM workspace reservations inside OCRAM that remain live until handoff completes.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# System Reset Controller Boot Mode Registers (SRC_SBMR1/2) & Internal OCRAM
definition: At POR_B deassertion, SRC_SBMR2 (0x020D801C) latches BMOD[1:0] in bits [25:24] (00 Boot From Fuses, 01 Serial Downloader SDP, 10 Internal Boot, 11 Reserved) and reflects eFUSE override state in BT_FUSE_SEL (bit 4), while SRC_SBMR1 (0x020D8004) latches BOOT_CFG1..4 strap bytes (LCD_DATA00..23). Note that Internal Boot (10) means ROM-directed boot flow (fetching from external SD, eMMC, NAND, or QSPI), not that the image is stored inside the SoC! Before external DDR3 is trained, internal On-Chip RAM (OCRAM) provides 128 KiB of static SRAM at [0x00900000, 0x00920000)—with low bytes reserved by the active Boot ROM itself.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
- Step through the four-stage reset-to-handoff pipeline below to connect pad sampling, policy selection, and…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# What Happens Electrically on Reset Before Any User Instruction Exists
Step 1: At POR_B rising edge, SRC latches BOOT_MODE[1:0] and LCD_DATA00..23 into read-only SBMR2 and SBMR1.
Separate reset-latched boot policy and ROM-reserved low OCRAM from post-boot GPIO/LCD pin behavior.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Decoding SRC_SBMR1/2 Bitfields & Partitioning 128 KiB Internal OCRAM
- Inspect Figure 4.1b to map the exact
32-bit register slices and physical SRAM boundaries used during…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Decoding SRC_SBMR1/2 Bitfields & Partitioning 128 KiB Internal OCRAM
- Look equally closely at panel
3of Figure 4.1b.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Decoding SRC_SBMR1/2 Bitfields & Partitioning 128 KiB Internal OCRAM
Figure 4.1b: Exact 32-bit bitfields of SRC_SBMR2 and SRC_SBMR1 alongside the 28 KiB ROM-reserved vs 100 KiB usable OCRAM split.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Decoding SRC_SBMR1/2 Bitfields & Partitioning 128 KiB Internal OCRAM
- In
boot_policy.cbelow, our freestandingARMv7-Ahelper inspectsSRC_SBMR2strictly through a `volati…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# boot_policy.c
learner@ksa:~/gl-e01/m04-l01$ bat boot_policy.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: boot_policy.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdint.h> 2 │ static volatile const uint32_t *const src_sbmr2 = 3 │ (volatile const uint32_t *)(uintptr_t)0x020d801cU; 4 │ unsigned sampled_boot_mode(void) 5 │ { 6 │ return (*src_sbmr2 >> 24) & 3U; 7 │ } 8 │ unsigned fuse_policy_selected(void) 9 │ { 10 │ return (*src_sbmr2 >> 4) & 1U; 11 │ } 12 │ /* Read-only inspection: no fuse programming and no boot-media writes. */───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Proving SBMR1/SBMR2 Policy Decoding & Overflow-Safe OCRAM Bounds in C11
- Before touching target hardware,
sbmr_boot_decoder.cproves the complete Boot ROM decision tree and `OCRA…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# sbmr_boot_decoder.c
learner@ksa:~/gl-e01/m04-l01$ bat sbmr_boot_decoder.c───────┬──────────────────────────────────────────────────────────────────────────────────────── │ File: sbmr_boot_decoder.c───────┼──────────────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum boot_path { BP_FUSE, BP_USB_SERIAL, BP_INT_STRAPS, BP_INT_FUSE, BP_RESERVED }; 7 │ enum boot_dev { DEV_NONE, DEV_NOR_EIM, DEV_QSPI, DEV_SD_ESD, DEV_MMC_EMMC, DEV_NAND }; 8 │ 9 │ static enum boot_path decode_sbmr2(uint32_t sbmr2) 10 │ { 11 │ unsigned bmod = (sbmr2 >> 24) & 3U; 12 │ bool bt_fuse_sel = ((sbmr2 >> 4) & 1U) != 0U; 13 │ switch (bmod) { 14 │ case 0U: return BP_FUSE;───────┴────────────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Running the Host Policy Verifier & Freestanding Cortex-A7 Object Check
- Compile and execute
sbmr_boot_decoder.con the workstation, then cross-compileboot_policy.cwith `clan…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Running the Host Policy Verifier & Freestanding Cortex-A7 Object Check
learner@ksa:~/gl-e01/m04-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic sbmr_boot_decoder.c -o sbmr_boot_decoderlearner@ksa:~/gl-e01/m04-l01$ ./sbmr_boot_decoderSBMR2=0x02000000->INT_STRAPS SBMR1=0x40->SD_ESD OCRAM_free=100KiBlearner@ksa:~/gl-e01/m04-l01$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c boot_policy.c -o target.olearner@ksa:~/gl-e01/m04-l01$ GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Running the Host Policy Verifier & Freestanding Cortex-A7 Object Check
learner@ksa:~/gl-e01/m04-l01$ strace -e trace=write,exit_group \> ./sbmr_boot_decoderwrite(1, "SBMR2=0x02000000->INT_STRAPS SBM"..., 66) = 66exit_group(0) = ?+++ exited with 0 +++GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Separating Bench Symptoms Across Reset Edges, USB SDP & Image Headers
- Keeping the reset-edge capture model in mind resolves three bench mysteries that routinely stall bring-up t…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A custom carrier attaches an external 1 kOhm pull-up or active sensor output to LCD_DATA05 or LCD_DATA06, and cold power-on stops booting from SD even though BOOT_MODE[1:0] switches still select 10 (Internal Boot). Root Cause: LCD_DATA00..23 double as BOOT_CFG1/2/4 inputs sampled on the rising edge of POR_B; the 1 kOhm external load overpowered the weak 47 kOhm board strap resistor during reset, latching eMMC or NAND into SRC_SBMR1. Fix: Isolate or tri-state external drivers on LCD_DATA pins until POR_B completes, and read back SRC_SBMR1 (0x020D8004) over SDP or JTAG to confirm latched strap bits.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Linking an early pre-DDR diagnostic image directly at 0x00900000 (the base of physical OCRAM) causes USB SDP download or SD boot handoff to crash before reaching _start. Root Cause: Physical validity ([0x00900000, 0x00920000)) is not allocation ownership: the Boot ROM itself uses [0x00900000, 0x00907000) (28 KiB) for its live execution stack, MMU/cache descriptors, and SDP state during transfer. Fix: Place pre-DDR SPL images and stacks strictly inside the unreserved 100 KiB window [0x00907000, 0x00920000).
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Guided Practice: Decoding SBMR1/SBMR2 & Sizing an OCRAM Stack
- Solve each bring-up check step by step.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Independent Practice: USDHC Port & Bus-Width Strap Auditor
- Extend
sbmr_boot_decoder.cintoboot_cfg_audit.cdecodingBOOT_CFG2(SBMR1[15:8]) alongside `BOOT_C…
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? SRC_SBMR2 reports BMOD[1:0] == 2 (10_2, Internal Boot) and BT_FUSE_SEL == 1 (bit 4). How does the i.MX6ULL Boot ROM choose the boot medium?
Select an option or press R to reveal.
Correct: A
Internal Boot (BMOD = 10) names the internal Boot ROM state machine, and BT_FUSE_SEL == 1 directs that state machine to read media configuration from eFUSEs instead of BOOT_CFG straps.
Common misconception: Confusing the phrase "Internal Boot" with internal image storage, or forgetting BT_FUSE_SEL precedence.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? An engineer flips the BOOT_MODE DIP switch from SD (10) to Serial Downloader (01) while the board remains powered, yet a software warm routine still sees the old boot mode in SRC_SBMR2. What is the root cause?
Select an option or press R to reveal.
Correct: C
SRC_SBMR1 and SRC_SBMR2 hold reset-sampled latch outputs; a full POR_B reset is required to capture the new switch level.
Common misconception: Treating reset-sampled boot straps as continuously polled GPIO inputs.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: why does ocram_user_fits(0x00900000U, 0x1000U) reject address 0x00900000 even though physical OCRAM spans [0x00900000, 0x00920000)?
Select an option or press R to reveal.
Correct: B
A valid physical SRAM address is not free memory while the Boot ROM is actively executing out of its reserved low-OCRAM workspace.
Common misconception: Equating physical memory-map presence with unreserved allocation ownership during boot handoff.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Summary
BOOT_MODE[1:0](SRC_SBMR2[25:24]) selects00Fuse Boot,01USB/UART Serial Downloader (SDPrecovery),10ROM-directed Internal Boot, or11Reserved (invalid).- Under
Internal Boot(10),BT_FUSE_SEL(SBMR2[4]) chooses between reset-sampledBOOT_CFGpin straps (SRC_SBMR1) and permanent eFUSE configuration. - Strap pads (
BOOT_MODEandLCD_DATA00..23) are latched on the rising edge ofPOR_B; post-reset peripheral pin reuse cannot alterSBMR1/SBMR2, whereas external loads during reset can corrupt media selection. - Internal
128 KiBOCRAM([0x00900000, 0x00920000)) operates immediately before externalDDR3initialization, with[0x00907000, 0x00920000)(100 KiB) available above the Boot ROM's own workspace.
GL-E01 · 4.1 (m04-l01)
>_ Kernel Systems Academy
# Key takeaways
- BOOT_MODE values 00, 01, 10, and 11 select fuse boot, serial downloader, internal boot, and a reserved encoding respectively.
- Internal boot media policy can depend on sampled BOOT_CFG inputs or fuse-selected configuration.
- No; ROM or handoff state may reserve part of that window.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# IVT, Boot Data, and SD/eMMC Offset Geometry
What you'll learn
- Decode the D1 00 20 40 IVT bytes without confusing mixed byte-order fields.
- Translate SD/eMMC media offset 0x400 into compact-file and runtime coordinates.
- Validate IVT self, entry, and Boot Data pointers against a stated image layout.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
- When
arm-none-eabi-objcopy -O binary bsp.elf bsp.binstrips anELFexecutable down to rawARMv7-Amac…
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
- Instead, on
SD/eMMCmedia, thei.MX6ULLBoot ROM seeks1 KiB(1024 B = 0x0400, **two512-byte sec…
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
- 1.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
Figure 4.2a: Exact alignment between SD/eMMC media offsets (M), compact .imx file offsets (F = M - 0x400), and runtime RAM addresses (R = start + M).
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mental model
note: Packing a bootable .imx container is like loading a pre-assembled equipment skid (F) onto bay 2 (M = 0x0400, LBA 2) of a flatbed railcar bound for a numbered factory floor (R = 0x877FF000 + M): bay position on the railcar, byte offset inside the skid, and floor coordinates at the destination are linked by exact arithmetic, never interchangeable zeros.
Where it stops working: Unlike physical cargo labels, the i.MX6ULL Boot ROM mixes big-endian 16-bit header lengths with little-endian 32-bit ARM runtime pointers inside the very same 32-byte table.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Image Vector Table (IVT) & Boot Data Structure
definition: The i.MX6ULL Image Vector Table (IVT) is a 32-byte structure at SD/eMMC media offset 0x0400 (LBA 2). Its 4-byte header D1 00 20 40 encodes tag 0xD1, big-endian 16-bit byte length 0x0020 (32), and version 0x40—which appears as 0x402000D1 when read as one 32-bit little-endian ARM word! Seven little-endian 32-bit pointers follow: entry (+0x04), reserved1 = 0 (+0x08), dcd (+0x0C), boot_data (+0x10), self (+0x14), csf = 0 (+0x18), and reserved2 = 0 (+0x1C). Immediately following (at self + 0x20), the 12-byte Boot Data record specifies little-endian start, length, and plugin (0 for normal boot images).
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
- Walk through the four-step coordinate conversion and pointer audit below before writing serializer code:
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
Step 1: Anchor SD/eMMC media coordinates at M_ivt = 0x0400 (LBA 2, sparing MBR) and M_payload = 0x1000 (LBA 8).
Name the coordinate origin (media M, compact file F, or runtime RAM R) on every variable before adding or comparing offsets.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mixed-Endian Header Bytes vs Little-Endian Runtime Pointers
- Study Figure 4.2b carefully to avoid a classic endianness trap.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mixed-Endian Header Bytes vs Little-Endian Runtime Pointers
Figure 4.2b: Byte-accurate anatomy of the 32-byte IVT and 12-byte Boot Data — big-endian 16-bit header length paired with little-endian 32-bit runtime pointers.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Mixed-Endian Header Bytes vs Little-Endian Runtime Pointers
- In
target.Sbelow,.section .ivt, "a"emitsimage_ivt(32 B) andimage_boot_data(12 B) using l…
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m04-l02$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .section .ivt, "a" 5 │ .global image_ivt 6 │ image_ivt: 7 │ .byte 0xd1, 0x00, 0x20, 0x40 8 │ .word _start 9 │ .word 0 10 │ .word image_dcd 11 │ .word image_boot_data 12 │ .word image_ivt 13 │ .word 0 14 │ .word 0───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Serializing & Auditing 44-Byte IVT + Boot Data Coordinates in ISO C11
- Never overlay a packed C
structdirectly onto disk bytes when fields mix endianness.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# ivt_serializer_audit.c
learner@ksa:~/gl-e01/m04-l02$ bat ivt_serializer_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: ivt_serializer_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ static void put_le32(unsigned char *p, uint32_t v) 9 │ { 10 │ for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * i)); 11 │ } 12 │ static uint32_t get_le32(const unsigned char *p) 13 │ { 14 │ return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Mixed-Endian Serialization & ARMv7-A Relocation Assembly
- Build and run
ivt_serializer_auditon the host, then assembletarget.Swith `clang --target=armv7a-none…
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Mixed-Endian Serialization & ARMv7-A Relocation Assembly
learner@ksa:~/gl-e01/m04-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic ivt_serializer_audit.c -o ivt_serializer_auditlearner@ksa:~/gl-e01/m04-l02$ ./ivt_serializer_auditIVT_word=0x402000D1 self=0x877FF400 bdata=0x877FF420 entry=0x87800000 LBA=2learner@ksa:~/gl-e01/m04-l02$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m04-l02$ GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Verifying Mixed-Endian Serialization & ARMv7-A Relocation Assembly
learner@ksa:~/gl-e01/m04-l02$ strace -e trace=write,exit_group \> ./ivt_serializer_auditwrite(1, "IVT_word=0x402000D1 self=0x877FF"..., 76) = 76exit_group(0) = ?+++ exited with 0 +++GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Why ENTRY(_start) Never Populates IVT.entry Automatically
- Connect what you just proved back to
ELFlinking from Modulem01.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Flashing firmware.imx onto a removable SD card with dd if=firmware.imx of=/dev/sdX bs=512 (forgetting seek=2) wipes the card's FAT/ext4 partition table while the board fails silently into USB Serial Downloader. Root Cause: Without seek=2 (1024 B), byte 0 of the compact .imx (0xD1) overwrites LBA 0 (MBR at 0x0000) instead of landing at 0x0400 (LBA 2), leaving payload padding at 0x0400 where the ROM checks for 0xD1. Fix: Always flash compact SD/eMMC .imx images with bs=512 seek=2 conv=fsync onto a verified removable block device.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A small 4 KiB blinky boots fine from SD, but after growing the firmware to 48 KiB, execution crashes randomly inside functions linked near the end of .text. Root Cause: BootData.length (+0x24) was left hardcoded to 0x4000 (16 KiB) instead of updating to 0x1000 + payload_bytes, so the Boot ROM stopped reading SD sectors partway through .text and left upper code words holding uninitialized DDR3 garbage. Fix: Compute BootData.length programmatically from the final binary byte count (0x1000 + payload_size) and assert entry + payload_size <= start + length.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Guided Practice: Relocating an IVT Container Into Pre-DDR OCRAM
- Re-derive all runtime pointers for an
SD-bootedSPLexecuting insideOCRAMwithoutDCD.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Independent Practice: Multi-Media IVT Validator (SD/eMMC vs QSPI)
- Extend
ivt_serializer_audit.cintoivt_media_check.cparameterized bymedia_ivt(0x0400for `SD/eMM…
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? A compact .imx image begins directly with its IVT and will be written to SD/eMMC media offset 0x0400 (LBA 2). Where must a payload linked for media offset 0x1000 sit inside that compact .imx file?
Select an option or press R to reveal.
Correct: C
Because byte 0x0000 of the compact .imx lands at media offset 0x0400, media offset 0x1000 maps to compact file offset 0x1000 - 0x0400 = 0x0C00 (3072 B).
Common misconception: Treating media sector offsets and compact-file byte offsets as a single coordinate system.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? What do the four IVT header bytes D1 00 20 40 encode, and how do those exact same four bytes appear as one 32-bit little-endian ARM word?
Select an option or press R to reveal.
Correct: B
In memory order p[0..3] = {0xD1, 0x00, 0x20, 0x40}, p[1..2] form big-endian 0x0020 = 32, while a little-endian uint32_t load places p[3] in bits [31:24] (0x402000D1).
Common misconception: Applying ARM little-endian word order blindly to the IVT's big-endian 16-bit length field.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: what value must IVT.self (+0x14) hold in our worked 0x87800000 SD layout (BootData.start = 0x877FF000)?
Select an option or press R to reveal.
Correct: A
Every pointer field inside the IVT (entry, dcd, boot_data, self, csf) is a runtime memory address in the target address space, never a host file offset or sector count.
Common misconception: Writing compact-file offset 0 into the IVT.self runtime pointer field.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Summary
IVTheader bytesD1 00 20 40encode tag0xD1, big-endian16-bit length32(0x0020), and version0x40, which read as0x402000D1in a32-bit little-endian ARM word.- On
SD/eMMCmedia, placing theIVTat media offset0x0400(1 KiB,LBA 2across512-byte sectors) preservesLBA 0..1partitioning structures. - Translating any media offset
M >= 0x0400into a compact.imxfile yieldsF = M - 0x0400(0x1000 -> 0x0C00), while runtime addresses followR = BootData.start + M = IVT.self + F. IVTpointers (entry,dcd,boot_data,self) andBoot Data(start,length,plugin) serialize as little-endian32-bit words with reserved fields strictly zero.
GL-E01 · 4.2 (m04-l02)
>_ Kernel Systems Academy
# Key takeaways
- The IVT header bytes D1 00 20 40 encode tag D1, a big-endian length of 32, and version 40.
- Those four bytes appear as 0x402000D1 when interpreted as one little-endian 32-bit word.
- The IVT runtime address, not its compact-file offset.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# DCD Commands and a Checked C11 .imx Packer
What you'll learn
- Encode big-endian DCD lengths, addresses, values, and masks.
- Reject truncated or zero-length Write, Check, and NOP commands.
- Construct a compact .imx artifact with independently checked IVT and payload offsets.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
- Think through what happens on cold power-up when
IVT.entrypoints to0x87800000in externalDDR3RAM.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
- Examine Figure 4.3a to see how
DCDbytecode is framed—and why naive.imxpackers break on their ver…
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
- 1.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
Figure 4.3a: Inside the 36-byte big-endian DCD stream (top), why put_le32() triggers silent ROM rejection (bottom left), and parser termination invariants (bottom right).
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Mental model
note: A DCD table is a pre-flight punch-card deck fed into the Boot ROM before the main engine (_start) starts: every card carries its own byte length and big-endian register coordinates, so one zero-length card or swapped endian helper derails every operation behind it.
Where it stops working: Unlike syntax-checking a punch card offline, proving that a DCD stream parses cleanly never proves that its register values match your PCB's DDR3 trace delays or voltage rails.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Device Configuration Data (DCD) & Structural vs Electrical Validation
definition: Device Configuration Data (DCD) is a bounded (<= 1768 B) big-endian Boot ROM command table (tag 0xD2, version 0x40) placed between Boot Data (0x002C in compact .imx) and the application payload (0x0C00), containing validated Write Data (0xCC), Check Data (0xCF), and NOP (0xC0) subcommands. Structural validity proves byte framing, big-endian encoding, and non-overlapping container offsets—it never proves that DDR3 timing or pad constants match an unmeasured physical board.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
- Trace the four-stage encoding, validation, and
.imxpacking pipeline below:
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Solving the Cold-Boot Chicken-and-Egg Problem with DCD
Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.
Keep LE32 IVT pointers and BE16/BE32 DCD commands strictly separated, and never equate valid framing with calibrated DDR3 timing.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Linker Coordinates, Container Packing & Pre-Boot Trade-Offs
- Inspect Figure 4.3b alongside
image_layout.ldsbelow to see how linker addresses and.imxfile offs…
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Linker Coordinates, Container Packing & Pre-Boot Trade-Offs
Figure 4.3b: Exact byte map of verified.imx (3088 B) and the engineering boundary between structural container proof and board DDR3 calibration.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# image_layout.lds
learner@ksa:~/gl-e01/m04-l03$ bat image_layout.lds───────┬──────────────────────────────────────────────────────────────────────────────── │ File: image_layout.lds───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ ENTRY(_start) 2 │ SECTIONS 3 │ { 4 │ image_load_base = 0x877ff000; 5 │ . = image_load_base + 0x400; 6 │ .ivt : { KEEP(*(.ivt)) } 7 │ .dcd : { KEEP(*(.dcd)) } 8 │ . = 0x87800000; 9 │ .text : { KEEP(*(.text.start)) *(.text*) } 10 │ .rodata ALIGN(4) : { *(.rodata*) } 11 │ .data ALIGN(4) : { *(.data*) } 12 │ image_load_end = .; 13 │ .bss (NOLOAD) : { *(.bss*) *(COMMON) } 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Implementing a Bounded DCD Validator & .imx Packer in ISO C11
- Study
valid_dcd()andmain()indcd_encoder_packer.cbelow.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# dcd_encoder_packer.c
learner@ksa:~/gl-e01/m04-l03$ bat dcd_encoder_packer.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: dcd_encoder_packer.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ static void put_be16(unsigned char *p, uint16_t v) 9 │ { 10 │ p[0] = (unsigned char)(v >> 8); p[1] = (unsigned char)(v & 0xffU); 11 │ } 12 │ static uint16_t get_be16(const unsigned char *p) 13 │ { 14 │ return (uint16_t)(((uint16_t)p[0] << 8) | p[1]);───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Generating verified.imx & Inspecting the Syscall Write Trace
- Compile and run
dcd_encoder_packerbelow.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Generating verified.imx & Inspecting the Syscall Write Trace
learner@ksa:~/gl-e01/m04-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic dcd_encoder_packer.c -o dcd_encoder_packerlearner@ksa:~/gl-e01/m04-l03$ ./dcd_encoder_packerverified.imx=3088B DCD=36B write_addr=02_0C_40_6C cmds=3learner@ksa:~/gl-e01/m04-l03$ GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Generating verified.imx & Inspecting the Syscall Write Trace
learner@ksa:~/gl-e01/m04-l03$ strace -e trace=write,exit_group \> ./dcd_encoder_packerwrite(3, "\321\0 @\0\0\200\207\0\0\0\0,\364\177\207 \364\177\207\0\364\177\207\0\0\0\0\0\0\0\0"..., 3088) = 3088write(1, "verified.imx=3088B DCD=36B write"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Coalescing Multi-Pair DCD Writes & Bridging to C Runtime Startup
- Notice how byte budgeting works when a real
MMDCDDR3init script needs~65register writes: emitting…
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Reusing put_le32() from IVT serialization to write 0x020C406C into a DCD Write Data (0xCC) command causes the i.MX6ULL Boot ROM to reject the image and enter USB Serial Downloader with zero UART output. Root Cause: Little-endian bytes 6C 40 0C 02 are parsed by the big-endian DCD interpreter as physical address 0x6C400C02, which falls outside the Boot ROM's allowed DCD address windows (MMDC, IOMUXC, CCM). Fix: Always serialize IVT/Boot Data pointers with put_le32() and every DCD length, address, value, mask, and count with put_be16()/put_be32().
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Expanding a DCD register list pushes total_dcd_len past 1768 B (or past 0x0C00 - 0x002C), causing silent ROM rejection or corrupting the first instructions of _start. Root Cause: Emitting uncoalesced 12-byte 0xCC commands without asserting total <= 1768U and 0x2C + total <= payload_offset overflows the Boot ROM's fixed DCD buffer limit. Fix: Coalesce adjacent 0xCC pairs (4 + 8 * k bytes) and fail the host packer build whenever total > 1768U or 0x2C + total > payload_offset.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Guided Practice: Encoding a Coalesced 2-Pair Set-Mask DCD Command
- Compute the exact hex framing by hand.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Independent Practice: Whitelist-Aware Coalescing DCD Compiler
- Extend
dcd_encoder_packer.cintodcd_range_compiler.cthat validates every targetaddragainst allowe…
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? While scanning a DCD buffer, valid_dcd() encounters a subcommand whose big-endian length field equals 0x0000. What must the parser do?
Select an option or press R to reveal.
Correct: B
Every valid DCD subcommand includes at least its own 4-byte header (len >= 4); accepting len == 0 violates framing and traps at += len in an infinite loop.
Common misconception: Tolerating zero-length or unknown command headers as harmless padding.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? In what exact byte order must register address 0x020C406C (CCM_CCGR1) appear inside a DCD Write Data (0xCC) command?
Select an option or press R to reveal.
Correct: A
Unlike little-endian IVT pointers, all DCD header lengths, 32-bit register addresses, values, masks, and counts use big-endian byte order.
Common misconception: Reusing little-endian IVT pointer helpers inside big-endian DCD subcommands.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: what engineering claim does generating and validating verified.imx (3088 B) on the host legitimately prove?
Select an option or press R to reveal.
Correct: C
Host container checks prove binary framing, endianness, and offset geometry; DDR3 electrical calibration and executable target instructions require separate verification.
Common misconception: Mistaking a structurally valid .imx container for a board-calibrated deployment image.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Lab: lab_m04_ivt_dcd_image
- Repair endian serialization, IVT coordinate relationships, DCD framing validation, and bounded compact-imag…
Verify: ./check.sh exits 0.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Summary
- A
DCDtable begins with[0xD2, len_be16, 0x40], wheretotal_len(4 <= total_len <= 1768 B) includes the4-byte header itself. Write Data(0xCC),Check Data(0xCF), andNOP(0xC0) serialize all16-bit lengths and32-bit addresses, values, masks, and counts in big-endian order—distinct from little-endianIVTpointers.- Bounded parsers must verify
len >= 4andlen <= total - atbefore advancing, preventing zero-length infinite loops and buffer overruns. - Structural
.imxvalidation proves container framing and0x00 / 0x20 / 0x2C / 0x0C00offsets, never board-specificDDR3calibration.
GL-E01 · 4.3 (m04-l03)
>_ Kernel Systems Academy
# Key takeaways
- A DCD header uses tag D2 and a big-endian total length including its header.
- Write Data command CC contains command framing followed by big-endian address and value data.
- Its tested structure and offsets, not a calibrated cold boot.
m05/
>_ Kernel Systems Academy
# C runtime startup, linker placement, and peripheral headers
- 5.1 start.S, SVC Entry, Data Copy, and BSS Initialization
- 5.2 GNU ld Scripts, VMA/LMA, and Linker Boundary Symbols
- 5.3 Struct-Mapped MMIO and Auditable SDK Header Adaptation
lab → lab_m05_lds_crt_sdk
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# start.S, SVC Entry, Data Copy, and BSS Initialization
What you'll learn
- Establish an aligned SVC stack before calling any C function.
- Copy the linked .data initialization span when its load and execution addresses differ.
- Zero exactly the linker-defined .bss range without damaging adjacent state.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# What ISO C11 Quietly Assumes Before main() Executes Its First Line
- On a desktop
Linuxworkstation, writing `int g_retry = 3; static int g_err_cnt; int main(void) { ...
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# What ISO C11 Quietly Assumes Before main() Executes Its First Line
- 1.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# What ISO C11 Quietly Assumes Before main() Executes Its First Line
Figure 5.1a: CPSR Supervisor/interrupt-mask configuration (top) and physical RAM transformation performed by start.S before bl main (bottom).
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Mental model
note: Entering C main() on bare silicon without start.S is like walking surgeons into an operating theater before facilities turn on power (OCRAM/DDR3), clear stray trays (.bss), unpack calibrated instruments (.data LMA -> VMA), or lock the operating table (8-byte-aligned SP_svc): every assumption C makes fails on contact.
Where it stops working: Unlike preparing a room once, start.S executes with zero stack until ldr sp completes, relies on prior OCRAM/DDR3 readiness, and must honor exact half-open linker address intervals.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Freestanding C Runtime Startup (crt0 / start.S)
definition: In a freestanding ARMv7-A binary, start.S (crt0) is the stackless assembly entry routine at _start that establishes every hardware precondition assumed by ISO C11 and AAPCS: (1) masking asynchronous IRQ/FIQ (CPSR.I = 1, F = 1) and selecting Supervisor mode (SVC, 0x13) from a compatible privileged state; (2) loading an 8-byte-aligned SP_svc = __stack_top in live RAM; (3) copying initialized writable .data from __data_load (LMA) to [__data_start, __data_end) (VMA) when LMA != VMA; (4) zeroing [__bss_start, __bss_end); and (5) calling bl main followed by a deterministic wfi halt loop.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# What ISO C11 Quietly Assumes Before main() Executes Its First Line
- Step through the four-stage runtime bring-up sequence below:
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# What ISO C11 Quietly Assumes Before main() Executes Its First Line
Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or DCD-trained DDR3 already backing RAM.
Never execute a C call before SP_svc, .data relocation, and .bss zeroing all complete.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Half-Open Loop Invariants, Unsigned BHS & Stackless Discipline
- Inspect Figure 5.1b alongside
target.Sbelow to see why every instruction in_startis chosen delib…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Half-Open Loop Invariants, Unsigned BHS & Stackless Discipline
- Third, trace the
.dataand.bssword loops in Figure 5.1b: whycmp r0, r1followed bybhs(…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Half-Open Loop Invariants, Unsigned BHS & Stackless Discipline
Figure 5.1b: Pre-checked unsigned half-open [start, end) word loops (left) contrasted against three classic bare-metal startup bugs (right).
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# target.S
learner@ksa:~/gl-e01/m05-l01$ bat target.S───────┬──────────────────────────────────────────────────────────────────────────────── │ File: target.S───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ .syntax unified 2 │ .cpu cortex-a7 3 │ .arm 4 │ .section .text.start, "ax" 5 │ .global _start 6 │ _start: 7 │ mrs r0, cpsr 8 │ bic r0, r0, #0x1f 9 │ orr r0, r0, #0x13 10 │ orr r0, r0, #0xc0 11 │ msr cpsr_c, r0 12 │ ldr sp, =__stack_top 13 │ ldr r0, =__data_start 14 │ ldr r1, =__data_end───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Sentinel-Poisoned Relocation & BSS Boundary Proof in ISO C11
- In
lds_vma_lma_solver.cbelow, we poison a64-byte simulated RAM arena with0xA5, place8initializ…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# lds_vma_lma_solver.c
learner@ksa:~/gl-e01/m05-l01$ bat lds_vma_lma_solver.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: lds_vma_lma_solver.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ struct crt_syms { 9 │ uint32_t text_base, etext, data_load, data_start, edata; 10 │ uint32_t bss_start, bss_end, stack_top; 11 │ }; 12 │ 13 │ static struct crt_syms solve_syms(uint32_t base, uint32_t text_ro, 14 │ uint32_t data_vma, uint32_t data_sz,───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Running the Relocation Solver & Assembling start.S for Cortex-A7
- Compile and run
lds_vma_lma_solver.con the workstation, then assembletarget.SintoARMv7-Aobject c…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Running the Relocation Solver & Assembling start.S for Cortex-A7
learner@ksa:~/gl-e01/m05-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic lds_vma_lma_solver.c -o lds_vma_lma_solverlearner@ksa:~/gl-e01/m05-l01$ ./lds_vma_lma_solveretext=0x87800090 data_vma=0x87810000..0x87810008 bss_end=0x87810018 sp=0x87820000learner@ksa:~/gl-e01/m05-l01$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m05-l01$ GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Running the Relocation Solver & Assembling start.S for Cortex-A7
learner@ksa:~/gl-e01/m05-l01$ strace -e trace=write,exit_group \> ./lds_vma_lma_solverwrite(1, "etext=0x87800090 data_vma=0x8781"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Flat RAM Builds vs Split XIP Builds & Linker Contract Coupling
- Notice two subtle couplings between
start.Sand the rest of the boot chain.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Zero-initialized globals (static int count;) start at 0 as expected, yet initialized globals (int baud = 115200;) hold random garbage inside main(). Root Cause: The linker script placed .data at VMA 0x87810000 using AT(_etext) (LMA 0x87800090), and start.S zeroed .bss while omitting the __data_load -> __data_start relocation loop (or BootData.length stopped before _etext + SIZEOF(.data)). Fix: Always copy [__data_load, __data_load + (__data_end - __data_start)) to __data_start when __data_load != __data_start and verify BootData.length covers the packed .data LMA tail.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: When a diagnostic main() returns 0 at the end of a self-test, the board unexpectedly fires random GPIO writes or triggers an Undefined Instruction exception. Root Cause: start.S branched to main with b main (leaving LR pointing back into Boot ROM) or omitted a halt loop after bl main, allowing execution to fall straight into literal pools (=0x87820000) assembled immediately after _start! Fix: Always invoke bl main and follow it immediately with 5: wfi; b 5b.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Guided Practice: Solving QSPI-to-OCRAM Relocation Symbols
- Trace a split
XIPbuild where.text+.rodata(0x1240 B) execute inQSPIflash at0x60001000wh…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Independent Practice: Overlap-Safe Memmove & Arbitrary-Byte Tail Verifier
- Extend
lds_vma_lma_solver.cintocrt_reloc_verifier.csupporting unrounded byte counts (data_sz = 7 B…
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? On a cold bare-metal boot, static uint32_t rx_errors; (declared at file scope with no explicit initializer) reads 0xA5A5A5A5 on the first line of main(). Which start.S obligation failed?
Select an option or press R to reveal.
Correct: C
Because .bss is SHT_NOBITS (occupying zero bytes in the binary image), start.S must write 0 across [__bss_start, __bss_end) in RAM before C executes.
Common misconception: Assuming C static zero-initialization happens automatically in RAM without runtime startup code.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? Why does start.S load three distinct symbols (__data_load, __data_start, and __data_end) to initialize .data?
Select an option or press R to reveal.
Correct: B
Linker scripts frequently pack .data initializers right after .rodata (LMA) while linking C code against a separate writable VMA span [__data_start, __data_end).
Common misconception: Assuming load placement and runtime execution placement are identical in every firmware layout.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: why is inserting bl early_uart_banner as the very first instruction of _start (before ldr sp, =__stack_top) a severe bare-metal defect?
Select an option or press R to reveal.
Correct: A
Even a two-line C function may emit stack pushes at -O0 or -O2; SP_svc must point to reserved, 8-byte-aligned RAM before any C call boundary.
Common misconception: Assuming a short C helper never touches the stack without inspecting generated machine code.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Summary
- Bare-metal
_startmust maskIRQ/FIQ(0xC0), selectSVCmode (0x13), and load a valid, reservedSP_svc = __stack_topbefore calling any C function. AAPCSrequires8-byte stack alignment ((SP & 7) == 0) at every public call interface (bl main).- When
.data's Load Memory Address (__data_load) differs from its execution Virtual Memory Address (__data_start),start.Scopies[__data_load, __data_load + size)before C reads writable globals. - Pre-checked unsigned
cmp + bhsloops zero[__bss_start, __bss_end)cleanly without touching[__bss_end]or misfiring on0-byte sections.
GL-E01 · 5.1 (m05-l01)
>_ Kernel Systems Academy
# Key takeaways
- Bare-metal startup must establish a valid stack before calling C code that can use it.
- A public AAPCS call boundary requires eight-byte stack alignment.
- The helper may use an invalid stack before its preconditions hold.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# GNU ld Scripts, VMA/LMA, and Linker Boundary Symbols
What you'll learn
- Place the entry section and data spans explicitly with ENTRY and SECTIONS.
- Compute VMA/LMA relocation and the serialized image extent.
- Assert aligned non-overlapping BSS and stack boundaries.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
- In Lesson
m05-l01,start.Sconsumed six magic names—__stack_top,__data_load,__data_start, `__da…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
- Trace Figure 5.2a from left to right to understand the two distinct addresses every output section poss…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
- 1.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
Figure 5.2a: Packed 152-byte LMA load image (left) versus sparse runtime VMA execution map with 8-byte-aligned banked IRQ and SVC stacks (right).
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Mental model
note: A linker script (bsp.lds) is the civil blueprint that assigns both compact shipping-container slots (LMA for objcopy / SD transfer) and anchored factory floor pads (VMA for C execution): startup cranes (start.S) read the blueprint's survey stakes (linker boundary symbols) directly rather than opening crates to look for coordinates inside.
Where it stops working: Unlike paper survey stakes, ELF linker symbols live solely in the symbol table (allocating zero bytes in RAM), and link-time ASSERTs verify address arithmetic without proving physical DDR3 is powered or trained.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# GNU ld Location Counter (.), VMA vs AT(LMA) & Symbol-Address Semantics
definition: Inside a GNU ld SECTIONS block, ENTRY(_start) records the ELF entry symbol, . (the location counter) tracks the current output VMA, and ALIGN(n) rounds upward to ( . + n - 1 ) & ~(n - 1) (leaving already-aligned addresses unchanged). ADDR(sec) yields runtime VMA while LOADADDR(sec) yields AT(...) load placement. A script assignment __bss_start = .; creates an ELF symbol-table entry whose address equals . (allocating zero storage bytes in RAM!), defining the exact [__bss_start, __bss_end) interval zeroed by start.S.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
- Walk through the four-stage contract connecting input
.osections,bsp.ldspolicy, boundary symbols, an…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.
Linker boundary symbols are an executable contract: define them inside aligned output sections and reference their addresses, never their dereferenced values.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Linker Symbol Address-vs-Value Semantics & Exact ALIGN Placement
- Study Figure 5.2b carefully—it illustrates one of the most notorious C firmware bugs in industry.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Linker Symbol Address-vs-Value Semantics & Exact ALIGN Placement
- Check two placement rules inside
bsp.ldsbelow as well.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Linker Symbol Address-vs-Value Semantics & Exact ALIGN Placement
Figure 5.2b: Why linker symbols must be declared as char arrays in C (top) and how ALIGN(4) brackets [__bss_start, __bss_end) for word loops (bottom).
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# bsp.lds
learner@ksa:~/gl-e01/m05-l02$ bat bsp.lds───────┬──────────────────────────────────────────────────────────────────────────────── │ File: bsp.lds───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ ENTRY(_start) 2 │ SECTIONS 3 │ { 4 │ . = 0x87800000; 5 │ .text : { KEEP(*(.text.start)) *(.text*) } 6 │ .rodata ALIGN(4) : { *(.rodata*) } 7 │ __data_lma = ALIGN(., 4); 8 │ .data 0x87810000 : AT(__data_lma) 9 │ { 10 │ __data_start = .; 11 │ *(.data*) 12 │ . = ALIGN(4); 13 │ __data_end = .; 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Verifying Overflow-Safe ALIGN() & Dual-Mode Stack Partitioning in C11
- When firmware enables
GICv2interrupts (GL-E02),_startpartitions bothSP_irq(4 KiB) and `S…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# reset_sp_bss_verifier.c
learner@ksa:~/gl-e01/m05-l02$ bat reset_sp_bss_verifier.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: reset_sp_bss_verifier.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ static bool align_up(uint32_t value, uint32_t alignment, uint32_t *out) 7 │ { 8 │ if (alignment == 0U || (alignment & (alignment - 1U)) != 0U) return false; 9 │ uint32_t add = alignment - 1U; 10 │ if (value > UINT32_MAX - add) return false; 11 │ *out = (value + add) & ~add; 12 │ return true; 13 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Executing the Linker-Map & Banked-Stack Verifier
- Compile and run
reset_sp_bss_verifier.cbelow.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Executing the Linker-Map & Banked-Stack Verifier
learner@ksa:~/gl-e01/m05-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic reset_sp_bss_verifier.c -o reset_sp_bss_verifierlearner@ksa:~/gl-e01/m05-l02$ ./reset_sp_bss_verifierLMA=0x87800090 packed=152B bss_end=0x87810048 irq_sp=0x87811048 svc_sp=0x87813048learner@ksa:~/gl-e01/m05-l02$ GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Executing the Linker-Map & Banked-Stack Verifier
learner@ksa:~/gl-e01/m05-l02$ strace -e trace=write,exit_group \> ./reset_sp_bss_verifierwrite(1, "LMA=0x87800090 packed=152B bss_e"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Auditing Orphan Sections with readelf -l & nm -n
- Even with
bsp.ldsin place, compilers occasionally emit auxiliary sections—such as.ARM.exidx(unwind t…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: A C startup helper declares extern uint32_t __bss_start, __bss_end; and calls memset((void *)__bss_start, 0, __bss_end - __bss_start), immediately crashing or zeroing address 0x00000000. Root Cause: Evaluating __bss_start as a uint32_t variable loads the word stored at __bss_start instead of taking the linker symbol's address. Fix: Declare linker boundary symbols as extern char __bss_start[], __bss_end[]; (using (size_t)(__bss_end - __bss_start)), where array decay yields the symbol table address directly without dereferencing RAM.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Adding -ffunction-sections -fdata-sections -Wl,--gc-sections shrinks bsp.bin, but the board stops booting because bsp.bin is 0 bytes (or starts inside an unrelated C helper at 0x87800000). Root Cause: Without ENTRY(_start) and KEEP(*(.text.start)) at the top of .text, linker garbage collection prunes _start (and .ivt) because no C function references them. Fix: Root reachability with ENTRY(_start) and wrap .ivt, .dcd, .vectors, and .text.start in KEEP(...).
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Guided Practice: Binary Gap Bloat & Banked SP Initialization
- Check three linker mechanics by hand.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Independent Practice: Multi-Section Overlap & Orphan Auditor (lds_map_auditor.c)
- Extend
reset_sp_bss_verifier.cintolds_map_auditor.cchecking an array of section records (name, `vm…
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? In bsp.lds, .data is linked with VMA = 0x87810000 (ADDR(.data)) and LMA = 0x87800090 (LOADADDR(.data)). Which address do compiled C functions access when reading or writing a global variable in .data?
Select an option or press R to reveal.
Correct: B
All symbol relocations inside .text bind .data variables to their runtime VMA (0x87810000); LMA (0x87800090) holds the packed initializers copied by start.S prior to main().
Common misconception: Treating LOADADDR (LMA) and ADDR (VMA) as interchangeable runtime pointers.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? Where must __bss_start = .; and __bss_end = .; be placed when start.S clears .bss using 4-byte str r2, [r0], #4 stores?
Select an option or press R to reveal.
Correct: A
Defining __bss_start after .bss's ALIGN(4) start and rounding . = ALIGN(4); before __bss_end guarantees (__bss_end - __bss_start) is an exact multiple of 4 bytes covering only .bss.
Common misconception: Placing boundary symbols outside section alignment adjustments, creating a mismatch with word-stepped startup loops.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: does writing ENTRY(_start) inside bsp.lds automatically populate the IVT.entry pointer inside a raw .imx boot image?
Select an option or press R to reveal.
Correct: C
ENTRY(_start) sets e_entry in bsp.elf (for gdb and --gc-sections rooting), whereas raw binary extraction discards ELF headers completely.
Common misconception: Assuming ELF header metadata survives objcopy -O binary into the raw boot container.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Summary
ENTRY(_start)plusKEEP(*(.text.start))at the start of.textpins the reset entry point at0x87800000and protects it from--gc-sections.- The location counter
.tracks currentVMA, whileALIGN(n)rounds upward to power-of-two boundaries without advancing already-aligned addresses. .data VMA : AT(LMA)separates runtimeADDR(.data)from packedLOADADDR(.data), preventing multi-kilobyte zero-padding bloat inobjcopy -O binaryoutputs while(NOLOAD)omits.bssand.stackbytes.- Linker boundary symbols (
__bss_start,__bss_end,__stack_top) encode addresses in.symtab(never allocated C pointer variables) and pair withASSERT(...)to catch alignment or RAM overflows at link time.
GL-E01 · 5.2 (m05-l02)
>_ Kernel Systems Academy
# Key takeaways
- ENTRY selects the ELF entry symbol, while SECTIONS controls placement of linked output sections.
- The location counter denotes the current linked address; ALIGN adjusts placement to the required boundary.
- No; the boot structure must carry the matching entry value.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Struct-Mapped MMIO and Auditable SDK Header Adaptation
What you'll learn
- Verify GPIO struct offsets with offsetof and static assertions.
- Explain why volatile is neither an atomic update nor a CPU memory barrier.
- Adapt register and pin identifiers through a narrow board wrapper without copying opaque policy.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
- In early assembly experiments (
m03-l03), poking0x0209C000(GPIO1_DR) and0x0209C004(GPIO1_GDIR)…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
- Look at the right panel of Figure 5.3a to see why two well-intentioned "defensive" C habits actually **…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
- 1.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
Figure 5.3a: Verified 32-byte struct gpio_regs layout (left) and why packed attributes and C bit-fields fail on ARMv7-A peripheral buses (right).
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Mental model
note: A C register struct overlay is a machined drilling jig clamped over an engine block (0x0209C000): if every bushing lines up to the byte (_Static_assert + offsetof), every 32-bit ldr/str hits the intended register; if one member shifts by 4 bytes, you bore through a neighboring register with zero syntax errors.
Where it stops working: Even a millimeter-accurate struct jig constrains only C byte offsets and compiler lvalue caching—it never makes read-modify-write updates atomic, inserts ARMv7-A memory barriers, or replaces W1C hardware rules.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Struct-Mapped MMIO Overlay, volatile Semantics & SDK Header Layering
definition: A struct-mapped MMIO overlay binds naturally aligned volatile uint32_t fields (and uint32_t _pad[k] reserved gaps) to documented hardware byte offsets verified at compile time via _Static_assert(offsetof(T, member) == offset, ...). Qualifying members volatile prevents compiler dead-store removal and register caching, without making load -> modify -> store sequences atomic or inserting CPU memory barriers (dsb). Clean SDK header adaptation keeps immutable silicon offsets in an SoC header while isolating carrier-specific pin assignments and active-low polarity inside a narrow board wrapper.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
- Step through the four-stage workflow for engineering auditable
MMIOheaders below:
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# How C Struct Overlays Map Onto Silicon Decode Comparators
Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
Prove every struct offset with _Static_assert(offsetof(...)), use explicit 32-bit masks, and separate silicon facts from board polarity.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Volatile Lost-Update Proof & Three-Tier SDK Adaptation
- Examine Figure 5.3b to separate two distinct boundaries that vendor SDKs routinely blur.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Volatile Lost-Update Proof & Three-Tier SDK Adaptation
- In panel
2of Figure 5.3b, observe how to adapt a vendor header cleanly instead of dumping a40,000…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Volatile Lost-Update Proof & Three-Tier SDK Adaptation
Figure 5.3b: Why volatile RMW still loses concurrent updates without serialization (top) and the three-tier SDK adaptation boundary (bottom).
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# gpio_regs.h
learner@ksa:~/gl-e01/m05-l03$ bat gpio_regs.h───────┬──────────────────────────────────────────────────────────────────────────────── │ File: gpio_regs.h───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #ifndef KSA_GPIO_REGS_H 2 │ #define KSA_GPIO_REGS_H 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ struct gpio_regs { 6 │ volatile uint32_t DR; 7 │ volatile uint32_t GDIR; 8 │ volatile const uint32_t PSR; 9 │ volatile uint32_t ICR1, ICR2, IMR, ISR, EDGE_SEL; 10 │ }; 11 │ _Static_assert(offsetof(struct gpio_regs,GDIR)==0x04U,"GDIR offset"); 12 │ _Static_assert(offsetof(struct gpio_regs,PSR)==0x08U,"PSR offset"); 13 │ _Static_assert(offsetof(struct gpio_regs,ISR)==0x18U,"ISR offset"); 14 │ _Static_assert(sizeof(struct gpio_regs)==0x20U,"GPIO span");───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Proving Offset Geometry, Interleaved RMW Loss & -MMD -MP Guards in C11
- In
mmio_map_dep_auditor.cbelow, we verify three interlocking firmware invariants on the host: (1) `_Stat…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# mmio_map_dep_auditor.c
learner@ksa:~/gl-e01/m05-l03$ bat mmio_map_dep_auditor.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: mmio_map_dep_auditor.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ struct gpio_overlay { 9 │ uint32_t dr, gdir, psr, icr1, icr2, imr, isr, edge_sel; 10 │ }; 11 │ _Static_assert(offsetof(struct gpio_overlay, gdir) == 0x04U, "GDIR"); 12 │ _Static_assert(offsetof(struct gpio_overlay, psr) == 0x08U, "PSR"); 13 │ _Static_assert(offsetof(struct gpio_overlay, isr) == 0x18U, "ISR"); 14 │ _Static_assert(sizeof(struct gpio_overlay) == 0x20U, "GPIO span");───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Cross-Checking Struct Layout on Both Host GCC & Target ARMv7-A Clang
- Run the host verifier and cross-compile
gpio_regs.hdirectly with `clang --target=armv7a-none-eabi ...
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Cross-Checking Struct Layout on Both Host GCC & Target ARMv7-A Clang
learner@ksa:~/gl-e01/m05-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP mmio_map_dep_auditor.c -o mmio_map_dep_auditorlearner@ksa:~/gl-e01/m05-l03$ ./mmio_map_dep_auditorgpio=32B ISR=+24 lost=2 ser=0x80000003 bin=152B imx=3224B mp=oklearner@ksa:~/gl-e01/m05-l03$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -Wno-unused-function -x c -c gpio_regs.h -o target.olearner@ksa:~/gl-e01/m05-l03$ GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Cross-Checking Struct Layout on Both Host GCC & Target ARMv7-A Clang
learner@ksa:~/gl-e01/m05-l03$ strace -e trace=write,exit_group \> ./mmio_map_dep_auditorwrite(1, "gpio=32B ISR=+24 lost=2 ser=0x80"..., 64) = 64exit_group(0) = ?+++ exited with 0 +++GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# From Bare-Metal Physical Casts to Linux 6.12 ioremap() & Modular BSPs
- Keep two architectural horizons clear as your codebase grows.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Annotating struct gpio_regs with __attribute__((packed)) causes freestanding Cortex-A7 builds (-mno-unaligned-access) to trigger Data Aborts or corrupt peripheral state whenever writing gpio->DR. Root Cause: packed sets alignof(struct gpio_regs) == 1, forcing the compiler to assume misaligned pointers and emit four 8-bit strb instructions instead of a single 32-bit str across the AIPS bus. Fix: Remove packed from aligned 32-bit MMIO structs, pad reserved gaps explicitly with volatile uint32_t _pad[N], and verify offsets with _Static_assert(offsetof(...)).
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Modeling GPIO1_ISR (+0x18) as a 32-bit C bit-field union and executing gpio->ISR_bits.pin18 = 1U; silently drops simultaneous interrupts on sibling pins in GPIO1. Root Cause: Bit-field assignment compiles to ldr + orr + str (RMW), replaying 1s onto every already-set bit in the W1C status register and clearing unhandled interrupts! Fix: Keep volatile uint32_t ISR; as an undivided 32-bit word and write (UINT32_C(1) << pin) directly via gpio_ack_mask().
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Guided Practice: Sizing Reserved Gap Arrays for CCM (0x020C4000)
- Design a sparse
struct ccm_sliceoverlay withoutpackedcoveringCCSR(+0x0C),CACRR(+0x10), a…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Independent Practice: Multi-Peripheral Header Suite (soc_headers_audit.c)
- Author a self-contained
soc_headers_audit.cdefining assertion-locked overlays forGPIO(0x20 B), `CC…
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? During SDK header adaptation, a missing reserved word shifts ISR inside struct gpio_regs to byte offset 0x14 instead of 0x18. What catches that defect deterministically at compile time?
Select an option or press R to reveal.
Correct: A
_Static_assert paired with offsetof forces the C11 compiler to check the exact byte offset of ISR against the hardware register map on every build.
Common misconception: Assuming volatile qualifiers or identifier names verify struct member offsets.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Why does updating gpio->DR |= (1U << 3); on a volatile uint32_t DR member still require exclusive bank ownership or interrupt masking?
Select an option or press R to reveal.
Correct: C
volatile prevents compiler optimization from eliding or merging accesses, but a read-modify-write remains a multi-instruction sequence vulnerable to concurrent lost updates.
Common misconception: Equating compiler-visible volatile loads and stores with hardware atomicity.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: how must a struct-based inline helper acknowledge pending interrupt mask inside the Write-One-to-Clear (W1C) ISR member?
Select an option or press R to reveal.
Correct: B
On W1C hardware, writing 1 clears that bit and writing 0 is a no-op; assigning mask directly clears only the intended event without reading and replaying other pending 1 bits.
Common misconception: Treating a named struct member like ordinary RW RAM (|= or &= ~) regardless of underlying W1C silicon behavior.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Lab: lab_m05_lds_crt_sdk
- Repair overflow-safe alignment, initialized-data copy, exact BSS clearing, and GPIO header geometry without…
Verify: ./check.sh exits 0.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Summary
- Every member of a struct-mapped
MMIOoverlay must sit at its exact documented peripheral byte offset, proven at compile time withoffsetofand_Static_assert(never__attribute__((packed))). volatileprevents compiler load/store removal and merging, yet provides neither atomic read-modify-write execution norARMv7-ACPU memory barriers.- Explicit
32-bit unsigned masks avoid implementation-defined C bit-field ordering, narrow byte loads (ldrb/strb), and accidentalRMWonW1Cstatus registers (gpio->ISR = mask). - Clean SDK adaptation keeps silicon base addresses and register structs separate from carrier-board pin assignments and active-low polarity wrappers.
GL-E01 · 5.3 (m05-l03)
>_ Kernel Systems Academy
# Key takeaways
- A struct-mapped register header must place every member at the peripheral's exact documented byte offset.
- Volatile-qualified accesses constrain compiler treatment but do not make a read-modify-write atomic.
- Assign the acknowledgment mask directly to the ISR member.
m06/
>_ Kernel Systems Academy
# Modular BSP, transistor-switched buzzer, and polled key capstone
- 6.1 Modular BSP Layout and Dependency-Correct Make Rules
- 6.2 Transistor Buzzer Switching and Safe GPIO Polarity
- 6.3 Capstone: A Nonblocking Polled Key and Modular BSP
lab → lab_m06_modular_bsp_io
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Modular BSP Layout and Dependency-Correct Make Rules
What you'll learn
- Partition clock, indicator, delay, and application responsibilities into narrow modules.
- Write pattern rules that retain source paths and generate header dependencies.
- Diagnose a stale object caused by a missing header dependency.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
- Once a bare-metal codebase grows beyond
start.Sand onemain.cinto clock gating, statusLEDs, buzzer…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
- Study Figure 6.1a to see how a real production Board Support Package (
BSP) establishes both **arc…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
- 1.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
Figure 6.1a: Three-layer bare-metal BSP header firewall — main.c never sees soc_regs.h, bounding both coupling and incremental rebuilds.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Mental model
note: A modular BSP and its Makefile work like a multi-sheet electrical schematic paired with an automated netlist checker: neat sheet boundaries isolate raw peripheral stages (soc_regs.h) from control logic (main.c), while the netlist (-MMD -MP .d files) ensures changing one header constant flags every affected .o target automatically.
Where it stops working: Unlike visual folder trees in an editor, GNU Make knows nothing about directories unless explicit pattern rules mirror paths under obj/ and -include splices generated .d prerequisite edges into the DAG.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Modular BSP Ownership & GCC -MMD -MP Dependency Generation
definition: A modular Board Support Package (BSP) partitions clock, indicator, timing, and application code behind narrow public headers while GNU Make schedules rebuilds strictly from its declared Directed Acyclic Graph (DAG) of target prerequisites—never from folder layout. Passing -MMD tells GCC/Clang to emit a .d file listing every non-system #include consumed by that .o, -MP appends empty phony header.h: rules so renamed or deleted headers do not break make, and -include $(OBJ:.o=.d) splices those edges into subsequent incremental builds.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
- Step through the four-stage ownership and dependency loop below:
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw MMIO literals.
Pair narrow subsystem headers with path-preserving obj/%.o rules and -include $(OBJ:.o=.d) so neither object collisions nor stale headers can survive.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Path-Preserving Object Rules, Phony Header Guards & ABI Consistency
- Inspect Figure 6.1b alongside
Makefile(target_m06_l01) below to see three subtleMakefilebugs p…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Path-Preserving Object Rules, Phony Header Guards & ABI Consistency
- 1.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Path-Preserving Object Rules, Phony Header Guards & ABI Consistency
Figure 6.1b: Path-mirroring pattern rules prevent basename collisions (left), while -MMD -MP plus -include closes the incremental header rebuild DAG (right).
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Makefile
learner@ksa:~/gl-e01/m06-l01$ bat Makefile───────┬──────────────────────────────────────────────────────────────────────────────── │ File: Makefile───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ CROSS_COMPILE ?= arm-linux-gnueabihf- 2 │ CC := $(CROSS_COMPILE)gcc 3 │ OBJCOPY := $(CROSS_COMPILE)objcopy 4 │ CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -ffreestanding \ 5 │ -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=soft -MMD -MP 6 │ CPPFLAGS := -Iinclude -Ibsp/clk -Ibsp/led -Ibsp/delay 7 │ SRC := project/main.c bsp/clk/clk.c bsp/led/led.c bsp/delay/delay.c 8 │ OBJ := $(patsubst %.c,obj/%.o,$(SRC)) obj/project/start.o 9 │ all: bsp.bin 10 │ obj/%.o: %.c 11 │ @mkdir -p $(dir $@) 12 │ $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ 13 │ obj/%.o: %.S 14 │ @mkdir -p $(dir $@)───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Auditing CCM Sparse Struct Offsets & DAG Invalidation Closure in C11
- In
bsp_header_dep_audit.cbelow, we prove two properties side by side: first,_Static_assertverifies `…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# bsp_header_dep_audit.c
learner@ksa:~/gl-e01/m06-l01$ bat bsp_header_dep_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: bsp_header_dep_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ #include <string.h> 7 │ 8 │ struct bsp_ccm_regs { 9 │ volatile uint32_t _pad0[26]; /* 0x00..0x64 */ 10 │ volatile uint32_t CCGR[7]; /* 0x68..0x80 */ 11 │ }; 12 │ _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[0]) == 0x68U, "CCGR0"); 13 │ _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[1]) == 0x6cU, "CCGR1"); 14 │ _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[6]) == 0x80U, "CCGR6");───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Compiling with -MMD -MP & Verifying Incremental Invalidation Masks
- Compile
bsp_header_dep_audit.cwith-MMD -MPand execute the audit binary below.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Compiling with -MMD -MP & Verifying Incremental Invalidation Masks
learner@ksa:~/gl-e01/m06-l01$ gcc -std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP bsp_header_dep_audit.c -o bsp_header_dep_auditlearner@ksa:~/gl-e01/m06-l01$ ./bsp_header_dep_auditCCM_span=132B CCGR1=+0x6C soc_chg=0x13 brd_chg=0x12 lds_chg=0x10learner@ksa:~/gl-e01/m06-l01$ GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Compiling with -MMD -MP & Verifying Incremental Invalidation Masks
learner@ksa:~/gl-e01/m06-l01$ strace -e trace=write,exit_group \> ./bsp_header_dep_auditwrite(1, "CCM_span=132B CCGR1=+0x6C soc_ch"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Tracking Compiler Flag Changes Alongside Header Dependencies
- One subtle detail separates good Makefiles from airtight ones:
.dfiles track.cand.htimestamps, *…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Editing LED_PIN inside bsp/led/led_board.h and running make prints Nothing to be done for 'all', leaving the old pin number baked into bsp.bin. Root Cause: Either -MMD -MP was omitted from CFLAGS, or -include looked for *.d in the project root while objects (and .d files) were placed under obj/bsp/led/led.d. Fix: Match the -include glob directly to OBJ via -include $(OBJ:.o=.d) and verify with touch bsp/led/led_board.h && make -n.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Changing -mfloat-abi=hard to -mfloat-abi=soft in Makefile and running incremental make fails during ld with uses VFP register arguments, bsp.elf does not. Root Cause: Generated .d files record #include header files, not Makefile flag variables, leaving stale hard-float .o files on disk. Fix: Add Makefile (or a compiler-flags stamp file) as a prerequisite on obj/%.o: %.c Makefile or run a clean rebuild whenever ABI flags change.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Guided Practice: Tracing a Deleted Header & Linker-Script Edit
- Walk through two incremental build scenarios.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Independent Practice: Build-Graph Layer & Cycle Linter (build_graph_lint.c)
- Extend
bsp_header_dep_audit.cintobuild_graph_lint.cthat checks an array of source paths for flattene…
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? An engineer updates a register offset inside include/soc_regs.h and runs make, but obj/bsp/clk/clk.o does not recompile. What is the first build-graph defect to check?
Select an option or press R to reveal.
Correct: B
GNU Make never scans C #include directives on its own; it relies on -MMD -MP .d files spliced in via -include $(OBJ:.o=.d).
Common misconception: Assuming directory names like include/ automatically create rebuild dependencies in Make.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? Why does OBJ := $(patsubst %.c,obj/%.o,$(SRC)) mirror full relative paths (obj/bsp/clk/clk.o) instead of flattening every object into obj/$(notdir).o?
Select an option or press R to reveal.
Correct: A
Path-preserving object rules guarantee a collision-free 1-to-1 mapping from every source file in the repository to its compiled .o and .d artifacts.
Common misconception: Assuming separate source directories stay separate when mapped through a flattened obj/%.o rule.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Quick check
? Retrieval: why must bsp.lds appear in the prerequisite list of bsp.elf: $(OBJ) bsp.lds in addition to -Wl,-T,bsp.lds in the recipe?
Select an option or press R to reveal.
Correct: C
GNU Make treats command-line recipe text as opaque shell strings; listing bsp.lds as a prerequisite ensures address-map edits trigger a relink of bsp.elf and bsp.bin.
Common misconception: Assuming a file mentioned inside -Wl,-T,... is automatically tracked by Make as an input dependency.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Summary
- A modular
BSPseparates pure silicon register structs (include/soc_regs.h), board-aware subsystem drivers (bsp/clk/,bsp/led/,bsp/delay/), and logical application code (project/main.c). - GNU Make rebuilds targets strictly from declared prerequisite timestamps and path-preserving
obj/%.orules rather than directory conventions. GCC/Clang-MMDemits non-system header dependencies per.o, while-MPadds empty phony header targets so deleted or renamed headers never stall incremental builds.-include $(OBJ:.o=.d)reconnects.dfiles into Make'sDAG, andbsp.elf: $(OBJ) bsp.ldsensures linker-script edits trigger deterministic relinking.
GL-E01 · 6.1 (m06-l01)
>_ Kernel Systems Academy
# Key takeaways
- A BSP can separate clock, LED, delay, and application responsibilities into distinct source modules.
- GNU Make decides rebuilds from declared prerequisites and artifact state rather than directory appearance.
- A new link of the ELF that depends on that placement policy.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Transistor Buzzer Switching and Safe GPIO Polarity
What you'll learn
- Derive PNP and NPN buzzer control polarity from their current paths.
- Reject invalid bank-local pin requests before shifting or writing.
- Preserve sibling DR bits while stating the exclusive-ownership requirement.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
- Why not wire a
30 mAmagnetic or piezoelectric buzzer directly between ani.MX6ULLGPIOpin and groun…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
- Trace all three BJT switching circuits in Figure 6.2a from emitter to collector to derive software pola…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
- 1.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
Figure 6.2a: BJT switching physics — 3.3 V PNP high-side active-low (A), 5.0 V NPN low-side active-high (B), and why a 5.0 V PNP cannot turn off from a 3.3 V GPIO (C).
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Mental model
note: A BJT switching stage is a hydraulic pilot valve: a 1.67 mA pilot current through R_B opens a 30 mA supply pipe through the collector-emitter path without forcing the i.MX6ULL CMOS pad to carry the heavy actuator load itself.
Where it stops working: Unlike an optically isolated relay, a BJT shares a common electrical reference with the SoC—mismatched 5 V PNP emitter rails can back-feed current straight into a 3.3 V GPIO pad!
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Active vs Passive Sounders, BJT Polarity & Shared-Bank Ownership
definition: An active buzzer integrates an internal oscillator and sounds from steady DC, whereas a passive sounder requires an external AC/PWM waveform. A 3.3 V PNP high-side switch conducts when its base is pulled low (active-low), while an NPN low-side switch conducts on positive base current (active-high)—translated behind buzzer_set(bool enabled) via drive_high = (asserted != active_low). Because GPIOx_DR packs 32 pins into one word, read-modify-write updates must preserve all 31 sibling bits under exclusive bank ownership or serialization.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
- Step through the four-stage actuator control path from logical request to collector current below:
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
Step 1: Application calls buzzer_set(true/false) with zero knowledge of PNP or NPN inversion.
Expose logical buzzer_set(enabled) to application code, preload inactive DR before GDIR, and validate pin < 32 before shifting.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# CCM_CCGR1 2-Bit Clock Gates, IOMUXC_SNVS & Chirp-Free Startup
- Inspect Figure 6.2b to wire up the complete
i.MX6ULLhardware path for an active buzzer on `SNVS_TAMP…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# CCM_CCGR1 2-Bit Clock Gates, IOMUXC_SNVS & Chirp-Free Startup
Figure 6.2b: CCM_CCGR1 2-bit clock gates (top), IOMUXC_SNVS pad routing plus chirp-free preload (bottom left), and Boolean polarity translation (bottom right).
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# CCM_CCGR1 2-Bit Clock Gates, IOMUXC_SNVS & Chirp-Free Startup
- In
bsp_buzzer.cbelow, verify howgpio_pin_write()checksdr == NULL || pin >= 32Ubefore evaluat…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# bsp_buzzer.c
learner@ksa:~/gl-e01/m06-l02$ bat bsp_buzzer.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: bsp_buzzer.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdbool.h> 2 │ #include <stddef.h> 3 │ #include <stdint.h> 4 │ bool gpio_pin_write(volatile uint32_t *dr, unsigned pin, 5 │ bool asserted, bool active_low) 6 │ { 7 │ if (dr == NULL || pin >= 32U) return false; 8 │ uint32_t mask = UINT32_C(1) << pin; 9 │ uint32_t value = *dr; /* caller serializes the shared bank */ 10 │ *dr = (asserted != active_low) ? value | mask : value & ~mask; 11 │ return true; 12 │ } 13 │ bool buzzer_set(bool enabled) 14 │ {───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Verifying Selective CCGR1 Gating & Buzzer Polarity Safety in C11
- In
ccm_ccgr_buzzer_audit.cbelow,ccgr_update()rejects invalidCCGRindices (>= 7), invalid slots…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# ccm_ccgr_buzzer_audit.c
learner@ksa:~/gl-e01/m06-l02$ bat ccm_ccgr_buzzer_audit.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: ccm_ccgr_buzzer_audit.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stddef.h> 4 │ #include <stdint.h> 5 │ #include <stdio.h> 6 │ 7 │ enum { CG_OFF = 0U, CG_RUN = 1U, CG_RSVD = 2U, CG_RUN_WAIT = 3U }; 8 │ 9 │ static bool ccgr_update(uint32_t ccgr[7], unsigned reg_idx, 10 │ unsigned cg_slot, unsigned policy) 11 │ { 12 │ if (reg_idx >= 7U || cg_slot >= 16U || policy > 3U || policy == CG_RSVD) 13 │ return false; 14 │ unsigned shift = cg_slot * 2U;───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Running the CCGR1 & Buzzer Polarity Audit + ARMv7-A Cross-Check
- Compile and run
ccm_ccgr_buzzer_auditon the workstation, then cross-compilebsp_buzzer.cfor freestand…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Running the CCGR1 & Buzzer Polarity Audit + ARMv7-A Cross-Check
learner@ksa:~/gl-e01/m06-l02$ gcc -std=c11 -Wall -Wextra -Werror -pedantic ccm_ccgr_buzzer_audit.c -o ccm_ccgr_buzzer_auditlearner@ksa:~/gl-e01/m06-l02$ ./ccm_ccgr_buzzer_auditCCGR1=0xCFFFFFF0 pnp_on_bit1=0 pnp_off_bit1=1 npn_on_bit1=1learner@ksa:~/gl-e01/m06-l02$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c bsp_buzzer.c -o target.olearner@ksa:~/gl-e01/m06-l02$ GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Running the CCGR1 & Buzzer Polarity Audit + ARMv7-A Cross-Check
learner@ksa:~/gl-e01/m06-l02$ strace -e trace=write,exit_group \> ./ccm_ccgr_buzzer_auditwrite(1, "CCGR1=0xCFFFFFF0 pnp_on_bit1=0 p"..., 60) = 60exit_group(0) = ?+++ exited with 0 +++GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Base-Current Sizing & Future Linux gpiod Descriptor Mapping
- Notice how clean hardware-software co-design makes future
Linux kernelmigration effortless.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Powering a PNP high-side buzzer from 5.0 V while connecting its base resistor directly to a 3.3 V i.MX6ULL GPIO causes the buzzer to sound continuously even when software sets DR |= (1U << 1) (3.3 V). Root Cause: At GPIO = 3.3 V, V_EB = 5.0 V - 3.3 V = 1.7 V > 0.7 V, keeping the PNP emitter-base junction forward-biased in saturation and injecting current into the 3.3 V pad clamp! Fix: Switch 5.0 V loads from 3.3 V GPIOs using an NPN (or N-channel MOSFET) low-side stage, or keep the PNP emitter on the matching 3.3 V rail.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Warning
warning: Symptom: CCGR1[31:30] (GPIO5) and GPIO5_GDIR/GPIO5_DR (0x020AC000) are configured properly, yet SNVS_TAMPER1 never toggles on an oscilloscope because mux writes targeted 0x020E0000 + offset. Root Cause: SNVS_TAMPER0..9 pads reside in the separate IOMUXC_SNVS peripheral block (0x02290000, SNVS_TAMPER1 mux at 0x0229000C), not main IOMUXC (0x020E0000). Fix: Always check whether a GPIO5 pad belongs to IOMUXC_SNVS (0x02290000) before programming ALT5.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Guided Practice: Sizing an NPN Base Resistor & Glitchless Init
- Compute the analog drive and register sequence for a
5.0 V,40 mAactive buzzer switched on the low sid…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Independent Practice: Multi-Actuator Chirp-Free BSP Verifier (actuator_bsp_audit.c)
- Extend
ccm_ccgr_buzzer_audit.cintoactuator_bsp_audit.cmanagingLED0(GPIO1_IO03, active-low, `CC…
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Why is it electrically incorrect to describe a standard PNP or NPN transistor buzzer stage as providing galvanic isolation for the i.MX6ULL?
Select an option or press R to reveal.
Correct: A
A BJT amplifies current (I_C = beta * I_B) so the GPIO pad sinks/sources milliamps instead of full load current, but both sides remain conductively coupled (unlike an optocoupler or transformer).
Common misconception: Confusing current buffering through a transistor with true galvanic isolation.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? On our 3.3 V PNP high-side active buzzer (SNVS_TAMPER1 / GPIO5_IO01, active_low = true), which GPIO5_DR bit 1 state silences (disables) the buzzer, and when must initialization establish it?
Select an option or press R to reveal.
Correct: C
Raising the PNP base to 3.3 V matches its 3.3 V emitter (V_EB = 0 V, cutoff), and preloading DR high prior to GDIR prevents a brief active-low startup chirp.
Common misconception: Assuming 0 always means "off" regardless of PNP high-side inversion.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Quick check
? Retrieval: under what concurrency condition is gpio_pin_write()'s *dr = ... read-modify-write guaranteed free from lost sibling-pin updates?
Select an option or press R to reveal.
Correct: B
Even when two writers target disjoint bits (bit 1 and bit 3), both read and write the entire 32-bit DR register; without serialization, an interleaved store overwrites the sibling update.
Common misconception: Assuming disjoint bit masks make multi-instruction MMIO read-modify-writes automatically atomic.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Summary
- Active buzzers contain an internal oscillator driven by steady DC, whereas passive sounders require an alternating
PWM/ timer waveform. - A
3.3 VPNPhigh-side switch conducts when pulled low (V_EB ~= 0.7 V, active-low), while anNPNlow-side switch conducts when driven high (V_BE ~= 0.75 V, active-high), unified behinddrive_high = (asserted != active_low). - BJT switches buffer load current (
I_B << I_C) via base resistorR_Bwithout providing galvanic isolation; never tie aPNPemitter to5 Vwhen driven directly from a3.3 VGPIO. - Enable
GPIO5'sCCM_CCGR1[31:30](CG15) clock gate andIOMUXC_SNVS(0x0229000C) mux, preload inactiveDRbeforeGDIR, validatepin < 32U, and serialize sharedDRread-modify-writes.
GL-E01 · 6.2 (m06-l02)
>_ Kernel Systems Academy
# Key takeaways
- An active buzzer contains an oscillator and can sound from an appropriate steady supply; a passive sounder needs an appropriate waveform.
- A PNP high-side switch commonly asserts when its base is driven sufficiently below its emitter, while an NPN low-side switch commonly asserts with positive base drive.
- When the bank operation has exclusive ownership or serialization.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Capstone: A Nonblocking Polled Key and Modular BSP
What you'll learn
- Normalize the sampled active-low PSR input into a logical pressed state.
- Accept a candidate only after a continuous sampled stable interval.
- Integrate one press event with LED and buzzer policy without blocking polling.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
- Press a spring-loaded metal dome inside a tactile PCB push-button and zoom in on an oscilloscope at `500 us…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
- Why not "fix" bounce with `if (pressed) { delay_ms(10); ...
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
- 1.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
Figure 6.3a: Active-low tactile switch input path into GPIO1_PSR[18] (top) and the exact capstone waveform turning press/release chatter into single-shot transitions (bottom).
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mental model
note: A nonblocking debounce FSM is an air-traffic clearance desk that logs a status transition only after radar sweeps confirm the new state holds continuously for 10 ticks—restarting since_ms on any bounce blip while keeping every other BSP subsystem runnable in < 30 CPU cycles per poll.
Where it stops working: Unlike continuous analog radar, discrete polling observes pad voltage only at sample instants and relies on a monotonic unsigned tick source whose poll interval stays well below the 2^32 wraparound horizon.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Nonblocking Debounce FSM & Modulo-2^32 Elapsed-Time Subtraction
definition: A nonblocking contact-debounce FSM stores (candidate, stable, since_ms): any sample pressed != candidate updates candidate = pressed and since_ms = now_ms (KEY_NONE), while an unchanged candidate != stable commits stable = candidate and emits exactly one transition event (KEY_PRESS or KEY_RELEASE) once (uint32_t)(now_ms - since_ms) >= threshold_ms. Computing elapsed duration via unsigned modulo-2^32 subtraction (uint32_t)(now - since) remains exact across UINT32_MAX -> 0 wraparound (~49.71 days at 1 kHz), whereas deadline addition now >= since + 10U wraps and misfires early!
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
- Step through the four-stage capstone super-loop connecting
GPIO1_PSR, debounce qualification, and `bsp/le…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Mechanical Contact Bounce Physics & Why Blocking Delays Fail
Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
Sample PSR (never DR), separate candidate from stable state, and always subtract (uint32_t)(now - since) >= threshold.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Modulo-2^32 Tick Wraparound Proof & O(1) Poll Architecture
- Study Figure 6.3b (
Panel 2) carefully—it explains a classic49.7-day uptime field bug that crashes…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Modulo-2^32 Tick Wraparound Proof & O(1) Poll Architecture
Figure 6.3b: Nonblocking O(1) debounce branches (left) and why unsigned subtraction (uint32_t)(now - since) survives 49.7-day UINT32_MAX wraparound (right).
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Modulo-2^32 Tick Wraparound Proof & O(1) Poll Architecture
- In
bsp_key.cbelow,key_poll()readsGPIO1_PSR(0x0209C008, base0x0209C000 + 0x08) through a `vo…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# bsp_key.c
learner@ksa:~/gl-e01/m06-l03$ bat bsp_key.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: bsp_key.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdbool.h> 2 │ #include <stdint.h> 3 │ enum key_event { KEY_NONE, KEY_PRESS, KEY_RELEASE }; 4 │ struct key_filter { bool candidate, stable; uint32_t since; }; 5 │ enum key_event key_poll(struct key_filter *f, uint32_t now_ms) 6 │ { 7 │ volatile const uint32_t *psr = 8 │ (volatile const uint32_t *)(uintptr_t)0x0209c008U; 9 │ bool pressed = (*psr & (UINT32_C(1) << 18)) == 0U; 10 │ if (pressed != f->candidate) { 11 │ f->candidate = pressed; 12 │ f->since = now_ms; 13 │ return KEY_NONE; 14 │ }───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Proving End-to-End Capstone Integration & Wraparound Safety in C11
debounce_fsm_capstone.cwires together every concept fromGL-E01into one deterministic host testbench:…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# debounce_fsm_capstone.c
learner@ksa:~/gl-e01/m06-l03$ bat debounce_fsm_capstone.c───────┬──────────────────────────────────────────────────────────────────────────────── │ File: debounce_fsm_capstone.c───────┼──────────────────────────────────────────────────────────────────────────────── 1 │ #include <assert.h> 2 │ #include <stdbool.h> 3 │ #include <stdint.h> 4 │ #include <stdio.h> 5 │ 6 │ enum key_ev { EV_NONE = 0, EV_PRESS = 1, EV_RELEASE = 2 }; 7 │ struct deb_fsm { bool candidate, stable; uint32_t since_ms; }; 8 │ 9 │ static bool psr_key_pressed(uint32_t gpio1_psr) 10 │ { 11 │ return (gpio1_psr & (UINT32_C(1) << 18)) == 0U; 12 │ } 13 │ 14 │ static enum key_ev debounce_step(struct deb_fsm *f, bool pressed, uint32_t now)───────┴────────────────────────────────────────────────────────────────────────────────GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Running the Capstone Verifier & Freestanding Cortex-A7 Object Check
- Compile and execute
debounce_fsm_capstone.con the workstation, then cross-compilebsp_key.cfor freest…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Running the Capstone Verifier & Freestanding Cortex-A7 Object Check
learner@ksa:~/gl-e01/m06-l03$ gcc -std=c11 -Wall -Wextra -Werror -pedantic debounce_fsm_capstone.c -o debounce_fsm_capstonelearner@ksa:~/gl-e01/m06-l03$ ./debounce_fsm_capstonepress@14 release@36 press@47 wrap@4 dr1_off=0xA5A5A5AD dr5_off=0x5A5A5A57learner@ksa:~/gl-e01/m06-l03$ clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c bsp_key.c -o target.olearner@ksa:~/gl-e01/m06-l03$ GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Running the Capstone Verifier & Freestanding Cortex-A7 Object Check
learner@ksa:~/gl-e01/m06-l03$ strace -e trace=write,exit_group \> ./debounce_fsm_capstonewrite(1, "press@14 release@36 press@47 wra"..., 74) = 74exit_group(0) = ?+++ exited with 0 +++GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Where You Stand Now & Bridging Forward to GL-E02
- Step back and appreciate the full bare-metal stack you now own from first principles:
ARMv7-AAAPCS/ `…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: After ~49.7 days of continuous 1 ms uptime (or whenever unit tests seed now_ms near 0xFFFFFFFA), tactile button bounces trigger immediate false KEY_PRESS events on the very first microsecond of contact chatter! Root Cause: Elapsed time was written if (now_ms >= f->since + 10U), allowing f->since + 10U to wrap modulo 2^32 to a small integer (4U) that 0xFFFFFFFB immediately exceeds! Fix: Always compute elapsed ticks via unsigned subtraction (uint32_t)(now_ms - f->since) >= 10U.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Warning
warning: Symptom: Configuring GPIO1_IO18 as an input (GDIR[18] = 0) and polling *gpio1_dr & (1U << 18) never detects a button press even when a multimeter measures 0 V right on the SoC ball. Root Cause: GPIOx_DR (+0x00) reads back the internal output data latch, whereas external pin voltage on an input pad is sampled through GPIOx_PSR (+0x08) (and requires IOMUXC pull-up biasing so the open switch cannot float). Fix: Read inputs strictly from GPIOx_PSR (+0x08) after configuring the ALT5 mux, pull-up network, and GDIR bit 0.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Guided Practice: Hand-Tracing Release Chatter & Modulo Subtraction
- Trace
debounce_step()starting from accepted pressed state `{candidate = true, stable = true, since_ms =…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Independent Practice: Short-Tap vs 500 ms Long-Hold BSP Controller
- Extend
debounce_fsm_capstone.cintokey_short_long_bsp.caddingEV_LONG_HOLD(emitted once per press…
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? In debounce_step(), a bouncing switch finally stays low starting at now = 4 (f->candidate = true, f->since_ms = 4) with threshold 10U. What does debounce_step() return when polled with pressed = true at now = 13?
Select an option or press R to reveal.
Correct: C
Elapsed duration between tick 4 and tick 13 is 13 - 4 = 9 ticks; the 10-tick stability threshold is reached at now = 14 (14 - 4 = 10).
Common misconception: Confusing fencepost inclusive label counting (4..13 = 10 numbers) with physical elapsed duration (13 - 4 = 9 intervals).
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? After EV_PRESS fires at now = 14, the user keeps holding the tactile switch down at now = 19, 20, 25.... Why does key_poll() emit zero additional KEY_PRESS events while held?
Select an option or press R to reveal.
Correct: B
Once stable catches up to candidate, both equal true; another KEY_PRESS cannot occur until the key first completes a full 10 ms debounced KEY_RELEASE (stable = false).
Common misconception: Thinking software debounce merely rate-limits repeats rather than detecting clean state transitions.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Quick check
? Retrieval: which GPIO1 register (base 0x0209C000) must bsp_key.c read to observe the external tactile switch on GPIO1_IO18?
Select an option or press R to reveal.
Correct: A
PSR (+0x08) samples the physical pad state; DR (+0x00) is the output data latch, and ISR (+0x18) is the W1C interrupt status register.
Common misconception: Reading the DR output latch or ISR interrupt register when polling a GPIO input pad.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Lab: lab_m06_modular_bsp_io
- Repair a candidate/stable debouncer, active-low output policy, and integrated press-driven toggling while r…
Verify: ./check.sh exits 0.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Summary
- Mechanical switch contacts bounce repeatedly across
1..5 mson both press and release;IOMUXChysteresis (HYS = 1) cleans slow edges while a software debounce FSM filters millisecond chatter. - Tracking
(candidate, stable, since_ms)in anO(1)nonblocking poll function qualifies transitions without starving siblingBSPwork insidedelay_ms()spin loops. - Unsigned subtraction
(uint32_t)(now_ms - since_ms) >= thresholdcomputes exact elapsed ticks acrossUINT32_MAX -> 0wraparound (~49.7days at1 kHz), avoiding thesince + thresholdoverflow bug. - Sampling
GPIO1_PSR(+0x08) and dispatching single-edgeEV_PRESStransitions into polarity-awareGPIO1_DR/GPIO5_DRhelpers completes an auditable, modular bare-metalBSP.
GL-E01 · 6.3 (m06-l03)
>_ Kernel Systems Academy
# Key takeaways
- Mechanical contacts can create multiple electrical transitions during one physical press or release.
- A debouncer can track candidate state, candidate-start time, and accepted stable state separately.
- PSR, with the selected active-low bit normalized into pressed.