cs-etm.c 85.6 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6 7 8 9
/*
 * Copyright(C) 2015-2018 Linaro Limited.
 *
 * Author: Tor Jeremiassen <tor@ti.com>
 * Author: Mathieu Poirier <mathieu.poirier@linaro.org>
 */

#include <linux/bitops.h>
10
#include <linux/coresight-pmu.h>
11 12 13 14
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/types.h>
15
#include <linux/zalloc.h>
16

17
#include <opencsd/ocsd_if_types.h>
18 19 20 21 22
#include <stdlib.h>

#include "auxtrace.h"
#include "color.h"
#include "cs-etm.h"
23
#include "cs-etm-decoder/cs-etm-decoder.h"
24
#include "debug.h"
25
#include "dso.h"
26 27 28 29 30
#include "evlist.h"
#include "intlist.h"
#include "machine.h"
#include "map.h"
#include "perf.h"
31
#include "session.h"
32 33
#include "map_symbol.h"
#include "branch.h"
34
#include "symbol.h"
35
#include "tool.h"
36 37
#include "thread.h"
#include "thread-stack.h"
38
#include <tools/libc_compat.h>
39
#include "util/synthetic-events.h"
40 41 42 43 44 45 46 47 48 49 50 51 52 53

struct cs_etm_auxtrace {
	struct auxtrace auxtrace;
	struct auxtrace_queues queues;
	struct auxtrace_heap heap;
	struct itrace_synth_opts synth_opts;
	struct perf_session *session;
	struct machine *machine;
	struct thread *unknown_thread;

	u8 timeless_decoding;
	u8 snapshot_mode;
	u8 data_queued;
	u8 sample_branches;
54
	u8 sample_instructions;
55 56

	int num_cpu;
57
	u64 latest_kernel_timestamp;
58 59 60
	u32 auxtrace_type;
	u64 branches_sample_type;
	u64 branches_id;
61 62 63
	u64 instructions_sample_type;
	u64 instructions_sample_period;
	u64 instructions_id;
64 65 66 67
	u64 **metadata;
	unsigned int pmu_type;
};

68 69
struct cs_etm_traceid_queue {
	u8 trace_chan_id;
70
	pid_t pid, tid;
71 72 73
	u64 period_instructions;
	size_t last_branch_pos;
	union perf_event *event_buf;
74
	struct thread *thread;
75 76 77 78 79 80 81
	struct branch_stack *last_branch;
	struct branch_stack *last_branch_rb;
	struct cs_etm_packet *prev_packet;
	struct cs_etm_packet *packet;
	struct cs_etm_packet_queue packet_queue;
};

82 83 84 85 86
struct cs_etm_queue {
	struct cs_etm_auxtrace *etm;
	struct cs_etm_decoder *decoder;
	struct auxtrace_buffer *buffer;
	unsigned int queue_nr;
87
	u8 pending_timestamp_chan_id;
88
	u64 offset;
89 90
	const unsigned char *buf;
	size_t buf_len, buf_used;
91 92 93
	/* Conversion between traceID and index in traceid_queues array */
	struct intlist *traceid_queues_list;
	struct cs_etm_traceid_queue **traceid_queues;
94 95
};

96 97 98
/* RB tree for quick conversion between traceID and metadata pointers */
static struct intlist *traceid_list;

99
static int cs_etm__process_queues(struct cs_etm_auxtrace *etm);
100
static int cs_etm__process_timeless_queues(struct cs_etm_auxtrace *etm,
101
					   pid_t tid);
102 103
static int cs_etm__get_data_block(struct cs_etm_queue *etmq);
static int cs_etm__decode_data_block(struct cs_etm_queue *etmq);
104

105 106 107
/* PTMs ETMIDR [11:8] set to b0011 */
#define ETMIDR_PTM_VERSION 0x00000300

108 109 110 111 112 113
/*
 * A struct auxtrace_heap_item only has a queue_nr and a timestamp to
 * work with.  One option is to modify to auxtrace_heap_XYZ() API or simply
 * encode the etm queue number as the upper 16 bit and the channel as
 * the lower 16 bit.
 */
114
#define TO_CS_QUEUE_NR(queue_nr, trace_chan_id)	\
115 116 117 118
		      (queue_nr << 16 | trace_chan_id)
#define TO_QUEUE_NR(cs_queue_nr) (cs_queue_nr >> 16)
#define TO_TRACE_CHAN_ID(cs_queue_nr) (cs_queue_nr & 0x0000ffff)

119 120 121 122 123 124 125 126 127 128
static u32 cs_etm__get_v7_protocol_version(u32 etmidr)
{
	etmidr &= ETMIDR_PTM_VERSION;

	if (etmidr == ETMIDR_PTM_VERSION)
		return CS_ETM_PROTO_PTM;

	return CS_ETM_PROTO_ETMV3;
}

129 130 131 132 133 134 135 136 137 138 139 140 141 142
static int cs_etm__get_magic(u8 trace_chan_id, u64 *magic)
{
	struct int_node *inode;
	u64 *metadata;

	inode = intlist__find(traceid_list, trace_chan_id);
	if (!inode)
		return -EINVAL;

	metadata = inode->priv;
	*magic = metadata[CS_ETM_MAGIC];
	return 0;
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156
int cs_etm__get_cpu(u8 trace_chan_id, int *cpu)
{
	struct int_node *inode;
	u64 *metadata;

	inode = intlist__find(traceid_list, trace_chan_id);
	if (!inode)
		return -EINVAL;

	metadata = inode->priv;
	*cpu = (int)metadata[CS_ETM_CPU];
	return 0;
}

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
/*
 * The returned PID format is presented by two bits:
 *
 *   Bit ETM_OPT_CTXTID: CONTEXTIDR or CONTEXTIDR_EL1 is traced;
 *   Bit ETM_OPT_CTXTID2: CONTEXTIDR_EL2 is traced.
 *
 * It's possible that the two bits ETM_OPT_CTXTID and ETM_OPT_CTXTID2
 * are enabled at the same time when the session runs on an EL2 kernel.
 * This means the CONTEXTIDR_EL1 and CONTEXTIDR_EL2 both will be
 * recorded in the trace data, the tool will selectively use
 * CONTEXTIDR_EL2 as PID.
 */
int cs_etm__get_pid_fmt(u8 trace_chan_id, u64 *pid_fmt)
{
	struct int_node *inode;
	u64 *metadata, val;

	inode = intlist__find(traceid_list, trace_chan_id);
	if (!inode)
		return -EINVAL;

	metadata = inode->priv;

	if (metadata[CS_ETM_MAGIC] == __perf_cs_etmv3_magic) {
		val = metadata[CS_ETM_ETMCR];
		/* CONTEXTIDR is traced */
		if (val & BIT(ETM_OPT_CTXTID))
			*pid_fmt = BIT(ETM_OPT_CTXTID);
	} else {
		val = metadata[CS_ETMV4_TRCCONFIGR];
		/* CONTEXTIDR_EL2 is traced */
		if (val & (BIT(ETM4_CFG_BIT_VMID) | BIT(ETM4_CFG_BIT_VMID_OPT)))
			*pid_fmt = BIT(ETM_OPT_CTXTID2);
		/* CONTEXTIDR_EL1 is traced */
		else if (val & BIT(ETM4_CFG_BIT_CTXTID))
			*pid_fmt = BIT(ETM_OPT_CTXTID);
	}

	return 0;
}

198 199 200 201
void cs_etm__etmq_set_traceid_queue_timestamp(struct cs_etm_queue *etmq,
					      u8 trace_chan_id)
{
	/*
202
	 * When a timestamp packet is encountered the backend code
203 204 205 206 207
	 * is stopped so that the front end has time to process packets
	 * that were accumulated in the traceID queue.  Since there can
	 * be more than one channel per cs_etm_queue, we need to specify
	 * what traceID queue needs servicing.
	 */
208
	etmq->pending_timestamp_chan_id = trace_chan_id;
209 210
}

211 212 213 214 215
static u64 cs_etm__etmq_get_timestamp(struct cs_etm_queue *etmq,
				      u8 *trace_chan_id)
{
	struct cs_etm_packet_queue *packet_queue;

216
	if (!etmq->pending_timestamp_chan_id)
217 218 219
		return 0;

	if (trace_chan_id)
220
		*trace_chan_id = etmq->pending_timestamp_chan_id;
221 222

	packet_queue = cs_etm__etmq_get_packet_queue(etmq,
223
						     etmq->pending_timestamp_chan_id);
224 225 226 227
	if (!packet_queue)
		return 0;

	/* Acknowledge pending status */
228
	etmq->pending_timestamp_chan_id = 0;
229 230

	/* See function cs_etm_decoder__do_{hard|soft}_timestamp() */
231
	return packet_queue->cs_timestamp;
232 233
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
static void cs_etm__clear_packet_queue(struct cs_etm_packet_queue *queue)
{
	int i;

	queue->head = 0;
	queue->tail = 0;
	queue->packet_count = 0;
	for (i = 0; i < CS_ETM_PACKET_MAX_BUFFER; i++) {
		queue->packet_buffer[i].isa = CS_ETM_ISA_UNKNOWN;
		queue->packet_buffer[i].start_addr = CS_ETM_INVAL_ADDR;
		queue->packet_buffer[i].end_addr = CS_ETM_INVAL_ADDR;
		queue->packet_buffer[i].instr_count = 0;
		queue->packet_buffer[i].last_instr_taken_branch = false;
		queue->packet_buffer[i].last_instr_size = 0;
		queue->packet_buffer[i].last_instr_type = 0;
		queue->packet_buffer[i].last_instr_subtype = 0;
		queue->packet_buffer[i].last_instr_cond = 0;
		queue->packet_buffer[i].flags = 0;
		queue->packet_buffer[i].exception_number = UINT32_MAX;
		queue->packet_buffer[i].trace_chan_id = UINT8_MAX;
		queue->packet_buffer[i].cpu = INT_MIN;
	}
}

258 259 260 261 262 263 264 265 266 267 268 269 270 271
static void cs_etm__clear_all_packet_queues(struct cs_etm_queue *etmq)
{
	int idx;
	struct int_node *inode;
	struct cs_etm_traceid_queue *tidq;
	struct intlist *traceid_queues_list = etmq->traceid_queues_list;

	intlist__for_each_entry(inode, traceid_queues_list) {
		idx = (int)(intptr_t)inode->priv;
		tidq = etmq->traceid_queues[idx];
		cs_etm__clear_packet_queue(&tidq->packet_queue);
	}
}

272 273 274 275 276
static int cs_etm__init_traceid_queue(struct cs_etm_queue *etmq,
				      struct cs_etm_traceid_queue *tidq,
				      u8 trace_chan_id)
{
	int rc = -ENOMEM;
277
	struct auxtrace_queue *queue;
278 279 280 281
	struct cs_etm_auxtrace *etm = etmq->etm;

	cs_etm__clear_packet_queue(&tidq->packet_queue);

282 283 284
	queue = &etmq->etm->queues.queue_array[etmq->queue_nr];
	tidq->tid = queue->tid;
	tidq->pid = -1;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	tidq->trace_chan_id = trace_chan_id;

	tidq->packet = zalloc(sizeof(struct cs_etm_packet));
	if (!tidq->packet)
		goto out;

	tidq->prev_packet = zalloc(sizeof(struct cs_etm_packet));
	if (!tidq->prev_packet)
		goto out_free;

	if (etm->synth_opts.last_branch) {
		size_t sz = sizeof(struct branch_stack);

		sz += etm->synth_opts.last_branch_sz *
		      sizeof(struct branch_entry);
		tidq->last_branch = zalloc(sz);
		if (!tidq->last_branch)
			goto out_free;
		tidq->last_branch_rb = zalloc(sz);
		if (!tidq->last_branch_rb)
			goto out_free;
	}

	tidq->event_buf = malloc(PERF_SAMPLE_MAX_SIZE);
	if (!tidq->event_buf)
		goto out_free;

	return 0;

out_free:
	zfree(&tidq->last_branch_rb);
	zfree(&tidq->last_branch);
	zfree(&tidq->prev_packet);
	zfree(&tidq->packet);
out:
	return rc;
}

static struct cs_etm_traceid_queue
*cs_etm__etmq_get_traceid_queue(struct cs_etm_queue *etmq, u8 trace_chan_id)
{
326 327 328 329
	int idx;
	struct int_node *inode;
	struct intlist *traceid_queues_list;
	struct cs_etm_traceid_queue *tidq, **traceid_queues;
330 331
	struct cs_etm_auxtrace *etm = etmq->etm;

332 333
	if (etm->timeless_decoding)
		trace_chan_id = CS_ETM_PER_THREAD_TRACEID;
334

335
	traceid_queues_list = etmq->traceid_queues_list;
336

337 338 339 340 341 342 343 344 345
	/*
	 * Check if the traceid_queue exist for this traceID by looking
	 * in the queue list.
	 */
	inode = intlist__find(traceid_queues_list, trace_chan_id);
	if (inode) {
		idx = (int)(intptr_t)inode->priv;
		return etmq->traceid_queues[idx];
	}
346

347
	/* We couldn't find a traceid_queue for this traceID, allocate one */
348 349 350 351 352 353
	tidq = malloc(sizeof(*tidq));
	if (!tidq)
		return NULL;

	memset(tidq, 0, sizeof(*tidq));

354 355 356 357 358 359 360 361 362 363
	/* Get a valid index for the new traceid_queue */
	idx = intlist__nr_entries(traceid_queues_list);
	/* Memory for the inode is free'ed in cs_etm_free_traceid_queues () */
	inode = intlist__findnew(traceid_queues_list, trace_chan_id);
	if (!inode)
		goto out_free;

	/* Associate this traceID with this index */
	inode->priv = (void *)(intptr_t)idx;

364 365 366
	if (cs_etm__init_traceid_queue(etmq, tidq, trace_chan_id))
		goto out_free;

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	/* Grow the traceid_queues array by one unit */
	traceid_queues = etmq->traceid_queues;
	traceid_queues = reallocarray(traceid_queues,
				      idx + 1,
				      sizeof(*traceid_queues));

	/*
	 * On failure reallocarray() returns NULL and the original block of
	 * memory is left untouched.
	 */
	if (!traceid_queues)
		goto out_free;

	traceid_queues[idx] = tidq;
	etmq->traceid_queues = traceid_queues;
382

383
	return etmq->traceid_queues[idx];
384 385

out_free:
386 387 388 389 390
	/*
	 * Function intlist__remove() removes the inode from the list
	 * and delete the memory associated to it.
	 */
	intlist__remove(traceid_queues_list, inode);
391 392 393 394 395
	free(tidq);

	return NULL;
}

396
struct cs_etm_packet_queue
397
*cs_etm__etmq_get_packet_queue(struct cs_etm_queue *etmq, u8 trace_chan_id)
398
{
399 400 401 402 403 404 405
	struct cs_etm_traceid_queue *tidq;

	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
	if (tidq)
		return &tidq->packet_queue;

	return NULL;
406 407
}

408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
static void cs_etm__packet_swap(struct cs_etm_auxtrace *etm,
				struct cs_etm_traceid_queue *tidq)
{
	struct cs_etm_packet *tmp;

	if (etm->sample_branches || etm->synth_opts.last_branch ||
	    etm->sample_instructions) {
		/*
		 * Swap PACKET with PREV_PACKET: PACKET becomes PREV_PACKET for
		 * the next incoming packet.
		 */
		tmp = tidq->packet;
		tidq->packet = tidq->prev_packet;
		tidq->prev_packet = tmp;
	}
}

425 426 427 428 429 430 431 432 433 434 435 436 437
static void cs_etm__packet_dump(const char *pkt_string)
{
	const char *color = PERF_COLOR_BLUE;
	int len = strlen(pkt_string);

	if (len && (pkt_string[len-1] == '\n'))
		color_fprintf(stdout, color, "	%s", pkt_string);
	else
		color_fprintf(stdout, color, "	%s\n", pkt_string);

	fflush(stdout);
}

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
static void cs_etm__set_trace_param_etmv3(struct cs_etm_trace_params *t_params,
					  struct cs_etm_auxtrace *etm, int idx,
					  u32 etmidr)
{
	u64 **metadata = etm->metadata;

	t_params[idx].protocol = cs_etm__get_v7_protocol_version(etmidr);
	t_params[idx].etmv3.reg_ctrl = metadata[idx][CS_ETM_ETMCR];
	t_params[idx].etmv3.reg_trc_id = metadata[idx][CS_ETM_ETMTRACEIDR];
}

static void cs_etm__set_trace_param_etmv4(struct cs_etm_trace_params *t_params,
					  struct cs_etm_auxtrace *etm, int idx)
{
	u64 **metadata = etm->metadata;

	t_params[idx].protocol = CS_ETM_PROTO_ETMV4i;
	t_params[idx].etmv4.reg_idr0 = metadata[idx][CS_ETMV4_TRCIDR0];
	t_params[idx].etmv4.reg_idr1 = metadata[idx][CS_ETMV4_TRCIDR1];
	t_params[idx].etmv4.reg_idr2 = metadata[idx][CS_ETMV4_TRCIDR2];
	t_params[idx].etmv4.reg_idr8 = metadata[idx][CS_ETMV4_TRCIDR8];
	t_params[idx].etmv4.reg_configr = metadata[idx][CS_ETMV4_TRCCONFIGR];
	t_params[idx].etmv4.reg_traceidr = metadata[idx][CS_ETMV4_TRCTRACEIDR];
}

static int cs_etm__init_trace_params(struct cs_etm_trace_params *t_params,
464 465
				     struct cs_etm_auxtrace *etm,
				     int decoders)
466 467 468 469 470
{
	int i;
	u32 etmidr;
	u64 architecture;

471
	for (i = 0; i < decoders; i++) {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
		architecture = etm->metadata[i][CS_ETM_MAGIC];

		switch (architecture) {
		case __perf_cs_etmv3_magic:
			etmidr = etm->metadata[i][CS_ETM_ETMIDR];
			cs_etm__set_trace_param_etmv3(t_params, etm, i, etmidr);
			break;
		case __perf_cs_etmv4_magic:
			cs_etm__set_trace_param_etmv4(t_params, etm, i);
			break;
		default:
			return -EINVAL;
		}
	}

	return 0;
}

490 491
static int cs_etm__init_decoder_params(struct cs_etm_decoder_params *d_params,
				       struct cs_etm_queue *etmq,
492 493
				       enum cs_etm_decoder_operation mode,
				       bool formatted)
494 495 496 497 498 499 500 501 502
{
	int ret = -EINVAL;

	if (!(mode < CS_ETM_OPERATION_MAX))
		goto out;

	d_params->packet_printer = cs_etm__packet_dump;
	d_params->operation = mode;
	d_params->data = etmq;
503
	d_params->formatted = formatted;
504 505 506 507 508 509 510 511 512
	d_params->fsyncs = false;
	d_params->hsyncs = false;
	d_params->frame_aligned = true;

	ret = 0;
out:
	return ret;
}

513
static void cs_etm__dump_event(struct cs_etm_queue *etmq,
514 515
			       struct auxtrace_buffer *buffer)
{
516
	int ret;
517 518 519 520 521 522 523 524 525 526 527 528
	const char *color = PERF_COLOR_BLUE;
	size_t buffer_used = 0;

	fprintf(stdout, "\n");
	color_fprintf(stdout, color,
		     ". ... CoreSight ETM Trace data: size %zu bytes\n",
		     buffer->size);

	do {
		size_t consumed;

		ret = cs_etm_decoder__process_data_block(
529
				etmq->decoder, buffer->offset,
530 531 532 533 534 535 536 537
				&((u8 *)buffer->data)[buffer_used],
				buffer->size - buffer_used, &consumed);
		if (ret)
			break;

		buffer_used += consumed;
	} while (buffer_used < buffer->size);

538
	cs_etm_decoder__reset(etmq->decoder);
539 540
}

541 542 543
static int cs_etm__flush_events(struct perf_session *session,
				struct perf_tool *tool)
{
544 545 546 547 548 549 550 551 552
	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);
	if (dump_trace)
		return 0;

	if (!tool->ordered_events)
		return -EINVAL;

553 554 555 556
	if (etm->timeless_decoding)
		return cs_etm__process_timeless_queues(etm, -1);

	return cs_etm__process_queues(etm);
557 558
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
static void cs_etm__free_traceid_queues(struct cs_etm_queue *etmq)
{
	int idx;
	uintptr_t priv;
	struct int_node *inode, *tmp;
	struct cs_etm_traceid_queue *tidq;
	struct intlist *traceid_queues_list = etmq->traceid_queues_list;

	intlist__for_each_entry_safe(inode, tmp, traceid_queues_list) {
		priv = (uintptr_t)inode->priv;
		idx = priv;

		/* Free this traceid_queue from the array */
		tidq = etmq->traceid_queues[idx];
		thread__zput(tidq->thread);
		zfree(&tidq->event_buf);
		zfree(&tidq->last_branch);
		zfree(&tidq->last_branch_rb);
		zfree(&tidq->prev_packet);
		zfree(&tidq->packet);
		zfree(&tidq);

		/*
		 * Function intlist__remove() removes the inode from the list
		 * and delete the memory associated to it.
		 */
		intlist__remove(traceid_queues_list, inode);
	}

	/* Then the RB tree itself */
	intlist__delete(traceid_queues_list);
	etmq->traceid_queues_list = NULL;

	/* finally free the traceid_queues array */
593
	zfree(&etmq->traceid_queues);
594 595
}

596 597 598 599
static void cs_etm__free_queue(void *priv)
{
	struct cs_etm_queue *etmq = priv;

600 601 602 603
	if (!etmq)
		return;

	cs_etm_decoder__free(etmq->decoder);
604
	cs_etm__free_traceid_queues(etmq);
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	free(etmq);
}

static void cs_etm__free_events(struct perf_session *session)
{
	unsigned int i;
	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);
	struct auxtrace_queues *queues = &aux->queues;

	for (i = 0; i < queues->nr_queues; i++) {
		cs_etm__free_queue(queues->queue_array[i].priv);
		queues->queue_array[i].priv = NULL;
	}

	auxtrace_queues__free(queues);
}

static void cs_etm__free(struct perf_session *session)
{
626 627
	int i;
	struct int_node *inode, *tmp;
628 629 630 631 632 633
	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);
	cs_etm__free_events(session);
	session->auxtrace = NULL;

634
	/* First remove all traceID/metadata nodes for the RB tree */
635 636 637 638 639 640 641 642
	intlist__for_each_entry_safe(inode, tmp, traceid_list)
		intlist__remove(traceid_list, inode);
	/* Then the RB tree itself */
	intlist__delete(traceid_list);

	for (i = 0; i < aux->num_cpu; i++)
		zfree(&aux->metadata[i]);

643
	thread__zput(aux->unknown_thread);
644
	zfree(&aux->metadata);
645 646 647
	zfree(&aux);
}

