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

4.7 Reading time correctly

MRS x0, CNTVCT_EL0 looks like the simplest instruction in the book. It is not a memory access, though, so none of the memory-ordering machinery of Part 7 applies to it. The PE is free to execute it early, late or speculatively unless you constrain it. This section covers the ordering rules, the FEAT_ECV registers that relax them, the Armv8.6 frequency change, counter scaling, and keeping one notion of time across chiplets. Register basics are in 4.6.

Why a counter read floats

DDI0487’s Generic Timer chapter states that reads of CNTPCT_EL0 (and CNTVCT_EL0) can occur speculatively and out of order relative to other instructions executed on the same PE. Two consequences follow:

  1. Barriers do not order it. DMB orders memory accesses against memory accesses (7.5). A counter read is a system-register read, so a DMB between a load and an MRS CNTVCT_EL0 constrains nothing. Acquire and release semantics (7.7) also only order memory accesses.
  2. The value can predate the code around it. An out-of-order core can sample the counter before older loads have returned, or before an older branch has resolved. A timestamp “after” an event can then hold a time before it.

Current issues of DDI0487 do guarantee that reads of CNTVCT_EL0 and CNTVCTSS_EL0 occur in program order relative to each other, so two back-to-back reads on one PE do not go backwards. They give no ordering against anything else.

Ordering a read after earlier instructions: ISB

The Arm ARM’s own example is the fix. If a load from memory obtains a signal that the counter must now be read, an ISB between the two makes the counter read occur after the signal has been read. The ISB is a context synchronization event (7.8): instructions after it are fetched and executed only after it completes, so the MRS cannot be hoisted above it.

1:  ldar    w0, [x1]            // observe "start" flag from another PE
    cbz     w0, 1b
    isb                         // counter read cannot be performed before this point
    mrs     x2, CNTVCT_EL0

ISB does not wait for earlier stores to complete. If you want the time at which an MMIO write has completed (for example, timing a device’s response), you need DSB to wait for completion (7.6), then ISB, then the read:

    str     w3, [x4]            // doorbell to Device memory
    dsb     sy                  // store has completed
    isb
    mrs     x5, CNTPCT_EL0

Ordering a read before later loads: the Linux dependency trick

The other direction is harder. In a seqlock reader, such as the Linux vDSO clock_gettime(), the counter must be read inside the critical section. That means before the re-read of the sequence count that validates it. A later load can be satisfied before the counter read has executed, and no barrier instruction orders a system-register read before a later load. Linux therefore turns the counter value into an address dependency:

/* arch/arm64/include/asm/arch_timer.h (abridged) */
#define arch_counter_enforce_ordering(val) do {         \
        u64 tmp, _val = (val);                          \
        asm volatile(                                   \
        "       eor     %0, %1, %1\n"   /* tmp = 0, but depends on val */ \
        "       add     %0, sp, %0\n"                   \
        "       ldr     xzr, [%0]"      /* dummy load from the stack */   \
        : "=r" (tmp) : "r" (_val));                     \
} while (0)

static __always_inline u64 __arch_counter_get_cntvct(void)
{
        u64 cnt;
        asm volatile(ALTERNATIVE("isb\n mrs %0, cntvct_el0",
                                 "nop\n" __mrs_s("%0", SYS_CNTVCTSS_EL0),
                                 ARM64_HAS_ECV) : "=r" (cnt));
        arch_counter_enforce_ordering(cnt);
        return cnt;
}

The dummy LDR cannot be issued until the counter value exists, because its address depends on it. The seqlock’s smp_rmb() (a DMB ISHLD) then orders the dummy load before the sequence re-read. Together they order the counter read before the re-read. The construction relies on the dependency rules of 7.4: a register data dependency through EOR x, v, v still counts, even though the result is always zero. A second ISB after the read would also work, at a higher cost on every clock_gettime().

