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