ARMv7-A Cortex-A7 Architecture, Boot ROM & Bare-Metal BSP

GL-E01Linux 6.12C11~545 min18 lessons · 6 labs

Embedded C, BSP, firmware, and Linux bring-up engineers

Outcome: Construct an inspected ARMv7-A bare-metal image, establish its C runtime, and test a modular GPIO BSP without confusing host-model evidence with board proof.

m01/

Cross-compilation workbench, ARM EABI, and schematics

GL-E01lesson 1/18free preview~20 min

1.1 Host–Target Workbench and the i.MX6ULL SoC

What you'll learn
  • Trace host, transport, RAM, and CPU boundaries in a bring-up experiment.
  • Diagnose serial, TFTP, and NFS failures without conflating their layers.
  • Record reproducible build evidence while identifying untested target behavior.

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:

  1. Mask Boot ROM (0x00000000) & 128 KiB OCRAM (0x00900000): Fixed boot firmware and static on-chip SRAM cells that work immediately after reset before external DRAM is configured.
  2. Multi-Mode DDR Controller (MMDC, external DDR3 at 0x80000000+): High-capacity off-chip RAM that returns garbage or hangs the bus until DCD tables or U-Boot calibrate timings.
  3. Clock Control (CCM, 0x020C4000) & Pin Multiplexer (IOMUXC, 0x020E0000): Hardware gates that supply peripheral clocks and route internal signals out to physical BGA balls.
  4. Peripheral IP Blocks (UART1 at 0x02020000, GPIO1..5 at 0x0209C000+, 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.

fig_m01_l01_a.svg — Host-to-target workbench architecture — separating…

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:

ast_m01_l01.svg — Identify which hardware or software boundary each…step 1/4
  1. 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.
  2. Step 2. Step 2 (Transport): UART1 observes asynchronous console text; U-Boot tftpboot moves UDP blocks into RAM without executing them.
  3. Step 3. Step 3 (Target Memory): 128 KiB works before DDR init; DDR3 loadaddr 0x87800000 must avoid U-Boot's relocated code and stack.
  4. 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:

  • UART Serial Console (115200 8N1, 3.3 V TTL): A two-wire (TX, RX + GND) asynchronous character stream. Always verify the schematic's logic voltage (3.3 V vs 1.8 V—never RS-232 +/-12 V!) and ground continuity before connecting. Silence on UART1 means the console port, baud rate, IOMUXC pad mux, UART clock gate, or early boot path failed; it says nothing about Ethernet health.
  • TFTP Image Download (UDP port 69 in U-Boot 2025.x): Once a network-capable bootloader (U-Boot) is running in initialized DDR3 RAM with a working ENET driver, tftpboot ${loadaddr} bsp.bin copies raw file bytes from the host TFTP export directory into physical target RAM at ${loadaddr} (0x87800000). TFTP cannot run on a blank bare-metal CPU without a network stack, and a passing crc32 proves only byte-identical delivery—not a valid ARM entry point or stack!
  • NFS Root Filesystem (RPC / TCP port 2049): Mounts an exported host folder into a running Linux kernel Virtual Filesystem (nfsroot=). NFS does not transfer bare-metal .bin images into OCRAM or DDR3; 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
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:

  1. Binary Struct Drift (LP64 vs ILP32): If a host image-packing tool declares header fields as unsigned long or void *, gcc on x86_64 allocates 8 bytes per field plus alignment padding (24 bytes total), whereas Cortex-A7 firmware expects 4-byte ILP32 words (12 or 16 bytes)—shifting entry_addr by 4+ bytes! Locking every serialized field to <stdint.h> uint32_t and guarding with _Static_assert(sizeof(...) == 16U, ...) forces identical 16-byte geometry on both machines.
  2. 32-Bit Unsigned Addition Wraparound (mod 2^32): Suppose a loader checks whether [start, start + length) fits inside [0x87800000, 0x87801000) using start >= base && start + length <= base + size. When a malformed header supplies start = 0xFFFFFFFCU and length = 8U, ISO C11 wraps 32-bit unsigned addition modulo 2^32 to 0x00000004U, which is <= 0x87801000U—accepting an out-of-bounds write across the 4 GiB boundary! Checking start >= base first and then subtracting (offset = start - base, offset <= size && length <= size - offset) cannot overflow for any uint32_t inputs.
fig_m01_l01_b.svg — Locking 16-byte cross-ABI descriptor layout with…

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
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;    }
  1. Lock image-descriptor fields to uint32_t so LP64 hosts and ILP32 Cortex-A7 targets agree on a 16-byte layout.
  2. Probe little-endian byte order explicitly rather than assuming host memory matches ARMv7-A target byte lanes.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m01-l01
learner@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 ChannelActive StageTransport / WidthWhat Success Proves (and Cannot Prove)
Host ISO C11 verifier (gcc)Pre-transfer build64-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 / runtimeAsynchronous 3.3 V TX/RXProves console clock, pad mux, baud rate, and TX code path; proves 0 Ethernet/NFS health
TFTP image load (tftpboot)U-Boot 2025.xUDP 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.12RPC/TCP or UDP VFS mountProves 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 0x87800000 succeeded; target entry address, EM_ARM ISA state, stack setup, or UART init inside bsp.bin now requires inspection
  • [ ] The Cortex-A7 executed bsp.bin cleanly, and serial silence proves the Ethernet TFTP cable dropped packets
  • [ ] External DDR3 hardware is defective, because a matching crc32 rules 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 C11 treats uint32_t addition overflow as undefined behavior that crashes gcc
  • [ ] Checking length <= size alone guarantees any 4-byte-aligned start fits inside DDR3
  • [x] Well-defined 32-bit unsigned wrap modulo 2^32 turns 0xFFFFFFFCU + 8U into 0x00000004U, 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.MX6ULL MMDC DDR3 calibration, 3.3 V UART1 pads, and U-Boot Ethernet links are ready to boot
  • [x] That the 16-byte uint32_t descriptor layout and overflow-safe RAM window predicate hold on all tested fixtures in host memory
  • [ ] That the attached Cortex-A7 core 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 LP64 build host (8-byte pointers/longs) from a 32-bit ILP32 freestanding Cortex-A7 target (4-byte pointers/longs, zero OS loader); lock shared binary structs to uint32_t.
  • Inside the i.MX6ULL SoC, Boot ROM and 128 KiB OCRAM (0x00900000) work immediately at reset, whereas external DDR3 (0x80000000+), CCM clocks, and IOMUXC pads require explicit initialization.
  • UART serial (115200 8N1 console), U-Boot TFTP (UDP RAM download), and Linux kernel NFS (VFS mount) test distinct layers with independent failure modes.
  • Guard 32-bit RAM placement windows by validating start >= base before comparing length <= size - (start - base), and distinguish host C11 proofs 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

1

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

2

Step 2 (Transport): UART1 observes asynchronous console text; U-Boot tftpboot moves UDP blocks into RAM without executing them.

reveals: step2

highlights: step2

3

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

4

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

GL-E01lesson 2/18free preview~20 min

1.2 ARM Hard-Float EABI, ELF Sections, and Object Inspection

What you'll learn
  • Identify ARM machine and floating-point ABI evidence in an ELF object.
  • Trace argument, return-value, and preserved-register obligations across an AAPCS call.
  • Classify initialized data and zero-initialized storage without confusing file and RAM size.

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:

  1. Core Integer & Pointer Contract (AAPCS32): The first four 32-bit integer or pointer arguments pass in r0..r3, and 32-bit results return in r0 (64-bit integers use an aligned register pair such as r0:r1). Arguments 5 and beyond spill onto the stack ([sp, #0], [sp, #4], ...). Crucially, registers split into two ownership classes: r0..r3 and r12 (IP) are caller-saved scratch (any function you call may destroy them freely), whereas r4..r11 and r13 (SP) are callee-saved (if a callee touches r4, it must push r4 on entry and restore it before returning; note r9 often carries platform-reserved state in bootloaders, so avoid casual scratch use). At every public call boundary, SP must be 8-byte aligned (SP mod 8 == 0).
  2. Soft-Float vs VFPv4 Hard-Float (-mfloat-abi=hard): Under the base/soft-float ABI (arm-none-eabi -mfloat-abi=soft), float values are bit-copied into integer registers r0..r3 and computed via software routines (or softfp wrappers). Under the hard-float variant (arm-linux-gnueabihf, .eabi_attribute 28, 1), float and double arguments pass directly in VFPv4 hardware registers s0..s15 / d0..d7 (s16..s31 / d8..d15 are callee-saved). Mixing the two is catastrophic if unchecked: a soft-float caller places 1.5f (0x3FC00000) into r0, while a hard-float callee reads uninitialized s0! Equally vital for bare-metal engineers: on a cold Cortex-A7 reset, the VFPv4/NEON silicon is powered off/disabled by hardware—executing even a single vadd.f32 or compiler-generated vldr struct copy triggers an Undefined Instruction exception until privileged startup enables CP15 CPACR (CP10/CP11) and sets FPEXC.EN = 1!
fig_m01_l02_a.svg — AAPCS32 register ownership — integer caller/callee…

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:

ast_m01_l02.svg — Never trust a .o or .bin filename: inspect ELF32…step 1/4
  1. Step 1. Step 1 (C Call Site): Word arguments enter in r0..r3; hard-float variants pass eligible floats in VFPv4 registers s0..s15.
  2. Step 2. Step 2 (Object Contract): readelf -h -A proves ELFCLASS32, little-endian LSB, EM_ARM (40), cortex-a7, and Tag_ABI_VFP_args.
  3. Step 3. Step 3 (File Bytes): .text, .rodata, and .data occupy p_filesz bytes on flash/TFTP; raw .bin strips headers and symbols.
  4. 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
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_floats

Auditing 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).

fig_m01_l02_b.svg — Exact Elf32_Ehdr / Elf32_Phdr byte offsets (top) and…

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
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;    }
  1. Verify ELF magic, ELFCLASS32 (1), little-endian data (1), EM_ARM (40), and 52/32-byte header sizes.
  2. Require p_memsz >= p_filesz so NOBITS .bss growth is accepted while truncated memory spans fail.
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m01-l02
learner@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 ChoiceRegister / File ImpactHardware PreconditionFailure Mode When Mismatched
-mfloat-abi=soft (integer EABI)Floats pass in r0..r3; soft-fp helpers linkedPure 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 firstUndefined Instruction trap on first vldr/vpush/vadd.f32 after reset
Linked ELF32 executable (.elf)Retains 52 B Ehdr, Phdr, .symtab, .ARM.attributesParsed 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 .bssSilent 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?

  • [ ] TFTP truncated the upper VFP registers during binary download
  • [ ] Both .o files lacked matching C header filenames during compilation
  • [x] One object was built for soft-float (AAPCS base) 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-A7 hardware MMU dynamically allocates missing .bss pages 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 storing 64 zero 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) via readelf -h -A
  • [ ] Checking that the filename ends in .o or .elf and compiled with 0 warnings
  • [ ] Verifying that tftpboot transferred the file into 0x87800000 with 0 dropped 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

  • AAPCS32 passes the first four 32-bit word arguments in caller-saved r0..r3, requires callees to preserve r4..r11 and 8-byte-aligned SP, and returns 32-bit scalars in r0.
  • The VFPv4 hard-float EABI (-mfloat-abi=hard, .eabi_attribute 28, 1) passes floats in s0..s15 / d0..d7, but faults on bare-metal Cortex-A7 reset until CPACR (CP10/CP11) and FPEXC.EN are enabled.
  • ELF32 stores code and constants in .text/.rodata and initialized variables in .data (p_filesz bytes), while SHT_NOBITS .bss adds p_memsz - p_filesz zero-initialized RAM bytes with zero file bloat.
  • Always retain .elf artifacts alongside stripped .bin images and verify ELFCLASS32, EM_ARM (40), and .ARM.attributes with readelf -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

1

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

2

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

3

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

4

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

GL-E01lesson 3/18free preview~20 min

1.3 Schematics, Active-Low Circuits, and Register Maps

What you'll learn
  • Trace a carrier net through a core connector to its SoC pad.
  • Derive active-low output behavior from an LED current path.
  • Calculate register addresses and masks without altering sibling pins.

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:

  1. High-Side PMOS Source (DR = 1): Connects the package ball up to 3.30 V (V_OH). If an external load runs from the pin through a resistor and LED to GND (active-high source topology, right panel), current flows out of the PMOS transistor into the LED when DR = 1.
  2. Low-Side NMOS Sink (DR = 0): Connects the package ball down to GND with a small transistor drop (V_OL = 0.15 V = 150 mV). On most carrier boards (active-low sink topology, left panel), the hardware designer wires 3.30 V -> R (1000 ohm) -> LED Anode | Cathode -> GPIO1_IO03. When DR[3] = 1, both ends of the LED+resistor branch sit near 3.30 V (0 V potential difference -> zero current -> LED dark!). When DR[3] = 0, the NMOS switch closes to GND: applying Kirchhoff's Voltage Law (KVL) around the loop gives I_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 conservative 8.0 mA (8000 uA) pad current limit!
fig_m01_l03_a.svg — Physical CMOS pad stage — why active-low sink circuits…

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:

ast_m01_l03.svg — Never guess polarity or GPIO numbers from net names:…step 1/4
  1. Step 1. Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
  2. 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.
  3. Step 3. Step 3 (Core Pad): Match the mating SOM connector pin to SoC ball GPIO1_IO03 (Bank 1, local bit index 3).
  4. 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.

fig_m01_l03_b.svg — Four-column schematic trace across board-to-board…

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:

  1. Bounds-First Unsigned Shift (pin < 32U + UINT32_C(1) << pin): In ISO C11, shifting by >= 32 on a 32-bit type—or shifting signed literal 1 into sign bit 31 (1 << 31)—is Undefined Behavior (UB)! Checking if (pin >= 32U) return false; before evaluating UINT32_C(1) << pin eliminates both traps.
  2. Boolean XOR Polarity (high = (on != active_low)): When active_low is true and caller requests on = true, true != true evaluates to false (0), clearing bit 3 (value & ~mask) to sink current while leaving all 31 sibling GPIO1 pins untouched.
learner@ksa: ~/gl-e01/m01-l03
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
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;    }
  1. Evaluate (vdd_mv - vf_mv - vol_mv) * 1000 / r_ohm in uint32_t microamps and enforce the pad sink ceiling.
  2. Reject pin >= 32 before shifting UINT32_C(1) << pin so C11 shift-width undefined behavior never executes.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m01-l03
learner@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 ChoiceDrive Equation / ExpressionPin Stress & Sibling SafetyFailure Mode When Misapplied
direct GPIO sink (<= 2 mA)dr &= ~(1U << pin) asserts; I = (V_DD - V_F - V_OL)/RSafe within pad I_OL budget; 31 siblings preservedDriving 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 preservedFails to conduct if V_OH rail (1.8 V) sits below V_F (2.05 V)
Whole-bank write *gpio1_dr = 0U1 store, 0 mask logicUnsafe: clobbers all 31 neighboring GPIO1 pinsAsserts or drops unrelated relays, chip-selects, and reset lines on GPIO1
Unchecked shift 1 << pin (signed int)Undefined behavior for pin >= 31 in ISO C11Corrupts sign bit at pin == 31 or shifts out of boundsTraps 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_IO03 configured as a high-impedance input so the latch floats
  • [x] Driving GPIO1_IO03 output low (0) so the pad's NMOS transistor sinks current to ground
  • [ ] Driving GPIO1_IO03 output high (1) so both terminals of the branch sit at 3.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, invoking ISO C11 Undefined Behavior
  • [ ] Unsigned shifts automatically wrap pin == 32U onto GPIO2 bit 0 safely
  • [ ] 1U << pin clears neighboring bits unless signed int 1 << pin is 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 0x0209C004U to volatile uint32_t * opens a USB tunnel to the target board
  • [ ] Yes; Linux user space identity-maps i.MX6ULL peripheral bus addresses automatically
  • [x] No; 0x0209C004U is a target SoC physical 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.

Lab 1: ARM32 ELF Header Gate, Overflow-Safe RAM Fit & Active-Low Pin Latch

env: host
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
  1. Validate 32-bit little-endian ARM ELF headers (0x7F 'E' 'L' 'F', EI_CLASS = 1, EI_DATA = 1, e_machine = 40 at bytes 18..19) while rejecting truncated buffers below 20 bytes.
  2. Prove overflow-safe target RAM window containment [start, start + length) inside [base, base + size) using post-guard subtraction (length <= size - (start - base)).
  3. Repair active-low vs active-high GPIOx_DR pin updates (on != active_low) so pin_write() preserves all 31 neighboring pins and rejects NULL pointers or pin >= 32 without mutating caller state.
  4. Benchmark archive build and 4-suite verification latency (p50/p95/p99) using CLOCK_MONOTONIC.
