Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lab setup

The labs in 5.9, 7.11 and 8.10 use four tools. Each answers a different question, and none of them answers all of them:

ToolWhat it isGood forCannot show
QEMU virt (TCG)Fast functional emulator with a gdbstubEL3 bare-metal code, exception and translation flow, quick iterationCaches (CMOs are no-ops), weak memory ordering, timing
Arm FVP FVP_Base_RevC-2xAEMvAArm’s Architecture Envelope Model of the Base platform, configurable per featureFeatures QEMU lacks or approximates, TF-A as on real platforms, Tarmac instruction traces, optional cache-state modellingReordering (each PE executes in order), timing
herd7Executes litmus tests against the formal AArch64 memory model (aarch64.cat)What the architecture allowsWhat any implementation does
litmus7Generates C test harnesses that run a litmus test millions of times on LinuxWhat an implementation doesAnything about the architecture as such

A step that needs a real board says so. See 18.4 for what each environment hides.

Host packages

On a Debian or Ubuntu x86-64 host:

sudo apt install build-essential git make device-tree-compiler libssl-dev \
    gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu gdb-multiarch \
    qemu-system-arm opam

qemu-system-arm provides qemu-system-aarch64. The distribution’s QEMU is fine if it is recent. Check that qemu-system-aarch64 -cpu help lists max. For the newest FEAT_ support, build QEMU from source.

For bare-metal code, use the Arm GNU Toolchain aarch64-none-elf target, downloaded from Arm’s developer site (search for “Arm GNU Toolchain downloads”):

mkdir -p "$HOME/opt"
tar xf arm-gnu-toolchain-*-x86_64-aarch64-none-elf.tar.xz -C "$HOME/opt"
export PATH="$(echo "$HOME"/opt/arm-gnu-toolchain-*-aarch64-none-elf/bin):$PATH"
aarch64-none-elf-gcc --version

The Makefile below also works with the distribution’s aarch64-linux-gnu-gcc (make CROSS=aarch64-linux-gnu-), because it passes -ffreestanding -nostdlib and disables PIE and the stack protector, which some distributions enable by default. aarch64-linux-gnu-gcc is required for litmus7 harnesses, which are Linux user programs.

Repository layout

The labs assume one working directory:

armv8-labs/
├── labs/
│   ├── common/          minimal EL3 image from this page: start.S vectors.S uart.c main.c link.ld Makefile
│   ├── part05/          5.9: self-contained start.S, lab.c, link.ld (see 5.9)
│   ├── part07/          7.11: tests/ (litmus files), run-qemu/, run-board/, model.txt
│   └── part08/          8.10: test sources, build/lab8.elf, build/lab8.bin
├── tf-a/                Trusted Firmware-A clone, for FVP runs that boot through BL1/BL31 (8.10)
└── guest/               Linux kernel Image and rootfs.ext4 for litmus7 runs (7.11)

Commands in the labs are given relative to armv8-labs/ unless the lab says cd first. Each lab directory holds its build output under build/, so a stale binary from another lab is never picked up.

A minimal bare-metal EL3 image

The image in labs/common/ is the smallest useful starting point. It parks every PE except the one with affinity 0.0.0, sets SCTLR_EL3 to a known value, installs an EL3 vector table, clears .bss, initialises the PL011 UART, prints a few ID registers, and takes a deliberate exception to prove that the vectors work. It runs unchanged on QEMU virt (with secure=on) and on the FVP. Only the UART base and the load address differ between the two.

link.ld

ENTRY(_start)
SECTIONS {
  . = LOAD_ADDR;
  .text : {
    *(.text.boot)
    . = ALIGN(2048);  *(.text.vectors)      /* VBAR_EL3 needs 2KB alignment */
    *(.text*)
  }
  .rodata : { *(.rodata*) }
  .data   : { *(.data*) }
  .bss    : ALIGN(16) { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(16); __bss_end = .; }
  . = ALIGN(16); . += 0x4000; __stack_top = .;
}

