Skip to content

fix: replace RISC-V cpu_relax fence.i with pause hint for spin-wait#3374

Open
Felix-Gong wants to merge 1 commit into
apache:masterfrom
Felix-Gong:fix-riscv-cpu-relax
Open

fix: replace RISC-V cpu_relax fence.i with pause hint for spin-wait#3374
Felix-Gong wants to merge 1 commit into
apache:masterfrom
Felix-Gong:fix-riscv-cpu-relax

Conversation

@Felix-Gong

@Felix-Gong Felix-Gong commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Description

fence.i is an instruction-synchronization barrier on RISC-V that flushes the instruction cache. Using it in cpu_relax() for spin-wait loops is unnecessarily heavy — it should only be used after writing code (e.g., JIT compilation, self-modifying code).

Fix

Replace fence.i with the pause hint (Zihintpause extension, encoding 0x0100000F). The encoding fence 0, 1 is a HINT on all RISC-V implementations: it never traps and is ignored on CPUs without Zihintpause. On CPUs with Zihintpause it provides a multi-cycle stall hint that reduces power and improves resource fairness during spin loops. Matches the RISC-V Linux kernel's ALT_RISCV_PAUSE() behavior.

.word 0x0100000f is used instead of the pause mnemonic for maximum assembler compatibility, avoiding dependency on the pause mnemonic (requires zihintpause in -march) or the .insn directive (requires recent binutils/Clang).

Verification

  • Compiled standalone test file containing .word 0x0100000f on RISC-V 64-bit server (SG2044, rv64gcv) with GCC 12.3.1 and Clang (both tested with -march=rv64gc, rv64gcv, and rv64gcv_zihintpause)
  • Disassembly confirmed pause encoding 0x0100000f emitted in all cases
  • Cross-compilation with riscv64-linux-gnu-g++ (GCC 13) also confirmed correct encoding

References

@Felix-Gong Felix-Gong force-pushed the fix-riscv-cpu-relax branch 2 times, most recently from ddc78f1 to 64ebf0e Compare July 8, 2026 00:36
fence.i is an instruction-synchronization barrier that flushes the icache,
too heavy for a spin-wait hint. Use the pause hint (Zihintpause extension,
encoding 0x0100000F) instead, matching the RISC-V Linux kernel's
ALT_RISCV_PAUSE() behavior.

.word is used to emit the raw encoding for maximum assembler compatibility,
avoiding dependency on either the 'pause' mnemonic (requires Zihintpause in
-march) or the .insn directive (requires recent binutils/Clang).

Signed-off-by: Xiaofei Gong <gongxiaofei24@iscas.ac.cn>
Signed-off-by: YuanSheng <yuansheng@isrc.iscas.ac.cn>
@Felix-Gong Felix-Gong force-pushed the fix-riscv-cpu-relax branch from 64ebf0e to d5ae54c Compare July 8, 2026 01:00
@Felix-Gong Felix-Gong changed the title fix: replace RISC-V cpu_relax fence.i with nop for spin-wait hint fix: replace RISC-V cpu_relax fence.i with pause hint for spin-wait Jul 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant