Skip to contentSkip to conversation

perf, kvm: Add PERF_SAMPLE_HOST_IP for host-side guest symbolization

RFC PATCH In review Ian Rogers 3 participants 25 messages Dec 1 – Dec 2

Subsystems (11)
x86 KVM BPF perf events +7 more subsystems
lore
Share & tools
lore

Ian Rogers

author reviewer
#0 lore raw

cover perf, kvm: Add PERF_SAMPLE_HOST_IP for host-side guest symbolization

This RFC proposes PERF_SAMPLE_HOST_IP along with BPF-filtered mmap_data recording so host-side perf can symbolize KVM guest code directly from host file-backed / DAX mappings without needing guest symbol state.

Note: This work is incomplete (for example, guest callchain / stack trace support is missing, as described below). It is being posted early as an RFC because combining host-translated guest IPs with DAX / host-mapped guest binaries is a novel approach, and I would like feedback on the overall idea, UAPI, and kernel/KVM/BPF design before investing further.

Motivation: Host IPs + DAX / file-backed guest mappings
=======================================================

Profiling KVM guests from the host currently records guest virtual IPs (PERF_SAMPLE_IP), which can only be symbolized if the host copies /proc/kallsyms, /proc/modules, and userspace maps/binaries out of each guest. That is difficult or impossible for opaque, ephemeral, or multi-tenant VMs.

When guest executables, shared libraries, or kernel/rootfs images are backed by host files mapped into the hypervisor address space (for example via DAX / virtio-pmem or direct file-backed guest memory), the host already knows which backing file and offset correspond to each guest page. By translating the guest instruction pointer (GVA -> GPA -> HVA in the hypervisor process) at PMI time into PERF_SAMPLE_HOST_IP and recording the hypervisor's non-executable file-backed mappings, host perf report/script can resolve guest samples to host DSOs, symbols, and build-IDs with no guest cooperation.

Known gaps & open questions for discussion
==========================================

1. Missing guest callchain support:
Perf currently bails out of perf_callchain_{kernel,user}() when perf_guest_state() is active on all architectures, so this RFC only translates the single sampled guest IP. Supporting host-IP translation for guest stack traces (where a per-sample on-stack page translation cache could amortize walks across frames in the same page) is left as future work.

2. No cross-PMI translation caching:
Each PMI walks guest page tables fresh. Under hardware TDP (EPT/NPT/Stage-2), guest page-table updates, INVLPG/TLBI, and CR3 loads do not trap to KVM, so caching GVA -> HVA across PMIs risks stale symbol attribution on guest remaps or THP splits.

3. UAPI for host IP sampling (Patch 1):
Is PERF_SAMPLE_HOST_IP alongside PERF_SAMPLE_IP (placed before PERF_SAMPLE_AUX so AUX remains last in PERF_RECORD_SAMPLE) the right UAPI, or would maintainers prefer a different representation?

4. Filtering non-executable hypervisor mappings via attr.mmap_bpf (Patch 2):
Hypervisors map guest memory without PROT_EXEC, so PERF_RECORD_MMAP misses DAX/file-backed guest images, while enabling attr.mmap_data system-wide floods the ring buffer with anonymous data mappings from every process. Patch 2 adds attr.mmap_bpf to run an attached BPF_PROG_TYPE_PERF_EVENT program (with access to the target vm_area_struct) as a per-event filter in perf_event_mmap_match(). Because it attaches to a non-tracing event's own event->prog and is evaluated per sideband perf_event in perf_iterate_sb(), separate perf commands do not filter each other's mmap records. However, setting attr.mmap_data still incurs system-wide d_path() preparation in perf_event_mmap_event() before per-event filtering, and reusing event->prog means a single perf_event cannot carry both an overflow BPF filter and an mmap_bpf filter (perf record puts mmap_bpf on a dedicated dummy tracking event). Is BPF filtering of mmap_data the right mechanism here?

5. NMI-safe KVM guest-to-host IP translation (Patches 3-7):
Patch 3 pairs synchronize_srcu_expedited(&kvm->srcu) with synchronize_rcu_expedited() in kvm_swap_active_memslots() for lockless NMI-safe memslot lookup and adds kvm_vcpu_read_guest_nofault() using copy_from_user_nofault(). Patches 4-7 implement kvm_arch_vcpu_get_ip_gpa() for x86 (including nested EPT/NPT), arm64, riscv, and loongarch. Feedback on the KVM locking/RCU tradeoffs and per-arch walkers is especially welcome.

Series overview
===============

- Patch 01: Add PERF_SAMPLE_HOST_IP and optional ->get_host_ip() on perf_guest_info_callbacks.
- Patch 02: Add attr.mmap_bpf to allow BPF filtering of non-executable mmap_data events.
- Patch 03: Add common NMI-safe KVM guest-to-host IP translation infrastructure (kvm_vcpu_read_guest_nofault(), kvm_guest_get_host_ip()).
- Patch 04: Implement kvm_arch_vcpu_get_ip_gpa() on x86.
- Patch 05: Implement kvm_arch_vcpu_get_ip_gpa() on arm64.
- Patch 06: Implement kvm_arch_vcpu_get_ip_gpa() on riscv.
- Patch 07: Implement kvm_arch_vcpu_get_ip_gpa() on loongarch.
- Patch 08: Sync tools/include/uapi/linux/perf_event.h.
- Patch 09: Add PERF_SAMPLE_HOST_IP parsing, synthesis, build-id hit marking, perf record --host-ip, and sample-parsing test updates.
- Patch 10: Resolve sample->host_ip against machines->host and fall back to host symbolization for unresolved guest samples.
- Patch 11: Add host_ip, host_dso, and host_sym sort keys in perf report and output fields in perf script.
- Patch 12: Discover hypervisor processes via /proc and synthesize existing non-executable file-backed data mappings for --host-ip.
- Patch 13: Add the kvm_mmap_filter BPF skeleton to filter runtime non-executable hypervisor mappings via attr.mmap_bpf.
- Patch 14: Support host_ip in BPF sample filters (--filter) and test.
- Patch 15: Anonymize sampled host_ip values in aslr_tool.
- Patch 16: Add the host-ip-sym C unit test suite for fallback symbolization, sorting, and ASLR anonymization.

