xref: /openbmc/linux/tools/perf/arch/arm/util/cs-etm.c (revision 82df5b73)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright(C) 2015 Linaro Limited. All rights reserved.
4  * Author: Mathieu Poirier <mathieu.poirier@linaro.org>
5  */
6 
7 #include <api/fs/fs.h>
8 #include <linux/bits.h>
9 #include <linux/bitops.h>
10 #include <linux/compiler.h>
11 #include <linux/coresight-pmu.h>
12 #include <linux/kernel.h>
13 #include <linux/log2.h>
14 #include <linux/string.h>
15 #include <linux/types.h>
16 #include <linux/zalloc.h>
17 
18 #include "cs-etm.h"
19 #include "../../util/debug.h"
20 #include "../../util/record.h"
21 #include "../../util/auxtrace.h"
22 #include "../../util/cpumap.h"
23 #include "../../util/event.h"
24 #include "../../util/evlist.h"
25 #include "../../util/evsel.h"
26 #include "../../util/perf_api_probe.h"
27 #include "../../util/evsel_config.h"
28 #include "../../util/pmu.h"
29 #include "../../util/cs-etm.h"
30 #include <internal/lib.h> // page_size
31 #include "../../util/session.h"
32 
33 #include <errno.h>
34 #include <stdlib.h>
35 #include <sys/stat.h>
36 
37 struct cs_etm_recording {
38 	struct auxtrace_record	itr;
39 	struct perf_pmu		*cs_etm_pmu;
40 	struct evlist		*evlist;
41 	int			wrapped_cnt;
42 	bool			*wrapped;
43 	bool			snapshot_mode;
44 	size_t			snapshot_size;
45 };
46 
47 static const char *metadata_etmv3_ro[CS_ETM_PRIV_MAX] = {
48 	[CS_ETM_ETMCCER]	= "mgmt/etmccer",
49 	[CS_ETM_ETMIDR]		= "mgmt/etmidr",
50 };
51 
52 static const char *metadata_etmv4_ro[CS_ETMV4_PRIV_MAX] = {
53 	[CS_ETMV4_TRCIDR0]		= "trcidr/trcidr0",
54 	[CS_ETMV4_TRCIDR1]		= "trcidr/trcidr1",
55 	[CS_ETMV4_TRCIDR2]		= "trcidr/trcidr2",
56 	[CS_ETMV4_TRCIDR8]		= "trcidr/trcidr8",
57 	[CS_ETMV4_TRCAUTHSTATUS]	= "mgmt/trcauthstatus",
58 };
59 
60 static bool cs_etm_is_etmv4(struct auxtrace_record *itr, int cpu);
61 
62 static int cs_etm_set_context_id(struct auxtrace_record *itr,
63 				 struct evsel *evsel, int cpu)
64 {
65 	struct cs_etm_recording *ptr;
66 	struct perf_pmu *cs_etm_pmu;
67 	char path[PATH_MAX];
68 	int err = -EINVAL;
69 	u32 val;
70 
71 	ptr = container_of(itr, struct cs_etm_recording, itr);
72 	cs_etm_pmu = ptr->cs_etm_pmu;
73 
74 	if (!cs_etm_is_etmv4(itr, cpu))
75 		goto out;
76 
77 	/* Get a handle on TRCIRD2 */
78 	snprintf(path, PATH_MAX, "cpu%d/%s",
79 		 cpu, metadata_etmv4_ro[CS_ETMV4_TRCIDR2]);
80 	err = perf_pmu__scan_file(cs_etm_pmu, path, "%x", &val);
81 
82 	/* There was a problem reading the file, bailing out */
83 	if (err != 1) {
84 		pr_err("%s: can't read file %s\n",
85 		       CORESIGHT_ETM_PMU_NAME, path);
86 		goto out;
87 	}
88 
89 	/*
90 	 * TRCIDR2.CIDSIZE, bit [9-5], indicates whether contextID tracing
91 	 * is supported:
92 	 *  0b00000 Context ID tracing is not supported.
93 	 *  0b00100 Maximum of 32-bit Context ID size.
94 	 *  All other values are reserved.
95 	 */
96 	val = BMVAL(val, 5, 9);
97 	if (!val || val != 0x4) {
98 		err = -EINVAL;
99 		goto out;
100 	}
101 
102 	/* All good, let the kernel know */
103 	evsel->core.attr.config |= (1 << ETM_OPT_CTXTID);
104 	err = 0;
105 
106 out:
107 
108 	return err;
109 }
110 
111 static int cs_etm_set_timestamp(struct auxtrace_record *itr,
112 				struct evsel *evsel, int cpu)
113 {
114 	struct cs_etm_recording *ptr;
115 	struct perf_pmu *cs_etm_pmu;
116 	char path[PATH_MAX];
117 	int err = -EINVAL;
118 	u32 val;
119 
120 	ptr = container_of(itr, struct cs_etm_recording, itr);
121 	cs_etm_pmu = ptr->cs_etm_pmu;
122 
123 	if (!cs_etm_is_etmv4(itr, cpu))
124 		goto out;
125 
126 	/* Get a handle on TRCIRD0 */
127 	snprintf(path, PATH_MAX, "cpu%d/%s",
128 		 cpu, metadata_etmv4_ro[CS_ETMV4_TRCIDR0]);
129 	err = perf_pmu__scan_file(cs_etm_pmu, path, "%x", &val);
130 
131 	/* There was a problem reading the file, bailing out */
132 	if (err != 1) {
133 		pr_err("%s: can't read file %s\n",
134 		       CORESIGHT_ETM_PMU_NAME, path);
135 		goto out;
136 	}
137 
138 	/*
139 	 * TRCIDR0.TSSIZE, bit [28-24], indicates whether global timestamping
140 	 * is supported:
141 	 *  0b00000 Global timestamping is not implemented
142 	 *  0b00110 Implementation supports a maximum timestamp of 48bits.
143 	 *  0b01000 Implementation supports a maximum timestamp of 64bits.
144 	 */
145 	val &= GENMASK(28, 24);
146 	if (!val) {
147 		err = -EINVAL;
148 		goto out;
149 	}
150 
151 	/* All good, let the kernel know */
152 	evsel->core.attr.config |= (1 << ETM_OPT_TS);
153 	err = 0;
154 
155 out:
156 	return err;
157 }
158 
159 static int cs_etm_set_option(struct auxtrace_record *itr,
160 			     struct evsel *evsel, u32 option)
161 {
162 	int i, err = -EINVAL;
163 	struct perf_cpu_map *event_cpus = evsel->evlist->core.cpus;
164 	struct perf_cpu_map *online_cpus = perf_cpu_map__new(NULL);
165 
166 	/* Set option of each CPU we have */
167 	for (i = 0; i < cpu__max_cpu(); i++) {
168 		if (!cpu_map__has(event_cpus, i) ||
169 		    !cpu_map__has(online_cpus, i))
170 			continue;
171 
172 		if (option & ETM_OPT_CTXTID) {
173 			err = cs_etm_set_context_id(itr, evsel, i);
174 			if (err)
175 				goto out;
176 		}
177 		if (option & ETM_OPT_TS) {
178 			err = cs_etm_set_timestamp(itr, evsel, i);
179 			if (err)
180 				goto out;
181 		}
182 		if (option & ~(ETM_OPT_CTXTID | ETM_OPT_TS))
183 			/* Nothing else is currently supported */
184 			goto out;
185 	}
186 
187 	err = 0;
188 out:
189 	perf_cpu_map__put(online_cpus);
190 	return err;
191 }
192 
193 static int cs_etm_parse_snapshot_options(struct auxtrace_record *itr,
194 					 struct record_opts *opts,
195 					 const char *str)
196 {
197 	struct cs_etm_recording *ptr =
198 				container_of(itr, struct cs_etm_recording, itr);
199 	unsigned long long snapshot_size = 0;
200 	char *endptr;
201 
202 	if (str) {
203 		snapshot_size = strtoull(str, &endptr, 0);
204 		if (*endptr || snapshot_size > SIZE_MAX)
205 			return -1;
206 	}
207 
208 	opts->auxtrace_snapshot_mode = true;
209 	opts->auxtrace_snapshot_size = snapshot_size;
210 	ptr->snapshot_size = snapshot_size;
211 
212 	return 0;
213 }
214 
215 static int cs_etm_set_sink_attr(struct perf_pmu *pmu,
216 				struct evsel *evsel)
217 {
218 	char msg[BUFSIZ], path[PATH_MAX], *sink;
219 	struct evsel_config_term *term;
220 	int ret = -EINVAL;
221 	u32 hash;
222 
223 	if (evsel->core.attr.config2 & GENMASK(31, 0))
224 		return 0;
225 
226 	list_for_each_entry(term, &evsel->config_terms, list) {
227 		if (term->type != EVSEL__CONFIG_TERM_DRV_CFG)
228 			continue;
229 
230 		sink = term->val.str;
231 		snprintf(path, PATH_MAX, "sinks/%s", sink);
232 
233 		ret = perf_pmu__scan_file(pmu, path, "%x", &hash);
234 		if (ret != 1) {
235 			pr_err("failed to set sink \"%s\" on event %s with %d (%s)\n",
236 			       sink, evsel__name(evsel), errno,
237 			       str_error_r(errno, msg, sizeof(msg)));
238 			return ret;
239 		}
240 
241 		evsel->core.attr.config2 |= hash;
242 		return 0;
243 	}
244 
245 	/*
246 	 * No sink was provided on the command line - for _now_ treat
247 	 * this as an error.
248 	 */
249 	return ret;
250 }
251 
252 static int cs_etm_recording_options(struct auxtrace_record *itr,
253 				    struct evlist *evlist,
254 				    struct record_opts *opts)
255 {
256 	int ret;
257 	struct cs_etm_recording *ptr =
258 				container_of(itr, struct cs_etm_recording, itr);
259 	struct perf_pmu *cs_etm_pmu = ptr->cs_etm_pmu;
260 	struct evsel *evsel, *cs_etm_evsel = NULL;
261 	struct perf_cpu_map *cpus = evlist->core.cpus;
262 	bool privileged = perf_event_paranoid_check(-1);
263 	int err = 0;
264 
265 	ptr->evlist = evlist;
266 	ptr->snapshot_mode = opts->auxtrace_snapshot_mode;
267 
268 	if (!record_opts__no_switch_events(opts) &&
269 	    perf_can_record_switch_events())
270 		opts->record_switch_events = true;
271 
272 	evlist__for_each_entry(evlist, evsel) {
273 		if (evsel->core.attr.type == cs_etm_pmu->type) {
274 			if (cs_etm_evsel) {
275 				pr_err("There may be only one %s event\n",
276 				       CORESIGHT_ETM_PMU_NAME);
277 				return -EINVAL;
278 			}
279 			evsel->core.attr.freq = 0;
280 			evsel->core.attr.sample_period = 1;
281 			cs_etm_evsel = evsel;
282 			opts->full_auxtrace = true;
283 		}
284 	}
285 
286 	/* no need to continue if at least one event of interest was found */
287 	if (!cs_etm_evsel)
288 		return 0;
289 
290 	ret = cs_etm_set_sink_attr(cs_etm_pmu, cs_etm_evsel);
291 	if (ret)
292 		return ret;
293 
294 	if (opts->use_clockid) {
295 		pr_err("Cannot use clockid (-k option) with %s\n",
296 		       CORESIGHT_ETM_PMU_NAME);
297 		return -EINVAL;
298 	}
299 
300 	/* we are in snapshot mode */
301 	if (opts->auxtrace_snapshot_mode) {
302 		/*
303 		 * No size were given to '-S' or '-m,', so go with
304 		 * the default
305 		 */
306 		if (!opts->auxtrace_snapshot_size &&
307 		    !opts->auxtrace_mmap_pages) {
308 			if (privileged) {
309 				opts->auxtrace_mmap_pages = MiB(4) / page_size;
310 			} else {
311 				opts->auxtrace_mmap_pages =
312 							KiB(128) / page_size;
313 				if (opts->mmap_pages == UINT_MAX)
314 					opts->mmap_pages = KiB(256) / page_size;
315 			}
316 		} else if (!opts->auxtrace_mmap_pages && !privileged &&
317 						opts->mmap_pages == UINT_MAX) {
318 			opts->mmap_pages = KiB(256) / page_size;
319 		}
320 
321 		/*
322 		 * '-m,xyz' was specified but no snapshot size, so make the
323 		 * snapshot size as big as the auxtrace mmap area.
324 		 */
325 		if (!opts->auxtrace_snapshot_size) {
326 			opts->auxtrace_snapshot_size =
327 				opts->auxtrace_mmap_pages * (size_t)page_size;
328 		}
329 
330 		/*
331 		 * -Sxyz was specified but no auxtrace mmap area, so make the
332 		 * auxtrace mmap area big enough to fit the requested snapshot
333 		 * size.
334 		 */
335 		if (!opts->auxtrace_mmap_pages) {
336 			size_t sz = opts->auxtrace_snapshot_size;
337 
338 			sz = round_up(sz, page_size) / page_size;
339 			opts->auxtrace_mmap_pages = roundup_pow_of_two(sz);
340 		}
341 
342 		/* Snapshost size can't be bigger than the auxtrace area */
343 		if (opts->auxtrace_snapshot_size >
344 				opts->auxtrace_mmap_pages * (size_t)page_size) {
345 			pr_err("Snapshot size %zu must not be greater than AUX area tracing mmap size %zu\n",
346 			       opts->auxtrace_snapshot_size,
347 			       opts->auxtrace_mmap_pages * (size_t)page_size);
348 			return -EINVAL;
349 		}
350 
351 		/* Something went wrong somewhere - this shouldn't happen */
352 		if (!opts->auxtrace_snapshot_size ||
353 		    !opts->auxtrace_mmap_pages) {
354 			pr_err("Failed to calculate default snapshot size and/or AUX area tracing mmap pages\n");
355 			return -EINVAL;
356 		}
357 	}
358 
359 	/* We are in full trace mode but '-m,xyz' wasn't specified */
360 	if (opts->full_auxtrace && !opts->auxtrace_mmap_pages) {
361 		if (privileged) {
362 			opts->auxtrace_mmap_pages = MiB(4) / page_size;
363 		} else {
364 			opts->auxtrace_mmap_pages = KiB(128) / page_size;
365 			if (opts->mmap_pages == UINT_MAX)
366 				opts->mmap_pages = KiB(256) / page_size;
367 		}
368 
369 	}
370 
371 	/* Validate auxtrace_mmap_pages provided by user */
372 	if (opts->auxtrace_mmap_pages) {
373 		unsigned int max_page = (KiB(128) / page_size);
374 		size_t sz = opts->auxtrace_mmap_pages * (size_t)page_size;
375 
376 		if (!privileged &&
377 		    opts->auxtrace_mmap_pages > max_page) {
378 			opts->auxtrace_mmap_pages = max_page;
379 			pr_err("auxtrace too big, truncating to %d\n",
380 			       max_page);
381 		}
382 
383 		if (!is_power_of_2(sz)) {
384 			pr_err("Invalid mmap size for %s: must be a power of 2\n",
385 			       CORESIGHT_ETM_PMU_NAME);
386 			return -EINVAL;
387 		}
388 	}
389 
390 	if (opts->auxtrace_snapshot_mode)
391 		pr_debug2("%s snapshot size: %zu\n", CORESIGHT_ETM_PMU_NAME,
392 			  opts->auxtrace_snapshot_size);
393 
394 	/*
395 	 * To obtain the auxtrace buffer file descriptor, the auxtrace
396 	 * event must come first.
397 	 */
398 	perf_evlist__to_front(evlist, cs_etm_evsel);
399 
400 	/*
401 	 * In the case of per-cpu mmaps, we need the CPU on the
402 	 * AUX event.  We also need the contextID in order to be notified
403 	 * when a context switch happened.
404 	 */
405 	if (!perf_cpu_map__empty(cpus)) {
406 		evsel__set_sample_bit(cs_etm_evsel, CPU);
407 
408 		err = cs_etm_set_option(itr, cs_etm_evsel,
409 					ETM_OPT_CTXTID | ETM_OPT_TS);
410 		if (err)
411 			goto out;
412 	}
413 
414 	/* Add dummy event to keep tracking */
415 	if (opts->full_auxtrace) {
416 		struct evsel *tracking_evsel;
417 
418 		err = parse_events(evlist, "dummy:u", NULL);
419 		if (err)
420 			goto out;
421 
422 		tracking_evsel = evlist__last(evlist);
423 		perf_evlist__set_tracking_event(evlist, tracking_evsel);
424 
425 		tracking_evsel->core.attr.freq = 0;
426 		tracking_evsel->core.attr.sample_period = 1;
427 
428 		/* In per-cpu case, always need the time of mmap events etc */
429 		if (!perf_cpu_map__empty(cpus))
430 			evsel__set_sample_bit(tracking_evsel, TIME);
431 	}
432 
433 out:
434 	return err;
435 }
436 
437 static u64 cs_etm_get_config(struct auxtrace_record *itr)
438 {
439 	u64 config = 0;
440 	struct cs_etm_recording *ptr =
441 			container_of(itr, struct cs_etm_recording, itr);
442 	struct perf_pmu *cs_etm_pmu = ptr->cs_etm_pmu;
443 	struct evlist *evlist = ptr->evlist;
444 	struct evsel *evsel;
445 
446 	evlist__for_each_entry(evlist, evsel) {
447 		if (evsel->core.attr.type == cs_etm_pmu->type) {
448 			/*
449 			 * Variable perf_event_attr::config is assigned to
450 			 * ETMv3/PTM.  The bit fields have been made to match
451 			 * the ETMv3.5 ETRMCR register specification.  See the
452 			 * PMU_FORMAT_ATTR() declarations in
453 			 * drivers/hwtracing/coresight/coresight-perf.c for
454 			 * details.
455 			 */
456 			config = evsel->core.attr.config;
457 			break;
458 		}
459 	}
460 
461 	return config;
462 }
463 
464 #ifndef BIT
465 #define BIT(N) (1UL << (N))
466 #endif
467 
468 static u64 cs_etmv4_get_config(struct auxtrace_record *itr)
469 {
470 	u64 config = 0;
471 	u64 config_opts = 0;
472 
473 	/*
474 	 * The perf event variable config bits represent both
475 	 * the command line options and register programming
476 	 * bits in ETMv3/PTM. For ETMv4 we must remap options
477 	 * to real bits
478 	 */
479 	config_opts = cs_etm_get_config(itr);
480 	if (config_opts & BIT(ETM_OPT_CYCACC))
481 		config |= BIT(ETM4_CFG_BIT_CYCACC);
482 	if (config_opts & BIT(ETM_OPT_CTXTID))
483 		config |= BIT(ETM4_CFG_BIT_CTXTID);
484 	if (config_opts & BIT(ETM_OPT_TS))
485 		config |= BIT(ETM4_CFG_BIT_TS);
486 	if (config_opts & BIT(ETM_OPT_RETSTK))
487 		config |= BIT(ETM4_CFG_BIT_RETSTK);
488 
489 	return config;
490 }
491 
492 static size_t
493 cs_etm_info_priv_size(struct auxtrace_record *itr __maybe_unused,
494 		      struct evlist *evlist __maybe_unused)
495 {
496 	int i;
497 	int etmv3 = 0, etmv4 = 0;
498 	struct perf_cpu_map *event_cpus = evlist->core.cpus;
499 	struct perf_cpu_map *online_cpus = perf_cpu_map__new(NULL);
500 
501 	/* cpu map is not empty, we have specific CPUs to work with */
502 	if (!perf_cpu_map__empty(event_cpus)) {
503 		for (i = 0; i < cpu__max_cpu(); i++) {
504 			if (!cpu_map__has(event_cpus, i) ||
505 			    !cpu_map__has(online_cpus, i))
506 				continue;
507 
508 			if (cs_etm_is_etmv4(itr, i))
509 				etmv4++;
510 			else
511 				etmv3++;
512 		}
513 	} else {
514 		/* get configuration for all CPUs in the system */
515 		for (i = 0; i < cpu__max_cpu(); i++) {
516 			if (!cpu_map__has(online_cpus, i))
517 				continue;
518 
519 			if (cs_etm_is_etmv4(itr, i))
520 				etmv4++;
521 			else
522 				etmv3++;
523 		}
524 	}
525 
526 	perf_cpu_map__put(online_cpus);
527 
528 	return (CS_ETM_HEADER_SIZE +
529 	       (etmv4 * CS_ETMV4_PRIV_SIZE) +
530 	       (etmv3 * CS_ETMV3_PRIV_SIZE));
531 }
532 
533 static bool cs_etm_is_etmv4(struct auxtrace_record *itr, int cpu)
534 {
535 	bool ret = false;
536 	char path[PATH_MAX];
537 	int scan;
538 	unsigned int val;
539 	struct cs_etm_recording *ptr =
540 			container_of(itr, struct cs_etm_recording, itr);
541 	struct perf_pmu *cs_etm_pmu = ptr->cs_etm_pmu;
542 
543 	/* Take any of the RO files for ETMv4 and see if it present */
544 	snprintf(path, PATH_MAX, "cpu%d/%s",
545 		 cpu, metadata_etmv4_ro[CS_ETMV4_TRCIDR0]);
546 	scan = perf_pmu__scan_file(cs_etm_pmu, path, "%x", &val);
547 
548 	/* The file was read successfully, we have a winner */
549 	if (scan == 1)
550 		ret = true;
551 
552 	return ret;
553 }
554 
555 static int cs_etm_get_ro(struct perf_pmu *pmu, int cpu, const char *path)
556 {
557 	char pmu_path[PATH_MAX];
558 	int scan;
559 	unsigned int val = 0;
560 
561 	/* Get RO metadata from sysfs */
562 	snprintf(pmu_path, PATH_MAX, "cpu%d/%s", cpu, path);
563 
564 	scan = perf_pmu__scan_file(pmu, pmu_path, "%x", &val);
565 	if (scan != 1)
566 		pr_err("%s: error reading: %s\n", __func__, pmu_path);
567 
568 	return val;
569 }
570 
571 static void cs_etm_get_metadata(int cpu, u32 *offset,
572 				struct auxtrace_record *itr,
573 				struct perf_record_auxtrace_info *info)
574 {
575 	u32 increment;
576 	u64 magic;
577 	struct cs_etm_recording *ptr =
578 			container_of(itr, struct cs_etm_recording, itr);
579 	struct perf_pmu *cs_etm_pmu = ptr->cs_etm_pmu;
580 
581 	/* first see what kind of tracer this cpu is affined to */
582 	if (cs_etm_is_etmv4(itr, cpu)) {
583 		magic = __perf_cs_etmv4_magic;
584 		/* Get trace configuration register */
585 		info->priv[*offset + CS_ETMV4_TRCCONFIGR] =
586 						cs_etmv4_get_config(itr);
587 		/* Get traceID from the framework */
588 		info->priv[*offset + CS_ETMV4_TRCTRACEIDR] =
589 						coresight_get_trace_id(cpu);
590 		/* Get read-only information from sysFS */
591 		info->priv[*offset + CS_ETMV4_TRCIDR0] =
592 			cs_etm_get_ro(cs_etm_pmu, cpu,
593 				      metadata_etmv4_ro[CS_ETMV4_TRCIDR0]);
594 		info->priv[*offset + CS_ETMV4_TRCIDR1] =
595 			cs_etm_get_ro(cs_etm_pmu, cpu,
596 				      metadata_etmv4_ro[CS_ETMV4_TRCIDR1]);
597 		info->priv[*offset + CS_ETMV4_TRCIDR2] =
598 			cs_etm_get_ro(cs_etm_pmu, cpu,
599 				      metadata_etmv4_ro[CS_ETMV4_TRCIDR2]);
600 		info->priv[*offset + CS_ETMV4_TRCIDR8] =
601 			cs_etm_get_ro(cs_etm_pmu, cpu,
602 				      metadata_etmv4_ro[CS_ETMV4_TRCIDR8]);
603 		info->priv[*offset + CS_ETMV4_TRCAUTHSTATUS] =
604 			cs_etm_get_ro(cs_etm_pmu, cpu,
605 				      metadata_etmv4_ro
606 				      [CS_ETMV4_TRCAUTHSTATUS]);
607 
608 		/* How much space was used */
609 		increment = CS_ETMV4_PRIV_MAX;
610 	} else {
611 		magic = __perf_cs_etmv3_magic;
612 		/* Get configuration register */
613 		info->priv[*offset + CS_ETM_ETMCR] = cs_etm_get_config(itr);
614 		/* Get traceID from the framework */
615 		info->priv[*offset + CS_ETM_ETMTRACEIDR] =
616 						coresight_get_trace_id(cpu);
617 		/* Get read-only information from sysFS */
618 		info->priv[*offset + CS_ETM_ETMCCER] =
619 			cs_etm_get_ro(cs_etm_pmu, cpu,
620 				      metadata_etmv3_ro[CS_ETM_ETMCCER]);
621 		info->priv[*offset + CS_ETM_ETMIDR] =
622 			cs_etm_get_ro(cs_etm_pmu, cpu,
623 				      metadata_etmv3_ro[CS_ETM_ETMIDR]);
624 
625 		/* How much space was used */
626 		increment = CS_ETM_PRIV_MAX;
627 	}
628 
629 	/* Build generic header portion */
630 	info->priv[*offset + CS_ETM_MAGIC] = magic;
631 	info->priv[*offset + CS_ETM_CPU] = cpu;
632 	/* Where the next CPU entry should start from */
633 	*offset += increment;
634 }
635 
636 static int cs_etm_info_fill(struct auxtrace_record *itr,
637 			    struct perf_session *session,
638 			    struct perf_record_auxtrace_info *info,
639 			    size_t priv_size)
640 {
641 	int i;
642 	u32 offset;
643 	u64 nr_cpu, type;
644 	struct perf_cpu_map *cpu_map;
645 	struct perf_cpu_map *event_cpus = session->evlist->core.cpus;
646 	struct perf_cpu_map *online_cpus = perf_cpu_map__new(NULL);
647 	struct cs_etm_recording *ptr =
648 			container_of(itr, struct cs_etm_recording, itr);
649 	struct perf_pmu *cs_etm_pmu = ptr->cs_etm_pmu;
650 
651 	if (priv_size != cs_etm_info_priv_size(itr, session->evlist))
652 		return -EINVAL;
653 
654 	if (!session->evlist->core.nr_mmaps)
655 		return -EINVAL;
656 
657 	/* If the cpu_map is empty all online CPUs are involved */
658 	if (perf_cpu_map__empty(event_cpus)) {
659 		cpu_map = online_cpus;
660 	} else {
661 		/* Make sure all specified CPUs are online */
662 		for (i = 0; i < perf_cpu_map__nr(event_cpus); i++) {
663 			if (cpu_map__has(event_cpus, i) &&
664 			    !cpu_map__has(online_cpus, i))
665 				return -EINVAL;
666 		}
667 
668 		cpu_map = event_cpus;
669 	}
670 
671 	nr_cpu = perf_cpu_map__nr(cpu_map);
672 	/* Get PMU type as dynamically assigned by the core */
673 	type = cs_etm_pmu->type;
674 
675 	/* First fill out the session header */
676 	info->type = PERF_AUXTRACE_CS_ETM;
677 	info->priv[CS_HEADER_VERSION_0] = 0;
678 	info->priv[CS_PMU_TYPE_CPUS] = type << 32;
679 	info->priv[CS_PMU_TYPE_CPUS] |= nr_cpu;
680 	info->priv[CS_ETM_SNAPSHOT] = ptr->snapshot_mode;
681 
682 	offset = CS_ETM_SNAPSHOT + 1;
683 
684 	for (i = 0; i < cpu__max_cpu() && offset < priv_size; i++)
685 		if (cpu_map__has(cpu_map, i))
686 			cs_etm_get_metadata(i, &offset, itr, info);
687 
688 	perf_cpu_map__put(online_cpus);
689 
690 	return 0;
691 }
692 
693 static int cs_etm_alloc_wrapped_array(struct cs_etm_recording *ptr, int idx)
694 {
695 	bool *wrapped;
696 	int cnt = ptr->wrapped_cnt;
697 
698 	/* Make @ptr->wrapped as big as @idx */
699 	while (cnt <= idx)
700 		cnt++;
701 
702 	/*
703 	 * Free'ed in cs_etm_recording_free().  Using realloc() to avoid
704 	 * cross compilation problems where the host's system supports
705 	 * reallocarray() but not the target.
706 	 */
707 	wrapped = realloc(ptr->wrapped, cnt * sizeof(bool));
708 	if (!wrapped)
709 		return -ENOMEM;
710 
711 	wrapped[cnt - 1] = false;
712 	ptr->wrapped_cnt = cnt;
713 	ptr->wrapped = wrapped;
714 
715 	return 0;
716 }
717 
718 static bool cs_etm_buffer_has_wrapped(unsigned char *buffer,
719 				      size_t buffer_size, u64 head)
720 {
721 	u64 i, watermark;
722 	u64 *buf = (u64 *)buffer;
723 	size_t buf_size = buffer_size;
724 
725 	/*
726 	 * We want to look the very last 512 byte (chosen arbitrarily) in
727 	 * the ring buffer.
728 	 */
729 	watermark = buf_size - 512;
730 
731 	/*
732 	 * @head is continuously increasing - if its value is equal or greater
733 	 * than the size of the ring buffer, it has wrapped around.
734 	 */
735 	if (head >= buffer_size)
736 		return true;
737 
738 	/*
739 	 * The value of @head is somewhere within the size of the ring buffer.
740 	 * This can be that there hasn't been enough data to fill the ring
741 	 * buffer yet or the trace time was so long that @head has numerically
742 	 * wrapped around.  To find we need to check if we have data at the very
743 	 * end of the ring buffer.  We can reliably do this because mmap'ed
744 	 * pages are zeroed out and there is a fresh mapping with every new
745 	 * session.
746 	 */
747 
748 	/* @head is less than 512 byte from the end of the ring buffer */
749 	if (head > watermark)
750 		watermark = head;
751 
752 	/*
753 	 * Speed things up by using 64 bit transactions (see "u64 *buf" above)
754 	 */
755 	watermark >>= 3;
756 	buf_size >>= 3;
757 
758 	/*
759 	 * If we find trace data at the end of the ring buffer, @head has
760 	 * been there and has numerically wrapped around at least once.
761 	 */
762 	for (i = watermark; i < buf_size; i++)
763 		if (buf[i])
764 			return true;
765 
766 	return false;
767 }
768 
769 static int cs_etm_find_snapshot(struct auxtrace_record *itr,
770 				int idx, struct auxtrace_mmap *mm,
771 				unsigned char *data,
772 				u64 *head, u64 *old)
773 {
774 	int err;
775 	bool wrapped;
776 	struct cs_etm_recording *ptr =
777 			container_of(itr, struct cs_etm_recording, itr);
778 
779 	/*
780 	 * Allocate memory to keep track of wrapping if this is the first
781 	 * time we deal with this *mm.
782 	 */
783 	if (idx >= ptr->wrapped_cnt) {
784 		err = cs_etm_alloc_wrapped_array(ptr, idx);
785 		if (err)
786 			return err;
787 	}
788 
789 	/*
790 	 * Check to see if *head has wrapped around.  If it hasn't only the
791 	 * amount of data between *head and *old is snapshot'ed to avoid
792 	 * bloating the perf.data file with zeros.  But as soon as *head has
793 	 * wrapped around the entire size of the AUX ring buffer it taken.
794 	 */
795 	wrapped = ptr->wrapped[idx];
796 	if (!wrapped && cs_etm_buffer_has_wrapped(data, mm->len, *head)) {
797 		wrapped = true;
798 		ptr->wrapped[idx] = true;
799 	}
800 
801 	pr_debug3("%s: mmap index %d old head %zu new head %zu size %zu\n",
802 		  __func__, idx, (size_t)*old, (size_t)*head, mm->len);
803 
804 	/* No wrap has occurred, we can just use *head and *old. */
805 	if (!wrapped)
806 		return 0;
807 
808 	/*
809 	 * *head has wrapped around - adjust *head and *old to pickup the
810 	 * entire content of the AUX buffer.
811 	 */
812 	if (*head >= mm->len) {
813 		*old = *head - mm->len;
814 	} else {
815 		*head += mm->len;
816 		*old = *head - mm->len;
817 	}
818 
819 	return 0;
820 }
821 
822 static int cs_etm_snapshot_start(struct auxtrace_record *itr)
823 {
824 	struct cs_etm_recording *ptr =
825 			container_of(itr, struct cs_etm_recording, itr);
826 	struct evsel *evsel;
827 
828 	evlist__for_each_entry(ptr->evlist, evsel) {
829 		if (evsel->core.attr.type == ptr->cs_etm_pmu->type)
830 			return evsel__disable(evsel);
831 	}
832 	return -EINVAL;
833 }
834 
835 static int cs_etm_snapshot_finish(struct auxtrace_record *itr)
836 {
837 	struct cs_etm_recording *ptr =
838 			container_of(itr, struct cs_etm_recording, itr);
839 	struct evsel *evsel;
840 
841 	evlist__for_each_entry(ptr->evlist, evsel) {
842 		if (evsel->core.attr.type == ptr->cs_etm_pmu->type)
843 			return evsel__enable(evsel);
844 	}
845 	return -EINVAL;
846 }
847 
848 static u64 cs_etm_reference(struct auxtrace_record *itr __maybe_unused)
849 {
850 	return (((u64) rand() <<  0) & 0x00000000FFFFFFFFull) |
851 		(((u64) rand() << 32) & 0xFFFFFFFF00000000ull);
852 }
853 
854 static void cs_etm_recording_free(struct auxtrace_record *itr)
855 {
856 	struct cs_etm_recording *ptr =
857 			container_of(itr, struct cs_etm_recording, itr);
858 
859 	zfree(&ptr->wrapped);
860 	free(ptr);
861 }
862 
863 struct auxtrace_record *cs_etm_record_init(int *err)
864 {
865 	struct perf_pmu *cs_etm_pmu;
866 	struct cs_etm_recording *ptr;
867 
868 	cs_etm_pmu = perf_pmu__find(CORESIGHT_ETM_PMU_NAME);
869 
870 	if (!cs_etm_pmu) {
871 		*err = -EINVAL;
872 		goto out;
873 	}
874 
875 	ptr = zalloc(sizeof(struct cs_etm_recording));
876 	if (!ptr) {
877 		*err = -ENOMEM;
878 		goto out;
879 	}
880 
881 	ptr->cs_etm_pmu			= cs_etm_pmu;
882 	ptr->itr.pmu			= cs_etm_pmu;
883 	ptr->itr.parse_snapshot_options	= cs_etm_parse_snapshot_options;
884 	ptr->itr.recording_options	= cs_etm_recording_options;
885 	ptr->itr.info_priv_size		= cs_etm_info_priv_size;
886 	ptr->itr.info_fill		= cs_etm_info_fill;
887 	ptr->itr.find_snapshot		= cs_etm_find_snapshot;
888 	ptr->itr.snapshot_start		= cs_etm_snapshot_start;
889 	ptr->itr.snapshot_finish	= cs_etm_snapshot_finish;
890 	ptr->itr.reference		= cs_etm_reference;
891 	ptr->itr.free			= cs_etm_recording_free;
892 	ptr->itr.read_finish		= auxtrace_record__read_finish;
893 
894 	*err = 0;
895 	return &ptr->itr;
896 out:
897 	return NULL;
898 }
899