Skip to contentSkip to conversation

KVM: x86/pmu: Dynamic mediated PMU context switching

RFC PATCH New Yosry Ahmed 2 participants 31 messages Nov 24

Subsystems (6)
Stable branch x86 KVM BPF +2 more subsystems
lore
Share & tools
lore
#0 lore raw

cover KVM: x86/pmu: Dynamic mediated PMU context switching

When KVM uses the mediated PMU, it loads the guest context and puts it around the inner fastpath loop, causing an expensive switch on every slowpath VM-Exit. On microbenchmarks like CPUID, this can result in up to 3x drop in throughput even when the host is not using the core PMU. On more realistic benchmarks like netperf TCP_RR, it results in up to ~15% regression (at least in some setups).

This series uses a dynamic scheme for PMU context switching instead. On slowpath VM-Exit, KVM only puts the guest context if host perf has events conflicting with the mediated PMU. Otherwise, the guest context remains loaded until either the vCPU is put (e.g. on context switch or return to userspace), or perf "reclaims" it. This recovers most/all performance (at least on CPUID and netperf) with a mediated PMU in the absence of host events. See "KVM:
x86/pmu: Put the mediated PMU context lazily on slowpath VM-Exits" for exact numbers.

The Perf Side
-------------

Perf reclaims the PMU before executing any remote call on a CPU if the guest context is loaded, including installing events, enabling events, etc. This is too conservative, as perf really only needs to reclaim the PMU before an event is both installed and enabled, but it results in a simpler and more future-proof implementation.

There are a couple of other hiccups that perf needs to deal with outside of reclaiming on remote calls, namely:

1. Intel PT/BTS. These PMUs are not mediated, but they use the same PMI delivery mechanism as the mediated core PMU (i.e. LVTPC). Since they are not mediated, they are not scheduled out while the guest context is loaded, and their PMIs can be delivered into the guest instead of the host. Today, BTS is never active while the guest runs (KVM doesn't allow the guest to enable it, and VM-Exit clears DEBUGCTL), so this is limited to short windows around VM-Entry/VM-Exit. Intel PT (in system mode) keeps tracing while the guest runs, so its PMIs raised while the guest is running are delivered to the guest.

Lazily putting the guest context would make this worse for both, as host code with tracing enabled could run with the guest context loaded for much longer, most notably for BTS, which would go from short windows around VM-Entry/VM-Exit to all of slowpath VM-Exit handling. To avoid that, this series tracks PMUs that share the same PMI mechanism, and having events on any of them prompts KVM to give up the PMU on slowpath VM-Exits, keeping the status quo.

Long-term, perhaps it would be better to schedule out Intel PT events while the guest context is loaded, or somehow demux the PMIs?

2. Handling bpf_get_branch_snapshot() while the guest context is loaded (a pre-existing bug that is more exposed by this series).

3. Clearing dirty counters when events are mmap()'d or the rdpmc attribute is updated, which needs to reclaim the PMU first if the guest context is loaded.

NOTE: The first 5 patches fix pre-existing problems (or prepare for those fixes) that are relevant to the series (or the dynamic switch makes them worse), but they can be merged independently.

The KVM Side
------------

The main change is needing to access guest PMU registers in hardware while the guest context is loaded. More specifically, the currently virtualized registers fall into one of two categories:

1. Registers that can be read from software but must be written to hardware (i.e. are always up-to-date in software). This includes registers that are always intercepted or sync'd on every VM-exit, namely control registers:
eventsel, fixed_ctr_ctrl, and GLOBAL_CTRL.

2. Registers that must be read and written from hardware (i.e. software can always be stale). This includes registers that can be updated by the guest or hardware while the guest runs, namely counters and GLOBAL_STATUS.

Additionally, KVM needs to keep the physical and virtual LVTPC in sync while the guest context is loaded.

KVM accessing registers in hardware as needed allows it to handle fastpath instruction emulation with a mediated PMU, so this restriction is dropped.

Testing
-------

This was tested by new (AI-generated) extensions to PMU selftests that mostly act as regression tests for the existing PMU, a selftest-style stress test, and stressing perf with a real Linux VM. The selftests will be cleaned up and sent out separately.

The full KVM x86 selftests and kvm-unit-tests were also run on Intel and AMD, with no new failures compared to the base kernel.

Testing was done with Zide's "KVM: SVM: Drop counter MSR checks in amd_is_valid_msr()" [1] applied, as without it saving vCPU state on AMD fails when the guest has fewer counters than the host (KVM_GET_MSRS fails on the unexposed counter MSRs).

[1] https://lore.kernel.org/r/[email protected]

Yosry Ahmed (26):
perf/core: Fix lockless time read for exclude_guest events perf/core: Don't subtract guest time for events that keep counting perf/core: Move is_guest_mediated_pmu_loaded() to the header perf/x86: Use irqsave guard in branch stack snapshotting callbacks perf/x86: Don't snapshot the branch stack while a guest PMU is loaded perf/core: Guard against accessing guest mediated vPMU state
perf: Add a guest callback to reclaim the mediated PMU perf/core: Reclaim the mediated PMU before executing remote calls perf/x86: Reclaim the mediated PMU before clearing dirty counters
perf: Track mediated PMU conflicts
KVM: x86/pmu: Move PMC MSR and type helpers earlier
KVM: x86/pmu: Access PMCs in hardware if the mediated PMU context is
loaded
KVM: x86/pmu: Compute eventsel_hw from eventsel when reprogramming
KVM: x86/pmu: Zero eventsel_hw for counters that can't count
KVM: x86/pmu: Write PMU controls to hardware on reprogram if loaded
KVM: x86/pmu: Write GLOBAL_CTRL to hardware if the guest context is
loaded
KVM: x86/pmu: Ignore reserved bits on writes to GLOBAL_STATUS_CLR
KVM: x86/pmu: Access GLOBAL_STATUS in hardware if the guest context is
loaded
KVM: x86/pmu: Sync the guest's LVTPC to hardware if the guest context
is loaded
KVM: x86/pmu: Check for a mediated PMU before loading/putting its
context
KVM: x86/pmu: Make loading/putting the mediated PMU context idempotent
KVM: x86/pmu: Put the mediated PMU context lazily on slowpath VM-Exits
KVM: x86/pmu: Add stats for mediated PMU context switches
KVM: VMX: WARN if the Intel PT PMI handler runs for a mediated PMU
KVM: x86/pmu: WARN if a mediated PMI arrives outside of guest IRQ
handling
KVM: x86/pmu: Allow emulation in the fastpath with a mediated PMU

 arch/x86/events/amd/core.c      |  12 ++-
 arch/x86/events/core.c          |   8 ++
 arch/x86/events/intel/bts.c     |   3 +-
 arch/x86/events/intel/core.c    |  31 ++++--
 arch/x86/events/intel/pt.c      |   3 +-
 arch/x86/include/asm/kvm_host.h |   3 +
 arch/x86/kvm/lapic.c            |   4 +
 arch/x86/kvm/msrs.c             |   3 -
 arch/x86/kvm/pmu.c              | 180 ++++++++++++++++++++++++--------
 arch/x86/kvm/pmu.h              |  78 ++++++++++----
 arch/x86/kvm/svm/pmu.c          |  13 ++-
 arch/x86/kvm/vmx/pmu_intel.c    |  15 +--
 arch/x86/kvm/vmx/vmx.c          |  10 ++
 arch/x86/kvm/x86.c              |  25 +++--
 include/linux/kvm_host.h        |   5 +-
 include/linux/perf_event.h      |  34 ++++++
 kernel/events/core.c            | 168 +++++++++++++++++++++++------
 virt/kvm/kvm_main.c             |   5 +-
 18 files changed, 464 insertions(+), 136 deletions(-)

base-commit: cbe54fc3462b3949ab27b9ae81fb9ddb509040c7

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#1 lore raw

RFC PATCH 1/26 perf/core: Fix lockless time read for exclude_guest events

When a host perf event has exclude_guest=1, its elapsed time should exclude guest time. However, lockless time reads through __perf_event_time_ctx_now() only subtracts guest time while a guest context is loaded, unlike __perf_event_time_ctx(). As a result, time_enabled and time_running read locklessly include past guest time after the guest context is put.

Subtract guest time regardless of whether a guest context is loaded. Guest time does not advance while no guest context is loaded, so use the accumulated guest time in that case.

Undo a minor optimization that avoids adding and subtracting 'now' while a guest context is loaded, to make it clearer that guest time is always subtracted, and only how it's calculated depends on whether a guest context is loaded.

Fixes 4593b4b6e218 ("perf: Add a EVENT_GUEST flag")
---
 kernel/events/core.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
kernel/events/core.c +12 -8
index f5f2261f1fe6f..6f076e5483cb7 100644
@@ -850,7 +850,7 @@ static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum e
 static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv)
 {
 	if (adv)
-		time->time += now - time->stamp;
+		WRITE_ONCE(time->time, time->time + now - time->stamp);
 	time->stamp = now;
 
 	/*
@@ -887,15 +887,19 @@ static inline u64 __perf_event_time_ctx_now(struct perf_event *event,
 					    struct perf_time_ctx *times,
 					    u64 now)
 {
-	if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) {
-		/*
-		 * (now + times[total].offset) - (now + times[guest].offset) :=
-		 * times[total].offset - times[guest].offset
-		 */
-		return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset);
+	u64 time = now + READ_ONCE(times[T_TOTAL].offset);
+	u64 guest_time;
+
+	if (event->attr.exclude_guest) {
+		if (is_guest_mediated_pmu_loaded())
+			guest_time = now + READ_ONCE(times[T_GUEST].offset);
+		else
+			guest_time = READ_ONCE(times[T_GUEST].time);
+
+		time -= guest_time;
 	}
 
-	return now + READ_ONCE(times[T_TOTAL].offset);
+	return time;
 }
 
 #ifdef CONFIG_CGROUP_PERF
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#2 lore raw

RFC PATCH 2/26 perf/core: Don't subtract guest time for events that keep counting

In reply to Yosry Ahmed

Currently, events with exclude_guest=1 in a non-mediated PMU context (e.g. software events) are not scheduled out while the guest context is loaded and keep counting, yet the guest time is subtracted from their time_running/time_enabled. This discrepancy grows if the guest context remains loaded beyond the KVM inner run loop (i.e. with dynamic PMU context switching).

Only subtract guest time for events that are actually scheduled out while the guest context is loaded (i.e. host-only events in a mediated-capable PMU context).

Software events with exclude_guest=0 grouped under a leader in a mediated PMU share the leader's PMU context, and are scheduled out while the guest context is loaded. Keep counting guest time as enabled for those, as they miss guest time they asked to count, similar to being multiplexed.

Fixes 4593b4b6e218 ("perf: Add a EVENT_GUEST flag")
---
 kernel/events/core.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