3. Environment Requirements
  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64 LP64 user space) inside labs/lab_m01_eabi_workbench/.
  • Target Architecture Alignment: core.h and core.c restrict register images and RAM addresses to <stdint.h> uint32_t and UINT32_C(1) shifts so host LP64 verification matches 32-bit ARMv7-A ILP32 freestanding builds bit-for-bit.
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, readelf).
  • Hardware: Standard Linux workstation (0 physical target boards or serial adapters required for graded TAP sign-off; 3.3 V active-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
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): Checks n >= 20U before indexing p[0..5] and p[18..19], accepting only 0x7f 'E' 'L' 'F', ELFCLASS32 (1U), ELFDATA2LSB (1U), and little-endian EM_ARM (p[18] == 40U && p[19] == 0U). tests.c case 1 rejects n = 19U, ELFCLASS64 (p[4] = 2U), and EM_X86_64 (p[18] = 62U).
  • image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length) (core.c:8-13): Rejects start < base or length == 0U up front, computes offset = start - base, and checks offset <= size && length <= size - offset so start = UINT32_MAX, length = 8U in tests.c case 2 cannot wrap into range.
  • Seeded Flaw in starter/core.c:18 (pin_write): starter evaluates *dr = (on == active_low) ? *dr | mask : *dr & ~mask; (logical equivalence / XNOR). When on = true and active_low = true (cathode-sink LED on), starter drives bit 3 high (3.3 V), turning the LED off; when on = true and active_low = false on pin = 31U (tests.c:34), starter clears bit 31 (0x12345678U) instead of setting 0x92345678U.
  • Verified Repair in files/core.c:14-20: Guards if (dr == NULL || pin >= 32U) return false; before UINT32_C(1) << pin (avoiding C11 shift undefined behavior at pin == 32U), then writes *dr = (on != active_low) ? *dr | mask : *dr & ~mask;.
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m01-l03
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/5
8. 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
  1. Signed-Shift Undefined Behavior at Pin 31 (UBSan): Replace UINT32_C(1) << pin with 1 << pin in a scratch copy and compile with -fsanitize=undefined: tests.c case 4 (pin = 31U) shifts 1 into the sign bit of 32-bit signed int, triggering an immediate runtime UBSan diagnostic.
  2. Modular Addition Wrap in image_fits(): Temporarily rewrite image_fits() as return length > 0U && start >= base && start + length <= base + size; and run verify 2: UINT32_MAX + 8U wraps to 7U <= 0x1100U, falsely accepting a span past 4 GiB.
  3. Big-Endian EM_ARM Spoof: Set h[18] = 0U; h[19] = 40U; (0x0028 big-endian) in a scratch test and confirm elf_arm32() rejects mismatched byte order even when EI_DATA claims 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 p50Host p95Host p99Cortex-A7 @ 528 MHz Equivalent
Full sh check.sh (make -B + gcc link + 4 processes)130.92 ms139.14 ms146.45 msHost-only toolchain step
verify 4-case binary suite (verify 1..4 sequential)3434.1 us3861.1 us4202.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
SymptomRoot CauseFix
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 corruption1 << pin shifts signed int instead of unsigned uint32_tForm 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 >= 32UPlace `if (dr == NULL \\pin >= 32U) return false; on the first line of pin_write()`
elf_arm32 accepts 256+ machine IDsChecked p[18] == 40U without verifying high byte p[19] == 0URequire both p[18] == 40U && p[19] == 0U for 16-bit little-endian e_machine
12. Guided Questions
  1. Why must pin_write() check pin >= 32U before evaluating UINT32_C(1) << pin, even when pin == 32U returns false on 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 (32 bits).
  • *Hint 2:* On x86_64, SHL eax, cl masks cl modulo 32 (1U << 32 yields 1!), whereas on ARMv7-A, LSL Rd, Rm, Rs uses the bottom 8 bits of Rs (1U << 32 yields 0) -- the compiler may optimize assuming pin < 32U already holds!
  1. Why does an active-low cathode-sink LED require DR[pin] = 0 for on == true while an active-high source LED requires DR[pin] = 1?
  • *Hint 1:* Trace the potential difference V_DD - V_pad across the series resistor and LED when the anode is tied to 3.3 V.
  • *Hint 2:* Write the 2 x 2 truth table of (on, active_low) -> pad_high and verify why pad_high = (on != active_low) covers all four rows.
13. Independent Challenges
  1. Near Transfer — Full Elf32_Ehdr + PT_LOAD Segment Gate: Extend elf_arm32() into elf_arm32_loadable(const unsigned char *buf, size_t len, uint32_t ram_base, uint32_t ram_size) that parses e_phoff, e_phentsize == 32U, and e_phnum, rejects p_memsz < p_filesz, and verifies every PT_LOAD segment (p_type == 1U) fits [ram_base, ram_base + ram_size) via image_fits().
  2. Far Transfer — Multi-Pin Atomic Mask Update (pin_group_write): Implement bool 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 outside group_mask.
14. Solutions & Explanations
  • Guided Question 1: Shifting a 32-bit uint32_t by >= 32 is undefined behavior in ISO C11; evaluating UINT32_C(1) << pin prior to if (pin >= 32U) lets an optimizing compiler elide the pin >= 32U branch altogether!
  • Guided Question 2: With anode at 3.3 V, driving DR = 1 (3.3 V) yields 0 V across the LED (off), whereas driving DR = 0 (V_OL) forward-biases the diode (on). Across all four (on, active_low) pairs, the output latch bit is 1 when (true, false) or (false, true), which is exact Boolean inequality on != 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 SoC ball and GPIO bank/bit.
  • Active-low sink circuits (V_DD -> R -> LED -> GPIO) conduct I = (V_DD - V_F - V_OL) / R when DR drives 0 (level_high = (on != active_low)).
  • Peripheral registers sit at Base + Offset (GPIO1_DR = 0x0209C000, GPIO1_GDIR = 0x0209C004); never dereference physical SoC addresses inside host user space.
  • Guard pin < 32U before evaluating UINT32_C(1) << pin and use masked read-modify-write under exclusive ownership so all 31 sibling 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

1

Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).

reveals: step1

highlights: step1

2

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

3

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

4

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

GL-E01lesson 4/18free preview~20 min

2.1 Processor Modes, Register Banks, and CP15 Control

What you'll learn
  • Classify all nine Cortex-A7 processor modes and their privilege boundaries.
  • Trace which register bank an exception handler actually modifies.
  • Decode CPSR controls and identify an MRC or MCR access to SCTLR.

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:

  1. Privilege Boundaries (PL0, PL1, PL2): User (0x10) is the sole unprivileged PL0 mode: it cannot mask interrupts, switch CPSR modes, or touch CP15 system control. Standard operating-system and bare-metal exception work runs at PL1: Supervisor (SVC, 0x13, entered on Reset and SVC syscalls), IRQ (0x12), FIQ (0x11), Abort (ABT, 0x17, memory faults), Undefined (UND, 0x1B, illegal/disabled opcodes), System (SYS, 0x1F), plus TrustZone Monitor (MON, 0x16) in Secure state. Hyp (HYP, 0x1A) sits at Non-Secure PL2 for virtualization (ERET / ELR_hyp).
  2. What Is Banked vs What Remains Shared! Look closely at the left column of Figure 2.1a: r0..r7 are 100% physically shared across every single mode (r8..r12 are also shared across 8 modes, banked only in FIQ 0x11 so ultra-fast FIQ handlers can run using r8_fiq..r12_fiq with zero stack pushes!). Exception modes (SVC, IRQ, FIQ, ABT, UND, MON) each own a private physical r13 (SP_<mode>), r14 (LR_<mode>), and SPSR_<mode>. Meanwhile, privileged System (0x1F) deliberately shares User's r13_usr and r14_usr with zero SPSR, letting an OS kernel manipulate user-mode stacks without risking SPSR corruption. Therefore, an IRQ handler gets its own safe kernel stack (SP_irq) instantly in hardware—yet if that IRQ handler modifies r0..r3 or r12 without pushing them first, it overwrites the interrupted program's live registers!
fig_m02_l01_a.svg — Physical Cortex-A7 register banking across all nine…

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:

ast_m02_l01.svg — Always resolve active CPSR mode, physical register…step 1/4
  1. 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.
  2. Step 2. Step 2 (Register View): Remember r0..r7 are shared everywhere; only FIQ banks r8..r12 alongside SP and LR.
  3. Step 3. Step 3 (Exception State): Exception entry snapshots CPSR into SPSR_<mode> and selects banked SP/LR (absent in USR/SYS).
  4. 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_2 in [31:28]) means N = 1, Z = 0, C = 1, V = 0.
  • Low control byte 0xD3 (1101_0011_2 in [7:0]) means I = 1 (IRQ masked), F = 1 (FIQ masked), T = 0 (32-bit ARM ISA), and M[4:0] = 0x13 (Supervisor mode).

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!

fig_m02_l01_b.svg — Exact 32-bit bitfields for CPSR (top) and CP15 SCTLR…

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
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 lr

Modeling 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
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;    }
  1. Classify all nine legal Cortex-A7 M[4:0] encodings and distinguish privileged SPSR-bearing exception modes from USR/SYS.
  2. Map FIQ r8..r14 and exception r13..r14 to distinct physical storage slots while keeping r0..r7 shared across every mode.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m02-l01
