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