riscv: pmu: Add support for Control Transfer Records Ext.
Subsystems (5)
v6 cover riscv: pmu: Add support for Control Transfer Records Ext.
This series enables Control Transfer Records extension support on riscv architecture. This extension is similar to Arch LBR in x86 and BRBE in ARM. The Extension has been ratified and latest release can be found here [0]
CTR extension depends on both the implementation of S-mode and Sscsrind extension v1.0.0 [1]. CTR access ctrsource, ctrtartget and ctrdata CSRs using sscsrind extension.
The series is based on Smcdeleg/Ssccfg counter delegation extension [2] patches [3]. CTR itself doesn't depend on counter delegation support. This rebase is basically to include the Smcsrind patches.
The last patch is in the perf tool to allow processing 256 entries. Without this perf seems to consider that sample as corrupted and discards it.
Here is the link to a quick guide [4] to setup and run a basic perf demo on Linux to use CTR Ext.
Qemu patches are merged upstream and is available with latest version.
Opensbi patch is merged upstream and is available with latest version.
[0]: https://github.com/riscv/riscv-control-transfer-records/releases/tag/v1.0
[1]: https://github.com/riscvarchive/riscv-indirect-csr-access/releases/tag/v1.0.0
[2]: https://github.com/riscvarchive/riscv-smcdeleg-ssccfg/releases/tag/v1.0.0
[3]: https://lore.kernel.org/lkml/[email protected]/
[4]: https://github.com/vikramsgh/riscv_linux_ctr_demo/wiki/Steps-to-run-basic-CTR-demo-on-RISCV-Virt
To: Peter Zijlstra <[email protected]>
To: Ingo Molnar <[email protected]>
To: Arnaldo Carvalho de Melo <[email protected]>
To: Namhyung Kim <[email protected]>
To: Mark Rutland <[email protected]>
To: Alexander Shishkin <[email protected]>
To: Jiri Olsa <[email protected]>
To: Ian Rogers <[email protected]>
To: Adrian Hunter <[email protected]>
To: Paul Walmsley <[email protected]>
To: Palmer Dabbelt <[email protected]>
To: Albert Ou <[email protected]>
To: Alexandre Ghiti <[email protected]>
To: Atish Kumar Patra <[email protected]>
To: Anup Patel <[email protected]>
To: Will Deacon <[email protected]>
To: Rob Herring <[email protected]>
To: Krzysztof Kozlowski <[email protected]>
To: Conor Dooley <[email protected]>
To: Beeman Strong <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: [email protected]
Cc: Conor Dooley <[email protected]>
Cc: [email protected]
---
Changelog:
v6:
- Rebased CTR driver and support files to Linux Kernel version 7.4 RC4
- Incorporated review comments and suggestions
v5:
- Rebased CTR driver and support files to Linux kernel version 7.4 RC3
v4:
- Ported CTR driver and support files from kernel version 6.14 to kernel version 7.2
- Added CSR indirect access header file to be used by CTR driver
- Changes in sched_task call back signature to accomodate new kernel headers
- Minor clean up
v3:
- Added missing To/Cc, especially [email protected]
- Changed the commit description to better describe the need of perf tool change that increases max sample size processing capacity of remove_loops function.
- Minor fixes found while doing a virtualization PoC.
- Added the missing commit and repository information to dt-bindings, indicating where the extension was ratified.
v2
- Added context save/restore support for tasks using CTR feature.
- https://lore.kernel.org/lkml/[email protected]/
v1:
- https://lore.kernel.org/lkml/[email protected]/
---
Vikram Singh (7):
perf: Increase the maximum number of branches remove_loops() can
process.
riscv: pmu: Add Control transfer records CSR definations.
riscv: Add Control Transfer Records extension parsing
riscv: pmu: Add infrastructure for Control Transfer Record
riscv: pmu: Add driver for Control Transfer Records Ext
riscv: pmu: Integrate CTR Ext support in riscv_pmu_dev driver
dt-bindings: riscv: add Sxctr ISA extension description
.../devicetree/bindings/riscv/extensions.yaml | 29 + MAINTAINERS | 2 + arch/riscv/include/asm/csr.h | 83 +++ arch/riscv/include/asm/hwcap.h | 4 + arch/riscv/kernel/cpufeature.c | 2 + drivers/perf/Kconfig | 11 + drivers/perf/Makefile | 1 + drivers/perf/riscv_ctr.c | 608 ++++++++++++++++++ drivers/perf/riscv_pmu.c | 21 +- drivers/perf/riscv_pmu_legacy.c | 2 + drivers/perf/riscv_pmu_sbi.c | 87 ++- include/linux/perf/riscv_pmu.h | 58 +- tools/perf/util/machine.c | 21 +- 13 files changed, 917 insertions(+), 12 deletions(-) create mode 100644 drivers/perf/riscv_ctr.c
Signature · 1 line
2.43.0
PATCH v6 1/7 perf: Increase the maximum number of branches remove_loops() can process.
RISCV CTR extension supports a maximum depth of 256 last branch records. Currently remove_loops() can only process 127 entries at max. This leads to samples with more than 127 entries being skipped. This change simply updates the remove_loops() logic to be able to process 256 entries.
--- tools/perf/util/machine.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-)
tools/perf/util/machine.c +14 -7
@@ -2334,25 +2334,32 @@ static void save_iterations(struct iterations *iter, iter->cycles += be[i].flags.cycles; } -#define CHASHSZ 127 -#define CHASHBITS 7 -#define NO_ENTRY 0xff +#define CHASHBITS 8 +#define NO_ENTRY 0xffU -#define PERF_MAX_BRANCH_DEPTH 127 +#define PERF_MAX_BRANCH_DEPTH 256/* Remove loops. */ +/* Note: Last entry (i==ff) will never be checked against NO_ENTRY +* so it's safe to have an unsigned char array to process 256 entries +* without causing clash between last entry and NO_ENTRY value. +*/ static int remove_loops (struct branch_entry *l,int nr,struct iterations *iter) {int i, j, off; -unsigned char chash[CHASHSZ ]; +unsigned char chash[PERF_MAX_BRANCH_DEPTH ];memset (chash,NO_ENTRY ,sizeof (chash)); -BUG_ON (PERF_MAX_BRANCH_DEPTH >255 ); +BUG_ON (PERF_MAX_BRANCH_DEPTH >256 );for (i =0 ; i < nr; i++) { -int h =hash_64 (l[i].from,CHASHBITS ) %CHASHSZ ; +/* Remainder division by PERF_MAX_BRANCH_DEPTH is not +* needed as hash_64 will anyway limit the hash +* to CHASHBITS +*/ +int h =hash_64 (l[i].from,CHASHBITS );/* no collision handling for now */ if (chash[h] ==NO_ENTRY ) {
Signature · 1 line
2.43.0
PATCH v6 2/7 riscv: pmu: Add Control transfer records CSR definations.
In reply to Vikram SinghAdding CSR defines for RISCV Control Transfer Records extension [0] along with bit-field macros for each CSR.
[0]: https://github.com/riscv/riscv-control-transfer-records
--- arch/riscv/include/asm/csr.h | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+)
arch/riscv/include/asm/csr.h +83 -0
@@ -350,6 +350,85 @@#define CSR_SCOUNTOVF 0xda0 +/* M-mode Control Transfer Records CSRs */ +#define CSR_MCTRCTL 0x34e + +/* S-mode Control Transfer Records CSRs */ +#define CSR_SCTRCTL 0x14e +#define CSR_SCTRSTATUS 0x14f +#define CSR_SCTRDEPTH 0x15f + +/* VS-mode Control Transfer Records CSRs */ +#define CSR_VSCTRCTL 0x24e + +/* xctrtl CSR bits. */ +#define CTRCTL_U_ENABLE _AC(0x1, UL) +#define CTRCTL_S_ENABLE _AC(0x2, UL) +#define CTRCTL_M_ENABLE _AC(0x4, UL) +#define CTRCTL_RASEMU _AC(0x80, UL) +#define CTRCTL_STE _AC(0x100, UL) +#define CTRCTL_MTE _AC(0x200, UL) +#define CTRCTL_BPFRZ _AC(0x800, UL) +#define CTRCTL_LCOFIFRZ _AC(0x1000, UL) +#define CTRCTL_EXCINH _AC(0x200000000, UL) +#define CTRCTL_INTRINH _AC(0x400000000, UL) +#define CTRCTL_TRETINH _AC(0x800000000, UL) +#define CTRCTL_NTBREN _AC(0x1000000000, UL) +#define CTRCTL_TKBRINH _AC(0x2000000000, UL) +#define CTRCTL_INDCALL_INH _AC(0x10000000000, UL) +#define CTRCTL_DIRCALL_INH _AC(0x20000000000, UL) +#define CTRCTL_INDJUMP_INH _AC(0x40000000000, UL) +#define CTRCTL_DIRJUMP_INH _AC(0x80000000000, UL) +#define CTRCTL_CORSWAP_INH _AC(0x100000000000, UL) +#define CTRCTL_RET_INH _AC(0x200000000000, UL) +#define CTRCTL_INDOJUMP_INH _AC(0x400000000000, UL) +#define CTRCTL_DIROJUMP_INH _AC(0x800000000000, UL) + +/* sctrstatus CSR bits. */ +#define SCTRSTATUS_WRPTR_MASK 0xFF +#define SCTRSTATUS_FROZEN _AC(0x80000000, UL) + +#ifdef CONFIG_RISCV_M_MODE +#define CTRCTL_KERNEL_ENABLE CTRCTL_M_ENABLE +#else +#define CTRCTL_KERNEL_ENABLE CTRCTL_S_ENABLE +#endif + +/* sctrdepth CSR bits. */ +#define SCTRDEPTH_MASK 0x7 + +#define SCTRDEPTH_MIN 0x0/* 16 Entries. */ +#define SCTRDEPTH_MAX 0x4/* 256 Entries. */ + +/* ctrsource, ctrtarget and ctrdata CSR bits. */ +#define CTRSOURCE_VALID 0x1ULL +#define CTRTARGET_MISP 0x1ULL + +#define CTRDATA_TYPE_MASK 0xF +#define CTRDATA_CCV 0x8000 +#define CTRDATA_CCM_MASK 0xFFF0000 +#define CTRDATA_CCE_MASK 0xF0000000 + +#define CTRDATA_TYPE_NONE 0 +#define CTRDATA_TYPE_EXCEPTION 1 +#define CTRDATA_TYPE_INTERRUPT 2 +#define CTRDATA_TYPE_TRAP_RET 3 +#define CTRDATA_TYPE_NONTAKEN_BRANCH 4 +#define CTRDATA_TYPE_TAKEN_BRANCH 5 +#define CTRDATA_TYPE_RESERVED_6 6 +#define CTRDATA_TYPE_RESERVED_7 7 +#define CTRDATA_TYPE_INDIRECT_CALL 8 +#define CTRDATA_TYPE_DIRECT_CALL 9 +#define CTRDATA_TYPE_INDIRECT_JUMP 10 +#define CTRDATA_TYPE_DIRECT_JUMP 11 +#define CTRDATA_TYPE_CO_ROUTINE_SWAP 12 +#define CTRDATA_TYPE_RETURN 13 +#define CTRDATA_TYPE_OTHER_INDIRECT_JUMP 14 +#define CTRDATA_TYPE_OTHER_DIRECT_JUMP 15 + +#define CTR_ENTRIES_FIRST 0x200 +#define CTR_ENTRIES_LAST 0x2ff +#define CSR_SSTATUS 0x100#define CSR_SIE 0x104#define CSR_STVEC 0x105
@@ -563,6 +642,8 @@# define CSR_TOPEI CSR_MTOPEI# define CSR_TOPI CSR_MTOPI +# define CSR_CTRCTL CSR_MCTRCTL +# define SR_IE SR_MIE# define SR_PIE SR_MPIE# define SR_PP SR_MPP
@@ -593,6 +674,8 @@# define CSR_TOPEI CSR_STOPEI# define CSR_TOPI CSR_STOPI +# define CSR_CTRCTL CSR_SCTRCTL +# define SR_IE SR_SIE# define SR_PIE SR_SPIE# define SR_PP SR_SPP
Signature · 1 line
2.43.0
PATCH v6 3/7 riscv: Add Control Transfer Records extension parsing
In reply to Vikram SinghAdding CTR extension in ISA extension map to lookup for extension availability.
--- arch/riscv/include/asm/hwcap.h | 4 ++++ arch/riscv/kernel/cpufeature.c | 2 ++ 2 files changed, 6 insertions(+)
arch/riscv/include/asm/hwcap.h +4 -0
@@ -126,6 +126,8 @@#define RISCV_ISA_EXT_ZIC64B 116#define RISCV_ISA_EXT_SV48 117#define RISCV_ISA_EXT_SV57 118 +#define RISCV_ISA_EXT_SMCTR 119 +#define RISCV_ISA_EXT_SSCTR 120#define RISCV_ISA_EXT_XLINUXENVCFG 127
@@ -136,10 +138,12 @@#define RISCV_ISA_EXT_SxAIA RISCV_ISA_EXT_SMAIA#define RISCV_ISA_EXT_SUPM RISCV_ISA_EXT_SMNPM#define RISCV_ISA_EXT_SxCSRIND RISCV_ISA_EXT_SMCSRIND +#define RISCV_ISA_EXT_SxCTR RISCV_ISA_EXT_SMCTR#else #define RISCV_ISA_EXT_SxAIA RISCV_ISA_EXT_SSAIA#define RISCV_ISA_EXT_SUPM RISCV_ISA_EXT_SSNPM#define RISCV_ISA_EXT_SxCSRIND RISCV_ISA_EXT_SSCSRIND +#define RISCV_ISA_EXT_SxCTR RISCV_ISA_EXT_SSCTR#endif #endif /* _ASM_RISCV_HWCAP_H */
arch/riscv/kernel/cpufeature.c +2 -0
@@ -649,6 +649,7 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = { riscv_ext_smcdeleg_validate),__RISCV_ISA_EXT_DATA (smcntrpmf,RISCV_ISA_EXT_SMCNTRPMF ),__RISCV_ISA_EXT_DATA (smcsrind,RISCV_ISA_EXT_SMCSRIND ), +__RISCV_ISA_EXT_DATA (smctr,RISCV_ISA_EXT_SMCTR ),__RISCV_ISA_EXT_DATA (smmpm,RISCV_ISA_EXT_SMMPM ),__RISCV_ISA_EXT_SUPERSET (smnpm,RISCV_ISA_EXT_SMNPM , riscv_xlinuxenvcfg_exts), __RISCV_ISA_EXT_DATA(smstateen, RISCV_ISA_EXT_SMSTATEEN),
@@ -656,6 +657,7 @@ const struct riscv_isa_ext_data riscv_isa_ext[] = {__RISCV_ISA_EXT_DATA_VALIDATE (ssccfg,RISCV_ISA_EXT_SSCCFG , riscv_ext_ssccfg_validate),__RISCV_ISA_EXT_DATA (sscofpmf,RISCV_ISA_EXT_SSCOFPMF ),__RISCV_ISA_EXT_DATA (sscsrind,RISCV_ISA_EXT_SSCSRIND ), +__RISCV_ISA_EXT_DATA (ssctr,RISCV_ISA_EXT_SSCTR ),__RISCV_ISA_EXT_SUPERSET (ssnpm,RISCV_ISA_EXT_SSNPM , riscv_xlinuxenvcfg_exts),__RISCV_ISA_EXT_DATA (ssqosid,RISCV_ISA_EXT_SSQOSID ), __RISCV_ISA_EXT_DATA(sstc, RISCV_ISA_EXT_SSTC),
Signature · 1 line
2.43.0
PATCH v6 4/7 riscv: pmu: Add infrastructure for Control Transfer Record
In reply to Vikram SinghTo support Control Transfer Records (CTR) extension, we need to extend the riscv_pmu framework with some basic infrastructure for branch stack sampling. Subsequent patches will use this to add support for CTR in the riscv_pmu_dev driver.
With CTR, the branches are stored into a hardware FIFO, which will be sampled by software when perf events overflow. A task may be context-switched between overflows, and to avoid leaking samples we need to clear the last task's records when a task is context-switched in. To do this we will be using the pmu::sched_task() callback added in this patch.
--- drivers/perf/riscv_pmu.c | 19 +++++++++++++++++++ drivers/perf/riscv_pmu_legacy.c | 2 ++ drivers/perf/riscv_pmu_sbi.c | 17 +++++++++++++++++ include/linux/perf/riscv_pmu.h | 20 ++++++++++++++++++-- 4 files changed, 56 insertions(+), 2 deletions(-)
drivers/perf/riscv_pmu.c +19 -0
@@ -157,6 +157,19 @@ u64 riscv_pmu_ctr_get_width_mask(struct perf_event *event)return GENMASK_ULL (cwidth,0 ); } +static void riscv_pmu_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in) +{ +struct riscv_pmu *pmu; + +if (!pmu_ctx) +return ; + + pmu =to_riscv_pmu (pmu_ctx->pmu); +if (pmu->sched_task) + pmu->sched_task (pmu_ctx, task, sched_in); +} +u64 riscv_pmu_event_update (struct perf_event *event) {struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu);
@@ -269,6 +282,8 @@ static int riscv_pmu_add(struct perf_event *event, int flags) cpuc->events[idx] = event; cpuc->n_events++; hwc->state =PERF_HES_UPTODATE |PERF_HES_STOPPED ; +if (rvpmu->ctr_add) + rvpmu->ctr_add (event, flags);if (flags &PERF_EF_START )riscv_pmu_start (event,PERF_EF_RELOAD );
@@ -290,6 +305,8 @@ static void riscv_pmu_del(struct perf_event *event, int flags)if (rvpmu->ctr_stop) rvpmu->ctr_stop (event,RISCV_PMU_STOP_FLAG_RESET ); cpuc->n_events--; +if (rvpmu->ctr_del) + rvpmu->ctr_del (event, flags);if (rvpmu->ctr_clear_idx) rvpmu->ctr_clear_idx (event);perf_event_update_userpage (event);
@@ -402,6 +419,7 @@ struct riscv_pmu *riscv_pmu_alloc(void)for_each_possible_cpu (cpuid) { cpuc =per_cpu_ptr (pmu->hw_events, cpuid); cpuc->n_events =0 ; + cpuc->ctr_users =0 ;for (i =0 ; i <RISCV_MAX_COUNTERS ; i++) cpuc->events[i] =NULL ; cpuc->snapshot_addr =NULL ;
@@ -416,6 +434,7 @@ struct riscv_pmu *riscv_pmu_alloc(void) .start = riscv_pmu_start, .stop = riscv_pmu_stop, .read = riscv_pmu_read, + .sched_task = riscv_pmu_sched_task, };return pmu;
drivers/perf/riscv_pmu_legacy.c +2 -0
@@ -115,6 +115,8 @@ static void pmu_legacy_init(struct riscv_pmu *pmu)set_bit (RISCV_PMU_LEGACY_INSTRET , pmu->cmask); pmu->ctr_start = pmu_legacy_ctr_start; pmu->ctr_stop =NULL ; + pmu->ctr_add =NULL ; + pmu->ctr_del =NULL ; pmu->event_map = pmu_legacy_event_map; pmu->ctr_get_idx = pmu_legacy_ctr_get_idx; pmu->ctr_get_width = pmu_legacy_ctr_get_width;
drivers/perf/riscv_pmu_sbi.c +17 -0
@@ -825,6 +825,14 @@ static void pmu_sbi_reset_scounteren(void *arg) csr_read(CSR_SCOUNTEREN) & ~BIT(pmu_sbi_csr_index(event))); } +static void pmu_sbi_ctr_add (struct perf_event *event,int flags) +{ +} + +static void pmu_sbi_ctr_del (struct perf_event *event,int flags) +{ +} +static void pmu_sbi_ctr_start (struct perf_event *event,u64 ival) {struct sbiret ret;
@@ -885,6 +893,12 @@ static void pmu_sbi_ctr_stop(struct perf_event *event, unsigned long flag) } } +static void pmu_sbi_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in) +{ +/* Call CTR specific Sched hook. */ +} +static int pmu_sbi_find_num_ctrs (void ) {struct sbiret ret;
@@ -1506,6 +1520,8 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) pmu->pmu.attr_groups = riscv_pmu_attr_groups; pmu->pmu.parent = &pdev->dev;bitmap_copy (pmu->cmask, cmask,RISCV_MAX_COUNTERS ); + pmu->ctr_add = pmu_sbi_ctr_add; + pmu->ctr_del = pmu_sbi_ctr_del; pmu->ctr_start = pmu_sbi_ctr_start; pmu->ctr_stop = pmu_sbi_ctr_stop; pmu->event_map = pmu_sbi_event_map;
@@ -1517,6 +1533,7 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) pmu->event_mapped = pmu_sbi_event_mapped; pmu->event_unmapped = pmu_sbi_event_unmapped; pmu->csr_index = pmu_sbi_csr_index; + pmu->sched_task = pmu_sbi_sched_task; ret =riscv_pm_pmu_register (pmu);if (ret)
include/linux/perf/riscv_pmu.h +18 -2
@@ -28,6 +28,13 @@#define RISCV_PMU_CONFIG1_GUEST_EVENTS 0x1 +#define MAX_BRANCH_RECORDS 256 + +struct branch_records { +struct perf_branch_stack branch_stack; +struct perf_branch_entry branch_entries[MAX_BRANCH_RECORDS ]; +}; +struct cpu_hw_events {/* currently enabled events */ int n_events;
@@ -47,6 +54,10 @@ struct cpu_hw_events {bool snapshot_set_done;/* A shadow copy of the counter values to avoid clobbering during multiple SBI calls */ u64 snapshot_cval_shcopy[RISCV_MAX_COUNTERS ]; +/* Saved branch records. */ +struct branch_records *branches; +/* Active events requesting branch records */ +int ctr_users; };struct riscv_pmu {
@@ -60,17 +71,22 @@ struct riscv_pmu {int (*ctr_get_idx)(struct perf_event *event);int (*ctr_get_width)(int idx);void (*ctr_clear_idx)(struct perf_event *event); +void (*ctr_add)(struct perf_event *event,int flags); +void (*ctr_del)(struct perf_event *event,int flags);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); - +void (*sched_task)(struct perf_event_pmu_context *ctx,struct task_struct *task, +bool sched_in);struct cpu_hw_events __percpu *hw_events;struct hlist_node node;struct notifier_block riscv_pm_nb; + +unsigned int ctr_depth; };#define to_riscv_pmu (p) (container_of(p, struct riscv_pmu, pmu))
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v6 4/7] riscv: pmu: Add infrastructure for Control Transfer Record
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] riscv: pmu: incompatible event_init() pointer type and ignored return value --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] riscv: pmu: incompatible event_init() pointer type and ignored return value
--
commit 15d211fd87e46912144256300103f163e02625b4
Author: Vikram Singh <[email protected]>
riscv: pmu: Add infrastructure for Control Transfer Record
This commit extends the RISC-V PMU framework with callbacks and data structures for Control Transfer Record branch stack sampling.
Quoted 4 lines
include/linux/perf/riscv_pmu.h +0
-0
[ ... ]
include/linux/perf/riscv_pmu.h struct riscv_pmu { · line 79
Quoted 11 lines
include/linux/perf/riscv_pmu.h +3
-1@@ -60,17 +71,22 @@ struct riscv_pmu {int (*ctr_get_idx)(struct perf_event *event);int (*ctr_get_width)(int idx);void (*ctr_clear_idx)(struct perf_event *event); +void (*ctr_add)(struct perf_event *event,int flags); +void (*ctr_del)(struct perf_event *event,int flags);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);
[Severity: High]
Does changing event_init() to return int here break compilation with CONFIG_RISCV_PMU_SBI enabled?
pmu_sbi_event_init() in drivers/perf/riscv_pmu_sbi.c still returns void in this patch, so assigning pmu->event_init = pmu_sbi_event_init in pmu_sbi_device_probe() fails the build under -Werror=incompatible-pointer-types (breaking bisection until later commit "riscv: pmu: Integrate CTR Ext support in riscv_pmu_dev driver" updates pmu_sbi_event_init()).
In addition, riscv_pmu_event_init() in drivers/perf/riscv_pmu.c still ignores the return value of rvpmu->event_init(event), so errors returned by the backend callback are silently dropped.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH v6 5/7 riscv: pmu: Add driver for Control Transfer Records Ext
In reply to Vikram SinghThis adds support for CTR Ext defined in [0]. The extension allows to records a maximum for 256 last branch records.
CTR extension depends on s[m|s]csrind and Sscofpmf extensions.
--- MAINTAINERS | 2 + drivers/perf/Kconfig | 11 + drivers/perf/Makefile | 1 + drivers/perf/riscv_ctr.c | 608 +++++++++++++++++++++++++++++++++ include/linux/perf/riscv_pmu.h | 40 ++- 5 files changed, 661 insertions(+), 1 deletion(-) create mode 100644 drivers/perf/riscv_ctr.c
MAINTAINERS +2 -0
@@ -24220,8 +24220,10 @@ F: arch/riscv/boot/dts/sifive/ RISC-V PMU DRIVERS M: Atish Patra <[email protected]> R: Anup Patel <[email protected]> +R: Vikram Singh <[email protected]> L: [email protected] S: Supported +F: drivers/perf/riscv_ctr.c F: drivers/perf/riscv_pmu.c F: drivers/perf/riscv_pmu_legacy.c F: drivers/perf/riscv_pmu_sbi.c
drivers/perf/Kconfig +11 -0
@@ -129,6 +129,17 @@ config ANDES_CUSTOM_PMU If you don't know what to do here, say "Y". +config RISCV_CTR + bool "Enable support for Control Transfer Records (CTR)" + depends on PERF_EVENTS && RISCV_PMU + default y + help + Enable support for Control Transfer Records (CTR) which + allows recording branches, Jumps, Calls, returns etc taken in an + execution path. This also supports privilege based filtering. It + captures additional relevant information such as cycle count, + branch misprediction etc. + config ARM_PMU_ACPI depends on ARM_PMU && ACPI def_bool y
drivers/perf/Makefile +1 -0
@@ -21,6 +21,7 @@ obj-$(CONFIG_RISCV_PMU) += riscv_pmu.o obj-$(CONFIG_RISCV_PMU_LEGACY) += riscv_pmu_legacy.o obj-$(CONFIG_RISCV_PMU_SBI) += riscv_pmu_sbi.o obj-$(CONFIG_STARFIVE_STARLINK_PMU) += starfive_starlink_pmu.o +obj-$(CONFIG_RISCV_CTR) += riscv_ctr.o obj-$(CONFIG_THUNDERX2_PMU) += thunderx2_pmu.o obj-$(CONFIG_XGENE_PMU) += xgene_pmu.o obj-$(CONFIG_ARM_SPE_PMU) += arm_spe_pmu.o
drivers/perf/riscv_ctr.c new file +608 -0
608 lines not on this page · raw message
include/linux/perf/riscv_pmu.h +39 -1
@@ -54,7 +54,7 @@ struct cpu_hw_events {bool snapshot_set_done;/* A shadow copy of the counter values to avoid clobbering during multiple SBI calls */ u64 snapshot_cval_shcopy[RISCV_MAX_COUNTERS ]; -/* Saved branch records. */ +/* Saved branch records */ struct branch_records *branches;/* Active events requesting branch records */ int ctr_users;
@@ -108,6 +108,44 @@ int riscv_pmu_get_hpm_info(u32 *hw_ctr_width, u32 *num_hw_ctr);int riscv_pmu_get_event_info (u32 type,u64 config,u64 *econfig);#endif +static inline bool riscv_pmu_ctr_supported (struct riscv_pmu *pmu) +{ +return !!pmu->ctr_depth; +} +#endif /* CONFIG_RISCV_PMU */ +#ifdef CONFIG_RISCV_CTR + +bool riscv_pmu_ctr_valid (struct perf_event *event); +void riscv_pmu_ctr_consume (struct cpu_hw_events *cpuc,struct perf_event *event); +void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in); +void riscv_pmu_ctr_add (struct perf_event *event); +void riscv_pmu_ctr_del (struct perf_event *event); +void riscv_pmu_ctr_enable (struct perf_event *event); +void riscv_pmu_ctr_disable (struct perf_event *event); +void riscv_pmu_ctr_dying_cpu (void ); +void riscv_pmu_ctr_starting_cpu (void ); +int riscv_pmu_ctr_init (struct riscv_pmu *riscv_pmu); +void riscv_pmu_ctr_finish (struct riscv_pmu *riscv_pmu); + +#else + +static inline bool riscv_pmu_ctr_valid (struct perf_event *event) {return false; } +static inline void riscv_pmu_ctr_consume (struct cpu_hw_events *cpuc, +struct perf_event *event) { } +static inline void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *, +struct task_struct *task,bool sched_in) { } +static void riscv_pmu_ctr_add (struct perf_event *event) { } +static void riscv_pmu_ctr_del (struct perf_event *event) { } +static inline void riscv_pmu_ctr_enable (struct perf_event *event) { } +static inline void riscv_pmu_ctr_disable (struct perf_event *event) { } +static inline void riscv_pmu_ctr_dying_cpu (void ) { } +static inline void riscv_pmu_ctr_starting_cpu (void ) { } +static inline int riscv_pmu_ctr_init (struct riscv_pmu *riscv_pmu) {return 0 ; } +static inline void riscv_pmu_ctr_finish (struct riscv_pmu *riscv_pmu) { } + +#endif /* CONFIG_RISCV_CTR */ +#endif /* _RISCV_PMU_H */
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v6 5/7] riscv: pmu: Add driver for Control Transfer Records Ext
Thank you for your contribution! Sashiko AI review found 14 potential issues to consider: - [Critical] riscv: pmu: perf_ctx_data type confusion and missing RCU in CTR task context - [High] riscv…
Thank you for your contribution! Sashiko AI review found 14 potential issues to consider:
- [Critical] riscv: pmu: perf_ctx_data type confusion and missing RCU in CTR task context
- [High] riscv: pmu: NULL event->ctx->task dereference in riscv_pmu_ctr_add() and del()
- [High] riscv: pmu: inverted CTRDATA_CCV check and cycle truncation in ctr_get_cycles()
- [High] riscv: pmu: missing SxCSRIND check and hardcoded CSR_SIREG* in CTR helpers
- [High] riscv: pmu: unmerged CSR_CTRCTL without filtering and hardirq pr_warn()
- [High] riscv: pmu: PERF_SAMPLE_BRANCH_HV rejected when H extension is absent
- [Medium] riscv: pmu: missing CTR reset in riscv_pmu_ctr_restore() and unpaused save
- [Medium] riscv: pmu: 32-bit truncation of CSR_CTRCTL filter bits on CONFIG_32BIT
- [Medium] riscv: pmu: reserved SCTRDEPTH_MASK write and unclamped ctr_get_depth()
- [Medium] riscv: pmu: broken !CONFIG_RISCV_CTR stubs and guards in riscv_pmu.h
- [Medium] riscv: pmu: section mismatch and unsafe CSR probing in riscv_pmu_ctr_init()
- [Medium] riscv: pmu: call and return inhibit bits left set for CTRCTL_RASEMU
- [Medium] riscv: pmu: early return and HV kernel enable in branch_type_to_ctr()
- [Low] riscv: pmu: redundant CSR_ISELECT writes in get/set_ctr_regset() --
commit d1deee5d4cfeac01fee55cdd3cfa24ef329d2acc
Author: Vikram Singh <[email protected]>
riscv: pmu: Add driver for Control Transfer Records Ext
This commit adds a driver for the RISC-V Control Transfer Records (CTR) extension to support hardware branch stack sampling in perf.
drivers/perf/Kconfig config ANDES_CUSTOM_PMU · line 135
Quoted 12 lines
drivers/perf/Kconfig +4
-0@@ -129,6 +129,17 @@ config ANDES_CUSTOM_PMU If you don't know what to do here, say "Y". +config RISCV_CTR + bool "Enable support for Control Transfer Records (CTR)" + depends on PERF_EVENTS && RISCV_PMU + default y
[Severity: Medium]
Should RISCV_CTR depend on 64BIT, or access the upper half of CSR_CTRCTL via CSR_CTRCTLH on 32-bit builds?
On CONFIG_32BIT=y, csr_read() and csr_write() cast values to a 32-bit unsigned long, truncating bits 33..47 (CTR_BRANCH_FILTERS_INH) in riscv_pmu_ctr_enable() and check_available_filters().
[ ... ]
Quoted 6 lines
drivers/perf/riscv_ctr.c new file +0
-0@@ -0,0 +1,608 @@
[ ... ]
Quoted 19 lines
drivers/perf/riscv_ctr.c new file +19
-0+static inline u64 get_ctr_src_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_src_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG ,CTR_ENTRIES_FIRST , ctr_idx, value); +} + +static inline u64 get_ctr_tgt_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG2 ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_tgt_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG2 ,CTR_ENTRIES_FIRST , ctr_idx, value); +}
drivers/perf/riscv_ctr.c line 116
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +static inline u64 get_ctr_data_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG3 ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_data_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG3 ,CTR_ENTRIES_FIRST , ctr_idx, value); +}
[Severity: High]
Should these helpers pass CSR_IREG, CSR_IREG2 and CSR_IREG3 instead of hardcoding S-mode CSR_SIREG*, and should riscv_pmu_ctr_init(), riscv_pmu_ctr_starting_cpu() and riscv_pmu_ctr_dying_cpu() check riscv_isa_extension_available(NULL, SxCSRIND)?
csr_indirect_read() and csr_indirect_write() write CSR_ISELECT, which maps to CSR_MISELECT under CONFIG_RISCV_M_MODE. Also, neither cpufeature.c nor the CTR init and hotplug paths verify that SxCSRIND is present before accessing indirect CSRs, which will trap with an illegal instruction exception if SxCSRIND is absent.
[ ... ]
Quoted 4 lines
drivers/perf/riscv_ctr.c new file +4
-0+static inline unsigned int ctr_get_cycles (u64 ctr_data) +{ +const unsigned int cce =FIELD_GET (CTRDATA_CCE_MASK , ctr_data); +const unsigned int ccm =FIELD_GET (CTRDATA_CCM_MASK , ctr_data);
drivers/perf/riscv_ctr.c line 141
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +if (ctr_data &CTRDATA_CCV ) +return 0 ; + +/* Formula to calculate cycles from spec: (2^12 + CCM) << CCE-1 */ +if (cce >0 ) +return (4096 + ccm) << (cce -1 ); + +return FIELD_GET (CTRDATA_CCM_MASK , ctr_data); +}
[Severity: High]
Is the CTRDATA_CCV check inverted here? Per the CTR specification, CTRDATA_CCV is the Cycle Count Valid bit (1 when valid), so this returns 0 for every valid cycle count and decodes invalid ones.
Also, when cce >= 5, (4096 + ccm) << (cce - 1) exceeds 16 bits, and assigning it to the 16-bit entry->cycles bitfield in capture_ctr_flags() truncates the upper bits instead of clamping to U16_MAX.
Quoted 12 lines
drivers/perf/riscv_ctr.c new file +12
-0+static inline unsigned int ctr_get_type (u64 ctr_data) +{ +return FIELD_GET (CTRDATA_TYPE_MASK , ctr_data); +} + +static inline unsigned int ctr_get_depth (u64 ctr_depth) +{ +/* Depth table from CTR Spec: 2.4 sctrdepth. +* +* sctrdepth.depth Depth +* 000 - 16 +* 001 - 32
drivers/perf/riscv_ctr.c line 164
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+* 010 - 64 +* 011 - 128 +* 100 - 256 +* +* Depth = 16 * 2 ^ (ctrdepth.depth) +* or +* Depth = 16 << ctrdepth.depth. +*/ +return 16 <<FIELD_GET (SCTRDEPTH_MASK , ctr_depth); +}
[Severity: Medium]
Can ctr_get_depth() return more than MAX_BRANCH_RECORDS (256), and should riscv_pmu_ctr_init() and riscv_pmu_ctr_starting_cpu() write SCTRDEPTH_MAX (0x4) instead of SCTRDEPTH_MASK (0x7) to CSR_SCTRDEPTH?
Values 0x5..0x7 are reserved in sctrdepth.depth. Writing 0x7 is not guaranteed by WARL rules to select 256, and if CSR_SCTRDEPTH reports a value above 4, ctr_get_depth() returns up to 2048 and overflows cpuc->branches->branch_entries[256] and task_ctx->store[256].
Quoted 16 lines
drivers/perf/riscv_ctr.c new file +16
-0+static inline struct riscv_perf_task_context *task_context (void *ctx) +{ +return (struct riscv_perf_task_context *)ctx; +} + +/* Reads CTR entry at idx and stores it in entry struct. */ +static bool get_ctr_regset (struct ctr_regset *entry,unsigned int idx) +{ + entry->src =get_ctr_src_reg (idx); + +if (!ctr_record_valid (entry->src)) +return false; + + entry->src = entry->src; + entry->target =get_ctr_tgt_reg (idx); + entry->ctr_data =get_ctr_data_reg (idx);
drivers/perf/riscv_ctr.c line 191
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +return true; +} + +static void set_ctr_regset (struct ctr_regset *entry,unsigned int idx) +{ +set_ctr_src_reg (idx, entry->src); +set_ctr_tgt_reg (idx, entry->target); +set_ctr_data_reg (idx, entry->ctr_data); +}
[Severity: Low]
Each call to get_ctr_*_reg() and set_ctr_*_reg() saves IRQs and writes CSR_ISELECT, even though selecting CTR_ENTRIES_FIRST + idx once in CSR_ISELECT exposes source, target and data across CSR_IREG, CSR_IREG2 and CSR_IREG3 simultaneously. get_ctr_regset() also has a redundant entry->src = entry->src assignment.
Quoted 9 lines
drivers/perf/riscv_ctr.c new file +9
-0+static u64 branch_type_to_ctr (int branch_type) +{ +u64 config =CTR_BRANCH_FILTERS_INH |CTRCTL_LCOFIFRZ ; + +if (branch_type &PERF_SAMPLE_BRANCH_USER ) + config |=CTRCTL_U_ENABLE ; + +if (branch_type &PERF_SAMPLE_BRANCH_KERNEL ) + config |=CTRCTL_KERNEL_ENABLE ;
drivers/perf/riscv_ctr.c line 211
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +if (branch_type &PERF_SAMPLE_BRANCH_HV ) { +if (riscv_isa_extension_available (NULL ,H )) + config |=CTRCTL_KERNEL_ENABLE ; + } + +if (branch_type &PERF_SAMPLE_BRANCH_ANY ) { + config &= ~CTR_BRANCH_FILTERS_INH ; +return config; + }
[Severity: Medium]
Does setting CTRCTL_KERNEL_ENABLE for PERF_SAMPLE_BRANCH_HV record host kernel branches even when PERF_SAMPLE_BRANCH_KERNEL is excluded?
Also, returning early on PERF_SAMPLE_BRANCH_ANY skips the PERF_SAMPLE_BRANCH_CALL_STACK check below, leaving CTRCTL_RASEMU unset when both flags are specified.
[ ... ]
drivers/perf/riscv_ctr.c line 230
Quoted 2 lines
drivers/perf/riscv_ctr.c new file +2
-0+if (branch_type &PERF_SAMPLE_BRANCH_CALL_STACK ) + config |=CTRCTL_RASEMU ;
[Severity: Medium]
Does PERF_SAMPLE_BRANCH_CALL_STACK also need to clear CTRCTL_INDCALL_INH, CTRCTL_DIRCALL_INH and CTRCTL_RET_INH?
When userspace enables LBR call-stack mode (such as perf record --call-graph lbr), it sets PERF_SAMPLE_BRANCH_CALL_STACK without separate call or return filter flags, so leaving those inhibit bits set in config suppresses all call and return records.
[ ... ]
drivers/perf/riscv_ctr.c line 339
Quoted 12 lines
drivers/perf/riscv_ctr.c new file +12
-0+bool riscv_pmu_ctr_valid (struct perf_event *event) +{ +u64 branch_type = event->attr.branch_sample_type; + +if (branch_type & ~allowed_filters) { +pr_debug_once ("Requested branch filters not supported 0x%llx\n" , + branch_type & ~allowed_filters); +return false; + } + +return true; +}
[Severity: High]
Does rejecting PERF_SAMPLE_BRANCH_HV when the H extension is absent break default branch sampling on non-H systems?
When userspace does not specify branch privilege bits, perf_copy_attr() automatically sets PERF_SAMPLE_BRANCH_HV whenever !attr->exclude_hv, so check_available_filters() omitting PERF_SAMPLE_BRANCH_HV on systems without H causes riscv_pmu_ctr_valid() to reject standard commands like perf record -j any.
[ ... ]
Quoted 19 lines
drivers/perf/riscv_ctr.c new file +19
-0+static void riscv_pmu_ctr_restore (void *ctx) +{ +if (task_context (ctx)->stack_state ==CTR_STATE_NONE || +task_context (ctx)->callstack_users ==0 ) { +return ; + } + +riscv_pmu_ctr_reset (); +__riscv_pmu_ctr_restore (ctx); + +task_context (ctx)->stack_state =CTR_STATE_NONE ; +} + +static void __riscv_pmu_ctr_save (void *ctx,unsigned int depth) +{ +struct riscv_perf_task_context *task_ctx = ctx; +struct ctr_regset *dst; +unsigned int i; +
drivers/perf/riscv_ctr.c line 399
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+for (i =0 ; i < depth; i++) { + dst = &task_ctx->store[i]; +if (!get_ctr_regset (dst, i)) +break ; + } + + task_ctx->num_entries = i; + + task_ctx->ctr_status =csr_read (CSR_SCTRSTATUS ); +}
[Severity: Medium]
When riscv_pmu_ctr_restore() returns early because stack_state is CTR_STATE_NONE or callstack_users is 0, riscv_pmu_ctr_sched_task() returns immediately without calling riscv_pmu_ctr_reset(). Doesn't that leave the previous task's CTR records in hardware for the incoming task?
Also, unlike ctr_read_entries(), __riscv_pmu_ctr_save() and __riscv_pmu_ctr_restore() read and write CTR registers without clearing CTR_BRANCH_ENABLE_BITS in CSR_CTRCTL, so branches taken inside the save/restore loops can clobber the CTR entries when kernel recording is enabled.
[ ... ]
Quoted 44 lines
drivers/perf/riscv_ctr.c new file +44
-0+void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (pmu_ctx->pmu); +struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); +void *task_ctx; + +if (!cpuc->ctr_users) +return ; + +/* Save branch records in task_ctx on sched out */ + task_ctx = pmu_ctx ? task->perf_ctx_data :NULL ; +if (task_ctx) { +if (sched_in) +riscv_pmu_ctr_restore (task_ctx); +else +riscv_pmu_ctr_save (task_ctx, rvpmu->ctr_depth); +return ; + } + +/* Reset branch records on sched in */ +if (sched_in) +riscv_pmu_ctr_reset (); +} + +static inline bool branch_user_callstack (unsigned int br_type) +{ +return (br_type &PERF_SAMPLE_BRANCH_USER ) && + (br_type &PERF_SAMPLE_BRANCH_CALL_STACK ); +} + +void riscv_pmu_ctr_add (struct perf_event *event) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu); +struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); + +if (branch_user_callstack (event->attr.branch_sample_type) && + event->ctx->task->perf_ctx_data) +task_context (event->ctx->task->perf_ctx_data)->callstack_users++; + +perf_sched_cb_inc (event->pmu); + +if (!cpuc->ctr_users++) +riscv_pmu_ctr_reset ();
drivers/perf/riscv_ctr.c line 476
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+} + +void riscv_pmu_ctr_del (struct perf_event *event) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu); +struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); + +if (branch_user_callstack (event->attr.branch_sample_type) && + event->ctx->task->perf_ctx_data) +task_context (event->ctx->task->perf_ctx_data)->callstack_users--;
[Severity: Critical]
Isn't task->perf_ctx_data an RCU-protected pointer to struct perf_ctx_data, whose ->data member holds the struct riscv_perf_task_context allocated from pmu->task_ctx_cache?
Passing task->perf_ctx_data directly to task_context(), riscv_pmu_ctr_save() and riscv_pmu_ctr_restore() without rcu_dereference() or dereferencing cd->data treats the 40-byte struct perf_ctx_data wrapper as a 6168-byte struct riscv_perf_task_context. Updating callstack_users corrupts cd->rcu_head, and __riscv_pmu_ctr_save() writes up to 256 ctr_regset entries past the end of struct perf_ctx_data into adjacent slab objects.
[Severity: High]
Can event->ctx->task be NULL in riscv_pmu_ctr_add() and riscv_pmu_ctr_del()?
For per-CPU events (pid == -1) configured with PERF_SAMPLE_BRANCH_USER | PERF_SAMPLE_BRANCH_CALL_STACK, event->ctx->task is NULL, so dereferencing event->ctx->task->perf_ctx_data causes a NULL pointer dereference when the event is scheduled.
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +perf_sched_cb_dec (event->pmu); + cpuc->ctr_users--; +WARN_ON_ONCE (cpuc->ctr_users <0 ); +} + +void riscv_pmu_ctr_enable (struct perf_event *event) +{ +u64 branch_type = event->attr.branch_sample_type; +u64 ctr;
drivers/perf/riscv_ctr.c line 496
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ + ctr =branch_type_to_ctr (branch_type); +csr_write (CSR_CTRCTL , ctr); +} + +void riscv_pmu_ctr_disable (struct perf_event *event) +{ +/* Clear CTRCTL to disable the recording. */ +csr_write (CSR_CTRCTL ,0 ); +}
[Severity: High]
What happens when multiple CTR events are active on the same CPU? riscv_pmu_ctr_enable() overwrites CSR_CTRCTL with a single event's filter and riscv_pmu_ctr_disable() zeroes CSR_CTRCTL even when other CTR events are still active. Because ctr_read_entries() does not filter entries in software by privilege or branch type (and branch_type_to_ctr() clears CTRCTL_EXCINH, CTRCTL_INTRINH and CTRCTL_TRETINH even without PERF_SAMPLE_BRANCH_KERNEL), kernel branch addresses recorded for one event can be copied into a concurrent user-only event's sample buffer.
Also, in ctr_set_perf_entry_type(), CTRDATA_TYPE_CO_ROUTINE_SWAP maps to PERF_BR_UNKNOWN and triggers an un-ratelimited pr_warn() in hardirq context (up to 256 times per PMU overflow interrupt) whenever userspace executes coroutine-swap jalr instructions under PERF_SAMPLE_BRANCH_ANY | PERF_SAMPLE_BRANCH_TYPE_SAVE.
Quoted 28 lines
drivers/perf/riscv_ctr.c new file +28
-0+ +/* +* Check for hardware supported perf filters here. To avoid missing +* any new added filter in perf, we do a BUILD_BUG_ON check, so make sure +* to update CTR_ALLOWED_BRANCH_FILTERS or CTR_EXCLUDE_BRANCH_FILTERS +* defines when adding support for it in below function. +*/ +static void __init check_available_filters (void ) +{ +u64 ctr_ctl; + +/* +* Ensure both perf branch filter allowed and exclude +* masks are always in sync with the generic perf ABI. +*/ +BUILD_BUG_ON (CTR_PERF_BRANCH_FILTERS != (PERF_SAMPLE_BRANCH_MAX -1 )); + + allowed_filters =PERF_SAMPLE_BRANCH_USER | +PERF_SAMPLE_BRANCH_KERNEL | +PERF_SAMPLE_BRANCH_ANY | +PERF_SAMPLE_BRANCH_HW_INDEX | +PERF_SAMPLE_BRANCH_NO_FLAGS | +PERF_SAMPLE_BRANCH_NO_CYCLES | +PERF_SAMPLE_BRANCH_TYPE_SAVE ; + +csr_write (CSR_CTRCTL , ~0 ); + ctr_ctl =csr_read (CSR_CTRCTL ); +csr_write (CSR_CTRCTL ,0 );
[ ... ]
Quoted 7 lines
drivers/perf/riscv_ctr.c new file +7
-0+int riscv_pmu_ctr_init (struct riscv_pmu *riscv_pmu) +{ +size_t size =sizeof (struct riscv_perf_task_context ); + +if (!riscv_isa_extension_available (NULL , SxCTR) || + !riscv_isa_extension_available (NULL ,SSCOFPMF )) +return 0 ;
drivers/perf/riscv_ctr.c line 590
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ + riscv_pmu->pmu.task_ctx_cache = +kmem_cache_create ("ctr_task_ctx" , size,sizeof (u64),0 ,NULL ); +if (!riscv_pmu->pmu.task_ctx_cache) +return -ENOMEM ; + +check_available_filters (); + + /* Set depth to maximum. */\n> + csr_write(CSR_SCTRDEPTH, SCTRDEPTH_MASK); + riscv_pmu->ctr_depth =ctr_get_depth (csr_read (CSR_SCTRDEPTH ));
[Severity: Medium]
Calling __init check_available_filters() from non-__init riscv_pmu_ctr_init() causes a section mismatch warning and will execute freed .init.text if PMU probe is deferred or rebound after boot.
In addition, check_available_filters() and riscv_pmu_ctr_init() write ~0 to CSR_CTRCTL (temporarily setting CTRCTL_U_ENABLE and CTRCTL_KERNEL_ENABLE) and probe per-CPU CSRs in preemptible context without disabling preemption or calling riscv_pmu_ctr_reset(). check_available_filters() also checks whether each filter's own inhibit bit is writable rather than the complement inhibit bits that branch_type_to_ctr() relies on, and riscv_pmu_ctr_valid() never checks that at least one branch type filter is set in branch_type.
[ ... ]
Quoted 29 lines
include/linux/perf/riscv_pmu.h +19
-0@@ -108,6 +108,44 @@ int riscv_pmu_get_hpm_info(u32 *hw_ctr_width, u32 *num_hw_ctr);int riscv_pmu_get_event_info (u32 type,u64 config,u64 *econfig);#endif +static inline bool riscv_pmu_ctr_supported (struct riscv_pmu *pmu) +{ +return !!pmu->ctr_depth; +} +#endif /* CONFIG_RISCV_PMU */ +#ifdef CONFIG_RISCV_CTR + +bool riscv_pmu_ctr_valid (struct perf_event *event); +void riscv_pmu_ctr_consume (struct cpu_hw_events *cpuc,struct perf_event *event); +void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in); +void riscv_pmu_ctr_add (struct perf_event *event); +void riscv_pmu_ctr_del (struct perf_event *event); +void riscv_pmu_ctr_enable (struct perf_event *event); +void riscv_pmu_ctr_disable (struct perf_event *event); +void riscv_pmu_ctr_dying_cpu (void ); +void riscv_pmu_ctr_starting_cpu (void ); +int riscv_pmu_ctr_init (struct riscv_pmu *riscv_pmu); +void riscv_pmu_ctr_finish (struct riscv_pmu *riscv_pmu);
include/linux/perf/riscv_pmu.h int riscv_pmu_get_hpm_info(u32 *hw_ctr_width, u32 *num_hw_ctr); · line 141
Quoted 10 lines
include/linux/perf/riscv_pmu.h +10
-0+ +#else + +static inline bool riscv_pmu_ctr_valid (struct perf_event *event) {return false; } +static inline void riscv_pmu_ctr_consume (struct cpu_hw_events *cpuc, +struct perf_event *event) { } +static inline void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *, +struct task_struct *task,bool sched_in) { } +static void riscv_pmu_ctr_add (struct perf_event *event) { } +static void riscv_pmu_ctr_del (struct perf_event *event) { }
[Severity: Medium]
Does this build when CONFIG_RISCV_CTR=n or CONFIG_RISCV_PMU=n?
In the !CONFIG_RISCV_CTR stubs, riscv_pmu_ctr_sched_task() omits the first parameter name (which fails under -std=gnu11), and riscv_pmu_ctr_add() and riscv_pmu_ctr_del() are missing inline (triggering -Wunused-function warnings). Also, placing this block outside #ifdef CONFIG_RISCV_PMU references struct cpu_hw_events and struct riscv_pmu when they have not been declared.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
PATCH v6 6/7 riscv: pmu: Integrate CTR Ext support in riscv_pmu_dev driver
In reply to Vikram SinghThis integrates recently added CTR ext support in riscv_pmu_dev driver to enable branch stack sampling using PMU events.
This mainly adds CTR enable/disable callbacks in rvpmu_ctr_stop() and rvpmu_ctr_start() function to start/stop branch recording along with the event.
PMU overflow handler rvpmu_ovf_handler() is also updated to sample CTR entries in case of the overflow for the particular event programmed to records branches. The recorded entries are fed to core perf for further processing.
--- drivers/perf/riscv_pmu.c | 2 +- drivers/perf/riscv_pmu_sbi.c | 72 ++++++++++++++++++++++++++++++++++-- 2 files changed, 70 insertions(+), 4 deletions(-)
drivers/perf/riscv_pmu.c +1 -1
@@ -327,7 +327,7 @@ static int riscv_pmu_event_init(struct perf_event *event)uint64_t cmask;/* driver does not support branch stack sampling */ -if (has_branch_stack (event)) +if (has_branch_stack (event) && !riscv_pmu_ctr_supported (rvpmu))return -EOPNOTSUPP ; hwc->flags =0 ;
drivers/perf/riscv_pmu_sbi.c +69 -3
156 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v6 6/7] riscv: pmu: Integrate CTR Ext support in riscv_pmu_dev driver
Thank you for your contribution! Sashiko AI review found 9 potential issues to consider: - [Critical] riscv: pmu: perf_ctx_data type confusion and OOB write in CTR callbacks - [High] riscv: pmu…
Thank you for your contribution! Sashiko AI review found 9 potential issues to consider:
- [Critical] riscv: pmu: perf_ctx_data type confusion and OOB write in CTR callbacks
- [High] riscv: pmu: duplicate cpuhp_state_add_instance() in pmu_sbi_device_probe()
- [High] riscv: pmu: NULL event->ctx->task dereference in riscv_pmu_ctr_add()
- [Medium] riscv: pmu: IRQ cleanup bypassed on error in pmu_sbi_device_probe()
- [Medium] riscv: pmu: per-CPU branch_records leak in branch_records_alloc()
- [Medium] riscv: pmu: broken CTR state in pmu_sbi_ctr_stop() and pmu_sbi_ovf_handler()
- [Medium] riscv: pmu: premature -EOPNOTSUPP in pmu_sbi_event_map() before type check
- [Medium] riscv: pmu: section mismatch calling __init check_available_filters()
- [Medium] riscv: pmu: missing inline on riscv_pmu_ctr_add() and del() header stubs
--
commit e9fe3c69a6f658642dd8da7db09d885c5571874f
Author: Vikram Singh <[email protected]>
riscv: pmu: Integrate CTR Ext support in riscv_pmu_dev driver
This commit integrates Control Transfer Record (CTR) extension support into the RISC-V SBI PMU driver to enable branch stack sampling on PMU events.
Quoted 5 lines
drivers/perf/riscv_pmu_sbi.c +0
-0
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_event_map(struct perf_event *event, u64 *econfig) · line 686
Quoted 9 lines
drivers/perf/riscv_pmu_sbi.c +3
-0@@ -678,6 +678,9 @@ static int pmu_sbi_event_map(struct perf_event *event, u64 *econfig)*/ flush_work (&check_std_events_work); +if (needs_branch_stack (event) && !riscv_pmu_ctr_valid (event)) +return -EOPNOTSUPP ; +return riscv_pmu_get_event_info (type, config, econfig); }
[Severity: Medium]
Should this check come after riscv_pmu_get_event_info() verifies that event->attr.type belongs to this PMU?
Returning -EOPNOTSUPP before riscv_pmu_get_event_info() can return -ENOENT for an unhandled event type causes perf_init_event() to abort iterating through other registered PMUs when an event with branch filters not in allowed_filters targets another PMU.
drivers/perf/riscv_pmu_sbi.c static void pmu_sbi_reset_scounteren(void *arg) · line 841
Quoted 13 lines
drivers/perf/riscv_pmu_sbi.c +4
-0@@ -827,10 +830,14 @@ static void pmu_sbi_reset_scounteren(void *arg)static void pmu_sbi_ctr_add (struct perf_event *event,int flags) { +if (needs_branch_stack (event)) +riscv_pmu_ctr_add (event); }static void pmu_sbi_ctr_del (struct perf_event *event,int flags) { +if (needs_branch_stack (event)) +riscv_pmu_ctr_del (event); }
[Severity: High]
Can riscv_pmu_ctr_add() and riscv_pmu_ctr_del() dereference a NULL event->ctx->task on per-CPU events?
Nothing in event initialization rejects a per-CPU event (pid == -1, where event->ctx->task is NULL) configured with PERF_SAMPLE_BRANCH_USER | PERF_SAMPLE_BRANCH_CALL_STACK, and both helpers dereference event->ctx->task without a NULL check:
drivers/perf/riscv_ctr.c:riscv_pmu_ctr_add() {
...
if (branch_user_callstack(event->attr.branch_sample_type) &&
event->ctx->task->perf_ctx_data)
task_context(event->ctx->task->perf_ctx_data)->callstack_users++;
...
}In addition, when CONFIG_RISCV_CTR is disabled, the stub definitions of riscv_pmu_ctr_add() and riscv_pmu_ctr_del() in include/linux/perf/riscv_pmu.h are missing the inline keyword:
include/linux/perf/riscv_pmu.h:
static void riscv_pmu_ctr_add(struct perf_event *event) { } static void riscv_pmu_ctr_del(struct perf_event *event) { }
This triggers -Wunused-function warnings in translation units that include the header without calling them.
[ ... ]
Quoted 22 lines
drivers/perf/riscv_pmu_sbi.c +4
-1@@ -864,6 +875,9 @@ static void pmu_sbi_ctr_stop(struct perf_event *event, unsigned long flag)struct cpu_hw_events *cpu_hw_evt =this_cpu_ptr (pmu->hw_events);struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr; +if (needs_branch_stack (event) && flag !=RISCV_PMU_STOP_FLAG_RESET ) +riscv_pmu_ctr_disable (event); +if ((hwc->flags &PERF_EVENT_FLAG_USER_ACCESS ) && (hwc->flags &PERF_EVENT_FLAG_USER_READ_CNT ))pmu_sbi_reset_scounteren ((void *)event);@@ -896,7 +910,7 @@ static void pmu_sbi_ctr_stop(struct perf_event *event, unsigned long flag)static void pmu_sbi_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task,bool sched_in) { -/* Call CTR specific Sched hook. */ +riscv_pmu_ctr_sched_task (pmu_ctx, task, sched_in); }static int pmu_sbi_find_num_ctrs (void )@@ -1179,6 +1193,12 @@ static irqreturn_t pmu_sbi_ovf_handler(int irq, void *dev) hw_evt->state |=PERF_HES_UPTODATE ;perf_sample_data_init (&data,0 , hw_evt->last_period);
drivers/perf/riscv_pmu_sbi.c static irqreturn_t pmu_sbi_ovf_handler(int irq, void *dev) · line 1204
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +6
-0if (riscv_pmu_event_set_period (event)) { +if (needs_branch_stack (event)) { +riscv_pmu_ctr_consume (cpu_hw_evt, event); +perf_sample_save_brstack (&data, event, + &cpu_hw_evt->branches->branch_stack,NULL ); + } +/* * Unlike other ISAs, RISC-V don't have to disable interrupts * to avoid throttling here. As per the specification, the
[Severity: Medium]
Can pmu_sbi_ctr_stop() and pmu_sbi_ovf_handler() leave CTR disabled, frozen, or recording kernel branches when multiple events or multi-part sample periods are active?
In pmu_sbi_ctr_stop(), riscv_pmu_ctr_disable() unconditionally clears CSR_CTRCTL even if other active branch-sampling events remain on the CPU (cpu_hw_evt->ctr_users > 1).
In pmu_sbi_ovf_handler(), hardware sets SCTRSTATUS_FROZEN on any LCOFI because CTRCTL_LCOFIFRZ is enabled, but SCTRSTATUS_FROZEN is only cleared inside riscv_pmu_ctr_consume(). If a co-scheduled non-branch counter overflows or riscv_pmu_event_set_period() returns 0 on an intermediate overflow, SCTRSTATUS_FROZEN stays set when pmu_sbi_start_overflow_mask() restarts the counters. Conversely, when riscv_pmu_ctr_consume() does run inside the loop, ctr_read_entries() re-enables CTR_BRANCH_ENABLE_BITS and clears SCTRSTATUS_FROZEN before perf_event_overflow() and pmu_sbi_start_overflow_mask() without resetting the CTR FIFO, so CTR records kernel branches while counters are still stopped and corrupts the buffer for any subsequent overflowed counter in the same interrupt.
[ ... ]
Quoted 17 lines
drivers/perf/riscv_pmu_sbi.c +12
-1@@ -1367,7 +1391,30 @@ static void riscv_pmu_destroy(struct riscv_pmu *pmu)cpuhp_state_remove_instance (CPUHP_AP_PERF_RISCV_STARTING , &pmu->node); } -static void pmu_sbi_event_init (struct perf_event *event) +static int branch_records_alloc (struct riscv_pmu *pmu) +{ +struct branch_records __percpu *tmp_alloc_ptr; +struct branch_records *records; +struct cpu_hw_events *events; +int cpu; + +if (!riscv_pmu_ctr_supported (pmu)) +return 0 ; + + tmp_alloc_ptr = alloc_percpu_gfp(struct branch_records, GFP_KERNEL); +if (!tmp_alloc_ptr)
drivers/perf/riscv_pmu_sbi.c static void riscv_pmu_destroy(struct riscv_pmu *pmu) · line 1415
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +10
-0+return -ENOMEM ; + +for_each_possible_cpu (cpu) { + events =per_cpu_ptr (pmu->hw_events, cpu); + records =per_cpu_ptr (tmp_alloc_ptr, cpu); + events->branches = records; + } + +return 0 ; +}
[Severity: Medium]
Does branch_records_alloc() leak tmp_alloc_ptr if a later step in pmu_sbi_device_probe() fails?
Only the per-CPU virtual pointers per_cpu_ptr(tmp_alloc_ptr, cpu) are saved in events->branches, while the __percpu base pointer tmp_alloc_ptr needed by free_percpu() is discarded on return and never freed by any error unwind label or teardown helper.
Quoted 6 lines
drivers/perf/riscv_pmu_sbi.c +2
-0+ +static int pmu_sbi_event_init (struct perf_event *event) {/* * The permissions are set at event_init so that we do not depend
drivers/perf/riscv_pmu_sbi.c static void pmu_sbi_event_init(struct perf_event *event) · line 1434
Quoted 9 lines
drivers/perf/riscv_pmu_sbi.c +5
-0@@ -1379,6 +1426,11 @@ static void pmu_sbi_event_init(struct perf_event *event) event->hw.flags |=PERF_EVENT_FLAG_USER_ACCESS ; else event->hw.flags |= PERF_EVENT_FLAG_LEGACY; + +if (branch_sample_call_stack (event)) + event->attach_state |=PERF_ATTACH_TASK_DATA ; + +return 0 ; }
[Severity: Critical]
Does setting PERF_ATTACH_TASK_DATA cause riscv_pmu_ctr_sched_task(), riscv_pmu_ctr_add(), and riscv_pmu_ctr_del() to write struct riscv_perf_task_context into the struct perf_ctx_data wrapper?
When PERF_ATTACH_TASK_DATA is set, attach_perf_ctx_data() stores a 40-byte struct perf_ctx_data wrapper in task->perf_ctx_data and places the PMU's struct riscv_perf_task_context allocation from pmu->task_ctx_cache in task->perf_ctx_data->data. However, riscv_pmu_ctr_add(), riscv_pmu_ctr_del(), and riscv_pmu_ctr_sched_task() access task->perf_ctx_data directly without rcu_read_lock()/rcu_dereference() and without dereferencing ->data:
drivers/perf/riscv_ctr.c:riscv_pmu_ctr_sched_task() {
...
/* Save branch records in task_ctx on sched out */
task_ctx = pmu_ctx ? task->perf_ctx_data : NULL;
if (task_ctx) {
if (sched_in)
riscv_pmu_ctr_restore(task_ctx);
else
riscv_pmu_ctr_save(task_ctx, rvpmu->ctr_depth);
return;
}
...
}When a task monitored with PERF_SAMPLE_BRANCH_USER | PERF_SAMPLE_BRANCH_CALL_STACK schedules out, riscv_pmu_ctr_save() writes up to 6168 bytes into the 40-byte struct perf_ctx_data slab object, corrupting its ctx_cache and data pointers and adjacent slab objects.
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_device_probe(struct platform_device *pdev) · line 1575
Quoted 12 lines
drivers/perf/riscv_pmu_sbi.c +3
-1static void pmu_sbi_event_mapped (struct perf_event *event,struct mm_struct *mm)@@ -1516,9 +1568,16 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) pmu->pmu.capabilities |=PERF_PMU_CAP_NO_EXCLUDE ; } irq_requested = (ret ==0 ); - pmu->pmu.attr_groups = riscv_pmu_attr_groups; pmu->pmu.parent = &pdev->dev; + ret =riscv_pmu_ctr_init (pmu); +if (ret) + goto out_free;
[Severity: Medium]
Does calling riscv_pmu_ctr_init() from pmu_sbi_device_probe() cause a section mismatch with check_available_filters()?
pmu_sbi_device_probe() and riscv_pmu_ctr_init() live in .text, whereas check_available_filters() in drivers/perf/riscv_ctr.c is marked __init, so probing the driver after init memory is freed will execute freed .init.text.
Quoted 9 lines
drivers/perf/riscv_pmu_sbi.c +5
-0+ + ret =branch_records_alloc (pmu); +if (ret) + goto out_ctr_finish; +bitmap_copy (pmu->cmask, cmask,RISCV_MAX_COUNTERS ); pmu->ctr_add = pmu_sbi_ctr_add; pmu->ctr_del = pmu_sbi_ctr_del;
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_device_probe(struct platform_device *pdev) · line 1603
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +4
-0@@ -1535,6 +1594,10 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) pmu->csr_index = pmu_sbi_csr_index; pmu->sched_task = pmu_sbi_sched_task; + ret =cpuhp_state_add_instance (CPUHP_AP_PERF_RISCV_STARTING , &pmu->node); +if (ret) + goto out_ctr_finish; + ret =riscv_pm_pmu_register (pmu);if (ret) goto out_destroy;
[Severity: High]
Does this register &pmu->node with CPUHP_AP_PERF_RISCV_STARTING twice in pmu_sbi_device_probe()?
pmu_sbi_device_probe() already registers &pmu->node after register_sysctl():
drivers/perf/riscv_pmu_sbi.c:pmu_sbi_device_probe() {
...
register_sysctl("kernel", sbi_pmu_sysctl_table);
ret = cpuhp_state_add_instance(CPUHP_AP_PERF_RISCV_STARTING, &pmu->node);
if (ret)
goto out_unregister;
...
}Calling cpuhp_state_add_instance() twice with the same struct hlist_node runs pmu_sbi_starting_cpu() twice on all present CPUs (the first time before SBI PMU snapshot shared memory is set up) and links pmu->node.next to itself in __cpuhp_state_add_instance_cpuslocked(), corrupting the hotplug state's hlist into a circular loop.
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_device_probe(struct platform_device *pdev) · line 1663
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +3
-0@@ -1592,6 +1655,9 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) riscv_pmu_irq =0 ; } +out_ctr_finish: +riscv_pmu_ctr_finish (pmu); + out_free:free_percpu (pmu->hw_events);kfree (pmu_ctr_list);
[Severity: Medium]
Does jumping to out_ctr_finish or out_free after pmu_sbi_setup_irqs() leave riscv_pmu_irq registered while freeing pmu->hw_events?
out_ctr_finish and out_free are placed below the irq_requested teardown block in out_destroy, so if riscv_pmu_ctr_init(), branch_records_alloc(), or cpuhp_state_add_instance() fails, free_percpu(pmu->hw_events) frees the per-CPU dev_id token while the per-CPU IRQ and its mapping remain registered.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH v6 7/7 dt-bindings: riscv: add Sxctr ISA extension description
In reply to Vikram SinghAdd the S[m|s]ctr ISA extension description.
--- .../devicetree/bindings/riscv/extensions.yaml | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+)
Documentation/devicetree/bindings/riscv/extensions.yaml +29 -0
@@ -202,6 +202,13 @@ properties: mechanism in M-mode as ratified in the 20240326 version of the privileged ISA specification. + - const: smctr + description: | + The standard Smctr supervisor-level extension for the machine mode + to enable recording limited branch history in a register-accessible + internal core storage as ratified at commit 9c87013 ("Merge pull + request #44 from riscv/issue-42-fix") of riscv-control-transfer-records. + - const: smmpm description: | The standard Smmpm extension for M-mode pointer masking as
@@ -263,6 +270,13 @@ properties: mechanism in S-mode as ratified in the 20240326 version of the privileged ISA specification. + - const: ssctr + description: | + The standard Ssctr supervisor-level extension for recording limited + branch history in a register-accessible internal core storage as + ratified at commit 9c87013 ("Merge pull request #44 from + riscv/issue-42-fix") of riscv-control-transfer-records. + - const: ssnpm description: | The standard Ssnpm extension for next-mode pointer masking as
@@ -1189,6 +1203,21 @@ properties: - contains: const: zicntr + # Smctr depends on Sscsrind + - if: + contains: + const: smctr + then: + contains: + const: sscsrind + # Ssctr depends on Sscsrind + - if: + contains: + const: ssctr + then: + contains: + const: sscsrind + allOf: # Zcf extension does not exist on rv64 - if:
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v6 7/7] dt-bindings: riscv: add Sxctr ISA extension description
Thank you for your contribution! Sashiko AI review found 7 potential issues to consider: - [Critical] perf: riscv: out-of-bounds slab corruption via direct cast of perf_ctx_data - [High] perf…
Thank you for your contribution! Sashiko AI review found 7 potential issues to consider:
- [Critical] perf: riscv: out-of-bounds slab corruption via direct cast of perf_ctx_data
- [High] perf: riscv: duplicate cpuhp_state_add_instance() in pmu_sbi_device_probe()
- [High] perf: riscv: NULL event->ctx->task dereference in riscv_pmu_ctr_add() and del()
- [Medium] perf: riscv: skipped riscv_pmu_ctr_reset() when riscv_pmu_ctr_restore() aborts
- [Medium] perf: riscv: missing inline on riscv_pmu_ctr_add() and del() stubs
- [Medium] perf: riscv: per-CPU branch_records leak in branch_records_alloc()
- [Medium] perf: riscv: missing SxCSRIND check and hardcoded CSR_SIREG* in CTR accessors
--
commit d8946febe7369229970ffb521dc938bff583395a
Author: Vikram Singh <[email protected]>
dt-bindings: riscv: add Sxctr ISA extension description
This series adds support for the RISC-V Control Transfer Records (CTR) extension, including CSR definitions, extension parsing, the CTR PMU driver, SBI PMU integration, and DeviceTree binding descriptions.
Quoted 6 lines
drivers/perf/riscv_ctr.c new file +0
-0@@ -0,0 +1,608 @@
[ ... ]
Quoted 19 lines
drivers/perf/riscv_ctr.c new file +19
-0+static inline u64 get_ctr_src_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_src_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG ,CTR_ENTRIES_FIRST , ctr_idx, value); +} + +static inline u64 get_ctr_tgt_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG2 ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_tgt_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG2 ,CTR_ENTRIES_FIRST , ctr_idx, value); +}
drivers/perf/riscv_ctr.c
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+ +static inline u64 get_ctr_data_reg (unsigned int ctr_idx) +{ +return csr_indirect_read (CSR_SIREG3 ,CTR_ENTRIES_FIRST , ctr_idx); +} + +static inline void set_ctr_data_reg (unsigned int ctr_idx,u64 value) +{ +return csr_indirect_write (CSR_SIREG3 ,CTR_ENTRIES_FIRST , ctr_idx, value); +}
[Severity: Medium]
Should these accessors use CSR_IREG, CSR_IREG2, and CSR_IREG3 instead of hardcoding the S-mode CSR_SIREG* registers, and should CTR initialization verify that SxCSRIND is available?
csr_indirect_read() and csr_indirect_write() select the target register via CSR_ISELECT (which maps to CSR_MISELECT under CONFIG_RISCV_M_MODE) and rely on the Smcsrind/Sscsrind extension. However, riscv_pmu_ctr_init(), riscv_pmu_ctr_starting_cpu(), and riscv_pmu_ctr_dying_cpu() only check for SxCTR and SSCOFPMF, so accessing these indirect CSRs when SxCSRIND is not implemented will trap with an illegal instruction.
[ ... ]
Quoted 12 lines
drivers/perf/riscv_ctr.c new file +12
-0+static void riscv_pmu_ctr_restore (void *ctx) +{ +if (task_context (ctx)->stack_state ==CTR_STATE_NONE || +task_context (ctx)->callstack_users ==0 ) { +return ; + } + +riscv_pmu_ctr_reset (); +__riscv_pmu_ctr_restore (ctx); + +task_context (ctx)->stack_state =CTR_STATE_NONE ; +}
[ ... ]
Quoted 14 lines
drivers/perf/riscv_ctr.c new file +14
-0+void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *pmu_ctx,struct task_struct *task, +bool sched_in) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (pmu_ctx->pmu); +struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); +void *task_ctx; + +if (!cpuc->ctr_users) +return ; + +/* Save branch records in task_ctx on sched out */ + task_ctx = pmu_ctx ? task->perf_ctx_data :NULL ; +if (task_ctx) { +if (sched_in)
drivers/perf/riscv_ctr.c
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+riscv_pmu_ctr_restore (task_ctx); + else + riscv_pmu_ctr_save(task_ctx, rvpmu->ctr_depth); +return ; + } + +/* Reset branch records on sched in */ +if (sched_in) +riscv_pmu_ctr_reset (); +}
[Severity: Medium]
Does returning early from riscv_pmu_ctr_restore() skip resetting the CTR registers on context switch-in?
When task_ctx is non-NULL and sched_in is true, riscv_pmu_ctr_sched_task() calls riscv_pmu_ctr_restore() and immediately returns. If stack_state is CTR_STATE_NONE (such as on the task's first schedule-in) or callstack_users is 0, riscv_pmu_ctr_restore() returns before calling riscv_pmu_ctr_reset(), leaving the previous task's branch records in the hardware registers.
Quoted 24 lines
drivers/perf/riscv_ctr.c new file +24
-0+static inline bool branch_user_callstack (unsigned int br_type) +{ +return (br_type &PERF_SAMPLE_BRANCH_USER ) && + (br_type &PERF_SAMPLE_BRANCH_CALL_STACK ); +} + +void riscv_pmu_ctr_add (struct perf_event *event) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu); +struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); + +if (branch_user_callstack (event->attr.branch_sample_type) && + event->ctx->task->perf_ctx_data) +task_context (event->ctx->task->perf_ctx_data)->callstack_users++; + +perf_sched_cb_inc (event->pmu); + +if (!cpuc->ctr_users++) +riscv_pmu_ctr_reset (); +} + +void riscv_pmu_ctr_del (struct perf_event *event) +{ +struct riscv_pmu *rvpmu =to_riscv_pmu (event->pmu);
drivers/perf/riscv_ctr.c
Quoted 10 lines
drivers/perf/riscv_ctr.c new file +10
-0+struct cpu_hw_events *cpuc =this_cpu_ptr (rvpmu->hw_events); + +if (branch_user_callstack (event->attr.branch_sample_type) && + event->ctx->task->perf_ctx_data) +task_context (event->ctx->task->perf_ctx_data)->callstack_users--; + +perf_sched_cb_dec (event->pmu); + cpuc->ctr_users--; +WARN_ON_ONCE (cpuc->ctr_users <0 ); +}
[Severity: Critical]
Does passing task->perf_ctx_data directly to task_context(), riscv_pmu_ctr_save(), and riscv_pmu_ctr_restore() corrupt struct perf_ctx_data and adjacent slab objects?
task->perf_ctx_data is a struct perf_ctx_data __rcu * wrapper whose ->data member points to the struct riscv_perf_task_context allocated from pmu->task_ctx_cache. Treating task->perf_ctx_data itself as struct riscv_perf_task_context * overwrites struct perf_ctx_data (starting with rcu_head) when updating callstack_users or stack_state, and writes up to 256 struct ctr_regset entries past the end of the 48-byte struct perf_ctx_data allocation on context switch. Should these callers dereference task->perf_ctx_data under RCU and pass cd->data instead?
[Severity: High]
Can event->ctx->task be NULL in riscv_pmu_ctr_add() and riscv_pmu_ctr_del()?
For CPU-wide events (pid == -1), event->ctx is a per-CPU context where event->ctx->task is NULL. Because neither riscv_pmu_event_init() nor pmu_sbi_event_init() rejects PERF_SAMPLE_BRANCH_USER | PERF_SAMPLE_BRANCH_CALL_STACK on CPU-wide events, dereferencing event->ctx->task->perf_ctx_data triggers a NULL pointer dereference when such an event is scheduled.
Quoted 4 lines
drivers/perf/riscv_pmu_sbi.c +0
-0
[ ... ]
Quoted 17 lines
drivers/perf/riscv_pmu_sbi.c +12
-1@@ -1353,7 +1391,30 @@ static void riscv_pmu_destroy(struct riscv_pmu *pmu)cpuhp_state_remove_instance (CPUHP_AP_PERF_RISCV_STARTING , &pmu->node); } -static void pmu_sbi_event_init (struct perf_event *event) +static int branch_records_alloc (struct riscv_pmu *pmu) +{ +struct branch_records __percpu *tmp_alloc_ptr; +struct branch_records *records; +struct cpu_hw_events *events; +int cpu; + +if (!riscv_pmu_ctr_supported (pmu)) +return 0 ; + + tmp_alloc_ptr = alloc_percpu_gfp(struct branch_records, GFP_KERNEL); +if (!tmp_alloc_ptr)
drivers/perf/riscv_pmu_sbi.c static void riscv_pmu_destroy(struct riscv_pmu *pmu) · line 1415
Quoted 10 lines
drivers/perf/riscv_pmu_sbi.c +10
-0+return -ENOMEM ; + +for_each_possible_cpu (cpu) { + events =per_cpu_ptr (pmu->hw_events, cpu); + records =per_cpu_ptr (tmp_alloc_ptr, cpu); + events->branches = records; + } + +return 0 ; +}
[Severity: Medium]
Does branch_records_alloc() leak the per-CPU branch_records allocation if pmu_sbi_device_probe() later fails?
tmp_alloc_ptr is local to branch_records_alloc(), while only the resolved per-CPU pointers are stored in events->branches. The __percpu pointer needed by free_percpu() is lost, and the probe error unwind paths never free the allocation.
[ ... ]
drivers/perf/riscv_pmu_sbi.c static int pmu_sbi_device_probe(struct platform_device *pdev) · line 1602
Quoted 12 lines
drivers/perf/riscv_pmu_sbi.c +5
-0@@ -1517,6 +1592,11 @@ static int pmu_sbi_device_probe(struct platform_device *pdev) pmu->event_mapped = pmu_sbi_event_mapped; pmu->event_unmapped = pmu_sbi_event_unmapped; pmu->csr_index = pmu_sbi_csr_index; + pmu->sched_task = pmu_sbi_sched_task; + + ret =cpuhp_state_add_instance (CPUHP_AP_PERF_RISCV_STARTING , &pmu->node); +if (ret) + goto out_ctr_finish; ret =riscv_pm_pmu_register (pmu);if (ret)
[Severity: High]
Does adding cpuhp_state_add_instance(CPUHP_AP_PERF_RISCV_STARTING, &pmu->node) here register the same hlist_node twice?
pmu_sbi_device_probe() already registers &pmu->node with CPUHP_AP_PERF_RISCV_STARTING after register_sysctl():
drivers/perf/riscv_pmu_sbi.c:pmu_sbi_device_probe() {
...
register_sysctl("kernel", sbi_pmu_sysctl_table);
ret = cpuhp_state_add_instance(CPUHP_AP_PERF_RISCV_STARTING, &pmu->node);
if (ret)
goto out_unregister;
...
}Calling cpuhp_state_add_instance() a second time on &pmu->node runs pmu_sbi_starting_cpu() twice on each online CPU and inserts &pmu->node at the head of the hotplug state's hlist while it is already on that list, corrupting the list into a self-loop.
Quoted 5 lines
include/linux/perf/riscv_pmu.h +0
-0@@ -92,6 +108,44 @@ int riscv_pmu_get_hpm_info(u32 *hw_ctr_width, u32 *num_hw_ctr);
[ ... ]
include/linux/perf/riscv_pmu.h
Quoted 5 lines
include/linux/perf/riscv_pmu.h +5
-0+static inline void riscv_pmu_ctr_sched_task (struct perf_event_pmu_context *, +struct task_struct *task,bool sched_in) { } +static void riscv_pmu_ctr_add (struct perf_event *event) { } +static void riscv_pmu_ctr_del (struct perf_event *event) { } +static inline void riscv_pmu_ctr_enable (struct perf_event *event) { }
[Severity: Medium]
Should the !CONFIG_RISCV_CTR stubs for riscv_pmu_ctr_add() and riscv_pmu_ctr_del() be marked static inline? Without inline, compilation units that include this header without calling both functions trigger -Wunused-function warnings when CONFIG_RISCV_CTR is disabled.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewSashiko has finished reviewing this 7-patch series:
Sashiko has finished reviewing this 7-patch series:
- Patches 1-3: no issues found.
- Patch 4 ("riscv: pmu: Add infrastructure for Control Transfer..."): 1 potential issue (1 High)
- Patch 5 ("riscv: pmu: Add driver for Control Transfer Records Ext"):
14 potential issues (1 Critical, 5 High, 7 Medium, 1 Low)
- Patch 6 ("riscv: pmu: Integrate CTR Ext support in riscv_pmu_d..."): 9 potential issues (1 Critical, 2 High, 6 Medium)
- Patch 7 ("dt-bindings: riscv: add Sxctr ISA extension description"): 7 potential issues (1 Critical, 2 High, 4 Medium)
Detailed reviews have been sent as separate replies to patches 4-7.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]