Prerequisites
=============

This series is based on torvalds/master (19cc08c1a6a6) plus two small pre-existing fix series posted separately:
- perf/bpf: Fix BPF program inheritance and overflow races
https://lore.kernel.org/linux-perf-users/[email protected]/
- perf evsel: Add missing bounds checks in __evsel__parse_sample()
https://lore.kernel.org/linux-perf-users/[email protected]/

Development & testing notes
===========================

This prototype, tests, and changelogs were developed with an AI coding assistant and reviewed with Sashiko.

Tested:
- Build-tested kernel/events/core.o and KVM across x86_64, arm64, riscv, loongarch, CONFIG_BPF_SYSCALL=n, and CONFIG_BPF_EVENTS=n.
- Build-tested tools/perf across intermediate split commits and at HEAD with BUILD_BPF_SKEL=1 EXTRA_CFLAGS=-DREFCNT_CHECKING=1 and BUILD_BPF_SKEL=0 NO_LIBBPF=1, passing
'perf test "Sample parsing" "PERF_SAMPLE_HOST_IP"'.
- Runtime-tested in x86_64 QEMU/KVM (CONFIG_PROVE_LOCKING=y, CONFIG_PROVE_RCU=y): verified 2MB huge-page (797/797) and 4KB 4-level (800/800) guest IP-to-HVA translations, plus end-to-end 'perf record --host-ip' + kvm_mmap_filter capturing a non-executable PROT_READ file-backed guest image and symbolizing guest execution in perf report/script with zero lockdep/RCU splats.
- Runtime-tested in arm64 QEMU/KVM (VHE EL2, CONFIG_PROVE_LOCKING=y, CONFIG_PROVE_RCU=y): verified MMU-off (154/154) and non-identity Stage-1 MMU-on (391/391) guest IP-to-HVA translations.

Not runtime-tested:
- riscv and loongarch KVM guest IP translation (compile-tested only).
- x86 nested EPT/NPT guest IP translation (compile-tested only).

Ian Rogers (16):
perf/core: Add PERF_SAMPLE_HOST_IP sample format perf/core, bpf: Support BPF filtering of mmap_data events
KVM: Add NMI-safe guest-to-host IP translation infrastructure
KVM: x86: Implement kvm_arch_vcpu_get_ip_gpa()
KVM: arm64: Implement kvm_arch_vcpu_get_ip_gpa()
KVM: riscv: Implement kvm_arch_vcpu_get_ip_gpa()
KVM: loongarch: Implement kvm_arch_vcpu_get_ip_gpa() tools headers UAPI: Sync linux/perf_event.h with the kernel sources perf tools: Add PERF_SAMPLE_HOST_IP parsing, synthesis, and record

    --host-ip
  perf symbol: Support host IP resolution and guest fallback
    symbolization
  perf report, script: Add host_ip, host_dso, and host_sym fields
  perf record: Synthesize hypervisor file-backed data mappings for
    --host-ip
  perf record: Filter runtime hypervisor data mmaps with BPF for
    --host-ip

perf bpf-filter: Support host_ip in BPF sample filters perf aslr: Anonymize sampled host_ip values
perf test: Add PERF_SAMPLE_HOST_IP symbolization, sorting, and ASLR
tests

 arch/arm64/include/asm/kvm_nested.h           |   2 +
 arch/arm64/kvm/arm.c                          |  38 +
 arch/arm64/kvm/at.c                           |  39 +-
 arch/loongarch/kvm/vcpu.c                     | 104 +++
 arch/riscv/kvm/vcpu.c                         | 103 +++
 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 +
 include/linux/kvm_host.h                      |   3 +
 include/linux/perf_event.h                    |  12 +
 include/uapi/linux/perf_event.h               |   7 +-
 kernel/events/core.c                          | 111 ++-
 tools/include/uapi/linux/perf_event.h         |   7 +-
 tools/perf/Documentation/perf-record.txt      |   7 +
 tools/perf/Documentation/perf-report.txt      |   3 +
 tools/perf/Documentation/perf-script.txt      |   4 +
 tools/perf/builtin-record.c                   |  25 +-
 tools/perf/builtin-script.c                   |  48 ++
 tools/perf/tests/Build                        |   1 +
 tools/perf/tests/builtin-test.c               |   1 +
 tools/perf/tests/host-ip-sym.c                | 691 ++++++++++++++++++
 tools/perf/tests/sample-parsing.c             |   7 +-
 tools/perf/tests/shell/record_bpf_filter.sh   |   8 +
 tools/perf/tests/tests.h                      |   1 +
 tools/perf/util/Build                         |   3 +
 tools/perf/util/addr_location.c               |   7 +
 tools/perf/util/addr_location.h               |   4 +
 tools/perf/util/aslr.c                        |  32 +
 tools/perf/util/aslr.h                        |   3 +-
 tools/perf/util/bpf-filter.c                  |   3 +-
 tools/perf/util/bpf-filter.l                  |   1 +
 tools/perf/util/bpf_kvm_mmap.c                | 120 +++
 .../perf/util/bpf_skel/kvm_mmap_filter.bpf.c  |  79 ++
 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    |  25 +
 tools/perf/util/build-id.c                    |  27 +
 tools/perf/util/event.c                       |  58 +-
 tools/perf/util/evsel.c                       |  22 +
 tools/perf/util/evsel.h                       |   1 +
 tools/perf/util/hist.c                        |  48 ++
 tools/perf/util/hist.h                        |   6 +
 tools/perf/util/kvm-mmap-filter.c             | 210 ++++++
 tools/perf/util/kvm-mmap-filter.h             |  46 ++
 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/sort.c                        | 114 +++
 tools/perf/util/sort.h                        |   4 +
 tools/perf/util/synthetic-events.c            |   8 +
 virt/kvm/kvm_main.c                           |  64 ++
 60 files changed, 2336 insertions(+), 39 deletions(-)
 create mode 100644 tools/perf/tests/host-ip-sym.c
 create mode 100644 tools/perf/util/bpf_kvm_mmap.c
 create mode 100644 tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c
 create mode 100644 tools/perf/util/kvm-mmap-filter.c
 create mode 100644 tools/perf/util/kvm-mmap-filter.h

