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