NeedSequence
Read after an earlier load or branchISB ; MRS
Read after an earlier store has completedDSB ; ISB ; MRS
Read before a later loadMRS ; address dependency into the load (or ISB)
Timer write takes effect before continuingMSR CNTx_CVAL/CTL ; ISB
Elapsed-time measurement of a code regionISB ; MRS t0 ; ... ; ISB ; MRS t1 (add DSB before the second ISB if memory side effects must be included)

Bring-up note: A missing ISB rarely shows up on in-order cores or functional models such as QEMU, which treat system registers as self-synchronizing. It shows up on wide out-of-order cores as occasional negative deltas, or as time that runs backwards across a seqlock retry. Test timing code on the real core or on a cycle-accurate model.

FEAT_ECV

FEAT_ECV (Enhanced Counter Virtualization) is mandatory from Armv8.6: ID_AA64MMFR0_EL1.ECV = 0b0000 is not permitted from v8.6. The field has two levels: 0b0001 gives the self-synchronized registers, the extra traps and EVNTIS, and 0b0010 adds CNTPOFF_EL2, CNTHCTL_EL2.ECV and SCR_EL3.ECVEn. Recent DDI0487 issues name the second level FEAT_ECV_POFF; see A2 for its permitted/mandatory status.

CNTPCTSS_EL0 and CNTVCTSS_EL0

These are self-synchronized views of the physical and virtual counts. A read returns a value consistent with the counter not having been read until the MRS was known to be non-speculative, and the read appears to occur in program order relative to other instructions, without an ISB. This replaces the leading ISB, which is why Linux patches the isb to nop when FEAT_ECV is present.

The ordering against later loads is a separate problem, and the self-synchronized read does not solve it. A younger load may still be satisfied early. Linux keeps arch_counter_enforce_ordering() after CNTVCTSS_EL0 for that reason. EL0 can test for the register through the HWCAP2_ECV bit, and EL0 access is controlled by the same CNTKCTL_EL1.EL0VCTEN/EL0PCTEN bits as the plain registers.

CNTPOFF_EL2

CNTPOFF_EL2 is a physical offset, the physical counterpart of CNTVOFF_EL2. When SCR_EL3.ECVEn = 1 and CNTHCTL_EL2.ECV = 1, the physical count seen by EL0 and EL1 (both CNTPCT_EL0 reads and the EL1 physical timer’s comparison) is reduced by CNTPOFF_EL2. It is not applied at EL2 or EL3, or at EL0 when HCR_EL2.{E2H,TGE} = {1,1}. A hypervisor can then give a guest a consistent physical and virtual view of time after migration, instead of trapping every physical counter access.

EL3 controls access: with SCR_EL3.ECVEn (bit 28) = 0, EL2 accesses to CNTPOFF_EL2 trap to EL3 and the offset is treated as zero for everything except direct accesses from EL3. In TF-A this is ENABLE_FEAT_ECV (17.3).

The extra CNTHCTL_EL2 traps

CNTHCTL_EL2.EL1TVT (bit 13) traps EL0 and EL1 accesses to the EL1 virtual timer registers, EL1TVCT (bit 14) traps EL0 and EL1 accesses to CNTVCT_EL0/CNTVCTSS_EL0 (neither applies when HCR_EL2.{E2H,TGE} = {1,1}), and EL1NVPCT/EL1NVVCT serve nested virtualization. All are described in 11.2 and 11.4.

EVNTIS

CNTKCTL_EL1.EVNTIS and CNTHCTL_EL2.EVNTIS (bit 17 in both) make EVNTI select a bit from counter bits [23:8] instead of [15:0]. At 1 GHz, bit 15 gives one event every 2^16 ns ≈ 65.5 µs at most, which is shorter than the 100 µs Linux targets. With EVNTIS, periods up to about 16.8 ms are possible.

The 1 GHz counter from v8.6 / v9.1

