xref: /openbmc/linux/tools/perf/util/machine.c (revision a44e4f3a)
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 "srcline.h"
20 #include "symbol.h"
21 #include "sort.h"
22 #include "strlist.h"
23 #include "target.h"
24 #include "thread.h"
25 #include "util.h"
26 #include "vdso.h"
27 #include <stdbool.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include "unwind.h"
32 #include "linux/hash.h"
33 #include "asm/bug.h"
34 #include "bpf-event.h"
35 #include <internal/lib.h> // page_size
36 
37 #include <linux/ctype.h>
38 #include <symbol/kallsyms.h>
39 #include <linux/mman.h>
40 #include <linux/string.h>
41 #include <linux/zalloc.h>
42 
43 static void __machine__remove_thread(struct machine *machine, struct thread *th, bool lock);
44 
45 static struct dso *machine__kernel_dso(struct machine *machine)
46 {
47 	return machine->vmlinux_map->dso;
48 }
49 
50 static void dsos__init(struct dsos *dsos)
51 {
52 	INIT_LIST_HEAD(&dsos->head);
53 	dsos->root = RB_ROOT;
54 	init_rwsem(&dsos->lock);
55 }
56 
57 static void machine__threads_init(struct machine *machine)
58 {
59 	int i;
60 
61 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
62 		struct threads *threads = &machine->threads[i];
63 		threads->entries = RB_ROOT_CACHED;
64 		init_rwsem(&threads->lock);
65 		threads->nr = 0;
66 		INIT_LIST_HEAD(&threads->dead);
67 		threads->last_match = NULL;
68 	}
69 }
70 
71 static int machine__set_mmap_name(struct machine *machine)
72 {
73 	if (machine__is_host(machine))
74 		machine->mmap_name = strdup("[kernel.kallsyms]");
75 	else if (machine__is_default_guest(machine))
76 		machine->mmap_name = strdup("[guest.kernel.kallsyms]");
77 	else if (asprintf(&machine->mmap_name, "[guest.kernel.kallsyms.%d]",
78 			  machine->pid) < 0)
79 		machine->mmap_name = NULL;
80 
81 	return machine->mmap_name ? 0 : -ENOMEM;
82 }
83 
84 int machine__init(struct machine *machine, const char *root_dir, pid_t pid)
85 {
86 	int err = -ENOMEM;
87 
88 	memset(machine, 0, sizeof(*machine));
89 	map_groups__init(&machine->kmaps, machine);
90 	RB_CLEAR_NODE(&machine->rb_node);
91 	dsos__init(&machine->dsos);
92 
93 	machine__threads_init(machine);
94 
95 	machine->vdso_info = NULL;
96 	machine->env = NULL;
97 
98 	machine->pid = pid;
99 
100 	machine->id_hdr_size = 0;
101 	machine->kptr_restrict_warned = false;
102 	machine->comm_exec = false;
103 	machine->kernel_start = 0;
104 	machine->vmlinux_map = NULL;
105 
106 	machine->root_dir = strdup(root_dir);
107 	if (machine->root_dir == NULL)
108 		return -ENOMEM;
109 
110 	if (machine__set_mmap_name(machine))
111 		goto out;
112 
113 	if (pid != HOST_KERNEL_ID) {
114 		struct thread *thread = machine__findnew_thread(machine, -1,
115 								pid);
116 		char comm[64];
117 
118 		if (thread == NULL)
119 			goto out;
120 
121 		snprintf(comm, sizeof(comm), "[guest/%d]", pid);
122 		thread__set_comm(thread, comm, 0);
123 		thread__put(thread);
124 	}
125 
126 	machine->current_tid = NULL;
127 	err = 0;
128 
129 out:
130 	if (err) {
131 		zfree(&machine->root_dir);
132 		zfree(&machine->mmap_name);
133 	}
134 	return 0;
135 }
136 
137 struct machine *machine__new_host(void)
138 {
139 	struct machine *machine = malloc(sizeof(*machine));
140 
141 	if (machine != NULL) {
142 		machine__init(machine, "", HOST_KERNEL_ID);
143 
144 		if (machine__create_kernel_maps(machine) < 0)
145 			goto out_delete;
146 	}
147 
148 	return machine;
149 out_delete:
150 	free(machine);
151 	return NULL;
152 }
153 
154 struct machine *machine__new_kallsyms(void)
155 {
156 	struct machine *machine = machine__new_host();
157 	/*
158 	 * FIXME:
159 	 * 1) We should switch to machine__load_kallsyms(), i.e. not explicitly
160 	 *    ask for not using the kcore parsing code, once this one is fixed
161 	 *    to create a map per module.
162 	 */
163 	if (machine && machine__load_kallsyms(machine, "/proc/kallsyms") <= 0) {
164 		machine__delete(machine);
165 		machine = NULL;
166 	}
167 
168 	return machine;
169 }
170 
171 static void dsos__purge(struct dsos *dsos)
172 {
173 	struct dso *pos, *n;
174 
175 	down_write(&dsos->lock);
176 
177 	list_for_each_entry_safe(pos, n, &dsos->head, node) {
178 		RB_CLEAR_NODE(&pos->rb_node);
179 		pos->root = NULL;
180 		list_del_init(&pos->node);
181 		dso__put(pos);
182 	}
183 
184 	up_write(&dsos->lock);
185 }
186 
187 static void dsos__exit(struct dsos *dsos)
188 {
189 	dsos__purge(dsos);
190 	exit_rwsem(&dsos->lock);
191 }
192 
193 void machine__delete_threads(struct machine *machine)
194 {
195 	struct rb_node *nd;
196 	int i;
197 
198 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
199 		struct threads *threads = &machine->threads[i];
200 		down_write(&threads->lock);
201 		nd = rb_first_cached(&threads->entries);
202 		while (nd) {
203 			struct thread *t = rb_entry(nd, struct thread, rb_node);
204 
205 			nd = rb_next(nd);
206 			__machine__remove_thread(machine, t, false);
207 		}
208 		up_write(&threads->lock);
209 	}
210 }
211 
212 void machine__exit(struct machine *machine)
213 {
214 	int i;
215 
216 	if (machine == NULL)
217 		return;
218 
219 	machine__destroy_kernel_maps(machine);
220 	map_groups__exit(&machine->kmaps);
221 	dsos__exit(&machine->dsos);
222 	machine__exit_vdso(machine);
223 	zfree(&machine->root_dir);
224 	zfree(&machine->mmap_name);
225 	zfree(&machine->current_tid);
226 
227 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
228 		struct threads *threads = &machine->threads[i];
229 		struct thread *thread, *n;
230 		/*
231 		 * Forget about the dead, at this point whatever threads were
232 		 * left in the dead lists better have a reference count taken
233 		 * by who is using them, and then, when they drop those references
234 		 * and it finally hits zero, thread__put() will check and see that
235 		 * its not in the dead threads list and will not try to remove it
236 		 * from there, just calling thread__delete() straight away.
237 		 */
238 		list_for_each_entry_safe(thread, n, &threads->dead, node)
239 			list_del_init(&thread->node);
240 
241 		exit_rwsem(&threads->lock);
242 	}
243 }
244 
245 void machine__delete(struct machine *machine)
246 {
247 	if (machine) {
248 		machine__exit(machine);
249 		free(machine);
250 	}
251 }
252 
253 void machines__init(struct machines *machines)
254 {
255 	machine__init(&machines->host, "", HOST_KERNEL_ID);
256 	machines->guests = RB_ROOT_CACHED;
257 }
258 
259 void machines__exit(struct machines *machines)
260 {
261 	machine__exit(&machines->host);
262 	/* XXX exit guest */
263 }
264 
265 struct machine *machines__add(struct machines *machines, pid_t pid,
266 			      const char *root_dir)
267 {
268 	struct rb_node **p = &machines->guests.rb_root.rb_node;
269 	struct rb_node *parent = NULL;
270 	struct machine *pos, *machine = malloc(sizeof(*machine));
271 	bool leftmost = true;
272 
273 	if (machine == NULL)
274 		return NULL;
275 
276 	if (machine__init(machine, root_dir, pid) != 0) {
277 		free(machine);
278 		return NULL;
279 	}
280 
281 	while (*p != NULL) {
282 		parent = *p;
283 		pos = rb_entry(parent, struct machine, rb_node);
284 		if (pid < pos->pid)
285 			p = &(*p)->rb_left;
286 		else {
287 			p = &(*p)->rb_right;
288 			leftmost = false;
289 		}
290 	}
291 
292 	rb_link_node(&machine->rb_node, parent, p);
293 	rb_insert_color_cached(&machine->rb_node, &machines->guests, leftmost);
294 
295 	return machine;
296 }
297 
298 void machines__set_comm_exec(struct machines *machines, bool comm_exec)
299 {
300 	struct rb_node *nd;
301 
302 	machines->host.comm_exec = comm_exec;
303 
304 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
305 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
306 
307 		machine->comm_exec = comm_exec;
308 	}
309 }
310 
311 struct machine *machines__find(struct machines *machines, pid_t pid)
312 {
313 	struct rb_node **p = &machines->guests.rb_root.rb_node;
314 	struct rb_node *parent = NULL;
315 	struct machine *machine;
316 	struct machine *default_machine = NULL;
317 
318 	if (pid == HOST_KERNEL_ID)
319 		return &machines->host;
320 
321 	while (*p != NULL) {
322 		parent = *p;
323 		machine = rb_entry(parent, struct machine, rb_node);
324 		if (pid < machine->pid)
325 			p = &(*p)->rb_left;
326 		else if (pid > machine->pid)
327 			p = &(*p)->rb_right;
328 		else
329 			return machine;
330 		if (!machine->pid)
331 			default_machine = machine;
332 	}
333 
334 	return default_machine;
335 }
336 
337 struct machine *machines__findnew(struct machines *machines, pid_t pid)
338 {
339 	char path[PATH_MAX];
340 	const char *root_dir = "";
341 	struct machine *machine = machines__find(machines, pid);
342 
343 	if (machine && (machine->pid == pid))
344 		goto out;
345 
346 	if ((pid != HOST_KERNEL_ID) &&
347 	    (pid != DEFAULT_GUEST_KERNEL_ID) &&
348 	    (symbol_conf.guestmount)) {
349 		sprintf(path, "%s/%d", symbol_conf.guestmount, pid);
350 		if (access(path, R_OK)) {
351 			static struct strlist *seen;
352 
353 			if (!seen)
354 				seen = strlist__new(NULL, NULL);
355 
356 			if (!strlist__has_entry(seen, path)) {
357 				pr_err("Can't access file %s\n", path);
358 				strlist__add(seen, path);
359 			}
360 			machine = NULL;
361 			goto out;
362 		}
363 		root_dir = path;
364 	}
365 
366 	machine = machines__add(machines, pid, root_dir);
367 out:
368 	return machine;
369 }
370 
371 void machines__process_guests(struct machines *machines,
372 			      machine__process_t process, void *data)
373 {
374 	struct rb_node *nd;
375 
376 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
377 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
378 		process(pos, data);
379 	}
380 }
381 
382 void machines__set_id_hdr_size(struct machines *machines, u16 id_hdr_size)
383 {
384 	struct rb_node *node;
385 	struct machine *machine;
386 
387 	machines->host.id_hdr_size = id_hdr_size;
388 
389 	for (node = rb_first_cached(&machines->guests); node;
390 	     node = rb_next(node)) {
391 		machine = rb_entry(node, struct machine, rb_node);
392 		machine->id_hdr_size = id_hdr_size;
393 	}
394 
395 	return;
396 }
397 
398 static void machine__update_thread_pid(struct machine *machine,
399 				       struct thread *th, pid_t pid)
400 {
401 	struct thread *leader;
402 
403 	if (pid == th->pid_ || pid == -1 || th->pid_ != -1)
404 		return;
405 
406 	th->pid_ = pid;
407 
408 	if (th->pid_ == th->tid)
409 		return;
410 
411 	leader = __machine__findnew_thread(machine, th->pid_, th->pid_);
412 	if (!leader)
413 		goto out_err;
414 
415 	if (!leader->mg)
416 		leader->mg = map_groups__new(machine);
417 
418 	if (!leader->mg)
419 		goto out_err;
420 
421 	if (th->mg == leader->mg)
422 		return;
423 
424 	if (th->mg) {
425 		/*
426 		 * Maps are created from MMAP events which provide the pid and
427 		 * tid.  Consequently there never should be any maps on a thread
428 		 * with an unknown pid.  Just print an error if there are.
429 		 */
430 		if (!map_groups__empty(th->mg))
431 			pr_err("Discarding thread maps for %d:%d\n",
432 			       th->pid_, th->tid);
433 		map_groups__put(th->mg);
434 	}
435 
436 	th->mg = map_groups__get(leader->mg);
437 out_put:
438 	thread__put(leader);
439 	return;
440 out_err:
441 	pr_err("Failed to join map groups for %d:%d\n", th->pid_, th->tid);
442 	goto out_put;
443 }
444 
445 /*
446  * Front-end cache - TID lookups come in blocks,
447  * so most of the time we dont have to look up
448  * the full rbtree:
449  */
450 static struct thread*
451 __threads__get_last_match(struct threads *threads, struct machine *machine,
452 			  int pid, int tid)
453 {
454 	struct thread *th;
455 
456 	th = threads->last_match;
457 	if (th != NULL) {
458 		if (th->tid == tid) {
459 			machine__update_thread_pid(machine, th, pid);
460 			return thread__get(th);
461 		}
462 
463 		threads->last_match = NULL;
464 	}
465 
466 	return NULL;
467 }
468 
469 static struct thread*
470 threads__get_last_match(struct threads *threads, struct machine *machine,
471 			int pid, int tid)
472 {
473 	struct thread *th = NULL;
474 
475 	if (perf_singlethreaded)
476 		th = __threads__get_last_match(threads, machine, pid, tid);
477 
478 	return th;
479 }
480 
481 static void
482 __threads__set_last_match(struct threads *threads, struct thread *th)
483 {
484 	threads->last_match = th;
485 }
486 
487 static void
488 threads__set_last_match(struct threads *threads, struct thread *th)
489 {
490 	if (perf_singlethreaded)
491 		__threads__set_last_match(threads, th);
492 }
493 
494 /*
495  * Caller must eventually drop thread->refcnt returned with a successful
496  * lookup/new thread inserted.
497  */
498 static struct thread *____machine__findnew_thread(struct machine *machine,
499 						  struct threads *threads,
500 						  pid_t pid, pid_t tid,
501 						  bool create)
502 {
503 	struct rb_node **p = &threads->entries.rb_root.rb_node;
504 	struct rb_node *parent = NULL;
505 	struct thread *th;
506 	bool leftmost = true;
507 
508 	th = threads__get_last_match(threads, machine, pid, tid);
509 	if (th)
510 		return th;
511 
512 	while (*p != NULL) {
513 		parent = *p;
514 		th = rb_entry(parent, struct thread, rb_node);
515 
516 		if (th->tid == tid) {
517 			threads__set_last_match(threads, th);
518 			machine__update_thread_pid(machine, th, pid);
519 			return thread__get(th);
520 		}
521 
522 		if (tid < th->tid)
523 			p = &(*p)->rb_left;
524 		else {
525 			p = &(*p)->rb_right;
526 			leftmost = false;
527 		}
528 	}
529 
530 	if (!create)
531 		return NULL;
532 
533 	th = thread__new(pid, tid);
534 	if (th != NULL) {
535 		rb_link_node(&th->rb_node, parent, p);
536 		rb_insert_color_cached(&th->rb_node, &threads->entries, leftmost);
537 
538 		/*
539 		 * We have to initialize map_groups separately
540 		 * after rb tree is updated.
541 		 *
542 		 * The reason is that we call machine__findnew_thread
543 		 * within thread__init_map_groups to find the thread
544 		 * leader and that would screwed the rb tree.
545 		 */
546 		if (thread__init_map_groups(th, machine)) {
547 			rb_erase_cached(&th->rb_node, &threads->entries);
548 			RB_CLEAR_NODE(&th->rb_node);
549 			thread__put(th);
550 			return NULL;
551 		}
552 		/*
553 		 * It is now in the rbtree, get a ref
554 		 */
555 		thread__get(th);
556 		threads__set_last_match(threads, th);
557 		++threads->nr;
558 	}
559 
560 	return th;
561 }
562 
563 struct thread *__machine__findnew_thread(struct machine *machine, pid_t pid, pid_t tid)
564 {
565 	return ____machine__findnew_thread(machine, machine__threads(machine, tid), pid, tid, true);
566 }
567 
568 struct thread *machine__findnew_thread(struct machine *machine, pid_t pid,
569 				       pid_t tid)
570 {
571 	struct threads *threads = machine__threads(machine, tid);
572 	struct thread *th;
573 
574 	down_write(&threads->lock);
575 	th = __machine__findnew_thread(machine, pid, tid);
576 	up_write(&threads->lock);
577 	return th;
578 }
579 
580 struct thread *machine__find_thread(struct machine *machine, pid_t pid,
581 				    pid_t tid)
582 {
583 	struct threads *threads = machine__threads(machine, tid);
584 	struct thread *th;
585 
586 	down_read(&threads->lock);
587 	th =  ____machine__findnew_thread(machine, threads, pid, tid, false);
588 	up_read(&threads->lock);
589 	return th;
590 }
591 
592 struct comm *machine__thread_exec_comm(struct machine *machine,
593 				       struct thread *thread)
594 {
595 	if (machine->comm_exec)
596 		return thread__exec_comm(thread);
597 	else
598 		return thread__comm(thread);
599 }
600 
601 int machine__process_comm_event(struct machine *machine, union perf_event *event,
602 				struct perf_sample *sample)
603 {
604 	struct thread *thread = machine__findnew_thread(machine,
605 							event->comm.pid,
606 							event->comm.tid);
607 	bool exec = event->header.misc & PERF_RECORD_MISC_COMM_EXEC;
608 	int err = 0;
609 
610 	if (exec)
611 		machine->comm_exec = true;
612 
613 	if (dump_trace)
614 		perf_event__fprintf_comm(event, stdout);
615 
616 	if (thread == NULL ||
617 	    __thread__set_comm(thread, event->comm.comm, sample->time, exec)) {
618 		dump_printf("problem processing PERF_RECORD_COMM, skipping event.\n");
619 		err = -1;
620 	}
621 
622 	thread__put(thread);
623 
624 	return err;
625 }
626 
627 int machine__process_namespaces_event(struct machine *machine __maybe_unused,
628 				      union perf_event *event,
629 				      struct perf_sample *sample __maybe_unused)
630 {
631 	struct thread *thread = machine__findnew_thread(machine,
632 							event->namespaces.pid,
633 							event->namespaces.tid);
634 	int err = 0;
635 
636 	WARN_ONCE(event->namespaces.nr_namespaces > NR_NAMESPACES,
637 		  "\nWARNING: kernel seems to support more namespaces than perf"
638 		  " tool.\nTry updating the perf tool..\n\n");
639 
640 	WARN_ONCE(event->namespaces.nr_namespaces < NR_NAMESPACES,
641 		  "\nWARNING: perf tool seems to support more namespaces than"
642 		  " the kernel.\nTry updating the kernel..\n\n");
643 
644 	if (dump_trace)
645 		perf_event__fprintf_namespaces(event, stdout);
646 
647 	if (thread == NULL ||
648 	    thread__set_namespaces(thread, sample->time, &event->namespaces)) {
649 		dump_printf("problem processing PERF_RECORD_NAMESPACES, skipping event.\n");
650 		err = -1;
651 	}
652 
653 	thread__put(thread);
654 
655 	return err;
656 }
657 
658 int machine__process_lost_event(struct machine *machine __maybe_unused,
659 				union perf_event *event, struct perf_sample *sample __maybe_unused)
660 {
661 	dump_printf(": id:%" PRI_lu64 ": lost:%" PRI_lu64 "\n",
662 		    event->lost.id, event->lost.lost);
663 	return 0;
664 }
665 
666 int machine__process_lost_samples_event(struct machine *machine __maybe_unused,
667 					union perf_event *event, struct perf_sample *sample)
668 {
669 	dump_printf(": id:%" PRIu64 ": lost samples :%" PRI_lu64 "\n",
670 		    sample->id, event->lost_samples.lost);
671 	return 0;
672 }
673 
674 static struct dso *machine__findnew_module_dso(struct machine *machine,
675 					       struct kmod_path *m,
676 					       const char *filename)
677 {
678 	struct dso *dso;
679 
680 	down_write(&machine->dsos.lock);
681 
682 	dso = __dsos__find(&machine->dsos, m->name, true);
683 	if (!dso) {
684 		dso = __dsos__addnew(&machine->dsos, m->name);
685 		if (dso == NULL)
686 			goto out_unlock;
687 
688 		dso__set_module_info(dso, m, machine);
689 		dso__set_long_name(dso, strdup(filename), true);
690 	}
691 
692 	dso__get(dso);
693 out_unlock:
694 	up_write(&machine->dsos.lock);
695 	return dso;
696 }
697 
698 int machine__process_aux_event(struct machine *machine __maybe_unused,
699 			       union perf_event *event)
700 {
701 	if (dump_trace)
702 		perf_event__fprintf_aux(event, stdout);
703 	return 0;
704 }
705 
706 int machine__process_itrace_start_event(struct machine *machine __maybe_unused,
707 					union perf_event *event)
708 {
709 	if (dump_trace)
710 		perf_event__fprintf_itrace_start(event, stdout);
711 	return 0;
712 }
713 
714 int machine__process_switch_event(struct machine *machine __maybe_unused,
715 				  union perf_event *event)
716 {
717 	if (dump_trace)
718 		perf_event__fprintf_switch(event, stdout);
719 	return 0;
720 }
721 
722 static int machine__process_ksymbol_register(struct machine *machine,
723 					     union perf_event *event,
724 					     struct perf_sample *sample __maybe_unused)
725 {
726 	struct symbol *sym;
727 	struct map *map;
728 
729 	map = map_groups__find(&machine->kmaps, event->ksymbol.addr);
730 	if (!map) {
731 		map = dso__new_map(event->ksymbol.name);
732 		if (!map)
733 			return -ENOMEM;
734 
735 		map->start = event->ksymbol.addr;
736 		map->end = map->start + event->ksymbol.len;
737 		map_groups__insert(&machine->kmaps, map);
738 	}
739 
740 	sym = symbol__new(map->map_ip(map, map->start),
741 			  event->ksymbol.len,
742 			  0, 0, event->ksymbol.name);
743 	if (!sym)
744 		return -ENOMEM;
745 	dso__insert_symbol(map->dso, sym);
746 	return 0;
747 }
748 
749 static int machine__process_ksymbol_unregister(struct machine *machine,
750 					       union perf_event *event,
751 					       struct perf_sample *sample __maybe_unused)
752 {
753 	struct map *map;
754 
755 	map = map_groups__find(&machine->kmaps, event->ksymbol.addr);
756 	if (map)
757 		map_groups__remove(&machine->kmaps, map);
758 
759 	return 0;
760 }
761 
762 int machine__process_ksymbol(struct machine *machine __maybe_unused,
763 			     union perf_event *event,
764 			     struct perf_sample *sample)
765 {
766 	if (dump_trace)
767 		perf_event__fprintf_ksymbol(event, stdout);
768 
769 	if (event->ksymbol.flags & PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER)
770 		return machine__process_ksymbol_unregister(machine, event,
771 							   sample);
772 	return machine__process_ksymbol_register(machine, event, sample);
773 }
774 
775 static void dso__adjust_kmod_long_name(struct dso *dso, const char *filename)
776 {
777 	const char *dup_filename;
778 
779 	if (!filename || !dso || !dso->long_name)
780 		return;
781 	if (dso->long_name[0] != '[')
782 		return;
783 	if (!strchr(filename, '/'))
784 		return;
785 
786 	dup_filename = strdup(filename);
787 	if (!dup_filename)
788 		return;
789 
790 	dso__set_long_name(dso, dup_filename, true);
791 }
792 
793 struct map *machine__findnew_module_map(struct machine *machine, u64 start,
794 					const char *filename)
795 {
796 	struct map *map = NULL;
797 	struct dso *dso = NULL;
798 	struct kmod_path m;
799 
800 	if (kmod_path__parse_name(&m, filename))
801 		return NULL;
802 
803 	map = map_groups__find_by_name(&machine->kmaps, m.name);
804 	if (map) {
805 		/*
806 		 * If the map's dso is an offline module, give dso__load()
807 		 * a chance to find the file path of that module by fixing
808 		 * long_name.
809 		 */
810 		dso__adjust_kmod_long_name(map->dso, filename);
811 		goto out;
812 	}
813 
814 	dso = machine__findnew_module_dso(machine, &m, filename);
815 	if (dso == NULL)
816 		goto out;
817 
818 	map = map__new2(start, dso);
819 	if (map == NULL)
820 		goto out;
821 
822 	map_groups__insert(&machine->kmaps, map);
823 
824 	/* Put the map here because map_groups__insert alread got it */
825 	map__put(map);
826 out:
827 	/* put the dso here, corresponding to  machine__findnew_module_dso */
828 	dso__put(dso);
829 	zfree(&m.name);
830 	return map;
831 }
832 
833 size_t machines__fprintf_dsos(struct machines *machines, FILE *fp)
834 {
835 	struct rb_node *nd;
836 	size_t ret = __dsos__fprintf(&machines->host.dsos.head, fp);
837 
838 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
839 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
840 		ret += __dsos__fprintf(&pos->dsos.head, fp);
841 	}
842 
843 	return ret;
844 }
845 
846 size_t machine__fprintf_dsos_buildid(struct machine *m, FILE *fp,
847 				     bool (skip)(struct dso *dso, int parm), int parm)
848 {
849 	return __dsos__fprintf_buildid(&m->dsos.head, fp, skip, parm);
850 }
851 
852 size_t machines__fprintf_dsos_buildid(struct machines *machines, FILE *fp,
853 				     bool (skip)(struct dso *dso, int parm), int parm)
854 {
855 	struct rb_node *nd;
856 	size_t ret = machine__fprintf_dsos_buildid(&machines->host, fp, skip, parm);
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 += machine__fprintf_dsos_buildid(pos, fp, skip, parm);
861 	}
862 	return ret;
863 }
864 
865 size_t machine__fprintf_vmlinux_path(struct machine *machine, FILE *fp)
866 {
867 	int i;
868 	size_t printed = 0;
869 	struct dso *kdso = machine__kernel_dso(machine);
870 
871 	if (kdso->has_build_id) {
872 		char filename[PATH_MAX];
873 		if (dso__build_id_filename(kdso, filename, sizeof(filename),
874 					   false))
875 			printed += fprintf(fp, "[0] %s\n", filename);
876 	}
877 
878 	for (i = 0; i < vmlinux_path__nr_entries; ++i)
879 		printed += fprintf(fp, "[%d] %s\n",
880 				   i + kdso->has_build_id, vmlinux_path[i]);
881 
882 	return printed;
883 }
884 
885 size_t machine__fprintf(struct machine *machine, FILE *fp)
886 {
887 	struct rb_node *nd;
888 	size_t ret;
889 	int i;
890 
891 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
892 		struct threads *threads = &machine->threads[i];
893 
894 		down_read(&threads->lock);
895 
896 		ret = fprintf(fp, "Threads: %u\n", threads->nr);
897 
898 		for (nd = rb_first_cached(&threads->entries); nd;
899 		     nd = rb_next(nd)) {
900 			struct thread *pos = rb_entry(nd, struct thread, rb_node);
901 
902 			ret += thread__fprintf(pos, fp);
903 		}
904 
905 		up_read(&threads->lock);
906 	}
907 	return ret;
908 }
909 
910 static struct dso *machine__get_kernel(struct machine *machine)
911 {
912 	const char *vmlinux_name = machine->mmap_name;
913 	struct dso *kernel;
914 
915 	if (machine__is_host(machine)) {
916 		if (symbol_conf.vmlinux_name)
917 			vmlinux_name = symbol_conf.vmlinux_name;
918 
919 		kernel = machine__findnew_kernel(machine, vmlinux_name,
920 						 "[kernel]", DSO_TYPE_KERNEL);
921 	} else {
922 		if (symbol_conf.default_guest_vmlinux_name)
923 			vmlinux_name = symbol_conf.default_guest_vmlinux_name;
924 
925 		kernel = machine__findnew_kernel(machine, vmlinux_name,
926 						 "[guest.kernel]",
927 						 DSO_TYPE_GUEST_KERNEL);
928 	}
929 
930 	if (kernel != NULL && (!kernel->has_build_id))
931 		dso__read_running_kernel_build_id(kernel, machine);
932 
933 	return kernel;
934 }
935 
936 struct process_args {
937 	u64 start;
938 };
939 
940 void machine__get_kallsyms_filename(struct machine *machine, char *buf,
941 				    size_t bufsz)
942 {
943 	if (machine__is_default_guest(machine))
944 		scnprintf(buf, bufsz, "%s", symbol_conf.default_guest_kallsyms);
945 	else
946 		scnprintf(buf, bufsz, "%s/proc/kallsyms", machine->root_dir);
947 }
948 
949 const char *ref_reloc_sym_names[] = {"_text", "_stext", NULL};
950 
951 /* Figure out the start address of kernel map from /proc/kallsyms.
952  * Returns the name of the start symbol in *symbol_name. Pass in NULL as
953  * symbol_name if it's not that important.
954  */
955 static int machine__get_running_kernel_start(struct machine *machine,
956 					     const char **symbol_name,
957 					     u64 *start, u64 *end)
958 {
959 	char filename[PATH_MAX];
960 	int i, err = -1;
961 	const char *name;
962 	u64 addr = 0;
963 
964 	machine__get_kallsyms_filename(machine, filename, PATH_MAX);
965 
966 	if (symbol__restricted_filename(filename, "/proc/kallsyms"))
967 		return 0;
968 
969 	for (i = 0; (name = ref_reloc_sym_names[i]) != NULL; i++) {
970 		err = kallsyms__get_function_start(filename, name, &addr);
971 		if (!err)
972 			break;
973 	}
974 
975 	if (err)
976 		return -1;
977 
978 	if (symbol_name)
979 		*symbol_name = name;
980 
981 	*start = addr;
982 
983 	err = kallsyms__get_function_start(filename, "_etext", &addr);
984 	if (!err)
985 		*end = addr;
986 
987 	return 0;
988 }
989 
990 int machine__create_extra_kernel_map(struct machine *machine,
991 				     struct dso *kernel,
992 				     struct extra_kernel_map *xm)
993 {
994 	struct kmap *kmap;
995 	struct map *map;
996 
997 	map = map__new2(xm->start, kernel);
998 	if (!map)
999 		return -1;
1000 
1001 	map->end   = xm->end;
1002 	map->pgoff = xm->pgoff;
1003 
1004 	kmap = map__kmap(map);
1005 
1006 	kmap->kmaps = &machine->kmaps;
1007 	strlcpy(kmap->name, xm->name, KMAP_NAME_LEN);
1008 
1009 	map_groups__insert(&machine->kmaps, map);
1010 
1011 	pr_debug2("Added extra kernel map %s %" PRIx64 "-%" PRIx64 "\n",
1012 		  kmap->name, map->start, map->end);
1013 
1014 	map__put(map);
1015 
1016 	return 0;
1017 }
1018 
1019 static u64 find_entry_trampoline(struct dso *dso)
1020 {
1021 	/* Duplicates are removed so lookup all aliases */
1022 	const char *syms[] = {
1023 		"_entry_trampoline",
1024 		"__entry_trampoline_start",
1025 		"entry_SYSCALL_64_trampoline",
1026 	};
1027 	struct symbol *sym = dso__first_symbol(dso);
1028 	unsigned int i;
1029 
1030 	for (; sym; sym = dso__next_symbol(sym)) {
1031 		if (sym->binding != STB_GLOBAL)
1032 			continue;
1033 		for (i = 0; i < ARRAY_SIZE(syms); i++) {
1034 			if (!strcmp(sym->name, syms[i]))
1035 				return sym->start;
1036 		}
1037 	}
1038 
1039 	return 0;
1040 }
1041 
1042 /*
1043  * These values can be used for kernels that do not have symbols for the entry
1044  * trampolines in kallsyms.
1045  */
1046 #define X86_64_CPU_ENTRY_AREA_PER_CPU	0xfffffe0000000000ULL
1047 #define X86_64_CPU_ENTRY_AREA_SIZE	0x2c000
1048 #define X86_64_ENTRY_TRAMPOLINE		0x6000
1049 
1050 /* Map x86_64 PTI entry trampolines */
1051 int machine__map_x86_64_entry_trampolines(struct machine *machine,
1052 					  struct dso *kernel)
1053 {
1054 	struct map_groups *kmaps = &machine->kmaps;
1055 	struct maps *maps = &kmaps->maps;
1056 	int nr_cpus_avail, cpu;
1057 	bool found = false;
1058 	struct map *map;
1059 	u64 pgoff;
1060 
1061 	/*
1062 	 * In the vmlinux case, pgoff is a virtual address which must now be
1063 	 * mapped to a vmlinux offset.
1064 	 */
1065 	maps__for_each_entry(maps, map) {
1066 		struct kmap *kmap = __map__kmap(map);
1067 		struct map *dest_map;
1068 
1069 		if (!kmap || !is_entry_trampoline(kmap->name))
1070 			continue;
1071 
1072 		dest_map = map_groups__find(kmaps, map->pgoff);
1073 		if (dest_map != map)
1074 			map->pgoff = dest_map->map_ip(dest_map, map->pgoff);
1075 		found = true;
1076 	}
1077 	if (found || machine->trampolines_mapped)
1078 		return 0;
1079 
1080 	pgoff = find_entry_trampoline(kernel);
1081 	if (!pgoff)
1082 		return 0;
1083 
1084 	nr_cpus_avail = machine__nr_cpus_avail(machine);
1085 
1086 	/* Add a 1 page map for each CPU's entry trampoline */
1087 	for (cpu = 0; cpu < nr_cpus_avail; cpu++) {
1088 		u64 va = X86_64_CPU_ENTRY_AREA_PER_CPU +
1089 			 cpu * X86_64_CPU_ENTRY_AREA_SIZE +
1090 			 X86_64_ENTRY_TRAMPOLINE;
1091 		struct extra_kernel_map xm = {
1092 			.start = va,
1093 			.end   = va + page_size,
1094 			.pgoff = pgoff,
1095 		};
1096 
1097 		strlcpy(xm.name, ENTRY_TRAMPOLINE_NAME, KMAP_NAME_LEN);
1098 
1099 		if (machine__create_extra_kernel_map(machine, kernel, &xm) < 0)
1100 			return -1;
1101 	}
1102 
1103 	machine->trampolines_mapped = nr_cpus_avail;
1104 
1105 	return 0;
1106 }
1107 
1108 int __weak machine__create_extra_kernel_maps(struct machine *machine __maybe_unused,
1109 					     struct dso *kernel __maybe_unused)
1110 {
1111 	return 0;
1112 }
1113 
1114 static int
1115 __machine__create_kernel_maps(struct machine *machine, struct dso *kernel)
1116 {
1117 	struct kmap *kmap;
1118 	struct map *map;
1119 
1120 	/* In case of renewal the kernel map, destroy previous one */
1121 	machine__destroy_kernel_maps(machine);
1122 
1123 	machine->vmlinux_map = map__new2(0, kernel);
1124 	if (machine->vmlinux_map == NULL)
1125 		return -1;
1126 
1127 	machine->vmlinux_map->map_ip = machine->vmlinux_map->unmap_ip = identity__map_ip;
1128 	map = machine__kernel_map(machine);
1129 	kmap = map__kmap(map);
1130 	if (!kmap)
1131 		return -1;
1132 
1133 	kmap->kmaps = &machine->kmaps;
1134 	map_groups__insert(&machine->kmaps, map);
1135 
1136 	return 0;
1137 }
1138 
1139 void machine__destroy_kernel_maps(struct machine *machine)
1140 {
1141 	struct kmap *kmap;
1142 	struct map *map = machine__kernel_map(machine);
1143 
1144 	if (map == NULL)
1145 		return;
1146 
1147 	kmap = map__kmap(map);
1148 	map_groups__remove(&machine->kmaps, map);
1149 	if (kmap && kmap->ref_reloc_sym) {
1150 		zfree((char **)&kmap->ref_reloc_sym->name);
1151 		zfree(&kmap->ref_reloc_sym);
1152 	}
1153 
1154 	map__zput(machine->vmlinux_map);
1155 }
1156 
1157 int machines__create_guest_kernel_maps(struct machines *machines)
1158 {
1159 	int ret = 0;
1160 	struct dirent **namelist = NULL;
1161 	int i, items = 0;
1162 	char path[PATH_MAX];
1163 	pid_t pid;
1164 	char *endp;
1165 
1166 	if (symbol_conf.default_guest_vmlinux_name ||
1167 	    symbol_conf.default_guest_modules ||
1168 	    symbol_conf.default_guest_kallsyms) {
1169 		machines__create_kernel_maps(machines, DEFAULT_GUEST_KERNEL_ID);
1170 	}
1171 
1172 	if (symbol_conf.guestmount) {
1173 		items = scandir(symbol_conf.guestmount, &namelist, NULL, NULL);
1174 		if (items <= 0)
1175 			return -ENOENT;
1176 		for (i = 0; i < items; i++) {
1177 			if (!isdigit(namelist[i]->d_name[0])) {
1178 				/* Filter out . and .. */
1179 				continue;
1180 			}
1181 			pid = (pid_t)strtol(namelist[i]->d_name, &endp, 10);
1182 			if ((*endp != '\0') ||
1183 			    (endp == namelist[i]->d_name) ||
1184 			    (errno == ERANGE)) {
1185 				pr_debug("invalid directory (%s). Skipping.\n",
1186 					 namelist[i]->d_name);
1187 				continue;
1188 			}
1189 			sprintf(path, "%s/%s/proc/kallsyms",
1190 				symbol_conf.guestmount,
1191 				namelist[i]->d_name);
1192 			ret = access(path, R_OK);
1193 			if (ret) {
1194 				pr_debug("Can't access file %s\n", path);
1195 				goto failure;
1196 			}
1197 			machines__create_kernel_maps(machines, pid);
1198 		}
1199 failure:
1200 		free(namelist);
1201 	}
1202 
1203 	return ret;
1204 }
1205 
1206 void machines__destroy_kernel_maps(struct machines *machines)
1207 {
1208 	struct rb_node *next = rb_first_cached(&machines->guests);
1209 
1210 	machine__destroy_kernel_maps(&machines->host);
1211 
1212 	while (next) {
1213 		struct machine *pos = rb_entry(next, struct machine, rb_node);
1214 
1215 		next = rb_next(&pos->rb_node);
1216 		rb_erase_cached(&pos->rb_node, &machines->guests);
1217 		machine__delete(pos);
1218 	}
1219 }
1220 
1221 int machines__create_kernel_maps(struct machines *machines, pid_t pid)
1222 {
1223 	struct machine *machine = machines__findnew(machines, pid);
1224 
1225 	if (machine == NULL)
1226 		return -1;
1227 
1228 	return machine__create_kernel_maps(machine);
1229 }
1230 
1231 int machine__load_kallsyms(struct machine *machine, const char *filename)
1232 {
1233 	struct map *map = machine__kernel_map(machine);
1234 	int ret = __dso__load_kallsyms(map->dso, filename, map, true);
1235 
1236 	if (ret > 0) {
1237 		dso__set_loaded(map->dso);
1238 		/*
1239 		 * Since /proc/kallsyms will have multiple sessions for the
1240 		 * kernel, with modules between them, fixup the end of all
1241 		 * sections.
1242 		 */
1243 		map_groups__fixup_end(&machine->kmaps);
1244 	}
1245 
1246 	return ret;
1247 }
1248 
1249 int machine__load_vmlinux_path(struct machine *machine)
1250 {
1251 	struct map *map = machine__kernel_map(machine);
1252 	int ret = dso__load_vmlinux_path(map->dso, map);
1253 
1254 	if (ret > 0)
1255 		dso__set_loaded(map->dso);
1256 
1257 	return ret;
1258 }
1259 
1260 static char *get_kernel_version(const char *root_dir)
1261 {
1262 	char version[PATH_MAX];
1263 	FILE *file;
1264 	char *name, *tmp;
1265 	const char *prefix = "Linux version ";
1266 
1267 	sprintf(version, "%s/proc/version", root_dir);
1268 	file = fopen(version, "r");
1269 	if (!file)
1270 		return NULL;
1271 
1272 	tmp = fgets(version, sizeof(version), file);
1273 	fclose(file);
1274 	if (!tmp)
1275 		return NULL;
1276 
1277 	name = strstr(version, prefix);
1278 	if (!name)
1279 		return NULL;
1280 	name += strlen(prefix);
1281 	tmp = strchr(name, ' ');
1282 	if (tmp)
1283 		*tmp = '\0';
1284 
1285 	return strdup(name);
1286 }
1287 
1288 static bool is_kmod_dso(struct dso *dso)
1289 {
1290 	return dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE ||
1291 	       dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE;
1292 }
1293 
1294 static int map_groups__set_module_path(struct map_groups *mg, const char *path,
1295 				       struct kmod_path *m)
1296 {
1297 	char *long_name;
1298 	struct map *map = map_groups__find_by_name(mg, m->name);
1299 
1300 	if (map == NULL)
1301 		return 0;
1302 
1303 	long_name = strdup(path);
1304 	if (long_name == NULL)
1305 		return -ENOMEM;
1306 
1307 	dso__set_long_name(map->dso, long_name, true);
1308 	dso__kernel_module_get_build_id(map->dso, "");
1309 
1310 	/*
1311 	 * Full name could reveal us kmod compression, so
1312 	 * we need to update the symtab_type if needed.
1313 	 */
1314 	if (m->comp && is_kmod_dso(map->dso)) {
1315 		map->dso->symtab_type++;
1316 		map->dso->comp = m->comp;
1317 	}
1318 
1319 	return 0;
1320 }
1321 
1322 static int map_groups__set_modules_path_dir(struct map_groups *mg,
1323 				const char *dir_name, int depth)
1324 {
1325 	struct dirent *dent;
1326 	DIR *dir = opendir(dir_name);
1327 	int ret = 0;
1328 
1329 	if (!dir) {
1330 		pr_debug("%s: cannot open %s dir\n", __func__, dir_name);
1331 		return -1;
1332 	}
1333 
1334 	while ((dent = readdir(dir)) != NULL) {
1335 		char path[PATH_MAX];
1336 		struct stat st;
1337 
1338 		/*sshfs might return bad dent->d_type, so we have to stat*/
1339 		snprintf(path, sizeof(path), "%s/%s", dir_name, dent->d_name);
1340 		if (stat(path, &st))
1341 			continue;
1342 
1343 		if (S_ISDIR(st.st_mode)) {
1344 			if (!strcmp(dent->d_name, ".") ||
1345 			    !strcmp(dent->d_name, ".."))
1346 				continue;
1347 
1348 			/* Do not follow top-level source and build symlinks */
1349 			if (depth == 0) {
1350 				if (!strcmp(dent->d_name, "source") ||
1351 				    !strcmp(dent->d_name, "build"))
1352 					continue;
1353 			}
1354 
1355 			ret = map_groups__set_modules_path_dir(mg, path,
1356 							       depth + 1);
1357 			if (ret < 0)
1358 				goto out;
1359 		} else {
1360 			struct kmod_path m;
1361 
1362 			ret = kmod_path__parse_name(&m, dent->d_name);
1363 			if (ret)
1364 				goto out;
1365 
1366 			if (m.kmod)
1367 				ret = map_groups__set_module_path(mg, path, &m);
1368 
1369 			zfree(&m.name);
1370 
1371 			if (ret)
1372 				goto out;
1373 		}
1374 	}
1375 
1376 out:
1377 	closedir(dir);
1378 	return ret;
1379 }
1380 
1381 static int machine__set_modules_path(struct machine *machine)
1382 {
1383 	char *version;
1384 	char modules_path[PATH_MAX];
1385 
1386 	version = get_kernel_version(machine->root_dir);
1387 	if (!version)
1388 		return -1;
1389 
1390 	snprintf(modules_path, sizeof(modules_path), "%s/lib/modules/%s",
1391 		 machine->root_dir, version);
1392 	free(version);
1393 
1394 	return map_groups__set_modules_path_dir(&machine->kmaps, modules_path, 0);
1395 }
1396 int __weak arch__fix_module_text_start(u64 *start __maybe_unused,
1397 				u64 *size __maybe_unused,
1398 				const char *name __maybe_unused)
1399 {
1400 	return 0;
1401 }
1402 
1403 static int machine__create_module(void *arg, const char *name, u64 start,
1404 				  u64 size)
1405 {
1406 	struct machine *machine = arg;
1407 	struct map *map;
1408 
1409 	if (arch__fix_module_text_start(&start, &size, name) < 0)
1410 		return -1;
1411 
1412 	map = machine__findnew_module_map(machine, start, name);
1413 	if (map == NULL)
1414 		return -1;
1415 	map->end = start + size;
1416 
1417 	dso__kernel_module_get_build_id(map->dso, machine->root_dir);
1418 
1419 	return 0;
1420 }
1421 
1422 static int machine__create_modules(struct machine *machine)
1423 {
1424 	const char *modules;
1425 	char path[PATH_MAX];
1426 
1427 	if (machine__is_default_guest(machine)) {
1428 		modules = symbol_conf.default_guest_modules;
1429 	} else {
1430 		snprintf(path, PATH_MAX, "%s/proc/modules", machine->root_dir);
1431 		modules = path;
1432 	}
1433 
1434 	if (symbol__restricted_filename(modules, "/proc/modules"))
1435 		return -1;
1436 
1437 	if (modules__parse(modules, machine, machine__create_module))
1438 		return -1;
1439 
1440 	if (!machine__set_modules_path(machine))
1441 		return 0;
1442 
1443 	pr_debug("Problems setting modules path maps, continuing anyway...\n");
1444 
1445 	return 0;
1446 }
1447 
1448 static void machine__set_kernel_mmap(struct machine *machine,
1449 				     u64 start, u64 end)
1450 {
1451 	machine->vmlinux_map->start = start;
1452 	machine->vmlinux_map->end   = end;
1453 	/*
1454 	 * Be a bit paranoid here, some perf.data file came with
1455 	 * a zero sized synthesized MMAP event for the kernel.
1456 	 */
1457 	if (start == 0 && end == 0)
1458 		machine->vmlinux_map->end = ~0ULL;
1459 }
1460 
1461 static void machine__update_kernel_mmap(struct machine *machine,
1462 				     u64 start, u64 end)
1463 {
1464 	struct map *map = machine__kernel_map(machine);
1465 
1466 	map__get(map);
1467 	map_groups__remove(&machine->kmaps, map);
1468 
1469 	machine__set_kernel_mmap(machine, start, end);
1470 
1471 	map_groups__insert(&machine->kmaps, map);
1472 	map__put(map);
1473 }
1474 
1475 int machine__create_kernel_maps(struct machine *machine)
1476 {
1477 	struct dso *kernel = machine__get_kernel(machine);
1478 	const char *name = NULL;
1479 	struct map *map;
1480 	u64 start = 0, end = ~0ULL;
1481 	int ret;
1482 
1483 	if (kernel == NULL)
1484 		return -1;
1485 
1486 	ret = __machine__create_kernel_maps(machine, kernel);
1487 	if (ret < 0)
1488 		goto out_put;
1489 
1490 	if (symbol_conf.use_modules && machine__create_modules(machine) < 0) {
1491 		if (machine__is_host(machine))
1492 			pr_debug("Problems creating module maps, "
1493 				 "continuing anyway...\n");
1494 		else
1495 			pr_debug("Problems creating module maps for guest %d, "
1496 				 "continuing anyway...\n", machine->pid);
1497 	}
1498 
1499 	if (!machine__get_running_kernel_start(machine, &name, &start, &end)) {
1500 		if (name &&
1501 		    map__set_kallsyms_ref_reloc_sym(machine->vmlinux_map, name, start)) {
1502 			machine__destroy_kernel_maps(machine);
1503 			ret = -1;
1504 			goto out_put;
1505 		}
1506 
1507 		/*
1508 		 * we have a real start address now, so re-order the kmaps
1509 		 * assume it's the last in the kmaps
1510 		 */
1511 		machine__update_kernel_mmap(machine, start, end);
1512 	}
1513 
1514 	if (machine__create_extra_kernel_maps(machine, kernel))
1515 		pr_debug("Problems creating extra kernel maps, continuing anyway...\n");
1516 
1517 	if (end == ~0ULL) {
1518 		/* update end address of the kernel map using adjacent module address */
1519 		map = map__next(machine__kernel_map(machine));
1520 		if (map)
1521 			machine__set_kernel_mmap(machine, start, map->start);
1522 	}
1523 
1524 out_put:
1525 	dso__put(kernel);
1526 	return ret;
1527 }
1528 
1529 static bool machine__uses_kcore(struct machine *machine)
1530 {
1531 	struct dso *dso;
1532 
1533 	list_for_each_entry(dso, &machine->dsos.head, node) {
1534 		if (dso__is_kcore(dso))
1535 			return true;
1536 	}
1537 
1538 	return false;
1539 }
1540 
1541 static bool perf_event__is_extra_kernel_mmap(struct machine *machine,
1542 					     union perf_event *event)
1543 {
1544 	return machine__is(machine, "x86_64") &&
1545 	       is_entry_trampoline(event->mmap.filename);
1546 }
1547 
1548 static int machine__process_extra_kernel_map(struct machine *machine,
1549 					     union perf_event *event)
1550 {
1551 	struct dso *kernel = machine__kernel_dso(machine);
1552 	struct extra_kernel_map xm = {
1553 		.start = event->mmap.start,
1554 		.end   = event->mmap.start + event->mmap.len,
1555 		.pgoff = event->mmap.pgoff,
1556 	};
1557 
1558 	if (kernel == NULL)
1559 		return -1;
1560 
1561 	strlcpy(xm.name, event->mmap.filename, KMAP_NAME_LEN);
1562 
1563 	return machine__create_extra_kernel_map(machine, kernel, &xm);
1564 }
1565 
1566 static int machine__process_kernel_mmap_event(struct machine *machine,
1567 					      union perf_event *event)
1568 {
1569 	struct map *map;
1570 	enum dso_kernel_type kernel_type;
1571 	bool is_kernel_mmap;
1572 
1573 	/* If we have maps from kcore then we do not need or want any others */
1574 	if (machine__uses_kcore(machine))
1575 		return 0;
1576 
1577 	if (machine__is_host(machine))
1578 		kernel_type = DSO_TYPE_KERNEL;
1579 	else
1580 		kernel_type = DSO_TYPE_GUEST_KERNEL;
1581 
1582 	is_kernel_mmap = memcmp(event->mmap.filename,
1583 				machine->mmap_name,
1584 				strlen(machine->mmap_name) - 1) == 0;
1585 	if (event->mmap.filename[0] == '/' ||
1586 	    (!is_kernel_mmap && event->mmap.filename[0] == '[')) {
1587 		map = machine__findnew_module_map(machine, event->mmap.start,
1588 						  event->mmap.filename);
1589 		if (map == NULL)
1590 			goto out_problem;
1591 
1592 		map->end = map->start + event->mmap.len;
1593 	} else if (is_kernel_mmap) {
1594 		const char *symbol_name = (event->mmap.filename +
1595 				strlen(machine->mmap_name));
1596 		/*
1597 		 * Should be there already, from the build-id table in
1598 		 * the header.
1599 		 */
1600 		struct dso *kernel = NULL;
1601 		struct dso *dso;
1602 
1603 		down_read(&machine->dsos.lock);
1604 
1605 		list_for_each_entry(dso, &machine->dsos.head, node) {
1606 
1607 			/*
1608 			 * The cpumode passed to is_kernel_module is not the
1609 			 * cpumode of *this* event. If we insist on passing
1610 			 * correct cpumode to is_kernel_module, we should
1611 			 * record the cpumode when we adding this dso to the
1612 			 * linked list.
1613 			 *
1614 			 * However we don't really need passing correct
1615 			 * cpumode.  We know the correct cpumode must be kernel
1616 			 * mode (if not, we should not link it onto kernel_dsos
1617 			 * list).
1618 			 *
1619 			 * Therefore, we pass PERF_RECORD_MISC_CPUMODE_UNKNOWN.
1620 			 * is_kernel_module() treats it as a kernel cpumode.
1621 			 */
1622 
1623 			if (!dso->kernel ||
1624 			    is_kernel_module(dso->long_name,
1625 					     PERF_RECORD_MISC_CPUMODE_UNKNOWN))
1626 				continue;
1627 
1628 
1629 			kernel = dso;
1630 			break;
1631 		}
1632 
1633 		up_read(&machine->dsos.lock);
1634 
1635 		if (kernel == NULL)
1636 			kernel = machine__findnew_dso(machine, machine->mmap_name);
1637 		if (kernel == NULL)
1638 			goto out_problem;
1639 
1640 		kernel->kernel = kernel_type;
1641 		if (__machine__create_kernel_maps(machine, kernel) < 0) {
1642 			dso__put(kernel);
1643 			goto out_problem;
1644 		}
1645 
1646 		if (strstr(kernel->long_name, "vmlinux"))
1647 			dso__set_short_name(kernel, "[kernel.vmlinux]", false);
1648 
1649 		machine__update_kernel_mmap(machine, event->mmap.start,
1650 					 event->mmap.start + event->mmap.len);
1651 
1652 		/*
1653 		 * Avoid using a zero address (kptr_restrict) for the ref reloc
1654 		 * symbol. Effectively having zero here means that at record
1655 		 * time /proc/sys/kernel/kptr_restrict was non zero.
1656 		 */
1657 		if (event->mmap.pgoff != 0) {
1658 			map__set_kallsyms_ref_reloc_sym(machine->vmlinux_map,
1659 							symbol_name,
1660 							event->mmap.pgoff);
1661 		}
1662 
1663 		if (machine__is_default_guest(machine)) {
1664 			/*
1665 			 * preload dso of guest kernel and modules
1666 			 */
1667 			dso__load(kernel, machine__kernel_map(machine));
1668 		}
1669 	} else if (perf_event__is_extra_kernel_mmap(machine, event)) {
1670 		return machine__process_extra_kernel_map(machine, event);
1671 	}
1672 	return 0;
1673 out_problem:
1674 	return -1;
1675 }
1676 
1677 int machine__process_mmap2_event(struct machine *machine,
1678 				 union perf_event *event,
1679 				 struct perf_sample *sample)
1680 {
1681 	struct thread *thread;
1682 	struct map *map;
1683 	int ret = 0;
1684 
1685 	if (dump_trace)
1686 		perf_event__fprintf_mmap2(event, stdout);
1687 
1688 	if (sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1689 	    sample->cpumode == PERF_RECORD_MISC_KERNEL) {
1690 		ret = machine__process_kernel_mmap_event(machine, event);
1691 		if (ret < 0)
1692 			goto out_problem;
1693 		return 0;
1694 	}
1695 
1696 	thread = machine__findnew_thread(machine, event->mmap2.pid,
1697 					event->mmap2.tid);
1698 	if (thread == NULL)
1699 		goto out_problem;
1700 
1701 	map = map__new(machine, event->mmap2.start,
1702 			event->mmap2.len, event->mmap2.pgoff,
1703 			event->mmap2.maj,
1704 			event->mmap2.min, event->mmap2.ino,
1705 			event->mmap2.ino_generation,
1706 			event->mmap2.prot,
1707 			event->mmap2.flags,
1708 			event->mmap2.filename, thread);
1709 
1710 	if (map == NULL)
1711 		goto out_problem_map;
1712 
1713 	ret = thread__insert_map(thread, map);
1714 	if (ret)
1715 		goto out_problem_insert;
1716 
1717 	thread__put(thread);
1718 	map__put(map);
1719 	return 0;
1720 
1721 out_problem_insert:
1722 	map__put(map);
1723 out_problem_map:
1724 	thread__put(thread);
1725 out_problem:
1726 	dump_printf("problem processing PERF_RECORD_MMAP2, skipping event.\n");
1727 	return 0;
1728 }
1729 
1730 int machine__process_mmap_event(struct machine *machine, union perf_event *event,
1731 				struct perf_sample *sample)
1732 {
1733 	struct thread *thread;
1734 	struct map *map;
1735 	u32 prot = 0;
1736 	int ret = 0;
1737 
1738 	if (dump_trace)
1739 		perf_event__fprintf_mmap(event, stdout);
1740 
1741 	if (sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1742 	    sample->cpumode == PERF_RECORD_MISC_KERNEL) {
1743 		ret = machine__process_kernel_mmap_event(machine, event);
1744 		if (ret < 0)
1745 			goto out_problem;
1746 		return 0;
1747 	}
1748 
1749 	thread = machine__findnew_thread(machine, event->mmap.pid,
1750 					 event->mmap.tid);
1751 	if (thread == NULL)
1752 		goto out_problem;
1753 
1754 	if (!(event->header.misc & PERF_RECORD_MISC_MMAP_DATA))
1755 		prot = PROT_EXEC;
1756 
1757 	map = map__new(machine, event->mmap.start,
1758 			event->mmap.len, event->mmap.pgoff,
1759 			0, 0, 0, 0, prot, 0,
1760 			event->mmap.filename,
1761 			thread);
1762 
1763 	if (map == NULL)
1764 		goto out_problem_map;
1765 
1766 	ret = thread__insert_map(thread, map);
1767 	if (ret)
1768 		goto out_problem_insert;
1769 
1770 	thread__put(thread);
1771 	map__put(map);
1772 	return 0;
1773 
1774 out_problem_insert:
1775 	map__put(map);
1776 out_problem_map:
1777 	thread__put(thread);
1778 out_problem:
1779 	dump_printf("problem processing PERF_RECORD_MMAP, skipping event.\n");
1780 	return 0;
1781 }
1782 
1783 static void __machine__remove_thread(struct machine *machine, struct thread *th, bool lock)
1784 {
1785 	struct threads *threads = machine__threads(machine, th->tid);
1786 
1787 	if (threads->last_match == th)
1788 		threads__set_last_match(threads, NULL);
1789 
1790 	if (lock)
1791 		down_write(&threads->lock);
1792 
1793 	BUG_ON(refcount_read(&th->refcnt) == 0);
1794 
1795 	rb_erase_cached(&th->rb_node, &threads->entries);
1796 	RB_CLEAR_NODE(&th->rb_node);
1797 	--threads->nr;
1798 	/*
1799 	 * Move it first to the dead_threads list, then drop the reference,
1800 	 * if this is the last reference, then the thread__delete destructor
1801 	 * will be called and we will remove it from the dead_threads list.
1802 	 */
1803 	list_add_tail(&th->node, &threads->dead);
1804 
1805 	/*
1806 	 * We need to do the put here because if this is the last refcount,
1807 	 * then we will be touching the threads->dead head when removing the
1808 	 * thread.
1809 	 */
1810 	thread__put(th);
1811 
1812 	if (lock)
1813 		up_write(&threads->lock);
1814 }
1815 
1816 void machine__remove_thread(struct machine *machine, struct thread *th)
1817 {
1818 	return __machine__remove_thread(machine, th, true);
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 (parent->pid_ != (pid_t)event->fork.ppid) {
1843 		dump_printf("removing erroneous parent thread %d/%d\n",
1844 			    parent->pid_, parent->tid);
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 sythesized 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 		thread__exited(thread);
1899 		thread__put(thread);
1900 	}
1901 
1902 	return 0;
1903 }
1904 
1905 int machine__process_event(struct machine *machine, union perf_event *event,
1906 			   struct perf_sample *sample)
1907 {
1908 	int ret;
1909 
1910 	switch (event->header.type) {
1911 	case PERF_RECORD_COMM:
1912 		ret = machine__process_comm_event(machine, event, sample); break;
1913 	case PERF_RECORD_MMAP:
1914 		ret = machine__process_mmap_event(machine, event, sample); break;
1915 	case PERF_RECORD_NAMESPACES:
1916 		ret = machine__process_namespaces_event(machine, event, sample); break;
1917 	case PERF_RECORD_MMAP2:
1918 		ret = machine__process_mmap2_event(machine, event, sample); break;
1919 	case PERF_RECORD_FORK:
1920 		ret = machine__process_fork_event(machine, event, sample); break;
1921 	case PERF_RECORD_EXIT:
1922 		ret = machine__process_exit_event(machine, event, sample); break;
1923 	case PERF_RECORD_LOST:
1924 		ret = machine__process_lost_event(machine, event, sample); break;
1925 	case PERF_RECORD_AUX:
1926 		ret = machine__process_aux_event(machine, event); break;
1927 	case PERF_RECORD_ITRACE_START:
1928 		ret = machine__process_itrace_start_event(machine, event); break;
1929 	case PERF_RECORD_LOST_SAMPLES:
1930 		ret = machine__process_lost_samples_event(machine, event, sample); break;
1931 	case PERF_RECORD_SWITCH:
1932 	case PERF_RECORD_SWITCH_CPU_WIDE:
1933 		ret = machine__process_switch_event(machine, event); break;
1934 	case PERF_RECORD_KSYMBOL:
1935 		ret = machine__process_ksymbol(machine, event, sample); break;
1936 	case PERF_RECORD_BPF_EVENT:
1937 		ret = machine__process_bpf(machine, event, sample); break;
1938 	default:
1939 		ret = -1;
1940 		break;
1941 	}
1942 
1943 	return ret;
1944 }
1945 
1946 static bool symbol__match_regex(struct symbol *sym, regex_t *regex)
1947 {
1948 	if (!regexec(regex, sym->name, 0, NULL, 0))
1949 		return 1;
1950 	return 0;
1951 }
1952 
1953 static void ip__resolve_ams(struct thread *thread,
1954 			    struct addr_map_symbol *ams,
1955 			    u64 ip)
1956 {
1957 	struct addr_location al;
1958 
1959 	memset(&al, 0, sizeof(al));
1960 	/*
1961 	 * We cannot use the header.misc hint to determine whether a
1962 	 * branch stack address is user, kernel, guest, hypervisor.
1963 	 * Branches may straddle the kernel/user/hypervisor boundaries.
1964 	 * Thus, we have to try consecutively until we find a match
1965 	 * or else, the symbol is unknown
1966 	 */
1967 	thread__find_cpumode_addr_location(thread, ip, &al);
1968 
1969 	ams->addr = ip;
1970 	ams->al_addr = al.addr;
1971 	ams->ms.mg  = al.mg;
1972 	ams->ms.sym = al.sym;
1973 	ams->ms.map = al.map;
1974 	ams->phys_addr = 0;
1975 }
1976 
1977 static void ip__resolve_data(struct thread *thread,
1978 			     u8 m, struct addr_map_symbol *ams,
1979 			     u64 addr, u64 phys_addr)
1980 {
1981 	struct addr_location al;
1982 
1983 	memset(&al, 0, sizeof(al));
1984 
1985 	thread__find_symbol(thread, m, addr, &al);
1986 
1987 	ams->addr = addr;
1988 	ams->al_addr = al.addr;
1989 	ams->ms.mg  = al.mg;
1990 	ams->ms.sym = al.sym;
1991 	ams->ms.map = al.map;
1992 	ams->phys_addr = phys_addr;
1993 }
1994 
1995 struct mem_info *sample__resolve_mem(struct perf_sample *sample,
1996 				     struct addr_location *al)
1997 {
1998 	struct mem_info *mi = mem_info__new();
1999 
2000 	if (!mi)
2001 		return NULL;
2002 
2003 	ip__resolve_ams(al->thread, &mi->iaddr, sample->ip);
2004 	ip__resolve_data(al->thread, al->cpumode, &mi->daddr,
2005 			 sample->addr, sample->phys_addr);
2006 	mi->data_src.val = sample->data_src;
2007 
2008 	return mi;
2009 }
2010 
2011 static char *callchain_srcline(struct map_symbol *ms, u64 ip)
2012 {
2013 	struct map *map = ms->map;
2014 	char *srcline = NULL;
2015 
2016 	if (!map || callchain_param.key == CCKEY_FUNCTION)
2017 		return srcline;
2018 
2019 	srcline = srcline__tree_find(&map->dso->srclines, ip);
2020 	if (!srcline) {
2021 		bool show_sym = false;
2022 		bool show_addr = callchain_param.key == CCKEY_ADDRESS;
2023 
2024 		srcline = get_srcline(map->dso, map__rip_2objdump(map, ip),
2025 				      ms->sym, show_sym, show_addr, ip);
2026 		srcline__tree_insert(&map->dso->srclines, ip, srcline);
2027 	}
2028 
2029 	return srcline;
2030 }
2031 
2032 struct iterations {
2033 	int nr_loop_iter;
2034 	u64 cycles;
2035 };
2036 
2037 static int add_callchain_ip(struct thread *thread,
2038 			    struct callchain_cursor *cursor,
2039 			    struct symbol **parent,
2040 			    struct addr_location *root_al,
2041 			    u8 *cpumode,
2042 			    u64 ip,
2043 			    bool branch,
2044 			    struct branch_flags *flags,
2045 			    struct iterations *iter,
2046 			    u64 branch_from)
2047 {
2048 	struct map_symbol ms;
2049 	struct addr_location al;
2050 	int nr_loop_iter = 0;
2051 	u64 iter_cycles = 0;
2052 	const char *srcline = NULL;
2053 
2054 	al.filtered = 0;
2055 	al.sym = NULL;
2056 	if (!cpumode) {
2057 		thread__find_cpumode_addr_location(thread, ip, &al);
2058 	} else {
2059 		if (ip >= PERF_CONTEXT_MAX) {
2060 			switch (ip) {
2061 			case PERF_CONTEXT_HV:
2062 				*cpumode = PERF_RECORD_MISC_HYPERVISOR;
2063 				break;
2064 			case PERF_CONTEXT_KERNEL:
2065 				*cpumode = PERF_RECORD_MISC_KERNEL;
2066 				break;
2067 			case PERF_CONTEXT_USER:
2068 				*cpumode = PERF_RECORD_MISC_USER;
2069 				break;
2070 			default:
2071 				pr_debug("invalid callchain context: "
2072 					 "%"PRId64"\n", (s64) ip);
2073 				/*
2074 				 * It seems the callchain is corrupted.
2075 				 * Discard all.
2076 				 */
2077 				callchain_cursor_reset(cursor);
2078 				return 1;
2079 			}
2080 			return 0;
2081 		}
2082 		thread__find_symbol(thread, *cpumode, ip, &al);
2083 	}
2084 
2085 	if (al.sym != NULL) {
2086 		if (perf_hpp_list.parent && !*parent &&
2087 		    symbol__match_regex(al.sym, &parent_regex))
2088 			*parent = al.sym;
2089 		else if (have_ignore_callees && root_al &&
2090 		  symbol__match_regex(al.sym, &ignore_callees_regex)) {
2091 			/* Treat this symbol as the root,
2092 			   forgetting its callees. */
2093 			*root_al = al;
2094 			callchain_cursor_reset(cursor);
2095 		}
2096 	}
2097 
2098 	if (symbol_conf.hide_unresolved && al.sym == NULL)
2099 		return 0;
2100 
2101 	if (iter) {
2102 		nr_loop_iter = iter->nr_loop_iter;
2103 		iter_cycles = iter->cycles;
2104 	}
2105 
2106 	ms.mg  = al.mg;
2107 	ms.map = al.map;
2108 	ms.sym = al.sym;
2109 	srcline = callchain_srcline(&ms, al.addr);
2110 	return callchain_cursor_append(cursor, ip, &ms,
2111 				       branch, flags, nr_loop_iter,
2112 				       iter_cycles, branch_from, srcline);
2113 }
2114 
2115 struct branch_info *sample__resolve_bstack(struct perf_sample *sample,
2116 					   struct addr_location *al)
2117 {
2118 	unsigned int i;
2119 	const struct branch_stack *bs = sample->branch_stack;
2120 	struct branch_info *bi = calloc(bs->nr, sizeof(struct branch_info));
2121 
2122 	if (!bi)
2123 		return NULL;
2124 
2125 	for (i = 0; i < bs->nr; i++) {
2126 		ip__resolve_ams(al->thread, &bi[i].to, bs->entries[i].to);
2127 		ip__resolve_ams(al->thread, &bi[i].from, bs->entries[i].from);
2128 		bi[i].flags = bs->entries[i].flags;
2129 	}
2130 	return bi;
2131 }
2132 
2133 static void save_iterations(struct iterations *iter,
2134 			    struct branch_entry *be, int nr)
2135 {
2136 	int i;
2137 
2138 	iter->nr_loop_iter++;
2139 	iter->cycles = 0;
2140 
2141 	for (i = 0; i < nr; i++)
2142 		iter->cycles += be[i].flags.cycles;
2143 }
2144 
2145 #define CHASHSZ 127
2146 #define CHASHBITS 7
2147 #define NO_ENTRY 0xff
2148 
2149 #define PERF_MAX_BRANCH_DEPTH 127
2150 
2151 /* Remove loops. */
2152 static int remove_loops(struct branch_entry *l, int nr,
2153 			struct iterations *iter)
2154 {
2155 	int i, j, off;
2156 	unsigned char chash[CHASHSZ];
2157 
2158 	memset(chash, NO_ENTRY, sizeof(chash));
2159 
2160 	BUG_ON(PERF_MAX_BRANCH_DEPTH > 255);
2161 
2162 	for (i = 0; i < nr; i++) {
2163 		int h = hash_64(l[i].from, CHASHBITS) % CHASHSZ;
2164 
2165 		/* no collision handling for now */
2166 		if (chash[h] == NO_ENTRY) {
2167 			chash[h] = i;
2168 		} else if (l[chash[h]].from == l[i].from) {
2169 			bool is_loop = true;
2170 			/* check if it is a real loop */
2171 			off = 0;
2172 			for (j = chash[h]; j < i && i + off < nr; j++, off++)
2173 				if (l[j].from != l[i + off].from) {
2174 					is_loop = false;
2175 					break;
2176 				}
2177 			if (is_loop) {
2178 				j = nr - (i + off);
2179 				if (j > 0) {
2180 					save_iterations(iter + i + off,
2181 						l + i, off);
2182 
2183 					memmove(iter + i, iter + i + off,
2184 						j * sizeof(*iter));
2185 
2186 					memmove(l + i, l + i + off,
2187 						j * sizeof(*l));
2188 				}
2189 
2190 				nr -= off;
2191 			}
2192 		}
2193 	}
2194 	return nr;
2195 }
2196 
2197 /*
2198  * Recolve LBR callstack chain sample
2199  * Return:
2200  * 1 on success get LBR callchain information
2201  * 0 no available LBR callchain information, should try fp
2202  * negative error code on other errors.
2203  */
2204 static int resolve_lbr_callchain_sample(struct thread *thread,
2205 					struct callchain_cursor *cursor,
2206 					struct perf_sample *sample,
2207 					struct symbol **parent,
2208 					struct addr_location *root_al,
2209 					int max_stack)
2210 {
2211 	struct ip_callchain *chain = sample->callchain;
2212 	int chain_nr = min(max_stack, (int)chain->nr), i;
2213 	u8 cpumode = PERF_RECORD_MISC_USER;
2214 	u64 ip, branch_from = 0;
2215 
2216 	for (i = 0; i < chain_nr; i++) {
2217 		if (chain->ips[i] == PERF_CONTEXT_USER)
2218 			break;
2219 	}
2220 
2221 	/* LBR only affects the user callchain */
2222 	if (i != chain_nr) {
2223 		struct branch_stack *lbr_stack = sample->branch_stack;
2224 		int lbr_nr = lbr_stack->nr, j, k;
2225 		bool branch;
2226 		struct branch_flags *flags;
2227 		/*
2228 		 * LBR callstack can only get user call chain.
2229 		 * The mix_chain_nr is kernel call chain
2230 		 * number plus LBR user call chain number.
2231 		 * i is kernel call chain number,
2232 		 * 1 is PERF_CONTEXT_USER,
2233 		 * lbr_nr + 1 is the user call chain number.
2234 		 * For details, please refer to the comments
2235 		 * in callchain__printf
2236 		 */
2237 		int mix_chain_nr = i + 1 + lbr_nr + 1;
2238 
2239 		for (j = 0; j < mix_chain_nr; j++) {
2240 			int err;
2241 			branch = false;
2242 			flags = NULL;
2243 
2244 			if (callchain_param.order == ORDER_CALLEE) {
2245 				if (j < i + 1)
2246 					ip = chain->ips[j];
2247 				else if (j > i + 1) {
2248 					k = j - i - 2;
2249 					ip = lbr_stack->entries[k].from;
2250 					branch = true;
2251 					flags = &lbr_stack->entries[k].flags;
2252 				} else {
2253 					ip = lbr_stack->entries[0].to;
2254 					branch = true;
2255 					flags = &lbr_stack->entries[0].flags;
2256 					branch_from =
2257 						lbr_stack->entries[0].from;
2258 				}
2259 			} else {
2260 				if (j < lbr_nr) {
2261 					k = lbr_nr - j - 1;
2262 					ip = lbr_stack->entries[k].from;
2263 					branch = true;
2264 					flags = &lbr_stack->entries[k].flags;
2265 				}
2266 				else if (j > lbr_nr)
2267 					ip = chain->ips[i + 1 - (j - lbr_nr)];
2268 				else {
2269 					ip = lbr_stack->entries[0].to;
2270 					branch = true;
2271 					flags = &lbr_stack->entries[0].flags;
2272 					branch_from =
2273 						lbr_stack->entries[0].from;
2274 				}
2275 			}
2276 
2277 			err = add_callchain_ip(thread, cursor, parent,
2278 					       root_al, &cpumode, ip,
2279 					       branch, flags, NULL,
2280 					       branch_from);
2281 			if (err)
2282 				return (err < 0) ? err : 0;
2283 		}
2284 		return 1;
2285 	}
2286 
2287 	return 0;
2288 }
2289 
2290 static int find_prev_cpumode(struct ip_callchain *chain, struct thread *thread,
2291 			     struct callchain_cursor *cursor,
2292 			     struct symbol **parent,
2293 			     struct addr_location *root_al,
2294 			     u8 *cpumode, int ent)
2295 {
2296 	int err = 0;
2297 
2298 	while (--ent >= 0) {
2299 		u64 ip = chain->ips[ent];
2300 
2301 		if (ip >= PERF_CONTEXT_MAX) {
2302 			err = add_callchain_ip(thread, cursor, parent,
2303 					       root_al, cpumode, ip,
2304 					       false, NULL, NULL, 0);
2305 			break;
2306 		}
2307 	}
2308 	return err;
2309 }
2310 
2311 static int thread__resolve_callchain_sample(struct thread *thread,
2312 					    struct callchain_cursor *cursor,
2313 					    struct evsel *evsel,
2314 					    struct perf_sample *sample,
2315 					    struct symbol **parent,
2316 					    struct addr_location *root_al,
2317 					    int max_stack)
2318 {
2319 	struct branch_stack *branch = sample->branch_stack;
2320 	struct ip_callchain *chain = sample->callchain;
2321 	int chain_nr = 0;
2322 	u8 cpumode = PERF_RECORD_MISC_USER;
2323 	int i, j, err, nr_entries;
2324 	int skip_idx = -1;
2325 	int first_call = 0;
2326 
2327 	if (chain)
2328 		chain_nr = chain->nr;
2329 
2330 	if (perf_evsel__has_branch_callstack(evsel)) {
2331 		err = resolve_lbr_callchain_sample(thread, cursor, sample, parent,
2332 						   root_al, max_stack);
2333 		if (err)
2334 			return (err < 0) ? err : 0;
2335 	}
2336 
2337 	/*
2338 	 * Based on DWARF debug information, some architectures skip
2339 	 * a callchain entry saved by the kernel.
2340 	 */
2341 	skip_idx = arch_skip_callchain_idx(thread, chain);
2342 
2343 	/*
2344 	 * Add branches to call stack for easier browsing. This gives
2345 	 * more context for a sample than just the callers.
2346 	 *
2347 	 * This uses individual histograms of paths compared to the
2348 	 * aggregated histograms the normal LBR mode uses.
2349 	 *
2350 	 * Limitations for now:
2351 	 * - No extra filters
2352 	 * - No annotations (should annotate somehow)
2353 	 */
2354 
2355 	if (branch && callchain_param.branch_callstack) {
2356 		int nr = min(max_stack, (int)branch->nr);
2357 		struct branch_entry be[nr];
2358 		struct iterations iter[nr];
2359 
2360 		if (branch->nr > PERF_MAX_BRANCH_DEPTH) {
2361 			pr_warning("corrupted branch chain. skipping...\n");
2362 			goto check_calls;
2363 		}
2364 
2365 		for (i = 0; i < nr; i++) {
2366 			if (callchain_param.order == ORDER_CALLEE) {
2367 				be[i] = branch->entries[i];
2368 
2369 				if (chain == NULL)
2370 					continue;
2371 
2372 				/*
2373 				 * Check for overlap into the callchain.
2374 				 * The return address is one off compared to
2375 				 * the branch entry. To adjust for this
2376 				 * assume the calling instruction is not longer
2377 				 * than 8 bytes.
2378 				 */
2379 				if (i == skip_idx ||
2380 				    chain->ips[first_call] >= PERF_CONTEXT_MAX)
2381 					first_call++;
2382 				else if (be[i].from < chain->ips[first_call] &&
2383 				    be[i].from >= chain->ips[first_call] - 8)
2384 					first_call++;
2385 			} else
2386 				be[i] = branch->entries[branch->nr - i - 1];
2387 		}
2388 
2389 		memset(iter, 0, sizeof(struct iterations) * nr);
2390 		nr = remove_loops(be, nr, iter);
2391 
2392 		for (i = 0; i < nr; i++) {
2393 			err = add_callchain_ip(thread, cursor, parent,
2394 					       root_al,
2395 					       NULL, be[i].to,
2396 					       true, &be[i].flags,
2397 					       NULL, be[i].from);
2398 
2399 			if (!err)
2400 				err = add_callchain_ip(thread, cursor, parent, root_al,
2401 						       NULL, be[i].from,
2402 						       true, &be[i].flags,
2403 						       &iter[i], 0);
2404 			if (err == -EINVAL)
2405 				break;
2406 			if (err)
2407 				return err;
2408 		}
2409 
2410 		if (chain_nr == 0)
2411 			return 0;
2412 
2413 		chain_nr -= nr;
2414 	}
2415 
2416 check_calls:
2417 	if (callchain_param.order != ORDER_CALLEE) {
2418 		err = find_prev_cpumode(chain, thread, cursor, parent, root_al,
2419 					&cpumode, chain->nr - first_call);
2420 		if (err)
2421 			return (err < 0) ? err : 0;
2422 	}
2423 	for (i = first_call, nr_entries = 0;
2424 	     i < chain_nr && nr_entries < max_stack; i++) {
2425 		u64 ip;
2426 
2427 		if (callchain_param.order == ORDER_CALLEE)
2428 			j = i;
2429 		else
2430 			j = chain->nr - i - 1;
2431 
2432 #ifdef HAVE_SKIP_CALLCHAIN_IDX
2433 		if (j == skip_idx)
2434 			continue;
2435 #endif
2436 		ip = chain->ips[j];
2437 		if (ip < PERF_CONTEXT_MAX)
2438                        ++nr_entries;
2439 		else if (callchain_param.order != ORDER_CALLEE) {
2440 			err = find_prev_cpumode(chain, thread, cursor, parent,
2441 						root_al, &cpumode, j);
2442 			if (err)
2443 				return (err < 0) ? err : 0;
2444 			continue;
2445 		}
2446 
2447 		err = add_callchain_ip(thread, cursor, parent,
2448 				       root_al, &cpumode, ip,
2449 				       false, NULL, NULL, 0);
2450 
2451 		if (err)
2452 			return (err < 0) ? err : 0;
2453 	}
2454 
2455 	return 0;
2456 }
2457 
2458 static int append_inlines(struct callchain_cursor *cursor, struct map_symbol *ms, u64 ip)
2459 {
2460 	struct symbol *sym = ms->sym;
2461 	struct map *map = ms->map;
2462 	struct inline_node *inline_node;
2463 	struct inline_list *ilist;
2464 	u64 addr;
2465 	int ret = 1;
2466 
2467 	if (!symbol_conf.inline_name || !map || !sym)
2468 		return ret;
2469 
2470 	addr = map__map_ip(map, ip);
2471 	addr = map__rip_2objdump(map, addr);
2472 
2473 	inline_node = inlines__tree_find(&map->dso->inlined_nodes, addr);
2474 	if (!inline_node) {
2475 		inline_node = dso__parse_addr_inlines(map->dso, addr, sym);
2476 		if (!inline_node)
2477 			return ret;
2478 		inlines__tree_insert(&map->dso->inlined_nodes, inline_node);
2479 	}
2480 
2481 	list_for_each_entry(ilist, &inline_node->val, list) {
2482 		struct map_symbol ilist_ms = {
2483 			.map = map,
2484 			.sym = ilist->symbol,
2485 		};
2486 		ret = callchain_cursor_append(cursor, ip, &ilist_ms, false,
2487 					      NULL, 0, 0, 0, ilist->srcline);
2488 
2489 		if (ret != 0)
2490 			return ret;
2491 	}
2492 
2493 	return ret;
2494 }
2495 
2496 static int unwind_entry(struct unwind_entry *entry, void *arg)
2497 {
2498 	struct callchain_cursor *cursor = arg;
2499 	const char *srcline = NULL;
2500 	u64 addr = entry->ip;
2501 
2502 	if (symbol_conf.hide_unresolved && entry->ms.sym == NULL)
2503 		return 0;
2504 
2505 	if (append_inlines(cursor, &entry->ms, entry->ip) == 0)
2506 		return 0;
2507 
2508 	/*
2509 	 * Convert entry->ip from a virtual address to an offset in
2510 	 * its corresponding binary.
2511 	 */
2512 	if (entry->ms.map)
2513 		addr = map__map_ip(entry->ms.map, entry->ip);
2514 
2515 	srcline = callchain_srcline(&entry->ms, addr);
2516 	return callchain_cursor_append(cursor, entry->ip, &entry->ms,
2517 				       false, NULL, 0, 0, 0, srcline);
2518 }
2519 
2520 static int thread__resolve_callchain_unwind(struct thread *thread,
2521 					    struct callchain_cursor *cursor,
2522 					    struct evsel *evsel,
2523 					    struct perf_sample *sample,
2524 					    int max_stack)
2525 {
2526 	/* Can we do dwarf post unwind? */
2527 	if (!((evsel->core.attr.sample_type & PERF_SAMPLE_REGS_USER) &&
2528 	      (evsel->core.attr.sample_type & PERF_SAMPLE_STACK_USER)))
2529 		return 0;
2530 
2531 	/* Bail out if nothing was captured. */
2532 	if ((!sample->user_regs.regs) ||
2533 	    (!sample->user_stack.size))
2534 		return 0;
2535 
2536 	return unwind__get_entries(unwind_entry, cursor,
2537 				   thread, sample, max_stack);
2538 }
2539 
2540 int thread__resolve_callchain(struct thread *thread,
2541 			      struct callchain_cursor *cursor,
2542 			      struct evsel *evsel,
2543 			      struct perf_sample *sample,
2544 			      struct symbol **parent,
2545 			      struct addr_location *root_al,
2546 			      int max_stack)
2547 {
2548 	int ret = 0;
2549 
2550 	callchain_cursor_reset(cursor);
2551 
2552 	if (callchain_param.order == ORDER_CALLEE) {
2553 		ret = thread__resolve_callchain_sample(thread, cursor,
2554 						       evsel, sample,
2555 						       parent, root_al,
2556 						       max_stack);
2557 		if (ret)
2558 			return ret;
2559 		ret = thread__resolve_callchain_unwind(thread, cursor,
2560 						       evsel, sample,
2561 						       max_stack);
2562 	} else {
2563 		ret = thread__resolve_callchain_unwind(thread, cursor,
2564 						       evsel, sample,
2565 						       max_stack);
2566 		if (ret)
2567 			return ret;
2568 		ret = thread__resolve_callchain_sample(thread, cursor,
2569 						       evsel, sample,
2570 						       parent, root_al,
2571 						       max_stack);
2572 	}
2573 
2574 	return ret;
2575 }
2576 
2577 int machine__for_each_thread(struct machine *machine,
2578 			     int (*fn)(struct thread *thread, void *p),
2579 			     void *priv)
2580 {
2581 	struct threads *threads;
2582 	struct rb_node *nd;
2583 	struct thread *thread;
2584 	int rc = 0;
2585 	int i;
2586 
2587 	for (i = 0; i < THREADS__TABLE_SIZE; i++) {
2588 		threads = &machine->threads[i];
2589 		for (nd = rb_first_cached(&threads->entries); nd;
2590 		     nd = rb_next(nd)) {
2591 			thread = rb_entry(nd, struct thread, rb_node);
2592 			rc = fn(thread, priv);
2593 			if (rc != 0)
2594 				return rc;
2595 		}
2596 
2597 		list_for_each_entry(thread, &threads->dead, node) {
2598 			rc = fn(thread, priv);
2599 			if (rc != 0)
2600 				return rc;
2601 		}
2602 	}
2603 	return rc;
2604 }
2605 
2606 int machines__for_each_thread(struct machines *machines,
2607 			      int (*fn)(struct thread *thread, void *p),
2608 			      void *priv)
2609 {
2610 	struct rb_node *nd;
2611 	int rc = 0;
2612 
2613 	rc = machine__for_each_thread(&machines->host, fn, priv);
2614 	if (rc != 0)
2615 		return rc;
2616 
2617 	for (nd = rb_first_cached(&machines->guests); nd; nd = rb_next(nd)) {
2618 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
2619 
2620 		rc = machine__for_each_thread(machine, fn, priv);
2621 		if (rc != 0)
2622 			return rc;
2623 	}
2624 	return rc;
2625 }
2626 
2627 pid_t machine__get_current_tid(struct machine *machine, int cpu)
2628 {
2629 	int nr_cpus = min(machine->env->nr_cpus_online, MAX_NR_CPUS);
2630 
2631 	if (cpu < 0 || cpu >= nr_cpus || !machine->current_tid)
2632 		return -1;
2633 
2634 	return machine->current_tid[cpu];
2635 }
2636 
2637 int machine__set_current_tid(struct machine *machine, int cpu, pid_t pid,
2638 			     pid_t tid)
2639 {
2640 	struct thread *thread;
2641 	int nr_cpus = min(machine->env->nr_cpus_online, MAX_NR_CPUS);
2642 
2643 	if (cpu < 0)
2644 		return -EINVAL;
2645 
2646 	if (!machine->current_tid) {
2647 		int i;
2648 
2649 		machine->current_tid = calloc(nr_cpus, sizeof(pid_t));
2650 		if (!machine->current_tid)
2651 			return -ENOMEM;
2652 		for (i = 0; i < nr_cpus; i++)
2653 			machine->current_tid[i] = -1;
2654 	}
2655 
2656 	if (cpu >= nr_cpus) {
2657 		pr_err("Requested CPU %d too large. ", cpu);
2658 		pr_err("Consider raising MAX_NR_CPUS\n");
2659 		return -EINVAL;
2660 	}
2661 
2662 	machine->current_tid[cpu] = tid;
2663 
2664 	thread = machine__findnew_thread(machine, pid, tid);
2665 	if (!thread)
2666 		return -ENOMEM;
2667 
2668 	thread->cpu = cpu;
2669 	thread__put(thread);
2670 
2671 	return 0;
2672 }
2673 
2674 /*
2675  * Compares the raw arch string. N.B. see instead perf_env__arch() if a
2676  * normalized arch is needed.
2677  */
2678 bool machine__is(struct machine *machine, const char *arch)
2679 {
2680 	return machine && !strcmp(perf_env__raw_arch(machine->env), arch);
2681 }
2682 
2683 int machine__nr_cpus_avail(struct machine *machine)
2684 {
2685 	return machine ? perf_env__nr_cpus_avail(machine->env) : 0;
2686 }
2687 
2688 int machine__get_kernel_start(struct machine *machine)
2689 {
2690 	struct map *map = machine__kernel_map(machine);
2691 	int err = 0;
2692 
2693 	/*
2694 	 * The only addresses above 2^63 are kernel addresses of a 64-bit
2695 	 * kernel.  Note that addresses are unsigned so that on a 32-bit system
2696 	 * all addresses including kernel addresses are less than 2^32.  In
2697 	 * that case (32-bit system), if the kernel mapping is unknown, all
2698 	 * addresses will be assumed to be in user space - see
2699 	 * machine__kernel_ip().
2700 	 */
2701 	machine->kernel_start = 1ULL << 63;
2702 	if (map) {
2703 		err = map__load(map);
2704 		/*
2705 		 * On x86_64, PTI entry trampolines are less than the
2706 		 * start of kernel text, but still above 2^63. So leave
2707 		 * kernel_start = 1ULL << 63 for x86_64.
2708 		 */
2709 		if (!err && !machine__is(machine, "x86_64"))
2710 			machine->kernel_start = map->start;
2711 	}
2712 	return err;
2713 }
2714 
2715 u8 machine__addr_cpumode(struct machine *machine, u8 cpumode, u64 addr)
2716 {
2717 	u8 addr_cpumode = cpumode;
2718 	bool kernel_ip;
2719 
2720 	if (!machine->single_address_space)
2721 		goto out;
2722 
2723 	kernel_ip = machine__kernel_ip(machine, addr);
2724 	switch (cpumode) {
2725 	case PERF_RECORD_MISC_KERNEL:
2726 	case PERF_RECORD_MISC_USER:
2727 		addr_cpumode = kernel_ip ? PERF_RECORD_MISC_KERNEL :
2728 					   PERF_RECORD_MISC_USER;
2729 		break;
2730 	case PERF_RECORD_MISC_GUEST_KERNEL:
2731 	case PERF_RECORD_MISC_GUEST_USER:
2732 		addr_cpumode = kernel_ip ? PERF_RECORD_MISC_GUEST_KERNEL :
2733 					   PERF_RECORD_MISC_GUEST_USER;
2734 		break;
2735 	default:
2736 		break;
2737 	}
2738 out:
2739 	return addr_cpumode;
2740 }
2741 
2742 struct dso *machine__findnew_dso(struct machine *machine, const char *filename)
2743 {
2744 	return dsos__findnew(&machine->dsos, filename);
2745 }
2746 
2747 char *machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
2748 {
2749 	struct machine *machine = vmachine;
2750 	struct map *map;
2751 	struct symbol *sym = machine__find_kernel_symbol(machine, *addrp, &map);
2752 
2753 	if (sym == NULL)
2754 		return NULL;
2755 
2756 	*modp = __map__is_kmodule(map) ? (char *)map->dso->short_name : NULL;
2757 	*addrp = map->unmap_ip(map, sym->start);
2758 	return sym->name;
2759 }
2760