Skip to contentSkip to conversation

Allow user space to restrict and augment MSR emulation

PATCH Superseded Alexander Graf 3 participants 18 messages Sep 2, 2020 – Sep 17, 2020

Subsystems (6)
Documentation x86 KVM Kselftest +2 more subsystems

v6 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v6 cover Allow user space to restrict and augment MSR emulation

While tying to add support for the MSR_CORE_THREAD_COUNT MSR in KVM, I realized that we were still in a world where user space has no control over what happens with MSR emulation in KVM.

That is bad for multiple reasons. In my case, I wanted to emulate the MSR in user space, because it's a CPU specific register that does not exist on older CPUs and that really only contains informational data that is on the package level, so it's a natural fit for user space to provide it.

However, it is also bad on a platform compatibility level. Currrently, KVM has no way to expose different MSRs based on the selected target CPU type.

This patch set introduces a way for user space to indicate to KVM which MSRs should be handled in kernel space. With that, we can solve part of the platform compatibility story. Or at least we can not handle AMD specific MSRs on an Intel platform and vice versa.

In addition, it introduces a way for user space to get into the loop when an MSR access would generate a #GP fault, such as when KVM finds an MSR that is not handled by the in-kernel MSR emulation or when the guest is trying to access reserved registers.

In combination with filtering, user space trapping allows us to emulate arbitrary MSRs in user space, paving the way for target CPU specific MSR implementations from user space.

v1 -> v2:

- s/ETRAP_TO_USER_SPACE/ENOENT/g
- deflect all #GP injection events to user space, not just unknown MSRs. That was we can also deflect allowlist errors later
- fix emulator case
- new patch: KVM: x86: Introduce allow list for MSR emulation
- new patch: KVM: selftests: Add test for user space MSR handling

v2 -> v3:

- return r if r == X86EMUL_IO_NEEDED
- s/KVM_EXIT_RDMSR/KVM_EXIT_X86_RDMSR/g
- s/KVM_EXIT_WRMSR/KVM_EXIT_X86_WRMSR/g
- Use complete_userspace_io logic instead of reply field
- Simplify trapping code
- document flags for KVM_X86_ADD_MSR_ALLOWLIST
- generalize exit path, always unlock when returning
- s/KVM_CAP_ADD_MSR_ALLOWLIST/KVM_CAP_X86_MSR_ALLOWLIST/g
- Add KVM_X86_CLEAR_MSR_ALLOWLIST
- Add test to clear whitelist
- Adjust to reply-less API
- Fix asserts
- Actually trap on MSR_IA32_POWER_CTL writes

v3 -> v4:

- Mention exit reasons in re-enter mandatory section of API documentation
- Clear padding bytes
- Generalize get/set deflect functions
- Remove redundant pending_user_msr field
- lock allow check and clearing
- free bitmaps on clear

v4 -> v5:

- use srcu

v5 -> v6:

- Switch from allow list to filtering API with explicit fallback option
- Support and test passthrough MSR filtering
- Check for filter exit reason
- Add .gitignore
- send filter change notification
- change to atomic set_msr_filter ioctl with fallback flag
- use EPERM for filter blocks
- add bit for MSR user space deflection
- check for overflow of BITS_TO_LONGS (thanks Dan Carpenter!)
- s/int i;/u32 i;/
- remove overlap check
- Introduce exit reason mask to allow for future expansion and filtering
- s/emul_to_vcpu(ctxt)/vcpu/
- imported patch: KVM: x86: Prepare MSR bitmaps for userspace tracked MSRs
- new patch: KVM: x86: Add infrastructure for MSR filtering
- new patch: KVM: x86: SVM: Prevent MSR passthrough when MSR access is denied
- new patch: KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

Aaron Lewis (1):
KVM: x86: Prepare MSR bitmaps for userspace tracked MSRs

Alexander Graf (6):
KVM: x86: Deflect unknown MSR accesses to user space
KVM: x86: Add infrastructure for MSR filtering
KVM: x86: SVM: Prevent MSR passthrough when MSR access is denied
KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied
KVM: x86: Introduce MSR filtering
KVM: selftests: Add test for user space MSR handling

 Documentation/virt/kvm/api.rst                | 176 +++++++++-
 arch/x86/include/asm/kvm_host.h               |  18 ++
 arch/x86/include/uapi/asm/kvm.h               |  19 ++
 arch/x86/kvm/emulate.c                        |  18 +-
 arch/x86/kvm/svm/svm.c                        | 122 +++++--
 arch/x86/kvm/svm/svm.h                        |   7 +
 arch/x86/kvm/vmx/nested.c                     |   2 +-
 arch/x86/kvm/vmx/vmx.c                        | 303 ++++++++++++------
 arch/x86/kvm/vmx/vmx.h                        |   9 +-
 arch/x86/kvm/x86.c                            | 268 +++++++++++++++-
 arch/x86/kvm/x86.h                            |   1 +
 include/trace/events/kvm.h                    |   2 +-
 include/uapi/linux/kvm.h                      |  17 +
 tools/testing/selftests/kvm/.gitignore        |   1 +
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/x86_64/user_msr_test.c      | 224 +++++++++++++
 16 files changed, 1056 insertions(+), 132 deletions(-)
 create mode 100644 tools/testing/selftests/kvm/x86_64/user_msr_test.c
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#1 lore raw

PATCH v6 1/7 KVM: x86: Deflect unknown MSR accesses to user space

MSRs are weird. Some of them are normal control registers, such as EFER. Some however are registers that really are model specific, not very interesting to virtualization workloads, and not performance critical. Others again are really just windows into package configuration.

Out of these MSRs, only the first category is necessary to implement in kernel space. Rarely accessed MSRs, MSRs that should be fine tunes against certain CPU models and MSRs that contain information on the package level are much better suited for user space to process. However, over time we have accumulated a lot of MSRs that are not the first category, but still handled by in-kernel KVM code.

This patch adds a generic interface to handle WRMSR and RDMSR from user space. With this, any future MSR that is part of the latter categories can be handled in user space.

Furthermore, it allows us to replace the existing "ignore_msrs" logic with something that applies per-VM rather than on the full system. That way you can run productive VMs in parallel to experimental ones where you don't care about proper MSR handling.

---

v1 -> v2:

- s/ETRAP_TO_USER_SPACE/ENOENT/g
- deflect all #GP injection events to user space, not just unknown MSRs. That was we can also deflect allowlist errors later
- fix emulator case

v2 -> v3:

- return r if r == X86EMUL_IO_NEEDED
- s/KVM_EXIT_RDMSR/KVM_EXIT_X86_RDMSR/g
- s/KVM_EXIT_WRMSR/KVM_EXIT_X86_WRMSR/g
- Use complete_userspace_io logic instead of reply field
- Simplify trapping code

v3 -> v4:

- Mention exit reasons in re-inter mandatory section of API documentation
- Clear padding bytes
- Generalize get/set deflect functions
- Remove redundant pending_user_msr field

v5 -> v6:

- Introduce exit reason mask to allow for future expansion and filtering
- s/emul_to_vcpu(ctxt)/vcpu/

---
 Documentation/virt/kvm/api.rst  |  73 +++++++++++++++++++-
 arch/x86/include/asm/kvm_host.h |   3 +
 arch/x86/kvm/emulate.c          |  18 ++++-
 arch/x86/kvm/x86.c              | 119 ++++++++++++++++++++++++++++++--
 include/trace/events/kvm.h      |   2 +-
 include/uapi/linux/kvm.h        |  12 ++++
 6 files changed, 218 insertions(+), 9 deletions(-)
Documentation/virt/kvm/api.rst +71 -2
index 320788f81a05..1aab18e8c0c3 100644
@@ -4861,8 +4861,8 @@ to the byte array.
 
 .. note::
 
-      For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR and
-      KVM_EXIT_EPR the corresponding
+      For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR,
+      KVM_EXIT_EPR, KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR the corresponding
 
 operations are complete (and guest state is consistent) only after userspace
 has re-entered the kernel with KVM_RUN.  The kernel side will first finish
@@ -5155,6 +5155,42 @@ Note that KVM does not skip the faulting instruction as it does for
 KVM_EXIT_MMIO, but userspace has to emulate any change to the processing state
 if it decides to decode and emulate the instruction.
 
+::
+
+		/* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+		struct {
+			__u8 error; /* user -> kernel */
+			__u8 pad[3];
+			__u32 reason; /* kernel -> user */
+			__u32 index; /* kernel -> user */
+			__u64 data; /* kernel <-> user */
+		} msr;
+
+Used on x86 systems. When the VM capability KVM_CAP_X86_USER_SPACE_MSR is
+enabled, MSR accesses to registers that would invoke a #GP by KVM kernel code
+will instead trigger a KVM_EXIT_X86_RDMSR exit for reads and KVM_EXIT_X86_WRMSR
+exit for writes.
+
+The "reason" field specifies why the MSR trap occurred. User space will only
+receive MSR exit traps when a particular reason was requested during through
+ENABLE_CAP. Currently valid exit reasons are:
+
+	KVM_MSR_EXIT_REASON_INVAL - access to invalid MSRs or reserved bits
+
+For KVM_EXIT_X86_RDMSR, the "index" field tells user space which MSR the guest
+wants to read. To respond to this request with a successful read, user space
+writes the respective data into the "data" field and must continue guest
+execution to ensure the read data is transferred into guest register state.
+
+If the RDMSR request was unsuccessful, user space indicates that with a "1" in
+the "error" field. This will inject a #GP into the guest when the VCPU is
+executed again.
+
+For KVM_EXIT_X86_WRMSR, the "index" field tells user space which MSR the guest
+wants to write. Once finished processing the event, user space must continue
+vCPU execution. If the MSR write was unsuccessful, user space also sets the
+"error" field to "1".
+
 ::
 
 		/* Fix the size of the union. */
@@ -5844,6 +5880,28 @@ controlled by the kvm module parameter halt_poll_ns. This capability allows
 the maximum halt time to specified on a per-VM basis, effectively overriding
 the module parameter for the target VM.
 