From Armv8.6 (and so Armv9.1), the system counter is required to be 64 bits wide and to count at 1 GHz. CNTFRQ_EL0 should therefore read 1,000,000,000 on any such system. This is architecturally the effective frequency. The physical implementation can update at a lower rate and increment by more than 1 per update. Several consequences follow:

  • Resolution is not 1 ns. Two reads a few nanoseconds apart can return the same value, and deltas come in multiples of the update increment. Do not treat CNTVCT deltas as cycle-accurate. Use the PMU cycle counter for that (16.3).
  • Wrap-around maths changes. Software that assumes the minimum 56-bit width reaches its wrap point after about 2.3 years at 1 GHz (2^56 ns), well within a product’s uptime, and Linux had to fix its clocksource masking for high-frequency counters. A full 64-bit count at 1 GHz wraps after about 584 years.
  • TVAL reaches only about 2.1 s ahead, so use CVAL (4.6).
  • Pre-v8.6 cores in the same system (for example a v8.2 management core beside v9 application cores) must see the same counter, so the system counter must run at 1 GHz for everyone. Check old firmware that hard-codes 24, 50 or 100 MHz.

FEAT_CNTSC: counter scaling

The cheap way to produce an effective 1 GHz count from a lower-frequency reference (say, a 50 MHz crystal) is to add a scaled increment per tick. FEAT_CNTSC provides this in the system counter:

  • CNTID.CNTSC = 0b0001 indicates support. CNTSCR sits at CNTControlBase + 0x010 (Secure only).
  • CNTSCR.ScaleVal is an unsigned fixed-point value with 8 integer and 24 fractional bits. With CNTCR.SCEN = 1, the counter adds ScaleVal on every tick. With SCEN = 0 it adds 0x1.000000, which is 1.
  • ScaleVal and SCEN can only be changed while CNTCR.EN = 0. Changing either while enabled makes the count UNKNOWN, and it stays UNKNOWN on later ticks.

For 50 MHz → 1 GHz, ScaleVal = 20.0 = 0x14000000, which is exact. For a 26 MHz reference, 1e9/26e6 = 38.4615… is not exactly representable in 2^-24 steps, and the rounding error drifts the count by parts per billion. That is negligible against crystal tolerance, but every die must use the identical ScaleVal, or their counters diverge steadily. The architecture version that FEAT_CNTSC is permitted from is listed in DDI0487 A2.

Keeping counters synchronized across chiplets

The architecture requires the system counter to provide a uniform view of system time to all PEs. Software relies on a stronger, practical property: if PE A reads time t1 and passes it to PE B, and B, ordered after observing it, reads t2, then t2 ≥ t1. The Linux scheduler, clock_gettime() across thread migration, and trace timestamps all assume it.

On one die this is achieved by distributing a single counter’s value to all PEs. Across dies there are two common schemes, both IMPLEMENTATION DEFINED:

SchemeHowBring-up obligations
One counter, distributedA master die’s counter value (often Gray-coded or interpolated, as with CoreSight timestamp distribution) is sent over the die-to-die linkLink latency must be compensated. The link must be up before any die reads time
One counter per die, synchronizedShared reference clock; each die’s CNTCV written with the same value and CNTCR.EN set by a simultaneous hardware triggerSame CNTFID/FCREQ and ScaleVal everywhere. A die that is reset or power-cycled alone must be resynchronized, not just re-enabled

Writing CNTCV and then setting EN from software on each die in turn leaves a skew equal to the software’s latency between the dies. That can be microseconds, which is far more than the cross-die message latency, so the monotonicity property above breaks. Skew only has to stay below the minimum one-way communication latency between PEs. The test for it is therefore a communication test, not a comparison of counter values. Frequency changes (FCREQ) must also be coordinated across dies. See 17.5 for where this fits in the bring-up order.

Validation note: Run a cross-die ping-pong. PE A executes ISB; MRS CNTVCT_EL0 and publishes the value with STLR. PE B waits with LDAR, then ISB; MRS CNTVCT_EL0, and checks t2 ≥ t1. Then swap roles. Run it for hours, across every die pair, across die-level power transitions and frequency mode changes. A failure with correct barriers means counter skew. A failure that disappears when you add the ISBs means the test itself was wrong. Also log t2 − t1 both ways: an asymmetric minimum shows the skew directly.

