"Smcdeleg/Ssccfg": Counter Delegation

Part II Linux boot: optional Vol. II (Privileged) pp. 93–95 · ~3 min read

  • counter delegation

Perf profiling writes counters constantly — clearing overflow state on every sample, reloading counters on every context switch. Without help, each write is an SBI trap to M-mode. Smcdeleg/Ssccfg (always implemented together) let M-mode hand chosen counters to S/HS for direct writes, through the indirect-CSR window.

The delegation map

Counter i is delegated iff menvcfg.CDE = 1 ∧ mcounteren[i] = 1. Then siselect = 0x40 + i exposes its state:

Indirect HPM state mappings (Table 25); gating extensions in notes
sireg (low)sireg4 (high, RV32)sireg2 (config)sireg5 (cfg-high, RV32)
0x40cycle (Zicntr)cyclehcyclecfg (Smcntrpmf)cyclecfgh
0x41— hole: always illegal —
0x42instretinstrethinstretcfginstretcfgh
0x43…0x5Fhpmcounter3…31 (Zihpm)…h twinshpmevent3…31 (MINH masked; Sscofpmf for OF semantics)…h twins (Sscofpmf)
Dotted-underlined cells have explanations — click one.

Illegal-instruction for: any access with CDE=0; sireg3/sireg6 (unused); sireg4/sireg5 when XLEN=64; the 0x41 hole; a non-delegated counter; or missing underlying extensions. Under H: VS-mode access to this range raises virtual-instruction when CDE=1 (the hypervisor emulates a vPMU — guest counters aren’t hardware-delegated), and vsireg* in this range is illegal even from M/S.

scountinhibit and virtualized overflow

scountinhibit (0x120) is a masked alias of mcountinhibit: delegated counters’ bits are read-write, the rest read-only zero (CDE=0 → illegal; VS/VU → virtual-instruction). For overflow interrupts: with H + Sscofpmf + CDE=1, VS/VU reads of scountovf raise virtual-instruction; and with AIA present, the LCOFI bits of mvip/mvien (and hvip/hvien under H) must be writable so virtual counter-overflow interrupts can be injected into S and VS guests.

Hardware Designer Notes

Hardware cost is a routing table and write masks; the value is measurable perf-overhead reduction in any OS that samples. If you built p05’s router, this extension is one weekend: 32 select entries pointing at registers you already have.

Minimal Linux-boot hart MUST

  • Route 0x40+i selects onto the existing machine counter/event registers with delegation write-masks
  • Mask MINH (bit 62) to zero in every sireg* view
  • Implement the exception matrix exactly — especially the 0x41 hole and the CDE=1 virtual-instruction cases under H

MAY simplify / trap-and-emulate

  • Skip the extension until Zihpm + perf matter — Linux falls back to SBI PMU calls
  • Implement scountinhibit as a masked read/write port on mcountinhibit (no new flops)

Check yourself — counter delegation

1.What makes counter i writable from S-mode under Smcdeleg?

2.Why is siselect=0x41 a hole that always raises illegal-instruction?

3.S-mode reads a delegated hpmevent through sireg2. What does bit 62 (MINH) show?

3 questions