xref: /linux/tools/perf/util/cs-etm.c (revision ca0e19074bd6afcb9c7b23aa474ca17238cdb241)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright(C) 2015-2018 Linaro Limited.
4  *
5  * Author: Tor Jeremiassen <tor@ti.com>
6  * Author: Mathieu Poirier <mathieu.poirier@linaro.org>
7  */
8 
9 #include <limits.h>
10 #include <linux/bitfield.h>
11 #include <linux/bitops.h>
12 #include <linux/coresight-pmu.h>
13 #include <linux/err.h>
14 #include <linux/log2.h>
15 #include <linux/types.h>
16 #include <linux/zalloc.h>
17 
18 #include <stdlib.h>
19 
20 #include "auxtrace.h"
21 #include "callchain.h"
22 #include "color.h"
23 #include "cs-etm.h"
24 #include "cs-etm-decoder/cs-etm-decoder.h"
25 #include "debug.h"
26 #include "dso.h"
27 #include "evlist.h"
28 #include "intlist.h"
29 #include "machine.h"
30 #include "map.h"
31 #include "perf.h"
32 #include "session.h"
33 #include "map_symbol.h"
34 #include "branch.h"
35 #include "symbol.h"
36 #include "tool.h"
37 #include "thread.h"
38 #include "thread-stack.h"
39 #include "tsc.h"
40 #include <tools/libc_compat.h>
41 #include "util/synthetic-events.h"
42 #include "util/util.h"
43 
44 struct cs_etm_auxtrace {
45 	struct auxtrace auxtrace;
46 	struct auxtrace_queues queues;
47 	struct auxtrace_heap heap;
48 	struct itrace_synth_opts synth_opts;
49 	struct perf_session *session;
50 	struct perf_tsc_conversion tc;
51 
52 	/*
53 	 * Timeless has no timestamps in the trace so overlapping mmap lookups
54 	 * are less accurate but produces smaller trace data. We use context IDs
55 	 * in the trace instead of matching timestamps with fork records so
56 	 * they're not really needed in the general case. Overlapping mmaps
57 	 * happen in cases like between a fork and an exec.
58 	 */
59 	bool timeless_decoding;
60 
61 	/*
62 	 * Per-thread ignores the trace channel ID and instead assumes that
63 	 * everything in a buffer comes from the same process regardless of
64 	 * which CPU it ran on. It also implies no context IDs so the TID is
65 	 * taken from the auxtrace buffer.
66 	 */
67 	bool per_thread_decoding;
68 	bool snapshot_mode;
69 	bool data_queued;
70 	bool has_virtual_ts; /* Virtual/Kernel timestamps in the trace. */
71 	bool use_thread_stack;
72 	bool use_callchain;
73 
74 	int num_cpu;
75 	u64 latest_kernel_timestamp;
76 	u32 auxtrace_type;
77 	u32 branches_filter;
78 	u64 branches_sample_type;
79 	u64 branches_id;
80 	u64 instructions_sample_type;
81 	u64 instructions_sample_period;
82 	u64 instructions_id;
83 	u64 **metadata;
84 	unsigned int pmu_type;
85 	enum cs_etm_pid_fmt pid_fmt;
86 };
87 
88 struct cs_etm_traceid_queue {
89 	u8 trace_chan_id;
90 	u64 period_instructions;
91 	u64 kernel_start;
92 	union perf_event *event_buf;
93 	unsigned int br_stack_sz;
94 	struct branch_stack *last_branch;
95 	struct ip_callchain *callchain;
96 	struct cs_etm_packet *prev_packet;
97 	struct cs_etm_packet *packet;
98 	struct cs_etm_packet_queue packet_queue;
99 
100 	struct thread *decode_thread;
101 	ocsd_ex_level decode_el;
102 
103 	/*
104 	 * The frontend accesses the EL from '[prev_]packet' because it needs
105 	 * previous EL for branch and current EL for instruction samples. It's
106 	 * not possible to change thread in a single branch sample so no need to
107 	 * store or access the thread through the packet.
108 	 */
109 	struct thread *frontend_thread;
110 };
111 
112 enum cs_etm_format {
113 	UNSET,
114 	FORMATTED,
115 	UNFORMATTED
116 };
117 
118 struct cs_etm_queue {
119 	struct cs_etm_auxtrace *etm;
120 	struct cs_etm_decoder *decoder;
121 	struct auxtrace_buffer *buffer;
122 	unsigned int queue_nr;
123 	u8 pending_timestamp_chan_id;
124 	enum cs_etm_format format;
125 	u64 offset;
126 	const unsigned char *buf;
127 	size_t buf_len, buf_used;
128 	/* Conversion between traceID and index in traceid_queues array */
129 	struct intlist *traceid_queues_list;
130 	struct cs_etm_traceid_queue **traceid_queues;
131 	/* Conversion between traceID and metadata pointers */
132 	struct intlist *traceid_list;
133 	/*
134 	 * Same as traceid_list, but traceid_list may be a reference to another
135 	 * queue's which has a matching sink ID.
136 	 */
137 	struct intlist *own_traceid_list;
138 	u32 sink_id;
139 };
140 
141 static int cs_etm__process_timestamped_queues(struct cs_etm_auxtrace *etm);
142 static int cs_etm__process_timeless_queues(struct cs_etm_auxtrace *etm,
143 					   pid_t tid);
144 static int cs_etm__get_data_block(struct cs_etm_queue *etmq);
145 static int cs_etm__decode_data_block(struct cs_etm_queue *etmq);
146 static int cs_etm__metadata_get_trace_id(u8 *trace_chan_id, u64 *cpu_metadata);
147 static u64 *get_cpu_data(struct cs_etm_auxtrace *etm, int cpu);
148 static int cs_etm__metadata_set_trace_id(u8 trace_chan_id, u64 *cpu_metadata);
149 
150 /* PTMs ETMIDR [11:8] set to b0011 */
151 #define ETMIDR_PTM_VERSION 0x00000300
152 
153 /*
154  * A struct auxtrace_heap_item only has a queue_nr and a timestamp to
155  * work with.  One option is to modify to auxtrace_heap_XYZ() API or simply
156  * encode the etm queue number as the upper 16 bit and the channel as
157  * the lower 16 bit.
158  */
159 #define TO_CS_QUEUE_NR(queue_nr, trace_chan_id)	\
160 		      (queue_nr << 16 | trace_chan_id)
161 #define TO_QUEUE_NR(cs_queue_nr) (cs_queue_nr >> 16)
162 #define TO_TRACE_CHAN_ID(cs_queue_nr) (cs_queue_nr & 0x0000ffff)
163 #define SINK_UNSET ((u32) -1)
164 
165 static u32 cs_etm__get_v7_protocol_version(u32 etmidr)
166 {
167 	etmidr &= ETMIDR_PTM_VERSION;
168 
169 	if (etmidr == ETMIDR_PTM_VERSION)
170 		return CS_ETM_PROTO_PTM;
171 
172 	return CS_ETM_PROTO_ETMV3;
173 }
174 
175 static int cs_etm__get_magic(struct cs_etm_queue *etmq, u8 trace_chan_id, u64 *magic)
176 {
177 	struct int_node *inode;
178 	u64 *metadata;
179 
180 	inode = intlist__find(etmq->traceid_list, trace_chan_id);
181 	if (!inode)
182 		return -EINVAL;
183 
184 	metadata = inode->priv;
185 	*magic = metadata[CS_ETM_MAGIC];
186 	return 0;
187 }
188 
189 int cs_etm__get_cpu(struct cs_etm_queue *etmq, u8 trace_chan_id, int *cpu)
190 {
191 	struct int_node *inode;
192 	u64 *metadata;
193 
194 	inode = intlist__find(etmq->traceid_list, trace_chan_id);
195 	if (!inode)
196 		return -EINVAL;
197 
198 	metadata = inode->priv;
199 	*cpu = (int)metadata[CS_ETM_CPU];
200 	return 0;
201 }
202 
203 /*
204  * The returned PID format is presented as an enum:
205  *
206  *   CS_ETM_PIDFMT_CTXTID: CONTEXTIDR or CONTEXTIDR_EL1 is traced.
207  *   CS_ETM_PIDFMT_CTXTID2: CONTEXTIDR_EL2 is traced.
208  *   CS_ETM_PIDFMT_NONE: No context IDs
209  *
210  * It's possible that the two format attributes 'contextid1' and 'contextid2'
211  * are enabled at the same time when the session runs on an EL2 kernel.
212  * This means the CONTEXTIDR_EL1 and CONTEXTIDR_EL2 both will be
213  * recorded in the trace data, the tool will selectively use
214  * CONTEXTIDR_EL2 as PID.
215  *
216  * The result is cached in etm->pid_fmt so this function only needs to be called
217  * when processing the aux info.
218  */
219 static enum cs_etm_pid_fmt cs_etm__init_pid_fmt(u64 *metadata)
220 {
221 	u64 val;
222 
223 	if (metadata[CS_ETM_MAGIC] == __perf_cs_etmv3_magic) {
224 		val = metadata[CS_ETM_ETMCR];
225 		/* CONTEXTIDR is traced */
226 		if (val & ETMCR_CTXTID)
227 			return CS_ETM_PIDFMT_CTXTID;
228 	} else {
229 		val = metadata[CS_ETMV4_TRCCONFIGR];
230 		/* CONTEXTIDR_EL2 is traced */
231 		if (val & (TRCCONFIGR_VMID | TRCCONFIGR_VMIDOPT))
232 			return CS_ETM_PIDFMT_CTXTID2;
233 		/* CONTEXTIDR_EL1 is traced */
234 		else if (val & TRCCONFIGR_CID)
235 			return CS_ETM_PIDFMT_CTXTID;
236 	}
237 
238 	return CS_ETM_PIDFMT_NONE;
239 }
240 
241 enum cs_etm_pid_fmt cs_etm__get_pid_fmt(struct cs_etm_queue *etmq)
242 {
243 	return etmq->etm->pid_fmt;
244 }
245 
246 static int cs_etm__insert_trace_id_node(struct cs_etm_queue *etmq,
247 					u8 trace_chan_id, u64 *cpu_metadata)
248 {
249 	/* Get an RB node for this CPU */
250 	struct int_node *inode = intlist__findnew(etmq->traceid_list, trace_chan_id);
251 
252 	/* Something went wrong, no need to continue */
253 	if (!inode)
254 		return -ENOMEM;
255 
256 	/* Disallow re-mapping a different traceID to metadata pair. */
257 	if (inode->priv) {
258 		u64 *curr_cpu_data = inode->priv;
259 		u8 curr_chan_id;
260 		int err;
261 
262 		if (curr_cpu_data[CS_ETM_CPU] != cpu_metadata[CS_ETM_CPU]) {
263 			/*
264 			 * With > CORESIGHT_TRACE_IDS_MAX ETMs, overlapping IDs
265 			 * are expected (but not supported) in per-thread mode,
266 			 * rather than signifying an error.
267 			 */
268 			if (etmq->etm->per_thread_decoding)
269 				pr_err("CS_ETM: overlapping Trace IDs aren't currently supported in per-thread mode\n");
270 			else
271 				pr_err("CS_ETM: map mismatch between HW_ID packet CPU and Trace ID\n");
272 
273 			return -EINVAL;
274 		}
275 
276 		/* check that the mapped ID matches */
277 		err = cs_etm__metadata_get_trace_id(&curr_chan_id, curr_cpu_data);
278 		if (err)
279 			return err;
280 
281 		if (curr_chan_id != trace_chan_id) {
282 			pr_err("CS_ETM: mismatch between CPU trace ID and HW_ID packet ID\n");
283 			return -EINVAL;
284 		}
285 
286 		/* Skip re-adding the same mappings if everything matched */
287 		return 0;
288 	}
289 
290 	/* Not one we've seen before, associate the traceID with the metadata pointer */
291 	inode->priv = cpu_metadata;
292 
293 	return 0;
294 }
295 
296 static struct cs_etm_queue *cs_etm__get_queue(struct cs_etm_auxtrace *etm, int cpu)
297 {
298 	if (etm->per_thread_decoding)
299 		return etm->queues.queue_array[0].priv;
300 
301 	if (cpu < 0 || cpu >= (int)etm->queues.nr_queues)
302 		return NULL;
303 
304 	return etm->queues.queue_array[cpu].priv;
305 }
306 
307 static int cs_etm__map_trace_id_v0(struct cs_etm_auxtrace *etm, u8 trace_chan_id,
308 				   u64 *cpu_metadata)
309 {
310 	struct cs_etm_queue *etmq;
311 
312 	/*
313 	 * If the queue is unformatted then only save one mapping in the
314 	 * queue associated with that CPU so only one decoder is made.
315 	 */
316 	etmq = cs_etm__get_queue(etm, cpu_metadata[CS_ETM_CPU]);
317 	if (!etmq)
318 		return -EINVAL;
319 
320 	if (etmq->format == UNFORMATTED)
321 		return cs_etm__insert_trace_id_node(etmq, trace_chan_id,
322 						    cpu_metadata);
323 
324 	/*
325 	 * Otherwise, version 0 trace IDs are global so save them into every
326 	 * queue.
327 	 */
328 	for (unsigned int i = 0; i < etm->queues.nr_queues; ++i) {
329 		int ret;
330 
331 		etmq = etm->queues.queue_array[i].priv;
332 		if (!etmq)
333 			continue;
334 
335 		ret = cs_etm__insert_trace_id_node(etmq, trace_chan_id,
336 						   cpu_metadata);
337 		if (ret)
338 			return ret;
339 	}
340 
341 	return 0;
342 }
343 
344 static int cs_etm__process_trace_id_v0(struct cs_etm_auxtrace *etm, int cpu,
345 				       u64 hw_id)
346 {
347 	int err;
348 	u64 *cpu_data;
349 	u8 trace_chan_id = FIELD_GET(CS_AUX_HW_ID_TRACE_ID_MASK, hw_id);
350 
351 	cpu_data = get_cpu_data(etm, cpu);
352 	if (cpu_data == NULL)
353 		return -EINVAL;
354 
355 	err = cs_etm__map_trace_id_v0(etm, trace_chan_id, cpu_data);
356 	if (err)
357 		return err;
358 
359 	/*
360 	 * if we are picking up the association from the packet, need to plug
361 	 * the correct trace ID into the metadata for setting up decoders later.
362 	 */
363 	return cs_etm__metadata_set_trace_id(trace_chan_id, cpu_data);
364 }
365 
366 static int cs_etm__process_trace_id_v0_1(struct cs_etm_auxtrace *etm, int cpu,
367 					 u64 hw_id)
368 {
369 	struct cs_etm_queue *etmq = cs_etm__get_queue(etm, cpu);
370 	int ret;
371 	u64 *cpu_data;
372 	u32 sink_id = FIELD_GET(CS_AUX_HW_ID_SINK_ID_MASK, hw_id);
373 	u8 trace_id = FIELD_GET(CS_AUX_HW_ID_TRACE_ID_MASK, hw_id);
374 
375 	if (!etmq)
376 		return -EINVAL;
377 
378 	/*
379 	 * Check sink id hasn't changed in per-cpu mode. In per-thread mode,
380 	 * let it pass for now until an actual overlapping trace ID is hit. In
381 	 * most cases IDs won't overlap even if the sink changes.
382 	 */
383 	if (!etmq->etm->per_thread_decoding && etmq->sink_id != SINK_UNSET &&
384 	    etmq->sink_id != sink_id) {
385 		pr_err("CS_ETM: mismatch between sink IDs\n");
386 		return -EINVAL;
387 	}
388 
389 	etmq->sink_id = sink_id;
390 
391 	/* Find which other queues use this sink and link their ID maps */
392 	for (unsigned int i = 0; i < etm->queues.nr_queues; ++i) {
393 		struct cs_etm_queue *other_etmq = etm->queues.queue_array[i].priv;
394 
395 		if (!other_etmq)
396 			continue;
397 
398 		/* Different sinks, skip */
399 		if (other_etmq->sink_id != etmq->sink_id)
400 			continue;
401 
402 		/* Already linked, skip */
403 		if (other_etmq->traceid_list == etmq->traceid_list)
404 			continue;
405 
406 		/* At the point of first linking, this one should be empty */
407 		if (!intlist__empty(etmq->traceid_list)) {
408 			pr_err("CS_ETM: Can't link populated trace ID lists\n");
409 			return -EINVAL;
410 		}
411 
412 		etmq->own_traceid_list = NULL;
413 		intlist__delete(etmq->traceid_list);
414 		etmq->traceid_list = other_etmq->traceid_list;
415 		break;
416 	}
417 
418 	cpu_data = get_cpu_data(etm, cpu);
419 	if (!cpu_data)
420 		return -EINVAL;
421 
422 	ret = cs_etm__insert_trace_id_node(etmq, trace_id, cpu_data);
423 	if (ret)
424 		return ret;
425 
426 	ret = cs_etm__metadata_set_trace_id(trace_id, cpu_data);
427 	if (ret)
428 		return ret;
429 
430 	return 0;
431 }
432 
433 static int cs_etm__metadata_get_trace_id(u8 *trace_chan_id, u64 *cpu_metadata)
434 {
435 	u64 cs_etm_magic = cpu_metadata[CS_ETM_MAGIC];
436 
437 	switch (cs_etm_magic) {
438 	case __perf_cs_etmv3_magic:
439 		*trace_chan_id = (u8)(cpu_metadata[CS_ETM_ETMTRACEIDR] &
440 				      CORESIGHT_TRACE_ID_VAL_MASK);
441 		break;
442 	case __perf_cs_etmv4_magic:
443 	case __perf_cs_ete_magic:
444 		*trace_chan_id = (u8)(cpu_metadata[CS_ETMV4_TRCTRACEIDR] &
445 				      CORESIGHT_TRACE_ID_VAL_MASK);
446 		break;
447 	default:
448 		return -EINVAL;
449 	}
450 	return 0;
451 }
452 
453 /*
454  * update metadata trace ID from the value found in the AUX_HW_INFO packet.
455  */
456 static int cs_etm__metadata_set_trace_id(u8 trace_chan_id, u64 *cpu_metadata)
457 {
458 	u64 cs_etm_magic = cpu_metadata[CS_ETM_MAGIC];
459 
460 	switch (cs_etm_magic) {
461 	case __perf_cs_etmv3_magic:
462 		 cpu_metadata[CS_ETM_ETMTRACEIDR] = trace_chan_id;
463 		break;
464 	case __perf_cs_etmv4_magic:
465 	case __perf_cs_ete_magic:
466 		cpu_metadata[CS_ETMV4_TRCTRACEIDR] = trace_chan_id;
467 		break;
468 
469 	default:
470 		return -EINVAL;
471 	}
472 	return 0;
473 }
474 
475 /*
476  * Get a metadata index for a specific cpu from an array.
477  *
478  */
479 static int get_cpu_data_idx(struct cs_etm_auxtrace *etm, int cpu)
480 {
481 	int i;
482 
483 	for (i = 0; i < etm->num_cpu; i++) {
484 		if (etm->metadata[i][CS_ETM_CPU] == (u64)cpu) {
485 			return i;
486 		}
487 	}
488 
489 	return -1;
490 }
491 
492 /*
493  * Get a metadata for a specific cpu from an array.
494  *
495  */
496 static u64 *get_cpu_data(struct cs_etm_auxtrace *etm, int cpu)
497 {
498 	int idx = get_cpu_data_idx(etm, cpu);
499 
500 	return (idx != -1) ? etm->metadata[idx] : NULL;
501 }
502 
503 /*
504  * Handle the PERF_RECORD_AUX_OUTPUT_HW_ID event.
505  *
506  * The payload associates the Trace ID and the CPU.
507  * The routine is tolerant of seeing multiple packets with the same association,
508  * but a CPU / Trace ID association changing during a session is an error.
509  */
510 static int cs_etm__process_aux_output_hw_id(struct perf_session *session,
511 					    union perf_event *event)
512 {
513 	struct cs_etm_auxtrace *etm;
514 	struct perf_sample sample;
515 	struct evsel *evsel;
516 	u64 hw_id;
517 	int cpu, version, err;
518 
519 	/* extract and parse the HW ID */
520 	hw_id = event->aux_output_hw_id.hw_id;
521 	version = FIELD_GET(CS_AUX_HW_ID_MAJOR_VERSION_MASK, hw_id);
522 
523 	/* check that we can handle this version */
524 	if (version > CS_AUX_HW_ID_MAJOR_VERSION) {
525 		pr_err("CS ETM Trace: PERF_RECORD_AUX_OUTPUT_HW_ID version %d not supported. Please update Perf.\n",
526 		       version);
527 		return -EINVAL;
528 	}
529 
530 	/* get access to the etm metadata */
531 	etm = container_of(session->auxtrace, struct cs_etm_auxtrace, auxtrace);
532 	if (!etm || !etm->metadata)
533 		return -EINVAL;
534 
535 	/* parse the sample to get the CPU */
536 	evsel = evlist__event2evsel(session->evlist, event);
537 	if (!evsel)
538 		return -EINVAL;
539 	perf_sample__init(&sample, /*all=*/false);
540 	err = evsel__parse_sample(evsel, event, &sample);
541 	if (err)
542 		goto out;
543 	cpu = sample.cpu;
544 	if (cpu == -1) {
545 		/* no CPU in the sample - possibly recorded with an old version of perf */
546 		pr_err("CS_ETM: no CPU AUX_OUTPUT_HW_ID sample. Use compatible perf to record.");
547 		err = -EINVAL;
548 		goto out;
549 	}
550 
551 	if (FIELD_GET(CS_AUX_HW_ID_MINOR_VERSION_MASK, hw_id) == 0) {
552 		err = cs_etm__process_trace_id_v0(etm, cpu, hw_id);
553 		goto out;
554 	}
555 
556 	err = cs_etm__process_trace_id_v0_1(etm, cpu, hw_id);
557 out:
558 	perf_sample__exit(&sample);
559 	return err;
560 }
561 
562 void cs_etm__etmq_set_traceid_queue_timestamp(struct cs_etm_queue *etmq,
563 					      u8 trace_chan_id)
564 {
565 	/*
566 	 * When a timestamp packet is encountered the backend code
567 	 * is stopped so that the front end has time to process packets
568 	 * that were accumulated in the traceID queue.  Since there can
569 	 * be more than one channel per cs_etm_queue, we need to specify
570 	 * what traceID queue needs servicing.
571 	 */
572 	etmq->pending_timestamp_chan_id = trace_chan_id;
573 }
574 
575 static u64 cs_etm__etmq_get_timestamp(struct cs_etm_queue *etmq,
576 				      u8 *trace_chan_id)
577 {
578 	struct cs_etm_packet_queue *packet_queue;
579 
580 	if (!etmq->pending_timestamp_chan_id)
581 		return 0;
582 
583 	if (trace_chan_id)
584 		*trace_chan_id = etmq->pending_timestamp_chan_id;
585 
586 	packet_queue = cs_etm__etmq_get_packet_queue(etmq,
587 						     etmq->pending_timestamp_chan_id);
588 	if (!packet_queue)
589 		return 0;
590 
591 	/* Acknowledge pending status */
592 	etmq->pending_timestamp_chan_id = 0;
593 
594 	/* See function cs_etm_decoder__do_{hard|soft}_timestamp() */
595 	return packet_queue->cs_timestamp;
596 }
597 
598 static void cs_etm__clear_packet_queue(struct cs_etm_packet_queue *queue)
599 {
600 	int i;
601 
602 	queue->head = 0;
603 	queue->tail = 0;
604 	queue->packet_count = 0;
605 	for (i = 0; i < CS_ETM_PACKET_MAX_BUFFER; i++) {
606 		queue->packet_buffer[i].isa = CS_ETM_ISA_UNKNOWN;
607 		queue->packet_buffer[i].start_addr = CS_ETM_INVAL_ADDR;
608 		queue->packet_buffer[i].end_addr = CS_ETM_INVAL_ADDR;
609 		queue->packet_buffer[i].instr_count = 0;
610 		queue->packet_buffer[i].last_instr_taken_branch = false;
611 		queue->packet_buffer[i].last_instr_size = 0;
612 		queue->packet_buffer[i].last_instr_type = 0;
613 		queue->packet_buffer[i].last_instr_subtype = 0;
614 		queue->packet_buffer[i].last_instr_cond = 0;
615 		queue->packet_buffer[i].flags = 0;
616 		queue->packet_buffer[i].exception_number = UINT32_MAX;
617 		queue->packet_buffer[i].trace_chan_id = UINT8_MAX;
618 		queue->packet_buffer[i].cpu = INT_MIN;
619 	}
620 }
621 
622 static void cs_etm__clear_all_packet_queues(struct cs_etm_queue *etmq)
623 {
624 	int idx;
625 	struct int_node *inode;
626 	struct cs_etm_traceid_queue *tidq;
627 	struct intlist *traceid_queues_list = etmq->traceid_queues_list;
628 
629 	intlist__for_each_entry(inode, traceid_queues_list) {
630 		idx = (int)(intptr_t)inode->priv;
631 		tidq = etmq->traceid_queues[idx];
632 		cs_etm__clear_packet_queue(&tidq->packet_queue);
633 	}
634 }
635 
636 static int cs_etm__init_traceid_queue(struct cs_etm_queue *etmq,
637 				      struct cs_etm_traceid_queue *tidq,
638 				      u8 trace_chan_id)
639 {
640 	int rc = -ENOMEM;
641 	struct auxtrace_queue *queue;
642 	struct cs_etm_auxtrace *etm = etmq->etm;
643 
644 	cs_etm__clear_packet_queue(&tidq->packet_queue);
645 
646 	queue = &etmq->etm->queues.queue_array[etmq->queue_nr];
647 	tidq->trace_chan_id = trace_chan_id;
648 	tidq->decode_el = ocsd_EL_unknown;
649 	tidq->frontend_thread = machine__findnew_thread(&etm->session->machines.host, -1,
650 					       queue->tid);
651 	tidq->decode_thread = machine__findnew_thread(&etm->session->machines.host, -1,
652 					       queue->tid);
653 	if (!tidq->frontend_thread || !tidq->decode_thread)
654 		goto out;
655 
656 	tidq->packet = zalloc(sizeof(struct cs_etm_packet));
657 	if (!tidq->packet)
658 		goto out;
659 
660 	tidq->prev_packet = zalloc(sizeof(struct cs_etm_packet));
661 	if (!tidq->prev_packet)
662 		goto out_free;
663 
664 	if (etm->use_thread_stack) {
665 		size_t sz = sizeof(struct branch_stack);
666 
667 		sz += etm->synth_opts.last_branch_sz *
668 		      sizeof(struct branch_entry);
669 		tidq->last_branch = zalloc(sz);
670 		if (!tidq->last_branch)
671 			goto out_free;
672 
673 		tidq->br_stack_sz = etm->synth_opts.last_branch_sz;
674 	}
675 
676 	if (etm->synth_opts.callchain) {
677 		/* Add 1 to callchain_sz for callchain context */
678 		tidq->callchain =
679 			zalloc(struct_size(tidq->callchain, ips,
680 					   etm->synth_opts.callchain_sz + 1));
681 		if (!tidq->callchain)
682 			goto out_free;
683 	}
684 
685 	tidq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
686 	if (!tidq->event_buf)
687 		goto out_free;
688 
689 	return 0;
690 
691 out_free:
692 	zfree(&tidq->callchain);
693 	zfree(&tidq->last_branch);
694 	zfree(&tidq->prev_packet);
695 	zfree(&tidq->packet);
696 out:
697 	thread__zput(tidq->frontend_thread);
698 	thread__zput(tidq->decode_thread);
699 	return rc;
700 }
701 
702 static struct cs_etm_traceid_queue
703 *cs_etm__etmq_get_traceid_queue(struct cs_etm_queue *etmq, u8 trace_chan_id)
704 {
705 	int idx;
706 	struct int_node *inode;
707 	struct intlist *traceid_queues_list;
708 	struct cs_etm_traceid_queue *tidq, **traceid_queues;
709 	struct cs_etm_auxtrace *etm = etmq->etm;
710 
711 	if (etm->per_thread_decoding)
712 		trace_chan_id = CS_ETM_PER_THREAD_TRACEID;
713 
714 	traceid_queues_list = etmq->traceid_queues_list;
715 
716 	/*
717 	 * Check if the traceid_queue exist for this traceID by looking
718 	 * in the queue list.
719 	 */
720 	inode = intlist__find(traceid_queues_list, trace_chan_id);
721 	if (inode) {
722 		idx = (int)(intptr_t)inode->priv;
723 		return etmq->traceid_queues[idx];
724 	}
725 
726 	/* We couldn't find a traceid_queue for this traceID, allocate one */
727 	tidq = malloc(sizeof(*tidq));
728 	if (!tidq)
729 		return NULL;
730 
731 	memset(tidq, 0, sizeof(*tidq));
732 
733 	/* Get a valid index for the new traceid_queue */
734 	idx = intlist__nr_entries(traceid_queues_list);
735 	/* Memory for the inode is free'ed in cs_etm_free_traceid_queues () */
736 	inode = intlist__findnew(traceid_queues_list, trace_chan_id);
737 	if (!inode)
738 		goto out_free;
739 
740 	/* Associate this traceID with this index */
741 	inode->priv = (void *)(intptr_t)idx;
742 
743 	if (cs_etm__init_traceid_queue(etmq, tidq, trace_chan_id))
744 		goto out_free;
745 
746 	/* Grow the traceid_queues array by one unit */
747 	traceid_queues = etmq->traceid_queues;
748 	traceid_queues = reallocarray(traceid_queues,
749 				      idx + 1,
750 				      sizeof(*traceid_queues));
751 
752 	/*
753 	 * On failure reallocarray() returns NULL and the original block of
754 	 * memory is left untouched.
755 	 */
756 	if (!traceid_queues)
757 		goto out_free;
758 
759 	traceid_queues[idx] = tidq;
760 	etmq->traceid_queues = traceid_queues;
761 
762 	return etmq->traceid_queues[idx];
763 
764 out_free:
765 	/*
766 	 * Function intlist__remove() removes the inode from the list
767 	 * and delete the memory associated to it.
768 	 */
769 	intlist__remove(traceid_queues_list, inode);
770 	free(tidq);
771 
772 	return NULL;
773 }
774 
775 struct cs_etm_packet_queue
776 *cs_etm__etmq_get_packet_queue(struct cs_etm_queue *etmq, u8 trace_chan_id)
777 {
778 	struct cs_etm_traceid_queue *tidq;
779 
780 	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
781 	if (tidq)
782 		return &tidq->packet_queue;
783 
784 	return NULL;
785 }
786 
787 static void cs_etm__packet_swap(struct cs_etm_auxtrace *etm,
788 				struct cs_etm_traceid_queue *tidq)
789 {
790 	struct cs_etm_packet *tmp;
791 
792 	if (etm->synth_opts.branches || etm->synth_opts.last_branch ||
793 	    etm->synth_opts.instructions) {
794 		/*
795 		 * Swap PACKET with PREV_PACKET: PACKET becomes PREV_PACKET for
796 		 * the next incoming packet.
797 		 */
798 		tmp = tidq->packet;
799 		tidq->packet = tidq->prev_packet;
800 		tidq->prev_packet = tmp;
801 	}
802 }
803 
804 static void cs_etm__packet_dump(const char *pkt_string, void *data)
805 {
806 	const char *color = PERF_COLOR_BLUE;
807 	int len = strlen(pkt_string);
808 	struct cs_etm_queue *etmq = data;
809 	char queue_nr[64];
810 
811 	if (verbose)
812 		snprintf(queue_nr, sizeof(queue_nr), "Qnr:%u; ", etmq->queue_nr);
813 	else
814 		queue_nr[0] = '\0';
815 
816 	if (len && (pkt_string[len-1] == '\n'))
817 		color_fprintf(stdout, color, "	%s%s", queue_nr, pkt_string);
818 	else
819 		color_fprintf(stdout, color, "	%s%s\n", queue_nr, pkt_string);
820 
821 	fflush(stdout);
822 }
823 
824 static void cs_etm__set_trace_param_etmv3(struct cs_etm_trace_params *t_params,
825 					  u64 *metadata, u32 etmidr)
826 {
827 	t_params->protocol = cs_etm__get_v7_protocol_version(etmidr);
828 	t_params->etmv3.reg_ctrl = metadata[CS_ETM_ETMCR];
829 	t_params->etmv3.reg_trc_id = metadata[CS_ETM_ETMTRACEIDR];
830 }
831 
832 static void cs_etm__set_trace_param_etmv4(struct cs_etm_trace_params *t_params,
833 					  u64 *metadata)
834 {
835 	t_params->protocol = CS_ETM_PROTO_ETMV4i;
836 	t_params->etmv4.reg_idr0 = metadata[CS_ETMV4_TRCIDR0];
837 	t_params->etmv4.reg_idr1 = metadata[CS_ETMV4_TRCIDR1];
838 	t_params->etmv4.reg_idr2 = metadata[CS_ETMV4_TRCIDR2];
839 	t_params->etmv4.reg_idr8 = metadata[CS_ETMV4_TRCIDR8];
840 	t_params->etmv4.reg_configr = metadata[CS_ETMV4_TRCCONFIGR];
841 	t_params->etmv4.reg_traceidr = metadata[CS_ETMV4_TRCTRACEIDR];
842 }
843 
844 static void cs_etm__set_trace_param_ete(struct cs_etm_trace_params *t_params,
845 					u64 *metadata)
846 {
847 	t_params->protocol = CS_ETM_PROTO_ETE;
848 	t_params->ete.reg_idr0 = metadata[CS_ETE_TRCIDR0];
849 	t_params->ete.reg_idr1 = metadata[CS_ETE_TRCIDR1];
850 	t_params->ete.reg_idr2 = metadata[CS_ETE_TRCIDR2];
851 	t_params->ete.reg_idr8 = metadata[CS_ETE_TRCIDR8];
852 	t_params->ete.reg_configr = metadata[CS_ETE_TRCCONFIGR];
853 	t_params->ete.reg_traceidr = metadata[CS_ETE_TRCTRACEIDR];
854 	t_params->ete.reg_devarch = metadata[CS_ETE_TRCDEVARCH];
855 }
856 
857 static int cs_etm__init_trace_params(struct cs_etm_trace_params *t_params,
858 				     struct cs_etm_queue *etmq)
859 {
860 	struct int_node *inode;
861 
862 	intlist__for_each_entry(inode, etmq->traceid_list) {
863 		u64 *metadata = inode->priv;
864 		u64 architecture = metadata[CS_ETM_MAGIC];
865 		u32 etmidr;
866 
867 		switch (architecture) {
868 		case __perf_cs_etmv3_magic:
869 			etmidr = metadata[CS_ETM_ETMIDR];
870 			cs_etm__set_trace_param_etmv3(t_params++, metadata, etmidr);
871 			break;
872 		case __perf_cs_etmv4_magic:
873 			cs_etm__set_trace_param_etmv4(t_params++, metadata);
874 			break;
875 		case __perf_cs_ete_magic:
876 			cs_etm__set_trace_param_ete(t_params++, metadata);
877 			break;
878 		default:
879 			return -EINVAL;
880 		}
881 	}
882 
883 	return 0;
884 }
885 
886 static int cs_etm__init_decoder_params(struct cs_etm_decoder_params *d_params,
887 				       struct cs_etm_queue *etmq,
888 				       enum cs_etm_decoder_operation mode)
889 {
890 	int ret = -EINVAL;
891 
892 	if (!(mode < CS_ETM_OPERATION_MAX))
893 		goto out;
894 
895 	d_params->packet_printer = cs_etm__packet_dump;
896 	d_params->operation = mode;
897 	d_params->data = etmq;
898 	d_params->formatted = etmq->format == FORMATTED;
899 	d_params->fsyncs = false;
900 	d_params->hsyncs = false;
901 	d_params->frame_aligned = true;
902 
903 	ret = 0;
904 out:
905 	return ret;
906 }
907 
908 static void cs_etm__dump_event(struct cs_etm_queue *etmq,
909 			       struct auxtrace_buffer *buffer)
910 {
911 	int ret;
912 	const char *color = PERF_COLOR_BLUE;
913 	size_t buffer_used = 0;
914 
915 	fprintf(stdout, "\n");
916 	color_fprintf(stdout, color,
917 		     ". ... CoreSight %s Trace data: size %#zx bytes\n",
918 		     cs_etm_decoder__get_name(etmq->decoder), buffer->size);
919 
920 	do {
921 		size_t consumed;
922 
923 		ret = cs_etm_decoder__process_data_block(
924 				etmq->decoder, buffer->offset,
925 				&((u8 *)buffer->data)[buffer_used],
926 				buffer->size - buffer_used, &consumed);
927 		if (ret)
928 			break;
929 
930 		buffer_used += consumed;
931 	} while (buffer_used < buffer->size);
932 
933 	cs_etm_decoder__reset(etmq->decoder);
934 }
935 
936 static int cs_etm__flush_events(struct perf_session *session,
937 				const struct perf_tool *tool)
938 {
939 	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
940 						   struct cs_etm_auxtrace,
941 						   auxtrace);
942 	if (dump_trace)
943 		return 0;
944 
945 	if (!tool->ordered_events)
946 		return -EINVAL;
947 
948 	if (etm->timeless_decoding) {
949 		/*
950 		 * Pass tid = -1 to process all queues. But likely they will have
951 		 * already been processed on PERF_RECORD_EXIT anyway.
952 		 */
953 		return cs_etm__process_timeless_queues(etm, -1);
954 	}
955 
956 	return cs_etm__process_timestamped_queues(etm);
957 }
958 
959 static void cs_etm__free_traceid_queues(struct cs_etm_queue *etmq)
960 {
961 	int idx;
962 	uintptr_t priv;
963 	struct int_node *inode, *tmp;
964 	struct cs_etm_traceid_queue *tidq;
965 	struct intlist *traceid_queues_list = etmq->traceid_queues_list;
966 
967 	intlist__for_each_entry_safe(inode, tmp, traceid_queues_list) {
968 		priv = (uintptr_t)inode->priv;
969 		idx = priv;
970 
971 		/* Free this traceid_queue from the array */
972 		tidq = etmq->traceid_queues[idx];
973 		thread__zput(tidq->frontend_thread);
974 		thread__zput(tidq->decode_thread);
975 		zfree(&tidq->event_buf);
976 		zfree(&tidq->callchain);
977 		zfree(&tidq->last_branch);
978 		zfree(&tidq->prev_packet);
979 		zfree(&tidq->packet);
980 		zfree(&tidq);
981 
982 		/*
983 		 * Function intlist__remove() removes the inode from the list
984 		 * and delete the memory associated to it.
985 		 */
986 		intlist__remove(traceid_queues_list, inode);
987 	}
988 
989 	/* Then the RB tree itself */
990 	intlist__delete(traceid_queues_list);
991 	etmq->traceid_queues_list = NULL;
992 
993 	/* finally free the traceid_queues array */
994 	zfree(&etmq->traceid_queues);
995 }
996 
997 static void cs_etm__free_queue(void *priv)
998 {
999 	struct int_node *inode, *tmp;
1000 	struct cs_etm_queue *etmq = priv;
1001 
1002 	if (!etmq)
1003 		return;
1004 
1005 	cs_etm_decoder__free(etmq->decoder);
1006 	cs_etm__free_traceid_queues(etmq);
1007 
1008 	if (etmq->own_traceid_list) {
1009 		/* First remove all traceID/metadata nodes for the RB tree */
1010 		intlist__for_each_entry_safe(inode, tmp, etmq->own_traceid_list)
1011 			intlist__remove(etmq->own_traceid_list, inode);
1012 
1013 		/* Then the RB tree itself */
1014 		intlist__delete(etmq->own_traceid_list);
1015 	}
1016 
1017 	free(etmq);
1018 }
1019 
1020 static void cs_etm__free_events(struct perf_session *session)
1021 {
1022 	unsigned int i;
1023 	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
1024 						   struct cs_etm_auxtrace,
1025 						   auxtrace);
1026 	struct auxtrace_queues *queues = &aux->queues;
1027 
1028 	for (i = 0; i < queues->nr_queues; i++) {
1029 		cs_etm__free_queue(queues->queue_array[i].priv);
1030 		queues->queue_array[i].priv = NULL;
1031 	}
1032 
1033 	auxtrace_queues__free(queues);
1034 }
1035 
1036 static void cs_etm__free(struct perf_session *session)
1037 {
1038 	int i;
1039 	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
1040 						   struct cs_etm_auxtrace,
1041 						   auxtrace);
1042 	cs_etm__free_events(session);
1043 	session->auxtrace = NULL;
1044 
1045 	for (i = 0; i < aux->num_cpu; i++)
1046 		zfree(&aux->metadata[i]);
1047 
1048 	zfree(&aux->metadata);
1049 	zfree(&aux);
1050 }
1051 
1052 static bool cs_etm__evsel_is_auxtrace(struct perf_session *session,
1053 				      struct evsel *evsel)
1054 {
1055 	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
1056 						   struct cs_etm_auxtrace,
1057 						   auxtrace);
1058 
1059 	return evsel->core.attr.type == aux->pmu_type;
1060 }
1061 
1062 static struct machine *cs_etm__get_machine(struct cs_etm_queue *etmq,
1063 					   ocsd_ex_level el)
1064 {
1065 	enum cs_etm_pid_fmt pid_fmt = cs_etm__get_pid_fmt(etmq);
1066 
1067 	/*
1068 	 * For any virtualisation based on nVHE (e.g. pKVM), or host kernels
1069 	 * running at EL1 assume everything is the host.
1070 	 */
1071 	if (pid_fmt == CS_ETM_PIDFMT_CTXTID)
1072 		return &etmq->etm->session->machines.host;
1073 
1074 	/*
1075 	 * Not perfect, but otherwise assume anything in EL1 is the default
1076 	 * guest, and everything else is the host. Distinguishing between guest
1077 	 * and host userspaces isn't currently supported either. Neither is
1078 	 * multiple guest support. All this does is reduce the likeliness of
1079 	 * decode errors where we look into the host kernel maps when it should
1080 	 * have been the guest maps.
1081 	 */
1082 	switch (el) {
1083 	case ocsd_EL1:
1084 		return machines__find_guest(&etmq->etm->session->machines,
1085 					    DEFAULT_GUEST_KERNEL_ID);
1086 	case ocsd_EL3:
1087 	case ocsd_EL2:
1088 	case ocsd_EL0:
1089 	case ocsd_EL_unknown:
1090 	default:
1091 		return &etmq->etm->session->machines.host;
1092 	}
1093 }
1094 
1095 static u8 cs_etm__cpu_mode(struct cs_etm_queue *etmq, u64 address,
1096 			   ocsd_ex_level el)
1097 {
1098 	struct machine *machine = cs_etm__get_machine(etmq, el);
1099 
1100 	if (address >= machine__kernel_start(machine)) {
1101 		if (machine__is_host(machine))
1102 			return PERF_RECORD_MISC_KERNEL;
1103 		else
1104 			return PERF_RECORD_MISC_GUEST_KERNEL;
1105 	} else {
1106 		if (machine__is_host(machine))
1107 			return PERF_RECORD_MISC_USER;
1108 		else {
1109 			/*
1110 			 * Can't really happen at the moment because
1111 			 * cs_etm__get_machine() will always return
1112 			 * machines.host for any non EL1 trace.
1113 			 */
1114 			return PERF_RECORD_MISC_GUEST_USER;
1115 		}
1116 	}
1117 }
1118 
1119 static u32 __cs_etm__mem_access(struct cs_etm_queue *etmq,
1120 				u64 address, size_t size, u8 *buffer,
1121 				const ocsd_mem_space_acc_t mem_space,
1122 				ocsd_ex_level el, struct thread *thread)
1123 {
1124 	u8  cpumode;
1125 	u64 offset;
1126 	int len;
1127 	struct addr_location al;
1128 	struct dso *dso;
1129 	int ret = 0;
1130 
1131 	if (!etmq)
1132 		return 0;
1133 
1134 	addr_location__init(&al);
1135 
1136 	/*
1137 	 * We track EL for the frontend and the backend when receiving context
1138 	 * and range packets. OpenCSD doesn't distinguish between EL0 and EL1
1139 	 * for this mem access callback so we had to do the extra tracking. Skip
1140 	 * validation if it's any of the 'any' values.
1141 	 */
1142 	if (!(mem_space == OCSD_MEM_SPACE_ANY ||
1143 	      mem_space == OCSD_MEM_SPACE_N || mem_space == OCSD_MEM_SPACE_S)) {
1144 		if (mem_space & OCSD_MEM_SPACE_EL1N) {
1145 			/* Includes both non secure EL1 and EL0 */
1146 			assert(el == ocsd_EL1 || el == ocsd_EL0);
1147 		} else if (mem_space & OCSD_MEM_SPACE_EL2)
1148 			assert(el == ocsd_EL2);
1149 		else if (mem_space & OCSD_MEM_SPACE_EL3)
1150 			assert(el == ocsd_EL3);
1151 	}
1152 
1153 	cpumode = cs_etm__cpu_mode(etmq, address, el);
1154 
1155 	if (!thread__find_map(thread, cpumode, address, &al))
1156 		goto out;
1157 
1158 	dso = map__dso(al.map);
1159 	if (!dso)
1160 		goto out;
1161 
1162 	if (dso__data(dso)->status == DSO_DATA_STATUS_ERROR &&
1163 	    dso__data_status_seen(dso, DSO_DATA_STATUS_SEEN_ITRACE))
1164 		goto out;
1165 
1166 	offset = map__map_ip(al.map, address);
1167 
1168 	map__load(al.map);
1169 
1170 	len = dso__data_read_offset(dso, maps__machine(thread__maps(thread)),
1171 				    offset, buffer, size);
1172 
1173 	if (len <= 0) {
1174 		ui__warning_once("CS ETM Trace: Missing DSO. Use 'perf archive' or debuginfod to export data from the traced system.\n"
1175 				 "              Enable CONFIG_PROC_KCORE or use option '-k /path/to/vmlinux' for kernel symbols.\n");
1176 		if (!dso__auxtrace_warned(dso)) {
1177 			pr_err("CS ETM Trace: Debug data not found for address %#"PRIx64" in %s\n",
1178 				address,
1179 				dso__long_name(dso) ? dso__long_name(dso) : "Unknown");
1180 			dso__set_auxtrace_warned(dso);
1181 		}
1182 		goto out;
1183 	}
1184 	ret = len;
1185 out:
1186 	addr_location__exit(&al);
1187 	return ret;
1188 }
1189 
1190 static u32 cs_etm__frontend_mem_access(struct cs_etm_queue *etmq,
1191 				       struct cs_etm_traceid_queue *tidq,
1192 				       struct cs_etm_packet *packet,
1193 				       u64 address, size_t size, u8 *buffer)
1194 {
1195 	return __cs_etm__mem_access(etmq, address, size, buffer, 0, packet->el,
1196 				    tidq->frontend_thread);
1197 }
1198 
1199 static u32 cs_etm__decoder_mem_access(struct cs_etm_queue *etmq, u8 trace_chan_id,
1200 				      u64 address, size_t size, u8 *buffer,
1201 				      const ocsd_mem_space_acc_t mem_space)
1202 {
1203 	struct cs_etm_traceid_queue *tidq;
1204 
1205 	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
1206 	if (!tidq)
1207 		return 0;
1208 
1209 	return __cs_etm__mem_access(etmq, address, size, buffer,
1210 				    mem_space, tidq->decode_el,
1211 				    tidq->decode_thread);
1212 }
1213 
1214 static struct cs_etm_queue *cs_etm__alloc_queue(void)
1215 {
1216 	struct cs_etm_queue *etmq = zalloc(sizeof(*etmq));
1217 	if (!etmq)
1218 		return NULL;
1219 
1220 	etmq->traceid_queues_list = intlist__new(NULL);
1221 	if (!etmq->traceid_queues_list)
1222 		goto out_free;
1223 
1224 	/*
1225 	 * Create an RB tree for traceID-metadata tuple.  Since the conversion
1226 	 * has to be made for each packet that gets decoded, optimizing access
1227 	 * in anything other than a sequential array is worth doing.
1228 	 */
1229 	etmq->traceid_list = etmq->own_traceid_list = intlist__new(NULL);
1230 	if (!etmq->traceid_list)
1231 		goto out_free;
1232 
1233 	return etmq;
1234 
1235 out_free:
1236 	intlist__delete(etmq->traceid_queues_list);
1237 	free(etmq);
1238 
1239 	return NULL;
1240 }
1241 
1242 static int cs_etm__setup_queue(struct cs_etm_auxtrace *etm,
1243 			       struct auxtrace_queue *queue,
1244 			       unsigned int queue_nr)
1245 {
1246 	struct cs_etm_queue *etmq = queue->priv;
1247 
1248 	if (etmq)
1249 		return 0;
1250 
1251 	etmq = cs_etm__alloc_queue();
1252 
1253 	if (!etmq)
1254 		return -ENOMEM;
1255 
1256 	queue->priv = etmq;
1257 	etmq->etm = etm;
1258 	etmq->queue_nr = queue_nr;
1259 	queue->cpu = queue_nr; /* Placeholder, may be reset to -1 in per-thread mode */
1260 	etmq->offset = 0;
1261 	etmq->sink_id = SINK_UNSET;
1262 
1263 	return 0;
1264 }
1265 
1266 static int cs_etm__queue_first_cs_timestamp(struct cs_etm_auxtrace *etm,
1267 					    struct cs_etm_queue *etmq,
1268 					    unsigned int queue_nr)
1269 {
1270 	int ret = 0;
1271 	unsigned int cs_queue_nr;
1272 	u8 trace_chan_id;
1273 	u64 cs_timestamp;
1274 
1275 	/*
1276 	 * We are under a CPU-wide trace scenario.  As such we need to know
1277 	 * when the code that generated the traces started to execute so that
1278 	 * it can be correlated with execution on other CPUs.  So we get a
1279 	 * handle on the beginning of traces and decode until we find a
1280 	 * timestamp.  The timestamp is then added to the auxtrace min heap
1281 	 * in order to know what nibble (of all the etmqs) to decode first.
1282 	 */
1283 	while (1) {
1284 		/*
1285 		 * Fetch an aux_buffer from this etmq.  Bail if no more
1286 		 * blocks or an error has been encountered.
1287 		 */
1288 		ret = cs_etm__get_data_block(etmq);
1289 		if (ret <= 0)
1290 			goto out;
1291 
1292 		/*
1293 		 * Run decoder on the trace block.  The decoder will stop when
1294 		 * encountering a CS timestamp, a full packet queue or the end of
1295 		 * trace for that block.
1296 		 */
1297 		ret = cs_etm__decode_data_block(etmq);
1298 		if (ret)
1299 			goto out;
1300 
1301 		/*
1302 		 * Function cs_etm_decoder__do_{hard|soft}_timestamp() does all
1303 		 * the timestamp calculation for us.
1304 		 */
1305 		cs_timestamp = cs_etm__etmq_get_timestamp(etmq, &trace_chan_id);
1306 
1307 		/* We found a timestamp, no need to continue. */
1308 		if (cs_timestamp)
1309 			break;
1310 
1311 		/*
1312 		 * We didn't find a timestamp so empty all the traceid packet
1313 		 * queues before looking for another timestamp packet, either
1314 		 * in the current data block or a new one.  Packets that were
1315 		 * just decoded are useless since no timestamp has been
1316 		 * associated with them.  As such simply discard them.
1317 		 */
1318 		cs_etm__clear_all_packet_queues(etmq);
1319 	}
1320 
1321 	/*
1322 	 * We have a timestamp.  Add it to the min heap to reflect when
1323 	 * instructions conveyed by the range packets of this traceID queue
1324 	 * started to execute.  Once the same has been done for all the traceID
1325 	 * queues of each etmq, redenring and decoding can start in
1326 	 * chronological order.
1327 	 *
1328 	 * Note that packets decoded above are still in the traceID's packet
1329 	 * queue and will be processed in cs_etm__process_timestamped_queues().
1330 	 */
1331 	cs_queue_nr = TO_CS_QUEUE_NR(queue_nr, trace_chan_id);
1332 	ret = auxtrace_heap__add(&etm->heap, cs_queue_nr, cs_timestamp);
1333 out:
1334 	return ret;
1335 }
1336 
1337 static inline int cs_etm__t32_instr_size(struct cs_etm_queue *etmq,
1338 					 struct cs_etm_traceid_queue *tidq,
1339 					 struct cs_etm_packet *packet, u64 addr)
1340 {
1341 	u8 instrBytes[2];
1342 
1343 	cs_etm__frontend_mem_access(etmq, tidq, packet, addr,
1344 				    ARRAY_SIZE(instrBytes), instrBytes);
1345 	/*
1346 	 * T32 instruction size is indicated by bits[15:11] of the first
1347 	 * 16-bit word of the instruction: 0b11101, 0b11110 and 0b11111
1348 	 * denote a 32-bit instruction.
1349 	 */
1350 	return ((instrBytes[1] & 0xF8) >= 0xE8) ? 4 : 2;
1351 }
1352 
1353 static inline int cs_etm__instr_size(struct cs_etm_queue *etmq,
1354 				     struct cs_etm_traceid_queue *tidq,
1355 				     struct cs_etm_packet *packet,
1356 				     u64 addr)
1357 {
1358 	if (packet->isa == CS_ETM_ISA_T32)
1359 		return cs_etm__t32_instr_size(etmq, tidq, packet, addr);
1360 
1361 	/* Otherwise, 4-byte instruction size for A32/A64 */
1362 	return 4;
1363 }
1364 
1365 static inline u64 cs_etm__first_executed_instr(struct cs_etm_packet *packet)
1366 {
1367 	/*
1368 	 * Return 0 for packets that have no addresses so that CS_ETM_INVAL_ADDR doesn't
1369 	 * appear in samples.
1370 	 */
1371 	if (packet->sample_type == CS_ETM_DISCONTINUITY ||
1372 	    packet->sample_type == CS_ETM_EXCEPTION)
1373 		return 0;
1374 
1375 	return packet->start_addr;
1376 }
1377 
1378 static inline
1379 u64 cs_etm__last_executed_instr(const struct cs_etm_packet *packet)
1380 {
1381 	/* Returns 0 for the CS_ETM_DISCONTINUITY packet */
1382 	if (packet->sample_type == CS_ETM_DISCONTINUITY)
1383 		return 0;
1384 
1385 	return packet->end_addr - packet->last_instr_size;
1386 }
1387 
1388 static inline u64 cs_etm__instr_addr(struct cs_etm_queue *etmq,
1389 				     struct cs_etm_traceid_queue *tidq,
1390 				     struct cs_etm_packet *packet,
1391 				     u64 offset)
1392 {
1393 	u64 addr = packet->start_addr;
1394 
1395 	/* 4-byte instruction size for A32/A64 */
1396 	if (packet->isa == CS_ETM_ISA_A64 || packet->isa == CS_ETM_ISA_A32)
1397 		return addr + offset * 4;
1398 
1399 	while (offset) {
1400 		addr += cs_etm__instr_size(etmq, tidq, packet, addr);
1401 		offset--;
1402 	}
1403 	return addr;
1404 }
1405 
1406 static int cs_etm__inject_event(struct cs_etm_auxtrace *etm, union perf_event *event,
1407 			       struct perf_sample *sample, u64 type)
1408 {
1409 	struct evsel *evsel = sample->evsel;
1410 	u64 branch_sample_type = 0;
1411 	size_t sz;
1412 
1413 	if (!evsel && etm->session && etm->session->evlist)
1414 		evsel = evlist__id2evsel(etm->session->evlist, sample->id);
1415 
1416 	if (evsel)
1417 		branch_sample_type = evsel->core.attr.branch_sample_type;
1418 
1419 	sz = perf_event__sample_event_size(sample, type, /*read_format=*/0,
1420 					   branch_sample_type);
1421 	if (sz >= PERF_SAMPLE_MAX_SIZE) {
1422 		pr_err("Sample size %zu exceeds max size %d\n", sz, PERF_SAMPLE_MAX_SIZE);
1423 		return -EFAULT;
1424 	}
1425 	event->header.size = sz;
1426 
1427 	return perf_event__synthesize_sample(event, type, /*read_format=*/0,
1428 					     branch_sample_type, sample);
1429 }
1430 
1431 
1432 static int
1433 cs_etm__get_trace(struct cs_etm_queue *etmq)
1434 {
1435 	struct auxtrace_buffer *aux_buffer = etmq->buffer;
1436 	struct auxtrace_buffer *old_buffer = aux_buffer;
1437 	struct auxtrace_queue *queue;
1438 
1439 	queue = &etmq->etm->queues.queue_array[etmq->queue_nr];
1440 
1441 	aux_buffer = auxtrace_buffer__next(queue, aux_buffer);
1442 
1443 	/* If no more data, drop the previous auxtrace_buffer and return */
1444 	if (!aux_buffer) {
1445 		if (old_buffer)
1446 			auxtrace_buffer__drop_data(old_buffer);
1447 		etmq->buf_len = 0;
1448 		return 0;
1449 	}
1450 
1451 	etmq->buffer = aux_buffer;
1452 
1453 	/* If the aux_buffer doesn't have data associated, try to load it */
1454 	if (!aux_buffer->data) {
1455 		/* get the file desc associated with the perf data file */
1456 		int fd = perf_data__fd(etmq->etm->session->data);
1457 
1458 		aux_buffer->data = auxtrace_buffer__get_data(aux_buffer, fd);
1459 		if (!aux_buffer->data)
1460 			return -ENOMEM;
1461 	}
1462 
1463 	/* If valid, drop the previous buffer */
1464 	if (old_buffer)
1465 		auxtrace_buffer__drop_data(old_buffer);
1466 
1467 	etmq->buf_used = 0;
1468 	etmq->buf_len = aux_buffer->size;
1469 	etmq->buf = aux_buffer->data;
1470 
1471 	return etmq->buf_len;
1472 }
1473 
1474 /*
1475  * Convert a raw thread number to a thread struct and assign it to **thread.
1476  */
1477 static int cs_etm__etmq_update_thread(struct cs_etm_queue *etmq,
1478 				      ocsd_ex_level el, pid_t tid,
1479 				      struct thread **thread)
1480 {
1481 	struct machine *machine = cs_etm__get_machine(etmq, el);
1482 
1483 	if (!machine || !*thread)
1484 		return -EINVAL;
1485 
1486 	if (tid != -1) {
1487 		thread__zput(*thread);
1488 		*thread = machine__find_thread(machine, -1, tid);
1489 	}
1490 
1491 	/* Couldn't find a known thread */
1492 	if (!*thread)
1493 		*thread = machine__idle_thread(machine);
1494 
1495 	return 0;
1496 }
1497 
1498 /*
1499  * Set the thread and EL of the decode context which is ahead in time of the
1500  * frontend context.
1501  */
1502 int cs_etm__etmq_update_decode_context(struct cs_etm_queue *etmq,
1503 				       u8 trace_chan_id,
1504 				       ocsd_ex_level el, pid_t tid)
1505 {
1506 	struct cs_etm_traceid_queue *tidq;
1507 	int ret;
1508 
1509 	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
1510 	if (!tidq)
1511 		return -EINVAL;
1512 
1513 	ret = cs_etm__etmq_update_thread(etmq, el, tid,
1514 					 &tidq->decode_thread);
1515 	if (ret)
1516 		return ret;
1517 
1518 	tidq->decode_el = el;
1519 	return 0;
1520 }
1521 
1522 bool cs_etm__etmq_is_timeless(struct cs_etm_queue *etmq)
1523 {
1524 	return !!etmq->etm->timeless_decoding;
1525 }
1526 
1527 static void cs_etm__copy_insn(struct cs_etm_queue *etmq,
1528 			      struct cs_etm_traceid_queue *tidq,
1529 			      struct cs_etm_packet *packet,
1530 			      struct perf_sample *sample)
1531 {
1532 	/*
1533 	 * It's pointless to read instructions for the CS_ETM_DISCONTINUITY
1534 	 * packet, so directly bail out with 'insn_len' = 0.
1535 	 */
1536 	if (packet->sample_type == CS_ETM_DISCONTINUITY) {
1537 		sample->insn_len = 0;
1538 		return;
1539 	}
1540 
1541 	sample->insn_len = cs_etm__instr_size(etmq, tidq, packet, sample->ip);
1542 
1543 	cs_etm__frontend_mem_access(etmq, tidq, packet, sample->ip,
1544 				    sample->insn_len, (void *)sample->insn);
1545 }
1546 
1547 u64 cs_etm__convert_sample_time(struct cs_etm_queue *etmq, u64 cs_timestamp)
1548 {
1549 	struct cs_etm_auxtrace *etm = etmq->etm;
1550 
1551 	if (etm->has_virtual_ts)
1552 		return tsc_to_perf_time(cs_timestamp, &etm->tc);
1553 	else
1554 		return cs_timestamp;
1555 }
1556 
1557 static inline u64 cs_etm__resolve_sample_time(struct cs_etm_queue *etmq,
1558 					       struct cs_etm_traceid_queue *tidq)
1559 {
1560 	struct cs_etm_auxtrace *etm = etmq->etm;
1561 	struct cs_etm_packet_queue *packet_queue = &tidq->packet_queue;
1562 
1563 	if (!etm->timeless_decoding && etm->has_virtual_ts)
1564 		return packet_queue->cs_timestamp;
1565 	else
1566 		return etm->latest_kernel_timestamp;
1567 }
1568 
1569 static bool cs_etm__packet_has_taken_branch(struct cs_etm_packet *packet)
1570 {
1571 	if (packet->sample_type == CS_ETM_RANGE &&
1572 	    packet->last_instr_taken_branch)
1573 		return true;
1574 
1575 	return false;
1576 }
1577 
1578 static void cs_etm__add_stack_event(struct cs_etm_queue *etmq,
1579 				    struct cs_etm_traceid_queue *tidq)
1580 {
1581 	struct cs_etm_auxtrace *etm = etmq->etm;
1582 	u64 from, to;
1583 	int size;
1584 
1585 	if (!etm->synth_opts.branches && !etm->synth_opts.instructions)
1586 		return;
1587 
1588 	if (!cs_etm__packet_has_taken_branch(tidq->prev_packet))
1589 		return;
1590 
1591 	if (etmq->etm->use_thread_stack) {
1592 		from = cs_etm__last_executed_instr(tidq->prev_packet);
1593 		to = cs_etm__first_executed_instr(tidq->packet);
1594 
1595 		size = cs_etm__instr_size(etmq, tidq, tidq->prev_packet, from);
1596 
1597 		/* Enable callchain so thread stack entry can be allocated */
1598 		thread_stack__event(tidq->frontend_thread, tidq->prev_packet->cpu,
1599 				    tidq->prev_packet->flags, from, to, size,
1600 				    etmq->buffer->buffer_nr + 1,
1601 				    etmq->etm->use_callchain,
1602 				    tidq->br_stack_sz, 0);
1603 	} else {
1604 		thread_stack__set_trace_nr(tidq->frontend_thread,
1605 					   tidq->prev_packet->cpu,
1606 					   etmq->buffer->buffer_nr + 1);
1607 	}
1608 }
1609 
1610 static void cs_etm__sample_branch_stack(struct cs_etm_auxtrace *etm,
1611 					struct cs_etm_traceid_queue *tidq,
1612 					struct perf_sample *sample)
1613 {
1614 	if (etm->synth_opts.last_branch) {
1615 		thread_stack__br_sample(tidq->frontend_thread, tidq->packet->cpu,
1616 					tidq->last_branch, tidq->br_stack_sz);
1617 		sample->branch_stack = tidq->last_branch;
1618 	}
1619 
1620 	if (etm->synth_opts.callchain) {
1621 		if (tidq->kernel_start)
1622 			thread_stack__sample(tidq->frontend_thread,
1623 					     tidq->packet->cpu,
1624 					     tidq->callchain,
1625 					     etm->synth_opts.callchain_sz + 1,
1626 					     sample->ip, tidq->kernel_start);
1627 		else
1628 			/*
1629 			 * Clear the callchain when the kernel start address is
1630 			 * not available yet. The empty callchain can then be
1631 			 * consumed by cs_etm__inject_event().
1632 			 */
1633 			memset(tidq->callchain, 0,
1634 			       struct_size(tidq->callchain, ips,
1635 					   etm->synth_opts.callchain_sz + 1));
1636 
1637 		sample->callchain = tidq->callchain;
1638 	}
1639 }
1640 
1641 static int cs_etm__synth_instruction_sample(struct cs_etm_queue *etmq,
1642 					    struct cs_etm_traceid_queue *tidq,
1643 					    struct cs_etm_packet *packet,
1644 					    u64 addr, u64 period)
1645 {
1646 	int ret = 0;
1647 	struct cs_etm_auxtrace *etm = etmq->etm;
1648 	union perf_event *event = tidq->event_buf;
1649 	struct perf_sample sample;
1650 
1651 	perf_sample__init(&sample, /*all=*/true);
1652 	event->sample.header.type = PERF_RECORD_SAMPLE;
1653 	event->sample.header.misc = cs_etm__cpu_mode(etmq, addr, packet->el);
1654 	event->sample.header.size = sizeof(struct perf_event_header);
1655 
1656 	/* Set time field based on etm auxtrace config. */
1657 	sample.time = cs_etm__resolve_sample_time(etmq, tidq);
1658 
1659 	sample.ip = addr;
1660 	sample.pid = thread__pid(tidq->frontend_thread);
1661 	sample.tid = thread__tid(tidq->frontend_thread);
1662 	sample.id = etmq->etm->instructions_id;
1663 	sample.stream_id = etmq->etm->instructions_id;
1664 	sample.period = period;
1665 	sample.cpu = packet->cpu;
1666 	sample.flags = tidq->prev_packet->flags;
1667 	sample.cpumode = event->sample.header.misc;
1668 
1669 	cs_etm__copy_insn(etmq, tidq, packet, &sample);
1670 	cs_etm__sample_branch_stack(etm, tidq, &sample);
1671 
1672 	if (etm->synth_opts.inject) {
1673 		ret = cs_etm__inject_event(etm, event, &sample,
1674 					   etm->instructions_sample_type);
1675 		if (ret)
1676 			return ret;
1677 	}
1678 
1679 	ret = perf_session__deliver_synth_event(etm->session, event, &sample);
1680 
1681 	if (ret)
1682 		pr_err(
1683 			"CS ETM Trace: failed to deliver instruction event, error %d\n",
1684 			ret);
1685 
1686 	perf_sample__exit(&sample);
1687 	return ret;
1688 }
1689 
1690 /*
1691  * The cs etm packet encodes an instruction range between a branch target
1692  * and the next taken branch. Generate sample accordingly.
1693  */
1694 static int cs_etm__synth_branch_sample(struct cs_etm_queue *etmq,
1695 				       struct cs_etm_traceid_queue *tidq)
1696 {
1697 	int ret = 0;
1698 	struct cs_etm_auxtrace *etm = etmq->etm;
1699 	struct perf_sample sample;
1700 	union perf_event *event = tidq->event_buf;
1701 
1702 	struct dummy_branch_stack {
1703 		u64			nr;
1704 		u64			hw_idx;
1705 		struct branch_entry	entries;
1706 	} dummy_bs;
1707 	u64 ip;
1708 
1709 	if (etm->branches_filter &&
1710 		!(etm->branches_filter & tidq->prev_packet->flags))
1711 		return 0;
1712 
1713 	perf_sample__init(&sample, /*all=*/true);
1714 	ip = cs_etm__last_executed_instr(tidq->prev_packet);
1715 
1716 	event->sample.header.type = PERF_RECORD_SAMPLE;
1717 	event->sample.header.misc = cs_etm__cpu_mode(etmq, ip,
1718 						     tidq->prev_packet->el);
1719 	event->sample.header.size = sizeof(struct perf_event_header);
1720 
1721 	/* Set time field based on etm auxtrace config. */
1722 	sample.time = cs_etm__resolve_sample_time(etmq, tidq);
1723 
1724 	sample.ip = ip;
1725 	sample.pid = thread__pid(tidq->frontend_thread);
1726 	sample.tid = thread__tid(tidq->frontend_thread);
1727 	sample.addr = cs_etm__first_executed_instr(tidq->packet);
1728 	sample.id = etmq->etm->branches_id;
1729 	sample.stream_id = etmq->etm->branches_id;
1730 	sample.period = 1;
1731 	sample.cpu = tidq->packet->cpu;
1732 	sample.flags = tidq->prev_packet->flags;
1733 	sample.cpumode = event->sample.header.misc;
1734 
1735 	cs_etm__copy_insn(etmq, tidq, tidq->prev_packet, &sample);
1736 
1737 	/*
1738 	 * perf report cannot handle events without a branch stack
1739 	 */
1740 	if (etm->synth_opts.last_branch) {
1741 		dummy_bs = (struct dummy_branch_stack){
1742 			.nr = 1,
1743 			.hw_idx = -1ULL,
1744 			.entries = {
1745 				.from = sample.ip,
1746 				.to = sample.addr,
1747 			},
1748 		};
1749 		sample.branch_stack = (struct branch_stack *)&dummy_bs;
1750 	}
1751 
1752 	if (etm->synth_opts.inject) {
1753 		ret = cs_etm__inject_event(etm, event, &sample,
1754 					   etm->branches_sample_type);
1755 		if (ret)
1756 			return ret;
1757 	}
1758 
1759 	ret = perf_session__deliver_synth_event(etm->session, event, &sample);
1760 
1761 	if (ret)
1762 		pr_err(
1763 		"CS ETM Trace: failed to deliver instruction event, error %d\n",
1764 		ret);
1765 
1766 	perf_sample__exit(&sample);
1767 	return ret;
1768 }
1769 
1770 static int cs_etm__synth_events(struct cs_etm_auxtrace *etm,
1771 				struct perf_session *session)
1772 {
1773 	struct evlist *evlist = session->evlist;
1774 	struct evsel *evsel;
1775 	struct perf_event_attr attr;
1776 	bool found = false;
1777 	u64 id;
1778 	int err;
1779 
1780 	evlist__for_each_entry(evlist, evsel) {
1781 		if (evsel->core.attr.type == etm->pmu_type) {
1782 			found = true;
1783 			break;
1784 		}
1785 	}
1786 
1787 	if (!found) {
1788 		pr_debug("No selected events with CoreSight Trace data\n");
1789 		return 0;
1790 	}
1791 
1792 	memset(&attr, 0, sizeof(struct perf_event_attr));
1793 	attr.size = sizeof(struct perf_event_attr);
1794 	attr.type = PERF_TYPE_HARDWARE;
1795 	attr.sample_type = evsel->core.attr.sample_type & PERF_SAMPLE_MASK;
1796 	attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
1797 			    PERF_SAMPLE_PERIOD;
1798 	if (etm->timeless_decoding)
1799 		attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
1800 	else
1801 		attr.sample_type |= PERF_SAMPLE_TIME;
1802 
1803 	attr.exclude_user = evsel->core.attr.exclude_user;
1804 	attr.exclude_kernel = evsel->core.attr.exclude_kernel;
1805 	attr.exclude_hv = evsel->core.attr.exclude_hv;
1806 	attr.exclude_host = evsel->core.attr.exclude_host;
1807 	attr.exclude_guest = evsel->core.attr.exclude_guest;
1808 	attr.sample_id_all = evsel->core.attr.sample_id_all;
1809 	attr.read_format = evsel->core.attr.read_format;
1810 
1811 	/* create new id val to be a fixed offset from evsel id */
1812 	id = auxtrace_synth_id_range_start(evsel);
1813 
1814 	if (etm->synth_opts.branches) {
1815 		attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
1816 		attr.sample_period = 1;
1817 		attr.sample_type |= PERF_SAMPLE_ADDR;
1818 		err = perf_session__deliver_synth_attr_event(session, &attr, id);
1819 		if (err)
1820 			return err;
1821 		etm->branches_sample_type = attr.sample_type;
1822 		etm->branches_id = id;
1823 		id += 1;
1824 		attr.sample_type &= ~(u64)PERF_SAMPLE_ADDR;
1825 	}
1826 
1827 	if (etm->synth_opts.last_branch) {
1828 		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
1829 		/*
1830 		 * We don't use the hardware index, but the sample generation
1831 		 * code uses the new format branch_stack with this field,
1832 		 * so the event attributes must indicate that it's present.
1833 		 */
1834 		attr.branch_sample_type |= PERF_SAMPLE_BRANCH_HW_INDEX;
1835 	}
1836 
1837 	if (etm->synth_opts.callchain)
1838 		attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
1839 
1840 	if (etm->synth_opts.instructions) {
1841 		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
1842 		attr.sample_period = etm->synth_opts.period;
1843 		etm->instructions_sample_period = attr.sample_period;
1844 		err = perf_session__deliver_synth_attr_event(session, &attr, id);
1845 		if (err)
1846 			return err;
1847 		etm->instructions_sample_type = attr.sample_type;
1848 		etm->instructions_id = id;
1849 		id += 1;
1850 	}
1851 
1852 	return 0;
1853 }
1854 
1855 static int cs_etm__sample(struct cs_etm_queue *etmq,
1856 			  struct cs_etm_traceid_queue *tidq)
1857 {
1858 	struct cs_etm_auxtrace *etm = etmq->etm;
1859 	int ret;
1860 	u64 instrs_prev;
1861 
1862 	/* Get instructions remainder from previous packet */
1863 	instrs_prev = tidq->period_instructions;
1864 
1865 	tidq->period_instructions += tidq->packet->instr_count;
1866 
1867 	cs_etm__add_stack_event(etmq, tidq);
1868 
1869 	if (etm->synth_opts.instructions &&
1870 	    tidq->period_instructions >= etm->instructions_sample_period) {
1871 		/*
1872 		 * Emit instruction sample periodically
1873 		 * TODO: allow period to be defined in cycles and clock time
1874 		 */
1875 
1876 		/*
1877 		 * Below diagram demonstrates the instruction samples
1878 		 * generation flows:
1879 		 *
1880 		 *    Instrs     Instrs       Instrs       Instrs
1881 		 *   Sample(n)  Sample(n+1)  Sample(n+2)  Sample(n+3)
1882 		 *    |            |            |            |
1883 		 *    V            V            V            V
1884 		 *   --------------------------------------------------
1885 		 *            ^                                  ^
1886 		 *            |                                  |
1887 		 *         Period                             Period
1888 		 *    instructions(Pi)                   instructions(Pi')
1889 		 *
1890 		 *            |                                  |
1891 		 *            \---------------- -----------------/
1892 		 *                             V
1893 		 *                 tidq->packet->instr_count
1894 		 *
1895 		 * Instrs Sample(n...) are the synthesised samples occurring
1896 		 * every etm->instructions_sample_period instructions - as
1897 		 * defined on the perf command line.  Sample(n) is being the
1898 		 * last sample before the current etm packet, n+1 to n+3
1899 		 * samples are generated from the current etm packet.
1900 		 *
1901 		 * tidq->packet->instr_count represents the number of
1902 		 * instructions in the current etm packet.
1903 		 *
1904 		 * Period instructions (Pi) contains the number of
1905 		 * instructions executed after the sample point(n) from the
1906 		 * previous etm packet.  This will always be less than
1907 		 * etm->instructions_sample_period.
1908 		 *
1909 		 * When generate new samples, it combines with two parts
1910 		 * instructions, one is the tail of the old packet and another
1911 		 * is the head of the new coming packet, to generate
1912 		 * sample(n+1); sample(n+2) and sample(n+3) consume the
1913 		 * instructions with sample period.  After sample(n+3), the rest
1914 		 * instructions will be used by later packet and it is assigned
1915 		 * to tidq->period_instructions for next round calculation.
1916 		 */
1917 
1918 		/*
1919 		 * Get the initial offset into the current packet instructions;
1920 		 * entry conditions ensure that instrs_prev is less than
1921 		 * etm->instructions_sample_period.
1922 		 */
1923 		u64 offset = etm->instructions_sample_period - instrs_prev;
1924 		u64 addr;
1925 
1926 		while (tidq->period_instructions >=
1927 				etm->instructions_sample_period) {
1928 			/*
1929 			 * Calculate the address of the sampled instruction (-1
1930 			 * as sample is reported as though instruction has just
1931 			 * been executed, but PC has not advanced to next
1932 			 * instruction)
1933 			 */
1934 			addr = cs_etm__instr_addr(etmq, tidq, tidq->packet,
1935 						  offset - 1);
1936 			ret = cs_etm__synth_instruction_sample(
1937 				etmq, tidq, tidq->packet, addr,
1938 				etm->instructions_sample_period);
1939 			if (ret)
1940 				return ret;
1941 
1942 			offset += etm->instructions_sample_period;
1943 			tidq->period_instructions -=
1944 				etm->instructions_sample_period;
1945 		}
1946 	}
1947 
1948 	if (etm->synth_opts.branches) {
1949 		bool generate_sample = false;
1950 
1951 		/* Generate sample for tracing on packet */
1952 		if (tidq->prev_packet->sample_type == CS_ETM_DISCONTINUITY)
1953 			generate_sample = true;
1954 
1955 		/* Generate sample for branch taken packet */
1956 		if (cs_etm__packet_has_taken_branch(tidq->prev_packet))
1957 			generate_sample = true;
1958 
1959 		if (generate_sample) {
1960 			ret = cs_etm__synth_branch_sample(etmq, tidq);
1961 			if (ret)
1962 				return ret;
1963 		}
1964 	}
1965 
1966 	cs_etm__packet_swap(etm, tidq);
1967 
1968 	return 0;
1969 }
1970 
1971 static int cs_etm__context(struct cs_etm_queue *etmq,
1972 			   struct cs_etm_traceid_queue *tidq)
1973 {
1974 	ocsd_ex_level el = tidq->packet->el;
1975 	struct machine *machine;
1976 	int ret;
1977 
1978 	machine = cs_etm__get_machine(etmq, el);
1979 	if (!machine) {
1980 		ret = -EINVAL;
1981 		goto err;
1982 	}
1983 
1984 	tidq->kernel_start = machine__kernel_start(machine);
1985 
1986 	ret = cs_etm__etmq_update_thread(etmq, el, tidq->packet->tid,
1987 					 &tidq->frontend_thread);
1988 	if (ret)
1989 		goto err;
1990 
1991 	return 0;
1992 
1993 err:
1994 	thread__zput(tidq->frontend_thread);
1995 	tidq->kernel_start = 0;
1996 	return ret;
1997 }
1998 
1999 static int cs_etm__exception(struct cs_etm_traceid_queue *tidq)
2000 {
2001 	/*
2002 	 * When the exception packet is inserted, whether the last instruction
2003 	 * in previous range packet is taken branch or not, we need to force
2004 	 * to set 'prev_packet->last_instr_taken_branch' to true.  This ensures
2005 	 * to generate branch sample for the instruction range before the
2006 	 * exception is trapped to kernel or before the exception returning.
2007 	 *
2008 	 * The exception packet includes the dummy address values, so don't
2009 	 * swap PACKET with PREV_PACKET.  This keeps PREV_PACKET to be useful
2010 	 * for generating instruction and branch samples.
2011 	 */
2012 	if (tidq->prev_packet->sample_type == CS_ETM_RANGE)
2013 		tidq->prev_packet->last_instr_taken_branch = true;
2014 
2015 	return 0;
2016 }
2017 
2018 static int cs_etm__flush(struct cs_etm_queue *etmq,
2019 			 struct cs_etm_traceid_queue *tidq)
2020 {
2021 	int err = 0;
2022 	struct cs_etm_auxtrace *etm = etmq->etm;
2023 
2024 	/* Handle start tracing packet */
2025 	if (tidq->prev_packet->sample_type == CS_ETM_EMPTY)
2026 		goto swap_packet;
2027 
2028 	if (etmq->etm->synth_opts.last_branch &&
2029 	    etmq->etm->synth_opts.instructions &&
2030 	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
2031 		u64 addr;
2032 		/*
2033 		 * Generate a last branch event for the branches left in the
2034 		 * circular buffer at the end of the trace.
2035 		 *
2036 		 * Use the address of the end of the last reported execution
2037 		 * range
2038 		 */
2039 		addr = cs_etm__last_executed_instr(tidq->prev_packet);
2040 
2041 		err = cs_etm__synth_instruction_sample(
2042 			etmq, tidq, tidq->prev_packet, addr,
2043 			tidq->period_instructions);
2044 		if (err)
2045 			return err;
2046 
2047 		tidq->period_instructions = 0;
2048 
2049 	}
2050 
2051 	if (etm->synth_opts.branches &&
2052 	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
2053 		err = cs_etm__synth_branch_sample(etmq, tidq);
2054 		if (err)
2055 			return err;
2056 	}
2057 
2058 swap_packet:
2059 	cs_etm__packet_swap(etm, tidq);
2060 
2061 	/* Reset last branches after flush the trace */
2062 	if (etm->use_thread_stack)
2063 		thread_stack__flush(tidq->frontend_thread);
2064 
2065 	return err;
2066 }
2067 
2068 static int cs_etm__end_block(struct cs_etm_queue *etmq,
2069 			     struct cs_etm_traceid_queue *tidq)
2070 {
2071 	int err;
2072 
2073 	/*
2074 	 * It has no new packet coming and 'etmq->packet' contains the stale
2075 	 * packet which was set at the previous time with packets swapping;
2076 	 * so skip to generate branch sample to avoid stale packet.
2077 	 *
2078 	 * For this case only flush branch stack and generate a last branch
2079 	 * event for the branches left in the circular buffer at the end of
2080 	 * the trace.
2081 	 */
2082 	if (etmq->etm->synth_opts.last_branch &&
2083 	    etmq->etm->synth_opts.instructions &&
2084 	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
2085 		u64 addr;
2086 
2087 		/*
2088 		 * Use the address of the end of the last reported execution
2089 		 * range.
2090 		 */
2091 		addr = cs_etm__last_executed_instr(tidq->prev_packet);
2092 
2093 		err = cs_etm__synth_instruction_sample(
2094 			etmq, tidq, tidq->prev_packet, addr,
2095 			tidq->period_instructions);
2096 		if (err)
2097 			return err;
2098 
2099 		tidq->period_instructions = 0;
2100 	}
2101 
2102 	return 0;
2103 }
2104 
2105 static int cs_etm__flush_stack_cb(struct thread *thread,
2106 				  void *data __maybe_unused)
2107 {
2108 	thread_stack__flush(thread);
2109 	return 0;
2110 }
2111 
2112 static void cs_etm__flush_machine_stack(struct cs_etm_queue *etmq, pid_t pid)
2113 {
2114 	struct machine *machine;
2115 
2116 	machine = machines__find(&etmq->etm->session->machines, pid);
2117 	if (machine)
2118 		machine__for_each_thread(machine, cs_etm__flush_stack_cb, NULL);
2119 }
2120 
2121 static void cs_etm__flush_all_stack(struct cs_etm_queue *etmq)
2122 {
2123 	enum cs_etm_pid_fmt pid_fmt = cs_etm__get_pid_fmt(etmq);
2124 
2125 	if (!etmq->etm->use_thread_stack)
2126 		return;
2127 
2128 	switch (pid_fmt) {
2129 	case CS_ETM_PIDFMT_CTXTID2:
2130 		/* Clear the guest stack if virtualization is supported */
2131 		cs_etm__flush_machine_stack(etmq, DEFAULT_GUEST_KERNEL_ID);
2132 		fallthrough;
2133 	case CS_ETM_PIDFMT_CTXTID:
2134 		cs_etm__flush_machine_stack(etmq, HOST_KERNEL_ID);
2135 		break;
2136 	case CS_ETM_PIDFMT_NONE:
2137 	default:
2138 		break;
2139 
2140 	}
2141 }
2142 
2143 /*
2144  * cs_etm__get_data_block: Fetch a block from the auxtrace_buffer queue
2145  *			   if need be.
2146  * Returns:	< 0	if error
2147  *		= 0	if no more auxtrace_buffer to read
2148  *		> 0	if the current buffer isn't empty yet
2149  */
2150 static int cs_etm__get_data_block(struct cs_etm_queue *etmq)
2151 {
2152 	int ret;
2153 
2154 	if (!etmq->buf_len) {
2155 		ret = cs_etm__get_trace(etmq);
2156 		if (ret <= 0)
2157 			return ret;
2158 		/*
2159 		 * We cannot assume consecutive blocks in the data file
2160 		 * are contiguous, reset the decoder to force re-sync.
2161 		 */
2162 		ret = cs_etm_decoder__reset(etmq->decoder);
2163 		if (ret)
2164 			return ret;
2165 
2166 		/*
2167 		 * Since the decoder is reset, this causes a global trace
2168 		 * discontinuity. Flush all thread stacks.
2169 		 */
2170 		cs_etm__flush_all_stack(etmq);
2171 	}
2172 
2173 	return etmq->buf_len;
2174 }
2175 
2176 static bool cs_etm__is_svc_instr(struct cs_etm_queue *etmq,
2177 				 struct cs_etm_traceid_queue *tidq,
2178 				 struct cs_etm_packet *packet, u64 end_addr)
2179 {
2180 	/* Initialise to keep compiler happy */
2181 	u16 instr16 = 0;
2182 	u32 instr32 = 0;
2183 	u64 addr;
2184 
2185 	switch (packet->isa) {
2186 	case CS_ETM_ISA_T32:
2187 		/*
2188 		 * The SVC of T32 is defined in ARM DDI 0487D.a, F5.1.247:
2189 		 *
2190 		 *  b'15         b'8
2191 		 * +-----------------+--------+
2192 		 * | 1 1 0 1 1 1 1 1 |  imm8  |
2193 		 * +-----------------+--------+
2194 		 *
2195 		 * According to the specification, it only defines SVC for T32
2196 		 * with 16 bits instruction and has no definition for 32bits;
2197 		 * so below only read 2 bytes as instruction size for T32.
2198 		 */
2199 		addr = end_addr - 2;
2200 		cs_etm__frontend_mem_access(etmq, tidq, packet, addr,
2201 					    sizeof(instr16), (u8 *)&instr16);
2202 		if ((instr16 & 0xFF00) == 0xDF00)
2203 			return true;
2204 
2205 		break;
2206 	case CS_ETM_ISA_A32:
2207 		/*
2208 		 * The SVC of A32 is defined in ARM DDI 0487D.a, F5.1.247:
2209 		 *
2210 		 *  b'31 b'28 b'27 b'24
2211 		 * +---------+---------+-------------------------+
2212 		 * |  !1111  | 1 1 1 1 |        imm24            |
2213 		 * +---------+---------+-------------------------+
2214 		 */
2215 		addr = end_addr - 4;
2216 		cs_etm__frontend_mem_access(etmq, tidq, packet, addr,
2217 					    sizeof(instr32), (u8 *)&instr32);
2218 		if ((instr32 & 0x0F000000) == 0x0F000000 &&
2219 		    (instr32 & 0xF0000000) != 0xF0000000)
2220 			return true;
2221 
2222 		break;
2223 	case CS_ETM_ISA_A64:
2224 		/*
2225 		 * The SVC of A64 is defined in ARM DDI 0487D.a, C6.2.294:
2226 		 *
2227 		 *  b'31               b'21           b'4     b'0
2228 		 * +-----------------------+---------+-----------+
2229 		 * | 1 1 0 1 0 1 0 0 0 0 0 |  imm16  | 0 0 0 0 1 |
2230 		 * +-----------------------+---------+-----------+
2231 		 */
2232 		addr = end_addr - 4;
2233 		cs_etm__frontend_mem_access(etmq, tidq, packet, addr,
2234 					    sizeof(instr32), (u8 *)&instr32);
2235 		if ((instr32 & 0xFFE0001F) == 0xd4000001)
2236 			return true;
2237 
2238 		break;
2239 	case CS_ETM_ISA_UNKNOWN:
2240 	default:
2241 		break;
2242 	}
2243 
2244 	return false;
2245 }
2246 
2247 static bool cs_etm__is_syscall(struct cs_etm_queue *etmq,
2248 			       struct cs_etm_traceid_queue *tidq, u64 magic)
2249 {
2250 	struct cs_etm_packet *packet = tidq->packet;
2251 	struct cs_etm_packet *prev_packet = tidq->prev_packet;
2252 
2253 	if (magic == __perf_cs_etmv3_magic)
2254 		if (packet->exception_number == CS_ETMV3_EXC_SVC)
2255 			return true;
2256 
2257 	/*
2258 	 * ETMv4 exception type CS_ETMV4_EXC_CALL covers SVC, SMC and
2259 	 * HVC cases; need to check if it's SVC instruction based on
2260 	 * packet address.
2261 	 */
2262 	if (magic == __perf_cs_etmv4_magic || magic == __perf_cs_ete_magic) {
2263 		if (packet->exception_number == CS_ETMV4_EXC_CALL &&
2264 		    cs_etm__is_svc_instr(etmq, tidq, prev_packet,
2265 					 prev_packet->end_addr))
2266 			return true;
2267 	}
2268 
2269 	return false;
2270 }
2271 
2272 static bool cs_etm__is_async_exception(struct cs_etm_traceid_queue *tidq,
2273 				       u64 magic)
2274 {
2275 	struct cs_etm_packet *packet = tidq->packet;
2276 
2277 	if (magic == __perf_cs_etmv3_magic)
2278 		if (packet->exception_number == CS_ETMV3_EXC_DEBUG_HALT ||
2279 		    packet->exception_number == CS_ETMV3_EXC_ASYNC_DATA_ABORT ||
2280 		    packet->exception_number == CS_ETMV3_EXC_PE_RESET ||
2281 		    packet->exception_number == CS_ETMV3_EXC_IRQ ||
2282 		    packet->exception_number == CS_ETMV3_EXC_FIQ)
2283 			return true;
2284 
2285 	if (magic == __perf_cs_etmv4_magic || magic == __perf_cs_ete_magic)
2286 		if (packet->exception_number == CS_ETMV4_EXC_RESET ||
2287 		    packet->exception_number == CS_ETMV4_EXC_DEBUG_HALT ||
2288 		    packet->exception_number == CS_ETMV4_EXC_SYSTEM_ERROR ||
2289 		    packet->exception_number == CS_ETMV4_EXC_INST_DEBUG ||
2290 		    packet->exception_number == CS_ETMV4_EXC_DATA_DEBUG ||
2291 		    packet->exception_number == CS_ETMV4_EXC_IRQ ||
2292 		    packet->exception_number == CS_ETMV4_EXC_FIQ)
2293 			return true;
2294 
2295 	return false;
2296 }
2297 
2298 static bool cs_etm__is_sync_exception(struct cs_etm_queue *etmq,
2299 				      struct cs_etm_traceid_queue *tidq,
2300 				      u64 magic)
2301 {
2302 	struct cs_etm_packet *packet = tidq->packet;
2303 	struct cs_etm_packet *prev_packet = tidq->prev_packet;
2304 
2305 	if (magic == __perf_cs_etmv3_magic)
2306 		if (packet->exception_number == CS_ETMV3_EXC_SMC ||
2307 		    packet->exception_number == CS_ETMV3_EXC_HYP ||
2308 		    packet->exception_number == CS_ETMV3_EXC_JAZELLE_THUMBEE ||
2309 		    packet->exception_number == CS_ETMV3_EXC_UNDEFINED_INSTR ||
2310 		    packet->exception_number == CS_ETMV3_EXC_PREFETCH_ABORT ||
2311 		    packet->exception_number == CS_ETMV3_EXC_DATA_FAULT ||
2312 		    packet->exception_number == CS_ETMV3_EXC_GENERIC)
2313 			return true;
2314 
2315 	if (magic == __perf_cs_etmv4_magic || magic == __perf_cs_ete_magic) {
2316 		if (packet->exception_number == CS_ETMV4_EXC_TRAP ||
2317 		    packet->exception_number == CS_ETMV4_EXC_ALIGNMENT ||
2318 		    packet->exception_number == CS_ETMV4_EXC_INST_FAULT ||
2319 		    packet->exception_number == CS_ETMV4_EXC_DATA_FAULT)
2320 			return true;
2321 
2322 		/*
2323 		 * For CS_ETMV4_EXC_CALL, except SVC other instructions
2324 		 * (SMC, HVC) are taken as sync exceptions.
2325 		 */
2326 		if (packet->exception_number == CS_ETMV4_EXC_CALL &&
2327 		    !cs_etm__is_svc_instr(etmq, tidq, prev_packet,
2328 					  prev_packet->end_addr))
2329 			return true;
2330 
2331 		/*
2332 		 * ETMv4 has 5 bits for exception number; if the numbers
2333 		 * are in the range ( CS_ETMV4_EXC_FIQ, CS_ETMV4_EXC_END ]
2334 		 * they are implementation defined exceptions.
2335 		 *
2336 		 * For this case, simply take it as sync exception.
2337 		 */
2338 		if (packet->exception_number > CS_ETMV4_EXC_FIQ &&
2339 		    packet->exception_number <= CS_ETMV4_EXC_END)
2340 			return true;
2341 	}
2342 
2343 	return false;
2344 }
2345 
2346 static int cs_etm__set_sample_flags(struct cs_etm_queue *etmq,
2347 				    struct cs_etm_traceid_queue *tidq)
2348 {
2349 	struct cs_etm_packet *packet = tidq->packet;
2350 	struct cs_etm_packet *prev_packet = tidq->prev_packet;
2351 	u64 magic;
2352 	int ret;
2353 
2354 	switch (packet->sample_type) {
2355 	case CS_ETM_RANGE:
2356 		/*
2357 		 * Immediate branch instruction without neither link nor
2358 		 * return flag, it's normal branch instruction within
2359 		 * the function.
2360 		 */
2361 		if (packet->last_instr_type == OCSD_INSTR_BR &&
2362 		    packet->last_instr_subtype == OCSD_S_INSTR_NONE) {
2363 			packet->flags = PERF_IP_FLAG_BRANCH;
2364 
2365 			if (packet->last_instr_cond)
2366 				packet->flags |= PERF_IP_FLAG_CONDITIONAL;
2367 		}
2368 
2369 		/*
2370 		 * Immediate branch instruction with link (e.g. BL), this is
2371 		 * branch instruction for function call.
2372 		 */
2373 		if (packet->last_instr_type == OCSD_INSTR_BR &&
2374 		    packet->last_instr_subtype == OCSD_S_INSTR_BR_LINK)
2375 			packet->flags = PERF_IP_FLAG_BRANCH |
2376 					PERF_IP_FLAG_CALL;
2377 
2378 		/*
2379 		 * Indirect branch instruction with link (e.g. BLR), this is
2380 		 * branch instruction for function call.
2381 		 */
2382 		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
2383 		    packet->last_instr_subtype == OCSD_S_INSTR_BR_LINK)
2384 			packet->flags = PERF_IP_FLAG_BRANCH |
2385 					PERF_IP_FLAG_CALL;
2386 
2387 		/*
2388 		 * Indirect branch instruction with subtype of
2389 		 * OCSD_S_INSTR_V7_IMPLIED_RET, this is explicit hint for
2390 		 * function return for A32/T32.
2391 		 */
2392 		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
2393 		    packet->last_instr_subtype == OCSD_S_INSTR_V7_IMPLIED_RET)
2394 			packet->flags = PERF_IP_FLAG_BRANCH |
2395 					PERF_IP_FLAG_RETURN;
2396 
2397 		/*
2398 		 * Indirect branch instruction without link (e.g. BR), usually
2399 		 * this is used for function return, especially for functions
2400 		 * within dynamic link lib.
2401 		 */
2402 		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
2403 		    packet->last_instr_subtype == OCSD_S_INSTR_NONE)
2404 			packet->flags = PERF_IP_FLAG_BRANCH |
2405 					PERF_IP_FLAG_RETURN;
2406 
2407 		/* Return instruction for function return. */
2408 		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
2409 		    packet->last_instr_subtype == OCSD_S_INSTR_V8_RET)
2410 			packet->flags = PERF_IP_FLAG_BRANCH |
2411 					PERF_IP_FLAG_RETURN;
2412 
2413 		/*
2414 		 * Decoder might insert a discontinuity in the middle of
2415 		 * instruction packets, fixup prev_packet with flag
2416 		 * PERF_IP_FLAG_TRACE_BEGIN to indicate restarting trace.
2417 		 */
2418 		if (prev_packet->sample_type == CS_ETM_DISCONTINUITY)
2419 			prev_packet->flags |= PERF_IP_FLAG_BRANCH |
2420 					      PERF_IP_FLAG_TRACE_BEGIN;
2421 
2422 		/*
2423 		 * If the previous packet is an exception return packet
2424 		 * and the return address just follows SVC instruction,
2425 		 * it needs to calibrate the previous packet sample flags
2426 		 * as PERF_IP_FLAG_SYSCALLRET.
2427 		 */
2428 		if (prev_packet->flags == (PERF_IP_FLAG_BRANCH |
2429 					   PERF_IP_FLAG_RETURN |
2430 					   PERF_IP_FLAG_INTERRUPT) &&
2431 		    cs_etm__is_svc_instr(etmq, tidq, packet, packet->start_addr)) {
2432 			prev_packet->flags = PERF_IP_FLAG_BRANCH |
2433 					     PERF_IP_FLAG_RETURN |
2434 					     PERF_IP_FLAG_SYSCALLRET;
2435 		}
2436 		break;
2437 	case CS_ETM_DISCONTINUITY:
2438 		/*
2439 		 * The trace is discontinuous, if the previous packet is
2440 		 * instruction packet, set flag PERF_IP_FLAG_TRACE_END
2441 		 * for previous packet.
2442 		 */
2443 		if (prev_packet->sample_type == CS_ETM_RANGE)
2444 			prev_packet->flags |= PERF_IP_FLAG_BRANCH |
2445 					      PERF_IP_FLAG_TRACE_END;
2446 		break;
2447 	case CS_ETM_EXCEPTION:
2448 		ret = cs_etm__get_magic(etmq, packet->trace_chan_id, &magic);
2449 		if (ret)
2450 			return ret;
2451 
2452 		/* The exception is for system call. */
2453 		if (cs_etm__is_syscall(etmq, tidq, magic))
2454 			packet->flags = PERF_IP_FLAG_BRANCH |
2455 					PERF_IP_FLAG_CALL |
2456 					PERF_IP_FLAG_SYSCALLRET;
2457 		/*
2458 		 * The exceptions are triggered by external signals from bus,
2459 		 * interrupt controller, debug module, PE reset or halt.
2460 		 */
2461 		else if (cs_etm__is_async_exception(tidq, magic))
2462 			packet->flags = PERF_IP_FLAG_BRANCH |
2463 					PERF_IP_FLAG_CALL |
2464 					PERF_IP_FLAG_ASYNC |
2465 					PERF_IP_FLAG_INTERRUPT;
2466 		/*
2467 		 * Otherwise, exception is caused by trap, instruction &
2468 		 * data fault, or alignment errors.
2469 		 */
2470 		else if (cs_etm__is_sync_exception(etmq, tidq, magic))
2471 			packet->flags = PERF_IP_FLAG_BRANCH |
2472 					PERF_IP_FLAG_CALL |
2473 					PERF_IP_FLAG_INTERRUPT;
2474 
2475 		/*
2476 		 * When the exception packet is inserted, since exception
2477 		 * packet is not used standalone for generating samples
2478 		 * and it's affiliation to the previous instruction range
2479 		 * packet; so set previous range packet flags to tell perf
2480 		 * it is an exception taken branch.
2481 		 */
2482 		if (prev_packet->sample_type == CS_ETM_RANGE)
2483 			prev_packet->flags = packet->flags;
2484 		break;
2485 	case CS_ETM_EXCEPTION_RET:
2486 		/*
2487 		 * When the exception return packet is inserted, since
2488 		 * exception return packet is not used standalone for
2489 		 * generating samples and it's affiliation to the previous
2490 		 * instruction range packet; so set previous range packet
2491 		 * flags to tell perf it is an exception return branch.
2492 		 *
2493 		 * The exception return can be for either system call or
2494 		 * other exception types; unfortunately the packet doesn't
2495 		 * contain exception type related info so we cannot decide
2496 		 * the exception type purely based on exception return packet.
2497 		 * If we record the exception number from exception packet and
2498 		 * reuse it for exception return packet, this is not reliable
2499 		 * due the trace can be discontinuity or the interrupt can
2500 		 * be nested, thus the recorded exception number cannot be
2501 		 * used for exception return packet for these two cases.
2502 		 *
2503 		 * For exception return packet, we only need to distinguish the
2504 		 * packet is for system call or for other types.  Thus the
2505 		 * decision can be deferred when receive the next packet which
2506 		 * contains the return address, based on the return address we
2507 		 * can read out the previous instruction and check if it's a
2508 		 * system call instruction and then calibrate the sample flag
2509 		 * as needed.
2510 		 */
2511 		if (prev_packet->sample_type == CS_ETM_RANGE)
2512 			prev_packet->flags = PERF_IP_FLAG_BRANCH |
2513 					     PERF_IP_FLAG_RETURN |
2514 					     PERF_IP_FLAG_INTERRUPT;
2515 		break;
2516 	case CS_ETM_CONTEXT:
2517 	case CS_ETM_EMPTY:
2518 	default:
2519 		break;
2520 	}
2521 
2522 	return 0;
2523 }
2524 
2525 static int cs_etm__decode_data_block(struct cs_etm_queue *etmq)
2526 {
2527 	int ret = 0;
2528 	size_t processed = 0;
2529 
2530 	/*
2531 	 * Packets are decoded and added to the decoder's packet queue
2532 	 * until the decoder packet processing callback has requested that
2533 	 * processing stops or there is nothing left in the buffer.  Normal
2534 	 * operations that stop processing are a timestamp packet or a full
2535 	 * decoder buffer queue.
2536 	 */
2537 	ret = cs_etm_decoder__process_data_block(etmq->decoder,
2538 						 etmq->offset,
2539 						 &etmq->buf[etmq->buf_used],
2540 						 etmq->buf_len,
2541 						 &processed);
2542 	if (ret)
2543 		goto out;
2544 
2545 	etmq->offset += processed;
2546 	etmq->buf_used += processed;
2547 	etmq->buf_len -= processed;
2548 
2549 out:
2550 	return ret;
2551 }
2552 
2553 static int cs_etm__process_traceid_queue(struct cs_etm_queue *etmq,
2554 					 struct cs_etm_traceid_queue *tidq)
2555 {
2556 	int ret;
2557 	struct cs_etm_packet_queue *packet_queue;
2558 
2559 	packet_queue = &tidq->packet_queue;
2560 
2561 	/* Process each packet in this chunk */
2562 	while (1) {
2563 		ret = cs_etm_decoder__get_packet(packet_queue,
2564 						 tidq->packet);
2565 		if (ret <= 0)
2566 			/*
2567 			 * Stop processing this chunk on
2568 			 * end of data or error
2569 			 */
2570 			break;
2571 
2572 		/*
2573 		 * Since packet addresses are swapped in packet
2574 		 * handling within below switch() statements,
2575 		 * thus setting sample flags must be called
2576 		 * prior to switch() statement to use address
2577 		 * information before packets swapping.
2578 		 */
2579 		ret = cs_etm__set_sample_flags(etmq, tidq);
2580 		if (ret < 0)
2581 			break;
2582 
2583 		switch (tidq->packet->sample_type) {
2584 		case CS_ETM_RANGE:
2585 			/*
2586 			 * If the packet contains an instruction
2587 			 * range, generate instruction sequence
2588 			 * events.
2589 			 */
2590 			cs_etm__sample(etmq, tidq);
2591 			break;
2592 		case CS_ETM_CONTEXT:
2593 			/*
2594 			 * Update context but don't swap packet. Keep the
2595 			 * previous one for branch source address info, if
2596 			 * tracing the kernel the context packet will be emitted
2597 			 * between two ranges.
2598 			 */
2599 			ret = cs_etm__context(etmq, tidq);
2600 			if (ret)
2601 				goto out;
2602 			break;
2603 		case CS_ETM_EXCEPTION:
2604 		case CS_ETM_EXCEPTION_RET:
2605 			/*
2606 			 * If the exception packet is coming,
2607 			 * make sure the previous instruction
2608 			 * range packet to be handled properly.
2609 			 */
2610 			cs_etm__exception(tidq);
2611 			break;
2612 		case CS_ETM_DISCONTINUITY:
2613 			/*
2614 			 * Discontinuity in trace, flush
2615 			 * previous branch stack
2616 			 */
2617 			cs_etm__flush(etmq, tidq);
2618 			break;
2619 		case CS_ETM_EMPTY:
2620 			/*
2621 			 * Should not receive empty packet,
2622 			 * report error.
2623 			 */
2624 			pr_err("CS ETM Trace: empty packet\n");
2625 			return -EINVAL;
2626 		default:
2627 			break;
2628 		}
2629 	}
2630 
2631 out:
2632 	return ret;
2633 }
2634 
2635 static void cs_etm__clear_all_traceid_queues(struct cs_etm_queue *etmq)
2636 {
2637 	int idx;
2638 	struct int_node *inode;
2639 	struct cs_etm_traceid_queue *tidq;
2640 	struct intlist *traceid_queues_list = etmq->traceid_queues_list;
2641 
2642 	intlist__for_each_entry(inode, traceid_queues_list) {
2643 		idx = (int)(intptr_t)inode->priv;
2644 		tidq = etmq->traceid_queues[idx];
2645 
2646 		/* Ignore return value */
2647 		cs_etm__process_traceid_queue(etmq, tidq);
2648 	}
2649 }
2650 
2651 static int cs_etm__run_per_thread_timeless_decoder(struct cs_etm_queue *etmq)
2652 {
2653 	int err = 0;
2654 	struct cs_etm_traceid_queue *tidq;
2655 
2656 	tidq = cs_etm__etmq_get_traceid_queue(etmq, CS_ETM_PER_THREAD_TRACEID);
2657 	if (!tidq)
2658 		return -EINVAL;
2659 
2660 	/* Go through each buffer in the queue and decode them one by one */
2661 	while (1) {
2662 		err = cs_etm__get_data_block(etmq);
2663 		if (err <= 0)
2664 			return err;
2665 
2666 		/* Run trace decoder until buffer consumed or end of trace */
2667 		do {
2668 			err = cs_etm__decode_data_block(etmq);
2669 			if (err)
2670 				return err;
2671 
2672 			/*
2673 			 * Process each packet in this chunk, nothing to do if
2674 			 * an error occurs other than hoping the next one will
2675 			 * be better.
2676 			 */
2677 			err = cs_etm__process_traceid_queue(etmq, tidq);
2678 
2679 		} while (etmq->buf_len);
2680 
2681 		if (err == 0)
2682 			/* Flush any remaining branch stack entries */
2683 			err = cs_etm__end_block(etmq, tidq);
2684 	}
2685 
2686 	return err;
2687 }
2688 
2689 static int cs_etm__run_per_cpu_timeless_decoder(struct cs_etm_queue *etmq)
2690 {
2691 	int idx, err = 0;
2692 	struct cs_etm_traceid_queue *tidq;
2693 	struct int_node *inode;
2694 
2695 	/* Go through each buffer in the queue and decode them one by one */
2696 	while (1) {
2697 		err = cs_etm__get_data_block(etmq);
2698 		if (err <= 0)
2699 			return err;
2700 
2701 		/* Run trace decoder until buffer consumed or end of trace */
2702 		do {
2703 			err = cs_etm__decode_data_block(etmq);
2704 			if (err)
2705 				return err;
2706 
2707 			/*
2708 			 * cs_etm__run_per_thread_timeless_decoder() runs on a
2709 			 * single traceID queue because each TID has a separate
2710 			 * buffer. But here in per-cpu mode we need to iterate
2711 			 * over each channel instead.
2712 			 */
2713 			intlist__for_each_entry(inode,
2714 						etmq->traceid_queues_list) {
2715 				idx = (int)(intptr_t)inode->priv;
2716 				tidq = etmq->traceid_queues[idx];
2717 				cs_etm__process_traceid_queue(etmq, tidq);
2718 			}
2719 		} while (etmq->buf_len);
2720 
2721 		intlist__for_each_entry(inode, etmq->traceid_queues_list) {
2722 			idx = (int)(intptr_t)inode->priv;
2723 			tidq = etmq->traceid_queues[idx];
2724 			/* Flush any remaining branch stack entries */
2725 			err = cs_etm__end_block(etmq, tidq);
2726 			if (err)
2727 				return err;
2728 		}
2729 	}
2730 
2731 	return err;
2732 }
2733 
2734 static int cs_etm__process_timeless_queues(struct cs_etm_auxtrace *etm,
2735 					   pid_t tid)
2736 {
2737 	unsigned int i;
2738 	struct auxtrace_queues *queues = &etm->queues;
2739 
2740 	for (i = 0; i < queues->nr_queues; i++) {
2741 		struct auxtrace_queue *queue = &etm->queues.queue_array[i];
2742 		struct cs_etm_queue *etmq = queue->priv;
2743 		struct cs_etm_traceid_queue *tidq;
2744 
2745 		if (!etmq)
2746 			continue;
2747 
2748 		if (etm->per_thread_decoding) {
2749 			tidq = cs_etm__etmq_get_traceid_queue(
2750 				etmq, CS_ETM_PER_THREAD_TRACEID);
2751 
2752 			if (!tidq)
2753 				continue;
2754 
2755 			if (tid == -1 || thread__tid(tidq->frontend_thread) == tid)
2756 				cs_etm__run_per_thread_timeless_decoder(etmq);
2757 		} else
2758 			cs_etm__run_per_cpu_timeless_decoder(etmq);
2759 	}
2760 
2761 	return 0;
2762 }
2763 
2764 static int cs_etm__process_timestamped_queues(struct cs_etm_auxtrace *etm)
2765 {
2766 	int ret = 0;
2767 	unsigned int cs_queue_nr, queue_nr, i;
2768 	u8 trace_chan_id;
2769 	u64 cs_timestamp;
2770 	struct auxtrace_queue *queue;
2771 	struct cs_etm_queue *etmq;
2772 	struct cs_etm_traceid_queue *tidq;
2773 
2774 	/*
2775 	 * Pre-populate the heap with one entry from each queue so that we can
2776 	 * start processing in time order across all queues.
2777 	 */
2778 	for (i = 0; i < etm->queues.nr_queues; i++) {
2779 		etmq = etm->queues.queue_array[i].priv;
2780 		if (!etmq)
2781 			continue;
2782 
2783 		ret = cs_etm__queue_first_cs_timestamp(etm, etmq, i);
2784 		if (ret)
2785 			return ret;
2786 	}
2787 
2788 	while (1) {
2789 		if (!etm->heap.heap_cnt)
2790 			break;
2791 
2792 		/* Take the entry at the top of the min heap */
2793 		cs_queue_nr = etm->heap.heap_array[0].queue_nr;
2794 		queue_nr = TO_QUEUE_NR(cs_queue_nr);
2795 		trace_chan_id = TO_TRACE_CHAN_ID(cs_queue_nr);
2796 		queue = &etm->queues.queue_array[queue_nr];
2797 		etmq = queue->priv;
2798 
2799 		/*
2800 		 * Remove the top entry from the heap since we are about
2801 		 * to process it.
2802 		 */
2803 		auxtrace_heap__pop(&etm->heap);
2804 
2805 		tidq  = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
2806 		if (!tidq) {
2807 			/*
2808 			 * No traceID queue has been allocated for this traceID,
2809 			 * which means something somewhere went very wrong.  No
2810 			 * other choice than simply exit.
2811 			 */
2812 			ret = -EINVAL;
2813 			goto out;
2814 		}
2815 
2816 		/*
2817 		 * Packets associated with this timestamp are already in
2818 		 * the etmq's traceID queue, so process them.
2819 		 */
2820 		ret = cs_etm__process_traceid_queue(etmq, tidq);
2821 		if (ret < 0)
2822 			goto out;
2823 
2824 		/*
2825 		 * Packets for this timestamp have been processed, time to
2826 		 * move on to the next timestamp, fetching a new auxtrace_buffer
2827 		 * if need be.
2828 		 */
2829 refetch:
2830 		ret = cs_etm__get_data_block(etmq);
2831 		if (ret < 0)
2832 			goto out;
2833 
2834 		/*
2835 		 * No more auxtrace_buffers to process in this etmq, simply
2836 		 * move on to another entry in the auxtrace_heap.
2837 		 */
2838 		if (!ret)
2839 			continue;
2840 
2841 		ret = cs_etm__decode_data_block(etmq);
2842 		if (ret)
2843 			goto out;
2844 
2845 		cs_timestamp = cs_etm__etmq_get_timestamp(etmq, &trace_chan_id);
2846 
2847 		if (!cs_timestamp) {
2848 			/*
2849 			 * Function cs_etm__decode_data_block() returns when
2850 			 * there is no more traces to decode in the current
2851 			 * auxtrace_buffer OR when a timestamp has been
2852 			 * encountered on any of the traceID queues.  Since we
2853 			 * did not get a timestamp, there is no more traces to
2854 			 * process in this auxtrace_buffer.  As such empty and
2855 			 * flush all traceID queues.
2856 			 */
2857 			cs_etm__clear_all_traceid_queues(etmq);
2858 
2859 			/* Fetch another auxtrace_buffer for this etmq */
2860 			goto refetch;
2861 		}
2862 
2863 		/*
2864 		 * Add to the min heap the timestamp for packets that have
2865 		 * just been decoded.  They will be processed and synthesized
2866 		 * during the next call to cs_etm__process_traceid_queue() for
2867 		 * this queue/traceID.
2868 		 */
2869 		cs_queue_nr = TO_CS_QUEUE_NR(queue_nr, trace_chan_id);
2870 		ret = auxtrace_heap__add(&etm->heap, cs_queue_nr, cs_timestamp);
2871 	}
2872 
2873 	for (i = 0; i < etm->queues.nr_queues; i++) {
2874 		struct int_node *inode;
2875 
2876 		etmq = etm->queues.queue_array[i].priv;
2877 		if (!etmq)
2878 			continue;
2879 
2880 		intlist__for_each_entry(inode, etmq->traceid_queues_list) {
2881 			int idx = (int)(intptr_t)inode->priv;
2882 
2883 			/* Flush any remaining branch stack entries */
2884 			tidq = etmq->traceid_queues[idx];
2885 			ret = cs_etm__end_block(etmq, tidq);
2886 			if (ret)
2887 				return ret;
2888 		}
2889 	}
2890 out:
2891 	return ret;
2892 }
2893 
2894 static int cs_etm__process_itrace_start(struct cs_etm_auxtrace *etm,
2895 					union perf_event *event)
2896 {
2897 	struct thread *th;
2898 
2899 	if (etm->timeless_decoding)
2900 		return 0;
2901 
2902 	/*
2903 	 * Add the tid/pid to the log so that we can get a match when we get a
2904 	 * contextID from the decoder. Only track for the host: only kernel
2905 	 * trace is supported for guests which wouldn't need pids so this should
2906 	 * be fine.
2907 	 */
2908 	th = machine__findnew_thread(&etm->session->machines.host,
2909 				     event->itrace_start.pid,
2910 				     event->itrace_start.tid);
2911 	if (!th)
2912 		return -ENOMEM;
2913 
2914 	thread__put(th);
2915 
2916 	return 0;
2917 }
2918 
2919 static int cs_etm__process_switch_cpu_wide(struct cs_etm_auxtrace *etm,
2920 					   union perf_event *event)
2921 {
2922 	struct thread *th;
2923 	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;
2924 
2925 	/*
2926 	 * Context switch in per-thread mode are irrelevant since perf
2927 	 * will start/stop tracing as the process is scheduled.
2928 	 */
2929 	if (etm->timeless_decoding)
2930 		return 0;
2931 
2932 	/*
2933 	 * SWITCH_IN events carry the next process to be switched out while
2934 	 * SWITCH_OUT events carry the process to be switched in.  As such
2935 	 * we don't care about IN events.
2936 	 */
2937 	if (!out)
2938 		return 0;
2939 
2940 	/*
2941 	 * Add the tid/pid to the log so that we can get a match when we get a
2942 	 * contextID from the decoder. Only track for the host: only kernel
2943 	 * trace is supported for guests which wouldn't need pids so this should
2944 	 * be fine.
2945 	 */
2946 	th = machine__findnew_thread(&etm->session->machines.host,
2947 				     event->context_switch.next_prev_pid,
2948 				     event->context_switch.next_prev_tid);
2949 	if (!th)
2950 		return -ENOMEM;
2951 
2952 	thread__put(th);
2953 
2954 	return 0;
2955 }
2956 
2957 static int cs_etm__process_event(struct perf_session *session,
2958 				 union perf_event *event,
2959 				 struct perf_sample *sample,
2960 				 const struct perf_tool *tool)
2961 {
2962 	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
2963 						   struct cs_etm_auxtrace,
2964 						   auxtrace);
2965 
2966 	if (dump_trace)
2967 		return 0;
2968 
2969 	if (!tool->ordered_events) {
2970 		pr_err("CoreSight ETM Trace requires ordered events\n");
2971 		return -EINVAL;
2972 	}
2973 
2974 	switch (event->header.type) {
2975 	case PERF_RECORD_EXIT:
2976 		/*
2977 		 * Don't need to wait for cs_etm__flush_events() in per-thread mode to
2978 		 * start the decode because we know there will be no more trace from
2979 		 * this thread. All this does is emit samples earlier than waiting for
2980 		 * the flush in other modes, but with timestamps it makes sense to wait
2981 		 * for flush so that events from different threads are interleaved
2982 		 * properly.
2983 		 */
2984 		if (etm->per_thread_decoding && etm->timeless_decoding)
2985 			return cs_etm__process_timeless_queues(etm,
2986 							       event->fork.tid);
2987 		break;
2988 
2989 	case PERF_RECORD_ITRACE_START:
2990 		return cs_etm__process_itrace_start(etm, event);
2991 
2992 	case PERF_RECORD_SWITCH_CPU_WIDE:
2993 		return cs_etm__process_switch_cpu_wide(etm, event);
2994 
2995 	case PERF_RECORD_AUX:
2996 		/*
2997 		 * Record the latest kernel timestamp available in the header
2998 		 * for samples so that synthesised samples occur from this point
2999 		 * onwards.
3000 		 */
3001 		if (sample->time && (sample->time != (u64)-1))
3002 			etm->latest_kernel_timestamp = sample->time;
3003 		break;
3004 
3005 	default:
3006 		break;
3007 	}
3008 
3009 	return 0;
3010 }
3011 
3012 static void dump_queued_data(struct cs_etm_auxtrace *etm,
3013 			     struct perf_record_auxtrace *event)
3014 {
3015 	struct auxtrace_buffer *buf;
3016 	unsigned int i;
3017 	/*
3018 	 * Find all buffers with same reference in the queues and dump them.
3019 	 * This is because the queues can contain multiple entries of the same
3020 	 * buffer that were split on aux records.
3021 	 */
3022 	for (i = 0; i < etm->queues.nr_queues; ++i)
3023 		list_for_each_entry(buf, &etm->queues.queue_array[i].head, list)
3024 			if (buf->reference == event->reference)
3025 				cs_etm__dump_event(etm->queues.queue_array[i].priv, buf);
3026 }
3027 
3028 static int cs_etm__process_auxtrace_event(struct perf_session *session,
3029 					  union perf_event *event,
3030 					  const struct perf_tool *tool __maybe_unused)
3031 {
3032 	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
3033 						   struct cs_etm_auxtrace,
3034 						   auxtrace);
3035 	if (!etm->data_queued) {
3036 		struct auxtrace_buffer *buffer;
3037 		off_t  data_offset;
3038 		int fd = perf_data__fd(session->data);
3039 		bool is_pipe = perf_data__is_pipe(session->data);
3040 		int err;
3041 		int idx = event->auxtrace.idx;
3042 
3043 		if (is_pipe)
3044 			data_offset = 0;
3045 		else {
3046 			data_offset = lseek(fd, 0, SEEK_CUR);
3047 			if (data_offset == -1)
3048 				return -errno;
3049 		}
3050 
3051 		err = auxtrace_queues__add_event(&etm->queues, session,
3052 						 event, data_offset, &buffer);
3053 		if (err)
3054 			return err;
3055 
3056 		if (dump_trace)
3057 			if (auxtrace_buffer__get_data(buffer, fd)) {
3058 				cs_etm__dump_event(etm->queues.queue_array[idx].priv, buffer);
3059 				auxtrace_buffer__put_data(buffer);
3060 			}
3061 	} else if (dump_trace)
3062 		dump_queued_data(etm, &event->auxtrace);
3063 
3064 	return 0;
3065 }
3066 
3067 static void cs_etm__setup_timeless_decoding(struct cs_etm_auxtrace *etm)
3068 {
3069 	/* Take first ETM as all options will be the same for all ETMs */
3070 	u64 *metadata = etm->metadata[0];
3071 
3072 	/* Override timeless mode with user input from --itrace=Z */
3073 	if (etm->synth_opts.timeless_decoding) {
3074 		etm->timeless_decoding = true;
3075 		return;
3076 	}
3077 
3078 	if (metadata[CS_ETM_MAGIC] == __perf_cs_etmv3_magic)
3079 		etm->timeless_decoding = !(metadata[CS_ETM_ETMCR] & ETMCR_TIMESTAMP_EN);
3080 	else
3081 		etm->timeless_decoding = !(metadata[CS_ETMV4_TRCCONFIGR] & TRCCONFIGR_TS);
3082 }
3083 
3084 /*
3085  * Read a single cpu parameter block from the auxtrace_info priv block.
3086  *
3087  * For version 1 there is a per cpu nr_params entry. If we are handling
3088  * version 1 file, then there may be less, the same, or more params
3089  * indicated by this value than the compile time number we understand.
3090  *
3091  * For a version 0 info block, there are a fixed number, and we need to
3092  * fill out the nr_param value in the metadata we create.
3093  */
3094 static u64 *cs_etm__create_meta_blk(u64 *buff_in, int *buff_in_offset,
3095 				    int out_blk_size, int nr_params_v0)
3096 {
3097 	u64 *metadata = NULL;
3098 	int hdr_version;
3099 	int nr_in_params, nr_out_params, nr_cmn_params;
3100 	int i, k;
3101 
3102 	metadata = zalloc(sizeof(*metadata) * out_blk_size);
3103 	if (!metadata)
3104 		return NULL;
3105 
3106 	/* read block current index & version */
3107 	i = *buff_in_offset;
3108 	hdr_version = buff_in[CS_HEADER_VERSION];
3109 
3110 	if (!hdr_version) {
3111 	/* read version 0 info block into a version 1 metadata block  */
3112 		nr_in_params = nr_params_v0;
3113 		metadata[CS_ETM_MAGIC] = buff_in[i + CS_ETM_MAGIC];
3114 		metadata[CS_ETM_CPU] = buff_in[i + CS_ETM_CPU];
3115 		metadata[CS_ETM_NR_TRC_PARAMS] = nr_in_params;
3116 		/* remaining block params at offset +1 from source */
3117 		for (k = CS_ETM_COMMON_BLK_MAX_V1 - 1; k < nr_in_params; k++)
3118 			metadata[k + 1] = buff_in[i + k];
3119 		/* version 0 has 2 common params */
3120 		nr_cmn_params = 2;
3121 	} else {
3122 	/* read version 1 info block - input and output nr_params may differ */
3123 		/* version 1 has 3 common params */
3124 		nr_cmn_params = 3;
3125 		nr_in_params = buff_in[i + CS_ETM_NR_TRC_PARAMS];
3126 
3127 		/* if input has more params than output - skip excess */
3128 		nr_out_params = nr_in_params + nr_cmn_params;
3129 		if (nr_out_params > out_blk_size)
3130 			nr_out_params = out_blk_size;
3131 
3132 		for (k = CS_ETM_MAGIC; k < nr_out_params; k++)
3133 			metadata[k] = buff_in[i + k];
3134 
3135 		/* record the actual nr params we copied */
3136 		metadata[CS_ETM_NR_TRC_PARAMS] = nr_out_params - nr_cmn_params;
3137 	}
3138 
3139 	/* adjust in offset by number of in params used */
3140 	i += nr_in_params + nr_cmn_params;
3141 	*buff_in_offset = i;
3142 	return metadata;
3143 }
3144 
3145 /**
3146  * Puts a fragment of an auxtrace buffer into the auxtrace queues based
3147  * on the bounds of aux_event, if it matches with the buffer that's at
3148  * file_offset.
3149  *
3150  * Normally, whole auxtrace buffers would be added to the queue. But we
3151  * want to reset the decoder for every PERF_RECORD_AUX event, and the decoder
3152  * is reset across each buffer, so splitting the buffers up in advance has
3153  * the same effect.
3154  */
3155 static int cs_etm__queue_aux_fragment(struct perf_session *session, off_t file_offset, size_t sz,
3156 				      struct perf_record_aux *aux_event, struct perf_sample *sample)
3157 {
3158 	int err;
3159 	char buf[PERF_SAMPLE_MAX_SIZE];
3160 	union perf_event *auxtrace_event_union;
3161 	struct perf_record_auxtrace *auxtrace_event;
3162 	union perf_event auxtrace_fragment;
3163 	__u64 aux_offset, aux_size;
3164 	enum cs_etm_format format;
3165 
3166 	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
3167 						   struct cs_etm_auxtrace,
3168 						   auxtrace);
3169 
3170 	/*
3171 	 * There should be a PERF_RECORD_AUXTRACE event at the file_offset that we got
3172 	 * from looping through the auxtrace index.
3173 	 */
3174 	err = perf_session__peek_event(session, file_offset, buf,
3175 				       PERF_SAMPLE_MAX_SIZE, &auxtrace_event_union, NULL);
3176 	if (err)
3177 		return err;
3178 	auxtrace_event = &auxtrace_event_union->auxtrace;
3179 	if (auxtrace_event->header.type != PERF_RECORD_AUXTRACE)
3180 		return -EINVAL;
3181 
3182 	if (auxtrace_event->header.size < sizeof(struct perf_record_auxtrace) ||
3183 		auxtrace_event->header.size != sz) {
3184 		return -EINVAL;
3185 	}
3186 
3187 	/*
3188 	 * In per-thread mode, auxtrace CPU is set to -1, but TID will be set instead. See
3189 	 * auxtrace_mmap_params__set_idx(). However, the sample AUX event will contain a
3190 	 * CPU as we set this always for the AUX_OUTPUT_HW_ID event.
3191 	 * So now compare only TIDs if auxtrace CPU is -1, and CPUs if auxtrace CPU is not -1.
3192 	 * Return 'not found' if mismatch.
3193 	 */
3194 	if (auxtrace_event->cpu == (__u32) -1) {
3195 		etm->per_thread_decoding = true;
3196 		if (auxtrace_event->tid != sample->tid)
3197 			return 1;
3198 	} else if (auxtrace_event->cpu != sample->cpu) {
3199 		if (etm->per_thread_decoding) {
3200 			/*
3201 			 * Found a per-cpu buffer after a per-thread one was
3202 			 * already found
3203 			 */
3204 			pr_err("CS ETM: Inconsistent per-thread/per-cpu mode.\n");
3205 			return -EINVAL;
3206 		}
3207 		return 1;
3208 	}
3209 
3210 	if (aux_event->flags & PERF_AUX_FLAG_OVERWRITE) {
3211 		/*
3212 		 * Clamp size in snapshot mode. The buffer size is clamped in
3213 		 * __auxtrace_mmap__read() for snapshots, so the aux record size doesn't reflect
3214 		 * the buffer size.
3215 		 */
3216 		aux_size = min(aux_event->aux_size, auxtrace_event->size);
3217 
3218 		/*
3219 		 * In this mode, the head also points to the end of the buffer so aux_offset
3220 		 * needs to have the size subtracted so it points to the beginning as in normal mode
3221 		 */
3222 		aux_offset = aux_event->aux_offset - aux_size;
3223 	} else {
3224 		aux_size = aux_event->aux_size;
3225 		aux_offset = aux_event->aux_offset;
3226 	}
3227 
3228 	if (aux_offset >= auxtrace_event->offset &&
3229 	    aux_offset + aux_size <= auxtrace_event->offset + auxtrace_event->size) {
3230 		struct cs_etm_queue *etmq = cs_etm__get_queue(etm, auxtrace_event->cpu);
3231 
3232 		if (!etmq)
3233 			return -EINVAL;
3234 
3235 		/*
3236 		 * If this AUX event was inside this buffer somewhere, create a new auxtrace event
3237 		 * based on the sizes of the aux event, and queue that fragment.
3238 		 */
3239 		auxtrace_fragment.auxtrace = *auxtrace_event;
3240 		auxtrace_fragment.auxtrace.size = aux_size;
3241 		auxtrace_fragment.auxtrace.offset = aux_offset;
3242 		auxtrace_fragment.auxtrace.idx = etmq->queue_nr;
3243 		file_offset += aux_offset - auxtrace_event->offset + auxtrace_event->header.size;
3244 
3245 		pr_debug3("CS ETM: Queue buffer size: %#"PRI_lx64" offset: %#"PRI_lx64
3246 			  " tid: %d cpu: %d\n", aux_size, aux_offset, sample->tid, sample->cpu);
3247 		err = auxtrace_queues__add_event(&etm->queues, session, &auxtrace_fragment,
3248 						 file_offset, NULL);
3249 		if (err)
3250 			return err;
3251 
3252 		format = (aux_event->flags & PERF_AUX_FLAG_CORESIGHT_FORMAT_RAW) ?
3253 				UNFORMATTED : FORMATTED;
3254 		if (etmq->format != UNSET && format != etmq->format) {
3255 			pr_err("CS_ETM: mixed formatted and unformatted trace not supported\n");
3256 			return -EINVAL;
3257 		}
3258 		etmq->format = format;
3259 		return 0;
3260 	}
3261 
3262 	/* Wasn't inside this buffer, but there were no parse errors. 1 == 'not found' */
3263 	return 1;
3264 }
3265 
3266 static int cs_etm__process_aux_hw_id_cb(struct perf_session *session, union perf_event *event,
3267 					u64 offset __maybe_unused, void *data __maybe_unused)
3268 {
3269 	/* look to handle PERF_RECORD_AUX_OUTPUT_HW_ID early to ensure decoders can be set up */
3270 	if (event->header.type == PERF_RECORD_AUX_OUTPUT_HW_ID) {
3271 		(*(int *)data)++; /* increment found count */
3272 		return cs_etm__process_aux_output_hw_id(session, event);
3273 	}
3274 	return 0;
3275 }
3276 
3277 static int cs_etm__queue_aux_records_cb(struct perf_session *session, union perf_event *event,
3278 					u64 offset __maybe_unused, void *data __maybe_unused)
3279 {
3280 	struct perf_sample sample;
3281 	int ret;
3282 	struct auxtrace_index_entry *ent;
3283 	struct auxtrace_index *auxtrace_index;
3284 	struct evsel *evsel;
3285 	size_t i;
3286 
3287 	/* Don't care about any other events, we're only queuing buffers for AUX events */
3288 	if (event->header.type != PERF_RECORD_AUX)
3289 		return 0;
3290 
3291 	if (event->header.size < sizeof(struct perf_record_aux))
3292 		return -EINVAL;
3293 
3294 	/* Truncated Aux records can have 0 size and shouldn't result in anything being queued. */
3295 	if (!event->aux.aux_size)
3296 		return 0;
3297 
3298 	/*
3299 	 * Parse the sample, we need the sample_id_all data that comes after the event so that the
3300 	 * CPU or PID can be matched to an AUXTRACE buffer's CPU or PID.
3301 	 */
3302 	evsel = evlist__event2evsel(session->evlist, event);
3303 	if (!evsel)
3304 		return -EINVAL;
3305 	perf_sample__init(&sample, /*all=*/false);
3306 	ret = evsel__parse_sample(evsel, event, &sample);
3307 	if (ret)
3308 		goto out;
3309 
3310 	/*
3311 	 * Loop through the auxtrace index to find the buffer that matches up with this aux event.
3312 	 */
3313 	list_for_each_entry(auxtrace_index, &session->auxtrace_index, list) {
3314 		for (i = 0; i < auxtrace_index->nr; i++) {
3315 			ent = &auxtrace_index->entries[i];
3316 			ret = cs_etm__queue_aux_fragment(session, ent->file_offset,
3317 							 ent->sz, &event->aux, &sample);
3318 			/*
3319 			 * Stop search on error or successful values. Continue search on
3320 			 * 1 ('not found')
3321 			 */
3322 			if (ret != 1)
3323 				goto out;
3324 		}
3325 	}
3326 
3327 	/*
3328 	 * Couldn't find the buffer corresponding to this aux record, something went wrong. Warn but
3329 	 * don't exit with an error because it will still be possible to decode other aux records.
3330 	 */
3331 	pr_err("CS ETM: Couldn't find auxtrace buffer for aux_offset: %#"PRI_lx64
3332 	       " tid: %d cpu: %d\n", event->aux.aux_offset, sample.tid, sample.cpu);
3333 	ret = 0;
3334 out:
3335 	perf_sample__exit(&sample);
3336 	return ret;
3337 }
3338 
3339 static int cs_etm__queue_aux_records(struct perf_session *session)
3340 {
3341 	struct auxtrace_index *index = list_first_entry_or_null(&session->auxtrace_index,
3342 								struct auxtrace_index, list);
3343 	if (index && index->nr > 0)
3344 		return perf_session__peek_events(session, session->header.data_offset,
3345 						 session->header.data_size,
3346 						 cs_etm__queue_aux_records_cb, NULL);
3347 
3348 	/*
3349 	 * We would get here if there are no entries in the index (either no auxtrace
3350 	 * buffers or no index at all). Fail silently as there is the possibility of
3351 	 * queueing them in cs_etm__process_auxtrace_event() if etm->data_queued is still
3352 	 * false.
3353 	 *
3354 	 * In that scenario, buffers will not be split by AUX records.
3355 	 */
3356 	return 0;
3357 }
3358 
3359 #define HAS_PARAM(j, type, param) (metadata[(j)][CS_ETM_NR_TRC_PARAMS] <= \
3360 				  (CS_##type##_##param - CS_ETM_COMMON_BLK_MAX_V1))
3361 
3362 /*
3363  * Loop through the ETMs and complain if we find at least one where ts_source != 1 (virtual
3364  * timestamps).
3365  */
3366 static bool cs_etm__has_virtual_ts(u64 **metadata, int num_cpu)
3367 {
3368 	int j;
3369 
3370 	for (j = 0; j < num_cpu; j++) {
3371 		switch (metadata[j][CS_ETM_MAGIC]) {
3372 		case __perf_cs_etmv4_magic:
3373 			if (HAS_PARAM(j, ETMV4, TS_SOURCE) || metadata[j][CS_ETMV4_TS_SOURCE] != 1)
3374 				return false;
3375 			break;
3376 		case __perf_cs_ete_magic:
3377 			if (HAS_PARAM(j, ETE, TS_SOURCE) || metadata[j][CS_ETE_TS_SOURCE] != 1)
3378 				return false;
3379 			break;
3380 		default:
3381 			/* Unknown / unsupported magic number. */
3382 			return false;
3383 		}
3384 	}
3385 	return true;
3386 }
3387 
3388 /* map trace ids to correct metadata block, from information in metadata */
3389 static int cs_etm__map_trace_ids_metadata(struct cs_etm_auxtrace *etm, int num_cpu,
3390 					  u64 **metadata)
3391 {
3392 	u64 cs_etm_magic;
3393 	u8 trace_chan_id;
3394 	int i, err;
3395 
3396 	for (i = 0; i < num_cpu; i++) {
3397 		cs_etm_magic = metadata[i][CS_ETM_MAGIC];
3398 		switch (cs_etm_magic) {
3399 		case __perf_cs_etmv3_magic:
3400 			metadata[i][CS_ETM_ETMTRACEIDR] &= CORESIGHT_TRACE_ID_VAL_MASK;
3401 			trace_chan_id = (u8)(metadata[i][CS_ETM_ETMTRACEIDR]);
3402 			break;
3403 		case __perf_cs_etmv4_magic:
3404 		case __perf_cs_ete_magic:
3405 			metadata[i][CS_ETMV4_TRCTRACEIDR] &= CORESIGHT_TRACE_ID_VAL_MASK;
3406 			trace_chan_id = (u8)(metadata[i][CS_ETMV4_TRCTRACEIDR]);
3407 			break;
3408 		default:
3409 			/* unknown magic number */
3410 			return -EINVAL;
3411 		}
3412 		err = cs_etm__map_trace_id_v0(etm, trace_chan_id, metadata[i]);
3413 		if (err)
3414 			return err;
3415 	}
3416 	return 0;
3417 }
3418 
3419 /*
3420  * Use the data gathered by the peeks for HW_ID (trace ID mappings) and AUX
3421  * (formatted or not) packets to create the decoders.
3422  */
3423 static int cs_etm__create_queue_decoders(struct cs_etm_queue *etmq)
3424 {
3425 	struct cs_etm_decoder_params d_params;
3426 	struct cs_etm_trace_params  *t_params;
3427 	int decoders = intlist__nr_entries(etmq->traceid_list);
3428 
3429 	if (decoders == 0)
3430 		return 0;
3431 
3432 	/*
3433 	 * Each queue can only contain data from one CPU when unformatted, so only one decoder is
3434 	 * needed.
3435 	 */
3436 	if (etmq->format == UNFORMATTED)
3437 		assert(decoders == 1);
3438 
3439 	/* Use metadata to fill in trace parameters for trace decoder */
3440 	t_params = zalloc(sizeof(*t_params) * decoders);
3441 
3442 	if (!t_params)
3443 		goto out_free;
3444 
3445 	if (cs_etm__init_trace_params(t_params, etmq))
3446 		goto out_free;
3447 
3448 	/* Set decoder parameters to decode trace packets */
3449 	if (cs_etm__init_decoder_params(&d_params, etmq,
3450 					dump_trace ? CS_ETM_OPERATION_PRINT :
3451 						     CS_ETM_OPERATION_DECODE))
3452 		goto out_free;
3453 
3454 	etmq->decoder = cs_etm_decoder__new(decoders, &d_params,
3455 					    t_params);
3456 
3457 	if (!etmq->decoder)
3458 		goto out_free;
3459 
3460 	/*
3461 	 * Register a function to handle all memory accesses required by
3462 	 * the trace decoder library.
3463 	 */
3464 	if (cs_etm_decoder__add_mem_access_cb(etmq->decoder,
3465 					      0x0L, ((u64) -1L),
3466 					      cs_etm__decoder_mem_access))
3467 		goto out_free_decoder;
3468 
3469 	zfree(&t_params);
3470 	return 0;
3471 
3472 out_free_decoder:
3473 	cs_etm_decoder__free(etmq->decoder);
3474 out_free:
3475 	zfree(&t_params);
3476 	return -EINVAL;
3477 }
3478 
3479 static int cs_etm__create_decoders(struct cs_etm_auxtrace *etm)
3480 {
3481 	struct auxtrace_queues *queues = &etm->queues;
3482 
3483 	for (unsigned int i = 0; i < queues->nr_queues; i++) {
3484 		bool empty = list_empty(&queues->queue_array[i].head);
3485 		struct cs_etm_queue *etmq = queues->queue_array[i].priv;
3486 		int ret;
3487 
3488 		/*
3489 		 * Don't create decoders for empty queues, mainly because
3490 		 * etmq->format is unknown for empty queues.
3491 		 */
3492 		assert(empty || etmq->format != UNSET);
3493 		if (empty)
3494 			continue;
3495 
3496 		ret = cs_etm__create_queue_decoders(etmq);
3497 		if (ret)
3498 			return ret;
3499 	}
3500 	return 0;
3501 }
3502 
3503 int cs_etm__process_auxtrace_info_full(union perf_event *event,
3504 				       struct perf_session *session)
3505 {
3506 	struct perf_record_auxtrace_info *auxtrace_info = &event->auxtrace_info;
3507 	struct cs_etm_auxtrace *etm = NULL;
3508 	struct perf_record_time_conv *tc = &session->time_conv;
3509 	int event_header_size = sizeof(struct perf_event_header);
3510 	int total_size = auxtrace_info->header.size;
3511 	int priv_size = 0;
3512 	int num_cpu, max_cpu = 0;
3513 	int err = 0;
3514 	int aux_hw_id_found;
3515 	int i;
3516 	u64 *ptr = NULL;
3517 	u64 **metadata = NULL;
3518 
3519 	/* First the global part */
3520 	ptr = (u64 *) auxtrace_info->priv;
3521 	num_cpu = ptr[CS_PMU_TYPE_CPUS] & 0xffffffff;
3522 
3523 	/*
3524 	 * Bound num_cpu by the event size: the global header consumes
3525 	 * CS_ETM_HEADER_SIZE bytes, and each CPU needs at least one u64
3526 	 * metadata entry after that.
3527 	 */
3528 	priv_size = total_size - event_header_size - INFO_HEADER_SIZE -
3529 		    CS_ETM_HEADER_SIZE;
3530 	if (num_cpu <= 0 || priv_size <= 0 ||
3531 	    num_cpu > priv_size / (int)sizeof(u64))
3532 		return -EINVAL;
3533 
3534 	metadata = zalloc(sizeof(*metadata) * num_cpu);
3535 	if (!metadata)
3536 		return -ENOMEM;
3537 
3538 	/* Start parsing after the common part of the header */
3539 	i = CS_HEADER_VERSION_MAX;
3540 
3541 	/*
3542 	 * The metadata is stored in the auxtrace_info section and encodes
3543 	 * the configuration of the ARM embedded trace macrocell which is
3544 	 * required by the trace decoder to properly decode the trace due
3545 	 * to its highly compressed nature.
3546 	 */
3547 	for (int j = 0; j < num_cpu; j++) {
3548 		if (ptr[i] == __perf_cs_etmv3_magic) {
3549 			metadata[j] =
3550 				cs_etm__create_meta_blk(ptr, &i,
3551 							CS_ETM_PRIV_MAX,
3552 							CS_ETM_NR_TRC_PARAMS_V0);
3553 		} else if (ptr[i] == __perf_cs_etmv4_magic) {
3554 			metadata[j] =
3555 				cs_etm__create_meta_blk(ptr, &i,
3556 							CS_ETMV4_PRIV_MAX,
3557 							CS_ETMV4_NR_TRC_PARAMS_V0);
3558 		} else if (ptr[i] == __perf_cs_ete_magic) {
3559 			metadata[j] = cs_etm__create_meta_blk(ptr, &i, CS_ETE_PRIV_MAX, -1);
3560 		} else {
3561 			ui__error("CS ETM Trace: Unrecognised magic number %#"PRIx64". File could be from a newer version of perf.\n",
3562 				  ptr[i]);
3563 			err = -EINVAL;
3564 			goto err_free_metadata;
3565 		}
3566 
3567 		if (!metadata[j]) {
3568 			err = -ENOMEM;
3569 			goto err_free_metadata;
3570 		}
3571 
3572 		/* CPU id comes from perf.data and must fit max_cpu + 1 without overflow */
3573 		if (metadata[j][CS_ETM_CPU] >= INT_MAX) {
3574 			err = -EINVAL;
3575 			goto err_free_metadata;
3576 		}
3577 
3578 		if ((int)metadata[j][CS_ETM_CPU] > max_cpu)
3579 			max_cpu = metadata[j][CS_ETM_CPU];
3580 	}
3581 
3582 	/*
3583 	 * Each of CS_HEADER_VERSION_MAX, CS_ETM_PRIV_MAX and
3584 	 * CS_ETMV4_PRIV_MAX mark how many double words are in the
3585 	 * global metadata, and each cpu's metadata respectively.
3586 	 * The following tests if the correct number of double words was
3587 	 * present in the auxtrace info section.
3588 	 */
3589 	priv_size = total_size - event_header_size - INFO_HEADER_SIZE;
3590 	if (i * 8 != priv_size) {
3591 		err = -EINVAL;
3592 		goto err_free_metadata;
3593 	}
3594 
3595 	etm = zalloc(sizeof(*etm));
3596 
3597 	if (!etm) {
3598 		err = -ENOMEM;
3599 		goto err_free_metadata;
3600 	}
3601 
3602 	/*
3603 	 * As all the ETMs run at the same exception level, the system should
3604 	 * have the same PID format crossing CPUs.  So cache the PID format
3605 	 * and reuse it for sequential decoding.
3606 	 */
3607 	etm->pid_fmt = cs_etm__init_pid_fmt(metadata[0]);
3608 
3609 	err = auxtrace_queues__init_nr(&etm->queues, max_cpu + 1);
3610 	if (err)
3611 		goto err_free_etm;
3612 
3613 	for (unsigned int j = 0; j < etm->queues.nr_queues; ++j) {
3614 		err = cs_etm__setup_queue(etm, &etm->queues.queue_array[j], j);
3615 		if (err)
3616 			goto err_free_queues;
3617 	}
3618 
3619 	if (session->itrace_synth_opts->set) {
3620 		etm->synth_opts = *session->itrace_synth_opts;
3621 	} else {
3622 		itrace_synth_opts__set_default(&etm->synth_opts,
3623 				session->itrace_synth_opts->default_no_sample);
3624 		etm->synth_opts.callchain = false;
3625 		etm->synth_opts.thread_stack = session->itrace_synth_opts->thread_stack;
3626 	}
3627 
3628 	if (etm->synth_opts.calls)
3629 		etm->branches_filter |= PERF_IP_FLAG_CALL |
3630 					PERF_IP_FLAG_TRACE_BEGIN |
3631 					PERF_IP_FLAG_TRACE_END;
3632 
3633 	if (etm->synth_opts.returns)
3634 		etm->branches_filter |= PERF_IP_FLAG_RETURN |
3635 					PERF_IP_FLAG_TRACE_BEGIN |
3636 					PERF_IP_FLAG_TRACE_END;
3637 
3638 	if (etm->synth_opts.callchain && !symbol_conf.use_callchain) {
3639 		symbol_conf.use_callchain = true;
3640 		if (callchain_register_param(&callchain_param) < 0) {
3641 			symbol_conf.use_callchain = false;
3642 			etm->synth_opts.callchain = false;
3643 		}
3644 	}
3645 
3646 	etm->session = session;
3647 
3648 	etm->num_cpu = num_cpu;
3649 	etm->pmu_type = (unsigned int) ((ptr[CS_PMU_TYPE_CPUS] >> 32) & 0xffffffff);
3650 	etm->snapshot_mode = (ptr[CS_ETM_SNAPSHOT] != 0);
3651 	etm->metadata = metadata;
3652 	etm->auxtrace_type = auxtrace_info->type;
3653 
3654 	if (etm->synth_opts.use_timestamp)
3655 		/*
3656 		 * Prior to Armv8.4, Arm CPUs don't support FEAT_TRF feature,
3657 		 * therefore the decoder cannot know if the timestamp trace is
3658 		 * same with the kernel time.
3659 		 *
3660 		 * If a user has knowledge for the working platform and can
3661 		 * specify itrace option 'T' to tell decoder to forcely use the
3662 		 * traced timestamp as the kernel time.
3663 		 */
3664 		etm->has_virtual_ts = true;
3665 	else
3666 		/* Use virtual timestamps if all ETMs report ts_source = 1 */
3667 		etm->has_virtual_ts = cs_etm__has_virtual_ts(metadata, num_cpu);
3668 
3669 	if (!etm->has_virtual_ts)
3670 		ui__warning("Virtual timestamps are not enabled, or not supported by the traced system.\n"
3671 			    "The time field of the samples will not be set accurately.\n"
3672 			    "For Arm CPUs prior to Armv8.4 or without support FEAT_TRF,\n"
3673 			    "you can specify the itrace option 'T' for timestamp decoding\n"
3674 			    "if the Coresight timestamp on the platform is same with the kernel time.\n\n");
3675 
3676 	etm->auxtrace.process_event = cs_etm__process_event;
3677 	etm->auxtrace.process_auxtrace_event = cs_etm__process_auxtrace_event;
3678 	etm->auxtrace.flush_events = cs_etm__flush_events;
3679 	etm->auxtrace.free_events = cs_etm__free_events;
3680 	etm->auxtrace.free = cs_etm__free;
3681 	etm->auxtrace.evsel_is_auxtrace = cs_etm__evsel_is_auxtrace;
3682 	session->auxtrace = &etm->auxtrace;
3683 
3684 	cs_etm__setup_timeless_decoding(etm);
3685 
3686 	etm->tc.time_shift = tc->time_shift;
3687 	etm->tc.time_mult = tc->time_mult;
3688 	etm->tc.time_zero = tc->time_zero;
3689 	if (event_contains(*tc, cap_user_time_short)) {
3690 		etm->tc.time_cycles = tc->time_cycles;
3691 		etm->tc.time_mask = tc->time_mask;
3692 		etm->tc.cap_user_time_zero = tc->cap_user_time_zero;
3693 		etm->tc.cap_user_time_short = tc->cap_user_time_short;
3694 	}
3695 
3696 	etm->use_thread_stack = etm->synth_opts.thread_stack ||
3697 				etm->synth_opts.last_branch ||
3698 				etm->synth_opts.callchain;
3699 
3700 	etm->use_callchain = etm->synth_opts.thread_stack ||
3701 			     etm->synth_opts.callchain;
3702 
3703 	err = cs_etm__synth_events(etm, session);
3704 	if (err)
3705 		goto err_free_queues;
3706 
3707 	err = cs_etm__queue_aux_records(session);
3708 	if (err)
3709 		goto err_free_queues;
3710 
3711 	/*
3712 	 * Map Trace ID values to CPU metadata.
3713 	 *
3714 	 * Trace metadata will always contain Trace ID values from the legacy algorithm
3715 	 * in case it's read by a version of Perf that doesn't know about HW_ID packets
3716 	 * or the kernel doesn't emit them.
3717 	 *
3718 	 * The updated kernel drivers that use AUX_HW_ID to sent Trace IDs will attempt to use
3719 	 * the same IDs as the old algorithm as far as is possible, unless there are clashes
3720 	 * in which case a different value will be used. This means an older perf may still
3721 	 * be able to record and read files generate on a newer system.
3722 	 *
3723 	 * For a perf able to interpret AUX_HW_ID packets we first check for the presence of
3724 	 * those packets. If they are there then the values will be mapped and plugged into
3725 	 * the metadata and decoders are only created for each mapping received.
3726 	 *
3727 	 * If no AUX_HW_ID packets are present - which means a file recorded on an old kernel
3728 	 * then we map Trace ID values to CPU directly from the metadata and create decoders
3729 	 * for all mappings.
3730 	 */
3731 
3732 	/* Scan for AUX_OUTPUT_HW_ID records to map trace ID values to CPU metadata */
3733 	aux_hw_id_found = 0;
3734 	err = perf_session__peek_events(session, session->header.data_offset,
3735 					session->header.data_size,
3736 					cs_etm__process_aux_hw_id_cb, &aux_hw_id_found);
3737 	if (err)
3738 		goto err_free_queues;
3739 
3740 	/* if no HW ID found this is a file with metadata values only, map from metadata */
3741 	if (!aux_hw_id_found) {
3742 		err = cs_etm__map_trace_ids_metadata(etm, num_cpu, metadata);
3743 		if (err)
3744 			goto err_free_queues;
3745 	}
3746 
3747 	err = cs_etm__create_decoders(etm);
3748 	if (err)
3749 		goto err_free_queues;
3750 
3751 	etm->data_queued = etm->queues.populated;
3752 	return 0;
3753 
3754 err_free_queues:
3755 	auxtrace_queues__free(&etm->queues);
3756 	session->auxtrace = NULL;
3757 err_free_etm:
3758 	zfree(&etm);
3759 err_free_metadata:
3760 	/* No need to check @metadata[j], free(NULL) is supported */
3761 	for (int j = 0; j < num_cpu; j++)
3762 		zfree(&metadata[j]);
3763 	zfree(&metadata);
3764 	return err;
3765 }
3766