7.11 Lab and exercises: litmus testing from model to silicon
The lab has three parts. You compute what the architecture allows with herd7, observe what an implementation does with litmus7, and then reason about the gap between the two. The tests are the shapes from 7.3, with the barriers and dependencies of 7.4–7.5. Files go in labs/part07/ (Lab setup).
Step 0: tools
opam install herdtools7 # provides herd7, litmus7, diy7, mcompare7
herd7 -version
mkdir -p labs/part07/{tests,run-qemu,run-board}
herd7 ships the AArch64 model as aarch64.cat in its library directory and uses it by default for AArch64 tests. Passing -model aarch64.cat makes the choice explicit in your logs.
Step 1: write the tests
tests/MP+dmb.st+addr.litmus. The address dependency is the classic EOR-to-zero trick from 7.4:
AArch64 MP+dmb.st+addr
{
0:X1=x; 0:X3=y;
1:X1=y; 1:X3=x;
}
P0 | P1 ;
MOV W0,#1 | LDR W0,[X1] ;
STR W0,[X1] | EOR W2,W0,W0 ;
DMB ST | LDR W4,[X3,W2,SXTW] ;
MOV W2,#1 | ;
STR W2,[X3] | ;
exists (1:X0=1 /\ 1:X4=0)
tests/SB+dmb.sys.litmus:
AArch64 SB+dmb.sys
{
0:X1=x; 0:X3=y;
1:X1=y; 1:X3=x;
}
P0 | P1 ;
MOV W0,#1 | MOV W0,#1 ;
STR W0,[X1] | STR W0,[X1] ;
DMB SY | DMB SY ;
LDR W2,[X3] | LDR W2,[X3] ;
exists (0:X2=0 /\ 1:X2=0)
tests/WRC+addr+addr.litmus is three threads. It tests other-multi-copy atomicity (7.2):
AArch64 WRC+addr+addr
{
0:X1=x;
1:X1=x; 1:X4=y;
2:X1=y; 2:X4=x;
}
P0 | P1 | P2 ;
MOV W0,#1 | LDR W0,[X1] | LDR W0,[X1] ;
STR W0,[X1] | EOR W2,W0,W0 | EOR W2,W0,W0 ;
| MOV W3,#1 | LDR W3,[X4,W2,SXTW] ;
| STR W3,[X4,W2,SXTW] | ;
exists (1:X0=1 /\ 2:X0=1 /\ 2:X3=0)
Also make the unfenced baselines MP, SB and WRC, by deleting the barriers and replacing each dependent access with a plain one. List all six in tests/@all.
Step 2: what the model says
cd labs/part07
herd7 -model aarch64.cat tests/@all > model.txt
herd7 -model aarch64.cat -show prop -graph columns -o dot tests/MP.litmus # witness graph
dot -Tsvg dot/MP.dot > MP.svg
Expected verdicts:
| Test | herd7 Observation | Why |
|---|---|---|
| MP | Sometimes | nothing orders either side |
| MP+dmb.st+addr | Never | DMB ST orders W→W; the address dependency is in dob |
| SB | Sometimes | store buffering is allowed |
| SB+dmb.sys | Never | full DMB orders W→R |
| WRC | Sometimes | no ordering on P1 or P2 |
| WRC+addr+addr | Never | dependencies plus other-multi-copy atomicity |
A Never line is the claim that the architecture forbids the outcome. The -show prop graph for MP shows the cycle that is allowed: po (P0), rfe, po (P1), fre. Neither po edge is in ob, so nothing closes it into a forbidden ordered cycle.
Step 3: run on QEMU TCG
litmus7 turns each test into a C harness with inline assembly. The harness runs as a Linux user program, so the guest needs Linux (Lab setup). Cross-compile a static archive:
litmus7 -a 4 -s 100k -r 20 -affinity incr1 -mem direct \
-gcc aarch64-linux-gnu-gcc -linkopt -static \
-o run-qemu.tar tests/@all
qemu-system-aarch64 -M virt -cpu max -smp 4 -m 2G -accel tcg,thread=multi \
-kernel Image -append "console=ttyAMA0 root=/dev/vda rw" \
-drive file=rootfs.ext4,format=raw,if=virtio -nographic
# in the guest: tar xf run-qemu.tar && make && sh run.sh > qemu.txt
Typical result on an x86 host: MTTCG maps guest loads and stores onto the host’s TSO memory order. SB shows the relaxed outcome, but MP and WRC usually report Never although the architecture allows them. QEMU is a functional model, not a weak-memory model. It tells you that your harness and expected-outcome files work. It tells you almost nothing about Arm hardware.
Step 4: run on the FVP, then on a board
FVP Base RevC AEM. The model interleaves PEs in quanta and executes each PE in order, so every relaxed outcome comes out Never. The FVP is useful in two cases: bring-up of the harness on your exact software stack, and experiments with features that QEMU lacks. Run Linux on it with small -s/-r, because it is slow. Smaller quanta (see --help for the quantum option) increase interleaving but never create reordering. Cache-state modelling (--list-params | grep -i cache_state) changes timing, not the memory model.
Board (needs real hardware). Build natively with the same options, then run:
litmus7 -a 4 -s 1M -r 100 -affinity incr1 -mem direct -o run-board tests/@all
cd run-board && make -j && sh run.sh > board.txt
mcompare7 ../model.txt board.txt # side-by-side model vs hardware
Step 5: read the histograms
Test MP Allowed
Histogram (4 states)
5005214 :>1:X0=0; 1:X4=0;
37 *>1:X0=1; 1:X4=0;
11523 :>1:X0=0; 1:X4=1;
4983226 :>1:X0=1; 1:X4=1;
Ok
Witnesses
Positive: 37, Negative: 9999963
Condition exists (1:X0=1 /\ 1:X4=0) is validated
Observation MP Sometimes 37 9999963
The line marked *> is the final condition. Read the result as a two-by-two matrix:
observed (Sometimes) | not observed (Never) | |
|---|---|---|
| model allows | normal | allowed-but-never-observed |
| model forbids | forbidden-but-observed | normal |
Allowed-but-never-observed is not a bug. Common causes: the microarchitecture never reorders that way (load buffering, LB, is rarely seen), the stress is too weak, or the platform is an in-order model. Software must still not rely on the outcome being absent, because the next core may produce it. Record the result as “allowed, unseen at N iterations” and try harder stress before you conclude anything.
Forbidden-but-observed is always a finding. Triage it in this order:
- Test bug. Check the initial-state lines, which register the condition names, and whether the dependency survives. A hand-written C harness can have its
EORoptimised away.litmus7copies the assembly verbatim, but your own tests may not. Also check memory type: litmus7 uses Normal WB memory, while a bare-metal port might use Device or Non-cacheable memory. - Model mismatch. Check the herdtools7 version and the
aarch64.catrevision. Pre-2017 material describes a non-MCA model (7.2). - Environment. Check for a hypervisor underneath, a QEMU bug, or a missing
isbin your own harness changes. - Silicon. Record
MIDR_EL1/REVIDR_EL1, check the published errata (1.3), and reduce the test to a minimum. Sweep-sand the affinity to find the conditions that trigger it. A well-known Armv7-era precedent is the Cortex-A9 read-after-read ordering erratum, exposed by exactly this kind of testing.
Step 6: stress
| Knob | How | What it exposes |
|---|---|---|
| Affinity | -affinity incr1 vs incr2, or an explicit -p 0,8,16,24 from lscpu -e / /sys/devices/system/cpu/cpu*/topology | same cluster vs cross-cluster vs cross-die paths |
| Cache-line placement | -mem direct/indirect, -stride <n>, -preload random | x and y in one line vs different lines and home nodes |
| Contention | -a larger than the thread count (several instances run concurrently), plus stress-ng --cache N pinned to other cores | snoop-filter and home-node pressure; longer store-buffer residency |
| Chiplets | pin P0 and P1 on different dies (NUMA nodes) | C2C latency widens windows; a forbidden outcome here points at the cross-die coherence protocol |
| Volume | -s 1M -r 1000, overnight | rare outcomes (single digits per 109) |
Validation note: For a new SoC, run the full
diy7-generated AArch64 suite, not just these six tests. Run it at least once on each topology class: intra-cluster, inter-cluster and inter-die. Any forbidden-but-observed result is a release blocker. While the test runs, read the PMU eventsMEM_ACCESSandBUS_ACCESSand, on the interconnect, the CMN cross-die (CCG) counters (16.5). They confirm that the shared lines really moved between dies. A forbidden-outcome-free run in which the lines never left the local die proves nothing about C2C.
Exercises: fix the barrier
Assume Normal WB Inner Shareable memory, coherent PEs, and Device-nGnRE MMIO unless stated otherwise.
E1. Sending an SGI with a payload.
str x2, [x0] // payload for target CPU
msr icc_sgi1r_el1, x1 // send SGI
Answer
Insert dsb ishst before the MSR, and isb after it if the code depends on the SGI having been issued. A DMB cannot order a system-register write. Without the DSB, the target can take the SGI and read the old payload. See 7.10 §4.
E2. Releasing a secondary from a holding pen (TF-A-style). The secondary is still running with its D-cache and MMU off.
hold_entry[cpu] = ep; /* primary, caches on */
hold_state[cpu] = HOLD_GO;
sev();
/* secondary: while (hold_state[me] != HOLD_GO) wfe(); jump(hold_entry[me]); */
Answer
There are three problems.
- Visibility. With the MMU off, the secondary’s data accesses are Device-nGnRnE (6.5). It reads memory directly and does not see lines that are dirty in the primary’s cache. The primary must clean both words to the PoC (
DC CVAC, as TF-A’sflush_dcache_rangedoes). - Producer ordering and completion. The secondary may wake spuriously from
WFEand poll at any time, sohold_statemust not reach memory beforehold_entry. Writehold_entry, clean it,DSB SY; then writehold_state, clean it,DSB SY; thenSEV. The finalDSBis also what makes the state visible before the event. - Consumer side. Do not rely on nR between two loads to DRAM, because “same peripheral” is IMPLEMENTATION DEFINED. After the wait loop sees
HOLD_GO, putdmb sy(or make thehold_stateload anLDAR) before loadinghold_entry. This protects against a stale entry left over from a previous power cycle.
E3. Installing vectors and unmasking SError.
adr x0, el3_vectors
msr vbar_el3, x0
msr daifclr, #4 // unmask SError
Answer
Add isb after the MSR VBAR_EL3. Exception entry reads VBAR_EL3 indirectly, so a direct write needs a CSE before it is guaranteed to be used (7.8). Without it, a pending SError taken right after the unmask can vector through the old (or reset UNKNOWN) table.
E4. Starting a non-coherent DMA engine.
1: dc cvac, x0 // clean buffer, line by line
add x0, x0, x3
cmp x0, x1
b.lo 1b
dmb osh
str w2, [x4, #DMA_START]
Answer
Replace dmb osh with dsb osh (or dsb sy). The master does not snoop, so it needs the cleans to have completed to the PoC. Only a DSB waits for cache maintenance to complete, and a DMB does not order DC CVAC against a later Device store in the sense required here. Also derive x3 from CTR_EL0.DminLine, not from a hard-coded 64 (8.5).
E5. FreeRTOS tickless idle.
mmio_write_32(PWRCTL_BASE + CORE_RET_EN, 1); /* allow retention */
__asm__ volatile("wfi");
Answer
Use dsb sy between the two. The Device write must complete before the PE stops, and WFI itself does not wait for outstanding accesses to complete (7.6). If the controller samples the enable asynchronously, read the register back first (7.9).
E6. Seqlock writer.
ldr w0, [x9]
add w0, w0, #1
stlr w0, [x9] // seq odd
stp x1, x2, [x10] // data
add w0, w0, #1
stlr w0, [x9] // seq even
Answer
The first STLR does not stop the later data stores from becoming visible before it. Replace it with str followed by dmb ishst. The second STLR is correct (7.10 §6).
Checkpoint
Q7.11.1 MP (no barriers) reports Never on QEMU TCG on an x86 host over 108 iterations. herd7 says Sometimes. What is the correct conclusion?
- A. QEMU has a bug, because it must exhibit every allowed outcome
- B. The herd model is too weak for this test
- C. The outcome is allowed but not exhibited by this platform. Software must still not rely on its absence
- D. MP is forbidden in practice on Armv8 since the 2017 multi-copy-atomicity revision
Answer
C. An implementation may be stronger than the architecture, and QEMU on a TSO host usually is. A is wrong because no implementation has to exhibit allowed outcomes. D confuses other-multi-copy atomicity (which forbids WRC-style outcomes with dependencies) with forbidding MP, which stays allowed without barriers.
Read more: Arm ARM (DDI0487), the AArch64 memory model; herdtools7 documentation, litmus7
Q7.11.2 On a two-die prototype, WRC+addr+addr reports Sometimes 3 in 109 runs, but only when P0 is on the other die from P1 and P2. The harness reproduces Never on single-die runs. What is the best next step?
- A. Accept it, because rare outcomes are within architectural tolerance
- B. Treat it as a likely ordering or coherence bug on the cross-die path. Confirm the test (dependencies intact, Normal WB memory), then minimise and file with
MIDR_EL1/REVIDR_EL1, topology and counters - C. Add
DMB SYto every thread until the outcome disappears, then close the issue - D. Rerun on the FVP to confirm
Answer
B. The model forbids the outcome, so any observation is a finding, and topology dependence points at the C2C path. C hides the symptom and loses the evidence. D cannot help because the FVP never reorders. A misreads “forbidden” as “rare”.
Read more: Arm ARM (DDI0487), multi-copy atomicity; herdtools7 documentation