Checkpoint

Q4.7.1 A latency test on PE B does ldar w0, [flag] in a loop until it is non-zero, then immediately mrs x1, CNTVCT_EL0. PE A wrote the flag with stlr after recording its own timestamp t1. Occasionally x1 < t1, even on a single die. What is the correct fix?

  • A. Replace LDAR with LDR followed by DMB ISH, so the counter read is ordered after the flag load
  • B. Nothing is wrong in the code, because a single die’s counter is always consistent, so this must be a hardware erratum
  • C. Insert an ISB between the LDAR loop and the MRS, because acquire semantics only order later memory accesses, and a counter read is not one
  • D. Insert a DSB ISH after PE A’s STLR
Answer

C. Counter reads can be performed speculatively and out of order relative to other instructions. LDAR orders later memory accesses after it, so the MRS can execute speculatively before the loop has exited. The Arm ARM gives exactly this pattern (a signal read from memory, then ISB, then the counter read). DMB (A) also orders only memory accesses. A DSB on PE A (D) does not constrain when PE B samples the counter. B blames hardware for a software ordering bug.

Read more: Arm ARM (DDI0487), The Generic Timer, reading CNTPCT_EL0 and CNTVCT_EL0 (speculation and ordering)

Q4.7.2 On FEAT_ECV hardware, Linux reads CNTVCTSS_EL0 without a leading ISB but still executes the eor/add/ldr xzr sequence after it. Why is the trailing sequence still needed?

  • A. CNTVCTSS_EL0 is only self-synchronizing at EL1, so the vDSO at EL0 needs extra ordering
  • B. Self-synchronization constrains when the counter is sampled relative to earlier instructions, but a later load (the seqlock re-read) can still be satisfied before the counter read; the address dependency plus smp_rmb() prevents that
  • C. The dummy load flushes the counter value from the PE’s register cache to memory
  • D. Without it, CNTVCTSS_EL0 reads may return values that go backwards relative to an earlier CNTVCTSS_EL0 read on the same PE
Answer

B. The self-synchronized view removes the need for the ISB before the read. Linux uses the dependency to order the read against later loads, which no barrier can do for a system-register read. The dummy load’s address depends on the counter value, and DMB ISHLD orders that load before the sequence re-read. D is tempting, but reads of CNTVCT_EL0/CNTVCTSS_EL0 are already in program order relative to each other. A and C are not architectural behaviours.

Read more: Arm ARM (DDI0487), CNTVCTSS_EL0; Linux arch/arm64/include/asm/arch_timer.h

Q4.7.3 A two-die SoC passes the cross-die ping-pong test from die 1 to die 0, but from die 0 to die 1 about 0.1% of iterations have t2 < t1 by roughly 300 ns. The test uses STLR/LDAR and an ISB before each counter read. Firmware enables each die’s counter by writing CNTCV then CNTCR.EN from the boot PE, die 0 first. What does the result indicate?

  • A. Die 0’s counter is ahead of die 1’s by more than the die 0 → die 1 message latency, a skew introduced by the sequential software enable. The fix is a synchronized hardware start (or distribution from one counter), not more barriers
  • B. The test is missing a DSB before each counter read
  • C. Die 0’s CNTFRQ_EL0 is programmed differently from die 1’s
  • D. The ISB cannot order a counter read after an LDAR, so PE B still samples the counter before it sees the flag
Answer

A. A one-directional failure is the signature of a constant offset. A message from the die that is ahead to the die that is behind can arrive at an earlier counter value whenever the skew exceeds the one-way latency, while the reverse direction always passes. Die 0 was enabled first, so it has been counting longer and is ahead by roughly the software latency between the two enables. Barriers cannot remove a skew between two counters (B). The test’s barriers are already sufficient: the Arm ARM’s own pattern for ordering a counter read after a memory read is ISB (D). CNTFRQ_EL0 (C) is only informational and does not change the count.

Read more: Arm ARM (DDI0487), The Generic Timer: the system counter; platform system counter integration documentation