base-commit: 19cc08c1a6a650f8e54c0461ff198be6448f425d
prerequisite-patch-id: 9d5da60cadbe4821cfe47b4ec47d6e2f11d635f1
prerequisite-patch-id: 974971a9ccbd0a396dcab1c1f587d8b807ef4abb
prerequisite-patch-id: 2b50af50ad0619ae3324a7a8932a68561ed55129

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#1 lore raw

RFC PATCH 1/16 perf/core: Add PERF_SAMPLE_HOST_IP sample format

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.

---
 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(-)
include/linux/perf_event.h +9 -0
index b52348eca6ef..8ce5383e4b0a 100644
@@ -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 */
include/uapi/linux/perf_event.h +3 -1
index c49fc76292f7..75ed8e968d30 100644
@@ -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
 	 * };
kernel/events/core.c +24 -0
index 526c486d1647..6da956ceead0 100644
@@ -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);
 
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#2 lore raw

RFC PATCH 2/16 perf/core, bpf: Support BPF filtering of mmap_data events

In reply to Ian Rogers

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.

---
 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(-)
include/linux/perf_event.h +3 -0
index 8ce5383e4b0a..c31e1bf278ec 100644
@@ -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
include/uapi/linux/perf_event.h +2 -1
index 75ed8e968d30..146df3041c31 100644
@@ -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 */
kernel/events/core.c +83 -4

129 lines not on this page · raw message

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#3 lore raw

RFC PATCH 3/16 KVM: Add NMI-safe guest-to-host IP translation infrastructure

In reply to Ian Rogers

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.

---
 include/linux/kvm_host.h |  3 ++
 virt/kvm/kvm_main.c      | 64 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 67 insertions(+)
include/linux/kvm_host.h +3 -0
index fe300a22ab0f..c3e5366d01ea 100644
@@ -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));
virt/kvm/kvm_main.c +64 -0

85 lines not on this page · raw message

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#6 lore raw

RFC PATCH 4/16 KVM: x86: Implement kvm_arch_vcpu_get_ip_gpa()

In reply to Ian Rogers

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.

---
 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(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 4dde4e3e608a..ca9d1e37306c 100644
@@ -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)
arch/x86/include/asm/kvm_host.h +6 -1
index 1ee4b127004d..44c492e6b15f 100644
@@ -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);
arch/x86/kvm/mmu.h +13 -1
index b2a295a9f084..4636e020c922 100644
@@ -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)
arch/x86/kvm/mmu/mmu.c +50 -3

88 lines not on this page · raw message

arch/x86/kvm/mmu/paging_tmpl.h +86 -0

92 lines not on this page · raw message

arch/x86/kvm/svm/nested.c +16 -1
index 07554089ec05..989912a2c190 100644
@@ -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);
 }
 
arch/x86/kvm/vmx/main.c +9 -0
index d75170a6199e..9ec117ceeea7 100644
@@ -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),
arch/x86/kvm/vmx/nested.c +4 -1
index cd9465f4ee34..773f8f1be629 100644
@@ -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);
 }
 
arch/x86/kvm/vmx/vmx.c +16 -0
index af52568b551b..944d86091968 100644
@@ -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)
 
arch/x86/kvm/vmx/x86_ops.h +1 -0
index cd72684d075d..21450e3dc94c 100644
@@ -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);
arch/x86/kvm/x86.c +38 -0
index 0549c0b48901..7533a22c2b4b 100644
@@ -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));
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#7 lore raw

RFC PATCH 5/16 KVM: arm64: Implement kvm_arch_vcpu_get_ip_gpa()

In reply to Ian Rogers

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.

---
 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(-)
arch/arm64/include/asm/kvm_nested.h +2 -0
index 27ec73da02c6..4e94b57d21e3 100644
@@ -396,6 +396,8 @@ struct s1_walk_info {
 	bool	     		s2;
 	bool			pa52bit;
 	bool			ha;
+	bool			nofault;
+	bool			insn_fetch;
 };
 
 struct s1_walk_result {
arch/arm64/kvm/arm.c +38 -0
index a148e80d0aef..98563c3bbec3 100644
@@ -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)
arch/arm64/kvm/at.c +25 -14
index 30d8f062b2c2..f7cfa1793b16 100644
@@ -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;
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#9 lore raw

RFC PATCH 6/16 KVM: riscv: Implement kvm_arch_vcpu_get_ip_gpa()

In reply to Ian Rogers

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().

---
 arch/riscv/kvm/vcpu.c | 103 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 103 insertions(+)
arch/riscv/kvm/vcpu.c +103 -0
index 570b6864e94c..fe9ceec6a7c1 100644
@@ -17,9 +17,11 @@
 #include <linux/fs.h>
 #include <linux/kvm_host.h>
 #include <asm/cacheflush.h>
+#include <asm/csr.h>
 #include <asm/kvm_mmu.h>
 #include <asm/kvm_nacl.h>
 #include <asm/kvm_vcpu_vector.h>
+#include <asm/pgtable.h>
 
 #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)
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#10 lore raw

RFC PATCH 7/16 KVM: loongarch: Implement kvm_arch_vcpu_get_ip_gpa()

