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