Skip to contentSkip to conversation

KVM TDX basic feature support

PATCH Superseded [email protected] 10 participants 219 messages Jun 27, 2022 – Aug 11, 2022 Page 3 of 3

Subsystems (17)
Documentation x86 KVM PowerPC +13 more subsystems

v7 of 19 Superseded Latest is v19 →

lore
Share & tools
lore
#213 lore raw
In reply to Sean Christopherson
Quoted 21 lines · Sean Christopherson
Quoted 12 lines · On Mon, Jun 27, 2022, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

KVM TDX basic feature support

Hello. This is v7 the patch series vof KVM TDX support.
This is based on v5.19-rc1 + kvm/queue branch + TDX HOST patch series. The tree can be found at https://github.com/intel/tdx/tree/kvm-upstream
How to run/test: It's describe at https://github.com/intel/tdx/wiki/TDX-KVM

Major changes from v6:
- rebased to v5.19 base

Quoted 7 lines

TODO:
- integrate fd-based guest memory. As the discussion is still on-going, I intentionally dropped fd-based guest memory support yet. The integration can be found at https://github.com/intel/tdx/tree/kvm-upstream-workaround.
- 2M large page support. It's work-in-progress.
For large page support, there are several design choices. Here is the design options. Any thoughts/feedback?

Quoted 33 lines

Apologies, I didn't read beyond the intro paragraph. In case something like this comes up again, it's probably best to send a standalone email tagged RFC, I doubt I'm the only one that missed this embedded RFC.

Quoted 1 line

KVM MMU Large page support for TDX

...

Quoted 25 lines

* options to track private or shared
At each page size (4KB, 2MB, and 1GB), track private, shared, or mixed (2MB and 1GB case). For 4KB each page, 1 bit per page is needed. private or shared. For large pages (2MB and 1GB), 2 bits per large page is needed. (private, shared, or mixed). When resolving KVM page fault, we don't want to check the lower-size pages to check if the given GPA can be a large for performance. On MapGPA check it instead.

Option A). enhance kvm_arch_memory_slot
enum kvm_page_type {
KVM_PAGE_TYPE_INVALID,
KVM_PAGE_TYPE_SHARED,
KVM_PAGE_TYPE_PRIVATE,
KVM_PAGE_TYPE_MIXED,
};

   struct kvm_page_attr {
        enum kvm_page_type type;
   };

struct kvm_arch_memory_slot {
+ struct kvm_page_attr *page_attr[KVM_NR_PAGE_SIZES];

Option B). steal one more bit SPTE_MIXED_MASK in addition to SPTE_SHARED_MASK If !SPTE_MIXED_MASK, it can be large page.

I don't think this is a good option, since it requires all the mappings exist all the time both in shared spte tree and private spte tree.

Quoted 17 lines
Quoted 17 lines

Option C). use SPTE_SHARED_MASK and kvm_mmu_page::mixed bitmap kvm_mmu_page::mixed bitmap of 1GB, root indicates mixed for 2MB, 1GB.

* comparison
A).
+ straightforward to implement
+ SPTE_SHARED_MASK isn't needed
- memory overhead compared to B). or C).
- more memory reference on KVM page fault

B).
+ simpler than C) (complex than A)?)
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- Waste precious SPTE bits.

Quoted 8 lines
Quoted 5 lines

C).
+ efficient on KVM page fault. (only SPTE reference)
+ low memory overhead
- complicates MapGPA
- scattered data structure

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

UPM v7[1] introduces "struct xarray mem_attr_array" to track the shared/private attr of a range.

So in kvm_vm_ioctl_set_encrypted_region() it needs to

- increase the lpage_info counter when a 2m/1g range changed from identical to mixed, and

- decrease the counter when mixed -> identical

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

Quoted 9 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

#88 lore raw

Re: [PATCH v7 036/102] KVM: x86/mmu: Allow non-zero value for non-present SPTE

In reply to Kai Huang
Quoted 22 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX introduced a new ETP, Secure-EPT, in addition to the existing EPT. Secure-EPT maps protected guest memory, which is called private. Since Secure-EPT page tables is also protected, those page tables is also called private. The existing EPT is often called shared EPT to distinguish from Secure-EPT. And also page tables for share EPT is also called shared.

Does this patch has anything to do with secure-EPT?

Quoted 2 lines

Virtualization Exception, #VE, is a new processor exception in VMX non-root

#VE isn't new. It's already in pre-TDX public spec AFAICT.

Quoted 5 lines

operation. In certain virtualizatoin-related conditions, #VE is injected into guest instead of exiting from guest to VMM so that guest is given a chance to inspect it. One important one is EPT violation. When "ETP-violation #VE" VM-execution is set, "#VE suppress bit" in EPT entry is cleared, #VE is injected instead of EPT violation.

Quoted 3 lines

We already know such fact based on pre-TDX public spec. Instead of repeating it here, why not focusing on saying what's new in TDX, so your below paragraph of setting a non-zero value for non-present SPTE can be justified?

Ok, will drop those two paragraph above.

Quoted 42 lines
Quoted 10 lines

Because guest memory is protected with TDX, VMM can't parse instructions in the guest memory. Instead, MMIO hypercall is used for guest to pass necessary information to VMM.

To make unmodified device driver work, guest TD expects #VE on accessing shared GPA. The #VE handler converts MMIO access into MMIO hypercall with the EPT entry of enabled "#VE" by clearing "suppress #VE" bit. Before VMM enabling #VE, it needs to figure out the given GPA is for MMIO by EPT violation.

As I said above, before here, you need to explain in TDX VMCS is controlled by the TDX module and it always sets the "EPT-violation #VE" in execution control bit.

Quoted 13 lines

So the execution flow looks like

- Allocate unused shared EPT entry with suppress #VE bit set.
- EPT violation on that GPA.
- VMM figures out the faulted GPA is for MMIO.
- VMM clears the suppress #VE bit.
- Guest TD gets #VE, and converts MMIO access into MMIO hypercall.
- If the GPA maps guest memory, VMM resolves it with guest pages.

For both cases, SPTE needs suppress #VE" bit set initially when it is allocated or zapped, therefore non-zero non-present value for SPTE needs to be allowed.

Quoted 5 lines

This change requires to update FNAME(sync_page) for shadow EPT. "if(!sp->spte[i])" in FNAME(sync_page) means that the spte entry is the initial value. With the introduction of shadow_nonpresent_value which can be non-zero, it doesn't hold any more. Replace zero check with "!is_shadow_present_pte() && !is_mmio_spte()".

I don't think you need to mention above paragraph. It's absolutely unclear how is_mmio_spte() will be impacted by this patch by reading above paragraphs.

From the "execution flow" you mentioned above, you will change MMIO fault from EPT misconfiguration to EPT violation (in order to get #VE), so theoretically you may effectively disable MMIO caching, in which case, if I understand correctly, is_mmio_spte() always returns false.

Quoted 8 lines

I guess you can just change to check:

	if (sp->spte[i] != shadow_nonpresent_value)

Anyway, IMO you can just comment in the code.

After all, what is shadow_nonpresent_value, given you haven't explained what it is?

I'll drop the paragraph and add a comment on the code.

Quoted 82 lines
Quoted 4 lines

TDP MMU uses REMOVED_SPTE = 0x5a0ULL as special constant to indicate the intermediate value to indicate one thread is operating on it and the value should be semi-arbitrary value. For TDX (more correctly to use #VE), the value should include suppress #VE value which is SHADOW_NONPRESENT_VALUE.

What is SHADOW_NONPRESENT_VALUE?

Quoted 2 lines

Rename REMOVED_SPTE to __REMOVED_SPTE and define REMOVED_SPTE as SHADOW_NONPRESENT_VALUE | REMOVED_SPTE to set suppress #VE bit.

Ditto. IMHO you don't even need to mention REMOVED_SPTE in changelog.

Quoted 43 lines
---
 arch/x86/kvm/mmu/mmu.c         | 55 ++++++++++++++++++++++++++++++----
 arch/x86/kvm/mmu/paging_tmpl.h |  3 +-
 arch/x86/kvm/mmu/spte.c        |  5 +++-
 arch/x86/kvm/mmu/spte.h        | 37 ++++++++++++++++++++---
 arch/x86/kvm/mmu/tdp_mmu.c     | 23 +++++++++-----
 5 files changed, 105 insertions(+), 18 deletions(-)
arch/x86/kvm/mmu/mmu.c +25 -0
index 51306b80f47c..f239b6cb5d53 100644
@@ -668,6 +668,44 @@ static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
 	}
 }
 
+static inline void kvm_init_shadow_page(void *page)
+{
+#ifdef CONFIG_X86_64
+	int ign;
+
+	WARN_ON_ONCE(shadow_nonpresent_value != SHADOW_NONPRESENT_VALUE);
+	asm volatile (
+		"rep stosq\n\t"
+		: "=c"(ign), "=D"(page)
+		: "a"(SHADOW_NONPRESENT_VALUE), "c"(4096/8), "D"(page)
+		: "memory"
+	);
+#else
+	BUG();
+#endif
+}
+
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
+	int start, end, i, r;
+	bool is_tdp_mmu = is_tdp_mmu_enabled(vcpu->kvm);
+
+	if (is_tdp_mmu && shadow_nonpresent_value)
+		start = kvm_mmu_memory_cache_nr_free_objects(mc);

arch/x86/kvm/mmu/mmu.c static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu) · line 705

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+
+	r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+	if (r)
+		return r;
+
+	if (is_tdp_mmu && shadow_nonpresent_value) {
+		end = kvm_mmu_memory_cache_nr_free_objects(mc);
+		for (i = start; i < end; i++)
+			kvm_init_shadow_page(mc->objects[i]);
+	}

I think you can just extend this to legacy MMU too, but not only TDP MMU.

After all, before this patch, where have you declared that TDX only supports TDP MMU? This is only enforced in:

[PATCH v7 043/102] KVM: x86/mmu: Focibly use TDP MMU for TDX

Which is 7 patches later.

Also, shadow_nonpresent_value is only used in couple of places, while SHADOW_NONPRESENT_VALUE is used directly in more places. Does it make more sense to always use shadow_nonpresent_value, instead of using SHADOW_NONPRESENT_VALUE?

Quoted 7 lines

Similar to other shadow values, we can provide a function to let caller (VMX/SVM) to decide whether it wants to use non-zero for non-present SPTE.

	void kvm_mmu_set_non_present_value(u64 value)
	{
		shadow_nonpresent_value = value;
	}

As you pointed out, those logic is independent of TDP MMU or legacy MMU. So I'll remove is_tdp_mmu.I'll drop shadwo_nonpresent_value and use SHADWO_NONPRESENT_VALUE.

Signature · 1 line
Isaku Yamahata <[email protected]>
#93 lore raw

Re: [PATCH v7 036/102] KVM: x86/mmu: Allow non-zero value for non-present SPTE

In reply to [email protected]

Thanks for review. Now here is the updated version.

From f1ee540d62ba13511b2c7d3db7662e32bd263e48 Mon Sep 17 00:00:00 2001
Message-Id: <f1ee540d62ba13511b2c7d3db7662e32bd263e48.1657823906.git.isaku.yamahata@intel.com>
In-Reply-To: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1657823906.git.isaku.yamahata@intel.com>
References: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1657823906.git.isaku.yamahata@intel.com>
From: Sean Christopherson <[email protected]>
Date: Mon, 29 Jul 2019 19:23:46 -0700
Subject: [PATCH 036/304] KVM: x86/mmu: Allow non-zero value for non-present
SPTE

TDX introduced a new ETP, Secure-EPT, in addition to the existing EPT. Secure-EPT maps protected guest memory, which is called private. Since Secure-EPT page tables is also protected, those page tables is also called private. The existing EPT is often called shared EPT to distinguish from Secure-EPT. And also page tables for shared EPT is also called shared.

TDX module enables #VE injection by setting "EPT-violation #VE" in secondary processor-based VM-execution controls of TD VMCS. It also sets "suppress #VE" bit in Secure-EPT so that EPT violation on Secure-EPT causes exit to VMM.

Because guest memory is protected with TDX, VMM can't parse instructions in the guest memory. Instead, MMIO hypercall is used for guest TD to pass necessary information to VMM. To make unmodified device driver work, guest TD expects #VE on accessing shared GPA for MMIO. The #VE handler of guest TD converts MMIO access into MMIO hypercall. To trigger #VE in guest TD, VMM needs to clear "suppress #VE" bit in shared EPT entry that corresponds to MMIO address.

So the execution flow related for MMIO is as follows

- TDX module sets "EPT-violation #VE" in secondary processor-based VM-execution controls of TD VMCS.
- Allocate page for shared EPT PML4E page. Shared EPT entries are initialized with suppress #VE bit set. Update the EPTP pointer.
- TD accesses a GPA for MMIO to trigger EPT violation. It exits to VMM with EPT violation due to suppress #VE bit of EPT entries of PML4E page.
- VMM figures out the faulted GPA is for MMIO
- start shared EPT page table walk.
- Allocate non-leaf EPT pages for the shared EPT.
- Allocate leaf EPT page for the shared EPT and initialize EPT entries with suppress #VE bit set.
- VMM clears the suppress #VE bit for faulted GPA for MMIO. Please notice the leaf EPT page has 512 SPTE and other 511 SPTE entries need to keep "suppress #VE" bit set because GPAs for those SPTEs are not known to be MMIO. (It requires further lookups.)
If GPA is a guest page, link the guest page from the leaf SPTE entry.
- resume TD vcpu.
- Guest TD gets #VE, and converts MMIO access into MMIO hypercall.
- If the GPA maps guest memory, VMM resolves it with guest pages.

SPTEs for shared EPT need suppress #VE" bit set initially when it is allocated or zapped, therefore non-zero non-present value for SPTE needs to be allowed.

TDP MMU uses REMOVED_SPTE = 0x5a0ULL as special constant to indicate the intermediate value to indicate one thread is operating on it and the value should be semi-arbitrary value. For TDX (more exactly to use #VE), the value should include suppress #VE bit. Rename REMOVED_SPTE to __REMOVED_SPTE and define REMOVED_SPTE as (REMOVED_SPTE | "suppress #VE") bit.

For simplicity, "suppress #VE" bit is set unconditionally for X86_64 for non-present SPTE. Because "suppress #VE" bit (bit position of 63) for non-present SPTE is ignored for non-TD case (AMD CPUs or Intel VMX case with "EPT-violation #VE" cleared), the functionality shouldn't change.

---
 arch/x86/kvm/mmu/mmu.c         | 71 ++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/paging_tmpl.h |  3 +-
 arch/x86/kvm/mmu/spte.c        |  5 ++-
 arch/x86/kvm/mmu/spte.h        | 28 +++++++++++++-
 arch/x86/kvm/mmu/tdp_mmu.c     | 23 +++++++----
 5 files changed, 116 insertions(+), 14 deletions(-)
arch/x86/kvm/mmu/mmu.c +68 -3
index 51306b80f47c..992f31458f94 100644
@@ -668,6 +668,55 @@ static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
 	}
 }
 
+#ifdef CONFIG_X86_64
+static inline void kvm_init_shadow_page(void *page)
+{
+	int ign;
+
+	/*
+	 * AMD: "suppress #VE" bit is ignored
+	 * Intel non-TD(VMX): "suppress #VE" bit is ignored because
+	 *   EPT_VIOLATION_VE isn't set.
+	 * guest TD: TDX module sets EPT_VIOLATION_VE
+	 *   conventional SEPT: "suppress #VE" bit must be set to get EPT violation
+	 *   private SEPT: "suppress #VE" bit is ignored.  CPU doesn't walk it
+	 *
+	 * For simplicity, unconditionally initialize SPET to set "suppress #VE".
+	 */
+	asm volatile ("rep stosq\n\t"
+		      : "=c"(ign), "=D"(page)
+		      : "a"(SHADOW_NONPRESENT_VALUE), "c"(4096/8), "D"(page)
+		      : "memory"
+	);
+}
+
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
+	int start, end, i, r;
+
+	start = kvm_mmu_memory_cache_nr_free_objects(mc);
+	r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+
+	/*
+	 * Note, topup may have allocated objects even if it failed to allocate
+	 * the minimum number of objects required to make forward progress _at
+	 * this time_.  Initialize newly allocated objects even on failure, as
+	 * userspace can free memory and rerun the vCPU in response to -ENOMEM.
+	 */
+	end = kvm_mmu_memory_cache_nr_free_objects(mc);
+	for (i = start; i < end; i++)
+		kvm_init_shadow_page(mc->objects[i]);
+	return r;
+}
+#else
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	return kvm_mmu_topup_memory_cache(vcpu->arch.mmu_shadow_page_cache,
+					  PT64_ROOT_MAX_LEVEL);
+}
+#endif /* CONFIG_X86_64 */
+
 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 {
 	int r;
@@ -677,8 +726,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
 	if (r)
 		return r;
-	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
-				       PT64_ROOT_MAX_LEVEL);
+	r = mmu_topup_shadow_page_cache(vcpu);
 	if (r)
 		return r;
 	if (maybe_indirect) {
@@ -5654,7 +5702,24 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
-	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
+	/*
+	 * When X86_64, initial SEPT entries are initialized with
+	 * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+	 * mmu_topup_shadow_page_cache().
+	 *
+	 * Shared EPTEs need to be initialized with SUPPRESS_VE=1, otherwise
+	 * not-present EPT violations would be reflected into the guest by
+	 * hardware as #VE exceptions.  This is handled by initializing page
+	 * allocations via kvm_init_shadow_page() during cache topup.
+	 * In that case, telling the page allocation to zero-initialize the page
+	 * would be wasted effort.
+	 *
+	 * The initialization is harmless for S-EPT entries because KVM's copy
+	 * of the S-EPT isn't consumed by hardware, and because under the hood
+	 * S-EPT entries should never #VE.
+	 */
+	if (!IS_ENABLED(X86_64))
+		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
 
 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
arch/x86/kvm/mmu/paging_tmpl.h +2 -1
index fe35d8fd3276..964ec76579f0 100644
@@ -1031,7 +1031,8 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 		gpa_t pte_gpa;
 		gfn_t gfn;
 
-		if (!sp->spt[i])
+		/* spt[i] has initial value of shadow page table allocation */
+		if (sp->spt[i] != SHADOW_NONPRESENT_VALUE)
 			continue;
 
 		pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);
arch/x86/kvm/mmu/spte.c +4 -1
index cda1851ec155..bd441458153f 100644
@@ -36,6 +36,9 @@ u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_value;
 u64 __read_mostly shadow_me_mask;
 u64 __read_mostly shadow_acc_track_mask;
+#ifdef CONFIG_X86_64
+u64 __read_mostly shadow_nonpresent_value;
+#endif
 
 u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
 u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
@@ -360,7 +363,7 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	 * not set any RWX bits.
 	 */
 	if (WARN_ON((mmio_value & mmio_mask) != mmio_value) ||
-	    WARN_ON(mmio_value && (REMOVED_SPTE & mmio_mask) == mmio_value))
+	    WARN_ON(mmio_value && (__REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;
 
 	if (!mmio_value)
arch/x86/kvm/mmu/spte.h +26 -2
index 0127bb6e3c7d..f5fd22f6bf5f 100644
@@ -140,6 +140,19 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
 #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+/*
+ * non-present SPTE value for both VMX and SVM for TDP MMU.
+ * For SVM NPT, for non-present spte (bit 0 = 0), other bits are ignored.
+ * For VMX EPT, bit 63 is ignored if #VE is disabled.
+ *              bit 63 is #VE suppress if #VE is enabled.
+ */
+#ifdef CONFIG_X86_64
+#define SHADOW_NONPRESENT_VALUE	BIT_ULL(63)
+static_assert(!(SHADOW_NONPRESENT_VALUE & SPTE_MMU_PRESENT_MASK));
+#else
+#define SHADOW_NONPRESENT_VALUE	0ULL
+#endif
+
 extern u64 __read_mostly shadow_host_writable_mask;
 extern u64 __read_mostly shadow_mmu_writable_mask;
 extern u64 __read_mostly shadow_nx_mask;
@@ -178,16 +191,27 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  * non-present intermediate value. Other threads which encounter this value
  * should not modify the SPTE.
  *
+ * For X86_64 case, SHADOW_NONPRESENT_VALUE, "suppress #VE" bit, is set because
+ * "EPT violation #VE" in the secondary VM execution control may be enabled.
+ * Because TDX module sets "EPT violation #VE" for TD, "suppress #VE" bit for
+ * the conventional EPT needs to be set.
+ *
  * Use a semi-arbitrary value that doesn't set RWX bits, i.e. is not-present on
  * bot AMD and Intel CPUs, and doesn't set PFN bits, i.e. doesn't create a L1TF
  * vulnerability.  Use only low bits to avoid 64-bit immediates.
  *
  * Only used by the TDP MMU.
  */
-#define REMOVED_SPTE	0x5a0ULL
+#define __REMOVED_SPTE	0x5a0ULL
 
 /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
-static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
+static_assert(!(__REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
+
+/*
+ * See above comment around __REMOVED_SPTE.  REMOVED_SPTE is the actual
+ * intermediate value set to the removed SPET.  it sets the "suppress #VE" bit.
+ */
+#define REMOVED_SPTE	(SHADOW_NONPRESENT_VALUE | __REMOVED_SPTE)
 
 static inline bool is_removed_spte(u64 spte)
 {
arch/x86/kvm/mmu/tdp_mmu.c +16 -7
index 7b9265d67131..2ca03ec3bf52 100644
@@ -692,8 +692,16 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * overwrite the special removed SPTE value. No bookkeeping is needed
 	 * here since the SPTE is going from non-present to non-present.  Use
 	 * the raw write helper to avoid an unnecessary check on volatile bits.
+	 *
+	 * Set non-present value to SHADOW_NONPRESENT_VALUE, rather than 0.
+	 * It is because when TDX is enabled, TDX module always
+	 * enables "EPT-violation #VE", so KVM needs to set
+	 * "suppress #VE" bit in EPT table entries, in order to get
+	 * real EPT violation, rather than TDVMCALL.  KVM sets
+	 * SHADOW_NONPRESENT_VALUE (which sets "suppress #VE" bit) so it
+	 * can be set when EPT table entries are zapped.
 	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 
 	return 0;
 }
@@ -870,8 +878,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 
 		if (!shared)
-			tdp_mmu_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
 			goto retry;
 	}
 }
@@ -927,8 +935,9 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 	if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
 		return false;
 
-	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-			   sp->gfn, sp->role.level + 1, true, true);
+	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			   SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1,
+			   true, true);
 
 	return true;
 }
@@ -965,7 +974,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 		    !is_last_spte(iter.old_spte, iter.level))
 			continue;
 
-		tdp_mmu_set_spte(kvm, &iter, 0);
+		tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
 		flush = true;
 	}
 
@@ -1330,7 +1339,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
 	 * invariant that the PFN of a present * leaf SPTE can never change.
 	 * See __handle_changed_spte().
 	 */
-	tdp_mmu_set_spte(kvm, iter, 0);
+	tdp_mmu_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
 
 	if (!pte_write(range->pte)) {
 		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
Signature · 6 lines
2.25.1



-- 
Isaku Yamahata <[email protected]>
#157 lore raw

Re: [PATCH v7 056/102] KVM: x86/mmu: steal software usable git to record if GFN is for shared or not

In reply to [email protected]
Quoted 1 line · On Mon, Jun 27, 2022 at 02:53:48PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Subject: s/git/bit

Quoted 41 lines

With TDX, all GFNs are private at guest boot time. At run time guest TD can explicitly change it to shared from private or vice-versa by MapGPA hypercall. If it's specified, the given GFN can't be used as otherwise. That's is, if a guest tells KVM that the GFN is shared, it can't be used as private. or vice-versa.

Steal software usable bit, SPTE_SHARED_MASK, for it from MMIO counter to record it. Use the bit SPTE_SHARED_MASK in shared or private EPT to determine which mapping, shared or private, is allowed. If requested mapping isn't allowed, return RET_PF_RETRY to wait for other vcpu to change it. The bit is recorded in both shared and private shadow page to avoid traverse one more shadow page when resolving KVM page fault.

The bit needs to be kept over zapping the EPT entry. Currently the EPT entry is initialized SHADOW_NONPRESENT_VALUE unconditionally to clear SPTE_SHARED_MASK bit. To carry SPTE_SHARED_MASK bit, introduce a helper function to get initial value for zapped entry with SPTE_SHARED_MASK bit. Replace SHADOW_NONPRESENT_VALUE with it.

---
 arch/x86/kvm/mmu/spte.h    | 17 +++++++---
 arch/x86/kvm/mmu/tdp_mmu.c | 65 ++++++++++++++++++++++++++++++++------
 2 files changed, 68 insertions(+), 14 deletions(-)
arch/x86/kvm/mmu/spte.h +3 -0
index 96312ab4fffb..7c1aaf0e963e 100644
@@ -14,6 +14,9 @@
  */
 #define SPTE_MMU_PRESENT_MASK		BIT_ULL(11)
 
+/* Masks that used to track for shared GPA **/
+#define SPTE_SHARED_MASK		BIT_ULL(62)
+
 /*
  * TDP SPTES (more specifically, EPT SPTEs) may not have A/D bits, and may also
  * be restricted to using write-protection (for L2 when CPU dirty logging, i.e.

arch/x86/kvm/mmu/spte.h static_assert(!(EPT_SPTE_MMU_WRITABLE & SHADOW_ACC_TRACK_SAVED_MASK)); · line 110

Quoted 5 lines
arch/x86/kvm/mmu/spte.h +1 -1
@@ -104,7 +107,7 @@ static_assert(!(EPT_SPTE_MMU_WRITABLE & SHADOW_ACC_TRACK_SAVED_MASK));
  * the memslots generation and is derived as follows:
  *
  * Bits 0-7 of the MMIO generation are propagated to spte bits 3-10
- * Bits 8-18 of the MMIO generation are propagated to spte bits 52-62
+ * Bits 8-18 of the MMIO generation are propagated to spte bits 52-61

Should be 8-17.

Quoted 128 lines
arch/x86/kvm/mmu/spte.h +9 -3
  *
  * The KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS flag is intentionally not included in
  * the MMIO generation number, as doing so would require stealing a bit from
@@ -118,7 +121,7 @@ static_assert(!(EPT_SPTE_MMU_WRITABLE & SHADOW_ACC_TRACK_SAVED_MASK));
 #define MMIO_SPTE_GEN_LOW_END		10
 
 #define MMIO_SPTE_GEN_HIGH_START	52
-#define MMIO_SPTE_GEN_HIGH_END		62
+#define MMIO_SPTE_GEN_HIGH_END		61
 
 #define MMIO_SPTE_GEN_LOW_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_END, \
 						    MMIO_SPTE_GEN_LOW_START)
@@ -131,7 +134,7 @@ static_assert(!(SPTE_MMU_PRESENT_MASK &
 #define MMIO_SPTE_GEN_HIGH_BITS		(MMIO_SPTE_GEN_HIGH_END - MMIO_SPTE_GEN_HIGH_START + 1)
 
 /* remember to adjust the comment above as well if you change these */
-static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
+static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 10);
 
 #define MMIO_SPTE_GEN_LOW_SHIFT		(MMIO_SPTE_GEN_LOW_START - 0)
 #define MMIO_SPTE_GEN_HIGH_SHIFT	(MMIO_SPTE_GEN_HIGH_START - MMIO_SPTE_GEN_LOW_BITS)
@@ -208,6 +211,7 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
 /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
 static_assert(!(__REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
 static_assert(!(__REMOVED_SPTE & SHADOW_NONPRESENT_VALUE));
+static_assert(!(__REMOVED_SPTE & SPTE_SHARED_MASK));
 
 /*
  * See above comment around __REMOVED_SPTE.  REMOVED_SPTE is the actual
@@ -217,7 +221,12 @@ static_assert(!(__REMOVED_SPTE & SHADOW_NONPRESENT_VALUE));
 
 static inline bool is_removed_spte(u64 spte)
 {
-	return spte == REMOVED_SPTE;
+	return (spte & ~SPTE_SHARED_MASK) == REMOVED_SPTE;
+}
+
+static inline u64 spte_shared_mask(u64 spte)
+{
+	return spte & SPTE_SHARED_MASK;
 }
 
 /*
arch/x86/kvm/mmu/tdp_mmu.c +29 -8
index fef6246086a8..4f279700b3cc 100644
@@ -758,6 +758,11 @@ static inline int tdp_mmu_set_spte_atomic(struct kvm *kvm,
 	return 0;
 }
 
+static u64 shadow_nonpresent_spte(u64 old_spte)
+{
+	return SHADOW_NONPRESENT_VALUE | spte_shared_mask(old_spte);
+}
+
 static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 					  struct tdp_iter *iter)
 {
@@ -791,7 +796,8 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * SHADOW_NONPRESENT_VALUE (which sets "suppress #VE" bit) so it
 	 * can be set when EPT table entries are zapped.
 	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
+	__kvm_tdp_mmu_write_spte(iter->sptep,
+			       shadow_nonpresent_spte(iter->old_spte));
 
 	return 0;
 }
@@ -975,8 +981,11 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 
 		if (!shared)
-			tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
+			tdp_mmu_set_spte(kvm, &iter,
+					 shadow_nonpresent_spte(iter.old_spte));
+		else if (tdp_mmu_set_spte_atomic(
+				 kvm, &iter,
+				 shadow_nonpresent_spte(iter.old_spte)))
 			goto retry;
 	}
 }
@@ -1033,7 +1042,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 		return false;
 
 	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
-			   SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1,
+			   shadow_nonpresent_spte(old_spte),
+			   sp->gfn, sp->role.level + 1,
 			   true, true, is_private_sp(sp));
 
 	return true;
@@ -1075,11 +1085,20 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 		}
 
+		/*
+		 * SPTE_SHARED_MASK is stored as 4K granularity.  The
+		 * information is lost if we delete upper level SPTE page.
+		 * TODO: support large page.
+		 */
+		if (kvm_gfn_shared_mask(kvm) && iter.level > PG_LEVEL_4K)
+			continue;
+
 		if (!is_shadow_present_pte(iter.old_spte) ||
 		    !is_last_spte(iter.old_spte, iter.level))
 			continue;
 
-		tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		tdp_mmu_set_spte(kvm, &iter,
+				 shadow_nonpresent_spte(iter.old_spte));
 		flush = true;
 	}
 
@@ -1195,18 +1214,44 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	gfn_t gfn_unalias = iter->gfn & ~kvm_gfn_shared_mask(vcpu->kvm);
 
 	WARN_ON(sp->role.level != fault->goal_level);
+	WARN_ON(is_private_sptep(iter->sptep) != fault->is_private);
 
-	/* TDX shared GPAs are no executable, enforce this for the SDV. */
-	if (kvm_gfn_shared_mask(vcpu->kvm) && !fault->is_private)
-		pte_access &= ~ACC_EXEC_MASK;
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		if (fault->is_private) {
+			/*
+			 * SPTE allows only RWX mapping. PFN can't be mapped it

arch/x86/kvm/mmu/tdp_mmu.c static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu, · line 1232

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +10 -0
+			 * as READONLY in GPA.
+			 */
+			if (fault->slot && !fault->map_writable)
+				return RET_PF_RETRY;
+			/*
+			 * This GPA is not allowed to map as private.  Let
+			 * vcpu loop in page fault until other vcpu change it
+			 * by MapGPA hypercall.
+			 */
+			if (fault->slot &&

Please consider to merge this if into above "if (fault->slot) {}"

Quoted 13 lines
arch/x86/kvm/mmu/tdp_mmu.c +11 -0
+				spte_shared_mask(iter->old_spte))
+				return RET_PF_RETRY;
+		} else {
+			/* This GPA is not allowed to map as shared. */
+			if (fault->slot &&
+				!spte_shared_mask(iter->old_spte))
+				return RET_PF_RETRY;
+			/* TDX shared GPAs are no executable, enforce this. */
+			pte_access &= ~ACC_EXEC_MASK;
+		}
+	}
 
 	if (unlikely(!fault->slot))

arch/x86/kvm/mmu/tdp_mmu.c static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu, · line 1254

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +4 -1
 		new_spte = make_mmio_spte(vcpu, gfn_unalias, pte_access);
-	else
+	else {
 		wrprot = make_spte(vcpu, sp, fault->slot, pte_access,
 				   gfn_unalias, fault->pfn, iter->old_spte,
 				   fault->prefetch, true, fault->map_writable,
 				   &new_spte);
+		if (spte_shared_mask(iter->old_spte))
+			new_spte |= SPTE_SHARED_MASK;
+	}

The if can be eliminated:
new_spte |= spte_shared_mask(iter->old_spte);

Quoted 15 lines
arch/x86/kvm/mmu/tdp_mmu.c +1 -2
 	if (new_spte == iter->old_spte)
 		ret = RET_PF_SPURIOUS;
@@ -1509,7 +1554,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
 	 * invariant that the PFN of a present * leaf SPTE can never change.
 	 * See __handle_changed_spte().
 	 */
-	tdp_mmu_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
+	tdp_mmu_set_spte(kvm, iter, shadow_nonpresent_spte(iter->old_spte));
 
 	if (!pte_write(range->pte)) {
 		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
--

2.25.1

#99 lore raw

Re: [PATCH v7 037/102] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to [email protected]

Here is the updated one. The changes are
- removed hunks that should be a part of other patches.
- removed shadow_default_mmio_mask
- trimed down commit messages.

From ed6b4a076e515550878b069596cf156a1bc33514 Mon Sep 17 00:00:00 2001
Message-Id: <ed6b4a076e515550878b069596cf156a1bc33514.1658220363.git.isaku.yamahata@intel.com>
In-Reply-To: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658220363.git.isaku.yamahata@intel.com>
References: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658220363.git.isaku.yamahata@intel.com>
From: Sean Christopherson <[email protected]>
Date: Wed, 10 Jun 2020 15:46:38 -0700
Subject: [PATCH 036/306] KVM: x86/mmu: Track shadow MMIO value/mask on a
per-VM basis

TDX will use a different shadow PTE entry value for MMIO from VMX. Add members to kvm_arch and track value for MMIO per-VM instead of global variables. By using the per-VM EPT entry value for MMIO, the existing VMX logic is kept working. To untangle the logic to initialize shadow_mmio_access_mask, introduce a setter function.

---
 arch/x86/include/asm/kvm_host.h |  4 +++
 arch/x86/kvm/mmu.h              |  3 ++-
 arch/x86/kvm/mmu/mmu.c          |  8 +++---
 arch/x86/kvm/mmu/spte.c         | 45 +++++++++------------------------
 arch/x86/kvm/mmu/spte.h         | 10 +++-----
 arch/x86/kvm/mmu/tdp_mmu.c      |  6 ++---
 arch/x86/kvm/svm/svm.c          | 11 +++++---
 arch/x86/kvm/vmx/tdx.c          |  4 +++
 arch/x86/kvm/vmx/vmx.c          | 26 +++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h      |  1 +
 10 files changed, 66 insertions(+), 52 deletions(-)
arch/x86/include/asm/kvm_host.h +4 -0
index 2c47aab72a1b..39215daa8576 100644
@@ -1161,6 +1161,10 @@ struct kvm_arch {
 	 */
 	spinlock_t mmu_unsync_pages_lock;
 
+	bool enable_mmio_caching;
+	u64 shadow_mmio_value;
+	u64 shadow_mmio_mask;
+
 	struct list_head assigned_dev_head;
 	struct iommu_domain *iommu_domain;
 	bool iommu_noncoherent;
arch/x86/kvm/mmu.h +2 -1
index ccf0ba7a6387..cfa3e658162c 100644
@@ -108,7 +108,8 @@ static inline u8 kvm_get_shadow_phys_bits(void)
 	return boot_cpu_data.x86_phys_bits;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask);
+void kvm_mmu_set_mmio_access_mask(u64 mmio_access_mask);
 void kvm_mmu_set_me_spte_mask(u64 me_value, u64 me_mask);
 void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only);
 
arch/x86/kvm/mmu/mmu.c +4 -4
index 5bfccfa0f50e..34240fcc45de 100644
@@ -2298,7 +2298,7 @@ static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
 				return kvm_mmu_prepare_zap_page(kvm, child,
 								invalid_list);
 		}
-	} else if (is_mmio_spte(pte)) {
+	} else if (is_mmio_spte(kvm, pte)) {
 		mmu_spte_clear_no_track(spte);
 	}
 	return 0;
@@ -3079,7 +3079,7 @@ static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fau
 		 * and only if L1's MAXPHYADDR is inaccurate with respect to
 		 * the hardware's).
 		 */
-		if (unlikely(!enable_mmio_caching) ||
+		if (unlikely(!vcpu->kvm->arch.enable_mmio_caching) ||
 		    unlikely(fault->gfn > kvm_mmu_max_gfn()))
 			return RET_PF_EMULATE;
 	}
@@ -3918,7 +3918,7 @@ static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
 	if (WARN_ON(reserved))
 		return -EINVAL;
 
-	if (is_mmio_spte(spte)) {
+	if (is_mmio_spte(vcpu->kvm, spte)) {
 		gfn_t gfn = get_mmio_spte_gfn(spte);
 		unsigned int access = get_mmio_spte_access(spte);
 
@@ -4361,7 +4361,7 @@ static unsigned long get_cr3(struct kvm_vcpu *vcpu)
 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
 			   unsigned int access)
 {
-	if (unlikely(is_mmio_spte(*sptep))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
 		if (gfn != get_mmio_spte_gfn(*sptep)) {
 			mmu_spte_clear_no_track(sptep);
 			return true;
arch/x86/kvm/mmu/spte.c +12 -33

89 lines not on this page · raw message

arch/x86/kvm/mmu/spte.h +3 -7
index f5fd22f6bf5f..99bce92b596e 100644
@@ -5,8 +5,6 @@
 
 #include "mmu_internal.h"
 
-extern bool __read_mostly enable_mmio_caching;
-
 /*
  * A MMU present SPTE is backed by actual memory and may or may not be present
  * in hardware.  E.g. MMIO SPTEs are not considered present.  Use bit 11, as it
@@ -160,8 +158,6 @@ extern u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 extern u64 __read_mostly shadow_user_mask;
 extern u64 __read_mostly shadow_accessed_mask;
 extern u64 __read_mostly shadow_dirty_mask;
-extern u64 __read_mostly shadow_mmio_value;
-extern u64 __read_mostly shadow_mmio_mask;
 extern u64 __read_mostly shadow_mmio_access_mask;
 extern u64 __read_mostly shadow_present_mask;
 extern u64 __read_mostly shadow_me_value;
@@ -228,10 +224,10 @@ static inline bool is_removed_spte(u64 spte)
  */
 extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
 
-static inline bool is_mmio_spte(u64 spte)
+static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)
 {
-	return (spte & shadow_mmio_mask) == shadow_mmio_value &&
-	       likely(enable_mmio_caching);
+	return (spte & kvm->arch.shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
+		likely(kvm->arch.enable_mmio_caching);
 }
 
 static inline bool is_shadow_present_pte(u64 pte)
arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index 2ca03ec3bf52..82f1bfac7ee6 100644
@@ -569,8 +569,8 @@ static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
 		 * impact the guest since both the former and current SPTEs
 		 * are nonpresent.
 		 */
-		if (WARN_ON(!is_mmio_spte(old_spte) &&
-			    !is_mmio_spte(new_spte) &&
+		if (WARN_ON(!is_mmio_spte(kvm, old_spte) &&
+			    !is_mmio_spte(kvm, new_spte) &&
 			    !is_removed_spte(new_spte)))
 			pr_err("Unexpected SPTE change! Nonpresent SPTEs\n"
 			       "should not be replaced with another,\n"
@@ -1108,7 +1108,7 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	}
 
 	/* If a MMIO SPTE is installed, the MMIO will need to be emulated. */
-	if (unlikely(is_mmio_spte(new_spte))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, new_spte))) {
 		vcpu->stat.pf_mmio_spte_created++;
 		trace_mark_mmio_spte(rcu_dereference(iter->sptep), iter->gfn,
 				     new_spte);
arch/x86/kvm/svm/svm.c +7 -4
index f01821f48bfd..0f63257161a6 100644
@@ -198,6 +198,7 @@ module_param(dump_invalid_vmcb, bool, 0644);
 bool intercept_smi = true;
 module_param(intercept_smi, bool, 0444);
 
+static u64 __read_mostly svm_shadow_mmio_mask;
 
 static bool svm_gp_erratum_intercept = true;
 
@@ -4685,6 +4686,9 @@ static bool svm_is_vm_type_supported(unsigned long type)
 
 static int svm_vm_init(struct kvm *kvm)
 {
+	kvm_mmu_set_mmio_spte_mask(kvm, svm_shadow_mmio_mask,
+				   svm_shadow_mmio_mask);
+
 	if (!pause_filter_count || !pause_filter_thresh)
 		kvm->arch.pause_in_guest = true;
 
@@ -4834,7 +4838,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 static __init void svm_adjust_mmio_mask(void)
 {
 	unsigned int enc_bit, mask_bit;
-	u64 msr, mask;
+	u64 msr;
 
 	/* If there is no memory encryption support, use existing mask */
 	if (cpuid_eax(0x80000000) < 0x8000001f)
@@ -4861,9 +4865,8 @@ static __init void svm_adjust_mmio_mask(void)
 	 *
 	 * If the mask bit location is 52 (or above), then clear the mask.
 	 */
-	mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
-
-	kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
+	svm_shadow_mmio_mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
+	kvm_mmu_set_mmio_access_mask(PT_WRITABLE_MASK | PT_USER_MASK);
 }
 
 static __init void svm_set_cpu_caps(void)
arch/x86/kvm/vmx/tdx.c +4 -0
index 36d2127cb7b7..52fb54880f9b 100644
@@ -7,6 +7,7 @@
 #include "x86_ops.h"
 #include "tdx.h"
 #include "x86.h"
+#include "mmu.h"
 
 #undef pr_fmt
 #define pr_fmt(fmt) "tdx: " fmt
@@ -276,6 +277,9 @@ int tdx_vm_init(struct kvm *kvm)
 	int ret, i;
 	u64 err;
 
+	kvm_mmu_set_mmio_spte_mask(kvm, vmx_shadow_mmio_mask,
+				   vmx_shadow_mmio_mask);
+
 	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
 	kvm->max_vcpus = 0;
 
arch/x86/kvm/vmx/vmx.c +26 -0
index e129ee663498..88e893fdffe8 100644
@@ -141,6 +141,8 @@ module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
 extern bool __read_mostly allow_smaller_maxphyaddr;
 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
 
+u64 __ro_after_init vmx_shadow_mmio_mask;
+
 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
 #define KVM_VM_CR0_ALWAYS_ON				\
@@ -7359,6 +7361,17 @@ int vmx_vm_init(struct kvm *kvm)
 	if (!ple_gap)
 		kvm->arch.pause_in_guest = true;
 
+	/*
+	 * EPT Misconfigurations can be generated if the value of bits 2:0
+	 * of an EPT paging-structure entry is 110b (write/execute).
+	 */
+	if (enable_ept)
+		kvm_mmu_set_mmio_spte_mask(kvm, VMX_EPT_MISCONFIG_WX_VALUE,
+					   VMX_EPT_RWX_MASK);
+	else
+		kvm_mmu_set_mmio_spte_mask(kvm, vmx_shadow_mmio_mask,
+					   vmx_shadow_mmio_mask);
+
 	if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
 		switch (l1tf_mitigation) {
 		case L1TF_MITIGATION_OFF:
@@ -8358,6 +8371,19 @@ int __init vmx_init(void)
 	if (!enable_ept)
 		allow_smaller_maxphyaddr = true;
 
+	/*
+	 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
+	 * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
+	 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
+	 * 52-bit physical addresses then there are no reserved PA bits in the
+	 * PTEs and so the reserved PA approach must be disabled.
+	 */
+	if (kvm_get_shadow_phys_bits() < 52)
+		vmx_shadow_mmio_mask = BIT_ULL(51) | PT_PRESENT_MASK;
+	else
+		vmx_shadow_mmio_mask = 0;
+	kvm_mmu_set_mmio_access_mask(0);
+
 	return 0;
 }
 
arch/x86/kvm/vmx/x86_ops.h +1 -0
index 7e38c7b756d4..279e5360c555 100644
@@ -13,6 +13,7 @@ void hv_vp_assist_page_exit(void);
 void __init vmx_init_early(void);
 int __init vmx_init(void);
 void vmx_exit(void);
+extern u64 __ro_after_init vmx_shadow_mmio_mask;
 
 __init int vmx_cpu_has_kvm_support(void);
 __init int vmx_disabled_by_bios(void);
Signature · 5 lines
2.25.1


-- 
Isaku Yamahata <[email protected]>
#106 lore raw

Re: [PATCH v7 039/102] KVM: x86/mmu: Allow per-VM override of the TDP max page level

In reply to Kai Huang
Quoted 40 lines · Kai Huang
Quoted 4 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TODO: This is a transient workaround patch until the large page support for TDX is implemented. Support large page for TDX and remove this patch.

I don't understand. How does this patch have anything to do with what you are talking about here?

If you want to remove this patch later, then why not just explain the reason to remove when you actually have that patch?

Quoted 5 lines

At this point, large page for TDX isn't supported, and need to allow guest TD to work only with 4K pages. On the other hand, conventional VMX VMs should continue to work with large page. Allow per-VM override of the TDP max page level.

At which point/previous patch have you made/declared "large page for TDX isn't supported"?

If you want to declare you don't want to support large page for TDX, IMHO just declare it here, for instance:

"For simplicity, only support 4K page for TD guest."

Quoted 10 lines

In the existing x86 KVM MMU code, there is already max_level member in struct kvm_page_fault with KVM_MAX_HUGEPAGE_LEVEL initial value. The KVM page fault handler denies page size larger than max_level.

Add per-VM member to indicate the allowed maximum page size with KVM_MAX_HUGEPAGE_LEVEL as default value and initialize max_level in struct kvm_page_fault with it. For the guest TD, the set per-VM value for allows maximum page size to 4K page size. Then only allowed page size is 4K. It means large page is disabled.

To me it's overcomplicated. You just need simple sentences for such simple infrastructural patch. For instance:

Quoted 6 lines

"TDX requires special handling to support large private page. For simplicity, only support 4K page for TD guest for now. Add per-VM maximum page level support to support different maximum page sizes for TD guest and conventional VMX guest."

Just for your reference.

Thanks for the sentences. I'll replace the commit message with yours.

Signature · 1 line
Isaku Yamahata <[email protected]>
#109 lore raw

Re: [PATCH v7 040/102] KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for private mmu

In reply to Kai Huang
Quoted 7 lines · Kai Huang
Quoted 4 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

For kvm mmu that has shared bit mask, zap only leaf SPTEs when deleting/moving a memslot. The existing kvm_mmu_zap_memslot() depends on

Unless I am mistaken, I don't see there's an 'existing' kvm_mmu_zap_memslot().

Oops. it should be kvm_tdp_mmu_invalidate_all_roots().

Quoted 10 lines
Quoted 7 lines

role.invalid with read lock of mmu_lock so that other vcpu can operate on kvm mmu concurrently.

Mark the root page table invalid, unlink it from page table pointer of CPU, process the page table.

Are you talking about the behaviour of existing code, or the change you are going to make? Looks like you mean the latter but I believe it's the former.

The existing code. The should "It marks ...".

Quoted 10 lines
Quoted 4 lines

It doesn't work for private
page table to unlink the root page table because it requires all SPTE entry to be non-present.

I don't think we can truly *unlink* the private root page table from secure EPTP, right? The EPTP (root table) is fixed (and hidden) during TD's runtime.

I guess you are trying to say: removing/unlinking one secure-EPT page requires removing/unlinking all its children first?

That's right. I'll update it as follows.

Quoted 2 lines

So the reason to only zap leaf is we cannot truly unlink the private root page table, correct? Sorry your changelog is not obvious to me.

The reason is, to unlink a page table from the parent's SPTE, all SPTEs of the page table need to be non-present.

Here is the updated commit message.

KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for private mmu|
For kvm mmu that has shared bit mask, zap only leaf SPTEs when             |
deleting/moving a memslot.  The existing kvm_tdp_mmu_invalidate_all_roots()|
depends on role.invalid with read lock of mmu_lock so that other vcpu can  |
operate on kvm mmu concurrently.  It marks the root page table invalid,    |
zaps SPTEs of the root page tables.                                        |
                                                                           |
It doesn't work to unlink a private page table from the parent's SPTE entry|
because it requires all SPTE entry of the page table to be non-present.    |
Instead, with write-lock of mmu_lock and zap only leaf SPTEs for kvm mmu   |

with shared bit mask.

Quoted 42 lines
Quoted 27 lines

Instead, with write-lock of mmu_lock and zap only leaf SPTEs for kvm mmu with shared bit mask.

---
 arch/x86/kvm/mmu/mmu.c | 35 ++++++++++++++++++++++++++++++++++-
 1 file changed, 34 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/mmu.c +10 -0
index 80d7c7709af3..c517c7bca105 100644
@@ -5854,11 +5854,44 @@ static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
 }
 
+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
+{
+	bool flush = false;
+
+	write_lock(&kvm->mmu_lock);
+
+	/*
+	 * Zapping non-leaf SPTEs, a.k.a. not-last SPTEs, isn't required, worst
+	 * case scenario we'll have unused shadow pages lying around until they
+	 * are recycled due to age or when the VM is destroyed.

arch/x86/kvm/mmu/mmu.c static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm) · line 5876

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	 */
+	if (is_tdp_mmu_enabled(kvm)) {
+		struct kvm_gfn_range range = {
+		      .slot = slot,
+		      .start = slot->base_gfn,
+		      .end = slot->base_gfn + slot->npages,
+		      .may_block = false,
+		};
+
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);

It appears you only unmap private GFNs (because the base_gfn doesn't have shared bit)? I think shared mapping in this slot must be zapped too?

Quoted 2 lines

How is this done? Or the kvm_tdp_mmu_unmap_gfn_range() also zaps shared mappings?

kvm_tdp_mmu_unmap_gfn_range() handles both private gfn and shared gfn as they are alias.

Quoted 1 line

It's hard to review if one patch's behaviour/logic depends on further patches.

I'll add a comment on the call.

Signature · 1 line
Isaku Yamahata <[email protected]>
#113 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Kai Huang
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

Quoted 5 lines

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

https://lore.kernel.org/lkml/[email protected]/

Quoted 27 lines · On 3/4/22 20:48, [email protected] wrote:

Review

Quoted 7 lines

+ if (enable_ept) {

(quoted diff) +4 -1
+  const u64 init_value = enable_tdx ? VMX_EPT_SUPPRESS_VE_BIT : 0ull;
    kvm_mmu_set_ept_masks(enable_ept_ad_bits,
-          cpu_has_vmx_ept_execute_only());
+          cpu_has_vmx_ept_execute_only(), init_value);
+  kvm_mmu_set_spte_init_value(init_value);
+ }

I think kvm-intel.ko should use VMX_EPT_SUPPRESS_VE_BIT unconditionally as the init value. The bit is ignored anyway if the "EPT-violation #VE" execution control is 0. Otherwise looks good, but I have a couple more crazy ideas:

1) there could even be a test mode where KVM enables the execution control, traps #VE in the exception bitmap, and shouts loudly if it gets a #VE. That might avoid hard-to-find bugs due to forgetting about VMX_EPT_SUPPRESS_VE_BIT.

2) or even, perhaps the init_value for the TDP MMU could set bit 63 _unconditionally_, because KVM always sets the NX bit on AMD hardware. That would remove the whole infrastructure to keep shadow_init_value, because it would be constant 0 in mmu.c and constant BIT(63) in tdp_mmu.c.

Sean, what do you think?

Paolo

Signature · 1 line
Isaku Yamahata <[email protected]>
#123 lore raw

Re: [PATCH v7 043/102] KVM: x86/mmu: Focibly use TDP MMU for TDX

In reply to Sean Christopherson
Quoted 15 lines · Sean Christopherson

s/Focibly/Forcibly, but that's a moot point because KVM shouldn't override the the module param. KVM should instead _require_ the TDP MMU to be enabled. E.g. if userspace disables the TDP MMU to workaround a fatal bug, then forcing the TDP MMU may silently expose KVM to said bug.

And overriding tdp_enabled is just mind-boggling broken, all of the SPTE masks will be wrong.

Quoted 5 lines · On Mon, Jun 27, 2022, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

In this patch series, TDX supports only TDP MMU and doesn't support legacy MMU. Forcibly use TDP MMU for TDX irrelevant of kernel parameter to disable TDP MMU.

Quoted 5 lines

Do not refer to the "patch series", instead phrase the statement with respect to what KVM support.

Require the TDP MMU for TDX guests, the so called "shadow" MMU does not support mapping guest private memory, i.e. does not support Secure-EPT.

Thanks for rewrite of the commit message. Now the TDP MMU is default, I'll change

Quoted 25 lines
Quoted 12 lines
---
 arch/x86/kvm/mmu/tdp_mmu.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index 82f1bfac7ee6..7eb41b176d1e 100644
@@ -18,8 +18,13 @@ int kvm_mmu_init_tdp_mmu(struct kvm *kvm)
 {
 	struct workqueue_struct *wq;

arch/x86/kvm/mmu/tdp_mmu.c int kvm_mmu_init_tdp_mmu(struct kvm *kvm) · line 27

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -2
 
-	if (!tdp_enabled || !READ_ONCE(tdp_mmu_enabled))
-		return 0;
+	/*
+	 *  Because TDX supports only TDP MMU, forcibly use TDP MMU in the case
+	 *  of TDX.
+	 */
+	if (kvm->arch.vm_type != KVM_X86_TDX_VM &&
+		(!tdp_enabled || !READ_ONCE(tdp_mmu_enabled)))
+		return false;

Yeah, no.

Quoted 2 lines
	if (!tdp_enabled || !READ_ONCE(tdp_mmu_enabled))
		return kvm->arch.vm_type == KVM_X86_TDX_VM ? -EINVAL : 0;

I'll use -EOPNOTSUPP instead of -EINVAL.

Signature · 1 line
Isaku Yamahata <[email protected]>
#126 lore raw

Re: [PATCH v7 044/102] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Kai Huang
Quoted 58 lines · Kai Huang
Quoted 43 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk encrypted private page table, allocate a more page to mirror the existing KVM page table.  Resolve KVM page fault with the existing code, and do additional operations necessary for the mirrored private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. no mirrored private page table), and the KVM page table with mirrored private page table is called a private page table. The relationship is depicted below.

Add private pointer to struct kvm_mmu_page for mirrored private page table and add helper functions to allocate/initialize/free a mirrored private page table page. Also, add helper functions to check if a given kvm_mmu_page is private. The later patch introduces hooks to operate on the mirrored private page table.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
 CPU/KVM shared PT root  KVM private PT root     |  CPU private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            private PT <----mirror----> mirrored private PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |
Quoted 4 lines

PT: page table

Both CPU and KVM refer to CPU/KVM shared page table. Private page table is used only by KVM. CPU refers to mirrored private page table.

Shouldn't the private page table maintained by KVM be "mirrored private PT"?

To me "mirrored" normally implies it is fake, or backup which isn't actually used. But here "mirrored private PT" is actually used by hardware.

And to me, "CPU and KVM" above are confusing. For instance, "Both CPU and KVM refer to CPU/KVM shared page table" took me at least one minute to understand, with the help from the diagram -- otherwise I won't be able to understand.

Quoted 6 lines

I guess you can just say somewhere:

1) Shared PT is visible to KVM and it is used by CPU;
1) Private PT is used by CPU but it is invisible to KVM;
2) Mirrored private PT is visible to KVM but not used by CPU. It is used to mirror the actual private PT which is used by CPU.

I removed "mirror" word and use protected for encrypted page table.

KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk protected (encrypted) page table, allocate one more page to copy the protected page table for KVM MMU code to directly walk. Resolve KVM page fault with the existing code, and do additional operations necessary for the protected page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. not associated with protected page table), and the page table with protected page table is called a private page table. The relationship is depicted below.

Add a private pointer to struct kvm_mmu_page for protected page table and add helper functions to allocate/initialize/free a protected page table page. Also, add helper functions to check if a given kvm_mmu_page is private. The later patch introduces hooks to operate on the protected page table.

KVM page fault |
| |
V |
-------------+---------- |
| | |
V V |
shared GPA private GPA |
| | |
V V |
shared PT root private PT root | protected PT root
| | | |
V V | V
shared PT private PT ----propagate----> protected PT
| | | |
| \-----------------+------\ |
| | | |
V | V V
shared guest page | private guest page
|
non-encrypted memory | encrypted memory
|
PT: page table
- Shared PT is visible to KVM and it is used by CPU.
- Protected PT is used by CPU but it is invisible to KVM.
- Private PT is visible to KVM but not used by CPU. It is used to propagate PT change to the actual protected PT which is used by CPU.

Signature · 1 line
Isaku Yamahata <[email protected]>
#145 lore raw

Re: [PATCH v7 049/102] KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs

In reply to Yuan Yao
Quoted 19 lines · Yuan Yao
Quoted 18 lines · On Mon, Jun 27, 2022 at 02:53:41PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Some KVM MMU operations (dirty page logging, page migration, aging page) aren't supported for private GFNs (yet) with the first generation of TDX. Silently return on unsupported TDX KVM MMU operations.

---
 arch/x86/kvm/mmu/tdp_mmu.c | 74 +++++++++++++++++++++++++++++++++++---
 arch/x86/kvm/x86.c         |  3 ++
 2 files changed, 72 insertions(+), 5 deletions(-)
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index 12f75e60a254..fef6246086a8 100644
@@ -387,6 +387,8 @@ static void handle_changed_spte_dirty_log(struct kvm *kvm, int as_id, gfn_t gfn,
 
Quoted 6 lines

arch/x86/kvm/mmu/tdp_mmu.c static void handle_changed_spte_dirty_log(struct kvm *kvm, int as_id, gfn_t gfn, · line 391

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c +2 -0
 	if ((!is_writable_pte(old_spte) || pfn_changed) &&
 	    is_writable_pte(new_spte)) {
+		/* For memory slot operations, use GFN without aliasing */
+		gfn = gfn & ~kvm_gfn_shared_mask(kvm);

This should be part of enabling, please consider to squash it into patch 46.

Yes, merged into it.

Quoted 54 lines
Quoted 54 lines
arch/x86/kvm/mmu/tdp_mmu.c +23 -3
 		slot = __gfn_to_memslot(__kvm_memslots(kvm, as_id), gfn);
 		mark_page_dirty_in_slot(kvm, slot, gfn);
 	}
@@ -1398,7 +1400,8 @@ typedef bool (*tdp_handler_t)(struct kvm *kvm, struct tdp_iter *iter,
 
 static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
 						   struct kvm_gfn_range *range,
-						   tdp_handler_t handler)
+						   tdp_handler_t handler,
+						   bool only_shared)
 {
 	struct kvm_mmu_page *root;
 	struct tdp_iter iter;
@@ -1409,9 +1412,23 @@ static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm,
 	 * into this helper allow blocking; it'd be dead, wasteful code.
 	 */
 	for_each_tdp_mmu_root(kvm, root, range->slot->as_id) {
+		gfn_t start;
+		gfn_t end;
+
+		if (only_shared && is_private_sp(root))
+			continue;
+
 		rcu_read_lock();
 
-		tdp_root_for_each_leaf_pte(iter, root, range->start, range->end)
+		/*
+		 * For TDX shared mapping, set GFN shared bit to the range,
+		 * so the handler() doesn't need to set it, to avoid duplicated
+		 * code in multiple handler()s.
+		 */
+		start = kvm_gfn_for_root(kvm, root, range->start);
+		end = kvm_gfn_for_root(kvm, root, range->end);
+
+		tdp_root_for_each_leaf_pte(iter, root, start, end)
 			ret |= handler(kvm, &iter, range);
 
 		rcu_read_unlock();
@@ -1455,7 +1472,12 @@ static bool age_gfn_range(struct kvm *kvm, struct tdp_iter *iter,
 
 bool kvm_tdp_mmu_age_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 {
-	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range);
+	/*
+	 * First TDX generation doesn't support clearing A bit for private
+	 * mapping, since there's no secure EPT API to support it.  However
+	 * it's a legitimate request for TDX guest.
+	 */
+	return kvm_tdp_mmu_handle_gfn(kvm, range, age_gfn_range, true);
 }
 
 static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter,
@@ -1466,7 +1488,7 @@ static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter,
 
Quoted 8 lines

arch/x86/kvm/mmu/tdp_mmu.c static bool test_age_gfn(struct kvm *kvm, struct tdp_iter *iter, · line 1491

Quoted 4 lines
arch/x86/kvm/mmu/tdp_mmu.c +1 -1
 bool kvm_tdp_mmu_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
 {
-	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn);
+	return kvm_tdp_mmu_handle_gfn(kvm, range, test_age_gfn, false);

The "false" here means we will do young testing for even private pages, but we don't have actual A bit state in iter->old_spte for them, so may here should be "true" ?

Yes, nice catch.

Quoted 13 lines

arch/x86/kvm/mmu/tdp_mmu.c bool kvm_tdp_mmu_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range) · line 1539

Quoted 11 lines
arch/x86/kvm/mmu/tdp_mmu.c +3 -0
 }
 
 static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
@@ -1511,8 +1533,11 @@ bool kvm_tdp_mmu_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
 	 * No need to handle the remote TLB flush under RCU protection, the
 	 * target SPTE _must_ be a leaf SPTE, i.e. cannot result in freeing a
 	 * shadow page.  See the WARN on pfn_changed in __handle_changed_spte().
+	 *
+	 * .change_pte() callback should not happen for private page, because
+	 * for now TDX private pages are pinned during VM's life time.
 	 */

Worth to catch this by WARN_ON() ? Depends on you.

It call back can be called for shared pages. Here there is no easy way which GPA (private or shared) caused it. i.e. no easy condition for WARN_ON().

Signature · 1 line
Isaku Yamahata <[email protected]>
#153 lore raw

Re: [PATCH v7 053/102] KVM: TDX: don't request KVM_REQ_APIC_PAGE_RELOAD

In reply to Chao Gao
Quoted 9 lines · Chao Gao
Quoted 6 lines · Yuan Yao
Quoted 5 lines · On Mon, Jun 27, 2022 at 02:53:45PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX doesn't need APIC page depending on vapic and its callback is WARN_ON_ONCE(is_tdx). To avoid unnecessary overhead and WARN_ON_ONCE(), skip requesting KVM_REQ_APIC_PAGE_RELOAD when TD.

!kvm_gfn_shared_mask() doesn't ensure the VM is a TD. Right?

That's right. I changed the check as follows.

commit 6753fc53f3b3fcbbd07ac688578ff5fb7f7f7d96 (HEAD)

Author: Isaku Yamahata <[email protected]>
Date:   Wed Mar 30 22:32:03 2022 -0700
    KVM: TDX: don't request KVM_REQ_APIC_PAGE_RELOAD
    
    TDX doesn't need APIC page depending on vapic and its callback is
    WARN_ON_ONCE(is_tdx).  To avoid unnecessary overhead and WARN_ON_ONCE(),
    skip requesting KVM_REQ_APIC_PAGE_RELOAD when TD.
    
      WARNING: arch/x86/kvm/vmx/main.c:696 vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
      RIP: 0010:vt_set_apic_access_page_addr+0x3c/0x50 [kvm_intel]
      Call Trace:
       vcpu_enter_guest+0x145d/0x24d0 [kvm]
       kvm_arch_vcpu_ioctl_run+0x25d/0xcc0 [kvm]
       kvm_vcpu_ioctl+0x414/0xa30 [kvm]
       __x64_sys_ioctl+0xc0/0x100
       do_syscall_64+0x39/0xc0
       entry_SYSCALL_64_after_hwframe+0x44/0xae
    
    Signed-off-by: Isaku Yamahata <[email protected]>
arch/x86/kvm/x86.c +3 -1
index 51ba2d163ec4..bfd7ed6ba385 100644
@@ -10045,7 +10045,9 @@ void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
         * Update it when it becomes invalid.
         */
        apic_address = gfn_to_hva(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
-       if (start <= apic_address && apic_address < end)
+       /* TDX doesn't need APIC page. */
+       if (kvm->arch.vm_type != KVM_X86_TDX_VM &&
+           start <= apic_address && apic_address < end)
                kvm_make_all_cpus_request(kvm, KVM_REQ_APIC_PAGE_RELOAD);
 }
 
Signature · 1 line
Isaku Yamahata <[email protected]>
#110 lore raw

Re: [PATCH v7 040/102] KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for private mmu

In reply to Isaku Yamahata
Quoted 51 lines · Isaku Yamahata
Quoted 7 lines · Kai Huang
Quoted 4 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Sean Christopherson <[email protected]>

For kvm mmu that has shared bit mask, zap only leaf SPTEs when deleting/moving a memslot. The existing kvm_mmu_zap_memslot() depends on

Unless I am mistaken, I don't see there's an 'existing' kvm_mmu_zap_memslot().

Oops. it should be kvm_tdp_mmu_invalidate_all_roots().

Quoted 10 lines
Quoted 7 lines

role.invalid with read lock of mmu_lock so that other vcpu can operate on kvm mmu concurrently.

Mark the root page table invalid, unlink it from page table pointer of CPU, process the page table.

Are you talking about the behaviour of existing code, or the change you are going to make? Looks like you mean the latter but I believe it's the former.

The existing code. The should "It marks ...".

Quoted 10 lines
Quoted 4 lines

It doesn't work for private
page table to unlink the root page table because it requires all SPTE entry to be non-present.

I don't think we can truly *unlink* the private root page table from secure EPTP, right? The EPTP (root table) is fixed (and hidden) during TD's runtime.

I guess you are trying to say: removing/unlinking one secure-EPT page requires removing/unlinking all its children first?

That's right. I'll update it as follows.

Quoted 2 lines

So the reason to only zap leaf is we cannot truly unlink the private root page table, correct? Sorry your changelog is not obvious to me.

The reason is, to unlink a page table from the parent's SPTE, all SPTEs of the page table need to be non-present.

Here is the updated commit message.

Quoted 9 lines
KVM: x86/mmu: Zap only leaf SPTEs for deleted/moved memslot for private mmu|
For kvm mmu that has shared bit mask, zap only leaf SPTEs when             |
deleting/moving a memslot.  The existing kvm_tdp_mmu_invalidate_all_roots()|
depends on role.invalid with read lock of mmu_lock so that other vcpu can  |
operate on kvm mmu concurrently.  It marks the root page table invalid,    |
zaps SPTEs of the root page tables.                                        |
                                                                           |
It doesn't work to unlink a private page table from the parent's SPTE entry|
because it requires all SPTE entry of the page table to be non-present.    |

AFAICT this isn't the real reason that you cannot mark private root table as invalid, and do the same zapping as you mentioned above. There might be some change to support "zapping all children before zapping the parent for private table" (currently the actual page table is freed after RCU grace period, but not at unlink time), but I don't see how this cannot be supported, or at least the changelog doesn't explain why it cannot be supported.

The true reason is, if I understand correctly, you cannot truly unlink the private root page table from the hardware and then, i.e. allocate a new one for it. So just zap the leafs.

Quoted 48 lines

Instead, with write-lock of mmu_lock and zap only leaf SPTEs for kvm mmu |
with shared bit mask.

Quoted 42 lines
Quoted 27 lines

Instead, with write-lock of mmu_lock and zap only leaf SPTEs for kvm mmu with shared bit mask.

---
 arch/x86/kvm/mmu/mmu.c | 35 ++++++++++++++++++++++++++++++++++-
 1 file changed, 34 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/mmu.c +10 -0
index 80d7c7709af3..c517c7bca105 100644
@@ -5854,11 +5854,44 @@ static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
 	return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
 }
 
+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
+{
+	bool flush = false;
+
+	write_lock(&kvm->mmu_lock);
+
+	/*
+	 * Zapping non-leaf SPTEs, a.k.a. not-last SPTEs, isn't required, worst
+	 * case scenario we'll have unused shadow pages lying around until they
+	 * are recycled due to age or when the VM is destroyed.

arch/x86/kvm/mmu/mmu.c static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm) · line 5876

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+	 */
+	if (is_tdp_mmu_enabled(kvm)) {
+		struct kvm_gfn_range range = {
+		      .slot = slot,
+		      .start = slot->base_gfn,
+		      .end = slot->base_gfn + slot->npages,
+		      .may_block = false,
+		};
+
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);

It appears you only unmap private GFNs (because the base_gfn doesn't have shared bit)? I think shared mapping in this slot must be zapped too?

Quoted 2 lines

How is this done? Or the kvm_tdp_mmu_unmap_gfn_range() also zaps shared mappings?

Quoted 8 lines

kvm_tdp_mmu_unmap_gfn_range() handles both private gfn and shared gfn as they are alias.

Quoted 1 line

It's hard to review if one patch's behaviour/logic depends on further patches.

I'll add a comment on the call.

I don't think adding a comment is enough. The correctness of one patch needs to depend on future patch doesn't seem right. Please also consider patch reorganize/reorder.

#94 lore raw

Re: [PATCH v7 036/102] KVM: x86/mmu: Allow non-zero value for non-present SPTE

In reply to Isaku Yamahata
Quoted 11 lines · Isaku Yamahata

Thanks for review. Now here is the updated version.

From f1ee540d62ba13511b2c7d3db7662e32bd263e48 Mon Sep 17 00:00:00 2001
Message-Id: <f1ee540d62ba13511b2c7d3db7662e32bd263e48.1657823906.git.isaku.yamahata@intel.com>
In-Reply-To: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1657823906.git.isaku.yamahata@intel.com>
References: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1657823906.git.isaku.yamahata@intel.com>
From: Sean Christopherson <[email protected]>
Date: Mon, 29 Jul 2019 19:23:46 -0700
Subject: [PATCH 036/304] KVM: x86/mmu: Allow non-zero value for non-present
SPTE

Quoted 5 lines

TDX introduced a new ETP, Secure-EPT, in addition to the existing EPT. Secure-EPT maps protected guest memory, which is called private. Since Secure-EPT page tables is also protected, those page tables is also called private. The existing EPT is often called shared EPT to distinguish from Secure-EPT. And also page tables for shared EPT is also called shared.

AFAICT secure-EPT isn't quite directly related here, so I don't think you should spend the paragraph on it. The first paragraph should state the problem and catch reviewer's eyeball.

Quoted 27 lines

TDX module enables #VE injection by setting "EPT-violation #VE" in secondary processor-based VM-execution controls of TD VMCS. It also sets "suppress #VE" bit in Secure-EPT so that EPT violation on Secure-EPT causes exit to VMM.

Because guest memory is protected with TDX, VMM can't parse instructions in the guest memory. Instead, MMIO hypercall is used for guest TD to pass necessary information to VMM. To make unmodified device driver work, guest TD expects #VE on accessing shared GPA for MMIO. The #VE handler of guest TD converts MMIO access into MMIO hypercall. To trigger #VE in guest TD, VMM needs to clear "suppress #VE" bit in shared EPT entry that corresponds to MMIO address.

So the execution flow related for MMIO is as follows

- TDX module sets "EPT-violation #VE" in secondary processor-based VM-execution controls of TD VMCS.
- Allocate page for shared EPT PML4E page. Shared EPT entries are initialized with suppress #VE bit set. Update the EPTP pointer.
- TD accesses a GPA for MMIO to trigger EPT violation. It exits to VMM with EPT violation due to suppress #VE bit of EPT entries of PML4E page.
- VMM figures out the faulted GPA is for MMIO
- start shared EPT page table walk.
- Allocate non-leaf EPT pages for the shared EPT.
- Allocate leaf EPT page for the shared EPT and initialize EPT entries with suppress #VE bit set.

Quoted 8 lines

- VMM clears the suppress #VE bit for faulted GPA for MMIO. Please notice the leaf EPT page has 512 SPTE and other 511 SPTE entries need to keep "suppress #VE" bit set because GPAs for those SPTEs are not known to be MMIO. (It requires further lookups.)
If GPA is a guest page, link the guest page from the leaf SPTE entry.
- resume TD vcpu.
- Guest TD gets #VE, and converts MMIO access into MMIO hypercall.
- If the GPA maps guest memory, VMM resolves it with guest pages.

Too many details IMHO.

Also, you forgot to mention the non-zero value for non-present SPTE is not just for MMIO, but also for shared memory.

How about below?

For TD guest, the current way to emulate MMIO doesn't work any more, as KVM is not able to access the private memory of TD guest and do the emulation. Instead, TD guest expects to receive #VE when it accesses the MMIO and then it can explicitly makes hypercall to KVM to get the expected information.

To achieve this, the TDX module always enables "EPT-violation #VE" in the VMCS control. And accordingly, KVM needs to configure the MMIO spte to trigger EPT violation (instead of misconfiguration) and at the same time, also clear the "suppress #VE" bit so the TD guest can get the #VE instead of causing actual EPT violation to KVM.

In order for KVM to be able to have chance to set up the correct SPTE for MMIO for TD guest, the default non-present SPTE must have the "suppress #VE" bit set so KVM can get a real EPT violation for the first time when TD guest accesses the MMIO.

Also, when TD guest accesses the actual shared memory, it should continue to trigger EPT violation to the KVM instead of receiving the #VE (the TDX module guarantees KVM will receive EPT violation for private memory access). This means for the shared memory, the SPTE also must have the "suppress #VE" bit set for the non-present SPTE.

Add support to allow a non-zero value for the non-present SPTE (i.e. when the page table is firstly allocated, and when the SPTE is zapped) to allow setting "suppress #VE" bit for the non-present SPTE.

Introduce a new macro SHADOW_NONPRESENT_VALUE to be the "suppress #VE" bit. Unconditionally set the "suppress #VE" bit (which is bit 63) for both AMD and Intel as: 1) AMD hardware doesn't use this bit; 2) for normal VMX guest, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

(if you want to set SHADOW_NONPRESENT_VALUE only for TDP MMU then continue to describe, but I don't see this is done in your below patch)

Quoted 11 lines

SPTEs for shared EPT need suppress #VE" bit set initially when it is allocated or zapped, therefore non-zero non-present value for SPTE needs to be allowed.

TDP MMU uses REMOVED_SPTE = 0x5a0ULL as special constant to indicate the intermediate value to indicate one thread is operating on it and the value should be semi-arbitrary value. For TDX (more exactly to use #VE), the value should include suppress #VE bit. Rename REMOVED_SPTE to __REMOVED_SPTE and define REMOVED_SPTE as (REMOVED_SPTE | "suppress #VE") bit.

IMHO REMOVED_SPTE is implementation details so it's OK to not mention in changelog.

Quoted 212 lines

For simplicity, "suppress #VE" bit is set unconditionally for X86_64 for non-present SPTE. Because "suppress #VE" bit (bit position of 63) for non-present SPTE is ignored for non-TD case (AMD CPUs or Intel VMX case with "EPT-violation #VE" cleared), the functionality shouldn't change.

---
 arch/x86/kvm/mmu/mmu.c         | 71 ++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/paging_tmpl.h |  3 +-
 arch/x86/kvm/mmu/spte.c        |  5 ++-
 arch/x86/kvm/mmu/spte.h        | 28 +++++++++++++-
 arch/x86/kvm/mmu/tdp_mmu.c     | 23 +++++++----
 5 files changed, 116 insertions(+), 14 deletions(-)
arch/x86/kvm/mmu/mmu.c +68 -3
index 51306b80f47c..992f31458f94 100644
@@ -668,6 +668,55 @@ static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
 	}
 }
 
+#ifdef CONFIG_X86_64
+static inline void kvm_init_shadow_page(void *page)
+{
+	int ign;
+
+	/*
+	 * AMD: "suppress #VE" bit is ignored
+	 * Intel non-TD(VMX): "suppress #VE" bit is ignored because
+	 *   EPT_VIOLATION_VE isn't set.
+	 * guest TD: TDX module sets EPT_VIOLATION_VE
+	 *   conventional SEPT: "suppress #VE" bit must be set to get EPT violation
+	 *   private SEPT: "suppress #VE" bit is ignored.  CPU doesn't walk it
+	 *
+	 * For simplicity, unconditionally initialize SPET to set "suppress #VE".
+	 */
+	asm volatile ("rep stosq\n\t"
+		      : "=c"(ign), "=D"(page)
+		      : "a"(SHADOW_NONPRESENT_VALUE), "c"(4096/8), "D"(page)
+		      : "memory"
+	);
+}
+
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	struct kvm_mmu_memory_cache *mc = &vcpu->arch.mmu_shadow_page_cache;
+	int start, end, i, r;
+
+	start = kvm_mmu_memory_cache_nr_free_objects(mc);
+	r = kvm_mmu_topup_memory_cache(mc, PT64_ROOT_MAX_LEVEL);
+
+	/*
+	 * Note, topup may have allocated objects even if it failed to allocate
+	 * the minimum number of objects required to make forward progress _at
+	 * this time_.  Initialize newly allocated objects even on failure, as
+	 * userspace can free memory and rerun the vCPU in response to -ENOMEM.
+	 */
+	end = kvm_mmu_memory_cache_nr_free_objects(mc);
+	for (i = start; i < end; i++)
+		kvm_init_shadow_page(mc->objects[i]);
+	return r;
+}
+#else
+static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
+{
+	return kvm_mmu_topup_memory_cache(vcpu->arch.mmu_shadow_page_cache,
+					  PT64_ROOT_MAX_LEVEL);
+}
+#endif /* CONFIG_X86_64 */
+
 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 {
 	int r;
@@ -677,8 +726,7 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 				       1 + PT64_ROOT_MAX_LEVEL + PTE_PREFETCH_NUM);
 	if (r)
 		return r;
-	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
-				       PT64_ROOT_MAX_LEVEL);
+	r = mmu_topup_shadow_page_cache(vcpu);
 	if (r)
 		return r;
 	if (maybe_indirect) {
@@ -5654,7 +5702,24 @@ int kvm_mmu_create(struct kvm_vcpu *vcpu)
 	vcpu->arch.mmu_page_header_cache.kmem_cache = mmu_page_header_cache;
 	vcpu->arch.mmu_page_header_cache.gfp_zero = __GFP_ZERO;
 
-	vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
+	/*
+	 * When X86_64, initial SEPT entries are initialized with
+	 * SHADOW_NONPRESENT_VALUE.  Otherwise zeroed.  See
+	 * mmu_topup_shadow_page_cache().
+	 *
+	 * Shared EPTEs need to be initialized with SUPPRESS_VE=1, otherwise
+	 * not-present EPT violations would be reflected into the guest by
+	 * hardware as #VE exceptions.  This is handled by initializing page
+	 * allocations via kvm_init_shadow_page() during cache topup.
+	 * In that case, telling the page allocation to zero-initialize the page
+	 * would be wasted effort.
+	 *
+	 * The initialization is harmless for S-EPT entries because KVM's copy
+	 * of the S-EPT isn't consumed by hardware, and because under the hood
+	 * S-EPT entries should never #VE.
+	 */
+	if (!IS_ENABLED(X86_64))
+		vcpu->arch.mmu_shadow_page_cache.gfp_zero = __GFP_ZERO;
 
 	vcpu->arch.mmu = &vcpu->arch.root_mmu;
 	vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
arch/x86/kvm/mmu/paging_tmpl.h +2 -1
index fe35d8fd3276..964ec76579f0 100644
@@ -1031,7 +1031,8 @@ static int FNAME(sync_page)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 		gpa_t pte_gpa;
 		gfn_t gfn;
 
-		if (!sp->spt[i])
+		/* spt[i] has initial value of shadow page table allocation */
+		if (sp->spt[i] != SHADOW_NONPRESENT_VALUE)
 			continue;
 
 		pte_gpa = first_pte_gpa + i * sizeof(pt_element_t);
arch/x86/kvm/mmu/spte.c +4 -1
index cda1851ec155..bd441458153f 100644
@@ -36,6 +36,9 @@ u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_value;
 u64 __read_mostly shadow_me_mask;
 u64 __read_mostly shadow_acc_track_mask;
+#ifdef CONFIG_X86_64
+u64 __read_mostly shadow_nonpresent_value;
+#endif
 
 u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
 u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
@@ -360,7 +363,7 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	 * not set any RWX bits.
 	 */
 	if (WARN_ON((mmio_value & mmio_mask) != mmio_value) ||
-	    WARN_ON(mmio_value && (REMOVED_SPTE & mmio_mask) == mmio_value))
+	    WARN_ON(mmio_value && (__REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;
 
 	if (!mmio_value)
arch/x86/kvm/mmu/spte.h +26 -2
index 0127bb6e3c7d..f5fd22f6bf5f 100644
@@ -140,6 +140,19 @@ static_assert(MMIO_SPTE_GEN_LOW_BITS == 8 && MMIO_SPTE_GEN_HIGH_BITS == 11);
 
 #define MMIO_SPTE_GEN_MASK		GENMASK_ULL(MMIO_SPTE_GEN_LOW_BITS + MMIO_SPTE_GEN_HIGH_BITS - 1, 0)
 
+/*
+ * non-present SPTE value for both VMX and SVM for TDP MMU.
+ * For SVM NPT, for non-present spte (bit 0 = 0), other bits are ignored.
+ * For VMX EPT, bit 63 is ignored if #VE is disabled.
+ *              bit 63 is #VE suppress if #VE is enabled.
+ */
+#ifdef CONFIG_X86_64
+#define SHADOW_NONPRESENT_VALUE	BIT_ULL(63)
+static_assert(!(SHADOW_NONPRESENT_VALUE & SPTE_MMU_PRESENT_MASK));
+#else
+#define SHADOW_NONPRESENT_VALUE	0ULL
+#endif
+
 extern u64 __read_mostly shadow_host_writable_mask;
 extern u64 __read_mostly shadow_mmu_writable_mask;
 extern u64 __read_mostly shadow_nx_mask;
@@ -178,16 +191,27 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  * non-present intermediate value. Other threads which encounter this value
  * should not modify the SPTE.
  *
+ * For X86_64 case, SHADOW_NONPRESENT_VALUE, "suppress #VE" bit, is set because
+ * "EPT violation #VE" in the secondary VM execution control may be enabled.
+ * Because TDX module sets "EPT violation #VE" for TD, "suppress #VE" bit for
+ * the conventional EPT needs to be set.
+ *
  * Use a semi-arbitrary value that doesn't set RWX bits, i.e. is not-present on
  * bot AMD and Intel CPUs, and doesn't set PFN bits, i.e. doesn't create a L1TF
  * vulnerability.  Use only low bits to avoid 64-bit immediates.
  *
  * Only used by the TDP MMU.
  */
-#define REMOVED_SPTE	0x5a0ULL
+#define __REMOVED_SPTE	0x5a0ULL
 
 /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
-static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
+static_assert(!(__REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
+
+/*
+ * See above comment around __REMOVED_SPTE.  REMOVED_SPTE is the actual
+ * intermediate value set to the removed SPET.  it sets the "suppress #VE" bit.
+ */
+#define REMOVED_SPTE	(SHADOW_NONPRESENT_VALUE | __REMOVED_SPTE)
 
 static inline bool is_removed_spte(u64 spte)
 {
arch/x86/kvm/mmu/tdp_mmu.c +1 -0
index 7b9265d67131..2ca03ec3bf52 100644
@@ -692,8 +692,16 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * overwrite the special removed SPTE value. No bookkeeping is needed
 	 * here since the SPTE is going from non-present to non-present.  Use
 	 * the raw write helper to avoid an unnecessary check on volatile bits.
+	 *

arch/x86/kvm/mmu/tdp_mmu.c static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm, · line 704

Quoted 10 lines
arch/x86/kvm/mmu/tdp_mmu.c +8 -1
+	 * Set non-present value to SHADOW_NONPRESENT_VALUE, rather than 0.
+	 * It is because when TDX is enabled, TDX module always
+	 * enables "EPT-violation #VE", so KVM needs to set
+	 * "suppress #VE" bit in EPT table entries, in order to get
+	 * real EPT violation, rather than TDVMCALL.  KVM sets
+	 * SHADOW_NONPRESENT_VALUE (which sets "suppress #VE" bit) so it
+	 * can be set when EPT table entries are zapped.
 	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);

Since you also always set SHADOW_NONPRESENT_VALUE to SPTE for legacy MMU when the page table is firstly allocated, it also makes sense to set it when SPTE is zapped for legacy MMU.

This part is missing in this patch.

Quoted 49 lines
arch/x86/kvm/mmu/tdp_mmu.c +7 -6
 	return 0;
 }
@@ -870,8 +878,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 
 		if (!shared)
-			tdp_mmu_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
 			goto retry;
 	}
 }
@@ -927,8 +935,9 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
 	if (WARN_ON_ONCE(!is_shadow_present_pte(old_spte)))
 		return false;
 
-	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte, 0,
-			   sp->gfn, sp->role.level + 1, true, true);
+	__tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			   SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1,
+			   true, true);
 
 	return true;
 }
@@ -965,7 +974,7 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 		    !is_last_spte(iter.old_spte, iter.level))
 			continue;
 
-		tdp_mmu_set_spte(kvm, &iter, 0);
+		tdp_mmu_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
 		flush = true;
 	}
 
@@ -1330,7 +1339,7 @@ static bool set_spte_gfn(struct kvm *kvm, struct tdp_iter *iter,
 	 * invariant that the PFN of a present * leaf SPTE can never change.
 	 * See __handle_changed_spte().
 	 */
-	tdp_mmu_set_spte(kvm, iter, 0);
+	tdp_mmu_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
 
 	if (!pte_write(range->pte)) {
 		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
Signature · 1 line
2.25.1
#95 lore raw

Re: [PATCH v7 036/102] KVM: x86/mmu: Allow non-zero value for non-present SPTE

In reply to Isaku Yamahata

arch/x86/kvm/mmu/spte.c u64 __read_mostly shadow_present_mask; · line 41

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +3 -0
@@ -36,6 +36,9 @@ u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_value;
 u64 __read_mostly shadow_me_mask;
 u64 __read_mostly shadow_acc_track_mask;
+#ifdef CONFIG_X86_64
+u64 __read_mostly shadow_nonpresent_value;
+#endif

Is this ever used?

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) · line 367

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +1 -1
 u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
 u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
@@ -360,7 +363,7 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	 * not set any RWX bits.
 	 */
 	if (WARN_ON((mmio_value & mmio_mask) != mmio_value) ||
-	    WARN_ON(mmio_value && (REMOVED_SPTE & mmio_mask) == mmio_value))
+	    WARN_ON(mmio_value && (__REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;

This chunk doesn't look right, or necessary. We need mmio_mask/mmio_value which causes EPT violation but with "suppress #VE" bit clear.

So, actually, we want to make sure SHADOW_NONPRESENT_VALUE is *NOT* in mmio_mask and mmio_value. Using (REMOVED_SPTE & mmio_mask) == mmio_value can actually ensure SHADOW_NONPRESENT_VALUE is never set in MMIO spte, correct? So I think using REMOVED_SPTE is fine.

Or maybe additionally adding a explicit check is even better:

	if (WARN_ON(mmio_mask & SHADOW_NONPRESENT_VALUE))
		mmio_value = 0;

But this change maybe should be in another patch which deals setting up per-VM mmio_mask/mmio_value anyway. This patch, instead, focuses on allowing non-zero value for non-present SPTE.

#100 lore raw

Re: [PATCH v7 037/102] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to Isaku Yamahata
Quoted 14 lines · Isaku Yamahata

Here is the updated one. The changes are
- removed hunks that should be a part of other patches.
- removed shadow_default_mmio_mask
- trimed down commit messages.

From ed6b4a076e515550878b069596cf156a1bc33514 Mon Sep 17 00:00:00 2001
Message-Id: <ed6b4a076e515550878b069596cf156a1bc33514.1658220363.git.isaku.yamahata@intel.com>
In-Reply-To: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658220363.git.isaku.yamahata@intel.com>
References: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658220363.git.isaku.yamahata@intel.com>
From: Sean Christopherson <[email protected]>
Date: Wed, 10 Jun 2020 15:46:38 -0700
Subject: [PATCH 036/306] KVM: x86/mmu: Track shadow MMIO value/mask on a
per-VM basis

Quoted 5 lines

TDX will use a different shadow PTE entry value for MMIO from VMX. Add members to kvm_arch and track value for MMIO per-VM instead of global variables. By using the per-VM EPT entry value for MMIO, the existing VMX logic is kept working. To untangle the logic to initialize shadow_mmio_access_mask, introduce a setter function.

introduce a separate setter function for it.

Quoted 123 lines
---
 arch/x86/include/asm/kvm_host.h |  4 +++
 arch/x86/kvm/mmu.h              |  3 ++-
 arch/x86/kvm/mmu/mmu.c          |  8 +++---
 arch/x86/kvm/mmu/spte.c         | 45 +++++++++------------------------
 arch/x86/kvm/mmu/spte.h         | 10 +++-----
 arch/x86/kvm/mmu/tdp_mmu.c      |  6 ++---
 arch/x86/kvm/svm/svm.c          | 11 +++++---
 arch/x86/kvm/vmx/tdx.c          |  4 +++
 arch/x86/kvm/vmx/vmx.c          | 26 +++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h      |  1 +
 10 files changed, 66 insertions(+), 52 deletions(-)
arch/x86/include/asm/kvm_host.h +4 -0
index 2c47aab72a1b..39215daa8576 100644
@@ -1161,6 +1161,10 @@ struct kvm_arch {
 	 */
 	spinlock_t mmu_unsync_pages_lock;
 
+	bool enable_mmio_caching;
+	u64 shadow_mmio_value;
+	u64 shadow_mmio_mask;
+
 	struct list_head assigned_dev_head;
 	struct iommu_domain *iommu_domain;
 	bool iommu_noncoherent;
arch/x86/kvm/mmu.h +2 -1
index ccf0ba7a6387..cfa3e658162c 100644
@@ -108,7 +108,8 @@ static inline u8 kvm_get_shadow_phys_bits(void)
 	return boot_cpu_data.x86_phys_bits;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask);
+void kvm_mmu_set_mmio_access_mask(u64 mmio_access_mask);
 void kvm_mmu_set_me_spte_mask(u64 me_value, u64 me_mask);
 void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only);
 
arch/x86/kvm/mmu/mmu.c +4 -4
index 5bfccfa0f50e..34240fcc45de 100644
@@ -2298,7 +2298,7 @@ static int mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
 				return kvm_mmu_prepare_zap_page(kvm, child,
 								invalid_list);
 		}
-	} else if (is_mmio_spte(pte)) {
+	} else if (is_mmio_spte(kvm, pte)) {
 		mmu_spte_clear_no_track(spte);
 	}
 	return 0;
@@ -3079,7 +3079,7 @@ static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fau
 		 * and only if L1's MAXPHYADDR is inaccurate with respect to
 		 * the hardware's).
 		 */
-		if (unlikely(!enable_mmio_caching) ||
+		if (unlikely(!vcpu->kvm->arch.enable_mmio_caching) ||
 		    unlikely(fault->gfn > kvm_mmu_max_gfn()))
 			return RET_PF_EMULATE;
 	}
@@ -3918,7 +3918,7 @@ static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
 	if (WARN_ON(reserved))
 		return -EINVAL;
 
-	if (is_mmio_spte(spte)) {
+	if (is_mmio_spte(vcpu->kvm, spte)) {
 		gfn_t gfn = get_mmio_spte_gfn(spte);
 		unsigned int access = get_mmio_spte_access(spte);
 
@@ -4361,7 +4361,7 @@ static unsigned long get_cr3(struct kvm_vcpu *vcpu)
 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
 			   unsigned int access)
 {
-	if (unlikely(is_mmio_spte(*sptep))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, *sptep))) {
 		if (gfn != get_mmio_spte_gfn(*sptep)) {
 			mmu_spte_clear_no_track(sptep);
 			return true;
arch/x86/kvm/mmu/spte.c +3 -6
index 92968e5605fc..9a130dd3d6a3 100644
@@ -29,8 +29,6 @@ u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 u64 __read_mostly shadow_user_mask;
 u64 __read_mostly shadow_accessed_mask;
 u64 __read_mostly shadow_dirty_mask;
-u64 __read_mostly shadow_mmio_value;
-u64 __read_mostly shadow_mmio_mask;
 u64 __read_mostly shadow_mmio_access_mask;
 u64 __read_mostly shadow_present_mask;
 u64 __read_mostly shadow_me_value;
@@ -62,10 +60,10 @@ u64 make_mmio_spte(struct kvm_vcpu *vcpu, u64 gfn, unsigned int access)
 	u64 spte = generation_mmio_spte_mask(gen);
 	u64 gpa = gfn << PAGE_SHIFT;
 
-	WARN_ON_ONCE(!shadow_mmio_value);
+	WARN_ON_ONCE(!vcpu->kvm->arch.shadow_mmio_value);
 
 	access &= shadow_mmio_access_mask;
-	spte |= shadow_mmio_value | access;
+	spte |= vcpu->kvm->arch.shadow_mmio_value | access;
 	spte |= gpa | shadow_nonpresent_or_rsvd_mask;
 	spte |= (gpa & shadow_nonpresent_or_rsvd_mask)
 		<< SHADOW_NONPRESENT_OR_RSVD_MASK_LEN;
@@ -337,9 +335,8 @@ u64 mark_spte_for_access_track(u64 spte)
 	return spte;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask)
 {
-	BUG_ON((u64)(unsigned)access_mask != access_mask);
 	WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
 
 	if (!enable_mmio_caching)

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) · line 366

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +1 -6
@@ -366,12 +363,9 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	    WARN_ON(mmio_value && (__REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;
 
-	if (!mmio_value)
-		enable_mmio_caching = false;
-
-	shadow_mmio_value = mmio_value;
-	shadow_mmio_mask  = mmio_mask;
-	shadow_mmio_access_mask = access_mask;
+	kvm->arch.enable_mmio_caching = !!mmio_value;

KVM has a global enable_mmio_caching boolean, and I think we should honor it here (in this patch) by doing below first:

	if (enabling_mmio_caching)
		mmio_value = 0;

For TD guest, the logic around enable_mmio_caching doesn't make sense anymore, so perhaps we can later tweak it by doing something like:

	/*
	 * Treat mmio_caching is false for TD guest, or true for it, depending
	 * on how you define it.
	 */
	if (kvm_gfn_shared_mask(kvm))
		kvm->arch.enable_mmio_caching = false;	/* or true? */
	else {
		if (!enable_mmio_caching)
			mmio_value = 0;
		kvm->arch.enable_mmio_caching = !!mmio_value;
	}
Quoted 56 lines
arch/x86/kvm/mmu/spte.c +8 -21
+	kvm->arch.shadow_mmio_value = mmio_value;
+	kvm->arch.shadow_mmio_mask = mmio_mask;
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
 
@@ -399,20 +393,12 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	shadow_acc_track_mask	= VMX_EPT_RWX_MASK;
 	shadow_host_writable_mask = EPT_SPTE_HOST_WRITABLE;
 	shadow_mmu_writable_mask  = EPT_SPTE_MMU_WRITABLE;
-
-	/*
-	 * EPT Misconfigurations are generated if the value of bits 2:0
-	 * of an EPT paging-structure entry is 110b (write/execute).
-	 */
-	kvm_mmu_set_mmio_spte_mask(VMX_EPT_MISCONFIG_WX_VALUE,
-				   VMX_EPT_RWX_MASK, 0);
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_ept_masks);
 
 void kvm_mmu_reset_all_pte_masks(void)
 {
 	u8 low_phys_bits;
-	u64 mask;
 
 	shadow_phys_bits = kvm_get_shadow_phys_bits();
 
@@ -452,18 +438,11 @@ void kvm_mmu_reset_all_pte_masks(void)
 
 	shadow_host_writable_mask = DEFAULT_SPTE_HOST_WRITABLE;
 	shadow_mmu_writable_mask  = DEFAULT_SPTE_MMU_WRITABLE;
+}
 
-	/*
-	 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
-	 * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
-	 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
-	 * 52-bit physical addresses then there are no reserved PA bits in the
-	 * PTEs and so the reserved PA approach must be disabled.
-	 */
-	if (shadow_phys_bits < 52)
-		mask = BIT_ULL(51) | PT_PRESENT_MASK;
-	else
-		mask = 0;
-
-	kvm_mmu_set_mmio_spte_mask(mask, mask, ACC_WRITE_MASK | ACC_USER_MASK);
+void kvm_mmu_set_mmio_access_mask(u64 mmio_access_mask)
+{
+	BUG_ON((u64)(unsigned)mmio_access_mask != mmio_access_mask);
+	shadow_mmio_access_mask = mmio_access_mask;
 }
+EXPORT_SYMBOL(kvm_mmu_set_mmio_access_mask);
arch/x86/kvm/mmu/spte.h +0 -0
index f5fd22f6bf5f..99bce92b596e 100644

arch/x86/kvm/mmu/spte.h line 9

Quoted 5 lines
arch/x86/kvm/mmu/spte.h +0 -2
@@ -5,8 +5,6 @@
 
 #include "mmu_internal.h"
 
-extern bool __read_mostly enable_mmio_caching;
-

Here you removed the ability to control enable_mmio_caching globally. It's not something you stated to do in the changelog. Perhaps we should still keep it, and enforce it in kvm_mmu_set_mmio_spte_mask() as commented above.

And in upstream KVM, it is a module parameter. What happens to it?

Quoted 106 lines
arch/x86/kvm/mmu/spte.h +3 -5
 /*
  * A MMU present SPTE is backed by actual memory and may or may not be present
  * in hardware.  E.g. MMIO SPTEs are not considered present.  Use bit 11, as it
@@ -160,8 +158,6 @@ extern u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
 extern u64 __read_mostly shadow_user_mask;
 extern u64 __read_mostly shadow_accessed_mask;
 extern u64 __read_mostly shadow_dirty_mask;
-extern u64 __read_mostly shadow_mmio_value;
-extern u64 __read_mostly shadow_mmio_mask;
 extern u64 __read_mostly shadow_mmio_access_mask;
 extern u64 __read_mostly shadow_present_mask;
 extern u64 __read_mostly shadow_me_value;
@@ -228,10 +224,10 @@ static inline bool is_removed_spte(u64 spte)
  */
 extern u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
 
-static inline bool is_mmio_spte(u64 spte)
+static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)
 {
-	return (spte & shadow_mmio_mask) == shadow_mmio_value &&
-	       likely(enable_mmio_caching);
+	return (spte & kvm->arch.shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
+		likely(kvm->arch.enable_mmio_caching);
 }
 
 static inline bool is_shadow_present_pte(u64 pte)
arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index 2ca03ec3bf52..82f1bfac7ee6 100644
@@ -569,8 +569,8 @@ static void __handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
 		 * impact the guest since both the former and current SPTEs
 		 * are nonpresent.
 		 */
-		if (WARN_ON(!is_mmio_spte(old_spte) &&
-			    !is_mmio_spte(new_spte) &&
+		if (WARN_ON(!is_mmio_spte(kvm, old_spte) &&
+			    !is_mmio_spte(kvm, new_spte) &&
 			    !is_removed_spte(new_spte)))
 			pr_err("Unexpected SPTE change! Nonpresent SPTEs\n"
 			       "should not be replaced with another,\n"
@@ -1108,7 +1108,7 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	}
 
 	/* If a MMIO SPTE is installed, the MMIO will need to be emulated. */
-	if (unlikely(is_mmio_spte(new_spte))) {
+	if (unlikely(is_mmio_spte(vcpu->kvm, new_spte))) {
 		vcpu->stat.pf_mmio_spte_created++;
 		trace_mark_mmio_spte(rcu_dereference(iter->sptep), iter->gfn,
 				     new_spte);
arch/x86/kvm/svm/svm.c +7 -4
index f01821f48bfd..0f63257161a6 100644
@@ -198,6 +198,7 @@ module_param(dump_invalid_vmcb, bool, 0644);
 bool intercept_smi = true;
 module_param(intercept_smi, bool, 0444);
 
+static u64 __read_mostly svm_shadow_mmio_mask;
 
 static bool svm_gp_erratum_intercept = true;
 
@@ -4685,6 +4686,9 @@ static bool svm_is_vm_type_supported(unsigned long type)
 
 static int svm_vm_init(struct kvm *kvm)
 {
+	kvm_mmu_set_mmio_spte_mask(kvm, svm_shadow_mmio_mask,
+				   svm_shadow_mmio_mask);
+
 	if (!pause_filter_count || !pause_filter_thresh)
 		kvm->arch.pause_in_guest = true;
 
@@ -4834,7 +4838,7 @@ static struct kvm_x86_ops svm_x86_ops __initdata = {
 static __init void svm_adjust_mmio_mask(void)
 {
 	unsigned int enc_bit, mask_bit;
-	u64 msr, mask;
+	u64 msr;
 
 	/* If there is no memory encryption support, use existing mask */
 	if (cpuid_eax(0x80000000) < 0x8000001f)
@@ -4861,9 +4865,8 @@ static __init void svm_adjust_mmio_mask(void)
 	 *
 	 * If the mask bit location is 52 (or above), then clear the mask.
 	 */
-	mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
-
-	kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
+	svm_shadow_mmio_mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
+	kvm_mmu_set_mmio_access_mask(PT_WRITABLE_MASK | PT_USER_MASK);
 }
 
 static __init void svm_set_cpu_caps(void)
arch/x86/kvm/vmx/tdx.c +1 -0
index 36d2127cb7b7..52fb54880f9b 100644
@@ -7,6 +7,7 @@
 #include "x86_ops.h"
 #include "tdx.h"
 #include "x86.h"
+#include "mmu.h"
 
 #undef pr_fmt
 #define pr_fmt(fmt) "tdx: " fmt

arch/x86/kvm/vmx/tdx.c int tdx_vm_init(struct kvm *kvm) · line 282

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +3 -0
@@ -276,6 +277,9 @@ int tdx_vm_init(struct kvm *kvm)
 	int ret, i;
 	u64 err;
 
+	kvm_mmu_set_mmio_spte_mask(kvm, vmx_shadow_mmio_mask,
+				   vmx_shadow_mmio_mask);
+

I prefer to split this chunk out to another patch so this patch can be purely
infrastructural. In this way you can even move this patch around easily in
this series.

Quoted 70 lines
arch/x86/kvm/vmx/tdx.c +0 -0
 	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
 	kvm->max_vcpus = 0;
 
arch/x86/kvm/vmx/vmx.c +26 -0
index e129ee663498..88e893fdffe8 100644
@@ -141,6 +141,8 @@ module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
 extern bool __read_mostly allow_smaller_maxphyaddr;
 module_param(allow_smaller_maxphyaddr, bool, S_IRUGO);
 
+u64 __ro_after_init vmx_shadow_mmio_mask;
+
 #define KVM_VM_CR0_ALWAYS_OFF (X86_CR0_NW | X86_CR0_CD)
 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
 #define KVM_VM_CR0_ALWAYS_ON				\
@@ -7359,6 +7361,17 @@ int vmx_vm_init(struct kvm *kvm)
 	if (!ple_gap)
 		kvm->arch.pause_in_guest = true;
 
+	/*
+	 * EPT Misconfigurations can be generated if the value of bits 2:0
+	 * of an EPT paging-structure entry is 110b (write/execute).
+	 */
+	if (enable_ept)
+		kvm_mmu_set_mmio_spte_mask(kvm, VMX_EPT_MISCONFIG_WX_VALUE,
+					   VMX_EPT_RWX_MASK);
+	else
+		kvm_mmu_set_mmio_spte_mask(kvm, vmx_shadow_mmio_mask,
+					   vmx_shadow_mmio_mask);
+
 	if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
 		switch (l1tf_mitigation) {
 		case L1TF_MITIGATION_OFF:
@@ -8358,6 +8371,19 @@ int __init vmx_init(void)
 	if (!enable_ept)
 		allow_smaller_maxphyaddr = true;
 
+	/*
+	 * Set a reserved PA bit in MMIO SPTEs to generate page faults with
+	 * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
+	 * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
+	 * 52-bit physical addresses then there are no reserved PA bits in the
+	 * PTEs and so the reserved PA approach must be disabled.
+	 */
+	if (kvm_get_shadow_phys_bits() < 52)
+		vmx_shadow_mmio_mask = BIT_ULL(51) | PT_PRESENT_MASK;
+	else
+		vmx_shadow_mmio_mask = 0;
+	kvm_mmu_set_mmio_access_mask(0);
+
 	return 0;
 }
 
arch/x86/kvm/vmx/x86_ops.h +1 -0
index 7e38c7b756d4..279e5360c555 100644
@@ -13,6 +13,7 @@ void hv_vp_assist_page_exit(void);
 void __init vmx_init_early(void);
 int __init vmx_init(void);
 void vmx_exit(void);
+extern u64 __ro_after_init vmx_shadow_mmio_mask;
 
 __init int vmx_cpu_has_kvm_support(void);
 __init int vmx_disabled_by_bios(void);
Signature · 1 line
2.25.1
#114 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Isaku Yamahata
Quoted 15 lines · Isaku Yamahata
Quoted 12 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

Quoted 9 lines
Quoted 2 lines

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

https://lore.kernel.org/lkml/[email protected]/

Quoted 1 line

OK. But can we assume a normal guest won't sending #VE IPI?

#214 lore raw
In reply to Sean Christopherson

On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...

Quoted 4 lines

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

Quoted 8 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

Hi Sean,

Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259

Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.

Any feedback is welcome.

Thanks,
Chao

-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory

Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.

Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.

---
 arch/x86/include/asm/kvm_host.h |   8 +++
 arch/x86/kvm/mmu/mmu.c          | 120 +++++++++++++++++++++++++++++++-
 include/linux/kvm_host.h        |  14 ++++
 virt/kvm/kvm_main.c             |  12 +++-
 4 files changed, 150 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +8 -0
index d460b8511041..b6ffe8b1c547 100644
@@ -38,6 +38,7 @@
 
 #define __KVM_HAVE_ARCH_VCPU_DEBUGFS
 #define __KVM_HAVE_ZAP_GFN_RANGE
+#define __KVM_HAVE_ARCH_UPDATE_MEM_ATTR
 
 #define KVM_MAX_VCPUS 1024
 
@@ -935,6 +936,13 @@ struct kvm_vcpu_arch {
 #endif
 };
 
+/*
+ * Use a bit in disallow_lpage to indicate private/shared pages mixed at the
+ * level. The remaining bits will be used as a reference count for other users.
+ */
+#define KVM_LPAGE_PRIVATE_SHARED_MIXED		(1U << 31)
+#define KVM_LPAGE_COUNT_MAX 			((1U << 31) - 1)
+
 struct kvm_lpage_info {
 	int disallow_lpage;
 };
arch/x86/kvm/mmu/mmu.c +119 -1

133 lines not on this page · raw message

include/linux/kvm_host.h +14 -0
index d45f00f5b3ee..7b18fcd71df5 100644
@@ -2282,6 +2282,10 @@ static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu)
 #define  KVM_DIRTY_RING_MAX_ENTRIES  65536
 
 #ifdef CONFIG_HAVE_KVM_PRIVATE_MEM
+
+#define KVM_MEM_ATTR_SHARED	0x0001
+#define KVM_MEM_ATTR_PRIVATE	0x0002
+
 static inline int kvm_private_mem_get_pfn(struct kvm_memory_slot *slot,
 					  gfn_t gfn, kvm_pfn_t *pfn, int *order)
 {
@@ -2307,6 +2311,16 @@ static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
 	return !!xa_load(&kvm->mem_attr_array, gfn);
 }
 
+#ifdef __KVM_HAVE_ARCH_UPDATE_MEM_ATTR
+void kvm_arch_update_mem_attr(struct kvm *kvm, unsigned int attr,
+			      gfn_t start, gfn_t end);
+#else
+static inline void kvm_arch_update_mem_attr(struct kvm *kvm, unsigned int attr,
+					    gfn_t start, gfn_t end)
+{
+}
+#endif
+
 #endif /* CONFIG_HAVE_KVM_PRIVATE_MEM */
 
 #endif
virt/kvm/kvm_main.c +9 -3
index 1ba4b9e5449c..1d22c8603f91 100644
@@ -863,12 +863,12 @@ static int kvm_init_mmu_notifier(struct kvm *kvm)
 #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
 
 #ifdef CONFIG_HAVE_KVM_PRIVATE_MEM
-#define KVM_MEM_ATTR_PRIVATE	0x0001
 static int kvm_vm_ioctl_set_encrypted_region(struct kvm *kvm, unsigned int ioctl,
 					     struct kvm_enc_region *region)
 {
 	unsigned long start, end;
 	void *entry;
+	int attr;
 	int r;
 
 	if (region->size == 0 || region->addr + region->size < region->addr)
@@ -879,13 +879,19 @@ static int kvm_vm_ioctl_set_encrypted_region(struct kvm *kvm, unsigned int ioctl
 	start = region->addr >> PAGE_SHIFT;
 	end = (region->addr + region->size - 1) >> PAGE_SHIFT;
 
-	entry = ioctl == KVM_MEMORY_ENCRYPT_REG_REGION ?
-				xa_mk_value(KVM_MEM_ATTR_PRIVATE) : NULL;
+	if (ioctl == KVM_MEMORY_ENCRYPT_REG_REGION) {
+		attr = KVM_MEM_ATTR_PRIVATE;
+		entry = xa_mk_value(KVM_MEM_ATTR_PRIVATE);
+	} else {
+		attr = KVM_MEM_ATTR_SHARED;
+		entry = NULL;
+	}
 
 	r = xa_err(xa_store_range(&kvm->mem_attr_array, start, end,
 					entry, GFP_KERNEL_ACCOUNT));
 
 	kvm_zap_gfn_range(kvm, start, end + 1);
+	kvm_arch_update_mem_attr(kvm, attr, start, end + 1);
 
 	return r;
 }
Signature · 1 line
2
#215 lore raw
Quoted 62 lines · Chao Peng

On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...

Quoted 4 lines

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

Quoted 8 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

Hi Sean,

Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259

Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.

Any feedback is welcome.

Thanks,
Chao

-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory

Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.

Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.

---

arch/x86/kvm/mmu/mmu.c +19 -0
+static void update_mem_lpage_info(struct kvm *kvm,
+				  struct kvm_memory_slot *slot,
+				  unsigned int attr,
+				  gfn_t start, gfn_t end)
+{
+	unsigned long lpage_start, lpage_end;
+	unsigned long gfn, pages, mask;
+	int level;
+
+	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
+		pages = KVM_PAGES_PER_HPAGE(level);
+		mask = ~(pages - 1);
+		lpage_start = start & mask;
+		lpage_end = end & mask;
+
+		/*
+		 * We only need to scan the head and tail page, for middle pages
+		 * we know they are not mixed.
+		 */

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+		update_mixed(lpage_info_slot(lpage_start, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_start,
+							  lpage_start + pages));
+
+		if (lpage_start == lpage_end)
+			return;
+
+		for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) {
+			update_mixed(lpage_info_slot(gfn, slot, level), false);
+		}

Boundary check missing here for the case when gfn reaches lpage_end.

		if (gfn == lpage_end)
			return;

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7340

Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+
+		update_mixed(lpage_info_slot(lpage_end, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_end,
+							  lpage_end + pages));
+	}
+}

Regards
Nikunj

#216 lore raw
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng

On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...

Quoted 4 lines

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

Quoted 8 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

Hi Sean,

Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259

Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.

Any feedback is welcome.

Thanks,
Chao

-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory

Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.

Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.

---

arch/x86/kvm/mmu/mmu.c +19 -0
+static void update_mem_lpage_info(struct kvm *kvm,
+				  struct kvm_memory_slot *slot,
+				  unsigned int attr,
+				  gfn_t start, gfn_t end)
+{
+	unsigned long lpage_start, lpage_end;
+	unsigned long gfn, pages, mask;
+	int level;
+
+	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
+		pages = KVM_PAGES_PER_HPAGE(level);
+		mask = ~(pages - 1);
+		lpage_start = start & mask;
+		lpage_end = end & mask;
+
+		/*
+		 * We only need to scan the head and tail page, for middle pages
+		 * we know they are not mixed.
+		 */

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+		update_mixed(lpage_info_slot(lpage_start, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_start,
+							  lpage_start + pages));
+
+		if (lpage_start == lpage_end)
+			return;
+
+		for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) {
+			update_mixed(lpage_info_slot(gfn, slot, level), false);
+		}

Boundary check missing here for the case when gfn reaches lpage_end.

Quoted 2 lines
		if (gfn == lpage_end)
			return;

In this case, it's actually the tail page that I want to scan for with below code.

It's also possible I misunderstand something here.

Chao

Quoted 10 lines

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7340

Quoted 7 lines
arch/x86/kvm/mmu/mmu.c +6 -0
+
+		update_mixed(lpage_info_slot(lpage_end, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_end,
+							  lpage_end + pages));
+	}
+}

Regards
Nikunj

#135 lore raw

Re: [PATCH v7 046/102] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Kai Huang
Quoted 38 lines · Kai Huang
Quoted 38 lines
(quoted diff) +24 -0
+static int kvm_faultin_pfn_private_mapped(struct kvm_vcpu *vcpu,
+					   struct kvm_page_fault *fault)
+{
+	hva_t hva = gfn_to_hva_memslot(fault->slot, fault->gfn);
+	struct page *page[1];
+
+	fault->map_writable = false;
+	fault->pfn = KVM_PFN_ERR_FAULT;
+	if (hva == KVM_HVA_ERR_RO_BAD || hva == KVM_HVA_ERR_BAD)
+		return RET_PF_CONTINUE;
+
+	/* TDX allows only RWX.  Read-only isn't supported. */
+	WARN_ON_ONCE(!fault->write);
+	if (pin_user_pages_fast(hva, 1, FOLL_WRITE, page) != 1)
+		return RET_PF_INVALID;
+
+	fault->map_writable = true;
+	fault->pfn = page_to_pfn(page[0]);
+	return RET_PF_CONTINUE;
+}
+
 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 	struct kvm_memory_slot *slot = fault->slot;
@@ -4058,6 +4094,9 @@ static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 			return RET_PF_EMULATE;
 	}
 
+	if (fault->is_private)
+		return kvm_faultin_pfn_private_mapped(vcpu, fault);
+
 	async = false;
 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, &async,
 					  fault->write, &fault->map_writable,
@@ -4110,6 +4149,17 @@ static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
 	       mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, fault->hva);
 }
 
Quoted 12 lines

Review static bool is_page_fault_stale(struct kvm_vcpu *vcpu, · line 4161

Quoted 10 lines
(quoted diff) +10 -0
+void kvm_mmu_release_fault(struct kvm *kvm, struct kvm_page_fault *fault, int r)
+{
+	if (is_error_noslot_pfn(fault->pfn) || kvm_is_reserved_pfn(fault->pfn))
+		return;
+
+	if (fault->is_private)
+		put_page(pfn_to_page(fault->pfn));
+	else
+		kvm_release_pfn_clean(fault->pfn);
+}

What's the purpose of 'int r'? Is it even used?

removed r because r is unused.

Quoted 7 lines
Quoted 7 lines
(quoted diff) +0 -0
 static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 	bool is_tdp_mmu_fault = is_tdp_mmu(vcpu->arch.mmu);
@@ -4117,7 +4167,7 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	unsigned long mmu_seq;
 	int r;
 
Quoted 5 lines

Review static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault · line 4171

Quoted 3 lines
(quoted diff) +1 -1
-	fault->gfn = fault->addr >> PAGE_SHIFT;
+	fault->gfn = gpa_to_gfn(fault->addr) & ~kvm_gfn_shared_mask(vcpu->kvm);
 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);

Where is fault->is_private set? Shouldn't it be set here?

kvm_mmu_do_page_fault() does it and no because is_private is constant. is_private is input. On the other hand gfn and slot is working variables.

Quoted 17 lines

Review void kvm_mmu_slot_remove_write_access(struct kvm *kvm, · line 6086

Quoted 12 lines
(quoted diff) +0 -0
 	}
 
(quoted diff) +5 -0
 	if (flush)
@@ -6023,6 +6079,11 @@ void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
 		write_unlock(&kvm->mmu_lock);
 	}
 
+	/*
+	 * For now this can only happen for non-TD VM, because TD private
+	 * mapping doesn't support write protection.  kvm_tdp_mmu_wrprot_slot()
+	 * will give a WARN() if it hits for TD.
+	 */

Unless I am mistaken, 'kvm_tdp_mmu_wrprot_slot() will give a WARN() if it hits for TD" is done in your later patch "KVM: x86/tdp_mmu: Ignore unsupported mmu operation on private GFNs". Why putting comment here?

Quoted 5 lines

Please move this comment to that patch, and I think you can put that patch before this patch.

And this problem happens repeatedly in this series. Could you check the entire series?

Split out those stuff into a patch.

Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/mmu/mmu_internal.h +2 -0
index 9f3a6bea60a3..d3b30d62aca0 100644
@@ -6,6 +6,8 @@
 #include <linux/kvm_host.h>
 #include <asm/kvm_host.h>
 
+#include "mmu.h"
+
 #undef MMU_DEBUG
 
 #ifdef MMU_DEBUG
@@ -164,11 +166,30 @@ static inline void kvm_mmu_alloc_private_sp(
 	WARN_ON_ONCE(!sp->private_sp);
 }
 
Quoted 11 lines

arch/x86/kvm/mmu/mmu_internal.h static inline void kvm_mmu_alloc_private_sp( · line 177

Quoted 9 lines
arch/x86/kvm/mmu/mmu_internal.h +9 -0
+static inline int kvm_alloc_private_sp_for_split(
+	struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	gfp &= ~__GFP_ZERO;
+	sp->private_sp = (void*)__get_free_page(gfp);
+	if (!sp->private_sp)
+		return -ENOMEM;
+	return 0;
+}

What does "for_split" mean? Why do we need it?

Split large page into smaller sized one. Followed tdp_mmu_alloc_sp_for_split(). We can defer to introduce this function until large page support.

Quoted 50 lines
Quoted 50 lines
arch/x86/kvm/mmu/mmu_internal.h +25 -0
+
 static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
 {
 	if (sp->private_sp != KVM_MMU_PRIVATE_SP_ROOT)
 		free_page((unsigned long)sp->private_sp);
 }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	if (is_private_sp(root))
+		return kvm_gfn_private(kvm, gfn);
+	else
+		return kvm_gfn_shared(kvm, gfn);
+}
 #else
 static inline bool is_private_sp(struct kvm_mmu_page *sp)
 {
@@ -194,11 +215,25 @@ static inline void kvm_mmu_alloc_private_sp(
 {
 }
 
+static inline int kvm_alloc_private_sp_for_split(
+	struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	return -ENOMEM;
+}
+
 static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
 {
 }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	return gfn;
+}
 #endif
 
+void kvm_mmu_release_fault(struct kvm *kvm, struct kvm_page_fault *fault, int r);
+
 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
 	/*
@@ -246,6 +281,7 @@ struct kvm_page_fault {
 	/* Derived from mmu and global state.  */
 	const bool is_tdp;
 	const bool nx_huge_page_workaround_enabled;
+	const bool is_private;
 
Quoted 9 lines

arch/x86/kvm/mmu/mmu_internal.h static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, · line 366

Quoted 7 lines
arch/x86/kvm/mmu/mmu_internal.h +1 -0
 	/*
 	 * Whether a >4KB mapping can be created or is forbidden due to NX
@@ -327,6 +363,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 		.prefetch = prefetch,
 		.is_tdp = likely(vcpu->arch.mmu->page_fault == kvm_tdp_page_fault),
 		.nx_huge_page_workaround_enabled = is_nx_huge_page_enabled(),
+		.is_private = kvm_is_private_gpa(vcpu->kvm, cr2_or_gpa),

I guess putting this chunk and setting up fault->gfn together would be clearer?

is_private is input for kvm page fault. gfn is working variable to resolve kvm page fault.

Quoted 13 lines
Quoted 13 lines
arch/x86/kvm/mmu/mmu_internal.h +2 -2
 static void handle_changed_spte(struct kvm *kvm, int as_id, gfn_t gfn,
-				u64 old_spte, u64 new_spte, int level,
-				bool shared)
+				bool private_spte, u64 old_spte, u64 new_spte,
+				int level, bool shared)

{

arch/x86/kvm/mmu/mmu_internal.h +2 -2
-	__handle_changed_spte(kvm, as_id, gfn, old_spte, new_spte, level,
-			      shared);
+	__handle_changed_spte(kvm, as_id, gfn, private_spte,
+			old_spte, new_spte, level, shared);
 	handle_changed_spte_acc_track(old_spte, new_spte, level);
 	handle_changed_spte_dirty_log(kvm, as_id, gfn, old_spte,
 				      new_spte, level);
Quoted 8 lines

arch/x86/kvm/mmu/mmu_internal.h static inline int tdp_mmu_set_spte_atomic(struct kvm *kvm, · line 718

Quoted 6 lines
arch/x86/kvm/mmu/mmu_internal.h +2 -0
@@ -640,6 +714,8 @@ static inline int tdp_mmu_set_spte_atomic(struct kvm *kvm,
 					  struct tdp_iter *iter,
 					  u64 new_spte)
 {
+	bool freeze_spte = iter->is_private && !is_removed_spte(new_spte);
+	u64 tmp_spte = freeze_spte ? REMOVED_SPTE : new_spte;

Perhaps I am missing something. Could you add comments to explain the logic?

Add a comment.
+ /*

+        * For conventional page table, the update flow is
+        * - update STPE with atomic operation
+        * - hanlde changed SPTE. __handle_changed_spte()
+        * NOTE: __handle_changed_spte() (and functions) must be safe against
+        * concurrent update.  It is an exception to zap SPTE.  See
+        * tdp_mmu_zap_spte_atomic().
+        *
+        * For private page table, callbacks are needed to propagate SPTE
+        * change into the protected page table.  In order to atomically update
+        * both the SPTE and the protected page tables with callbacks, utilize
+        * freezing SPTE.
+        * - Freeze the SPTE. Set entry to REMOVED_SPTE.
+        * - Trigger callbacks for protected page tables. __handle_changed_spte()
+        * - Unfreeze the SPTE.  Set the entry to new_spte.
+        */
Quoted 23 lines
Quoted 14 lines
arch/x86/kvm/mmu/mmu_internal.h +6 -0
@@ -1067,6 +1163,12 @@ void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 	list_for_each_entry(root, &kvm->arch.tdp_mmu_roots, link) {
+		/*
+		 * Skip private root since private page table
+		 * is only torn down when VM is destroyed.
+		 */
+		if (is_private_sp(root))
+			continue;
 		if (!root->role.invalid &&
 		    !WARN_ON_ONCE(!kvm_tdp_mmu_get_root(root))) {
 			root->role.invalid = true;

arch/x86/kvm/mmu/mmu_internal.h static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu, · line 1193

Quoted 5 lines
arch/x86/kvm/mmu/mmu_internal.h +2 -0
@@ -1087,14 +1189,22 @@ static int tdp_mmu_map_handle_target_level(struct kvm_vcpu *vcpu,
 	u64 new_spte;
 	int ret = RET_PF_FIXED;
 	bool wrprot = false;
+	unsigned long pte_access = ACC_ALL;
+	gfn_t gfn_unalias = iter->gfn & ~kvm_gfn_shared_mask(vcpu->kvm);

Here looks the iter->gfn still contains the shared bits. It is not consistent with above.

Quoted 4 lines

Can you put some words into the changelog explaining exactly what GFN will you put to iterator?

Or can you even split out this part as a separate patch?

I think you meant the above is zap_leafs function. It zaps GPA range module alias (module shared bit).
This function is to resolve kvm page fault. It means gpa includes shared bit.

here is the updated patch.

From ae3cee62e53a877bef04813e6ae8d710b4a9128a Mon Sep 17 00:00:00 2001
Message-Id: <ae3cee62e53a877bef04813e6ae8d710b4a9128a.1658878587.git.isaku.yamahata@intel.com>
In-Reply-To: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658878587.git.isaku.yamahata@intel.com>
References: <3941849bf08a55cfbbe69b222f0fd0dac7c5ee53.1658878587.git.isaku.yamahata@intel.com>
From: Isaku Yamahata <[email protected]>
Date: Thu, 14 Jul 2022 15:11:24 -0700
Subject: [PATCH 048/292] KVM: x86/tdp_mmu: Support TDX private mapping for TDP
MMU

Allocate protected page table for private page table, and add hooks to operate on protected page table. This patch adds allocation/free of protected page tables and hooks. When calling hooks to update SPTE entry, freeze the entry, call hooks and unfree the entry to allow concurrent updates on page tables. Which is the advantage of TDP MMU. As kvm_gfn_shared_mask() returns false always, those hooks aren't called yet with this patch.

When the faulting GPA is private, the KVM fault is called private. When resolving private KVM, allocate protected page table and call hooks to operate on protected page table. On the change of the private PTE entry, invoke kvm_x86_ops hook in __handle_changed_spte() to propagate the change to protected page table. The following depicts the relationship.

  private KVM page fault   |
      |                    |
      V                    |
 private GPA               |     CPU protected EPTP
      |                    |           |
      V                    |           V
 private PT root           |     protected PT root
      |                    |           |
      V                    |           V
   private PT --hook to propagate-->protected PT
      |                    |           |
      \--------------------+------\    |
                           |      |    |
                           |      V    V
                           |    private guest page
                           |
                           |
     non-encrypted memory  |    encrypted memory
                           |

PT: page table

The existing KVM TDP MMU code uses atomic update of SPTE. On populating the EPT entry, atomically set the entry. However, it requires TLB shootdown to zap SPTE. To address it, the entry is frozen with the special SPTE value that clears the present bit. After the TLB shootdown, the entry is set to the eventual value (unfreeze).

For protected page table, hooks are called to update protected page table in addition to direct access to the private SPTE. For the zapping case, it works to freeze the SPTE. It can call hooks in addition to TLB shootdown. For populating the private SPTE entry, there can be a race condition without further protection

vcpu 1: populating 2M private SPTE
vcpu 2: populating 4K private SPTE
vcpu 2: TDX SEAMCALL to update 4K protected SPTE => error vcpu 1: TDX SEAMCALL to update 2M protected SPTE

To avoid the race, the frozen SPTE is utilized. Instead of atomic update of the private entry, freeze the entry, call the hook that update protected SPTE, set the entry to the final value.

Support 4K page only at this stage. 2M page support can be done in future patches.

Add is_private member to kvm_page_fault to indicate the fault is private. Also is_private member to struct tdp_inter to propagate it.

---
 arch/x86/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |  20 +++
 arch/x86/kvm/mmu/mmu.c             |  15 +-
 arch/x86/kvm/mmu/mmu_internal.h    |  35 +++++
 arch/x86/kvm/mmu/tdp_iter.h        |   2 +-
 arch/x86/kvm/mmu/tdp_mmu.c         | 215 ++++++++++++++++++++++++-----
 arch/x86/kvm/mmu/tdp_mmu.h         |   2 +-
 virt/kvm/kvm_main.c                |   1 +
 8 files changed, 254 insertions(+), 38 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 32a6df784ea6..6982d57e4518 100644
@@ -93,6 +93,8 @@ KVM_X86_OP_OPTIONAL_RET0(set_tss_addr)
 KVM_X86_OP_OPTIONAL_RET0(set_identity_map_addr)
 KVM_X86_OP(get_mt_mask)
 KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP_OPTIONAL(free_private_sp)
+KVM_X86_OP_OPTIONAL(handle_changed_private_spte)
 KVM_X86_OP(has_wbinvd_exit)
 KVM_X86_OP(get_l2_tsc_offset)
 KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +20 -0
index a73050a69aab..23a4d9d06772 100644
@@ -467,6 +467,7 @@ struct kvm_mmu {
 			 struct kvm_mmu_page *sp);
 	void (*invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa);
 	struct kvm_mmu_root_info root;
+	hpa_t private_root_hpa;
 	union kvm_cpu_role cpu_role;
 	union kvm_mmu_page_role root_role;
 
@@ -1462,6 +1463,20 @@ static inline u16 kvm_lapic_irq_dest_mode(bool dest_mode_logical)
 	return dest_mode_logical ? APIC_DEST_LOGICAL : APIC_DEST_PHYSICAL;
 }
 
+struct kvm_spte {
+	kvm_pfn_t pfn;
+	bool is_present;
+	bool is_leaf;
+};
+
+struct kvm_spte_change {
+	gfn_t gfn;
+	enum pg_level level;
+	struct kvm_spte old;
+	struct kvm_spte new;
+	void *sept_page;
+};
+
 struct kvm_x86_ops {
 	const char *name;
 
@@ -1574,6 +1589,11 @@ struct kvm_x86_ops {
 	void (*load_mmu_pgd)(struct kvm_vcpu *vcpu, hpa_t root_hpa,
 			     int root_level);
 
+	int (*free_private_sp)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+			       void *private_sp);
+	void (*handle_changed_private_spte)(
+		struct kvm *kvm, const struct kvm_spte_change *change);
+
 	bool (*has_wbinvd_exit)(void);
 
 	u64 (*get_l2_tsc_offset)(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/mmu.c +11 -2
index 37ae04ef0719..98138e688c59 100644
@@ -3465,7 +3465,12 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
 		goto out_unlock;
 
 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
-		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
+		if (kvm_gfn_shared_mask(vcpu->kvm) &&
+		    !VALID_PAGE(mmu->private_root_hpa)) {
+			root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, true);
+			mmu->private_root_hpa = root;
+		}
+		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, false);
 		mmu->root.hpa = root;
 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
@@ -4128,7 +4133,7 @@ static int direct_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 	unsigned long mmu_seq;
 	int r;
 
-	fault->gfn = fault->addr >> PAGE_SHIFT;
+	fault->gfn = gpa_to_gfn(fault->addr) & ~kvm_gfn_shared_mask(vcpu->kvm);
 	fault->slot = kvm_vcpu_gfn_to_memslot(vcpu, fault->gfn);
 
 	if (page_fault_handle_page_track(vcpu, fault))
@@ -5669,6 +5674,7 @@ static int __kvm_mmu_create(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
 
 	mmu->root.hpa = INVALID_PAGE;
 	mmu->root.pgd = 0;
+	mmu->private_root_hpa = INVALID_PAGE;
 	for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
 		mmu->prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
 
@@ -6467,6 +6473,9 @@ int kvm_mmu_vendor_module_init(void)
 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_unload(vcpu);
+	if (is_tdp_mmu_enabled(vcpu->kvm))
+		mmu_free_root_page(vcpu->kvm, &vcpu->arch.mmu->private_root_hpa,
+				NULL);
 	free_mmu_pages(&vcpu->arch.root_mmu);
 	free_mmu_pages(&vcpu->arch.guest_mmu);
 	mmu_free_memory_caches(vcpu);
arch/x86/kvm/mmu/mmu_internal.h +35 -0
index 29904f8d8719..6c529c804875 100644
@@ -6,6 +6,8 @@
 #include <linux/kvm_host.h>
 #include <asm/kvm_host.h>
 
+#include "mmu.h"
+
 #undef MMU_DEBUG
 
 #ifdef MMU_DEBUG
@@ -163,11 +165,30 @@ static inline void kvm_mmu_alloc_private_sp(
 	}
 }
 
+static inline int kvm_alloc_private_sp_for_split(
+	struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	gfp &= ~__GFP_ZERO;
+	sp->private_sp = (void*)__get_free_page(gfp);
+	if (!sp->private_sp)
+		return -ENOMEM;
+	return 0;
+}
+
 static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
 {
 	if (sp->private_sp)
 		free_page((unsigned long)sp->private_sp);
 }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	if (is_private_sp(root))
+		return kvm_gfn_private(kvm, gfn);
+	else
+		return kvm_gfn_shared(kvm, gfn);
+}
 #else
 static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
 {
@@ -183,9 +204,21 @@ static inline void kvm_mmu_alloc_private_sp(
 {
 }
 
+static inline int kvm_alloc_private_sp_for_split(
+	struct kvm_mmu_page *sp, gfp_t gfp)
+{
+	return -ENOMEM;
+}
+
 static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
 {
 }
+
+static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct kvm_mmu_page *root,
+				     gfn_t gfn)
+{
+	return gfn;
+}
 #endif
 
 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
@@ -235,6 +268,7 @@ struct kvm_page_fault {
 	/* Derived from mmu and global state.  */
 	const bool is_tdp;
 	const bool nx_huge_page_workaround_enabled;
+	const bool is_private;
 
 	/*
 	 * Whether a >4KB mapping can be created or is forbidden due to NX
@@ -316,6 +350,7 @@ static inline int kvm_mmu_do_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
 		.prefetch = prefetch,
 		.is_tdp = likely(vcpu->arch.mmu->page_fault == kvm_tdp_page_fault),
 		.nx_huge_page_workaround_enabled = is_nx_huge_page_enabled(),
+		.is_private = kvm_is_private_gpa(vcpu->kvm, cr2_or_gpa),
 
 		.max_level = vcpu->kvm->arch.tdp_max_page_level,
 		.req_level = PG_LEVEL_4K,
arch/x86/kvm/mmu/tdp_iter.h +1 -1
index e25992df5bba..20422eeba6aa 100644
@@ -71,7 +71,7 @@ struct tdp_iter {
 	tdp_ptep_t pt_path[PT64_ROOT_MAX_LEVEL];
 	/* A pointer to the current SPTE */
 	tdp_ptep_t sptep;
-	/* The lowest GFN mapped by the current SPTE */
+	/* The lowest GFN (shared bits included) mapped by the current SPTE */
 	gfn_t gfn;
 	/* The level of the root page given to the iterator */
 	int root_level;
arch/x86/kvm/mmu/tdp_mmu.c +182 -33

386 lines not on this page · raw message

arch/x86/kvm/mmu/tdp_mmu.h +1 -1
index c98c7df449a8..695175c921a5 100644
@@ -5,7 +5,7 @@
 
 #include <linux/kvm_host.h>
 
-hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu);
+hpa_t kvm_tdp_mmu_get_vcpu_root_hpa(struct kvm_vcpu *vcpu, bool private);
 
 __must_check static inline bool kvm_tdp_mmu_get_root(struct kvm_mmu_page *root)
 {
virt/kvm/kvm_main.c +1 -0
index 0acb0b6d1f82..7a5261eb7eb8 100644
@@ -196,6 +196,7 @@ bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
 
 	return true;
 }
+EXPORT_SYMBOL_GPL(kvm_is_reserved_pfn);
 
 /*
  * Switches to specified vcpu, until a matching vcpu_put()
Signature · 7 lines
2.25.1




-- 
Isaku Yamahata <[email protected]>
#137 lore raw

Re: [PATCH v7 046/102] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Yuan Yao
Quoted 227 lines · Yuan Yao
Quoted 226 lines · On Mon, Jun 27, 2022 at 02:53:38PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Allocate mirrored private page table for private page table, and add hooks to operate on mirrored private page table. This patch adds only hooks. As kvm_gfn_shared_mask() returns false always, those hooks aren't called yet.

Because private guest page is protected, page copy with mmu_notifier to migrate page doesn't work. Callback from backing store is needed.

When the faulting GPA is private, the KVM fault is also called private. When resolving private KVM, allocate mirrored private page table and call hooks to operate on mirrored private page table. On the change of the private PTE entry, invoke kvm_x86_ops hook in __handle_changed_spte() to propagate the change to mirrored private page table. The following depicts the relationship.

  private KVM page fault   |
      |                    |
      V                    |
 private GPA               |
      |                    |
      V                    |
 KVM private PT root       |  CPU private PT root
      |                    |           |
      V                    |           V
   private PT ---hook to mirror--->mirrored private PT
      |                    |           |
      \--------------------+------\    |
                           |      |    |
                           |      V    V
                           |    private guest page
                           |
                           |
     non-encrypted memory  |    encrypted memory
                           |

PT: page table

The existing KVM TDP MMU code uses atomic update of SPTE. On populating the EPT entry, atomically set the entry. However, it requires TLB shootdown to zap SPTE. To address it, the entry is frozen with the special SPTE value that clears the present bit. After the TLB shootdown, the entry is set to the eventual value (unfreeze).

For mirrored private page table, hooks are called to update mirrored private page table in addition to direct access to the private SPTE. For the zapping case, it works to freeze the SPTE. It can call hooks in addition to TLB shootdown. For populating the private SPTE entry, there can be a race condition without further protection

vcpu 1: populating 2M private SPTE
vcpu 2: populating 4K private SPTE
vcpu 2: TDX SEAMCALL to update 4K mirrored private SPTE => error vcpu 1: TDX SEAMCALL to update 2M mirrored private SPTE

To avoid the race, the frozen SPTE is utilized. Instead of atomic update of the private entry, freeze the entry, call the hook that update mirrored private SPTE, set the entry to the final value.

Support 4K page only at this stage. 2M page support can be done in future patches.

Add is_private member to kvm_page_fault to indicate the fault is private. Also is_private member to struct tdp_inter to propagate it.

---
 arch/x86/include/asm/kvm-x86-ops.h |   2 +
 arch/x86/include/asm/kvm_host.h    |  20 +++
 arch/x86/kvm/mmu/mmu.c             |  86 +++++++++-
 arch/x86/kvm/mmu/mmu_internal.h    |  37 +++++
 arch/x86/kvm/mmu/paging_tmpl.h     |   2 +-
 arch/x86/kvm/mmu/tdp_iter.c        |   1 +
 arch/x86/kvm/mmu/tdp_iter.h        |   5 +-
 arch/x86/kvm/mmu/tdp_mmu.c         | 247 +++++++++++++++++++++++------
 arch/x86/kvm/mmu/tdp_mmu.h         |   7 +-
 virt/kvm/kvm_main.c                |   1 +
 10 files changed, 346 insertions(+), 62 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +2 -0
index 32a6df784ea6..6982d57e4518 100644
@@ -93,6 +93,8 @@ KVM_X86_OP_OPTIONAL_RET0(set_tss_addr)
 KVM_X86_OP_OPTIONAL_RET0(set_identity_map_addr)
 KVM_X86_OP(get_mt_mask)
 KVM_X86_OP(load_mmu_pgd)
+KVM_X86_OP_OPTIONAL(free_private_sp)
+KVM_X86_OP_OPTIONAL(handle_changed_private_spte)
 KVM_X86_OP(has_wbinvd_exit)
 KVM_X86_OP(get_l2_tsc_offset)
 KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +20 -0
index bfc934dc9a33..f2a4d5a18851 100644
@@ -440,6 +440,7 @@ struct kvm_mmu {
 			 struct kvm_mmu_page *sp);
 	void (*invlpg)(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root_hpa);
 	struct kvm_mmu_root_info root;
+	hpa_t private_root_hpa;
 	union kvm_cpu_role cpu_role;
 	union kvm_mmu_page_role root_role;
 
@@ -1435,6 +1436,20 @@ static inline u16 kvm_lapic_irq_dest_mode(bool dest_mode_logical)
 	return dest_mode_logical ? APIC_DEST_LOGICAL : APIC_DEST_PHYSICAL;
 }
 
+struct kvm_spte {
+	kvm_pfn_t pfn;
+	bool is_present;
+	bool is_leaf;
+};
+
+struct kvm_spte_change {
+	gfn_t gfn;
+	enum pg_level level;
+	struct kvm_spte old;
+	struct kvm_spte new;
+	void *sept_page;
+};
+
 struct kvm_x86_ops {
 	const char *name;
 
@@ -1547,6 +1562,11 @@ struct kvm_x86_ops {
 	void (*load_mmu_pgd)(struct kvm_vcpu *vcpu, hpa_t root_hpa,
 			     int root_level);
 
+	int (*free_private_sp)(struct kvm *kvm, gfn_t gfn, enum pg_level level,
+			       void *private_sp);
+	void (*handle_changed_private_spte)(
+		struct kvm *kvm, const struct kvm_spte_change *change);
+
 	bool (*has_wbinvd_exit)(void);
 
 	u64 (*get_l2_tsc_offset)(struct kvm_vcpu *vcpu);
arch/x86/kvm/mmu/mmu.c +42 -3
index a5bf3e40e209..ef925722ee28 100644
@@ -1577,7 +1577,11 @@ bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
 		flush = kvm_handle_gfn_range(kvm, range, kvm_unmap_rmapp);
 
 	if (is_tdp_mmu_enabled(kvm))
-		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush);
+		/*
+		 * private page needs to be kept and handle page migration
+		 * on next EPT violation.
+		 */
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, range, flush, false);
 
 	return flush;
 }
@@ -3082,7 +3086,8 @@ static int handle_abnormal_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fau
 		 * SPTE value without #VE suppress bit cleared
 		 * (kvm->arch.shadow_mmio_value = 0).
 		 */
-		if (unlikely(!vcpu->kvm->arch.enable_mmio_caching) ||
+		if (unlikely(!vcpu->kvm->arch.enable_mmio_caching &&
+			     !kvm_gfn_shared_mask(vcpu->kvm)) ||
 		    unlikely(fault->gfn > kvm_mmu_max_gfn()))
 			return RET_PF_EMULATE;
 	}
@@ -3454,7 +3459,12 @@ static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
 		goto out_unlock;
 
 	if (is_tdp_mmu_enabled(vcpu->kvm)) {
-		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu);
+		if (kvm_gfn_shared_mask(vcpu->kvm) &&
+		    !VALID_PAGE(mmu->private_root_hpa)) {
+			root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, true);
+			mmu->private_root_hpa = root;
+		}
+		root = kvm_tdp_mmu_get_vcpu_root_hpa(vcpu, false);
 		mmu->root.hpa = root;
 	} else if (shadow_root_level >= PT64_ROOT_4LEVEL) {
 		root = mmu_alloc_root(vcpu, 0, 0, shadow_root_level, true);
@@ -4026,6 +4036,32 @@ void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
 	kvm_mmu_do_page_fault(vcpu, work->cr2_or_gpa, 0, true);
 }
 
+/*
+ * Private page can't be release on mmu_notifier without losing page contents.
+ * The help, callback, from backing store is needed to allow page migration.
+ * For now, pin the page.
+ */
+static int kvm_faultin_pfn_private_mapped(struct kvm_vcpu *vcpu,
+					   struct kvm_page_fault *fault)
+{
+	hva_t hva = gfn_to_hva_memslot(fault->slot, fault->gfn);
+	struct page *page[1];
+
+	fault->map_writable = false;
+	fault->pfn = KVM_PFN_ERR_FAULT;
+	if (hva == KVM_HVA_ERR_RO_BAD || hva == KVM_HVA_ERR_BAD)
+		return RET_PF_CONTINUE;
+
+	/* TDX allows only RWX.  Read-only isn't supported. */
+	WARN_ON_ONCE(!fault->write);
+	if (pin_user_pages_fast(hva, 1, FOLL_WRITE, page) != 1)
+		return RET_PF_INVALID;
+
+	fault->map_writable = true;
+	fault->pfn = page_to_pfn(page[0]);
+	return RET_PF_CONTINUE;
+}
+
 static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 {
 	struct kvm_memory_slot *slot = fault->slot;
@@ -4058,6 +4094,9 @@ static int kvm_faultin_pfn(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 			return RET_PF_EMULATE;
 	}
 
+	if (fault->is_private)
+		return kvm_faultin_pfn_private_mapped(vcpu, fault);
+
 	async = false;
 	fault->pfn = __gfn_to_pfn_memslot(slot, fault->gfn, false, &async,
 					  fault->write, &fault->map_writable,
@@ -4110,6 +4149,17 @@ static bool is_page_fault_stale(struct kvm_vcpu *vcpu,
 	       mmu_notifier_retry_hva(vcpu->kvm, mmu_seq, fault->hva);
 }
 
Quoted 13 lines

arch/x86/kvm/mmu/mmu.c static bool is_page_fault_stale(struct kvm_vcpu *vcpu, · line 4158

Quoted 7 lines
arch/x86/kvm/mmu/mmu.c +7 -0
+void kvm_mmu_release_fault(struct kvm *kvm, struct kvm_page_fault *fault, int r)
+{
+	if (is_error_noslot_pfn(fault->pfn) || kvm_is_reserved_pfn(fault->pfn))
+		return;
+
+	if (fault->is_private)
+		put_page(pfn_to_page(fault->pfn));

The pin_user_pages_fast() is used above which has FOLL_PIN set internal, so should we use unpin_user_page() here ? The FOLL_PIN means the unpin should be done by unpin_user_page() but not put_page, please see /Documentation/core-api/pin_user_pages.rst and comments on FOLL_PIN;

To align with large page support, I'll make it to use get_user_pages_fast() and put_page().

Signature · 1 line
Isaku Yamahata <[email protected]>
#139 lore raw

Re: [PATCH v7 046/102] KVM: x86/tdp_mmu: Support TDX private mapping for TDP MMU

In reply to Yuan Yao
Quoted 6 lines · Yuan Yao
Quoted 6 lines
arch/x86/kvm/mmu/paging_tmpl.h +0 -0
index 62ae590d4e5b..e5b73638bd83 100644
@@ -877,7 +877,7 @@ static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault
 
Quoted 6 lines

arch/x86/kvm/mmu/paging_tmpl.h static int FNAME(page_fault)(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault · line 880

Quoted 4 lines
arch/x86/kvm/mmu/paging_tmpl.h +1 -1
 out_unlock:
 	write_unlock(&vcpu->kvm->mmu_lock);
-	kvm_release_pfn_clean(fault->pfn);
+	kvm_mmu_release_fault(vcpu->kvm, fault, r);

Do we really need this? Shadow page table is not supported for TD guest.

For consistency. pair of kvm_faultin_pfn() and kvm_mmu_release_fault().

Signature · 1 line
Isaku Yamahata <[email protected]>
#4 lore raw

Re: [PATCH v7 002/102] Partially revert "KVM: Pass kvm_init()'s opaque param to additional arch funcs"

In reply to Kai Huang
Quoted 17 lines · Kai Huang
Quoted 10 lines · On Mon, 2022-06-27 at 14:52 -0700, [email protected] wrote:

From: Chao Gao <[email protected]>

This partially reverts commit b99040853738 ("KVM: Pass kvm_init()'s opaque param to additional arch funcs") remove opaque from kvm_arch_check_processor_compat because no one uses this opaque now. Address conflicts for ARM (due to file movement) and manually handle RISC-V which comes after the commit.

And changes about kvm_arch_hardware_setup() in original commit are still needed so they are not reverted.

I tried to dig the history to find out why we are doing this.

IMHO it's better to give a reason why you need to revert the opaque. I guess no one uses this opaque now doesn't mean we need to remove it?

Quoted 6 lines

Perhaps you should mention this is a preparation to hardware_enable_all()/hardware_disable_all() during module loading time. Instead of extending hardware_enable_all()/hardware_disable_all() to take the opaque and pass to kvm_arch_check_process_compat(), just remove the opaque.

Or perhaps just merge this patch to next one?

Here is the updated commit message.

Partially revert "KVM: Pass kvm_init()'s opaque param to additional arch funcs"

This partially reverts commit b99040853738 ("KVM: Pass kvm_init()'s opaque param to additional arch funcs") remove opaque from kvm_arch_check_processor_compat because no one uses this opaque now. Address conflicts for ARM (due to file movement) and manually handle RISC-V which comes after the commit. The change about kvm_arch_hardware_setup() in original commit are still needed so they are not reverted.

The current implementation enables hardware (e.g. enable VMX on all CPUs), arch-specific initialization for VM creation, and disables hardware (in x86, disable VMX on all CPUs) for last VM destruction.

TDX requires its initialization on loading KVM module with VMX enabled on all available CPUs. It needs to enable/disable hardware on module initialization. To reuse the same logic, one way is to pass around the unused opaque argument, another way is to remove the unused opaque argument. This patch is a preparation for the latter by removing the argument.

Signature · 1 line
Isaku Yamahata <[email protected]>
#31 lore raw

Re: [PATCH v7 011/102] KVM: TDX: Initialize TDX module when loading kvm_intel.ko

In reply to Kai Huang
Quoted 4 lines · Kai Huang
Quoted 2 lines

To use TDX functionality, TDX module needs to be loaded and initialized. This patch is to call a function, tdx_init(), when loading kvm_intel.ko.

Could you add explain why we need to init TDX module when loading KVM module?

Makes sense. Added a paragraph for it.

Quoted 13 lines
Quoted 4 lines

Add a hook, kvm_arch_post_hardware_enable_setup, to module initialization while hardware is enabled, i.e. after hardware_enable_all() and before hardware_disable_all(). Because TDX requires all present CPUs to enable VMX (VMXON).

Please explicitly say it is a replacement of the default __weak version, so people can know there's already a default one. Otherwise people may wonder why this isn't called in this patch (i.e. I skipped patch 03 as it looks not directly related to TDX).

That being said, why cannot you send out that patch separately but have to include it into TDX series?

Quoted 7 lines

Looking at it, the only thing that is related to TDX is an empty kvm_arch_post_hardware_enable_setup() with a comment saying TDX needs to do something there. This logic has nothing to do with the actual job in that patch.

So why cannot we introduce that __weak version in this patch, so that the rest of it can be non-TDX related at all and can be upstreamed separately?

The patch that adds weak kvm_arch_post_hardware_enable_setup() doesn't make sense without the hook because it only enable_hardware and then disable hardware immediately.
The patch touches multiple kvm arch. and I split out TDX specific part in this patch. Ideally those two patch should be near. But I move it early to draw attention for reviewers from multiple kvm arch.

Here is the updated version.

KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

To use TDX, the TDX module needs to be loaded and initialized. This patch is to call a function to initialize the TDX module when loading KVM intel kernel module.

There are several options on when to initialize the TDX module. A.) kernel boot time as builtin, B.) kernel module loading time, C.) the first guest TD creation time. B.) was chosen. A.) causes unnecessary overhead (boot time and memory) even when TDX isn't used. With C.), a user may hit an error of the TDX initialization when trying to create the first guest TD. The machine that fails to initialize the TDX module can't boot any guest TD further. Such failure is undesirable. B.) has a good balance between them.

Add a hook, kvm_arch_post_hardware_enable_setup, to module initialization while hardware is enabled, i.e. after hardware_enable_all() and before hardware_disable_all(). Because TDX requires all present CPUs to enable VMX (VMXON). The x86 specific kvm_arch_post_hardware_enable_setup overrides the existing weak symbol of kvm_arch_post_hardware_enable_setup which is called at the KVM module initialization.

Signature · 1 line
Isaku Yamahata <[email protected]>
#22 lore raw

Re: [PATCH v7 008/102] KVM: x86: Refactor KVM VMX module init/exit functions

In reply to Kai Huang
Quoted 47 lines · Kai Huang
Quoted 46 lines · Isaku Yamahata
Quoted 42 lines · Kai Huang
Quoted 28 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Currently, KVM VMX module initialization/exit functions are a single function each. Refactor KVM VMX module initialization functions into KVM common part and VMX part so that TDX specific part can be added cleanly. Opportunistically refactor module exit function as well.

The current module initialization flow is, 1.) calculate the sizes of VMX kvm structure and VMX vcpu structure, 2.) hyper-v specific initialization 3.) report those sizes to the KVM common layer and KVM common initialization, and 4.) VMX specific system-wide initialization.

Refactor the KVM VMX module initialization function into functions with a wrapper function to separate VMX logic in vmx.c from a file, main.c, common among VMX and TDX. We have a wrapper function, "vt_init() {vmx kvm/vcpu size calculation; hv_vp_assist_page_init(); kvm_init(); vmx_init(); }" in main.c, and hv_vp_assist_page_init() and vmx_init() in vmx.c. hv_vp_assist_page_init() initializes hyper-v specific assist pages, kvm_init() does system-wide initialization of the KVM common layer, and vmx_init() does system-wide VMX initialization.

The KVM architecture common layer allocates struct kvm with reported size for architecture-specific code. The KVM VMX module defines its structure as struct vmx_kvm { struct kvm; VMX specific members;} and uses it as struct vmx kvm. Similar for vcpu structure. TDX KVM patches will define TDX specific kvm and vcpu structures, add tdx_pre_kvm_init() to report the sizes of them to the KVM common layer.

Quoted 4 lines

The current module exit function is also a single function, a combination of VMX specific logic and common KVM logic. Refactor it into VMX specific logic and KVM common logic. This is just refactoring to keep the VMX specific logic in vmx.c from main.c.

This patch, coupled with the patch:

KVM: VMX: Move out vmx_x86_ops to 'main.c' to wrap VMX and TDX

Basically provides an infrastructure to support both VMX and TDX. Why we cannot merge them into one patch? What's the benefit of splitting them?

At least, why the two patches cannot be put together closely?

Quoted 7 lines
Quoted 3 lines

It is trivial for the change of "KVM: VMX: Move out vmx_x86_ops to 'main.c' to wrap VMX and TDX" to introduce no functional change. But it's not trivial for this patch to introduce no functional change.

This doesn't sound right. If I understand correctly, this patch supposedly shouldn't bring any functional change, right? Could you explain what functional change does this patch bring?

This patch doesn't bring functional change. This patch changes orders of some function calls. It doesn't matter actually. But I think it's non-trivial.

Signature · 1 line
Isaku Yamahata <[email protected]>
#32 lore raw

Re: [PATCH v7 011/102] KVM: TDX: Initialize TDX module when loading kvm_intel.ko

In reply to Isaku Yamahata
Quoted 29 lines · Isaku Yamahata
Quoted 4 lines · Kai Huang
Quoted 2 lines

To use TDX functionality, TDX module needs to be loaded and initialized. This patch is to call a function, tdx_init(), when loading kvm_intel.ko.

Could you add explain why we need to init TDX module when loading KVM module?

Makes sense. Added a paragraph for it.

Quoted 18 lines
Quoted 4 lines

Add a hook, kvm_arch_post_hardware_enable_setup, to module initialization while hardware is enabled, i.e. after hardware_enable_all() and before hardware_disable_all(). Because TDX requires all present CPUs to enable VMX (VMXON).

Please explicitly say it is a replacement of the default __weak version, so people can know there's already a default one. Otherwise people may wonder why this isn't called in this patch (i.e. I skipped patch 03 as it looks not directly related to TDX).

That being said, why cannot you send out that patch separately but have to include it into TDX series?

Looking at it, the only thing that is related to TDX is an empty kvm_arch_post_hardware_enable_setup() with a comment saying TDX needs to do something there. This logic has nothing to do with the actual job in that patch.

Quoted 6 lines
Quoted 2 lines

So why cannot we introduce that __weak version in this patch, so that the rest of it can be non-TDX related at all and can be upstreamed separately?

The patch that adds weak kvm_arch_post_hardware_enable_setup() doesn't make sense without the hook because it only enable_hardware and then disable hardware immediately.

It's not a disaster if you describe the reason to do so in the changelog, but no strong opinion here.

But I do think you need a comment to explain why disable hardware is called immediately. Is it because we want to maintain the current behaviour that we want to allow out-of-tree driver, i.e. virtualbox to be loaded when KVM is loaded?

Quoted 3 lines

The patch touches multiple kvm arch. and I split out TDX specific part in this patch. Ideally those two patch should be near. But I move it early to draw attention for reviewers from multiple kvm arch.

Explicitly say this is the replacement of the default __weak version is fine.

Quoted 9 lines

Here is the updated version.

KVM: TDX: Initialize the TDX module when loading the KVM intel kernel module

To use TDX, the TDX module needs to be loaded and initialized. This patch is to call a function to initialize the TDX module when loading KVM intel kernel module.

Quoted 8 lines

There are several options on when to initialize the TDX module. A.) kernel boot time as builtin, B.) kernel module loading time, C.) the first guest TD creation time. B.) was chosen. A.) causes unnecessary overhead (boot time and memory) even when TDX isn't used. With C.), a user may hit an error of the TDX initialization when trying to create the first guest TD. The machine that fails to initialize the TDX module can't boot any guest TD further. Such failure is undesirable. B.) has a good balance between them.

You don't need to mention A. When this patch is merged, the host series must have been merged already. In another words, this is already a fact, but not an option.

Quoted 5 lines

Add a hook, kvm_arch_post_hardware_enable_setup, to module initialization while hardware is enabled, i.e. after hardware_enable_all() and before hardware_disable_all().

You don't need to say "add a hook ..., i.e. after hardware_enable_all() and before hardware_disable_all()". Where the function is called is already a fact. We have a __weak version already.

Quoted 5 lines

Because TDX requires all present CPUs to enable
VMX (VMXON). The x86 specific kvm_arch_post_hardware_enable_setup overrides the existing weak symbol of kvm_arch_post_hardware_enable_setup which is called at the KVM module initialization.

#217 lore raw
In reply to Chao Peng
Quoted 77 lines · Chao Peng
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng

On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...

Quoted 4 lines

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

Quoted 8 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

Hi Sean,

Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259

Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.

Any feedback is welcome.

Thanks,
Chao

-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory

Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.

Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.

---

arch/x86/kvm/mmu/mmu.c +19 -0
+static void update_mem_lpage_info(struct kvm *kvm,
+				  struct kvm_memory_slot *slot,
+				  unsigned int attr,
+				  gfn_t start, gfn_t end)
+{
+	unsigned long lpage_start, lpage_end;
+	unsigned long gfn, pages, mask;
+	int level;
+
+	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
+		pages = KVM_PAGES_PER_HPAGE(level);
+		mask = ~(pages - 1);
+		lpage_start = start & mask;
+		lpage_end = end & mask;
+
+		/*
+		 * We only need to scan the head and tail page, for middle pages
+		 * we know they are not mixed.
+		 */

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+		update_mixed(lpage_info_slot(lpage_start, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_start,
+							  lpage_start + pages));
+
+		if (lpage_start == lpage_end)
+			return;
+
+		for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) {
+			update_mixed(lpage_info_slot(gfn, slot, level), false);
+		}

Boundary check missing here for the case when gfn reaches lpage_end.

Quoted 5 lines
Quoted 2 lines
		if (gfn == lpage_end)
			return;

In this case, it's actually the tail page that I want to scan for with below code.

What if you do not have the tail lpage?

For example: memslot base_gfn = 0x1000 and npages is 0x800, so memslot range is 0x1000 to 0x17ff.

Assume a case when this function is called with start = 1000 and end = 1800. For 2M, page mask is 0x1ff. start and end both are 2M aligned.

First update_mixed takes care of 0x1000-0x1200
Loop update_mixed: goes over from 0x1200 - 0x1800, there are no pages left for last update_mixed to process.

Quoted 9 lines

It's also possible I misunderstand something here.

Chao

Quoted 5 lines

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7338

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +4 -0
+
+		update_mixed(lpage_info_slot(lpage_end, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_end,
+							  lpage_end + pages));

lpage_info_slot some times causes a crash, as I noticed that lpage_info_slot() returns out-of-bound index.

Regards
Nikunj

#9 lore raw

Re: [PATCH v7 003/102] KVM: Refactor CPU compatibility check on module initialiization

In reply to [email protected]

Here is the updated version.

commit 7d042749b631f668ed9e99044228f16c212161bc

Author: Isaku Yamahata <[email protected]>
Date:   Fri Apr 22 16:56:51 2022 -0700

KVM: Refactor CPU compatibility check on module initialization

TDX module requires its initialization. It requires VMX to be enabled. Although there are several options of when to initialize it, the choice is the initialization time of the KVM kernel module. There is no usable arch-specific hook for the TDX module to utilize during the KVM kernel module initialization. The code doesn't enable/disable hardware (VMX in TDX case) during the kernel module initialization. Add a hook for enabling hardware, arch-specific initialization, and disabling hardware during KVM kernel module initialization to make a room for TDX module initialization. The current KVM enables hardware when the first VM is created and disables hardware when the last VM is destroyed. When no VM is running, hardware is disabled. To follow these semantics, the kernel module initialization needs to disable hardware. Opportunistically refactor the code to enable/disable hardware.

Add hadware_enable_all() and hardware_disable_all() to kvm_init() and introduce a new arch-specific callback function, kvm_arch_post_hardware_enable_setup, for arch to do arch-specific initialization that requires hardware_enable_all(). Opportunistically, move kvm_arch_check_processor_compat() to to hardware_enabled_nolock(). TDX module initialization code will go into kvm_arch_post_hardware_enable_setup().

This patch reorders some function calls as below from (*) (**) (A) and (B) to (A) (B) and (*). Here (A) and (B) depends on (*), but not (**). By code inspection, only mips and VMX has the code of (*). No other arch has empty (*). So refactor mips and VMX and eliminate the necessity hook for (*) instead of adding an unused hook.

Before this patch:
- Arch module initialization
- kvm_init()
- kvm_arch_init()
- kvm_arch_check_processor_compat() on each CPUs
- post-arch-specific initialization -- (*): (A) and (B) depends on this
- post-arch-specific initialization -- (**): no dependency to (A) and (B)

- When creating/deleting the first/last VM
- kvm_arch_hardware_enable() on each CPUs -- (A)
- kvm_arch_hardware_disable() on each CPUs -- (B)

After this patch:
- Arch module initialization
- kvm_init()
- kvm_arch_init()
- arch-specific initialization -- (*)
- kvm_arch_check_processor_compat() on each CPUs
- kvm_arch_hardware_enable() on each CPUs -- (A)
- kvm_arch_hardware_disable() on each CPUs -- (B)
- post-arch-specific initialization -- (**)

- When creating/deleting the first/last VM (no logic change)
- kvm_arch_hardware_enable() on each CPUs -- (A)
- kvm_arch_hardware_disable() on each CPUs -- (B)

Code inspection result:
As long as I inspected, I found only mips and VMX have non-empty (*) or non-empty (A) or (B).
x86: tested on a real machine
mips: compile test only
powerpc, s390, arm, riscv: code inspection only

- arch/mips/kvm/mips.c
module init function, kvm_mips_init(), does some initialization after kvm_init(). Compile test only.

- arch/x86/kvm/x86.c
- uses vm_list which is statically initialized.
- static_call(kvm_x86_hardware_enable)();
- SVM: (*) and (**) are empty.
- VMX: initialize percpu variable loaded_vmcss_on_cpu that VMXON uses.

- arch/powerpc/kvm/powerpc.c
kvm_arch_hardware_enable/disable() are nop

- arch/s390/kvm/kvm-s390.c
kvm_arch_hardware_enable/disable() are nop

- arch/arm64/kvm/arm.c
module init function, arm_init(), calls only kvm_init(). (*) and (**) are empty

- arch/riscv/kvm/main.c
module init function, riscv_kvm_init(), calls only kvm_init(). (*) and (**) are empty

arch/mips/kvm/mips.c +11 -5
index 092d09fb6a7e..fd7339cff57c 100644
@@ -1642,12 +1642,11 @@ static int __init kvm_mips_init(void)
 		return -EOPNOTSUPP;
 	}
 
+	/*
+	 * kvm_init() calls kvm_arch_hardware_enable/disable().  The early
+	 * initialization is needed before calling kvm_init().
+	 */
 	ret = kvm_mips_entry_setup();
-	if (ret)
-		return ret;
-
-	ret = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
-
 	if (ret)
 		return ret;
 
@@ -1656,6 +1655,13 @@ static int __init kvm_mips_init(void)
 
 	register_die_notifier(&kvm_mips_csr_die_notifier);
 
+	ret = kvm_init(NULL, sizeof(struct kvm_vcpu), 0, THIS_MODULE);
+
+	if (ret) {
+		unregister_die_notifier(&kvm_mips_csr_die_notifier);
+		return ret;
+	}
+
 	return 0;
 }
 
arch/x86/kvm/vmx/vmx.c +19 -4
index 111e0c42479a..5c59b4ea6524 100644
@@ -8442,6 +8442,23 @@ static void vmx_exit(void)
 }
 module_exit(vmx_exit);
 
+/*
+ * Early initialization before kvm_init() so that vmx_hardware_enable/disable()
+ * can work.
+ */
+static void __init vmx_init_early(void)
+{
+	int cpu;
+
+	/*
+	 * vmx_hardware_disable() accesses loaded_vmcss_on_cpu list.
+	 * Initialize the variable before kvm_init() that calls
+	 * vmx_hardware_enable/disable().
+	 */
+	for_each_possible_cpu(cpu)
+		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
+}
+
 static int __init vmx_init(void)
 {
 	int r, cpu;
@@ -8479,6 +8496,7 @@ static int __init vmx_init(void)
 	}
 #endif
 
+	vmx_init_early();
 	r = kvm_init(&vmx_init_ops, sizeof(struct vcpu_vmx),
 		     __alignof__(struct vcpu_vmx), THIS_MODULE);
 	if (r)
@@ -8499,11 +8517,8 @@ static int __init vmx_init(void)
 
 	vmx_setup_fb_clear_ctrl();
 
-	for_each_possible_cpu(cpu) {
-		INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
-
+	for_each_possible_cpu(cpu)
 		pi_init_cpu(cpu);
-	}
 
 #ifdef CONFIG_KEXEC_CORE
 	rcu_assign_pointer(crash_vmclear_loaded_vmcss,
include/linux/kvm_host.h +1 -0
index d4f130a9f5c8..79a4988fd51f 100644
@@ -1441,6 +1441,7 @@ void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_
 int kvm_arch_hardware_enable(void);
 void kvm_arch_hardware_disable(void);
 int kvm_arch_hardware_setup(void *opaque);
+int kvm_arch_post_hardware_enable_setup(void *opaque);
 void kvm_arch_hardware_unsetup(void);
 int kvm_arch_check_processor_compat(void);
 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu);
virt/kvm/kvm_main.c +24 -7
index a5bada53f1fe..51b8ac5faca5 100644
@@ -4899,8 +4899,13 @@ static void hardware_enable_nolock(void *junk)
 
 	cpumask_set_cpu(cpu, cpus_hardware_enabled);
 
+	r = kvm_arch_check_processor_compat();
+	if (r)
+		goto out;
+
 	r = kvm_arch_hardware_enable();
 
+out:
 	if (r) {
 		cpumask_clear_cpu(cpu, cpus_hardware_enabled);
 		atomic_inc(&hardware_enable_failed);
@@ -5697,9 +5702,9 @@ void kvm_unregister_perf_callbacks(void)
 }
 #endif
 
-static void check_processor_compat(void *rtn)
+__weak int kvm_arch_post_hardware_enable_setup(void *opaque)
 {
-	*(int *)rtn = kvm_arch_check_processor_compat();
+	return 0;
 }
 
 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
@@ -5732,11 +5737,23 @@ int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
 	if (r < 0)
 		goto out_free_1;
 
-	for_each_online_cpu(cpu) {
-		smp_call_function_single(cpu, check_processor_compat, &r, 1);
-		if (r < 0)
-			goto out_free_2;
-	}
+	/* hardware_enable_nolock() checks CPU compatibility on each CPUs. */
+	r = hardware_enable_all();
+	if (r)
+		goto out_free_2;
+	/*
+	 * Arch specific initialization that requires to enable virtualization
+	 * feature.  e.g. TDX module initialization requires VMXON on all
+	 * present CPUs.
+	 */
+	kvm_arch_post_hardware_enable_setup(opaque);
+	/*
+	 * Make hardware disabled after the KVM module initialization.  KVM
+	 * enables hardware when the first KVM VM is created and disables
+	 * hardware when the last KVM VM is destroyed.  When no KVM VM is
+	 * running, hardware is disabled.  Keep that semantics.
+	 */
+	hardware_disable_all();
 
 	r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
 				      kvm_starting_cpu, kvm_dying_cpu);
Signature · 1 line
Isaku Yamahata <[email protected]>
#101 lore raw

Re: [PATCH v7 037/102] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to Kai Huang
Quoted 26 lines · Kai Huang
Quoted 12 lines
arch/x86/kvm/mmu/spte.c +1 -2
@@ -337,9 +335,8 @@ u64 mark_spte_for_access_track(u64 spte)
 	return spte;
 }
 
-void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
+void kvm_mmu_set_mmio_spte_mask(struct kvm *kvm, u64 mmio_value, u64 mmio_mask)
 {
-	BUG_ON((u64)(unsigned)access_mask != access_mask);
 	WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
 
 	if (!enable_mmio_caching)

arch/x86/kvm/mmu/spte.c void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask) · line 366

Quoted 10 lines
arch/x86/kvm/mmu/spte.c +1 -6
@@ -366,12 +363,9 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 	    WARN_ON(mmio_value && (__REMOVED_SPTE & mmio_mask) == mmio_value))
 		mmio_value = 0;
 
-	if (!mmio_value)
-		enable_mmio_caching = false;
-
-	shadow_mmio_value = mmio_value;
-	shadow_mmio_mask  = mmio_mask;
-	shadow_mmio_access_mask = access_mask;
+	kvm->arch.enable_mmio_caching = !!mmio_value;

KVM has a global enable_mmio_caching boolean, and I think we should honor it here (in this patch) by doing below first:

Quoted 2 lines
	if (enabling_mmio_caching)
		mmio_value = 0;

This function already includes "if (!enable_mmio_caching) mmio_value = 0;" in the beginning. (But not in this hunk, though). So this patch honors the kernel module parameter.

Quoted 8 lines
Quoted 8 lines
arch/x86/kvm/mmu/spte.h +0 -0
index f5fd22f6bf5f..99bce92b596e 100644
@@ -5,8 +5,6 @@
 
 #include "mmu_internal.h"
 
Quoted 8 lines

arch/x86/kvm/mmu/spte.h line 9

Quoted 2 lines
arch/x86/kvm/mmu/spte.h +0 -2
-extern bool __read_mostly enable_mmio_caching;
-

Here you removed the ability to control enable_mmio_caching globally. It's not something you stated to do in the changelog. Perhaps we should still keep it, and enforce it in kvm_mmu_set_mmio_spte_mask() as commented above.

And in upstream KVM, it is a module parameter. What happens to it?

Ditto. the upstredam kvm_mmu_set_mmio_spte_mask() has "if (!enable_mmio_caching) mmio_value = 0;" and this patch keeps it.

Quoted 16 lines
Quoted 16 lines
arch/x86/kvm/vmx/tdx.c +1 -0
index 36d2127cb7b7..52fb54880f9b 100644
@@ -7,6 +7,7 @@
 #include "x86_ops.h"
 #include "tdx.h"
 #include "x86.h"
+#include "mmu.h"
 
 #undef pr_fmt
 #define pr_fmt(fmt) "tdx: " fmt
@@ -276,6 +277,9 @@ int tdx_vm_init(struct kvm *kvm)
 	int ret, i;
 	u64 err;
 
Quoted 7 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_init(struct kvm *kvm) · line 282

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	kvm_mmu_set_mmio_spte_mask(kvm, vmx_shadow_mmio_mask,
+				   vmx_shadow_mmio_mask);
+

I prefer to split this chunk out to another patch so this patch can be purely
infrastructural. In this way you can even move this patch around easily in
this series.

Ok. I'll move it to a patch that touches TDX.

Signature · 1 line
Isaku Yamahata <[email protected]>
#115 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Kai Huang
Quoted 19 lines · Kai Huang
Quoted 18 lines · Isaku Yamahata
Quoted 14 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Quoted 8 lines
Quoted 6 lines

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

https://lore.kernel.org/lkml/[email protected]/

Quoted 1 line

OK. But can we assume a normal guest won't sending #VE IPI?

Theoretically nothing prevents that. I wouldn't way "normal". Anyway this is off by default.

Signature · 1 line
Isaku Yamahata <[email protected]>
#102 lore raw

Re: [PATCH v7 037/102] KVM: x86/mmu: Track shadow MMIO value/mask on a per-VM basis

In reply to Isaku Yamahata
Quoted 10 lines · Isaku Yamahata
Quoted 5 lines

KVM has a global enable_mmio_caching boolean, and I think we should honor it here (in this patch) by doing below first:

  if (enabling_mmio_caching)
  mmio_value = 0;

This function already includes "if (!enable_mmio_caching) mmio_value = 0;" in the beginning. (But not in this hunk, though).  So this patch honors the kernel
module parameter.

Yeah I missed that. Thanks.

Signature · 2 lines
Thanks,
-Kai
#116 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Isaku Yamahata
Quoted 25 lines · Isaku Yamahata
Quoted 22 lines · Kai Huang
Quoted 21 lines · Isaku Yamahata
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

Quoted 5 lines

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

https://lore.kernel.org/lkml/[email protected]/

Quoted 1 line

OK. But can we assume a normal guest won't sending #VE IPI?

Theoretically nothing prevents that. I wouldn't way "normal". Anyway this is off by default.

I don't think whether it is on or off by default matters. If it can happen legitimately in the guest, it doesn't look right to print out something like below:

	pr_err("VMEXIT due to unexpected #VE.\n");

Anyway, will let maintainers to decide.

Signature · 2 lines
Thanks,
-Kai
#128 lore raw

Re: [PATCH v7 044/102] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 61 lines · On Mon, Jun 27, 2022 at 02:53:36PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk encrypted private page table, allocate a more page to mirror the existing KVM page table. Resolve KVM page fault with the existing code, and do additional operations necessary for the mirrored private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. no mirrored private page table), and the KVM page table with mirrored private page table is called a private page table. The relationship is depicted below.

Add private pointer to struct kvm_mmu_page for mirrored private page table and add helper functions to allocate/initialize/free a mirrored private page table page. Also, add helper functions to check if a given kvm_mmu_page is private. The later patch introduces hooks to operate on the mirrored private page table.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
 CPU/KVM shared PT root  KVM private PT root     |  CPU private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            private PT <----mirror----> mirrored private PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |

PT: page table

Both CPU and KVM refer to CPU/KVM shared page table. Private page table is used only by KVM. CPU refers to mirrored private page table.

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/kvm/mmu/mmu.c          |  9 ++++
 arch/x86/kvm/mmu/mmu_internal.h | 84 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/tdp_mmu.c      |  3 ++
 4 files changed, 97 insertions(+)
arch/x86/include/asm/kvm_host.h +0 -0
index f4d4ed41641b..bfc934dc9a33 100644

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 719

Quoted 4 lines
arch/x86/include/asm/kvm_host.h +1 -0
@@ -716,6 +716,7 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;

I notice that mmu_private_sp_cache.gfp_zero is left unset so these pages may contain garbage. Is this by design because the TDX module can't rely on the contents being zero and has to take care of initializing the page itself? i.e. GFP_ZERO would be a waste of cycles?

If I'm correct please include a comment here in the next revision to explain why GFP_ZERO is not necessary.

Quoted 30 lines
arch/x86/include/asm/kvm_host.h +0 -0
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +8 -0
index c517c7bca105..a5bf3e40e209 100644
@@ -691,6 +691,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
 	int start, end, i, r;
 	bool is_tdp_mmu = is_tdp_mmu_enabled(vcpu->kvm);
 
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
 	if (is_tdp_mmu && shadow_nonpresent_value)
 		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
@@ -732,6 +739,7 @@ static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_sp_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
 }

arch/x86/kvm/mmu/mmu.c static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct · line 1747

Quoted 4 lines
arch/x86/kvm/mmu/mmu.c +1 -0
@@ -1736,6 +1744,7 @@ static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct
 	if (!direct)
 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
+	kvm_mmu_init_private_sp(sp, NULL);

This is unnecessary. kvm_mmu_page structs are zero-initialized so private_sp will already be NULL.

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 59

Quoted 13 lines
arch/x86/kvm/mmu/mmu.c +0 -0
 	/*
 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
arch/x86/kvm/mmu/mmu_internal.h +2 -0
index 44a04fad4bed..9f3a6bea60a3 100644
@@ -55,6 +55,10 @@ struct kvm_mmu_page {
 	u64 *spt;
 	/* hold the gfn of each spte inside spt */
 	gfn_t *gfns;
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	/* associated private shadow page, e.g. SEPT page. */

Can we use "Secure EPT" instead of SEPT in KVM code and comments? (i.e. also including variable names like sept_page -> secure_ept_page)

"SEPT" looks like a mispelling of SPTE, which is used all over KVM. It will be difficult to read code that contains both acronyms.

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 60

Quoted 1 line
arch/x86/kvm/mmu/mmu_internal.h +1 -0
+	void *private_sp;

Please name this "private_spt" and move it up next to "spt".

sp" or "shadow page" is used to refer to kvm_mmu_page structs. For example, look at all the code in KVM that uses struct kvm_mmu_page *sp.

"spt" is "shadow page table", i.e. the actual page table memory. See kvm_mmu_page.spt. Calling this field "private_spt" makes it obvious that this pointer is pointing to a page table.

Also please update the language in the comment accordingly to "private shadow page table".

Quoted 115 lines
arch/x86/kvm/mmu/mmu_internal.h +81 -0
+#endif
 	/* Currently serving as active root */
 	union {
 		int root_count;
@@ -115,6 +119,86 @@ static inline int kvm_mmu_page_as_id(struct kvm_mmu_page *sp)
 	return kvm_mmu_role_as_id(sp->role);
 }
 
+/*
+ * TDX vcpu allocates page for root Secure EPT page and assigns to CPU secure
+ * EPT pointer.  KVM doesn't need to allocate and link to the secure EPT.
+ * Dummy value to make is_pivate_sp() return true.
+ */
+#define KVM_MMU_PRIVATE_SP_ROOT	((void *)1)
+
+#ifdef CONFIG_KVM_MMU_PRIVATE
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return !!sp->private_sp;
+}
+
+static inline bool is_private_sptep(u64 *sptep)
+{
+	WARN_ON(!sptep);
+	return is_private_sp(sptep_to_sp(sptep));
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return sp->private_sp;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp, void *private_sp)
+{
+	sp->private_sp = private_sp;
+}
+
+/* Valid sp->role.level is required. */
+static inline void kvm_mmu_alloc_private_sp(
+	struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, bool is_root)
+{
+	if (is_root)
+		sp->private_sp = KVM_MMU_PRIVATE_SP_ROOT;
+	else
+		sp->private_sp = kvm_mmu_memory_cache_alloc(
+			&vcpu->arch.mmu_private_sp_cache);
+	/*
+	 * Because mmu_private_sp_cache is topped up before staring kvm page
+	 * fault resolving, the allocation above shouldn't fail.
+	 */
+	WARN_ON_ONCE(!sp->private_sp);
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+	if (sp->private_sp != KVM_MMU_PRIVATE_SP_ROOT)
+		free_page((unsigned long)sp->private_sp);
+}
+#else
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return false;
+}
+
+static inline bool is_private_sptep(u64 *sptep)
+{
+	return false;
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return NULL;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp, void *private_sp)
+{
+}
+
+static inline void kvm_mmu_alloc_private_sp(
+	struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, bool is_root)
+{
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+}
+#endif
+
 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
 	/*
arch/x86/kvm/mmu/tdp_mmu.c +3 -0
index 7eb41b176d1e..b2568b062faa 100644
@@ -72,6 +72,8 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
 
 static void tdp_mmu_free_sp(struct kvm_mmu_page *sp)
 {
+	if (is_private_sp(sp))
+		kvm_mmu_free_private_sp(sp);
 	free_page((unsigned long)sp->spt);
 	kmem_cache_free(mmu_page_header_cache, sp);
 }
@@ -295,6 +297,7 @@ static void tdp_mmu_init_sp(struct kvm_mmu_page *sp, tdp_ptep_t sptep,
 	sp->gfn = gfn;
 	sp->ptep = sptep;
 	sp->tdp_mmu_page = true;
+	kvm_mmu_init_private_sp(sp);
 
 	trace_kvm_mmu_get_page(sp, true);
 }
Signature · 1 line
2.25.1
#117 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Kai Huang
Quoted 30 lines · Kai Huang
Quoted 29 lines · Isaku Yamahata
Quoted 26 lines · Kai Huang
Quoted 24 lines · Isaku Yamahata
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

Quoted 5 lines

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

https://lore.kernel.org/lkml/[email protected]/

Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

OK. But can we assume a normal guest won't sending #VE IPI?

Theoretically nothing prevents that. I wouldn't way "normal". Anyway this is off by default.

I don't think whether it is on or off by default matters.

It matters in the sense that the module param is intended purely for testing, i.e. there's zero reason to ever enable it in production. That changes what is and wasn't isn't a reasonable response to an unexpected #VE.

Quoted 4 lines

If it can happen legitimately in the guest, it doesn't look right to print out something like below:

	pr_err("VMEXIT due to unexpected #VE.\n");

Agreed. In this particular case I think the right approach is to treat an unexpected #VE as a fatal KVM bug. Yes, disabling EPT violation #VEs would likely allow the guest to live, but as above the module param should never be enabled in production. And if we get a #VE with the module param disabled, then KVM is truly in the weeds and killing the VM is the safe option.

E.g. something like

arch/x86/kvm/vmx/vmx.c +3 -0
index 4fd25e1d6ec9..54b9cb56f6e2 100644
@@ -5010,6 +5010,9 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
        if (is_invalid_opcode(intr_info))
                return handle_ud(vcpu);
 
+       if (KVM_BUG_ON(is_ve_fault(intr_info), vcpu->kvm))
+               return -EIO;
+
        error_code = 0;
        if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
                error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
#130 lore raw

Re: [PATCH v7 044/102] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]
Quoted 107 lines · On Mon, Jun 27, 2022 at 02:53:36PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk encrypted private page table, allocate a more page to mirror the existing KVM page table. Resolve KVM page fault with the existing code, and do additional operations necessary for the mirrored private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. no mirrored private page table), and the KVM page table with mirrored private page table is called a private page table. The relationship is depicted below.

Add private pointer to struct kvm_mmu_page for mirrored private page table and add helper functions to allocate/initialize/free a mirrored private page table page. Also, add helper functions to check if a given kvm_mmu_page is private. The later patch introduces hooks to operate on the mirrored private page table.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
 CPU/KVM shared PT root  KVM private PT root     |  CPU private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            private PT <----mirror----> mirrored private PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |

PT: page table

Both CPU and KVM refer to CPU/KVM shared page table. Private page table is used only by KVM. CPU refers to mirrored private page table.

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/kvm/mmu/mmu.c          |  9 ++++
 arch/x86/kvm/mmu/mmu_internal.h | 84 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/tdp_mmu.c      |  3 ++
 4 files changed, 97 insertions(+)
arch/x86/include/asm/kvm_host.h +1 -0
index f4d4ed41641b..bfc934dc9a33 100644
@@ -716,6 +716,7 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;
 
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +9 -0
index c517c7bca105..a5bf3e40e209 100644
@@ -691,6 +691,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
 	int start, end, i, r;
 	bool is_tdp_mmu = is_tdp_mmu_enabled(vcpu->kvm);
 
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
 	if (is_tdp_mmu && shadow_nonpresent_value)
 		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
@@ -732,6 +739,7 @@ static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_sp_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
 }
@@ -1736,6 +1744,7 @@ static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct
 	if (!direct)
 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
+	kvm_mmu_init_private_sp(sp, NULL);
 
 	/*
 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
arch/x86/kvm/mmu/mmu_internal.h +0 -0
index 44a04fad4bed..9f3a6bea60a3 100644

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 61

Quoted 7 lines
arch/x86/kvm/mmu/mmu_internal.h +4 -0
@@ -55,6 +55,10 @@ struct kvm_mmu_page {
 	u64 *spt;
 	/* hold the gfn of each spte inside spt */
 	gfn_t *gfns;
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	/* associated private shadow page, e.g. SEPT page. */
+	void *private_sp;
+#endif