kernel/events/core.c +14 -3
index 6f076e5483cb7..5a3e40155ce70 100644
@@ -176,7 +176,8 @@ enum event_type_t {
 	 * - In for_each_epc() to skip PMUs that don't support events in a
 	 *   MEDIATED_VPMU guest, i.e. don't need to be context switched.
 	 * - To indicate the start/end point of the events in a guest.  Guest
-	 *   running time is deducted for host-only (exclude_guest) events.
+	 *   running time is deducted for host-only (exclude_guest) events of
+	 *   MEDIATED_VPMU PMUs, which are scheduled out while the guest runs.
 	 */
 	EVENT_GUEST	= 0x40,
 	EVENT_FLAGS	= EVENT_CGROUP | EVENT_GUEST,
@@ -872,12 +873,22 @@ static_assert(offsetof(struct perf_event_context, timeguest) -
 #define T_TOTAL		0
 #define T_GUEST		1
 
+/*
+ * Exclude guest time only for host-only events in a mediated PMU context, as
+ * those are scheduled out while a guest with a mediated vPMU runs.
+ */
+static inline bool perf_event_exclude_guest_time(struct perf_event *event)
+{
+	return event->attr.exclude_guest &&
+	       (event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU);
+}
+
 static inline u64 __perf_event_time_ctx(struct perf_event *event,
 					struct perf_time_ctx *times)
 {
 	u64 time = times[T_TOTAL].time;
 
-	if (event->attr.exclude_guest)
+	if (perf_event_exclude_guest_time(event))
 		time -= times[T_GUEST].time;
 
 	return time;
@@ -890,7 +901,7 @@ static inline u64 __perf_event_time_ctx_now(struct perf_event *event,
 	u64 time = now + READ_ONCE(times[T_TOTAL].offset);
 	u64 guest_time;
 
-	if (event->attr.exclude_guest) {
+	if (perf_event_exclude_guest_time(event)) {
 		if (is_guest_mediated_pmu_loaded())
 			guest_time = now + READ_ONCE(times[T_GUEST].offset);
 		else
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#3 lore raw

Re: [RFC PATCH 02/26] perf/core: Don't subtract guest time for events that keep counting

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] perf/core: NULL pointer deref in perf_event_exclude_guest_time() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] perf/core: NULL pointer deref in perf_event_exclude_guest_time()
--

commit db83e3f1bd6bd93912ce35d2e1ee8eb8daf9be37
Author: Yosry Ahmed <[email protected]>

perf/core: Don't subtract guest time for events that keep counting

This commit restricts guest time subtraction to host-only events in a mediated-capable PMU context so that events in non-mediated PMU contexts do not have guest time subtracted while they continue counting.

Quoted 4 lines
kernel/events/core.c +0 -0
index 6f076e5483cb7..5a3e40155ce70 100644

[ ... ]

kernel/events/core.c static_assert(offsetof(struct perf_event_context, timeguest) - · line 884

Quoted 13 lines
kernel/events/core.c +9 -0
@@ -872,12 +873,22 @@ static_assert(offsetof(struct perf_event_context, timeguest) -
 #define T_TOTAL		0
 #define T_GUEST		1
 
+/*
+ * Exclude guest time only for host-only events in a mediated PMU context, as
+ * those are scheduled out while a guest with a mediated vPMU runs.
+ */
+static inline bool perf_event_exclude_guest_time(struct perf_event *event)
+{
+	return event->attr.exclude_guest &&
+	       (event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU);
+}

[Severity: High]
Can event->pmu_ctx be NULL here when reading a revoked event?

When perf_pmu_unregister() detaches an event, __pmu_detach_event() puts and clears event->pmu_ctx while event->ctx remains valid until the last file reference is dropped. If an event with exclude_guest=1 is held in a BPF_MAP_TYPE_PERF_EVENT_ARRAY map after its PMU is unregistered, calling bpf_perf_event_read_value() reaches perf_event_read_local() -> calc_timer_values() -> perf_event_time_now() -> perf_event_exclude_guest_time(), causing a NULL pointer dereference on event->pmu_ctx.

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

RFC PATCH 3/26 perf/core: Move is_guest_mediated_pmu_loaded() to the header

In reply to Yosry Ahmed

In preparation for using is_guest_mediated_pmu_loaded() in x86 perf code and in KVM, move it to perf_event.h. Make the per-CPU flag it reads global, renaming it to perf_guest_ctx_loaded to avoid polluting the global namespace, and export it to KVM.

No functional change intended.

---
 include/linux/perf_event.h | 13 +++++++++++++
 kernel/events/core.c       | 25 +++++++------------------
 2 files changed, 20 insertions(+), 18 deletions(-)
include/linux/perf_event.h +13 -0
index e1e11500df097..5ecd477bd6969 100644
@@ -1933,6 +1933,19 @@ int perf_create_mediated_pmu(void);
 void perf_release_mediated_pmu(void);
 void perf_load_guest_context(void);
 void perf_put_guest_context(void);
+
+DECLARE_PER_CPU(bool, perf_guest_ctx_loaded);
+
+static __always_inline bool is_guest_mediated_pmu_loaded(void)
+{
+	return __this_cpu_read(perf_guest_ctx_loaded);
+}
+
+#else /* !CONFIG_PERF_GUEST_MEDIATED_PMU */
+static __always_inline bool is_guest_mediated_pmu_loaded(void)
+{
+	return false;
+}
 #endif
 
 #else /* !CONFIG_PERF_EVENTS: */
kernel/events/core.c +7 -18
index 5a3e40155ce70..8fd1e19cf5ab9 100644
@@ -473,20 +473,6 @@ static cpumask_var_t perf_online_pkg_mask;
 static cpumask_var_t perf_online_sys_mask;
 static struct kmem_cache *perf_event_cache;
 
-#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
-static DEFINE_PER_CPU(bool, guest_ctx_loaded);
-
-static __always_inline bool is_guest_mediated_pmu_loaded(void)
-{
-	return __this_cpu_read(guest_ctx_loaded);
-}
-#else
-static __always_inline bool is_guest_mediated_pmu_loaded(void)
-{
-	return false;
-}
-#endif
-
 /*
  * perf event paranoia level:
  *  -1 - not paranoid at all
@@ -6377,6 +6363,9 @@ u64 perf_event_pause(struct perf_event *event, bool reset)
 EXPORT_SYMBOL_GPL(perf_event_pause);
 
 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
+DEFINE_PER_CPU(bool, perf_guest_ctx_loaded);
+EXPORT_SYMBOL_FOR_KVM(perf_guest_ctx_loaded);
+
 static atomic_t nr_include_guest_events __read_mostly;
 
 static atomic_t nr_mediated_pmu_vms __read_mostly;
@@ -6464,7 +6453,7 @@ void perf_load_guest_context(void)
 
 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
 
-	if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded)))
+	if (WARN_ON_ONCE(__this_cpu_read(perf_guest_ctx_loaded)))
 		return;
 
 	perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
@@ -6478,7 +6467,7 @@ void perf_load_guest_context(void)
 	if (cpuctx->task_ctx)
 		perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
 
-	__this_cpu_write(guest_ctx_loaded, true);
+	__this_cpu_write(perf_guest_ctx_loaded, true);
 }
 EXPORT_SYMBOL_GPL(perf_load_guest_context);
 
@@ -6490,7 +6479,7 @@ void perf_put_guest_context(void)
 
 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
 
-	if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded)))
+	if (WARN_ON_ONCE(!__this_cpu_read(perf_guest_ctx_loaded)))
 		return;
 
 	perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
@@ -6503,7 +6492,7 @@ void perf_put_guest_context(void)
 		perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
 	perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST);
 
-	__this_cpu_write(guest_ctx_loaded, false);
+	__this_cpu_write(perf_guest_ctx_loaded, false);
 }
 EXPORT_SYMBOL_GPL(perf_put_guest_context);
 #else
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#5 lore raw

RFC PATCH 4/26 perf/x86: Use irqsave guard in branch stack snapshotting callbacks

In reply to Yosry Ahmed

In preparation for adding an early return to these functions, use guard(irqsave)() instead of local_irq_{save,restore}(), which also drops the local flags variable. IRQs are no longer restored in __intel_pmu_snapshot_branch_stack(), but in its callers.

The guard saves IRQs at the same point local_irq_save() did and restores them at scope exit, after the PMU and LBR are re-enabled, so the branch-free window before the LBR is frozen is unchanged.

No functional change intended.

---
 arch/x86/events/amd/core.c   |  4 +---
 arch/x86/events/intel/core.c | 15 +++++----------
 2 files changed, 6 insertions(+), 13 deletions(-)
arch/x86/events/amd/core.c +1 -3
index 49b6b8fce5664..79a1c5f91b3af 100644
@@ -931,13 +931,12 @@ static int amd_pmu_handle_irq(struct pt_regs *regs)
 static int amd_pmu_v2_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int cnt)
 {
 	struct cpu_hw_events *cpuc;
-	unsigned long flags;
 
 	/*
 	 * The sequence of steps to freeze LBR should be completely inlined
 	 * and contain no branches to minimize contamination of LBR snapshot
 	 */
-	local_irq_save(flags);
+	guard(irqsave)();
 	amd_pmu_core_disable_all();
 	__amd_pmu_lbr_disable();
 
@@ -948,7 +947,6 @@ static int amd_pmu_v2_snapshot_branch_stack(struct perf_branch_entry *entries, u
 	memcpy(entries, cpuc->lbr_entries, sizeof(struct perf_branch_entry) * cnt);
 
 	amd_pmu_v2_enable_all(0);
-	local_irq_restore(flags);
 
 	return cnt;
 }
arch/x86/events/intel/core.c +5 -10
index 0a34d674df590..4992cf76c7e83 100644
@@ -2817,7 +2817,7 @@ static void intel_pmu_enable_all(int added)
 
 static noinline int
 __intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries,
-				  unsigned int cnt, unsigned long flags)
+				  unsigned int cnt)
 {
 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
 
@@ -2826,34 +2826,29 @@ __intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries,
 
 	memcpy(entries, cpuc->lbr_entries, sizeof(struct perf_branch_entry) * cnt);
 	intel_pmu_enable_all(0);
-	local_irq_restore(flags);
 	return cnt;
 }
 
 static int
 intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int cnt)
 {
-	unsigned long flags;
-
 	/* must not have branches... */
-	local_irq_save(flags);
+	guard(irqsave)();
 	__intel_pmu_disable_all(false); /* we don't care about BTS */
 	__intel_pmu_lbr_disable();
 	/*            ... until here */
-	return __intel_pmu_snapshot_branch_stack(entries, cnt, flags);
+	return __intel_pmu_snapshot_branch_stack(entries, cnt);
 }
 
 static int
 intel_pmu_snapshot_arch_branch_stack(struct perf_branch_entry *entries, unsigned int cnt)
 {
-	unsigned long flags;
-
 	/* must not have branches... */
-	local_irq_save(flags);
+	guard(irqsave)();
 	__intel_pmu_disable_all(false); /* we don't care about BTS */
 	__intel_pmu_arch_lbr_disable();
 	/*            ... until here */
-	return __intel_pmu_snapshot_branch_stack(entries, cnt, flags);
+	return __intel_pmu_snapshot_branch_stack(entries, cnt);
 }
 
 /*
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#6 lore raw

RFC PATCH 5/26 perf/x86: Don't snapshot the branch stack while a guest PMU is loaded

In reply to Yosry Ahmed

The branch stack snapshot callbacks behind perf_snapshot_branch_stack() (used by bpf_get_branch_snapshot()) freeze the LBRs by disabling the PMU, copy the entries, and re-enable the PMU. If a guest's mediated vPMU context is loaded, e.g. if the snapshot is taken from NMI context or within KVM's inner run loop, re-enabling the PMU writes the host's GLOBAL_CTRL over the guest's PMU state.

On Intel, guest counters then count host code (and can raise PMIs delivered to the guest) until the next VM-Enter. On AMD, the guest's GLOBAL_CTRL itself is overwritten. KVM putting the guest context lazily would make this worse, as the guest context would also stay loaded while handling slowpath VM-Exits, e.g. across KVM tracepoints.

The snapshot isn't useful either: the host LBR users (core PMU events) are scheduled out while a guest context is loaded, so the LBRs aren't read, and callers get stale entries from the last time the LBRs were read for the host.

Return an empty snapshot if a guest context is loaded, before touching the PMU. Callers already handle empty snapshots, e.g. bpf_get_branch_snapshot() returns -ENOENT for 0 entries, which the default static call returns without LBR support.

Use unlikely() to hint to the compiler to lay out the not-taken path as the fall-through, so that the common path doesn't add a taken branch to the snapshot. Both GCC 15.2 and Clang 18.1.8 do this with the unlikely() hint, and emit a taken branch on the common path without it (GCC's -freorder-blocks, enabled at -O2 and -Os, uses __builtin_expect() probabilities to reduce taken branches [1]). If the hint isn't honored, the worst case is one extra branch entry in the snapshot.

[1] https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-freorder-blocks

Fixes 42457a7fb6cac ("perf: Add APIs to load/put guest mediated PMU context")
Cc Andrii Nakryiko <[email protected]>
Cc Song Liu <[email protected]>
---
 arch/x86/events/amd/core.c   |  8 ++++++++
 arch/x86/events/intel/core.c | 16 ++++++++++++++++
 2 files changed, 24 insertions(+)
arch/x86/events/amd/core.c +8 -0
index 79a1c5f91b3af..874beab47541a 100644
@@ -937,6 +937,14 @@ static int amd_pmu_v2_snapshot_branch_stack(struct perf_branch_entry *entries, u
 	 * and contain no branches to minimize contamination of LBR snapshot
 	 */
 	guard(irqsave)();
+
+	/*
+	 * Bail if the guest owns the PMU.  unlikely() hints the compiler to not
+	 * take a branch on the common path, which would pollute the snapshot.
+	 */
+	if (unlikely(is_guest_mediated_pmu_loaded()))
+		return 0;
+
 	amd_pmu_core_disable_all();
 	__amd_pmu_lbr_disable();
 
arch/x86/events/intel/core.c +16 -0
index 4992cf76c7e83..8972fe5c850c2 100644
@@ -2834,6 +2834,14 @@ intel_pmu_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int
 {
 	/* must not have branches... */
 	guard(irqsave)();
+
+	/*
+	 * Bail if the guest owns the PMU.  unlikely() hints the compiler to not
+	 * take a branch on the common path, which would pollute the snapshot.
+	 */
+	if (unlikely(is_guest_mediated_pmu_loaded()))
+		return 0;
+
 	__intel_pmu_disable_all(false); /* we don't care about BTS */
 	__intel_pmu_lbr_disable();
 	/*            ... until here */
@@ -2845,6 +2853,14 @@ intel_pmu_snapshot_arch_branch_stack(struct perf_branch_entry *entries, unsigned
 {
 	/* must not have branches... */
 	guard(irqsave)();
+
+	/*
+	 * Bail if the guest owns the PMU.  unlikely() hints the compiler to not
+	 * take a branch on the common path, which would pollute the snapshot.
+	 */
+	if (unlikely(is_guest_mediated_pmu_loaded()))
+		return 0;
+
 	__intel_pmu_disable_all(false); /* we don't care about BTS */
 	__intel_pmu_arch_lbr_disable();
 	/*            ... until here */
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#7 lore raw

RFC PATCH 6/26 perf/core: Guard against accessing guest mediated vPMU state

In reply to Yosry Ahmed

While iterating PMU contexts (i.e. using for_each_epc()) for purposes other than switching to/from guest context (i.e. other than EVENT_GUEST), skip contexts of mediated PMUs if the guest context is loaded, to avoid clobbering guest state (e.g. disabling/enabling the core PMU would overwrite the guest GLOBAL_CTRL on x86). The guest context should be put before any host events on those PMUs are activated, so WARN if the skipped PMUs have any active events.

In merge_sched_in(), WARN if the check for events on mediated PMUs is true, as that shouldn't happen anymore. merge_sched_in() is only reachable through:

- ctx_sched_in(): Uses for_each_epc(), which now skips such contexts.

- perf_rotate_context(): Rotation is never necessary for such PMUs while the guest context is loaded. rotate_necessary is cleared when the host contexts are scheduled out before loading the guest context, and only set again when the contexts are scheduled back in after the guest context is put.

---
 kernel/events/core.c | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)
kernel/events/core.c +17 -3
index 8fd1e19cf5ab9..78441df572487 100644
@@ -802,6 +802,18 @@ static bool perf_skip_pmu_ctx(struct perf_event_pmu_context *pmu_ctx,
 	if ((event_type & EVENT_GUEST) &&
 	    !(pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU))
 		return true;
+
+	/*
+	 * Except when loading/putting the guest vPMU context, accessing a
+	 * mediated PMU while the guest vPMU context is loaded would clobber
+	 * guest state.
+	 */
+	if (!(event_type & EVENT_GUEST) && is_guest_mediated_pmu_loaded() &&
+	    (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU)) {
+		WARN_ON_ONCE(perf_pmu_ctx_is_active(pmu_ctx));
+		return true;
+	}
+
 	return false;
 }
 
@@ -4139,13 +4151,15 @@ static int merge_sched_in(struct perf_event *event, void *data)
 		return 0;
 
 	/*
-	 * Don't schedule in any host events from PMU with
-	 * PERF_PMU_CAP_MEDIATED_VPMU, while a guest is running.
+	 * perf_skip_pmu_ctx() skips mediated PMUs while the guest vPMU context
+	 * is loaded, except when loading/putting it.
 	 */
 	if (is_guest_mediated_pmu_loaded() &&
 	    event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU &&
-	    !(msd->event_type & EVENT_GUEST))
+	    !(msd->event_type & EVENT_GUEST)) {
+		WARN_ON_ONCE(1);
 		return 0;
+	}
 
 	if (group_can_go_on(event, msd->can_add_hw)) {
 		if (!group_sched_in(event, ctx))
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#8 lore raw

RFC PATCH 7/26 perf: Add a guest callback to reclaim the mediated PMU

In reply to Yosry Ahmed

Add a reclaim_mediated_pmu() callback to perf_guest_info_callbacks, for perf to ask KVM to hand the PMU back to the host on the current CPU. This will be needed once KVM keeps the guest PMU context loaded beyond its inner run loop, i.e. with IRQs enabled, where perf can end up touching the PMU (e.g. installing new events) while the guest context is loaded.

No functional change intended, as KVM doesn't provide the callback yet.

---
 include/linux/perf_event.h | 7 +++++++
 kernel/events/core.c       | 6 ++++++
 virt/kvm/kvm_main.c        | 1 +
 3 files changed, 14 insertions(+)
include/linux/perf_event.h +7 -0
index 5ecd477bd6969..a83b9f2785301 100644
@@ -1685,6 +1685,7 @@ struct perf_guest_info_callbacks {
 	unsigned int			(*handle_intel_pt_intr)(void);
 
 	void				(*handle_mediated_pmi)(void);
+	void				(*reclaim_mediated_pmu)(void);
 };
 
 #ifdef CONFIG_GUEST_PERF_EVENTS
@@ -1695,6 +1696,7 @@ 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_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);
+DECLARE_STATIC_CALL(__perf_guest_reclaim_mediated_pmu, *perf_guest_cbs->reclaim_mediated_pmu);
 
 static inline unsigned int perf_guest_state(void)
 {
@@ -1716,6 +1718,11 @@ static inline void perf_guest_handle_mediated_pmi(void)
 	static_call(__perf_guest_handle_mediated_pmi)();
 }
 
+static inline void perf_guest_reclaim_mediated_pmu(void)
+{
+	static_call(__perf_guest_reclaim_mediated_pmu)();
+}
+
 extern void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs);
 extern void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs);
 
kernel/events/core.c +6 -0
index 78441df572487..2f301ef0bd26a 100644
@@ -7801,6 +7801,7 @@ 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_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);
+DEFINE_STATIC_CALL_RET0(__perf_guest_reclaim_mediated_pmu, *perf_guest_cbs->reclaim_mediated_pmu);
 
 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
 {
@@ -7819,6 +7820,10 @@ void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
 	if (cbs->handle_mediated_pmi)
 		static_call_update(__perf_guest_handle_mediated_pmi,
 				   cbs->handle_mediated_pmi);
+
+	if (cbs->reclaim_mediated_pmu)
+		static_call_update(__perf_guest_reclaim_mediated_pmu,
+				   cbs->reclaim_mediated_pmu);
 }
 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
 
@@ -7832,6 +7837,7 @@ void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
 	static_call_update(__perf_guest_get_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);
+	static_call_update(__perf_guest_reclaim_mediated_pmu, (void *)&__static_call_return0);
 	synchronize_rcu();
 }
 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