learner@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])PrivilegePrivate Banked RegistersSPSR PresentPrimary Bare-Metal / OS Role
User (0x10)PL0 (unpriv)None (shares r0..r14 with SYS)NoUnprivileged user-space application execution
System (0x1F)PL1 (priv)Shares USR r0..r14 bankNoPrivileged OS helpers accessing User SP/LR without SPSR risk
Supervisor (0x13) / IRQ (0x12)PL1 (priv)r13 (SP), r14 (LR) per modeYes (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?

  • [ ] IRQ mode automatically restores r0 only when SCTLR.A is 1
  • [ ] IRQ mode has a private r0_irq, and hardware overwrites r0_usr during subs pc, lr, #4
  • [x] IRQ mode banks only r13 (SP_irq), r14 (LR_irq), and SPSR_irq; r0..r12 share physical storage with User mode

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, #0x13 without clearing prior M[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 with mov 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 r4 on the stack to honor the AAPCS32 software calling convention
  • [ ] Hardware switches r4 to a new register bank on every BL instruction
  • [ ] CP15 SCTLR snapshots r4..r11 into SPSR_svc automatically

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-A7 provides nine modes (User at PL0; FIQ, IRQ, Supervisor, Abort, Undefined, System, and Secure Monitor at PL1; Hyp at PL2) encoded in CPSR.M[4:0].
  • r0..r7 are physically shared across every mode (FIQ privately banks r8..r14, other exception modes bank SP and LR, and System shares User's r0..r14).
  • CPSR holds live NZCV flags, A/I/F masks, T state, and M[4:0]; exception modes save interrupted CPSR into SPSR_<mode>, whereas User and System have no SPSR.
  • Privileged CP15 registers like SCTLR (c1, c0, 0) are read via MRC p15 and 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

1

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

2

Step 2 (Register View): Remember r0..r7 are shared everywhere; only FIQ banks r8..r12 alongside SP and LR.

reveals: step2

highlights: step2

3

Step 3 (Exception State): Exception entry snapshots CPSR into SPSR_<mode> and selects banked SP/LR (absent in USR/SYS).

reveals: step3

highlights: step3

4

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

GL-E01lesson 5/18free preview~20 min

2.2 ARM Load/Store Addressing, Shifts, and Conditions

What you'll learn
  • Compute pre-indexed and post-indexed effective addresses and writeback values.
  • Derive field replacement with BIC and ORR without corrupting adjacent bits.
  • Distinguish unsigned carry conditions from signed overflow conditions.

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:

  1. Effective Address (EA) vs Base Writeback (! vs post-index): Every LDR/STR answers two independent questions: which memory address hits the bus (EA), and what value remains in the base register afterward? Starting from r1 = 0x1000:
  • Offset (ldr r2, [r1, #4]): EA = 0x1004; r1 stays 0x1000 (zero writeback).
  • Pre-indexed writeback (ldr r2, [r1, #4]!): Adds #4 first, reads EA = 0x1004, and writes 0x1004 back into r1 (skipping word 0x1000!).
  • Post-indexed writeback (ldr r2, [r1], #4): Reads original EA = 0x1000 first, then writes 0x1004 into r1! Notice that inspecting r1 == 0x1004 in a debugger after the instruction cannot tell you whether 0x1000 or 0x1004 was read!
  1. Zero-Cycle Inline Barrel Shifter + BIC/ORR: Placed directly ahead of the ALU's second input port (Operand2) is a combinational barrel shifter (LSL, LSR, ASR, ROR) that shifts a register by 0..31 bits in the same clock cycle as ADD, ORR, or LDR! Pairing BIC (Bit Clear: Rd <- Rn & ~Op2) with width-clamped AND and shifted ORR (orr r2, r2, r1, lsl #8) replaces multi-bit register fields cleanly without corrupting neighbors.
fig_m02_l02_a.svg — Separating accessed Effective Address from base…

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:

ast_m02_l02.svg — Track accessed address, final base register, field…step 1/4
  1. Step 1. Step 1 (Base & Offset): Separate base pointer Rn from byte offset; VBAR exception bases also require 32-byte alignment.
  2. Step 2. Step 2 (Effective Address): Pre-index [Rn, #4]! touches Rn+4; post-index [Rn], #4 touches original Rn before advancing.
  3. Step 3. Step 3 (Operand Path): Clamp incoming field width with AND before barrel-shifting LSL into BIC + ORR.
  4. 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) sees 2,273,312,768 >= 9,437,184 -> TRUE!
  • A signed branch bge (N == V) sees -2,021,654,528 < +9,437,184 (1 != 0) -> FALSE! Writing blt instead of blo in a .bss zeroing loop inside DDR3 (0x87800000) instantly treats valid RAM addresses as negative integers!
fig_m02_l02_b.svg — Exception vector base routing via SCTLR.V and…

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
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_nibble

Auditing 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
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;    }
  1. Enforce VBAR[4:0] == 0 (32-byte alignment) and select 0xFFFF0000 high vectors whenever SCTLR.V (bit 13) is 1.
  2. Distinguish pre-indexed [base, #off]! (base + off accessed) from post-indexed [base], #off (base accessed).
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m02-l02
learner@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 MechanismSyntax ExampleEffective Address / Flag RuleClassic Bring-Up Bug When Confused
Offset addressing (no writeback)ldr r2, [r0, #4]EA = r0 + 4; r0 unchangedLoop pointer never advances (infinite loop over first word)
Pre-indexed writebackldr r2, [r0, #4]!EA = r0 + 4; r0 <- r0 + 4Skips word 0 ([r0 + 0]) at the start of .data copy or .bss zeroing
Post-indexed writebackldr r2, [r0], #4EA = r0; r0 <- r0 + 4Subsequent str r2, [r0] writes r0 + 4 unless [r0, #-4] compensates
Unsigned BHS vs signed BGEcmp r0, r1 -> bhs / bgeBHS: C == 1; BGE: N == VUsing 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]! reads 0x1004, whereas post-indexed [r1], #4 reads the original 0x1000 before updating r1
  • [ ] Post-indexed [r1], #4 discards the loaded word unless S is 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 in r1 (such as 0x32) shift into [31:12] and corrupt neighboring register fields
  • [ ] ORR on Cortex-A7 faults unless its shifted source operand is < 16
  • [ ] AND converts W1C status 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?

  • [ ] BHI and BLT read two different physical ALU result registers
  • [ ] CMP rewrites r0 from unsigned format into two's-complement format
  • [x] 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)

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-A separates ALU/barrel-shifter register operations from LDR/STR memory transfers, and separates accessed Effective Address (EA) from base writeback.
  • Pre-indexed [Rn, #off]! accesses Rn + off and writes Rn + off back; post-indexed [Rn], #off accesses original Rn first and writes Rn + off back afterward.
  • Replace multi-bit subfields by clearing the field mask with BIC, clamping the new value's bit-width with AND, and inserting via shifted ORR.
  • After CMP, unsigned comparisons test carry (BHS C==1, BLO C==0—mandatory for DDR3 addresses >= 0x80000000!), whereas signed comparisons test N == V (BGE) and N != 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

1

Step 1 (Base & Offset): Separate base pointer Rn from byte offset; VBAR exception bases also require 32-byte alignment.

reveals: step1

highlights: step1

2

Step 2 (Effective Address): Pre-index [Rn, #4]! touches Rn+4; post-index [Rn], #4 touches original Rn before advancing.

reveals: step2

highlights: step2

3

Step 3 (Operand Path): Clamp incoming field width with AND before barrel-shifting LSL into BIC + ORR.

reveals: step3

highlights: step3

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.

reveals: step4

highlights: step4

GL-E01lesson 6/18free preview~20 min

2.3 Branches, Full-Descending Stacks, and Calling C

What you'll learn
  • Trace B, BL, and BX without confusing subroutine and exception returns.
  • Construct an eight-byte-aligned full-descending frame around a nested call.
  • Verify saved-register order and restore the caller-visible state.

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:

  1. Full-Descending Stack (STMFD == STMDB, LDMFD == LDMIA): Descending means the stack grows downward from high RAM addresses (0x1000) toward low addresses (0x0FF8); Full means SP (r13) always points at the last occupied word (not the next empty slot). Executing stmfd sp!, {r4, lr} (popcount = 2 words = 8 bytes) decrements SP from 0x1000 to 0x0FF8 before storing. Even more important: inside the 32-bit ARM opcode, {r4, lr} is encoded as a 16-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-numbered lr (r14) at 0x0FFC = [sp + 4], even if you type {lr, r4} in source!
  2. Mandatory 8-Byte Public SP Alignment (SP mod 8 == 0): AAPCS32 requires SP to be a multiple of 8 bytes at every public C call boundary because 64-bit integers (uint64_t), double values, va_arg(), and ARMv7-A doubleword instructions (LDRD / STRD) require 8-byte stack alignment. If incoming SP = 0x1000 (mod 8 == 0) and an assembly wrapper pushes {lr} alone (4 bytes -> SP = 0x0FFC, mod 8 == 4), calling printf or any uint64_t C helper either triggers a hardware Alignment Data Abort or reads swapped 32-bit words! Pushing an even register pair (stmfd sp!, {r4, lr}) subtracts 8 bytes (0x0FF8 mod 8 == 0), saving both outer LR and callee-owned r4 in one instruction!
fig_m02_l03_a.svg — Full-descending stack frame layout and 16-bit register…

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:

ast_m02_l03.svg — Every non-leaf assembly routine calling C must save…step 1/4
  1. Step 1. Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.
  2. Step 2. Step 2 (Prologue Save): stmfd sp!, {r4, lr} decrements SP by 8 bytes, placing r4 at [sp] and LR at [sp + 4].
  3. 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.
  4. 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:

  1. Caller enters sum_then_double(7, 9) via bl: r0 = 7, r1 = 9, SP = 0x1000, LR = 0x87800104.
  2. Prologue stmfd sp!, {r4, lr} sets SP = 0x0FF8, writes caller r4 to [0x0FF8] and 0x87800104 to [0x0FFC].
  3. bl add_words overwrites live LR with 0x87800208; add_words computes r0 = 7 + 9 = 16 and executes bx lr (PC <- 0x87800208, zero stack traffic!).
  4. lsl r0, r0, #1 doubles r0 to 32, and epilogue ldmfd sp!, {r4, pc} restores r4, loads [0x0FFC] = 0x87800104 directly into PC (interworking-capable in ARMv7-A!), and restores SP = 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)!

fig_m02_l03_b.svg — Return-address lifetime across nested BL calls (top)…

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
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_words

Proving 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
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;    }
  1. Require 8-byte SP alignment and an even push count before entering a nested AAPCS32 public call.
  2. Store r4 at the lower word (sp) and lr at the upper word (sp + 1) matching hardware register-number order.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m02-l03
learner@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!

InstructionUpdates LR?Restores CPSR?Interworks ARM/Thumb?Valid Use Case
b labelNoNoNo (same ISA state)Local unconditional jump or zero-frame tail-call
bl helperYes (LR = next_instr)NoNo (BLX switches state)Standard subroutine call; clobbers caller's live LR
bx lrNoNoYes (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-ANon-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_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
  • [ ] r0..r3 become permanently banked to inner_fn
  • [ ] The linker automatically rewrites bx lr into ldmfd 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 4 from LR before pushing so the return address aligns SP
  • [ ] Clear sp bits [2:0] with bic sp, sp, #7 after pushing without restoring the old sp
  • [x] 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

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), because lr was written first inside {lr, r4}
  • [x] r4, because hardware encodes a 16-bit register bitmask and always stores the lowest-numbered register at the lowest address
  • [ ] Neither; STMFD stores at 0x1000 and 0x1004 before decrementing SP

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.

Lab 2: ARMv7-A CPSR Mode Switch, Indexing EA, Nibble BIC/ORR & AAPCS32 Frame

env: host
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
  1. Preserve CPSR status, endianness, thumb, and interrupt-mask bits (~0x1FU) when replacing M[4:0] (select_mode) to enter SVC (0x13).
  2. Distinguish pre-indexed (base + offset) from post-indexed (base) memory effective addresses in effective() so load/store models match Cortex-A7 AGU hardware.
  3. Mask oversized 4-bit field inputs ((value & 15U) << 8) after clearing bits [11:8] (~0xF00U) in replace_field().
  4. Enforce full-descending 8-byte-aligned two-word stack pushes (r4 at lower address words[*sp], lr at words[*sp + 1U]) in frame().
3. Environment Requirements
  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) executing inside labs/lab_m02_armv7_isa_sim/.
  • Target Architecture Alignment: Models 32-bit ARMv7-A (A32 state) architectural registers (CPSR, r0..r15) and AAPCS32 word-indexed stack memory (words[0..7], 4 bytes per word, even word index <=> 8-byte byte-address alignment).
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 JTAG debuggers or physical Cortex-A7 boards required for the 5-check TAP grader).
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
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), modeling BIC r0, r0, #0x1f followed by ORR r0, r0, #0x13. In tests.c case 1, 0xa00000d0U (N=1, C=1, I=1, F=1, USR=0x10) transitions to 0xa00000d3U (SVC=0x13) with upper 27 bits intact.
  • Seeded Flaw in starter/core.c:6-9 (effective): starter computes return pre ? base : base + offset; -- swapping pre-indexed and post-indexed addressing! On ARMv7-A, post-indexed LDR Rt, [Rn], #4 (pre == false) accesses memory at Rn (base) before writing Rn + 4 back to Rn, whereas pre-indexed LDR Rt, [Rn, #4]! (pre == true) accesses memory at Rn + 4 (base + offset).
  • Verified Repair in files/core.c:6-9: Restores return pre ? base + offset : base;, matching tests.c case 2 (effective(0x1000U, 4U, false) == 0x1000U and effective(0x1000U, 4U, true) == 0x1004U).
  • replace_field & frame (core.c:10-21): replace_field() clears [11:8] with ~UINT32_C(0xf00) and truncates oversized value = 0x32U via (value & 15U) << 8 (0xa5a5f2ffU). frame() enforces *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U (8-byte alignment), decrements *sp -= 2U, and stores lowest-numbered r4 at words[*sp] and lr (r14) at words[*sp + 1U] matching PUSH {r4, lr} (STMDB sp!, {r4, lr}).
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m02-l03
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/5
8. 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
  1. Unmasked ORR Spill in replace_field(): Remove & 15U in a scratch copy so replace_field() computes (old & ~UINT32_C(0xf00)) | (value << 8) on old = 0x00000000U, value = 0x32U: bit 12 and bit 13 (0x3000U) bleed into adjacent register fields, failing tests.c:18.
  2. Swapped Register-List Order in frame(): Swap words[*sp] = lr; words[*sp + 1U] = r4; and run verify 4: ARMv7-A STMDB sp!, {r4, lr} always places the lowest register number (r4) at the lowest memory address regardless of assembly syntax order, so words[6] == 0x44444444U aborts.
  3. 4-Byte Misaligned Call-Site SP: Remove (*sp & 1U) != 0U in a scratch copy and observe tests.c:26 (sp = 1U, byte offset 4) fail, demonstrating why AAPCS32 rejects 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 p50Host p95Host p99Cortex-A7 @ 528 MHz Hardware Timing
Full sh check.sh (make -B + gcc link + verify 1..4)127.95 ms136.35 ms142.79 msHost build + process spawn overhead
verify 4-case ISA simulator suite (1..4 sequential)3466.4 us4050.7 us4293.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
SymptomRoot CauseFix
not ok 3 (effective fails case 2 at tests.c:14)Ternary returns base for pre == true and base + offset for pre == falseReturn 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 ~0x1fUClear 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 11Mask 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) != 0UValidate *sp >= 2U && *sp <= 8U && (*sp & 1U) == 0U prior to mutating *sp
12. Guided Questions
  1. Why do .data copy loops in ARMv7-A _start overwhelmingly use post-indexed LDR r3, [r0], #4 / STR r3, [r1], #4 rather than pre-indexed [r0, #4]!?
  • *Hint 1:* Linker symbols __data_load (r0) and __data_start (r1) point directly to byte 0 of the section, not 4 bytes below it.
  • *Hint 2:* Trace which address the very first iteration loads under pre = true (r0 + 4, skipping word 0!) versus pre = false (r0, then advancing r0 <- r0 + 4 for iteration 2).
  1. Why does AAPCS32 mandate 8-byte SP alignment ((*sp & 1U) == 0U in 32-bit words) at public function boundaries when ordinary r0..r15 registers are only 4 bytes wide?
  • *Hint 1:* Consider instructions that transfer 64-bit doublewords on the stack (LDRD/STRD, VPUSH/VPOP, and int64_t/uint64_t/double printf varargs).
  • *Hint 2:* What alignment fault fires on Cortex-A7 when LDRD executes against an address that is 4-byte aligned (0x...4) instead of 8-byte aligned (0x...0 or 0x...8)?
13. Independent Challenges
  1. Near Transfer — Legal Cortex-A7 Mode Whitelist (select_mode_checked): Write bool select_mode_checked(uint32_t old, uint32_t mode, uint32_t *out) that accepts only the 9 architectural Cortex-A7 M[4:0] encodings (0x10, 0x11, 0x12, 0x13, 0x16, 0x17, 0x1A, 0x1B, 0x1F) and rejects reserved 5-bit patterns such as 0x00 or 0x14 without altering *out.
  2. Far Transfer — Paired Epilogue unframe() (LDMIA sp!, {r4, pc}): Implement bool unframe(const uint32_t *words, unsigned *sp, uint32_t *r4_out, uint32_t *pc_out) that validates *sp <= 6U && (*sp & 1U) == 0U, pops r4 and pc in full-descending order, increments *sp += 2U, and proves frame followed by unframe is 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], #4 dereferences Rn + 0 on iteration 0 and leaves Rn equal to _edata when the loop terminates; pre-indexed [Rn, #4]! would skip [Rn + 0] unless the pointer were pre-biased by -4.
  • Guided Question 2: AAPCS32 aligns SP to 8 bytes at every public call site so callees can issue 64-bit LDRD/STRD and VFP stack spills without runtime realignment prologues or alignment data aborts.
  • Challenge 1 Bitmask Trick: Since mode & 0x1fU lies in 0..31, test membership in O(1) via const 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

  • B jumps without touching LR, BL records the subroutine return address in LR (clobbering any unsaved LR), and BX Rm branches while selecting ARM/Thumb state from Rm[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.
  • AAPCS32 requires 8-byte stack alignment (SP mod 8 == 0) at every public call site and requires callees to preserve r4..r11 and SP.
  • Never use subs pc, lr, #4 (an IRQ exception return) to return from an ordinary BL subroutine; use bx lr (leaf) or ldmfd 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

1

Step 1 (Caller Entry): Outer BL writes return address into live LR with incoming SP aligned to 8 bytes.

reveals: step1

highlights: step1

2

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

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.

reveals: step3

highlights: step3

4

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

GL-E01lesson 7/18free preview~20 min

3.1 CCM Clock Gates, Pad Mux Modes, and SION

What you'll learn
  • Locate CCGR0–CCGR6 fields without enabling every peripheral.
  • Derive a legal pad mux value from the selected pad's function table.
  • Explain what SION forces and what it does not connect.

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:

  1. Dynamic Switching Power & CCM_CCGR0..CCGR6 Clock Gates (0x020C4068..0x020C4080): Every CMOS flip-flop burns dynamic power proportional to capacitance, voltage squared, and clock frequency (P = C * V^2 * f). An i.MX6ULL integrates over 50 peripheral 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) places 16 two-bit Clock Gate (CG0..CG15) latches inside each of the seven 32-bit CCGR0..CCGR6 words (00 = clock off, 01 = clock on in RUN mode only, 10 = reserved, 11 = clock on in RUN and WAIT low-power idle). Crucially, if a peripheral's CG field is 00, its internal IPG bus 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 blasting 0xFFFFFFFFU into CCGR0..CCGR6: update only the 2-bit CG slot you own so power policy and missing-clock bugs remain diagnosable.
  2. BGA Pin Scarcity & IOMUXC Alternate-Function Crossbars (0x020E0000+): A 14 x 14 mm i.MX6ULL package has roughly 100+ general I/O balls, yet its internal peripherals expose over 600 distinct 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 of ALT0..ALT8 functions (for ball GPIO1_IO03, ALT0 = I2C1_SDA, ALT5 = GPIO1_IO03, etc.—not every ALT number 0..8 exists on every ball!). Until MUX_MODE[3:0] selects ALT5 (5), GPIO1's data latch can toggle all day while the physical ball remains connected to I2C1 or UART!
fig_m03_l01_a.svg — End-to-end silicon signal graph — CCM clock gate…

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:

ast_m03_l01.svg — Enable the peripheral clock first, then select a…step 1/4
  1. Step 1. Step 1 (CCM Policy): Update only CCGR1[27:26] = 0b11 (mask 0x0C000000) and issue DSB SY before touching GPIO1.
  2. Step 2. Step 2 (Pad Function Table): Confirm the exact ball implements the target ALT mode (not all pads implement ALT0..ALT8).
  3. 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.
  4. 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:

  1. 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. Setting SION = 1 (0x15 = SION | ALT5) forces that single ball's input receiver ON, letting GPIO1_PSR observe actual wire voltage while driving an output or letting an I2C controller monitor open-drain bus arbitration! SION is not a magic internal wire connecting UART1_TX to SPI2_RX; it only enables input sampling of that physical ball.
  2. Why SELECT_INPUT (DAISY) Exists: An output mux (1 ball choosing among 8 peripherals) lives at the ball. What about an input signal like UART1_RX_DATA that i.MX6ULL allows you to wire to 2 or 4 different package balls? The UART1 receiver needs its own N-to-1 multiplexer (IOMUXC_UART1_RX_DATA_SELECT_INPUT) whose DAISY bits tell UART1 which ball to listen to! Forgetting SELECT_INPUT leaves TX working while RX listens to an unconnected pin.
fig_m03_l01_b.svg — Exact 32-bit bitfields for CCM_CCGR1 (top) and…

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
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 lr

Validating CCGR Slots, Per-Ball ALT Tables, and Daisy Bounds in C11

In iomuxc_mux_daisy_audit.c, notice how we validate hardware capability, not just bit width! 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
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;    }
  1. Update only the 2-bit CG[index] field in CCGRx while rejecting index >= 16 or reserved mode 2.
  2. Check (allowed_alts & (1U << alt)) before writing MUX_MODE[3:0] and compose SION at bit 4.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m03-l01
learner@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 PracticeRegister EffectSide-Effect / Power ScopeEngineering Verdict
Masked CGk update (~(3U << 2k))Updates 2 bits in 1 CCGR wordNeighboring 15 peripheral clocks untouchedRecommended: explicit dependency and minimal power waste
Blanket CCGR0..6 = 0xFFFFFFFFUForces all 112 CG slots to 0b11Masks missing-clock bugs; clocks unused IP in WAITAvoid: hides broken driver clock claims
MUX_MODE = ALT5, SION = 0 (0x05)Routes GPIO mux; normal dir-controlled inputStandard unidirectional input or outputDefault for pure outputs/inputs
MUX_MODE = ALT5, SION = 1 (0x15)Forces pad input buffer active (PSR live)Slightly higher receiver switching activityUse 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_DR requires a 64-bit store to override I2C1
  • [x] IOMUXC_SW_MUX_CTL_PAD_GPIO1_IO03 (0x020E0068) has not been switched to ALT5 (MUX_MODE = 5)
  • [ ] CCM_CCGR0..6 must all be written to 0xFFFFFFFFU before GPIO1 routes 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 ALT encodings leave the pin disconnected or undefined
  • [ ] ALT8 is reserved exclusively for Hyp (PL2) mode instructions
  • [ ] ALT8 becomes valid on every pad as soon as SION (bit 4) is set to 1

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_CCGRx clock gates and sets GPIO_GDIR to 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 using 16 two-bit CG fields per word (00 off, 01 RUN, 11 RUN+WAIT); enable the clock + dsb sy before accessing peripheral .
  • Peripheral clocking (CCM) and ball signal routing (IOMUXC_SW_MUX_CTL_PAD_*) are independent hardware requirements.
  • MUX_MODE[3:0] must select an ALT function actually implemented on that exact SoC ball (ALT5 for GPIO1_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

1

Step 1 (CCM Policy): Update only CCGR1[27:26] = 0b11 (mask 0x0C000000) and issue DSB SY before touching GPIO1.

reveals: step1

highlights: step1

2

Step 2 (Pad Function Table): Confirm the exact ball implements the target ALT mode (not all pads implement ALT0..ALT8).

reveals: step2

highlights: step2

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.

reveals: step3

highlights: step3

4

Step 4 (Observable Pad): Program SELECT_INPUT DAISY for shared RX inputs, then configure pad electricals and GPIO direction.

reveals: step4

highlights: step4

GL-E01lesson 8/18free preview~20 min

3.2 Pad Electrical Fields: Pulls, Drive, Slew, and Open-Drain

What you'll learn
  • Decode HYS, PUS, PUE, PKE, ODE, SPEED, DSE, and SRE fields.
  • Diagnose why selecting PUS alone does not necessarily enable a pull resistor.
  • Choose a conservative pad policy and state which electrical claims still require measurement.

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):

  1. Schmitt-Trigger Input Receiver (HYS, bit 16): A plain CMOS inverter switches around a single threshold (~V_DD / 2). When a slow RC sensor edge crawls across 1.65 V carrying 40 mV of power-rail noise, a single-threshold receiver fires a burst of false 0->1->0->1 digital glitches! Enabling HYS = 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: HYS rejects millivolt analog noise on an edge—it is not a time-based debouncer and cannot absorb 5..15 ms mechanical switch contact bounce!
  2. Hierarchical Bias Network (PKE bit 12 -> PUE bit 13 -> PUS bits [15:14]): Why three separate fields? Because silicon offers two fundamentally different weak bias circuits behind one master power switch PKE (Pull/Keeper Enable, bit 12):
  • If PKE == 0, the entire bias block is disconnected (Hi-Z floating input).
  • If PKE == 1 and PUE == 0 (Pull/Keeper Select = Keeper), silicon connects a weak cross-coupled inverter latch (bus keeper) that gently holds whichever logic 0 or 1 was last driven on the wire—and PUS[15:14] is completely ignored! That proves why 0x10B0 (bit 12 = 1, bit 13 = 0) is a bus keeper, never a 100 kOhm pull-down!
  • Only when PKE == 1 AND PUE == 1 does silicon connect the resistive PUS[15:14] network: 00 = 100 kOhm pull-down, 01 = 47 kOhm pull-up, 10 = 100 kOhm pull-up, 11 = 22 kOhm pull-up.
  1. Output Driver Stage (ODE bit 11, SPEED [7:6], DSE [5:3], SRE [0]): Normal push-pull mode (ODE = 0) drives both PMOS (high) and NMOS (low). Setting ODE = 1 (Open-Drain Enable) disables the high-side PMOS transistor: writing 0 actively sinks to GND, whereas writing 1 releases the wire (Hi-Z) so an external pull-up resistor (2.2 kOhm..4.7 kOhm on I2C) pulls the bus high at tau = R_pull * C_bus! Meanwhile, DSE[5:3] (Drive Strength) switches 1..7 parallel transistor fingers in (R0/1 ~ 260 ohm down to R0/6 ~ 43 ohm, R0/7 ~ 37 ohm)—whereas DSE == 0 disconnects ALL output fingers (Hi-Z), killing output drive even when GPIO_GDIR == 1! SRE[0] (Slew Rate) selects slow (0, lower EMI/ringing) vs fast (1, sharp high-frequency edges).
fig_m03_l02_a.svg — Inside an i.MX6ULL CMOS pad cell — output DSE slices…

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:

ast_m03_l02.svg — Decode PKE -> PUE -> PUS and DSE != 0 explicitly…step 1/4
  1. Step 1. Step 1 (Input Path): Enable HYS[16] = 1 for Schmitt noise immunity on slow digital edges (still debounce switches in software!).
  2. Step 2. Step 2 (Bias Network): Check PKE[12] = 1 and PUE[13] = 1 before trusting PUS[15:14]; PUE = 0 selects bus keeper.
  3. 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!).
  4. 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 a 1 Hz LED!).
  • 0x0001B000 (Pulled-Up Digital Input, pad_policy.c below): (1U << 16) | (2U << 14) | (1U << 13) | (1U << 12) enables HYS=1, PUS=2 (100 kOhm pull-up), PUE=1 (pull mode!), and PKE=1, with DSE=0.
  • 0x0001B8B0 (Open-Drain I2C Bus): Adds ODE=1 (bit 11) + DSE=6 + SPEED=2 (and pairs with SION=1 in SW_MUX_CTL plus an external 2.2 kOhm pull-up because internal ~100 kOhm * 100 pF takes ~22 us to rise, violating 400 kHz I2C's 300 ns rise-time spec!).
fig_m03_l02_b.svg — Exact 32-bit SW_PAD_CTL bitfields under mask 0x0001F8F9…

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
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
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;    }
  1. Validate multi-bit ranges (PUS <= 3, SPEED <= 3, DSE <= 7) before shifting into mask 0x0001F8F9U.
  2. Check PKE (bit 12) before PUE (bit 13): PUS [15:14] has zero pull effect whenever PKE == 0 or PUE == 0.
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m03-l02
learner@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 RoleTypical SW_PAD_CTL WordDecoded Active FieldsElectrical Caveat
Push-pull GPIO LED output0x000010B0PKE=1, PUE=0 (keeper), SPEED=2, DSE=6, SRE=0DSE=0 (Hi-Z) disables output driver completely even when GDIR=1!
tactile switch input0x0001B000HYS=1, PUS=2 (100K up), PUE=1, PKE=1, DSE=0HYS suppresses slow-edge threshold chatter, NOT 5..15 ms contact bounce
Open-drain shared bus (I2C)0x0001B8B0HYS=1, PUS=2, PUE=1, PKE=1, ODE=1, DSE=6Requires SION=1 in MUX_CTL + external 2.2k..4.7k pull-up for 400 kHz
High-speed SD/ENET clock/data0x000170F9 / B9HYS=1, 47K up, SPEED=2/3, DSE=6/7, SRE=1Fast 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; PUS is inactive because PUE == 0
  • [ ] The 100 kOhm pull-up resistor is active because non-zero PUS overrides PUE
  • [ ] High-side PMOS drive forces the pin to 3.3 V regardless 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 PMOS high-side fingers actively source R0/6 current up to 3.3 V
  • [ ] The Schmitt trigger toggles the pin until PSR matches DR
  • [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 HYS and PUE automatically selects ALT5 (GPIO)
  • [x] No; SW_PAD_CTL sets electrical pad behavior only, while SW_MUX_CTL (0x020E0068) independently selects MUX_MODE
  • [ ] Yes, whenever DSE[5:3] is 0 (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.MX6ULL SW_PAD_CTL words pack HYS[16], PUS[15:14], PUE[13], PKE[12], ODE[11], SPEED[7:6], DSE[5:3], and SRE[0] inside mask 0x0001F8F9U.
  • PKE (bit 12) powers the bias block, and PUE (bit 13) chooses resistive pull (1, using PUS) versus bus keeper (0, ignoring PUS).
  • ODE (bit 11 = 1) releases high-side PMOS drive on logical 1; DSE[5:3] sets output impedance (R0/1..R0/7, with 0 = Hi-Z disabled!).
  • 0x000010B0 enables bus keeper (PKE=1, PUE=0) with DSE=6 and SPEED=2—not an active 100 kOhm pull-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

1

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

2

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

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!).

reveals: step3

highlights: step3

4

Step 4 (Measurement): Preserve reserved gaps (~0x0001F8F9U) and verify rise time tau = R * C and rail levels on an oscilloscope.

reveals: step4

highlights: step4

GL-E01lesson 9/18free preview~20 min

3.3 GPIO DR, GDIR, PSR, Interrupt Status, and Assembly LED Control

What you'll learn
  • Distinguish DR output state, GDIR direction, and PSR pad sampling.
  • Derive ICR1 and ICR2 fields from a bank-local GPIO index.
  • Acknowledge one W1C interrupt bit without clearing sibling events.

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:

  1. DR (+0x00) vs GDIR (+0x04) vs PSR (+0x08): DR is an internal 32-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-only PSR samples the actual electrical voltage at the package ball! Two immediate engineering consequences follow:
  • Why DR != PSR: If DR[3] = 1 and GDIR[3] = 1, yet an external short-circuit or open-drain slave clamps the board trace to 0 V (or SW_PAD_CTL.DSE == 0 left the driver Hi-Z), reading DR returns 1 (what you requested), whereas reading PSR returns 0 (what is physically on the wire)!
  • Glitch-Free Active-Low Startup (Panel 2 of Figure 3.3a): At reset, DR and GDIR both clear to 0. On an active-low LED, buzzer, or relay (0 = ON!), if firmware sets GDIR[3] = 1 before setting DR[3] = 1, the tri-state buffer turns ON while DR[3] is still 0—firing a spurious low pulse onto the hardware load! Always preload DR to its safe inactive state (1) + dsb sy before setting GDIR = 1!
  1. Interrupt Trigger Split (ICR1 / ICR2) & Why GPIO_ISR Is Write-One-to-Clear (W1C): Configuring 4 trigger modes (00 low-level, 01 high-level, 10 rising-edge, 11 falling-edge) across 32 pins takes 32 * 2 = 64 bits, so hardware splits pins 0..15 into ICR1 (+0x0C) and pins 16..31 into ICR2 (+0x10) at local shift 2 * (pin % 16) (with EDGE_SEL at +0x1C overriding for dual-edge capture), masked by IMR (+0x14). Why did silicon architects make ISR (+0x18) Write-One-to-Clear (W1C) instead of ordinary read/write? Because asynchronous pin edges can set a sibling bit in ISR on any clock cycle between a CPU LDR and STR! With W1C (ISR_next = ISR_curr & ~W_data), writing 0 bits is a hardware no-op and writing a pure mask (0x08 for pin 3) atomically clears only bit 3 in a single STR—whereas an ordinary RMW (ISR |= 0x08) replays 1s on every pending sibling bit (0x0A) and wipes them out (0x00)!
fig_m03_l03_a.svg — Inside GPIO1 @ 0x0209C000 — separating DR request, GDIR…

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:

ast_m03_l03.svg — Match every GPIO operation to its exact register…step 1/4
  1. Step 1. Step 1 (Output Latch): Preload inactive high DR[3] = 1 (+0x00) + DSB SY before enabling output direction.
  2. Step 2. Step 2 (Direction): Set GDIR[3] = 1 (+0x04) via masked RMW so all 31 neighboring pins keep their directions.
  3. Step 3. Step 3 (Pad Observation): Sample physical wire state from read-only PSR (+0x08), which can differ from DR under load/clamp.
  4. 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:

  1. ICR1 (0..15) vs ICR2 (16..31) Shift Math: Pin 15 occupies bits [31:30] of ICR1 (shift = 30). Pin 16 starts over at bits [1:0] (shift = 0!) of ICR2! Writing 2 * pin without pin % 16 shifts by 32..62 for pins 16..31—triggering ISO C11 Undefined Behavior and missing ICR2 completely.
  2. Zero-Load W1C Acknowledgment (gpio1_ack_pin3): Look at lines 23..28 of target.S! Whereas led_prepare_inactive and led_assert execute ldr -> orr/bic -> str on ordinary RW latches DR (0x0209C000) and GDIR (0x0209C004), gpio1_ack_pin3 executes mov r1, #8 followed immediately by str r1, [r0] (0x0209C018) with NO ldr! On ISR = 0x0A (pins 3 and 1 pending), storing 0x08 leaves 0x02 intact, whereas ldr + orr #8 + str writes 0x0A and destroys pin 1's interrupt!
fig_m03_l03_b.svg — ICR1 / ICR2 half-bank bit-pair split (top) and why…

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
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 lr

Simulating 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
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;    }
  1. Partition pins 0..15 into ICR1 and pins 16..31 into ICR2 so local shifts stay within [0, 30].
  2. Hardware W1C clears every bit position written as 1 (b->isr &= ~word_written); writing 0 leaves pending bits intact.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m03-l03
