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.6 Instruction cache maintenance and cross-modifying code

Data stores and instruction fetches are not coherent with each other by default. A store goes into the data side of the hierarchy (store buffer, L1D, possibly further out). Instruction fetch reads from the L1I, which may hold a stale copy, and it may have read from memory at any time since the last context synchronization event on that PE. The Arm ARM states the second point explicitly: the PE may have fetched instructions “at any time since the last Context synchronization event”. To make newly written instructions executable, three things must happen:

  1. The new data must reach a point where instruction fetch can see it. That point is the Point of Unification (PoU) (8.4).
  2. Any stale copy in instruction caches must be removed.
  3. Every PE that will execute the new code must discard instructions it has already fetched. That requires a context synchronization event on that PE (7.8).

The canonical sequence

For a single location, with the code written through a Normal, Inner Shareable, cacheable mapping:

    str     w1, [x0]          // write the new instruction
    dc      cvau, x0          // clean data cache by VA to PoU
    dsb     ish               // wait for the clean to complete
    ic      ivau, x0          // invalidate instruction cache by VA to PoU
    dsb     ish               // wait for the invalidate to complete
    isb                       // discard fetched instructions on this PE

Each step has a reason:

StepWhy
DC CVAUPushes the dirty line from the data cache out to the PoU, where the I-side fetch path meets the D-side. Without it, the I-cache refills from a level that still holds the old bytes.
first DSB ISHIC IVAU is not ordered after DC CVAU by default. If the invalidate runs first, a refetch (including a speculative one) can pull the old bytes back into the L1I before the clean lands.
IC IVAURemoves stale copies from instruction caches. For a location in Inner Shareable memory (normal coherent memory), the by-VA operation is broadcast to the instruction caches of all PEs in the Inner Shareable domain, so one PE can do this for everyone.
second DSB ISHWaits for the invalidate to complete on all PEs it is broadcast to. Before that, a refetch can still hit a stale line.
ISBA context synchronization event. Instructions fetched before it, possibly from the old line, are discarded and refetched. It only affects the PE that executes it.

For a range, loop the DC CVAU over the range in CTR_EL0.DminLine steps, then one DSB ISH, then loop IC IVAU in CTR_EL0.IminLine steps, then DSB ISH; ISB. The line sizes come from CTR_EL0 (8.1). Always read them from the register: big.LITTLE systems have had cores with different I-line sizes, and Linux uses the system-wide minimum for this reason.

IC IALLU (local, to PoU) and IC IALLUIS (Inner Shareable) invalidate all instruction caches without needing a VA. They are the right tool after loading a large image, or when no VA is mapped. The cost is that every hot code path on every PE refetches.

What CTR_EL0.IDC and DIC let you omit

CTR_EL0 advertises two IMPLEMENTATION DEFINED properties:

FieldBitMeaning when 1Omittable step
IDC28Data cache clean to PoU is not required for instruction-to-data coherenceDC CVAU
DIC29Instruction cache invalidation to PoU is not required for data-to-instruction coherenceIC IVAU

The effective value of IDC is also 1 when CLIDR_EL1.LoC == 0, or when both LoUIS and LoUU are 0, because then no data cache lies inside the PoU. If DIC is 1, IDC must also read 1. All PEs in the same Inner Shareable domain must agree on both values.

The reduced sequences are:

// IDC == 1, DIC == 0
    str     w1, [x0]
    dsb     ish               // still needed: the store must be visible
    ic      ivau, x0          //   before the invalidate is performed
    dsb     ish
    isb

// IDC == 1, DIC == 1
    str     w1, [x0]
    dsb     ish               // store complete for all IS observers
    isb                       // local PE refetches; remote PEs need their own

The DSB and the ISB are never optional. DIC says the instruction cache does not need invalidating. It does not say instructions that are already fetched are thrown away. The pipeline still holds them until a context synchronization event.

Bring-up note: Some implementations have errata where CTR_EL0.DIC reads 1 but the I-side can still see stale data. Neoverse N1 erratum 1542419 is the best-known case: Linux traps EL0 reads of CTR_EL0 and reports DIC = 0, so that user space performs the IC IVAU, and the workaround has a firmware counterpart in TF-A. If you rely on DIC in firmware, check the core’s SDEN first (1.3).

Who sees the new code: the cross-PE sequence

The modifying PE’s DC/IC operations are broadcast, so it can clean and invalidate for the whole Inner Shareable domain. It cannot run an ISB on another PE. The architecture therefore requires a split sequence for code that another PE will execute:

// Modifying PE (P0)
    str     w1, [x0]          // new instruction(s)
    dc      cvau, x0
    dsb     ish
    ic      ivau, x0
    dsb     ish               // invalidate complete on all IS PEs
    mov     w3, #1
    str     w3, [x2]          // publish "code ready" flag (STLR is also fine)

