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