Linux Audio

Check our new training course

Linux debugging, profiling, tracing and performance analysis training

Apr 14-17, 2025
Register
Loading...
v6.2
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Perf support for the Statistical Profiling Extension, introduced as
   4 * part of ARMv8.2.
   5 *
   6 * Copyright (C) 2016 ARM Limited
   7 *
   8 * Author: Will Deacon <will.deacon@arm.com>
   9 */
  10
  11#define PMUNAME					"arm_spe"
  12#define DRVNAME					PMUNAME "_pmu"
  13#define pr_fmt(fmt)				DRVNAME ": " fmt
  14
  15#include <linux/bitops.h>
  16#include <linux/bug.h>
  17#include <linux/capability.h>
  18#include <linux/cpuhotplug.h>
  19#include <linux/cpumask.h>
  20#include <linux/device.h>
  21#include <linux/errno.h>
  22#include <linux/interrupt.h>
  23#include <linux/irq.h>
  24#include <linux/kernel.h>
  25#include <linux/list.h>
  26#include <linux/module.h>
  27#include <linux/of_address.h>
  28#include <linux/of_device.h>
  29#include <linux/perf_event.h>
  30#include <linux/perf/arm_pmu.h>
  31#include <linux/platform_device.h>
  32#include <linux/printk.h>
  33#include <linux/slab.h>
  34#include <linux/smp.h>
  35#include <linux/vmalloc.h>
  36
  37#include <asm/barrier.h>
  38#include <asm/cpufeature.h>
  39#include <asm/mmu.h>
  40#include <asm/sysreg.h>
  41
  42/*
  43 * Cache if the event is allowed to trace Context information.
  44 * This allows us to perform the check, i.e, perfmon_capable(),
  45 * in the context of the event owner, once, during the event_init().
  46 */
  47#define SPE_PMU_HW_FLAGS_CX			0x00001
  48
  49static_assert((PERF_EVENT_FLAG_ARCH & SPE_PMU_HW_FLAGS_CX) == SPE_PMU_HW_FLAGS_CX);
  50
  51static void set_spe_event_has_cx(struct perf_event *event)
  52{
  53	if (IS_ENABLED(CONFIG_PID_IN_CONTEXTIDR) && perfmon_capable())
  54		event->hw.flags |= SPE_PMU_HW_FLAGS_CX;
  55}
  56
  57static bool get_spe_event_has_cx(struct perf_event *event)
  58{
  59	return !!(event->hw.flags & SPE_PMU_HW_FLAGS_CX);
  60}
  61
  62#define ARM_SPE_BUF_PAD_BYTE			0
  63
  64struct arm_spe_pmu_buf {
  65	int					nr_pages;
  66	bool					snapshot;
  67	void					*base;
  68};
  69
  70struct arm_spe_pmu {
  71	struct pmu				pmu;
  72	struct platform_device			*pdev;
  73	cpumask_t				supported_cpus;
  74	struct hlist_node			hotplug_node;
  75
  76	int					irq; /* PPI */
  77	u16					pmsver;
  78	u16					min_period;
  79	u16					counter_sz;
  80
  81#define SPE_PMU_FEAT_FILT_EVT			(1UL << 0)
  82#define SPE_PMU_FEAT_FILT_TYP			(1UL << 1)
  83#define SPE_PMU_FEAT_FILT_LAT			(1UL << 2)
  84#define SPE_PMU_FEAT_ARCH_INST			(1UL << 3)
  85#define SPE_PMU_FEAT_LDS			(1UL << 4)
  86#define SPE_PMU_FEAT_ERND			(1UL << 5)
  87#define SPE_PMU_FEAT_DEV_PROBED			(1UL << 63)
  88	u64					features;
  89
  90	u16					max_record_sz;
  91	u16					align;
  92	struct perf_output_handle __percpu	*handle;
  93};
  94
  95#define to_spe_pmu(p) (container_of(p, struct arm_spe_pmu, pmu))
  96
  97/* Convert a free-running index from perf into an SPE buffer offset */
  98#define PERF_IDX2OFF(idx, buf)	((idx) % ((buf)->nr_pages << PAGE_SHIFT))
  99
 100/* Keep track of our dynamic hotplug state */
 101static enum cpuhp_state arm_spe_pmu_online;
 102
 103enum arm_spe_pmu_buf_fault_action {
 104	SPE_PMU_BUF_FAULT_ACT_SPURIOUS,
 105	SPE_PMU_BUF_FAULT_ACT_FATAL,
 106	SPE_PMU_BUF_FAULT_ACT_OK,
 107};
 108
 109/* This sysfs gunk was really good fun to write. */
 110enum arm_spe_pmu_capabilities {
 111	SPE_PMU_CAP_ARCH_INST = 0,
 112	SPE_PMU_CAP_ERND,
 113	SPE_PMU_CAP_FEAT_MAX,
 114	SPE_PMU_CAP_CNT_SZ = SPE_PMU_CAP_FEAT_MAX,
 115	SPE_PMU_CAP_MIN_IVAL,
 116};
 117
 118static int arm_spe_pmu_feat_caps[SPE_PMU_CAP_FEAT_MAX] = {
 119	[SPE_PMU_CAP_ARCH_INST]	= SPE_PMU_FEAT_ARCH_INST,
 120	[SPE_PMU_CAP_ERND]	= SPE_PMU_FEAT_ERND,
 121};
 122
 123static u32 arm_spe_pmu_cap_get(struct arm_spe_pmu *spe_pmu, int cap)
 124{
 125	if (cap < SPE_PMU_CAP_FEAT_MAX)
 126		return !!(spe_pmu->features & arm_spe_pmu_feat_caps[cap]);
 127
 128	switch (cap) {
 129	case SPE_PMU_CAP_CNT_SZ:
 130		return spe_pmu->counter_sz;
 131	case SPE_PMU_CAP_MIN_IVAL:
 132		return spe_pmu->min_period;
 133	default:
 134		WARN(1, "unknown cap %d\n", cap);
 135	}
 136
 137	return 0;
 138}
 139
 140static ssize_t arm_spe_pmu_cap_show(struct device *dev,
 141				    struct device_attribute *attr,
 142				    char *buf)
 143{
 144	struct arm_spe_pmu *spe_pmu = dev_get_drvdata(dev);
 145	struct dev_ext_attribute *ea =
 146		container_of(attr, struct dev_ext_attribute, attr);
 147	int cap = (long)ea->var;
 148
 149	return sysfs_emit(buf, "%u\n", arm_spe_pmu_cap_get(spe_pmu, cap));
 150}
 151
 152#define SPE_EXT_ATTR_ENTRY(_name, _func, _var)				\
 153	&((struct dev_ext_attribute[]) {				\
 154		{ __ATTR(_name, S_IRUGO, _func, NULL), (void *)_var }	\
 155	})[0].attr.attr
 156
 157#define SPE_CAP_EXT_ATTR_ENTRY(_name, _var)				\
 158	SPE_EXT_ATTR_ENTRY(_name, arm_spe_pmu_cap_show, _var)
 159
 160static struct attribute *arm_spe_pmu_cap_attr[] = {
 161	SPE_CAP_EXT_ATTR_ENTRY(arch_inst, SPE_PMU_CAP_ARCH_INST),
 162	SPE_CAP_EXT_ATTR_ENTRY(ernd, SPE_PMU_CAP_ERND),
 163	SPE_CAP_EXT_ATTR_ENTRY(count_size, SPE_PMU_CAP_CNT_SZ),
 164	SPE_CAP_EXT_ATTR_ENTRY(min_interval, SPE_PMU_CAP_MIN_IVAL),
 165	NULL,
 166};
 167
 168static const struct attribute_group arm_spe_pmu_cap_group = {
 169	.name	= "caps",
 170	.attrs	= arm_spe_pmu_cap_attr,
 171};
 172
 173/* User ABI */
 174#define ATTR_CFG_FLD_ts_enable_CFG		config	/* PMSCR_EL1.TS */
 175#define ATTR_CFG_FLD_ts_enable_LO		0
 176#define ATTR_CFG_FLD_ts_enable_HI		0
 177#define ATTR_CFG_FLD_pa_enable_CFG		config	/* PMSCR_EL1.PA */
 178#define ATTR_CFG_FLD_pa_enable_LO		1
 179#define ATTR_CFG_FLD_pa_enable_HI		1
 180#define ATTR_CFG_FLD_pct_enable_CFG		config	/* PMSCR_EL1.PCT */
 181#define ATTR_CFG_FLD_pct_enable_LO		2
 182#define ATTR_CFG_FLD_pct_enable_HI		2
 183#define ATTR_CFG_FLD_jitter_CFG			config	/* PMSIRR_EL1.RND */
 184#define ATTR_CFG_FLD_jitter_LO			16
 185#define ATTR_CFG_FLD_jitter_HI			16
 186#define ATTR_CFG_FLD_branch_filter_CFG		config	/* PMSFCR_EL1.B */
 187#define ATTR_CFG_FLD_branch_filter_LO		32
 188#define ATTR_CFG_FLD_branch_filter_HI		32
 189#define ATTR_CFG_FLD_load_filter_CFG		config	/* PMSFCR_EL1.LD */
 190#define ATTR_CFG_FLD_load_filter_LO		33
 191#define ATTR_CFG_FLD_load_filter_HI		33
 192#define ATTR_CFG_FLD_store_filter_CFG		config	/* PMSFCR_EL1.ST */
 193#define ATTR_CFG_FLD_store_filter_LO		34
 194#define ATTR_CFG_FLD_store_filter_HI		34
 195
 196#define ATTR_CFG_FLD_event_filter_CFG		config1	/* PMSEVFR_EL1 */
 197#define ATTR_CFG_FLD_event_filter_LO		0
 198#define ATTR_CFG_FLD_event_filter_HI		63
 199
 200#define ATTR_CFG_FLD_min_latency_CFG		config2	/* PMSLATFR_EL1.MINLAT */
 201#define ATTR_CFG_FLD_min_latency_LO		0
 202#define ATTR_CFG_FLD_min_latency_HI		11
 203
 204/* Why does everything I do descend into this? */
 205#define __GEN_PMU_FORMAT_ATTR(cfg, lo, hi)				\
 206	(lo) == (hi) ? #cfg ":" #lo "\n" : #cfg ":" #lo "-" #hi
 207
 208#define _GEN_PMU_FORMAT_ATTR(cfg, lo, hi)				\
 209	__GEN_PMU_FORMAT_ATTR(cfg, lo, hi)
 210
 211#define GEN_PMU_FORMAT_ATTR(name)					\
 212	PMU_FORMAT_ATTR(name,						\
 213	_GEN_PMU_FORMAT_ATTR(ATTR_CFG_FLD_##name##_CFG,			\
 214			     ATTR_CFG_FLD_##name##_LO,			\
 215			     ATTR_CFG_FLD_##name##_HI))
 216
 217#define _ATTR_CFG_GET_FLD(attr, cfg, lo, hi)				\
 218	((((attr)->cfg) >> lo) & GENMASK(hi - lo, 0))
 219
 220#define ATTR_CFG_GET_FLD(attr, name)					\
 221	_ATTR_CFG_GET_FLD(attr,						\
 222			  ATTR_CFG_FLD_##name##_CFG,			\
 223			  ATTR_CFG_FLD_##name##_LO,			\
 224			  ATTR_CFG_FLD_##name##_HI)
 225
 226GEN_PMU_FORMAT_ATTR(ts_enable);
 227GEN_PMU_FORMAT_ATTR(pa_enable);
 228GEN_PMU_FORMAT_ATTR(pct_enable);
 229GEN_PMU_FORMAT_ATTR(jitter);
 230GEN_PMU_FORMAT_ATTR(branch_filter);
 231GEN_PMU_FORMAT_ATTR(load_filter);
 232GEN_PMU_FORMAT_ATTR(store_filter);
 233GEN_PMU_FORMAT_ATTR(event_filter);
 234GEN_PMU_FORMAT_ATTR(min_latency);
 235
 236static struct attribute *arm_spe_pmu_formats_attr[] = {
 237	&format_attr_ts_enable.attr,
 238	&format_attr_pa_enable.attr,
 239	&format_attr_pct_enable.attr,
 240	&format_attr_jitter.attr,
 241	&format_attr_branch_filter.attr,
 242	&format_attr_load_filter.attr,
 243	&format_attr_store_filter.attr,
 244	&format_attr_event_filter.attr,
 245	&format_attr_min_latency.attr,
 246	NULL,
 247};
 248
 249static const struct attribute_group arm_spe_pmu_format_group = {
 250	.name	= "format",
 251	.attrs	= arm_spe_pmu_formats_attr,
 252};
 253
 254static ssize_t cpumask_show(struct device *dev,
 255			    struct device_attribute *attr, char *buf)
 256{
 257	struct arm_spe_pmu *spe_pmu = dev_get_drvdata(dev);
 258
 259	return cpumap_print_to_pagebuf(true, buf, &spe_pmu->supported_cpus);
 260}
 261static DEVICE_ATTR_RO(cpumask);
 262
 263static struct attribute *arm_spe_pmu_attrs[] = {
 264	&dev_attr_cpumask.attr,
 265	NULL,
 266};
 267
 268static const struct attribute_group arm_spe_pmu_group = {
 269	.attrs	= arm_spe_pmu_attrs,
 270};
 271
 272static const struct attribute_group *arm_spe_pmu_attr_groups[] = {
 273	&arm_spe_pmu_group,
 274	&arm_spe_pmu_cap_group,
 275	&arm_spe_pmu_format_group,
 276	NULL,
 277};
 278
 279/* Convert between user ABI and register values */
 280static u64 arm_spe_event_to_pmscr(struct perf_event *event)
 281{
 282	struct perf_event_attr *attr = &event->attr;
 283	u64 reg = 0;
 284
 285	reg |= ATTR_CFG_GET_FLD(attr, ts_enable) << SYS_PMSCR_EL1_TS_SHIFT;
 286	reg |= ATTR_CFG_GET_FLD(attr, pa_enable) << SYS_PMSCR_EL1_PA_SHIFT;
 287	reg |= ATTR_CFG_GET_FLD(attr, pct_enable) << SYS_PMSCR_EL1_PCT_SHIFT;
 288
 289	if (!attr->exclude_user)
 290		reg |= BIT(SYS_PMSCR_EL1_E0SPE_SHIFT);
 291
 292	if (!attr->exclude_kernel)
 293		reg |= BIT(SYS_PMSCR_EL1_E1SPE_SHIFT);
 294
 295	if (get_spe_event_has_cx(event))
 296		reg |= BIT(SYS_PMSCR_EL1_CX_SHIFT);
 297
 298	return reg;
 299}
 300
 301static void arm_spe_event_sanitise_period(struct perf_event *event)
 302{
 303	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 304	u64 period = event->hw.sample_period;
 305	u64 max_period = SYS_PMSIRR_EL1_INTERVAL_MASK
 306			 << SYS_PMSIRR_EL1_INTERVAL_SHIFT;
 307
 308	if (period < spe_pmu->min_period)
 309		period = spe_pmu->min_period;
 310	else if (period > max_period)
 311		period = max_period;
 312	else
 313		period &= max_period;
 314
 315	event->hw.sample_period = period;
 316}
 317
 318static u64 arm_spe_event_to_pmsirr(struct perf_event *event)
 319{
 320	struct perf_event_attr *attr = &event->attr;
 321	u64 reg = 0;
 322
 323	arm_spe_event_sanitise_period(event);
 324
 325	reg |= ATTR_CFG_GET_FLD(attr, jitter) << SYS_PMSIRR_EL1_RND_SHIFT;
 326	reg |= event->hw.sample_period;
 327
 328	return reg;
 329}
 330
 331static u64 arm_spe_event_to_pmsfcr(struct perf_event *event)
 332{
 333	struct perf_event_attr *attr = &event->attr;
 334	u64 reg = 0;
 335
 336	reg |= ATTR_CFG_GET_FLD(attr, load_filter) << SYS_PMSFCR_EL1_LD_SHIFT;
 337	reg |= ATTR_CFG_GET_FLD(attr, store_filter) << SYS_PMSFCR_EL1_ST_SHIFT;
 338	reg |= ATTR_CFG_GET_FLD(attr, branch_filter) << SYS_PMSFCR_EL1_B_SHIFT;
 339
 340	if (reg)
 341		reg |= BIT(SYS_PMSFCR_EL1_FT_SHIFT);
 342
 343	if (ATTR_CFG_GET_FLD(attr, event_filter))
 344		reg |= BIT(SYS_PMSFCR_EL1_FE_SHIFT);
 345
 346	if (ATTR_CFG_GET_FLD(attr, min_latency))
 347		reg |= BIT(SYS_PMSFCR_EL1_FL_SHIFT);
 348
 349	return reg;
 350}
 351
 352static u64 arm_spe_event_to_pmsevfr(struct perf_event *event)
 353{
 354	struct perf_event_attr *attr = &event->attr;
 355	return ATTR_CFG_GET_FLD(attr, event_filter);
 356}
 357
 358static u64 arm_spe_event_to_pmslatfr(struct perf_event *event)
 359{
 360	struct perf_event_attr *attr = &event->attr;
 361	return ATTR_CFG_GET_FLD(attr, min_latency)
 362	       << SYS_PMSLATFR_EL1_MINLAT_SHIFT;
 363}
 364
 365static void arm_spe_pmu_pad_buf(struct perf_output_handle *handle, int len)
 366{
 367	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 368	u64 head = PERF_IDX2OFF(handle->head, buf);
 369
 370	memset(buf->base + head, ARM_SPE_BUF_PAD_BYTE, len);
 371	if (!buf->snapshot)
 372		perf_aux_output_skip(handle, len);
 373}
 374
 375static u64 arm_spe_pmu_next_snapshot_off(struct perf_output_handle *handle)
 376{
 377	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 378	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 379	u64 head = PERF_IDX2OFF(handle->head, buf);
 380	u64 limit = buf->nr_pages * PAGE_SIZE;
 381
 382	/*
 383	 * The trace format isn't parseable in reverse, so clamp
 384	 * the limit to half of the buffer size in snapshot mode
 385	 * so that the worst case is half a buffer of records, as
 386	 * opposed to a single record.
 387	 */
 388	if (head < limit >> 1)
 389		limit >>= 1;
 390
 391	/*
 392	 * If we're within max_record_sz of the limit, we must
 393	 * pad, move the head index and recompute the limit.
 394	 */
 395	if (limit - head < spe_pmu->max_record_sz) {
 396		arm_spe_pmu_pad_buf(handle, limit - head);
 397		handle->head = PERF_IDX2OFF(limit, buf);
 398		limit = ((buf->nr_pages * PAGE_SIZE) >> 1) + handle->head;
 399	}
 400
 401	return limit;
 402}
 403
 404static u64 __arm_spe_pmu_next_off(struct perf_output_handle *handle)
 405{
 406	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 407	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 408	const u64 bufsize = buf->nr_pages * PAGE_SIZE;
 409	u64 limit = bufsize;
 410	u64 head, tail, wakeup;
 411
 412	/*
 413	 * The head can be misaligned for two reasons:
 414	 *
 415	 * 1. The hardware left PMBPTR pointing to the first byte after
 416	 *    a record when generating a buffer management event.
 417	 *
 418	 * 2. We used perf_aux_output_skip to consume handle->size bytes
 419	 *    and CIRC_SPACE was used to compute the size, which always
 420	 *    leaves one entry free.
 421	 *
 422	 * Deal with this by padding to the next alignment boundary and
 423	 * moving the head index. If we run out of buffer space, we'll
 424	 * reduce handle->size to zero and end up reporting truncation.
 425	 */
 426	head = PERF_IDX2OFF(handle->head, buf);
 427	if (!IS_ALIGNED(head, spe_pmu->align)) {
 428		unsigned long delta = roundup(head, spe_pmu->align) - head;
 429
 430		delta = min(delta, handle->size);
 431		arm_spe_pmu_pad_buf(handle, delta);
 432		head = PERF_IDX2OFF(handle->head, buf);
 433	}
 434
 435	/* If we've run out of free space, then nothing more to do */
 436	if (!handle->size)
 437		goto no_space;
 438
 439	/* Compute the tail and wakeup indices now that we've aligned head */
 440	tail = PERF_IDX2OFF(handle->head + handle->size, buf);
 441	wakeup = PERF_IDX2OFF(handle->wakeup, buf);
 442
 443	/*
 444	 * Avoid clobbering unconsumed data. We know we have space, so
 445	 * if we see head == tail we know that the buffer is empty. If
 446	 * head > tail, then there's nothing to clobber prior to
 447	 * wrapping.
 448	 */
 449	if (head < tail)
 450		limit = round_down(tail, PAGE_SIZE);
 451
 452	/*
 453	 * Wakeup may be arbitrarily far into the future. If it's not in
 454	 * the current generation, either we'll wrap before hitting it,
 455	 * or it's in the past and has been handled already.
 456	 *
 457	 * If there's a wakeup before we wrap, arrange to be woken up by
 458	 * the page boundary following it. Keep the tail boundary if
 459	 * that's lower.
 460	 */
 461	if (handle->wakeup < (handle->head + handle->size) && head <= wakeup)
 462		limit = min(limit, round_up(wakeup, PAGE_SIZE));
 463
 464	if (limit > head)
 465		return limit;
 466
 467	arm_spe_pmu_pad_buf(handle, handle->size);
 468no_space:
 469	perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED);
 470	perf_aux_output_end(handle, 0);
 471	return 0;
 472}
 473
 474static u64 arm_spe_pmu_next_off(struct perf_output_handle *handle)
 475{
 476	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 477	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 478	u64 limit = __arm_spe_pmu_next_off(handle);
 479	u64 head = PERF_IDX2OFF(handle->head, buf);
 480
 481	/*
 482	 * If the head has come too close to the end of the buffer,
 483	 * then pad to the end and recompute the limit.
 484	 */
 485	if (limit && (limit - head < spe_pmu->max_record_sz)) {
 486		arm_spe_pmu_pad_buf(handle, limit - head);
 487		limit = __arm_spe_pmu_next_off(handle);
 488	}
 489
 490	return limit;
 491}
 492
 493static void arm_spe_perf_aux_output_begin(struct perf_output_handle *handle,
 494					  struct perf_event *event)
 495{
 496	u64 base, limit;
 497	struct arm_spe_pmu_buf *buf;
 498
 499	/* Start a new aux session */
 500	buf = perf_aux_output_begin(handle, event);
 501	if (!buf) {
 502		event->hw.state |= PERF_HES_STOPPED;
 503		/*
 504		 * We still need to clear the limit pointer, since the
 505		 * profiler might only be disabled by virtue of a fault.
 506		 */
 507		limit = 0;
 508		goto out_write_limit;
 509	}
 510
 511	limit = buf->snapshot ? arm_spe_pmu_next_snapshot_off(handle)
 512			      : arm_spe_pmu_next_off(handle);
 513	if (limit)
 514		limit |= BIT(SYS_PMBLIMITR_EL1_E_SHIFT);
 515
 516	limit += (u64)buf->base;
 517	base = (u64)buf->base + PERF_IDX2OFF(handle->head, buf);
 518	write_sysreg_s(base, SYS_PMBPTR_EL1);
 519
 520out_write_limit:
 521	write_sysreg_s(limit, SYS_PMBLIMITR_EL1);
 522}
 523
 524static void arm_spe_perf_aux_output_end(struct perf_output_handle *handle)
 525{
 526	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 527	u64 offset, size;
 528
 529	offset = read_sysreg_s(SYS_PMBPTR_EL1) - (u64)buf->base;
 530	size = offset - PERF_IDX2OFF(handle->head, buf);
 531
 532	if (buf->snapshot)
 533		handle->head = offset;
 534
 535	perf_aux_output_end(handle, size);
 536}
 537
 538static void arm_spe_pmu_disable_and_drain_local(void)
 539{
 540	/* Disable profiling at EL0 and EL1 */
 541	write_sysreg_s(0, SYS_PMSCR_EL1);
 542	isb();
 543
 544	/* Drain any buffered data */
 545	psb_csync();
 546	dsb(nsh);
 547
 548	/* Disable the profiling buffer */
 549	write_sysreg_s(0, SYS_PMBLIMITR_EL1);
 550	isb();
 551}
 552
 553/* IRQ handling */
 554static enum arm_spe_pmu_buf_fault_action
 555arm_spe_pmu_buf_get_fault_act(struct perf_output_handle *handle)
 556{
 557	const char *err_str;
 558	u64 pmbsr;
 559	enum arm_spe_pmu_buf_fault_action ret;
 560
 561	/*
 562	 * Ensure new profiling data is visible to the CPU and any external
 563	 * aborts have been resolved.
 564	 */
 565	psb_csync();
 566	dsb(nsh);
 567
 568	/* Ensure hardware updates to PMBPTR_EL1 are visible */
 569	isb();
 570
 571	/* Service required? */
 572	pmbsr = read_sysreg_s(SYS_PMBSR_EL1);
 573	if (!(pmbsr & BIT(SYS_PMBSR_EL1_S_SHIFT)))
 574		return SPE_PMU_BUF_FAULT_ACT_SPURIOUS;
 575
 576	/*
 577	 * If we've lost data, disable profiling and also set the PARTIAL
 578	 * flag to indicate that the last record is corrupted.
 579	 */
 580	if (pmbsr & BIT(SYS_PMBSR_EL1_DL_SHIFT))
 581		perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED |
 582					     PERF_AUX_FLAG_PARTIAL);
 583
 584	/* Report collisions to userspace so that it can up the period */
 585	if (pmbsr & BIT(SYS_PMBSR_EL1_COLL_SHIFT))
 586		perf_aux_output_flag(handle, PERF_AUX_FLAG_COLLISION);
 587
 588	/* We only expect buffer management events */
 589	switch (pmbsr & (SYS_PMBSR_EL1_EC_MASK << SYS_PMBSR_EL1_EC_SHIFT)) {
 590	case SYS_PMBSR_EL1_EC_BUF:
 591		/* Handled below */
 592		break;
 593	case SYS_PMBSR_EL1_EC_FAULT_S1:
 594	case SYS_PMBSR_EL1_EC_FAULT_S2:
 595		err_str = "Unexpected buffer fault";
 596		goto out_err;
 597	default:
 598		err_str = "Unknown error code";
 599		goto out_err;
 600	}
 601
 602	/* Buffer management event */
 603	switch (pmbsr &
 604		(SYS_PMBSR_EL1_BUF_BSC_MASK << SYS_PMBSR_EL1_BUF_BSC_SHIFT)) {
 605	case SYS_PMBSR_EL1_BUF_BSC_FULL:
 606		ret = SPE_PMU_BUF_FAULT_ACT_OK;
 607		goto out_stop;
 608	default:
 609		err_str = "Unknown buffer status code";
 610	}
 611
 612out_err:
 613	pr_err_ratelimited("%s on CPU %d [PMBSR=0x%016llx, PMBPTR=0x%016llx, PMBLIMITR=0x%016llx]\n",
 614			   err_str, smp_processor_id(), pmbsr,
 615			   read_sysreg_s(SYS_PMBPTR_EL1),
 616			   read_sysreg_s(SYS_PMBLIMITR_EL1));
 617	ret = SPE_PMU_BUF_FAULT_ACT_FATAL;
 618
 619out_stop:
 620	arm_spe_perf_aux_output_end(handle);
 621	return ret;
 622}
 623
 624static irqreturn_t arm_spe_pmu_irq_handler(int irq, void *dev)
 625{
 626	struct perf_output_handle *handle = dev;
 627	struct perf_event *event = handle->event;
 628	enum arm_spe_pmu_buf_fault_action act;
 629
 630	if (!perf_get_aux(handle))
 631		return IRQ_NONE;
 632
 633	act = arm_spe_pmu_buf_get_fault_act(handle);
 634	if (act == SPE_PMU_BUF_FAULT_ACT_SPURIOUS)
 635		return IRQ_NONE;
 636
 637	/*
 638	 * Ensure perf callbacks have completed, which may disable the
 639	 * profiling buffer in response to a TRUNCATION flag.
 640	 */
 641	irq_work_run();
 642
 643	switch (act) {
 644	case SPE_PMU_BUF_FAULT_ACT_FATAL:
 645		/*
 646		 * If a fatal exception occurred then leaving the profiling
 647		 * buffer enabled is a recipe waiting to happen. Since
 648		 * fatal faults don't always imply truncation, make sure
 649		 * that the profiling buffer is disabled explicitly before
 650		 * clearing the syndrome register.
 651		 */
 652		arm_spe_pmu_disable_and_drain_local();
 653		break;
 654	case SPE_PMU_BUF_FAULT_ACT_OK:
 655		/*
 656		 * We handled the fault (the buffer was full), so resume
 657		 * profiling as long as we didn't detect truncation.
 658		 * PMBPTR might be misaligned, but we'll burn that bridge
 659		 * when we get to it.
 660		 */
 661		if (!(handle->aux_flags & PERF_AUX_FLAG_TRUNCATED)) {
 662			arm_spe_perf_aux_output_begin(handle, event);
 663			isb();
 664		}
 665		break;
 666	case SPE_PMU_BUF_FAULT_ACT_SPURIOUS:
 667		/* We've seen you before, but GCC has the memory of a sieve. */
 668		break;
 669	}
 670
 671	/* The buffer pointers are now sane, so resume profiling. */
 672	write_sysreg_s(0, SYS_PMBSR_EL1);
 673	return IRQ_HANDLED;
 674}
 675
 676static u64 arm_spe_pmsevfr_res0(u16 pmsver)
 677{
 678	switch (pmsver) {
 679	case ID_AA64DFR0_EL1_PMSVer_IMP:
 680		return SYS_PMSEVFR_EL1_RES0_8_2;
 681	case ID_AA64DFR0_EL1_PMSVer_V1P1:
 682	/* Return the highest version we support in default */
 683	default:
 684		return SYS_PMSEVFR_EL1_RES0_8_3;
 685	}
 686}
 687
 688/* Perf callbacks */
 689static int arm_spe_pmu_event_init(struct perf_event *event)
 690{
 691	u64 reg;
 692	struct perf_event_attr *attr = &event->attr;
 693	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 694
 695	/* This is, of course, deeply driver-specific */
 696	if (attr->type != event->pmu->type)
 697		return -ENOENT;
 698
 699	if (event->cpu >= 0 &&
 700	    !cpumask_test_cpu(event->cpu, &spe_pmu->supported_cpus))
 701		return -ENOENT;
 702
 703	if (arm_spe_event_to_pmsevfr(event) & arm_spe_pmsevfr_res0(spe_pmu->pmsver))
 704		return -EOPNOTSUPP;
 705
 706	if (attr->exclude_idle)
 707		return -EOPNOTSUPP;
 708
 709	/*
 710	 * Feedback-directed frequency throttling doesn't work when we
 711	 * have a buffer of samples. We'd need to manually count the
 712	 * samples in the buffer when it fills up and adjust the event
 713	 * count to reflect that. Instead, just force the user to specify
 714	 * a sample period.
 715	 */
 716	if (attr->freq)
 717		return -EINVAL;
 718
 719	reg = arm_spe_event_to_pmsfcr(event);
 720	if ((reg & BIT(SYS_PMSFCR_EL1_FE_SHIFT)) &&
 721	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_EVT))
 722		return -EOPNOTSUPP;
 723
 724	if ((reg & BIT(SYS_PMSFCR_EL1_FT_SHIFT)) &&
 725	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_TYP))
 726		return -EOPNOTSUPP;
 727
 728	if ((reg & BIT(SYS_PMSFCR_EL1_FL_SHIFT)) &&
 729	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_LAT))
 730		return -EOPNOTSUPP;
 731
 732	set_spe_event_has_cx(event);
 733	reg = arm_spe_event_to_pmscr(event);
 734	if (!perfmon_capable() &&
 735	    (reg & (BIT(SYS_PMSCR_EL1_PA_SHIFT) |
 
 736		    BIT(SYS_PMSCR_EL1_PCT_SHIFT))))
 737		return -EACCES;
 738
 739	return 0;
 740}
 741
 742static void arm_spe_pmu_start(struct perf_event *event, int flags)
 743{
 744	u64 reg;
 745	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 746	struct hw_perf_event *hwc = &event->hw;
 747	struct perf_output_handle *handle = this_cpu_ptr(spe_pmu->handle);
 748
 749	hwc->state = 0;
 750	arm_spe_perf_aux_output_begin(handle, event);
 751	if (hwc->state)
 752		return;
 753
 754	reg = arm_spe_event_to_pmsfcr(event);
 755	write_sysreg_s(reg, SYS_PMSFCR_EL1);
 756
 757	reg = arm_spe_event_to_pmsevfr(event);
 758	write_sysreg_s(reg, SYS_PMSEVFR_EL1);
 759
 760	reg = arm_spe_event_to_pmslatfr(event);
 761	write_sysreg_s(reg, SYS_PMSLATFR_EL1);
 762
 763	if (flags & PERF_EF_RELOAD) {
 764		reg = arm_spe_event_to_pmsirr(event);
 765		write_sysreg_s(reg, SYS_PMSIRR_EL1);
 766		isb();
 767		reg = local64_read(&hwc->period_left);
 768		write_sysreg_s(reg, SYS_PMSICR_EL1);
 769	}
 770
 771	reg = arm_spe_event_to_pmscr(event);
 772	isb();
 773	write_sysreg_s(reg, SYS_PMSCR_EL1);
 774}
 775
 776static void arm_spe_pmu_stop(struct perf_event *event, int flags)
 777{
 778	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 779	struct hw_perf_event *hwc = &event->hw;
 780	struct perf_output_handle *handle = this_cpu_ptr(spe_pmu->handle);
 781
 782	/* If we're already stopped, then nothing to do */
 783	if (hwc->state & PERF_HES_STOPPED)
 784		return;
 785
 786	/* Stop all trace generation */
 787	arm_spe_pmu_disable_and_drain_local();
 788
 789	if (flags & PERF_EF_UPDATE) {
 790		/*
 791		 * If there's a fault pending then ensure we contain it
 792		 * to this buffer, since we might be on the context-switch
 793		 * path.
 794		 */
 795		if (perf_get_aux(handle)) {
 796			enum arm_spe_pmu_buf_fault_action act;
 797
 798			act = arm_spe_pmu_buf_get_fault_act(handle);
 799			if (act == SPE_PMU_BUF_FAULT_ACT_SPURIOUS)
 800				arm_spe_perf_aux_output_end(handle);
 801			else
 802				write_sysreg_s(0, SYS_PMBSR_EL1);
 803		}
 804
 805		/*
 806		 * This may also contain ECOUNT, but nobody else should
 807		 * be looking at period_left, since we forbid frequency
 808		 * based sampling.
 809		 */
 810		local64_set(&hwc->period_left, read_sysreg_s(SYS_PMSICR_EL1));
 811		hwc->state |= PERF_HES_UPTODATE;
 812	}
 813
 814	hwc->state |= PERF_HES_STOPPED;
 815}
 816
 817static int arm_spe_pmu_add(struct perf_event *event, int flags)
 818{
 819	int ret = 0;
 820	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 821	struct hw_perf_event *hwc = &event->hw;
 822	int cpu = event->cpu == -1 ? smp_processor_id() : event->cpu;
 823
 824	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
 825		return -ENOENT;
 826
 827	hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
 828
 829	if (flags & PERF_EF_START) {
 830		arm_spe_pmu_start(event, PERF_EF_RELOAD);
 831		if (hwc->state & PERF_HES_STOPPED)
 832			ret = -EINVAL;
 833	}
 834
 835	return ret;
 836}
 837
 838static void arm_spe_pmu_del(struct perf_event *event, int flags)
 839{
 840	arm_spe_pmu_stop(event, PERF_EF_UPDATE);
 841}
 842
 843static void arm_spe_pmu_read(struct perf_event *event)
 844{
 845}
 846
 847static void *arm_spe_pmu_setup_aux(struct perf_event *event, void **pages,
 848				   int nr_pages, bool snapshot)
 849{
 850	int i, cpu = event->cpu;
 851	struct page **pglist;
 852	struct arm_spe_pmu_buf *buf;
 853
 854	/* We need at least two pages for this to work. */
 855	if (nr_pages < 2)
 856		return NULL;
 857
 858	/*
 859	 * We require an even number of pages for snapshot mode, so that
 860	 * we can effectively treat the buffer as consisting of two equal
 861	 * parts and give userspace a fighting chance of getting some
 862	 * useful data out of it.
 863	 */
 864	if (snapshot && (nr_pages & 1))
 865		return NULL;
 866
 867	if (cpu == -1)
 868		cpu = raw_smp_processor_id();
 869
 870	buf = kzalloc_node(sizeof(*buf), GFP_KERNEL, cpu_to_node(cpu));
 871	if (!buf)
 872		return NULL;
 873
 874	pglist = kcalloc(nr_pages, sizeof(*pglist), GFP_KERNEL);
 875	if (!pglist)
 876		goto out_free_buf;
 877
 878	for (i = 0; i < nr_pages; ++i)
 879		pglist[i] = virt_to_page(pages[i]);
 880
 881	buf->base = vmap(pglist, nr_pages, VM_MAP, PAGE_KERNEL);
 882	if (!buf->base)
 883		goto out_free_pglist;
 884
 885	buf->nr_pages	= nr_pages;
 886	buf->snapshot	= snapshot;
 887
 888	kfree(pglist);
 889	return buf;
 890
 891out_free_pglist:
 892	kfree(pglist);
 893out_free_buf:
 894	kfree(buf);
 895	return NULL;
 896}
 897
 898static void arm_spe_pmu_free_aux(void *aux)
 899{
 900	struct arm_spe_pmu_buf *buf = aux;
 901
 902	vunmap(buf->base);
 903	kfree(buf);
 904}
 905
 906/* Initialisation and teardown functions */
 907static int arm_spe_pmu_perf_init(struct arm_spe_pmu *spe_pmu)
 908{
 909	static atomic_t pmu_idx = ATOMIC_INIT(-1);
 910
 911	int idx;
 912	char *name;
 913	struct device *dev = &spe_pmu->pdev->dev;
 914
 915	spe_pmu->pmu = (struct pmu) {
 916		.module = THIS_MODULE,
 917		.capabilities	= PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE,
 918		.attr_groups	= arm_spe_pmu_attr_groups,
 919		/*
 920		 * We hitch a ride on the software context here, so that
 921		 * we can support per-task profiling (which is not possible
 922		 * with the invalid context as it doesn't get sched callbacks).
 923		 * This requires that userspace either uses a dummy event for
 924		 * perf_event_open, since the aux buffer is not setup until
 925		 * a subsequent mmap, or creates the profiling event in a
 926		 * disabled state and explicitly PERF_EVENT_IOC_ENABLEs it
 927		 * once the buffer has been created.
 928		 */
 929		.task_ctx_nr	= perf_sw_context,
 930		.event_init	= arm_spe_pmu_event_init,
 931		.add		= arm_spe_pmu_add,
 932		.del		= arm_spe_pmu_del,
 933		.start		= arm_spe_pmu_start,
 934		.stop		= arm_spe_pmu_stop,
 935		.read		= arm_spe_pmu_read,
 936		.setup_aux	= arm_spe_pmu_setup_aux,
 937		.free_aux	= arm_spe_pmu_free_aux,
 938	};
 939
 940	idx = atomic_inc_return(&pmu_idx);
 941	name = devm_kasprintf(dev, GFP_KERNEL, "%s_%d", PMUNAME, idx);
 942	if (!name) {
 943		dev_err(dev, "failed to allocate name for pmu %d\n", idx);
 944		return -ENOMEM;
 945	}
 946
 947	return perf_pmu_register(&spe_pmu->pmu, name, -1);
 948}
 949
 950static void arm_spe_pmu_perf_destroy(struct arm_spe_pmu *spe_pmu)
 951{
 952	perf_pmu_unregister(&spe_pmu->pmu);
 953}
 954
 955static void __arm_spe_pmu_dev_probe(void *info)
 956{
 957	int fld;
 958	u64 reg;
 959	struct arm_spe_pmu *spe_pmu = info;
 960	struct device *dev = &spe_pmu->pdev->dev;
 961
 962	fld = cpuid_feature_extract_unsigned_field(read_cpuid(ID_AA64DFR0_EL1),
 963						   ID_AA64DFR0_EL1_PMSVer_SHIFT);
 964	if (!fld) {
 965		dev_err(dev,
 966			"unsupported ID_AA64DFR0_EL1.PMSVer [%d] on CPU %d\n",
 967			fld, smp_processor_id());
 968		return;
 969	}
 970	spe_pmu->pmsver = (u16)fld;
 971
 972	/* Read PMBIDR first to determine whether or not we have access */
 973	reg = read_sysreg_s(SYS_PMBIDR_EL1);
 974	if (reg & BIT(SYS_PMBIDR_EL1_P_SHIFT)) {
 975		dev_err(dev,
 976			"profiling buffer owned by higher exception level\n");
 977		return;
 978	}
 979
 980	/* Minimum alignment. If it's out-of-range, then fail the probe */
 981	fld = reg >> SYS_PMBIDR_EL1_ALIGN_SHIFT & SYS_PMBIDR_EL1_ALIGN_MASK;
 982	spe_pmu->align = 1 << fld;
 983	if (spe_pmu->align > SZ_2K) {
 984		dev_err(dev, "unsupported PMBIDR.Align [%d] on CPU %d\n",
 985			fld, smp_processor_id());
 986		return;
 987	}
 988
 989	/* It's now safe to read PMSIDR and figure out what we've got */
 990	reg = read_sysreg_s(SYS_PMSIDR_EL1);
 991	if (reg & BIT(SYS_PMSIDR_EL1_FE_SHIFT))
 992		spe_pmu->features |= SPE_PMU_FEAT_FILT_EVT;
 993
 994	if (reg & BIT(SYS_PMSIDR_EL1_FT_SHIFT))
 995		spe_pmu->features |= SPE_PMU_FEAT_FILT_TYP;
 996
 997	if (reg & BIT(SYS_PMSIDR_EL1_FL_SHIFT))
 998		spe_pmu->features |= SPE_PMU_FEAT_FILT_LAT;
 999
1000	if (reg & BIT(SYS_PMSIDR_EL1_ARCHINST_SHIFT))
1001		spe_pmu->features |= SPE_PMU_FEAT_ARCH_INST;
1002
1003	if (reg & BIT(SYS_PMSIDR_EL1_LDS_SHIFT))
1004		spe_pmu->features |= SPE_PMU_FEAT_LDS;
1005
1006	if (reg & BIT(SYS_PMSIDR_EL1_ERND_SHIFT))
1007		spe_pmu->features |= SPE_PMU_FEAT_ERND;
1008
1009	/* This field has a spaced out encoding, so just use a look-up */
1010	fld = reg >> SYS_PMSIDR_EL1_INTERVAL_SHIFT & SYS_PMSIDR_EL1_INTERVAL_MASK;
1011	switch (fld) {
1012	case 0:
1013		spe_pmu->min_period = 256;
1014		break;
1015	case 2:
1016		spe_pmu->min_period = 512;
1017		break;
1018	case 3:
1019		spe_pmu->min_period = 768;
1020		break;
1021	case 4:
1022		spe_pmu->min_period = 1024;
1023		break;
1024	case 5:
1025		spe_pmu->min_period = 1536;
1026		break;
1027	case 6:
1028		spe_pmu->min_period = 2048;
1029		break;
1030	case 7:
1031		spe_pmu->min_period = 3072;
1032		break;
1033	default:
1034		dev_warn(dev, "unknown PMSIDR_EL1.Interval [%d]; assuming 8\n",
1035			 fld);
1036		fallthrough;
1037	case 8:
1038		spe_pmu->min_period = 4096;
1039	}
1040
1041	/* Maximum record size. If it's out-of-range, then fail the probe */
1042	fld = reg >> SYS_PMSIDR_EL1_MAXSIZE_SHIFT & SYS_PMSIDR_EL1_MAXSIZE_MASK;
1043	spe_pmu->max_record_sz = 1 << fld;
1044	if (spe_pmu->max_record_sz > SZ_2K || spe_pmu->max_record_sz < 16) {
1045		dev_err(dev, "unsupported PMSIDR_EL1.MaxSize [%d] on CPU %d\n",
1046			fld, smp_processor_id());
1047		return;
1048	}
1049
1050	fld = reg >> SYS_PMSIDR_EL1_COUNTSIZE_SHIFT & SYS_PMSIDR_EL1_COUNTSIZE_MASK;
1051	switch (fld) {
1052	default:
1053		dev_warn(dev, "unknown PMSIDR_EL1.CountSize [%d]; assuming 2\n",
1054			 fld);
1055		fallthrough;
1056	case 2:
1057		spe_pmu->counter_sz = 12;
1058		break;
1059	case 3:
1060		spe_pmu->counter_sz = 16;
1061	}
1062
1063	dev_info(dev,
1064		 "probed for CPUs %*pbl [max_record_sz %u, align %u, features 0x%llx]\n",
1065		 cpumask_pr_args(&spe_pmu->supported_cpus),
1066		 spe_pmu->max_record_sz, spe_pmu->align, spe_pmu->features);
1067
1068	spe_pmu->features |= SPE_PMU_FEAT_DEV_PROBED;
1069}
1070
1071static void __arm_spe_pmu_reset_local(void)
1072{
1073	/*
1074	 * This is probably overkill, as we have no idea where we're
1075	 * draining any buffered data to...
1076	 */
1077	arm_spe_pmu_disable_and_drain_local();
1078
1079	/* Reset the buffer base pointer */
1080	write_sysreg_s(0, SYS_PMBPTR_EL1);
1081	isb();
1082
1083	/* Clear any pending management interrupts */
1084	write_sysreg_s(0, SYS_PMBSR_EL1);
1085	isb();
1086}
1087
1088static void __arm_spe_pmu_setup_one(void *info)
1089{
1090	struct arm_spe_pmu *spe_pmu = info;
1091
1092	__arm_spe_pmu_reset_local();
1093	enable_percpu_irq(spe_pmu->irq, IRQ_TYPE_NONE);
1094}
1095
1096static void __arm_spe_pmu_stop_one(void *info)
1097{
1098	struct arm_spe_pmu *spe_pmu = info;
1099
1100	disable_percpu_irq(spe_pmu->irq);
1101	__arm_spe_pmu_reset_local();
1102}
1103
1104static int arm_spe_pmu_cpu_startup(unsigned int cpu, struct hlist_node *node)
1105{
1106	struct arm_spe_pmu *spe_pmu;
1107
1108	spe_pmu = hlist_entry_safe(node, struct arm_spe_pmu, hotplug_node);
1109	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
1110		return 0;
1111
1112	__arm_spe_pmu_setup_one(spe_pmu);
1113	return 0;
1114}
1115
1116static int arm_spe_pmu_cpu_teardown(unsigned int cpu, struct hlist_node *node)
1117{
1118	struct arm_spe_pmu *spe_pmu;
1119
1120	spe_pmu = hlist_entry_safe(node, struct arm_spe_pmu, hotplug_node);
1121	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
1122		return 0;
1123
1124	__arm_spe_pmu_stop_one(spe_pmu);
1125	return 0;
1126}
1127
1128static int arm_spe_pmu_dev_init(struct arm_spe_pmu *spe_pmu)
1129{
1130	int ret;
1131	cpumask_t *mask = &spe_pmu->supported_cpus;
1132
1133	/* Make sure we probe the hardware on a relevant CPU */
1134	ret = smp_call_function_any(mask,  __arm_spe_pmu_dev_probe, spe_pmu, 1);
1135	if (ret || !(spe_pmu->features & SPE_PMU_FEAT_DEV_PROBED))
1136		return -ENXIO;
1137
1138	/* Request our PPIs (note that the IRQ is still disabled) */
1139	ret = request_percpu_irq(spe_pmu->irq, arm_spe_pmu_irq_handler, DRVNAME,
1140				 spe_pmu->handle);
1141	if (ret)
1142		return ret;
1143
1144	/*
1145	 * Register our hotplug notifier now so we don't miss any events.
1146	 * This will enable the IRQ for any supported CPUs that are already
1147	 * up.
1148	 */
1149	ret = cpuhp_state_add_instance(arm_spe_pmu_online,
1150				       &spe_pmu->hotplug_node);
1151	if (ret)
1152		free_percpu_irq(spe_pmu->irq, spe_pmu->handle);
1153
1154	return ret;
1155}
1156
1157static void arm_spe_pmu_dev_teardown(struct arm_spe_pmu *spe_pmu)
1158{
1159	cpuhp_state_remove_instance(arm_spe_pmu_online, &spe_pmu->hotplug_node);
1160	free_percpu_irq(spe_pmu->irq, spe_pmu->handle);
1161}
1162
1163/* Driver and device probing */
1164static int arm_spe_pmu_irq_probe(struct arm_spe_pmu *spe_pmu)
1165{
1166	struct platform_device *pdev = spe_pmu->pdev;
1167	int irq = platform_get_irq(pdev, 0);
1168
1169	if (irq < 0)
1170		return -ENXIO;
1171
1172	if (!irq_is_percpu(irq)) {
1173		dev_err(&pdev->dev, "expected PPI but got SPI (%d)\n", irq);
1174		return -EINVAL;
1175	}
1176
1177	if (irq_get_percpu_devid_partition(irq, &spe_pmu->supported_cpus)) {
1178		dev_err(&pdev->dev, "failed to get PPI partition (%d)\n", irq);
1179		return -EINVAL;
1180	}
1181
1182	spe_pmu->irq = irq;
1183	return 0;
1184}
1185
1186static const struct of_device_id arm_spe_pmu_of_match[] = {
1187	{ .compatible = "arm,statistical-profiling-extension-v1", .data = (void *)1 },
1188	{ /* Sentinel */ },
1189};
1190MODULE_DEVICE_TABLE(of, arm_spe_pmu_of_match);
1191
1192static const struct platform_device_id arm_spe_match[] = {
1193	{ ARMV8_SPE_PDEV_NAME, 0},
1194	{ }
1195};
1196MODULE_DEVICE_TABLE(platform, arm_spe_match);
1197
1198static int arm_spe_pmu_device_probe(struct platform_device *pdev)
1199{
1200	int ret;
1201	struct arm_spe_pmu *spe_pmu;
1202	struct device *dev = &pdev->dev;
1203
1204	/*
1205	 * If kernelspace is unmapped when running at EL0, then the SPE
1206	 * buffer will fault and prematurely terminate the AUX session.
1207	 */
1208	if (arm64_kernel_unmapped_at_el0()) {
1209		dev_warn_once(dev, "profiling buffer inaccessible. Try passing \"kpti=off\" on the kernel command line\n");
1210		return -EPERM;
1211	}
1212
1213	spe_pmu = devm_kzalloc(dev, sizeof(*spe_pmu), GFP_KERNEL);
1214	if (!spe_pmu)
1215		return -ENOMEM;
1216
1217	spe_pmu->handle = alloc_percpu(typeof(*spe_pmu->handle));
1218	if (!spe_pmu->handle)
1219		return -ENOMEM;
1220
1221	spe_pmu->pdev = pdev;
1222	platform_set_drvdata(pdev, spe_pmu);
1223
1224	ret = arm_spe_pmu_irq_probe(spe_pmu);
1225	if (ret)
1226		goto out_free_handle;
1227
1228	ret = arm_spe_pmu_dev_init(spe_pmu);
1229	if (ret)
1230		goto out_free_handle;
1231
1232	ret = arm_spe_pmu_perf_init(spe_pmu);
1233	if (ret)
1234		goto out_teardown_dev;
1235
1236	return 0;
1237
1238out_teardown_dev:
1239	arm_spe_pmu_dev_teardown(spe_pmu);
1240out_free_handle:
1241	free_percpu(spe_pmu->handle);
1242	return ret;
1243}
1244
1245static int arm_spe_pmu_device_remove(struct platform_device *pdev)
1246{
1247	struct arm_spe_pmu *spe_pmu = platform_get_drvdata(pdev);
1248
1249	arm_spe_pmu_perf_destroy(spe_pmu);
1250	arm_spe_pmu_dev_teardown(spe_pmu);
1251	free_percpu(spe_pmu->handle);
1252	return 0;
1253}
1254
1255static struct platform_driver arm_spe_pmu_driver = {
1256	.id_table = arm_spe_match,
1257	.driver	= {
1258		.name		= DRVNAME,
1259		.of_match_table	= of_match_ptr(arm_spe_pmu_of_match),
1260		.suppress_bind_attrs = true,
1261	},
1262	.probe	= arm_spe_pmu_device_probe,
1263	.remove	= arm_spe_pmu_device_remove,
1264};
1265
1266static int __init arm_spe_pmu_init(void)
1267{
1268	int ret;
1269
1270	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, DRVNAME,
1271				      arm_spe_pmu_cpu_startup,
1272				      arm_spe_pmu_cpu_teardown);
1273	if (ret < 0)
1274		return ret;
1275	arm_spe_pmu_online = ret;
1276
1277	ret = platform_driver_register(&arm_spe_pmu_driver);
1278	if (ret)
1279		cpuhp_remove_multi_state(arm_spe_pmu_online);
1280
1281	return ret;
1282}
1283
1284static void __exit arm_spe_pmu_exit(void)
1285{
1286	platform_driver_unregister(&arm_spe_pmu_driver);
1287	cpuhp_remove_multi_state(arm_spe_pmu_online);
1288}
1289
1290module_init(arm_spe_pmu_init);
1291module_exit(arm_spe_pmu_exit);
1292
1293MODULE_DESCRIPTION("Perf driver for the ARMv8.2 Statistical Profiling Extension");
1294MODULE_AUTHOR("Will Deacon <will.deacon@arm.com>");
1295MODULE_LICENSE("GPL v2");
v5.14.15
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Perf support for the Statistical Profiling Extension, introduced as
   4 * part of ARMv8.2.
   5 *
   6 * Copyright (C) 2016 ARM Limited
   7 *
   8 * Author: Will Deacon <will.deacon@arm.com>
   9 */
  10
  11#define PMUNAME					"arm_spe"
  12#define DRVNAME					PMUNAME "_pmu"
  13#define pr_fmt(fmt)				DRVNAME ": " fmt
  14
  15#include <linux/bitops.h>
  16#include <linux/bug.h>
  17#include <linux/capability.h>
  18#include <linux/cpuhotplug.h>
  19#include <linux/cpumask.h>
  20#include <linux/device.h>
  21#include <linux/errno.h>
  22#include <linux/interrupt.h>
  23#include <linux/irq.h>
  24#include <linux/kernel.h>
  25#include <linux/list.h>
  26#include <linux/module.h>
  27#include <linux/of_address.h>
  28#include <linux/of_device.h>
  29#include <linux/perf_event.h>
  30#include <linux/perf/arm_pmu.h>
  31#include <linux/platform_device.h>
  32#include <linux/printk.h>
  33#include <linux/slab.h>
  34#include <linux/smp.h>
  35#include <linux/vmalloc.h>
  36
  37#include <asm/barrier.h>
  38#include <asm/cpufeature.h>
  39#include <asm/mmu.h>
  40#include <asm/sysreg.h>
  41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  42#define ARM_SPE_BUF_PAD_BYTE			0
  43
  44struct arm_spe_pmu_buf {
  45	int					nr_pages;
  46	bool					snapshot;
  47	void					*base;
  48};
  49
  50struct arm_spe_pmu {
  51	struct pmu				pmu;
  52	struct platform_device			*pdev;
  53	cpumask_t				supported_cpus;
  54	struct hlist_node			hotplug_node;
  55
  56	int					irq; /* PPI */
  57	u16					pmsver;
  58	u16					min_period;
  59	u16					counter_sz;
  60
  61#define SPE_PMU_FEAT_FILT_EVT			(1UL << 0)
  62#define SPE_PMU_FEAT_FILT_TYP			(1UL << 1)
  63#define SPE_PMU_FEAT_FILT_LAT			(1UL << 2)
  64#define SPE_PMU_FEAT_ARCH_INST			(1UL << 3)
  65#define SPE_PMU_FEAT_LDS			(1UL << 4)
  66#define SPE_PMU_FEAT_ERND			(1UL << 5)
  67#define SPE_PMU_FEAT_DEV_PROBED			(1UL << 63)
  68	u64					features;
  69
  70	u16					max_record_sz;
  71	u16					align;
  72	struct perf_output_handle __percpu	*handle;
  73};
  74
  75#define to_spe_pmu(p) (container_of(p, struct arm_spe_pmu, pmu))
  76
  77/* Convert a free-running index from perf into an SPE buffer offset */
  78#define PERF_IDX2OFF(idx, buf)	((idx) % ((buf)->nr_pages << PAGE_SHIFT))
  79
  80/* Keep track of our dynamic hotplug state */
  81static enum cpuhp_state arm_spe_pmu_online;
  82
  83enum arm_spe_pmu_buf_fault_action {
  84	SPE_PMU_BUF_FAULT_ACT_SPURIOUS,
  85	SPE_PMU_BUF_FAULT_ACT_FATAL,
  86	SPE_PMU_BUF_FAULT_ACT_OK,
  87};
  88
  89/* This sysfs gunk was really good fun to write. */
  90enum arm_spe_pmu_capabilities {
  91	SPE_PMU_CAP_ARCH_INST = 0,
  92	SPE_PMU_CAP_ERND,
  93	SPE_PMU_CAP_FEAT_MAX,
  94	SPE_PMU_CAP_CNT_SZ = SPE_PMU_CAP_FEAT_MAX,
  95	SPE_PMU_CAP_MIN_IVAL,
  96};
  97
  98static int arm_spe_pmu_feat_caps[SPE_PMU_CAP_FEAT_MAX] = {
  99	[SPE_PMU_CAP_ARCH_INST]	= SPE_PMU_FEAT_ARCH_INST,
 100	[SPE_PMU_CAP_ERND]	= SPE_PMU_FEAT_ERND,
 101};
 102
 103static u32 arm_spe_pmu_cap_get(struct arm_spe_pmu *spe_pmu, int cap)
 104{
 105	if (cap < SPE_PMU_CAP_FEAT_MAX)
 106		return !!(spe_pmu->features & arm_spe_pmu_feat_caps[cap]);
 107
 108	switch (cap) {
 109	case SPE_PMU_CAP_CNT_SZ:
 110		return spe_pmu->counter_sz;
 111	case SPE_PMU_CAP_MIN_IVAL:
 112		return spe_pmu->min_period;
 113	default:
 114		WARN(1, "unknown cap %d\n", cap);
 115	}
 116
 117	return 0;
 118}
 119
 120static ssize_t arm_spe_pmu_cap_show(struct device *dev,
 121				    struct device_attribute *attr,
 122				    char *buf)
 123{
 124	struct arm_spe_pmu *spe_pmu = dev_get_drvdata(dev);
 125	struct dev_ext_attribute *ea =
 126		container_of(attr, struct dev_ext_attribute, attr);
 127	int cap = (long)ea->var;
 128
 129	return sysfs_emit(buf, "%u\n", arm_spe_pmu_cap_get(spe_pmu, cap));
 130}
 131
 132#define SPE_EXT_ATTR_ENTRY(_name, _func, _var)				\
 133	&((struct dev_ext_attribute[]) {				\
 134		{ __ATTR(_name, S_IRUGO, _func, NULL), (void *)_var }	\
 135	})[0].attr.attr
 136
 137#define SPE_CAP_EXT_ATTR_ENTRY(_name, _var)				\
 138	SPE_EXT_ATTR_ENTRY(_name, arm_spe_pmu_cap_show, _var)
 139
 140static struct attribute *arm_spe_pmu_cap_attr[] = {
 141	SPE_CAP_EXT_ATTR_ENTRY(arch_inst, SPE_PMU_CAP_ARCH_INST),
 142	SPE_CAP_EXT_ATTR_ENTRY(ernd, SPE_PMU_CAP_ERND),
 143	SPE_CAP_EXT_ATTR_ENTRY(count_size, SPE_PMU_CAP_CNT_SZ),
 144	SPE_CAP_EXT_ATTR_ENTRY(min_interval, SPE_PMU_CAP_MIN_IVAL),
 145	NULL,
 146};
 147
 148static const struct attribute_group arm_spe_pmu_cap_group = {
 149	.name	= "caps",
 150	.attrs	= arm_spe_pmu_cap_attr,
 151};
 152
 153/* User ABI */
 154#define ATTR_CFG_FLD_ts_enable_CFG		config	/* PMSCR_EL1.TS */
 155#define ATTR_CFG_FLD_ts_enable_LO		0
 156#define ATTR_CFG_FLD_ts_enable_HI		0
 157#define ATTR_CFG_FLD_pa_enable_CFG		config	/* PMSCR_EL1.PA */
 158#define ATTR_CFG_FLD_pa_enable_LO		1
 159#define ATTR_CFG_FLD_pa_enable_HI		1
 160#define ATTR_CFG_FLD_pct_enable_CFG		config	/* PMSCR_EL1.PCT */
 161#define ATTR_CFG_FLD_pct_enable_LO		2
 162#define ATTR_CFG_FLD_pct_enable_HI		2
 163#define ATTR_CFG_FLD_jitter_CFG			config	/* PMSIRR_EL1.RND */
 164#define ATTR_CFG_FLD_jitter_LO			16
 165#define ATTR_CFG_FLD_jitter_HI			16
 166#define ATTR_CFG_FLD_branch_filter_CFG		config	/* PMSFCR_EL1.B */
 167#define ATTR_CFG_FLD_branch_filter_LO		32
 168#define ATTR_CFG_FLD_branch_filter_HI		32
 169#define ATTR_CFG_FLD_load_filter_CFG		config	/* PMSFCR_EL1.LD */
 170#define ATTR_CFG_FLD_load_filter_LO		33
 171#define ATTR_CFG_FLD_load_filter_HI		33
 172#define ATTR_CFG_FLD_store_filter_CFG		config	/* PMSFCR_EL1.ST */
 173#define ATTR_CFG_FLD_store_filter_LO		34
 174#define ATTR_CFG_FLD_store_filter_HI		34
 175
 176#define ATTR_CFG_FLD_event_filter_CFG		config1	/* PMSEVFR_EL1 */
 177#define ATTR_CFG_FLD_event_filter_LO		0
 178#define ATTR_CFG_FLD_event_filter_HI		63
 179
 180#define ATTR_CFG_FLD_min_latency_CFG		config2	/* PMSLATFR_EL1.MINLAT */
 181#define ATTR_CFG_FLD_min_latency_LO		0
 182#define ATTR_CFG_FLD_min_latency_HI		11
 183
 184/* Why does everything I do descend into this? */
 185#define __GEN_PMU_FORMAT_ATTR(cfg, lo, hi)				\
 186	(lo) == (hi) ? #cfg ":" #lo "\n" : #cfg ":" #lo "-" #hi
 187
 188#define _GEN_PMU_FORMAT_ATTR(cfg, lo, hi)				\
 189	__GEN_PMU_FORMAT_ATTR(cfg, lo, hi)
 190
 191#define GEN_PMU_FORMAT_ATTR(name)					\
 192	PMU_FORMAT_ATTR(name,						\
 193	_GEN_PMU_FORMAT_ATTR(ATTR_CFG_FLD_##name##_CFG,			\
 194			     ATTR_CFG_FLD_##name##_LO,			\
 195			     ATTR_CFG_FLD_##name##_HI))
 196
 197#define _ATTR_CFG_GET_FLD(attr, cfg, lo, hi)				\
 198	((((attr)->cfg) >> lo) & GENMASK(hi - lo, 0))
 199
 200#define ATTR_CFG_GET_FLD(attr, name)					\
 201	_ATTR_CFG_GET_FLD(attr,						\
 202			  ATTR_CFG_FLD_##name##_CFG,			\
 203			  ATTR_CFG_FLD_##name##_LO,			\
 204			  ATTR_CFG_FLD_##name##_HI)
 205
 206GEN_PMU_FORMAT_ATTR(ts_enable);
 207GEN_PMU_FORMAT_ATTR(pa_enable);
 208GEN_PMU_FORMAT_ATTR(pct_enable);
 209GEN_PMU_FORMAT_ATTR(jitter);
 210GEN_PMU_FORMAT_ATTR(branch_filter);
 211GEN_PMU_FORMAT_ATTR(load_filter);
 212GEN_PMU_FORMAT_ATTR(store_filter);
 213GEN_PMU_FORMAT_ATTR(event_filter);
 214GEN_PMU_FORMAT_ATTR(min_latency);
 215
 216static struct attribute *arm_spe_pmu_formats_attr[] = {
 217	&format_attr_ts_enable.attr,
 218	&format_attr_pa_enable.attr,
 219	&format_attr_pct_enable.attr,
 220	&format_attr_jitter.attr,
 221	&format_attr_branch_filter.attr,
 222	&format_attr_load_filter.attr,
 223	&format_attr_store_filter.attr,
 224	&format_attr_event_filter.attr,
 225	&format_attr_min_latency.attr,
 226	NULL,
 227};
 228
 229static const struct attribute_group arm_spe_pmu_format_group = {
 230	.name	= "format",
 231	.attrs	= arm_spe_pmu_formats_attr,
 232};
 233
 234static ssize_t cpumask_show(struct device *dev,
 235			    struct device_attribute *attr, char *buf)
 236{
 237	struct arm_spe_pmu *spe_pmu = dev_get_drvdata(dev);
 238
 239	return cpumap_print_to_pagebuf(true, buf, &spe_pmu->supported_cpus);
 240}
 241static DEVICE_ATTR_RO(cpumask);
 242
 243static struct attribute *arm_spe_pmu_attrs[] = {
 244	&dev_attr_cpumask.attr,
 245	NULL,
 246};
 247
 248static const struct attribute_group arm_spe_pmu_group = {
 249	.attrs	= arm_spe_pmu_attrs,
 250};
 251
 252static const struct attribute_group *arm_spe_pmu_attr_groups[] = {
 253	&arm_spe_pmu_group,
 254	&arm_spe_pmu_cap_group,
 255	&arm_spe_pmu_format_group,
 256	NULL,
 257};
 258
 259/* Convert between user ABI and register values */
 260static u64 arm_spe_event_to_pmscr(struct perf_event *event)
 261{
 262	struct perf_event_attr *attr = &event->attr;
 263	u64 reg = 0;
 264
 265	reg |= ATTR_CFG_GET_FLD(attr, ts_enable) << SYS_PMSCR_EL1_TS_SHIFT;
 266	reg |= ATTR_CFG_GET_FLD(attr, pa_enable) << SYS_PMSCR_EL1_PA_SHIFT;
 267	reg |= ATTR_CFG_GET_FLD(attr, pct_enable) << SYS_PMSCR_EL1_PCT_SHIFT;
 268
 269	if (!attr->exclude_user)
 270		reg |= BIT(SYS_PMSCR_EL1_E0SPE_SHIFT);
 271
 272	if (!attr->exclude_kernel)
 273		reg |= BIT(SYS_PMSCR_EL1_E1SPE_SHIFT);
 274
 275	if (IS_ENABLED(CONFIG_PID_IN_CONTEXTIDR) && perfmon_capable())
 276		reg |= BIT(SYS_PMSCR_EL1_CX_SHIFT);
 277
 278	return reg;
 279}
 280
 281static void arm_spe_event_sanitise_period(struct perf_event *event)
 282{
 283	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 284	u64 period = event->hw.sample_period;
 285	u64 max_period = SYS_PMSIRR_EL1_INTERVAL_MASK
 286			 << SYS_PMSIRR_EL1_INTERVAL_SHIFT;
 287
 288	if (period < spe_pmu->min_period)
 289		period = spe_pmu->min_period;
 290	else if (period > max_period)
 291		period = max_period;
 292	else
 293		period &= max_period;
 294
 295	event->hw.sample_period = period;
 296}
 297
 298static u64 arm_spe_event_to_pmsirr(struct perf_event *event)
 299{
 300	struct perf_event_attr *attr = &event->attr;
 301	u64 reg = 0;
 302
 303	arm_spe_event_sanitise_period(event);
 304
 305	reg |= ATTR_CFG_GET_FLD(attr, jitter) << SYS_PMSIRR_EL1_RND_SHIFT;
 306	reg |= event->hw.sample_period;
 307
 308	return reg;
 309}
 310
 311static u64 arm_spe_event_to_pmsfcr(struct perf_event *event)
 312{
 313	struct perf_event_attr *attr = &event->attr;
 314	u64 reg = 0;
 315
 316	reg |= ATTR_CFG_GET_FLD(attr, load_filter) << SYS_PMSFCR_EL1_LD_SHIFT;
 317	reg |= ATTR_CFG_GET_FLD(attr, store_filter) << SYS_PMSFCR_EL1_ST_SHIFT;
 318	reg |= ATTR_CFG_GET_FLD(attr, branch_filter) << SYS_PMSFCR_EL1_B_SHIFT;
 319
 320	if (reg)
 321		reg |= BIT(SYS_PMSFCR_EL1_FT_SHIFT);
 322
 323	if (ATTR_CFG_GET_FLD(attr, event_filter))
 324		reg |= BIT(SYS_PMSFCR_EL1_FE_SHIFT);
 325
 326	if (ATTR_CFG_GET_FLD(attr, min_latency))
 327		reg |= BIT(SYS_PMSFCR_EL1_FL_SHIFT);
 328
 329	return reg;
 330}
 331
 332static u64 arm_spe_event_to_pmsevfr(struct perf_event *event)
 333{
 334	struct perf_event_attr *attr = &event->attr;
 335	return ATTR_CFG_GET_FLD(attr, event_filter);
 336}
 337
 338static u64 arm_spe_event_to_pmslatfr(struct perf_event *event)
 339{
 340	struct perf_event_attr *attr = &event->attr;
 341	return ATTR_CFG_GET_FLD(attr, min_latency)
 342	       << SYS_PMSLATFR_EL1_MINLAT_SHIFT;
 343}
 344
 345static void arm_spe_pmu_pad_buf(struct perf_output_handle *handle, int len)
 346{
 347	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 348	u64 head = PERF_IDX2OFF(handle->head, buf);
 349
 350	memset(buf->base + head, ARM_SPE_BUF_PAD_BYTE, len);
 351	if (!buf->snapshot)
 352		perf_aux_output_skip(handle, len);
 353}
 354
 355static u64 arm_spe_pmu_next_snapshot_off(struct perf_output_handle *handle)
 356{
 357	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 358	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 359	u64 head = PERF_IDX2OFF(handle->head, buf);
 360	u64 limit = buf->nr_pages * PAGE_SIZE;
 361
 362	/*
 363	 * The trace format isn't parseable in reverse, so clamp
 364	 * the limit to half of the buffer size in snapshot mode
 365	 * so that the worst case is half a buffer of records, as
 366	 * opposed to a single record.
 367	 */
 368	if (head < limit >> 1)
 369		limit >>= 1;
 370
 371	/*
 372	 * If we're within max_record_sz of the limit, we must
 373	 * pad, move the head index and recompute the limit.
 374	 */
 375	if (limit - head < spe_pmu->max_record_sz) {
 376		arm_spe_pmu_pad_buf(handle, limit - head);
 377		handle->head = PERF_IDX2OFF(limit, buf);
 378		limit = ((buf->nr_pages * PAGE_SIZE) >> 1) + handle->head;
 379	}
 380
 381	return limit;
 382}
 383
 384static u64 __arm_spe_pmu_next_off(struct perf_output_handle *handle)
 385{
 386	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 387	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 388	const u64 bufsize = buf->nr_pages * PAGE_SIZE;
 389	u64 limit = bufsize;
 390	u64 head, tail, wakeup;
 391
 392	/*
 393	 * The head can be misaligned for two reasons:
 394	 *
 395	 * 1. The hardware left PMBPTR pointing to the first byte after
 396	 *    a record when generating a buffer management event.
 397	 *
 398	 * 2. We used perf_aux_output_skip to consume handle->size bytes
 399	 *    and CIRC_SPACE was used to compute the size, which always
 400	 *    leaves one entry free.
 401	 *
 402	 * Deal with this by padding to the next alignment boundary and
 403	 * moving the head index. If we run out of buffer space, we'll
 404	 * reduce handle->size to zero and end up reporting truncation.
 405	 */
 406	head = PERF_IDX2OFF(handle->head, buf);
 407	if (!IS_ALIGNED(head, spe_pmu->align)) {
 408		unsigned long delta = roundup(head, spe_pmu->align) - head;
 409
 410		delta = min(delta, handle->size);
 411		arm_spe_pmu_pad_buf(handle, delta);
 412		head = PERF_IDX2OFF(handle->head, buf);
 413	}
 414
 415	/* If we've run out of free space, then nothing more to do */
 416	if (!handle->size)
 417		goto no_space;
 418
 419	/* Compute the tail and wakeup indices now that we've aligned head */
 420	tail = PERF_IDX2OFF(handle->head + handle->size, buf);
 421	wakeup = PERF_IDX2OFF(handle->wakeup, buf);
 422
 423	/*
 424	 * Avoid clobbering unconsumed data. We know we have space, so
 425	 * if we see head == tail we know that the buffer is empty. If
 426	 * head > tail, then there's nothing to clobber prior to
 427	 * wrapping.
 428	 */
 429	if (head < tail)
 430		limit = round_down(tail, PAGE_SIZE);
 431
 432	/*
 433	 * Wakeup may be arbitrarily far into the future. If it's not in
 434	 * the current generation, either we'll wrap before hitting it,
 435	 * or it's in the past and has been handled already.
 436	 *
 437	 * If there's a wakeup before we wrap, arrange to be woken up by
 438	 * the page boundary following it. Keep the tail boundary if
 439	 * that's lower.
 440	 */
 441	if (handle->wakeup < (handle->head + handle->size) && head <= wakeup)
 442		limit = min(limit, round_up(wakeup, PAGE_SIZE));
 443
 444	if (limit > head)
 445		return limit;
 446
 447	arm_spe_pmu_pad_buf(handle, handle->size);
 448no_space:
 449	perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED);
 450	perf_aux_output_end(handle, 0);
 451	return 0;
 452}
 453
 454static u64 arm_spe_pmu_next_off(struct perf_output_handle *handle)
 455{
 456	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 457	struct arm_spe_pmu *spe_pmu = to_spe_pmu(handle->event->pmu);
 458	u64 limit = __arm_spe_pmu_next_off(handle);
 459	u64 head = PERF_IDX2OFF(handle->head, buf);
 460
 461	/*
 462	 * If the head has come too close to the end of the buffer,
 463	 * then pad to the end and recompute the limit.
 464	 */
 465	if (limit && (limit - head < spe_pmu->max_record_sz)) {
 466		arm_spe_pmu_pad_buf(handle, limit - head);
 467		limit = __arm_spe_pmu_next_off(handle);
 468	}
 469
 470	return limit;
 471}
 472
 473static void arm_spe_perf_aux_output_begin(struct perf_output_handle *handle,
 474					  struct perf_event *event)
 475{
 476	u64 base, limit;
 477	struct arm_spe_pmu_buf *buf;
 478
 479	/* Start a new aux session */
 480	buf = perf_aux_output_begin(handle, event);
 481	if (!buf) {
 482		event->hw.state |= PERF_HES_STOPPED;
 483		/*
 484		 * We still need to clear the limit pointer, since the
 485		 * profiler might only be disabled by virtue of a fault.
 486		 */
 487		limit = 0;
 488		goto out_write_limit;
 489	}
 490
 491	limit = buf->snapshot ? arm_spe_pmu_next_snapshot_off(handle)
 492			      : arm_spe_pmu_next_off(handle);
 493	if (limit)
 494		limit |= BIT(SYS_PMBLIMITR_EL1_E_SHIFT);
 495
 496	limit += (u64)buf->base;
 497	base = (u64)buf->base + PERF_IDX2OFF(handle->head, buf);
 498	write_sysreg_s(base, SYS_PMBPTR_EL1);
 499
 500out_write_limit:
 501	write_sysreg_s(limit, SYS_PMBLIMITR_EL1);
 502}
 503
 504static void arm_spe_perf_aux_output_end(struct perf_output_handle *handle)
 505{
 506	struct arm_spe_pmu_buf *buf = perf_get_aux(handle);
 507	u64 offset, size;
 508
 509	offset = read_sysreg_s(SYS_PMBPTR_EL1) - (u64)buf->base;
 510	size = offset - PERF_IDX2OFF(handle->head, buf);
 511
 512	if (buf->snapshot)
 513		handle->head = offset;
 514
 515	perf_aux_output_end(handle, size);
 516}
 517
 518static void arm_spe_pmu_disable_and_drain_local(void)
 519{
 520	/* Disable profiling at EL0 and EL1 */
 521	write_sysreg_s(0, SYS_PMSCR_EL1);
 522	isb();
 523
 524	/* Drain any buffered data */
 525	psb_csync();
 526	dsb(nsh);
 527
 528	/* Disable the profiling buffer */
 529	write_sysreg_s(0, SYS_PMBLIMITR_EL1);
 530	isb();
 531}
 532
 533/* IRQ handling */
 534static enum arm_spe_pmu_buf_fault_action
 535arm_spe_pmu_buf_get_fault_act(struct perf_output_handle *handle)
 536{
 537	const char *err_str;
 538	u64 pmbsr;
 539	enum arm_spe_pmu_buf_fault_action ret;
 540
 541	/*
 542	 * Ensure new profiling data is visible to the CPU and any external
 543	 * aborts have been resolved.
 544	 */
 545	psb_csync();
 546	dsb(nsh);
 547
 548	/* Ensure hardware updates to PMBPTR_EL1 are visible */
 549	isb();
 550
 551	/* Service required? */
 552	pmbsr = read_sysreg_s(SYS_PMBSR_EL1);
 553	if (!(pmbsr & BIT(SYS_PMBSR_EL1_S_SHIFT)))
 554		return SPE_PMU_BUF_FAULT_ACT_SPURIOUS;
 555
 556	/*
 557	 * If we've lost data, disable profiling and also set the PARTIAL
 558	 * flag to indicate that the last record is corrupted.
 559	 */
 560	if (pmbsr & BIT(SYS_PMBSR_EL1_DL_SHIFT))
 561		perf_aux_output_flag(handle, PERF_AUX_FLAG_TRUNCATED |
 562					     PERF_AUX_FLAG_PARTIAL);
 563
 564	/* Report collisions to userspace so that it can up the period */
 565	if (pmbsr & BIT(SYS_PMBSR_EL1_COLL_SHIFT))
 566		perf_aux_output_flag(handle, PERF_AUX_FLAG_COLLISION);
 567
 568	/* We only expect buffer management events */
 569	switch (pmbsr & (SYS_PMBSR_EL1_EC_MASK << SYS_PMBSR_EL1_EC_SHIFT)) {
 570	case SYS_PMBSR_EL1_EC_BUF:
 571		/* Handled below */
 572		break;
 573	case SYS_PMBSR_EL1_EC_FAULT_S1:
 574	case SYS_PMBSR_EL1_EC_FAULT_S2:
 575		err_str = "Unexpected buffer fault";
 576		goto out_err;
 577	default:
 578		err_str = "Unknown error code";
 579		goto out_err;
 580	}
 581
 582	/* Buffer management event */
 583	switch (pmbsr &
 584		(SYS_PMBSR_EL1_BUF_BSC_MASK << SYS_PMBSR_EL1_BUF_BSC_SHIFT)) {
 585	case SYS_PMBSR_EL1_BUF_BSC_FULL:
 586		ret = SPE_PMU_BUF_FAULT_ACT_OK;
 587		goto out_stop;
 588	default:
 589		err_str = "Unknown buffer status code";
 590	}
 591
 592out_err:
 593	pr_err_ratelimited("%s on CPU %d [PMBSR=0x%016llx, PMBPTR=0x%016llx, PMBLIMITR=0x%016llx]\n",
 594			   err_str, smp_processor_id(), pmbsr,
 595			   read_sysreg_s(SYS_PMBPTR_EL1),
 596			   read_sysreg_s(SYS_PMBLIMITR_EL1));
 597	ret = SPE_PMU_BUF_FAULT_ACT_FATAL;
 598
 599out_stop:
 600	arm_spe_perf_aux_output_end(handle);
 601	return ret;
 602}
 603
 604static irqreturn_t arm_spe_pmu_irq_handler(int irq, void *dev)
 605{
 606	struct perf_output_handle *handle = dev;
 607	struct perf_event *event = handle->event;
 608	enum arm_spe_pmu_buf_fault_action act;
 609
 610	if (!perf_get_aux(handle))
 611		return IRQ_NONE;
 612
 613	act = arm_spe_pmu_buf_get_fault_act(handle);
 614	if (act == SPE_PMU_BUF_FAULT_ACT_SPURIOUS)
 615		return IRQ_NONE;
 616
 617	/*
 618	 * Ensure perf callbacks have completed, which may disable the
 619	 * profiling buffer in response to a TRUNCATION flag.
 620	 */
 621	irq_work_run();
 622
 623	switch (act) {
 624	case SPE_PMU_BUF_FAULT_ACT_FATAL:
 625		/*
 626		 * If a fatal exception occurred then leaving the profiling
 627		 * buffer enabled is a recipe waiting to happen. Since
 628		 * fatal faults don't always imply truncation, make sure
 629		 * that the profiling buffer is disabled explicitly before
 630		 * clearing the syndrome register.
 631		 */
 632		arm_spe_pmu_disable_and_drain_local();
 633		break;
 634	case SPE_PMU_BUF_FAULT_ACT_OK:
 635		/*
 636		 * We handled the fault (the buffer was full), so resume
 637		 * profiling as long as we didn't detect truncation.
 638		 * PMBPTR might be misaligned, but we'll burn that bridge
 639		 * when we get to it.
 640		 */
 641		if (!(handle->aux_flags & PERF_AUX_FLAG_TRUNCATED)) {
 642			arm_spe_perf_aux_output_begin(handle, event);
 643			isb();
 644		}
 645		break;
 646	case SPE_PMU_BUF_FAULT_ACT_SPURIOUS:
 647		/* We've seen you before, but GCC has the memory of a sieve. */
 648		break;
 649	}
 650
 651	/* The buffer pointers are now sane, so resume profiling. */
 652	write_sysreg_s(0, SYS_PMBSR_EL1);
 653	return IRQ_HANDLED;
 654}
 655
 656static u64 arm_spe_pmsevfr_res0(u16 pmsver)
 657{
 658	switch (pmsver) {
 659	case ID_AA64DFR0_PMSVER_8_2:
 660		return SYS_PMSEVFR_EL1_RES0_8_2;
 661	case ID_AA64DFR0_PMSVER_8_3:
 662	/* Return the highest version we support in default */
 663	default:
 664		return SYS_PMSEVFR_EL1_RES0_8_3;
 665	}
 666}
 667
 668/* Perf callbacks */
 669static int arm_spe_pmu_event_init(struct perf_event *event)
 670{
 671	u64 reg;
 672	struct perf_event_attr *attr = &event->attr;
 673	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 674
 675	/* This is, of course, deeply driver-specific */
 676	if (attr->type != event->pmu->type)
 677		return -ENOENT;
 678
 679	if (event->cpu >= 0 &&
 680	    !cpumask_test_cpu(event->cpu, &spe_pmu->supported_cpus))
 681		return -ENOENT;
 682
 683	if (arm_spe_event_to_pmsevfr(event) & arm_spe_pmsevfr_res0(spe_pmu->pmsver))
 684		return -EOPNOTSUPP;
 685
 686	if (attr->exclude_idle)
 687		return -EOPNOTSUPP;
 688
 689	/*
 690	 * Feedback-directed frequency throttling doesn't work when we
 691	 * have a buffer of samples. We'd need to manually count the
 692	 * samples in the buffer when it fills up and adjust the event
 693	 * count to reflect that. Instead, just force the user to specify
 694	 * a sample period.
 695	 */
 696	if (attr->freq)
 697		return -EINVAL;
 698
 699	reg = arm_spe_event_to_pmsfcr(event);
 700	if ((reg & BIT(SYS_PMSFCR_EL1_FE_SHIFT)) &&
 701	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_EVT))
 702		return -EOPNOTSUPP;
 703
 704	if ((reg & BIT(SYS_PMSFCR_EL1_FT_SHIFT)) &&
 705	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_TYP))
 706		return -EOPNOTSUPP;
 707
 708	if ((reg & BIT(SYS_PMSFCR_EL1_FL_SHIFT)) &&
 709	    !(spe_pmu->features & SPE_PMU_FEAT_FILT_LAT))
 710		return -EOPNOTSUPP;
 711
 
 712	reg = arm_spe_event_to_pmscr(event);
 713	if (!perfmon_capable() &&
 714	    (reg & (BIT(SYS_PMSCR_EL1_PA_SHIFT) |
 715		    BIT(SYS_PMSCR_EL1_CX_SHIFT) |
 716		    BIT(SYS_PMSCR_EL1_PCT_SHIFT))))
 717		return -EACCES;
 718
 719	return 0;
 720}
 721
 722static void arm_spe_pmu_start(struct perf_event *event, int flags)
 723{
 724	u64 reg;
 725	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 726	struct hw_perf_event *hwc = &event->hw;
 727	struct perf_output_handle *handle = this_cpu_ptr(spe_pmu->handle);
 728
 729	hwc->state = 0;
 730	arm_spe_perf_aux_output_begin(handle, event);
 731	if (hwc->state)
 732		return;
 733
 734	reg = arm_spe_event_to_pmsfcr(event);
 735	write_sysreg_s(reg, SYS_PMSFCR_EL1);
 736
 737	reg = arm_spe_event_to_pmsevfr(event);
 738	write_sysreg_s(reg, SYS_PMSEVFR_EL1);
 739
 740	reg = arm_spe_event_to_pmslatfr(event);
 741	write_sysreg_s(reg, SYS_PMSLATFR_EL1);
 742
 743	if (flags & PERF_EF_RELOAD) {
 744		reg = arm_spe_event_to_pmsirr(event);
 745		write_sysreg_s(reg, SYS_PMSIRR_EL1);
 746		isb();
 747		reg = local64_read(&hwc->period_left);
 748		write_sysreg_s(reg, SYS_PMSICR_EL1);
 749	}
 750
 751	reg = arm_spe_event_to_pmscr(event);
 752	isb();
 753	write_sysreg_s(reg, SYS_PMSCR_EL1);
 754}
 755
 756static void arm_spe_pmu_stop(struct perf_event *event, int flags)
 757{
 758	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 759	struct hw_perf_event *hwc = &event->hw;
 760	struct perf_output_handle *handle = this_cpu_ptr(spe_pmu->handle);
 761
 762	/* If we're already stopped, then nothing to do */
 763	if (hwc->state & PERF_HES_STOPPED)
 764		return;
 765
 766	/* Stop all trace generation */
 767	arm_spe_pmu_disable_and_drain_local();
 768
 769	if (flags & PERF_EF_UPDATE) {
 770		/*
 771		 * If there's a fault pending then ensure we contain it
 772		 * to this buffer, since we might be on the context-switch
 773		 * path.
 774		 */
 775		if (perf_get_aux(handle)) {
 776			enum arm_spe_pmu_buf_fault_action act;
 777
 778			act = arm_spe_pmu_buf_get_fault_act(handle);
 779			if (act == SPE_PMU_BUF_FAULT_ACT_SPURIOUS)
 780				arm_spe_perf_aux_output_end(handle);
 781			else
 782				write_sysreg_s(0, SYS_PMBSR_EL1);
 783		}
 784
 785		/*
 786		 * This may also contain ECOUNT, but nobody else should
 787		 * be looking at period_left, since we forbid frequency
 788		 * based sampling.
 789		 */
 790		local64_set(&hwc->period_left, read_sysreg_s(SYS_PMSICR_EL1));
 791		hwc->state |= PERF_HES_UPTODATE;
 792	}
 793
 794	hwc->state |= PERF_HES_STOPPED;
 795}
 796
 797static int arm_spe_pmu_add(struct perf_event *event, int flags)
 798{
 799	int ret = 0;
 800	struct arm_spe_pmu *spe_pmu = to_spe_pmu(event->pmu);
 801	struct hw_perf_event *hwc = &event->hw;
 802	int cpu = event->cpu == -1 ? smp_processor_id() : event->cpu;
 803
 804	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
 805		return -ENOENT;
 806
 807	hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
 808
 809	if (flags & PERF_EF_START) {
 810		arm_spe_pmu_start(event, PERF_EF_RELOAD);
 811		if (hwc->state & PERF_HES_STOPPED)
 812			ret = -EINVAL;
 813	}
 814
 815	return ret;
 816}
 817
 818static void arm_spe_pmu_del(struct perf_event *event, int flags)
 819{
 820	arm_spe_pmu_stop(event, PERF_EF_UPDATE);
 821}
 822
 823static void arm_spe_pmu_read(struct perf_event *event)
 824{
 825}
 826
 827static void *arm_spe_pmu_setup_aux(struct perf_event *event, void **pages,
 828				   int nr_pages, bool snapshot)
 829{
 830	int i, cpu = event->cpu;
 831	struct page **pglist;
 832	struct arm_spe_pmu_buf *buf;
 833
 834	/* We need at least two pages for this to work. */
 835	if (nr_pages < 2)
 836		return NULL;
 837
 838	/*
 839	 * We require an even number of pages for snapshot mode, so that
 840	 * we can effectively treat the buffer as consisting of two equal
 841	 * parts and give userspace a fighting chance of getting some
 842	 * useful data out of it.
 843	 */
 844	if (snapshot && (nr_pages & 1))
 845		return NULL;
 846
 847	if (cpu == -1)
 848		cpu = raw_smp_processor_id();
 849
 850	buf = kzalloc_node(sizeof(*buf), GFP_KERNEL, cpu_to_node(cpu));
 851	if (!buf)
 852		return NULL;
 853
 854	pglist = kcalloc(nr_pages, sizeof(*pglist), GFP_KERNEL);
 855	if (!pglist)
 856		goto out_free_buf;
 857
 858	for (i = 0; i < nr_pages; ++i)
 859		pglist[i] = virt_to_page(pages[i]);
 860
 861	buf->base = vmap(pglist, nr_pages, VM_MAP, PAGE_KERNEL);
 862	if (!buf->base)
 863		goto out_free_pglist;
 864
 865	buf->nr_pages	= nr_pages;
 866	buf->snapshot	= snapshot;
 867
 868	kfree(pglist);
 869	return buf;
 870
 871out_free_pglist:
 872	kfree(pglist);
 873out_free_buf:
 874	kfree(buf);
 875	return NULL;
 876}
 877
 878static void arm_spe_pmu_free_aux(void *aux)
 879{
 880	struct arm_spe_pmu_buf *buf = aux;
 881
 882	vunmap(buf->base);
 883	kfree(buf);
 884}
 885
 886/* Initialisation and teardown functions */
 887static int arm_spe_pmu_perf_init(struct arm_spe_pmu *spe_pmu)
 888{
 889	static atomic_t pmu_idx = ATOMIC_INIT(-1);
 890
 891	int idx;
 892	char *name;
 893	struct device *dev = &spe_pmu->pdev->dev;
 894
 895	spe_pmu->pmu = (struct pmu) {
 896		.module = THIS_MODULE,
 897		.capabilities	= PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE,
 898		.attr_groups	= arm_spe_pmu_attr_groups,
 899		/*
 900		 * We hitch a ride on the software context here, so that
 901		 * we can support per-task profiling (which is not possible
 902		 * with the invalid context as it doesn't get sched callbacks).
 903		 * This requires that userspace either uses a dummy event for
 904		 * perf_event_open, since the aux buffer is not setup until
 905		 * a subsequent mmap, or creates the profiling event in a
 906		 * disabled state and explicitly PERF_EVENT_IOC_ENABLEs it
 907		 * once the buffer has been created.
 908		 */
 909		.task_ctx_nr	= perf_sw_context,
 910		.event_init	= arm_spe_pmu_event_init,
 911		.add		= arm_spe_pmu_add,
 912		.del		= arm_spe_pmu_del,
 913		.start		= arm_spe_pmu_start,
 914		.stop		= arm_spe_pmu_stop,
 915		.read		= arm_spe_pmu_read,
 916		.setup_aux	= arm_spe_pmu_setup_aux,
 917		.free_aux	= arm_spe_pmu_free_aux,
 918	};
 919
 920	idx = atomic_inc_return(&pmu_idx);
 921	name = devm_kasprintf(dev, GFP_KERNEL, "%s_%d", PMUNAME, idx);
 922	if (!name) {
 923		dev_err(dev, "failed to allocate name for pmu %d\n", idx);
 924		return -ENOMEM;
 925	}
 926
 927	return perf_pmu_register(&spe_pmu->pmu, name, -1);
 928}
 929
 930static void arm_spe_pmu_perf_destroy(struct arm_spe_pmu *spe_pmu)
 931{
 932	perf_pmu_unregister(&spe_pmu->pmu);
 933}
 934
 935static void __arm_spe_pmu_dev_probe(void *info)
 936{
 937	int fld;
 938	u64 reg;
 939	struct arm_spe_pmu *spe_pmu = info;
 940	struct device *dev = &spe_pmu->pdev->dev;
 941
 942	fld = cpuid_feature_extract_unsigned_field(read_cpuid(ID_AA64DFR0_EL1),
 943						   ID_AA64DFR0_PMSVER_SHIFT);
 944	if (!fld) {
 945		dev_err(dev,
 946			"unsupported ID_AA64DFR0_EL1.PMSVer [%d] on CPU %d\n",
 947			fld, smp_processor_id());
 948		return;
 949	}
 950	spe_pmu->pmsver = (u16)fld;
 951
 952	/* Read PMBIDR first to determine whether or not we have access */
 953	reg = read_sysreg_s(SYS_PMBIDR_EL1);
 954	if (reg & BIT(SYS_PMBIDR_EL1_P_SHIFT)) {
 955		dev_err(dev,
 956			"profiling buffer owned by higher exception level\n");
 957		return;
 958	}
 959
 960	/* Minimum alignment. If it's out-of-range, then fail the probe */
 961	fld = reg >> SYS_PMBIDR_EL1_ALIGN_SHIFT & SYS_PMBIDR_EL1_ALIGN_MASK;
 962	spe_pmu->align = 1 << fld;
 963	if (spe_pmu->align > SZ_2K) {
 964		dev_err(dev, "unsupported PMBIDR.Align [%d] on CPU %d\n",
 965			fld, smp_processor_id());
 966		return;
 967	}
 968
 969	/* It's now safe to read PMSIDR and figure out what we've got */
 970	reg = read_sysreg_s(SYS_PMSIDR_EL1);
 971	if (reg & BIT(SYS_PMSIDR_EL1_FE_SHIFT))
 972		spe_pmu->features |= SPE_PMU_FEAT_FILT_EVT;
 973
 974	if (reg & BIT(SYS_PMSIDR_EL1_FT_SHIFT))
 975		spe_pmu->features |= SPE_PMU_FEAT_FILT_TYP;
 976
 977	if (reg & BIT(SYS_PMSIDR_EL1_FL_SHIFT))
 978		spe_pmu->features |= SPE_PMU_FEAT_FILT_LAT;
 979
 980	if (reg & BIT(SYS_PMSIDR_EL1_ARCHINST_SHIFT))
 981		spe_pmu->features |= SPE_PMU_FEAT_ARCH_INST;
 982
 983	if (reg & BIT(SYS_PMSIDR_EL1_LDS_SHIFT))
 984		spe_pmu->features |= SPE_PMU_FEAT_LDS;
 985
 986	if (reg & BIT(SYS_PMSIDR_EL1_ERND_SHIFT))
 987		spe_pmu->features |= SPE_PMU_FEAT_ERND;
 988
 989	/* This field has a spaced out encoding, so just use a look-up */
 990	fld = reg >> SYS_PMSIDR_EL1_INTERVAL_SHIFT & SYS_PMSIDR_EL1_INTERVAL_MASK;
 991	switch (fld) {
 992	case 0:
 993		spe_pmu->min_period = 256;
 994		break;
 995	case 2:
 996		spe_pmu->min_period = 512;
 997		break;
 998	case 3:
 999		spe_pmu->min_period = 768;
1000		break;
1001	case 4:
1002		spe_pmu->min_period = 1024;
1003		break;
1004	case 5:
1005		spe_pmu->min_period = 1536;
1006		break;
1007	case 6:
1008		spe_pmu->min_period = 2048;
1009		break;
1010	case 7:
1011		spe_pmu->min_period = 3072;
1012		break;
1013	default:
1014		dev_warn(dev, "unknown PMSIDR_EL1.Interval [%d]; assuming 8\n",
1015			 fld);
1016		fallthrough;
1017	case 8:
1018		spe_pmu->min_period = 4096;
1019	}
1020
1021	/* Maximum record size. If it's out-of-range, then fail the probe */
1022	fld = reg >> SYS_PMSIDR_EL1_MAXSIZE_SHIFT & SYS_PMSIDR_EL1_MAXSIZE_MASK;
1023	spe_pmu->max_record_sz = 1 << fld;
1024	if (spe_pmu->max_record_sz > SZ_2K || spe_pmu->max_record_sz < 16) {
1025		dev_err(dev, "unsupported PMSIDR_EL1.MaxSize [%d] on CPU %d\n",
1026			fld, smp_processor_id());
1027		return;
1028	}
1029
1030	fld = reg >> SYS_PMSIDR_EL1_COUNTSIZE_SHIFT & SYS_PMSIDR_EL1_COUNTSIZE_MASK;
1031	switch (fld) {
1032	default:
1033		dev_warn(dev, "unknown PMSIDR_EL1.CountSize [%d]; assuming 2\n",
1034			 fld);
1035		fallthrough;
1036	case 2:
1037		spe_pmu->counter_sz = 12;
 
 
 
1038	}
1039
1040	dev_info(dev,
1041		 "probed for CPUs %*pbl [max_record_sz %u, align %u, features 0x%llx]\n",
1042		 cpumask_pr_args(&spe_pmu->supported_cpus),
1043		 spe_pmu->max_record_sz, spe_pmu->align, spe_pmu->features);
1044
1045	spe_pmu->features |= SPE_PMU_FEAT_DEV_PROBED;
1046}
1047
1048static void __arm_spe_pmu_reset_local(void)
1049{
1050	/*
1051	 * This is probably overkill, as we have no idea where we're
1052	 * draining any buffered data to...
1053	 */
1054	arm_spe_pmu_disable_and_drain_local();
1055
1056	/* Reset the buffer base pointer */
1057	write_sysreg_s(0, SYS_PMBPTR_EL1);
1058	isb();
1059
1060	/* Clear any pending management interrupts */
1061	write_sysreg_s(0, SYS_PMBSR_EL1);
1062	isb();
1063}
1064
1065static void __arm_spe_pmu_setup_one(void *info)
1066{
1067	struct arm_spe_pmu *spe_pmu = info;
1068
1069	__arm_spe_pmu_reset_local();
1070	enable_percpu_irq(spe_pmu->irq, IRQ_TYPE_NONE);
1071}
1072
1073static void __arm_spe_pmu_stop_one(void *info)
1074{
1075	struct arm_spe_pmu *spe_pmu = info;
1076
1077	disable_percpu_irq(spe_pmu->irq);
1078	__arm_spe_pmu_reset_local();
1079}
1080
1081static int arm_spe_pmu_cpu_startup(unsigned int cpu, struct hlist_node *node)
1082{
1083	struct arm_spe_pmu *spe_pmu;
1084
1085	spe_pmu = hlist_entry_safe(node, struct arm_spe_pmu, hotplug_node);
1086	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
1087		return 0;
1088
1089	__arm_spe_pmu_setup_one(spe_pmu);
1090	return 0;
1091}
1092
1093static int arm_spe_pmu_cpu_teardown(unsigned int cpu, struct hlist_node *node)
1094{
1095	struct arm_spe_pmu *spe_pmu;
1096
1097	spe_pmu = hlist_entry_safe(node, struct arm_spe_pmu, hotplug_node);
1098	if (!cpumask_test_cpu(cpu, &spe_pmu->supported_cpus))
1099		return 0;
1100
1101	__arm_spe_pmu_stop_one(spe_pmu);
1102	return 0;
1103}
1104
1105static int arm_spe_pmu_dev_init(struct arm_spe_pmu *spe_pmu)
1106{
1107	int ret;
1108	cpumask_t *mask = &spe_pmu->supported_cpus;
1109
1110	/* Make sure we probe the hardware on a relevant CPU */
1111	ret = smp_call_function_any(mask,  __arm_spe_pmu_dev_probe, spe_pmu, 1);
1112	if (ret || !(spe_pmu->features & SPE_PMU_FEAT_DEV_PROBED))
1113		return -ENXIO;
1114
1115	/* Request our PPIs (note that the IRQ is still disabled) */
1116	ret = request_percpu_irq(spe_pmu->irq, arm_spe_pmu_irq_handler, DRVNAME,
1117				 spe_pmu->handle);
1118	if (ret)
1119		return ret;
1120
1121	/*
1122	 * Register our hotplug notifier now so we don't miss any events.
1123	 * This will enable the IRQ for any supported CPUs that are already
1124	 * up.
1125	 */
1126	ret = cpuhp_state_add_instance(arm_spe_pmu_online,
1127				       &spe_pmu->hotplug_node);
1128	if (ret)
1129		free_percpu_irq(spe_pmu->irq, spe_pmu->handle);
1130
1131	return ret;
1132}
1133
1134static void arm_spe_pmu_dev_teardown(struct arm_spe_pmu *spe_pmu)
1135{
1136	cpuhp_state_remove_instance(arm_spe_pmu_online, &spe_pmu->hotplug_node);
1137	free_percpu_irq(spe_pmu->irq, spe_pmu->handle);
1138}
1139
1140/* Driver and device probing */
1141static int arm_spe_pmu_irq_probe(struct arm_spe_pmu *spe_pmu)
1142{
1143	struct platform_device *pdev = spe_pmu->pdev;
1144	int irq = platform_get_irq(pdev, 0);
1145
1146	if (irq < 0)
1147		return -ENXIO;
1148
1149	if (!irq_is_percpu(irq)) {
1150		dev_err(&pdev->dev, "expected PPI but got SPI (%d)\n", irq);
1151		return -EINVAL;
1152	}
1153
1154	if (irq_get_percpu_devid_partition(irq, &spe_pmu->supported_cpus)) {
1155		dev_err(&pdev->dev, "failed to get PPI partition (%d)\n", irq);
1156		return -EINVAL;
1157	}
1158
1159	spe_pmu->irq = irq;
1160	return 0;
1161}
1162
1163static const struct of_device_id arm_spe_pmu_of_match[] = {
1164	{ .compatible = "arm,statistical-profiling-extension-v1", .data = (void *)1 },
1165	{ /* Sentinel */ },
1166};
1167MODULE_DEVICE_TABLE(of, arm_spe_pmu_of_match);
1168
1169static const struct platform_device_id arm_spe_match[] = {
1170	{ ARMV8_SPE_PDEV_NAME, 0},
1171	{ }
1172};
1173MODULE_DEVICE_TABLE(platform, arm_spe_match);
1174
1175static int arm_spe_pmu_device_probe(struct platform_device *pdev)
1176{
1177	int ret;
1178	struct arm_spe_pmu *spe_pmu;
1179	struct device *dev = &pdev->dev;
1180
1181	/*
1182	 * If kernelspace is unmapped when running at EL0, then the SPE
1183	 * buffer will fault and prematurely terminate the AUX session.
1184	 */
1185	if (arm64_kernel_unmapped_at_el0()) {
1186		dev_warn_once(dev, "profiling buffer inaccessible. Try passing \"kpti=off\" on the kernel command line\n");
1187		return -EPERM;
1188	}
1189
1190	spe_pmu = devm_kzalloc(dev, sizeof(*spe_pmu), GFP_KERNEL);
1191	if (!spe_pmu)
1192		return -ENOMEM;
1193
1194	spe_pmu->handle = alloc_percpu(typeof(*spe_pmu->handle));
1195	if (!spe_pmu->handle)
1196		return -ENOMEM;
1197
1198	spe_pmu->pdev = pdev;
1199	platform_set_drvdata(pdev, spe_pmu);
1200
1201	ret = arm_spe_pmu_irq_probe(spe_pmu);
1202	if (ret)
1203		goto out_free_handle;
1204
1205	ret = arm_spe_pmu_dev_init(spe_pmu);
1206	if (ret)
1207		goto out_free_handle;
1208
1209	ret = arm_spe_pmu_perf_init(spe_pmu);
1210	if (ret)
1211		goto out_teardown_dev;
1212
1213	return 0;
1214
1215out_teardown_dev:
1216	arm_spe_pmu_dev_teardown(spe_pmu);
1217out_free_handle:
1218	free_percpu(spe_pmu->handle);
1219	return ret;
1220}
1221
1222static int arm_spe_pmu_device_remove(struct platform_device *pdev)
1223{
1224	struct arm_spe_pmu *spe_pmu = platform_get_drvdata(pdev);
1225
1226	arm_spe_pmu_perf_destroy(spe_pmu);
1227	arm_spe_pmu_dev_teardown(spe_pmu);
1228	free_percpu(spe_pmu->handle);
1229	return 0;
1230}
1231
1232static struct platform_driver arm_spe_pmu_driver = {
1233	.id_table = arm_spe_match,
1234	.driver	= {
1235		.name		= DRVNAME,
1236		.of_match_table	= of_match_ptr(arm_spe_pmu_of_match),
1237		.suppress_bind_attrs = true,
1238	},
1239	.probe	= arm_spe_pmu_device_probe,
1240	.remove	= arm_spe_pmu_device_remove,
1241};
1242
1243static int __init arm_spe_pmu_init(void)
1244{
1245	int ret;
1246
1247	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, DRVNAME,
1248				      arm_spe_pmu_cpu_startup,
1249				      arm_spe_pmu_cpu_teardown);
1250	if (ret < 0)
1251		return ret;
1252	arm_spe_pmu_online = ret;
1253
1254	ret = platform_driver_register(&arm_spe_pmu_driver);
1255	if (ret)
1256		cpuhp_remove_multi_state(arm_spe_pmu_online);
1257
1258	return ret;
1259}
1260
1261static void __exit arm_spe_pmu_exit(void)
1262{
1263	platform_driver_unregister(&arm_spe_pmu_driver);
1264	cpuhp_remove_multi_state(arm_spe_pmu_online);
1265}
1266
1267module_init(arm_spe_pmu_init);
1268module_exit(arm_spe_pmu_exit);
1269
1270MODULE_DESCRIPTION("Perf driver for the ARMv8.2 Statistical Profiling Extension");
1271MODULE_AUTHOR("Will Deacon <will.deacon@arm.com>");
1272MODULE_LICENSE("GPL v2");