learner@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 MeaningWrite SemanticsSafe Single-Pin Update Pattern
GPIOx_DR (+0x00)Latched output valueOrdinary read/write latchExclusive-owner `(DR & ~mask) \val`
GPIOx_GDIR (+0x04)0 = input, 1 = outputOrdinary read/write latchPreload DR safe state + dsb sy first, then `GDIR \= mask`
GPIOx_PSR (+0x08)Sampled pad receiver stateRead-only (const in C overlay)Read (PSR >> pin) & 1U (set SION=1 if output readback required)
GPIOx_ISR (+0x18)1 = latched trigger eventWrite-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 via GPIO1->ISR |= (1U << 3)
  • [ ] 0x02, computed via GPIO1->ISR &= ~(1U << 3)
  • [x] 0x08 (UINT32_C(1) << 3) written directly with zero prior read, leaving bit 1 (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 shift 16 (bits [17:16])
  • [x] In GPIO1_ICR2 (+0x10) at bit shift 0 (bits [1:0])
  • [ ] In GPIO1_ICR1 (+0x0C) at bit shift 32

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] 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
  • [ ] Reading PSR automatically switches the Cortex-A7 into IRQ mode and clears DR
  • [ ] volatile pointers cache PSR in 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.

Lab 3: CCM Gate Slots, IOMUXC Pad/Bias Decoding & Non-Destructive GPIO W1C

env: host
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
  1. Update individual 2-bit CCM_CCGRx clock-gate slots (index in 0..15, mode in 0..3) without disturbing the remaining 15 peripheral gates in the 32-bit word.
  2. Validate per-pad MUX_MODE[3:0] legality against a uint16_t allowed bitmask while orthogonally encoding SION (bit 4, 0x10U) in pad_mux().
  3. Decode IOMUXC_SW_PAD_CTL bias states (0 disabled when PKE == 0, 1 keeper when PKE == 1 && PUE == 0, 2 pull when PKE == 1 && PUE == 1) in bias_mode().
  4. Repair write-1-to-clear (W1C) interrupt acknowledgment (acknowledge) and GPIOx_ICR1/ICR2 2-bit register/shift indexing (icr_field) across pins 0..31.