648 649 650 651 652 653 654 655 656 657
static bool cs_etm__evsel_is_auxtrace(struct perf_session *session,
				      struct evsel *evsel)
{
	struct cs_etm_auxtrace *aux = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);

	return evsel->core.attr.type == aux->pmu_type;
}

658 659 660 661 662 663
static u8 cs_etm__cpu_mode(struct cs_etm_queue *etmq, u64 address)
{
	struct machine *machine;

	machine = etmq->etm->machine;

664
	if (address >= machine__kernel_start(machine)) {
665 666 667 668 669 670 671 672 673 674 675 676 677 678
		if (machine__is_host(machine))
			return PERF_RECORD_MISC_KERNEL;
		else
			return PERF_RECORD_MISC_GUEST_KERNEL;
	} else {
		if (machine__is_host(machine))
			return PERF_RECORD_MISC_USER;
		else if (perf_guest)
			return PERF_RECORD_MISC_GUEST_USER;
		else
			return PERF_RECORD_MISC_HYPERVISOR;
	}
}

679 680
static u32 cs_etm__mem_access(struct cs_etm_queue *etmq, u8 trace_chan_id,
			      u64 address, size_t size, u8 *buffer)
681 682 683 684
{
	u8  cpumode;
	u64 offset;
	int len;
685 686 687 688
	struct thread *thread;
	struct machine *machine;
	struct addr_location al;
	struct cs_etm_traceid_queue *tidq;
689

690
	if (!etmq)
691
		return 0;
692 693

	machine = etmq->etm->machine;
694
	cpumode = cs_etm__cpu_mode(etmq, address);
695 696 697
	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
	if (!tidq)
		return 0;
698

699
	thread = tidq->thread;
700 701
	if (!thread) {
		if (cpumode != PERF_RECORD_MISC_KERNEL)
702
			return 0;
703 704 705
		thread = etmq->etm->unknown_thread;
	}

706
	if (!thread__find_map(thread, cpumode, address, &al) || !al.map->dso)
707 708 709 710 711 712 713 714 715 716 717 718
		return 0;

	if (al.map->dso->data.status == DSO_DATA_STATUS_ERROR &&
	    dso__data_status_seen(al.map->dso, DSO_DATA_STATUS_SEEN_ITRACE))
		return 0;

	offset = al.map->map_ip(al.map, address);

	map__load(al.map);

	len = dso__data_read_offset(al.map->dso, machine, offset, buffer, size);

719 720 721 722 723 724 725 726 727
	if (len <= 0) {
		ui__warning_once("CS ETM Trace: Missing DSO. Use 'perf archive' or debuginfod to export data from the traced system.\n"
				 "              Enable CONFIG_PROC_KCORE or use option '-k /path/to/vmlinux' for kernel symbols.\n");
		if (!al.map->dso->auxtrace_warned) {
			pr_err("CS ETM Trace: Debug data not found for address %#"PRIx64" in %s\n",
				    address,
				    al.map->dso->long_name ? al.map->dso->long_name : "Unknown");
			al.map->dso->auxtrace_warned = true;
		}
728
		return 0;
729
	}
730 731 732 733

	return len;
}

734 735
static struct cs_etm_queue *cs_etm__alloc_queue(struct cs_etm_auxtrace *etm,
						bool formatted)
736 737
{
	struct cs_etm_decoder_params d_params;
738
	struct cs_etm_trace_params  *t_params = NULL;
739
	struct cs_etm_queue *etmq;
740 741 742 743 744
	/*
	 * Each queue can only contain data from one CPU when unformatted, so only one decoder is
	 * needed.
	 */
	int decoders = formatted ? etm->num_cpu : 1;
745 746 747 748 749

	etmq = zalloc(sizeof(*etmq));
	if (!etmq)
		return NULL;

750 751 752 753
	etmq->traceid_queues_list = intlist__new(NULL);
	if (!etmq->traceid_queues_list)
		goto out_free;

754
	/* Use metadata to fill in trace parameters for trace decoder */
755
	t_params = zalloc(sizeof(*t_params) * decoders);
756 757 758 759

	if (!t_params)
		goto out_free;

760
	if (cs_etm__init_trace_params(t_params, etm, decoders))
761
		goto out_free;
762

763
	/* Set decoder parameters to decode trace packets */
764
	if (cs_etm__init_decoder_params(&d_params, etmq,
765
					dump_trace ? CS_ETM_OPERATION_PRINT :
766 767
						     CS_ETM_OPERATION_DECODE,
					formatted))
768
		goto out_free;
769

770 771
	etmq->decoder = cs_etm_decoder__new(decoders, &d_params,
					    t_params);
772 773 774 775 776 777 778 779 780 781 782 783 784

	if (!etmq->decoder)
		goto out_free;

	/*
	 * Register a function to handle all memory accesses required by
	 * the trace decoder library.
	 */
	if (cs_etm_decoder__add_mem_access_cb(etmq->decoder,
					      0x0L, ((u64) -1L),
					      cs_etm__mem_access))
		goto out_free_decoder;

785
	zfree(&t_params);
786 787 788 789 790
	return etmq;

out_free_decoder:
	cs_etm_decoder__free(etmq->decoder);
out_free:
791
	intlist__delete(etmq->traceid_queues_list);
792 793 794 795 796 797 798
	free(etmq);

	return NULL;
}

static int cs_etm__setup_queue(struct cs_etm_auxtrace *etm,
			       struct auxtrace_queue *queue,
799 800
			       unsigned int queue_nr,
			       bool formatted)
801 802 803 804
{
	struct cs_etm_queue *etmq = queue->priv;

	if (list_empty(&queue->head) || etmq)
805
		return 0;
806

807
	etmq = cs_etm__alloc_queue(etm, formatted);
808

809 810
	if (!etmq)
		return -ENOMEM;
811 812

	queue->priv = etmq;
813 814 815
	etmq->etm = etm;
	etmq->queue_nr = queue_nr;
	etmq->offset = 0;
816

817 818 819 820 821 822 823 824 825 826 827
	return 0;
}

