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