3. Environment Requirements
  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) inside labs/lab_m03_iomuxc_gpio_mmio/.
  • Target Silicon Alignment: Bit positions match i.MX6ULL CCM_CCGR0..6 (2 bits per CG), IOMUXC_SW_MUX_CTL_PAD_* (MUX_MODE[3:0], SION[4]), IOMUXC_SW_PAD_CTL_PAD_* (PKE[12], PUE[13]), and GPIO1..GPIO5 (ICR1 pins 0..15, ICR2 pins 16..31, ISR W1C).
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 physical target hardware required for automated TAP grading).
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
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() rejects index >= 16U || mode > 3U and updates shift = index * 2U (CG13 -> bits 27:26 = 0x0c000000U in tests.c case 1). pad_mux() rejects alt > 8U before shifting UINT16_C(1) << alt, checks (allowed & (UINT16_C(1) << alt)) != 0U, and writes (*r & ~UINT32_C(0x1f)) | alt | (sion ? 0x10U : 0U) (0x15U for ALT5 + SION).
  • bias_mode & icr_field (core.c:13-17, 22-26): bias_mode() checks PKE (bit 12) first -- returning 0U even if PUE (bit 13) is 1 (1U << 13 in tests.c:25), 1U for 0x10b0U (keeper), and 2U for 0x1b000U (pull). icr_field() maps pin / 16U to ICR1 (0) vs ICR2 (1) and (pin % 16U) * 2U to the even shift (pin 15 -> reg 0, shift 30; pin 16 -> reg 1, shift 0).
  • Seeded Flaw in starter/core.c:18-21 (acknowledge): starter computes return pending & ~(pending | mask); -- the exact state transition produced on hardware when buggy code executes GPIO1->ISR |= mask (writing pending | mask to a W1C register clears pending | mask, always leaving 0U!).
  • Verified Repair in files/core.c:18-21: Replaces the body with return pending & ~mask;, modeling a direct GPIO1->ISR = mask store that clears only mask (0x8U) and leaves concurrent pending bit 1 (0x2U) intact (acknowledge(0xaU, 8U) == 2U).
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m03-l03
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/5
8. 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
  1. Missing PKE Master-Enable Check (bias_mode): Change bias_mode() in a scratch copy to inspect PUE (bit 13) without first testing PKE (bit 12): tests.c:25 (bias_mode(1U << 13)) returns 2U (pull) instead of 0U (disabled), mirroring the real datasheet trap where PUE is ignored whenever PKE == 0.
  2. Upper-Bank Modulo Omission (icr_field): Replace (pin % 16U) * 2U with pin * 2U: pin = 16U computes shift = 32U (an out-of-range shift width on GPIOx_ICR2 instead of shift = 0U at ICR2[1:0]).
  3. SION Cleared by Narrow Mux Mask: Change ~UINT32_C(0x1f) to ~UINT32_C(0x0f) in pad_mux(), call pad_mux(&r, 5U, true, 0x21U) followed by pad_mux(&r, 0U, false, 0x21U), and observe stale SION (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 p50Host p95Host p99Cortex-A7 @ 528 MHz Hardware Equivalent
Full sh check.sh (make -B + gcc link + 4 cases)135.10 ms151.49 ms154.74 msHost toolchain + shell subshell orchestration
verify 4-case helper suite (verify 1..4)3554.3 us4110.7 us4220.6 us< 2 us in-cache register-helper calls
Direct W1C STR (GPIO1->ISR = mask) vs RMW1 store vs 1 load + 1 store1 store1 storeSaves 1 IPG bus read (~30 - 50 ns) and prevents race loss
11. Troubleshooting
SymptomRoot CauseFix
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 > 8UGuard `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 > 3UCompute shift = index * 2U and guard index < 16U && mode <= 3U
12. Guided Questions
  1. Why is a direct W1C store (GPIO1->ISR = (1U << 3)) race-free even if hardware latches bit 1 on the exact IPG clock cycle just before the STR lands, whereas a normal RMW register requires interrupt masking?
  • *Hint 1:* Inspect every bit position k != 3 in the 32-bit value 0x00000008U written onto the peripheral data bus.
  • *Hint 2:* Under the hardware W1C contract, what effect does writing 0 to bit 1 have on the ISR[1] flip-flop?
  1. When does an i.MX6ULL peripheral pin require SION = 1 (bit 4 of IOMUXC_SW_MUX_CTL_PAD_*) in addition to selecting the right MUX_MODE?
  • *Hint 1:* Compare an output-only indicator pad against an open-drain I2C SCL/SDA pad or a GPIO output loopback check via GPIOx_PSR.
  • *Hint 2:* What happens to the pad's input path when the selected mux function drives the pad purely as an output unless SION forces the input buffer active?
13. Independent Challenges
  1. Near Transfer — Complete IOMUXC_SW_PAD_CTL Encoder/Verifier: Add bool build_pad_ctl(bool hys, unsigned pus, bool pue, bool pke, bool ode, unsigned speed, unsigned dse, bool sre, uint32_t *out) that rejects pus > 3U || speed > 3U || dse > 7U, packs bits 16, 15:14, 13, 12, 11, 7:6, 5:3, and 0, asserts (*out & ~0x0001F8F9U) == 0U, and verifies bias_mode(*out) agrees with (pke, pue).
  2. Far Transfer — Full ICR1/ICR2 Trigger-Type Configurator (gpio_set_irq_trigger): Implement bool gpio_set_irq_trigger(uint32_t *icr1, uint32_t *icr2, uint32_t *edge_sel, unsigned pin, unsigned trig) supporting LOW_LEVEL (0), HIGH_LEVEL (1), RISING_EDGE (2), FALLING_EDGE (3), and BOTH_EDGES (4) (remembering that EDGE_SEL[pin] = 1 overrides ICR1/ICR2 on i.MX6ULL!).
14. Solutions & Explanations
  • Guided Question 1: Writing 0x00000008U places 0 on bits [31:4] and [2:0]; under W1C hardware logic (next_ISR = (ISR & ~bus_write) | new_hw_edges), 0 bits are unconditional no-ops, so no read occurs and concurrent hardware edges on bit 1 cannot be overwritten.
  • Guided Question 2: SION = 1 forces the pad's input path active regardless of the output mux direction, allowing I2C controllers to monitor bus arbitration/clock-stretching on SDA/SCL and allowing software to read actual physical pad voltage back through GPIOx_PSR.
  • Challenge 2 Key Logic: Route pin < 16U to icr1 and pin >= 16U to icr2 via icr_field(pin, &reg, &shift); if trig == 4U, set *edge_sel |= (UINT32_C(1) << pin), otherwise clear *edge_sel &= ~(UINT32_C(1) << pin) and write trig & 3U into (reg == 0U ? icr1 : icr2) at shift.

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-only GPIOx_PSR (+0x08) samples physical pad state; preload DR inactive before setting GDIR on active-low loads.
  • GPIOx_ICR1 (+0x0C) configures 2-bit triggers for pins 0..15 and GPIOx_ICR2 (+0x10) configures pins 16..31 at local shift 2 * (pin % 16).
  • GPIOx_IMR (+0x14) masks interrupt propagation while GPIOx_ISR (+0x18) latches trigger events.
  • GPIOx_ISR is 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

1

Step 1 (Output Latch): Preload inactive high DR[3] = 1 (+0x00) + DSB SY before enabling output direction.

reveals: step1

highlights: step1

2

Step 2 (Direction): Set GDIR[3] = 1 (+0x04) via masked RMW so all 31 neighboring pins keep their directions.

reveals: step2

highlights: step2

3

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

4

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

GL-E01lesson 10/18free preview~20 min

4.1 Boot Straps, eFUSE Selection, and Internal OCRAM

What you'll learn
  • Decode all BOOT_MODE values without treating a reserved value as a recovery mode.
  • Distinguish strap-selected media policy from fuse-selected policy.
  • Place pre-DDR work in an explicitly reserved OCRAM region rather than uninitialized external RAM.

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:

  1. Post-reset pin reuse is safe, but reset-time load contention is fatal: Once POR_B rises, firmware can freely re-mux LCD_DATA00..23 to drive an RGB panel without altering the already-latched SRC_SBMR1 flip-flops. Conversely, soldering an unbuffered 1 kOhm external pull-up or active sensor output onto an LCD_DATA trace overpowers the 47 kOhm board strap during POR_B, latching the wrong boot medium before your code ever executes!
  2. Moving a DIP switch while power stays on does nothing: Flipping BOOT_MODE switches changes live pad voltage, not SRC_SBMR2. Only asserting a fresh POR_B reset 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!
fig_m04_l01_a.svg — POR_B rising-edge strap capture circuit (top) and the…

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:

ast_m04_l01.svg — Separate reset-latched boot policy and ROM-reserved low…step 1/4
  1. 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.
  2. Step 2. Step 2: ROM decodes BMOD[1:0] (00 Fuse, 01 SDP recovery, 10 Internal via straps or eFUSEs, 11 Reserved).
  3. Step 3. Step 3: Pre-DDR code executes only inside unreserved OCRAM [0x00907000, 0x00920000), sparing ROM workspace.
  4. 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.

fig_m04_l01_b.svg — Exact 32-bit bitfields of SRC_SBMR2 and SRC_SBMR1…

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 MechanismRegister / Address EncodingReset-Time PreconditionFailure Boundary When Misapplied
BMOD = 10, BT_FUSE_SEL = 0SBMR2[25:24] = 2, [4] = 0LCD_DATA strap pulls undisturbed at POR_BStrong 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 trainingJumping 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
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. */
  1. Qualify 0x020D801C as volatile const uint32_t * so hardware status reads are never optimized away and writes fail compilation.
  2. 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
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;    }
  1. Decode BMOD[1:0] (SBMR2[25:24]) and BT_FUSE_SEL (SBMR2[4]), explicitly rejecting reserved BMOD == 3.
  2. Classify BOOT_CFG1[7:4] (SBMR1[7:4]) into SD/eSD, MMC/eMMC, NAND, QSPI, or NOR/EIM when straps drive internal boot.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m04-l01
learner@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_CFG pin straps
  • [ ] It ignores eFUSEs whenever BMOD == 2 and reads live LCD_DATA pin voltages continuously
  • [ ] It boots an application permanently stored inside on-chip OCRAM without 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_sbmr2 because const disables volatile hardware reads
  • [ ] IOMUXC pad-mux registers must be cleared from main() before DIP switches connect to SRC
  • [x] Boot strap pads are captured at the reset sampling edge (POR_B); moving switches afterward does not retroactively update latched SBMR flip-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)?

  • [ ] OCRAM requires MMDC DDR3 write-leveling calibration on its lower 28 KiB bank
  • [x] The active Boot ROM reserves low OCRAM ([0x00900000, 0x00907000)) for its own stack, SDP buffers, and handoff state
  • [ ] Cortex-A7 SVC mode cannot address physical memory below 0x00907000

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]) selects 00 Fuse Boot, 01 USB/UART Serial Downloader (SDP recovery), 10 ROM-directed Internal Boot, or 11 Reserved (invalid).
  • Under Internal Boot (10), BT_FUSE_SEL (SBMR2[4]) chooses between reset-sampled BOOT_CFG pin straps (SRC_SBMR1) and permanent eFUSE configuration.
  • Strap pads (BOOT_MODE and LCD_DATA00..23) are latched on the rising edge of POR_B; post-reset peripheral pin reuse cannot alter SBMR1/SBMR2, whereas external loads during reset can corrupt media selection.
  • Internal 128 KiB OCRAM ([0x00900000, 0x00920000)) operates immediately before external DDR3 initialization, 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

1

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

2

Step 2: ROM decodes BMOD[1:0] (00 Fuse, 01 SDP recovery, 10 Internal via straps or eFUSEs, 11 Reserved).

reveals: step2

highlights: step2

3

Step 3: Pre-DDR code executes only inside unreserved OCRAM [0x00907000, 0x00920000), sparing ROM workspace.

reveals: step3

highlights: step3

4

Step 4: ROM validates the boot image on the selected medium (or falls back to USB/UART SDP on failure).

reveals: step4

highlights: step4

GL-E01lesson 11/18free preview~20 min

4.2 IVT, Boot Data, and SD/eMMC Offset Geometry

What you'll learn
  • Decode the D1 00 20 40 IVT bytes without confusing mixed byte-order fields.
  • Translate SD/eMMC media offset 0x400 into compact-file and runtime coordinates.
  • Validate IVT self, entry, and Boot Data pointers against a stated image layout.

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:

  1. Storage Media Coordinate (M, origin = card byte 0x0000): MBR occupies 0x0000..0x03FF (LBA 0..1), IVT sits at M = 0x0400 (LBA 2), Boot Data sits at M = 0x0420, DCD starts at M = 0x042C, and our application _start payload (P bytes) sits at M = 0x1000 (LBA 8).
  2. Compact .imx File Coordinate (F = M - 0x0400, origin = IVT byte 0): Because dd seek=2 bs=512 skips the first 1024 B on the card, a compact .imx file omits 0x0000..0x03FF completely! File offset F = 0x0000 is the IVT, F = 0x0020 is Boot Data, F = 0x002C is DCD, and the payload sits at F = 0x1000 - 0x0400 = 0x0C00 (3072 B)—never 0x1000!
  3. Runtime Memory Coordinate (R = BootData.start + M = IVT.self + F): For an entry point linked at R = 0x87800000 (M = 0x1000), BootData.start equals 0x87800000 - 0x1000 = 0x877FF000, placing IVT.self at 0x877FF000 + 0x0400 = 0x877FF400, Boot Data at 0x877FF420, and BootData.length at 0x1000 + P (0x1010 when P = 16 B, even though the compact .imx file is 0x0C10 bytes!).
fig_m04_l02_a.svg — Exact alignment between SD/eMMC media offsets (M),…

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:

ast_m04_l02.svg — Name the coordinate origin (media M, compact file F, or…step 1/4
  1. Step 1. Step 1: Anchor SD/eMMC media coordinates at M_ivt = 0x0400 (LBA 2, sparing MBR) and M_payload = 0x1000 (LBA 8).
  2. Step 2. Step 2: Subtract 0x0400 for the compact .imx file: IVT at F = 0x0000, Boot Data at 0x0020, payload at F = 0x0C00.
  3. Step 3. Step 3: Map runtime RAM from BootData.start = 0x877FF000 so IVT.self = 0x877FF400 and IVT.entry = 0x87800000.
  4. 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.

fig_m04_l02_b.svg — Byte-accurate anatomy of the 32-byte IVT and 12-byte…

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 RegionSD/eMMC Media MCompact .imx FRuntime Address R (start = 0x877FF000)Size & Byte-Order Rule
MBR / Partition Table0x0000..0x03FF (LBA 0..1)Omitted (dd seek=2 bs=512)0x877FF000..0x877FF3FF1024 B skipped in .imx
IVT (image_ivt)0x0400 (LBA 2)0x00000x877FF400 (IVT.self)32 B (BE16 len, LE32 ptrs)
Boot Data + DCD0x0420 / 0x042C0x0020 / 0x002C0x877FF420 / 0x877FF42C12 B LE32 + DCD (BE)
Application _start0x1000 (LBA 8)0x0C000x87800000 (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
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
  1. Emit D1 00 20 40 as explicit bytes so big-endian length 0x0020 and little-endian word 0x402000D1 are unambiguous.
  2. Store image_ivt (0x877FF400) in self (+0x14) and strictly zero reserved1 (+0x08), csf (+0x18), and reserved2 (+0x1C).
  3. 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
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;    }
  1. Emit D1 00 20 40 explicitly so big-endian length 32 and little-endian 0x402000D1 agree on every host.
  2. Enforce reserved1 == 0, reserved2 == 0, and self == boot_start + 0x400 (the IVT runtime address, not file offset 0).
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m04-l02
learner@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 origin 0
  • [ ] File offset 0x1400, because 0x0400 and 0x1000 add together
  • [x] File offset 0x0C00, after subtracting the omitted 0x0400 (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 length 8192 (0x2000), version 0x40 -> word 0xD1002040
  • [x] Tag 0xD1, big-endian length 32 (0x0020), version 0x40 -> little-endian word 0x402000D1
  • [ ] Tag 0x40, big-endian length 32 (0x0020), version 0xD1 -> word 0x402000D1

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 the IVT itself lands (start + 0x0400)
  • [ ] 0x00000000, because the IVT sits at byte 0 of the compact .imx file
  • [ ] 0x00000002, the starting 512-byte LBA sector index on the SD card

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

  • IVT header bytes D1 00 20 40 encode tag 0xD1, big-endian 16-bit length 32 (0x0020), and version 0x40, which read as 0x402000D1 in a 32-bit little-endian ARM word.
  • On SD/eMMC media, placing the IVT at media offset 0x0400 (1 KiB, LBA 2 across 512-byte sectors) preserves LBA 0..1 partitioning structures.
  • Translating any media offset M >= 0x0400 into a compact .imx file yields F = M - 0x0400 (0x1000 -> 0x0C00), while runtime addresses follow R = BootData.start + M = IVT.self + F.
  • IVT pointers (entry, dcd, boot_data, self) and Boot Data (start, length, plugin) serialize as little-endian 32-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

1

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

2

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

3

Step 3: Map runtime RAM from BootData.start = 0x877FF000 so IVT.self = 0x877FF400 and IVT.entry = 0x87800000.

reveals: step3

highlights: step3

4

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

GL-E01lesson 12/18free preview~20 min

4.3 DCD Commands and a Checked C11 .imx Packer

What you'll learn
  • Encode big-endian DCD lengths, addresses, values, and masks.
  • Reject truncated or zero-length Write, Check, and NOP commands.
  • Construct a compact .imx artifact with independently checked IVT and payload offsets.

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)!

  1. Table Header (0xD2): [0xD2, len_hi, len_lo, 0x40], where big-endian total_len (4 <= total_len <= 1768 B) includes the 4-byte 0xD2 header itself.
  2. Write Data (0xCC): [0xCC, cmd_len_be16, param] followed by k >= 1 big-endian (addr32, val_or_mask32) pairs (cmd_len = 4 + 8 * k). In param, bits [2:0] select access width (1, 2, or 4 bytes) and bits [4:3] select plain write (00), clear-mask (01), or set-mask (10).
  3. Check Data (0xCF) & NOP (0xC0): 0xCF polls a status register (param = 0x0C checks (*addr & mask) == mask on 4-byte width; cmd_len = 12 unbounded or 16 with a big-endian count32 timeout), while 0xC0 is [0xC0, 0x00, 0x04, 0x00]. If a packer accidentally writes 0x020C406C (CCM_CCGR1) with put_le32(), the ROM reads big-endian 0x6C400C02—outside its permitted peripheral whitelist—and aborts straight into USB Serial Downloader!
fig_m04_l03_a.svg — Inside the 36-byte big-endian DCD stream (top), why…

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:

ast_m04_l03.svg — Keep LE32 IVT pointers and BE16/BE32 DCD commands…step 1/4
  1. Step 1. Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.
  2. Step 2. Step 2: Validate every CC, CF, and C0 subcommand length >= 4 and <= total - at before advancing the cursor.
  3. Step 3. Step 3: Assemble (0x00 LE), Boot Data (0x20 LE), DCD (0x2C BE), and payload (0x0C00) into verified.imx.
  4. 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).

fig_m04_l03_b.svg — Exact byte map of verified.imx (3088 B) and the…

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 StrategyExecuted BySize & Capability LimitOperational Trade-Off
Static DCD stream (0xD2)Internal Boot ROM<= 1768 B (<= 220 coalesced pairs); ROM whitelist onlySimple single-stage .imx; cannot probe RAM size or I2C PMICs
U-Boot SPL in OCRAMCortex-A7 (0x00908000)~100 KiB OCRAM; full C11 control flow & UART logsProduction standard in U-Boot 2025.x; supports dynamic DDR3 training
Unbounded Check Data (len = 12)Internal Boot ROMPolls *addr & mask forever with zero timeoutWedges pre-console boot permanently if a PLL/PHY bit fails to lock
Bounded Check Data (len = 16)Internal Boot ROMPolls up to big-endian count iterationsAborts cleanly into SDP recovery when hardware readiness times out
learner@ksa: ~/gl-e01/m04-l03
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) }    }
  1. Place .ivt and .dcd at image_load_base + 0x400 (0x877FF400), matching SD/eMMC LBA 2.
  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
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;    }
  1. Use big-endian helpers for DCD lengths, register addresses, values, and poll counts, never put_le32().
  2. Reject len < 4 or len > total - at before advancing so a zero-length command cannot cause an infinite loop.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m04-l03
learner@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 4 bytes past the subcommand header and continue scanning
  • [x] Reject the DCD stream immediately before advancing or dispatching any command
  • [ ] Treat length 0 as a NOP (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, following DCD's big-endian address and value specification
  • [ ] 6C 40 0C 02, matching the little-endian IVT.entry pointer format
  • [ ] 0C 02 6C 40, swapping 16-bit halfwords for ARM Thumb 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 DDR3 memory chip soldered to any i.MX6ULL board will calibrate and run reliably
  • [ ] That the 16-byte "FORMAT-FIXTURE!!" payload is valid ARMv7-A machine code
  • [x] That IVT, Boot Data, DCD big-endian framing, and 0x0C00 compact-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.

Lab 4: Mixed-Endian Boot Image Packing — Little-Endian IVT vs Big-Endian DCD

env: host
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
  1. Serialize and parse 32-bit little-endian IVT and Boot Data pointers (entry = 0x87800000, boot_data = 0x877FF420, self = 0x877FF400, start = 0x877FF000, length = 0x1010) without host-alignment traps.
  2. Validate big-endian DCD blocks (0xD2 header, 16-bit total length <= 1768 B, 0xCC Write Data, 0xCF Check Data, and 0xC0 NOP subcommands) in dcd_valid().
  3. Reconcile compact .imx file offsets (IVT at 0x0000, payload at 0x0C00) with raw SD/eMMC card geometry (0x0400 LBA 2 leading gap -> payload at 0x1000 in target RAM).
  4. Preserve caller output buffers untouched when pack_image() rejects insufficient capacity < 0x0C10U.
3. Environment Requirements
  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) inside labs/lab_m04_ivt_dcd_image/.
  • Target Boot ROM Contract: Matches i.MX6ULL Boot ROM v0x40 IVT (32 bytes), Boot Data (12 bytes), DCD (<= 1768 bytes, big-endian byte stream), and SD/eMMC 1 KiB (0x400) offset rules.
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils / hex tools (nm, od or hexdump).
  • Hardware: Standard Linux workstation (0 SD cards or physical Cortex-A7 boards required; dd seek=2 bs=512 applies 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
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): starter writes p[i] = (unsigned char)(value >> (8U * (3U - i))); -- serializing most-significant byte first (big-endian) while get_le32() (lines 7-11) reconstructs p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24) (little-endian)!
  • Verified Repair in files/core.c:3-6: Changes the shift to p[i] = (unsigned char)(value >> (8U * i)); so 0x87800000U writes [0x00, 0x00, 0x80, 0x87] at out + 4, 0x877ff420U at out + 16 (boot_data), 0x877ff400U at out + 20 (self), 0x877ff000U at out + 32 (Boot Data.start), and 0x1010U at out + 36 (Boot Data.length).
  • dcd_valid (core.c:16-34): Verifies p[0] == 0xd2U && p[3] == 0x40U and big-endian total = be16(p + 1) in [4, 1768] and <= n, then walks every command record checking subtraction bound len <= total - at and legal command shapes: Write Data (0xcc, param == 4, len >= 12, (len - 4) % 8 == 0), Check Data (0xcf, param == 0x0c, len == 16), or NOP (0xc0, param == 0, len == 4).
  • pack_image (core.c:35-44): Rejects capacity < 0xc10U before memset(out, 0, 0xc10U), writes IVT header bytes [0xd1, 0x00, 0x20, 0x40] directly at out[0..3], populates IVT and Boot Data pointers, and places the 16-byte "FORMAT-FIXTURE!!" payload at out + 0xc00 (self + 0xc00 = 0x87800000).
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m04-l03
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/5
8. 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
  1. Zero-Length DCD Subcommand Infinite-Loop Trap: Remove len < 4U on core.c:25 in a scratch copy and run tests.c case 3 (which mutates d[6] = 0U at line 29 so be16(p + 5) == 0): without len >= 4U, at += 0 spins forever inside while (at < total)!
  2. ROM 1768-Byte DCD Ceiling Breach: Construct an otherwise valid 1772-byte DCD buffer (0xD2, 0x06, 0xEC, 0x40 + 442 NOP records) and confirm dcd_valid() rejects total > 1768U just as the i.MX6ULL Boot ROM does.
  3. Host Unaligned-Pointer Cast vs Bytewise put_le32: Compile tests.c and files/core.c with -fsanitize=undefined,address and verify bytewise put_le32(p + 1, ...) never triggers an unaligned uint32_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 p50Host p95Host p99Cortex-A7 / Boot ROM Context
Full sh check.sh (make -B + gcc link + 4 cases)136.50 ms156.61 ms160.90 msHost build & test-runner latency
verify 4-case .imx / DCD suite (verify 1..4)3530.6 us4584.0 us5507.5 usHost validation of 3088 B .imx + 36 B DCD
Boot ROM SD read of 4112 B (~9 sectors @ 25 MHz)Modeled in RAMModeled in RAMModeled in RAM~350 - 900 us SPI/SDHC transfer + DCD MMIO writes
11. Troubleshooting
SymptomRoot CauseFix
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 RAMWrote 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] = 0Udcd_valid() accepted len == 0U and failed to advance atEnforce `if (len < 4U \\len > total - at) return false;`
.imx written at byte 0 of SD card wipes MBR & fails bootConfused compact .imx (starts at 0x400) with full disk imageFlash .imx with dd bs=512 seek=2 conv=fsync (1024-byte offset)
12. Guided Questions
  1. Why does pack_image() store length = 0x1010U (sizeof image + 0x400U) inside Boot Data at out + 36 even though the .imx buffer itself is only 0x0C10U (3088) bytes long?
  • *Hint 1:* Compute self - start (0x877FF400 - 0x877FF000 = 0x400) and inspect where byte 0 of the SD/eMMC card lands in target DDR when the Boot ROM copies from LBA 0.
  • *Hint 2:* Add the 0x400-byte leading media gap (LBA 0..1) to the 0x0C00-byte IVT-to-entry span (0x87800000 - 0x877FF400) plus the 0x10-byte payload (0x400 + 0xC00 + 0x10).
  1. Why do put_le32() and get_le32() operate on unsigned 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 (p need not be 4-byte aligned).
  • *Hint 2:* What would *(uint32_t *)p = value emit if the host packer were compiled on a big-endian build server?
13. Independent Challenges
  1. Near Transfer — Embedded DCD Pointer Integration (pack_image_with_dcd): Write bool pack_image_with_dcd(unsigned char *out, size_t cap, const unsigned char *dcd, size_t dcd_len) that validates dcd via dcd_valid(), places dcd at out + 0x40 (0x877FF440 in RAM, safely clear of IVT [0x00..0x1F] and Boot Data [0x20..0x2B]), and writes 0x877FF440U into IVT.dcd (out + 8) only when dcd != NULL.
  2. Far Transfer — .imx Binary Dissector & Consistency Auditor: Build a standalone C11 tool that reads a packed .imx image and checks IVT header D1 00 20 40, self > start, boot_data == self + 0x20, dcd == 0 || dcd_valid(...), and entry >= self + 0x40 && entry < start + length.
14. Solutions & Explanations
  • Guided Question 1: Boot Data.start (0x877FF000) represents the destination of byte 0 of the boot medium (0x400 bytes below IVT.self = 0x877FF400), so Boot Data.length must cover the initial 0x400 media offset plus the entire .imx file (0x0C10), totaling 0x1010 bytes (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 via dcd_valid's 1768U cap) before memcpy(out + 0x40, dcd, dcd_len) and put_le32(out + 8, 0x877ff440U).

Run locally in your terminal and check off each verification milestone.

Not started

Summary

  • A DCD table begins with [0xD2, len_be16, 0x40], where total_len (4 <= total_len <= 1768 B) includes the 4-byte header itself.
  • Write Data (0xCC), Check Data (0xCF), and NOP (0xC0) serialize all 16-bit lengths and 32-bit addresses, values, masks, and counts in big-endian order—distinct from little-endian IVT pointers.
  • Bounded parsers must verify len >= 4 and len <= total - at before advancing, preventing zero-length infinite loops and buffer overruns.
  • Structural .imx validation proves container framing and 0x00 / 0x20 / 0x2C / 0x0C00 offsets, never board-specific DDR3 calibration.
  • 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

1

Step 1: Emit DCD header [0xD2, BE16(total), 0x40] where 4 <= total <= 1768 includes the 4-byte header.

reveals: step1

highlights: step1

2

Step 2: Validate every CC, CF, and C0 subcommand length >= 4 and <= total - at before advancing the cursor.

reveals: step2

highlights: step2

3

Step 3: Assemble IVT (0x00 LE), Boot Data (0x20 LE), DCD (0x2C BE), and payload (0x0C00) into verified.imx.

reveals: step3

highlights: step3

4

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

GL-E01lesson 13/18free preview~20 min

5.1 start.S, SVC Entry, Data Copy, and BSS Initialization

What you'll learn
  • Establish an aligned SVC stack before calling any C function.
  • Copy the linked .data initialization span when its load and execution addresses differ.
  • Zero exactly the linker-defined .bss range without damaging adjacent state.

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:

  1. No valid C stack exists yet (SP_svc is unknown): If your very first C function pushes {r4, lr} (stmfd sp!, {r4, lr}) or spills a 64-bit integer (strd, requiring 8-byte AAPCS stack alignment), an uninitialized or 4-byte-misaligned SP corrupts random memory or triggers an alignment Data Abort!
  2. .data initializers may sit at a different Load Memory Address (LMA) than their runtime Virtual Memory Address (VMA): When .data is linked at VMA 0x87810000 (__data_start) while its initial bytes {1..8} are packed right after .rodata at LMA 0x87800090 (__data_load), 0x87810000 still holds random DDR3 power-on bit patterns (0xA5A5A5A5) until startup copies [__data_load, __data_load + len) to __data_start!
  3. .bss occupies zero file bytes (SHT_NOBITS): Uninitialized globals (static int g_err_cnt;) have no zero bytes stored in bsp.bin. Unless startup explicitly writes 0 across [__bss_start, __bss_end), every if (g_err_cnt == 0) check in C reads random DDR3 charge!
fig_m05_l01_a.svg — CPSR Supervisor/interrupt-mask configuration (top) and…

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:

ast_m05_l01.svg — Never execute a C call before SP_svc, .data relocation,…step 1/4
  1. Step 1. Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or -trained DDR3 already backing RAM.
  2. Step 2. Step 2: Mask IRQ/FIQ (0xC0) in SVC mode (0x13) via CPSR RMW, then load 8-byte-aligned SP = __stack_top.
  3. Step 3. Step 3: Copy [__data_load, +size) to __data_start and zero [__bss_start, __bss_end) with pre-checked loops.
  4. 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 (cmp before str) handles 0-byte sections: When .bss is empty (__bss_start == __bss_end), cmp r0, r1 sets C = 1, Z = 1 and bhs 4f exits immediately with zero stores—whereas a post-checked do..while loop overwrites 4 bytes past __bss_end!
  • Exclusive upper bound (bhs, not bhi): Linker end symbols (__data_end, __bss_end) mark the first byte after the section ([start, end)), so r0 == r1 must stop immediately without clobbering the neighbor at [end].
  • Unsigned (bhs, not signed bge): DDR3 addresses at 0x87800000 have bit 31 == 1 (negative if misinterpreted as signed int32_t!); unsigned carry flags order the full 0x00000000..0xFFFFFFFF physical map monotonically.
fig_m05_l01_b.svg — Pre-checked unsigned half-open [start, end) word loops…

Figure 5.1b. Pre-checked unsigned half-open [start, end) word loops (left) contrasted against three classic bare-metal startup bugs (right).

Startup Implementation DetailInstruction SequenceEmpty / Boundary BehaviorDefect When Violated
Pre-checked unsigned loopcmp r0, r1 -> bhs done -> str0 stores when start == end; stops at endProduction safe across 0..4 GiB
Post-checked loop (do..while)str -> cmp r0, r1 -> blo loopWrites 4 B when start == end!Corrupts word at __bss_end on empty .bss
Inclusive upper bound (<=)cmp r0, r1 -> bhi doneWrites 1 extra word past end every boot!Silently zeroes first word of .stack/.rodata
Early bl before ldr spbl debug_led at line 1 of _startPushes {r4, lr} to wild/unaligned SP_svcImmediate Data Abort or Boot ROM/RAM corruption
learner@ksa: ~/gl-e01/m05-l01
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
  1. Establish 8-byte-aligned SP_svc AFTER masking IRQ/FIQ in SVC mode and BEFORE any bl call.
  2. Pre-checked unsigned bhs handles start == end cleanly and stops before exclusive __data_end / __bss_end.
  3. 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
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;    }
  1. Compute _etext, __data_load (LMA), __data_start.._edata (VMA), [__bss_start, __bss_end), and 8-byte aligned __stack_top.
  2. Require 8-byte AAPCS32 stack alignment and non-overlap above __bss_end before copying .data or zeroing .bss.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m05-l01
learner@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-objcopy during binary extraction
  • [ ] AAPCS requires passing zero-initialized globals in r0..r3
  • [x] start.S failed to zero the complete linker-defined [__bss_start, __bss_end) runtime range before bl 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 DDR3 requires 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 AAPCS stores local stack variables between __data_load and __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 misaligned SP_svc
  • [ ] ARMv7-A forbids executing bl while IRQ and FIQ are masked in CPSR
  • [ ] UART1 registers are inaccessible from Supervisor (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 _start must mask IRQ/FIQ (0xC0), select SVC mode (0x13), and load a valid, reserved SP_svc = __stack_top before calling any C function.
  • AAPCS requires 8-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.S copies [__data_load, __data_load + size) before C reads writable globals.
  • Pre-checked unsigned cmp + bhs loops zero [__bss_start, __bss_end) cleanly without touching [__bss_end] or misfiring on 0-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

1

Step 1: Enter _start in 32-bit ARM privileged state with OCRAM or DCD-trained DDR3 already backing RAM.

reveals: step1

highlights: step1

2

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

3

Step 3: Copy [__data_load, +size) to __data_start and zero [__bss_start, __bss_end) with pre-checked loops.

reveals: step3

highlights: step3

4

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

GL-E01lesson 14/18free preview~20 min

5.2 GNU ld Scripts, VMA/LMA, and Linker Boundary Symbols

What you'll learn
  • Place the entry section and data spans explicitly with ENTRY and SECTIONS.
  • Compute VMA/LMA relocation and the serialized image extent.
  • Assert aligned non-overlapping BSS and stack boundaries.

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):

  1. Virtual Memory Address (VMA, queried via ADDR(.data)): The runtime execution address baked into C ldr/str instructions and bl branch targets. In Figure 5.2a, .text (128 B) and .rodata (16 B) execute at 0x87800000..0x87800090, while writable .data (8 B) is linked at VMA = 0x87810000.
  2. Load Memory Address (LMA, set via AT(__data_lma) and queried via LOADADDR(.data)): Where objcopy -O binary (and the Boot ROM) places the section's initial image bytes! If you link .data at 0x87810000 without AT(__data_lma), LMA defaults to VMA (0x87810000), forcing objcopy to zero-pad the entire 65,392-byte gap (0x87800090..0x87810000) and bloating bsp.bin from 152 B to 65,544 B! Adding AT(__data_lma) packs those 8 .data bytes snugly at 0x87800090 (152 B total .bin), while (NOLOAD) marks .bss and .stack as SHT_NOBITS (0 file bytes!).
fig_m05_l02_a.svg — Packed 152-byte LMA load image (left) versus sparse…

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:

ast_m05_l02.svg — Linker boundary symbols are an executable contract:…step 1/4
  1. Step 1. Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.
  2. Step 2. Step 2: Pack .data initializers at AT(__data_lma) while linking live globals at VMA 0x87810000.
  3. Step 3. Step 3: Define __bss_start and ALIGN(4)-rounded __bss_end inside a (NOLOAD) .bss section including *(COMMON).
  4. 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."

fig_m05_l02_b.svg — Why linker symbols must be declared as char arrays in 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 DirectiveEffect on bsp.elf / bsp.binRuntime / Packer ObligationDefect When Omitted
KEEP(*(.text.start)) at .text startPins _start at 0x87800000; survives --gc-sectionsIVT.entry must also store 0x87800000Helper function lands at 0x87800000 ahead of _start!
.data VMA : AT(__data_lma)Separates ADDR(.data) from LOADADDR(.data)start.S copies SIZEOF(.data) LMA -> VMA64 KiB+ zero-padding bloat in bsp.bin
(NOLOAD) on .bss and .stackEmits 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/misalignSync ceiling (0x87900000) with board RAM mapSilent stack/.bss overlap or AAPCS alignment fault
learner@ksa: ~/gl-e01/m05-l02
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")    }
  1. Pin .text.start at 0x87800000 with KEEP() so neither link order nor --gc-sections displaces _start.
  2. Export LOADADDR(.data) as __data_load and compute __image_load_end for BootData.length validation.
  3. 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
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;    }
  1. Accept only power-of-two alignments and guard value <= UINT32_MAX - add before rounding up.
  2. Require I|F masked (0xC0) and word-aligned [bss_start, bss_end) boundaries matching the 4-byte zero loop.
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m05-l02
learner@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-A7 hardware aliases LMA and VMA
  • [x] 0x87810000 (VMA), after start.S copies the initial bytes from 0x87800090 (LMA)
  • [ ] 0x87800090 (LMA) for reads and 0x87810000 (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) .bss output section, with . = ALIGN(4); immediately before __bss_end = .;
  • [ ] Before .data so a single zeroing loop clears both .data and .bss
  • [ ] Outside .bss before ALIGN(16) so unaligned bytes in .data are 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.MX6ULL Boot ROM parses ELF headers directly from LBA 2
  • [ ] Yes; objcopy -O binary prepends a 32-byte IVT whenever ENTRY(_start) is present
  • [x] No; objcopy -O binary strips ELF metadata, so .section .ivt or the .imx packer must explicitly write _start's runtime address into IVT.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) plus KEEP(*(.text.start)) at the start of .text pins the reset entry point at 0x87800000 and protects it from --gc-sections.
  • The location counter . tracks current VMA, while ALIGN(n) rounds upward to power-of-two boundaries without advancing already-aligned addresses.
  • .data VMA : AT(LMA) separates runtime ADDR(.data) from packed LOADADDR(.data), preventing multi-kilobyte zero-padding bloat in objcopy -O binary outputs while (NOLOAD) omits .bss and .stack bytes.
  • Linker boundary symbols (__bss_start, __bss_end, __stack_top) encode addresses in .symtab (never allocated C pointer variables) and pair with ASSERT(...) 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

1

Step 1: Set ENTRY(_start) and place KEEP(*(.text.start)) first in .text so _start stays pinned at 0x87800000.

reveals: step1

highlights: step1

2

Step 2: Pack .data initializers at AT(__data_lma) while linking live globals at VMA 0x87810000.

reveals: step2

highlights: step2

3

Step 3: Define __bss_start and ALIGN(4)-rounded __bss_end inside a (NOLOAD) .bss section including *(COMMON).

reveals: step3

highlights: step3

4

Step 4: Reserve 8-byte-aligned banked stacks above .bss and guard alignment + RAM ceiling with ASSERT().

reveals: step4

highlights: step4

GL-E01lesson 15/18free preview~20 min

5.3 Struct-Mapped MMIO and Auditable SDK Header Adaptation

What you'll learn
  • Verify GPIO struct offsets with offsetof and static assertions.
  • Explain why volatile is neither an atomic update nor a CPU memory barrier.
  • Adapt register and pin identifiers through a narrow board wrapper without copying opaque policy.

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:

  1. Why __attribute__((packed)) breaks 32-bit peripheral registers: Adding packed drops alignof(struct gpio_regs) from 4 down to 1. Under -ffreestanding / -mno-unaligned-access, the compiler can no longer assume the struct base pointer is 4-byte aligned, so it decomposes gpio->DR = val into four 8-bit strb byte transactions! On i.MX6ULL IPS/AIPS peripheral bridges, many 32-bit control registers fault or corrupt state on narrow byte accesses. Always use natural 4-byte-aligned uint32_t members (explicit uint32_t _pad[N] arrays for address gaps) and prove every offset at compile time with _Static_assert(offsetof(...) == ...)!
  2. Why C bit-fields (uint32_t pin3 : 1;) break W1C and bus width: Bit-field bit ordering and storage-unit load width (ldrb vs ldr) are implementation-defined in ISO C11. Worse, gpio->ISR.pin3 = 1; compiles into ldr r1, [r0, #0x18] -> orr r1, #8 -> str r1, [r0, #0x18]—a read-modify-write on a W1C status register that wipes every concurrent pending interrupt in the bank!
fig_m05_l03_a.svg — Verified 32-byte struct gpio_regs layout (left) and why…

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:

ast_m05_l03.svg — Prove every struct offset with…step 1/4
  1. Step 1. Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.
  2. Step 2. Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.
  3. Step 3. Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.
  4. 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:

  1. soc_imx6ull.h: Pure silicon facts (0x0209C000U, 0x020C4000U).
  2. gpio_regs.h (target_m05_l03 below): struct gpio_regs with volatile const uint32_t PSR (turning accidental writes to read-only PSR into compile errors!), _Static_assert checks, and gpio_ack_mask() writing gpio->ISR = mask directly without RMW.
  3. board_led.h: Carrier pin (GPIO1_IO03) and active-low policy, exposing led_set(bool on) to main.c.
fig_m05_l03_b.svg — Why volatile RMW still loses concurrent updates without…

Figure 5.3b. Why volatile RMW still loses concurrent updates without serialization (top) and the three-tier SDK adaptation boundary (bottom).

Register Access StrategyEmitted ARM InstructionsOffset & Semantic SafetyEngineering Verdict
Aligned volatile uint32_t struct + _Static_assert + masks32-bit ldr / strCompile-time offset proof; explicit W1C vs RMWProduction bare-metal standard
Raw #define REG(a) (*(volatile uint32_t *)(a))32-bit ldr / strNo struct type safety across peripheral blocksMinimal start stubs only
C bit-fields (volatile uint32_t isr_3 : 1;)ldrb/strb or ldr+orr+strBroken: narrow bus faults + wipes sibling W1C IRQsNever use on MMIO
__attribute__((packed)) on 32-bit MMIO struct4 x ldrb / 4 x strbBroken: alignof == 1 splits 32-bit bus cyclesNever pack aligned MMIO
learner@ksa: ~/gl-e01/m05-l03
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
  1. Qualify PSR as volatile const uint32_t so hardware reads always execute while accidental C assignments fail to compile.
  2. Prove GDIR (+0x04), PSR (+0x08), ISR (+0x18), and total 32-byte struct size on every compilation.
  3. 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
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;    }
  1. Lock every 32-bit GPIO register offset at compile time via _Static_assert and offsetof.
  2. Verify .bin, compact .imx (+0x0C00), and Boot Data (+0x1000) spans from symbol-map addresses.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m05-l03
learner@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-aliasing so GCC repairs MMIO member 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 volatile instructs the compiler to cache DR inside r4 across function calls
  • [ ] Because volatile automatically emits ldrex/strex atomic loops that stall on MMIO memory
  • [x] Because gpio->DR |= mask still compiles into separate ldr and str instructions 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.

Lab 5: Linker Alignment, Exclusive .bss C-Runtime Init & GPIO Struct Geometry

env: host
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
  1. Verify 32-byte GPIO peripheral struct layout (psr at +8, isr at +24, sizeof == 32) at compile time using _Static_assert and offsetof.
  2. Round addresses upward to power-of-two boundaries in align_address() while rejecting 0, non-powers-of-two (3), and inputs exceeding UINT32_MAX - (alignment - 1U).
  3. Repair init_runtime() so .data relocation (memcpy) and .bss clearing (for (size_t i = bss_begin; i < bss_end; ++i)) honor half-open intervals, reject .data/.bss overlap, and leave surrounding sentinels untouched.
  4. 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) inside labs/lab_m05_lds_crt_sdk/.
  • Target Runtime Contract: Models GNU ld section bounds (__data_start, __bss_start, __bss_end), ARMv7-A 4/8-byte address alignment, and i.MX6ULL GPIO 0x00..0x1C register offsets.
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 physical target hardware required for TAP verification).
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
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 eight uint32_t registers (dr, gdir, psr, icr1, icr2, imr, isr, edge); tests.c enforces offsetof(psr) == 8U, offsetof(isr) == 24U, and sizeof == 32U at compile time before main() even links.
  • align_address (core.c:3-9): Rejects alignment == 0U || (alignment & (alignment - 1U)) != 0U, checks value > UINT32_MAX - add (add = alignment - 1U) so UINT32_MAX aligned to 8U fails without overwriting *out = 0x55U, and computes (value + add) & ~add.
  • Seeded Flaw in starter/core.c:17 (init_runtime): starter loops for (size_t i = bss_begin; i <= bss_end; ++i) ram[i] = 0U;. In GNU ld scripts (.bss : { __bss_start = .; *(.bss*) __bss_end = .; }), __bss_end is the first byte after .bss: when .bss is [24, 40), ram[40] belongs to the next section (or lies 1 byte past ram[63] when bss_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 .data overlapping non-empty .bss (data_at < bss_end && bss_begin < data_at + data_size), guards if (data_size != 0U) memcpy(...), and zeroes strictly for (size_t i = bss_begin; i < bss_end; ++i).
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m05-l03
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/5
8. 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
  1. Unchecked memcpy on Zero-Length .data at End of RAM: Pass data = NULL, data_size = 0U in a scratch test after removing if (data_size != 0U) before memcpy(ram + data_at, data, data_size) under -fsanitize=undefined: ISO C11 Section 7.24.1p2 forbids NULL pointers in memcpy even when the byte count is zero!
  2. Struct Member Insertion Caught at Compile Time: Insert uint32_t pad; between psr and icr1 in a scratch copy of core.h and run sh check.sh: check 1 fails immediately at compile time on _Static_assert(offsetof(struct gpio_model, isr) == 24U, "ISR").
  3. Unmasked value in data_update(): Rewrite data_update() as (old & ~mask) | value and run verify 4: data_update(0U, 0x80000000U, 0xffffffffU) returns 0xffffffffU instead of 0x80000000U.
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 p50Host p95Host p99Cortex-A7 @ 528 MHz Startup Cost
Full sh check.sh (make -B + gcc link + 4 cases)143.25 ms157.56 ms165.52 msHost compile + archive + test execution
verify 4-case runtime/SDK suite (verify 1..4)3524.5 us4305.9 us4863.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
SymptomRoot CauseFix
not ok 3 (ram[40] is 0U instead of 0xa5U).bss loop used inclusive i <= bss_endLoop 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)) == 0UReject `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 - addGuard 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
  1. Why does (alignment & (alignment - 1U)) == 0U (combined with alignment != 0U) identify powers of two across all 32-bit unsigned integers in O(1) time?
  • *Hint 1:* Write the binary representation of 2^k (0b001000) and 2^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 with n - 1?
  1. Why does an ARMv7-A _start assembly loop (cmp r0, r1 / blo 1b with str r2, [r0], #4) require . = ALIGN(4); on both __bss_start and __bss_end in the linker script?
  • *Hint 1:* Suppose .bss ends with a single char flag; so __bss_end - __bss_start == 5 bytes (__bss_end = 0x87810005).
  • *Hint 2:* Trace r0 stepping by +4 (0x87810000 -> 0x87810004 -> 0x87810008) under blo: how many bytes past 0x87810005 get zeroed on the second 4-byte STR?
13. Independent Challenges
  1. Near Transfer — Word-Wide init_runtime_aligned32(): Write a stricter startup verifier requiring data_at, data_size, bss_begin, and bss_end to be multiples of 4U (just like a 4-byte LDR/STR _start loop), performing 4-byte chunk operations and rejecting unaligned linker symbols cleanly.
  2. Far Transfer — Full .text + .rodata + .data (LMA != VMA) + .bss + IRQ/SVC Stack Solver: Implement bool solve_lds_layout(...) that computes _etext, __data_load (LMA), __data_start.._edata (VMA), [__bss_start, __bss_end), and 8-byte-aligned IRQ/SVC stack tops inside [ram_base, ram_base + ram_size), rejecting stack-into-.bss collisions.
14. Solutions & Explanations
  • Guided Question 1: An exact power of two has a single 1 bit (2^k), and subtracting 1 clears bit k and sets bits 0..k-1, yielding zero bit overlap (& == 0); any number with two or more 1 bits retains its most-significant 1 bit in n - 1, so n & (n - 1) is non-zero.
  • Guided Question 2: Stepping 4 bytes per STR while r0 < __bss_end when __bss_end is unaligned (+5) executes at +0 and +4, writing bytes +4..+7 (3 bytes past __bss_end!); aligning __bss_end = ALIGN(4) reserves those 3 tail 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 MMIO overlay must sit at its exact documented peripheral byte offset, proven at compile time with offsetof and _Static_assert (never __attribute__((packed))).
  • volatile prevents compiler load/store removal and merging, yet provides neither atomic read-modify-write execution nor ARMv7-A CPU memory barriers.
  • Explicit 32-bit unsigned masks avoid implementation-defined C bit-field ordering, narrow byte loads (ldrb/strb), and accidental RMW on W1C status 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

1

Step 1: Record peripheral base addresses, 32-bit register offsets, reserved gaps, and RW/RO/W1C contracts.

reveals: step1

highlights: step1

2

Step 2: Define naturally aligned volatile uint32_t members locked by _Static_assert(offsetof(...)) and sizeof.

reveals: step2

highlights: step2

3

Step 3: Mark read-only status volatile const, serialize shared DR RMW, and write pure masks to W1C ISR.

reveals: step3

highlights: step3

4

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

GL-E01lesson 16/18free preview~20 min

6.1 Modular BSP Layout and Dependency-Correct Make Rules

What you'll learn
  • Partition clock, indicator, delay, and application responsibilities into narrow modules.
  • Write pattern rules that retain source paths and generate header dependencies.
  • Diagnose a stale object caused by a missing header dependency.

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:

  1. Layer 1 — Pure Silicon Register Definitions (include/soc_regs.h): Owns immutable i.MX6ULL base addresses and _Static_assert-verified overlays (struct bsp_ccm_regs with _pad0[26] placing CCGR[0..6] at exact offsets +0x68..+0x80, sizeof == 0x84 = 132 B). Zero board pin numbers live here!
  2. Layer 2 — Narrow Subsystem Modules (bsp/clk/, bsp/led/, bsp/delay/): Each subsystem .c file includes soc_regs.h privately and owns one hardware domain (clk.c owns CCM_CCGR0..6; led.c + led_board.h own GPIO1_IO03 muxing and active-low inversion; delay.c owns timing). Their public headers (led.h, delay.h) expose only logical actions (void led_set(bool on);)—never volatile register structs!
  3. Layer 3 — Application Policy (project/start.S, project/main.c): Includes only led.h and delay.h. Consequently, as bsp_header_dep_audit.c proves, editing include/soc_regs.h rebuilds clk.o and led.o (0x13 with bsp.elf) while leaving project/main.o completely untouched!
fig_m06_l01_a.svg — Three-layer bare-metal BSP header firewall — main.c…

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:

ast_m06_l01.svg — Pair narrow subsystem headers with path-preserving…step 1/4
  1. Step 1. Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw literals.
  2. Step 2. Step 2: Encapsulate CCGR gates, pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.
  3. Step 3. Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.
  4. 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:

  1. Preventing basename collisions (obj/init.o): Many tutorials flatten objects with OBJ := $(addprefix obj/,$(notdir $(SRC:.c=.o))). The moment both bsp/clk/init.c and bsp/led/init.c exist, both map to obj/init.o—silently overwriting one module at build time! Using $(patsubst %.c,obj/%.o,$(SRC)) with @mkdir -p $(dir $@) inside obj/%.o: %.c preserves a 1-to-1 bijection (obj/bsp/clk/init.o != obj/bsp/led/init.o).
  2. Why -MMD needs BOTH -MP and -include: Generating .d files without -include $(OBJ:.o=.d) does nothing at all! Leading - in -include tells Make not to fail on a clean checkout before .d files exist. Once .d files exist, if you refactor and delete led_board.h, Make sees obj/bsp/led/led.o: ... bsp/led/led_board.h in the old .d file and aborts with No rule to make target 'bsp/led/led_board.h' unless -MP emitted the empty phony target bsp/led/led_board.h:!
  3. Linker script & unified freestanding EABI flags: Notice bsp.elf: $(OBJ) bsp.lds—making bsp.lds a prerequisite forces a relink whenever VMA/LMA addresses change—and notice -ffreestanding -fno-builtin -mcpu=cortex-a7 -marm -mfloat-abi=soft shared across every .c and .S rule even when invoking an arm-linux-gnueabihf- toolchain prefix, preventing accidental VFP register usage before CPACR enables the FPU!
fig_m06_l01_b.svg — Path-mirroring pattern rules prevent basename…

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 PatternHeader Edit BehaviorHeader Rename / DeleteEngineering Verdict
-MMD -MP + -include $(OBJ:.o=.d)Rebuilds exact consumer .o set + bsp.elfSurvives cleanly via empty phony hdr.h: ruleProduction GNU Make standard
-MMD without -MPRebuilds exact consumer .o setFails with No rule to make target deleted.hBreaks refactoring without make clean
%.o: %.c with no .d includeRebuilds 0 objects on .h edits!Links stale struct offsets/macros into bsp.binDangerous silent build corruption
Flattened obj/$(notdir).oCollides whenever two folders have init.cOverwrites .o / .d files unpredictablyBroken on multi-subsystem BSPs
learner@ksa: ~/gl-e01/m06-l01
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
  1. Enforce one freestanding Cortex-A7 soft-float ABI across all objects and emit .d files with -MMD -MP.
  2. Mirror source paths under obj/ and create parent directories on demand via $(dir $@).
  3. Declare bsp.lds as an explicit prerequisite of bsp.elf so layout edits force a relink.
  4. 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
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;    }
  1. Verify sparse CCM CCGR0..CCGR6 (+0x68..+0x80) and GPIO (+0x00..+0x1C) BSP header offsets at compile time.
  2. Keep project/main.o decoupled from include/soc_regs.h so silicon-header edits rebuild only BSP driver objects.
  3. 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-l01
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-l01
strace — learner@ksa: ~/gl-e01/m06-l01
learner@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_CCGR1 was enabled on the workstation before invoking make
  • [x] Whether -MMD -MP .d dependency generation or -include $(OBJ:.o=.d) was omitted or pointed at the wrong path
  • [ ] Whether include/ needs to be renamed headers/ 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.c and bsp/led/init.c) can share file basenames without colliding on obj/init.o
  • [ ] Because the ARMv7-A AAPCS procedure-call standard embeds directory names inside BL instructions
  • [ ] Because objcopy -O binary sorts sections alphabetically by obj/ 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.lds causes gcc to ignore bsp.lds unless Make exports $^
  • [ ] Changing bsp.lds requires recompiling every .c file to regenerate .d header rules
  • [x] Make inspects the prerequisite list (not recipe flags!) to decide whether bsp.elf is older than bsp.lds and 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 BSP separates 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/%.o rules rather than directory conventions.
  • GCC/Clang -MMD emits non-system header dependencies per .o, while -MP adds empty phony header targets so deleted or renamed headers never stall incremental builds.
  • -include $(OBJ:.o=.d) reconnects .d files into Make's DAG, and bsp.elf: $(OBJ) bsp.lds ensures 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

