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