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

8.10 Lab and exercises: validating coherency and cache maintenance

This lab turns Part 8 into tests that can fail. Each test has a checker, a value that is wrong if and only if coherency or maintenance is broken. It also has a fingerprint, the PMU counts that show the test exercised what it claims to. A test with no failing variant proves nothing, so every test here is run with its maintenance or atomicity removed as well. Expect that variant to fail.

Setup

Use the bare-metal image and the labs/part08/ layout from Lab setup. The test binary runs at EL2 or EL1 Non-secure with the MMU and caches on. It brings secondaries up with PSCI CPU_ON, maps a few test regions with selectable attributes, and prints over the PL011.

# QEMU virt: built-in PSCI (conduit is hvc; smc if virtualization=on), 8 CPUs, no caches modelled
qemu-system-aarch64 -M virt,gic-version=3 -cpu max -smp 8 -m 1G \
    -nographic -kernel build/lab8.elf

# FVP Base RevC, TF-A as firmware, lab8.bin as BL33; two 4-core clusters
FVP_Base_RevC-2xAEMvA \
    -C cluster0.NUM_CORES=4 -C cluster1.NUM_CORES=4 \
    -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=uart0.log
# build the FIP with: make PLAT=fvp BL33=../labs/part08/build/lab8.bin all fip

Rerun every FVP test with -C cache_state_modelled=0. The comparison matters more than either run:

EnvironmentModelsA CMO-removal test there…
QEMU TCGTLBs, atomicity (host atomics), no cachesalways passes: CMOs are no-ops and memory is always coherent
FVP, cache_state_modelled=0TLBs, no cache statealways passes, same reason
FVP, cache_state_modelled=1cache contents, dirty lines, coherency protocol; no timingmust fail when a CMO is removed; PMU cache events may not match silicon, and timing is meaningless
Silicon or emulator with the real RTLeverything, including timing and PMUmust fail; timing and PMU fingerprints are meaningful (needs a real board or emulator)

Validation note: Record, for every test, which environment can fail it. A green run on an environment that cannot fail the test is not coverage. Reporting it as coverage is the most common pre-silicon validation mistake in this area (18.4).

PMU harness

Program counters at the EL the test runs at. EL3 and EL2 must not trap or disable them: MDCR_EL3, and MDCR_EL2.HPMN must cover the counters. Details are in 16.3.

#define NSH (1UL << 27)   /* PMEVTYPERn_EL0.NSH: also count at EL2 */

static inline void pmu_setup(void) {
    write_sysreg(NSH | 0x03, pmevtyper0_el0);   /* L1D_CACHE_REFILL */
    write_sysreg(NSH | 0x04, pmevtyper1_el0);   /* L1D_CACHE */
    write_sysreg(NSH | 0x15, pmevtyper2_el0);   /* L1D_CACHE_WB */
    write_sysreg(NSH | 0x19, pmevtyper3_el0);   /* BUS_ACCESS */
    write_sysreg(NSH, pmccfiltr_el0);           /* cycle counter: same filter */
    write_sysreg(0xF | (1UL << 31), pmcntenset_el0); /* counters 0-3 + cycle */
    write_sysreg(read_sysreg(pmcr_el0) | 0x7, pmcr_el0); /* E, P, C: enable+reset */
    isb();
}

With NSH == 0 (the value a bare event number gives), events at EL2 are not counted, so a test running at EL2 would read zeros. The event numbers are the common architectural events. A core may not implement all of them, so check PMCEID0_EL0 (for events 0x00 to 0x1F, bit n set means event n is implemented; PMCEID1_EL0 covers 0x20 to 0x3F). Interconnect events, such as snoops sent, snoop-filter hits and back-invalidations at the HN-F, or DVM operations, come from the CMN or DSU PMU. Their encodings are IMPLEMENTATION DEFINED, so take them from that product’s TRM.

Test 1: false sharing vs true sharing

Two cores each increment their own counter 10⁶ times with plain LDR/ADD/STR.

  • Variant F (false sharing): the counters are in one 64-byte line.
  • Variant P (padded): the counters are CTR_EL0.CWG-aligned and in separate lines.

