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