static int cs_etm__queue_first_cs_timestamp(struct cs_etm_auxtrace *etm,
					    struct cs_etm_queue *etmq,
					    unsigned int queue_nr)
{
	int ret = 0;
	unsigned int cs_queue_nr;
	u8 trace_chan_id;
	u64 cs_timestamp;
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

	/*
	 * We are under a CPU-wide trace scenario.  As such we need to know
	 * when the code that generated the traces started to execute so that
	 * it can be correlated with execution on other CPUs.  So we get a
	 * handle on the beginning of traces and decode until we find a
	 * timestamp.  The timestamp is then added to the auxtrace min heap
	 * in order to know what nibble (of all the etmqs) to decode first.
	 */
	while (1) {
		/*
		 * Fetch an aux_buffer from this etmq.  Bail if no more
		 * blocks or an error has been encountered.
		 */
		ret = cs_etm__get_data_block(etmq);
		if (ret <= 0)
			goto out;

		/*
		 * Run decoder on the trace block.  The decoder will stop when
848
		 * encountering a CS timestamp, a full packet queue or the end of
849 850 851 852 853 854 855 856 857 858
		 * trace for that block.
		 */
		ret = cs_etm__decode_data_block(etmq);
		if (ret)
			goto out;

		/*
		 * Function cs_etm_decoder__do_{hard|soft}_timestamp() does all
		 * the timestamp calculation for us.
		 */
859
		cs_timestamp = cs_etm__etmq_get_timestamp(etmq, &trace_chan_id);
860 861

		/* We found a timestamp, no need to continue. */
862
		if (cs_timestamp)
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
			break;

		/*
		 * We didn't find a timestamp so empty all the traceid packet
		 * queues before looking for another timestamp packet, either
		 * in the current data block or a new one.  Packets that were
		 * just decoded are useless since no timestamp has been
		 * associated with them.  As such simply discard them.
		 */
		cs_etm__clear_all_packet_queues(etmq);
	}

	/*
	 * We have a timestamp.  Add it to the min heap to reflect when
	 * instructions conveyed by the range packets of this traceID queue
	 * started to execute.  Once the same has been done for all the traceID
	 * queues of each etmq, redenring and decoding can start in
	 * chronological order.
	 *
	 * Note that packets decoded above are still in the traceID's packet
	 * queue and will be processed in cs_etm__process_queues().
	 */
885
	cs_queue_nr = TO_CS_QUEUE_NR(queue_nr, trace_chan_id);
886
	ret = auxtrace_heap__add(&etm->heap, cs_queue_nr, cs_timestamp);
887 888
out:
	return ret;
889 890
}

891 892 893
static inline
void cs_etm__copy_last_branch_rb(struct cs_etm_queue *etmq,
				 struct cs_etm_traceid_queue *tidq)
894
{
895 896
	struct branch_stack *bs_src = tidq->last_branch_rb;
	struct branch_stack *bs_dst = tidq->last_branch;
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
	size_t nr = 0;

	/*
	 * Set the number of records before early exit: ->nr is used to
	 * determine how many branches to copy from ->entries.
	 */
	bs_dst->nr = bs_src->nr;

	/*
	 * Early exit when there is nothing to copy.
	 */
	if (!bs_src->nr)
		return;

	/*
	 * As bs_src->entries is a circular buffer, we need to copy from it in
	 * two steps.  First, copy the branches from the most recently inserted
	 * branch ->last_branch_pos until the end of bs_src->entries buffer.
	 */
916
	nr = etmq->etm->synth_opts.last_branch_sz - tidq->last_branch_pos;
917
	memcpy(&bs_dst->entries[0],
918
	       &bs_src->entries[tidq->last_branch_pos],
919 920 921 922 923 924 925 926 927 928 929 930
	       sizeof(struct branch_entry) * nr);

	/*
	 * If we wrapped around at least once, the branches from the beginning
	 * of the bs_src->entries buffer and until the ->last_branch_pos element
	 * are older valid branches: copy them over.  The total number of
	 * branches copied over will be equal to the number of branches asked by
	 * the user in last_branch_sz.
	 */
	if (bs_src->nr >= etmq->etm->synth_opts.last_branch_sz) {
		memcpy(&bs_dst->entries[nr],
		       &bs_src->entries[0],
931
		       sizeof(struct branch_entry) * tidq->last_branch_pos);
932 933 934
	}
}

935 936
static inline
void cs_etm__reset_last_branch_rb(struct cs_etm_traceid_queue *tidq)
937
{
938 939
	tidq->last_branch_pos = 0;
	tidq->last_branch_rb->nr = 0;
940 941
}

942
static inline int cs_etm__t32_instr_size(struct cs_etm_queue *etmq,
943 944
					 u8 trace_chan_id, u64 addr)
{
945
	u8 instrBytes[2];
946

947 948
	cs_etm__mem_access(etmq, trace_chan_id, addr,
			   ARRAY_SIZE(instrBytes), instrBytes);
949
	/*
950 951 952
	 * T32 instruction size is indicated by bits[15:11] of the first
	 * 16-bit word of the instruction: 0b11101, 0b11110 and 0b11111
	 * denote a 32-bit instruction.
953
	 */
954
	return ((instrBytes[1] & 0xF8) >= 0xE8) ? 4 : 2;
955 956
}

957 958
static inline u64 cs_etm__first_executed_instr(struct cs_etm_packet *packet)
{
959 960
	/* Returns 0 for the CS_ETM_DISCONTINUITY packet */
	if (packet->sample_type == CS_ETM_DISCONTINUITY)
961 962 963 964 965
		return 0;

	return packet->start_addr;
}

966 967
static inline
u64 cs_etm__last_executed_instr(const struct cs_etm_packet *packet)
968
{
969 970
	/* Returns 0 for the CS_ETM_DISCONTINUITY packet */
	if (packet->sample_type == CS_ETM_DISCONTINUITY)
971 972 973
		return 0;

	return packet->end_addr - packet->last_instr_size;
974 975
}

976
static inline u64 cs_etm__instr_addr(struct cs_etm_queue *etmq,
977
				     u64 trace_chan_id,
978
				     const struct cs_etm_packet *packet,
979 980
				     u64 offset)
{
981 982 983
	if (packet->isa == CS_ETM_ISA_T32) {
		u64 addr = packet->start_addr;

984
		while (offset) {
985 986
			addr += cs_etm__t32_instr_size(etmq,
						       trace_chan_id, addr);
987 988 989 990 991 992 993
			offset--;
		}
		return addr;
	}

	/* Assume a 4 byte instruction size (A32/A64) */
	return packet->start_addr + offset * 4;
994 995
}

996 997
static void cs_etm__update_last_branch_rb(struct cs_etm_queue *etmq,
					  struct cs_etm_traceid_queue *tidq)
998
{
999
	struct branch_stack *bs = tidq->last_branch_rb;
1000 1001 1002 1003 1004 1005 1006 1007
	struct branch_entry *be;

	/*
	 * The branches are recorded in a circular buffer in reverse
	 * chronological order: we start recording from the last element of the
	 * buffer down.  After writing the first element of the stack, move the
	 * insert position back to the end of the buffer.
	 */
1008 1009
	if (!tidq->last_branch_pos)
		tidq->last_branch_pos = etmq->etm->synth_opts.last_branch_sz;
1010

1011
	tidq->last_branch_pos -= 1;
1012

1013 1014 1015
	be       = &bs->entries[tidq->last_branch_pos];
	be->from = cs_etm__last_executed_instr(tidq->prev_packet);
	be->to	 = cs_etm__first_executed_instr(tidq->packet);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	/* No support for mispredict */
	be->flags.mispred = 0;
	be->flags.predicted = 1;

	/*
	 * Increment bs->nr until reaching the number of last branches asked by
	 * the user on the command line.
	 */
	if (bs->nr < etmq->etm->synth_opts.last_branch_sz)
		bs->nr += 1;
}

static int cs_etm__inject_event(union perf_event *event,
			       struct perf_sample *sample, u64 type)
{
	event->header.size = perf_event__sample_event_size(sample, type, 0);
	return perf_event__synthesize_sample(event, type, 0, sample);
}


1036
static int
1037
cs_etm__get_trace(struct cs_etm_queue *etmq)
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
{
	struct auxtrace_buffer *aux_buffer = etmq->buffer;
	struct auxtrace_buffer *old_buffer = aux_buffer;
	struct auxtrace_queue *queue;

	queue = &etmq->etm->queues.queue_array[etmq->queue_nr];

	aux_buffer = auxtrace_buffer__next(queue, aux_buffer);

	/* If no more data, drop the previous auxtrace_buffer and return */
	if (!aux_buffer) {
		if (old_buffer)
			auxtrace_buffer__drop_data(old_buffer);
1051
		etmq->buf_len = 0;
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
		return 0;
	}

	etmq->buffer = aux_buffer;

	/* If the aux_buffer doesn't have data associated, try to load it */
	if (!aux_buffer->data) {
		/* get the file desc associated with the perf data file */
		int fd = perf_data__fd(etmq->etm->session->data);

		aux_buffer->data = auxtrace_buffer__get_data(aux_buffer, fd);
		if (!aux_buffer->data)
			return -ENOMEM;
	}

	/* If valid, drop the previous buffer */
	if (old_buffer)
		auxtrace_buffer__drop_data(old_buffer);

1071 1072 1073
	etmq->buf_used = 0;
	etmq->buf_len = aux_buffer->size;
	etmq->buf = aux_buffer->data;
1074

1075
	return etmq->buf_len;
1076 1077
}

L
Leo Yan 已提交
1078
static void cs_etm__set_pid_tid_cpu(struct cs_etm_auxtrace *etm,
1079
				    struct cs_etm_traceid_queue *tidq)