+7.21 KVM_CAP_X86_USER_SPACE_MSR
+-------------------------------
+
+:Architectures: x86
+:Target: VM
+:Parameters: args[0] contains the mask of KVM_MSR_EXIT_REASON_* events to report
+:Returns: 0 on success; -1 on error
+
+This capability enables trapping of #GP invoking RDMSR and WRMSR instructions
+into user space.
+
+When a guest requests to read or write an MSR, KVM may not implement all MSRs
+that are relevant to a respective system. It also does not differentiate by
+CPU type.
+
+To allow more fine grained control over MSR handling, user space may enable
+this capability. With it enabled, MSR accesses that match the mask specified in
+args[0] and trigger a #GP event inside the guest by KVM will instead trigger
+KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR exit notifications which user space
+can then handle to implement model specific MSR handling and/or user notifications
+to inform a user that an MSR was not handled.
+
 8. Other capabilities.
 ======================
 
@@ -6151,3 +6209,14 @@ KVM can therefore start protected VMs.
 This capability governs the KVM_S390_PV_COMMAND ioctl and the
 KVM_MP_STATE_LOAD MP_STATE. KVM_SET_MP_STATE can fail for protected
 guests when the state change is invalid.
+
+8.24 KVM_CAP_X86_USER_SPACE_MSR
+----------------------------
+
+:Architectures: x86
+
+This capability indicates that KVM supports deflection of MSR reads and
+writes to user space. It can be enabled on a VM level. If enabled, MSR
+accesses that would usually trigger a #GP by KVM into the guest will
+instead get bounced to user space through the KVM_EXIT_X86_RDMSR and
+KVM_EXIT_X86_WRMSR exit notifications.
arch/x86/include/asm/kvm_host.h +3 -0
index be5363b21540..6608c8efbfa1 100644
@@ -1002,6 +1002,9 @@ struct kvm_arch {
 	bool guest_can_read_msr_platform_info;
 	bool exception_payload_enabled;
 
+	/* Deflect RDMSR and WRMSR to user space when they trigger a #GP */
+	u32 user_space_msr_mask;
+
 	struct kvm_pmu_event_filter *pmu_event_filter;
 	struct task_struct *nx_lpage_recovery_thread;
 };
arch/x86/kvm/emulate.c +16 -2
index d0e2825ae617..744ab9c92b73 100644
@@ -3689,11 +3689,18 @@ static int em_dr_write(struct x86_emulate_ctxt *ctxt)
 
 static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
 {
+	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
 	u64 msr_data;
+	int r;
 
 	msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX)
 		| ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32);
-	if (ctxt->ops->set_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), msr_data))
+	r = ctxt->ops->set_msr(ctxt, msr_index, msr_data);
+
+	if (r == X86EMUL_IO_NEEDED)
+		return r;
+
+	if (r)
 		return emulate_gp(ctxt, 0);
 
 	return X86EMUL_CONTINUE;
@@ -3701,9 +3708,16 @@ static int em_wrmsr(struct x86_emulate_ctxt *ctxt)
 
 static int em_rdmsr(struct x86_emulate_ctxt *ctxt)
 {
+	u64 msr_index = reg_read(ctxt, VCPU_REGS_RCX);
 	u64 msr_data;
+	int r;
+
+	r = ctxt->ops->get_msr(ctxt, msr_index, &msr_data);
+
+	if (r == X86EMUL_IO_NEEDED)
+		return r;
 
-	if (ctxt->ops->get_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &msr_data))
+	if (r)
 		return emulate_gp(ctxt, 0);
 
 	*reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data;
arch/x86/kvm/x86.c +115 -4

160 lines not on this page · raw message

include/trace/events/kvm.h +1 -1
index 9417a34aad08..26cfb0fa8e7e 100644
@@ -17,7 +17,7 @@
 	ERSN(NMI), ERSN(INTERNAL_ERROR), ERSN(OSI), ERSN(PAPR_HCALL),	\
 	ERSN(S390_UCONTROL), ERSN(WATCHDOG), ERSN(S390_TSCH), ERSN(EPR),\
 	ERSN(SYSTEM_EVENT), ERSN(S390_STSI), ERSN(IOAPIC_EOI),          \
-	ERSN(HYPERV), ERSN(ARM_NISV)
+	ERSN(HYPERV), ERSN(ARM_NISV), ERSN(X86_RDMSR), ERSN(X86_WRMSR)
 
 TRACE_EVENT(kvm_userspace_exit,
 	    TP_PROTO(__u32 reason, int errno),
include/uapi/linux/kvm.h +12 -0
index 4fdf30316582..a42841141cae 100644
@@ -248,6 +248,8 @@ struct kvm_hyperv_exit {
 #define KVM_EXIT_IOAPIC_EOI       26
 #define KVM_EXIT_HYPERV           27
 #define KVM_EXIT_ARM_NISV         28
+#define KVM_EXIT_X86_RDMSR        29
+#define KVM_EXIT_X86_WRMSR        30
 
 /* For KVM_EXIT_INTERNAL_ERROR */
 /* Emulate instruction failed. */
@@ -412,6 +414,15 @@ struct kvm_run {
 			__u64 esr_iss;
 			__u64 fault_ipa;
 		} arm_nisv;
+		/* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+		struct {
+			__u8 error; /* user -> kernel */
+			__u8 pad[3];
+#define KVM_MSR_EXIT_REASON_INVAL	(1 << 0)
+			__u32 reason; /* kernel -> user */
+			__u32 index; /* kernel -> user */
+			__u64 data; /* kernel <-> user */
+		} msr;
 		/* Fix the size of the union. */
 		char padding[256];
 	};
@@ -1031,6 +1042,7 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_PPC_SECURE_GUEST 181
 #define KVM_CAP_HALT_POLL 182
 #define KVM_CAP_ASYNC_PF_INT 183
+#define KVM_CAP_X86_USER_SPACE_MSR 184
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#7 lore raw

PATCH v6 2/7 KVM: x86: Add infrastructure for MSR filtering

In reply to Alexander Graf

In the following commits we will add pieces of MSR filtering. To ensure that code compiles even with the feature half-merged, let's add a few stubs and struct definitions before the real patches start.

---
 arch/x86/include/asm/kvm_host.h | 1 +
 arch/x86/include/uapi/asm/kvm.h | 2 ++
 arch/x86/kvm/x86.c              | 6 ++++++
 arch/x86/kvm/x86.h              | 1 +
 4 files changed, 10 insertions(+)
arch/x86/include/asm/kvm_host.h +1 -0
index 6608c8efbfa1..a9e3cc13bca6 100644
@@ -1272,6 +1272,7 @@ struct kvm_x86_ops {
 	int (*enable_direct_tlbflush)(struct kvm_vcpu *vcpu);
 
 	void (*migrate_timers)(struct kvm_vcpu *vcpu);
+	void (*msr_filter_changed)(struct kvm_vcpu *vcpu);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/include/uapi/asm/kvm.h +2 -0
index 0780f97c1850..50650cfd235a 100644
@@ -192,6 +192,8 @@ struct kvm_msr_list {
 	__u32 indices[0];
 };
 
+#define KVM_MSR_ALLOW_READ  (1 << 0)
+#define KVM_MSR_ALLOW_WRITE (1 << 1)
 
 struct kvm_cpuid_entry {
 	__u32 function;
arch/x86/kvm/x86.c +6 -0
index 4d285bf054fb..6024d1cdea5a 100644
@@ -1472,6 +1472,12 @@ void kvm_enable_efer_bits(u64 mask)
 }
 EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
 
+bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type)
+{
+	return true;
+}
+EXPORT_SYMBOL_GPL(kvm_msr_allowed);
+
 /*
  * Write @data into the MSR specified by @index.  Select MSR specific fault
  * checks are bypassed if @host_initiated is %true.
arch/x86/kvm/x86.h +1 -0
index 6eb62e97e59f..1d67d9168b8c 100644
@@ -365,5 +365,6 @@ void kvm_load_guest_xsave_state(struct kvm_vcpu *vcpu);
 void kvm_load_host_xsave_state(struct kvm_vcpu *vcpu);
 u64 kvm_spec_ctrl_valid_bits(struct kvm_vcpu *vcpu);
 bool kvm_vcpu_exit_request(struct kvm_vcpu *vcpu);
+bool kvm_msr_allowed(struct kvm_vcpu *vcpu, u32 index, u32 type);
 
 #endif
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#8 lore raw

PATCH v6 3/7 KVM: x86: Prepare MSR bitmaps for userspace tracked MSRs

In reply to Alexander Graf

From: Aaron Lewis <[email protected]>

Prepare vmx and svm for a subsequent change that ensures the MSR permission bitmap is set to allow an MSR that userspace is tracking to force a vmx_vmexit in the guest.

---
 arch/x86/kvm/svm/svm.c    | 48 +++++++++++-----------
 arch/x86/kvm/vmx/nested.c |  2 +-
 arch/x86/kvm/vmx/vmx.c    | 83 +++++++++++++++++++--------------------
 arch/x86/kvm/vmx/vmx.h    |  2 +-
 4 files changed, 67 insertions(+), 68 deletions(-)
arch/x86/kvm/svm/svm.c +25 -23
index c0da4dd78ac5..eb673b59f7b7 100644
@@ -564,7 +564,7 @@ static bool valid_msr_intercept(u32 index)
 	return false;
 }
 
-static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
+static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
 {
 	u8 bit_write;
 	unsigned long tmp;
@@ -583,9 +583,11 @@ static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
 	return !!test_bit(bit_write,  &tmp);
 }
 
-static void set_msr_interception(u32 *msrpm, unsigned msr,
-				 int read, int write)
+static void set_msr_interception(struct kvm_vcpu *vcpu, u32 msr, int read,
+				 int write)
 {
+	struct vcpu_svm *svm = to_svm(vcpu);
+	u32 *msrpm = svm->msrpm;
 	u8 bit_read, bit_write;
 	unsigned long tmp;
 	u32 offset;
@@ -609,7 +611,7 @@ static void set_msr_interception(u32 *msrpm, unsigned msr,
 	msrpm[offset] = tmp;
 }
 
-static void svm_vcpu_init_msrpm(u32 *msrpm)
+static void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
 {
 	int i;
 
@@ -619,7 +621,7 @@ static void svm_vcpu_init_msrpm(u32 *msrpm)
 		if (!direct_access_msrs[i].always)
 			continue;
 
-		set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
+		set_msr_interception(vcpu, direct_access_msrs[i].index, 1, 1);
 	}
 }
 
@@ -666,26 +668,26 @@ static void init_msrpm_offsets(void)
 	}
 }
 
-static void svm_enable_lbrv(struct vcpu_svm *svm)
+static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
 {
-	u32 *msrpm = svm->msrpm;
+	struct vcpu_svm *svm = to_svm(vcpu);
 
 	svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
-	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
-	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
-	set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
-	set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
+	set_msr_interception(vcpu, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
+	set_msr_interception(vcpu, MSR_IA32_LASTBRANCHTOIP, 1, 1);
+	set_msr_interception(vcpu, MSR_IA32_LASTINTFROMIP, 1, 1);
+	set_msr_interception(vcpu, MSR_IA32_LASTINTTOIP, 1, 1);
 }
 
-static void svm_disable_lbrv(struct vcpu_svm *svm)
+static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
 {
-	u32 *msrpm = svm->msrpm;
+	struct vcpu_svm *svm = to_svm(vcpu);
 
 	svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
-	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
-	set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
-	set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
-	set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
+	set_msr_interception(vcpu, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
+	set_msr_interception(vcpu, MSR_IA32_LASTBRANCHTOIP, 0, 0);
+	set_msr_interception(vcpu, MSR_IA32_LASTINTFROMIP, 0, 0);
+	set_msr_interception(vcpu, MSR_IA32_LASTINTTOIP, 0, 0);
 }
 
 void disable_nmi_singlestep(struct vcpu_svm *svm)
@@ -1196,10 +1198,10 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)
 	clear_page(svm->nested.hsave);
 
 	svm->msrpm = page_address(msrpm_pages);
-	svm_vcpu_init_msrpm(svm->msrpm);
+	svm_vcpu_init_msrpm(vcpu, svm->msrpm);
 
 	svm->nested.msrpm = page_address(nested_msrpm_pages);
-	svm_vcpu_init_msrpm(svm->nested.msrpm);
+	svm_vcpu_init_msrpm(vcpu, svm->nested.msrpm);
 
 	svm->vmcb = page_address(page);
 	clear_page(svm->vmcb);
@@ -2540,7 +2542,7 @@ static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 		 * We update the L1 MSR bit as well since it will end up
 		 * touching the MSR anyway now.
 		 */