In reply to Ian Rogers

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().

---
 arch/loongarch/kvm/vcpu.c | 104 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)
arch/loongarch/kvm/vcpu.c +104 -0
index 76afd386abd2..32985380a636 100644
@@ -4,9 +4,12 @@
  */
 
 #include <linux/kvm_host.h>
+#include <asm/addrspace.h>
 #include <asm/fpu.h>
+#include <asm/kvm_csr.h>
 #include <asm/lbt.h>
 #include <asm/loongarch.h>
+#include <asm/pgtable-bits.h>
 #include <asm/setup.h>
 #include <asm/time.h>
 #include <asm/timex.h>
@@ -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,
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#11 lore raw

RFC PATCH 8/16 tools headers UAPI: Sync linux/perf_event.h with the kernel sources

In reply to Ian Rogers

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.

---
 tools/include/uapi/linux/perf_event.h | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
tools/include/uapi/linux/perf_event.h +5 -2
index c49fc76292f7..146df3041c31 100644
@@ -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
 	 * };
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#12 lore raw

RFC PATCH 9/16 perf tools: Add PERF_SAMPLE_HOST_IP parsing, synthesis, and record --host-ip

In reply to Ian Rogers

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).

---
 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(-)
tools/perf/Documentation/perf-record.txt +7 -0
index 2351f7b4f5fc..fb3029f82a08 100644
@@ -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
tools/perf/builtin-record.c +2 -0
index 085d3648a30a..4ff929191211 100644
@@ -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"),
tools/perf/tests/sample-parsing.c +6 -1
index acbd353d3588..9c04eaba813d 100644
@@ -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;
 	}
tools/perf/util/build-id.c +27 -0
index 02233ef0eaff..cc5ce39ddacd 100644
@@ -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);
 
tools/perf/util/evsel.c +22 -0
index 90269b8d1745..5950a383eff4 100644
@@ -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)
tools/perf/util/evsel.h +1 -0
index 53f3641b66e1..ce38cea0f729 100644
@@ -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;
tools/perf/util/perf_event_attr_fprintf.c +2 -1
index 2e8be9a357dc..492dcc04bd99 100644
@@ -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);
tools/perf/util/record.h +1 -0
index 411bb7276ad7..99f20019dbf8 100644
@@ -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;
tools/perf/util/sample.h +2 -0
index cb4b16654876..c27f21db45e1 100644
@@ -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. */
tools/perf/util/session.c +3 -0
index 56a5e57ec512..f143ffbd7f8b 100644
@@ -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);
 
tools/perf/util/synthetic-events.c +8 -0
index b9dbd105cdc3..92e9b086b1b3 100644
@@ -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;
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#14 lore raw

RFC PATCH 10/16 perf symbol: Support host IP resolution and guest fallback symbolization

In reply to Ian Rogers

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.

---
 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(-)
tools/perf/util/addr_location.c +7 -0
index 57e8217a00f9..ca0380260ee6 100644
@@ -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);
 }
tools/perf/util/addr_location.h +4 -0
index fdc4d3f3a68b..d4148d7df998 100644
@@ -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;
tools/perf/util/event.c +56 -2

76 lines not on this page · raw message

Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#15 lore raw

RFC PATCH 11/16 perf report, script: Add host_ip, host_dso, and host_sym fields

In reply to Ian Rogers

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.

---
 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(+)
tools/perf/Documentation/perf-report.txt +3 -0
index e145124d6c9a..64466ccab9fd 100644
@@ -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
tools/perf/Documentation/perf-script.txt +4 -0
index f0228e784ced..ed66a6d23a68 100644
@@ -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.
 
tools/perf/builtin-script.c +48 -0

72 lines not on this page · raw message

tools/perf/util/hist.c +48 -0

100 lines not on this page · raw message

tools/perf/util/hist.h +6 -0
index 0d08011aebce..263b349b9597 100644
@@ -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;
tools/perf/util/sort.c +114 -0

138 lines not on this page · raw message

tools/perf/util/sort.h +4 -0
index c962e77e4b93..db6f541a82a2 100644
@@ -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,
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#17 lore raw

RFC PATCH 12/16 perf record: Synthesize hypervisor file-backed data mappings for --host-ip

In reply to Ian Rogers

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).

---
 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
tools/perf/builtin-record.c +3 -0
index 4ff929191211..5e11ccda8c6d 100644
@@ -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) {
tools/perf/util/Build +1 -0
index 2c1f880c4c47..fd34879d45ba 100644
@@ -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/
tools/perf/util/kvm-mmap-filter.c new file +210 -0

210 lines not on this page · raw message

tools/perf/util/kvm-mmap-filter.h new file +16 -0
new file mode 100644
index 000000000000..c269a862f7b2
@@ -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 */
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#18 lore raw

RFC PATCH 13/16 perf record: Filter runtime hypervisor data mmaps with BPF for --host-ip

In reply to Ian Rogers

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.

---
 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
tools/perf/builtin-record.c +19 -1
index 5e11ccda8c6d..1807ac3d8cc8 100644
@@ -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();
tools/perf/util/Build +2 -0
index fd34879d45ba..e48edc11eb21 100644
@@ -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
tools/perf/util/bpf_kvm_mmap.c new file +120 -0

120 lines not on this page · raw message

tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c new file +79 -0

79 lines not on this page · raw message

tools/perf/util/bpf_skel/vmlinux/vmlinux.h +24 -0
index 94e42b022ab1..7d07c565762c 100644
@@ -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));
 
 /*
tools/perf/util/kvm-mmap-filter.h +30 -0
index c269a862f7b2..56b49442567d 100644
@@ -2,8 +2,10 @@
 #ifndef PERF_UTIL_KVM_MMAP_FILTER_H
 #define PERF_UTIL_KVM_MMAP_FILTER_H
 
+#include <stdbool.h>
 #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 */
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#20 lore raw