1

Step 1: Keep project/main.c purely logical (led_set, delay_ms) with zero raw MMIO literals.

reveals: step1

highlights: step1

2

Step 2: Encapsulate CCGR gates, IOMUXC pads, and active-low polarity inside bsp/clk, bsp/led, and bsp/delay.

reveals: step2

highlights: step2

3

Step 3: Mirror source paths under obj/ (obj/%.o: %.c) and list bsp.lds as a prerequisite of bsp.elf.

reveals: step3

highlights: step3

4

Step 4: Compile with -MMD -MP and load -include $(OBJ:.o=.d) so header edits rebuild exact consumer .o files.

reveals: step4

highlights: step4

GL-E01lesson 17/18free preview~20 min

6.2 Transistor Buzzer Switching and Safe GPIO Polarity

What you'll learn
  • Derive PNP and NPN buzzer control polarity from their current paths.
  • Reject invalid bank-local pin requests before shifting or writing.
  • Preserve sibling DR bits while stating the exclusive-ownership requirement.

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:

  1. Panel A — 3.3 V PNP High-Side Switch (SNVS_TAMPER1 / GPIO5_IO01, Active-Low): The PNP emitter sits on VCC = 3.3 V. When GPIO5_IO01 drives 0 V (Low), V_EB ~= 0.7 V forward-biases the emitter-base junction, sinking I_B = (3.3 V - 0.7 V - 0.1 V) / 1.5 kOhm = 1.67 mA through R_B and saturating the transistor so I_C = 30 mA flows into the buzzer (ON)! When GPIO5_IO01 drives 3.3 V (High), V_EB = 3.3 V - 3.3 V = 0 V cuts the transistor OFF.
  2. Panel B — 5.0 V NPN Low-Side Switch (Active-High): The NPN emitter sits at GND below a 5.0 V load. Driving GPIO = 3.3 V sources I_B = (3.15 V - 0.75 V) / 1.0 kOhm = 2.4 mA (V_BE ~= 0.75 V), saturating the collector to sink 40 mA (ON), while GPIO = 0 V gives V_BE = 0 V (OFF)—cleanly switching a 5 V load from a 3.3 V ! Notice, however, that both circuits share a conductive ground/rail with the SoC: a transistor switch is current amplification, NEVER galvanic isolation!
  3. Panel C — The Classic 5.0 V PNP Hardware Trap: If someone wires a PNP emitter to 5.0 V and drives R_B directly from a 3.3 V GPIO, writing GPIO = 1 (3.3 V) leaves V_EB = 5.0 V - 3.3 V = 1.7 V > 0.7 V—the buzzer never turns off and 5 V back-feeds current into the SoC's 3.3 V ESD clamp diode!
