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