-		set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
+		set_msr_interception(vcpu, MSR_IA32_SPEC_CTRL, 1, 1);
 		break;
 	case MSR_IA32_PRED_CMD:
 		if (!msr->host_initiated &&
@@ -2555,7 +2557,7 @@ static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 			break;
 
 		wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
-		set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
+		set_msr_interception(vcpu, MSR_IA32_PRED_CMD, 0, 1);
 		break;
 	case MSR_AMD64_VIRT_SPEC_CTRL:
 		if (!msr->host_initiated &&
@@ -2619,9 +2621,9 @@ static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
 		svm->vmcb->save.dbgctl = data;
 		mark_dirty(svm->vmcb, VMCB_LBR);
 		if (data & (1ULL<<0))
-			svm_enable_lbrv(svm);
+			svm_enable_lbrv(vcpu);
 		else
-			svm_disable_lbrv(svm);
+			svm_disable_lbrv(vcpu);
 		break;
 	case MSR_VM_HSAVE_PA:
 		svm->nested.hsave_msr = data;
arch/x86/kvm/vmx/nested.c +1 -1
index d4a4cec034d0..9313814d9e91 100644
@@ -4704,7 +4704,7 @@ static int enter_vmx_operation(struct kvm_vcpu *vcpu)
 
 	if (vmx_pt_mode_is_host_guest()) {
 		vmx->pt_desc.guest.ctl = 0;
-		pt_update_intercept_for_msr(vmx);
+		pt_update_intercept_for_msr(vcpu);
 	}
 
 	return 0;
arch/x86/kvm/vmx/vmx.c +40 -43

167 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.h +1 -1
index 639798e4a6ca..b3c74f0fe8a1 100644
@@ -350,7 +350,7 @@ bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
 void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
 void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu);
 struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr);
-void pt_update_intercept_for_msr(struct vcpu_vmx *vmx);
+void pt_update_intercept_for_msr(struct kvm_vcpu *vcpu);
 void vmx_update_host_rsp(struct vcpu_vmx *vmx, unsigned long host_rsp);
 int vmx_find_msr_index(struct vmx_msrs *m, u32 msr);
 int vmx_handle_memory_failure(struct kvm_vcpu *vcpu, int r,
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#9 lore raw

PATCH v6 4/7 KVM: x86: SVM: Prevent MSR passthrough when MSR access is denied

In reply to Alexander Graf

We will introduce the concept of MSRs that may not be handled in kernel space soon. Some MSRs are directly passed through to the guest, effectively making them handled by KVM from user space's point of view.

This patch introduces all logic required to ensure that MSRs that user space wants trapped are not marked as direct access for guests.

---
 arch/x86/kvm/svm/svm.c | 78 +++++++++++++++++++++++++++++++++++++-----
 arch/x86/kvm/svm/svm.h |  7 ++++
 2 files changed, 77 insertions(+), 8 deletions(-)
arch/x86/kvm/svm/svm.c +70 -8
index eb673b59f7b7..6a3f4017dd98 100644
@@ -91,7 +91,7 @@ static DEFINE_PER_CPU(u64, current_tsc_ratio);
 static const struct svm_direct_access_msrs {
 	u32 index;   /* Index of the MSR */
 	bool always; /* True if intercept is always on */
-} direct_access_msrs[] = {
+} direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
 	{ .index = MSR_STAR,				.always = true  },
 	{ .index = MSR_IA32_SYSENTER_CS,		.always = true  },
 #ifdef CONFIG_X86_64
@@ -553,15 +553,40 @@ static int svm_cpu_init(int cpu)
 
 }
 
-static bool valid_msr_intercept(u32 index)
+static int direct_access_msr_idx(u32 msr)
 {
-	int i;
+	u32 i;
 
 	for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
-		if (direct_access_msrs[i].index == index)
-			return true;
+		if (direct_access_msrs[i].index == msr)
+			return i;
 
-	return false;
+	return -EINVAL;
+}
+
+static void set_shadow_msr_intercept(struct vcpu_svm *svm, u32 msr, int read,
+				     int write)
+{
+	int idx = direct_access_msr_idx(msr);
+
+	if (idx == -EINVAL)
+		return;
+
+	/* Set the shadow bitmaps to the desired intercept states */
+	if (read)
+		set_bit(idx, svm->shadow_msr_intercept.read);
+	else
+		clear_bit(idx, svm->shadow_msr_intercept.read);
+
+	if (write)
+		set_bit(idx, svm->shadow_msr_intercept.write);
+	else
+		clear_bit(idx, svm->shadow_msr_intercept.write);
+}
+
+static bool valid_msr_intercept(u32 index)
+{
+	return direct_access_msr_idx(index) != -EINVAL;
 }
 
 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
@@ -583,8 +608,8 @@ static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
 	return !!test_bit(bit_write,  &tmp);
 }
 
-static void set_msr_interception(struct kvm_vcpu *vcpu, u32 msr, int read,
-				 int write)
+static void set_msr_interception_nosync(struct kvm_vcpu *vcpu, u32 msr,
+					int read, int write)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
 	u32 *msrpm = svm->msrpm;
@@ -598,6 +623,13 @@ static void set_msr_interception(struct kvm_vcpu *vcpu, u32 msr, int read,
 	 */
 	WARN_ON(!valid_msr_intercept(msr));
 
+	/* Enforce non allowed MSRs to trap */
+	if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_ALLOW_READ))
+		read = 0;
+
+	if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_ALLOW_WRITE))
+		write = 0;
+
 	offset    = svm_msrpm_offset(msr);
 	bit_read  = 2 * (msr & 0x0f);
 	bit_write = 2 * (msr & 0x0f) + 1;
@@ -611,6 +643,15 @@ static void set_msr_interception(struct kvm_vcpu *vcpu, u32 msr, int read,
 	msrpm[offset] = tmp;
 }
 
+static void set_msr_interception(struct kvm_vcpu *vcpu, u32 msr, int read,
+				 int write)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+
+	set_shadow_msr_intercept(svm, msr, read, write);
+	set_msr_interception_nosync(vcpu, msr, read, write);
+}
+
 static void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
 {
 	int i;
@@ -625,6 +666,25 @@ static void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
 	}
 }
 
