Add PERF_SAMPLE_HOST_IP (1U << 25) to enum perf_event_sample_format so that samples can record a host virtual instruction pointer alongside PERF_SAMPLE_IP. When sampling a guest (should_sample_guest()), PERF_SAMPLE_HOST_IP invokes an optional ->get_host_ip() callback on perf_guest_info_callbacks to translate the guest instruction pointer into the corresponding host virtual address in the hypervisor process, allowing host-side file-backed/DAX mappings to symbolize guest code without guest symbol state. When not in guest context and !attr.exclude_host, it records perf_instruction_pointer(). Ensure __perf_event_header_size() accounts for sizeof(data->host_ip), respect exclude_kernel on skidded guest-kernel samples and exclude_host on skidded host samples, and keep ->get_host_ip() optional so hypervisors such as Xen default safely to returning 0. Signed-off-by: Ian Rogers --- include/linux/perf_event.h | 9 +++++++++ include/uapi/linux/perf_event.h | 4 +++- kernel/events/core.c | 24 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index b52348eca6ef..8ce5383e4b0a 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -1329,6 +1329,7 @@ struct perf_sample_data { * perf_{prepare,output}_sample(). */ u64 ip; + u64 host_ip; struct perf_callchain_entry *callchain; struct perf_raw_record *raw; struct perf_branch_stack *br_stack; @@ -1683,6 +1684,7 @@ extern void perf_event_bpf_event(struct bpf_prog *prog, struct perf_guest_info_callbacks { unsigned int (*state)(void); unsigned long (*get_ip)(void); + unsigned long (*get_host_ip)(void); unsigned int (*handle_intel_pt_intr)(void); void (*handle_mediated_pmi)(void); @@ -1694,6 +1696,7 @@ extern struct perf_guest_info_callbacks __rcu *perf_guest_cbs; DECLARE_STATIC_CALL(__perf_guest_state, *perf_guest_cbs->state); DECLARE_STATIC_CALL(__perf_guest_get_ip, *perf_guest_cbs->get_ip); +DECLARE_STATIC_CALL(__perf_guest_get_host_ip, *perf_guest_cbs->get_host_ip); DECLARE_STATIC_CALL(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); DECLARE_STATIC_CALL(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); @@ -1707,6 +1710,11 @@ static inline unsigned long perf_guest_get_ip(void) return static_call(__perf_guest_get_ip)(); } +static inline unsigned long perf_guest_get_host_ip(void) +{ + return static_call(__perf_guest_get_host_ip)(); +} + static inline unsigned int perf_guest_handle_intel_pt_intr(void) { return static_call(__perf_guest_handle_intel_pt_intr)(); @@ -1724,6 +1732,7 @@ extern void perf_unregister_guest_info_callbacks(struct perf_guest_info_callback static inline unsigned int perf_guest_state(void) { return 0; } static inline unsigned long perf_guest_get_ip(void) { return 0; } +static inline unsigned long perf_guest_get_host_ip(void) { return 0; } static inline unsigned int perf_guest_handle_intel_pt_intr(void) { return 0; } #endif /* !CONFIG_GUEST_PERF_EVENTS */ diff --git a/include/uapi/linux/perf_event.h b/include/uapi/linux/perf_event.h index c49fc76292f7..75ed8e968d30 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -165,8 +165,9 @@ enum perf_event_sample_format { PERF_SAMPLE_DATA_PAGE_SIZE = 1U << 22, PERF_SAMPLE_CODE_PAGE_SIZE = 1U << 23, PERF_SAMPLE_WEIGHT_STRUCT = 1U << 24, + PERF_SAMPLE_HOST_IP = 1U << 25, - PERF_SAMPLE_MAX = 1U << 25, /* non-ABI */ + PERF_SAMPLE_MAX = 1U << 26, /* non-ABI */ }; #define PERF_SAMPLE_WEIGHT_TYPE (PERF_SAMPLE_WEIGHT | PERF_SAMPLE_WEIGHT_STRUCT) @@ -1093,6 +1094,7 @@ enum perf_event_type { * { u64 cgroup;} && PERF_SAMPLE_CGROUP * { u64 data_page_size;} && PERF_SAMPLE_DATA_PAGE_SIZE * { u64 code_page_size;} && PERF_SAMPLE_CODE_PAGE_SIZE + * { u64 host_ip;} && PERF_SAMPLE_HOST_IP * { u64 size; * char data[size]; } && PERF_SAMPLE_AUX * }; diff --git a/kernel/events/core.c b/kernel/events/core.c index 526c486d1647..6da956ceead0 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -2103,6 +2103,9 @@ static void __perf_event_header_size(struct perf_event *event, u64 sample_type) if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) size += sizeof(data->code_page_size); + if (sample_type & PERF_SAMPLE_HOST_IP) + size += sizeof(data->host_ip); + event->header_size = size; } @@ -7804,6 +7807,7 @@ struct perf_guest_info_callbacks __rcu *perf_guest_cbs; DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); +DEFINE_STATIC_CALL_RET0(__perf_guest_get_host_ip, *perf_guest_cbs->get_host_ip); DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); @@ -7816,6 +7820,10 @@ void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) static_call_update(__perf_guest_state, cbs->state); static_call_update(__perf_guest_get_ip, cbs->get_ip); + /* Implementing ->get_host_ip is optional. */ + if (cbs->get_host_ip) + static_call_update(__perf_guest_get_host_ip, cbs->get_host_ip); + /* Implementing ->handle_intel_pt_intr is optional. */ if (cbs->handle_intel_pt_intr) static_call_update(__perf_guest_handle_intel_pt_intr, @@ -7835,6 +7843,7 @@ void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) rcu_assign_pointer(perf_guest_cbs, NULL); static_call_update(__perf_guest_state, (void *)&__static_call_return0); static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); + static_call_update(__perf_guest_get_host_ip, (void *)&__static_call_return0); static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0); static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); synchronize_rcu(); @@ -8595,6 +8604,9 @@ void perf_output_sample(struct perf_output_handle *handle, if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) perf_output_put(handle, data->code_page_size); + if (sample_type & PERF_SAMPLE_HOST_IP) + perf_output_put(handle, data->host_ip); + if (sample_type & PERF_SAMPLE_AUX) { perf_output_put(handle, data->aux_size); @@ -8838,6 +8850,18 @@ void perf_prepare_sample(struct perf_sample_data *data, data->sample_flags |= PERF_SAMPLE_IP; } + if (filtered_sample_type & PERF_SAMPLE_HOST_IP) { + data->host_ip = 0; + if (should_sample_guest(event)) { + if (!event->attr.exclude_kernel || + (perf_guest_state() & PERF_GUEST_USER)) + data->host_ip = perf_guest_get_host_ip(); + } else if (!event->attr.exclude_host) { + data->host_ip = perf_instruction_pointer(event, regs); + } + data->sample_flags |= PERF_SAMPLE_HOST_IP; + } + if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) perf_sample_save_callchain(data, event, regs); -- 2.56.1.915.g69d5ec7298-goog Add attr.mmap_bpf to struct perf_event_attr and expose the target struct vm_area_struct *vma in struct bpf_perf_event_data_kern. When attr.mmap_data and attr.mmap_bpf are both set on an event, perf_event_mmap_match() invokes the attached BPF_PROG_TYPE_PERF_EVENT program before emitting non-executable PERF_RECORD_MMAP/MMAP2 records. This allows tools such as perf record --host-ip to capture file-backed mappings in hypervisor processes without flooding the ring buffer with anonymous data mappings across the system. Signed-off-by: Ian Rogers --- include/linux/perf_event.h | 3 ++ include/uapi/linux/perf_event.h | 3 +- kernel/events/core.c | 87 +++++++++++++++++++++++++++++++-- 3 files changed, 88 insertions(+), 5 deletions(-) diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index 8ce5383e4b0a..c31e1bf278ec 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -1167,10 +1167,13 @@ struct perf_output_handle { int page; }; +struct vm_area_struct; + struct bpf_perf_event_data_kern { bpf_user_pt_regs_t *regs; struct perf_sample_data *data; struct perf_event *event; + struct vm_area_struct *vma; }; #ifdef CONFIG_CGROUP_PERF diff --git a/include/uapi/linux/perf_event.h b/include/uapi/linux/perf_event.h index 75ed8e968d30..146df3041c31 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -469,7 +469,8 @@ struct perf_event_attr { sigtrap : 1, /* send synchronous SIGTRAP on event */ defer_callchain: 1, /* request PERF_RECORD_CALLCHAIN_DEFERRED records */ defer_output : 1, /* output PERF_RECORD_CALLCHAIN_DEFERRED records */ - __reserved_1 : 24; + mmap_bpf : 1, /* filter mmap_data events with BPF prog */ + __reserved_1 : 23; union { __u32 wakeup_events; /* wake up every n events */ diff --git a/kernel/events/core.c b/kernel/events/core.c index 6da956ceead0..d32aaf141c9e 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -9880,6 +9880,9 @@ struct perf_mmap_event { } event_id; }; +static int bpf_mmap_handler(struct perf_event *event, + struct vm_area_struct *vma); + static int perf_event_mmap_match(struct perf_event *event, void *data) { @@ -9887,8 +9890,16 @@ static int perf_event_mmap_match(struct perf_event *event, struct vm_area_struct *vma = mmap_event->vma; int executable = vma->vm_flags & VM_EXEC; - return (!executable && event->attr.mmap_data) || - (executable && (event->attr.mmap || event->attr.mmap2)); + if (executable) + return event->attr.mmap || event->attr.mmap2; + + if (!event->attr.mmap_data) + return 0; + + if (event->attr.mmap_bpf && !bpf_mmap_handler(event, vma)) + return 0; + + return 1; } static void perf_event_mmap_output(struct perf_event *event, @@ -10878,6 +10889,58 @@ static int bpf_overflow_handler(struct perf_event *event, return ret; } +static int bpf_mmap_handler(struct perf_event *event, + struct vm_area_struct *vma) +{ + struct pt_regs caller_regs = {}; + struct pt_regs *regs = &caller_regs; + struct perf_sample_data data = { + .addr = vma->vm_start, + .period = vma->vm_end - vma->vm_start, + .sample_flags = PERF_SAMPLE_ADDR | PERF_SAMPLE_PERIOD, + }; + struct bpf_perf_event_data_kern ctx = { + .data = &data, + .event = event, + .vma = vma, + }; + struct bpf_prog *prog; + int ret = 0; + + perf_fetch_caller_regs(regs); + ctx.regs = perf_arch_bpf_user_pt_regs(regs); + + preempt_disable(); + if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) + goto out; + rcu_read_lock(); + /* Pairs with smp_store_release() in perf_event_set_bpf_handler() */ + prog = smp_load_acquire(&event->prog); + if (prog && prog->type == BPF_PROG_TYPE_PERF_EVENT) { + if (prog->call_get_stack && + (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)) { + data.callchain = get_perf_callchain(regs, + !event->attr.exclude_callchain_kernel, + !event->attr.exclude_callchain_user && + is_user_task(current) && current->mm, + event->attr.sample_max_stack, + event->ctx->task && + event->ctx->task != current, + true, 0); + if (!data.callchain) + data.callchain = &__empty_callchain; + data.sample_flags |= PERF_SAMPLE_CALLCHAIN; + } + ret = bpf_prog_run(prog, &ctx); + } + rcu_read_unlock(); +out: + __this_cpu_dec(bpf_prog_active); + preempt_enable(); + + return ret; +} + static inline int perf_event_set_bpf_handler(struct perf_event *event, struct bpf_prog *prog, u64 bpf_cookie) @@ -10934,6 +10997,12 @@ static inline int bpf_overflow_handler(struct perf_event *event, return 1; } +static inline int bpf_mmap_handler(struct perf_event *event, + struct vm_area_struct *vma) +{ + return 1; +} + static inline int perf_event_set_bpf_handler(struct perf_event *event, struct bpf_prog *prog, u64 bpf_cookie) @@ -10978,8 +11047,8 @@ static int __perf_event_overflow(struct perf_event *event, if (event->attr.aux_pause) perf_event_aux_pause(event->aux_event, true); - if (!perf_event_is_tracing(event) && READ_ONCE(event->prog) && - !bpf_overflow_handler(event, data, regs)) + if (!event->attr.mmap_bpf && !perf_event_is_tracing(event) && + READ_ONCE(event->prog) && !bpf_overflow_handler(event, data, regs)) goto out; /* @@ -11917,6 +11986,9 @@ static int __perf_event_set_bpf_prog(struct perf_event *event, if (!perf_event_is_tracing(event)) return perf_event_set_bpf_handler(event, prog, bpf_cookie); + if (event->attr.mmap_bpf) + return -EINVAL; + is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; @@ -13958,6 +14030,13 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) return -EINVAL; +#if !defined(CONFIG_BPF_SYSCALL) || !defined(CONFIG_EVENT_TRACING) + if (attr->mmap_bpf) + return -EOPNOTSUPP; +#endif + if (attr->mmap_bpf && !attr->mmap_data) + return -EINVAL; + if (!attr->inherit && attr->inherit_thread) return -EINVAL; -- 2.56.1.915.g69d5ec7298-goog Wire up kvm_guest_get_host_ip() in common KVM code and provide the NMI-safe primitives architectures need to implement kvm_arch_vcpu_get_ip_gpa() for PERF_SAMPLE_HOST_IP. Because perf PMIs run in NMI or hardirq-disabled context and cannot sleep or mix SRCU flavors on kvm->srcu: - Pair synchronize_srcu_expedited(&kvm->srcu) with synchronize_rcu_expedited() in kvm_swap_active_memslots() and add an RCU-protected, read-only memslot lookup helper (kvm_vcpu_gfn_to_hva_nofault()) so NMI callers never touch kvm->srcu or last_used_slot caches. - Add kvm_vcpu_read_guest_nofault() using copy_from_user_nofault() so arch guest page-table reads are non-faulting, NMI-safe, and support KVM_MEM_READONLY memslots. - Add a __weak kvm_arch_vcpu_get_ip_gpa() default returning INVALID_GPA and wire kvm_guest_get_host_ip() into kvm_guest_cbs.get_host_ip. Signed-off-by: Ian Rogers --- include/linux/kvm_host.h | 3 ++ virt/kvm/kvm_main.c | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/include/linux/kvm_host.h b/include/linux/kvm_host.h index fe300a22ab0f..c3e5366d01ea 100644 --- a/include/linux/kvm_host.h +++ b/include/linux/kvm_host.h @@ -1468,6 +1468,8 @@ DEFINE_VCPU_MAP_CLASS(_readonly); unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn); unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable); +int kvm_vcpu_read_guest_nofault(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, + unsigned long len); int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, int offset, int len); int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, @@ -1821,6 +1823,7 @@ static inline bool kvm_arch_intc_initialized(struct kvm *kvm) #ifdef CONFIG_GUEST_PERF_EVENTS unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu); +gpa_t kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu); void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void), void (*mediated_pmi_handler)(void)); diff --git a/virt/kvm/kvm_main.c b/virt/kvm/kvm_main.c index 83e727bf6452..7935d4a346a3 100644 --- a/virt/kvm/kvm_main.c +++ b/virt/kvm/kvm_main.c @@ -1658,6 +1658,7 @@ static void kvm_swap_active_memslots(struct kvm *kvm, int as_id) mutex_unlock(&kvm->slots_arch_lock); synchronize_srcu_expedited(&kvm->srcu); + synchronize_rcu_expedited(); /* * Increment the new memslot generation a second time, dropping the @@ -2880,6 +2881,41 @@ unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *w return gfn_to_hva_memslot_prot(slot, gfn, writable); } +static unsigned long kvm_vcpu_gfn_to_hva_nofault(struct kvm_vcpu *vcpu, + gfn_t gfn) +{ + int as_id = kvm_arch_vcpu_memslots_id(vcpu); + struct kvm_memslots *slots; + struct kvm_memory_slot *slot; + + guard(rcu)(); + as_id = array_index_nospec(as_id, KVM_MAX_NR_ADDRESS_SPACES); + slots = rcu_dereference(vcpu->kvm->memslots[as_id]); + slot = search_memslots(slots, gfn, false); + return __gfn_to_hva_many(slot, gfn, NULL, false); +} + +int kvm_vcpu_read_guest_nofault(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, + unsigned long len) +{ + gfn_t gfn = gpa >> PAGE_SHIFT; + int offset = offset_in_page(gpa); + unsigned long addr; + + if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) + return -EINVAL; + + addr = kvm_vcpu_gfn_to_hva_nofault(vcpu, gfn); + if (kvm_is_error_hva(addr)) + return -EFAULT; + + if (copy_from_user_nofault(data, (const void __user *)(addr + offset), len)) + return -EFAULT; + + return 0; +} +EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_nofault); + static bool kvm_is_ad_tracked_page(struct page *page) { /* @@ -6578,9 +6614,37 @@ static unsigned long kvm_guest_get_ip(void) return kvm_arch_vcpu_get_ip(vcpu); } +gpa_t __weak kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu) +{ + return INVALID_GPA; +} + +static unsigned long kvm_guest_get_host_ip(void) +{ + struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); + unsigned long hva = 0; + gpa_t gpa; + + /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */ + if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu))) + return 0; + + gpa = kvm_arch_vcpu_get_ip_gpa(vcpu); + if (gpa != INVALID_GPA) { + hva = kvm_vcpu_gfn_to_hva_nofault(vcpu, gpa_to_gfn(gpa)); + if (kvm_is_error_hva(hva)) + hva = 0; + else + hva += offset_in_page(gpa); + } + + return hva; +} + static struct perf_guest_info_callbacks kvm_guest_cbs = { .state = kvm_guest_state, .get_ip = kvm_guest_get_ip, + .get_host_ip = kvm_guest_get_host_ip, .handle_intel_pt_intr = NULL, .handle_mediated_pmi = NULL, }; -- 2.56.1.915.g69d5ec7298-goog Implement NMI-safe guest virtual-to-physical instruction pointer translation on x86 via kvm_arch_vcpu_get_ip_gpa() so PERF_SAMPLE_HOST_IP can translate guest RIP into the backing host virtual address: - Add gva_to_gpa_nofault and get_pdptr_nofault callbacks for nonpaging, 32-bit, PAE/64-bit/LA57, and nested EPT/NPT page walks that read guest page tables via kvm_vcpu_read_guest_nofault(), never sleep, never mutate guest A/D bits, and validate PFERR_FETCH_MASK permissions. - Temporarily restore host PKRU while reading guest page tables via copy_from_user_nofault() if an NMI PMI fires while guest PKRU is loaded, and translate kvm_get_linear_rip() with the guest's current CPL. Signed-off-by: Ian Rogers --- arch/x86/include/asm/kvm-x86-ops.h | 1 + arch/x86/include/asm/kvm_host.h | 7 ++- arch/x86/kvm/mmu.h | 14 ++++- arch/x86/kvm/mmu/mmu.c | 53 ++++++++++++++++-- arch/x86/kvm/mmu/paging_tmpl.h | 86 ++++++++++++++++++++++++++++++ arch/x86/kvm/svm/nested.c | 17 +++++- arch/x86/kvm/vmx/main.c | 9 ++++ arch/x86/kvm/vmx/nested.c | 5 +- arch/x86/kvm/vmx/vmx.c | 16 ++++++ arch/x86/kvm/vmx/x86_ops.h | 1 + arch/x86/kvm/x86.c | 38 +++++++++++++ 11 files changed, 240 insertions(+), 7 deletions(-) diff --git a/arch/x86/include/asm/kvm-x86-ops.h b/arch/x86/include/asm/kvm-x86-ops.h index 4dde4e3e608a..ca9d1e37306c 100644 --- a/arch/x86/include/asm/kvm-x86-ops.h +++ b/arch/x86/include/asm/kvm-x86-ops.h @@ -52,6 +52,7 @@ KVM_X86_OP(set_gdt) KVM_X86_OP(sync_dirty_debug_regs) KVM_X86_OP(set_dr7) KVM_X86_OP(cache_reg) +KVM_X86_OP_OPTIONAL(read_pdptr_nofault) KVM_X86_OP(get_rflags) KVM_X86_OP(set_rflags) KVM_X86_OP(get_if_flag) diff --git a/arch/x86/include/asm/kvm_host.h b/arch/x86/include/asm/kvm_host.h index 1ee4b127004d..44c492e6b15f 100644 --- a/arch/x86/include/asm/kvm_host.h +++ b/arch/x86/include/asm/kvm_host.h @@ -487,12 +487,16 @@ struct kvm_page_fault; struct kvm_pagewalk { unsigned long (*get_guest_pgd)(struct kvm_vcpu *vcpu); u64 (*get_pdptr)(struct kvm_vcpu *vcpu, int index); + int (*get_pdptr_nofault)(struct kvm_vcpu *vcpu, int index, u64 *pdptr); void (*inject_page_fault)(struct kvm_vcpu *vcpu, struct x86_exception *fault, bool from_hardware); gpa_t (*gva_to_gpa)(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w, gpa_t gva_or_gpa, u64 access, struct x86_exception *exception); + gpa_t (*gva_to_gpa_nofault)(struct kvm_vcpu *vcpu, + struct kvm_pagewalk *w, + gpa_t gva_or_gpa, u64 access); union kvm_cpu_role cpu_role; struct kvm_page_format fmt; @@ -1565,6 +1569,7 @@ struct kvm_x86_ops { void (*sync_dirty_debug_regs)(struct kvm_vcpu *vcpu); void (*set_dr7)(struct kvm_vcpu *vcpu, unsigned long value); void (*cache_reg)(struct kvm_vcpu *vcpu, enum kvm_reg reg); + int (*read_pdptr_nofault)(struct kvm_vcpu *vcpu, int index, u64 *pdptr); unsigned long (*get_rflags)(struct kvm_vcpu *vcpu); void (*set_rflags)(struct kvm_vcpu *vcpu, unsigned long rflags); bool (*get_if_flag)(struct kvm_vcpu *vcpu); @@ -1774,7 +1779,7 @@ struct kvm_x86_nested_ops { gpa_t (*translate_nested_gpa)(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access, struct x86_exception *exception, - u64 pte_access); + u64 pte_access, bool nofault); int (*enable_evmcs)(struct kvm_vcpu *vcpu, uint16_t *vmcs_version); diff --git a/arch/x86/kvm/mmu.h b/arch/x86/kvm/mmu.h index b2a295a9f084..4636e020c922 100644 --- a/arch/x86/kvm/mmu.h +++ b/arch/x86/kvm/mmu.h @@ -394,7 +394,19 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, if (!mmu_is_nested(vcpu) || w == &vcpu->arch.ngpa_walk) return gpa; return kvm_nested_call(translate_nested_gpa)(vcpu, gpa, access, - exception, pte_access); + exception, pte_access, + false); +} + +static inline gpa_t kvm_translate_gpa_nofault(struct kvm_vcpu *vcpu, + struct kvm_pagewalk *w, + gpa_t gpa, u64 access, + u64 pte_access) +{ + if (!mmu_is_nested(vcpu) || w == &vcpu->arch.ngpa_walk) + return gpa; + return kvm_nested_call(translate_nested_gpa)(vcpu, gpa, access, + NULL, pte_access, true); } static inline bool kvm_has_mirrored_tdp(const struct kvm *kvm) diff --git a/arch/x86/kvm/mmu/mmu.c b/arch/x86/kvm/mmu/mmu.c index b122061b1fab..c92ba1555b2f 100644 --- a/arch/x86/kvm/mmu/mmu.c +++ b/arch/x86/kvm/mmu/mmu.c @@ -4487,6 +4487,15 @@ static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w, exception, ACC_ALL); } +static gpa_t nonpaging_gva_to_gpa_nofault(struct kvm_vcpu *vcpu, + struct kvm_pagewalk *w, + gpa_t vaddr, u64 access) +{ + return kvm_translate_gpa_nofault(vcpu, w, vaddr, + access | PFERR_GUEST_FINAL_MASK, + ACC_ALL); +} + static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct) { /* @@ -5566,6 +5575,8 @@ static void __reset_rsvds_bits_mask(struct kvm_page_format *fmt, rsvd_bits(1, 2); /* PDPTE */ fmt->rsvd_bits_mask[0][1] = high_bits_rsvd; /* PDE */ fmt->rsvd_bits_mask[0][0] = high_bits_rsvd; /* PTE */ + fmt->rsvd_bits_mask[1][2] = + fmt->rsvd_bits_mask[0][2]; fmt->rsvd_bits_mask[1][1] = high_bits_rsvd | rsvd_bits(13, 20); /* large page */ fmt->rsvd_bits_mask[1][0] = @@ -6156,6 +6167,36 @@ static void init_kvm_shadow_mmu(struct kvm_vcpu *vcpu, shadow_mmu_init_context(vcpu, context, root_role); } +static int kvm_pdptr_read_nofault(struct kvm_vcpu *vcpu, int index, u64 *pdptr) +{ + struct kvm_pagewalk *w = &vcpu->arch.gva_walk; + gpa_t pdpt_gpa; + + if (!tdp_enabled) { + *pdptr = vcpu->arch.pdptrs[index]; + return 0; + } + + if (kvm_x86_ops.read_pdptr_nofault) + return kvm_x86_call(read_pdptr_nofault)(vcpu, index, pdptr); + + /* + * Under NPT, SVM hardware does not cache architectural PDPTRs in the + * VMCB and instead fetches PAE PDPTEs directly from guest CR3. + */ + pdpt_gpa = (kvm_read_cr3(vcpu) & GENMASK_ULL(31, 5)) + + (unsigned int)index * sizeof(u64); + pdpt_gpa = kvm_translate_gpa_nofault(vcpu, w, pdpt_gpa, + PFERR_WRITE_MASK | + PFERR_USER_MASK | + PFERR_GUEST_PAGE_MASK, 0); + if (pdpt_gpa == INVALID_GPA) + return -EFAULT; + + return kvm_vcpu_read_guest_nofault(vcpu, pdpt_gpa, pdptr, + sizeof(*pdptr)); +} + static void init_kvm_page_walk(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w, union kvm_cpu_role cpu_role) { @@ -6165,14 +6206,19 @@ static void init_kvm_page_walk(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w, w->cpu_role.as_u64 = cpu_role.as_u64; w->inject_page_fault = kvm_inject_page_fault; w->get_pdptr = kvm_pdptr_read; + w->get_pdptr_nofault = kvm_pdptr_read_nofault; w->get_guest_pgd = get_guest_cr3; - if (!is_cr0_pg(w)) + if (!is_cr0_pg(w)) { w->gva_to_gpa = nonpaging_gva_to_gpa; - else if (is_cr4_pae(w)) + w->gva_to_gpa_nofault = nonpaging_gva_to_gpa_nofault; + } else if (is_cr4_pae(w)) { w->gva_to_gpa = paging64_gva_to_gpa; - else + w->gva_to_gpa_nofault = paging64_gva_to_gpa_nofault; + } else { w->gva_to_gpa = paging32_gva_to_gpa; + w->gva_to_gpa_nofault = paging32_gva_to_gpa_nofault; + } reset_guest_paging_metadata(vcpu, w); } @@ -6251,6 +6297,7 @@ void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly, context->page_fault = ept_page_fault; ngpa_walk->gva_to_gpa = ept_gva_to_gpa; + ngpa_walk->gva_to_gpa_nofault = ept_gva_to_gpa_nofault; context->sync_spte = ept_sync_spte; update_permission_bitmask(ngpa_walk, true, true); diff --git a/arch/x86/kvm/mmu/paging_tmpl.h b/arch/x86/kvm/mmu/paging_tmpl.h index 939a10fc1110..02753a1042b9 100644 --- a/arch/x86/kvm/mmu/paging_tmpl.h +++ b/arch/x86/kvm/mmu/paging_tmpl.h @@ -933,6 +933,92 @@ static gpa_t FNAME(gva_to_gpa)(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w, return gpa; } +static gpa_t FNAME(gva_to_gpa_nofault)(struct kvm_vcpu *vcpu, + struct kvm_pagewalk *w, + gpa_t addr, u64 access) +{ + int level = w->cpu_role.base.level; + pt_element_t pte = kvm_mmu_get_guest_pgd(vcpu, w); + u64 nested_access = (PT_HAVE_ACCESSED_DIRTY(w) ? PFERR_WRITE_MASK : 0) | + PFERR_USER_MASK; + u64 walk_nx_mask = 0; + u64 pt_access, pte_access = ~0; + unsigned int pte_pkey, walker_pte_access; + gpa_t real_gpa; + gfn_t gfn; + +#ifndef CONFIG_X86_64 + if ((addr >> 32) && w == &vcpu->arch.gva_walk) + return INVALID_GPA; +#endif + +#if PTTYPE == 64 + walk_nx_mask = 1ULL << PT64_NX_SHIFT; + if (level == PT32E_ROOT_LEVEL) { + if (!w->get_pdptr_nofault || + w->get_pdptr_nofault(vcpu, (addr >> 30) & 3, &pte)) + return INVALID_GPA; + if (!FNAME(is_present_gpte)(w, pte) || + FNAME(is_rsvd_bits_set)(&w->fmt, pte, PT32E_ROOT_LEVEL)) + return INVALID_GPA; + --level; + } +#endif + if (unlikely((is_long_mode(vcpu) && !is_pae(vcpu)) || + level > PT_MAX_FULL_LEVELS || level < 1)) + return INVALID_GPA; + + ++level; + do { + gfn_t table_gfn; + int offset; + + pt_access = pte_access; + --level; + if (unlikely(level < 1)) + return INVALID_GPA; + + table_gfn = gpte_to_gfn(pte); + offset = PT_INDEX(addr, level) * sizeof(pt_element_t); + + real_gpa = kvm_translate_gpa_nofault(vcpu, w, + gfn_to_gpa(table_gfn), + nested_access | + PFERR_GUEST_PAGE_MASK, 0); + if (unlikely(real_gpa == INVALID_GPA)) + return INVALID_GPA; + + if (unlikely(kvm_vcpu_read_guest_nofault(vcpu, + real_gpa + offset, + &pte, sizeof(pte)))) + return INVALID_GPA; + + pte_access = pt_access & (pte ^ walk_nx_mask); + if (unlikely(!FNAME(is_present_gpte)(w, pte) || + FNAME(is_rsvd_bits_set)(&w->fmt, pte, level))) + return INVALID_GPA; + } while (!FNAME(is_last_gpte)(w, level, pte)); + + pte_pkey = FNAME(gpte_pkeys)(vcpu, pte); + walker_pte_access = FNAME(gpte_access)(pte_access ^ walk_nx_mask); + if (unlikely(permission_fault(vcpu, w, walker_pte_access, pte_pkey, access))) + return INVALID_GPA; + + gfn = gpte_to_gfn_lvl(pte, level); + gfn += (addr & PT_LVL_OFFSET_MASK(level)) >> PAGE_SHIFT; +#if PTTYPE == 32 + if (level > PG_LEVEL_4K && is_cpuid_PSE36()) + gfn += pse36_gfn_delta(pte); +#endif + real_gpa = kvm_translate_gpa_nofault(vcpu, w, gfn_to_gpa(gfn), + access | PFERR_GUEST_FINAL_MASK, + walker_pte_access); + if (real_gpa == INVALID_GPA) + return INVALID_GPA; + + return real_gpa | (addr & ~PAGE_MASK); +} + /* * Using the information in sp->shadowed_translation (kvm_mmu_page_get_gfn()) is * safe because SPTEs are protected by mmu_notifiers and memslot generations, so diff --git a/arch/x86/kvm/svm/nested.c b/arch/x86/kvm/svm/nested.c index 07554089ec05..989912a2c190 100644 --- a/arch/x86/kvm/svm/nested.c +++ b/arch/x86/kvm/svm/nested.c @@ -89,6 +89,17 @@ static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index) return pdpte; } +static int nested_svm_get_tdp_pdptr_nofault(struct kvm_vcpu *vcpu, int index, + u64 *pdpte) +{ + struct vcpu_svm *svm = to_svm(vcpu); + u64 cr3 = svm->nested.ctl.nested_cr3; + + return kvm_vcpu_read_guest_nofault(vcpu, + (cr3 & ~0x1fULL) + index * 8, + pdpte, sizeof(*pdpte)); +} + static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu) { struct vcpu_svm *svm = to_svm(vcpu); @@ -116,6 +127,7 @@ static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu) vcpu->arch.ngpa_walk.get_guest_pgd = nested_svm_get_tdp_cr3; vcpu->arch.ngpa_walk.get_pdptr = nested_svm_get_tdp_pdptr; + vcpu->arch.ngpa_walk.get_pdptr_nofault = nested_svm_get_tdp_pdptr_nofault; vcpu->arch.ngpa_walk.inject_page_fault = nested_svm_inject_npf_exit; } @@ -2163,7 +2175,7 @@ static bool svm_get_nested_state_pages(struct kvm_vcpu *vcpu) static gpa_t svm_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access, struct x86_exception *exception, - u64 pte_access) + u64 pte_access, bool nofault) { struct vcpu_svm *svm = to_svm(vcpu); struct kvm_pagewalk *w = &vcpu->arch.ngpa_walk; @@ -2175,6 +2187,9 @@ static gpa_t svm_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, if (!(svm->nested.ctl.misc_ctl & SVM_MISC_ENABLE_GMET)) access |= PFERR_USER_MASK; + if (nofault) + return w->gva_to_gpa_nofault(vcpu, w, gpa, access); + return w->gva_to_gpa(vcpu, w, gpa, access, exception); } diff --git a/arch/x86/kvm/vmx/main.c b/arch/x86/kvm/vmx/main.c index d75170a6199e..9ec117ceeea7 100644 --- a/arch/x86/kvm/vmx/main.c +++ b/arch/x86/kvm/vmx/main.c @@ -495,6 +495,14 @@ static void vt_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg) vmx_cache_reg(vcpu, reg); } +static int vt_read_pdptr_nofault(struct kvm_vcpu *vcpu, int index, u64 *pdptr) +{ + if (WARN_ON_ONCE(is_td_vcpu(vcpu))) + return -EINVAL; + + return vmx_read_pdptr_nofault(vcpu, index, pdptr); +} + static unsigned long vt_get_rflags(struct kvm_vcpu *vcpu) { if (is_td_vcpu(vcpu)) @@ -1050,6 +1058,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = { .set_dr7 = vt_op(set_dr7), .sync_dirty_debug_regs = vt_op(sync_dirty_debug_regs), .cache_reg = vt_op(cache_reg), + .read_pdptr_nofault = vt_op(read_pdptr_nofault), .get_rflags = vt_op(get_rflags), .set_rflags = vt_op(set_rflags), .get_if_flag = vt_op(get_if_flag), diff --git a/arch/x86/kvm/vmx/nested.c b/arch/x86/kvm/vmx/nested.c index cd9465f4ee34..773f8f1be629 100644 --- a/arch/x86/kvm/vmx/nested.c +++ b/arch/x86/kvm/vmx/nested.c @@ -7495,7 +7495,7 @@ __init int nested_vmx_hardware_setup(int (*exit_handlers[])(struct kvm_vcpu *)) static gpa_t vmx_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u64 access, struct x86_exception *exception, - u64 pte_access) + u64 pte_access, bool nofault) { struct kvm_pagewalk *w = &vcpu->arch.ngpa_walk; @@ -7510,6 +7510,9 @@ static gpa_t vmx_translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, if ((pte_access & ACC_USER_MASK) && (access & PFERR_GUEST_FINAL_MASK)) access |= PFERR_USER_MASK; + if (nofault) + return w->gva_to_gpa_nofault(vcpu, w, gpa, access); + return w->gva_to_gpa(vcpu, w, gpa, access, exception); } diff --git a/arch/x86/kvm/vmx/vmx.c b/arch/x86/kvm/vmx/vmx.c index af52568b551b..944d86091968 100644 --- a/arch/x86/kvm/vmx/vmx.c +++ b/arch/x86/kvm/vmx/vmx.c @@ -3436,6 +3436,22 @@ void ept_save_pdptrs(struct kvm_vcpu *vcpu) kvm_register_mark_available(vcpu, VCPU_REG_PDPTR); } +int vmx_read_pdptr_nofault(struct kvm_vcpu *vcpu, int index, u64 *pdptr) +{ + static const u16 guest_pdptr_fields[] = { + GUEST_PDPTR0, GUEST_PDPTR1, GUEST_PDPTR2, GUEST_PDPTR3, + }; + + if (WARN_ON_ONCE((unsigned int)index >= ARRAY_SIZE(guest_pdptr_fields))) + return -EINVAL; + + if (enable_ept) + *pdptr = vmcs_read64(guest_pdptr_fields[index]); + else + *pdptr = vcpu->arch.pdptrs[index]; + return 0; +} + #define CR3_EXITING_BITS (CPU_BASED_CR3_LOAD_EXITING | \ CPU_BASED_CR3_STORE_EXITING) diff --git a/arch/x86/kvm/vmx/x86_ops.h b/arch/x86/kvm/vmx/x86_ops.h index cd72684d075d..21450e3dc94c 100644 --- a/arch/x86/kvm/vmx/x86_ops.h +++ b/arch/x86/kvm/vmx/x86_ops.h @@ -76,6 +76,7 @@ void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt); void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val); void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu); void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg); +int vmx_read_pdptr_nofault(struct kvm_vcpu *vcpu, int index, u64 *pdptr); unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu); void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags); bool vmx_get_if_flag(struct kvm_vcpu *vcpu); diff --git a/arch/x86/kvm/x86.c b/arch/x86/kvm/x86.c index 0549c0b48901..7533a22c2b4b 100644 --- a/arch/x86/kvm/x86.c +++ b/arch/x86/kvm/x86.c @@ -10482,6 +10482,44 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) return kvm_rip_read(vcpu); } +gpa_t kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu) +{ + struct kvm_pagewalk *gva_walk = &vcpu->arch.gva_walk; + unsigned long gva; + u32 saved_pkru; + bool restore_pkru = false; + u64 access; + gpa_t gpa; + + WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu)); + + if (vcpu->arch.guest_state_protected || !gva_walk->gva_to_gpa_nofault) + return INVALID_GPA; + + /* + * An NMI PMI can fire inside vcpu_run() while guest PKRU is loaded. + * Temporarily switch back to host PKRU so copy_from_user_nofault() + * reads host VMAs using the host protection-key permissions. + */ + saved_pkru = read_pkru(); + if (saved_pkru != vcpu->arch.host_pkru) { + write_pkru(vcpu->arch.host_pkru); + restore_pkru = true; + } + + gva = kvm_get_linear_rip(vcpu); + access = PFERR_FETCH_MASK; + if (kvm_x86_call(get_cpl)(vcpu) == 3) + access |= PFERR_USER_MASK; + + gpa = gva_walk->gva_to_gpa_nofault(vcpu, gva_walk, gva, access); + + if (restore_pkru) + write_pkru(saved_pkru); + + return gpa; +} + static inline u32 kvm_async_pf_hash_fn(gfn_t gfn) { BUILD_BUG_ON(!is_power_of_2(ASYNC_PF_PER_VCPU)); -- 2.56.1.915.g69d5ec7298-goog Implement kvm_arch_vcpu_get_ip_gpa() on arm64 so PERF_SAMPLE_HOST_IP translates the guest PC to a guest physical address using non-faulting guest memory reads. Parameterize the Stage-1 translation walk in at.c with a non-faulting guest read mode backed by kvm_vcpu_read_guest_nofault() and use __kvm_translate_va() to translate the guest PC with execute permission checks (including LPA2, contiguous mappings, S1PIE, and S1POE), returning INVALID_GPA under pKVM or nested Stage-2. Signed-off-by: Ian Rogers --- arch/arm64/include/asm/kvm_nested.h | 2 ++ arch/arm64/kvm/arm.c | 38 ++++++++++++++++++++++++++++ arch/arm64/kvm/at.c | 39 ++++++++++++++++++----------- 3 files changed, 65 insertions(+), 14 deletions(-) diff --git a/arch/arm64/include/asm/kvm_nested.h b/arch/arm64/include/asm/kvm_nested.h index 27ec73da02c6..4e94b57d21e3 100644 --- a/arch/arm64/include/asm/kvm_nested.h +++ b/arch/arm64/include/asm/kvm_nested.h @@ -396,6 +396,8 @@ struct s1_walk_info { bool s2; bool pa52bit; bool ha; + bool nofault; + bool insn_fetch; }; struct s1_walk_result { diff --git a/arch/arm64/kvm/arm.c b/arch/arm64/kvm/arm.c index a148e80d0aef..98563c3bbec3 100644 --- a/arch/arm64/kvm/arm.c +++ b/arch/arm64/kvm/arm.c @@ -983,6 +983,44 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) { return *vcpu_pc(vcpu); } + +gpa_t kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu) +{ + struct s1_walk_result wr = {}; + struct s1_walk_info wi = { + .nofault = true, + .insn_fetch = true, + }; + u64 va = *vcpu_pc(vcpu); + + if (kvm_vm_is_protected(vcpu->kvm)) + return INVALID_GPA; + + if (vcpu_mode_is_32bit(vcpu)) { + if (vcpu_has_nv(vcpu) && + (__vcpu_sys_reg(vcpu, HCR_EL2) & + (HCR_EL2_VM | HCR_EL2_DC | HCR_EL2_TGE))) + return INVALID_GPA; + if (vcpu_read_sys_reg(vcpu, SCTLR_EL1) & SCTLR_ELx_M) + return INVALID_GPA; + return va & GENMASK_ULL(31, 0); + } + + if (is_hyp_ctxt(vcpu)) + wi.regime = vcpu_el2_e2h_is_set(vcpu) ? TR_EL20 : TR_EL2; + else + wi.regime = TR_EL10; + wi.as_el0 = !vcpu_mode_priv(vcpu); + + if (__kvm_translate_va(vcpu, &wi, &wr, va)) + return INVALID_GPA; + if (wi.s2) + return INVALID_GPA; + if (wi.as_el0 ? !wr.ux : !wr.px) + return INVALID_GPA; + + return wr.pa; +} #endif static void kvm_init_mpidr_data(struct kvm *kvm) diff --git a/arch/arm64/kvm/at.c b/arch/arm64/kvm/at.c index 30d8f062b2c2..f7cfa1793b16 100644 --- a/arch/arm64/kvm/at.c +++ b/arch/arm64/kvm/at.c @@ -274,10 +274,13 @@ static int setup_s1_walk(struct kvm_vcpu *vcpu, struct s1_walk_info *wi, goto addrsz; tbi = (wi->regime == TR_EL2 ? - FIELD_GET(TCR_EL2_TBI, tcr) : + (FIELD_GET(TCR_EL2_TBI, tcr) && + (!wi->insn_fetch || !FIELD_GET(TCR_EL2_TBID, tcr))) : (va55 ? - FIELD_GET(TCR_TBI1, tcr) : - FIELD_GET(TCR_TBI0, tcr))); + (FIELD_GET(TCR_TBI1, tcr) && + (!wi->insn_fetch || !(tcr & TCR_TBID1))) : + (FIELD_GET(TCR_TBI0, tcr) && + (!wi->insn_fetch || !(tcr & TCR_TBID0))))); if (!tbi && (u64)sign_extend64(va, 55) != va) goto addrsz; @@ -433,7 +436,10 @@ static int kvm_read_s1_desc(struct kvm_vcpu *vcpu, u64 pa, u64 *desc, u64 val; int r; - r = kvm_read_guest(vcpu->kvm, pa, &val, sizeof(val)); + if (wi->nofault) + r = kvm_vcpu_read_guest_nofault(vcpu, pa, &val, sizeof(val)); + else + r = kvm_read_guest(vcpu->kvm, pa, &val, sizeof(val)); if (r) return r; @@ -481,6 +487,9 @@ static int walk_s1(struct kvm_vcpu *vcpu, struct s1_walk_info *wi, ipa = baddr | index; if (wi->s2) { + if (wi->nofault) + return -EOPNOTSUPP; + ret = kvm_walk_nested_s2(vcpu, ipa, &s2_trans); if (ret == -EAGAIN) return ret; @@ -580,17 +589,19 @@ static int walk_s1(struct kvm_vcpu *vcpu, struct s1_walk_info *wi, new_desc |= PTE_AF; if (new_desc != desc) { - if (wi->s2 && !kvm_s2_trans_writable(&s2_trans)) { - fail_s1_walk(wr, ESR_ELx_FSC_PERM_L(level), true); - return -EPERM; - } + if (!wi->nofault) { + if (wi->s2 && !kvm_s2_trans_writable(&s2_trans)) { + fail_s1_walk(wr, ESR_ELx_FSC_PERM_L(level), true); + return -EPERM; + } - ret = kvm_swap_s1_desc(vcpu, ipa, desc, new_desc, wi); - if (ret == -EAGAIN) - return ret; - if (ret) { - fail_s1_walk(wr, ESR_ELx_FSC_SEA_TTW(level), false); - return ret; + ret = kvm_swap_s1_desc(vcpu, ipa, desc, new_desc, wi); + if (ret == -EAGAIN) + return ret; + if (ret) { + fail_s1_walk(wr, ESR_ELx_FSC_SEA_TTW(level), false); + return ret; + } } desc = new_desc; -- 2.56.1.915.g69d5ec7298-goog Implement kvm_arch_vcpu_get_ip_gpa() on RISC-V so PERF_SAMPLE_HOST_IP translates the guest PC to a guest physical address using non-faulting guest memory reads. Read live CSR_VSATP when the vCPU is loaded on the current CPU (via NACL shmem or hardware CSR, falling back to saved guest_csr.vsatp otherwise) and walk Sv32, Sv39, Sv48, or Sv57 guest page tables (including Svnapot 64KB pages) with execute and U/S privilege checks using kvm_vcpu_read_guest_nofault(). Signed-off-by: Ian Rogers --- arch/riscv/kvm/vcpu.c | 103 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/arch/riscv/kvm/vcpu.c b/arch/riscv/kvm/vcpu.c index 570b6864e94c..fe9ceec6a7c1 100644 --- a/arch/riscv/kvm/vcpu.c +++ b/arch/riscv/kvm/vcpu.c @@ -17,9 +17,11 @@ #include #include #include +#include #include #include #include +#include #define CREATE_TRACE_POINTS #include "trace.h" @@ -249,6 +251,107 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) { return vcpu->arch.guest_context.sepc; } + +gpa_t kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu) +{ + unsigned long gva = vcpu->arch.guest_context.sepc; + unsigned long vsatp, mode, ppn, pte; + unsigned int levels, vpn_bits; + int level; + + if (vcpu->cpu == raw_smp_processor_id()) { + if (kvm_riscv_nacl_available()) + vsatp = nacl_csr_read(nacl_shmem(), CSR_VSATP); + else + vsatp = csr_read(CSR_VSATP); + } else { + vsatp = vcpu->arch.guest_csr.vsatp; + } + + mode = vsatp >> SATP_MODE_SHIFT; + if (mode == 0) + return (gpa_t)gva; + +#ifdef CONFIG_64BIT + switch (vsatp & (0xfUL << SATP_MODE_SHIFT)) { + case SATP_MODE_39: + levels = 3; + if ((unsigned long)sign_extend64(gva, 38) != gva) + return INVALID_GPA; + break; + case SATP_MODE_48: + levels = 4; + if ((unsigned long)sign_extend64(gva, 47) != gva) + return INVALID_GPA; + break; + case SATP_MODE_57: + levels = 5; + if ((unsigned long)sign_extend64(gva, 56) != gva) + return INVALID_GPA; + break; + default: + return INVALID_GPA; + } + vpn_bits = 9; +#else + if ((vsatp & SATP_MODE_32) == 0) + return INVALID_GPA; + levels = 2; + vpn_bits = 10; +#endif + + ppn = vsatp & SATP_PPN; + for (level = levels - 1; level >= 0; level--) { + unsigned int shift = PAGE_SHIFT + level * vpn_bits; + unsigned long vpn = (gva >> shift) & ((1UL << vpn_bits) - 1); + gpa_t pte_gpa = ((gpa_t)ppn << PAGE_SHIFT) + + vpn * sizeof(unsigned long); + + if (kvm_vcpu_read_guest_nofault(vcpu, pte_gpa, &pte, sizeof(pte))) + return INVALID_GPA; + + if (!(pte & _PAGE_PRESENT)) + return INVALID_GPA; + if ((pte & (_PAGE_READ | _PAGE_WRITE)) == _PAGE_WRITE) + return INVALID_GPA; + +#ifdef CONFIG_64BIT + ppn = (pte & GENMASK_ULL(53, 10)) >> _PAGE_PFN_SHIFT; +#else + ppn = pte >> _PAGE_PFN_SHIFT; +#endif + + if (pte & (_PAGE_READ | _PAGE_WRITE | _PAGE_EXEC)) { + if (!(pte & _PAGE_EXEC)) + return INVALID_GPA; + if (kvm_arch_vcpu_in_kernel(vcpu) ? + (pte & _PAGE_USER) : !(pte & _PAGE_USER)) + return INVALID_GPA; + if (level > 0 && (ppn & ((1UL << (level * vpn_bits)) - 1))) + return INVALID_GPA; +#ifdef CONFIG_64BIT + if (pte & _PAGE_NAPOT) { + if (!riscv_isa_extension_available(vcpu->arch.isa, SVNAPOT) || + level != 0 || + (ppn & ((1UL << NAPOT_CONT64KB_ORDER) - 1)) != + BIT(NAPOT_CONT64KB_ORDER - 1)) + return INVALID_GPA; + ppn &= ~((1UL << NAPOT_CONT64KB_ORDER) - 1); + return ((gpa_t)ppn << PAGE_SHIFT) | + (gva & (napot_cont_size(NAPOT_CONT64KB_ORDER) - 1)); + } +#endif + return ((gpa_t)ppn << PAGE_SHIFT) | + (gva & ((1ULL << shift) - 1)); + } +#ifdef CONFIG_64BIT + if (pte & _PAGE_NAPOT) + return INVALID_GPA; +#endif + } + + return INVALID_GPA; +} #endif vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf) -- 2.56.1.915.g69d5ec7298-goog Implement kvm_arch_vcpu_get_ip_gpa() on LoongArch so PERF_SAMPLE_HOST_IP translates the guest PC to a guest physical address using non-faulting guest memory reads. Handle direct-addressing mode, DMWIN0/DMWIN1 instruction fetch windows, and PWCTL0/PWCTL1 multi-level page-table walks (up to 4 levels plus huge pages) with execute and PLV/RPLV permission checks using kvm_vcpu_read_guest_nofault(). Signed-off-by: Ian Rogers --- arch/loongarch/kvm/vcpu.c | 104 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/arch/loongarch/kvm/vcpu.c b/arch/loongarch/kvm/vcpu.c index 76afd386abd2..32985380a636 100644 --- a/arch/loongarch/kvm/vcpu.c +++ b/arch/loongarch/kvm/vcpu.c @@ -4,9 +4,12 @@ */ #include +#include #include +#include #include #include +#include #include #include #include @@ -396,6 +399,107 @@ unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) return vcpu->arch.pc; } +static bool kvm_loongarch_pte_exec_allowed(u64 entry, unsigned long plv) +{ + unsigned long entry_plv = (entry & _PAGE_PLV) >> _PAGE_PLV_SHIFT; + + if (!(entry & _PAGE_VALID) || (entry & _PAGE_NO_EXEC)) + return false; + if (plv > entry_plv) + return false; + if ((entry & _PAGE_RPLV) && plv != entry_plv) + return false; + return true; +} + +gpa_t kvm_arch_vcpu_get_ip_gpa(struct kvm_vcpu *vcpu) +{ + unsigned long gva = vcpu->arch.pc; + unsigned long crmd, plv, dmw0, dmw1, pgd, pwctl0, pwctl1; + struct { + unsigned int base; + unsigned int width; + } dirs[4]; + unsigned int ptbase, ptwidth; + u64 entry; + gpa_t table_gpa; + int i; + + preempt_disable(); + crmd = read_gcsr_crmd(); + dmw0 = read_gcsr_directwin0(); + dmw1 = read_gcsr_directwin1(); + pgd = (gva & BIT_ULL(63)) ? read_gcsr_pgdh() : read_gcsr_pgdl(); + pwctl0 = read_gcsr_pwctl0(); + pwctl1 = read_gcsr_pwctl1(); + preempt_enable(); + + if ((crmd & CSR_CRMD_DA) && !(crmd & CSR_CRMD_PG)) + return gva & TO_PHYS_MASK; + + if (!(crmd & CSR_CRMD_PG)) + return INVALID_GPA; + + plv = crmd & CSR_CRMD_PLV; + if (((dmw0 & BIT(plv)) && ((dmw0 ^ gva) >> 60) == 0) || + ((dmw1 & BIT(plv)) && ((dmw1 ^ gva) >> 60) == 0)) + return gva & TO_PHYS_MASK; + + dirs[0].base = (pwctl1 >> CSR_PWCTL1_DIR3BASE_SHIFT) & 0x3f; + dirs[0].width = (pwctl1 >> CSR_PWCTL1_DIR3WIDTH_SHIFT) & 0x1f; + dirs[1].base = (pwctl1 >> CSR_PWCTL1_DIR2BASE_SHIFT) & 0x3f; + dirs[1].width = (pwctl1 >> CSR_PWCTL1_DIR2WIDTH_SHIFT) & 0x1f; + dirs[2].base = (pwctl0 >> CSR_PWCTL0_DIR1BASE_SHIFT) & 0x1f; + dirs[2].width = (pwctl0 >> CSR_PWCTL0_DIR1WIDTH_SHIFT) & 0x1f; + dirs[3].base = (pwctl0 >> CSR_PWCTL0_DIR0BASE_SHIFT) & 0x1f; + dirs[3].width = (pwctl0 >> CSR_PWCTL0_DIR0WIDTH_SHIFT) & 0x1f; + ptbase = (pwctl0 >> CSR_PWCTL0_PTBASE_SHIFT) & 0x1f; + ptwidth = (pwctl0 >> CSR_PWCTL0_PTWIDTH_SHIFT) & 0x1f; + + if (ptbase < 12 || ptbase > 16 || !ptwidth || ptbase + ptwidth > 48) + return INVALID_GPA; + + table_gpa = pgd & GENMASK_ULL(47, 12); + for (i = 0; i < ARRAY_SIZE(dirs); i++) { + unsigned long idx; + + if (!dirs[i].width) + continue; + if (dirs[i].base < ptbase + ptwidth || + dirs[i].base + dirs[i].width > 63) + return INVALID_GPA; + + idx = (gva >> dirs[i].base) & ((1UL << dirs[i].width) - 1); + if (kvm_vcpu_read_guest_nofault(vcpu, + table_gpa + idx * sizeof(u64), + &entry, sizeof(entry))) + return INVALID_GPA; + + if (entry & _PAGE_HUGE) { + if (dirs[i].base >= 48 || + !kvm_loongarch_pte_exec_allowed(entry, plv)) + return INVALID_GPA; + return (entry & GENMASK_ULL(47, dirs[i].base)) | + (gva & GENMASK_ULL(dirs[i].base - 1, 0)); + } + + table_gpa = entry & GENMASK_ULL(47, 12); + } + + if (kvm_vcpu_read_guest_nofault(vcpu, + table_gpa + + (((gva >> ptbase) & ((1UL << ptwidth) - 1)) * + sizeof(u64)), + &entry, sizeof(entry))) + return INVALID_GPA; + + if (!kvm_loongarch_pte_exec_allowed(entry, plv)) + return INVALID_GPA; + + return (entry & GENMASK_ULL(47, ptbase)) | + (gva & GENMASK_ULL(ptbase - 1, 0)); +} + /* * Returns true if a Performance Monitoring Interrupt (PMI), a.k.a. perf event, * arrived in guest context. For LoongArch64, if PMU is not passthrough to VM, -- 2.56.1.915.g69d5ec7298-goog Copy the PERF_SAMPLE_HOST_IP and attr.mmap_bpf additions from include/uapi/linux/perf_event.h to tools/include/uapi/linux/perf_event.h. Signed-off-by: Ian Rogers --- tools/include/uapi/linux/perf_event.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tools/include/uapi/linux/perf_event.h b/tools/include/uapi/linux/perf_event.h index c49fc76292f7..146df3041c31 100644 --- a/tools/include/uapi/linux/perf_event.h +++ b/tools/include/uapi/linux/perf_event.h @@ -165,8 +165,9 @@ enum perf_event_sample_format { PERF_SAMPLE_DATA_PAGE_SIZE = 1U << 22, PERF_SAMPLE_CODE_PAGE_SIZE = 1U << 23, PERF_SAMPLE_WEIGHT_STRUCT = 1U << 24, + PERF_SAMPLE_HOST_IP = 1U << 25, - PERF_SAMPLE_MAX = 1U << 25, /* non-ABI */ + PERF_SAMPLE_MAX = 1U << 26, /* non-ABI */ }; #define PERF_SAMPLE_WEIGHT_TYPE (PERF_SAMPLE_WEIGHT | PERF_SAMPLE_WEIGHT_STRUCT) @@ -468,7 +469,8 @@ struct perf_event_attr { sigtrap : 1, /* send synchronous SIGTRAP on event */ defer_callchain: 1, /* request PERF_RECORD_CALLCHAIN_DEFERRED records */ defer_output : 1, /* output PERF_RECORD_CALLCHAIN_DEFERRED records */ - __reserved_1 : 24; + mmap_bpf : 1, /* filter mmap_data events with BPF prog */ + __reserved_1 : 23; union { __u32 wakeup_events; /* wake up every n events */ @@ -1093,6 +1095,7 @@ enum perf_event_type { * { u64 cgroup;} && PERF_SAMPLE_CGROUP * { u64 data_page_size;} && PERF_SAMPLE_DATA_PAGE_SIZE * { u64 code_page_size;} && PERF_SAMPLE_CODE_PAGE_SIZE + * { u64 host_ip;} && PERF_SAMPLE_HOST_IP * { u64 size; * char data[size]; } && PERF_SAMPLE_AUX * }; -- 2.56.1.915.g69d5ec7298-goog Add core userspace plumbing for PERF_SAMPLE_HOST_IP: - Add host_ip to struct perf_sample and wire __evsel__parse_sample(), perf_event__sample_event_size(), perf_event__synthesize_sample(), dump_sample(), and perf_event_attr__fprintf() (placing PERF_SAMPLE_HOST_IP right after PERF_SAMPLE_CODE_PAGE_SIZE and before PERF_SAMPLE_AUX). - Add --host-ip to perf record (and perf kvm record) to request PERF_SAMPLE_HOST_IP on non-dummy events, probe kernel support in evsel__detect_missing_features(), and report a helpful message in evsel__open_strerror(). - Mark host DSOs hit via sample->host_ip in build_id__mark_dso_hit() so perf record --host-ip caches their build-ids. - Update the sample-parsing test to cover PERF_SAMPLE_HOST_IP (standalone, combined with all sample bits, and truncated bounds checking). Signed-off-by: Ian Rogers --- tools/perf/Documentation/perf-record.txt | 7 ++++++ tools/perf/builtin-record.c | 2 ++ tools/perf/tests/sample-parsing.c | 7 +++++- tools/perf/util/build-id.c | 27 +++++++++++++++++++++++ tools/perf/util/evsel.c | 22 ++++++++++++++++++ tools/perf/util/evsel.h | 1 + tools/perf/util/perf_event_attr_fprintf.c | 3 ++- tools/perf/util/record.h | 1 + tools/perf/util/sample.h | 2 ++ tools/perf/util/session.c | 3 +++ tools/perf/util/synthetic-events.c | 8 +++++++ 11 files changed, 81 insertions(+), 2 deletions(-) diff --git a/tools/perf/Documentation/perf-record.txt b/tools/perf/Documentation/perf-record.txt index 2351f7b4f5fc..fb3029f82a08 100644 --- a/tools/perf/Documentation/perf-record.txt +++ b/tools/perf/Documentation/perf-record.txt @@ -534,6 +534,13 @@ sets are allowed like -I. --running-time:: Record running and enabled time for read events (:S) +--host-ip:: +Record host virtual IP addresses alongside sampled instruction addresses +(PERF_SAMPLE_HOST_IP). When profiling virtual machines with direct-access (DAX) +or file-backed hypervisor mappings, this allows host mappings to symbolize guest +samples without requiring guest symbol information, and filters non-executable +hypervisor file mappings via BPF when supported. + -k:: --clockid:: Sets the clock id to use for the various time fields in the perf_event_type diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index 085d3648a30a..4ff929191211 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -3546,6 +3546,8 @@ static struct option __record_options[] = { "Record the sampled data address data page size"), OPT_BOOLEAN(0, "code-page-size", &record.opts.sample_code_page_size, "Record the sampled code address (ip) page size"), + OPT_BOOLEAN(0, "host-ip", &record.opts.sample_host_ip, + "Record host virtual IP addresses for sampled instructions"), OPT_BOOLEAN(0, "sample-mem-info", &record.opts.sample_data_src, "Record the data source for memory operations"), OPT_BOOLEAN(0, "sample-cpu", &record.opts.sample_cpu, "Record the sample cpu"), diff --git a/tools/perf/tests/sample-parsing.c b/tools/perf/tests/sample-parsing.c index acbd353d3588..9c04eaba813d 100644 --- a/tools/perf/tests/sample-parsing.c +++ b/tools/perf/tests/sample-parsing.c @@ -209,6 +209,9 @@ static bool samples_same(struct perf_sample *s1, if (type & PERF_SAMPLE_CODE_PAGE_SIZE) COMP(code_page_size); + if (type & PERF_SAMPLE_HOST_IP) + COMP(host_ip); + if (type & PERF_SAMPLE_AUX) { COMP(aux_sample.size); if (memcmp(s1->aux_sample.data, s2->aux_sample.data, @@ -295,6 +298,7 @@ static int do_test(u64 sample_type, u64 sample_regs, u64 read_format) .size = sizeof(aux_data), .data = (void *)aux_data, }, + .host_ip = 119, }; struct sample_read_value values[] = {{1, 5, 0}, {9, 3, 0}, {2, 7, 0}, {6, 4, 1},}; struct sample_read_value packed_values[ARRAY_SIZE(values)]; @@ -554,6 +558,7 @@ static int test_truncated_u64_fields(void) PERF_SAMPLE_CGROUP, PERF_SAMPLE_DATA_PAGE_SIZE, PERF_SAMPLE_CODE_PAGE_SIZE, + PERF_SAMPLE_HOST_IP, }; for (size_t i = 0; i < ARRAY_SIZE(types); i++) { @@ -606,7 +611,7 @@ static int test__sample_parsing(struct test_suite *test __maybe_unused, int subt * were added. Please actually update the test rather than just change * the condition below. */ - if (PERF_SAMPLE_MAX > PERF_SAMPLE_WEIGHT_STRUCT << 1) { + if (PERF_SAMPLE_MAX > PERF_SAMPLE_HOST_IP << 1) { pr_debug("sample format has changed, some new PERF_SAMPLE_ bit was introduced - test needs updating\n"); return -1; } diff --git a/tools/perf/util/build-id.c b/tools/perf/util/build-id.c index 02233ef0eaff..cc5ce39ddacd 100644 --- a/tools/perf/util/build-id.c +++ b/tools/perf/util/build-id.c @@ -74,6 +74,33 @@ int build_id__mark_dso_hit(const struct perf_tool *tool __maybe_unused, addr_location__exit(&al); + if (sample->host_ip) { + struct machine *host_machine = machine__is_host(machine) ? + machine : (machine->machines ? &machine->machines->host : NULL); + + if (host_machine) { + struct thread *host_thread = machine__findnew_thread(host_machine, + sample->pid, + sample->tid); + struct maps *host_maps = NULL; + + if (machine__kernel_ip(host_machine, sample->host_ip)) + host_maps = machine__kernel_maps(host_machine); + else if (host_thread) + host_maps = thread__maps(host_thread); + + if (host_maps) { + struct map *host_map = maps__find(host_maps, sample->host_ip); + + if (host_map) { + dso__set_hit(map__dso(host_map)); + map__put(host_map); + } + } + thread__put(host_thread); + } + } + sample__for_each_callchain_node(thread, sample, PERF_MAX_STACK_DEPTH, /*symbols=*/false, mark_dso_hit_callback, /*data=*/NULL); diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c index 90269b8d1745..5950a383eff4 100644 --- a/tools/perf/util/evsel.c +++ b/tools/perf/util/evsel.c @@ -1769,6 +1769,9 @@ void evsel__config(struct evsel *evsel, const struct record_opts *opts, if (opts->sample_code_page_size) evsel__set_sample_bit(evsel, CODE_PAGE_SIZE); + if (opts->sample_host_ip && !evsel__is_dummy_event(evsel)) + evsel__set_sample_bit(evsel, HOST_IP); + if (opts->record_switch_events) attr->context_switch = track; @@ -2825,6 +2828,13 @@ static bool evsel__detect_missing_features(struct evsel *evsel, struct perf_cpu /* Please add new feature detection here. */ + attr.sample_type = PERF_SAMPLE_HOST_IP; + if (has_attr_feature(&attr, /*flags=*/0)) + goto found; + perf_missing_features.host_ip = true; + pr_debug2_peo("Kernel has no PERF_SAMPLE_HOST_IP support\n"); + attr.sample_type = 0; + attr.defer_callchain = true; if (has_attr_feature(&attr, /*flags=*/0)) goto found; @@ -3898,6 +3908,13 @@ int __evsel__parse_sample(struct evsel *evsel, union perf_event *event, array++; } + data->host_ip = 0; + if (type & PERF_SAMPLE_HOST_IP) { + OVERFLOW_CHECK_u64(array); + data->host_ip = *array; + array++; + } + if (type & PERF_SAMPLE_AUX) { OVERFLOW_CHECK_u64(array); sz = *array++; @@ -4677,6 +4694,11 @@ int evsel__open_strerror(struct evsel *evsel, struct target *target, size - printed); break; case EINVAL: + if ((evsel->core.attr.sample_type & PERF_SAMPLE_HOST_IP) && + perf_missing_features.host_ip) { + return scnprintf(msg, size, + "Asking for the host IP isn't supported by this kernel."); + } if (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE && perf_missing_features.code_page_size) return scnprintf(msg, size, "Asking for the code page size isn't supported by this kernel."); if (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE && perf_missing_features.data_page_size) diff --git a/tools/perf/util/evsel.h b/tools/perf/util/evsel.h index 53f3641b66e1..ce38cea0f729 100644 --- a/tools/perf/util/evsel.h +++ b/tools/perf/util/evsel.h @@ -236,6 +236,7 @@ struct perf_missing_features { bool aux_action; bool inherit_sample_read; bool defer_callchain; + bool host_ip; }; extern struct perf_missing_features perf_missing_features; diff --git a/tools/perf/util/perf_event_attr_fprintf.c b/tools/perf/util/perf_event_attr_fprintf.c index 2e8be9a357dc..492dcc04bd99 100644 --- a/tools/perf/util/perf_event_attr_fprintf.c +++ b/tools/perf/util/perf_event_attr_fprintf.c @@ -40,7 +40,7 @@ static void __p_sample_type(char *buf, size_t size, u64 value) bit_name(IDENTIFIER), bit_name(REGS_INTR), bit_name(DATA_SRC), bit_name(WEIGHT), bit_name(PHYS_ADDR), bit_name(AUX), bit_name(CGROUP), bit_name(DATA_PAGE_SIZE), bit_name(CODE_PAGE_SIZE), - bit_name(WEIGHT_STRUCT), + bit_name(WEIGHT_STRUCT), bit_name(HOST_IP), { .name = NULL, } }; #undef bit_name @@ -384,6 +384,7 @@ int perf_event_attr__fprintf(FILE *fp, struct perf_event_attr *attr, PRINT_ATTRf_bf(sigtrap, p_unsigned); PRINT_ATTRf_bf(defer_callchain, p_unsigned); PRINT_ATTRf_bf(defer_output, p_unsigned); + PRINT_ATTRf_bf(mmap_bpf, p_unsigned); } PRINT_ATTRn("{ wakeup_events, wakeup_watermark }", wakeup_events, p_unsigned, false); diff --git a/tools/perf/util/record.h b/tools/perf/util/record.h index 411bb7276ad7..99f20019dbf8 100644 --- a/tools/perf/util/record.h +++ b/tools/perf/util/record.h @@ -23,6 +23,7 @@ struct record_opts { bool sample_phys_addr; bool sample_data_page_size; bool sample_code_page_size; + bool sample_host_ip; bool sample_weight; bool sample_time; bool sample_time_set; diff --git a/tools/perf/util/sample.h b/tools/perf/util/sample.h index cb4b16654876..c27f21db45e1 100644 --- a/tools/perf/util/sample.h +++ b/tools/perf/util/sample.h @@ -163,6 +163,8 @@ struct perf_sample { u64 code_page_size; /** @cgroup: The sample event PERF_SAMPLE_CGROUP value. */ u64 cgroup; + /** @host_ip: The sample event PERF_SAMPLE_HOST_IP value. */ + u64 host_ip; /** @file_offset: Byte offset of this event in the perf.data file. */ u64 file_offset; /** @flags: Extra flag data from auxiliary events like intel-pt. */ diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c index 56a5e57ec512..f143ffbd7f8b 100644 --- a/tools/perf/util/session.c +++ b/tools/perf/util/session.c @@ -1734,6 +1734,9 @@ static void dump_sample(struct machine *machine, union perf_event *event, if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) printf(" .. code page size: %s\n", get_page_size_name(sample->code_page_size, str)); + if (sample_type & PERF_SAMPLE_HOST_IP) + printf(" .. host_ip: %#" PRIx64 "\n", sample->host_ip); + if (sample_type & PERF_SAMPLE_TRANSACTION) printf("... transaction: %" PRIx64 "\n", sample->transaction); diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c index b9dbd105cdc3..92e9b086b1b3 100644 --- a/tools/perf/util/synthetic-events.c +++ b/tools/perf/util/synthetic-events.c @@ -1704,6 +1704,9 @@ size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type, if (type & PERF_SAMPLE_CODE_PAGE_SIZE) result += sizeof(u64); + if (type & PERF_SAMPLE_HOST_IP) + result += sizeof(u64); + if (type & PERF_SAMPLE_AUX) { result += sizeof(u64); result += sample->aux_sample.size; @@ -1958,6 +1961,11 @@ int perf_event__synthesize_sample(union perf_event *event, u64 type, u64 read_fo array++; } + if (type & PERF_SAMPLE_HOST_IP) { + *array = sample->host_ip; + array++; + } + if (type & PERF_SAMPLE_AUX) { sz = sample->aux_sample.size; *array++ = sz; -- 2.56.1.915.g69d5ec7298-goog Store resolved host mapping state (host_map, host_sym, host_addr, raw_host_ip) in struct addr_location and resolve sample->host_ip against machines->host in machine__resolve(). When a guest sample cannot be symbolized in the guest machine, automatically fall back to the resolved host mapping and symbol (and clear HIST_FILTER__GUEST when perf_host or perf_guest is active), so guest code backed by host DAX or file-backed mappings symbolizes transparently without guest symbol state. Signed-off-by: Ian Rogers --- tools/perf/util/addr_location.c | 7 ++++ tools/perf/util/addr_location.h | 4 +++ tools/perf/util/event.c | 58 +++++++++++++++++++++++++++++++-- 3 files changed, 67 insertions(+), 2 deletions(-) diff --git a/tools/perf/util/addr_location.c b/tools/perf/util/addr_location.c index 57e8217a00f9..ca0380260ee6 100644 --- a/tools/perf/util/addr_location.c +++ b/tools/perf/util/addr_location.c @@ -9,8 +9,12 @@ void addr_location__init(struct addr_location *al) al->thread = NULL; al->map = NULL; al->sym = NULL; + al->host_map = NULL; + al->host_sym = NULL; al->srcline = NULL; al->addr = 0; + al->host_addr = 0; + al->raw_host_ip = 0; al->level = 0; al->filtered = 0; al->cpumode = 0; @@ -28,6 +32,7 @@ void addr_location__init(struct addr_location *al) void addr_location__exit(struct addr_location *al) { map__zput(al->map); + map__zput(al->host_map); thread__zput(al->thread); } @@ -35,7 +40,9 @@ void addr_location__copy(struct addr_location *dst, struct addr_location *src) { thread__put(dst->thread); map__put(dst->map); + map__put(dst->host_map); *dst = *src; dst->thread = thread__get(src->thread); dst->map = map__get(src->map); + dst->host_map = map__get(src->host_map); } diff --git a/tools/perf/util/addr_location.h b/tools/perf/util/addr_location.h index fdc4d3f3a68b..d4148d7df998 100644 --- a/tools/perf/util/addr_location.h +++ b/tools/perf/util/addr_location.h @@ -13,8 +13,12 @@ struct addr_location { struct thread *thread; struct map *map; struct symbol *sym; + struct map *host_map; + struct symbol *host_sym; const char *srcline; u64 addr; + u64 host_addr; + u64 raw_host_ip; char level; u8 cpumode; u16 filtered; diff --git a/tools/perf/util/event.c b/tools/perf/util/event.c index ea75816d126a..96d88d88ba06 100644 --- a/tools/perf/util/event.c +++ b/tools/perf/util/event.c @@ -808,6 +808,11 @@ int machine__resolve(struct machine *machine, struct addr_location *al, struct thread *thread; struct dso *dso; + map__zput(al->host_map); + al->host_sym = NULL; + al->host_addr = 0; + al->raw_host_ip = sample->host_ip; + if (symbol_conf.guest_code && !machine__is_host(machine)) thread = machine__findnew_guest_code(machine, sample->pid); else @@ -862,6 +867,57 @@ int machine__resolve(struct machine *machine, struct addr_location *al, */ al->latency = sample->period * 1000 / al->parallelism; + if (al->map) + al->sym = map__find_symbol(al->map, al->addr); + + if (sample->host_ip) { + struct machine *host_machine = machine__is_host(machine) ? + machine : (machine->machines ? &machine->machines->host : NULL); + + if (host_machine) { + struct thread *host_thread = machine__findnew_thread(host_machine, + sample->pid, + sample->tid); + struct maps *host_maps = NULL; + bool load_host_map = false; + + if (machine__kernel_ip(host_machine, sample->host_ip)) { + host_maps = machine__kernel_maps(host_machine); + load_host_map = !symbol_conf.lazy_load_kernel_maps; + } else if (host_thread) { + host_maps = thread__maps(host_thread); + } + + if (host_maps) { + al->host_map = maps__find(host_maps, sample->host_ip); + if (al->host_map) { + if (load_host_map) + map__load(al->host_map); + al->host_addr = map__map_ip(al->host_map, + sample->host_ip); + al->host_sym = map__find_symbol(al->host_map, + al->host_addr); + } + } + thread__put(host_thread); + } + + if ((sample->cpumode == PERF_RECORD_MISC_GUEST_USER || + sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL) && + !al->sym && al->host_map && (al->host_sym || !al->map)) { + map__zput(al->map); + al->map = map__get(al->host_map); + al->addr = al->host_addr; + al->sym = al->host_sym; + dso = map__dso(al->map); + if (perf_host || perf_guest) { + al->filtered &= ~(1 << HIST_FILTER__GUEST); + al->level = (sample->cpumode == PERF_RECORD_MISC_GUEST_KERNEL) ? + 'g' : 'u'; + } + } + } + if (al->map) { if (symbol_conf.dso_list && (!dso || !(strlist__has_entry(symbol_conf.dso_list, @@ -871,8 +927,6 @@ int machine__resolve(struct machine *machine, struct addr_location *al, dso__long_name(dso)))))) { al->filtered |= (1 << HIST_FILTER__DSO); } - - al->sym = map__find_symbol(al->map, al->addr); } else if (symbol_conf.dso_list) { al->filtered |= (1 << HIST_FILTER__DSO); } -- 2.56.1.915.g69d5ec7298-goog Store the resolved host_map, host_sym, host_addr, and raw_host_ip on struct hist_entry and expose explicit host_ip, host_dso, and host_sym sort keys in perf report as well as host_ip, host_sym, and host_dso output fields in perf script. Signed-off-by: Ian Rogers --- tools/perf/Documentation/perf-report.txt | 3 + tools/perf/Documentation/perf-script.txt | 4 + tools/perf/builtin-script.c | 48 ++++++++++ tools/perf/util/hist.c | 48 ++++++++++ tools/perf/util/hist.h | 6 ++ tools/perf/util/sort.c | 114 +++++++++++++++++++++++ tools/perf/util/sort.h | 4 + 7 files changed, 227 insertions(+) diff --git a/tools/perf/Documentation/perf-report.txt b/tools/perf/Documentation/perf-report.txt index e145124d6c9a..64466ccab9fd 100644 --- a/tools/perf/Documentation/perf-report.txt +++ b/tools/perf/Documentation/perf-report.txt @@ -156,6 +156,9 @@ OPTIONS - p_stage_cyc: On powerpc, this presents the number of cycles spent in a pipeline stage. And currently supported only on powerpc. - addr: (Full) virtual address of the sampled instruction + - host_ip: Host virtual address of the sampled instruction (recorded with --host-ip) + - host_dso: Host DSO mapped at host_ip + - host_sym / host_symbol: Host symbol resolved at host_ip - retire_lat: On X86, this reports pipeline stall of this instruction compared to the previous instruction in cycles. And currently supported only on X86 - simd: Flags describing a SIMD operation. The architecture type can be Arm's diff --git a/tools/perf/Documentation/perf-script.txt b/tools/perf/Documentation/perf-script.txt index f0228e784ced..ed66a6d23a68 100644 --- a/tools/perf/Documentation/perf-script.txt +++ b/tools/perf/Documentation/perf-script.txt @@ -169,6 +169,10 @@ OPTIONS The cgroup fields requires sample having the cgroup id which is saved when "--all-cgroups" option is passed to 'perf record'. + The host_ip, host_sym and host_dso fields display the host virtual IP + address, host symbol and host DSO resolved on the host machine when + recorded with 'perf record --host-ip'. + Finally, a user may not set fields to none for all event types. i.e., -F "" is not allowed. diff --git a/tools/perf/builtin-script.c b/tools/perf/builtin-script.c index b6691ebb1b4e..f1f0e388d713 100644 --- a/tools/perf/builtin-script.c +++ b/tools/perf/builtin-script.c @@ -147,6 +147,9 @@ enum perf_output_field { PERF_OUTPUT_DISASM = 1ULL << 42, PERF_OUTPUT_BRSTACKDISASM = 1ULL << 43, PERF_OUTPUT_BRCNTR = 1ULL << 44, + PERF_OUTPUT_HOST_IP = 1ULL << 45, + PERF_OUTPUT_HOST_SYM = 1ULL << 46, + PERF_OUTPUT_HOST_DSO = 1ULL << 47, }; struct perf_script { @@ -223,6 +226,9 @@ static struct output_option { {.str = "retire_lat", .field = PERF_OUTPUT_RETIRE_LAT}, {.str = "brstackdisasm", .field = PERF_OUTPUT_BRSTACKDISASM}, {.str = "brcntr", .field = PERF_OUTPUT_BRCNTR}, + {.str = "host_ip", .field = PERF_OUTPUT_HOST_IP}, + {.str = "host_sym", .field = PERF_OUTPUT_HOST_SYM}, + {.str = "host_dso", .field = PERF_OUTPUT_HOST_DSO}, }; enum { @@ -595,6 +601,18 @@ static int evsel__check_attr(struct evsel *evsel, struct perf_session *session) evsel__check_stype(evsel, PERF_SAMPLE_WEIGHT_STRUCT, "WEIGHT_STRUCT", PERF_OUTPUT_RETIRE_LAT)) return -EINVAL; + if (PRINT_FIELD(HOST_IP) && + evsel__check_stype(evsel, PERF_SAMPLE_HOST_IP, "HOST_IP", PERF_OUTPUT_HOST_IP)) + return -EINVAL; + + if (PRINT_FIELD(HOST_SYM) && + evsel__check_stype(evsel, PERF_SAMPLE_HOST_IP, "HOST_IP", PERF_OUTPUT_HOST_SYM)) + return -EINVAL; + + if (PRINT_FIELD(HOST_DSO) && + evsel__check_stype(evsel, PERF_SAMPLE_HOST_IP, "HOST_IP", PERF_OUTPUT_HOST_DSO)) + return -EINVAL; + return 0; } @@ -2745,6 +2763,36 @@ static void process_event(struct perf_script *script, symbol_conf.bt_stop_list, fp); } + if (PRINT_FIELD(HOST_IP) || PRINT_FIELD(HOST_SYM) || PRINT_FIELD(HOST_DSO)) { + struct perf_sample host_sample = *sample; + struct addr_location host_al; + unsigned int host_opts = 0; + + if (PRINT_FIELD(HOST_IP)) + host_opts |= EVSEL__PRINT_IP; + if (PRINT_FIELD(HOST_SYM)) + host_opts |= EVSEL__PRINT_SYM; + if (PRINT_FIELD(HOST_DSO)) + host_opts |= EVSEL__PRINT_DSO; + if (PRINT_FIELD(DSOFF)) + host_opts |= EVSEL__PRINT_DSOFF; + if (PRINT_FIELD(SYMOFFSET)) + host_opts |= EVSEL__PRINT_SYMOFFSET; + if (output[type].print_ip_opts & EVSEL__PRINT_UNKNOWN_AS_ADDR) + host_opts |= EVSEL__PRINT_UNKNOWN_AS_ADDR; + + host_sample.ip = sample->host_ip; + addr_location__init(&host_al); + host_al.map = map__get(al->host_map); + host_al.sym = al->host_sym; + host_al.addr = al->host_map ? al->host_addr : sample->host_ip; + + fputc(' ', fp); + sample__fprintf_sym(&host_sample, &host_al, 0, host_opts, + NULL, NULL, fp); + addr_location__exit(&host_al); + } + if (PRINT_FIELD(IREGS)) { perf_sample__fprintf_iregs(sample, attr, thread__e_machine(thread, machine, &e_flags), diff --git a/tools/perf/util/hist.c b/tools/perf/util/hist.c index 364754e9d12a..50ecb65a354a 100644 --- a/tools/perf/util/hist.c +++ b/tools/perf/util/hist.c @@ -119,6 +119,24 @@ void hists__calc_col_len(struct hists *hists, struct hist_entry *h) hists__new_col_len(hists, HISTC_DSO, len); } + if (h->host_ms.sym) { + symlen = h->host_ms.sym->namelen + 4; + if (verbose > 0) + symlen += BITS_PER_LONG / 4 + 2 + 3; + hists__new_col_len(hists, HISTC_HOST_SYMBOL, symlen); + } else { + symlen = unresolved_col_width + 4 + 2; + hists__new_col_len(hists, HISTC_HOST_SYMBOL, symlen); + hists__set_unres_dso_col_len(hists, HISTC_HOST_DSO); + } + + if (h->host_ms.map) { + len = dso__name_len(map__dso(h->host_ms.map)); + hists__new_col_len(hists, HISTC_HOST_DSO, len); + } + + hists__new_col_len(hists, HISTC_HOST_IP, BITS_PER_LONG / 4 + 2); + if (h->parent) hists__new_col_len(hists, HISTC_PARENT, h->parent->namelen); @@ -543,6 +561,8 @@ static int hist_entry__init(struct hist_entry *he, he->ms.thread = thread__get(he->ms.thread); he->ms.map = map__get(he->ms.map); + he->host_ms.thread = thread__get(he->host_ms.thread); + he->host_ms.map = map__get(he->host_ms.map); if (he->branch_info) { /* @@ -616,6 +636,7 @@ static int hist_entry__init(struct hist_entry *he, if (he->mem_info) mem_info__zput(he->mem_info); err: + map_symbol__exit(&he->host_ms); map_symbol__exit(&he->ms); zfree(&he->stat_acc); return -ENOMEM; @@ -734,6 +755,20 @@ static struct hist_entry *hists__findnew_entry(struct hists *hists, map__put(he->ms.map); he->ms.map = map__get(entry->ms.map); } + if (hists__has(hists, host_sym) && + entry->host_ms.map && + he->host_ms.map != entry->host_ms.map) { + if (he->host_ms.sym) { + u64 addr = he->host_ms.sym->start; + + he->host_ms.sym = + map__find_symbol(entry->host_ms.map, addr); + } + + map__put(he->host_ms.map); + he->host_ms.map = map__get(entry->host_ms.map); + he->host_ip = entry->host_ip; + } goto out; } @@ -819,11 +854,17 @@ __hists__add_entry(struct hists *hists, .map = al->map, .sym = al->sym, }, + .host_ms = { + .thread = al->thread, + .map = al->host_map, + .sym = al->host_sym, + }, .srcline = (char *) al->srcline, .socket = al->socket, .cpu = al->cpu, .cpumode = al->cpumode, .ip = al->addr, + .host_ip = al->host_map ? al->host_addr : al->raw_host_ip, .level = al->level, .code_page_size = sample->code_page_size, .parallelism = al->parallelism, @@ -1236,11 +1277,17 @@ iter_add_next_cumulative_entry(struct hist_entry_iter *iter, .thread = al->thread, .comm = thread__comm(al->thread), .ip = al->addr, + .host_ip = al->host_map ? al->host_addr : al->raw_host_ip, .ms = { .thread = al->thread, .map = al->map, .sym = al->sym, }, + .host_ms = { + .thread = al->thread, + .map = al->host_map, + .sym = al->host_sym, + }, .srcline = (char *) al->srcline, .parent = iter->parent, .raw_data = sample->raw_data, @@ -1467,6 +1514,7 @@ void hist_entry__delete(struct hist_entry *he) } thread__zput(he->thread); + map_symbol__exit(&he->host_ms); map_symbol__exit(&he->ms); if (he->branch_info) { diff --git a/tools/perf/util/hist.h b/tools/perf/util/hist.h index 0d08011aebce..263b349b9597 100644 --- a/tools/perf/util/hist.h +++ b/tools/perf/util/hist.h @@ -97,6 +97,9 @@ enum hist_column { HISTC_CALLCHAIN_BRANCH_PREDICTED, HISTC_CALLCHAIN_BRANCH_ABORT, HISTC_CALLCHAIN_BRANCH_CYCLES, + HISTC_HOST_IP, + HISTC_HOST_DSO, + HISTC_HOST_SYMBOL, HISTC_NR_COLS, /* Last entry */ }; @@ -247,11 +250,13 @@ struct hist_entry { struct he_stat *stat_acc; struct he_mem_stat *mem_stat; struct map_symbol ms; + struct map_symbol host_ms; struct thread *thread; struct comm *comm; struct namespace_id cgroup_id; u64 cgroup; u64 ip; + u64 host_ip; u64 transaction; u64 code_page_size; u64 weight; @@ -532,6 +537,7 @@ struct perf_hpp_list { int need_collapse; int parent; int sym; + int host_sym; int dso; int socket; int thread; diff --git a/tools/perf/util/sort.c b/tools/perf/util/sort.c index 58638ec9ae0e..229b836479c4 100644 --- a/tools/perf/util/sort.c +++ b/tools/perf/util/sort.c @@ -2476,6 +2476,111 @@ static struct sort_entry sort_addr = { .se_width_idx = HISTC_ADDR, }; +/* --sort host_ip */ + +static int64_t +sort__host_ip_cmp(struct hist_entry *left, struct hist_entry *right) +{ + u64 left_ip = left->host_ip; + u64 right_ip = right->host_ip; + struct map *left_map = left->host_ms.map; + struct map *right_map = right->host_ms.map; + + if (left_map) + left_ip = map__unmap_ip(left_map, left_ip); + if (right_map) + right_ip = map__unmap_ip(right_map, right_ip); + + return _sort__addr_cmp(left_ip, right_ip); +} + +static int hist_entry__host_ip_snprintf(struct hist_entry *he, char *bf, + size_t size, unsigned int width) +{ + u64 ip = he->host_ip; + struct map *map = he->host_ms.map; + + if (map) + ip = map__unmap_ip(map, ip); + + return repsep_snprintf(bf, size, "%-#*llx", width, ip); +} + +static struct sort_entry sort_host_ip = { + .se_header = "Host IP", + .se_cmp = sort__host_ip_cmp, + .se_snprintf = hist_entry__host_ip_snprintf, + .se_width_idx = HISTC_HOST_IP, +}; + +/* --sort host_dso */ + +static int64_t +sort__host_dso_cmp(struct hist_entry *left, struct hist_entry *right) +{ + return _sort__dso_cmp(right->host_ms.map, left->host_ms.map); +} + +static int hist_entry__host_dso_snprintf(struct hist_entry *he, char *bf, + size_t size, unsigned int width) +{ + return _hist_entry__dso_snprintf(he->host_ms.map, bf, size, width); +} + +static struct sort_entry sort_host_dso = { + .se_header = "Host Shared Object", + .se_cmp = sort__host_dso_cmp, + .se_snprintf = hist_entry__host_dso_snprintf, + .se_width_idx = HISTC_HOST_DSO, +}; + +/* --sort host_sym */ + +static int64_t +sort__host_sym_cmp(struct hist_entry *left, struct hist_entry *right) +{ + int64_t ret; + + if (!left->host_ms.sym && !right->host_ms.sym) + return sort__host_ip_cmp(left, right); + + ret = sort__host_dso_cmp(left, right); + if (ret != 0) + return ret; + + return _sort__sym_cmp(left->host_ms.sym, right->host_ms.sym); +} + +static int64_t +sort__host_sym_sort(struct hist_entry *left, struct hist_entry *right) +{ + if (!left->host_ms.sym || !right->host_ms.sym) + return cmp_null(left->host_ms.sym, right->host_ms.sym); + + return strcmp(right->host_ms.sym->name, left->host_ms.sym->name); +} + +static int hist_entry__host_sym_snprintf(struct hist_entry *he, char *bf, + size_t size, unsigned int width) +{ + struct dso *dso = he->host_ms.map ? map__dso(he->host_ms.map) : NULL; + char level = (dso && dso__kernel(dso)) ? 'k' : '.'; + u64 ip = he->host_ip; + + if (!he->host_ms.sym && he->host_ms.map) + ip = map__unmap_ip(he->host_ms.map, ip); + + return _hist_entry__sym_snprintf(&he->host_ms, ip, level, bf, size, width); +} + +static struct sort_entry sort_host_sym = { + .se_header = "Host Symbol", + .se_cmp = sort__host_sym_cmp, + .se_sort = sort__host_sym_sort, + .se_snprintf = hist_entry__host_sym_snprintf, + .se_width_idx = HISTC_HOST_SYMBOL, +}; + /* --sort type */ struct annotated_data_type unknown_type = { @@ -2757,6 +2862,10 @@ static struct sort_dimension common_sort_dimensions[] = { DIM(SORT_SYM_OFFSET, "symoff", sort_sym_offset), DIM(SORT_ANNOTATE_DATA_TYPE_CACHELINE, "typecln", sort_type_cacheline), DIM(SORT_PARALLELISM, "parallelism", sort_parallelism), + DIM(SORT_HOST_IP, "host_ip", sort_host_ip), + DIM(SORT_HOST_DSO, "host_dso", sort_host_dso), + DIM(SORT_HOST_SYM, "host_sym", sort_host_sym), + DIM(SORT_HOST_SYMBOL, "host_symbol", sort_host_sym), }; #undef DIM @@ -3712,6 +3821,10 @@ static int __sort_dimension__update(struct sort_dimension *sd, } else if (sd->entry == &sort_sym_offset) { list->sym = 1; + } else if (sd->entry == &sort_host_sym) { + list->host_sym = 1; + if (sort__mode == SORT_MODE__DIFF) + sd->entry->se_collapse = sort__host_sym_sort; } else if (sd->entry == &sort_dso) { list->dso = 1; } else if (sd->entry == &sort_socket) { @@ -4453,6 +4566,7 @@ void reset_output_field(void) perf_hpp_list.need_collapse = 0; perf_hpp_list.parent = 0; perf_hpp_list.sym = 0; + perf_hpp_list.host_sym = 0; perf_hpp_list.dso = 0; field_order = NULL; diff --git a/tools/perf/util/sort.h b/tools/perf/util/sort.h index c962e77e4b93..db6f541a82a2 100644 --- a/tools/perf/util/sort.h +++ b/tools/perf/util/sort.h @@ -76,6 +76,10 @@ enum sort_type { SORT_ANNOTATE_DATA_TYPE_CACHELINE, SORT_PARALLELISM, SORT_TGID, + SORT_HOST_IP, + SORT_HOST_DSO, + SORT_HOST_SYM, + SORT_HOST_SYMBOL, /* branch stack specific sort keys */ __SORT_BRANCH_STACK, -- 2.56.1.915.g69d5ec7298-goog Hypervisors map guest images (such as DAX / virtio-pmem or direct file-backed guest memory) without PROT_EXEC, so normal executable PERF_RECORD_MMAP synthesis misses them. Add /proc hypervisor process discovery (using stack-allocated io_dir with openat()/readlinkat() to check for /dev/kvm or anon_inode:kvm-vm* descriptors) and synthesize non-executable linked regular-file MMAP2 records for existing hypervisor processes during perf record --host-ip (when --data-mmap is not already enabled). Signed-off-by: Ian Rogers --- tools/perf/builtin-record.c | 3 + tools/perf/util/Build | 1 + tools/perf/util/kvm-mmap-filter.c | 210 ++++++++++++++++++++++++++++++ tools/perf/util/kvm-mmap-filter.h | 16 +++ 4 files changed, 230 insertions(+) create mode 100644 tools/perf/util/kvm-mmap-filter.c create mode 100644 tools/perf/util/kvm-mmap-filter.h diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index 4ff929191211..5e11ccda8c6d 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -52,6 +52,7 @@ #include "util/clockid.h" #include "util/off_cpu.h" #include "util/bpf-filter.h" +#include "util/kvm-mmap-filter.h" #include "util/strbuf.h" #include "asm/bug.h" #include "perf.h" @@ -2221,6 +2222,8 @@ static int record__synthesize(struct record *rec, bool tail) evlist__core(rec->evlist)->threads, f, needs_mmap, opts->record_data_mmap, rec->opts.nr_threads_synthesize); + if (!err && needs_mmap && opts->sample_host_ip && !opts->record_data_mmap) + err = perf_kvm_mmap_filter__synthesize_maps(tool, machine, f); } if (rec->opts.nr_threads_synthesize > 1) { diff --git a/tools/perf/util/Build b/tools/perf/util/Build index 2c1f880c4c47..fd34879d45ba 100644 --- a/tools/perf/util/Build +++ b/tools/perf/util/Build @@ -130,6 +130,7 @@ perf-util-y += iostat.o perf-util-y += stream.o perf-util-$(CONFIG_LIBTRACEEVENT) += kvm-stat.o perf-util-y += kvm-stat-arch/ +perf-util-y += kvm-mmap-filter.o perf-util-y += lock-contention.o perf-util-y += auxtrace.o perf-util-y += intel-pt-decoder/ diff --git a/tools/perf/util/kvm-mmap-filter.c b/tools/perf/util/kvm-mmap-filter.c new file mode 100644 index 000000000000..daf29359035b --- /dev/null +++ b/tools/perf/util/kvm-mmap-filter.c @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "util/kvm-mmap-filter.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "util/debug.h" +#include "util/event.h" +#include "util/intlist.h" +#include "util/machine.h" +#include "util/tool.h" + +static bool pid_has_kvm_fd(int proc_dirfd, const char *pid_name) +{ + char fd_subpath[32]; + struct io_dirent64 *de; + struct io_dir fd_dir; + bool found = false; + int fd_dirfd; + + if (snprintf(fd_subpath, sizeof(fd_subpath), "%s/fd", pid_name) >= + (int)sizeof(fd_subpath)) + return false; + + fd_dirfd = openat(proc_dirfd, fd_subpath, + O_CLOEXEC | O_DIRECTORY | O_RDONLY); + if (fd_dirfd < 0) + return false; + + io_dir__init(&fd_dir, fd_dirfd); + while ((de = io_dir__readdir(&fd_dir)) != NULL) { + char target[32]; + ssize_t len; + + if (!isdigit((unsigned char)de->d_name[0])) + continue; + + len = readlinkat(fd_dir.dirfd, de->d_name, + target, sizeof(target) - 1); + if (len <= 0) + continue; + target[len] = '\0'; + + if (!strcmp(target, "/dev/kvm") || + !strncmp(target, "anon_inode:kvm-vm", 17)) { + found = true; + break; + } + } + + close(fd_dirfd); + return found; +} + +int perf_kvm_mmap_filter__discover_pids(struct intlist *pids) +{ + const char *proc_root = procfs__mountpoint(); + struct io_dirent64 *de; + struct io_dir proc_dir; + int proc_dirfd; + + if (!proc_root || !*proc_root) + proc_root = "/proc"; + + proc_dirfd = open(proc_root, O_CLOEXEC | O_DIRECTORY | O_RDONLY); + if (proc_dirfd < 0) + return -errno; + + io_dir__init(&proc_dir, proc_dirfd); + while ((de = io_dir__readdir(&proc_dir)) != NULL) { + char *endptr = NULL; + long pid; + + if (!isdigit((unsigned char)de->d_name[0])) + continue; + + pid = strtol(de->d_name, &endptr, 10); + if (!endptr || *endptr != '\0' || pid <= 0 || pid > INT_MAX) + continue; + + if (pid_has_kvm_fd(proc_dir.dirfd, de->d_name)) { + int err = intlist__add(pids, (int)pid); + + if (err && err != -EEXIST) { + close(proc_dirfd); + return err; + } + } + } + + close(proc_dirfd); + return 0; +} + +struct kvm_mmap_synth_ctx { + struct perf_tool tool; + const struct perf_tool *orig_tool; + perf_event__handler_t orig_process; +}; + +static bool is_linked_regular_file_mmap(const char *filename) +{ + struct stat st; + + if (!filename || filename[0] != '/' || filename[1] == '/') + return false; + if (!strncmp(filename, "/memfd:", 7) || !strncmp(filename, "/SYSV", 5)) + return false; + if (stat(filename, &st) != 0) + return false; + + return S_ISREG(st.st_mode) && st.st_nlink > 0; +} + +static int kvm_mmap_synth_cb(const struct perf_tool *tool, + union perf_event *event, + struct perf_sample *sample, + struct machine *machine) +{ + const struct kvm_mmap_synth_ctx *ctx = + container_of(tool, struct kvm_mmap_synth_ctx, tool); + const char *filename; + + /* + * Executable mappings are already synthesized by normal thread + * synthesis; only emit non-executable linked regular-file mappings. + */ + if (!(event->header.misc & PERF_RECORD_MISC_MMAP_DATA)) + return 0; + + if (event->header.type == PERF_RECORD_MMAP2) + filename = event->mmap2.filename; + else if (event->header.type == PERF_RECORD_MMAP) + filename = event->mmap.filename; + else + return 0; + + if (!is_linked_regular_file_mmap(filename)) + return 0; + + return ctx->orig_process(ctx->orig_tool, event, sample, machine); +} + +int perf_kvm_mmap_filter__synthesize_maps(const struct perf_tool *tool, + struct machine *machine, + perf_event__handler_t process) +{ + struct kvm_mmap_synth_ctx ctx = { + .orig_tool = tool, + .orig_process = process, + }; + struct intlist *pids; + struct int_node *pos; + union perf_event *event; + int err = 0; + + pids = intlist__new(NULL); + if (!pids) + return -ENOMEM; + + err = perf_kvm_mmap_filter__discover_pids(pids); + if (err || intlist__empty(pids)) { + intlist__delete(pids); + return 0; + } + + if (tool) + ctx.tool = *tool; + else + perf_tool__init(&ctx.tool, /*ordered_events=*/false); + + event = zalloc(sizeof(event->mmap2) + machine->id_hdr_size); + if (!event) { + intlist__delete(pids); + return -ENOMEM; + } + + intlist__for_each_entry(pos, pids) { + pid_t tgid = (pid_t)pos->i; + + err = perf_event__synthesize_mmap_events(&ctx.tool, event, + tgid, tgid, + kvm_mmap_synth_cb, + machine, + /*mmap_data=*/true); + if (err) + pr_debug("Failed to synthesize hypervisor data mmaps for pid %d\n", + (int)tgid); + err = 0; + } + + free(event); + intlist__delete(pids); + return err; +} diff --git a/tools/perf/util/kvm-mmap-filter.h b/tools/perf/util/kvm-mmap-filter.h new file mode 100644 index 000000000000..c269a862f7b2 --- /dev/null +++ b/tools/perf/util/kvm-mmap-filter.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef PERF_UTIL_KVM_MMAP_FILTER_H +#define PERF_UTIL_KVM_MMAP_FILTER_H + +#include "util/synthetic-events.h" + +struct intlist; +struct machine; +struct perf_tool; + +int perf_kvm_mmap_filter__discover_pids(struct intlist *pids); +int perf_kvm_mmap_filter__synthesize_maps(const struct perf_tool *tool, + struct machine *machine, + perf_event__handler_t process); + +#endif /* PERF_UTIL_KVM_MMAP_FILTER_H */ -- 2.56.1.915.g69d5ec7298-goog To capture non-executable file-backed mappings created after recording starts (including newly launched hypervisor processes) without flooding the perf ring buffer with system-wide anonymous data mappings, add the kvm_mmap_filter BPF skeleton and attach it via attr.mmap_bpf to a dedicated tracking dummy event in perf record --host-ip. The BPF program matches linked regular-file VMAs belonging to either discovered hypervisor PIDs or processes with active MMU notifier subscriptions (such as KVM), and gracefully falls back if the running kernel does not support attr.mmap_bpf. Signed-off-by: Ian Rogers --- tools/perf/builtin-record.c | 20 ++- tools/perf/util/Build | 2 + tools/perf/util/bpf_kvm_mmap.c | 120 ++++++++++++++++++ .../perf/util/bpf_skel/kvm_mmap_filter.bpf.c | 79 ++++++++++++ tools/perf/util/bpf_skel/vmlinux/vmlinux.h | 24 ++++ tools/perf/util/kvm-mmap-filter.h | 30 +++++ 6 files changed, 274 insertions(+), 1 deletion(-) create mode 100644 tools/perf/util/bpf_kvm_mmap.c create mode 100644 tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c diff --git a/tools/perf/builtin-record.c b/tools/perf/builtin-record.c index 5e11ccda8c6d..1807ac3d8cc8 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -937,7 +937,7 @@ static int record__config_tracking_events(struct record *rec) * delay of waiting or event synthesis. */ if (opts->target.initial_delay || target__has_cpu(&opts->target) || - perf_pmus__num_core_pmus() > 1) { + perf_pmus__num_core_pmus() > 1 || opts->sample_host_ip) { /* * User space tasks can migrate between CPUs, so when tracing * selected CPUs, sideband for all CPUs is still needed. @@ -949,6 +949,13 @@ static int record__config_tracking_events(struct record *rec) if (!evsel) return -ENOMEM; + if (opts->sample_host_ip && !list_empty(&evsel->bpf_filters)) { + evsel = evlist__add_aux_dummy(evlist, system_wide); + if (!evsel) + return -ENOMEM; + evlist__set_tracking_event(evlist, evsel); + } + /* * Enable the tracking event when the process is forked for * initial_delay, immediately for system wide. @@ -958,6 +965,9 @@ static int record__config_tracking_events(struct record *rec) evsel->core.attr.enable_on_exec = 1; else evsel->immediate = 1; + + if (opts->sample_host_ip && !opts->record_data_mmap) + perf_kvm_mmap_filter__prepare(evsel); } return 0; @@ -1378,6 +1388,8 @@ static int record__open(struct record *rec) if (evsel__open(pos, pos->core.cpus, pos->core.threads) < 0) { bool report_error = true; + if (perf_kvm_mmap_filter__fallback(pos, errno, opts->record_data_mmap)) + goto try_again; if (evsel__fallback(pos, &opts->target, errno, msg, sizeof(msg))) { if (verbose > 0) ui__warning("%s\n", msg); @@ -1474,6 +1486,11 @@ static int record__open(struct record *rec) goto out; } + if (perf_kvm_mmap_filter__apply()) { + rc = -1; + goto out; + } + rc = record__mmap(rec); if (rc) goto out; @@ -4431,6 +4448,7 @@ int cmd_record(int argc, const char **argv) err = __cmd_record(&record, argc, argv); out: + perf_kvm_mmap_filter__destroy(); record__free_thread_masks(rec, rec->nr_threads); rec->nr_threads = 0; symbol__exit(); diff --git a/tools/perf/util/Build b/tools/perf/util/Build index fd34879d45ba..e48edc11eb21 100644 --- a/tools/perf/util/Build +++ b/tools/perf/util/Build @@ -175,6 +175,7 @@ perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf_counter.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf_counter_cgroup.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf_ftrace.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf_off_cpu.o +perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf_kvm_mmap.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf-filter.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf-filter-flex.o perf-util-$(CONFIG_PERF_BPF_SKEL) += bpf-filter-bison.o @@ -451,6 +452,7 @@ $(OUTPUT)util/bpf_ftrace.o: $(SKEL_OUT)/func_latency.skel.h $(OUTPUT)util/bpf-filter.o: $(SKEL_OUT)/sample_filter.skel.h $(OUTPUT)util/bpf_kwork_top.o: $(SKEL_OUT)/kwork_top.skel.h $(OUTPUT)util/bpf_off_cpu.o: $(SKEL_OUT)/off_cpu.skel.h +$(OUTPUT)util/bpf_kvm_mmap.o: $(SKEL_OUT)/kvm_mmap_filter.skel.h $(OUTPUT)util/bpf-trace-summary.o: $(SKEL_OUT)/syscall_summary.skel.h $(OUTPUT)util/bpf_counter_cgroup.o: $(SKEL_OUT)/bperf_cgroup.skel.h $(OUTPUT)util/bpf_trace_augment.o: $(SKEL_OUT)/augmented_raw_syscalls.skel.h diff --git a/tools/perf/util/bpf_kvm_mmap.c b/tools/perf/util/bpf_kvm_mmap.c new file mode 100644 index 000000000000..ca96edc86777 --- /dev/null +++ b/tools/perf/util/bpf_kvm_mmap.c @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "util/kvm-mmap-filter.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "util/bpf-utils.h" +#include "util/cap.h" +#include "util/debug.h" +#include "util/evsel.h" +#include "util/intlist.h" + +#include "bpf_skel/kvm_mmap_filter.skel.h" + +#define FD(e, x, y) (*(int *)xyarray__entry((e)->core.fd, x, y)) + +static struct kvm_mmap_filter_bpf *skel; +static struct evsel *filter_evsel; + +int perf_kvm_mmap_filter__prepare(struct evsel *evsel) +{ + struct intlist *pids; + struct int_node *pos; + int map_fd; + + if (!evsel || skel) + return 0; + + if (!perf_cap__capable(CAP_BPF) && !perf_cap__capable(CAP_SYS_ADMIN)) { + pr_debug("Insufficient capabilities to load kvm_mmap_filter BPF skeleton\n"); + return 0; + } + + skel = kvm_mmap_filter_bpf__open_and_load(); + if (!skel) { + pr_debug("Failed to load kvm_mmap_filter BPF skeleton; runtime hypervisor data mmaps will not be filtered via BPF\n"); + return 0; + } + + map_fd = bpf_map__fd(skel->maps.hypervisor_pids); + pids = intlist__new(NULL); + if (pids) { + if (perf_kvm_mmap_filter__discover_pids(pids) == 0) { + intlist__for_each_entry(pos, pids) { + __u32 tgid = (__u32)pos->i; + __u8 one = 1; + + bpf_map_update_elem(map_fd, &tgid, &one, BPF_ANY); + } + } + intlist__delete(pids); + } + + filter_evsel = evsel; + evsel->core.attr.mmap_data = 1; + evsel->core.attr.mmap_bpf = 1; + return 0; +} + +bool perf_kvm_mmap_filter__fallback(struct evsel *evsel, int err, bool keep_mmap_data) +{ + if (!skel || evsel != filter_evsel || !evsel->core.attr.mmap_bpf) + return false; + + if (err != EINVAL && err != EOPNOTSUPP) + return false; + + pr_debug("Kernel does not support attr.mmap_bpf, disabling runtime BPF hypervisor mmap filter\n"); + evsel->core.attr.mmap_bpf = 0; + if (!keep_mmap_data) + evsel->core.attr.mmap_data = 0; + + perf_kvm_mmap_filter__destroy(); + return true; +} + +int perf_kvm_mmap_filter__apply(void) +{ + int prog_fd; + + if (!skel || !filter_evsel || !filter_evsel->core.fd) + return 0; + + prog_fd = bpf_program__fd(skel->progs.perf_kvm_mmap_filter); + if (prog_fd < 0) + return -EINVAL; + + for (int x = 0; x < xyarray__max_x(filter_evsel->core.fd); x++) { + for (int y = 0; y < xyarray__max_y(filter_evsel->core.fd); y++) { + int fd = FD(filter_evsel, x, y); + + if (fd < 0) + continue; + + if (ioctl(fd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) { + int ret = -errno; + + pr_err("Failed to attach hypervisor mmap BPF filter: %m\n"); + return ret; + } + } + } + + return 0; +} + +void perf_kvm_mmap_filter__destroy(void) +{ + kvm_mmap_filter_bpf__destroy(skel); + skel = NULL; + filter_evsel = NULL; +} diff --git a/tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c b/tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c new file mode 100644 index 000000000000..3f089412fa59 --- /dev/null +++ b/tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) +#include "vmlinux.h" +#include +#include + +#ifndef S_IFMT +#define S_IFMT 00170000 +#define S_IFREG 0100000 +#endif + +#define MAX_HYPERVISOR_PIDS 4096 + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __type(key, __u32); + __type(value, __u8); + __uint(max_entries, MAX_HYPERVISOR_PIDS); +} hypervisor_pids SEC(".maps"); + +void *bpf_cast_to_kern_ctx(void *) __ksym; + +/* + * Filter non-executable mmap_data events so only linked regular-file mappings + * (such as direct-access guest images and firmware ROMs) in hypervisor + * processes are emitted into the perf ring buffer. + */ +SEC("perf_event") +int perf_kvm_mmap_filter(void *ctx) +{ + struct bpf_perf_event_data_kern *kctx; + struct vm_area_struct *vma; + struct file *file; + struct inode *inode; + struct mm_struct *mm; + unsigned int nlink; + unsigned short mode; + __u32 tgid; + + kctx = bpf_cast_to_kern_ctx(ctx); + if (!bpf_core_field_exists(kctx->vma)) + return 0; + + vma = kctx->vma; + if (!vma) + return 0; + + file = BPF_CORE_READ(vma, vm_file); + if (!file) + return 0; + + inode = BPF_CORE_READ(file, f_inode); + if (!inode) + return 0; + + mode = BPF_CORE_READ(inode, i_mode); + if ((mode & S_IFMT) != S_IFREG) + return 0; + + nlink = BPF_CORE_READ(inode, __i_nlink); + if (nlink == 0) + return 0; + + tgid = bpf_get_current_pid_tgid() >> 32; + if (bpf_map_lookup_elem(&hypervisor_pids, &tgid)) + return 1; + + mm = BPF_CORE_READ(vma, vm_mm); + if (mm && bpf_core_field_exists(mm->notifier_subscriptions) && + BPF_CORE_READ(mm, notifier_subscriptions) != NULL) { + __u8 one = 1; + + bpf_map_update_elem(&hypervisor_pids, &tgid, &one, BPF_ANY); + return 1; + } + + return 0; +} + +char LICENSE[] SEC("license") = "Dual BSD/GPL"; diff --git a/tools/perf/util/bpf_skel/vmlinux/vmlinux.h b/tools/perf/util/bpf_skel/vmlinux/vmlinux.h index 94e42b022ab1..7d07c565762c 100644 --- a/tools/perf/util/bpf_skel/vmlinux/vmlinux.h +++ b/tools/perf/util/bpf_skel/vmlinux/vmlinux.h @@ -101,8 +101,31 @@ struct css_set { struct cgroup *dfl_cgrp; } __attribute__((preserve_access_index)); +struct mmu_notifier_subscriptions; + struct mm_struct { struct rw_semaphore mmap_lock; + struct mmu_notifier_subscriptions *notifier_subscriptions; +} __attribute__((preserve_access_index)); + +struct inode { + unsigned short i_mode; + union { + const unsigned int i_nlink; + unsigned int __i_nlink; + }; +} __attribute__((preserve_access_index)); + +struct file { + struct inode *f_inode; +} __attribute__((preserve_access_index)); + +struct vm_area_struct { + struct mm_struct *vm_mm; + union { + const unsigned long vm_flags; + }; + struct file *vm_file; } __attribute__((preserve_access_index)); struct task_struct { @@ -193,6 +216,7 @@ struct perf_event { struct bpf_perf_event_data_kern { struct perf_sample_data *data; struct perf_event *event; + struct vm_area_struct *vma; } __attribute__((preserve_access_index)); /* diff --git a/tools/perf/util/kvm-mmap-filter.h b/tools/perf/util/kvm-mmap-filter.h index c269a862f7b2..56b49442567d 100644 --- a/tools/perf/util/kvm-mmap-filter.h +++ b/tools/perf/util/kvm-mmap-filter.h @@ -2,8 +2,10 @@ #ifndef PERF_UTIL_KVM_MMAP_FILTER_H #define PERF_UTIL_KVM_MMAP_FILTER_H +#include #include "util/synthetic-events.h" +struct evsel; struct intlist; struct machine; struct perf_tool; @@ -13,4 +15,32 @@ int perf_kvm_mmap_filter__synthesize_maps(const struct perf_tool *tool, struct machine *machine, perf_event__handler_t process); +#ifdef HAVE_BPF_SKEL +int perf_kvm_mmap_filter__prepare(struct evsel *evsel); +bool perf_kvm_mmap_filter__fallback(struct evsel *evsel, int err, bool keep_mmap_data); +int perf_kvm_mmap_filter__apply(void); +void perf_kvm_mmap_filter__destroy(void); +#else +static inline int perf_kvm_mmap_filter__prepare(struct evsel *evsel __maybe_unused) +{ + return 0; +} + +static inline bool perf_kvm_mmap_filter__fallback(struct evsel *evsel __maybe_unused, + int err __maybe_unused, + bool keep_mmap_data __maybe_unused) +{ + return false; +} + +static inline int perf_kvm_mmap_filter__apply(void) +{ + return 0; +} + +static inline void perf_kvm_mmap_filter__destroy(void) +{ +} +#endif /* HAVE_BPF_SKEL */ + #endif /* PERF_UTIL_KVM_MMAP_FILTER_H */ -- 2.56.1.915.g69d5ec7298-goog Add the host_ip term to the BPF sample filter lexer, sample flag validation, sample-filter.h / sample_filter.bpf.c (using 1ULL shifts for sample bit checks), and vmlinux.h, and extend record_bpf_filter.sh to verify host_ip filter sample-flag validation. Signed-off-by: Ian Rogers --- tools/perf/tests/shell/record_bpf_filter.sh | 8 ++++++++ tools/perf/util/bpf-filter.c | 3 ++- tools/perf/util/bpf-filter.l | 1 + tools/perf/util/bpf_skel/sample-filter.h | 3 ++- tools/perf/util/bpf_skel/sample_filter.bpf.c | 9 +++++++-- tools/perf/util/bpf_skel/vmlinux/vmlinux.h | 1 + 6 files changed, 21 insertions(+), 4 deletions(-) diff --git a/tools/perf/tests/shell/record_bpf_filter.sh b/tools/perf/tests/shell/record_bpf_filter.sh index 383574cb3bd3..5c898b52b263 100755 --- a/tools/perf/tests/shell/record_bpf_filter.sh +++ b/tools/perf/tests/shell/record_bpf_filter.sh @@ -113,6 +113,14 @@ test_bpf_filter_group() { return fi + if ! perf record -e task-clock --filter 'period > 0 || host_ip > 0' \ + -o /dev/null true 2>&1 | grep -q PERF_SAMPLE_HOST_IP + then + echo "Group bpf-filter test [Failed forbidden HOST_IP]" + err=1 + return + fi + echo "Group bpf-filter test [Success]" } diff --git a/tools/perf/util/bpf-filter.c b/tools/perf/util/bpf-filter.c index 72e83ac1d6a4..698fcd7c2d09 100644 --- a/tools/perf/util/bpf-filter.c +++ b/tools/perf/util/bpf-filter.c @@ -104,6 +104,7 @@ static const struct perf_sample_info { PERF_SAMPLE_TYPE(CODE_PAGE_SIZE, "--code-page-size"), PERF_SAMPLE_TYPE(DATA_PAGE_SIZE, "--data-page-size"), PERF_SAMPLE_TYPE(CGROUP, "--all-cgroups"), + PERF_SAMPLE_TYPE(HOST_IP, "--host-ip"), }; static int get_pinned_fd(const char *name); @@ -124,7 +125,7 @@ static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * const struct perf_sample_info *info; if (expr->term >= PBF_TERM_SAMPLE_START && expr->term <= PBF_TERM_SAMPLE_END && - (evsel->core.attr.sample_type & (1 << (expr->term - PBF_TERM_SAMPLE_START)))) + (evsel->core.attr.sample_type & (1ULL << (expr->term - PBF_TERM_SAMPLE_START)))) return 0; if (expr->term == PBF_TERM_UID || expr->term == PBF_TERM_GID) { diff --git a/tools/perf/util/bpf-filter.l b/tools/perf/util/bpf-filter.l index 1be9df6550fc..ade6d88bb964 100644 --- a/tools/perf/util/bpf-filter.l +++ b/tools/perf/util/bpf-filter.l @@ -86,6 +86,7 @@ ident [_a-zA-Z][_a-zA-Z0-9]+ {space} { } ip { return sample(PBF_TERM_IP); } +host_ip { return sample(PBF_TERM_HOST_IP); } id { return sample(PBF_TERM_ID); } tid { return sample(PBF_TERM_TID); } pid { return sample_part(PBF_TERM_TID, 1); } diff --git a/tools/perf/util/bpf_skel/sample-filter.h b/tools/perf/util/bpf_skel/sample-filter.h index 683fec85e71e..04d0314e8f53 100644 --- a/tools/perf/util/bpf_skel/sample-filter.h +++ b/tools/perf/util/bpf_skel/sample-filter.h @@ -49,7 +49,8 @@ enum perf_bpf_filter_term { PBF_TERM_DATA_PAGE_SIZE = PBF_TERM_SAMPLE_START + 22, /* SAMPLE_DATA_PAGE_SIZE = 1U << 22 */ PBF_TERM_CODE_PAGE_SIZE = PBF_TERM_SAMPLE_START + 23, /* SAMPLE_CODE_PAGE_SIZE = 1U << 23 */ PBF_TERM_WEIGHT_STRUCT = PBF_TERM_SAMPLE_START + 24, /* SAMPLE_WEIGHT_STRUCT = 1U << 24 */ - PBF_TERM_SAMPLE_END = PBF_TERM_WEIGHT_STRUCT, + PBF_TERM_HOST_IP = PBF_TERM_SAMPLE_START + 25, /* SAMPLE_HOST_IP = 1U << 25 */ + PBF_TERM_SAMPLE_END = PBF_TERM_HOST_IP, /* Terms computed from BPF helpers. */ PBF_TERM_UID, PBF_TERM_GID, diff --git a/tools/perf/util/bpf_skel/sample_filter.bpf.c b/tools/perf/util/bpf_skel/sample_filter.bpf.c index e5666d4c1722..c22d9c867c7e 100644 --- a/tools/perf/util/bpf_skel/sample_filter.bpf.c +++ b/tools/perf/util/bpf_skel/sample_filter.bpf.c @@ -80,7 +80,7 @@ static inline __u64 perf_get_sample(struct bpf_perf_event_data_kern *kctx, return 0; #define BUILD_CHECK_SAMPLE(x) \ - _Static_assert((1 << (PBF_TERM_##x - PBF_TERM_SAMPLE_START)) == PERF_SAMPLE_##x, \ + _Static_assert((1ULL << (PBF_TERM_##x - PBF_TERM_SAMPLE_START)) == PERF_SAMPLE_##x, \ "Mismatched PBF term to sample bit " #x) BUILD_CHECK_SAMPLE(IP); BUILD_CHECK_SAMPLE(TID); @@ -97,16 +97,21 @@ static inline __u64 perf_get_sample(struct bpf_perf_event_data_kern *kctx, BUILD_CHECK_SAMPLE(DATA_PAGE_SIZE); BUILD_CHECK_SAMPLE(CODE_PAGE_SIZE); BUILD_CHECK_SAMPLE(WEIGHT_STRUCT); + BUILD_CHECK_SAMPLE(HOST_IP); #undef BUILD_CHECK_SAMPLE /* For sample terms check the sample bit is set. */ if (entry->term >= PBF_TERM_SAMPLE_START && entry->term <= PBF_TERM_SAMPLE_END && - (data->sample_flags & (1 << (entry->term - PBF_TERM_SAMPLE_START))) == 0) + (data->sample_flags & (1ULL << (entry->term - PBF_TERM_SAMPLE_START))) == 0) return 0; switch (entry->term) { case PBF_TERM_IP: return kctx->data->ip; + case PBF_TERM_HOST_IP: + if (bpf_core_field_exists(kctx->data->host_ip)) + return kctx->data->host_ip; + return 0; case PBF_TERM_ID: return kctx->data->id; case PBF_TERM_TID: diff --git a/tools/perf/util/bpf_skel/vmlinux/vmlinux.h b/tools/perf/util/bpf_skel/vmlinux/vmlinux.h index 7d07c565762c..2d7659d4cb7e 100644 --- a/tools/perf/util/bpf_skel/vmlinux/vmlinux.h +++ b/tools/perf/util/bpf_skel/vmlinux/vmlinux.h @@ -206,6 +206,7 @@ struct perf_sample_data { u64 cgroup; u64 data_page_size; u64 code_page_size; + u64 host_ip; } __attribute__((__aligned__(64))) __attribute__((preserve_access_index)); struct perf_event { -- 2.56.1.915.g69d5ec7298-goog Include PERF_SAMPLE_HOST_IP in ASLR_SAMPLE_MASK and remap sampled host_ip addresses against the host machine in aslr_tool__process_sample() so anonymized perf.data files do not leak raw host hypervisor virtual addresses. Signed-off-by: Ian Rogers --- tools/perf/util/aslr.c | 32 ++++++++++++++++++++++++++++++++ tools/perf/util/aslr.h | 3 ++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/tools/perf/util/aslr.c b/tools/perf/util/aslr.c index e365f807b021..ec2c0989e19d 100644 --- a/tools/perf/util/aslr.c +++ b/tools/perf/util/aslr.c @@ -1109,6 +1109,38 @@ static int aslr_tool__process_sample(const struct perf_tool *tool, if (orig_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) COPY_U64(); /* code_page_size */ + if (orig_sample_type & PERF_SAMPLE_HOST_IP) { + u64 remapped = 0; + + if (CHECK_BOUNDS(1, 1)) { + ret = -EFAULT; + goto out_put; + } + if (sample->host_ip) { + struct machine *host_machine = &aslr->machines.host; + struct thread *host_thread; + u8 host_cpumode = PERF_RECORD_MISC_USER; + + if (aslr_tool__preload_kernel_maps(host_machine) < 0) { + ret = -ENOMEM; + goto out_put; + } + host_thread = machine__findnew_thread(host_machine, sample->pid, + sample->tid); + if (!host_thread) { + ret = -ENOMEM; + goto out_put; + } + if (machine__kernel_ip(host_machine, sample->host_ip)) + host_cpumode = PERF_RECORD_MISC_KERNEL; + remapped = aslr_tool__remap_address(aslr, host_thread, + host_cpumode, sample->host_ip); + thread__put(host_thread); + } + out_array[j++] = remapped; + i++; + } + if (orig_sample_type & PERF_SAMPLE_AUX) { u64 size; diff --git a/tools/perf/util/aslr.h b/tools/perf/util/aslr.h index 9cc14f0263db..8850511a4a43 100644 --- a/tools/perf/util/aslr.h +++ b/tools/perf/util/aslr.h @@ -26,7 +26,8 @@ PERF_SAMPLE_CGROUP | \ PERF_SAMPLE_DATA_PAGE_SIZE | \ PERF_SAMPLE_CODE_PAGE_SIZE | \ - PERF_SAMPLE_AUX) + PERF_SAMPLE_AUX | \ + PERF_SAMPLE_HOST_IP) struct perf_session; struct perf_tool; -- 2.56.1.915.g69d5ec7298-goog Add a dedicated host-ip-sym C test suite covering: - Automatic guest-to-host symbolization fallback across non-executable (PROT_READ) file-backed host MMAP2 mappings with non-zero pgoff, default host-only (!perf_guest) mode, perf kvm --guest (!perf_host) mode, guest symbol precedence when guest mappings are present, and build_id__mark_dso_hit() DSO hit marking via sample->host_ip. - Histogram collapsing, sorting, and formatting for host_dso, host_sym, and host_ip sort keys. - ASLR address anonymization of sampled host_ip values in aslr_tool. Signed-off-by: Ian Rogers --- tools/perf/tests/Build | 1 + tools/perf/tests/builtin-test.c | 1 + tools/perf/tests/host-ip-sym.c | 691 ++++++++++++++++++++++++++++++++ tools/perf/tests/tests.h | 1 + 4 files changed, 694 insertions(+) create mode 100644 tools/perf/tests/host-ip-sym.c diff --git a/tools/perf/tests/Build b/tools/perf/tests/Build index 58858f3d2bf9..ace316b165a1 100644 --- a/tools/perf/tests/Build +++ b/tools/perf/tests/Build @@ -73,6 +73,7 @@ perf-test-y += hwmon_pmu.o perf-test-y += tool_pmu.o perf-test-y += subcmd-help.o perf-test-y += kallsyms-split.o +perf-test-y += host-ip-sym.o ifeq ($(SRCARCH),$(filter $(SRCARCH),x86 arm arm64 powerpc riscv)) perf-test-$(CONFIG_DWARF_UNWIND) += dwarf-unwind.o diff --git a/tools/perf/tests/builtin-test.c b/tools/perf/tests/builtin-test.c index 0b8897fd42ca..f7388c5acf2b 100644 --- a/tools/perf/tests/builtin-test.c +++ b/tools/perf/tests/builtin-test.c @@ -177,6 +177,7 @@ static struct test_suite *generic_tests[] = { &suite__util, &suite__subcmd_help, &suite__kallsyms_split, + &suite__host_ip_sym, NULL, }; diff --git a/tools/perf/tests/host-ip-sym.c b/tools/perf/tests/host-ip-sym.c new file mode 100644 index 000000000000..b2acf08446e9 --- /dev/null +++ b/tools/perf/tests/host-ip-sym.c @@ -0,0 +1,691 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "perf.h" +#include "tests/tests.h" +#include "util/addr_location.h" +#include "util/aslr.h" +#include "util/build-id.h" +#include "util/debug.h" +#include "util/dso.h" +#include "util/event.h" +#include "util/evlist.h" +#include "util/evsel.h" +#include "util/hist.h" +#include "util/machine.h" +#include "util/map.h" +#include "util/parse-events.h" +#include "util/sample.h" +#include "util/sort.h" +#include "util/symbol.h" +#include "util/synthetic-events.h" +#include "util/thread.h" +#include "util/tool.h" + +#define TEST_HV_PID 4242 +#define TEST_VCPU_TID 4243 +#define TEST_DAX_START 0x7f0000200000ULL +#define TEST_DAX_LEN 0x10000ULL +#define TEST_DAX_PGOFF 0x4000ULL +#define TEST_DAX_SYM1_OFF 0x4100ULL +#define TEST_DAX_SYM2_OFF 0x4200ULL +#define TEST_DAX_SYM_LEN 0x80ULL +#define TEST_HOST_IP1 (TEST_DAX_START + (TEST_DAX_SYM1_OFF - TEST_DAX_PGOFF) + 0x20ULL) +#define TEST_HOST_IP2 (TEST_DAX_START + (TEST_DAX_SYM2_OFF - TEST_DAX_PGOFF) + 0x20ULL) +#define TEST_GUEST_IP 0x401120ULL + +static void cleanup_machines(struct machines *machines) +{ + struct rb_node *nd; + + while ((nd = rb_first_cached(&machines->guests)) != NULL) { + struct machine *guest = rb_entry(nd, struct machine, rb_node); + + rb_erase_cached(nd, &machines->guests); + machine__delete(guest); + } + machines__exit(machines); +} + +static void delete_all_hist_entries(struct hists *hists) +{ + struct rb_root_cached *root_in; + struct rb_root_cached *root_out = &hists->entries; + struct rb_node *node; + + if (hists__has(hists, need_collapse)) + root_in = &hists->entries_collapsed; + else + root_in = hists->entries_in; + + while (!RB_EMPTY_ROOT(&root_out->rb_root)) { + struct hist_entry *he; + + node = rb_first_cached(root_out); + he = rb_entry(node, struct hist_entry, rb_node); + rb_erase_cached(node, root_out); + rb_erase_cached(&he->rb_node_in, root_in); + hist_entry__delete(he); + } +} + +static int setup_host_dax_mapping(struct machine *host_machine) +{ + struct thread *thread; + struct dso *dso; + struct symbol *sym1, *sym2; + struct perf_sample mmap_sample = { + .pid = TEST_HV_PID, + .tid = TEST_HV_PID, + .cpumode = PERF_RECORD_MISC_USER, + }; + union perf_event mmap2_ev = { + .mmap2 = { + .header = { + .type = PERF_RECORD_MMAP2, + .misc = PERF_RECORD_MISC_USER | PERF_RECORD_MISC_MMAP_DATA, + .size = sizeof(struct perf_record_mmap2), + }, + .pid = TEST_HV_PID, + .tid = TEST_HV_PID, + .start = TEST_DAX_START, + .len = TEST_DAX_LEN, + .pgoff = TEST_DAX_PGOFF, + .maj = 8, + .min = 1, + .ino = 123456, + .ino_generation = 1, + .prot = PROT_READ, + .flags = MAP_SHARED, + }, + }; + + snprintf(mmap2_ev.mmap2.filename, sizeof(mmap2_ev.mmap2.filename), + "/mnt/dax/guest_app"); + + thread = machine__findnew_thread(host_machine, TEST_HV_PID, TEST_VCPU_TID); + if (!thread) + return -ENOMEM; + thread__set_comm(thread, "qemu-vcpu", 0); + thread__put(thread); + + if (machine__process_mmap2_event(host_machine, &mmap2_ev, &mmap_sample) < 0) + return -1; + + dso = machine__findnew_dso(host_machine, "/mnt/dax/guest_app"); + if (!dso) + return -ENOMEM; + + dso__set_loaded(dso); + + sym1 = symbol__new(TEST_DAX_SYM1_OFF, TEST_DAX_SYM_LEN, + STB_GLOBAL, STT_FUNC, "dax_guest_hot_fn"); + sym2 = symbol__new(TEST_DAX_SYM2_OFF, TEST_DAX_SYM_LEN, + STB_GLOBAL, STT_FUNC, "dax_guest_cold_fn"); + if (!sym1 || !sym2) { + if (sym1) + symbol__delete(sym1); + if (sym2) + symbol__delete(sym2); + dso__put(dso); + return -ENOMEM; + } + + symbols__insert(dso__symbols(dso), sym1); + symbols__insert(dso__symbols(dso), sym2); + dso__put(dso); + return 0; +} + +static int test__host_ip_fallback(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + struct machines machines = { 0 }; + struct machine *guest_machine; + struct addr_location al; + struct dso *guest_dso; + struct symbol *guest_sym; + bool saved_host = perf_host; + bool saved_guest = perf_guest; + int ret = TEST_FAIL; + struct perf_sample sample = { + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .ip = TEST_GUEST_IP, + .host_ip = TEST_HOST_IP1, + .period = 100, + .cpumode = PERF_RECORD_MISC_GUEST_USER, + }; + struct perf_sample guest_mmap_sample = { + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .cpumode = PERF_RECORD_MISC_GUEST_USER, + }; + union perf_event guest_mmap_ev = { + .mmap = { + .header = { + .type = PERF_RECORD_MMAP, + .misc = PERF_RECORD_MISC_GUEST_USER, + .size = sizeof(struct perf_record_mmap), + }, + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .start = 0x401000ULL, + .len = 0x1000ULL, + .pgoff = 0, + }, + }; + + if (machines__init(&machines, /*session=*/NULL)) + return TEST_FAIL; + + perf_host = true; + perf_guest = true; + + if (setup_host_dax_mapping(&machines.host)) + goto out_machines; + + guest_machine = machines__find_guest(&machines, TEST_HV_PID); + if (!guest_machine) + goto out_machines; + + addr_location__init(&al); + + /* + * 1. Guest sample with no guest symbols automatically falls back to + * the non-executable DAX mapping on machines.host. + */ + if (machine__resolve(guest_machine, &al, &sample) < 0) + goto out_al; + + if (!al.map || !al.sym || strcmp(al.sym->name, "dax_guest_hot_fn") != 0) { + pr_debug("Expected fallback sym dax_guest_hot_fn, got %s\n", + al.sym ? al.sym->name : ""); + goto out_al; + } + if (al.addr != TEST_DAX_SYM1_OFF + 0x20ULL || al.level != 'u') { + pr_debug("Unexpected fallback addr=%#" PRIx64 " level=%c\n", + al.addr, al.level); + goto out_al; + } + if (!al.host_map || !al.host_sym || + strcmp(al.host_sym->name, "dax_guest_hot_fn") != 0 || + al.host_addr != TEST_DAX_SYM1_OFF + 0x20ULL || + al.raw_host_ip != TEST_HOST_IP1) { + pr_debug("Explicit host_map/host_sym mismatch\n"); + goto out_al; + } + addr_location__exit(&al); + + /* + * 2. In 'perf kvm --guest' mode (perf_host == false, perf_guest == true), + * host_ip lookup on machines.host must still succeed without setting + * HIST_FILTER__HOST. + */ + perf_host = false; + perf_guest = true; + addr_location__init(&al); + if (machine__resolve(guest_machine, &al, &sample) < 0) + goto out_al; + + if (al.filtered != 0 || !al.sym || + strcmp(al.sym->name, "dax_guest_hot_fn") != 0) { + pr_debug("perf kvm --guest mode failed: filtered=%#x sym=%s\n", + al.filtered, al.sym ? al.sym->name : ""); + goto out_al; + } + addr_location__exit(&al); + perf_host = true; + + /* + * 2b. In default perf report/script mode (perf_host == true, + * perf_guest == false), resolving a guest sample via machines.host + * must clear HIST_FILTER__GUEST when falling back to host_map. + */ + perf_host = true; + perf_guest = false; + addr_location__init(&al); + if (machine__resolve(&machines.host, &al, &sample) < 0) + goto out_al; + + if (al.filtered != 0 || al.level != 'u' || !al.sym || + strcmp(al.sym->name, "dax_guest_hot_fn") != 0) { + pr_debug("default host-only mode failed: filtered=%#x level=%c sym=%s\n", + al.filtered, al.level, al.sym ? al.sym->name : ""); + goto out_al; + } + addr_location__exit(&al); + perf_guest = true; + + /* + * 2c. build_id__mark_dso_hit() must mark the host DSO hit via + * sample.host_ip for guest samples so perf record --host-ip + * caches its build-id. + */ + { + struct perf_event_attr attr = { + .type = PERF_TYPE_HARDWARE, + .config = PERF_COUNT_HW_CPU_CYCLES, + .sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | + PERF_SAMPLE_HOST_IP, + }; + union perf_event sample_ev = { + .header = { + .type = PERF_RECORD_SAMPLE, + .misc = PERF_RECORD_MISC_GUEST_USER, + .size = sizeof(struct perf_event_header), + }, + }; + struct evsel *evsel = evsel__new(&attr); + struct dso *host_dso = machine__findnew_dso(&machines.host, + "/mnt/dax/guest_app"); + int hit_err; + + if (!evsel || !host_dso) { + evsel__put(evsel); + dso__put(host_dso); + goto out_machines; + } + if (dso__hit(host_dso)) { + pr_debug("host DSO unexpectedly marked hit before build_id__mark_dso_hit\n"); + evsel__put(evsel); + dso__put(host_dso); + goto out_machines; + } + sample.evsel = evsel; + hit_err = build_id__mark_dso_hit(/*tool=*/NULL, &sample_ev, + &sample, guest_machine); + sample.evsel = NULL; + if (hit_err < 0 || !dso__hit(host_dso)) { + pr_debug("build_id__mark_dso_hit failed to mark host DSO hit\n"); + evsel__put(evsel); + dso__put(host_dso); + goto out_machines; + } + evsel__put(evsel); + dso__put(host_dso); + } + + /* + * 3. When the guest machine DOES have a symbol for sample.ip, guest + * symbolization takes precedence for al.sym while al.host_sym still + * exposes the host symbol. + */ + snprintf(guest_mmap_ev.mmap.filename, sizeof(guest_mmap_ev.mmap.filename), + "/bin/guest_native"); + if (machine__process_mmap_event(guest_machine, &guest_mmap_ev, + &guest_mmap_sample) < 0) + goto out_machines; + + guest_dso = machine__findnew_dso(guest_machine, "/bin/guest_native"); + if (!guest_dso) + goto out_machines; + dso__set_loaded(guest_dso); + guest_sym = symbol__new(0x100ULL, 0x80ULL, STB_GLOBAL, STT_FUNC, + "guest_native_fn"); + if (!guest_sym) { + dso__put(guest_dso); + goto out_machines; + } + symbols__insert(dso__symbols(guest_dso), guest_sym); + dso__put(guest_dso); + + addr_location__init(&al); + if (machine__resolve(guest_machine, &al, &sample) < 0) + goto out_al; + + if (!al.sym || strcmp(al.sym->name, "guest_native_fn") != 0 || + !al.host_sym || strcmp(al.host_sym->name, "dax_guest_hot_fn") != 0) { + pr_debug("Guest symbol precedence failed: sym=%s host_sym=%s\n", + al.sym ? al.sym->name : "", + al.host_sym ? al.host_sym->name : ""); + goto out_al; + } + + ret = TEST_OK; +out_al: + addr_location__exit(&al); +out_machines: + perf_host = saved_host; + perf_guest = saved_guest; + cleanup_machines(&machines); + return ret; +} + +static int add_guest_hist_sample(struct evsel *evsel, struct machine *guest_machine, + u64 guest_ip, u64 host_ip) +{ + struct addr_location al; + struct perf_sample sample = { + .evsel = evsel, + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .cpu = 0, + .ip = guest_ip, + .host_ip = host_ip, + .period = 100, + .cpumode = PERF_RECORD_MISC_GUEST_USER, + }; + struct hist_entry_iter iter = { + .sample = &sample, + .ops = &hist_iter_normal, + .hide_unresolved = false, + }; + int err; + + addr_location__init(&al); + err = machine__resolve(guest_machine, &al, &sample); + if (!err) + err = hist_entry_iter__add(&iter, &al, sysctl_perf_event_max_stack, NULL); + addr_location__exit(&al); + return err; +} + +static int test__host_ip_hist_sort(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + struct machines machines = { 0 }; + struct machine *guest_machine; + struct evlist *evlist; + struct evsel *evsel; + struct hists *hists; + struct rb_node *node; + struct hist_entry *he; + char buf[512]; + struct perf_hpp hpp = { + .buf = buf, + .size = sizeof(buf), + }; + bool saved_host = perf_host; + bool saved_guest = perf_guest; + int ret = TEST_FAIL; + + evlist = evlist__new(); + if (!evlist) + return TEST_FAIL; + + if (parse_event(evlist, "cpu-clock")) + goto out_evlist; + + if (machines__init(&machines, /*session=*/NULL)) + goto out_evlist; + + perf_host = true; + perf_guest = true; + + if (setup_host_dax_mapping(&machines.host)) + goto out_machines; + + guest_machine = machines__find_guest(&machines, TEST_HV_PID); + if (!guest_machine) + goto out_machines; + + field_order = NULL; + sort_order = "host_dso,host_sym,host_ip"; + if (setup_sorting(/*evlist=*/NULL, machines.host.env) < 0) + goto out_machines; + perf_hpp__init(); + + evsel = evlist__first(evlist); + hists = evsel__hists(evsel); + + if (add_guest_hist_sample(evsel, guest_machine, TEST_GUEST_IP, TEST_HOST_IP1) || + add_guest_hist_sample(evsel, guest_machine, TEST_GUEST_IP + 4, TEST_HOST_IP1) || + add_guest_hist_sample(evsel, guest_machine, TEST_GUEST_IP + 0x100, TEST_HOST_IP2)) + goto out_hists; + + hists__collapse_resort(hists, NULL); + evsel__output_resort(evsel, NULL); + + node = rb_first_cached(&hists->entries); + if (!node) + goto out_hists; + + he = rb_entry(node, struct hist_entry, rb_node); + if (he->stat.period != 200 || !he->host_ms.sym || + strcmp(he->host_ms.sym->name, "dax_guest_hot_fn") != 0 || + !he->host_ms.map || + strcmp(dso__short_name(map__dso(he->host_ms.map)), "guest_app") != 0 || + map__unmap_ip(he->host_ms.map, he->host_ip) != TEST_HOST_IP1) { + pr_debug("Unexpected top hist_entry for host sort keys\n"); + goto out_hists; + } + + hists__calc_col_len(hists, he); + { + struct perf_hpp_fmt *fmt; + + buf[0] = '\0'; + hists__for_each_format(hists, fmt) { + int printed = fmt->entry(fmt, &hpp, he); + + if (printed > 0) + advance_hpp(&hpp, printed); + } + } + if (!strstr(buf, "guest_app") || !strstr(buf, "dax_guest_hot_fn") || + !strstr(buf, "7f0000200120")) { + pr_debug("Formatted hist_entry missing expected host fields: '%s'\n", buf); + goto out_hists; + } + + node = rb_next(node); + if (!node) + goto out_hists; + he = rb_entry(node, struct hist_entry, rb_node); + if (he->stat.period != 100 || !he->host_ms.sym || + strcmp(he->host_ms.sym->name, "dax_guest_cold_fn") != 0) { + pr_debug("Unexpected second hist_entry for host sort keys\n"); + goto out_hists; + } + + /* + * Verify collapsing a sample with host_ip == 0 into an existing + * comm-sorted entry preserves valid host_ms.map/sym references. + */ + delete_all_hist_entries(hists); + reset_output_field(); + sort_order = "comm"; + if (setup_sorting(/*evlist=*/NULL, machines.host.env) < 0) + goto out_machines; + perf_hpp__init(); + + if (add_guest_hist_sample(evsel, guest_machine, TEST_GUEST_IP, TEST_HOST_IP1) || + add_guest_hist_sample(evsel, guest_machine, TEST_GUEST_IP + 4, 0)) + goto out_hists; + + hists__collapse_resort(hists, NULL); + evsel__output_resort(evsel, NULL); + node = rb_first_cached(&hists->entries); + if (!node) + goto out_hists; + he = rb_entry(node, struct hist_entry, rb_node); + if (he->stat.period != 200 || !he->host_ms.map || !he->host_ms.sym || + strcmp(he->host_ms.sym->name, "dax_guest_hot_fn") != 0) { + pr_debug("Collapsing sample with host_ip=0 corrupted host_ms\n"); + goto out_hists; + } + + ret = TEST_OK; +out_hists: + delete_all_hist_entries(hists); + reset_output_field(); + sort_order = NULL; +out_machines: + perf_host = saved_host; + perf_guest = saved_guest; + cleanup_machines(&machines); +out_evlist: + evlist__put(evlist); + return ret; +} + +struct aslr_capture_tool { + struct perf_tool tool; + u64 remapped_host_ip[2]; + int count; +}; + +static int capture_sample_cb(const struct perf_tool *tool, + union perf_event *event __maybe_unused, + struct perf_sample *sample, + struct machine *machine __maybe_unused) +{ + struct aslr_capture_tool *cap = + container_of(tool, struct aslr_capture_tool, tool); + + if (cap->count < 2) + cap->remapped_host_ip[cap->count] = sample->host_ip; + cap->count++; + return 0; +} + +static int nop_mmap2_cb(const struct perf_tool *tool __maybe_unused, + union perf_event *event __maybe_unused, + struct perf_sample *sample __maybe_unused, + struct machine *machine __maybe_unused) +{ + return 0; +} + +static int test__host_ip_aslr(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + struct aslr_capture_tool cap = { .count = 0 }; + struct perf_tool *aslr; + struct machines machines = { 0 }; + struct machine *guest_machine; + struct perf_event_attr attr = { + .type = PERF_TYPE_HARDWARE, + .config = PERF_COUNT_HW_CPU_CYCLES, + .sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_HOST_IP, + }; + struct evsel *evsel = NULL; + union perf_event *ev = NULL; + union perf_event mmap2_ev = { + .mmap2 = { + .header = { + .type = PERF_RECORD_MMAP2, + .misc = PERF_RECORD_MISC_USER | PERF_RECORD_MISC_MMAP_DATA, + .size = sizeof(struct perf_record_mmap2), + }, + .pid = TEST_HV_PID, + .tid = TEST_HV_PID, + .start = TEST_DAX_START, + .len = TEST_DAX_LEN, + .pgoff = TEST_DAX_PGOFF, + .prot = PROT_READ, + .flags = MAP_SHARED, + }, + }; + struct perf_sample mmap_sample = { + .pid = TEST_HV_PID, + .tid = TEST_HV_PID, + .cpumode = PERF_RECORD_MISC_USER, + }; + struct perf_sample s1 = { + .ip = TEST_GUEST_IP, + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .host_ip = TEST_HOST_IP1, + .cpumode = PERF_RECORD_MISC_GUEST_USER, + }; + struct perf_sample s2 = { + .ip = TEST_GUEST_IP, + .pid = TEST_HV_PID, + .tid = TEST_VCPU_TID, + .host_ip = 0, + .cpumode = PERF_RECORD_MISC_GUEST_USER, + }; + size_t sz; + int ret = TEST_FAIL; + + snprintf(mmap2_ev.mmap2.filename, sizeof(mmap2_ev.mmap2.filename), + "/mnt/dax/guest_app"); + + if (machines__init(&machines, /*session=*/NULL)) + return TEST_FAIL; + + guest_machine = machines__find_guest(&machines, TEST_HV_PID); + if (!guest_machine) + goto out_machines; + + perf_tool__init(&cap.tool, /*ordered_events=*/false); + cap.tool.sample = capture_sample_cb; + cap.tool.mmap2 = nop_mmap2_cb; + + aslr = aslr_tool__new(&cap.tool); + if (!aslr) + goto out_machines; + + evsel = evsel__new(&attr); + if (!evsel) + goto out_aslr; + evsel->sample_size = __evsel__sample_size(attr.sample_type); + + if (aslr->mmap2(aslr, &mmap2_ev, &mmap_sample, &machines.host) < 0) + goto out_evsel; + + sz = perf_event__sample_event_size(&s1, attr.sample_type, 0, 0); + ev = calloc(1, sz); + if (!ev) + goto out_evsel; + + ev->header.type = PERF_RECORD_SAMPLE; + ev->header.misc = PERF_RECORD_MISC_GUEST_USER; + ev->header.size = sz; + + s1.evsel = evsel; + if (perf_event__synthesize_sample(ev, attr.sample_type, 0, 0, &s1)) + goto out_ev; + if (aslr->sample(aslr, ev, &s1, guest_machine) < 0) + goto out_ev; + + s2.evsel = evsel; + if (perf_event__synthesize_sample(ev, attr.sample_type, 0, 0, &s2)) + goto out_ev; + if (aslr->sample(aslr, ev, &s2, guest_machine) < 0) + goto out_ev; + + if (cap.count != 2 || cap.remapped_host_ip[0] == 0 || + cap.remapped_host_ip[0] == TEST_HOST_IP1 || + (cap.remapped_host_ip[0] & 0xfffULL) != (TEST_HOST_IP1 & 0xfffULL) || + cap.remapped_host_ip[1] != 0) { + pr_debug("Unexpected ASLR host_ip remapping: %#" PRIx64 ", %#" PRIx64 "\n", + cap.remapped_host_ip[0], cap.remapped_host_ip[1]); + goto out_ev; + } + + ret = TEST_OK; +out_ev: + free(ev); +out_evsel: + evsel__put(evsel); +out_aslr: + aslr_tool__delete(aslr); +out_machines: + cleanup_machines(&machines); + return ret; +} + +static struct test_case tests__host_ip_sym[] = { + TEST_CASE("Guest fallback symbolization via host IP", host_ip_fallback), + TEST_CASE("Histogram sorting and formatting for host IP keys", host_ip_hist_sort), + TEST_CASE("ASLR anonymization of sampled host IP", host_ip_aslr), + { .name = NULL, } +}; + +struct test_suite suite__host_ip_sym = { + .desc = "PERF_SAMPLE_HOST_IP symbolization and sorting", + .test_cases = tests__host_ip_sym, +}; diff --git a/tools/perf/tests/tests.h b/tools/perf/tests/tests.h index 20ae3609892b..3dce04124d6c 100644 --- a/tools/perf/tests/tests.h +++ b/tools/perf/tests/tests.h @@ -201,6 +201,7 @@ DECLARE_SUITE(util); DECLARE_SUITE(uncore_event_sorting); DECLARE_SUITE(subcmd_help); DECLARE_SUITE(kallsyms_split); +DECLARE_SUITE(host_ip_sym); /* * PowerPC and S390 do not support creation of instruction breakpoints using the -- 2.56.1.915.g69d5ec7298-goog