1080
{
1081
	if ((!tidq->thread) && (tidq->tid != -1))
1082
		tidq->thread = machine__find_thread(etm->machine, -1,
1083
						    tidq->tid);
1084

1085
	if (tidq->thread)
1086
		tidq->pid = tidq->thread->pid_;
1087 1088
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
int cs_etm__etmq_set_tid(struct cs_etm_queue *etmq,
			 pid_t tid, u8 trace_chan_id)
{
	int cpu, err = -EINVAL;
	struct cs_etm_auxtrace *etm = etmq->etm;
	struct cs_etm_traceid_queue *tidq;

	tidq = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
	if (!tidq)
		return err;

	if (cs_etm__get_cpu(trace_chan_id, &cpu) < 0)
		return err;

	err = machine__set_current_tid(etm->machine, cpu, tid, tid);
	if (err)
		return err;

	tidq->tid = tid;
	thread__zput(tidq->thread);

	cs_etm__set_pid_tid_cpu(etm, tidq);
	return 0;
}

1114 1115 1116 1117 1118
bool cs_etm__etmq_is_timeless(struct cs_etm_queue *etmq)
{
	return !!etmq->etm->timeless_decoding;
}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
static void cs_etm__copy_insn(struct cs_etm_queue *etmq,
			      u64 trace_chan_id,
			      const struct cs_etm_packet *packet,
			      struct perf_sample *sample)
{
	/*
	 * It's pointless to read instructions for the CS_ETM_DISCONTINUITY
	 * packet, so directly bail out with 'insn_len' = 0.
	 */
	if (packet->sample_type == CS_ETM_DISCONTINUITY) {
		sample->insn_len = 0;
		return;
	}

	/*
	 * T32 instruction size might be 32-bit or 16-bit, decide by calling
	 * cs_etm__t32_instr_size().
	 */
	if (packet->isa == CS_ETM_ISA_T32)
		sample->insn_len = cs_etm__t32_instr_size(etmq, trace_chan_id,
							  sample->ip);
	/* Otherwise, A64 and A32 instruction size are always 32-bit. */
	else
		sample->insn_len = 4;

	cs_etm__mem_access(etmq, trace_chan_id, sample->ip,
			   sample->insn_len, (void *)sample->insn);
}

1148
static int cs_etm__synth_instruction_sample(struct cs_etm_queue *etmq,
1149
					    struct cs_etm_traceid_queue *tidq,
1150 1151 1152 1153
					    u64 addr, u64 period)
{
	int ret = 0;
	struct cs_etm_auxtrace *etm = etmq->etm;
1154
	union perf_event *event = tidq->event_buf;
1155 1156 1157
	struct perf_sample sample = {.ip = 0,};

	event->sample.header.type = PERF_RECORD_SAMPLE;
1158
	event->sample.header.misc = cs_etm__cpu_mode(etmq, addr);
1159 1160
	event->sample.header.size = sizeof(struct perf_event_header);

1161 1162
	if (!etm->timeless_decoding)
		sample.time = etm->latest_kernel_timestamp;
1163
	sample.ip = addr;
1164 1165
	sample.pid = tidq->pid;
	sample.tid = tidq->tid;
1166 1167 1168
	sample.id = etmq->etm->instructions_id;
	sample.stream_id = etmq->etm->instructions_id;
	sample.period = period;
1169 1170
	sample.cpu = tidq->packet->cpu;
	sample.flags = tidq->prev_packet->flags;
1171
	sample.cpumode = event->sample.header.misc;
1172

1173 1174
	cs_etm__copy_insn(etmq, tidq->trace_chan_id, tidq->packet, &sample);

1175
	if (etm->synth_opts.last_branch)
1176
		sample.branch_stack = tidq->last_branch;
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194

	if (etm->synth_opts.inject) {
		ret = cs_etm__inject_event(event, &sample,
					   etm->instructions_sample_type);
		if (ret)
			return ret;
	}

	ret = perf_session__deliver_synth_event(etm->session, event, &sample);

	if (ret)
		pr_err(
			"CS ETM Trace: failed to deliver instruction event, error %d\n",
			ret);

	return ret;
}

1195 1196 1197 1198
/*
 * The cs etm packet encodes an instruction range between a branch target
 * and the next taken branch. Generate sample accordingly.
 */
1199 1200
static int cs_etm__synth_branch_sample(struct cs_etm_queue *etmq,
				       struct cs_etm_traceid_queue *tidq)
1201 1202 1203 1204
{
	int ret = 0;
	struct cs_etm_auxtrace *etm = etmq->etm;
	struct perf_sample sample = {.ip = 0,};
1205
	union perf_event *event = tidq->event_buf;
1206 1207
	struct dummy_branch_stack {
		u64			nr;
1208
		u64			hw_idx;
1209 1210
		struct branch_entry	entries;
	} dummy_bs;
1211 1212
	u64 ip;

1213
	ip = cs_etm__last_executed_instr(tidq->prev_packet);
1214 1215

	event->sample.header.type = PERF_RECORD_SAMPLE;
1216
	event->sample.header.misc = cs_etm__cpu_mode(etmq, ip);
1217 1218
	event->sample.header.size = sizeof(struct perf_event_header);

1219 1220
	if (!etm->timeless_decoding)
		sample.time = etm->latest_kernel_timestamp;
1221
	sample.ip = ip;
1222 1223
	sample.pid = tidq->pid;
	sample.tid = tidq->tid;
1224
	sample.addr = cs_etm__first_executed_instr(tidq->packet);
1225 1226 1227
	sample.id = etmq->etm->branches_id;
	sample.stream_id = etmq->etm->branches_id;
	sample.period = 1;
1228 1229
	sample.cpu = tidq->packet->cpu;
	sample.flags = tidq->prev_packet->flags;
1230
	sample.cpumode = event->sample.header.misc;
1231

1232 1233 1234
	cs_etm__copy_insn(etmq, tidq->trace_chan_id, tidq->prev_packet,
			  &sample);

1235 1236 1237 1238 1239 1240
	/*
	 * perf report cannot handle events without a branch stack
	 */
	if (etm->synth_opts.last_branch) {
		dummy_bs = (struct dummy_branch_stack){
			.nr = 1,
1241
			.hw_idx = -1ULL,
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
			.entries = {
				.from = sample.ip,
				.to = sample.addr,
			},
		};
		sample.branch_stack = (struct branch_stack *)&dummy_bs;
	}

	if (etm->synth_opts.inject) {
		ret = cs_etm__inject_event(event, &sample,
					   etm->branches_sample_type);
		if (ret)
			return ret;
	}

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
	ret = perf_session__deliver_synth_event(etm->session, event, &sample);

	if (ret)
		pr_err(
		"CS ETM Trace: failed to deliver instruction event, error %d\n",
		ret);

	return ret;
}

struct cs_etm_synth {
	struct perf_tool dummy_tool;
	struct perf_session *session;
};

static int cs_etm__event_synth(struct perf_tool *tool,
			       union perf_event *event,
			       struct perf_sample *sample __maybe_unused,
			       struct machine *machine __maybe_unused)
{
	struct cs_etm_synth *cs_etm_synth =
		      container_of(tool, struct cs_etm_synth, dummy_tool);

	return perf_session__deliver_synth_event(cs_etm_synth->session,
						 event, NULL);
}

static int cs_etm__synth_event(struct perf_session *session,
			       struct perf_event_attr *attr, u64 id)
{
	struct cs_etm_synth cs_etm_synth;

	memset(&cs_etm_synth, 0, sizeof(struct cs_etm_synth));
	cs_etm_synth.session = session;

	return perf_event__synthesize_attr(&cs_etm_synth.dummy_tool, attr, 1,
					   &id, cs_etm__event_synth);
}

static int cs_etm__synth_events(struct cs_etm_auxtrace *etm,
				struct perf_session *session)
{
1299
	struct evlist *evlist = session->evlist;
1300
	struct evsel *evsel;
1301 1302 1303 1304 1305 1306
	struct perf_event_attr attr;
	bool found = false;
	u64 id;
	int err;

	evlist__for_each_entry(evlist, evsel) {
1307
		if (evsel->core.attr.type == etm->pmu_type) {
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
			found = true;
			break;
		}
	}

	if (!found) {
		pr_debug("No selected events with CoreSight Trace data\n");
		return 0;
	}

	memset(&attr, 0, sizeof(struct perf_event_attr));
	attr.size = sizeof(struct perf_event_attr);
	attr.type = PERF_TYPE_HARDWARE;
1321
	attr.sample_type = evsel->core.attr.sample_type & PERF_SAMPLE_MASK;
1322 1323 1324 1325 1326 1327 1328
	attr.sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID |
			    PERF_SAMPLE_PERIOD;
	if (etm->timeless_decoding)
		attr.sample_type &= ~(u64)PERF_SAMPLE_TIME;
	else
		attr.sample_type |= PERF_SAMPLE_TIME;

1329 1330 1331 1332 1333 1334 1335
	attr.exclude_user = evsel->core.attr.exclude_user;
	attr.exclude_kernel = evsel->core.attr.exclude_kernel;
	attr.exclude_hv = evsel->core.attr.exclude_hv;
	attr.exclude_host = evsel->core.attr.exclude_host;
	attr.exclude_guest = evsel->core.attr.exclude_guest;
	attr.sample_id_all = evsel->core.attr.sample_id_all;
	attr.read_format = evsel->core.attr.read_format;
1336 1337

	/* create new id val to be a fixed offset from evsel id */
1338
	id = evsel->core.id[0] + 1000000000;
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352

	if (!id)
		id = 1;

	if (etm->synth_opts.branches) {
		attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS;
		attr.sample_period = 1;
		attr.sample_type |= PERF_SAMPLE_ADDR;
		err = cs_etm__synth_event(session, &attr, id);
		if (err)
			return err;
		etm->sample_branches = true;
		etm->branches_sample_type = attr.sample_type;
		etm->branches_id = id;
1353 1354 1355 1356
		id += 1;
		attr.sample_type &= ~(u64)PERF_SAMPLE_ADDR;
	}

1357
	if (etm->synth_opts.last_branch) {
1358
		attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
1359 1360 1361 1362 1363 1364 1365
		/*
		 * We don't use the hardware index, but the sample generation
		 * code uses the new format branch_stack with this field,
		 * so the event attributes must indicate that it's present.
		 */
		attr.branch_sample_type |= PERF_SAMPLE_BRANCH_HW_INDEX;
	}
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

	if (etm->synth_opts.instructions) {
		attr.config = PERF_COUNT_HW_INSTRUCTIONS;
		attr.sample_period = etm->synth_opts.period;
		etm->instructions_sample_period = attr.sample_period;
		err = cs_etm__synth_event(session, &attr, id);
		if (err)
			return err;
		etm->sample_instructions = true;
		etm->instructions_sample_type = attr.sample_type;
		etm->instructions_id = id;
		id += 1;
1378 1379 1380 1381 1382
	}

	return 0;
}

1383 1384
static int cs_etm__sample(struct cs_etm_queue *etmq,
			  struct cs_etm_traceid_queue *tidq)
1385
{
1386
	struct cs_etm_auxtrace *etm = etmq->etm;
1387
	int ret;
1388
	u8 trace_chan_id = tidq->trace_chan_id;
1389
	u64 instrs_prev;
1390

1391 1392 1393 1394
	/* Get instructions remainder from previous packet */
	instrs_prev = tidq->period_instructions;

	tidq->period_instructions += tidq->packet->instr_count;
1395 1396 1397 1398 1399 1400

	/*
	 * Record a branch when the last instruction in
	 * PREV_PACKET is a branch.
	 */
	if (etm->synth_opts.last_branch &&
1401 1402 1403
	    tidq->prev_packet->sample_type == CS_ETM_RANGE &&
	    tidq->prev_packet->last_instr_taken_branch)
		cs_etm__update_last_branch_rb(etmq, tidq);
1404 1405

	if (etm->sample_instructions &&
1406
	    tidq->period_instructions >= etm->instructions_sample_period) {
1407 1408 1409 1410 1411 1412
		/*
		 * Emit instruction sample periodically
		 * TODO: allow period to be defined in cycles and clock time
		 */

		/*
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
		 * Below diagram demonstrates the instruction samples
		 * generation flows:
		 *
		 *    Instrs     Instrs       Instrs       Instrs
		 *   Sample(n)  Sample(n+1)  Sample(n+2)  Sample(n+3)
		 *    |            |            |            |
		 *    V            V            V            V
		 *   --------------------------------------------------
		 *            ^                                  ^
		 *            |                                  |
		 *         Period                             Period
		 *    instructions(Pi)                   instructions(Pi')
		 *
		 *            |                                  |
		 *            \---------------- -----------------/
		 *                             V
		 *                 tidq->packet->instr_count
		 *
		 * Instrs Sample(n...) are the synthesised samples occurring
		 * every etm->instructions_sample_period instructions - as
		 * defined on the perf command line.  Sample(n) is being the
		 * last sample before the current etm packet, n+1 to n+3
		 * samples are generated from the current etm packet.
		 *
		 * tidq->packet->instr_count represents the number of
		 * instructions in the current etm packet.
		 *
		 * Period instructions (Pi) contains the the number of
		 * instructions executed after the sample point(n) from the
		 * previous etm packet.  This will always be less than
		 * etm->instructions_sample_period.
		 *
		 * When generate new samples, it combines with two parts
		 * instructions, one is the tail of the old packet and another
		 * is the head of the new coming packet, to generate
		 * sample(n+1); sample(n+2) and sample(n+3) consume the
		 * instructions with sample period.  After sample(n+3), the rest
		 * instructions will be used by later packet and it is assigned
		 * to tidq->period_instructions for next round calculation.
1452 1453
		 */

1454 1455 1456 1457 1458 1459 1460 1461
		/*
		 * Get the initial offset into the current packet instructions;
		 * entry conditions ensure that instrs_prev is less than
		 * etm->instructions_sample_period.
		 */
		u64 offset = etm->instructions_sample_period - instrs_prev;
		u64 addr;

1462 1463 1464 1465
		/* Prepare last branches for instruction sample */
		if (etm->synth_opts.last_branch)
			cs_etm__copy_last_branch_rb(etmq, tidq);

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
		while (tidq->period_instructions >=
				etm->instructions_sample_period) {
			/*
			 * Calculate the address of the sampled instruction (-1
			 * as sample is reported as though instruction has just
			 * been executed, but PC has not advanced to next
			 * instruction)
			 */
			addr = cs_etm__instr_addr(etmq, trace_chan_id,
						  tidq->packet, offset - 1);
			ret = cs_etm__synth_instruction_sample(
				etmq, tidq, addr,
				etm->instructions_sample_period);
			if (ret)
				return ret;
1481

1482 1483 1484 1485
			offset += etm->instructions_sample_period;
			tidq->period_instructions -=
				etm->instructions_sample_period;
		}
1486 1487
	}

1488
	if (etm->sample_branches) {
1489 1490 1491
		bool generate_sample = false;

		/* Generate sample for tracing on packet */
1492
		if (tidq->prev_packet->sample_type == CS_ETM_DISCONTINUITY)
1493 1494 1495
			generate_sample = true;

		/* Generate sample for branch taken packet */
1496 1497
		if (tidq->prev_packet->sample_type == CS_ETM_RANGE &&
		    tidq->prev_packet->last_instr_taken_branch)
1498 1499 1500
			generate_sample = true;

		if (generate_sample) {
1501
			ret = cs_etm__synth_branch_sample(etmq, tidq);
1502 1503 1504
			if (ret)
				return ret;
		}
1505
	}
1506

1507
	cs_etm__packet_swap(etm, tidq);
1508 1509 1510 1511

	return 0;
}

1512
static int cs_etm__exception(struct cs_etm_traceid_queue *tidq)
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
{
	/*
	 * When the exception packet is inserted, whether the last instruction
	 * in previous range packet is taken branch or not, we need to force
	 * to set 'prev_packet->last_instr_taken_branch' to true.  This ensures
	 * to generate branch sample for the instruction range before the
	 * exception is trapped to kernel or before the exception returning.
	 *
	 * The exception packet includes the dummy address values, so don't
	 * swap PACKET with PREV_PACKET.  This keeps PREV_PACKET to be useful
	 * for generating instruction and branch samples.
	 */
1525 1526
	if (tidq->prev_packet->sample_type == CS_ETM_RANGE)
		tidq->prev_packet->last_instr_taken_branch = true;
1527 1528 1529 1530

	return 0;
}

1531 1532
static int cs_etm__flush(struct cs_etm_queue *etmq,
			 struct cs_etm_traceid_queue *tidq)
1533 1534
{
	int err = 0;
1535
	struct cs_etm_auxtrace *etm = etmq->etm;
1536

1537
	/* Handle start tracing packet */
1538
	if (tidq->prev_packet->sample_type == CS_ETM_EMPTY)
1539 1540
		goto swap_packet;

1541
	if (etmq->etm->synth_opts.last_branch &&
1542
	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
1543 1544 1545 1546 1547
		u64 addr;

		/* Prepare last branches for instruction sample */
		cs_etm__copy_last_branch_rb(etmq, tidq);

1548 1549 1550 1551 1552 1553 1554
		/*
		 * Generate a last branch event for the branches left in the
		 * circular buffer at the end of the trace.
		 *
		 * Use the address of the end of the last reported execution
		 * range
		 */
1555
		addr = cs_etm__last_executed_instr(tidq->prev_packet);
1556 1557

		err = cs_etm__synth_instruction_sample(
1558 1559
			etmq, tidq, addr,
			tidq->period_instructions);
1560 1561 1562
		if (err)
			return err;

1563
		tidq->period_instructions = 0;
1564

1565 1566
	}

1567
	if (etm->sample_branches &&
1568 1569
	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
		err = cs_etm__synth_branch_sample(etmq, tidq);
1570 1571 1572 1573
		if (err)
			return err;
	}

1574
swap_packet:
1575
	cs_etm__packet_swap(etm, tidq);
1576

1577 1578 1579 1580
	/* Reset last branches after flush the trace */
	if (etm->synth_opts.last_branch)
		cs_etm__reset_last_branch_rb(tidq);

1581 1582 1583
	return err;
}

1584 1585
static int cs_etm__end_block(struct cs_etm_queue *etmq,
			     struct cs_etm_traceid_queue *tidq)
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
{
	int err;

	/*
	 * It has no new packet coming and 'etmq->packet' contains the stale
	 * packet which was set at the previous time with packets swapping;
	 * so skip to generate branch sample to avoid stale packet.
	 *
	 * For this case only flush branch stack and generate a last branch
	 * event for the branches left in the circular buffer at the end of
	 * the trace.
	 */
	if (etmq->etm->synth_opts.last_branch &&
1599
	    tidq->prev_packet->sample_type == CS_ETM_RANGE) {
1600 1601 1602 1603 1604
		u64 addr;

		/* Prepare last branches for instruction sample */
		cs_etm__copy_last_branch_rb(etmq, tidq);

1605 1606 1607 1608
		/*
		 * Use the address of the end of the last reported execution
		 * range.
		 */
1609
		addr = cs_etm__last_executed_instr(tidq->prev_packet);
1610 1611

		err = cs_etm__synth_instruction_sample(
1612 1613
			etmq, tidq, addr,
			tidq->period_instructions);
1614 1615 1616
		if (err)
			return err;

1617
		tidq->period_instructions = 0;
1618 1619 1620 1621
	}

	return 0;
}
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
/*
 * cs_etm__get_data_block: Fetch a block from the auxtrace_buffer queue
 *			   if need be.
 * Returns:	< 0	if error
 *		= 0	if no more auxtrace_buffer to read
 *		> 0	if the current buffer isn't empty yet
 */
static int cs_etm__get_data_block(struct cs_etm_queue *etmq)
{
	int ret;

	if (!etmq->buf_len) {
		ret = cs_etm__get_trace(etmq);
		if (ret <= 0)
			return ret;
		/*
		 * We cannot assume consecutive blocks in the data file
		 * are contiguous, reset the decoder to force re-sync.
		 */
		ret = cs_etm_decoder__reset(etmq->decoder);
		if (ret)
			return ret;
	}

	return etmq->buf_len;
}
1648

1649
static bool cs_etm__is_svc_instr(struct cs_etm_queue *etmq, u8 trace_chan_id,
1650 1651 1652
				 struct cs_etm_packet *packet,
				 u64 end_addr)
{
1653 1654 1655
	/* Initialise to keep compiler happy */
	u16 instr16 = 0;
	u32 instr32 = 0;
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
	u64 addr;

	switch (packet->isa) {
	case CS_ETM_ISA_T32:
		/*
		 * The SVC of T32 is defined in ARM DDI 0487D.a, F5.1.247:
		 *
		 *  b'15         b'8
		 * +-----------------+--------+
		 * | 1 1 0 1 1 1 1 1 |  imm8  |
		 * +-----------------+--------+
		 *
1668
		 * According to the specification, it only defines SVC for T32
1669 1670 1671 1672
		 * with 16 bits instruction and has no definition for 32bits;
		 * so below only read 2 bytes as instruction size for T32.
		 */
		addr = end_addr - 2;
1673 1674
		cs_etm__mem_access(etmq, trace_chan_id, addr,
				   sizeof(instr16), (u8 *)&instr16);
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
		if ((instr16 & 0xFF00) == 0xDF00)
			return true;

		break;
	case CS_ETM_ISA_A32:
		/*
		 * The SVC of A32 is defined in ARM DDI 0487D.a, F5.1.247:
		 *
		 *  b'31 b'28 b'27 b'24
		 * +---------+---------+-------------------------+
		 * |  !1111  | 1 1 1 1 |        imm24            |
		 * +---------+---------+-------------------------+
		 */
		addr = end_addr - 4;
1689 1690
		cs_etm__mem_access(etmq, trace_chan_id, addr,
				   sizeof(instr32), (u8 *)&instr32);
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
		if ((instr32 & 0x0F000000) == 0x0F000000 &&
		    (instr32 & 0xF0000000) != 0xF0000000)
			return true;

		break;
	case CS_ETM_ISA_A64:
		/*
		 * The SVC of A64 is defined in ARM DDI 0487D.a, C6.2.294:
		 *
		 *  b'31               b'21           b'4     b'0
		 * +-----------------------+---------+-----------+
		 * | 1 1 0 1 0 1 0 0 0 0 0 |  imm16  | 0 0 0 0 1 |
		 * +-----------------------+---------+-----------+
		 */
		addr = end_addr - 4;
1706 1707
		cs_etm__mem_access(etmq, trace_chan_id, addr,
				   sizeof(instr32), (u8 *)&instr32);
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
		if ((instr32 & 0xFFE0001F) == 0xd4000001)
			return true;

		break;
	case CS_ETM_ISA_UNKNOWN:
	default:
		break;
	}

	return false;
}

1720 1721
static bool cs_etm__is_syscall(struct cs_etm_queue *etmq,
			       struct cs_etm_traceid_queue *tidq, u64 magic)
1722
{
1723
	u8 trace_chan_id = tidq->trace_chan_id;
1724 1725
	struct cs_etm_packet *packet = tidq->packet;
	struct cs_etm_packet *prev_packet = tidq->prev_packet;
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737

	if (magic == __perf_cs_etmv3_magic)
		if (packet->exception_number == CS_ETMV3_EXC_SVC)
			return true;

	/*
	 * ETMv4 exception type CS_ETMV4_EXC_CALL covers SVC, SMC and
	 * HVC cases; need to check if it's SVC instruction based on
	 * packet address.
	 */
	if (magic == __perf_cs_etmv4_magic) {
		if (packet->exception_number == CS_ETMV4_EXC_CALL &&
1738
		    cs_etm__is_svc_instr(etmq, trace_chan_id, prev_packet,
1739 1740 1741 1742 1743 1744 1745
					 prev_packet->end_addr))
			return true;
	}

	return false;
}

1746 1747
static bool cs_etm__is_async_exception(struct cs_etm_traceid_queue *tidq,
				       u64 magic)
1748
{
1749
	struct cs_etm_packet *packet = tidq->packet;
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771

	if (magic == __perf_cs_etmv3_magic)
		if (packet->exception_number == CS_ETMV3_EXC_DEBUG_HALT ||
		    packet->exception_number == CS_ETMV3_EXC_ASYNC_DATA_ABORT ||
		    packet->exception_number == CS_ETMV3_EXC_PE_RESET ||
		    packet->exception_number == CS_ETMV3_EXC_IRQ ||
		    packet->exception_number == CS_ETMV3_EXC_FIQ)
			return true;

	if (magic == __perf_cs_etmv4_magic)
		if (packet->exception_number == CS_ETMV4_EXC_RESET ||
		    packet->exception_number == CS_ETMV4_EXC_DEBUG_HALT ||
		    packet->exception_number == CS_ETMV4_EXC_SYSTEM_ERROR ||
		    packet->exception_number == CS_ETMV4_EXC_INST_DEBUG ||
		    packet->exception_number == CS_ETMV4_EXC_DATA_DEBUG ||
		    packet->exception_number == CS_ETMV4_EXC_IRQ ||
		    packet->exception_number == CS_ETMV4_EXC_FIQ)
			return true;

	return false;
}

1772 1773 1774
static bool cs_etm__is_sync_exception(struct cs_etm_queue *etmq,
				      struct cs_etm_traceid_queue *tidq,
				      u64 magic)
1775
{
1776
	u8 trace_chan_id = tidq->trace_chan_id;
1777 1778
	struct cs_etm_packet *packet = tidq->packet;
	struct cs_etm_packet *prev_packet = tidq->prev_packet;
1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801

	if (magic == __perf_cs_etmv3_magic)
		if (packet->exception_number == CS_ETMV3_EXC_SMC ||
		    packet->exception_number == CS_ETMV3_EXC_HYP ||
		    packet->exception_number == CS_ETMV3_EXC_JAZELLE_THUMBEE ||
		    packet->exception_number == CS_ETMV3_EXC_UNDEFINED_INSTR ||
		    packet->exception_number == CS_ETMV3_EXC_PREFETCH_ABORT ||
		    packet->exception_number == CS_ETMV3_EXC_DATA_FAULT ||
		    packet->exception_number == CS_ETMV3_EXC_GENERIC)
			return true;

	if (magic == __perf_cs_etmv4_magic) {
		if (packet->exception_number == CS_ETMV4_EXC_TRAP ||
		    packet->exception_number == CS_ETMV4_EXC_ALIGNMENT ||
		    packet->exception_number == CS_ETMV4_EXC_INST_FAULT ||
		    packet->exception_number == CS_ETMV4_EXC_DATA_FAULT)
			return true;

		/*
		 * For CS_ETMV4_EXC_CALL, except SVC other instructions
		 * (SMC, HVC) are taken as sync exceptions.
		 */
		if (packet->exception_number == CS_ETMV4_EXC_CALL &&
1802
		    !cs_etm__is_svc_instr(etmq, trace_chan_id, prev_packet,
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
					  prev_packet->end_addr))
			return true;

		/*
		 * ETMv4 has 5 bits for exception number; if the numbers
		 * are in the range ( CS_ETMV4_EXC_FIQ, CS_ETMV4_EXC_END ]
		 * they are implementation defined exceptions.
		 *
		 * For this case, simply take it as sync exception.
		 */
		if (packet->exception_number > CS_ETMV4_EXC_FIQ &&
		    packet->exception_number <= CS_ETMV4_EXC_END)
			return true;
	}

	return false;
}

1821 1822
static int cs_etm__set_sample_flags(struct cs_etm_queue *etmq,
				    struct cs_etm_traceid_queue *tidq)
1823
{
1824 1825
	struct cs_etm_packet *packet = tidq->packet;
	struct cs_etm_packet *prev_packet = tidq->prev_packet;
1826
	u8 trace_chan_id = tidq->trace_chan_id;
1827 1828
	u64 magic;
	int ret;
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

	switch (packet->sample_type) {
	case CS_ETM_RANGE:
		/*
		 * Immediate branch instruction without neither link nor
		 * return flag, it's normal branch instruction within
		 * the function.
		 */
		if (packet->last_instr_type == OCSD_INSTR_BR &&
		    packet->last_instr_subtype == OCSD_S_INSTR_NONE) {
			packet->flags = PERF_IP_FLAG_BRANCH;

			if (packet->last_instr_cond)
				packet->flags |= PERF_IP_FLAG_CONDITIONAL;
		}

		/*
		 * Immediate branch instruction with link (e.g. BL), this is
		 * branch instruction for function call.
		 */
		if (packet->last_instr_type == OCSD_INSTR_BR &&
		    packet->last_instr_subtype == OCSD_S_INSTR_BR_LINK)
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_CALL;

		/*
		 * Indirect branch instruction with link (e.g. BLR), this is
		 * branch instruction for function call.
		 */
		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
		    packet->last_instr_subtype == OCSD_S_INSTR_BR_LINK)
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_CALL;

		/*
		 * Indirect branch instruction with subtype of
		 * OCSD_S_INSTR_V7_IMPLIED_RET, this is explicit hint for
		 * function return for A32/T32.
		 */
		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
		    packet->last_instr_subtype == OCSD_S_INSTR_V7_IMPLIED_RET)
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_RETURN;

		/*
		 * Indirect branch instruction without link (e.g. BR), usually
		 * this is used for function return, especially for functions
		 * within dynamic link lib.
		 */
		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
		    packet->last_instr_subtype == OCSD_S_INSTR_NONE)
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_RETURN;

		/* Return instruction for function return. */
		if (packet->last_instr_type == OCSD_INSTR_BR_INDIRECT &&
		    packet->last_instr_subtype == OCSD_S_INSTR_V8_RET)
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_RETURN;
1888 1889 1890 1891 1892 1893 1894 1895 1896

		/*
		 * Decoder might insert a discontinuity in the middle of
		 * instruction packets, fixup prev_packet with flag
		 * PERF_IP_FLAG_TRACE_BEGIN to indicate restarting trace.
		 */
		if (prev_packet->sample_type == CS_ETM_DISCONTINUITY)
			prev_packet->flags |= PERF_IP_FLAG_BRANCH |
					      PERF_IP_FLAG_TRACE_BEGIN;
