xref: /openbmc/linux/tools/perf/util/session.c (revision 497a4dc8)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <inttypes.h>
4 #include <linux/err.h>
5 #include <linux/kernel.h>
6 #include <linux/zalloc.h>
7 #include <api/fs/fs.h>
8 
9 #include <byteswap.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12 #include <sys/mman.h>
13 #include <perf/cpumap.h>
14 
15 #include "map_symbol.h"
16 #include "branch.h"
17 #include "debug.h"
18 #include "evlist.h"
19 #include "evsel.h"
20 #include "memswap.h"
21 #include "map.h"
22 #include "symbol.h"
23 #include "session.h"
24 #include "tool.h"
25 #include "perf_regs.h"
26 #include "asm/bug.h"
27 #include "auxtrace.h"
28 #include "thread.h"
29 #include "thread-stack.h"
30 #include "sample-raw.h"
31 #include "stat.h"
32 #include "ui/progress.h"
33 #include "../perf.h"
34 #include "arch/common.h"
35 #include "units.h"
36 #include <internal/lib.h>
37 
38 #ifdef HAVE_ZSTD_SUPPORT
39 static int perf_session__process_compressed_event(struct perf_session *session,
40 						  union perf_event *event, u64 file_offset)
41 {
42 	void *src;
43 	size_t decomp_size, src_size;
44 	u64 decomp_last_rem = 0;
45 	size_t mmap_len, decomp_len = session->header.env.comp_mmap_len;
46 	struct decomp *decomp, *decomp_last = session->decomp_last;
47 
48 	if (decomp_last) {
49 		decomp_last_rem = decomp_last->size - decomp_last->head;
50 		decomp_len += decomp_last_rem;
51 	}
52 
53 	mmap_len = sizeof(struct decomp) + decomp_len;
54 	decomp = mmap(NULL, mmap_len, PROT_READ|PROT_WRITE,
55 		      MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
56 	if (decomp == MAP_FAILED) {
57 		pr_err("Couldn't allocate memory for decompression\n");
58 		return -1;
59 	}
60 
61 	decomp->file_pos = file_offset;
62 	decomp->mmap_len = mmap_len;
63 	decomp->head = 0;
64 
65 	if (decomp_last_rem) {
66 		memcpy(decomp->data, &(decomp_last->data[decomp_last->head]), decomp_last_rem);
67 		decomp->size = decomp_last_rem;
68 	}
69 
70 	src = (void *)event + sizeof(struct perf_record_compressed);
71 	src_size = event->pack.header.size - sizeof(struct perf_record_compressed);
72 
73 	decomp_size = zstd_decompress_stream(&(session->zstd_data), src, src_size,
74 				&(decomp->data[decomp_last_rem]), decomp_len - decomp_last_rem);
75 	if (!decomp_size) {
76 		munmap(decomp, mmap_len);
77 		pr_err("Couldn't decompress data\n");
78 		return -1;
79 	}
80 
81 	decomp->size += decomp_size;
82 
83 	if (session->decomp == NULL) {
84 		session->decomp = decomp;
85 		session->decomp_last = decomp;
86 	} else {
87 		session->decomp_last->next = decomp;
88 		session->decomp_last = decomp;
89 	}
90 
91 	pr_debug("decomp (B): %zd to %zd\n", src_size, decomp_size);
92 
93 	return 0;
94 }
95 #else /* !HAVE_ZSTD_SUPPORT */
96 #define perf_session__process_compressed_event perf_session__process_compressed_event_stub
97 #endif
98 
99 static int perf_session__deliver_event(struct perf_session *session,
100 				       union perf_event *event,
101 				       struct perf_tool *tool,
102 				       u64 file_offset);
103 
104 static int perf_session__open(struct perf_session *session)
105 {
106 	struct perf_data *data = session->data;
107 
108 	if (perf_session__read_header(session) < 0) {
109 		pr_err("incompatible file format (rerun with -v to learn more)\n");
110 		return -1;
111 	}
112 
113 	if (perf_data__is_pipe(data))
114 		return 0;
115 
116 	if (perf_header__has_feat(&session->header, HEADER_STAT))
117 		return 0;
118 
119 	if (!evlist__valid_sample_type(session->evlist)) {
120 		pr_err("non matching sample_type\n");
121 		return -1;
122 	}
123 
124 	if (!evlist__valid_sample_id_all(session->evlist)) {
125 		pr_err("non matching sample_id_all\n");
126 		return -1;
127 	}
128 
129 	if (!evlist__valid_read_format(session->evlist)) {
130 		pr_err("non matching read_format\n");
131 		return -1;
132 	}
133 
134 	return 0;
135 }
136 
137 void perf_session__set_id_hdr_size(struct perf_session *session)
138 {
139 	u16 id_hdr_size = evlist__id_hdr_size(session->evlist);
140 
141 	machines__set_id_hdr_size(&session->machines, id_hdr_size);
142 }
143 
144 int perf_session__create_kernel_maps(struct perf_session *session)
145 {
146 	int ret = machine__create_kernel_maps(&session->machines.host);
147 
148 	if (ret >= 0)
149 		ret = machines__create_guest_kernel_maps(&session->machines);
150 	return ret;
151 }
152 
153 static void perf_session__destroy_kernel_maps(struct perf_session *session)
154 {
155 	machines__destroy_kernel_maps(&session->machines);
156 }
157 
158 static bool perf_session__has_comm_exec(struct perf_session *session)
159 {
160 	struct evsel *evsel;
161 
162 	evlist__for_each_entry(session->evlist, evsel) {
163 		if (evsel->core.attr.comm_exec)
164 			return true;
165 	}
166 
167 	return false;
168 }
169 
170 static void perf_session__set_comm_exec(struct perf_session *session)
171 {
172 	bool comm_exec = perf_session__has_comm_exec(session);
173 
174 	machines__set_comm_exec(&session->machines, comm_exec);
175 }
176 
177 static int ordered_events__deliver_event(struct ordered_events *oe,
178 					 struct ordered_event *event)
179 {
180 	struct perf_session *session = container_of(oe, struct perf_session,
181 						    ordered_events);
182 
183 	return perf_session__deliver_event(session, event->event,
184 					   session->tool, event->file_offset);
185 }
186 
187 struct perf_session *perf_session__new(struct perf_data *data,
188 				       bool repipe, struct perf_tool *tool)
189 {
190 	int ret = -ENOMEM;
191 	struct perf_session *session = zalloc(sizeof(*session));
192 
193 	if (!session)
194 		goto out;
195 
196 	session->repipe = repipe;
197 	session->tool   = tool;
198 	INIT_LIST_HEAD(&session->auxtrace_index);
199 	machines__init(&session->machines);
200 	ordered_events__init(&session->ordered_events,
201 			     ordered_events__deliver_event, NULL);
202 
203 	perf_env__init(&session->header.env);
204 	if (data) {
205 		ret = perf_data__open(data);
206 		if (ret < 0)
207 			goto out_delete;
208 
209 		session->data = data;
210 
211 		if (perf_data__is_read(data)) {
212 			ret = perf_session__open(session);
213 			if (ret < 0)
214 				goto out_delete;
215 
216 			/*
217 			 * set session attributes that are present in perf.data
218 			 * but not in pipe-mode.
219 			 */
220 			if (!data->is_pipe) {
221 				perf_session__set_id_hdr_size(session);
222 				perf_session__set_comm_exec(session);
223 			}
224 
225 			evlist__init_trace_event_sample_raw(session->evlist);
226 
227 			/* Open the directory data. */
228 			if (data->is_dir) {
229 				ret = perf_data__open_dir(data);
230 				if (ret)
231 					goto out_delete;
232 			}
233 
234 			if (!symbol_conf.kallsyms_name &&
235 			    !symbol_conf.vmlinux_name)
236 				symbol_conf.kallsyms_name = perf_data__kallsyms_name(data);
237 		}
238 	} else  {
239 		session->machines.host.env = &perf_env;
240 	}
241 
242 	session->machines.host.single_address_space =
243 		perf_env__single_address_space(session->machines.host.env);
244 
245 	if (!data || perf_data__is_write(data)) {
246 		/*
247 		 * In O_RDONLY mode this will be performed when reading the
248 		 * kernel MMAP event, in perf_event__process_mmap().
249 		 */
250 		if (perf_session__create_kernel_maps(session) < 0)
251 			pr_warning("Cannot read kernel map\n");
252 	}
253 
254 	/*
255 	 * In pipe-mode, evlist is empty until PERF_RECORD_HEADER_ATTR is
256 	 * processed, so evlist__sample_id_all is not meaningful here.
257 	 */
258 	if ((!data || !data->is_pipe) && tool && tool->ordering_requires_timestamps &&
259 	    tool->ordered_events && !evlist__sample_id_all(session->evlist)) {
260 		dump_printf("WARNING: No sample_id_all support, falling back to unordered processing\n");
261 		tool->ordered_events = false;
262 	}
263 
264 	return session;
265 
266  out_delete:
267 	perf_session__delete(session);
268  out:
269 	return ERR_PTR(ret);
270 }
271 
272 static void perf_session__delete_threads(struct perf_session *session)
273 {
274 	machine__delete_threads(&session->machines.host);
275 }
276 
277 static void perf_session__release_decomp_events(struct perf_session *session)
278 {
279 	struct decomp *next, *decomp;
280 	size_t mmap_len;
281 	next = session->decomp;
282 	do {
283 		decomp = next;
284 		if (decomp == NULL)
285 			break;
286 		next = decomp->next;
287 		mmap_len = decomp->mmap_len;
288 		munmap(decomp, mmap_len);
289 	} while (1);
290 }
291 
292 void perf_session__delete(struct perf_session *session)
293 {
294 	if (session == NULL)
295 		return;
296 	auxtrace__free(session);
297 	auxtrace_index__free(&session->auxtrace_index);
298 	perf_session__destroy_kernel_maps(session);
299 	perf_session__delete_threads(session);
300 	perf_session__release_decomp_events(session);
301 	perf_env__exit(&session->header.env);
302 	machines__exit(&session->machines);
303 	if (session->data)
304 		perf_data__close(session->data);
305 	free(session);
306 }
307 
308 static int process_event_synth_tracing_data_stub(struct perf_session *session
309 						 __maybe_unused,
310 						 union perf_event *event
311 						 __maybe_unused)
312 {
313 	dump_printf(": unhandled!\n");
314 	return 0;
315 }
316 
317 static int process_event_synth_attr_stub(struct perf_tool *tool __maybe_unused,
318 					 union perf_event *event __maybe_unused,
319 					 struct evlist **pevlist
320 					 __maybe_unused)
321 {
322 	dump_printf(": unhandled!\n");
323 	return 0;
324 }
325 
326 static int process_event_synth_event_update_stub(struct perf_tool *tool __maybe_unused,
327 						 union perf_event *event __maybe_unused,
328 						 struct evlist **pevlist
329 						 __maybe_unused)
330 {
331 	if (dump_trace)
332 		perf_event__fprintf_event_update(event, stdout);
333 
334 	dump_printf(": unhandled!\n");
335 	return 0;
336 }
337 
338 static int process_event_sample_stub(struct perf_tool *tool __maybe_unused,
339 				     union perf_event *event __maybe_unused,
340 				     struct perf_sample *sample __maybe_unused,
341 				     struct evsel *evsel __maybe_unused,
342 				     struct machine *machine __maybe_unused)
343 {
344 	dump_printf(": unhandled!\n");
345 	return 0;
346 }
347 
348 static int process_event_stub(struct perf_tool *tool __maybe_unused,
349 			      union perf_event *event __maybe_unused,
350 			      struct perf_sample *sample __maybe_unused,
351 			      struct machine *machine __maybe_unused)
352 {
353 	dump_printf(": unhandled!\n");
354 	return 0;
355 }
356 
357 static int process_finished_round_stub(struct perf_tool *tool __maybe_unused,
358 				       union perf_event *event __maybe_unused,
359 				       struct ordered_events *oe __maybe_unused)
360 {
361 	dump_printf(": unhandled!\n");
362 	return 0;
363 }
364 
365 static int process_finished_round(struct perf_tool *tool,
366 				  union perf_event *event,
367 				  struct ordered_events *oe);
368 
369 static int skipn(int fd, off_t n)
370 {
371 	char buf[4096];
372 	ssize_t ret;
373 
374 	while (n > 0) {
375 		ret = read(fd, buf, min(n, (off_t)sizeof(buf)));
376 		if (ret <= 0)
377 			return ret;
378 		n -= ret;
379 	}
380 
381 	return 0;
382 }
383 
384 static s64 process_event_auxtrace_stub(struct perf_session *session __maybe_unused,
385 				       union perf_event *event)
386 {
387 	dump_printf(": unhandled!\n");
388 	if (perf_data__is_pipe(session->data))
389 		skipn(perf_data__fd(session->data), event->auxtrace.size);
390 	return event->auxtrace.size;
391 }
392 
393 static int process_event_op2_stub(struct perf_session *session __maybe_unused,
394 				  union perf_event *event __maybe_unused)
395 {
396 	dump_printf(": unhandled!\n");
397 	return 0;
398 }
399 
400 
401 static
402 int process_event_thread_map_stub(struct perf_session *session __maybe_unused,
403 				  union perf_event *event __maybe_unused)
404 {
405 	if (dump_trace)
406 		perf_event__fprintf_thread_map(event, stdout);
407 
408 	dump_printf(": unhandled!\n");
409 	return 0;
410 }
411 
412 static
413 int process_event_cpu_map_stub(struct perf_session *session __maybe_unused,
414 			       union perf_event *event __maybe_unused)
415 {
416 	if (dump_trace)
417 		perf_event__fprintf_cpu_map(event, stdout);
418 
419 	dump_printf(": unhandled!\n");
420 	return 0;
421 }
422 
423 static
424 int process_event_stat_config_stub(struct perf_session *session __maybe_unused,
425 				   union perf_event *event __maybe_unused)
426 {
427 	if (dump_trace)
428 		perf_event__fprintf_stat_config(event, stdout);
429 
430 	dump_printf(": unhandled!\n");
431 	return 0;
432 }
433 
434 static int process_stat_stub(struct perf_session *perf_session __maybe_unused,
435 			     union perf_event *event)
436 {
437 	if (dump_trace)
438 		perf_event__fprintf_stat(event, stdout);
439 
440 	dump_printf(": unhandled!\n");
441 	return 0;
442 }
443 
444 static int process_stat_round_stub(struct perf_session *perf_session __maybe_unused,
445 				   union perf_event *event)
446 {
447 	if (dump_trace)
448 		perf_event__fprintf_stat_round(event, stdout);
449 
450 	dump_printf(": unhandled!\n");
451 	return 0;
452 }
453 
454 static int perf_session__process_compressed_event_stub(struct perf_session *session __maybe_unused,
455 						       union perf_event *event __maybe_unused,
456 						       u64 file_offset __maybe_unused)
457 {
458        dump_printf(": unhandled!\n");
459        return 0;
460 }
461 
462 void perf_tool__fill_defaults(struct perf_tool *tool)
463 {
464 	if (tool->sample == NULL)
465 		tool->sample = process_event_sample_stub;
466 	if (tool->mmap == NULL)
467 		tool->mmap = process_event_stub;
468 	if (tool->mmap2 == NULL)
469 		tool->mmap2 = process_event_stub;
470 	if (tool->comm == NULL)
471 		tool->comm = process_event_stub;
472 	if (tool->namespaces == NULL)
473 		tool->namespaces = process_event_stub;
474 	if (tool->cgroup == NULL)
475 		tool->cgroup = process_event_stub;
476 	if (tool->fork == NULL)
477 		tool->fork = process_event_stub;
478 	if (tool->exit == NULL)
479 		tool->exit = process_event_stub;
480 	if (tool->lost == NULL)
481 		tool->lost = perf_event__process_lost;
482 	if (tool->lost_samples == NULL)
483 		tool->lost_samples = perf_event__process_lost_samples;
484 	if (tool->aux == NULL)
485 		tool->aux = perf_event__process_aux;
486 	if (tool->itrace_start == NULL)
487 		tool->itrace_start = perf_event__process_itrace_start;
488 	if (tool->context_switch == NULL)
489 		tool->context_switch = perf_event__process_switch;
490 	if (tool->ksymbol == NULL)
491 		tool->ksymbol = perf_event__process_ksymbol;
492 	if (tool->bpf == NULL)
493 		tool->bpf = perf_event__process_bpf;
494 	if (tool->text_poke == NULL)
495 		tool->text_poke = perf_event__process_text_poke;
496 	if (tool->read == NULL)
497 		tool->read = process_event_sample_stub;
498 	if (tool->throttle == NULL)
499 		tool->throttle = process_event_stub;
500 	if (tool->unthrottle == NULL)
501 		tool->unthrottle = process_event_stub;
502 	if (tool->attr == NULL)
503 		tool->attr = process_event_synth_attr_stub;
504 	if (tool->event_update == NULL)
505 		tool->event_update = process_event_synth_event_update_stub;
506 	if (tool->tracing_data == NULL)
507 		tool->tracing_data = process_event_synth_tracing_data_stub;
508 	if (tool->build_id == NULL)
509 		tool->build_id = process_event_op2_stub;
510 	if (tool->finished_round == NULL) {
511 		if (tool->ordered_events)
512 			tool->finished_round = process_finished_round;
513 		else
514 			tool->finished_round = process_finished_round_stub;
515 	}
516 	if (tool->id_index == NULL)
517 		tool->id_index = process_event_op2_stub;
518 	if (tool->auxtrace_info == NULL)
519 		tool->auxtrace_info = process_event_op2_stub;
520 	if (tool->auxtrace == NULL)
521 		tool->auxtrace = process_event_auxtrace_stub;
522 	if (tool->auxtrace_error == NULL)
523 		tool->auxtrace_error = process_event_op2_stub;
524 	if (tool->thread_map == NULL)
525 		tool->thread_map = process_event_thread_map_stub;
526 	if (tool->cpu_map == NULL)
527 		tool->cpu_map = process_event_cpu_map_stub;
528 	if (tool->stat_config == NULL)
529 		tool->stat_config = process_event_stat_config_stub;
530 	if (tool->stat == NULL)
531 		tool->stat = process_stat_stub;
532 	if (tool->stat_round == NULL)
533 		tool->stat_round = process_stat_round_stub;
534 	if (tool->time_conv == NULL)
535 		tool->time_conv = process_event_op2_stub;
536 	if (tool->feature == NULL)
537 		tool->feature = process_event_op2_stub;
538 	if (tool->compressed == NULL)
539 		tool->compressed = perf_session__process_compressed_event;
540 }
541 
542 static void swap_sample_id_all(union perf_event *event, void *data)
543 {
544 	void *end = (void *) event + event->header.size;
545 	int size = end - data;
546 
547 	BUG_ON(size % sizeof(u64));
548 	mem_bswap_64(data, size);
549 }
550 
551 static void perf_event__all64_swap(union perf_event *event,
552 				   bool sample_id_all __maybe_unused)
553 {
554 	struct perf_event_header *hdr = &event->header;
555 	mem_bswap_64(hdr + 1, event->header.size - sizeof(*hdr));
556 }
557 
558 static void perf_event__comm_swap(union perf_event *event, bool sample_id_all)
559 {
560 	event->comm.pid = bswap_32(event->comm.pid);
561 	event->comm.tid = bswap_32(event->comm.tid);
562 
563 	if (sample_id_all) {
564 		void *data = &event->comm.comm;
565 
566 		data += PERF_ALIGN(strlen(data) + 1, sizeof(u64));
567 		swap_sample_id_all(event, data);
568 	}
569 }
570 
571 static void perf_event__mmap_swap(union perf_event *event,
572 				  bool sample_id_all)
573 {
574 	event->mmap.pid	  = bswap_32(event->mmap.pid);
575 	event->mmap.tid	  = bswap_32(event->mmap.tid);
576 	event->mmap.start = bswap_64(event->mmap.start);
577 	event->mmap.len	  = bswap_64(event->mmap.len);
578 	event->mmap.pgoff = bswap_64(event->mmap.pgoff);
579 
580 	if (sample_id_all) {
581 		void *data = &event->mmap.filename;
582 
583 		data += PERF_ALIGN(strlen(data) + 1, sizeof(u64));
584 		swap_sample_id_all(event, data);
585 	}
586 }
587 
588 static void perf_event__mmap2_swap(union perf_event *event,
589 				  bool sample_id_all)
590 {
591 	event->mmap2.pid   = bswap_32(event->mmap2.pid);
592 	event->mmap2.tid   = bswap_32(event->mmap2.tid);
593 	event->mmap2.start = bswap_64(event->mmap2.start);
594 	event->mmap2.len   = bswap_64(event->mmap2.len);
595 	event->mmap2.pgoff = bswap_64(event->mmap2.pgoff);
596 
597 	if (!(event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID)) {
598 		event->mmap2.maj   = bswap_32(event->mmap2.maj);
599 		event->mmap2.min   = bswap_32(event->mmap2.min);
600 		event->mmap2.ino   = bswap_64(event->mmap2.ino);
601 		event->mmap2.ino_generation = bswap_64(event->mmap2.ino_generation);
602 	}
603 
604 	if (sample_id_all) {
605 		void *data = &event->mmap2.filename;
606 
607 		data += PERF_ALIGN(strlen(data) + 1, sizeof(u64));
608 		swap_sample_id_all(event, data);
609 	}
610 }
611 static void perf_event__task_swap(union perf_event *event, bool sample_id_all)
612 {
613 	event->fork.pid	 = bswap_32(event->fork.pid);
614 	event->fork.tid	 = bswap_32(event->fork.tid);
615 	event->fork.ppid = bswap_32(event->fork.ppid);
616 	event->fork.ptid = bswap_32(event->fork.ptid);
617 	event->fork.time = bswap_64(event->fork.time);
618 
619 	if (sample_id_all)
620 		swap_sample_id_all(event, &event->fork + 1);
621 }
622 
623 static void perf_event__read_swap(union perf_event *event, bool sample_id_all)
624 {
625 	event->read.pid		 = bswap_32(event->read.pid);
626 	event->read.tid		 = bswap_32(event->read.tid);
627 	event->read.value	 = bswap_64(event->read.value);
628 	event->read.time_enabled = bswap_64(event->read.time_enabled);
629 	event->read.time_running = bswap_64(event->read.time_running);
630 	event->read.id		 = bswap_64(event->read.id);
631 
632 	if (sample_id_all)
633 		swap_sample_id_all(event, &event->read + 1);
634 }
635 
636 static void perf_event__aux_swap(union perf_event *event, bool sample_id_all)
637 {
638 	event->aux.aux_offset = bswap_64(event->aux.aux_offset);
639 	event->aux.aux_size   = bswap_64(event->aux.aux_size);
640 	event->aux.flags      = bswap_64(event->aux.flags);
641 
642 	if (sample_id_all)
643 		swap_sample_id_all(event, &event->aux + 1);
644 }
645 
646 static void perf_event__itrace_start_swap(union perf_event *event,
647 					  bool sample_id_all)
648 {
649 	event->itrace_start.pid	 = bswap_32(event->itrace_start.pid);
650 	event->itrace_start.tid	 = bswap_32(event->itrace_start.tid);
651 
652 	if (sample_id_all)
653 		swap_sample_id_all(event, &event->itrace_start + 1);
654 }
655 
656 static void perf_event__switch_swap(union perf_event *event, bool sample_id_all)
657 {
658 	if (event->header.type == PERF_RECORD_SWITCH_CPU_WIDE) {
659 		event->context_switch.next_prev_pid =
660 				bswap_32(event->context_switch.next_prev_pid);
661 		event->context_switch.next_prev_tid =
662 				bswap_32(event->context_switch.next_prev_tid);
663 	}
664 
665 	if (sample_id_all)
666 		swap_sample_id_all(event, &event->context_switch + 1);
667 }
668 
669 static void perf_event__text_poke_swap(union perf_event *event, bool sample_id_all)
670 {
671 	event->text_poke.addr    = bswap_64(event->text_poke.addr);
672 	event->text_poke.old_len = bswap_16(event->text_poke.old_len);
673 	event->text_poke.new_len = bswap_16(event->text_poke.new_len);
674 
675 	if (sample_id_all) {
676 		size_t len = sizeof(event->text_poke.old_len) +
677 			     sizeof(event->text_poke.new_len) +
678 			     event->text_poke.old_len +
679 			     event->text_poke.new_len;
680 		void *data = &event->text_poke.old_len;
681 
682 		data += PERF_ALIGN(len, sizeof(u64));
683 		swap_sample_id_all(event, data);
684 	}
685 }
686 
687 static void perf_event__throttle_swap(union perf_event *event,
688 				      bool sample_id_all)
689 {
690 	event->throttle.time	  = bswap_64(event->throttle.time);
691 	event->throttle.id	  = bswap_64(event->throttle.id);
692 	event->throttle.stream_id = bswap_64(event->throttle.stream_id);
693 
694 	if (sample_id_all)
695 		swap_sample_id_all(event, &event->throttle + 1);
696 }
697 
698 static void perf_event__namespaces_swap(union perf_event *event,
699 					bool sample_id_all)
700 {
701 	u64 i;
702 
703 	event->namespaces.pid		= bswap_32(event->namespaces.pid);
704 	event->namespaces.tid		= bswap_32(event->namespaces.tid);
705 	event->namespaces.nr_namespaces	= bswap_64(event->namespaces.nr_namespaces);
706 
707 	for (i = 0; i < event->namespaces.nr_namespaces; i++) {
708 		struct perf_ns_link_info *ns = &event->namespaces.link_info[i];
709 
710 		ns->dev = bswap_64(ns->dev);
711 		ns->ino = bswap_64(ns->ino);
712 	}
713 
714 	if (sample_id_all)
715 		swap_sample_id_all(event, &event->namespaces.link_info[i]);
716 }
717 
718 static void perf_event__cgroup_swap(union perf_event *event, bool sample_id_all)
719 {
720 	event->cgroup.id = bswap_64(event->cgroup.id);
721 
722 	if (sample_id_all) {
723 		void *data = &event->cgroup.path;
724 
725 		data += PERF_ALIGN(strlen(data) + 1, sizeof(u64));
726 		swap_sample_id_all(event, data);
727 	}
728 }
729 
730 static u8 revbyte(u8 b)
731 {
732 	int rev = (b >> 4) | ((b & 0xf) << 4);
733 	rev = ((rev & 0xcc) >> 2) | ((rev & 0x33) << 2);
734 	rev = ((rev & 0xaa) >> 1) | ((rev & 0x55) << 1);
735 	return (u8) rev;
736 }
737 
738 /*
739  * XXX this is hack in attempt to carry flags bitfield
740  * through endian village. ABI says:
741  *
742  * Bit-fields are allocated from right to left (least to most significant)
743  * on little-endian implementations and from left to right (most to least
744  * significant) on big-endian implementations.
745  *
746  * The above seems to be byte specific, so we need to reverse each
747  * byte of the bitfield. 'Internet' also says this might be implementation
748  * specific and we probably need proper fix and carry perf_event_attr
749  * bitfield flags in separate data file FEAT_ section. Thought this seems
750  * to work for now.
751  */
752 static void swap_bitfield(u8 *p, unsigned len)
753 {
754 	unsigned i;
755 
756 	for (i = 0; i < len; i++) {
757 		*p = revbyte(*p);
758 		p++;
759 	}
760 }
761 
762 /* exported for swapping attributes in file header */
763 void perf_event__attr_swap(struct perf_event_attr *attr)
764 {
765 	attr->type		= bswap_32(attr->type);
766 	attr->size		= bswap_32(attr->size);
767 
768 #define bswap_safe(f, n) 					\
769 	(attr->size > (offsetof(struct perf_event_attr, f) + 	\
770 		       sizeof(attr->f) * (n)))
771 #define bswap_field(f, sz) 			\
772 do { 						\
773 	if (bswap_safe(f, 0))			\
774 		attr->f = bswap_##sz(attr->f);	\
775 } while(0)
776 #define bswap_field_16(f) bswap_field(f, 16)
777 #define bswap_field_32(f) bswap_field(f, 32)
778 #define bswap_field_64(f) bswap_field(f, 64)
779 
780 	bswap_field_64(config);
781 	bswap_field_64(sample_period);
782 	bswap_field_64(sample_type);
783 	bswap_field_64(read_format);
784 	bswap_field_32(wakeup_events);
785 	bswap_field_32(bp_type);
786 	bswap_field_64(bp_addr);
787 	bswap_field_64(bp_len);
788 	bswap_field_64(branch_sample_type);
789 	bswap_field_64(sample_regs_user);
790 	bswap_field_32(sample_stack_user);
791 	bswap_field_32(aux_watermark);
792 	bswap_field_16(sample_max_stack);
793 	bswap_field_32(aux_sample_size);
794 
795 	/*
796 	 * After read_format are bitfields. Check read_format because
797 	 * we are unable to use offsetof on bitfield.
798 	 */
799 	if (bswap_safe(read_format, 1))
800 		swap_bitfield((u8 *) (&attr->read_format + 1),
801 			      sizeof(u64));
802 #undef bswap_field_64
803 #undef bswap_field_32
804 #undef bswap_field
805 #undef bswap_safe
806 }
807 
808 static void perf_event__hdr_attr_swap(union perf_event *event,
809 				      bool sample_id_all __maybe_unused)
810 {
811 	size_t size;
812 
813 	perf_event__attr_swap(&event->attr.attr);
814 
815 	size = event->header.size;
816 	size -= (void *)&event->attr.id - (void *)event;
817 	mem_bswap_64(event->attr.id, size);
818 }
819 
820 static void perf_event__event_update_swap(union perf_event *event,
821 					  bool sample_id_all __maybe_unused)
822 {
823 	event->event_update.type = bswap_64(event->event_update.type);
824 	event->event_update.id   = bswap_64(event->event_update.id);
825 }
826 
827 static void perf_event__event_type_swap(union perf_event *event,
828 					bool sample_id_all __maybe_unused)
829 {
830 	event->event_type.event_type.event_id =
831 		bswap_64(event->event_type.event_type.event_id);
832 }
833 
834 static void perf_event__tracing_data_swap(union perf_event *event,
835 					  bool sample_id_all __maybe_unused)
836 {
837 	event->tracing_data.size = bswap_32(event->tracing_data.size);
838 }
839 
840 static void perf_event__auxtrace_info_swap(union perf_event *event,
841 					   bool sample_id_all __maybe_unused)
842 {
843 	size_t size;
844 
845 	event->auxtrace_info.type = bswap_32(event->auxtrace_info.type);
846 
847 	size = event->header.size;
848 	size -= (void *)&event->auxtrace_info.priv - (void *)event;
849 	mem_bswap_64(event->auxtrace_info.priv, size);
850 }
851 
852 static void perf_event__auxtrace_swap(union perf_event *event,
853 				      bool sample_id_all __maybe_unused)
854 {
855 	event->auxtrace.size      = bswap_64(event->auxtrace.size);
856 	event->auxtrace.offset    = bswap_64(event->auxtrace.offset);
857 	event->auxtrace.reference = bswap_64(event->auxtrace.reference);
858 	event->auxtrace.idx       = bswap_32(event->auxtrace.idx);
859 	event->auxtrace.tid       = bswap_32(event->auxtrace.tid);
860 	event->auxtrace.cpu       = bswap_32(event->auxtrace.cpu);
861 }
862 
863 static void perf_event__auxtrace_error_swap(union perf_event *event,
864 					    bool sample_id_all __maybe_unused)
865 {
866 	event->auxtrace_error.type = bswap_32(event->auxtrace_error.type);
867 	event->auxtrace_error.code = bswap_32(event->auxtrace_error.code);
868 	event->auxtrace_error.cpu  = bswap_32(event->auxtrace_error.cpu);
869 	event->auxtrace_error.pid  = bswap_32(event->auxtrace_error.pid);
870 	event->auxtrace_error.tid  = bswap_32(event->auxtrace_error.tid);
871 	event->auxtrace_error.fmt  = bswap_32(event->auxtrace_error.fmt);
872 	event->auxtrace_error.ip   = bswap_64(event->auxtrace_error.ip);
873 	if (event->auxtrace_error.fmt)
874 		event->auxtrace_error.time = bswap_64(event->auxtrace_error.time);
875 }
876 
877 static void perf_event__thread_map_swap(union perf_event *event,
878 					bool sample_id_all __maybe_unused)
879 {
880 	unsigned i;
881 
882 	event->thread_map.nr = bswap_64(event->thread_map.nr);
883 
884 	for (i = 0; i < event->thread_map.nr; i++)
885 		event->thread_map.entries[i].pid = bswap_64(event->thread_map.entries[i].pid);
886 }
887 
888 static void perf_event__cpu_map_swap(union perf_event *event,
889 				     bool sample_id_all __maybe_unused)
890 {
891 	struct perf_record_cpu_map_data *data = &event->cpu_map.data;
892 	struct cpu_map_entries *cpus;
893 	struct perf_record_record_cpu_map *mask;
894 	unsigned i;
895 
896 	data->type = bswap_64(data->type);
897 
898 	switch (data->type) {
899 	case PERF_CPU_MAP__CPUS:
900 		cpus = (struct cpu_map_entries *)data->data;
901 
902 		cpus->nr = bswap_16(cpus->nr);
903 
904 		for (i = 0; i < cpus->nr; i++)
905 			cpus->cpu[i] = bswap_16(cpus->cpu[i]);
906 		break;
907 	case PERF_CPU_MAP__MASK:
908 		mask = (struct perf_record_record_cpu_map *)data->data;
909 
910 		mask->nr = bswap_16(mask->nr);
911 		mask->long_size = bswap_16(mask->long_size);
912 
913 		switch (mask->long_size) {
914 		case 4: mem_bswap_32(&mask->mask, mask->nr); break;
915 		case 8: mem_bswap_64(&mask->mask, mask->nr); break;
916 		default:
917 			pr_err("cpu_map swap: unsupported long size\n");
918 		}
919 	default:
920 		break;
921 	}
922 }
923 
924 static void perf_event__stat_config_swap(union perf_event *event,
925 					 bool sample_id_all __maybe_unused)
926 {
927 	u64 size;
928 
929 	size  = event->stat_config.nr * sizeof(event->stat_config.data[0]);
930 	size += 1; /* nr item itself */
931 	mem_bswap_64(&event->stat_config.nr, size);
932 }
933 
934 static void perf_event__stat_swap(union perf_event *event,
935 				  bool sample_id_all __maybe_unused)
936 {
937 	event->stat.id     = bswap_64(event->stat.id);
938 	event->stat.thread = bswap_32(event->stat.thread);
939 	event->stat.cpu    = bswap_32(event->stat.cpu);
940 	event->stat.val    = bswap_64(event->stat.val);
941 	event->stat.ena    = bswap_64(event->stat.ena);
942 	event->stat.run    = bswap_64(event->stat.run);
943 }
944 
945 static void perf_event__stat_round_swap(union perf_event *event,
946 					bool sample_id_all __maybe_unused)
947 {
948 	event->stat_round.type = bswap_64(event->stat_round.type);
949 	event->stat_round.time = bswap_64(event->stat_round.time);
950 }
951 
952 typedef void (*perf_event__swap_op)(union perf_event *event,
953 				    bool sample_id_all);
954 
955 static perf_event__swap_op perf_event__swap_ops[] = {
956 	[PERF_RECORD_MMAP]		  = perf_event__mmap_swap,
957 	[PERF_RECORD_MMAP2]		  = perf_event__mmap2_swap,
958 	[PERF_RECORD_COMM]		  = perf_event__comm_swap,
959 	[PERF_RECORD_FORK]		  = perf_event__task_swap,
960 	[PERF_RECORD_EXIT]		  = perf_event__task_swap,
961 	[PERF_RECORD_LOST]		  = perf_event__all64_swap,
962 	[PERF_RECORD_READ]		  = perf_event__read_swap,
963 	[PERF_RECORD_THROTTLE]		  = perf_event__throttle_swap,
964 	[PERF_RECORD_UNTHROTTLE]	  = perf_event__throttle_swap,
965 	[PERF_RECORD_SAMPLE]		  = perf_event__all64_swap,
966 	[PERF_RECORD_AUX]		  = perf_event__aux_swap,
967 	[PERF_RECORD_ITRACE_START]	  = perf_event__itrace_start_swap,
968 	[PERF_RECORD_LOST_SAMPLES]	  = perf_event__all64_swap,
969 	[PERF_RECORD_SWITCH]		  = perf_event__switch_swap,
970 	[PERF_RECORD_SWITCH_CPU_WIDE]	  = perf_event__switch_swap,
971 	[PERF_RECORD_NAMESPACES]	  = perf_event__namespaces_swap,
972 	[PERF_RECORD_CGROUP]		  = perf_event__cgroup_swap,
973 	[PERF_RECORD_TEXT_POKE]		  = perf_event__text_poke_swap,
974 	[PERF_RECORD_HEADER_ATTR]	  = perf_event__hdr_attr_swap,
975 	[PERF_RECORD_HEADER_EVENT_TYPE]	  = perf_event__event_type_swap,
976 	[PERF_RECORD_HEADER_TRACING_DATA] = perf_event__tracing_data_swap,
977 	[PERF_RECORD_HEADER_BUILD_ID]	  = NULL,
978 	[PERF_RECORD_ID_INDEX]		  = perf_event__all64_swap,
979 	[PERF_RECORD_AUXTRACE_INFO]	  = perf_event__auxtrace_info_swap,
980 	[PERF_RECORD_AUXTRACE]		  = perf_event__auxtrace_swap,
981 	[PERF_RECORD_AUXTRACE_ERROR]	  = perf_event__auxtrace_error_swap,
982 	[PERF_RECORD_THREAD_MAP]	  = perf_event__thread_map_swap,
983 	[PERF_RECORD_CPU_MAP]		  = perf_event__cpu_map_swap,
984 	[PERF_RECORD_STAT_CONFIG]	  = perf_event__stat_config_swap,
985 	[PERF_RECORD_STAT]		  = perf_event__stat_swap,
986 	[PERF_RECORD_STAT_ROUND]	  = perf_event__stat_round_swap,
987 	[PERF_RECORD_EVENT_UPDATE]	  = perf_event__event_update_swap,
988 	[PERF_RECORD_TIME_CONV]		  = perf_event__all64_swap,
989 	[PERF_RECORD_HEADER_MAX]	  = NULL,
990 };
991 
992 /*
993  * When perf record finishes a pass on every buffers, it records this pseudo
994  * event.
995  * We record the max timestamp t found in the pass n.
996  * Assuming these timestamps are monotonic across cpus, we know that if
997  * a buffer still has events with timestamps below t, they will be all
998  * available and then read in the pass n + 1.
999  * Hence when we start to read the pass n + 2, we can safely flush every
1000  * events with timestamps below t.
1001  *
1002  *    ============ PASS n =================
1003  *       CPU 0         |   CPU 1
1004  *                     |
1005  *    cnt1 timestamps  |   cnt2 timestamps
1006  *          1          |         2
1007  *          2          |         3
1008  *          -          |         4  <--- max recorded
1009  *
1010  *    ============ PASS n + 1 ==============
1011  *       CPU 0         |   CPU 1
1012  *                     |
1013  *    cnt1 timestamps  |   cnt2 timestamps
1014  *          3          |         5
1015  *          4          |         6
1016  *          5          |         7 <---- max recorded
1017  *
1018  *      Flush every events below timestamp 4
1019  *
1020  *    ============ PASS n + 2 ==============
1021  *       CPU 0         |   CPU 1
1022  *                     |
1023  *    cnt1 timestamps  |   cnt2 timestamps
1024  *          6          |         8
1025  *          7          |         9
1026  *          -          |         10
1027  *
1028  *      Flush every events below timestamp 7
1029  *      etc...
1030  */
1031 static int process_finished_round(struct perf_tool *tool __maybe_unused,
1032 				  union perf_event *event __maybe_unused,
1033 				  struct ordered_events *oe)
1034 {
1035 	if (dump_trace)
1036 		fprintf(stdout, "\n");
1037 	return ordered_events__flush(oe, OE_FLUSH__ROUND);
1038 }
1039 
1040 int perf_session__queue_event(struct perf_session *s, union perf_event *event,
1041 			      u64 timestamp, u64 file_offset)
1042 {
1043 	return ordered_events__queue(&s->ordered_events, event, timestamp, file_offset);
1044 }
1045 
1046 static void callchain__lbr_callstack_printf(struct perf_sample *sample)
1047 {
1048 	struct ip_callchain *callchain = sample->callchain;
1049 	struct branch_stack *lbr_stack = sample->branch_stack;
1050 	struct branch_entry *entries = perf_sample__branch_entries(sample);
1051 	u64 kernel_callchain_nr = callchain->nr;
1052 	unsigned int i;
1053 
1054 	for (i = 0; i < kernel_callchain_nr; i++) {
1055 		if (callchain->ips[i] == PERF_CONTEXT_USER)
1056 			break;
1057 	}
1058 
1059 	if ((i != kernel_callchain_nr) && lbr_stack->nr) {
1060 		u64 total_nr;
1061 		/*
1062 		 * LBR callstack can only get user call chain,
1063 		 * i is kernel call chain number,
1064 		 * 1 is PERF_CONTEXT_USER.
1065 		 *
1066 		 * The user call chain is stored in LBR registers.
1067 		 * LBR are pair registers. The caller is stored
1068 		 * in "from" register, while the callee is stored
1069 		 * in "to" register.
1070 		 * For example, there is a call stack
1071 		 * "A"->"B"->"C"->"D".
1072 		 * The LBR registers will recorde like
1073 		 * "C"->"D", "B"->"C", "A"->"B".
1074 		 * So only the first "to" register and all "from"
1075 		 * registers are needed to construct the whole stack.
1076 		 */
1077 		total_nr = i + 1 + lbr_stack->nr + 1;
1078 		kernel_callchain_nr = i + 1;
1079 
1080 		printf("... LBR call chain: nr:%" PRIu64 "\n", total_nr);
1081 
1082 		for (i = 0; i < kernel_callchain_nr; i++)
1083 			printf("..... %2d: %016" PRIx64 "\n",
1084 			       i, callchain->ips[i]);
1085 
1086 		printf("..... %2d: %016" PRIx64 "\n",
1087 		       (int)(kernel_callchain_nr), entries[0].to);
1088 		for (i = 0; i < lbr_stack->nr; i++)
1089 			printf("..... %2d: %016" PRIx64 "\n",
1090 			       (int)(i + kernel_callchain_nr + 1), entries[i].from);
1091 	}
1092 }
1093 
1094 static void callchain__printf(struct evsel *evsel,
1095 			      struct perf_sample *sample)
1096 {
1097 	unsigned int i;
1098 	struct ip_callchain *callchain = sample->callchain;
1099 
1100 	if (evsel__has_branch_callstack(evsel))
1101 		callchain__lbr_callstack_printf(sample);
1102 
1103 	printf("... FP chain: nr:%" PRIu64 "\n", callchain->nr);
1104 
1105 	for (i = 0; i < callchain->nr; i++)
1106 		printf("..... %2d: %016" PRIx64 "\n",
1107 		       i, callchain->ips[i]);
1108 }
1109 
1110 static void branch_stack__printf(struct perf_sample *sample, bool callstack)
1111 {
1112 	struct branch_entry *entries = perf_sample__branch_entries(sample);
1113 	uint64_t i;
1114 
1115 	printf("%s: nr:%" PRIu64 "\n",
1116 		!callstack ? "... branch stack" : "... branch callstack",
1117 		sample->branch_stack->nr);
1118 
1119 	for (i = 0; i < sample->branch_stack->nr; i++) {
1120 		struct branch_entry *e = &entries[i];
1121 
1122 		if (!callstack) {
1123 			printf("..... %2"PRIu64": %016" PRIx64 " -> %016" PRIx64 " %hu cycles %s%s%s%s %x\n",
1124 				i, e->from, e->to,
1125 				(unsigned short)e->flags.cycles,
1126 				e->flags.mispred ? "M" : " ",
1127 				e->flags.predicted ? "P" : " ",
1128 				e->flags.abort ? "A" : " ",
1129 				e->flags.in_tx ? "T" : " ",
1130 				(unsigned)e->flags.reserved);
1131 		} else {
1132 			printf("..... %2"PRIu64": %016" PRIx64 "\n",
1133 				i, i > 0 ? e->from : e->to);
1134 		}
1135 	}
1136 }
1137 
1138 static void regs_dump__printf(u64 mask, u64 *regs)
1139 {
1140 	unsigned rid, i = 0;
1141 
1142 	for_each_set_bit(rid, (unsigned long *) &mask, sizeof(mask) * 8) {
1143 		u64 val = regs[i++];
1144 
1145 		printf(".... %-5s 0x%016" PRIx64 "\n",
1146 		       perf_reg_name(rid), val);
1147 	}
1148 }
1149 
1150 static const char *regs_abi[] = {
1151 	[PERF_SAMPLE_REGS_ABI_NONE] = "none",
1152 	[PERF_SAMPLE_REGS_ABI_32] = "32-bit",
1153 	[PERF_SAMPLE_REGS_ABI_64] = "64-bit",
1154 };
1155 
1156 static inline const char *regs_dump_abi(struct regs_dump *d)
1157 {
1158 	if (d->abi > PERF_SAMPLE_REGS_ABI_64)
1159 		return "unknown";
1160 
1161 	return regs_abi[d->abi];
1162 }
1163 
1164 static void regs__printf(const char *type, struct regs_dump *regs)
1165 {
1166 	u64 mask = regs->mask;
1167 
1168 	printf("... %s regs: mask 0x%" PRIx64 " ABI %s\n",
1169 	       type,
1170 	       mask,
1171 	       regs_dump_abi(regs));
1172 
1173 	regs_dump__printf(mask, regs->regs);
1174 }
1175 
1176 static void regs_user__printf(struct perf_sample *sample)
1177 {
1178 	struct regs_dump *user_regs = &sample->user_regs;
1179 
1180 	if (user_regs->regs)
1181 		regs__printf("user", user_regs);
1182 }
1183 
1184 static void regs_intr__printf(struct perf_sample *sample)
1185 {
1186 	struct regs_dump *intr_regs = &sample->intr_regs;
1187 
1188 	if (intr_regs->regs)
1189 		regs__printf("intr", intr_regs);
1190 }
1191 
1192 static void stack_user__printf(struct stack_dump *dump)
1193 {
1194 	printf("... ustack: size %" PRIu64 ", offset 0x%x\n",
1195 	       dump->size, dump->offset);
1196 }
1197 
1198 static void evlist__print_tstamp(struct evlist *evlist, union perf_event *event, struct perf_sample *sample)
1199 {
1200 	u64 sample_type = __evlist__combined_sample_type(evlist);
1201 
1202 	if (event->header.type != PERF_RECORD_SAMPLE &&
1203 	    !evlist__sample_id_all(evlist)) {
1204 		fputs("-1 -1 ", stdout);
1205 		return;
1206 	}
1207 
1208 	if ((sample_type & PERF_SAMPLE_CPU))
1209 		printf("%u ", sample->cpu);
1210 
1211 	if (sample_type & PERF_SAMPLE_TIME)
1212 		printf("%" PRIu64 " ", sample->time);
1213 }
1214 
1215 static void sample_read__printf(struct perf_sample *sample, u64 read_format)
1216 {
1217 	printf("... sample_read:\n");
1218 
1219 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1220 		printf("...... time enabled %016" PRIx64 "\n",
1221 		       sample->read.time_enabled);
1222 
1223 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1224 		printf("...... time running %016" PRIx64 "\n",
1225 		       sample->read.time_running);
1226 
1227 	if (read_format & PERF_FORMAT_GROUP) {
1228 		u64 i;
1229 
1230 		printf(".... group nr %" PRIu64 "\n", sample->read.group.nr);
1231 
1232 		for (i = 0; i < sample->read.group.nr; i++) {
1233 			struct sample_read_value *value;
1234 
1235 			value = &sample->read.group.values[i];
1236 			printf("..... id %016" PRIx64
1237 			       ", value %016" PRIx64 "\n",
1238 			       value->id, value->value);
1239 		}
1240 	} else
1241 		printf("..... id %016" PRIx64 ", value %016" PRIx64 "\n",
1242 			sample->read.one.id, sample->read.one.value);
1243 }
1244 
1245 static void dump_event(struct evlist *evlist, union perf_event *event,
1246 		       u64 file_offset, struct perf_sample *sample)
1247 {
1248 	if (!dump_trace)
1249 		return;
1250 
1251 	printf("\n%#" PRIx64 " [%#x]: event: %d\n",
1252 	       file_offset, event->header.size, event->header.type);
1253 
1254 	trace_event(event);
1255 	if (event->header.type == PERF_RECORD_SAMPLE && evlist->trace_event_sample_raw)
1256 		evlist->trace_event_sample_raw(evlist, event, sample);
1257 
1258 	if (sample)
1259 		evlist__print_tstamp(evlist, event, sample);
1260 
1261 	printf("%#" PRIx64 " [%#x]: PERF_RECORD_%s", file_offset,
1262 	       event->header.size, perf_event__name(event->header.type));
1263 }
1264 
1265 char *get_page_size_name(u64 size, char *str)
1266 {
1267 	if (!size || !unit_number__scnprintf(str, PAGE_SIZE_NAME_LEN, size))
1268 		snprintf(str, PAGE_SIZE_NAME_LEN, "%s", "N/A");
1269 
1270 	return str;
1271 }
1272 
1273 static void dump_sample(struct evsel *evsel, union perf_event *event,
1274 			struct perf_sample *sample)
1275 {
1276 	u64 sample_type;
1277 	char str[PAGE_SIZE_NAME_LEN];
1278 
1279 	if (!dump_trace)
1280 		return;
1281 
1282 	printf("(IP, 0x%x): %d/%d: %#" PRIx64 " period: %" PRIu64 " addr: %#" PRIx64 "\n",
1283 	       event->header.misc, sample->pid, sample->tid, sample->ip,
1284 	       sample->period, sample->addr);
1285 
1286 	sample_type = evsel->core.attr.sample_type;
1287 
1288 	if (evsel__has_callchain(evsel))
1289 		callchain__printf(evsel, sample);
1290 
1291 	if (evsel__has_br_stack(evsel))
1292 		branch_stack__printf(sample, evsel__has_branch_callstack(evsel));
1293 
1294 	if (sample_type & PERF_SAMPLE_REGS_USER)
1295 		regs_user__printf(sample);
1296 
1297 	if (sample_type & PERF_SAMPLE_REGS_INTR)
1298 		regs_intr__printf(sample);
1299 
1300 	if (sample_type & PERF_SAMPLE_STACK_USER)
1301 		stack_user__printf(&sample->user_stack);
1302 
1303 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
1304 		printf("... weight: %" PRIu64 "", sample->weight);
1305 			if (sample_type & PERF_SAMPLE_WEIGHT_STRUCT)
1306 				printf(",0x%"PRIx16"", sample->ins_lat);
1307 		printf("\n");
1308 	}
1309 
1310 	if (sample_type & PERF_SAMPLE_DATA_SRC)
1311 		printf(" . data_src: 0x%"PRIx64"\n", sample->data_src);
1312 
1313 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1314 		printf(" .. phys_addr: 0x%"PRIx64"\n", sample->phys_addr);
1315 
1316 	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1317 		printf(" .. data page size: %s\n", get_page_size_name(sample->data_page_size, str));
1318 
1319 	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1320 		printf(" .. code page size: %s\n", get_page_size_name(sample->code_page_size, str));
1321 
1322 	if (sample_type & PERF_SAMPLE_TRANSACTION)
1323 		printf("... transaction: %" PRIx64 "\n", sample->transaction);
1324 
1325 	if (sample_type & PERF_SAMPLE_READ)
1326 		sample_read__printf(sample, evsel->core.attr.read_format);
1327 }
1328 
1329 static void dump_read(struct evsel *evsel, union perf_event *event)
1330 {
1331 	struct perf_record_read *read_event = &event->read;
1332 	u64 read_format;
1333 
1334 	if (!dump_trace)
1335 		return;
1336 
1337 	printf(": %d %d %s %" PRI_lu64 "\n", event->read.pid, event->read.tid,
1338 	       evsel__name(evsel), event->read.value);
1339 
1340 	if (!evsel)
1341 		return;
1342 
1343 	read_format = evsel->core.attr.read_format;
1344 
1345 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1346 		printf("... time enabled : %" PRI_lu64 "\n", read_event->time_enabled);
1347 
1348 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1349 		printf("... time running : %" PRI_lu64 "\n", read_event->time_running);
1350 
1351 	if (read_format & PERF_FORMAT_ID)
1352 		printf("... id           : %" PRI_lu64 "\n", read_event->id);
1353 }
1354 
1355 static struct machine *machines__find_for_cpumode(struct machines *machines,
1356 					       union perf_event *event,
1357 					       struct perf_sample *sample)
1358 {
1359 	if (perf_guest &&
1360 	    ((sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL) ||
1361 	     (sample->cpumode == PERF_RECORD_MISC_GUEST_USER))) {
1362 		u32 pid;
1363 
1364 		if (event->header.type == PERF_RECORD_MMAP
1365 		    || event->header.type == PERF_RECORD_MMAP2)
1366 			pid = event->mmap.pid;
1367 		else
1368 			pid = sample->pid;
1369 
1370 		return machines__find_guest(machines, pid);
1371 	}
1372 
1373 	return &machines->host;
1374 }
1375 
1376 static int deliver_sample_value(struct evlist *evlist,
1377 				struct perf_tool *tool,
1378 				union perf_event *event,
1379 				struct perf_sample *sample,
1380 				struct sample_read_value *v,
1381 				struct machine *machine)
1382 {
1383 	struct perf_sample_id *sid = evlist__id2sid(evlist, v->id);
1384 	struct evsel *evsel;
1385 
1386 	if (sid) {
1387 		sample->id     = v->id;
1388 		sample->period = v->value - sid->period;
1389 		sid->period    = v->value;
1390 	}
1391 
1392 	if (!sid || sid->evsel == NULL) {
1393 		++evlist->stats.nr_unknown_id;
1394 		return 0;
1395 	}
1396 
1397 	/*
1398 	 * There's no reason to deliver sample
1399 	 * for zero period, bail out.
1400 	 */
1401 	if (!sample->period)
1402 		return 0;
1403 
1404 	evsel = container_of(sid->evsel, struct evsel, core);
1405 	return tool->sample(tool, event, sample, evsel, machine);
1406 }
1407 
1408 static int deliver_sample_group(struct evlist *evlist,
1409 				struct perf_tool *tool,
1410 				union  perf_event *event,
1411 				struct perf_sample *sample,
1412 				struct machine *machine)
1413 {
1414 	int ret = -EINVAL;
1415 	u64 i;
1416 
1417 	for (i = 0; i < sample->read.group.nr; i++) {
1418 		ret = deliver_sample_value(evlist, tool, event, sample,
1419 					   &sample->read.group.values[i],
1420 					   machine);
1421 		if (ret)
1422 			break;
1423 	}
1424 
1425 	return ret;
1426 }
1427 
1428 static int evlist__deliver_sample(struct evlist *evlist, struct perf_tool *tool,
1429 				  union  perf_event *event, struct perf_sample *sample,
1430 				  struct evsel *evsel, struct machine *machine)
1431 {
1432 	/* We know evsel != NULL. */
1433 	u64 sample_type = evsel->core.attr.sample_type;
1434 	u64 read_format = evsel->core.attr.read_format;
1435 
1436 	/* Standard sample delivery. */
1437 	if (!(sample_type & PERF_SAMPLE_READ))
1438 		return tool->sample(tool, event, sample, evsel, machine);
1439 
1440 	/* For PERF_SAMPLE_READ we have either single or group mode. */
1441 	if (read_format & PERF_FORMAT_GROUP)
1442 		return deliver_sample_group(evlist, tool, event, sample,
1443 					    machine);
1444 	else
1445 		return deliver_sample_value(evlist, tool, event, sample,
1446 					    &sample->read.one, machine);
1447 }
1448 
1449 static int machines__deliver_event(struct machines *machines,
1450 				   struct evlist *evlist,
1451 				   union perf_event *event,
1452 				   struct perf_sample *sample,
1453 				   struct perf_tool *tool, u64 file_offset)
1454 {
1455 	struct evsel *evsel;
1456 	struct machine *machine;
1457 
1458 	dump_event(evlist, event, file_offset, sample);
1459 
1460 	evsel = evlist__id2evsel(evlist, sample->id);
1461 
1462 	machine = machines__find_for_cpumode(machines, event, sample);
1463 
1464 	switch (event->header.type) {
1465 	case PERF_RECORD_SAMPLE:
1466 		if (evsel == NULL) {
1467 			++evlist->stats.nr_unknown_id;
1468 			return 0;
1469 		}
1470 		dump_sample(evsel, event, sample);
1471 		if (machine == NULL) {
1472 			++evlist->stats.nr_unprocessable_samples;
1473 			return 0;
1474 		}
1475 		return evlist__deliver_sample(evlist, tool, event, sample, evsel, machine);
1476 	case PERF_RECORD_MMAP:
1477 		return tool->mmap(tool, event, sample, machine);
1478 	case PERF_RECORD_MMAP2:
1479 		if (event->header.misc & PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT)
1480 			++evlist->stats.nr_proc_map_timeout;
1481 		return tool->mmap2(tool, event, sample, machine);
1482 	case PERF_RECORD_COMM:
1483 		return tool->comm(tool, event, sample, machine);
1484 	case PERF_RECORD_NAMESPACES:
1485 		return tool->namespaces(tool, event, sample, machine);
1486 	case PERF_RECORD_CGROUP:
1487 		return tool->cgroup(tool, event, sample, machine);
1488 	case PERF_RECORD_FORK:
1489 		return tool->fork(tool, event, sample, machine);
1490 	case PERF_RECORD_EXIT:
1491 		return tool->exit(tool, event, sample, machine);
1492 	case PERF_RECORD_LOST:
1493 		if (tool->lost == perf_event__process_lost)
1494 			evlist->stats.total_lost += event->lost.lost;
1495 		return tool->lost(tool, event, sample, machine);
1496 	case PERF_RECORD_LOST_SAMPLES:
1497 		if (tool->lost_samples == perf_event__process_lost_samples)
1498 			evlist->stats.total_lost_samples += event->lost_samples.lost;
1499 		return tool->lost_samples(tool, event, sample, machine);
1500 	case PERF_RECORD_READ:
1501 		dump_read(evsel, event);
1502 		return tool->read(tool, event, sample, evsel, machine);
1503 	case PERF_RECORD_THROTTLE:
1504 		return tool->throttle(tool, event, sample, machine);
1505 	case PERF_RECORD_UNTHROTTLE:
1506 		return tool->unthrottle(tool, event, sample, machine);
1507 	case PERF_RECORD_AUX:
1508 		if (tool->aux == perf_event__process_aux) {
1509 			if (event->aux.flags & PERF_AUX_FLAG_TRUNCATED)
1510 				evlist->stats.total_aux_lost += 1;
1511 			if (event->aux.flags & PERF_AUX_FLAG_PARTIAL)
1512 				evlist->stats.total_aux_partial += 1;
1513 		}
1514 		return tool->aux(tool, event, sample, machine);
1515 	case PERF_RECORD_ITRACE_START:
1516 		return tool->itrace_start(tool, event, sample, machine);
1517 	case PERF_RECORD_SWITCH:
1518 	case PERF_RECORD_SWITCH_CPU_WIDE:
1519 		return tool->context_switch(tool, event, sample, machine);
1520 	case PERF_RECORD_KSYMBOL:
1521 		return tool->ksymbol(tool, event, sample, machine);
1522 	case PERF_RECORD_BPF_EVENT:
1523 		return tool->bpf(tool, event, sample, machine);
1524 	case PERF_RECORD_TEXT_POKE:
1525 		return tool->text_poke(tool, event, sample, machine);
1526 	default:
1527 		++evlist->stats.nr_unknown_events;
1528 		return -1;
1529 	}
1530 }
1531 
1532 static int perf_session__deliver_event(struct perf_session *session,
1533 				       union perf_event *event,
1534 				       struct perf_tool *tool,
1535 				       u64 file_offset)
1536 {
1537 	struct perf_sample sample;
1538 	int ret = evlist__parse_sample(session->evlist, event, &sample);
1539 
1540 	if (ret) {
1541 		pr_err("Can't parse sample, err = %d\n", ret);
1542 		return ret;
1543 	}
1544 
1545 	ret = auxtrace__process_event(session, event, &sample, tool);
1546 	if (ret < 0)
1547 		return ret;
1548 	if (ret > 0)
1549 		return 0;
1550 
1551 	ret = machines__deliver_event(&session->machines, session->evlist,
1552 				      event, &sample, tool, file_offset);
1553 
1554 	if (dump_trace && sample.aux_sample.size)
1555 		auxtrace__dump_auxtrace_sample(session, &sample);
1556 
1557 	return ret;
1558 }
1559 
1560 static s64 perf_session__process_user_event(struct perf_session *session,
1561 					    union perf_event *event,
1562 					    u64 file_offset)
1563 {
1564 	struct ordered_events *oe = &session->ordered_events;
1565 	struct perf_tool *tool = session->tool;
1566 	struct perf_sample sample = { .time = 0, };
1567 	int fd = perf_data__fd(session->data);
1568 	int err;
1569 
1570 	if (event->header.type != PERF_RECORD_COMPRESSED ||
1571 	    tool->compressed == perf_session__process_compressed_event_stub)
1572 		dump_event(session->evlist, event, file_offset, &sample);
1573 
1574 	/* These events are processed right away */
1575 	switch (event->header.type) {
1576 	case PERF_RECORD_HEADER_ATTR:
1577 		err = tool->attr(tool, event, &session->evlist);
1578 		if (err == 0) {
1579 			perf_session__set_id_hdr_size(session);
1580 			perf_session__set_comm_exec(session);
1581 		}
1582 		return err;
1583 	case PERF_RECORD_EVENT_UPDATE:
1584 		return tool->event_update(tool, event, &session->evlist);
1585 	case PERF_RECORD_HEADER_EVENT_TYPE:
1586 		/*
1587 		 * Depreceated, but we need to handle it for sake
1588 		 * of old data files create in pipe mode.
1589 		 */
1590 		return 0;
1591 	case PERF_RECORD_HEADER_TRACING_DATA:
1592 		/*
1593 		 * Setup for reading amidst mmap, but only when we
1594 		 * are in 'file' mode. The 'pipe' fd is in proper
1595 		 * place already.
1596 		 */
1597 		if (!perf_data__is_pipe(session->data))
1598 			lseek(fd, file_offset, SEEK_SET);
1599 		return tool->tracing_data(session, event);
1600 	case PERF_RECORD_HEADER_BUILD_ID:
1601 		return tool->build_id(session, event);
1602 	case PERF_RECORD_FINISHED_ROUND:
1603 		return tool->finished_round(tool, event, oe);
1604 	case PERF_RECORD_ID_INDEX:
1605 		return tool->id_index(session, event);
1606 	case PERF_RECORD_AUXTRACE_INFO:
1607 		return tool->auxtrace_info(session, event);
1608 	case PERF_RECORD_AUXTRACE:
1609 		/* setup for reading amidst mmap */
1610 		lseek(fd, file_offset + event->header.size, SEEK_SET);
1611 		return tool->auxtrace(session, event);
1612 	case PERF_RECORD_AUXTRACE_ERROR:
1613 		perf_session__auxtrace_error_inc(session, event);
1614 		return tool->auxtrace_error(session, event);
1615 	case PERF_RECORD_THREAD_MAP:
1616 		return tool->thread_map(session, event);
1617 	case PERF_RECORD_CPU_MAP:
1618 		return tool->cpu_map(session, event);
1619 	case PERF_RECORD_STAT_CONFIG:
1620 		return tool->stat_config(session, event);
1621 	case PERF_RECORD_STAT:
1622 		return tool->stat(session, event);
1623 	case PERF_RECORD_STAT_ROUND:
1624 		return tool->stat_round(session, event);
1625 	case PERF_RECORD_TIME_CONV:
1626 		session->time_conv = event->time_conv;
1627 		return tool->time_conv(session, event);
1628 	case PERF_RECORD_HEADER_FEATURE:
1629 		return tool->feature(session, event);
1630 	case PERF_RECORD_COMPRESSED:
1631 		err = tool->compressed(session, event, file_offset);
1632 		if (err)
1633 			dump_event(session->evlist, event, file_offset, &sample);
1634 		return err;
1635 	default:
1636 		return -EINVAL;
1637 	}
1638 }
1639 
1640 int perf_session__deliver_synth_event(struct perf_session *session,
1641 				      union perf_event *event,
1642 				      struct perf_sample *sample)
1643 {
1644 	struct evlist *evlist = session->evlist;
1645 	struct perf_tool *tool = session->tool;
1646 
1647 	events_stats__inc(&evlist->stats, event->header.type);
1648 
1649 	if (event->header.type >= PERF_RECORD_USER_TYPE_START)
1650 		return perf_session__process_user_event(session, event, 0);
1651 
1652 	return machines__deliver_event(&session->machines, evlist, event, sample, tool, 0);
1653 }
1654 
1655 static void event_swap(union perf_event *event, bool sample_id_all)
1656 {
1657 	perf_event__swap_op swap;
1658 
1659 	swap = perf_event__swap_ops[event->header.type];
1660 	if (swap)
1661 		swap(event, sample_id_all);
1662 }
1663 
1664 int perf_session__peek_event(struct perf_session *session, off_t file_offset,
1665 			     void *buf, size_t buf_sz,
1666 			     union perf_event **event_ptr,
1667 			     struct perf_sample *sample)
1668 {
1669 	union perf_event *event;
1670 	size_t hdr_sz, rest;
1671 	int fd;
1672 
1673 	if (session->one_mmap && !session->header.needs_swap) {
1674 		event = file_offset - session->one_mmap_offset +
1675 			session->one_mmap_addr;
1676 		goto out_parse_sample;
1677 	}
1678 
1679 	if (perf_data__is_pipe(session->data))
1680 		return -1;
1681 
1682 	fd = perf_data__fd(session->data);
1683 	hdr_sz = sizeof(struct perf_event_header);
1684 
1685 	if (buf_sz < hdr_sz)
1686 		return -1;
1687 
1688 	if (lseek(fd, file_offset, SEEK_SET) == (off_t)-1 ||
1689 	    readn(fd, buf, hdr_sz) != (ssize_t)hdr_sz)
1690 		return -1;
1691 
1692 	event = (union perf_event *)buf;
1693 
1694 	if (session->header.needs_swap)
1695 		perf_event_header__bswap(&event->header);
1696 
1697 	if (event->header.size < hdr_sz || event->header.size > buf_sz)
1698 		return -1;
1699 
1700 	rest = event->header.size - hdr_sz;
1701 
1702 	if (readn(fd, buf, rest) != (ssize_t)rest)
1703 		return -1;
1704 
1705 	if (session->header.needs_swap)
1706 		event_swap(event, evlist__sample_id_all(session->evlist));
1707 
1708 out_parse_sample:
1709 
1710 	if (sample && event->header.type < PERF_RECORD_USER_TYPE_START &&
1711 	    evlist__parse_sample(session->evlist, event, sample))
1712 		return -1;
1713 
1714 	*event_ptr = event;
1715 
1716 	return 0;
1717 }
1718 
1719 int perf_session__peek_events(struct perf_session *session, u64 offset,
1720 			      u64 size, peek_events_cb_t cb, void *data)
1721 {
1722 	u64 max_offset = offset + size;
1723 	char buf[PERF_SAMPLE_MAX_SIZE];
1724 	union perf_event *event;
1725 	int err;
1726 
1727 	do {
1728 		err = perf_session__peek_event(session, offset, buf,
1729 					       PERF_SAMPLE_MAX_SIZE, &event,
1730 					       NULL);
1731 		if (err)
1732 			return err;
1733 
1734 		err = cb(session, event, offset, data);
1735 		if (err)
1736 			return err;
1737 
1738 		offset += event->header.size;
1739 		if (event->header.type == PERF_RECORD_AUXTRACE)
1740 			offset += event->auxtrace.size;
1741 
1742 	} while (offset < max_offset);
1743 
1744 	return err;
1745 }
1746 
1747 static s64 perf_session__process_event(struct perf_session *session,
1748 				       union perf_event *event, u64 file_offset)
1749 {
1750 	struct evlist *evlist = session->evlist;
1751 	struct perf_tool *tool = session->tool;
1752 	int ret;
1753 
1754 	if (session->header.needs_swap)
1755 		event_swap(event, evlist__sample_id_all(evlist));
1756 
1757 	if (event->header.type >= PERF_RECORD_HEADER_MAX)
1758 		return -EINVAL;
1759 
1760 	events_stats__inc(&evlist->stats, event->header.type);
1761 
1762 	if (event->header.type >= PERF_RECORD_USER_TYPE_START)
1763 		return perf_session__process_user_event(session, event, file_offset);
1764 
1765 	if (tool->ordered_events) {
1766 		u64 timestamp = -1ULL;
1767 
1768 		ret = evlist__parse_sample_timestamp(evlist, event, &timestamp);
1769 		if (ret && ret != -1)
1770 			return ret;
1771 
1772 		ret = perf_session__queue_event(session, event, timestamp, file_offset);
1773 		if (ret != -ETIME)
1774 			return ret;
1775 	}
1776 
1777 	return perf_session__deliver_event(session, event, tool, file_offset);
1778 }
1779 
1780 void perf_event_header__bswap(struct perf_event_header *hdr)
1781 {
1782 	hdr->type = bswap_32(hdr->type);
1783 	hdr->misc = bswap_16(hdr->misc);
1784 	hdr->size = bswap_16(hdr->size);
1785 }
1786 
1787 struct thread *perf_session__findnew(struct perf_session *session, pid_t pid)
1788 {
1789 	return machine__findnew_thread(&session->machines.host, -1, pid);
1790 }
1791 
1792 int perf_session__register_idle_thread(struct perf_session *session)
1793 {
1794 	struct thread *thread = machine__idle_thread(&session->machines.host);
1795 
1796 	/* machine__idle_thread() got the thread, so put it */
1797 	thread__put(thread);
1798 	return thread ? 0 : -1;
1799 }
1800 
1801 static void
1802 perf_session__warn_order(const struct perf_session *session)
1803 {
1804 	const struct ordered_events *oe = &session->ordered_events;
1805 	struct evsel *evsel;
1806 	bool should_warn = true;
1807 
1808 	evlist__for_each_entry(session->evlist, evsel) {
1809 		if (evsel->core.attr.write_backward)
1810 			should_warn = false;
1811 	}
1812 
1813 	if (!should_warn)
1814 		return;
1815 	if (oe->nr_unordered_events != 0)
1816 		ui__warning("%u out of order events recorded.\n", oe->nr_unordered_events);
1817 }
1818 
1819 static void perf_session__warn_about_errors(const struct perf_session *session)
1820 {
1821 	const struct events_stats *stats = &session->evlist->stats;
1822 
1823 	if (session->tool->lost == perf_event__process_lost &&
1824 	    stats->nr_events[PERF_RECORD_LOST] != 0) {
1825 		ui__warning("Processed %d events and lost %d chunks!\n\n"
1826 			    "Check IO/CPU overload!\n\n",
1827 			    stats->nr_events[0],
1828 			    stats->nr_events[PERF_RECORD_LOST]);
1829 	}
1830 
1831 	if (session->tool->lost_samples == perf_event__process_lost_samples) {
1832 		double drop_rate;
1833 
1834 		drop_rate = (double)stats->total_lost_samples /
1835 			    (double) (stats->nr_events[PERF_RECORD_SAMPLE] + stats->total_lost_samples);
1836 		if (drop_rate > 0.05) {
1837 			ui__warning("Processed %" PRIu64 " samples and lost %3.2f%%!\n\n",
1838 				    stats->nr_events[PERF_RECORD_SAMPLE] + stats->total_lost_samples,
1839 				    drop_rate * 100.0);
1840 		}
1841 	}
1842 
1843 	if (session->tool->aux == perf_event__process_aux &&
1844 	    stats->total_aux_lost != 0) {
1845 		ui__warning("AUX data lost %" PRIu64 " times out of %u!\n\n",
1846 			    stats->total_aux_lost,
1847 			    stats->nr_events[PERF_RECORD_AUX]);
1848 	}
1849 
1850 	if (session->tool->aux == perf_event__process_aux &&
1851 	    stats->total_aux_partial != 0) {
1852 		bool vmm_exclusive = false;
1853 
1854 		(void)sysfs__read_bool("module/kvm_intel/parameters/vmm_exclusive",
1855 		                       &vmm_exclusive);
1856 
1857 		ui__warning("AUX data had gaps in it %" PRIu64 " times out of %u!\n\n"
1858 		            "Are you running a KVM guest in the background?%s\n\n",
1859 			    stats->total_aux_partial,
1860 			    stats->nr_events[PERF_RECORD_AUX],
1861 			    vmm_exclusive ?
1862 			    "\nReloading kvm_intel module with vmm_exclusive=0\n"
1863 			    "will reduce the gaps to only guest's timeslices." :
1864 			    "");
1865 	}
1866 
1867 	if (stats->nr_unknown_events != 0) {
1868 		ui__warning("Found %u unknown events!\n\n"
1869 			    "Is this an older tool processing a perf.data "
1870 			    "file generated by a more recent tool?\n\n"
1871 			    "If that is not the case, consider "
1872 			    "reporting to linux-kernel@vger.kernel.org.\n\n",
1873 			    stats->nr_unknown_events);
1874 	}
1875 
1876 	if (stats->nr_unknown_id != 0) {
1877 		ui__warning("%u samples with id not present in the header\n",
1878 			    stats->nr_unknown_id);
1879 	}
1880 
1881 	if (stats->nr_invalid_chains != 0) {
1882 		ui__warning("Found invalid callchains!\n\n"
1883 			    "%u out of %u events were discarded for this reason.\n\n"
1884 			    "Consider reporting to linux-kernel@vger.kernel.org.\n\n",
1885 			    stats->nr_invalid_chains,
1886 			    stats->nr_events[PERF_RECORD_SAMPLE]);
1887 	}
1888 
1889 	if (stats->nr_unprocessable_samples != 0) {
1890 		ui__warning("%u unprocessable samples recorded.\n"
1891 			    "Do you have a KVM guest running and not using 'perf kvm'?\n",
1892 			    stats->nr_unprocessable_samples);
1893 	}
1894 
1895 	perf_session__warn_order(session);
1896 
1897 	events_stats__auxtrace_error_warn(stats);
1898 
1899 	if (stats->nr_proc_map_timeout != 0) {
1900 		ui__warning("%d map information files for pre-existing threads were\n"
1901 			    "not processed, if there are samples for addresses they\n"
1902 			    "will not be resolved, you may find out which are these\n"
1903 			    "threads by running with -v and redirecting the output\n"
1904 			    "to a file.\n"
1905 			    "The time limit to process proc map is too short?\n"
1906 			    "Increase it by --proc-map-timeout\n",
1907 			    stats->nr_proc_map_timeout);
1908 	}
1909 }
1910 
1911 static int perf_session__flush_thread_stack(struct thread *thread,
1912 					    void *p __maybe_unused)
1913 {
1914 	return thread_stack__flush(thread);
1915 }
1916 
1917 static int perf_session__flush_thread_stacks(struct perf_session *session)
1918 {
1919 	return machines__for_each_thread(&session->machines,
1920 					 perf_session__flush_thread_stack,
1921 					 NULL);
1922 }
1923 
1924 volatile int session_done;
1925 
1926 static int __perf_session__process_decomp_events(struct perf_session *session);
1927 
1928 static int __perf_session__process_pipe_events(struct perf_session *session)
1929 {
1930 	struct ordered_events *oe = &session->ordered_events;
1931 	struct perf_tool *tool = session->tool;
1932 	union perf_event *event;
1933 	uint32_t size, cur_size = 0;
1934 	void *buf = NULL;
1935 	s64 skip = 0;
1936 	u64 head;
1937 	ssize_t err;
1938 	void *p;
1939 
1940 	perf_tool__fill_defaults(tool);
1941 
1942 	head = 0;
1943 	cur_size = sizeof(union perf_event);
1944 
1945 	buf = malloc(cur_size);
1946 	if (!buf)
1947 		return -errno;
1948 	ordered_events__set_copy_on_queue(oe, true);
1949 more:
1950 	event = buf;
1951 	err = perf_data__read(session->data, event,
1952 			      sizeof(struct perf_event_header));
1953 	if (err <= 0) {
1954 		if (err == 0)
1955 			goto done;
1956 
1957 		pr_err("failed to read event header\n");
1958 		goto out_err;
1959 	}
1960 
1961 	if (session->header.needs_swap)
1962 		perf_event_header__bswap(&event->header);
1963 
1964 	size = event->header.size;
1965 	if (size < sizeof(struct perf_event_header)) {
1966 		pr_err("bad event header size\n");
1967 		goto out_err;
1968 	}
1969 
1970 	if (size > cur_size) {
1971 		void *new = realloc(buf, size);
1972 		if (!new) {
1973 			pr_err("failed to allocate memory to read event\n");
1974 			goto out_err;
1975 		}
1976 		buf = new;
1977 		cur_size = size;
1978 		event = buf;
1979 	}
1980 	p = event;
1981 	p += sizeof(struct perf_event_header);
1982 
1983 	if (size - sizeof(struct perf_event_header)) {
1984 		err = perf_data__read(session->data, p,
1985 				      size - sizeof(struct perf_event_header));
1986 		if (err <= 0) {
1987 			if (err == 0) {
1988 				pr_err("unexpected end of event stream\n");
1989 				goto done;
1990 			}
1991 
1992 			pr_err("failed to read event data\n");
1993 			goto out_err;
1994 		}
1995 	}
1996 
1997 	if ((skip = perf_session__process_event(session, event, head)) < 0) {
1998 		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
1999 		       head, event->header.size, event->header.type);
2000 		err = -EINVAL;
2001 		goto out_err;
2002 	}
2003 
2004 	head += size;
2005 
2006 	if (skip > 0)
2007 		head += skip;
2008 
2009 	err = __perf_session__process_decomp_events(session);
2010 	if (err)
2011 		goto out_err;
2012 
2013 	if (!session_done())
2014 		goto more;
2015 done:
2016 	/* do the final flush for ordered samples */
2017 	err = ordered_events__flush(oe, OE_FLUSH__FINAL);
2018 	if (err)
2019 		goto out_err;
2020 	err = auxtrace__flush_events(session, tool);
2021 	if (err)
2022 		goto out_err;
2023 	err = perf_session__flush_thread_stacks(session);
2024 out_err:
2025 	free(buf);
2026 	if (!tool->no_warn)
2027 		perf_session__warn_about_errors(session);
2028 	ordered_events__free(&session->ordered_events);
2029 	auxtrace__free_events(session);
2030 	return err;
2031 }
2032 
2033 static union perf_event *
2034 prefetch_event(char *buf, u64 head, size_t mmap_size,
2035 	       bool needs_swap, union perf_event *error)
2036 {
2037 	union perf_event *event;
2038 
2039 	/*
2040 	 * Ensure we have enough space remaining to read
2041 	 * the size of the event in the headers.
2042 	 */
2043 	if (head + sizeof(event->header) > mmap_size)
2044 		return NULL;
2045 
2046 	event = (union perf_event *)(buf + head);
2047 	if (needs_swap)
2048 		perf_event_header__bswap(&event->header);
2049 
2050 	if (head + event->header.size <= mmap_size)
2051 		return event;
2052 
2053 	/* We're not fetching the event so swap back again */
2054 	if (needs_swap)
2055 		perf_event_header__bswap(&event->header);
2056 
2057 	pr_debug("%s: head=%#" PRIx64 " event->header_size=%#x, mmap_size=%#zx:"
2058 		 " fuzzed or compressed perf.data?\n",__func__, head, event->header.size, mmap_size);
2059 
2060 	return error;
2061 }
2062 
2063 static union perf_event *
2064 fetch_mmaped_event(u64 head, size_t mmap_size, char *buf, bool needs_swap)
2065 {
2066 	return prefetch_event(buf, head, mmap_size, needs_swap, ERR_PTR(-EINVAL));
2067 }
2068 
2069 static union perf_event *
2070 fetch_decomp_event(u64 head, size_t mmap_size, char *buf, bool needs_swap)
2071 {
2072 	return prefetch_event(buf, head, mmap_size, needs_swap, NULL);
2073 }
2074 
2075 static int __perf_session__process_decomp_events(struct perf_session *session)
2076 {
2077 	s64 skip;
2078 	u64 size, file_pos = 0;
2079 	struct decomp *decomp = session->decomp_last;
2080 
2081 	if (!decomp)
2082 		return 0;
2083 
2084 	while (decomp->head < decomp->size && !session_done()) {
2085 		union perf_event *event = fetch_decomp_event(decomp->head, decomp->size, decomp->data,
2086 							     session->header.needs_swap);
2087 
2088 		if (!event)
2089 			break;
2090 
2091 		size = event->header.size;
2092 
2093 		if (size < sizeof(struct perf_event_header) ||
2094 		    (skip = perf_session__process_event(session, event, file_pos)) < 0) {
2095 			pr_err("%#" PRIx64 " [%#x]: failed to process type: %d\n",
2096 				decomp->file_pos + decomp->head, event->header.size, event->header.type);
2097 			return -EINVAL;
2098 		}
2099 
2100 		if (skip)
2101 			size += skip;
2102 
2103 		decomp->head += size;
2104 	}
2105 
2106 	return 0;
2107 }
2108 
2109 /*
2110  * On 64bit we can mmap the data file in one go. No need for tiny mmap
2111  * slices. On 32bit we use 32MB.
2112  */
2113 #if BITS_PER_LONG == 64
2114 #define MMAP_SIZE ULLONG_MAX
2115 #define NUM_MMAPS 1
2116 #else
2117 #define MMAP_SIZE (32 * 1024 * 1024ULL)
2118 #define NUM_MMAPS 128
2119 #endif
2120 
2121 struct reader;
2122 
2123 typedef s64 (*reader_cb_t)(struct perf_session *session,
2124 			   union perf_event *event,
2125 			   u64 file_offset);
2126 
2127 struct reader {
2128 	int		 fd;
2129 	u64		 data_size;
2130 	u64		 data_offset;
2131 	reader_cb_t	 process;
2132 };
2133 
2134 static int
2135 reader__process_events(struct reader *rd, struct perf_session *session,
2136 		       struct ui_progress *prog)
2137 {
2138 	u64 data_size = rd->data_size;
2139 	u64 head, page_offset, file_offset, file_pos, size;
2140 	int err = 0, mmap_prot, mmap_flags, map_idx = 0;
2141 	size_t	mmap_size;
2142 	char *buf, *mmaps[NUM_MMAPS];
2143 	union perf_event *event;
2144 	s64 skip;
2145 
2146 	page_offset = page_size * (rd->data_offset / page_size);
2147 	file_offset = page_offset;
2148 	head = rd->data_offset - page_offset;
2149 
2150 	ui_progress__init_size(prog, data_size, "Processing events...");
2151 
2152 	data_size += rd->data_offset;
2153 
2154 	mmap_size = MMAP_SIZE;
2155 	if (mmap_size > data_size) {
2156 		mmap_size = data_size;
2157 		session->one_mmap = true;
2158 	}
2159 
2160 	memset(mmaps, 0, sizeof(mmaps));
2161 
2162 	mmap_prot  = PROT_READ;
2163 	mmap_flags = MAP_SHARED;
2164 
2165 	if (session->header.needs_swap) {
2166 		mmap_prot  |= PROT_WRITE;
2167 		mmap_flags = MAP_PRIVATE;
2168 	}
2169 remap:
2170 	buf = mmap(NULL, mmap_size, mmap_prot, mmap_flags, rd->fd,
2171 		   file_offset);
2172 	if (buf == MAP_FAILED) {
2173 		pr_err("failed to mmap file\n");
2174 		err = -errno;
2175 		goto out;
2176 	}
2177 	mmaps[map_idx] = buf;
2178 	map_idx = (map_idx + 1) & (ARRAY_SIZE(mmaps) - 1);
2179 	file_pos = file_offset + head;
2180 	if (session->one_mmap) {
2181 		session->one_mmap_addr = buf;
2182 		session->one_mmap_offset = file_offset;
2183 	}
2184 
2185 more:
2186 	event = fetch_mmaped_event(head, mmap_size, buf, session->header.needs_swap);
2187 	if (IS_ERR(event))
2188 		return PTR_ERR(event);
2189 
2190 	if (!event) {
2191 		if (mmaps[map_idx]) {
2192 			munmap(mmaps[map_idx], mmap_size);
2193 			mmaps[map_idx] = NULL;
2194 		}
2195 
2196 		page_offset = page_size * (head / page_size);
2197 		file_offset += page_offset;
2198 		head -= page_offset;
2199 		goto remap;
2200 	}
2201 
2202 	size = event->header.size;
2203 
2204 	skip = -EINVAL;
2205 
2206 	if (size < sizeof(struct perf_event_header) ||
2207 	    (skip = rd->process(session, event, file_pos)) < 0) {
2208 		pr_err("%#" PRIx64 " [%#x]: failed to process type: %d [%s]\n",
2209 		       file_offset + head, event->header.size,
2210 		       event->header.type, strerror(-skip));
2211 		err = skip;
2212 		goto out;
2213 	}
2214 
2215 	if (skip)
2216 		size += skip;
2217 
2218 	head += size;
2219 	file_pos += size;
2220 
2221 	err = __perf_session__process_decomp_events(session);
2222 	if (err)
2223 		goto out;
2224 
2225 	ui_progress__update(prog, size);
2226 
2227 	if (session_done())
2228 		goto out;
2229 
2230 	if (file_pos < data_size)
2231 		goto more;
2232 
2233 out:
2234 	return err;
2235 }
2236 
2237 static s64 process_simple(struct perf_session *session,
2238 			  union perf_event *event,
2239 			  u64 file_offset)
2240 {
2241 	return perf_session__process_event(session, event, file_offset);
2242 }
2243 
2244 static int __perf_session__process_events(struct perf_session *session)
2245 {
2246 	struct reader rd = {
2247 		.fd		= perf_data__fd(session->data),
2248 		.data_size	= session->header.data_size,
2249 		.data_offset	= session->header.data_offset,
2250 		.process	= process_simple,
2251 	};
2252 	struct ordered_events *oe = &session->ordered_events;
2253 	struct perf_tool *tool = session->tool;
2254 	struct ui_progress prog;
2255 	int err;
2256 
2257 	perf_tool__fill_defaults(tool);
2258 
2259 	if (rd.data_size == 0)
2260 		return -1;
2261 
2262 	ui_progress__init_size(&prog, rd.data_size, "Processing events...");
2263 
2264 	err = reader__process_events(&rd, session, &prog);
2265 	if (err)
2266 		goto out_err;
2267 	/* do the final flush for ordered samples */
2268 	err = ordered_events__flush(oe, OE_FLUSH__FINAL);
2269 	if (err)
2270 		goto out_err;
2271 	err = auxtrace__flush_events(session, tool);
2272 	if (err)
2273 		goto out_err;
2274 	err = perf_session__flush_thread_stacks(session);
2275 out_err:
2276 	ui_progress__finish();
2277 	if (!tool->no_warn)
2278 		perf_session__warn_about_errors(session);
2279 	/*
2280 	 * We may switching perf.data output, make ordered_events
2281 	 * reusable.
2282 	 */
2283 	ordered_events__reinit(&session->ordered_events);
2284 	auxtrace__free_events(session);
2285 	session->one_mmap = false;
2286 	return err;
2287 }
2288 
2289 int perf_session__process_events(struct perf_session *session)
2290 {
2291 	if (perf_session__register_idle_thread(session) < 0)
2292 		return -ENOMEM;
2293 
2294 	if (perf_data__is_pipe(session->data))
2295 		return __perf_session__process_pipe_events(session);
2296 
2297 	return __perf_session__process_events(session);
2298 }
2299 
2300 bool perf_session__has_traces(struct perf_session *session, const char *msg)
2301 {
2302 	struct evsel *evsel;
2303 
2304 	evlist__for_each_entry(session->evlist, evsel) {
2305 		if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT)
2306 			return true;
2307 	}
2308 
2309 	pr_err("No trace sample to read. Did you call 'perf %s'?\n", msg);
2310 	return false;
2311 }
2312 
2313 int map__set_kallsyms_ref_reloc_sym(struct map *map, const char *symbol_name, u64 addr)
2314 {
2315 	char *bracket;
2316 	struct ref_reloc_sym *ref;
2317 	struct kmap *kmap;
2318 
2319 	ref = zalloc(sizeof(struct ref_reloc_sym));
2320 	if (ref == NULL)
2321 		return -ENOMEM;
2322 
2323 	ref->name = strdup(symbol_name);
2324 	if (ref->name == NULL) {
2325 		free(ref);
2326 		return -ENOMEM;
2327 	}
2328 
2329 	bracket = strchr(ref->name, ']');
2330 	if (bracket)
2331 		*bracket = '\0';
2332 
2333 	ref->addr = addr;
2334 
2335 	kmap = map__kmap(map);
2336 	if (kmap)
2337 		kmap->ref_reloc_sym = ref;
2338 
2339 	return 0;
2340 }
2341 
2342 size_t perf_session__fprintf_dsos(struct perf_session *session, FILE *fp)
2343 {
2344 	return machines__fprintf_dsos(&session->machines, fp);
2345 }
2346 
2347 size_t perf_session__fprintf_dsos_buildid(struct perf_session *session, FILE *fp,
2348 					  bool (skip)(struct dso *dso, int parm), int parm)
2349 {
2350 	return machines__fprintf_dsos_buildid(&session->machines, fp, skip, parm);
2351 }
2352 
2353 size_t perf_session__fprintf_nr_events(struct perf_session *session, FILE *fp)
2354 {
2355 	size_t ret;
2356 	const char *msg = "";
2357 
2358 	if (perf_header__has_feat(&session->header, HEADER_AUXTRACE))
2359 		msg = " (excludes AUX area (e.g. instruction trace) decoded / synthesized events)";
2360 
2361 	ret = fprintf(fp, "\nAggregated stats:%s\n", msg);
2362 
2363 	ret += events_stats__fprintf(&session->evlist->stats, fp);
2364 	return ret;
2365 }
2366 
2367 size_t perf_session__fprintf(struct perf_session *session, FILE *fp)
2368 {
2369 	/*
2370 	 * FIXME: Here we have to actually print all the machines in this
2371 	 * session, not just the host...
2372 	 */
2373 	return machine__fprintf(&session->machines.host, fp);
2374 }
2375 
2376 struct evsel *perf_session__find_first_evtype(struct perf_session *session,
2377 					      unsigned int type)
2378 {
2379 	struct evsel *pos;
2380 
2381 	evlist__for_each_entry(session->evlist, pos) {
2382 		if (pos->core.attr.type == type)
2383 			return pos;
2384 	}
2385 	return NULL;
2386 }
2387 
2388 int perf_session__cpu_bitmap(struct perf_session *session,
2389 			     const char *cpu_list, unsigned long *cpu_bitmap)
2390 {
2391 	int i, err = -1;
2392 	struct perf_cpu_map *map;
2393 	int nr_cpus = min(session->header.env.nr_cpus_avail, MAX_NR_CPUS);
2394 
2395 	for (i = 0; i < PERF_TYPE_MAX; ++i) {
2396 		struct evsel *evsel;
2397 
2398 		evsel = perf_session__find_first_evtype(session, i);
2399 		if (!evsel)
2400 			continue;
2401 
2402 		if (!(evsel->core.attr.sample_type & PERF_SAMPLE_CPU)) {
2403 			pr_err("File does not contain CPU events. "
2404 			       "Remove -C option to proceed.\n");
2405 			return -1;
2406 		}
2407 	}
2408 
2409 	map = perf_cpu_map__new(cpu_list);
2410 	if (map == NULL) {
2411 		pr_err("Invalid cpu_list\n");
2412 		return -1;
2413 	}
2414 
2415 	for (i = 0; i < map->nr; i++) {
2416 		int cpu = map->map[i];
2417 
2418 		if (cpu >= nr_cpus) {
2419 			pr_err("Requested CPU %d too large. "
2420 			       "Consider raising MAX_NR_CPUS\n", cpu);
2421 			goto out_delete_map;
2422 		}
2423 
2424 		set_bit(cpu, cpu_bitmap);
2425 	}
2426 
2427 	err = 0;
2428 
2429 out_delete_map:
2430 	perf_cpu_map__put(map);
2431 	return err;
2432 }
2433 
2434 void perf_session__fprintf_info(struct perf_session *session, FILE *fp,
2435 				bool full)
2436 {
2437 	if (session == NULL || fp == NULL)
2438 		return;
2439 
2440 	fprintf(fp, "# ========\n");
2441 	perf_header__fprintf_info(session, fp, full);
2442 	fprintf(fp, "# ========\n#\n");
2443 }
2444 
2445 int perf_event__process_id_index(struct perf_session *session,
2446 				 union perf_event *event)
2447 {
2448 	struct evlist *evlist = session->evlist;
2449 	struct perf_record_id_index *ie = &event->id_index;
2450 	size_t i, nr, max_nr;
2451 
2452 	max_nr = (ie->header.size - sizeof(struct perf_record_id_index)) /
2453 		 sizeof(struct id_index_entry);
2454 	nr = ie->nr;
2455 	if (nr > max_nr)
2456 		return -EINVAL;
2457 
2458 	if (dump_trace)
2459 		fprintf(stdout, " nr: %zu\n", nr);
2460 
2461 	for (i = 0; i < nr; i++) {
2462 		struct id_index_entry *e = &ie->entries[i];
2463 		struct perf_sample_id *sid;
2464 
2465 		if (dump_trace) {
2466 			fprintf(stdout,	" ... id: %"PRI_lu64, e->id);
2467 			fprintf(stdout,	"  idx: %"PRI_lu64, e->idx);
2468 			fprintf(stdout,	"  cpu: %"PRI_ld64, e->cpu);
2469 			fprintf(stdout,	"  tid: %"PRI_ld64"\n", e->tid);
2470 		}
2471 
2472 		sid = evlist__id2sid(evlist, e->id);
2473 		if (!sid)
2474 			return -ENOENT;
2475 		sid->idx = e->idx;
2476 		sid->cpu = e->cpu;
2477 		sid->tid = e->tid;
2478 	}
2479 	return 0;
2480 }
2481