fig_m06_l02_a.svg — BJT switching physics — 3.3 V PNP high-side active-low…

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:

ast_m06_l02.svg — Expose logical buzzer_set(enabled) to application code,…step 1/4
  1. Step 1. Step 1: Application calls buzzer_set(true/false) with zero knowledge of PNP or NPN inversion.
  2. Step 2. Step 2: maps circuit topology via drive_high = (asserted != active_low) and preloads inactive DR before GDIR.
  3. Step 3. Step 3: Guard CCGR1[31:30] != 0, dr != NULL, and pin < 32U before forming UINT32_C(1) << pin.
  4. 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:

  1. CCM_CCGR1 (0x020C406C) 2-bit clock-gate slots: Each CCGR0..CCGR6 register packs 16 two-bit CG fields (shift = cg_slot * 2): 00 = gated off, 01 = run mode only, 10 = reserved (do not write!), and 11 = enabled in run + wait (wfi) modes. GPIO5 sits in CCGR1 slot CG15 (bits [31:30])! Updating CCGR1 with (ccgr1 & ~(3U << 30)) | (3U << 30) turns on GPIO5 (0x020AC000) while preserving CG0..CG14 (such as GPIO1 at CG13 [27:26]).
  2. Separate IOMUXC_SNVS mux block (0x02290000) & chirp-free DR-before-GDIR order: SNVS_TAMPER0..9 pads belong to the battery-backed SNVS domain—their mux registers live at 0x02290000 (SW_MUX_CTL_PAD_SNVS_TAMPER1 = 0x0229000C, ALT5), not main IOMUXC (0x020E0000)! And on an active-low PNP stage, always set GPIO5->DR |= (1U << 1) (High = OFF) BEFORE setting GPIO5->GDIR |= (1U << 1) so the buzzer never emits an audible startup chirp!