virt/kvm/kvm_main.c +1 -0
index 3746682b1a721..2b9a46bfd3696 100644
@@ -6599,6 +6599,7 @@ static struct perf_guest_info_callbacks kvm_guest_cbs = {
 	.get_ip			= kvm_guest_get_ip,
 	.handle_intel_pt_intr	= NULL,
 	.handle_mediated_pmi	= NULL,
+	.reclaim_mediated_pmu	= NULL,
 };
 
 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void),
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#9 lore raw

RFC PATCH 8/26 perf/core: Reclaim the mediated PMU before executing remote calls

In reply to Yosry Ahmed

Remote function calls (e.g. installing, enabling or disabling events) may alter the PMU state, which would clobber the guest's state if a guest's mediated PMU context is loaded on the target CPU. In preparation for KVM leaving the guest context loaded with IRQs enabled (where host events may get scheduled), reclaim the PMU before executing any remote call.

Hooking remote_function() is conservative, as only installing events through __perf_install_in_context() strictly needs to reclaim the PMU. However, hooking only event installation would be less future-proof, and would require perf_install_in_context() to not skip the IPI when installing a disabled event on a mediated-capable PMU, as the event could otherwise be enabled later through perf_event_enable() while the guest context is still loaded.

The PMU reclaim callback must be called with IRQs disabled and without perf context locks held (and hence isn't NMI-safe), as putting the guest context takes them. WARN if the guest context is still loaded after the callback.

No functional change intended, as the guest context is currently only loaded with IRQs disabled, so remote_function() never runs while it's loaded.

---
 include/linux/perf_event.h |  3 +++
 kernel/events/core.c       | 28 ++++++++++++++++++++++++++++
 2 files changed, 31 insertions(+)
include/linux/perf_event.h +3 -0
index a83b9f2785301..50b625f1aff20 100644
@@ -1938,6 +1938,7 @@ extern u64 perf_event_pause(struct perf_event *event, bool reset);
 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
 int perf_create_mediated_pmu(void);
 void perf_release_mediated_pmu(void);
+void perf_reclaim_mediated_pmu(void);
 void perf_load_guest_context(void);
 void perf_put_guest_context(void);
 
@@ -1953,6 +1954,8 @@ static __always_inline bool is_guest_mediated_pmu_loaded(void)
 {
 	return false;
 }
+
+static __always_inline void perf_reclaim_mediated_pmu(void) { }
 #endif
 
 #else /* !CONFIG_PERF_EVENTS: */
kernel/events/core.c +28 -0
index 2f301ef0bd26a..99aa56ced8253 100644
@@ -93,6 +93,13 @@ static void remote_function(void *data)
 			return;
 	}
 
+	/*
+	 * Reclaim the mediated vPMU from any potentially loaded guest context
+	 * before executing the remote function call, as it may alter the PMU
+	 * state (e.g. by installing new events).
+	 */
+	perf_reclaim_mediated_pmu();
+
 	tfc->ret = tfc->func(tfc->info);
 }
 
@@ -6425,6 +6432,27 @@ static void mediated_pmu_unaccount_event(struct perf_event *event)
 	atomic_dec(&nr_include_guest_events);
 }
 
+/*
+ * Reclaim the mediated vPMU from any loaded guest context on this CPU. This
+ * must be called with IRQs disabled and without any perf ctx locks held, and is
+ * not NMI-safe.
+ */
+void perf_reclaim_mediated_pmu(void)
+{
+	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
+
+	WARN_ON_ONCE(in_nmi());
+	lockdep_assert_irqs_disabled();
+	lockdep_assert_not_held(&cpuctx->ctx.lock);
+	if (cpuctx->task_ctx)
+		lockdep_assert_not_held(&cpuctx->task_ctx->lock);
+
+	if (is_guest_mediated_pmu_loaded()) {
+		perf_guest_reclaim_mediated_pmu();
+		WARN_ON_ONCE(is_guest_mediated_pmu_loaded());
+	}
+}
+
 /*
  * Currently invoked at VM creation to
  * - Check whether there are existing !exclude_guest events of PMU with
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#10 lore raw

RFC PATCH 9/26 perf/x86: Reclaim the mediated PMU before clearing dirty counters

In reply to Yosry Ahmed

perf_clear_dirty_counters() zeroes PMCs that aren't assigned to host events before enabling RDPMC for a task, so that it can't read stale values. It doesn't go through remote_function(), so it doesn't reclaim the PMU, and if a guest's mediated PMU context is loaded, the "dirty" counters hold guest state that clearing would clobber.

In preparation for KVM leaving the guest context loaded with IRQs enabled, reclaim the PMU before clearing dirty counters. Do so before filtering out the counters assigned to host events, as host events are scheduled out while the guest context is loaded, and putting the guest context schedules them back in, assigning counters to them.

No functional change intended, as the guest context is currently only loaded with IRQs disabled, where perf_clear_dirty_counters() never runs

---
 arch/x86/events/core.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/x86/events/core.c +8 -0
index 4e344fb1ae3ed..95ebdec4d5f5d 100644
@@ -3026,6 +3026,14 @@ void perf_clear_dirty_counters(void)
 	struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
 	int i;
 
+	/*
+	 * Reclaim the mediated vPMU from any loaded guest context before
+	 * accessing counters to avoid clobbering guest state.  Do so before
+	 * filtering out assigned counters, as putting the guest context can
+	 * schedule in host events.
+	 */
+	perf_reclaim_mediated_pmu();
+
 	 /* Don't need to clear the assigned counter. */
 	for (i = 0; i < cpuc->n_events; i++)
 		__clear_bit(cpuc->assign[i], cpuc->dirty);
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#11 lore raw

RFC PATCH 10/26 perf: Track mediated PMU conflicts

In reply to Yosry Ahmed

Track perf events conflicting with the mediated PMU, which are events on mediated-capable PMUs, or on PMUs using the same PMI delivery mechanism as the guest PMIs (LVTPC on x86). Add a new PMU capability for the latter, and set it for Intel PT and Intel BTS.

Whether or not perf has events conflicting with the mediated PMU will be used by KVM to determine if putting the guest PMU context on the VM-exit slowpath is necessary.

Intel BTS is never active while the guest runs, as KVM doesn't allow the guest to set DEBUGCTL.TR/BTS and VM-exit clears DEBUGCTL. Today, its interrupts can only be delivered to the guest in the short windows between loading the guest context and VM-entry, and between VM-exit and putting the guest context. Tracking it keeps those windows from extending to slowpath VM-exit handling.

Intel PT (in system mode) keeps tracing while the guest runs, so its interrupts can already be delivered to the guest today. Tracking it keeps that from extending to slowpath VM-exit handling.

---
 arch/x86/events/intel/bts.c |  3 ++-
 arch/x86/events/intel/pt.c  |  3 ++-
 include/linux/perf_event.h  | 11 ++++++++
 kernel/events/core.c        | 54 +++++++++++++++++++++++++++++++++++++
 4 files changed, 69 insertions(+), 2 deletions(-)
arch/x86/events/intel/bts.c +2 -1
index 5849392cf26d5..178fcb1bff7cc 100644
@@ -627,7 +627,8 @@ static __init int bts_init(void)
 		return -ENOMEM;
 
 	bts_pmu.capabilities	= PERF_PMU_CAP_AUX_NO_SG | PERF_PMU_CAP_ITRACE |
-				  PERF_PMU_CAP_EXCLUSIVE;
+				  PERF_PMU_CAP_EXCLUSIVE |
+				  PERF_PMU_CAP_USES_MEDIATED_PMI;
 	bts_pmu.task_ctx_nr	= perf_sw_context;
 	bts_pmu.event_init	= bts_event_init;
 	bts_pmu.add		= bts_event_add;
arch/x86/events/intel/pt.c +2 -1
index 3782af40f0832..5e3cd809bcb08 100644
@@ -1899,7 +1899,8 @@ static __init int pt_init(void)
 
 	pt_pmu.pmu.capabilities		|= PERF_PMU_CAP_EXCLUSIVE |
 					   PERF_PMU_CAP_ITRACE |
-					   PERF_PMU_CAP_AUX_PAUSE;
+					   PERF_PMU_CAP_AUX_PAUSE |
+					   PERF_PMU_CAP_USES_MEDIATED_PMI;
 	pt_pmu.pmu.attr_groups		 = pt_attr_groups;
 	pt_pmu.pmu.task_ctx_nr		 = perf_sw_context;
 	pt_pmu.pmu.event_init		 = pt_event_init;
include/linux/perf_event.h +11 -0
index 50b625f1aff20..1308b99a0abb6 100644
@@ -306,6 +306,7 @@ struct perf_event_pmu_context;
 #define PERF_PMU_CAP_AUX_PAUSE		0x0200
 #define PERF_PMU_CAP_MEDIATED_VPMU	0x0400
 #define PERF_PMU_CAP_SIMD_REGS		0x0800
+#define PERF_PMU_CAP_USES_MEDIATED_PMI	0x1000
 
 /**
  * pmu::scope
@@ -1032,6 +1033,10 @@ struct perf_event_context {
 	int				nr_user;
 	int				is_active;
 
+#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
+	int				nr_mediated_pmu_conflicts;
+#endif
+
 	int				nr_stat;
 	int				nr_freq;
 	int				rotate_disable;
@@ -1939,6 +1944,7 @@ extern u64 perf_event_pause(struct perf_event *event, bool reset);
 int perf_create_mediated_pmu(void);
 void perf_release_mediated_pmu(void);
 void perf_reclaim_mediated_pmu(void);
+bool perf_has_mediated_pmu_conflicts(void);
 void perf_load_guest_context(void);
 void perf_put_guest_context(void);
 
@@ -1956,6 +1962,11 @@ static __always_inline bool is_guest_mediated_pmu_loaded(void)
 }
 
 static __always_inline void perf_reclaim_mediated_pmu(void) { }
+
+static __always_inline bool perf_has_mediated_pmu_conflicts(void)
+{
+	return false;
+}
 #endif
 
 #else /* !CONFIG_PERF_EVENTS: */
kernel/events/core.c +54 -0

78 lines not on this page · raw message

Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#12 lore raw

Re: [RFC PATCH 10/26] perf: Track mediated PMU conflicts

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf: missed conflict accounting for grouped events in account_mediated_pmu_conflicts() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf: missed conflict accounting for grouped events in account_mediated_pmu_conflicts()
--

commit d02999449ac3f60478e5b2d635e9ec7e78dbd825
Author: Yosry Ahmed <[email protected]>

perf: Track mediated PMU conflicts

This commit tracks perf events that conflict with a guest mediated PMU in perf_event_context and exposes perf_has_mediated_pmu_conflicts() for KVM, marking Intel PT and Intel BTS with PERF_PMU_CAP_USES_MEDIATED_PMI.

Quoted 8 lines
kernel/events/core.c +0 -0
index 99aa56ced8253..33422b92dc0db 100644
@@ -1989,6 +1989,22 @@ static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
 	return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
 }
 

kernel/events/core.c static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr) · line 2001

Quoted 10 lines
kernel/events/core.c +10 -0
+#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
+static void account_mediated_pmu_conflicts(struct perf_event *event,
+					   struct perf_event_context *ctx,
+					   int nr)
+{
+	if (event->pmu_ctx->pmu->capabilities &
+	    (PERF_PMU_CAP_MEDIATED_VPMU | PERF_PMU_CAP_USES_MEDIATED_PMI))
+		WRITE_ONCE(ctx->nr_mediated_pmu_conflicts,
+			   ctx->nr_mediated_pmu_conflicts + nr);
+}

[Severity: Medium]
Should account_mediated_pmu_conflicts() check event->pmu->capabilities rather than event->pmu_ctx->pmu->capabilities?