RFC PATCH 14/16 perf bpf-filter: Support host_ip in BPF sample filters

In reply to Ian Rogers

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.

---
 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(-)
tools/perf/tests/shell/record_bpf_filter.sh +8 -0
index 383574cb3bd3..5c898b52b263 100755
@@ -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]"
 }
 
tools/perf/util/bpf-filter.c +2 -1
index 72e83ac1d6a4..698fcd7c2d09 100644
@@ -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) {
tools/perf/util/bpf-filter.l +1 -0
index 1be9df6550fc..ade6d88bb964 100644
@@ -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); }
tools/perf/util/bpf_skel/sample-filter.h +2 -1
index 683fec85e71e..04d0314e8f53 100644
@@ -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,
tools/perf/util/bpf_skel/sample_filter.bpf.c +7 -2
index e5666d4c1722..c22d9c867c7e 100644
@@ -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:
tools/perf/util/bpf_skel/vmlinux/vmlinux.h +1 -0
index 7d07c565762c..2d7659d4cb7e 100644
@@ -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 {
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#21 lore raw

RFC PATCH 15/16 perf aslr: Anonymize sampled host_ip values

In reply to Ian Rogers

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.

---
 tools/perf/util/aslr.c | 32 ++++++++++++++++++++++++++++++++
 tools/perf/util/aslr.h |  3 ++-
 2 files changed, 34 insertions(+), 1 deletion(-)
tools/perf/util/aslr.c +32 -0
index e365f807b021..ec2c0989e19d 100644
@@ -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;
 
tools/perf/util/aslr.h +2 -1
index 9cc14f0263db..8850511a4a43 100644
@@ -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;
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
author reviewer
#22 lore raw

RFC PATCH 16/16 perf test: Add PERF_SAMPLE_HOST_IP symbolization, sorting, and ASLR tests

In reply to Ian Rogers

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.

---
 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
tools/perf/tests/Build +1 -0
index 58858f3d2bf9..ace316b165a1 100644
@@ -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
tools/perf/tests/builtin-test.c +1 -0
index 0b8897fd42ca..f7388c5acf2b 100644
@@ -177,6 +177,7 @@ static struct test_suite *generic_tests[] = {
 	&suite__util,
 	&suite__subcmd_help,
 	&suite__kallsyms_split,
+	&suite__host_ip_sym,
 	NULL,
 };
 
tools/perf/tests/host-ip-sym.c new file +691 -0

691 lines not on this page · raw message

tools/perf/tests/tests.h +1 -0
index 20ae3609892b..3dce04124d6c 100644
@@ -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
Signature · 1 line
2.56.1.915.g69d5ec7298-goog
#13 lore raw

Re: [RFC PATCH 09/16] perf tools: Add PERF_SAMPLE_HOST_IP parsing, synthesis, and record --host-ip

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf build-id: redundant host_ip resolution work in build_id__mark_dso_hit() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf build-id: redundant host_ip resolution work in build_id__mark_dso_hit()
--

commit f48af508d6ae21b2cf368f9f3892365b8960eca5
Author: Ian Rogers <[email protected]>

perf tools: Add PERF_SAMPLE_HOST_IP parsing, synthesis, and record --host-ip

This commit adds userspace support for PERF_SAMPLE_HOST_IP, including sample parsing, synthesis, build-id hit tracking, and a --host-ip option in perf record.

Quoted 24 lines
tools/perf/util/build-id.c +16 -0
index 02233ef0eafff..cc5ce39ddacd4 100644
@@ -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) {

tools/perf/util/build-id.c int build_id__mark_dso_hit(const struct perf_tool *tool __maybe_unused, · line 102

Quoted 10 lines
tools/perf/util/build-id.c +10 -0
+				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);
+		}
+	}

[Severity: Low]
Does calling machine__kernel_ip() on every non-zero sample->host_ip force an eager load of the host kernel symbol table even for pure user-space samples?

machine__kernel_ip() calls machine__get_kernel_start(), which invokes map__load() on the host vmlinux map on the first sample, bypassing symbol_conf.lazy_load_kernel_maps in cmd_record():

tools/perf/util/machine.c:machine__get_kernel_start() {
	...
	if (map) {
		err = map__load(map);
		/*
		 * On x86_64, PTI entry trampolines are less than the
		 * start of kernel text, but still above 2^63. So leave
		 * kernel_start = 1ULL << 63 for x86_64.
		 */
		if (!err && !machine__is(machine, EM_X86_64))
			machine->kernel_start = map__start(map);
	}
	...
}

In addition, when host_machine == machine and sample->host_ip == sample->ip, this repeats machine__findnew_thread() (even before checking whether host_thread is needed for a user-space address) and repeats the map lookup already done by thread__find_map() above.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#4 lore raw

Re: [RFC PATCH 03/16] KVM: Add NMI-safe guest-to-host IP translation infrastructure

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: host-wide IPI storms from synchronize_rcu_expedited() on memslot swaps --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: host-wide IPI storms from synchronize_rcu_expedited() on memslot swaps
--

commit c3fd2e2a56f630639fb857330005768b10210e44
Author: Ian Rogers <[email protected]>

KVM: Add NMI-safe guest-to-host IP translation infrastructure

This commit adds RCU-protected memslot lookup and no-fault guest memory read helpers, and wires up kvm_guest_get_host_ip() in kvm_guest_cbs for NMI-safe guest-to-host IP translation.

virt/kvm/kvm_main.c static void kvm_swap_active_memslots(struct kvm *kvm, int as_id) · line 1661

Quoted 9 lines
virt/kvm/kvm_main.c +1 -0
index 83e727bf6452c..7935d4a346a37 100644
@@ -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();

[Severity: Medium]
Does calling synchronize_rcu_expedited() unconditionally here cause host-wide IPI storms on memslot updates?

