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