+static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+	u32 i;
+
+	/*
+	 * Set intercept permissions for all direct access MSRs again. They
+	 * will automatically get filtered through the MSR filter, so we are
+	 * back in sync after this.
+	 */
+	for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
+		u32 msr = direct_access_msrs[i].index;
+		u32 read = test_bit(i, svm->shadow_msr_intercept.read);
+		u32 write = test_bit(i, svm->shadow_msr_intercept.write);
+
+		set_msr_interception_nosync(vcpu, msr, read, write);
+	}
+}
+
 static void add_msr_offset(u32 offset)
 {
 	int i;
@@ -4088,6 +4148,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.need_emulation_on_page_fault = svm_need_emulation_on_page_fault,
 
 	.apic_init_signal_blocked = svm_apic_init_signal_blocked,
+
+	.msr_filter_changed = svm_msr_filter_changed,
 };
 
 static struct kvm_x86_init_ops svm_init_ops __initdata = {
arch/x86/kvm/svm/svm.h +7 -0
index 6ac4c00a5d82..4c387470c27f 100644
@@ -31,6 +31,7 @@ static const u32 host_save_user_msrs[] = {
 
 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
 
+#define MAX_DIRECT_ACCESS_MSRS	15
 #define MSRPM_OFFSETS	16
 extern u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
 extern bool npt_enabled;
@@ -161,6 +162,12 @@ struct vcpu_svm {
 
 	/* which host CPU was used for running this vcpu */
 	unsigned int last_cpu;
+
+	/* Save desired MSR intercept (read: pass-through) state */
+	struct {
+		DECLARE_BITMAP(read, MAX_DIRECT_ACCESS_MSRS);
+		DECLARE_BITMAP(write, MAX_DIRECT_ACCESS_MSRS);
+	} shadow_msr_intercept;
 };
 
 struct svm_cpu_data {
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#10 lore raw

PATCH v6 5/7 KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

In reply to Alexander Graf

We will introduce the concept of MSRs that may not be handled in kernel space soon. Some MSRs are directly passed through to the guest, effectively making them handled by KVM from user space's point of view.

This patch introduces all logic required to ensure that MSRs that user space wants trapped are not marked as direct access for guests.

---
 arch/x86/kvm/vmx/vmx.c | 226 +++++++++++++++++++++++++++++++----------
 arch/x86/kvm/vmx/vmx.h |   7 ++
 2 files changed, 181 insertions(+), 52 deletions(-)
arch/x86/kvm/vmx/vmx.c +174 -52
index 1313e47a5a1e..6523f792652d 100644
@@ -148,6 +148,26 @@ module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
 #define MSR_IA32_RTIT_OUTPUT_BASE_MASK \
 	(~((1UL << cpuid_query_maxphyaddr(vcpu)) - 1) | 0x7f)
 
+/*
+ * List of MSRs that can be directly passed to the guest.
+ * In addition to these x2apic and PT MSRs are handled specially.
+ */
+static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSGHROUGH_MSRS] = {
+	MSR_IA32_SPEC_CTRL,
+	MSR_IA32_PRED_CMD,
+	MSR_IA32_TSC,
+	MSR_FS_BASE,
+	MSR_GS_BASE,
+	MSR_KERNEL_GS_BASE,
+	MSR_IA32_SYSENTER_CS,
+	MSR_IA32_SYSENTER_ESP,
+	MSR_IA32_SYSENTER_EIP,
+	MSR_CORE_C1_RES,
+	MSR_CORE_C3_RESIDENCY,
+	MSR_CORE_C6_RESIDENCY,
+	MSR_CORE_C7_RESIDENCY,
+};
+
 /*
  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
  * ple_gap:    upper bound on the amount of time between two successive
@@ -622,6 +642,41 @@ static inline bool report_flexpriority(void)
 	return flexpriority_enabled;
 }
 
+static int possible_passthrough_msr_idx(u32 msr)
+{
+	u32 i;
+
+	for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++)
+		if (vmx_possible_passthrough_msrs[i] == msr)
+			return i;
+
+	return -ENOENT;
+}
+
+static bool is_valid_passthrough_msr(u32 msr)
+{
+	bool r;
+
+	switch (msr) {
+	case 0x800 ... 0x8ff:
+		/* x2APIC MSRs. These are handled in vmx_update_msr_bitmap_x2apic() */
+		return true;
+	case MSR_IA32_RTIT_STATUS:
+	case MSR_IA32_RTIT_OUTPUT_BASE:
+	case MSR_IA32_RTIT_OUTPUT_MASK:
+	case MSR_IA32_RTIT_CR3_MATCH:
+	case MSR_IA32_RTIT_ADDR0_A ... MSR_IA32_RTIT_ADDR3_B:
+		/* PT MSRs. These are handled in pt_update_intercept_for_msr() */
+		return true;
+	}
+
+	r = possible_passthrough_msr_idx(msr) != -ENOENT;
+
+	WARN(!r, "Invalid MSR %x, please adapt vmx_possible_passthrough_msrs[]", msr);
+
+	return r;
+}
+
 static inline int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
 {
 	int i;
@@ -3690,12 +3745,51 @@ void free_vpid(int vpid)
 	spin_unlock(&vmx_vpid_lock);
 }
 
+static void vmx_clear_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
+{
+	int f = sizeof(unsigned long);
+
+	if (msr <= 0x1fff)
+		__clear_bit(msr, msr_bitmap + 0x000 / f);
+	else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
+		__clear_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
+}
+
+static void vmx_clear_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
+{
+	int f = sizeof(unsigned long);
+
+	if (msr <= 0x1fff)
+		__clear_bit(msr, msr_bitmap + 0x800 / f);
+	else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
+		__clear_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
+}
+
+static void vmx_set_msr_bitmap_read(ulong *msr_bitmap, u32 msr)
+{
+	int f = sizeof(unsigned long);
+
+	if (msr <= 0x1fff)
+		__set_bit(msr, msr_bitmap + 0x000 / f);
+	else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
+		__set_bit(msr & 0x1fff, msr_bitmap + 0x400 / f);
+}
+
+static void vmx_set_msr_bitmap_write(ulong *msr_bitmap, u32 msr)
+{
+	int f = sizeof(unsigned long);
+
+	if (msr <= 0x1fff)
+		__set_bit(msr, msr_bitmap + 0x800 / f);
+	else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff))
+		__set_bit(msr & 0x1fff, msr_bitmap + 0xc00 / f);
+}
+
 static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
 							  u32 msr, int type)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
-	int f = sizeof(unsigned long);
 
 	if (!cpu_has_vmx_msr_bitmap())
 		return;
@@ -3704,30 +3798,37 @@ static __always_inline void vmx_disable_intercept_for_msr(struct kvm_vcpu *vcpu,
 		evmcs_touch_msr_bitmap();
 
 	/*
-	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
-	 * have the write-low and read-high bitmap offsets the wrong way round.
-	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
-	 */
-	if (msr <= 0x1fff) {
-		if (type & MSR_TYPE_R)
-			/* read-low */
-			__clear_bit(msr, msr_bitmap + 0x000 / f);
+	 * Mark the desired intercept state in shadow bitmap, this is needed
+	 * for resync when the MSR filters change.
+	*/
+	if (is_valid_passthrough_msr(msr)) {
+		int idx = possible_passthrough_msr_idx(msr);
+
+		if (idx != -ENOENT) {
+			if (type & MSR_TYPE_R)
+				clear_bit(idx, vmx->shadow_msr_intercept.read);
+			if (type & MSR_TYPE_W)
+				clear_bit(idx, vmx->shadow_msr_intercept.write);
+		}
+	}
 
-		if (type & MSR_TYPE_W)
-			/* write-low */
-			__clear_bit(msr, msr_bitmap + 0x800 / f);
+	if ((type & MSR_TYPE_R) &&
+	    !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ)) {
+		vmx_set_msr_bitmap_read(msr_bitmap, msr);
+		type &= ~MSR_TYPE_R;
+	}
 
-	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
-		msr &= 0x1fff;
-		if (type & MSR_TYPE_R)
-			/* read-high */
-			__clear_bit(msr, msr_bitmap + 0x400 / f);
+	if ((type & MSR_TYPE_W) &&
+	    !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE)) {
+		vmx_set_msr_bitmap_write(msr_bitmap, msr);
+		type &= ~MSR_TYPE_W;
+	}
 
-		if (type & MSR_TYPE_W)
-			/* write-high */
-			__clear_bit(msr, msr_bitmap + 0xc00 / f);
+	if (type & MSR_TYPE_R)
+		vmx_clear_msr_bitmap_read(msr_bitmap, msr);
 
-	}
+	if (type & MSR_TYPE_W)
+		vmx_clear_msr_bitmap_write(msr_bitmap, msr);
 }
 
 static __always_inline void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu,
@@ -3735,7 +3836,6 @@ static __always_inline void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu,
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
 	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
-	int f = sizeof(unsigned long);
 
 	if (!cpu_has_vmx_msr_bitmap())
 		return;
@@ -3744,30 +3844,25 @@ static __always_inline void vmx_enable_intercept_for_msr(struct kvm_vcpu *vcpu,
 		evmcs_touch_msr_bitmap();
 
 	/*
-	 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
-	 * have the write-low and read-high bitmap offsets the wrong way round.
-	 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
-	 */
-	if (msr <= 0x1fff) {
-		if (type & MSR_TYPE_R)
-			/* read-low */
-			__set_bit(msr, msr_bitmap + 0x000 / f);
-
-		if (type & MSR_TYPE_W)
-			/* write-low */
-			__set_bit(msr, msr_bitmap + 0x800 / f);
-
-	} else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
-		msr &= 0x1fff;
-		if (type & MSR_TYPE_R)
-			/* read-high */
-			__set_bit(msr, msr_bitmap + 0x400 / f);
+	 * Mark the desired intercept state in shadow bitmap, this is needed
+	 * for resync when the MSR filter changes.
+	*/
+	if (is_valid_passthrough_msr(msr)) {
+		int idx = possible_passthrough_msr_idx(msr);
+
+		if (idx != -ENOENT) {
+			if (type & MSR_TYPE_R)
+				set_bit(idx, vmx->shadow_msr_intercept.read);
+			if (type & MSR_TYPE_W)
+				set_bit(idx, vmx->shadow_msr_intercept.write);
+		}
+	}
 
-		if (type & MSR_TYPE_W)
-			/* write-high */
-			__set_bit(msr, msr_bitmap + 0xc00 / f);
+	if (type & MSR_TYPE_R)
+		vmx_set_msr_bitmap_read(msr_bitmap, msr);
 
-	}
+	if (type & MSR_TYPE_W)
+		vmx_set_msr_bitmap_write(msr_bitmap, msr);
 }
 
 static __always_inline void vmx_set_intercept_for_msr(struct kvm_vcpu *vcpu,
@@ -3794,15 +3889,14 @@ static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
 	return mode;
 }
 
-static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu,
-					 unsigned long *msr_bitmap, u8 mode)
+static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu, u8 mode)
 {
 	int msr;
 
-	for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
-		unsigned word = msr / BITS_PER_LONG;
-		msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
-		msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
+	for (msr = 0x800; msr <= 0x8ff; msr++) {
+		bool intercepted = !!(mode & MSR_BITMAP_MODE_X2APIC_APICV);
+
+		vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_RW, intercepted);
 	}
 
 	if (mode & MSR_BITMAP_MODE_X2APIC) {
@@ -3822,7 +3916,6 @@ static void vmx_update_msr_bitmap_x2apic(struct kvm_vcpu *vcpu,
 void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_vmx *vmx = to_vmx(vcpu);
-	unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
 	u8 mode = vmx_msr_bitmap_mode(vcpu);
 	u8 changed = mode ^ vmx->msr_bitmap_mode;
 
@@ -3830,7 +3923,7 @@ void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
 		return;
 
 	if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
-		vmx_update_msr_bitmap_x2apic(vcpu, msr_bitmap, mode);
+		vmx_update_msr_bitmap_x2apic(vcpu, mode);
 
 	vmx->msr_bitmap_mode = mode;
 }
@@ -3871,6 +3964,29 @@ static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
 	return ((rvi & 0xf0) > (vppr & 0xf0));
 }
 