Previously, kvm_swap_active_memslots() only synchronized the per-VM kvm->srcu, which completes via local barriers and per-CPU counter checks without sending cross-CPU IPIs. Adding synchronize_rcu_expedited() turns every memslot create or flag change into one global expedited RCU grace period (and every delete or move into two, via kvm_invalidate_memslot() followed by kvm_activate_memslot()), broadcasting IPIs to all non-idle online CPUs on the host during VM startup, PCI BAR enumeration, or dirty-log toggling even when no guest perf event is active or no vCPU has run.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#23 lore raw

Re: [RFC PATCH 16/16] perf test: Add PERF_SAMPLE_HOST_IP symbolization, sorting, and ASLR tests

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf test: missing reset_output_field() on setup_sorting() error path --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf test: missing reset_output_field() on setup_sorting() error path
--

commit 27b0696436e8693a733c90ea5666e742b5cfaa44
Author: Ian Rogers <[email protected]>

perf test: Add PERF_SAMPLE_HOST_IP symbolization, sorting, and ASLR tests

This commit adds a C test suite for PERF_SAMPLE_HOST_IP covering guest-to-host symbolization fallback, histogram sorting and formatting for host sort keys, and ASLR anonymization of sampled host_ip values.

Quoted 6 lines
tools/perf/tests/host-ip-sym.c new file +0 -0
new file mode 100644
index 0000000000000..b2acf08446e94
@@ -0,0 +1,691 @@

[ ... ]

Quoted 3 lines
tools/perf/tests/host-ip-sym.c new file +3 -0
+static int test__host_ip_hist_sort(struct test_suite *test __maybe_unused,
+				   int subtest __maybe_unused)
+{

[ ... ]

Quoted 5 lines
tools/perf/tests/host-ip-sym.c new file +5 -0
+	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();

[ ... ]

Quoted 23 lines
tools/perf/tests/host-ip-sym.c new file +23 -0
+	/*
+	 * 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) {

tools/perf/tests/host-ip-sym.c line 524

Quoted 10 lines
tools/perf/tests/host-ip-sym.c new file +10 -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:

[Severity: Low]
Should both setup_sorting() failure paths jump to out_hists (or a label that calls reset_output_field() and clears sort_order) instead of out_machines? If setup_sorting() fails part-way through, jumping to out_machines leaks any perf_hpp_fmt and hpp_sort_entry objects already linked onto perf_hpp_list and leaves global sort_order and dimension state dirty for subsequent tests in the same process.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=16
#8 lore raw

Re: [RFC PATCH 05/16] KVM: arm64: Implement kvm_arch_vcpu_get_ip_gpa()

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] KVM: arm64: S1POE bitwise-AND on bool clears execute perms in at.c - [Medium] KVM: arm64…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] KVM: arm64: S1POE bitwise-AND on bool clears execute perms in at.c
- [Medium] KVM: arm64: vcpu_mode_is_32bit() check breaks 32-bit EL0 IP translation
- [Medium] KVM: arm64: kvm_vm_is_protected() misses non-protected pKVM guests
--

commit 3cc4c3ee57836b5df873d0dbeffedcd751a7a24c
Author: Ian Rogers <[email protected]>

KVM: arm64: Implement kvm_arch_vcpu_get_ip_gpa()

This commit implements kvm_arch_vcpu_get_ip_gpa() on arm64 by extending the Stage-1 translation walk in at.c with a non-faulting guest memory read mode and using __kvm_translate_va() to translate the guest PC.

Quoted 10 lines
arch/arm64/kvm/arm.c +2 -0
index a148e80d0aef7..98563c3bbec3f 100644
@@ -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)

arch/arm64/kvm/arm.c unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) · line 997

Quoted 10 lines
arch/arm64/kvm/arm.c +10 -0
+{
+	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;

[Severity: Medium]
Should this check is_protected_kvm_enabled() (or
kvm_vm_hyp_is_distrusting(vcpu->kvm)) instead of
kvm_vm_is_protected(vcpu->kvm)?

kvm_vm_is_protected() only matches protected VMs (VM_PROTECTED_PKVM) and is false for normal non-protected guests running under pKVM (VM_PKVM). For VM_PKVM guests, EL2 owns the live system registers and does not sync them to host_vcpu->arch.ctxt.sys_regs on IRQ exits:

arch/arm64/kvm/hyp/nvhe/hyp-main.c:sync_hyp_vcpu() {
	...
	} else {
		/* Non-protected: the host gets the full fault. */
		host_vcpu->arch.fault = hyp_vcpu->vcpu.arch.fault;
		host_vcpu->arch.iflags = hyp_vcpu->vcpu.arch.iflags;
		...
		host_vcpu->arch.ctxt.regs.pc = hyp_vcpu->vcpu.arch.ctxt.regs.pc;
		host_vcpu->arch.ctxt.regs.pstate = hyp_vcpu->vcpu.arch.ctxt.regs.pstate;
	}
}

On a PMU interrupt exit for a non-protected pKVM guest, __kvm_translate_va() will walk the guest Stage-1 page tables using stale host-side SCTLR_EL1, TCR_EL1, and TTBRx_EL1 values instead of returning INVALID_GPA as described in the commit message.

arch/arm64/kvm/arm.c unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) · line 1007

Quoted 10 lines
arch/arm64/kvm/arm.c +10 -0
+
+	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);
+	}

[Severity: Medium]
Does checking vcpu_mode_is_32bit(vcpu) here break IP translation for 32-bit compat EL0 tasks running under a 64-bit guest kernel?