Checker: each final counter equals 10⁶. False sharing is a performance effect, never a correctness one. Any difference is a coherency bug.

Fingerprint, on silicon: in F, L1D_CACHE_REFILL approaches one per increment on each core, because every store must regain unique ownership, and cycles per iteration rise by 10–100×. In P, refills are near zero after warm-up. Put the two cores on different clusters, then on different chiplets. The refill count stays the same but the cycles per refill grow, which measures the snoop path (8.3). If F and P have the same refill rate, look for a wrong line-size assumption, or an allocation that is not the size you think.

True sharing: both cores increment one counter. Now the checker is the lost-update test.

Test 2: lost-update detection, exclusives vs LSE

N cores (one per cluster and chiplet at least) each add 1 to a shared counter M times. Three implementations:

// (a) plain: expected to lose updates
1:  ldr     x1, [x0]
    add     x1, x1, #1
    str     x1, [x0]
// (b) exclusives
2:  ldxr    x1, [x0]
    add     x1, x1, #1
    stxr    w2, x1, [x0]
    cbnz    w2, 2b
// (c) LSE (FEAT_LSE)
    mov     x1, #1
    stadd   x1, [x0]

Checker: the total equals N×M for (b) and (c). For (a), the architecture permits lost updates but does not require them; under real contention the total comes out below N×M in practice, and the test design relies on that. If (a) never loses an update, the test is not creating contention: the cores are not actually running at the same time, or the model serialises them. Fix the test before trusting (b) and (c).

Fingerprint: for (b), count STXR failures in software (the cbnz taken count). It should be non-zero under contention and must not grow without bound (livelock). For (c), on CHI systems that execute far atomics, L1D_CACHE_REFILL on the counter line can stay near zero while HN-F atomic counters rise. Whether STADD goes near or far is IMPLEMENTATION DEFINED, and on some cores it is configurable. Run the test on Write-Back memory and on Non-cacheable memory, where exclusives depend on a global monitor. The memory-type matrix and the near/far details are in 10.1 and 10.2.

Test 3: CMO-plus-DMA round trips

Use a real non-coherent DMA engine on a board. On FVP with cache modelling, a Non-cacheable alias of the buffer stands in for the non-coherent master, because its accesses bypass the modelled caches. This is a deliberate mismatched-attribute trick for testing only (6.6), and it emulates the data path of a master that does not snoop, not its timing.

Checker pattern: every 64-bit word holds addr ^ seed ^ iteration. It is unique per word and per pass, so a stale line shows up as the previous iteration’s value at a known address, not as random garbage.

for (it = 0; it < ITERS; it++) {
    fill(src, len, seed, it);              /* PE writes via WB mapping */
    memset(dst, 0xA5, len);                /* PE dirties dst, so T2 matters */
    dc_cvac_range(src, len); dsb_sy();     /* to-device: clean      [T1] */
    dc_civac_range(dst, len); dsb_sy();    /* from-device: pre-clean [T2] */
    dma_copy(dst, src, len);               /* or NC-alias memcpy on FVP */
    dma_wait();
    dc_ivac_range(dst, len); dsb_sy();     /* from-device: invalidate [T3] */
    check(dst, len, seed, it);             /* report first bad addr + value */
}

Run the matrix: remove T1, T2, T3 one at a time. Misalign dst by 8–56 bytes with live neighbour data. Add a second core that read-streams dst during the copy, to provoke speculative and prefetch refills. The expected outcomes on a cache-modelling environment are: no T1 gives old data at the destination; no T2 corrupts the destination (with 0xA5 bytes) when a dirty line from the memset is evicted during or after the copy; no T3 gives stale reads, more often with the prefetching core; misalignment damages the neighbour data. Each failure should be reproducible within a bounded number of iterations. A failure that never appears means that environment cannot see it. The sequences themselves are in 8.7.

Test 4: TLBI shootdown across clusters and chiplets

