riscv: add SBI Supervisor Software Events support
Subsystems (7)
v10 cover riscv: add SBI Supervisor Software Events support
This is v10 rebased onto v7.3-rc4, as a base for the RAS work requested by Himanshu. No additional fixes or features are included.
Only patch 7 needed adaptation: keep the upstream counter-mask bitmap conversion and snapshot NULL-check ordering, and adapt the SSE stop-all helper and early counter-mask initialization to the bitmap representation. The fast-only GUP user-stack copy remains unchanged.
Rebase validation: RV64 defconfig with SSE, PMU-SSE, CPU PM and kexec enabled builds Image, modules, the SSE test module and the user-stack selftest. The SSE, trap, fault and PMU objects also build for RV32. The exported series applies cleanly to v7.3-rc4 and reproduces the branch tree. On EVB247, the Debian-packaged rc4 kernel boots via kexec with its matching initrd and modules. The SSE framework and priority tests, all four stress layers in stress=1, and both user-stack selftests pass. The latter includes 32 concurrent samplers. No new kernel errors were observed. Unavailable injection events were skipped by the framework test; KVM was disabled in this test configuration, so virtualization was not retested.
The functional results below are retained from the original v10 and are not claims of runtime validation on this rebased kernel.
RISC-V does not architecturally define a supervisor-mode non-maskable interrupt (NMI). An interrupt that arrives while Linux has cleared SIE stays pending and is not observed until interrupts are enabled again. That is correct for ordinary interrupt handling, but some kernel work needs an NMI-like notification that can run even inside an interrupt-disabled region:
sampling a PMU overflow at the instruction that caused it, or taking a high-priority RAS report promptly, cannot wait for the next unmask boundary.
The SBI Supervisor Software Events (SSE) extension [1] fills this gap. It lets Linux register handlers for events that the SBI implementation can deliver ahead of ordinary traps and interrupts, giving RISC-V the NMI-like supervisor notification mechanism it otherwise lacks.
SSE can carry several event sources: high-priority RAS reports, double traps, and PMU overflow, with room for further standard and platform events. This series focuses on PMU overflow, its first user. Delivering overflows through SSE lets perf sample the code that was actually running while interrupts were disabled, rather than the later point where execution reached an interrupt-unmask boundary.
This series implements the Linux side of that interface: the architecture entry machinery, a firmware driver that exposes SSE events to in-kernel clients, PMU overflow delivery, and regression tests. Per-hart local events and system-wide global events share one client API.
SSE delivery model
==================
Linux first registers a handler and an event stack with the SBI implementation, then enables the event. When an event source is signalled, the M-mode SBI implementation preempts Linux even in an interrupt-disabled region:
it saves the interrupted supervisor state and constructs an S-mode context that enters the registered handler. Linux can now run its own handler, for example to take a perf sample or process a RAS report, then completes the event with another SBI call, allowing the interrupted context to resume.
The typical hardware-triggered delivery flow is (software-injected events skip the hardware trigger):
<--------- Linux kernel -----------> <-- Firmware ---> <- Hardware ->
interrupted context SSE handler OpenSBI Hardware
| | | |
[1] setup | |-register & enable--> |
| | | |
[2] trigger | | <----trigger------|
| | | |
[3] save | | +--------------+ |
| | | context save | |
| | +--------------+ |
| | | |
[4] inject | | +-----------------------+ |
| | | handler context setup | |
| | +-----------------------+ |
| <---inject (mret) ---| |
| | | |
[5] handle | +----------------+ | |
| | event handling | | |
| +----------------+ | |
| | | |
[6] complete | |-----complete-------> |
| | | |
[7] restore | | +-----------------+ |
| | | context restore | |
| | +-----------------+ |
| | | |
[8] resume <------------resume (mret) ------------| |
| | | |The context used to enter the handler exists only for this handoff; it is not the task context that the event interrupted. The architecture entry code joins the two sides: it moves execution onto the event's dedicated stack and shadow call stack, establishes the current task, and presents the interrupted registers to the callback as a normal pt_regs. Clients can therefore operate on the original interrupted context without depending on the firmware entry details.
Linux implementation
====================
An SSE handler runs in NMI-like context: it must not sleep, must not take a page fault, and may interrupt code that holds arbitrary locks or is partway through kernel entry. The implementation is shaped by those constraints.
Because it is NMI-like, an SSE can arrive at any point where interrupts are disabled, including while Linux is midway through exception entry, a task switch, or a KVM guest transition, where the normal kernel entry state is only partially established. The SSE entry wrapper (the architecture assembly that runs before the client callback) copes with this: it preserves Linux-owned stvec, hstatus, and task stack metadata across the handler and any nested exception, and its earliest instructions, which run before the event stack and current task are set up, are kept outside kprobe instrumentation.
The callback receives the interrupted registers as a pt_regs and is allowed to edit them. On RISC-V a6 and a7 carry SBI call arguments and results, so a callback that wants to influence an in-flight SBI call the event interrupted edits them there. The entry wrapper copies just a6 and a7 from that pt_regs back into the context handed to the completion SBI call, so the edit takes effect when the interrupted code resumes; the rest of the interrupted state is restored by firmware and left untouched.
The firmware driver maps the SBI event state machine onto kernel resource ownership. A callback, stack, and attribute buffer stay alive until firmware has removed every registration that can refer to them. Failed partial operations remain tracked for later cleanup, an aborted CPU-offline operation restores the requested event state, and shutdown and kexec mask SSE before Linux stops servicing handlers.
PMU overflow and perf
=====================
The RISC-V SBI PMU driver delivers overflows through ordinary interrupts by default. When firmware implements SSE and the local PMU-overflow event, the driver routes overflows through SSE instead. The choice is made once at setup and is not switched at runtime; an operational failure disables sampling rather than risking two active routes for the same overflow.
This changes where perf can observe an overflow, not how applications use perf. A normal PMU interrupt raised while S-mode interrupts are masked is handled only once they are enabled again, so the resulting sample often points at the unmask boundary rather than at the code that consumed the cycles. SSE can enter Linux at the original point and remove that source of sampling bias. No new perf option or perf.data format is introduced.
The entry code supplies the interrupted pt_regs needed for register samples and for kernel and user callchains. DWARF callchains additionally require a copy of the interrupted user stack. Since an SSE handler cannot take a normal page fault, this series takes a temporary reference to the resident user pages with fast-only GUP, copies them through their kernel mappings, and truncates the sample at the first page that is not immediately available. The existing in-atomic copy remains unchanged outside SSE context.
The PMU integration retains perf's throttling and stopped-event semantics. It restarts only runnable counters and orders the CPU power-management callbacks so that counters cannot resume after a hart has failed to restore its SSE delivery path.
Hardware results
================
We measured this on a RISC-V server platform. The same kernel source and perf binary were used for both routes; one delivered PMU overflows through ordinary interrupts and the other through SSE. The table shows the mean of three runs of three million single-CPU "perf bench sched pipe" operations. The "ops/s" columns are workload throughput (higher is better, so they show the profiling overhead); the "samples/s" columns are the sampling rate perf actually achieved against the requested -F frequency:
rate IRQ ops/s SSE ops/s delta IRQ samples/s SSE samples/s -F 99 337,707 339,555 +0.55% 98.0 98.6 -F 999 338,352 338,289 -0.02% 995.7 998.0 -F 5000 329,002 333,034 +1.23% 5001.7 5001.6
There were no lost samples. Across these normal frequency settings, both delivery modes reached the requested sample rate and workload throughput differed by no more than 1.23%.
The "perf bench sched pipe" workload also shows why the delivery mechanism matters to the resulting profile. Ordinary PMU interrupts cannot enter an interrupt-disabled kernel critical section. Overflows raised there remain pending until interrupts are enabled again. Samples consequently accumulate at the enable boundary rather than at the code that consumed the cycles. In the IRQ profile, finish_task_switch() and _raw_spin_unlock_irqrestore() therefore accounted for 54.99% of all samples.
SSE can enter Linux while S-mode interrupts are disabled. The PMU-SSE profile therefore samples inside those critical sections and exposes the scheduler, locking, address-space switching, and wake-up paths doing the actual work. The leading entries from the two -F 999 reports show the difference.
With ordinary PMU interrupt delivery:
overhead symbol
36.63% finish_task_switch.isra.0
18.36% _raw_spin_unlock_irqrestore
7.66% __internal_syscall_cancel
7.55% do_trap_ecall_u
4.19% mutex_lock
3.64% mutex_unlock
3.06% exit_to_user_mode_loopWith PMU-SSE delivery:
overhead symbol
5.48% __kprobes_text_end
5.29% __schedule
5.10% ret_from_exception
4.71% do_raw_spin_lock
4.01% do_trap_ecall_u
3.99% mutex_lock
3.66% switch_mm
3.43% mutex_unlock
3.29% exit_to_user_mode_loop
3.28% psi_group_changeThe ordinary interrupt profile is dominated by two interrupt-enable boundaries. With SSE, those two entries account for only 3.37%. The samples are instead distributed across scheduler paths within the critical sections.
At perf's configured limit of 100,000 samples per second, both routes still made progress without lost samples. In this deliberately saturated regime SSE reduced workload throughput by 2.7% to 5.8%, which exposes the additional firmware-entry cost and marks a practical upper boundary for sampling. Thirty-second perf top runs at the same rate each processed about 3.1 million samples with no loss, stalls, or kernel failures.
The DWARF callchain path gets dedicated coverage because it was the source of the corruption this series fixes. On the same platform,
"perf record -a -g --call-graph dwarf,512 -F 999" layered on a concurrent "hackbench -g25 -l600" -- the configuration that previously corrupted spinlocks and mutexes under SSE -- now completes cleanly, with no lost samples, lockups, RCU stalls, or faults, including a 431-iteration soak. Patch 9 adds a regression test that drives the non-faulting user-stack copy through the SSE handler with 32 concurrent samplers and checks perf's truncation semantics.
Changes in this resend
======================
This resend only rebases v10 onto v7.3-rc4. The only merge conflict was in patch 7, due to the upstream PMU counter-mask bitmap conversion. In v11, I will address the Sashiko review feedback and improve user-stack copying with an NMI-safe interface similar to x86's copy_from_user_nmi().
Changes in v10
==============
V10 turns the earlier feature series into a path suitable for sustained perf use. In particular, it:
- reconstructs and publishes the interrupted context for perf register
samples and kernel and user callchains;
- preserves current, task stack metadata, stvec, hstatus, and shadow-call
stack state across synthetic entry and nested exceptions;
- prevents fault-disabled accesses from entering the generic RISC-V page
fault path and provides a non-faulting SSE user-stack copy;
- makes event lifetime and rollback explicit across partial firmware
operations, CPU hotplug, shutdown, crash, and kexec; - closes PMU throttle, counter restart, CPU power-management, and cleanup races without adding a runtime SSE-to-IRQ transition; and
- expands the framework stress coverage and adds a regression test for high-frequency DWARF user-stack sampling.
Changes in v9:
- Rebased the original series onto RISC-V for-next.
- Preserved Linux-owned trap, virtualization, and supervisor state across the synthetic SSE handler.
- Added framework stress modes and updated MAINTAINERS.
Previous versions:
v9:
https://lore.kernel.org/r/[email protected] v8: https://lore.kernel.org/r/[email protected]
How to test
===========
Enable the SSE framework and SSE overflow delivery:
CONFIG_RISCV_SBI_SSE=y
CONFIG_RISCV_PMU_SBI=y
CONFIG_RISCV_PMU_SBI_SSE=y
PMU-SSE also requires two OpenSBI fixes:
f30a54f3b3a0 ("lib: sbi: pmu: Remove MIP clearing from pmu_sse_enable()")
[2], included since OpenSBI v1.7,
which keeps an overflow pending while its SSE event is temporarily disabled; and
35511bc6ee1c ("lib: sbi: sse: clear SPV for non-virtualized events") [3],
not yet included in a tagged release,
which stops a stale HSTATUS.SPV from being applied to a non-virtualized event.
Build tools/testing/selftests/riscv, then run:
for stress in 0 1 2; do
./run_sse_test.sh stress=$stress || break
done
./sse_perf_ustackUseful perf regression workloads include:
perf record -e cycles -a -- sleep 1
perf top
perf record -g -F 999 -- hackbench
perf record --call-graph dwarf,8192 -F 999 -- hackbench
perf record -a -C 3 -e cycles -F 999 -- \
taskset -c 3 perf bench sched pipe -l 3000000Limitations and follow-up work
==============================
This series does not yet deliver SSE events into a guest or unwind a guest stack; a later KVM-SSE series will let the host receive an event from firmware and inject the corresponding event into the guest.
Hibernation and crash kernels are unsupported: the current SBI interface cannot reconstruct firmware registrations after an image is restored, and a crash kernel cannot take over the registrations left by the crashed kernel, so it leaves SSE masked.
[1] https://docs.riscv.org/reference/sbi/ext-sse.html
[2] https://github.com/riscv-software-src/opensbi/commit/f30a54f3b3a091c225a00476f4039bf399badd1f
[3] https://github.com/riscv-software-src/opensbi/commit/35511bc6ee1c9c17b6a89b44c52e2044bb51b979
Acknowledgements
================
The original five feature patches were developed by Clément Léger and Himanshu Chauhan. Thanks to Susheng Yang for reporting the perf callchain failure and for providing a workload that made it reproducible.
Sorry for keeping you waiting. Since v9 I spent a good deal of time hardening the lifecycle and error paths and reproducing and analysing the bugs that only show up in the callchain path, until the series finally passed both functional and sustained stress testing on hardware. I am confident in v10, but, echoing Clément, SSE is a genuinely complex feature: it adds a new NMI-like entry path into the kernel to stand in for a hardware NMI. I would therefore welcome wider community testing and feedback, especially under high-frequency delivery and more complex handlers.
---
Clément Léger (5):
riscv: add SBI SSE extension definitions
riscv: add support for SBI Supervisor Software Events extension
drivers: firmware: add riscv SSE support
perf: RISC-V: add support for SSE event selftests/riscv: add SSE test module
Zhanpeng Zhang (4):
riscv: sse: mask events during shutdown and kexec
riscv: mm: avoid enabling interrupts for nofault page faults
perf: RISC-V: support callchains with SSE delivery selftests/riscv: add perf user-stack SSE copy regression test
Documentation/arch/riscv/index.rst | 1 + Documentation/arch/riscv/pmu-sse.rst | 55 + MAINTAINERS | 22 + arch/riscv/include/asm/asm.h | 14 +- arch/riscv/include/asm/perf_event.h | 10 + arch/riscv/include/asm/sbi.h | 63 + arch/riscv/include/asm/scs.h | 7 + arch/riscv/include/asm/sse.h | 82 ++ arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/Makefile | 1 + arch/riscv/kernel/asm-offsets.c | 14 + arch/riscv/kernel/entry.S | 14 + arch/riscv/kernel/machine_kexec.c | 11 + arch/riscv/kernel/perf_callchain.c | 142 ++ arch/riscv/kernel/reset.c | 18 + arch/riscv/kernel/sbi_sse.c | 246 ++++ arch/riscv/kernel/sbi_sse_entry.S | 226 +++ arch/riscv/kernel/smp.c | 17 + arch/riscv/mm/fault.c | 11 +- drivers/firmware/Kconfig | 1 + drivers/firmware/Makefile | 1 + drivers/firmware/riscv/Kconfig | 18 + drivers/firmware/riscv/Makefile | 3 + drivers/firmware/riscv/riscv_sbi_sse.c | 1228 +++++++++++++++++ drivers/perf/Kconfig | 11 + drivers/perf/riscv_pmu.c | 14 +- drivers/perf/riscv_pmu_sbi.c | 540 ++++++-- include/linux/cpuhotplug.h | 1 + include/linux/perf/riscv_pmu.h | 20 +- include/linux/riscv_sbi_sse.h | 95 ++ tools/testing/selftests/riscv/Makefile | 2 +- tools/testing/selftests/riscv/sse/Makefile | 10 + .../selftests/riscv/sse/module/Makefile | 22 + .../riscv/sse/module/riscv_sse_test.c | 1154 ++++++++++++++++ .../selftests/riscv/sse/run_sse_test.sh | 59 + .../selftests/riscv/sse/sse_perf_ustack.c | 564 ++++++++ 36 files changed, 4599 insertions(+), 99 deletions(-) create mode 100644 Documentation/arch/riscv/pmu-sse.rst create mode 100644 arch/riscv/include/asm/sse.h create mode 100644 arch/riscv/kernel/sbi_sse.c create mode 100644 arch/riscv/kernel/sbi_sse_entry.S create mode 100644 drivers/firmware/riscv/Kconfig create mode 100644 drivers/firmware/riscv/Makefile create mode 100644 drivers/firmware/riscv/riscv_sbi_sse.c create mode 100644 include/linux/riscv_sbi_sse.h create mode 100644 tools/testing/selftests/riscv/sse/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/riscv_sse_test.c create mode 100644 tools/testing/selftests/riscv/sse/run_sse_test.sh create mode 100644 tools/testing/selftests/riscv/sse/sse_perf_ustack.c
base-commit: 93f51579e7df248780214094418f205253383cc5
Signature · 1 line
2.50.1 (Apple Git-155)
PATCH RESEND v10 1/9 riscv: add SBI SSE extension definitions
From: Clément Léger <[email protected]>
Add definitions for the SBI Supervisor Software Events extension [1]. This extension enables the SBI to inject events into supervisor software much like ARM SDEI.
[1] https://lists.riscv.org/g/tech-prs/message/515
--- arch/riscv/include/asm/sbi.h | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+)
arch/riscv/include/asm/sbi.h +63 -0
@@ -38,6 +38,7 @@ enum sbi_ext_id {SBI_EXT_FWFT =0x46574654 ,SBI_EXT_MPXY =0x4D505859 ,SBI_EXT_DBTR =0x44425452 , +SBI_EXT_SSE =0x535345 ,/* Experimentals extensions must lie within this range */ SBI_EXT_EXPERIMENTAL_START = 0x08000000,
@@ -506,6 +507,68 @@ enum sbi_mpxy_rpmi_attribute_id {#define SBI_MPXY_CHAN_CAP_SEND_WITHOUT_RESP BIT(4)#define SBI_MPXY_CHAN_CAP_GET_NOTIFICATIONS BIT(5) +enum sbi_ext_sse_fid { +SBI_SSE_EVENT_ATTR_READ =0 , +SBI_SSE_EVENT_ATTR_WRITE , +SBI_SSE_EVENT_REGISTER , +SBI_SSE_EVENT_UNREGISTER , +SBI_SSE_EVENT_ENABLE , +SBI_SSE_EVENT_DISABLE , +SBI_SSE_EVENT_COMPLETE , +SBI_SSE_EVENT_INJECT , +SBI_SSE_HART_UNMASK , +SBI_SSE_HART_MASK , +}; + +enum sbi_sse_state { +SBI_SSE_STATE_UNUSED =0 , +SBI_SSE_STATE_REGISTERED =1 , +SBI_SSE_STATE_ENABLED =2 , +SBI_SSE_STATE_RUNNING =3 , +}; + +/* SBI SSE Event Attributes. */ +enum sbi_sse_attr_id { +SBI_SSE_ATTR_STATUS =0x00000000 , +SBI_SSE_ATTR_PRIO =0x00000001 , +SBI_SSE_ATTR_CONFIG =0x00000002 , +SBI_SSE_ATTR_PREFERRED_HART =0x00000003 , +SBI_SSE_ATTR_ENTRY_PC =0x00000004 , +SBI_SSE_ATTR_ENTRY_ARG =0x00000005 , +SBI_SSE_ATTR_INTERRUPTED_SEPC =0x00000006 , +SBI_SSE_ATTR_INTERRUPTED_FLAGS =0x00000007 , +SBI_SSE_ATTR_INTERRUPTED_A6 =0x00000008 , +SBI_SSE_ATTR_INTERRUPTED_A7 =0x00000009 , + +SBI_SSE_ATTR_MAX =0x0000000A +}; + +#define SBI_SSE_ATTR_STATUS_STATE_OFFSET 0 +#define SBI_SSE_ATTR_STATUS_STATE_MASK 0x3 +#define SBI_SSE_ATTR_STATUS_PENDING_OFFSET 2 +#define SBI_SSE_ATTR_STATUS_INJECT_OFFSET 3 + +#define SBI_SSE_ATTR_CONFIG_ONESHOT BIT(0) + +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_SSTATUS_SPP BIT(0) +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_SSTATUS_SPIE BIT(1) +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_HSTATUS_SPV BIT(2) +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_HSTATUS_SPVP BIT(3) +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_SSTATUS_SPELP BIT(4) +#define SBI_SSE_ATTR_INTERRUPTED_FLAGS_SSTATUS_SDT BIT(5) + +#define SBI_SSE_EVENT_LOCAL_HIGH_PRIO_RAS 0x00000000 +#define SBI_SSE_EVENT_LOCAL_DOUBLE_TRAP 0x00000001 +#define SBI_SSE_EVENT_GLOBAL_HIGH_PRIO_RAS 0x00008000 +#define SBI_SSE_EVENT_LOCAL_PMU_OVERFLOW 0x00010000 +#define SBI_SSE_EVENT_LOCAL_LOW_PRIO_RAS 0x00100000 +#define SBI_SSE_EVENT_GLOBAL_LOW_PRIO_RAS 0x00108000 +#define SBI_SSE_EVENT_LOCAL_SOFTWARE_INJECTED 0xffff0000 +#define SBI_SSE_EVENT_GLOBAL_SOFTWARE_INJECTED 0xffff8000 + +#define SBI_SSE_EVENT_PLATFORM BIT(14) +#define SBI_SSE_EVENT_GLOBAL BIT(15) +/* SBI debug triggers function IDs */ enum sbi_ext_dbtr_fid {SBI_EXT_DBTR_NUM_TRIGGERS =0 ,
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 1/9] riscv: add SBI SSE extension definitions
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines
From: Clément Léger <[email protected]>
Add definitions for the SBI Supervisor Software Events extension [1]. This extension enables the SBI to inject events into supervisor software much like ARM SDEI.
Quoted 7 lines
[1] https://lists.riscv.org/g/tech-prs/message/515
Signed-off-by Clément Léger <[email protected]>Co-developed-by Himanshu Chauhan <[email protected]>Signed-off-by Himanshu Chauhan <[email protected]>Co-developed-by Zhanpeng Zhang <[email protected]>Signed-off-by Zhanpeng Zhang <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH RESEND v10 2/9 riscv: add support for SBI Supervisor Software Events extension
In reply to Zhanpeng ZhangFrom: Clément Léger <[email protected]>
The SBI SSE extension allows firmware to notify supervisor software of events that must be delivered independently of normal S-mode interrupts. Firmware saves the minimal state required to enter the supervisor handler, and Linux builds the synthetic handler context around it.
SSE can arrive while Linux is already in an exception entry path. At that point sscratch and tp may be in the middle of the normal trap-entry exchange, so they cannot always identify current. Store current in a per-CPU slot and use the hart ID passed by firmware to recover it.
Give each event, including each CPU instance of a local event, a dedicated stack and shadow call stack. Synchronize vmapped stack ranges before unmasking events so that the handler cannot take a vmalloc fault while running in an NMI-like context.
The handler is a synthetic supervisor episode, but completion must resume the context interrupted by the SSE. Preserve stvec and, when the hypervisor extension is present, hstatus across the handler. Read the interrupted a6 and a7 values from the SSE attributes, construct pt_regs for the interrupted context, and write back any changes made by the handler.
Nested exceptions on the SSE event stack temporarily replace both TASK_TI_KERNEL_SP and TASK_TI_USER_SP. Preserve their original values across the handler and restore them before completing the event, so a nested exception cannot leave the interrupted task referring to the event stack.
Keep an explicit EVENT_REGISTER not-supported result distinct from other firmware failures. This lets clients select another delivery mechanism only when firmware has positively rejected the requested event.
--- MAINTAINERS | 12 ++ arch/riscv/include/asm/asm.h | 14 +- arch/riscv/include/asm/scs.h | 7 + arch/riscv/include/asm/sse.h | 82 +++++++++ arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/Makefile | 1 + arch/riscv/kernel/asm-offsets.c | 14 ++ arch/riscv/kernel/entry.S | 14 ++ arch/riscv/kernel/sbi_sse.c | 246 +++++++++++++++++++++++++++ arch/riscv/kernel/sbi_sse_entry.S | 226 ++++++++++++++++++++++++ 10 files changed, 614 insertions(+), 3 deletions(-) create mode 100644 arch/riscv/include/asm/sse.h create mode 100644 arch/riscv/kernel/sbi_sse.c create mode 100644 arch/riscv/kernel/sbi_sse_entry.S
MAINTAINERS +12 -0
@@ -23595,6 +23595,18 @@ F: arch/riscv/boot/dts/spacemit/ N: spacemit K: spacemit +RISC-V SUPERVISOR SOFTWARE EVENTS +M: Zhanpeng Zhang <[email protected]> +M: Himanshu Chauhan <[email protected]> +R: Yunhui Cui <[email protected]> +L: [email protected] +S: Maintained +F: arch/riscv/include/asm/sse.h +F: arch/riscv/kernel/sbi_sse.c +F: arch/riscv/kernel/sbi_sse_entry.S +F: drivers/firmware/riscv/riscv_sbi_sse.c +F: include/linux/riscv_sbi_sse.h + RISC-V TENSTORRENT SoC SUPPORT M: Drew Fustini <[email protected]> M: Joel Stanley <[email protected]>
arch/riscv/include/asm/asm.h +11 -3
@@ -91,16 +91,24 @@ .endm#ifdef CONFIG_SMP -.macro asm_per_cpu dst sym tmp - lw \tmp, TASK_TI_CPU_NUM(tp) - slli \tmp, \tmp, RISCV_LGPTR +.macro asm_per_cpu_with_cpu dst sym tmp cpu + slli \tmp, \cpu, RISCV_LGPTR la \dst, __per_cpu_offset add \dst, \dst, \tmp REG_L \tmp, 0(\dst) la \dst, \sym add \dst, \dst, \tmp .endm + +.macro asm_per_cpu dst sym tmp + lw \tmp, TASK_TI_CPU_NUM(tp) + asm_per_cpu_with_cpu \dst \sym \tmp \tmp +.endm #else /* CONFIG_SMP */ +.macro asm_per_cpu_with_cpu dst sym tmp cpu + la \dst, \sym +.endm + .macro asm_per_cpu dst sym tmp la \dst, \sym .endm
arch/riscv/include/asm/scs.h +7 -0
@@ -17,6 +17,11 @@ load_per_cpu gp, irq_shadow_call_stack_ptr, \tmp .endm +/* Load the per-CPU IRQ shadow call stack to gp. */ +.macro scs_load_sse_stack reg_evt + REG_L gp, SSE_REG_EVT_SHADOW_STACK(\reg_evt) +.endm + /* Load task_scs_sp(current) to gp. */ .macro scs_load_current REG_L gp, TASK_TI_SCS_SP(tp)
@@ -40,6 +45,8 @@ .endm .macro scs_load_irq_stack tmp .endm +.macro scs_load_sse_stack reg_evt +.endm .macro scs_load_current .endm .macro scs_load_current_if_task_changed prev
arch/riscv/include/asm/sse.h new file +82 -0
82 lines not on this page · raw message
arch/riscv/include/asm/thread_info.h +1 -0
@@ -36,6 +36,7 @@#define OVERFLOW_STACK_SIZE SZ_4K#define IRQ_STACK_SIZE THREAD_SIZE +#define SSE_STACK_SIZE THREAD_SIZE#ifndef __ASSEMBLER__
arch/riscv/kernel/Makefile +1 -0
@@ -101,6 +101,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE) += mcount-dyn.o obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o +obj-$(CONFIG_RISCV_SBI_SSE) += sbi_sse.o sbi_sse_entry.o ifeq ($(CONFIG_RISCV_SBI), y) obj-$(CONFIG_SMP) += sbi-ipi.o obj-$(CONFIG_SMP) += cpu_ops_sbi.o
arch/riscv/kernel/asm-offsets.c +14 -0
@@ -15,6 +15,8 @@#include <asm/ptrace.h> #include <asm/cpu_ops_sbi.h> #include <asm/stacktrace.h> +#include <asm/sbi.h> +#include <asm/sse.h> #include <asm/suspend.h> void asm_offsets (void );
@@ -533,6 +535,18 @@ void asm_offsets(void)DEFINE (FREGS_A6 , offsetof(struct __arch_ftrace_regs , a6));DEFINE (FREGS_A7 , offsetof(struct __arch_ftrace_regs , a7));#endif + +#ifdef CONFIG_RISCV_SBI_SSE +OFFSET (SSE_REG_EVT_STACK , sse_event_arch_data, stack); +OFFSET (SSE_REG_EVT_SHADOW_STACK , sse_event_arch_data, shadow_stack); +OFFSET (SSE_REG_EVT_TMP , sse_event_arch_data, tmp); +OFFSET (SSE_REG_HART_ID , sse_event_arch_data, hart_id); +OFFSET (SSE_REG_CPU_ID , sse_event_arch_data, cpu_id); + +DEFINE (SBI_EXT_SSE ,SBI_EXT_SSE ); +DEFINE (SBI_SSE_EVENT_COMPLETE ,SBI_SSE_EVENT_COMPLETE ); +DEFINE (ASM_NR_CPUS ,CONFIG_NR_CPUS ); +#endif #ifdef CONFIG_RISCV_SBI DEFINE (SBI_EXT_FWFT ,SBI_EXT_FWFT );DEFINE (SBI_EXT_FWFT_SET ,SBI_EXT_FWFT_SET );
arch/riscv/kernel/entry.S +14 -0
@@ -424,6 +424,15 @@ SYM_FUNC_END(call_on_irq_stack) * arguments are passed to schedule_tail. */ SYM_FUNC_START(__switch_to) +#ifdef CONFIG_RISCV_SBI_SSE + /* + * Mark the interval where tp changes from prev to next. SSE entry uses + * the interrupted tp while this per-CPU pointer is NULL. + */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S zero, 0(t0) +#endif + /* Save context into prev->thread */ li a4, TASK_THREAD_RA add a3, a0, a4
@@ -470,6 +479,11 @@ SYM_FUNC_START(__switch_to) REG_L s11, TASK_THREAD_S11_RA(a4) /* The offset of thread_info in task_struct is zero. */ move tp, a1 +#ifdef CONFIG_RISCV_SBI_SSE + /* Publish next only after tp contains its task_struct pointer. */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S tp, 0(t0) +#endif /* Switch to the next shadow call stack */ scs_load_current ret
arch/riscv/kernel/sbi_sse.c new file +246 -0
246 lines not on this page · raw message
arch/riscv/kernel/sbi_sse_entry.S new file +226 -0
226 lines not on this page · raw message
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 2/9] riscv: add support for SBI Supervisor Software Events extension
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Critical] riscv: premature restoration of CSR_SSTATUS re-enables interrupts leading to privilege…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Critical] riscv: premature restoration of CSR_SSTATUS re-enables interrupts leading to privilege escalation
- [High] riscv: truncation of 64-bit physical addresses on RV32 during SBI ecall
--
commit 491bc3336b6e02d6ec5b41c80039d8746df8e36e
Author: Clément Léger <[email protected]>
riscv: add support for SBI Supervisor Software Events extension
This commit introduces support for the SBI Supervisor Software Events extension, allowing firmware to notify supervisor software of independent events. It implements event registration, handler contexts with dedicated stacks, and restoration of the interrupted supervisor state.
arch/riscv/kernel/sbi_sse.c new file +0 -0
@@ -0,0 +1,246 @@
[ ... ]
Quoted 3 lines
(quoted diff) +3
-0+void noinstr do_sse(struct sse_event_arch_data *arch_evt, + struct pt_regs *regs, unsigned long hstatus) +{
[ ... ]
Review
Quoted 6 lines
(quoted diff) +6
-0+ /* Retrieve missing GPRs from SBI */ + sret = sbi_ecall(SBI_EXT_SSE, SBI_SSE_EVENT_ATTR_READ, arch_evt->evt_id, + SBI_SSE_ATTR_INTERRUPTED_A6, + (SBI_SSE_ATTR_INTERRUPTED_A7 - + SBI_SSE_ATTR_INTERRUPTED_A6) + 1, + (unsigned long)arch_evt->interrupted_phys, 0, 0);
[Severity: High]
Does this cast to unsigned long truncate the upper 32 bits of the physical address on RV32 systems?
On RV32 systems with 34-bit physical addressing (Sv32), phys_addr_t is 64-bit. If the event data is allocated in memory residing above the 4GB boundary, this truncation could cause the firmware to write the interrupted registers to the wrong physical address in the lower 4GB, resulting in memory corruption.
Quoted 1 line
(quoted diff) +1
-0+ if (sret.error) {
[ ... ]
Review
Quoted 9 lines
(quoted diff) +9
-0+ if (memcmp(®s->a6, arch_evt->interrupted, + sizeof(*arch_evt->interrupted))) { + memcpy(arch_evt->interrupted, ®s->a6, + sizeof(*arch_evt->interrupted)); + sret = sbi_ecall(SBI_EXT_SSE, SBI_SSE_EVENT_ATTR_WRITE, + arch_evt->evt_id, SBI_SSE_ATTR_INTERRUPTED_A6, + (SBI_SSE_ATTR_INTERRUPTED_A7 - + SBI_SSE_ATTR_INTERRUPTED_A6) + 1, + (unsigned long)arch_evt->interrupted_phys, 0, 0);
[Severity: High]
Similarly, does this truncation happen identically on the writeback path?
Quoted 4 lines
(quoted diff) +4
-0+ /* + * If writeback fails, COMPLETE resumes with firmware's original + * a6/a7 rather than treating the shared buffer as committed. + */
[ ... ]
arch/riscv/kernel/sbi_sse_entry.S new file +0 -0
@@ -0,0 +1,226 @@
[ ... ]
Review
Quoted 12 lines
(quoted diff) +12
-0+ csrw CSR_SSCRATCH, s4 + ALTERNATIVE("nop", "csrw hstatus, s5", 0, RISCV_ISA_EXT_H, 1) + csrw CSR_STVEC, s3 + + REG_L a0, PT_STATUS(sp) + REG_L a1, PT_EPC(sp) + REG_L a2, PT_BADADDR(sp) + REG_L a3, PT_CAUSE(sp) + csrw CSR_SSTATUS, a0 + csrw CSR_EPC, a1 + csrw CSR_STVAL, a2 + csrw CSR_SCAUSE, a3
[Severity: Critical]
Does restoring the interrupted context's sstatus here prematurely re-enable interrupts before the handler completes natively via the SBI firmware?
If the interrupted context had interrupts enabled (SR_SIE bit set), writing it back immediately re-enables interrupts while still executing on the kernel's SSE stack.
If a pending interrupt fires during the window before the ecall, handle_exception reads the previously restored sscratch. If sscratch contains a user task pointer, handle_exception could incorrectly swap the user's TASK_TI_USER_SP with the kernel SSE stack pointer, leaking the kernel stack to userspace.
Quoted 3 lines
(quoted diff) +3
-0+ + REG_L ra, PT_RA(sp) + REG_L s0, PT_S0(sp)
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Re: [PATCH v10 RESEND 2/9] riscv: add support for SBI Supervisor Software Events extension
In reply to Zhanpeng ZhangHi Zhanpeng,
Quoted 64 lines · Zhanpeng Zhang
From: Clément Léger <[email protected]>
The SBI SSE extension allows firmware to notify supervisor software of events that must be delivered independently of normal S-mode interrupts. Firmware saves the minimal state required to enter the supervisor handler, and Linux builds the synthetic handler context around it.
SSE can arrive while Linux is already in an exception entry path. At that point sscratch and tp may be in the middle of the normal trap-entry exchange, so they cannot always identify current. Store current in a per-CPU slot and use the hart ID passed by firmware to recover it.
Give each event, including each CPU instance of a local event, a dedicated stack and shadow call stack. Synchronize vmapped stack ranges before unmasking events so that the handler cannot take a vmalloc fault while running in an NMI-like context.
The handler is a synthetic supervisor episode, but completion must resume the context interrupted by the SSE. Preserve stvec and, when the hypervisor extension is present, hstatus across the handler. Read the interrupted a6 and a7 values from the SSE attributes, construct
pt_regsfor the interrupted context, and write back any changes made by the handler.Nested exceptions on the SSE event stack temporarily replace both
TASK_TI_KERNEL_SPandTASK_TI_USER_SP. Preserve their original values across the handler and restore them before completing the event, so a nested exception cannot leave the interrupted task referring to the event stack.Keep an explicit
EVENT_REGISTERnot-supported result distinct from other firmware failures. This lets clients select another delivery mechanism only when firmware has positively rejected the requested event.Signed-off-by Clément Léger <[email protected]>Co-developed-by Himanshu Chauhan <[email protected]>Signed-off-by Himanshu Chauhan <[email protected]>Co-developed-by Zhanpeng Zhang <[email protected]>Signed-off-by Zhanpeng Zhang <[email protected]>--- MAINTAINERS | 12 ++ arch/riscv/include/asm/asm.h | 14 +- arch/riscv/include/asm/scs.h | 7 + arch/riscv/include/asm/sse.h | 82 +++++++++ arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/Makefile | 1 + arch/riscv/kernel/asm-offsets.c | 14 ++ arch/riscv/kernel/entry.S | 14 ++ arch/riscv/kernel/sbi_sse.c | 246 +++++++++++++++++++++++++++ arch/riscv/kernel/sbi_sse_entry.S | 226 ++++++++++++++++++++++++ 10 files changed, 614 insertions(+), 3 deletions(-) create mode 100644 arch/riscv/include/asm/sse.h create mode 100644 arch/riscv/kernel/sbi_sse.c create mode 100644 arch/riscv/kernel/sbi_sse_entry.SMAINTAINERS +2
-0@@ -23595,6 +23595,18 @@ F: arch/riscv/boot/dts/spacemit/ N: spacemit K: spacemit +RISC-V SUPERVISOR SOFTWARE EVENTS +M: Zhanpeng Zhang <[email protected]>
MAINTAINERS F: arch/riscv/boot/dts/spacemit/ · line 23609
Quoted 10 lines
MAINTAINERS +10
-0+M: Himanshu Chauhan <[email protected]> +R: Yunhui Cui <[email protected]> +L: [email protected] +S: Maintained +F: arch/riscv/include/asm/sse.h +F: arch/riscv/kernel/sbi_sse.c +F: arch/riscv/kernel/sbi_sse_entry.S +F: drivers/firmware/riscv/riscv_sbi_sse.c +F: include/linux/riscv_sbi_sse.h +
I would suggest that you make changes in maintainers as a separate patch.
Quoted 423 lines
MAINTAINERS +0
-0RISC-V TENSTORRENT SoC SUPPORT M: Drew Fustini <[email protected]> M: Joel Stanley <[email protected]>arch/riscv/include/asm/asm.h +11
-3@@ -91,16 +91,24 @@ .endm#ifdef CONFIG_SMP -.macro asm_per_cpu dst sym tmp - lw \tmp, TASK_TI_CPU_NUM(tp) - slli \tmp, \tmp, RISCV_LGPTR +.macro asm_per_cpu_with_cpu dst sym tmp cpu + slli \tmp, \cpu, RISCV_LGPTR la \dst, __per_cpu_offset add \dst, \dst, \tmp REG_L \tmp, 0(\dst) la \dst, \sym add \dst, \dst, \tmp .endm + +.macro asm_per_cpu dst sym tmp + lw \tmp, TASK_TI_CPU_NUM(tp) + asm_per_cpu_with_cpu \dst \sym \tmp \tmp +.endm #else /* CONFIG_SMP */ +.macro asm_per_cpu_with_cpu dst sym tmp cpu + la \dst, \sym +.endm + .macro asm_per_cpu dst sym tmp la \dst, \sym .endmarch/riscv/include/asm/scs.h +7
-0@@ -17,6 +17,11 @@ load_per_cpu gp, irq_shadow_call_stack_ptr, \tmp .endm +/* Load the per-CPU IRQ shadow call stack to gp. */ +.macro scs_load_sse_stack reg_evt + REG_L gp, SSE_REG_EVT_SHADOW_STACK(\reg_evt) +.endm + /* Load task_scs_sp(current) to gp. */ .macro scs_load_current REG_L gp, TASK_TI_SCS_SP(tp)@@ -40,6 +45,8 @@ .endm .macro scs_load_irq_stack tmp .endm +.macro scs_load_sse_stack reg_evt +.endm .macro scs_load_current .endm .macro scs_load_current_if_task_changed prevarch/riscv/include/asm/sse.h new file +82
-0@@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright (C) 2024 Rivos Inc. +*/ +#ifndef __ASM_SSE_H +#define __ASM_SSE_H + +#include <linux/printk.h> +#include <linux/types.h> + +#include <asm/sbi.h> + +static inline bool riscv_sse_available (void ) +{ +#ifdef CONFIG_RISCV_SBI +return sbi_probe_extension (SBI_EXT_SSE ) >0 ; +#else +return false; +#endif +} + +static inline void riscv_sse_mask_current_hart (void ) +{ +#ifdef CONFIG_RISCV_SBI +struct sbiret ret; + +if (!riscv_sse_available ()) +return ; + + ret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_HART_MASK ,0 ,0 ,0 ,0 ,0 ,0 ); +if (ret.error && ret.error !=SBI_ERR_ALREADY_STOPPED ) +pr_emerg ("SSE hart mask failed: %ld\n" , ret.error); +#endif +} + +#ifdef CONFIG_RISCV_SBI_SSE + +struct sse_event_interrupted_state { +unsigned long a6; +unsigned long a7; +}; + +struct sse_event_arch_data { +void *stack; +void *shadow_stack; +unsigned long tmp; +struct sse_event_interrupted_state *interrupted; +phys_addr_t interrupted_phys; +u32 evt_id; +unsigned long hart_id; +unsigned int cpu_id; +}; + +struct riscv_sse_interrupted_context { +struct pt_regs *regs; +unsigned long hstatus; +}; + +static inline bool sse_event_is_global (u32 evt) +{ +return !!(evt &SBI_SSE_EVENT_GLOBAL ); +} + +void arch_sse_event_update_cpu (struct sse_event_arch_data *arch_evt,int cpu); +int arch_sse_init_event (struct sse_event_arch_data *arch_evt,u32 evt_id, +int cpu); +void arch_sse_free_event (struct sse_event_arch_data *arch_evt); +int arch_sse_register_event (struct sse_event_arch_data *arch_evt); +void arch_sse_init_cpu (void ); + +void sse_handle_event (struct sse_event_arch_data *arch_evt, +struct pt_regs *regs); +asmlinkage void handle_sse(void); +asmlinkage void noinstr do_sse(struct sse_event_arch_data *arch_evt, +struct pt_regs *regs,unsigned long hstatus); + +const struct riscv_sse_interrupted_context * +riscv_sse_get_interrupted_context (void ); + +#endif + +#endif arch/riscv/include/asm/thread_info.h +1
-0@@ -36,6 +36,7 @@#define OVERFLOW_STACK_SIZE SZ_4K#define IRQ_STACK_SIZE THREAD_SIZE +#define SSE_STACK_SIZE THREAD_SIZE#ifndef __ASSEMBLER__arch/riscv/kernel/Makefile +1
-0@@ -101,6 +101,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE) += mcount-dyn.o obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o +obj-$(CONFIG_RISCV_SBI_SSE) += sbi_sse.o sbi_sse_entry.o ifeq ($(CONFIG_RISCV_SBI), y) obj-$(CONFIG_SMP) += sbi-ipi.o obj-$(CONFIG_SMP) += cpu_ops_sbi.oarch/riscv/kernel/asm-offsets.c +14
-0@@ -15,6 +15,8 @@#include <asm/ptrace.h> #include <asm/cpu_ops_sbi.h> #include <asm/stacktrace.h> +#include <asm/sbi.h> +#include <asm/sse.h> #include <asm/suspend.h> void asm_offsets (void );@@ -533,6 +535,18 @@ void asm_offsets(void)DEFINE (FREGS_A6 , offsetof(struct __arch_ftrace_regs , a6));DEFINE (FREGS_A7 , offsetof(struct __arch_ftrace_regs , a7));#endif + +#ifdef CONFIG_RISCV_SBI_SSE +OFFSET (SSE_REG_EVT_STACK , sse_event_arch_data, stack); +OFFSET (SSE_REG_EVT_SHADOW_STACK , sse_event_arch_data, shadow_stack); +OFFSET (SSE_REG_EVT_TMP , sse_event_arch_data, tmp); +OFFSET (SSE_REG_HART_ID , sse_event_arch_data, hart_id); +OFFSET (SSE_REG_CPU_ID , sse_event_arch_data, cpu_id); + +DEFINE (SBI_EXT_SSE ,SBI_EXT_SSE ); +DEFINE (SBI_SSE_EVENT_COMPLETE ,SBI_SSE_EVENT_COMPLETE ); +DEFINE (ASM_NR_CPUS ,CONFIG_NR_CPUS ); +#endif #ifdef CONFIG_RISCV_SBI DEFINE (SBI_EXT_FWFT ,SBI_EXT_FWFT );DEFINE (SBI_EXT_FWFT_SET ,SBI_EXT_FWFT_SET );arch/riscv/kernel/entry.S +14
-0@@ -424,6 +424,15 @@ SYM_FUNC_END(call_on_irq_stack) * arguments are passed to schedule_tail. */ SYM_FUNC_START(__switch_to) +#ifdef CONFIG_RISCV_SBI_SSE + /* + * Mark the interval where tp changes from prev to next. SSE entry uses + * the interrupted tp while this per-CPU pointer is NULL. + */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S zero, 0(t0) +#endif + /* Save context into prev->thread */ li a4, TASK_THREAD_RA add a3, a0, a4@@ -470,6 +479,11 @@ SYM_FUNC_START(__switch_to) REG_L s11, TASK_THREAD_S11_RA(a4) /* The offset of thread_info in task_struct is zero. */ move tp, a1 +#ifdef CONFIG_RISCV_SBI_SSE + /* Publish next only after tp contains its task_struct pointer. */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S tp, 0(t0) +#endif /* Switch to the next shadow call stack */ scs_load_current retarch/riscv/kernel/sbi_sse.c new file +181
-0@@ -0,0 +1,246 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Copyright (C) 2025 Rivos Inc. +*/ +#include <linux/nmi.h> +#include <linux/sched.h> +#include <linux/scs.h> +#include <linux/bitfield.h> +#include <linux/percpu-defs.h> +#include <linux/string.h> + +#include <asm/asm-prototypes.h> +#include <asm/switch_to.h> +#include <asm/irq_stack.h> +#include <asm/sbi.h> +#include <asm/sse.h> +#include <asm/tlbflush.h> + +DEFINE_PER_CPU(struct task_struct *, __sbi_sse_entry_task); +static DEFINE_PER_CPU(struct riscv_sse_interrupted_context *, + riscv_sse_interrupted_context); + +const struct riscv_sse_interrupted_context * +riscv_sse_get_interrupted_context (void ) +{ +return this_cpu_read (riscv_sse_interrupted_context); +} + +void __weak sse_handle_event (struct sse_event_arch_data *arch_evt,struct pt_regs *regs) +{ +} + +void noinstr do_sse(struct sse_event_arch_data *arch_evt, +struct pt_regs *regs,unsigned long hstatus) +{ +struct riscv_sse_interrupted_context context = { regs, hstatus }; +struct riscv_sse_interrupted_context *previous; +struct sbiret sret; + +nmi_enter (); +instrumentation_begin (); + +/* Retrieve missing GPRs from SBI */ + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_ATTR_READ , arch_evt->evt_id, +SBI_SSE_ATTR_INTERRUPTED_A6 , + (SBI_SSE_ATTR_INTERRUPTED_A7 - +SBI_SSE_ATTR_INTERRUPTED_A6 ) +1 , + (unsigned long )arch_evt->interrupted_phys,0 ,0 ); +if (sret.error) { +pr_warn ("Failed to read interrupted registers for event %x: %ld\n" , + arch_evt->evt_id, sret.error); +/* Let the client quiesce its source without using incomplete regs. */ +sse_handle_event (arch_evt,NULL ); + goto out; + } + +memcpy (®s->a6, arch_evt->interrupted, +sizeof (*arch_evt->interrupted)); + +/* Make the interrupted frame visible while clients handle this event. */ + previous =this_cpu_read (riscv_sse_interrupted_context); +this_cpu_write (riscv_sse_interrupted_context, &context); +sse_handle_event (arch_evt, regs); +this_cpu_write (riscv_sse_interrupted_context, previous); + +if (memcmp (®s->a6, arch_evt->interrupted, +sizeof (*arch_evt->interrupted))) { +memcpy (arch_evt->interrupted, ®s->a6, +sizeof (*arch_evt->interrupted)); + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_ATTR_WRITE , + arch_evt->evt_id,SBI_SSE_ATTR_INTERRUPTED_A6 , + (SBI_SSE_ATTR_INTERRUPTED_A7 - +SBI_SSE_ATTR_INTERRUPTED_A6 ) +1 , + (unsigned long )arch_evt->interrupted_phys,0 ,0 ); +/* +* If writeback fails, COMPLETE resumes with firmware's original +* a6/a7 rather than treating the shared buffer as committed. +*/ +if (sret.error) +pr_warn ("Failed to write interrupted registers for event %x: %ld\n" , + arch_evt->evt_id, sret.error); + } + +out: +instrumentation_end (); +nmi_exit (); +} + +static void *alloc_to_stack_pointer (void *alloc) +{ +return alloc ? alloc +SSE_STACK_SIZE :NULL ; +} + +static void *stack_pointer_to_alloc (void *stack) +{ +return stack ? stack -SSE_STACK_SIZE :NULL ; +} + +static void arch_sse_flush_tlb_range (struct sse_event_arch_data *arch_evt, +unsigned long start,unsigned long size) +{ +unsigned long end = start + size; + +if (sse_event_is_global (arch_evt->evt_id)) +flush_tlb_kernel_range (start, end); +else +local_flush_tlb_kernel_range (start, end); +} + +static void arch_sse_shadow_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +#ifdef CONFIG_SHADOW_CALL_STACK +if (arch_evt->shadow_stack) +arch_sse_flush_tlb_range (arch_evt, + (unsigned long )arch_evt->shadow_stack, +SCS_SIZE ); +#endif +} + +#ifdef CONFIG_VMAP_STACK +static void *sse_stack_alloc (unsigned int cpu) +{ +void *stack =arch_alloc_vmap_stack (SSE_STACK_SIZE ,cpu_to_node (cpu)); + +return alloc_to_stack_pointer (stack); +} + +static void sse_stack_free (void *stack) +{ +vfree (stack_pointer_to_alloc (stack)); +} + +static void arch_sse_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +void *p_stack = arch_evt->stack; +unsigned long stack = (unsigned long )stack_pointer_to_alloc (p_stack); + +/* +* Flush the tlb to avoid taking any exception when accessing the +* vmapped stack inside the SSE handler +*/ +arch_sse_flush_tlb_range (arch_evt, stack,SSE_STACK_SIZE ); + +arch_sse_shadow_stack_cpu_sync (arch_evt); +} +#else /* CONFIG_VMAP_STACK */ +static void *sse_stack_alloc (unsigned int cpu) +{ +void *stack =kmalloc (SSE_STACK_SIZE ,GFP_KERNEL ); + +return alloc_to_stack_pointer (stack); +} + +static void sse_stack_free (void *stack) +{ +kfree (stack_pointer_to_alloc (stack)); +} + +static void arch_sse_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +arch_sse_shadow_stack_cpu_sync (arch_evt); +} +#endif /* CONFIG_VMAP_STACK */ + +static int sse_init_scs (int cpu,struct sse_event_arch_data *arch_evt) +{ +void *stack; + +if (!scs_is_enabled ()) +return 0 ; + + stack =scs_alloc (cpu_to_node (cpu)); +if (!stack) +return -ENOMEM ; + + arch_evt->shadow_stack = stack; + +return 0 ; +} + +void arch_sse_event_update_cpu (struct sse_event_arch_data *arch_evt,int cpu)
arch/riscv/kernel/sbi_sse.c line 191
Quoted 10 lines
arch/riscv/kernel/sbi_sse.c new file +10
-0+{ + arch_evt->cpu_id = cpu; + arch_evt->hart_id =cpuid_to_hartid_map (cpu); +} + +void arch_sse_init_cpu (void ) +{ +__this_cpu_write (__sbi_sse_entry_task, current); +} +
This is called from sse_cpu_online() in the cpuhp callback, which runs preemptible, and the boot CPU instance runs from an initcall. With DEBUG_PREEMPT you can get a __this_cpu_write() in preemptible warning. Can you check? Moreover, if the task migrates between computing the per-CPU address and the store, the wrong CPU's slot is written. I would suggest use this_cpu_write() under preempt_disable().
Quoted 148 lines
arch/riscv/kernel/sbi_sse.c new file +55
-0+int arch_sse_init_event (struct sse_event_arch_data *arch_evt,u32 evt_id, +int cpu) +{ +void *stack; + + arch_evt->interrupted =kmalloc_obj (*arch_evt->interrupted,GFP_KERNEL ); +if (!arch_evt->interrupted) +return -ENOMEM ; + + arch_evt->evt_id = evt_id; + stack =sse_stack_alloc (cpu); +if (!stack) + goto err_free_interrupted; + + arch_evt->stack = stack; + +if (sse_init_scs (cpu, arch_evt)) { +sse_stack_free (arch_evt->stack); + goto err_free_interrupted; + } + +/* kmalloc keeps the two adjacent SBI attribute words contiguous. */ + arch_evt->interrupted_phys =virt_to_phys (arch_evt->interrupted); + +arch_sse_event_update_cpu (arch_evt, cpu); + +return 0 ; + +err_free_interrupted: +kfree (arch_evt->interrupted); + arch_evt->interrupted =NULL ; +return -ENOMEM ; +} + +void arch_sse_free_event (struct sse_event_arch_data *arch_evt) +{ +scs_free (arch_evt->shadow_stack); +sse_stack_free (arch_evt->stack); +kfree (arch_evt->interrupted); +} + +int arch_sse_register_event (struct sse_event_arch_data *arch_evt) +{ +struct sbiret sret; + +arch_sse_stack_cpu_sync (arch_evt); + + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_REGISTER , arch_evt->evt_id, + (unsigned long )handle_sse, (unsigned long )arch_evt,0 , +0 ,0 ); +if (sret.error ==SBI_ERR_NOT_SUPPORTED ) +return -EOPNOTSUPP ; + +return sbi_err_map_linux_errno (sret.error); +}arch/riscv/kernel/sbi_sse_entry.S new file +87
-0@@ -0,0 +1,226 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2025 Rivos Inc. + */ + +#include <linux/init.h> +#include <linux/linkage.h> + +#include <asm/alternative-macros.h> +#include <asm/asm.h> +#include <asm/csr.h> +#include <asm/hwcap.h> +#include <asm/scs.h> + +/* When entering handle_sse, the following registers are set: + * a6: contains the hartid + * a7: contains a sse_event_arch_data struct pointer + */ +SYM_CODE_START(handle_sse) + /* Save stack temporarily */ + REG_S sp, SSE_REG_EVT_TMP(a7) + /* Set entry stack */ + REG_L sp, SSE_REG_EVT_STACK(a7) + + addi sp, sp, -(PT_SIZE_ON_STACK) + REG_S ra, PT_RA(sp) + REG_S s0, PT_S0(sp) + REG_S s1, PT_S1(sp) + REG_S s2, PT_S2(sp) + REG_S s3, PT_S3(sp) + REG_S s4, PT_S4(sp) + REG_S s5, PT_S5(sp) + REG_S s6, PT_S6(sp) + REG_S s7, PT_S7(sp) + REG_S s8, PT_S8(sp) + REG_S s9, PT_S9(sp) + REG_S s10, PT_S10(sp) + REG_S s11, PT_S11(sp) + REG_S tp, PT_TP(sp) + REG_S t0, PT_T0(sp) + REG_S t1, PT_T1(sp) + REG_S t2, PT_T2(sp) + REG_S t3, PT_T3(sp) + REG_S t4, PT_T4(sp) + REG_S t5, PT_T5(sp) + REG_S t6, PT_T6(sp) + REG_S gp, PT_GP(sp) + REG_S a0, PT_A0(sp) + REG_S a1, PT_A1(sp) + REG_S a2, PT_A2(sp) + REG_S a3, PT_A3(sp) + REG_S a4, PT_A4(sp) + REG_S a5, PT_A5(sp) + + /* Retrieve entry sp */ + REG_L a4, SSE_REG_EVT_TMP(a7) + /* Save CSRs */ + csrr a0, CSR_EPC + csrr a1, CSR_SSTATUS + csrr a2, CSR_STVAL + csrr a3, CSR_SCAUSE + + REG_S a0, PT_EPC(sp) + REG_S a1, PT_STATUS(sp) + REG_S a2, PT_BADADDR(sp) + REG_S a3, PT_CAUSE(sp) + REG_S a4, PT_SP(sp) + + /* Disable user memory access and floating/vector computing */ + li t0, SR_SUM | SR_FS_VS + csrc CSR_STATUS, t0 + + load_global_pointer + scs_load_sse_stack a7 + +#ifdef CONFIG_SMP + REG_L t4, SSE_REG_HART_ID(a7) + lw t3, SSE_REG_CPU_ID(a7) + + bne t4, a6, .Lfind_hart_id_slowpath + +.Lcpu_id_found: +#else + mv t3, zero +#endif + + asm_per_cpu_with_cpu t2 __sbi_sse_entry_task t1 t3
arch/riscv/kernel/sbi_sse_entry.S line 97
Quoted 10 lines
arch/riscv/kernel/sbi_sse_entry.S new file +10
-0+ REG_L tp, 0(t2) + bnez tp, .Lcurrent_task_found + + /* __switch_to() marks its transition window with a NULL entry task. */ + REG_L tp, PT_TP(sp) + +.Lcurrent_task_found: + /* Nested exceptions temporarily replace these with the SSE stack. */ + REG_L s6, TASK_TI_KERNEL_SP(tp) + REG_L s7, TASK_TI_USER_SP(tp)
Only KERNEL_SP and USER_SP are preserved. handle_exception's new_valid_map_cpus_check macro parks a0/a1/a2 in TASK_TI_A0/A1/A2(tp) and reloads them a few instructions later, for any page fault on a kernel address on 64-bit MMU. If an SSE arrives inside that window and the handler takes a vmalloc/kfence fault of its own, the nested handle_exception runs the same macro on the same tp and overwrites those three slots. When the SSE completes, the interrupted macro reloads a0/a1/a2 with the handler's values and they end up in the saved context, i.e. a corrupted syscall argument / user a0-a2. The window is small, but "nested exceptions are transparent" is then false. Please save and restore those three slots the same way as s6/s7.
I am wondering if this is the reason for the "repeated nested faults corrupt the interrupted context" that your 6/9 patch refers to; if so it should be fixed here, not worked around in perf. Check if its indeed true.
Quoted 132 lines
arch/riscv/kernel/sbi_sse_entry.S new file +129
-0+ + mv a1, sp /* pt_regs on stack */ + + /* + * Run the SSE handler with the normal exception vector, but restore the + * interrupted stvec before completing the event. SSE can arrive while + * the kernel is using a temporary trap vector in a sensitive entry path. + */ + csrr s3, CSR_STVEC + la t0, handle_exception + csrw CSR_STVEC, t0 + + /* + * Preserve the full HS-mode virtualization state across the handler. + * hstatus is live supervisor state rather than an SSE interrupted + * attribute, and OpenSBI consumes hstatus.SPV during event completion. + * Saving the whole CSR keeps the handler episode transparent to KVM and + * avoids having to infer which hstatus bits may matter to a guest resume. + */ + li s5, 0 + ALTERNATIVE("nop", "csrr s5, hstatus", 0, RISCV_ISA_EXT_H, 1) + + /* + * Save sscratch for restoration since we might have interrupted the + * kernel in early exception path and thus, we don't know the content of + * sscratch. + */ + csrrw s4, CSR_SSCRATCH, x0 + + mv a0, a7 + mv a2, s5 + + call do_sse + + /* Leave no reference to the event stack in the interrupted task. */ + REG_S s7, TASK_TI_USER_SP(tp) + REG_S s6, TASK_TI_KERNEL_SP(tp) + + csrw CSR_SSCRATCH, s4 + ALTERNATIVE("nop", "csrw hstatus, s5", 0, RISCV_ISA_EXT_H, 1) + csrw CSR_STVEC, s3 + + REG_L a0, PT_STATUS(sp) + REG_L a1, PT_EPC(sp) + REG_L a2, PT_BADADDR(sp) + REG_L a3, PT_CAUSE(sp) + csrw CSR_SSTATUS, a0 + csrw CSR_EPC, a1 + csrw CSR_STVAL, a2 + csrw CSR_SCAUSE, a3 + + REG_L ra, PT_RA(sp) + REG_L s0, PT_S0(sp) + REG_L s1, PT_S1(sp) + REG_L s2, PT_S2(sp) + REG_L s3, PT_S3(sp) + REG_L s4, PT_S4(sp) + REG_L s5, PT_S5(sp) + REG_L s6, PT_S6(sp) + REG_L s7, PT_S7(sp) + REG_L s8, PT_S8(sp) + REG_L s9, PT_S9(sp) + REG_L s10, PT_S10(sp) + REG_L s11, PT_S11(sp) + REG_L tp, PT_TP(sp) + REG_L t0, PT_T0(sp) + REG_L t1, PT_T1(sp) + REG_L t2, PT_T2(sp) + REG_L t3, PT_T3(sp) + REG_L t4, PT_T4(sp) + REG_L t5, PT_T5(sp) + REG_L t6, PT_T6(sp) + REG_L gp, PT_GP(sp) + REG_L a0, PT_A0(sp) + REG_L a1, PT_A1(sp) + REG_L a2, PT_A2(sp) + REG_L a3, PT_A3(sp) + REG_L a4, PT_A4(sp) + REG_L a5, PT_A5(sp) + + REG_L sp, PT_SP(sp) + + li a7, SBI_EXT_SSE + li a6, SBI_SSE_EVENT_COMPLETE + ecall + + /* + * COMPLETE must resume the interrupted context and never return. Trap + * through the normal vector instead of falling into adjacent assembly. + */ + la t0, handle_exception + csrw CSR_STVEC, t0 + ebreak + /* The fatal trap must not return; execution should never reach here. */ + +#ifdef CONFIG_SMP +.Lfind_hart_id_slowpath: + + /* Restore current task struct from __sbi_sse_entry_task */ + li t1, ASM_NR_CPUS + /* Slowpath to find the CPU id associated to the hart id */ + la t0, __cpuid_to_hartid_map + li t3, 0 + +.Lhart_id_loop: + REG_L t2, 0(t0) + beq t2, a6, .Lcpu_id_found + + /* Increment pointer and CPU number */ + addi t3, t3, 1 + addi t0, t0, RISCV_SZPTR + bltu t3, t1, .Lhart_id_loop + + /* + * This should never happen since we expect the hart_id to match one + * of our CPU, but better be safe than sorry + */ + la tp, init_task + la a0, sse_hart_id_panic_string + la t0, panic + jalr t0 +#endif + +SYM_CODE_END(handle_sse) +ASM_NOKPROBE(handle_sse) + +SYM_DATA_START_LOCAL(sse_hart_id_panic_string) + .ascii "Unable to match hart_id with cpu\0" +SYM_DATA_END(sse_hart_id_panic_string)Signature · 1 line
2.50.1 (Apple Git-155)
Re: [PATCH v10 RESEND 2/9] riscv: add support for SBI Supervisor Software Events extension
Hi Himanshu,
Quoted 65 lines · Himanshu Chauhan
Hi Zhanpeng,
Quoted 62 lines · Zhanpeng Zhang
From: Clément Léger <[email protected]>
The SBI SSE extension allows firmware to notify supervisor software of events that must be delivered independently of normal S-mode interrupts. Firmware saves the minimal state required to enter the supervisor handler, and Linux builds the synthetic handler context around it.
SSE can arrive while Linux is already in an exception entry path. At that point sscratch and tp may be in the middle of the normal trap-entry exchange, so they cannot always identify current. Store current in a per-CPU slot and use the hart ID passed by firmware to recover it.
Give each event, including each CPU instance of a local event, a dedicated stack and shadow call stack. Synchronize vmapped stack ranges before unmasking events so that the handler cannot take a vmalloc fault while running in an NMI-like context.
The handler is a synthetic supervisor episode, but completion must resume the context interrupted by the SSE. Preserve stvec and, when the hypervisor extension is present, hstatus across the handler. Read the interrupted a6 and a7 values from the SSE attributes, construct
pt_regsfor the interrupted context, and write back any changes made by the handler.Nested exceptions on the SSE event stack temporarily replace both
TASK_TI_KERNEL_SPandTASK_TI_USER_SP. Preserve their original values across the handler and restore them before completing the event, so a nested exception cannot leave the interrupted task referring to the event stack.Keep an explicit
EVENT_REGISTERnot-supported result distinct from other firmware failures. This lets clients select another delivery mechanism only when firmware has positively rejected the requested event.Signed-off-by Clément Léger <[email protected]>Co-developed-by Himanshu Chauhan <[email protected]>Signed-off-by Himanshu Chauhan <[email protected]>Co-developed-by Zhanpeng Zhang <[email protected]>Signed-off-by Zhanpeng Zhang <[email protected]>--- MAINTAINERS | 12 ++ arch/riscv/include/asm/asm.h | 14 +- arch/riscv/include/asm/scs.h | 7 + arch/riscv/include/asm/sse.h | 82 +++++++++ arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/Makefile | 1 + arch/riscv/kernel/asm-offsets.c | 14 ++ arch/riscv/kernel/entry.S | 14 ++ arch/riscv/kernel/sbi_sse.c | 246 +++++++++++++++++++++++++++ arch/riscv/kernel/sbi_sse_entry.S | 226 ++++++++++++++++++++++++ 10 files changed, 614 insertions(+), 3 deletions(-)create mode 100644
arch/riscv/include/asm/sse.hcreate mode 100644arch/riscv/kernel/sbi_sse.ccreate mode 100644arch/riscv/kernel/sbi_sse_entry.SMAINTAINERS +0
-0@@ -23595,6 +23595,18 @@ F: arch/riscv/boot/dts/spacemit/ N: spacemit K: spacemit
Quoted 14 lines
MAINTAINERS F: arch/riscv/boot/dts/spacemit/ · line 23609
Quoted 12 lines
MAINTAINERS +12
-0+RISC-V SUPERVISOR SOFTWARE EVENTS +M: Zhanpeng Zhang <[email protected]> +M: Himanshu Chauhan <[email protected]> +R: Yunhui Cui <[email protected]> +L: [email protected] +S: Maintained +F: arch/riscv/include/asm/sse.h +F: arch/riscv/kernel/sbi_sse.c +F: arch/riscv/kernel/sbi_sse_entry.S +F: drivers/firmware/riscv/riscv_sbi_sse.c +F: include/linux/riscv_sbi_sse.h +I would suggest that you make changes in maintainers as a separate patch.
Agreed. I'll move the MAINTAINERS changes into a separate patch in v11.
Quoted 430 lines
Quoted 430 lines
MAINTAINERS +0
-0RISC-V TENSTORRENT SoC SUPPORT M: Drew Fustini <[email protected]> M: Joel Stanley <[email protected]>arch/riscv/include/asm/asm.h +11
-3@@ -91,16 +91,24 @@ .endm#ifdef CONFIG_SMP -.macro asm_per_cpu dst sym tmp - lw \tmp, TASK_TI_CPU_NUM(tp) - slli \tmp, \tmp, RISCV_LGPTR +.macro asm_per_cpu_with_cpu dst sym tmp cpu + slli \tmp, \cpu, RISCV_LGPTR la \dst, __per_cpu_offset add \dst, \dst, \tmp REG_L \tmp, 0(\dst) la \dst, \sym add \dst, \dst, \tmp .endm + +.macro asm_per_cpu dst sym tmp + lw \tmp, TASK_TI_CPU_NUM(tp) + asm_per_cpu_with_cpu \dst \sym \tmp \tmp +.endm #else /* CONFIG_SMP */ +.macro asm_per_cpu_with_cpu dst sym tmp cpu + la \dst, \sym +.endm + .macro asm_per_cpu dst sym tmp la \dst, \sym .endmarch/riscv/include/asm/scs.h +7
-0@@ -17,6 +17,11 @@ load_per_cpu gp, irq_shadow_call_stack_ptr, \tmp .endm +/* Load the per-CPU IRQ shadow call stack to gp. */ +.macro scs_load_sse_stack reg_evt + REG_L gp, SSE_REG_EVT_SHADOW_STACK(\reg_evt) +.endm + /* Load task_scs_sp(current) to gp. */ .macro scs_load_current REG_L gp, TASK_TI_SCS_SP(tp)@@ -40,6 +45,8 @@ .endm .macro scs_load_irq_stack tmp .endm +.macro scs_load_sse_stack reg_evt +.endm .macro scs_load_current .endm .macro scs_load_current_if_task_changed prevarch/riscv/include/asm/sse.h new file +82
-0@@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Copyright (C) 2024 Rivos Inc. +*/ +#ifndef __ASM_SSE_H +#define __ASM_SSE_H + +#include <linux/printk.h> +#include <linux/types.h> + +#include <asm/sbi.h> + +static inline bool riscv_sse_available (void ) +{ +#ifdef CONFIG_RISCV_SBI +return sbi_probe_extension (SBI_EXT_SSE ) >0 ; +#else +return false; +#endif +} + +static inline void riscv_sse_mask_current_hart (void ) +{ +#ifdef CONFIG_RISCV_SBI +struct sbiret ret; + +if (!riscv_sse_available ()) +return ; + + ret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_HART_MASK ,0 ,0 ,0 ,0 ,0 ,0 ); +if (ret.error && ret.error !=SBI_ERR_ALREADY_STOPPED ) +pr_emerg ("SSE hart mask failed: %ld\n" , ret.error); +#endif +} + +#ifdef CONFIG_RISCV_SBI_SSE + +struct sse_event_interrupted_state { +unsigned long a6; +unsigned long a7; +}; + +struct sse_event_arch_data { +void *stack; +void *shadow_stack; +unsigned long tmp; +struct sse_event_interrupted_state *interrupted; +phys_addr_t interrupted_phys; +u32 evt_id; +unsigned long hart_id; +unsigned int cpu_id; +}; + +struct riscv_sse_interrupted_context { +struct pt_regs *regs; +unsigned long hstatus; +}; + +static inline bool sse_event_is_global (u32 evt) +{ +return !!(evt &SBI_SSE_EVENT_GLOBAL ); +} + +void arch_sse_event_update_cpu (struct sse_event_arch_data *arch_evt,int cpu); +int arch_sse_init_event (struct sse_event_arch_data *arch_evt,u32 evt_id, +int cpu); +void arch_sse_free_event (struct sse_event_arch_data *arch_evt); +int arch_sse_register_event (struct sse_event_arch_data *arch_evt); +void arch_sse_init_cpu (void ); + +void sse_handle_event (struct sse_event_arch_data *arch_evt, +struct pt_regs *regs); +asmlinkage void handle_sse(void); +asmlinkage void noinstr do_sse(struct sse_event_arch_data *arch_evt, +struct pt_regs *regs,unsigned long hstatus); + +const struct riscv_sse_interrupted_context * +riscv_sse_get_interrupted_context (void ); + +#endif + +#endif arch/riscv/include/asm/thread_info.h +1
-0@@ -36,6 +36,7 @@#define OVERFLOW_STACK_SIZE SZ_4K#define IRQ_STACK_SIZE THREAD_SIZE +#define SSE_STACK_SIZE THREAD_SIZE#ifndef __ASSEMBLER__arch/riscv/kernel/Makefile +1
-0@@ -101,6 +101,7 @@ obj-$(CONFIG_DYNAMIC_FTRACE) += mcount-dyn.o obj-$(CONFIG_PERF_EVENTS) += perf_callchain.o obj-$(CONFIG_HAVE_PERF_REGS) += perf_regs.o obj-$(CONFIG_RISCV_SBI) += sbi.o sbi_ecall.o +obj-$(CONFIG_RISCV_SBI_SSE) += sbi_sse.o sbi_sse_entry.o ifeq ($(CONFIG_RISCV_SBI), y) obj-$(CONFIG_SMP) += sbi-ipi.o obj-$(CONFIG_SMP) += cpu_ops_sbi.oarch/riscv/kernel/asm-offsets.c +14
-0@@ -15,6 +15,8 @@#include <asm/ptrace.h> #include <asm/cpu_ops_sbi.h> #include <asm/stacktrace.h> +#include <asm/sbi.h> +#include <asm/sse.h> #include <asm/suspend.h> void asm_offsets (void );@@ -533,6 +535,18 @@ void asm_offsets(void)DEFINE (FREGS_A6 , offsetof(struct __arch_ftrace_regs , a6));DEFINE (FREGS_A7 , offsetof(struct __arch_ftrace_regs , a7));#endif + +#ifdef CONFIG_RISCV_SBI_SSE +OFFSET (SSE_REG_EVT_STACK , sse_event_arch_data, stack); +OFFSET (SSE_REG_EVT_SHADOW_STACK , sse_event_arch_data, shadow_stack); +OFFSET (SSE_REG_EVT_TMP , sse_event_arch_data, tmp); +OFFSET (SSE_REG_HART_ID , sse_event_arch_data, hart_id); +OFFSET (SSE_REG_CPU_ID , sse_event_arch_data, cpu_id); + +DEFINE (SBI_EXT_SSE ,SBI_EXT_SSE ); +DEFINE (SBI_SSE_EVENT_COMPLETE ,SBI_SSE_EVENT_COMPLETE ); +DEFINE (ASM_NR_CPUS ,CONFIG_NR_CPUS ); +#endif #ifdef CONFIG_RISCV_SBI DEFINE (SBI_EXT_FWFT ,SBI_EXT_FWFT );DEFINE (SBI_EXT_FWFT_SET ,SBI_EXT_FWFT_SET );arch/riscv/kernel/entry.S +14
-0@@ -424,6 +424,15 @@ SYM_FUNC_END(call_on_irq_stack) * arguments are passed to schedule_tail. */ SYM_FUNC_START(__switch_to) +#ifdef CONFIG_RISCV_SBI_SSE + /* + * Mark the interval where tp changes from prev to next. SSE entry uses + * the interrupted tp while this per-CPU pointer is NULL. + */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S zero, 0(t0) +#endif + /* Save context into prev->thread */ li a4, TASK_THREAD_RA add a3, a0, a4@@ -470,6 +479,11 @@ SYM_FUNC_START(__switch_to) REG_L s11, TASK_THREAD_S11_RA(a4) /* The offset of thread_info in task_struct is zero. */ move tp, a1 +#ifdef CONFIG_RISCV_SBI_SSE + /* Publish next only after tp contains its task_struct pointer. */ + asm_per_cpu t0, __sbi_sse_entry_task, t1 + REG_S tp, 0(t0) +#endif /* Switch to the next shadow call stack */ scs_load_current retarch/riscv/kernel/sbi_sse.c new file +188
-0@@ -0,0 +1,246 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* Copyright (C) 2025 Rivos Inc. +*/ +#include <linux/nmi.h> +#include <linux/sched.h> +#include <linux/scs.h> +#include <linux/bitfield.h> +#include <linux/percpu-defs.h> +#include <linux/string.h> + +#include <asm/asm-prototypes.h> +#include <asm/switch_to.h> +#include <asm/irq_stack.h> +#include <asm/sbi.h> +#include <asm/sse.h> +#include <asm/tlbflush.h> + +DEFINE_PER_CPU(struct task_struct *, __sbi_sse_entry_task); +static DEFINE_PER_CPU(struct riscv_sse_interrupted_context *, + riscv_sse_interrupted_context); + +const struct riscv_sse_interrupted_context * +riscv_sse_get_interrupted_context (void ) +{ +return this_cpu_read (riscv_sse_interrupted_context); +} + +void __weak sse_handle_event (struct sse_event_arch_data *arch_evt,struct pt_regs *regs) +{ +} + +void noinstr do_sse(struct sse_event_arch_data *arch_evt, +struct pt_regs *regs,unsigned long hstatus) +{ +struct riscv_sse_interrupted_context context = { regs, hstatus }; +struct riscv_sse_interrupted_context *previous; +struct sbiret sret; + +nmi_enter (); +instrumentation_begin (); + +/* Retrieve missing GPRs from SBI */ + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_ATTR_READ , arch_evt->evt_id, +SBI_SSE_ATTR_INTERRUPTED_A6 , + (SBI_SSE_ATTR_INTERRUPTED_A7 - +SBI_SSE_ATTR_INTERRUPTED_A6 ) +1 , + (unsigned long )arch_evt->interrupted_phys,0 ,0 ); +if (sret.error) { +pr_warn ("Failed to read interrupted registers for event %x: %ld\n" , + arch_evt->evt_id, sret.error); +/* Let the client quiesce its source without using incomplete regs. */ +sse_handle_event (arch_evt,NULL ); + goto out; + } + +memcpy (®s->a6, arch_evt->interrupted, +sizeof (*arch_evt->interrupted)); + +/* Make the interrupted frame visible while clients handle this event. */ + previous =this_cpu_read (riscv_sse_interrupted_context); +this_cpu_write (riscv_sse_interrupted_context, &context); +sse_handle_event (arch_evt, regs); +this_cpu_write (riscv_sse_interrupted_context, previous); + +if (memcmp (®s->a6, arch_evt->interrupted, +sizeof (*arch_evt->interrupted))) { +memcpy (arch_evt->interrupted, ®s->a6, +sizeof (*arch_evt->interrupted)); + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_ATTR_WRITE , + arch_evt->evt_id,SBI_SSE_ATTR_INTERRUPTED_A6 , + (SBI_SSE_ATTR_INTERRUPTED_A7 - +SBI_SSE_ATTR_INTERRUPTED_A6 ) +1 , + (unsigned long )arch_evt->interrupted_phys,0 ,0 ); +/* +* If writeback fails, COMPLETE resumes with firmware's original +* a6/a7 rather than treating the shared buffer as committed. +*/ +if (sret.error) +pr_warn ("Failed to write interrupted registers for event %x: %ld\n" , + arch_evt->evt_id, sret.error); + } + +out: +instrumentation_end (); +nmi_exit (); +} + +static void *alloc_to_stack_pointer (void *alloc) +{ +return alloc ? alloc +SSE_STACK_SIZE :NULL ; +} + +static void *stack_pointer_to_alloc (void *stack) +{ +return stack ? stack -SSE_STACK_SIZE :NULL ; +} + +static void arch_sse_flush_tlb_range (struct sse_event_arch_data *arch_evt, +unsigned long start,unsigned long size) +{ +unsigned long end = start + size; + +if (sse_event_is_global (arch_evt->evt_id)) +flush_tlb_kernel_range (start, end); +else +local_flush_tlb_kernel_range (start, end); +} + +static void arch_sse_shadow_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +#ifdef CONFIG_SHADOW_CALL_STACK +if (arch_evt->shadow_stack) +arch_sse_flush_tlb_range (arch_evt, + (unsigned long )arch_evt->shadow_stack, +SCS_SIZE ); +#endif +} + +#ifdef CONFIG_VMAP_STACK +static void *sse_stack_alloc (unsigned int cpu) +{ +void *stack =arch_alloc_vmap_stack (SSE_STACK_SIZE ,cpu_to_node (cpu)); + +return alloc_to_stack_pointer (stack); +} + +static void sse_stack_free (void *stack) +{ +vfree (stack_pointer_to_alloc (stack)); +} + +static void arch_sse_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +void *p_stack = arch_evt->stack; +unsigned long stack = (unsigned long )stack_pointer_to_alloc (p_stack); + +/* +* Flush the tlb to avoid taking any exception when accessing the +* vmapped stack inside the SSE handler +*/ +arch_sse_flush_tlb_range (arch_evt, stack,SSE_STACK_SIZE ); + +arch_sse_shadow_stack_cpu_sync (arch_evt); +} +#else /* CONFIG_VMAP_STACK */ +static void *sse_stack_alloc (unsigned int cpu) +{ +void *stack =kmalloc (SSE_STACK_SIZE ,GFP_KERNEL ); + +return alloc_to_stack_pointer (stack); +} + +static void sse_stack_free (void *stack) +{ +kfree (stack_pointer_to_alloc (stack)); +} + +static void arch_sse_stack_cpu_sync (struct sse_event_arch_data *arch_evt) +{ +arch_sse_shadow_stack_cpu_sync (arch_evt); +} +#endif /* CONFIG_VMAP_STACK */ + +static int sse_init_scs (int cpu,struct sse_event_arch_data *arch_evt) +{ +void *stack; + +if (!scs_is_enabled ()) +return 0 ; + + stack =scs_alloc (cpu_to_node (cpu)); +if (!stack) +return -ENOMEM ; + + arch_evt->shadow_stack = stack; + +return 0 ; +} + +void arch_sse_event_update_cpu (struct sse_event_arch_data *arch_evt,int cpu) +{ + arch_evt->cpu_id = cpu; + arch_evt->hart_id =cpuid_to_hartid_map (cpu); +} + +void arch_sse_init_cpu (void ) +{
Quoted 9 lines
arch/riscv/kernel/sbi_sse.c line 191
Quoted 3 lines
arch/riscv/kernel/sbi_sse.c new file +3
-0+__this_cpu_write (__sbi_sse_entry_task, current); +} +This is called from
sse_cpu_online()in the cpuhp callback, which runs preemptible, and the boot CPU instance runs from an initcall. WithDEBUG_PREEMPTyou can get a__this_cpu_write()in preemptible warning. Can you check? Moreover, if the task migrates between computing the per-CPU address and the store, the wrong CPU's slot is written. I would suggest usethis_cpu_write()underpreempt_disable().
Agreed. The existing preemption guards do not cover arch_sse_init_cpu(). I'll add preemption protection around the per-CPU update.
Quoted 160 lines
Quoted 148 lines
arch/riscv/kernel/sbi_sse.c new file +55
-0+int arch_sse_init_event (struct sse_event_arch_data *arch_evt,u32 evt_id, +int cpu) +{ +void *stack; + + arch_evt->interrupted =kmalloc_obj (*arch_evt->interrupted,GFP_KERNEL ); +if (!arch_evt->interrupted) +return -ENOMEM ; + + arch_evt->evt_id = evt_id; + stack =sse_stack_alloc (cpu); +if (!stack) + goto err_free_interrupted; + + arch_evt->stack = stack; + +if (sse_init_scs (cpu, arch_evt)) { +sse_stack_free (arch_evt->stack); + goto err_free_interrupted; + } + +/* kmalloc keeps the two adjacent SBI attribute words contiguous. */ + arch_evt->interrupted_phys =virt_to_phys (arch_evt->interrupted); + +arch_sse_event_update_cpu (arch_evt, cpu); + +return 0 ; + +err_free_interrupted: +kfree (arch_evt->interrupted); + arch_evt->interrupted =NULL ; +return -ENOMEM ; +} + +void arch_sse_free_event (struct sse_event_arch_data *arch_evt) +{ +scs_free (arch_evt->shadow_stack); +sse_stack_free (arch_evt->stack); +kfree (arch_evt->interrupted); +} + +int arch_sse_register_event (struct sse_event_arch_data *arch_evt) +{ +struct sbiret sret; + +arch_sse_stack_cpu_sync (arch_evt); + + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_REGISTER , arch_evt->evt_id, + (unsigned long )handle_sse, (unsigned long )arch_evt,0 , +0 ,0 ); +if (sret.error ==SBI_ERR_NOT_SUPPORTED ) +return -EOPNOTSUPP ; + +return sbi_err_map_linux_errno (sret.error); +}arch/riscv/kernel/sbi_sse_entry.S new file +87
-0@@ -0,0 +1,226 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Copyright (C) 2025 Rivos Inc. + */ + +#include <linux/init.h> +#include <linux/linkage.h> + +#include <asm/alternative-macros.h> +#include <asm/asm.h> +#include <asm/csr.h> +#include <asm/hwcap.h> +#include <asm/scs.h> + +/* When entering handle_sse, the following registers are set: + * a6: contains the hartid + * a7: contains a sse_event_arch_data struct pointer + */ +SYM_CODE_START(handle_sse) + /* Save stack temporarily */ + REG_S sp, SSE_REG_EVT_TMP(a7) + /* Set entry stack */ + REG_L sp, SSE_REG_EVT_STACK(a7) + + addi sp, sp, -(PT_SIZE_ON_STACK) + REG_S ra, PT_RA(sp) + REG_S s0, PT_S0(sp) + REG_S s1, PT_S1(sp) + REG_S s2, PT_S2(sp) + REG_S s3, PT_S3(sp) + REG_S s4, PT_S4(sp) + REG_S s5, PT_S5(sp) + REG_S s6, PT_S6(sp) + REG_S s7, PT_S7(sp) + REG_S s8, PT_S8(sp) + REG_S s9, PT_S9(sp) + REG_S s10, PT_S10(sp) + REG_S s11, PT_S11(sp) + REG_S tp, PT_TP(sp) + REG_S t0, PT_T0(sp) + REG_S t1, PT_T1(sp) + REG_S t2, PT_T2(sp) + REG_S t3, PT_T3(sp) + REG_S t4, PT_T4(sp) + REG_S t5, PT_T5(sp) + REG_S t6, PT_T6(sp) + REG_S gp, PT_GP(sp) + REG_S a0, PT_A0(sp) + REG_S a1, PT_A1(sp) + REG_S a2, PT_A2(sp) + REG_S a3, PT_A3(sp) + REG_S a4, PT_A4(sp) + REG_S a5, PT_A5(sp) + + /* Retrieve entry sp */ + REG_L a4, SSE_REG_EVT_TMP(a7) + /* Save CSRs */ + csrr a0, CSR_EPC + csrr a1, CSR_SSTATUS + csrr a2, CSR_STVAL + csrr a3, CSR_SCAUSE + + REG_S a0, PT_EPC(sp) + REG_S a1, PT_STATUS(sp) + REG_S a2, PT_BADADDR(sp) + REG_S a3, PT_CAUSE(sp) + REG_S a4, PT_SP(sp) + + /* Disable user memory access and floating/vector computing */ + li t0, SR_SUM | SR_FS_VS + csrc CSR_STATUS, t0 + + load_global_pointer + scs_load_sse_stack a7 + +#ifdef CONFIG_SMP + REG_L t4, SSE_REG_HART_ID(a7) + lw t3, SSE_REG_CPU_ID(a7) + + bne t4, a6, .Lfind_hart_id_slowpath + +.Lcpu_id_found: +#else + mv t3, zero +#endif + + asm_per_cpu_with_cpu t2 __sbi_sse_entry_task t1 t3arch/riscv/kernel/sbi_sse_entry.S line 97
Quoted 10 lines
arch/riscv/kernel/sbi_sse_entry.S new file +10
-0+ REG_L tp, 0(t2) + bnez tp, .Lcurrent_task_found + + /* __switch_to() marks its transition window with a NULL entry task. */ + REG_L tp, PT_TP(sp) + +.Lcurrent_task_found: + /* Nested exceptions temporarily replace these with the SSE stack. */ + REG_L s6, TASK_TI_KERNEL_SP(tp) + REG_L s7, TASK_TI_USER_SP(tp)Only
KERNEL_SPandUSER_SPare preserved. handle_exception'snew_valid_map_cpus_checkmacro
Quoted 8 lines
parks a0/a1/a2 in TASK_TI_A0/A1/A2(tp) and reloads them a few instructions later, for any page fault on a kernel address on 64-bit MMU. If an SSE arrives inside that window and the handler takes a vmalloc/kfence fault of its own, the nested
handle_exceptionruns the same macro on the same tp and overwrites those three slots. When the SSE completes, the interrupted macro reloads a0/a1/a2 with the handler's values and they end up in the saved context, i.e. a corrupted syscall argument / user a0-a2. The window is small, but "nested exceptions are transparent" is then false. Please save and restore those three slots the same way as s6/s7.
Good catch! I independently noticed this omission as well and have added save/restore of TASK_TI_A0/A1/A2 in my local v11 tree, using s8–s10, which are already saved in the SSE register frame.
Quoted 3 lines
I am wondering if this is the reason for the "repeated nested faults corrupt the interrupted context" that your 6/9 patch refers to;
It could explain context corruption in that window, but I cannot yet confirm that it caused the earlier crashes. I'm still testing this and will avoid attributing those failures to this omission without further evidence. The fix belongs in the SSE entry code, as you pointed out.
Quoted 3 lines
if so it should be fixed here, not worked around in perf. Check if its indeed true.
Sure, as mentioned in the resend cover letter, the perf GUP approach was an interim workaround. v11 will replace it with an x86 way:
pagefault-disabled inatomic copy using exception-table fixup.
Quoted 124 lines
Quoted 124 lines
arch/riscv/kernel/sbi_sse_entry.S new file +124
-0+ + mv a1, sp /* pt_regs on stack */ + + /* + * Run the SSE handler with the normal exception vector, but restore the + * interrupted stvec before completing the event. SSE can arrive while + * the kernel is using a temporary trap vector in a sensitive entry path. + */ + csrr s3, CSR_STVEC + la t0, handle_exception + csrw CSR_STVEC, t0 + + /* + * Preserve the full HS-mode virtualization state across the handler. + * hstatus is live supervisor state rather than an SSE interrupted + * attribute, and OpenSBI consumes hstatus.SPV during event completion. + * Saving the whole CSR keeps the handler episode transparent to KVM and + * avoids having to infer which hstatus bits may matter to a guest resume. + */ + li s5, 0 + ALTERNATIVE("nop", "csrr s5, hstatus", 0, RISCV_ISA_EXT_H, 1) + + /* + * Save sscratch for restoration since we might have interrupted the + * kernel in early exception path and thus, we don't know the content of + * sscratch. + */ + csrrw s4, CSR_SSCRATCH, x0 + + mv a0, a7 + mv a2, s5 + + call do_sse + + /* Leave no reference to the event stack in the interrupted task. */ + REG_S s7, TASK_TI_USER_SP(tp) + REG_S s6, TASK_TI_KERNEL_SP(tp) + + csrw CSR_SSCRATCH, s4 + ALTERNATIVE("nop", "csrw hstatus, s5", 0, RISCV_ISA_EXT_H, 1) + csrw CSR_STVEC, s3 + + REG_L a0, PT_STATUS(sp) + REG_L a1, PT_EPC(sp) + REG_L a2, PT_BADADDR(sp) + REG_L a3, PT_CAUSE(sp) + csrw CSR_SSTATUS, a0 + csrw CSR_EPC, a1 + csrw CSR_STVAL, a2 + csrw CSR_SCAUSE, a3 + + REG_L ra, PT_RA(sp) + REG_L s0, PT_S0(sp) + REG_L s1, PT_S1(sp) + REG_L s2, PT_S2(sp) + REG_L s3, PT_S3(sp) + REG_L s4, PT_S4(sp) + REG_L s5, PT_S5(sp) + REG_L s6, PT_S6(sp) + REG_L s7, PT_S7(sp) + REG_L s8, PT_S8(sp) + REG_L s9, PT_S9(sp) + REG_L s10, PT_S10(sp) + REG_L s11, PT_S11(sp) + REG_L tp, PT_TP(sp) + REG_L t0, PT_T0(sp) + REG_L t1, PT_T1(sp) + REG_L t2, PT_T2(sp) + REG_L t3, PT_T3(sp) + REG_L t4, PT_T4(sp) + REG_L t5, PT_T5(sp) + REG_L t6, PT_T6(sp) + REG_L gp, PT_GP(sp) + REG_L a0, PT_A0(sp) + REG_L a1, PT_A1(sp) + REG_L a2, PT_A2(sp) + REG_L a3, PT_A3(sp) + REG_L a4, PT_A4(sp) + REG_L a5, PT_A5(sp) + + REG_L sp, PT_SP(sp) + + li a7, SBI_EXT_SSE + li a6, SBI_SSE_EVENT_COMPLETE + ecall + + /* + * COMPLETE must resume the interrupted context and never return. Trap + * through the normal vector instead of falling into adjacent assembly. + */ + la t0, handle_exception + csrw CSR_STVEC, t0 + ebreak + /* The fatal trap must not return; execution should never reach here. */ + +#ifdef CONFIG_SMP +.Lfind_hart_id_slowpath: + + /* Restore current task struct from __sbi_sse_entry_task */ + li t1, ASM_NR_CPUS + /* Slowpath to find the CPU id associated to the hart id */ + la t0, __cpuid_to_hartid_map + li t3, 0 + +.Lhart_id_loop: + REG_L t2, 0(t0) + beq t2, a6, .Lcpu_id_found + + /* Increment pointer and CPU number */ + addi t3, t3, 1 + addi t0, t0, RISCV_SZPTR + bltu t3, t1, .Lhart_id_loop + + /* + * This should never happen since we expect the hart_id to match one + * of our CPU, but better be safe than sorry + */ + la tp, init_task + la a0, sse_hart_id_panic_string + la t0, panic + jalr t0 +#endif + +SYM_CODE_END(handle_sse)
Quoted 8 lines
Quoted 8 lines
arch/riscv/kernel/sbi_sse_entry.S new file +5
-1+ASM_NOKPROBE(handle_sse) + +SYM_DATA_START_LOCAL(sse_hart_id_panic_string) + .ascii "Unable to match hart_id with cpu\0" +SYM_DATA_END(sse_hart_id_panic_string) --2.50.1 (Apple Git-155)
Thanks again for your detailed review!
Regards,
Zhanpeng
PATCH RESEND v10 3/9 riscv: sse: mask events during shutdown and kexec
In reply to Zhanpeng ZhangSSE delivery is independent of normal S-mode interrupts. Firmware may also retain an event registration until Linux explicitly unregisters it. A hart must therefore stop accepting SSE events before Linux stops servicing the registered handler.
Mask SSE on the local hart before panic stop, CPU stop, restart, poweroff, and crash shutdown paths. This prevents firmware from entering Linux-owned handler state after the corresponding CPU or kernel context is no longer valid.
A crash kernel cannot identify or take ownership of registrations inherited from the crashed kernel. Reject a later normal kexec while such SSE state may still exist, rather than transferring unknown firmware state to another kernel.
--- arch/riscv/kernel/machine_kexec.c | 11 +++++++++++ arch/riscv/kernel/reset.c | 18 ++++++++++++++++++ arch/riscv/kernel/smp.c | 17 +++++++++++++++++ 3 files changed, 46 insertions(+)
arch/riscv/kernel/machine_kexec.c +11 -0
@@ -14,10 +14,13 @@#include <asm/set_memory.h> /* For set_memory_x() */ #include <linux/compiler.h> /* For unreachable() */ #include <linux/cpu.h> /* For cpu_down() */ +#include <linux/crash_dump.h> #include <linux/reboot.h> #include <linux/interrupt.h> #include <linux/irq.h> +#include <asm/sse.h> +/* * machine_kexec_prepare - Initialize kexec *
@@ -36,6 +39,13 @@ machine_kexec_prepare(struct kimage *image)unsigned int control_code_buffer_sz =0 ;int i =0 ; +/* A crash kernel cannot tear down registrations inherited from firmware. */ +if (is_kdump_kernel () && image->type !=KEXEC_TYPE_CRASH && +riscv_sse_available ()) { +pr_err ("Normal kexec from a crash kernel is unsupported with SSE\n" ); +return -EOPNOTSUPP ; + } +/* Find the Flattened Device Tree and save its physical address */ for (i =0 ; i < image->nr_segments; i++) {if (image->segment[i].memsz <=sizeof (fdt))
@@ -127,6 +137,7 @@ void machine_crash_shutdown(struct pt_regs *regs) {local_irq_disable (); +riscv_sse_mask_current_hart ();/* shutdown non-crashing cpus */ crash_smp_send_stop ();
arch/riscv/kernel/reset.c +18 -0
@@ -6,6 +6,20 @@#include <linux/efi.h> #include <linux/reboot.h> #include <linux/pm.h> +#include <linux/smp.h> + +#include <asm/sse.h> + +#ifndef CONFIG_SMP +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +#endif static void __noreturn default_power_off (void ) {
@@ -18,6 +32,8 @@ EXPORT_SYMBOL(pm_power_off);void machine_restart (char *cmd) { +riscv_sse_mask_current_hart (); +/* * UpdateCapsule() depends on the system being reset via ResetSystem(). */
@@ -30,12 +46,14 @@ void machine_restart(char *cmd)void machine_halt (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }void machine_power_off (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }
arch/riscv/kernel/smp.c +17 -0
@@ -23,10 +23,13 @@#include <linux/irq.h> #include <linux/irq_work.h> #include <linux/nmi.h> +#include <linux/panic.h> #include <asm/tlbflush.h> #include <asm/cacheflush.h> #include <asm/cpu_ops.h> +#include <asm/sbi.h> +#include <asm/sse.h> enum ipi_message_type {IPI_RESCHEDULE ,
@@ -79,8 +82,18 @@ int riscv_hartid_to_cpuid(unsigned long hartid)return -ENOENT ; } +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +static void ipi_stop (void ) { +riscv_sse_mask_current_hart ();set_cpu_online (smp_processor_id (), false);while (1 )wait_for_interrupt ();
@@ -91,6 +104,7 @@ static atomic_t waiting_for_crash_ipi = ATOMIC_INIT(0);static inline void ipi_cpu_crash_stop (unsigned int cpu,struct pt_regs *regs) { +riscv_sse_mask_current_hart ();crash_save_cpu (regs, cpu);atomic_dec (&waiting_for_crash_ipi);
@@ -254,6 +268,8 @@ void smp_send_stop(void) {unsigned long timeout; +riscv_sse_mask_current_hart (); +if (num_online_cpus () >1 ) {cpumask_t mask;
@@ -301,6 +317,7 @@ void crash_smp_send_stop(void)return ; cpus_stopped =1 ; +riscv_sse_mask_current_hart ();/* * If this cpu is the only one alive at this point in time, online or
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 3/9] riscv: sse: mask events during shutdown and kexec
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] riscv: dead code in UP panic_smp_self_stop() misses early SSE mask --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] riscv: dead code in UP panic_smp_self_stop() misses early SSE mask --
commit 7602c0f047088ef36df958ced3408ede048d0ce9
Author: Zhanpeng Zhang <[email protected]>
riscv: sse: mask events during shutdown and kexec
This commit masks SSE events on the local hart before panic stop, CPU stop, restart, poweroff, and crash shutdown paths to prevent firmware from entering a Linux-owned handler state after the CPU or kernel context becomes invalid. It also rejects normal kexec from a crash kernel to avoid transferring unknown firmware state to the new kernel.
Quoted 12 lines
arch/riscv/kernel/reset.c +4
-0@@ -6,6 +6,20 @@#include <linux/efi.h> #include <linux/reboot.h> #include <linux/pm.h> +#include <linux/smp.h> + +#include <asm/sse.h> +
arch/riscv/kernel/reset.c line 22
Quoted 10 lines
arch/riscv/kernel/reset.c +10
-0+#ifndef CONFIG_SMP +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +#endif
[Severity: Low]
Is this panic_smp_self_stop() function reachable on UP systems?
When a kernel panic occurs on a UP system, the single CPU will always win the panic_try_start() race and proceed as the primary panicking CPU. The primary panicking CPU never calls panic_smp_self_stop().
Additionally, on UP systems, the smp_send_stop() and crash_smp_send_stop() functions are inline no-ops, so the primary CPU does not mask its own SSE early in the panic path. Although a follow-up patch (Patch 4) adds a panic notifier that eventually masks the SSE before the final infinite loop, the UP CPU remains unmasked during the early panic stages (such as stack trace dumping), and this added UP code appears to be entirely dead.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH v10 RESEND 3/9] riscv: sse: mask events during shutdown and kexec
In reply to Zhanpeng ZhangQuoted 166 lines · Zhanpeng Zhang
SSE delivery is independent of normal S-mode interrupts. Firmware may also retain an event registration until Linux explicitly unregisters it. A hart must therefore stop accepting SSE events before Linux stops servicing the registered handler.
Mask SSE on the local hart before panic stop, CPU stop, restart, poweroff, and crash shutdown paths. This prevents firmware from entering Linux-owned handler state after the corresponding CPU or kernel context is no longer valid.
A crash kernel cannot identify or take ownership of registrations inherited from the crashed kernel. Reject a later normal kexec while such SSE state may still exist, rather than transferring unknown firmware state to another kernel.
Signed-off-by Zhanpeng Zhang <[email protected]>--- arch/riscv/kernel/machine_kexec.c | 11 +++++++++++ arch/riscv/kernel/reset.c | 18 ++++++++++++++++++ arch/riscv/kernel/smp.c | 17 +++++++++++++++++ 3 files changed, 46 insertions(+)arch/riscv/kernel/machine_kexec.c +11
-0@@ -14,10 +14,13 @@#include <asm/set_memory.h> /* For set_memory_x() */ #include <linux/compiler.h> /* For unreachable() */ #include <linux/cpu.h> /* For cpu_down() */ +#include <linux/crash_dump.h> #include <linux/reboot.h> #include <linux/interrupt.h> #include <linux/irq.h> +#include <asm/sse.h> +/* * machine_kexec_prepare - Initialize kexec * @@ -36,6 +39,13 @@ machine_kexec_prepare(struct kimage *image)unsigned int control_code_buffer_sz =0 ;int i =0 ; +/* A crash kernel cannot tear down registrations inherited from firmware. */ +if (is_kdump_kernel () && image->type !=KEXEC_TYPE_CRASH && +riscv_sse_available ()) { +pr_err ("Normal kexec from a crash kernel is unsupported with SSE\n" ); +return -EOPNOTSUPP ; + } +/* Find the Flattened Device Tree and save its physical address */ for (i =0 ; i < image->nr_segments; i++) {if (image->segment[i].memsz <=sizeof (fdt))@@ -127,6 +137,7 @@ void machine_crash_shutdown(struct pt_regs *regs) {local_irq_disable (); +riscv_sse_mask_current_hart ();/* shutdown non-crashing cpus */ crash_smp_send_stop ();arch/riscv/kernel/reset.c +18
-0@@ -6,6 +6,20 @@#include <linux/efi.h> #include <linux/reboot.h> #include <linux/pm.h> +#include <linux/smp.h> + +#include <asm/sse.h> + +#ifndef CONFIG_SMP +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +#endif static void __noreturn default_power_off (void ) {@@ -18,6 +32,8 @@ EXPORT_SYMBOL(pm_power_off);void machine_restart (char *cmd) { +riscv_sse_mask_current_hart (); +/* * UpdateCapsule() depends on the system being reset via ResetSystem(). */ @@ -30,12 +46,14 @@ void machine_restart(char *cmd)void machine_halt (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }void machine_power_off (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }arch/riscv/kernel/smp.c +16
-0@@ -23,10 +23,13 @@#include <linux/irq.h> #include <linux/irq_work.h> #include <linux/nmi.h> +#include <linux/panic.h> #include <asm/tlbflush.h> #include <asm/cacheflush.h> #include <asm/cpu_ops.h> +#include <asm/sbi.h> +#include <asm/sse.h> enum ipi_message_type {IPI_RESCHEDULE ,@@ -79,8 +82,18 @@ int riscv_hartid_to_cpuid(unsigned long hartid)return -ENOENT ; } +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +static void ipi_stop (void ) { +riscv_sse_mask_current_hart ();set_cpu_online (smp_processor_id (), false);while (1 )wait_for_interrupt ();@@ -91,6 +104,7 @@ static atomic_t waiting_for_crash_ipi = ATOMIC_INIT(0);static inline void ipi_cpu_crash_stop (unsigned int cpu,struct pt_regs *regs) { +riscv_sse_mask_current_hart ();crash_save_cpu (regs, cpu);atomic_dec (&waiting_for_crash_ipi);@@ -254,6 +268,8 @@ void smp_send_stop(void) {unsigned long timeout; +riscv_sse_mask_current_hart (); +if (num_online_cpus () >1 ) {cpumask_t mask;
arch/riscv/kernel/smp.c void crash_smp_send_stop(void) · line 323
Quoted 7 lines
arch/riscv/kernel/smp.c +1
-0@@ -301,6 +317,7 @@ void crash_smp_send_stop(void)return ; cpus_stopped =1 ; +riscv_sse_mask_current_hart ();/* * If this cpu is the only one alive at this point in time, online or
Quoted 3 lines
Signature · 1 line
2.50.1 (Apple Git-155)
Re: [PATCH v10 RESEND 3/9] riscv: sse: mask events during shutdown and kexec
In reply to Zhanpeng ZhangQuoted 41 lines · Zhanpeng Zhang
SSE delivery is independent of normal S-mode interrupts. Firmware may also retain an event registration until Linux explicitly unregisters it. A hart must therefore stop accepting SSE events before Linux stops servicing the registered handler.
Mask SSE on the local hart before panic stop, CPU stop, restart, poweroff, and crash shutdown paths. This prevents firmware from entering Linux-owned handler state after the corresponding CPU or kernel context is no longer valid.
A crash kernel cannot identify or take ownership of registrations inherited from the crashed kernel. Reject a later normal kexec while such SSE state may still exist, rather than transferring unknown firmware state to another kernel.
Signed-off-by Zhanpeng Zhang <[email protected]>--- arch/riscv/kernel/machine_kexec.c | 11 +++++++++++ arch/riscv/kernel/reset.c | 18 ++++++++++++++++++ arch/riscv/kernel/smp.c | 17 +++++++++++++++++ 3 files changed, 46 insertions(+)arch/riscv/kernel/machine_kexec.c +3
-0@@ -14,10 +14,13 @@#include <asm/set_memory.h> /* For set_memory_x() */ #include <linux/compiler.h> /* For unreachable() */ #include <linux/cpu.h> /* For cpu_down() */ +#include <linux/crash_dump.h> #include <linux/reboot.h> #include <linux/interrupt.h> #include <linux/irq.h> +#include <asm/sse.h> +/* * machine_kexec_prepare - Initialize kexec *
arch/riscv/kernel/machine_kexec.c machine_kexec_prepare(struct kimage *image) · line 44
Quoted 6 lines
arch/riscv/kernel/machine_kexec.c +3
-0@@ -36,6 +39,13 @@ machine_kexec_prepare(struct kimage *image)unsigned int control_code_buffer_sz =0 ;int i =0 ; +/* A crash kernel cannot tear down registrations inherited from firmware. */ +if (is_kdump_kernel () && image->type !=KEXEC_TYPE_CRASH && +riscv_sse_available ()) {
I just realized. This rejects a normal kexec from any kdump kernel whenever firmware merely advertises SSE, regardless of CONFIG_RISCV_SBI_SSE or whether anything is registered. Can you check if its breaking kexec() with SSE just being advertised?
Also, there are some shasiko's comments worth addressing.
Quoted 21 lines
arch/riscv/kernel/machine_kexec.c +5
-0+pr_err ("Normal kexec from a crash kernel is unsupported with SSE\n" ); +return -EOPNOTSUPP ; + } +/* Find the Flattened Device Tree and save its physical address */ for (i =0 ; i < image->nr_segments; i++) {if (image->segment[i].memsz <=sizeof (fdt))@@ -127,6 +137,7 @@ void machine_crash_shutdown(struct pt_regs *regs) {local_irq_disable (); +riscv_sse_mask_current_hart ();/* shutdown non-crashing cpus */ crash_smp_send_stop ();arch/riscv/kernel/reset.c +0
-0@@ -6,6 +6,20 @@#include <linux/efi.h>
arch/riscv/kernel/reset.c line 16
Quoted 10 lines
arch/riscv/kernel/reset.c +8
-0#include <linux/reboot.h> #include <linux/pm.h> +#include <linux/smp.h> + +#include <asm/sse.h> + +#ifndef CONFIG_SMP +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart ();
This function call does SSE probe on every call. Wouldn't it be cheaper to do once?
Regards
Himanshu
Quoted 98 lines
arch/riscv/kernel/reset.c +10
-0+local_irq_disable (); + +for (;;) + cpu_relax(); +} +#endif static void __noreturn default_power_off (void ) {@@ -18,6 +32,8 @@ EXPORT_SYMBOL(pm_power_off);void machine_restart (char *cmd) { +riscv_sse_mask_current_hart (); +/* * UpdateCapsule() depends on the system being reset via ResetSystem(). */ @@ -30,12 +46,14 @@ void machine_restart(char *cmd)void machine_halt (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }void machine_power_off (void ) { +riscv_sse_mask_current_hart ();do_kernel_power_off ();default_power_off (); }arch/riscv/kernel/smp.c +17
-0@@ -23,10 +23,13 @@#include <linux/irq.h> #include <linux/irq_work.h> #include <linux/nmi.h> +#include <linux/panic.h> #include <asm/tlbflush.h> #include <asm/cacheflush.h> #include <asm/cpu_ops.h> +#include <asm/sbi.h> +#include <asm/sse.h> enum ipi_message_type {IPI_RESCHEDULE ,@@ -79,8 +82,18 @@ int riscv_hartid_to_cpuid(unsigned long hartid)return -ENOENT ; } +void __noreturn panic_smp_self_stop (void ) +{ +riscv_sse_mask_current_hart (); +local_irq_disable (); + +for (;;) +cpu_relax (); +} +static void ipi_stop (void ) { +riscv_sse_mask_current_hart ();set_cpu_online (smp_processor_id (), false);while (1 )wait_for_interrupt ();@@ -91,6 +104,7 @@ static atomic_t waiting_for_crash_ipi = ATOMIC_INIT(0);static inline void ipi_cpu_crash_stop (unsigned int cpu,struct pt_regs *regs) { +riscv_sse_mask_current_hart ();crash_save_cpu (regs, cpu);atomic_dec (&waiting_for_crash_ipi);@@ -254,6 +268,8 @@ void smp_send_stop(void) {unsigned long timeout; +riscv_sse_mask_current_hart (); +if (num_online_cpus () >1 ) {cpumask_t mask;@@ -301,6 +317,7 @@ void crash_smp_send_stop(void)return ; cpus_stopped =1 ; +riscv_sse_mask_current_hart ();/* * If this cpu is the only one alive at this point in time, online or Signature · 1 line
2.50.1 (Apple Git-155)
PATCH RESEND v10 4/9 drivers: firmware: add riscv SSE support
In reply to Zhanpeng ZhangFrom: Clément Léger <[email protected]>
Add a driver-level interface for RISC-V SSE. Linux clients can register handlers, select a target CPU for global events, and enable, disable or unregister events. The architecture entry wrapper completes an event after the registered handler returns. PMU and GHES drivers can use this interface.
Represent global events with one firmware registration and local events with one registration per possible CPU. Keep registration and enable state stable across CPU hotplug, and validate firmware-provided hart IDs before converting them to Linux CPU IDs. Use phys_addr_t for attribute buffers to match the physical addresses passed to firmware. Require MMU support because the current event-stack implementation relies on vmapped memory and TLB synchronization.
Serialize client list updates with the SSE mutex and the CPU read lock. Normal CPU hotplug callbacks provide the matching write-side exclusion, and CPUHP state removal holds the SSE mutex. These rules avoid holding an additional spinlock across firmware calls. Local event operations select a per-CPU registration, so require callers to remain on the current CPU and use lockdep assertions to verify that contract. Because CPU hotplug callbacks run in a preemptible thread, disable preemption around the local operations they perform on the offlining or onlining hart.
Propagate firmware failures from register, disable and unregister operations. Update Linux state only after successful firmware operations, and release an event only after all registrations are gone. Preserve the difference between SBI_ERR_NOT_SUPPORTED and a generic SBI failure so clients only select a fallback after firmware explicitly rejects an SSE operation.
If setup fails partway through a local event, roll back only the CPU instances changed by that invocation. Keep non-fallback errors across CPUs. This lets a client distinguish an event rejected as unsupported by every failing hart from an unknown firmware failure.
A failed registration rollback can leave firmware state without a client handle. Retain these events on a driver-owned cleanup list with a no-op handler. This lets CPU hotplug and shutdown retry cleanup without relying on client callback lifetime.
Mask SSE before CPU teardown. If a normal CPU-offline teardown fails after partially changing local events, reconstruct their requested registration and enable state. Unmask the hart, then return the original error to abort the offline operation. Shutdown and CPUHP state removal cannot fail, so record incomplete cleanup and refuse an unsafe normal kexec instead.
Close enable admission before reboot or kexec teardown. Protect the shutdown check and firmware enable operation with RCU, then drain existing enable calls before CPUHP removes registrations. This prevents a client from re-enabling an event between the teardown disable and unregister operations.
A crash kernel cannot identify registrations inherited from the crashed kernel. Leave SSE masked, report the retained firmware state separately from an unavailable extension, and do not let clients select a delivery path that may still be owned by the old kernel.
--- MAINTAINERS | 7 + drivers/firmware/Kconfig | 1 + drivers/firmware/Makefile | 1 + drivers/firmware/riscv/Kconfig | 18 + drivers/firmware/riscv/Makefile | 3 + drivers/firmware/riscv/riscv_sbi_sse.c | 1219 ++++++++++++++++++++++++ include/linux/cpuhotplug.h | 1 + include/linux/riscv_sbi_sse.h | 89 ++ 8 files changed, 1339 insertions(+) create mode 100644 drivers/firmware/riscv/Kconfig create mode 100644 drivers/firmware/riscv/Makefile create mode 100644 drivers/firmware/riscv/riscv_sbi_sse.c create mode 100644 include/linux/riscv_sbi_sse.h
MAINTAINERS +7 -0
@@ -23501,6 +23501,13 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/iommu/linux.git F: Documentation/devicetree/bindings/iommu/riscv,iommu.yaml F: drivers/iommu/riscv/ +RISC-V FIRMWARE DRIVERS +M: Conor Dooley <[email protected]> +L: [email protected] +S: Maintained +T: git git://git.kernel.org/pub/scm/linux/kernel/git/conor/linux.git +F: drivers/firmware/riscv/ + RISC-V MICROCHIP SUPPORT M: Conor Dooley <[email protected]> M: Daire McNamara <[email protected]>
drivers/firmware/Kconfig +1 -0
@@ -306,6 +306,7 @@ source "drivers/firmware/meson/Kconfig" source "drivers/firmware/microchip/Kconfig" source "drivers/firmware/psci/Kconfig" source "drivers/firmware/qcom/Kconfig" +source "drivers/firmware/riscv/Kconfig" source "drivers/firmware/samsung/Kconfig" source "drivers/firmware/smccc/Kconfig" source "drivers/firmware/tegra/Kconfig"
drivers/firmware/Makefile +1 -0
@@ -35,6 +35,7 @@ obj-y += efi/ obj-y += imx/ obj-y += psci/ obj-y += qcom/ +obj-y += riscv/ obj-y += samsung/ obj-y += smccc/ obj-y += tegra/
drivers/firmware/riscv/Kconfig new file +18 -0
@@ -0,0 +1,18 @@ +# SPDX-License-Identifier: GPL-2.0-only +menu "Risc-V Specific firmware drivers" +depends on RISCV + +config RISCV_SBI_SSE + bool "Enable SBI Supervisor Software Events support" + depends on RISCV_SBI && MMU && !HIBERNATION + default y + help + The Supervisor Software Events support allows the SBI to deliver + NMI-like notifications to the supervisor mode software. When enabled, + this option provides support to register callbacks on specific SSE + events. + + Hibernation is not supported because firmware registrations do not + survive restoring a kernel image. + +endmenu
drivers/firmware/riscv/Makefile new file +3 -0
@@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_RISCV_SBI_SSE) += riscv_sbi_sse.o
drivers/firmware/riscv/riscv_sbi_sse.c new file +1219 -0
1,219 lines not on this page · raw message
include/linux/cpuhotplug.h +1 -0
@@ -200,6 +200,7 @@ enum cpuhp_state {CPUHP_AP_ARM_MVEBU_SYNC_CLOCKS ,CPUHP_AP_ARM_CORESIGHT_ONLINE ,CPUHP_AP_X86_INTEL_EPB_ONLINE , +CPUHP_AP_RISCV_SSE_ONLINE ,CPUHP_AP_PERF_ONLINE ,CPUHP_AP_PERF_X86_ONLINE , CPUHP_AP_PERF_X86_UNCORE_ONLINE,
include/linux/riscv_sbi_sse.h new file +89 -0
89 lines not on this page · raw message
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 4/9] drivers: firmware: add riscv SSE support
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 15 lines
From: Clément Léger <[email protected]>
Add a driver-level interface for RISC-V SSE. Linux clients can register handlers, select a target CPU for global events, and enable, disable or unregister events. The architecture entry wrapper completes an event after the registered handler returns. PMU and GHES drivers can use this interface.
Represent global events with one firmware registration and local events with one registration per possible CPU. Keep registration and enable state stable across CPU hotplug, and validate firmware-provided hart IDs before converting them to Linux CPU IDs. Use
phys_addr_tfor attribute buffers to match the physical addresses passed to firmware. Require MMU support because the current event-stack implementation relies on vmapped memory and TLB synchronization.
Quoted 6 lines
[ ... ]Signed-off-by Clément Léger <[email protected]>Co-developed-by Himanshu Chauhan <[email protected]>Signed-off-by Himanshu Chauhan <[email protected]>Co-developed-by Zhanpeng Zhang <[email protected]>Signed-off-by Zhanpeng Zhang <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH RESEND v10 5/9 riscv: mm: avoid enabling interrupts for nofault page faults
In reply to Zhanpeng ZhangRISC-V enables interrupts in handle_page_fault() before checking whether the fault occurred with fault handling disabled. A nofault access from an atomic context can therefore run tracepoints and open an interrupt window before reaching the exception-table fixup.
Handle an exception-table entry before entering the generic fault path when fault handling is disabled. Also keep interrupts disabled until such a fault has been resolved.
This makes RISC-V consistent with the expectation that an in-atomic nofault access does not enter the normal fault-handling path. It also removes one source of re-entry when perf sampling is delivered through an SBI Supervisor Software Event (SSE).
--- arch/riscv/mm/fault.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
arch/riscv/mm/fault.c +9 -2
@@ -294,6 +294,13 @@ void handle_page_fault(struct pt_regs *regs)if (kprobe_page_fault (regs, cause))return ; +/* +* Nofault accesses must be resolved through the exception table before +* entering the generic fault path or enabling interrupts. +*/ +if (unlikely (faulthandler_disabled ()) &&fixup_exception (regs)) +return ; +if (user_mode (regs))trace_page_fault_user (addr, regs, cause);else
@@ -314,8 +321,8 @@ void handle_page_fault(struct pt_regs *regs)return ; } -/* Enable interrupts if they were enabled in the parent context. */ -if (!regs_irqs_disabled (regs)) +/* Do not open an interrupt window before a nofault fixup completes. */ +if (!regs_irqs_disabled (regs) && !faulthandler_disabled ())local_irq_enable ();/*
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 5/9] riscv: mm: avoid enabling interrupts for nofault page faults
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] riscv: mm: fixup_exception bypasses vmalloc_fault for nofault accesses --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] riscv: mm: fixup_exception bypasses vmalloc_fault for nofault accesses --
commit b959120cb7ee095dc7b5e388ec2110c0a78dd4ac
Author: Zhanpeng Zhang <[email protected]>
riscv: mm: avoid enabling interrupts for nofault page faults
This commit modifies the RISC-V page fault handler to resolve nofault accesses via the exception table before enabling interrupts or entering the generic fault path. It aims to prevent in-atomic nofault accesses from inadvertently running tracepoints or opening an interrupt window.
arch/riscv/mm/fault.c void handle_page_fault(struct pt_regs *regs) · line 302
Quoted 13 lines
arch/riscv/mm/fault.c +6
-0@@ -294,6 +294,13 @@ void handle_page_fault(struct pt_regs *regs)if (kprobe_page_fault (regs, cause))return ; +/* +* Nofault accesses must be resolved through the exception table before +* entering the generic fault path or enabling interrupts. +*/ +if (unlikely (faulthandler_disabled ()) &&fixup_exception (regs)) +return ;
[Severity: High]
Will this new check in handle_page_fault intercept faults on valid vmalloc addresses before vmalloc_fault has a chance to execute?
When tools like BPF or perf perform a legitimate nofault read (such as via copy_from_kernel_nofault) on a vmalloc address that has not yet been synchronized to the current task PGD, it triggers a page fault. Since faulthandler_disabled is true in a nofault context, it appears this new early check will call fixup_exception and immediately return.
On 32-bit RISC-V and !MMU configurations, this bypasses the lazy PGD synchronization performed a few lines further down:
if ((!IS_ENABLED(CONFIG_MMU) || !IS_ENABLED(CONFIG_64BIT)) &&
unlikely(addr >= VMALLOC_START && addr < VMALLOC_END)) {
vmalloc_fault(regs, code, addr);
return;
}Could this cause valid kernel vmalloc reads via nofault accessors to spuriously fail with -EFAULT?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
PATCH RESEND v10 6/9 perf: RISC-V: support callchains with SSE delivery
In reply to Zhanpeng ZhangPMU overflow delivery through SSE enters Linux with a synthetic supervisor context on a dedicated event stack. The perf unwinder must use the context interrupted by the overflow rather than treating the SSE handler frame as the sampled frame.
Use the interrupted pt_regs published by the RISC-V SSE entry path. Walk a kernel callchain only when the interrupted PC, SP, and frame pointer are consistent with the current task stack. For sensitive entry windows and IRQ stacks whose bounds cannot be proven, retain the interrupted PC without following an unsafe frame chain.
User callchains continue through the existing nofault RISC-V user unwinder. If hstatus.SPV says the interrupted context was a guest, do not interpret the guest stack through the host address space.
DWARF callchains additionally copy a raw user stack. The generic arch_perf_out_copy_user() implementation can take an exception-table handled fault when a source page is not resident. Repeated nested faults from the SSE handler can corrupt the interrupted kernel context under load.
Provide an SSE-specific RISC-V copy path. Verify that the active page table belongs to current, use fast-only GUP to acquire each resident source page without falling back to a faulting slow path, and copy through the kernel mapping while holding the page reference. Stop at the first unavailable page and preserve perf's existing truncated-user-stack semantics. Keep the generic in-atomic user copy unchanged outside an SSE handler.
Susheng Yang reported this failure with perf callchain workloads.
--- arch/riscv/include/asm/perf_event.h | 10 ++ arch/riscv/kernel/perf_callchain.c | 142 ++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+)
arch/riscv/include/asm/perf_event.h +10 -0
@@ -18,6 +18,16 @@ (regs)->sp = current_stack_pointer; \ (regs)->status =SR_PP ; \ } + +#ifdef CONFIG_RISCV_SBI_SSE +/* +* Raw user-stack sampling can run in the NMI-like SSE context. Route it +* through an implementation that does not fault on a non-resident page. +*/ +unsigned long riscv_perf_out_copy_user (void *dst,const void *src, +unsigned long n); +#define arch_perf_out_copy_user riscv_perf_out_copy_user +#endif #endif #endif /* _ASM_RISCV_PERF_EVENT_H */
arch/riscv/kernel/perf_callchain.c +142 -0
169 lines not on this page · raw message
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 6/9] perf: RISC-V: support callchains with SSE delivery
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] perf: RISC-V: user stack unwinder retains context-corrupting nested faults - [Medium] perf…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] perf: RISC-V: user stack unwinder retains context-corrupting nested faults
- [Medium] perf: RISC-V: kernel callchain truncation without CONFIG_FRAME_POINTER --
commit a95d15a6320c76f0780598b2a4d0ec479bdebc3c
Author: Zhanpeng Zhang <[email protected]>
perf: RISC-V: support callchains with SSE delivery
PMU overflow delivery through SSE enters Linux with a synthetic supervisor context on a dedicated event stack. This patch implements an SSE-specific RISC-V user and kernel callchain unwinder that attempts to avoid exception-table handled faults.
Quoted 4 lines
arch/riscv/kernel/perf_callchain.c +0
-0
[ ... ]
Quoted 5 lines
arch/riscv/kernel/perf_callchain.c +5
-0+static bool sse_kernel_regs_safe (struct pt_regs *regs) +{ +unsigned long fp =frame_pointer (regs); +unsigned long pc =instruction_pointer (regs); +unsigned long sp =user_stack_pointer (regs);
arch/riscv/kernel/perf_callchain.c static bool fill_callchain(void *entry, unsigned long pc) · line 50
Quoted 10 lines
arch/riscv/kernel/perf_callchain.c +10
-0+ +if (!__kernel_text_address (pc)) +return false; +if (!sse_addr_on_task_stack (sp,sizeof (unsigned long ))) +return false; +if (fp <sizeof (struct stackframe )) +return false; + +return sse_addr_on_task_stack (fp -sizeof (struct stackframe ), +sizeof (struct stackframe ));
[Severity: Medium]
Does this logic unconditionally enforce frame pointer validity, which might break stack unwinding when the kernel doesn't use frame pointers?
When CONFIG_FRAME_POINTER is disabled, regs->s0 (fp) is a general-purpose callee-saved register containing arbitrary data, not a valid frame pointer. Unconditionally validating fp as a valid stack address could fail, causing sse_callchain_kernel() to skip the walk_stackframe() fallback and truncate PMU kernel callchains to a single PC entry.
The walk_stackframe() fallback correctly handles CONFIG_FRAME_POINTER=n by iterating the stack pointer. Can we avoid unconditionally requiring a valid frame pointer here?
[ ... ]
Quoted 8 lines
void perf_callchain_user(struct
perf_callchain_entry_ctx*entry,arch/riscv/kernel/perf_callchain.c +5
-0struct pt_regs *regs) { +#ifdef CONFIG_RISCV_SBI_SSE +const struct riscv_sse_interrupted_context *context; + + context =riscv_sse_get_interrupted_context (); +/* A guest stack cannot be walked using the host address space. */
arch/riscv/kernel/perf_callchain.c static bool fill_callchain(void *entry, unsigned long pc)
Quoted 10 lines
arch/riscv/kernel/perf_callchain.c +4
-0+if (sse_callchain_is_guest (context)) +return ; +#endif +if (perf_guest_state ()) {/* TODO: We don't support guest os callchain now */ return ; }arch_stack_walk_user (fill_callchain, entry, regs);
[Severity: High]
Does this still invoke the user unwinder which relies on __copy_from_user_inatomic(), conflicting with the patch's goal of avoiding hardware faults in SSE handlers?
The commit message states that taking an exception-table handled fault from the SSE handler can corrupt the interrupted kernel context. While this patch introduces arch_perf_out_copy_user() to bypass __copy_from_user_inatomic() for raw stack sampling, perf_callchain_user() continues to use arch_stack_walk_user().
Since arch_stack_walk_user() reads user memory via __copy_from_user_inatomic() and hardware traps could corrupt the SSE context, won't the user stack unwinder trigger the same context corruption when encountering a non-resident page?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH RESEND v10 7/9 perf: RISC-V: add support for SSE event
In reply to Zhanpeng ZhangFrom: Clément Léger <[email protected]>
Register a handler for the local PMU overflow SSE event so that RISC-V perf can receive overflows even when normal S-mode interrupts are masked. Reuse the existing overflow handler and pass it the interrupted pt_regs rebuilt by the architecture SSE entry path.
Select the delivery mechanism once during PMU probe. Prefer SSE when its event can be registered and enabled. If the extension or PMU event is explicitly unsupported, use the ordinary PMU interrupt. Do not enable the interrupt after any other SSE setup failure or when a crash kernel may have inherited firmware state. Install the PMU enable and disable callbacks only after SSE delivery becomes active.
Keep the local PMU SSE event disabled across CPU power management. On entry, the generic SSE notifier masks the hart before the lower-priority PMU notifier disables the event and stops the counters. On exit, the SSE notifier first unmasks the hart while the event remains disabled. The PMU notifier then restores counters and event userpage state before enabling the event. An unmask failure stops the notifier chain and leaves the counters stopped. Ordinary PMU interrupts retain their existing notifier ordering.
An SSE overflow can arrive as soon as the event is enabled during probe. Publish the counter mask before SSE setup, so an early handler can stop the counter source even before perf starts admitting normal samples. After a real overflow, restart only counters whose perf state is still running. Honor a non-zero return from perf_event_overflow() and leave throttled events stopped.
Guest attribution is not part of this version. Detect an interrupted guest from hstatus.SPV and skip its sample while still updating the period and counter state, rather than exposing guest state as a host sample.
The perf PMU callbacks cannot return errors. If an SSE transition or interrupted-context read fails, latch the failure per CPU and stop its mapped events through the normal perf state transitions. Do not reset the firmware counter mapping behind perf, restart a failed event, or attempt a runtime switch to IRQ delivery.
During cleanup, close callback admission and synchronously drain each CPU before disabling and unregistering the SSE event. If firmware refuses the cleanup, stop the counter source and transfer the event to the SSE core so later CPU hotplug or shutdown processing can retry without using freed PMU callback state.
--- Documentation/arch/riscv/index.rst | 1 + Documentation/arch/riscv/pmu-sse.rst | 55 +++ MAINTAINERS | 1 + drivers/firmware/riscv/riscv_sbi_sse.c | 9 + drivers/perf/Kconfig | 11 + drivers/perf/riscv_pmu.c | 14 +- drivers/perf/riscv_pmu_sbi.c | 540 ++++++++++++++++++++----- include/linux/perf/riscv_pmu.h | 20 +- include/linux/riscv_sbi_sse.h | 6 + 9 files changed, 564 insertions(+), 93 deletions(-) create mode 100644 Documentation/arch/riscv/pmu-sse.rst
Documentation/arch/riscv/index.rst +1 -0
@@ -11,6 +11,7 @@ RISC-V architecture vm-layout hwprobe patch-acceptance + pmu-sse uabi vector cmodx
Documentation/arch/riscv/pmu-sse.rst new file +55 -0
55 lines not on this page · raw message
MAINTAINERS +1 -0
@@ -23563,6 +23563,7 @@ M: Atish Patra <[email protected]> R: Anup Patel <[email protected]> L: [email protected] S: Supported +F: Documentation/arch/riscv/pmu-sse.rst F: drivers/perf/riscv_pmu.c F: drivers/perf/riscv_pmu_legacy.c F: drivers/perf/riscv_pmu_sbi.c
drivers/firmware/riscv/riscv_sbi_sse.c +9 -0
@@ -161,6 +161,15 @@ static int sse_sbi_event_func(struct sse_event *event, unsigned long func)return 0 ; } +bool sse_event_is_enabled_local (struct sse_event *event) +{ +if (!sse_event_is_global (event->evt_id)) +lockdep_assert_preemption_disabled (); + +return sse_get_reg_evt (event)->is_enabled; +} +EXPORT_SYMBOL_GPL (sse_event_is_enabled_local); +int sse_event_disable_local (struct sse_event *event) {if (!sse_event_is_global (event->evt_id))
drivers/perf/Kconfig +11 -0
@@ -105,6 +105,17 @@ config RISCV_PMU_SBI full perf feature support i.e. counter overflow, privilege mode filtering, counter configuration. +config RISCV_PMU_SBI_SSE + depends on RISCV_PMU_SBI && RISCV_SBI_SSE + bool "RISC-V PMU SSE events" + default n + help + Say y if you want to use SSE events to deliver PMU interrupts. This + provides a way to profile the kernel at any level by using NMI-like + SSE events. SSE events being really intrusive, this option allows + to select it only if needed. See Documentation/arch/riscv/pmu-sse.rst + for interrupted-context limitations. + config STARFIVE_STARLINK_PMU depends on ARCH_STARFIVE || COMPILE_TEST depends on 64BIT
drivers/perf/riscv_pmu.c +12 -2
@@ -13,6 +13,7 @@#include <linux/irqdesc.h> #include <linux/perf/riscv_pmu.h> #include <linux/printk.h> +#include <linux/riscv_sbi_sse.h> #include <linux/smp.h> #include <linux/sched_clock.h>
@@ -247,6 +248,11 @@ void riscv_pmu_start(struct perf_event *event, int flags)if (flags &PERF_EF_RELOAD )WARN_ON_ONCE (!(event->hw.state &PERF_HES_UPTODATE )); +#ifdef CONFIG_RISCV_PMU_SBI_SSE +if (unlikely (this_cpu_ptr (rvpmu->hw_events)->sse_failed)) +return ; +#endif + hwc->state =0 ;riscv_pmu_event_set_period (event); init_val =local64_read (&hwc->prev_count) & max_period;
@@ -306,6 +312,7 @@ static int riscv_pmu_event_init(struct perf_event *event)struct hw_perf_event *hwc = &event->hw;struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu);int mapped_event; +int ret;u64 event_config =0 ;uint64_t cmask;
@@ -331,8 +338,11 @@ static int riscv_pmu_event_init(struct perf_event *event) hwc->idx =-1 ; hwc->event_base = mapped_event; -if (rvpmu->event_init) - rvpmu->event_init (event); +if (rvpmu->event_init) { + ret = rvpmu->event_init (event); +if (ret) +return ret; + }if (!is_sampling_event (event)) {/*
drivers/perf/riscv_pmu_sbi.c +450 -90
797 lines not on this page · raw message
include/linux/perf/riscv_pmu.h +19 -1
@@ -28,6 +28,8 @@#define RISCV_PMU_CONFIG1_GUEST_EVENTS 0x1 +struct sse_event ; +struct cpu_hw_events {/* currently enabled events */ int n_events;
@@ -39,6 +41,18 @@ struct cpu_hw_events {DECLARE_BITMAP (used_hw_ctrs,RISCV_MAX_COUNTERS );/* currently enabled firmware counters */ DECLARE_BITMAP (used_fw_ctrs,RISCV_MAX_COUNTERS ); +#ifdef CONFIG_RISCV_PMU_SBI_SSE +/* Keep counters stopped after an unrecoverable SSE transition failure. */ +bool sse_failed; +#endif +#ifdef CONFIG_CPU_PM +/* Counters stopped by CPU PM and still waiting to be restored. */ +DECLARE_BITMAP (pm_resume_hw_ctrs,RISCV_MAX_COUNTERS ); +#ifdef CONFIG_RISCV_PMU_SBI_SSE +/* Restore the local PMU SSE event after counters and userpage state. */ +bool pm_resume_sse; +#endif +#endif /* The virtual address of the shared memory where counter snapshot will be taken */ void *snapshot_addr;/* The physical address of the shared memory where counter snapshot will be taken */
@@ -54,6 +68,10 @@ struct riscv_pmu {char *name;irqreturn_t (*handle_irq)(int irq_num,void *dev); +#ifdef CONFIG_RISCV_PMU_SBI_SSE +struct sse_event *sse_evt; +bool sse_active; +#endif DECLARE_BITMAP (cmask,RISCV_MAX_COUNTERS );u64 (*ctr_read)(struct perf_event *event);
@@ -63,7 +81,7 @@ struct riscv_pmu {void (*ctr_start)(struct perf_event *event,u64 init_val);void (*ctr_stop)(struct perf_event *event,unsigned long flag);int (*event_map)(struct perf_event *event,u64 *config); -void (*event_init)(struct perf_event *event); +int (*event_init)(struct perf_event *event);void (*event_mapped)(struct perf_event *event,struct mm_struct *mm);void (*event_unmapped)(struct perf_event *event,struct mm_struct *mm);uint8_t (*csr_index)(struct perf_event *event);
include/linux/riscv_sbi_sse.h +6 -0
@@ -42,6 +42,7 @@ int sse_event_enable(struct sse_event *sse_evt);int sse_event_disable (struct sse_event *sse_evt);/* Local events require the caller to remain on the current CPU. */ +bool sse_event_is_enabled_local (struct sse_event *sse_evt);int sse_event_enable_local (struct sse_event *sse_evt);int sse_event_disable_local (struct sse_event *sse_evt);
@@ -76,6 +77,11 @@ static inline int sse_event_disable(struct sse_event *sse_evt)return -EOPNOTSUPP ; } +static inline bool sse_event_is_enabled_local (struct sse_event *sse_evt) +{ +return false; +} +static inline int sse_event_enable_local (struct sse_event *sse_evt) {return -EOPNOTSUPP ;
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 7/9] perf: RISC-V: add support for SSE event
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] perf/riscv: flawed IRQ teardown logic on probe error when using SSE --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] perf/riscv: flawed IRQ teardown logic on probe error when using SSE --
commit 032c8cbfa5a61964759ab79256536a060b79e8f8
Author: Clément Léger <[email protected]>
perf: RISC-V: add support for SSE event
This commit registers a handler for the local PMU overflow SSE event so that RISC-V perf can receive overflows when normal S-mode interrupts are masked. It sets up the delivery mechanism once during PMU probe and handles SSE delivery state transitions during CPU power management.
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_device_probe(struct platform_device *pdev)
Quoted 11 lines
drivers/perf/riscv_pmu_sbi.c +0
-0@@ -1844,6 +1844,7 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) ret =pmu_sbi_setup_irqs (pmu, pdev);if (ret <0 ) {pr_info ("Perf sampling/filtering is not supported as sscof extension is not available\n" ); pmu->pmu.capabilities |=PERF_PMU_CAP_NO_INTERRUPT ; pmu->pmu.capabilities |=PERF_PMU_CAP_NO_EXCLUDE ; } irq_requested = (ret ==0 );
[Severity: Low]
When pmu_sbi_setup_irqs() successfully configures SSE delivery, it returns 0 without mapping an IRQ. Does this mistakenly set irq_requested to true, treating general delivery setup success as an IRQ allocation? Should this condition check riscv_pmu_use_irq instead?
Quoted 7 lines
drivers/perf/riscv_pmu_sbi.c +6
-0+#ifdef CONFIG_RISCV_PMU_SBI_SSE +if (pmu->sse_active) { + pmu->pmu.pmu_enable = pmu_sbi_sse_enable; + pmu->pmu.pmu_disable = pmu_sbi_sse_disable; + } +#endif
[ ... ]
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +0
-0@@ -1885,8 +1895,8 @@ out_unregister:perf_pmu_unregister (&pmu->pmu); out_destroy:riscv_pmu_destroy (pmu);if (irq_requested) {free_percpu_irq (riscv_pmu_irq, pmu->hw_events);irq_dispose_mapping (riscv_pmu_irq); riscv_pmu_irq =0 ;}
[Severity: Low]
If pmu_sbi_device_probe() fails later (such as in perf_pmu_register()) after SSE delivery is configured, irq_requested will evaluate to true here.
Does this inadvertently cause the cleanup path to attempt to free and dispose of an unallocated IRQ (with riscv_pmu_irq == 0)?
Although the IRQ subsystem safely mitigates this since irq_dispose_mapping(0) ignores virq == 0 and free_percpu_irq(0) safely returns early, could this flawed logic be corrected by verifying riscv_pmu_use_irq instead of the ret == 0 success flag?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Re: [PATCH v10 RESEND 7/9] perf: RISC-V: add support for SSE event
In reply to Zhanpeng ZhangQuoted 51 lines · Zhanpeng Zhang
From: Clément Léger <[email protected]>
Register a handler for the local PMU overflow SSE event so that RISC-V perf can receive overflows even when normal S-mode interrupts are masked. Reuse the existing overflow handler and pass it the interrupted
pt_regsrebuilt by the architecture SSE entry path.Select the delivery mechanism once during PMU probe. Prefer SSE when its event can be registered and enabled. If the extension or PMU event is explicitly unsupported, use the ordinary PMU interrupt. Do not enable the interrupt after any other SSE setup failure or when a crash kernel may have inherited firmware state. Install the PMU enable and disable callbacks only after SSE delivery becomes active.
Keep the local PMU SSE event disabled across CPU power management. On entry, the generic SSE notifier masks the hart before the lower-priority PMU notifier disables the event and stops the counters. On exit, the SSE notifier first unmasks the hart while the event remains disabled. The PMU notifier then restores counters and event userpage state before enabling the event. An unmask failure stops the notifier chain and leaves the counters stopped. Ordinary PMU interrupts retain their existing notifier ordering.
An SSE overflow can arrive as soon as the event is enabled during probe. Publish the counter mask before SSE setup, so an early handler can stop the counter source even before perf starts admitting normal samples. After a real overflow, restart only counters whose perf state is still running. Honor a non-zero return from
perf_event_overflow()and leave throttled events stopped.Guest attribution is not part of this version. Detect an interrupted guest from hstatus.SPV and skip its sample while still updating the period and counter state, rather than exposing guest state as a host sample.
The perf PMU callbacks cannot return errors. If an SSE transition or interrupted-context read fails, latch the failure per CPU and stop its mapped events through the normal perf state transitions. Do not reset the firmware counter mapping behind perf, restart a failed event, or attempt a runtime switch to IRQ delivery.
During cleanup, close callback admission and synchronously drain each CPU before disabling and unregistering the SSE event. If firmware refuses the cleanup, stop the counter source and transfer the event to the SSE core so later CPU hotplug or shutdown processing can retry without using freed PMU callback state.
Signed-off-by Clément Léger <[email protected]>Co-developed-by Himanshu Chauhan <[email protected]>Signed-off-by Himanshu Chauhan <[email protected]>Co-developed-by Zhanpeng Zhang <[email protected]>Signed-off-by Zhanpeng Zhang <[email protected]>
Quoted 12 lines
--- Documentation/arch/riscv/index.rst | 1 + Documentation/arch/riscv/pmu-sse.rst | 55 +++ MAINTAINERS | 1 + drivers/firmware/riscv/riscv_sbi_sse.c | 9 + drivers/perf/Kconfig | 11 + drivers/perf/riscv_pmu.c | 14 +- drivers/perf/riscv_pmu_sbi.c | 540 ++++++++++++++++++++----- include/linux/perf/riscv_pmu.h | 20 +- include/linux/riscv_sbi_sse.h | 6 + 9 files changed, 564 insertions(+), 93 deletions(-) create mode 100644 Documentation/arch/riscv/pmu-sse.rst
PATCH RESEND v10 8/9 selftests/riscv: add SSE test module
In reply to Zhanpeng ZhangFrom: Clément Léger <[email protected]>
Add an SSE selftest module and runner. Loading the module executes smoke tests for the SSE framework, and the runner reports any error emitted by the module.
Add stress={0,1,2} modes to exercise repeated handler entry and completion, single and multiple read-only SBI calls from a handler, and self re-injection. Check the SBI return values so handler execution alone cannot produce a false pass, and avoid touching an unreserved PMU counter owned by another user.
Harden the test against false failures and leaks by using TEST_PROGS for the runner, using phys_addr_t for SBI attribute buffers, adding timeouts to busy waits, pinning each priority chain with migrate_disable(), and holding the CPU read lock while a fast-test target is selected, injected, and completed. Unregister all registered events on error, check teardown failures, and let kthread_stop() drive monitor-thread exit.
Track handler progress across fast, priority, and stress paths. If firmware reports injectable events but the test cannot acquire or handle any of them, report SKIP instead of silently passing a capability-only run.
--- MAINTAINERS | 2 + tools/testing/selftests/riscv/Makefile | 2 +- tools/testing/selftests/riscv/sse/Makefile | 5 + .../selftests/riscv/sse/module/Makefile | 22 + .../riscv/sse/module/riscv_sse_test.c | 1154 +++++++++++++++++ .../selftests/riscv/sse/run_sse_test.sh | 59 + 6 files changed, 1243 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/riscv/sse/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/riscv_sse_test.c create mode 100644 tools/testing/selftests/riscv/sse/run_sse_test.sh
MAINTAINERS +2 -0
@@ -23489,6 +23489,7 @@ C: irc://irc.libera.chat/riscv P: Documentation/arch/riscv/patch-acceptance.rst T: git git://git.kernel.org/pub/scm/linux/kernel/git/riscv/linux.git F: arch/riscv/ +F: tools/testing/selftests/riscv/ N: riscv K: riscv
@@ -23614,6 +23615,7 @@ F: arch/riscv/kernel/sbi_sse.c F: arch/riscv/kernel/sbi_sse_entry.S F: drivers/firmware/riscv/riscv_sbi_sse.c F: include/linux/riscv_sbi_sse.h +F: tools/testing/selftests/riscv/sse/ RISC-V TENSTORRENT SoC SUPPORT M: Drew Fustini <[email protected]>
tools/testing/selftests/riscv/Makefile +1 -1
@@ -5,7 +5,7 @@ ARCH ?= $(shell uname -m 2>/dev/null || echo not) ifneq (,$(filter $(ARCH),riscv)) -RISCV_SUBTARGETS ?= abi hwprobe mm sigreturn vector cfi +RISCV_SUBTARGETS ?= abi hwprobe mm sigreturn vector cfi sse else RISCV_SUBTARGETS := endif
tools/testing/selftests/riscv/sse/Makefile new file +5 -0
@@ -0,0 +1,5 @@ +TEST_GEN_MODS_DIR := module + +TEST_PROGS := run_sse_test.sh + +include ../../lib.mk
tools/testing/selftests/riscv/sse/module/Makefile new file +22 -0
@@ -0,0 +1,22 @@ +ifneq ($(CONFIG_RISCV_SBI_SSE),) +obj-m += riscv_sse_test.o +endif + +ifndef KERNELRELEASE + +TESTMODS_DIR := $(realpath $(dir $(abspath $(lastword $(MAKEFILE_LIST))))) +KDIR ?= /lib/modules/$(shell uname -r)/build + +# Ensure that KDIR exists, otherwise skip the compilation +modules: +ifneq ("$(wildcard $(KDIR))", "") + $(Q)$(MAKE) -C $(KDIR) modules KBUILD_EXTMOD=$(TESTMODS_DIR) +endif + +# Ensure that KDIR exists, otherwise skip the clean target +clean: +ifneq ("$(wildcard $(KDIR))", "") + $(Q)$(MAKE) -C $(KDIR) clean KBUILD_EXTMOD=$(TESTMODS_DIR) +endif + +endif
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +1154 -0
1,154 lines not on this page · raw message
tools/testing/selftests/riscv/sse/run_sse_test.sh new file +59 -0
59 lines not on this page · raw message
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 8/9] selftests/riscv: add SSE test module
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] riscv/sse: truncating physical address in sse_event_attr_read() causes memory corruption on RV32…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] riscv/sse: truncating physical address in sse_event_attr_read() causes memory corruption on RV32
- [High] riscv/sse: unhandled timeout in sse_run_fast_test() leaves asynchronous firmware event pending
- [High] riscv/sse: cleanup work loop deadlocks because sse_event_disable() on disabled event fails
- [Medium] riscv/sse: HZ/100 timeout calculation causes guaranteed immediate timeout when HZ < 100 --
commit a979d907b51d143e2d5c8ad22d308f8c21385e6f
Author: Clément Léger <[email protected]>
selftests/riscv: add SSE test module
Add an SSE selftest module and runner. Loading the module executes smoke tests for the SSE framework, and the runner reports any error emitted by the module.
Quoted 5 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +0
-0
[ ... ]
Quoted 9 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +9
-0+static void sse_test_cleanup_workfn (struct work_struct *work) +{ +bool retry = false; +int i, ret; + +mutex_lock (&sse_test_cleanup_lock); +for (i =0 ; i <ARRAY_SIZE (sse_test_cleanup_events); i++) { +struct sse_event *event = sse_test_cleanup_events[i]; +
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c line 203
Quoted 10 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +10
-0+if (!event) +continue ; + + ret =sse_event_disable (event); +if (!ret) + ret =sse_event_unregister (event); +if (ret) { + retry = true; +continue ; + }
[Severity: High]
Does this code introduce an infinite loop during cleanup? If sse_event_disable() is called on an already-disabled event, it may return an error like SBI_ERR_INVALID_STATE. If ret is set, this check will skip sse_event_unregister(), set retry = true, and permanently reschedule the work, deadlocking the cleanup work queue.
Quoted 10 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +10
-0+ + sse_test_cleanup_events[i] =NULL ; +module_put (THIS_MODULE ); + } +mutex_unlock (&sse_test_cleanup_lock); + +if (retry) +mod_delayed_work (system_wq, &sse_test_cleanup_work, +msecs_to_jiffies (100 )); +}
[ ... ]
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c line 229
Quoted 10 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +10
-0+static int sse_event_attr_read (u32 evt,unsigned long attr_id, +unsigned long *attr_buf) +{ +struct sbiret sret; +phys_addr_t phys; + + phys =virt_to_phys (attr_buf); + + sret =sbi_ecall (SBI_EXT_SSE ,SBI_SSE_EVENT_ATTR_READ , evt, attr_id,1 , + (unsigned long )phys,0 ,0 );
[Severity: High]
Can this corrupt memory on RV32 systems? The function casts phys_addr_t phys to unsigned long, which truncates it to 32 bits on RV32. Since 0 is passed for arg4 (phys_hi), the SBI firmware will write attributes to the truncated physical address, potentially corrupting arbitrary memory below 4GB instead of modifying the intended buffer.
Quoted 5 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +5
-0+if (sret.error) +return sbi_err_map_linux_errno (sret.error); + +return 0 ; +}
[ ... ]
Quoted 11 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +11
-0+static int sse_run_fast_test_cpu (struct fast_test_arg *test_arg, +struct sse_event *event,u32 evt,int cpu) +{ +unsigned long timeout; +int ret; + +WRITE_ONCE (test_arg->completion, false); +WRITE_ONCE (test_arg->args_ready, false); +WRITE_ONCE (test_arg->evt, evt); +WRITE_ONCE (test_arg->cpu, cpu); +/* Publish all arguments before firmware can inject on another hart. */
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c line 439
Quoted 10 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +10
-0+smp_store_release (&test_arg->args_ready, true); + + ret =sse_test_inject_event (event, evt, cpu); +if (ret) { +sse_err ("event %s injection failed, err %d\n" , +sse_evt_name (evt), ret); +return ret; + } + + timeout = jiffies +HZ /100 ;
[Severity: Medium]
Will this evaluate to 0 if HZ < 100? If the kernel is configured with a low HZ, HZ / 100 is 0. This causes the subsequent time_before() check to immediately fail before the event can be handled, resulting in false test failures.
Quoted 40 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +40
-0+/* We can not use <linux/completion.h> since they are not NMI safe */ +/* Pairs with the handler's completion publication. */ +while (!smp_load_acquire (&test_arg->completion) && +time_before (jiffies, timeout)) +cpu_relax (); +/* Acquire the handler's checks even if the loop observed a timeout. */ +if (!smp_load_acquire (&test_arg->completion)) { +sse_err ("Failed to wait for event %s completion on CPU %d\n" , +sse_evt_name (evt), cpu); +return -ETIMEDOUT ; + } + +return sse_test_wait_not_running_on_cpu (evt, cpu); +} + +static void sse_run_fast_test (struct fast_test_arg *test_arg, +struct sse_event *event,u32 evt) +{ +int cpu; + +if (sse_event_is_global (evt)) { +/* Keep the selected target online through injection and completion. */ +cpu_hotplug_disable (); +for_each_online_cpu (cpu) { +if (sse_run_fast_test_cpu (test_arg, event, evt, cpu)) +break ; + } +cpu_hotplug_enable (); +return ; + } + +guard (cpus_read_lock)(); +for_each_online_cpu (cpu) { +if (sse_run_fast_test_cpu (test_arg, event, evt, cpu)) +return ; + } +} + +static void sse_test_injection_fast (void ) +{
[ ... ]
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c line 518
Quoted 4 lines
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +4
-0+pr_info ("Starting testing event %s\n" ,sse_evt_name (evt)); + +for (j =0 ; j <RUN_LOOP_COUNT ; j++) +sse_run_fast_test (&fast_test_arg, event, evt);
[Severity: High]
Does this code ignore unhandled timeouts? If sse_run_fast_test_cpu() times out and returns -ETIMEDOUT, the error is swallowed because sse_run_fast_test() returns void. This loop immediately fires the next iteration, overwriting fast_test_arg while an asynchronous firmware event may still be pending from the previous loop, potentially causing a data race on the global test state.
Quoted 1 line
tools/testing/selftests/riscv/sse/module/riscv_sse_test.c new file +1
-0+pr_info ("Finished testing event %s\n" ,sse_evt_name (evt));
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
PATCH RESEND v10 9/9 selftests/riscv: add perf user-stack SSE copy regression test
In reply to Zhanpeng ZhangOn RISC-V, PMU overflow interrupts can be delivered through the SBI Supervisor Software Events (SSE) mechanism. A perf event that samples the raw user stack (PERF_SAMPLE_STACK_USER, as perf record --call-graph dwarf does) then copies a chunk of the interrupted task's user stack from an NMI-like context. If that copy is allowed to take a nested page fault it can corrupt the interrupted task's kernel state and hang or crash the machine under load; this is what riscv_perf_out_copy_user() and the nofault page-fault change fix.
The existing SSE selftest module exercises the framework (register, enable, inject, complete, priorities, stress) but never drives the perf user-stack copy that motivated the no-fault path. Add a userspace test that closes that gap:
- Open a sampling hardware PMU event with PERF_SAMPLE_STACK_USER over a deep, partially non-resident user stack, drain the ring buffer, and verify every SAMPLE record is well formed and never reports more dumped bytes than were requested. This checks that a non-resident page truncates the dump cleanly instead of faulting or overrunning.
- Drive a multi-CPU unix-socket + deep-recursion workload under high-frequency DWARF sampling; the pass criterion is simply that the machine survives, since the original bug took it down.
The test reports SKIP when hardware PMU sampling is unavailable or perf_event_paranoid forbids it, so it is safe to run unprivileged or in constrained environments. It is placed under the RISC-V SSE selftests because SSE delivery is the RISC-V-specific condition it protects, and is wired into the sse subtarget Makefile alongside the module runner.
--- tools/testing/selftests/riscv/sse/Makefile | 5 + .../selftests/riscv/sse/sse_perf_ustack.c | 564 ++++++++++++++++++ 2 files changed, 569 insertions(+) create mode 100644 tools/testing/selftests/riscv/sse/sse_perf_ustack.c
tools/testing/selftests/riscv/sse/Makefile +5 -0
@@ -1,5 +1,10 @@ +CFLAGS += -I$(top_srcdir)/tools/testing/selftests +LDLIBS += -lpthread + TEST_GEN_MODS_DIR := module +TEST_GEN_PROGS := sse_perf_ustack + TEST_PROGS := run_sse_test.sh include ../../lib.mk
tools/testing/selftests/riscv/sse/sse_perf_ustack.c new file +564 -0
564 lines not on this page · raw message
Signature · 1 line
2.50.1 (Apple Git-155)
[email protected]
AI reviewRe: [PATCH v10 RESEND 9/9] selftests/riscv: add perf user-stack SSE copy regression test
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 23 lines
On RISC-V, PMU overflow interrupts can be delivered through the SBI Supervisor Software Events (SSE) mechanism. A perf event that samples the raw user stack (
PERF_SAMPLE_STACK_USER, as perf record --call-graph dwarf does) then copies a chunk of the interrupted task's user stack from an NMI-like context. If that copy is allowed to take a nested page fault it can corrupt the interrupted task's kernel state and hang or crash the machine under load; this is whatriscv_perf_out_copy_user()and the nofault page-fault change fix.The existing SSE selftest module exercises the framework (register, enable, inject, complete, priorities, stress) but never drives the perf user-stack copy that motivated the no-fault path. Add a userspace test that closes that gap:
- Open a sampling hardware PMU event with
PERF_SAMPLE_STACK_USERover a deep, partially non-resident user stack, drain the ring buffer, and verify every SAMPLE record is well formed and never reports more dumped bytes than were requested. This checks that a non-resident page truncates the dump cleanly instead of faulting or overrunning.
- Drive a multi-CPU unix-socket + deep-recursion workload under high-frequency DWARF sampling; the pass criterion is simply that the machine survives, since the original bug took it down.
Quoted 7 lines
The test reports SKIP when hardware PMU sampling is unavailable or
perf_event_paranoidforbids it, so it is safe to run unprivileged or in constrained environments. It is placed under the RISC-V SSE selftests because SSE delivery is the RISC-V-specific condition it protects, and is wired into the sse subtargetMakefilealongside the module runner.Signed-off-by Zhanpeng Zhang <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Quoted 3 lines · Zhanpeng Zhang
This is v10 rebased onto v7.3-rc4, as a base for the RAS work requested by Himanshu. No additional fixes or features are included.
Thanks for this! This patch series sees a lot of churn. My patches don't directly apply. Give me sometime to review and test.
Regards
Himanshu
Quoted 412 lines
Only patch 7 needed adaptation: keep the upstream counter-mask bitmap conversion and snapshot NULL-check ordering, and adapt the SSE stop-all helper and early counter-mask initialization to the bitmap representation. The fast-only GUP user-stack copy remains unchanged.
Rebase validation: RV64 defconfig with SSE, PMU-SSE, CPU PM and kexec enabled builds Image, modules, the SSE test module and the user-stack selftest. The SSE, trap, fault and PMU objects also build for RV32. The exported series applies cleanly to v7.3-rc4 and reproduces the branch tree. On EVB247, the Debian-packaged rc4 kernel boots via kexec with its matching initrd and modules. The SSE framework and priority tests, all four stress layers in stress=1, and both user-stack selftests pass. The latter includes 32 concurrent samplers. No new kernel errors were observed. Unavailable injection events were skipped by the framework test; KVM was disabled in this test configuration, so virtualization was not retested.
The functional results below are retained from the original v10 and are not claims of runtime validation on this rebased kernel.
RISC-V does not architecturally define a supervisor-mode non-maskable interrupt (NMI). An interrupt that arrives while Linux has cleared SIE stays pending and is not observed until interrupts are enabled again. That is correct for ordinary interrupt handling, but some kernel work needs an NMI-like notification that can run even inside an interrupt-disabled region:
sampling a PMU overflow at the instruction that caused it, or taking a high-priority RAS report promptly, cannot wait for the next unmask boundary.The SBI Supervisor Software Events (SSE) extension [1] fills this gap. It lets Linux register handlers for events that the SBI implementation can deliver ahead of ordinary traps and interrupts, giving RISC-V the NMI-like supervisor notification mechanism it otherwise lacks.
SSE can carry several event sources: high-priority RAS reports, double traps, and PMU overflow, with room for further standard and platform events. This series focuses on PMU overflow, its first user. Delivering overflows through SSE lets perf sample the code that was actually running while interrupts were disabled, rather than the later point where execution reached an interrupt-unmask boundary.
This series implements the Linux side of that interface: the architecture entry machinery, a firmware driver that exposes SSE events to in-kernel clients, PMU overflow delivery, and regression tests. Per-hart local events and system-wide global events share one client API.
SSE delivery model
==================Linux first registers a handler and an event stack with the SBI implementation, then enables the event. When an event source is signalled, the M-mode SBI implementation preempts Linux even in an interrupt-disabled region:
it saves the interrupted supervisor state and constructs an S-mode context that enters the registered handler. Linux can now run its own handler, for example to take a perf sample or process a RAS report, then completes the event with another SBI call, allowing the interrupted context to resume.The typical hardware-triggered delivery flow is (software-injected events skip the hardware trigger):
<--------- Linux kernel -----------> <-- Firmware ---> <- Hardware ->
interrupted context SSE handler OpenSBI Hardware
| | | |[1] setup | |-register & enable--> | | | | | [2] trigger | | <----trigger------| | | | | [3] save | | +--------------+ | | | | context save | | | | +--------------+ | | | | | [4] inject | | +-----------------------+ | | | | handler context setup | | | | +-----------------------+ | | <---inject (mret) ---| | | | | | [5] handle | +----------------+ | | | | event handling | | | | +----------------+ | | | | | | [6] complete | |-----complete-------> | | | | | [7] restore | | +-----------------+ | | | | context restore | | | | +-----------------+ | | | | | [8] resume <------------resume (mret) ------------| | | | | |The context used to enter the handler exists only for this handoff; it is not the task context that the event interrupted. The architecture entry code joins the two sides: it moves execution onto the event's dedicated stack and shadow call stack, establishes the current task, and presents the interrupted registers to the callback as a normal
pt_regs. Clients can therefore operate on the original interrupted context without depending on the firmware entry details.Linux implementation
====================An SSE handler runs in NMI-like context: it must not sleep, must not take a page fault, and may interrupt code that holds arbitrary locks or is partway through kernel entry. The implementation is shaped by those constraints.
Because it is NMI-like, an SSE can arrive at any point where interrupts are disabled, including while Linux is midway through exception entry, a task switch, or a KVM guest transition, where the normal kernel entry state is only partially established. The SSE entry wrapper (the architecture assembly that runs before the client callback) copes with this: it preserves Linux-owned stvec, hstatus, and task stack metadata across the handler and any nested exception, and its earliest instructions, which run before the event stack and current task are set up, are kept outside kprobe instrumentation.
The callback receives the interrupted registers as a
pt_regsand is allowed to edit them. On RISC-V a6 and a7 carry SBI call arguments and results, so a callback that wants to influence an in-flight SBI call the event interrupted edits them there. The entry wrapper copies just a6 and a7 from thatpt_regsback into the context handed to the completion SBI call, so the edit takes effect when the interrupted code resumes; the rest of the interrupted state is restored by firmware and left untouched.The firmware driver maps the SBI event state machine onto kernel resource ownership. A callback, stack, and attribute buffer stay alive until firmware has removed every registration that can refer to them. Failed partial operations remain tracked for later cleanup, an aborted CPU-offline operation restores the requested event state, and shutdown and kexec mask SSE before Linux stops servicing handlers.
PMU overflow and perf
=====================The RISC-V SBI PMU driver delivers overflows through ordinary interrupts by default. When firmware implements SSE and the local PMU-overflow event, the driver routes overflows through SSE instead. The choice is made once at setup and is not switched at runtime; an operational failure disables sampling rather than risking two active routes for the same overflow.
This changes where perf can observe an overflow, not how applications use perf. A normal PMU interrupt raised while S-mode interrupts are masked is handled only once they are enabled again, so the resulting sample often points at the unmask boundary rather than at the code that consumed the cycles. SSE can enter Linux at the original point and remove that source of sampling bias. No new perf option or perf.data format is introduced.
The entry code supplies the interrupted
pt_regsneeded for register samples and for kernel and user callchains. DWARF callchains additionally require a copy of the interrupted user stack. Since an SSE handler cannot take a normal page fault, this series takes a temporary reference to the resident user pages with fast-only GUP, copies them through their kernel mappings, and truncates the sample at the first page that is not immediately available. The existing in-atomic copy remains unchanged outside SSE context.The PMU integration retains perf's throttling and stopped-event semantics. It restarts only runnable counters and orders the CPU power-management callbacks so that counters cannot resume after a hart has failed to restore its SSE delivery path.
Hardware results
================We measured this on a RISC-V server platform. The same kernel source and perf binary were used for both routes; one delivered PMU overflows through ordinary interrupts and the other through SSE. The table shows the mean of three runs of three million single-CPU "perf bench sched pipe" operations. The "ops/s" columns are workload throughput (higher is better, so they show the profiling overhead); the "
samples/s" columns are the sampling rate perf actually achieved against the requested -F frequency:rate IRQ ops/s SSE ops/s delta IRQ samples/s SSE samples/s -F 99 337,707 339,555 +0.55% 98.0 98.6 -F 999 338,352 338,289 -0.02% 995.7 998.0 -F 5000 329,002 333,034 +1.23% 5001.7 5001.6There were no lost samples. Across these normal frequency settings, both delivery modes reached the requested sample rate and workload throughput differed by no more than 1.23%.
The "perf bench sched pipe" workload also shows why the delivery mechanism matters to the resulting profile. Ordinary PMU interrupts cannot enter an interrupt-disabled kernel critical section. Overflows raised there remain pending until interrupts are enabled again. Samples consequently accumulate at the enable boundary rather than at the code that consumed the cycles. In the IRQ profile,
finish_task_switch()and_raw_spin_unlock_irqrestore()therefore accounted for 54.99% of all samples.SSE can enter Linux while S-mode interrupts are disabled. The PMU-SSE profile therefore samples inside those critical sections and exposes the scheduler, locking, address-space switching, and wake-up paths doing the actual work. The leading entries from the two -F 999 reports show the difference.
With ordinary PMU interrupt delivery:
overhead symbol 36.63% finish_task_switch.isra.0 18.36% _raw_spin_unlock_irqrestore 7.66% __internal_syscall_cancel 7.55% do_trap_ecall_u 4.19% mutex_lock 3.64% mutex_unlock 3.06% exit_to_user_mode_loopWith PMU-SSE delivery:
overhead symbol 5.48% __kprobes_text_end 5.29% __schedule 5.10% ret_from_exception 4.71% do_raw_spin_lock 4.01% do_trap_ecall_u 3.99% mutex_lock 3.66% switch_mm 3.43% mutex_unlock 3.29% exit_to_user_mode_loop 3.28% psi_group_changeThe ordinary interrupt profile is dominated by two interrupt-enable boundaries. With SSE, those two entries account for only 3.37%. The samples are instead distributed across scheduler paths within the critical sections.
At perf's configured limit of 100,000 samples per second, both routes still made progress without lost samples. In this deliberately saturated regime SSE reduced workload throughput by 2.7% to 5.8%, which exposes the additional firmware-entry cost and marks a practical upper boundary for sampling. Thirty-second perf top runs at the same rate each processed about 3.1 million samples with no loss, stalls, or kernel failures.
The DWARF callchain path gets dedicated coverage because it was the source of the corruption this series fixes. On the same platform,
"perf record -a -g --call-graph dwarf,512 -F 999" layered on a concurrent "hackbench -g25 -l600" -- the configuration that previously corrupted spinlocks and mutexes under SSE -- now completes cleanly, with no lost samples, lockups, RCU stalls, or faults, including a 431-iteration soak. Patch 9 adds a regression test that drives the non-faulting user-stack copy through the SSE handler with 32 concurrent samplers and checks perf's truncation semantics.Changes in this resend
======================This resend only rebases v10 onto v7.3-rc4. The only merge conflict was in patch 7, due to the upstream PMU counter-mask bitmap conversion. In v11, I will address the Sashiko review feedback and improve user-stack copying with an NMI-safe interface similar to x86's
copy_from_user_nmi().Changes in v10
==============V10 turns the earlier feature series into a path suitable for sustained perf use. In particular, it:
- reconstructs and publishes the interrupted context for perf register
samples and kernel and user callchains; - preserves current, task stack metadata, stvec, hstatus, and shadow-call stack state across synthetic entry and nested exceptions; - prevents fault-disabled accesses from entering the generic RISC-V page fault path and provides a non-faulting SSE user-stack copy; - makes event lifetime and rollback explicit across partial firmware operations, CPU hotplug, shutdown, crash, and kexec;- closes PMU throttle, counter restart, CPU power-management, and cleanup races without adding a runtime SSE-to-IRQ transition; and
- expands the framework stress coverage and adds a regression test for high-frequency DWARF user-stack sampling.Changes in v9:
- Rebased the original series onto RISC-V for-next.
- Preserved Linux-owned trap, virtualization, and supervisor state across the synthetic SSE handler.
- Added framework stress modes and updatedMAINTAINERS.Previous versions:
v9:https://lore.kernel.org/r/[email protected] v8: https://lore.kernel.org/r/[email protected]How to test
===========Enable the SSE framework and SSE overflow delivery:
CONFIG_RISCV_SBI_SSE=y
CONFIG_RISCV_PMU_SBI=y
CONFIG_RISCV_PMU_SBI_SSE=yPMU-SSE also requires two OpenSBI fixes:
f30a54f3b3a0("lib: sbi: pmu: Remove MIP clearing frompmu_sse_enable()")
[2], included since OpenSBI v1.7,
which keeps an overflow pending while its SSE event is temporarily disabled; and
35511bc6ee1c("lib: sbi: sse: clear SPV for non-virtualized events") [3],
not yet included in a tagged release,
which stops a stale HSTATUS.SPV from being applied to a non-virtualized event.Build
tools/testing/selftests/riscv, then run:for stress in 0 1 2; do ./run_sse_test.sh stress=$stress || break done ./sse_perf_ustackUseful perf regression workloads include:
perf record -e cycles -a -- sleep 1 perf top perf record -g -F 999 -- hackbench perf record --call-graph dwarf,8192 -F 999 -- hackbench perf record -a -C 3 -e cycles -F 999 -- \ taskset -c 3 perf bench sched pipe -l 3000000Limitations and follow-up work
==============================This series does not yet deliver SSE events into a guest or unwind a guest stack; a later KVM-SSE series will let the host receive an event from firmware and inject the corresponding event into the guest.
Hibernation and crash kernels are unsupported: the current SBI interface cannot reconstruct firmware registrations after an image is restored, and a crash kernel cannot take over the registrations left by the crashed kernel, so it leaves SSE masked.
[1] https://docs.riscv.org/reference/sbi/ext-sse.html
[2] https://github.com/riscv-software-src/opensbi/commit/f30a54f3b3a091c225a00476f4039bf399badd1f
[3] https://github.com/riscv-software-src/opensbi/commit/35511bc6ee1c9c17b6a89b44c52e2044bb51b979Acknowledgements
================The original five feature patches were developed by Clément Léger and Himanshu Chauhan. Thanks to Susheng Yang for reporting the perf callchain failure and for providing a workload that made it reproducible.
Sorry for keeping you waiting. Since v9 I spent a good deal of time hardening the lifecycle and error paths and reproducing and analysing the bugs that only show up in the callchain path, until the series finally passed both functional and sustained stress testing on hardware. I am confident in v10, but, echoing Clément, SSE is a genuinely complex feature: it adds a new NMI-like entry path into the kernel to stand in for a hardware NMI. I would therefore welcome wider community testing and feedback, especially under high-frequency delivery and more complex handlers.
---
Clément Léger (5):
riscv: add SBI SSE extension definitions
riscv: add support for SBI Supervisor Software Events extension
drivers: firmware: add riscv SSE support
perf: RISC-V: add support for SSE event selftests/riscv: add SSE test moduleZhanpeng Zhang (4):
riscv: sse: mask events during shutdown and kexec
riscv: mm: avoid enabling interrupts for nofault page faults
perf: RISC-V: support callchains with SSE delivery selftests/riscv: add perf user-stack SSE copy regression testDocumentation/arch/riscv/index.rst | 1 + Documentation/arch/riscv/pmu-sse.rst | 55 + MAINTAINERS | 22 + arch/riscv/include/asm/asm.h | 14 +- arch/riscv/include/asm/perf_event.h | 10 + arch/riscv/include/asm/sbi.h | 63 + arch/riscv/include/asm/scs.h | 7 + arch/riscv/include/asm/sse.h | 82 ++ arch/riscv/include/asm/thread_info.h | 1 + arch/riscv/kernel/Makefile | 1 + arch/riscv/kernel/asm-offsets.c | 14 + arch/riscv/kernel/entry.S | 14 + arch/riscv/kernel/machine_kexec.c | 11 + arch/riscv/kernel/perf_callchain.c | 142 ++ arch/riscv/kernel/reset.c | 18 + arch/riscv/kernel/sbi_sse.c | 246 ++++ arch/riscv/kernel/sbi_sse_entry.S | 226 +++ arch/riscv/kernel/smp.c | 17 + arch/riscv/mm/fault.c | 11 +- drivers/firmware/Kconfig | 1 + drivers/firmware/Makefile | 1 + drivers/firmware/riscv/Kconfig | 18 + drivers/firmware/riscv/Makefile | 3 + drivers/firmware/riscv/riscv_sbi_sse.c | 1228 +++++++++++++++++ drivers/perf/Kconfig | 11 + drivers/perf/riscv_pmu.c | 14 +- drivers/perf/riscv_pmu_sbi.c | 540 ++++++-- include/linux/cpuhotplug.h | 1 + include/linux/perf/riscv_pmu.h | 20 +- include/linux/riscv_sbi_sse.h | 95 ++ tools/testing/selftests/riscv/Makefile | 2 +- tools/testing/selftests/riscv/sse/Makefile | 10 + .../selftests/riscv/sse/module/Makefile | 22 + .../riscv/sse/module/riscv_sse_test.c | 1154 ++++++++++++++++ .../selftests/riscv/sse/run_sse_test.sh | 59 + .../selftests/riscv/sse/sse_perf_ustack.c | 564 ++++++++ 36 files changed, 4599 insertions(+), 99 deletions(-) create mode 100644 Documentation/arch/riscv/pmu-sse.rst create mode 100644 arch/riscv/include/asm/sse.h create mode 100644 arch/riscv/kernel/sbi_sse.c create mode 100644 arch/riscv/kernel/sbi_sse_entry.S create mode 100644 drivers/firmware/riscv/Kconfig create mode 100644 drivers/firmware/riscv/Makefile create mode 100644 drivers/firmware/riscv/riscv_sbi_sse.c create mode 100644 include/linux/riscv_sbi_sse.h create mode 100644 tools/testing/selftests/riscv/sse/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/Makefile create mode 100644 tools/testing/selftests/riscv/sse/module/riscv_sse_test.c create mode 100644 tools/testing/selftests/riscv/sse/run_sse_test.sh create mode 100644 tools/testing/selftests/riscv/sse/sse_perf_ustack.cbase-commit:
93f51579e7df248780214094418f205253383cc5Signature · 1 line
2.50.1 (Apple Git-155)