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