1897 1898 1899

		/*
		 * If the previous packet is an exception return packet
1900
		 * and the return address just follows SVC instruction,
1901 1902 1903 1904 1905 1906
		 * it needs to calibrate the previous packet sample flags
		 * as PERF_IP_FLAG_SYSCALLRET.
		 */
		if (prev_packet->flags == (PERF_IP_FLAG_BRANCH |
					   PERF_IP_FLAG_RETURN |
					   PERF_IP_FLAG_INTERRUPT) &&
1907 1908
		    cs_etm__is_svc_instr(etmq, trace_chan_id,
					 packet, packet->start_addr))
1909 1910 1911
			prev_packet->flags = PERF_IP_FLAG_BRANCH |
					     PERF_IP_FLAG_RETURN |
					     PERF_IP_FLAG_SYSCALLRET;
1912 1913
		break;
	case CS_ETM_DISCONTINUITY:
1914 1915 1916 1917 1918 1919 1920 1921 1922
		/*
		 * The trace is discontinuous, if the previous packet is
		 * instruction packet, set flag PERF_IP_FLAG_TRACE_END
		 * for previous packet.
		 */
		if (prev_packet->sample_type == CS_ETM_RANGE)
			prev_packet->flags |= PERF_IP_FLAG_BRANCH |
					      PERF_IP_FLAG_TRACE_END;
		break;
1923
	case CS_ETM_EXCEPTION:
1924 1925 1926 1927 1928
		ret = cs_etm__get_magic(packet->trace_chan_id, &magic);
		if (ret)
			return ret;

		/* The exception is for system call. */
1929
		if (cs_etm__is_syscall(etmq, tidq, magic))
1930 1931 1932 1933 1934 1935 1936
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_CALL |
					PERF_IP_FLAG_SYSCALLRET;
		/*
		 * The exceptions are triggered by external signals from bus,
		 * interrupt controller, debug module, PE reset or halt.
		 */
1937
		else if (cs_etm__is_async_exception(tidq, magic))
1938 1939 1940 1941 1942 1943 1944 1945
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_CALL |
					PERF_IP_FLAG_ASYNC |
					PERF_IP_FLAG_INTERRUPT;
		/*
		 * Otherwise, exception is caused by trap, instruction &
		 * data fault, or alignment errors.
		 */
1946
		else if (cs_etm__is_sync_exception(etmq, tidq, magic))
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
			packet->flags = PERF_IP_FLAG_BRANCH |
					PERF_IP_FLAG_CALL |
					PERF_IP_FLAG_INTERRUPT;

		/*
		 * When the exception packet is inserted, since exception
		 * packet is not used standalone for generating samples
		 * and it's affiliation to the previous instruction range
		 * packet; so set previous range packet flags to tell perf
		 * it is an exception taken branch.
		 */
		if (prev_packet->sample_type == CS_ETM_RANGE)
			prev_packet->flags = packet->flags;
		break;
