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