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