10.4 Waiting and locking
The earlier sections in this part give you atomic operations. A lock also needs a way to wait that does not burn power or flood the interconnect. Firmware also has to lock in conditions where those atomics are not guaranteed: before the caches are on, and against agents that are not coherent at all.
The event register, WFE, SEV and SEVL
Each PE has a one-bit event register. Software cannot read it directly. It is set by:
SEVexecuted by any PE in the system (a broadcast);SEVLexecuted by this PE (local only);- an exception return;
- the clearing of this PE’s global monitor (the global-monitor event, below);
- an event from the Generic Timer event stream (
CNTKCTL_EL1.EVNTEN/EVNTI, andCNTHCTL_EL2for EL2. See 4.6); - IMPLEMENTATION DEFINED sources, such as an external event input.
WFE then behaves as follows. If the event register is set, WFE clears it and completes immediately. Otherwise the PE may enter a low-power state until a WFE wake-up event occurs. Wake-up events are the event-register sources above, plus pending interrupts and SErrors and certain debug events, as listed in DDI0487 Wait for Event. WFE is a hint. An implementation may treat it as a NOP, and it may wake for no visible reason, so every WFE is inside a loop that re-checks the condition.
SEVL exists to prime that loop. It lets the first WFE fall straight through, so the loop can be written “wait, then check” without a special first iteration. TF-A’s exclusive spinlock is the textbook use:
// TF-A lib/locks/exclusive/aarch64/spinlock.S (non-CAS build)
spin_lock:
mov w2, #1
sevl
l1: wfe
l2: ldaxr w1, [x0] // load-acquire and arm the global monitor
cbnz w1, l1 // held: sleep until the monitor is cleared
stxr w1, w2, [x0]
cbnz w1, l2
ret
spin_unlock:
stlr wzr, [x0] // the store clears waiters' monitors, so no SEV needed
ret
Traps on WFE: SCTLR_EL1.nTWE (EL0 to EL1), HCR_EL2.TWE (to EL2) and SCR_EL3.TWE (bit 13, to EL3), all reported as EC 0x01. FEAT_TWED adds a configurable delay before the trap is taken (SCR_EL3.TWEDEn/TWEDEL and the EL2 equivalents). Hypervisors trap WFE to deschedule a vCPU that is spinning on a lock held by a preempted vCPU.
The global-monitor event
The unlock above has no SEV, yet waiters wake. The waiter’s LDAXR marks the lock’s granule in its global monitor. When the owner’s STLR writes that granule, the waiter’s global monitor goes from Exclusive Access to Open Access, and that transition generates an event for the waiter. The protocol is race-free by construction. If the unlock lands between the waiter’s LDAXR and its WFE, the monitor is already cleared, so the event register is already set and the WFE falls through.
The event only exists where a global monitor exists. On Normal Write-Back Shareable memory, the cache-based monitor’s loss of the line provides it (10.1). On Non-cacheable or Device memory without a system monitor, a store from the owner generates no event. A waiter then sleeps until some unrelated SEV, interrupt or event-stream tick. LSE locks combine both mechanisms. TF-A’s USE_SPINLOCK_CAS build takes the lock with CASA, and when it sees the lock held it does LDXR only to arm the monitor before WFE. Its bit_lock does the same with LDSETAB and LDXRB.
The event stream is the safety net. With EVNTEN set, every waiter wakes at a bounded period (Linux sets about 10 kHz). A missing event costs latency instead of a hang. Firmware that relies on WFE in memory of uncertain type should either enable the event stream or send SEV explicitly in its unlock path.
WFET and WFIT (FEAT_WFxT)
FEAT_WFxT (mandatory from v8.7, ID_AA64ISAR2_EL1.WFxT = 0b0010) adds WFET Xt and WFIT Xt. They behave like WFE/WFI, but also complete when the virtual count CNTVCT_EL0 reaches the value in Xt. The value is an absolute deadline, not a duration:
mrs x1, cntvct_el0
add x1, x1, x2 // x2 = timeout in counter ticks
1: ldaxr w3, [x0]
cbz w3, 2f // condition met
wfet x1 // sleep until event, wake-up or deadline
mrs x4, cntvct_el0
cmp x4, x1
b.lo 1b
// timed out
2:
Because the deadline is in virtual time, CNTVOFF_EL2 applies. EL2 code that uses physical time must convert. The same trap controls cover them: nTWE/TWE cover WFET, and nTWI/TWI cover WFIT. On a trap, ESR reports the register number, which is what 0b0010 in the ID field means. A timed wait no longer has to depend on the event stream.
Ticket locks, qspinlock and MCS (brief)
A test-and-set lock (above) is unfair: whichever core wins the race after an unlock gets the lock. A ticket lock is FIFO. It has two 16-bit halves, next and owner:
// lock word: [31:16] next, [15:0] owner
mov w2, #0x10000
ldadda w2, w1, [x0] // take a ticket: old value in w1
eor w2, w1, w1, ror #16 // owner == my ticket?
cbz w2, 3f
sevl
2: wfe
ldaxrh w3, [x0] // owner half; arms monitor
eor w2, w3, w1, lsr #16
cbnz w2, 2b
3: // locked
// unlock: owner++ with release
ldrh w1, [x0]
add w1, w1, #1
stlrh w1, [x0]
The problem at scale is that every waiter spins on the same line. Each unlock invalidates it in all N waiting caches, and N re-reads follow. Handover cost grows with the number of waiters, and on a multi-chiplet system each re-read may cross the die-to-die link. MCS locks give each waiter its own queue node and spin location, so a handover touches one remote line. Linux’s qspinlock packs an MCS queue into a 32-bit word with a fast path for the uncontended case. arm64 Linux moved from its own ticket lock to qspinlock in 2018. For firmware with a handful of cores, a ticket or test-and-set lock is fine. For runtime services entered concurrently by hundreds of cores, it is not.
Locks before the MMU and caches are on: TF-A’s bakery lock
PSCI power-down and warm-boot paths run while some cores have the D-cache disabled. Their data accesses are then Device-nGnRnE (MMU off) or Non-cacheable, while other cores access the same lock with caches on. Exclusives are not guaranteed on those memory types (10.1), and the mismatched attributes break coherency (6.6). TF-A’s design document says it directly: BL31 touches PSCI state “before the data cache is enabled in the warm boot path”, so it “uses locks based on Lamport’s Bakery algorithm instead.”
The bakery algorithm needs no read-modify-write at all. Each CPU writes only its own entry, a choosing bit plus a ticket number, and reads everyone else’s. It relies only on aligned 16-bit loads and stores being single-copy atomic, which the architecture guarantees whatever the translation state. bakery_lock_get() takes max(all tickets) + 1, waits for each other CPU that is choosing, waits (with wfe) on any CPU with a lower (ticket, CPU index) pair, and ends with dmbish(). bakery_lock_release() does dmbish(), clears its entry, then dsb(); sev();. The SEV is required because no global-monitor event exists here.
TF-A has two variants:
| Build | Lock storage | Coherency handling |
|---|---|---|
USE_COHERENT_MEM=1 (bakery_lock_coherent.c) | .bakery_lock inside .coherent_ram, mapped Device/Non-cacheable at EL3 | All CPUs see the same attributes whatever their cache state |
USE_COHERENT_MEM=0 (bakery_lock_normal.c) | Normal cacheable memory, one cache-line-aligned block per CPU (PLAT_PERCPU_BAKERY_LOCK_SIZE must be a multiple of CACHE_WRITEBACK_GRANULE) | Explicit maintenance: after writing, DC CVAC (cache on) or DC IVAC (cache off), then DSB ISH; before reading, DC CIVAC (cache on only) then DMB ISH |
The per-CPU line split in the second variant is essential. If two CPUs’ entries shared a line, a cache-off CPU’s DC IVAC would discard a cache-on CPU’s dirty update to its own entry.
With HW_ASSISTED_COHERENCY=1, which is for cores that stay coherent through power transitions (DSU-based designs), PSCI uses ordinary spinlocks instead (lib/psci/psci_private.h). Bakery locks cost O(N) reads per acquisition, so on a many-core, multi-chiplet SoC this option is worth a lot. See 8.8 and 17.4.
Synchronising with non-coherent agents (SCP, MCP, RSE)
System control, management and security processors (SCP, MCP, RSE) are usually Cortex-M or R class. They are not in the application cores’ coherency domain and cannot take part in their atomics. No lock is shared. Instead, the protocol is single-writer ownership plus a doorbell. SCMI’s shared-memory transport (DEN0056) is the standard example. Its channel header has a channel status word whose bit 0 means “channel free” and bit 1 means “channel error”:
- The agent (AP, EL3) waits for
free == 1. Only the side that owns the channel writes it. - The agent writes the message header and payload, then clears
free, which hands ownership to the platform. - Barrier: a
DSB(at leastDMB OSH; see 7.9) so that the payload and status stores are observed before the doorbell. - The agent writes the doorbell, typically an MHU register (Device-nGnRE).
- The platform processes the message, writes the response, sets
free, and raises a completion interrupt, or the agent pollsfree. - The agent reads the response only after it observes
free == 1. That load is the acquire point, so useLDAR, or a load followed byDMB, before reading the payload.
Memory attributes must match what the other side can see. Map the shared area Non-cacheable or Device on the AP. If it must be cacheable, use DC CVAC before the doorbell and DC IVAC before reading the response, to the point the agent reads from (8.7). Never use LDXR/STXR or LSE atomics on this memory to “lock” it against the SCP, because the SCP’s writes will not clear your monitor. The same pattern covers the RSE communication channel used for measured boot and the cross-chiplet mailboxes in 17.5.
Validation note: a core found spinning in a
WFEloop is the most common lock symptom in bring-up triage (18.2). Sample its PC non-intrusively (PMPCSR/EDPCSR) and read the lock word over the debug port. If the lock is free but the core still sleeps, a wake-up was lost: the lock is in memory with no global-monitor event and the unlock has noSEV, or the event stream is off (CNTKCTL_EL1.EVNTEN == 0). Confirm by enabling the event stream: the hang should become a slow but correct path. If the lock word reads as held by a CPU that has powered down, suspect a bakery entry lost through aDC IVACon a shared line, or an exclusiveSTXRthat “succeeded” without a monitor. For a lost-update stress test of the lock itself, see 8.10.
Checkpoint
Q10.4.1 In the TF-A non-CAS spin_lock, why can the waiter safely execute WFE after seeing the lock held, even if the owner’s STLR to release it happens just before the WFE executes?
- A.
STLRalways broadcasts anSEVto all PEs, so the event register is set whenever a lock is released - B. The waiter’s
LDAXRarmed its global monitor. The owner’s store clears it and sets the waiter’s event register, so the laterWFEcompletes immediately - C.
WFEre-executes the precedingLDAXRwhen it wakes, so it observes the new value - D. The
SEVLat the top of the function keeps the event register permanently set during the loop
Answer
B. The event comes from the global monitor’s transition to Open Access, and the event register latches it until the next WFE, so the race is closed. A store-release has no SEV side effect, so A is wrong. That is why the global-monitor mechanism matters. SEVL sets the register once and the first WFE consumes it, so D is wrong. WFE does not replay instructions.
Read more: Arm ARM (DDI0487), Wait for Event mechanism and Send event; Use of Wait for Event and Send Event with exclusive monitors
Q10.4.2 A firmware lock in Normal Non-cacheable SRAM is taken with CASA and waited for with LDXR plus WFE, and released with a plain STLR. On silicon, waiters sometimes stall for up to 100 µs after a release, but never hang. What best explains this?
- A.
CASAon Non-cacheable memory is performed far, which adds 100 µs of latency - B.
STLRon Non-cacheable memory is buffered until the nextDSB - C. The release has no acquire, so the waiter must wait for the store to propagate
- D. The SRAM path has no global monitor, so the release generates no event. Waiters wake only at the next event-stream tick, and the stall is bounded by that period
Answer
D. The global-monitor event exists only where a global monitor tracks the location. Without one, the WFE is woken by the next event-stream event, interrupt or unrelated SEV, so the stall is bounded and recurring. Adding DSB; SEV to the unlock path, or moving the lock to Write-Back memory, fixes it. A far atomic costs hundreds of nanoseconds, not 100 µs. Stores do not wait indefinitely for a DSB.
Read more: Arm ARM (DDI0487), Wait for Event; CNTKCTL_EL1 (EVNTEN, EVNTI)
Q10.4.3 A platform builds TF-A with USE_COHERENT_MEM=0, and a porting engineer sets CACHE_WRITEBACK_SHIFT to 5 and PLAT_PERCPU_BAKERY_LOCK_SIZE to 32 bytes to save memory, on a core whose CTR_EL0.CWG reports a 64-byte writeback granule. The build-time size check passes. Under PSCI stress, CPU_ON and CPU_SUSPEND occasionally corrupt power-domain state. Why?
- A. Two CPUs’ bakery entries share a cache line. A CPU with its cache off does
DC IVACon its entry and discards another CPU’s dirty update to its entry in the same line - B. The bakery algorithm requires 64-bit tickets, and 32 bytes truncates them
- C.
DC IVACis not permitted with the MMU off, so the invalidate is ignored - D. Bakery locks require exclusives, and the smaller size breaks the ERG
Answer
A. The normal-memory variant is only correct if each CPU’s entry occupies its own writeback granule, which is why TF-A asserts that the size is a multiple of CACHE_WRITEBACK_GRANULE. That check is only as good as the granule the platform declares: with 32 declared on 64-byte hardware, two CPUs’ entries share a line. A per-CPU block split across a line lets cache maintenance by one CPU destroy another CPU’s data. Bakery locks use no exclusives at all, so D is wrong. Cache maintenance by VA works with the MMU off, using a flat mapping, so C is wrong.
Read more: TF-A firmware design, Bakery lock data; Arm ARM (DDI0487), DC IVAC and CTR_EL0.CWG