Linux Audio

Check our new training course

Loading...
   1#define _FILE_OFFSET_BITS 64
   2
   3#include <linux/kernel.h>
   4
   5#include <byteswap.h>
   6#include <unistd.h>
   7#include <sys/types.h>
   8#include <sys/mman.h>
   9
  10#include "evlist.h"
  11#include "evsel.h"
  12#include "session.h"
  13#include "tool.h"
  14#include "sort.h"
  15#include "util.h"
  16#include "cpumap.h"
  17
  18static int perf_session__open(struct perf_session *self, bool force)
  19{
  20	struct stat input_stat;
  21
  22	if (!strcmp(self->filename, "-")) {
  23		self->fd_pipe = true;
  24		self->fd = STDIN_FILENO;
  25
  26		if (perf_session__read_header(self, self->fd) < 0)
  27			pr_err("incompatible file format (rerun with -v to learn more)");
  28
  29		return 0;
  30	}
  31
  32	self->fd = open(self->filename, O_RDONLY);
  33	if (self->fd < 0) {
  34		int err = errno;
  35
  36		pr_err("failed to open %s: %s", self->filename, strerror(err));
  37		if (err == ENOENT && !strcmp(self->filename, "perf.data"))
  38			pr_err("  (try 'perf record' first)");
  39		pr_err("\n");
  40		return -errno;
  41	}
  42
  43	if (fstat(self->fd, &input_stat) < 0)
  44		goto out_close;
  45
  46	if (!force && input_stat.st_uid && (input_stat.st_uid != geteuid())) {
  47		pr_err("file %s not owned by current user or root\n",
  48		       self->filename);
  49		goto out_close;
  50	}
  51
  52	if (!input_stat.st_size) {
  53		pr_info("zero-sized file (%s), nothing to do!\n",
  54			self->filename);
  55		goto out_close;
  56	}
  57
  58	if (perf_session__read_header(self, self->fd) < 0) {
  59		pr_err("incompatible file format (rerun with -v to learn more)");
  60		goto out_close;
  61	}
  62
  63	if (!perf_evlist__valid_sample_type(self->evlist)) {
  64		pr_err("non matching sample_type");
  65		goto out_close;
  66	}
  67
  68	if (!perf_evlist__valid_sample_id_all(self->evlist)) {
  69		pr_err("non matching sample_id_all");
  70		goto out_close;
  71	}
  72
  73	self->size = input_stat.st_size;
  74	return 0;
  75
  76out_close:
  77	close(self->fd);
  78	self->fd = -1;
  79	return -1;
  80}
  81
  82void perf_session__update_sample_type(struct perf_session *self)
  83{
  84	self->sample_type = perf_evlist__sample_type(self->evlist);
  85	self->sample_size = __perf_evsel__sample_size(self->sample_type);
  86	self->sample_id_all = perf_evlist__sample_id_all(self->evlist);
  87	self->id_hdr_size = perf_evlist__id_hdr_size(self->evlist);
  88	self->host_machine.id_hdr_size = self->id_hdr_size;
  89}
  90
  91int perf_session__create_kernel_maps(struct perf_session *self)
  92{
  93	int ret = machine__create_kernel_maps(&self->host_machine);
  94
  95	if (ret >= 0)
  96		ret = machines__create_guest_kernel_maps(&self->machines);
  97	return ret;
  98}
  99
 100static void perf_session__destroy_kernel_maps(struct perf_session *self)
 101{
 102	machine__destroy_kernel_maps(&self->host_machine);
 103	machines__destroy_guest_kernel_maps(&self->machines);
 104}
 105
 106struct perf_session *perf_session__new(const char *filename, int mode,
 107				       bool force, bool repipe,
 108				       struct perf_tool *tool)
 109{
 110	struct perf_session *self;
 111	struct stat st;
 112	size_t len;
 113
 114	if (!filename || !strlen(filename)) {
 115		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
 116			filename = "-";
 117		else
 118			filename = "perf.data";
 119	}
 120
 121	len = strlen(filename);
 122	self = zalloc(sizeof(*self) + len);
 123
 124	if (self == NULL)
 125		goto out;
 126
 127	memcpy(self->filename, filename, len);
 128	/*
 129	 * On 64bit we can mmap the data file in one go. No need for tiny mmap
 130	 * slices. On 32bit we use 32MB.
 131	 */
 132#if BITS_PER_LONG == 64
 133	self->mmap_window = ULLONG_MAX;
 134#else
 135	self->mmap_window = 32 * 1024 * 1024ULL;
 136#endif
 137	self->machines = RB_ROOT;
 138	self->repipe = repipe;
 139	INIT_LIST_HEAD(&self->ordered_samples.samples);
 140	INIT_LIST_HEAD(&self->ordered_samples.sample_cache);
 141	INIT_LIST_HEAD(&self->ordered_samples.to_free);
 142	machine__init(&self->host_machine, "", HOST_KERNEL_ID);
 143	hists__init(&self->hists);
 144
 145	if (mode == O_RDONLY) {
 146		if (perf_session__open(self, force) < 0)
 147			goto out_delete;
 148		perf_session__update_sample_type(self);
 149	} else if (mode == O_WRONLY) {
 150		/*
 151		 * In O_RDONLY mode this will be performed when reading the
 152		 * kernel MMAP event, in perf_event__process_mmap().
 153		 */
 154		if (perf_session__create_kernel_maps(self) < 0)
 155			goto out_delete;
 156	}
 157
 158	if (tool && tool->ordering_requires_timestamps &&
 159	    tool->ordered_samples && !self->sample_id_all) {
 160		dump_printf("WARNING: No sample_id_all support, falling back to unordered processing\n");
 161		tool->ordered_samples = false;
 162	}
 163
 164out:
 165	return self;
 166out_delete:
 167	perf_session__delete(self);
 168	return NULL;
 169}
 170
 171static void machine__delete_dead_threads(struct machine *machine)
 172{
 173	struct thread *n, *t;
 174
 175	list_for_each_entry_safe(t, n, &machine->dead_threads, node) {
 176		list_del(&t->node);
 177		thread__delete(t);
 178	}
 179}
 180
 181static void perf_session__delete_dead_threads(struct perf_session *session)
 182{
 183	machine__delete_dead_threads(&session->host_machine);
 184}
 185
 186static void machine__delete_threads(struct machine *self)
 187{
 188	struct rb_node *nd = rb_first(&self->threads);
 189
 190	while (nd) {
 191		struct thread *t = rb_entry(nd, struct thread, rb_node);
 192
 193		rb_erase(&t->rb_node, &self->threads);
 194		nd = rb_next(nd);
 195		thread__delete(t);
 196	}
 197}
 198
 199static void perf_session__delete_threads(struct perf_session *session)
 200{
 201	machine__delete_threads(&session->host_machine);
 202}
 203
 204void perf_session__delete(struct perf_session *self)
 205{
 206	perf_session__destroy_kernel_maps(self);
 207	perf_session__delete_dead_threads(self);
 208	perf_session__delete_threads(self);
 209	machine__exit(&self->host_machine);
 210	close(self->fd);
 211	free(self);
 212}
 213
 214void machine__remove_thread(struct machine *self, struct thread *th)
 215{
 216	self->last_match = NULL;
 217	rb_erase(&th->rb_node, &self->threads);
 218	/*
 219	 * We may have references to this thread, for instance in some hist_entry
 220	 * instances, so just move them to a separate list.
 221	 */
 222	list_add_tail(&th->node, &self->dead_threads);
 223}
 224
 225static bool symbol__match_parent_regex(struct symbol *sym)
 226{
 227	if (sym->name && !regexec(&parent_regex, sym->name, 0, NULL, 0))
 228		return 1;
 229
 230	return 0;
 231}
 232
 233static const u8 cpumodes[] = {
 234	PERF_RECORD_MISC_USER,
 235	PERF_RECORD_MISC_KERNEL,
 236	PERF_RECORD_MISC_GUEST_USER,
 237	PERF_RECORD_MISC_GUEST_KERNEL
 238};
 239#define NCPUMODES (sizeof(cpumodes)/sizeof(u8))
 240
 241static void ip__resolve_ams(struct machine *self, struct thread *thread,
 242			    struct addr_map_symbol *ams,
 243			    u64 ip)
 244{
 245	struct addr_location al;
 246	size_t i;
 247	u8 m;
 248
 249	memset(&al, 0, sizeof(al));
 250
 251	for (i = 0; i < NCPUMODES; i++) {
 252		m = cpumodes[i];
 253		/*
 254		 * We cannot use the header.misc hint to determine whether a
 255		 * branch stack address is user, kernel, guest, hypervisor.
 256		 * Branches may straddle the kernel/user/hypervisor boundaries.
 257		 * Thus, we have to try consecutively until we find a match
 258		 * or else, the symbol is unknown
 259		 */
 260		thread__find_addr_location(thread, self, m, MAP__FUNCTION,
 261				ip, &al, NULL);
 262		if (al.sym)
 263			goto found;
 264	}
 265found:
 266	ams->addr = ip;
 267	ams->al_addr = al.addr;
 268	ams->sym = al.sym;
 269	ams->map = al.map;
 270}
 271
 272struct branch_info *machine__resolve_bstack(struct machine *self,
 273					    struct thread *thr,
 274					    struct branch_stack *bs)
 275{
 276	struct branch_info *bi;
 277	unsigned int i;
 278
 279	bi = calloc(bs->nr, sizeof(struct branch_info));
 280	if (!bi)
 281		return NULL;
 282
 283	for (i = 0; i < bs->nr; i++) {
 284		ip__resolve_ams(self, thr, &bi[i].to, bs->entries[i].to);
 285		ip__resolve_ams(self, thr, &bi[i].from, bs->entries[i].from);
 286		bi[i].flags = bs->entries[i].flags;
 287	}
 288	return bi;
 289}
 290
 291int machine__resolve_callchain(struct machine *self,
 292			       struct perf_evsel *evsel __used,
 293			       struct thread *thread,
 294			       struct ip_callchain *chain,
 295			       struct symbol **parent)
 296{
 297	u8 cpumode = PERF_RECORD_MISC_USER;
 298	unsigned int i;
 299	int err;
 300
 301	callchain_cursor_reset(&callchain_cursor);
 302
 303	if (chain->nr > PERF_MAX_STACK_DEPTH) {
 304		pr_warning("corrupted callchain. skipping...\n");
 305		return 0;
 306	}
 307
 308	for (i = 0; i < chain->nr; i++) {
 309		u64 ip;
 310		struct addr_location al;
 311
 312		if (callchain_param.order == ORDER_CALLEE)
 313			ip = chain->ips[i];
 314		else
 315			ip = chain->ips[chain->nr - i - 1];
 316
 317		if (ip >= PERF_CONTEXT_MAX) {
 318			switch (ip) {
 319			case PERF_CONTEXT_HV:
 320				cpumode = PERF_RECORD_MISC_HYPERVISOR;	break;
 321			case PERF_CONTEXT_KERNEL:
 322				cpumode = PERF_RECORD_MISC_KERNEL;	break;
 323			case PERF_CONTEXT_USER:
 324				cpumode = PERF_RECORD_MISC_USER;	break;
 325			default:
 326				pr_debug("invalid callchain context: "
 327					 "%"PRId64"\n", (s64) ip);
 328				/*
 329				 * It seems the callchain is corrupted.
 330				 * Discard all.
 331				 */
 332				callchain_cursor_reset(&callchain_cursor);
 333				return 0;
 334			}
 335			continue;
 336		}
 337
 338		al.filtered = false;
 339		thread__find_addr_location(thread, self, cpumode,
 340					   MAP__FUNCTION, ip, &al, NULL);
 341		if (al.sym != NULL) {
 342			if (sort__has_parent && !*parent &&
 343			    symbol__match_parent_regex(al.sym))
 344				*parent = al.sym;
 345			if (!symbol_conf.use_callchain)
 346				break;
 347		}
 348
 349		err = callchain_cursor_append(&callchain_cursor,
 350					      ip, al.map, al.sym);
 351		if (err)
 352			return err;
 353	}
 354
 355	return 0;
 356}
 357
 358static int process_event_synth_tracing_data_stub(union perf_event *event __used,
 359						 struct perf_session *session __used)
 360{
 361	dump_printf(": unhandled!\n");
 362	return 0;
 363}
 364
 365static int process_event_synth_attr_stub(union perf_event *event __used,
 366					 struct perf_evlist **pevlist __used)
 367{
 368	dump_printf(": unhandled!\n");
 369	return 0;
 370}
 371
 372static int process_event_sample_stub(struct perf_tool *tool __used,
 373				     union perf_event *event __used,
 374				     struct perf_sample *sample __used,
 375				     struct perf_evsel *evsel __used,
 376				     struct machine *machine __used)
 377{
 378	dump_printf(": unhandled!\n");
 379	return 0;
 380}
 381
 382static int process_event_stub(struct perf_tool *tool __used,
 383			      union perf_event *event __used,
 384			      struct perf_sample *sample __used,
 385			      struct machine *machine __used)
 386{
 387	dump_printf(": unhandled!\n");
 388	return 0;
 389}
 390
 391static int process_finished_round_stub(struct perf_tool *tool __used,
 392				       union perf_event *event __used,
 393				       struct perf_session *perf_session __used)
 394{
 395	dump_printf(": unhandled!\n");
 396	return 0;
 397}
 398
 399static int process_event_type_stub(struct perf_tool *tool __used,
 400				   union perf_event *event __used)
 401{
 402	dump_printf(": unhandled!\n");
 403	return 0;
 404}
 405
 406static int process_finished_round(struct perf_tool *tool,
 407				  union perf_event *event,
 408				  struct perf_session *session);
 409
 410static void perf_tool__fill_defaults(struct perf_tool *tool)
 411{
 412	if (tool->sample == NULL)
 413		tool->sample = process_event_sample_stub;
 414	if (tool->mmap == NULL)
 415		tool->mmap = process_event_stub;
 416	if (tool->comm == NULL)
 417		tool->comm = process_event_stub;
 418	if (tool->fork == NULL)
 419		tool->fork = process_event_stub;
 420	if (tool->exit == NULL)
 421		tool->exit = process_event_stub;
 422	if (tool->lost == NULL)
 423		tool->lost = perf_event__process_lost;
 424	if (tool->read == NULL)
 425		tool->read = process_event_sample_stub;
 426	if (tool->throttle == NULL)
 427		tool->throttle = process_event_stub;
 428	if (tool->unthrottle == NULL)
 429		tool->unthrottle = process_event_stub;
 430	if (tool->attr == NULL)
 431		tool->attr = process_event_synth_attr_stub;
 432	if (tool->event_type == NULL)
 433		tool->event_type = process_event_type_stub;
 434	if (tool->tracing_data == NULL)
 435		tool->tracing_data = process_event_synth_tracing_data_stub;
 436	if (tool->build_id == NULL)
 437		tool->build_id = process_finished_round_stub;
 438	if (tool->finished_round == NULL) {
 439		if (tool->ordered_samples)
 440			tool->finished_round = process_finished_round;
 441		else
 442			tool->finished_round = process_finished_round_stub;
 443	}
 444}
 445 
 446void mem_bswap_32(void *src, int byte_size)
 447{
 448	u32 *m = src;
 449	while (byte_size > 0) {
 450		*m = bswap_32(*m);
 451		byte_size -= sizeof(u32);
 452		++m;
 453	}
 454}
 455
 456void mem_bswap_64(void *src, int byte_size)
 457{
 458	u64 *m = src;
 459
 460	while (byte_size > 0) {
 461		*m = bswap_64(*m);
 462		byte_size -= sizeof(u64);
 463		++m;
 464	}
 465}
 466
 467static void swap_sample_id_all(union perf_event *event, void *data)
 468{
 469	void *end = (void *) event + event->header.size;
 470	int size = end - data;
 471
 472	BUG_ON(size % sizeof(u64));
 473	mem_bswap_64(data, size);
 474}
 475
 476static void perf_event__all64_swap(union perf_event *event,
 477				   bool sample_id_all __used)
 478{
 479	struct perf_event_header *hdr = &event->header;
 480	mem_bswap_64(hdr + 1, event->header.size - sizeof(*hdr));
 481}
 482
 483static void perf_event__comm_swap(union perf_event *event, bool sample_id_all)
 484{
 485	event->comm.pid = bswap_32(event->comm.pid);
 486	event->comm.tid = bswap_32(event->comm.tid);
 487
 488	if (sample_id_all) {
 489		void *data = &event->comm.comm;
 490
 491		data += ALIGN(strlen(data) + 1, sizeof(u64));
 492		swap_sample_id_all(event, data);
 493	}
 494}
 495
 496static void perf_event__mmap_swap(union perf_event *event,
 497				  bool sample_id_all)
 498{
 499	event->mmap.pid	  = bswap_32(event->mmap.pid);
 500	event->mmap.tid	  = bswap_32(event->mmap.tid);
 501	event->mmap.start = bswap_64(event->mmap.start);
 502	event->mmap.len	  = bswap_64(event->mmap.len);
 503	event->mmap.pgoff = bswap_64(event->mmap.pgoff);
 504
 505	if (sample_id_all) {
 506		void *data = &event->mmap.filename;
 507
 508		data += ALIGN(strlen(data) + 1, sizeof(u64));
 509		swap_sample_id_all(event, data);
 510	}
 511}
 512
 513static void perf_event__task_swap(union perf_event *event, bool sample_id_all)
 514{
 515	event->fork.pid	 = bswap_32(event->fork.pid);
 516	event->fork.tid	 = bswap_32(event->fork.tid);
 517	event->fork.ppid = bswap_32(event->fork.ppid);
 518	event->fork.ptid = bswap_32(event->fork.ptid);
 519	event->fork.time = bswap_64(event->fork.time);
 520
 521	if (sample_id_all)
 522		swap_sample_id_all(event, &event->fork + 1);
 523}
 524
 525static void perf_event__read_swap(union perf_event *event, bool sample_id_all)
 526{
 527	event->read.pid		 = bswap_32(event->read.pid);
 528	event->read.tid		 = bswap_32(event->read.tid);
 529	event->read.value	 = bswap_64(event->read.value);
 530	event->read.time_enabled = bswap_64(event->read.time_enabled);
 531	event->read.time_running = bswap_64(event->read.time_running);
 532	event->read.id		 = bswap_64(event->read.id);
 533
 534	if (sample_id_all)
 535		swap_sample_id_all(event, &event->read + 1);
 536}
 537
 538static u8 revbyte(u8 b)
 539{
 540	int rev = (b >> 4) | ((b & 0xf) << 4);
 541	rev = ((rev & 0xcc) >> 2) | ((rev & 0x33) << 2);
 542	rev = ((rev & 0xaa) >> 1) | ((rev & 0x55) << 1);
 543	return (u8) rev;
 544}
 545
 546/*
 547 * XXX this is hack in attempt to carry flags bitfield
 548 * throught endian village. ABI says:
 549 *
 550 * Bit-fields are allocated from right to left (least to most significant)
 551 * on little-endian implementations and from left to right (most to least
 552 * significant) on big-endian implementations.
 553 *
 554 * The above seems to be byte specific, so we need to reverse each
 555 * byte of the bitfield. 'Internet' also says this might be implementation
 556 * specific and we probably need proper fix and carry perf_event_attr
 557 * bitfield flags in separate data file FEAT_ section. Thought this seems
 558 * to work for now.
 559 */
 560static void swap_bitfield(u8 *p, unsigned len)
 561{
 562	unsigned i;
 563
 564	for (i = 0; i < len; i++) {
 565		*p = revbyte(*p);
 566		p++;
 567	}
 568}
 569
 570/* exported for swapping attributes in file header */
 571void perf_event__attr_swap(struct perf_event_attr *attr)
 572{
 573	attr->type		= bswap_32(attr->type);
 574	attr->size		= bswap_32(attr->size);
 575	attr->config		= bswap_64(attr->config);
 576	attr->sample_period	= bswap_64(attr->sample_period);
 577	attr->sample_type	= bswap_64(attr->sample_type);
 578	attr->read_format	= bswap_64(attr->read_format);
 579	attr->wakeup_events	= bswap_32(attr->wakeup_events);
 580	attr->bp_type		= bswap_32(attr->bp_type);
 581	attr->bp_addr		= bswap_64(attr->bp_addr);
 582	attr->bp_len		= bswap_64(attr->bp_len);
 583
 584	swap_bitfield((u8 *) (&attr->read_format + 1), sizeof(u64));
 585}
 586
 587static void perf_event__hdr_attr_swap(union perf_event *event,
 588				      bool sample_id_all __used)
 589{
 590	size_t size;
 591
 592	perf_event__attr_swap(&event->attr.attr);
 593
 594	size = event->header.size;
 595	size -= (void *)&event->attr.id - (void *)event;
 596	mem_bswap_64(event->attr.id, size);
 597}
 598
 599static void perf_event__event_type_swap(union perf_event *event,
 600					bool sample_id_all __used)
 601{
 602	event->event_type.event_type.event_id =
 603		bswap_64(event->event_type.event_type.event_id);
 604}
 605
 606static void perf_event__tracing_data_swap(union perf_event *event,
 607					  bool sample_id_all __used)
 608{
 609	event->tracing_data.size = bswap_32(event->tracing_data.size);
 610}
 611
 612typedef void (*perf_event__swap_op)(union perf_event *event,
 613				    bool sample_id_all);
 614
 615static perf_event__swap_op perf_event__swap_ops[] = {
 616	[PERF_RECORD_MMAP]		  = perf_event__mmap_swap,
 617	[PERF_RECORD_COMM]		  = perf_event__comm_swap,
 618	[PERF_RECORD_FORK]		  = perf_event__task_swap,
 619	[PERF_RECORD_EXIT]		  = perf_event__task_swap,
 620	[PERF_RECORD_LOST]		  = perf_event__all64_swap,
 621	[PERF_RECORD_READ]		  = perf_event__read_swap,
 622	[PERF_RECORD_SAMPLE]		  = perf_event__all64_swap,
 623	[PERF_RECORD_HEADER_ATTR]	  = perf_event__hdr_attr_swap,
 624	[PERF_RECORD_HEADER_EVENT_TYPE]	  = perf_event__event_type_swap,
 625	[PERF_RECORD_HEADER_TRACING_DATA] = perf_event__tracing_data_swap,
 626	[PERF_RECORD_HEADER_BUILD_ID]	  = NULL,
 627	[PERF_RECORD_HEADER_MAX]	  = NULL,
 628};
 629
 630struct sample_queue {
 631	u64			timestamp;
 632	u64			file_offset;
 633	union perf_event	*event;
 634	struct list_head	list;
 635};
 636
 637static void perf_session_free_sample_buffers(struct perf_session *session)
 638{
 639	struct ordered_samples *os = &session->ordered_samples;
 640
 641	while (!list_empty(&os->to_free)) {
 642		struct sample_queue *sq;
 643
 644		sq = list_entry(os->to_free.next, struct sample_queue, list);
 645		list_del(&sq->list);
 646		free(sq);
 647	}
 648}
 649
 650static int perf_session_deliver_event(struct perf_session *session,
 651				      union perf_event *event,
 652				      struct perf_sample *sample,
 653				      struct perf_tool *tool,
 654				      u64 file_offset);
 655
 656static void flush_sample_queue(struct perf_session *s,
 657			       struct perf_tool *tool)
 658{
 659	struct ordered_samples *os = &s->ordered_samples;
 660	struct list_head *head = &os->samples;
 661	struct sample_queue *tmp, *iter;
 662	struct perf_sample sample;
 663	u64 limit = os->next_flush;
 664	u64 last_ts = os->last_sample ? os->last_sample->timestamp : 0ULL;
 665	unsigned idx = 0, progress_next = os->nr_samples / 16;
 666	int ret;
 667
 668	if (!tool->ordered_samples || !limit)
 669		return;
 670
 671	list_for_each_entry_safe(iter, tmp, head, list) {
 672		if (iter->timestamp > limit)
 673			break;
 674
 675		ret = perf_session__parse_sample(s, iter->event, &sample);
 676		if (ret)
 677			pr_err("Can't parse sample, err = %d\n", ret);
 678		else
 679			perf_session_deliver_event(s, iter->event, &sample, tool,
 680						   iter->file_offset);
 681
 682		os->last_flush = iter->timestamp;
 683		list_del(&iter->list);
 684		list_add(&iter->list, &os->sample_cache);
 685		if (++idx >= progress_next) {
 686			progress_next += os->nr_samples / 16;
 687			ui_progress__update(idx, os->nr_samples,
 688					    "Processing time ordered events...");
 689		}
 690	}
 691
 692	if (list_empty(head)) {
 693		os->last_sample = NULL;
 694	} else if (last_ts <= limit) {
 695		os->last_sample =
 696			list_entry(head->prev, struct sample_queue, list);
 697	}
 698
 699	os->nr_samples = 0;
 700}
 701
 702/*
 703 * When perf record finishes a pass on every buffers, it records this pseudo
 704 * event.
 705 * We record the max timestamp t found in the pass n.
 706 * Assuming these timestamps are monotonic across cpus, we know that if
 707 * a buffer still has events with timestamps below t, they will be all
 708 * available and then read in the pass n + 1.
 709 * Hence when we start to read the pass n + 2, we can safely flush every
 710 * events with timestamps below t.
 711 *
 712 *    ============ PASS n =================
 713 *       CPU 0         |   CPU 1
 714 *                     |
 715 *    cnt1 timestamps  |   cnt2 timestamps
 716 *          1          |         2
 717 *          2          |         3
 718 *          -          |         4  <--- max recorded
 719 *
 720 *    ============ PASS n + 1 ==============
 721 *       CPU 0         |   CPU 1
 722 *                     |
 723 *    cnt1 timestamps  |   cnt2 timestamps
 724 *          3          |         5
 725 *          4          |         6
 726 *          5          |         7 <---- max recorded
 727 *
 728 *      Flush every events below timestamp 4
 729 *
 730 *    ============ PASS n + 2 ==============
 731 *       CPU 0         |   CPU 1
 732 *                     |
 733 *    cnt1 timestamps  |   cnt2 timestamps
 734 *          6          |         8
 735 *          7          |         9
 736 *          -          |         10
 737 *
 738 *      Flush every events below timestamp 7
 739 *      etc...
 740 */
 741static int process_finished_round(struct perf_tool *tool,
 742				  union perf_event *event __used,
 743				  struct perf_session *session)
 744{
 745	flush_sample_queue(session, tool);
 746	session->ordered_samples.next_flush = session->ordered_samples.max_timestamp;
 747
 748	return 0;
 749}
 750
 751/* The queue is ordered by time */
 752static void __queue_event(struct sample_queue *new, struct perf_session *s)
 753{
 754	struct ordered_samples *os = &s->ordered_samples;
 755	struct sample_queue *sample = os->last_sample;
 756	u64 timestamp = new->timestamp;
 757	struct list_head *p;
 758
 759	++os->nr_samples;
 760	os->last_sample = new;
 761
 762	if (!sample) {
 763		list_add(&new->list, &os->samples);
 764		os->max_timestamp = timestamp;
 765		return;
 766	}
 767
 768	/*
 769	 * last_sample might point to some random place in the list as it's
 770	 * the last queued event. We expect that the new event is close to
 771	 * this.
 772	 */
 773	if (sample->timestamp <= timestamp) {
 774		while (sample->timestamp <= timestamp) {
 775			p = sample->list.next;
 776			if (p == &os->samples) {
 777				list_add_tail(&new->list, &os->samples);
 778				os->max_timestamp = timestamp;
 779				return;
 780			}
 781			sample = list_entry(p, struct sample_queue, list);
 782		}
 783		list_add_tail(&new->list, &sample->list);
 784	} else {
 785		while (sample->timestamp > timestamp) {
 786			p = sample->list.prev;
 787			if (p == &os->samples) {
 788				list_add(&new->list, &os->samples);
 789				return;
 790			}
 791			sample = list_entry(p, struct sample_queue, list);
 792		}
 793		list_add(&new->list, &sample->list);
 794	}
 795}
 796
 797#define MAX_SAMPLE_BUFFER	(64 * 1024 / sizeof(struct sample_queue))
 798
 799static int perf_session_queue_event(struct perf_session *s, union perf_event *event,
 800				    struct perf_sample *sample, u64 file_offset)
 801{
 802	struct ordered_samples *os = &s->ordered_samples;
 803	struct list_head *sc = &os->sample_cache;
 804	u64 timestamp = sample->time;
 805	struct sample_queue *new;
 806
 807	if (!timestamp || timestamp == ~0ULL)
 808		return -ETIME;
 809
 810	if (timestamp < s->ordered_samples.last_flush) {
 811		printf("Warning: Timestamp below last timeslice flush\n");
 812		return -EINVAL;
 813	}
 814
 815	if (!list_empty(sc)) {
 816		new = list_entry(sc->next, struct sample_queue, list);
 817		list_del(&new->list);
 818	} else if (os->sample_buffer) {
 819		new = os->sample_buffer + os->sample_buffer_idx;
 820		if (++os->sample_buffer_idx == MAX_SAMPLE_BUFFER)
 821			os->sample_buffer = NULL;
 822	} else {
 823		os->sample_buffer = malloc(MAX_SAMPLE_BUFFER * sizeof(*new));
 824		if (!os->sample_buffer)
 825			return -ENOMEM;
 826		list_add(&os->sample_buffer->list, &os->to_free);
 827		os->sample_buffer_idx = 2;
 828		new = os->sample_buffer + 1;
 829	}
 830
 831	new->timestamp = timestamp;
 832	new->file_offset = file_offset;
 833	new->event = event;
 834
 835	__queue_event(new, s);
 836
 837	return 0;
 838}
 839
 840static void callchain__printf(struct perf_sample *sample)
 841{
 842	unsigned int i;
 843
 844	printf("... chain: nr:%" PRIu64 "\n", sample->callchain->nr);
 845
 846	for (i = 0; i < sample->callchain->nr; i++)
 847		printf("..... %2d: %016" PRIx64 "\n",
 848		       i, sample->callchain->ips[i]);
 849}
 850
 851static void branch_stack__printf(struct perf_sample *sample)
 852{
 853	uint64_t i;
 854
 855	printf("... branch stack: nr:%" PRIu64 "\n", sample->branch_stack->nr);
 856
 857	for (i = 0; i < sample->branch_stack->nr; i++)
 858		printf("..... %2"PRIu64": %016" PRIx64 " -> %016" PRIx64 "\n",
 859			i, sample->branch_stack->entries[i].from,
 860			sample->branch_stack->entries[i].to);
 861}
 862
 863static void perf_session__print_tstamp(struct perf_session *session,
 864				       union perf_event *event,
 865				       struct perf_sample *sample)
 866{
 867	if (event->header.type != PERF_RECORD_SAMPLE &&
 868	    !session->sample_id_all) {
 869		fputs("-1 -1 ", stdout);
 870		return;
 871	}
 872
 873	if ((session->sample_type & PERF_SAMPLE_CPU))
 874		printf("%u ", sample->cpu);
 875
 876	if (session->sample_type & PERF_SAMPLE_TIME)
 877		printf("%" PRIu64 " ", sample->time);
 878}
 879
 880static void dump_event(struct perf_session *session, union perf_event *event,
 881		       u64 file_offset, struct perf_sample *sample)
 882{
 883	if (!dump_trace)
 884		return;
 885
 886	printf("\n%#" PRIx64 " [%#x]: event: %d\n",
 887	       file_offset, event->header.size, event->header.type);
 888
 889	trace_event(event);
 890
 891	if (sample)
 892		perf_session__print_tstamp(session, event, sample);
 893
 894	printf("%#" PRIx64 " [%#x]: PERF_RECORD_%s", file_offset,
 895	       event->header.size, perf_event__name(event->header.type));
 896}
 897
 898static void dump_sample(struct perf_session *session, union perf_event *event,
 899			struct perf_sample *sample)
 900{
 901	if (!dump_trace)
 902		return;
 903
 904	printf("(IP, %d): %d/%d: %#" PRIx64 " period: %" PRIu64 " addr: %#" PRIx64 "\n",
 905	       event->header.misc, sample->pid, sample->tid, sample->ip,
 906	       sample->period, sample->addr);
 907
 908	if (session->sample_type & PERF_SAMPLE_CALLCHAIN)
 909		callchain__printf(sample);
 910
 911	if (session->sample_type & PERF_SAMPLE_BRANCH_STACK)
 912		branch_stack__printf(sample);
 913}
 914
 915static struct machine *
 916	perf_session__find_machine_for_cpumode(struct perf_session *session,
 917					       union perf_event *event)
 918{
 919	const u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
 920
 921	if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL && perf_guest) {
 922		u32 pid;
 923
 924		if (event->header.type == PERF_RECORD_MMAP)
 925			pid = event->mmap.pid;
 926		else
 927			pid = event->ip.pid;
 928
 929		return perf_session__findnew_machine(session, pid);
 930	}
 931
 932	return perf_session__find_host_machine(session);
 933}
 934
 935static int perf_session_deliver_event(struct perf_session *session,
 936				      union perf_event *event,
 937				      struct perf_sample *sample,
 938				      struct perf_tool *tool,
 939				      u64 file_offset)
 940{
 941	struct perf_evsel *evsel;
 942	struct machine *machine;
 943
 944	dump_event(session, event, file_offset, sample);
 945
 946	evsel = perf_evlist__id2evsel(session->evlist, sample->id);
 947	if (evsel != NULL && event->header.type != PERF_RECORD_SAMPLE) {
 948		/*
 949		 * XXX We're leaving PERF_RECORD_SAMPLE unnacounted here
 950		 * because the tools right now may apply filters, discarding
 951		 * some of the samples. For consistency, in the future we
 952		 * should have something like nr_filtered_samples and remove
 953		 * the sample->period from total_sample_period, etc, KISS for
 954		 * now tho.
 955		 *
 956		 * Also testing against NULL allows us to handle files without
 957		 * attr.sample_id_all and/or without PERF_SAMPLE_ID. In the
 958		 * future probably it'll be a good idea to restrict event
 959		 * processing via perf_session to files with both set.
 960		 */
 961		hists__inc_nr_events(&evsel->hists, event->header.type);
 962	}
 963
 964	machine = perf_session__find_machine_for_cpumode(session, event);
 965
 966	switch (event->header.type) {
 967	case PERF_RECORD_SAMPLE:
 968		dump_sample(session, event, sample);
 969		if (evsel == NULL) {
 970			++session->hists.stats.nr_unknown_id;
 971			return 0;
 972		}
 973		if (machine == NULL) {
 974			++session->hists.stats.nr_unprocessable_samples;
 975			return 0;
 976		}
 977		return tool->sample(tool, event, sample, evsel, machine);
 978	case PERF_RECORD_MMAP:
 979		return tool->mmap(tool, event, sample, machine);
 980	case PERF_RECORD_COMM:
 981		return tool->comm(tool, event, sample, machine);
 982	case PERF_RECORD_FORK:
 983		return tool->fork(tool, event, sample, machine);
 984	case PERF_RECORD_EXIT:
 985		return tool->exit(tool, event, sample, machine);
 986	case PERF_RECORD_LOST:
 987		if (tool->lost == perf_event__process_lost)
 988			session->hists.stats.total_lost += event->lost.lost;
 989		return tool->lost(tool, event, sample, machine);
 990	case PERF_RECORD_READ:
 991		return tool->read(tool, event, sample, evsel, machine);
 992	case PERF_RECORD_THROTTLE:
 993		return tool->throttle(tool, event, sample, machine);
 994	case PERF_RECORD_UNTHROTTLE:
 995		return tool->unthrottle(tool, event, sample, machine);
 996	default:
 997		++session->hists.stats.nr_unknown_events;
 998		return -1;
 999	}
1000}
1001
1002static int perf_session__preprocess_sample(struct perf_session *session,
1003					   union perf_event *event, struct perf_sample *sample)
1004{
1005	if (event->header.type != PERF_RECORD_SAMPLE ||
1006	    !(session->sample_type & PERF_SAMPLE_CALLCHAIN))
1007		return 0;
1008
1009	if (!ip_callchain__valid(sample->callchain, event)) {
1010		pr_debug("call-chain problem with event, skipping it.\n");
1011		++session->hists.stats.nr_invalid_chains;
1012		session->hists.stats.total_invalid_chains += sample->period;
1013		return -EINVAL;
1014	}
1015	return 0;
1016}
1017
1018static int perf_session__process_user_event(struct perf_session *session, union perf_event *event,
1019					    struct perf_tool *tool, u64 file_offset)
1020{
1021	int err;
1022
1023	dump_event(session, event, file_offset, NULL);
1024
1025	/* These events are processed right away */
1026	switch (event->header.type) {
1027	case PERF_RECORD_HEADER_ATTR:
1028		err = tool->attr(event, &session->evlist);
1029		if (err == 0)
1030			perf_session__update_sample_type(session);
1031		return err;
1032	case PERF_RECORD_HEADER_EVENT_TYPE:
1033		return tool->event_type(tool, event);
1034	case PERF_RECORD_HEADER_TRACING_DATA:
1035		/* setup for reading amidst mmap */
1036		lseek(session->fd, file_offset, SEEK_SET);
1037		return tool->tracing_data(event, session);
1038	case PERF_RECORD_HEADER_BUILD_ID:
1039		return tool->build_id(tool, event, session);
1040	case PERF_RECORD_FINISHED_ROUND:
1041		return tool->finished_round(tool, event, session);
1042	default:
1043		return -EINVAL;
1044	}
1045}
1046
1047static void event_swap(union perf_event *event, bool sample_id_all)
1048{
1049	perf_event__swap_op swap;
1050
1051	swap = perf_event__swap_ops[event->header.type];
1052	if (swap)
1053		swap(event, sample_id_all);
1054}
1055
1056static int perf_session__process_event(struct perf_session *session,
1057				       union perf_event *event,
1058				       struct perf_tool *tool,
1059				       u64 file_offset)
1060{
1061	struct perf_sample sample;
1062	int ret;
1063
1064	if (session->header.needs_swap)
1065		event_swap(event, session->sample_id_all);
1066
1067	if (event->header.type >= PERF_RECORD_HEADER_MAX)
1068		return -EINVAL;
1069
1070	hists__inc_nr_events(&session->hists, event->header.type);
1071
1072	if (event->header.type >= PERF_RECORD_USER_TYPE_START)
1073		return perf_session__process_user_event(session, event, tool, file_offset);
1074
1075	/*
1076	 * For all kernel events we get the sample data
1077	 */
1078	ret = perf_session__parse_sample(session, event, &sample);
1079	if (ret)
1080		return ret;
1081
1082	/* Preprocess sample records - precheck callchains */
1083	if (perf_session__preprocess_sample(session, event, &sample))
1084		return 0;
1085
1086	if (tool->ordered_samples) {
1087		ret = perf_session_queue_event(session, event, &sample,
1088					       file_offset);
1089		if (ret != -ETIME)
1090			return ret;
1091	}
1092
1093	return perf_session_deliver_event(session, event, &sample, tool,
1094					  file_offset);
1095}
1096
1097void perf_event_header__bswap(struct perf_event_header *self)
1098{
1099	self->type = bswap_32(self->type);
1100	self->misc = bswap_16(self->misc);
1101	self->size = bswap_16(self->size);
1102}
1103
1104struct thread *perf_session__findnew(struct perf_session *session, pid_t pid)
1105{
1106	return machine__findnew_thread(&session->host_machine, pid);
1107}
1108
1109static struct thread *perf_session__register_idle_thread(struct perf_session *self)
1110{
1111	struct thread *thread = perf_session__findnew(self, 0);
1112
1113	if (thread == NULL || thread__set_comm(thread, "swapper")) {
1114		pr_err("problem inserting idle task.\n");
1115		thread = NULL;
1116	}
1117
1118	return thread;
1119}
1120
1121static void perf_session__warn_about_errors(const struct perf_session *session,
1122					    const struct perf_tool *tool)
1123{
1124	if (tool->lost == perf_event__process_lost &&
1125	    session->hists.stats.nr_events[PERF_RECORD_LOST] != 0) {
1126		ui__warning("Processed %d events and lost %d chunks!\n\n"
1127			    "Check IO/CPU overload!\n\n",
1128			    session->hists.stats.nr_events[0],
1129			    session->hists.stats.nr_events[PERF_RECORD_LOST]);
1130	}
1131
1132	if (session->hists.stats.nr_unknown_events != 0) {
1133		ui__warning("Found %u unknown events!\n\n"
1134			    "Is this an older tool processing a perf.data "
1135			    "file generated by a more recent tool?\n\n"
1136			    "If that is not the case, consider "
1137			    "reporting to linux-kernel@vger.kernel.org.\n\n",
1138			    session->hists.stats.nr_unknown_events);
1139	}
1140
1141	if (session->hists.stats.nr_unknown_id != 0) {
1142		ui__warning("%u samples with id not present in the header\n",
1143			    session->hists.stats.nr_unknown_id);
1144	}
1145
1146 	if (session->hists.stats.nr_invalid_chains != 0) {
1147 		ui__warning("Found invalid callchains!\n\n"
1148 			    "%u out of %u events were discarded for this reason.\n\n"
1149 			    "Consider reporting to linux-kernel@vger.kernel.org.\n\n",
1150 			    session->hists.stats.nr_invalid_chains,
1151 			    session->hists.stats.nr_events[PERF_RECORD_SAMPLE]);
1152 	}
1153
1154	if (session->hists.stats.nr_unprocessable_samples != 0) {
1155		ui__warning("%u unprocessable samples recorded.\n"
1156			    "Do you have a KVM guest running and not using 'perf kvm'?\n",
1157			    session->hists.stats.nr_unprocessable_samples);
1158	}
1159}
1160
1161#define session_done()	(*(volatile int *)(&session_done))
1162volatile int session_done;
1163
1164static int __perf_session__process_pipe_events(struct perf_session *self,
1165					       struct perf_tool *tool)
1166{
1167	union perf_event *event;
1168	uint32_t size, cur_size = 0;
1169	void *buf = NULL;
1170	int skip = 0;
1171	u64 head;
1172	int err;
1173	void *p;
1174
1175	perf_tool__fill_defaults(tool);
1176
1177	head = 0;
1178	cur_size = sizeof(union perf_event);
1179
1180	buf = malloc(cur_size);
1181	if (!buf)
1182		return -errno;
1183more:
1184	event = buf;
1185	err = readn(self->fd, event, sizeof(struct perf_event_header));
1186	if (err <= 0) {
1187		if (err == 0)
1188			goto done;
1189
1190		pr_err("failed to read event header\n");
1191		goto out_err;
1192	}
1193
1194	if (self->header.needs_swap)
1195		perf_event_header__bswap(&event->header);
1196
1197	size = event->header.size;
1198	if (size == 0)
1199		size = 8;
1200
1201	if (size > cur_size) {
1202		void *new = realloc(buf, size);
1203		if (!new) {
1204			pr_err("failed to allocate memory to read event\n");
1205			goto out_err;
1206		}
1207		buf = new;
1208		cur_size = size;
1209		event = buf;
1210	}
1211	p = event;
1212	p += sizeof(struct perf_event_header);
1213
1214	if (size - sizeof(struct perf_event_header)) {
1215		err = readn(self->fd, p, size - sizeof(struct perf_event_header));
1216		if (err <= 0) {
1217			if (err == 0) {
1218				pr_err("unexpected end of event stream\n");
1219				goto done;
1220			}
1221
1222			pr_err("failed to read event data\n");
1223			goto out_err;
1224		}
1225	}
1226
1227	if ((skip = perf_session__process_event(self, event, tool, head)) < 0) {
1228		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
1229		       head, event->header.size, event->header.type);
1230		err = -EINVAL;
1231		goto out_err;
1232	}
1233
1234	head += size;
1235
1236	if (skip > 0)
1237		head += skip;
1238
1239	if (!session_done())
1240		goto more;
1241done:
1242	err = 0;
1243out_err:
1244	free(buf);
1245	perf_session__warn_about_errors(self, tool);
1246	perf_session_free_sample_buffers(self);
1247	return err;
1248}
1249
1250static union perf_event *
1251fetch_mmaped_event(struct perf_session *session,
1252		   u64 head, size_t mmap_size, char *buf)
1253{
1254	union perf_event *event;
1255
1256	/*
1257	 * Ensure we have enough space remaining to read
1258	 * the size of the event in the headers.
1259	 */
1260	if (head + sizeof(event->header) > mmap_size)
1261		return NULL;
1262
1263	event = (union perf_event *)(buf + head);
1264
1265	if (session->header.needs_swap)
1266		perf_event_header__bswap(&event->header);
1267
1268	if (head + event->header.size > mmap_size)
1269		return NULL;
1270
1271	return event;
1272}
1273
1274int __perf_session__process_events(struct perf_session *session,
1275				   u64 data_offset, u64 data_size,
1276				   u64 file_size, struct perf_tool *tool)
1277{
1278	u64 head, page_offset, file_offset, file_pos, progress_next;
1279	int err, mmap_prot, mmap_flags, map_idx = 0;
1280	size_t	page_size, mmap_size;
1281	char *buf, *mmaps[8];
1282	union perf_event *event;
1283	uint32_t size;
1284
1285	perf_tool__fill_defaults(tool);
1286
1287	page_size = sysconf(_SC_PAGESIZE);
1288
1289	page_offset = page_size * (data_offset / page_size);
1290	file_offset = page_offset;
1291	head = data_offset - page_offset;
1292
1293	if (data_offset + data_size < file_size)
1294		file_size = data_offset + data_size;
1295
1296	progress_next = file_size / 16;
1297
1298	mmap_size = session->mmap_window;
1299	if (mmap_size > file_size)
1300		mmap_size = file_size;
1301
1302	memset(mmaps, 0, sizeof(mmaps));
1303
1304	mmap_prot  = PROT_READ;
1305	mmap_flags = MAP_SHARED;
1306
1307	if (session->header.needs_swap) {
1308		mmap_prot  |= PROT_WRITE;
1309		mmap_flags = MAP_PRIVATE;
1310	}
1311remap:
1312	buf = mmap(NULL, mmap_size, mmap_prot, mmap_flags, session->fd,
1313		   file_offset);
1314	if (buf == MAP_FAILED) {
1315		pr_err("failed to mmap file\n");
1316		err = -errno;
1317		goto out_err;
1318	}
1319	mmaps[map_idx] = buf;
1320	map_idx = (map_idx + 1) & (ARRAY_SIZE(mmaps) - 1);
1321	file_pos = file_offset + head;
1322
1323more:
1324	event = fetch_mmaped_event(session, head, mmap_size, buf);
1325	if (!event) {
1326		if (mmaps[map_idx]) {
1327			munmap(mmaps[map_idx], mmap_size);
1328			mmaps[map_idx] = NULL;
1329		}
1330
1331		page_offset = page_size * (head / page_size);
1332		file_offset += page_offset;
1333		head -= page_offset;
1334		goto remap;
1335	}
1336
1337	size = event->header.size;
1338
1339	if (size == 0 ||
1340	    perf_session__process_event(session, event, tool, file_pos) < 0) {
1341		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
1342		       file_offset + head, event->header.size,
1343		       event->header.type);
1344		err = -EINVAL;
1345		goto out_err;
1346	}
1347
1348	head += size;
1349	file_pos += size;
1350
1351	if (file_pos >= progress_next) {
1352		progress_next += file_size / 16;
1353		ui_progress__update(file_pos, file_size,
1354				    "Processing events...");
1355	}
1356
1357	if (file_pos < file_size)
1358		goto more;
1359
1360	err = 0;
1361	/* do the final flush for ordered samples */
1362	session->ordered_samples.next_flush = ULLONG_MAX;
1363	flush_sample_queue(session, tool);
1364out_err:
1365	perf_session__warn_about_errors(session, tool);
1366	perf_session_free_sample_buffers(session);
1367	return err;
1368}
1369
1370int perf_session__process_events(struct perf_session *self,
1371				 struct perf_tool *tool)
1372{
1373	int err;
1374
1375	if (perf_session__register_idle_thread(self) == NULL)
1376		return -ENOMEM;
1377
1378	if (!self->fd_pipe)
1379		err = __perf_session__process_events(self,
1380						     self->header.data_offset,
1381						     self->header.data_size,
1382						     self->size, tool);
1383	else
1384		err = __perf_session__process_pipe_events(self, tool);
1385
1386	return err;
1387}
1388
1389bool perf_session__has_traces(struct perf_session *self, const char *msg)
1390{
1391	if (!(self->sample_type & PERF_SAMPLE_RAW)) {
1392		pr_err("No trace sample to read. Did you call 'perf %s'?\n", msg);
1393		return false;
1394	}
1395
1396	return true;
1397}
1398
1399int maps__set_kallsyms_ref_reloc_sym(struct map **maps,
1400				     const char *symbol_name, u64 addr)
1401{
1402	char *bracket;
1403	enum map_type i;
1404	struct ref_reloc_sym *ref;
1405
1406	ref = zalloc(sizeof(struct ref_reloc_sym));
1407	if (ref == NULL)
1408		return -ENOMEM;
1409
1410	ref->name = strdup(symbol_name);
1411	if (ref->name == NULL) {
1412		free(ref);
1413		return -ENOMEM;
1414	}
1415
1416	bracket = strchr(ref->name, ']');
1417	if (bracket)
1418		*bracket = '\0';
1419
1420	ref->addr = addr;
1421
1422	for (i = 0; i < MAP__NR_TYPES; ++i) {
1423		struct kmap *kmap = map__kmap(maps[i]);
1424		kmap->ref_reloc_sym = ref;
1425	}
1426
1427	return 0;
1428}
1429
1430size_t perf_session__fprintf_dsos(struct perf_session *self, FILE *fp)
1431{
1432	return __dsos__fprintf(&self->host_machine.kernel_dsos, fp) +
1433	       __dsos__fprintf(&self->host_machine.user_dsos, fp) +
1434	       machines__fprintf_dsos(&self->machines, fp);
1435}
1436
1437size_t perf_session__fprintf_dsos_buildid(struct perf_session *self, FILE *fp,
1438					  bool with_hits)
1439{
1440	size_t ret = machine__fprintf_dsos_buildid(&self->host_machine, fp, with_hits);
1441	return ret + machines__fprintf_dsos_buildid(&self->machines, fp, with_hits);
1442}
1443
1444size_t perf_session__fprintf_nr_events(struct perf_session *session, FILE *fp)
1445{
1446	struct perf_evsel *pos;
1447	size_t ret = fprintf(fp, "Aggregated stats:\n");
1448
1449	ret += hists__fprintf_nr_events(&session->hists, fp);
1450
1451	list_for_each_entry(pos, &session->evlist->entries, node) {
1452		ret += fprintf(fp, "%s stats:\n", event_name(pos));
1453		ret += hists__fprintf_nr_events(&pos->hists, fp);
1454	}
1455
1456	return ret;
1457}
1458
1459size_t perf_session__fprintf(struct perf_session *session, FILE *fp)
1460{
1461	/*
1462	 * FIXME: Here we have to actually print all the machines in this
1463	 * session, not just the host...
1464	 */
1465	return machine__fprintf(&session->host_machine, fp);
1466}
1467
1468void perf_session__remove_thread(struct perf_session *session,
1469				 struct thread *th)
1470{
1471	/*
1472	 * FIXME: This one makes no sense, we need to remove the thread from
1473	 * the machine it belongs to, perf_session can have many machines, so
1474	 * doing it always on ->host_machine is wrong.  Fix when auditing all
1475	 * the 'perf kvm' code.
1476	 */
1477	machine__remove_thread(&session->host_machine, th);
1478}
1479
1480struct perf_evsel *perf_session__find_first_evtype(struct perf_session *session,
1481					      unsigned int type)
1482{
1483	struct perf_evsel *pos;
1484
1485	list_for_each_entry(pos, &session->evlist->entries, node) {
1486		if (pos->attr.type == type)
1487			return pos;
1488	}
1489	return NULL;
1490}
1491
1492void perf_event__print_ip(union perf_event *event, struct perf_sample *sample,
1493			  struct machine *machine, struct perf_evsel *evsel,
1494			  int print_sym, int print_dso, int print_symoffset)
1495{
1496	struct addr_location al;
1497	struct callchain_cursor_node *node;
1498
1499	if (perf_event__preprocess_sample(event, machine, &al, sample,
1500					  NULL) < 0) {
1501		error("problem processing %d event, skipping it.\n",
1502			event->header.type);
1503		return;
1504	}
1505
1506	if (symbol_conf.use_callchain && sample->callchain) {
1507
1508		if (machine__resolve_callchain(machine, evsel, al.thread,
1509						sample->callchain, NULL) != 0) {
1510			if (verbose)
1511				error("Failed to resolve callchain. Skipping\n");
1512			return;
1513		}
1514		callchain_cursor_commit(&callchain_cursor);
1515
1516		while (1) {
1517			node = callchain_cursor_current(&callchain_cursor);
1518			if (!node)
1519				break;
1520
1521			printf("\t%16" PRIx64, node->ip);
1522			if (print_sym) {
1523				printf(" ");
1524				symbol__fprintf_symname(node->sym, stdout);
1525			}
1526			if (print_dso) {
1527				printf(" (");
1528				map__fprintf_dsoname(node->map, stdout);
1529				printf(")");
1530			}
1531			printf("\n");
1532
1533			callchain_cursor_advance(&callchain_cursor);
1534		}
1535
1536	} else {
1537		printf("%16" PRIx64, sample->ip);
1538		if (print_sym) {
1539			printf(" ");
1540			if (print_symoffset)
1541				symbol__fprintf_symname_offs(al.sym, &al,
1542							     stdout);
1543			else
1544				symbol__fprintf_symname(al.sym, stdout);
1545		}
1546
1547		if (print_dso) {
1548			printf(" (");
1549			map__fprintf_dsoname(al.map, stdout);
1550			printf(")");
1551		}
1552	}
1553}
1554
1555int perf_session__cpu_bitmap(struct perf_session *session,
1556			     const char *cpu_list, unsigned long *cpu_bitmap)
1557{
1558	int i;
1559	struct cpu_map *map;
1560
1561	for (i = 0; i < PERF_TYPE_MAX; ++i) {
1562		struct perf_evsel *evsel;
1563
1564		evsel = perf_session__find_first_evtype(session, i);
1565		if (!evsel)
1566			continue;
1567
1568		if (!(evsel->attr.sample_type & PERF_SAMPLE_CPU)) {
1569			pr_err("File does not contain CPU events. "
1570			       "Remove -c option to proceed.\n");
1571			return -1;
1572		}
1573	}
1574
1575	map = cpu_map__new(cpu_list);
1576	if (map == NULL) {
1577		pr_err("Invalid cpu_list\n");
1578		return -1;
1579	}
1580
1581	for (i = 0; i < map->nr; i++) {
1582		int cpu = map->map[i];
1583
1584		if (cpu >= MAX_NR_CPUS) {
1585			pr_err("Requested CPU %d too large. "
1586			       "Consider raising MAX_NR_CPUS\n", cpu);
1587			return -1;
1588		}
1589
1590		set_bit(cpu, cpu_bitmap);
1591	}
1592
1593	return 0;
1594}
1595
1596void perf_session__fprintf_info(struct perf_session *session, FILE *fp,
1597				bool full)
1598{
1599	struct stat st;
1600	int ret;
1601
1602	if (session == NULL || fp == NULL)
1603		return;
1604
1605	ret = fstat(session->fd, &st);
1606	if (ret == -1)
1607		return;
1608
1609	fprintf(fp, "# ========\n");
1610	fprintf(fp, "# captured on: %s", ctime(&st.st_ctime));
1611	perf_header__fprintf_info(session, fp, full);
1612	fprintf(fp, "# ========\n#\n");
1613}