One page VA V is mapped to PA1 (filled with tag 0x11) and readable by every core. Readers loop: read flag F with LDAR, read [V], record any (F == 1, value == 0x11) pair. The writer remaps with break-before-make (9.2):

    // x_pte, x_va, x_new, x_flag are symbolic; substitute real registers
    str     xzr, [x_pte]              // invalidate descriptor
    dsb     ishst
    tlbi    vale1is, x_va             // broadcast; x_va = VA[55:12] (and ASID)
    dsb     ish                       // complete on every PE in the IS domain
    str     x_new, [x_pte]            // descriptor for PA2 (tag 0x22)
    dsb     ishst
    mov     w9, #1
    stlr    w9, [x_flag]

Checker: no reader may observe F == 1 and then read 0x11. That combination means some PE kept a translation through a completed broadcast TLBI: a DVM message did not reach its cluster or chiplet, or a DVM Sync completed early. Readers may legitimately fault while the descriptor is invalid. Make the fault handler retry. Place readers on every cluster and every chiplet; a chiplet whose DVM forwarding is misconfigured is the target (17.5). Then drop IS (use TLBI VALE1) and confirm the checker fires on remote readers. On QEMU it may not fire, because TCG’s cross-CPU flush is often stronger than the architecture requires. The full sequence rationale is in 9.1.

Fingerprint: the CMN or DSU DVM counters increment once per TLBI ...IS plus one sync per DSB. A reader core’s L1D_TLB_REFILL (0x05) rises once after each remap.

Exercises: find the missing CMO

Each snippet is from firmware for a platform with the stated properties. Say what is missing, why it fails, and when it would show up.

E1. BL2 running at EL3 (as in a RESET_TO_BL2 build), with MMU and D-cache on, copies BL31 into SRAM with memcpy, then ERETs to BL31’s entry, which runs with SCTLR_EL3.{M,C,I} = 0.

Answer

BL31’s image may still be dirty in BL2’s D-cache. BL31 fetches and reads with caches off, so from memory, and it can get stale bytes. Clean the image to PoC (DC CVAC loop, DSB SY) before the ERET. Invalidate the I-cache (IC IALLU) if BL31’s address range may have been executed before. TF-A’s image loader does this with flush_dcache_range(). On FVP this fails only with cache_state_modelled=1, and typically as a hang in BL31’s early C code.

E2. A non-coherent NIC transmit path:

desc->addr = buf_pa; desc->len = len; desc->own = 1;
dmb(st);
writel(TX_DOORBELL, tail);
Answer

Both the payload buf and the descriptor must be cleaned to PoC (DC CVAC over each), and a DSB must separate the cleans from the doorbell. DMB ST orders the stores as PE-side observers see them, but the NIC reads DRAM and never snoops, so it can fetch an old descriptor or payload. The symptom is intermittently corrupt frames, or a descriptor the NIC reports as not owned. It is worse when the buffer was recently written and still sits in L1.

E3. The receive path does DC CIVAC over the buffer and DSB SY, starts the DMA, and on the completion IRQ parses the buffer directly.

Answer

The invalidate after completion is missing. During the transfer the PE can speculatively or prefetch-allocate lines of the buffer, holding pre-DMA data. Add DC IVAC (or DC CIVAC on non-line-aligned edges) plus DSB SY before parsing. It shows up rarely, and more often when other code touches adjacent memory or the hardware prefetcher is aggressive.

E4. The primary core writes the secondary’s entry point and stack pointer to a mailbox in DRAM with caches on, then releases the secondary with an SEV. The secondary starts with MMU and caches off and spins reading the mailbox.

Answer

The mailbox must be cleaned to PoC (DC CVAC, DSB SY) before the SEV. The secondary’s reads are Device-nGnRnE (MMU off) and go to memory. They cannot see the primary’s dirty line in any architecturally guaranteed way. The DSB before SEV is also needed so that the clean completes before the event is sent. The symptom is a secondary that never leaves its spin loop, or jumps to address 0. It often “goes away” with debug prints, because those evict the line.

E5. A JIT on core A:

    // code written via x0..x1
    dc   cvau, x0          // looped over range
    ic   ivau, x0          // looped over range
    dsb  ish
    isb
    stlr x0, [x_fnptr]

Core B loads fnptr with LDAR and calls it. CTR_EL0.IDC == DIC == 0.

Answer