fig_m06_l02_b.svg — CCM_CCGR1 2-bit clock gates (top), IOMUXC_SNVS pad…

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 StageGPIO Assert LevelRequired SignalHardware Failure If Misconfigured
Active buzzer + 3.3 V PNP high-side0 (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-side1 (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 sounderAlternating edges2..4 kHz PWM square waveSteady DC level makes 1 faint click and heats magnetic coil
Direct GPIO drive (no transistor)Circuit-dependent<= 2..4 mA indicator current30 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
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);    }
  1. Reject NULL pointers and pin >= 32U BEFORE computing UINT32_C(1) << pin so out-of-range calls never invoke shift UB or alter *dr.
  2. Boolean inequality (asserted != active_low) drives 0 for active-low assertion and 1 for active-low deassertion while preserving 31 sibling bits.
  3. 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
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;    }
  1. Accept only legal CCGR 2-bit policies (0, 1, and 3) across CCGR0..CCGR6 and preserve the other 15 CG slots.
  2. Refuse GPIO5_DR writes while GPIO5's CCGR1[31:30] gate is 00, and reject NULL or pin >= 32 before shifting.
  3. 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-l02
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-l02
strace — learner@ksa: ~/gl-e01/m06-l02
learner@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 GPIO and the transistor load still share direct conductive ground or supply return paths
  • [ ] Because bipolar transistors only amplify AC waveforms and block DC currents
  • [ ] Because GPIO5 operates without a CCM clock 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 setting GDIR[1] = 1
  • [ ] Either 0 or 1, because active buzzers toggle state only on rising edges
  • [x] Bit 1 = 1 (3.3 V inactive high, V_EB = 0 V), preloaded into GPIO5_DR before setting GPIO5_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 1 vs pin 3) on the same GPIO bank
  • [x] Only when the GPIO bank enjoys single-owner access or explicit serialization (such as IRQ masking / a lock) across the load-modify-store window
  • [ ] Whenever dr is declared volatile 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 V PNP high-side switch conducts when pulled low (V_EB ~= 0.7 V, active-low), while an NPN low-side switch conducts when driven high (V_BE ~= 0.75 V, active-high), unified behind drive_high = (asserted != active_low).
  • BJT switches buffer load current (I_B << I_C) via base resistor R_B without providing galvanic isolation; never tie a PNP emitter to 5 V when driven directly from a 3.3 V GPIO.
  • Enable GPIO5's CCM_CCGR1[31:30] (CG15) clock gate and IOMUXC_SNVS (0x0229000C) mux, preload inactive DR before GDIR, validate pin < 32U, and serialize shared DR read-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

1

Step 1: Application calls buzzer_set(true/false) with zero knowledge of PNP or NPN inversion.

reveals: step1

highlights: step1

2

Step 2: BSP maps circuit topology via drive_high = (asserted != active_low) and preloads inactive DR before GDIR.

reveals: step2

highlights: step2

3

Step 3: Guard CCGR1[31:30] != 0, dr != NULL, and pin < 32U before forming UINT32_C(1) << pin.

reveals: step3

highlights: step3

4

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

GL-E01lesson 18/18free preview~20 min

6.3 Capstone: A Nonblocking Polled Key and Modular BSP

What you'll learn
  • Normalize the sampled active-low PSR input into a logical pressed state.
  • Accept a candidate only after a continuous sampled stable interval.
  • Integrate one press event with LED and buzzer policy without blocking polling.

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):

  1. Read GPIO1_PSR (+0x08), never GPIO1_DR (+0x00): On input UART1_CTS_B (ALT5 -> GPIO1_IO18, pulled to 3.3 V idle and switched to GND when pressed), PSR samples the live external pad (pressed = (*psr & (1U << 18)) == 0U), whereas DR holds the unused output latch!
  2. Qualify continuous stability (t = 1..48 ms in Figure 6.3a): Raw chatter at t = 1, 3, 4 keeps resetting since_ms = 4; at t = 13 (13 - 4 = 9 < 10), no event fires; at t = 14 (14 - 4 == 10), stable commits true and one EV_PRESS fires (turning alarm_on = true)! Holding at t = 19 sees candidate == stable (EV_NONE); release chatter at t = 20, 25, 26 settles at t = 36 (EV_RELEASE, re-arming the button without toggling the alarm); and a second press at t = 37 fires EV_PRESS at t = 47 (toggling alarm_on = false)!
fig_m06_l03_a.svg — Active-low tactile switch input path into GPIO1_PSR[18]…

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:

ast_m06_l03.svg — Sample PSR (never DR), separate candidate from stable…step 1/4
  1. Step 1. Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.
  2. Step 2. Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.
  3. Step 3. Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.
  4. 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 + 10U overflows 32 bits and wraps to 0x00000004! Just 1 ms later (now = 0xFFFFFFFB), 0xFFFFFFFB >= 0x00000004 evaluates true immediately—passing raw contact bounce straight into your application!
  • Why if ((uint32_t)(now - since) >= 10U) is exact: At now = 0xFFFFFFFE, 0xFFFFFFFE - 0xFFFFFFFA == 4U (< 10U); after wrap at now = 0x00000003, (3U - 0xFFFFFFFAU) == 9U (< 10U); and at now = 0x00000004, (4U - 0xFFFFFFFAU) == 10U (>= 10U, firing after the exact 10-tick physical interval)!
fig_m06_l03_b.svg — Nonblocking O(1) debounce branches (left) and why…

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 ImplementationSuper-Loop CPU CostBounce & UINT32_MAX BehaviorEngineering Verdict
Blocking if (!psr) { delay_ms(10); ... }Burns 5.28M cycles @ 528 MHzStarves UART/sensors; re-fires while held!Broken beyond toy demos
Deadline now >= since + 10UO(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) >= 10UO(1) nonblocking (< 30 cycles)Exact across UINT32_MAX; debounces press & releaseProduction bare-metal standard
Reading GPIO1_DR (+0x00) instead of PSRO(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
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. */
  1. Sample GPIO1_PSR at 0x0209C008 (+0x08, never DR at +0x00!) and normalize active-low bit 18 (0V -> pressed = true).
  2. 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
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;    }
  1. Normalize active-low GPIO1_PSR bit 18 ((psr & (1U << 18)) == 0U) into logical pressed.
  2. Use unsigned subtraction (uint32_t)(now - f->since) >= 10U so 32-bit tick wrap across UINT32_MAX never triggers early.
  3. 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-l03
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-l03
strace — learner@ksa: ~/gl-e01/m06-l03
learner@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 ticks 4 through 13 inclusively spans ten labels
  • [ ] EV_RELEASE, because 13 < 14 resets f->candidate back to false
  • [x] EV_NONE, because (uint32_t)(13U - 4U) == 9U < 10U (9 elapsed ticks, firing at now = 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_PSR automatically clears the pad voltage latch until the next reset
  • [x] 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
  • [ ] key_poll() disables CCM_CCGR1 after each KEY_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 bit 18 ((*psr & (1U << 18)) == 0U)
  • [ ] GPIO1_DR (0x0209C000), because DR mirrors external input pins whenever GDIR[18] == 0
  • [ ] GPIO1_ISR (0x0209C018), clearing bit 18 with |= (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.

Lab 6: Wraparound-Safe 10 ms Key Debounce FSM & Active-Low BSP Output Integration

env: host
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
  1. Reject sub-10-tick mechanical contact bounce on both press and release transitions by resetting f->candidate and f->since whenever pressed != f->candidate.
  2. Suppress repeated PRESS events while a button remains held (f->candidate == f->stable) and require a full 10-tick RELEASE qualification before accepting the next press.
  3. Repair 32-bit monotonic tick elapsed-time comparison using unsigned modular subtraction ((uint32_t)(now - f->since) >= 10U) across UINT32_MAX -> 0.
  4. Integrate sample_key() and output_write() inside bsp_step() so accepted PRESS events toggle active-low bit 1 (mask = 2U) without disturbing bits [31:2] or bit 0.
3. Environment Requirements
  • Tested Workstation Host: Linux 7.0.0-42-generic (x86_64) inside labs/lab_m06_modular_bsp_io/.
  • Target Hardware Alignment: Models active-low KEY0 input normalized from GPIO1_PSR[18] (0x0209C008), monotonic 32-bit timer ticks (EPIT/GPT), and active-low PNP buzzer output on GPIO5_DR[1] (0x020AC000).
4. Required Software & Hardware
  • Software: gcc (-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNU make, GNU ar, POSIX /bin/sh, and Binutils (nm, objdump).
  • Hardware: Standard Linux workstation (0 physical switches, buzzers, or Cortex-A7 boards required for the 5-check TAP grader).
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
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): Whenever pressed != f->candidate, sample_key() sets f->candidate = pressed; f->since = now; and returns NONE immediately. In tests.c case 1, chatter at now = 1 (true) -> 3 (false) -> 4 (true) resets f->since to 4U, so now = 13U (elapsed = 9U) still returns NONE and now = 14U (elapsed = 10U) emits PRESS.
  • Seeded Flaw in starter/core.c:8 (sample_key): starter tests f->candidate != f->stable && now >= f->since + 10U. When f->since = UINT32_MAX - 5U (0xFFFFFFFAU) in tests.c case 3, f->since + 10U wraps modulo 2^32 to 4U, making now >= 4U immediately true at now = UINT32_MAX - 1U (0xFFFFFFFEU, only 4 ticks elapsed!).
  • Verified Repair in files/core.c:8: Evaluates (uint32_t)(now - f->since) >= 10U. Across the wrap boundary (since = 0xFFFFFFFAU), now = 0xFFFFFFFEU gives elapsed = 4U < 10U (NONE), now = 3U gives (uint32_t)(3U - 0xFFFFFFFAU) == 9U < 10U (NONE), and now = 4U gives 10U >= 10U (PRESS), after which f->stable = true suppresses now = 5U (NONE).
  • output_write & bsp_step (core.c:13-25): bsp_step() toggles *enabled = !*enabled strictly when event == PRESS (RELEASE leaves *enabled unchanged in tests.c:36), then calls output_write(dr, 1U, *enabled, true) to clear bit 1 (0U) when enabled and set bit 1 (2U) when disabled while preserving siblings = dr & ~2U.
7. Expected TAP-13 Output
learner@ksa: ~/gl-e01/m06-l03
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/5
8. 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
  1. Toggle on Both Edges Bug (bsp_step): Change if (event == PRESS) to if (event != NONE) in a scratch copy and run verify 4: *enabled turns on at t = 11 (PRESS) and immediately turns off upon finger lift at t = 31 (RELEASE), converting a latching toggle button into a momentary dead-man switch (tests.c:36 aborts).
  2. Off-By-One Threshold (> 10U vs >= 10U): Change >= 10U to > 10U in sample_key(): tests.c case 1 (since = 4U, now = 14U), case 2 (1 -> 11), case 3 (UINT32_MAX - 5U -> 4U), and case 4 (1 -> 11) all fail because 10 elapsed ticks require an 11th tick to fire.
  3. Held-At-Boot Policy Check: Initialize struct filter f = {true, true, 0U}; when GPIO1_PSR[18] reads 0 at reset and verify a button already held across power-on emits zero spurious PRESS events 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 p50Host p95Host p99Cortex-A7 @ 528 MHz Superloop Impact
Full sh check.sh (make -B + gcc link + 4 cases)143.97 ms169.45 ms170.52 msHost compile + link + process launch
verify 4-case capstone FSM suite (verify 1..4)3668.5 us4674.6 us4923.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 / pollSaves 5,280,000 stalled CPU cycles (10 ms) per bounce!
11. Troubleshooting
SymptomRoot CauseFix
not ok 4 (sample_key fires PRESS at UINT32_MAX - 1U)Deadline addition f->since + 10U wraps modulo 2^32 to 4UCompare 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->candidateReset 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->stableGate 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_writeMask single bit 1U via output_write(dr, 1U, *enabled, true)
12. Guided Questions
  1. Under what maximum polling-gap constraint is (uint32_t)(now - f->since) >= 10U guaranteed free of wraparound ambiguity on a 1 kHz (1 ms) uint32_t tick counter?
  • *Hint 1:* Compute the full period 2^32 ms in 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 ms while f->candidate != f->stable so (uint32_t)(now - f->since) aliases back to 2U < 10U?
  1. Why does bsp_step() call output_write(dr, 1U, *enabled, true) unconditionally or on state change rather than blocking inside sample_key() for 10 ms?
  • *Hint 1:* Count how many independent peripherals (UART RX FIFO, LED heartbeat, watchdog service, multiple buttons) share a bare-metal cooperative superloop.
  • *Hint 2:* If UART1 receives bytes at 115200 baud (~86.8 us per byte, 32-byte hardware RX FIFO = 2.78 ms to overflow), what happens to incoming serial frames during a 10 ms blocking delay_ms(10) debounce?
13. Independent Challenges
  1. Near Transfer — Asymmetric Press/Release Thresholds & Long-Press Event (LONG_PRESS): Extend enum event with LONG_PRESS (>= 1000 ticks continuous hold after PRESS, emitted at most once per hold via bool long_sent in struct filter) while keeping 10-tick press and 15-tick release qualification wraparound-safe.
  2. 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 debounces 8 simultaneous GPIO keypad inputs using 2-bit vertical saturating counters sampled every 5 ms (3 consecutive matching samples = 10 - 15 ms qualification) with zero per-pin branches.
14. Solutions & Explanations
  • Guided Question 1: Unsigned subtraction now - since measures exact elapsed ticks modulo 2^32 provided consecutive polls while candidate != stable occur within < 2^32 - 10 ticks (~49.71 days at 1 kHz), so polling every 1 - 5 ms has 9 orders of magnitude safety margin.
  • Guided Question 2: At 115200 8N1 (11,520 bytes/s), 10 ms delivers 115 bytes -- overflowing a 32-byte UART FIFO 3.6x over! Nonblocking state-machine polling finishes in nanoseconds so UART, 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, set f->long_sent = true, and return LONG_PRESS; clear f->long_sent = false whenever f->stable transitions to false (RELEASE).

Run locally in your terminal and check off each verification milestone.

Not started

Summary

  • Mechanical switch contacts bounce repeatedly across 1..5 ms on both press and release; IOMUXC hysteresis (HYS = 1) cleans slow edges while a software debounce FSM filters millisecond chatter.
  • Tracking (candidate, stable, since_ms) in an O(1) nonblocking poll function qualifies transitions without starving sibling BSP work inside delay_ms() spin loops.
  • Unsigned subtraction (uint32_t)(now_ms - since_ms) >= threshold computes exact elapsed ticks across UINT32_MAX -> 0 wraparound (~49.7 days at 1 kHz), avoiding the since + threshold overflow bug.
  • Sampling GPIO1_PSR (+0x08) and dispatching single-edge EV_PRESS transitions into polarity-aware GPIO1_DR/GPIO5_DR helpers completes an auditable, modular bare-metal BSP.
  • 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

1

Step 1: Read GPIO1_PSR (+0x08) and normalize active-low bit 18 into logical pressed.

reveals: step1

highlights: step1

2

Step 2: On any pressed != candidate edge or bounce, update candidate and reset since_ms = now_ms.

reveals: step2

highlights: step2

3

Step 3: Once candidate != stable and (uint32_t)(now_ms - since_ms) >= 10U, commit stable and emit 1 event.

reveals: step3

highlights: step3

4

Step 4: Toggle LED0 (GPIO1_DR[3]) and PNP buzzer (GPIO5_DR[1]) on EV_PRESS while preserving sibling bits.

reveals: step4

highlights: step4

search — fzf

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

keyboard shortcuts — less

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

figure