start.S

    .section .text.boot, "ax"
    .global _start
_start:
    mrs     x0, mpidr_el1
    and     x0, x0, #0xffffff       // Aff2:Aff1:Aff0
    cbz     x0, primary
park:                               // secondaries: QEMU (secure=on) and FVP may start them here too
    wfe
    b       park

primary:
    ldr     x0, =0x30c50830         // SCTLR_EL3 base value (see below); M=0 C=0 I=0 A=0 EE=0
    msr     sctlr_el3, x0
    ldr     x0, =el3_vectors
    msr     vbar_el3, x0
    isb                             // new SCTLR_EL3 and VBAR_EL3 in effect before anything can fault

    ldr     x0, =__bss_start
    ldr     x1, =__bss_end
1:  cmp     x0, x1
    b.hs    2f
    str     xzr, [x0], #8
    b       1b
2:  ldr     x0, =__stack_top
    mov     sp, x0                  // PSTATE.SP is 1 at reset, so this is SP_EL3
    bl      main
3:  wfe
    b       3b

Most SCTLR_EL3 fields reset to UNKNOWN values, so the code writes the whole register. 0x30c50830 sets bits 29, 28, 23, 22, 18, 16, 11, 5 and 4, which is TF-A’s SCTLR_EL3 base value. They are RES1, except that bits 22 and 11 are EIS and EOS when FEAT_ExS is implemented, and 1 is the setting that keeps exception entry and exit context-synchronizing. With M = 0, EL3 data accesses are Device-nGnRnE, so every access must be aligned. That is why the Makefile passes -mstrict-align (6.5).

vectors.S

    .macro  ventry id
    .balign 0x80
    mov     x0, #\id
    b       el3_unhandled
    .endm

    .section .text.vectors, "ax"
    .balign 0x800
    .global el3_vectors
el3_vectors:
    ventry 0    // Current EL, SP_EL0: Synchronous
    ventry 1    //                     IRQ
    ventry 2    //                     FIQ
    ventry 3    //                     SError
    ventry 4    // Current EL, SP_ELx: Synchronous
    ventry 5    //                     IRQ
    ventry 6    //                     FIQ
    ventry 7    //                     SError
    ventry 8    // Lower EL, AArch64:  Synchronous
    ventry 9    //                     IRQ
    ventry 10   //                     FIQ
    ventry 11   //                     SError
    ventry 12   // Lower EL, AArch32:  Synchronous
    ventry 13   //                     IRQ
    ventry 14   //                     FIQ
    ventry 15   //                     SError

Each entry is 0x80 bytes and the table is 0x800 bytes, aligned to 2KB (3.1). The handler never returns, so it does not save registers.

uart.c (PL011; register offsets from the PL011 TRM)

#include <stdint.h>

#ifdef PLAT_FVP
#define UART_BASE 0x1c090000UL          /* FVP Base: UART0 */
#else
#define UART_BASE 0x09000000UL          /* QEMU virt: UART0 */
#endif

#define REG(off)   (*(volatile uint32_t *)(UART_BASE + (off)))
#define UARTDR     REG(0x000)
#define UARTFR     REG(0x018)
#define UARTIBRD   REG(0x024)
#define UARTFBRD   REG(0x028)
#define UARTLCR_H  REG(0x02c)
#define UARTCR     REG(0x030)
#define FR_BUSY    (1u << 3)
#define FR_TXFF    (1u << 5)

void uart_init(void)
{
    UARTCR = 0;                         /* disable while configuring */
    while (UARTFR & FR_BUSY)
        ;
    UARTIBRD = 13;                      /* 115200 baud from a 24 MHz UARTCLK */
    UARTFBRD = 1;
    UARTLCR_H = (3u << 5) | (1u << 4);  /* 8 data bits, FIFOs on; also latches IBRD/FBRD */
    UARTCR = (1u << 9) | (1u << 8) | 1u;/* RXE, TXE, UARTEN */
}

void uart_putc(char c)
{
    if (c == '\n')
        uart_putc('\r');
    while (UARTFR & FR_TXFF)
        ;
    UARTDR = (uint32_t)c;
}

void uart_puts(const char *s) { while (*s) uart_putc(*s++); }

void uart_hex(uint64_t v)
{
    uart_puts("0x");
    for (int i = 60; i >= 0; i -= 4)
        uart_putc("0123456789abcdef"[(v >> i) & 0xf]);
}

Neither model needs the baud-rate setup to produce output, but real PL011s do, and recent QEMU logs a guest error (-d guest_errors) if you write to a UART whose UARTEN or TXE bit is clear. The divisor assumes the 24 MHz UART clock of the FVP Base platform. Check your board’s clock.

main.c

#include <stdint.h>

void uart_init(void);
void uart_puts(const char *s);
void uart_hex(uint64_t v);

#define READ_SYSREG(r) ({ uint64_t _v; __asm__ volatile("mrs %0, " #r : "=r"(_v)); _v; })

static void show(const char *name, uint64_t v) { uart_puts(name); uart_hex(v); uart_puts("\n"); }

void el3_unhandled(uint64_t slot)
{
    show("\nunhandled exception, vector slot ", slot);
    show("  ESR_EL3  ", READ_SYSREG(esr_el3));
    show("  ELR_EL3  ", READ_SYSREG(elr_el3));
    show("  FAR_EL3  ", READ_SYSREG(far_el3));
    show("  SPSR_EL3 ", READ_SYSREG(spsr_el3));
    for (;;)
        __asm__ volatile("wfe");
}

int main(void)
{
    uart_init();
    show("CurrentEL        ", READ_SYSREG(CurrentEL) >> 2);
    show("MIDR_EL1         ", READ_SYSREG(midr_el1));
    show("MPIDR_EL1        ", READ_SYSREG(mpidr_el1));
    show("ID_AA64PFR0_EL1  ", READ_SYSREG(id_aa64pfr0_el1));
    show("ID_AA64MMFR0_EL1 ", READ_SYSREG(id_aa64mmfr0_el1));
    uart_puts("taking BRK #0x42 at EL3...\n");
    __asm__ volatile("brk #0x42");
    return 0;
}

Makefile (recipe lines start with a tab)

PLAT    ?= qemu
CROSS   ?= aarch64-none-elf-
CC       = $(CROSS)gcc
OBJCOPY  = $(CROSS)objcopy
CFLAGS   = -O1 -g -Wall -ffreestanding -nostdlib -fno-pie -fno-stack-protector \
           -mstrict-align -mgeneral-regs-only -fno-tree-loop-distribute-patterns
ifeq ($(PLAT),fvp)
CFLAGS  += -DPLAT_FVP
LOAD     = 0x80000000
else
LOAD     = 0x40080000
endif
OUT      = build/$(PLAT)
SRCS     = start.S vectors.S uart.c main.c

$(OUT)/el3.elf: $(SRCS) link.ld | $(OUT)
	$(CC) $(CFLAGS) -no-pie -static -Wl,--defsym=LOAD_ADDR=$(LOAD) -T link.ld $(SRCS) -o $@
	$(OBJCOPY) -O binary $@ $(OUT)/el3.bin

$(OUT):
	mkdir -p $@

clean:
	rm -rf build
.PHONY: clean

-mgeneral-regs-only keeps the compiler from using FP/SIMD registers. Their use would trap if CPTR_EL3.TFP, which is UNKNOWN after reset, happened to be 1 (15.3). -fno-tree-loop-distribute-patterns stops GCC from turning the loops into calls to memset, which does not exist here. QEMU loads the image at 0x40080000 rather than at the base of RAM, because for a bare-metal ELF it places the device tree blob at the start of RAM.

Expected output (values vary with the model and its configuration):

