Skip to contentSkip to conversation

Add AMD Secure Nested Paging (SEV-SNP) Hypervisor Support

RFC PATCH Superseded Brijesh Singh 11 participants 178 messages Jul 7, 2021 – Jun 6, 2022 Page 2 of 2

Subsystems (12)

v4 of 12 Superseded Latest is v12 →

lore
Share & tools
lore
#155 lore raw

Re: [PATCH Part2 RFC v4 35/40] KVM: Add arch hooks to track the host write to guest memory

In reply to Sean Christopherson

On 7/19/21 6:30 PM, Sean Christopherson wrote:
...>

Quoted 5 lines

NAK on converting RMP entries in response to guest accesses. Corrupting guest data (due to dropping the "validated" flag) on a rogue/incorrect guest emulation request or misconfigured PV feature is double ungood. The potential kernel panic below isn't much better.

I also debated myself whether its okay to transition the page state to shared to complete the write operation. I am good with removing the converting RMP entries from the patch, and that will also remove the kernel panic code.

Quoted 4 lines

And I also don't think we need this heavyweight flow for user access, e.g. __copy_to_user(), just eat the RMP violation #PF like all other #PFs and exit to userspace with -EFAULT.

Yes, we could improve the __copy_to_user() to eat the RMP violation. I was tempted to go on that path but struggled to find a strong reason for it and was not sure if that accepted. I can add that support in next rev.

Quoted 1 line

kvm_vcpu_map() and friends might need the manual lookup, at least initially,

Yes, the enhancement to the __copy_to_user() does not solve this problem and for it we need to do the manually lookup.

but

Quoted 25 lines

in an ideal world that would be naturally handled by gup(), e.g. by unmapping guest private memory or whatever approach TDX ends up employing to avoid #MCs.

Quoted 8 lines
arch/x86/kvm/svm/sev.c +8 -0
+	 */
+	if (rmpentry_assigned(e)) {
+		pr_err("SEV-SNP: write to guest private gfn %llx\n", gfn);
+		rc = snp_make_page_shared(kvm_get_vcpu(kvm, 0),
+				gfn << PAGE_SHIFT, pfn, PG_LEVEL_4K);
+		BUG_ON(rc != 0);
+	}
+}

...

arch/x86/kvm/x86.c void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm, · line 9110

Quoted 3 lines
arch/x86/kvm/x86.c +3 -0
+void kvm_arch_write_gfn_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn)
+{
+	update_gfn_track(slot, gfn, KVM_PAGE_TRACK_WRITE, 1);

Tracking only writes isn't correct, as KVM reads to guest private memory will return garbage. Pulling the rug out from under KVM reads won't fail as spectacularly as writes (at least not right away), but they'll still fail. I'm actually ok reading garbage if the guest screws up, but KVM needs consistent semantics.

Quoted 7 lines

Good news is that per-gfn tracking is probably overkill anyways. As mentioned above, user access don't need extra magic, they either fail or they don't.

For kvm_vcpu_map(), one thought would be to add a "short-term" map variant that is not allowed to be retained across VM-Entry, and then use e.g. SRCU to block PSC requests until there are no consumers.

Sounds good to me, i will add the support in the next rev.

thanks

#156 lore raw

RFC PATCH v4 36/40 KVM: X86: Export the kvm_zap_gfn_range() for the SNP use

In reply to Brijesh Singh

While resolving the RMP page fault, we may run into cases where the page level between the RMP entry and TDP does not match and the 2M RMP entry must be split into 4K RMP entries. Or a 2M TDP page need to be broken into multiple of 4K pages.

To keep the RMP and TDP page level in sync, we will zap the gfn range after splitting the pages in the RMP entry. The zap should force the TDP to gets rebuilt with the new page level.

---
 arch/x86/include/asm/kvm_host.h | 2 ++
 arch/x86/kvm/mmu.h              | 2 --
 arch/x86/kvm/mmu/mmu.c          | 1 +
 3 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index 678992e9966a..46323af09995 100644
@@ -1490,6 +1490,8 @@ void kvm_mmu_zap_all(struct kvm *kvm);
 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen);
 unsigned long kvm_mmu_calculate_default_mmu_pages(struct kvm *kvm);
 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long kvm_nr_mmu_pages);
+void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
+
 
 int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3);
 bool pdptrs_changed(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu.h +0 -2
index 147e76ab1536..eec62011bb2e 100644
@@ -228,8 +228,6 @@ static inline u8 permission_fault(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
 	return -(u32)fault & errcode;
 }
 
-void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end);
-
 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu);
 
 int kvm_mmu_post_init_vm(struct kvm *kvm);
arch/x86/kvm/mmu/mmu.c +1 -0
index 4abc0dc49d55..e60f54455cdc 100644
@@ -5657,6 +5657,7 @@ static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
 
 	return need_tlb_flush;
 }
+EXPORT_SYMBOL_GPL(kvm_zap_gfn_range);
 
 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
 				   const struct kvm_memory_slot *memslot)
Signature · 1 line
2.17.1
#157 lore raw

RFC PATCH v4 37/40 KVM: SVM: Add support to handle the RMP nested page fault

In reply to Brijesh Singh

Follow the recommendation from APM2 section 15.36.10 and 15.36.11 to resolve the RMP violation encountered during the NPT table walk.

---
 arch/x86/include/asm/kvm_host.h |  3 ++
 arch/x86/kvm/mmu/mmu.c          | 20 ++++++++++++
 arch/x86/kvm/svm/sev.c          | 57 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c          |  2 ++
 arch/x86/kvm/svm/svm.h          |  2 ++
 5 files changed, 84 insertions(+)
arch/x86/include/asm/kvm_host.h +3 -0
index 46323af09995..117e2e08d7ed 100644
@@ -1399,6 +1399,9 @@ struct kvm_x86_ops {
 
 	void (*write_page_begin)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
 	void (*write_page_end)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
+
+	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
+			int level, u64 error_code);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +20 -0
index e60f54455cdc..b6a676ba1862 100644
@@ -5096,6 +5096,18 @@ static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
 	write_unlock(&vcpu->kvm->mmu_lock);
 }
 
+static int handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
+{
+	kvm_pfn_t pfn;
+	int level;
+
+	if (unlikely(!kvm_mmu_get_tdp_walk(vcpu, gpa, &pfn, &level)))
+		return RET_PF_RETRY;
+
+	kvm_x86_ops.handle_rmp_page_fault(vcpu, gpa, pfn, level, error_code);
+	return RET_PF_RETRY;
+}
+
 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
 		       void *insn, int insn_len)
 {
@@ -5112,6 +5124,14 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
 			goto emulate;
 	}
 
+	if (unlikely(error_code & PFERR_GUEST_RMP_MASK)) {
+		r = handle_rmp_page_fault(vcpu, cr2_or_gpa, error_code);
+		if (r == RET_PF_RETRY)
+			return 1;
+		else
+			return r;
+	}
+
 	if (r == RET_PF_INVALID) {
 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
 					  lower_32_bits(error_code), false);
arch/x86/kvm/svm/sev.c +57 -0

60 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +2 -0
index 4ff6fc86dd18..32e35d396508 100644
@@ -4579,6 +4579,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.get_tdp_max_page_level = sev_get_tdp_max_page_level,
 
 	.write_page_begin = sev_snp_write_page_begin,
+
+	.handle_rmp_page_fault = snp_handle_rmp_page_fault,
 };
 
 static struct kvm_x86_init_ops svm_init_ops __initdata = {
arch/x86/kvm/svm/svm.h +2 -0
index e0276ad8a1ae..ccdaaa4e1fb1 100644
@@ -577,6 +577,8 @@ void sev_es_unmap_ghcb(struct vcpu_svm *svm);
 struct page *snp_safe_alloc_page(struct kvm_vcpu *vcpu);
 int sev_get_tdp_max_page_level(struct kvm_vcpu *vcpu, gpa_t gpa, int max_level);
 void sev_snp_write_page_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
+int snp_handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
+			      int level, u64 error_code);
 
 /* vmenter.S */
 
Signature · 1 line
2.17.1
#158 lore raw

Re: [PATCH Part2 RFC v4 37/40] KVM: SVM: Add support to handle the RMP nested page fault

Quoted 2 lines · Brijesh Singh

Follow the recommendation from APM2 section 15.36.10 and 15.36.11 to resolve the RMP violation encountered during the NPT table walk.

Heh, please elaborate on exactly what that recommendation is. A recommendation isn't exactly architectural, i.e. is subject to change :-)

And, do we have to follow the APM's recommendation? Specifically, can KVM treat #NPF RMP violations as guest errors, or is that not allowed by the GHCB spec? I.e. can we mandate accesses be preceded by page state change requests? It would simplify KVM (albeit not much of a simplificiation) and would also make debugging easier since transitions would require an explicit guest request and guest bugs would result in errors instead of random corruption/weirdness.

Quoted 37 lines

index 46323af09995..117e2e08d7ed 100644

arch/x86/include/asm/kvm_host.h +3 -0
@@ -1399,6 +1399,9 @@ struct kvm_x86_ops {
 
 	void (*write_page_begin)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
 	void (*write_page_end)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
+
+	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
+			int level, u64 error_code);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +12 -0
index e60f54455cdc..b6a676ba1862 100644
@@ -5096,6 +5096,18 @@ static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
 	write_unlock(&vcpu->kvm->mmu_lock);
 }
 
+static int handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
+{
+	kvm_pfn_t pfn;
+	int level;
+
+	if (unlikely(!kvm_mmu_get_tdp_walk(vcpu, gpa, &pfn, &level)))
+		return RET_PF_RETRY;
+
+	kvm_x86_ops.handle_rmp_page_fault(vcpu, gpa, pfn, level, error_code);
+	return RET_PF_RETRY;
+}
+
 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
 		       void *insn, int insn_len)
 {

arch/x86/kvm/mmu/mmu.c int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code, · line 5128

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +2 -0
@@ -5112,6 +5124,14 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
 			goto emulate;
 	}
 
+	if (unlikely(error_code & PFERR_GUEST_RMP_MASK)) {
+		r = handle_rmp_page_fault(vcpu, cr2_or_gpa, error_code);

Adding a kvm_x86_ops hook is silly, there's literally one path, npf_interception() that can encounter RMP violations. Just invoke snp_handle_rmp_page_fault() from there. That works even if kvm_mmu_get_tdp_walk() stays around since it was exported earlier.

Quoted 24 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+		if (r == RET_PF_RETRY)
+			return 1;
+		else
+			return r;
+	}
+
 	if (r == RET_PF_INVALID) {
 		r = kvm_mmu_do_page_fault(vcpu, cr2_or_gpa,
 					  lower_32_bits(error_code), false);
arch/x86/kvm/svm/sev.c +7 -0
index 839cf321c6dd..53a60edc810e 100644
@@ -3519,3 +3519,60 @@ void sev_snp_write_page_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn
 		BUG_ON(rc != 0);
 	}
 }
+
+int snp_handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
+			      int level, u64 error_code)
+{
+	struct rmpentry *e;
+	int rlevel, rc = 0;
+	bool private;

arch/x86/kvm/svm/sev.c void sev_snp_write_page_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn · line 3538

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	gfn_t gfn;
+
+	e = snp_lookup_page_in_rmptable(pfn_to_page(pfn), &rlevel);
+	if (!e)
+		return 1;
+
+	private = !!(error_code & PFERR_GUEST_ENC_MASK);
+
+	/*
+	 * See APM section 15.36.11 on how to handle the RMP fault for the large pages.

Please do not punt the reader to the APM for things like this. It's ok when there are gory details about CPU behavior that aren't worth commenting, but under no circumstance should KVM's software implementation be "documented" in a CPU spec.

Quoted 18 lines
arch/x86/kvm/svm/sev.c +18 -0
+	 *
+	 *  npt	     rmp    access      action
+	 *  --------------------------------------------------
+	 *  4k       2M     C=1       psmash
+	 *  x        x      C=1       if page is not private then add a new RMP entry
+	 *  x        x      C=0       if page is private then make it shared
+	 *  2M       4k     C=x       zap
+	 */
+	if ((error_code & PFERR_GUEST_SIZEM_MASK) ||
+	    ((level == PG_LEVEL_4K) && (rlevel == PG_LEVEL_2M) && private)) {
+		rc = snp_rmptable_psmash(vcpu, pfn);
+		goto zap_gfn;
+	}
+
+	/*
+	 * If it's a private access, and the page is not assigned in the RMP table, create a
+	 * new private RMP entry.
+	 */

arch/x86/kvm/svm/sev.c void sev_snp_write_page_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn · line 3566

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	if (!rmpentry_assigned(e) && private) {
+		rc = snp_make_page_private(vcpu, gpa, pfn, PG_LEVEL_4K);
+		goto zap_gfn;
+	}
+
+	/*
+	 * If it's a shared access, then make the page shared in the RMP table.
+	 */
+	if (rmpentry_assigned(e) && !private)
+		rc = snp_make_page_shared(vcpu, gpa, pfn, PG_LEVEL_4K);

Hrm, this really feels like it needs to be protected by mmu_lock. Functionally, it might all work out in the end after enough RMP violations, but it's extremely difficult to reason about and probably even more difficult if multiple vCPUs end up fighting over a gfn.

My gut reaction is that this is also backwards, i.e. KVM should update the RMP to match its TDP SPTEs, not the other way around.

The one big complication is that the TDP MMU only takes mmu_lock for read. A few options come to mind but none of them are all that pretty. I'll wait to hear back on whether or not we can make PSC request mandatory before thinking too hard on this one.

Quoted 11 lines
arch/x86/kvm/svm/sev.c +11 -0
+zap_gfn:
+	/*
+	 * Now that we have updated the RMP pagesize, zap the existing rmaps for
+	 * large entry ranges so that nested page table gets rebuilt with the updated RMP
+	 * pagesize.
+	 */
+	gfn = gpa_to_gfn(gpa) & ~(KVM_PAGES_PER_HPAGE(PG_LEVEL_2M) - 1);
+	kvm_zap_gfn_range(vcpu->kvm, gfn, gfn + 512);
+
+	return 0;
+}
#159 lore raw

Re: [PATCH Part2 RFC v4 37/40] KVM: SVM: Add support to handle the RMP nested page fault

Quoted 6 lines · Sean Christopherson
Quoted 2 lines · Brijesh Singh

Follow the recommendation from APM2 section 15.36.10 and 15.36.11 to resolve the RMP violation encountered during the NPT table walk.

Heh, please elaborate on exactly what that recommendation is. A recommendation isn't exactly architectural, i.e. is subject to change :-)

I will try to expand it :)

Quoted 2 lines

And, do we have to follow the APM's recommendation?

Yes, unless we want to be very strict on what a guest can do.

Specifically, can KVM treat

Quoted 1 line

#NPF RMP violations as guest errors, or is that not allowed by the GHCB spec?

The GHCB spec does not say anything about the #NPF RMP violation error. And not all #NPF RMP is a guest error (mainly those size mismatch etc).

Quoted 1 line

I.e. can we mandate accesses be preceded by page state change requests?

This is a good question, the GHCB spec does not enforce that a guest *must* use page state. If the page state changes is not done by the guest then it will cause #NPF and its up to the hypervisor to decide on what it wants to do.

It would

Quoted 4 lines

simplify KVM (albeit not much of a simplificiation) and would also make debugging easier since transitions would require an explicit guest request and guest bugs would result in errors instead of random corruption/weirdness.

I am good with enforcing this from the KVM. But the question is, what fault we should inject in the guest when KVM detects that guest has issued the page state change.

Quoted 40 lines
Quoted 40 lines

index 46323af09995..117e2e08d7ed 100644

arch/x86/include/asm/kvm_host.h +3 -0
@@ -1399,6 +1399,9 @@ struct kvm_x86_ops {
 
  	void (*write_page_begin)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
  	void (*write_page_end)(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
+
+	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
+			int level, u64 error_code);
  };
 
  struct kvm_x86_nested_ops {
arch/x86/kvm/mmu/mmu.c +12 -0
index e60f54455cdc..b6a676ba1862 100644
@@ -5096,6 +5096,18 @@ static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
  	write_unlock(&vcpu->kvm->mmu_lock);
  }
 
+static int handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u64 error_code)
+{
+	kvm_pfn_t pfn;
+	int level;
+
+	if (unlikely(!kvm_mmu_get_tdp_walk(vcpu, gpa, &pfn, &level)))
+		return RET_PF_RETRY;
+
+	kvm_x86_ops.handle_rmp_page_fault(vcpu, gpa, pfn, level, error_code);
+	return RET_PF_RETRY;
+}
+
  int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
  		       void *insn, int insn_len)
  {
@@ -5112,6 +5124,14 @@ int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
  			goto emulate;
  	}
 
Quoted 8 lines

arch/x86/kvm/mmu/mmu.c int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code, · line 5128

Quoted 2 lines
arch/x86/kvm/mmu/mmu.c +2 -0
+	if (unlikely(error_code & PFERR_GUEST_RMP_MASK)) {
+		r = handle_rmp_page_fault(vcpu, cr2_or_gpa, error_code);

Adding a kvm_x86_ops hook is silly, there's literally one path, npf_interception() that can encounter RMP violations. Just invoke snp_handle_rmp_page_fault() from there. That works even if kvm_mmu_get_tdp_walk() stays around since it was exported earlier.

Noted.

Quoted 12 lines

arch/x86/kvm/mmu/mmu.c int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code, · line 5134

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+
+	/*
+	 * If it's a shared access, then make the page shared in the RMP table.
+	 */
+	if (rmpentry_assigned(e) && !private)
+		rc = snp_make_page_shared(vcpu, gpa, pfn, PG_LEVEL_4K);

Hrm, this really feels like it needs to be protected by mmu_lock. Functionally, it might all work out in the end after enough RMP violations, but it's extremely difficult to reason about and probably even more difficult if multiple vCPUs end up fighting over a gfn.

Lets see what's your thought on enforcing the page state change for the KVM. If we want the guest to issue the page state change before the access then this case will simply need to inject an error in the guest and we can remove all of it.

Quoted 8 lines

My gut reaction is that this is also backwards, i.e. KVM should update the RMP to match its TDP SPTEs, not the other way around.

The one big complication is that the TDP MMU only takes mmu_lock for read. A few options come to mind but none of them are all that pretty. I'll wait to hear back on whether or not we can make PSC request mandatory before thinking too hard on this one.

#160 lore raw

Re: [PATCH Part2 RFC v4 37/40] KVM: SVM: Add support to handle the RMP nested page fault

Quoted 22 lines · Brijesh Singh
Quoted 6 lines · Sean Christopherson
Quoted 2 lines · Brijesh Singh

Follow the recommendation from APM2 section 15.36.10 and 15.36.11 to resolve the RMP violation encountered during the NPT table walk.

Heh, please elaborate on exactly what that recommendation is. A recommendation isn't exactly architectural, i.e. is subject to change :-)

I will try to expand it :)

Quoted 2 lines

And, do we have to follow the APM's recommendation?

Yes, unless we want to be very strict on what a guest can do.

Quoted 2 lines

Specifically, can KVM treat #NPF RMP violations as guest errors, or is that not allowed by the GHCB spec?

The GHCB spec does not say anything about the #NPF RMP violation error. And not all #NPF RMP is a guest error (mainly those size mismatch etc).

Quoted 6 lines
Quoted 1 line

I.e. can we mandate accesses be preceded by page state change requests?

This is a good question, the GHCB spec does not enforce that a guest *must* use page state. If the page state changes is not done by the guest then it will cause #NPF and its up to the hypervisor to decide on what it wants to do.

Drat. Is there any hope of pushing through a GHCB change to require the guest to use PSC?

Quoted 8 lines
Quoted 4 lines

It would simplify KVM (albeit not much of a simplificiation) and would also make debugging easier since transitions would require an explicit guest request and guest bugs would result in errors instead of random corruption/weirdness.

I am good with enforcing this from the KVM. But the question is, what fault we should inject in the guest when KVM detects that guest has issued the page state change.

Injecting a fault, at least from KVM, isn't an option since there's no architectural behavior we can leverage. E.g. a guest that isn't enlightened enough to properly use PSC isn't going to do anything useful with a #MC or #VC.

Sadly, as is I think our only options are to either automatically convert RMP entries as need, or to punt the exit to userspace. Maybe we could do both, e.g. have a module param to control the behavior? The problem with punting to userspace is that KVM would also need a way for userspace to fix the issue, otherwise we're just taking longer to kill the guest :-/

#161 lore raw

Re: [PATCH Part2 RFC v4 37/40] KVM: SVM: Add support to handle the RMP nested page fault

On 7/20/21 5:31 PM, Sean Christopherson wrote:
...

Quoted 6 lines
Quoted 4 lines

This is a good question, the GHCB spec does not enforce that a guest *must* use page state. If the page state changes is not done by the guest then it will cause #NPF and its up to the hypervisor to decide on what it wants to do.

Drat. Is there any hope of pushing through a GHCB change to require the guest to use PSC?

Well, I am not sure if we can push it through GHCB. Other hypervisor also need to agree to it. We need to define them some architectural way for hypervisor to detect the violation and notify guest about it.

Quoted 11 lines
Quoted 7 lines
Quoted 4 lines

It would simplify KVM (albeit not much of a simplificiation) and would also make debugging easier since transitions would require an explicit guest request and guest bugs would result in errors instead of random corruption/weirdness.

I am good with enforcing this from the KVM. But the question is, what fault we should inject in the guest when KVM detects that guest has issued the page state change.

Injecting a fault, at least from KVM, isn't an option since there's no architectural behavior we can leverage. E.g. a guest that isn't enlightened enough to properly use PSC isn't going to do anything useful with a #MC or #VC.

Quoted 6 lines

Sadly, as is I think our only options are to either automatically convert RMP entries as need, or to punt the exit to userspace. Maybe we could do both, e.g. have a module param to control the behavior? The problem with punting to userspace is that KVM would also need a way for userspace to fix the issue, otherwise we're just taking longer to kill the guest :-/

I think we should automatically convert the RMP entries at time, its possible that non Linux guest may access the page without going through the PSC.

thanks

#162 lore raw

Re: [PATCH Part2 RFC v4 37/40] KVM: SVM: Add support to handle the RMP nested page fault

Quoted 7 lines · Brijesh Singh

On 7/20/21 5:31 PM, Sean Christopherson wrote:
...

Quoted 4 lines
Quoted 4 lines

This is a good question, the GHCB spec does not enforce that a guest *must* use page state. If the page state changes is not done by the guest then it will cause #NPF and its up to the hypervisor to decide on what it wants to do.

Quoted 6 lines
Quoted 2 lines

Drat. Is there any hope of pushing through a GHCB change to require the guest to use PSC?

Well, I am not sure if we can push it through GHCB. Other hypervisor also need to agree to it. We need to define them some architectural way for hypervisor to detect the violation and notify guest about it.

And other guest's, too :-/

Quoted 17 lines
Quoted 11 lines
Quoted 7 lines
Quoted 4 lines

It would simplify KVM (albeit not much of a simplificiation) and would also make debugging easier since transitions would require an explicit guest request and guest bugs would result in errors instead of random corruption/weirdness.

I am good with enforcing this from the KVM. But the question is, what fault we should inject in the guest when KVM detects that guest has issued the page state change.

Injecting a fault, at least from KVM, isn't an option since there's no architectural behavior we can leverage. E.g. a guest that isn't enlightened enough to properly use PSC isn't going to do anything useful with a #MC or #VC.

Quoted 6 lines

Sadly, as is I think our only options are to either automatically convert RMP entries as need, or to punt the exit to userspace. Maybe we could do both, e.g. have a module param to control the behavior? The problem with punting to userspace is that KVM would also need a way for userspace to fix the issue, otherwise we're just taking longer to kill the guest :-/

Quoted 3 lines

I think we should automatically convert the RMP entries at time, its possible that non Linux guest may access the page without going through the PSC.

Agreed. I don't love that KVM will disallow automatic conversions when the host is accessing guest memory, but not when the guest is accessing memory. On the other hand, auto-converting when accessing from the host is far, far worse.

And FWIW, IIRC this is also aligns with the expected/proposed TDX behavior, so that's a plus.

#163 lore raw

RFC PATCH v4 38/40 KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

In reply to Brijesh Singh

Version 2 of GHCB specification added the support two SNP Guest Request Message NAE event. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

The SNP_GUEST_REQUEST requires two unique pages, one page for the request and one page for the response. The response page need to be in the firmware state. The GHCB specification says that both the pages need to be in the hypervisor state but before executing the SEV-SNP command the response page need to be in the firmware state.

The SNP_EXT_GUEST_REQUEST is similar to SNP_GUEST_REQUEST with the difference of an additional certificate blob that can be passed through the SNP_SET_CONFIG ioctl defined in the CCP driver. The CCP driver exposes snp_guest_ext_guest_request() that is used by the KVM to get the both report and additional data at once.

In order to minimize the page state transition during the command handling, pre-allocate a firmware page on guest creation. Use the pre-allocated firmware page to complete the command execution and copy the result in the guest response page.

Ratelimit the handling of SNP_GUEST_REQUEST NAE to avoid the possibility of a guest creating a denial of service attack aginst the SNP firmware.

Now that KVM supports all the VMGEXIT NAEs required for the base SEV-SNP feature, set the hypervisor feature to advertise it.

---
 arch/x86/kvm/svm/sev.c | 223 ++++++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/svm/svm.h |   6 +-
 2 files changed, 225 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +220 -3
index 53a60edc810e..4cb4c1d7e444 100644
@@ -18,6 +18,8 @@
 #include <linux/processor.h>
 #include <linux/trace_events.h>
 #include <linux/sev.h>
+#include <linux/kvm_host.h>
+#include <linux/sev-guest.h>
 #include <asm/fpu/internal.h>
 
 #include <asm/trapnr.h>
@@ -1534,6 +1536,7 @@ static int sev_receive_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
 
 static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 {
+	struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
 	struct sev_data_snp_gctx_create data = {};
 	void *context;
 	int rc;
@@ -1543,14 +1546,24 @@ static void *snp_context_create(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	if (!context)
 		return NULL;
 
-	data.gctx_paddr = __psp_pa(context);
-	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
-	if (rc) {
+	/* Allocate a firmware buffer used during the guest command handling. */
+	sev->snp_resp_page = snp_alloc_firmware_page(GFP_KERNEL_ACCOUNT);
+	if (!sev->snp_resp_page) {
 		snp_free_firmware_page(context);
 		return NULL;
 	}
 
+	data.gctx_paddr = __psp_pa(context);
+	rc = __sev_issue_cmd(argp->sev_fd, SEV_CMD_SNP_GCTX_CREATE, &data, &argp->error);
+	if (rc)
+		goto e_free;
+
 	return context;
+
+e_free:
+	snp_free_firmware_page(context);
+	snp_free_firmware_page(sev->snp_resp_page);
+	return NULL;
 }
 
 static int snp_bind_asid(struct kvm *kvm, int *error)
@@ -1618,6 +1631,12 @@ static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	if (rc)
 		goto e_free_context;
 
+	/* Used for rate limiting SNP guest message request, use the default settings */
+	ratelimit_default_init(&sev->snp_guest_msg_rs);
+
+	/* Allocate memory used for the certs data in SNP guest request */
+	sev->snp_certs_data = kmalloc(SEV_FW_BLOB_MAX_SIZE, GFP_KERNEL_ACCOUNT);
+
 	return 0;
 
 e_free_context:
@@ -2218,6 +2237,9 @@ static int snp_decommission_context(struct kvm *kvm)
 	snp_free_firmware_page(sev->snp_context);
 	sev->snp_context = NULL;
 
+	/* Free the response page. */
+	snp_free_firmware_page(sev->snp_resp_page);
+
 	return 0;
 }
 
@@ -2268,6 +2290,9 @@ void sev_vm_destroy(struct kvm *kvm)
 		sev_unbind_asid(kvm, sev->handle);
 	}
 
+
+	kfree(sev->snp_certs_data);
+
 	sev_asid_free(sev);
 }
 
@@ -2663,6 +2688,8 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 	case SVM_VMGEXIT_HV_FT:
 	case SVM_VMGEXIT_PSC:
+	case SVM_VMGEXIT_GUEST_REQUEST:
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST:
 		break;
 	default:
 		goto vmgexit_err;
@@ -3053,6 +3080,181 @@ static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb)
 	return rc ? map_to_psc_vmgexit_code(rc) : 0;
 }
 
+static int snp_build_guest_buf(struct vcpu_svm *svm, struct sev_data_snp_guest_request *data,
+			       gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	kvm_pfn_t req_pfn, resp_pfn;
+	struct kvm_sev_info *sev;
+
+	if (!IS_ALIGNED(req_gpa, PAGE_SIZE) || !IS_ALIGNED(resp_gpa, PAGE_SIZE)) {
+		pr_err_ratelimited("svm: guest request (%#llx) or response (%#llx) is not page aligned\n",
+			req_gpa, resp_gpa);
+		return -EINVAL;
+	}
+
+	req_pfn = gfn_to_pfn(kvm, gpa_to_gfn(req_gpa));
+	if (is_error_noslot_pfn(req_pfn)) {
+		pr_err_ratelimited("svm: guest request invalid gpa=%#llx\n", req_gpa);
+		return -EINVAL;
+	}
+
+	resp_pfn = gfn_to_pfn(kvm, gpa_to_gfn(resp_gpa));
+	if (is_error_noslot_pfn(resp_pfn)) {
+		pr_err_ratelimited("svm: guest response invalid gpa=%#llx\n", resp_gpa);
+		return -EINVAL;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	data->gctx_paddr = __psp_pa(sev->snp_context);
+	data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);
+	data->res_paddr = __psp_pa(sev->snp_resp_page);
+
+	return 0;
+}
+
+static void snp_handle_guest_request(struct vcpu_svm *svm, struct ghcb *ghcb,
+				     gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request data = {};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_info *sev;
+	int rc, err = 0;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = -ENODEV;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	if (!__ratelimit(&sev->snp_guest_msg_rs)) {
+		pr_info_ratelimited("svm: too many guest message requests\n");
+		rc = -EAGAIN;
+		goto e_fail;
+	}
+
+	rc = snp_build_guest_buf(svm, &data, req_gpa, resp_gpa);
+	if (rc)
+		goto e_fail;
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	mutex_lock(&kvm->lock);
+
+	rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &err);
+	if (rc) {
+		mutex_unlock(&kvm->lock);
+
+		/* If we have a firmware error code then use it. */
+		if (err)
+			rc = err;
+
+		goto e_fail;
+	}
+
+	/* Copy the response after the firmware returns success. */
+	rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
+
+	mutex_unlock(&kvm->lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(ghcb, rc);
+}
+
+static void snp_handle_ext_guest_request(struct vcpu_svm *svm, struct ghcb *ghcb,
+					 gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request req = {};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	unsigned long data_npages;
+	struct kvm_sev_info *sev;
+	unsigned long err;
+	u64 data_gpa;
+	int rc;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = -ENODEV;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	if (!__ratelimit(&sev->snp_guest_msg_rs)) {
+		pr_info_ratelimited("svm: too many guest message requests\n");
+		rc = -EAGAIN;
+		goto e_fail;
+	}
+
+	if (!sev->snp_certs_data) {
+		pr_err("svm: certs data memory is not allocated\n");
+		rc = -EFAULT;
+		goto e_fail;
+	}
+
+	data_gpa = ghcb_get_rax(ghcb);
+	data_npages = ghcb_get_rbx(ghcb);
+
+	if (!IS_ALIGNED(data_gpa, PAGE_SIZE)) {
+		pr_err_ratelimited("svm: certs data GPA is not page aligned (%#llx)\n", data_gpa);
+		rc = -EINVAL;
+		goto e_fail;
+	}
+
+	/* Verify that requested blob will fit in our intermediate buffer */
+	if ((data_npages << PAGE_SHIFT) > SEV_FW_BLOB_MAX_SIZE) {
+		rc = -EINVAL;
+		goto e_fail;
+	}
+
+	rc = snp_build_guest_buf(svm, &req, req_gpa, resp_gpa);
+	if (rc)
+		goto e_fail;
+
+	mutex_lock(&kvm->lock);
+	rc = snp_guest_ext_guest_request(&req, (unsigned long)sev->snp_certs_data,
+					 &data_npages, &err);
+	if (rc) {
+		mutex_unlock(&kvm->lock);
+
+		/*
+		 * If buffer length is small then return the expected
+		 * length in rbx.
+		 */
+		if (err == SNP_GUEST_REQ_INVALID_LEN) {
+			vcpu->arch.regs[VCPU_REGS_RBX] = data_npages;
+			ghcb_set_sw_exit_info_2(ghcb, err);
+			return;
+		}
+
+		/* If we have a firmware error code then use it. */
+		if (err)
+			rc = (int)err;
+
+		goto e_fail;
+	}
+
+	/* Copy the response after the firmware returns success. */
+	rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
+
+	mutex_unlock(&kvm->lock);
+
+	if (rc)
+		goto e_fail;
+
+	/* Copy the certificate blob in the guest memory */
+	if (data_npages &&
+	    kvm_write_guest(kvm, data_gpa, sev->snp_certs_data, data_npages << PAGE_SHIFT))
+		rc = -EFAULT;
+
+e_fail:
+	ghcb_set_sw_exit_info_2(ghcb, rc);
+}
+
 static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 {
 	struct vmcb_control_area *control = &svm->vmcb->control;
@@ -3306,6 +3508,21 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		ghcb_set_sw_exit_info_2(ghcb, rc);
 		break;
 	}
+	case SVM_VMGEXIT_GUEST_REQUEST: {
+		snp_handle_guest_request(svm, ghcb, control->exit_info_1, control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
+	case SVM_VMGEXIT_EXT_GUEST_REQUEST: {
+		snp_handle_ext_guest_request(svm,
+					     ghcb,
+					     control->exit_info_1,
+					     control->exit_info_2);
+
+		ret = 1;
+		break;
+	}
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
arch/x86/kvm/svm/svm.h +5 -1
index ccdaaa4e1fb1..9fcfc0a51737 100644
@@ -18,6 +18,7 @@
 #include <linux/kvm_types.h>
 #include <linux/kvm_host.h>
 #include <linux/bits.h>
+#include <linux/ratelimit.h>
 
 #include <asm/svm.h>
 #include <asm/sev-common.h>
@@ -68,6 +69,9 @@ struct kvm_sev_info {
 	struct kvm *enc_context_owner; /* Owner of copied encryption context */
 	struct misc_cg *misc_cg; /* For misc cgroup accounting */
 	void *snp_context;      /* SNP guest context page */
+	void *snp_resp_page;	/* SNP guest response page */
+	struct ratelimit_state snp_guest_msg_rs; /* Rate limit the SNP guest message */
+	void *snp_certs_data;
 };
 
 struct kvm_svm {
@@ -550,7 +554,7 @@ void svm_vcpu_unblocking(struct kvm_vcpu *vcpu);
 #define GHCB_VERSION_MAX	2ULL
 #define GHCB_VERSION_MIN	1ULL
 
-#define GHCB_HV_FT_SUPPORTED	0
+#define GHCB_HV_FT_SUPPORTED	GHCB_HV_FT_SNP
 
 extern unsigned int max_sev_asid;
 
Signature · 1 line
2.17.1
#164 lore raw

Re: [PATCH Part2 RFC v4 38/40] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

Quoted 4 lines · Brijesh Singh

Version 2 of GHCB specification added the support two SNP Guest Request Message NAE event. The events allows for an SEV-SNP guest to make request to the SEV-SNP firmware through hypervisor using the SNP_GUEST_REQUEST API define in the SEV-SNP firmware specification.

IIUC, this snippet in the spec means KVM can't restrict what requests are made by the guests. If so, that makes it difficult to detect/ratelimit a misbehaving guest, and also limits our options if there are firmware issues (hopefully there aren't). E.g. ratelimiting a guest after KVM has explicitly requested it to migrate is not exactly desirable.

The hypervisor cannot alter the messages without detection nor read the plaintext of the messages.

Quoted 5 lines

The SNP_GUEST_REQUEST requires two unique pages, one page for the request and one page for the response. The response page need to be in the firmware state. The GHCB specification says that both the pages need to be in the hypervisor state but before executing the SEV-SNP command the response page need to be in the firmware state.

...

Quoted 2 lines

Now that KVM supports all the VMGEXIT NAEs required for the base SEV-SNP feature, set the hypervisor feature to advertise it.

It would helpful if this changelog listed the Guest Requests that are required for "base" SNP, e.g. to provide some insight as to why we care about guest requests.

arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1635

Quoted 7 lines

static int snp_bind_asid(struct kvm *kvm, int *error)

arch/x86/kvm/svm/sev.c +2 -0
@@ -1618,6 +1631,12 @@ static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
 	if (rc)
 		goto e_free_context;
 
+	/* Used for rate limiting SNP guest message request, use the default settings */
+	ratelimit_default_init(&sev->snp_guest_msg_rs);

Is this exposed to userspace in any way? This feels very much like a knob that needs to be configurable per-VM.

Also, what are the estimated latencies of a guest request? If the worst case latency is >200ms, a default ratelimit frequency of 5hz isn't going to do a whole lot.

Quoted 9 lines
arch/x86/kvm/svm/sev.c +9 -0
+static void snp_handle_guest_request(struct vcpu_svm *svm, struct ghcb *ghcb,
+				     gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request data = {};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	struct kvm_sev_info *sev;
+	int rc, err = 0;
+

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3136

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = -ENODEV;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	if (!__ratelimit(&sev->snp_guest_msg_rs)) {
+		pr_info_ratelimited("svm: too many guest message requests\n");
+		rc = -EAGAIN;

What guarantee do we have that the guest actually understands -EAGAIN? Ditto for -EINVAL returned by snp_build_guest_buf(). AFAICT, our options are to return one of the error codes defined in "Table 95. Status Codes for SNP_GUEST_REQUEST" of the firmware ABI, kill the guest, or ratelimit the guest without returning control to the guest.

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3146

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+		goto e_fail;
+	}
+
+	rc = snp_build_guest_buf(svm, &data, req_gpa, resp_gpa);
+	if (rc)
+		goto e_fail;
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	mutex_lock(&kvm->lock);

Question on the VMPCK sequences. The firmware ABI says:

Each guest has four VMPCKs ... Each message contains a sequence number per VMPCK. The sequence number is incremented with each message sent. Messages sent by the guest to the firmware and by the firmware to the guest must be delivered in order. If not, the firmware will reject subsequent messages ...

Does that mean there are four independent sequences, i.e. four streams the guest can use "concurrently", or does it mean the overall freshess/integrity check is composed from four VMPCK sequences, all of which must be correct for the message to be valid?

If it's the latter, then a traditional mutex isn't really necessary because the guest must implement its own serialization, e.g. it's own mutex or whatever, to ensure there is at most one request in-flight at any given time. And on the KVM side it means KVM can simpy reject requests if there is already an in-flight request. It might also give us more/better options for ratelimiting?

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3150

Quoted 3 lines
arch/x86/kvm/svm/sev.c +3 -0
+	rc = sev_issue_cmd(kvm, SEV_CMD_SNP_GUEST_REQUEST, &data, &err);
+	if (rc) {
+		mutex_unlock(&kvm->lock);

I suspect you reused this pattern from other, more complex code, but here it's overkill. E.g.

	if (!rc)
		rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
	else if (err)
		rc = err;

	mutex_unlock(&kvm->lock);

	ghcb_set_sw_exit_info_2(ghcb, rc);
Quoted 34 lines
arch/x86/kvm/svm/sev.c +34 -0
+		/* If we have a firmware error code then use it. */
+		if (err)
+			rc = err;
+
+		goto e_fail;
+	}
+
+	/* Copy the response after the firmware returns success. */
+	rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
+
+	mutex_unlock(&kvm->lock);
+
+e_fail:
+	ghcb_set_sw_exit_info_2(ghcb, rc);
+}
+
+static void snp_handle_ext_guest_request(struct vcpu_svm *svm, struct ghcb *ghcb,
+					 gpa_t req_gpa, gpa_t resp_gpa)
+{
+	struct sev_data_snp_guest_request req = {};
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm *kvm = vcpu->kvm;
+	unsigned long data_npages;
+	struct kvm_sev_info *sev;
+	unsigned long err;
+	u64 data_gpa;
+	int rc;
+
+	if (!sev_snp_guest(vcpu->kvm)) {
+		rc = -ENODEV;
+		goto e_fail;
+	}
+
+	sev = &to_kvm_svm(kvm)->sev_info;

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3195

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+	if (!__ratelimit(&sev->snp_guest_msg_rs)) {
+		pr_info_ratelimited("svm: too many guest message requests\n");
+		rc = -EAGAIN;
+		goto e_fail;
+	}
+
+	if (!sev->snp_certs_data) {
+		pr_err("svm: certs data memory is not allocated\n");
+		rc = -EFAULT;

Another instance where the kernel's error numbers will not suffice.

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+		goto e_fail;
+	}
+
+	data_gpa = ghcb_get_rax(ghcb);
+	data_npages = ghcb_get_rbx(ghcb);
#165 lore raw

Re: [PATCH Part2 RFC v4 38/40] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

On 7/19/21 5:50 PM, Sean Christopherson wrote:
...

Quoted 7 lines

IIUC, this snippet in the spec means KVM can't restrict what requests are made by the guests. If so, that makes it difficult to detect/ratelimit a misbehaving guest, and also limits our options if there are firmware issues (hopefully there aren't). E.g. ratelimiting a guest after KVM has explicitly requested it to migrate is not exactly desirable.

The guest message page contains a message header followed by the encrypted payload. So, technically KVM can peek into the message header format to determine the message request type. If needed, we can ratelimit based on the message type.

In the current series we don't support migration etc so I decided to ratelimit unconditionally.

...

Quoted 8 lines
Quoted 3 lines

Now that KVM supports all the VMGEXIT NAEs required for the base SEV-SNP feature, set the hypervisor feature to advertise it.

It would helpful if this changelog listed the Guest Requests that are required for "base" SNP, e.g. to provide some insight as to why we care about guest requests.

Sure, I'll add more.

Quoted 11 lines

arch/x86/kvm/svm/sev.c static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp) · line 1635

Quoted 7 lines

static int snp_bind_asid(struct kvm *kvm, int *error)

arch/x86/kvm/svm/sev.c +2 -0
@@ -1618,6 +1631,12 @@ static int snp_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
  	if (rc)
  		goto e_free_context;
 
+	/* Used for rate limiting SNP guest message request, use the default settings */
+	ratelimit_default_init(&sev->snp_guest_msg_rs);

Is this exposed to userspace in any way? This feels very much like a knob that needs to be configurable per-VM.

It's not exposed to the userspace and I am not sure if userspace care about this knob.

Quoted 4 lines

Also, what are the estimated latencies of a guest request? If the worst case latency is >200ms, a default ratelimit frequency of 5hz isn't going to do a whole lot.

The latency will depend on what else is going in the system at the time the request comes to the hypervisor. Access to the PSP is serialized so other parallel PSP command execution will contribute to the latency.

...

Quoted 11 lines

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3136

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+
+	if (!__ratelimit(&sev->snp_guest_msg_rs)) {
+		pr_info_ratelimited("svm: too many guest message requests\n");
+		rc = -EAGAIN;

What guarantee do we have that the guest actually understands -EAGAIN? Ditto for -EINVAL returned by snp_build_guest_buf(). AFAICT, our options are to return one of the error codes defined in "Table 95. Status Codes for SNP_GUEST_REQUEST" of the firmware ABI, kill the guest, or ratelimit the guest without returning control to the guest.

Yes, let me look into passing one of the status code defined in the spec.

Quoted 18 lines

arch/x86/kvm/svm/sev.c static unsigned long snp_handle_psc(struct vcpu_svm *svm, struct ghcb *ghcb) · line 3146

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+		goto e_fail;
+	}
+
+	rc = snp_build_guest_buf(svm, &data, req_gpa, resp_gpa);
+	if (rc)
+		goto e_fail;
+
+	sev = &to_kvm_svm(kvm)->sev_info;
+
+	mutex_lock(&kvm->lock);

Question on the VMPCK sequences. The firmware ABI says:

Each guest has four VMPCKs ... Each message contains a sequence number per VMPCK. The sequence number is incremented with each message sent. Messages sent by the guest to the firmware and by the firmware to the guest must be delivered in order. If not, the firmware will reject subsequent messages ...

Quoted 5 lines

Does that mean there are four independent sequences, i.e. four streams the guest can use "concurrently", or does it mean the overall freshess/integrity check is composed from four VMPCK sequences, all of which must be correct for the message to be valid?

There are four independent sequence counter and in theory guest can use them concurrently. But the access to the PSP must be serialized. Currently, the guest driver uses the VMPCK0 key to communicate with the PSP.

Quoted 3 lines

If it's the latter, then a traditional mutex isn't really necessary because the guest must implement its own serialization, e.g. it's own mutex or whatever, to ensure there is at most one request in-flight at any given time.

The guest driver uses the its own serialization to ensure that there is *exactly* one request in-flight.

The mutex used here is to protect the KVM's internal firmware response buffer.

And on the KVM

Quoted 3 lines

side it means KVM can simpy reject requests if there is already an in-flight request. It might also give us more/better options for ratelimiting?

I don't think we should be running into this scenario unless there is a bug in the guest kernel. The guest kernel support and CCP driver both ensure that request to the PSP is serialized.

In normal operation we may see 1 to 2 quest requests for the entire guest lifetime. I am thinking first request maybe for the attestation report and second maybe to derive keys etc. It may change slightly when we add the migration command; I have not looked into a great detail yet.

thanks

#166 lore raw

Re: [PATCH Part2 RFC v4 38/40] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

Quoted 11 lines · Brijesh Singh

On 7/19/21 5:50 PM, Sean Christopherson wrote:
...

Quoted 7 lines

IIUC, this snippet in the spec means KVM can't restrict what requests are made by the guests. If so, that makes it difficult to detect/ratelimit a misbehaving guest, and also limits our options if there are firmware issues (hopefully there aren't). E.g. ratelimiting a guest after KVM has explicitly requested it to migrate is not exactly desirable.

Quoted 4 lines

The guest message page contains a message header followed by the encrypted payload. So, technically KVM can peek into the message header format to determine the message request type. If needed, we can ratelimit based on the message type.

Ah, I got confused by this code in snp_build_guest_buf():

	data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);

I was thinking that setting the C-bit meant the memory was guest private, but that's setting the C-bit for the HPA, which is correct since KVM installs guest memory with C-bit=1 in the NPT, i.e. encrypts shared memory with the host key.

Tangetially related question, is it correct to say that the host can _read_ memory from a page that is assigned=1, but has asid=0? I.e. KVM can read the response page in order to copy it into the guest, even though it is a firmware page?

	/* Copy the response after the firmware returns success. */
	rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
Quoted 2 lines

In the current series we don't support migration etc so I decided to ratelimit unconditionally.

Since KVM can peek at the request header, KVM should flat out disallow requests that KVM doesn't explicitly support. E.g. migration requests should not be sent to the PSP.

One concern though: How does the guest query what requests are supported? This snippet implies there's some form of enumeration:

Note: This guest message may be removed in future versions as it is redundant with the CPUID page in SNP_LAUNCH_UPDATE (see Section 8.14).

But all I can find is a "Message Version" in "Table 94. Message Type Encodings", which implies that request support is all or nothing for a given version. That would be rather unfortunate as KVM has no way to tell the guest that something is unsupported :-(

Quoted 5 lines
Quoted 2 lines

Is this exposed to userspace in any way? This feels very much like a knob that needs to be configurable per-VM.

It's not exposed to the userspace and I am not sure if userspace care about this knob.

Userspace definitely cares, otherwise the system would need to be rebooted just to tune the ratelimiting. And userspace may want to disable ratelimiting entirely, e.g. if the entire system is dedicated to a single VM.

Quoted 8 lines
Quoted 4 lines

Also, what are the estimated latencies of a guest request? If the worst case latency is >200ms, a default ratelimit frequency of 5hz isn't going to do a whole lot.

The latency will depend on what else is going in the system at the time the request comes to the hypervisor. Access to the PSP is serialized so other parallel PSP command execution will contribute to the latency.

I get that it will be variable, but what are some ballpark latencies? E.g. what's the latency of the slowest command without PSP contention?

Quoted 7 lines
Quoted 7 lines

Question on the VMPCK sequences. The firmware ABI says:

Each guest has four VMPCKs ... Each message contains a sequence number per VMPCK. The sequence number is incremented with each message sent. Messages sent by the guest to the firmware and by the firmware to the guest must be delivered in order. If not, the firmware will reject subsequent messages ...

Quoted 8 lines
Quoted 5 lines

Does that mean there are four independent sequences, i.e. four streams the guest can use "concurrently", or does it mean the overall freshess/integrity check is composed from four VMPCK sequences, all of which must be correct for the message to be valid?

There are four independent sequence counter and in theory guest can use them concurrently. But the access to the PSP must be serialized.

Technically that's not required from the guest's perspective, correct? The guest only cares about the sequence numbers for a given VMPCK, e.g. it can have one in-flight request per VMPCK and expect that to work, even without fully serializing its own requests.

Out of curiosity, why 4 VMPCKs? It seems completely arbitrary.

Quoted 9 lines

Currently, the guest driver uses the VMPCK0 key to communicate with the PSP.

Quoted 3 lines

If it's the latter, then a traditional mutex isn't really necessary because the guest must implement its own serialization, e.g. it's own mutex or whatever, to ensure there is at most one request in-flight at any given time.

The guest driver uses the its own serialization to ensure that there is *exactly* one request in-flight.

But KVM can't rely on that because it doesn't control the guest, e.g. it may be running a non-Linux guest.

Quoted 2 lines

The mutex used here is to protect the KVM's internal firmware response buffer.

Ya, where I was going with my question was that if the guest was architecturally restricted to a single in-flight request, then KVM could do something like this instead of taking kvm->lock (bad pseudocode):

	if (test_and_set(sev->guest_request)) {
		rc = AEAD_OFLOW;
		goto fail;
	}

	<do request>

	clear_bit(...)

I.e. multiple in-flight requests can't work because the guest can guarantee ordering between vCPUs. But, because the guest can theoretically have up to four in-flight requests, it's not that simple.

The reason I'm going down this path is that taking kvm->lock inside vcpu->mutex violates KVM's locking rules, i.e. is susceptibl to deadlocks. Per kvm/locking.rst,

- kvm->lock is taken outside vcpu->mutex

That means a different mutex is needed to protect the guest request pages.

Quoted 7 lines
Quoted 3 lines

And on the KVM side it means KVM can simpy reject requests if there is already an in-flight request. It might also give us more/better options for ratelimiting?

I don't think we should be running into this scenario unless there is a bug in the guest kernel. The guest kernel support and CCP driver both ensure that request to the PSP is serialized.

Again, what the Linux kernel does is irrelevant. What matters is what is architecturally allowed.

Quoted 4 lines

In normal operation we may see 1 to 2 quest requests for the entire guest lifetime. I am thinking first request maybe for the attestation report and second maybe to derive keys etc. It may change slightly when we add the migration command; I have not looked into a great detail yet.

#167 lore raw

Re: [PATCH Part2 RFC v4 38/40] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

Quoted 5 lines · Sean Christopherson

Ah, I got confused by this code in snp_build_guest_buf():

	data->req_paddr = __sme_set(req_pfn << PAGE_SHIFT);
Quoted 8 lines

I was thinking that setting the C-bit meant the memory was guest private, but that's setting the C-bit for the HPA, which is correct since KVM installs guest memory with C-bit=1 in the NPT, i.e. encrypts shared memory with the host key.

Tangetially related question, is it correct to say that the host can _read_ memory from a page that is assigned=1, but has asid=0? I.e. KVM can read the response page in order to copy it into the guest, even though it is a firmware page?

Yes. The firmware page means that x86 cannot write to it; the read is still allowed.

Quoted 10 lines
	/* Copy the response after the firmware returns success. */
	rc = kvm_write_guest(kvm, resp_gpa, sev->snp_resp_page, PAGE_SIZE);
Quoted 2 lines

In the current series we don't support migration etc so I decided to ratelimit unconditionally.

Since KVM can peek at the request header, KVM should flat out disallow requests that KVM doesn't explicitly support. E.g. migration requests should not be sent to the PSP.

That is acceptable.

Quoted 11 lines

One concern though: How does the guest query what requests are supported? This snippet implies there's some form of enumeration:

Note: This guest message may be removed in future versions as it is redundant with the CPUID page in SNP_LAUNCH_UPDATE (see Section 8.14).

But all I can find is a "Message Version" in "Table 94. Message Type Encodings", which implies that request support is all or nothing for a given version. That would be rather unfortunate as KVM has no way to tell the guest that something is unsupported :-(

The firmware supports all the commands listed in the spec. The HV support is always going to be behind what a firmware or hardware is capable of doing. As per the spec is concerned, it say

The firmware checks that MSG_TYPE is a valid message type. The firmware then checks that MSG_SIZE is large enough to hold the indicated message type at the indicated message version. If not, the firmware returns INVALID_PARAM.

So, a hypervisor could potentially send the INVALID_PARAMS to indicate that guest that a message type is not supported.

Quoted 9 lines
Quoted 5 lines
Quoted 2 lines

Is this exposed to userspace in any way? This feels very much like a knob that needs to be configurable per-VM.

It's not exposed to the userspace and I am not sure if userspace care about this knob.

Userspace definitely cares, otherwise the system would need to be rebooted just to tune the ratelimiting. And userspace may want to disable ratelimiting entirely, e.g. if the entire system is dedicated to a single VM.

Ok.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

Also, what are the estimated latencies of a guest request? If the worst case latency is >200ms, a default ratelimit frequency of 5hz isn't going to do a whole lot.

Quoted 7 lines
Quoted 3 lines

The latency will depend on what else is going in the system at the time the request comes to the hypervisor. Access to the PSP is serialized so other parallel PSP command execution will contribute to the latency.

I get that it will be variable, but what are some ballpark latencies? E.g. what's the latency of the slowest command without PSP contention?

In my single VM, I am seeing latency of guest request to be around ~35ms.

Quoted 13 lines
Quoted 13 lines
Quoted 12 lines

Question on the VMPCK sequences. The firmware ABI says:

Each guest has four VMPCKs ... Each message contains a sequence number per VMPCK. The sequence number is incremented with each message sent. Messages sent by the guest to the firmware and by the firmware to the guest must be delivered in order. If not, the firmware will reject subsequent messages ...

Does that mean there are four independent sequences, i.e. four streams the guest can use "concurrently", or does it mean the overall freshess/integrity check is composed from four VMPCK sequences, all of which must be correct for the message to be valid?

Quoted 4 lines
Quoted 2 lines

There are four independent sequence counter and in theory guest can use them concurrently. But the access to the PSP must be serialized.

Technically that's not required from the guest's perspective, correct?

Correct.

The guest

Quoted 6 lines

only cares about the sequence numbers for a given VMPCK, e.g. it can have one in-flight request per VMPCK and expect that to work, even without fully serializing its own requests.

Out of curiosity, why 4 VMPCKs? It seems completely arbitrary.

I believe the thought process was by providing 4 keys it can provide flexibility for each VMPL levels to use a different keys (if they wish). The firmware does not care about the vmpl level during the guest request handling, it just want to know which key is used for encrypting the payload so that he can decrypt and provide the response for it.

Quoted 7 lines
Quoted 7 lines

Currently, the guest driver uses the VMPCK0 key to communicate with the PSP.

Quoted 3 lines

If it's the latter, then a traditional mutex isn't really necessary because the guest must implement its own serialization, e.g. it's own mutex or whatever, to ensure there is at most one request in-flight at any given time.

Quoted 6 lines
Quoted 2 lines

The guest driver uses the its own serialization to ensure that there is *exactly* one request in-flight.

But KVM can't rely on that because it doesn't control the guest, e.g. it may be running a non-Linux guest.

Yes, KVM should not rely on it. I mentioned that mainly because you said that guest must implement its own serialization. In the case of KVM, the CCP driver ensure that the command sent to the PSP is serialized.

Quoted 20 lines
Quoted 2 lines

The mutex used here is to protect the KVM's internal firmware response buffer.

Ya, where I was going with my question was that if the guest was architecturally restricted to a single in-flight request, then KVM could do something like this instead of taking kvm->lock (bad pseudocode):

	if (test_and_set(sev->guest_request)) {
		rc = AEAD_OFLOW;
		goto fail;
	}

	<do request>

	clear_bit(...)

I.e. multiple in-flight requests can't work because the guest can guarantee ordering between vCPUs. But, because the guest can theoretically have up to four in-flight requests, it's not that simple.

Quoted 7 lines

The reason I'm going down this path is that taking kvm->lock inside vcpu->mutex violates KVM's locking rules, i.e. is susceptibl to deadlocks. Per kvm/locking.rst,

- kvm->lock is taken outside vcpu->mutex

That means a different mutex is needed to protect the guest request pages.

Ah, I see your point on the locking. From architecturally a guest can issue multiple requests in parallel. It sounds like having a separate lock to protect the guest request pages makes sense.

-Brijesh

#168 lore raw

Re: [PATCH Part2 RFC v4 38/40] KVM: SVM: Provide support for SNP_GUEST_REQUEST NAE event

Quoted 10 lines · Brijesh Singh
Quoted 2 lines · Sean Christopherson

Out of curiosity, why 4 VMPCKs? It seems completely arbitrary.

I believe the thought process was by providing 4 keys it can provide flexibility for each VMPL levels to use a different keys (if they wish). The firmware does not care about the vmpl level during the guest request handling, it just want to know which key is used for encrypting the payload so that he can decrypt and provide the response for it.

Ah, I forgot about VMPLs. That makes sense.

Thanks!

#169 lore raw

RFC PATCH v4 39/40 KVM: SVM: Use a VMSA physical address variable for populating VMCB

In reply to Brijesh Singh

From: Tom Lendacky <[email protected]>

In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.

---
 arch/x86/kvm/svm/sev.c | 5 ++---
 arch/x86/kvm/svm/svm.c | 9 ++++++++-
 arch/x86/kvm/svm/svm.h | 1 +
 3 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +2 -3
index 4cb4c1d7e444..d8ad6dd58c87 100644
@@ -3553,10 +3553,9 @@ void sev_es_init_vmcb(struct vcpu_svm *svm)
 
 	/*
 	 * An SEV-ES guest requires a VMSA area that is a separate from the
-	 * VMCB page. Do not include the encryption mask on the VMSA physical
-	 * address since hardware will access it using the guest key.
+	 * VMCB page.
 	 */
-	svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);
+	svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
 
 	/* Can't intercept CR register access, HV can't modify CR registers */
 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
arch/x86/kvm/svm/svm.c +8 -1
index 32e35d396508..74bc635c9608 100644
@@ -1379,9 +1379,16 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)
 	svm->vmcb01.ptr = page_address(vmcb01_page);
 	svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
 
-	if (vmsa_page)
+	if (vmsa_page) {
 		svm->vmsa = page_address(vmsa_page);
 
+		/*
+		 * Do not include the encryption mask on the VMSA physical
+		 * address since hardware will access it using the guest key.
+		 */
+		svm->vmsa_pa = __pa(svm->vmsa);
+	}
+
 	svm->guest_state_loaded = false;
 
 	svm_switch_vmcb(svm, &svm->vmcb01);
arch/x86/kvm/svm/svm.h +1 -0
index 9fcfc0a51737..285d9b97b4d2 100644
@@ -177,6 +177,7 @@ struct vcpu_svm {
 
 	/* SEV-ES support */
 	struct sev_es_save_area *vmsa;
+	hpa_t vmsa_pa;
 	struct ghcb *ghcb;
 	struct kvm_host_map ghcb_map;
 	bool received_first_sipi;
Signature · 1 line
2.17.1
#170 lore raw

Re: [PATCH Part2 RFC v4 39/40] KVM: SVM: Use a VMSA physical address variable for populating VMCB

Quoted 6 lines · Brijesh Singh

From: Tom Lendacky <[email protected]>

In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.

I'm pretty sure adding vmsa_pa is unnecessary. The next patch sets svm->vmsa_pa and vmcb->control.vmsa_pa as a pair. And for the existing code, my proposed patch to emulate INIT on shutdown would eliminate the one path that zeros the VMCB[1]. That series patch also drops the init_vmcb() in svm_create_vcpu()[2].

Assuming there are no VMCB shenanigans I'm missing, sev_es_init_vmcb() can do

	if (!init_event)
		svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);

And while I'm thinking of it, the next patch should ideally free svm->vmsa when the the guest configures a new VMSA for the vCPU.

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

Quoted 62 lines
---
 arch/x86/kvm/svm/sev.c | 5 ++---
 arch/x86/kvm/svm/svm.c | 9 ++++++++-
 arch/x86/kvm/svm/svm.h | 1 +
 3 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +2 -3
index 4cb4c1d7e444..d8ad6dd58c87 100644
@@ -3553,10 +3553,9 @@ void sev_es_init_vmcb(struct vcpu_svm *svm)
 
 	/*
 	 * An SEV-ES guest requires a VMSA area that is a separate from the
-	 * VMCB page. Do not include the encryption mask on the VMSA physical
-	 * address since hardware will access it using the guest key.
+	 * VMCB page.
 	 */
-	svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);
+	svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
 
 	/* Can't intercept CR register access, HV can't modify CR registers */
 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
arch/x86/kvm/svm/svm.c +8 -1
index 32e35d396508..74bc635c9608 100644
@@ -1379,9 +1379,16 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)
 	svm->vmcb01.ptr = page_address(vmcb01_page);
 	svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
 
-	if (vmsa_page)
+	if (vmsa_page) {
 		svm->vmsa = page_address(vmsa_page);
 
+		/*
+		 * Do not include the encryption mask on the VMSA physical
+		 * address since hardware will access it using the guest key.
+		 */
+		svm->vmsa_pa = __pa(svm->vmsa);
+	}
+
 	svm->guest_state_loaded = false;
 
 	svm_switch_vmcb(svm, &svm->vmcb01);
arch/x86/kvm/svm/svm.h +1 -0
index 9fcfc0a51737..285d9b97b4d2 100644
@@ -177,6 +177,7 @@ struct vcpu_svm {
 
 	/* SEV-ES support */
 	struct sev_es_save_area *vmsa;
+	hpa_t vmsa_pa;
 	struct ghcb *ghcb;
 	struct kvm_host_map ghcb_map;
 	bool received_first_sipi;
Signature · 1 line
2.17.1
maintainer
#171 lore raw

Re: [PATCH Part2 RFC v4 39/40] KVM: SVM: Use a VMSA physical address variable for populating VMCB

Quoted 13 lines · Sean Christopherson
Quoted 6 lines · Brijesh Singh

From: Tom Lendacky <[email protected]>

In preparation to support SEV-SNP AP Creation, use a variable that holds the VMSA physical address rather than converting the virtual address. This will allow SEV-SNP AP Creation to set the new physical address that will be used should the vCPU reset path be taken.

I'm pretty sure adding vmsa_pa is unnecessary. The next patch sets svm->vmsa_pa and vmcb->control.vmsa_pa as a pair. And for the existing code, my proposed patch to emulate INIT on shutdown would eliminate the one path that zeros the VMCB[1]. That series patch also drops the init_vmcb() in svm_create_vcpu()[2].

Quoted 4 lines

Assuming there are no VMCB shenanigans I'm missing, sev_es_init_vmcb() can do

	if (!init_event)
		svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);

That will require passing init_event through to init_vmcb and successive functions and ensuring that there isn't a path that could cause it to not be set after it should no longer be used. This is very simple at the moment, but maybe can be re-worked once all of the other changes you mention are integrated.

Thanks,
Tom

Quoted 69 lines

And while I'm thinking of it, the next patch should ideally free svm->vmsa when the the guest configures a new VMSA for the vCPU.

[1] https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Flkml.kernel.org%2Fr%2F20210713163324.627647-45-seanjc%40google.com&amp;data=04%7C01%7Cthomas.lendacky%40amd.com%7Cef81e5604f5242262b6908d94bdd5b32%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637624236352681486%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&amp;sdata=O3LKXhVLqNuT1PpCNzkjG8Vho7wfMEibFgGbZkoFlMk%3D&amp;reserved=0
[2] https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Flkml.kernel.org%2Fr%2F20210713163324.627647-10-seanjc%40google.com&amp;data=04%7C01%7Cthomas.lendacky%40amd.com%7Cef81e5604f5242262b6908d94bdd5b32%7C3dd8961fe4884e608e11a82d994e183d%7C0%7C0%7C637624236352681486%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C1000&amp;sdata=rn6zZZbGEnN4Hd60Mg3EsPU3fIaoBHdA3jTluiDRvpo%3D&amp;reserved=0

Quoted 62 lines
---
 arch/x86/kvm/svm/sev.c | 5 ++---
 arch/x86/kvm/svm/svm.c | 9 ++++++++-
 arch/x86/kvm/svm/svm.h | 1 +
 3 files changed, 11 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/sev.c +2 -3
index 4cb4c1d7e444..d8ad6dd58c87 100644
@@ -3553,10 +3553,9 @@ void sev_es_init_vmcb(struct vcpu_svm *svm)
 
 	/*
 	 * An SEV-ES guest requires a VMSA area that is a separate from the
-	 * VMCB page. Do not include the encryption mask on the VMSA physical
-	 * address since hardware will access it using the guest key.
+	 * VMCB page.
 	 */
-	svm->vmcb->control.vmsa_pa = __pa(svm->vmsa);
+	svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
 
 	/* Can't intercept CR register access, HV can't modify CR registers */
 	svm_clr_intercept(svm, INTERCEPT_CR0_READ);
arch/x86/kvm/svm/svm.c +8 -1
index 32e35d396508..74bc635c9608 100644
@@ -1379,9 +1379,16 @@ static int svm_create_vcpu(struct kvm_vcpu *vcpu)
 	svm->vmcb01.ptr = page_address(vmcb01_page);
 	svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
 
-	if (vmsa_page)
+	if (vmsa_page) {
 		svm->vmsa = page_address(vmsa_page);
 
+		/*
+		 * Do not include the encryption mask on the VMSA physical
+		 * address since hardware will access it using the guest key.
+		 */
+		svm->vmsa_pa = __pa(svm->vmsa);
+	}
+
 	svm->guest_state_loaded = false;
 
 	svm_switch_vmcb(svm, &svm->vmcb01);
arch/x86/kvm/svm/svm.h +1 -0
index 9fcfc0a51737..285d9b97b4d2 100644
@@ -177,6 +177,7 @@ struct vcpu_svm {
 
 	/* SEV-ES support */
 	struct sev_es_save_area *vmsa;
+	hpa_t vmsa_pa;
 	struct ghcb *ghcb;
 	struct kvm_host_map ghcb_map;
 	bool received_first_sipi;
Signature · 1 line
2.17.1
#172 lore raw

RFC PATCH v4 40/40 KVM: SVM: Support SEV-SNP AP Creation NAE event

In reply to Brijesh Singh

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to create and start APs on their own.

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

---
 arch/x86/include/asm/kvm_host.h |   3 +
 arch/x86/include/asm/svm.h      |   3 +
 arch/x86/kvm/svm/sev.c          | 133 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c          |   7 +-
 arch/x86/kvm/svm/svm.h          |  16 +++-
 arch/x86/kvm/x86.c              |  11 ++-
 6 files changed, 170 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index 117e2e08d7ed..881e05b3f74e 100644
@@ -91,6 +91,7 @@
 #define KVM_REQ_MSR_FILTER_CHANGED	KVM_ARCH_REQ(29)
 #define KVM_REQ_UPDATE_CPU_DIRTY_LOGGING \
 	KVM_ARCH_REQ_FLAGS(30, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
+#define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE	KVM_ARCH_REQ(31)
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -1402,6 +1403,8 @@ struct kvm_x86_ops {
 
 	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
 			int level, u64 error_code);
+
+	void (*update_protected_guest_state)(struct kvm_vcpu *vcpu);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/include/asm/svm.h +3 -0
index 5e72faa00cf2..6634a952563e 100644
@@ -220,6 +220,9 @@ struct __attribute__ ((__packed__)) vmcb_control_area {
 #define SVM_SEV_FEATURES_DEBUG_SWAP		BIT(5)
 #define SVM_SEV_FEATURES_PREVENT_HOST_IBS	BIT(6)
 #define SVM_SEV_FEATURES_BTB_ISOLATION		BIT(7)
+#define SVM_SEV_FEATURES_INT_INJ_MODES			\
+	(SVM_SEV_FEATURES_RESTRICTED_INJECTION |	\
+	 SVM_SEV_FEATURES_ALTERNATE_INJECTION)
 
 struct vmcb_seg {
 	u16 selector;
arch/x86/kvm/svm/sev.c +133 -0

169 lines not on this page · raw message

arch/x86/kvm/svm/svm.c +6 -1
index 74bc635c9608..078a569c85a8 100644
@@ -1304,7 +1304,10 @@ static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	svm->spec_ctrl = 0;
 	svm->virt_spec_ctrl = 0;
 
-	if (!init_event) {
+	if (init_event && svm->snp_vmsa_update_on_init) {
+		svm->snp_vmsa_update_on_init = false;
+		sev_snp_update_protected_guest_state(vcpu);
+	} else {
 		vcpu->arch.apic_base = APIC_DEFAULT_PHYS_BASE |
 				       MSR_IA32_APICBASE_ENABLE;
 		if (kvm_vcpu_is_reset_bsp(vcpu))
@@ -4588,6 +4591,8 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 	.write_page_begin = sev_snp_write_page_begin,
 
 	.handle_rmp_page_fault = snp_handle_rmp_page_fault,
+
+	.update_protected_guest_state = sev_snp_update_protected_guest_state,
 };
 
 static struct kvm_x86_init_ops svm_init_ops __initdata = {
arch/x86/kvm/svm/svm.h +15 -1
index 285d9b97b4d2..f9d25d944f26 100644
@@ -60,18 +60,26 @@ struct kvm_sev_info {
 	bool active;		/* SEV enabled guest */
 	bool es_active;		/* SEV-ES enabled guest */
 	bool snp_active;	/* SEV-SNP enabled guest */
+
 	unsigned int asid;	/* ASID used for this guest */
 	unsigned int handle;	/* SEV firmware handle */
 	int fd;			/* SEV device fd */
+
 	unsigned long pages_locked; /* Number of pages locked */
 	struct list_head regions_list;  /* List of registered regions */
+
 	u64 ap_jump_table;	/* SEV-ES AP Jump Table address */
+
 	struct kvm *enc_context_owner; /* Owner of copied encryption context */
+
 	struct misc_cg *misc_cg; /* For misc cgroup accounting */
+
 	void *snp_context;      /* SNP guest context page */
 	void *snp_resp_page;	/* SNP guest response page */
 	struct ratelimit_state snp_guest_msg_rs; /* Rate limit the SNP guest message */
 	void *snp_certs_data;
+
+	u64 sev_features;	/* Features set at VMSA creation */
 };
 
 struct kvm_svm {
@@ -192,6 +200,11 @@ struct vcpu_svm {
 	bool guest_state_loaded;
 
 	u64 ghcb_registered_gpa;
+
+	struct mutex snp_vmsa_mutex;
+	gpa_t snp_vmsa_gpa;
+	kvm_pfn_t snp_vmsa_pfn;
+	bool snp_vmsa_update_on_init;	/* SEV-SNP AP Creation on INIT-SIPI */
 };
 
 struct svm_cpu_data {
@@ -555,7 +568,7 @@ void svm_vcpu_unblocking(struct kvm_vcpu *vcpu);
 #define GHCB_VERSION_MAX	2ULL
 #define GHCB_VERSION_MIN	1ULL
 
-#define GHCB_HV_FT_SUPPORTED	GHCB_HV_FT_SNP
+#define GHCB_HV_FT_SUPPORTED	(GHCB_HV_FT_SNP | GHCB_HV_FT_SNP_AP_CREATION)
 
 extern unsigned int max_sev_asid;
 
@@ -584,6 +597,7 @@ int sev_get_tdp_max_page_level(struct kvm_vcpu *vcpu, gpa_t gpa, int max_level);
 void sev_snp_write_page_begin(struct kvm *kvm, struct kvm_memory_slot *slot, gfn_t gfn);
 int snp_handle_rmp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
 			      int level, u64 error_code);
+void sev_snp_update_protected_guest_state(struct kvm_vcpu *vcpu);
 
 /* vmenter.S */
 
arch/x86/kvm/x86.c +10 -1
index 1398b8021982..e9fd59913bc2 100644
@@ -9279,6 +9279,14 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 		if (kvm_check_request(KVM_REQ_UPDATE_CPU_DIRTY_LOGGING, vcpu))
 			static_call(kvm_x86_update_cpu_dirty_logging)(vcpu);
+
+		if (kvm_check_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu)) {
+			kvm_x86_ops.update_protected_guest_state(vcpu);
+			if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) {
+				r = 1;
+				goto out;
+			}
+		}
 	}
 
 	if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win ||
@@ -11236,7 +11244,8 @@ static inline bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu)
 	if (!list_empty_careful(&vcpu->async_pf.done))
 		return true;
 
-	if (kvm_apic_has_events(vcpu))
+	if (kvm_apic_has_events(vcpu) ||
+	    kvm_test_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, vcpu))
 		return true;
 
 	if (vcpu->arch.pv.pv_unhalted)
Signature · 1 line
2.17.1
#173 lore raw

Re: [PATCH Part2 RFC v4 40/40] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 4 lines · Brijesh Singh

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to create and start APs on their own.

The changelog really needs to clarify that this doesn't allow the guest to create arbitrary vCPUs. The GHCB uses CREATE/DESTROY terminology, but this patch and its comments/documentation should very clearly call out that KVM's implementation is more along the line of vCPU online/offline.

It should also be noted that KVM still onlines APs by default. That also raises the question of whether or not KVM should support creating an offlined vCPU. E.g. several of the use cases I'm aware of want to do something along the lines of creating a VM with the max number of theoretical vCPUs, but in most instances only run a handful of vCPUs. That's a fair amount of potential memory savings if the max theoretical number of vCPUs is high.

Quoted 121 lines

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

---
 arch/x86/include/asm/kvm_host.h |   3 +
 arch/x86/include/asm/svm.h      |   3 +
 arch/x86/kvm/svm/sev.c          | 133 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c          |   7 +-
 arch/x86/kvm/svm/svm.h          |  16 +++-
 arch/x86/kvm/x86.c              |  11 ++-
 6 files changed, 170 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index 117e2e08d7ed..881e05b3f74e 100644
@@ -91,6 +91,7 @@
 #define KVM_REQ_MSR_FILTER_CHANGED	KVM_ARCH_REQ(29)
 #define KVM_REQ_UPDATE_CPU_DIRTY_LOGGING \
 	KVM_ARCH_REQ_FLAGS(30, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
+#define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE	KVM_ARCH_REQ(31)
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -1402,6 +1403,8 @@ struct kvm_x86_ops {
 
 	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
 			int level, u64 error_code);
+
+	void (*update_protected_guest_state)(struct kvm_vcpu *vcpu);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/include/asm/svm.h +3 -0
index 5e72faa00cf2..6634a952563e 100644
@@ -220,6 +220,9 @@ struct __attribute__ ((__packed__)) vmcb_control_area {
 #define SVM_SEV_FEATURES_DEBUG_SWAP		BIT(5)
 #define SVM_SEV_FEATURES_PREVENT_HOST_IBS	BIT(6)
 #define SVM_SEV_FEATURES_BTB_ISOLATION		BIT(7)
+#define SVM_SEV_FEATURES_INT_INJ_MODES			\
+	(SVM_SEV_FEATURES_RESTRICTED_INJECTION |	\
+	 SVM_SEV_FEATURES_ALTERNATE_INJECTION)
 
 struct vmcb_seg {
 	u16 selector;
arch/x86/kvm/svm/sev.c +15 -0
index d8ad6dd58c87..95f5d25b4f08 100644
@@ -582,6 +582,7 @@ static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
 
 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
 {
+	struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
 	struct sev_es_save_area *save = svm->vmsa;
 
 	/* Check some debug related fields before encrypting the VMSA */
@@ -625,6 +626,12 @@ static int sev_es_sync_vmsa(struct vcpu_svm *svm)
 	if (sev_snp_guest(svm->vcpu.kvm))
 		save->sev_features |= SVM_SEV_FEATURES_SNP_ACTIVE;
 
+	/*
+	 * Save the VMSA synced SEV features. For now, they are the same for
+	 * all vCPUs, so just save each time.
+	 */
+	sev->sev_features = save->sev_features;
+
 	return 0;
 }
 
@@ -2682,6 +2689,10 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 		if (!ghcb_sw_scratch_is_valid(ghcb))
 			goto vmgexit_err;
 		break;
+	case SVM_VMGEXIT_AP_CREATION:
+		if (!ghcb_rax_is_valid(ghcb))
+			goto vmgexit_err;
+		break;
 	case SVM_VMGEXIT_NMI_COMPLETE:
 	case SVM_VMGEXIT_AP_HLT_LOOP:
 	case SVM_VMGEXIT_AP_JUMP_TABLE:
@@ -3395,6 +3406,121 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 	return ret;
 }
 
+void sev_snp_update_protected_guest_state(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+	kvm_pfn_t pfn;

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3422

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+	mutex_lock(&svm->snp_vmsa_mutex);
+
+	vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
+
+	/* Clear use of the VMSA in the sev_es_init_vmcb() path */
+	svm->vmsa_pa = 0;
+
+	/* Clear use of the VMSA from the VMCB */
+	svm->vmcb->control.vmsa_pa = 0;

PA=0 is not an invalid address. I don't care what value the GHCB uses for "invalid GPA", KVM should always use INVALID_PAGE to track an invalid physical address.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3426

Quoted 3 lines
arch/x86/kvm/svm/sev.c +3 -0
+	/* Un-pin previous VMSA */
+	if (svm->snp_vmsa_pfn) {
+		kvm_release_pfn_dirty(svm->snp_vmsa_pfn);

Oof, I was wondering why KVM tracks three versions of VMSA. Actually, I'm still wondering why there are three versions. Aren't snp_vmsa_pfn and vmsa_pa tracking the same thing? Ah, finally figured it out. vmsa_pa points at svm->vmsa by default. Blech.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3430

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+		svm->snp_vmsa_pfn = 0;
+	}
+
+	if (svm->snp_vmsa_gpa) {

This is bogus, GPA=0 is perfectly valid. As above, use INVALID_PAGE. A comment explaining that the vCPU is offline when VMSA is invalid would also be helpful.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3432

Quoted 2 lines
arch/x86/kvm/svm/sev.c +2 -0
+		/* Validate that the GPA is page aligned */
+		if (!PAGE_ALIGNED(svm->snp_vmsa_gpa))

This needs to be moved to the VMGEXIT, and it should use page_address_valid() so that KVM also checks for a legal GPA.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3436

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+			goto e_unlock;
+
+		/*
+		 * The VMSA is referenced by thy hypervisor physical address,

s/thy/the, although converting to archaic English could be hilarious...

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3441

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+		 * so retrieve the PFN and pin it.
+		 */
+		pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(svm->snp_vmsa_gpa));
+		if (is_error_pfn(pfn))
+			goto e_unlock;

Silently ignoring the guest request is bad behavior, at worst KVM should exit to userspace with an emulation error.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3451

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+		svm->snp_vmsa_pfn = pfn;
+
+		/* Use the new VMSA in the sev_es_init_vmcb() path */
+		svm->vmsa_pa = pfn_to_hpa(pfn);
+		svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
+
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	} else {
+		vcpu->arch.pv.pv_unhalted = false;

Shouldn't the RUNNABLE path also clear pv_unhalted?

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3451

Quoted 1 line
arch/x86/kvm/svm/sev.c +1 -0
+		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;

What happens if userspace calls kvm_arch_vcpu_ioctl_set_mpstate, or even worse the guest sends INIT-SIPI? Unless I'm mistaken, either case will cause KVM to run the vCPU with vmcb->control.vmsa_pa==0.

My initial reaction is that the "offline" case needs a new mp_state, or maybe just use KVM_MP_STATE_STOPPED.

Quoted 13 lines
arch/x86/kvm/svm/sev.c +13 -0
+	}
+
+e_unlock:
+	mutex_unlock(&svm->snp_vmsa_mutex);
+}
+
+static void sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm_vcpu *target_vcpu;
+	struct vcpu_svm *target_svm;
+	unsigned int request;

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3475

Quoted 10 lines
arch/x86/kvm/svm/sev.c +10 -0
+	unsigned int apic_id;
+	bool kick;
+
+	request = lower_32_bits(svm->vmcb->control.exit_info_1);
+	apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
+
+	/* Validate the APIC ID */
+	target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);
+	if (!target_vcpu)
+		return;

KVM should not silently ignore bad requests, this needs to return an error to the guest.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3479

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+
+	target_svm = to_svm(target_vcpu);
+
+	kick = true;

This is wrong, e.g. KVM will kick the target vCPU even if the request fails. I suspect the correct behavior would be to:

1. do all sanity checks
2. take the necessary lock(s)
3. modify target vCPU state
4. kick target vCPU unless request==SVM_VMGEXIT_AP_CREATE_ON_INIT

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3481

Quoted 1 line
arch/x86/kvm/svm/sev.c +1 -0
+	mutex_lock(&target_svm->snp_vmsa_mutex);

This seems like it's missing a big pile of sanity checks. E.g. KVM should reject SVM_VMGEXIT_AP_CREATE if the target vCPU is already "created", including the case where it was "created_on_init" but hasn't yet received INIT-SIPI.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3492

Quoted 11 lines
arch/x86/kvm/svm/sev.c +11 -0
+
+	target_svm->snp_vmsa_gpa = 0;
+	target_svm->snp_vmsa_update_on_init = false;
+
+	/* Interrupt injection mode shouldn't change for AP creation */
+	if (request < SVM_VMGEXIT_AP_DESTROY) {
+		u64 sev_features;
+
+		sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+		sev_features ^= sev->sev_features;
+		if (sev_features & SVM_SEV_FEATURES_INT_INJ_MODES) {

Why is only INT_INJ_MODES checked? The new comment in sev_es_sync_vmsa() explicitly states that sev_features are the same for all vCPUs, but that's not enforced here. At a bare minimum I would expect this to sanity check SVM_SEV_FEATURES_SNP_ACTIVE.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3500

Quoted 8 lines
arch/x86/kvm/svm/sev.c +8 -0
+			vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+				    vcpu->arch.regs[VCPU_REGS_RAX]);
+			goto out;
+		}
+	}
+
+	switch (request) {
+	case SVM_VMGEXIT_AP_CREATE_ON_INIT:

Out of curiosity, what's the use case for this variant? I assume the guest has to preconfigure the VMSA and ensure the target vCPU's RIP points at something sane anyways, otherwise the hypervisor could attack the guest by immediately attempting to run the deferred vCPU. At that point, a guest could simply use an existing mechanism to put the target vCPU into a holding pattern.

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3505

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+		kick = false;
+		target_svm->snp_vmsa_update_on_init = true;
+		fallthrough;
+	case SVM_VMGEXIT_AP_CREATE:
+		target_svm->snp_vmsa_gpa = svm->vmcb->control.exit_info_2;

The incoming GPA needs to be checked for validity, at least as much possible. E.g. the PAGE_ALIGNED() check should be done here and be morphed to a synchronous error for the guest, not a silent "oops, didn't run your vCPU".

Quoted 47 lines
arch/x86/kvm/svm/sev.c +25 -0
+		break;
+	case SVM_VMGEXIT_AP_DESTROY:
+		break;
+	default:
+		vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+			    request);
+		break;
+	}
+
+out:
+	mutex_unlock(&target_svm->snp_vmsa_mutex);
+
+	if (kick) {
+		kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
+		kvm_vcpu_kick(target_vcpu);
+	}
+}
+
 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
@@ -3523,6 +3649,11 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		ret = 1;
 		break;
 	}
+	case SVM_VMGEXIT_AP_CREATION:
+		sev_snp_ap_creation(svm);
+
+		ret = 1;
+		break;
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
@@ -3597,6 +3728,8 @@ void sev_es_create_vcpu(struct vcpu_svm *svm)
 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
 					    GHCB_VERSION_MIN,
 					    sev_enc_bit));
+
+	mutex_init(&svm->snp_vmsa_mutex);
 }
 
 void sev_es_prepare_guest_switch(struct vcpu_svm *svm, unsigned int cpu)
arch/x86/kvm/svm/svm.c +0 -0
index 74bc635c9608..078a569c85a8 100644

arch/x86/kvm/svm/svm.c static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 1307

Quoted 5 lines
arch/x86/kvm/svm/svm.c +1 -1
@@ -1304,7 +1304,10 @@ static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	svm->spec_ctrl = 0;
 	svm->virt_spec_ctrl = 0;
 
-	if (!init_event) {
+	if (init_event && svm->snp_vmsa_update_on_init) {

This can race with sev_snp_ap_creation() since the new snp_vmsa_mutex isn't held. There needs to be smp_rmb() and smp_wmb() barriers to ensure correct ordering between snp_vmsa_update_on_init and consuming the new VMSA gpa. And of course sev_snp_ap_creation() needs to have correct ordering, e.g. as is this code can see snp_vmsa_update_on_init=true before the new snp_vmsa_gpa is set.

Quoted 6 lines
arch/x86/kvm/svm/svm.c +3 -0
+		svm->snp_vmsa_update_on_init = false;
+		sev_snp_update_protected_guest_state(vcpu);
+	} else {
 		vcpu->arch.apic_base = APIC_DEFAULT_PHYS_BASE |
 				       MSR_IA32_APICBASE_ENABLE;
 		if (kvm_vcpu_is_reset_bsp(vcpu))
maintainer
#174 lore raw

Re: [PATCH Part2 RFC v4 40/40] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 10 lines · Sean Christopherson
Quoted 4 lines · Brijesh Singh

From: Tom Lendacky <[email protected]>

Add support for the SEV-SNP AP Creation NAE event. This allows SEV-SNP guests to create and start APs on their own.

The changelog really needs to clarify that this doesn't allow the guest to create arbitrary vCPUs. The GHCB uses CREATE/DESTROY terminology, but this patch and its comments/documentation should very clearly call out that KVM's implementation is more along the line of vCPU online/offline.

Will update.

Quoted 135 lines

It should also be noted that KVM still onlines APs by default. That also raises the question of whether or not KVM should support creating an offlined vCPU. E.g. several of the use cases I'm aware of want to do something along the lines of creating a VM with the max number of theoretical vCPUs, but in most instances only run a handful of vCPUs. That's a fair amount of potential memory savings if the max theoretical number of vCPUs is high.

Quoted 127 lines

A new event, KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, is created and used so as to avoid updating the VMSA pointer while the vCPU is running.

For CREATE
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID. The GPA is saved in the svm struct of the target vCPU, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to the vCPU and then the vCPU is kicked.

For CREATE_ON_INIT:
The guest supplies the GPA of the VMSA to be used for the vCPU with the specified APIC ID the next time an INIT is performed. The GPA is saved in the svm struct of the target vCPU.

For DESTROY:
The guest indicates it wishes to stop the vCPU. The GPA is cleared from the svm struct, the KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event is added to vCPU and then the vCPU is kicked.

The KVM_REQ_UPDATE_PROTECTED_GUEST_STATE event handler will be invoked as a result of the event or as a result of an INIT. The handler sets the vCPU to the KVM_MP_STATE_UNINITIALIZED state, so that any errors will leave the vCPU as not runnable. Any previous VMSA pages that were installed as part of an SEV-SNP AP Creation NAE event are un-pinned. If a new VMSA is to be installed, the VMSA guest page is pinned and set as the VMSA in the vCPU VMCB and the vCPU state is set to KVM_MP_STATE_RUNNABLE. If a new VMSA is not to be installed, the VMSA is cleared in the vCPU VMCB and the vCPU state is left as KVM_MP_STATE_UNINITIALIZED to prevent it from being run.

---
 arch/x86/include/asm/kvm_host.h |   3 +
 arch/x86/include/asm/svm.h      |   3 +
 arch/x86/kvm/svm/sev.c          | 133 ++++++++++++++++++++++++++++++++
 arch/x86/kvm/svm/svm.c          |   7 +-
 arch/x86/kvm/svm/svm.h          |  16 +++-
 arch/x86/kvm/x86.c              |  11 ++-
 6 files changed, 170 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm_host.h +3 -0
index 117e2e08d7ed..881e05b3f74e 100644
@@ -91,6 +91,7 @@
 #define KVM_REQ_MSR_FILTER_CHANGED	KVM_ARCH_REQ(29)
 #define KVM_REQ_UPDATE_CPU_DIRTY_LOGGING \
 	KVM_ARCH_REQ_FLAGS(30, KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
+#define KVM_REQ_UPDATE_PROTECTED_GUEST_STATE	KVM_ARCH_REQ(31)
 
 #define CR0_RESERVED_BITS                                               \
 	(~(unsigned long)(X86_CR0_PE | X86_CR0_MP | X86_CR0_EM | X86_CR0_TS \
@@ -1402,6 +1403,8 @@ struct kvm_x86_ops {
 
 	int (*handle_rmp_page_fault)(struct kvm_vcpu *vcpu, gpa_t gpa, kvm_pfn_t pfn,
 			int level, u64 error_code);
+
+	void (*update_protected_guest_state)(struct kvm_vcpu *vcpu);
 };
 
 struct kvm_x86_nested_ops {
arch/x86/include/asm/svm.h +3 -0
index 5e72faa00cf2..6634a952563e 100644
@@ -220,6 +220,9 @@ struct __attribute__ ((__packed__)) vmcb_control_area {
 #define SVM_SEV_FEATURES_DEBUG_SWAP		BIT(5)
 #define SVM_SEV_FEATURES_PREVENT_HOST_IBS	BIT(6)
 #define SVM_SEV_FEATURES_BTB_ISOLATION		BIT(7)
+#define SVM_SEV_FEATURES_INT_INJ_MODES			\
+	(SVM_SEV_FEATURES_RESTRICTED_INJECTION |	\
+	 SVM_SEV_FEATURES_ALTERNATE_INJECTION)
 
 struct vmcb_seg {
 	u16 selector;
arch/x86/kvm/svm/sev.c +21 -0
index d8ad6dd58c87..95f5d25b4f08 100644
@@ -582,6 +582,7 @@ static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
 
 static int sev_es_sync_vmsa(struct vcpu_svm *svm)
 {
+	struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
 	struct sev_es_save_area *save = svm->vmsa;
 
 	/* Check some debug related fields before encrypting the VMSA */
@@ -625,6 +626,12 @@ static int sev_es_sync_vmsa(struct vcpu_svm *svm)
 	if (sev_snp_guest(svm->vcpu.kvm))
 		save->sev_features |= SVM_SEV_FEATURES_SNP_ACTIVE;
 
+	/*
+	 * Save the VMSA synced SEV features. For now, they are the same for
+	 * all vCPUs, so just save each time.
+	 */
+	sev->sev_features = save->sev_features;
+
 	return 0;
 }
 
@@ -2682,6 +2689,10 @@ static int sev_es_validate_vmgexit(struct vcpu_svm *svm)
 		if (!ghcb_sw_scratch_is_valid(ghcb))
 			goto vmgexit_err;
 		break;
+	case SVM_VMGEXIT_AP_CREATION:
+		if (!ghcb_rax_is_valid(ghcb))
+			goto vmgexit_err;
+		break;
 	case SVM_VMGEXIT_NMI_COMPLETE:
 	case SVM_VMGEXIT_AP_HLT_LOOP:
 	case SVM_VMGEXIT_AP_JUMP_TABLE:
@@ -3395,6 +3406,121 @@ static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm)
 	return ret;
 }
 
+void sev_snp_update_protected_guest_state(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_svm *svm = to_svm(vcpu);
+	kvm_pfn_t pfn;
+
+	mutex_lock(&svm->snp_vmsa_mutex);
+
+	vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
+
+	/* Clear use of the VMSA in the sev_es_init_vmcb() path */
Quoted 8 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3422

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+	svm->vmsa_pa = 0;
+
+	/* Clear use of the VMSA from the VMCB */
+	svm->vmcb->control.vmsa_pa = 0;

PA=0 is not an invalid address. I don't care what value the GHCB uses for "invalid GPA", KVM should always use INVALID_PAGE to track an invalid physical address.

Right, I'll switch everything over to INVALID_PAGE, which will also cause an error on VMRUN, so that is good.

Quoted 10 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3426

Quoted 4 lines
arch/x86/kvm/svm/sev.c +3 -0
+	/* Un-pin previous VMSA */
+	if (svm->snp_vmsa_pfn) {
+		kvm_release_pfn_dirty(svm->snp_vmsa_pfn);

Oof, I was wondering why KVM tracks three versions of VMSA. Actually, I'm still wondering why there are three versions. Aren't snp_vmsa_pfn and vmsa_pa tracking the same thing? Ah, finally figured it out. vmsa_pa points at svm->vmsa by default. Blech.

Quoted 7 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3430

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+		svm->snp_vmsa_pfn = 0;
+	}
+
+	if (svm->snp_vmsa_gpa) {

This is bogus, GPA=0 is perfectly valid. As above, use INVALID_PAGE. A comment explaining that the vCPU is offline when VMSA is invalid would also be helpful.

Will do.

Quoted 6 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3432

Quoted 3 lines
arch/x86/kvm/svm/sev.c +2 -0
+		/* Validate that the GPA is page aligned */
+		if (!PAGE_ALIGNED(svm->snp_vmsa_gpa))

This needs to be moved to the VMGEXIT, and it should use page_address_valid() so that KVM also checks for a legal GPA.

Will do.

Quoted 7 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3436

Quoted 5 lines
arch/x86/kvm/svm/sev.c +4 -0
+			goto e_unlock;
+
+		/*
+		 * The VMSA is referenced by thy hypervisor physical address,

s/thy/the, although converting to archaic English could be hilarious...

Heh, I'll fix that.

Quoted 9 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3441

Quoted 6 lines
arch/x86/kvm/svm/sev.c +5 -0
+		 * so retrieve the PFN and pin it.
+		 */
+		pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(svm->snp_vmsa_gpa));
+		if (is_error_pfn(pfn))
+			goto e_unlock;

Silently ignoring the guest request is bad behavior, at worst KVM should exit to userspace with an emulation error.

You'll end up with a VMRUN failure, which is likely to be the same result. But I can look at what it would take to exit up to userspace before that.

Quoted 13 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3451

Quoted 11 lines
arch/x86/kvm/svm/sev.c +10 -0
+
+		svm->snp_vmsa_pfn = pfn;
+
+		/* Use the new VMSA in the sev_es_init_vmcb() path */
+		svm->vmsa_pa = pfn_to_hpa(pfn);
+		svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
+
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	} else {
+		vcpu->arch.pv.pv_unhalted = false;

Shouldn't the RUNNABLE path also clear pv_unhalted?

If anything it should set it, since it will be "unhalted" now. But, I looked through the code to try and understand if there was a need to set it and didn't really see any reason. It is only ever set (at least directly) in one place and is cleared everywhere else. It was odd to me.

Quoted 6 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3451

Quoted 2 lines
arch/x86/kvm/svm/sev.c +1 -0
+		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;

What happens if userspace calls kvm_arch_vcpu_ioctl_set_mpstate, or even worse the guest sends INIT-SIPI? Unless I'm mistaken, either case will cause KVM to run the vCPU with vmcb->control.vmsa_pa==0.

Using the INVALID_PAGE value now (and even when it was 0), you'll get a VMRUN failure.

The AP CREATE_ON_INIT is meant to be used with INIT-SIPI, so if the guest hasn't done the right thing, then it will fail on VMRUN.

Quoted 3 lines

My initial reaction is that the "offline" case needs a new mp_state, or maybe just use KVM_MP_STATE_STOPPED.

I'll look at KVM_MP_STATE_STOPPED. Qemu doesn't reference that state at all in the i386 support, though, which is why I went with UNINITIALIZED.

Quoted 19 lines
Quoted 19 lines
arch/x86/kvm/svm/sev.c +18 -0
+	}
+
+e_unlock:
+	mutex_unlock(&svm->snp_vmsa_mutex);
+}
+
+static void sev_snp_ap_creation(struct vcpu_svm *svm)
+{
+	struct kvm_sev_info *sev = &to_kvm_svm(svm->vcpu.kvm)->sev_info;
+	struct kvm_vcpu *vcpu = &svm->vcpu;
+	struct kvm_vcpu *target_vcpu;
+	struct vcpu_svm *target_svm;
+	unsigned int request;
+	unsigned int apic_id;
+	bool kick;
+
+	request = lower_32_bits(svm->vmcb->control.exit_info_1);
+	apic_id = upper_32_bits(svm->vmcb->control.exit_info_1);
Quoted 8 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3475

Quoted 5 lines
arch/x86/kvm/svm/sev.c +5 -0
+
+	/* Validate the APIC ID */
+	target_vcpu = kvm_get_vcpu_by_id(vcpu->kvm, apic_id);
+	if (!target_vcpu)
+		return;

KVM should not silently ignore bad requests, this needs to return an error to the guest.

This can be made to return an int and then follow standard VMGEXIT processing.

Which reminds me to get a GHCB discussion going on returning some other form of error besides exceptions.

Quoted 9 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3479

Quoted 5 lines
arch/x86/kvm/svm/sev.c +4 -0
+
+	target_svm = to_svm(target_vcpu);
+
+	kick = true;

This is wrong, e.g. KVM will kick the target vCPU even if the request fails. I suspect the correct behavior would be to:

Quoted 4 lines

1. do all sanity checks
2. take the necessary lock(s)
3. modify target vCPU state
4. kick target vCPU unless request==SVM_VMGEXIT_AP_CREATE_ON_INIT

I'm not sure... the guest is really trying to do an INIT-SIPI type of action and if they don't do something correctly, we don't want to leave the AP running in its previous state, hence the kick, so that it will end up falling back to UNINITIALIZED state.

Quoted 6 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3481

Quoted 2 lines
arch/x86/kvm/svm/sev.c +1 -0
+	mutex_lock(&target_svm->snp_vmsa_mutex);

This seems like it's missing a big pile of sanity checks. E.g. KVM should reject SVM_VMGEXIT_AP_CREATE if the target vCPU is already "created", including the case where it was "created_on_init" but hasn't yet received INIT-SIPI.

Why? If the guest wants to call it multiple times I guess I don't see a reason that it would need to call DESTROY first and then CREATE. I don't know why a guest would want to do that, but I don't think we should prevent it.

Quoted 16 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3492

Quoted 12 lines
arch/x86/kvm/svm/sev.c +11 -0
+
+	target_svm->snp_vmsa_gpa = 0;
+	target_svm->snp_vmsa_update_on_init = false;
+
+	/* Interrupt injection mode shouldn't change for AP creation */
+	if (request < SVM_VMGEXIT_AP_DESTROY) {
+		u64 sev_features;
+
+		sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+		sev_features ^= sev->sev_features;
+		if (sev_features & SVM_SEV_FEATURES_INT_INJ_MODES) {

Why is only INT_INJ_MODES checked? The new comment in sev_es_sync_vmsa() explicitly states that sev_features are the same for all vCPUs, but that's not enforced here. At a bare minimum I would expect this to sanity check SVM_SEV_FEATURES_SNP_ACTIVE.

That's because we can't really enforce it. The SEV_FEATURES value is part of the VMSA, of which the hypervisor has no insight into (its encrypted).

The interrupt injection mechanism was specifically requested as a sanity check type of thing during the GHCB review, and as there were no objections, it was added (see the end of section 4.1.9).

I can definitely add the check for the SNP_ACTIVE bit, but it isn't required.

Quoted 15 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3500

Quoted 9 lines
arch/x86/kvm/svm/sev.c +8 -0
+			vcpu_unimpl(vcpu, "vmgexit: invalid AP injection mode [%#lx] from guest\n",
+				    vcpu->arch.regs[VCPU_REGS_RAX]);
+			goto out;
+		}
+	}
+
+	switch (request) {
+	case SVM_VMGEXIT_AP_CREATE_ON_INIT:

Out of curiosity, what's the use case for this variant? I assume the guest has to preconfigure the VMSA and ensure the target vCPU's RIP points at something sane anyways, otherwise the hypervisor could attack the guest by immediately attempting to run the deferred vCPU. At that point, a guest could simply use an existing mechanism to put the target vCPU into a holding pattern.

It came up in early discussions and so was included in the initial draft of the GHCB SNP support. There wasn't any discussion about it nor any objections, so it stayed.

Quoted 10 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3505

Quoted 6 lines
arch/x86/kvm/svm/sev.c +5 -0
+		kick = false;
+		target_svm->snp_vmsa_update_on_init = true;
+		fallthrough;
+	case SVM_VMGEXIT_AP_CREATE:
+		target_svm->snp_vmsa_gpa = svm->vmcb->control.exit_info_2;

The incoming GPA needs to be checked for validity, at least as much possible. E.g. the PAGE_ALIGNED() check should be done here and be morphed to a synchronous error for the guest, not a silent "oops, didn't run your vCPU".

Will do.

Quoted 51 lines
Quoted 51 lines
arch/x86/kvm/svm/sev.c +25 -0
+		break;
+	case SVM_VMGEXIT_AP_DESTROY:
+		break;
+	default:
+		vcpu_unimpl(vcpu, "vmgexit: invalid AP creation request [%#x] from guest\n",
+			    request);
+		break;
+	}
+
+out:
+	mutex_unlock(&target_svm->snp_vmsa_mutex);
+
+	if (kick) {
+		kvm_make_request(KVM_REQ_UPDATE_PROTECTED_GUEST_STATE, target_vcpu);
+		kvm_vcpu_kick(target_vcpu);
+	}
+}
+
 int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 {
 	struct vcpu_svm *svm = to_svm(vcpu);
@@ -3523,6 +3649,11 @@ int sev_handle_vmgexit(struct kvm_vcpu *vcpu)
 		ret = 1;
 		break;
 	}
+	case SVM_VMGEXIT_AP_CREATION:
+		sev_snp_ap_creation(svm);
+
+		ret = 1;
+		break;
 	case SVM_VMGEXIT_UNSUPPORTED_EVENT:
 		vcpu_unimpl(vcpu,
 			    "vmgexit: unsupported event - exit_info_1=%#llx, exit_info_2=%#llx\n",
@@ -3597,6 +3728,8 @@ void sev_es_create_vcpu(struct vcpu_svm *svm)
 	set_ghcb_msr(svm, GHCB_MSR_SEV_INFO(GHCB_VERSION_MAX,
 					    GHCB_VERSION_MIN,
 					    sev_enc_bit));
+
+	mutex_init(&svm->snp_vmsa_mutex);
 }
 
 void sev_es_prepare_guest_switch(struct vcpu_svm *svm, unsigned int cpu)
arch/x86/kvm/svm/svm.c +0 -0
index 74bc635c9608..078a569c85a8 100644
@@ -1304,7 +1304,10 @@ static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
 	svm->spec_ctrl = 0;
 	svm->virt_spec_ctrl = 0;
 
Quoted 8 lines

arch/x86/kvm/svm/svm.c static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) · line 1307

Quoted 2 lines
arch/x86/kvm/svm/svm.c +1 -1
-	if (!init_event) {
+	if (init_event && svm->snp_vmsa_update_on_init) {

This can race with sev_snp_ap_creation() since the new snp_vmsa_mutex isn't held. There needs to be smp_rmb() and smp_wmb() barriers to ensure correct ordering between snp_vmsa_update_on_init and consuming the new VMSA gpa. And of course sev_snp_ap_creation() needs to have correct ordering, e.g. as is this code can see snp_vmsa_update_on_init=true before the new snp_vmsa_gpa is set.

I'll work on that.

Thanks,
Tom

Quoted 8 lines
Quoted 7 lines
arch/x86/kvm/svm/svm.c +3 -0
+		svm->snp_vmsa_update_on_init = false;
+		sev_snp_update_protected_guest_state(vcpu);
+	} else {
 		vcpu->arch.apic_base = APIC_DEFAULT_PHYS_BASE |
 				       MSR_IA32_APICBASE_ENABLE;
 		if (kvm_vcpu_is_reset_bsp(vcpu))
#175 lore raw

Re: [PATCH Part2 RFC v4 40/40] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 16 lines · Tom Lendacky
Quoted 14 lines · Sean Christopherson

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3451

Quoted 11 lines · Brijesh Singh

From: Tom Lendacky <[email protected]>

arch/x86/kvm/svm/sev.c +10 -0
+
+		svm->snp_vmsa_pfn = pfn;
+
+		/* Use the new VMSA in the sev_es_init_vmcb() path */
+		svm->vmsa_pa = pfn_to_hpa(pfn);
+		svm->vmcb->control.vmsa_pa = svm->vmsa_pa;
+
+		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	} else {
+		vcpu->arch.pv.pv_unhalted = false;

Shouldn't the RUNNABLE path also clear pv_unhalted?

Quoted 4 lines

If anything it should set it, since it will be "unhalted" now. But, I looked through the code to try and understand if there was a need to set it and didn't really see any reason. It is only ever set (at least directly) in one place and is cleared everywhere else. It was odd to me.

pv_unhalted is specifically used for a "magic" IPI (KVM hijacked a defunct IPI type) in the context of PV spinlocks. The idea is that a vCPU that's releasing a spinlock can kick the next vCPU in the queue, and KVM will directly yield to the vCPU being kicked so that the guest can efficiently make forward progress.

So it's not wrong to leave pv_unhalted as is, but it's odd to clear it in the DESTROY case but not CREATE_INIT case. It should be a moot point, as a sane implementation should make it impossible to get to CREATE with pv_unhalted=1.

Quoted 13 lines
Quoted 5 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+		vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;

What happens if userspace calls kvm_arch_vcpu_ioctl_set_mpstate, or even worse the guest sends INIT-SIPI? Unless I'm mistaken, either case will cause KVM to run the vCPU with vmcb->control.vmsa_pa==0.

Using the INVALID_PAGE value now (and even when it was 0), you'll get a VMRUN failure.

The AP CREATE_ON_INIT is meant to be used with INIT-SIPI, so if the guest hasn't done the right thing, then it will fail on VMRUN.

Quoted 1 line
Quoted 5 lines
Quoted 2 lines

My initial reaction is that the "offline" case needs a new mp_state, or maybe just use KVM_MP_STATE_STOPPED.

I'll look at KVM_MP_STATE_STOPPED. Qemu doesn't reference that state at all in the i386 support, though, which is why I went with UNINITIALIZED.

Ya, it'd effectively be a new feature. My concern with UNINITIALIZED is that it be impossible for KVM to differentiate between "never run" and "destroyed and may have an invalid VMSA" without looking at the VMSA.

Quoted 10 lines
Quoted 5 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3481

Quoted 1 line
arch/x86/kvm/svm/sev.c +1 -0
+	mutex_lock(&target_svm->snp_vmsa_mutex);

This seems like it's missing a big pile of sanity checks. E.g. KVM should reject SVM_VMGEXIT_AP_CREATE if the target vCPU is already "created", including the case where it was "created_on_init" but hasn't yet received INIT-SIPI.

Why? If the guest wants to call it multiple times I guess I don't see a reason that it would need to call DESTROY first and then CREATE. I don't know why a guest would want to do that, but I don't think we should prevent it.

Because "creating" a vCPU that already exists is non-sensical. Ditto for onlining a vCPU that is already onlined. E.g. from the guest's perspective, I would fully expect a SVM_VMGEXIT_AP_CREATE to fail, not effectively send the vCPU to an arbitrary state.

Any ambiguity as to the legality of CREATE/DESTROY absolutely needs to be clarified in the GHCB.

Quoted 16 lines
Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/svm/sev.c +7 -0
+
+	target_svm->snp_vmsa_gpa = 0;
+	target_svm->snp_vmsa_update_on_init = false;
+
+	/* Interrupt injection mode shouldn't change for AP creation */
+	if (request < SVM_VMGEXIT_AP_DESTROY) {
+		u64 sev_features;
Quoted 8 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3492

Quoted 4 lines
arch/x86/kvm/svm/sev.c +4 -0
+
+		sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+		sev_features ^= sev->sev_features;
+		if (sev_features & SVM_SEV_FEATURES_INT_INJ_MODES) {

Why is only INT_INJ_MODES checked? The new comment in sev_es_sync_vmsa() explicitly states that sev_features are the same for all vCPUs, but that's not enforced here. At a bare minimum I would expect this to sanity check SVM_SEV_FEATURES_SNP_ACTIVE.

Quoted 8 lines

That's because we can't really enforce it. The SEV_FEATURES value is part of the VMSA, of which the hypervisor has no insight into (its encrypted).

The interrupt injection mechanism was specifically requested as a sanity check type of thing during the GHCB review, and as there were no objections, it was added (see the end of section 4.1.9).

I can definitely add the check for the SNP_ACTIVE bit, but it isn't required.

I'm confused. If we've no insight into what the guest is actually using, what's the point of the INT_INJ_MODES check?

maintainer
#176 lore raw

Re: [PATCH Part2 RFC v4 40/40] KVM: SVM: Support SEV-SNP AP Creation NAE event

Quoted 5 lines · Sean Christopherson
Quoted 4 lines · Tom Lendacky
Quoted 3 lines · Sean Christopherson
Quoted 1 line · Brijesh Singh

From: Tom Lendacky <[email protected]>

...

Quoted 10 lines
Quoted 8 lines
Quoted 3 lines

This seems like it's missing a big pile of sanity checks. E.g. KVM should reject SVM_VMGEXIT_AP_CREATE if the target vCPU is already "created", including the case where it was "created_on_init" but hasn't yet received INIT-SIPI.

Why? If the guest wants to call it multiple times I guess I don't see a reason that it would need to call DESTROY first and then CREATE. I don't know why a guest would want to do that, but I don't think we should prevent it.

Because "creating" a vCPU that already exists is non-sensical. Ditto for

Maybe the names of CREATE and DESTROY weren't the best choice. The intent is to replace INIT-SIPI.

Quoted 3 lines

onlining a vCPU that is already onlined. E.g. from the guest's perspective, I would fully expect a SVM_VMGEXIT_AP_CREATE to fail, not effectively send the vCPU to an arbitrary state.

The GHCB document does not require thos. To accomplish the same thing that a CREATE does today, the guest does DESTROY followed by CREATE. What's the difference, the DESTROY will kick the vCPU out and make it non-runnable and the guest will immediately follow that with a CREATE and set the new state. All of which can be accomplished by just calling CREATE to begin with - the net is the same, the vCPU gets taken from one state to a new state.

Quoted 3 lines

Any ambiguity as to the legality of CREATE/DESTROY absolutely needs to be clarified in the GHCB.

I don't see any ambiguity. The document states when the VMSA becomes effective and there's no requirement/need to issue a DESTROY before another CREATE.

Quoted 20 lines
Quoted 20 lines
Quoted 16 lines

arch/x86/kvm/svm/sev.c static int sev_handle_vmgexit_msr_protocol(struct vcpu_svm *svm) · line 3492

Quoted 12 lines
arch/x86/kvm/svm/sev.c +11 -0
+
+	target_svm->snp_vmsa_gpa = 0;
+	target_svm->snp_vmsa_update_on_init = false;
+
+	/* Interrupt injection mode shouldn't change for AP creation */
+	if (request < SVM_VMGEXIT_AP_DESTROY) {
+		u64 sev_features;
+
+		sev_features = vcpu->arch.regs[VCPU_REGS_RAX];
+		sev_features ^= sev->sev_features;
+		if (sev_features & SVM_SEV_FEATURES_INT_INJ_MODES) {

Why is only INT_INJ_MODES checked? The new comment in sev_es_sync_vmsa() explicitly states that sev_features are the same for all vCPUs, but that's not enforced here. At a bare minimum I would expect this to sanity check SVM_SEV_FEATURES_SNP_ACTIVE.

That's because we can't really enforce it. The SEV_FEATURES value is part of the VMSA, of which the hypervisor has no insight into (its encrypted).

Quoted 8 lines
Quoted 5 lines

The interrupt injection mechanism was specifically requested as a sanity check type of thing during the GHCB review, and as there were no objections, it was added (see the end of section 4.1.9).

I can definitely add the check for the SNP_ACTIVE bit, but it isn't required.

I'm confused. If we've no insight into what the guest is actually using, what's the point of the INT_INJ_MODES check?

As I said, it was requested and there were no objections, all with the knowledge that the guest could "lie" about it. Maybe it is just to ensure the proper behavior of an "honest" guest? It makes for a small bit of extra work, but, yes, isn't very useful from a KVM perspective.

Thanks,
Tom

Quoted 1 line
#177 lore raw
In reply to Brijesh Singh
Quoted 8 lines · Brijesh Singh

Changes since v3:
* Add support for extended guest message request.
* Add ioctl to query the SNP Platform status.
* Add ioctl to get and set the SNP config.
* Add check to verify that memory reserved for the RMP covers the full system RAM.
* Start the SNP specific commands from 256 instead of 255.
* Multiple cleanup and fixes based on the review feedback.

Quoted 9 lines

Changes since v2:
* Add AP creation support.
* Drop the patch to handle the RMP fault for the kernel address.
* Add functions to track the write access from the hypervisor.
* Do not enable the SNP feature when IOMMU is disabled or is in passthrough mode.
* Dump the RMP entry on RMP violation for the debug.
* Shorten the GHCB macro names.
* Start the SNP_INIT command id from 255 to give some gap for the legacy SEV.
* Sync the header with the latest 0.9 SNP spec.

What happened to the THP splitting on RMP violations?