+static void vmx_msr_filter_changed(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_vmx *vmx = to_vmx(vcpu);
+	u32 i;
+
+	/*
+	 * Set intercept permissions for all potentially passed through MSRs
+	 * again. They will automatically get filtered through the MSR filter,
+	 * so we are back in sync after this.
+	 */
+	for (i = 0; i < ARRAY_SIZE(vmx_possible_passthrough_msrs); i++) {
+		u32 msr = vmx_possible_passthrough_msrs[i];
+		bool read = test_bit(i, vmx->shadow_msr_intercept.read);
+		bool write = test_bit(i, vmx->shadow_msr_intercept.write);
+
+		vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_R, read);
+		vmx_set_intercept_for_msr(vcpu, msr, MSR_TYPE_W, write);
+	}
+
+	pt_update_intercept_for_msr(vcpu);
+	vmx_update_msr_bitmap_x2apic(vcpu, vmx_msr_bitmap_mode(vcpu));
+}
+
 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
 						     bool nested)
 {
@@ -6901,6 +7017,10 @@ static int vmx_create_vcpu(struct kvm_vcpu *vcpu)
 	if (err < 0)
 		goto free_pml;
 
+	/* The MSR bitmap starts with all ones */
+	bitmap_fill(vmx->shadow_msr_intercept.read, MAX_POSSIBLE_PASSGHROUGH_MSRS);
+	bitmap_fill(vmx->shadow_msr_intercept.write, MAX_POSSIBLE_PASSGHROUGH_MSRS);
+
 	msr_bitmap = vmx->vmcs01.msr_bitmap;
 	vmx_disable_intercept_for_msr(vcpu, MSR_IA32_TSC, MSR_TYPE_R);
 	vmx_disable_intercept_for_msr(vcpu, MSR_FS_BASE, MSR_TYPE_RW);
@@ -7965,6 +8085,8 @@ static struct kvm_x86_ops vmx_x86_ops __initdata = {
 	.need_emulation_on_page_fault = vmx_need_emulation_on_page_fault,
 	.apic_init_signal_blocked = vmx_apic_init_signal_blocked,
 	.migrate_timers = vmx_migrate_timers,
+
+	.msr_filter_changed = vmx_msr_filter_changed,
 };
 
 static __init int hardware_setup(void)
arch/x86/kvm/vmx/vmx.h +7 -0
index b3c74f0fe8a1..05694d2fd4ff 100644
@@ -300,6 +300,13 @@ struct vcpu_vmx {
 	u64 ept_pointer;
 
 	struct pt_desc pt_desc;
+
+	/* Save desired MSR intercept (read: pass-through) state */
+#define MAX_POSSIBLE_PASSGHROUGH_MSRS	13
+	struct {
+		DECLARE_BITMAP(read, MAX_POSSIBLE_PASSGHROUGH_MSRS);
+		DECLARE_BITMAP(write, MAX_POSSIBLE_PASSGHROUGH_MSRS);
+	} shadow_msr_intercept;
 };
 
 enum ept_pointers_status {
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#16 lore raw

PATCH v6 7/7 KVM: selftests: Add test for user space MSR handling

In reply to Alexander Graf

Now that we have the ability to handle MSRs from user space and also to select which ones we do want to prevent in-kernel KVM code from handling, let's add a selftest to show case and verify the API.

---

v2 -> v3:

- s/KVM_CAP_ADD_MSR_ALLOWLIST/KVM_CAP_X86_MSR_ALLOWLIST/g
- Add test to clear whitelist
- Adjust to reply-less API
- Fix asserts
- Actually trap on MSR_IA32_POWER_CTL writes

v5 -> v6:

- Adapt to new ioctl API
- Check for passthrough MSRs
- Check for filter exit reason
- Add .gitignore

---
 tools/testing/selftests/kvm/.gitignore        |   1 +
 tools/testing/selftests/kvm/Makefile          |   1 +
 .../selftests/kvm/x86_64/user_msr_test.c      | 224 ++++++++++++++++++
 3 files changed, 226 insertions(+)
 create mode 100644 tools/testing/selftests/kvm/x86_64/user_msr_test.c
tools/testing/selftests/kvm/.gitignore +1 -0
index 452787152748..307ceaadbbb9 100644
@@ -11,6 +11,7 @@
 /x86_64/set_sregs_test
 /x86_64/smm_test
 /x86_64/state_test
+/x86_64/user_msr_test
 /x86_64/vmx_preemption_timer_test
 /x86_64/svm_vmcall_test
 /x86_64/sync_regs_test
tools/testing/selftests/kvm/Makefile +1 -0
index 4a166588d99f..80d5c348354c 100644
@@ -55,6 +55,7 @@ TEST_GEN_PROGS_x86_64 += x86_64/vmx_set_nested_state_test
 TEST_GEN_PROGS_x86_64 += x86_64/vmx_tsc_adjust_test
 TEST_GEN_PROGS_x86_64 += x86_64/xss_msr_test
 TEST_GEN_PROGS_x86_64 += x86_64/debug_regs
+TEST_GEN_PROGS_x86_64 += x86_64/user_msr_test
 TEST_GEN_PROGS_x86_64 += clear_dirty_log_test
 TEST_GEN_PROGS_x86_64 += demand_paging_test
 TEST_GEN_PROGS_x86_64 += dirty_log_test
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +224 -0

224 lines not on this page · raw message

Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#15 lore raw

PATCH v6 6/7 KVM: x86: Introduce MSR filtering

In reply to Alexander Graf

It's not desireable to have all MSRs always handled by KVM kernel space. Some MSRs would be useful to handle in user space to either emulate behavior (like uCode updates) or differentiate whether they are valid based on the CPU model.

To allow user space to specify which MSRs it wants to see handled by KVM, this patch introduces a new ioctl to push filter rules with bitmaps into KVM. Based on these bitmaps, KVM can then decide whether to reject MSR access. With the addition of KVM_CAP_X86_USER_SPACE_MSR it can also deflect the denied MSR events to user space to operate on.

If no filter is populated, MSR handling stays identical to before.

---

v2 -> v3:

- document flags for KVM_X86_ADD_MSR_ALLOWLIST
- generalize exit path, always unlock when returning
- s/KVM_CAP_ADD_MSR_ALLOWLIST/KVM_CAP_X86_MSR_ALLOWLIST/g
- Add KVM_X86_CLEAR_MSR_ALLOWLIST

v3 -> v4:
- lock allow check and clearing
- free bitmaps on clear

v4 -> v5:

- use srcu

v5 -> v6:

- send filter change notification
- change to atomic set_msr_filter ioctl with fallback flag
- use EPERM for filter blocks
- add bit for MSR user space deflection
- check for overflow of BITS_TO_LONGS (thanks Dan Carpenter!)
- s/int i;/u32 i;/
- remove overlap check

---
 Documentation/virt/kvm/api.rst  | 103 +++++++++++++++++++++++
 arch/x86/include/asm/kvm_host.h |  14 +++
 arch/x86/include/uapi/asm/kvm.h |  21 ++++-
 arch/x86/kvm/svm/svm.c          |   4 +-
 arch/x86/kvm/x86.c              | 145 +++++++++++++++++++++++++++++++-
 include/uapi/linux/kvm.h        |   5 ++
 6 files changed, 287 insertions(+), 5 deletions(-)
Documentation/virt/kvm/api.rst +103 -0
index 1aab18e8c0c3..cb2f60415639 100644
@@ -4697,6 +4697,94 @@ KVM_PV_VM_VERIFY
   Verify the integrity of the unpacked image. Only if this succeeds,
   KVM is allowed to start protected VCPUs.
 
+4.126 KVM_X86_SET_MSR_FILTER
+----------------------------
+
+:Capability: KVM_X86_SET_MSR_FILTER
+:Architectures: x86
+:Type: vm ioctl
+:Parameters: struct kvm_msr_filter
+:Returns: 0 on success, < 0 on error
+
+::
+
+  struct kvm_msr_filter_range {
+  #define KVM_MSR_FILTER_READ  (1 << 0)
+  #define KVM_MSR_FILTER_WRITE (1 << 1)
+	__u32 flags;
+	__u32 nmsrs; /* number of msrs in bitmap */
+	__u32 base;  /* MSR index the bitmap starts at */
+	__u8 *bitmap; /* a 1 bit allows the operations in flags, 0 denies */
+  };
+  
+  struct kvm_msr_filter {
+  #define KVM_MSR_FILTER_DEFAULT_ALLOW (0 << 0)
+  #define KVM_MSR_FILTER_DEFAULT_DENY  (1 << 0)
+	__u32 flags;
+	struct kvm_msr_filter_range ranges[16];
+  };
+
+flags values:
+
+KVM_MSR_FILTER_READ
+
+  Filter read accesses to MSRs using the given bitmap. A 0 in the bitmap
+  indicates that a read should immediately fail, while a 1 indicates that
+  a read should be handled like without the filter.
+
+KVM_MSR_FILTER_WRITE
+
+  Filter write accesses to MSRs using the given bitmap. A 0 in the bitmap
+  indicates that a write should immediately fail, while a 1 indicates that
+  a write should be handled like without the filter.
+
+KVM_MSR_FILTER_READ | KVM_MSR_FILTER_WRITE
+
+  Filter booth read and write accesses to MSRs using the given bitmap. A 0
+  in the bitmap indicates that both reads and writes should immediately fail,
+  while a 1 indicates that reads and writes should be handled like without
+  the filter.
+
+KVM_MSR_FILTER_DEFAULT_ALLOW
+
+  If no filter range matches an MSR index that is getting accessed, KVM will
+  fall back to allowing access to the MSR.
+
+KVM_MSR_FILTER_DEFAULT_DENY
+
+  If no filter range matches an MSR index that is getting accessed, KVM will
+  fall back to rejecting access to the MSR. In this mode, all MSRs that should
+  be processed by KVM need to explicitly be marked as allowed in the bitmaps.
+
+This ioctl allows user space to define a up to 16 bitmaps of MSR ranges to
+specify whether a certain MSR access should be explicitly rejected or not.
+
+If this ioctl has never been invoked, MSR accesses are not guarded and the
+old KVM in-kernel emulation behavior is fully preserved.
+
+As soon as the filtering is in place, every MSR access is precessed through
+the filtering. If a bit is within one of the defined ranges, read and write
+accesses are guarded by the bitmap's value for the MSR index. If it is not
+defined in any range, whether MSR access is rejected is determined by the flags
+field of in the kvm_msr_filter struct: KVM_MSR_FILTER_DEFAULT_ALLOW and
+KVM_MSR_FILTER_DEFAULT_DENY.
+
+Calling this ioctl with an empty set of ranges (all nmsrs == 0) disables MSR
+filtering. In that mode, KVM_MSR_FILTER_DEFAULT_DENY no longer has any effect.
+
+Each bitmap range specifies a range of MSRs to potentially allow access on.
+The range goes from MSR index [base .. base+nmsrs]. The flags field
+indicates whether reads, writes or both reads and writes are filtered
+by setting a 1 bit in the bitmap for the corresponding MSR index.
+
+If an MSR access is not permitted through the filtering, it generates a
+#GP inside the guest. When combined with KVM_CAP_X86_USER_SPACE_MSR, that
+allows user space to deflect and potentially handle various MSR accesses
+into user space.
+
+If a vCPU is in running state while this ioctl is invoked, the vCPU may
+experience inconsistent filtering behavior on MSR accesses.
+
 
 5. The kvm_run structure
 ========================
@@ -5176,6 +5264,7 @@ receive MSR exit traps when a particular reason was requested during through
 ENABLE_CAP. Currently valid exit reasons are:
 
 	KVM_MSR_EXIT_REASON_INVAL - access to invalid MSRs or reserved bits
+	KVM_MSR_EXIT_REASON_FILTER - access blocked by KVM_X86_SET_MSR_FILTER
 
 For KVM_EXIT_X86_RDMSR, the "index" field tells user space which MSR the guest
 wants to read. To respond to this request with a successful read, user space
@@ -6220,3 +6309,17 @@ writes to user space. It can be enabled on a VM level. If enabled, MSR
 accesses that would usually trigger a #GP by KVM into the guest will
 instead get bounced to user space through the KVM_EXIT_X86_RDMSR and
 KVM_EXIT_X86_WRMSR exit notifications.
+
+8.25 KVM_X86_SET_MSR_FILTER
+---------------------------
+
+:Architectures: x86
+
+This capability indicates that KVM supports that accesses to user defined MSRs
+may be rejected. With this capability exposed, KVM exports new VM ioctl
+KVM_X86_SET_MSR_FILTER which user space can call to specify bitmaps of MSR
+ranges that KVM should reject access to.
+
+In combination with KVM_CAP_X86_USER_SPACE_MSR, this allows user space to
+trap and emulate MSRs that are outside of the scope of KVM as well as
+limit the attack surface on KVM's MSR emulation code.
arch/x86/include/asm/kvm_host.h +14 -0
index a9e3cc13bca6..64184469b0f8 100644
@@ -87,6 +87,7 @@
 #define KVM_REQ_HV_TLB_FLUSH \
 	KVM_ARCH_REQ_FLAGS(27, KVM_REQUEST_NO_WAKEUP)
 #define KVM_REQ_APF_READY		KVM_ARCH_REQ(28)
+#define KVM_REQ_MSR_FILTER_CHANGED	KVM_ARCH_REQ(29)
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -901,6 +902,13 @@ struct kvm_hv {
 	struct kvm_hv_syndbg hv_syndbg;
 };
 
+struct msr_bitmap_range {
+	u32 flags;
+	u32 nmsrs;
+	u32 base;
+	unsigned long *bitmap;
+};
+
 enum kvm_irqchip_mode {
 	KVM_IRQCHIP_NONE,
 	KVM_IRQCHIP_KERNEL,       /* created with KVM_CREATE_IRQCHIP */
@@ -1005,6 +1013,12 @@ struct kvm_arch {
 	/* Deflect RDMSR and WRMSR to user space when they trigger a #GP */
 	u32 user_space_msr_mask;
 
+	struct {
+		u8 count;
+		bool default_allow:1;
+		struct msr_bitmap_range ranges[16];
+	} msr_filter;
+
 	struct kvm_pmu_event_filter *pmu_event_filter;
 	struct task_struct *nx_lpage_recovery_thread;
 };
arch/x86/include/uapi/asm/kvm.h +19 -2
index 50650cfd235a..66bba91e1bb8 100644
@@ -192,8 +192,25 @@ struct kvm_msr_list {
 	__u32 indices[0];
 };
 
-#define KVM_MSR_ALLOW_READ  (1 << 0)
-#define KVM_MSR_ALLOW_WRITE (1 << 1)
+/* Maximum size of any access bitmap in bytes */
+#define KVM_MSR_FILTER_MAX_BITMAP_SIZE 0x600
+
+/* for KVM_X86_SET_MSR_FILTER */
+struct kvm_msr_filter_range {
+#define KVM_MSR_FILTER_READ  (1 << 0)
+#define KVM_MSR_FILTER_WRITE (1 << 1)
+	__u32 flags;
+	__u32 nmsrs; /* number of msrs in bitmap */
+	__u32 base;  /* MSR index the bitmap starts at */
+	__u8 *bitmap; /* a 1 bit allows the operations in flags, 0 denies */
+};
+
+struct kvm_msr_filter {
+#define KVM_MSR_FILTER_DEFAULT_ALLOW (0 << 0)
+#define KVM_MSR_FILTER_DEFAULT_DENY  (1 << 0)
+	__u32 flags;
+	struct kvm_msr_filter_range ranges[16];
+};
 
 struct kvm_cpuid_entry {
 	__u32 function;
arch/x86/kvm/svm/svm.c +2 -2
index 6a3f4017dd98..41e1eb77c3c0 100644
@@ -624,10 +624,10 @@ static void set_msr_interception_nosync(struct kvm_vcpu *vcpu, u32 msr,
 	WARN_ON(!valid_msr_intercept(msr));
 
 	/* Enforce non allowed MSRs to trap */
-	if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_ALLOW_READ))
+	if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
 		read = 0;
 
-	if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_ALLOW_WRITE))
+	if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
 		write = 0;
 
 	offset    = svm_msrpm_offset(msr);
arch/x86/kvm/x86.c +144 -1

205 lines not on this page · raw message

include/uapi/linux/kvm.h +5 -0
index a42841141cae..677d48f531f1 100644
@@ -419,6 +419,7 @@ struct kvm_run {
 			__u8 error; /* user -> kernel */
 			__u8 pad[3];
 #define KVM_MSR_EXIT_REASON_INVAL	(1 << 0)
+#define KVM_MSR_EXIT_REASON_FILTER	(1 << 1)
 			__u32 reason; /* kernel -> user */
 			__u32 index; /* kernel -> user */
 			__u64 data; /* kernel <-> user */
@@ -1043,6 +1044,7 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_HALT_POLL 182
 #define KVM_CAP_ASYNC_PF_INT 183
 #define KVM_CAP_X86_USER_SPACE_MSR 184
+#define KVM_CAP_X86_MSR_FILTER 185
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
@@ -1544,6 +1546,9 @@ struct kvm_pv_cmd {
 /* Available with KVM_CAP_S390_PROTECTED */
 #define KVM_S390_PV_COMMAND		_IOWR(KVMIO, 0xc5, struct kvm_pv_cmd)
 
+/* Available with KVM_CAP_X86_MSR_FILTER */
+#define KVM_X86_SET_MSR_FILTER	_IOW(KVMIO,  0xc6, struct kvm_msr_filter)
+
 /* Secure Encrypted Virtualization command */
 enum sev_cmd_id {
 	/* Guest initialization commands */
Signature · 12 lines
2.17.1




Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss
Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879
#2 lore raw

Re: [PATCH v6 1/7] KVM: x86: Deflect unknown MSR accesses to user space

In reply to Alexander Graf
Quoted 11 lines

+::

Documentation/virt/kvm/api.rst +10 -0
+
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];
+                       __u32 reason; /* kernel -> user */
+                       __u32 index; /* kernel -> user */
+                       __u64 data; /* kernel <-> user */
+               } msr;
+

Documentation/virt/kvm/api.rst Note that KVM does not skip the faulting instruction as it does for · line 5178

Quoted 10 lines
Documentation/virt/kvm/api.rst +10 -0
+Used on x86 systems. When the VM capability KVM_CAP_X86_USER_SPACE_MSR is
+enabled, MSR accesses to registers that would invoke a #GP by KVM kernel code
+will instead trigger a KVM_EXIT_X86_RDMSR exit for reads and KVM_EXIT_X86_WRMSR
+exit for writes.
+
+The "reason" field specifies why the MSR trap occurred. User space will only
+receive MSR exit traps when a particular reason was requested during through
+ENABLE_CAP. Currently valid exit reasons are:
+
+       KVM_MSR_EXIT_REASON_INVAL - access to invalid MSRs or reserved bits

Can we also have ENOENT?
KVM_MSR_EXIT_REASON_ENOENT - Unknown MSR

Quoted 12 lines
Documentation/virt/kvm/api.rst +5 -0
+
+For KVM_EXIT_X86_RDMSR, the "index" field tells user space which MSR the guest
+wants to read. To respond to this request with a successful read, user space
+writes the respective data into the "data" field and must continue guest
+execution to ensure the read data is transferred into guest register state.
arch/x86/kvm/x86.c +0 -0
index 88c593f83b28..4d285bf054fb 100644

arch/x86/kvm/x86.c int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data) · line 1555

Quoted 7 lines
arch/x86/kvm/x86.c +4 -0
@@ -1549,12 +1549,88 @@ int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
 }
 EXPORT_SYMBOL_GPL(kvm_set_msr);
 
