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