xref: /linux/tools/perf/util/machine.c (revision 7255fcc80d4b525cc10cfaaf7f485830d4ed2000)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <dirent.h>
3 #include <errno.h>
4 #include <inttypes.h>
5 #include <regex.h>
6 #include <stdlib.h>
7 #include "callchain.h"
8 #include "debug.h"
9 #include "dso.h"
10 #include "env.h"
11 #include "event.h"
12 #include "evsel.h"
13 #include "hist.h"
14 #include "machine.h"
15 #include "map.h"
16 #include "map_symbol.h"
17 #include "branch.h"
18 #include "mem-events.h"
19 #include "path.h"
20 #include "srcline.h"
21 #include "symbol.h"
22 #include "sort.h"
23 #include "strlist.h"
24 #include "target.h"
25 #include "thread.h"
26 #include "util.h"
27 #include "vdso.h"
28 #include <stdbool.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <unistd.h>
32 #include "unwind.h"
33 #include "linux/hash.h"
34 #include "asm/bug.h"
35 #include "bpf-event.h"
36 #include <internal/lib.h> // page_size
37 #include "cgroup.h"
38 #include "arm64-frame-pointer-unwind-support.h"
39 
40 #include <linux/ctype.h>
41 #include <symbol/kallsyms.h>
42 #include <linux/mman.h>
43 #include <linux/string.h>
44 #include <linux/zalloc.h>
45 
46 static struct dso *machine__kernel_dso(struct machine *machine)
47 {
48 	return map__dso(machine->vmlinux_map);
49 }
50 
51 static int machine__set_mmap_name(struct machine *machine)
52 {
53 	if (machine__is_host(machine))
54 		machine->mmap_name = strdup("[kernel.kallsyms]");
55 	else if (machine__is_default_guest(machine))
56 		machine->mmap_name = strdup("[guest.kernel.kallsyms]");
57 	else if (asprintf(&machine->mmap_name, "[guest.kernel.kallsyms.%d]",
58 			  machine->pid) < 0)
59 		machine->mmap_name = NULL;
60 
61 	return machine->mmap_name ? 0 : -ENOMEM;
62 }
63 
64 static void thread__set_guest_comm(struct thread *thread, pid_t pid)
65 {
66 	char comm[64];
67 
68 	snprintf(comm, sizeof(comm), "[guest/%d]", pid);
69 	thread__set_comm(thread, comm, 0);
70 }
71 
72 int machine__init(struct machine *machine, const char *root_dir, pid_t pid)
73 {
74 	int err = -ENOMEM;
75 
76 	memset(machine, 0, sizeof(*machine));
77 	machine->kmaps = maps__new(machine);
78 	if (machine->kmaps == NULL)
79 		return -ENOMEM;
80 
81 	RB_CLEAR_NODE(&machine->rb_node);
82 	dsos__init(&machine->dsos);
83 
84 	threads__init(&machine->threads);
85 
86 	machine->vdso_info = NULL;
87 	machine->env = NULL;
88 
89 	machine->pid = pid;
90 
91 	machine->id_hdr_size = 0;
92 	machine->kptr_restrict_warned = false;
93 	machine->comm_exec = false;
94 	machine->kernel_start = 0;
95 	machine->vmlinux_map = NULL;
96 
97 	machine->root_dir = strdup(root_dir);
98 	if (machine->root_dir == NULL)
99 		goto out;
100 
101 	if (machine__set_mmap_name(machine))
102 		goto out;
103 
104 	if (pid != HOST_KERNEL_ID) {
105 		struct thread *thread = machine__findnew_thread(machine, -1,
106 								pid);
107 
108 		if (thread == NULL)
109 			goto out;
110 
111 		thread__set_guest_comm(thread, pid);
112 		thread__put(thread);
113 	}
114 
115 	machine->current_tid = NULL;
116 	err = 0;
117 
118 out:
119 	if (err) {
120 		zfree(&machine->kmaps);
121 		zfree(&machine->root_dir);
122 		zfree(&machine->mmap_name);
123 	}
124 	return 0;
125 }
126 
127 struct machine *machine__new_host(void)
128 {
129 	struct machine *machine = malloc(sizeof(*machine));
130 
131 	if (machine != NULL) {
132 		machine__init(machine, "", HOST_KERNEL_ID);
133 
134 		if (machine__create_kernel_maps(machine) < 0)
135 			goto out_delete;
136 	}
137 
138 	return machine;
139 out_delete:
140 	free(machine);
141 	return NULL;
142 }
143 
144 struct machine *machine__new_kallsyms(void)
145 {
146 	struct machine *machine = machine__new_host();
147 	/*
148 	 * FIXME:
149 	 * 1) We should switch to machine__load_kallsyms(), i.e. not explicitly
150 	 *    ask for not using the kcore parsing code, once this one is fixed
151 	 *    to create a map per module.
152 	 */
153 	if (machine && machine__load_kallsyms(machine, "/proc/kallsyms") <= 0) {
154 		machine__delete(machine);
155 		machine = NULL;
156 	}
157 
158 	return machine;
159 }
160 
161 void machine__delete_threads(struct machine *machine)
162 {
163 	threads__remove_all_threads(&machine->threads);
164 }
165 
166 void machine__exit(struct machine *machine)
167 {
168 	if (machine == NULL)
169 		return;
170 
171 	machine__destroy_kernel_maps(machine);
172 	maps__zput(machine->kmaps);
173 	dsos__exit(&machine->dsos);
174 	machine__exit_vdso(machine);
175 	zfree(&machine->root_dir);
176 	zfree(&machine->mmap_name);
177 	zfree(&machine->current_tid);
178 	zfree(&machine->kallsyms_filename);
179 
180 	threads__exit(&machine->threads);
181 }
182 
183 void machine__delete(struct machine *machine)
184 {
185 	if (machine) {
186 		machine__exit(machine);
187 		free(machine);
188 	}
189 }
190 
191 void machines__init(struct machines *machines)
192 {
193 	machine__init(&machines->host, "", HOST_KERNEL_ID);
194 	machines->guests = RB_ROOT_CACHED;
195 }
196 
197 void machines__exit(struct machines *machines)
198 {
199 	machine__exit(&machines->host);
200 	/* XXX exit guest */
201 }
202 
203 struct machine *machines__add(struct machines *machines, pid_t pid,
204 			      const char *root_dir)
205 {
206 	struct rb_node **p = &machines->guests.rb_root.rb_node;
207 	struct rb_node *parent = NULL;
208 	struct machine *pos, *machine = malloc(sizeof(*machine));
209 	bool leftmost = true;
210 
211 	if (machine == NULL)
212 		return NULL;
213 
214 	if (machine__init(machine, root_dir, pid) != 0) {
215 		free(machine);
216 		return NULL;
217 	}
218 
219 	while (*p != NULL) {
220 		parent = *p;
221 		pos = rb_entry(parent, struct machine, rb_node);
222 		if (pid < pos->pid)
223 			p = &(*p)->rb_left;
224 		else {
225 			p = &(*p)->rb_right;
226 			leftmost = false;
227 		}
228 	}
229 
230 	rb_link_node(&machine->rb_node, parent, p);
231 	rb_insert_color_cached(&machine->rb_node, &machines->guests, leftmost);
232 
233 	machine->machines = machines;
234 
235 	return machine;
236 }
237 
238 void machines__set_comm_exec(struct machines *machines, bool comm_exec)
239 {
240 	struct rb_node *nd;
241 
242 	machines->host.comm_exec = comm_exec;
243 
244 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
245 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
246 
247 		machine->comm_exec = comm_exec;
248 	}
249 }
250 
251 struct machine *machines__find(struct machines *machines, pid_t pid)
252 {
253 	struct rb_node **p = &machines->guests.rb_root.rb_node;
254 	struct rb_node *parent = NULL;
255 	struct machine *machine;
256 	struct machine *default_machine = NULL;
257 
258 	if (pid == HOST_KERNEL_ID)
259 		return &machines->host;
260 
261 	while (*p != NULL) {
262 		parent = *p;
263 		machine = rb_entry(parent, struct machine, rb_node);
264 		if (pid < machine->pid)
265 			p = &(*p)->rb_left;
266 		else if (pid > machine->pid)
267 			p = &(*p)->rb_right;
268 		else
269 			return machine;
270 		if (!machine->pid)
271 			default_machine = machine;
272 	}
273 
274 	return default_machine;
275 }
276 
277 struct machine *machines__findnew(struct machines *machines, pid_t pid)
278 {
279 	char path[PATH_MAX];
280 	const char *root_dir = "";
281 	struct machine *machine = machines__find(machines, pid);
282 
283 	if (machine && (machine->pid == pid))
284 		goto out;
285 
286 	if ((pid != HOST_KERNEL_ID) &&
287 	    (pid != DEFAULT_GUEST_KERNEL_ID) &&
288 	    (symbol_conf.guestmount)) {
289 		sprintf(path, "%s/%d", symbol_conf.guestmount, pid);
290 		if (access(path, R_OK)) {
291 			static struct strlist *seen;
292 
293 			if (!seen)
294 				seen = strlist__new(NULL, NULL);
295 
296 			if (!strlist__has_entry(seen, path)) {
297 				pr_err("Can't access file %s\n", path);
298 				strlist__add(seen, path);
299 			}
300 			machine = NULL;
301 			goto out;
302 		}
303 		root_dir = path;
304 	}
305 
306 	machine = machines__add(machines, pid, root_dir);
307 out:
308 	return machine;
309 }
310 
311 struct machine *machines__find_guest(struct machines *machines, pid_t pid)
312 {
313 	struct machine *machine = machines__find(machines, pid);
314 
315 	if (!machine)
316 		machine = machines__findnew(machines, DEFAULT_GUEST_KERNEL_ID);
317 	return machine;
318 }
319 
320 /*
321  * A common case for KVM test programs is that the test program acts as the
322  * hypervisor, creating, running and destroying the virtual machine, and
323  * providing the guest object code from its own object code. In this case,
324  * the VM is not running an OS, but only the functions loaded into it by the
325  * hypervisor test program, and conveniently, loaded at the same virtual
326  * addresses.
327  *
328  * Normally to resolve addresses, MMAP events are needed to map addresses
329  * back to the object code and debug symbols for that object code.
330  *
331  * Currently, there is no way to get such mapping information from guests
332  * but, in the scenario described above, the guest has the same mappings
333  * as the hypervisor, so support for that scenario can be achieved.
334  *
335  * To support that, copy the host thread's maps to the guest thread's maps.
336  * Note, we do not discover the guest until we encounter a guest event,
337  * which works well because it is not until then that we know that the host
338  * thread's maps have been set up.
339  *
340  * This function returns the guest thread. Apart from keeping the data
341  * structures sane, using a thread belonging to the guest machine, instead
342  * of the host thread, allows it to have its own comm (refer
343  * thread__set_guest_comm()).
344  */
345 static struct thread *findnew_guest_code(struct machine *machine,
346 					 struct machine *host_machine,
347 					 pid_t pid)
348 {
349 	struct thread *host_thread;
350 	struct thread *thread;
351 	int err;
352 
353 	if (!machine)
354 		return NULL;
355 
356 	thread = machine__findnew_thread(machine, -1, pid);
357 	if (!thread)
358 		return NULL;
359 
360 	/* Assume maps are set up if there are any */
361 	if (!maps__empty(thread__maps(thread)))
362 		return thread;
363 
364 	host_thread = machine__find_thread(host_machine, -1, pid);
365 	if (!host_thread)
366 		goto out_err;
367 
368 	thread__set_guest_comm(thread, pid);
369 
370 	/*
371 	 * Guest code can be found in hypervisor process at the same address
372 	 * so copy host maps.
373 	 */
374 	err = maps__copy_from(thread__maps(thread), thread__maps(host_thread));
375 	thread__put(host_thread);
376 	if (err)
377 		goto out_err;
378 
379 	return thread;
380 
381 out_err:
382 	thread__zput(thread);
383 	return NULL;
384 }
385 
386 struct thread *machines__findnew_guest_code(struct machines *machines, pid_t pid)
387 {
388 	struct machine *host_machine = machines__find(machines, HOST_KERNEL_ID);
389 	struct machine *machine = machines__findnew(machines, pid);
390 
391 	return findnew_guest_code(machine, host_machine, pid);
392 }
393 
394 struct thread *machine__findnew_guest_code(struct machine *machine, pid_t pid)
395 {
396 	struct machines *machines = machine->machines;
397 	struct machine *host_machine;
398 
399 	if (!machines)
400 		return NULL;
401 
402 	host_machine = machines__find(machines, HOST_KERNEL_ID);
403 
404 	return findnew_guest_code(machine, host_machine, pid);
405 }
406 
407 void machines__process_guests(struct machines *machines,
408 			      machine__process_t process, void *data)
409 {
410 	struct rb_node *nd;
411 
412 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
413 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
414 		process(pos, data);
415 	}
416 }
417 
418 void machines__set_id_hdr_size(struct machines *machines, u16 id_hdr_size)
419 {
420 	struct rb_node *node;
421 	struct machine *machine;
422 
423 	machines->host.id_hdr_size = id_hdr_size;
424 
425 	for (node = rb_first_cached(&machines->guests); node;
426 	     node = rb_next(node)) {
427 		machine = rb_entry(node, struct machine, rb_node);
428 		machine->id_hdr_size = id_hdr_size;
429 	}
430 
431 	return;
432 }
433 
434 static void machine__update_thread_pid(struct machine *machine,
435 				       struct thread *th, pid_t pid)
436 {
437 	struct thread *leader;
438 
439 	if (pid == thread__pid(th) || pid == -1 || thread__pid(th) != -1)
440 		return;
441 
442 	thread__set_pid(th, pid);
443 
444 	if (thread__pid(th) == thread__tid(th))
445 		return;
446 
447 	leader = machine__findnew_thread(machine, thread__pid(th), thread__pid(th));
448 	if (!leader)
449 		goto out_err;
450 
451 	if (!thread__maps(leader))
452 		thread__set_maps(leader, maps__new(machine));
453 
454 	if (!thread__maps(leader))
455 		goto out_err;
456 
457 	if (thread__maps(th) == thread__maps(leader))
458 		goto out_put;
459 
460 	if (thread__maps(th)) {
461 		/*
462 		 * Maps are created from MMAP events which provide the pid and
463 		 * tid.  Consequently there never should be any maps on a thread
464 		 * with an unknown pid.  Just print an error if there are.
465 		 */
466 		if (!maps__empty(thread__maps(th)))
467 			pr_err("Discarding thread maps for %d:%d\n",
468 				thread__pid(th), thread__tid(th));
469 		maps__put(thread__maps(th));
470 	}
471 
472 	thread__set_maps(th, maps__get(thread__maps(leader)));
473 out_put:
474 	thread__put(leader);
475 	return;
476 out_err:
477 	pr_err("Failed to join map groups for %d:%d\n", thread__pid(th), thread__tid(th));
478 	goto out_put;
479 }
480 
481 /*
482  * Caller must eventually drop thread->refcnt returned with a successful
483  * lookup/new thread inserted.
484  */
485 static struct thread *__machine__findnew_thread(struct machine *machine,
486 						pid_t pid,
487 						pid_t tid,
488 						bool create)
489 {
490 	struct thread *th = threads__find(&machine->threads, tid);
491 	bool created;
492 
493 	if (th) {
494 		machine__update_thread_pid(machine, th, pid);
495 		return th;
496 	}
497 	if (!create)
498 		return NULL;
499 
500 	th = threads__findnew(&machine->threads, pid, tid, &created);
501 	if (created) {
502 		/*
503 		 * We have to initialize maps separately after rb tree is
504 		 * updated.
505 		 *
506 		 * The reason is that we call machine__findnew_thread within
507 		 * thread__init_maps to find the thread leader and that would
508 		 * screwed the rb tree.
509 		 */
510 		if (thread__init_maps(th, machine)) {
511 			pr_err("Thread init failed thread %d\n", pid);
512 			threads__remove(&machine->threads, th);
513 			thread__put(th);
514 			return NULL;
515 		}
516 	} else
517 		machine__update_thread_pid(machine, th, pid);
518 
519 	return th;
520 }
521 
522 struct thread *machine__findnew_thread(struct machine *machine, pid_t pid, pid_t tid)
523 {
524 	return __machine__findnew_thread(machine, pid, tid, /*create=*/true);
525 }
526 
527 struct thread *machine__find_thread(struct machine *machine, pid_t pid,
528 				    pid_t tid)
529 {
530 	return __machine__findnew_thread(machine, pid, tid, /*create=*/false);
531 }
532 
533 /*
534  * Threads are identified by pid and tid, and the idle task has pid == tid == 0.
535  * So here a single thread is created for that, but actually there is a separate
536  * idle task per cpu, so there should be one 'struct thread' per cpu, but there
537  * is only 1. That causes problems for some tools, requiring workarounds. For
538  * example get_idle_thread() in builtin-sched.c, or thread_stack__per_cpu().
539  */
540 struct thread *machine__idle_thread(struct machine *machine)
541 {
542 	struct thread *thread = machine__findnew_thread(machine, 0, 0);
543 
544 	if (!thread || thread__set_comm(thread, "swapper", 0) ||
545 	    thread__set_namespaces(thread, 0, NULL))
546 		pr_err("problem inserting idle task for machine pid %d\n", machine->pid);
547 
548 	return thread;
549 }
550 
551 struct comm *machine__thread_exec_comm(struct machine *machine,
552 				       struct thread *thread)
553 {
554 	if (machine->comm_exec)
555 		return thread__exec_comm(thread);
556 	else
557 		return thread__comm(thread);
558 }
559 
560 int machine__process_comm_event(struct machine *machine, union perf_event *event,
561 				struct perf_sample *sample)
562 {
563 	struct thread *thread = machine__findnew_thread(machine,
564 							event->comm.pid,
565 							event->comm.tid);
566 	bool exec = event->header.misc & PERF_RECORD_MISC_COMM_EXEC;
567 	int err = 0;
568 
569 	if (exec)
570 		machine->comm_exec = true;
571 
572 	if (dump_trace)
573 		perf_event__fprintf_comm(event, stdout);
574 
575 	if (thread == NULL ||
576 	    __thread__set_comm(thread, event->comm.comm, sample->time, exec)) {
577 		dump_printf("problem processing PERF_RECORD_COMM, skipping event.\n");
578 		err = -1;
579 	}
580 
581 	thread__put(thread);
582 
583 	return err;
584 }
585 
586 int machine__process_namespaces_event(struct machine *machine __maybe_unused,
587 				      union perf_event *event,
588 				      struct perf_sample *sample __maybe_unused)
589 {
590 	struct thread *thread = machine__findnew_thread(machine,
591 							event->namespaces.pid,
592 							event->namespaces.tid);
593 	int err = 0;
594 
595 	WARN_ONCE(event->namespaces.nr_namespaces > NR_NAMESPACES,
596 		  "\nWARNING: kernel seems to support more namespaces than perf"
597 		  " tool.\nTry updating the perf tool..\n\n");
598 
599 	WARN_ONCE(event->namespaces.nr_namespaces < NR_NAMESPACES,
600 		  "\nWARNING: perf tool seems to support more namespaces than"
601 		  " the kernel.\nTry updating the kernel..\n\n");
602 
603 	if (dump_trace)
604 		perf_event__fprintf_namespaces(event, stdout);
605 
606 	if (thread == NULL ||
607 	    thread__set_namespaces(thread, sample->time, &event->namespaces)) {
608 		dump_printf("problem processing PERF_RECORD_NAMESPACES, skipping event.\n");
609 		err = -1;
610 	}
611 
612 	thread__put(thread);
613 
614 	return err;
615 }
616 
617 int machine__process_cgroup_event(struct machine *machine,
618 				  union perf_event *event,
619 				  struct perf_sample *sample __maybe_unused)
620 {
621 	struct cgroup *cgrp;
622 
623 	if (dump_trace)
624 		perf_event__fprintf_cgroup(event, stdout);
625 
626 	cgrp = cgroup__findnew(machine->env, event->cgroup.id, event->cgroup.path);
627 	if (cgrp == NULL)
628 		return -ENOMEM;
629 
630 	return 0;
631 }
632 
633 int machine__process_lost_event(struct machine *machine __maybe_unused,
634 				union perf_event *event, struct perf_sample *sample __maybe_unused)
635 {
636 	dump_printf(": id:%" PRI_lu64 ": lost:%" PRI_lu64 "\n",
637 		    event->lost.id, event->lost.lost);
638 	return 0;
639 }
640 
641 int machine__process_lost_samples_event(struct machine *machine __maybe_unused,
642 					union perf_event *event, struct perf_sample *sample)
643 {
644 	dump_printf(": id:%" PRIu64 ": lost samples :%" PRI_lu64 "\n",
645 		    sample->id, event->lost_samples.lost);
646 	return 0;
647 }
648 
649 int machine__process_aux_event(struct machine *machine __maybe_unused,
650 			       union perf_event *event)
651 {
652 	if (dump_trace)
653 		perf_event__fprintf_aux(event, stdout);
654 	return 0;
655 }
656 
657 int machine__process_itrace_start_event(struct machine *machine __maybe_unused,
658 					union perf_event *event)
659 {
660 	if (dump_trace)
661 		perf_event__fprintf_itrace_start(event, stdout);
662 	return 0;
663 }
664 
665 int machine__process_aux_output_hw_id_event(struct machine *machine __maybe_unused,
666 					    union perf_event *event)
667 {
668 	if (dump_trace)
669 		perf_event__fprintf_aux_output_hw_id(event, stdout);
670 	return 0;
671 }
672 
673 int machine__process_switch_event(struct machine *machine __maybe_unused,
674 				  union perf_event *event)
675 {
676 	if (dump_trace)
677 		perf_event__fprintf_switch(event, stdout);
678 	return 0;
679 }
680 
681 static int machine__process_ksymbol_register(struct machine *machine,
682 					     union perf_event *event,
683 					     struct perf_sample *sample __maybe_unused)
684 {
685 	struct symbol *sym;
686 	struct dso *dso;
687 	struct map *map = maps__find(machine__kernel_maps(machine), event->ksymbol.addr);
688 	int err = 0;
689 
690 	if (!map) {
691 		dso = dso__new(event->ksymbol.name);
692 
693 		if (!dso) {
694 			err = -ENOMEM;
695 			goto out;
696 		}
697 		dso->kernel = DSO_SPACE__KERNEL;
698 		map = map__new2(0, dso);
699 		dso__put(dso);
700 		if (!map) {
701 			err = -ENOMEM;
702 			goto out;
703 		}
704 		if (event->ksymbol.ksym_type == PERF_RECORD_KSYMBOL_TYPE_OOL) {
705 			dso->binary_type = DSO_BINARY_TYPE__OOL;
706 			dso->data.file_size = event->ksymbol.len;
707 			dso__set_loaded(dso);
708 		}
709 
710 		map__set_start(map, event->ksymbol.addr);
711 		map__set_end(map, map__start(map) + event->ksymbol.len);
712 		err = maps__insert(machine__kernel_maps(machine), map);
713 		if (err) {
714 			err = -ENOMEM;
715 			goto out;
716 		}
717 
718 		dso__set_loaded(dso);
719 
720 		if (is_bpf_image(event->ksymbol.name)) {
721 			dso->binary_type = DSO_BINARY_TYPE__BPF_IMAGE;
722 			dso__set_long_name(dso, "", false);
723 		}
724 	} else {
725 		dso = map__dso(map);
726 	}
727 
728 	sym = symbol__new(map__map_ip(map, map__start(map)),
729 			  event->ksymbol.len,
730 			  0, 0, event->ksymbol.name);
731 	if (!sym) {
732 		err = -ENOMEM;
733 		goto out;
734 	}
735 	dso__insert_symbol(dso, sym);
736 out:
737 	map__put(map);
738 	return err;
739 }
740 
741 static int machine__process_ksymbol_unregister(struct machine *machine,
742 					       union perf_event *event,
743 					       struct perf_sample *sample __maybe_unused)
744 {
745 	struct symbol *sym;
746 	struct map *map;
747 
748 	map = maps__find(machine__kernel_maps(machine), event->ksymbol.addr);
749 	if (!map)
750 		return 0;
751 
752 	if (!RC_CHK_EQUAL(map, machine->vmlinux_map))
753 		maps__remove(machine__kernel_maps(machine), map);
754 	else {
755 		struct dso *dso = map__dso(map);
756 
757 		sym = dso__find_symbol(dso, map__map_ip(map, map__start(map)));
758 		if (sym)
759 			dso__delete_symbol(dso, sym);
760 	}
761 	map__put(map);
762 	return 0;
763 }
764 
765 int machine__process_ksymbol(struct machine *machine __maybe_unused,
766 			     union perf_event *event,
767 			     struct perf_sample *sample)
768 {
769 	if (dump_trace)
770 		perf_event__fprintf_ksymbol(event, stdout);
771 
772 	if (event->ksymbol.flags & PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER)
773 		return machine__process_ksymbol_unregister(machine, event,
774 							   sample);
775 	return machine__process_ksymbol_register(machine, event, sample);
776 }
777 
778 int machine__process_text_poke(struct machine *machine, union perf_event *event,
779 			       struct perf_sample *sample __maybe_unused)
780 {
781 	struct map *map = maps__find(machine__kernel_maps(machine), event->text_poke.addr);
782 	u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
783 	struct dso *dso = map ? map__dso(map) : NULL;
784 
785 	if (dump_trace)
786 		perf_event__fprintf_text_poke(event, machine, stdout);
787 
788 	if (!event->text_poke.new_len)
789 		goto out;
790 
791 	if (cpumode != PERF_RECORD_MISC_KERNEL) {
792 		pr_debug("%s: unsupported cpumode - ignoring\n", __func__);
793 		goto out;
794 	}
795 
796 	if (dso) {
797 		u8 *new_bytes = event->text_poke.bytes + event->text_poke.old_len;
798 		int ret;
799 
800 		/*
801 		 * Kernel maps might be changed when loading symbols so loading
802 		 * must be done prior to using kernel maps.
803 		 */
804 		map__load(map);
805 		ret = dso__data_write_cache_addr(dso, map, machine,
806 						 event->text_poke.addr,
807 						 new_bytes,
808 						 event->text_poke.new_len);
809 		if (ret != event->text_poke.new_len)
810 			pr_debug("Failed to write kernel text poke at %#" PRI_lx64 "\n",
811 				 event->text_poke.addr);
812 	} else {
813 		pr_debug("Failed to find kernel text poke address map for %#" PRI_lx64 "\n",
814 			 event->text_poke.addr);
815 	}
816 out:
817 	map__put(map);
818 	return 0;
819 }
820 
821 static struct map *machine__addnew_module_map(struct machine *machine, u64 start,
822 					      const char *filename)
823 {
824 	struct map *map = NULL;
825 	struct kmod_path m;
826 	struct dso *dso;
827 	int err;
828 
829 	if (kmod_path__parse_name(&m, filename))
830 		return NULL;
831 
832 	dso = dsos__findnew_module_dso(&machine->dsos, machine, &m, filename);
833 	if (dso == NULL)
834 		goto out;
835 
836 	map = map__new2(start, dso);
837 	if (map == NULL)
838 		goto out;
839 
840 	err = maps__insert(machine__kernel_maps(machine), map);
841 	/* If maps__insert failed, return NULL. */
842 	if (err) {
843 		map__put(map);
844 		map = NULL;
845 	}
846 out:
847 	/* put the dso here, corresponding to  machine__findnew_module_dso */
848 	dso__put(dso);
849 	zfree(&m.name);
850 	return map;
851 }
852 
853 size_t machines__fprintf_dsos(struct machines *machines, FILE *fp)
854 {
855 	struct rb_node *nd;
856 	size_t ret = dsos__fprintf(&machines->host.dsos, fp);
857 
858 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
859 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
860 		ret += dsos__fprintf(&pos->dsos, fp);
861 	}
862 
863 	return ret;
864 }
865 
866 size_t machine__fprintf_dsos_buildid(struct machine *m, FILE *fp,
867 				     bool (skip)(struct dso *dso, int parm), int parm)
868 {
869 	return dsos__fprintf_buildid(&m->dsos, fp, skip, parm);
870 }
871 
872 size_t machines__fprintf_dsos_buildid(struct machines *machines, FILE *fp,
873 				     bool (skip)(struct dso *dso, int parm), int parm)
874 {
875 	struct rb_node *nd;
876 	size_t ret = machine__fprintf_dsos_buildid(&machines->host, fp, skip, parm);
877 
878 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
879 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
880 		ret += machine__fprintf_dsos_buildid(pos, fp, skip, parm);
881 	}
882 	return ret;
883 }
884 
885 size_t machine__fprintf_vmlinux_path(struct machine *machine, FILE *fp)
886 {
887 	int i;
888 	size_t printed = 0;
889 	struct dso *kdso = machine__kernel_dso(machine);
890 
891 	if (kdso->has_build_id) {
892 		char filename[PATH_MAX];
893 		if (dso__build_id_filename(kdso, filename, sizeof(filename),
894 					   false))
895 			printed += fprintf(fp, "[0] %s\n", filename);
896 	}
897 
898 	for (i = 0; i < vmlinux_path__nr_entries; ++i)
899 		printed += fprintf(fp, "[%d] %s\n",
900 				   i + kdso->has_build_id, vmlinux_path[i]);
901 
902 	return printed;
903 }
904 
905 struct machine_fprintf_cb_args {
906 	FILE *fp;
907 	size_t printed;
908 };
909 
910 static int machine_fprintf_cb(struct thread *thread, void *data)
911 {
912 	struct machine_fprintf_cb_args *args = data;
913 
914 	/* TODO: handle fprintf errors. */
915 	args->printed += thread__fprintf(thread, args->fp);
916 	return 0;
917 }
918 
919 size_t machine__fprintf(struct machine *machine, FILE *fp)
920 {
921 	struct machine_fprintf_cb_args args = {
922 		.fp = fp,
923 		.printed = 0,
924 	};
925 	size_t ret = fprintf(fp, "Threads: %zu\n", threads__nr(&machine->threads));
926 
927 	machine__for_each_thread(machine, machine_fprintf_cb, &args);
928 	return ret + args.printed;
929 }
930 
931 static struct dso *machine__get_kernel(struct machine *machine)
932 {
933 	const char *vmlinux_name = machine->mmap_name;
934 	struct dso *kernel;
935 
936 	if (machine__is_host(machine)) {
937 		if (symbol_conf.vmlinux_name)
938 			vmlinux_name = symbol_conf.vmlinux_name;
939 
940 		kernel = machine__findnew_kernel(machine, vmlinux_name,
941 						 "[kernel]", DSO_SPACE__KERNEL);
942 	} else {
943 		if (symbol_conf.default_guest_vmlinux_name)
944 			vmlinux_name = symbol_conf.default_guest_vmlinux_name;
945 
946 		kernel = machine__findnew_kernel(machine, vmlinux_name,
947 						 "[guest.kernel]",
948 						 DSO_SPACE__KERNEL_GUEST);
949 	}
950 
951 	if (kernel != NULL && (!kernel->has_build_id))
952 		dso__read_running_kernel_build_id(kernel, machine);
953 
954 	return kernel;
955 }
956 
957 void machine__get_kallsyms_filename(struct machine *machine, char *buf,
958 				    size_t bufsz)
959 {
960 	if (machine__is_default_guest(machine))
961 		scnprintf(buf, bufsz, "%s", symbol_conf.default_guest_kallsyms);
962 	else
963 		scnprintf(buf, bufsz, "%s/proc/kallsyms", machine->root_dir);
964 }
965 
966 const char *ref_reloc_sym_names[] = {"_text", "_stext", NULL};
967 
968 /* Figure out the start address of kernel map from /proc/kallsyms.
969  * Returns the name of the start symbol in *symbol_name. Pass in NULL as
970  * symbol_name if it's not that important.
971  */
972 static int machine__get_running_kernel_start(struct machine *machine,
973 					     const char **symbol_name,
974 					     u64 *start, u64 *end)
975 {
976 	char filename[PATH_MAX];
977 	int i, err = -1;
978 	const char *name;
979 	u64 addr = 0;
980 
981 	machine__get_kallsyms_filename(machine, filename, PATH_MAX);
982 
983 	if (symbol__restricted_filename(filename, "/proc/kallsyms"))
984 		return 0;
985 
986 	for (i = 0; (name = ref_reloc_sym_names[i]) != NULL; i++) {
987 		err = kallsyms__get_function_start(filename, name, &addr);
988 		if (!err)
989 			break;
990 	}
991 
992 	if (err)
993 		return -1;
994 
995 	if (symbol_name)
996 		*symbol_name = name;
997 
998 	*start = addr;
999 
1000 	err = kallsyms__get_symbol_start(filename, "_edata", &addr);
1001 	if (err)
1002 		err = kallsyms__get_function_start(filename, "_etext", &addr);
1003 	if (!err)
1004 		*end = addr;
1005 
1006 	return 0;
1007 }
1008 
1009 int machine__create_extra_kernel_map(struct machine *machine,
1010 				     struct dso *kernel,
1011 				     struct extra_kernel_map *xm)
1012 {
1013 	struct kmap *kmap;
1014 	struct map *map;
1015 	int err;
1016 
1017 	map = map__new2(xm->start, kernel);
1018 	if (!map)
1019 		return -ENOMEM;
1020 
1021 	map__set_end(map, xm->end);
1022 	map__set_pgoff(map, xm->pgoff);
1023 
1024 	kmap = map__kmap(map);
1025 
1026 	strlcpy(kmap->name, xm->name, KMAP_NAME_LEN);
1027 
1028 	err = maps__insert(machine__kernel_maps(machine), map);
1029 
1030 	if (!err) {
1031 		pr_debug2("Added extra kernel map %s %" PRIx64 "-%" PRIx64 "\n",
1032 			kmap->name, map__start(map), map__end(map));
1033 	}
1034 
1035 	map__put(map);
1036 
1037 	return err;
1038 }
1039 
1040 static u64 find_entry_trampoline(struct dso *dso)
1041 {
1042 	/* Duplicates are removed so lookup all aliases */
1043 	const char *syms[] = {
1044 		"_entry_trampoline",
1045 		"__entry_trampoline_start",
1046 		"entry_SYSCALL_64_trampoline",
1047 	};
1048 	struct symbol *sym = dso__first_symbol(dso);
1049 	unsigned int i;
1050 
1051 	for (; sym; sym = dso__next_symbol(sym)) {
1052 		if (sym->binding != STB_GLOBAL)
1053 			continue;
1054 		for (i = 0; i < ARRAY_SIZE(syms); i++) {
1055 			if (!strcmp(sym->name, syms[i]))
1056 				return sym->start;
1057 		}
1058 	}
1059 
1060 	return 0;
1061 }
1062 
1063 /*
1064  * These values can be used for kernels that do not have symbols for the entry
1065  * trampolines in kallsyms.
1066  */
1067 #define X86_64_CPU_ENTRY_AREA_PER_CPU	0xfffffe0000000000ULL
1068 #define X86_64_CPU_ENTRY_AREA_SIZE	0x2c000
1069 #define X86_64_ENTRY_TRAMPOLINE		0x6000
1070 
1071 struct machine__map_x86_64_entry_trampolines_args {
1072 	struct maps *kmaps;
1073 	bool found;
1074 };
1075 
1076 static int machine__map_x86_64_entry_trampolines_cb(struct map *map, void *data)
1077 {
1078 	struct machine__map_x86_64_entry_trampolines_args *args = data;
1079 	struct map *dest_map;
1080 	struct kmap *kmap = __map__kmap(map);
1081 
1082 	if (!kmap || !is_entry_trampoline(kmap->name))
1083 		return 0;
1084 
1085 	dest_map = maps__find(args->kmaps, map__pgoff(map));
1086 	if (RC_CHK_ACCESS(dest_map) != RC_CHK_ACCESS(map))
1087 		map__set_pgoff(map, map__map_ip(dest_map, map__pgoff(map)));
1088 
1089 	map__put(dest_map);
1090 	args->found = true;
1091 	return 0;
1092 }
1093 
1094 /* Map x86_64 PTI entry trampolines */
1095 int machine__map_x86_64_entry_trampolines(struct machine *machine,
1096 					  struct dso *kernel)
1097 {
1098 	struct machine__map_x86_64_entry_trampolines_args args = {
1099 		.kmaps = machine__kernel_maps(machine),
1100 		.found = false,
1101 	};
1102 	int nr_cpus_avail, cpu;
1103 	u64 pgoff;
1104 
1105 	/*
1106 	 * In the vmlinux case, pgoff is a virtual address which must now be
1107 	 * mapped to a vmlinux offset.
1108 	 */
1109 	maps__for_each_map(args.kmaps, machine__map_x86_64_entry_trampolines_cb, &args);
1110 
1111 	if (args.found || machine->trampolines_mapped)
1112 		return 0;
1113 
1114 	pgoff = find_entry_trampoline(kernel);
1115 	if (!pgoff)
1116 		return 0;
1117 
1118 	nr_cpus_avail = machine__nr_cpus_avail(machine);
1119 
1120 	/* Add a 1 page map for each CPU's entry trampoline */
1121 	for (cpu = 0; cpu < nr_cpus_avail; cpu++) {
1122 		u64 va = X86_64_CPU_ENTRY_AREA_PER_CPU +
1123 			 cpu * X86_64_CPU_ENTRY_AREA_SIZE +
1124 			 X86_64_ENTRY_TRAMPOLINE;
1125 		struct extra_kernel_map xm = {
1126 			.start = va,
1127 			.end   = va + page_size,
1128 			.pgoff = pgoff,
1129 		};
1130 
1131 		strlcpy(xm.name, ENTRY_TRAMPOLINE_NAME, KMAP_NAME_LEN);
1132 
1133 		if (machine__create_extra_kernel_map(machine, kernel, &xm) < 0)
1134 			return -1;
1135 	}
1136 
1137 	machine->trampolines_mapped = nr_cpus_avail;
1138 
1139 	return 0;
1140 }
1141 
1142 int __weak machine__create_extra_kernel_maps(struct machine *machine __maybe_unused,
1143 					     struct dso *kernel __maybe_unused)
1144 {
1145 	return 0;
1146 }
1147 
1148 static int
1149 __machine__create_kernel_maps(struct machine *machine, struct dso *kernel)
1150 {
1151 	/* In case of renewal the kernel map, destroy previous one */
1152 	machine__destroy_kernel_maps(machine);
1153 
1154 	map__put(machine->vmlinux_map);
1155 	machine->vmlinux_map = map__new2(0, kernel);
1156 	if (machine->vmlinux_map == NULL)
1157 		return -ENOMEM;
1158 
1159 	map__set_mapping_type(machine->vmlinux_map, MAPPING_TYPE__IDENTITY);
1160 	return maps__insert(machine__kernel_maps(machine), machine->vmlinux_map);
1161 }
1162 
1163 void machine__destroy_kernel_maps(struct machine *machine)
1164 {
1165 	struct kmap *kmap;
1166 	struct map *map = machine__kernel_map(machine);
1167 
1168 	if (map == NULL)
1169 		return;
1170 
1171 	kmap = map__kmap(map);
1172 	maps__remove(machine__kernel_maps(machine), map);
1173 	if (kmap && kmap->ref_reloc_sym) {
1174 		zfree((char **)&kmap->ref_reloc_sym->name);
1175 		zfree(&kmap->ref_reloc_sym);
1176 	}
1177 
1178 	map__zput(machine->vmlinux_map);
1179 }
1180 
1181 int machines__create_guest_kernel_maps(struct machines *machines)
1182 {
1183 	int ret = 0;
1184 	struct dirent **namelist = NULL;
1185 	int i, items = 0;
1186 	char path[PATH_MAX];
1187 	pid_t pid;
1188 	char *endp;
1189 
1190 	if (symbol_conf.default_guest_vmlinux_name ||
1191 	    symbol_conf.default_guest_modules ||
1192 	    symbol_conf.default_guest_kallsyms) {
1193 		machines__create_kernel_maps(machines, DEFAULT_GUEST_KERNEL_ID);
1194 	}
1195 
1196 	if (symbol_conf.guestmount) {
1197 		items = scandir(symbol_conf.guestmount, &namelist, NULL, NULL);
1198 		if (items <= 0)
1199 			return -ENOENT;
1200 		for (i = 0; i < items; i++) {
1201 			if (!isdigit(namelist[i]->d_name[0])) {
1202 				/* Filter out . and .. */
1203 				continue;
1204 			}
1205 			pid = (pid_t)strtol(namelist[i]->d_name, &endp, 10);
1206 			if ((*endp != '\0') ||
1207 			    (endp == namelist[i]->d_name) ||
1208 			    (errno == ERANGE)) {
1209 				pr_debug("invalid directory (%s). Skipping.\n",
1210 					 namelist[i]->d_name);
1211 				continue;
1212 			}
1213 			sprintf(path, "%s/%s/proc/kallsyms",
1214 				symbol_conf.guestmount,
1215 				namelist[i]->d_name);
1216 			ret = access(path, R_OK);
1217 			if (ret) {
1218 				pr_debug("Can't access file %s\n", path);
1219 				goto failure;
1220 			}
1221 			machines__create_kernel_maps(machines, pid);
1222 		}
1223 failure:
1224 		free(namelist);
1225 	}
1226 
1227 	return ret;
1228 }
1229 
1230 void machines__destroy_kernel_maps(struct machines *machines)
1231 {
1232 	struct rb_node *next = rb_first_cached(&machines->guests);
1233 
1234 	machine__destroy_kernel_maps(&machines->host);
1235 
1236 	while (next) {
1237 		struct machine *pos = rb_entry(next, struct machine, rb_node);
1238 
1239 		next = rb_next(&pos->rb_node);
1240 		rb_erase_cached(&pos->rb_node, &machines->guests);
1241 		machine__delete(pos);
1242 	}
1243 }
1244 
1245 int machines__create_kernel_maps(struct machines *machines, pid_t pid)
1246 {
1247 	struct machine *machine = machines__findnew(machines, pid);
1248 
1249 	if (machine == NULL)
1250 		return -1;
1251 
1252 	return machine__create_kernel_maps(machine);
1253 }
1254 
1255 int machine__load_kallsyms(struct machine *machine, const char *filename)
1256 {
1257 	struct map *map = machine__kernel_map(machine);
1258 	struct dso *dso = map__dso(map);
1259 	int ret = __dso__load_kallsyms(dso, filename, map, true);
1260 
1261 	if (ret > 0) {
1262 		dso__set_loaded(dso);
1263 		/*
1264 		 * Since /proc/kallsyms will have multiple sessions for the
1265 		 * kernel, with modules between them, fixup the end of all
1266 		 * sections.
1267 		 */
1268 		maps__fixup_end(machine__kernel_maps(machine));
1269 	}
1270 
1271 	return ret;
1272 }
1273 
1274 int machine__load_vmlinux_path(struct machine *machine)
1275 {
1276 	struct map *map = machine__kernel_map(machine);
1277 	struct dso *dso = map__dso(map);
1278 	int ret = dso__load_vmlinux_path(dso, map);
1279 
1280 	if (ret > 0)
1281 		dso__set_loaded(dso);
1282 
1283 	return ret;
1284 }
1285 
1286 static char *get_kernel_version(const char *root_dir)
1287 {
1288 	char version[PATH_MAX];
1289 	FILE *file;
1290 	char *name, *tmp;
1291 	const char *prefix = "Linux version ";
1292 
1293 	sprintf(version, "%s/proc/version", root_dir);
1294 	file = fopen(version, "r");
1295 	if (!file)
1296 		return NULL;
1297 
1298 	tmp = fgets(version, sizeof(version), file);
1299 	fclose(file);
1300 	if (!tmp)
1301 		return NULL;
1302 
1303 	name = strstr(version, prefix);
1304 	if (!name)
1305 		return NULL;
1306 	name += strlen(prefix);
1307 	tmp = strchr(name, ' ');
1308 	if (tmp)
1309 		*tmp = '\0';
1310 
1311 	return strdup(name);
1312 }
1313 
1314 static bool is_kmod_dso(struct dso *dso)
1315 {
1316 	return dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE ||
1317 	       dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE;
1318 }
1319 
1320 static int maps__set_module_path(struct maps *maps, const char *path, struct kmod_path *m)
1321 {
1322 	char *long_name;
1323 	struct dso *dso;
1324 	struct map *map = maps__find_by_name(maps, m->name);
1325 
1326 	if (map == NULL)
1327 		return 0;
1328 
1329 	long_name = strdup(path);
1330 	if (long_name == NULL) {
1331 		map__put(map);
1332 		return -ENOMEM;
1333 	}
1334 
1335 	dso = map__dso(map);
1336 	dso__set_long_name(dso, long_name, true);
1337 	dso__kernel_module_get_build_id(dso, "");
1338 
1339 	/*
1340 	 * Full name could reveal us kmod compression, so
1341 	 * we need to update the symtab_type if needed.
1342 	 */
1343 	if (m->comp && is_kmod_dso(dso)) {
1344 		dso->symtab_type++;
1345 		dso->comp = m->comp;
1346 	}
1347 	map__put(map);
1348 	return 0;
1349 }
1350 
1351 static int maps__set_modules_path_dir(struct maps *maps, const char *dir_name, int depth)
1352 {
1353 	struct dirent *dent;
1354 	DIR *dir = opendir(dir_name);
1355 	int ret = 0;
1356 
1357 	if (!dir) {
1358 		pr_debug("%s: cannot open %s dir\n", __func__, dir_name);
1359 		return -1;
1360 	}
1361 
1362 	while ((dent = readdir(dir)) != NULL) {
1363 		char path[PATH_MAX];
1364 		struct stat st;
1365 
1366 		/*sshfs might return bad dent->d_type, so we have to stat*/
1367 		path__join(path, sizeof(path), dir_name, dent->d_name);
1368 		if (stat(path, &st))
1369 			continue;
1370 
1371 		if (S_ISDIR(st.st_mode)) {
1372 			if (!strcmp(dent->d_name, ".") ||
1373 			    !strcmp(dent->d_name, ".."))
1374 				continue;
1375 
1376 			/* Do not follow top-level source and build symlinks */
1377 			if (depth == 0) {
1378 				if (!strcmp(dent->d_name, "source") ||
1379 				    !strcmp(dent->d_name, "build"))
1380 					continue;
1381 			}
1382 
1383 			ret = maps__set_modules_path_dir(maps, path, depth + 1);
1384 			if (ret < 0)
1385 				goto out;
1386 		} else {
1387 			struct kmod_path m;
1388 
1389 			ret = kmod_path__parse_name(&m, dent->d_name);
1390 			if (ret)
1391 				goto out;
1392 
1393 			if (m.kmod)
1394 				ret = maps__set_module_path(maps, path, &m);
1395 
1396 			zfree(&m.name);
1397 
1398 			if (ret)
1399 				goto out;
1400 		}
1401 	}
1402 
1403 out:
1404 	closedir(dir);
1405 	return ret;
1406 }
1407 
1408 static int machine__set_modules_path(struct machine *machine)
1409 {
1410 	char *version;
1411 	char modules_path[PATH_MAX];
1412 
1413 	version = get_kernel_version(machine->root_dir);
1414 	if (!version)
1415 		return -1;
1416 
1417 	snprintf(modules_path, sizeof(modules_path), "%s/lib/modules/%s",
1418 		 machine->root_dir, version);
1419 	free(version);
1420 
1421 	return maps__set_modules_path_dir(machine__kernel_maps(machine), modules_path, 0);
1422 }
1423 int __weak arch__fix_module_text_start(u64 *start __maybe_unused,
1424 				u64 *size __maybe_unused,
1425 				const char *name __maybe_unused)
1426 {
1427 	return 0;
1428 }
1429 
1430 static int machine__create_module(void *arg, const char *name, u64 start,
1431 				  u64 size)
1432 {
1433 	struct machine *machine = arg;
1434 	struct map *map;
1435 
1436 	if (arch__fix_module_text_start(&start, &size, name) < 0)
1437 		return -1;
1438 
1439 	map = machine__addnew_module_map(machine, start, name);
1440 	if (map == NULL)
1441 		return -1;
1442 	map__set_end(map, start + size);
1443 
1444 	dso__kernel_module_get_build_id(map__dso(map), machine->root_dir);
1445 	map__put(map);
1446 	return 0;
1447 }
1448 
1449 static int machine__create_modules(struct machine *machine)
1450 {
1451 	const char *modules;
1452 	char path[PATH_MAX];
1453 
1454 	if (machine__is_default_guest(machine)) {
1455 		modules = symbol_conf.default_guest_modules;
1456 	} else {
1457 		snprintf(path, PATH_MAX, "%s/proc/modules", machine->root_dir);
1458 		modules = path;
1459 	}
1460 
1461 	if (symbol__restricted_filename(modules, "/proc/modules"))
1462 		return -1;
1463 
1464 	if (modules__parse(modules, machine, machine__create_module))
1465 		return -1;
1466 
1467 	if (!machine__set_modules_path(machine))
1468 		return 0;
1469 
1470 	pr_debug("Problems setting modules path maps, continuing anyway...\n");
1471 
1472 	return 0;
1473 }
1474 
1475 static void machine__set_kernel_mmap(struct machine *machine,
1476 				     u64 start, u64 end)
1477 {
1478 	map__set_start(machine->vmlinux_map, start);
1479 	map__set_end(machine->vmlinux_map, end);
1480 	/*
1481 	 * Be a bit paranoid here, some perf.data file came with
1482 	 * a zero sized synthesized MMAP event for the kernel.
1483 	 */
1484 	if (start == 0 && end == 0)
1485 		map__set_end(machine->vmlinux_map, ~0ULL);
1486 }
1487 
1488 static int machine__update_kernel_mmap(struct machine *machine,
1489 				     u64 start, u64 end)
1490 {
1491 	struct map *orig, *updated;
1492 	int err;
1493 
1494 	orig = machine->vmlinux_map;
1495 	updated = map__get(orig);
1496 
1497 	machine->vmlinux_map = updated;
1498 	maps__remove(machine__kernel_maps(machine), orig);
1499 	machine__set_kernel_mmap(machine, start, end);
1500 	err = maps__insert(machine__kernel_maps(machine), updated);
1501 	map__put(orig);
1502 
1503 	return err;
1504 }
1505 
1506 int machine__create_kernel_maps(struct machine *machine)
1507 {
1508 	struct dso *kernel = machine__get_kernel(machine);
1509 	const char *name = NULL;
1510 	u64 start = 0, end = ~0ULL;
1511 	int ret;
1512 
1513 	if (kernel == NULL)
1514 		return -1;
1515 
1516 	ret = __machine__create_kernel_maps(machine, kernel);
1517 	if (ret < 0)
1518 		goto out_put;
1519 
1520 	if (symbol_conf.use_modules && machine__create_modules(machine) < 0) {
1521 		if (machine__is_host(machine))
1522 			pr_debug("Problems creating module maps, "
1523 				 "continuing anyway...\n");
1524 		else
1525 			pr_debug("Problems creating module maps for guest %d, "
1526 				 "continuing anyway...\n", machine->pid);
1527 	}
1528 
1529 	if (!machine__get_running_kernel_start(machine, &name, &start, &end)) {
1530 		if (name &&
1531 		    map__set_kallsyms_ref_reloc_sym(machine->vmlinux_map, name, start)) {
1532 			machine__destroy_kernel_maps(machine);
1533 			ret = -1;
1534 			goto out_put;
1535 		}
1536 
1537 		/*
1538 		 * we have a real start address now, so re-order the kmaps
1539 		 * assume it's the last in the kmaps
1540 		 */
1541 		ret = machine__update_kernel_mmap(machine, start, end);
1542 		if (ret < 0)
1543 			goto out_put;
1544 	}
1545 
1546 	if (machine__create_extra_kernel_maps(machine, kernel))
1547 		pr_debug("Problems creating extra kernel maps, continuing anyway...\n");
1548 
1549 	if (end == ~0ULL) {
1550 		/* update end address of the kernel map using adjacent module address */
1551 		struct map *next = maps__find_next_entry(machine__kernel_maps(machine),
1552 							 machine__kernel_map(machine));
1553 
1554 		if (next) {
1555 			machine__set_kernel_mmap(machine, start, map__start(next));
1556 			map__put(next);
1557 		}
1558 	}
1559 
1560 out_put:
1561 	dso__put(kernel);
1562 	return ret;
1563 }
1564 
1565 static int machine__uses_kcore_cb(struct dso *dso, void *data __maybe_unused)
1566 {
1567 	return dso__is_kcore(dso) ? 1 : 0;
1568 }
1569 
1570 static bool machine__uses_kcore(struct machine *machine)
1571 {
1572 	return dsos__for_each_dso(&machine->dsos, machine__uses_kcore_cb, NULL) != 0 ? true : false;
1573 }
1574 
1575 static bool perf_event__is_extra_kernel_mmap(struct machine *machine,
1576 					     struct extra_kernel_map *xm)
1577 {
1578 	return machine__is(machine, "x86_64") &&
1579 	       is_entry_trampoline(xm->name);
1580 }
1581 
1582 static int machine__process_extra_kernel_map(struct machine *machine,
1583 					     struct extra_kernel_map *xm)
1584 {
1585 	struct dso *kernel = machine__kernel_dso(machine);
1586 
1587 	if (kernel == NULL)
1588 		return -1;
1589 
1590 	return machine__create_extra_kernel_map(machine, kernel, xm);
1591 }
1592 
1593 static int machine__process_kernel_mmap_event(struct machine *machine,
1594 					      struct extra_kernel_map *xm,
1595 					      struct build_id *bid)
1596 {
1597 	enum dso_space_type dso_space;
1598 	bool is_kernel_mmap;
1599 	const char *mmap_name = machine->mmap_name;
1600 
1601 	/* If we have maps from kcore then we do not need or want any others */
1602 	if (machine__uses_kcore(machine))
1603 		return 0;
1604 
1605 	if (machine__is_host(machine))
1606 		dso_space = DSO_SPACE__KERNEL;
1607 	else
1608 		dso_space = DSO_SPACE__KERNEL_GUEST;
1609 
1610 	is_kernel_mmap = memcmp(xm->name, mmap_name, strlen(mmap_name) - 1) == 0;
1611 	if (!is_kernel_mmap && !machine__is_host(machine)) {
1612 		/*
1613 		 * If the event was recorded inside the guest and injected into
1614 		 * the host perf.data file, then it will match a host mmap_name,
1615 		 * so try that - see machine__set_mmap_name().
1616 		 */
1617 		mmap_name = "[kernel.kallsyms]";
1618 		is_kernel_mmap = memcmp(xm->name, mmap_name, strlen(mmap_name) - 1) == 0;
1619 	}
1620 	if (xm->name[0] == '/' ||
1621 	    (!is_kernel_mmap && xm->name[0] == '[')) {
1622 		struct map *map = machine__addnew_module_map(machine, xm->start, xm->name);
1623 
1624 		if (map == NULL)
1625 			goto out_problem;
1626 
1627 		map__set_end(map, map__start(map) + xm->end - xm->start);
1628 
1629 		if (build_id__is_defined(bid))
1630 			dso__set_build_id(map__dso(map), bid);
1631 
1632 		map__put(map);
1633 	} else if (is_kernel_mmap) {
1634 		const char *symbol_name = xm->name + strlen(mmap_name);
1635 		/*
1636 		 * Should be there already, from the build-id table in
1637 		 * the header.
1638 		 */
1639 		struct dso *kernel = dsos__find_kernel_dso(&machine->dsos);
1640 
1641 		if (kernel == NULL)
1642 			kernel = machine__findnew_dso(machine, machine->mmap_name);
1643 		if (kernel == NULL)
1644 			goto out_problem;
1645 
1646 		kernel->kernel = dso_space;
1647 		if (__machine__create_kernel_maps(machine, kernel) < 0) {
1648 			dso__put(kernel);
1649 			goto out_problem;
1650 		}
1651 
1652 		if (strstr(kernel->long_name, "vmlinux"))
1653 			dso__set_short_name(kernel, "[kernel.vmlinux]", false);
1654 
1655 		if (machine__update_kernel_mmap(machine, xm->start, xm->end) < 0) {
1656 			dso__put(kernel);
1657 			goto out_problem;
1658 		}
1659 
1660 		if (build_id__is_defined(bid))
1661 			dso__set_build_id(kernel, bid);
1662 
1663 		/*
1664 		 * Avoid using a zero address (kptr_restrict) for the ref reloc
1665 		 * symbol. Effectively having zero here means that at record
1666 		 * time /proc/sys/kernel/kptr_restrict was non zero.
1667 		 */
1668 		if (xm->pgoff != 0) {
1669 			map__set_kallsyms_ref_reloc_sym(machine->vmlinux_map,
1670 							symbol_name,
1671 							xm->pgoff);
1672 		}
1673 
1674 		if (machine__is_default_guest(machine)) {
1675 			/*
1676 			 * preload dso of guest kernel and modules
1677 			 */
1678 			dso__load(kernel, machine__kernel_map(machine));
1679 		}
1680 		dso__put(kernel);
1681 	} else if (perf_event__is_extra_kernel_mmap(machine, xm)) {
1682 		return machine__process_extra_kernel_map(machine, xm);
1683 	}
1684 	return 0;
1685 out_problem:
1686 	return -1;
1687 }
1688 
1689 int machine__process_mmap2_event(struct machine *machine,
1690 				 union perf_event *event,
1691 				 struct perf_sample *sample)
1692 {
1693 	struct thread *thread;
1694 	struct map *map;
1695 	struct dso_id dso_id = {
1696 		.maj = event->mmap2.maj,
1697 		.min = event->mmap2.min,
1698 		.ino = event->mmap2.ino,
1699 		.ino_generation = event->mmap2.ino_generation,
1700 	};
1701 	struct build_id __bid, *bid = NULL;
1702 	int ret = 0;
1703 
1704 	if (dump_trace)
1705 		perf_event__fprintf_mmap2(event, stdout);
1706 
1707 	if (event->header.misc & PERF_RECORD_MISC_MMAP_BUILD_ID) {
1708 		bid = &__bid;
1709 		build_id__init(bid, event->mmap2.build_id, event->mmap2.build_id_size);
1710 	}
1711 
1712 	if (sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1713 	    sample->cpumode == PERF_RECORD_MISC_KERNEL) {
1714 		struct extra_kernel_map xm = {
1715 			.start = event->mmap2.start,
1716 			.end   = event->mmap2.start + event->mmap2.len,
1717 			.pgoff = event->mmap2.pgoff,
1718 		};
1719 
1720 		strlcpy(xm.name, event->mmap2.filename, KMAP_NAME_LEN);
1721 		ret = machine__process_kernel_mmap_event(machine, &xm, bid);
1722 		if (ret < 0)
1723 			goto out_problem;
1724 		return 0;
1725 	}
1726 
1727 	thread = machine__findnew_thread(machine, event->mmap2.pid,
1728 					event->mmap2.tid);
1729 	if (thread == NULL)
1730 		goto out_problem;
1731 
1732 	map = map__new(machine, event->mmap2.start,
1733 			event->mmap2.len, event->mmap2.pgoff,
1734 			&dso_id, event->mmap2.prot,
1735 			event->mmap2.flags, bid,
1736 			event->mmap2.filename, thread);
1737 
1738 	if (map == NULL)
1739 		goto out_problem_map;
1740 
1741 	ret = thread__insert_map(thread, map);
1742 	if (ret)
1743 		goto out_problem_insert;
1744 
1745 	thread__put(thread);
1746 	map__put(map);
1747 	return 0;
1748 
1749 out_problem_insert:
1750 	map__put(map);
1751 out_problem_map:
1752 	thread__put(thread);
1753 out_problem:
1754 	dump_printf("problem processing PERF_RECORD_MMAP2, skipping event.\n");
1755 	return 0;
1756 }
1757 
1758 int machine__process_mmap_event(struct machine *machine, union perf_event *event,
1759 				struct perf_sample *sample)
1760 {
1761 	struct thread *thread;
1762 	struct map *map;
1763 	u32 prot = 0;
1764 	int ret = 0;
1765 
1766 	if (dump_trace)
1767 		perf_event__fprintf_mmap(event, stdout);
1768 
1769 	if (sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1770 	    sample->cpumode == PERF_RECORD_MISC_KERNEL) {
1771 		struct extra_kernel_map xm = {
1772 			.start = event->mmap.start,
1773 			.end   = event->mmap.start + event->mmap.len,
1774 			.pgoff = event->mmap.pgoff,
1775 		};
1776 
1777 		strlcpy(xm.name, event->mmap.filename, KMAP_NAME_LEN);
1778 		ret = machine__process_kernel_mmap_event(machine, &xm, NULL);
1779 		if (ret < 0)
1780 			goto out_problem;
1781 		return 0;
1782 	}
1783 
1784 	thread = machine__findnew_thread(machine, event->mmap.pid,
1785 					 event->mmap.tid);
1786 	if (thread == NULL)
1787 		goto out_problem;
1788 
1789 	if (!(event->header.misc & PERF_RECORD_MISC_MMAP_DATA))
1790 		prot = PROT_EXEC;
1791 
1792 	map = map__new(machine, event->mmap.start,
1793 			event->mmap.len, event->mmap.pgoff,
1794 			NULL, prot, 0, NULL, event->mmap.filename, thread);
1795 
1796 	if (map == NULL)
1797 		goto out_problem_map;
1798 
1799 	ret = thread__insert_map(thread, map);
1800 	if (ret)
1801 		goto out_problem_insert;
1802 
1803 	thread__put(thread);
1804 	map__put(map);
1805 	return 0;
1806 
1807 out_problem_insert:
1808 	map__put(map);
1809 out_problem_map:
1810 	thread__put(thread);
1811 out_problem:
1812 	dump_printf("problem processing PERF_RECORD_MMAP, skipping event.\n");
1813 	return 0;
1814 }
1815 
1816 void machine__remove_thread(struct machine *machine, struct thread *th)
1817 {
1818 	return threads__remove(&machine->threads, th);
1819 }
1820 
1821 int machine__process_fork_event(struct machine *machine, union perf_event *event,
1822 				struct perf_sample *sample)
1823 {
1824 	struct thread *thread = machine__find_thread(machine,
1825 						     event->fork.pid,
1826 						     event->fork.tid);
1827 	struct thread *parent = machine__findnew_thread(machine,
1828 							event->fork.ppid,
1829 							event->fork.ptid);
1830 	bool do_maps_clone = true;
1831 	int err = 0;
1832 
1833 	if (dump_trace)
1834 		perf_event__fprintf_task(event, stdout);
1835 
1836 	/*
1837 	 * There may be an existing thread that is not actually the parent,
1838 	 * either because we are processing events out of order, or because the
1839 	 * (fork) event that would have removed the thread was lost. Assume the
1840 	 * latter case and continue on as best we can.
1841 	 */
1842 	if (thread__pid(parent) != (pid_t)event->fork.ppid) {
1843 		dump_printf("removing erroneous parent thread %d/%d\n",
1844 			    thread__pid(parent), thread__tid(parent));
1845 		machine__remove_thread(machine, parent);
1846 		thread__put(parent);
1847 		parent = machine__findnew_thread(machine, event->fork.ppid,
1848 						 event->fork.ptid);
1849 	}
1850 
1851 	/* if a thread currently exists for the thread id remove it */
1852 	if (thread != NULL) {
1853 		machine__remove_thread(machine, thread);
1854 		thread__put(thread);
1855 	}
1856 
1857 	thread = machine__findnew_thread(machine, event->fork.pid,
1858 					 event->fork.tid);
1859 	/*
1860 	 * When synthesizing FORK events, we are trying to create thread
1861 	 * objects for the already running tasks on the machine.
1862 	 *
1863 	 * Normally, for a kernel FORK event, we want to clone the parent's
1864 	 * maps because that is what the kernel just did.
1865 	 *
1866 	 * But when synthesizing, this should not be done.  If we do, we end up
1867 	 * with overlapping maps as we process the synthesized MMAP2 events that
1868 	 * get delivered shortly thereafter.
1869 	 *
1870 	 * Use the FORK event misc flags in an internal way to signal this
1871 	 * situation, so we can elide the map clone when appropriate.
1872 	 */
1873 	if (event->fork.header.misc & PERF_RECORD_MISC_FORK_EXEC)
1874 		do_maps_clone = false;
1875 
1876 	if (thread == NULL || parent == NULL ||
1877 	    thread__fork(thread, parent, sample->time, do_maps_clone) < 0) {
1878 		dump_printf("problem processing PERF_RECORD_FORK, skipping event.\n");
1879 		err = -1;
1880 	}
1881 	thread__put(thread);
1882 	thread__put(parent);
1883 
1884 	return err;
1885 }
1886 
1887 int machine__process_exit_event(struct machine *machine, union perf_event *event,
1888 				struct perf_sample *sample __maybe_unused)
1889 {
1890 	struct thread *thread = machine__find_thread(machine,
1891 						     event->fork.pid,
1892 						     event->fork.tid);
1893 
1894 	if (dump_trace)
1895 		perf_event__fprintf_task(event, stdout);
1896 
1897 	if (thread != NULL) {
1898 		if (symbol_conf.keep_exited_threads)
1899 			thread__set_exited(thread, /*exited=*/true);
1900 		else
1901 			machine__remove_thread(machine, thread);
1902 	}
1903 	thread__put(thread);
1904 	return 0;
1905 }
1906 
1907 int machine__process_event(struct machine *machine, union perf_event *event,
1908 			   struct perf_sample *sample)
1909 {
1910 	int ret;
1911 
1912 	switch (event->header.type) {
1913 	case PERF_RECORD_COMM:
1914 		ret = machine__process_comm_event(machine, event, sample); break;
1915 	case PERF_RECORD_MMAP:
1916 		ret = machine__process_mmap_event(machine, event, sample); break;
1917 	case PERF_RECORD_NAMESPACES:
1918 		ret = machine__process_namespaces_event(machine, event, sample); break;
1919 	case PERF_RECORD_CGROUP:
1920 		ret = machine__process_cgroup_event(machine, event, sample); break;
1921 	case PERF_RECORD_MMAP2:
1922 		ret = machine__process_mmap2_event(machine, event, sample); break;
1923 	case PERF_RECORD_FORK:
1924 		ret = machine__process_fork_event(machine, event, sample); break;
1925 	case PERF_RECORD_EXIT:
1926 		ret = machine__process_exit_event(machine, event, sample); break;
1927 	case PERF_RECORD_LOST:
1928 		ret = machine__process_lost_event(machine, event, sample); break;
1929 	case PERF_RECORD_AUX:
1930 		ret = machine__process_aux_event(machine, event); break;
1931 	case PERF_RECORD_ITRACE_START:
1932 		ret = machine__process_itrace_start_event(machine, event); break;
1933 	case PERF_RECORD_LOST_SAMPLES:
1934 		ret = machine__process_lost_samples_event(machine, event, sample); break;
1935 	case PERF_RECORD_SWITCH:
1936 	case PERF_RECORD_SWITCH_CPU_WIDE:
1937 		ret = machine__process_switch_event(machine, event); break;
1938 	case PERF_RECORD_KSYMBOL:
1939 		ret = machine__process_ksymbol(machine, event, sample); break;
1940 	case PERF_RECORD_BPF_EVENT:
1941 		ret = machine__process_bpf(machine, event, sample); break;
1942 	case PERF_RECORD_TEXT_POKE:
1943 		ret = machine__process_text_poke(machine, event, sample); break;
1944 	case PERF_RECORD_AUX_OUTPUT_HW_ID:
1945 		ret = machine__process_aux_output_hw_id_event(machine, event); break;
1946 	default:
1947 		ret = -1;
1948 		break;
1949 	}
1950 
1951 	return ret;
1952 }
1953 
1954 static bool symbol__match_regex(struct symbol *sym, regex_t *regex)
1955 {
1956 	return regexec(regex, sym->name, 0, NULL, 0) == 0;
1957 }
1958 
1959 static void ip__resolve_ams(struct thread *thread,
1960 			    struct addr_map_symbol *ams,
1961 			    u64 ip)
1962 {
1963 	struct addr_location al;
1964 
1965 	addr_location__init(&al);
1966 	/*
1967 	 * We cannot use the header.misc hint to determine whether a
1968 	 * branch stack address is user, kernel, guest, hypervisor.
1969 	 * Branches may straddle the kernel/user/hypervisor boundaries.
1970 	 * Thus, we have to try consecutively until we find a match
1971 	 * or else, the symbol is unknown
1972 	 */
1973 	thread__find_cpumode_addr_location(thread, ip, &al);
1974 
1975 	ams->addr = ip;
1976 	ams->al_addr = al.addr;
1977 	ams->al_level = al.level;
1978 	ams->ms.maps = maps__get(al.maps);
1979 	ams->ms.sym = al.sym;
1980 	ams->ms.map = map__get(al.map);
1981 	ams->phys_addr = 0;
1982 	ams->data_page_size = 0;
1983 	addr_location__exit(&al);
1984 }
1985 
1986 static void ip__resolve_data(struct thread *thread,
1987 			     u8 m, struct addr_map_symbol *ams,
1988 			     u64 addr, u64 phys_addr, u64 daddr_page_size)
1989 {
1990 	struct addr_location al;
1991 
1992 	addr_location__init(&al);
1993 
1994 	thread__find_symbol(thread, m, addr, &al);
1995 
1996 	ams->addr = addr;
1997 	ams->al_addr = al.addr;
1998 	ams->al_level = al.level;
1999 	ams->ms.maps = maps__get(al.maps);
2000 	ams->ms.sym = al.sym;
2001 	ams->ms.map = map__get(al.map);
2002 	ams->phys_addr = phys_addr;
2003 	ams->data_page_size = daddr_page_size;
2004 	addr_location__exit(&al);
2005 }
2006 
2007 struct mem_info *sample__resolve_mem(struct perf_sample *sample,
2008 				     struct addr_location *al)
2009 {
2010 	struct mem_info *mi = mem_info__new();
2011 
2012 	if (!mi)
2013 		return NULL;
2014 
2015 	ip__resolve_ams(al->thread, &mi->iaddr, sample->ip);
2016 	ip__resolve_data(al->thread, al->cpumode, &mi->daddr,
2017 			 sample->addr, sample->phys_addr,
2018 			 sample->data_page_size);
2019 	mi->data_src.val = sample->data_src;
2020 
2021 	return mi;
2022 }
2023 
2024 static char *callchain_srcline(struct map_symbol *ms, u64 ip)
2025 {
2026 	struct map *map = ms->map;
2027 	char *srcline = NULL;
2028 	struct dso *dso;
2029 
2030 	if (!map || callchain_param.key == CCKEY_FUNCTION)
2031 		return srcline;
2032 
2033 	dso = map__dso(map);
2034 	srcline = srcline__tree_find(&dso->srclines, ip);
2035 	if (!srcline) {
2036 		bool show_sym = false;
2037 		bool show_addr = callchain_param.key == CCKEY_ADDRESS;
2038 
2039 		srcline = get_srcline(dso, map__rip_2objdump(map, ip),
2040 				      ms->sym, show_sym, show_addr, ip);
2041 		srcline__tree_insert(&dso->srclines, ip, srcline);
2042 	}
2043 
2044 	return srcline;
2045 }
2046 
2047 struct iterations {
2048 	int nr_loop_iter;
2049 	u64 cycles;
2050 };
2051 
2052 static int add_callchain_ip(struct thread *thread,
2053 			    struct callchain_cursor *cursor,
2054 			    struct symbol **parent,
2055 			    struct addr_location *root_al,
2056 			    u8 *cpumode,
2057 			    u64 ip,
2058 			    bool branch,
2059 			    struct branch_flags *flags,
2060 			    struct iterations *iter,
2061 			    u64 branch_from)
2062 {
2063 	struct map_symbol ms = {};
2064 	struct addr_location al;
2065 	int nr_loop_iter = 0, err = 0;
2066 	u64 iter_cycles = 0;
2067 	const char *srcline = NULL;
2068 
2069 	addr_location__init(&al);
2070 	al.filtered = 0;
2071 	al.sym = NULL;
2072 	al.srcline = NULL;
2073 	if (!cpumode) {
2074 		thread__find_cpumode_addr_location(thread, ip, &al);
2075 	} else {
2076 		if (ip >= PERF_CONTEXT_MAX) {
2077 			switch (ip) {
2078 			case PERF_CONTEXT_HV:
2079 				*cpumode = PERF_RECORD_MISC_HYPERVISOR;
2080 				break;
2081 			case PERF_CONTEXT_KERNEL:
2082 				*cpumode = PERF_RECORD_MISC_KERNEL;
2083 				break;
2084 			case PERF_CONTEXT_USER:
2085 				*cpumode = PERF_RECORD_MISC_USER;
2086 				break;
2087 			default:
2088 				pr_debug("invalid callchain context: "
2089 					 "%"PRId64"\n", (s64) ip);
2090 				/*
2091 				 * It seems the callchain is corrupted.
2092 				 * Discard all.
2093 				 */
2094 				callchain_cursor_reset(cursor);
2095 				err = 1;
2096 				goto out;
2097 			}
2098 			goto out;
2099 		}
2100 		thread__find_symbol(thread, *cpumode, ip, &al);
2101 	}
2102 
2103 	if (al.sym != NULL) {
2104 		if (perf_hpp_list.parent && !*parent &&
2105 		    symbol__match_regex(al.sym, &parent_regex))
2106 			*parent = al.sym;
2107 		else if (have_ignore_callees && root_al &&
2108 		  symbol__match_regex(al.sym, &ignore_callees_regex)) {
2109 			/* Treat this symbol as the root,
2110 			   forgetting its callees. */
2111 			addr_location__copy(root_al, &al);
2112 			callchain_cursor_reset(cursor);
2113 		}
2114 	}
2115 
2116 	if (symbol_conf.hide_unresolved && al.sym == NULL)
2117 		goto out;
2118 
2119 	if (iter) {
2120 		nr_loop_iter = iter->nr_loop_iter;
2121 		iter_cycles = iter->cycles;
2122 	}
2123 
2124 	ms.maps = maps__get(al.maps);
2125 	ms.map = map__get(al.map);
2126 	ms.sym = al.sym;
2127 	srcline = callchain_srcline(&ms, al.addr);
2128 	err = callchain_cursor_append(cursor, ip, &ms,
2129 				      branch, flags, nr_loop_iter,
2130 				      iter_cycles, branch_from, srcline);
2131 out:
2132 	addr_location__exit(&al);
2133 	map_symbol__exit(&ms);
2134 	return err;
2135 }
2136 
2137 struct branch_info *sample__resolve_bstack(struct perf_sample *sample,
2138 					   struct addr_location *al)
2139 {
2140 	unsigned int i;
2141 	const struct branch_stack *bs = sample->branch_stack;
2142 	struct branch_entry *entries = perf_sample__branch_entries(sample);
2143 	struct branch_info *bi = calloc(bs->nr, sizeof(struct branch_info));
2144 
2145 	if (!bi)
2146 		return NULL;
2147 
2148 	for (i = 0; i < bs->nr; i++) {
2149 		ip__resolve_ams(al->thread, &bi[i].to, entries[i].to);
2150 		ip__resolve_ams(al->thread, &bi[i].from, entries[i].from);
2151 		bi[i].flags = entries[i].flags;
2152 	}
2153 	return bi;
2154 }
2155 
2156 static void save_iterations(struct iterations *iter,
2157 			    struct branch_entry *be, int nr)
2158 {
2159 	int i;
2160 
2161 	iter->nr_loop_iter++;
2162 	iter->cycles = 0;
2163 
2164 	for (i = 0; i < nr; i++)
2165 		iter->cycles += be[i].flags.cycles;
2166 }
2167 
2168 #define CHASHSZ 127
2169 #define CHASHBITS 7
2170 #define NO_ENTRY 0xff
2171 
2172 #define PERF_MAX_BRANCH_DEPTH 127
2173 
2174 /* Remove loops. */
2175 static int remove_loops(struct branch_entry *l, int nr,
2176 			struct iterations *iter)
2177 {
2178 	int i, j, off;
2179 	unsigned char chash[CHASHSZ];
2180 
2181 	memset(chash, NO_ENTRY, sizeof(chash));
2182 
2183 	BUG_ON(PERF_MAX_BRANCH_DEPTH > 255);
2184 
2185 	for (i = 0; i < nr; i++) {
2186 		int h = hash_64(l[i].from, CHASHBITS) % CHASHSZ;
2187 
2188 		/* no collision handling for now */
2189 		if (chash[h] == NO_ENTRY) {
2190 			chash[h] = i;
2191 		} else if (l[chash[h]].from == l[i].from) {
2192 			bool is_loop = true;
2193 			/* check if it is a real loop */
2194 			off = 0;
2195 			for (j = chash[h]; j < i && i + off < nr; j++, off++)
2196 				if (l[j].from != l[i + off].from) {
2197 					is_loop = false;
2198 					break;
2199 				}
2200 			if (is_loop) {
2201 				j = nr - (i + off);
2202 				if (j > 0) {
2203 					save_iterations(iter + i + off,
2204 						l + i, off);
2205 
2206 					memmove(iter + i, iter + i + off,
2207 						j * sizeof(*iter));
2208 
2209 					memmove(l + i, l + i + off,
2210 						j * sizeof(*l));
2211 				}
2212 
2213 				nr -= off;
2214 			}
2215 		}
2216 	}
2217 	return nr;
2218 }
2219 
2220 static int lbr_callchain_add_kernel_ip(struct thread *thread,
2221 				       struct callchain_cursor *cursor,
2222 				       struct perf_sample *sample,
2223 				       struct symbol **parent,
2224 				       struct addr_location *root_al,
2225 				       u64 branch_from,
2226 				       bool callee, int end)
2227 {
2228 	struct ip_callchain *chain = sample->callchain;
2229 	u8 cpumode = PERF_RECORD_MISC_USER;
2230 	int err, i;
2231 
2232 	if (callee) {
2233 		for (i = 0; i < end + 1; i++) {
2234 			err = add_callchain_ip(thread, cursor, parent,
2235 					       root_al, &cpumode, chain->ips[i],
2236 					       false, NULL, NULL, branch_from);
2237 			if (err)
2238 				return err;
2239 		}
2240 		return 0;
2241 	}
2242 
2243 	for (i = end; i >= 0; i--) {
2244 		err = add_callchain_ip(thread, cursor, parent,
2245 				       root_al, &cpumode, chain->ips[i],
2246 				       false, NULL, NULL, branch_from);
2247 		if (err)
2248 			return err;
2249 	}
2250 
2251 	return 0;
2252 }
2253 
2254 static void save_lbr_cursor_node(struct thread *thread,
2255 				 struct callchain_cursor *cursor,
2256 				 int idx)
2257 {
2258 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
2259 
2260 	if (!lbr_stitch)
2261 		return;
2262 
2263 	if (cursor->pos == cursor->nr) {
2264 		lbr_stitch->prev_lbr_cursor[idx].valid = false;
2265 		return;
2266 	}
2267 
2268 	if (!cursor->curr)
2269 		cursor->curr = cursor->first;
2270 	else
2271 		cursor->curr = cursor->curr->next;
2272 	memcpy(&lbr_stitch->prev_lbr_cursor[idx], cursor->curr,
2273 	       sizeof(struct callchain_cursor_node));
2274 
2275 	lbr_stitch->prev_lbr_cursor[idx].valid = true;
2276 	cursor->pos++;
2277 }
2278 
2279 static int lbr_callchain_add_lbr_ip(struct thread *thread,
2280 				    struct callchain_cursor *cursor,
2281 				    struct perf_sample *sample,
2282 				    struct symbol **parent,
2283 				    struct addr_location *root_al,
2284 				    u64 *branch_from,
2285 				    bool callee)
2286 {
2287 	struct branch_stack *lbr_stack = sample->branch_stack;
2288 	struct branch_entry *entries = perf_sample__branch_entries(sample);
2289 	u8 cpumode = PERF_RECORD_MISC_USER;
2290 	int lbr_nr = lbr_stack->nr;
2291 	struct branch_flags *flags;
2292 	int err, i;
2293 	u64 ip;
2294 
2295 	/*
2296 	 * The curr and pos are not used in writing session. They are cleared
2297 	 * in callchain_cursor_commit() when the writing session is closed.
2298 	 * Using curr and pos to track the current cursor node.
2299 	 */
2300 	if (thread__lbr_stitch(thread)) {
2301 		cursor->curr = NULL;
2302 		cursor->pos = cursor->nr;
2303 		if (cursor->nr) {
2304 			cursor->curr = cursor->first;
2305 			for (i = 0; i < (int)(cursor->nr - 1); i++)
2306 				cursor->curr = cursor->curr->next;
2307 		}
2308 	}
2309 
2310 	if (callee) {
2311 		/* Add LBR ip from first entries.to */
2312 		ip = entries[0].to;
2313 		flags = &entries[0].flags;
2314 		*branch_from = entries[0].from;
2315 		err = add_callchain_ip(thread, cursor, parent,
2316 				       root_al, &cpumode, ip,
2317 				       true, flags, NULL,
2318 				       *branch_from);
2319 		if (err)
2320 			return err;
2321 
2322 		/*
2323 		 * The number of cursor node increases.
2324 		 * Move the current cursor node.
2325 		 * But does not need to save current cursor node for entry 0.
2326 		 * It's impossible to stitch the whole LBRs of previous sample.
2327 		 */
2328 		if (thread__lbr_stitch(thread) && (cursor->pos != cursor->nr)) {
2329 			if (!cursor->curr)
2330 				cursor->curr = cursor->first;
2331 			else
2332 				cursor->curr = cursor->curr->next;
2333 			cursor->pos++;
2334 		}
2335 
2336 		/* Add LBR ip from entries.from one by one. */
2337 		for (i = 0; i < lbr_nr; i++) {
2338 			ip = entries[i].from;
2339 			flags = &entries[i].flags;
2340 			err = add_callchain_ip(thread, cursor, parent,
2341 					       root_al, &cpumode, ip,
2342 					       true, flags, NULL,
2343 					       *branch_from);
2344 			if (err)
2345 				return err;
2346 			save_lbr_cursor_node(thread, cursor, i);
2347 		}
2348 		return 0;
2349 	}
2350 
2351 	/* Add LBR ip from entries.from one by one. */
2352 	for (i = lbr_nr - 1; i >= 0; i--) {
2353 		ip = entries[i].from;
2354 		flags = &entries[i].flags;
2355 		err = add_callchain_ip(thread, cursor, parent,
2356 				       root_al, &cpumode, ip,
2357 				       true, flags, NULL,
2358 				       *branch_from);
2359 		if (err)
2360 			return err;
2361 		save_lbr_cursor_node(thread, cursor, i);
2362 	}
2363 
2364 	if (lbr_nr > 0) {
2365 		/* Add LBR ip from first entries.to */
2366 		ip = entries[0].to;
2367 		flags = &entries[0].flags;
2368 		*branch_from = entries[0].from;
2369 		err = add_callchain_ip(thread, cursor, parent,
2370 				root_al, &cpumode, ip,
2371 				true, flags, NULL,
2372 				*branch_from);
2373 		if (err)
2374 			return err;
2375 	}
2376 
2377 	return 0;
2378 }
2379 
2380 static int lbr_callchain_add_stitched_lbr_ip(struct thread *thread,
2381 					     struct callchain_cursor *cursor)
2382 {
2383 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
2384 	struct callchain_cursor_node *cnode;
2385 	struct stitch_list *stitch_node;
2386 	int err;
2387 
2388 	list_for_each_entry(stitch_node, &lbr_stitch->lists, node) {
2389 		cnode = &stitch_node->cursor;
2390 
2391 		err = callchain_cursor_append(cursor, cnode->ip,
2392 					      &cnode->ms,
2393 					      cnode->branch,
2394 					      &cnode->branch_flags,
2395 					      cnode->nr_loop_iter,
2396 					      cnode->iter_cycles,
2397 					      cnode->branch_from,
2398 					      cnode->srcline);
2399 		if (err)
2400 			return err;
2401 	}
2402 	return 0;
2403 }
2404 
2405 static struct stitch_list *get_stitch_node(struct thread *thread)
2406 {
2407 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
2408 	struct stitch_list *stitch_node;
2409 
2410 	if (!list_empty(&lbr_stitch->free_lists)) {
2411 		stitch_node = list_first_entry(&lbr_stitch->free_lists,
2412 					       struct stitch_list, node);
2413 		list_del(&stitch_node->node);
2414 
2415 		return stitch_node;
2416 	}
2417 
2418 	return malloc(sizeof(struct stitch_list));
2419 }
2420 
2421 static bool has_stitched_lbr(struct thread *thread,
2422 			     struct perf_sample *cur,
2423 			     struct perf_sample *prev,
2424 			     unsigned int max_lbr,
2425 			     bool callee)
2426 {
2427 	struct branch_stack *cur_stack = cur->branch_stack;
2428 	struct branch_entry *cur_entries = perf_sample__branch_entries(cur);
2429 	struct branch_stack *prev_stack = prev->branch_stack;
2430 	struct branch_entry *prev_entries = perf_sample__branch_entries(prev);
2431 	struct lbr_stitch *lbr_stitch = thread__lbr_stitch(thread);
2432 	int i, j, nr_identical_branches = 0;
2433 	struct stitch_list *stitch_node;
2434 	u64 cur_base, distance;
2435 
2436 	if (!cur_stack || !prev_stack)
2437 		return false;
2438 
2439 	/* Find the physical index of the base-of-stack for current sample. */
2440 	cur_base = max_lbr - cur_stack->nr + cur_stack->hw_idx + 1;
2441 
2442 	distance = (prev_stack->hw_idx > cur_base) ? (prev_stack->hw_idx - cur_base) :
2443 						     (max_lbr + prev_stack->hw_idx - cur_base);
2444 	/* Previous sample has shorter stack. Nothing can be stitched. */
2445 	if (distance + 1 > prev_stack->nr)
2446 		return false;
2447 
2448 	/*
2449 	 * Check if there are identical LBRs between two samples.
2450 	 * Identical LBRs must have same from, to and flags values. Also,
2451 	 * they have to be saved in the same LBR registers (same physical
2452 	 * index).
2453 	 *
2454 	 * Starts from the base-of-stack of current sample.
2455 	 */
2456 	for (i = distance, j = cur_stack->nr - 1; (i >= 0) && (j >= 0); i--, j--) {
2457 		if ((prev_entries[i].from != cur_entries[j].from) ||
2458 		    (prev_entries[i].to != cur_entries[j].to) ||
2459 		    (prev_entries[i].flags.value != cur_entries[j].flags.value))
2460 			break;
2461 		nr_identical_branches++;
2462 	}
2463 
2464 	if (!nr_identical_branches)
2465 		return false;
2466 
2467 	/*
2468 	 * Save the LBRs between the base-of-stack of previous sample
2469 	 * and the base-of-stack of current sample into lbr_stitch->lists.
2470 	 * These LBRs will be stitched later.
2471 	 */
2472 	for (i = prev_stack->nr - 1; i > (int)distance; i--) {
2473 
2474 		if (!lbr_stitch->prev_lbr_cursor[i].valid)
2475 			continue;
2476 
2477 		stitch_node = get_stitch_node(thread);
2478 		if (!stitch_node)
2479 			return false;
2480 
2481 		memcpy(&stitch_node->cursor, &lbr_stitch->prev_lbr_cursor[i],
2482 		       sizeof(struct callchain_cursor_node));
2483 
2484 		if (callee)
2485 			list_add(&stitch_node->node, &lbr_stitch->lists);
2486 		else
2487 			list_add_tail(&stitch_node->node, &lbr_stitch->lists);
2488 	}
2489 
2490 	return true;
2491 }
2492 
2493 static bool alloc_lbr_stitch(struct thread *thread, unsigned int max_lbr)
2494 {
2495 	if (thread__lbr_stitch(thread))
2496 		return true;
2497 
2498 	thread__set_lbr_stitch(thread, zalloc(sizeof(struct lbr_stitch)));
2499 	if (!thread__lbr_stitch(thread))
2500 		goto err;
2501 
2502 	thread__lbr_stitch(thread)->prev_lbr_cursor =
2503 		calloc(max_lbr + 1, sizeof(struct callchain_cursor_node));
2504 	if (!thread__lbr_stitch(thread)->prev_lbr_cursor)
2505 		goto free_lbr_stitch;
2506 
2507 	INIT_LIST_HEAD(&thread__lbr_stitch(thread)->lists);
2508 	INIT_LIST_HEAD(&thread__lbr_stitch(thread)->free_lists);
2509 
2510 	return true;
2511 
2512 free_lbr_stitch:
2513 	free(thread__lbr_stitch(thread));
2514 	thread__set_lbr_stitch(thread, NULL);
2515 err:
2516 	pr_warning("Failed to allocate space for stitched LBRs. Disable LBR stitch\n");
2517 	thread__set_lbr_stitch_enable(thread, false);
2518 	return false;
2519 }
2520 
2521 /*
2522  * Resolve LBR callstack chain sample
2523  * Return:
2524  * 1 on success get LBR callchain information
2525  * 0 no available LBR callchain information, should try fp
2526  * negative error code on other errors.
2527  */
2528 static int resolve_lbr_callchain_sample(struct thread *thread,
2529 					struct callchain_cursor *cursor,
2530 					struct perf_sample *sample,
2531 					struct symbol **parent,
2532 					struct addr_location *root_al,
2533 					int max_stack,
2534 					unsigned int max_lbr)
2535 {
2536 	bool callee = (callchain_param.order == ORDER_CALLEE);
2537 	struct ip_callchain *chain = sample->callchain;
2538 	int chain_nr = min(max_stack, (int)chain->nr), i;
2539 	struct lbr_stitch *lbr_stitch;
2540 	bool stitched_lbr = false;
2541 	u64 branch_from = 0;
2542 	int err;
2543 
2544 	for (i = 0; i < chain_nr; i++) {
2545 		if (chain->ips[i] == PERF_CONTEXT_USER)
2546 			break;
2547 	}
2548 
2549 	/* LBR only affects the user callchain */
2550 	if (i == chain_nr)
2551 		return 0;
2552 
2553 	if (thread__lbr_stitch_enable(thread) && !sample->no_hw_idx &&
2554 	    (max_lbr > 0) && alloc_lbr_stitch(thread, max_lbr)) {
2555 		lbr_stitch = thread__lbr_stitch(thread);
2556 
2557 		stitched_lbr = has_stitched_lbr(thread, sample,
2558 						&lbr_stitch->prev_sample,
2559 						max_lbr, callee);
2560 
2561 		if (!stitched_lbr && !list_empty(&lbr_stitch->lists)) {
2562 			list_replace_init(&lbr_stitch->lists,
2563 					  &lbr_stitch->free_lists);
2564 		}
2565 		memcpy(&lbr_stitch->prev_sample, sample, sizeof(*sample));
2566 	}
2567 
2568 	if (callee) {
2569 		/* Add kernel ip */
2570 		err = lbr_callchain_add_kernel_ip(thread, cursor, sample,
2571 						  parent, root_al, branch_from,
2572 						  true, i);
2573 		if (err)
2574 			goto error;
2575 
2576 		err = lbr_callchain_add_lbr_ip(thread, cursor, sample, parent,
2577 					       root_al, &branch_from, true);
2578 		if (err)
2579 			goto error;
2580 
2581 		if (stitched_lbr) {
2582 			err = lbr_callchain_add_stitched_lbr_ip(thread, cursor);
2583 			if (err)
2584 				goto error;
2585 		}
2586 
2587 	} else {
2588 		if (stitched_lbr) {
2589 			err = lbr_callchain_add_stitched_lbr_ip(thread, cursor);
2590 			if (err)
2591 				goto error;
2592 		}
2593 		err = lbr_callchain_add_lbr_ip(thread, cursor, sample, parent,
2594 					       root_al, &branch_from, false);
2595 		if (err)
2596 			goto error;
2597 
2598 		/* Add kernel ip */
2599 		err = lbr_callchain_add_kernel_ip(thread, cursor, sample,
2600 						  parent, root_al, branch_from,
2601 						  false, i);
2602 		if (err)
2603 			goto error;
2604 	}
2605 	return 1;
2606 
2607 error:
2608 	return (err < 0) ? err : 0;
2609 }
2610 
2611 static int find_prev_cpumode(struct ip_callchain *chain, struct thread *thread,
2612 			     struct callchain_cursor *cursor,
2613 			     struct symbol **parent,
2614 			     struct addr_location *root_al,
2615 			     u8 *cpumode, int ent)
2616 {
2617 	int err = 0;
2618 
2619 	while (--ent >= 0) {
2620 		u64 ip = chain->ips[ent];
2621 
2622 		if (ip >= PERF_CONTEXT_MAX) {
2623 			err = add_callchain_ip(thread, cursor, parent,
2624 					       root_al, cpumode, ip,
2625 					       false, NULL, NULL, 0);
2626 			break;
2627 		}
2628 	}
2629 	return err;
2630 }
2631 
2632 static u64 get_leaf_frame_caller(struct perf_sample *sample,
2633 		struct thread *thread, int usr_idx)
2634 {
2635 	if (machine__normalized_is(maps__machine(thread__maps(thread)), "arm64"))
2636 		return get_leaf_frame_caller_aarch64(sample, thread, usr_idx);
2637 	else
2638 		return 0;
2639 }
2640 
2641 static int thread__resolve_callchain_sample(struct thread *thread,
2642 					    struct callchain_cursor *cursor,
2643 					    struct evsel *evsel,
2644 					    struct perf_sample *sample,
2645 					    struct symbol **parent,
2646 					    struct addr_location *root_al,
2647 					    int max_stack)
2648 {
2649 	struct branch_stack *branch = sample->branch_stack;
2650 	struct branch_entry *entries = perf_sample__branch_entries(sample);
2651 	struct ip_callchain *chain = sample->callchain;
2652 	int chain_nr = 0;
2653 	u8 cpumode = PERF_RECORD_MISC_USER;
2654 	int i, j, err, nr_entries, usr_idx;
2655 	int skip_idx = -1;
2656 	int first_call = 0;
2657 	u64 leaf_frame_caller;
2658 
2659 	if (chain)
2660 		chain_nr = chain->nr;
2661 
2662 	if (evsel__has_branch_callstack(evsel)) {
2663 		struct perf_env *env = evsel__env(evsel);
2664 
2665 		err = resolve_lbr_callchain_sample(thread, cursor, sample, parent,
2666 						   root_al, max_stack,
2667 						   !env ? 0 : env->max_branches);
2668 		if (err)
2669 			return (err < 0) ? err : 0;
2670 	}
2671 
2672 	/*
2673 	 * Based on DWARF debug information, some architectures skip
2674 	 * a callchain entry saved by the kernel.
2675 	 */
2676 	skip_idx = arch_skip_callchain_idx(thread, chain);
2677 
2678 	/*
2679 	 * Add branches to call stack for easier browsing. This gives
2680 	 * more context for a sample than just the callers.
2681 	 *
2682 	 * This uses individual histograms of paths compared to the
2683 	 * aggregated histograms the normal LBR mode uses.
2684 	 *
2685 	 * Limitations for now:
2686 	 * - No extra filters
2687 	 * - No annotations (should annotate somehow)
2688 	 */
2689 
2690 	if (branch && callchain_param.branch_callstack) {
2691 		int nr = min(max_stack, (int)branch->nr);
2692 		struct branch_entry be[nr];
2693 		struct iterations iter[nr];
2694 
2695 		if (branch->nr > PERF_MAX_BRANCH_DEPTH) {
2696 			pr_warning("corrupted branch chain. skipping...\n");
2697 			goto check_calls;
2698 		}
2699 
2700 		for (i = 0; i < nr; i++) {
2701 			if (callchain_param.order == ORDER_CALLEE) {
2702 				be[i] = entries[i];
2703 
2704 				if (chain == NULL)
2705 					continue;
2706 
2707 				/*
2708 				 * Check for overlap into the callchain.
2709 				 * The return address is one off compared to
2710 				 * the branch entry. To adjust for this
2711 				 * assume the calling instruction is not longer
2712 				 * than 8 bytes.
2713 				 */
2714 				if (i == skip_idx ||
2715 				    chain->ips[first_call] >= PERF_CONTEXT_MAX)
2716 					first_call++;
2717 				else if (be[i].from < chain->ips[first_call] &&
2718 				    be[i].from >= chain->ips[first_call] - 8)
2719 					first_call++;
2720 			} else
2721 				be[i] = entries[branch->nr - i - 1];
2722 		}
2723 
2724 		memset(iter, 0, sizeof(struct iterations) * nr);
2725 		nr = remove_loops(be, nr, iter);
2726 
2727 		for (i = 0; i < nr; i++) {
2728 			err = add_callchain_ip(thread, cursor, parent,
2729 					       root_al,
2730 					       NULL, be[i].to,
2731 					       true, &be[i].flags,
2732 					       NULL, be[i].from);
2733 
2734 			if (!err)
2735 				err = add_callchain_ip(thread, cursor, parent, root_al,
2736 						       NULL, be[i].from,
2737 						       true, &be[i].flags,
2738 						       &iter[i], 0);
2739 			if (err == -EINVAL)
2740 				break;
2741 			if (err)
2742 				return err;
2743 		}
2744 
2745 		if (chain_nr == 0)
2746 			return 0;
2747 
2748 		chain_nr -= nr;
2749 	}
2750 
2751 check_calls:
2752 	if (chain && callchain_param.order != ORDER_CALLEE) {
2753 		err = find_prev_cpumode(chain, thread, cursor, parent, root_al,
2754 					&cpumode, chain->nr - first_call);
2755 		if (err)
2756 			return (err < 0) ? err : 0;
2757 	}
2758 	for (i = first_call, nr_entries = 0;
2759 	     i < chain_nr && nr_entries < max_stack; i++) {
2760 		u64 ip;
2761 
2762 		if (callchain_param.order == ORDER_CALLEE)
2763 			j = i;
2764 		else
2765 			j = chain->nr - i - 1;
2766 
2767 #ifdef HAVE_SKIP_CALLCHAIN_IDX
2768 		if (j == skip_idx)
2769 			continue;
2770 #endif
2771 		ip = chain->ips[j];
2772 		if (ip < PERF_CONTEXT_MAX)
2773                        ++nr_entries;
2774 		else if (callchain_param.order != ORDER_CALLEE) {
2775 			err = find_prev_cpumode(chain, thread, cursor, parent,
2776 						root_al, &cpumode, j);
2777 			if (err)
2778 				return (err < 0) ? err : 0;
2779 			continue;
2780 		}
2781 
2782 		/*
2783 		 * PERF_CONTEXT_USER allows us to locate where the user stack ends.
2784 		 * Depending on callchain_param.order and the position of PERF_CONTEXT_USER,
2785 		 * the index will be different in order to add the missing frame
2786 		 * at the right place.
2787 		 */
2788 
2789 		usr_idx = callchain_param.order == ORDER_CALLEE ? j-2 : j-1;
2790 
2791 		if (usr_idx >= 0 && chain->ips[usr_idx] == PERF_CONTEXT_USER) {
2792 
2793 			leaf_frame_caller = get_leaf_frame_caller(sample, thread, usr_idx);
2794 
2795 			/*
2796 			 * check if leaf_frame_Caller != ip to not add the same
2797 			 * value twice.
2798 			 */
2799 
2800 			if (leaf_frame_caller && leaf_frame_caller != ip) {
2801 
2802 				err = add_callchain_ip(thread, cursor, parent,
2803 					       root_al, &cpumode, leaf_frame_caller,
2804 					       false, NULL, NULL, 0);
2805 				if (err)
2806 					return (err < 0) ? err : 0;
2807 			}
2808 		}
2809 
2810 		err = add_callchain_ip(thread, cursor, parent,
2811 				       root_al, &cpumode, ip,
2812 				       false, NULL, NULL, 0);
2813 
2814 		if (err)
2815 			return (err < 0) ? err : 0;
2816 	}
2817 
2818 	return 0;
2819 }
2820 
2821 static int append_inlines(struct callchain_cursor *cursor, struct map_symbol *ms, u64 ip)
2822 {
2823 	struct symbol *sym = ms->sym;
2824 	struct map *map = ms->map;
2825 	struct inline_node *inline_node;
2826 	struct inline_list *ilist;
2827 	struct dso *dso;
2828 	u64 addr;
2829 	int ret = 1;
2830 	struct map_symbol ilist_ms;
2831 
2832 	if (!symbol_conf.inline_name || !map || !sym)
2833 		return ret;
2834 
2835 	addr = map__dso_map_ip(map, ip);
2836 	addr = map__rip_2objdump(map, addr);
2837 	dso = map__dso(map);
2838 
2839 	inline_node = inlines__tree_find(&dso->inlined_nodes, addr);
2840 	if (!inline_node) {
2841 		inline_node = dso__parse_addr_inlines(dso, addr, sym);
2842 		if (!inline_node)
2843 			return ret;
2844 		inlines__tree_insert(&dso->inlined_nodes, inline_node);
2845 	}
2846 
2847 	ilist_ms = (struct map_symbol) {
2848 		.maps = maps__get(ms->maps),
2849 		.map = map__get(map),
2850 	};
2851 	list_for_each_entry(ilist, &inline_node->val, list) {
2852 		ilist_ms.sym = ilist->symbol;
2853 		ret = callchain_cursor_append(cursor, ip, &ilist_ms, false,
2854 					      NULL, 0, 0, 0, ilist->srcline);
2855 
2856 		if (ret != 0)
2857 			return ret;
2858 	}
2859 	map_symbol__exit(&ilist_ms);
2860 
2861 	return ret;
2862 }
2863 
2864 static int unwind_entry(struct unwind_entry *entry, void *arg)
2865 {
2866 	struct callchain_cursor *cursor = arg;
2867 	const char *srcline = NULL;
2868 	u64 addr = entry->ip;
2869 
2870 	if (symbol_conf.hide_unresolved && entry->ms.sym == NULL)
2871 		return 0;
2872 
2873 	if (append_inlines(cursor, &entry->ms, entry->ip) == 0)
2874 		return 0;
2875 
2876 	/*
2877 	 * Convert entry->ip from a virtual address to an offset in
2878 	 * its corresponding binary.
2879 	 */
2880 	if (entry->ms.map)
2881 		addr = map__dso_map_ip(entry->ms.map, entry->ip);
2882 
2883 	srcline = callchain_srcline(&entry->ms, addr);
2884 	return callchain_cursor_append(cursor, entry->ip, &entry->ms,
2885 				       false, NULL, 0, 0, 0, srcline);
2886 }
2887 
2888 static int thread__resolve_callchain_unwind(struct thread *thread,
2889 					    struct callchain_cursor *cursor,
2890 					    struct evsel *evsel,
2891 					    struct perf_sample *sample,
2892 					    int max_stack)
2893 {
2894 	/* Can we do dwarf post unwind? */
2895 	if (!((evsel->core.attr.sample_type & PERF_SAMPLE_REGS_USER) &&
2896 	      (evsel->core.attr.sample_type & PERF_SAMPLE_STACK_USER)))
2897 		return 0;
2898 
2899 	/* Bail out if nothing was captured. */
2900 	if ((!sample->user_regs.regs) ||
2901 	    (!sample->user_stack.size))
2902 		return 0;
2903 
2904 	return unwind__get_entries(unwind_entry, cursor,
2905 				   thread, sample, max_stack, false);
2906 }
2907 
2908 int thread__resolve_callchain(struct thread *thread,
2909 			      struct callchain_cursor *cursor,
2910 			      struct evsel *evsel,
2911 			      struct perf_sample *sample,
2912 			      struct symbol **parent,
2913 			      struct addr_location *root_al,
2914 			      int max_stack)
2915 {
2916 	int ret = 0;
2917 
2918 	if (cursor == NULL)
2919 		return -ENOMEM;
2920 
2921 	callchain_cursor_reset(cursor);
2922 
2923 	if (callchain_param.order == ORDER_CALLEE) {
2924 		ret = thread__resolve_callchain_sample(thread, cursor,
2925 						       evsel, sample,
2926 						       parent, root_al,
2927 						       max_stack);
2928 		if (ret)
2929 			return ret;
2930 		ret = thread__resolve_callchain_unwind(thread, cursor,
2931 						       evsel, sample,
2932 						       max_stack);
2933 	} else {
2934 		ret = thread__resolve_callchain_unwind(thread, cursor,
2935 						       evsel, sample,
2936 						       max_stack);
2937 		if (ret)
2938 			return ret;
2939 		ret = thread__resolve_callchain_sample(thread, cursor,
2940 						       evsel, sample,
2941 						       parent, root_al,
2942 						       max_stack);
2943 	}
2944 
2945 	return ret;
2946 }
2947 
2948 int machine__for_each_thread(struct machine *machine,
2949 			     int (*fn)(struct thread *thread, void *p),
2950 			     void *priv)
2951 {
2952 	return threads__for_each_thread(&machine->threads, fn, priv);
2953 }
2954 
2955 int machines__for_each_thread(struct machines *machines,
2956 			      int (*fn)(struct thread *thread, void *p),
2957 			      void *priv)
2958 {
2959 	struct rb_node *nd;
2960 	int rc = 0;
2961 
2962 	rc = machine__for_each_thread(&machines->host, fn, priv);
2963 	if (rc != 0)
2964 		return rc;
2965 
2966 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
2967 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
2968 
2969 		rc = machine__for_each_thread(machine, fn, priv);
2970 		if (rc != 0)
2971 			return rc;
2972 	}
2973 	return rc;
2974 }
2975 
2976 
2977 static int thread_list_cb(struct thread *thread, void *data)
2978 {
2979 	struct list_head *list = data;
2980 	struct thread_list *entry = malloc(sizeof(*entry));
2981 
2982 	if (!entry)
2983 		return -ENOMEM;
2984 
2985 	entry->thread = thread__get(thread);
2986 	list_add_tail(&entry->list, list);
2987 	return 0;
2988 }
2989 
2990 int machine__thread_list(struct machine *machine, struct list_head *list)
2991 {
2992 	return machine__for_each_thread(machine, thread_list_cb, list);
2993 }
2994 
2995 void thread_list__delete(struct list_head *list)
2996 {
2997 	struct thread_list *pos, *next;
2998 
2999 	list_for_each_entry_safe(pos, next, list, list) {
3000 		thread__zput(pos->thread);
3001 		list_del(&pos->list);
3002 		free(pos);
3003 	}
3004 }
3005 
3006 pid_t machine__get_current_tid(struct machine *machine, int cpu)
3007 {
3008 	if (cpu < 0 || (size_t)cpu >= machine->current_tid_sz)
3009 		return -1;
3010 
3011 	return machine->current_tid[cpu];
3012 }
3013 
3014 int machine__set_current_tid(struct machine *machine, int cpu, pid_t pid,
3015 			     pid_t tid)
3016 {
3017 	struct thread *thread;
3018 	const pid_t init_val = -1;
3019 
3020 	if (cpu < 0)
3021 		return -EINVAL;
3022 
3023 	if (realloc_array_as_needed(machine->current_tid,
3024 				    machine->current_tid_sz,
3025 				    (unsigned int)cpu,
3026 				    &init_val))
3027 		return -ENOMEM;
3028 
3029 	machine->current_tid[cpu] = tid;
3030 
3031 	thread = machine__findnew_thread(machine, pid, tid);
3032 	if (!thread)
3033 		return -ENOMEM;
3034 
3035 	thread__set_cpu(thread, cpu);
3036 	thread__put(thread);
3037 
3038 	return 0;
3039 }
3040 
3041 /*
3042  * Compares the raw arch string. N.B. see instead perf_env__arch() or
3043  * machine__normalized_is() if a normalized arch is needed.
3044  */
3045 bool machine__is(struct machine *machine, const char *arch)
3046 {
3047 	return machine && !strcmp(perf_env__raw_arch(machine->env), arch);
3048 }
3049 
3050 bool machine__normalized_is(struct machine *machine, const char *arch)
3051 {
3052 	return machine && !strcmp(perf_env__arch(machine->env), arch);
3053 }
3054 
3055 int machine__nr_cpus_avail(struct machine *machine)
3056 {
3057 	return machine ? perf_env__nr_cpus_avail(machine->env) : 0;
3058 }
3059 
3060 int machine__get_kernel_start(struct machine *machine)
3061 {
3062 	struct map *map = machine__kernel_map(machine);
3063 	int err = 0;
3064 
3065 	/*
3066 	 * The only addresses above 2^63 are kernel addresses of a 64-bit
3067 	 * kernel.  Note that addresses are unsigned so that on a 32-bit system
3068 	 * all addresses including kernel addresses are less than 2^32.  In
3069 	 * that case (32-bit system), if the kernel mapping is unknown, all
3070 	 * addresses will be assumed to be in user space - see
3071 	 * machine__kernel_ip().
3072 	 */
3073 	machine->kernel_start = 1ULL << 63;
3074 	if (map) {
3075 		err = map__load(map);
3076 		/*
3077 		 * On x86_64, PTI entry trampolines are less than the
3078 		 * start of kernel text, but still above 2^63. So leave
3079 		 * kernel_start = 1ULL << 63 for x86_64.
3080 		 */
3081 		if (!err && !machine__is(machine, "x86_64"))
3082 			machine->kernel_start = map__start(map);
3083 	}
3084 	return err;
3085 }
3086 
3087 u8 machine__addr_cpumode(struct machine *machine, u8 cpumode, u64 addr)
3088 {
3089 	u8 addr_cpumode = cpumode;
3090 	bool kernel_ip;
3091 
3092 	if (!machine->single_address_space)
3093 		goto out;
3094 
3095 	kernel_ip = machine__kernel_ip(machine, addr);
3096 	switch (cpumode) {
3097 	case PERF_RECORD_MISC_KERNEL:
3098 	case PERF_RECORD_MISC_USER:
3099 		addr_cpumode = kernel_ip ? PERF_RECORD_MISC_KERNEL :
3100 					   PERF_RECORD_MISC_USER;
3101 		break;
3102 	case PERF_RECORD_MISC_GUEST_KERNEL:
3103 	case PERF_RECORD_MISC_GUEST_USER:
3104 		addr_cpumode = kernel_ip ? PERF_RECORD_MISC_GUEST_KERNEL :
3105 					   PERF_RECORD_MISC_GUEST_USER;
3106 		break;
3107 	default:
3108 		break;
3109 	}
3110 out:
3111 	return addr_cpumode;
3112 }
3113 
3114 struct dso *machine__findnew_dso_id(struct machine *machine, const char *filename, struct dso_id *id)
3115 {
3116 	return dsos__findnew_id(&machine->dsos, filename, id);
3117 }
3118 
3119 struct dso *machine__findnew_dso(struct machine *machine, const char *filename)
3120 {
3121 	return machine__findnew_dso_id(machine, filename, NULL);
3122 }
3123 
3124 char *machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
3125 {
3126 	struct machine *machine = vmachine;
3127 	struct map *map;
3128 	struct symbol *sym = machine__find_kernel_symbol(machine, *addrp, &map);
3129 
3130 	if (sym == NULL)
3131 		return NULL;
3132 
3133 	*modp = __map__is_kmodule(map) ? (char *)map__dso(map)->short_name : NULL;
3134 	*addrp = map__unmap_ip(map, sym->start);
3135 	return sym->name;
3136 }
3137 
3138 struct machine__for_each_dso_cb_args {
3139 	struct machine *machine;
3140 	machine__dso_t fn;
3141 	void *priv;
3142 };
3143 
3144 static int machine__for_each_dso_cb(struct dso *dso, void *data)
3145 {
3146 	struct machine__for_each_dso_cb_args *args = data;
3147 
3148 	return args->fn(dso, args->machine, args->priv);
3149 }
3150 
3151 int machine__for_each_dso(struct machine *machine, machine__dso_t fn, void *priv)
3152 {
3153 	struct machine__for_each_dso_cb_args args = {
3154 		.machine = machine,
3155 		.fn = fn,
3156 		.priv = priv,
3157 	};
3158 
3159 	return dsos__for_each_dso(&machine->dsos, machine__for_each_dso_cb, &args);
3160 }
3161 
3162 int machine__for_each_kernel_map(struct machine *machine, machine__map_t fn, void *priv)
3163 {
3164 	struct maps *maps = machine__kernel_maps(machine);
3165 
3166 	return maps__for_each_map(maps, fn, priv);
3167 }
3168 
3169 bool machine__is_lock_function(struct machine *machine, u64 addr)
3170 {
3171 	if (!machine->sched.text_start) {
3172 		struct map *kmap;
3173 		struct symbol *sym = machine__find_kernel_symbol_by_name(machine, "__sched_text_start", &kmap);
3174 
3175 		if (!sym) {
3176 			/* to avoid retry */
3177 			machine->sched.text_start = 1;
3178 			return false;
3179 		}
3180 
3181 		machine->sched.text_start = map__unmap_ip(kmap, sym->start);
3182 
3183 		/* should not fail from here */
3184 		sym = machine__find_kernel_symbol_by_name(machine, "__sched_text_end", &kmap);
3185 		machine->sched.text_end = map__unmap_ip(kmap, sym->start);
3186 
3187 		sym = machine__find_kernel_symbol_by_name(machine, "__lock_text_start", &kmap);
3188 		machine->lock.text_start = map__unmap_ip(kmap, sym->start);
3189 
3190 		sym = machine__find_kernel_symbol_by_name(machine, "__lock_text_end", &kmap);
3191 		machine->lock.text_end = map__unmap_ip(kmap, sym->start);
3192 
3193 		sym = machine__find_kernel_symbol_by_name(machine, "__traceiter_contention_begin", &kmap);
3194 		if (sym) {
3195 			machine->traceiter.text_start = map__unmap_ip(kmap, sym->start);
3196 			machine->traceiter.text_end = map__unmap_ip(kmap, sym->end);
3197 		}
3198 		sym = machine__find_kernel_symbol_by_name(machine, "trace_contention_begin", &kmap);
3199 		if (sym) {
3200 			machine->trace.text_start = map__unmap_ip(kmap, sym->start);
3201 			machine->trace.text_end = map__unmap_ip(kmap, sym->end);
3202 		}
3203 	}
3204 
3205 	/* failed to get kernel symbols */
3206 	if (machine->sched.text_start == 1)
3207 		return false;
3208 
3209 	/* mutex and rwsem functions are in sched text section */
3210 	if (machine->sched.text_start <= addr && addr < machine->sched.text_end)
3211 		return true;
3212 
3213 	/* spinlock functions are in lock text section */
3214 	if (machine->lock.text_start <= addr && addr < machine->lock.text_end)
3215 		return true;
3216 
3217 	/* traceiter functions currently don't have their own section
3218 	 * but we consider them lock functions
3219 	 */
3220 	if (machine->traceiter.text_start != 0) {
3221 		if (machine->traceiter.text_start <= addr && addr < machine->traceiter.text_end)
3222 			return true;
3223 	}
3224 
3225 	if (machine->trace.text_start != 0) {
3226 		if (machine->trace.text_start <= addr && addr < machine->trace.text_end)
3227 			return true;
3228 	}
3229 
3230 	return false;
3231 }
3232 
3233 int machine__hit_all_dsos(struct machine *machine)
3234 {
3235 	return dsos__hit_all(&machine->dsos);
3236 }
3237