1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Arm Statistical Profiling Extensions (SPE) support
4 * Copyright (c) 2017-2018, Arm Ltd.
5 */
6
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/bitops.h>
10#include <linux/log2.h>
11#include <linux/zalloc.h>
12#include <time.h>
13
14#include "../../../util/cpumap.h"
15#include "../../../util/event.h"
16#include "../../../util/evsel.h"
17#include "../../../util/evsel_config.h"
18#include "../../../util/evlist.h"
19#include "../../../util/session.h"
20#include <internal/lib.h> // page_size
21#include "../../../util/pmu.h"
22#include "../../../util/debug.h"
23#include "../../../util/auxtrace.h"
24#include "../../../util/record.h"
25#include "../../../util/arm-spe.h"
26#include <tools/libc_compat.h> // reallocarray
27
28#define KiB(x) ((x) * 1024)
29#define MiB(x) ((x) * 1024 * 1024)
30
31struct arm_spe_recording {
32	struct auxtrace_record		itr;
33	struct perf_pmu			*arm_spe_pmu;
34	struct evlist		*evlist;
35	int			wrapped_cnt;
36	bool			*wrapped;
37};
38
39static size_t
40arm_spe_info_priv_size(struct auxtrace_record *itr __maybe_unused,
41		       struct evlist *evlist __maybe_unused)
42{
43	return ARM_SPE_AUXTRACE_PRIV_SIZE;
44}
45
46static int arm_spe_info_fill(struct auxtrace_record *itr,
47			     struct perf_session *session,
48			     struct perf_record_auxtrace_info *auxtrace_info,
49			     size_t priv_size)
50{
51	struct arm_spe_recording *sper =
52			container_of(itr, struct arm_spe_recording, itr);
53	struct perf_pmu *arm_spe_pmu = sper->arm_spe_pmu;
54
55	if (priv_size != ARM_SPE_AUXTRACE_PRIV_SIZE)
56		return -EINVAL;
57
58	if (!session->evlist->core.nr_mmaps)
59		return -EINVAL;
60
61	auxtrace_info->type = PERF_AUXTRACE_ARM_SPE;
62	auxtrace_info->priv[ARM_SPE_PMU_TYPE] = arm_spe_pmu->type;
63
64	return 0;
65}
66
67static void
68arm_spe_snapshot_resolve_auxtrace_defaults(struct record_opts *opts,
69					   bool privileged)
70{
71	/*
72	 * The default snapshot size is the auxtrace mmap size. If neither auxtrace mmap size nor
73	 * snapshot size is specified, then the default is 4MiB for privileged users, 128KiB for
74	 * unprivileged users.
75	 *
76	 * The default auxtrace mmap size is 4MiB/page_size for privileged users, 128KiB for
77	 * unprivileged users. If an unprivileged user does not specify mmap pages, the mmap pages
78	 * will be reduced from the default 512KiB/page_size to 256KiB/page_size, otherwise the
79	 * user is likely to get an error as they exceed their mlock limmit.
80	 */
81
82	/*
83	 * No size were given to '-S' or '-m,', so go with the default
84	 */
85	if (!opts->auxtrace_snapshot_size && !opts->auxtrace_mmap_pages) {
86		if (privileged) {
87			opts->auxtrace_mmap_pages = MiB(4) / page_size;
88		} else {
89			opts->auxtrace_mmap_pages = KiB(128) / page_size;
90			if (opts->mmap_pages == UINT_MAX)
91				opts->mmap_pages = KiB(256) / page_size;
92		}
93	} else if (!opts->auxtrace_mmap_pages && !privileged && opts->mmap_pages == UINT_MAX) {
94		opts->mmap_pages = KiB(256) / page_size;
95	}
96
97	/*
98	 * '-m,xyz' was specified but no snapshot size, so make the snapshot size as big as the
99	 * auxtrace mmap area.
100	 */
101	if (!opts->auxtrace_snapshot_size)
102		opts->auxtrace_snapshot_size = opts->auxtrace_mmap_pages * (size_t)page_size;
103
104	/*
105	 * '-Sxyz' was specified but no auxtrace mmap area, so make the auxtrace mmap area big
106	 * enough to fit the requested snapshot size.
107	 */
108	if (!opts->auxtrace_mmap_pages) {
109		size_t sz = opts->auxtrace_snapshot_size;
110
111		sz = round_up(sz, page_size) / page_size;
112		opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
113	}
114}
115
116static int arm_spe_recording_options(struct auxtrace_record *itr,
117				     struct evlist *evlist,
118				     struct record_opts *opts)
119{
120	struct arm_spe_recording *sper =
121			container_of(itr, struct arm_spe_recording, itr);
122	struct perf_pmu *arm_spe_pmu = sper->arm_spe_pmu;
123	struct evsel *evsel, *arm_spe_evsel = NULL;
124	struct perf_cpu_map *cpus = evlist->core.user_requested_cpus;
125	bool privileged = perf_event_paranoid_check(-1);
126	struct evsel *tracking_evsel;
127	int err;
128	u64 bit;
129
130	sper->evlist = evlist;
131
132	evlist__for_each_entry(evlist, evsel) {
133		if (evsel->core.attr.type == arm_spe_pmu->type) {
134			if (arm_spe_evsel) {
135				pr_err("There may be only one " ARM_SPE_PMU_NAME "x event\n");
136				return -EINVAL;
137			}
138			evsel->core.attr.freq = 0;
139			evsel->core.attr.sample_period = arm_spe_pmu->default_config->sample_period;
140			evsel->needs_auxtrace_mmap = true;
141			arm_spe_evsel = evsel;
142			opts->full_auxtrace = true;
143		}
144	}
145
146	if (!opts->full_auxtrace)
147		return 0;
148
149	/*
150	 * we are in snapshot mode.
151	 */
152	if (opts->auxtrace_snapshot_mode) {
153		/*
154		 * Command arguments '-Sxyz' and/or '-m,xyz' are missing, so fill those in with
155		 * default values.
156		 */
157		if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages)
158			arm_spe_snapshot_resolve_auxtrace_defaults(opts, privileged);
159
160		/*
161		 * Snapshot size can't be bigger than the auxtrace area.
162		 */
163		if (opts->auxtrace_snapshot_size > opts->auxtrace_mmap_pages * (size_t)page_size) {
164			pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
165			       opts->auxtrace_snapshot_size,
166			       opts->auxtrace_mmap_pages * (size_t)page_size);
167			return -EINVAL;
168		}
169
170		/*
171		 * Something went wrong somewhere - this shouldn't happen.
172		 */
173		if (!opts->auxtrace_snapshot_size || !opts->auxtrace_mmap_pages) {
174			pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
175			return -EINVAL;
176		}
177	}
178
179	/* We are in full trace mode but '-m,xyz' wasn't specified */
180	if (!opts->auxtrace_mmap_pages) {
181		if (privileged) {
182			opts->auxtrace_mmap_pages = MiB(4) / page_size;
183		} else {
184			opts->auxtrace_mmap_pages = KiB(128) / page_size;
185			if (opts->mmap_pages == UINT_MAX)
186				opts->mmap_pages = KiB(256) / page_size;
187		}
188	}
189
190	/* Validate auxtrace_mmap_pages */
191	if (opts->auxtrace_mmap_pages) {
192		size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
193		size_t min_sz = KiB(8);
194
195		if (sz < min_sz || !is_power_of_2(sz)) {
196			pr_err("Invalid mmap size for ARM SPE: must be at least %zuKiB and a power of 2\n",
197			       min_sz / 1024);
198			return -EINVAL;
199		}
200	}
201
202	if (opts->auxtrace_snapshot_mode)
203		pr_debug2("%sx snapshot size: %zu\n", ARM_SPE_PMU_NAME,
204			  opts->auxtrace_snapshot_size);
205
206	/*
207	 * To obtain the auxtrace buffer file descriptor, the auxtrace event
208	 * must come first.
209	 */
210	evlist__to_front(evlist, arm_spe_evsel);
211
212	/*
213	 * In the case of per-cpu mmaps, sample CPU for AUX event;
214	 * also enable the timestamp tracing for samples correlation.
215	 */
216	if (!perf_cpu_map__empty(cpus)) {
217		evsel__set_sample_bit(arm_spe_evsel, CPU);
218		evsel__set_config_if_unset(arm_spe_pmu, arm_spe_evsel,
219					   "ts_enable", 1);
220	}
221
222	/*
223	 * Set this only so that perf report knows that SPE generates memory info. It has no effect
224	 * on the opening of the event or the SPE data produced.
225	 */
226	evsel__set_sample_bit(arm_spe_evsel, DATA_SRC);
227
228	/*
229	 * The PHYS_ADDR flag does not affect the driver behaviour, it is used to
230	 * inform that the resulting output's SPE samples contain physical addresses
231	 * where applicable.
232	 */
233	bit = perf_pmu__format_bits(arm_spe_pmu, "pa_enable");
234	if (arm_spe_evsel->core.attr.config & bit)
235		evsel__set_sample_bit(arm_spe_evsel, PHYS_ADDR);
236
237	/* Add dummy event to keep tracking */
238	err = parse_event(evlist, "dummy:u");
239	if (err)
240		return err;
241
242	tracking_evsel = evlist__last(evlist);
243	evlist__set_tracking_event(evlist, tracking_evsel);
244
245	tracking_evsel->core.attr.freq = 0;
246	tracking_evsel->core.attr.sample_period = 1;
247
248	/* In per-cpu case, always need the time of mmap events etc */
249	if (!perf_cpu_map__empty(cpus)) {
250		evsel__set_sample_bit(tracking_evsel, TIME);
251		evsel__set_sample_bit(tracking_evsel, CPU);
252
253		/* also track task context switch */
254		if (!record_opts__no_switch_events(opts))
255			tracking_evsel->core.attr.context_switch = 1;
256	}
257
258	return 0;
259}
260
261static int arm_spe_parse_snapshot_options(struct auxtrace_record *itr __maybe_unused,
262					 struct record_opts *opts,
263					 const char *str)
264{
265	unsigned long long snapshot_size = 0;
266	char *endptr;
267
268	if (str) {
269		snapshot_size = strtoull(str, &endptr, 0);
270		if (*endptr || snapshot_size > SIZE_MAX)
271			return -1;
272	}
273
274	opts->auxtrace_snapshot_mode = true;
275	opts->auxtrace_snapshot_size = snapshot_size;
276
277	return 0;
278}
279
280static int arm_spe_snapshot_start(struct auxtrace_record *itr)
281{
282	struct arm_spe_recording *ptr =
283			container_of(itr, struct arm_spe_recording, itr);
284	struct evsel *evsel;
285
286	evlist__for_each_entry(ptr->evlist, evsel) {
287		if (evsel->core.attr.type == ptr->arm_spe_pmu->type)
288			return evsel__disable(evsel);
289	}
290	return -EINVAL;
291}
292
293static int arm_spe_snapshot_finish(struct auxtrace_record *itr)
294{
295	struct arm_spe_recording *ptr =
296			container_of(itr, struct arm_spe_recording, itr);
297	struct evsel *evsel;
298
299	evlist__for_each_entry(ptr->evlist, evsel) {
300		if (evsel->core.attr.type == ptr->arm_spe_pmu->type)
301			return evsel__enable(evsel);
302	}
303	return -EINVAL;
304}
305
306static int arm_spe_alloc_wrapped_array(struct arm_spe_recording *ptr, int idx)
307{
308	bool *wrapped;
309	int cnt = ptr->wrapped_cnt, new_cnt, i;
310
311	/*
312	 * No need to allocate, so return early.
313	 */
314	if (idx < cnt)
315		return 0;
316
317	/*
318	 * Make ptr->wrapped as big as idx.
319	 */
320	new_cnt = idx + 1;
321
322	/*
323	 * Free'ed in arm_spe_recording_free().
324	 */
325	wrapped = reallocarray(ptr->wrapped, new_cnt, sizeof(bool));
326	if (!wrapped)
327		return -ENOMEM;
328
329	/*
330	 * init new allocated values.
331	 */
332	for (i = cnt; i < new_cnt; i++)
333		wrapped[i] = false;
334
335	ptr->wrapped_cnt = new_cnt;
336	ptr->wrapped = wrapped;
337
338	return 0;
339}
340
341static bool arm_spe_buffer_has_wrapped(unsigned char *buffer,
342				      size_t buffer_size, u64 head)
343{
344	u64 i, watermark;
345	u64 *buf = (u64 *)buffer;
346	size_t buf_size = buffer_size;
347
348	/*
349	 * Defensively handle the case where head might be continually increasing - if its value is
350	 * equal or greater than the size of the ring buffer, then we can safely determine it has
351	 * wrapped around. Otherwise, continue to detect if head might have wrapped.
352	 */
353	if (head >= buffer_size)
354		return true;
355
356	/*
357	 * We want to look the very last 512 byte (chosen arbitrarily) in the ring buffer.
358	 */
359	watermark = buf_size - 512;
360
361	/*
362	 * The value of head is somewhere within the size of the ring buffer. This can be that there
363	 * hasn't been enough data to fill the ring buffer yet or the trace time was so long that
364	 * head has numerically wrapped around.  To find we need to check if we have data at the
365	 * very end of the ring buffer.  We can reliably do this because mmap'ed pages are zeroed
366	 * out and there is a fresh mapping with every new session.
367	 */
368
369	/*
370	 * head is less than 512 byte from the end of the ring buffer.
371	 */
372	if (head > watermark)
373		watermark = head;
374
375	/*
376	 * Speed things up by using 64 bit transactions (see "u64 *buf" above)
377	 */
378	watermark /= sizeof(u64);
379	buf_size /= sizeof(u64);
380
381	/*
382	 * If we find trace data at the end of the ring buffer, head has been there and has
383	 * numerically wrapped around at least once.
384	 */
385	for (i = watermark; i < buf_size; i++)
386		if (buf[i])
387			return true;
388
389	return false;
390}
391
392static int arm_spe_find_snapshot(struct auxtrace_record *itr, int idx,
393				  struct auxtrace_mmap *mm, unsigned char *data,
394				  u64 *head, u64 *old)
395{
396	int err;
397	bool wrapped;
398	struct arm_spe_recording *ptr =
399			container_of(itr, struct arm_spe_recording, itr);
400
401	/*
402	 * Allocate memory to keep track of wrapping if this is the first
403	 * time we deal with this *mm.
404	 */
405	if (idx >= ptr->wrapped_cnt) {
406		err = arm_spe_alloc_wrapped_array(ptr, idx);
407		if (err)
408			return err;
409	}
410
411	/*
412	 * Check to see if *head has wrapped around.  If it hasn't only the
413	 * amount of data between *head and *old is snapshot'ed to avoid
414	 * bloating the perf.data file with zeros.  But as soon as *head has
415	 * wrapped around the entire size of the AUX ring buffer it taken.
416	 */
417	wrapped = ptr->wrapped[idx];
418	if (!wrapped && arm_spe_buffer_has_wrapped(data, mm->len, *head)) {
419		wrapped = true;
420		ptr->wrapped[idx] = true;
421	}
422
423	pr_debug3("%s: mmap index %d old head %zu new head %zu size %zu\n",
424		  __func__, idx, (size_t)*old, (size_t)*head, mm->len);
425
426	/*
427	 * No wrap has occurred, we can just use *head and *old.
428	 */
429	if (!wrapped)
430		return 0;
431
432	/*
433	 * *head has wrapped around - adjust *head and *old to pickup the
434	 * entire content of the AUX buffer.
435	 */
436	if (*head >= mm->len) {
437		*old = *head - mm->len;
438	} else {
439		*head += mm->len;
440		*old = *head - mm->len;
441	}
442
443	return 0;
444}
445
446static u64 arm_spe_reference(struct auxtrace_record *itr __maybe_unused)
447{
448	struct timespec ts;
449
450	clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
451
452	return ts.tv_sec ^ ts.tv_nsec;
453}
454
455static void arm_spe_recording_free(struct auxtrace_record *itr)
456{
457	struct arm_spe_recording *sper =
458			container_of(itr, struct arm_spe_recording, itr);
459
460	zfree(&sper->wrapped);
461	free(sper);
462}
463
464struct auxtrace_record *arm_spe_recording_init(int *err,
465					       struct perf_pmu *arm_spe_pmu)
466{
467	struct arm_spe_recording *sper;
468
469	if (!arm_spe_pmu) {
470		*err = -ENODEV;
471		return NULL;
472	}
473
474	sper = zalloc(sizeof(struct arm_spe_recording));
475	if (!sper) {
476		*err = -ENOMEM;
477		return NULL;
478	}
479
480	sper->arm_spe_pmu = arm_spe_pmu;
481	sper->itr.pmu = arm_spe_pmu;
482	sper->itr.snapshot_start = arm_spe_snapshot_start;
483	sper->itr.snapshot_finish = arm_spe_snapshot_finish;
484	sper->itr.find_snapshot = arm_spe_find_snapshot;
485	sper->itr.parse_snapshot_options = arm_spe_parse_snapshot_options;
486	sper->itr.recording_options = arm_spe_recording_options;
487	sper->itr.info_priv_size = arm_spe_info_priv_size;
488	sper->itr.info_fill = arm_spe_info_fill;
489	sper->itr.free = arm_spe_recording_free;
490	sper->itr.reference = arm_spe_reference;
491	sper->itr.read_finish = auxtrace_record__read_finish;
492	sper->itr.alignment = 0;
493
494	*err = 0;
495	return &sper->itr;
496}
497
498struct perf_event_attr
499*arm_spe_pmu_default_config(struct perf_pmu *arm_spe_pmu)
500{
501	struct perf_event_attr *attr;
502
503	attr = zalloc(sizeof(struct perf_event_attr));
504	if (!attr) {
505		pr_err("arm_spe default config cannot allocate a perf_event_attr\n");
506		return NULL;
507	}
508
509	/*
510	 * If kernel driver doesn't advertise a minimum,
511	 * use max allowable by PMSIDR_EL1.INTERVAL
512	 */
513	if (perf_pmu__scan_file(arm_spe_pmu, "caps/min_interval", "%llu",
514				  &attr->sample_period) != 1) {
515		pr_debug("arm_spe driver doesn't advertise a min. interval. Using 4096\n");
516		attr->sample_period = 4096;
517	}
518
519	arm_spe_pmu->selectable = true;
520	arm_spe_pmu->is_uncore = false;
521
522	return attr;
523}
524