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