Both Intel PT and Intel BTS set task_ctx_nr = perf_sw_context, so __do_sys_perf_event_open() gives their events PERF_EV_CAP_SOFTWARE. When an Intel PT or Intel BTS event is grouped with a non-software event on a PMU without PERF_PMU_CAP_MEDIATED_VPMU or PERF_PMU_CAP_USES_MEDIATED_PMI (for example via aux_output or move_group), event->pmu still points to pt_pmu or bts_pmu, but event->pmu_ctx->pmu points to the other PMU:

kernel/events/core.c:__do_sys_perf_event_open() {
    ...
		if (is_software_event(event) &&
		    !in_software_context(group_leader)) {
			pmu = group_leader->pmu_ctx->pmu;
		} else if (!is_software_event(event)) {
			if (is_software_event(group_leader) &&
			    (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
				move_group = 1;
			}
    ...
}

In that case ctx->nr_mediated_pmu_conflicts is left at 0 while the PT or BTS event is installed, so perf_has_mediated_pmu_conflicts() returns false and KVM leaves the guest mediated PMU context loaded during slowpath VM-exit handling.

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

RFC PATCH 11/26 KVM: x86/pmu: Move PMC MSR and type helpers earlier

In reply to Yosry Ahmed

Move {fixed_counter,gp_counter,gp_eventsel}_msr() above pmc_write_counter(), and pmc_is_{gp,fixed}() above pmc_read_counter(), in preparation for using them to access PMCs in hardware while the guest's mediated PMU context is loaded.

No functional change intended.

---
 arch/x86/kvm/pmu.c | 30 +++++++++++++++---------------
 arch/x86/kvm/pmu.h | 20 ++++++++++----------
 2 files changed, 25 insertions(+), 25 deletions(-)
arch/x86/kvm/pmu.c +15 -15
index eef2f792dc9e8..4d170abb2b384 100644
@@ -404,6 +404,21 @@ static void pmc_update_sample_period(struct kvm_pmc *pmc)
 			  get_sample_period(pmc, pmc->counter));
 }
 