Two things are missing. First, a DSB ISH between the DC CVAU loop and the IC IVAU loop; without it, the invalidate can complete before the clean, and a refill can bring the old bytes back into the I-cache. Second, core B needs a context synchronization event (an ISB) after its LDAR and before the call; A’s ISB affects only A. See 8.6. The second bug shows up as B occasionally executing the previous contents of a reused code buffer.

E6. On a Cortex-A53 cluster, the PSCI power-down path for the last core in the cluster clears SCTLR_EL3.C, cleans and invalidates by set/way up to LoUIS, clears SMPEN, and requests cluster power-off.

Answer

LoUIS covers only the L1 on Cortex-A53. The cluster’s shared L2 also loses power, so the last core must also clean and invalidate L2 by set/way (TF-A’s cortex_a53_cluster_pwr_dwn calls dcsw_op_level2, or uses dcsw_op_all) before leaving coherency. Dirty lines that lived only in L2 are lost. That data is often other cores’ data, such as kernel state written just before those cores went offline. It appears after cluster-level suspend, not core-level suspend. See 8.8.

Checkpoint

Q8.10.1 A pre-silicon team reports that the DMA round-trip test passes with every combination of CMOs removed, on both QEMU and FVP. What is the correct conclusion?

  • A. The SoC’s DMA path is I/O-coherent, so the driver’s CMOs can be dropped
  • B. The CMOs are correct, because the test passed with them in place
  • C. The checker pattern is too weak and should use random data
  • D. Neither environment can fail this test as run. The result gives no coverage until it is rerun on FVP with cache_state_modelled=1 (or on RTL or silicon) and the removal variants fail
Answer

D. QEMU models no caches, and the FVP run evidently has cache-state modelling off, or the “device” bypasses nothing. A test whose failing variants pass has not shown it can detect the bug. Option A confuses a model artefact with a hardware property: I/O coherency must come from the SoC’s design and its firmware description (IORT/DT), not from a green test.

Read more: Arm Fast Models / FVP Reference Guide, cache state modelling; Arm ARM (DDI0487), data cache maintenance instructions

Q8.10.2 In the TLBI shootdown test, a reader on chiplet 1 records F == 1 followed by a read of the old page’s tag. Readers on chiplet 0 never do. The writer’s sequence is exactly as shown in Test 4. What is the most likely cause?

  • A. The reader is missing an ISB after its LDAR
  • B. The broadcast TLBI or its DVM Sync is not reaching, or not being completed by, chiplet 1. For example, the chiplet link’s DVM forwarding is not enabled
  • C. TLBI VALE1IS only invalidates last-level entries, so the reader’s walk cache kept the old leaf
  • D. The reader’s load is speculative and therefore allowed to use stale translations
Answer

B. After the writer’s DSB ISH completes, no PE in the Inner Shareable domain may still use the old translation. A failure confined to one chiplet points at DVM propagation or sync completion across the link. Option A: an ISB is not needed for data accesses to use a new translation once the TLBI has completed, and the acquire orders the data read after the flag. Option C: VALE1 removes the leaf entry, which is exactly the one that changed.

Read more: Arm ARM (DDI0487), TLB maintenance instructions and completion by DSB; CHI specification, DVM operations

Q8.10.3 In the lost-update test, variant (a) (plain LDR/ADD/STR) never loses an update over 10⁹ iterations on 8 cores in a model, and variants (b) and (c) also total exactly N×M. What should you conclude?

  • A. Variant (a) is accidentally atomic because the counter is 64-bit aligned
  • B. The environment provides sequential consistency, so the atomics are correct
  • C. The test is not producing real contention in that environment, so the (b) and (c) results are not evidence of atomicity
  • D. The exclusive monitor is working, so (a) also benefits from it
Answer

C. The architecture does not forbid a plain read-modify-write from losing updates, and under real concurrency over 10⁹ iterations it does so in practice. If it never does, the cores are being serialised, for example by a model’s quantum scheduling, or they are not running at the same time. Then the atomic variants are not being tested either. Fix the test (raise the iterations, shrink the model’s quantum, or confirm the cores overlap) before drawing conclusions. Option A misreads single-copy atomicity: each access is atomic, but the read-modify-write sequence is not.

Read more: Arm ARM (DDI0487), single-copy atomicity; Load-Exclusive and Store-Exclusive instructions