1961
	case CS_ETM_EXCEPTION_RET:
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
		/*
		 * When the exception return packet is inserted, since
		 * exception return packet is not used standalone for
		 * generating samples and it's affiliation to the previous
		 * instruction range packet; so set previous range packet
		 * flags to tell perf it is an exception return branch.
		 *
		 * The exception return can be for either system call or
		 * other exception types; unfortunately the packet doesn't
		 * contain exception type related info so we cannot decide
		 * the exception type purely based on exception return packet.
		 * If we record the exception number from exception packet and
1974
		 * reuse it for exception return packet, this is not reliable
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991
		 * due the trace can be discontinuity or the interrupt can
		 * be nested, thus the recorded exception number cannot be
		 * used for exception return packet for these two cases.
		 *
		 * For exception return packet, we only need to distinguish the
		 * packet is for system call or for other types.  Thus the
		 * decision can be deferred when receive the next packet which
		 * contains the return address, based on the return address we
		 * can read out the previous instruction and check if it's a
		 * system call instruction and then calibrate the sample flag
		 * as needed.
		 */
		if (prev_packet->sample_type == CS_ETM_RANGE)
			prev_packet->flags = PERF_IP_FLAG_BRANCH |
					     PERF_IP_FLAG_RETURN |
					     PERF_IP_FLAG_INTERRUPT;
		break;
1992 1993 1994 1995 1996 1997 1998 1999
	case CS_ETM_EMPTY:
	default:
		break;
	}

	return 0;
}

2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
static int cs_etm__decode_data_block(struct cs_etm_queue *etmq)
{
	int ret = 0;
	size_t processed = 0;

	/*
	 * Packets are decoded and added to the decoder's packet queue
	 * until the decoder packet processing callback has requested that
	 * processing stops or there is nothing left in the buffer.  Normal
	 * operations that stop processing are a timestamp packet or a full
	 * decoder buffer queue.
	 */
	ret = cs_etm_decoder__process_data_block(etmq->decoder,
						 etmq->offset,
						 &etmq->buf[etmq->buf_used],
						 etmq->buf_len,
						 &processed);
	if (ret)
		goto out;

	etmq->offset += processed;
	etmq->buf_used += processed;
	etmq->buf_len -= processed;

out:
	return ret;
}

2028 2029
static int cs_etm__process_traceid_queue(struct cs_etm_queue *etmq,
					 struct cs_etm_traceid_queue *tidq)
2030 2031
{
	int ret;
2032 2033
	struct cs_etm_packet_queue *packet_queue;

2034
	packet_queue = &tidq->packet_queue;
2035

2036 2037 2038
	/* Process each packet in this chunk */
	while (1) {
		ret = cs_etm_decoder__get_packet(packet_queue,
2039
						 tidq->packet);
2040 2041 2042 2043 2044 2045
		if (ret <= 0)
			/*
			 * Stop processing this chunk on
			 * end of data or error
			 */
			break;
2046

2047 2048 2049 2050 2051 2052 2053
		/*
		 * Since packet addresses are swapped in packet
		 * handling within below switch() statements,
		 * thus setting sample flags must be called
		 * prior to switch() statement to use address
		 * information before packets swapping.
		 */
2054
		ret = cs_etm__set_sample_flags(etmq, tidq);
2055 2056 2057
		if (ret < 0)
			break;

2058
		switch (tidq->packet->sample_type) {
2059 2060 2061 2062 2063 2064
		case CS_ETM_RANGE:
			/*
			 * If the packet contains an instruction
			 * range, generate instruction sequence
			 * events.
			 */
2065
			cs_etm__sample(etmq, tidq);
2066 2067 2068
			break;
		case CS_ETM_EXCEPTION:
		case CS_ETM_EXCEPTION_RET:
2069
			/*
2070 2071 2072
			 * If the exception packet is coming,
			 * make sure the previous instruction
			 * range packet to be handled properly.
2073
			 */
2074
			cs_etm__exception(tidq);
2075 2076 2077 2078 2079 2080
			break;
		case CS_ETM_DISCONTINUITY:
			/*
			 * Discontinuity in trace, flush
			 * previous branch stack
			 */
2081
			cs_etm__flush(etmq, tidq);
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
			break;
		case CS_ETM_EMPTY:
			/*
			 * Should not receive empty packet,
			 * report error.
			 */
			pr_err("CS ETM Trace: empty packet\n");
			return -EINVAL;
		default:
			break;
2092
		}
2093
	}
2094 2095 2096 2097

	return ret;
}

2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
static void cs_etm__clear_all_traceid_queues(struct cs_etm_queue *etmq)
{
	int idx;
	struct int_node *inode;
	struct cs_etm_traceid_queue *tidq;
	struct intlist *traceid_queues_list = etmq->traceid_queues_list;

	intlist__for_each_entry(inode, traceid_queues_list) {
		idx = (int)(intptr_t)inode->priv;
		tidq = etmq->traceid_queues[idx];

		/* Ignore return value */
		cs_etm__process_traceid_queue(etmq, tidq);

		/*
		 * Generate an instruction sample with the remaining
		 * branchstack entries.
		 */
		cs_etm__flush(etmq, tidq);
	}
}

2120 2121 2122
static int cs_etm__run_decoder(struct cs_etm_queue *etmq)
{
	int err = 0;
2123 2124 2125 2126 2127
	struct cs_etm_traceid_queue *tidq;

	tidq = cs_etm__etmq_get_traceid_queue(etmq, CS_ETM_PER_THREAD_TRACEID);
	if (!tidq)
		return -EINVAL;
2128 2129

	/* Go through each buffer in the queue and decode them one by one */
2130
	while (1) {
2131 2132 2133
		err = cs_etm__get_data_block(etmq);
		if (err <= 0)
			return err;
2134

2135 2136
		/* Run trace decoder until buffer consumed or end of trace */
		do {
2137
			err = cs_etm__decode_data_block(etmq);
2138 2139 2140
			if (err)
				return err;

2141 2142 2143 2144 2145
			/*
			 * Process each packet in this chunk, nothing to do if
			 * an error occurs other than hoping the next one will
			 * be better.
			 */
2146
			err = cs_etm__process_traceid_queue(etmq, tidq);
2147

2148
		} while (etmq->buf_len);
2149

2150 2151
		if (err == 0)
			/* Flush any remaining branch stack entries */
2152
			err = cs_etm__end_block(etmq, tidq);
2153
	}
2154 2155 2156 2157 2158

	return err;
}

static int cs_etm__process_timeless_queues(struct cs_etm_auxtrace *etm,
2159
					   pid_t tid)
2160 2161 2162 2163 2164 2165 2166
{
	unsigned int i;
	struct auxtrace_queues *queues = &etm->queues;

	for (i = 0; i < queues->nr_queues; i++) {
		struct auxtrace_queue *queue = &etm->queues.queue_array[i];
		struct cs_etm_queue *etmq = queue->priv;
2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
		struct cs_etm_traceid_queue *tidq;

		if (!etmq)
			continue;

		tidq = cs_etm__etmq_get_traceid_queue(etmq,
						CS_ETM_PER_THREAD_TRACEID);

		if (!tidq)
			continue;
2177

2178
		if ((tid == -1) || (tidq->tid == tid)) {
2179
			cs_etm__set_pid_tid_cpu(etm, tidq);
2180 2181 2182 2183 2184 2185 2186
			cs_etm__run_decoder(etmq);
		}
	}

	return 0;
}

2187 2188 2189
static int cs_etm__process_queues(struct cs_etm_auxtrace *etm)
{
	int ret = 0;
2190
	unsigned int cs_queue_nr, queue_nr, i;
2191
	u8 trace_chan_id;
2192
	u64 cs_timestamp;
2193 2194 2195 2196
	struct auxtrace_queue *queue;
	struct cs_etm_queue *etmq;
	struct cs_etm_traceid_queue *tidq;

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
	/*
	 * Pre-populate the heap with one entry from each queue so that we can
	 * start processing in time order across all queues.
	 */
	for (i = 0; i < etm->queues.nr_queues; i++) {
		etmq = etm->queues.queue_array[i].priv;
		if (!etmq)
			continue;

		ret = cs_etm__queue_first_cs_timestamp(etm, etmq, i);
		if (ret)
			return ret;
	}

2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
	while (1) {
		if (!etm->heap.heap_cnt)
			goto out;

		/* Take the entry at the top of the min heap */
		cs_queue_nr = etm->heap.heap_array[0].queue_nr;
		queue_nr = TO_QUEUE_NR(cs_queue_nr);
		trace_chan_id = TO_TRACE_CHAN_ID(cs_queue_nr);
		queue = &etm->queues.queue_array[queue_nr];
		etmq = queue->priv;

		/*
		 * Remove the top entry from the heap since we are about
		 * to process it.
		 */
		auxtrace_heap__pop(&etm->heap);

		tidq  = cs_etm__etmq_get_traceid_queue(etmq, trace_chan_id);
		if (!tidq) {
			/*
			 * No traceID queue has been allocated for this traceID,
			 * which means something somewhere went very wrong.  No
			 * other choice than simply exit.
			 */
			ret = -EINVAL;
			goto out;
		}

		/*
		 * Packets associated with this timestamp are already in
		 * the etmq's traceID queue, so process them.
		 */
		ret = cs_etm__process_traceid_queue(etmq, tidq);
		if (ret < 0)
			goto out;

		/*
		 * Packets for this timestamp have been processed, time to
		 * move on to the next timestamp, fetching a new auxtrace_buffer
		 * if need be.
		 */
refetch:
		ret = cs_etm__get_data_block(etmq);
		if (ret < 0)
			goto out;

		/*
		 * No more auxtrace_buffers to process in this etmq, simply
		 * move on to another entry in the auxtrace_heap.
		 */
		if (!ret)
			continue;

		ret = cs_etm__decode_data_block(etmq);
		if (ret)
			goto out;

2268
		cs_timestamp = cs_etm__etmq_get_timestamp(etmq, &trace_chan_id);
2269

2270
		if (!cs_timestamp) {
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
			/*
			 * Function cs_etm__decode_data_block() returns when
			 * there is no more traces to decode in the current
			 * auxtrace_buffer OR when a timestamp has been
			 * encountered on any of the traceID queues.  Since we
			 * did not get a timestamp, there is no more traces to
			 * process in this auxtrace_buffer.  As such empty and
			 * flush all traceID queues.
			 */
			cs_etm__clear_all_traceid_queues(etmq);

			/* Fetch another auxtrace_buffer for this etmq */
			goto refetch;
		}

		/*
		 * Add to the min heap the timestamp for packets that have
		 * just been decoded.  They will be processed and synthesized
		 * during the next call to cs_etm__process_traceid_queue() for
		 * this queue/traceID.
		 */
		cs_queue_nr = TO_CS_QUEUE_NR(queue_nr, trace_chan_id);
2293
		ret = auxtrace_heap__add(&etm->heap, cs_queue_nr, cs_timestamp);
2294 2295 2296 2297 2298 2299
	}

out:
	return ret;
}

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
static int cs_etm__process_itrace_start(struct cs_etm_auxtrace *etm,
					union perf_event *event)
{
	struct thread *th;

	if (etm->timeless_decoding)
		return 0;

	/*
	 * Add the tid/pid to the log so that we can get a match when
	 * we get a contextID from the decoder.
	 */
	th = machine__findnew_thread(etm->machine,
				     event->itrace_start.pid,
				     event->itrace_start.tid);
	if (!th)
		return -ENOMEM;

	thread__put(th);

	return 0;
}

2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
static int cs_etm__process_switch_cpu_wide(struct cs_etm_auxtrace *etm,
					   union perf_event *event)
{
	struct thread *th;
	bool out = event->header.misc & PERF_RECORD_MISC_SWITCH_OUT;

	/*
	 * Context switch in per-thread mode are irrelevant since perf
	 * will start/stop tracing as the process is scheduled.
	 */
	if (etm->timeless_decoding)
		return 0;

	/*
	 * SWITCH_IN events carry the next process to be switched out while
	 * SWITCH_OUT events carry the process to be switched in.  As such
	 * we don't care about IN events.
	 */
	if (!out)
		return 0;

	/*
	 * Add the tid/pid to the log so that we can get a match when
	 * we get a contextID from the decoder.
	 */
	th = machine__findnew_thread(etm->machine,
				     event->context_switch.next_prev_pid,
				     event->context_switch.next_prev_tid);
	if (!th)
		return -ENOMEM;

	thread__put(th);

	return 0;
}

2359 2360 2361 2362 2363
static int cs_etm__process_event(struct perf_session *session,
				 union perf_event *event,
				 struct perf_sample *sample,
				 struct perf_tool *tool)
{
2364
	u64 sample_kernel_timestamp;
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);

	if (dump_trace)
		return 0;

	if (!tool->ordered_events) {
		pr_err("CoreSight ETM Trace requires ordered events\n");
		return -EINVAL;
	}

	if (sample->time && (sample->time != (u64) -1))
2378
		sample_kernel_timestamp = sample->time;
2379
	else
2380
		sample_kernel_timestamp = 0;
2381

2382 2383 2384 2385 2386
	/*
	 * Don't wait for cs_etm__flush_events() in per-thread/timeless mode to start the decode. We
	 * need the tid of the PERF_RECORD_EXIT event to assign to the synthesised samples because
	 * ETM_OPT_CTXTID is not enabled.
	 */
2387 2388
	if (etm->timeless_decoding &&
	    event->header.type == PERF_RECORD_EXIT)
2389
		return cs_etm__process_timeless_queues(etm,
2390
						       event->fork.tid);
2391

2392 2393
	if (event->header.type == PERF_RECORD_ITRACE_START)
		return cs_etm__process_itrace_start(etm, event);
2394 2395
	else if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE)
		return cs_etm__process_switch_cpu_wide(etm, event);
2396

2397 2398 2399 2400 2401 2402 2403 2404
	if (!etm->timeless_decoding && event->header.type == PERF_RECORD_AUX) {
		/*
		 * Record the latest kernel timestamp available in the header
		 * for samples so that synthesised samples occur from this point
		 * onwards.
		 */
		etm->latest_kernel_timestamp = sample_kernel_timestamp;
	}
2405

2406 2407 2408
	return 0;
}

