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