// Each executing PE (P1..Pn)
1:  ldr     w3, [x2]          // or LDAR
    cbz     w3, 1b
    isb                       // P1's own context synchronization event
    br      x0                // now guaranteed to execute the new code

The flag store must be ordered after the second DSB. A DSB orders all later instructions, so a plain STR is enough. The executing PE needs no DC or IC of its own, but it does need the ISB after it has observed the flag. Instead of an ISB, any other context synchronization event works: taking an exception (unless SCTLR_ELx.EIS == 0 under FEAT_ExS) or returning from one (unless SCTLR_ELx.EOS == 0 under FEAT_ExS). This is why Linux’s kick_all_cpus_sync() (an IPI to every CPU) is a valid cross-PE synchronisation: the IRQ entry on each CPU is its context synchronization event.

CMODX: modifying code that may be executing right now

The sequence above assumes no PE is executing the location while it changes. Concurrent modification and execution of instructions (CMODX) is the case where P1 may fetch the location while P0 overwrites it, and P1 has done no synchronisation. Live patching, tracepoints and JIT back-patching all work this way.

The architecture gives a guarantee only for a small set of instructions. If both the old and the new instruction are in that set, P1 executes either the old or the new instruction, nothing else. The set is:

  • B, BL (immediate branches)
  • NOP
  • BRK, SVC, HVC, SMC
  • ISB

For conditional branches, concurrent modification is allowed, but the PE may combine the old condition with the new target or the new condition with the old target. Patch the condition and the target as separate steps, or avoid patching conditional branches at all. The current DDI0487 issue words this precisely; read it before you extend the set.

If either the old or the new instruction is outside the set, the behaviour is CONSTRAINED UNPREDICTABLE. It can be any behaviour achievable by executing any sequence of instructions at the same Exception level. That bound is why CMODX is not a privilege-escalation risk, but it is no correctness guarantee at all. A torn fetch of a half-written MOVZ/MOVK pair, for example, is permitted.

The concurrent store must also be single-copy atomic for the instruction: one aligned 32-bit STR. Rewriting an instruction with two 16-bit stores gives P1 a chance to fetch a mixed encoding, even if both endpoints are in the set.

Even within the set, “old or new” holds only until P1 next synchronises. Before that, P1 may keep executing the old instruction indefinitely (it may still be in its L1I or pipeline). The full cache-maintenance sequence is still needed, and P1 must take a context synchronization event, before you can rely on P1 executing the new instruction.

The standard live-patching recipe follows from this:

  1. Overwrite the first instruction of the site with a BRK or a B to a trampoline (both in the CMODX set), then run the maintenance sequence and synchronise all PEs.
  2. Rewrite the rest of the site; no PE can be executing it now.
  3. Replace the first instruction with the final one, again via the set, or synchronise all PEs first.

Linux’s aarch64_insn_patch_text() avoids the problem differently. It uses stop_machine() so that no other CPU is executing kernel text during the write.

Security note: In a CMODX window, an instruction outside the set can execute as anything reachable at the current EL. For EL3 or S-EL1 code patched at runtime (for example a debug hook in BL31), that means arbitrary EL3 behaviour. Don’t patch EL3 text while secondaries run; park them, or only patch through the CMODX set.

FEAT_CMOW: cache maintenance needs write permission

EL0 can execute IC IVAU and DC CIVAC when SCTLR_EL1.UCI == 1, which Linux sets for JITs. Before FEAT_CMOW, read permission was enough. EL0 could invalidate lines of read-only pages it shares with others, such as shared libraries or the vDSO. That gives an attacker a Flush+Reload-style flush primitive on memory it could never write. FEAT_CMOW (mandatory from v8.8) adds two controls:

ControlEffect when 1
SCTLR_EL1.CMOW (bit 32)IC IVAU, DC CIVAC, DC CIGDVAC and DC CIGVAC at EL0, on a location with stage 1 read but not write permission, generate a stage 1 Permission fault.
HCRX_EL2.CMOW (bit 9)The same instructions at EL1 or EL0 on a location without stage 2 write permission generate a stage 2 Permission fault. The effective value is 0 unless SCR_EL3.HXEn == 1.

For stage 1, “write permission” here means AP[2] == 0 or DBM == 1, with APTable[1] == 0 at every level. The bits only affect execution at EL0 or EL1. With HCR_EL2.{E2H,TGE} == {1,1}, SCTLR_EL1.CMOW has no effect.

A JIT that uses W^X with two aliases (writable and executable) must run its IC IVAU on the writable alias once CMOW is set, or it takes a Permission fault. By-VA invalidation acts on the physical line, so either alias is correct for coherence.