2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
static void dump_queued_data(struct cs_etm_auxtrace *etm,
			     struct perf_record_auxtrace *event)
{
	struct auxtrace_buffer *buf;
	unsigned int i;
	/*
	 * Find all buffers with same reference in the queues and dump them.
	 * This is because the queues can contain multiple entries of the same
	 * buffer that were split on aux records.
	 */
	for (i = 0; i < etm->queues.nr_queues; ++i)
		list_for_each_entry(buf, &etm->queues.queue_array[i].head, list)
			if (buf->reference == event->reference)
2422
				cs_etm__dump_event(etm->queues.queue_array[i].priv, buf);
2423 2424
}

2425 2426
static int cs_etm__process_auxtrace_event(struct perf_session *session,
					  union perf_event *event,
2427
					  struct perf_tool *tool __maybe_unused)
2428
{
2429 2430 2431 2432 2433 2434 2435 2436 2437
	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);
	if (!etm->data_queued) {
		struct auxtrace_buffer *buffer;
		off_t  data_offset;
		int fd = perf_data__fd(session->data);
		bool is_pipe = perf_data__is_pipe(session->data);
		int err;
2438
		int idx = event->auxtrace.idx;
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452

		if (is_pipe)
			data_offset = 0;
		else {
			data_offset = lseek(fd, 0, SEEK_CUR);
			if (data_offset == -1)
				return -errno;
		}

		err = auxtrace_queues__add_event(&etm->queues, session,
						 event, data_offset, &buffer);
		if (err)
			return err;

2453 2454 2455 2456 2457 2458
		/*
		 * Knowing if the trace is formatted or not requires a lookup of
		 * the aux record so only works in non-piped mode where data is
		 * queued in cs_etm__queue_aux_records(). Always assume
		 * formatted in piped mode (true).
		 */
2459
		err = cs_etm__setup_queue(etm, &etm->queues.queue_array[idx],
2460
					  idx, true);
2461 2462 2463
		if (err)
			return err;

2464 2465
		if (dump_trace)
			if (auxtrace_buffer__get_data(buffer, fd)) {
2466
				cs_etm__dump_event(etm->queues.queue_array[idx].priv, buffer);
2467 2468
				auxtrace_buffer__put_data(buffer);
			}
2469 2470
	} else if (dump_trace)
		dump_queued_data(etm, &event->auxtrace);
2471

2472 2473 2474 2475 2476
	return 0;
}

static bool cs_etm__is_timeless_decoding(struct cs_etm_auxtrace *etm)
{
2477
	struct evsel *evsel;
2478
	struct evlist *evlist = etm->session->evlist;
2479 2480
	bool timeless_decoding = true;

2481 2482 2483 2484
	/* Override timeless mode with user input from --itrace=Z */
	if (etm->synth_opts.timeless_decoding)
		return true;

2485 2486 2487 2488 2489
	/*
	 * Circle through the list of event and complain if we find one
	 * with the time bit set.
	 */
	evlist__for_each_entry(evlist, evsel) {
2490
		if ((evsel->core.attr.sample_type & PERF_SAMPLE_TIME))
2491 2492 2493 2494 2495 2496
			timeless_decoding = false;
	}

	return timeless_decoding;
}

2497
static const char * const cs_etm_global_header_fmts[] = {
2498
	[CS_HEADER_VERSION]	= "	Header version		       %llx\n",
2499 2500 2501 2502 2503 2504 2505
	[CS_PMU_TYPE_CPUS]	= "	PMU type/num cpus	       %llx\n",
	[CS_ETM_SNAPSHOT]	= "	Snapshot		       %llx\n",
};

static const char * const cs_etm_priv_fmts[] = {
	[CS_ETM_MAGIC]		= "	Magic number		       %llx\n",
	[CS_ETM_CPU]		= "	CPU			       %lld\n",
2506
	[CS_ETM_NR_TRC_PARAMS]	= "	NR_TRC_PARAMS		       %llx\n",
2507 2508 2509 2510 2511 2512 2513 2514 2515
	[CS_ETM_ETMCR]		= "	ETMCR			       %llx\n",
	[CS_ETM_ETMTRACEIDR]	= "	ETMTRACEIDR		       %llx\n",
	[CS_ETM_ETMCCER]	= "	ETMCCER			       %llx\n",
	[CS_ETM_ETMIDR]		= "	ETMIDR			       %llx\n",
};

static const char * const cs_etmv4_priv_fmts[] = {
	[CS_ETM_MAGIC]		= "	Magic number		       %llx\n",
	[CS_ETM_CPU]		= "	CPU			       %lld\n",
2516
	[CS_ETM_NR_TRC_PARAMS]	= "	NR_TRC_PARAMS		       %llx\n",
2517 2518 2519 2520 2521 2522 2523
	[CS_ETMV4_TRCCONFIGR]	= "	TRCCONFIGR		       %llx\n",
	[CS_ETMV4_TRCTRACEIDR]	= "	TRCTRACEIDR		       %llx\n",
	[CS_ETMV4_TRCIDR0]	= "	TRCIDR0			       %llx\n",
	[CS_ETMV4_TRCIDR1]	= "	TRCIDR1			       %llx\n",
	[CS_ETMV4_TRCIDR2]	= "	TRCIDR2			       %llx\n",
	[CS_ETMV4_TRCIDR8]	= "	TRCIDR8			       %llx\n",
	[CS_ETMV4_TRCAUTHSTATUS] = "	TRCAUTHSTATUS		       %llx\n",
2524
	[CS_ETE_TRCDEVARCH]	= "	TRCDEVARCH                     %llx\n"
2525 2526
};

2527 2528 2529 2530 2531 2532
static const char * const param_unk_fmt =
	"	Unknown parameter [%d]	       %llx\n";
static const char * const magic_unk_fmt =
	"	Magic number Unknown	       %llx\n";

static int cs_etm__print_cpu_metadata_v0(__u64 *val, int *offset)
2533
{
2534 2535
	int i = *offset, j, nr_params = 0, fmt_offset;
	__u64 magic;
2536

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
	/* check magic value */
	magic = val[i + CS_ETM_MAGIC];
	if ((magic != __perf_cs_etmv3_magic) &&
	    (magic != __perf_cs_etmv4_magic)) {
		/* failure - note bad magic value */
		fprintf(stdout, magic_unk_fmt, magic);
		return -EINVAL;
	}

	/* print common header block */
	fprintf(stdout, cs_etm_priv_fmts[CS_ETM_MAGIC], val[i++]);
	fprintf(stdout, cs_etm_priv_fmts[CS_ETM_CPU], val[i++]);

	if (magic == __perf_cs_etmv3_magic) {
		nr_params = CS_ETM_NR_TRC_PARAMS_V0;
		fmt_offset = CS_ETM_ETMCR;
		/* after common block, offset format index past NR_PARAMS */
		for (j = fmt_offset; j < nr_params + fmt_offset; j++, i++)
			fprintf(stdout, cs_etm_priv_fmts[j], val[i]);
	} else if (magic == __perf_cs_etmv4_magic) {
		nr_params = CS_ETMV4_NR_TRC_PARAMS_V0;
		fmt_offset = CS_ETMV4_TRCCONFIGR;
		/* after common block, offset format index past NR_PARAMS */
		for (j = fmt_offset; j < nr_params + fmt_offset; j++, i++)
			fprintf(stdout, cs_etmv4_priv_fmts[j], val[i]);
	}
	*offset = i;
	return 0;
}

static int cs_etm__print_cpu_metadata_v1(__u64 *val, int *offset)
{
	int i = *offset, j, total_params = 0;
	__u64 magic;

	magic = val[i + CS_ETM_MAGIC];
	/* total params to print is NR_PARAMS + common block size for v1 */
	total_params = val[i + CS_ETM_NR_TRC_PARAMS] + CS_ETM_COMMON_BLK_MAX_V1;
2575

2576 2577 2578 2579 2580 2581
	if (magic == __perf_cs_etmv3_magic) {
		for (j = 0; j < total_params; j++, i++) {
			/* if newer record - could be excess params */
			if (j >= CS_ETM_PRIV_MAX)
				fprintf(stdout, param_unk_fmt, j, val[i]);
			else
2582
				fprintf(stdout, cs_etm_priv_fmts[j], val[i]);
2583
		}
2584 2585 2586 2587 2588 2589
	} else if (magic == __perf_cs_etmv4_magic || magic == __perf_cs_ete_magic) {
		/*
		 * ETE and ETMv4 can be printed in the same block because the number of parameters
		 * is saved and they share the list of parameter names. ETE is also only supported
		 * in V1 files.
		 */
2590 2591
		for (j = 0; j < total_params; j++, i++) {
			/* if newer record - could be excess params */
2592
			if (j >= CS_ETE_PRIV_MAX)
2593 2594
				fprintf(stdout, param_unk_fmt, j, val[i]);
			else
2595
				fprintf(stdout, cs_etmv4_priv_fmts[j], val[i]);
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
		}
	} else {
		/* failure - note bad magic value and error out */
		fprintf(stdout, magic_unk_fmt, magic);
		return -EINVAL;
	}
	*offset = i;
	return 0;
}

static void cs_etm__print_auxtrace_info(__u64 *val, int num)
{
	int i, cpu = 0, version, err;

	/* bail out early on bad header version */
	version = val[0];
	if (version > CS_HEADER_CURRENT_VERSION) {
		/* failure.. return */
		fprintf(stdout, "	Unknown Header Version = %x, ", version);
		fprintf(stdout, "Version supported <= %x\n", CS_HEADER_CURRENT_VERSION);
		return;
	}

	for (i = 0; i < CS_HEADER_VERSION_MAX; i++)
		fprintf(stdout, cs_etm_global_header_fmts[i], val[i]);

	for (i = CS_HEADER_VERSION_MAX; cpu < num; cpu++) {
		if (version == 0)
			err = cs_etm__print_cpu_metadata_v0(val, &i);
		else if (version == 1)
			err = cs_etm__print_cpu_metadata_v1(val, &i);
		if (err)
2628 2629 2630 2631
			return;
	}
}

2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
/*
 * Read a single cpu parameter block from the auxtrace_info priv block.
 *
 * For version 1 there is a per cpu nr_params entry. If we are handling
 * version 1 file, then there may be less, the same, or more params
 * indicated by this value than the compile time number we understand.
 *
 * For a version 0 info block, there are a fixed number, and we need to
 * fill out the nr_param value in the metadata we create.
 */
static u64 *cs_etm__create_meta_blk(u64 *buff_in, int *buff_in_offset,
				    int out_blk_size, int nr_params_v0)
{
	u64 *metadata = NULL;
	int hdr_version;
	int nr_in_params, nr_out_params, nr_cmn_params;
	int i, k;

	metadata = zalloc(sizeof(*metadata) * out_blk_size);
	if (!metadata)
		return NULL;

	/* read block current index & version */
	i = *buff_in_offset;
	hdr_version = buff_in[CS_HEADER_VERSION];

	if (!hdr_version) {
	/* read version 0 info block into a version 1 metadata block  */
		nr_in_params = nr_params_v0;
		metadata[CS_ETM_MAGIC] = buff_in[i + CS_ETM_MAGIC];
		metadata[CS_ETM_CPU] = buff_in[i + CS_ETM_CPU];
		metadata[CS_ETM_NR_TRC_PARAMS] = nr_in_params;
		/* remaining block params at offset +1 from source */
		for (k = CS_ETM_COMMON_BLK_MAX_V1 - 1; k < nr_in_params; k++)
			metadata[k + 1] = buff_in[i + k];
		/* version 0 has 2 common params */
		nr_cmn_params = 2;
	} else {
	/* read version 1 info block - input and output nr_params may differ */
		/* version 1 has 3 common params */
		nr_cmn_params = 3;
		nr_in_params = buff_in[i + CS_ETM_NR_TRC_PARAMS];

		/* if input has more params than output - skip excess */
		nr_out_params = nr_in_params + nr_cmn_params;
		if (nr_out_params > out_blk_size)
			nr_out_params = out_blk_size;

		for (k = CS_ETM_MAGIC; k < nr_out_params; k++)
			metadata[k] = buff_in[i + k];

		/* record the actual nr params we copied */
		metadata[CS_ETM_NR_TRC_PARAMS] = nr_out_params - nr_cmn_params;
	}

	/* adjust in offset by number of in params used */
	i += nr_in_params + nr_cmn_params;
	*buff_in_offset = i;
	return metadata;
}

2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
/**
 * Puts a fragment of an auxtrace buffer into the auxtrace queues based
 * on the bounds of aux_event, if it matches with the buffer that's at
 * file_offset.
 *
 * Normally, whole auxtrace buffers would be added to the queue. But we
 * want to reset the decoder for every PERF_RECORD_AUX event, and the decoder
 * is reset across each buffer, so splitting the buffers up in advance has
 * the same effect.
 */
static int cs_etm__queue_aux_fragment(struct perf_session *session, off_t file_offset, size_t sz,
				      struct perf_record_aux *aux_event, struct perf_sample *sample)
{
	int err;
	char buf[PERF_SAMPLE_MAX_SIZE];
	union perf_event *auxtrace_event_union;
	struct perf_record_auxtrace *auxtrace_event;
	union perf_event auxtrace_fragment;
	__u64 aux_offset, aux_size;
2712
	__u32 idx;
2713
	bool formatted;
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774

	struct cs_etm_auxtrace *etm = container_of(session->auxtrace,
						   struct cs_etm_auxtrace,
						   auxtrace);

	/*
	 * There should be a PERF_RECORD_AUXTRACE event at the file_offset that we got
	 * from looping through the auxtrace index.
	 */
	err = perf_session__peek_event(session, file_offset, buf,
				       PERF_SAMPLE_MAX_SIZE, &auxtrace_event_union, NULL);
	if (err)
		return err;
	auxtrace_event = &auxtrace_event_union->auxtrace;
	if (auxtrace_event->header.type != PERF_RECORD_AUXTRACE)
		return -EINVAL;

	if (auxtrace_event->header.size < sizeof(struct perf_record_auxtrace) ||
		auxtrace_event->header.size != sz) {
		return -EINVAL;
	}

	/*
	 * In per-thread mode, CPU is set to -1, but TID will be set instead. See
	 * auxtrace_mmap_params__set_idx(). Return 'not found' if neither CPU nor TID match.
	 */
	if ((auxtrace_event->cpu == (__u32) -1 && auxtrace_event->tid != sample->tid) ||
			auxtrace_event->cpu != sample->cpu)
		return 1;