+static int complete_emulated_msr(struct kvm_vcpu *vcpu, bool is_read)
+{
+       if (vcpu->run->msr.error) {
+               kvm_inject_gp(vcpu, 0);

Add return 1. The RIP doesn’t advance when the instruction raises a fault.

Quoted 18 lines
arch/x86/kvm/x86.c +13 -0
+       } else if (is_read) {
+               kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
+               kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
+       }
+
+       return kvm_skip_emulated_instruction(vcpu);
+}
+
+static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
+{
+       return complete_emulated_msr(vcpu, true);
+}
+
 
 /* For KVM_EXIT_INTERNAL_ERROR */
 /* Emulate instruction failed. */

arch/x86/kvm/x86.c struct kvm_run { · line 420

Quoted 7 lines
arch/x86/kvm/x86.c +4 -0
@@ -412,6 +414,15 @@ struct kvm_run {
                        __u64 esr_iss;
                        __u64 fault_ipa;
                } arm_nisv;
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];

__u8 pad[7] to maintain 8 byte alignment? unless we can get away with fewer bits for 'reason' and
get them from 'pad'.

Quoted 32 lines
arch/x86/kvm/x86.c +6 -1
+#define KVM_MSR_EXIT_REASON_INVAL      (1 << 0)
+                       __u32 reason; /* kernel -> user */
+                       __u32 index; /* kernel -> user */
+                       __u64 data; /* kernel <-> user */
+               } msr;
                /* Fix the size of the union. */
                char padding[256];
        };
