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.
Print this handbook or save as PDF (A4 or Letter) for offline engineering reference. Terminal listings convert automatically to crisp white ink-saving frames in print.
m01/
Cross-compilation workbench, ARM EABI, and schematics
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.
Host vs Target Machines and the i.MX6ULL Silicon Graph
When you compile and run ./hello on a desktop workstation, one computer performs every role: your x86_64 processor runs the C compiler, asks the running Linux kernel to map virtual memory pages and zero .bss, executes variable-length x86_64 machine instructions, and prints text through POSIX write() system calls. Embedded bare-metal bring-up splits that world across two physically distinct computers that share neither an instruction set, nor word widths, nor an operating system. Your build host is a 64-bit x86_64 workstation running under the LP64 data model (sizeof(long) == 8, sizeof(void *) == 8). Your execution target is a 32-bit ARMv7-A Cortex-A7 core inside an i.MX6ULL System-on-Chip (SoC), running freestanding (-ffreestanding -nostdlib) under the ILP32 data model (sizeof(long) == 4, sizeof(void *) == 4) with zero OS loader at power-on!
What physically sits inside that i.MX6ULL package alongside the Cortex-A7 CPU? Look at the right column of Figure 1.1a. A microcontroller or SoC is not a naked arithmetic unit wired straight to package pins; it is an interconnected silicon city bridged by AXI, AHB, and IPG on-chip buses:
- Mask
Boot ROM(0x00000000) &128 KiBOCRAM(0x00900000): Fixed boot firmware and static on-chip SRAM cells that work immediately after reset before external DRAM is configured. - Multi-Mode
DDRController (MMDC, externalDDR3at0x80000000+): High-capacity off-chip RAM that returns garbage or hangs the bus untilDCDtables orU-Bootcalibrate timings. - Clock Control (
CCM,0x020C4000) & Pin Multiplexer (IOMUXC,0x020E0000): Hardware gates that supply peripheral clocks and route internal signals out to physicalBGAballs. - Peripheral IP Blocks (
UART1at0x02020000,GPIO1..5at0x0209C000+,ENET): Memory-mapped controllers whose registers sit at fixed physical bus addresses.
Because every hardware block along that chain can fail independently, the Cortex-A7 core can fetch and execute valid ARMv7-A instructions while an external LED stays dark (gated CCM clock or unmuxed pad) or the serial terminal stays blank (wrong UART baud divisor or TX/RX swap). Engineering bring-up therefore treats host compilation, byte transport, target RAM placement, CPU execution, and peripheral routing as separate, testable hypotheses.
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 .
mental model: 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.
definition (Cross-Compilation Host, Freestanding Target & Bring-Up Planes): 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.
Step through the four workbench boundaries below to see exactly what each observation proves—and what remains untested until the next stage:
- Step 1. Step 1 (Build Host): C11 host verifiers prove math and struct layout; the cross toolchain emits EM_ARM ELF32 and raw binary artifacts.
- Step 2. Step 2 (Transport): UART1 observes asynchronous console text; U-Boot tftpboot moves UDP blocks into RAM without executing them.
- Step 3. Step 3 (Target Memory): 128 KiB works before DDR init; DDR3 loadaddr 0x87800000 must avoid U-Boot's relocated code and stack.
- Step 4. Step 4 (Execution): Cortex-A7 fetches 32-bit ARM instructions from the entry address; NFS mounts remote directories only after Linux boots.
Figure 1.1b. Identify which hardware or software boundary each workbench observation actually tests.
Isolating UART, TFTP, and NFS Transport Planes
Why do bring-up engineers wire both a 3.3 V USB-to-UART adapter and an isolated lab Ethernet cable to a development board, and why must you never conflate UART, TFTP, and NFS when diagnosing a failure? Each channel requires a completely different stack of active silicon:
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 kernelVirtual 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.
Study the U-Boot 2025.x transfer sequence below from the target's perspective. Notice three distinct namespaces: bsp.bin is the host TFTP server's export filename, 0x87800000 (loadaddr) is a physical DDR3 address inside the i.MX6ULL 4 GiB address map (check bdinfo first so your download never overwrites U-Boot's own relocated image near the top of DDR3!), and ${filesize} records exact received byte count for crc32 verification before any jump.
learner@ksa:~/gl-e01/m01-l01$ bat workbench.uboot File: workbench.uboot # Example isolated lab assignments; adapt to your lab network. setenv ipaddr 192.0.2.20 setenv serverip 192.0.2.10 setenv loadaddr 0x87800000 printenv ipaddr serverip loadaddr # Run only after checking target RAM ownership and server policy. tftpboot ${loadaddr} bsp.bin crc32 ${loadaddr} ${filesize} # Downloading is not permission to jump to an uninspected image.Locking LP64 vs ILP32 Struct Widths and Window Bounds in C11
Throughout GL-E01, every lesson pairs real ARMv7-A target code with a native strict ISO C11 host verifier so you can prove bitfield algebra, binary header layouts, and state-machine invariants deterministically before touching hardware. Inspect Figure 1.1b to see the two classic host-tool bugs that abi_workbench_audit.c eliminates:
- Binary Struct Drift (
LP64vsILP32): If a host image-packing tool declares header fields asunsigned longorvoid *,gcconx86_64allocates8bytes per field plus alignment padding (24bytes total), whereasCortex-A7firmware expects4-byteILP32words (12or16bytes)—shiftingentry_addrby4+bytes! Locking every serialized field to<stdint.h>uint32_tand guarding with_Static_assert(sizeof(...) == 16U, ...)forces identical16-byte geometry on both machines. 32-Bit Unsigned Addition Wraparound (mod 2^32): Suppose a loader checks whether[start, start + length)fits inside[0x87800000, 0x87801000)usingstart >= base && start + length <= base + size. When a malformed header suppliesstart = 0xFFFFFFFCUandlength = 8U,ISO C11wraps32-bit unsigned addition modulo2^32to0x00000004U, which is<= 0x87801000U—accepting an out-of-bounds write across the4 GiBboundary! Checkingstart >= basefirst and then subtracting (offset = start - base,offset <= size && length <= size - offset) cannot overflow for anyuint32_tinputs.
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).
learner@ksa:~/gl-e01/m01-l01$ bat -H 9 -H 10 -H 11 -H 12 -H 18 -H 26 -H 27 -H 28 -H 29 abi_workbench_audit.c File: abi_workbench_audit.c #include <assert.h> #include <stdbool.h> #include <stdalign.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> struct armv7_load_desc { uint32_t load_addr; uint32_t entry_addr; uint32_t byte_len; uint32_t crc32_val; }; _Static_assert(sizeof(struct armv7_load_desc) == 16U, "descriptor size"); _Static_assert(alignof(struct armv7_load_desc) == 4U, "descriptor align"); static bool host_is_little_endian(void) { const uint32_t probe = UINT32_C(0x04030201); const unsigned char *bytes = (const unsigned char *)&probe; return bytes[0] == 1U && bytes[1] == 2U && bytes[2] == 3U && bytes[3] == 4U; } static bool ram_window_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length) { if (length == 0U || start < base) return false; uint32_t offset = start - base; return offset <= size && length <= size - offset; } int main(void) { assert(sizeof(uint32_t) == 4U && alignof(uint32_t) == 4U); assert(offsetof(struct armv7_load_desc, crc32_val) == 12U); assert(host_is_little_endian()); assert(ram_window_fits(0x87800000U, 0x1000U, 0x87800000U, 0x1000U)); assert(!ram_window_fits(0x87800000U, 0x1000U, 0x87800000U, 0x1001U)); assert(!ram_window_fits(0x87800000U, 0x1000U, 0x877fffffU, 1U)); assert(!ram_window_fits(0x87800000U, 0x1000U, UINT32_MAX, 8U)); assert(!ram_window_fits(0x87800000U, 0x1000U, 0x87800000U, 0U)); printf("abi_desc=%zuB align=%zuB host_ptr=%zuB arm32_ptr=4B le=%d window=ok\n", sizeof(struct armv7_load_desc), alignof(struct armv7_load_desc), sizeof(void *), host_is_little_endian() ? 1 : 0); return 0; }- Lock image-descriptor fields to uint32_t so LP64 hosts and ILP32 Cortex-A7 targets agree on a 16-byte layout.
- Probe little-endian byte order explicitly rather than assuming host memory matches ARMv7-A target byte lanes.
- Validate start >= base before subtracting so unsigned wrap near UINT32_MAX cannot masquerade as an in-bounds span.
Executing the ABI and Placement Verifier
Compile and run abi_workbench_audit.c under -std=c11 -Wall -Wextra -Werror -pedantic. Observe host_ptr=8B versus arm32_ptr=4B alongside the 16B descriptor proof, then inject the wraparound bug (start + length <= base + size) on (UINT32_MAX, 8U) in a scratch edit to watch assert(!ram_window_fits(...)) catch the mod 2^32 wrap immediately before restoring the subtraction check.
learner@ksa:~/gl-e01/m01-l01gcc -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-l01learner@ksa:~/gl-e01/m01-l01strace -e trace=write,exit_group \./abi_workbench_auditwrite(1, "abi_desc=16B align=4B host_ptr=8"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++Evidence Boundaries, Wraparound Proofs, and Channel Trade-Offs
Look at the strace trace above (write(1, ..., 62) followed by exit_group(0) on an x86_64 host): that syscall boundary is visual proof of why host models and bare-metal targets differ. On x86_64, printf hands 62 bytes to a running OS kernel; on freestanding Cortex-A7 silicon, there is no write syscall—every character on UART1 will require your own CCM clock gate, IOMUXC pin mux, baud-rate divisor, and TX FIFO loop. Likewise, keep your engineering claims exact: this C11 check proves 16-byte fixed-width layout and overflow-free [base, base + size) window math, while DDR3 calibration, 3.3 V serial levels, and Cortex-A7 fetch require target measurements.
| Workbench Channel | Active Stage | Transport / Width | What Success Proves (and Cannot Prove) |
|---|---|---|---|
Host ISO C11 verifier (gcc) | Pre-transfer build | 64-bit host process (LP64) | Proves fixed-width uint32_t layout and range math; proves 0 target bus or pad facts |
UART serial console (115200 8N1) | Bootloader / runtime | Asynchronous 3.3 V TX/RX | Proves console clock, pad mux, baud rate, and TX code path; proves 0 Ethernet/NFS health |
TFTP image load (tftpboot) | U-Boot 2025.x | UDP blocks into RAM (loadaddr) | Proves byte delivery and filesize/crc32; does not prove valid EM_ARM code or stack |
NFS root mount (nfsroot=) | Linux kernel 6.12 | RPC/TCP or UDP VFS mount | Proves kernel TCP/IP + VFS export visibility; unusable before a kernel/network stack runs |
Later: Lesson m01-l02 opens the compiled binary itself to inspect how ARM AAPCS32 passes integer and VFPv4 floating-point arguments and how ELF32 separates file-backed .text/.data bytes from zero-initialized .bss RAM.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Auditing a Mixed-Width Header & OCRAM Span
Step 1 (Stride Calculation): On x86_64 (LP64), compute offsetof(struct bad_hdr, entry) and sizeof(struct bad_hdr) for struct bad_hdr { unsigned long magic; uint32_t len; void *entry; }; (hint: 8-byte entry forces 4 bytes of alignment padding after len, placing entry at +16 and size at 24 B, versus +8 and 12 B on 32-bit Cortex-A7). Step 2 (Fixed-Width Fix): Replace every field with uint32_t target equivalents and verify sizeof == 12 B on both hosts. Step 3 (OCRAM Window): Evaluate ram_window_fits(0x00900000U, 0x00020000U, 0x0091FF00U, 0x200U) for 128 KiB OCRAM (0x1FF00 + 0x200 overruns 0x20000 by 256 bytes -> false).
Independent Practice: Multi-Region Target Memory Map Auditor (memmap_audit.c)
Write a standalone ISO C11 program memmap_audit.c encoding the i.MX6ULL bring-up map: Boot ROM workspace [0x00900000, 0x00907000) (reserved), free OCRAM [0x00907000, 0x00920000) (writable), payload DDR3 [0x87800000, 0x87900000) (writable), and U-Boot top-of-RAM [0x9FF00000, 0xA0000000) (reserved). Implement int validate_download(uint32_t addr, uint32_t len) requiring 4-byte alignment, containment inside one writable window, zero reserved overlap, and wraparound immunity across 7 positive/negative test vectors.
? check 1 · 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?
- [x] Byte delivery into
0x87800000succeeded; target entry address,EM_ARMISA state, stack setup, orUARTinit insidebsp.binnow requires inspection - [ ] The
Cortex-A7executedbsp.bincleanly, and serial silence proves the EthernetTFTPcable dropped packets - [ ] External
DDR3hardware is defective, because a matchingcrc32rules out any software entry or stack mistake
Answer: Byte delivery into 0x87800000 succeeded; target entry address, EM_ARM ISA state, stack setup, or UART init inside bsp.bin now requires inspection
Why: 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.
? check 2 · 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?
- [ ]
ISO C11treatsuint32_taddition overflow as undefined behavior that crashesgcc - [ ] Checking
length <= sizealone guarantees any4-byte-alignedstartfits insideDDR3 - [x] Well-defined
32-bit unsigned wrap modulo2^32turns0xFFFFFFFCU + 8Uinto0x00000004U, falsely passing<= base + size
Answer: Well-defined 32-bit unsigned wrap modulo 2^32 turns 0xFFFFFFFCU + 8U into 0x00000004U, falsely passing <= base + size
Why: 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.
? check 3 · Retrieval: what does a 0 exit code from the native x86_64 abi_workbench_audit binary prove?
- [ ] That
i.MX6ULLMMDCDDR3calibration,3.3 VUART1pads, andU-BootEthernet links are ready to boot - [x] That the
16-byteuint32_tdescriptor layout and overflow-safe RAM window predicate hold on all tested fixtures in host memory - [ ] That the attached
Cortex-A7core fetched and executed the cross-compiled binary
Answer: That the 16-byte uint32_t descriptor layout and overflow-safe RAM window predicate hold on all tested fixtures in host memory
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m01_l01
Step 1 (Build Host): C11 host verifiers prove math and struct layout; the cross toolchain emits EM_ARM ELF32 and raw binary artifacts.
reveals: step1
highlights: step1
Step 2 (Transport): UART1 observes asynchronous console text; U-Boot tftpboot moves UDP blocks into RAM without executing them.
reveals: step2
highlights: step2
Step 3 (Target Memory): 128 KiB OCRAM works before DDR init; DDR3 loadaddr 0x87800000 must avoid U-Boot's relocated code and stack.
reveals: step3
highlights: step3
Step 4 (Execution): Cortex-A7 fetches 32-bit ARM instructions from the entry address; NFS mounts remote directories only after Linux boots.
reveals: step4
highlights: step4
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.
Why Binary Objects Need a Hardware Calling Convention
Once a C compiler translates float gain(float a, float b); into 32-bit ARMv7-A machine instructions, parameter names, C types, and header files vanish completely. All that exists in silicon is a bank of 32-bit general-purpose registers (r0..r15), an optional Vector Floating-Point / NEON register file (s0..s31 / d0..d31), and raw bytes in RAM. If main.o (compiled on Monday) calls gain.o (compiled into a library on Tuesday), how do those two independently compiled .o files agree on which register holds a, where the return value lands, which registers gain is allowed to overwrite, and how the stack pointer is aligned? That machine-level treaty is the Application Binary Interface (ABI)—specifically the Arm Architecture Procedure Call Standard (AAPCS32 / EABI).
Trace both halves of the Cortex-A7 register contract in Figure 1.2a before reading a line of assembly:
- Core Integer & Pointer Contract (
AAPCS32): The first four32-bit integer or pointer arguments pass inr0..r3, and32-bit results return inr0(64-bit integers use an aligned register pair such asr0:r1). Arguments5and beyond spill onto the stack ([sp, #0],[sp, #4], ...). Crucially, registers split into two ownership classes:r0..r3andr12(IP) are caller-saved scratch (any function you call may destroy them freely), whereasr4..r11andr13(SP) are callee-saved (if a callee touchesr4, it must pushr4on entry and restore it before returning; noter9often carries platform-reserved state in bootloaders, so avoid casual scratch use). At every public call boundary,SPmust be8-byte aligned (SP mod 8 == 0). - Soft-Float vs VFPv4 Hard-Float (
-mfloat-abi=hard): Under the base/soft-float ABI (arm-none-eabi-mfloat-abi=soft),floatvalues are bit-copied into integer registersr0..r3and computed via software routines (or softfp wrappers). Under the hard-float variant (arm-linux-gnueabihf,.eabi_attribute 28, 1),floatanddoublearguments pass directly inVFPv4hardware registerss0..s15/d0..d7(s16..s31/d8..d15are callee-saved). Mixing the two is catastrophic if unchecked: a soft-float caller places1.5f(0x3FC00000) intor0, while a hard-float callee reads uninitializeds0! Equally vital for bare-metal engineers: on a coldCortex-A7reset, theVFPv4/NEONsilicon is powered off/disabled by hardware—executing even a singlevadd.f32or compiler-generatedvldrstruct copy triggers an Undefined Instruction exception until privileged startup enablesCP15CPACR(CP10/CP11) and setsFPEXC.EN = 1!
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).
mental model: 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, .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 .
definition (AAPCS32, Hard-Float EABI & ELF32 Section/Segment Roles): 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).
Walk through the four-stage contract from C call site to runtime RAM layout below:
- Step 1. Step 1 (C Call Site): Word arguments enter in r0..r3; hard-float variants pass eligible floats in VFPv4 registers s0..s15.
- Step 2. Step 2 (Object Contract): readelf -h -A proves ELFCLASS32, little-endian LSB, EM_ARM (40), cortex-a7, and Tag_ABI_VFP_args.
- Step 3. Step 3 (File Bytes): .text, .rodata, and .data occupy p_filesz bytes on flash/TFTP; raw .bin strips headers and symbols.
- Step 4. Step 4 (Runtime Memory): SHT_NOBITS .bss adds (p_memsz - p_filesz) RAM bytes that bare-metal startup must zero before main().
Figure 1.2b. Never trust a .o or .bin filename: inspect ELF32 machine class, VFP ABI attributes, and .bss expansion before execution.
Inspecting AAPCS32 Leaf Assembly, VFPv4 Attributes, and ELF Headers
Why does an ELF file have both Section Headers (.text, .rodata, .data, .bss, .ARM.attributes) and Program Headers (PT_LOAD), and why do we keep the .elf file even when flashing a stripped .bin? Sections are the linker's view during compilation: relocatable .o files have sections and relocation records (0 program headers) so ld can merge all .text blocks and patch symbol addresses. Program headers (Elf32_Phdr) are the loader's view in a linked executable: each 32-byte PT_LOAD entry tells a loader to copy p_filesz initialized bytes from flash/load address p_paddr (LMA) into p_memsz runtime bytes at p_vaddr (VMA), where the extra p_memsz - p_filesz tail is SHT_NOBITS .bss! Why did ELF designers make .bss NOBITS? Because storing 64 KiB of literal 0x00 bytes for static uint8_t rx_ring[65536]; inside SPI NOR flash or a TFTP packet wastes storage and boot time when a 4-instruction loop in _start can zero RAM in microseconds!
Examine the two Cortex-A7 leaf functions in target.S below. Notice .eabi_attribute 28, 1 (Tag_ABI_VFP_args = 1), which stamps hard-float ABI metadata into .ARM.attributes. Because neither add_words (r0 <- r0 + r1) nor add_floats (s0 <- s0 + s1) touches callee-saved r4..r11 / d8..d15 or calls another subroutine, neither allocates stack space, and both return via bx lr (which branches to LR and sets Thumb state from LR[0]—a subroutine return, distinct from hardware exception returns covered in Module 2).
learner@ksa:~/gl-e01/m01-l02$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .fpu neon-vfpv4 .eabi_attribute 28, 1 .arm .text .global add_words .type add_words, %function add_words: add r0, r0, r1 bx lr .size add_words, .-add_words .global add_floats .type add_floats, %function add_floats: vadd.f32 s0, s0, s1 bx lr .size add_floats, .-add_floatsAuditing 32-Bit ELF Headers and NOBITS Segment Expansion in C11
Compare the exact byte offsets in Figure 1.2b against elf32_phdr_audit.c below. Notice that our x86_64 host tool never casts raw bytes to Elf64_Ehdr or unaligned pointers—it decodes little-endian 16-bit and 32-bit fields explicitly via rd_le16() and rd_le32(). Inside the 52-byte Elf32_Ehdr, bytes 0..3 hold 0x7F 'E' 'L' 'F', byte 4 (EI_CLASS = 1) proves ELF32, byte 5 (EI_DATA = 1) proves two's-complement little-endian, offset +18 (e_machine = 40) proves EM_ARM (rejecting 62 = EM_X86_64!), offset +40 (e_ehsize) equals 52, and offset +42 (e_phentsize) equals 32. Inside the 32-byte Elf32_Phdr, .text (128 B) + .rodata (16 B) + .data (8 B) give p_filesz = 152, while 64 B of .bss gives p_memsz = 216 (bss_tail = 216 - 152 = 64), rejecting both p_memsz < p_filesz (151) and 32-bit p_vaddr wraparound (0xFFFFFF80 + 216).
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).
learner@ksa:~/gl-e01/m01-l02$ bat -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 elf32_phdr_audit.c File: elf32_phdr_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> static uint16_t rd_le16(const unsigned char *p) { return (uint16_t)((uint16_t)p[0] | ((uint16_t)p[1] << 8)); } static uint32_t rd_le32(const unsigned char *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); } static bool valid_arm_ehdr(const unsigned char *eh, size_t n) { return n >= 52U && eh[0] == 0x7fU && eh[1] == 'E' && eh[2] == 'L' && eh[3] == 'F' && eh[4] == 1U && eh[5] == 1U && rd_le16(eh + 18) == 40U && rd_le16(eh + 40) == 52U && rd_le16(eh + 42) == 32U; } static bool valid_pt_load(const unsigned char *ph, uint32_t *bss_tail) { uint32_t p_type = rd_le32(ph + 0), p_vaddr = rd_le32(ph + 8); uint32_t p_paddr = rd_le32(ph + 12), p_filesz = rd_le32(ph + 16); uint32_t p_memsz = rd_le32(ph + 20); if (p_type != 1U || p_memsz < p_filesz || p_memsz == 0U) return false; if (p_memsz - 1U > UINT32_MAX - p_vaddr) return false; if (p_filesz > 0U && p_filesz - 1U > UINT32_MAX - p_paddr) return false; *bss_tail = p_memsz - p_filesz; return true; } static void wr_le32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * i)); } int main(void) { unsigned char eh[52] = {0x7fU, 'E', 'L', 'F', 1U, 1U, 1U}; eh[18] = 40U; eh[40] = 52U; eh[42] = 32U; assert(valid_arm_ehdr(eh, sizeof eh) && !valid_arm_ehdr(eh, 51U)); eh[4] = 2U; assert(!valid_arm_ehdr(eh, sizeof eh)); eh[4] = 1U; eh[18] = 62U; assert(!valid_arm_ehdr(eh, sizeof eh)); eh[18] = 40U; unsigned char ph[32] = {0U}; wr_le32(ph + 0, 1U); /* PT_LOAD */ wr_le32(ph + 8, 0x87800000U); /* p_vaddr */ wr_le32(ph + 12, 0x877ff400U); /* p_paddr */ wr_le32(ph + 16, 152U); /* p_filesz = 128 + 16 + 8 */ wr_le32(ph + 20, 216U); /* p_memsz = 152 + 64 (.bss) */ uint32_t bss = 0U; assert(valid_pt_load(ph, &bss) && bss == 64U); wr_le32(ph + 20, 151U); assert(!valid_pt_load(ph, &bss)); wr_le32(ph + 20, 216U); wr_le32(ph + 8, 0xffffff80U); assert(!valid_pt_load(ph, &bss)); printf("ELF32 EM_ARM=40 ehdr=52B phdr=32B filesz=152 memsz=216 bss=%u\n", bss); return 0; }- Verify ELF magic, ELFCLASS32 (1), little-endian data (1), EM_ARM (40), and 52/32-byte header sizes.
- Require p_memsz >= p_filesz so NOBITS .bss growth is accepted while truncated memory spans fail.
- Check p_memsz - 1 <= UINT32_MAX - p_vaddr to reject 32-bit virtual-address wraparound.
Cross-Assembling for Cortex-A7 and Verifying ELF Metadata
Run the native elf32_phdr_audit verifier first, then cross-assemble target.S with clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm and inspect the real emitted ELF32 header and aeabi attribute section via readelf -h -A target.o. Match Class: ELF32, Machine: ARM, Size of this header: 52 (bytes), Number of program headers: 0 (relocatable .o), and Tag_ABI_VFP_args: VFP registers directly against our byte decoder.
learner@ksa:~/gl-e01/m01-l02gcc -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-l02clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m01-l02readelf -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: ARM Version: 0x1 Entry point address: 0x0 Start of program headers: 0 (bytes into file) Start of section headers: 252 (bytes into file) Flags: 0x5000000, Version5 EABI Size of this header: 52 (bytes) Size of program headers: 0 (bytes) Number of program headers: 0 Size of section headers: 40 (bytes) Number of section headers: 5 Section header string table index: 1Attribute Section: aeabiFile Attributes Tag_CPU_name: "cortex-a7" Tag_CPU_arch: v7 Tag_CPU_arch_profile: Application Tag_ARM_ISA_use: Yes Tag_THUMB_ISA_use: Thumb-2 Tag_FP_arch: VFPv4 Tag_Advanced_SIMD_arch: NEONv1 with Fused-MAC Tag_ABI_VFP_args: VFP registers Tag_CPU_unaligned_access: None Tag_MPextension_use: Allowed Tag_DIV_use: Allowed in v7-A with integer division extension Tag_Virtualization_use: TrustZone and Virtualization Extensionslearner@ksa:~/gl-e01/m01-l02learner@ksa:~/gl-e01/m01-l02strace -e trace=write,exit_group \./elf32_phdr_auditwrite(1, "ELF32 EM_ARM=40 ehdr=52B phdr=32"..., 62) = 62exit_group(0) = ?+++ exited with 0 +++File Payload vs Runtime RAM Footprint and Float-ABI Trade-Offs
Always archive the linked .elf and linker .map file beside any objcopy -O binary output! When objcopy -O binary app.elf app.bin strips an executable for U-Boot or the i.MX6ULL Boot ROM, it discards Elf32_Ehdr, Elf32_Phdr, .symtab, .ARM.attributes, and every trace of .bss (p_memsz - p_filesz). Without app.elf, you cannot verify Tag_ABI_VFP_args or map a crash PC (0x878001A4) back to a C line. Equally important: readelf proving Tag_FP_arch: VFPv4 is a static file fact, whereas CPACR + FPEXC.EN enabling vadd.f32 on silicon is a privileged runtime fact.
| Build / Artifact Choice | Register / File Impact | Hardware Precondition | Failure Mode When Mismatched |
|---|---|---|---|
-mfloat-abi=soft (integer EABI) | Floats pass in r0..r3; soft-fp helpers linked | Pure integer Cortex-A7 pipeline (0 VFP setup) | Link error or silent NaN/garbage if mixed with -mfloat-abi=hard objects |
-mfloat-abi=hard (VFPv4) | Floats pass in s0..s15 (0 GPR copy overhead) | CPACR CP10/11 + FPEXC.EN must be enabled first | Undefined Instruction trap on first vldr/vpush/vadd.f32 after reset |
Linked ELF32 executable (.elf) | Retains 52 B Ehdr, Phdr, .symtab, .ARM.attributes | Parsed by host tools / debuggers (readelf, gdb) | Rejected by i.MX6ULL Boot ROM if flashed raw without IVT/.bin extraction |
Stripped raw binary (objcopy -O binary) | p_filesz bytes only (0 .bss bytes, 0 headers) | _start must relocate .data and zero .bss | Silent corruption if .bss goes unzeroed or load address drifts from p_vaddr |
Later: Lesson m01-l03 moves from binary contracts to hardware schematics, deriving active-low CMOS sink currents from Kirchhoff's Voltage Law and mapping package balls to 32-bit GPIO register masks.
Common Production Pitfalls
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/ code with -mfloat-abi=soft -mno-unaligned-access (or explicitly enable CP10/CP11 + FPEXC.EN in assembly before calling C).
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).
Practice & Retrieval
Guided Practice: Decoding a Bare-Metal OCRAM Segment Header
Step 1 (Little-Endian Decode): Given Elf32_Phdr slices ph[8..11] = {0x00, 0x70, 0x90, 0x00}, ph[16..19] = {0x80, 0x04, 0x00, 0x00}, and ph[20..23] = {0x00, 0x06, 0x00, 0x00}, compute p_vaddr, p_filesz, p_memsz, and the NOBITS .bss byte count (0x00907000, 1152 B, 1536 B, leaving 384 B of .bss). Step 2 (LMA vs VMA): If .data (64 B initialized, 128 B .bss) has p_vaddr = 0x87810000 and p_paddr = 0x87800480, state which address objcopy -O binary uses to position those 64 bytes (p_paddr, the LMA). Step 3 (Attribute Check): Predict how Tag_ABI_VFP_args changes in readelf -A if .eabi_attribute 28, 1 is changed to .eabi_attribute 28, 0.
Independent Practice: Multi-Segment ELF32 Overlap & Entry Verifier (elf32_image_check.c)
Extend elf32_phdr_audit.c into elf32_image_check.c accepting e_entry (Elf32_Ehdr + 24) and an array of Elf32_Phdr structures. Verify that e_entry falls inside a PT_LOAD segment carrying PF_X (0x1 in p_flags at +24), (p_vaddr % p_align) == (p_offset % p_align) holds whenever power-of-two p_align > 1 (+28), and no two PT_LOAD segments overlap in [p_vaddr, p_vaddr + p_memsz) or [p_paddr, p_paddr + p_filesz).
? check 1 · 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?
- [ ]
TFTPtruncated the upperVFPregisters during binary download - [ ] Both
.ofiles lacked matching C header filenames during compilation - [x] One object was built for soft-float (
AAPCSbase) and the other for hard-float (AAPCS-VFP-mfloat-abi=hard)
Answer: One object was built for soft-float (AAPCS base) and the other for hard-float (AAPCS-VFP -mfloat-abi=hard)
Why: 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.
? check 2 · Why does adding static uint8_t dma_desc[64]; (uninitialized) increase Elf32_Phdr.p_memsz by 64 bytes while leaving p_filesz unchanged?
- [ ] The
Cortex-A7hardware MMU dynamically allocates missing.bsspages on first fault - [x] Zero-initialized globals sit in
SHT_NOBITS.bss, recording a runtime RAM reservation (p_memsz - p_filesz) that startup zeroes without storing64zero bytes in the file - [ ] The linker optimizes away unused arrays so they consume zero RAM at runtime
Answer: Zero-initialized globals sit in SHT_NOBITS .bss, recording a runtime RAM reservation (p_memsz - p_filesz) that startup zeroes without storing 64 zero bytes in the file
Why: 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).
? check 3 · 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?
- [x] Inspecting
Elf32_Ehdr(ELFCLASS32, little-endian,EM_ARM = 40) and.ARM.attributes(Tag_CPU_arch,Tag_ABI_VFP_args) viareadelf -h -A - [ ] Checking that the filename ends in
.oor.elfand compiled with0warnings - [ ] Verifying that
tftpboottransferred the file into0x87800000with0dropped UDP packets
Answer: Inspecting Elf32_Ehdr (ELFCLASS32, little-endian, EM_ARM = 40) and .ARM.attributes (Tag_CPU_arch, Tag_ABI_VFP_args) via readelf -h -A
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m01_l02
Step 1 (C Call Site): Word arguments enter in r0..r3; hard-float variants pass eligible floats in VFPv4 registers s0..s15.
reveals: step1
highlights: step1
Step 2 (Object Contract): readelf -h -A proves ELFCLASS32, little-endian LSB, EM_ARM (40), cortex-a7, and Tag_ABI_VFP_args.
reveals: step2
highlights: step2
Step 3 (File Bytes): .text, .rodata, and .data occupy p_filesz bytes on flash/TFTP; raw .bin strips headers and symbols.
reveals: step3
highlights: step3
Step 4 (Runtime Memory): SHT_NOBITS .bss adds (p_memsz - p_filesz) RAM bytes that bare-metal startup must zero before main().
reveals: step4
highlights: step4
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.
CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
Beginners often assume "writing 1 to a GPIO pin turns an LED on, and writing 0 turns it off." On industrial ARM boards, writing 1 frequently turns the LED off, and writing 0 turns it brightly on! Why? Because a GPIO pin is not a magic software boolean—it is a pair of physical complementary MOSFET switches (CMOS) wired between the pad's I/O supply rail (NVCC_GPIO = 3.30 V) and board ground (GND = 0 V). Look inside the pad stage in Figure 1.3a:
- High-Side
PMOSSource (DR = 1): Connects the package ball up to3.30 V(V_OH). If an external load runs from the pin through a resistor and LED toGND(active-high source topology, right panel), current flows out of thePMOStransistor into the LED whenDR = 1. - Low-Side
NMOSSink (DR = 0): Connects the package ball down toGNDwith a small transistor drop (V_OL = 0.15 V = 150 mV). On most carrier boards (active-low sink topology, left panel), the hardware designer wires3.30 V -> R (1000 ohm) -> LED Anode | Cathode -> GPIO1_IO03. WhenDR[3] = 1, both ends of the LED+resistor branch sit near3.30 V(0 Vpotential difference -> zero current -> LED dark!). WhenDR[3] = 0, theNMOSswitch closes toGND: applying Kirchhoff's Voltage Law (KVL) around the loop givesI_sink = (V_DD - V_F - V_OL) / R = (3300 - 2050 - 150) mV / 1000 ohm = 1.10 mA(1100 uA), illuminating the LED well below a conservative8.0 mA(8000 uA) pad current limit!
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).
Why do board designers prefer active-low sinking for status LEDs? Historically and physically, silicon NMOS electron mobility exceeds PMOS hole mobility (NMOS sinks low with lower on-resistance than PMOS sources high), and keeping indicator current off the 's high-side NVCC rail reduces supply bounce—provided the external series resistor R limits I_sink safely (R = 100 ohm would pull 11.0 mA, overstressing the pad!).
mental model: 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.
definition (Schematic Net Continuity, Active-Low Sink & Peripheral Offset Geometry): 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 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.
Trace the complete four-stage path from external LED load to 32-bit register bitmask below:
- Step 1. Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
- Step 2. Step 2 (Carrier Net): Follow net label LED0 to its exact board-to-board header pin and check shared pulls or boot straps.
- Step 3. Step 3 (Core Pad): Match the mating SOM connector pin to SoC ball GPIO1_IO03 (Bank 1, local bit index 3).
- Step 4. Step 4 (Register Mask): Compute Base + Offset (0x0209C000) and update bit 3 via UINT32_C(1) << pin without touching 31 siblings.
Figure 1.3b. Never guess polarity or GPIO numbers from net names: trace Load -> Connector Pin -> SoC Ball -> Masked Base+Offset.
Tracing Carrier Nets Across Connectors to Physical GPIO Registers
Most production i.MX6ULL hardware splits into two schematics: a compact Core SOM (housing the SoC, DDR3, PMIC, and eMMC/NAND) and a Carrier Board (housing LEDs, relays, UART headers, and Ethernet PHYs). Searching the SOM schematic PDF for LED0 often returns zero hits because the carrier net LED0 terminates on header J1 pin 14, while the mating SOM connector P1 pin 14 names that exact copper conductor GPIO1_IO03! Always build the four-column trace shown at the top of Figure 1.3b (Load Terminal -> Carrier Net/Pin -> SOM Pin/Ball -> Bank/Bit/Address) and note whether any external pull resistor shares a reset BOOT_CFG strap pin.
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).
Once GPIO1_IO03 maps to Bank GPIO1 (0x0209C000), local bit 3, examine how schematic_gpio.c translates logical intent into an electrical level without scattering inverted 0/1 magic numbers across application code:
- Bounds-First Unsigned Shift (
pin < 32U+UINT32_C(1) << pin): InISO C11, shifting by>= 32on a32-bit type—or shifting signed literal1into sign bit31(1 << 31)—is Undefined Behavior (UB)! Checkingif (pin >= 32U) return false;before evaluatingUINT32_C(1) << pineliminates both traps. - Boolean XOR Polarity (
high = (on != active_low)): Whenactive_lowistrueand caller requestson = true,true != trueevaluates tofalse(0), clearing bit3(value & ~mask) to sink current while leaving all31siblingGPIO1pins untouched.
learner@ksa:~/gl-e01/m01-l03$ bat schematic_gpio.c File: schematic_gpio.c #include <stdint.h> #include <stdbool.h> static volatile uint32_t *const gpio1_dr = (volatile uint32_t *)(uintptr_t)0x0209c000U; bool led_write(unsigned pin, bool on, bool active_low) { if (pin >= 32U) return false; const uint32_t mask = UINT32_C(1) << pin; const bool high = on != active_low; uint32_t value = *gpio1_dr; /* exclusive bank ownership required */ value = high ? value | mask : value & ~mask; *gpio1_dr = value; return true; }Verifying KVL Sink Headroom, Polarity XOR, and Shift Safety in C11
Never dereference (volatile uint32_t *)0x0209c000U in a host process (where 0x0209C000 is an unmapped virtual address, not an i.MX6ULL IPG peripheral bus!). Instead, sink_drive_audit.c verifies both integer microampere KVL circuit analysis and 32-bit RAM-modeled GPIO1_DR bit preservation on the host. Notice how sink_current_ua() checks vdd_mv <= vf_mv + vol_mv before subtracting so an under-volted 1.8 V (1800 mV) rail driving a 2.05 V (2050 mV) red LED returns false cleanly instead of wrapping unsigned headroom to 4.29 GV, and rejects R = 100 ohm (11000 uA > 8000 uA).
learner@ksa:~/gl-e01/m01-l03$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 19 -H 20 -H 21 -H 22 -H 23 sink_drive_audit.c File: sink_drive_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> static bool sink_current_ua(uint32_t vdd_mv, uint32_t vf_mv, uint32_t vol_mv, uint32_t r_ohm, uint32_t max_ua, uint32_t *out_ua) { if (r_ohm == 0U || vdd_mv <= vf_mv + vol_mv) return false; uint32_t headroom_mv = vdd_mv - vf_mv - vol_mv; uint32_t ua = (headroom_mv * 1000U) / r_ohm; if (ua == 0U || ua > max_ua) return false; *out_ua = ua; return true; } static bool set_pin_level(uint32_t *dr, unsigned pin, bool on, bool active_low) { if (dr == NULL || pin >= 32U) return false; uint32_t mask = UINT32_C(1) << pin; *dr = (on != active_low) ? (*dr | mask) : (*dr & ~mask); return true; } int main(void) { uint32_t ua = 0U; assert(sink_current_ua(3300U, 2050U, 150U, 1000U, 8000U, &ua) && ua == 1100U); assert(sink_current_ua(3300U, 2100U, 0U, 1200U, 8000U, &ua) && ua == 1000U); assert(!sink_current_ua(3300U, 2050U, 150U, 100U, 8000U, &ua)); assert(!sink_current_ua(1800U, 2050U, 150U, 1000U, 8000U, &ua)); assert(0x0209c000U + 0x04U == 0x0209c004U); uint32_t dr = 0xa5a5a5a5U, before = dr; assert(set_pin_level(&dr, 3U, true, true)); assert((dr & 8U) == 0U && (dr & ~8U) == (before & ~8U)); assert(set_pin_level(&dr, 3U, false, true) && (dr & 8U) != 0U); assert(set_pin_level(&dr, 3U, false, false) && (dr & 8U) == 0U); assert(set_pin_level(&dr, 3U, true, false) && (dr & 8U) != 0U); before = dr; assert(!set_pin_level(&dr, 32U, true, true) && dr == before); printf("sink_ua=1100 gdir=0x%08X dr_active_low_on=0x%08X\n", 0x0209c000U + 0x04U, before & ~8U); return 0; }- Evaluate (vdd_mv - vf_mv - vol_mv) * 1000 / r_ohm in uint32_t microamps and enforce the pad sink ceiling.
- Reject pin >= 32 before shifting UINT32_C(1) << pin so C11 shift-width undefined behavior never executes.
- Map logical assertion through (on != active_low) while preserving all 31 sibling bits in *dr.
Running the Circuit Current and Mask Verifier
Execute sink_drive_audit on the workstation and cross-compile schematic_gpio.c into freestanding ARMv7-A machine code (target.o) with -mfloat-abi=soft -ffreestanding -Werror to confirm clean target code generation alongside host algebraic verification.
learner@ksa:~/gl-e01/m01-l03gcc -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-l03clang --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-l03learner@ksa:~/gl-e01/m01-l03strace -e trace=write,exit_group \./sink_drive_auditwrite(1, "sink_ua=1100 gdir=0x0209C004 dr_"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++End-to-End Signal Provenance and Drive Topology Trade-Offs
Compare the four drive and register patterns in the matrix below. Notice that led_write() updating GPIO1_DR at 0x0209C000 is necessary but still not sufficient to light the physical LED on cold silicon: Module 3 will add CCM_CCGR1 clock gating, IOMUXC ALT5 pad routing, SW_PAD_CTL DSE output drive, and GPIO1_GDIR (0x0209C004) output direction!
| Circuit / Software Choice | Drive Equation / Expression | Pin Stress & Sibling Safety | Failure Mode When Misapplied | |
|---|---|---|---|---|
direct GPIO sink (<= 2 mA) | dr &= ~(1U << pin) asserts; I = (V_DD - V_F - V_OL)/R | Safe within pad I_OL budget; 31 siblings preserved | Driving 1 turns LED off; omitting R overcurrents pad bond wire | |
Active-high direct GPIO source | `dr \ | = (1U << pin) asserts; I = (V_OH - V_F)/R` | Pulls current from NVCC rail; 31 siblings preserved | Fails to conduct if V_OH rail (1.8 V) sits below V_F (2.05 V) |
Whole-bank write *gpio1_dr = 0U | 1 store, 0 mask logic | Unsafe: clobbers all 31 neighboring GPIO1 pins | Asserts or drops unrelated relays, chip-selects, and reset lines on GPIO1 | |
Unchecked shift 1 << pin (signed int) | Undefined behavior for pin >= 31 in ISO C11 | Corrupts sign bit at pin == 31 or shifts out of bounds | Traps under -fsanitize=undefined or toggles wrong bit |
Later: Module 2 (m02-l01..m02-l03) dives inside the Cortex-A7 core itself—processor modes, banked registers, CP15 SCTLR/VBAR, load/store writeback, and 8-byte-aligned assembly stack frames—before Module 3 lights the physical LED in assembly and C.
Common Production Pitfalls
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.
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.
Practice & Retrieval
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 using a low-forward-voltage LED (V_F = 1200 mV, V_OL = 120 mV); solve (1800 - 1200 - 120) * 1000 / 1600 for series resistor R at 1600 uA (300 ohm). Step 2 (Pin 31 Polarity): Starting from dr = 0x80000008U, evaluate set_pin_level(&dr, 31U, true, true) in hex (0x00000008U). Step 3 (Offset Math): Given GPIO5 base 0x020AC000, state the physical addresses of GPIO5_DR (+0x00) and GPIO5_GDIR (+0x04).
Independent Practice: Worst-Case Tolerance & Netlist Auditor (board_led_spec.c)
Write a standalone ISO C11 verifier board_led_spec.c evaluating struct led_circuit across supply tolerance (vdd_min_mv, vdd_max_mv), LED drop spread (vf_min_mv, vf_max_mv), vol_max_mv, and resistor tolerance (r_nominal_ohm, r_tol_pct). Assert both worst-case visibility (I_min >= 500 uA at vdd_min, vf_max, R_max) and pad safety (I_max <= 6000 uA at vdd_max, vf_min, vol = 0, R_min) across 6 valid and faulted circuits.
? check 1 · 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?
- [ ] Leaving
GPIO1_IO03configured as a high-impedance input so the latch floats - [x] Driving
GPIO1_IO03output low (0) so the pad'sNMOStransistor sinks current to ground - [ ] Driving
GPIO1_IO03output high (1) so both terminals of the branch sit at3.3 V
Answer: Driving GPIO1_IO03 output low (0) so the pad's NMOS transistor sinks current to ground
Why: 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).
? check 2 · A helper computes uint32_t mask = 1U << pin; if (pin >= 32U) return false;. Why is this C11 code defective?
- [x] For
pin >= 32U, the out-of-range shift executes before the bounds check, invokingISO C11Undefined Behavior - [ ] Unsigned shifts automatically wrap
pin == 32UontoGPIO2bit0safely - [ ]
1U << pinclears neighboring bits unlesssigned int1 << pinis used
Answer: For pin >= 32U, the out-of-range shift executes before the bounds check, invoking ISO C11 Undefined Behavior
Why: 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.
? check 3 · Retrieval: does computing 0x0209C000U + 0x04U == 0x0209C004U in a host C11 program map GPIO1_GDIR into the workstation process?
- [ ] Yes; casting
0x0209C004Utovolatile uint32_t *opens a USB tunnel to the target board - [ ] Yes;
Linuxuser space identity-mapsi.MX6ULLperipheral bus addresses automatically - [x] No;
0x0209C004Uis a targetSoCphysical bus address—dereferencing it on the host faults in process virtual memory
Answer: No; 0x0209C004U is a target SoC physical bus address—dereferencing it on the host faults in process virtual memory
Why: 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.
1. Motivation
First-week Cortex-A7 bring-up sessions stall when an engineer downloads an x86_64 host binary (e_machine = 62) over TFTP into 0x87800000, trusts start + length <= base + size near 0xFFFFFFFF where 32-bit unsigned addition wraps modulo 2^32, or drives an active-low cathode-sink LED on GPIO1_IO03 with inverted Boolean logic that extinguishes the indicator when on == true. In this laboratory, you will audit starter/core.c, isolate a silent-compile polarity inversion inside pin_write(), and prove ELF32 EM_ARM identification, subtraction-based RAM placement bounds, and sibling-preserving GPIO data-latch updates under TAP version 13.
2. Learning Objectives
- Validate
32-bit little-endianARMELFheaders (0x7F 'E' 'L' 'F',EI_CLASS = 1,EI_DATA = 1,e_machine = 40at bytes18..19) while rejecting truncated buffers below20bytes. - Prove overflow-safe target RAM window containment
[start, start + length)inside[base, base + size)using post-guard subtraction (length <= size - (start - base)). - Repair active-low vs active-high
GPIOx_DRpin updates (on != active_low) sopin_write()preserves all31neighboring pins and rejectsNULLpointers orpin >= 32without mutating caller state. - Benchmark archive build and 4-suite verification latency (
p50/p95/p99) usingCLOCK_MONOTONIC.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64LP64user space) insidelabs/lab_m01_eabi_workbench/. - Target Architecture Alignment:
core.handcore.crestrict register images and RAM addresses to<stdint.h>uint32_tandUINT32_C(1)shifts so hostLP64verification matches32-bitARMv7-AILP32freestanding builds bit-for-bit.
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,readelf). - Hardware: Standard Linux workstation (
0physical target boards or serial adapters required for gradedTAPsign-off;3.3 Vactive-low sink verification applies during optional bench bring-up).
5. Complete Executable Commands
Run these commands from labs/lab_m01_eabi_workbench/ to reproduce the starter/ failure in a disposable sandbox, isolate failing test vectors 3 and 4, inspect the static archive libbsp.a, and confirm 5/5 TAP checks on files/:
learner@ksa:~/gl-e01/m01-l03$ bat script.sh File: script.sh # 1. Stage starter/ in a disposable temp directory and run check.sh without clobbering files/ TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Link tests.c directly against starter/core.c to pinpoint which case aborts TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/v" && { "$TMP/v" 3 || echo "starter case 3 aborted (rc=$?)"; "$TMP/v" 4 || echo "starter case 4 aborted (rc=$?)"; } ; rm -rf "$TMP" # 3. Rebuild the reference library files/libbsp.a and inspect exported ABI symbols make -B -C files ar -t files/libbsp.a && nm -g --defined-only files/libbsp.a # 4. Run the authoritative 5-point TAP version 13 verification harness sh check.sh*Why each step runs:* Step 1 mirrors coursec labs by grading starter/ inside an isolated directory so files/ remains clean; Step 2 executes tests.c cases 3 and 4 directly to expose the SIGABRT exit codes (rc=134); Step 3 proves Makefile -MMD -MP compilation and archive symbol visibility (elf_arm32, image_fits, pin_write); and Step 4 emits graded TAP version 13 output.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
elf_arm32(const unsigned char *p, size_t n)(core.c:2-7): Checksn >= 20Ubefore indexingp[0..5]andp[18..19], accepting only0x7f 'E' 'L' 'F',ELFCLASS32(1U),ELFDATA2LSB(1U), and little-endianEM_ARM(p[18] == 40U && p[19] == 0U).tests.ccase1rejectsn = 19U,ELFCLASS64(p[4] = 2U), andEM_X86_64(p[18] = 62U).image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length)(core.c:8-13): Rejectsstart < baseorlength == 0Uup front, computesoffset = start - base, and checksoffset <= size && length <= size - offsetsostart = UINT32_MAX, length = 8Uintests.ccase2cannot wrap into range.- Seeded Flaw in
starter/core.c:18(pin_write):starterevaluates*dr = (on == active_low) ? *dr | mask : *dr & ~mask;(logical equivalence / XNOR). Whenon = trueandactive_low = true(cathode-sinkLEDon),starterdrives bit3high (3.3 V), turning theLEDoff; whenon = trueandactive_low = falseonpin = 31U(tests.c:34),starterclears bit31(0x12345678U) instead of setting0x92345678U. - Verified Repair in
files/core.c:14-20: Guardsif (dr == NULL || pin >= 32U) return false;beforeUINT32_C(1) << pin(avoiding C11 shift undefined behavior atpin == 32U), then writes*dr = (on != active_low) ? *dr | mask : *dr & ~mask;.
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m01-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 3/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations not ok 4 - maps both output polarities and preserves sibling pins --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 3; inspect tests.c for the exact input and expected result' ... not ok 5 - rejects invalid pins without changing the output object --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 4; inspect tests.c for the exact input and expected result' ... # pass 3/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations ok 4 - maps both output polarities and preserves sibling pins ok 5 - rejects invalid pins without changing the output object # pass 5/58. Explanation of Observed Behavior
In starter/, check 1 (ok 1), check 2 (ok 2), and check 3 (ok 3) pass cleanly because elf_arm32() and image_fits() are intact and (on == active_low) triggers zero -Wall -Wextra -Werror diagnostics. Check 4 (not ok 4) fails at tests.c:24: starting from dr = 0xa5a5a5a5U (where bit 3 is 0), pin_write(&dr, 3U, true, true) sets bit 3 (0xa5a5a5adU) instead of keeping before & ~8U. Check 5 (not ok 5) passes the pin = 32U and NULL guards at tests.c:32-33 but aborts at tests.c:34 because pin_write(&dr, 31U, true, false) clears bit 31 instead of producing 0x92345678U. Changing == to != in files/core.c satisfies all four polarity combinations (# pass 5/5).
9. Experiment Variations
- Signed-Shift Undefined Behavior at Pin 31 (
UBSan): ReplaceUINT32_C(1) << pinwith1 << pinin a scratch copy and compile with-fsanitize=undefined:tests.ccase4(pin = 31U) shifts1into the sign bit of32-bit signedint, triggering an immediate runtimeUBSandiagnostic. - Modular Addition Wrap in
image_fits(): Temporarily rewriteimage_fits()asreturn length > 0U && start >= base && start + length <= base + size;and runverify 2:UINT32_MAX + 8Uwraps to7U <= 0x1100U, falsely accepting a span past4 GiB. - Big-Endian
EM_ARMSpoof: Seth[18] = 0U; h[19] = 40U;(0x0028big-endian) in a scratch test and confirmelf_arm32()rejects mismatched byte order even whenEI_DATAclaims little-endian.
10. Performance Measurements
Timed on Linux 7.0.0-42-generic (x86_64) with CLOCK_MONOTONIC across 5 warmup runs and 35 measured iterations (reproduce binary timing via python3 -c 'import subprocess,time,statistics as s; [subprocess.run(["sh","check.sh"],stdout=-3) for _ in range(5)]; t=[(time.monotonic_ns(),subprocess.run(["sh","check.sh"],stdout=-3),time.monotonic_ns()) for _ in range(35)]; d=sorted((b-a)/1e6 for a,_,b in t); print(f"p50={s.median(d):.2f}ms p95={d[33]:.2f}ms")'):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Equivalent |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 processes) | 130.92 ms | 139.14 ms | 146.45 ms | Host-only toolchain step |
verify 4-case binary suite (verify 1..4 sequential) | 3434.1 us | 3861.1 us | 4202.8 us | < 2 us in-SRAM function calls (0 fork/exec) |
Single GPIO1_DR RMW (LDR + BIC/ORR + STR) | ~1 ns (L1 RAM) | ~2 ns | ~3 ns | ~40 - 90 ns across IPG peripheral bridge |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 4 & not ok 5 (# pass 3/5) | pin_write() uses (on == active_low) instead of (on != active_low) | Use `(on != active_low) ? *dr \ | mask : *dr & ~mask in core.c` | |
Shift warning or pin = 31 sign-extension corruption | 1 << pin shifts signed int instead of unsigned uint32_t | Form the bitmask as UINT32_C(1) << pin after checking pin < 32U | ||
verify 4 crashes with SIGSEGV | *dr read occurs before checking dr == NULL or pin >= 32U | Place `if (dr == NULL \ | \ | pin >= 32U) return false; on the first line of pin_write()` |
elf_arm32 accepts 256+ machine IDs | Checked p[18] == 40U without verifying high byte p[19] == 0U | Require both p[18] == 40U && p[19] == 0U for 16-bit little-endian e_machine |
12. Guided Questions
- Why must
pin_write()checkpin >= 32Ubefore evaluatingUINT32_C(1) << pin, even whenpin == 32Ureturnsfalseon the next line?
- *Hint 1:* Consult ISO C11 Section 6.5.7 on bitwise shift operators when the right operand equals or exceeds the promoted width of the left operand (
32bits). - *Hint 2:* On
x86_64,SHL eax, clmasksclmodulo32(1U << 32yields1!), whereas onARMv7-A,LSL Rd, Rm, Rsuses the bottom8bits ofRs(1U << 32yields0) -- the compiler may optimize assumingpin < 32Ualready holds!
- Why does an active-low cathode-sink
LEDrequireDR[pin] = 0foron == truewhile an active-high sourceLEDrequiresDR[pin] = 1?
- *Hint 1:* Trace the potential difference
V_DD - V_padacross the series resistor andLEDwhen the anode is tied to3.3 V. - *Hint 2:* Write the
2 x 2truth table of(on, active_low) -> pad_highand verify whypad_high = (on != active_low)covers all four rows.
13. Independent Challenges
- Near Transfer — Full
Elf32_Ehdr+PT_LOADSegment Gate: Extendelf_arm32()intoelf_arm32_loadable(const unsigned char *buf, size_t len, uint32_t ram_base, uint32_t ram_size)that parsese_phoff,e_phentsize == 32U, ande_phnum, rejectsp_memsz < p_filesz, and verifies everyPT_LOADsegment (p_type == 1U) fits[ram_base, ram_base + ram_size)viaimage_fits(). - Far Transfer — Multi-Pin Atomic Mask Update (
pin_group_write): Implementbool pin_group_write(uint32_t *dr, uint32_t group_mask, uint32_t logical_on, uint32_t active_low_mask)that updates an arbitrary subset of pins in one read-modify-write expression without per-pin loops while preserving all bits outsidegroup_mask.
14. Solutions & Explanations
- Guided Question 1: Shifting a
32-bituint32_tby>= 32is undefined behavior in ISO C11; evaluatingUINT32_C(1) << pinprior toif (pin >= 32U)lets an optimizing compiler elide thepin >= 32Ubranch altogether! - Guided Question 2: With anode at
3.3 V, drivingDR = 1(3.3 V) yields0 Vacross theLED(off), whereas drivingDR = 0(V_OL) forward-biases the diode (on). Across all four(on, active_low)pairs, the output latch bit is1when(true, false)or(false, true), which is exact Boolean inequalityon != active_low. - Challenge 2 Key Formula: Compute
desired_levels = logical_on ^ active_low_mask; *dr = (*dr & ~group_mask) | (desired_levels & group_mask);.
Run locally in your terminal and check off each verification milestone.
Not started
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. - 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.
Step sequence — frame strip: steps_m01_l03
Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
reveals: step1
highlights: step1
Step 2 (Carrier Net): Follow net label LED0 to its exact board-to-board header pin and check shared pulls or boot straps.
reveals: step2
highlights: step2
Step 3 (Core Pad): Match the mating SOM connector pin to SoC ball GPIO1_IO03 (Bank 1, local bit index 3).
reveals: step3
highlights: step3
Step 4 (Register Mask): Compute Base + Offset (0x0209C000) and update bit 3 via UINT32_C(1) << pin without touching 31 siblings.
reveals: step4
highlights: step4
m02/
Cortex-A7 modes, CP15, and ARMv7 assembly
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.
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 interrupt asserts while an unprivileged application is executing? Suppose the CPU had only one Stack Pointer (SP) and one privilege state. If the user program had just corrupted SP (or pointed SP at kernel memory!) when the interrupt arrived, hardware pushing return state onto that untrusted SP would either trigger a double-fault crash or hand Ring 0 write access to an attacker! Conversely, if hardware copied all 16 general-purpose registers into RAM on every interrupt, entry latency would balloon by dozens of bus cycles.
ARMv7-A (AArch32 on Cortex-A7) solves both problems simultaneously using nine architectural processor modes selected by the low five bits M[4:0] of the Current Program Status Register (CPSR), paired with selective hardware register banking. Study the physical register matrix in Figure 2.1a:
- Privilege Boundaries (
PL0,PL1,PL2):User(0x10) is the sole unprivilegedPL0mode: it cannot mask interrupts, switchCPSRmodes, or touchCP15system control. Standard operating-system and bare-metal exception work runs atPL1:Supervisor(SVC,0x13, entered on Reset andSVCsyscalls),IRQ(0x12),FIQ(0x11),Abort(ABT,0x17, memory faults),Undefined(UND,0x1B, illegal/disabled opcodes),System(SYS,0x1F), plus TrustZoneMonitor(MON,0x16) in Secure state.Hyp(HYP,0x1A) sits at Non-SecurePL2for virtualization (ERET/ELR_hyp). - What Is Banked vs What Remains Shared! Look closely at the left column of Figure 2.1a:
r0..r7are100%physically shared across every single mode (r8..r12are also shared across8modes, banked only inFIQ0x11so ultra-fastFIQhandlers can run usingr8_fiq..r12_fiqwith zero stack pushes!). Exception modes (SVC,IRQ,FIQ,ABT,UND,MON) each own a private physicalr13(SP_<mode>),r14(LR_<mode>), andSPSR_<mode>. Meanwhile, privilegedSystem(0x1F) deliberately sharesUser'sr13_usrandr14_usrwith zeroSPSR, letting an OS kernel manipulate user-mode stacks without riskingSPSRcorruption. Therefore, anIRQhandler gets its own safe kernel stack (SP_irq) instantly in hardware—yet if thatIRQhandler modifiesr0..r3orr12without pushing them first, it overwrites the interrupted program's live registers!
Figure 2.1a. Physical Cortex-A7 register banking across all nine modes — private SP/LR/ protect exception entry, while shared r0..r7 (and r8..r12 outside FIQ) still require software stack saves.
mental model: 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 system switches requires pipeline synchronization barriers to take effect cleanly.
definition (, Saved Program Status (SPSR) & CP15 System Control (SCTLR)): 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.
Step through the four-stage resolution of mode, register bank, SPSR, and CP15 state below:
- Step 1. Step 1 (Current State): Decode CPSR M[4:0] and preserve NZCV [31:28] plus I/F/T [7:5] via ~0x1FU masking.
- Step 2. Step 2 (Register View): Remember r0..r7 are shared everywhere; only FIQ banks r8..r12 alongside SP and LR.
- Step 3. Step 3 (Exception State): Exception entry snapshots CPSR into SPSR_<mode> and selects banked SP/LR (absent in USR/SYS).
- Step 4. Step 4 (System Control): Read SCTLR via MRC p15, modify only target bits, and serialize MCR p15 with DSB SY and ISB.
Figure 2.1b. Always resolve active CPSR mode, physical register bank, and I/F masks before touching SP or CP15.
Decoding CPSR Control Lanes and Synchronizing CP15 SCTLR Writes
Inspect Figure 2.1b to see every bit slice inside CPSR and CP15 SCTLR (p15, 0, Rt, c1, c0, 0). Take the classic bare-metal reset word 0xA00000D3:
- Upper nibble
0xA(1010_2in[31:28]) meansN = 1,Z = 0,C = 1,V = 0. - Low control byte
0xD3(1101_0011_2in[7:0]) meansI = 1(IRQmasked),F = 1(FIQmasked),T = 0(32-bit ARM ISA), andM[4:0] = 0x13(Supervisormode).
Notice what happens if startup assembly carelessly writes msr cpsr_c, #0x13 instead of #0xD3 (or masked RMW): clearing bits 7 and 6 unmasks live IRQ and FIQ interrupts before _start has initialized SP_irq or VBAR!
Figure 2.1b. Exact 32-bit bitfields for CPSR (top) and CP15 SCTLR (bottom) with barrier-ordered control updates.
Why does SCTLR use special coprocessor instructions (mrc / mcr) plus dsb sy and isb instead of a memory-mapped 0x020... address? Because SCTLR sits inside the Cortex-A7 core pipeline, controlling how the CPU itself translates virtual addresses (M, bit 0), checks pointer alignment (A, bit 1), caches data (C, bit 2) and instructions (I, bit 12), and locates exception vectors (V, bit 13). In enable_alignment_check below, mrc p15, 0, r0, c1, c0, 0 copies SCTLR into r0, orr r0, r0, #2 sets only SCTLR.A (bit 1) without disturbing M, C, I, or V, dsb sy drains pending memory accesses under the old rules, mcr writes SCTLR, and isb flushes already-fetched pipeline instructions so the very next load/store obeys strict alignment! (Note: disabling SCTLR.C or SCTLR.M requires full set/way cache cleaning first so dirty L1/L2 lines are never abandoned.)
learner@ksa:~/gl-e01/m02-l01$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global read_sctlr read_sctlr: mrc p15, 0, r0, c1, c0, 0 bx lr .global enable_alignment_check enable_alignment_check: mrc p15, 0, r0, c1, c0, 0 orr r0, r0, #2 dsb sy mcr p15, 0, r0, c1, c0, 0 isb bx lrModeling CPSR Mode Validity and Physical Bank Aliasing in C11
In cpsr_bank_decoder.c, we turn the architectural tables into an executable verifier. First, decode_cpsr() validates M[4:0] against the exact nine Cortex-A7 encodings (rejecting undefined 5-bit patterns like 0x14), derives PL1/PL2 privilege (m != MODE_USR), and flags SPSR existence (m != MODE_USR && m != MODE_SYS). Second, bank_slot() maps (mode, reg) pairs onto physical storage indices—proving USR and SYS alias the same r13 (SP), IRQ owns a distinct r13, and FIQ owns private r8..r14 while sharing r0..r7!
learner@ksa:~/gl-e01/m02-l01$ bat -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 39 -H 40 cpsr_bank_decoder.c File: cpsr_bank_decoder.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> enum { MODE_USR = 0x10U, MODE_FIQ = 0x11U, MODE_IRQ = 0x12U, MODE_SVC = 0x13U, MODE_MON = 0x16U, MODE_ABT = 0x17U, MODE_HYP = 0x1aU, MODE_UND = 0x1bU, MODE_SYS = 0x1fU }; static bool decode_cpsr(uint32_t cpsr, bool *priv, bool *has_spsr, bool *irq_m, bool *fiq_m, bool *thumb) { unsigned m = cpsr & 0x1fU; bool valid = (m == MODE_USR || m == MODE_FIQ || m == MODE_IRQ || m == MODE_SVC || m == MODE_MON || m == MODE_ABT || m == MODE_HYP || m == MODE_UND || m == MODE_SYS); if (!valid) return false; *priv = (m != MODE_USR); *has_spsr = (m != MODE_USR && m != MODE_SYS); *irq_m = ((cpsr >> 7) & 1U) != 0U; *fiq_m = ((cpsr >> 6) & 1U) != 0U; *thumb = ((cpsr >> 5) & 1U) != 0U; return true; } static unsigned bank_slot(unsigned mode, unsigned reg) { assert(reg < 15U); if (mode == MODE_FIQ && reg >= 8U) return 16U + (reg - 8U); if (reg >= 13U && mode == MODE_IRQ) return 23U + (reg - 13U); if (reg >= 13U && mode == MODE_SVC) return 25U + (reg - 13U); if (reg >= 13U && mode == MODE_ABT) return 27U + (reg - 13U); if (reg >= 13U && mode == MODE_UND) return 29U + (reg - 13U); return reg; } int main(void) { bool priv = false, spsr = false, im = false, fm = false, th = false; assert(decode_cpsr(0xa00000d3U, &priv, &spsr, &im, &fm, &th)); assert(priv && spsr && im && fm && !th); assert(decode_cpsr(0x60000030U, &priv, &spsr, &im, &fm, &th)); assert(!priv && !spsr && !im && !fm && th); assert(decode_cpsr(MODE_SYS, &priv, &spsr, &im, &fm, &th) && priv && !spsr); assert(!decode_cpsr(0x14U, &priv, &spsr, &im, &fm, &th)); assert(bank_slot(MODE_USR, 13U) == bank_slot(MODE_SYS, 13U)); assert(bank_slot(MODE_IRQ, 13U) != bank_slot(MODE_USR, 13U)); assert(bank_slot(MODE_FIQ, 8U) != bank_slot(MODE_USR, 8U)); assert(bank_slot(MODE_FIQ, 0U) == bank_slot(MODE_USR, 0U)); uint32_t old = 0xa00000c0U | MODE_USR; uint32_t next = (old & ~UINT32_C(0x1f)) | MODE_SVC; assert((next & 0x1fU) == MODE_SVC && (next & ~0x1fU) == (old & ~0x1fU)); uint32_t sctlr = 0x00c50078U, mod = sctlr | 2U; assert((mod & ~2U) == (sctlr & ~2U)); printf("CPSR=0x%08X mode=0x%02X I=%d F=%d T=%d SCTLR.A=%u\n", next, next & 0x1fU, (next >> 7) & 1U, (next >> 6) & 1U, (next >> 5) & 1U, (mod >> 1) & 1U); return 0; }- Classify all nine legal Cortex-A7 M[4:0] encodings and distinguish privileged SPSR-bearing exception modes from USR/SYS.
- Map FIQ r8..r14 and exception r13..r14 to distinct physical storage slots while keeping r0..r7 shared across every mode.
- Clear only ~0x1FU when switching CPSR mode so NZCV flags [31:28] and I/F/T controls [7:5] remain intact.
Running the Mode Decoder and Cross-Assembling CP15 Accessors
Compile and run cpsr_bank_decoder.c, then cross-assemble target.S for Cortex-A7. Remember the host/target boundary: clang proves valid ARMv7-A MRC/MCR instruction encoding in target.o, whereas executing mrc p15, 0, r0, c1, c0, 0 from User mode (0x10) on real silicon immediately traps into Undefined (0x1B) mode!
learner@ksa:~/gl-e01/m02-l01gcc -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-l01clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l01learner@ksa:~/gl-e01/m02-l01strace -e trace=write,exit_group \./cpsr_bank_decoderwrite(1, "CPSR=0xA00000D3 mode=0x13 I=1 F="..., 48) = 48exit_group(0) = ?+++ exited with 0 +++Hardware Banking vs AAPCS Software Preservation
Keep hardware mode banking (CPSR.M[4:0] selecting private SP/LR) strictly separate from software AAPCS32 preservation (callees pushing r4..r11). Ordinary BL function calls never change processor mode or register banks—the callee saves r4..r11 on the current stack by convention. Conversely, hardware IRQ entry switches SP to SP_irq and LR to LR_irq, yet leaves r0..r12 pointing at the interrupted program's physical registers—so your top-level IRQ stub must push r0..r3 and r12 onto SP_irq before calling any C function!
Processor Mode (M[4:0]) | Privilege | Private Banked Registers | SPSR Present | Primary Bare-Metal / OS Role |
|---|---|---|---|---|
User (0x10) | PL0 (unpriv) | None (shares r0..r14 with SYS) | No | Unprivileged user-space application execution |
System (0x1F) | PL1 (priv) | Shares USR r0..r14 bank | No | Privileged OS helpers accessing User SP/LR without SPSR risk |
Supervisor (0x13) / IRQ (0x12) | PL1 (priv) | r13 (SP), r14 (LR) per mode | Yes (SPSR_svc/irq) | Reset/kernel SVC execution and GICv2 IRQ entry (r0..r12 shared!) |
FIQ (0x11) | PL1 (priv) | r8..r12, r13 (SP_fiq), r14 (LR_fiq) | Yes (SPSR_fiq) | Low-latency fast interrupt path avoiding stack saves on r8..r12 |
Later: Lesson m02-l02 examines how SCTLR.V and CP15 VBAR compute exception vector addresses alongside ARMv7-A pre/post-indexed load/store addressing and CMP condition flags.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Decoding CPSR 0x80000192 & Multi-Mode SP Setup
Step 1 (Bitfield Decode): Decode CPSR = 0x80000192U into flags, masks, ISA state, mode, privilege, and SPSR presence (N=1 at bit 31, A=1 at bit 8, 0x92 = 1001_0010_2 -> I=1, F=0, T=0 ARM, M=0x12 IRQ mode at PL1 with valid SPSR_irq). Step 2 (Banked SP Trace): If _start initializes sp = 0x87820000 in SVC (0x13) and switches to IRQ (0x12) without loading sp again, state what SP_svc and SP_irq hold (SP_svc == 0x87820000, SP_irq == uninitialized garbage!). Step 3 (Mask Expression): Write the C expression that clears only CPSR.I (bit 7) (cpsr & ~(UINT32_C(1) << 7)).
Independent Practice: IRQ Entry & SPSR Return Simulator (mode_transition_sim.c)
Write a standalone ISO C11 verifier mode_transition_sim.c modeling a 31-word physical Cortex-A7 register file, cpsr, and per-mode spsr array. Implement enter_irq() (SPSR_irq = CPSR, M = 0x12, I = 1, T = 0, LR_irq = pc + 4) and subs_pc_lr_4() (restoring CPSR = SPSR_irq while rejecting calls from USR or SYS). Prove r13_usr survives an IRQ round-trip while an unsaved write to r2 inside the handler clobbers User r2.
? check 1 · An IRQ (0x12) assembly handler overwrites r0 without pushing it first. Why does this corrupt the interrupted User (0x10) program upon return?
- [ ]
IRQmode automatically restoresr0only whenSCTLR.Ais1 - [ ]
IRQmode has a privater0_irq, and hardware overwritesr0_usrduringsubs pc, lr, #4 - [x]
IRQmode banks onlyr13(SP_irq),r14(LR_irq), andSPSR_irq;r0..r12share physical storage withUsermode
Answer: IRQ mode banks only r13 (SP_irq), r14 (LR_irq), and SPSR_irq; r0..r12 share physical storage with User mode
Why: 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.
? check 2 · 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?
- [ ]
orr r0, r0, #0x13without clearing priorM[4:0]bits - [x] Clear bits
[4:0](bic r0, r0, #0x1f) and OR in#0x13(orr r0, r0, #0x13) - [ ] Overwrite the entire
32-bit register withmov r0, #0x13
Answer: Clear bits [4:0] (bic r0, r0, #0x1f) and OR in #0x13 (orr r0, r0, #0x13)
Why: 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.
? check 3 · Retrieval: during an ordinary BL subroutine call in Supervisor mode, what protects a caller's value in r4?
- [x] The callee pushes and pops
r4on the stack to honor theAAPCS32software calling convention - [ ] Hardware switches
r4to a new register bank on everyBLinstruction - [ ]
CP15SCTLRsnapshotsr4..r11intoSPSR_svcautomatically
Answer: The callee pushes and pops r4 on the stack to honor the AAPCS32 software calling convention
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m02_l01
Step 1 (Current State): Decode CPSR M[4:0] and preserve NZCV [31:28] plus I/F/T [7:5] via ~0x1FU masking.
reveals: step1
highlights: step1
Step 2 (Register View): Remember r0..r7 are shared everywhere; only FIQ banks r8..r12 alongside SP and LR.
reveals: step2
highlights: step2
Step 3 (Exception State): Exception entry snapshots CPSR into SPSR_<mode> and selects banked SP/LR (absent in USR/SYS).
reveals: step3
highlights: step3
Step 4 (System Control): Read SCTLR via MRC p15, modify only target bits, and serialize MCR p15 with DSB SY and ISB.
reveals: step4
highlights: step4
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.
Load/Store Effective Addresses, Barrel Shifts, and ALU Condition Physics
Why does ARMv7-A forbid CISC-style instructions like orl $8, 0x0209C000 that modify memory in a single instruction? Because Cortex-A7 is a load/store RISC pipeline: arithmetic and bitwise logic (ADD, SUB, BIC, ORR, CMP) operate exclusively on internal 32-bit registers in a single ALU cycle, while dedicated LDR and STR instructions move words between registers and the bus. That clean separation unlocks two hardware superpowers—and two classic assembly traps—illustrated in Figure 2.2a:
- Effective Address (
EA) vs Base Writeback (!vs post-index): EveryLDR/STRanswers two independent questions: which memory address hits the bus (EA), and what value remains in the base register afterward? Starting fromr1 = 0x1000:
- Offset (
ldr r2, [r1, #4]):EA = 0x1004;r1stays0x1000(zero writeback). - Pre-indexed writeback (
ldr r2, [r1, #4]!): Adds#4first, readsEA = 0x1004, and writes0x1004back intor1(skipping word0x1000!). - Post-indexed writeback (
ldr r2, [r1], #4): Reads originalEA = 0x1000first, then writes0x1004intor1! Notice that inspectingr1 == 0x1004in a debugger after the instruction cannot tell you whether0x1000or0x1004was read!
- Zero-Cycle Inline Barrel Shifter +
BIC/ORR: Placed directly ahead of theALU's second input port (Operand2) is a combinational barrel shifter (LSL,LSR,ASR,ROR) that shifts a register by0..31bits in the same clock cycle asADD,ORR, orLDR! PairingBIC(Bit Clear:Rd <- Rn & ~Op2) with width-clampedANDand shiftedORR(orr r2, r2, r1, lsl #8) replaces multi-bit register fields cleanly without corrupting neighbors.
Figure 2.2a. Separating accessed Effective Address from base writeback (top) and inline barrel-shifted BIC/ORR field replacement (bottom).
mental model: 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 side effects, and comparing 32-bit pointers above 0x80000000 with signed condition codes treats valid DDR3 RAM as negative numbers.
definition (Effective Address,BIC/ORR Field Masking & Unsigned vs Signed CMP Flags): 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).
Trace the four independent computations—base/offset, effective address, shifted mask, and flag interpretation—in the step diagram below:
- Step 1. Step 1 (Base & Offset): Separate base pointer Rn from byte offset; VBAR exception bases also require 32-byte alignment.
- Step 2. Step 2 (Effective Address): Pre-index [Rn, #4]! touches Rn+4; post-index [Rn], #4 touches original Rn before advancing.
- Step 3. Step 3 (Operand Path): Clamp incoming field width with AND before barrel-shifting LSL into BIC + ORR.
- Step 4. Step 4 (Condition Flags): Always use unsigned BHS/BLO (C flag) for RAM pointers >= 0x80000000; reserve BGE/BLT (N vs V) for signed ints.
Figure 2.2b. Track accessed address, final base register, field width mask, and unsigned vs signed flags as four separate facts.
Exception Vector Base Routing and Unsigned vs Signed Flag Divergence
Why does signed versus unsigned branching bite i.MX6ULL firmware engineers on Day 1? Look at the right panel of Figure 2.2b! External DDR3 on i.MX6ULL starts at physical address 0x80000000 (bit 31 == 1), while internal OCRAM sits at 0x00900000 (bit 31 == 0). Inside the hardware ALU, cmp r0, r1 (0x87800000 - 0x00900000 = 0x86F00000) computes 0x87800000 + 0xFF6FFFFF + 1, producing N = 1 (bit 31 of result is 1), Z = 0, C = 1 (carry out of bit 31 -> zero unsigned borrow!), and V = 0.
- An unsigned branch
bhs(C == 1) sees2,273,312,768 >= 9,437,184-> TRUE! - A signed branch
bge(N == V) sees-2,021,654,528 < +9,437,184(1 != 0) -> FALSE! Writingbltinstead ofbloin a.bsszeroing loop insideDDR3(0x87800000) instantly treats valid RAM addresses as negative integers!
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).
Now inspect the left panel of Figure 2.2b (Exception Vector Base Routing) and replace_nibble in target.S below. First, when an IRQ (slot 6) arrives, Cortex-A7 checks SCTLR.V (bit 13): if V == 1, it fetches 0xFFFF0000 + 4 * 6 = 0xFFFF0018; if V == 0, it fetches VBAR + 4 * 6 (0x87800018), where VBAR (c12, c0, 0) must be 32-byte aligned (VBAR[4:0] == 0) because 8 vector words occupy 32 bytes (slot 5 at +0x14 is reserved). Second, in replace_nibble, ldr r2, [r0], #4 reads original [r0] and post-increments r0 by +4; therefore, str r2, [r0, #-4] must subtract 4 to write back the modified word rather than clobbering the next word in RAM, while and r1, r1, #15 clamps oversized caller inputs (0x32 -> 0x02) before lsl #8!
learner@ksa:~/gl-e01/m02-l02$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global replace_nibble .type replace_nibble, %function replace_nibble: ldr r2, [r0], #4 bic r2, r2, #0x00000f00 and r1, r1, #15 orr r2, r2, r1, lsl #8 str r2, [r0, #-4] bx lr .size replace_nibble, .-replace_nibbleAuditing Vector Alignment, Pre/Post Indexing, and Nibble Masking in C11
sctlr_vbar_addr_audit.c verifies all four mechanisms in strict ISO C11: vector_entry_addr() rejects reserved slot 5, enforces 32-byte VBAR alignment ((vbar & 0x1fU) == 0U) whenever SCTLR.V == 0, and overrides VBAR with 0xFFFF0000U when SCTLR.V == 1; eff_addr() proves post-index (0x1000) and pre-index (0x1004) touch distinct addresses despite identical 0x1004 writeback; and replace_nibble(0xA5A5FFFFU, 0x32U) proves 0x32 & 0x0F prevents upper bits from spilling into [15:12].
learner@ksa:~/gl-e01/m02-l02$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 20 -H 21 -H 22 -H 23 -H 27 -H 28 -H 29 -H 30 sctlr_vbar_addr_audit.c File: sctlr_vbar_addr_audit.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> enum { VEC_RESET = 0U, VEC_UNDEF = 1U, VEC_SVC = 2U, VEC_PABT = 3U, VEC_DABT = 4U, VEC_IRQ = 6U, VEC_FIQ = 7U }; static bool vector_entry_addr(uint32_t sctlr, uint32_t vbar, unsigned slot, uint32_t *addr_out) { if (slot > 7U || slot == 5U) return false; bool high_vecs = ((sctlr >> 13) & 1U) != 0U; if (!high_vecs && (vbar & 0x1fU) != 0U) return false; uint32_t base = high_vecs ? 0xffff0000U : vbar; *addr_out = base + (slot << 2); return true; } static uint32_t eff_addr(uint32_t base, uint32_t off, bool pre, uint32_t *wb) { *wb = base + off; return pre ? (base + off) : base; } static uint32_t replace_nibble(uint32_t old, uint32_t field) { return (old & ~UINT32_C(0x0f00)) | ((field & 0x0fU) << 8); } int main(void) { uint32_t irq_vec = 0U, hi_irq = 0U; uint32_t sctlr_v0 = (1U << 12) | (1U << 2) | 1U; /* I=1, C=1, M=1, V=0 */ assert(vector_entry_addr(sctlr_v0, 0x87800000U, VEC_IRQ, &irq_vec)); assert(irq_vec == 0x87800018U); assert(!vector_entry_addr(sctlr_v0, 0x87800010U, VEC_IRQ, &irq_vec)); assert(vector_entry_addr(sctlr_v0 | (1U << 13), 0x87800010U, VEC_IRQ, &hi_irq)); assert(hi_irq == 0xffff0018U); uint32_t wb1 = 0U, wb2 = 0U; assert(eff_addr(0x1000U, 4U, false, &wb1) == 0x1000U); assert(eff_addr(0x1000U, 4U, true, &wb2) == 0x1004U && wb1 == wb2); uint32_t next = replace_nibble(0xa5a5ffffU, 0x32U); assert(next == 0xa5a5f2ffU && (next & ~0xf00U) == 0xa5a5f0ffU); assert(UINT32_MAX >= 1U && INT32_C(-1) < INT32_C(1)); printf("IRQ_vec=0x%08X hi_vec=0x%08X post=0x1000 pre=0x1004 nib=0x%08X\n", irq_vec, hi_irq, next); return 0; }- Enforce VBAR[4:0] == 0 (32-byte alignment) and select 0xFFFF0000 high vectors whenever SCTLR.V (bit 13) is 1.
- Distinguish pre-indexed [base, #off]! (base + off accessed) from post-indexed [base], #off (base accessed).
- Mask the incoming value to 4 bits before shifting by 8 so BIC + ORR cannot spill into bits [15:12].
Executing the Addressing and Vector Verifier
Build and run sctlr_vbar_addr_audit.c on the workstation and cross-assemble target.S for Cortex-A7. Experiment by deleting & 0x0fU inside replace_nibble() in a temporary edit to watch 0x32U << 8 corrupt nibble [15:12] and trip the neighbor-preservation assertion immediately.
learner@ksa:~/gl-e01/m02-l02gcc -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-l02clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l02learner@ksa:~/gl-e01/m02-l02strace -e trace=write,exit_group \./sctlr_vbar_addr_auditwrite(1, "IRQ_vec=0x87800018 hi_vec=0xFFFF"..., 75) = 75exit_group(0) = ?+++ exited with 0 +++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. Also keep peripheral semantics in mind: replace_nibble is safe on ordinary RAM or RW control latches under exclusive ownership, never on FIFO data ports or Write-One-to-Clear (W1C) status registers where reading or replaying 1 bits triggers hardware side effects.
| ARMv7-A Mechanism | Syntax Example | Effective Address / Flag Rule | Classic Bring-Up Bug When Confused |
|---|---|---|---|
| Offset addressing (no writeback) | ldr r2, [r0, #4] | EA = r0 + 4; r0 unchanged | Loop pointer never advances (infinite loop over first word) |
| Pre-indexed writeback | ldr r2, [r0, #4]! | EA = r0 + 4; r0 <- r0 + 4 | Skips word 0 ([r0 + 0]) at the start of .data copy or .bss zeroing |
| Post-indexed writeback | ldr r2, [r0], #4 | EA = r0; r0 <- r0 + 4 | Subsequent str r2, [r0] writes r0 + 4 unless [r0, #-4] compensates |
Unsigned BHS vs signed BGE | cmp r0, r1 -> bhs / bge | BHS: C == 1; BGE: N == V | Using signed BLT/BGE on DDR3 (>= 0x80000000) treats RAM pointers as negative! |
Later: Lesson m02-l03 combines load/store writeback with control flow—building 8-byte-aligned full-descending stack frames (STMFD / LDMFD) across nested assembly-to-C calls.
Common Production Pitfalls
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 <=).
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.
Practice & Retrieval
Guided Practice: Scaled Barrel-Shift Indexing & CMP Flag Trace
Step 1 (Scaled Register Offset): Given r0 = 0x020C4068 (CCM_CCGR0) and r1 = 3, compute EA and final r0 for ldr r2, [r0, r1, lsl #2] vs ldr r2, [r0, r1, lsl #2]! (3 << 2 = 12 = 0x0C -> 0x020C4074 CCM_CCGR3; only ! updates r0). Step 2 (VBAR Check): State why VBAR = 0x00907020 is legal while 0x00907010 is invalid when SCTLR.V == 0 (bit 4 violates 32-byte alignment). Step 3 (Flag Trace): For CMP 0x87800000, 0x00900000, verify N=1, Z=0, C=1, V=0, BHS = true, and BGE = false.
Independent Practice: Exact AArch32 ALU Subtraction Flag Simulator (cmp_flags_audit.c)
Write a standalone ISO C11 verifier cmp_flags_audit.c implementing void arm_cmp32(uint32_t a, uint32_t b, bool *n, bool *z, bool *c, bool *v) using 64-bit unsigned carry ((uint64_t)a + (uint64_t)(~b) + 1ULL) and signed overflow (((a ^ b) & (a ^ diff)) >> 31) != 0U. Assert BEQ, BHS, BLO, BHI, BGE, and BLT across (0x87800000U, 0x00900000U), (0x7FFFFFFFU, 0x80000000U), (0U, 1U), and (UINT32_MAX, UINT32_MAX).
? check 1 · Starting from r1 = 0x1000, both ldr r0, [r1, #4]! and ldr r0, [r1], #4 leave r1 == 0x1004. What distinguishes their memory behavior?
- [ ] Only instruction byte length differs; both loads read
0x1004 - [x] Pre-indexed
[r1, #4]!reads0x1004, whereas post-indexed[r1], #4reads the original0x1000before updatingr1 - [ ] Post-indexed
[r1], #4discards the loaded word unlessSis appended
Answer: Pre-indexed [r1, #4]! reads 0x1004, whereas post-indexed [r1], #4 reads the original 0x1000 before updating r1
Why: 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.
? check 2 · 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]?
- [x] Without
& 15, any stray upper bits inr1(such as0x32) shift into[31:12]and corrupt neighboring register fields - [ ]
ORRonCortex-A7faults unless its shifted source operand is< 16 - [ ]
ANDconvertsW1Cstatus registers into ordinary read/write latches
Answer: Without & 15, any stray upper bits in r1 (such as 0x32) shift into [31:12] and corrupt neighboring register fields
Why: 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.
? check 3 · 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?
- [ ]
BHIandBLTread two different physicalALUresult registers - [ ]
CMPrewritesr0from unsigned format into two's-complement format - [x]
0xFFFFFFFF - 1setsN=1, Z=0, C=1, V=0; unsignedBHIchecksC==1 && Z==0(4294967295 > 1), while signedBLTchecksN != V(-1 < 1)
Answer: 0xFFFFFFFF - 1 sets N=1, Z=0, C=1, V=0; unsigned BHI checks C==1 && Z==0 (4294967295 > 1), while signed BLT checks N != V (-1 < 1)
Why: 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.
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). - 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.
Step sequence — frame strip: steps_m02_l02
Step 1 (Base & Offset): Separate base pointer Rn from byte offset; VBAR exception bases also require 32-byte alignment.
reveals: step1
highlights: step1
Step 2 (Effective Address): Pre-index [Rn, #4]! touches Rn+4; post-index [Rn], #4 touches original Rn before advancing.
reveals: step2
highlights: step2
Step 3 (Operand Path): Clamp incoming field width with AND before barrel-shifting LSL into BIC + ORR.
reveals: step3
highlights: step3
Step 4 (Condition Flags): Always use unsigned BHS/BLO (C flag) for RAM pointers >= 0x80000000; reserve BGE/BLT (N vs V) for signed ints.
reveals: step4
highlights: step4
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.
Link-Register Lifetime, Full-Descending Stacks, and 8-Byte Alignment
On x86_64, executing call helper automatically decrements %rsp and writes an 8-byte return address into RAM—even if helper is a 2-instruction leaf function (add + ret) that never needed RAM at all! ARM RISC designers asked: why burn two memory bus cycles on every tiny leaf call? Instead, BL (Branch with Link) writes the return address (next_instr) directly into r14 (LR, the Link Register) in zero memory cycles, allowing a leaf function (add_words) to return instantly via BX LR! What is the catch? Look at the timeline in Figure 2.3b: Cortex-A7 has only ONE live LR in the current mode! The instant a non-leaf function (sum_then_double) executes a nested bl add_words, that inner bl overwrites LR, erasing the outer caller's return address forever unless the prologue saved LR to RAM first!
How does ARMv7-A organize that stack in RAM, and why can pushing {lr} alone (4 bytes) crash a C program? Inspect both halves of Figure 2.3a:
- Full-Descending Stack (
STMFD==STMDB,LDMFD==LDMIA): Descending means the stack grows downward from high RAM addresses (0x1000) toward low addresses (0x0FF8); Full meansSP(r13) always points at the last occupied word (not the next empty slot). Executingstmfd sp!, {r4, lr}(popcount = 2words =8bytes) decrementsSPfrom0x1000to0x0FF8before storing. Even more important: inside the32-bit ARM opcode,{r4, lr}is encoded as a16-bit register bitmask ((1 << 4) | (1 << 14) = 0x4010)! Hardware always stores the lowest-numbered register (r4) at the lowest byte address (0x0FF8 = [sp]) and higher-numberedlr(r14) at0x0FFC = [sp + 4], even if you type{lr, r4}in source! - Mandatory
8-Byte PublicSPAlignment (SP mod 8 == 0):AAPCS32requiresSPto be a multiple of8bytes at every public C call boundary because64-bit integers (uint64_t),doublevalues,va_arg(), andARMv7-Adoubleword instructions (LDRD/STRD) require8-byte stack alignment. If incomingSP = 0x1000(mod 8 == 0) and an assembly wrapper pushes{lr}alone (4bytes ->SP = 0x0FFC,mod 8 == 4), callingprintfor anyuint64_tC helper either triggers a hardware AlignmentData Abortor reads swapped32-bit words! Pushing an even register pair (stmfd sp!, {r4, lr}) subtracts8bytes (0x0FF8 mod 8 == 0), saving both outerLRand callee-ownedr4in one instruction!
Figure 2.3a. frame layout and 16-bit register bitmask ordering (left) vs why public C calls require 8-byte SP alignment (right).
mental model: 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.
definition (B / BL / BX Control Transfer, Full-Descending Stack & 8-Byte AAPCS32 Frame): 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.
Step through the four phases of a non-leaf assembly-to-C call frame below:
- Step 1. Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.
- Step 2. Step 2 (Prologue Save): stmfd sp!, {r4, lr} decrements SP by 8 bytes, placing r4 at [sp] and LR at [sp + 4].
- Step 3. Step 3 (Nested Call): Inner BL overwrites live LR and scratch r0..r3/r12 while saved LR and r4 remain safe on the stack.
- Step 4. Step 4 (Epilogue Pop): ldmfd sp!, {r4, pc} restores caller r4, pops outer LR into PC, and restores SP.
Figure 2.3b. Every non-leaf assembly routine calling C must save outer LR and keep SP 8-byte aligned across all exit paths.
Tracing Nested Calls and Separating Subroutine vs Exception Returns
Follow the exact register and stack values across sum_then_double in Figure 2.3b and target.S below:
- Caller enters
sum_then_double(7, 9)viabl:r0 = 7,r1 = 9,SP = 0x1000,LR = 0x87800104. - Prologue
stmfd sp!, {r4, lr}setsSP = 0x0FF8, writes callerr4to[0x0FF8]and0x87800104to[0x0FFC]. bl add_wordsoverwrites liveLRwith0x87800208;add_wordscomputesr0 = 7 + 9 = 16and executesbx lr(PC <- 0x87800208, zero stack traffic!).lsl r0, r0, #1doublesr0to32, and epilogueldmfd sp!, {r4, pc}restoresr4, loads[0x0FFC] = 0x87800104directly intoPC(interworking-capable inARMv7-A!), and restoresSP = 0x1000.
Look at Panel 2 of Figure 2.3b: never confuse bx lr with subs pc, lr, #4! Hardware IRQ exception entry biases LR_irq = interrupted_PC + 4 and snapshots SPSR_irq, so IRQ handlers return via subs pc, lr, #4 (copying SPSR -> CPSR). Subroutine BL already stores the exact next instruction address in LR without touching SPSR; running subs pc, lr, #4 at the end of add_words jumps 4 bytes backward right onto bl add_words in an infinite loop (or faults in USR/SYS where no SPSR exists)!
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).
learner@ksa:~/gl-e01/m02-l03$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global sum_then_double .type sum_then_double, %function sum_then_double: stmfd sp!, {r4, lr} bl add_words lsl r0, r0, #1 ldmfd sp!, {r4, pc} .size sum_then_double, .-sum_then_double .type add_words, %function add_words: add r0, r0, r1 bx lr .size add_words, .-add_wordsProving AAPCS32 Stack Alignment and Callee Preservation in C11
aapcs32_frame_verifier.c simulates the 16-word ARMv7-A register file and a 16-word full-descending stack. Notice three deliberate adversarial checks inside simulate_nested_call(): (1) push_pair_fd() rejects any misaligned incoming SP (sp_word = 7 -> 28 bytes, 28 & 7 != 0) before touching memory; (2) stack[sp] receives r4 while stack[sp + 1] receives lr (reg_lo < reg_hi); and (3) the simulated nested BL fills caller-saved r1, r2, r12, and live r14 (LR) with 0xDEADBEEFU while asserting every callee-saved register r4..r11 emerges bit-for-bit identical on return!
learner@ksa:~/gl-e01/m02-l03$ bat -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 aapcs32_frame_verifier.c File: aapcs32_frame_verifier.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct aapcs_ctx { uint32_t r[16]; /* r13 = SP word index, r14 = LR, r15 = PC */ uint32_t stack[16]; }; static bool push_pair_fd(struct aapcs_ctx *c, unsigned reg_lo, unsigned reg_hi) { if (reg_lo >= reg_hi || c->r[13] < 2U || ((c->r[13] * 4U) & 7U) != 0U) return false; c->r[13] -= 2U; c->stack[c->r[13]] = c->r[reg_lo]; c->stack[c->r[13] + 1U] = c->r[reg_hi]; return ((c->r[13] * 4U) & 7U) == 0U; } static bool simulate_nested_call(struct aapcs_ctx *c) { uint32_t saved_callees[8]; for (unsigned i = 0U; i < 8U; ++i) saved_callees[i] = c->r[4U + i]; if (!push_pair_fd(c, 4U, 14U)) return false; c->r[4] = c->r[0] + c->r[1]; /* caller uses r4 across nested BL */ c->r[14] = 0x87800208U; /* nested BL overwrites live LR */ c->r[0] = c->r[4]; c->r[1] = 0xdeadbeefU; c->r[2] = 0xdeadbeefU; c->r[12] = 0xdeadbeefU; c->r[0] <<= 1; /* helper result doubled */ c->r[4] = c->stack[c->r[13]]; c->r[15] = c->stack[c->r[13] + 1U]; c->r[13] += 2U; for (unsigned i = 0U; i < 8U; ++i) if (c->r[4U + i] != saved_callees[i]) return false; return true; } int main(void) { struct aapcs_ctx c = {{0U}, {0U}}; c.r[0] = 7U; c.r[1] = 9U; c.r[13] = 8U; c.r[14] = 0x87800104U; for (unsigned i = 4U; i <= 11U; ++i) c.r[i] = 0x40000000U + i; assert(simulate_nested_call(&c)); assert(c.r[0] == 32U && c.r[4] == 0x40000004U); assert(c.r[15] == 0x87800104U && c.r[13] == 8U); assert(c.stack[6] == 0x40000004U && c.stack[7] == 0x87800104U); c.r[13] = 7U; /* 28 bytes: 4-byte aligned, violates 8-byte public boundary */ assert(!push_pair_fd(&c, 4U, 14U) && c.r[13] == 7U); printf("AAPCS32 frame=8B sp_word=%u r0=%u r4=0x%08X ret_pc=0x%08X\n", 8U, c.r[0], c.r[4], c.r[15]); return 0; }- Require 8-byte SP alignment and an even push count before entering a nested AAPCS32 public call.
- Store r4 at the lower word (sp) and lr at the upper word (sp + 1) matching hardware register-number order.
- Clobber caller-saved r1..r3, r12, and live lr inside the nested call while requiring r4..r11 to match on exit.
Running the Frame Verifier and Checking Target Encodings
Compile and run aapcs32_frame_verifier.c, then cross-assemble target.S. Remember that on physical i.MX6ULL silicon, stmfd sp!, {r4, lr} also requires sp to point into live RAM (128 KiB OCRAM 0x00900000..0x00920000 before DDR3 init, or calibrated DDR3 afterward)—an 8-byte-aligned pointer into uninitialized DDR3 still crashes on first push!
learner@ksa:~/gl-e01/m02-l03gcc -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-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m02-l03learner@ksa:~/gl-e01/m02-l03strace -e trace=write,exit_group \./aapcs32_frame_verifierwrite(1, "AAPCS32 frame=8B sp_word=8 r0=32"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++Control-Transfer Matrix and Balanced Exit Paths
Audit every early-return branch in hand-written assembly: if an error path jumps to bx lr after stmfd sp!, {r4, lr} without executing ldmfd sp!, {r4, pc}, SP leaks 8 bytes and bx lr jumps to a clobbered inner LR!
| Instruction | Updates LR? | Restores CPSR? | Interworks ARM/Thumb? | Valid Use Case |
|---|---|---|---|---|
b label | No | No | No (same ISA state) | Local unconditional jump or zero-frame tail-call |
bl helper | Yes (LR = next_instr) | No | No (BLX switches state) | Standard subroutine call; clobbers caller's live LR |
bx lr | No | No | Yes (LR[0] == 1 -> Thumb) | Leaf-function subroutine return (0 stack accesses) |
ldmfd sp!, {r4, pc} | No (loads saved LR -> PC) | No (^ suffix is exception-only) | Yes in ARMv7-A | Non-leaf subroutine epilogue restoring 8-byte frame |
Later: Module 3 (m03-l01..m03-l03) applies BIC, ORR, DSB SY, and AAPCS32-callable assembly routines directly to i.MX6ULL CCM clock gates, IOMUXC pad electricals, and GPIO1 W1C registers.
Common Production Pitfalls
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.
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).
Practice & Retrieval
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, uint32_t e) from assembly with SP = 0x87820000, state where a..d and e go and how much stack space to allocate (a..d in r0..r3; allocate 8 bytes via sub sp, sp, #8 so SP = 0x8781FFF8 stays 8-byte aligned, placing e at [sp, #0] and 4 pad bytes at [sp, #4]). Step 2 (Bitmask Order): List the exact byte addresses written by stmfd sp!, {r12, r4, lr, r6} from SP = 0x1000 (r4 @ 0x0FF0, r6 @ 0x0FF4, r12 @ 0x0FF8, lr @ 0x0FFC). Step 3 (Scratch Check): State whether r12 survives bl pack5 (No—r12 is caller-saved IP scratch!).
Independent Practice: General 16-Bit Bitmask STMFD/LDMFD Verifier (stmfd_abi_audit.c)
Extend aapcs32_frame_verifier.c into stmfd_abi_audit.c implementing exec_stmfd() and exec_ldmfd() for any non-zero uint16_t regmask. Prove that storage order depends solely on bit index 0..15, reject regmask == 0, enforce SP mod 8 == 0 at simulated C call sites, and verify a 5-argument call frame ([sp, #0] = arg4, [sp, #4] = pad).
? check 1 · 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?
- [x]
outer_fnbranches back into itself right afterbl inner_fnin an infinite loop becausebl inner_fnoverwrote the outer return address inLR - [ ]
r0..r3become permanently banked toinner_fn - [ ] The linker automatically rewrites
bx lrintoldmfd sp!, {pc}
Answer: outer_fn branches back into itself right after bl inner_fn in an infinite loop because bl inner_fn overwrote the outer return address in LR
Why: 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.
? check 2 · 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?
- [ ] Subtract
4fromLRbefore pushing so the return address alignsSP - [ ] Clear
spbits[2:0]withbic sp, sp, #7after pushing without restoring the oldsp - [x] Push a balanced
8-byte register pair such asstmfd sp!, {r4, lr}(or allocate4extra pad bytes) soSP mod 8 == 0holds at the call
Answer: Push a balanced 8-byte register pair such as stmfd sp!, {r4, lr} (or allocate 4 extra pad bytes) so SP mod 8 == 0 holds at the call
Why: 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.
? check 3 · Retrieval: when stmfd sp!, {lr, r4} executes at SP = 0x1000, which word lands at the lower address 0x0FF8?
- [ ]
lr(r14), becauselrwas written first inside{lr, r4} - [x]
r4, because hardware encodes a16-bit register bitmask and always stores the lowest-numbered register at the lowest address - [ ] Neither;
STMFDstores at0x1000and0x1004before decrementingSP
Answer: r4, because hardware encodes a 16-bit register bitmask and always stores the lowest-numbered register at the lowest address
Why: 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.
1. Motivation
Early ARMv7-A startup routines fail in subtle ways when a mode transition from IRQ (0x12) to SVC (0x13) accidentally clears CPSR.I/CPSR.F (bits 7:6) or condition flags NZCV (bits 31:28), when a memory-copy loop confuses pre-indexed [Rn, #4]! with post-indexed [Rn], #4 and skips the first word of .data, or when a prologue pushes an odd register count and violates AAPCS32 8-byte SP alignment ((SP mod 8) == 0) before calling C. In this laboratory, you will diagnose a swapped effective-address calculation in starter/core.c and verify CPSR mode-field masking, pre/post indexing semantics, 4-bit BIC/ORR field replacement, and full-descending AAPCS32 stack-frame invariants.
2. Learning Objectives
- Preserve
CPSRstatus, endianness, thumb, and interrupt-mask bits (~0x1FU) when replacingM[4:0](select_mode) to enterSVC(0x13). - Distinguish pre-indexed (
base + offset) from post-indexed (base) memory effective addresses ineffective()so load/store models matchCortex-A7AGU hardware. - Mask oversized
4-bit field inputs ((value & 15U) << 8) after clearingbits [11:8](~0xF00U) inreplace_field(). - Enforce full-descending
8-byte-aligned two-word stack pushes (r4at lower addresswords[*sp],lratwords[*sp + 1U]) inframe().
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) executing insidelabs/lab_m02_armv7_isa_sim/. - Target Architecture Alignment: Models
32-bitARMv7-A(A32state) architectural registers (CPSR,r0..r15) andAAPCS32word-indexed stack memory (words[0..7],4bytes per word, even word index<=>8-byte byte-address alignment).
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0JTAG debuggers or physicalCortex-A7boards required for the 5-checkTAPgrader).
5. Complete Executable Commands
Execute the command sequence below inside labs/lab_m02_armv7_isa_sim/ to reproduce not ok 3 on starter/, inspect the failing case-2 assertion, build files/libbsp.a, and verify 5/5 TAP checks:
learner@ksa:~/gl-e01/m02-l03$ bat script.sh File: script.sh # 1. Run check.sh against an isolated copy of starter/ to observe check 3 fail (# pass 4/5) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Compile tests.c against starter/core.c and execute cases 1..4 individually TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/sim" && for c in 1 2 3 4; do "$TMP/sim" "$c" && echo "case $c: PASS" || echo "case $c: FAIL (rc=$?)"; done ; rm -rf "$TMP" # 3. Compile files/libbsp.a and disassemble effective() and frame() to inspect generated instructions make -B -C files nm -g --defined-only files/libbsp.a && objdump -d files/core.o # 4. Run the graded TAP version 13 harness on files/ sh check.sh*Why each step runs:* Step 1 exercises starter/ through the exact check.sh grader without overwriting files/core.c; Step 2 isolates case 2 (effective) as the sole SIGABRT while confirming cases 1, 3, and 4 pass; Step 3 confirms clean -Werror archive generation; and Step 4 validates all 5 TAP invariants.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
select_mode(uint32_t old, uint32_t mode)(core.c:2-5): Evaluates(old & ~UINT32_C(0x1f)) | (mode & 0x1fU), modelingBIC r0, r0, #0x1ffollowed byORR r0, r0, #0x13. Intests.ccase1,0xa00000d0U(N=1, C=1, I=1, F=1, USR=0x10) transitions to0xa00000d3U(SVC=0x13) with upper27bits intact.- Seeded Flaw in
starter/core.c:6-9(effective):startercomputesreturn pre ? base : base + offset;-- swapping pre-indexed and post-indexed addressing! OnARMv7-A, post-indexedLDR Rt, [Rn], #4(pre == false) accesses memory atRn(base) before writingRn + 4back toRn, whereas pre-indexedLDR Rt, [Rn, #4]!(pre == true) accesses memory atRn + 4(base + offset). - Verified Repair in
files/core.c:6-9: Restoresreturn pre ? base + offset : base;, matchingtests.ccase2(effective(0x1000U, 4U, false) == 0x1000Uandeffective(0x1000U, 4U, true) == 0x1004U). replace_field&frame(core.c:10-21):replace_field()clears[11:8]with~UINT32_C(0xf00)and truncates oversizedvalue = 0x32Uvia(value & 15U) << 8(0xa5a5f2ffU).frame()enforces*sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U(8-byte alignment), decrements*sp -= 2U, and stores lowest-numberedr4atwords[*sp]andlr(r14) atwords[*sp + 1U]matchingPUSH {r4, lr}(STMDB sp!, {r4, lr}).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m02-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 4/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - preserves CPSR fields while selecting a legal ordinary mode not ok 3 - distinguishes pre-indexed and post-indexed access addresses --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 2; inspect tests.c for the exact input and expected result' ... ok 4 - replaces only the selected field and masks oversized values ok 5 - saves and restores a full-descending aligned register pair # pass 4/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - preserves CPSR fields while selecting a legal ordinary mode ok 3 - distinguishes pre-indexed and post-indexed access addresses ok 4 - replaces only the selected field and masks oversized values ok 5 - saves and restores a full-descending aligned register pair # pass 5/58. Explanation of Observed Behavior
Under starter/, tests.c case 2 aborts immediately at line 14 (assert(effective(0x1000U, 4U, false) == 0x1000U)) because starter added offset = 4U on a post-indexed access and returned 0x1004U. Notice why line 16 (effective(0x1000U, 0U, true) == 0x1000U) would not have caught this defect on its own: when offset == 0U, base and base + offset coincide! Testing a non-zero offset (4U) across both pre == false and pre == true exposes the reversed ternary expression immediately, and repairing files/core.c:8 brings the suite to # pass 5/5.
9. Experiment Variations
- Unmasked
ORRSpill inreplace_field(): Remove& 15Uin a scratch copy soreplace_field()computes(old & ~UINT32_C(0xf00)) | (value << 8)onold = 0x00000000U, value = 0x32U: bit12and bit13(0x3000U) bleed into adjacent register fields, failingtests.c:18. - Swapped Register-List Order in
frame(): Swapwords[*sp] = lr; words[*sp + 1U] = r4;and runverify 4:ARMv7-ASTMDB sp!, {r4, lr}always places the lowest register number (r4) at the lowest memory address regardless of assembly syntax order, sowords[6] == 0x44444444Uaborts. - 4-Byte Misaligned Call-Site
SP: Remove(*sp & 1U) != 0Uin a scratch copy and observetests.c:26(sp = 1U, byte offset4) fail, demonstrating whyAAPCS32rejects odd-word stack pointers at public boundaries.
10. Performance Measurements
Benchmarked on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed runs):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Hardware Timing |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + verify 1..4) | 127.95 ms | 136.35 ms | 142.79 ms | Host build + process spawn overhead |
verify 4-case ISA simulator suite (1..4 sequential) | 3466.4 us | 4050.7 us | 4293.0 us | < 1.5 us direct C calls without OS execve |
CPSR mode change (MRS + BIC + ORR + MSR + ISB) | ~1 ns pure ALU | ~2 ns | ~2 ns | ~12 - 20 cycles (23 - 38 ns, pipeline flush at ISB) |
11. Troubleshooting
| Symptom | Root Cause | Fix | |
|---|---|---|---|
not ok 3 (effective fails case 2 at tests.c:14) | Ternary returns base for pre == true and base + offset for pre == false | Return pre ? base + offset : base; in files/core.c | |
not ok 2 (CPSR NZCV or I/F bits clobbered) | Wrote old = mode or masked ~0xffU instead of ~0x1fU | Clear only M[4:0] via `(old & ~UINT32_C(0x1f)) \ | (mode & 0x1fU)` |
not ok 4 (0xa5a5ffffU becomes 0xa5a7f2ffU) | Missing & 15U allowed upper bits of 0x32U to overflow past bit 11 | Mask input width before shifting: ((value & 15U) << 8) | |
not ok 5 (sp = 1U modifies sp or words[]) | Decremented *sp -= 2U before checking *sp < 2U or (*sp & 1U) != 0U | Validate *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U prior to mutating *sp |
12. Guided Questions
- Why do
.datacopy loops inARMv7-A_startoverwhelmingly use post-indexedLDR r3, [r0], #4/STR r3, [r1], #4rather than pre-indexed[r0, #4]!?
- *Hint 1:* Linker symbols
__data_load(r0) and__data_start(r1) point directly to byte0of the section, not4bytes below it. - *Hint 2:* Trace which address the very first iteration loads under
pre = true(r0 + 4, skipping word0!) versuspre = false(r0, then advancingr0 <- r0 + 4for iteration2).
- Why does
AAPCS32mandate8-byteSPalignment ((*sp & 1U) == 0Uin32-bit words) at public function boundaries when ordinaryr0..r15registers are only4bytes wide?
- *Hint 1:* Consider instructions that transfer
64-bit doublewords on the stack (LDRD/STRD,VPUSH/VPOP, andint64_t/uint64_t/doubleprintfvarargs). - *Hint 2:* What alignment fault fires on
Cortex-A7whenLDRDexecutes against an address that is4-byte aligned (0x...4) instead of8-byte aligned (0x...0or0x...8)?
13. Independent Challenges
- Near Transfer — Legal
Cortex-A7Mode Whitelist (select_mode_checked): Writebool select_mode_checked(uint32_t old, uint32_t mode, uint32_t *out)that accepts only the9architecturalCortex-A7M[4:0]encodings (0x10,0x11,0x12,0x13,0x16,0x17,0x1A,0x1B,0x1F) and rejects reserved5-bit patterns such as0x00or0x14without altering*out. - Far Transfer — Paired Epilogue
unframe()(LDMIA sp!, {r4, pc}): Implementbool unframe(const uint32_t *words, unsigned *sp, uint32_t *r4_out, uint32_t *pc_out)that validates*sp <= 6U && (*sp & 1U) == 0U, popsr4andpcin full-descending order, increments*sp += 2U, and provesframefollowed byunframeis an exact identity on(sp, r4, lr).
14. Solutions & Explanations
- Guided Question 1: Because linker start symbols address the first element (
offset 0), post-indexed[Rn], #4dereferencesRn + 0on iteration0and leavesRnequal to_edatawhen the loop terminates; pre-indexed[Rn, #4]!would skip[Rn + 0]unless the pointer were pre-biased by-4. - Guided Question 2:
AAPCS32alignsSPto8bytes at every public call site so callees can issue64-bitLDRD/STRDandVFPstack spills without runtime realignment prologues or alignment data aborts. - Challenge 1 Bitmask Trick: Since
mode & 0x1fUlies in0..31, test membership inO(1)viaconst uint32_t legal = (1U<<0x10)|(1U<<0x11)|(1U<<0x12)|(1U<<0x13)|(1U<<0x16)|(1U<<0x17)|(1U<<0x1a)|(1U<<0x1b)|(1U<<0x1f);and check(mode <= 0x1fU) && ((legal >> mode) & 1U) != 0U.
Run locally in your terminal and check off each verification milestone.
Not started
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). - 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.
Step sequence — frame strip: steps_m02_l03
Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.
reveals: step1
highlights: step1
Step 2 (Prologue Save): stmfd sp!, {r4, lr} decrements SP by 8 bytes, placing r4 at [sp] and LR at [sp + 4].
reveals: step2
highlights: step2
Step 3 (Nested Call): Inner BL overwrites live LR and scratch r0..r3/r12 while saved LR and r4 remain safe on the stack.
reveals: step3
highlights: step3
Step 4 (Epilogue Pop): ldmfd sp!, {r4, pc} restores caller r4, pops outer LR into PC, and restores SP.
reveals: step4
highlights: step4
m03/
IOMUXC muxing, pad electrical policy, and GPIO MMIO
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.
Why SoCs Gate Peripheral Clocks and Multiplex Package Balls
Why can't you just write *gpio1_dr = 0 immediately after reset and watch GPIO1_IO03 pull low? Two physical constraints of modern CMOS silicon stand between a peripheral register and a package pin, both mapped in Figure 3.1a:
- Dynamic Switching Power &
CCM_CCGR0..CCGR6Clock Gates (0x020C4068..0x020C4080): Every CMOS flip-flop burns dynamic power proportional to capacitance, voltage squared, and clock frequency (P = C * V^2 * f). Ani.MX6ULLintegrates over50peripheral blocks (UART1..8,I2C1..4,SPI1..4,GPIO1..5,USDHC1..2,ENET1..2,CAN1..2). Clocking all of them continuously would waste power in battery and industrial gateways, so the Clock Control Module (CCM) places16two-bit Clock Gate (CG0..CG15) latches inside each of the seven32-bitCCGR0..CCGR6words (00= clock off,01= clock on inRUNmode only,10= reserved,11= clock on inRUNandWAITlow-power idle). Crucially, if a peripheral'sCGfield is00, its internalIPGbus interface flip-flops receive zero clock edges—so reading or writing its registers either hangs/aborts on the bus or drops your write silently! Resist the tutorial anti-pattern of blasting0xFFFFFFFFUintoCCGR0..CCGR6: update only the2-bitCGslot you own so power policy and missing-clock bugs remain diagnosable. - BGA Pin Scarcity &
IOMUXCAlternate-Function Crossbars (0x020E0000+): A14 x 14 mmi.MX6ULLpackage has roughly100+general I/O balls, yet its internal peripherals expose over600distinct I/O signals! Silicon solves this by placing an I/O Multiplexer (IOMUXC_SW_MUX_CTL_PAD_*) behind each package ball. Each ball physically wires only a small subset ofALT0..ALT8functions (for ballGPIO1_IO03,ALT0=I2C1_SDA,ALT5=GPIO1_IO03, etc.—not everyALTnumber0..8exists on every ball!). UntilMUX_MODE[3:0]selectsALT5(5),GPIO1's data latch can toggle all day while the physical ball remains connected toI2C1orUART!
Figure 3.1a. End-to-end silicon signal graph — CCM clock gate (CG13), peripheral block, MUX_MODE + SION loopback, and SELECT_INPUT daisy routing.
mental model: 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.
definition (CCM Clock Gates (CCGR0..6), IOMUXC MUX_MODE, SION & SELECT_INPUT): 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.
Step through the four hardware dependencies in order before writing register code:
- Step 1. Step 1 (CCM Policy): Update only CCGR1[27:26] = 0b11 (mask 0x0C000000) and issue DSB SY before touching GPIO1.
- Step 2. Step 2 (Pad Function Table): Confirm the exact ball implements the target ALT mode (not all pads implement ALT0..ALT8).
- Step 3. Step 3 (Mux Register): Replace MUX_MODE[3:0] + SION[4] via (*mux & ~0x1FU); set SION=1 only when output pad readback is needed.
- Step 4. Step 4 (Observable Pad): Program SELECT_INPUT DAISY for shared RX inputs, then configure pad electricals and GPIO direction.
Figure 3.1b. Enable the peripheral clock first, then select a pad-supported ALT mode, SION policy, and SELECT_INPUT daisy source.
What SION and Daisy-Chain Input Muxes Physically Connect
Demystify two IOMUXC features that trip up experienced engineers—both drawn in Figure 3.1a and bit-mapped in Figure 3.1b:
- What
SION(Software Input On,bit 4) Does—and Does Not—Do: Inside every bidirectional pad cell sit two buffers: an output tri-state driver (peripheral -> ball) and an input receiver (ball -> peripheral). When a peripheral drives an output, hardware normally turns off the input feedback path unless that protocol expects it. SettingSION = 1(0x15=SION | ALT5) forces that single ball's input receiver ON, lettingGPIO1_PSRobserve actual wire voltage while driving an output or letting anI2Ccontroller monitor open-drain bus arbitration!SIONis not a magic internal wire connectingUART1_TXtoSPI2_RX; it only enables input sampling of that physical ball. - Why
SELECT_INPUT(DAISY) Exists: An output mux (1ball choosing among8peripherals) lives at the ball. What about an input signal likeUART1_RX_DATAthati.MX6ULLallows you to wire to2or4different package balls? TheUART1receiver needs its ownN-to-1multiplexer (IOMUXC_UART1_RX_DATA_SELECT_INPUT) whoseDAISYbits tellUART1which ball to listen to! ForgettingSELECT_INPUTleavesTXworking whileRXlistens to an unconnected pin.
Figure 3.1b. Exact 32-bit bitfields for CCM_CCGR1 (top) and IOMUXC_SW_MUX_CTL_PAD_GPIO1_IO03 + SELECT_INPUT (bottom).
Trace gpio1_clock_and_mux in target.S below: first it updates CCM_CCGR1 (0x020C406C) bits [27:26] (3 << 26 = 0x0C000000) via bic + orr and drains the store buffer with dsb sy so GPIO1 is clocked before any GPIO1 access; second it clears 0x1F (SION | MUX_MODE) in SW_MUX_CTL_PAD_GPIO1_IO03 (0x020E0068), installs ALT5 (#5 with SION = 0), and executes dsb sy.
learner@ksa:~/gl-e01/m03-l01$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global gpio1_clock_and_mux gpio1_clock_and_mux: ldr r0, =0x020c406c ldr r1, [r0] bic r1, r1, #(3 << 26) orr r1, r1, #(3 << 26) str r1, [r0] dsb sy ldr r0, =0x020e0068 ldr r1, [r0] bic r1, r1, #0x1f orr r1, r1, #5 str r1, [r0] dsb sy bx lrValidating 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! Even though MUX_MODE[3:0] can represent 0..15, iomuxc_set_mux() checks (allowed_alts & (UINT16_C(1) << alt)) != 0U so requesting unimplemented ALT8 on GPIO1_IO03 fails cleanly without touching *mux_ctl. Likewise, ccgr_set_gate() rejects reserved mode == 2 (0b10) and index >= 16, while iomuxc_set_daisy() enforces choice < daisy_count.
learner@ksa:~/gl-e01/m03-l01$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 iomuxc_mux_daisy_audit.c File: iomuxc_mux_daisy_audit.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> static bool ccgr_set_gate(uint32_t *ccgr, unsigned index, unsigned mode) { if (index >= 16U || mode > 3U || mode == 2U) return false; uint32_t shift = index * 2U, mask = UINT32_C(3) << shift; *ccgr = (*ccgr & ~mask) | ((uint32_t)mode << shift); return true; } static bool iomuxc_set_mux(uint32_t *mux_ctl, unsigned alt, bool sion, uint16_t allowed_alts) { if (alt > 8U || (allowed_alts & (UINT16_C(1) << alt)) == 0U) return false; *mux_ctl = (*mux_ctl & ~UINT32_C(0x1f)) | alt | (sion ? 0x10U : 0U); return true; } static bool iomuxc_set_daisy(uint32_t *sel_inp, unsigned choice, unsigned daisy_count) { if (daisy_count == 0U || daisy_count > 4U || choice >= daisy_count) return false; *sel_inp = (*sel_inp & ~UINT32_C(3)) | choice; return true; } int main(void) { uint32_t ccgr1 = 0xa5a5a5a5U, old = ccgr1; assert(ccgr_set_gate(&ccgr1, 13U, 3U)); assert((ccgr1 & 0x0c000000U) == 0x0c000000U); assert((ccgr1 & ~0x0c000000U) == (old & ~0x0c000000U)); old = ccgr1; assert(!ccgr_set_gate(&ccgr1, 16U, 3U) && ccgr1 == old); assert(!ccgr_set_gate(&ccgr1, 13U, 2U) && ccgr1 == old); uint32_t mux = 0xa5a5a5a5U; uint16_t pad_io03_alts = (UINT16_C(1) << 0) | (UINT16_C(1) << 5); assert(iomuxc_set_mux(&mux, 5U, true, pad_io03_alts) && (mux & 0x1fU) == 0x15U); old = mux; assert(!iomuxc_set_mux(&mux, 8U, false, pad_io03_alts) && mux == old); assert(iomuxc_set_mux(&mux, 5U, false, pad_io03_alts) && (mux & 0x1fU) == 0x05U); uint32_t daisy = 0x00000002U; assert(iomuxc_set_daisy(&daisy, 1U, 4U) && (daisy & 3U) == 1U); assert(!iomuxc_set_daisy(&daisy, 4U, 4U) && (daisy & 3U) == 1U); printf("CCGR1_CG13=0x%08X MUX_ALT5_SION=0x15 MUX_ALT5=0x%02X DAISY=%u\n", ccgr1 & 0x0c000000U, mux & 0x1fU, daisy & 3U); return 0; }- Update only the 2-bit CG[index] field in CCGRx while rejecting index >= 16 or reserved mode 2.
- Check (allowed_alts & (1U << alt)) before writing MUX_MODE[3:0] and compose SION at bit 4.
- Validate SELECT_INPUT daisy-chain choice against the receiver's pad count when an input signal has multiple pad sources.
Running the Clock-Gate and Pinmux Verifier
Compile and run iomuxc_mux_daisy_audit.c on the workstation and cross-assemble target.S into target.o. Notice how MUX_ALT5_SION=0x15 (0x10 | 0x05) and MUX_ALT5=0x05 clear stale SION bits cleanly because & ~0x1FU wipes both [4] and [3:0] before ORing.
learner@ksa:~/gl-e01/m03-l01gcc -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-l01clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m03-l01learner@ksa:~/gl-e01/m03-l01strace -e trace=write,exit_group \./iomuxc_mux_daisy_auditwrite(1, "CCGR1_CG13=0x0C000000 MUX_ALT5_S"..., 63) = 63exit_group(0) = ?+++ exited with 0 +++Clock-Gate and Pin-Routing Policy Matrix
Compare narrow field updates against blanket register writes below. When U-Boot or the Linux kernel pinctrl-imx6ul driver takes over later in the boot chain, clean per-peripheral gates make power and pin-conflict debugging immediate.
| Bring-Up Practice | Register Effect | Side-Effect / Power Scope | Engineering Verdict |
|---|---|---|---|
Masked CGk update (~(3U << 2k)) | Updates 2 bits in 1 CCGR word | Neighboring 15 peripheral clocks untouched | Recommended: explicit dependency and minimal power waste |
Blanket CCGR0..6 = 0xFFFFFFFFU | Forces all 112 CG slots to 0b11 | Masks missing-clock bugs; clocks unused IP in WAIT | Avoid: hides broken driver clock claims |
MUX_MODE = ALT5, SION = 0 (0x05) | Routes GPIO mux; normal dir-controlled input | Standard unidirectional input or output | Default for pure outputs/inputs |
MUX_MODE = ALT5, SION = 1 (0x15) | Forces pad input buffer active (PSR live) | Slightly higher receiver switching activity | Use when: reading actual wire state (PSR / I2C) on driven net |
Later: Lesson m03-l02 opens the electrical pad cell right behind SW_MUX_CTL—decoding Schmitt hysteresis (HYS), hierarchical pull vs bus keeper bias (PKE/PUE/PUS), open-drain (ODE), and DSE drive impedance.
Common Production Pitfalls
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 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_*.
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.
Practice & Retrieval
Guided Practice: Deriving GPIO5 Clock Gates & SION Masks
Step 1 (CCGR1 CG15): Given CCM_CCGR0 at 0x020C4068, verify CCM_CCGR1 is 0x020C406C and compute the 32-bit clear mask and RUN-only (0b01) value for CG15 (GPIO5, shift = 30: mask 0xC0000000U, RUN-only 0x40000000U). Step 2 (SION Byte): Compute the SW_MUX_CTL low byte for ALT0 (I2C1_SDA) with SION = 1 (0x10U | 0x00U = 0x10U) and state why I2C open-drain arbitration needs SION = 1. Step 3 (Allowed ALTs): Write allowed_alts in hex for a pad implementing ALT0, ALT1, ALT3, ALT5, and ALT8 (0x012BU).
Independent Practice: Board Pinmux & Daisy-Chain Conflict Linter (pinmux_table_audit.c)
Write a standalone ISO C11 verifier pinmux_table_audit.c auditing an array of struct pin_cfg board entries. Reject duplicate mux_addr collisions (two drivers claiming one ball!), unimplemented alt modes, missing sel_inp_addr when daisy_max > 1, daisy >= daisy_max, ccgr_idx > 6, or cg_slot >= 16 across 1 valid 4-pin table and 4 faulted configurations.
? check 1 · 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?
- [ ]
GPIO1_DRrequires a64-bit store to overrideI2C1 - [x]
IOMUXC_SW_MUX_CTL_PAD_GPIO1_IO03(0x020E0068) has not been switched toALT5(MUX_MODE = 5) - [ ]
CCM_CCGR0..6must all be written to0xFFFFFFFFUbeforeGPIO1routes to a ball
Answer: IOMUXC_SW_MUX_CTL_PAD_GPIO1_IO03 (0x020E0068) has not been switched to ALT5 (MUX_MODE = 5)
Why: 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.
? check 2 · Why must iomuxc_set_mux() reject ALT8 (8) on GPIO1_IO03 even though MUX_MODE[3:0] is 4 bits wide (0..15)?
- [x] Each physical SoC ball wires only its documented subset of alternate functions; unimplemented
ALTencodings leave the pin disconnected or undefined - [ ]
ALT8is reserved exclusively forHyp(PL2) mode instructions - [ ]
ALT8becomes valid on every pad as soon asSION(bit 4) is set to1
Answer: Each physical SoC ball wires only its documented subset of alternate functions; unimplemented ALT encodings leave the pin disconnected or undefined
Why: 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.
? check 3 · Retrieval: what does setting SION (bit 4 = 1) in IOMUXC_SW_MUX_CTL_PAD_* physically accomplish?
- [ ] It cross-connects any internal TX peripheral directly to any chosen RX peripheral without touching a ball
- [ ] It bypasses
CCM_CCGRxclock gates and setsGPIO_GDIRto input automatically - [x] It forces that specific pad's input buffer active so peripherals/software can sample actual ball state even while driving an output
Answer: It forces that specific pad's input buffer active so peripherals/software can sample actual ball state even while driving an output
Why: 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.
Summary
CCM_CCGR0..CCGR6(0x020C4068..0x020C4080) gate peripheral clocks using16two-bitCGfields per word (00off,01RUN,11RUN+WAIT); enable the clock +dsb sybefore accessing peripheral .- 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.- 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.
Step sequence — frame strip: steps_m03_l01
Step 1 (CCM Policy): Update only CCGR1[27:26] = 0b11 (mask 0x0C000000) and issue DSB SY before touching GPIO1.
reveals: step1
highlights: step1
Step 2 (Pad Function Table): Confirm the exact ball implements the target ALT mode (not all pads implement ALT0..ALT8).
reveals: step2
highlights: step2
Step 3 (Mux Register): Replace MUX_MODE[3:0] + SION[4] via (*mux & ~0x1FU); set SION=1 only when output pad readback is needed.
reveals: step3
highlights: step3
Step 4 (Observable Pad): Program SELECT_INPUT DAISY for shared RX inputs, then configure pad electricals and GPIO direction.
reveals: step4
highlights: step4
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.
Inside an i.MX6ULL CMOS Pad Cell: Transistors, Bias, and Hysteresis
Open almost any vendor file and you will spot magic constants like *pad_ctl = 0x10B0; with a misleading comment claiming *"100K pull-down LED config."* If you copy 0x10B0 onto an external button input expecting a 100 kOhm pull-down resistor, pressing the button once latches the pin forever—because 0x10B0 does NOT enable a pull-down resistor at all! Why? Stop memorizing hex literals and trace the three analog/CMOS subcircuits inside a physical i.MX6ULL pad cell in Figure 3.2a (IOMUXC_SW_PAD_CTL_PAD_GPIO1_IO03 at 0x020E02F4):
- Schmitt-Trigger Input Receiver (
HYS, bit16): A plain CMOS inverter switches around a single threshold (~V_DD / 2). When a slow RC sensor edge crawls across1.65 Vcarrying40 mVof power-rail noise, a single-threshold receiver fires a burst of false0->1->0->1digital glitches! EnablingHYS = 1(hysteresis) activates positive feedback inside the receiver, splitting the rising threshold (V_IH) above the falling threshold (V_IL) so small noise ripples inside the deadband are ignored. Crucial limit:HYSrejects millivolt analog noise on an edge—it is not a time-based debouncer and cannot absorb5..15 msmechanical switch contact bounce! - Hierarchical Bias Network (
PKEbit12->PUEbit13->PUSbits[15:14]): Why three separate fields? Because silicon offers two fundamentally different weak bias circuits behind one master power switchPKE(Pull/Keeper Enable, bit12):
- If
PKE == 0, the entire bias block is disconnected (Hi-Zfloating input). - If
PKE == 1andPUE == 0(Pull/Keeper Select = Keeper), silicon connects a weak cross-coupled inverter latch (bus keeper) that gently holds whichever logic0or1was last driven on the wire—andPUS[15:14]is completely ignored! That proves why0x10B0(bit 12 = 1,bit 13 = 0) is a bus keeper, never a100 kOhmpull-down! - Only when
PKE == 1ANDPUE == 1does silicon connect the resistivePUS[15:14]network:00=100 kOhmpull-down,01=47 kOhmpull-up,10=100 kOhmpull-up,11=22 kOhmpull-up.
- Output Driver Stage (
ODEbit11,SPEED[7:6],DSE[5:3],SRE[0]): Normal push-pull mode (ODE = 0) drives bothPMOS(high) andNMOS(low). SettingODE = 1(Open-Drain Enable) disables the high-sidePMOStransistor: writing0actively sinks toGND, whereas writing1releases the wire (Hi-Z) so an external pull-up resistor (2.2 kOhm..4.7 kOhmonI2C) pulls the bus high attau = R_pull * C_bus! Meanwhile,DSE[5:3](Drive Strength) switches1..7parallel transistor fingers in (R0/1~260 ohmdown toR0/6~43 ohm,R0/7~37 ohm)—whereasDSE == 0disconnects ALL output fingers (Hi-Z), killing output drive even whenGPIO_GDIR == 1!SRE[0](Slew Rate) selects slow (0, lower EMI/ringing) vs fast (1, sharp high-frequency edges).
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).
mental model: 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.
definition ( SW_PAD_CTL Electrical Policy Bitfields): 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.
Step through the four-stage electrical design checklist below:
- Step 1. Step 1 (Input Path): Enable HYS[16] = 1 for Schmitt noise immunity on slow digital edges (still debounce switches in software!).
- Step 2. Step 2 (Bias Network): Check PKE[12] = 1 and PUE[13] = 1 before trusting PUS[15:14]; PUE = 0 selects bus keeper.
- Step 3. Step 3 (Output Path): Set ODE[11] = 1 for open-drain release and choose non-zero DSE[5:3] (DSE = 0 disables the output driver!).
- Step 4. Step 4 (Measurement): Preserve reserved gaps (~0x0001F8F9U) and verify rise time tau = R * C and rail levels on an oscilloscope.
Figure 3.2b. Decode PKE -> PUE -> PUS and DSE != 0 explicitly instead of copying opaque hex constants.
Decoding 32-Bit SW_PAD_CTL Words and Preserving Reserved Gaps
Inspect Figure 3.2b to compare the exact 32-bit bitfield layout (0x0001F8F9U active mask, leaving [31:17], [10:8], and [2:1] untouched) across three real board roles:
0x000010B0(Push-Pull LED Output):PKE=1, PUE=0(Keeper),SPEED=2(100 MHz),DSE=6(R0/6),SRE=0(slow edge—no needless RF ringing for a1 HzLED!).0x0001B000(Pulled-Up Digital Input,pad_policy.cbelow):(1U << 16) | (2U << 14) | (1U << 13) | (1U << 12)enablesHYS=1,PUS=2(100 kOhmpull-up),PUE=1(pull mode!), andPKE=1, withDSE=0.0x0001B8B0(Open-DrainI2CBus): AddsODE=1(bit 11) +DSE=6+SPEED=2(and pairs withSION=1inSW_MUX_CTLplus an external2.2 kOhmpull-up because internal~100 kOhm * 100 pFtakes~22 usto rise, violating400 kHzI2C's300 nsrise-time spec!).
Figure 3.2b. Exact 32-bit SW_PAD_CTL bitfields under mask 0x0001F8F9 (top) and three verified electrical profiles (bottom).
learner@ksa:~/gl-e01/m03-l02$ bat pad_policy.c File: pad_policy.c #include <stdint.h> static volatile uint32_t *const pad_gpio1_io03 = (volatile uint32_t *)(uintptr_t)0x020e02f4U; void configure_input_pullup(void) { const uint32_t mask = 0x0001f8f9U; const uint32_t policy = (1U << 16) | (2U << 14) | (1U << 13) | (1U << 12); uint32_t old = *pad_gpio1_io03; *pad_gpio1_io03 = (old & ~mask) | (policy & mask); }Encoding and Auditing Hierarchical Pad Policies in C11
iomuxc_pad_ctl_builder.c encodes all eight fields with range checks (pus <= 3, speed <= 3, dse <= 7), implements decode_bias() following the hardware PKE -> PUE gate hierarchy (proving 1U << 13 alone is BIAS_DISABLED while 0x10B0U is BIAS_KEEPER), verifies 0x1B000U (BIAS_PULL) and 0x1B8B0U (od_i2c), and confirms apply_pad_masked() preserves every bit outside 0x0001F8F9U.
learner@ksa:~/gl-e01/m03-l02$ bat -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 31 -H 32 -H 33 -H 34 -H 35 iomuxc_pad_ctl_builder.c File: iomuxc_pad_ctl_builder.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> enum bias_kind { BIAS_DISABLED = 0, BIAS_KEEPER = 1, BIAS_PULL = 2 }; struct pad_cfg { bool hys, pue, pke, ode, sre; unsigned pus, speed, dse; }; static bool build_pad_ctl(const struct pad_cfg *c, uint32_t *word_out) { if (c->pus > 3U || c->speed > 3U || c->dse > 7U) return false; *word_out = ((uint32_t)c->hys << 16) | (c->pus << 14) | ((uint32_t)c->pue << 13) | ((uint32_t)c->pke << 12) | ((uint32_t)c->ode << 11) | (c->speed << 6) | (c->dse << 3) | (uint32_t)c->sre; return true; } static enum bias_kind decode_bias(uint32_t r) { if ((r & (1U << 12)) == 0U) return BIAS_DISABLED; return (r & (1U << 13)) != 0U ? BIAS_PULL : BIAS_KEEPER; } static uint32_t apply_pad_masked(uint32_t old, uint32_t policy) { const uint32_t mask = UINT32_C(0x0001f8f9); return (old & ~mask) | (policy & mask); } int main(void) { assert(decode_bias(0U) == BIAS_DISABLED); assert(decode_bias(1U << 13) == BIAS_DISABLED); assert(decode_bias(0x10b0U) == BIAS_KEEPER); assert(((0x10b0U >> 3) & 7U) == 6U && ((0x10b0U >> 6) & 3U) == 2U); struct pad_cfg in_pullup = {true, true, true, false, false, 2U, 0U, 0U}; uint32_t pol = 0U; assert(build_pad_ctl(&in_pullup, &pol) && pol == 0x1b000U); assert(decode_bias(pol) == BIAS_PULL); struct pad_cfg bad_dse = {false, false, false, false, false, 0U, 0U, 8U}; assert(!build_pad_ctl(&bad_dse, &pol)); uint32_t old = 0xa5a5a5a5U, next = apply_pad_masked(old, pol); assert((next & ~UINT32_C(0x1f8f9)) == (old & ~UINT32_C(0x1f8f9))); struct pad_cfg od_i2c = {true, true, true, true, false, 2U, 2U, 6U}; uint32_t od_word = 0U; assert(build_pad_ctl(&od_i2c, &od_word) && od_word == 0x1b8b0U); printf("0x10B0=keeper(DSE=%u,SPD=%u) pullup=0x%05X od_i2c=0x%05X\n", (0x10b0U >> 3) & 7U, (0x10b0U >> 6) & 3U, pol, od_word); return 0; }- Validate multi-bit ranges (PUS <= 3, SPEED <= 3, DSE <= 7) before shifting into mask 0x0001F8F9U.
- Check PKE (bit 12) before PUE (bit 13): PUS [15:14] has zero pull effect whenever PKE == 0 or PUE == 0.
- Preserve reserved bit gaps [31:17], [10:8], and [2:1] when updating an existing SW_PAD_CTL register.
Running the Pad-Control Builder and Cross-Compiling Target Policy
Execute iomuxc_pad_ctl_builder on the workstation and cross-compile pad_policy.c for freestanding Cortex-A7. Remember that SW_PAD_CTL configures electrical behavior only—SW_MUX_CTL (m03-l01) must still route the desired peripheral function to the ball!
learner@ksa:~/gl-e01/m03-l02gcc -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-l02clang --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-l02learner@ksa:~/gl-e01/m03-l02strace -e trace=write,exit_group \./iomuxc_pad_ctl_builderwrite(1, "0x10B0=keeper(DSE=6,SPD=2) pullu"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++Pad Electrical Role Comparison Matrix
Match every board trace to the electrical profile its external circuit requires:
| Pad Role | Typical SW_PAD_CTL Word | Decoded Active Fields | Electrical Caveat |
|---|---|---|---|
Push-pull GPIO LED output | 0x000010B0 | PKE=1, PUE=0 (keeper), SPEED=2, DSE=6, SRE=0 | DSE=0 (Hi-Z) disables output driver completely even when GDIR=1! |
| tactile switch input | 0x0001B000 | HYS=1, PUS=2 (100K up), PUE=1, PKE=1, DSE=0 | HYS suppresses slow-edge threshold chatter, NOT 5..15 ms contact bounce |
Open-drain shared bus (I2C) | 0x0001B8B0 | HYS=1, PUS=2, PUE=1, PKE=1, ODE=1, DSE=6 | Requires SION=1 in MUX_CTL + external 2.2k..4.7k pull-up for 400 kHz |
High-speed SD/ENET clock/data | 0x000170F9 / B9 | HYS=1, 47K up, SPEED=2/3, DSE=6/7, SRE=1 | Fast slew (SRE=1) + strong DSE rings on unterminated long wires |
Later: Lesson m03-l03 completes the GPIO chain inside 0x0209C000—preload-safe DR/GDIR sequencing, PSR wire observation, ICR1/ICR2 edge configuration, and Write-One-to-Clear (W1C) ISR acknowledgment.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Decoding 0x000178B1 & Encoding Custom Output Pads
Step 1 (Decode): Decode 0x000178B1U field by field (HYS=1, PUS=1 47K pull-up, PUE=1, PKE=1, ODE=1 open-drain, SPEED=2 100 MHz, DSE=6 R0/6, SRE=1 fast slew). Step 2 (Hi-Z Output Check): State why ode = false, dse = 0U fails to drive an LED even when GPIO_GDIR bit 3 is 1 (DSE=0 tri-states the pad buffer). Step 3 (Encode): Compute the hex word for HYS=0, PKE=0, ODE=0, SPEED=1 (50 MHz), DSE=4 (R0/4), SRE=0 ((1U << 6) | (4U << 3) = 0x00000060U).
Independent Practice: Pad-Role Consistency Linter (pad_role_lint.c)
Write a standalone ISO C11 verifier pad_role_lint.c implementing int audit_pad_policy(uint32_t mux_ctl, uint32_t pad_ctl, bool is_output, bool is_od_bus). Flag: (1) is_output && DSE == 0; (2) PUS != 0 && (!PKE || !PUE) (dead pull bits); (3) is_od_bus && (!ODE || !(mux_ctl & 0x10U)); and (4) any set bit outside 0x0001F8F9U. Test 3 valid profiles and 4 defective ones.
? check 1 · 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?
- [x] The weak bus keeper latch is connected;
PUSis inactive becausePUE == 0 - [ ] The
100 kOhmpull-up resistor is active because non-zeroPUSoverridesPUE - [ ] High-side
PMOSdrive forces the pin to3.3 Vregardless of external drivers
Answer: The weak bus keeper latch is connected; PUS is inactive because PUE == 0
Why: 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).
? check 2 · When ODE (bit 11) is 1 (open-drain enabled), what happens electrically at the ball when software writes logical 1 to the output latch?
- [ ] The
PMOShigh-side fingers actively sourceR0/6current up to3.3 V - [ ] The Schmitt trigger toggles the pin until
PSRmatchesDR - [x] Both high-side and low-side output FETs turn off (releasing the line), so an external or internal pull-up resistor must pull the voltage high
Answer: Both high-side and low-side output FETs turn off (releasing the line), so an external or internal pull-up resistor must pull the voltage high
Why: 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.
? check 3 · 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?
- [ ] Yes; enabling
HYSandPUEautomatically selectsALT5(GPIO) - [x] No;
SW_PAD_CTLsets electrical pad behavior only, whileSW_MUX_CTL(0x020E0068) independently selectsMUX_MODE - [ ] Yes, whenever
DSE[5:3]is0(Hi-Z)
Answer: No; SW_PAD_CTL sets electrical pad behavior only, while SW_MUX_CTL (0x020E0068) independently selects MUX_MODE
Why: 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).
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.- 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.
Step sequence — frame strip: steps_m03_l02
Step 1 (Input Path): Enable HYS[16] = 1 for Schmitt noise immunity on slow digital edges (still debounce switches in software!).
reveals: step1
highlights: step1
Step 2 (Bias Network): Check PKE[12] = 1 and PUE[13] = 1 before trusting PUS[15:14]; PUE = 0 selects bus keeper.
reveals: step2
highlights: step2
Step 3 (Output Path): Set ODE[11] = 1 for open-drain release and choose non-zero DSE[5:3] (DSE = 0 disables the output driver!).
reveals: step3
highlights: step3
Step 4 (Measurement): Preserve reserved gaps (~0x0001F8F9U) and verify rise time tau = R * C and rail levels on an oscilloscope.
reveals: step4
highlights: step4
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.
Inside a 32-Pin GPIO Bank: DR Latches, Tri-State GDIR, PSR, and W1C Physics
Why does an i.MX6ULL GPIO controller (GPIO1 at 0x0209C000) expose both a Data Register (DR, +0x00) and a Pad Status Register (PSR, +0x08) alongside GDIR (+0x04)—aren't DR and PSR the same 32 bits? No! Look at the internal logic schematic in Panel 1 of Figure 3.3a:
DR(+0x00) vsGDIR(+0x04) vsPSR(+0x08):DRis an internal32-bit output-request D-flip-flop;GDIR(0= input,1= output) drives the Output-Enable (OE) gate of the tri-state buffer feeding the pad; and read-onlyPSRsamples the actual electrical voltage at the package ball! Two immediate engineering consequences follow:
- Why
DR!=PSR: IfDR[3] = 1andGDIR[3] = 1, yet an external short-circuit or open-drain slave clamps the board trace to0 V(orSW_PAD_CTL.DSE == 0left the driverHi-Z), readingDRreturns1(what you requested), whereas readingPSRreturns0(what is physically on the wire)! - Glitch-Free Active-Low Startup (Panel 2 of Figure 3.3a): At reset,
DRandGDIRboth clear to0. On an active-low LED, buzzer, or relay (0= ON!), if firmware setsGDIR[3] = 1before settingDR[3] = 1, the tri-state buffer turns ON whileDR[3]is still0—firing a spurious low pulse onto the hardware load! Always preloadDRto its safe inactive state (1) +dsb sybefore settingGDIR = 1!
- Interrupt Trigger Split (
ICR1/ICR2) & WhyGPIO_ISRIs Write-One-to-Clear (W1C): Configuring4trigger modes (00low-level,01high-level,10rising-edge,11falling-edge) across32pins takes32 * 2 = 64bits, so hardware splits pins0..15intoICR1(+0x0C) and pins16..31intoICR2(+0x10) at local shift2 * (pin % 16)(withEDGE_SELat+0x1Coverriding for dual-edge capture), masked byIMR(+0x14). Why did silicon architects makeISR(+0x18) Write-One-to-Clear (W1C) instead of ordinary read/write? Because asynchronous pin edges can set a sibling bit inISRon any clock cycle between a CPULDRandSTR! WithW1C(ISR_next = ISR_curr & ~W_data), writing0bits is a hardware no-op and writing a pure mask (0x08for pin3) atomically clears only bit3in a singleSTR—whereas an ordinary RMW (ISR |= 0x08) replays1s on every pending sibling bit (0x0A) and wipes them out (0x00)!
Figure 3.3a. Inside GPIO1 @ 0x0209C000 — separating DR request, GDIR tri-state enable, PSR wire sampling, and the ICR -> ISR () -> IMR interrupt pipeline.
mental model: 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 .I=0 before vectoring the Cortex-A7 CPU.
definition (GPIO Bank Register Map, Half-Bank ICR & Write-One-to-Clear (W1C)): 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.
Step through all four GPIO register roles in the interactive sequence below:
- Step 1. Step 1 (Output Latch): Preload inactive high DR[3] = 1 (+0x00) + DSB SY before enabling output direction.
- Step 2. Step 2 (Direction): Set GDIR[3] = 1 (+0x04) via masked RMW so all 31 neighboring pins keep their directions.
- Step 3. Step 3 (Pad Observation): Sample physical wire state from read-only PSR (+0x08), which can differ from DR under load/clamp.
- Step 4. Step 4 (Event Path): Partition ICR1/ICR2 via pin/16 and acknowledge ISR (+0x18) with a pure 1-bit W1C store.
Figure 3.3b. Match every GPIO operation to its exact register contract: preload DR -> enable GDIR -> sample PSR -> direct-mask W1C ISR.
Half-Bank ICR Shifts, W1C Assembly Stores, and Active-Low LED Routines
Compare the two register traps in Figure 3.3b against our Cortex-A7 assembly listing target.S below:
ICR1(0..15) vsICR2(16..31) Shift Math: Pin15occupies bits[31:30]ofICR1(shift = 30). Pin16starts over at bits[1:0](shift = 0!) ofICR2! Writing2 * pinwithoutpin % 16shifts by32..62for pins16..31—triggeringISO C11Undefined Behavior and missingICR2completely.- Zero-Load
W1CAcknowledgment (gpio1_ack_pin3): Look at lines23..28oftarget.S! Whereasled_prepare_inactiveandled_assertexecuteldr -> orr/bic -> stron ordinary RW latchesDR(0x0209C000) andGDIR(0x0209C004),gpio1_ack_pin3executesmov r1, #8followed immediately bystr r1, [r0](0x0209C018) with NOldr! OnISR = 0x0A(pins3and1pending), storing0x08leaves0x02intact, whereasldr + orr #8 + strwrites0x0Aand destroys pin1's interrupt!
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).
learner@ksa:~/gl-e01/m03-l03$ bat target.S File: target.S .syntax unified .cpu cortex-a7 .arm .text .global led_prepare_inactive led_prepare_inactive: ldr r0, =0x0209c000 ldr r1, [r0] orr r1, r1, #8 str r1, [r0] dsb sy ldr r1, [r0, #4] orr r1, r1, #8 str r1, [r0, #4] bx lr .global led_assert led_assert: ldr r0, =0x0209c000 ldr r1, [r0] bic r1, r1, #8 str r1, [r0] bx lr .global gpio1_ack_pin3 gpio1_ack_pin3: ldr r0, =0x0209c018 mov r1, #8 str r1, [r0] bx lrSimulating GPIO Bank Registers and W1C Race Loss in C11
gpio_w1c_bank_sim.c models all seven core GPIO registers in a deterministic C11 harness: it verifies DR = 0x08 preload divergence from an externally clamped PSR = 0x00, tests boundary pins 15 (ICR1 shift 30), 16 (ICR2 shift 0), 31 (ICR2 shift 30), and out-of-range 32, and proves side-by-side that direct W1C store 0x08 on ISR = 0x0A retains 0x02 (W1C_rem=0x02), while buggy.isr | 0x08U wipes ISR to 0x00 (RMW_rem=0x00).
learner@ksa:~/gl-e01/m03-l03$ bat -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 21 -H 22 -H 23 -H 24 -H 25 -H 36 -H 37 -H 38 -H 39 -H 40 -H 41 gpio_w1c_bank_sim.c File: gpio_w1c_bank_sim.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> struct gpio_bank_sim { uint32_t dr, gdir, psr, icr1, icr2, imr, isr; }; static bool gpio_cfg_icr(struct gpio_bank_sim *b, unsigned pin, unsigned trig) { if (pin >= 32U || trig > 3U) return false; uint32_t *icr = (pin < 16U) ? &b->icr1 : &b->icr2; unsigned shift = (pin % 16U) * 2U; uint32_t mask = UINT32_C(3) << shift; *icr = (*icr & ~mask) | ((uint32_t)trig << shift); return true; } static void gpio_write_isr_w1c(struct gpio_bank_sim *b, uint32_t word_written) { b->isr &= ~word_written; } int main(void) { struct gpio_bank_sim g = {0U, 0U, 0x00000000U, 0U, 0U, 0U, 0U}; g.dr |= (UINT32_C(1) << 3); /* preload inactive high before GDIR=1 */ g.gdir |= (UINT32_C(1) << 3); assert((g.dr & 8U) != 0U && (g.psr & 8U) == 0U); /* external clamp keeps PSR=0 */ assert(gpio_cfg_icr(&g, 15U, 3U) && (g.icr1 >> 30) == 3U); assert(gpio_cfg_icr(&g, 16U, 2U) && (g.icr2 & 3U) == 2U); assert(gpio_cfg_icr(&g, 31U, 1U) && (g.icr2 >> 30) == 1U); assert(!gpio_cfg_icr(&g, 32U, 2U)); g.imr = 0x0aU; /* unmask pin 1 and pin 3 */ g.isr = 0x0aU; /* both pin 1 and pin 3 latched pending */ gpio_write_isr_w1c(&g, UINT32_C(1) << 3); /* direct mask write: 0x08 */ assert(g.isr == 0x02U && (g.isr & g.imr) == 0x02U); struct gpio_bank_sim buggy = g; buggy.isr = 0x0aU; gpio_write_isr_w1c(&buggy, buggy.isr | 0x08U); /* RMW writes 0x0A! */ assert(buggy.isr == 0x00U); printf("DR=0x%02X PSR=0x%02X ICR1_15=%u ICR2_16=%u W1C_rem=0x%02X RMW_rem=0x%02X\n", g.dr, g.psr, g.icr1 >> 30, g.icr2 & 3U, g.isr, buggy.isr); return 0; }- Partition pins 0..15 into ICR1 and pins 16..31 into ICR2 so local shifts stay within [0, 30].
- Hardware W1C clears every bit position written as 1 (b->isr &= ~word_written); writing 0 leaves pending bits intact.
- Contrast direct mask write (0x08 -> leaves sibling 0x02) against RMW (0x0A -> destroys sibling 0x02).
Executing the GPIO Bank Simulator and Assembly Check
Build and run gpio_w1c_bank_sim on the host and cross-assemble target.S for Cortex-A7. Note the system-level boundary: clearing GPIO1_ISR handles the peripheral latch, while end-to-end interrupt delivery on bare-metal silicon also requires routing the bank IRQ through the ARM Generic Interrupt Controller (GICv2, covered in GL-E02).
learner@ksa:~/gl-e01/m03-l03gcc -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-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m03-l03learner@ksa:~/gl-e01/m03-l03strace -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 +++GPIO Register Access Semantics Comparison
Never hide DR and ISR behind one generic set_bit(addr, mask) macro—their hardware write contracts are opposites:
Register (Offset) | Read Meaning | Write Semantics | Safe Single-Pin Update Pattern | |
|---|---|---|---|---|
GPIOx_DR (+0x00) | Latched output value | Ordinary read/write latch | Exclusive-owner `(DR & ~mask) \ | val` |
GPIOx_GDIR (+0x04) | 0 = input, 1 = output | Ordinary read/write latch | Preload DR safe state + dsb sy first, then `GDIR \ | = mask` |
GPIOx_PSR (+0x08) | Sampled pad receiver state | Read-only (const in C overlay) | Read (PSR >> pin) & 1U (set SION=1 if output readback required) | |
GPIOx_ISR (+0x18) | 1 = latched trigger event | Write-One-to-Clear (W1C) | Direct command store ISR = (UINT32_C(1) << pin) (0 loads!) |
Later: Module 4 (m04-l01..m04-l03) shows how the i.MX6ULL internal Boot ROM actually loads your assembled image off SD/eMMC—decoding BOOT_MODE straps, IVT (0x402000D1) headers at 0x400, and DCD (0xD2) big-endian register streams!
Common Production Pitfalls
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);.
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.
Practice & Retrieval
Guided Practice: Configuring GPIO1_IO18 (UART1_CTS_B Button) Interrupts
Step 1 (ICR2 Address & Mask): For GPIO1 (0x0209C000) pin 18, compute the ICR physical address, shift, clear mask, and falling-edge (0b11) value (18 >= 16 -> ICR2 at 0x0209C010, shift (18 % 16) * 2 = 4, clear mask 0x30U, falling-edge 0x30U). Step 2 (EDGE_SEL Override): Because GPIO1_EDGE_SEL (+0x1C) bit 18 = 1 overrides ICR2 to trigger on any edge, confirm EDGE_SEL &= ~(UINT32_C(1) << 18) is required for single-edge ICR2 operation. Step 3 (W1C Trace): Given ISR = 0x000C0008U and IMR = 0x00040008U, state active unmasked pins (3 and 18) and ISR after GPIO1->ISR = (UINT32_C(1) << 18) (0x00080008U).
Independent Practice: Full 8-Register GPIO Edge & Dispatch Simulator (gpio_edge_sim.c)
Extend gpio_w1c_bank_sim.c into gpio_edge_sim.c adding edge_sel (+0x1C) and gpio_apply_pad_transition(struct gpio_bank_sim *b, uint32_t new_pads) latching rising/falling/both edges across all 32 pins, plus dispatch_next_irq() servicing the lowest set bit of b->isr & b->imr via single-bit W1C acknowledgment across simultaneous transitions on pins 0, 15, 16, and 31.
? check 1 · 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?
- [ ]
0x0A, computed viaGPIO1->ISR |= (1U << 3) - [ ]
0x02, computed viaGPIO1->ISR &= ~(1U << 3) - [x]
0x08(UINT32_C(1) << 3) written directly with zero prior read, leaving bit1(0x02) pending
Answer: 0x08 (UINT32_C(1) << 3) written directly with zero prior read, leaving bit 1 (0x02) pending
Why: 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.
? check 2 · Where does GPIO1 pin 16's two-bit interrupt trigger configuration live?
- [ ] In
GPIO1_ICR2(+0x10) at bit shift16(bits [17:16]) - [x] In
GPIO1_ICR2(+0x10) at bit shift0(bits [1:0]) - [ ] In
GPIO1_ICR1(+0x0C) at bit shift32
Answer: In GPIO1_ICR2 (+0x10) at bit shift 0 (bits [1:0])
Why: 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.
? check 3 · Retrieval: why can GPIO1_DR bit 3 read 1 while GPIO1_PSR bit 3 simultaneously reads 0?
- [x]
DRreports the internal output request flip-flop, whereasPSRsamples the physical pad receiver—which can be held low by an external clamp, disabledDSE=0driver, or unselectedIOMUXCroute - [ ] Reading
PSRautomatically switches theCortex-A7intoIRQmode and clearsDR - [ ]
volatilepointers cachePSRin registers across function calls
Answer: DR reports the internal output request flip-flop, whereas PSR samples the physical pad receiver—which can be held low by an external clamp, disabled DSE=0 driver, or unselected IOMUXC route
Why: 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.
1. Motivation
On i.MX6ULL silicon, peripheral bring-up fails across four coupled MMIO registers: accessing GPIO1 while CCM_CCGR1 CG13 (bits 27:26) is 00 stalls or faults on the bus, selecting an unimplemented MUX_MODE routes a pad to nowhere, misreading PKE/PUE in IOMUXC_SW_PAD_CTL confuses a bus-keeper (0x10B0) with an active pull-up (0x1B000), and acknowledging GPIOx_ISR with GPIO1->ISR |= (1U << 3) writes 1 back to every pending interrupt bit -- silently dropping concurrent edge events! In this laboratory, you will locate and repair a destructive W1C read-modify-write bug in starter/core.c and validate all five CCM/IOMUXC/GPIO register helpers under TAP version 13.
2. Learning Objectives
- Update individual
2-bitCCM_CCGRxclock-gate slots (indexin0..15,modein0..3) without disturbing the remaining15peripheral gates in the32-bit word. - Validate per-pad
MUX_MODE[3:0]legality against auint16_t allowedbitmask while orthogonally encodingSION(bit 4,0x10U) inpad_mux(). - Decode
IOMUXC_SW_PAD_CTLbias states (0disabled whenPKE == 0,1keeper whenPKE == 1 && PUE == 0,2pull whenPKE == 1 && PUE == 1) inbias_mode(). - Repair write-1-to-clear (
W1C) interrupt acknowledgment (acknowledge) andGPIOx_ICR1/ICR22-bit register/shift indexing (icr_field) across pins0..31.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m03_iomuxc_gpio_mmio/. - Target Silicon Alignment: Bit positions match
i.MX6ULLCCM_CCGR0..6(2bits perCG),IOMUXC_SW_MUX_CTL_PAD_*(MUX_MODE[3:0],SION[4]),IOMUXC_SW_PAD_CTL_PAD_*(PKE[12],PUE[13]), andGPIO1..GPIO5(ICR1pins0..15,ICR2pins16..31,ISRW1C).
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0physical target hardware required for automatedTAPgrading).
5. Complete Executable Commands
Run the commands below from labs/lab_m03_iomuxc_gpio_mmio/ to reproduce starter/'s W1C bug in check 5, inspect case 4 directly, compile files/libbsp.a, and pass all 5 TAP checks:
learner@ksa:~/gl-e01/m03-l03$ bat script.sh File: script.sh # 1. Stage starter/ in a temporary workspace and run check.sh (# pass 4/5, check 5 fails) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Link tests.c against starter/core.c and run case 4 to trigger the W1C assertion failure TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/mmio" && { "$TMP/mmio" 1 && "$TMP/mmio" 2 && "$TMP/mmio" 3 && echo "cases 1..3 OK"; "$TMP/mmio" 4 || echo "case 4 aborted (rc=$?)"; } ; rm -rf "$TMP" # 3. Build files/libbsp.a cleanly and list the five exported MMIO helper symbols make -B -C files nm -g --defined-only files/libbsp.a # 4. Run the full 5-check TAP version 13 suite sh check.sh*Why each step runs:* Step 1 executes check.sh against starter/ in a disposable directory so files/ stays untouched; Step 2 confirms clock_field, pad_mux, and bias_mode pass (cases 1..3) while acknowledge aborts in case 4; Step 3 rebuilds files/libbsp.a with -MMD -MP; and Step 4 verifies # pass 5/5.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
clock_field&pad_mux(core.c:2-12):clock_field()rejectsindex >= 16U || mode > 3Uand updatesshift = index * 2U(CG13 -> bits 27:26 = 0x0c000000Uintests.ccase1).pad_mux()rejectsalt > 8Ubefore shiftingUINT16_C(1) << alt, checks(allowed & (UINT16_C(1) << alt)) != 0U, and writes(*r & ~UINT32_C(0x1f)) | alt | (sion ? 0x10U : 0U)(0x15UforALT5 + SION).bias_mode&icr_field(core.c:13-17, 22-26):bias_mode()checksPKE(bit 12) first -- returning0Ueven ifPUE(bit 13) is1(1U << 13intests.c:25),1Ufor0x10b0U(keeper), and2Ufor0x1b000U(pull).icr_field()mapspin / 16UtoICR1(0) vsICR2(1) and(pin % 16U) * 2Uto the even shift (pin 15 -> reg 0, shift 30;pin 16 -> reg 1, shift 0).- Seeded Flaw in
starter/core.c:18-21(acknowledge):startercomputesreturn pending & ~(pending | mask);-- the exact state transition produced on hardware when buggy code executesGPIO1->ISR |= mask(writingpending | maskto aW1Cregister clearspending | mask, always leaving0U!). - Verified Repair in
files/core.c:18-21: Replaces the body withreturn pending & ~mask;, modeling a directGPIO1->ISR = maskstore that clears onlymask(0x8U) and leaves concurrent pending bit1(0x2U) intact (acknowledge(0xaU, 8U) == 2U).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m03-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 4/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - updates one clock gate without changing neighboring fields ok 3 - validates pad-specific mux modes and SION independently ok 4 - distinguishes disabled bias keeper and enabled pull not ok 5 - clears only requested W1C events and locates upper ICR fields --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 4; inspect tests.c for the exact input and expected result' ... # pass 4/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - updates one clock gate without changing neighboring fields ok 3 - validates pad-specific mux modes and SION independently ok 4 - distinguishes disabled bias keeper and enabled pull ok 5 - clears only requested W1C events and locates upper ICR fields # pass 5/58. Explanation of Observed Behavior
In tests.c case 4 (line 29), two GPIO lines have latched pending interrupts simultaneously: bit 3 (0x8U) and bit 1 (0x2U), giving pending = 0xaU. When the handler acknowledges bit 3 (mask = 8U), starter/core.c evaluates 0xaU & ~(0xaU | 8U) == 0U, wiping bit 1 before its handler ever runs and aborting check 5 (not ok 5). Even worse, on line 30 (acknowledge(0xaU, 0U)), starter would also wipe 0xaU down to 0U on a no-op mask! Returning pending & ~mask in files/core.c preserves 0x2U on line 29 and 0xaU on line 30, yielding # pass 5/5.
9. Experiment Variations
- Missing
PKEMaster-Enable Check (bias_mode): Changebias_mode()in a scratch copy to inspectPUE(bit 13) without first testingPKE(bit 12):tests.c:25(bias_mode(1U << 13)) returns2U(pull) instead of0U(disabled), mirroring the real datasheet trap wherePUEis ignored wheneverPKE == 0. - Upper-Bank Modulo Omission (
icr_field): Replace(pin % 16U) * 2Uwithpin * 2U:pin = 16Ucomputesshift = 32U(an out-of-range shift width onGPIOx_ICR2instead ofshift = 0UatICR2[1:0]). SIONCleared by Narrow Mux Mask: Change~UINT32_C(0x1f)to~UINT32_C(0x0f)inpad_mux(), callpad_mux(&r, 5U, true, 0x21U)followed bypad_mux(&r, 0U, false, 0x21U), and observe staleSION(0x10U) remain stuck high!
10. Performance Measurements
Measured on Linux 7.0.0-42-generic (x86_64) with CLOCK_MONOTONIC across 5 warmup runs and 35 timed runs:
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Hardware Equivalent |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 135.10 ms | 151.49 ms | 154.74 ms | Host toolchain + shell subshell orchestration |
verify 4-case helper suite (verify 1..4) | 3554.3 us | 4110.7 us | 4220.6 us | < 2 us in-cache register-helper calls |
Direct W1C STR (GPIO1->ISR = mask) vs RMW | 1 store vs 1 load + 1 store | 1 store | 1 store | Saves 1 IPG bus read (~30 - 50 ns) and prevents race loss |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 5 (acknowledge(0xaU, 8U) returns 0U) | starter simulates `ISR \ | = mask via pending & ~(pending \ | mask)` | Return pending & ~mask; (write mask directly to ISR on hardware) |
not ok 4 (bias_mode(1U << 13) returns 2U) | Tested PUE (bit 13) before checking master enable PKE (bit 12) | Return 0U immediately whenever (value & (1U << 12)) == 0U | ||
not ok 3 (pad_mux shifts UB on alt = 32U) | Evaluated UINT16_C(1) << alt prior to checking alt > 8U | Guard `if (alt > 8U \ | \ | ...) return false; before forming 1 << alt` |
not ok 2 (clock_field corrupts adjacent CG slot) | Shifted mode by index (1-bit stride) or failed to reject mode > 3U | Compute shift = index * 2U and guard index < 16U && mode <= 3U |
12. Guided Questions
- Why is a direct
W1Cstore (GPIO1->ISR = (1U << 3)) race-free even if hardware latches bit1on the exactIPGclock cycle just before theSTRlands, whereas a normal RMW register requires interrupt masking?
- *Hint 1:* Inspect every bit position
k != 3in the32-bit value0x00000008Uwritten onto the peripheral data bus. - *Hint 2:* Under the hardware
W1Ccontract, what effect does writing0to bit1have on theISR[1]flip-flop?
- When does an
i.MX6ULLperipheral pin requireSION = 1(bit 4ofIOMUXC_SW_MUX_CTL_PAD_*) in addition to selecting the rightMUX_MODE?
- *Hint 1:* Compare an output-only indicator pad against an open-drain
I2CSCL/SDApad or aGPIOoutput loopback check viaGPIOx_PSR. - *Hint 2:* What happens to the pad's input path when the selected mux function drives the pad purely as an output unless
SIONforces the input buffer active?
13. Independent Challenges
- Near Transfer — Complete
IOMUXC_SW_PAD_CTLEncoder/Verifier: Addbool build_pad_ctl(bool hys, unsigned pus, bool pue, bool pke, bool ode, unsigned speed, unsigned dse, bool sre, uint32_t *out)that rejectspus > 3U || speed > 3U || dse > 7U, packs bits16,15:14,13,12,11,7:6,5:3, and0, asserts(*out & ~0x0001F8F9U) == 0U, and verifiesbias_mode(*out)agrees with(pke, pue). - Far Transfer — Full
ICR1/ICR2Trigger-Type Configurator (gpio_set_irq_trigger): Implementbool gpio_set_irq_trigger(uint32_t *icr1, uint32_t *icr2, uint32_t *edge_sel, unsigned pin, unsigned trig)supportingLOW_LEVEL (0),HIGH_LEVEL (1),RISING_EDGE (2),FALLING_EDGE (3), andBOTH_EDGES (4)(remembering thatEDGE_SEL[pin] = 1overridesICR1/ICR2oni.MX6ULL!).
14. Solutions & Explanations
- Guided Question 1: Writing
0x00000008Uplaces0on bits[31:4]and[2:0]; underW1Chardware logic (next_ISR = (ISR & ~bus_write) | new_hw_edges),0bits are unconditional no-ops, so no read occurs and concurrent hardware edges on bit1cannot be overwritten. - Guided Question 2:
SION = 1forces the pad's input path active regardless of the output mux direction, allowingI2Ccontrollers to monitor bus arbitration/clock-stretching onSDA/SCLand allowing software to read actual physical pad voltage back throughGPIOx_PSR. - Challenge 2 Key Logic: Route
pin < 16Utoicr1andpin >= 16Utoicr2viaicr_field(pin, ®, &shift); iftrig == 4U, set*edge_sel |= (UINT32_C(1) << pin), otherwise clear*edge_sel &= ~(UINT32_C(1) << pin)and writetrig & 3Uinto(reg == 0U ? icr1 : icr2)atshift.
Run locally in your terminal and check off each verification milestone.
Not started
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.- 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.
Step sequence — frame strip: steps_m03_l03
Step 1 (Output Latch): Preload inactive high DR[3] = 1 (+0x00) + DSB SY before enabling output direction.
reveals: step1
highlights: step1
Step 2 (Direction): Set GDIR[3] = 1 (+0x04) via masked RMW so all 31 neighboring pins keep their directions.
reveals: step2
highlights: step2
Step 3 (Pad Observation): Sample physical wire state from read-only PSR (+0x08), which can differ from DR under load/clamp.
reveals: step3
highlights: step3
Step 4 (Event Path): Partition ICR1/ICR2 via pin/16 and acknowledge ISR (+0x18) with a pure 1-bit W1C store.
reveals: step4
highlights: step4
m04/
Boot ROM selection, IVT geometry, and DCD command streams
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.
What Happens Electrically on Reset Before Any User Instruction Exists
When power stabilizes on an i.MX6ULL board and the external power-on-reset pin (POR_B) rises from 0 V to 3.3 V, your bare-metal start.S and main() are not running yet—external DDR3 is unclocked, UART1 is dark, and the ARM Cortex-A7 core fetches its very first instruction from mask-programmed on-chip Boot ROM at 0x00000000. How does fixed silicon ROM know whether to boot from an SD card, an eMMC chip, QSPI NOR, NAND, or wait on USB_OTG1 for host recovery?
As Figure 4.1a illustrates, the i.MX6ULL System Reset Controller (SRC, 0x020D8000) wires 26 dual-purpose package balls—BOOT_MODE0..1 plus LCD_DATA00..23 (BOOT_CFG1/2/4)—into edge-triggered hardware capture latches clocked by the rising edge of POR_B. On the carrier board, weak bias resistors (typically 10 kOhm pull-ups and 47 kOhm pull-downs) and DIP switches establish a clean 0 V or 3.3 V DC voltage on each strap ball while reset is held low. At the exact nanosecond POR_B deasserts, SRC snapshots those voltages into read-only status registers SRC_SBMR1 (0x020D8004) and SRC_SBMR2 (0x020D801C). Two immediate hardware laws follow from this circuit:
- Post-reset pin reuse is safe, but reset-time load contention is fatal: Once
POR_Brises, firmware can freely re-muxLCD_DATA00..23to drive an RGB panel without altering the already-latchedSRC_SBMR1flip-flops. Conversely, soldering an unbuffered1 kOhmexternal pull-up or active sensor output onto anLCD_DATAtrace overpowers the47 kOhmboard strap duringPOR_B, latching the wrong boot medium before your code ever executes! - Moving a DIP switch while power stays on does nothing: Flipping
BOOT_MODEswitches changes live pad voltage, notSRC_SBMR2. Only asserting a freshPOR_Breset re-clocks the capture latches. Furthermore, persistent one-time-programmable eFUSEs (BT_FUSE_SEL) can override pin straps permanently—never burn eFUSEs on a bring-up board!
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).
mental model: 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 that remain live until handoff completes.
definition (System Reset Controller Boot Mode Registers (SRC_SBMR1/2) & Internal OCRAM): 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 ! 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.
Step through the four-stage reset-to-handoff pipeline below to connect pad sampling, policy selection, and OCRAM memory readiness:
- Step 1. Step 1: At POR_B rising edge, SRC latches BOOT_MODE[1:0] and LCD_DATA00..23 into read-only SBMR2 and SBMR1.
- Step 2. Step 2: ROM decodes BMOD[1:0] (00 Fuse, 01 SDP recovery, 10 Internal via straps or eFUSEs, 11 Reserved).
- Step 3. Step 3: Pre-DDR code executes only inside unreserved OCRAM [0x00907000, 0x00920000), sparing ROM workspace.
- Step 4. Step 4: ROM validates the boot image on the selected medium (or falls back to USB/UART SDP on failure).
Figure 4.1b. Separate reset-latched boot policy and ROM-reserved low OCRAM from post-boot GPIO/LCD pin behavior.
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 board bring-up. In SRC_SBMR2 (0x020D801C), BMOD[1:0] ([25:24]) selects the top-level ROM state: notably, BMOD == 01 (Serial Downloader) enters the binary USB_OTG1 / UART Serial Download Protocol (SDP) even if BT_FUSE_SEL (bit 4) is 1, giving engineers a non-destructive recovery path whenever an SD or eMMC image is corrupted. When BMOD == 10 (Internal Boot) and BT_FUSE_SEL == 0, the ROM consults SRC_SBMR1 (0x020D8004), where BOOT_CFG1[7:4] (SBMR1[7:4]) selects SD/eSD (010x), MMC/eMMC (011x), NAND (1xxx), QSPI (0001), or NOR/EIM.
Look equally closely at panel 3 of Figure 4.1b. Why can't a pre-DDR payload load straight into 0x80000000 (DDR3) or 0x00900000 (the first byte of OCRAM)? External DDR3 (0x80000000+) requires MMDC clock gating, pad drive calibration, and JEDEC initialization sequences before a single word can retain bits. Meanwhile, OCRAM ([0x00900000, 0x00920000), 128 KiB) consists of six-transistor static CMOS SRAM cells ready immediately at POR_B—but the Boot ROM itself is a C program that needs a stack, USB SDP descriptors, MMU translation tables, and HAB scratch RAM! Those ROM structures occupy [0x00900000, 0x00907000) (28 KiB), leaving the upper 100 KiB window [0x00907000, 0x00920000) (0x19000 bytes) safe for pre-DDR SPL code and stacks.
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.
| Boot / Storage Mechanism | Register / Address Encoding | Reset-Time Precondition | Failure Boundary When Misapplied |
|---|---|---|---|
BMOD = 10, BT_FUSE_SEL = 0 | SBMR2[25:24] = 2, [4] = 0 | LCD_DATA strap pulls undisturbed at POR_B | Strong external load on LCD_DATA latches wrong medium |
BMOD = 01 (Serial Downloader) | SBMR2[25:24] = 1 (ignores [4]) | USB_OTG1 cable + host SDP loader (uuu) | Mistaken for an ASCII UART1 shell (ROM speaks binary SDP) |
Usable Pre-DDR OCRAM (100 KiB) | [0x00907000, 0x00920000) | Ready at t = 0 (0 DCD writes needed) | Loading at 0x00900000 clobbers active Boot ROM stack/state! |
External DDR3 (MMDC) | 0x80000000+ | Valid DCD table or OCRAM SPL training | Jumping to 0x87800000 uninitialized hangs or fetches garbage |
In boot_policy.c below, our freestanding ARMv7-A helper inspects SRC_SBMR2 strictly through a volatile const uint32_t * pointer—collecting diagnostic evidence of what POR_B latched without ever touching OCOTP fuse-programming registers.
learner@ksa:~/gl-e01/m04-l01$ bat -H 2 -H 3 -H 4 -H 5 -H 6 -H 9 boot_policy.c File: boot_policy.c #include <stdint.h> static volatile const uint32_t *const src_sbmr2 = (volatile const uint32_t *)(uintptr_t)0x020d801cU; unsigned sampled_boot_mode(void) { return (*src_sbmr2 >> 24) & 3U; } unsigned fuse_policy_selected(void) { return (*src_sbmr2 >> 4) & 1U; } /* Read-only inspection: no fuse programming and no boot-media writes. */- Qualify 0x020D801C as volatile const uint32_t * so hardware status reads are never optimized away and writes fail compilation.
- Extract BT_FUSE_SEL at bit 4 (not bit 0!) to distinguish fuse-governed internal boot from pin-strapped internal boot.
Proving SBMR1/SBMR2 Policy Decoding & Overflow-Safe OCRAM Bounds in C11
Before touching target hardware, sbmr_boot_decoder.c proves the complete Boot ROM decision tree and OCRAM allocation math in strict host ISO C11. Notice three defensive invariants in the code: (1) decode_sbmr2() routes BMOD == 1U to BP_USB_SERIAL even when BT_FUSE_SEL (0x10U) is set, while explicitly flagging BMOD == 3U as BP_RESERVED; (2) decode_sbmr1_dev() decodes the BOOT_CFG1[7:4] upper nibble into NAND, SD/eSD, MMC/eMMC, QSPI, or NOR/EIM; and (3) ocram_user_fits(addr, len) subtracts off = addr - base and checks len <= span - off so addr + len can never wrap 32-bit unsigned arithmetic!
learner@ksa:~/gl-e01/m04-l01$ bat -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 34 -H 35 -H 36 -H 37 -H 38 -H 39 sbmr_boot_decoder.c File: sbmr_boot_decoder.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> enum boot_path { BP_FUSE, BP_USB_SERIAL, BP_INT_STRAPS, BP_INT_FUSE, BP_RESERVED }; enum boot_dev { DEV_NONE, DEV_NOR_EIM, DEV_QSPI, DEV_SD_ESD, DEV_MMC_EMMC, DEV_NAND }; static enum boot_path decode_sbmr2(uint32_t sbmr2) { unsigned bmod = (sbmr2 >> 24) & 3U; bool bt_fuse_sel = ((sbmr2 >> 4) & 1U) != 0U; switch (bmod) { case 0U: return BP_FUSE; case 1U: return BP_USB_SERIAL; case 2U: return bt_fuse_sel ? BP_INT_FUSE : BP_INT_STRAPS; default: return BP_RESERVED; } } static enum boot_dev decode_sbmr1_dev(uint32_t sbmr1) { unsigned cfg1_hi = (sbmr1 >> 4) & 0x0fU; if ((cfg1_hi & 0x8U) != 0U) return DEV_NAND; if ((cfg1_hi & 0xeU) == 0x4U) return DEV_SD_ESD; if ((cfg1_hi & 0xeU) == 0x6U) return DEV_MMC_EMMC; return (cfg1_hi == 0x1U) ? DEV_QSPI : DEV_NOR_EIM; } static bool ocram_user_fits(uint32_t addr, uint32_t len) { const uint32_t base = 0x00907000U, span = 0x00019000U; /* [0x907000, 0x920000) */ if (len == 0U || addr < base) return false; uint32_t off = addr - base; return off <= span && len <= span - off; } int main(void) { assert(decode_sbmr2(0x00000000U) == BP_FUSE); assert(decode_sbmr2(0x01000010U) == BP_USB_SERIAL); assert(decode_sbmr2(0x02000000U) == BP_INT_STRAPS); assert(decode_sbmr2(0x02000010U) == BP_INT_FUSE); assert(decode_sbmr2(0x03000000U) == BP_RESERVED); assert(decode_sbmr1_dev(0x00000040U) == DEV_SD_ESD); assert(decode_sbmr1_dev(0x00000060U) == DEV_MMC_EMMC); assert(decode_sbmr1_dev(0x00000080U) == DEV_NAND); assert(!ocram_user_fits(0x00900000U, 0x1000U)); /* overlaps ROM workspace */ assert(ocram_user_fits(0x00907000U, 0x19000U)); assert(!ocram_user_fits(0x0091ffffU, 2U)); printf("SBMR2=0x02000000->INT_STRAPS SBMR1=0x40->SD_ESD OCRAM_free=100KiB\n"); return 0; }- Decode BMOD[1:0] (SBMR2[25:24]) and BT_FUSE_SEL (SBMR2[4]), explicitly rejecting reserved BMOD == 3.
- Classify BOOT_CFG1[7:4] (SBMR1[7:4]) into SD/eSD, MMC/eMMC, NAND, QSPI, or NOR/EIM when straps drive internal boot.
- Reject pre-DDR placements inside the [0x00900000, 0x00907000) Boot ROM workspace as well as overflows past 0x00920000.
Running the Host Policy Verifier & Freestanding Cortex-A7 Object Check
Compile and execute sbmr_boot_decoder.c on the workstation, then cross-compile boot_policy.c with clang --target=armv7a-none-eabi to verify freestanding Cortex-A7 code generation. Try fault-injecting ocram_user_fits(0x00906FFFU, 4U) or decode_sbmr2(0x03000010U) locally to watch the boundary assertions catch low-OCRAM overlap and reserved BMOD encodings immediately.
learner@ksa:~/gl-e01/m04-l01gcc -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-l01clang --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-l01learner@ksa:~/gl-e01/m04-l01strace -e trace=write,exit_group \./sbmr_boot_decoderwrite(1, "SBMR2=0x02000000->INT_STRAPS SBM"..., 66) = 66exit_group(0) = ?+++ exited with 0 +++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 teams. First, if a board boots nothing on UART1 after you flip its DIP switches to SD, verify that you pulsed POR_B (full power-cycle), not just a peripheral warm reset, and check lsusb on the host: if the Boot ROM rejected a missing or malformed SD image, it silently falls into USB_OTG1 Serial Downloader (SDP), enumerating as a USB HID device while emitting zero characters on UART1! Second, remember that selecting SD via BOOT_CFG only tells the ROM where to look; it does not prove the card holds a valid boot header. Later: Lesson m04-l02 constructs the exact 32-byte Image Vector Table (IVT) and 12-byte Boot Data header the ROM looks for at sector 2 (0x400).
Common Production Pitfalls
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.
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).
Practice & Retrieval
Guided Practice: Decoding SBMR1/SBMR2 & Sizing an OCRAM Stack
Solve each bring-up check step by step. Step 1 (Register Decode): Given SRC_SBMR2 = 0x02000001U and SRC_SBMR1 = 0x00001860U, extract BMOD[1:0] (bits [25:24] = 2), BT_FUSE_SEL (bit 4 = 0, ignoring bit 0!), and BOOT_CFG1[7:4] (0x6), confirming BP_INT_STRAPS -> DEV_MMC_EMMC. Step 2 (OCRAM Budget): Place an 8-byte-aligned SVC stack top at 0x00920000 reserving 8 KiB (0x2000 B down to 0x0091E000), and compute the maximum payload span starting at 0x00908000 (0x0091E000 - 0x00908000 = 0x16000 = 88 KiB).
Independent Practice: USDHC Port & Bus-Width Strap Auditor
Extend sbmr_boot_decoder.c into boot_cfg_audit.c decoding BOOT_CFG2 (SBMR1[15:8]) alongside BOOT_CFG1: extract USDHC controller port (USDHC1 vs USDHC2) and data width (1-bit, 4-bit, 8-bit), reject 8-bit bus configurations when DEV_SD_ESD (rather than DEV_MMC_EMMC) is selected, and verify that IVT + Boot Data + payload + stack fit non-overlapping inside [0x00907000, 0x00920000).
? check 1 · 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?
- [x] It executes the ROM-directed internal boot flow using fuse-selected media settings rather than live
BOOT_CFGpin straps - [ ] It ignores eFUSEs whenever
BMOD == 2and reads liveLCD_DATApin voltages continuously - [ ] It boots an application permanently stored inside on-chip
OCRAMwithout touching external media
Answer: It executes the ROM-directed internal boot flow using fuse-selected media settings rather than live BOOT_CFG pin straps
Why: 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.
? check 2 · 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?
- [ ] The C compiler cached
*src_sbmr2becauseconstdisablesvolatilehardware reads - [ ]
IOMUXCpad-mux registers must be cleared frommain()before DIP switches connect toSRC - [x] Boot strap pads are captured at the reset sampling edge (
POR_B); moving switches afterward does not retroactively update latchedSBMRflip-flops
Answer: Boot strap pads are captured at the reset sampling edge (POR_B); moving switches afterward does not retroactively update latched SBMR flip-flops
Why: 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.
? check 3 · Retrieval: why does ocram_user_fits(0x00900000U, 0x1000U) reject address 0x00900000 even though physical OCRAM spans [0x00900000, 0x00920000)?
- [ ]
OCRAMrequiresMMDCDDR3write-leveling calibration on its lower28 KiBbank - [x] The active Boot ROM reserves low
OCRAM([0x00900000, 0x00907000)) for its own stack,SDPbuffers, and handoff state - [ ]
Cortex-A7SVCmode cannot address physical memory below0x00907000
Answer: The active Boot ROM reserves low OCRAM ([0x00900000, 0x00907000)) for its own stack, SDP buffers, and handoff state
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m04_l01
Step 1: At POR_B rising edge, SRC latches BOOT_MODE[1:0] and LCD_DATA00..23 into read-only SBMR2 and SBMR1.
reveals: step1
highlights: step1
Step 2: ROM decodes BMOD[1:0] (00 Fuse, 01 SDP recovery, 10 Internal via straps or eFUSEs, 11 Reserved).
reveals: step2
highlights: step2
Step 3: Pre-DDR code executes only inside unreserved OCRAM [0x00907000, 0x00920000), sparing ROM workspace.
reveals: step3
highlights: step3
Step 4: ROM validates the boot image on the selected medium (or falls back to USB/UART SDP on failure).
reveals: step4
highlights: step4
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.
Why Raw .bin Images Cannot Cold-Boot & The Three Coordinate Systems
When arm-none-eabi-objcopy -O binary bsp.elf bsp.bin strips an ELF executable down to raw ARMv7-A machine instructions, every piece of loader metadata vanishes—e_entry, PT_LOAD destination addresses, and byte lengths are gone! If you write bsp.bin onto an SD card, the i.MX6ULL Boot ROM has no way to know where in OCRAM or DDR3 those bytes belong, how many sectors to read, whether DDR3 needs register setup first, or which address holds _start. Also, why doesn't the Boot ROM simply read byte 0x0000 (LBA 0) of an SD or eMMC card? Because LBA 0 (bytes 0x000..0x1FF) holds the standard Master Boot Record (MBR) / GPT partition table! Overwriting 0x0000 would destroy filesystem partitions needed later by U-Boot and the Linux kernel.
Instead, on SD/eMMC media, the i.MX6ULL Boot ROM seeks 1 KiB (1024 B = 0x0400, two 512-byte sectors = LBA 2) into the card and looks for a 32-byte Image Vector Table (IVT). As Figure 4.2a shows, nearly every boot-image bug comes from calling three different origins "the offset" without naming its coordinate system:
- Storage Media Coordinate (
M, origin = card byte0x0000):MBRoccupies0x0000..0x03FF(LBA 0..1),IVTsits atM = 0x0400(LBA 2),Boot Datasits atM = 0x0420,DCDstarts atM = 0x042C, and our application_startpayload (Pbytes) sits atM = 0x1000(LBA 8). - Compact
.imxFile Coordinate (F = M - 0x0400, origin =IVTbyte0): Becausedd seek=2 bs=512skips the first1024 Bon the card, a compact.imxfile omits0x0000..0x03FFcompletely! File offsetF = 0x0000is theIVT,F = 0x0020isBoot Data,F = 0x002CisDCD, and the payload sits atF = 0x1000 - 0x0400 = 0x0C00(3072 B)—never0x1000! - Runtime Memory Coordinate (
R = BootData.start + M = IVT.self + F): For an entry point linked atR = 0x87800000(M = 0x1000),BootData.startequals0x87800000 - 0x1000 = 0x877FF000, placingIVT.selfat0x877FF000 + 0x0400 = 0x877FF400,Boot Dataat0x877FF420, andBootData.lengthat0x1000 + P(0x1010whenP = 16 B, even though the compact.imxfile is0x0C10bytes!).
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).
mental model: 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.
definition (Image Vector Table () & Boot Data Structure): 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).
Walk through the four-step coordinate conversion and pointer audit below before writing serializer code:
- Step 1. Step 1: Anchor SD/eMMC media coordinates at M_ivt = 0x0400 (LBA 2, sparing MBR) and M_payload = 0x1000 (LBA 8).
- Step 2. Step 2: Subtract 0x0400 for the compact .imx file: IVT at F = 0x0000, Boot Data at 0x0020, payload at F = 0x0C00.
- Step 3. Step 3: Map runtime RAM from BootData.start = 0x877FF000 so IVT.self = 0x877FF400 and IVT.entry = 0x87800000.
- Step 4. Step 4: Verify header D1 00 20 40, reserved words == 0, boot_data == self + 32, and entry inside [bdata+12, start+len).
Figure 4.2b. Name the coordinate origin (media M, compact file F, or runtime RAM R) on every variable before adding or comparing offsets.
Mixed-Endian Header Bytes vs Little-Endian Runtime Pointers
Study Figure 4.2b carefully to avoid a classic endianness trap. Why do hex dumps of .imx files show d1 00 20 40 byte-by-byte (od -tx1), yet 32-bit ARM word dumps (od -tx4) print 402000d1? Because the HAB/ROM container specification frames tag-length-version headers in network (big-endian) byte order—byte [0] is tag 0xD1, bytes [1..2] are big-endian length (0x00 << 8) | 0x20 = 32, and byte [3] is version 0x40—while storing all subsequent IVT and Boot Data memory addresses (+0x04..+0x28) as little-endian 32-bit ARM words! If you misread 00 20 as little-endian, you get 0x2000 = 8192 instead of 32; conversely, if you emit .byte 0xd1, 0x00, 0x20, 0x40 explicitly in assembly (target.S) or byte arrays (buf44[0..3]), host endianness can never scramble the header.
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.
| Container Region | SD/eMMC Media M | Compact .imx F | Runtime Address R (start = 0x877FF000) | Size & Byte-Order Rule |
|---|---|---|---|---|
MBR / Partition Table | 0x0000..0x03FF (LBA 0..1) | Omitted (dd seek=2 bs=512) | 0x877FF000..0x877FF3FF | 1024 B skipped in .imx |
IVT (image_ivt) | 0x0400 (LBA 2) | 0x0000 | 0x877FF400 (IVT.self) | 32 B (BE16 len, LE32 ptrs) |
Boot Data + DCD | 0x0420 / 0x042C | 0x0020 / 0x002C | 0x877FF420 / 0x877FF42C | 12 B LE32 + DCD (BE) |
Application _start | 0x1000 (LBA 8) | 0x0C00 | 0x87800000 (IVT.entry) | P bytes (ARMv7-A LE code) |
In target.S below, .section .ivt, "a" emits image_ivt (32 B) and image_boot_data (12 B) using linker-resolved symbols (_start, image_dcd, image_load_base, image_load_size). Notice that self (+0x14) receives image_ivt—its runtime memory address (0x877FF400), never compact-file offset 0!
learner@ksa:~/gl-e01/m04-l02$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 target.S File: target.S .syntax unified .cpu cortex-a7 .arm .section .ivt, "a" .global image_ivt image_ivt: .byte 0xd1, 0x00, 0x20, 0x40 .word _start .word 0 .word image_dcd .word image_boot_data .word image_ivt .word 0 .word 0 image_boot_data: .word image_load_base .word image_load_size .word 0 .extern _start .extern image_dcd .extern image_load_base .extern image_load_size- Emit D1 00 20 40 as explicit bytes so big-endian length 0x0020 and little-endian word 0x402000D1 are unambiguous.
- Store image_ivt (0x877FF400) in self (+0x14) and strictly zero reserved1 (+0x08), csf (+0x18), and reserved2 (+0x1C).
- Linker-defined image_load_size spans from image_load_base (0x877FF000) through the end of initialized payload.
Serializing & Auditing 44-Byte IVT + Boot Data Coordinates in ISO C11
Never overlay a packed C struct directly onto disk bytes when fields mix endianness. In ivt_serializer_audit.c below, serialize_ivt_boot() writes into a 44-byte unsigned char array via explicit put_le32() shifts, while validate_ivt_coords() checks both perspectives on the header (get_le32(hdr) == 0x402000D1U and get_be16(hdr + 1) == 32U), enforces zero reserved words (+0x08 and +0x1C), proves self == start + media_ivt and boot_data == self + 32U, and verifies via subtraction (entry - start < len) that the ROM copy window actually covers entry!
learner@ksa:~/gl-e01/m04-l02$ bat -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 -H 36 -H 37 ivt_serializer_audit.c File: ivt_serializer_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> static void put_le32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * i)); } static uint32_t get_le32(const unsigned char *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); } static uint16_t get_be16(const unsigned char *p) { return (uint16_t)(((uint16_t)p[0] << 8) | p[1]); } static void serialize_ivt_boot(unsigned char *buf44, uint32_t boot_start, uint32_t entry, uint32_t dcd, uint32_t boot_len) { memset(buf44, 0, 44U); buf44[0] = 0xd1U; buf44[1] = 0x00U; buf44[2] = 0x20U; buf44[3] = 0x40U; uint32_t self = boot_start + 0x400U; put_le32(buf44 + 4, entry); put_le32(buf44 + 12, dcd); put_le32(buf44 + 16, self + 32U); put_le32(buf44 + 20, self); put_le32(buf44 + 32, boot_start); put_le32(buf44 + 36, boot_len); } static bool validate_ivt_coords(const unsigned char *b, uint32_t media_ivt) { if (b[0] != 0xd1U || get_be16(b + 1) != 32U || (b[3] != 0x40U && b[3] != 0x41U)) return false; if (get_le32(b + 8) != 0U || get_le32(b + 28) != 0U) return false; uint32_t entry = get_le32(b + 4), bdata = get_le32(b + 16), self = get_le32(b + 20); uint32_t start = get_le32(b + 32), len = get_le32(b + 36); if (self != start + media_ivt || bdata != self + 32U) return false; return len > media_ivt && entry >= bdata + 12U && entry - start < len; } int main(void) { unsigned char hdr[44]; serialize_ivt_boot(hdr, 0x877ff000U, 0x87800000U, 0x877ff42cU, 0x1010U); assert(get_le32(hdr) == 0x402000d1U && get_be16(hdr + 1) == 32U); assert(validate_ivt_coords(hdr, 0x400U)); assert(0x400U / 512U == 2U && 0x1000U - 0x400U == 0x0c00U); put_le32(hdr + 20, 0U); /* wrong: file offset 0 written as runtime self */ assert(!validate_ivt_coords(hdr, 0x400U)); put_le32(hdr + 20, 0x877ff400U); put_le32(hdr + 8, 1U); /* wrong: nonzero reserved1 */ assert(!validate_ivt_coords(hdr, 0x400U)); printf("IVT_word=0x%08X self=0x%08X bdata=0x%08X entry=0x%08X LBA=%u\n", get_le32(hdr), 0x877ff400U, get_le32(hdr + 16), get_le32(hdr + 4), 2U); return 0; }- Emit D1 00 20 40 explicitly so big-endian length 32 and little-endian 0x402000D1 agree on every host.
- Enforce reserved1 == 0, reserved2 == 0, and self == boot_start + 0x400 (the IVT runtime address, not file offset 0).
- Require entry >= self + 32 + 12 and entry < boot_start + boot_len so the ROM actually loads the entry point.
Verifying Mixed-Endian Serialization & ARMv7-A Relocation Assembly
Build and run ivt_serializer_audit on the host, then assemble target.S with clang --target=armv7a-none-eabi to confirm clean relocation records for .section .ivt. Notice how the two fault-injection assertions in main() explicitly verify that writing 0 into self (hdr + 20) or 1 into reserved1 (hdr + 8) fails validation immediately.
learner@ksa:~/gl-e01/m04-l02gcc -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-l02clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m04-l02learner@ksa:~/gl-e01/m04-l02strace -e trace=write,exit_group \./ivt_serializer_auditwrite(1, "IVT_word=0x402000D1 self=0x877FF"..., 76) = 76exit_group(0) = ?+++ exited with 0 +++Why ENTRY(_start) Never Populates IVT.entry Automatically
Connect what you just proved back to ELF linking from Module m01. Writing ENTRY(_start) in a linker script sets e_entry inside bsp.elf for gdb—yet objcopy -O binary discards the entire ELF header! On cold boot, the i.MX6ULL Boot ROM knows your entry point solely from IVT.entry (+0x04) and copies sectors solely according to BootData.start and BootData.length (+0x20..+0x24). Keeping bsp.elf, bsp.map, and your .imx packer checked against each other guarantees IVT.entry matches _start and BootData.length covers 0x1000 + payload_bytes. Later: Lesson m04-l03 fills in image_dcd (0x877FF42C) with big-endian Device Configuration Data commands and writes a complete .imx binary file.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Relocating an IVT Container Into Pre-DDR OCRAM
Re-derive all runtime pointers for an SD-booted SPL executing inside OCRAM without DCD. Step 1 (Addresses): Given M_ivt = 0x0400, M_payload = 0x1000, and IVT.entry = 0x00908000, compute BootData.start (0x00908000 - 0x1000 = 0x00907000), IVT.self (0x00907400), and IVT.boot_data (0x00907420). Step 2 (Sizes & ): For a 24 KiB (0x6000 B) SPL binary with zero DCD commands, state IVT.dcd (0x00000000), compact .imx file size (0x0C00 + 0x6000 = 0x6C00 B), and BootData.length (0x1000 + 0x6000 = 0x7000 B, ending at 0x0090E000 < 0x00920000).
Independent Practice: Multi-Media IVT Validator (SD/eMMC vs QSPI)
Extend ivt_serializer_audit.c into ivt_media_check.c parameterized by media_ivt (0x0400 for SD/eMMC vs 0x1000 for QSPI NOR). Enforce 4-byte ARM alignment on entry, require dcd == 0 when targeting OCRAM [0x00907000, 0x00920000) or dcd == self + 0x2C when DCD is present, and reject any layout whose DCD overflows into the payload offset.
? check 1 · 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?
- [ ] File offset
0x1000, because file offsets and media offsets share origin0 - [ ] File offset
0x1400, because0x0400and0x1000add together - [x] File offset
0x0C00, after subtracting the omitted0x0400(1 KiB) prefix
Answer: File offset 0x0C00, after subtracting the omitted 0x0400 (1 KiB) prefix
Why: 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.
? check 2 · 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?
- [ ] Tag
0xD1, little-endian length8192(0x2000), version0x40-> word0xD1002040 - [x] Tag
0xD1, big-endian length32(0x0020), version0x40-> little-endian word0x402000D1 - [ ] Tag
0x40, big-endian length32(0x0020), version0xD1-> word0x402000D1
Answer: Tag 0xD1, big-endian length 32 (0x0020), version 0x40 -> little-endian word 0x402000D1
Why: 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.
? check 3 · Retrieval: what value must IVT.self (+0x14) hold in our worked 0x87800000 SD layout (BootData.start = 0x877FF000)?
- [x]
0x877FF400, the runtime memory address where theIVTitself lands (start + 0x0400) - [ ]
0x00000000, because theIVTsits at byte0of the compact.imxfile - [ ]
0x00000002, the starting512-byteLBAsector index on theSDcard
Answer: 0x877FF400, the runtime memory address where the IVT itself lands (start + 0x0400)
Why: 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.
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.- 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.
Step sequence — frame strip: steps_m04_l02
Step 1: Anchor SD/eMMC media coordinates at M_ivt = 0x0400 (LBA 2, sparing MBR) and M_payload = 0x1000 (LBA 8).
reveals: step1
highlights: step1
Step 2: Subtract 0x0400 for the compact .imx file: IVT at F = 0x0000, Boot Data at 0x0020, payload at F = 0x0C00.
reveals: step2
highlights: step2
Step 3: Map runtime RAM from BootData.start = 0x877FF000 so IVT.self = 0x877FF400 and IVT.entry = 0x87800000.
reveals: step3
highlights: step3
Step 4: Verify header D1 00 20 40, reserved words == 0, boot_data == self + 32, and entry inside [bdata+12, start+len).
reveals: step4
highlights: step4
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.
Solving the Cold-Boot Chicken-and-Egg Problem with DCD
Think through what happens on cold power-up when IVT.entry points to 0x87800000 in external DDR3 RAM. The i.MX6ULL Boot ROM wants to copy your firmware from SD sector 2+ into 0x877FF000..0x8780XXXX—yet external DDR3 is completely dead at reset until clock gates (CCM), pad drive strengths (IOMUXC), and Multi-Mode DDR Controller (MMDC) timing registers are programmed! Your _start code inside the payload cannot initialize DDR3, because _start itself has nowhere to be copied until DDR3 works! Firmware architectures solve this chicken-and-egg puzzle in one of two ways: either load a small U-Boot SPL into internal OCRAM (0x00908000) to train DDR3 in C, or attach a declarative Device Configuration Data (DCD) bytecode stream at IVT.dcd (0x877FF42C) that the Boot ROM interprets before copying the payload to DDR3.
Examine Figure 4.3a to see how DCD bytecode is framed—and why naive .imx packers break on their very first register write. Whereas IVT and Boot Data pointers (m04-l02) are little-endian 32-bit ARM words, every length, register address, data word, mask, and poll count inside DCD is strictly big-endian (BE16 / BE32)!
- Table Header (
0xD2):[0xD2, len_hi, len_lo, 0x40], where big-endiantotal_len(4 <= total_len <= 1768 B) includes the4-byte0xD2header itself. Write Data(0xCC):[0xCC, cmd_len_be16, param]followed byk >= 1big-endian(addr32, val_or_mask32)pairs (cmd_len = 4 + 8 * k). Inparam, bits[2:0]select access width (1,2, or4bytes) and bits[4:3]select plain write (00), clear-mask (01), or set-mask (10).Check Data(0xCF) &NOP(0xC0):0xCFpolls a status register (param = 0x0Cchecks(*addr & mask) == maskon4-byte width;cmd_len = 12unbounded or16with a big-endiancount32timeout), while0xC0is[0xC0, 0x00, 0x04, 0x00]. If a packer accidentally writes0x020C406C(CCM_CCGR1) withput_le32(), the ROM reads big-endian0x6C400C02—outside its permitted peripheral whitelist—and aborts straight intoUSBSerial Downloader!
Figure 4.3a. Inside the 36-byte big-endian stream (top), why put_le32() triggers silent ROM rejection (bottom left), and parser termination invariants (bottom right).
mental model: 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.
definition (Device Configuration Data (DCD) & Structural vs Electrical Validation): 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.
Trace the four-stage encoding, validation, and .imx packing pipeline below:
- Step 1. Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.
- Step 2. Step 2: Validate every CC, CF, and C0 subcommand length >= 4 and <= total - at before advancing the cursor.
- Step 3. Step 3: Assemble (0x00 LE), Boot Data (0x20 LE), DCD (0x2C BE), and payload (0x0C00) into verified.imx.
- Step 4. Step 4: Assert known raw byte vectors (02 0C 40 6C) and separate container-format proof from DDR3 calibration.
Figure 4.3b. Keep LE32 IVT pointers and BE16/BE32 DCD commands strictly separated, and never equate valid framing with calibrated DDR3 timing.
Linker Coordinates, Container Packing & Pre-Boot Trade-Offs
Inspect Figure 4.3b alongside image_layout.lds below to see how linker addresses and .imx file offsets lock together. In image_layout.lds, image_load_base = 0x877FF000 anchors medium byte 0x0000, . = image_load_base + 0x400 (0x877FF400) places .ivt and .dcd, and . = 0x87800000 places .text (KEEP(*(.text.start))), .rodata, and .data up to image_load_end. In the corresponding 3088-byte (0x0C10) verified.imx container, IVT (32 B), Boot Data (12 B), and our 36-byte DCD fixture occupy 0x000..0x04F, zero padding spans 0x050..0xBFF (0x002C + 36 = 0x0050 <= 0x0C00, proving zero metadata/payload overlap!), and the 16-byte fixture payload sits at 0x0C00..0x0C0F (BootData.length = 0x1010 = 4112 B).
Figure 4.3b. Exact byte map of verified.imx (3088 B) and the engineering boundary between structural container proof and board DDR3 calibration.
| Pre-Boot Initialization Strategy | Executed By | Size & Capability Limit | Operational Trade-Off |
|---|---|---|---|
Static DCD stream (0xD2) | Internal Boot ROM | <= 1768 B (<= 220 coalesced pairs); ROM whitelist only | Simple single-stage .imx; cannot probe RAM size or I2C PMICs |
U-Boot SPL in OCRAM | Cortex-A7 (0x00908000) | ~100 KiB OCRAM; full C11 control flow & UART logs | Production standard in U-Boot 2025.x; supports dynamic DDR3 training |
Unbounded Check Data (len = 12) | Internal Boot ROM | Polls *addr & mask forever with zero timeout | Wedges pre-console boot permanently if a PLL/PHY bit fails to lock |
Bounded Check Data (len = 16) | Internal Boot ROM | Polls up to big-endian count iterations | Aborts cleanly into SDP recovery when hardware readiness times out |
learner@ksa:~/gl-e01/m04-l03$ bat -H 4 -H 5 -H 6 -H 7 -H 8 image_layout.lds File: image_layout.lds ENTRY(_start) SECTIONS { image_load_base = 0x877ff000; . = image_load_base + 0x400; .ivt : { KEEP(*(.ivt)) } .dcd : { KEEP(*(.dcd)) } . = 0x87800000; .text : { KEEP(*(.text.start)) *(.text*) } .rodata ALIGN(4) : { *(.rodata*) } .data ALIGN(4) : { *(.data*) } image_load_end = .; .bss (NOLOAD) : { *(.bss*) *(COMMON) } }- Place .ivt and .dcd at image_load_base + 0x400 (0x877FF400), matching SD/eMMC LBA 2.
- Advance location counter to 0x87800000 (compact offset 0x0C00) and pin .text.start first with KEEP().
Implementing a Bounded DCD Validator & .imx Packer in ISO C11
Study valid_dcd() and main() in dcd_encoder_packer.c below. Before advancing at += len, the parser enforces len >= 4U && len <= total - at—preventing a malformed len == 0 command from spinning while (at < total) in an infinite loop and preventing truncated tails from reading past buffer bounds! Equally important, assert(dcd[8] == 0x02U && dcd[9] == 0x0cU && dcd[10] == 0x40U && dcd[11] == 0x6cU) checks the raw big-endian wire bytes directly so a symmetric endian bug in both encoder and decoder can never pass unnoticed.
learner@ksa:~/gl-e01/m04-l03$ bat -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 -H 36 -H 37 -H 38 -H 39 -H 55 -H 56 -H 57 -H 58 -H 59 -H 60 -H 61 -H 62 dcd_encoder_packer.c File: dcd_encoder_packer.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> static void put_be16(unsigned char *p, uint16_t v) { p[0] = (unsigned char)(v >> 8); p[1] = (unsigned char)(v & 0xffU); } static uint16_t get_be16(const unsigned char *p) { return (uint16_t)(((uint16_t)p[0] << 8) | p[1]); } static void put_be32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * (3U - i))); } static void put_le32(unsigned char *p, uint32_t v) { for (unsigned i = 0U; i < 4U; ++i) p[i] = (unsigned char)(v >> (8U * i)); } static bool valid_dcd(const unsigned char *p, size_t n) { if (n < 4U || p[0] != 0xd2U || p[3] != 0x40U) return false; size_t total = get_be16(p + 1); if (total < 4U || total > n || total > 1768U) return false; size_t at = 4U; while (at < total) { if (total - at < 4U) return false; size_t len = get_be16(p + at + 1); if (len < 4U || len > total - at) return false; unsigned tag = p[at], param = p[at + 3U]; bool wr = (tag == 0xccU && param == 4U && len >= 12U && (len - 4U) % 8U == 0U); bool ck = (tag == 0xcfU && param == 0x0cU && len == 16U); bool np = (tag == 0xc0U && param == 0U && len == 4U); if (!wr && !ck && !np) return false; at += len; } return at == total; } int main(void) { unsigned char dcd[36] = {0U}; dcd[0] = 0xd2U; put_be16(dcd + 1, 36U); dcd[3] = 0x40U; dcd[4] = 0xccU; put_be16(dcd + 5, 12U); dcd[7] = 0x04U; put_be32(dcd + 8, 0x020c406cU); put_be32(dcd + 12, 0x0c000000U); dcd[16] = 0xcfU; put_be16(dcd + 17, 16U); dcd[19] = 0x0cU; put_be32(dcd + 20, 0x020c406cU); put_be32(dcd + 24, 0x0c000000U); put_be32(dcd + 28, 32U); dcd[32] = 0xc0U; put_be16(dcd + 33, 4U); dcd[35] = 0x00U; assert(dcd[8] == 0x02U && dcd[9] == 0x0cU && dcd[10] == 0x40U && dcd[11] == 0x6cU); assert(valid_dcd(dcd, sizeof dcd) && !valid_dcd(dcd, sizeof dcd - 1U)); unsigned char bad[36]; memcpy(bad, dcd, sizeof dcd); bad[6] = 0U; assert(!valid_dcd(bad, sizeof bad)); memcpy(bad, dcd, sizeof dcd); bad[4] = 0xffU; assert(!valid_dcd(bad, sizeof bad)); unsigned char img[0xc10] = {0U}; img[0] = 0xd1U; img[2] = 0x20U; img[3] = 0x40U; put_le32(img + 4, 0x87800000U); put_le32(img + 12, 0x877ff42cU); put_le32(img + 16, 0x877ff420U); put_le32(img + 20, 0x877ff400U); put_le32(img + 32, 0x877ff000U); put_le32(img + 36, 0x1010U); memcpy(img + 0x2c, dcd, sizeof dcd); memcpy(img + 0xc00, "FORMAT-FIXTURE!!", 16U); FILE *f = fopen("verified.imx", "wb"); if (!f) return 1; bool ok = (fwrite(img, 1U, sizeof img, f) == sizeof img); if (fclose(f) != 0 || !ok) return 1; printf("verified.imx=%zuB DCD=%uB write_addr=02_0C_40_6C cmds=3\n", sizeof img, get_be16(dcd + 1)); return 0; }- Use big-endian helpers for DCD lengths, register addresses, values, and poll counts, never put_le32().
- Reject len < 4 or len > total - at before advancing so a zero-length command cannot cause an infinite loop.
- Place IVT at 0x00, Boot Data at 0x20, DCD at 0x2C, and payload marker at compact offset 0x0C00 (media 0x1000).
Generating verified.imx & Inspecting the Syscall Write Trace
Compile and run dcd_encoder_packer below. Observe in the strace log that file descriptor 3 (verified.imx) receives a single exact 3088-byte write (\321\0 @ = 0xD1 0x00 0x20 0x40 followed by little-endian 0x87800000) before stdout prints the 57-byte audit summary.
learner@ksa:~/gl-e01/m04-l03gcc -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-l03learner@ksa:~/gl-e01/m04-l03strace -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 +++Coalescing Multi-Pair DCD Writes & Bridging to C Runtime Startup
Notice how byte budgeting works when a real MMDC DDR3 init script needs ~65 register writes: emitting 65 separate 12-byte 0xCC commands takes 4 + 65 * 12 = 784 B (and hits the 1768 B ROM ceiling at 147 writes), whereas coalescing k consecutive same-parameter writes into a single 0xCC command consumes only 4 + 8 * k bytes—fitting up to 220 (addr, val) pairs inside 1768 B! Also keep your verification ledger honest: verified.imx proves container structure and endianness, while FORMAT-FIXTURE!! at 0x0C00 is a 16-byte test marker rather than ARMv7-A code or calibrated DDR3 timing. Later: Module m05 (m05-l01) writes the real _start assembly routine that sits at 0x0C00 (0x87800000), establishes an 8-byte-aligned SVC stack, copies .data, zeroes .bss, and enters main().
Common Production Pitfalls
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().
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.
Practice & Retrieval
Guided Practice: Encoding a Coalesced 2-Pair Set-Mask DCD Command
Compute the exact hex framing by hand. Step 1 (Command Header): Encode one Write Data (0xCC) command with set-mask parameter param = 0x14 (4-byte width + set-mask bit 4) carrying k = 2 pairs (0x020C4068, 0x00000003) and (0x020C406C, 0x0C000000): total command length is 4 + 8 * 2 = 20 = 0x0014, giving header CC 00 14 14. Step 2 (Table Header): Combine that 20-byte 0xCC command with one 16-byte bounded 0xCF Check Data command inside a 0xD2 table: 4 + 20 + 16 = 40 = 0x0028, yielding D2 00 28 40.
Independent Practice: Whitelist-Aware Coalescing DCD Compiler
Extend dcd_encoder_packer.c into dcd_range_compiler.c that validates every target addr against allowed i.MX6ULL DCD ranges (IOMUXC [0x020E0000, 0x020E4000), CCM [0x020C4000, 0x020C8000), MMDC [0x021B0000, 0x021B4000), OCRAM [0x00907000, 0x00920000)), coalesces adjacent same-param 0xCC writes automatically, and rejects tables exceeding 1768 B.
? check 1 · While scanning a DCD buffer, valid_dcd() encounters a subcommand whose big-endian length field equals 0x0000. What must the parser do?
- [ ] Advance
4bytes past the subcommand header and continue scanning - [x] Reject the
DCDstream immediately before advancing or dispatching any command - [ ] Treat length
0as aNOP(0xC0) and re-read the same offset
Answer: Reject the DCD stream immediately before advancing or dispatching any command
Why: 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.
? check 2 · In what exact byte order must register address 0x020C406C (CCM_CCGR1) appear inside a DCD Write Data (0xCC) command?
- [x]
02 0C 40 6C, followingDCD's big-endian address and value specification - [ ]
6C 40 0C 02, matching the little-endianIVT.entrypointer format - [ ]
0C 02 6C 40, swapping16-bit halfwords forARMThumb compatibility
Answer: 02 0C 40 6C, following DCD's big-endian address and value specification
Why: 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.
? check 3 · Retrieval: what engineering claim does generating and validating verified.imx (3088 B) on the host legitimately prove?
- [ ] That any
DDR3memory chip soldered to anyi.MX6ULLboard will calibrate and run reliably - [ ] That the
16-byte"FORMAT-FIXTURE!!"payload is validARMv7-Amachine code - [x] That
IVT,Boot Data,DCDbig-endian framing, and0x0C00compact-file offsets satisfy structural container rules—not calibrated cold boot
Answer: That IVT, Boot Data, DCD big-endian framing, and 0x0C00 compact-file offsets satisfy structural container rules—not calibrated cold boot
Why: 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.
1. Motivation
An i.MX6ULL SD/eMMC boot image silently refuses to boot -- emitting zero characters on UART1 and falling straight into the USB Serial Downloader -- whenever a custom host packer mixes up the two byte orders mandated by the internal Boot ROM: 32-bit addresses inside the Image Vector Table (IVT) and Boot Data structure are little-endian (ARMv7-A memory words), whereas the 4-byte IVT/DCD tag headers (D1 00 20 40, D2 xx xx 40) and every DCD address/value operand are big-endian! In this laboratory, you will diagnose a byte-order reversal inside starter/core.c, validate DCD command-stream bounds (1768 B max), and pack a 0x0C10-byte .imx fixture under TAP version 13.
2. Learning Objectives
- Serialize and parse
32-bit little-endianIVTandBoot Datapointers (entry = 0x87800000,boot_data = 0x877FF420,self = 0x877FF400,start = 0x877FF000,length = 0x1010) without host-alignment traps. - Validate big-endian
DCDblocks (0xD2header,16-bit total length<= 1768 B,0xCCWrite Data,0xCFCheck Data, and0xC0NOPsubcommands) indcd_valid(). - Reconcile compact
.imxfile offsets (IVTat0x0000, payload at0x0C00) with rawSD/eMMCcard geometry (0x0400LBA 2leading gap -> payload at0x1000in target RAM). - Preserve caller output buffers untouched when
pack_image()rejects insufficientcapacity < 0x0C10U.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m04_ivt_dcd_image/. - Target Boot ROM Contract: Matches
i.MX6ULLBoot ROM v0x40IVT(32bytes),Boot Data(12bytes),DCD(<= 1768bytes, big-endian byte stream), andSD/eMMC1 KiB(0x400) offset rules.
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils / hex tools (nm,odorhexdump). - Hardware: Standard Linux workstation (
0SDcards or physicalCortex-A7boards required;dd seek=2 bs=512applies only when flashing real removable media).
5. Complete Executable Commands
Execute the commands below from labs/lab_m04_ivt_dcd_image/ to reproduce starter/ failing checks 2 and 3, inspect the byte-swapped IVT bytes, rebuild files/libbsp.a, and verify 5/5 TAP checks:
learner@ksa:~/gl-e01/m04-l03$ bat script.sh File: script.sh # 1. Grade starter/ in a temporary sandbox to observe checks 2 and 3 fail (# pass 3/5) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Dump the first 40 bytes packed by starter/ vs files/ to see the endianness mismatch at byte +4 TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter -x c - starter/core.c -o "$TMP/dump" <<'EOF' && "$TMP/dump" ; rm -rf "$TMP" #include "core.h" #include <stdio.h> int main(void) { unsigned char b[0xc10]; pack_image(b, sizeof b); printf("starter IVT[0..7]=%02X_%02X_%02X_%02X entry=%02X_%02X_%02X_%02X (get_le32=0x%08X)\n", b[0],b[1],b[2],b[3], b[4],b[5],b[6],b[7], get_le32(b+4)); return 0; } EOF # 3. Build the repaired archive files/libbsp.a and inspect exported symbols make -B -C files nm -g --defined-only files/libbsp.a # 4. Run the authoritative 5-check TAP version 13 harness sh check.sh*Why each step runs:* Step 1 reproduces failing_tap safely in $TMP; Step 2 prints the exact serialized bytes 87_80_00_00 (get_le32 = 0x00008087) emitted by starter/core.c; Step 3 compiles files/libbsp.a cleanly under -Werror; and Step 4 verifies all 5 TAP checks exit 0.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
- Seeded Flaw in
starter/core.c:3-6(put_le32):starterwritesp[i] = (unsigned char)(value >> (8U * (3U - i)));-- serializing most-significant byte first (big-endian) whileget_le32()(lines 7-11) reconstructsp[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)(little-endian)! - Verified Repair in
files/core.c:3-6: Changes the shift top[i] = (unsigned char)(value >> (8U * i));so0x87800000Uwrites[0x00, 0x00, 0x80, 0x87]atout + 4,0x877ff420Uatout + 16(boot_data),0x877ff400Uatout + 20(self),0x877ff000Uatout + 32(Boot Data.start), and0x1010Uatout + 36(Boot Data.length). dcd_valid(core.c:16-34): Verifiesp[0] == 0xd2U && p[3] == 0x40Uand big-endiantotal = be16(p + 1)in[4, 1768]and<= n, then walks every command record checking subtraction boundlen <= total - atand legal command shapes:Write Data(0xcc,param == 4,len >= 12,(len - 4) % 8 == 0),Check Data(0xcf,param == 0x0c,len == 16), orNOP(0xc0,param == 0,len == 4).pack_image(core.c:35-44): Rejectscapacity < 0xc10Ubeforememset(out, 0, 0xc10U), writesIVTheader bytes[0xd1, 0x00, 0x20, 0x40]directly atout[0..3], populatesIVTandBoot Datapointers, and places the16-byte"FORMAT-FIXTURE!!"payload atout + 0xc00(self + 0xc00 = 0x87800000).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m04-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 3/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link not ok 2 - serializes known IVT header bytes and runtime pointers --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 1; inspect tests.c for the exact input and expected result' ... not ok 3 - validates compact file and media geometry independently --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 2; inspect tests.c for the exact input and expected result' ... ok 4 - accepts the supported DCD command fixture and rejects malformed input ok 5 - rejects insufficient output capacity without modifying the destination # pass 3/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - serializes known IVT header bytes and runtime pointers ok 3 - validates compact file and media geometry independently ok 4 - accepts the supported DCD command fixture and rejects malformed input ok 5 - rejects insufficient output capacity without modifying the destination # pass 5/58. Explanation of Observed Behavior
Notice why starter/ passes check 4 (ok 4) and check 5 (ok 5) while failing checks 2 and 3: dcd_valid() uses be16() on big-endian DCD bytes and never calls put_le32(), and pack_image(image, sizeof image - 1U) returns false on line 37 before calling put_le32(). In check 2 (tests.c case 1), image[0..3] (D1 00 20 40) passes line 12 because pack_image() wrote those four header bytes directly, then get_le32(image + 4) == 0x87800000U aborts on line 13 (0x00008087U != 0x87800000U). In check 3 (tests.c case 2), Boot Data.start at image + 32 (0x00f07f87U) aborts line 19. Fixing put_le32() resolves both checks (# pass 5/5).
9. Experiment Variations
- Zero-Length
DCDSubcommand Infinite-Loop Trap: Removelen < 4Uoncore.c:25in a scratch copy and runtests.ccase3(which mutatesd[6] = 0Uat line29sobe16(p + 5) == 0): withoutlen >= 4U,at += 0spins forever insidewhile (at < total)! - ROM
1768-ByteDCDCeiling Breach: Construct an otherwise valid1772-byteDCDbuffer (0xD2, 0x06, 0xEC, 0x40+442NOPrecords) and confirmdcd_valid()rejectstotal > 1768Ujust as thei.MX6ULLBoot ROM does. - Host Unaligned-Pointer Cast vs Bytewise
put_le32: Compiletests.candfiles/core.cwith-fsanitize=undefined,addressand verify bytewiseput_le32(p + 1, ...)never triggers an unaligneduint32_t *store fault.
10. Performance Measurements
Measured on Linux 7.0.0-42-generic (x86_64) using CLOCK_MONOTONIC across 5 warmup runs and 35 timed samples:
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 / Boot ROM Context |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 136.50 ms | 156.61 ms | 160.90 ms | Host build & test-runner latency |
verify 4-case .imx / DCD suite (verify 1..4) | 3530.6 us | 4584.0 us | 5507.5 us | Host validation of 3088 B .imx + 36 B DCD |
Boot ROM SD read of 4112 B (~9 sectors @ 25 MHz) | Modeled in RAM | Modeled in RAM | Modeled in RAM | ~350 - 900 us SPI/SDHC transfer + DCD MMIO writes |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 2 & not ok 3 (get_le32 reads byte-reversed addresses) | put_le32() shifts by 8U * (3U - i) (big-endian) | Shift by 8U * i so p[0] holds LSB and p[3] holds MSB | ||
IVT word reads 0xD1002040 instead of 0x402000D1 in ARM RAM | Wrote 0x402000D1 with big-endian byte order [0x40, 0x20, 0x00, 0xD1] | Emit bytes [0xD1, 0x00, 0x20, 0x40] (put_le32(out, 0x402000D1U)) | ||
verify 3 hangs when d[6] = 0U | dcd_valid() accepted len == 0U and failed to advance at | Enforce `if (len < 4U \ | \ | len > total - at) return false;` |
.imx written at byte 0 of SD card wipes MBR & fails boot | Confused compact .imx (starts at 0x400) with full disk image | Flash .imx with dd bs=512 seek=2 conv=fsync (1024-byte offset) |
12. Guided Questions
- Why does
pack_image()storelength = 0x1010U(sizeof image + 0x400U) insideBoot Dataatout + 36even though the.imxbuffer itself is only0x0C10U(3088) bytes long?
- *Hint 1:* Compute
self - start(0x877FF400 - 0x877FF000 = 0x400) and inspect where byte0of theSD/eMMCcard lands in targetDDRwhen the Boot ROM copies fromLBA 0. - *Hint 2:* Add the
0x400-byte leading media gap (LBA 0..1) to the0x0C00-byteIVT-to-entry span (0x87800000 - 0x877FF400) plus the0x10-byte payload (0x400 + 0xC00 + 0x10).
- Why do
put_le32()andget_le32()operate onunsigned char *byte-by-byte instead of casting*(uint32_t *)p = value?
- *Hint 1:* Check ISO C11 strict-aliasing rules (Section 6.5p7) and arbitrary caller buffer alignment (
pneed not be4-byte aligned). - *Hint 2:* What would
*(uint32_t *)p = valueemit if the host packer were compiled on a big-endian build server?
13. Independent Challenges
- Near Transfer — Embedded
DCDPointer Integration (pack_image_with_dcd): Writebool pack_image_with_dcd(unsigned char *out, size_t cap, const unsigned char *dcd, size_t dcd_len)that validatesdcdviadcd_valid(), placesdcdatout + 0x40(0x877FF440in RAM, safely clear ofIVT[0x00..0x1F]andBoot Data[0x20..0x2B]), and writes0x877FF440UintoIVT.dcd(out + 8) only whendcd != NULL. - Far Transfer —
.imxBinary Dissector & Consistency Auditor: Build a standalone C11 tool that reads a packed.imximage and checksIVTheaderD1 00 20 40,self > start,boot_data == self + 0x20,dcd == 0 || dcd_valid(...), andentry >= self + 0x40 && entry < start + length.
14. Solutions & Explanations
- Guided Question 1:
Boot Data.start(0x877FF000) represents the destination of byte0of the boot medium (0x400bytes belowIVT.self = 0x877FF400), soBoot Data.lengthmust cover the initial0x400media offset plus the entire.imxfile (0x0C10), totaling0x1010bytes (end = 0x87800010). - Guided Question 2: Bytewise shifts on
unsigned char *are 100% portable across little-endian and big-endian hosts and immune to both unaligned-pointer traps and C11 strict-aliasing undefined behavior. - Challenge 1 Guard: Ensure
0x40U + dcd_len <= 0x0C00U(dcd_len <= 3008U, already tighter viadcd_valid's1768Ucap) beforememcpy(out + 0x40, dcd, dcd_len)andput_le32(out + 8, 0x877ff440U).
Run locally in your terminal and check off each verification milestone.
Not started
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. - 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.
Step sequence — frame strip: steps_m04_l03
Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.
reveals: step1
highlights: step1
Step 2: Validate every CC, CF, and C0 subcommand length >= 4 and <= total - at before advancing the cursor.
reveals: step2
highlights: step2
Step 3: Assemble IVT (0x00 LE), Boot Data (0x20 LE), DCD (0x2C BE), and payload (0x0C00) into verified.imx.
reveals: step3
highlights: step3
Step 4: Assert known raw byte vectors (02 0C 40 6C) and separate container-format proof from DDR3 calibration.
reveals: step4
highlights: step4
m05/
C runtime startup, linker placement, and peripheral headers
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.
What ISO C11 Quietly Assumes Before main() Executes Its First Line
On a desktop Linux workstation, writing int g_retry = 3; static int g_err_cnt; int main(void) { ... } feels effortless because the Linux kernel execve() loader and user-space _start (crt1.o) build an entire world before main() runs: virtual pages are mapped, an 8-byte-aligned stack is allocated, .data pages hold 3, and .bss pages are demand-zeroed to 0. On bare-metal Cortex-A7 silicon, none of that happens automatically! When the i.MX6ULL Boot ROM finishes copying your .imx payload to 0x87800000 (IVT.entry) and branches to _start, Figure 5.1a shows the raw hardware reality:
- No valid C stack exists yet (
SP_svcis unknown): If your very first C function pushes{r4, lr}(stmfd sp!, {r4, lr}) or spills a64-bit integer (strd, requiring8-byteAAPCSstack alignment), an uninitialized or4-byte-misalignedSPcorrupts random memory or triggers an alignment Data Abort! .datainitializers may sit at a different Load Memory Address (LMA) than their runtime Virtual Memory Address (VMA): When.datais linked atVMA 0x87810000(__data_start) while its initial bytes{1..8}are packed right after.rodataatLMA 0x87800090(__data_load),0x87810000still holds randomDDR3power-on bit patterns (0xA5A5A5A5) until startup copies[__data_load, __data_load + len)to__data_start!.bssoccupies zero file bytes (SHT_NOBITS): Uninitialized globals (static int g_err_cnt;) have no zero bytes stored inbsp.bin. Unless startup explicitly writes0across[__bss_start, __bss_end), everyif (g_err_cnt == 0)check in C reads randomDDR3charge!
Figure 5.1a. Supervisor/interrupt-mask configuration (top) and physical RAM transformation performed by start.S before bl main (bottom).
mental model: 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 /DDR3 readiness, and must honor exact half-open linker address intervals.
definition (Freestanding C Runtime Startup (crt0 / start.S)): 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.
Step through the four-stage runtime bring-up sequence below:
- Step 1. Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or -trained DDR3 already backing RAM.
- Step 2. Step 2: Mask IRQ/FIQ (0xC0) in SVC mode (0x13) via CPSR RMW, then load 8-byte-aligned SP = __stack_top.
- Step 3. Step 3: Copy [__data_load, +size) to __data_start and zero [__bss_start, __bss_end) with pre-checked loops.
- Step 4. Step 4: Branch-with-link (bl main) into C11 and catch any return inside a bounded 5: wfi; b 5b loop.
Figure 5.1b. Never execute a C call before SP_svc, .data relocation, and .bss zeroing all complete.
Half-Open Loop Invariants, Unsigned BHS & Stackless Discipline
Inspect Figure 5.1b alongside target.S below to see why every instruction in _start is chosen deliberately. First, _start modifies CPSR via read-modify-write (mrs r0, cpsr -> bic #0x1f -> orr #0x13 -> orr #0xc0 -> msr cpsr_c, r0) rather than blasting a magic literal across all 32 CPSR bits. Note the architectural precondition: if a bootloader ever entered your image in Hyp mode (0x1A), exiting Hyp to SVC requires eret (msr elr_hyp / spsr_hyp), not msr cpsr_c. Second, notice that _start touches zero stack memory until ldr sp, =__stack_top completes!
Third, trace the .data and .bss word loops in Figure 5.1b: why cmp r0, r1 followed by bhs (Branch if Higher or Same, unsigned >=) before str?
- Pre-checked (
cmpbeforestr) handles0-byte sections: When.bssis empty (__bss_start == __bss_end),cmp r0, r1setsC = 1, Z = 1andbhs 4fexits immediately with zero stores—whereas a post-checkeddo..whileloop overwrites4bytes past__bss_end! - Exclusive upper bound (
bhs, notbhi): Linker end symbols (__data_end,__bss_end) mark the first byte after the section ([start, end)), sor0 == r1must stop immediately without clobbering the neighbor at[end]. - Unsigned (
bhs, not signedbge):DDR3addresses at0x87800000have bit31 == 1(negative if misinterpreted as signedint32_t!); unsigned carry flags order the full0x00000000..0xFFFFFFFFphysical map monotonically.
Figure 5.1b. Pre-checked unsigned half-open [start, end) word loops (left) contrasted against three classic bare-metal startup bugs (right).
| Startup Implementation Detail | Instruction Sequence | Empty / Boundary Behavior | Defect When Violated |
|---|---|---|---|
| Pre-checked unsigned loop | cmp r0, r1 -> bhs done -> str | 0 stores when start == end; stops at end | Production safe across 0..4 GiB |
Post-checked loop (do..while) | str -> cmp r0, r1 -> blo loop | Writes 4 B when start == end! | Corrupts word at __bss_end on empty .bss |
Inclusive upper bound (<=) | cmp r0, r1 -> bhi done | Writes 1 extra word past end every boot! | Silently zeroes first word of .stack/.rodata |
Early bl before ldr sp | bl debug_led at line 1 of _start | Pushes {r4, lr} to wild/unaligned SP_svc | Immediate Data Abort or Boot ROM/RAM corruption |
learner@ksa:~/gl-e01/m05-l01$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 28 -H 29 -H 30 target.S File: target.S .syntax unified .cpu cortex-a7 .arm .section .text.start, "ax" .global _start _start: mrs r0, cpsr bic r0, r0, #0x1f orr r0, r0, #0x13 orr r0, r0, #0xc0 msr cpsr_c, r0 ldr sp, =__stack_top ldr r0, =__data_start ldr r1, =__data_end ldr r2, =__data_load 1: cmp r0, r1 bhs 2f ldr r3, [r2], #4 str r3, [r0], #4 b 1b 2: ldr r0, =__bss_start ldr r1, =__bss_end mov r2, #0 3: cmp r0, r1 bhs 4f str r2, [r0], #4 b 3b 4: bl main 5: wfi b 5b- Establish 8-byte-aligned SP_svc AFTER masking IRQ/FIQ in SVC mode and BEFORE any bl call.
- Pre-checked unsigned bhs handles start == end cleanly and stops before exclusive __data_end / __bss_end.
- Catch any return from main() inside a low-power wfi loop instead of falling into literal pools.
Sentinel-Poisoned Relocation & BSS Boundary Proof in ISO C11
In lds_vma_lma_solver.c below, we poison a 64-byte simulated RAM arena with 0xA5, place 8 initializer bytes {1..8} at the LMA offset (4), copy them to VMA (16..23), and zero .bss ([24, 40)). Asserting ram[23] == 8U (last .data byte intact) and ram[40] == 0xA5U (byte right at exclusive bss_end untouched!), followed by an empty [48, 48) .bss pass (ram[48] == 0xA5U) and an unaligned SP = 0x87820004U rejection, proves every boundary algebraically!
learner@ksa:~/gl-e01/m05-l01$ bat -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 lds_vma_lma_solver.c File: lds_vma_lma_solver.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct crt_syms { uint32_t text_base, etext, data_load, data_start, edata; uint32_t bss_start, bss_end, stack_top; }; static struct crt_syms solve_syms(uint32_t base, uint32_t text_ro, uint32_t data_vma, uint32_t data_sz, uint32_t bss_sz, uint32_t stack_top) { struct crt_syms s; s.text_base = base; s.etext = base + text_ro; s.data_load = (s.etext + 3U) & ~3U; s.data_start = data_vma; s.edata = data_vma + ((data_sz + 3U) & ~3U); s.bss_start = (s.edata + 3U) & ~3U; s.bss_end = s.bss_start + ((bss_sz + 3U) & ~3U); s.stack_top = stack_top; return s; } static bool crt_init_ram(unsigned char *ram, size_t cap, size_t lma_off, size_t vma_off, size_t data_sz, size_t bss_off, size_t bss_end, uint32_t sp_top) { if ((sp_top & 7U) != 0U || bss_off > bss_end || bss_end > cap) return false; if (lma_off + data_sz > cap || vma_off + data_sz > bss_off) return false; if (data_sz > 0U && lma_off != vma_off) memcpy(ram + vma_off, ram + lma_off, data_sz); for (size_t i = bss_off; i < bss_end; ++i) ram[i] = 0U; return true; } int main(void) { struct crt_syms s = solve_syms(0x87800000U, 144U, 0x87810000U, 8U, 16U, 0x87820000U); assert(s.etext == 0x87800090U && s.data_load == 0x87800090U); assert(s.edata == 0x87810008U && s.bss_end == 0x87810018U); unsigned char ram[64]; const unsigned char init[8] = {1U, 2U, 3U, 4U, 5U, 6U, 7U, 8U}; memset(ram, 0xa5, sizeof ram); memcpy(ram + 4U, init, sizeof init); /* LMA image bytes at offset 4 */ assert(crt_init_ram(ram, 64U, 4U, 16U, 8U, 24U, 40U, s.stack_top)); assert(memcmp(ram + 16U, init, 8U) == 0 && ram[23] != 0U && ram[40] == 0xa5U); for (size_t i = 24U; i < 40U; ++i) assert(ram[i] == 0U); assert(crt_init_ram(ram, 64U, 4U, 16U, 0U, 48U, 48U, s.stack_top) && ram[48] == 0xa5U); assert(!crt_init_ram(ram, 64U, 4U, 16U, 8U, 24U, 40U, 0x87820004U)); printf("etext=0x%08X data_vma=0x%08X..0x%08X bss_end=0x%08X sp=0x%08X\n", s.etext, s.data_start, s.edata, s.bss_end, s.stack_top); return 0; }- Compute _etext, __data_load (LMA), __data_start.._edata (VMA), [__bss_start, __bss_end), and 8-byte aligned __stack_top.
- Require 8-byte AAPCS32 stack alignment and non-overlap above __bss_end before copying .data or zeroing .bss.
- Copy [lma, lma + data_sz) to vma and zero [bss_start, bss_end) exclusively, performing zero writes when bss_start == bss_end.
Running the Relocation Solver & Assembling start.S for Cortex-A7
Compile and run lds_vma_lma_solver.c on the workstation, then assemble target.S into ARMv7-A object code (target.o) to verify instruction syntax and label resolution.
learner@ksa:~/gl-e01/m05-l01gcc -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-l01clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -c target.S -o target.olearner@ksa:~/gl-e01/m05-l01learner@ksa:~/gl-e01/m05-l01strace -e trace=write,exit_group \./lds_vma_lma_solverwrite(1, "etext=0x87800090 data_vma=0x8781"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++Flat RAM Builds vs Split XIP Builds & Linker Contract Coupling
Notice two subtle couplings between start.S and the rest of the boot chain. First, if a flat TFTP or DDR3 image links .data with LMA == VMA (__data_load == __data_start), inserting cmp r0, r2; beq 2f ahead of the .data loop skips redundant self-copying cleanly; conversely, on a QSPI Execute-in-Place (XIP) build (LMA in 0x60000000 flash, VMA in 0x00908000 OCRAM), that LMA -> VMA copy is the only way writable globals receive their initializers! Second, BootData.length (m04-l02) must cover __data_load + (__data_end - __data_start)—otherwise start.S diligently copies uninitialized RAM into .data! Later: Lesson m05-l02 authors the exact GNU ld script (bsp.lds) that defines __data_load, __data_start, __data_end, __bss_start, __bss_end, and __stack_top.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Solving QSPI-to-OCRAM Relocation Symbols
Trace a split XIP build where .text + .rodata (0x1240 B) execute in QSPI flash at 0x60001000 while .data (20 B), .bss (48 B), and .stack live in OCRAM starting at 0x00908000 (stack_top = 0x00918000). Step 1 (Addresses): Compute _etext = __data_load = 0x60002240, __data_start = 0x00908000, _edata = __bss_start = 0x00908014, and __bss_end = 0x00908044. Step 2 (Word Loop Check): Verify (0x14 % 4 == 0) and (0x30 % 4 == 0) so word-stepped #4 loops never overrun a 1-, 2-, or 3-byte tail.
Independent Practice: Overlap-Safe Memmove & Arbitrary-Byte Tail Verifier
Extend lds_vma_lma_solver.c into crt_reloc_verifier.c supporting unrounded byte counts (data_sz = 7 B) and overlapping self-relocation (vma > lma with vma < lma + len), proving why forward copy corrupts overlapping upper destinations while backward copy preserves every byte.
? check 1 · 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?
- [ ] The cross-compiler omitted
-fzero-bss-in-objcopyduring binary extraction - [ ]
AAPCSrequires passing zero-initialized globals inr0..r3 - [x]
start.Sfailed to zero the complete linker-defined[__bss_start, __bss_end)runtime range beforebl main
Answer: start.S failed to zero the complete linker-defined [__bss_start, __bss_end) runtime range before bl main
Why: 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.
? check 2 · Why does start.S load three distinct symbols (__data_load, __data_start, and __data_end) to initialize .data?
- [ ] Because
DDR3requires reading every address twice before writing - [x] Because
.data's initial bytes in the loaded image (LMA = __data_load) can reside at a different address from the live writable globals (VMA = __data_start..__data_end) - [ ] Because
AAPCSstores local stack variables between__data_loadand__data_start
Answer: Because .data's initial bytes in the loaded image (LMA = __data_load) can reside at a different address from the live writable globals (VMA = __data_start..__data_end)
Why: 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.
? check 3 · 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?
- [x] The C callee's prologue (
push {r4, lr}) or register spills can immediately write through an uninitialized or misalignedSP_svc - [ ]
ARMv7-Aforbids executingblwhileIRQandFIQare masked inCPSR - [ ]
UART1registers are inaccessible fromSupervisor(0x13) mode
Answer: The C callee's prologue (push {r4, lr}) or register spills can immediately write through an uninitialized or misaligned SP_svc
Why: 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.
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. - Bare-metal startup must establish a valid stack before calling C code that can use it.
- A public call boundary requires eight-byte stack alignment.
- The helper may use an invalid stack before its preconditions hold.
Step sequence — frame strip: steps_m05_l01
Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or DCD-trained DDR3 already backing RAM.
reveals: step1
highlights: step1
Step 2: Mask IRQ/FIQ (0xC0) in SVC mode (0x13) via CPSR RMW, then load 8-byte-aligned SP = __stack_top.
reveals: step2
highlights: step2
Step 3: Copy [__data_load, +size) to __data_start and zero [__bss_start, __bss_end) with pre-checked loops.
reveals: step3
highlights: step3
Step 4: Branch-with-link (bl main) into C11 and catch any return inside a bounded 5: wfi; b 5b loop.
reveals: step4
highlights: step4
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.
How GNU ld Turns Relocatable .o Files Into Dual-Address Firmware Maps
In Lesson m05-l01, start.S consumed six magic names—__stack_top, __data_load, __data_start, __data_end, __bss_start, and __bss_end—without defining any of them! Where do those exact addresses come from, and what stops the linker from placing a random helper function at 0x87800000 ahead of _start, or inflating bsp.bin by 64 KiB of useless zeros? That contract belongs to the GNU ld linker script (bsp.lds).
Trace Figure 5.2a from left to right to understand the two distinct addresses every output section possesses inside ELF program headers (readelf -l), even when the ARMv7-A MMU is completely turned off (SCTLR.M = 0):
- Virtual Memory Address (
VMA, queried viaADDR(.data)): The runtime execution address baked into Cldr/strinstructions andblbranch targets. In Figure 5.2a,.text(128 B) and.rodata(16 B) execute at0x87800000..0x87800090, while writable.data(8 B) is linked atVMA = 0x87810000. - Load Memory Address (
LMA, set viaAT(__data_lma)and queried viaLOADADDR(.data)): Whereobjcopy -O binary(and the Boot ROM) places the section's initial image bytes! If you link.dataat0x87810000withoutAT(__data_lma),LMAdefaults toVMA(0x87810000), forcingobjcopyto zero-pad the entire65,392-byte gap (0x87800090..0x87810000) and bloatingbsp.binfrom152 Bto65,544 B! AddingAT(__data_lma)packs those8.databytes snugly at0x87800090(152 Btotal.bin), while(NOLOAD)marks.bssand.stackasSHT_NOBITS(0file bytes!).
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).
mental model: 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, 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.
definition (GNU ld Location Counter (.), VMA vs AT(LMA) & Symbol-Address Semantics): 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.
Walk through the four-stage contract connecting input .o sections, bsp.lds policy, boundary symbols, and banked stacks:
- Step 1. Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.
- Step 2. Step 2: Pack .data initializers at AT(__data_lma) while linking live globals at VMA 0x87810000.
- Step 3. Step 3: Define __bss_start and ALIGN(4)-rounded __bss_end inside a (NOLOAD) .bss section including *(COMMON).
- Step 4. Step 4: Reserve 8-byte-aligned banked stacks above .bss and guard alignment + RAM ceiling with ASSERT().
Figure 5.2b. Linker boundary symbols are an executable contract: define them inside aligned output sections and reference their addresses, never their dereferenced values.
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. When you write uint32_t g_var = 42; in C, the linker reserves 4 bytes in .data and puts g_var's address in .symtab; evaluating g_var in C emits an ldr that reads 42 from memory. When you write __bss_start = .; in bsp.lds, the linker puts 0x87810008 in .symtab and reserves zero bytes (0x87810008 is the first global inside .bss!). Therefore, declaring extern uint32_t __bss_start; and casting (void *)__bss_start in C dereferences 0x87810008 and treats whatever garbage sits in .bss as a pointer! Always declare linker symbols in C as extern char __bss_start[], __bss_end[]; so array-to-pointer decay yields the symbol address 0x87810008 directly (matching ldr r0, =__bss_start in start.S).
Check two placement rules inside bsp.lds below as well. First, put __bss_start = .; inside .bss ALIGN(4) (NOLOAD) : { ... } (after section alignment adjusts .) and put . = ALIGN(4); before __bss_end = .;, guaranteeing (__bss_end - __bss_start) % 4 == 0 for start.S's 4-byte str r2, [r0], #4 loop! Second, wrap *(.text.start) in KEEP(...) so --gc-sections never deletes _start as "uncalled by C."
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).
GNU ld Directive | Effect on bsp.elf / bsp.bin | Runtime / Packer Obligation | Defect When Omitted |
|---|---|---|---|
KEEP(*(.text.start)) at .text start | Pins _start at 0x87800000; survives --gc-sections | IVT.entry must also store 0x87800000 | Helper function lands at 0x87800000 ahead of _start! |
.data VMA : AT(__data_lma) | Separates ADDR(.data) from LOADADDR(.data) | start.S copies SIZEOF(.data) LMA -> VMA | 64 KiB+ zero-padding bloat in bsp.bin |
(NOLOAD) on .bss and .stack | Emits SHT_NOBITS (0 file bytes in bsp.bin) | start.S zeroes [__bss_start, __bss_end) | .bss/.stack dumped into .bin, inflating transfer |
ASSERT((__stack_top & 7) == 0, ...) | Fails ld exit status immediately on overflow/misalign | Sync ceiling (0x87900000) with board RAM map | Silent stack/.bss overlap or AAPCS alignment fault |
learner@ksa:~/gl-e01/m05-l02$ bat -H 5 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 30 -H 31 bsp.lds File: bsp.lds ENTRY(_start) SECTIONS { . = 0x87800000; .text : { KEEP(*(.text.start)) *(.text*) } .rodata ALIGN(4) : { *(.rodata*) } __data_lma = ALIGN(., 4); .data 0x87810000 : AT(__data_lma) { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } __data_load = LOADADDR(.data); __image_load_end = LOADADDR(.data) + SIZEOF(.data); .bss ALIGN(4) (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } .stack ALIGN(8) (NOLOAD) : { __stack_bottom = .; . += 4096; __stack_top = .; } ASSERT((__stack_top & 7) == 0, "stack alignment") ASSERT(__stack_top <= 0x87900000, "RAM window exceeded") }- Pin .text.start at 0x87800000 with KEEP() so neither link order nor --gc-sections displaces _start.
- Export LOADADDR(.data) as __data_load and compute __image_load_end for BootData.length validation.
- Fail the link at build time if __stack_top violates 8-byte alignment or exceeds the 1 MiB RAM window.
Verifying Overflow-Safe ALIGN() & Dual-Mode Stack Partitioning in C11
When firmware enables GICv2 interrupts (GL-E02), _start partitions both SP_irq (4 KiB) and SP_svc (8 KiB) above __bss_end while CPSR keeps I | F == 0xC0 masked. In reset_sp_bss_verifier.c below, align_up() validates power-of-two alignments ((a & (a - 1)) == 0) and guards value <= UINT32_MAX - (a - 1) before adding, while verify_reset_map() checks CPSR interrupt masking, 4-byte .bss alignment, 8-byte IRQ/SVC stack alignment, and non-overflow inside [0x87800000, 0x87900000).
learner@ksa:~/gl-e01/m05-l02$ bat -H 7 -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 reset_sp_bss_verifier.c File: reset_sp_bss_verifier.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> static bool align_up(uint32_t value, uint32_t alignment, uint32_t *out) { if (alignment == 0U || (alignment & (alignment - 1U)) != 0U) return false; uint32_t add = alignment - 1U; if (value > UINT32_MAX - add) return false; *out = (value + add) & ~add; return true; } static bool verify_reset_map(uint32_t cpsr_reset, uint32_t bss_start, uint32_t bss_end, uint32_t irq_sz, uint32_t svc_sz, uint32_t win_end, uint32_t *irq_sp, uint32_t *svc_sp) { if ((cpsr_reset & 0xc0U) != 0xc0U) return false; /* CPSID if required */ if (bss_start > bss_end || ((bss_start | bss_end) & 3U) != 0U) return false; if (irq_sz == 0U || svc_sz == 0U || ((irq_sz | svc_sz) & 7U) != 0U) return false; uint32_t irq_bot = 0U; if (!align_up(bss_end, 8U, &irq_bot)) return false; if (irq_sz > win_end - irq_bot) return false; uint32_t irq_top = irq_bot + irq_sz; if (svc_sz > win_end - irq_top) return false; *irq_sp = irq_top; *svc_sp = irq_top + svc_sz; return ((*irq_sp & 7U) == 0U) && ((*svc_sp & 7U) == 0U); } int main(void) { uint32_t out = 0U; assert(align_up(0x87800000U, 4U, &out) && out == 0x87800000U); assert(align_up(0x87800003U, 4U, &out) && out == 0x87800004U); assert(!align_up(UINT32_MAX, 8U, &out) && !align_up(10U, 3U, &out)); uint32_t text = 128U, rodata = 16U, data = 8U, bss = 64U; uint32_t data_lma = 0x87800000U + text + rodata; uint32_t data_vma = 0x87810000U, bss_start = data_vma + data; uint32_t bss_end = bss_start + bss, irq_sp = 0U, svc_sp = 0U; assert(data_lma == 0x87800090U && text + rodata + data == 152U); assert(verify_reset_map(0xd3U, bss_start, bss_end, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); assert(!verify_reset_map(0x13U, bss_start, bss_end, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); assert(!verify_reset_map(0xd3U, bss_start, bss_end + 2U, 4096U, 8192U, 0x87900000U, &irq_sp, &svc_sp)); printf("LMA=0x%08X packed=%uB bss_end=0x%08X irq_sp=0x%08X svc_sp=0x%08X\n", data_lma, text + rodata + data, bss_end, irq_sp, svc_sp); return 0; }- Accept only power-of-two alignments and guard value <= UINT32_MAX - add before rounding up.
- Require I|F masked (0xC0) and word-aligned [bss_start, bss_end) boundaries matching the 4-byte zero loop.
- Place 8-byte-aligned IRQ and SVC stacks sequentially above __bss_end without overlapping or exceeding win_end.
Executing the Linker-Map & Banked-Stack Verifier
Compile and run reset_sp_bss_verifier.c below. Confirm that packed=152B (128 + 16 + 8), bss_end=0x87810048, irq_sp=0x87811048, and svc_sp=0x87813048 (0x48 == 72 == 9 * 8, 8-byte aligned), while unmasked CPSR = 0x13U and unrounded bss_end + 2U are rejected cleanly.
learner@ksa:~/gl-e01/m05-l02gcc -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-l02learner@ksa:~/gl-e01/m05-l02strace -e trace=write,exit_group \./reset_sp_bss_verifierwrite(1, "LMA=0x87800090 packed=152B bss_e"..., 82) = 82exit_group(0) = ?+++ exited with 0 +++Auditing Orphan Sections with readelf -l & nm -n
Even with bsp.lds in place, compilers occasionally emit auxiliary sections—such as .ARM.exidx (unwind tables) or .rodata.str1.4 (merged strings). If a wildcard (*(.rodata*)) misses an input section, GNU ld places that orphan section heuristically, potentially slipping bytes after __image_load_end! Always pass -Wl,--orphan-handling=warn (or =error once .ARM.attributes / .comment are handled) and inspect readelf -S -l bsp.elf plus nm -n bsp.elf so __image_load_end - 0x87800000 equals the exact bsp.bin file size. Later: Lesson m05-l03 moves from RAM layout to Memory-Mapped I/O (MMIO) peripheral structs, proving register byte offsets at compile time with _Static_assert and offsetof.
Common Production Pitfalls
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.
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(...).
Practice & Retrieval
Guided Practice: Binary Gap Bloat & Banked SP Initialization
Check three linker mechanics by hand. Step 1 (Binary Size): With .text (512 B) at 0x87800000 and .data (32 B) at 0x87810000, compute bsp.bin size without AT(...) (0x87810020 - 0x87800000 = 65,568 B) versus with AT(ALIGN(LOADADDR(.text) + SIZEOF(.text), 4)) (512 + 32 = 544 B). Step 2 (Pre-Align Bug): If __bss_start = .; sits outside .bss ALIGN(16) when . = 0x87810004, note that [0x87810004, 0x87810010) (12 padding bytes before .bss) would be zeroed unintentionally.
Independent Practice: Multi-Section Overlap & Orphan Auditor (lds_map_auditor.c)
Extend reset_sp_bss_verifier.c into lds_map_auditor.c checking an array of section records (name, vma, lma, size, align, noload): verify power-of-two vma and lma alignments, pairwise non-overlap of all runtime [vma, vma + size) intervals, pairwise non-overlap of load [lma, lma + size) intervals on non-NOLOAD sections, and exact agreement between serialized .bin span and BootData.length - 0x1000.
? check 1 · 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?
- [ ] Either address interchangeably, because
Cortex-A7hardware aliasesLMAandVMA - [x]
0x87810000(VMA), afterstart.Scopies the initial bytes from0x87800090(LMA) - [ ]
0x87800090(LMA) for reads and0x87810000(VMA) for writes
Answer: 0x87810000 (VMA), after start.S copies the initial bytes from 0x87800090 (LMA)
Why: 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.
? check 2 · Where must __bss_start = .; and __bss_end = .; be placed when start.S clears .bss using 4-byte str r2, [r0], #4 stores?
- [x] Inside the
ALIGN(4).bssoutput section, with. = ALIGN(4);immediately before__bss_end = .; - [ ] Before
.dataso a single zeroing loop clears both.dataand.bss - [ ] Outside
.bssbeforeALIGN(16)so unaligned bytes in.dataare cleared too
Answer: Inside the ALIGN(4) .bss output section, with . = ALIGN(4); immediately before __bss_end = .;
Why: 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.
? check 3 · Retrieval: does writing ENTRY(_start) inside bsp.lds automatically populate the IVT.entry pointer inside a raw .imx boot image?
- [ ] Yes; the
i.MX6ULLBoot ROM parsesELFheaders directly fromLBA 2 - [ ] Yes;
objcopy -O binaryprepends a32-byteIVTwheneverENTRY(_start)is present - [x] No;
objcopy -O binarystripsELFmetadata, so.section .ivtor the.imxpacker must explicitly write_start's runtime address intoIVT.entry
Answer: No; objcopy -O binary strips ELF metadata, so .section .ivt or the .imx packer must explicitly write _start's runtime address into IVT.entry
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m05_l02
Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.
reveals: step1
highlights: step1
Step 2: Pack .data initializers at AT(__data_lma) while linking live globals at VMA 0x87810000.
reveals: step2
highlights: step2
Step 3: Define __bss_start and ALIGN(4)-rounded __bss_end inside a (NOLOAD) .bss section including *(COMMON).
reveals: step3
highlights: step3
Step 4: Reserve 8-byte-aligned banked stacks above .bss and guard alignment + RAM ceiling with ASSERT().
reveals: step4
highlights: step4
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.
How C Struct Overlays Map Onto Silicon Decode Comparators
In early assembly experiments (m03-l03), poking 0x0209C000 (GPIO1_DR) and 0x0209C004 (GPIO1_GDIR) by raw numeric literals works for five lines—then rapidly turns unmaintainable across seven GPIO registers, CCM clock gates, and SRC status blocks. Firmware engineers replace raw #define pointer arithmetic with struct-mapped Memory-Mapped I/O (MMIO) overlays (KSA_GPIO1->GDIR |= mask;), as shown on the left of Figure 5.3a. Physically, inside the i.MX6ULL AIPS peripheral bus bridge, hardware address comparators decode bits [4:2] of the 32-bit bus transaction relative to 0x0209C000: +0x00 routes to DR, +0x04 to GDIR, +0x08 to read-only PSR, and +0x18 to Write-One-to-Clear (W1C) ISR. If a C struct accidentally omits ICR2 (+0x10), gpio->ISR silently compiles to ldr/str [r0, #0x14]—writing an interrupt acknowledgment mask straight into IMR (+0x14) without a single compiler warning!
Look at the right panel of Figure 5.3a to see why two well-intentioned "defensive" C habits actually break ARMv7-A MMIO hardware:
- Why
__attribute__((packed))breaks32-bit peripheral registers: Addingpackeddropsalignof(struct gpio_regs)from4down to1. Under-ffreestanding/-mno-unaligned-access, the compiler can no longer assume the struct base pointer is4-byte aligned, so it decomposesgpio->DR = valinto four8-bitstrbbyte transactions! Oni.MX6ULLIPS/AIPSperipheral bridges, many32-bit control registers fault or corrupt state on narrow byte accesses. Always use natural4-byte-aligneduint32_tmembers (explicit uint32_t _pad[N]arrays for address gaps) and prove every offset at compile time with_Static_assert(offsetof(...) == ...)! - Why C bit-fields (
uint32_t pin3 : 1;) breakW1Cand bus width: Bit-field bit ordering and storage-unit load width (ldrbvsldr) are implementation-defined inISO C11. Worse,gpio->ISR.pin3 = 1;compiles intoldr r1, [r0, #0x18] -> orr r1, #8 -> str r1, [r0, #0x18]—a read-modify-write on aW1Cstatus register that wipes every concurrent pending interrupt in the bank!
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).
mental model: 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 hardware rules.
definition (Struct-Mapped Overlay, volatile Semantics & SDK Header Layering): 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 header while isolating carrier-specific pin assignments and active-low polarity inside a narrow board wrapper.
Step through the four-stage workflow for engineering auditable MMIO headers below:
- Step 1. Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
- Step 2. Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.
- Step 3. Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.
- Step 4. Step 4: Wrap board pin and active-low policy behind a narrow API tracked by GCC -MMD -MP dependencies.
Figure 5.3b. Prove every struct offset with _Static_assert(offsetof(...)), use explicit 32-bit masks, and separate silicon facts from board polarity.
Volatile Lost-Update Proof & Three-Tier SDK Adaptation
Examine Figure 5.3b to separate two distinct boundaries that vendor SDKs routinely blur. In panel 1, watch what happens when main() (Writer A) and an interrupt handler (Writer B) both update a volatile uint32_t DR register on different pins (bit 0 vs bit 1): Writer A loads 0, computes 1, and gets preempted; Writer B loads 0, computes 2, and stores 2; when Writer A resumes (or vice versa, as modeled sequentially in mmio_map_dep_auditor.c), the second stale store overwrites the first, leaving DR == 2 instead of 3! volatile forced the compiler to emit every ldr and str, yet zero atomicity existed across the two instructions. Shared DR banks require single-owner discipline or IRQ masking (cpsid i / spinlock).
In panel 2 of Figure 5.3b, observe how to adapt a vendor header cleanly instead of dumping a 40,000-line SDK header into every .c file:
soc_imx6ull.h: Pure silicon facts (0x0209C000U,0x020C4000U).gpio_regs.h(target_m05_l03below):struct gpio_regswithvolatile const uint32_t PSR(turning accidental writes to read-onlyPSRinto compile errors!),_Static_assertchecks, andgpio_ack_mask()writinggpio->ISR = maskdirectly withoutRMW.board_led.h: Carrier pin (GPIO1_IO03) and active-low policy, exposingled_set(bool on)tomain.c.
Figure 5.3b. Why volatile RMW still loses concurrent updates without serialization (top) and the three-tier SDK adaptation boundary (bottom).
| Register Access Strategy | Emitted ARM Instructions | Offset & Semantic Safety | Engineering Verdict |
|---|---|---|---|
Aligned volatile uint32_t struct + _Static_assert + masks | 32-bit ldr / str | Compile-time offset proof; explicit W1C vs RMW | Production bare-metal standard |
Raw #define REG(a) (*(volatile uint32_t *)(a)) | 32-bit ldr / str | No struct type safety across peripheral blocks | Minimal start stubs only |
C bit-fields (volatile uint32_t isr_3 : 1;) | ldrb/strb or ldr+orr+str | Broken: narrow bus faults + wipes sibling W1C IRQs | Never use on MMIO |
__attribute__((packed)) on 32-bit MMIO struct | 4 x ldrb / 4 x strb | Broken: alignof == 1 splits 32-bit bus cycles | Never pack aligned MMIO |
learner@ksa:~/gl-e01/m05-l03$ bat -H 8 -H 11 -H 12 -H 13 -H 14 -H 18 gpio_regs.h File: gpio_regs.h #ifndef KSA_GPIO_REGS_H #define KSA_GPIO_REGS_H #include <stddef.h> #include <stdint.h> struct gpio_regs { volatile uint32_t DR; volatile uint32_t GDIR; volatile const uint32_t PSR; volatile uint32_t ICR1, ICR2, IMR, ISR, EDGE_SEL; }; _Static_assert(offsetof(struct gpio_regs,GDIR)==0x04U,"GDIR offset"); _Static_assert(offsetof(struct gpio_regs,PSR)==0x08U,"PSR offset"); _Static_assert(offsetof(struct gpio_regs,ISR)==0x18U,"ISR offset"); _Static_assert(sizeof(struct gpio_regs)==0x20U,"GPIO span"); #define KSA_GPIO1 ((struct gpio_regs *)(uintptr_t)0x0209c000U) static inline void gpio_ack_mask(struct gpio_regs *gpio, uint32_t mask) { gpio->ISR = mask; } #endif- Qualify PSR as volatile const uint32_t so hardware reads always execute while accidental C assignments fail to compile.
- Prove GDIR (+0x04), PSR (+0x08), ISR (+0x18), and total 32-byte struct size on every compilation.
- Write mask directly to W1C ISR without reading first so concurrent pending interrupt flags survive.
Proving Offset Geometry, Interleaved RMW Loss & -MMD -MP Guards in C11
In mmio_map_dep_auditor.c below, we verify three interlocking firmware invariants on the host: (1) _Static_assert locks the 32-byte GPIO struct layout; (2) interleaving wa = g.dr; wb = g.dr; wa |= 1U; wb |= 2U; g.dr = wa; g.dr = wb; proves g.dr == 2U (bit 0 lost!) versus serialized 0x80000003U (UINT32_C(1) << 31 safe from signed shift UB); and (3) audit_image_map() + has_mmd_mp_guard() verify .bin/.imx/BootData span equations and -MMD -MP phony header rules so header edits never leave stale .o files behind!
learner@ksa:~/gl-e01/m05-l03$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 mmio_map_dep_auditor.c File: mmio_map_dep_auditor.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct gpio_overlay { uint32_t dr, gdir, psr, icr1, icr2, imr, isr, edge_sel; }; _Static_assert(offsetof(struct gpio_overlay, gdir) == 0x04U, "GDIR"); _Static_assert(offsetof(struct gpio_overlay, psr) == 0x08U, "PSR"); _Static_assert(offsetof(struct gpio_overlay, isr) == 0x18U, "ISR"); _Static_assert(sizeof(struct gpio_overlay) == 0x20U, "GPIO span"); static bool audit_image_map(uint32_t entry, uint32_t load_end, uint32_t max_ram, uint32_t *bin_sz, uint32_t *imx_sz, uint32_t *boot_span) { if (load_end <= entry || load_end - entry > max_ram) return false; *bin_sz = load_end - entry; *imx_sz = 0x0c00U + *bin_sz; *boot_span = 0x1000U + *bin_sz; return true; } static bool has_mmd_mp_guard(const char *dep_text, const char *obj, const char *hdr) { char phony[64]; int n = snprintf(phony, sizeof phony, "\n%s:", hdr); if (n <= 0 || (size_t)n >= sizeof phony) return false; return strstr(dep_text, obj) != NULL && strstr(dep_text, hdr) != NULL && strstr(dep_text, phony) != NULL; } int main(void) { struct gpio_overlay g = {0U}; uint32_t wa = g.dr, wb = g.dr; wa |= 1U; wb |= 2U; g.dr = wa; g.dr = wb; assert(g.dr == 2U); /* interleaved RMW loses bit 0 */ g.dr = 0U; g.dr |= 1U; g.dr |= 2U; g.dr |= (UINT32_C(1) << 31); assert(g.dr == 0x80000003U); uint32_t bin = 0U, imx = 0U, span = 0U; assert(audit_image_map(0x87800000U, 0x87800098U, 0x100000U, &bin, &imx, &span)); assert(bin == 152U && imx == 3224U && span == 4248U); assert(!audit_image_map(0x87800000U, 0x87800000U, 0x100000U, &bin, &imx, &span)); const char *good_d = "obj/led.o: bsp/led.c include/gpio_regs.h\ninclude/gpio_regs.h:\n"; const char *no_mp = "obj/led.o: bsp/led.c include/gpio_regs.h\n"; assert(has_mmd_mp_guard(good_d, "obj/led.o:", "include/gpio_regs.h")); assert(!has_mmd_mp_guard(no_mp, "obj/led.o:", "include/gpio_regs.h")); printf("gpio=%zuB ISR=+%zu lost=2 ser=0x%08X bin=%uB imx=%uB mp=ok\n", sizeof g, offsetof(struct gpio_overlay, isr), g.dr, bin, imx); return 0; }- Lock every 32-bit GPIO register offset at compile time via _Static_assert and offsetof.
- Verify .bin, compact .imx (+0x0C00), and Boot Data (+0x1000) spans from symbol-map addresses.
- Confirm GCC -MMD -MP output contains both the object target rule and the phony header: target.
Cross-Checking Struct Layout on Both Host GCC & Target ARMv7-A Clang
Run the host verifier and cross-compile gpio_regs.h directly with clang --target=armv7a-none-eabi ... -x c -c gpio_regs.h! Compiling a header standalone as a translation unit forces the 32-bit ARM EABI front-end to check #ifndef guards, self-contained #includes, and every _Static_assert under the exact target data model (ILP32).
learner@ksa:~/gl-e01/m05-l03gcc -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-l03clang --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-l03learner@ksa:~/gl-e01/m05-l03strace -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 +++From Bare-Metal Physical Casts to Linux 6.12 ioremap() & Modular BSPs
Keep two architectural horizons clear as your codebase grows. First, #define KSA_GPIO1 ((struct gpio_regs *)(uintptr_t)0x0209c000U) works in bare-metal GL-E01 only while SCTLR.M == 0 (flat physical addressing) or under an identity MT_DEVICE MMU map; once the Linux kernel boots with virtual memory active (GL-E04), drivers replace raw physical casts with devm_ioremap_resource() + readl()/writel() (or gpiod consumer descriptors). Second, now that we have clean, assertion-locked peripheral headers, how do we scale from single-file programs to a multi-directory bare-metal Board Support Package without header spaghetti or stale incremental builds? Later: Module m06 (m06-l01) builds that complete modular BSP and Makefile graph.
Common Production Pitfalls
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(...)).
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().
Practice & Retrieval
Guided Practice: Sizing Reserved Gap Arrays for CCM (0x020C4000)
Design a sparse struct ccm_slice overlay without packed covering CCSR (+0x0C), CACRR (+0x10), and CCGR[7] (+0x68..+0x80). Step 1 (Compute Gaps): Before +0x0C lie 0x0C / 4 = 3 words (volatile uint32_t _pad0[3];); between CACRR end (+0x14) and CCGR[0] (+0x68) lie (0x68 - 0x14) / 4 = 0x54 / 4 = 21 words (volatile uint32_t _pad1[21];). Step 2 (Prove Layout): Write _Static_assert(offsetof(struct ccm_slice, CCGR[0]) == 0x68U, "CCGR0"); and _Static_assert(sizeof(struct ccm_slice) == 0x84U, "CCM size");.
Independent Practice: Multi-Peripheral Header Suite (soc_headers_audit.c)
Author a self-contained soc_headers_audit.c defining assertion-locked overlays for GPIO (0x20 B), CCM (0x84 B), and SRC (0x20 B with SCR +0x00, SBMR1 +0x04, _pad[5], SBMR2 +0x1C), asserting alignof(T) == 4U on all three structs and separating silicon offsets from board-level LED/KEY pin macros.
? check 1 · 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?
- [x]
_Static_assert(offsetof(struct gpio_regs, ISR) == 0x18U, "ISR offset"); - [ ] Qualifying the struct pointer with
volatile const - [ ] Compiling with
-fno-strict-aliasingsoGCCrepairsMMIOmember offsets
Answer: _Static_assert(offsetof(struct gpio_regs, ISR) == 0x18U, "ISR offset");
Why: _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.
? check 2 · Why does updating gpio->DR |= (1U << 3); on a volatile uint32_t DR member still require exclusive bank ownership or interrupt masking?
- [ ] Because
volatileinstructs the compiler to cacheDRinsider4across function calls - [ ] Because
volatileautomatically emitsldrex/strexatomic loops that stall onMMIOmemory - [x] Because
gpio->DR |= maskstill compiles into separateldrandstrinstructions whose window can interleave with an ISR or another writer
Answer: Because gpio->DR |= mask still compiles into separate ldr and str instructions whose window can interleave with an ISR or another writer
Why: 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.
? check 3 · Retrieval: how must a struct-based inline helper acknowledge pending interrupt mask inside the Write-One-to-Clear (W1C) ISR member?
- [ ]
gpio->ISR &= ~mask; - [x]
gpio->ISR = mask; - [ ]
gpio->ISR |= mask;
Answer: gpio->ISR = mask;
Why: 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.
1. Motivation
Freestanding C firmware crashes before main() -- or corrupts the bottom word of an adjacent stack/heap -- when _start zeroes [__bss_start, __bss_end] with an inclusive <= comparison instead of the half-open linker interval [__bss_start, __bss_end), when ALIGN(8) address rounding overflows uint32_t near 0xFFFFFFFF, or when a careless edit to a peripheral struct shifts GPIOx_ISR off byte +0x18. In this laboratory, you will diagnose an off-by-one .bss overrun inside starter/core.c, verify compile-time _Static_assert register offsets in struct gpio_model, and prove overflow-safe alignment and masked data updates under TAP version 13.
2. Learning Objectives
- Verify
32-byteGPIOperipheral struct layout (psrat+8,israt+24,sizeof == 32) at compile time using_Static_assertandoffsetof. - Round addresses upward to power-of-two boundaries in
align_address()while rejecting0, non-powers-of-two (3), and inputs exceedingUINT32_MAX - (alignment - 1U). - Repair
init_runtime()so.datarelocation (memcpy) and.bssclearing (for (size_t i = bss_begin; i < bss_end; ++i)) honor half-open intervals, reject.data/.bssoverlap, and leave surrounding sentinels untouched. - Apply arbitrary multi-bit masks cleanly in
data_update()via(old & ~mask) | (value & mask).
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m05_lds_crt_sdk/. - Target Runtime Contract: Models GNU
ldsection bounds (__data_start,__bss_start,__bss_end),ARMv7-A4/8-byte address alignment, andi.MX6ULLGPIO0x00..0x1Cregister offsets.
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0physical target hardware required forTAPverification).
5. Complete Executable Commands
Run the commands below from labs/lab_m05_lds_crt_sdk/ to reproduce starter/ failing check 3, catch starter/'s out-of-bounds write with AddressSanitizer (ASan), build files/libbsp.a, and verify 5/5 TAP checks:
learner@ksa:~/gl-e01/m05-l03$ bat script.sh File: script.sh # 1. Run check.sh against starter/ in a disposable temp folder to observe check 3 fail (# pass 4/5) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Compile starter/ with AddressSanitizer (-fsanitize=address) on cases 2 and 3 to expose both OOB bugs TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -fsanitize=address -g -Istarter tests.c starter/core.c -o "$TMP/crt" && { "$TMP/crt" 2 || echo "case 2 sentinel clobbered (rc=$?)"; "$TMP/crt" 3 || echo "case 3 ASan stack-buffer-overflow (rc=$?)"; } ; rm -rf "$TMP" # 3. Build files/libbsp.a and verify exported C-runtime and SDK symbols make -B -C files nm -g --defined-only files/libbsp.a # 4. Execute the authoritative 5-check TAP version 13 harness sh check.sh*Why each step runs:* Step 1 reproduces not ok 3 without touching files/; Step 2 reveals a critical bonus insight -- under -fsanitize=address, starter/ not only clobbers ram[40] in case 2 (rc=134) but also commits a 1-byte stack buffer overflow (ram[64] = 0U on unsigned char ram[64]) in case 3 (init_runtime(ram, 64U, data, 0U, 64U, 64U, 64U))!; Step 3 builds files/libbsp.a; and Step 4 confirms # pass 5/5.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
struct gpio_model(core.h:6,tests.c:5-7): Declares eightuint32_tregisters (dr,gdir,psr,icr1,icr2,imr,isr,edge);tests.cenforcesoffsetof(psr) == 8U,offsetof(isr) == 24U, andsizeof == 32Uat compile time beforemain()even links.align_address(core.c:3-9): Rejectsalignment == 0U || (alignment & (alignment - 1U)) != 0U, checksvalue > UINT32_MAX - add(add = alignment - 1U) soUINT32_MAXaligned to8Ufails without overwriting*out = 0x55U, and computes(value + add) & ~add.- Seeded Flaw in
starter/core.c:17(init_runtime):starterloopsfor (size_t i = bss_begin; i <= bss_end; ++i) ram[i] = 0U;. In GNUldscripts (.bss : { __bss_start = .; *(.bss*) __bss_end = .; }),__bss_endis the first byte after.bss: when.bssis[24, 40),ram[40]belongs to the next section (or lies1byte pastram[63]whenbss_begin == bss_end == 64!). - Verified Repair in
files/core.c:10-19: Validates bounds (data_at <= size,data_size <= size - data_at,bss_begin <= bss_end <= size), rejects non-empty.dataoverlapping non-empty.bss(data_at < bss_end && bss_begin < data_at + data_size), guardsif (data_size != 0U) memcpy(...), and zeroes strictlyfor (size_t i = bss_begin; i < bss_end; ++i).
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m05-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 4/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - aligns valid addresses and rejects overflow or non-power-of-two requests not ok 3 - copies data and clears only the exclusive BSS interval --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 2; inspect tests.c for the exact input and expected result' ... ok 4 - handles empty ranges and rejects invalid geometry without modification ok 5 - proves GPIO offsets and preserves neighboring output bits # pass 4/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - aligns valid addresses and rejects overflow or non-power-of-two requests ok 3 - copies data and clears only the exclusive BSS interval ok 4 - handles empty ranges and rejects invalid geometry without modification ok 5 - proves GPIO offsets and preserves neighboring output bits # pass 5/58. Explanation of Observed Behavior
In tests.c case 2, ram[0..63] is filled with sentinel 0xa5U, 4 bytes of .data ({1, 2, 3, 4}) are copied into ram[8..11], and .bss spans [24, 40) (16 bytes: indices 24..39). Because starter/core.c uses i <= bss_end, iteration i = 40U writes 0U into ram[40], tripping assert(... && ram[40] == 0xa5U) at tests.c:23 (not ok 3). Even more subtly, without ASan, tests.c case 3 appeared to pass (ok 4) on starter/ only because ram[64] = 0U overwrote unasserted stack padding outside ram[0..63]! Repairing i < bss_end eliminates both the sentinel overwrite and the latent undefined behavior (# pass 5/5, ASan-clean).
9. Experiment Variations
- Unchecked
memcpyon Zero-Length.dataat End of RAM: Passdata = NULL, data_size = 0Uin a scratch test after removingif (data_size != 0U)beforememcpy(ram + data_at, data, data_size)under-fsanitize=undefined: ISO C11 Section 7.24.1p2 forbidsNULLpointers inmemcpyeven when the byte count is zero! - Struct Member Insertion Caught at Compile Time: Insert
uint32_t pad;betweenpsrandicr1in a scratch copy ofcore.hand runsh check.sh: check1fails immediately at compile time on_Static_assert(offsetof(struct gpio_model, isr) == 24U, "ISR"). - Unmasked
valueindata_update(): Rewritedata_update()as(old & ~mask) | valueand runverify 4:data_update(0U, 0x80000000U, 0xffffffffU)returns0xffffffffUinstead of0x80000000U.
10. Performance Measurements
Measured on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed iterations):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Startup Cost |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 143.25 ms | 157.56 ms | 165.52 ms | Host compile + archive + test execution |
verify 4-case runtime/SDK suite (verify 1..4) | 3524.5 us | 4305.9 us | 4863.4 us | < 2 us in-memory .data/.bss simulation |
Zeroing 64 KiB .bss (16,384 32-bit STR words) | ~4 us (L1/L2) | ~7 us | ~9 us | ~95 - 180 us in OCRAM/DDR3 before I/D caches enable |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 3 (ram[40] is 0U instead of 0xa5U) | .bss loop used inclusive i <= bss_end | Loop over half-open for (size_t i = bss_begin; i < bss_end; ++i) | ||
not ok 2 (align_address(1U, 3U, &out) returns true) | Missing power-of-two bit test (alignment & (alignment - 1U)) == 0U | Reject `alignment == 0U \ | \ | (alignment & (alignment - 1U)) != 0U` |
not ok 2 (align_address(UINT32_MAX, 8U, &out) wraps to 0U) | Computed (value + add) & ~add before checking value > UINT32_MAX - add | Guard if (value > UINT32_MAX - add) return false; before modifying *out | ||
not ok 4 (data and bss overlap accepted when data_size > 0) | Omitted half-open interval intersection test [data_at, data_end) vs [bss_begin, bss_end) | Reject when data_size != 0U && bss_begin < bss_end && data_at < bss_end && bss_begin < data_at + data_size |
12. Guided Questions
- Why does
(alignment & (alignment - 1U)) == 0U(combined withalignment != 0U) identify powers of two across all32-bit unsigned integers inO(1)time?
- *Hint 1:* Write the binary representation of
2^k(0b001000) and2^k - 1(0b000111). - *Hint 2:* What happens to the highest set bit of any composite number
n = 2^k + m(0 < m < 2^k, e.g.,6 = 0b0110,5 = 0b0101) when bitwise-ANDed withn - 1?
- Why does an
ARMv7-A_startassembly loop (cmp r0, r1/blo 1bwithstr r2, [r0], #4) require. = ALIGN(4);on both__bss_startand__bss_endin the linker script?
- *Hint 1:* Suppose
.bssends with a singlechar flag;so__bss_end - __bss_start == 5bytes (__bss_end = 0x87810005). - *Hint 2:* Trace
r0stepping by+4(0x87810000 -> 0x87810004 -> 0x87810008) underblo: how many bytes past0x87810005get zeroed on the second4-byteSTR?
13. Independent Challenges
- Near Transfer — Word-Wide
init_runtime_aligned32(): Write a stricter startup verifier requiringdata_at,data_size,bss_begin, andbss_endto be multiples of4U(just like a4-byteLDR/STR_startloop), performing4-byte chunk operations and rejecting unaligned linker symbols cleanly. - Far Transfer — Full
.text+.rodata+.data(LMA != VMA) +.bss+IRQ/SVCStack Solver: Implementbool solve_lds_layout(...)that computes_etext,__data_load(LMA),__data_start.._edata(VMA),[__bss_start, __bss_end), and8-byte-alignedIRQ/SVCstack tops inside[ram_base, ram_base + ram_size), rejecting stack-into-.bsscollisions.
14. Solutions & Explanations
- Guided Question 1: An exact power of two has a single
1bit (2^k), and subtracting1clears bitkand sets bits0..k-1, yielding zero bit overlap (& == 0); any number with two or more1bits retains its most-significant1bit inn - 1, son & (n - 1)is non-zero. - Guided Question 2: Stepping
4bytes perSTRwhiler0 < __bss_endwhen__bss_endis unaligned (+5) executes at+0and+4, writing bytes+4..+7(3bytes past__bss_end!); aligning__bss_end = ALIGN(4)reserves those3tail padding bytes explicitly inside.bss. - Challenge 1 Alignment Check: Guard
if (((data_at | data_size | bss_begin | bss_end) & 3U) != 0U) return false;before delegating to the bounds and overlap checks.
Run locally in your terminal and check off each verification milestone.
Not started
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.
- 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.
Step sequence — frame strip: steps_m05_l03
Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
reveals: step1
highlights: step1
Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.
reveals: step2
highlights: step2
Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.
reveals: step3
highlights: step3
Step 4: Wrap board pin and active-low policy behind a narrow API tracked by GCC -MMD -MP dependencies.
reveals: step4
highlights: step4
m06/
Modular BSP, transistor-switched buzzer, and polled key capstone
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.
Why Moving Files Into Folders Is Not Modularity Without a Header Firewall
Once a bare-metal codebase grows beyond start.S and one main.c into clock gating, status LEDs, buzzers, keys, UARTs, and timers, two failure modes hit almost every team simultaneously. First, engineers split .c files into neat bsp/clk/, bsp/led/, and project/ folders—but create a single giant "bsp_all.h" included everywhere, leaking 0x0209C000, IOMUXC hex constants, and active-low inversions straight into main.c! Second, an engineer edits a register offset or polarity macro inside a .h file, runs make, flashes bsp.bin, and wastes two hours debugging hardware because make saw no .c timestamp change and silently linked yesterday's stale .o file!
Study Figure 6.1a to see how a real production Board Support Package (BSP) establishes both architectural information hiding and minimal incremental rebuild blast radius:
- Layer 1 — Pure Silicon Register Definitions (
include/soc_regs.h): Owns immutablei.MX6ULLbase addresses and_Static_assert-verified overlays (struct bsp_ccm_regswith_pad0[26]placingCCGR[0..6]at exact offsets+0x68..+0x80,sizeof == 0x84 = 132 B). Zero board pin numbers live here! - Layer 2 — Narrow Subsystem Modules (
bsp/clk/,bsp/led/,bsp/delay/): Each subsystem.cfile includessoc_regs.hprivately and owns one hardware domain (clk.cownsCCM_CCGR0..6;led.c+led_board.hownGPIO1_IO03muxing and active-low inversion;delay.cowns timing). Their public headers (led.h,delay.h) expose only logical actions (void led_set(bool on);)—nevervolatileregister structs! - Layer 3 — Application Policy (
project/start.S,project/main.c): Includes onlyled.handdelay.h. Consequently, asbsp_header_dep_audit.cproves, editinginclude/soc_regs.hrebuildsclk.oandled.o(0x13withbsp.elf) while leavingproject/main.ocompletely untouched!
Figure 6.1a. Three-layer bare-metal BSP header firewall — main.c never sees soc_regs.h, bounding both coupling and incremental rebuilds.
mental model: 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.
definition (Modular BSP Ownership & GCC -MMD -MP Dependency Generation): 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.
Step through the four-stage ownership and dependency loop below:
- Step 1. Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw literals.
- Step 2. Step 2: Encapsulate CCGR gates, pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.
- Step 3. Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.
- Step 4. Step 4: Compile with -MMD -MP and load -include $(OBJ:.o=.d) so header edits rebuild exact consumer .o files.
Figure 6.1b. Pair narrow subsystem headers with path-preserving obj/%.o rules and -include $(OBJ:.o=.d) so neither object collisions nor stale headers can survive.
Path-Preserving Object Rules, Phony Header Guards & ABI Consistency
Inspect Figure 6.1b alongside Makefile (target_m06_l01) below to see three subtle Makefile bugs prevented by 15 clean lines:
- Preventing basename collisions (
obj/init.o): Many tutorials flatten objects withOBJ := $(addprefix obj/,$(notdir $(SRC:.c=.o))). The moment bothbsp/clk/init.candbsp/led/init.cexist, both map toobj/init.o—silently overwriting one module at build time! Using$(patsubst %.c,obj/%.o,$(SRC))with@mkdir -p $(dir $@)insideobj/%.o: %.cpreserves a 1-to-1 bijection (obj/bsp/clk/init.o != obj/bsp/led/init.o). - Why
-MMDneeds BOTH-MPand-include: Generating.dfiles without-include $(OBJ:.o=.d)does nothing at all! Leading-in-includetells Make not to fail on a clean checkout before.dfiles exist. Once.dfiles exist, if you refactor and deleteled_board.h, Make seesobj/bsp/led/led.o: ... bsp/led/led_board.hin the old.dfile and aborts withNo rule to make target 'bsp/led/led_board.h'unless-MPemitted the empty phony targetbsp/led/led_board.h:! - Linker script & unified freestanding
EABIflags: Noticebsp.elf: $(OBJ) bsp.lds—makingbsp.ldsa prerequisite forces a relink wheneverVMA/LMAaddresses change—and notice-ffreestanding -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=softshared across every.cand.Srule even when invoking anarm-linux-gnueabihf-toolchain prefix, preventing accidental VFP register usage beforeCPACRenables the FPU!
Figure 6.1b. Path-mirroring pattern rules prevent basename collisions (left), while -MMD -MP plus -include closes the incremental header rebuild DAG (right).
| Makefile / Header Pattern | Header Edit Behavior | Header Rename / Delete | Engineering Verdict |
|---|---|---|---|
-MMD -MP + -include $(OBJ:.o=.d) | Rebuilds exact consumer .o set + bsp.elf | Survives cleanly via empty phony hdr.h: rule | Production GNU Make standard |
-MMD without -MP | Rebuilds exact consumer .o set | Fails with No rule to make target deleted.h | Breaks refactoring without make clean |
%.o: %.c with no .d include | Rebuilds 0 objects on .h edits! | Links stale struct offsets/macros into bsp.bin | Dangerous silent build corruption |
Flattened obj/$(notdir).o | Collides whenever two folders have init.c | Overwrites .o / .d files unpredictably | Broken on multi-subsystem BSPs |
learner@ksa:~/gl-e01/m06-l01$ bat -H 4 -H 5 -H 8 -H 10 -H 11 -H 12 -H 16 -H 20 Makefile File: Makefile CROSS_COMPILE ?= arm-linux-gnueabihf- CC := $(CROSS_COMPILE)gcc OBJCOPY := $(CROSS_COMPILE)objcopy CFLAGS := -std=c11 -Wall -Wextra -Werror -O2 -ffreestanding \ -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=soft -MMD -MP CPPFLAGS := -Iinclude -Ibsp/clk -Ibsp/led -Ibsp/delay SRC := project/main.c bsp/clk/clk.c bsp/led/led.c bsp/delay/delay.c OBJ := $(patsubst %.c,obj/%.o,$(SRC)) obj/project/start.o all: bsp.bin obj/%.o: %.c @mkdir -p $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ obj/%.o: %.S @mkdir -p $(dir $@) $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@ bsp.elf: $(OBJ) bsp.lds $(CC) -nostdlib -Wl,-T,bsp.lds,-Map,bsp.map $(OBJ) -o $@ bsp.bin: bsp.elf $(OBJCOPY) -O binary $< $@ -include $(OBJ:.o=.d) .PHONY: all- Enforce one freestanding Cortex-A7 soft-float ABI across all objects and emit .d files with -MMD -MP.
- Mirror source paths under obj/ and create parent directories on demand via $(dir $@).
- Declare bsp.lds as an explicit prerequisite of bsp.elf so layout edits force a relink.
- Splice generated .d files into Make's DAG, tolerating missing .d files on the initial clean build.
Auditing CCM Sparse Struct Offsets & DAG Invalidation Closure in C11
In bsp_header_dep_audit.c below, we prove two properties side by side: first, _Static_assert verifies struct bsp_ccm_regs (26 reserved uint32_t words = 0x68 bytes ahead of CCGR[7], placing CCGR[0] at +0x68, CCGR[1] at +0x6C, CCGR[6] at +0x80, and sizeof == 0x84 = 132 B); second, invalid_targets(changed) computes the exact bitmask of invalidated targets when soc_regs.h (0x13 = clk.o | led.o | bsp.elf), led_board.h (0x12 = led.o | bsp.elf), led.h (0x1A = led.o | main.o | bsp.elf), or bsp.lds (0x10 = bsp.elf only) is modified!
learner@ksa:~/gl-e01/m06-l01$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 bsp_header_dep_audit.c File: bsp_header_dep_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> struct bsp_ccm_regs { volatile uint32_t _pad0[26]; /* 0x00..0x64 */ volatile uint32_t CCGR[7]; /* 0x68..0x80 */ }; _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[0]) == 0x68U, "CCGR0"); _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[1]) == 0x6cU, "CCGR1"); _Static_assert(offsetof(struct bsp_ccm_regs, CCGR[6]) == 0x80U, "CCGR6"); _Static_assert(sizeof(struct bsp_ccm_regs) == 0x84U, "CCM span"); enum inputs { IN_SOC_REGS = 1U, IN_LED_BRD = 2U, IN_LED_API = 4U, IN_DELAY_API = 8U, IN_LDS = 16U }; enum targets { T_CLK_O = 1U, T_LED_O = 2U, T_DLY_O = 4U, T_MAIN_O = 8U, T_ELF = 16U }; static unsigned invalid_targets(unsigned changed) { const unsigned obj_deps[4] = { IN_SOC_REGS, /* obj/bsp/clk/clk.o */ IN_SOC_REGS | IN_LED_BRD | IN_LED_API, /* obj/bsp/led/led.o */ IN_DELAY_API, /* obj/bsp/delay/delay.o */ IN_LED_API | IN_DELAY_API /* obj/project/main.o */ }; unsigned out = 0U; for (size_t i = 0U; i < 4U; ++i) if ((obj_deps[i] & changed) != 0U) out |= (1U << i); if (out != 0U || (changed & IN_LDS) != 0U) out |= T_ELF; return out; } int main(void) { assert(invalid_targets(0U) == 0U); assert(invalid_targets(IN_SOC_REGS) == (T_CLK_O | T_LED_O | T_ELF)); assert(invalid_targets(IN_LED_BRD) == (T_LED_O | T_ELF)); assert(invalid_targets(IN_LED_API) == (T_LED_O | T_MAIN_O | T_ELF)); assert(invalid_targets(IN_LDS) == T_ELF); assert(strcmp("obj/bsp/clk/init.o", "obj/bsp/led/init.o") != 0); printf("CCM_span=%zuB CCGR1=+0x%02zX soc_chg=0x%02X brd_chg=0x%02X lds_chg=0x%02X\n", sizeof(struct bsp_ccm_regs), offsetof(struct bsp_ccm_regs, CCGR[1]), invalid_targets(IN_SOC_REGS), invalid_targets(IN_LED_BRD), invalid_targets(IN_LDS)); return 0; }- Verify sparse CCM CCGR0..CCGR6 (+0x68..+0x80) and GPIO (+0x00..+0x1C) BSP header offsets at compile time.
- Keep project/main.o decoupled from include/soc_regs.h so silicon-header edits rebuild only BSP driver objects.
- Propagate any rebuilt .o or modified bsp.lds prerequisite into a relink of bsp.elf (bit 4).
Compiling with -MMD -MP & Verifying Incremental Invalidation Masks
Compile bsp_header_dep_audit.c with -MMD -MP and execute the audit binary below. Confirm CCM_span=132B, CCGR1=+0x6C, soc_chg=0x13, brd_chg=0x12, and lds_chg=0x10.
learner@ksa:~/gl-e01/m06-l01gcc -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-l01learner@ksa:~/gl-e01/m06-l01strace -e trace=write,exit_group \./bsp_header_dep_auditwrite(1, "CCM_span=132B CCGR1=+0x6C soc_ch"..., 65) = 65exit_group(0) = ?+++ exited with 0 +++Tracking Compiler Flag Changes Alongside Header Dependencies
One subtle detail separates good Makefiles from airtight ones: .d files track .c and .h timestamps, not edits to CFLAGS inside Makefile! If you switch -mfloat-abi=hard to -mfloat-abi=soft inside Makefile without running make clean, existing obj/*.o files appear "up to date" and fail at link time with a VFP ABI mismatch. Listing Makefile as a second prerequisite on pattern rules (obj/%.o: %.c Makefile, keeping $< bound to the first prerequisite %.c!) automatically invalidates all objects whenever compiler flags change. Later: Lesson m06-l02 adds a new actuator subsystem (bsp/buzzer/) to this modular BSP, deriving PNP vs NPN transistor switching circuits and SNVS GPIO5 clock gating from first principles.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Tracing a Deleted Header & Linker-Script Edit
Walk through two incremental build scenarios. Step 1 (Deleted Header): Suppose obj/bsp/led/led.d lists bsp/led/old_pins.h without -MP and you merge old_pins.h into led_board.h and delete old_pins.h: Make aborts with No rule to make target 'bsp/led/old_pins.h', whereas -MP's empty bsp/led/old_pins.h: rule lets led.o recompile and regenerate a clean led.d. Step 2 (Linker Edit): Touching bsp.lds alone triggers bsp.elf -> bsp.bin with zero .c recompilations (lds_chg=0x10).
Independent Practice: Build-Graph Layer & Cycle Linter (build_graph_lint.c)
Extend bsp_header_dep_audit.c into build_graph_lint.c that checks an array of source paths for flattened $(notdir) collisions, flags architectural layer violations if project/* includes include/soc_regs.h directly, and detects circular #include cycles via 3-color depth-first search.
? check 1 · 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?
- [ ] Whether
CCM_CCGR1was enabled on the workstation before invokingmake - [x] Whether
-MMD -MP.ddependency generation or-include $(OBJ:.o=.d)was omitted or pointed at the wrong path - [ ] Whether
include/needs to be renamedheaders/so GNU Make scans it automatically
Answer: Whether -MMD -MP .d dependency generation or -include $(OBJ:.o=.d) was omitted or pointed at the wrong path
Why: 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.
? check 2 · 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?
- [x] So distinct subsystems (
bsp/clk/init.candbsp/led/init.c) can share file basenames without colliding onobj/init.o - [ ] Because the
ARMv7-AAAPCSprocedure-call standard embeds directory names insideBLinstructions - [ ] Because
objcopy -O binarysorts sections alphabetically byobj/subfolder depth
Answer: So distinct subsystems (bsp/clk/init.c and bsp/led/init.c) can share file basenames without colliding on obj/init.o
Why: 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.
? check 3 · 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?
- [ ] Passing
-Wl,-T,bsp.ldscausesgccto ignorebsp.ldsunless Make exports$^ - [ ] Changing
bsp.ldsrequires recompiling every.cfile to regenerate.dheader rules - [x] Make inspects the prerequisite list (not recipe flags!) to decide whether
bsp.elfis older thanbsp.ldsand must be relinked
Answer: Make inspects the prerequisite list (not recipe flags!) to decide whether bsp.elf is older than bsp.lds and must be relinked
Why: 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.
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.- 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 that depends on that placement policy.
Step sequence — frame strip: steps_m06_l01
Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw MMIO literals.
reveals: step1
highlights: step1
Step 2: Encapsulate CCGR gates, IOMUXC pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.
reveals: step2
highlights: step2
Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.
reveals: step3
highlights: step3
Step 4: Compile with -MMD -MP and load -include $(OBJ:.o=.d) so header edits rebuild exact consumer .o files.
reveals: step4
highlights: step4
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.
Why Buzzers Use Transistor Stages & How BJT Topologies Set Polarity
Why not wire a 30 mA magnetic or piezoelectric buzzer directly between an i.MX6ULL GPIO pin and ground like a 2 mA status LED? First, pulling 30..50 mA directly through a CMOS output pad sags the local NVCC I/O rail, overheats microscopic bond wires, and risks inductive flyback spikes damaging the pad's output MOSFETs. Second, distinguish the acoustic transducer type on your schematic before writing a single line of code: an active buzzer houses an internal oscillator IC and sounds continuously from a steady DC supply (3.3 V or 5.0 V), whereas a passive sounder is a bare voice-coil or piezo diaphragm that requires an alternating 2..4 kHz PWM square wave (applying steady DC to a passive magnetic sounder produces only one faint click while burning continuous I^2 * R heat!).
Trace all three BJT switching circuits in Figure 6.2a from emitter to collector to derive software polarity from first-principles junction physics rather than memorizing rules of thumb:
- Panel A —
3.3 VPNPHigh-Side Switch (SNVS_TAMPER1 / GPIO5_IO01, Active-Low): ThePNPemitter sits onVCC = 3.3 V. WhenGPIO5_IO01drives0 V(Low),V_EB ~= 0.7 Vforward-biases the emitter-base junction, sinkingI_B = (3.3 V - 0.7 V - 0.1 V) / 1.5 kOhm = 1.67 mAthroughR_Band saturating the transistor soI_C = 30 mAflows into the buzzer (ON)! WhenGPIO5_IO01drives3.3 V(High),V_EB = 3.3 V - 3.3 V = 0 Vcuts the transistor OFF. - Panel B —
5.0 VNPNLow-Side Switch (Active-High): TheNPNemitter sits atGNDbelow a5.0 Vload. DrivingGPIO = 3.3 VsourcesI_B = (3.15 V - 0.75 V) / 1.0 kOhm = 2.4 mA(V_BE ~= 0.75 V), saturating the collector to sink40 mA(ON), whileGPIO = 0 VgivesV_BE = 0 V(OFF)—cleanly switching a5 Vload from a3.3 V! Notice, however, that both circuits share a conductive ground/rail with the SoC: a transistor switch is current amplification, NEVER galvanic isolation! - Panel C — The Classic
5.0 VPNPHardware Trap: If someone wires aPNPemitter to5.0 Vand drivesR_Bdirectly from a3.3 VGPIO, writingGPIO = 1(3.3 V) leavesV_EB = 5.0 V - 3.3 V = 1.7 V > 0.7 V—the buzzer never turns off and5 Vback-feeds current into the SoC's3.3 VESD clamp diode!
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).
mental model: 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!
definition (Active vs Passive Sounders, BJT Polarity & Shared-Bank Ownership): 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.
Step through the four-stage actuator control path from logical request to collector current below:
- Step 1. Step 1: Application calls buzzer_set(true/false) with zero knowledge of PNP or NPN inversion.
- Step 2. Step 2: maps circuit topology via drive_high = (asserted != active_low) and preloads inactive DR before GDIR.
- Step 3. Step 3: Guard CCGR1[31:30] != 0, dr != NULL, and pin < 32U before forming UINT32_C(1) << pin.
- Step 4. Step 4: Base resistor R_B limits GPIO pad current to 1.67 mA while the saturated BJT switches 30 mA.
Figure 6.2b. Expose logical buzzer_set(enabled) to application code, preload inactive DR before GDIR, and validate pin < 32 before shifting.
CCM_CCGR1 2-Bit Clock Gates, IOMUXC_SNVS & Chirp-Free Startup
Inspect Figure 6.2b to wire up the complete i.MX6ULL hardware path for an active buzzer on SNVS_TAMPER1 (GPIO5_IO01). Notice two silicon-specific details that trip up engineers accustomed to GPIO1:
CCM_CCGR1(0x020C406C)2-bit clock-gate slots: EachCCGR0..CCGR6register packs16two-bitCGfields (shift = cg_slot * 2):00= gated off,01= run mode only,10= reserved (do not write!), and11= enabled in run + wait (wfi) modes.GPIO5sits inCCGR1slotCG15(bits [31:30])! UpdatingCCGR1with(ccgr1 & ~(3U << 30)) | (3U << 30)turns onGPIO5(0x020AC000) while preservingCG0..CG14(such asGPIO1atCG13[27:26]).- Separate
IOMUXC_SNVSmux block (0x02290000) & chirp-freeDR-before-GDIRorder:SNVS_TAMPER0..9pads belong to the battery-backedSNVSdomain—their mux registers live at0x02290000(SW_MUX_CTL_PAD_SNVS_TAMPER1 = 0x0229000C,ALT5), not mainIOMUXC(0x020E0000)! And on an active-lowPNPstage, always setGPIO5->DR |= (1U << 1)(High = OFF) BEFORE settingGPIO5->GDIR |= (1U << 1)so the buzzer never emits an audible startup chirp!
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).
| Transducer & Switch Stage | GPIO Assert Level | Required Signal | Hardware Failure If Misconfigured | |
|---|---|---|---|---|
Active buzzer + 3.3 V PNP high-side | 0 (active_low = true) | Steady DC 0 V (DR &= ~2U) | Setting GDIR while DR == 0 causes boot chirp; 5 V rail sticks ON | |
Active buzzer + 5.0 V NPN low-side | 1 (active_low = false) | Steady DC 3.3 V (`DR \ | = 2U`) | Preloading DR = 1 chirps at boot; load positive stays live when off |
| Passive magnetic / piezo sounder | Alternating edges | 2..4 kHz PWM square wave | Steady DC level makes 1 faint click and heats magnetic coil | |
Direct GPIO drive (no transistor) | Circuit-dependent | <= 2..4 mA indicator current | 30 mA load sags NVCC, stresses pad FETs, and lacks flyback margin |
In bsp_buzzer.c below, verify how gpio_pin_write() checks dr == NULL || pin >= 32U before evaluating UINT32_C(1) << pin (since shifting a 32-bit integer by >= 32 is Undefined Behavior in ISO C11!), then applies (asserted != active_low) across all four truth-table rows cleanly.
learner@ksa:~/gl-e01/m06-l02$ bat -H 6 -H 7 -H 8 -H 9 -H 14 bsp_buzzer.c File: bsp_buzzer.c #include <stdbool.h> #include <stddef.h> #include <stdint.h> bool gpio_pin_write(volatile uint32_t *dr, unsigned pin, bool asserted, bool active_low) { if (dr == NULL || pin >= 32U) return false; uint32_t mask = UINT32_C(1) << pin; uint32_t value = *dr; /* caller serializes the shared bank */ *dr = (asserted != active_low) ? value | mask : value & ~mask; return true; } bool buzzer_set(bool enabled) { volatile uint32_t *dr = (volatile uint32_t *)(uintptr_t)0x020ac000U; return gpio_pin_write(dr, 1U, enabled, true); }- Reject NULL pointers and pin >= 32U BEFORE computing UINT32_C(1) << pin so out-of-range calls never invoke shift UB or alter *dr.
- Boolean inequality (asserted != active_low) drives 0 for active-low assertion and 1 for active-low deassertion while preserving 31 sibling bits.
- Encapsulate GPIO5_DR (0x020AC000), pin 1, and PNP active_low=true inside buzzer_set().
Verifying Selective CCGR1 Gating & Buzzer Polarity Safety in C11
In ccm_ccgr_buzzer_audit.c below, ccgr_update() rejects invalid CCGR indices (>= 7), invalid slots (>= 16), and the reserved 2-bit encoding CG_RSVD == 2U, updating CCGR1 CG15 (GPIO5) from 0x0FFFFFF0U to 0xCFFFFFF0U without disturbing CG0..CG14. Meanwhile, buzzer_pin_write() refuses to touch DR while GPIO5's clock gate is CG_OFF (00_2), proves PNP (active_low = true) and NPN (active_low = false) bit updates preserve 0xA5A5A5A5 sibling bits, exercises bit 31 (0x80000000U), and confirms pin == 32U and NULL leave dr untouched!
learner@ksa:~/gl-e01/m06-l02$ bat -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 16 -H 17 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 26 -H 27 -H 28 ccm_ccgr_buzzer_audit.c File: ccm_ccgr_buzzer_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> enum { CG_OFF = 0U, CG_RUN = 1U, CG_RSVD = 2U, CG_RUN_WAIT = 3U }; static bool ccgr_update(uint32_t ccgr[7], unsigned reg_idx, unsigned cg_slot, unsigned policy) { if (reg_idx >= 7U || cg_slot >= 16U || policy > 3U || policy == CG_RSVD) return false; unsigned shift = cg_slot * 2U; uint32_t mask = UINT32_C(3) << shift; ccgr[reg_idx] = (ccgr[reg_idx] & ~mask) | ((uint32_t)policy << shift); return true; } static bool buzzer_pin_write(const uint32_t ccgr[7], uint32_t *dr, unsigned pin, bool asserted, bool active_low) { if (dr == NULL || pin >= 32U) return false; if (((ccgr[1] >> 30) & 3U) == CG_OFF) return false; /* GPIO5 CG15 gated */ uint32_t mask = UINT32_C(1) << pin; *dr = (asserted != active_low) ? (*dr | mask) : (*dr & ~mask); return true; } int main(void) { uint32_t ccgr[7] = {0U, 0x0ffffff0U, 0U, 0U, 0U, 0U, 0U}; uint32_t dr = 0xa5a5a5a5U, old_dr = dr; assert(!buzzer_pin_write(ccgr, &dr, 1U, true, true) && dr == old_dr); assert(!ccgr_update(ccgr, 1U, 15U, CG_RSVD)); assert(ccgr_update(ccgr, 1U, 15U, CG_RUN_WAIT)); assert(ccgr[1] == 0xcffffff0U); /* CG15=11, CG0..14 preserved */ assert(buzzer_pin_write(ccgr, &dr, 1U, true, true) && dr == (old_dr & ~2U)); assert(buzzer_pin_write(ccgr, &dr, 1U, false, true) && dr == (old_dr | 2U)); assert(buzzer_pin_write(ccgr, &dr, 1U, true, false) && (dr & 2U) != 0U); assert(buzzer_pin_write(ccgr, &dr, 31U, true, false) && (dr & 0x80000000U) != 0U); old_dr = dr; assert(!buzzer_pin_write(ccgr, &dr, 32U, true, true) && dr == old_dr); assert(!buzzer_pin_write(ccgr, NULL, 1U, true, true)); printf("CCGR1=0x%08X pnp_on_bit1=%u pnp_off_bit1=%u npn_on_bit1=%u\n", ccgr[1], 0U, 1U, 1U); return 0; }- Accept only legal CCGR 2-bit policies (0, 1, and 3) across CCGR0..CCGR6 and preserve the other 15 CG slots.
- Refuse GPIO5_DR writes while GPIO5's CCGR1[31:30] gate is 00, and reject NULL or pin >= 32 before shifting.
- Translate PNP active-low (asserted != true -> 0) and NPN active-high (asserted != false -> 1) cleanly.
Running the CCGR1 & Buzzer Polarity Audit + ARMv7-A Cross-Check
Compile and run ccm_ccgr_buzzer_audit on the workstation, then cross-compile bsp_buzzer.c for freestanding Cortex-A7 with -Werror to confirm clean EABI object emission.
learner@ksa:~/gl-e01/m06-l02gcc -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-l02clang --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-l02learner@ksa:~/gl-e01/m06-l02strace -e trace=write,exit_group \./ccm_ccgr_buzzer_auditwrite(1, "CCGR1=0xCFFFFFF0 pnp_on_bit1=0 p"..., 60) = 60exit_group(0) = ?+++ exited with 0 +++Base-Current Sizing & Future Linux gpiod Descriptor Mapping
Notice how clean hardware-software co-design makes future Linux kernel migration effortless. Later in GL-E05, when Device Tree describes this exact PNP buzzer with gpios = <&gpio5 1 GPIO_ACTIVE_LOW>;, gpiod_set_value(desc, 1) performs the exact same logical-to-electrical inversion (1 -> physical 0 V) inside the kernel's gpiolib core while serializing GPIO5_DR under the bank spinlock! And in Lesson m06-l03 next, we close our GL-E01 bare-metal capstone by wiring a mechanical tactile key (GPIO1_IO18) into a nonblocking, wraparound-safe 10 ms debounce state machine that drives both bsp/led and bsp/buzzer.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Sizing an NPN Base Resistor & Glitchless Init
Compute the analog drive and register sequence for a 5.0 V, 40 mA active buzzer switched on the low side by an NPN BJT (V_BE_sat = 0.75 V, forced beta_sat = 20) from a 3.3 V GPIO (V_OH = 3.15 V). Step 1 (R_B Math): I_B_min = 40 mA / 20 = 2.0 mA, so R_B_max = (3.15 V - 0.75 V) / 2.0 mA = 1.2 kOhm (choose standard 1.0 kOhm -> 2.4 mA). Step 2 (Preload): Because NPN low-side is active-high, preload DR &= ~mask (0 V = OFF) before GDIR |= mask.
Independent Practice: Multi-Actuator Chirp-Free BSP Verifier (actuator_bsp_audit.c)
Extend ccm_ccgr_buzzer_audit.c into actuator_bsp_audit.c managing LED0 (GPIO1_IO03, active-low, CCGR1 CG13), BUZZER (GPIO5_IO01, active-low PNP, CCGR1 CG15), and RELAY (GPIO1_IO09, active-high NPN, CCGR1 CG13), proving zero active transient glitches occur during initialization and all sibling DR bits survive arbitrary toggle sequences.
? check 1 · Why is it electrically incorrect to describe a standard PNP or NPN transistor buzzer stage as providing galvanic isolation for the i.MX6ULL?
- [x] Because the SoC
GPIOand the transistor load still share direct conductive ground or supply return paths - [ ] Because bipolar transistors only amplify AC waveforms and block DC currents
- [ ] Because
GPIO5operates without aCCMclock gate
Answer: Because the SoC GPIO and the transistor load still share direct conductive ground or supply return paths
Why: 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.
? check 2 · 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?
- [ ] Bit
1 = 0(0 V), written after settingGDIR[1] = 1 - [ ] Either
0or1, because active buzzers toggle state only on rising edges - [x] Bit
1 = 1(3.3 Vinactive high,V_EB = 0 V), preloaded intoGPIO5_DRbefore settingGPIO5_GDIR[1] = 1
Answer: Bit 1 = 1 (3.3 V inactive high, V_EB = 0 V), preloaded into GPIO5_DR before setting GPIO5_GDIR[1] = 1
Why: 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.
? check 3 · Retrieval: under what concurrency condition is gpio_pin_write()'s *dr = ... read-modify-write guaranteed free from lost sibling-pin updates?
- [ ] Whenever two callers target different pin numbers (
pin 1vspin 3) on the sameGPIObank - [x] Only when the
GPIObank enjoys single-owner access or explicit serialization (such as IRQ masking / a lock) across the load-modify-store window - [ ] Whenever
dris declaredvolatile uint32_t *and compiled at-O2
Answer: Only when the GPIO bank enjoys single-owner access or explicit serialization (such as IRQ masking / a lock) across the load-modify-store window
Why: 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.
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. - 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.
Step sequence — frame strip: steps_m06_l02
Step 1: Application calls buzzer_set(true/false) with zero knowledge of PNP or NPN inversion.
reveals: step1
highlights: step1
Step 2: BSP maps circuit topology via drive_high = (asserted != active_low) and preloads inactive DR before GDIR.
reveals: step2
highlights: step2
Step 3: Guard CCGR1[31:30] != 0, dr != NULL, and pin < 32U before forming UINT32_C(1) << pin.
reveals: step3
highlights: step3
Step 4: Base resistor R_B limits GPIO pad current to 1.67 mA while the saturated BJT switches 30 mA.
reveals: step4
highlights: step4
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.
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/div: the voltage on the pin does not step cleanly from 3.3 V to 0 V once! Because elastic metal contacts collide with kinetic energy, rebound microscopically, and re-strike 3..15 times over 1..5 ms on both press and release, the pad sees a rapid burst of 3.3 V <-> 0 V square edges (contact bounce). Look at Figure 6.3a (Panel 1): enabling Schmitt-trigger hysteresis (HYS = 1) in IOMUXC cleans up slow analog RC transitions so mid-rail noise cannot oscillate, but hysteresis cannot suppress full-swing 0 V <-> 3.3 V mechanical bounces separated by milliseconds! If your loop toggles the PNP buzzer on every raw 0 V edge, a single finger press toggles the alarm four or five times at random!
Why not "fix" bounce with if (pressed) { delay_ms(10); ... } inside key_read()? At 528 MHz, spinning inside delay_ms(10) burns 5,280,000 Cortex-A7 clock cycles doing nothing—freezing UART reception, LED telemetry, and other keys on every electrical glitch, while still double-triggering if the user holds their finger down or releases with chatter! Instead, trace the synchronized waveform in Figure 6.3a (Panel 2), driven by a nonblocking three-variable Finite State Machine (candidate, stable, since_ms):
- Read
GPIO1_PSR(+0x08), neverGPIO1_DR(+0x00): On inputUART1_CTS_B(ALT5->GPIO1_IO18, pulled to3.3 Vidle and switched toGNDwhen pressed),PSRsamples the live external pad (pressed = (*psr & (1U << 18)) == 0U), whereasDRholds the unused output latch! - Qualify continuous stability (
t = 1..48 msin Figure 6.3a): Raw chatter att = 1, 3, 4keeps resettingsince_ms = 4; att = 13(13 - 4 = 9 < 10), no event fires; att = 14(14 - 4 == 10),stablecommitstrueand oneEV_PRESSfires (turningalarm_on = true)! Holding att = 19seescandidate == stable(EV_NONE); release chatter att = 20, 25, 26settles att = 36(EV_RELEASE, re-arming the button without toggling the alarm); and a second press att = 37firesEV_PRESSatt = 47(togglingalarm_on = false)!
Figure 6.3a. tactile switch input path into GPIO1_PSR[18] (top) and the exact capstone waveform turning press/release chatter into single-shot transitions (bottom).
mental model: 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.
definition (Nonblocking FSM & Modulo-2^32 Elapsed-Time Subtraction): 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!
Step through the four-stage capstone super-loop connecting GPIO1_PSR, debounce qualification, and bsp/led + bsp/buzzer below:
- Step 1. Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
- Step 2. Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.
- Step 3. Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.
- Step 4. Step 4: Toggle LED0 (GPIO1_DR[3]) and PNP buzzer (GPIO5_DR[1]) on EV_PRESS while preserving sibling bits.
Figure 6.3b. Sample PSR (never DR), separate candidate from stable state, and always subtract (uint32_t)(now - since) >= threshold.
Modulo-2^32 Tick Wraparound Proof & O(1) Poll Architecture
Study Figure 6.3b (Panel 2) carefully—it explains a classic 49.7-day uptime field bug that crashes industrial controllers. A 32-bit 1 ms tick counter (uint32_t now_ms) counts from 0x00000000 up to 0xFFFFFFFF (4,294,967,295 ms ~= 49.71 days) and then wraps cleanly back to 0x00000000 under ISO C11 unsigned modulo-2^32 arithmetic. Suppose a button bounce starts 6 milliseconds before wraparound: since = UINT32_MAX - 5 = 0xFFFFFFFA.
- Why
if (now >= since + 10U)is broken:0xFFFFFFFA + 10Uoverflows32bits and wraps to0x00000004! Just1 mslater (now = 0xFFFFFFFB),0xFFFFFFFB >= 0x00000004evaluatestrueimmediately—passing raw contact bounce straight into your application! - Why
if ((uint32_t)(now - since) >= 10U)is exact: Atnow = 0xFFFFFFFE,0xFFFFFFFE - 0xFFFFFFFA == 4U(< 10U); after wrap atnow = 0x00000003,(3U - 0xFFFFFFFAU) == 9U(< 10U); and atnow = 0x00000004,(4U - 0xFFFFFFFAU) == 10U(>= 10U, firing after the exact10-tick physical interval)!
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).
| Switch-Handling Implementation | Super-Loop CPU Cost | Bounce & UINT32_MAX Behavior | Engineering Verdict |
|---|---|---|---|
Blocking if (!psr) { delay_ms(10); ... } | Burns 5.28M cycles @ 528 MHz | Starves UART/sensors; re-fires while held! | Broken beyond toy demos |
Deadline now >= since + 10U | O(1) nonblocking (< 30 cycles) | Fails near UINT32_MAX: wrapped since + 10 fires in 1 tick! | Latent 49.7-day uptime bug |
Subtraction (uint32_t)(now - since) >= 10U | O(1) nonblocking (< 30 cycles) | Exact across UINT32_MAX; debounces press & release | Production bare-metal standard |
Reading GPIO1_DR (+0x00) instead of PSR | O(1) | Reads output latch instead of external switch pin! | Dead input bug |
In bsp_key.c below, key_poll() reads GPIO1_PSR (0x0209C008, base 0x0209C000 + 0x08) through a volatile const uint32_t * pointer, normalizes active-low bit 18, and executes the exact O(1) three-branch FSM.
learner@ksa:~/gl-e01/m06-l03$ bat -H 8 -H 9 -H 10 -H 16 -H 17 -H 18 bsp_key.c File: bsp_key.c #include <stdbool.h> #include <stdint.h> enum key_event { KEY_NONE, KEY_PRESS, KEY_RELEASE }; struct key_filter { bool candidate, stable; uint32_t since; }; enum key_event key_poll(struct key_filter *f, uint32_t now_ms) { volatile const uint32_t *psr = (volatile const uint32_t *)(uintptr_t)0x0209c008U; bool pressed = (*psr & (UINT32_C(1) << 18)) == 0U; if (pressed != f->candidate) { f->candidate = pressed; f->since = now_ms; return KEY_NONE; } if (f->candidate != f->stable && (uint32_t)(now_ms - f->since) >= 10U) { f->stable = f->candidate; return f->stable ? KEY_PRESS : KEY_RELEASE; } return KEY_NONE; } /* Initialize candidate and stable from a known startup policy before polling. */- Sample GPIO1_PSR at 0x0209C008 (+0x08, never DR at +0x00!) and normalize active-low bit 18 (0V -> pressed = true).
- Subtract (uint32_t)(now_ms - f->since) >= 10U and update f->stable once so held keys emit zero duplicate events.
Proving End-to-End Capstone Integration & Wraparound Safety in C11
debounce_fsm_capstone.c wires together every concept from GL-E01 into one deterministic host testbench: psr_key_pressed() normalizes GPIO1_PSR[18], debounce_step() filters press chatter (t = 1, 3, 4 -> EV_PRESS @ 14), suppresses steady holds (t = 19 -> EV_NONE), filters release chatter (t = 20, 25, 26 -> EV_RELEASE @ 36), accepts a second press (t = 37 -> EV_PRESS @ 47), and proves UINT32_MAX - 5U -> 4U wraparound, while bsp_poll_cycle() toggles active-low LED0 (GPIO1_DR bit 3) and PNP buzzer (GPIO5_DR bit 1) without disturbing any of the 31 sibling bits in 0xA5A5A5AD or 0x5A5A5A57!
learner@ksa:~/gl-e01/m06-l03$ bat -H 10 -H 11 -H 12 -H 13 -H 15 -H 16 -H 17 -H 18 -H 19 -H 20 -H 21 -H 22 -H 23 -H 24 -H 25 -H 27 -H 28 -H 29 -H 30 -H 31 -H 32 -H 33 -H 34 -H 35 -H 36 -H 37 debounce_fsm_capstone.c File: debounce_fsm_capstone.c #include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> enum key_ev { EV_NONE = 0, EV_PRESS = 1, EV_RELEASE = 2 }; struct deb_fsm { bool candidate, stable; uint32_t since_ms; }; static bool psr_key_pressed(uint32_t gpio1_psr) { return (gpio1_psr & (UINT32_C(1) << 18)) == 0U; } static enum key_ev debounce_step(struct deb_fsm *f, bool pressed, uint32_t now) { if (pressed != f->candidate) { f->candidate = pressed; f->since_ms = now; return EV_NONE; } if (f->candidate != f->stable && (uint32_t)(now - f->since_ms) >= 10U) { f->stable = f->candidate; return f->stable ? EV_PRESS : EV_RELEASE; } return EV_NONE; } static enum key_ev bsp_poll_cycle(struct deb_fsm *f, uint32_t psr, uint32_t now, bool *alarm_on, uint32_t *gpio1_dr, uint32_t *gpio5_dr) { enum key_ev ev = debounce_step(f, psr_key_pressed(psr), now); if (ev == EV_PRESS) *alarm_on = !*alarm_on; *gpio1_dr = *alarm_on ? (*gpio1_dr & ~8U) : (*gpio1_dr | 8U); *gpio5_dr = *alarm_on ? (*gpio5_dr & ~2U) : (*gpio5_dr | 2U); return ev; } int main(void) { const uint32_t HI = UINT32_C(1) << 18, LO = 0U; struct deb_fsm f = {false, false, 0U}; bool alarm = false; uint32_t dr1 = 0xa5a5a5adU, dr5 = 0x5a5a5a57U; assert(bsp_poll_cycle(&f, LO, 1U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, HI, 3U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, LO, 4U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, LO, 13U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, LO, 14U, &alarm, &dr1, &dr5) == EV_PRESS && alarm); assert((dr1 & 8U) == 0U && (dr5 & 2U) == 0U && (dr1 & ~8U) == 0xa5a5a5a5U); assert(bsp_poll_cycle(&f, LO, 19U, &alarm, &dr1, &dr5) == EV_NONE && alarm); assert(bsp_poll_cycle(&f, HI, 20U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, LO, 25U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, HI, 26U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, HI, 36U, &alarm, &dr1, &dr5) == EV_RELEASE && alarm); assert(bsp_poll_cycle(&f, LO, 37U, &alarm, &dr1, &dr5) == EV_NONE); assert(bsp_poll_cycle(&f, LO, 47U, &alarm, &dr1, &dr5) == EV_PRESS && !alarm); struct deb_fsm w = {false, false, 0U}; assert(debounce_step(&w, true, UINT32_MAX - 5U) == EV_NONE); assert(debounce_step(&w, true, UINT32_MAX - 1U) == EV_NONE); assert(debounce_step(&w, true, 3U) == EV_NONE); assert(debounce_step(&w, true, 4U) == EV_PRESS); printf("press@14 release@36 press@47 wrap@4 dr1_off=0x%08X dr5_off=0x%08X\n", dr1, dr5); return 0; }- Normalize active-low GPIO1_PSR bit 18 ((psr & (1U << 18)) == 0U) into logical pressed.
- Use unsigned subtraction (uint32_t)(now - f->since) >= 10U so 32-bit tick wrap across UINT32_MAX never triggers early.
- Toggle logical alarm state once per EV_PRESS and update active-low GPIO1_DR/GPIO5_DR while preserving sibling bits.
Running the Capstone Verifier & Freestanding Cortex-A7 Object Check
Compile and execute debounce_fsm_capstone.c on the workstation, then cross-compile bsp_key.c for freestanding ARMv7-A (target.o) under -Werror.
learner@ksa:~/gl-e01/m06-l03gcc -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-l03clang --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-l03learner@ksa:~/gl-e01/m06-l03strace -e trace=write,exit_group \./debounce_fsm_capstonewrite(1, "press@14 release@36 press@47 wra"..., 74) = 74exit_group(0) = ?+++ exited with 0 +++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-A AAPCS / CPSR modes (m01–m02), CCM gates, IOMUXC pad cells, and GPIO DR/GDIR/PSR/W1C ISR silicon (m03), POR_B boot straps, OCRAM, IVT/Boot Data coordinates, and big-endian DCD .imx packing (m04), start.S, bsp.lds VMA/LMA relocation, and _Static_assert MMIO structs (m05), and now a modular -MMD -MP BSP coordinating transistor actuators and wraparound-safe debounced inputs (m06)! Later: Course GL-E02 (imx6ull-baremetal-peripherals) supplies hardware now_ms ticks from EPIT/GPT timers, retunes ARM PLL1 to 528 MHz, routes GICv2 interrupts, trains external DDR3 (MMDC), and drives UART1, LCD, I2C, and SPI peripherals on bare silicon.
Common Production Pitfalls
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.
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.
Practice & Retrieval
Guided Practice: Hand-Tracing Release Chatter & Modulo Subtraction
Trace debounce_step() starting from accepted pressed state {candidate = true, stable = true, since_ms = 14}. Step 1 (Chatter Reset): Poll (false, 50) -> candidate = false, since_ms = 50; bounce (true, 56) -> candidate = true, since_ms = 56; settle (false, 58) -> candidate = false, since_ms = 58; at t = 67 (67 - 58 = 9 < 10) -> EV_NONE; at t = 68 (68 - 58 == 10) -> EV_RELEASE. Step 2 (Wrap Check): Evaluate (uint32_t)(2U - 0xFFFFFFF9U) -> 2 + 7 = 9U (< 10U).
Independent Practice: Short-Tap vs 500 ms Long-Hold BSP Controller
Extend debounce_fsm_capstone.c into key_short_long_bsp.c adding EV_LONG_HOLD (emitted once per press when stable == true persists for (uint32_t)(now - accepted_at) >= 500U) and EV_TAP_RELEASE (emitted on EV_RELEASE only if EV_LONG_HOLD did not fire during that press), wiring taps to toggle LED0 (GPIO1_IO03) and long holds to assert the PNP buzzer (GPIO5_IO01).
? check 1 · 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?
- [ ]
EV_PRESS, because counting ticks4through13inclusively spans ten labels - [ ]
EV_RELEASE, because13 < 14resetsf->candidateback tofalse - [x]
EV_NONE, because(uint32_t)(13U - 4U) == 9U < 10U(9elapsed ticks, firing atnow = 14)
Answer: EV_NONE, because (uint32_t)(13U - 4U) == 9U < 10U (9 elapsed ticks, firing at now = 14)
Why: 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).
? check 2 · 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?
- [ ] Reading
GPIO1_PSRautomatically clears the pad voltage latch until the next reset - [x] Accepting the press sets
f->stable = f->candidate(true == true), sof->candidate != f->stablestaysfalseuntil an accepted release resetsf->stable = false - [ ]
key_poll()disablesCCM_CCGR1after eachKEY_PRESS
Answer: Accepting the press sets f->stable = f->candidate (true == true), so f->candidate != f->stable stays false until an accepted release resets f->stable = false
Why: 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.
? check 3 · Retrieval: which GPIO1 register (base 0x0209C000) must bsp_key.c read to observe the external tactile switch on GPIO1_IO18?
- [x]
GPIO1_PSR(0x0209C008), normalizing active-low bit18((*psr & (1U << 18)) == 0U) - [ ]
GPIO1_DR(0x0209C000), becauseDRmirrors external input pins wheneverGDIR[18] == 0 - [ ]
GPIO1_ISR(0x0209C018), clearing bit18with|= (1U << 18)on every poll
Answer: GPIO1_PSR (0x0209C008), normalizing active-low bit 18 ((*psr & (1U << 18)) == 0U)
Why: 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.
1. Motivation
A bare-metal tactile-button and buzzer BSP appears to work during a two-minute bench demo yet misfires in continuous operation for two classic reasons: mechanical switch contacts chatter between 0 V and 3.3 V for 1 - 5 ms on every press and release (toggling an un-debounced alarm multiple times per finger tap), and deadline comparisons written as now >= f->since + 10U overflow 32-bit millisecond ticks whenever f->since lands within 9 ticks of UINT32_MAX (49.71 days at 1 kHz or 71.58 minutes at 1 MHz), firing PRESS prematurely! In this capstone laboratory, you will repair sample_key() in starter/core.c and verify end-to-end bounce rejection, hold suppression, 32-bit counter wraparound, and sibling-safe active-low GPIO output control under TAP version 13.
2. Learning Objectives
- Reject sub-
10-tick mechanical contact bounce on both press and release transitions by resettingf->candidateandf->sincewheneverpressed != f->candidate. - Suppress repeated
PRESSevents while a button remains held (f->candidate == f->stable) and require a full10-tickRELEASEqualification before accepting the next press. - Repair
32-bit monotonic tick elapsed-time comparison using unsigned modular subtraction ((uint32_t)(now - f->since) >= 10U) acrossUINT32_MAX -> 0. - Integrate
sample_key()andoutput_write()insidebsp_step()so acceptedPRESSevents toggle active-low bit1(mask = 2U) without disturbing bits[31:2]or bit0.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64) insidelabs/lab_m06_modular_bsp_io/. - Target Hardware Alignment: Models active-low
KEY0input normalized fromGPIO1_PSR[18](0x0209C008), monotonic32-bit timer ticks (EPIT/GPT), and active-lowPNPbuzzer output onGPIO5_DR[1](0x020AC000).
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,objdump). - Hardware: Standard Linux workstation (
0physical switches, buzzers, orCortex-A7boards required for the 5-checkTAPgrader).
5. Complete Executable Commands
Execute the commands below from labs/lab_m06_modular_bsp_io/ to reproduce starter/ failing check 4 (tick wrap), inspect the exact premature PRESS at UINT32_MAX - 1U, build files/libbsp.a, and pass all 5 TAP checks:
learner@ksa:~/gl-e01/m06-l03$ bat script.sh File: script.sh # 1. Stage starter/ in a temporary directory and run check.sh to observe check 4 fail (# pass 4/5) TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Trace starter/'s sample_key() across UINT32_MAX - 5 -> UINT32_MAX - 1 -> 3 -> 4 TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter -x c - starter/core.c -o "$TMP/wrap" <<'EOF' && "$TMP/wrap" ; rm -rf "$TMP" #include "core.h" #include <stdio.h> int main(void) { struct filter f = {false, false, 0U}; uint32_t t0 = UINT32_MAX - 5U, t1 = UINT32_MAX - 1U; printf("t0=0x%08X -> ev=%d (since+10 wraps to 0x%08X)\n", t0, sample_key(&f, true, t0), f.since + 10U); printf("t1=0x%08X (only 4 ticks later!) -> starter ev=%d (expected 0=NONE)\n", t1, sample_key(&f, true, t1)); return 0; } EOF # 3. Compile the repaired archive files/libbsp.a and list exported symbols make -B -C files nm -g --defined-only files/libbsp.a # 4. Run the authoritative 5-check TAP version 13 harness sh check.sh*Why each step runs:* Step 1 runs check.sh against starter/ safely inside $TMP; Step 2 prints the exact wrapped deadline 0x00000004 (0xFFFFFFFA + 10) that causes starter to emit ev = 1 (PRESS) at 0xFFFFFFFE after just 4 ticks; Step 3 builds files/libbsp.a; and Step 4 confirms # pass 5/5.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
- Candidate Reset & Edge Gate (
core.c:3-12): Wheneverpressed != f->candidate,sample_key()setsf->candidate = pressed; f->since = now;and returnsNONEimmediately. Intests.ccase1, chatter atnow = 1 (true) -> 3 (false) -> 4 (true)resetsf->sinceto4U, sonow = 13U(elapsed = 9U) still returnsNONEandnow = 14U(elapsed = 10U) emitsPRESS. - Seeded Flaw in
starter/core.c:8(sample_key):startertestsf->candidate != f->stable && now >= f->since + 10U. Whenf->since = UINT32_MAX - 5U(0xFFFFFFFAU) intests.ccase3,f->since + 10Uwraps modulo2^32to4U, makingnow >= 4Uimmediatelytrueatnow = UINT32_MAX - 1U(0xFFFFFFFEU, only4ticks elapsed!). - Verified Repair in
files/core.c:8: Evaluates(uint32_t)(now - f->since) >= 10U. Across the wrap boundary (since = 0xFFFFFFFAU),now = 0xFFFFFFFEUgiveselapsed = 4U < 10U(NONE),now = 3Ugives(uint32_t)(3U - 0xFFFFFFFAU) == 9U < 10U(NONE), andnow = 4Ugives10U >= 10U(PRESS), after whichf->stable = truesuppressesnow = 5U(NONE). output_write&bsp_step(core.c:13-25):bsp_step()toggles*enabled = !*enabledstrictly whenevent == PRESS(RELEASEleaves*enabledunchanged intests.c:36), then callsoutput_write(dr, 1U, *enabled, true)to clear bit1(0U) when enabled and set bit1(2U) when disabled while preservingsiblings = dr & ~2U.
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m06-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 4/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - rejects a bouncing press until the full stable interval ok 3 - suppresses held repeats and accepts release before the next press not ok 4 - handles tick wrap and threshold boundaries without deadline overflow --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 3; inspect tests.c for the exact input and expected result' ... ok 5 - integrates two accepted presses with sibling-safe active-low output updates # pass 4/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - rejects a bouncing press until the full stable interval ok 3 - suppresses held repeats and accepts release before the next press ok 4 - handles tick wrap and threshold boundaries without deadline overflow ok 5 - integrates two accepted presses with sibling-safe active-low output updates # pass 5/58. Explanation of Observed Behavior
Notice how insidious starter/core.c is during ordinary testing: checks 2, 3, and 5 (tests.c cases 1, 2, and 4) all use small startup timestamps (1..122), where f->since + 10U never wraps, so starter/ passes 4/5 checks without warning! Only check 4 (tests.c case 3), which seeds now = UINT32_MAX - 5U, exposes the modular deadline overflow at tests.c:25 (assert(sample_key(&f, true, UINT32_MAX - 1U) == NONE)). Switching to subtraction (uint32_t)(now - f->since) >= 10U makes the FSM invariant under arbitrary 32-bit starting phases (# pass 5/5).
9. Experiment Variations
- Toggle on Both Edges Bug (
bsp_step): Changeif (event == PRESS)toif (event != NONE)in a scratch copy and runverify 4:*enabledturns on att = 11(PRESS) and immediately turns off upon finger lift att = 31(RELEASE), converting a latching toggle button into a momentary dead-man switch (tests.c:36aborts). - Off-By-One Threshold (
> 10Uvs>= 10U): Change>= 10Uto> 10Uinsample_key():tests.ccase1(since = 4U, now = 14U), case2(1 -> 11), case3(UINT32_MAX - 5U -> 4U), and case4(1 -> 11) all fail because10elapsed ticks require an11thtick to fire. - Held-At-Boot Policy Check: Initialize
struct filter f = {true, true, 0U};whenGPIO1_PSR[18]reads0at reset and verify a button already held across power-on emits zero spuriousPRESSevents until released and pressed anew.
10. Performance Measurements
Benchmarked on Linux 7.0.0-42-generic (x86_64) via CLOCK_MONOTONIC (5 warmup runs, 35 timed samples):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Superloop Impact |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 cases) | 143.97 ms | 169.45 ms | 170.52 ms | Host compile + link + process launch |
verify 4-case capstone FSM suite (verify 1..4) | 3668.5 us | 4674.6 us | 4923.4 us | < 2 us for all 26 sample_key/bsp_step transitions |
Nonblocking bsp_step() vs 10 ms busy-wait delay | ~3 ns / poll | ~4 ns / poll | ~5 ns / poll | Saves 5,280,000 stalled CPU cycles (10 ms) per bounce! |
11. Troubleshooting
| Symptom | Root Cause | Fix |
|---|---|---|
not ok 4 (sample_key fires PRESS at UINT32_MAX - 1U) | Deadline addition f->since + 10U wraps modulo 2^32 to 4U | Compare elapsed ticks via (uint32_t)(now - f->since) >= 10U |
not ok 2 (bounce glitch at t = 3 still fires PRESS at t = 11) | Updated f->since only when pressed == true instead of every pressed != f->candidate | Reset f->candidate = pressed; f->since = now; on any mismatch |
not ok 3 (holding button at t = 100 emits second PRESS) | Checked (now - f->since) >= 10U without f->candidate != f->stable | Gate qualification on f->candidate != f->stable and set f->stable = f->candidate |
not ok 5 (GPIO sibling bits [31:2] or bit 0 overwritten) | bsp_step wrote *dr = *enabled ? 0U : 2U instead of calling output_write | Mask single bit 1U via output_write(dr, 1U, *enabled, true) |
12. Guided Questions
- Under what maximum polling-gap constraint is
(uint32_t)(now - f->since) >= 10Uguaranteed free of wraparound ambiguity on a1 kHz(1 ms)uint32_ttick counter?
- *Hint 1:* Compute the full period
2^32 msin days (4,294,967,296 ms / 86,400,000 ms/day ~= 49.71 days). - *Hint 2:* What happens if the superloop stalls for
2^32 + 2 mswhilef->candidate != f->stableso(uint32_t)(now - f->since)aliases back to2U < 10U?
- Why does
bsp_step()calloutput_write(dr, 1U, *enabled, true)unconditionally or on state change rather than blocking insidesample_key()for10 ms?
- *Hint 1:* Count how many independent peripherals (
UARTRX FIFO,LEDheartbeat, watchdog service, multiple buttons) share a bare-metal cooperative superloop. - *Hint 2:* If
UART1receives bytes at115200baud (~86.8 usper byte,32-byte hardware RX FIFO =2.78 msto overflow), what happens to incoming serial frames during a10 msblockingdelay_ms(10)debounce?
13. Independent Challenges
- Near Transfer — Asymmetric Press/Release Thresholds & Long-Press Event (
LONG_PRESS): Extendenum eventwithLONG_PRESS(>= 1000ticks continuous hold afterPRESS, emitted at most once per hold viabool long_sentinstruct filter) while keeping10-tick press and15-tick release qualification wraparound-safe. - Far Transfer — 8-Button Bit-Parallel Vertical Counter Debouncer: Design
uint8_t debounce_port8(struct port_deb *d, uint8_t raw_active_low, uint32_t now)that debounces8simultaneousGPIOkeypad inputs using2-bit vertical saturating counters sampled every5 ms(3consecutive matching samples =10 - 15 msqualification) with zero per-pin branches.
14. Solutions & Explanations
- Guided Question 1: Unsigned subtraction
now - sincemeasures exact elapsed ticks modulo2^32provided consecutive polls whilecandidate != stableoccur within< 2^32 - 10ticks (~49.71 daysat1 kHz), so polling every1 - 5 mshas9orders of magnitude safety margin. - Guided Question 2: At
115200 8N1(11,520bytes/s),10 msdelivers115bytes -- overflowing a32-byteUARTFIFO3.6xover! Nonblocking state-machine polling finishes in nanoseconds soUART, timers, and other keys stay responsive every millisecond. - Challenge 1 Guard: After
f->candidate == f->stable && f->stable && !f->long_sent, check(uint32_t)(now - f->since) >= 1000U, setf->long_sent = true, and returnLONG_PRESS; clearf->long_sent = falsewheneverf->stabletransitions tofalse(RELEASE).
Run locally in your terminal and check off each verification milestone.
Not started
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. - 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.
Step sequence — frame strip: steps_m06_l03
Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
reveals: step1
highlights: step1
Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.
reveals: step2
highlights: step2
Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.
reveals: step3
highlights: step3
Step 4: Toggle LED0 (GPIO1_DR[3]) and PNP buzzer (GPIO5_DR[1]) on EV_PRESS while preserving sibling bits.
reveals: step4
highlights: step4