vcpu_mode_is_32bit() checks PSR_MODE32_BIT in PSTATE, which is also set when a 64-bit EL1 kernel (!vcpu_el1_is_32bit(vcpu)) runs a 32-bit EL0 userspace task with SCTLR_EL1.M enabled. In that case the EL1&0 regime still uses standard AArch64 Stage-1 page tables, so masking va to 32 bits and translating it through __kvm_translate_va() works, whereas rejecting SCTLR_ELx_M here causes every 32-bit compat EL0 sample to return INVALID_GPA. Also, for nested virtualization vCPUs (or when !kvm_supports_32bit_el0()), any 32-bit mode is illegal (vcpu_mode_is_bad_32bit()), yet this block returns va & GENMASK_ULL(31, 0) when HCR_EL2.{VM,DC,TGE} and SCTLR_EL1.M are clear.

arch/arm64/kvm/arm.c unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu) · line 1020

Quoted 13 lines
arch/arm64/kvm/arm.c +13 -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;

[Severity: Medium]
Will this execute permission check always fail and return INVALID_GPA whenever the guest has S1POE enabled?

In struct s1_walk_result, wr.px, wr.ux, wr.pw, and wr.uw are bool fields (0 or 1), while POE_X is UL(0x2) and POE_W is UL(0x4). In compute_s1_overlay_permissions(), the compound bitwise-ANDs do not normalize the bitmask tests to booleans:

arch/arm64/kvm/at.c:compute_s1_overlay_permissions() {
	...
	if (wr->pov) {
		...
		wr->pr &= pov_perms & POE_R;
		wr->pw &= pov_perms & POE_W;
		wr->px &= pov_perms & POE_X;
	}

	if (wr->uov) {
		...
		wr->ur &= uov_perms & POE_R;
		wr->uw &= uov_perms & POE_W;
		wr->ux &= uov_perms & POE_X;
	}
}

Because 1UL & 2UL is 0, wr->px and wr->ux (as well as wr->pw and wr->uw) are unconditionally cleared to false whenever S1POE is active.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#16 lore raw

Re: [RFC PATCH 11/16] perf report, script: Add host_ip, host_dso, and host_sym fields

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 4 potential issues to consider: - [Medium] perf sort: double unmapping of host_ip in hist_entry__host_sym_snprintf() - [Medium] perf sort…

Thank you for your contribution! Sashiko AI review found 4 potential issues to consider:
- [Medium] perf sort: double unmapping of host_ip in hist_entry__host_sym_snprintf()
- [Medium] perf sort: strict weak ordering violation in sort__host_sym_cmp()
- [Low] perf script: symoff and dsoff validation ignores host_sym and host_dso
- [Low] perf hist: missing verbose width for unresolved HISTC_HOST_SYMBOL
--

commit 976f06507181de924b5188635a7f011b6d5746e0
Author: Ian Rogers <[email protected]>

perf report, script: Add host_ip, host_dso, and host_sym fields

This commit records resolved host map, symbol, and address fields on struct hist_entry and adds host_ip, host_dso, and host_sym sort keys and output fields to perf report and perf script.

Quoted 4 lines
tools/perf/builtin-script.c +0 -0
index b6691ebb1b4ef..f1f0e388d713e 100644

[ ... ]

Quoted 9 lines
tools/perf/builtin-script.c +5 -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;
+

tools/perf/builtin-script.c static void process_event(struct perf_script *script, · line 2780

Quoted 10 lines
tools/perf/builtin-script.c +10 -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;

[Severity: Low]
Should evsel__check_attr() and perf_session__check_output_opt() also account for HOST_SYM and HOST_DSO when validating SYMOFFSET and DSOFF?

evsel__check_attr() rejects PRINT_FIELD(SYMOFFSET) when !PRINT_FIELD(SYM), so running perf script with -F -sym,+host_sym or -F host_sym,symoff fails with -EINVAL. Likewise, perf_session__check_output_opt() unconditionally sets PERF_OUTPUT_DSO whenever PERF_OUTPUT_DSOFF is requested, even if only host_dso was selected.

Quoted 8 lines
tools/perf/util/hist.c +0 -0
index 364754e9d12aa..50ecb65a354ad 100644
@@ -119,6 +119,24 @@ void hists__calc_col_len(struct hists *hists, struct hist_entry *h)
 		hists__new_col_len(hists, HISTC_DSO, len);
 	}
 

tools/perf/util/hist.c void hists__calc_col_len(struct hists *hists, struct hist_entry *h) · line 131

Quoted 10 lines
tools/perf/util/hist.c +10 -0
+	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);
+	}

[Severity: Low]
Does the unresolved branch here and hists__sort_list_width() in tools/perf/ui/hist.c miss the verbose address-and-origin prefix width for HISTC_HOST_SYMBOL?

_hist_entry__sym_snprintf() prints the verbose prefix even when ms->sym is NULL, and hists__sort_list_width() only checks hists__has(hists, sym) before adding 3 + BITS_PER_LONG / 4. When running perf report -v sorted by host_sym without sym, unresolved host symbols can overflow the calculated column width and truncate the output line in hists__fprintf().

Quoted 4 lines
tools/perf/util/sort.c +0 -0
index 58638ec9ae0ed..229b836479c45 100644

[ ... ]

Quoted 6 lines
tools/perf/util/sort.c +6 -0
+/* --sort host_sym */
+
+static int64_t
+sort__host_sym_cmp(struct hist_entry *left, struct hist_entry *right)
+{
+	int64_t ret;

tools/perf/util/sort.c static struct sort_entry sort_addr = { · line 2552

Quoted 10 lines
tools/perf/util/sort.c +10 -0
+
+	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);
+}

[Severity: Medium]
Does comparing sort__host_ip_cmp() before sort__host_dso_cmp() when both symbols are NULL break comparator transitivity for the hists RB-tree?

When one entry has a symbol and the other does not, sort__host_sym_cmp() orders them by host DSO first, whereas two unresolved entries are ordered by unmapped host_ip across different DSOs. Three entries across DSOs liba.so (sym == NULL, host_ip = 0x3000), libb.so (sym != NULL), and libc.so (sym == NULL, host_ip = 0x1000) can then form a cycle A > B > C > A, corrupting RB-tree lookups under --sort host_sym. In addition, if two unresolved entries with different host_ms.map pointers share the same unmapped host_ip, sort__host_sym_cmp() returns 0 and hists__findnew_entry() overwrites he->host_ms.map in place without rebalancing the RB-tree.