@@ -1031,6 +1042,7 @@ struct kvm_ppc_resize_hpt {
 #define KVM_CAP_PPC_SECURE_GUEST 181
 #define KVM_CAP_HALT_POLL 182
 #define KVM_CAP_ASYNC_PF_INT 183
+#define KVM_CAP_X86_USER_SPACE_MSR 184
 
 #ifdef KVM_CAP_IRQ_ROUTING
 
--

2.17.1

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#17 lore raw

Re: [PATCH v6 7/7] KVM: selftests: Add test for user space MSR handling

In reply to Alexander Graf

tools/testing/selftests/kvm/x86_64/user_msr_test.c line 151

Quoted 8 lines
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +8 -0
+static void handle_rdmsr(struct kvm_run *run)
+{
+       run->msr.data = run->msr.index;
+       msr_reads++;
+
+       if (run->msr.index == MSR_SYSCALL_MASK ||
+           run->msr.index == MSR_GS_BASE) {
+               TEST_ASSERT(run->msr.reason != KVM_MSR_EXIT_REASON_FILTER,

TEST_ASSERT(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER,

tools/testing/selftests/kvm/x86_64/user_msr_test.c line 162

Quoted 11 lines
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +11 -0
+                           "MSR read trap w/o access fault");
+       }
+}
+
+static void handle_wrmsr(struct kvm_run *run)
+{
+       /* ignore */
+       msr_writes++;
+
+       if (run->msr.index == MSR_IA32_POWER_CTL) {
+               TEST_ASSERT(run->msr.data != 0x1234,

TEST_ASSERT(run->msr.data == 0x1234,

tools/testing/selftests/kvm/x86_64/user_msr_test.c line 164

Quoted 2 lines
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +2 -0
+                           "MSR data for MSR_IA32_POWER_CTL incorrect");
+               TEST_ASSERT(run->msr.reason != KVM_MSR_EXIT_REASON_FILTER,

TEST_ASSERT(run->msr.reason == KVM_MSR_EXIT_REASON_FILTER,

tools/testing/selftests/kvm/x86_64/user_msr_test.c line 173

Quoted 9 lines
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +9 -0
+                           "MSR_IA32_POWER_CTL trap w/o access fault");
+       }
+}
+
+int main(int argc, char *argv[])
+{
+       struct kvm_enable_cap cap = {
+               .cap = KVM_CAP_X86_USER_SPACE_MSR,
+               .args[0] = 1,

.args[0] = KVM_MSR_EXIT_REASON_FILTER,

Quoted 4 lines
tools/testing/selftests/kvm/x86_64/user_msr_test.c new file +4 -0
+       };
+       struct kvm_vm *vm;
+       struct kvm_run *run;
+       int rc;
#11 lore raw

Re: [PATCH v6 5/7] KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

In reply to Alexander Graf

arch/x86/kvm/vmx/vmx.c module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); · line 155

Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +5 -0
+/*
+ * List of MSRs that can be directly passed to the guest.
+ * In addition to these x2apic and PT MSRs are handled specially.
+ */
+static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSGHROUGH_MSRS] = {

MAX_POSSIBLE_PASSGHROUGH_MSRS should be MAX_POSSIBLE_PASSTHROUGH_MSRS

Quoted 4 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+       MSR_IA32_SPEC_CTRL,
+       MSR_IA32_PRED_CMD,
+       MSR_IA32_TSC,
+       MSR_FS_BASE,

arch/x86/kvm/vmx/vmx.c module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); · line 169

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+       MSR_GS_BASE,
+       MSR_KERNEL_GS_BASE,
+       MSR_IA32_SYSENTER_CS,
+       MSR_IA32_SYSENTER_ESP,
+       MSR_IA32_SYSENTER_EIP,
+       MSR_CORE_C1_RES,
+       MSR_CORE_C3_RESIDENCY,
+       MSR_CORE_C6_RESIDENCY,
+       MSR_CORE_C7_RESIDENCY,
+};

Is there any reason not to construct this list on the fly? That could help prevent the list from becoming stale over time if this is missed when calls to vmx_disable_intercept_for_msr() are added.

arch/x86/kvm/vmx/vmx.c static inline bool report_flexpriority(void) · line 643

Quoted 7 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+
 /*
  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
  * ple_gap:    upper bound on the amount of time between two successive
@@ -622,6 +642,41 @@ static inline bool report_flexpriority(void)
        return flexpriority_enabled;
 }

One thing that seems to be missing is removing MSRs from the permission bitmap or resetting the permission bitmap to its original state before adding changes on top of it. This would be needed on subsequent calls to kvm_vm_ioctl_set_msr_filter(). When that happens the original changes made by KVM_REQ_MSR_FILTER_CHANGED need to be backed out before applying the new set.

#3 lore raw

Re: [PATCH v6 1/7] KVM: x86: Deflect unknown MSR accesses to user space

In reply to Aaron Lewis

Hi Aaron,

Thanks a lot for the amazing review! I've been caught in some other things recently, so sorry for the delayed response.

Quoted 18 lines · Aaron Lewis
Quoted 18 lines

+::

Documentation/virt/kvm/api.rst +16 -0
+
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];
+                       __u32 reason; /* kernel -> user */
+                       __u32 index; /* kernel -> user */
+                       __u64 data; /* kernel <-> user */
+               } msr;
+
+Used on x86 systems. When the VM capability KVM_CAP_X86_USER_SPACE_MSR is
+enabled, MSR accesses to registers that would invoke a #GP by KVM kernel code
+will instead trigger a KVM_EXIT_X86_RDMSR exit for reads and KVM_EXIT_X86_WRMSR
+exit for writes.
+
+The "reason" field specifies why the MSR trap occurred. User space will only
Quoted 8 lines

Documentation/virt/kvm/api.rst Note that KVM does not skip the faulting instruction as it does for · line 5178

Quoted 4 lines
Documentation/virt/kvm/api.rst +4 -0
+receive MSR exit traps when a particular reason was requested during through
+ENABLE_CAP. Currently valid exit reasons are:
+
+       KVM_MSR_EXIT_REASON_INVAL - access to invalid MSRs or reserved bits

Can we also have ENOENT?
KVM_MSR_EXIT_REASON_ENOENT - Unknown MSR

I tried to add that at first, but it gets tricky really fast. Why should user space have a vested interest in differentiating between "MSR is not implemented" and "MSR is guarded by a CPUID flag and thus not handled" or "MSR is guarded by a CAP"?

The more details we reveal, the more likely we're to break ABI compatibility.

Quoted 16 lines
Quoted 16 lines
Documentation/virt/kvm/api.rst +5 -0
+
+For KVM_EXIT_X86_RDMSR, the "index" field tells user space which MSR the guest
+wants to read. To respond to this request with a successful read, user space
+writes the respective data into the "data" field and must continue guest
+execution to ensure the read data is transferred into guest register state.
arch/x86/kvm/x86.c +0 -0
index 88c593f83b28..4d285bf054fb 100644
@@ -1549,12 +1549,88 @@ int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data)
  }
  EXPORT_SYMBOL_GPL(kvm_set_msr);
 
Quoted 6 lines

arch/x86/kvm/x86.c int kvm_set_msr(struct kvm_vcpu *vcpu, u32 index, u64 data) · line 1555

Quoted 4 lines
arch/x86/kvm/x86.c +4 -0
+static int complete_emulated_msr(struct kvm_vcpu *vcpu, bool is_read)
+{
+       if (vcpu->run->msr.error) {
+               kvm_inject_gp(vcpu, 0);

Add return 1. The RIP doesn’t advance when the instruction raises a fault.

Yikes. Good catch! Thank you!

Quoted 16 lines
Quoted 16 lines
arch/x86/kvm/x86.c +13 -0
+       } else if (is_read) {
+               kvm_rax_write(vcpu, (u32)vcpu->run->msr.data);
+               kvm_rdx_write(vcpu, vcpu->run->msr.data >> 32);
+       }
+
+       return kvm_skip_emulated_instruction(vcpu);
+}
+
+static int complete_emulated_rdmsr(struct kvm_vcpu *vcpu)
+{
+       return complete_emulated_msr(vcpu, true);
+}
+
 
Quoted 14 lines

arch/x86/kvm/x86.c struct kvm_run { · line 420

Quoted 10 lines
arch/x86/kvm/x86.c +4 -0
  /* For KVM_EXIT_INTERNAL_ERROR */
  /* Emulate instruction failed. */
@@ -412,6 +414,15 @@ struct kvm_run {
                         __u64 esr_iss;
                         __u64 fault_ipa;
                 } arm_nisv;
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];

__u8 pad[7] to maintain 8 byte alignment? unless we can get away with fewer bits for 'reason' and
get them from 'pad'.

Why would we need an 8 byte alignment here? I always thought natural u64 alignment on x86_64 was on 4 bytes?

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#5 lore raw

Re: [PATCH v6 1/7] KVM: x86: Deflect unknown MSR accesses to user space

In reply to Sean Christopherson
Quoted 16 lines · Sean Christopherson
Quoted 14 lines · Alexander Graf
Quoted 12 lines · Aaron Lewis

include/uapi/linux/kvm.h struct kvm_run { · line 420

Quoted 8 lines
include/uapi/linux/kvm.h +4 -0
@@ -412,6 +414,15 @@ struct kvm_run {
                          __u64 esr_iss;
                          __u64 fault_ipa;
                  } arm_nisv;
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];

__u8 pad[7] to maintain 8 byte alignment? unless we can get away with fewer bits for 'reason' and
get them from 'pad'.

Quoted 6 lines
Quoted 2 lines

Why would we need an 8 byte alignment here? I always thought natural u64 alignment on x86_64 was on 4 bytes?

u64 will usually (always?) be 8 byte aligned by the compiler. "Natural" alignment means an object is aligned to its size. E.g. an 8-byte object can split a cache line if it's only aligned on a 4-byte boundary.