	if (aux_event->flags & PERF_AUX_FLAG_OVERWRITE) {
		/*
		 * Clamp size in snapshot mode. The buffer size is clamped in
		 * __auxtrace_mmap__read() for snapshots, so the aux record size doesn't reflect
		 * the buffer size.
		 */
		aux_size = min(aux_event->aux_size, auxtrace_event->size);

		/*
		 * In this mode, the head also points to the end of the buffer so aux_offset
		 * needs to have the size subtracted so it points to the beginning as in normal mode
		 */
		aux_offset = aux_event->aux_offset - aux_size;
	} else {
		aux_size = aux_event->aux_size;
		aux_offset = aux_event->aux_offset;
	}

	if (aux_offset >= auxtrace_event->offset &&
	    aux_offset + aux_size <= auxtrace_event->offset + auxtrace_event->size) {
		/*
		 * If this AUX event was inside this buffer somewhere, create a new auxtrace event
		 * based on the sizes of the aux event, and queue that fragment.
		 */
		auxtrace_fragment.auxtrace = *auxtrace_event;
		auxtrace_fragment.auxtrace.size = aux_size;
		auxtrace_fragment.auxtrace.offset = aux_offset;
		file_offset += aux_offset - auxtrace_event->offset + auxtrace_event->header.size;

		pr_debug3("CS ETM: Queue buffer size: %#"PRI_lx64" offset: %#"PRI_lx64
			  " tid: %d cpu: %d\n", aux_size, aux_offset, sample->tid, sample->cpu);
2775 2776 2777 2778 2779 2780
		err = auxtrace_queues__add_event(&etm->queues, session, &auxtrace_fragment,
						 file_offset, NULL);
		if (err)
			return err;

		idx = auxtrace_event->idx;
2781 2782 2783
		formatted = !(aux_event->flags & PERF_AUX_FLAG_CORESIGHT_FORMAT_RAW);
		return cs_etm__setup_queue(etm, &etm->queues.queue_array[idx],
					   idx, formatted);
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867
	}

	/* Wasn't inside this buffer, but there were no parse errors. 1 == 'not found' */
	return 1;
}

static int cs_etm__queue_aux_records_cb(struct perf_session *session, union perf_event *event,
					u64 offset __maybe_unused, void *data __maybe_unused)
{
	struct perf_sample sample;
	int ret;
	struct auxtrace_index_entry *ent;
	struct auxtrace_index *auxtrace_index;
	struct evsel *evsel;
	size_t i;

	/* Don't care about any other events, we're only queuing buffers for AUX events */
	if (event->header.type != PERF_RECORD_AUX)
		return 0;

	if (event->header.size < sizeof(struct perf_record_aux))
		return -EINVAL;

	/* Truncated Aux records can have 0 size and shouldn't result in anything being queued. */
	if (!event->aux.aux_size)
		return 0;

	/*
	 * Parse the sample, we need the sample_id_all data that comes after the event so that the
	 * CPU or PID can be matched to an AUXTRACE buffer's CPU or PID.
	 */
	evsel = evlist__event2evsel(session->evlist, event);
	if (!evsel)
		return -EINVAL;
	ret = evsel__parse_sample(evsel, event, &sample);
	if (ret)
		return ret;

	/*
	 * Loop through the auxtrace index to find the buffer that matches up with this aux event.
	 */
	list_for_each_entry(auxtrace_index, &session->auxtrace_index, list) {
		for (i = 0; i < auxtrace_index->nr; i++) {
			ent = &auxtrace_index->entries[i];
			ret = cs_etm__queue_aux_fragment(session, ent->file_offset,
							 ent->sz, &event->aux, &sample);
			/*
			 * Stop search on error or successful values. Continue search on
			 * 1 ('not found')
			 */
			if (ret != 1)
				return ret;
		}
	}

	/*
	 * Couldn't find the buffer corresponding to this aux record, something went wrong. Warn but
	 * don't exit with an error because it will still be possible to decode other aux records.
	 */
	pr_err("CS ETM: Couldn't find auxtrace buffer for aux_offset: %#"PRI_lx64
	       " tid: %d cpu: %d\n", event->aux.aux_offset, sample.tid, sample.cpu);
	return 0;
}

static int cs_etm__queue_aux_records(struct perf_session *session)
{
	struct auxtrace_index *index = list_first_entry_or_null(&session->auxtrace_index,
								struct auxtrace_index, list);
	if (index && index->nr > 0)
		return perf_session__peek_events(session, session->header.data_offset,
						 session->header.data_size,
						 cs_etm__queue_aux_records_cb, NULL);

	/*
	 * We would get here if there are no entries in the index (either no auxtrace
	 * buffers or no index at all). Fail silently as there is the possibility of
	 * queueing them in cs_etm__process_auxtrace_event() if etm->data_queued is still
	 * false.
	 *
	 * In that scenario, buffers will not be split by AUX records.
	 */
	return 0;
}

2868 2869 2870
int cs_etm__process_auxtrace_info(union perf_event *event,
				  struct perf_session *session)
{
2871
	struct perf_record_auxtrace_info *auxtrace_info = &event->auxtrace_info;
2872
	struct cs_etm_auxtrace *etm = NULL;
2873 2874
	struct int_node *inode;
	unsigned int pmu_type;
2875 2876 2877
	int event_header_size = sizeof(struct perf_event_header);
	int info_header_size;
	int total_size = auxtrace_info->header.size;
2878
	int priv_size = 0;
2879 2880 2881
	int num_cpu, trcidr_idx;
	int err = 0;
	int i, j;
2882 2883
	u64 *ptr, *hdr = NULL;
	u64 **metadata = NULL;
2884
	u64 hdr_version;
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894

	/*
	 * sizeof(auxtrace_info_event::type) +
	 * sizeof(auxtrace_info_event::reserved) == 8
	 */
	info_header_size = 8;

	if (total_size < (event_header_size + info_header_size))
		return -EINVAL;

2895 2896 2897 2898 2899
	priv_size = total_size - event_header_size - info_header_size;

	/* First the global part */
	ptr = (u64 *) auxtrace_info->priv;

2900 2901 2902 2903 2904 2905
	/* Look for version of the header */
	hdr_version = ptr[0];
	if (hdr_version > CS_HEADER_CURRENT_VERSION) {
		/* print routine will print an error on bad version */
		if (dump_trace)
			cs_etm__print_auxtrace_info(auxtrace_info->priv, 0);
2906
		return -EINVAL;
2907
	}
2908

2909
	hdr = zalloc(sizeof(*hdr) * CS_HEADER_VERSION_MAX);
2910 2911 2912 2913
	if (!hdr)
		return -ENOMEM;

	/* Extract header information - see cs-etm.h for format */
2914
	for (i = 0; i < CS_HEADER_VERSION_MAX; i++)
2915 2916 2917 2918 2919 2920
		hdr[i] = ptr[i];
	num_cpu = hdr[CS_PMU_TYPE_CPUS] & 0xffffffff;
	pmu_type = (unsigned int) ((hdr[CS_PMU_TYPE_CPUS] >> 32) &
				    0xffffffff);

	/*
2921 2922 2923
	 * Create an RB tree for traceID-metadata tuple.  Since the conversion
	 * has to be made for each packet that gets decoded, optimizing access
	 * in anything other than a sequential array is worth doing.
2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
	 */
	traceid_list = intlist__new(NULL);
	if (!traceid_list) {
		err = -ENOMEM;
		goto err_free_hdr;
	}

	metadata = zalloc(sizeof(*metadata) * num_cpu);
	if (!metadata) {
		err = -ENOMEM;
		goto err_free_traceid_list;
	}

	/*
	 * The metadata is stored in the auxtrace_info section and encodes
	 * the configuration of the ARM embedded trace macrocell which is
	 * required by the trace decoder to properly decode the trace due
	 * to its highly compressed nature.
	 */
	for (j = 0; j < num_cpu; j++) {
		if (ptr[i] == __perf_cs_etmv3_magic) {
2945 2946 2947 2948
			metadata[j] =
				cs_etm__create_meta_blk(ptr, &i,
							CS_ETM_PRIV_MAX,
							CS_ETM_NR_TRC_PARAMS_V0);
2949 2950

			/* The traceID is our handle */
2951 2952
			trcidr_idx = CS_ETM_ETMTRACEIDR;

2953
		} else if (ptr[i] == __perf_cs_etmv4_magic) {
2954 2955 2956 2957
			metadata[j] =
				cs_etm__create_meta_blk(ptr, &i,
							CS_ETMV4_PRIV_MAX,
							CS_ETMV4_NR_TRC_PARAMS_V0);
2958 2959

			/* The traceID is our handle */
2960
			trcidr_idx = CS_ETMV4_TRCTRACEIDR;
2961 2962 2963 2964 2965
		} else if (ptr[i] == __perf_cs_ete_magic) {
			metadata[j] = cs_etm__create_meta_blk(ptr, &i, CS_ETE_PRIV_MAX, -1);

			/* ETE shares first part of metadata with ETMv4 */
			trcidr_idx = CS_ETMV4_TRCTRACEIDR;
2966 2967 2968 2969 2970
		}

		if (!metadata[j]) {
			err = -ENOMEM;
			goto err_free_metadata;
2971 2972 2973
		}

		/* Get an RB node for this CPU */
2974
		inode = intlist__findnew(traceid_list, metadata[j][trcidr_idx]);
2975 2976 2977

		/* Something went wrong, no need to continue */
		if (!inode) {
2978
			err = -ENOMEM;
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
			goto err_free_metadata;
		}

		/*
		 * The node for that CPU should not be taken.
		 * Back out if that's the case.
		 */
		if (inode->priv) {
			err = -EINVAL;
			goto err_free_metadata;
		}
2990 2991
		/* All good, associate the traceID with the metadata pointer */
		inode->priv = metadata[j];
2992 2993 2994
	}

	/*
2995
	 * Each of CS_HEADER_VERSION_MAX, CS_ETM_PRIV_MAX and
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
	 * CS_ETMV4_PRIV_MAX mark how many double words are in the
	 * global metadata, and each cpu's metadata respectively.
	 * The following tests if the correct number of double words was
	 * present in the auxtrace info section.
	 */
	if (i * 8 != priv_size) {
		err = -EINVAL;
		goto err_free_metadata;
	}

3006 3007
	etm = zalloc(sizeof(*etm));

3008
	if (!etm) {
3009
		err = -ENOMEM;
3010 3011
		goto err_free_metadata;
	}
3012 3013 3014 3015 3016

	err = auxtrace_queues__init(&etm->queues);
	if (err)
		goto err_free_etm;

3017 3018 3019 3020 3021 3022 3023 3024
	if (session->itrace_synth_opts->set) {
		etm->synth_opts = *session->itrace_synth_opts;
	} else {
		itrace_synth_opts__set_default(&etm->synth_opts,
				session->itrace_synth_opts->default_no_sample);
		etm->synth_opts.callchain = false;
	}

3025 3026 3027
	etm->session = session;
	etm->machine = &session->machines.host;

3028 3029 3030 3031
	etm->num_cpu = num_cpu;
	etm->pmu_type = pmu_type;
	etm->snapshot_mode = (hdr[CS_ETM_SNAPSHOT] != 0);
	etm->metadata = metadata;
3032 3033 3034 3035 3036 3037 3038 3039
	etm->auxtrace_type = auxtrace_info->type;
	etm->timeless_decoding = cs_etm__is_timeless_decoding(etm);

	etm->auxtrace.process_event = cs_etm__process_event;
	etm->auxtrace.process_auxtrace_event = cs_etm__process_auxtrace_event;
	etm->auxtrace.flush_events = cs_etm__flush_events;
	etm->auxtrace.free_events = cs_etm__free_events;
	etm->auxtrace.free = cs_etm__free;
3040
	etm->auxtrace.evsel_is_auxtrace = cs_etm__evsel_is_auxtrace;
3041 3042
	session->auxtrace = &etm->auxtrace;

3043
	etm->unknown_thread = thread__new(999999999, 999999999);
3044 3045
	if (!etm->unknown_thread) {
		err = -ENOMEM;
3046
		goto err_free_queues;
3047
	}
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058

	/*
	 * Initialize list node so that at thread__zput() we can avoid
	 * segmentation fault at list_del_init().
	 */
	INIT_LIST_HEAD(&etm->unknown_thread->node);

	err = thread__set_comm(etm->unknown_thread, "unknown", 0);
	if (err)
		goto err_delete_thread;

3059
	if (thread__init_maps(etm->unknown_thread, etm->machine)) {
3060
		err = -ENOMEM;
3061
		goto err_delete_thread;
3062
	}
3063

3064 3065 3066
	if (dump_trace) {
		cs_etm__print_auxtrace_info(auxtrace_info->priv, num_cpu);
	}
3067

3068 3069
	err = cs_etm__synth_events(etm, session);
	if (err)
3070
		goto err_delete_thread;
3071

3072
	err = cs_etm__queue_aux_records(session);
3073
	if (err)
3074
		goto err_delete_thread;
3075 3076

	etm->data_queued = etm->queues.populated;
3077 3078 3079 3080 3081 3082 3083
	/*
	 * Print warning in pipe mode, see cs_etm__process_auxtrace_event() and
	 * cs_etm__queue_aux_fragment() for details relating to limitations.
	 */
	if (!etm->data_queued)
		pr_warning("CS ETM warning: Coresight decode and TRBE support requires random file access.\n"
			   "Continuing with best effort decoding in piped mode.\n\n");
3084 3085 3086

	return 0;

3087 3088
err_delete_thread:
	thread__zput(etm->unknown_thread);
3089 3090 3091 3092 3093
err_free_queues:
	auxtrace_queues__free(&etm->queues);
	session->auxtrace = NULL;
err_free_etm:
	zfree(&etm);
3094 3095 3096
err_free_metadata:
	/* No need to check @metadata[j], free(NULL) is supported */
	for (j = 0; j < num_cpu; j++)
3097
		zfree(&metadata[j]);
3098 3099 3100 3101 3102
	zfree(&metadata);
err_free_traceid_list:
	intlist__delete(traceid_list);
err_free_hdr:
	zfree(&hdr);
3103 3104 3105 3106 3107 3108 3109
	/*
	 * At this point, as a minimum we have valid header. Dump the rest of
	 * the info section - the print routines will error out on structural
	 * issues.
	 */
	if (dump_trace)
		cs_etm__print_auxtrace_info(auxtrace_info->priv, num_cpu);
3110
	return err;
3111
}