xref: /linux-6.15/tools/perf/util/machine.c (revision 7f47d8cc)
1 #include "callchain.h"
2 #include "debug.h"
3 #include "event.h"
4 #include "evsel.h"
5 #include "hist.h"
6 #include "machine.h"
7 #include "map.h"
8 #include "sort.h"
9 #include "strlist.h"
10 #include "thread.h"
11 #include "vdso.h"
12 #include <stdbool.h>
13 #include <symbol/kallsyms.h>
14 #include "unwind.h"
15 #include "linux/hash.h"
16 
17 static void __machine__remove_thread(struct machine *machine, struct thread *th, bool lock);
18 
19 static void dsos__init(struct dsos *dsos)
20 {
21 	INIT_LIST_HEAD(&dsos->head);
22 	dsos->root = RB_ROOT;
23 	pthread_rwlock_init(&dsos->lock, NULL);
24 }
25 
26 int machine__init(struct machine *machine, const char *root_dir, pid_t pid)
27 {
28 	map_groups__init(&machine->kmaps, machine);
29 	RB_CLEAR_NODE(&machine->rb_node);
30 	dsos__init(&machine->dsos);
31 
32 	machine->threads = RB_ROOT;
33 	pthread_rwlock_init(&machine->threads_lock, NULL);
34 	INIT_LIST_HEAD(&machine->dead_threads);
35 	machine->last_match = NULL;
36 
37 	machine->vdso_info = NULL;
38 	machine->env = NULL;
39 
40 	machine->pid = pid;
41 
42 	machine->symbol_filter = NULL;
43 	machine->id_hdr_size = 0;
44 	machine->comm_exec = false;
45 	machine->kernel_start = 0;
46 
47 	machine->root_dir = strdup(root_dir);
48 	if (machine->root_dir == NULL)
49 		return -ENOMEM;
50 
51 	if (pid != HOST_KERNEL_ID) {
52 		struct thread *thread = machine__findnew_thread(machine, -1,
53 								pid);
54 		char comm[64];
55 
56 		if (thread == NULL)
57 			return -ENOMEM;
58 
59 		snprintf(comm, sizeof(comm), "[guest/%d]", pid);
60 		thread__set_comm(thread, comm, 0);
61 		thread__put(thread);
62 	}
63 
64 	machine->current_tid = NULL;
65 
66 	return 0;
67 }
68 
69 struct machine *machine__new_host(void)
70 {
71 	struct machine *machine = malloc(sizeof(*machine));
72 
73 	if (machine != NULL) {
74 		machine__init(machine, "", HOST_KERNEL_ID);
75 
76 		if (machine__create_kernel_maps(machine) < 0)
77 			goto out_delete;
78 	}
79 
80 	return machine;
81 out_delete:
82 	free(machine);
83 	return NULL;
84 }
85 
86 static void dsos__purge(struct dsos *dsos)
87 {
88 	struct dso *pos, *n;
89 
90 	pthread_rwlock_wrlock(&dsos->lock);
91 
92 	list_for_each_entry_safe(pos, n, &dsos->head, node) {
93 		RB_CLEAR_NODE(&pos->rb_node);
94 		pos->root = NULL;
95 		list_del_init(&pos->node);
96 		dso__put(pos);
97 	}
98 
99 	pthread_rwlock_unlock(&dsos->lock);
100 }
101 
102 static void dsos__exit(struct dsos *dsos)
103 {
104 	dsos__purge(dsos);
105 	pthread_rwlock_destroy(&dsos->lock);
106 }
107 
108 void machine__delete_threads(struct machine *machine)
109 {
110 	struct rb_node *nd;
111 
112 	pthread_rwlock_wrlock(&machine->threads_lock);
113 	nd = rb_first(&machine->threads);
114 	while (nd) {
115 		struct thread *t = rb_entry(nd, struct thread, rb_node);
116 
117 		nd = rb_next(nd);
118 		__machine__remove_thread(machine, t, false);
119 	}
120 	pthread_rwlock_unlock(&machine->threads_lock);
121 }
122 
123 void machine__exit(struct machine *machine)
124 {
125 	machine__destroy_kernel_maps(machine);
126 	map_groups__exit(&machine->kmaps);
127 	dsos__exit(&machine->dsos);
128 	machine__exit_vdso(machine);
129 	zfree(&machine->root_dir);
130 	zfree(&machine->current_tid);
131 	pthread_rwlock_destroy(&machine->threads_lock);
132 }
133 
134 void machine__delete(struct machine *machine)
135 {
136 	machine__exit(machine);
137 	free(machine);
138 }
139 
140 void machines__init(struct machines *machines)
141 {
142 	machine__init(&machines->host, "", HOST_KERNEL_ID);
143 	machines->guests = RB_ROOT;
144 	machines->symbol_filter = NULL;
145 }
146 
147 void machines__exit(struct machines *machines)
148 {
149 	machine__exit(&machines->host);
150 	/* XXX exit guest */
151 }
152 
153 struct machine *machines__add(struct machines *machines, pid_t pid,
154 			      const char *root_dir)
155 {
156 	struct rb_node **p = &machines->guests.rb_node;
157 	struct rb_node *parent = NULL;
158 	struct machine *pos, *machine = malloc(sizeof(*machine));
159 
160 	if (machine == NULL)
161 		return NULL;
162 
163 	if (machine__init(machine, root_dir, pid) != 0) {
164 		free(machine);
165 		return NULL;
166 	}
167 
168 	machine->symbol_filter = machines->symbol_filter;
169 
170 	while (*p != NULL) {
171 		parent = *p;
172 		pos = rb_entry(parent, struct machine, rb_node);
173 		if (pid < pos->pid)
174 			p = &(*p)->rb_left;
175 		else
176 			p = &(*p)->rb_right;
177 	}
178 
179 	rb_link_node(&machine->rb_node, parent, p);
180 	rb_insert_color(&machine->rb_node, &machines->guests);
181 
182 	return machine;
183 }
184 
185 void machines__set_symbol_filter(struct machines *machines,
186 				 symbol_filter_t symbol_filter)
187 {
188 	struct rb_node *nd;
189 
190 	machines->symbol_filter = symbol_filter;
191 	machines->host.symbol_filter = symbol_filter;
192 
193 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
194 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
195 
196 		machine->symbol_filter = symbol_filter;
197 	}
198 }
199 
200 void machines__set_comm_exec(struct machines *machines, bool comm_exec)
201 {
202 	struct rb_node *nd;
203 
204 	machines->host.comm_exec = comm_exec;
205 
206 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
207 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
208 
209 		machine->comm_exec = comm_exec;
210 	}
211 }
212 
213 struct machine *machines__find(struct machines *machines, pid_t pid)
214 {
215 	struct rb_node **p = &machines->guests.rb_node;
216 	struct rb_node *parent = NULL;
217 	struct machine *machine;
218 	struct machine *default_machine = NULL;
219 
220 	if (pid == HOST_KERNEL_ID)
221 		return &machines->host;
222 
223 	while (*p != NULL) {
224 		parent = *p;
225 		machine = rb_entry(parent, struct machine, rb_node);
226 		if (pid < machine->pid)
227 			p = &(*p)->rb_left;
228 		else if (pid > machine->pid)
229 			p = &(*p)->rb_right;
230 		else
231 			return machine;
232 		if (!machine->pid)
233 			default_machine = machine;
234 	}
235 
236 	return default_machine;
237 }
238 
239 struct machine *machines__findnew(struct machines *machines, pid_t pid)
240 {
241 	char path[PATH_MAX];
242 	const char *root_dir = "";
243 	struct machine *machine = machines__find(machines, pid);
244 
245 	if (machine && (machine->pid == pid))
246 		goto out;
247 
248 	if ((pid != HOST_KERNEL_ID) &&
249 	    (pid != DEFAULT_GUEST_KERNEL_ID) &&
250 	    (symbol_conf.guestmount)) {
251 		sprintf(path, "%s/%d", symbol_conf.guestmount, pid);
252 		if (access(path, R_OK)) {
253 			static struct strlist *seen;
254 
255 			if (!seen)
256 				seen = strlist__new(NULL, NULL);
257 
258 			if (!strlist__has_entry(seen, path)) {
259 				pr_err("Can't access file %s\n", path);
260 				strlist__add(seen, path);
261 			}
262 			machine = NULL;
263 			goto out;
264 		}
265 		root_dir = path;
266 	}
267 
268 	machine = machines__add(machines, pid, root_dir);
269 out:
270 	return machine;
271 }
272 
273 void machines__process_guests(struct machines *machines,
274 			      machine__process_t process, void *data)
275 {
276 	struct rb_node *nd;
277 
278 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
279 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
280 		process(pos, data);
281 	}
282 }
283 
284 char *machine__mmap_name(struct machine *machine, char *bf, size_t size)
285 {
286 	if (machine__is_host(machine))
287 		snprintf(bf, size, "[%s]", "kernel.kallsyms");
288 	else if (machine__is_default_guest(machine))
289 		snprintf(bf, size, "[%s]", "guest.kernel.kallsyms");
290 	else {
291 		snprintf(bf, size, "[%s.%d]", "guest.kernel.kallsyms",
292 			 machine->pid);
293 	}
294 
295 	return bf;
296 }
297 
298 void machines__set_id_hdr_size(struct machines *machines, u16 id_hdr_size)
299 {
300 	struct rb_node *node;
301 	struct machine *machine;
302 
303 	machines->host.id_hdr_size = id_hdr_size;
304 
305 	for (node = rb_first(&machines->guests); node; node = rb_next(node)) {
306 		machine = rb_entry(node, struct machine, rb_node);
307 		machine->id_hdr_size = id_hdr_size;
308 	}
309 
310 	return;
311 }
312 
313 static void machine__update_thread_pid(struct machine *machine,
314 				       struct thread *th, pid_t pid)
315 {
316 	struct thread *leader;
317 
318 	if (pid == th->pid_ || pid == -1 || th->pid_ != -1)
319 		return;
320 
321 	th->pid_ = pid;
322 
323 	if (th->pid_ == th->tid)
324 		return;
325 
326 	leader = __machine__findnew_thread(machine, th->pid_, th->pid_);
327 	if (!leader)
328 		goto out_err;
329 
330 	if (!leader->mg)
331 		leader->mg = map_groups__new(machine);
332 
333 	if (!leader->mg)
334 		goto out_err;
335 
336 	if (th->mg == leader->mg)
337 		return;
338 
339 	if (th->mg) {
340 		/*
341 		 * Maps are created from MMAP events which provide the pid and
342 		 * tid.  Consequently there never should be any maps on a thread
343 		 * with an unknown pid.  Just print an error if there are.
344 		 */
345 		if (!map_groups__empty(th->mg))
346 			pr_err("Discarding thread maps for %d:%d\n",
347 			       th->pid_, th->tid);
348 		map_groups__put(th->mg);
349 	}
350 
351 	th->mg = map_groups__get(leader->mg);
352 
353 	return;
354 
355 out_err:
356 	pr_err("Failed to join map groups for %d:%d\n", th->pid_, th->tid);
357 }
358 
359 static struct thread *____machine__findnew_thread(struct machine *machine,
360 						  pid_t pid, pid_t tid,
361 						  bool create)
362 {
363 	struct rb_node **p = &machine->threads.rb_node;
364 	struct rb_node *parent = NULL;
365 	struct thread *th;
366 
367 	/*
368 	 * Front-end cache - TID lookups come in blocks,
369 	 * so most of the time we dont have to look up
370 	 * the full rbtree:
371 	 */
372 	th = machine->last_match;
373 	if (th != NULL) {
374 		if (th->tid == tid) {
375 			machine__update_thread_pid(machine, th, pid);
376 			return th;
377 		}
378 
379 		machine->last_match = NULL;
380 	}
381 
382 	while (*p != NULL) {
383 		parent = *p;
384 		th = rb_entry(parent, struct thread, rb_node);
385 
386 		if (th->tid == tid) {
387 			machine->last_match = th;
388 			machine__update_thread_pid(machine, th, pid);
389 			return th;
390 		}
391 
392 		if (tid < th->tid)
393 			p = &(*p)->rb_left;
394 		else
395 			p = &(*p)->rb_right;
396 	}
397 
398 	if (!create)
399 		return NULL;
400 
401 	th = thread__new(pid, tid);
402 	if (th != NULL) {
403 		rb_link_node(&th->rb_node, parent, p);
404 		rb_insert_color(&th->rb_node, &machine->threads);
405 
406 		/*
407 		 * We have to initialize map_groups separately
408 		 * after rb tree is updated.
409 		 *
410 		 * The reason is that we call machine__findnew_thread
411 		 * within thread__init_map_groups to find the thread
412 		 * leader and that would screwed the rb tree.
413 		 */
414 		if (thread__init_map_groups(th, machine)) {
415 			rb_erase_init(&th->rb_node, &machine->threads);
416 			RB_CLEAR_NODE(&th->rb_node);
417 			thread__delete(th);
418 			return NULL;
419 		}
420 		/*
421 		 * It is now in the rbtree, get a ref
422 		 */
423 		thread__get(th);
424 		machine->last_match = th;
425 	}
426 
427 	return th;
428 }
429 
430 struct thread *__machine__findnew_thread(struct machine *machine, pid_t pid, pid_t tid)
431 {
432 	return ____machine__findnew_thread(machine, pid, tid, true);
433 }
434 
435 struct thread *machine__findnew_thread(struct machine *machine, pid_t pid,
436 				       pid_t tid)
437 {
438 	struct thread *th;
439 
440 	pthread_rwlock_wrlock(&machine->threads_lock);
441 	th = thread__get(__machine__findnew_thread(machine, pid, tid));
442 	pthread_rwlock_unlock(&machine->threads_lock);
443 	return th;
444 }
445 
446 struct thread *machine__find_thread(struct machine *machine, pid_t pid,
447 				    pid_t tid)
448 {
449 	struct thread *th;
450 	pthread_rwlock_rdlock(&machine->threads_lock);
451 	th =  thread__get(____machine__findnew_thread(machine, pid, tid, false));
452 	pthread_rwlock_unlock(&machine->threads_lock);
453 	return th;
454 }
455 
456 struct comm *machine__thread_exec_comm(struct machine *machine,
457 				       struct thread *thread)
458 {
459 	if (machine->comm_exec)
460 		return thread__exec_comm(thread);
461 	else
462 		return thread__comm(thread);
463 }
464 
465 int machine__process_comm_event(struct machine *machine, union perf_event *event,
466 				struct perf_sample *sample)
467 {
468 	struct thread *thread = machine__findnew_thread(machine,
469 							event->comm.pid,
470 							event->comm.tid);
471 	bool exec = event->header.misc & PERF_RECORD_MISC_COMM_EXEC;
472 	int err = 0;
473 
474 	if (exec)
475 		machine->comm_exec = true;
476 
477 	if (dump_trace)
478 		perf_event__fprintf_comm(event, stdout);
479 
480 	if (thread == NULL ||
481 	    __thread__set_comm(thread, event->comm.comm, sample->time, exec)) {
482 		dump_printf("problem processing PERF_RECORD_COMM, skipping event.\n");
483 		err = -1;
484 	}
485 
486 	thread__put(thread);
487 
488 	return err;
489 }
490 
491 int machine__process_lost_event(struct machine *machine __maybe_unused,
492 				union perf_event *event, struct perf_sample *sample __maybe_unused)
493 {
494 	dump_printf(": id:%" PRIu64 ": lost:%" PRIu64 "\n",
495 		    event->lost.id, event->lost.lost);
496 	return 0;
497 }
498 
499 int machine__process_lost_samples_event(struct machine *machine __maybe_unused,
500 					union perf_event *event, struct perf_sample *sample)
501 {
502 	dump_printf(": id:%" PRIu64 ": lost samples :%" PRIu64 "\n",
503 		    sample->id, event->lost_samples.lost);
504 	return 0;
505 }
506 
507 static struct dso *machine__findnew_module_dso(struct machine *machine,
508 					       struct kmod_path *m,
509 					       const char *filename)
510 {
511 	struct dso *dso;
512 
513 	pthread_rwlock_wrlock(&machine->dsos.lock);
514 
515 	dso = __dsos__find(&machine->dsos, m->name, true);
516 	if (!dso) {
517 		dso = __dsos__addnew(&machine->dsos, m->name);
518 		if (dso == NULL)
519 			goto out_unlock;
520 
521 		if (machine__is_host(machine))
522 			dso->symtab_type = DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE;
523 		else
524 			dso->symtab_type = DSO_BINARY_TYPE__GUEST_KMODULE;
525 
526 		/* _KMODULE_COMP should be next to _KMODULE */
527 		if (m->kmod && m->comp)
528 			dso->symtab_type++;
529 
530 		dso__set_short_name(dso, strdup(m->name), true);
531 		dso__set_long_name(dso, strdup(filename), true);
532 	}
533 
534 	dso__get(dso);
535 out_unlock:
536 	pthread_rwlock_unlock(&machine->dsos.lock);
537 	return dso;
538 }
539 
540 int machine__process_aux_event(struct machine *machine __maybe_unused,
541 			       union perf_event *event)
542 {
543 	if (dump_trace)
544 		perf_event__fprintf_aux(event, stdout);
545 	return 0;
546 }
547 
548 int machine__process_itrace_start_event(struct machine *machine __maybe_unused,
549 					union perf_event *event)
550 {
551 	if (dump_trace)
552 		perf_event__fprintf_itrace_start(event, stdout);
553 	return 0;
554 }
555 
556 int machine__process_switch_event(struct machine *machine __maybe_unused,
557 				  union perf_event *event)
558 {
559 	if (dump_trace)
560 		perf_event__fprintf_switch(event, stdout);
561 	return 0;
562 }
563 
564 static void dso__adjust_kmod_long_name(struct dso *dso, const char *filename)
565 {
566 	const char *dup_filename;
567 
568 	if (!filename || !dso || !dso->long_name)
569 		return;
570 	if (dso->long_name[0] != '[')
571 		return;
572 	if (!strchr(filename, '/'))
573 		return;
574 
575 	dup_filename = strdup(filename);
576 	if (!dup_filename)
577 		return;
578 
579 	dso__set_long_name(dso, filename, true);
580 }
581 
582 struct map *machine__findnew_module_map(struct machine *machine, u64 start,
583 					const char *filename)
584 {
585 	struct map *map = NULL;
586 	struct dso *dso = NULL;
587 	struct kmod_path m;
588 
589 	if (kmod_path__parse_name(&m, filename))
590 		return NULL;
591 
592 	map = map_groups__find_by_name(&machine->kmaps, MAP__FUNCTION,
593 				       m.name);
594 	if (map) {
595 		/*
596 		 * If the map's dso is an offline module, give dso__load()
597 		 * a chance to find the file path of that module by fixing
598 		 * long_name.
599 		 */
600 		dso__adjust_kmod_long_name(map->dso, filename);
601 		goto out;
602 	}
603 
604 	dso = machine__findnew_module_dso(machine, &m, filename);
605 	if (dso == NULL)
606 		goto out;
607 
608 	map = map__new2(start, dso, MAP__FUNCTION);
609 	if (map == NULL)
610 		goto out;
611 
612 	map_groups__insert(&machine->kmaps, map);
613 
614 	/* Put the map here because map_groups__insert alread got it */
615 	map__put(map);
616 out:
617 	/* put the dso here, corresponding to  machine__findnew_module_dso */
618 	dso__put(dso);
619 	free(m.name);
620 	return map;
621 }
622 
623 size_t machines__fprintf_dsos(struct machines *machines, FILE *fp)
624 {
625 	struct rb_node *nd;
626 	size_t ret = __dsos__fprintf(&machines->host.dsos.head, fp);
627 
628 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
629 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
630 		ret += __dsos__fprintf(&pos->dsos.head, fp);
631 	}
632 
633 	return ret;
634 }
635 
636 size_t machine__fprintf_dsos_buildid(struct machine *m, FILE *fp,
637 				     bool (skip)(struct dso *dso, int parm), int parm)
638 {
639 	return __dsos__fprintf_buildid(&m->dsos.head, fp, skip, parm);
640 }
641 
642 size_t machines__fprintf_dsos_buildid(struct machines *machines, FILE *fp,
643 				     bool (skip)(struct dso *dso, int parm), int parm)
644 {
645 	struct rb_node *nd;
646 	size_t ret = machine__fprintf_dsos_buildid(&machines->host, fp, skip, parm);
647 
648 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
649 		struct machine *pos = rb_entry(nd, struct machine, rb_node);
650 		ret += machine__fprintf_dsos_buildid(pos, fp, skip, parm);
651 	}
652 	return ret;
653 }
654 
655 size_t machine__fprintf_vmlinux_path(struct machine *machine, FILE *fp)
656 {
657 	int i;
658 	size_t printed = 0;
659 	struct dso *kdso = machine__kernel_map(machine)->dso;
660 
661 	if (kdso->has_build_id) {
662 		char filename[PATH_MAX];
663 		if (dso__build_id_filename(kdso, filename, sizeof(filename)))
664 			printed += fprintf(fp, "[0] %s\n", filename);
665 	}
666 
667 	for (i = 0; i < vmlinux_path__nr_entries; ++i)
668 		printed += fprintf(fp, "[%d] %s\n",
669 				   i + kdso->has_build_id, vmlinux_path[i]);
670 
671 	return printed;
672 }
673 
674 size_t machine__fprintf(struct machine *machine, FILE *fp)
675 {
676 	size_t ret = 0;
677 	struct rb_node *nd;
678 
679 	pthread_rwlock_rdlock(&machine->threads_lock);
680 
681 	for (nd = rb_first(&machine->threads); nd; nd = rb_next(nd)) {
682 		struct thread *pos = rb_entry(nd, struct thread, rb_node);
683 
684 		ret += thread__fprintf(pos, fp);
685 	}
686 
687 	pthread_rwlock_unlock(&machine->threads_lock);
688 
689 	return ret;
690 }
691 
692 static struct dso *machine__get_kernel(struct machine *machine)
693 {
694 	const char *vmlinux_name = NULL;
695 	struct dso *kernel;
696 
697 	if (machine__is_host(machine)) {
698 		vmlinux_name = symbol_conf.vmlinux_name;
699 		if (!vmlinux_name)
700 			vmlinux_name = "[kernel.kallsyms]";
701 
702 		kernel = machine__findnew_kernel(machine, vmlinux_name,
703 						 "[kernel]", DSO_TYPE_KERNEL);
704 	} else {
705 		char bf[PATH_MAX];
706 
707 		if (machine__is_default_guest(machine))
708 			vmlinux_name = symbol_conf.default_guest_vmlinux_name;
709 		if (!vmlinux_name)
710 			vmlinux_name = machine__mmap_name(machine, bf,
711 							  sizeof(bf));
712 
713 		kernel = machine__findnew_kernel(machine, vmlinux_name,
714 						 "[guest.kernel]",
715 						 DSO_TYPE_GUEST_KERNEL);
716 	}
717 
718 	if (kernel != NULL && (!kernel->has_build_id))
719 		dso__read_running_kernel_build_id(kernel, machine);
720 
721 	return kernel;
722 }
723 
724 struct process_args {
725 	u64 start;
726 };
727 
728 static void machine__get_kallsyms_filename(struct machine *machine, char *buf,
729 					   size_t bufsz)
730 {
731 	if (machine__is_default_guest(machine))
732 		scnprintf(buf, bufsz, "%s", symbol_conf.default_guest_kallsyms);
733 	else
734 		scnprintf(buf, bufsz, "%s/proc/kallsyms", machine->root_dir);
735 }
736 
737 const char *ref_reloc_sym_names[] = {"_text", "_stext", NULL};
738 
739 /* Figure out the start address of kernel map from /proc/kallsyms.
740  * Returns the name of the start symbol in *symbol_name. Pass in NULL as
741  * symbol_name if it's not that important.
742  */
743 static u64 machine__get_running_kernel_start(struct machine *machine,
744 					     const char **symbol_name)
745 {
746 	char filename[PATH_MAX];
747 	int i;
748 	const char *name;
749 	u64 addr = 0;
750 
751 	machine__get_kallsyms_filename(machine, filename, PATH_MAX);
752 
753 	if (symbol__restricted_filename(filename, "/proc/kallsyms"))
754 		return 0;
755 
756 	for (i = 0; (name = ref_reloc_sym_names[i]) != NULL; i++) {
757 		addr = kallsyms__get_function_start(filename, name);
758 		if (addr)
759 			break;
760 	}
761 
762 	if (symbol_name)
763 		*symbol_name = name;
764 
765 	return addr;
766 }
767 
768 int __machine__create_kernel_maps(struct machine *machine, struct dso *kernel)
769 {
770 	enum map_type type;
771 	u64 start = machine__get_running_kernel_start(machine, NULL);
772 
773 	for (type = 0; type < MAP__NR_TYPES; ++type) {
774 		struct kmap *kmap;
775 		struct map *map;
776 
777 		machine->vmlinux_maps[type] = map__new2(start, kernel, type);
778 		if (machine->vmlinux_maps[type] == NULL)
779 			return -1;
780 
781 		machine->vmlinux_maps[type]->map_ip =
782 			machine->vmlinux_maps[type]->unmap_ip =
783 				identity__map_ip;
784 		map = __machine__kernel_map(machine, type);
785 		kmap = map__kmap(map);
786 		if (!kmap)
787 			return -1;
788 
789 		kmap->kmaps = &machine->kmaps;
790 		map_groups__insert(&machine->kmaps, map);
791 	}
792 
793 	return 0;
794 }
795 
796 void machine__destroy_kernel_maps(struct machine *machine)
797 {
798 	enum map_type type;
799 
800 	for (type = 0; type < MAP__NR_TYPES; ++type) {
801 		struct kmap *kmap;
802 		struct map *map = __machine__kernel_map(machine, type);
803 
804 		if (map == NULL)
805 			continue;
806 
807 		kmap = map__kmap(map);
808 		map_groups__remove(&machine->kmaps, map);
809 		if (kmap && kmap->ref_reloc_sym) {
810 			/*
811 			 * ref_reloc_sym is shared among all maps, so free just
812 			 * on one of them.
813 			 */
814 			if (type == MAP__FUNCTION) {
815 				zfree((char **)&kmap->ref_reloc_sym->name);
816 				zfree(&kmap->ref_reloc_sym);
817 			} else
818 				kmap->ref_reloc_sym = NULL;
819 		}
820 
821 		map__put(machine->vmlinux_maps[type]);
822 		machine->vmlinux_maps[type] = NULL;
823 	}
824 }
825 
826 int machines__create_guest_kernel_maps(struct machines *machines)
827 {
828 	int ret = 0;
829 	struct dirent **namelist = NULL;
830 	int i, items = 0;
831 	char path[PATH_MAX];
832 	pid_t pid;
833 	char *endp;
834 
835 	if (symbol_conf.default_guest_vmlinux_name ||
836 	    symbol_conf.default_guest_modules ||
837 	    symbol_conf.default_guest_kallsyms) {
838 		machines__create_kernel_maps(machines, DEFAULT_GUEST_KERNEL_ID);
839 	}
840 
841 	if (symbol_conf.guestmount) {
842 		items = scandir(symbol_conf.guestmount, &namelist, NULL, NULL);
843 		if (items <= 0)
844 			return -ENOENT;
845 		for (i = 0; i < items; i++) {
846 			if (!isdigit(namelist[i]->d_name[0])) {
847 				/* Filter out . and .. */
848 				continue;
849 			}
850 			pid = (pid_t)strtol(namelist[i]->d_name, &endp, 10);
851 			if ((*endp != '\0') ||
852 			    (endp == namelist[i]->d_name) ||
853 			    (errno == ERANGE)) {
854 				pr_debug("invalid directory (%s). Skipping.\n",
855 					 namelist[i]->d_name);
856 				continue;
857 			}
858 			sprintf(path, "%s/%s/proc/kallsyms",
859 				symbol_conf.guestmount,
860 				namelist[i]->d_name);
861 			ret = access(path, R_OK);
862 			if (ret) {
863 				pr_debug("Can't access file %s\n", path);
864 				goto failure;
865 			}
866 			machines__create_kernel_maps(machines, pid);
867 		}
868 failure:
869 		free(namelist);
870 	}
871 
872 	return ret;
873 }
874 
875 void machines__destroy_kernel_maps(struct machines *machines)
876 {
877 	struct rb_node *next = rb_first(&machines->guests);
878 
879 	machine__destroy_kernel_maps(&machines->host);
880 
881 	while (next) {
882 		struct machine *pos = rb_entry(next, struct machine, rb_node);
883 
884 		next = rb_next(&pos->rb_node);
885 		rb_erase(&pos->rb_node, &machines->guests);
886 		machine__delete(pos);
887 	}
888 }
889 
890 int machines__create_kernel_maps(struct machines *machines, pid_t pid)
891 {
892 	struct machine *machine = machines__findnew(machines, pid);
893 
894 	if (machine == NULL)
895 		return -1;
896 
897 	return machine__create_kernel_maps(machine);
898 }
899 
900 int machine__load_kallsyms(struct machine *machine, const char *filename,
901 			   enum map_type type, symbol_filter_t filter)
902 {
903 	struct map *map = machine__kernel_map(machine);
904 	int ret = dso__load_kallsyms(map->dso, filename, map, filter);
905 
906 	if (ret > 0) {
907 		dso__set_loaded(map->dso, type);
908 		/*
909 		 * Since /proc/kallsyms will have multiple sessions for the
910 		 * kernel, with modules between them, fixup the end of all
911 		 * sections.
912 		 */
913 		__map_groups__fixup_end(&machine->kmaps, type);
914 	}
915 
916 	return ret;
917 }
918 
919 int machine__load_vmlinux_path(struct machine *machine, enum map_type type,
920 			       symbol_filter_t filter)
921 {
922 	struct map *map = machine__kernel_map(machine);
923 	int ret = dso__load_vmlinux_path(map->dso, map, filter);
924 
925 	if (ret > 0)
926 		dso__set_loaded(map->dso, type);
927 
928 	return ret;
929 }
930 
931 static void map_groups__fixup_end(struct map_groups *mg)
932 {
933 	int i;
934 	for (i = 0; i < MAP__NR_TYPES; ++i)
935 		__map_groups__fixup_end(mg, i);
936 }
937 
938 static char *get_kernel_version(const char *root_dir)
939 {
940 	char version[PATH_MAX];
941 	FILE *file;
942 	char *name, *tmp;
943 	const char *prefix = "Linux version ";
944 
945 	sprintf(version, "%s/proc/version", root_dir);
946 	file = fopen(version, "r");
947 	if (!file)
948 		return NULL;
949 
950 	version[0] = '\0';
951 	tmp = fgets(version, sizeof(version), file);
952 	fclose(file);
953 
954 	name = strstr(version, prefix);
955 	if (!name)
956 		return NULL;
957 	name += strlen(prefix);
958 	tmp = strchr(name, ' ');
959 	if (tmp)
960 		*tmp = '\0';
961 
962 	return strdup(name);
963 }
964 
965 static bool is_kmod_dso(struct dso *dso)
966 {
967 	return dso->symtab_type == DSO_BINARY_TYPE__SYSTEM_PATH_KMODULE ||
968 	       dso->symtab_type == DSO_BINARY_TYPE__GUEST_KMODULE;
969 }
970 
971 static int map_groups__set_module_path(struct map_groups *mg, const char *path,
972 				       struct kmod_path *m)
973 {
974 	struct map *map;
975 	char *long_name;
976 
977 	map = map_groups__find_by_name(mg, MAP__FUNCTION, m->name);
978 	if (map == NULL)
979 		return 0;
980 
981 	long_name = strdup(path);
982 	if (long_name == NULL)
983 		return -ENOMEM;
984 
985 	dso__set_long_name(map->dso, long_name, true);
986 	dso__kernel_module_get_build_id(map->dso, "");
987 
988 	/*
989 	 * Full name could reveal us kmod compression, so
990 	 * we need to update the symtab_type if needed.
991 	 */
992 	if (m->comp && is_kmod_dso(map->dso))
993 		map->dso->symtab_type++;
994 
995 	return 0;
996 }
997 
998 static int map_groups__set_modules_path_dir(struct map_groups *mg,
999 				const char *dir_name, int depth)
1000 {
1001 	struct dirent *dent;
1002 	DIR *dir = opendir(dir_name);
1003 	int ret = 0;
1004 
1005 	if (!dir) {
1006 		pr_debug("%s: cannot open %s dir\n", __func__, dir_name);
1007 		return -1;
1008 	}
1009 
1010 	while ((dent = readdir(dir)) != NULL) {
1011 		char path[PATH_MAX];
1012 		struct stat st;
1013 
1014 		/*sshfs might return bad dent->d_type, so we have to stat*/
1015 		snprintf(path, sizeof(path), "%s/%s", dir_name, dent->d_name);
1016 		if (stat(path, &st))
1017 			continue;
1018 
1019 		if (S_ISDIR(st.st_mode)) {
1020 			if (!strcmp(dent->d_name, ".") ||
1021 			    !strcmp(dent->d_name, ".."))
1022 				continue;
1023 
1024 			/* Do not follow top-level source and build symlinks */
1025 			if (depth == 0) {
1026 				if (!strcmp(dent->d_name, "source") ||
1027 				    !strcmp(dent->d_name, "build"))
1028 					continue;
1029 			}
1030 
1031 			ret = map_groups__set_modules_path_dir(mg, path,
1032 							       depth + 1);
1033 			if (ret < 0)
1034 				goto out;
1035 		} else {
1036 			struct kmod_path m;
1037 
1038 			ret = kmod_path__parse_name(&m, dent->d_name);
1039 			if (ret)
1040 				goto out;
1041 
1042 			if (m.kmod)
1043 				ret = map_groups__set_module_path(mg, path, &m);
1044 
1045 			free(m.name);
1046 
1047 			if (ret)
1048 				goto out;
1049 		}
1050 	}
1051 
1052 out:
1053 	closedir(dir);
1054 	return ret;
1055 }
1056 
1057 static int machine__set_modules_path(struct machine *machine)
1058 {
1059 	char *version;
1060 	char modules_path[PATH_MAX];
1061 
1062 	version = get_kernel_version(machine->root_dir);
1063 	if (!version)
1064 		return -1;
1065 
1066 	snprintf(modules_path, sizeof(modules_path), "%s/lib/modules/%s",
1067 		 machine->root_dir, version);
1068 	free(version);
1069 
1070 	return map_groups__set_modules_path_dir(&machine->kmaps, modules_path, 0);
1071 }
1072 
1073 static int machine__create_module(void *arg, const char *name, u64 start)
1074 {
1075 	struct machine *machine = arg;
1076 	struct map *map;
1077 
1078 	map = machine__findnew_module_map(machine, start, name);
1079 	if (map == NULL)
1080 		return -1;
1081 
1082 	dso__kernel_module_get_build_id(map->dso, machine->root_dir);
1083 
1084 	return 0;
1085 }
1086 
1087 static int machine__create_modules(struct machine *machine)
1088 {
1089 	const char *modules;
1090 	char path[PATH_MAX];
1091 
1092 	if (machine__is_default_guest(machine)) {
1093 		modules = symbol_conf.default_guest_modules;
1094 	} else {
1095 		snprintf(path, PATH_MAX, "%s/proc/modules", machine->root_dir);
1096 		modules = path;
1097 	}
1098 
1099 	if (symbol__restricted_filename(modules, "/proc/modules"))
1100 		return -1;
1101 
1102 	if (modules__parse(modules, machine, machine__create_module))
1103 		return -1;
1104 
1105 	if (!machine__set_modules_path(machine))
1106 		return 0;
1107 
1108 	pr_debug("Problems setting modules path maps, continuing anyway...\n");
1109 
1110 	return 0;
1111 }
1112 
1113 int machine__create_kernel_maps(struct machine *machine)
1114 {
1115 	struct dso *kernel = machine__get_kernel(machine);
1116 	const char *name;
1117 	u64 addr = machine__get_running_kernel_start(machine, &name);
1118 	int ret;
1119 
1120 	if (!addr || kernel == NULL)
1121 		return -1;
1122 
1123 	ret = __machine__create_kernel_maps(machine, kernel);
1124 	dso__put(kernel);
1125 	if (ret < 0)
1126 		return -1;
1127 
1128 	if (symbol_conf.use_modules && machine__create_modules(machine) < 0) {
1129 		if (machine__is_host(machine))
1130 			pr_debug("Problems creating module maps, "
1131 				 "continuing anyway...\n");
1132 		else
1133 			pr_debug("Problems creating module maps for guest %d, "
1134 				 "continuing anyway...\n", machine->pid);
1135 	}
1136 
1137 	/*
1138 	 * Now that we have all the maps created, just set the ->end of them:
1139 	 */
1140 	map_groups__fixup_end(&machine->kmaps);
1141 
1142 	if (maps__set_kallsyms_ref_reloc_sym(machine->vmlinux_maps, name,
1143 					     addr)) {
1144 		machine__destroy_kernel_maps(machine);
1145 		return -1;
1146 	}
1147 
1148 	return 0;
1149 }
1150 
1151 static void machine__set_kernel_mmap_len(struct machine *machine,
1152 					 union perf_event *event)
1153 {
1154 	int i;
1155 
1156 	for (i = 0; i < MAP__NR_TYPES; i++) {
1157 		machine->vmlinux_maps[i]->start = event->mmap.start;
1158 		machine->vmlinux_maps[i]->end   = (event->mmap.start +
1159 						   event->mmap.len);
1160 		/*
1161 		 * Be a bit paranoid here, some perf.data file came with
1162 		 * a zero sized synthesized MMAP event for the kernel.
1163 		 */
1164 		if (machine->vmlinux_maps[i]->end == 0)
1165 			machine->vmlinux_maps[i]->end = ~0ULL;
1166 	}
1167 }
1168 
1169 static bool machine__uses_kcore(struct machine *machine)
1170 {
1171 	struct dso *dso;
1172 
1173 	list_for_each_entry(dso, &machine->dsos.head, node) {
1174 		if (dso__is_kcore(dso))
1175 			return true;
1176 	}
1177 
1178 	return false;
1179 }
1180 
1181 static int machine__process_kernel_mmap_event(struct machine *machine,
1182 					      union perf_event *event)
1183 {
1184 	struct map *map;
1185 	char kmmap_prefix[PATH_MAX];
1186 	enum dso_kernel_type kernel_type;
1187 	bool is_kernel_mmap;
1188 
1189 	/* If we have maps from kcore then we do not need or want any others */
1190 	if (machine__uses_kcore(machine))
1191 		return 0;
1192 
1193 	machine__mmap_name(machine, kmmap_prefix, sizeof(kmmap_prefix));
1194 	if (machine__is_host(machine))
1195 		kernel_type = DSO_TYPE_KERNEL;
1196 	else
1197 		kernel_type = DSO_TYPE_GUEST_KERNEL;
1198 
1199 	is_kernel_mmap = memcmp(event->mmap.filename,
1200 				kmmap_prefix,
1201 				strlen(kmmap_prefix) - 1) == 0;
1202 	if (event->mmap.filename[0] == '/' ||
1203 	    (!is_kernel_mmap && event->mmap.filename[0] == '[')) {
1204 		map = machine__findnew_module_map(machine, event->mmap.start,
1205 						  event->mmap.filename);
1206 		if (map == NULL)
1207 			goto out_problem;
1208 
1209 		map->end = map->start + event->mmap.len;
1210 	} else if (is_kernel_mmap) {
1211 		const char *symbol_name = (event->mmap.filename +
1212 				strlen(kmmap_prefix));
1213 		/*
1214 		 * Should be there already, from the build-id table in
1215 		 * the header.
1216 		 */
1217 		struct dso *kernel = NULL;
1218 		struct dso *dso;
1219 
1220 		pthread_rwlock_rdlock(&machine->dsos.lock);
1221 
1222 		list_for_each_entry(dso, &machine->dsos.head, node) {
1223 
1224 			/*
1225 			 * The cpumode passed to is_kernel_module is not the
1226 			 * cpumode of *this* event. If we insist on passing
1227 			 * correct cpumode to is_kernel_module, we should
1228 			 * record the cpumode when we adding this dso to the
1229 			 * linked list.
1230 			 *
1231 			 * However we don't really need passing correct
1232 			 * cpumode.  We know the correct cpumode must be kernel
1233 			 * mode (if not, we should not link it onto kernel_dsos
1234 			 * list).
1235 			 *
1236 			 * Therefore, we pass PERF_RECORD_MISC_CPUMODE_UNKNOWN.
1237 			 * is_kernel_module() treats it as a kernel cpumode.
1238 			 */
1239 
1240 			if (!dso->kernel ||
1241 			    is_kernel_module(dso->long_name,
1242 					     PERF_RECORD_MISC_CPUMODE_UNKNOWN))
1243 				continue;
1244 
1245 
1246 			kernel = dso;
1247 			break;
1248 		}
1249 
1250 		pthread_rwlock_unlock(&machine->dsos.lock);
1251 
1252 		if (kernel == NULL)
1253 			kernel = machine__findnew_dso(machine, kmmap_prefix);
1254 		if (kernel == NULL)
1255 			goto out_problem;
1256 
1257 		kernel->kernel = kernel_type;
1258 		if (__machine__create_kernel_maps(machine, kernel) < 0) {
1259 			dso__put(kernel);
1260 			goto out_problem;
1261 		}
1262 
1263 		if (strstr(kernel->long_name, "vmlinux"))
1264 			dso__set_short_name(kernel, "[kernel.vmlinux]", false);
1265 
1266 		machine__set_kernel_mmap_len(machine, event);
1267 
1268 		/*
1269 		 * Avoid using a zero address (kptr_restrict) for the ref reloc
1270 		 * symbol. Effectively having zero here means that at record
1271 		 * time /proc/sys/kernel/kptr_restrict was non zero.
1272 		 */
1273 		if (event->mmap.pgoff != 0) {
1274 			maps__set_kallsyms_ref_reloc_sym(machine->vmlinux_maps,
1275 							 symbol_name,
1276 							 event->mmap.pgoff);
1277 		}
1278 
1279 		if (machine__is_default_guest(machine)) {
1280 			/*
1281 			 * preload dso of guest kernel and modules
1282 			 */
1283 			dso__load(kernel, machine__kernel_map(machine), NULL);
1284 		}
1285 	}
1286 	return 0;
1287 out_problem:
1288 	return -1;
1289 }
1290 
1291 int machine__process_mmap2_event(struct machine *machine,
1292 				 union perf_event *event,
1293 				 struct perf_sample *sample __maybe_unused)
1294 {
1295 	u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1296 	struct thread *thread;
1297 	struct map *map;
1298 	enum map_type type;
1299 	int ret = 0;
1300 
1301 	if (dump_trace)
1302 		perf_event__fprintf_mmap2(event, stdout);
1303 
1304 	if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1305 	    cpumode == PERF_RECORD_MISC_KERNEL) {
1306 		ret = machine__process_kernel_mmap_event(machine, event);
1307 		if (ret < 0)
1308 			goto out_problem;
1309 		return 0;
1310 	}
1311 
1312 	thread = machine__findnew_thread(machine, event->mmap2.pid,
1313 					event->mmap2.tid);
1314 	if (thread == NULL)
1315 		goto out_problem;
1316 
1317 	if (event->header.misc & PERF_RECORD_MISC_MMAP_DATA)
1318 		type = MAP__VARIABLE;
1319 	else
1320 		type = MAP__FUNCTION;
1321 
1322 	map = map__new(machine, event->mmap2.start,
1323 			event->mmap2.len, event->mmap2.pgoff,
1324 			event->mmap2.pid, event->mmap2.maj,
1325 			event->mmap2.min, event->mmap2.ino,
1326 			event->mmap2.ino_generation,
1327 			event->mmap2.prot,
1328 			event->mmap2.flags,
1329 			event->mmap2.filename, type, thread);
1330 
1331 	if (map == NULL)
1332 		goto out_problem_map;
1333 
1334 	thread__insert_map(thread, map);
1335 	thread__put(thread);
1336 	map__put(map);
1337 	return 0;
1338 
1339 out_problem_map:
1340 	thread__put(thread);
1341 out_problem:
1342 	dump_printf("problem processing PERF_RECORD_MMAP2, skipping event.\n");
1343 	return 0;
1344 }
1345 
1346 int machine__process_mmap_event(struct machine *machine, union perf_event *event,
1347 				struct perf_sample *sample __maybe_unused)
1348 {
1349 	u8 cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
1350 	struct thread *thread;
1351 	struct map *map;
1352 	enum map_type type;
1353 	int ret = 0;
1354 
1355 	if (dump_trace)
1356 		perf_event__fprintf_mmap(event, stdout);
1357 
1358 	if (cpumode == PERF_RECORD_MISC_GUEST_KERNEL ||
1359 	    cpumode == PERF_RECORD_MISC_KERNEL) {
1360 		ret = machine__process_kernel_mmap_event(machine, event);
1361 		if (ret < 0)
1362 			goto out_problem;
1363 		return 0;
1364 	}
1365 
1366 	thread = machine__findnew_thread(machine, event->mmap.pid,
1367 					 event->mmap.tid);
1368 	if (thread == NULL)
1369 		goto out_problem;
1370 
1371 	if (event->header.misc & PERF_RECORD_MISC_MMAP_DATA)
1372 		type = MAP__VARIABLE;
1373 	else
1374 		type = MAP__FUNCTION;
1375 
1376 	map = map__new(machine, event->mmap.start,
1377 			event->mmap.len, event->mmap.pgoff,
1378 			event->mmap.pid, 0, 0, 0, 0, 0, 0,
1379 			event->mmap.filename,
1380 			type, thread);
1381 
1382 	if (map == NULL)
1383 		goto out_problem_map;
1384 
1385 	thread__insert_map(thread, map);
1386 	thread__put(thread);
1387 	map__put(map);
1388 	return 0;
1389 
1390 out_problem_map:
1391 	thread__put(thread);
1392 out_problem:
1393 	dump_printf("problem processing PERF_RECORD_MMAP, skipping event.\n");
1394 	return 0;
1395 }
1396 
1397 static void __machine__remove_thread(struct machine *machine, struct thread *th, bool lock)
1398 {
1399 	if (machine->last_match == th)
1400 		machine->last_match = NULL;
1401 
1402 	BUG_ON(atomic_read(&th->refcnt) == 0);
1403 	if (lock)
1404 		pthread_rwlock_wrlock(&machine->threads_lock);
1405 	rb_erase_init(&th->rb_node, &machine->threads);
1406 	RB_CLEAR_NODE(&th->rb_node);
1407 	/*
1408 	 * Move it first to the dead_threads list, then drop the reference,
1409 	 * if this is the last reference, then the thread__delete destructor
1410 	 * will be called and we will remove it from the dead_threads list.
1411 	 */
1412 	list_add_tail(&th->node, &machine->dead_threads);
1413 	if (lock)
1414 		pthread_rwlock_unlock(&machine->threads_lock);
1415 	thread__put(th);
1416 }
1417 
1418 void machine__remove_thread(struct machine *machine, struct thread *th)
1419 {
1420 	return __machine__remove_thread(machine, th, true);
1421 }
1422 
1423 int machine__process_fork_event(struct machine *machine, union perf_event *event,
1424 				struct perf_sample *sample)
1425 {
1426 	struct thread *thread = machine__find_thread(machine,
1427 						     event->fork.pid,
1428 						     event->fork.tid);
1429 	struct thread *parent = machine__findnew_thread(machine,
1430 							event->fork.ppid,
1431 							event->fork.ptid);
1432 	int err = 0;
1433 
1434 	if (dump_trace)
1435 		perf_event__fprintf_task(event, stdout);
1436 
1437 	/*
1438 	 * There may be an existing thread that is not actually the parent,
1439 	 * either because we are processing events out of order, or because the
1440 	 * (fork) event that would have removed the thread was lost. Assume the
1441 	 * latter case and continue on as best we can.
1442 	 */
1443 	if (parent->pid_ != (pid_t)event->fork.ppid) {
1444 		dump_printf("removing erroneous parent thread %d/%d\n",
1445 			    parent->pid_, parent->tid);
1446 		machine__remove_thread(machine, parent);
1447 		thread__put(parent);
1448 		parent = machine__findnew_thread(machine, event->fork.ppid,
1449 						 event->fork.ptid);
1450 	}
1451 
1452 	/* if a thread currently exists for the thread id remove it */
1453 	if (thread != NULL) {
1454 		machine__remove_thread(machine, thread);
1455 		thread__put(thread);
1456 	}
1457 
1458 	thread = machine__findnew_thread(machine, event->fork.pid,
1459 					 event->fork.tid);
1460 
1461 	if (thread == NULL || parent == NULL ||
1462 	    thread__fork(thread, parent, sample->time) < 0) {
1463 		dump_printf("problem processing PERF_RECORD_FORK, skipping event.\n");
1464 		err = -1;
1465 	}
1466 	thread__put(thread);
1467 	thread__put(parent);
1468 
1469 	return err;
1470 }
1471 
1472 int machine__process_exit_event(struct machine *machine, union perf_event *event,
1473 				struct perf_sample *sample __maybe_unused)
1474 {
1475 	struct thread *thread = machine__find_thread(machine,
1476 						     event->fork.pid,
1477 						     event->fork.tid);
1478 
1479 	if (dump_trace)
1480 		perf_event__fprintf_task(event, stdout);
1481 
1482 	if (thread != NULL) {
1483 		thread__exited(thread);
1484 		thread__put(thread);
1485 	}
1486 
1487 	return 0;
1488 }
1489 
1490 int machine__process_event(struct machine *machine, union perf_event *event,
1491 			   struct perf_sample *sample)
1492 {
1493 	int ret;
1494 
1495 	switch (event->header.type) {
1496 	case PERF_RECORD_COMM:
1497 		ret = machine__process_comm_event(machine, event, sample); break;
1498 	case PERF_RECORD_MMAP:
1499 		ret = machine__process_mmap_event(machine, event, sample); break;
1500 	case PERF_RECORD_MMAP2:
1501 		ret = machine__process_mmap2_event(machine, event, sample); break;
1502 	case PERF_RECORD_FORK:
1503 		ret = machine__process_fork_event(machine, event, sample); break;
1504 	case PERF_RECORD_EXIT:
1505 		ret = machine__process_exit_event(machine, event, sample); break;
1506 	case PERF_RECORD_LOST:
1507 		ret = machine__process_lost_event(machine, event, sample); break;
1508 	case PERF_RECORD_AUX:
1509 		ret = machine__process_aux_event(machine, event); break;
1510 	case PERF_RECORD_ITRACE_START:
1511 		ret = machine__process_itrace_start_event(machine, event); break;
1512 	case PERF_RECORD_LOST_SAMPLES:
1513 		ret = machine__process_lost_samples_event(machine, event, sample); break;
1514 	case PERF_RECORD_SWITCH:
1515 	case PERF_RECORD_SWITCH_CPU_WIDE:
1516 		ret = machine__process_switch_event(machine, event); break;
1517 	default:
1518 		ret = -1;
1519 		break;
1520 	}
1521 
1522 	return ret;
1523 }
1524 
1525 static bool symbol__match_regex(struct symbol *sym, regex_t *regex)
1526 {
1527 	if (sym->name && !regexec(regex, sym->name, 0, NULL, 0))
1528 		return 1;
1529 	return 0;
1530 }
1531 
1532 static void ip__resolve_ams(struct thread *thread,
1533 			    struct addr_map_symbol *ams,
1534 			    u64 ip)
1535 {
1536 	struct addr_location al;
1537 
1538 	memset(&al, 0, sizeof(al));
1539 	/*
1540 	 * We cannot use the header.misc hint to determine whether a
1541 	 * branch stack address is user, kernel, guest, hypervisor.
1542 	 * Branches may straddle the kernel/user/hypervisor boundaries.
1543 	 * Thus, we have to try consecutively until we find a match
1544 	 * or else, the symbol is unknown
1545 	 */
1546 	thread__find_cpumode_addr_location(thread, MAP__FUNCTION, ip, &al);
1547 
1548 	ams->addr = ip;
1549 	ams->al_addr = al.addr;
1550 	ams->sym = al.sym;
1551 	ams->map = al.map;
1552 }
1553 
1554 static void ip__resolve_data(struct thread *thread,
1555 			     u8 m, struct addr_map_symbol *ams, u64 addr)
1556 {
1557 	struct addr_location al;
1558 
1559 	memset(&al, 0, sizeof(al));
1560 
1561 	thread__find_addr_location(thread, m, MAP__VARIABLE, addr, &al);
1562 	if (al.map == NULL) {
1563 		/*
1564 		 * some shared data regions have execute bit set which puts
1565 		 * their mapping in the MAP__FUNCTION type array.
1566 		 * Check there as a fallback option before dropping the sample.
1567 		 */
1568 		thread__find_addr_location(thread, m, MAP__FUNCTION, addr, &al);
1569 	}
1570 
1571 	ams->addr = addr;
1572 	ams->al_addr = al.addr;
1573 	ams->sym = al.sym;
1574 	ams->map = al.map;
1575 }
1576 
1577 struct mem_info *sample__resolve_mem(struct perf_sample *sample,
1578 				     struct addr_location *al)
1579 {
1580 	struct mem_info *mi = zalloc(sizeof(*mi));
1581 
1582 	if (!mi)
1583 		return NULL;
1584 
1585 	ip__resolve_ams(al->thread, &mi->iaddr, sample->ip);
1586 	ip__resolve_data(al->thread, al->cpumode, &mi->daddr, sample->addr);
1587 	mi->data_src.val = sample->data_src;
1588 
1589 	return mi;
1590 }
1591 
1592 static int add_callchain_ip(struct thread *thread,
1593 			    struct symbol **parent,
1594 			    struct addr_location *root_al,
1595 			    u8 *cpumode,
1596 			    u64 ip)
1597 {
1598 	struct addr_location al;
1599 
1600 	al.filtered = 0;
1601 	al.sym = NULL;
1602 	if (!cpumode) {
1603 		thread__find_cpumode_addr_location(thread, MAP__FUNCTION,
1604 						   ip, &al);
1605 	} else {
1606 		if (ip >= PERF_CONTEXT_MAX) {
1607 			switch (ip) {
1608 			case PERF_CONTEXT_HV:
1609 				*cpumode = PERF_RECORD_MISC_HYPERVISOR;
1610 				break;
1611 			case PERF_CONTEXT_KERNEL:
1612 				*cpumode = PERF_RECORD_MISC_KERNEL;
1613 				break;
1614 			case PERF_CONTEXT_USER:
1615 				*cpumode = PERF_RECORD_MISC_USER;
1616 				break;
1617 			default:
1618 				pr_debug("invalid callchain context: "
1619 					 "%"PRId64"\n", (s64) ip);
1620 				/*
1621 				 * It seems the callchain is corrupted.
1622 				 * Discard all.
1623 				 */
1624 				callchain_cursor_reset(&callchain_cursor);
1625 				return 1;
1626 			}
1627 			return 0;
1628 		}
1629 		thread__find_addr_location(thread, *cpumode, MAP__FUNCTION,
1630 					   ip, &al);
1631 	}
1632 
1633 	if (al.sym != NULL) {
1634 		if (sort__has_parent && !*parent &&
1635 		    symbol__match_regex(al.sym, &parent_regex))
1636 			*parent = al.sym;
1637 		else if (have_ignore_callees && root_al &&
1638 		  symbol__match_regex(al.sym, &ignore_callees_regex)) {
1639 			/* Treat this symbol as the root,
1640 			   forgetting its callees. */
1641 			*root_al = al;
1642 			callchain_cursor_reset(&callchain_cursor);
1643 		}
1644 	}
1645 
1646 	if (symbol_conf.hide_unresolved && al.sym == NULL)
1647 		return 0;
1648 	return callchain_cursor_append(&callchain_cursor, al.addr, al.map, al.sym);
1649 }
1650 
1651 struct branch_info *sample__resolve_bstack(struct perf_sample *sample,
1652 					   struct addr_location *al)
1653 {
1654 	unsigned int i;
1655 	const struct branch_stack *bs = sample->branch_stack;
1656 	struct branch_info *bi = calloc(bs->nr, sizeof(struct branch_info));
1657 
1658 	if (!bi)
1659 		return NULL;
1660 
1661 	for (i = 0; i < bs->nr; i++) {
1662 		ip__resolve_ams(al->thread, &bi[i].to, bs->entries[i].to);
1663 		ip__resolve_ams(al->thread, &bi[i].from, bs->entries[i].from);
1664 		bi[i].flags = bs->entries[i].flags;
1665 	}
1666 	return bi;
1667 }
1668 
1669 #define CHASHSZ 127
1670 #define CHASHBITS 7
1671 #define NO_ENTRY 0xff
1672 
1673 #define PERF_MAX_BRANCH_DEPTH 127
1674 
1675 /* Remove loops. */
1676 static int remove_loops(struct branch_entry *l, int nr)
1677 {
1678 	int i, j, off;
1679 	unsigned char chash[CHASHSZ];
1680 
1681 	memset(chash, NO_ENTRY, sizeof(chash));
1682 
1683 	BUG_ON(PERF_MAX_BRANCH_DEPTH > 255);
1684 
1685 	for (i = 0; i < nr; i++) {
1686 		int h = hash_64(l[i].from, CHASHBITS) % CHASHSZ;
1687 
1688 		/* no collision handling for now */
1689 		if (chash[h] == NO_ENTRY) {
1690 			chash[h] = i;
1691 		} else if (l[chash[h]].from == l[i].from) {
1692 			bool is_loop = true;
1693 			/* check if it is a real loop */
1694 			off = 0;
1695 			for (j = chash[h]; j < i && i + off < nr; j++, off++)
1696 				if (l[j].from != l[i + off].from) {
1697 					is_loop = false;
1698 					break;
1699 				}
1700 			if (is_loop) {
1701 				memmove(l + i, l + i + off,
1702 					(nr - (i + off)) * sizeof(*l));
1703 				nr -= off;
1704 			}
1705 		}
1706 	}
1707 	return nr;
1708 }
1709 
1710 /*
1711  * Recolve LBR callstack chain sample
1712  * Return:
1713  * 1 on success get LBR callchain information
1714  * 0 no available LBR callchain information, should try fp
1715  * negative error code on other errors.
1716  */
1717 static int resolve_lbr_callchain_sample(struct thread *thread,
1718 					struct perf_sample *sample,
1719 					struct symbol **parent,
1720 					struct addr_location *root_al,
1721 					int max_stack)
1722 {
1723 	struct ip_callchain *chain = sample->callchain;
1724 	int chain_nr = min(max_stack, (int)chain->nr);
1725 	u8 cpumode = PERF_RECORD_MISC_USER;
1726 	int i, j, err;
1727 	u64 ip;
1728 
1729 	for (i = 0; i < chain_nr; i++) {
1730 		if (chain->ips[i] == PERF_CONTEXT_USER)
1731 			break;
1732 	}
1733 
1734 	/* LBR only affects the user callchain */
1735 	if (i != chain_nr) {
1736 		struct branch_stack *lbr_stack = sample->branch_stack;
1737 		int lbr_nr = lbr_stack->nr;
1738 		/*
1739 		 * LBR callstack can only get user call chain.
1740 		 * The mix_chain_nr is kernel call chain
1741 		 * number plus LBR user call chain number.
1742 		 * i is kernel call chain number,
1743 		 * 1 is PERF_CONTEXT_USER,
1744 		 * lbr_nr + 1 is the user call chain number.
1745 		 * For details, please refer to the comments
1746 		 * in callchain__printf
1747 		 */
1748 		int mix_chain_nr = i + 1 + lbr_nr + 1;
1749 
1750 		if (mix_chain_nr > PERF_MAX_STACK_DEPTH + PERF_MAX_BRANCH_DEPTH) {
1751 			pr_warning("corrupted callchain. skipping...\n");
1752 			return 0;
1753 		}
1754 
1755 		for (j = 0; j < mix_chain_nr; j++) {
1756 			if (callchain_param.order == ORDER_CALLEE) {
1757 				if (j < i + 1)
1758 					ip = chain->ips[j];
1759 				else if (j > i + 1)
1760 					ip = lbr_stack->entries[j - i - 2].from;
1761 				else
1762 					ip = lbr_stack->entries[0].to;
1763 			} else {
1764 				if (j < lbr_nr)
1765 					ip = lbr_stack->entries[lbr_nr - j - 1].from;
1766 				else if (j > lbr_nr)
1767 					ip = chain->ips[i + 1 - (j - lbr_nr)];
1768 				else
1769 					ip = lbr_stack->entries[0].to;
1770 			}
1771 
1772 			err = add_callchain_ip(thread, parent, root_al, &cpumode, ip);
1773 			if (err)
1774 				return (err < 0) ? err : 0;
1775 		}
1776 		return 1;
1777 	}
1778 
1779 	return 0;
1780 }
1781 
1782 static int thread__resolve_callchain_sample(struct thread *thread,
1783 					    struct perf_evsel *evsel,
1784 					    struct perf_sample *sample,
1785 					    struct symbol **parent,
1786 					    struct addr_location *root_al,
1787 					    int max_stack)
1788 {
1789 	struct branch_stack *branch = sample->branch_stack;
1790 	struct ip_callchain *chain = sample->callchain;
1791 	int chain_nr = min(max_stack, (int)chain->nr);
1792 	u8 cpumode = PERF_RECORD_MISC_USER;
1793 	int i, j, err;
1794 	int skip_idx = -1;
1795 	int first_call = 0;
1796 
1797 	callchain_cursor_reset(&callchain_cursor);
1798 
1799 	if (has_branch_callstack(evsel)) {
1800 		err = resolve_lbr_callchain_sample(thread, sample, parent,
1801 						   root_al, max_stack);
1802 		if (err)
1803 			return (err < 0) ? err : 0;
1804 	}
1805 
1806 	/*
1807 	 * Based on DWARF debug information, some architectures skip
1808 	 * a callchain entry saved by the kernel.
1809 	 */
1810 	if (chain->nr < PERF_MAX_STACK_DEPTH)
1811 		skip_idx = arch_skip_callchain_idx(thread, chain);
1812 
1813 	/*
1814 	 * Add branches to call stack for easier browsing. This gives
1815 	 * more context for a sample than just the callers.
1816 	 *
1817 	 * This uses individual histograms of paths compared to the
1818 	 * aggregated histograms the normal LBR mode uses.
1819 	 *
1820 	 * Limitations for now:
1821 	 * - No extra filters
1822 	 * - No annotations (should annotate somehow)
1823 	 */
1824 
1825 	if (branch && callchain_param.branch_callstack) {
1826 		int nr = min(max_stack, (int)branch->nr);
1827 		struct branch_entry be[nr];
1828 
1829 		if (branch->nr > PERF_MAX_BRANCH_DEPTH) {
1830 			pr_warning("corrupted branch chain. skipping...\n");
1831 			goto check_calls;
1832 		}
1833 
1834 		for (i = 0; i < nr; i++) {
1835 			if (callchain_param.order == ORDER_CALLEE) {
1836 				be[i] = branch->entries[i];
1837 				/*
1838 				 * Check for overlap into the callchain.
1839 				 * The return address is one off compared to
1840 				 * the branch entry. To adjust for this
1841 				 * assume the calling instruction is not longer
1842 				 * than 8 bytes.
1843 				 */
1844 				if (i == skip_idx ||
1845 				    chain->ips[first_call] >= PERF_CONTEXT_MAX)
1846 					first_call++;
1847 				else if (be[i].from < chain->ips[first_call] &&
1848 				    be[i].from >= chain->ips[first_call] - 8)
1849 					first_call++;
1850 			} else
1851 				be[i] = branch->entries[branch->nr - i - 1];
1852 		}
1853 
1854 		nr = remove_loops(be, nr);
1855 
1856 		for (i = 0; i < nr; i++) {
1857 			err = add_callchain_ip(thread, parent, root_al,
1858 					       NULL, be[i].to);
1859 			if (!err)
1860 				err = add_callchain_ip(thread, parent, root_al,
1861 						       NULL, be[i].from);
1862 			if (err == -EINVAL)
1863 				break;
1864 			if (err)
1865 				return err;
1866 		}
1867 		chain_nr -= nr;
1868 	}
1869 
1870 check_calls:
1871 	if (chain->nr > PERF_MAX_STACK_DEPTH && (int)chain->nr > max_stack) {
1872 		pr_warning("corrupted callchain. skipping...\n");
1873 		return 0;
1874 	}
1875 
1876 	for (i = first_call; i < chain_nr; i++) {
1877 		u64 ip;
1878 
1879 		if (callchain_param.order == ORDER_CALLEE)
1880 			j = i;
1881 		else
1882 			j = chain->nr - i - 1;
1883 
1884 #ifdef HAVE_SKIP_CALLCHAIN_IDX
1885 		if (j == skip_idx)
1886 			continue;
1887 #endif
1888 		ip = chain->ips[j];
1889 
1890 		err = add_callchain_ip(thread, parent, root_al, &cpumode, ip);
1891 
1892 		if (err)
1893 			return (err < 0) ? err : 0;
1894 	}
1895 
1896 	return 0;
1897 }
1898 
1899 static int unwind_entry(struct unwind_entry *entry, void *arg)
1900 {
1901 	struct callchain_cursor *cursor = arg;
1902 
1903 	if (symbol_conf.hide_unresolved && entry->sym == NULL)
1904 		return 0;
1905 	return callchain_cursor_append(cursor, entry->ip,
1906 				       entry->map, entry->sym);
1907 }
1908 
1909 int thread__resolve_callchain(struct thread *thread,
1910 			      struct perf_evsel *evsel,
1911 			      struct perf_sample *sample,
1912 			      struct symbol **parent,
1913 			      struct addr_location *root_al,
1914 			      int max_stack)
1915 {
1916 	int ret = thread__resolve_callchain_sample(thread, evsel,
1917 						   sample, parent,
1918 						   root_al, max_stack);
1919 	if (ret)
1920 		return ret;
1921 
1922 	/* Can we do dwarf post unwind? */
1923 	if (!((evsel->attr.sample_type & PERF_SAMPLE_REGS_USER) &&
1924 	      (evsel->attr.sample_type & PERF_SAMPLE_STACK_USER)))
1925 		return 0;
1926 
1927 	/* Bail out if nothing was captured. */
1928 	if ((!sample->user_regs.regs) ||
1929 	    (!sample->user_stack.size))
1930 		return 0;
1931 
1932 	return unwind__get_entries(unwind_entry, &callchain_cursor,
1933 				   thread, sample, max_stack);
1934 
1935 }
1936 
1937 int machine__for_each_thread(struct machine *machine,
1938 			     int (*fn)(struct thread *thread, void *p),
1939 			     void *priv)
1940 {
1941 	struct rb_node *nd;
1942 	struct thread *thread;
1943 	int rc = 0;
1944 
1945 	for (nd = rb_first(&machine->threads); nd; nd = rb_next(nd)) {
1946 		thread = rb_entry(nd, struct thread, rb_node);
1947 		rc = fn(thread, priv);
1948 		if (rc != 0)
1949 			return rc;
1950 	}
1951 
1952 	list_for_each_entry(thread, &machine->dead_threads, node) {
1953 		rc = fn(thread, priv);
1954 		if (rc != 0)
1955 			return rc;
1956 	}
1957 	return rc;
1958 }
1959 
1960 int machines__for_each_thread(struct machines *machines,
1961 			      int (*fn)(struct thread *thread, void *p),
1962 			      void *priv)
1963 {
1964 	struct rb_node *nd;
1965 	int rc = 0;
1966 
1967 	rc = machine__for_each_thread(&machines->host, fn, priv);
1968 	if (rc != 0)
1969 		return rc;
1970 
1971 	for (nd = rb_first(&machines->guests); nd; nd = rb_next(nd)) {
1972 		struct machine *machine = rb_entry(nd, struct machine, rb_node);
1973 
1974 		rc = machine__for_each_thread(machine, fn, priv);
1975 		if (rc != 0)
1976 			return rc;
1977 	}
1978 	return rc;
1979 }
1980 
1981 int __machine__synthesize_threads(struct machine *machine, struct perf_tool *tool,
1982 				  struct target *target, struct thread_map *threads,
1983 				  perf_event__handler_t process, bool data_mmap,
1984 				  unsigned int proc_map_timeout)
1985 {
1986 	if (target__has_task(target))
1987 		return perf_event__synthesize_thread_map(tool, threads, process, machine, data_mmap, proc_map_timeout);
1988 	else if (target__has_cpu(target))
1989 		return perf_event__synthesize_threads(tool, process, machine, data_mmap, proc_map_timeout);
1990 	/* command specified */
1991 	return 0;
1992 }
1993 
1994 pid_t machine__get_current_tid(struct machine *machine, int cpu)
1995 {
1996 	if (cpu < 0 || cpu >= MAX_NR_CPUS || !machine->current_tid)
1997 		return -1;
1998 
1999 	return machine->current_tid[cpu];
2000 }
2001 
2002 int machine__set_current_tid(struct machine *machine, int cpu, pid_t pid,
2003 			     pid_t tid)
2004 {
2005 	struct thread *thread;
2006 
2007 	if (cpu < 0)
2008 		return -EINVAL;
2009 
2010 	if (!machine->current_tid) {
2011 		int i;
2012 
2013 		machine->current_tid = calloc(MAX_NR_CPUS, sizeof(pid_t));
2014 		if (!machine->current_tid)
2015 			return -ENOMEM;
2016 		for (i = 0; i < MAX_NR_CPUS; i++)
2017 			machine->current_tid[i] = -1;
2018 	}
2019 
2020 	if (cpu >= MAX_NR_CPUS) {
2021 		pr_err("Requested CPU %d too large. ", cpu);
2022 		pr_err("Consider raising MAX_NR_CPUS\n");
2023 		return -EINVAL;
2024 	}
2025 
2026 	machine->current_tid[cpu] = tid;
2027 
2028 	thread = machine__findnew_thread(machine, pid, tid);
2029 	if (!thread)
2030 		return -ENOMEM;
2031 
2032 	thread->cpu = cpu;
2033 	thread__put(thread);
2034 
2035 	return 0;
2036 }
2037 
2038 int machine__get_kernel_start(struct machine *machine)
2039 {
2040 	struct map *map = machine__kernel_map(machine);
2041 	int err = 0;
2042 
2043 	/*
2044 	 * The only addresses above 2^63 are kernel addresses of a 64-bit
2045 	 * kernel.  Note that addresses are unsigned so that on a 32-bit system
2046 	 * all addresses including kernel addresses are less than 2^32.  In
2047 	 * that case (32-bit system), if the kernel mapping is unknown, all
2048 	 * addresses will be assumed to be in user space - see
2049 	 * machine__kernel_ip().
2050 	 */
2051 	machine->kernel_start = 1ULL << 63;
2052 	if (map) {
2053 		err = map__load(map, machine->symbol_filter);
2054 		if (map->start)
2055 			machine->kernel_start = map->start;
2056 	}
2057 	return err;
2058 }
2059 
2060 struct dso *machine__findnew_dso(struct machine *machine, const char *filename)
2061 {
2062 	return dsos__findnew(&machine->dsos, filename);
2063 }
2064 
2065 char *machine__resolve_kernel_addr(void *vmachine, unsigned long long *addrp, char **modp)
2066 {
2067 	struct machine *machine = vmachine;
2068 	struct map *map;
2069 	struct symbol *sym = map_groups__find_symbol(&machine->kmaps, MAP__FUNCTION, *addrp, &map,  NULL);
2070 
2071 	if (sym == NULL)
2072 		return NULL;
2073 
2074 	*modp = __map__is_kmodule(map) ? (char *)map->dso->short_name : NULL;
2075 	*addrp = map->unmap_ip(map, sym->start);
2076 	return sym->name;
2077 }
2078