+static __always_inline u32 fixed_counter_msr(u32 idx)
+{
+	return kvm_pmu_ops.FIXED_COUNTER_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
+}
+
+static __always_inline u32 gp_counter_msr(u32 idx)
+{
+	return kvm_pmu_ops.GP_COUNTER_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
+}
+
+static __always_inline u32 gp_eventsel_msr(u32 idx)
+{
+	return kvm_pmu_ops.GP_EVENTSEL_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
+}
+
 void pmc_write_counter(struct kvm_pmc *pmc, u64 val)
 {
 	if (kvm_vcpu_has_mediated_pmu(pmc->vcpu)) {
@@ -1304,21 +1319,6 @@ int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
 	return r;
 }
 
-static __always_inline u32 fixed_counter_msr(u32 idx)
-{
-	return kvm_pmu_ops.FIXED_COUNTER_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
-}
-
-static __always_inline u32 gp_counter_msr(u32 idx)
-{
-	return kvm_pmu_ops.GP_COUNTER_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
-}
-
-static __always_inline u32 gp_eventsel_msr(u32 idx)
-{
-	return kvm_pmu_ops.GP_EVENTSEL_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
-}
-
 static void kvm_pmu_load_guest_pmcs(struct kvm_vcpu *vcpu)
 {
 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
arch/x86/kvm/pmu.h +10 -10
index 090c9bbb74f48..ff4b6f15b915c 100644
@@ -127,6 +127,16 @@ static inline u64 pmc_bitmask(struct kvm_pmc *pmc)
 	return pmu->counter_bitmask[pmc->type];
 }
 
+static inline bool pmc_is_gp(struct kvm_pmc *pmc)
+{
+	return pmc->type == KVM_PMC_GP;
+}
+
+static inline bool pmc_is_fixed(struct kvm_pmc *pmc)
+{
+	return pmc->type == KVM_PMC_FIXED;
+}
+
 static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
 {
 	u64 counter, enabled, running;
@@ -145,16 +155,6 @@ static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
 
 void pmc_write_counter(struct kvm_pmc *pmc, u64 val);
 
-static inline bool pmc_is_gp(struct kvm_pmc *pmc)
-{
-	return pmc->type == KVM_PMC_GP;
-}
-
-static inline bool pmc_is_fixed(struct kvm_pmc *pmc)
-{
-	return pmc->type == KVM_PMC_FIXED;
-}
-
 static inline bool kvm_valid_perf_global_ctrl(struct kvm_pmu *pmu,
 						 u64 data)
 {
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#14 lore raw

RFC PATCH 12/26 KVM: x86/pmu: Access PMCs in hardware if the mediated PMU context is loaded

In reply to Yosry Ahmed

In preparation for leaving the guest's mediated PMU context loaded during slowpath VM-Exit handling, read and write the guest's counters in hardware if the guest context is loaded. While the guest context is loaded, the guest's counter values live in hardware, and KVM's software copies in pmc->counter may be stale, as they are only synced from hardware when the context is put.

Read counters with RDPMC, refreshing the software copy, and write them through to hardware in addition to updating the software copy. Use the accessors when incrementing counters for emulated instructions too, instead of updating pmc->counter directly. Updating the software copy while the guest context is loaded isn't strictly necessary, as it's synced from hardware when the context is put. This could be optimized by tracking whether the software copy is up-to-date.

Add kvm_pmu_guest_context_wrmsr() to write a guest PMU MSR only if the guest context is loaded, as it will be reused for other guest PMU registers, and document there which guest PMU state lives in hardware while the guest context is loaded.

Disable IRQs across checking whether the guest context is loaded and accessing the counter, as perf may reclaim the PMU via IPI and put the guest context.

---
 arch/x86/kvm/pmu.c | 21 ++++++++++++++++-----
 arch/x86/kvm/pmu.h | 32 +++++++++++++++++++++++++++++++-
 2 files changed, 47 insertions(+), 6 deletions(-)
arch/x86/kvm/pmu.c +16 -5
index 4d170abb2b384..6f82213058f14 100644
@@ -419,10 +419,19 @@ static __always_inline u32 gp_eventsel_msr(u32 idx)
 	return kvm_pmu_ops.GP_EVENTSEL_BASE + idx * kvm_pmu_ops.MSR_STRIDE;
 }
 
+static u32 pmc_counter_msr(struct kvm_pmc *pmc)
+{
+	return pmc_is_fixed(pmc) ?
+	       fixed_counter_msr(pmc->idx - KVM_FIXED_PMC_BASE_IDX) :
+	       gp_counter_msr(pmc->idx);
+}
+
 void pmc_write_counter(struct kvm_pmc *pmc, u64 val)
 {
 	if (kvm_vcpu_has_mediated_pmu(pmc->vcpu)) {
+		guard(irqsave)();
 		pmc->counter = val & pmc_bitmask(pmc);
+		kvm_pmu_guest_context_wrmsr(pmc_counter_msr(pmc), pmc->counter);
 		return;
 	}
 
@@ -1082,6 +1091,7 @@ static bool pmc_is_pmi_enabled(struct kvm_pmc *pmc)
 static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
 {
 	struct kvm_vcpu *vcpu = pmc->vcpu;
+	u64 counter;
 
 	/*
 	 * For perf-based PMUs, accumulate software-emulated events separately
@@ -1096,12 +1106,13 @@ static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
 	}
 
 	/*
-	 * For mediated PMUs, pmc->counter is updated when the vCPU's PMU is
-	 * put, and will be loaded into hardware when the PMU is loaded. Simply
-	 * increment the counter and signal overflow if it wraps to zero.
+	 * For mediated PMUs, the counter may be live in hardware or in
+	 * pmc->counter; the helpers will access it as needed. Signal overflow
+	 * if the counter wraps to zero after the increment.
 	 */
-	pmc->counter = (pmc->counter + 1) & pmc_bitmask(pmc);
-	if (!pmc->counter) {
+	counter = (pmc_read_counter(pmc) + 1) & pmc_bitmask(pmc);
+	pmc_write_counter(pmc, counter);
+	if (!counter) {
 		pmc_to_pmu(pmc)->global_status |= BIT_ULL(pmc->idx);
 		if (pmc_is_pmi_enabled(pmc))
 			kvm_make_request(KVM_REQ_PMI, vcpu);
arch/x86/kvm/pmu.h +31 -1
index ff4b6f15b915c..fe1baa50ebceb 100644
@@ -137,12 +137,24 @@ static inline bool pmc_is_fixed(struct kvm_pmc *pmc)
 	return pmc->type == KVM_PMC_FIXED;
 }
 
+static inline u64 pmc_rdpmc(struct kvm_pmc *pmc)
+{
+	if (pmc_is_fixed(pmc))
+		return rdpmc(INTEL_PMC_FIXED_RDPMC_BASE | (pmc->idx - KVM_FIXED_PMC_BASE_IDX));
+
+	return rdpmc(pmc->idx);
+}
+
 static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
 {
 	u64 counter, enabled, running;
 
-	if (kvm_vcpu_has_mediated_pmu(pmc->vcpu))
+	if (kvm_vcpu_has_mediated_pmu(pmc->vcpu)) {
+		guard(irqsave)();
+		if (is_guest_mediated_pmu_loaded())
+			pmc->counter = pmc_rdpmc(pmc);
 		return pmc->counter & pmc_bitmask(pmc);
+	}
 
 	counter = pmc->counter + pmc->emulated_counter;
 
@@ -153,6 +165,24 @@ static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
 	return counter & pmc_bitmask(pmc);
 }
 
+/*
+ * While the guest's mediated PMU context is loaded, the guest's PMU state
+ * lives in hardware.  State that changes while the guest runs and is only
+ * saved when the guest context is put (counters) must be read from
+ * hardware, and written to both hardware and the software copy.
+ *
+ * Write a guest PMU MSR, but only if the guest context is loaded on this
+ * CPU.  Callers must keep IRQs disabled across updating KVM's software copy
+ * and calling this, so that the two are atomic with respect to perf
+ * reclaiming the mediated PMU (via IPI) and putting the guest context.
+ */
+static inline void kvm_pmu_guest_context_wrmsr(u32 msr, u64 val)
+{
+	lockdep_assert_irqs_disabled();
+	if (is_guest_mediated_pmu_loaded())
+		wrmsrq(msr, val);
+}
+
 void pmc_write_counter(struct kvm_pmc *pmc, u64 val);
 
 static inline bool kvm_valid_perf_global_ctrl(struct kvm_pmu *pmu,
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#15 lore raw

RFC PATCH 13/26 KVM: x86/pmu: Compute eventsel_hw from eventsel when reprogramming

In reply to Yosry Ahmed

Instead of only setting the enable bit in eventsel_hw when refreshing the event filter, compute the entire eventsel_hw from eventsel when reprogramming a counter that's allowed to count, and rename kvm_mediated_pmu_refresh_event_filter() to kvm_mediated_pmu_reprogram_counter() accordingly. As counters are only allowed to count if the enable bit is set in eventsel, copying eventsel also sets the enable bit.

Move forcing GUESTONLY and clearing HOSTONLY on AMD from amd_pmu_set_msr() to the reprogramming path, using vendor-provided bits to set and clear, and have amd_pmu_set_msr() record the guest's value as-is like Intel. Writing an event selector always requests a reprogram, which is handled before the guest context is loaded, so the value is fixed up before it's written to hardware.

For counters that can't count, the event selector in hardware may now differ in the GUESTONLY and HOSTONLY bits, which is benign as the enable bit is cleared.

---
 arch/x86/kvm/pmu.c     | 8 ++++----
 arch/x86/kvm/pmu.h     | 2 ++
 arch/x86/kvm/svm/pmu.c | 5 +++--
 3 files changed, 9 insertions(+), 6 deletions(-)
arch/x86/kvm/pmu.c +4 -4
index 6f82213058f14..0a5299532c086 100644
@@ -570,7 +570,7 @@ static bool pmc_is_event_allowed(struct kvm_pmc *pmc)
 	return is_fixed_event_allowed(filter, pmc->idx);
 }
 
-static void kvm_mediated_pmu_refresh_event_filter(struct kvm_pmc *pmc)
+static void kvm_mediated_pmu_reprogram_counter(struct kvm_pmc *pmc)
 {
 	bool allowed = pmc_is_locally_enabled(pmc) && pmc_is_event_allowed(pmc);
 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
@@ -578,8 +578,8 @@ static void kvm_mediated_pmu_refresh_event_filter(struct kvm_pmc *pmc)
 	if (pmc_is_gp(pmc)) {
 		pmc->eventsel_hw &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
 		if (allowed)
-			pmc->eventsel_hw |= pmc->eventsel &
-					    ARCH_PERFMON_EVENTSEL_ENABLE;
+			pmc->eventsel_hw = (pmc->eventsel | kvm_pmu_ops.EVENTSEL_HW_SET) &
+					   ~kvm_pmu_ops.EVENTSEL_HW_CLR;
 	} else {
 		u64 mask = intel_fixed_bits_by_idx(pmc->idx - KVM_FIXED_PMC_BASE_IDX, 0xf);
 
@@ -598,7 +598,7 @@ static int reprogram_counter(struct kvm_pmc *pmc)
 	u8 fixed_ctr_ctrl;
 
 	if (kvm_vcpu_has_mediated_pmu(pmu_to_vcpu(pmu))) {
-		kvm_mediated_pmu_refresh_event_filter(pmc);
+		kvm_mediated_pmu_reprogram_counter(pmc);
 		return 0;
 	}
 
arch/x86/kvm/pmu.h +2 -0
index fe1baa50ebceb..462df3a9de491 100644
@@ -44,6 +44,8 @@ struct kvm_pmu_ops {
 	void (*write_global_ctrl)(u64 global_ctrl);
 
 	const u64 EVENTSEL_EVENT;
+	const u64 EVENTSEL_HW_SET;
+	const u64 EVENTSEL_HW_CLR;
 	const int MAX_NR_GP_COUNTERS;
 	const int MIN_NR_GP_COUNTERS;
 
arch/x86/kvm/svm/pmu.c +3 -2
index c18286545a7ac..232c4779e5a32 100644
@@ -166,8 +166,7 @@ static int amd_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 		data &= ~pmu->reserved_bits;
 		if (data != pmc->eventsel) {
 			pmc->eventsel = data;
-			pmc->eventsel_hw = (data & ~AMD64_EVENTSEL_HOSTONLY) |
-					   AMD64_EVENTSEL_GUESTONLY;
+			pmc->eventsel_hw = data;
 
 			if (data & AMD64_EVENTSEL_HOST_GUEST_MASK)
 				__set_bit(pmc->idx, pmu->pmc_has_mode_specific_enables);
@@ -317,6 +316,8 @@ struct kvm_pmu_ops amd_pmu_ops __initdata = {
 	.mediated_put = amd_mediated_pmu_put,
 
 	.EVENTSEL_EVENT = AMD64_EVENTSEL_EVENT,
+	.EVENTSEL_HW_SET = AMD64_EVENTSEL_GUESTONLY,
+	.EVENTSEL_HW_CLR = AMD64_EVENTSEL_HOSTONLY,
 	.MAX_NR_GP_COUNTERS = KVM_MAX_NR_AMD_GP_COUNTERS,
 	.MIN_NR_GP_COUNTERS = AMD64_NUM_COUNTERS,
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#16 lore raw

RFC PATCH 14/26 KVM: x86/pmu: Zero eventsel_hw for counters that can't count

In reply to Yosry Ahmed

When reprogramming a counter that can't count, zero eventsel_hw instead of only clearing the enable bit, so that putting the guest context doesn't need to clear its event selector in hardware. The guest's view is unaffected, as reads return eventsel, and the counter doesn't count either way.

---
 arch/x86/kvm/pmu.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
arch/x86/kvm/pmu.c +5 -1
index 0a5299532c086..44d947b854b9c 100644
@@ -576,7 +576,11 @@ static void kvm_mediated_pmu_reprogram_counter(struct kvm_pmc *pmc)
 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
 
 	if (pmc_is_gp(pmc)) {
-		pmc->eventsel_hw &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
+		/*
+		 * Leave eventsel_hw zero for counters that can't count, so that
+		 * they don't need to be cleared when putting the guest context.
+		 */
+		pmc->eventsel_hw = 0;
 		if (allowed)
 			pmc->eventsel_hw = (pmc->eventsel | kvm_pmu_ops.EVENTSEL_HW_SET) &
 					   ~kvm_pmu_ops.EVENTSEL_HW_CLR;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#17 lore raw

RFC PATCH 15/26 KVM: x86/pmu: Write PMU controls to hardware on reprogram if loaded

In reply to Yosry Ahmed

In preparation for leaving the guest's mediated PMU context loaded during slowpath VM-Exit handling, write eventsel_hw and fixed_ctr_ctrl_hw to hardware when reprogramming counters if the guest context is loaded.

Only update eventsel_hw and fixed_ctr_ctrl_hw when reprogramming counters, instead of also updating them when the guest writes the MSRs, to keep them in sync with hardware and keep the hardware writes in one place. Otherwise, if e.g. eventsel_hw is zeroed on an MSR write and the guest context is put before reprogramming, putting the context would skip clearing the event selector in hardware.

As fixed_ctr_ctrl_hw is no longer overwritten with the guest's value on MSR writes, compare against the guest's previous fixed_ctr_ctrl in reprogram_fixed_counters() again, effectively reverting commit 9c6e2463c9f3 ("KVM: x86/pmu: Use hardware value when reprogramming for FIXED_CTR_CTRL changes"). Comparing against fixed_ctr_ctrl_hw was only needed because the overwrite could leave counters that are disallowed by the event filter enabled in fixed_ctr_ctrl_hw without reprogramming them.

Disable IRQs across updating the software fields and writing hardware, so that the two are atomic with respect to perf reclaiming the mediated PMU (via IPI) and putting the guest context. Document which guest PMU registers are read from software and written through to hardware while the guest context is loaded.

---
 arch/x86/kvm/pmu.c           |  7 +++++++
 arch/x86/kvm/pmu.h           | 15 ++++++++++++---
 arch/x86/kvm/svm/pmu.c       |  1 -
 arch/x86/kvm/vmx/pmu_intel.c | 12 +-----------
 4 files changed, 20 insertions(+), 15 deletions(-)
arch/x86/kvm/pmu.c +7 -0
index 44d947b854b9c..ffee8a4741ee1 100644
@@ -575,6 +575,8 @@ static void kvm_mediated_pmu_reprogram_counter(struct kvm_pmc *pmc)
 	bool allowed = pmc_is_locally_enabled(pmc) && pmc_is_event_allowed(pmc);
 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
 
+	guard(irqsave)();
+
 	if (pmc_is_gp(pmc)) {
 		/*
 		 * Leave eventsel_hw zero for counters that can't count, so that
@@ -584,12 +586,17 @@ static void kvm_mediated_pmu_reprogram_counter(struct kvm_pmc *pmc)
 		if (allowed)
 			pmc->eventsel_hw = (pmc->eventsel | kvm_pmu_ops.EVENTSEL_HW_SET) &
 					   ~kvm_pmu_ops.EVENTSEL_HW_CLR;
+
+		kvm_pmu_guest_context_wrmsr(gp_eventsel_msr(pmc->idx), pmc->eventsel_hw);
 	} else {
 		u64 mask = intel_fixed_bits_by_idx(pmc->idx - KVM_FIXED_PMC_BASE_IDX, 0xf);
 
 		pmu->fixed_ctr_ctrl_hw &= ~mask;
 		if (allowed)
 			pmu->fixed_ctr_ctrl_hw |= pmu->fixed_ctr_ctrl & mask;
+
+		kvm_pmu_guest_context_wrmsr(MSR_CORE_PERF_FIXED_CTR_CTRL,
+					    pmu->fixed_ctr_ctrl_hw);
 	}
 }
 
arch/x86/kvm/pmu.h +12 -3
index 462df3a9de491..89d35a39b524b 100644
@@ -169,9 +169,18 @@ static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
 
 /*
  * While the guest's mediated PMU context is loaded, the guest's PMU state
- * lives in hardware.  State that changes while the guest runs and is only
- * saved when the guest context is put (counters) must be read from
- * hardware, and written to both hardware and the software copy.
+ * lives in hardware.  Guest PMU registers fall into two categories:
+ *
+ *  - State that changes while the guest runs and is only saved when the
+ *    guest context is put (counters) must be read from hardware, and
+ *    written to both hardware and the software copy.
+ *
+ *  - Controls whose software copy is always up to date (event selectors
+ *    and FIXED_CTR_CTRL) can be read from the software copy, but writes
+ *    must be propagated to hardware.  Guest writes to event selectors and
+ *    FIXED_CTR_CTRL are always intercepted.  Note, the value written to
+ *    hardware may differ from the guest-visible value, e.g. eventsel_hw
+ *    vs. eventsel.
  *
  * Write a guest PMU MSR, but only if the guest context is loaded on this
  * CPU.  Callers must keep IRQs disabled across updating KVM's software copy
arch/x86/kvm/svm/pmu.c +0 -1
index 232c4779e5a32..1b5ed347bf1df 100644
@@ -166,7 +166,6 @@ static int amd_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 		data &= ~pmu->reserved_bits;
 		if (data != pmc->eventsel) {
 			pmc->eventsel = data;
-			pmc->eventsel_hw = data;
 
 			if (data & AMD64_EVENTSEL_HOST_GUEST_MASK)
 				__set_bit(pmc->idx, pmu->pmc_has_mode_specific_enables);
arch/x86/kvm/vmx/pmu_intel.c +1 -11
index fb7ad53855f1d..69e8cc1b6732f 100644
@@ -57,20 +57,11 @@ static struct x86_pmu_lbr *vcpu_to_lbr_records(struct kvm_vcpu *vcpu)
 
 static void reprogram_fixed_counters(struct kvm_pmu *pmu, u64 data)
 {
-	/*
-	 * Compare against the value the mediated PMU shoves into hardware, not
-	 * the guest's desired value.  For the emulated PMU (proxied via perf),
-	 * they are one and the same (fixed_ctr_ctrl_hw isn't used other than
-	 * here).  For the mediated PMU, KVM needs to reprogram the actual MSR,
-	 * and so needs to react to potential changes in the value shoved into
-	 * hardware, e.g. to ensure the event filter is enforced.
-	 */
-	u64 old_fixed_ctr_ctrl = pmu->fixed_ctr_ctrl_hw;
 	struct kvm_pmc *pmc;
+	u64 old_fixed_ctr_ctrl = pmu->fixed_ctr_ctrl;
 	int i;
 
 	pmu->fixed_ctr_ctrl = data;
-	pmu->fixed_ctr_ctrl_hw = data;
 	for (i = 0; i < pmu->nr_arch_fixed_counters; i++) {
 		u8 new_ctrl = fixed_ctrl_field(data, i);
 		u8 old_ctrl = fixed_ctrl_field(old_fixed_ctr_ctrl, i);
@@ -445,7 +436,6 @@ static int intel_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 
 			if (data != pmc->eventsel) {
 				pmc->eventsel = data;
-				pmc->eventsel_hw = data;
 				kvm_pmu_request_counter_reprogram(pmc);
 			}
 			break;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#18 lore raw

RFC PATCH 16/26 KVM: x86/pmu: Write GLOBAL_CTRL to hardware if the guest context is loaded

In reply to Yosry Ahmed

In preparation for leaving the guest's mediated PMU context loaded during slowpath VM-Exit handling, write the guest's GLOBAL_CTRL to hardware on AMD if the guest context is loaded. On Intel, the guest's GLOBAL_CTRL lives in the VMCS and is loaded by hardware on VM-Enter, so intel_pmu_write_global_ctrl() already writes it to the right place.

Add kvm_pmu_set_global_ctrl() to update the software copy and forward the value to vendor code, and implement write_global_ctrl() for AMD using kvm_pmu_guest_context_wrmsr(). Disable IRQs across the update, so that checking whether the guest context is loaded and writing the MSR are atomic with respect to perf reclaiming the mediated PMU (via IPI) and putting the guest context.

Disabling IRQs isn't needed on Intel, as the VMCS isn't affected by perf reclaiming the PMU, but special casing Intel isn't worth the trouble. Alternatively, the software update and disabling IRQs could be moved into vendor code, but the software copy also needs to be updated for the emulated PMU (which doesn't use write_global_ctrl()), so keeping the update in common code is simpler.

Document GLOBAL_CTRL as a control that's read from the software copy and written through to hardware while the guest context is loaded.

---
 arch/x86/kvm/pmu.c     | 17 ++++++++++++-----
 arch/x86/kvm/pmu.h     | 14 ++++++++------
 arch/x86/kvm/svm/pmu.c |  6 ++++++
 3 files changed, 26 insertions(+), 11 deletions(-)
arch/x86/kvm/pmu.c +12 -5
index ffee8a4741ee1..d312f1b2f586a 100644
@@ -873,6 +873,16 @@ static void kvm_pmu_mark_pmc_in_use(struct kvm_vcpu *vcpu, u32 msr)
 		__set_bit(pmc->idx, pmu->pmc_in_use);
 }
 
+static void kvm_pmu_set_global_ctrl(struct kvm_vcpu *vcpu, u64 global_ctrl)
+{
+	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
+
+	guard(irqsave)();
+	pmu->global_ctrl = global_ctrl;
+	if (kvm_vcpu_has_mediated_pmu(vcpu))
+		kvm_pmu_call(write_global_ctrl)(global_ctrl);
+}
+
 int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 {
 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
@@ -934,15 +944,13 @@ int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 
 		if (pmu->global_ctrl != data) {
 			diff = pmu->global_ctrl ^ data;
-			pmu->global_ctrl = data;
 			kvm_pmu_request_counters_reprogram(pmu, diff);
 		}
 		/*
 		 * Unconditionally forward writes to vendor code, i.e. to the
 		 * VMC{B,S}, as pmu->global_ctrl is per-VCPU, not per-VMC{B,S}.
 		 */
-		if (kvm_vcpu_has_mediated_pmu(vcpu))
-			kvm_pmu_call(write_global_ctrl)(data);
+		kvm_pmu_set_global_ctrl(vcpu, data);
 		break;
 	case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
 		/*
@@ -1043,8 +1051,7 @@ void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
 	    (kvm_pmu_has_perf_global_ctrl(pmu) || kvm_vcpu_has_mediated_pmu(vcpu)))
 		pmu->global_ctrl = GENMASK_ULL(pmu->nr_arch_gp_counters - 1, 0);
 
-	if (kvm_vcpu_has_mediated_pmu(vcpu))
-		kvm_pmu_call(write_global_ctrl)(pmu->global_ctrl);
+	kvm_pmu_set_global_ctrl(vcpu, pmu->global_ctrl);
 
 	bitmap_set(pmu->all_valid_pmc_idx, 0, pmu->nr_arch_gp_counters);
 	bitmap_set(pmu->all_valid_pmc_idx, KVM_FIXED_PMC_BASE_IDX,
arch/x86/kvm/pmu.h +8 -6
index 89d35a39b524b..a83560ac51e00 100644
@@ -175,12 +175,14 @@ static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
  *    guest context is put (counters) must be read from hardware, and
  *    written to both hardware and the software copy.
  *
- *  - Controls whose software copy is always up to date (event selectors
- *    and FIXED_CTR_CTRL) can be read from the software copy, but writes
- *    must be propagated to hardware.  Guest writes to event selectors and
- *    FIXED_CTR_CTRL are always intercepted.  Note, the value written to
- *    hardware may differ from the guest-visible value, e.g. eventsel_hw
- *    vs. eventsel.
+ *  - Controls whose software copy is always up to date (event selectors,
+ *    FIXED_CTR_CTRL and GLOBAL_CTRL) can be read from the software copy,
+ *    but writes must be propagated to hardware.  Guest writes to event
+ *    selectors and FIXED_CTR_CTRL are always intercepted, and GLOBAL_CTRL
+ *    is saved on every VM-Exit if guest writes aren't intercepted.  Note,
+ *    the value written to hardware may differ from the guest-visible
+ *    value, e.g. eventsel_hw vs. eventsel, and the guest's GLOBAL_CTRL
+ *    lives in the VMCS on Intel.
  *
  * Write a guest PMU MSR, but only if the guest context is loaded on this
  * CPU.  Callers must keep IRQs disabled across updating KVM's software copy
arch/x86/kvm/svm/pmu.c +6 -0
index 1b5ed347bf1df..9c7d248f4ee10 100644
@@ -242,6 +242,11 @@ static bool amd_pmu_is_mediated_pmu_supported(struct x86_pmu_capability *host_pm
 	return host_pmu->version >= 2;
 }
 
+static void amd_pmu_write_global_ctrl(u64 global_ctrl)
+{
+	kvm_pmu_guest_context_wrmsr(MSR_AMD64_PERF_CNTR_GLOBAL_CTL, global_ctrl);
+}
+
 static void amd_mediated_pmu_load(struct kvm_vcpu *vcpu)
 {
 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
@@ -313,6 +318,7 @@ struct kvm_pmu_ops amd_pmu_ops __initdata = {
 	.is_mediated_pmu_supported = amd_pmu_is_mediated_pmu_supported,
 	.mediated_load = amd_mediated_pmu_load,
 	.mediated_put = amd_mediated_pmu_put,
+	.write_global_ctrl = amd_pmu_write_global_ctrl,
 
 	.EVENTSEL_EVENT = AMD64_EVENTSEL_EVENT,
 	.EVENTSEL_HW_SET = AMD64_EVENTSEL_GUESTONLY,
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#19 lore raw

RFC PATCH 17/26 KVM: x86/pmu: Ignore reserved bits on writes to GLOBAL_STATUS_CLR

In reply to Yosry Ahmed

In preparation for propagating GLOBAL_STATUS_CLR writes to hardware if the guest's mediated PMU context is loaded, ignore reserved bits when the guest writes AMD's GLOBAL_STATUS_CLR, as is already done for GLOBAL_STATUS_SET, so that guest-controlled reserved bits aren't written to hardware.

Writes to Intel's GLOBAL_OVF_CTRL, which share the code, are unaffected, as they already #GP if any reserved bits are set.

---
 arch/x86/kvm/pmu.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kvm/pmu.c +1 -1
index d312f1b2f586a..81278a64be43f 100644
@@ -962,7 +962,7 @@ int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 		fallthrough;
 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
 		if (!msr_info->host_initiated)
-			pmu->global_status &= ~data;
+			pmu->global_status &= ~(data & ~pmu->global_status_rsvd);
 		break;
 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
 		if (!msr_info->host_initiated)
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#20 lore raw

RFC PATCH 18/26 KVM: x86/pmu: Access GLOBAL_STATUS in hardware if the guest context is loaded

In reply to Yosry Ahmed

In preparation for leaving the guest's mediated PMU context loaded during slowpath VM-Exit handling, read and write the guest's GLOBAL_STATUS in hardware if the guest context is loaded. Hardware sets overflow bits in GLOBAL_STATUS while the guest runs, and KVM's software copy is only synced from hardware when the guest context is put.

Add helpers to read GLOBAL_STATUS, refreshing the software copy, and to clear and set bits via GLOBAL_STATUS_CLR and GLOBAL_STATUS_SET (GLOBAL_OVF_CTRL and GLOBAL_STATUS_SET on Intel), updating both the software copy and hardware. Use the helpers when signaling overflow of counters incremented for emulated instructions too, and disable IRQs across the whole increment to avoid toggling IRQs in each helper. Add the MSR indices to kvm_pmu_ops for use in common code.

As with counters, disable IRQs so that checking whether the guest context is loaded and accessing hardware are atomic with respect to perf reclaiming the mediated PMU (via IPI) and putting the guest context.

Document GLOBAL_STATUS as state that's read from hardware while the guest context is loaded.

---
 arch/x86/kvm/pmu.c           | 43 ++++++++++++++++++++++++++++++------
 arch/x86/kvm/pmu.h           |  7 ++++--
 arch/x86/kvm/svm/pmu.c       |  3 +++
 arch/x86/kvm/vmx/pmu_intel.c |  3 +++
 4 files changed, 47 insertions(+), 9 deletions(-)
arch/x86/kvm/pmu.c +36 -7
index 81278a64be43f..11d12093d3a6a 100644
@@ -187,6 +187,32 @@ void kvm_init_pmu_capability(struct kvm_pmu_ops *pmu_ops)
 		perf_get_hw_event_config(PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
 }
 
+/*
+ * GLOBAL_STATUS is updated by hardware (counter overflow) while the guest's
+ * mediated PMU context is loaded, so hardware is authoritative while loaded.
+ */
+static u64 kvm_pmu_read_global_status(struct kvm_pmu *pmu)
+{
+	guard(irqsave)();
+	if (is_guest_mediated_pmu_loaded())
+		rdmsrq(kvm_pmu_ops.PERF_GLOBAL_STATUS, pmu->global_status);
+	return pmu->global_status;
+}
+
+static void kvm_pmu_clear_global_status(struct kvm_pmu *pmu, u64 bits)
+{
+	guard(irqsave)();
+	pmu->global_status &= ~bits;
+	kvm_pmu_guest_context_wrmsr(kvm_pmu_ops.PERF_GLOBAL_STATUS_CLR, bits);
+}
+
+static void kvm_pmu_set_global_status(struct kvm_pmu *pmu, u64 bits)
+{
+	guard(irqsave)();
+	pmu->global_status |= bits;
+	kvm_pmu_guest_context_wrmsr(kvm_pmu_ops.PERF_GLOBAL_STATUS_SET, bits);
+}
+
 void kvm_handle_guest_mediated_pmi(void)
 {
 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
@@ -891,7 +917,7 @@ int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 	switch (msr) {
 	case MSR_CORE_PERF_GLOBAL_STATUS:
 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
-		msr_info->data = pmu->global_status;
+		msr_info->data = kvm_pmu_read_global_status(pmu);
 		break;
 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
 	case MSR_CORE_PERF_GLOBAL_CTRL:
@@ -962,11 +988,11 @@ int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 		fallthrough;
 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
 		if (!msr_info->host_initiated)
-			pmu->global_status &= ~(data & ~pmu->global_status_rsvd);
+			kvm_pmu_clear_global_status(pmu, data & ~pmu->global_status_rsvd);
 		break;
 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET:
 		if (!msr_info->host_initiated)
-			pmu->global_status |= data & ~pmu->global_status_rsvd;
+			kvm_pmu_set_global_status(pmu, data & ~pmu->global_status_rsvd);
 		break;
 	default:
 		kvm_pmu_mark_pmc_in_use(vcpu, msr_info->index);
@@ -1124,14 +1150,17 @@ static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
 	}
 
 	/*
-	 * For mediated PMUs, the counter may be live in hardware or in
-	 * pmc->counter; the helpers will access it as needed. Signal overflow
-	 * if the counter wraps to zero after the increment.
+	 * For mediated PMUs, the counter and GLOBAL_STATUS may be live in
+	 * hardware or in software fields; the helpers will update them as
+	 * needed. Disable IRQs throughout to avoid toggling IRQs in every
+	 * helper. Signal overflow if the counter wraps to zero after the
+	 * increment.
 	 */
+	guard(irqsave)();
 	counter = (pmc_read_counter(pmc) + 1) & pmc_bitmask(pmc);
 	pmc_write_counter(pmc, counter);
 	if (!counter) {
-		pmc_to_pmu(pmc)->global_status |= BIT_ULL(pmc->idx);
+		kvm_pmu_set_global_status(pmc_to_pmu(pmc), BIT_ULL(pmc->idx));
 		if (pmc_is_pmi_enabled(pmc))
 			kvm_make_request(KVM_REQ_PMI, vcpu);
 	}
arch/x86/kvm/pmu.h +5 -2
index a83560ac51e00..6a340a66e9246 100644
@@ -50,6 +50,9 @@ struct kvm_pmu_ops {
 	const int MIN_NR_GP_COUNTERS;
 
 	const u32 PERF_GLOBAL_CTRL;
+	const u32 PERF_GLOBAL_STATUS;
+	const u32 PERF_GLOBAL_STATUS_CLR;
+	const u32 PERF_GLOBAL_STATUS_SET;
 	const u32 GP_EVENTSEL_BASE;
 	const u32 GP_COUNTER_BASE;
 	const u32 FIXED_COUNTER_BASE;
@@ -172,8 +175,8 @@ static inline u64 pmc_read_counter(struct kvm_pmc *pmc)
  * lives in hardware.  Guest PMU registers fall into two categories:
  *
  *  - State that changes while the guest runs and is only saved when the
- *    guest context is put (counters) must be read from hardware, and
- *    written to both hardware and the software copy.
+ *    guest context is put (counters and GLOBAL_STATUS) must be read from
+ *    hardware, and written to both hardware and the software copy.
  *
  *  - Controls whose software copy is always up to date (event selectors,
  *    FIXED_CTR_CTRL and GLOBAL_CTRL) can be read from the software copy,
arch/x86/kvm/svm/pmu.c +3 -0
index 9c7d248f4ee10..e81e83c3d43b9 100644
@@ -327,6 +327,9 @@ struct kvm_pmu_ops amd_pmu_ops __initdata = {
 	.MIN_NR_GP_COUNTERS = AMD64_NUM_COUNTERS,
 
 	.PERF_GLOBAL_CTRL = MSR_AMD64_PERF_CNTR_GLOBAL_CTL,
+	.PERF_GLOBAL_STATUS = MSR_AMD64_PERF_CNTR_GLOBAL_STATUS,
+	.PERF_GLOBAL_STATUS_CLR = MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR,
+	.PERF_GLOBAL_STATUS_SET = MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_SET,
 	.GP_EVENTSEL_BASE = MSR_F15H_PERF_CTL0,
 	.GP_COUNTER_BASE = MSR_F15H_PERF_CTR0,
 	.FIXED_COUNTER_BASE = 0,
arch/x86/kvm/vmx/pmu_intel.c +3 -0
index 69e8cc1b6732f..4d1370e0f97e7 100644
@@ -858,6 +858,9 @@ struct kvm_pmu_ops intel_pmu_ops __initdata = {
 	.MIN_NR_GP_COUNTERS = 1,
 
 	.PERF_GLOBAL_CTRL = MSR_CORE_PERF_GLOBAL_CTRL,
+	.PERF_GLOBAL_STATUS = MSR_CORE_PERF_GLOBAL_STATUS,
+	.PERF_GLOBAL_STATUS_CLR = MSR_CORE_PERF_GLOBAL_OVF_CTRL,
+	.PERF_GLOBAL_STATUS_SET = MSR_CORE_PERF_GLOBAL_STATUS_SET,
 	.GP_EVENTSEL_BASE = MSR_P6_EVNTSEL0,
 	.GP_COUNTER_BASE = MSR_IA32_PMC0,
 	.FIXED_COUNTER_BASE = MSR_CORE_PERF_FIXED_CTR0,
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#21 lore raw

RFC PATCH 19/26 KVM: x86/pmu: Sync the guest's LVTPC to hardware if the guest context is loaded

In reply to Yosry Ahmed

In preparation for leaving the guest's mediated PMU context loaded during slowpath VM-Exit handling, propagate writes to the guest's virtual LVTPC to hardware if the guest context is loaded.

The guest's LVTPC is emulated by KVM: guest writes are intercepted and only update the virtual LVTPC, and its mask bit is only written to the hardware LVTPC when the guest context is loaded. Currently, the guest context is put on every VM-Exit that isn't handled in the fastpath and loaded again before the next VM-Enter, and fastpath handlers never write the virtual LVTPC, so changes reach hardware before the guest runs again. Once the guest context stays loaded across slowpath VM-Exits, changes wouldn't reach hardware until the guest context is put and loaded again.

For example, KVM masks the virtual LVTPC when delivering a PMI. If the guest context is loaded while the virtual LVTPC is masked and then stays loaded, the guest unmasking LVTPC at the end of its PMI handler would only update the virtual LVTPC, leaving the hardware LVTPC masked, and the guest would stop getting PMIs.

Hook kvm_lapic_set_reg(), which handles all writes to the virtual LVTPC, except for kvm_apic_set_state() restoring the APIC state from userspace, which can't happen with the guest context loaded.

RFC note: Intel CPUs also set the mask bit in the hardware LVTPC when delivering a PMI. KVM emulates this by masking the virtual LVTPC, which is now propagated to hardware, but it doesn't do so if the guest's CPUID isn't Intel-compatible, or if delivering the PMI fails (e.g. the guest's APIC is hardware-disabled, or the virtual LVTPC has an invalid delivery mode). In those cases, the hardware LVTPC stays masked while the guest context stays loaded, instead of being unmasked at the next VM-Enter. Cross-vendor configurations aren't supported with a mediated PMU, and the other cases require a misconfigured guest, so this is ignored for now. If it matters, kvm_pmu_deliver_pmi() could resync the hardware LVTPC when the virtual LVTPC remains unmasked.

---
 arch/x86/kvm/lapic.c |  4 ++++
 arch/x86/kvm/pmu.c   | 15 +++++++++++++++
 arch/x86/kvm/pmu.h   |  1 +
 3 files changed, 20 insertions(+)
arch/x86/kvm/lapic.c +4 -0
index d341801b61cba..b554c0e949886 100644
@@ -46,6 +46,7 @@
 #include "cpuid.h"
 #include "hyperv.h"
 #include "smm.h"
+#include "pmu.h"
 
 #ifndef CONFIG_X86_64
 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
@@ -94,6 +95,9 @@ static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
 static inline void kvm_lapic_set_reg(struct kvm_lapic *apic, int reg_off, u32 val)
 {
 	apic_set_reg(apic->regs, reg_off, val);
+
+	if (reg_off == APIC_LVTPC)
+		kvm_pmu_sync_lvtpc(apic->vcpu, val);
 }
 
 static __always_inline u64 kvm_lapic_get_reg64(struct kvm_lapic *apic, int reg)
arch/x86/kvm/pmu.c +15 -0
index 11d12093d3a6a..cee3c4719dd14 100644
@@ -1403,6 +1403,21 @@ static void kvm_pmu_load_guest_pmcs(struct kvm_vcpu *vcpu)
 	}
 }
 
+/*
+ * Mirror a change of the guest's virtual LVTPC into hardware if the guest's
+ * mediated PMU context is loaded. Only the mask bit of the guest's LVTPC is
+ * reflected in hardware (perf owns the vector and delivery mode).
+ */
+void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc)
+{
+	if (!kvm_vcpu_has_mediated_pmu(vcpu))
+		return;
+
+	guard(irqsave)();
+	if (is_guest_mediated_pmu_loaded())
+		perf_load_guest_lvtpc(lvtpc);
+}
+
 void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
 {
 	if (!kvm_vcpu_has_mediated_pmu(vcpu) ||
arch/x86/kvm/pmu.h +1 -0
index 6a340a66e9246..317848ac3df7b 100644
@@ -330,6 +330,7 @@ void kvm_pmu_destroy(struct kvm_vcpu *vcpu);
 int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp);
 void kvm_pmu_instruction_retired(struct kvm_vcpu *vcpu);
 void kvm_pmu_branch_retired(struct kvm_vcpu *vcpu);
+void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc);
 void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu);
 void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu);
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#22 lore raw

RFC PATCH 20/26 KVM: x86/pmu: Check for a mediated PMU before loading/putting its context

In reply to Yosry Ahmed

Move the checks for whether the vCPU has a mediated PMU from kvm_mediated_pmu_load() and kvm_mediated_pmu_put() to their callers, in preparation for putting the guest context from more places, and conditionally on whether perf has events conflicting with the mediated PMU. The new callers need to check for a mediated PMU first anyway, e.g. to avoid querying perf or disabling IRQs for vCPUs without a mediated PMU.

No functional change intended.

---
 arch/x86/kvm/pmu.c | 6 ++----
 arch/x86/kvm/x86.c | 6 ++++--
 2 files changed, 6 insertions(+), 6 deletions(-)
arch/x86/kvm/pmu.c +2 -4
index cee3c4719dd14..e92a7a1f20a89 100644
@@ -1420,8 +1420,7 @@ void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc)
 
 void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
 {
-	if (!kvm_vcpu_has_mediated_pmu(vcpu) ||
-	    KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+	if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
 		return;
 
 	lockdep_assert_irqs_disabled();
@@ -1481,8 +1480,7 @@ static void kvm_pmu_put_guest_pmcs(struct kvm_vcpu *vcpu)
 
 void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
 {
-	if (!kvm_vcpu_has_mediated_pmu(vcpu) ||
-	    KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+	if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
 		return;
 
 	lockdep_assert_irqs_disabled();
arch/x86/kvm/x86.c +4 -2
index 2cd9ee316aada..8370ccceadb82 100644
@@ -8392,7 +8392,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 		run_flags |= KVM_RUN_LOAD_DEBUGCTL;
 	vcpu->arch.host_debugctl = debug_ctl;
 
-	kvm_mediated_pmu_load(vcpu);
+	if (kvm_vcpu_has_mediated_pmu(vcpu))
+		kvm_mediated_pmu_load(vcpu);
 
 	guest_timing_enter_irqoff();
 
@@ -8432,7 +8433,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 	kvm_load_host_pkru(vcpu);
 
-	kvm_mediated_pmu_put(vcpu);
+	if (kvm_vcpu_has_mediated_pmu(vcpu))
+		kvm_mediated_pmu_put(vcpu);
 
 	/*
 	 * Do this here before restoring debug registers on the host.  And
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#23 lore raw

RFC PATCH 21/26 KVM: x86/pmu: Make loading/putting the mediated PMU context idempotent

In reply to Yosry Ahmed

Make kvm_mediated_pmu_load() and kvm_mediated_pmu_put() bail if the guest context is already loaded or put, respectively, in preparation for leaving the guest context loaded across slowpath VM-Exits. kvm_mediated_pmu_load() will still be called on every vcpu_enter_guest(), even if the guest context is still loaded, and kvm_mediated_pmu_put() will be called from multiple paths, e.g. on slowpath VM-Exits, on vcpu_put(), and when perf reclaims the mediated PMU, any of which may find the guest context already put.

Checking the per-CPU state is sufficient, as only the running vCPU's guest context can be loaded on a CPU: it is put on vcpu_put() before another vCPU can run.

Move lockdep_assert_irqs_disabled() before the checks, so that callers are verified to have IRQs disabled even if loading/putting is skipped.

---
 arch/x86/kvm/pmu.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
arch/x86/kvm/pmu.c +8 -6
index e92a7a1f20a89..d56cd0fa817d7 100644
@@ -1420,11 +1420,12 @@ void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc)
 
 void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu)
 {
-	if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
-		return;
-
 	lockdep_assert_irqs_disabled();
 
+	if (is_guest_mediated_pmu_loaded() ||
+	    KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+		return;
+
 	perf_load_guest_context();
 
 	/*
@@ -1480,11 +1481,12 @@ static void kvm_pmu_put_guest_pmcs(struct kvm_vcpu *vcpu)
 
 void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
 {
-	if (KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
-		return;
-
 	lockdep_assert_irqs_disabled();
 
+	if (!is_guest_mediated_pmu_loaded() ||
+	    KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
+		return;
+
 	/*
 	 * Defer handling of PERF_GLOBAL_CTRL to vendor code.  On Intel, it's
 	 * atomically cleared on VM-Exit, i.e. doesn't need to be clear here.
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#24 lore raw

RFC PATCH 22/26 KVM: x86/pmu: Put the mediated PMU context lazily on slowpath VM-Exits

In reply to Yosry Ahmed

Instead of putting the guest's mediated PMU context on every slowpath VM-Exit, only put it on slowpath VM-Exits if perf has events conflicting with the mediated PMU, i.e. events on mediated-capable PMUs or on PMUs that deliver interrupts like guest PMIs. Otherwise, leave the guest context loaded while handling slowpath VM-Exits, and put it when the vCPU is put (including when the vCPU task is scheduled out), or when perf reclaims the mediated PMU before accessing it for the host.

Saving and restoring the guest's PMU state on every slowpath VM-Exit is expensive. Below is the throughput (median of 10 x 5s runs) of a CPUID loop in a guest and of netperf TCP_RR between two guests, on AMD Turin and Intel Granite Rapids, with a mediated PMU before (eager) and after (lazy) this change, and without a vPMU. The rows are without perf events (idle), and with perf events in the guest, in the host, or both:

Turin Granite Rapids
eager lazy no vPMU eager lazy no vPMU
CPUID/s:

    idle        547.8K  1688.6K  1816.5K     687.9K  1386.2K  1352.5K
    guest perf  483.2K  1484.8K        -     631.6K  1266.7K        -
    host perf   342.1K   352.5K        -     418.4K   411.4K        -
    both        339.9K   338.4K        -     403.4K   396.2K        -
  TCP_RR/s:
    idle         43.4K    49.9K    50.4K      12.1K    13.7K    13.8K
    guest perf   42.5K    50.0K        -      12.0K    13.7K        -
    host perf    39.5K    40.1K        -      11.8K    12.0K        -
    both         39.7K    40.0K        -      11.8K    12.0K        -

Without perf events, CPUID throughput improves by 208% on Turin and 102% on Granite Rapids, reaching 93% and 100% of the throughput without a vPMU, and TCP_RR throughput improves by 15% and 13%, reaching 99% of the throughput without a vPMU. With host perf events, KVM still puts the guest context on every slowpath VM-Exit, and throughput is within 3% of before.

KVM already accesses guest PMU state in hardware while the guest context is loaded, including the LVTPC. Conflicting events can only be added after perf reclaims the mediated PMU, and conflicts are checked with IRQs disabled after the VM-Exit, so host events never run with the guest context loaded. As loading and putting the guest context is idempotent, it doesn't matter which path puts it first.

---
 arch/x86/kvm/pmu.c       | 10 ++++++++++
 arch/x86/kvm/pmu.h       |  1 +
 arch/x86/kvm/x86.c       | 10 ++++++++--
 include/linux/kvm_host.h |  5 +++--
 virt/kvm/kvm_main.c      |  4 +++-
 5 files changed, 25 insertions(+), 5 deletions(-)
arch/x86/kvm/pmu.c +10 -0
index d56cd0fa817d7..4879578c7d579 100644
@@ -223,6 +223,16 @@ void kvm_handle_guest_mediated_pmi(void)
 	kvm_make_request(KVM_REQ_PMI, vcpu);
 }
 
+void kvm_handle_mediated_pmu_reclaim(void)
+{
+	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
+
+	if (WARN_ON_ONCE(!vcpu || !kvm_vcpu_has_mediated_pmu(vcpu)))
+		return;
+
+	kvm_mediated_pmu_put(vcpu);
+}
+
 static inline void __kvm_perf_overflow(struct kvm_pmc *pmc, bool in_pmi)
 {
 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
arch/x86/kvm/pmu.h +1 -0
index 317848ac3df7b..89807e7a3c771 100644
@@ -73,6 +73,7 @@ extern bool enable_mediated_pmu;
 void kvm_pmu_ops_update(const struct kvm_pmu_ops *pmu_ops);
 
 void kvm_handle_guest_mediated_pmi(void);
+void kvm_handle_mediated_pmu_reclaim(void);
 
 static inline bool kvm_pmu_has_perf_global_ctrl(struct kvm_pmu *pmu)
 {
arch/x86/kvm/x86.c +8 -2
index 8370ccceadb82..7fb954ed8e84b 100644
@@ -2708,6 +2708,11 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
 		srcu_read_unlock(&vcpu->kvm->srcu, idx);
 	}
 
+	if (kvm_vcpu_has_mediated_pmu(vcpu)) {
+		scoped_guard(irqsave)
+			kvm_mediated_pmu_put(vcpu);
+	}
+
 	kvm_x86_call(vcpu_put)(vcpu);
 	vcpu->arch.last_host_tsc = rdtsc();
 }
@@ -7176,7 +7181,8 @@ int kvm_x86_vendor_init(struct kvm_x86_init_ops *ops)
 #endif
 
 	__kvm_register_perf_callbacks(ops->handle_intel_pt_intr,
-				      enable_mediated_pmu ? kvm_handle_guest_mediated_pmi : NULL);
+				      enable_mediated_pmu ? kvm_handle_guest_mediated_pmi : NULL,
+				      enable_mediated_pmu ? kvm_handle_mediated_pmu_reclaim : NULL);
 
 	if (IS_ENABLED(CONFIG_KVM_SW_PROTECTED_VM) && tdp_mmu_enabled)
 		kvm_caps.supported_vm_types |= BIT(KVM_X86_SW_PROTECTED_VM);
@@ -8433,7 +8439,7 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 	kvm_load_host_pkru(vcpu);
 
-	if (kvm_vcpu_has_mediated_pmu(vcpu))
+	if (kvm_vcpu_has_mediated_pmu(vcpu) && perf_has_mediated_pmu_conflicts())
 		kvm_mediated_pmu_put(vcpu);
 
 	/*
include/linux/kvm_host.h +3 -2
index 6debea9c255ee..3656fa2212c8e 100644
@@ -1825,11 +1825,12 @@ static inline bool kvm_arch_intc_initialized(struct kvm *kvm)
 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu);
 
 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void),
-				   void (*mediated_pmi_handler)(void));
+				   void (*mediated_pmi_handler)(void),
+				   void (*mediated_pmu_reclaim_handler)(void));
 
 static inline void kvm_register_perf_callbacks(void)
 {
-	__kvm_register_perf_callbacks(NULL, NULL);
+	__kvm_register_perf_callbacks(NULL, NULL, NULL);
 }
 
 void kvm_unregister_perf_callbacks(void);
virt/kvm/kvm_main.c +3 -1
index 2b9a46bfd3696..1bd3aa2227d28 100644
@@ -6603,10 +6603,12 @@ static struct perf_guest_info_callbacks kvm_guest_cbs = {
 };
 
 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void),
-				   void (*mediated_pmi_handler)(void))
+				   void (*mediated_pmi_handler)(void),
+				   void (*mediated_pmu_reclaim_handler)(void))
 {
 	kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler;
 	kvm_guest_cbs.handle_mediated_pmi = mediated_pmi_handler;
+	kvm_guest_cbs.reclaim_mediated_pmu = mediated_pmu_reclaim_handler;
 
 	perf_register_guest_info_callbacks(&kvm_guest_cbs);
 }
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#25 lore raw

Re: [RFC PATCH 22/26] KVM: x86/pmu: Put the mediated PMU context lazily on slowpath VM-Exits

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] KVM: x86/pmu: cgroup guest time corruption in kvm_arch_vcpu_put() on sched-out --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] KVM: x86/pmu: cgroup guest time corruption in kvm_arch_vcpu_put() on sched-out
--

commit 17f48d0588e7da0bb43ece63664106faa2d5150c
Author: Yosry Ahmed <[email protected]>

KVM: x86/pmu: Put the mediated PMU context lazily on slowpath VM-Exits

This commit keeps the guest mediated PMU context loaded across slowpath VM-Exits when there are no conflicting host perf events, deferring the put until vcpu_put() or when perf reclaims the mediated PMU.

Quoted 6 lines
arch/x86/kvm/x86.c +0 -0
index 8370ccceadb82..7fb954ed8e84b 100644
@@ -2708,6 +2708,11 @@ void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
 		srcu_read_unlock(&vcpu->kvm->srcu, idx);

arch/x86/kvm/x86.c void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu) · line 2718

Quoted 10 lines
arch/x86/kvm/x86.c +5 -0
 	}
 
+	if (kvm_vcpu_has_mediated_pmu(vcpu)) {
+		scoped_guard(irqsave)
+			kvm_mediated_pmu_put(vcpu);
+	}
+
 	kvm_x86_call(vcpu_put)(vcpu);
 	vcpu->arch.last_host_tsc = rdtsc();
 }

[Severity: Medium]
Can calling kvm_mediated_pmu_put() from kvm_arch_vcpu_put() during a task switch corrupt cgroup guest time accounting (info->timeguest.time) for the incoming task's cgroup?

When a vCPU takes a slowpath VM-Exit while a non-conflicting cgroup perf event (such as a software or uncore event) is active on the CPU, perf_has_mediated_pmu_conflicts() is false, so the guest mediated PMU context stays loaded with preemption enabled. If the vCPU task is then scheduled out to a task in another cgroup, prepare_task_switch() runs perf_event_task_sched_out() before fire_sched_out_preempt_notifiers():

kernel/sched/core.c:prepare_task_switch() {
    ...
	perf_event_task_sched_out(prev, next);
	fire_sched_out_preempt_notifiers(prev, next);
    ...
}

During the switch:

prepare_task_switch(prev, next)

    perf_event_task_sched_out(prev, next)
      ...
        perf_cgroup_switch(next)
          cpuctx->cgrp = cgrp;  /* switched to next's cgroup */
          ctx_sched_in(..., EVENT_ALL|EVENT_CGROUP)
            perf_cgroup_set_timestamp(cpuctx, false)
              /* sets info->time.stamp, leaves info->timeguest.stamp
               * uninitialized or stale on next's cgroup */
    fire_sched_out_preempt_notifiers(prev, next)
      kvm_sched_out()
        ...
          kvm_arch_vcpu_put()
            kvm_mediated_pmu_put()
              perf_put_guest_context()
                perf_event_sched_in(..., EVENT_GUEST)
                  ctx_sched_in(..., EVENT_PINNED | EVENT_GUEST)
                    update_cgrp_time_from_cpuctx(cpuctx, false)
                      __update_cgrp_guest_time(info, now, true)
                        info->timeguest.time += now - info->timeguest.stamp;

Because perf_guest_ctx_loaded is not cleared until the end of perf_put_guest_context(), update_cgrp_time_from_cpuctx() sees is_guest_mediated_pmu_loaded() == true and adds now - info->timeguest.stamp to next's cgroup using an uninitialized (0) or stale timestamp. This adds up to the full perf_clock() uptime to next's cgroup guest time and causes 64-bit unsigned underflow when computing enabled/running time for exclude_guest mediated PMU events in that cgroup.

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

RFC PATCH 23/26 KVM: x86/pmu: Add stats for mediated PMU context switches

In reply to Yosry Ahmed

Add per-vCPU stats counting how many times the guest's mediated PMU context is put, and why, mainly to help debug performance problems caused by frequent guest context switches, e.g. due to host perf events conflicting with the mediated PMU. The stats are also useful for testing. Add:

- pmu_ctx_switches: all puts of the guest context.

- pmu_ctx_switches_vmexit: puts on VM-Exits, because perf has events conflicting with the mediated PMU. Note, the guest context is only put on slowpath VM-Exits, not on every VM-Exit.

- pmu_ctx_switches_reclaim: puts because perf reclaimed the mediated PMU.

Don't add a stat for puts when the vCPU is put, e.g. when the vCPU task is scheduled out or KVM_RUN returns to userspace, as it can be derived from the other stats, and when exactly the vCPU is put is an implementation detail.

Return whether the guest context was actually put from kvm_mediated_pmu_put(), as it may already be put when perf reclaims the mediated PMU. The guest context is always loaded on slowpath VM-Exits for vCPUs with a mediated PMU, so WARN if it wasn't put there, and count the put unconditionally.

---
 arch/x86/include/asm/kvm_host.h |  3 +++
 arch/x86/kvm/pmu.c              | 11 ++++++++---
 arch/x86/kvm/pmu.h              |  2 +-
 arch/x86/kvm/x86.c              |  9 +++++++--
 4 files changed, 19 insertions(+), 6 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index 3efef3415f8e8..366b00ffa37f4 100644
@@ -1477,6 +1477,9 @@ struct kvm_vcpu_stat {
 	u64 preemption_other;
 	u64 guest_mode;
 	u64 notify_window_exits;
+	u64 pmu_ctx_switches;
+	u64 pmu_ctx_switches_vmexit;
+	u64 pmu_ctx_switches_reclaim;
 };
 
 struct x86_instruction_info;
arch/x86/kvm/pmu.c +8 -3
index 4879578c7d579..80229f3d477fb 100644
@@ -230,7 +230,8 @@ void kvm_handle_mediated_pmu_reclaim(void)
 	if (WARN_ON_ONCE(!vcpu || !kvm_vcpu_has_mediated_pmu(vcpu)))
 		return;
 
-	kvm_mediated_pmu_put(vcpu);
+	if (kvm_mediated_pmu_put(vcpu))
+		++vcpu->stat.pmu_ctx_switches_reclaim;
 }
 
 static inline void __kvm_perf_overflow(struct kvm_pmc *pmc, bool in_pmi)
@@ -1489,13 +1490,14 @@ static void kvm_pmu_put_guest_pmcs(struct kvm_vcpu *vcpu)
 	}
 }
 
-void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
+/* Returns true if the guest context was loaded and is now put. */
+bool kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
 {
 	lockdep_assert_irqs_disabled();
 
 	if (!is_guest_mediated_pmu_loaded() ||
 	    KVM_BUG_ON(!lapic_in_kernel(vcpu), vcpu->kvm))
-		return;
+		return false;
 
 	/*
 	 * Defer handling of PERF_GLOBAL_CTRL to vendor code.  On Intel, it's
@@ -1508,4 +1510,7 @@ void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu)
 	perf_put_guest_lvtpc();
 
 	perf_put_guest_context();
+
+	++vcpu->stat.pmu_ctx_switches;
+	return true;
 }
arch/x86/kvm/pmu.h +1 -1
index 89807e7a3c771..565e09b23c498 100644
@@ -333,7 +333,7 @@ void kvm_pmu_instruction_retired(struct kvm_vcpu *vcpu);
 void kvm_pmu_branch_retired(struct kvm_vcpu *vcpu);
 void kvm_pmu_sync_lvtpc(struct kvm_vcpu *vcpu, u32 lvtpc);
 void kvm_mediated_pmu_load(struct kvm_vcpu *vcpu);
-void kvm_mediated_pmu_put(struct kvm_vcpu *vcpu);
+bool kvm_mediated_pmu_put(struct kvm_vcpu *vcpu);
 
 bool is_vmware_backdoor_pmc(u32 pmc_idx);
 bool kvm_need_perf_global_ctrl_intercept(struct kvm_vcpu *vcpu);
arch/x86/kvm/x86.c +7 -2
index 7fb954ed8e84b..ca2a58079b019 100644
@@ -299,6 +299,9 @@ const struct kvm_stats_desc kvm_vcpu_stats_desc[] = {
 	STATS_DESC_COUNTER(VCPU, preemption_other),
 	STATS_DESC_IBOOLEAN(VCPU, guest_mode),
 	STATS_DESC_COUNTER(VCPU, notify_window_exits),
+	STATS_DESC_COUNTER(VCPU, pmu_ctx_switches),
+	STATS_DESC_COUNTER(VCPU, pmu_ctx_switches_vmexit),
+	STATS_DESC_COUNTER(VCPU, pmu_ctx_switches_reclaim),
 };
 
 const struct kvm_stats_header kvm_vcpu_stats_header = {
@@ -8439,8 +8442,10 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 	kvm_load_host_pkru(vcpu);
 
-	if (kvm_vcpu_has_mediated_pmu(vcpu) && perf_has_mediated_pmu_conflicts())
-		kvm_mediated_pmu_put(vcpu);
+	if (kvm_vcpu_has_mediated_pmu(vcpu) && perf_has_mediated_pmu_conflicts()) {
+		WARN_ON_ONCE(!kvm_mediated_pmu_put(vcpu));
+		++vcpu->stat.pmu_ctx_switches_vmexit;
+	}
 
 	/*
 	 * Do this here before restoring debug registers on the host.  And
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#27 lore raw

RFC PATCH 24/26 KVM: VMX: WARN if the Intel PT PMI handler runs for a mediated PMU

In reply to Yosry Ahmed

vmx_handle_intel_pt_intr() handles ToPA PMIs for guests using Intel PT by setting the ToPA bit in KVM's software copy of the guest's GLOBAL_STATUS, and requesting a PMI for the guest. This doesn't work with a mediated PMU, as the guest's GLOBAL_STATUS lives in hardware while the guest context is loaded, and the software copy is overwritten when the guest context is put. The GLOBAL_STATUS accessors can't be used instead, as the handler runs in NMI context.

The handler can't run for a vCPU with a mediated PMU though: while the guest context is loaded, the LVTPC routes PMIs to the mediated PMI vector, and perf ignores NMIs (see perf_event_nmi_handler()). NMIs from the guest are handled right after the VM-Exit, before the guest context can be put. WARN if it runs anyway.

Don't bail after the WARN, as handling the PMI is still the best effort:
the guest still gets a PMI, and setting the ToPA bit in the software copy is either correct (if the guest context is not loaded) or harmlessly lost. Bailing would drop the guest's PMI, and let perf handle the interrupt as a host Intel PT interrupt.

---
 arch/x86/kvm/vmx/vmx.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
arch/x86/kvm/vmx/vmx.c +10 -0
index 68fa251dda600..14d33b7ffcd93 100644
@@ -8484,6 +8484,16 @@ static unsigned int vmx_handle_intel_pt_intr(void)
 	if (!vcpu || !kvm_handling_nmi_from_guest(vcpu))
 		return 0;
 
+	/*
+	 * With a mediated PMU, LVTPC points at the mediated PMI vector while the
+	 * guest runs, so a guest ToPA PMI should never arrive as an NMI. Also,
+	 * hardware GLOBAL_STATUS is authoritative while the guest context is
+	 * loaded, and pmu->global_status is overwritten when it is put, so the
+	 * bit set below would be lost. The GLOBAL_STATUS accessors can't be used
+	 * here either, as this runs in NMI context.
+	 */
+	WARN_ON_ONCE(kvm_vcpu_has_mediated_pmu(vcpu));
+
 	kvm_make_request(KVM_REQ_PMI, vcpu);
 	__set_bit(MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI_BIT,
 		  (unsigned long *)&vcpu->arch.pmu.global_status);
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#28 lore raw

RFC PATCH 25/26 KVM: x86/pmu: WARN if a mediated PMI arrives outside of guest IRQ handling

In reply to Yosry Ahmed

Guest PMIs are delivered to KVM's mediated PMI handler while KVM handles IRQs that are pending after a VM-Exit, either because the PMI caused the VM-Exit, or because it was raised right before it. Guest counters don't count while host code runs (GLOBAL_CTRL is cleared on VM-Exit on Intel, and events are guest-only on AMD), so guest PMIs shouldn't arrive at any other time.

Now that the guest context can stay loaded while host code runs with IRQs enabled, a PMI arriving outside of guest IRQ handling would most likely be raised by a host PMU that perf failed to account for as conflicting with the mediated PMU, and misrouted to the guest. WARN in that case to catch such bugs.

In theory, the WARN could fire for a guest PMI that is delivered late, e.g. after KVM is done handling IRQs following a VM-Exit. Checking the guest's GLOBAL_STATUS for an overflow to rule this out doesn't work as the guest can clear it, making the WARN guest-triggerable. Such late guest PMIs haven't been observed when stress testing on 8 different platforms (Skylake, Cascade, Icelake, Sapphirerapids, Emeraldrapids, Graniterapids, Genoa, or Turin).

---
 arch/x86/kvm/pmu.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/x86/kvm/pmu.c +8 -0
index 80229f3d477fb..b1f949b9e05b5 100644
@@ -220,6 +220,14 @@ void kvm_handle_guest_mediated_pmi(void)
 	if (WARN_ON_ONCE(!vcpu || !kvm_vcpu_has_mediated_pmu(vcpu)))
 		return;
 
+	/*
+	 * Guest PMIs are delivered while KVM handles IRQs that are pending after
+	 * a VM-Exit, as guest counters don't count while host code runs.  A PMI
+	 * arriving at any other time was raised by a host PMU that perf failed
+	 * to account for, and was misrouted to the guest.
+	 */
+	WARN_ON_ONCE(vcpu->arch.handling_intr_from_guest != KVM_HANDLING_IRQ);
+
 	kvm_make_request(KVM_REQ_PMI, vcpu);
 }
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#29 lore raw

RFC PATCH 26/26 KVM: x86/pmu: Allow emulation in the fastpath with a mediated PMU

In reply to Yosry Ahmed

Effectively revert commit f7a65e58d643 ("KVM: x86/pmu: Disallow emulation in the fastpath if mediated PMCs are active"), as KVM no longer relies on its software copies of PMU state being consistent with hardware while the guest context is loaded.

KVM now accesses PMU registers in hardware if needed with the guest context loaded, and can therefore emulate instructions correctly in the fastpath with a mediated PMU. Specifically, KVM writes to hardware when incrementing counters or setting bits in GLOBAL_STATUS if the guest context is loaded.

When emulating an instruction in the fastpath, KVM increments PMCs that count instructions with the guest context loaded. KVM now updates counters and GLOBAL_STATUS in hardware in that case. kvm_pmu_trigger_event() reads GLOBAL_CTRL from software to determine which counters to increment, but the software copy is up to date even when the guest context is loaded: either guest writes are intercepted, or it's synced from hardware after every VM-Exit

---
 arch/x86/kvm/msrs.c |  3 ---
 arch/x86/kvm/pmu.h  | 10 ----------
 arch/x86/kvm/x86.c  |  6 ------
 3 files changed, 19 deletions(-)
arch/x86/kvm/msrs.c +0 -3
index c58889cf36f55..9f2172060d331 100644
@@ -924,9 +924,6 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_msr_write);
 
 static fastpath_t __handle_fastpath_wrmsr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
 {
-	if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
-		return EXIT_FASTPATH_NONE;
-
 	switch (msr) {
 	case APIC_BASE_MSR + (APIC_ICR >> 4):
 		if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(vcpu->arch.apic) ||
arch/x86/kvm/pmu.h +0 -10
index 565e09b23c498..5953f3e8a5d45 100644
@@ -308,16 +308,6 @@ static inline bool pmc_is_globally_enabled(struct kvm_pmc *pmc)
 	return test_bit(pmc->idx, (unsigned long *)&pmu->global_ctrl);
 }
 
-static inline bool kvm_pmu_is_fastpath_emulation_allowed(struct kvm_vcpu *vcpu)
-{
-	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
-
-	return !kvm_vcpu_has_mediated_pmu(vcpu) ||
-	       !bitmap_intersects(pmu->pmc_counting_instructions,
-				  (unsigned long *)&pmu->global_ctrl,
-				  X86_PMC_IDX_MAX);
-}
-
 void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu);
 int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned pmc, u64 *data);
 int kvm_pmu_check_rdpmc_early(struct kvm_vcpu *vcpu, unsigned int idx);
arch/x86/kvm/x86.c +0 -6
index ca2a58079b019..c1469a64c880d 100644
@@ -831,9 +831,6 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_invd);
 
 fastpath_t handle_fastpath_invd(struct kvm_vcpu *vcpu)
 {
-	if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
-		return EXIT_FASTPATH_NONE;
-
 	if (!kvm_emulate_invd(vcpu))
 		return EXIT_FASTPATH_EXIT_USERSPACE;
 
@@ -8780,9 +8777,6 @@ EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_emulate_halt);
 
 fastpath_t handle_fastpath_hlt(struct kvm_vcpu *vcpu)
 {
-	if (!kvm_pmu_is_fastpath_emulation_allowed(vcpu))
-		return EXIT_FASTPATH_NONE;
-
 	if (!kvm_emulate_halt(vcpu))
 		return EXIT_FASTPATH_EXIT_USERSPACE;
 
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
#30 lore raw
In reply to Yosry Ahmed
Sashiko has finished reviewing this 26-patch series:

Sashiko has finished reviewing this 26-patch series:

- Patches 1, 3-9, 11-21, and 23-26: no issues found.
- Patch 2 ("perf/core: Don't subtract guest time for events that..."): 1 potential issue (1 High)
- Patch 10 ("perf: Track mediated PMU conflicts"): 1 potential issue (1 Medium)
- Patch 22 ("KVM: x86/pmu: Put the mediated PMU context lazily on..."):
1 potential issue (1 Medium)

Detailed reviews have been sent as separate replies to patches 2, 10, and 22.

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