Quoted 11 lines
tools/perf/util/sort.c +11 -0
+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)

tools/perf/util/sort.c static struct sort_entry sort_addr = { · line 2574

Quoted 10 lines
tools/perf/util/sort.c +10 -0
+{
+	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);
+}

[Severity: Medium]
Doesn't calling map__unmap_ip() here cause _hist_entry__sym_snprintf() to unmap ip a second time in verbose mode?

tools/perf/util/sort.c:_hist_entry__sym_snprintf() {
    ...
	if (verbose > 0) {
		struct dso *dso = map ? map__dso(map) : NULL;
		char o = map ? dso__symtab_origin(dso) : '!';
		u64 rip = ip;

		if (dso && dso__kernel(dso) && dso__adjust_symbols(dso))
			rip = map__unmap_ip(map, ip);
    ...
}

Because he->host_ip already holds al->host_addr when he->host_ms.map is present (matching how he->ip holds al->addr in hist_entry__sym_snprintf()), pre-unmapping ip when !he->host_ms.sym && he->host_ms.map causes adjusted kernel and module DSOs to be unmapped twice under perf report -v, printing a bogus address.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
#19 lore raw

Re: [RFC PATCH 13/16] perf record: Filter runtime hypervisor data mmaps with BPF for --host-ip

In reply to Ian Rogers
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] perf bpf: direct field access in perf_kvm_mmap_filter() breaks GEN_VMLINUX_H=1 --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] perf bpf: direct field access in perf_kvm_mmap_filter() breaks GEN_VMLINUX_H=1
--

commit ee1db873881f238429396b011d3810e0ce79e595
Author: Ian Rogers <[email protected]>

perf record: Filter runtime hypervisor data mmaps with BPF for --host-ip

This commit adds the kvm_mmap_filter BPF skeleton and attaches it via attr.mmap_bpf to filter runtime non-executable file-backed hypervisor mappings during perf record --host-ip.

Quoted 6 lines
tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c new file +0 -0
new file mode 100644
index 0000000000000..3f089412fa594
@@ -0,0 +1,79 @@

[ ... ]

Quoted 17 lines
tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c new file +17 -0
+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;

[ ... ]

tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c line 74

Quoted 8 lines
tools/perf/util/bpf_skel/kvm_mmap_filter.bpf.c new file +8 -0
+	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;
+	}

[Severity: Low]
Does referencing kctx->vma and mm->notifier_subscriptions directly on struct bpf_perf_event_data_kern and struct mm_struct break builds with GEN_VMLINUX_H=1?

When GEN_VMLINUX_H=1 is set, tools/perf/bpf_skel.mak generates vmlinux.h from the host kernel BTF instead of using the bundled header. If that BTF comes from a kernel predating bpf_perf_event_data_kern::vma or built without CONFIG_MMU_NOTIFIER, the fields do not exist on the static struct types and clang fails at compile time despite the bpf_core_field_exists() guards. Defining local ___new CO-RE struct flavors (such as struct bpf_perf_event_data_kern___new and struct mm_struct___new) avoids relying on the generated vmlinux.h definitions.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
#24 lore raw
In reply to Ian Rogers
Sashiko has finished reviewing this 16-patch series:

Sashiko has finished reviewing this 16-patch series:

- Patches 1, 2, 4, 6-8, 10, 12, 14, and 15: no issues found.
- Patch 3 ("KVM: Add NMI-safe guest-to-host IP translation infra..."): 1 potential issue (1 Medium)
- Patch 5 ("KVM: arm64: Implement kvm_arch_vcpu_get_ip_gpa()"): 3 potential issues (3 Medium)
- Patch 9 ("perf tools: Add PERF_SAMPLE_HOST_IP parsing, synthes..."): 1 potential issue (1 Low)
- Patch 11 ("perf report, script: Add host_ip, host_dso, and host..."):
4 potential issues (2 Medium, 2 Low)
- Patch 13 ("perf record: Filter runtime hypervisor data mmaps wi..."):
1 potential issue (1 Low)
- Patch 16 ("perf test: Add PERF_SAMPLE_HOST_IP symbolization, so..."):
1 potential issue (1 Low)

Detailed reviews have been sent as separate replies to patches 3, 5, 9, 11, 13, and 16.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]
#5 lore raw

Re: [RFC PATCH 03/16] KVM: Add NMI-safe guest-to-host IP translation infrastructure

In reply to Ian Rogers

Am 02.12.26 um 00:21 schrieb Ian Rogers:

Quoted 50 lines

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.

---
  include/linux/kvm_host.h |  3 ++
  virt/kvm/kvm_main.c      | 64 ++++++++++++++++++++++++++++++++++++++++
  2 files changed, 67 insertions(+)
include/linux/kvm_host.h +3 -0
index fe300a22ab0f..c3e5366d01ea 100644
@@ -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));
virt/kvm/kvm_main.c +0 -0
index 83e727bf6452..7935d4a346a3 100644

virt/kvm/kvm_main.c static void kvm_swap_active_memslots(struct kvm *kvm, int as_id) · line 1661

Quoted 4 lines
virt/kvm/kvm_main.c +1 -0
@@ -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();

Probably not critical but maybe limit that to architectures that implement CONFIG_GUEST_PERF_EVENTS.

cc Hendrik. We might want to look at GUEST_PERF_EVENTSfor s390 in general. Right now this perf_arch_instruction_pointer() returns the _guest_ PSW address when the interrupt hit (or via hw sample) If we decide to change that, we could re-use the existing gaccess DAT walker to also implement this here for s390.

This might also be relevant for our arm on s390.