1// SPDX-License-Identifier: GPL-2.0
2/*
3 * RISC-V performance counter support.
4 *
5 * Copyright (C) 2021 Western Digital Corporation or its affiliates.
6 *
7 * This code is based on ARM perf event code which is in turn based on
8 * sparc64 and x86 code.
9 */
10
11#define pr_fmt(fmt) "riscv-pmu-sbi: " fmt
12
13#include <linux/mod_devicetable.h>
14#include <linux/perf/riscv_pmu.h>
15#include <linux/platform_device.h>
16#include <linux/irq.h>
17#include <linux/irqdomain.h>
18#include <linux/of_irq.h>
19#include <linux/of.h>
20#include <linux/cpu_pm.h>
21#include <linux/sched/clock.h>
22#include <linux/soc/andes/irq.h>
23
24#include <asm/errata_list.h>
25#include <asm/sbi.h>
26#include <asm/cpufeature.h>
27
28#define ALT_SBI_PMU_OVERFLOW(__ovl)					\
29asm volatile(ALTERNATIVE_2(						\
30	"csrr %0, " __stringify(CSR_SCOUNTOVF),				\
31	"csrr %0, " __stringify(THEAD_C9XX_CSR_SCOUNTEROF),		\
32		THEAD_VENDOR_ID, ERRATA_THEAD_PMU,			\
33		CONFIG_ERRATA_THEAD_PMU,				\
34	"csrr %0, " __stringify(ANDES_CSR_SCOUNTEROF),			\
35		0, RISCV_ISA_EXT_XANDESPMU,				\
36		CONFIG_ANDES_CUSTOM_PMU)				\
37	: "=r" (__ovl) :						\
38	: "memory")
39
40#define ALT_SBI_PMU_OVF_CLEAR_PENDING(__irq_mask)			\
41asm volatile(ALTERNATIVE(						\
42	"csrc " __stringify(CSR_IP) ", %0\n\t",				\
43	"csrc " __stringify(ANDES_CSR_SLIP) ", %0\n\t",			\
44		0, RISCV_ISA_EXT_XANDESPMU,				\
45		CONFIG_ANDES_CUSTOM_PMU)				\
46	: : "r"(__irq_mask)						\
47	: "memory")
48
49#define SYSCTL_NO_USER_ACCESS	0
50#define SYSCTL_USER_ACCESS	1
51#define SYSCTL_LEGACY		2
52
53#define PERF_EVENT_FLAG_NO_USER_ACCESS	BIT(SYSCTL_NO_USER_ACCESS)
54#define PERF_EVENT_FLAG_USER_ACCESS	BIT(SYSCTL_USER_ACCESS)
55#define PERF_EVENT_FLAG_LEGACY		BIT(SYSCTL_LEGACY)
56
57PMU_FORMAT_ATTR(event, "config:0-47");
58PMU_FORMAT_ATTR(firmware, "config:63");
59
60static bool sbi_v2_available;
61static DEFINE_STATIC_KEY_FALSE(sbi_pmu_snapshot_available);
62#define sbi_pmu_snapshot_available() \
63	static_branch_unlikely(&sbi_pmu_snapshot_available)
64
65static struct attribute *riscv_arch_formats_attr[] = {
66	&format_attr_event.attr,
67	&format_attr_firmware.attr,
68	NULL,
69};
70
71static struct attribute_group riscv_pmu_format_group = {
72	.name = "format",
73	.attrs = riscv_arch_formats_attr,
74};
75
76static const struct attribute_group *riscv_pmu_attr_groups[] = {
77	&riscv_pmu_format_group,
78	NULL,
79};
80
81/* Allow user mode access by default */
82static int sysctl_perf_user_access __read_mostly = SYSCTL_USER_ACCESS;
83
84/*
85 * RISC-V doesn't have heterogeneous harts yet. This need to be part of
86 * per_cpu in case of harts with different pmu counters
87 */
88static union sbi_pmu_ctr_info *pmu_ctr_list;
89static bool riscv_pmu_use_irq;
90static unsigned int riscv_pmu_irq_num;
91static unsigned int riscv_pmu_irq_mask;
92static unsigned int riscv_pmu_irq;
93
94/* Cache the available counters in a bitmask */
95static unsigned long cmask;
96
97struct sbi_pmu_event_data {
98	union {
99		union {
100			struct hw_gen_event {
101				uint32_t event_code:16;
102				uint32_t event_type:4;
103				uint32_t reserved:12;
104			} hw_gen_event;
105			struct hw_cache_event {
106				uint32_t result_id:1;
107				uint32_t op_id:2;
108				uint32_t cache_id:13;
109				uint32_t event_type:4;
110				uint32_t reserved:12;
111			} hw_cache_event;
112		};
113		uint32_t event_idx;
114	};
115};
116
117static const struct sbi_pmu_event_data pmu_hw_event_map[] = {
118	[PERF_COUNT_HW_CPU_CYCLES]		= {.hw_gen_event = {
119							SBI_PMU_HW_CPU_CYCLES,
120							SBI_PMU_EVENT_TYPE_HW, 0}},
121	[PERF_COUNT_HW_INSTRUCTIONS]		= {.hw_gen_event = {
122							SBI_PMU_HW_INSTRUCTIONS,
123							SBI_PMU_EVENT_TYPE_HW, 0}},
124	[PERF_COUNT_HW_CACHE_REFERENCES]	= {.hw_gen_event = {
125							SBI_PMU_HW_CACHE_REFERENCES,
126							SBI_PMU_EVENT_TYPE_HW, 0}},
127	[PERF_COUNT_HW_CACHE_MISSES]		= {.hw_gen_event = {
128							SBI_PMU_HW_CACHE_MISSES,
129							SBI_PMU_EVENT_TYPE_HW, 0}},
130	[PERF_COUNT_HW_BRANCH_INSTRUCTIONS]	= {.hw_gen_event = {
131							SBI_PMU_HW_BRANCH_INSTRUCTIONS,
132							SBI_PMU_EVENT_TYPE_HW, 0}},
133	[PERF_COUNT_HW_BRANCH_MISSES]		= {.hw_gen_event = {
134							SBI_PMU_HW_BRANCH_MISSES,
135							SBI_PMU_EVENT_TYPE_HW, 0}},
136	[PERF_COUNT_HW_BUS_CYCLES]		= {.hw_gen_event = {
137							SBI_PMU_HW_BUS_CYCLES,
138							SBI_PMU_EVENT_TYPE_HW, 0}},
139	[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND]	= {.hw_gen_event = {
140							SBI_PMU_HW_STALLED_CYCLES_FRONTEND,
141							SBI_PMU_EVENT_TYPE_HW, 0}},
142	[PERF_COUNT_HW_STALLED_CYCLES_BACKEND]	= {.hw_gen_event = {
143							SBI_PMU_HW_STALLED_CYCLES_BACKEND,
144							SBI_PMU_EVENT_TYPE_HW, 0}},
145	[PERF_COUNT_HW_REF_CPU_CYCLES]		= {.hw_gen_event = {
146							SBI_PMU_HW_REF_CPU_CYCLES,
147							SBI_PMU_EVENT_TYPE_HW, 0}},
148};
149
150#define C(x) PERF_COUNT_HW_CACHE_##x
151static const struct sbi_pmu_event_data pmu_cache_event_map[PERF_COUNT_HW_CACHE_MAX]
152[PERF_COUNT_HW_CACHE_OP_MAX]
153[PERF_COUNT_HW_CACHE_RESULT_MAX] = {
154	[C(L1D)] = {
155		[C(OP_READ)] = {
156			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
157					C(OP_READ), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
158			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
159					C(OP_READ), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
160		},
161		[C(OP_WRITE)] = {
162			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
163					C(OP_WRITE), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
164			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
165					C(OP_WRITE), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
166		},
167		[C(OP_PREFETCH)] = {
168			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
169					C(OP_PREFETCH), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
170			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
171					C(OP_PREFETCH), C(L1D), SBI_PMU_EVENT_TYPE_CACHE, 0}},
172		},
173	},
174	[C(L1I)] = {
175		[C(OP_READ)] = {
176			[C(RESULT_ACCESS)] = {.hw_cache_event =	{C(RESULT_ACCESS),
177					C(OP_READ), C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
178			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS), C(OP_READ),
179					C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
180		},
181		[C(OP_WRITE)] = {
182			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
183					C(OP_WRITE), C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
184			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
185					C(OP_WRITE), C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
186		},
187		[C(OP_PREFETCH)] = {
188			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
189					C(OP_PREFETCH), C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
190			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
191					C(OP_PREFETCH), C(L1I), SBI_PMU_EVENT_TYPE_CACHE, 0}},
192		},
193	},
194	[C(LL)] = {
195		[C(OP_READ)] = {
196			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
197					C(OP_READ), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
198			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
199					C(OP_READ), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
200		},
201		[C(OP_WRITE)] = {
202			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
203					C(OP_WRITE), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
204			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
205					C(OP_WRITE), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
206		},
207		[C(OP_PREFETCH)] = {
208			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
209					C(OP_PREFETCH), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
210			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
211					C(OP_PREFETCH), C(LL), SBI_PMU_EVENT_TYPE_CACHE, 0}},
212		},
213	},
214	[C(DTLB)] = {
215		[C(OP_READ)] = {
216			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
217					C(OP_READ), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
218			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
219					C(OP_READ), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
220		},
221		[C(OP_WRITE)] = {
222			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
223					C(OP_WRITE), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
224			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
225					C(OP_WRITE), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
226		},
227		[C(OP_PREFETCH)] = {
228			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
229					C(OP_PREFETCH), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
230			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
231					C(OP_PREFETCH), C(DTLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
232		},
233	},
234	[C(ITLB)] = {
235		[C(OP_READ)] = {
236			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
237					C(OP_READ), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
238			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
239					C(OP_READ), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
240		},
241		[C(OP_WRITE)] = {
242			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
243					C(OP_WRITE), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
244			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
245					C(OP_WRITE), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
246		},
247		[C(OP_PREFETCH)] = {
248			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
249					C(OP_PREFETCH), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
250			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
251					C(OP_PREFETCH), C(ITLB), SBI_PMU_EVENT_TYPE_CACHE, 0}},
252		},
253	},
254	[C(BPU)] = {
255		[C(OP_READ)] = {
256			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
257					C(OP_READ), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
258			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
259					C(OP_READ), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
260		},
261		[C(OP_WRITE)] = {
262			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
263					C(OP_WRITE), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
264			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
265					C(OP_WRITE), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
266		},
267		[C(OP_PREFETCH)] = {
268			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
269					C(OP_PREFETCH), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
270			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
271					C(OP_PREFETCH), C(BPU), SBI_PMU_EVENT_TYPE_CACHE, 0}},
272		},
273	},
274	[C(NODE)] = {
275		[C(OP_READ)] = {
276			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
277					C(OP_READ), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
278			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
279					C(OP_READ), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
280		},
281		[C(OP_WRITE)] = {
282			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
283					C(OP_WRITE), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
284			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
285					C(OP_WRITE), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
286		},
287		[C(OP_PREFETCH)] = {
288			[C(RESULT_ACCESS)] = {.hw_cache_event = {C(RESULT_ACCESS),
289					C(OP_PREFETCH), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
290			[C(RESULT_MISS)] = {.hw_cache_event = {C(RESULT_MISS),
291					C(OP_PREFETCH), C(NODE), SBI_PMU_EVENT_TYPE_CACHE, 0}},
292		},
293	},
294};
295
296static int pmu_sbi_ctr_get_width(int idx)
297{
298	return pmu_ctr_list[idx].width;
299}
300
301static bool pmu_sbi_ctr_is_fw(int cidx)
302{
303	union sbi_pmu_ctr_info *info;
304
305	info = &pmu_ctr_list[cidx];
306	if (!info)
307		return false;
308
309	return (info->type == SBI_PMU_CTR_TYPE_FW) ? true : false;
310}
311
312/*
313 * Returns the counter width of a programmable counter and number of hardware
314 * counters. As we don't support heterogeneous CPUs yet, it is okay to just
315 * return the counter width of the first programmable counter.
316 */
317int riscv_pmu_get_hpm_info(u32 *hw_ctr_width, u32 *num_hw_ctr)
318{
319	int i;
320	union sbi_pmu_ctr_info *info;
321	u32 hpm_width = 0, hpm_count = 0;
322
323	if (!cmask)
324		return -EINVAL;
325
326	for_each_set_bit(i, &cmask, RISCV_MAX_COUNTERS) {
327		info = &pmu_ctr_list[i];
328		if (!info)
329			continue;
330		if (!hpm_width && info->csr != CSR_CYCLE && info->csr != CSR_INSTRET)
331			hpm_width = info->width;
332		if (info->type == SBI_PMU_CTR_TYPE_HW)
333			hpm_count++;
334	}
335
336	*hw_ctr_width = hpm_width;
337	*num_hw_ctr = hpm_count;
338
339	return 0;
340}
341EXPORT_SYMBOL_GPL(riscv_pmu_get_hpm_info);
342
343static uint8_t pmu_sbi_csr_index(struct perf_event *event)
344{
345	return pmu_ctr_list[event->hw.idx].csr - CSR_CYCLE;
346}
347
348static unsigned long pmu_sbi_get_filter_flags(struct perf_event *event)
349{
350	unsigned long cflags = 0;
351	bool guest_events = false;
352
353	if (event->attr.config1 & RISCV_PMU_CONFIG1_GUEST_EVENTS)
354		guest_events = true;
355	if (event->attr.exclude_kernel)
356		cflags |= guest_events ? SBI_PMU_CFG_FLAG_SET_VSINH : SBI_PMU_CFG_FLAG_SET_SINH;
357	if (event->attr.exclude_user)
358		cflags |= guest_events ? SBI_PMU_CFG_FLAG_SET_VUINH : SBI_PMU_CFG_FLAG_SET_UINH;
359	if (guest_events && event->attr.exclude_hv)
360		cflags |= SBI_PMU_CFG_FLAG_SET_SINH;
361	if (event->attr.exclude_host)
362		cflags |= SBI_PMU_CFG_FLAG_SET_UINH | SBI_PMU_CFG_FLAG_SET_SINH;
363	if (event->attr.exclude_guest)
364		cflags |= SBI_PMU_CFG_FLAG_SET_VSINH | SBI_PMU_CFG_FLAG_SET_VUINH;
365
366	return cflags;
367}
368
369static int pmu_sbi_ctr_get_idx(struct perf_event *event)
370{
371	struct hw_perf_event *hwc = &event->hw;
372	struct riscv_pmu *rvpmu = to_riscv_pmu(event->pmu);
373	struct cpu_hw_events *cpuc = this_cpu_ptr(rvpmu->hw_events);
374	struct sbiret ret;
375	int idx;
376	uint64_t cbase = 0, cmask = rvpmu->cmask;
377	unsigned long cflags = 0;
378
379	cflags = pmu_sbi_get_filter_flags(event);
380
381	/*
382	 * In legacy mode, we have to force the fixed counters for those events
383	 * but not in the user access mode as we want to use the other counters
384	 * that support sampling/filtering.
385	 */
386	if (hwc->flags & PERF_EVENT_FLAG_LEGACY) {
387		if (event->attr.config == PERF_COUNT_HW_CPU_CYCLES) {
388			cflags |= SBI_PMU_CFG_FLAG_SKIP_MATCH;
389			cmask = 1;
390		} else if (event->attr.config == PERF_COUNT_HW_INSTRUCTIONS) {
391			cflags |= SBI_PMU_CFG_FLAG_SKIP_MATCH;
392			cmask = BIT(CSR_INSTRET - CSR_CYCLE);
393		}
394	}
395
396	/* retrieve the available counter index */
397#if defined(CONFIG_32BIT)
398	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_CFG_MATCH, cbase,
399			cmask, cflags, hwc->event_base, hwc->config,
400			hwc->config >> 32);
401#else
402	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_CFG_MATCH, cbase,
403			cmask, cflags, hwc->event_base, hwc->config, 0);
404#endif
405	if (ret.error) {
406		pr_debug("Not able to find a counter for event %lx config %llx\n",
407			hwc->event_base, hwc->config);
408		return sbi_err_map_linux_errno(ret.error);
409	}
410
411	idx = ret.value;
412	if (!test_bit(idx, &rvpmu->cmask) || !pmu_ctr_list[idx].value)
413		return -ENOENT;
414
415	/* Additional sanity check for the counter id */
416	if (pmu_sbi_ctr_is_fw(idx)) {
417		if (!test_and_set_bit(idx, cpuc->used_fw_ctrs))
418			return idx;
419	} else {
420		if (!test_and_set_bit(idx, cpuc->used_hw_ctrs))
421			return idx;
422	}
423
424	return -ENOENT;
425}
426
427static void pmu_sbi_ctr_clear_idx(struct perf_event *event)
428{
429
430	struct hw_perf_event *hwc = &event->hw;
431	struct riscv_pmu *rvpmu = to_riscv_pmu(event->pmu);
432	struct cpu_hw_events *cpuc = this_cpu_ptr(rvpmu->hw_events);
433	int idx = hwc->idx;
434
435	if (pmu_sbi_ctr_is_fw(idx))
436		clear_bit(idx, cpuc->used_fw_ctrs);
437	else
438		clear_bit(idx, cpuc->used_hw_ctrs);
439}
440
441static int pmu_event_find_cache(u64 config)
442{
443	unsigned int cache_type, cache_op, cache_result, ret;
444
445	cache_type = (config >>  0) & 0xff;
446	if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
447		return -EINVAL;
448
449	cache_op = (config >>  8) & 0xff;
450	if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
451		return -EINVAL;
452
453	cache_result = (config >> 16) & 0xff;
454	if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
455		return -EINVAL;
456
457	ret = pmu_cache_event_map[cache_type][cache_op][cache_result].event_idx;
458
459	return ret;
460}
461
462static bool pmu_sbi_is_fw_event(struct perf_event *event)
463{
464	u32 type = event->attr.type;
465	u64 config = event->attr.config;
466
467	if ((type == PERF_TYPE_RAW) && ((config >> 63) == 1))
468		return true;
469	else
470		return false;
471}
472
473static int pmu_sbi_event_map(struct perf_event *event, u64 *econfig)
474{
475	u32 type = event->attr.type;
476	u64 config = event->attr.config;
477	int bSoftware;
478	u64 raw_config_val;
479	int ret;
480
481	switch (type) {
482	case PERF_TYPE_HARDWARE:
483		if (config >= PERF_COUNT_HW_MAX)
484			return -EINVAL;
485		ret = pmu_hw_event_map[event->attr.config].event_idx;
486		break;
487	case PERF_TYPE_HW_CACHE:
488		ret = pmu_event_find_cache(config);
489		break;
490	case PERF_TYPE_RAW:
491		/*
492		 * As per SBI specification, the upper 16 bits must be unused for
493		 * a raw event. Use the MSB (63b) to distinguish between hardware
494		 * raw event and firmware events.
495		 */
496		bSoftware = config >> 63;
497		raw_config_val = config & RISCV_PMU_RAW_EVENT_MASK;
498		if (bSoftware) {
499			ret = (raw_config_val & 0xFFFF) |
500				(SBI_PMU_EVENT_TYPE_FW << 16);
501		} else {
502			ret = RISCV_PMU_RAW_EVENT_IDX;
503			*econfig = raw_config_val;
504		}
505		break;
506	default:
507		ret = -EINVAL;
508		break;
509	}
510
511	return ret;
512}
513
514static void pmu_sbi_snapshot_free(struct riscv_pmu *pmu)
515{
516	int cpu;
517
518	for_each_possible_cpu(cpu) {
519		struct cpu_hw_events *cpu_hw_evt = per_cpu_ptr(pmu->hw_events, cpu);
520
521		if (!cpu_hw_evt->snapshot_addr)
522			continue;
523
524		free_page((unsigned long)cpu_hw_evt->snapshot_addr);
525		cpu_hw_evt->snapshot_addr = NULL;
526		cpu_hw_evt->snapshot_addr_phys = 0;
527	}
528}
529
530static int pmu_sbi_snapshot_alloc(struct riscv_pmu *pmu)
531{
532	int cpu;
533	struct page *snapshot_page;
534
535	for_each_possible_cpu(cpu) {
536		struct cpu_hw_events *cpu_hw_evt = per_cpu_ptr(pmu->hw_events, cpu);
537
538		snapshot_page = alloc_page(GFP_ATOMIC | __GFP_ZERO);
539		if (!snapshot_page) {
540			pmu_sbi_snapshot_free(pmu);
541			return -ENOMEM;
542		}
543		cpu_hw_evt->snapshot_addr = page_to_virt(snapshot_page);
544		cpu_hw_evt->snapshot_addr_phys = page_to_phys(snapshot_page);
545	}
546
547	return 0;
548}
549
550static int pmu_sbi_snapshot_disable(void)
551{
552	struct sbiret ret;
553
554	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_SNAPSHOT_SET_SHMEM, SBI_SHMEM_DISABLE,
555			SBI_SHMEM_DISABLE, 0, 0, 0, 0);
556	if (ret.error) {
557		pr_warn("failed to disable snapshot shared memory\n");
558		return sbi_err_map_linux_errno(ret.error);
559	}
560
561	return 0;
562}
563
564static int pmu_sbi_snapshot_setup(struct riscv_pmu *pmu, int cpu)
565{
566	struct cpu_hw_events *cpu_hw_evt;
567	struct sbiret ret = {0};
568
569	cpu_hw_evt = per_cpu_ptr(pmu->hw_events, cpu);
570	if (!cpu_hw_evt->snapshot_addr_phys)
571		return -EINVAL;
572
573	if (cpu_hw_evt->snapshot_set_done)
574		return 0;
575
576	if (IS_ENABLED(CONFIG_32BIT))
577		ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_SNAPSHOT_SET_SHMEM,
578				cpu_hw_evt->snapshot_addr_phys,
579				(u64)(cpu_hw_evt->snapshot_addr_phys) >> 32, 0, 0, 0, 0);
580	else
581		ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_SNAPSHOT_SET_SHMEM,
582				cpu_hw_evt->snapshot_addr_phys, 0, 0, 0, 0, 0);
583
584	/* Free up the snapshot area memory and fall back to SBI PMU calls without snapshot */
585	if (ret.error) {
586		if (ret.error != SBI_ERR_NOT_SUPPORTED)
587			pr_warn("pmu snapshot setup failed with error %ld\n", ret.error);
588		return sbi_err_map_linux_errno(ret.error);
589	}
590
591	memset(cpu_hw_evt->snapshot_cval_shcopy, 0, sizeof(u64) * RISCV_MAX_COUNTERS);
592	cpu_hw_evt->snapshot_set_done = true;
593
594	return 0;
595}
596
597static u64 pmu_sbi_ctr_read(struct perf_event *event)
598{
599	struct hw_perf_event *hwc = &event->hw;
600	int idx = hwc->idx;
601	struct sbiret ret;
602	u64 val = 0;
603	struct riscv_pmu *pmu = to_riscv_pmu(event->pmu);
604	struct cpu_hw_events *cpu_hw_evt = this_cpu_ptr(pmu->hw_events);
605	struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr;
606	union sbi_pmu_ctr_info info = pmu_ctr_list[idx];
607
608	/* Read the value from the shared memory directly only if counter is stopped */
609	if (sbi_pmu_snapshot_available() && (hwc->state & PERF_HES_STOPPED)) {
610		val = sdata->ctr_values[idx];
611		return val;
612	}
613
614	if (pmu_sbi_is_fw_event(event)) {
615		ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_FW_READ,
616				hwc->idx, 0, 0, 0, 0, 0);
617		if (ret.error)
618			return 0;
619
620		val = ret.value;
621		if (IS_ENABLED(CONFIG_32BIT) && sbi_v2_available && info.width >= 32) {
622			ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_FW_READ_HI,
623					hwc->idx, 0, 0, 0, 0, 0);
624			if (!ret.error)
625				val |= ((u64)ret.value << 32);
626			else
627				WARN_ONCE(1, "Unable to read upper 32 bits of firmware counter error: %ld\n",
628					  ret.error);
629		}
630	} else {
631		val = riscv_pmu_ctr_read_csr(info.csr);
632		if (IS_ENABLED(CONFIG_32BIT))
633			val |= ((u64)riscv_pmu_ctr_read_csr(info.csr + 0x80)) << 32;
634	}
635
636	return val;
637}
638
639static void pmu_sbi_set_scounteren(void *arg)
640{
641	struct perf_event *event = (struct perf_event *)arg;
642
643	if (event->hw.idx != -1)
644		csr_write(CSR_SCOUNTEREN,
645			  csr_read(CSR_SCOUNTEREN) | BIT(pmu_sbi_csr_index(event)));
646}
647
648static void pmu_sbi_reset_scounteren(void *arg)
649{
650	struct perf_event *event = (struct perf_event *)arg;
651
652	if (event->hw.idx != -1)
653		csr_write(CSR_SCOUNTEREN,
654			  csr_read(CSR_SCOUNTEREN) & ~BIT(pmu_sbi_csr_index(event)));
655}
656
657static void pmu_sbi_ctr_start(struct perf_event *event, u64 ival)
658{
659	struct sbiret ret;
660	struct hw_perf_event *hwc = &event->hw;
661	unsigned long flag = SBI_PMU_START_FLAG_SET_INIT_VALUE;
662
663	/* There is no benefit setting SNAPSHOT FLAG for a single counter */
664#if defined(CONFIG_32BIT)
665	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, hwc->idx,
666			1, flag, ival, ival >> 32, 0);
667#else
668	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, hwc->idx,
669			1, flag, ival, 0, 0);
670#endif
671	if (ret.error && (ret.error != SBI_ERR_ALREADY_STARTED))
672		pr_err("Starting counter idx %d failed with error %d\n",
673			hwc->idx, sbi_err_map_linux_errno(ret.error));
674
675	if ((hwc->flags & PERF_EVENT_FLAG_USER_ACCESS) &&
676	    (hwc->flags & PERF_EVENT_FLAG_USER_READ_CNT))
677		pmu_sbi_set_scounteren((void *)event);
678}
679
680static void pmu_sbi_ctr_stop(struct perf_event *event, unsigned long flag)
681{
682	struct sbiret ret;
683	struct hw_perf_event *hwc = &event->hw;
684	struct riscv_pmu *pmu = to_riscv_pmu(event->pmu);
685	struct cpu_hw_events *cpu_hw_evt = this_cpu_ptr(pmu->hw_events);
686	struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr;
687
688	if ((hwc->flags & PERF_EVENT_FLAG_USER_ACCESS) &&
689	    (hwc->flags & PERF_EVENT_FLAG_USER_READ_CNT))
690		pmu_sbi_reset_scounteren((void *)event);
691
692	if (sbi_pmu_snapshot_available())
693		flag |= SBI_PMU_STOP_FLAG_TAKE_SNAPSHOT;
694
695	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_STOP, hwc->idx, 1, flag, 0, 0, 0);
696	if (!ret.error && sbi_pmu_snapshot_available()) {
697		/*
698		 * The counter snapshot is based on the index base specified by hwc->idx.
699		 * The actual counter value is updated in shared memory at index 0 when counter
700		 * mask is 0x01. To ensure accurate counter values, it's necessary to transfer
701		 * the counter value to shared memory. However, if hwc->idx is zero, the counter
702		 * value is already correctly updated in shared memory, requiring no further
703		 * adjustment.
704		 */
705		if (hwc->idx > 0) {
706			sdata->ctr_values[hwc->idx] = sdata->ctr_values[0];
707			sdata->ctr_values[0] = 0;
708		}
709	} else if (ret.error && (ret.error != SBI_ERR_ALREADY_STOPPED) &&
710		flag != SBI_PMU_STOP_FLAG_RESET) {
711		pr_err("Stopping counter idx %d failed with error %d\n",
712			hwc->idx, sbi_err_map_linux_errno(ret.error));
713	}
714}
715
716static int pmu_sbi_find_num_ctrs(void)
717{
718	struct sbiret ret;
719
720	ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_NUM_COUNTERS, 0, 0, 0, 0, 0, 0);
721	if (!ret.error)
722		return ret.value;
723	else
724		return sbi_err_map_linux_errno(ret.error);
725}
726
727static int pmu_sbi_get_ctrinfo(int nctr, unsigned long *mask)
728{
729	struct sbiret ret;
730	int i, num_hw_ctr = 0, num_fw_ctr = 0;
731	union sbi_pmu_ctr_info cinfo;
732
733	pmu_ctr_list = kcalloc(nctr, sizeof(*pmu_ctr_list), GFP_KERNEL);
734	if (!pmu_ctr_list)
735		return -ENOMEM;
736
737	for (i = 0; i < nctr; i++) {
738		ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_GET_INFO, i, 0, 0, 0, 0, 0);
739		if (ret.error)
740			/* The logical counter ids are not expected to be contiguous */
741			continue;
742
743		*mask |= BIT(i);
744
745		cinfo.value = ret.value;
746		if (cinfo.type == SBI_PMU_CTR_TYPE_FW)
747			num_fw_ctr++;
748		else
749			num_hw_ctr++;
750		pmu_ctr_list[i].value = cinfo.value;
751	}
752
753	pr_info("%d firmware and %d hardware counters\n", num_fw_ctr, num_hw_ctr);
754
755	return 0;
756}
757
758static inline void pmu_sbi_stop_all(struct riscv_pmu *pmu)
759{
760	/*
761	 * No need to check the error because we are disabling all the counters
762	 * which may include counters that are not enabled yet.
763	 */
764	sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_STOP,
765		  0, pmu->cmask, 0, 0, 0, 0);
766}
767
768static inline void pmu_sbi_stop_hw_ctrs(struct riscv_pmu *pmu)
769{
770	struct cpu_hw_events *cpu_hw_evt = this_cpu_ptr(pmu->hw_events);
771	struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr;
772	unsigned long flag = 0;
773	int i, idx;
774	struct sbiret ret;
775	u64 temp_ctr_overflow_mask = 0;
776
777	if (sbi_pmu_snapshot_available())
778		flag = SBI_PMU_STOP_FLAG_TAKE_SNAPSHOT;
779
780	/* Reset the shadow copy to avoid save/restore any value from previous overflow */
781	memset(cpu_hw_evt->snapshot_cval_shcopy, 0, sizeof(u64) * RISCV_MAX_COUNTERS);
782
783	for (i = 0; i < BITS_TO_LONGS(RISCV_MAX_COUNTERS); i++) {
784		/* No need to check the error here as we can't do anything about the error */
785		ret = sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_STOP, i * BITS_PER_LONG,
786				cpu_hw_evt->used_hw_ctrs[i], flag, 0, 0, 0);
787		if (!ret.error && sbi_pmu_snapshot_available()) {
788			/* Save the counter values to avoid clobbering */
789			for_each_set_bit(idx, &cpu_hw_evt->used_hw_ctrs[i], BITS_PER_LONG)
790				cpu_hw_evt->snapshot_cval_shcopy[i * BITS_PER_LONG + idx] =
791							sdata->ctr_values[idx];
792			/* Save the overflow mask to avoid clobbering */
793			temp_ctr_overflow_mask |= sdata->ctr_overflow_mask << (i * BITS_PER_LONG);
794		}
795	}
796
797	/* Restore the counter values to the shared memory for used hw counters */
798	if (sbi_pmu_snapshot_available()) {
799		for_each_set_bit(idx, cpu_hw_evt->used_hw_ctrs, RISCV_MAX_COUNTERS)
800			sdata->ctr_values[idx] = cpu_hw_evt->snapshot_cval_shcopy[idx];
801		if (temp_ctr_overflow_mask)
802			sdata->ctr_overflow_mask = temp_ctr_overflow_mask;
803	}
804}
805
806/*
807 * This function starts all the used counters in two step approach.
808 * Any counter that did not overflow can be start in a single step
809 * while the overflowed counters need to be started with updated initialization
810 * value.
811 */
812static inline void pmu_sbi_start_ovf_ctrs_sbi(struct cpu_hw_events *cpu_hw_evt,
813					      u64 ctr_ovf_mask)
814{
815	int idx = 0, i;
816	struct perf_event *event;
817	unsigned long flag = SBI_PMU_START_FLAG_SET_INIT_VALUE;
818	unsigned long ctr_start_mask = 0;
819	uint64_t max_period;
820	struct hw_perf_event *hwc;
821	u64 init_val = 0;
822
823	for (i = 0; i < BITS_TO_LONGS(RISCV_MAX_COUNTERS); i++) {
824		ctr_start_mask = cpu_hw_evt->used_hw_ctrs[i] & ~ctr_ovf_mask;
825		/* Start all the counters that did not overflow in a single shot */
826		sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, i * BITS_PER_LONG, ctr_start_mask,
827			0, 0, 0, 0);
828	}
829
830	/* Reinitialize and start all the counter that overflowed */
831	while (ctr_ovf_mask) {
832		if (ctr_ovf_mask & 0x01) {
833			event = cpu_hw_evt->events[idx];
834			hwc = &event->hw;
835			max_period = riscv_pmu_ctr_get_width_mask(event);
836			init_val = local64_read(&hwc->prev_count) & max_period;
837#if defined(CONFIG_32BIT)
838			sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, idx, 1,
839				  flag, init_val, init_val >> 32, 0);
840#else
841			sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, idx, 1,
842				  flag, init_val, 0, 0);
843#endif
844			perf_event_update_userpage(event);
845		}
846		ctr_ovf_mask = ctr_ovf_mask >> 1;
847		idx++;
848	}
849}
850
851static inline void pmu_sbi_start_ovf_ctrs_snapshot(struct cpu_hw_events *cpu_hw_evt,
852						   u64 ctr_ovf_mask)
853{
854	int i, idx = 0;
855	struct perf_event *event;
856	unsigned long flag = SBI_PMU_START_FLAG_INIT_SNAPSHOT;
857	u64 max_period, init_val = 0;
858	struct hw_perf_event *hwc;
859	struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr;
860
861	for_each_set_bit(idx, cpu_hw_evt->used_hw_ctrs, RISCV_MAX_COUNTERS) {
862		if (ctr_ovf_mask & BIT(idx)) {
863			event = cpu_hw_evt->events[idx];
864			hwc = &event->hw;
865			max_period = riscv_pmu_ctr_get_width_mask(event);
866			init_val = local64_read(&hwc->prev_count) & max_period;
867			cpu_hw_evt->snapshot_cval_shcopy[idx] = init_val;
868		}
869		/*
870		 * We do not need to update the non-overflow counters the previous
871		 * value should have been there already.
872		 */
873	}
874
875	for (i = 0; i < BITS_TO_LONGS(RISCV_MAX_COUNTERS); i++) {
876		/* Restore the counter values to relative indices for used hw counters */
877		for_each_set_bit(idx, &cpu_hw_evt->used_hw_ctrs[i], BITS_PER_LONG)
878			sdata->ctr_values[idx] =
879					cpu_hw_evt->snapshot_cval_shcopy[idx + i * BITS_PER_LONG];
880		/* Start all the counters in a single shot */
881		sbi_ecall(SBI_EXT_PMU, SBI_EXT_PMU_COUNTER_START, idx * BITS_PER_LONG,
882			  cpu_hw_evt->used_hw_ctrs[i], flag, 0, 0, 0);
883	}
884}
885
886static void pmu_sbi_start_overflow_mask(struct riscv_pmu *pmu,
887					u64 ctr_ovf_mask)
888{
889	struct cpu_hw_events *cpu_hw_evt = this_cpu_ptr(pmu->hw_events);
890
891	if (sbi_pmu_snapshot_available())
892		pmu_sbi_start_ovf_ctrs_snapshot(cpu_hw_evt, ctr_ovf_mask);
893	else
894		pmu_sbi_start_ovf_ctrs_sbi(cpu_hw_evt, ctr_ovf_mask);
895}
896
897static irqreturn_t pmu_sbi_ovf_handler(int irq, void *dev)
898{
899	struct perf_sample_data data;
900	struct pt_regs *regs;
901	struct hw_perf_event *hw_evt;
902	union sbi_pmu_ctr_info *info;
903	int lidx, hidx, fidx;
904	struct riscv_pmu *pmu;
905	struct perf_event *event;
906	u64 overflow;
907	u64 overflowed_ctrs = 0;
908	struct cpu_hw_events *cpu_hw_evt = dev;
909	u64 start_clock = sched_clock();
910	struct riscv_pmu_snapshot_data *sdata = cpu_hw_evt->snapshot_addr;
911
912	if (WARN_ON_ONCE(!cpu_hw_evt))
913		return IRQ_NONE;
914
915	/* Firmware counter don't support overflow yet */
916	fidx = find_first_bit(cpu_hw_evt->used_hw_ctrs, RISCV_MAX_COUNTERS);
917	if (fidx == RISCV_MAX_COUNTERS) {
918		csr_clear(CSR_SIP, BIT(riscv_pmu_irq_num));
919		return IRQ_NONE;
920	}
921
922	event = cpu_hw_evt->events[fidx];
923	if (!event) {
924		ALT_SBI_PMU_OVF_CLEAR_PENDING(riscv_pmu_irq_mask);
925		return IRQ_NONE;
926	}
927
928	pmu = to_riscv_pmu(event->pmu);
929	pmu_sbi_stop_hw_ctrs(pmu);
930
931	/* Overflow status register should only be read after counter are stopped */
932	if (sbi_pmu_snapshot_available())
933		overflow = sdata->ctr_overflow_mask;
934	else
935		ALT_SBI_PMU_OVERFLOW(overflow);
936
937	/*
938	 * Overflow interrupt pending bit should only be cleared after stopping
939	 * all the counters to avoid any race condition.
940	 */
941	ALT_SBI_PMU_OVF_CLEAR_PENDING(riscv_pmu_irq_mask);
942
943	/* No overflow bit is set */
944	if (!overflow)
945		return IRQ_NONE;
946
947	regs = get_irq_regs();
948
949	for_each_set_bit(lidx, cpu_hw_evt->used_hw_ctrs, RISCV_MAX_COUNTERS) {
950		struct perf_event *event = cpu_hw_evt->events[lidx];
951
952		/* Skip if invalid event or user did not request a sampling */
953		if (!event || !is_sampling_event(event))
954			continue;
955
956		info = &pmu_ctr_list[lidx];
957		/* Do a sanity check */
958		if (!info || info->type != SBI_PMU_CTR_TYPE_HW)
959			continue;
960
961		if (sbi_pmu_snapshot_available())
962			/* SBI implementation already updated the logical indicies */
963			hidx = lidx;
964		else
965			/* compute hardware counter index */
966			hidx = info->csr - CSR_CYCLE;
967
968		/* check if the corresponding bit is set in sscountovf or overflow mask in shmem */
969		if (!(overflow & BIT(hidx)))
970			continue;
971
972		/*
973		 * Keep a track of overflowed counters so that they can be started
974		 * with updated initial value.
975		 */
976		overflowed_ctrs |= BIT(lidx);
977		hw_evt = &event->hw;
978		/* Update the event states here so that we know the state while reading */
979		hw_evt->state |= PERF_HES_STOPPED;
980		riscv_pmu_event_update(event);
981		hw_evt->state |= PERF_HES_UPTODATE;
982		perf_sample_data_init(&data, 0, hw_evt->last_period);
983		if (riscv_pmu_event_set_period(event)) {
984			/*
985			 * Unlike other ISAs, RISC-V don't have to disable interrupts
986			 * to avoid throttling here. As per the specification, the
987			 * interrupt remains disabled until the OF bit is set.
988			 * Interrupts are enabled again only during the start.
989			 * TODO: We will need to stop the guest counters once
990			 * virtualization support is added.
991			 */
992			perf_event_overflow(event, &data, regs);
993		}
994		/* Reset the state as we are going to start the counter after the loop */
995		hw_evt->state = 0;
996	}
997
998	pmu_sbi_start_overflow_mask(pmu, overflowed_ctrs);
999	perf_sample_event_took(sched_clock() - start_clock);
1000
1001	return IRQ_HANDLED;
1002}
1003
1004static int pmu_sbi_starting_cpu(unsigned int cpu, struct hlist_node *node)
1005{
1006	struct riscv_pmu *pmu = hlist_entry_safe(node, struct riscv_pmu, node);
1007	struct cpu_hw_events *cpu_hw_evt = this_cpu_ptr(pmu->hw_events);
1008
1009	/*
1010	 * We keep enabling userspace access to CYCLE, TIME and INSTRET via the
1011	 * legacy option but that will be removed in the future.
1012	 */
1013	if (sysctl_perf_user_access == SYSCTL_LEGACY)
1014		csr_write(CSR_SCOUNTEREN, 0x7);
1015	else
1016		csr_write(CSR_SCOUNTEREN, 0x2);
1017
1018	/* Stop all the counters so that they can be enabled from perf */
1019	pmu_sbi_stop_all(pmu);
1020
1021	if (riscv_pmu_use_irq) {
1022		cpu_hw_evt->irq = riscv_pmu_irq;
1023		ALT_SBI_PMU_OVF_CLEAR_PENDING(riscv_pmu_irq_mask);
1024		enable_percpu_irq(riscv_pmu_irq, IRQ_TYPE_NONE);
1025	}
1026
1027	if (sbi_pmu_snapshot_available())
1028		return pmu_sbi_snapshot_setup(pmu, cpu);
1029
1030	return 0;
1031}
1032
1033static int pmu_sbi_dying_cpu(unsigned int cpu, struct hlist_node *node)
1034{
1035	if (riscv_pmu_use_irq) {
1036		disable_percpu_irq(riscv_pmu_irq);
1037	}
1038
1039	/* Disable all counters access for user mode now */
1040	csr_write(CSR_SCOUNTEREN, 0x0);
1041
1042	if (sbi_pmu_snapshot_available())
1043		return pmu_sbi_snapshot_disable();
1044
1045	return 0;
1046}
1047
1048static int pmu_sbi_setup_irqs(struct riscv_pmu *pmu, struct platform_device *pdev)
1049{
1050	int ret;
1051	struct cpu_hw_events __percpu *hw_events = pmu->hw_events;
1052	struct irq_domain *domain = NULL;
1053
1054	if (riscv_isa_extension_available(NULL, SSCOFPMF)) {
1055		riscv_pmu_irq_num = RV_IRQ_PMU;
1056		riscv_pmu_use_irq = true;
1057	} else if (IS_ENABLED(CONFIG_ERRATA_THEAD_PMU) &&
1058		   riscv_cached_mvendorid(0) == THEAD_VENDOR_ID &&
1059		   riscv_cached_marchid(0) == 0 &&
1060		   riscv_cached_mimpid(0) == 0) {
1061		riscv_pmu_irq_num = THEAD_C9XX_RV_IRQ_PMU;
1062		riscv_pmu_use_irq = true;
1063	} else if (riscv_isa_extension_available(NULL, XANDESPMU) &&
1064		   IS_ENABLED(CONFIG_ANDES_CUSTOM_PMU)) {
1065		riscv_pmu_irq_num = ANDES_SLI_CAUSE_BASE + ANDES_RV_IRQ_PMOVI;
1066		riscv_pmu_use_irq = true;
1067	}
1068
1069	riscv_pmu_irq_mask = BIT(riscv_pmu_irq_num % BITS_PER_LONG);
1070
1071	if (!riscv_pmu_use_irq)
1072		return -EOPNOTSUPP;
1073
1074	domain = irq_find_matching_fwnode(riscv_get_intc_hwnode(),
1075					  DOMAIN_BUS_ANY);
1076	if (!domain) {
1077		pr_err("Failed to find INTC IRQ root domain\n");
1078		return -ENODEV;
1079	}
1080
1081	riscv_pmu_irq = irq_create_mapping(domain, riscv_pmu_irq_num);
1082	if (!riscv_pmu_irq) {
1083		pr_err("Failed to map PMU interrupt for node\n");
1084		return -ENODEV;
1085	}
1086
1087	ret = request_percpu_irq(riscv_pmu_irq, pmu_sbi_ovf_handler, "riscv-pmu", hw_events);
1088	if (ret) {
1089		pr_err("registering percpu irq failed [%d]\n", ret);
1090		return ret;
1091	}
1092
1093	return 0;
1094}
1095
1096#ifdef CONFIG_CPU_PM
1097static int riscv_pm_pmu_notify(struct notifier_block *b, unsigned long cmd,
1098				void *v)
1099{
1100	struct riscv_pmu *rvpmu = container_of(b, struct riscv_pmu, riscv_pm_nb);
1101	struct cpu_hw_events *cpuc = this_cpu_ptr(rvpmu->hw_events);
1102	int enabled = bitmap_weight(cpuc->used_hw_ctrs, RISCV_MAX_COUNTERS);
1103	struct perf_event *event;
1104	int idx;
1105
1106	if (!enabled)
1107		return NOTIFY_OK;
1108
1109	for (idx = 0; idx < RISCV_MAX_COUNTERS; idx++) {
1110		event = cpuc->events[idx];
1111		if (!event)
1112			continue;
1113
1114		switch (cmd) {
1115		case CPU_PM_ENTER:
1116			/*
1117			 * Stop and update the counter
1118			 */
1119			riscv_pmu_stop(event, PERF_EF_UPDATE);
1120			break;
1121		case CPU_PM_EXIT:
1122		case CPU_PM_ENTER_FAILED:
1123			/*
1124			 * Restore and enable the counter.
1125			 */
1126			riscv_pmu_start(event, PERF_EF_RELOAD);
1127			break;
1128		default:
1129			break;
1130		}
1131	}
1132
1133	return NOTIFY_OK;
1134}
1135
1136static int riscv_pm_pmu_register(struct riscv_pmu *pmu)
1137{
1138	pmu->riscv_pm_nb.notifier_call = riscv_pm_pmu_notify;
1139	return cpu_pm_register_notifier(&pmu->riscv_pm_nb);
1140}
1141
1142static void riscv_pm_pmu_unregister(struct riscv_pmu *pmu)
1143{
1144	cpu_pm_unregister_notifier(&pmu->riscv_pm_nb);
1145}
1146#else
1147static inline int riscv_pm_pmu_register(struct riscv_pmu *pmu) { return 0; }
1148static inline void riscv_pm_pmu_unregister(struct riscv_pmu *pmu) { }
1149#endif
1150
1151static void riscv_pmu_destroy(struct riscv_pmu *pmu)
1152{
1153	if (sbi_v2_available) {
1154		if (sbi_pmu_snapshot_available()) {
1155			pmu_sbi_snapshot_disable();
1156			pmu_sbi_snapshot_free(pmu);
1157		}
1158	}
1159	riscv_pm_pmu_unregister(pmu);
1160	cpuhp_state_remove_instance(CPUHP_AP_PERF_RISCV_STARTING, &pmu->node);
1161}
1162
1163static void pmu_sbi_event_init(struct perf_event *event)
1164{
1165	/*
1166	 * The permissions are set at event_init so that we do not depend
1167	 * on the sysctl value that can change.
1168	 */
1169	if (sysctl_perf_user_access == SYSCTL_NO_USER_ACCESS)
1170		event->hw.flags |= PERF_EVENT_FLAG_NO_USER_ACCESS;
1171	else if (sysctl_perf_user_access == SYSCTL_USER_ACCESS)
1172		event->hw.flags |= PERF_EVENT_FLAG_USER_ACCESS;
1173	else
1174		event->hw.flags |= PERF_EVENT_FLAG_LEGACY;
1175}
1176
1177static void pmu_sbi_event_mapped(struct perf_event *event, struct mm_struct *mm)
1178{
1179	if (event->hw.flags & PERF_EVENT_FLAG_NO_USER_ACCESS)
1180		return;
1181
1182	if (event->hw.flags & PERF_EVENT_FLAG_LEGACY) {
1183		if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES &&
1184		    event->attr.config != PERF_COUNT_HW_INSTRUCTIONS) {
1185			return;
1186		}
1187	}
1188
1189	/*
1190	 * The user mmapped the event to directly access it: this is where
1191	 * we determine based on sysctl_perf_user_access if we grant userspace
1192	 * the direct access to this event. That means that within the same
1193	 * task, some events may be directly accessible and some other may not,
1194	 * if the user changes the value of sysctl_perf_user_accesss in the
1195	 * meantime.
1196	 */
1197
1198	event->hw.flags |= PERF_EVENT_FLAG_USER_READ_CNT;
1199
1200	/*
1201	 * We must enable userspace access *before* advertising in the user page
1202	 * that it is possible to do so to avoid any race.
1203	 * And we must notify all cpus here because threads that currently run
1204	 * on other cpus will try to directly access the counter too without
1205	 * calling pmu_sbi_ctr_start.
1206	 */
1207	if (event->hw.flags & PERF_EVENT_FLAG_USER_ACCESS)
1208		on_each_cpu_mask(mm_cpumask(mm),
1209				 pmu_sbi_set_scounteren, (void *)event, 1);
1210}
1211
1212static void pmu_sbi_event_unmapped(struct perf_event *event, struct mm_struct *mm)
1213{
1214	if (event->hw.flags & PERF_EVENT_FLAG_NO_USER_ACCESS)
1215		return;
1216
1217	if (event->hw.flags & PERF_EVENT_FLAG_LEGACY) {
1218		if (event->attr.config != PERF_COUNT_HW_CPU_CYCLES &&
1219		    event->attr.config != PERF_COUNT_HW_INSTRUCTIONS) {
1220			return;
1221		}
1222	}
1223
1224	/*
1225	 * Here we can directly remove user access since the user does not have
1226	 * access to the user page anymore so we avoid the racy window where the
1227	 * user could have read cap_user_rdpmc to true right before we disable
1228	 * it.
1229	 */
1230	event->hw.flags &= ~PERF_EVENT_FLAG_USER_READ_CNT;
1231
1232	if (event->hw.flags & PERF_EVENT_FLAG_USER_ACCESS)
1233		on_each_cpu_mask(mm_cpumask(mm),
1234				 pmu_sbi_reset_scounteren, (void *)event, 1);
1235}
1236
1237static void riscv_pmu_update_counter_access(void *info)
1238{
1239	if (sysctl_perf_user_access == SYSCTL_LEGACY)
1240		csr_write(CSR_SCOUNTEREN, 0x7);
1241	else
1242		csr_write(CSR_SCOUNTEREN, 0x2);
1243}
1244
1245static int riscv_pmu_proc_user_access_handler(struct ctl_table *table,
1246					      int write, void *buffer,
1247					      size_t *lenp, loff_t *ppos)
1248{
1249	int prev = sysctl_perf_user_access;
1250	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
1251
1252	/*
1253	 * Test against the previous value since we clear SCOUNTEREN when
1254	 * sysctl_perf_user_access is set to SYSCTL_USER_ACCESS, but we should
1255	 * not do that if that was already the case.
1256	 */
1257	if (ret || !write || prev == sysctl_perf_user_access)
1258		return ret;
1259
1260	on_each_cpu(riscv_pmu_update_counter_access, NULL, 1);
1261
1262	return 0;
1263}
1264
1265static struct ctl_table sbi_pmu_sysctl_table[] = {
1266	{
1267		.procname       = "perf_user_access",
1268		.data		= &sysctl_perf_user_access,
1269		.maxlen		= sizeof(unsigned int),
1270		.mode           = 0644,
1271		.proc_handler	= riscv_pmu_proc_user_access_handler,
1272		.extra1		= SYSCTL_ZERO,
1273		.extra2		= SYSCTL_TWO,
1274	},
1275};
1276
1277static int pmu_sbi_device_probe(struct platform_device *pdev)
1278{
1279	struct riscv_pmu *pmu = NULL;
1280	int ret = -ENODEV;
1281	int num_counters;
1282
1283	pr_info("SBI PMU extension is available\n");
1284	pmu = riscv_pmu_alloc();
1285	if (!pmu)
1286		return -ENOMEM;
1287
1288	num_counters = pmu_sbi_find_num_ctrs();
1289	if (num_counters < 0) {
1290		pr_err("SBI PMU extension doesn't provide any counters\n");
1291		goto out_free;
1292	}
1293
1294	/* It is possible to get from SBI more than max number of counters */
1295	if (num_counters > RISCV_MAX_COUNTERS) {
1296		num_counters = RISCV_MAX_COUNTERS;
1297		pr_info("SBI returned more than maximum number of counters. Limiting the number of counters to %d\n", num_counters);
1298	}
1299
1300	/* cache all the information about counters now */
1301	if (pmu_sbi_get_ctrinfo(num_counters, &cmask))
1302		goto out_free;
1303
1304	ret = pmu_sbi_setup_irqs(pmu, pdev);
1305	if (ret < 0) {
1306		pr_info("Perf sampling/filtering is not supported as sscof extension is not available\n");
1307		pmu->pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1308		pmu->pmu.capabilities |= PERF_PMU_CAP_NO_EXCLUDE;
1309	}
1310
1311	pmu->pmu.attr_groups = riscv_pmu_attr_groups;
1312	pmu->pmu.parent = &pdev->dev;
1313	pmu->cmask = cmask;
1314	pmu->ctr_start = pmu_sbi_ctr_start;
1315	pmu->ctr_stop = pmu_sbi_ctr_stop;
1316	pmu->event_map = pmu_sbi_event_map;
1317	pmu->ctr_get_idx = pmu_sbi_ctr_get_idx;
1318	pmu->ctr_get_width = pmu_sbi_ctr_get_width;
1319	pmu->ctr_clear_idx = pmu_sbi_ctr_clear_idx;
1320	pmu->ctr_read = pmu_sbi_ctr_read;
1321	pmu->event_init = pmu_sbi_event_init;
1322	pmu->event_mapped = pmu_sbi_event_mapped;
1323	pmu->event_unmapped = pmu_sbi_event_unmapped;
1324	pmu->csr_index = pmu_sbi_csr_index;
1325
1326	ret = riscv_pm_pmu_register(pmu);
1327	if (ret)
1328		goto out_unregister;
1329
1330	ret = perf_pmu_register(&pmu->pmu, "cpu", PERF_TYPE_RAW);
1331	if (ret)
1332		goto out_unregister;
1333
1334	/* SBI PMU Snapsphot is only available in SBI v2.0 */
1335	if (sbi_v2_available) {
1336		ret = pmu_sbi_snapshot_alloc(pmu);
1337		if (ret)
1338			goto out_unregister;
1339
1340		ret = pmu_sbi_snapshot_setup(pmu, smp_processor_id());
1341		if (ret) {
1342			/* Snapshot is an optional feature. Continue if not available */
1343			pmu_sbi_snapshot_free(pmu);
1344		} else {
1345			pr_info("SBI PMU snapshot detected\n");
1346			/*
1347			 * We enable it once here for the boot cpu. If snapshot shmem setup
1348			 * fails during cpu hotplug process, it will fail to start the cpu
1349			 * as we can not handle hetergenous PMUs with different snapshot
1350			 * capability.
1351			 */
1352			static_branch_enable(&sbi_pmu_snapshot_available);
1353		}
1354	}
1355
1356	register_sysctl("kernel", sbi_pmu_sysctl_table);
1357
1358	ret = cpuhp_state_add_instance(CPUHP_AP_PERF_RISCV_STARTING, &pmu->node);
1359	if (ret)
1360		goto out_unregister;
1361
1362	return 0;
1363
1364out_unregister:
1365	riscv_pmu_destroy(pmu);
1366
1367out_free:
1368	kfree(pmu);
1369	return ret;
1370}
1371
1372static struct platform_driver pmu_sbi_driver = {
1373	.probe		= pmu_sbi_device_probe,
1374	.driver		= {
1375		.name	= RISCV_PMU_SBI_PDEV_NAME,
1376	},
1377};
1378
1379static int __init pmu_sbi_devinit(void)
1380{
1381	int ret;
1382	struct platform_device *pdev;
1383
1384	if (sbi_spec_version < sbi_mk_version(0, 3) ||
1385	    !sbi_probe_extension(SBI_EXT_PMU)) {
1386		return 0;
1387	}
1388
1389	if (sbi_spec_version >= sbi_mk_version(2, 0))
1390		sbi_v2_available = true;
1391
1392	ret = cpuhp_setup_state_multi(CPUHP_AP_PERF_RISCV_STARTING,
1393				      "perf/riscv/pmu:starting",
1394				      pmu_sbi_starting_cpu, pmu_sbi_dying_cpu);
1395	if (ret) {
1396		pr_err("CPU hotplug notifier could not be registered: %d\n",
1397		       ret);
1398		return ret;
1399	}
1400
1401	ret = platform_driver_register(&pmu_sbi_driver);
1402	if (ret)
1403		return ret;
1404
1405	pdev = platform_device_register_simple(RISCV_PMU_SBI_PDEV_NAME, -1, NULL, 0);
1406	if (IS_ERR(pdev)) {
1407		platform_driver_unregister(&pmu_sbi_driver);
1408		return PTR_ERR(pdev);
1409	}
1410
1411	/* Notify legacy implementation that SBI pmu is available*/
1412	riscv_pmu_legacy_skip_init();
1413
1414	return ret;
1415}
1416device_initcall(pmu_sbi_devinit)
1417