For some reason I always thought that x86_64 had a special hack that allows u64s to be "naturally" aligned on a 32bit boundary. But I just double checked what you said and indeed, gcc does pad it to an actual natural boundary.

You never stop learning :).

In that case, it absolutely makes sense to make the padding explicit (and pull it earlier)!

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#12 lore raw

Re: [PATCH v6 5/7] KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

In reply to Aaron Lewis
Quoted 8 lines · Aaron Lewis

arch/x86/kvm/vmx/vmx.c module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); · line 155

Quoted 6 lines
arch/x86/kvm/vmx/vmx.c +5 -0
+/*
+ * List of MSRs that can be directly passed to the guest.
+ * In addition to these x2apic and PT MSRs are handled specially.
+ */
+static u32 vmx_possible_passthrough_msrs[MAX_POSSIBLE_PASSGHROUGH_MSRS] = {

MAX_POSSIBLE_PASSGHROUGH_MSRS should be MAX_POSSIBLE_PASSTHROUGH_MSRS

Ouch. Thanks :).

Quoted 16 lines
Quoted 5 lines
arch/x86/kvm/vmx/vmx.c +4 -0
+       MSR_IA32_SPEC_CTRL,
+       MSR_IA32_PRED_CMD,
+       MSR_IA32_TSC,
+       MSR_FS_BASE,

arch/x86/kvm/vmx/vmx.c module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO); · line 169

Quoted 10 lines
arch/x86/kvm/vmx/vmx.c +10 -0
+       MSR_GS_BASE,
+       MSR_KERNEL_GS_BASE,
+       MSR_IA32_SYSENTER_CS,
+       MSR_IA32_SYSENTER_ESP,
+       MSR_IA32_SYSENTER_EIP,
+       MSR_CORE_C1_RES,
+       MSR_CORE_C3_RESIDENCY,
+       MSR_CORE_C6_RESIDENCY,
+       MSR_CORE_C7_RESIDENCY,
+};
Quoted 3 lines

Is there any reason not to construct this list on the fly? That could help prevent the list from becoming stale over time if this is missed when calls to vmx_disable_intercept_for_msr() are added.

The problem is that we have an upper bound of elements that we can store in the bitmap. We can either make that number arbitrary and then have really awkward failure modes or be incredibly picky instead.

I went for incredibly picky. If anything goes out of sync, like when someone adds an MSR to the list without changing MAX_POSSIBLE_PASSTHROUGH_MSRS, a call to vmx_{en,dis}able_intercept_for_msr() is done on an MSR that is not part of the list, we will abort early and in the former case already through the compiler.

If you can think of a good way to construct the list dynamically and still have a working bitmap of "desired" passthrough states, I'm all ears :).

Quoted 15 lines

arch/x86/kvm/vmx/vmx.c static inline bool report_flexpriority(void) · line 643

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+
  /*
   * These 2 parameters are used to config the controls for Pause-Loop Exiting:
   * ple_gap:    upper bound on the amount of time between two successive
@@ -622,6 +642,41 @@ static inline bool report_flexpriority(void)
         return flexpriority_enabled;
  }

One thing that seems to be missing is removing MSRs from the permission bitmap or resetting the permission bitmap to its original state before adding changes on top of it. This would be needed on subsequent calls to kvm_vm_ioctl_set_msr_filter(). When that happens the original changes made by KVM_REQ_MSR_FILTER_CHANGED need to be backed out before applying the new set.

I'm not sure I follow. Subsequent calls to set_msr_filter() will invoke the "please reset the whole MSR passthrough bitmap to a consistent state" which will then reapply the in-kvm desired state through the bitmap and filter state on top on each of those.

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#13 lore raw

Re: [PATCH v6 5/7] KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

Quoted 16 lines
Quoted 15 lines

arch/x86/kvm/vmx/vmx.c static inline bool report_flexpriority(void) · line 643

Quoted 8 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+
  /*
   * These 2 parameters are used to config the controls for Pause-Loop Exiting:
   * ple_gap:    upper bound on the amount of time between two successive
@@ -622,6 +642,41 @@ static inline bool report_flexpriority(void)
         return flexpriority_enabled;
  }

One thing that seems to be missing is removing MSRs from the permission bitmap or resetting the permission bitmap to its original state before adding changes on top of it. This would be needed on subsequent calls to kvm_vm_ioctl_set_msr_filter(). When that happens the original changes made by KVM_REQ_MSR_FILTER_CHANGED need to be backed out before applying the new set.

Quoted 5 lines

I'm not sure I follow. Subsequent calls to set_msr_filter() will invoke the "please reset the whole MSR passthrough bitmap to a consistent state" which will then reapply the in-kvm desired state through the bitmap and filter state on top on each of those.

Yes, you're correct. I discovered this after the fact by adding a test to the selftest I wrote for the deny list system which I revamped to work for your filter system. It proved the permission bitmaps are in fact set as expected on subsequent calls. You can disregard this comment.

As a side note, I'm happy to share the test if you'd like. I also used it to uncover an issue in the first commit of this series.

#14 lore raw

Re: [PATCH v6 5/7] KVM: x86: VMX: Prevent MSR passthrough when MSR access is denied

Quoted 23 lines · Aaron Lewis
Quoted 17 lines
Quoted 16 lines

arch/x86/kvm/vmx/vmx.c static inline bool report_flexpriority(void) · line 643

Quoted 9 lines
arch/x86/kvm/vmx/vmx.c +1 -0
+
   /*
    * These 2 parameters are used to config the controls for Pause-Loop Exiting:
    * ple_gap:    upper bound on the amount of time between two successive
@@ -622,6 +642,41 @@ static inline bool report_flexpriority(void)
          return flexpriority_enabled;
   }

One thing that seems to be missing is removing MSRs from the permission bitmap or resetting the permission bitmap to its original state before adding changes on top of it. This would be needed on subsequent calls to kvm_vm_ioctl_set_msr_filter(). When that happens the original changes made by KVM_REQ_MSR_FILTER_CHANGED need to be backed out before applying the new set.

Quoted 5 lines

I'm not sure I follow. Subsequent calls to set_msr_filter() will invoke the "please reset the whole MSR passthrough bitmap to a consistent state" which will then reapply the in-kvm desired state through the bitmap and filter state on top on each of those.

Quoted 8 lines

Yes, you're correct. I discovered this after the fact by adding a test to the selftest I wrote for the deny list system which I revamped to work for your filter system. It proved the permission bitmaps are in fact set as expected on subsequent calls. You can disregard this comment.

As a side note, I'm happy to share the test if you'd like. I also used it to uncover an issue in the first commit of this series.

I really enjoy the tests that you submitted and would love to see you add your test coverage to the filtering patch set :)

Thanks!

Alex

Amazon Development Center Germany GmbH
Krausenstr. 38
10117 Berlin
Geschaeftsfuehrung: Christian Schlaeger, Jonathan Weiss Eingetragen am Amtsgericht Charlottenburg unter HRB 149173 B
Sitz: Berlin
Ust-ID: DE 289 237 879

#4 lore raw

Re: [PATCH v6 1/7] KVM: x86: Deflect unknown MSR accesses to user space

In reply to Alexander Graf
Quoted 14 lines · Alexander Graf
Quoted 4 lines · Aaron Lewis
Quoted 4 lines
include/uapi/linux/kvm.h +0 -0
@@ -412,6 +414,15 @@ struct kvm_run {
                         __u64 esr_iss;
                         __u64 fault_ipa;
                 } arm_nisv;
Quoted 8 lines

Documentation/virt/kvm/api.rst Note that KVM does not skip the faulting instruction as it does for · line 5163

Quoted 4 lines
Documentation/virt/kvm/api.rst +4 -0
+               /* KVM_EXIT_X86_RDMSR / KVM_EXIT_X86_WRMSR */
+               struct {
+                       __u8 error; /* user -> kernel */
+                       __u8 pad[3];

__u8 pad[7] to maintain 8 byte alignment? unless we can get away with fewer bits for 'reason' and
get them from 'pad'.

Quoted 2 lines

Why would we need an 8 byte alignment here? I always thought natural u64 alignment on x86_64 was on 4 bytes?

u64 will usually (always?) be 8 byte aligned by the compiler. "Natural" alignment means an object is aligned to its size. E.g. an 8-byte object can split a cache line if it's only aligned on a 4-byte boundary.

#6 lore raw

Re: [PATCH v6 1/7] KVM: x86: Deflect unknown MSR accesses to user space

In reply to Alexander Graf
Quoted 10 lines
Quoted 9 lines

Documentation/virt/kvm/api.rst Note that KVM does not skip the faulting instruction as it does for · line 5178

Quoted 5 lines
Documentation/virt/kvm/api.rst +5 -0
+The "reason" field specifies why the MSR trap occurred. User space will only
+receive MSR exit traps when a particular reason was requested during through
+ENABLE_CAP. Currently valid exit reasons are:
+
+       KVM_MSR_EXIT_REASON_INVAL - access to invalid MSRs or reserved bits

Can we also have ENOENT?
KVM_MSR_EXIT_REASON_ENOENT - Unknown MSR

Quoted 8 lines

I tried to add that at first, but it gets tricky really fast. Why should user space have a vested interest in differentiating between "MSR is not implemented" and "MSR is guarded by a CPUID flag and thus not handled" or "MSR is guarded by a CAP"?

The more details we reveal, the more likely we're to break ABI compatibility.

I don't suspect we will ever have a stable ABI here, whether we split the two error values or not. But there could be value in it. Consider an MSR that raises #GP if any bit in the high dword is set. KVM version 0 knows nothing about this MSR, but KVM version 1 implements it properly. Assuming ignore_msrs=0 and error codes:
EINVAL (invalid argument, should raise a #GP) and ENOTSUP (seems like a better name than ENOENT, Unknown MSR).

With Just EINVAL: KVM version 0 will always exit to userspace if EINVAL is requested (it needs help). KVM version 1 will exit to userspace only for illegal accesses if EINVAL is requested (but it doesn't really need help).
With EINVAL and ENOTSUP: KVM version 0 will always exit to userspace if ENOTSUP is requested (it needs help). KVM version 1 will not exit to userspace if ENOTSUP is requested.

If you want to implement ignore_msrs in userspace it seems much easier with the second approach, and I think all you'd have to do is return -ENOTSUP from kvm_msr_ignored_check() instead of returning 1.