CurrentEL        0x0000000000000003
MIDR_EL1         0x...
MPIDR_EL1        0x...
ID_AA64PFR0_EL1  0x...
ID_AA64MMFR0_EL1 0x...
taking BRK #0x42 at EL3...

unhandled exception, vector slot 0x0000000000000004
  ESR_EL3  0x00000000f2000042
  ELR_EL3  0x...                      (address of the BRK)
  FAR_EL3  0x...                      (UNKNOWN for this exception)
  SPSR_EL3 0x...

The exception arrives in slot 4 (current EL with SP_ELx, Synchronous). ESR_EL3 = 0xf2000042 decodes as EC 0x3C (BRK instruction execution in AArch64 state), IL = 1, ISS = the immediate 0x42. A BRK is taken to the current Exception level when that level is EL2 or EL3. If the output stops before the BRK line, the UART base or load address is wrong. If it stops at the BRK line, VBAR_EL3 or the table alignment is wrong.

Running on QEMU

cd labs/common && make PLAT=qemu
qemu-system-aarch64 -M virt,secure=on,virtualization=on -cpu max -smp 1 -m 1G \
    -nographic -kernel build/qemu/el3.elf \
    -d int,mmu,guest_errors,unimp -D qemu.log      # exit QEMU: Ctrl-A then x
  • secure=on gives the CPU EL3 and adds the Secure-only memory and devices. virtualization=on gives it EL2. With both set, an ELF that is not a Linux kernel image starts at EL3, at its ELF entry point. With -smp greater than 1, whether the secondary CPUs also start at the entry point or are held powered off depends on the QEMU version and machine options, so start.S parks any PE whose affinity is not 0.0.0.
  • -cpu max enables every feature the QEMU build supports. Individual features can be switched off (-cpu max,sve=off, -cpu max,pauth=off) to test discovery code. -M virt,...,mte=on adds MTE tag storage. -cpu max,x-rme=on enables QEMU’s experimental RME support. Check the result in the ID registers rather than trusting the command line.
  • -d int logs every exception taken, with its ESR, FAR and ELR. This is the fastest way to find a fault loop. mmu logs MMU-related events, guest_errors logs accesses that real hardware would reject or that are probably bugs (unmapped MMIO, a disabled UART), and unimp logs accesses to devices or registers QEMU does not implement. -D sends the log to a file. qemu-system-aarch64 -d help lists all items.
  • gdbstub. Add -s -S to listen on TCP port 1234 and hold the CPU at reset:
qemu-system-aarch64 ... -s -S &
gdb-multiarch build/qemu/el3.elf \
    -ex 'target remote :1234' -ex 'break main' -ex 'continue'

QEMU exposes the system registers to gdb by their architectural names, so p/x $SCTLR_EL3 and p/x $VBAR_EL3 work, and info all-registers lists them all. The aarch64-none-elf-gdb from the Arm GNU Toolchain works too, if your toolchain package includes it.

Running on the Arm FVP

Download the Armv-A Base RevC AEM FVP (FVP_Base_RevC-2xAEMvA) from Arm’s Ecosystem FVP downloads page (free, Linux x86-64 and AArch64 hosts). It unpacks to a Base_RevC_AEMvA_pkg/ directory. The executable is under models/Linux64_GCC-*/ and the plugins are under plugins/Linux64_GCC-*/. The GCC version in the directory name changes between releases.

