Chapter 5: Memory-Mapped I/O, Register Abstractions, and Low-Level Control on Cortex-M
The chapter shifts from firmware startup to correctness-sensitive, day-to-day hardware interaction on Cortex-M.
After this chapter you will be able to
- Hardware interaction correctness risks. Explain why routine hardware interactions require care: a misplaced read or missing barrier can silently corrupt state or cause a signal to be missed.
- Memory-mapped register semantics. Explain how the CPU accesses a peripheral register and why that access differs from ordinary memory access.
- Volatile access and ordering. Explain why MMIO accesses may require volatile operations and, separately, memory barriers.
- Cortex-M memory map regions. Explain that Cortex-M has a 4 GB address space divided into regions with predefined roles, and that device-specific register blocks are usually found in the Peripheral region.
- Hardware control through addresses. Explain that MMIO places hardware control registers in the address map alongside code and data, and that firmware programs those registers to configure peripherals and respond to their state.
- CPU Access and Memory Types. Explain that the CPU uses the same load and store instructions for peripherals and RAM, while Cortex-M memory types differ in side effects, caching, buffering, and ordering.
- Buffered Write Ordering. Trace the section’s example of how a buffered write followed by a read can appear on the system bus in a different order from the instructions.
- DMB and DSB Barriers. Distinguish the ordering guarantees described for DMB and DSB, and explain why barriers can be needed for memory access synchronization.
- Unsafe register access. Explain that Rust can access memory-mapped peripheral registers through addresses, as C does, but accessing arbitrary memory requires an explicit unsafe block because the compiler cannot guarantee its correctness.
- Meaning of unsafe blocks. Explain that an unsafe block permits operations Rust cannot statically verify, while leaving checks in place and making the programmer responsible for upholding Rust’s safety guarantees. Name the examples given: dereferencing raw pointers, calling unsafe functions or methods, and accessing mutable static variables.
- Review and isolation of unsafe code. Justify why unsafe blocks should be audited and why Rust promotes isolating unsafe operations behind safe abstractions such as PACs and HALs.
- Raw pointer register access. Describe how a raw pointer can address an STM32F1 GPIOA register for a read or write, and explain why dereferencing it requires an unsafe block.
- Volatile MMIO access requirement. Explain why an ordinary raw-pointer dereference is not sufficient for MMIO and identify the safer access approaches named here.
- Compiler guarantees of volatile access. Explain why register accesses use read_volatile and write_volatile: each access must remain an explicit load or store rather than being removed, merged, or reordered by the compiler.
- System limits of volatile. Distinguish volatile's compiler-level effect from hardware-level ordering, visibility, completion, and cache maintenance.
- Roles of Cortex-M barriers. Distinguish DMB, DSB, and ISB by the ordering, completion, or instruction-pipeline need each addresses, and describe the peripheral-configuration and instruction-side examples given.
- Typed register block access. Explain how a peripheral register-block struct and volatile-register’s RO, WO, and RW fields improve on manually managing MMIO addresses and offsets.
- Wrapper safety boundaries. Distinguish the access rules enforced by volatile-register from the hardware properties it cannot verify.
- Raw and volatile register access. Explain why raw pointer dereferencing illustrates MMIO but is not a robust register-access pattern, and what explicit volatile operations add.
- Typed GPIO register overlays. Explain what a typed register overlay adds to raw addresses in the GPIO example, and state the output-register hazard the section notes.
- Motivation for Register Abstractions. Explain why effective low-level access to memory-mapped I/O through unsafe Rust is not always a good way to build larger embedded applications, and why the section turns to PACs and HALs.
- Localized unsafe register access. Explain how a small, specialized function can keep raw register access and unsafe code out of the rest of an application.
- Atomic GPIO bit updates. Distinguish updating an STM32 GPIO output through ODR from writing BSRR, and explain why BSRR is preferred for a safe wrapper.
- SVD to PAC generation. Explain what an SVD describes and how svd2rust turns it into a PAC with named, strongly typed peripheral registers and fields instead of hand-written pointers and offsets.
- Exclusive peripheral access. Explain how Peripherals::take() gives the program exclusive access to strongly typed handles for the device’s memory-mapped peripherals.
- Register write and modify. Distinguish a PAC register’s write method from modify, including how modify preserves fields that the closure does not change.
- HAL and PAC roles. Distinguish the register-level access a PAC provides from the higher-level peripheral types a HAL builds on it, and explain how embedded-hal traits can make drivers portable across supported chips.
- GPIO decomposition and typestate. Trace how a HAL turns a PAC GPIO port into individual pins and how changing a pin’s mode changes its type to prevent misuse.
- Frozen clocks and timing. Describe how .constrain() and .freeze() produce a Clocks value and explain why timing-dependent peripherals use it.
- Portable driver trait contracts. Explain how embedded-hal traits let a driver use common interfaces such as I2C or delays without depending on a particular microcontroller, while an MCU-specific HAL implements those traits using the device PAC.
- Explicit memory layout control. Explain why Rust’s ownership protections do not remove the need to control how data is represented and accessed when working with bare-metal hardware.
- Value size and alignment. Explain that a value has both a size and an alignment, and why alignment requirements matter for memory accesses.
- Struct padding and placement. Describe why SampleLayout occupies 8 bytes despite its fields totaling 7 bytes, and state its alignment requirement.
- Predictable hardware register layout. Explain why Rust’s default struct layout cannot be relied on for hardware registers or C interfaces, and how #[repr©] gives fields declaration order with padding under C ABI rules.
- Layout versus volatile access. Distinguish the layout guarantee of #[repr©] from volatile register access, and describe how the example uses VolatileCell to read and write registers.
- Packed Layout and MMIO Risks. Explain how #[repr(packed)] changes a struct’s size and alignment, and why packed structs are unsuitable for MMIO register overlays.
- Explicit Alignment for Cached Buffers. Describe what #[repr(align(N))] guarantees for a buffer and why cache-line alignment helps, while stating its limit for DMA coherency.
- Section placement responsibilities. Explain how a Rust symbol is placed in a physical memory region and why `link_section` is unsafe in the 2024 edition.
- Custom section initialization. Explain what `NOLOAD` means for the DTCM section and what startup must do when custom-section data needs initialization.
- Vector Table Entry Order. Describe the vector table as data in memory: its first word supplies the initial Main Stack Pointer, its second supplies the reset handler address, and later entries supply exception and interrupt handler addresses.
- Flash Alias at Reset. Explain why placing the vector table at the start of Flash works on the STM32F1 even though Flash is physically mapped at 0x0800_0000.
- Rust and Linker Placement. Trace how #[unsafe(link_section)] tags Rust symbols for placement and how the linker script collects their sections into an ordered vector-table region at the start of Flash.
- Need for assembly-level access. Explain why embedded development may require assembly-level access even when using Rust.
- Reasons for using assembly. Explain the situations in which assembly is justified in embedded Rust: accessing processor-specific instructions or privileged CPU state, meeting precise timing or performance requirements, and bootstrapping without a runtime.
- Assembly safety responsibility. Explain why assembly requires extra care: it bypasses Rust’s safety model, so the programmer must make their intent explicit and take responsibility for side effects, register constraints, and synchronization.
- Data barrier guarantees. Distinguish the guarantees of dmb() and dsb() and explain why peripheral or DMA hand-offs may need a memory barrier.
- Instruction barrier after control changes. Explain why isb() is needed after changes to system control state such as CONTROL, privilege level, or MPU configuration.
- Interrupt and event waits. Distinguish wfi() from wfe()/sev() and describe the idle-loop or signalling use explained for each.
- Compiler interface contract. Explain why asm!() is unsafe and why its declared effects must match what the instructions actually do.
- Register operand bindings. Distinguish input, output, and read-modify-write register bindings, and state when a specific register is warranted.
- Core system register access. Explain why some Cortex-M system registers call for assembly, and describe the privilege and synchronization cautions given here.
- Module-level assembly routines. Distinguish global_asm! from inline asm! and describe how assembler text defines linker-visible functions or data at module scope. Explain why this is useful for startup code or handlers needing explicit control.
- Standalone routine ABI obligations. Explain why a routine written with global_asm! must follow the platform ABI, including register preservation, stack invariants, and the correct return. Distinguish Cortex-M hardware-saved exception registers from additional callee-saved registers.
- Rust access to assembly symbols. Describe how Rust code references a symbol defined in global_asm! and when that reference is resolved.
- External assembly file integration. Explain that a Rust project can use build.rs to assemble and link an existing .S file alongside its Rust sources, keeping substantial assembly in a dedicated file.
What it builds on
- Mapping output sections (chapter 4) · Firmware sections are placed within a defined memory layout.
- Configuring and controlling interrupts with the Nested Vectored Interrupt Controller (chapter 4) · The NVIC’s role in controlling interrupts.
- Defining physical memory regions (chapter 4) · Assumes physical memory regions are defined for the target device.
- Writing a minimal startup routine in Rust (chapter 4) · Assumes startup code can initialize memory before the application uses it.
- Manually creating a vector table in Rust (chapter 4) · the earlier hand-built vector table
- A detailed look at reset vector fetching and execution (chapter 4) · reset vector fetching and execution
- Exceptions and interrupts: Concepts and distinctions (chapter 4) · The concept of an interrupt
- The Cortex-M exception handling model (chapter 4) · Cortex-M exception entry and exit.
Section by section
Introduction
The chapter shifts from firmware startup to correctness-sensitive, day-to-day hardware interaction on Cortex-M.
- Hardware interaction correctness risks: Explain why routine hardware interactions require care: a misplaced read or missing barrier can silently corrupt state or cause a signal to be missed.
Why it matters: Hardware interactions can appear routine while small mistakes produce failures that are easy to miss.
Key terms: memory-mapped I/O, barrier, peripheral
5.1 What are memory-mapped I/Os in a microcontroller?
The section explains how Cortex-M memory-mapped I/O places hardware registers in the address space and why accessing them differs from accessing ordinary memory.
- Memory-mapped register semantics: Explain how the CPU accesses a peripheral register and why that access differs from ordinary memory access.
Why it matters: A register access may change hardware behavior even though it looks like a memory access. - Peripheral register block layout: Describe how device peripherals and their registers are arranged in the Cortex-M address map.
Why it matters: The block-and-offset layout explains how a register’s address is located. - Core and device peripherals: Distinguish memory-mapped processor components from vendor device peripherals.
Why it matters: Not every MMIO address refers to a vendor-provided peripheral. - Volatile access and ordering: Explain why MMIO accesses may require volatile operations and, separately, memory barriers.
Why it matters: Preserving a register access and ensuring its ordering are distinct correctness concerns.
Key terms: memory-mapped I/O (MMIO), hardware registers, load/store instructions, side effects, Peripheral region, register block, base addresses, fixed offset, core peripherals, System region
5.1.1 The memory map
This section locates code, data, and peripheral registers within the Cortex-M address space.
- Cortex-M memory map regions: Explain that Cortex-M has a 4 GB address space divided into regions with predefined roles, and that device-specific register blocks are usually found in the Peripheral region.
Why it matters: It explains why firmware can address a peripheral’s registers at known locations.
Key terms: memory map, address space, Peripheral region, register blocks
5.1.2 What is memory-mapped?
This section explains how memory-mapped I/O makes hardware registers reachable through the address map and why Cortex-M’s defined core addresses aid portability.
- Hardware control through addresses: Explain that MMIO places hardware control registers in the address map alongside code and data, and that firmware programs those registers to configure peripherals and respond to their state.
Why it matters: This is the basis for understanding why embedded firmware accesses hardware through registers. - Cortex-M core address portability: Explain why architecturally defined addresses for Cortex-M core facilities let low-level code target common core functionality with little device-specific variation.
Why it matters: Common core addresses reduce the device-specific changes needed in low-level Cortex-M code.
Key terms: MMIO, address map, registers, GPIO, Cortex-M, System region, architecturally defined addresses, SysTick, NVIC, MPU
5.1.3 From the CPU’s perspective
This section explains why CPU loads and stores to memory-mapped peripherals need attention to memory types, access ordering, and barriers.
- CPU Access and Memory Types: Explain that the CPU uses the same load and store instructions for peripherals and RAM, while Cortex-M memory types differ in side effects, caching, buffering, and ordering.
Why it matters: A peripheral register may be accessed with an ordinary CPU instruction without behaving like ordinary RAM. - Buffered Write Ordering: Trace the section’s example of how a buffered write followed by a read can appear on the system bus in a different order from the instructions.
Why it matters: Source-code order alone may not provide the access ordering a device interaction requires. - DMB and DSB Barriers: Distinguish the ordering guarantees described for DMB and DSB, and explain why barriers can be needed for memory access synchronization.
Why it matters: Barriers provide a way to enforce ordering when buffering or reordering could matter.
Key terms: load/store instructions, Device memory, Normal memory, Strongly ordered, bufferable address, write buffer, system bus, memory accesses, DMB, Data Memory Barrier
5.2 Rust’s Embedded ecosystem: Abstractions and unsafe code
The section introduces why direct access to memory-mapped registers in Rust must be marked unsafe.
- Unsafe register access: Explain that Rust can access memory-mapped peripheral registers through addresses, as C does, but accessing arbitrary memory requires an explicit unsafe block because the compiler cannot guarantee its correctness.
Why it matters: It clarifies where Rust’s compiler protections end when code accesses hardware directly.
Key terms: memory-mapped registers, unsafe block, safe and unsafe operations
5.2.1 Unsafe code: A necessary evil
This subsection explains what an unsafe block permits, why it still requires review, and why unsafe operations should be isolated behind safe abstractions.
- Meaning of unsafe blocks: Explain that an unsafe block permits operations Rust cannot statically verify, while leaving checks in place and making the programmer responsible for upholding Rust’s safety guarantees. Name the examples given: dereferencing raw pointers, calling unsafe functions or methods, and accessing mutable static variables.
Why it matters: This distinction explains why low-level access needs an explicit unsafe block without treating that block as a safety guarantee. - Review and isolation of unsafe code: Justify why unsafe blocks should be audited and why Rust promotes isolating unsafe operations behind safe abstractions such as PACs and HALs.
Why it matters: Visible, contained unsafe code gives collaborators a clear place to focus safety review.
Key terms: unsafe blocks, safety guarantees, raw pointers, unsafe functions or methods, mutable static variables, safe abstractions, PACs, HALs
5.2.2 Accessing registers via raw pointers
The section shows direct register access through raw pointers in Rust and explains why plain dereferences are unsafe and insufficient for reliable MMIO.
- Raw pointer register access: Describe how a raw pointer can address an STM32F1 GPIOA register for a read or write, and explain why dereferencing it requires an unsafe block.
Why it matters: The unsafe block marks assumptions about the hardware address that Rust cannot check for you. - Volatile MMIO access requirement: Explain why an ordinary raw-pointer dereference is not sufficient for MMIO and identify the safer access approaches named here.
Why it matters: Hardware register accesses must not disappear or change order merely because the compiler optimizes the program. - Whole register write effects: Explain why writing a value directly to the ODR can affect more pins than intended and name the alternatives mentioned.
Why it matters: A write intended for one pin can unintentionally change the state of other pins.
Key terms: raw pointer, unsafe block, GPIOA Output Data Register (ODR), *mut u32, alignment, plain dereference, volatile MMIO access, volatile operations, PAC/HAL API, ODR
5.2.3 Using read_volatile and write_volatile
Explains how volatile register accesses constrain the compiler, why they do not provide system-wide guarantees, and when Cortex-M barriers are needed.
- Compiler guarantees of volatile access: Explain why register accesses use read_volatile and write_volatile: each access must remain an explicit load or store rather than being removed, merged, or reordered by the compiler.
Why it matters: A register access can have a hardware effect even when an ordinary memory access appears unnecessary to the compiler. - Raw addresses for mutable statics: Describe how to obtain an address for volatile access when the value is a static mut rather than a const raw pointer, and why taking a reference is not an option in the 2024 edition.
Why it matters: It distinguishes using an existing raw address from obtaining one for a mutable static without creating a forbidden reference. - System limits of volatile: Distinguish volatile's compiler-level effect from hardware-level ordering, visibility, completion, and cache maintenance.
Why it matters: Preserving an instruction in compiled code is different from ensuring its effect has propagated through the hardware. - Roles of Cortex-M barriers: Distinguish DMB, DSB, and ISB by the ordering, completion, or instruction-pipeline need each addresses, and describe the peripheral-configuration and instruction-side examples given.
Why it matters: Choosing a barrier depends on whether the requirement is ordered data access, completed operations, or execution under updated instruction-side rules.
Key terms: core::ptr, read_volatile, write_volatile, volatile, static mut, const raw pointer, core::ptr::addr_of!, addr_of_mut!, bus masters, buffered or posted writes
5.2.4 Safer MMIO with the volatile-register crate
This section explains how a register-block struct and volatile register wrappers make MMIO clearer and restrict invalid reads and writes, while leaving important hardware-safety checks to the programmer.
- Typed register block access: Explain how a peripheral register-block struct and volatile-register’s RO, WO, and RW fields improve on manually managing MMIO addresses and offsets.
Why it matters: Named, typed registers reduce offset mistakes and catch mismatched read or write operations before the firmware runs. - Wrapper safety boundaries: Distinguish the access rules enforced by volatile-register from the hardware properties it cannot verify.
Why it matters: Compile-time access restrictions help, but they do not establish that a register mapping or operation is correct for the device. - Register abstraction trade-offs: Describe where volatile-register sits among the other register-access options named in this section.
Why it matters: The options trade setup effort against how much register structure and access behavior they provide.
Key terms: struct overlay, volatile-register, RO, WO, RW, unsafe, software contract, struct layout, reserved bits, vcell
5.2.5 Real-World examples
The section compares raw, volatile, and typed ways to access hardware registers through SysTick, NVIC, and GPIO examples.
- Raw and volatile register access: Explain why raw pointer dereferencing illustrates MMIO but is not a robust register-access pattern, and what explicit volatile operations add.
Why it matters: Hardware register accesses can matter even when an ordinary memory access would look redundant. - NVIC write-one-to-set behavior: Describe how the example enables an interrupt line through the NVIC ISER and why it uses one targeted write rather than read-modify-write.
Why it matters: A register’s write semantics determine the correct access pattern. - Typed GPIO register overlays: Explain what a typed register overlay adds to raw addresses in the GPIO example, and state the output-register hazard the section notes.
Why it matters: Named, typed register access reduces offset mistakes without removing the need to respect hardware-specific register behavior.
Key terms: MMIO, raw pointer dereferencing, write_volatile, read_volatile, NVIC, Interrupt Set-Enable Register, ISER, write-one-to-set, read-modify-write, struct overlay
5.3 Working with Peripheral Access Crates (PACs) & Hardware Abstraction Layers (HALs)
The section motivates moving from direct unsafe memory-mapped I/O access toward PACs and HALs by identifying the limitations of hand-written low-level code.
- Motivation for Register Abstractions: Explain why effective low-level access to memory-mapped I/O through unsafe Rust is not always a good way to build larger embedded applications, and why the section turns to PACs and HALs.
Why it matters: This explains the problem the subsequent register abstractions are meant to address.
Key terms: memory-mapped I/O, unsafe code, Peripheral Access Crates (PACs), Hardware Abstraction Layers (HALs)
5.3.1 From Unsafe Code to Safe Wrappers
This section shows how a small wrapper can contain unsafe register access, why STM32 GPIO wrappers should use BSRR for bit updates, and where manual wrappers fall short.
- Localized unsafe register access: Explain how a small, specialized function can keep raw register access and unsafe code out of the rest of an application.
Why it matters: Containing unsafe MMIO makes the code easier to call and review. - Atomic GPIO bit updates: Distinguish updating an STM32 GPIO output through ODR from writing BSRR, and explain why BSRR is preferred for a safe wrapper.
Why it matters: The wrapper’s register choice matters when other code can update the same GPIO port. - Limits of manual wrappers: Explain what a hand-written register wrapper still leaves to the developer and why extending that approach across a device becomes burdensome.
Why it matters: It explains why a useful local wrapper is not a practical way to cover every device register by hand.
Key terms: raw register access, unsafe, wrapper, narrow, well-defined API, ODR, Output Data Register, read-modify-write, BSRR, atomic set/reset register, manual wrapper
5.3.2 Introducing svd2rust and auto-generated PACs
This subsection explains how SVD files and svd2rust produce register-level PACs, and why the quality of a PAC depends on its source data and maintenance.
- SVD to PAC generation: Explain what an SVD describes and how svd2rust turns it into a PAC with named, strongly typed peripheral registers and fields instead of hand-written pointers and offsets.
Why it matters: This explains where a PAC’s register names and types come from. - PAC quality and selection: Explain why a generated PAC is not automatically complete or correct, and describe the section’s advice for choosing an existing PAC.
Why it matters: Generated register definitions are only as trustworthy as their source data and upkeep.
Key terms: Peripheral Access Crates (PACs), System View Description (SVD), svd2rust, register-level API, PAC, SVD data, community-maintained PAC, crates.io
5.3.3 Using a PAC: stm32f1xx GPIO example
This section shows how an STM32 PAC provides exclusive, typed peripheral access, field-level register operations, and typed device interrupt identifiers.
- Exclusive peripheral access: Explain how Peripherals::take() gives the program exclusive access to strongly typed handles for the device’s memory-mapped peripherals.
Why it matters: Exclusive, typed handles are the starting point for using device peripherals through a PAC. - Register write and modify: Distinguish a PAC register’s write method from modify, including how modify preserves fields that the closure does not change.
Why it matters: Choosing between write and modify determines whether unrelated register fields retain their values. - BSRR set and reset writes: Explain why the GPIO BSRR example uses a direct write and what that write does.
Why it matters: The example shows why a full register write can be appropriate when the hardware register is designed for it. - Typed device interrupt access: Describe what the PAC’s Interrupt enum covers, how it is used with NVIC functions, and why enabling an interrupt may be unsafe.
Why it matters: Typed interrupt selection does not remove the concurrency risk of enabling an interrupt.
Key terms: Peripherals, Peripherals::take(), singleton, peripheral register block, read, write, modify, read proxy, write proxy, read-modify-write
5.3.4 Moving up to the HALs
This section shows how a HAL builds on a PAC to offer higher-level peripheral APIs, type-checked pin configuration, and clock-aware timing.
- HAL and PAC roles: Distinguish the register-level access a PAC provides from the higher-level peripheral types a HAL builds on it, and explain how embedded-hal traits can make drivers portable across supported chips.
Why it matters: This explains why application code can be easier to write than direct PAC code without giving up the PAC’s register definitions. - GPIO decomposition and typestate: Trace how a HAL turns a PAC GPIO port into individual pins and how changing a pin’s mode changes its type to prevent misuse.
Why it matters: The pin’s type lets the compiler catch configuration mistakes before firmware runs. - Frozen clocks and timing: Describe how .constrain() and .freeze() produce a Clocks value and explain why timing-dependent peripherals use it.
Why it matters: Timing code needs the configured clock frequencies to calculate settings such as a SysTick reload value correctly. - HAL imports and PAC access: Explain why HAL examples may import the PAC through the HAL and bring the prelude into scope.
Why it matters: These imports explain where the PAC types come from and why HAL methods appear on them.
Key terms: PAC, HAL, embedded-hal, register blocks, bitfields, .split(), GPIOC, pc13, push-pull output, typestate
5.3.5 The Role of embedded-hal
This section explains how embedded-hal traits let drivers work across microcontrollers and distinguishes the sibling embedded-io crate.
- Portable driver trait contracts: Explain how embedded-hal traits let a driver use common interfaces such as I2C or delays without depending on a particular microcontroller, while an MCU-specific HAL implements those traits using the device PAC.
Why it matters: This separation lets you reuse a driver when you change microcontroller families. - Sibling generic I/O traits: Distinguish embedded-io from embedded-hal by stating that embedded-io is a sibling crate providing generic I/O traits usable in no_std environments.
Why it matters: It helps you recognize that generic I/O contracts have a separate crate alongside embedded-hal.
Key terms: embedded-hal, traits, HAL, PAC, embedded_hal::i2c::I2c, DelayNs, embedded-io, generic I/O traits, no_std
5.4 Memory & data placement considerations
This section explains why embedded Rust needs explicit control over memory layout and data placement despite the protections of safe Rust.
- Explicit memory layout control: Explain why Rust’s ownership protections do not remove the need to control how data is represented and accessed when working with bare-metal hardware.
Why it matters: Memory safety alone does not ensure that data is laid out as the hardware requires.
Key terms: memory layout, alignment, data placement, ownership model
5.4.1 Understanding data alignment and layout
This section explains why values have alignment requirements and uses a struct example to show how padding affects size and placement.
- Value size and alignment: Explain that a value has both a size and an alignment, and why alignment requirements matter for memory accesses.
Why it matters: Alignment helps explain why a value’s memory layout is not determined by its size alone. - Struct padding and placement: Describe why SampleLayout occupies 8 bytes despite its fields totaling 7 bytes, and state its alignment requirement.
Why it matters: A struct can occupy more memory than its fields add up to, which matters when reasoning about layout.
Key terms: size, alignment, misaligned memory accesses, SampleLayout, padding, most-aligned field, char
5.4.2 Struct layout
Explains why hardware register structures need a defined field layout and why that layout alone does not make register access volatile-safe.
- Predictable hardware register layout: Explain why Rust’s default struct layout cannot be relied on for hardware registers or C interfaces, and how #[repr©] gives fields declaration order with padding under C ABI rules.
Why it matters: A register-block struct must match the layout the hardware expects. - Layout versus volatile access: Distinguish the layout guarantee of #[repr©] from volatile register access, and describe how the example uses VolatileCell to read and write registers.
Why it matters: Matching register positions and performing volatile register accesses are separate requirements.
Key terms: #[repr©], structure layout, padding, C Application Binary Interface (ABI), hardware register blocks, tail padding, vcell, VolatileCell, volatile memory access, .get()
5.4.3 Packed layout and alignment
This section contrasts packed structs, which remove padding but can cause unaligned accesses, with explicit alignment for cache-sensitive buffers.
- Packed Layout and MMIO Risks: Explain how #[repr(packed)] changes a struct’s size and alignment, and why packed structs are unsuitable for MMIO register overlays.
Why it matters: A compact register layout is not useful if accessing its fields faults or becomes inefficient. - Explicit Alignment for Cached Buffers: Describe what #[repr(align(N))] guarantees for a buffer and why cache-line alignment helps, while stating its limit for DMA coherency.
Why it matters: Alignment can reduce cache traffic, but treating it as complete DMA protection would be a mistake.
Key terms: #[repr(packed)], #[repr(C, packed)], padding, alignment, MMIO register overlays, #[repr(align(N))], cache lines, split-line, DMA coherency, cache clean/invalidate barriers
5.4.4 Section placement with #[unsafe(link_section)]
Explains how Rust section attributes and linker scripts place code or data in device memory, using DTCM as an example and addressing placement safety and initialization.
- Section placement responsibilities: Explain how a Rust symbol is placed in a physical memory region and why `link_section` is unsafe in the 2024 edition.
Why it matters: A section tag cannot guarantee correct hardware placement without a matching linker script. - TCM placement rationale: Describe why the example places a performance-critical buffer in DTCM and distinguish the stated purposes of DTCM and ITCM.
Why it matters: The target device must actually have the memory region that the linker script names. - Custom section initialization: Explain what `NOLOAD` means for the DTCM section and what startup must do when custom-section data needs initialization.
Why it matters: Putting a buffer in a custom section does not automatically give it the initial contents your program expects. - Mutable static access rule: State how the section’s `CRITICAL_BUFFER` must be accessed under the stated 2024-edition rule.
Why it matters: Correct section placement does not remove the separate restriction on accessing this mutable static.
Key terms: #[unsafe(link_section)], MEMORY, SECTIONS, linker script, TCM, ITCM, DTCM, NOLOAD, cortex-m-rt, .bss
5.4.5 Revisiting Vector Table Placement
This section explains how a Cortex-M vector table is laid out, why an STM32F1 can find it at reset, and how Rust section attributes and a linker script place it in Flash.
- Vector Table Entry Order: Describe the vector table as data in memory: its first word supplies the initial Main Stack Pointer, its second supplies the reset handler address, and later entries supply exception and interrupt handler addresses.
Why it matters: The entry order explains what the processor obtains from the table when it starts. - Flash Alias at Reset: Explain why placing the vector table at the start of Flash works on the STM32F1 even though Flash is physically mapped at 0x0800_0000.
Why it matters: The alias reconciles Flash's physical address with the address from which the core fetches its initial vectors. - Rust and Linker Placement: Trace how #[unsafe(link_section)] tags Rust symbols for placement and how the linker script collects their sections into an ordered vector-table region at the start of Flash.
Why it matters: Correct section placement preserves the entry order the processor expects at reset.
Key terms: vector table, Main Stack Pointer (MSP), reset handler, STM32F1, boot/memory remap logic, vector-table base address, BOOT0, BOOT1, #[unsafe(link_section)], linker script
5.5 Writing Low-Level Code with Assembly in Rust
The section explains why embedded Rust sometimes needs assembly-level access despite Rust’s high-level abstractions and memory safety guarantees.
- Need for assembly-level access: Explain why embedded development may require assembly-level access even when using Rust.
Why it matters: This explains why low-level assembly remains relevant in embedded Rust.
Key terms: assembly-level access, CPU registers, critical hardware state
5.5.1 Why Write Assembly in Embedded Rust?
This subsection explains when embedded Rust needs assembly and why using it requires explicit responsibility for safety.
- Reasons for using assembly: Explain the situations in which assembly is justified in embedded Rust: accessing processor-specific instructions or privileged CPU state, meeting precise timing or performance requirements, and bootstrapping without a runtime.
Why it matters: These reasons help you recognize when ordinary Rust is not enough for a low-level task. - Assembly safety responsibility: Explain why assembly requires extra care: it bypasses Rust’s safety model, so the programmer must make their intent explicit and take responsibility for side effects, register constraints, and synchronization.
Why it matters: Recognizing this responsibility prevents treating assembly as if Rust’s usual safety checks still cover it.
Key terms: assembly, processor-specific instructions, privileged CPU state, timing-critical routines, #[no_std], Rust’s safety model, side effects, register constraints, synchronization
5.5.2 Safe Intrinsics via cortex-m::asm
This section explains how cortex-m intrinsics issue precise Cortex-M operations for debugging, memory ordering, system-control changes, and waiting for work.
- Purpose of Cortex-M intrinsics: Explain why firmware uses cortex-m intrinsics for routine low-level operations and why their simple calls still require care.
Why it matters: A short Rust call can have a precise architectural effect. - Precise breakpoint placement: Describe what bkpt() does during interactive debugging and why it can be useful instead of a source-level breakpoint.
Why it matters: It gives you an exact place to pause when inspecting a running device. - Data barrier guarantees: Distinguish the guarantees of dmb() and dsb() and explain why peripheral or DMA hand-offs may need a memory barrier.
Why it matters: A peripheral must see the intended writes before firmware relies on them. - Instruction barrier after control changes: Explain why isb() is needed after changes to system control state such as CONTROL, privilege level, or MPU configuration.
Why it matters: Changing a control register is not enough if the core continues executing instructions fetched under the old rules. - Interrupt and event waits: Distinguish wfi() from wfe()/sev() and describe the idle-loop or signalling use explained for each.
Why it matters: Waiting for work avoids a tight polling loop and distinguishes interrupt-driven idling from event signalling.
Key terms: cortex-m crate, intrinsic functions, inline assembly, bkpt(), breakpoint instruction, memory barriers, dmb(), dsb(), system-bus visibility, DMA descriptors
5.5.3 Writing Inline Assembly with asm!()
This section explains how to use Rust’s inline assembly for Cortex-M while accurately describing its effects to the compiler.
- Inline assembly capabilities: Explain when core::arch::asm!() is useful compared with cortex-m::asm, and describe how it can hold a short sequence of instructions.
Why it matters: This helps you recognize when an intrinsic is enough and when inline assembly offers needed flexibility. - Compiler interface contract: Explain why asm!() is unsafe and why its declared effects must match what the instructions actually do.
Why it matters: Correct instructions are not enough if the compiler has been given a false account of their effects. - Register operand bindings: Distinguish input, output, and read-modify-write register bindings, and state when a specific register is warranted.
Why it matters: Bindings let Rust and the assembly block exchange values without unnecessarily constraining register choice. - Scratch register clobbers: Explain how to declare a scratch register whose contents assembly overwrites without returning a Rust value.
Why it matters: Declaring scratch-register changes prevents assembly from silently destroying a live Rust value. - Core system register access: Explain why some Cortex-M system registers call for assembly, and describe the privilege and synchronization cautions given here.
Why it matters: System-register access has different requirements from memory-mapped I/O and can affect how subsequent instructions execute.
Key terms: core::arch::asm!(), cortex-m::asm, unsafe, nomem, nostack, preserves_flags, in(reg), out(reg), inout(reg), ABI
5.5.4 Using global_asm! for Module-Level Assembly
Explains when to use global_asm! for module-level assembly, how its symbols connect to Rust, and what ABI obligations its routines must meet.
- Module-level assembly routines: Distinguish global_asm! from inline asm! and describe how assembler text defines linker-visible functions or data at module scope. Explain why this is useful for startup code or handlers needing explicit control.
Why it matters: This tells you when assembly needs to be a separate routine rather than instructions embedded in a Rust function. - Standalone routine ABI obligations: Explain why a routine written with global_asm! must follow the platform ABI, including register preservation, stack invariants, and the correct return. Distinguish Cortex-M hardware-saved exception registers from additional callee-saved registers.
Why it matters: An assembly routine can have a valid symbol yet still break execution if it violates the platform’s calling convention. - Rust access to assembly symbols: Describe how Rust code references a symbol defined in global_asm! and when that reference is resolved.
Why it matters: Exporting a symbol from assembly is only part of making it callable from Rust.
Key terms: global_asm!, asm!, .global, .section, named symbols, ABI, callee-saved registers, stack invariants, r4–r11, unsafe extern "C"
5.5.5 Linking External Assembly Files
This section explains that Rust projects can include separate assembly files through a Cargo build script.
- External assembly file integration: Explain that a Rust project can use build.rs to assemble and link an existing .S file alongside its Rust sources, keeping substantial assembly in a dedicated file.
Why it matters: This gives you a way to incorporate existing assembly while keeping it in its own file.
Key terms: .S file, build.rs, Cargo build script
5.6 Summary
Where this is used later
- Struct layout and alignment (chapter 8) · The role of data alignment in memory layout.
- Sizing the heap and avoiding allocation pitfalls (chapter 7) · The idea of explicitly placing data in a memory section.
- Launching a debugging session (chapter 6) · Provides a way to pause execution during a debugging session
- The ABI and the procedure call standard (chapter 8) · Writing inline assembly in Rust.
- Setting up the bridgeheads (chapter 8) · Revisits declaring interfaces across language boundaries.
Concepts explained in this chapter
- DSBdsb is a Cortex-M data synchronization barrier instruction that waits for preceding memory operations to complete before subsequent instruction execution.
- peripheral access crateA peripheral access crate is a typically auto-generated Rust library that exposes fine-grained access to the registers and bit fields of a specific microcontroller family.
- hardware abstraction layerA hardware abstraction layer is a software interface that represents hardware peripherals while hiding device-specific implementation details.
- memory barrierA barrier instruction is a processor instruction that constrains the ordering or completion of memory operations.
- ISBISB is an Arm Instruction Synchronization Barrier that flushes the processor pipeline and causes subsequent instructions to be fetched under preceding configuration changes.
- DMBDMB is an Arm Data Memory Barrier instruction that enforces ordering of relevant memory accesses without necessarily waiting for them to complete.
- embedded-halembedded-hal is a Rust crate defining standardized traits for accessing common embedded peripherals and services independently of specific hardware.
- volatile accessA volatile memory access is a read or write that the compiler must preserve as an observable memory operation.
- memory-mapped register blockA memory-mapped register block is a structured set of hardware control and status registers exposed at memory addresses for programmatic access.
- raw pointerRaw pointer dereferencing accesses memory through a Rust raw pointer without the safety guarantees of an ordinary reference.
- link_section attributeThe Rust link_section attribute places an item in a named object-file section.
- memory-mapped I/OMemory-mapped I/O exposes hardware registers in a processor's address space so software can access them through memory operations.
- asm!asm! is Rust's inline assembly macro for embedding target-specific instructions with explicit operands and options.
- BKPT instructionBKPT is an Arm breakpoint instruction that generates a debug breakpoint event.
- write_volatilewrite_volatile is a Rust operation that writes a value to a memory location using volatile semantics, preventing the compiler from eliding or merging the access.
- BSRRBSRR is an STM32 GPIO bit set/reset register that atomically sets or clears individual output bits without reading the current port state.
- read-modify-write operationRead-modify-write reads a value, changes selected parts, and writes the result back to the same location.
- repr(align)`repr(align)` is a Rust representation attribute that raises a type's minimum alignment to a specified boundary.
- compiler intrinsicAn intrinsic function is a compiler- or architecture-provided function that exposes a low-level operation with direct correspondence to machine instructions.
- wfiWFI is a processor instruction that puts the core into a low-power wait state until an interrupt or other wake-up event occurs.
- global_asm!global_asm! is a Rust macro that emits module-level assembler text as standalone symbols in the resulting object or executable.
- typed register overlayA struct overlay represents a hardware register block as a typed structure whose fields correspond to registers at fixed memory offsets.
- assembly operand constraintA register operand constraint directs inline assembly to bind an operand to a compiler-selected register for input, output, or read-modify-write access.
- Arm Cortex-MArm Cortex-M is a family of energy-efficient processor cores designed primarily for microcontrollers and embedded systems.
- svd2rustsvd2rust is a code-generation tool that converts a microcontroller SVD description into Rust peripheral-access source code.
- alignmentAlignment is the placement of a data object at an address satisfying the boundary requirements of its representation or hardware access.
- unsafe RustUnsafe Rust is Rust code that uses operations requiring the programmer to uphold safety invariants the compiler cannot verify.
- PRIMASKPRIMASK is a Cortex-M processor register that controls whether most configurable interrupts are permitted.
- control and status registerA system register is a processor register in the architectural system-register file that controls or reports execution state and core configuration.
- peripheralA peripheral is a hardware component connected to a processor that provides a specialized input, output, communication, timing, or control function.
- type stateThe typestate pattern represents an object's state in its type so that operations can be restricted to valid states at compile time.
- C representation`repr(C)` is a Rust representation attribute that applies C-compatible layout rules to a type.
- Peripherals::take()Peripherals::take() is a singleton-acquisition function that returns exclusive access to a device's peripheral handles when they have not already been taken.
- peripheral handleA peripheral handle is an owning value that grants exclusive software control over a peripheral's memory-mapped registers.
- memory locationA memory region is a contiguous address range with a defined role or access behavior in a processor's address space.
- unsafe blockAn unsafe block is a Rust construct in which operations requiring explicit programmer verification, such as raw-pointer dereferencing, are permitted.
- HardFaultHardFault is a Cortex-M processor exception raised when a fault cannot be handled by a more specific enabled fault handler or escalates to HardFault.
- unaligned accessAn unaligned access is a processor memory access whose address does not satisfy the alignment required by the accessed value or instruction.
- memory layoutA memory layout specifies the placement of a program's code, data, stack, and other regions in memory.
- NOLOADNOLOAD is a linker-script directive that reserves runtime memory for a section without storing its contents in the loadable image.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
