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