export FVP_DIR=$HOME/opt/Base_RevC_AEMvA_pkg
export PATH="$(echo "$FVP_DIR"/models/Linux64_GCC-*):$PATH"
cd labs/common && make PLAT=fvp
FVP_Base_RevC-2xAEMvA \
    -C cluster0.NUM_CORES=1 -C bp.secure_memory=0 \
    -C bp.pl011_uart0.out_file=- -C bp.pl011_uart0.unbuffered_output=1 \
    -C bp.terminal_0.start_telnet=0 -C bp.vis.disable_visualisation=1 \
    -a cluster0.cpu0=build/fvp/el3.elf \
    --plugin "$(echo "$FVP_DIR"/plugins/Linux64_GCC-*/TarmacTrace.so)" \
    -C TRACE.TarmacTrace.trace-file=el3.tarmac
  • -a cluster0.cpu0=FILE loads the ELF and sets that PE’s start address to its entry point. If your FVP version does not, set the reset address with -C cluster0.cpu0.RVBAR=0x80000000.
  • bp.secure_memory=0 turns off the platform’s TrustZone memory filtering, so EL3 can run from DRAM at 0x80000000 without programming the TZC first. TF-A’s documented FVP runs set bp.secure_memory=1, so that the filtering TF-A programs is enforced.
  • UART. out_file=- sends UART0 to stdout, and start_telnet=0 stops the model opening a terminal window.
  • Tarmac records every executed instruction, register write, memory access and exception. Grep it for ESR_EL3 or for an exception record instead of single-stepping. The trace options vary by FVP release. List them with --plugin .../TarmacTrace.so --list-params | grep TRACE.TarmacTrace.
  • Parameters in general. FVP_Base_RevC-2xAEMvA --list-params prints every parameter with its default. Pipe it to grep -i when a lab names a parameter your version does not recognise. Parameter names do change between releases.
  • Debugging. -I starts the Iris debug server, which Arm Development Studio connects to. Recent FVP packages also ship a GDBRemoteConnection.so plugin for gdb. It prints its port when the model starts, and its parameters appear in --list-params when it is loaded.

Selecting architecture features

The AEM model implements whatever the parameters say. These are the ones the book uses. Set each one for cluster1 as well if that cluster has cores.

ParameterEffect
cluster0.has_arm_v9-2=1 (or v8-7, v9-4, …)Selects the architecture version and its mandatory features
cluster0.memory_tagging_support_level=2 plus bp.dram_metadata.is_enabled=1FEAT_MTE2. Use 3 for FEAT_MTE3. Without the DRAM metadata parameter, tags are not stored, and the model does not warn you.
cluster0.rme_support_level=2 plus bp.has_rme=1FEAT_RME in the PE, plus the platform-side RME support. TF-A must be built with ENABLE_RME=1. The TF-A RME documentation gives the complete parameter list.
cluster0.has_sve=1, cluster0.sve.has_sme=1, cluster0.sve.has_sme2=1SVE, SME and SME2
cluster0.has_branch_target_exception=1FEAT_BTI
cluster0.max_32bit_el=-1No AArch32 at any EL
cluster0.PA_SIZE=48Physical address size, reported in ID_AA64MMFR0_EL1.PARange
cache_state_modelled=1Model cache contents, so that missing maintenance can produce wrong data (8.10). Slower.

Booting through TF-A

8.10 runs its test at EL2 or EL1 as a BL33 image, with TF-A providing BL1, BL2, BL31 and PSCI:

git clone https://git.trustedfirmware.org/TF-A/trusted-firmware-a.git tf-a
make -C tf-a CROSS_COMPILE=aarch64-none-elf- PLAT=fvp DEBUG=0 \
    BL33=$PWD/labs/part08/build/lab8.bin all fip
# outputs: tf-a/build/fvp/release/bl1.bin and fip.bin
FVP_Base_RevC-2xAEMvA \
    -C pctl.startup=0.0.0.0 -C bp.secure_memory=1 -C cache_state_modelled=1 \
    -C bp.secureflashloader.fname=tf-a/build/fvp/release/bl1.bin \
    -C bp.flashloader0.fname=tf-a/build/fvp/release/fip.bin \
    -C bp.pl011_uart0.out_file=- -C bp.terminal_0.start_telnet=0 \
    -C bp.vis.disable_visualisation=1 -C bp.ve_sysregs.exit_on_shutdown=1

