xref: /openbmc/linux/tools/perf/util/session.c (revision 7c0f4a41)
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 #include "event-parse.h"
18 
19 static int perf_session__open(struct perf_session *self, bool force)
20 {
21 	struct stat input_stat;
22 
23 	if (!strcmp(self->filename, "-")) {
24 		self->fd_pipe = true;
25 		self->fd = STDIN_FILENO;
26 
27 		if (perf_session__read_header(self, self->fd) < 0)
28 			pr_err("incompatible file format (rerun with -v to learn more)");
29 
30 		return 0;
31 	}
32 
33 	self->fd = open(self->filename, O_RDONLY);
34 	if (self->fd < 0) {
35 		int err = errno;
36 
37 		pr_err("failed to open %s: %s", self->filename, strerror(err));
38 		if (err == ENOENT && !strcmp(self->filename, "perf.data"))
39 			pr_err("  (try 'perf record' first)");
40 		pr_err("\n");
41 		return -errno;
42 	}
43 
44 	if (fstat(self->fd, &input_stat) < 0)
45 		goto out_close;
46 
47 	if (!force && input_stat.st_uid && (input_stat.st_uid != geteuid())) {
48 		pr_err("file %s not owned by current user or root\n",
49 		       self->filename);
50 		goto out_close;
51 	}
52 
53 	if (!input_stat.st_size) {
54 		pr_info("zero-sized file (%s), nothing to do!\n",
55 			self->filename);
56 		goto out_close;
57 	}
58 
59 	if (perf_session__read_header(self, self->fd) < 0) {
60 		pr_err("incompatible file format (rerun with -v to learn more)");
61 		goto out_close;
62 	}
63 
64 	if (!perf_evlist__valid_sample_type(self->evlist)) {
65 		pr_err("non matching sample_type");
66 		goto out_close;
67 	}
68 
69 	if (!perf_evlist__valid_sample_id_all(self->evlist)) {
70 		pr_err("non matching sample_id_all");
71 		goto out_close;
72 	}
73 
74 	self->size = input_stat.st_size;
75 	return 0;
76 
77 out_close:
78 	close(self->fd);
79 	self->fd = -1;
80 	return -1;
81 }
82 
83 void perf_session__update_sample_type(struct perf_session *self)
84 {
85 	self->sample_type = perf_evlist__sample_type(self->evlist);
86 	self->sample_size = __perf_evsel__sample_size(self->sample_type);
87 	self->sample_id_all = perf_evlist__sample_id_all(self->evlist);
88 	self->id_hdr_size = perf_evlist__id_hdr_size(self->evlist);
89 	self->host_machine.id_hdr_size = self->id_hdr_size;
90 }
91 
92 int perf_session__create_kernel_maps(struct perf_session *self)
93 {
94 	int ret = machine__create_kernel_maps(&self->host_machine);
95 
96 	if (ret >= 0)
97 		ret = machines__create_guest_kernel_maps(&self->machines);
98 	return ret;
99 }
100 
101 static void perf_session__destroy_kernel_maps(struct perf_session *self)
102 {
103 	machine__destroy_kernel_maps(&self->host_machine);
104 	machines__destroy_guest_kernel_maps(&self->machines);
105 }
106 
107 struct perf_session *perf_session__new(const char *filename, int mode,
108 				       bool force, bool repipe,
109 				       struct perf_tool *tool)
110 {
111 	struct perf_session *self;
112 	struct stat st;
113 	size_t len;
114 
115 	if (!filename || !strlen(filename)) {
116 		if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
117 			filename = "-";
118 		else
119 			filename = "perf.data";
120 	}
121 
122 	len = strlen(filename);
123 	self = zalloc(sizeof(*self) + len);
124 
125 	if (self == NULL)
126 		goto out;
127 
128 	memcpy(self->filename, filename, len);
129 	/*
130 	 * On 64bit we can mmap the data file in one go. No need for tiny mmap
131 	 * slices. On 32bit we use 32MB.
132 	 */
133 #if BITS_PER_LONG == 64
134 	self->mmap_window = ULLONG_MAX;
135 #else
136 	self->mmap_window = 32 * 1024 * 1024ULL;
137 #endif
138 	self->machines = RB_ROOT;
139 	self->repipe = repipe;
140 	INIT_LIST_HEAD(&self->ordered_samples.samples);
141 	INIT_LIST_HEAD(&self->ordered_samples.sample_cache);
142 	INIT_LIST_HEAD(&self->ordered_samples.to_free);
143 	machine__init(&self->host_machine, "", HOST_KERNEL_ID);
144 	hists__init(&self->hists);
145 
146 	if (mode == O_RDONLY) {
147 		if (perf_session__open(self, force) < 0)
148 			goto out_delete;
149 		perf_session__update_sample_type(self);
150 	} else if (mode == O_WRONLY) {
151 		/*
152 		 * In O_RDONLY mode this will be performed when reading the
153 		 * kernel MMAP event, in perf_event__process_mmap().
154 		 */
155 		if (perf_session__create_kernel_maps(self) < 0)
156 			goto out_delete;
157 	}
158 
159 	if (tool && tool->ordering_requires_timestamps &&
160 	    tool->ordered_samples && !self->sample_id_all) {
161 		dump_printf("WARNING: No sample_id_all support, falling back to unordered processing\n");
162 		tool->ordered_samples = false;
163 	}
164 
165 out:
166 	return self;
167 out_delete:
168 	perf_session__delete(self);
169 	return NULL;
170 }
171 
172 static void machine__delete_dead_threads(struct machine *machine)
173 {
174 	struct thread *n, *t;
175 
176 	list_for_each_entry_safe(t, n, &machine->dead_threads, node) {
177 		list_del(&t->node);
178 		thread__delete(t);
179 	}
180 }
181 
182 static void perf_session__delete_dead_threads(struct perf_session *session)
183 {
184 	machine__delete_dead_threads(&session->host_machine);
185 }
186 
187 static void machine__delete_threads(struct machine *self)
188 {
189 	struct rb_node *nd = rb_first(&self->threads);
190 
191 	while (nd) {
192 		struct thread *t = rb_entry(nd, struct thread, rb_node);
193 
194 		rb_erase(&t->rb_node, &self->threads);
195 		nd = rb_next(nd);
196 		thread__delete(t);
197 	}
198 }
199 
200 static void perf_session__delete_threads(struct perf_session *session)
201 {
202 	machine__delete_threads(&session->host_machine);
203 }
204 
205 void perf_session__delete(struct perf_session *self)
206 {
207 	perf_session__destroy_kernel_maps(self);
208 	perf_session__delete_dead_threads(self);
209 	perf_session__delete_threads(self);
210 	machine__exit(&self->host_machine);
211 	close(self->fd);
212 	free(self);
213 }
214 
215 void machine__remove_thread(struct machine *self, struct thread *th)
216 {
217 	self->last_match = NULL;
218 	rb_erase(&th->rb_node, &self->threads);
219 	/*
220 	 * We may have references to this thread, for instance in some hist_entry
221 	 * instances, so just move them to a separate list.
222 	 */
223 	list_add_tail(&th->node, &self->dead_threads);
224 }
225 
226 static bool symbol__match_parent_regex(struct symbol *sym)
227 {
228 	if (sym->name && !regexec(&parent_regex, sym->name, 0, NULL, 0))
229 		return 1;
230 
231 	return 0;
232 }
233 
234 static const u8 cpumodes[] = {
235 	PERF_RECORD_MISC_USER,
236 	PERF_RECORD_MISC_KERNEL,
237 	PERF_RECORD_MISC_GUEST_USER,
238 	PERF_RECORD_MISC_GUEST_KERNEL
239 };
240 #define NCPUMODES (sizeof(cpumodes)/sizeof(u8))
241 
242 static void ip__resolve_ams(struct machine *self, struct thread *thread,
243 			    struct addr_map_symbol *ams,
244 			    u64 ip)
245 {
246 	struct addr_location al;
247 	size_t i;
248 	u8 m;
249 
250 	memset(&al, 0, sizeof(al));
251 
252 	for (i = 0; i < NCPUMODES; i++) {
253 		m = cpumodes[i];
254 		/*
255 		 * We cannot use the header.misc hint to determine whether a
256 		 * branch stack address is user, kernel, guest, hypervisor.
257 		 * Branches may straddle the kernel/user/hypervisor boundaries.
258 		 * Thus, we have to try consecutively until we find a match
259 		 * or else, the symbol is unknown
260 		 */
261 		thread__find_addr_location(thread, self, m, MAP__FUNCTION,
262 				ip, &al, NULL);
263 		if (al.sym)
264 			goto found;
265 	}
266 found:
267 	ams->addr = ip;
268 	ams->al_addr = al.addr;
269 	ams->sym = al.sym;
270 	ams->map = al.map;
271 }
272 
273 struct branch_info *machine__resolve_bstack(struct machine *self,
274 					    struct thread *thr,
275 					    struct branch_stack *bs)
276 {
277 	struct branch_info *bi;
278 	unsigned int i;
279 
280 	bi = calloc(bs->nr, sizeof(struct branch_info));
281 	if (!bi)
282 		return NULL;
283 
284 	for (i = 0; i < bs->nr; i++) {
285 		ip__resolve_ams(self, thr, &bi[i].to, bs->entries[i].to);
286 		ip__resolve_ams(self, thr, &bi[i].from, bs->entries[i].from);
287 		bi[i].flags = bs->entries[i].flags;
288 	}
289 	return bi;
290 }
291 
292 int machine__resolve_callchain(struct machine *self,
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 
358 static 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 
365 static 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 
372 static 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 
382 static 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 
391 static 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 
399 static 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 
406 static int process_finished_round(struct perf_tool *tool,
407 				  union perf_event *event,
408 				  struct perf_session *session);
409 
410 static 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 
446 void 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 
456 void 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 
467 static 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 
476 static 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 
483 static 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 
496 static 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 
513 static 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 
525 static 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 
538 static 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  */
560 static 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 */
571 void 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 
587 static 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 
599 static 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 
606 static 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 
612 typedef void (*perf_event__swap_op)(union perf_event *event,
613 				    bool sample_id_all);
614 
615 static 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 
630 struct sample_queue {
631 	u64			timestamp;
632 	u64			file_offset;
633 	union perf_event	*event;
634 	struct list_head	list;
635 };
636 
637 static 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 
650 static 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 
656 static 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  */
741 static 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 */
752 static 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 
799 static 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 
840 static 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 
851 static 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 
863 static 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 
880 static 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 
898 static 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 
915 static 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 (perf_guest &&
922 	    ((cpumode == PERF_RECORD_MISC_GUEST_KERNEL) ||
923 	     (cpumode == PERF_RECORD_MISC_GUEST_USER))) {
924 		u32 pid;
925 
926 		if (event->header.type == PERF_RECORD_MMAP)
927 			pid = event->mmap.pid;
928 		else
929 			pid = event->ip.pid;
930 
931 		return perf_session__findnew_machine(session, pid);
932 	}
933 
934 	return perf_session__find_host_machine(session);
935 }
936 
937 static int perf_session_deliver_event(struct perf_session *session,
938 				      union perf_event *event,
939 				      struct perf_sample *sample,
940 				      struct perf_tool *tool,
941 				      u64 file_offset)
942 {
943 	struct perf_evsel *evsel;
944 	struct machine *machine;
945 
946 	dump_event(session, event, file_offset, sample);
947 
948 	evsel = perf_evlist__id2evsel(session->evlist, sample->id);
949 	if (evsel != NULL && event->header.type != PERF_RECORD_SAMPLE) {
950 		/*
951 		 * XXX We're leaving PERF_RECORD_SAMPLE unnacounted here
952 		 * because the tools right now may apply filters, discarding
953 		 * some of the samples. For consistency, in the future we
954 		 * should have something like nr_filtered_samples and remove
955 		 * the sample->period from total_sample_period, etc, KISS for
956 		 * now tho.
957 		 *
958 		 * Also testing against NULL allows us to handle files without
959 		 * attr.sample_id_all and/or without PERF_SAMPLE_ID. In the
960 		 * future probably it'll be a good idea to restrict event
961 		 * processing via perf_session to files with both set.
962 		 */
963 		hists__inc_nr_events(&evsel->hists, event->header.type);
964 	}
965 
966 	machine = perf_session__find_machine_for_cpumode(session, event);
967 
968 	switch (event->header.type) {
969 	case PERF_RECORD_SAMPLE:
970 		dump_sample(session, event, sample);
971 		if (evsel == NULL) {
972 			++session->hists.stats.nr_unknown_id;
973 			return 0;
974 		}
975 		if (machine == NULL) {
976 			++session->hists.stats.nr_unprocessable_samples;
977 			return 0;
978 		}
979 		return tool->sample(tool, event, sample, evsel, machine);
980 	case PERF_RECORD_MMAP:
981 		return tool->mmap(tool, event, sample, machine);
982 	case PERF_RECORD_COMM:
983 		return tool->comm(tool, event, sample, machine);
984 	case PERF_RECORD_FORK:
985 		return tool->fork(tool, event, sample, machine);
986 	case PERF_RECORD_EXIT:
987 		return tool->exit(tool, event, sample, machine);
988 	case PERF_RECORD_LOST:
989 		if (tool->lost == perf_event__process_lost)
990 			session->hists.stats.total_lost += event->lost.lost;
991 		return tool->lost(tool, event, sample, machine);
992 	case PERF_RECORD_READ:
993 		return tool->read(tool, event, sample, evsel, machine);
994 	case PERF_RECORD_THROTTLE:
995 		return tool->throttle(tool, event, sample, machine);
996 	case PERF_RECORD_UNTHROTTLE:
997 		return tool->unthrottle(tool, event, sample, machine);
998 	default:
999 		++session->hists.stats.nr_unknown_events;
1000 		return -1;
1001 	}
1002 }
1003 
1004 static int perf_session__preprocess_sample(struct perf_session *session,
1005 					   union perf_event *event, struct perf_sample *sample)
1006 {
1007 	if (event->header.type != PERF_RECORD_SAMPLE ||
1008 	    !(session->sample_type & PERF_SAMPLE_CALLCHAIN))
1009 		return 0;
1010 
1011 	if (!ip_callchain__valid(sample->callchain, event)) {
1012 		pr_debug("call-chain problem with event, skipping it.\n");
1013 		++session->hists.stats.nr_invalid_chains;
1014 		session->hists.stats.total_invalid_chains += sample->period;
1015 		return -EINVAL;
1016 	}
1017 	return 0;
1018 }
1019 
1020 static int perf_session__process_user_event(struct perf_session *session, union perf_event *event,
1021 					    struct perf_tool *tool, u64 file_offset)
1022 {
1023 	int err;
1024 
1025 	dump_event(session, event, file_offset, NULL);
1026 
1027 	/* These events are processed right away */
1028 	switch (event->header.type) {
1029 	case PERF_RECORD_HEADER_ATTR:
1030 		err = tool->attr(event, &session->evlist);
1031 		if (err == 0)
1032 			perf_session__update_sample_type(session);
1033 		return err;
1034 	case PERF_RECORD_HEADER_EVENT_TYPE:
1035 		return tool->event_type(tool, event);
1036 	case PERF_RECORD_HEADER_TRACING_DATA:
1037 		/* setup for reading amidst mmap */
1038 		lseek(session->fd, file_offset, SEEK_SET);
1039 		return tool->tracing_data(event, session);
1040 	case PERF_RECORD_HEADER_BUILD_ID:
1041 		return tool->build_id(tool, event, session);
1042 	case PERF_RECORD_FINISHED_ROUND:
1043 		return tool->finished_round(tool, event, session);
1044 	default:
1045 		return -EINVAL;
1046 	}
1047 }
1048 
1049 static void event_swap(union perf_event *event, bool sample_id_all)
1050 {
1051 	perf_event__swap_op swap;
1052 
1053 	swap = perf_event__swap_ops[event->header.type];
1054 	if (swap)
1055 		swap(event, sample_id_all);
1056 }
1057 
1058 static int perf_session__process_event(struct perf_session *session,
1059 				       union perf_event *event,
1060 				       struct perf_tool *tool,
1061 				       u64 file_offset)
1062 {
1063 	struct perf_sample sample;
1064 	int ret;
1065 
1066 	if (session->header.needs_swap)
1067 		event_swap(event, session->sample_id_all);
1068 
1069 	if (event->header.type >= PERF_RECORD_HEADER_MAX)
1070 		return -EINVAL;
1071 
1072 	hists__inc_nr_events(&session->hists, event->header.type);
1073 
1074 	if (event->header.type >= PERF_RECORD_USER_TYPE_START)
1075 		return perf_session__process_user_event(session, event, tool, file_offset);
1076 
1077 	/*
1078 	 * For all kernel events we get the sample data
1079 	 */
1080 	ret = perf_session__parse_sample(session, event, &sample);
1081 	if (ret)
1082 		return ret;
1083 
1084 	/* Preprocess sample records - precheck callchains */
1085 	if (perf_session__preprocess_sample(session, event, &sample))
1086 		return 0;
1087 
1088 	if (tool->ordered_samples) {
1089 		ret = perf_session_queue_event(session, event, &sample,
1090 					       file_offset);
1091 		if (ret != -ETIME)
1092 			return ret;
1093 	}
1094 
1095 	return perf_session_deliver_event(session, event, &sample, tool,
1096 					  file_offset);
1097 }
1098 
1099 void perf_event_header__bswap(struct perf_event_header *self)
1100 {
1101 	self->type = bswap_32(self->type);
1102 	self->misc = bswap_16(self->misc);
1103 	self->size = bswap_16(self->size);
1104 }
1105 
1106 struct thread *perf_session__findnew(struct perf_session *session, pid_t pid)
1107 {
1108 	return machine__findnew_thread(&session->host_machine, pid);
1109 }
1110 
1111 static struct thread *perf_session__register_idle_thread(struct perf_session *self)
1112 {
1113 	struct thread *thread = perf_session__findnew(self, 0);
1114 
1115 	if (thread == NULL || thread__set_comm(thread, "swapper")) {
1116 		pr_err("problem inserting idle task.\n");
1117 		thread = NULL;
1118 	}
1119 
1120 	return thread;
1121 }
1122 
1123 static void perf_session__warn_about_errors(const struct perf_session *session,
1124 					    const struct perf_tool *tool)
1125 {
1126 	if (tool->lost == perf_event__process_lost &&
1127 	    session->hists.stats.nr_events[PERF_RECORD_LOST] != 0) {
1128 		ui__warning("Processed %d events and lost %d chunks!\n\n"
1129 			    "Check IO/CPU overload!\n\n",
1130 			    session->hists.stats.nr_events[0],
1131 			    session->hists.stats.nr_events[PERF_RECORD_LOST]);
1132 	}
1133 
1134 	if (session->hists.stats.nr_unknown_events != 0) {
1135 		ui__warning("Found %u unknown events!\n\n"
1136 			    "Is this an older tool processing a perf.data "
1137 			    "file generated by a more recent tool?\n\n"
1138 			    "If that is not the case, consider "
1139 			    "reporting to linux-kernel@vger.kernel.org.\n\n",
1140 			    session->hists.stats.nr_unknown_events);
1141 	}
1142 
1143 	if (session->hists.stats.nr_unknown_id != 0) {
1144 		ui__warning("%u samples with id not present in the header\n",
1145 			    session->hists.stats.nr_unknown_id);
1146 	}
1147 
1148  	if (session->hists.stats.nr_invalid_chains != 0) {
1149  		ui__warning("Found invalid callchains!\n\n"
1150  			    "%u out of %u events were discarded for this reason.\n\n"
1151  			    "Consider reporting to linux-kernel@vger.kernel.org.\n\n",
1152  			    session->hists.stats.nr_invalid_chains,
1153  			    session->hists.stats.nr_events[PERF_RECORD_SAMPLE]);
1154  	}
1155 
1156 	if (session->hists.stats.nr_unprocessable_samples != 0) {
1157 		ui__warning("%u unprocessable samples recorded.\n"
1158 			    "Do you have a KVM guest running and not using 'perf kvm'?\n",
1159 			    session->hists.stats.nr_unprocessable_samples);
1160 	}
1161 }
1162 
1163 #define session_done()	(*(volatile int *)(&session_done))
1164 volatile int session_done;
1165 
1166 static int __perf_session__process_pipe_events(struct perf_session *self,
1167 					       struct perf_tool *tool)
1168 {
1169 	union perf_event *event;
1170 	uint32_t size, cur_size = 0;
1171 	void *buf = NULL;
1172 	int skip = 0;
1173 	u64 head;
1174 	int err;
1175 	void *p;
1176 
1177 	perf_tool__fill_defaults(tool);
1178 
1179 	head = 0;
1180 	cur_size = sizeof(union perf_event);
1181 
1182 	buf = malloc(cur_size);
1183 	if (!buf)
1184 		return -errno;
1185 more:
1186 	event = buf;
1187 	err = readn(self->fd, event, sizeof(struct perf_event_header));
1188 	if (err <= 0) {
1189 		if (err == 0)
1190 			goto done;
1191 
1192 		pr_err("failed to read event header\n");
1193 		goto out_err;
1194 	}
1195 
1196 	if (self->header.needs_swap)
1197 		perf_event_header__bswap(&event->header);
1198 
1199 	size = event->header.size;
1200 	if (size == 0)
1201 		size = 8;
1202 
1203 	if (size > cur_size) {
1204 		void *new = realloc(buf, size);
1205 		if (!new) {
1206 			pr_err("failed to allocate memory to read event\n");
1207 			goto out_err;
1208 		}
1209 		buf = new;
1210 		cur_size = size;
1211 		event = buf;
1212 	}
1213 	p = event;
1214 	p += sizeof(struct perf_event_header);
1215 
1216 	if (size - sizeof(struct perf_event_header)) {
1217 		err = readn(self->fd, p, size - sizeof(struct perf_event_header));
1218 		if (err <= 0) {
1219 			if (err == 0) {
1220 				pr_err("unexpected end of event stream\n");
1221 				goto done;
1222 			}
1223 
1224 			pr_err("failed to read event data\n");
1225 			goto out_err;
1226 		}
1227 	}
1228 
1229 	if ((skip = perf_session__process_event(self, event, tool, head)) < 0) {
1230 		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
1231 		       head, event->header.size, event->header.type);
1232 		err = -EINVAL;
1233 		goto out_err;
1234 	}
1235 
1236 	head += size;
1237 
1238 	if (skip > 0)
1239 		head += skip;
1240 
1241 	if (!session_done())
1242 		goto more;
1243 done:
1244 	err = 0;
1245 out_err:
1246 	free(buf);
1247 	perf_session__warn_about_errors(self, tool);
1248 	perf_session_free_sample_buffers(self);
1249 	return err;
1250 }
1251 
1252 static union perf_event *
1253 fetch_mmaped_event(struct perf_session *session,
1254 		   u64 head, size_t mmap_size, char *buf)
1255 {
1256 	union perf_event *event;
1257 
1258 	/*
1259 	 * Ensure we have enough space remaining to read
1260 	 * the size of the event in the headers.
1261 	 */
1262 	if (head + sizeof(event->header) > mmap_size)
1263 		return NULL;
1264 
1265 	event = (union perf_event *)(buf + head);
1266 
1267 	if (session->header.needs_swap)
1268 		perf_event_header__bswap(&event->header);
1269 
1270 	if (head + event->header.size > mmap_size)
1271 		return NULL;
1272 
1273 	return event;
1274 }
1275 
1276 int __perf_session__process_events(struct perf_session *session,
1277 				   u64 data_offset, u64 data_size,
1278 				   u64 file_size, struct perf_tool *tool)
1279 {
1280 	u64 head, page_offset, file_offset, file_pos, progress_next;
1281 	int err, mmap_prot, mmap_flags, map_idx = 0;
1282 	size_t	page_size, mmap_size;
1283 	char *buf, *mmaps[8];
1284 	union perf_event *event;
1285 	uint32_t size;
1286 
1287 	perf_tool__fill_defaults(tool);
1288 
1289 	page_size = sysconf(_SC_PAGESIZE);
1290 
1291 	page_offset = page_size * (data_offset / page_size);
1292 	file_offset = page_offset;
1293 	head = data_offset - page_offset;
1294 
1295 	if (data_offset + data_size < file_size)
1296 		file_size = data_offset + data_size;
1297 
1298 	progress_next = file_size / 16;
1299 
1300 	mmap_size = session->mmap_window;
1301 	if (mmap_size > file_size)
1302 		mmap_size = file_size;
1303 
1304 	memset(mmaps, 0, sizeof(mmaps));
1305 
1306 	mmap_prot  = PROT_READ;
1307 	mmap_flags = MAP_SHARED;
1308 
1309 	if (session->header.needs_swap) {
1310 		mmap_prot  |= PROT_WRITE;
1311 		mmap_flags = MAP_PRIVATE;
1312 	}
1313 remap:
1314 	buf = mmap(NULL, mmap_size, mmap_prot, mmap_flags, session->fd,
1315 		   file_offset);
1316 	if (buf == MAP_FAILED) {
1317 		pr_err("failed to mmap file\n");
1318 		err = -errno;
1319 		goto out_err;
1320 	}
1321 	mmaps[map_idx] = buf;
1322 	map_idx = (map_idx + 1) & (ARRAY_SIZE(mmaps) - 1);
1323 	file_pos = file_offset + head;
1324 
1325 more:
1326 	event = fetch_mmaped_event(session, head, mmap_size, buf);
1327 	if (!event) {
1328 		if (mmaps[map_idx]) {
1329 			munmap(mmaps[map_idx], mmap_size);
1330 			mmaps[map_idx] = NULL;
1331 		}
1332 
1333 		page_offset = page_size * (head / page_size);
1334 		file_offset += page_offset;
1335 		head -= page_offset;
1336 		goto remap;
1337 	}
1338 
1339 	size = event->header.size;
1340 
1341 	if (size == 0 ||
1342 	    perf_session__process_event(session, event, tool, file_pos) < 0) {
1343 		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
1344 		       file_offset + head, event->header.size,
1345 		       event->header.type);
1346 		err = -EINVAL;
1347 		goto out_err;
1348 	}
1349 
1350 	head += size;
1351 	file_pos += size;
1352 
1353 	if (file_pos >= progress_next) {
1354 		progress_next += file_size / 16;
1355 		ui_progress__update(file_pos, file_size,
1356 				    "Processing events...");
1357 	}
1358 
1359 	if (file_pos < file_size)
1360 		goto more;
1361 
1362 	err = 0;
1363 	/* do the final flush for ordered samples */
1364 	session->ordered_samples.next_flush = ULLONG_MAX;
1365 	flush_sample_queue(session, tool);
1366 out_err:
1367 	perf_session__warn_about_errors(session, tool);
1368 	perf_session_free_sample_buffers(session);
1369 	return err;
1370 }
1371 
1372 int perf_session__process_events(struct perf_session *self,
1373 				 struct perf_tool *tool)
1374 {
1375 	int err;
1376 
1377 	if (perf_session__register_idle_thread(self) == NULL)
1378 		return -ENOMEM;
1379 
1380 	if (!self->fd_pipe)
1381 		err = __perf_session__process_events(self,
1382 						     self->header.data_offset,
1383 						     self->header.data_size,
1384 						     self->size, tool);
1385 	else
1386 		err = __perf_session__process_pipe_events(self, tool);
1387 
1388 	return err;
1389 }
1390 
1391 bool perf_session__has_traces(struct perf_session *self, const char *msg)
1392 {
1393 	if (!(self->sample_type & PERF_SAMPLE_RAW)) {
1394 		pr_err("No trace sample to read. Did you call 'perf %s'?\n", msg);
1395 		return false;
1396 	}
1397 
1398 	return true;
1399 }
1400 
1401 int maps__set_kallsyms_ref_reloc_sym(struct map **maps,
1402 				     const char *symbol_name, u64 addr)
1403 {
1404 	char *bracket;
1405 	enum map_type i;
1406 	struct ref_reloc_sym *ref;
1407 
1408 	ref = zalloc(sizeof(struct ref_reloc_sym));
1409 	if (ref == NULL)
1410 		return -ENOMEM;
1411 
1412 	ref->name = strdup(symbol_name);
1413 	if (ref->name == NULL) {
1414 		free(ref);
1415 		return -ENOMEM;
1416 	}
1417 
1418 	bracket = strchr(ref->name, ']');
1419 	if (bracket)
1420 		*bracket = '\0';
1421 
1422 	ref->addr = addr;
1423 
1424 	for (i = 0; i < MAP__NR_TYPES; ++i) {
1425 		struct kmap *kmap = map__kmap(maps[i]);
1426 		kmap->ref_reloc_sym = ref;
1427 	}
1428 
1429 	return 0;
1430 }
1431 
1432 size_t perf_session__fprintf_dsos(struct perf_session *self, FILE *fp)
1433 {
1434 	return __dsos__fprintf(&self->host_machine.kernel_dsos, fp) +
1435 	       __dsos__fprintf(&self->host_machine.user_dsos, fp) +
1436 	       machines__fprintf_dsos(&self->machines, fp);
1437 }
1438 
1439 size_t perf_session__fprintf_dsos_buildid(struct perf_session *self, FILE *fp,
1440 					  bool with_hits)
1441 {
1442 	size_t ret = machine__fprintf_dsos_buildid(&self->host_machine, fp, with_hits);
1443 	return ret + machines__fprintf_dsos_buildid(&self->machines, fp, with_hits);
1444 }
1445 
1446 size_t perf_session__fprintf_nr_events(struct perf_session *session, FILE *fp)
1447 {
1448 	struct perf_evsel *pos;
1449 	size_t ret = fprintf(fp, "Aggregated stats:\n");
1450 
1451 	ret += hists__fprintf_nr_events(&session->hists, fp);
1452 
1453 	list_for_each_entry(pos, &session->evlist->entries, node) {
1454 		ret += fprintf(fp, "%s stats:\n", perf_evsel__name(pos));
1455 		ret += hists__fprintf_nr_events(&pos->hists, fp);
1456 	}
1457 
1458 	return ret;
1459 }
1460 
1461 size_t perf_session__fprintf(struct perf_session *session, FILE *fp)
1462 {
1463 	/*
1464 	 * FIXME: Here we have to actually print all the machines in this
1465 	 * session, not just the host...
1466 	 */
1467 	return machine__fprintf(&session->host_machine, fp);
1468 }
1469 
1470 void perf_session__remove_thread(struct perf_session *session,
1471 				 struct thread *th)
1472 {
1473 	/*
1474 	 * FIXME: This one makes no sense, we need to remove the thread from
1475 	 * the machine it belongs to, perf_session can have many machines, so
1476 	 * doing it always on ->host_machine is wrong.  Fix when auditing all
1477 	 * the 'perf kvm' code.
1478 	 */
1479 	machine__remove_thread(&session->host_machine, th);
1480 }
1481 
1482 struct perf_evsel *perf_session__find_first_evtype(struct perf_session *session,
1483 					      unsigned int type)
1484 {
1485 	struct perf_evsel *pos;
1486 
1487 	list_for_each_entry(pos, &session->evlist->entries, node) {
1488 		if (pos->attr.type == type)
1489 			return pos;
1490 	}
1491 	return NULL;
1492 }
1493 
1494 void perf_event__print_ip(union perf_event *event, struct perf_sample *sample,
1495 			  struct machine *machine, int print_sym,
1496 			  int print_dso, int print_symoffset)
1497 {
1498 	struct addr_location al;
1499 	struct callchain_cursor_node *node;
1500 
1501 	if (perf_event__preprocess_sample(event, machine, &al, sample,
1502 					  NULL) < 0) {
1503 		error("problem processing %d event, skipping it.\n",
1504 			event->header.type);
1505 		return;
1506 	}
1507 
1508 	if (symbol_conf.use_callchain && sample->callchain) {
1509 
1510 		if (machine__resolve_callchain(machine, al.thread,
1511 						sample->callchain, NULL) != 0) {
1512 			if (verbose)
1513 				error("Failed to resolve callchain. Skipping\n");
1514 			return;
1515 		}
1516 		callchain_cursor_commit(&callchain_cursor);
1517 
1518 		while (1) {
1519 			node = callchain_cursor_current(&callchain_cursor);
1520 			if (!node)
1521 				break;
1522 
1523 			printf("\t%16" PRIx64, node->ip);
1524 			if (print_sym) {
1525 				printf(" ");
1526 				symbol__fprintf_symname(node->sym, stdout);
1527 			}
1528 			if (print_dso) {
1529 				printf(" (");
1530 				map__fprintf_dsoname(node->map, stdout);
1531 				printf(")");
1532 			}
1533 			printf("\n");
1534 
1535 			callchain_cursor_advance(&callchain_cursor);
1536 		}
1537 
1538 	} else {
1539 		printf("%16" PRIx64, sample->ip);
1540 		if (print_sym) {
1541 			printf(" ");
1542 			if (print_symoffset)
1543 				symbol__fprintf_symname_offs(al.sym, &al,
1544 							     stdout);
1545 			else
1546 				symbol__fprintf_symname(al.sym, stdout);
1547 		}
1548 
1549 		if (print_dso) {
1550 			printf(" (");
1551 			map__fprintf_dsoname(al.map, stdout);
1552 			printf(")");
1553 		}
1554 	}
1555 }
1556 
1557 int perf_session__cpu_bitmap(struct perf_session *session,
1558 			     const char *cpu_list, unsigned long *cpu_bitmap)
1559 {
1560 	int i;
1561 	struct cpu_map *map;
1562 
1563 	for (i = 0; i < PERF_TYPE_MAX; ++i) {
1564 		struct perf_evsel *evsel;
1565 
1566 		evsel = perf_session__find_first_evtype(session, i);
1567 		if (!evsel)
1568 			continue;
1569 
1570 		if (!(evsel->attr.sample_type & PERF_SAMPLE_CPU)) {
1571 			pr_err("File does not contain CPU events. "
1572 			       "Remove -c option to proceed.\n");
1573 			return -1;
1574 		}
1575 	}
1576 
1577 	map = cpu_map__new(cpu_list);
1578 	if (map == NULL) {
1579 		pr_err("Invalid cpu_list\n");
1580 		return -1;
1581 	}
1582 
1583 	for (i = 0; i < map->nr; i++) {
1584 		int cpu = map->map[i];
1585 
1586 		if (cpu >= MAX_NR_CPUS) {
1587 			pr_err("Requested CPU %d too large. "
1588 			       "Consider raising MAX_NR_CPUS\n", cpu);
1589 			return -1;
1590 		}
1591 
1592 		set_bit(cpu, cpu_bitmap);
1593 	}
1594 
1595 	return 0;
1596 }
1597 
1598 void perf_session__fprintf_info(struct perf_session *session, FILE *fp,
1599 				bool full)
1600 {
1601 	struct stat st;
1602 	int ret;
1603 
1604 	if (session == NULL || fp == NULL)
1605 		return;
1606 
1607 	ret = fstat(session->fd, &st);
1608 	if (ret == -1)
1609 		return;
1610 
1611 	fprintf(fp, "# ========\n");
1612 	fprintf(fp, "# captured on: %s", ctime(&st.st_ctime));
1613 	perf_header__fprintf_info(session, fp, full);
1614 	fprintf(fp, "# ========\n#\n");
1615 }
1616 
1617 
1618 int __perf_session__set_tracepoints_handlers(struct perf_session *session,
1619 					     const struct perf_evsel_str_handler *assocs,
1620 					     size_t nr_assocs)
1621 {
1622 	struct perf_evlist *evlist = session->evlist;
1623 	struct event_format *format;
1624 	struct perf_evsel *evsel;
1625 	char *tracepoint, *name;
1626 	size_t i;
1627 	int err;
1628 
1629 	for (i = 0; i < nr_assocs; i++) {
1630 		err = -ENOMEM;
1631 		tracepoint = strdup(assocs[i].name);
1632 		if (tracepoint == NULL)
1633 			goto out;
1634 
1635 		err = -ENOENT;
1636 		name = strchr(tracepoint, ':');
1637 		if (name == NULL)
1638 			goto out_free;
1639 
1640 		*name++ = '\0';
1641 		format = pevent_find_event_by_name(session->pevent,
1642 						   tracepoint, name);
1643 		if (format == NULL) {
1644 			/*
1645 			 * Adding a handler for an event not in the session,
1646 			 * just ignore it.
1647 			 */
1648 			goto next;
1649 		}
1650 
1651 		evsel = perf_evlist__find_tracepoint_by_id(evlist, format->id);
1652 		if (evsel == NULL)
1653 			goto next;
1654 
1655 		err = -EEXIST;
1656 		if (evsel->handler.func != NULL)
1657 			goto out_free;
1658 		evsel->handler.func = assocs[i].handler;
1659 next:
1660 		free(tracepoint);
1661 	}
1662 
1663 	err = 0;
1664 out:
1665 	return err;
1666 
1667 out_free:
1668 	free(tracepoint);
1669 	goto out;
1670 }
1671