write_flooding_count and unsync_children are only used in shadow MMU SPs and private_sp is only used in TDP MMU SPs. So it seems like we could put these together in a union and drop CONFIG_KVM_MMU_PRIVATE without increasing the size of kvm_mmu_page. i.e.

	union {
		struct {
			unsigned int unsync_children;
			/* Number of writes since the last time traversal visited this page.  */
			atomic_t write_flooding_count;
		};
		/*
		 * The associated private shadow page table, e.g. for Secure EPT.
		 * Only valid if tdp_mmu_page is true.
		 */
		void *private_spt;
	};

Then change is_private_sp() to:

static inline bool is_private_sp(struct kvm_mmu_page *sp)

{
	return sp->tdp_mmu_page && sp->private_sp;
}

This will allow us to drop CONFIG_KVM_MMU_PRIVATE, the only benefit of which I see is to avoid increasing the size of kvm_mmu_page. However to actually realize that benefit Cloud vendors (for example) would have to create separate kernel builds for TDX and non-TDX hosts, which seems like a huge hassel.

Quoted 114 lines
arch/x86/kvm/mmu/mmu_internal.h +80 -0
 	/* Currently serving as active root */
 	union {
 		int root_count;
@@ -115,6 +119,86 @@ static inline int kvm_mmu_page_as_id(struct kvm_mmu_page *sp)
 	return kvm_mmu_role_as_id(sp->role);
 }
 
+/*
+ * TDX vcpu allocates page for root Secure EPT page and assigns to CPU secure
+ * EPT pointer.  KVM doesn't need to allocate and link to the secure EPT.
+ * Dummy value to make is_pivate_sp() return true.
+ */
+#define KVM_MMU_PRIVATE_SP_ROOT	((void *)1)
+
+#ifdef CONFIG_KVM_MMU_PRIVATE
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return !!sp->private_sp;
+}
+
+static inline bool is_private_sptep(u64 *sptep)
+{
+	WARN_ON(!sptep);
+	return is_private_sp(sptep_to_sp(sptep));
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return sp->private_sp;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp, void *private_sp)
+{
+	sp->private_sp = private_sp;
+}
+
+/* Valid sp->role.level is required. */
+static inline void kvm_mmu_alloc_private_sp(
+	struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, bool is_root)
+{
+	if (is_root)
+		sp->private_sp = KVM_MMU_PRIVATE_SP_ROOT;
+	else
+		sp->private_sp = kvm_mmu_memory_cache_alloc(
+			&vcpu->arch.mmu_private_sp_cache);
+	/*
+	 * Because mmu_private_sp_cache is topped up before staring kvm page
+	 * fault resolving, the allocation above shouldn't fail.
+	 */
+	WARN_ON_ONCE(!sp->private_sp);
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+	if (sp->private_sp != KVM_MMU_PRIVATE_SP_ROOT)
+		free_page((unsigned long)sp->private_sp);
+}
+#else
+static inline bool is_private_sp(struct kvm_mmu_page *sp)
+{
+	return false;
+}
+
+static inline bool is_private_sptep(u64 *sptep)
+{
+	return false;
+}
+
+static inline void *kvm_mmu_private_sp(struct kvm_mmu_page *sp)
+{
+	return NULL;
+}
+
+static inline void kvm_mmu_init_private_sp(struct kvm_mmu_page *sp, void *private_sp)
+{
+}
+
+static inline void kvm_mmu_alloc_private_sp(
+	struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, bool is_root)
+{
+}
+
+static inline void kvm_mmu_free_private_sp(struct kvm_mmu_page *sp)
+{
+}
+#endif
+
 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
 	/*
arch/x86/kvm/mmu/tdp_mmu.c +3 -0
index 7eb41b176d1e..b2568b062faa 100644
@@ -72,6 +72,8 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
 
 static void tdp_mmu_free_sp(struct kvm_mmu_page *sp)
 {
+	if (is_private_sp(sp))
+		kvm_mmu_free_private_sp(sp);
 	free_page((unsigned long)sp->spt);
 	kmem_cache_free(mmu_page_header_cache, sp);
 }
@@ -295,6 +297,7 @@ static void tdp_mmu_init_sp(struct kvm_mmu_page *sp, tdp_ptep_t sptep,
 	sp->gfn = gfn;
 	sp->ptep = sptep;
 	sp->tdp_mmu_page = true;
+	kvm_mmu_init_private_sp(sp);
 
 	trace_kvm_mmu_get_page(sp, true);
 }
Signature · 1 line
2.25.1
#52 lore raw

Re: [PATCH v7 022/102] KVM: TDX: create/destroy VM structure

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 287

Quoted 13 lines · On Mon, Jun 27, 2022, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +13 -0
+int tdx_vm_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	int ret, i;
+	u64 err;
+
+	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
+	kvm->max_vcpus = 0;
+
+	kvm_tdx->hkid = tdx_keyid_alloc();
+	if (kvm_tdx->hkid < 0)
+		return -EBUSY;

We (Google) have been working through potential flows for intrahost (copyless) migration, and one of the things that came up is that allocating the HKID during KVM_CREATE_VM will be problematic as HKID are a relatively scarce resource. E.g. if all key IDs are in use, then creating a destination TDX VM will be impossible even though intrahost migration can create succeed since the "new" would reuse the source's HKID.

Allocating the various pages is also annoying, e.g. they'd have to be freed, but not as directly problematic.

SEV (all flavors) has a similar problem with ASIDs. The solution for SEV was to not allocate an ASID during KVM_CREATE_VM and instead "activate" SEV during KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM.

I think we should prepare for a similar future for TDX and move the HKID allocation and all dependent resource allocation to KVM_TDX_INIT_VM. AFAICT (and remember), this should be a fairly simple code movement, but I'd prefer it be done before merging TDX so that if it's not so simple, e.g. requires another sub-ioctl, then we don't have to try and tweak KVM's ABI to enable intrahost migration.

Quoted 14 lines
arch/x86/kvm/vmx/tdx.c +14 -0
+
+	ret = tdx_alloc_td_page(&kvm_tdx->tdr);
+	if (ret)
+		goto free_hkid;
+
+	kvm_tdx->tdcs = kcalloc(tdx_caps.tdcs_nr_pages, sizeof(*kvm_tdx->tdcs),
+				GFP_KERNEL_ACCOUNT);
+	if (!kvm_tdx->tdcs)
+		goto free_tdr;
+	for (i = 0; i < tdx_caps.tdcs_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&kvm_tdx->tdcs[i]);
+		if (ret)
+			goto free_tdcs;
+	}
#64 lore raw

Re: [PATCH v7 028/102] KVM: TDX: allocate/free TDX vcpu structure

In reply to [email protected]
Quoted 16 lines · On Mon, Jun 27, 2022, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +16 -0
+int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int ret, i;
+
+	/* TDX only supports x2APIC, which requires an in-kernel local APIC. */
+	if (!vcpu->arch.apic)
+		return -EINVAL;
+
+	fpstate_set_confidential(&vcpu->arch.guest_fpu);
+
+	ret = tdx_alloc_td_page(&tdx->tdvpr);
+	if (ret)
+		return ret;
+
+	tdx->tdvpx = kcalloc(tdx_caps.tdvpx_nr_pages, sizeof(*tdx->tdvpx),

arch/x86/kvm/vmx/tdx.c int tdx_vm_init(struct kvm *kvm) · line 426

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			GFP_KERNEL_ACCOUNT);
+	if (!tdx->tdvpx) {
+		ret = -ENOMEM;
+		goto free_tdvpr;
+	}
+	for (i = 0; i < tdx_caps.tdvpx_nr_pages; i++) {
+		ret = tdx_alloc_td_page(&tdx->tdvpx[i]);
+		if (ret)
+			goto free_tdvpx;
+	}

Similar to HKID allocation for intrahost migration, can the TDVPX allocations be moved to KVM_TDX_INIT_VCPU?

#218 lore raw
In reply to Nikunj A. Dadhania
Quoted 89 lines · Nikunj A. Dadhania
Quoted 77 lines · Chao Peng
Quoted 76 lines · Nikunj A. Dadhania
Quoted 62 lines · Chao Peng

On Thu, Jul 14, 2022 at 01:03:46AM +0000, Sean Christopherson wrote:
...

Quoted 4 lines

Option D). track shared regions in an Xarray, update kvm_arch_memory_slot.lpage_info on insertion/removal to (dis)allow hugepages as needed.

Quoted 8 lines

+ efficient on KVM page fault (no new lookups)
+ zero memory overhead (assuming KVM has to eat the cost of the Xarray anyways)
+ straightforward to implement
+ can (and should) be merged as part of the UPM series

I believe xa_for_each_range() can be used to see if a given 2mb/1gb range is completely covered (fully shared) or not covered at all (fully private), but I'm not 100% certain that xa_for_each_range() works the way I think it does.

Hi Sean,

Below is the implementation to support 2M as you mentioned as option D. It's based on UPM v7 xarray code: https://lkml.org/lkml/2022/7/6/259

Everything sounds good, the only trick bit is inc/dec disallow_lpage. If we still treat it as a count, it will be a challenge to make the inc/dec balanced. So in this patch I stole a bit for the purpose, looks ugly.

Any feedback is welcome.

Thanks,
Chao

-----------------------------------------------------------------------
From: Chao Peng <[email protected]>
Date: Wed, 20 Jul 2022 11:37:18 +0800
Subject: [PATCH] KVM: Add large page support for private memory

Update lpage_info when handling KVM_MEMORY_ENCRYPT_{UN,}REG_REGION.

Reserve a bit in disallow_lpage to indicate a large page has private/share pages mixed.

---

arch/x86/kvm/mmu/mmu.c +19 -0
+static void update_mem_lpage_info(struct kvm *kvm,
+				  struct kvm_memory_slot *slot,
+				  unsigned int attr,
+				  gfn_t start, gfn_t end)
+{
+	unsigned long lpage_start, lpage_end;
+	unsigned long gfn, pages, mask;
+	int level;
+
+	for (level = PG_LEVEL_2M; level <= KVM_MAX_HUGEPAGE_LEVEL; level++) {
+		pages = KVM_PAGES_PER_HPAGE(level);
+		mask = ~(pages - 1);
+		lpage_start = start & mask;
+		lpage_end = end & mask;
+
+		/*
+		 * We only need to scan the head and tail page, for middle pages
+		 * we know they are not mixed.
+		 */

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7334

Quoted 10 lines
arch/x86/kvm/mmu/mmu.c +10 -0
+		update_mixed(lpage_info_slot(lpage_start, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_start,
+							  lpage_start + pages));
+
+		if (lpage_start == lpage_end)
+			return;
+
+		for (gfn = lpage_start + pages; gfn < lpage_end; gfn += pages) {
+			update_mixed(lpage_info_slot(gfn, slot, level), false);
+		}

Boundary check missing here for the case when gfn reaches lpage_end.

Quoted 5 lines
Quoted 2 lines
		if (gfn == lpage_end)
			return;

In this case, it's actually the tail page that I want to scan for with below code.

What if you do not have the tail lpage?

For example: memslot base_gfn = 0x1000 and npages is 0x800, so memslot range is 0x1000 to 0x17ff.

Quoted 6 lines

Assume a case when this function is called with start = 1000 and end = 1800. For 2M, page mask is 0x1ff. start and end both are 2M aligned.

First update_mixed takes care of 0x1000-0x1200
Loop update_mixed: goes over from 0x1200 - 0x1800, there are no pages left for last update_mixed to process.

Oops, good catch. I would fix it differently by playing with lpage_end:

	lpage_end = (end - 1) & mask;

Thanks,
Chao

Quoted 17 lines
Quoted 10 lines

It's also possible I misunderstand something here.

Chao

Quoted 5 lines

arch/x86/kvm/mmu/mmu.c void kvm_mmu_pre_destroy_vm(struct kvm *kvm) · line 7338

Quoted 5 lines
arch/x86/kvm/mmu/mmu.c +4 -0
+
+		update_mixed(lpage_info_slot(lpage_end, slot, level),
+			     mem_attr_is_mixed(kvm, attr, lpage_end,
+							  lpage_end + pages));

lpage_info_slot some times causes a crash, as I noticed that lpage_info_slot() returns out-of-bound index.

Regards
Nikunj

#118 lore raw

Re: [PATCH v7 041/102] KVM: VMX: Introduce test mode related to EPT violation VE

In reply to Sean Christopherson
Quoted 47 lines · Sean Christopherson
Quoted 30 lines · Kai Huang
Quoted 29 lines · Isaku Yamahata
Quoted 26 lines · Kai Huang
Quoted 24 lines · Isaku Yamahata
Quoted 9 lines · Kai Huang
Quoted 7 lines · On Mon, 2022-06-27 at 14:53 -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

To support TDX, KVM is enhanced to operate with #VE. For TDX, KVM programs to inject #VE conditionally and set #VE suppress bit in EPT entry. For VMX case, #VE isn't used. If #VE happens for VMX, it's a bug. To be defensive (test that VMX case isn't broken), introduce option ept_violation_ve_test and when it's set, set error.

Quoted 5 lines

I don't see why we need this patch. It may be helpful during your test, but why do we need this patch for formal submission?

And for a normal guest, what prevents one vcpu from sending #VE IPI to another vcpu?

Paolo suggested it as follows. Maybe it should be kernel config. (I forgot to add suggested-by. I'll add it)

https://lore.kernel.org/lkml/[email protected]/

Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

OK. But can we assume a normal guest won't sending #VE IPI?

Theoretically nothing prevents that. I wouldn't way "normal". Anyway this is off by default.

I don't think whether it is on or off by default matters.

It matters in the sense that the module param is intended purely for testing, i.e. there's zero reason to ever enable it in production. That changes what is and wasn't isn't a reasonable response to an unexpected #VE.

Quoted 4 lines

If it can happen legitimately in the guest, it doesn't look right to print out something like below:

	pr_err("VMEXIT due to unexpected #VE.\n");
Quoted 7 lines

Agreed. In this particular case I think the right approach is to treat an unexpected #VE as a fatal KVM bug. Yes, disabling EPT violation #VEs would likely allow the guest to live, but as above the module param should never be enabled in production. And if we get a #VE with the module param disabled, then KVM is truly in the weeds and killing the VM is the safe option.

E.g. something like

Thanks, I finally ended up with the following.

arch/x86/kvm/vmx/vmcs.h +5 -0
index ac290a44a693..9277676057a7 100644
@@ -140,6 +140,11 @@ static inline bool is_nm_fault(u32 intr_info)
 	return is_exception_n(intr_info, NM_VECTOR);
 }
 
+static inline bool is_ve_fault(u32 intr_info)
+{
+	return is_exception_n(intr_info, VE_VECTOR);
+}
+
 /* Undocumented: icebp/int1 */
 static inline bool is_icebp(u32 intr_info)
 {
arch/x86/kvm/vmx/vmx.c +6 -7
index 881db80ceee9..c3e4c0d17b63 100644
@@ -5047,6 +5047,12 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
 	if (is_invalid_opcode(intr_info))
 		return handle_ud(vcpu);
 
+	/*
+	 * #VE isn't supposed to happen.  Although vcpu can send
+	 */
+	if (KVM_BUG_ON(is_ve_fault(intr_info), vcpu->kvm))
+		return -EIO;
+
 	error_code = 0;
 	if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
 		error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
@@ -5167,14 +5173,7 @@ static int handle_exception_nmi(struct kvm_vcpu *vcpu)
 		if (handle_guest_split_lock(kvm_rip_read(vcpu)))
 			return 1;
 		fallthrough;
-	case VE_VECTOR:
 	default:
-		if (ept_violation_ve_test && ex_no == VE_VECTOR) {
-			pr_err("VMEXIT due to unexpected #VE.\n");
-			secondary_exec_controls_clearbit(
-				vmx, SECONDARY_EXEC_EPT_VIOLATION_VE);
-			return 1;
-		}
 		kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
 		kvm_run->ex.exception = ex_no;
 		kvm_run->ex.error_code = error_code;
Signature · 1 line
Isaku Yamahata <[email protected]>
#131 lore raw

Re: [PATCH v7 044/102] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to David Matlack
Quoted 112 lines · David Matlack
Quoted 111 lines · On Mon, Jun 27, 2022 at 02:53:36PM -0700, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

For private GPA, CPU refers a private page table whose contents are encrypted. The dedicated APIs to operate on it (e.g. updating/reading its PTE entry) are used and their cost is expensive.

When KVM resolves KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost to directly walk encrypted private page table, allocate a more page to mirror the existing KVM page table. Resolve KVM page fault with the existing code, and do additional operations necessary for the mirrored private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. no mirrored private page table), and the KVM page table with mirrored private page table is called a private page table. The relationship is depicted below.

Add private pointer to struct kvm_mmu_page for mirrored private page table and add helper functions to allocate/initialize/free a mirrored private page table page. Also, add helper functions to check if a given kvm_mmu_page is private. The later patch introduces hooks to operate on the mirrored private page table.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
 CPU/KVM shared PT root  KVM private PT root     |  CPU private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            private PT <----mirror----> mirrored private PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |

PT: page table

Both CPU and KVM refer to CPU/KVM shared page table. Private page table is used only by KVM. CPU refers to mirrored private page table.

---
 arch/x86/include/asm/kvm_host.h |  1 +
 arch/x86/kvm/mmu/mmu.c          |  9 ++++
 arch/x86/kvm/mmu/mmu_internal.h | 84 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/mmu/tdp_mmu.c      |  3 ++
 4 files changed, 97 insertions(+)
arch/x86/include/asm/kvm_host.h +1 -0
index f4d4ed41641b..bfc934dc9a33 100644
@@ -716,6 +716,7 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;
 
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +9 -0
index c517c7bca105..a5bf3e40e209 100644
@@ -691,6 +691,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
 	int start, end, i, r;
 	bool is_tdp_mmu = is_tdp_mmu_enabled(vcpu->kvm);
 
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
 	if (is_tdp_mmu && shadow_nonpresent_value)
 		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
@@ -732,6 +739,7 @@ static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_sp_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
 }
@@ -1736,6 +1744,7 @@ static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct
 	if (!direct)
 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
+	kvm_mmu_init_private_sp(sp, NULL);
 
 	/*
 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
arch/x86/kvm/mmu/mmu_internal.h +1 -0
index 44a04fad4bed..9f3a6bea60a3 100644
@@ -55,6 +55,10 @@ struct kvm_mmu_page {
 	u64 *spt;
 	/* hold the gfn of each spte inside spt */
 	gfn_t *gfns;
+#ifdef CONFIG_KVM_MMU_PRIVATE
Quoted 8 lines

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 61

Quoted 3 lines
arch/x86/kvm/mmu/mmu_internal.h +3 -0
+	/* associated private shadow page, e.g. SEPT page. */
+	void *private_sp;
+#endif

write_flooding_count and unsync_children are only used in shadow MMU SPs and private_sp is only used in TDP MMU SPs. So it seems like we could put these together in a union and drop CONFIG_KVM_MMU_PRIVATE without increasing the size of kvm_mmu_page. i.e.

I introduced KVM_MMU_PRIVATE as a alias to INTEL_TDX_HOST because I don't want to use it in kvm/mmu and I'd like KVM_MMU_PRIVATE (a sort of) independent from INTEL_TDX_HOST. Anyway once the patch series is merged, we can drop KVM_MMU_PRIVATE.

Quoted 20 lines
	union {
		struct {
			unsigned int unsync_children;
			/* Number of writes since the last time traversal visited this page.  */
			atomic_t write_flooding_count;
		};
		/*
		 * The associated private shadow page table, e.g. for Secure EPT.
		 * Only valid if tdp_mmu_page is true.
		 */
		void *private_spt;
	};

Then change is_private_sp() to:

static inline bool is_private_sp(struct kvm_mmu_page *sp)

{
	return sp->tdp_mmu_page && sp->private_sp;
}
Quoted 5 lines

This will allow us to drop CONFIG_KVM_MMU_PRIVATE, the only benefit of which I see is to avoid increasing the size of kvm_mmu_page. However to actually realize that benefit Cloud vendors (for example) would have to create separate kernel builds for TDX and non-TDX hosts, which seems like a huge hassel.

Good idea. I'll use union.

Signature · 1 line
Isaku Yamahata <[email protected]>
#129 lore raw

Re: [PATCH v7 044/102] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to David Matlack
Quoted 15 lines · David Matlack

arch/x86/include/asm/kvm_host.h struct kvm_vcpu_arch { · line 719

Quoted 9 lines
arch/x86/include/asm/kvm_host.h +1 -0
index f4d4ed41641b..bfc934dc9a33 100644
@@ -716,6 +716,7 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_gfn_array_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	struct kvm_mmu_memory_cache mmu_private_sp_cache;

I notice that mmu_private_sp_cache.gfp_zero is left unset so these pages may contain garbage. Is this by design because the TDX module can't rely on the contents being zero and has to take care of initializing the page itself? i.e. GFP_ZERO would be a waste of cycles?

Quoted 2 lines

If I'm correct please include a comment here in the next revision to explain why GFP_ZERO is not necessary.

Yes, exactly. Here is the added comments.
/*
* This cache is to allocate pages used for Secure-EPT used by the TDX
* module. Because the TDX module doesn't trust VMM and initializes the
* pages itself, KVM doesn't initialize them. Allocate pages with
* garbage and give them to the TDX module.
*/

Quoted 20 lines
Quoted 20 lines
arch/x86/include/asm/kvm_host.h +0 -0
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +7 -0
index c517c7bca105..a5bf3e40e209 100644
@@ -691,6 +691,13 @@ static int mmu_topup_shadow_page_cache(struct kvm_vcpu *vcpu)
 	int start, end, i, r;
 	bool is_tdp_mmu = is_tdp_mmu_enabled(vcpu->kvm);
 
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_sp_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
+
 	if (is_tdp_mmu && shadow_nonpresent_value)
 		start = kvm_mmu_memory_cache_nr_free_objects(mc);
 
Quoted 16 lines

arch/x86/kvm/mmu/mmu.c static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct · line 1747

Quoted 13 lines
arch/x86/kvm/mmu/mmu.c +2 -0
@@ -732,6 +739,7 @@ static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
 {
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_sp_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_gfn_array_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
 }
@@ -1736,6 +1744,7 @@ static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct
 	if (!direct)
 		sp->gfns = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_gfn_array_cache);
 	set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
+	kvm_mmu_init_private_sp(sp, NULL);

This is unnecessary. kvm_mmu_page structs are zero-initialized so private_sp will already be NULL.

Ok.

Quoted 17 lines

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 59

Quoted 13 lines
arch/x86/kvm/mmu/mmu.c +0 -0
 	/*
 	 * active_mmu_pages must be a FIFO list, as kvm_zap_obsolete_pages()
arch/x86/kvm/mmu/mmu_internal.h +2 -0
index 44a04fad4bed..9f3a6bea60a3 100644
@@ -55,6 +55,10 @@ struct kvm_mmu_page {
 	u64 *spt;
 	/* hold the gfn of each spte inside spt */
 	gfn_t *gfns;
+#ifdef CONFIG_KVM_MMU_PRIVATE
+	/* associated private shadow page, e.g. SEPT page. */

Can we use "Secure EPT" instead of SEPT in KVM code and comments? (i.e. also including variable names like sept_page -> secure_ept_page)

Quoted 2 lines

"SEPT" looks like a mispelling of SPTE, which is used all over KVM. It will be difficult to read code that contains both acronyms.

Makes sense. Will update it.

Quoted 7 lines

arch/x86/kvm/mmu/mmu_internal.h struct kvm_mmu_page { · line 60

Quoted 1 line
arch/x86/kvm/mmu/mmu_internal.h +1 -0
+	void *private_sp;

Please name this "private_spt" and move it up next to "spt".

sp" or "shadow page" is used to refer to kvm_mmu_page structs. For example, look at all the code in KVM that uses struct kvm_mmu_page *sp.

Quoted 6 lines

"spt" is "shadow page table", i.e. the actual page table memory. See kvm_mmu_page.spt. Calling this field "private_spt" makes it obvious that this pointer is pointing to a page table.

Also please update the language in the comment accordingly to "private shadow page table".

I'll rename as follows

private_sp => private_spt
spet_page => private_spt
mmu_private_sp_cache => mmu_private_spt_cache kvm_mmu_init_private_sp => kvm_mmu_inite_private_spt kvm_mmu_alloc_private_sp => kvm_mmu_alloc_private_spt kvm_mmu_free_private_sp => kvm_mmu_free_private_spt kvm_alloc_private_sp_for_split => kvm_alloc_private_spt_for_split

Thanks,

Signature · 1 line
Isaku Yamahata <[email protected]>
#53 lore raw

Re: [PATCH v7 022/102] KVM: TDX: create/destroy VM structure

In reply to Sean Christopherson
Quoted 29 lines · Sean Christopherson

arch/x86/kvm/vmx/tdx.c struct tdx_capabilities { · line 287

Quoted 13 lines · On Mon, Jun 27, 2022, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +13 -0
+int tdx_vm_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	int ret, i;
+	u64 err;
+
+	/* vCPUs can't be created until after KVM_TDX_INIT_VM. */
+	kvm->max_vcpus = 0;
+
+	kvm_tdx->hkid = tdx_keyid_alloc();
+	if (kvm_tdx->hkid < 0)
+		return -EBUSY;

We (Google) have been working through potential flows for intrahost (copyless) migration, and one of the things that came up is that allocating the HKID during KVM_CREATE_VM will be problematic as HKID are a relatively scarce resource. E.g. if all key IDs are in use, then creating a destination TDX VM will be impossible even though intrahost migration can create succeed since the "new" would reuse the source's HKID.

Allocating the various pages is also annoying, e.g. they'd have to be freed, but not as directly problematic.

SEV (all flavors) has a similar problem with ASIDs. The solution for SEV was to not allocate an ASID during KVM_CREATE_VM and instead "activate" SEV during KVM_CAP_VM_MOVE_ENC_CONTEXT_FROM.

Quoted 5 lines

I think we should prepare for a similar future for TDX and move the HKID allocation and all dependent resource allocation to KVM_TDX_INIT_VM. AFAICT (and remember), this should be a fairly simple code movement, but I'd prefer it be done before merging TDX so that if it's not so simple, e.g. requires another sub-ioctl, then we don't have to try and tweak KVM's ABI to enable intrahost migration.

The simple code movement works here. The TDX related initialization/allocation can simply be moved to KVM_TDX_INIT_VM and KVM_TDX_INIT_VCPU.

I'll update them with the next respin.

Thanks,

Signature · 1 line
Isaku Yamahata <[email protected]>