The pctl.startup, secure_memory and cache_state_modelled settings follow TF-A’s documented FVP runs. Drop cache_state_modelled=1 for faster runs when you are not testing maintenance. DEBUG=1 puts the output in build/fvp/debug/ and makes BL1 and BL31 log much more. TF-A’s FVP build needs dtc (device-tree-compiler), and its host tools need OpenSSL headers. Arm’s Shrinkwrap tool packages complete FVP configurations (firmware, kernel and the matching model parameters) if you want a full software stack without assembling it yourself.

herdtools7: herd7 and litmus7

Install through opam, OCaml’s package manager:

opam init -y && eval "$(opam env)"
opam install herdtools7               # herd7, litmus7, diy7, mcompare7 and friends
herd7 -version

To build from source instead, clone https://github.com/herd/herdtools7, install the dependencies with opam install . --deps-only, then make all and make PREFIX=$HOME/.local install. The default PREFIX is $HOME.

Smoke test: message passing with DMB on both sides, whose relaxed outcome the model forbids.

AArch64 MP+dmb.sys
{
0:X1=x; 0:X3=y;
1:X1=y; 1:X3=x;
}
 P0          | P1          ;
 MOV W0,#1   | LDR W0,[X1] ;
 STR W0,[X1] | DMB SY      ;
 DMB SY      | LDR W2,[X3] ;
 MOV W2,#1   |             ;
 STR W2,[X3] |             ;
exists (1:X0=1 /\ 1:X2=0)
mkdir -p labs/part07/tests && cd labs/part07
# save the test above as tests/MP+dmb.sys.litmus
herd7 -model aarch64.cat tests/MP+dmb.sys.litmus

The output lists three reachable final states and ends with Observation MP+dmb.sys Never 0 3: the exists clause is satisfied in none of them. Delete both DMB SY lines and the result becomes Sometimes. Recent herd7 versions may also print a flag about the shareability argument of DMB (7.5). That flag does not change the verdict.

A Linux guest for litmus7

litmus7 harnesses are Linux user programs, so the QEMU and FVP runs in 7.11 need a kernel and a root filesystem. Buildroot builds both:

git clone https://gitlab.com/buildroot.org/buildroot.git guest/buildroot
make -C guest/buildroot qemu_aarch64_virt_defconfig
make -C guest/buildroot -j"$(nproc)"
cp guest/buildroot/output/images/Image guest/buildroot/output/images/rootfs.ext4 guest/

The guest has no compiler, so build the harness on the host and copy the binaries in. Generate it with the 7.11 options (-gcc aarch64-linux-gnu-gcc -linkopt -static). Pass -o run-qemu to get a directory rather than an archive, or unpack the archive into run-qemu/. Then:

cd labs/part07
make -C run-qemu                      # cross-compiles with aarch64-linux-gnu-gcc
mkdir -p mnt && sudo mount -o loop ../../guest/rootfs.ext4 mnt
sudo cp -r run-qemu mnt/root/ && sudo umount mnt
cd ../..
qemu-system-aarch64 -M virt -cpu max -smp 4 -m 2G -accel tcg,thread=multi -nographic \
    -kernel guest/Image -append "rootwait root=/dev/vda console=ttyAMA0" \
    -drive file=guest/rootfs.ext4,if=none,format=raw,id=hd0 \
    -device virtio-blk-device,drive=hd0
# log in as root, then:  cd run-qemu && sh run.sh > qemu.txt

On a board running Linux, build natively, or cross-build the same way and copy the directory over. Only board runs can show relaxed outcomes that QEMU on an x86 host and the FVP never produce (7.11).

Checklist

Before starting the labs, confirm that:

  • the EL3 image prints CurrentEL 0x...03 and the BRK report on both QEMU and the FVP;
  • qemu.log shows the BRK exception when run with -d int;
  • the FVP Tarmac file contains the brk instruction and the exception entry that follows it;
  • herd7 reports Never for MP+dmb.sys and Sometimes for the version without barriers;
  • the Linux guest boots in QEMU and runs a litmus7 harness built on the host.