JITs, loaders and firmware

  • Loaders (BL2 loading BL31, a bootloader loading an OS). If the image was written with the MMU and caches on, clean it to PoU (to PoC if the next stage starts with caches off; see 8.7 and 9.3), invalidate the I-cache, DSB, then ISB or the exception return into the new image. TF-A’s flush_dcache_range plus the ERET into the next image follows this pattern. An image written by DMA or by a debugger through the external debug interface bypasses the PE’s D-cache, but stale lines in the I-cache still need IC IALLU.
  • JITs. Generate code, run the range sequence once per batch, and publish the entry pointer with release semantics. Every thread that calls into the new code needs a context synchronization event after it observes the pointer. In practice this comes from an ISB in the call stub, or from an exception, such as the mprotect syscall or the first-touch page fault. A thread that already has the old target in flight is a CMODX case.
  • EL0 access controls. SCTLR_EL1.UCT lets EL0 read CTR_EL0. SCTLR_EL1.UCI lets EL0 execute DC CVAU, DC CIVAC, DC CVAC, IC IVAU and related instructions; if it is 0, they trap to EL1.

Validation note: Test with a P0/P1 pair. P0 rewrites a MOV w0, #1; RET stub to MOV w0, #2; RET, runs the full sequence and sets a flag. P1 spins on the flag, then calls the stub with or without the ISB. Without the ISB, an old result after the flag is allowed. If P1 still returns the old value with the ISB, the bug is real: a broken IC broadcast, a wrong DIC, or the maintenance not reaching the PoU. On cores that count them, the PMU events L1I_CACHE_REFILL (0x01) and L1I_TLB_REFILL confirm whether P1 really refetched. FVP’s cache models (with cache state modelling enabled) are needed to see the stale-I-cache failure at all, because QEMU TCG has no instruction cache to go stale (8.10).

Checkpoint

Q8.6.1 A system reports CTR_EL0.IDC == 1 and CTR_EL0.DIC == 1. P0 writes a new function, executes DSB ISH, and stores a pointer to it. P1 loads the pointer with LDAR and branches to it straight away. What is guaranteed?

  • A. P1 executes the new code, because DIC means no instruction cache maintenance is needed
  • B. P1 executes the new code, because LDAR orders the instruction fetch after the load
  • C. Nothing: P1 may execute stale instructions it fetched earlier, because it has had no context synchronization event after observing the pointer
  • D. P1 takes a CONSTRAINED UNPREDICTABLE exception
Answer

C. DIC removes the need for IC IVAU, not for a context synchronization event on each executing PE. Instruction fetch is not a memory read ordered by acquire semantics. P1 may have fetched (or speculatively prefetched) from that address at any time since its last CSE. An ISB on P1 after the LDAR, or an exception entry or return, is required. Option A is the tempting misreading of DIC.

Read more: Arm ARM (DDI0487), Concurrent modification and execution of instructions; CTR_EL0

Q8.6.2 A live-patching tool replaces an ADD x0, x0, #1 with ADD x0, x0, #2 in kernel text, using one aligned 32-bit store while other CPUs may be executing it, followed by the full DC/IC/DSB sequence and an IPI to all CPUs. What does the architecture say about another CPU that fetches the instruction during the window?

  • A. Its behaviour is CONSTRAINED UNPREDICTABLE, because ADD is not in the set of instructions that may be concurrently modified
  • B. It executes either the old or the new ADD, because the store is single-copy atomic
  • C. It always executes the old ADD until its IPI arrives
  • D. It takes an Instruction Abort, because the line is being invalidated
Answer

A. The “old or new” guarantee holds only when both instructions are in the CMODX set (B, BL, NOP, BRK, SVC, HVC, SMC, ISB). Single-copy atomicity of the store (option B) is necessary but not sufficient. The safe approach is to route through the set (for example, patch in a BRK or a branch first) or to stop the other CPUs during the write.

Read more: Arm ARM (DDI0487), Concurrent modification and execution of instructions

Q8.6.3 On a v8.8 system, Linux sets SCTLR_EL1.UCI = 1 and SCTLR_EL1.CMOW = 1. A JIT maps its code buffer twice: RW at VA1 and RX at VA2. After writing code through VA1, it executes IC IVAU on VA2 from EL0. What happens?

  • A. The invalidate works, because IC IVAU needs only read or execute permission
  • B. It traps to EL1 as a system instruction trap, because UCI does not cover IC IVAU
  • C. It completes but has no effect, because an instruction cache invalidate on an alias is ignored
  • D. It generates a stage 1 Permission fault, because VA2 has no write permission and CMOW requires it
Answer

D. With CMOW == 1, IC IVAU (and DC CIVAC and the tag variants) at EL0 on a location that is readable but not writable at stage 1 generates a Permission fault. The JIT should run the maintenance on the RW alias VA1. That is architecturally correct, because by-VA maintenance acts on the physical line. Option B is wrong: UCI is exactly the control that lets EL0 execute IC IVAU.

Read more: Arm ARM (DDI0487), SCTLR_EL1.CMOW; HCRX_EL2.CMOW; FEAT_CMOW