Skip to contentSkip to conversation

KVM TDX basic feature support

PATCH In review [email protected] 21 participants 695 messages Feb 26, 2024 – Jul 18, 2024 Page 3 of 6

Subsystems (8)
Documentation x86 KVM Kselftest +4 more subsystems
lore
Share & tools
lore
#276 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to Huang, Kai
Quoted 17 lines · Kai

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Quoted 4 lines

Are you sure it is TDCX, but not TDCS?

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

TDCS, TDVPR, and TDCX. Will update the comment.

Quoted 25 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 188

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	 * assigned to the TD.  Here the cache associated to the TD
+	 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+	 * cache doesn't need to be flushed again.
+	 */

How about put this part as the comment for this function?

/*
* Reclaim <name of control page> page(s) which are crypto-protected
* by TDX guest's private KeyID. Assume the cache associated with the
* TDX private KeyID has been flushed.
*/

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 197

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	if (tdx_reclaim_page(td_page_pa))
+		/*
+		 * Leak the page on failure:
+		 * tdx_reclaim_page() returns an error if and only if there's an
+		 * unexpected, fatal error, e.g. a SEAMCALL with bad params,
+		 * incorrect concurrency in KVM, a TDX Module bug, etc.
+		 * Retrying at a later point is highly unlikely to be
+		 * successful.
+		 * No log here as tdx_reclaim_page() already did.

IMHO can be simplified to below, and nothing else matters.

Quoted 6 lines
	/*
	 * Leak the page if the kernel failed to reclaim the page.
	 * The krenel cannot use it safely anymore.
	 */

And you can put this comment above the 'if (tdx_reclaim_page())' statement.

Sure.

Quoted 13 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		 */
+		return;

Empty line.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 203

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	free_page((unsigned long)__va(td_page_pa));
+}
+
+static void tdx_do_tdh_phymem_cache_wb(void *unused)

Better to make the name explicit that it is a smp_func, and you don't need the "tdx_" prefix for all the 'static' functions here:

Quoted 1 line

static void smp_func_do_phymem_cache_wb(void *unused)

Ok, will rename it.

Quoted 10 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 208

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+{
+	u64 err = 0;
+
+	do {
+		err = tdh_phymem_cache_wb(!!err);
		bool resume = !!err;

		err = tdh_phymem_cache_wb(resume);
Quoted 2 lines

So that we don't need to jump to the tdh_phymem_cache_wb() to see what does !!err mean.

Ok.

Quoted 4 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 209

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	} while (err == TDX_INTERRUPTED_RESUMABLE);

Add a comment before the do {} while():

Quoted 8 lines

/*
* TDH.PHYMEM.CACHE.WB flushes caches associated with _ANY_
* TDX private KeyID on the package (or logical cpu?) where
* it is called on. The TDX module may not finish the cache
* flush but return TDX_INTERRUPTED_RESUMEABLE instead. The
* kernel should retry it until it returns success w/o
* rescheduling.
*/

Ok.

Quoted 29 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 213

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+	/* Other thread may have done for us. */
+	if (err == TDX_NO_HKID_READY_TO_WBCACHE)
+		err = TDX_SUCCESS;

Empty line.

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	if (WARN_ON_ONCE(err))
+		pr_tdx_error(TDH_PHYMEM_CACHE_WB, err, NULL);
+}
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

Quoted 4 lines

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

As Chao suggested, will introduce state machine for vm and vcpu.

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Quoted 19 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 241

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+
+	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
+	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
+	cpus_read_lock();
+
+	/*
+	 * We can destroy multiple guest TDs simultaneously.  Prevent
+	 * tdh_phymem_cache_wb from returning TDX_BUSY by serialization.
+	 */

IMHO it's better to remind people that TDH.PHYMEM.CACHE.WB tries to grab the global TDX module lock:

/*
* TDH.PHYMEM.CACHE.WB tries to acquire the TDX module global
* lock and can fail with TDX_OPERAND_BUSY when it fails to
* grab. Multiple TDX guests can be destroyed simultaneously.
* Take the mutex to prevent it from getting error. */

Quoted 9 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	mutex_lock(&tdx_lock);
+
+	/*
+	 * Go through multiple TDX HKID state transitions with three SEAMCALLs
+	 * to make TDH.PHYMEM.PAGE.RECLAIM() usable.

What is "TDX HKID state transitions"? Not mentioned before, so needs explanation _if_ you want to say this.

Ok.

Quoted 3 lines

And what are the three "SEAMCALLs"? Where are they? The only _two_ SEAMCALLs that I can see here are: TDH.PHYMEM.CACHE.WB and TDH.MNG.KEY.FREEID.

tdh_mng_vpflushdone(). I'll those three in the comment. It may not seem to hkid state machine, though.

Quoted 5 lines

Make the transition atomic

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 247

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	 * to other functions to operate private pages and Secure-EPT pages.

What's the consequence to "other functions" if we don't make it atomic here?

Other thread can be removing pages from TD. If the HKID is freed, other thread in loop to remove pages can get error.

TDH.MEM.SEPT.REMOVE(), TDH.MEM.PAGE.REMOVE() can fail with TDX_OP_STATE_INCORRECT when HKID is not assigned.

When HKID is freed, we need to use TDH.PHYMEM.PAGE.RECLAIM(). TDH.PHYMEM.PAGE.RECLAIM() fails with TDX_LIECYCLE_STATE_INCORRECT when HKID isn't freed.

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Quoted 11 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 253

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	 *
+	 * Avoid race for kvm_gmem_release() to call kvm_mmu_unmap_gfn_range().
+	 * This function is called via mmu notifier, mmu_release().
+	 * kvm_gmem_release() is called via fput() on process exit.
+	 */
+	write_lock(&kvm->mmu_lock);

I don't fully get the race here, but it seems strange that this function is called via mmu notifier.

IIUC, this function is "supposedly" only be called when we tear down the VM,

That's correct. The hook when destroying the VM is mmu notifier mmu_release(). It's called on the behalf of mmput(). Because other component like vhost-net can increment the reference, mmu_release mmu notifier can be triggered by a thread other than the guest VM.

Quoted 1 line

so I don't know why there's such race.

When guest_memfd is released, the private memory is unmapped. the thread of guest VM can issue exit to closes guest_memfd and other thread can trigger mmu notifier of the guest VM.

Also, if we have multiple fds for the same guest_memfd, the last file closure can be done in the context of the guest VM or other process.

Quoted 16 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 266

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+
+	for_each_online_cpu(i) {
+		if (packages_allocated &&
+		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
+					     packages))
+			continue;
+		if (targets_allocated)
+			cpumask_set_cpu(i, targets);
+	}
+	if (targets_allocated)
+		on_each_cpu_mask(targets, tdx_do_tdh_phymem_cache_wb, NULL, true);
+	else
+		on_each_cpu(tdx_do_tdh_phymem_cache_wb, NULL, true);

I don't understand the logic here -- no comments whatever.

Quoted 1 line

But I am 99% sure the logic here could be simplified.

Yes, as Chao suggested, I'll use global variable for those cpumasks.
https://lore.kernel.org/kvm/ZfpwIespKy8qxWWE@chao-email/

Quoted 9 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 272

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	/*
+	 * In the case of error in tdx_do_tdh_phymem_cache_wb(), the following
+	 * tdh_mng_key_freeid() will fail.
+	 */
+	err = tdh_mng_key_freeid(kvm_tdx->tdr_pa);
+	if (WARN_ON_ONCE(err)) {

I see KVM_BUG_ON() is normally used for SEAMCALL error. Why this uses WARN_ON_ONCE() here?

Because vm_free() hook is (one of) the final steps to free struct kvm. No one else touches this kvm. Because it doesn't harm to use KVM_BUG_ON() here, I'll change it for consistency.

Quoted 25 lines
Quoted 25 lines
arch/x86/kvm/vmx/tdx.c +25 -0
+		pr_tdx_error(TDH_MNG_KEY_FREEID, err, NULL);
+		pr_err("tdh_mng_key_freeid() failed. HKID %d is leaked.\n",
+		       kvm_tdx->hkid);
+	} else
+		tdx_hkid_free(kvm_tdx);
+
+	write_unlock(&kvm->mmu_lock);
+	mutex_unlock(&tdx_lock);
+	cpus_read_unlock();
+	free_cpumask_var(targets);
+	free_cpumask_var(packages);
+}
+
+void tdx_vm_free(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	u64 err;
+	int i;
+
+	/*
+	 * tdx_mmu_release_hkid() failed to reclaim HKID.  Something went wrong
+	 * heavily with TDX module.  Give up freeing TD pages.  As the function
+	 * already warned, don't warn it again.
+	 */
+	if (is_hkid_assigned(kvm_tdx))
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 303

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+		return;
+
+	if (kvm_tdx->tdcs_pa) {
+		for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+			if (kvm_tdx->tdcs_pa[i])
+				tdx_reclaim_control_page(kvm_tdx->tdcs_pa[i]);

AFAICT, here tdcs_pa[i] cannot be NULL, right? How about:

If tdh_mng_addcx() fails in the middle of 0 < i < nr_tdcs_pages, tdcs_pa[i] can be NULL. The current allocation/free code is unnecessarily convoluted. I'll clean them up.

Quoted 8 lines
			if (!WARN_ON_ONCE(!kvm_tdx->tdcs_pa[i]))
				continue;
			
			tdx_reclaim_control_page(...);

which at least saves you some indent.

Btw, does it make sense to stop if any tdx_reclaim_control_page() fails?

It doesn't matter much in practice because it's unlikely to hit error for some of TDCS pages. So I chose to make it return void to skip error check by the caller.

Quoted 9 lines

It's OK to continue, but perhaps worth to add a comment to point out:

/*
* Continue to reclaim other control pages and
* TDR page, even failed to reclaim one control
* page. Do the best to reclaim these TDX
* private pages.
*/
tdx_reclaim_control_page();

Sure, it will make the intention clear.

Quoted 21 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 317

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+		}
+		kfree(kvm_tdx->tdcs_pa);
+		kvm_tdx->tdcs_pa = NULL;
+	}
+
+	if (!kvm_tdx->tdr_pa)
+		return;
+	if (__tdx_reclaim_page(kvm_tdx->tdr_pa))
+		return;
+	/*
+	 * TDX module maps TDR with TDX global HKID.  TDX module may access TDR
+	 * while operating on TD (Especially reclaiming TDCS).  Cache flush with > +	 * TDX global HKID is needed.
+	 */

"Especially reclaiming TDCS" -> "especially when it is reclaiming TDCS".

Use imperative mode to describe your change:

Use the SEAMCALL to ask the TDX module to flush the cache of it using the global KeyID.

Quoted 7 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 320

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(kvm_tdx->tdr_pa,
+						     tdx_global_keyid));
+	if (WARN_ON_ONCE(err)) {

Again, KVM_BUG_ON()?

Should't matter, though.

Ok, let's use KVM_BUG_ON() consistently.

Quoted 18 lines
Quoted 18 lines
arch/x86/kvm/vmx/tdx.c +18 -0
+		pr_tdx_error(TDH_PHYMEM_PAGE_WBINVD, err, NULL);
+		return;
+	}
+	tdx_clear_page(kvm_tdx->tdr_pa);
+
+	free_page((unsigned long)__va(kvm_tdx->tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+}
+
+static int tdx_do_tdh_mng_key_config(void *param)
+{
+	hpa_t *tdr_p = param;
+	u64 err;
+
+	do {
+		err = tdh_mng_key_config(*tdr_p);
+
+		/*
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 343

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		 * If it failed to generate a random key, retry it because this
+		 * is typically caused by an entropy error of the CPU's random
+		 * number generator.
+		 */
+	} while (err == TDX_KEY_GENERATION_FAILED);

If you want to handle TDX_KEY_GENERTION_FAILED, it's better to have a retry limit similar to the TDX host code does.

Ok, although it would complicates the error recovery path, let me update it.

Quoted 15 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+
+	if (WARN_ON_ONCE(err)) {

KVM_BUG_ON()?

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		pr_tdx_error(TDH_MNG_KEY_CONFIG, err, NULL);
+		return -EIO;
+	}
+
+	return 0;
+}
+
+static int __tdx_td_init(struct kvm *kvm);
+
+int tdx_vm_init(struct kvm *kvm)
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 361

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+{
+	/*
+	 * TDX has its own limit of the number of vcpus in addition to
+	 * KVM_MAX_VCPUS.
+	 */
+	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);

I believe this should be part of the patch that handles KVM_CAP_MAX_VCPUS.

Ok.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 20 lines · Isaku Yamahata
Quoted 17 lines · Kai

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but
this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Quoted 6 lines
Quoted 4 lines

Are you sure it is TDCX, but not TDCS?

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

TDCS, TDVPR, and TDCX. Will update the comment.

But TDCX, TDVPR are vcpu-scoped. Do you want to mention them _here_?

Otherwise you will have to explain them.

[...]

Quoted 19 lines
Quoted 19 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

Quoted 8 lines
Quoted 4 lines

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

As Chao suggested, will introduce state machine for vm and vcpu.

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Could you elaborate what will the state machine look like?

I need to understand it.

[...]

Quoted 11 lines

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Could you elaborate why it is still possible to have other thread removing pages from TD?

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

IIUC, by reaching here, you must already have done VPFLUSHDONE, which should be called when you free vcpu? Freeing vcpus is done in kvm_arch_destroy_vm(), which is _after_ mmu_notifier->release(), in which this tdx_mmu_release_keyid() is called?

But here we are depending vcpus to be freed before tdx_mmu_release_hkid()?

Quoted 10 lines
Quoted 9 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 272

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	/*
+	 * In the case of error in tdx_do_tdh_phymem_cache_wb(), the following
+	 * tdh_mng_key_freeid() will fail.
+	 */
+	err = tdh_mng_key_freeid(kvm_tdx->tdr_pa);
+	if (WARN_ON_ONCE(err)) {

I see KVM_BUG_ON() is normally used for SEAMCALL error. Why this uses WARN_ON_ONCE() here?

Quoted 3 lines

Because vm_free() hook is (one of) the final steps to free struct kvm. No one else touches this kvm. Because it doesn't harm to use KVM_BUG_ON() here, I'll change it for consistency.

I am fine with either. You can use KVM_BUG_ON() for SEAMCALLs at runtime, but use WARN_ON_ONCE() for those involved during VM creation.

[...]

Quoted 10 lines
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 320

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	err = tdh_phymem_page_wbinvd(set_hkid_to_hpa(kvm_tdx->tdr_pa,
+						     tdx_global_keyid));
+	if (WARN_ON_ONCE(err)) {

Again, KVM_BUG_ON()?

Should't matter, though.

Ok, let's use KVM_BUG_ON() consistently.

Ditto.

#278 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 23 lines · Kai
Quoted 20 lines · Isaku Yamahata
Quoted 17 lines · Kai

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but
this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Quoted 8 lines
Quoted 6 lines
Quoted 4 lines

Are you sure it is TDCX, but not TDCS?

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

TDCS, TDVPR, and TDCX. Will update the comment.

But TDCX, TDVPR are vcpu-scoped. Do you want to mention them _here_?

So I'll make the patch that frees TDVPR, TDCX will change this comment.

Quoted 28 lines

Otherwise you will have to explain them.

[...]

Quoted 24 lines
Quoted 23 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

Quoted 7 lines
Quoted 3 lines

As Chao suggested, will introduce state machine for vm and vcpu.

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Could you elaborate what will the state machine look like?

I need to understand it.

Not yet. Chao only propose to introduce state machine. Right now it's just an idea.

Quoted 11 lines
Quoted 10 lines

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Quoted 6 lines

Could you elaborate why it is still possible to have other thread removing pages from TD?

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Quoted 2 lines

IIUC, by reaching here, you must already have done VPFLUSHDONE, which should be called when you free vcpu?

Not necessarily.

Quoted 3 lines

Freeing vcpus is done in
kvm_arch_destroy_vm(), which is _after_ mmu_notifier->release(), in which this tdx_mmu_release_keyid() is called?

guest memfd complicates things. The race is between guest memfd release and mmu notifier release. kvm_arch_destroy_vm() is called after closing all kvm fds including guest memfd.

Here is the example. Let's say, we have fds for vhost, guest_memfd, kvm vcpu, and kvm vm. The process is exiting. Please notice vhost increments the reference of the mmu to access guest (shared) memory.

exit_mmap():
Usually mmu notifier release is fired. But not yet because of vhost.

exit_files()
close vhost fd. vhost starts timer to issue mmput().

close guest_memfd. kvm_gmem_release() calls kvm_mmu_unmap_gfn_range().
kvm_mmu_unmap_gfn_range() eventually this calls TDH.MEM.SEPT.REMOVE() and TDH.MEM.PAGE.REMOVE(). This takes time because it processes whole guest memory. Call kvm_put_kvm() at last.

During unmapping on behalf of guest memfd, the timer of vhost fires to call mmput(). It triggers mmu notifier release.

Close kvm vcpus/vm. they call kvm_put_kvm(). The last one calls kvm_destroy_vm().

It's ideal to free HKID first for efficiency. But KVM doesn't have control on the order of fds.

Quoted 1 line

But here we are depending vcpus to be freed before tdx_mmu_release_hkid()?

Not necessarily.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 28 lines · Isaku Yamahata
Quoted 25 lines · Kai
Quoted 22 lines · Isaku Yamahata
Quoted 19 lines · Kai

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but
this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Are you sure it is TDCX, but not TDCS?

Quoted 9 lines
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

TDCS, TDVPR, and TDCX. Will update the comment.

But TDCX, TDVPR are vcpu-scoped. Do you want to mention them _here_?

So I'll make the patch that frees TDVPR, TDCX will change this comment.

Hmm.. Looking again, I am not sure why do we even need tdx_reclaim_control_page()?

It basically does tdx_reclaim_page() + free_page():

+static void tdx_reclaim_control_page(unsigned long td_page_pa) +{
+ WARN_ON_ONCE(!td_page_pa);
+
+ /*
+ * TDCX are being reclaimed. TDX module maps TDCX with HKID
+ * assigned to the TD. Here the cache associated to the TD
+ * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+ * cache doesn't need to be flushed again.
+ */
+ if (tdx_reclaim_page(td_page_pa))
+ /*
+ * Leak the page on failure:
+ * tdx_reclaim_page() returns an error if and only if there's
an
+ * unexpected, fatal error, e.g. a SEAMCALL with bad params,
+ * incorrect concurrency in KVM, a TDX Module bug, etc.
+ * Retrying at a later point is highly unlikely to be
+ * successful.
+ * No log here as tdx_reclaim_page() already did.
+ */
+ return;
+ free_page((unsigned long)__va(td_page_pa));
+}

And why do you need a special function just for control page(s)?

Quoted 31 lines
Quoted 31 lines

Otherwise you will have to explain them.

[...]

Quoted 26 lines
Quoted 19 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

Quoted 4 lines

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

As Chao suggested, will introduce state machine for vm and vcpu.

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Could you elaborate what will the state machine look like?

I need to understand it.

Not yet. Chao only propose to introduce state machine. Right now it's just an idea.

Then why state machine is better? I guess we need some concrete example to tell which is better?

Quoted 20 lines
Quoted 13 lines
Quoted 4 lines

How about this?

Quoted 8 lines

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Quoted 6 lines

Could you elaborate why it is still possible to have other thread removing pages from TD?

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

Quoted 5 lines

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Can you elaborate why TDH.MEM.{SEPT,PAGE}.REMOVE is slower than TDH.PHYMEM.PAGE.RECLAIM()?

And does the difference matter in practice, i.e. did you see using the former having noticeable performance downgrade?

Quoted 6 lines
Quoted 4 lines

IIUC, by reaching here, you must already have done VPFLUSHDONE, which should be called when you free vcpu?

Not necessarily.

OK. I got confused between TDH.VP.FLUSH and TDH.MNG.VPFLUSHDONE.

Quoted 14 lines
Quoted 5 lines

Freeing vcpus is done in
kvm_arch_destroy_vm(), which is _after_ mmu_notifier->release(), in which this tdx_mmu_release_keyid() is called?

guest memfd complicates things. The race is between guest memfd release and mmu notifier release. kvm_arch_destroy_vm() is called after closing all kvm fds including guest memfd.

Here is the example. Let's say, we have fds for vhost, guest_memfd, kvm vcpu, and kvm vm. The process is exiting. Please notice vhost increments the reference of the mmu to access guest (shared) memory.

Quoted 5 lines

exit_mmap():
Usually mmu notifier release is fired. But not yet because of vhost.

exit_files()
close vhost fd. vhost starts timer to issue mmput().

Why does it need to start a timer to issue mmput(), but not call mmput() directly?

Quoted 6 lines

close guest_memfd. kvm_gmem_release() calls kvm_mmu_unmap_gfn_range().
kvm_mmu_unmap_gfn_range() eventually this calls TDH.MEM.SEPT.REMOVE() and TDH.MEM.PAGE.REMOVE(). This takes time because it processes whole guest memory. Call kvm_put_kvm() at last.

Quoted 8 lines

During unmapping on behalf of guest memfd, the timer of vhost fires to call mmput(). It triggers mmu notifier release.

Close kvm vcpus/vm. they call kvm_put_kvm(). The last one calls kvm_destroy_vm().

It's ideal to free HKID first for efficiency. But KVM doesn't have control on the order of fds.

Firstly, what kinda performance efficiency gain are we talking about?

We cannot really tell whether it can be justified to use two different methods to tear down SEPT page because of this.

Even if it's worth to do, it is an optimization, which can/should be done later after you have put all building blocks together.

That being said, you are putting too many logic in this patch, i.e., it just doesn't make sense to release TDX keyID in the MMU code path in _this_ patch.

Quoted 5 lines
Quoted 3 lines

But here we are depending vcpus to be freed before tdx_mmu_release_hkid()?

Not necessarily.

I am wondering when is TDH.VP.FLUSH done? Supposedly it should be called when we free vcpus? But again this means you need to call TDH.MNG.VPFLUSHDONE _after_ freeing vcpus. And this looks conflicting if you make tdx_mmu_release_keyid() being called from MMU notifier.

#280 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 33 lines · Kai
Quoted 33 lines
Quoted 33 lines

[...]

Quoted 19 lines
Quoted 19 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

Quoted 8 lines
Quoted 4 lines

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

As Chao suggested, will introduce state machine for vm and vcpu.

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Could you elaborate what will the state machine look like?

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

I need to understand it.

Not yet. Chao only propose to introduce state machine. Right now it's just an idea.

Then why state machine is better? I guess we need some concrete example to tell which is better?

Something like the TD Life Cycle State Machine (Section 9.1 of TDX module spec[1])

[1]: https://cdrdv2.intel.com/v1/dl/getContent/733568

I don't have the code. But using a few boolean variables to track the state of TD and VCPU looks bad and hard to maintain and extend. At least, the state machine is well-documented.

#281 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to Huang, Kai
Quoted 69 lines · Kai
Quoted 28 lines · Isaku Yamahata
Quoted 25 lines · Kai
Quoted 22 lines · Isaku Yamahata
Quoted 19 lines · Kai

... continue the previous review ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 181

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);

From the name 'td_page_pa' we cannot tell whether it is a control page, but
this function is only intended for control page AFAICT, so perhaps a more specific name.

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 184

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID

"are" -> "is".

Are you sure it is TDCX, but not TDCS?

Quoted 9 lines
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

AFAICT TDCX is the control structure for 'vcpu', but here you are handling the control structure for the VM.

TDCS, TDVPR, and TDCX. Will update the comment.

But TDCX, TDVPR are vcpu-scoped. Do you want to mention them _here_?

So I'll make the patch that frees TDVPR, TDCX will change this comment.

Hmm.. Looking again, I am not sure why do we even need tdx_reclaim_control_page()?

It basically does tdx_reclaim_page() + free_page():

arch/x86/kvm/vmx/tdx.c +14 -0
+static void tdx_reclaim_control_page(unsigned long td_page_pa)
+{
+	WARN_ON_ONCE(!td_page_pa);
+
+	/*
+	 * TDCX are being reclaimed.  TDX module maps TDCX with HKID
+	 * assigned to the TD.  Here the cache associated to the TD
+	 * was already flushed by TDH.PHYMEM.CACHE.WB before here, So
+	 * cache doesn't need to be flushed again.
+	 */
+	if (tdx_reclaim_page(td_page_pa))
+		/*
+		 * Leak the page on failure:
+		 * tdx_reclaim_page() returns an error if and only if there's

an

arch/x86/kvm/vmx/tdx.c +9 -0
+		 * unexpected, fatal error, e.g. a SEAMCALL with bad params,
+		 * incorrect concurrency in KVM, a TDX Module bug, etc.
+		 * Retrying at a later point is highly unlikely to be
+		 * successful.
+		 * No log here as tdx_reclaim_page() already did.
+		 */
+		return;
+	free_page((unsigned long)__va(td_page_pa));
+}
Quoted 1 line

And why do you need a special function just for control page(s)?

We can revise the code to have common function for reclaiming page.

Quoted 34 lines
Quoted 34 lines
Quoted 34 lines

Otherwise you will have to explain them.

[...]

Quoted 19 lines
Quoted 19 lines
Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+void tdx_mmu_release_hkid(struct kvm *kvm)
+{
+	bool packages_allocated, targets_allocated;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages, targets;

arch/x86/kvm/vmx/tdx.c int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap) · line 232

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	u64 err;
+	int i;
+
+	if (!is_hkid_assigned(kvm_tdx))
+		return;
+
+	if (!is_td_created(kvm_tdx)) {
+		tdx_hkid_free(kvm_tdx);
+		return;
+	}

I lost tracking what does "td_created()" mean.

Quoted 8 lines
Quoted 4 lines

I guess it means: KeyID has been allocated to the TDX guest, but not yet programmed/configured.

Perhaps add a comment to remind the reviewer?

As Chao suggested, will introduce state machine for vm and vcpu.

https://lore.kernel.org/kvm/ZfvI8t7SlfIsxbmT@chao-email/

Could you elaborate what will the state machine look like?

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

I need to understand it.

Not yet. Chao only propose to introduce state machine. Right now it's just an idea.

Then why state machine is better? I guess we need some concrete example to tell which is better?

At this point we don't know which is better. I personally think it's worthwhile to give it a try. After experiment, we may discard or adapt the idea.

Because the TDX spec already defines its state machine, we could follow it.

Quoted 24 lines
Quoted 18 lines
Quoted 11 lines
Quoted 10 lines

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Quoted 6 lines

Could you elaborate why it is still possible to have other thread removing pages from TD?

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

Quoted 5 lines

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Quoted 5 lines

Can you elaborate why TDH.MEM.{SEPT,PAGE}.REMOVE is slower than TDH.PHYMEM.PAGE.RECLAIM()?

And does the difference matter in practice, i.e. did you see using the former having noticeable performance downgrade?

Yes. With HKID alive, we have to assume that vcpu can run still. It means TLB shootdown. The difference is 2 extra SEAMCALL + IPI synchronization for each guest private page. If the guest has hundreds of GB, the difference can be tens of minutes.

With HKID alive, we need to assume vcpu is alive.
- TDH.MEM.PAGE.REMOVE()
- TDH.PHYMEM.PAGE_WBINVD()
- TLB shoot down
- TDH.MEM.TRACK()
- IPI to other vcpus
- wait for other vcpu to exit

After freeing HKID
- TDH.PHYMEM.PAGE.RECLAIM()
We already flushed TLBs and memory cache.

Quoted 12 lines
Quoted 12 lines
Quoted 3 lines

Freeing vcpus is done in
kvm_arch_destroy_vm(), which is _after_ mmu_notifier->release(), in which this tdx_mmu_release_keyid() is called?

guest memfd complicates things. The race is between guest memfd release and mmu notifier release. kvm_arch_destroy_vm() is called after closing all kvm fds including guest memfd.

Here is the example. Let's say, we have fds for vhost, guest_memfd, kvm vcpu, and kvm vm. The process is exiting. Please notice vhost increments the reference of the mmu to access guest (shared) memory.

Quoted 8 lines
Quoted 5 lines

exit_mmap():
Usually mmu notifier release is fired. But not yet because of vhost.

exit_files()
close vhost fd. vhost starts timer to issue mmput().

Why does it need to start a timer to issue mmput(), but not call mmput() directly?

That's how vhost implements it. It's out of KVM control. Other component or user space as other thread can get reference to mmu or FDs. They can keep/free them as they like.

Quoted 8 lines
Quoted 8 lines

close guest_memfd. kvm_gmem_release() calls kvm_mmu_unmap_gfn_range().
kvm_mmu_unmap_gfn_range() eventually this calls TDH.MEM.SEPT.REMOVE() and TDH.MEM.PAGE.REMOVE(). This takes time because it processes whole guest memory. Call kvm_put_kvm() at last.

During unmapping on behalf of guest memfd, the timer of vhost fires to call mmput(). It triggers mmu notifier release.

Quoted 7 lines
Quoted 5 lines

Close kvm vcpus/vm. they call kvm_put_kvm(). The last one calls kvm_destroy_vm().

It's ideal to free HKID first for efficiency. But KVM doesn't have control on the order of fds.

Firstly, what kinda performance efficiency gain are we talking about?

2 extra SEAMCALL + IPI sync for each guest private page. If the guest memory is hundreds of GB, the difference can be tens of minutes.

Quoted 8 lines

We cannot really tell whether it can be justified to use two different methods to tear down SEPT page because of this.

Even if it's worth to do, it is an optimization, which can/should be done later after you have put all building blocks together.

That being said, you are putting too many logic in this patch, i.e., it just doesn't make sense to release TDX keyID in the MMU code path in _this_ patch.

I agree that this patch is too huge, and that we should break it into smaller patches.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

But here we are depending vcpus to be freed before tdx_mmu_release_hkid()?

Not necessarily.

I am wondering when is TDH.VP.FLUSH done? Supposedly it should be called when we free vcpus? But again this means you need to call TDH.MNG.VPFLUSHDONE _after_ freeing vcpus. And this looks conflicting if you make tdx_mmu_release_keyid() being called from MMU notifier.

tdx_mmu_release_keyid() call it explicitly for all vcpus.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

On 3/29/2024 4:39 AM, Isaku Yamahata wrote:

[...]

Quoted 31 lines
Quoted 21 lines
Quoted 13 lines
Quoted 13 lines
Quoted 10 lines

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Could you elaborate why it is still possible to have other thread removing pages from TD?

Quoted 8 lines
Quoted 3 lines

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Quoted 5 lines

Can you elaborate why TDH.MEM.{SEPT,PAGE}.REMOVE is slower than TDH.PHYMEM.PAGE.RECLAIM()?

And does the difference matter in practice, i.e. did you see using the former having noticeable performance downgrade?

Yes. With HKID alive, we have to assume that vcpu can run still. It means TLB shootdown. The difference is 2 extra SEAMCALL + IPI synchronization for each guest private page. If the guest has hundreds of GB, the difference can be tens of minutes.

Quoted 7 lines

With HKID alive, we need to assume vcpu is alive.
- TDH.MEM.PAGE.REMOVE()
- TDH.PHYMEM.PAGE_WBINVD()
- TLB shoot down
- TDH.MEM.TRACK()
- IPI to other vcpus
- wait for other vcpu to exit

Do we have a way to batch the TLB shoot down.
IIUC, in current implementation, TLB shoot down needs to be done for each page remove, right?

Quoted 66 lines

After freeing HKID
- TDH.PHYMEM.PAGE.RECLAIM()
We already flushed TLBs and memory cache.

Quoted 11 lines
Quoted 11 lines
Quoted 3 lines

Freeing vcpus is done in
kvm_arch_destroy_vm(), which is _after_ mmu_notifier->release(), in which this tdx_mmu_release_keyid() is called?

guest memfd complicates things. The race is between guest memfd release and mmu notifier release. kvm_arch_destroy_vm() is called after closing all kvm fds including guest memfd.

Here is the example. Let's say, we have fds for vhost, guest_memfd, kvm vcpu, and kvm vm. The process is exiting. Please notice vhost increments the reference of the mmu to access guest (shared) memory.

Quoted 7 lines
Quoted 5 lines

exit_mmap():
Usually mmu notifier release is fired. But not yet because of vhost.

exit_files()
close vhost fd. vhost starts timer to issue mmput().

Why does it need to start a timer to issue mmput(), but not call mmput() directly?

That's how vhost implements it. It's out of KVM control. Other component or user space as other thread can get reference to mmu or FDs. They can keep/free them as they like.

Quoted 8 lines
Quoted 8 lines

close guest_memfd. kvm_gmem_release() calls kvm_mmu_unmap_gfn_range().
kvm_mmu_unmap_gfn_range() eventually this calls TDH.MEM.SEPT.REMOVE() and TDH.MEM.PAGE.REMOVE(). This takes time because it processes whole guest memory. Call kvm_put_kvm() at last.

During unmapping on behalf of guest memfd, the timer of vhost fires to call mmput(). It triggers mmu notifier release.

Quoted 6 lines
Quoted 5 lines

Close kvm vcpus/vm. they call kvm_put_kvm(). The last one calls kvm_destroy_vm().

It's ideal to free HKID first for efficiency. But KVM doesn't have control on the order of fds.

Firstly, what kinda performance efficiency gain are we talking about?

2 extra SEAMCALL + IPI sync for each guest private page. If the guest memory is hundreds of GB, the difference can be tens of minutes.

Quoted 8 lines

We cannot really tell whether it can be justified to use two different methods to tear down SEPT page because of this.

Even if it's worth to do, it is an optimization, which can/should be done later after you have put all building blocks together.

That being said, you are putting too many logic in this patch, i.e., it just doesn't make sense to release TDX keyID in the MMU code path in _this_ patch.

I agree that this patch is too huge, and that we should break it into smaller patches.

Quoted 6 lines
Quoted 2 lines
Quoted 1 line

But here we are depending vcpus to be freed before tdx_mmu_release_hkid()?

Not necessarily.

I am wondering when is TDH.VP.FLUSH done? Supposedly it should be called when we free vcpus? But again this means you need to call TDH.MNG.VPFLUSHDONE _after_ freeing vcpus. And this looks conflicting if you make tdx_mmu_release_keyid() being called from MMU notifier.

tdx_mmu_release_keyid() call it explicitly for all vcpus.

#283 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 44 lines · Binbin Wu

On 3/29/2024 4:39 AM, Isaku Yamahata wrote:

[...]

Quoted 31 lines
Quoted 21 lines
Quoted 13 lines
Quoted 13 lines
Quoted 10 lines

How about this?

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Could you elaborate why it is still possible to have other thread removing pages from TD?

Quoted 8 lines
Quoted 3 lines

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Quoted 5 lines

Can you elaborate why TDH.MEM.{SEPT,PAGE}.REMOVE is slower than TDH.PHYMEM.PAGE.RECLAIM()?

And does the difference matter in practice, i.e. did you see using the former having noticeable performance downgrade?

Yes. With HKID alive, we have to assume that vcpu can run still. It means TLB shootdown. The difference is 2 extra SEAMCALL + IPI synchronization for each guest private page. If the guest has hundreds of GB, the difference can be tens of minutes.

Quoted 7 lines

With HKID alive, we need to assume vcpu is alive.
- TDH.MEM.PAGE.REMOVE()
- TDH.PHYMEM.PAGE_WBINVD()
- TLB shoot down
- TDH.MEM.TRACK()
- IPI to other vcpus
- wait for other vcpu to exit

Quoted 3 lines

Do we have a way to batch the TLB shoot down.
IIUC, in current implementation, TLB shoot down needs to be done for each page remove, right?

That's right because the TDP MMU allows multiple vcpus to operate on EPT concurrently. Batching makes the logic more complex. It's straightforward to use the mmu notifier to know that we start to destroy the guest.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to Isaku Yamahata

[...]

Quoted 4 lines
Quoted 2 lines

And why do you need a special function just for control page(s)?

We can revise the code to have common function for reclaiming page.

I interpret this as you will remove tdx_reclaim_control_page(), and have one function to reclaim _ALL_ TDX private pages.

Quoted 49 lines
Quoted 26 lines
Quoted 20 lines
Quoted 13 lines
Quoted 4 lines

How about this?

Quoted 8 lines

/*
* We need three SEAMCALLs, TDH.MNG.VPFLUSHDONE(), TDH.PHYMEM.CACHE.WB(), and
* TDH.MNG.KEY.FREEID() to free the HKID.
* Other threads can remove pages from TD. When the HKID is assigned, we need
* to use TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE().
* TDH.PHYMEM.PAGE.RECLAIM() is needed when the HKID is free. Get lock to not
* present transient state of HKID.
*/

Quoted 6 lines

Could you elaborate why it is still possible to have other thread removing pages from TD?

I am probably missing something, but the thing I don't understand is why this function is triggered by MMU release? All the things done in this function don't seem to be related to MMU at all.

Quoted 5 lines

The KVM releases EPT pages on MMU notifier release. kvm_mmu_zap_all() does. If we follow that way, kvm_mmu_zap_all() zaps all the Secure-EPTs by TDH.MEM.SEPT.REMOVE() or TDH.MEM.PAGE.REMOVE(). Because TDH.MEM.{SEPT, PAGE}.REMOVE() is slow, we can free HKID before kvm_mmu_zap_all() to use TDH.PHYMEM.PAGE.RECLAIM().

Quoted 5 lines

Can you elaborate why TDH.MEM.{SEPT,PAGE}.REMOVE is slower than TDH.PHYMEM.PAGE.RECLAIM()?

And does the difference matter in practice, i.e. did you see using the former having noticeable performance downgrade?

Yes. With HKID alive, we have to assume that vcpu can run still. It means TLB shootdown. The difference is 2 extra SEAMCALL + IPI synchronization for each guest private page. If the guest has hundreds of GB, the difference can be tens of minutes.

With HKID alive, we need to assume vcpu is alive.
- TDH.MEM.PAGE.REMOVE()
- TDH.PHYMEM.PAGE_WBINVD()
- TLB shoot down
- TDH.MEM.TRACK()
- IPI to other vcpus
- wait for other vcpu to exit

After freeing HKID
- TDH.PHYMEM.PAGE.RECLAIM()
We already flushed TLBs and memory cache.

Quoted 1 line
Quoted 1 line
Quoted 1 line

[...]

Quoted 5 lines
Quoted 2 lines

Firstly, what kinda performance efficiency gain are we talking about?

2 extra SEAMCALL + IPI sync for each guest private page. If the guest memory is hundreds of GB, the difference can be tens of minutes.

[...]

Quoted 5 lines
Quoted 5 lines

We cannot really tell whether it can be justified to use two different methods to tear down SEPT page because of this.

Quoted 8 lines
Quoted 5 lines

Even if it's worth to do, it is an optimization, which can/should be done later after you have put all building blocks together.

That being said, you are putting too many logic in this patch, i.e., it just doesn't make sense to release TDX keyID in the MMU code path in _this_ patch.

I agree that this patch is too huge, and that we should break it into smaller patches.

IMHO it's not only breaking into smaller pieces, but also you are mixing performance optimization and essential functionalities together.

Moving reclaiming TDX private KeyID to MMU notifier (in order to have a better performance when shutting down TDX guest) depends on a lot SEPT details (how to reclaim private page, TLB flush etc), which haven't yet been mentioned at all.

It's hard to review code like this.

I think here in this patch, we should just put reclaiming TDX keyID to the "normal" place. After you have done all SEPT (and related) patches, you can have a patch to improve the performance:

KVM: TDX: Improve TDX guest shutdown latency

Then you put your performance data there, i.e., "tens of minutes difference for TDX guest with hundreds of GB memory", to justify that patch.

#285 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to [email protected]

... to continue the previous review ...

Quoted 15 lines
arch/x86/kvm/vmx/tdx.c +14 -0
+static int __tdx_td_init(struct kvm *kvm)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	cpumask_var_t packages;
+	unsigned long *tdcs_pa = NULL;
+	unsigned long tdr_pa = 0;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	ret = tdx_guest_keyid_alloc();
+	if (ret < 0)
+		return ret;
+	kvm_tdx->hkid = ret;

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 442

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		goto free_hkid;
+	tdr_pa = __pa(va);
+
+	tdcs_pa = kcalloc(tdx_info->nr_tdcs_pages, sizeof(*kvm_tdx->tdcs_pa),
+			  GFP_KERNEL_ACCOUNT | __GFP_ZERO);
+	if (!tdcs_pa)
+		goto free_tdr;

Empty line.

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 453

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c +11 -0
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va)
+			goto free_tdcs;
+		tdcs_pa[i] = __pa(va);
+	}
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL)) {
+		ret = -ENOMEM;
+		goto free_tdcs;
+	}

Empty line.

Quoted 22 lines
arch/x86/kvm/vmx/tdx.c +22 -0
+	cpus_read_lock();
+	/*
+	 * Need at least one CPU of the package to be online in order to
+	 * program all packages for host key id.  Check it.
+	 */
+	for_each_present_cpu(i)
+		cpumask_set_cpu(topology_physical_package_id(i), packages);
+	for_each_online_cpu(i)
+		cpumask_clear_cpu(topology_physical_package_id(i), packages);
+	if (!cpumask_empty(packages)) {
+		ret = -EIO;
+		/*
+		 * Because it's hard for human operator to figure out the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
+		pr_warn_ratelimited(MSG_ALLPKG);
+		goto free_packages;
+	}
+
+	/*
+	 * Acquire global lock to avoid TDX_OPERAND_BUSY:

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 * TDH.MNG.CREATE and other APIs try to lock the global Key Owner
+	 * Table (KOT) to track the assigned TDX private HKID.  It doesn't spin
+	 * to acquire the lock, returns TDX_OPERAND_BUSY instead, and let the
+	 * caller to handle the contention.  This is because of time limitation
+	 * usable inside the TDX module and OS/VMM knows better about process
+	 * scheduling.
+	 *
+	 * APIs to acquire the lock of KOT:
+	 * TDH.MNG.CREATE, TDH.MNG.KEY.FREEID, TDH.MNG.VPFLUSHDONE, and
+	 * TDH.PHYMEM.CACHE.WB. > +	 */

Don't need to mention all SEAMCALLs here, but put a comment where appliciable, i.e., where they are used.

/*
* TDH.MNG.CREATE tries to grab the global TDX module and fails
* with TDX_OPERAND_BUSY when it fails to grab. Take the global
* lock to prevent it from failure.
*/

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 489

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	mutex_lock(&tdx_lock);
+	err = tdh_mng_create(tdr_pa, kvm_tdx->hkid);
+	mutex_unlock(&tdx_lock);

Empty line.

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 498

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+	if (err == TDX_RND_NO_ENTROPY) {
+		ret = -EAGAIN;
+		goto free_packages;
+	}
+	if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_CREATE, err, NULL);
+		ret = -EIO;
+		goto free_packages;
+	}

I would prefer more empty lines.

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 513

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */

IIUC the race can only happen when you are creating multiple TDX guests simulatenously? Please clarify this in the comment.

And I even don't think you need all these TDX module details:

/*
* Concurrent run of TDH.MNG.KEY.CONFIG on the same
* package resluts in TDX_OPERAND_BUSY. When creating
* multiple TDX guests simultaneously this can run
* concurrently. Take the per-package lock to
* serialize.
*/

Quoted 23 lines
arch/x86/kvm/vmx/tdx.c +23 -0
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 546

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */

Then, how about renaming this function to __tdx_td_create()?

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 563

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);

The code to "free TDCS pages in a loop and free the array" is done below with duplicated code. I am wondering whether we have way to eliminate one.

But I have lost track here, so perhaps we can review again after we split the patch to smaller pieces.

Quoted 44 lines
arch/x86/kvm/vmx/tdx.c +27 -1
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  {
  	struct kvm_tdx_cmd tdx_cmd;
@@ -215,12 +664,13 @@ static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
 
  static int __init tdx_module_setup(void)
  {
-	u16 num_cpuid_config;
+	u16 num_cpuid_config, tdcs_base_size;
  	int ret;
  	u32 i;
 
  	struct tdx_md_map mds[] = {
  		TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+		TDX_MD_MAP(TDCS_BASE_SIZE, &tdcs_base_size),
  	};
 
  	struct tdx_metadata_field_mapping fields[] = {

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 727

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +2 -0
@@ -273,6 +723,8 @@ static int __init tdx_module_setup(void)
  		c->edx = ecx_edx >> 32;
  	}
 
+	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+

Round up the 'tdcs_base_size' to make sure you have enough room, or put a WARN() here if not page aligned?

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 776

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +2 -0
  	return 0;
 
  error_out:
@@ -319,13 +771,27 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  	struct tdx_enabled enable = {
  		.err = ATOMIC_INIT(0),
  	};
+	int max_pkgs;
  	int r = 0;
+	int i;

Nit: you can put the 3 into one line.

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 779

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	if (!cpu_feature_enabled(X86_FEATURE_MOVDIR64B)) {
+		pr_warn("MOVDIR64B is reqiured for TDX\n");

It's better to make it more clear:

"Disable TDX: MOVDIR64B is not supported or disabled by the kernel."

Or, to match below:

"Cannot enable TDX w/o MOVDIR64B".

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		return -EOPNOTSUPP;
+	}
  	if (!enable_ept) {
  		pr_warn("Cannot enable TDX with EPT disabled\n");
  		return -EINVAL;

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 794

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
  	}
 
+	max_pkgs = topology_max_packages();
+	tdx_mng_key_config_lock = kcalloc(max_pkgs, sizeof(*tdx_mng_key_config_lock),
+				   GFP_KERNEL);
+	if (!tdx_mng_key_config_lock)
+		return -ENOMEM;
+	for (i = 0; i < max_pkgs; i++)
+		mutex_init(&tdx_mng_key_config_lock[i]);
+

Using a per-socket lock looks a little bit overkill to me. I don't know whether we need to do in the initial version. Will leave to others.

Please at least add a comment to explain this is for better performance when creating multiple TDX guests IIUC?

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 819

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +1 -0
  	if (!zalloc_cpumask_var(&enable.enabled, GFP_KERNEL)) {
  		r = -ENOMEM;
  		goto out;
@@ -350,4 +816,5 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  void tdx_hardware_unsetup(void)
  {
  	kfree(tdx_info);
+	kfree(tdx_mng_key_config_lock);

The kernel actually has a mutex_destroy(). It is empty when CONFIG_DEBUG_LOCK_ALLOC is off, but I think it should be standard proceedure to also mutex_destory()?

[...]

#286 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 21 lines · Kai
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 513

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */

IIUC the race can only happen when you are creating multiple TDX guests simulatenously? Please clarify this in the comment.

And I even don't think you need all these TDX module details:

Quoted 7 lines

/*
* Concurrent run of TDH.MNG.KEY.CONFIG on the same
* package resluts in TDX_OPERAND_BUSY. When creating
* multiple TDX guests simultaneously this can run
* concurrently. Take the per-package lock to
* serialize.
*/

As pointed by Chao, those mutex will be dropped.
https://lore.kernel.org/kvm/ZfpwIespKy8qxWWE@chao-email/
Also we would simplify cpu masks to track which package is online/offline, which cpu to use for each package somehow.

Quoted 27 lines
Quoted 27 lines
arch/x86/kvm/vmx/tdx.c +27 -0
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 546

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */

Then, how about renaming this function to __tdx_td_create()?

So do we want to rename also ioctl name for consistency? i.e. KVM_TDX_INIT_VM => KVM_TDX_CREATE_VM.

I don't have strong opinion those names. Maybe
KVM_TDX_{INIT, CREATE, or CONFIG}_VM?
And we can rename the function name to match it.

Quoted 21 lines
Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 563

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);

The code to "free TDCS pages in a loop and free the array" is done below with duplicated code. I am wondering whether we have way to eliminate one.

Quoted 2 lines

But I have lost track here, so perhaps we can review again after we split the patch to smaller pieces.

Surely we can simplify it. Originally we had a spin lock and I had to separate blocking memory allocation from its usage with this error clean up path. Now it's mutex, we mix page allocation with its usage.

Quoted 40 lines
Quoted 40 lines
arch/x86/kvm/vmx/tdx.c +27 -1
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
  int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
  {
  	struct kvm_tdx_cmd tdx_cmd;
@@ -215,12 +664,13 @@ static int tdx_md_read(struct tdx_md_map *maps, int nr_maps)
  static int __init tdx_module_setup(void)
  {
-	u16 num_cpuid_config;
+	u16 num_cpuid_config, tdcs_base_size;
  	int ret;
  	u32 i;
  	struct tdx_md_map mds[] = {
  		TDX_MD_MAP(NUM_CPUID_CONFIG, &num_cpuid_config),
+		TDX_MD_MAP(TDCS_BASE_SIZE, &tdcs_base_size),
  	};
  	struct tdx_metadata_field_mapping fields[] = {
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 726

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +2 -0
@@ -273,6 +723,8 @@ static int __init tdx_module_setup(void)
  		c->edx = ecx_edx >> 32;
  	}
+	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+

Round up the 'tdcs_base_size' to make sure you have enough room, or put a WARN() here if not page aligned?

Ok, will add round up. Same for tdvps_base_size.
I can't find about those sizes and page size in the TDX spec. Although TDH.MNG.ADDCX() and TDH.VP.ADDCX() imply that those sizes are multiple of PAGE SIZE, the spec doesn't guarantee it. I think silent round up is better than WARN() because we can do nothing about those values the TDX module provides.

Quoted 17 lines

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 776

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +2 -0
  	return 0;
  error_out:
@@ -319,13 +771,27 @@ int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops)
  	struct tdx_enabled enable = {
  		.err = ATOMIC_INIT(0),
  	};
+	int max_pkgs;
  	int r = 0;
+	int i;

Nit: you can put the 3 into one line.

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 779

Quoted 2 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+	if (!cpu_feature_enabled(X86_FEATURE_MOVDIR64B)) {
+		pr_warn("MOVDIR64B is reqiured for TDX\n");

It's better to make it more clear:

Quoted 5 lines

"Disable TDX: MOVDIR64B is not supported or disabled by the kernel."

Or, to match below:

"Cannot enable TDX w/o MOVDIR64B".

Ok.

Quoted 18 lines
Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +2 -0
+		return -EOPNOTSUPP;
+	}
  	if (!enable_ept) {
  		pr_warn("Cannot enable TDX with EPT disabled\n");

arch/x86/kvm/vmx/tdx.c int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops) · line 794

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +8 -0
  		return -EINVAL;
  	}
+	max_pkgs = topology_max_packages();
+	tdx_mng_key_config_lock = kcalloc(max_pkgs, sizeof(*tdx_mng_key_config_lock),
+				   GFP_KERNEL);
+	if (!tdx_mng_key_config_lock)
+		return -ENOMEM;
+	for (i = 0; i < max_pkgs; i++)
+		mutex_init(&tdx_mng_key_config_lock[i]);
+

Using a per-socket lock looks a little bit overkill to me. I don't know whether we need to do in the initial version. Will leave to others.

Quoted 2 lines

Please at least add a comment to explain this is for better performance when creating multiple TDX guests IIUC?

Will delete the mutex and simply the related logic.

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

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 32 lines · Isaku
Quoted 21 lines · Kai
Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	kvm_tdx->tdr_pa = tdr_pa;
+
+	for_each_online_cpu(i) {
+		int pkg = topology_physical_package_id(i);
+

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 513

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		if (cpumask_test_and_set_cpu(pkg, packages))
+			continue;
+
+		/*
+		 * Program the memory controller in the package with an
+		 * encryption key associated to a TDX private host key id
+		 * assigned to this TDR.  Concurrent operations on same memory
+		 * controller results in TDX_OPERAND_BUSY.  Avoid this race by
+		 * mutex.
+		 */

IIUC the race can only happen when you are creating multiple TDX guests simulatenously? Please clarify this in the comment.

And I even don't think you need all these TDX module details:

Quoted 7 lines

/*
* Concurrent run of TDH.MNG.KEY.CONFIG on the same
* package resluts in TDX_OPERAND_BUSY. When creating
* multiple TDX guests simultaneously this can run
* concurrently. Take the per-package lock to
* serialize.
*/

Quoted 4 lines

As pointed by Chao, those mutex will be dropped.
https://lore.kernel.org/kvm/ZfpwIespKy8qxWWE@chao-email/
Also we would simplify cpu masks to track which package is online/offline, which cpu to use for each package somehow.

Please see my reply there. I might be missing something, though.

Quoted 38 lines
Quoted 29 lines
Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +27 -0
+		mutex_lock(&tdx_mng_key_config_lock[pkg]);
+		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
+				      &kvm_tdx->tdr_pa, true);
+		mutex_unlock(&tdx_mng_key_config_lock[pkg]);
+		if (ret)
+			break;
+	}
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+	if (ret) {
+		i = 0;
+		goto teardown;
+	}
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 546

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */

Then, how about renaming this function to __tdx_td_create()?

Quoted 2 lines

So do we want to rename also ioctl name for consistency? i.e. KVM_TDX_INIT_VM => KVM_TDX_CREATE_VM.

Hmm.. but this __tdx_td_create() (the __tdx_td_init() in this patch) is called via kvm_x86_ops->vm_init(), but not IOCTL()?

If I read correctly, only TDH.MNG.INIT is called via IOCTL(), in that sense it makes more sense to name the IOCTL() as KVM_TDX_INIT_VM.

Quoted 5 lines

I don't have strong opinion those names. Maybe
KVM_TDX_{INIT, CREATE, or CONFIG}_VM?
And we can rename the function name to match it.

#288 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

In reply to [email protected]

On 2/26/2024 4:25 PM, [email protected] wrote:

...

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 533

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;

So userspace is expected to stop creating TD and quit on this?

If so, it exposes an DOS attack surface that malicious users in another can drain the entropy with busy-loop on RDSEED.

Can you clarify why it's hard to allow userspace to retry? To me, it's OK to retry that "teardown" cleans everything up, and userspace and issue the KVM_TDX_INIT_VM again.

Quoted 55 lines
arch/x86/kvm/vmx/tdx.c +55 -0
+			goto teardown;
+		}
+		if (WARN_ON_ONCE(err)) {
+			pr_tdx_error(TDH_MNG_ADDCX, err, NULL);
+			ret = -EIO;
+			goto teardown;
+		}
+	}
+
+	/*
+	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
+	 * ioctl() to define the configure CPUID values for the TD.
+	 */
+	return 0;
+
+	/*
+	 * The sequence for freeing resources from a partially initialized TD
+	 * varies based on where in the initialization flow failure occurred.
+	 * Simply use the full teardown and destroy, which naturally play nice
+	 * with partial initialization.
+	 */
+teardown:
+	for (; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i]) {
+			free_page((unsigned long)__va(tdcs_pa[i]));
+			tdcs_pa[i] = 0;
+		}
+	}
+	if (!kvm_tdx->tdcs_pa)
+		kfree(tdcs_pa);
+	tdx_mmu_release_hkid(kvm);
+	tdx_vm_free(kvm);
+	return ret;
+
+free_packages:
+	cpus_read_unlock();
+	free_cpumask_var(packages);
+free_tdcs:
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		if (tdcs_pa[i])
+			free_page((unsigned long)__va(tdcs_pa[i]));
+	}
+	kfree(tdcs_pa);
+	kvm_tdx->tdcs_pa = NULL;
+
+free_tdr:
+	if (tdr_pa)
+		free_page((unsigned long)__va(tdr_pa));
+	kvm_tdx->tdr_pa = 0;
+free_hkid:
+	if (is_hkid_assigned(kvm_tdx))
+		tdx_hkid_free(kvm_tdx);
+	return ret;
+}
+
#289 lore raw

Re: [PATCH v19 038/130] KVM: TDX: create/destroy VM structure

Quoted 14 lines · Xiaoyao Li

On 2/26/2024 4:25 PM, [email protected] wrote:

...

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 533

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+
+	kvm_tdx->tdcs_pa = tdcs_pa;
+	for (i = 0; i < tdx_info->nr_tdcs_pages; i++) {
+		err = tdh_mng_addcx(kvm_tdx->tdr_pa, tdcs_pa[i]);
+		if (err == TDX_RND_NO_ENTROPY) {
+			/* Here it's hard to allow userspace to retry. */
+			ret = -EBUSY;

So userspace is expected to stop creating TD and quit on this?

Quoted 6 lines

If so, it exposes an DOS attack surface that malicious users in another can drain the entropy with busy-loop on RDSEED.

Can you clarify why it's hard to allow userspace to retry? To me, it's OK to retry that "teardown" cleans everything up, and userspace and issue the KVM_TDX_INIT_VM again.

The current patch has complicated error recovery path. After simplifying the code, it would be possible to return -EAGAIN in this patch.

For the retry case, we need to avoid TDH.MNG.CREATE() and TDH.MNG.KEY.CONFIG().

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

PATCH v19 39/130 KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX requires additional parameters for TDX VM for confidential execution to protect the confidentiality of its memory contents and CPU state from any other software, including VMM. When creating a guest TD VM before creating vcpu, the number of vcpu, TSC frequency (the values are the same among vcpus, and it can't change.) CPUIDs which the TDX module emulates. Guest TDs can trust those CPUIDs and sha384 values for measurement.

Add a new subcommand, KVM_TDX_INIT_VM, to pass parameters for the TDX guest. It assigns an encryption key to the TDX guest for memory encryption. TDX encrypts memory per guest basis. The device model, say qemu, passes per-VM parameters for the TDX guest. The maximum number of vcpus, TSC frequency (TDX guest has fixed VM-wide TSC frequency, not per vcpu. The TDX guest can not change it.), attributes (production or debug), available extended features (which configure guest XCR0, IA32_XSS MSR), CPUIDs, sha384 measurements, etc.

Call this subcommand before creating vcpu and KVM_SET_CPUID2, i.e. CPUID configurations aren't available yet. So CPUIDs configuration values need to be passed in struct kvm_tdx_init_vm. The device model's responsibility to make this CPUID config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

---
v19:
- Check NO_RBP_MOD of feature0 and set it
- Update the comment for PT and CET

v18:
- remove the change of tools/arch/x86/include/uapi/asm/kvm.h
- typo in comment. sha348 => sha384
- updated comment in setup_tdparams_xfam()
- fix setup_tdparams_xfam() to use init_vm instead of td_params

v15 -> v16:
- Removed AMX check as the KVM upstream supports AMX.
- Added CET flag to guest supported xss

v14 -> v15:
- add check if the reserved area of init_vm is zero

---
 arch/x86/include/uapi/asm/kvm.h |  27 ++++
 arch/x86/kvm/cpuid.c            |   7 +
 arch/x86/kvm/cpuid.h            |   2 +
 arch/x86/kvm/vmx/tdx.c          | 273 ++++++++++++++++++++++++++++++--
 arch/x86/kvm/vmx/tdx.h          |  18 +++
 arch/x86/kvm/vmx/tdx_arch.h     |   6 +
 6 files changed, 323 insertions(+), 10 deletions(-)
arch/x86/include/uapi/asm/kvm.h +27 -0
index e28189c81691..9ac0246bd974 100644
@@ -570,6 +570,7 @@ struct kvm_pmu_event_filter {
 /* Trust Domain eXtension sub-ioctl() commands. */
 enum kvm_tdx_cmd_id {
 	KVM_TDX_CAPABILITIES = 0,
+	KVM_TDX_INIT_VM,
 
 	KVM_TDX_CMD_NR_MAX,
 };
@@ -621,4 +622,30 @@ struct kvm_tdx_capabilities {
 	struct kvm_tdx_cpuid_config cpuid_configs[];
 };
 
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha384 digest */
+	/*
+	 * For future extensibility to make sizeof(struct kvm_tdx_init_vm) = 8KB.
+	 * This should be enough given sizeof(TD_PARAMS) = 1024.
+	 * 8KB was chosen given because
+	 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(=256) = 8KB.
+	 */
+	__u64 reserved[1004];
+
+	/*
+	 * Call KVM_TDX_INIT_VM before vcpu creation, thus before
+	 * KVM_SET_CPUID2.
+	 * This configuration supersedes KVM_SET_CPUID2s for VCPUs because the
+	 * TDX module directly virtualizes those CPUIDs without VMM.  The user
+	 * space VMM, e.g. qemu, should make KVM_SET_CPUID2 consistent with
+	 * those values.  If it doesn't, KVM may have wrong idea of vCPUIDs of
+	 * the guest, and KVM may wrongly emulate CPUIDs or MSRs that the TDX
+	 * module doesn't virtualize.
+	 */
+	struct kvm_cpuid2 cpuid;
+};
+
 #endif /* _ASM_X86_KVM_H */
arch/x86/kvm/cpuid.c +7 -0
index adba49afb5fe..8cdcd6f406aa 100644
@@ -1443,6 +1443,13 @@ int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid,
 	return r;
 }
 
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry2);
+
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
 						    u32 function, u32 index)
 {
arch/x86/kvm/cpuid.h +2 -0
index 856e3037e74f..215d1c68c6d1 100644
@@ -13,6 +13,8 @@ void kvm_set_cpu_caps(void);
 
 void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu);
 void kvm_update_pv_runtime(struct kvm_vcpu *vcpu);
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(struct kvm_cpuid_entry2 *entries,
+					       int nent, u32 function, u64 index);
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
 						    u32 function, u32 index);
 struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,
arch/x86/kvm/vmx/tdx.c +263 -10

331 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +18 -0
index ae117f864cfb..184fe394da86 100644
@@ -12,7 +12,11 @@ struct kvm_tdx {
 	unsigned long tdr_pa;
 	unsigned long *tdcs_pa;
 
+	u64 attributes;
+	u64 xfam;
 	int hkid;
+
+	u64 tsc_offset;
 };
 
 struct vcpu_tdx {
@@ -39,6 +43,20 @@ static inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
 {
 	return container_of(vcpu, struct vcpu_tdx, vcpu);
 }
+
+static __always_inline u64 td_tdcs_exec_read64(struct kvm_tdx *kvm_tdx, u32 field)
+{
+	struct tdx_module_args out;
+	u64 err;
+
+	err = tdh_mng_rd(kvm_tdx->tdr_pa, TDCS_EXEC(field), &out);
+	if (unlikely(err)) {
+		pr_err("TDH_MNG_RD[EXEC.0x%x] failed: 0x%llx\n", field, err);
+		return 0;
+	}
+	return out.r8;
+}
+
 #else
 struct kvm_tdx {
 	struct kvm kvm;
arch/x86/kvm/vmx/tdx_arch.h +6 -0
index e2c1a6f429d7..efc3c61c14ab 100644
@@ -117,6 +117,12 @@ struct tdx_cpuid_value {
 #define TDX_TD_ATTRIBUTE_KL		BIT_ULL(31)
 #define TDX_TD_ATTRIBUTE_PERFMON	BIT_ULL(63)
 
+/*
+ * TODO: Once XFEATURE_CET_{U, S} in arch/x86/include/asm/fpu/types.h is
+ * defined, Replace these with define ones.
+ */
+#define TDX_TD_XFAM_CET	(BIT(11) | BIT(12))
+
 /*
  * TD_PARAMS is provided as an input to TDH_MNG_INIT, the size of which is 1024B.
  */
Signature · 1 line
2.25.1
#291 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 1 line · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

...

Quoted 17 lines

TDX requires additional parameters for TDX VM for confidential execution to protect the confidentiality of its memory contents and CPU state from any other software, including VMM. When creating a guest TD VM before creating vcpu, the number of vcpu, TSC frequency (the values are the same among vcpus, and it can't change.) CPUIDs which the TDX module emulates. Guest TDs can trust those CPUIDs and sha384 values for measurement.

Add a new subcommand, KVM_TDX_INIT_VM, to pass parameters for the TDX guest. It assigns an encryption key to the TDX guest for memory encryption. TDX encrypts memory per guest basis. The device model, say qemu, passes per-VM parameters for the TDX guest. The maximum number of vcpus, TSC frequency (TDX guest has fixed VM-wide TSC frequency, not per vcpu. The TDX guest can not change it.), attributes (production or debug), available extended features (which configure guest XCR0, IA32_XSS MSR), CPUIDs, sha384 measurements, etc.

Quoted 7 lines

Call this subcommand before creating vcpu and KVM_SET_CPUID2, i.e. CPUID configurations aren't available yet. So CPUIDs configuration values need to be passed in struct kvm_tdx_init_vm. The device model's responsibility to make this CPUID config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

the SOB chain makes no sense.

Quoted 22 lines
arch/x86/kvm/vmx/tdx.c +22 -0
+static void setup_tdparams_cpuids(struct kvm_cpuid2 *cpuid,
+				  struct td_params *td_params)
+{
+	int i;
+
+	/*
+	 * td_params.cpuid_values: The number and the order of cpuid_value must
+	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
+	 * It's assumed that td_params was zeroed.
+	 */
+	for (i = 0; i < tdx_info->num_cpuid_config; i++) {
+		const struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+		/* KVM_TDX_CPUID_NO_SUBLEAF means index = 0. */
+		u32 index = c->sub_leaf == KVM_TDX_CPUID_NO_SUBLEAF ? 0 : c->sub_leaf;
+		const struct kvm_cpuid_entry2 *entry =
+			kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent,
+					      c->leaf, index);
+		struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+		if (!entry)
+			continue;
+

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 482

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		/*
+		 * tdsysinfo.cpuid_configs[].{eax, ebx, ecx, edx}
+		 * bit 1 means it can be configured to zero or one.
+		 * bit 0 means it must be zero.
+		 * Mask out non-configurable bits.
+		 */
+		value->eax = entry->eax & c->eax;
+		value->ebx = entry->ebx & c->ebx;
+		value->ecx = entry->ecx & c->ecx;
+		value->edx = entry->edx & c->edx;

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +28 -0
+	}
+}
+
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+
+	/* Setup td_params.xfam */
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+
+	/*
+	 * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+	 * and, CET support.
+	 */
+	guest_supported_xss &=

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 520

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		(kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
+#define MSG_LBR	"TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH properly.\n"
+		pr_warn(MSG_LBR);

Drop the pr_warn() because userspace can trigger it at will.

I don't think KVM needs to relay TDX module capabilities to userspace as-is. KVM should advertise a feature only if both TDX module's and KVM's support are in place. if KVM masked out LBR and PERFMON, it should be a problem of userspace and we don't need to warn here.

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+		return -EOPNOTSUPP;
+	}
+
+	return 0;

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 534

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+}
+
+static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
+			struct kvm_tdx_init_vm *init_vm)
+{
+	struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+	int ret;
+
+	if (kvm->created_vcpus)
+		return -EBUSY;

-EINVAL

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 542

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+	if (init_vm->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		/*
+		 * TODO: save/restore PMU related registers around TDENTER.
+		 * Once it's done, remove this guard.
+		 */
+#define MSG_PERFMON	"TD doesn't support perfmon yet. KVM needs to save/restore host perf registers properly.\n"
+		pr_warn(MSG_PERFMON);

drop the pr_warn().

Quoted 74 lines
arch/x86/kvm/vmx/tdx.c +31 -0
+		return -EOPNOTSUPP;
+	}
+
+	td_params->max_vcpus = kvm->max_vcpus;
+	td_params->attributes = init_vm->attributes;
+	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;
+	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
+
+	ret = setup_tdparams_eptp_controls(cpuid, td_params);
+	if (ret)
+		return ret;
+	setup_tdparams_cpuids(cpuid, td_params);
+	ret = setup_tdparams_xfam(cpuid, td_params);
+	if (ret)
+		return ret;
+
+#define MEMCPY_SAME_SIZE(dst, src)				\
+	do {							\
+		BUILD_BUG_ON(sizeof(dst) != sizeof(src));	\
+		memcpy((dst), (src), sizeof(dst));		\
+	} while (0)
+
+	MEMCPY_SAME_SIZE(td_params->mrconfigid, init_vm->mrconfigid);
+	MEMCPY_SAME_SIZE(td_params->mrowner, init_vm->mrowner);
+	MEMCPY_SAME_SIZE(td_params->mrownerconfig, init_vm->mrownerconfig);
+
+	return 0;
+}
+
+static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
+			 u64 *seamcall_err)
{
	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
(quoted diff) +1 -0
+	struct tdx_module_args out;
	cpumask_var_t packages;
	unsigned long *tdcs_pa = NULL;
	unsigned long tdr_pa = 0;
arch/x86/kvm/vmx/tdx.c +18 -4
@@ -426,6 +581,7 @@ static int __tdx_td_init(struct kvm *kvm)
 	int ret, i;
 	u64 err;
 
+	*seamcall_err = 0;
 	ret = tdx_guest_keyid_alloc();
 	if (ret < 0)
 		return ret;
@@ -540,10 +696,23 @@ static int __tdx_td_init(struct kvm *kvm)
 		}
 	}
 
-	/*
-	 * Note, TDH_MNG_INIT cannot be invoked here.  TDH_MNG_INIT requires a dedicated
-	 * ioctl() to define the configure CPUID values for the TD.
-	 */
+	err = tdh_mng_init(kvm_tdx->tdr_pa, __pa(td_params), &out);
+	if ((err & TDX_SEAMCALL_STATUS_MASK) == TDX_OPERAND_INVALID) {
+		/*
+		 * Because a user gives operands, don't warn.
+		 * Return a hint to the user because it's sometimes hard for the
+		 * user to figure out which operand is invalid.  SEAMCALL status
+		 * code includes which operand caused invalid operand error.
+		 */
+		*seamcall_err = err;
+		ret = -EINVAL;
+		goto teardown;
+	} else if (WARN_ON_ONCE(err)) {
+		pr_tdx_error(TDH_MNG_INIT, err, &out);
+		ret = -EIO;
+		goto teardown;
+	}
+
 	return 0;
 
 	/*

arch/x86/kvm/vmx/tdx.c static int __tdx_td_init(struct kvm *kvm) · line 761

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +4 -0
@@ -586,6 +755,76 @@ static int __tdx_td_init(struct kvm *kvm)
 	return ret;
 }
 
+static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
+	struct kvm_tdx_init_vm *init_vm = NULL;

no need to initialize it to NULL.

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+	struct td_params *td_params = NULL;
+	int ret;
+
+	BUILD_BUG_ON(sizeof(*init_vm) != 8 * 1024);
+	BUILD_BUG_ON(sizeof(struct td_params) != 1024);

arch/x86/kvm/vmx/tdx.c static int __tdx_td_init(struct kvm *kvm) · line 776

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	if (is_hkid_assigned(kvm_tdx))
+		return -EINVAL;
+
+	if (cmd->flags)
+		return -EINVAL;
+
+	init_vm = kzalloc(sizeof(*init_vm) +
+			  sizeof(init_vm->cpuid.entries[0]) * KVM_MAX_CPUID_ENTRIES,
+			  GFP_KERNEL);

no need to zero the memory given ...

arch/x86/kvm/vmx/tdx.c static int __tdx_td_init(struct kvm *kvm) · line 779

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	if (!init_vm)
+		return -ENOMEM;
+	if (copy_from_user(init_vm, (void __user *)cmd->data, sizeof(*init_vm))) {

... this.

Quoted 18 lines
arch/x86/kvm/vmx/tdx.c +18 -0
+		ret = -EFAULT;
+		goto out;
+	}
+	if (init_vm->cpuid.nent > KVM_MAX_CPUID_ENTRIES) {
+		ret = -E2BIG;
+		goto out;
+	}
+	if (copy_from_user(init_vm->cpuid.entries,
+			   (void __user *)cmd->data + sizeof(*init_vm),
+			   flex_array_size(init_vm, cpuid.entries, init_vm->cpuid.nent))) {
+		ret = -EFAULT;
+		goto out;
+	}
+
+	if (memchr_inv(init_vm->reserved, 0, sizeof(init_vm->reserved))) {
+		ret = -EINVAL;
+		goto out;
+	}
#292 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 29 lines · Chao Gao
Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +29 -0
+static void setup_tdparams_cpuids(struct kvm_cpuid2 *cpuid,
+				  struct td_params *td_params)
+{
+	int i;
+
+	/*
+	 * td_params.cpuid_values: The number and the order of cpuid_value must
+	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
+	 * It's assumed that td_params was zeroed.
+	 */
+	for (i = 0; i < tdx_info->num_cpuid_config; i++) {
+		const struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+		/* KVM_TDX_CPUID_NO_SUBLEAF means index = 0. */
+		u32 index = c->sub_leaf == KVM_TDX_CPUID_NO_SUBLEAF ? 0 : c->sub_leaf;
+		const struct kvm_cpuid_entry2 *entry =
+			kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent,
+					      c->leaf, index);
+		struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+		if (!entry)
+			continue;
+
+		/*
+		 * tdsysinfo.cpuid_configs[].{eax, ebx, ecx, edx}
+		 * bit 1 means it can be configured to zero or one.
+		 * bit 0 means it must be zero.
+		 * Mask out non-configurable bits.
+		 */
+		value->eax = entry->eax & c->eax;
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 482

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+		value->ebx = entry->ebx & c->ebx;
+		value->ecx = entry->ecx & c->ecx;
+		value->edx = entry->edx & c->edx;

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Ok, I'll eliminate them. If user space passes wrong cpuids, TDX module will return error. I'll leave the error check to the TDX module.

Quoted 41 lines
Quoted 28 lines
arch/x86/kvm/vmx/tdx.c +28 -0
+	}
+}
+
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+
+	/* Setup td_params.xfam */
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+
+	/*
+	 * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+	 * and, CET support.
+	 */
+	guest_supported_xss &=

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 520

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		(kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
+#define MSG_LBR	"TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH properly.\n"
+		pr_warn(MSG_LBR);

Drop the pr_warn() because userspace can trigger it at will.

Quoted 4 lines

I don't think KVM needs to relay TDX module capabilities to userspace as-is. KVM should advertise a feature only if both TDX module's and KVM's support are in place. if KVM masked out LBR and PERFMON, it should be a problem of userspace and we don't need to warn here.

Makes sense. Drop those message and don't advertise those features to user space.

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 41 lines · Isaku Yamahata
Quoted 29 lines · Chao Gao
Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +29 -0
+static void setup_tdparams_cpuids(struct kvm_cpuid2 *cpuid,
+                                 struct td_params *td_params)
+{
+       int i;
+
+       /*
+        * td_params.cpuid_values: The number and the order of cpuid_value must
+        * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
+        * It's assumed that td_params was zeroed.
+        */
+       for (i = 0; i < tdx_info->num_cpuid_config; i++) {
+               const struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+               /* KVM_TDX_CPUID_NO_SUBLEAF means index = 0. */
+               u32 index = c->sub_leaf == KVM_TDX_CPUID_NO_SUBLEAF ? 0 : c->sub_leaf;
+               const struct kvm_cpuid_entry2 *entry =
+                       kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent,
+                                             c->leaf, index);
+               struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+               if (!entry)
+                       continue;
+
+               /*
+                * tdsysinfo.cpuid_configs[].{eax, ebx, ecx, edx}
+                * bit 1 means it can be configured to zero or one.
+                * bit 0 means it must be zero.
+                * Mask out non-configurable bits.
+                */
+               value->eax = entry->eax & c->eax;
Quoted 8 lines
Quoted 3 lines

+               value->ebx = entry->ebx & c->ebx;
+               value->ecx = entry->ecx & c->ecx;
+               value->edx = entry->edx & c->edx;

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Quoted 2 lines

Ok, I'll eliminate them.  If user space passes wrong cpuids, TDX module will return error. I'll leave the error check to the TDX module.

I was just looking at this. Agreed. It breaks the selftests though.

#294 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 42 lines · Rick P
Quoted 41 lines · Isaku Yamahata
Quoted 37 lines · Chao Gao
Quoted 22 lines
arch/x86/kvm/vmx/tdx.c +22 -0
+static void setup_tdparams_cpuids(struct kvm_cpuid2 *cpuid,
+                                 struct td_params *td_params)
+{
+       int i;
+
+       /*
+        * td_params.cpuid_values: The number and the order of cpuid_value must
+        * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
+        * It's assumed that td_params was zeroed.
+        */
+       for (i = 0; i < tdx_info->num_cpuid_config; i++) {
+               const struct kvm_tdx_cpuid_config *c = &tdx_info->cpuid_configs[i];
+               /* KVM_TDX_CPUID_NO_SUBLEAF means index = 0. */
+               u32 index = c->sub_leaf == KVM_TDX_CPUID_NO_SUBLEAF ? 0 : c->sub_leaf;
+               const struct kvm_cpuid_entry2 *entry =
+                       kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent,
+                                             c->leaf, index);
+               struct tdx_cpuid_value *value = &td_params->cpuid_values[i];
+
+               if (!entry)
+                       continue;
+

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 482

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+               /*
+                * tdsysinfo.cpuid_configs[].{eax, ebx, ecx, edx}
+                * bit 1 means it can be configured to zero or one.
+                * bit 0 means it must be zero.
+                * Mask out non-configurable bits.
+                */
+               value->eax = entry->eax & c->eax;
+               value->ebx = entry->ebx & c->ebx;
+               value->ecx = entry->ecx & c->ecx;
+               value->edx = entry->edx & c->edx;

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Quoted 4 lines
Quoted 2 lines

Ok, I'll eliminate them.  If user space passes wrong cpuids, TDX module will return error. I'll leave the error check to the TDX module.

I was just looking at this. Agreed. It breaks the selftests though.

If all you prefer to go this direction, then please update the error handling of this specific SEAMCALL.

#295 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 5 lines · Xiaoyao Li
Quoted 5 lines
Quoted 5 lines
Quoted 4 lines

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Ok, I'll eliminate them.  If user space passes wrong cpuids, TDX module will return error. I'll leave the error check to the TDX module.

I was just looking at this. Agreed. It breaks the selftests though.

If all you prefer to go this direction, then please update the error handling of this specific SEAMCALL.

What do you mean by SEAMCALL, TDH_MNG_INIT? Can you be more specific?

#296 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 9 lines · Rick P
Quoted 8 lines · Xiaoyao Li
Quoted 8 lines
Quoted 7 lines
Quoted 4 lines

Any reason to mask off non-configurable bits rather than return an error? this is misleading to userspace because guest sees the values emulated by TDX module instead of the values passed from userspace (i.e., the request from userspace isn't done but there is no indication of that to userspace).

Ok, I'll eliminate them.  If user space passes wrong cpuids, TDX module will return error. I'll leave the error check to the TDX module.

Quoted 6 lines
Quoted 4 lines
Quoted 1 line

I was just looking at this. Agreed. It breaks the selftests though.

If all you prefer to go this direction, then please update the error handling of this specific SEAMCALL.

What do you mean by SEAMCALL, TDH_MNG_INIT? Can you be more specific?

Sorry. I missed the fact that current patch already has the specific handling for TDX_OPERAND_INVALID for TDH.MNG.INIT.

I need to update QEMU to match the new behavior.

#297 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]

On 2/26/2024 4:25 PM, [email protected] wrote:

...

Quoted 26 lines
arch/x86/kvm/vmx/tdx.c +26 -0
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+
+	/* Setup td_params.xfam */
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+
+	/*
+	 * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+	 * and, CET support.
+	 */
+	guest_supported_xss &=
+		(kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 521

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
+#define MSG_LBR	"TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH properly.\n"
+		pr_warn(MSG_LBR);
+		return -EOPNOTSUPP;

This unsupported behavior is totally decided by KVM even if TDX module supports it. I think we need to reflect it in tdx_info->xfam_fixed0, which gets reported to userspace via KVM_TDX_CAPABILITIES. So userspace will aware that LBR is not supported for TDs.

Quoted 12 lines
arch/x86/kvm/vmx/tdx.c +12 -0
+	}
+
+	return 0;
+}
+
+static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
+			struct kvm_tdx_init_vm *init_vm)
+{
+	struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+	int ret;
+
+	if (kvm->created_vcpus)

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 543

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		return -EBUSY;
+
+	if (init_vm->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+		/*
+		 * TODO: save/restore PMU related registers around TDENTER.
+		 * Once it's done, remove this guard.
+		 */
+#define MSG_PERFMON	"TD doesn't support perfmon yet. KVM needs to save/restore host perf registers properly.\n"
+		pr_warn(MSG_PERFMON);
+		return -EOPNOTSUPP;

similar as above, we need reflect it in tdx_info->attributes_fixed0

Quoted 2 lines
(quoted diff) +2 -0
+	}
+
#298 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 37 lines · Xiaoyao Li

On 2/26/2024 4:25 PM, [email protected] wrote:

...

Quoted 33 lines
arch/x86/kvm/vmx/tdx.c +33 -0
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+	const struct kvm_cpuid_entry2 *entry;
+	u64 guest_supported_xcr0;
+	u64 guest_supported_xss;
+
+	/* Setup td_params.xfam */
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+	if (entry)
+		guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+	else
+		guest_supported_xcr0 = 0;
+	guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+	if (entry)
+		guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+	else
+		guest_supported_xss = 0;
+
+	/*
+	 * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+	 * and, CET support.
+	 */
+	guest_supported_xss &=
+		(kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);
+
+	td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+	if (td_params->xfam & XFEATURE_MASK_LBR) {
+		/*
+		 * TODO: once KVM supports LBR(save/restore LBR related
+		 * registers around TDENTER), remove this guard.
+		 */
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 521

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+#define MSG_LBR	"TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH properly.\n"
+		pr_warn(MSG_LBR);
+		return -EOPNOTSUPP;

This unsupported behavior is totally decided by KVM even if TDX module supports it. I think we need to reflect it in tdx_info->xfam_fixed0, which gets reported to userspace via KVM_TDX_CAPABILITIES. So userspace will aware that LBR is not supported for TDs.

Yes, we can suppress KVM unpported features. I replied at
https://lore.kernel.org/kvm/[email protected]/

So far we used KVM_TDX_CAPABILITIES for feature enumeration. I'm wondering about KVM_GET_DEVICE_ATTR [1]. It's future extensible. It's also consistent with SEV.

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

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 636

Quoted 12 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/include/uapi/asm/kvm.h +12 -0
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha384 digest */
+	/*
+	 * For future extensibility to make sizeof(struct kvm_tdx_init_vm) = 8KB.
+	 * This should be enough given sizeof(TD_PARAMS) = 1024.
+	 * 8KB was chosen given because
+	 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(=256) = 8KB.
+	 */
+	__u64 reserved[1004];

This is insane.

You said you want to reserve 8K for CPUID entries, but how can these 1004 * 8 bytes be used for CPUID entries since ...

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 648

Quoted 12 lines
arch/x86/include/uapi/asm/kvm.h +12 -0
+
+	/*
+	 * Call KVM_TDX_INIT_VM before vcpu creation, thus before
+	 * KVM_SET_CPUID2.
+	 * This configuration supersedes KVM_SET_CPUID2s for VCPUs because the
+	 * TDX module directly virtualizes those CPUIDs without VMM.  The user
+	 * space VMM, e.g. qemu, should make KVM_SET_CPUID2 consistent with
+	 * those values.  If it doesn't, KVM may have wrong idea of vCPUIDs of
+	 * the guest, and KVM may wrongly emulate CPUIDs or MSRs that the TDX
+	 * module doesn't virtualize.
+	 */
+	struct kvm_cpuid2 cpuid;

... they are actually placed right after here?

Quoted 2 lines
arch/x86/include/uapi/asm/kvm.h +2 -0
+};
+
#300 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 16 lines · Kai

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 636

Quoted 12 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/include/uapi/asm/kvm.h +12 -0
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha384 digest */
+	/*
+	 * For future extensibility to make sizeof(struct kvm_tdx_init_vm) = 8KB.
+	 * This should be enough given sizeof(TD_PARAMS) = 1024.
+	 * 8KB was chosen given because
+	 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(=256) = 8KB.
+	 */
+	__u64 reserved[1004];

This is insane.

Quoted 2 lines

You said you want to reserve 8K for CPUID entries, but how can these 1004 * 8 bytes be used for CPUID entries since ...

I tried to overestimate it. It's too much, how about to make it 1024, reserved[109]?

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 19 lines · Isaku
Quoted 16 lines · Kai

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 636

Quoted 12 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/include/uapi/asm/kvm.h +12 -0
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha384 digest */
+	/*
+	 * For future extensibility to make sizeof(struct kvm_tdx_init_vm) = 8KB.
+	 * This should be enough given sizeof(TD_PARAMS) = 1024.
+	 * 8KB was chosen given because
+	 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(=256) = 8KB.
+	 */
+	__u64 reserved[1004];

This is insane.

Quoted 6 lines
Quoted 2 lines

You said you want to reserve 8K for CPUID entries, but how can these 1004 * 8 bytes be used for CPUID entries since ...

I tried to overestimate it. It's too much, how about to make it 1024, reserved[109]?

I am not sure why we need 1024B either.

IIUC, the inputs here in 'kvm_tdx_init_vm' should be a subset of the members in TD_PARAMS. This IOCTL() isn't intended to carry any additional input besides these defined in TD_PARAMS, right?

If so, then it seems to me you "at most" only need to reserve the space for the members excluding the CPUID entries, because for the CPUID entries we will always pass them as a flexible array at the end of the structure.

Based on the spec, the "non-CPUID-entry" part only occupies 256 bytes. To me it seems we have no reason to reserve more space than 256 bytes.

#302 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 33 lines · Kai
Quoted 19 lines · Isaku
Quoted 16 lines · Kai

arch/x86/include/uapi/asm/kvm.h struct kvm_tdx_capabilities { · line 636

Quoted 12 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/include/uapi/asm/kvm.h +12 -0
+struct kvm_tdx_init_vm {
+	__u64 attributes;
+	__u64 mrconfigid[6];	/* sha384 digest */
+	__u64 mrowner[6];	/* sha384 digest */
+	__u64 mrownerconfig[6];	/* sha384 digest */
+	/*
+	 * For future extensibility to make sizeof(struct kvm_tdx_init_vm) = 8KB.
+	 * This should be enough given sizeof(TD_PARAMS) = 1024.
+	 * 8KB was chosen given because
+	 * sizeof(struct kvm_cpuid_entry2) * KVM_MAX_CPUID_ENTRIES(=256) = 8KB.
+	 */
+	__u64 reserved[1004];

This is insane.

Quoted 6 lines
Quoted 2 lines

You said you want to reserve 8K for CPUID entries, but how can these 1004 * 8 bytes be used for CPUID entries since ...

I tried to overestimate it. It's too much, how about to make it 1024, reserved[109]?

I am not sure why we need 1024B either.

IIUC, the inputs here in 'kvm_tdx_init_vm' should be a subset of the members in TD_PARAMS. This IOCTL() isn't intended to carry any additional input besides these defined in TD_PARAMS, right?

Quoted 6 lines

If so, then it seems to me you "at most" only need to reserve the space for the members excluding the CPUID entries, because for the CPUID entries we will always pass them as a flexible array at the end of the structure.

Based on the spec, the "non-CPUID-entry" part only occupies 256 bytes. To me it seems we have no reason to reserve more space than 256 bytes.

Ok, I'll make it 256 bytes.

The alternative is to use key-value. The user space loops to set all necessary parameters. Something like as follows.

KVM_TDX_SET_VM_PARAM

struct kvm_tdx_vm_param {
        /* TDCS metadata field. */
        __u64 field_id;
        /*
         * value for attributes or data less or qeual to __u64.
         * pointer for sha384, cpuid, or data larger than __u64.
         */
        __u64 value_or_ptr;
};
Signature · 1 line
Isaku Yamahata <[email protected]>
#303 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]
Quoted 5 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX requires additional parameters for TDX VM for confidential execution to protect the confidentiality of its memory contents and CPU state from any other software, including VMM.

Hmm.. not only "confidentiality" but also "integrity". And the "per-VM" TDX initializaiton here actually has nothing to do with "crypto-protection", because the establishment of the key has already been done before reaching here.

I would just say:

After the crypto-protection key has been configured, TDX requires a VM-scope initialization as a step of creating the TDX guest. This "per-VM" TDX initialization does the global configurations/features that the TDX guest can support, such as guest's CPUIDs (emulated by the TDX module), the maximum number of vcpus etc.

When creating a guest TD VM before creating

Quoted 2 lines

vcpu, the number of vcpu, TSC frequency (the values are the same among vcpus, and it can't change.) CPUIDs which the TDX module emulates.

I cannot parse this sentence. It doesn't look like a sentence to me.

Guest

Quoted 1 line

TDs can trust those CPUIDs and sha384 values for measurement.

Trustness is not about the "guest can trust", but the "people using the guest can trust".

Just remove it.

If you want to emphasize the attestation, you can add something like:

"
It also passes the VM's measurement and hash of the signer etc and the hardware only allows to initialize the TDX guest when that match. "

Quoted 3 lines

Add a new subcommand, KVM_TDX_INIT_VM, to pass parameters for the TDX guest.

[...]

It assigns an encryption key to the TDX guest for memory

Quoted 1 line

encryption. TDX encrypts memory per guest basis.

No it doesn't. The key has been programmed already in your previous patch.

The device model, say

Quoted 1 line

qemu, passes per-VM parameters for the TDX guest.

This is implied by your first sentence of this paragraph.

The maximum number of

Quoted 4 lines

vcpus, TSC frequency (TDX guest has fixed VM-wide TSC frequency, not per vcpu. The TDX guest can not change it.), attributes (production or debug), available extended features (which configure guest XCR0, IA32_XSS MSR), CPUIDs, sha384 measurements, etc.

This is not a sentence.

Quoted 3 lines

Call this subcommand before creating vcpu and KVM_SET_CPUID2, i.e. CPUID configurations aren't available yet.

"
This "per-VM" TDX initialization must be done before any "vcpu-scope" TDX initialization. To match this better, require the KVM_TDX_INIT_VM IOCTL() to be done before KVM creates any vcpus.

Note KVM configures the VM's CPUIDs in KVM_SET_CPUID2 via vcpu. The downside of this approach is KVM will need to do some enforcement later to make sure the consisntency between the CPUIDs passed here and the CPUIDs done in KVM_SET_CPUID2. "

So CPUIDs configuration values need

Quoted 2 lines

to be passed in struct kvm_tdx_init_vm. The device model's responsibility to make this CPUID config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

And I would leave how to handle KVM_SET_CPUID2 to the patch that actually enforces the consisntency.

Quoted 2 lines

Missing Co-developed-by tag for Xiaoyao.

Quoted 1 line

[...]

arch/x86/kvm/cpuid.c int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid, · line 1451

Quoted 7 lines
arch/x86/kvm/cpuid.c +6 -0
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry2);

Not sure whether we can export cpuid_entry2_find() directly?

No strong opinion of course.

But if we want to expose the wrapper, looks ...

Quoted 9 lines
arch/x86/kvm/cpuid.c +1 -0
+
  struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
  						    u32 function, u32 index)
  {
arch/x86/kvm/cpuid.h +0 -0
index 856e3037e74f..215d1c68c6d1 100644

arch/x86/kvm/cpuid.h void kvm_set_cpu_caps(void); · line 19

Quoted 7 lines
arch/x86/kvm/cpuid.h +2 -0
@@ -13,6 +13,8 @@ void kvm_set_cpu_caps(void);
 
  void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu);
  void kvm_update_pv_runtime(struct kvm_vcpu *vcpu);
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(struct kvm_cpuid_entry2 *entries,
+					       int nent, u32 function, u64 index);
  struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
  						    u32 function, u32 index); >   struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,

... __kvm_find_cpuid_entry() would fit better?

arch/x86/kvm/vmx/tdx.c line 11

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +0 -1
index 1cf2b15da257..b11f105db3cd 100644
@@ -8,7 +8,6 @@
  #include "mmu.h"
  #include "tdx_arch.h"
  #include "tdx.h"
-#include "tdx_ops.h"

??

If it isn't needed, then it shouldn't be included in some previous patch.

Quoted 16 lines
arch/x86/kvm/vmx/tdx.c +5 -2
  #include "x86.h"
 
  #undef pr_fmt
@@ -350,18 +349,21 @@ static int tdx_do_tdh_mng_key_config(void *param)
  	return 0;
  }
 
-static int __tdx_td_init(struct kvm *kvm);
-
  int tdx_vm_init(struct kvm *kvm)
  {
+	/*
+	 * This function initializes only KVM software construct.  It doesn't
+	 * initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
+	 * It is handled by KVM_TDX_INIT_VM, __tdx_td_init().
+	 */

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 366

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +2 -2
+
  	/*
  	 * TDX has its own limit of the number of vcpus in addition to
  	 * KVM_MAX_VCPUS.
  	 */
  	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
 
-	/* Place holder for TDX specific logic. */
-	return __tdx_td_init(kvm);
+	return 0;

??

I don't quite understand. What's wrong of still calling __tdx_td_init() in tdx_vm_init()?

If there's anything preventing doing __tdx_td_init() from tdx_vm_init(), then it's wrong to implement that in your previous patch.

[...]

#304 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 79 lines · Kai
Quoted 5 lines · On 26/02/2024 9:25 pm, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX requires additional parameters for TDX VM for confidential execution to protect the confidentiality of its memory contents and CPU state from any other software, including VMM.

Hmm.. not only "confidentiality" but also "integrity". And the "per-VM" TDX initializaiton here actually has nothing to do with "crypto-protection", because the establishment of the key has already been done before reaching here.

I would just say:

After the crypto-protection key has been configured, TDX requires a VM-scope initialization as a step of creating the TDX guest. This "per-VM" TDX initialization does the global configurations/features that the TDX guest can support, such as guest's CPUIDs (emulated by the TDX module), the maximum number of vcpus etc.

When creating a guest TD VM before creating

Quoted 2 lines

vcpu, the number of vcpu, TSC frequency (the values are the same among vcpus, and it can't change.) CPUIDs which the TDX module emulates.

I cannot parse this sentence. It doesn't look like a sentence to me.

Guest

Quoted 1 line

TDs can trust those CPUIDs and sha384 values for measurement.

Trustness is not about the "guest can trust", but the "people using the guest can trust".

Just remove it.

If you want to emphasize the attestation, you can add something like:

"
It also passes the VM's measurement and hash of the signer etc and the hardware only allows to initialize the TDX guest when that match. "

Quoted 3 lines

Add a new subcommand, KVM_TDX_INIT_VM, to pass parameters for the TDX guest.

[...]

It assigns an encryption key to the TDX guest for memory

Quoted 1 line

encryption. TDX encrypts memory per guest basis.

No it doesn't. The key has been programmed already in your previous patch.

The device model, say

Quoted 1 line

qemu, passes per-VM parameters for the TDX guest.

This is implied by your first sentence of this paragraph.

The maximum number of

Quoted 4 lines

vcpus, TSC frequency (TDX guest has fixed VM-wide TSC frequency, not per vcpu. The TDX guest can not change it.), attributes (production or debug), available extended features (which configure guest XCR0, IA32_XSS MSR), CPUIDs, sha384 measurements, etc.

This is not a sentence.

Quoted 3 lines

Call this subcommand before creating vcpu and KVM_SET_CPUID2, i.e. CPUID configurations aren't available yet.

"
This "per-VM" TDX initialization must be done before any "vcpu-scope" TDX initialization. To match this better, require the KVM_TDX_INIT_VM IOCTL() to be done before KVM creates any vcpus.

Quoted 5 lines

Note KVM configures the VM's CPUIDs in KVM_SET_CPUID2 via vcpu. The downside of this approach is KVM will need to do some enforcement later to make sure the consisntency between the CPUIDs passed here and the CPUIDs done in KVM_SET_CPUID2.
"

Thanks for the draft. Let me update it.

Quoted 6 lines

So CPUIDs configuration values need

Quoted 2 lines

to be passed in struct kvm_tdx_init_vm. The device model's responsibility to make this CPUID config for KVM_TDX_INIT_VM and KVM_SET_CPUID2.

And I would leave how to handle KVM_SET_CPUID2 to the patch that actually enforces the consisntency.

Yes, that's a different discussion.

Quoted 9 lines

arch/x86/kvm/cpuid.c int kvm_dev_ioctl_get_cpuid(struct kvm_cpuid2 *cpuid, · line 1451

Quoted 6 lines
arch/x86/kvm/cpuid.c +6 -0
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(
+	struct kvm_cpuid_entry2 *entries, int nent, u32 function, u64 index)
+{
+	return cpuid_entry2_find(entries, nent, function, index);
+}
+EXPORT_SYMBOL_GPL(kvm_find_cpuid_entry2);

Not sure whether we can export cpuid_entry2_find() directly?

Quoted 3 lines

No strong opinion of course.

But if we want to expose the wrapper, looks ...

Almost all KVM exported symbols have kvm_ prefix. I'm afraid that cpuid is too common. We can rename the function directly without wrapper.

Quoted 9 lines
Quoted 9 lines
arch/x86/kvm/cpuid.c +1 -0
+
  struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
  						    u32 function, u32 index)
  {
arch/x86/kvm/cpuid.h +0 -0
index 856e3037e74f..215d1c68c6d1 100644
@@ -13,6 +13,8 @@ void kvm_set_cpu_caps(void);
Quoted 8 lines

arch/x86/kvm/cpuid.h void kvm_set_cpu_caps(void);

Quoted 6 lines
arch/x86/kvm/cpuid.h +2 -0
  void kvm_update_cpuid_runtime(struct kvm_vcpu *vcpu);
  void kvm_update_pv_runtime(struct kvm_vcpu *vcpu);
+struct kvm_cpuid_entry2 *kvm_find_cpuid_entry2(struct kvm_cpuid_entry2 *entries,
+					       int nent, u32 function, u64 index);
  struct kvm_cpuid_entry2 *kvm_find_cpuid_entry_index(struct kvm_vcpu *vcpu,
  						    u32 function, u32 index); >   struct kvm_cpuid_entry2 *kvm_find_cpuid_entry(struct kvm_vcpu *vcpu,

... __kvm_find_cpuid_entry() would fit better?

Ok, let's rename it.

Quoted 12 lines

arch/x86/kvm/vmx/tdx.c line 11

Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +0 -1
index 1cf2b15da257..b11f105db3cd 100644
@@ -8,7 +8,6 @@
  #include "mmu.h"
  #include "tdx_arch.h"
  #include "tdx.h"
-#include "tdx_ops.h"

??

Quoted 1 line

If it isn't needed, then it shouldn't be included in some previous patch.

Will fix.

Quoted 26 lines
Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +4 -2
  #include "x86.h"
  #undef pr_fmt
@@ -350,18 +349,21 @@ static int tdx_do_tdh_mng_key_config(void *param)
  	return 0;
  }
-static int __tdx_td_init(struct kvm *kvm);
-
  int tdx_vm_init(struct kvm *kvm)
  {
+	/*
+	 * This function initializes only KVM software construct.  It doesn't
+	 * initialize TDX stuff, e.g. TDCS, TDR, TDCX, HKID etc.
+	 * It is handled by KVM_TDX_INIT_VM, __tdx_td_init().

arch/x86/kvm/vmx/tdx.c static int tdx_do_tdh_mng_key_config(void *param) · line 364

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +3 -2
+	 */
+
  	/*
  	 * TDX has its own limit of the number of vcpus in addition to
  	 * KVM_MAX_VCPUS.
  	 */
  	kvm->max_vcpus = min(kvm->max_vcpus, TDX_MAX_VCPUS);
-	/* Place holder for TDX specific logic. */
-	return __tdx_td_init(kvm);
+	return 0;

??

Quoted 5 lines

I don't quite understand. What's wrong of still calling __tdx_td_init() in tdx_vm_init()?

If there's anything preventing doing __tdx_td_init() from tdx_vm_init(), then it's wrong to implement that in your previous patch.

Yes. As discussed the previous patch is too big, we need to break the previous patch and this patch.

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]
Quoted 16 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +16 -0
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+       const struct kvm_cpuid_entry2 *entry;
+       u64 guest_supported_xcr0;
+       u64 guest_supported_xss;
+
+       /* Setup td_params.xfam */
+       entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+       if (entry)
+               guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+       else
+               guest_supported_xcr0 = 0;
+       guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+       entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+       if (entry)

arch/x86/kvm/vmx/tdx.c static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd) · line 511

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+               guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+       else
+               guest_supported_xss = 0;
+
+       /*
+        * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+        * and, CET support.
+        */
+       guest_supported_xss &=
+               (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);

So this enables features based on xss support in the passed CPUID, but these features are not dependent xsave. You could have CET without xsave support. And in fact Kernel IBT doesn't use it. To utilize CPUID leafs to configure features, but diverge from the HW meaning seems like asking for trouble.

Quoted 31 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+       td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+       if (td_params->xfam & XFEATURE_MASK_LBR) {
+               /*
+                * TODO: once KVM supports LBR(save/restore LBR related
+                * registers around TDENTER), remove this guard.
+                */
+#define MSG_LBR        "TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH

properly.\n"
+               pr_warn(MSG_LBR);
+               return -EOPNOTSUPP;
+       }

arch/x86/kvm/vmx/tdx.c +19 -0
+
+       return 0;
+}
+
+static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
+                       struct kvm_tdx_init_vm *init_vm)
+{
+       struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+       int ret;
+
+       if (kvm->created_vcpus)
+               return -EBUSY;
+
+       if (init_vm->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+               /*
+                * TODO: save/restore PMU related registers around TDENTER.
+                * Once it's done, remove this guard.
+                */
+#define MSG_PERFMON    "TD doesn't support perfmon yet. KVM needs to save/restore host perf
Quoted 2 lines

registers properly.\n"
+               pr_warn(MSG_PERFMON);

We need to remove the TODOs and a warn doesn't seem appropriate.

Quoted 5 lines

+               return -EOPNOTSUPP;
+       }
+
+       td_params->max_vcpus = kvm->max_vcpus; +       td_params->attributes = init_vm->attributes;

Don't we need to sanitize this for a selection of features known to KVM. For example what if something else like TDX_TD_ATTRIBUTE_PERFMON is added to a future TDX module and then suddenly userspace can configure it.

So xfam is how to control features that are tied to save (CET, etc). And ATTRIBUTES are tied to features without xsave support (PKS, etc).

If we are going to use CPUID for specifying which features should get enabled in the TDX module, we should match the arch definitions of the leafs. For things like CET whether xfam controls the value of multiple CPUID leafs, then we need should check that they are all set to some consistent values and otherwise reject them. So for CET we would need to check the SHSTK and IBT bits, as well as two XCR0 bits.

If we are going to do that for XFAM based features, then why not do the same for ATTRIBUTE based features?

We would need something like GET_SUPPORTED_CPUID for TDX, but also since some features can be forced on we would need to expose something like GET_SUPPORTED_CPUID_REQUIRED as well.

Quoted 2 lines

+       td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;
+       td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);

#306 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 24 lines · Rick P
Quoted 23 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +23 -0
+static int setup_tdparams_xfam(struct kvm_cpuid2 *cpuid, struct td_params *td_params)
+{
+       const struct kvm_cpuid_entry2 *entry;
+       u64 guest_supported_xcr0;
+       u64 guest_supported_xss;
+
+       /* Setup td_params.xfam */
+       entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 0);
+       if (entry)
+               guest_supported_xcr0 = (entry->eax | ((u64)entry->edx << 32));
+       else
+               guest_supported_xcr0 = 0;
+       guest_supported_xcr0 &= kvm_caps.supported_xcr0;
+
+       entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0xd, 1);
+       if (entry)
+               guest_supported_xss = (entry->ecx | ((u64)entry->edx << 32));
+       else
+               guest_supported_xss = 0;
+
+       /*
+        * PT and CET can be exposed to TD guest regardless of KVM's XSS, PT
+        * and, CET support.
Quoted 8 lines
Quoted 3 lines

+        */
+       guest_supported_xss &=
+               (kvm_caps.supported_xss | XFEATURE_MASK_PT | TDX_TD_XFAM_CET);

So this enables features based on xss support in the passed CPUID, but these features are not dependent xsave. You could have CET without xsave support. And in fact Kernel IBT doesn't use it. To utilize CPUID leafs to configure features, but diverge from the HW meaning seems like asking for trouble.

TDX module checks the consistency. KVM can rely on it not to re-implement it. The TDX Base Architecture specification describes what check is done. Table 11.4: Extended Features Enumeration and Execution Control

Quoted 27 lines
Quoted 27 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+       td_params->xfam = guest_supported_xcr0 | guest_supported_xss;
+       if (td_params->xfam & XFEATURE_MASK_LBR) {
+               /*
+                * TODO: once KVM supports LBR(save/restore LBR related
+                * registers around TDENTER), remove this guard.
+                */
+#define MSG_LBR        "TD doesn't support LBR yet. KVM needs to save/restore IA32_LBR_DEPTH

properly.\n"
+               pr_warn(MSG_LBR);
+               return -EOPNOTSUPP;
+       }

arch/x86/kvm/vmx/tdx.c +15 -0
+
+       return 0;
+}
+
+static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
+                       struct kvm_tdx_init_vm *init_vm)
+{
+       struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
+       int ret;
+
+       if (kvm->created_vcpus)
+               return -EBUSY;
+
+       if (init_vm->attributes & TDX_TD_ATTRIBUTE_PERFMON) {
+               /*
Quoted 8 lines
Quoted 6 lines

+                * TODO: save/restore PMU related registers around TDENTER.
+                * Once it's done, remove this guard.
+                */
+#define MSG_PERFMON    "TD doesn't support perfmon yet. KVM needs to save/restore host perf registers properly.\n"
+               pr_warn(MSG_PERFMON);

We need to remove the TODOs and a warn doesn't seem appropriate.

Sure, let me drop them.

Quoted 19 lines
Quoted 5 lines

+               return -EOPNOTSUPP;
+       }
+
+       td_params->max_vcpus = kvm->max_vcpus; +       td_params->attributes = init_vm->attributes;

Don't we need to sanitize this for a selection of features known to KVM. For example what if something else like TDX_TD_ATTRIBUTE_PERFMON is added to a future TDX module and then suddenly userspace can configure it.

So xfam is how to control features that are tied to save (CET, etc). And ATTRIBUTES are tied to features without xsave support (PKS, etc).

If we are going to use CPUID for specifying which features should get enabled in the TDX module, we should match the arch definitions of the leafs. For things like CET whether xfam controls the value of multiple CPUID leafs, then we need should check that they are all set to some consistent values and otherwise reject them. So for CET we would need to check the SHSTK and IBT bits, as well as two XCR0 bits.

Quoted 5 lines

If we are going to do that for XFAM based features, then why not do the same for ATTRIBUTE based features?

We would need something like GET_SUPPORTED_CPUID for TDX, but also since some features can be forced on we would need to expose something like GET_SUPPORTED_CPUID_REQUIRED as well.

I agree to reject attributes unknown to KVM. Let's add the check.

The TDX module checks consistency between attributes, xfam, and cpuids as described in the spec, KVM can rely on it. When TDX module finds inconsistency (or anything bad), it returns error as SEAMCALL error status code. It includes which cpuid is bad. KVM returns it to the userspace VMM in struct kvm_tdx_cmd.error. We don't have to re-implement similar checks.

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 9 lines · Isaku Yamahata
Quoted 8 lines

So this enables features based on xss support in the passed CPUID, but these features are not
dependent xsave. You could have CET without xsave support. And in fact Kernel IBT doesn't use it. To
utilize CPUID leafs to configure features, but diverge from the HW meaning seems like asking for
trouble.

Quoted 3 lines

TDX module checks the consistency.  KVM can rely on it not to re-implement it. The TDX Base Architecture specification describes what check is done. Table 11.4: Extended Features Enumeration and Execution Control

The point is that it is an strange interface. Why not take XFAM as a specific field in struct kvm_tdx_init_vm?

#308 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 10 lines · Rick P
Quoted 9 lines · Isaku Yamahata
Quoted 8 lines

So this enables features based on xss support in the passed CPUID, but these features are not
dependent xsave. You could have CET without xsave support. And in fact Kernel IBT doesn't use it. To
utilize CPUID leafs to configure features, but diverge from the HW meaning seems like asking for
trouble.

Quoted 6 lines
Quoted 3 lines

TDX module checks the consistency.  KVM can rely on it not to re-implement it. The TDX Base Architecture specification describes what check is done. Table 11.4: Extended Features Enumeration and Execution Control

The point is that it is an strange interface. Why not take XFAM as a specific field in struct kvm_tdx_init_vm?

Now I see your point. Yes, we can add xfam to struct kvm_tdx_init_vm and move the burden to create xfam from the kernel to the user space.

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

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 20 lines · Isaku Yamahata
Quoted 17 lines · Rick P
Quoted 15 lines · Isaku Yamahata
Quoted 10 lines

So this enables features based on xss support in the passed CPUID, but these
features are not
dependent xsave. You could have CET without xsave support. And in fact Kernel IBT doesn't use it. To
utilize CPUID leafs to configure features, but diverge from the HW meaning
seems like asking for
trouble.

TDX module checks the consistency.  KVM can rely on it not to re-implement it.
The TDX Base Architecture specification describes what check is done. Table 11.4: Extended Features Enumeration and Execution Control

Quoted 6 lines
Quoted 3 lines

The point is that it is an strange interface. Why not take XFAM as a specific
field in struct kvm_tdx_init_vm?

Now I see your point. Yes, we can add xfam to struct kvm_tdx_init_vm and move the burden to create xfam from the kernel to the user space.

Oh, right. Qemu would have to figure out how to take it's CPUID based model and convert it to XFAM. I still think it would be better, but I was only thinking of it from KVM's perspective. We can see how the API discussion on the PUCK call resolves.

#310 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 975

Quoted 10 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
 
 	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
 
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		pr_err("Too old version of TDX module. Consider upgrade.\n");
+		ret = -EOPNOTSUPP;
+		goto error_out;
+	}
+
 	return 0;
 
Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#311 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 5 lines · Kirill A. Shutemov
Quoted 4 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +0 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
 
  	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
 
Quoted 9 lines

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 975

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Juergen

Quoted 9 lines
Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		pr_err("Too old version of TDX module. Consider upgrade.\n");
+		ret = -EOPNOTSUPP;
+		goto error_out;
+	}
+
  	return 0;
 
#312 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
  	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#313 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 22 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

arch/x86/kvm/vmx/tdx.c static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
   	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Quoted 9 lines

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Juergen

#314 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 29 lines · Jürgen Groß
Quoted 28 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

Review static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
(quoted diff) +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
   	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

Quoted 7 lines
Quoted 3 lines

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Could you check if it is visible from the guest side?

It is zero for me.

arch/x86/coco/tdx/tdx.c +24 -1
index c1cb90369915..f65993a6066d 100644
@@ -822,13 +822,33 @@ static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
 	return true;
 }
 
+#define TDG_VM_RD			7
+
+#define TDCS_CONFIG_FLAGS		0x1110000300000016
+
+#define TDCS_CONFIG_NO_RBP_MOD		BIT_ULL(2)
+
+/* Read TD-scoped metadata */
+static inline u64 tdg_vm_rd(u64 field, u64 *value)
+{
+	struct tdx_module_args args = {
+		.rdx = field,
+	};
+	u64 ret;
+
+	ret = __tdcall_ret(TDG_VM_RD, &args);
+	*value = args.r8;
+
+	return ret;
+}
+
 void __init tdx_early_init(void)
 {
 	struct tdx_module_args args = {
 		.rdx = TDCS_NOTIFY_ENABLES,
 		.r9 = -1ULL,
 	};
-	u64 cc_mask;
+	u64 cc_mask, config;
 	u32 eax, sig[3];
 
 	cpuid_count(TDX_CPUID_LEAF_ID, 0, &eax, &sig[0], &sig[2],  &sig[1]);
@@ -893,4 +913,7 @@ void __init tdx_early_init(void)
 	x86_cpuinit.parallel_bringup = false;
 
 	pr_info("Guest detected\n");
+
+	tdg_vm_rd(TDCS_CONFIG_FLAGS, &config);
+	printk("NO_RBP_MOD: %#llx\n", config & TDCS_CONFIG_NO_RBP_MOD);
 }
Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#315 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 34 lines · Kirill A. Shutemov
Quoted 33 lines · Jürgen Groß
Quoted 31 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

Review static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
(quoted diff) +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
   	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

Quoted 5 lines
Quoted 3 lines

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Could you check if it is visible from the guest side?

Jürgen, have you tried it?

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#316 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 35 lines · Kirill A. Shutemov
Quoted 34 lines · Kirill A. Shutemov
Quoted 33 lines · Jürgen Groß
Quoted 31 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

Review static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
(quoted diff) +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
    	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Could you check if it is visible from the guest side?

Jürgen, have you tried it?

No, I'm not yet at the point where I can boot a guest successfully.

Juergen

#317 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

In reply to Kirill A. Shutemov
Quoted 47 lines · Kirill A. Shutemov
Quoted 29 lines · Jürgen Groß
Quoted 28 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

Review static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
(quoted diff) +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
    	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

Quoted 7 lines
Quoted 3 lines

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Could you check if it is visible from the guest side?

It is zero for me.

arch/x86/coco/tdx/tdx.c +0 -0
index c1cb90369915..f65993a6066d 100644

arch/x86/coco/tdx/tdx.c static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages, · line 828

Quoted 7 lines
arch/x86/coco/tdx/tdx.c +4 -0
@@ -822,13 +822,33 @@ static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
  	return true;
  }
 
+#define TDG_VM_RD			7
+
+#define TDCS_CONFIG_FLAGS		0x1110000300000016
+

Hi Kirill,

Where did you get this metadata field ID value from? I assume you meant below one, from which the ID is 0x9110000300000016?

Or is there anything special rule for using metadata field ID in the guest?

{
"Control Structure": "TDCS",
"Class": "Execution Controls",
"Field Name": "CONFIG_FLAGS",
"Description": [
"Non-attested TD configuration flags"
],
"Type": "64b bitmap",
"VM Applicability": null,
"Mutability": "TDH.MNG.INIT/ TDH.IMPORT.STATE.IMMUTABLE", "Initial Value": "From TDH.MNG.INIT input", "Field Size (Bytes)": "8",
"Num Fields": "1",
"Num Elements": "1",
"Element Size (Bytes)": "8",
"Overall Size (Bytes)": "8",
"Base FIELD_ID (Hex)": "0x9110000300000016", "Host VMM Access for a Production TD": "RO", "Host VMM Access for a Debug TD": "RO",
"Guest Access": "RO",
"Migration TD Access": "RO",
"Host VMM Rd Mask for a Production TD ": "-1", "Host VMM Wr Mask for a Production TD ": "0", "Host VMM Rd Mask for a Debug TD ": "-1",
"Host VMM Wr Mask for a Debug TD ": "0",
"Guest Rd Mask": "-1",
"Guest Wr Mask": "0",
"Migration TD Rd Mask": "-1",
"Migration TD wr Mask": "0"
},

#318 lore raw

Re: [PATCH v19 039/130] KVM: TDX: initialize VM with TDX specific parameters

Quoted 59 lines · Kai
Quoted 47 lines · Kirill A. Shutemov
Quoted 29 lines · Jürgen Groß
Quoted 28 lines · Kirill A. Shutemov
Quoted 14 lines · Juergen Gross
Quoted 12 lines · Kirill A. Shutemov

Review static int __init tdx_module_setup(void) · line 973

Quoted 8 lines · On Mon, Feb 26, 2024 at 12:25:41AM -0800, [email protected] wrote:
(quoted diff) +6 -0
@@ -725,6 +967,17 @@ static int __init tdx_module_setup(void)
    	tdx_info->nr_tdcs_pages = tdcs_base_size / PAGE_SIZE;
+	/*
+	 * Make TDH.VP.ENTER preserve RBP so that the stack unwinder
+	 * always work around it.  Query the feature.
+	 */
+	if (!(tdx_info->features0 & MD_FIELD_ID_FEATURES0_NO_RBP_MOD) &&
+	    !IS_ENABLED(CONFIG_FRAME_POINTER)) {

I think it supposed to be IS_ENABLED(CONFIG_FRAME_POINTER). "!" shouldn't be here.

Quoted 4 lines

No, I don't think so.

With CONFIG_FRAME_POINTER %rbp is being saved and restored, so there is no problem in case the seamcall is clobbering it.

Could you check setup_tdparams() in your tree?

Commit

[SEAM-WORKAROUND] KVM: TDX: Don't use NO_RBP_MOD for backward compatibility

in my tree comments out the setting TDX_CONTROL_FLAG_NO_RBP_MOD.

Quoted 7 lines
Quoted 3 lines

I now remember there was problem in EDK2 using RBP. So the patch is temporary until EDK2 is fixed.

I have the following line in setup_tdparams() (not commented out):

	td_params->exec_controls = TDX_CONTROL_FLAG_NO_RBP_MOD;

Could you check if it is visible from the guest side?

It is zero for me.

arch/x86/coco/tdx/tdx.c +0 -0
index c1cb90369915..f65993a6066d 100644

arch/x86/coco/tdx/tdx.c static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages, · line 827

Quoted 6 lines
arch/x86/coco/tdx/tdx.c +4 -0
@@ -822,13 +822,33 @@ static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
  	return true;
  }
+#define TDG_VM_RD			7
+
+#define TDCS_CONFIG_FLAGS		0x1110000300000016
+

Hi Kirill,

Quoted 2 lines

Where did you get this metadata field ID value from? I assume you meant below one, from which the ID is 0x9110000300000016?

The ID has changed in recent JSON ABI definitions. Looks fishy. I will find out what is going on.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#319 lore raw

PATCH v19 40/130 KVM: TDX: Make pmu_intel.c ignore guest TD case

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because TDX KVM doesn't support PMU yet (it's future work of TDX KVM support as another patch series) and pmu_intel.c touches vmx specific structure in vcpu initialization, as workaround add dummy structure to struct vcpu_tdx and pmu_intel.c can ignore TDX case.

---
v18:
- Removed unnecessary change to vmx.c which caused kernel warning.

---
 arch/x86/kvm/vmx/pmu_intel.c | 46 +++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/pmu_intel.h | 28 ++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.h       |  8 ++++++-
 arch/x86/kvm/vmx/vmx.h       | 32 +------------------------
 4 files changed, 81 insertions(+), 33 deletions(-)
 create mode 100644 arch/x86/kvm/vmx/pmu_intel.h
arch/x86/kvm/vmx/pmu_intel.c +45 -1
index 315c7c2ba89b..7e6e51efd879 100644
@@ -19,6 +19,7 @@
 #include "lapic.h"
 #include "nested.h"
 #include "pmu.h"
+#include "tdx.h"
 
 #define MSR_PMC_FULL_WIDTH_BIT      (MSR_IA32_PMC0 - MSR_IA32_PERFCTR0)
 
@@ -68,6 +69,26 @@ static int fixed_pmc_events[] = {
 	[2] = PSEUDO_ARCH_REFERENCE_CYCLES,
 };
 
+struct lbr_desc *vcpu_to_lbr_desc(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_INTEL_TDX_HOST
+	if (is_td_vcpu(vcpu))
+		return &to_tdx(vcpu)->lbr_desc;
+#endif
+
+	return &to_vmx(vcpu)->lbr_desc;
+}
+
+struct x86_pmu_lbr *vcpu_to_lbr_records(struct kvm_vcpu *vcpu)
+{
+#ifdef CONFIG_INTEL_TDX_HOST
+	if (is_td_vcpu(vcpu))
+		return &to_tdx(vcpu)->lbr_desc.records;
+#endif
+
+	return &to_vmx(vcpu)->lbr_desc.records;
+}
+
 static void reprogram_fixed_counters(struct kvm_pmu *pmu, u64 data)
 {
 	struct kvm_pmc *pmc;
@@ -179,6 +200,23 @@ static inline struct kvm_pmc *get_fw_gp_pmc(struct kvm_pmu *pmu, u32 msr)
 	return get_gp_pmc(pmu, msr, MSR_IA32_PMC0);
 }
 
+bool intel_pmu_lbr_is_compatible(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return false;
+	return cpuid_model_is_consistent(vcpu);
+}
+
+bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
+{
+	struct x86_pmu_lbr *lbr = vcpu_to_lbr_records(vcpu);
+
+	if (is_td_vcpu(vcpu))
+		return false;
+
+	return lbr->nr && (vcpu_get_perf_capabilities(vcpu) & PMU_CAP_LBR_FMT);
+}
+
 static bool intel_pmu_is_valid_lbr_msr(struct kvm_vcpu *vcpu, u32 index)
 {
 	struct x86_pmu_lbr *records = vcpu_to_lbr_records(vcpu);
@@ -244,6 +282,9 @@ static inline void intel_pmu_release_guest_lbr_event(struct kvm_vcpu *vcpu)
 {
 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
 
+	if (is_td_vcpu(vcpu))
+		return;
+
 	if (lbr_desc->event) {
 		perf_event_release_kernel(lbr_desc->event);
 		lbr_desc->event = NULL;
@@ -285,6 +326,9 @@ int intel_pmu_create_guest_lbr_event(struct kvm_vcpu *vcpu)
 					PERF_SAMPLE_BRANCH_USER,
 	};
 
+	if (WARN_ON_ONCE(is_td_vcpu(vcpu)))
+		return 0;
+
 	if (unlikely(lbr_desc->event)) {
 		__set_bit(INTEL_PMC_IDX_FIXED_VLBR, pmu->pmc_in_use);
 		return 0;
@@ -578,7 +622,7 @@ static void intel_pmu_refresh(struct kvm_vcpu *vcpu)
 		INTEL_PMC_MAX_GENERIC, pmu->nr_arch_fixed_counters);
 
 	perf_capabilities = vcpu_get_perf_capabilities(vcpu);
-	if (cpuid_model_is_consistent(vcpu) &&
+	if (intel_pmu_lbr_is_compatible(vcpu) &&
 	    (perf_capabilities & PMU_CAP_LBR_FMT))
 		x86_perf_get_lbr(&lbr_desc->records);
 	else
arch/x86/kvm/vmx/pmu_intel.h new file +28 -0
new file mode 100644
index 000000000000..66bba47c1269
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef __KVM_X86_VMX_PMU_INTEL_H
+#define  __KVM_X86_VMX_PMU_INTEL_H
+
+struct lbr_desc *vcpu_to_lbr_desc(struct kvm_vcpu *vcpu);
+struct x86_pmu_lbr *vcpu_to_lbr_records(struct kvm_vcpu *vcpu);
+
+bool intel_pmu_lbr_is_compatible(struct kvm_vcpu *vcpu);
+bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu);
+int intel_pmu_create_guest_lbr_event(struct kvm_vcpu *vcpu);
+
+struct lbr_desc {
+	/* Basic info about guest LBR records. */
+	struct x86_pmu_lbr records;
+
+	/*
+	 * Emulate LBR feature via passthrough LBR registers when the
+	 * per-vcpu guest LBR event is scheduled on the current pcpu.
+	 *
+	 * The records may be inaccurate if the host reclaims the LBR.
+	 */
+	struct perf_event *event;
+
+	/* True if LBRs are marked as not intercepted in the MSR bitmap */
+	bool msr_passthrough;
+};
+
+#endif /* __KVM_X86_VMX_PMU_INTEL_H */
arch/x86/kvm/vmx/tdx.h +7 -1
index 184fe394da86..173ed19207fb 100644
@@ -4,6 +4,7 @@
 
 #ifdef CONFIG_INTEL_TDX_HOST
 
+#include "pmu_intel.h"
 #include "tdx_ops.h"
 
 struct kvm_tdx {
@@ -21,7 +22,12 @@ struct kvm_tdx {
 
 struct vcpu_tdx {
 	struct kvm_vcpu	vcpu;
-	/* TDX specific members follow. */
+
+	/*
+	 * Dummy to make pmu_intel not corrupt memory.
+	 * TODO: Support PMU for TDX.  Future work.
+	 */
+	struct lbr_desc lbr_desc;
 };
 
 static inline bool is_td(struct kvm *kvm)
arch/x86/kvm/vmx/vmx.h +1 -31
index e3b0985bb74a..04ed2a9eada1 100644
@@ -11,6 +11,7 @@
 #include "capabilities.h"
 #include "../kvm_cache_regs.h"
 #include "posted_intr.h"
+#include "pmu_intel.h"
 #include "vmcs.h"
 #include "vmx_ops.h"
 #include "../cpuid.h"
@@ -93,22 +94,6 @@ union vmx_exit_reason {
 	u32 full;
 };
 
-struct lbr_desc {
-	/* Basic info about guest LBR records. */
-	struct x86_pmu_lbr records;
-
-	/*
-	 * Emulate LBR feature via passthrough LBR registers when the
-	 * per-vcpu guest LBR event is scheduled on the current pcpu.
-	 *
-	 * The records may be inaccurate if the host reclaims the LBR.
-	 */
-	struct perf_event *event;
-
-	/* True if LBRs are marked as not intercepted in the MSR bitmap */
-	bool msr_passthrough;
-};
-
 /*
  * The nested_vmx structure is part of vcpu_vmx, and holds information we need
  * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
@@ -659,21 +644,6 @@ static __always_inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
 	return container_of(vcpu, struct vcpu_vmx, vcpu);
 }
 
-static inline struct lbr_desc *vcpu_to_lbr_desc(struct kvm_vcpu *vcpu)
-{
-	return &to_vmx(vcpu)->lbr_desc;
-}
-
-static inline struct x86_pmu_lbr *vcpu_to_lbr_records(struct kvm_vcpu *vcpu)
-{
-	return &vcpu_to_lbr_desc(vcpu)->records;
-}
-
-static inline bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
-{
-	return !!vcpu_to_lbr_records(vcpu)->nr;
-}
-
 void intel_pmu_cross_mapped_check(struct kvm_pmu *pmu);
 int intel_pmu_create_guest_lbr_event(struct kvm_vcpu *vcpu);
 void vmx_passthrough_lbr_msrs(struct kvm_vcpu *vcpu);
Signature · 1 line
2.25.1
#320 lore raw

Re: [PATCH v19 040/130] KVM: TDX: Make pmu_intel.c ignore guest TD case

Quoted 6 lines · On Mon, Feb 26, 2024 at 12:25:42AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX KVM doesn't support PMU yet (it's future work of TDX KVM support as another patch series) and pmu_intel.c touches vmx specific structure in vcpu initialization, as workaround add dummy structure to struct vcpu_tdx and pmu_intel.c can ignore TDX case.

Can we instead factor pmu_intel.c to avoid corrupting memory? how hard would it be?

arch/x86/kvm/vmx/pmu_intel.c static inline struct kvm_pmc *get_fw_gp_pmc(struct kvm_pmu *pmu, u32 msr) · line 217

Quoted 8 lines
arch/x86/kvm/vmx/pmu_intel.c +8 -0
+bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
+{
+	struct x86_pmu_lbr *lbr = vcpu_to_lbr_records(vcpu);
+
+	if (is_td_vcpu(vcpu))
+		return false;
+
+	return lbr->nr && (vcpu_get_perf_capabilities(vcpu) & PMU_CAP_LBR_FMT);

The check about vcpu's perf capabilities is new. is it necessary?

Quoted 5 lines
arch/x86/kvm/vmx/vmx.h +0 -5
-static inline bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
-{
-	return !!vcpu_to_lbr_records(vcpu)->nr;
-}
-
#321 lore raw

Re: [PATCH v19 040/130] KVM: TDX: Make pmu_intel.c ignore guest TD case

Quoted 10 lines · Chao Gao
Quoted 6 lines · On Mon, Feb 26, 2024 at 12:25:42AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX KVM doesn't support PMU yet (it's future work of TDX KVM support as another patch series) and pmu_intel.c touches vmx specific structure in vcpu initialization, as workaround add dummy structure to struct vcpu_tdx and pmu_intel.c can ignore TDX case.

Can we instead factor pmu_intel.c to avoid corrupting memory? how hard would it be?

Do you mean sprinkling "if (tdx) return"? It's easy. Just add it to all hooks in kvm_pmu_ops.

I chose this approach because we'll soon support vPMU support. For simplicity, will switch to sprinkle "if (tdx) return".

Quoted 10 lines

arch/x86/kvm/vmx/pmu_intel.c static inline struct kvm_pmc *get_fw_gp_pmc(struct kvm_pmu *pmu, u32 msr) · line 217

Quoted 8 lines
arch/x86/kvm/vmx/pmu_intel.c +8 -0
+bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
+{
+	struct x86_pmu_lbr *lbr = vcpu_to_lbr_records(vcpu);
+
+	if (is_td_vcpu(vcpu))
+		return false;
+
+	return lbr->nr && (vcpu_get_perf_capabilities(vcpu) & PMU_CAP_LBR_FMT);

The check about vcpu's perf capabilities is new. is it necessary?

No. Will delete it. It crept in during rebase.

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

PATCH v19 41/130 KVM: TDX: Refuse to unplug the last cpu on the package

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

In order to reclaim TDX HKID, (i.e. when deleting guest TD), needs to call TDH.PHYMEM.PAGE.WBINVD on all packages. If we have active TDX HKID, refuse to offline the last online cpu to guarantee at least one CPU online per package. Add arch callback for cpu offline.
Because TDX doesn't support suspend, this also refuses suspend if TDs are running. If no TD is running, suspend is allowed.

---
v18:
- Added reviewed-by BinBin

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  1 +
 arch/x86/kvm/vmx/main.c            |  1 +
 arch/x86/kvm/vmx/tdx.c             | 41 ++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h         |  2 ++
 arch/x86/kvm/x86.c                 |  5 ++++
 include/linux/kvm_host.h           |  1 +
 virt/kvm/kvm_main.c                | 12 +++++++--
 8 files changed, 62 insertions(+), 2 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 97f0a681e02c..f78200492a3d 100644
@@ -18,6 +18,7 @@ KVM_X86_OP(check_processor_compatibility)
 KVM_X86_OP(hardware_enable)
 KVM_X86_OP(hardware_disable)
 KVM_X86_OP(hardware_unsetup)
+KVM_X86_OP_OPTIONAL_RET0(offline_cpu)
 KVM_X86_OP(has_emulated_msr)
 KVM_X86_OP(vcpu_after_set_cpuid)
 KVM_X86_OP(is_vm_type_supported)
arch/x86/include/asm/kvm_host.h +1 -0
index 6dedb5cb71ef..0e2408a4707e 100644
@@ -1600,6 +1600,7 @@ struct kvm_x86_ops {
 	int (*hardware_enable)(void);
 	void (*hardware_disable)(void);
 	void (*hardware_unsetup)(void);
+	int (*offline_cpu)(void);
 	bool (*has_emulated_msr)(struct kvm *kvm, u32 index);
 	void (*vcpu_after_set_cpuid)(struct kvm_vcpu *vcpu);
 
arch/x86/kvm/vmx/main.c +1 -0
index 437c6d5e802e..d69dd474775b 100644
@@ -110,6 +110,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.check_processor_compatibility = vmx_check_processor_compat,
 
 	.hardware_unsetup = vt_hardware_unsetup,
+	.offline_cpu = tdx_offline_cpu,
 
 	/* TDX cpu enablement is done by tdx_hardware_setup(). */
 	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +41 -0

62 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +2 -0
index 7f123ffe4d42..33ab6800eab8 100644
@@ -138,6 +138,7 @@ void vmx_setup_mce(struct kvm_vcpu *vcpu);
 int __init tdx_hardware_setup(struct kvm_x86_ops *x86_ops);
 void tdx_hardware_unsetup(void);
 bool tdx_is_vm_type_supported(unsigned long type);
+int tdx_offline_cpu(void);
 
 int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap);
 int tdx_vm_init(struct kvm *kvm);
@@ -148,6 +149,7 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
 static inline void tdx_hardware_unsetup(void) {}
 static inline bool tdx_is_vm_type_supported(unsigned long type) { return false; }
+static inline int tdx_offline_cpu(void) { return 0; }
 
 static inline int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 {
arch/x86/kvm/x86.c +5 -0
index 1f01c7f91652..e27ea5ed2968 100644
@@ -12508,6 +12508,11 @@ void kvm_arch_hardware_disable(void)
 	drop_user_return_notifiers();
 }
 
+int kvm_arch_offline_cpu(unsigned int cpu)
+{
+	return static_call(kvm_x86_offline_cpu)();
+}
+
 bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
 {
 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
include/linux/kvm_host.h +1 -0
index eeaf4e73317c..813952eca1bf 100644
@@ -1502,6 +1502,7 @@ static inline void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) {}
 int kvm_arch_hardware_enable(void);
 void kvm_arch_hardware_disable(void);
 #endif
+int kvm_arch_offline_cpu(unsigned int cpu);
 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu);
 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu);
 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu);
virt/kvm/kvm_main.c +10 -2
index 2f0a8e28795e..de38f308738e 100644
@@ -5653,13 +5653,21 @@ static void hardware_disable_nolock(void *junk)
 	__this_cpu_write(hardware_enabled, false);
 }
 
+__weak int kvm_arch_offline_cpu(unsigned int cpu)
+{
+	return 0;
+}
+
 static int kvm_offline_cpu(unsigned int cpu)
 {
+	int r = 0;
+
 	mutex_lock(&kvm_lock);
-	if (kvm_usage_count)
+	r = kvm_arch_offline_cpu(cpu);
+	if (!r && kvm_usage_count)
 		hardware_disable_nolock(NULL);
 	mutex_unlock(&kvm_lock);
-	return 0;
+	return r;
 }
 
 static void hardware_disable_all_nolock(void)
Signature · 1 line
2.25.1
#323 lore raw

Re: [PATCH v19 041/130] KVM: TDX: Refuse to unplug the last cpu on the package

Quoted 25 lines
arch/x86/kvm/vmx/main.c +1 -0
index 437c6d5e802e..d69dd474775b 100644
@@ -110,6 +110,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.check_processor_compatibility = vmx_check_processor_compat,
 
 	.hardware_unsetup = vt_hardware_unsetup,
+	.offline_cpu = tdx_offline_cpu,
 
 	/* TDX cpu enablement is done by tdx_hardware_setup(). */
 	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +1 -0
index b11f105db3cd..f2ee5abac14e 100644
@@ -97,6 +97,7 @@ int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 */
 static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
+static atomic_t nr_configured_hkid;
 
 static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
 {

arch/x86/kvm/vmx/tdx.c static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx) · line 116

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +1 -0
@@ -112,6 +113,7 @@ static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
 {
 	tdx_guest_keyid_free(kvm_tdx->hkid);
 	kvm_tdx->hkid = -1;
+	atomic_dec(&nr_configured_hkid);

I may think it is better to extend IDA infrastructure e.g., add an API to check if any ID is allocated for a given range. No strong opinion on this.

Quoted 29 lines
arch/x86/kvm/vmx/tdx.c +15 -0
 }
 
 static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
@@ -586,6 +588,7 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 	if (ret < 0)
 		return ret;
 	kvm_tdx->hkid = ret;
+	atomic_inc(&nr_configured_hkid);
 
 	va = __get_free_page(GFP_KERNEL_ACCOUNT);
 	if (!va)
@@ -1071,3 +1074,41 @@ void tdx_hardware_unsetup(void)
 	kfree(tdx_info);
 	kfree(tdx_mng_key_config_lock);
 }
+
+int tdx_offline_cpu(void)
+{
+	int curr_cpu = smp_processor_id();
+	cpumask_var_t packages;
+	int ret = 0;
+	int i;
+
+	/* No TD is running.  Allow any cpu to be offline. */
+	if (!atomic_read(&nr_configured_hkid))
+		return 0;
+
+	/*
+	 * In order to reclaim TDX HKID, (i.e. when deleting guest TD), need to

arch/x86/kvm/vmx/tdx.c void tdx_hardware_unsetup(void) · line 1100

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	 * call TDH.PHYMEM.PAGE.WBINVD on all packages to program all memory
+	 * controller with pconfig.  If we have active TDX HKID, refuse to
+	 * offline the last online cpu.
+	 */
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+	for_each_online_cpu(i) {
+		if (i != curr_cpu)
+			cpumask_set_cpu(topology_physical_package_id(i), packages);
+	}

Just check if any other CPU is in the same package of the one about to go offline. This would obviate the need for the cpumask and allow us to break once one cpu in the same package is found.

Quoted 14 lines
arch/x86/kvm/vmx/tdx.c +14 -0
+	/* Check if this cpu is the last online cpu of this package. */
+	if (!cpumask_test_cpu(topology_physical_package_id(curr_cpu), packages))
+		ret = -EBUSY;
+	free_cpumask_var(packages);
+	if (ret)
+		/*
+		 * Because it's hard for human operator to understand the
+		 * reason, warn it.
+		 */
+#define MSG_ALLPKG_ONLINE \
+	"TDX requires all packages to have an online CPU. Delete all TDs in order to offline all CPUs of a package.\n"
+		pr_warn_ratelimited(MSG_ALLPKG_ONLINE);
+	return ret;
+}
#324 lore raw

Re: [PATCH v19 041/130] KVM: TDX: Refuse to unplug the last cpu on the package

Quoted 22 lines · Chao Gao
Quoted 22 lines
arch/x86/kvm/vmx/main.c +1 -0
index 437c6d5e802e..d69dd474775b 100644
@@ -110,6 +110,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.check_processor_compatibility = vmx_check_processor_compat,
 
 	.hardware_unsetup = vt_hardware_unsetup,
+	.offline_cpu = tdx_offline_cpu,
 
 	/* TDX cpu enablement is done by tdx_hardware_setup(). */
 	.hardware_enable = vmx_hardware_enable,
arch/x86/kvm/vmx/tdx.c +1 -0
index b11f105db3cd..f2ee5abac14e 100644
@@ -97,6 +97,7 @@ int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 */
 static DEFINE_MUTEX(tdx_lock);
 static struct mutex *tdx_mng_key_config_lock;
+static atomic_t nr_configured_hkid;
 
Quoted 10 lines

arch/x86/kvm/vmx/tdx.c static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx) · line 116

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +1 -0
 static __always_inline hpa_t set_hkid_to_hpa(hpa_t pa, u16 hkid)
 {
@@ -112,6 +113,7 @@ static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
 {
 	tdx_guest_keyid_free(kvm_tdx->hkid);
 	kvm_tdx->hkid = -1;
+	atomic_dec(&nr_configured_hkid);

I may think it is better to extend IDA infrastructure e.g., add an API to check if any ID is allocated for a given range. No strong opinion on this.

Will use ida_is_empyt().

Quoted 35 lines
Quoted 35 lines
arch/x86/kvm/vmx/tdx.c +21 -0
 }
 
 static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
@@ -586,6 +588,7 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 	if (ret < 0)
 		return ret;
 	kvm_tdx->hkid = ret;
+	atomic_inc(&nr_configured_hkid);
 
 	va = __get_free_page(GFP_KERNEL_ACCOUNT);
 	if (!va)
@@ -1071,3 +1074,41 @@ void tdx_hardware_unsetup(void)
 	kfree(tdx_info);
 	kfree(tdx_mng_key_config_lock);
 }
+
+int tdx_offline_cpu(void)
+{
+	int curr_cpu = smp_processor_id();
+	cpumask_var_t packages;
+	int ret = 0;
+	int i;
+
+	/* No TD is running.  Allow any cpu to be offline. */
+	if (!atomic_read(&nr_configured_hkid))
+		return 0;
+
+	/*
+	 * In order to reclaim TDX HKID, (i.e. when deleting guest TD), need to
+	 * call TDH.PHYMEM.PAGE.WBINVD on all packages to program all memory
+	 * controller with pconfig.  If we have active TDX HKID, refuse to
+	 * offline the last online cpu.
+	 */
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c void tdx_hardware_unsetup(void) · line 1100

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	for_each_online_cpu(i) {
+		if (i != curr_cpu)
+			cpumask_set_cpu(topology_physical_package_id(i), packages);
+	}

Just check if any other CPU is in the same package of the one about to go offline. This would obviate the need for the cpumask and allow us to break once one cpu in the same package is found.

Good idea. Will rewrite it so.

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

PATCH v19 42/130 The start of TDX KVM patch series: TD vcpu creation/destruction

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of TD vcpu creation/destruction.

---
 Documentation/virt/kvm/intel-tdx-layer-status.rst | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
Documentation/virt/kvm/intel-tdx-layer-status.rst +3 -3
index 098150da6ea2..25082e9c0b20 100644
@@ -9,7 +9,7 @@ Layer status
 What qemu can do
 ----------------
 - TDX VM TYPE is exposed to Qemu.
-- Qemu can try to create VM of TDX VM type and then fails.
+- Qemu can create/destroy guest of TDX vm type.
 
 Patch Layer status
 ------------------
@@ -17,8 +17,8 @@ Patch Layer status
 
 * TDX, VMX coexistence:                 Applied
 * TDX architectural definitions:        Applied
-* TD VM creation/destruction:           Applying
-* TD vcpu creation/destruction:         Not yet
+* TD VM creation/destruction:           Applied
+* TD vcpu creation/destruction:         Applying
 * TDX EPT violation:                    Not yet
 * TD finalization:                      Not yet
 * TD vcpu enter/exit:                   Not yet
Signature · 1 line
2.25.1
#326 lore raw

PATCH v19 43/130 KVM: TDX: create/free TDX vcpu structure

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The next step of TDX guest creation is to create vcpu. Create TDX vcpu structures, initialize it that doesn't require TDX SEAMCALL. TDX specific vcpu initialization will be implemented as independent KVM_TDX_INIT_VCPU so that when error occurs it's easy to determine which component has the issue, KVM or TDX.

---
v19:
- removed stale comment in tdx_vcpu_create().

v18:
- update commit log to use create instead of allocate because the patch doesn't newly allocate memory for TDX vcpu.

v15 -> v16:
- Add AMX support as the KVM upstream supports it.

---
 arch/x86/kvm/vmx/main.c    | 44 ++++++++++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.c     | 44 ++++++++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/x86_ops.h | 10 +++++++++
 arch/x86/kvm/x86.c         |  2 ++
 4 files changed, 96 insertions(+), 4 deletions(-)
arch/x86/kvm/vmx/main.c +40 -4
index d69dd474775b..5796fb45433f 100644
@@ -87,6 +87,42 @@ static void vt_vm_free(struct kvm *kvm)
 		tdx_vm_free(kvm);
 }
 
+static int vt_vcpu_precreate(struct kvm *kvm)
+{
+	if (is_td(kvm))
+		return 0;
+
+	return vmx_vcpu_precreate(kvm);
+}
+
+static int vt_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu))
+		return tdx_vcpu_create(vcpu);
+
+	return vmx_vcpu_create(vcpu);
+}
+
+static void vt_vcpu_free(struct kvm_vcpu *vcpu)
+{
+	if (is_td_vcpu(vcpu)) {
+		tdx_vcpu_free(vcpu);
+		return;
+	}
+
+	vmx_vcpu_free(vcpu);
+}
+
+static void vt_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
+{
+	if (is_td_vcpu(vcpu)) {
+		tdx_vcpu_reset(vcpu, init_event);
+		return;
+	}
+
+	vmx_vcpu_reset(vcpu, init_event);
+}
+
 static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 {
 	if (!is_td(kvm))
@@ -126,10 +162,10 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.vm_destroy = vt_vm_destroy,
 	.vm_free = vt_vm_free,
 
-	.vcpu_precreate = vmx_vcpu_precreate,
-	.vcpu_create = vmx_vcpu_create,
-	.vcpu_free = vmx_vcpu_free,
-	.vcpu_reset = vmx_vcpu_reset,
+	.vcpu_precreate = vt_vcpu_precreate,
+	.vcpu_create = vt_vcpu_create,
+	.vcpu_free = vt_vcpu_free,
+	.vcpu_reset = vt_vcpu_reset,
 
 	.prepare_switch_to_guest = vmx_prepare_switch_to_guest,
 	.vcpu_load = vmx_vcpu_load,
arch/x86/kvm/vmx/tdx.c +44 -0

50 lines not on this page · raw message

arch/x86/kvm/vmx/x86_ops.h +10 -0
index 33ab6800eab8..bb73a9b5b354 100644
@@ -144,7 +144,12 @@ int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap);
 int tdx_vm_init(struct kvm *kvm);
 void tdx_mmu_release_hkid(struct kvm *kvm);
 void tdx_vm_free(struct kvm *kvm);
+
 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
+
+int tdx_vcpu_create(struct kvm_vcpu *vcpu);
+void tdx_vcpu_free(struct kvm_vcpu *vcpu);
+void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
 static inline void tdx_hardware_unsetup(void) {}
@@ -158,7 +163,12 @@ static inline int tdx_vm_enable_cap(struct kvm *kvm, struct kvm_enable_cap *cap)
 static inline int tdx_vm_init(struct kvm *kvm) { return -EOPNOTSUPP; }
 static inline void tdx_mmu_release_hkid(struct kvm *kvm) {}
 static inline void tdx_vm_free(struct kvm *kvm) {}
+
 static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOPNOTSUPP; }
+
+static inline int tdx_vcpu_create(struct kvm_vcpu *vcpu) { return -EOPNOTSUPP; }
+static inline void tdx_vcpu_free(struct kvm_vcpu *vcpu) {}
+static inline void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) {}
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
arch/x86/kvm/x86.c +2 -0
index e27ea5ed2968..c002761bb662 100644
@@ -502,6 +502,7 @@ int kvm_set_apic_base(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
 	kvm_recalculate_apic_map(vcpu->kvm);
 	return 0;
 }
+EXPORT_SYMBOL_GPL(kvm_set_apic_base);
 
 /*
  * Handle a fault on a hardware virtualization (VMX or SVM) instruction.
@@ -12517,6 +12518,7 @@ bool kvm_vcpu_is_reset_bsp(struct kvm_vcpu *vcpu)
 {
 	return vcpu->kvm->arch.bsp_vcpu_id == vcpu->vcpu_id;
 }
+EXPORT_SYMBOL_GPL(kvm_vcpu_is_reset_bsp);
 
 bool kvm_vcpu_is_bsp(struct kvm_vcpu *vcpu)
 {
Signature · 1 line
2.25.1
#327 lore raw

Re: [PATCH v19 043/130] KVM: TDX: create/free TDX vcpu structure

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

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
+	WARN_ON_ONCE(vcpu->arch.cpuid_entries);
+	WARN_ON_ONCE(vcpu->arch.cpuid_nent);
+
+	/* TDX only supports x2APIC, which requires an in-kernel local APIC. */

Cannot QEMU emulate x2APIC? In my understanding, the reason is TDX module always enables APICv for TDs. So, KVM cannot intercept every access to APIC and forward them to QEMU for emulation.

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

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	if (!vcpu->arch.apic)

will "if (!irqchip_in_kernel(vcpu->kvm))" work? looks this is the custome for such a check.

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

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+		return -EINVAL;
+
+	fpstate_set_confidential(&vcpu->arch.guest_fpu);
+
+	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
+
+	vcpu->arch.cr0_guest_owned_bits = -1ul;
+	vcpu->arch.cr4_guest_owned_bits = -1ul;
+
+	vcpu->arch.tsc_offset = to_kvm_tdx(vcpu->kvm)->tsc_offset;

kvm_tdx->tsc_offset;

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

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+	vcpu->arch.l1_tsc_offset = vcpu->arch.tsc_offset;
+	vcpu->arch.guest_state_protected =
+		!(to_kvm_tdx(vcpu->kvm)->attributes & TDX_TD_ATTRIBUTE_DEBUG);

!(kvm_tdx->attributes & TDX_TD_ATTRIBUTE_DEBUG);

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +6 -0
+
+	if ((kvm_tdx->xfam & XFEATURE_MASK_XTILE) == XFEATURE_MASK_XTILE)
+		vcpu->arch.xfd_no_write_intercept = true;
+
+	return 0;
+}
#328 lore raw

Re: [PATCH v19 043/130] KVM: TDX: create/free TDX vcpu structure

Quoted 4 lines · Chao Gao
Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+int tdx_vcpu_create(struct kvm_vcpu *vcpu)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+
Quoted 8 lines

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

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+	WARN_ON_ONCE(vcpu->arch.cpuid_entries);
+	WARN_ON_ONCE(vcpu->arch.cpuid_nent);
+
+	/* TDX only supports x2APIC, which requires an in-kernel local APIC. */

Cannot QEMU emulate x2APIC? In my understanding, the reason is TDX module always enables APICv for TDs. So, KVM cannot intercept every access to APIC and forward them to QEMU for emulation.

You're right. Let me update it as follows.

/*
* TDX module always enables APICv for TDs. So, KVM cannot intercept every
* access to APIC and forward them to user space VMM.
*/

Quoted 4 lines

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

Quoted 1 line
arch/x86/kvm/vmx/tdx.c +1 -0
+	if (!vcpu->arch.apic)

will "if (!irqchip_in_kernel(vcpu->kvm))" work? looks this is the custome for such a check.

It should work because kvm_arch_vcpu_create(). Will update it.

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

PATCH v19 44/130 KVM: TDX: Do TDX specific vcpu initialization

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TD guest vcpu needs TDX specific initialization before running. Repurpose KVM_MEMORY_ENCRYPT_OP to vcpu-scope, add a new sub-command KVM_TDX_INIT_VCPU, and implement the callback for it.

---
v18:
- Use tdh_sys_rd() instead of struct tdsysinfo_struct.
- Rename tdx_reclaim_td_page() => tdx_reclaim_control_page()
- Remove the change of tools/arch/x86/include/uapi/asm/kvm.h.

---
 arch/x86/include/asm/kvm-x86-ops.h |   1 +
 arch/x86/include/asm/kvm_host.h    |   1 +
 arch/x86/include/uapi/asm/kvm.h    |   1 +
 arch/x86/kvm/vmx/main.c            |   9 ++
 arch/x86/kvm/vmx/tdx.c             | 184 ++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/tdx.h             |   8 ++
 arch/x86/kvm/vmx/x86_ops.h         |   4 +
 arch/x86/kvm/x86.c                 |   6 +
 8 files changed, 211 insertions(+), 3 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index f78200492a3d..a8e96804a252 100644
@@ -129,6 +129,7 @@ KVM_X86_OP(leave_smm)
 KVM_X86_OP(enable_smi_window)
 #endif
 KVM_X86_OP(mem_enc_ioctl)
+KVM_X86_OP_OPTIONAL(vcpu_mem_enc_ioctl)
 KVM_X86_OP_OPTIONAL(mem_enc_register_region)
 KVM_X86_OP_OPTIONAL(mem_enc_unregister_region)
 KVM_X86_OP_OPTIONAL(vm_copy_enc_context_from)
arch/x86/include/asm/kvm_host.h +1 -0
index 0e2408a4707e..5da3c211955d 100644
@@ -1778,6 +1778,7 @@ struct kvm_x86_ops {
 #endif
 
 	int (*mem_enc_ioctl)(struct kvm *kvm, void __user *argp);
+	int (*vcpu_mem_enc_ioctl)(struct kvm_vcpu *vcpu, void __user *argp);
 	int (*mem_enc_register_region)(struct kvm *kvm, struct kvm_enc_region *argp);
 	int (*mem_enc_unregister_region)(struct kvm *kvm, struct kvm_enc_region *argp);
 	int (*vm_copy_enc_context_from)(struct kvm *kvm, unsigned int source_fd);
arch/x86/include/uapi/asm/kvm.h +1 -0
index 9ac0246bd974..4000a2e087a8 100644
@@ -571,6 +571,7 @@ struct kvm_pmu_event_filter {
 enum kvm_tdx_cmd_id {
 	KVM_TDX_CAPABILITIES = 0,
 	KVM_TDX_INIT_VM,
+	KVM_TDX_INIT_VCPU,
 
 	KVM_TDX_CMD_NR_MAX,
 };
arch/x86/kvm/vmx/main.c +9 -0
index 5796fb45433f..d0f75020579f 100644
@@ -131,6 +131,14 @@ static int vt_mem_enc_ioctl(struct kvm *kvm, void __user *argp)
 	return tdx_vm_ioctl(kvm, argp);
 }
 
+static int vt_vcpu_mem_enc_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
+{
+	if (!is_td_vcpu(vcpu))
+		return -EINVAL;
+
+	return tdx_vcpu_ioctl(vcpu, argp);
+}
+
 #define VMX_REQUIRED_APICV_INHIBITS				\
 	(BIT(APICV_INHIBIT_REASON_DISABLE)|			\
 	 BIT(APICV_INHIBIT_REASON_ABSENT) |			\
@@ -291,6 +299,7 @@ struct kvm_x86_ops vt_x86_ops __initdata = {
 	.get_untagged_addr = vmx_get_untagged_addr,
 
 	.mem_enc_ioctl = vt_mem_enc_ioctl,
+	.vcpu_mem_enc_ioctl = vt_vcpu_mem_enc_ioctl,
 };
 
 struct kvm_x86_init_ops vt_init_ops __initdata = {
arch/x86/kvm/vmx/tdx.c +181 -3

239 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +8 -0
index 173ed19207fb..d3077151252c 100644
@@ -17,12 +17,20 @@ struct kvm_tdx {
 	u64 xfam;
 	int hkid;
 
+	bool finalized;
+
 	u64 tsc_offset;
 };
 
 struct vcpu_tdx {
 	struct kvm_vcpu	vcpu;
 
+	unsigned long tdvpr_pa;
+	unsigned long *tdvpx_pa;
+	bool td_vcpu_created;
+
+	bool initialized;
+
 	/*
 	 * Dummy to make pmu_intel not corrupt memory.
 	 * TODO: Support PMU for TDX.  Future work.
arch/x86/kvm/vmx/x86_ops.h +4 -0
index bb73a9b5b354..f5820f617b2e 100644
@@ -150,6 +150,8 @@ int tdx_vm_ioctl(struct kvm *kvm, void __user *argp);
 int tdx_vcpu_create(struct kvm_vcpu *vcpu);
 void tdx_vcpu_free(struct kvm_vcpu *vcpu);
 void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event);
+
+int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp);
 #else
 static inline int tdx_hardware_setup(struct kvm_x86_ops *x86_ops) { return -EOPNOTSUPP; }
 static inline void tdx_hardware_unsetup(void) {}
@@ -169,6 +171,8 @@ static inline int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) { return -EOP
 static inline int tdx_vcpu_create(struct kvm_vcpu *vcpu) { return -EOPNOTSUPP; }
 static inline void tdx_vcpu_free(struct kvm_vcpu *vcpu) {}
 static inline void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event) {}
+
+static inline int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp) { return -EOPNOTSUPP; }
 #endif
 
 #endif /* __KVM_X86_VMX_X86_OPS_H */
arch/x86/kvm/x86.c +6 -0
index c002761bb662..2bd4b7c8fa51 100644
@@ -6274,6 +6274,12 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
 	case KVM_SET_DEVICE_ATTR:
 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
 		break;
+	case KVM_MEMORY_ENCRYPT_OP:
+		r = -ENOTTY;
+		if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
+			goto out;
+		r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
+		break;
 	default:
 		r = -EINVAL;
 	}
Signature · 1 line
2.25.1
#330 lore raw

Re: [PATCH v19 044/130] KVM: TDX: Do TDX specific vcpu initialization

Quoted 38 lines
arch/x86/kvm/vmx/tdx.c +38 -0
+/* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
+static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	unsigned long *tdvpx_pa = NULL;
+	unsigned long tdvpr_pa;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	if (is_td_vcpu_created(tdx))
+		return -EINVAL;
+
+	/*
+	 * vcpu_free method frees allocated pages.  Avoid partial setup so
+	 * that the method can't handle it.
+	 */
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		return -ENOMEM;
+	tdvpr_pa = __pa(va);
+
+	tdvpx_pa = kcalloc(tdx_info->nr_tdvpx_pages, sizeof(*tdx->tdvpx_pa),
+			   GFP_KERNEL_ACCOUNT);
+	if (!tdvpx_pa) {
+		ret = -ENOMEM;
+		goto free_tdvpr;
+	}
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va) {
+			ret = -ENOMEM;
+			goto free_tdvpx;
+		}
+		tdvpx_pa[i] = __pa(va);
+	}
+

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 995

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	err = tdh_vp_create(kvm_tdx->tdr_pa, tdvpr_pa);
+	if (KVM_BUG_ON(err, vcpu->kvm)) {
+		ret = -EIO;
+		pr_tdx_error(TDH_VP_CREATE, err, NULL);
+		goto free_tdvpx;
+	}
+	tdx->tdvpr_pa = tdvpr_pa;
+
+	tdx->tdvpx_pa = tdvpx_pa;
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {

Can you merge the for-loop above into this one? then ...

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1002

Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+		err = tdh_vp_addcx(tdx->tdvpr_pa, tdvpx_pa[i]);
+		if (KVM_BUG_ON(err, vcpu->kvm)) {
+			pr_tdx_error(TDH_VP_ADDCX, err, NULL);
 
+			for (; i < tdx_info->nr_tdvpx_pages; i++) {
+				free_page((unsigned long)__va(tdvpx_pa[i]));
+				tdvpx_pa[i] = 0;
+			}

... no need to free remaining pages.

Quoted 33 lines
arch/x86/kvm/vmx/tdx.c +33 -0
+			/* vcpu_free method frees TDVPX and TDR donated to TDX */
+			return -EIO;
+		}
+	}
+
+	err = tdh_vp_init(tdx->tdvpr_pa, vcpu_rcx);
+	if (KVM_BUG_ON(err, vcpu->kvm)) {
+		pr_tdx_error(TDH_VP_INIT, err, NULL);
+		return -EIO;
+	}
+
+	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	tdx->td_vcpu_created = true;
+	return 0;
+
+free_tdvpx:
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+		if (tdvpx_pa[i])
+			free_page((unsigned long)__va(tdvpx_pa[i]));
+		tdvpx_pa[i] = 0;
+	}
+	kfree(tdvpx_pa);
+	tdx->tdvpx_pa = NULL;
+free_tdvpr:
+	if (tdvpr_pa)
+		free_page((unsigned long)__va(tdvpr_pa));
+	tdx->tdvpr_pa = 0;
+
+	return ret;
+}
+
+int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
+{

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1045

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	struct msr_data apic_base_msr;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	struct kvm_tdx_cmd cmd;
+	int ret;
+
+	if (tdx->initialized)
+		return -EINVAL;
+
+	if (!is_hkid_assigned(kvm_tdx) || is_td_finalized(kvm_tdx))

These checks look random e.g., I am not sure why is_td_created() isn't check here.

A few helper functions and boolean variables are added to track which stage the TD or TD vCPU is in. e.g.,

is_hkid_assigned()
is_td_finalized()
is_td_created()
tdx->initialized
td_vcpu_created

Insteading of doing this, I am wondering if adding two state machines for TD and TD vCPU would make the implementation clear and easy to extend.

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1056

Quoted 11 lines
arch/x86/kvm/vmx/tdx.c +11 -0
+		return -EINVAL;
+
+	if (copy_from_user(&cmd, argp, sizeof(cmd)))
+		return -EFAULT;
+
+	if (cmd.error)
+		return -EINVAL;
+
+	/* Currently only KVM_TDX_INTI_VCPU is defined for vcpu operation. */
+	if (cmd.flags || cmd.id != KVM_TDX_INIT_VCPU)
+		return -EINVAL;

Even though KVM_TD_INIT_VCPU is the only supported command, it is worthwhile to use a switch-case statement. New commands can be added easily without the need to refactor this function first.

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1069

Quoted 13 lines
arch/x86/kvm/vmx/tdx.c +13 -0
+
+	/*
+	 * As TDX requires X2APIC, set local apic mode to X2APIC.  User space
+	 * VMM, e.g. qemu, is required to set CPUID[0x1].ecx.X2APIC=1 by
+	 * KVM_SET_CPUID2.  Otherwise kvm_set_apic_base() will fail.
+	 */
+	apic_base_msr = (struct msr_data) {
+		.host_initiated = true,
+		.data = APIC_DEFAULT_PHYS_BASE | LAPIC_MODE_X2APIC |
+		(kvm_vcpu_is_reset_bsp(vcpu) ? MSR_IA32_APICBASE_BSP : 0),
+	};
+	if (kvm_set_apic_base(vcpu, &apic_base_msr))
+		return -EINVAL;

Exporting kvm_vcpu_is_reset_bsp() and kvm_set_apic_base() should be done here (rather than in a previous patch).

Quoted 15 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+
+	ret = tdx_td_vcpu_init(vcpu, (u64)cmd.data);
+	if (ret)
+		return ret;
+
+	tdx->initialized = true;
+	return 0;
+}
+
arch/x86/kvm/x86.c +0 -0
index c002761bb662..2bd4b7c8fa51 100644

arch/x86/kvm/x86.c long kvm_arch_vcpu_ioctl(struct file *filp, · line 6278

Quoted 5 lines
arch/x86/kvm/x86.c +2 -0
@@ -6274,6 +6274,12 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
 	case KVM_SET_DEVICE_ATTR:
 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
 		break;
+	case KVM_MEMORY_ENCRYPT_OP:
+		r = -ENOTTY;

Maybe -EINVAL is better. Because previously trying to call this on vCPU fd failed with -EINVAL given ...

arch/x86/kvm/x86.c long kvm_arch_vcpu_ioctl(struct file *filp, · line 6284

Quoted 6 lines
arch/x86/kvm/x86.c +4 -0
+		if (!kvm_x86_ops.vcpu_mem_enc_ioctl)
+			goto out;
+		r = kvm_x86_ops.vcpu_mem_enc_ioctl(vcpu, argp);
+		break;
 	default:
 		r = -EINVAL;

... this.

Quoted 5 lines
arch/x86/kvm/x86.c +0 -0
 	}
Signature · 1 line
2.25.1
#331 lore raw

Re: [PATCH v19 044/130] KVM: TDX: Do TDX specific vcpu initialization

Quoted 55 lines · Chao Gao
Quoted 38 lines
arch/x86/kvm/vmx/tdx.c +38 -0
+/* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
+static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
+{
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	unsigned long *tdvpx_pa = NULL;
+	unsigned long tdvpr_pa;
+	unsigned long va;
+	int ret, i;
+	u64 err;
+
+	if (is_td_vcpu_created(tdx))
+		return -EINVAL;
+
+	/*
+	 * vcpu_free method frees allocated pages.  Avoid partial setup so
+	 * that the method can't handle it.
+	 */
+	va = __get_free_page(GFP_KERNEL_ACCOUNT);
+	if (!va)
+		return -ENOMEM;
+	tdvpr_pa = __pa(va);
+
+	tdvpx_pa = kcalloc(tdx_info->nr_tdvpx_pages, sizeof(*tdx->tdvpx_pa),
+			   GFP_KERNEL_ACCOUNT);
+	if (!tdvpx_pa) {
+		ret = -ENOMEM;
+		goto free_tdvpr;
+	}
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+		va = __get_free_page(GFP_KERNEL_ACCOUNT);
+		if (!va) {
+			ret = -ENOMEM;
+			goto free_tdvpx;
+		}
+		tdvpx_pa[i] = __pa(va);
+	}
+

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 995

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	err = tdh_vp_create(kvm_tdx->tdr_pa, tdvpr_pa);
+	if (KVM_BUG_ON(err, vcpu->kvm)) {
+		ret = -EIO;
+		pr_tdx_error(TDH_VP_CREATE, err, NULL);
+		goto free_tdvpx;
+	}
+	tdx->tdvpr_pa = tdvpr_pa;
+
+	tdx->tdvpx_pa = tdvpx_pa;
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {

Can you merge the for-loop above into this one? then ...

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +3 -0
+		err = tdh_vp_addcx(tdx->tdvpr_pa, tdvpx_pa[i]);
+		if (KVM_BUG_ON(err, vcpu->kvm)) {
+			pr_tdx_error(TDH_VP_ADDCX, err, NULL);
Quoted 6 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1002

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+			for (; i < tdx_info->nr_tdvpx_pages; i++) {
+				free_page((unsigned long)__va(tdvpx_pa[i]));
+				tdvpx_pa[i] = 0;
+			}

... no need to free remaining pages.

Makes sense. Let me clean up this.

Quoted 49 lines
Quoted 33 lines
arch/x86/kvm/vmx/tdx.c +33 -0
+			/* vcpu_free method frees TDVPX and TDR donated to TDX */
+			return -EIO;
+		}
+	}
+
+	err = tdh_vp_init(tdx->tdvpr_pa, vcpu_rcx);
+	if (KVM_BUG_ON(err, vcpu->kvm)) {
+		pr_tdx_error(TDH_VP_INIT, err, NULL);
+		return -EIO;
+	}
+
+	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+	tdx->td_vcpu_created = true;
+	return 0;
+
+free_tdvpx:
+	for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+		if (tdvpx_pa[i])
+			free_page((unsigned long)__va(tdvpx_pa[i]));
+		tdvpx_pa[i] = 0;
+	}
+	kfree(tdvpx_pa);
+	tdx->tdvpx_pa = NULL;
+free_tdvpr:
+	if (tdvpr_pa)
+		free_page((unsigned long)__va(tdvpr_pa));
+	tdx->tdvpr_pa = 0;
+
+	return ret;
+}
+
+int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
+{

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1045

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+	struct msr_data apic_base_msr;
+	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	struct kvm_tdx_cmd cmd;
+	int ret;
+
+	if (tdx->initialized)
+		return -EINVAL;
+
+	if (!is_hkid_assigned(kvm_tdx) || is_td_finalized(kvm_tdx))

These checks look random e.g., I am not sure why is_td_created() isn't check here.

A few helper functions and boolean variables are added to track which stage the TD or TD vCPU is in. e.g.,

Quoted 8 lines

is_hkid_assigned()
is_td_finalized()
is_td_created()
tdx->initialized
td_vcpu_created

Insteading of doing this, I am wondering if adding two state machines for TD and TD vCPU would make the implementation clear and easy to extend.

Let me look into the state machine. Originally I hoped we don't need it, but it seems to deserve the state machine..

Quoted 7 lines
Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +7 -0
+		return -EINVAL;
+
+	if (copy_from_user(&cmd, argp, sizeof(cmd)))
+		return -EFAULT;
+
+	if (cmd.error)
+		return -EINVAL;
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1056

Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +4 -0
+
+	/* Currently only KVM_TDX_INTI_VCPU is defined for vcpu operation. */
+	if (cmd.flags || cmd.id != KVM_TDX_INIT_VCPU)
+		return -EINVAL;

Even though KVM_TD_INIT_VCPU is the only supported command, it is worthwhile to use a switch-case statement. New commands can be added easily without the need to refactor this function first.

Yes. For KVM_MAP_MEMORY, I will make KVM_TDX_INIT_MEM_REGION vcpu ioctl instead of vm ioctl because it is consistent and scalable. We'll have switch statement in the next respin.

Quoted 8 lines
Quoted 8 lines
arch/x86/kvm/vmx/tdx.c +8 -0
+
+	/*
+	 * As TDX requires X2APIC, set local apic mode to X2APIC.  User space
+	 * VMM, e.g. qemu, is required to set CPUID[0x1].ecx.X2APIC=1 by
+	 * KVM_SET_CPUID2.  Otherwise kvm_set_apic_base() will fail.
+	 */
+	apic_base_msr = (struct msr_data) {
+		.host_initiated = true,
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 1069

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +5 -0
+		.data = APIC_DEFAULT_PHYS_BASE | LAPIC_MODE_X2APIC |
+		(kvm_vcpu_is_reset_bsp(vcpu) ? MSR_IA32_APICBASE_BSP : 0),
+	};
+	if (kvm_set_apic_base(vcpu, &apic_base_msr))
+		return -EINVAL;

Exporting kvm_vcpu_is_reset_bsp() and kvm_set_apic_base() should be done here (rather than in a previous patch).

Sure.

Quoted 10 lines
Quoted 9 lines
arch/x86/kvm/vmx/tdx.c +9 -0
+
+	ret = tdx_td_vcpu_init(vcpu, (u64)cmd.data);
+	if (ret)
+		return ret;
+
+	tdx->initialized = true;
+	return 0;
+}
+
Quoted 13 lines

arch/x86/kvm/x86.c long kvm_arch_vcpu_ioctl(struct file *filp, · line 6278

Quoted 10 lines
arch/x86/kvm/x86.c +2 -0
index c002761bb662..2bd4b7c8fa51 100644
@@ -6274,6 +6274,12 @@ long kvm_arch_vcpu_ioctl(struct file *filp,
 	case KVM_SET_DEVICE_ATTR:
 		r = kvm_vcpu_ioctl_device_attr(vcpu, ioctl, argp);
 		break;
+	case KVM_MEMORY_ENCRYPT_OP:
+		r = -ENOTTY;

Maybe -EINVAL is better. Because previously trying to call this on vCPU fd failed with -EINVAL given ...

Oh, ok. Will change it. I followed VM ioctl case as default value. But vcpu ioctl seems to have -EINVAL as default value.

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

Re: [PATCH v19 044/130] KVM: TDX: Do TDX specific vcpu initialization

In reply to [email protected]

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 954

Quoted 7 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +7 -0
+/* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
+static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
+{
+       struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+       unsigned long *tdvpx_pa = NULL;
+       unsigned long tdvpr_pa;

I think we could drop theselocal variables and just use tdx->tdvpr_pa and tdx->tdvpx_pa. Then we don't have to have the assignments later.

Quoted 30 lines

+       unsigned long va;
+       int ret, i;
+       u64 err;

arch/x86/kvm/vmx/tdx.c +27 -0
+
+       if (is_td_vcpu_created(tdx))
+               return -EINVAL;
+
+       /*
+        * vcpu_free method frees allocated pages.  Avoid partial setup so
+        * that the method can't handle it.
+        */
+       va = __get_free_page(GFP_KERNEL_ACCOUNT);
+       if (!va)
+               return -ENOMEM;
+       tdvpr_pa = __pa(va);
+
+       tdvpx_pa = kcalloc(tdx_info->nr_tdvpx_pages, sizeof(*tdx->tdvpx_pa),
+                          GFP_KERNEL_ACCOUNT);
+       if (!tdvpx_pa) {
+               ret = -ENOMEM;
+               goto free_tdvpr;
+       }
+       for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+               va = __get_free_page(GFP_KERNEL_ACCOUNT);
+               if (!va) {
+                       ret = -ENOMEM;
+                       goto free_tdvpx;
+               }
+               tdvpx_pa[i] = __pa(va);
+       }

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 994

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+       err = tdh_vp_create(kvm_tdx->tdr_pa, tdvpr_pa);
+       if (KVM_BUG_ON(err, vcpu->kvm)) {
+               ret = -EIO;
+               pr_tdx_error(TDH_VP_CREATE, err, NULL);
+               goto free_tdvpx;
+       }
+       tdx->tdvpr_pa = tdvpr_pa;
+
+       tdx->tdvpx_pa = tdvpx_pa;

Or alternatively let's move these to right before they are used. (in the current branch

Quoted 4 lines

+       for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) { +               err = tdh_vp_addcx(tdx->tdvpr_pa, tdvpx_pa[i]); +               if (KVM_BUG_ON(err, vcpu->kvm)) {
+                       pr_tdx_error(TDH_VP_ADDCX, err, NULL);

Quoted 10 lines

+                       for (; i < tdx_info->nr_tdvpx_pages; i++) { +                               free_page((unsigned long)__va(tdvpx_pa[i])); +                               tdvpx_pa[i] = 0;
+                       }
+                       /* vcpu_free method frees TDVPX and TDR donated to TDX */ +                       return -EIO;
+               }
+       }

In the current branch tdh_vp_init() takes struct vcpu_tdx, so they would be moved right here.

What do you think?

Quoted 26 lines
arch/x86/kvm/vmx/tdx.c +26 -0
+
+       err = tdh_vp_init(tdx->tdvpr_pa, vcpu_rcx);
+       if (KVM_BUG_ON(err, vcpu->kvm)) {
+               pr_tdx_error(TDH_VP_INIT, err, NULL);
+               return -EIO;
+       }
+
+       vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
+       tdx->td_vcpu_created = true;
+       return 0;
+
+free_tdvpx:
+       for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+               if (tdvpx_pa[i])
+                       free_page((unsigned long)__va(tdvpx_pa[i]));
+               tdvpx_pa[i] = 0;
+       }
+       kfree(tdvpx_pa);
+       tdx->tdvpx_pa = NULL;
+free_tdvpr:
+       if (tdvpr_pa)
+               free_page((unsigned long)__va(tdvpr_pa));
+       tdx->tdvpr_pa = 0;
+
+       return ret;
+}
#333 lore raw

Re: [PATCH v19 044/130] KVM: TDX: Do TDX specific vcpu initialization

Quoted 12 lines · Rick P

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 954

Quoted 7 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:
arch/x86/kvm/vmx/tdx.c +7 -0
+/* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
+static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
+{
+       struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
+       struct vcpu_tdx *tdx = to_tdx(vcpu);
+       unsigned long *tdvpx_pa = NULL;
+       unsigned long tdvpr_pa;

I think we could drop theselocal variables and just use tdx->tdvpr_pa and tdx->tdvpx_pa. Then we don't have to have the assignments later.

Yes, let me clean it up. The old version acquired spin lock in the middle. Now we don't have it.

Quoted 57 lines
Quoted 30 lines

+       unsigned long va;
+       int ret, i;
+       u64 err;

arch/x86/kvm/vmx/tdx.c +27 -0
+
+       if (is_td_vcpu_created(tdx))
+               return -EINVAL;
+
+       /*
+        * vcpu_free method frees allocated pages.  Avoid partial setup so
+        * that the method can't handle it.
+        */
+       va = __get_free_page(GFP_KERNEL_ACCOUNT);
+       if (!va)
+               return -ENOMEM;
+       tdvpr_pa = __pa(va);
+
+       tdvpx_pa = kcalloc(tdx_info->nr_tdvpx_pages, sizeof(*tdx->tdvpx_pa),
+                          GFP_KERNEL_ACCOUNT);
+       if (!tdvpx_pa) {
+               ret = -ENOMEM;
+               goto free_tdvpr;
+       }
+       for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) {
+               va = __get_free_page(GFP_KERNEL_ACCOUNT);
+               if (!va) {
+                       ret = -ENOMEM;
+                       goto free_tdvpx;
+               }
+               tdvpx_pa[i] = __pa(va);
+       }

arch/x86/kvm/vmx/tdx.c int tdx_vm_ioctl(struct kvm *kvm, void __user *argp) · line 994

Quoted 10 lines
arch/x86/kvm/vmx/tdx.c +10 -0
+
+       err = tdh_vp_create(kvm_tdx->tdr_pa, tdvpr_pa);
+       if (KVM_BUG_ON(err, vcpu->kvm)) {
+               ret = -EIO;
+               pr_tdx_error(TDH_VP_CREATE, err, NULL);
+               goto free_tdvpx;
+       }
+       tdx->tdvpr_pa = tdvpr_pa;
+
+       tdx->tdvpx_pa = tdvpx_pa;

Or alternatively let's move these to right before they are used. (in the current branch

Quoted 4 lines

+       for (i = 0; i < tdx_info->nr_tdvpx_pages; i++) { +               err = tdh_vp_addcx(tdx->tdvpr_pa, tdvpx_pa[i]); +               if (KVM_BUG_ON(err, vcpu->kvm)) {
+                       pr_tdx_error(TDH_VP_ADDCX, err, NULL);

Quoted 10 lines

+                       for (; i < tdx_info->nr_tdvpx_pages; i++) { +                               free_page((unsigned long)__va(tdvpx_pa[i])); +                               tdvpx_pa[i] = 0;
+                       }
+                       /* vcpu_free method frees TDVPX and TDR donated to TDX */ +                       return -EIO;
+               }
+       }

Quoted 3 lines

In the current branch tdh_vp_init() takes struct vcpu_tdx, so they would be moved right here.

What do you think?

Yes, I should revise the error recovery path.

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

PATCH v19 45/130 The start of TDX KVM patch series: KVM MMU GPA shared bits

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of KVM MMU GPA shared bits.

---
 Documentation/virt/kvm/intel-tdx-layer-status.rst | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
Documentation/virt/kvm/intel-tdx-layer-status.rst +3 -2
index 25082e9c0b20..8b8186e7bfeb 100644
@@ -10,6 +10,7 @@ What qemu can do
 ----------------
 - TDX VM TYPE is exposed to Qemu.
 - Qemu can create/destroy guest of TDX vm type.
+- Qemu can create/destroy vcpu of TDX vm type.
 
 Patch Layer status
 ------------------
@@ -18,12 +19,12 @@ Patch Layer status
 * TDX, VMX coexistence:                 Applied
 * TDX architectural definitions:        Applied
 * TD VM creation/destruction:           Applied
-* TD vcpu creation/destruction:         Applying
+* TD vcpu creation/destruction:         Applied
 * TDX EPT violation:                    Not yet
 * TD finalization:                      Not yet
 * TD vcpu enter/exit:                   Not yet
 * TD vcpu interrupts/exit/hypercall:    Not yet
 
-* KVM MMU GPA shared bits:              Not yet
+* KVM MMU GPA shared bits:              Applying
 * KVM TDP refactoring for TDX:          Not yet
 * KVM TDP MMU hooks:                    Not yet
Signature · 1 line
2.25.1
#335 lore raw

PATCH v19 46/130 KVM: x86/mmu: Add address conversion functions for TDX shared bit of GPA

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX repurposes one GPA bit (51 bit or 47 bit based on configuration) to indicate the GPA is private(if cleared) or shared (if set) with VMM. If GPA.shared is set, GPA is covered by the existing conventional EPT pointed by EPTP. If GPA.shared bit is cleared, GPA is covered by TDX module. VMM has to issue SEAMCALLs to operate.

Add a member to remember GPA shared bit for each guest TDs, add address conversion functions between private GPA and shared GPA and test if GPA is private.

Because struct kvm_arch (or struct kvm which includes struct kvm_arch. See kvm_arch_alloc_vm() that passes __GPF_ZERO) is zero-cleared when allocated, the new member to remember GPA shared bit is guaranteed to be zero with this patch unless it's initialized explicitly.

			default or SEV-SNP	TDX: S = (47 or 51) - 12

gfn_shared_mask 0 S bit
kvm_is_private_gpa() always false true if GFN has S bit set
kvm_gfn_to_shared() nop set S bit
kvm_gfn_to_private() nop clear S bit

fault.is_private means that host page should be gotten from guest_memfd is_private_gpa() means that KVM MMU should invoke private MMU hooks.

---
v19:
- Add comment on default vm case.
- Added behavior table in the commit message
- drop CONFIG_KVM_MMU_PRIVATE

v18:
- Added Reviewed-by Binbin

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              | 33 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.c          |  5 +++++
 3 files changed, 40 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 5da3c211955d..de6dd42d226f 100644
@@ -1505,6 +1505,8 @@ struct kvm_arch {
 	 */
 #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
 	struct kvm_mmu_memory_cache split_desc_cache;
+
+	gfn_t gfn_shared_mask;
 };
 
 struct kvm_vm_stat {
arch/x86/kvm/mmu.h +33 -0
index d96c93a25b3b..395b55684cb9 100644
@@ -322,4 +322,37 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 		return gpa;
 	return translate_nested_gpa(vcpu, gpa, access, exception);
 }
+
+/*
+ *			default or SEV-SNP	TDX: where S = (47 or 51) - 12
+ * gfn_shared_mask	0			S bit
+ * is_private_gpa()	always false		if GPA has S bit set
+ * gfn_to_shared()	nop			set S bit
+ * gfn_to_private()	nop			clear S bit
+ *
+ * fault.is_private means that host page should be gotten from guest_memfd
+ * is_private_gpa() means that KVM MMU should invoke private MMU hooks.
+ */
+static inline gfn_t kvm_gfn_shared_mask(const struct kvm *kvm)
+{
+	return kvm->arch.gfn_shared_mask;
+}
+
+static inline gfn_t kvm_gfn_to_shared(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_shared_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_to_private(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_shared_mask(kvm);
+}
+
+static inline bool kvm_is_private_gpa(const struct kvm *kvm, gpa_t gpa)
+{
+	gfn_t mask = kvm_gfn_shared_mask(kvm);
+
+	return mask && !(gpa_to_gfn(gpa) & mask);
+}
+
 #endif
arch/x86/kvm/vmx/tdx.c +5 -0
index aa1da51b8af7..54e0d4efa2bd 100644
@@ -906,6 +906,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	kvm_tdx->attributes = td_params->attributes;
 	kvm_tdx->xfam = td_params->xfam;
 
+	if (td_params->exec_controls & TDX_EXEC_CONTROL_MAX_GPAW)
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(51));
+	else
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(47));
+
 out:
 	/* kfree() accepts NULL. */
 	kfree(init_vm);
Signature · 1 line
2.25.1
#336 lore raw

Re: [PATCH v19 046/130] KVM: x86/mmu: Add address conversion functions for TDX shared bit of GPA

Quoted 12 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX repurposes one GPA bit (51 bit or 47 bit based on configuration) to indicate the GPA is private(if cleared) or shared (if set) with VMM. If GPA.shared is set, GPA is covered by the existing conventional EPT pointed by EPTP. If GPA.shared bit is cleared, GPA is covered by TDX module. VMM has to issue SEAMCALLs to operate.

Add a member to remember GPA shared bit for each guest TDs, add address conversion functions between private GPA and shared GPA and test if GPA is private.

Quoted 8 lines

Because struct kvm_arch (or struct kvm which includes struct kvm_arch. See kvm_arch_alloc_vm() that passes __GPF_ZERO) is zero-cleared when allocated, the new member to remember GPA shared bit is guaranteed to be zero with this patch unless it's initialized explicitly.

			default or SEV-SNP	TDX: S = (47 or 51) - 12

gfn_shared_mask 0 S bit
kvm_is_private_gpa() always false true if GFN has S bit set

TDX: true if GFN has S bit clear?

Quoted 97 lines

kvm_gfn_to_shared() nop set S bit
kvm_gfn_to_private() nop clear S bit

fault.is_private means that host page should be gotten from guest_memfd is_private_gpa() means that KVM MMU should invoke private MMU hooks.

---
v19:
- Add comment on default vm case.
- Added behavior table in the commit message
- drop CONFIG_KVM_MMU_PRIVATE

v18:
- Added Reviewed-by Binbin

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              | 33 +++++++++++++++++++++++++++++++++
 arch/x86/kvm/vmx/tdx.c          |  5 +++++
 3 files changed, 40 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 5da3c211955d..de6dd42d226f 100644
@@ -1505,6 +1505,8 @@ struct kvm_arch {
 	 */
 #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
 	struct kvm_mmu_memory_cache split_desc_cache;
+
+	gfn_t gfn_shared_mask;
 };
 
 struct kvm_vm_stat {
arch/x86/kvm/mmu.h +33 -0
index d96c93a25b3b..395b55684cb9 100644
@@ -322,4 +322,37 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
 		return gpa;
 	return translate_nested_gpa(vcpu, gpa, access, exception);
 }
+
+/*
+ *			default or SEV-SNP	TDX: where S = (47 or 51) - 12
+ * gfn_shared_mask	0			S bit
+ * is_private_gpa()	always false		if GPA has S bit set
+ * gfn_to_shared()	nop			set S bit
+ * gfn_to_private()	nop			clear S bit
+ *
+ * fault.is_private means that host page should be gotten from guest_memfd
+ * is_private_gpa() means that KVM MMU should invoke private MMU hooks.
+ */
+static inline gfn_t kvm_gfn_shared_mask(const struct kvm *kvm)
+{
+	return kvm->arch.gfn_shared_mask;
+}
+
+static inline gfn_t kvm_gfn_to_shared(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_shared_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_to_private(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_shared_mask(kvm);
+}
+
+static inline bool kvm_is_private_gpa(const struct kvm *kvm, gpa_t gpa)
+{
+	gfn_t mask = kvm_gfn_shared_mask(kvm);
+
+	return mask && !(gpa_to_gfn(gpa) & mask);
+}
+
 #endif
arch/x86/kvm/vmx/tdx.c +5 -0
index aa1da51b8af7..54e0d4efa2bd 100644
@@ -906,6 +906,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
 	kvm_tdx->attributes = td_params->attributes;
 	kvm_tdx->xfam = td_params->xfam;
 
+	if (td_params->exec_controls & TDX_EXEC_CONTROL_MAX_GPAW)
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(51));
+	else
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(47));
+
 out:
 	/* kfree() accepts NULL. */
 	kfree(init_vm);
#337 lore raw

Re: [PATCH v19 046/130] KVM: x86/mmu: Add address conversion functions for TDX shared bit of GPA

Quoted 62 lines · Chenyi Qiang
Quoted 12 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX repurposes one GPA bit (51 bit or 47 bit based on configuration) to indicate the GPA is private(if cleared) or shared (if set) with VMM. If GPA.shared is set, GPA is covered by the existing conventional EPT pointed by EPTP. If GPA.shared bit is cleared, GPA is covered by TDX module. VMM has to issue SEAMCALLs to operate.

Add a member to remember GPA shared bit for each guest TDs, add address conversion functions between private GPA and shared GPA and test if GPA is private.

Quoted 8 lines

Because struct kvm_arch (or struct kvm which includes struct kvm_arch. See kvm_arch_alloc_vm() that passes __GPF_ZERO) is zero-cleared when allocated, the new member to remember GPA shared bit is guaranteed to be zero with this patch unless it's initialized explicitly.

			default or SEV-SNP	TDX: S = (47 or 51) - 12

gfn_shared_mask 0 S bit
kvm_is_private_gpa() always false true if GFN has S bit set

TDX: true if GFN has S bit clear?

Quoted 38 lines

kvm_gfn_to_shared() nop set S bit
kvm_gfn_to_private() nop clear S bit

fault.is_private means that host page should be gotten from guest_memfd is_private_gpa() means that KVM MMU should invoke private MMU hooks.

---
v19:
- Add comment on default vm case.
- Added behavior table in the commit message
- drop CONFIG_KVM_MMU_PRIVATE

v18:
- Added Reviewed-by Binbin

---
  arch/x86/include/asm/kvm_host.h |  2 ++
  arch/x86/kvm/mmu.h              | 33 +++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.c          |  5 +++++
  3 files changed, 40 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 5da3c211955d..de6dd42d226f 100644
@@ -1505,6 +1505,8 @@ struct kvm_arch {
  	 */
  #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
  	struct kvm_mmu_memory_cache split_desc_cache;
+
+	gfn_t gfn_shared_mask;
  };
 
Quoted 14 lines
Quoted 6 lines
arch/x86/include/asm/kvm_host.h +0 -0
  struct kvm_vm_stat {
arch/x86/kvm/mmu.h +0 -0
index d96c93a25b3b..395b55684cb9 100644

arch/x86/kvm/mmu.h static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, · line 329

Quoted 8 lines
arch/x86/kvm/mmu.h +5 -0
@@ -322,4 +322,37 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
  		return gpa;
  	return translate_nested_gpa(vcpu, gpa, access, exception);
  }
+
+/*
+ *			default or SEV-SNP	TDX: where S = (47 or 51) - 12
+ * gfn_shared_mask	0			S bit
+ * is_private_gpa()	always false		if GPA has S bit set

Also here,
TDX: true if GFN has S bit cleared

Quoted 45 lines
Quoted 45 lines
arch/x86/kvm/mmu.h +28 -0
+ * gfn_to_shared()	nop			set S bit
+ * gfn_to_private()	nop			clear S bit
+ *
+ * fault.is_private means that host page should be gotten from guest_memfd
+ * is_private_gpa() means that KVM MMU should invoke private MMU hooks.
+ */
+static inline gfn_t kvm_gfn_shared_mask(const struct kvm *kvm)
+{
+	return kvm->arch.gfn_shared_mask;
+}
+
+static inline gfn_t kvm_gfn_to_shared(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn | kvm_gfn_shared_mask(kvm);
+}
+
+static inline gfn_t kvm_gfn_to_private(const struct kvm *kvm, gfn_t gfn)
+{
+	return gfn & ~kvm_gfn_shared_mask(kvm);
+}
+
+static inline bool kvm_is_private_gpa(const struct kvm *kvm, gpa_t gpa)
+{
+	gfn_t mask = kvm_gfn_shared_mask(kvm);
+
+	return mask && !(gpa_to_gfn(gpa) & mask);
+}
+
  #endif
arch/x86/kvm/vmx/tdx.c +5 -0
index aa1da51b8af7..54e0d4efa2bd 100644
@@ -906,6 +906,11 @@ static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
  	kvm_tdx->attributes = td_params->attributes;
  	kvm_tdx->xfam = td_params->xfam;
 
+	if (td_params->exec_controls & TDX_EXEC_CONTROL_MAX_GPAW)
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(51));
+	else
+		kvm->arch.gfn_shared_mask = gpa_to_gfn(BIT_ULL(47));
+
  out:
  	/* kfree() accepts NULL. */
  	kfree(init_vm);
#338 lore raw

Re: [PATCH v19 046/130] KVM: x86/mmu: Add address conversion functions for TDX shared bit of GPA

Quoted 73 lines · Binbin Wu
Quoted 70 lines · Chenyi Qiang
Quoted 12 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

TDX repurposes one GPA bit (51 bit or 47 bit based on configuration) to indicate the GPA is private(if cleared) or shared (if set) with VMM. If GPA.shared is set, GPA is covered by the existing conventional EPT pointed by EPTP. If GPA.shared bit is cleared, GPA is covered by TDX module. VMM has to issue SEAMCALLs to operate.

Add a member to remember GPA shared bit for each guest TDs, add address conversion functions between private GPA and shared GPA and test if GPA is private.

Quoted 8 lines

Because struct kvm_arch (or struct kvm which includes struct kvm_arch. See kvm_arch_alloc_vm() that passes __GPF_ZERO) is zero-cleared when allocated, the new member to remember GPA shared bit is guaranteed to be zero with this patch unless it's initialized explicitly.

			default or SEV-SNP	TDX: S = (47 or 51) - 12

gfn_shared_mask 0 S bit
kvm_is_private_gpa() always false true if GFN has S bit set

TDX: true if GFN has S bit clear?

Quoted 46 lines

kvm_gfn_to_shared() nop set S bit
kvm_gfn_to_private() nop clear S bit

fault.is_private means that host page should be gotten from guest_memfd is_private_gpa() means that KVM MMU should invoke private MMU hooks.

---
v19:
- Add comment on default vm case.
- Added behavior table in the commit message
- drop CONFIG_KVM_MMU_PRIVATE

v18:
- Added Reviewed-by Binbin

---
  arch/x86/include/asm/kvm_host.h |  2 ++
  arch/x86/kvm/mmu.h              | 33 +++++++++++++++++++++++++++++++++
  arch/x86/kvm/vmx/tdx.c          |  5 +++++
  3 files changed, 40 insertions(+)
arch/x86/include/asm/kvm_host.h +2 -0
index 5da3c211955d..de6dd42d226f 100644
@@ -1505,6 +1505,8 @@ struct kvm_arch {
  	 */
  #define SPLIT_DESC_CACHE_MIN_NR_OBJECTS (SPTE_ENT_PER_PAGE + 1)
  	struct kvm_mmu_memory_cache split_desc_cache;
+
+	gfn_t gfn_shared_mask;
  };
  struct kvm_vm_stat {
arch/x86/kvm/mmu.h +0 -0
index d96c93a25b3b..395b55684cb9 100644
@@ -322,4 +322,37 @@ static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu,
  		return gpa;
  	return translate_nested_gpa(vcpu, gpa, access, exception);
  }
Quoted 8 lines
Quoted 5 lines

arch/x86/kvm/mmu.h static inline gpa_t kvm_translate_gpa(struct kvm_vcpu *vcpu, · line 329

Quoted 5 lines
arch/x86/kvm/mmu.h +5 -0
+
+/*
+ *			default or SEV-SNP	TDX: where S = (47 or 51) - 12
+ * gfn_shared_mask	0			S bit
+ * is_private_gpa()	always false		if GPA has S bit set

Also here,
TDX: true if GFN has S bit cleared

Oops. Will fix both.

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

PATCH v19 47/130 The start of TDX KVM patch series: KVM TDP refactoring for TDX

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of KVM TDP refactoring for TDX.

---
 Documentation/virt/kvm/intel-tdx-layer-status.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
Documentation/virt/kvm/intel-tdx-layer-status.rst +2 -2
index 8b8186e7bfeb..e893a3d714c7 100644
@@ -25,6 +25,6 @@ Patch Layer status
 * TD vcpu enter/exit:                   Not yet
 * TD vcpu interrupts/exit/hypercall:    Not yet
 
-* KVM MMU GPA shared bits:              Applying
-* KVM TDP refactoring for TDX:          Not yet
+* KVM MMU GPA shared bits:              Applied
+* KVM TDP refactoring for TDX:          Applying
 * KVM TDP MMU hooks:                    Not yet
Signature · 1 line
2.25.1
#340 lore raw

PATCH v19 48/130 KVM: Allow page-sized MMU caches to be initialized with custom 64-bit values

In reply to [email protected]

From: Sean Christopherson <[email protected]>

Add support to MMU caches for initializing a page with a custom 64-bit value, e.g. to pre-fill an entire page table with non-zero PTE values. The functionality will be used by x86 to support Intel's TDX, which needs to set bit 63 in all non-present PTEs in order to prevent !PRESENT page faults from getting reflected into the guest (Intel's EPT Violation #VE architecture made the less than brilliant decision of having the per-PTE behavior be opt-out instead of opt-in).

---
 include/linux/kvm_types.h |  1 +
 virt/kvm/kvm_main.c       | 16 ++++++++++++++--
 2 files changed, 15 insertions(+), 2 deletions(-)
include/linux/kvm_types.h +1 -0
index 9d1f7835d8c1..60c8d5c9eab9 100644
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
 struct kvm_mmu_memory_cache {
 	gfp_t gfp_zero;
 	gfp_t gfp_custom;
+	u64 init_value;
 	struct kmem_cache *kmem_cache;
 	int capacity;
 	int nobjs;
virt/kvm/kvm_main.c +14 -2
index de38f308738e..d399009ef1d7 100644
@@ -401,12 +401,17 @@ static void kvm_flush_shadow_all(struct kvm *kvm)
 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
 					       gfp_t gfp_flags)
 {
+	void *page;
+
 	gfp_flags |= mc->gfp_zero;
 
 	if (mc->kmem_cache)
 		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
-	else
-		return (void *)__get_free_page(gfp_flags);
+
+	page = (void *)__get_free_page(gfp_flags);
+	if (page && mc->init_value)
+		memset64(page, mc->init_value, PAGE_SIZE / sizeof(mc->init_value));
+	return page;
 }
 
 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)
@@ -421,6 +426,13 @@ int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity,
 		if (WARN_ON_ONCE(!capacity))
 			return -EIO;
 
+		/*
+		 * Custom init values can be used only for page allocations,
+		 * and obviously conflict with __GFP_ZERO.
+		 */
+		if (WARN_ON_ONCE(mc->init_value && (mc->kmem_cache || mc->gfp_zero)))
+			return -EIO;
+
 		mc->objects = kvmalloc_array(sizeof(void *), capacity, gfp);
 		if (!mc->objects)
 			return -ENOMEM;
Signature · 1 line
2.25.1
#341 lore raw

Re: [PATCH v19 048/130] KVM: Allow page-sized MMU caches to be initialized with custom 64-bit values

Quoted 39 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Add support to MMU caches for initializing a page with a custom 64-bit value, e.g. to pre-fill an entire page table with non-zero PTE values. The functionality will be used by x86 to support Intel's TDX, which needs to set bit 63 in all non-present PTEs in order to prevent !PRESENT page faults from getting reflected into the guest (Intel's EPT Violation #VE architecture made the less than brilliant decision of having the per-PTE behavior be opt-out instead of opt-in).

---
  include/linux/kvm_types.h |  1 +
  virt/kvm/kvm_main.c       | 16 ++++++++++++++--
  2 files changed, 15 insertions(+), 2 deletions(-)
include/linux/kvm_types.h +1 -0
index 9d1f7835d8c1..60c8d5c9eab9 100644
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
  struct kvm_mmu_memory_cache {
  	gfp_t gfp_zero;
  	gfp_t gfp_custom;
+	u64 init_value;
  	struct kmem_cache *kmem_cache;
  	int capacity;
  	int nobjs;
virt/kvm/kvm_main.c +2 -0
index de38f308738e..d399009ef1d7 100644
@@ -401,12 +401,17 @@ static void kvm_flush_shadow_all(struct kvm *kvm)
  static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
  					       gfp_t gfp_flags)
  {
+	void *page;
+

virt/kvm/kvm_main.c static void kvm_flush_shadow_all(struct kvm *kvm) · line 413

Quoted 10 lines
virt/kvm/kvm_main.c +4 -2
  	gfp_flags |= mc->gfp_zero;
 
  	if (mc->kmem_cache)
  		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
-	else
-		return (void *)__get_free_page(gfp_flags);
+
+	page = (void *)__get_free_page(gfp_flags);
+	if (page && mc->init_value)
+		memset64(page, mc->init_value, PAGE_SIZE / sizeof(mc->init_value));

Do we need a static_assert() to make sure mc->init_value is 64bit?

Quoted 18 lines
virt/kvm/kvm_main.c +8 -0
+	return page;
  }
 
  int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min)
@@ -421,6 +426,13 @@ int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity,
  		if (WARN_ON_ONCE(!capacity))
  			return -EIO;
 
+		/*
+		 * Custom init values can be used only for page allocations,
+		 * and obviously conflict with __GFP_ZERO.
+		 */
+		if (WARN_ON_ONCE(mc->init_value && (mc->kmem_cache || mc->gfp_zero)))
+			return -EIO;
+
  		mc->objects = kvmalloc_array(sizeof(void *), capacity, gfp);
  		if (!mc->objects)
  			return -ENOMEM;
#342 lore raw

Re: [PATCH v19 048/130] KVM: Allow page-sized MMU caches to be initialized with custom 64-bit values

Quoted 45 lines · Binbin Wu
Quoted 42 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Add support to MMU caches for initializing a page with a custom 64-bit value, e.g. to pre-fill an entire page table with non-zero PTE values. The functionality will be used by x86 to support Intel's TDX, which needs to set bit 63 in all non-present PTEs in order to prevent !PRESENT page faults from getting reflected into the guest (Intel's EPT Violation #VE architecture made the less than brilliant decision of having the per-PTE behavior be opt-out instead of opt-in).

---
  include/linux/kvm_types.h |  1 +
  virt/kvm/kvm_main.c       | 16 ++++++++++++++--
  2 files changed, 15 insertions(+), 2 deletions(-)
include/linux/kvm_types.h +1 -0
index 9d1f7835d8c1..60c8d5c9eab9 100644
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
  struct kvm_mmu_memory_cache {
  	gfp_t gfp_zero;
  	gfp_t gfp_custom;
+	u64 init_value;
  	struct kmem_cache *kmem_cache;
  	int capacity;
  	int nobjs;
virt/kvm/kvm_main.c +2 -0
index de38f308738e..d399009ef1d7 100644
@@ -401,12 +401,17 @@ static void kvm_flush_shadow_all(struct kvm *kvm)
  static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
  					       gfp_t gfp_flags)
  {
+	void *page;
+
  	gfp_flags |= mc->gfp_zero;
  	if (mc->kmem_cache)
  		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
Quoted 8 lines

virt/kvm/kvm_main.c static void kvm_flush_shadow_all(struct kvm *kvm) · line 413

Quoted 6 lines
virt/kvm/kvm_main.c +4 -2
-	else
-		return (void *)__get_free_page(gfp_flags);
+
+	page = (void *)__get_free_page(gfp_flags);
+	if (page && mc->init_value)
+		memset64(page, mc->init_value, PAGE_SIZE / sizeof(mc->init_value));

Do we need a static_assert() to make sure mc->init_value is 64bit?

I don't see much value. Is your concern sizeof() part? If so, we can replace it with 8.

        memset64(page, mc->init_value, PAGE_SIZE / 8);
Signature · 1 line
Isaku Yamahata <[email protected]>
#343 lore raw

Re: [PATCH v19 048/130] KVM: Allow page-sized MMU caches to be initialized with custom 64-bit values

Quoted 54 lines · Isaku Yamahata
Quoted 43 lines · Binbin Wu
Quoted 41 lines · On 2/26/2024 4:25 PM, [email protected] wrote:

From: Sean Christopherson <[email protected]>

Add support to MMU caches for initializing a page with a custom 64-bit value, e.g. to pre-fill an entire page table with non-zero PTE values. The functionality will be used by x86 to support Intel's TDX, which needs to set bit 63 in all non-present PTEs in order to prevent !PRESENT page faults from getting reflected into the guest (Intel's EPT Violation #VE architecture made the less than brilliant decision of having the per-PTE behavior be opt-out instead of opt-in).

---
   include/linux/kvm_types.h |  1 +
   virt/kvm/kvm_main.c       | 16 ++++++++++++++--
   2 files changed, 15 insertions(+), 2 deletions(-)
include/linux/kvm_types.h +1 -0
index 9d1f7835d8c1..60c8d5c9eab9 100644
@@ -94,6 +94,7 @@ struct gfn_to_pfn_cache {
   struct kvm_mmu_memory_cache {
   	gfp_t gfp_zero;
   	gfp_t gfp_custom;
+	u64 init_value;
   	struct kmem_cache *kmem_cache;
   	int capacity;
   	int nobjs;
virt/kvm/kvm_main.c +2 -0
index de38f308738e..d399009ef1d7 100644
@@ -401,12 +401,17 @@ static void kvm_flush_shadow_all(struct kvm *kvm)
   static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
   					       gfp_t gfp_flags)
   {
+	void *page;
+
   	gfp_flags |= mc->gfp_zero;
   	if (mc->kmem_cache)
Quoted 8 lines

virt/kvm/kvm_main.c static void kvm_flush_shadow_all(struct kvm *kvm) · line 413

Quoted 7 lines
virt/kvm/kvm_main.c +4 -2
   		return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
-	else
-		return (void *)__get_free_page(gfp_flags);
+
+	page = (void *)__get_free_page(gfp_flags);
+	if (page && mc->init_value)
+		memset64(page, mc->init_value, PAGE_SIZE / sizeof(mc->init_value));

Do we need a static_assert() to make sure mc->init_value is 64bit?

Quoted 4 lines

I don't see much value. Is your concern sizeof() part? If so, we can replace it with 8.

         memset64(page, mc->init_value, PAGE_SIZE / 8);

Yes, but it's trivial. So, up to you. :)

#344 lore raw

PATCH v19 49/130 KVM: x86/mmu: Replace hardcoded value 0 for the initial value for SPTE

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The TDX support will need the "suppress #VE" bit (bit 63) set as the initial value for SPTE. To reduce code change size, introduce a new macro SHADOW_NONPRESENT_VALUE for the initial value for the shadow page table entry (SPTE) and replace hard-coded value 0 for it. Initialize shadow page tables with their value.

The plan is to unconditionally set the "suppress #VE" bit for both AMD and Intel as: 1) AMD hardware uses the bit 63 as NX for present SPTE and ignored for non-present SPTE; 2) for conventional VMX guests, KVM never enables the "EPT-violation #VE" in VMCS control and "suppress #VE" bit is ignored by hardware.

---
 arch/x86/kvm/mmu/mmu.c         | 20 +++++++++++++++-----
 arch/x86/kvm/mmu/paging_tmpl.h |  2 +-
 arch/x86/kvm/mmu/spte.h        |  2 ++
 arch/x86/kvm/mmu/tdp_mmu.c     | 14 +++++++-------
 4 files changed, 25 insertions(+), 13 deletions(-)
arch/x86/kvm/mmu/mmu.c +15 -5
index 2becc86c71b2..211c0e72f45d 100644
@@ -567,9 +567,9 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
 
 	if (!is_shadow_present_pte(old_spte) ||
 	    !spte_has_volatile_bits(old_spte))
-		__update_clear_spte_fast(sptep, 0ull);
+		__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 	else
-		old_spte = __update_clear_spte_slow(sptep, 0ull);
+		old_spte = __update_clear_spte_slow(sptep, SHADOW_NONPRESENT_VALUE);
 
 	if (!is_shadow_present_pte(old_spte))
 		return old_spte;
@@ -603,7 +603,7 @@ static u64 mmu_spte_clear_track_bits(struct kvm *kvm, u64 *sptep)
  */
 static void mmu_spte_clear_no_track(u64 *sptep)
 {
-	__update_clear_spte_fast(sptep, 0ull);
+	__update_clear_spte_fast(sptep, SHADOW_NONPRESENT_VALUE);
 }
 
 static u64 mmu_spte_get_lockless(u64 *sptep)
@@ -1950,7 +1950,8 @@ static bool kvm_sync_page_check(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
 
 static int kvm_sync_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int i)
 {
-	if (!sp->spt[i])
+	/* sp->spt[i] has initial value of shadow page table allocation */
+	if (sp->spt[i] == SHADOW_NONPRESENT_VALUE)
 		return 0;
 
 	return vcpu->arch.mmu->sync_spte(vcpu, sp, i);
@@ -6204,7 +6205,16 @@ 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_memory_cache_alloc_obj().
+	 */
+	if (IS_ENABLED(CONFIG_X86_64))
+		vcpu->arch.mmu_shadow_page_cache.init_value =
+			SHADOW_NONPRESENT_VALUE;
+	if (!vcpu->arch.mmu_shadow_page_cache.init_value)
+		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 +1 -1
index 4d4e98fe4f35..bebd73cd61bb 100644
@@ -911,7 +911,7 @@ static int FNAME(sync_spte)(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp, int
 	gpa_t pte_gpa;
 	gfn_t gfn;
 
-	if (WARN_ON_ONCE(!sp->spt[i]))
+	if (WARN_ON_ONCE(sp->spt[i] == SHADOW_NONPRESENT_VALUE))
 		return 0;
 
 	first_pte_gpa = FNAME(get_level1_sp_gpa)(sp);
arch/x86/kvm/mmu/spte.h +2 -0
index a129951c9a88..4d1799ba2bf8 100644
@@ -149,6 +149,8 @@ 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)
 
+#define SHADOW_NONPRESENT_VALUE	0ULL
+
 extern u64 __read_mostly shadow_host_writable_mask;
 extern u64 __read_mostly shadow_mmu_writable_mask;
 extern u64 __read_mostly shadow_nx_mask;
arch/x86/kvm/mmu/tdp_mmu.c +7 -7
index 6ae19b4ee5b1..bdeb23ff9e71 100644
@@ -570,7 +570,7 @@ static inline int tdp_mmu_zap_spte_atomic(struct kvm *kvm,
 	 * 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.
 	 */
-	__kvm_tdp_mmu_write_spte(iter->sptep, 0);
+	__kvm_tdp_mmu_write_spte(iter->sptep, SHADOW_NONPRESENT_VALUE);
 
 	return 0;
 }
@@ -707,8 +707,8 @@ static void __tdp_mmu_zap_root(struct kvm *kvm, struct kvm_mmu_page *root,
 			continue;
 
 		if (!shared)
-			tdp_mmu_iter_set_spte(kvm, &iter, 0);
-		else if (tdp_mmu_set_spte_atomic(kvm, &iter, 0))
+			tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
+		else if (tdp_mmu_set_spte_atomic(kvm, &iter, SHADOW_NONPRESENT_VALUE))
 			goto retry;
 	}
 }
@@ -764,8 +764,8 @@ 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);
+	tdp_mmu_set_spte(kvm, kvm_mmu_page_as_id(sp), sp->ptep, old_spte,
+			 SHADOW_NONPRESENT_VALUE, sp->gfn, sp->role.level + 1);
 
 	return true;
 }
@@ -799,7 +799,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_iter_set_spte(kvm, &iter, 0);
+		tdp_mmu_iter_set_spte(kvm, &iter, SHADOW_NONPRESENT_VALUE);
 		flush = true;
 	}
 
@@ -1226,7 +1226,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_iter_set_spte(kvm, iter, 0);
+	tdp_mmu_iter_set_spte(kvm, iter, SHADOW_NONPRESENT_VALUE);
 
 	if (!pte_write(range->arg.pte)) {
 		new_spte = kvm_mmu_changed_pte_notifier_make_spte(iter->old_spte,
Signature · 1 line
2.25.1
#345 lore raw

PATCH v19 50/130 KVM: x86/mmu: Allow non-zero value for non-present SPTE and removed SPTE

In reply to [email protected]

From: Sean Christopherson <[email protected]>

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 make 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, for the MMIO spte for the shared GPA,
1. KVM needs to set "suppress #VE" bit for the non-present SPTE so that EPT violation happens on TD accessing MMIO range. 2. On EPT violation, KVM sets the MMIO spte to clear "suppress #VE" bit so the TD guest can receive the #VE instead of EPT misconfiguration unlike VMX case. For the shared GPA that is not populated yet, EPT violation need to be triggered when TD guest accesses such shared GPA. The non-present SPTE value for shared GPA should set "suppress #VE" bit.

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

---
v19:
- fix typo in the commit message

---
 arch/x86/kvm/mmu/spte.h | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/spte.h +14 -1
index 4d1799ba2bf8..26bc95bbc962 100644
@@ -149,7 +149,20 @@ 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. (EPT_VIOLATION_VE=0)
+ *              bit 63 is #VE suppress if #VE is enabled. (EPT_VIOLATION_VE=1)
+ * For TDX:
+ *   TDX module sets EPT_VIOLATION_VE for Secure-EPT and conventional EPT
+ */
+#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;
@@ -196,7 +209,7 @@ extern u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
  *
  * Only used by the TDP MMU.
  */
-#define REMOVED_SPTE	0x5a0ULL
+#define REMOVED_SPTE	(SHADOW_NONPRESENT_VALUE | 0x5a0ULL)
 
 /* Removed SPTEs must not be misconstrued as shadow present PTEs. */
 static_assert(!(REMOVED_SPTE & SPTE_MMU_PRESENT_MASK));
Signature · 1 line
2.25.1
#346 lore raw

PATCH v19 51/130 KVM: x86/mmu: Add Suppress VE bit to shadow_mmio_mask/shadow_present_mask

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

To make use of the same value of shadow_mmio_mask and shadow_present_mask for TDX and VMX, add Suppress-VE bit to shadow_mmio_mask and shadow_present_mask so that they can be common for both VMX and TDX.

TDX will require shadow_mmio_mask and shadow_present_mask to include VMX_SUPPRESS_VE for shared GPA so that EPT violation is triggered for shared GPA. For VMX, VMX_SUPPRESS_VE doesn't matter for MMIO because the spte value is required to cause EPT misconfig. the additional bit doesn't affect VMX logic to add the bit to shadow_mmio_{value, mask}.

---
 arch/x86/include/asm/vmx.h | 1 +
 arch/x86/kvm/mmu/spte.c    | 6 ++++--
 2 files changed, 5 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +1 -0
index 0e73616b82f3..76ed39541a52 100644
@@ -513,6 +513,7 @@ enum vmcs_field {
 #define VMX_EPT_IPAT_BIT    			(1ull << 6)
 #define VMX_EPT_ACCESS_BIT			(1ull << 8)
 #define VMX_EPT_DIRTY_BIT			(1ull << 9)
+#define VMX_EPT_SUPPRESS_VE_BIT			(1ull << 63)
 #define VMX_EPT_RWX_MASK                        (VMX_EPT_READABLE_MASK |       \
 						 VMX_EPT_WRITABLE_MASK |       \
 						 VMX_EPT_EXECUTABLE_MASK)
arch/x86/kvm/mmu/spte.c +4 -2
index 4a599130e9c9..02a466de2991 100644
@@ -429,7 +429,9 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	shadow_dirty_mask	= has_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull;
 	shadow_nx_mask		= 0ull;
 	shadow_x_mask		= VMX_EPT_EXECUTABLE_MASK;
-	shadow_present_mask	= has_exec_only ? 0ull : VMX_EPT_READABLE_MASK;
+	/* VMX_EPT_SUPPRESS_VE_BIT is needed for W or X violation. */
+	shadow_present_mask	=
+		(has_exec_only ? 0ull : VMX_EPT_READABLE_MASK) | VMX_EPT_SUPPRESS_VE_BIT;
 	/*
 	 * EPT overrides the host MTRRs, and so KVM must program the desired
 	 * memtype directly into the SPTEs.  Note, this mask is just the mask
@@ -446,7 +448,7 @@ void kvm_mmu_set_ept_masks(bool has_ad_bits, bool has_exec_only)
 	 * 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);
+				   VMX_EPT_RWX_MASK | VMX_EPT_SUPPRESS_VE_BIT, 0);
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_ept_masks);
 
Signature · 1 line
2.25.1
#347 lore raw

PATCH v19 52/130 KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

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. Introduce a separate setter function so that guest TD can override later.

Also require mmio spte caching for TDX. Actually this is true case because TDX requires EPT and KVM EPT allows mmio spte caching.

---
v19:
- fix typo in the commit message.

---
 arch/x86/include/asm/kvm_host.h |  2 ++
 arch/x86/kvm/mmu.h              |  1 +
 arch/x86/kvm/mmu/mmu.c          |  8 +++++---
 arch/x86/kvm/mmu/spte.c         | 10 ++++++++--
 arch/x86/kvm/mmu/spte.h         |  4 ++--
 arch/x86/kvm/mmu/tdp_mmu.c      |  6 +++---
 6 files changed, 21 insertions(+), 10 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index de6dd42d226f..6c10d8d1017f 100644
@@ -1312,6 +1312,8 @@ struct kvm_arch {
 	 */
 	spinlock_t mmu_unsync_pages_lock;
 
+	u64 shadow_mmio_value;
+
 	struct iommu_domain *iommu_domain;
 	bool iommu_noncoherent;
 #define __KVM_HAVE_ARCH_NONCOHERENT_DMA
arch/x86/kvm/mmu.h +1 -0
index 395b55684cb9..ab2854f337ab 100644
@@ -101,6 +101,7 @@ static inline u8 kvm_get_shadow_phys_bits(void)
 }
 
 void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask);
+void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value);
 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 +5 -3
index 211c0e72f45d..84e7a289ad07 100644
@@ -2515,7 +2515,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;
@@ -4184,7 +4184,7 @@ static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
 	if (WARN_ON_ONCE(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);
 
@@ -4837,7 +4837,7 @@ EXPORT_SYMBOL_GPL(kvm_mmu_new_pgd);
 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;
@@ -6357,6 +6357,8 @@ static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
 
 void kvm_mmu_init_vm(struct kvm *kvm)
 {
+
+	kvm->arch.shadow_mmio_value = shadow_mmio_value;
 	INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
 	INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
 	INIT_LIST_HEAD(&kvm->arch.possible_nx_huge_pages);
arch/x86/kvm/mmu/spte.c +8 -2
index 02a466de2991..318135daf685 100644
@@ -74,10 +74,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;
@@ -411,6 +411,12 @@ void kvm_mmu_set_mmio_spte_mask(u64 mmio_value, u64 mmio_mask, u64 access_mask)
 }
 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
 
+void kvm_mmu_set_mmio_spte_value(struct kvm *kvm, u64 mmio_value)
+{
+	kvm->arch.shadow_mmio_value = mmio_value;
+}
+EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_value);
+
 void kvm_mmu_set_me_spte_mask(u64 me_value, u64 me_mask)
 {
 	/* shadow_me_value must be a subset of shadow_me_mask */
arch/x86/kvm/mmu/spte.h +2 -2
index 26bc95bbc962..1a163aee9ec6 100644
@@ -264,9 +264,9 @@ static inline struct kvm_mmu_page *root_to_sp(hpa_t root)
 	return spte_to_child_sp(root);
 }
 
-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 &&
+	return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
 	       likely(enable_mmio_caching);
 }
 
arch/x86/kvm/mmu/tdp_mmu.c +3 -3
index bdeb23ff9e71..04c6af49c3e8 100644
@@ -462,8 +462,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_ONCE(!is_mmio_spte(old_spte) &&
-				 !is_mmio_spte(new_spte) &&
+		if (WARN_ON_ONCE(!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"
@@ -978,7 +978,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);
Signature · 1 line
2.25.1
#348 lore raw

Re: [PATCH v19 052/130] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 8 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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.  Introduce a separate setter function so that guest TD can override later.

Quoted 6 lines

Also require mmio spte caching for TDX.

Actually this is true case
because TDX requires EPT and KVM EPT allows mmio spte caching.

I can't understand what this is trying to say.

Quoted 5 lines


 void kvm_mmu_init_vm(struct kvm *kvm)
 {
+
+       kvm->arch.shadow_mmio_value = shadow_mmio_value;

It could use kvm_mmu_set_mmio_spte_value()?

Quoted 1 line

        INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);

#349 lore raw

Re: [PATCH v19 052/130] KVM: x86/mmu: Track shadow MMIO value on a per-VM basis

Quoted 9 lines · Rick P
Quoted 8 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

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.  Introduce a separate setter function so that guest TD can override later.

Quoted 8 lines
Quoted 6 lines

Also require mmio spte caching for TDX.

Actually this is true case
because TDX requires EPT and KVM EPT allows mmio spte caching.

I can't understand what this is trying to say.

I'll drop this sentence as the logic moved to "069/130 KVM: TDX: Require TDP MMU and mmio caching for TDX".

Quoted 5 lines
Quoted 3 lines

 {
+
+       kvm->arch.shadow_mmio_value = shadow_mmio_value;

It could use kvm_mmu_set_mmio_spte_value()?

Yes.

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

PATCH v19 53/130 KVM: x86/mmu: Disallow fast page fault on private GPA

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

TDX requires TDX SEAMCALL to operate Secure EPT instead of direct memory access and TDX SEAMCALL is heavy operation. Fast page fault on private GPA doesn't make sense. Disallow fast page fault on private GPA.

---
v19:
- updated comment to mention VM type other than TDX.

---
 arch/x86/kvm/mmu/mmu.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
arch/x86/kvm/mmu/mmu.c +12 -2
index 84e7a289ad07..eeebbc67e42b 100644
@@ -3339,8 +3339,18 @@ static int kvm_handle_noslot_fault(struct kvm_vcpu *vcpu,
 	return RET_PF_CONTINUE;
 }
 
-static bool page_fault_can_be_fast(struct kvm_page_fault *fault)
+static bool page_fault_can_be_fast(struct kvm *kvm, struct kvm_page_fault *fault)
 {
+	/*
+	 * TDX private mapping doesn't support fast page fault because the EPT
+	 * entry is read/written with TDX SEAMCALLs instead of direct memory
+	 * access.
+	 * For other VM type, kvm_is_private_gpa() is always false because
+	 * gfn_shared_mask is zero.
+	 */
+	if (kvm_is_private_gpa(kvm, fault->addr))
+		return false;
+
 	/*
 	 * Page faults with reserved bits set, i.e. faults on MMIO SPTEs, only
 	 * reach the common page fault handler if the SPTE has an invalid MMIO
@@ -3450,7 +3460,7 @@ static int fast_page_fault(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 	u64 *sptep;
 	uint retry_count = 0;
 
-	if (!page_fault_can_be_fast(fault))
+	if (!page_fault_can_be_fast(vcpu->kvm, fault))
 		return ret;
 
 	walk_shadow_page_lockless_begin(vcpu);
Signature · 1 line
2.25.1
#351 lore raw

PATCH v19 54/130 KVM: VMX: Introduce test mode related to EPT violation VE

In reply to [email protected]

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.

---
 arch/x86/include/asm/vmx.h | 12 +++++++
 arch/x86/kvm/vmx/vmcs.h    |  5 +++
 arch/x86/kvm/vmx/vmx.c     | 69 +++++++++++++++++++++++++++++++++++++-
 arch/x86/kvm/vmx/vmx.h     |  6 +++-
 4 files changed, 90 insertions(+), 2 deletions(-)
arch/x86/include/asm/vmx.h +12 -0
index 76ed39541a52..f703bae0c4ac 100644
@@ -70,6 +70,7 @@
 #define SECONDARY_EXEC_ENCLS_EXITING		VMCS_CONTROL_BIT(ENCLS_EXITING)
 #define SECONDARY_EXEC_RDSEED_EXITING		VMCS_CONTROL_BIT(RDSEED_EXITING)
 #define SECONDARY_EXEC_ENABLE_PML               VMCS_CONTROL_BIT(PAGE_MOD_LOGGING)
+#define SECONDARY_EXEC_EPT_VIOLATION_VE		VMCS_CONTROL_BIT(EPT_VIOLATION_VE)
 #define SECONDARY_EXEC_PT_CONCEAL_VMX		VMCS_CONTROL_BIT(PT_CONCEAL_VMX)
 #define SECONDARY_EXEC_ENABLE_XSAVES		VMCS_CONTROL_BIT(XSAVES)
 #define SECONDARY_EXEC_MODE_BASED_EPT_EXEC	VMCS_CONTROL_BIT(MODE_BASED_EPT_EXEC)
@@ -225,6 +226,8 @@ enum vmcs_field {
 	VMREAD_BITMAP_HIGH              = 0x00002027,
 	VMWRITE_BITMAP                  = 0x00002028,
 	VMWRITE_BITMAP_HIGH             = 0x00002029,
+	VE_INFORMATION_ADDRESS		= 0x0000202A,
+	VE_INFORMATION_ADDRESS_HIGH	= 0x0000202B,
 	XSS_EXIT_BITMAP                 = 0x0000202C,
 	XSS_EXIT_BITMAP_HIGH            = 0x0000202D,
 	ENCLS_EXITING_BITMAP		= 0x0000202E,
@@ -630,4 +633,13 @@ enum vmx_l1d_flush_state {
 
 extern enum vmx_l1d_flush_state l1tf_vmx_mitigation;
 
+struct vmx_ve_information {
+	u32 exit_reason;
+	u32 delivery;
+	u64 exit_qualification;
+	u64 guest_linear_address;
+	u64 guest_physical_address;
+	u16 eptp_index;
+};
+
 #endif
arch/x86/kvm/vmx/vmcs.h +5 -0
index 7c1996b433e2..b25625314658 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 +68 -1

124 lines not on this page · raw message

arch/x86/kvm/vmx/vmx.h +5 -1
index 04ed2a9eada1..79ff54f08fee 100644
@@ -349,6 +349,9 @@ struct vcpu_vmx {
 		DECLARE_BITMAP(read, MAX_POSSIBLE_PASSTHROUGH_MSRS);
 		DECLARE_BITMAP(write, MAX_POSSIBLE_PASSTHROUGH_MSRS);
 	} shadow_msr_intercept;
+
+	/* ve_info must be page aligned. */
+	struct vmx_ve_information *ve_info;
 };
 
 struct kvm_vmx {
@@ -561,7 +564,8 @@ static inline u8 vmx_get_rvi(void)
 	 SECONDARY_EXEC_ENABLE_VMFUNC |					\
 	 SECONDARY_EXEC_BUS_LOCK_DETECTION |				\
 	 SECONDARY_EXEC_NOTIFY_VM_EXITING |				\
-	 SECONDARY_EXEC_ENCLS_EXITING)
+	 SECONDARY_EXEC_ENCLS_EXITING |					\
+	 SECONDARY_EXEC_EPT_VIOLATION_VE)
 
 #define KVM_REQUIRED_VMX_TERTIARY_VM_EXEC_CONTROL 0
 #define KVM_OPTIONAL_VMX_TERTIARY_VM_EXEC_CONTROL			\
Signature · 1 line
2.25.1
#352 lore raw

PATCH v19 55/130 The start of TDX KVM patch series: KVM TDP MMU hooks

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

This empty commit is to mark the start of patch series of KVM TDP MMU hooks.

---
 Documentation/virt/kvm/intel-tdx-layer-status.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
Documentation/virt/kvm/intel-tdx-layer-status.rst +2 -2
index e893a3d714c7..7903473abad1 100644
@@ -26,5 +26,5 @@ Patch Layer status
 * TD vcpu interrupts/exit/hypercall:    Not yet
 
 * KVM MMU GPA shared bits:              Applied
-* KVM TDP refactoring for TDX:          Applying
-* KVM TDP MMU hooks:                    Not yet
+* KVM TDP refactoring for TDX:          Applied
+* KVM TDP MMU hooks:                    Applying
Signature · 1 line
2.25.1
#353 lore raw

PATCH v19 56/130 KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Refactor tdp_mmu_alloc_sp() and tdp_mmu_init_sp and eliminate tdp_mmu_init_child_sp(). Currently tdp_mmu_init_sp() (or tdp_mmu_init_child_sp()) sets kvm_mmu_page.role after tdp_mmu_alloc_sp() allocating struct kvm_mmu_page and its page table page. This patch makes tdp_mmu_alloc_sp() initialize kvm_mmu_page.role instead of tdp_mmu_init_sp().

To handle private page tables, argument of is_private needs to be passed down. Given that already page level is passed down, it would be cumbersome to add one more parameter about sp. Instead replace the level argument with union kvm_mmu_page_role. Thus the number of argument won't be increased and more info about sp can be passed down.

For private sp, secure page table will be also allocated in addition to struct kvm_mmu_page and page table (spt member). The allocation functions (tdp_mmu_alloc_sp() and __tdp_mmu_alloc_sp_for_split()) need to know if the allocation is for the conventional page table or private page table. Pass union kvm_mmu_role to those functions and initialize role member of struct kvm_mmu_page.

---
 arch/x86/kvm/mmu/tdp_iter.h | 12 ++++++++++
 arch/x86/kvm/mmu/tdp_mmu.c  | 44 ++++++++++++++++---------------------
 2 files changed, 31 insertions(+), 25 deletions(-)
arch/x86/kvm/mmu/tdp_iter.h +12 -0
index fae559559a80..e1e40e3f5eb7 100644
@@ -135,4 +135,16 @@ void tdp_iter_start(struct tdp_iter *iter, struct kvm_mmu_page *root,
 void tdp_iter_next(struct tdp_iter *iter);
 void tdp_iter_restart(struct tdp_iter *iter);
 
+static inline union kvm_mmu_page_role tdp_iter_child_role(struct tdp_iter *iter)
+{
+	union kvm_mmu_page_role child_role;
+	struct kvm_mmu_page *parent_sp;
+
+	parent_sp = sptep_to_sp(rcu_dereference(iter->sptep));
+
+	child_role = parent_sp->role;
+	child_role.level--;
+	return child_role;
+}
+
 #endif /* __KVM_X86_MMU_TDP_ITER_H */
arch/x86/kvm/mmu/tdp_mmu.c +19 -25

119 lines not on this page · raw message

Signature · 1 line
2.25.1
#354 lore raw

Re: [PATCH v19 056/130] KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

To handle private page tables, argument of is_private needs to be passed
down.  Given that already page level is passed down, it would be cumbersome
to add one more parameter about sp. Instead replace the level argument with
union kvm_mmu_page_role.  Thus the number of argument won't be increased
and more info about sp can be passed down.

Quoted 11 lines

For private sp, secure page table will be also allocated in addition to
struct kvm_mmu_page and page table (spt member).  The allocation functions
(tdp_mmu_alloc_sp() and __tdp_mmu_alloc_sp_for_split()) need to know if the
allocation is for the conventional page table or private page table. Pass
union kvm_mmu_role to those functions and initialize role member of struct
kvm_mmu_page.

tdp_mmu_alloc_sp() is only called in two places. One for the root, and one for the mid-level tables.

In later patches when the kvm_mmu_alloc_private_spt() part is added, the root case doesn't need anything done. So the code has to take special care in tdp_mmu_alloc_sp() to avoid doing anything for the root.

It only needs to do the special private spt allocation in non-root case. If we open code that case, I think maybe we could drop this patch, like the below.

The benefits are to drop this patch (which looks to already be part of Paolo's series), and simplify "KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page". I'm not sure though, what do you think? Only build tested.

(quoted diff) +0 -0

b/arch/x86/kvm/mmu/mmu_internal.h
index f1533a753974..d6c2ee8bb636 100644

arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -176,30 +176,12 @@ static inline void

kvm_mmu_init_private_spt(struct kvm_mmu_page *sp, void *priva

static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp)
{
- bool is_root = vcpu->arch.root_mmu.root_role.level == sp-

Quoted 1 line

role.level;

-
- KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu->kvm);
- if (is_root)
- /*
- * Because TDX module assigns root Secure-EPT page and
set it to
- * Secure-EPTP when TD vcpu is created, secure page
table for
- * root isn't needed.
- */
- sp->private_spt = NULL;
- else {
- /*
- * 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.
- */
- sp->private_spt = kvm_mmu_memory_cache_alloc(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache);

- /*
- * Because mmu_private_spt_cache is topped up before
starting
- * kvm page fault resolving, the allocation above
shouldn't
- * fail.
- */
- WARN_ON_ONCE(!sp->private_spt);
- }
+ /*

+        * 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.
+        */

+ sp->private_spt = kvm_mmu_memory_cache_alloc(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache);

}

static inline gfn_t kvm_gfn_for_root(struct kvm *kvm, struct
kvm_mmu_page *root,

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index ac7bf37b353f..f423a38019fb 100644
@@ -195,9 +195,6 @@ static struct kvm_mmu_page *tdp_mmu_alloc_sp(struct

kvm_vcpu *vcpu)
sp = kvm_mmu_memory_cache_alloc(&vcpu-

Quoted 1 line

arch.mmu_page_header_cache);

        sp->spt = kvm_mmu_memory_cache_alloc(&vcpu-
Quoted 1 line

arch.mmu_shadow_page_cache);

- if (kvm_mmu_page_role_is_private(role))
- kvm_mmu_alloc_private_spt(vcpu, sp);
-

        return sp;

}

@@ -1378,6 +1375,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)

                 * needs to be split.
                 */
                sp = tdp_mmu_alloc_sp(vcpu);
+               if (!(raw_gfn & kvm_gfn_shared_mask(kvm)))
+                       kvm_mmu_alloc_private_spt(vcpu, sp);
                tdp_mmu_init_child_sp(sp, &iter);
 
                sp->nx_huge_page_disallowed = fault-
Quoted 1 line

huge_page_disallowed;

@@ -1670,7 +1669,6 @@ static struct kvm_mmu_page *__tdp_mmu_alloc_sp_for_split(struct kvm *kvm, gfp_t

        sp->spt = (void *)__get_free_page(gfp);
        /* TODO: large page support for private GPA. */
-       WARN_ON_ONCE(kvm_mmu_page_role_is_private(role));
        if (!sp->spt) {
                kmem_cache_free(mmu_page_header_cache, sp);
                return NULL;
@@ -1686,10 +1684,6 @@ static struct kvm_mmu_page
*tdp_mmu_alloc_sp_for_split(struct kvm *kvm,
        struct kvm_mmu_page *sp;
 
        kvm_lockdep_assert_mmu_lock_held(kvm, shared);

- KVM_BUG_ON(kvm_mmu_page_role_is_private(role) !=
- is_private_sptep(iter->sptep), kvm);
- /* TODO: Large page isn't supported for private SPTE yet. */
- KVM_BUG_ON(kvm_mmu_page_role_is_private(role), kvm);

/*
* Since we are allocating while under the MMU lock we have to
be

#355 lore raw

Re: [PATCH v19 056/130] KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

Quoted 31 lines · Rick P
Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

To handle private page tables, argument of is_private needs to be passed
down.  Given that already page level is passed down, it would be cumbersome
to add one more parameter about sp. Instead replace the level argument with
union kvm_mmu_page_role.  Thus the number of argument won't be increased
and more info about sp can be passed down.

Quoted 11 lines

For private sp, secure page table will be also allocated in addition to
struct kvm_mmu_page and page table (spt member).  The allocation functions
(tdp_mmu_alloc_sp() and __tdp_mmu_alloc_sp_for_split()) need to know if the
allocation is for the conventional page table or private page table. Pass
union kvm_mmu_role to those functions and initialize role member of struct
kvm_mmu_page.

tdp_mmu_alloc_sp() is only called in two places. One for the root, and one for the mid-level tables.

In later patches when the kvm_mmu_alloc_private_spt() part is added, the root case doesn't need anything done. So the code has to take special care in tdp_mmu_alloc_sp() to avoid doing anything for the root.

Quoted 8 lines

It only needs to do the special private spt allocation in non-root case. If we open code that case, I think maybe we could drop this patch, like the below.

The benefits are to drop this patch (which looks to already be part of Paolo's series), and simplify "KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page". I'm not sure though, what do you think? Only build tested.

Makes sense. Until v18, it had config to disable private mmu part at compile time. Those functions have #ifdef in mmu_internal.h. v19 dropped the config for the feedback.
https://lore.kernel.org/kvm/[email protected]/

After looking at mmu_internal.h, I think the following three function could be open coded.
kvm_mmu_private_spt(), kvm_mmu_init_private_spt(), kvm_mmu_alloc_private_spt(), and kvm_mmu_free_private_spt().

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

Re: [PATCH v19 056/130] KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

Quoted 48 lines · Isaku Yamahata
Quoted 31 lines · Rick P
Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

To handle private page tables, argument of is_private needs to be passed
down.  Given that already page level is passed down, it would be cumbersome
to add one more parameter about sp. Instead replace the level argument with
union kvm_mmu_page_role.  Thus the number of argument won't be increased
and more info about sp can be passed down.

Quoted 11 lines

For private sp, secure page table will be also allocated in addition to
struct kvm_mmu_page and page table (spt member).  The allocation functions
(tdp_mmu_alloc_sp() and __tdp_mmu_alloc_sp_for_split()) need to know if the
allocation is for the conventional page table or private page table. Pass
union kvm_mmu_role to those functions and initialize role member of struct
kvm_mmu_page.

tdp_mmu_alloc_sp() is only called in two places. One for the root, and one for the mid-level tables.

In later patches when the kvm_mmu_alloc_private_spt() part is added, the root case doesn't need anything done. So the code has to take special care in tdp_mmu_alloc_sp() to avoid doing anything for the root.

Quoted 8 lines

It only needs to do the special private spt allocation in non-root case. If we open code that case, I think maybe we could drop this patch, like the below.

The benefits are to drop this patch (which looks to already be part of Paolo's series), and simplify "KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page". I'm not sure though, what do you think? Only build tested.

Makes sense. Until v18, it had config to disable private mmu part at compile time. Those functions have #ifdef in mmu_internal.h. v19 dropped the config for the feedback.
https://lore.kernel.org/kvm/[email protected]/

Quoted 4 lines

After looking at mmu_internal.h, I think the following three function could be open coded.
kvm_mmu_private_spt(), kvm_mmu_init_private_spt(), kvm_mmu_alloc_private_spt(), and kvm_mmu_free_private_spt().

It took me a few minutes to figure out why the mirror root page doesn't need a private_spt.

Per TDX module spec:

Secure EPT’s root page (EPML4 or EPML5, depending on whether the host VMM uses 4-level or 5-level EPT) does not need to be explicitly added. It is created during TD initialization (TDH.MNG.INIT) and is stored as part of TDCS.

I suggest adding the above as a comment somewhere even if we decide to open-code kvm_mmu_alloc_private_spt().

IMO, some TDX details bleed into KVM MMU regardless of whether we open-code kvm_mmu_alloc_private_spt() or not. This isn't good though I cannot think of a better solution.

#357 lore raw

Re: [PATCH v19 056/130] KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

Quoted 57 lines · Chao Gao
Quoted 48 lines · Isaku Yamahata
Quoted 31 lines · Rick P
Quoted 10 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

To handle private page tables, argument of is_private needs to be passed
down.  Given that already page level is passed down, it would be cumbersome
to add one more parameter about sp. Instead replace the level argument with
union kvm_mmu_page_role.  Thus the number of argument won't be increased
and more info about sp can be passed down.

Quoted 11 lines

For private sp, secure page table will be also allocated in addition to
struct kvm_mmu_page and page table (spt member).  The allocation functions
(tdp_mmu_alloc_sp() and __tdp_mmu_alloc_sp_for_split()) need to know if the
allocation is for the conventional page table or private page table. Pass
union kvm_mmu_role to those functions and initialize role member of struct
kvm_mmu_page.

tdp_mmu_alloc_sp() is only called in two places. One for the root, and one for the mid-level tables.

In later patches when the kvm_mmu_alloc_private_spt() part is added, the root case doesn't need anything done. So the code has to take special care in tdp_mmu_alloc_sp() to avoid doing anything for the root.

Quoted 8 lines

It only needs to do the special private spt allocation in non-root case. If we open code that case, I think maybe we could drop this patch, like the below.

The benefits are to drop this patch (which looks to already be part of Paolo's series), and simplify "KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page". I'm not sure though, what do you think? Only build tested.

Makes sense. Until v18, it had config to disable private mmu part at compile time. Those functions have #ifdef in mmu_internal.h. v19 dropped the config for the feedback.
https://lore.kernel.org/kvm/[email protected]/

Quoted 4 lines

After looking at mmu_internal.h, I think the following three function could be open coded.
kvm_mmu_private_spt(), kvm_mmu_init_private_spt(), kvm_mmu_alloc_private_spt(), and kvm_mmu_free_private_spt().

It took me a few minutes to figure out why the mirror root page doesn't need a private_spt.

Quoted 8 lines

Per TDX module spec:

Secure EPT’s root page (EPML4 or EPML5, depending on whether the host VMM uses 4-level or 5-level EPT) does not need to be explicitly added. It is created during TD initialization (TDH.MNG.INIT) and is stored as part of TDCS.

I suggest adding the above as a comment somewhere even if we decide to open-code kvm_mmu_alloc_private_spt().

058/130 has such comment. The citation from the spec would be better.

Quoted 4 lines

IMO, some TDX details bleed into KVM MMU regardless of whether we open-code kvm_mmu_alloc_private_spt() or not. This isn't good though I cannot think of a better solution.

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

Re: [PATCH v19 056/130] KVM: x86/tdp_mmu: Init role member of struct kvm_mmu_page at allocation

In reply to Edgecombe, Rick P

Review int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct · line 1380

Quoted 7 lines · Rick Edgecombe
(quoted diff) +2 -0
@@ -1378,6 +1375,8 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct
 kvm_page_fault *fault)
                  * needs to be split.
                  */
                 sp = tdp_mmu_alloc_sp(vcpu);
+               if (!(raw_gfn & kvm_gfn_shared_mask(kvm)))
+                       kvm_mmu_alloc_private_spt(vcpu, sp);

This will try to allocate the private SP for normal VMs (which have a zero shared mask), it should be:

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index efed70580922..585c80fb62c5 100644
@@ -1350,7 +1350,7 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct

kvm_page_fault *fault)

                 * needs to be split.
                 */
                sp = tdp_mmu_alloc_sp(vcpu);
-               if (!(raw_gfn & kvm_gfn_shared_mask(kvm)))
+               if (kvm_is_private_gpa(kvm, raw_gfn << PAGE_SHIFT))
                        kvm_mmu_alloc_private_spt(vcpu, sp);
                tdp_mmu_init_child_sp(sp, &iter);
#359 lore raw

PATCH v19 57/130 KVM: x86/mmu: Add a new is_private member for union kvm_mmu_page_role

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

Because TDX support introduces private mapping, add a new member in union kvm_mmu_page_role with access functions to check the member.

---
v19:
- Fix is_private_sptep() when NULL case.
- drop CONFIG_KVM_MMU_PRIVATE

---
 arch/x86/include/asm/kvm_host.h | 13 ++++++++++++-
 arch/x86/kvm/mmu/mmu_internal.h |  5 +++++
 arch/x86/kvm/mmu/spte.h         |  7 +++++++
 3 files changed, 24 insertions(+), 1 deletion(-)
arch/x86/include/asm/kvm_host.h +12 -1
index 6c10d8d1017f..dcc6f7c38a83 100644
@@ -349,7 +349,8 @@ union kvm_mmu_page_role {
 		unsigned ad_disabled:1;
 		unsigned guest_mode:1;
 		unsigned passthrough:1;
-		unsigned :5;
+		unsigned is_private:1;
+		unsigned :4;
 
 		/*
 		 * This is left at the top of the word so that
@@ -361,6 +362,16 @@ union kvm_mmu_page_role {
 	};
 };
 
+static inline bool kvm_mmu_page_role_is_private(union kvm_mmu_page_role role)
+{
+	return !!role.is_private;
+}
+
+static inline void kvm_mmu_page_role_set_private(union kvm_mmu_page_role *role)
+{
+	role->is_private = 1;
+}
+
 /*
  * kvm_mmu_extended_role complements kvm_mmu_page_role, tracking properties
  * relevant to the current MMU configuration.   When loading CR0, CR4, or EFER,
arch/x86/kvm/mmu/mmu_internal.h +5 -0
index 0443bfcf5d9c..e3f54701f98d 100644
@@ -145,6 +145,11 @@ static inline int kvm_mmu_page_as_id(struct kvm_mmu_page *sp)
 	return kvm_mmu_role_as_id(sp->role);
 }
 
+static inline bool is_private_sp(const struct kvm_mmu_page *sp)
+{
+	return kvm_mmu_page_role_is_private(sp->role);
+}
+
 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
 	/*
arch/x86/kvm/mmu/spte.h +7 -0
index 1a163aee9ec6..3ef8ea18321b 100644
@@ -264,6 +264,13 @@ static inline struct kvm_mmu_page *root_to_sp(hpa_t root)
 	return spte_to_child_sp(root);
 }
 
+static inline bool is_private_sptep(u64 *sptep)
+{
+	if (WARN_ON_ONCE(!sptep))
+		return false;
+	return is_private_sp(sptep_to_sp(sptep));
+}
+
 static inline bool is_mmio_spte(struct kvm *kvm, u64 spte)
 {
 	return (spte & shadow_mmio_mask) == kvm->arch.shadow_mmio_value &&
Signature · 1 line
2.25.1
#360 lore raw

Re: [PATCH v19 057/130] KVM: x86/mmu: Add a new is_private member for union kvm_mmu_page_role

Quoted 5 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX support introduces private mapping, add a new member in union
kvm_mmu_page_role with access functions to check the member.

I guess we should have a role bit for private like in this patch, but just barely. AFAICT we have a gfn and struct kvm in every place where it is checked (assuming my proposal in patch 56 holds water). So we could have
bool is_private = !(gfn & kvm_gfn_shared_mask(kvm));

But there are extra bits available in the role, so we can skip the extra step. Can you think of any more reasons? I want to try to write a log for this one. It's very short.

arch/x86/kvm/mmu/spte.h static inline struct kvm_mmu_page *root_to_sp(hpa_t root) · line 270

Quoted 5 lines
arch/x86/kvm/mmu/spte.h +4 -0
+static inline bool is_private_sptep(u64 *sptep)
+{
+       if (WARN_ON_ONCE(!sptep))
+               return false;

This is not supposed to be NULL, from the existence of the warning. It looks like some previous comments were to not let the NULL pointer deference happen and bail if it's NULL. I think maybe we should just drop the check and warning completely. The NULL pointer deference will be plenty loud if it happens.

Quoted 3 lines

+       return is_private_sp(sptep_to_sp(sptep));

(quoted diff) +2 -0
+}
+
#361 lore raw

Re: [PATCH v19 057/130] KVM: x86/mmu: Add a new is_private member for union kvm_mmu_page_role

Quoted 7 lines · Rick P
Quoted 5 lines · On Mon, 2024-02-26 at 00:25 -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

Because TDX support introduces private mapping, add a new member in union
kvm_mmu_page_role with access functions to check the member.

Quoted 5 lines

I guess we should have a role bit for private like in this patch, but just barely. AFAICT we have a gfn and struct kvm in every place where it is checked (assuming my proposal in patch 56 holds water). So we could have
bool is_private = !(gfn & kvm_gfn_shared_mask(kvm));

Yes, we can use such combination. or !!sp->private_spt or something. Originally we didn't use role.is_private and passed around private parameter.

Quoted 3 lines

But there are extra bits available in the role, so we can skip the extra step. Can you think of any more reasons? I want to try to write a log for this one. It's very short.

There are several places to compare role and shared<->private. For example, kvm_tdp_mmu_alloc_root(). role.is_private simplifies such comparison.

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

PATCH v19 58/130 KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]

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 private page table, allocate one more page to copy the dummy page table for KVM MMU code to directly walk. Resolve KVM page fault with the existing code, and do additional operations necessary for the private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e. not associated with private page table), and the page table with private page table is called a private page table. The relationship is depicted below.

Add a private pointer to struct kvm_mmu_page for private page table and add helper functions to allocate/initialize/free a private page table page.

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      dummy PT root            |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            dummy PT ----propagate---->   private 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.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU. It is used to propagate PT change to the actual private PT which is used by CPU.

---
v19:
- typo in the comment in kvm_mmu_alloc_private_spt()
- drop CONFIG_KVM_MMU_PRIVATE

---
 arch/x86/include/asm/kvm_host.h |  5 +++
 arch/x86/kvm/mmu/mmu.c          |  7 ++++
 arch/x86/kvm/mmu/mmu_internal.h | 63 ++++++++++++++++++++++++++++++---
 arch/x86/kvm/mmu/tdp_mmu.c      |  1 +
 4 files changed, 72 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +5 -0
index dcc6f7c38a83..efd3fda1c177 100644
@@ -825,6 +825,11 @@ struct kvm_vcpu_arch {
 	struct kvm_mmu_memory_cache mmu_shadow_page_cache;
 	struct kvm_mmu_memory_cache mmu_shadowed_info_cache;
 	struct kvm_mmu_memory_cache mmu_page_header_cache;
+	/*
+	 * This cache is to allocate private page table. E.g.  Secure-EPT used
+	 * by the TDX module.
+	 */
+	struct kvm_mmu_memory_cache mmu_private_spt_cache;
 
 	/*
 	 * QEMU userspace and the guest each have their own FPU state.
arch/x86/kvm/mmu/mmu.c +7 -0
index eeebbc67e42b..0d6d4506ec97 100644
@@ -685,6 +685,12 @@ 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;
+	if (kvm_gfn_shared_mask(vcpu->kvm)) {
+		r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_private_spt_cache,
+					       PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
+	}
 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
 				       PT64_ROOT_MAX_LEVEL);
 	if (r)
@@ -704,6 +710,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_shadowed_info_cache);
+	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_spt_cache);
 	kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache);
 }
 
arch/x86/kvm/mmu/mmu_internal.h +59 -4

81 lines not on this page · raw message

arch/x86/kvm/mmu/tdp_mmu.c +1 -0
index 87233b3ceaef..d47f0daf1b03 100644
@@ -53,6 +53,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
 
 static void tdp_mmu_free_sp(struct kvm_mmu_page *sp)
 {
+	kvm_mmu_free_private_spt(sp);
 	free_page((unsigned long)sp->spt);
 	kmem_cache_free(mmu_page_header_cache, sp);
 }
Signature · 1 line
2.25.1
#363 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 17 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

Quoted 6 lines

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

Quoted 117 lines

  The relationship
is depicted below.

Add a private pointer to struct kvm_mmu_page for private page table and
add helper functions to allocate/initialize/free a private page table page.

              KVM page fault                     |

                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      dummy PT root            |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            dummy PT ----propagate---->   private 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.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

---
v19:
- typo in the comment in kvm_mmu_alloc_private_spt()
- drop CONFIG_KVM_MMU_PRIVATE
---
 arch/x86/include/asm/kvm_host.h |  5 +++ arch/x86/kvm/mmu/mmu.c          |  7 ++++ arch/x86/kvm/mmu/mmu_internal.h | 63 ++++++++++++++++++++++++++++++- --
 arch/x86/kvm/mmu/tdp_mmu.c      |  1 +

 4 files changed, 72 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -0
index dcc6f7c38a83..efd3fda1c177 100644
@@ -825,6 +825,11 @@ struct kvm_vcpu_arch {
         struct kvm_mmu_memory_cache mmu_shadow_page_cache;
         struct kvm_mmu_memory_cache mmu_shadowed_info_cache;
         struct kvm_mmu_memory_cache mmu_page_header_cache;
+       /*
+        * This cache is to allocate private page table. E.g. 

Secure-EPT used
+        * by the TDX module.
+        */
+       struct kvm_mmu_memory_cache mmu_private_spt_cache;
        /*
         * QEMU userspace and the guest each have their own FPU state.

arch/x86/kvm/mmu/mmu.c +0 -0
index eeebbc67e42b..0d6d4506ec97 100644
@@ -685,6 +685,12 @@ 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;
+       if (kvm_gfn_shared_mask(vcpu->kvm)) {
+               r = kvm_mmu_topup_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache,

+                                              PT64_ROOT_MAX_LEVEL); +               if (r)
+                       return r;
+       }
        r = kvm_mmu_topup_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_shadow_page_cache,

                                       PT64_ROOT_MAX_LEVEL); if (r)

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -704,6 +710,7 @@ static void mmu_free_memory_caches(struct
 kvm_vcpu *vcpu)

        kvm_mmu_free_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_pte_list_desc_cache);

        kvm_mmu_free_memory_cache(&vcpu->arch.mmu_shadow_page_cache); kvm_mmu_free_memory_cache(&vcpu-

Quoted 1 line

arch.mmu_shadowed_info_cache);

+       kvm_mmu_free_memory_cache(&vcpu->arch.mmu_private_spt_cache); kvm_mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache); }

arch/x86/kvm/mmu/mmu_internal.h +5 -1
index e3f54701f98d..002f3f80bf3b 100644
@@ -101,7 +101,21 @@ struct kvm_mmu_page {
                 int root_count;
                 refcount_t tdp_mmu_root_count;
         };
-       unsigned int unsync_children;
+       union {
+               struct {
+                       unsigned int unsync_children;
+                       /*
+                        * Number of writes since the last time
Quoted 5 lines

traversal
+                        * visited this page. +                        */
+                       atomic_t write_flooding_count; +               };

I think the point of putting these in a union is that they only apply to shadow paging and so can't be used with TDX. I think you are putting more than the sizeof(void *) in there as there are multiple in the same category. But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

I think the commit log should have more discussion of this union and maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Quoted 67 lines

+               /*
+                * Associated private shadow page table, e.g. Secure- EPT page
+                * passed to the TDX module.
+                */
+               void *private_spt;
+       };
        union {
                struct kvm_rmap_head parent_ptes; /* rmap pointers to parent sptes */
                tdp_ptep_t ptep;

arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -124,9 +138,6 @@ struct kvm_mmu_page {
         int clear_spte_count;
  #endif


-       /* Number of writes since the last time traversal visited this page.  */
-       atomic_t write_flooding_count;
-
 #ifdef CONFIG_X86_64
        /* Used for freeing the page asynchronously if it is a TDP MMU page. */
        struct rcu_head rcu_head;

arch/x86/kvm/mmu/mmu_internal.h +0 -0
@@ -150,6 +161,50 @@ static inline bool is_private_sp(const struct
 kvm_mmu_page *sp)
         return kvm_mmu_page_role_is_private(sp->role);
  }

arch/x86/kvm/mmu/mmu_internal.h +6 -0
+static inline void *kvm_mmu_private_spt(struct kvm_mmu_page *sp)
+{
+       return sp->private_spt;
+}
+
+static inline void kvm_mmu_init_private_spt(struct kvm_mmu_page *sp,

void *private_spt)

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+{
+       sp->private_spt = private_spt;
+}
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu,

struct kvm_mmu_page *sp)
+{
+       bool is_root = vcpu->arch.root_mmu.root_role.level == sp-

Quoted 1 line

role.level;

+
+       KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu-

Quoted 1 line

kvm);

+       if (is_root)
+               /*
+                * Because TDX module assigns root Secure-EPT page and set it to
+                * Secure-EPTP when TD vcpu is created, secure page table for
+                * root isn't needed.
+                */
+               sp->private_spt = NULL;
+       else {
+               /*
+                * 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.
+                */
+               sp->private_spt = kvm_mmu_memory_cache_alloc(&vcpu-

Quoted 1 line

arch.mmu_private_spt_cache);

Quoted 8 lines

+               /*
+                * Because mmu_private_spt_cache is topped up before starting
+                * kvm page fault resolving, the allocation above shouldn't
+                * fail.
+                */
+               WARN_ON_ONCE(!sp->private_spt);

There is already a BUG_ON() for the allocation failure in kvm_mmu_memory_cache_alloc().

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sp(const struct kvm_mmu_page *sp) · line 204

Quoted 6 lines

+       }

arch/x86/kvm/mmu/mmu_internal.h +5 -0
+}
+
+static inline void kvm_mmu_free_private_spt(struct kvm_mmu_page *sp)
+{
+       if (sp->private_spt)

free_page() can accept NULL, so the above check is unneeded.

Quoted 12 lines

+               free_page((unsigned long)sp->private_spt);

arch/x86/kvm/mmu/mmu_internal.h +2 -0
+}
+

 static inline bool kvm_mmu_page_ad_need_write_protect(struct kvm_mmu_page *sp)
 {
        /*

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index 87233b3ceaef..d47f0daf1b03 100644
@@ -53,6 +53,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
Quoted 4 lines


 static void tdp_mmu_free_sp(struct kvm_mmu_page *sp) {
+       kvm_mmu_free_private_spt(sp);

This particular memcache zeros the allocations so it is safe to free this without regard to whether sp->private_spt has been set and that the allocation caller is not in place yet. It would be nice to add this detail in the log.

Quoted 3 lines

        free_page((unsigned long)sp->spt); kmem_cache_free(mmu_page_header_cache, sp); }

#364 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 25 lines · Rick P
Quoted 17 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

Quoted 6 lines

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

Quoted 3 lines

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

How about this,
Call the existing KVM page table associated with shared GPA as shared page table. Call the KVM page table associate with private GPA as private page table.

Quoted 40 lines
Quoted 40 lines

  The relationship
is depicted below.

Add a private pointer to struct kvm_mmu_page for private page table and
add helper functions to allocate/initialize/free a private page table page.

              KVM page fault                     |

                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      dummy PT root            |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT            dummy PT ----propagate---->   private 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.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

---

...snip...

Quoted 17 lines
Quoted 17 lines
arch/x86/kvm/mmu/mmu_internal.h +5 -1
index e3f54701f98d..002f3f80bf3b 100644
@@ -101,7 +101,21 @@ struct kvm_mmu_page {
                 int root_count;
                 refcount_t tdp_mmu_root_count;
         };
-       unsigned int unsync_children;
+       union {
+               struct {
+                       unsigned int unsync_children;
+                       /*
+                        * Number of writes since the last time

traversal
+                        * visited this page.

Quoted 8 lines
Quoted 3 lines

+                        */
+                       atomic_t write_flooding_count; +               };

I think the point of putting these in a union is that they only apply to shadow paging and so can't be used with TDX. I think you are putting more than the sizeof(void *) in there as there are multiple in the same category.

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8. I moved write_flooding_count to have 8 bytes.

Quoted 3 lines

But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

Originally TDX MMU support was implemented for legacy tdp mmu. It used shadowed_translation. It was not an option at that time. Later we switched to (new) TDP MMU. Now we have choice to which member to overlay.

Quoted 4 lines

I think the commit log should have more discussion of this union and maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Sure. We'd like to add void * pointer to struct kvm_mmu_page. Given some members are used only for legacy KVM MMUs and not used for TDP MMU, we can save memory overhead with union. We have options.
- u64 *shadowed_translation
This was not chosen for the old implementation. Now this is option.
- pack unsync_children and write_flooding_count for 8 bytes
This patch chosen this for historical reason. Other two option is possible.
- unsync_child_bitmap
Historically it was unioned with other members. But now it's not.

I don't have strong preference for TDX support as long as we can have void *.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 28 lines · Isaku Yamahata
Quoted 25 lines · Rick P
Quoted 23 lines · On Mon, 2024-02-26 at 00:26 -0800, [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 private
page table, allocate one more page to copy the dummy page table for KVM MMU
code to directly walk.  Resolve KVM page fault with the existing code, and
do additional operations necessary for the private page table.

To
distinguish such cases, the existing KVM page table is called a shared page
table (i.e. not associated with private page table), and the page table
with private page table is called a private page table.

Quoted 7 lines
Quoted 3 lines

This makes it sound like the dummy page table for the private alias is also called a shared page table, but in the drawing below it looks like only the shared alias is called "shared PT".

How about this,
Call the existing KVM page table associated with shared GPA as shared page table. > Call the KVM page table associate with private GPA as private page table.

For the second one, are you talking about the *true* secure/private EPT page table used by hardware, or the one visible to KVM but not used by hardware?

We have 3 page tables as you mentioned:

PT: page table
- Shared PT is visible to KVM and it is used by CPU.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU. It is used to propagate PT change to the actual private PT which is used by CPU.

If I recall correctly, we used to call the last one "mirrored (private) page table".

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Btw, one nit, perhaps:

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

#366 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 12 lines · Kai

We have 3 page tables as you mentioned:

PT: page table
- Shared PT is visible to KVM and it is used by CPU.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

If I recall correctly, we used to call the last one "mirrored (private)
page table".

Quoted 5 lines

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means
it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Mirrored makes sense to me. So like:

Private - Table actually mapping private alias, in TDX module Shared - Shared alias table, visible in KVM
Mirror - Mirroring private, visible in KVM

Quoted 9 lines

Btw, one nit, perhaps:

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

Yep, this seems clearer.

#367 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 28 lines · Rick P
Quoted 12 lines · Kai

We have 3 page tables as you mentioned:

PT: page table
- Shared PT is visible to KVM and it is used by CPU.
- Private PT is used by CPU but it is invisible to KVM.
- Dummy PT is visible to KVM but not used by CPU.  It is used to propagate PT change to the actual private PT which is used by CPU.

If I recall correctly, we used to call the last one "mirrored (private)
page table".

Quoted 5 lines

I lost the tracking when we changed to use "dummy page table", but it seems to me "mirrored" is better than "dummy" because the latter means
it is useless but in fact it is used to propagate changes to the real private page table used by hardware.

Mirrored makes sense to me. So like:

Private - Table actually mapping private alias, in TDX module Shared - Shared alias table, visible in KVM
Mirror - Mirroring private, visible in KVM

Quoted 3 lines

Btw, one nit, perhaps:

Quoted 8 lines
Quoted 6 lines

"Shared PT is visible to KVM and it is used by CPU." -> "Shared PT is visible to KVM and it is used by CPU for shared mappings".

To make it more clearer it is used for "shared mappings".

But this may be unnecessary to others, so up to you.

Yep, this seems clearer.

Here is the updated one. Renamed dummy -> mirroed.

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

              KVM page fault                     |
                     |                           |
                     V                           |
        -------------+----------                 |
        |                      |                 |
        V                      V                 |
     shared GPA           private GPA            |
        |                      |                 |
        V                      V                 |
    shared PT root      mirrored PT root         |    private PT root
        |                      |                 |           |
        V                      V                 |           V
     shared PT           mirrored PT ----propagate---->  private PT
        |                      |                 |           |
        |                      \-----------------+------\    |
        |                                        |      |    |
        V                                        |      V    V
  shared guest page                              |    private guest page
                                                 |
                           non-encrypted memory  |    encrypted memory
                                                 |

PT: Page table
Shared PT: visible to KVM, and the CPU uses it for shared mappings. Private PT: the CPU uses it, but it is invisible to KVM. TDX module
updates this table to map private guest pages.
Mirrored PT: It is visible to KVM, but the CPU doesn't use it. KVM uses it
to propagate PT change to the actual private PT.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 5 lines · Isaku Yamahata

Here is the updated one. Renamed dummy -> mirroed.

When KVM resolves the KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost of directly walking the private page table, allocate one more page to copy the mirrored page

Here "copy" is a bit confusing for me.
The mirrored page table is maintained by KVM, not copied from anywhere.

Quoted 36 lines

table for the KVM MMU code to directly walk. Resolve the KVM page fault with the existing code, and do additional operations necessary for the private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e., not associated with a private page table), and the page table with a private page table is called a mirrored page table. The relationship is depicted below.

               KVM page fault                     |
                      |                           |
                      V                           |
         -------------+----------                 |
         |                      |                 |
         V                      V                 |
      shared GPA           private GPA            |
         |                      |                 |
         V                      V                 |
     shared PT root      mirrored PT root         |    private PT root
         |                      |                 |           |
         V                      V                 |           V
      shared PT           mirrored PT ----propagate---->  private PT
         |                      |                 |           |
         |                      \-----------------+------\    |
         |                                        |      |    |
         V                                        |      V    V
   shared guest page                              |    private guest page
                                                  |
                            non-encrypted memory  |    encrypted memory
                                                  |

PT: Page table
Shared PT: visible to KVM, and the CPU uses it for shared mappings. Private PT: the CPU uses it, but it is invisible to KVM. TDX module
updates this table to map private guest pages.
Mirrored PT: It is visible to KVM, but the CPU doesn't use it. KVM uses it
to propagate PT change to the actual private PT.

#369 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 11 lines · Binbin Wu
Quoted 5 lines · Isaku Yamahata

Here is the updated one. Renamed dummy -> mirroed.

When KVM resolves the KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost of directly walking the private page table, allocate one more page to copy the mirrored page

Here "copy" is a bit confusing for me.
The mirrored page table is maintained by KVM, not copied from anywhere.

How about, "maintain" or "keep"?

Quoted 39 lines
Quoted 37 lines

table for the KVM MMU code to directly walk. Resolve the KVM page fault with the existing code, and do additional operations necessary for the private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e., not associated with a private page table), and the page table with a private page table is called a mirrored page table. The relationship is depicted below.

               KVM page fault                     |
                      |                           |
                      V                           |
         -------------+----------                 |
         |                      |                 |
         V                      V                 |
      shared GPA           private GPA            |
         |                      |                 |
         V                      V                 |
     shared PT root      mirrored PT root         |    private PT root
         |                      |                 |           |
         V                      V                 |           V
      shared PT           mirrored PT ----propagate---->  private PT
         |                      |                 |           |
         |                      \-----------------+------\    |
         |                                        |      |    |
         V                                        |      V    V
   shared guest page                              |    private guest page
                                                  |
                            non-encrypted memory  |    encrypted memory
                                                  |

PT: Page table
Shared PT: visible to KVM, and the CPU uses it for shared mappings. Private PT: the CPU uses it, but it is invisible to KVM. TDX module
updates this table to map private guest pages.
Mirrored PT: It is visible to KVM, but the CPU doesn't use it. KVM uses it
to propagate PT change to the actual private PT.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 5 lines · Isaku Yamahata
Quoted 2 lines · Binbin Wu

On 3/15/2024 9:09 AM, Isaku Yamahata wrote:

Quoted 8 lines
Quoted 7 lines
Quoted 5 lines

Here is the updated one. Renamed dummy -> mirroed.

When KVM resolves the KVM page fault, it walks the page tables. To reuse the existing KVM MMU code and mitigate the heavy cost of directly walking the private page table, allocate one more page to copy the mirrored page

Here "copy" is a bit confusing for me.
The mirrored page table is maintained by KVM, not copied from anywhere.

How about, "maintain" or "keep"?

Or just use "for"?

i.e, allocate one more page for the mirrored page table ...

Quoted 38 lines
Quoted 38 lines
Quoted 37 lines

table for the KVM MMU code to directly walk. Resolve the KVM page fault with the existing code, and do additional operations necessary for the private page table. To distinguish such cases, the existing KVM page table is called a shared page table (i.e., not associated with a private page table), and the page table with a private page table is called a mirrored page table. The relationship is depicted below.

                KVM page fault                     |
                       |                           |
                       V                           |
          -------------+----------                 |
          |                      |                 |
          V                      V                 |
       shared GPA           private GPA            |
          |                      |                 |
          V                      V                 |
      shared PT root      mirrored PT root         |    private PT root
          |                      |                 |           |
          V                      V                 |           V

shared PT mirrored PT ----propagate----> private PT
| | | |
| \-----------------+------\ |
| | | |
V | V V
shared guest page | private guest page
|
non-encrypted memory | encrypted memory
|
PT: Page table
Shared PT: visible to KVM, and the CPU uses it for shared mappings. Private PT: the CPU uses it, but it is invisible to KVM. TDX module
updates this table to map private guest pages.
Mirrored PT: It is visible to KVM, but the CPU doesn't use it. KVM uses it
to propagate PT change to the actual private PT.

#371 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to Isaku Yamahata
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

I think the point of putting these in a union is that they only apply
to shadow paging and so can't be used with TDX. I think you are putting
more than the sizeof(void *) in there as there are multiple in the same
category.

Quoted 4 lines

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8.
I moved write_flooding_count to have 8 bytes.

Ah, I see. Yes you are write about it summing to 8. Ok, what do you think about putting a comment that these will always be unused with TDX?

Quoted 19 lines
Quoted 5 lines

But there seems to be a new one added, *shadowed_translation. Should it go in there too? Is the union because there wasn't room before, or just to be tidy?

Originally TDX MMU support was implemented for legacy tdp mmu.  It used
shadowed_translation.  It was not an option at that time.  Later we switched to
(new) TDP MMU.  Now we have choice to which member to overlay.

Quoted 5 lines

I think the commit log should have more discussion of this union and
maybe a comment in the struct to explain the purpose of the organization. Can you explain the reasoning now for the sake of discussion?

Quoted 7 lines

Sure.  We'd like to add void * pointer to struct kvm_mmu_page.  Given some
members are used only for legacy KVM MMUs and not used for TDP MMU, we can save
memory overhead with union.  We have options.
- u64 *shadowed_translation
  This was not chosen for the old implementation. Now this is option.

This seems a little more straighforward, but I'm on the fence if it's worth changing.

Quoted 8 lines

- pack unsync_children and write_flooding_count for 8 bytes This patch chosen this for historical reason. Other two option is possible.
- unsync_child_bitmap
  Historically it was unioned with other members. But now it's not.

I don't have strong preference for TDX support as long as we can have void *.

#372 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 9 lines · Rick P
Quoted 8 lines · Isaku Yamahata
Quoted 7 lines

I think the point of putting these in a union is that they only apply
to shadow paging and so can't be used with TDX. I think you are putting
more than the sizeof(void *) in there as there are multiple in the same
category.

Quoted 8 lines
Quoted 4 lines

I'm not sure if I'm following you.
On x86_64, sizeof(unsigned int) = 4, sizeof(atomic_t) = 4, sizeof(void *) = 8.
I moved write_flooding_count to have 8 bytes.

Ah, I see. Yes you are write about it summing to 8. Ok, what do you think about putting a comment that these will always be unused with TDX?

Ok, will add a comment. Also add some to the commit message.

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

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

In reply to [email protected]

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sp(const struct kvm_mmu_page *sp) · line 172

Quoted 10 lines · On Mon, Feb 26, 2024 at 12:26:00AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/mmu/mmu_internal.h +9 -0
+static inline void *kvm_mmu_private_spt(struct kvm_mmu_page *sp)
+{
+	return sp->private_spt;
+}
+
+static inline void kvm_mmu_init_private_spt(struct kvm_mmu_page *sp, void *private_spt)
+{
+	sp->private_spt = private_spt;
+}

This function is actually not used for initialization.
Instead, it's only called after failure of free_private_spt() in order to intentionally leak the page to prevent kernel from accessing the encrypted page.

So to avoid confusion, how about renaming it to kvm_mmu_leak_private_spt() and always resetting the pointer to NULL?

static inline void kvm_mmu_leak_private_spt(struct kvm_mmu_page *sp)

{
	sp->private_spt = NULL;
}
Quoted 28 lines
arch/x86/kvm/mmu/mmu_internal.h +28 -0
+
+static inline void kvm_mmu_alloc_private_spt(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
+{
+	bool is_root = vcpu->arch.root_mmu.root_role.level == sp->role.level;
+
+	KVM_BUG_ON(!kvm_mmu_page_role_is_private(sp->role), vcpu->kvm);
+	if (is_root)
+		/*
+		 * Because TDX module assigns root Secure-EPT page and set it to
+		 * Secure-EPTP when TD vcpu is created, secure page table for
+		 * root isn't needed.
+		 */
+		sp->private_spt = NULL;
+	else {
+		/*
+		 * 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.
+		 */
+		sp->private_spt = kvm_mmu_memory_cache_alloc(&vcpu->arch.mmu_private_spt_cache);
+		/*
+		 * Because mmu_private_spt_cache is topped up before starting
+		 * kvm page fault resolving, the allocation above shouldn't
+		 * fail.
+		 */
+		WARN_ON_ONCE(!sp->private_spt);
+	}
+}
#374 lore raw

Re: [PATCH v19 058/130] KVM: x86/mmu: Add a private pointer to struct kvm_mmu_page

Quoted 15 lines · Yan Zhao

arch/x86/kvm/mmu/mmu_internal.h static inline bool is_private_sp(const struct kvm_mmu_page *sp) · line 172

Quoted 10 lines · On Mon, Feb 26, 2024 at 12:26:00AM -0800, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

arch/x86/kvm/mmu/mmu_internal.h +9 -0
+static inline void *kvm_mmu_private_spt(struct kvm_mmu_page *sp)
+{
+	return sp->private_spt;
+}
+
+static inline void kvm_mmu_init_private_spt(struct kvm_mmu_page *sp, void *private_spt)
+{
+	sp->private_spt = private_spt;
+}

This function is actually not used for initialization.
Instead, it's only called after failure of free_private_spt() in order to intentionally leak the page to prevent kernel from accessing the encrypted page.

Quoted 7 lines

So to avoid confusion, how about renaming it to kvm_mmu_leak_private_spt() and always resetting the pointer to NULL?

static inline void kvm_mmu_leak_private_spt(struct kvm_mmu_page *sp)

{
	sp->private_spt = NULL;
}

The older version had a config to disable TDX TDP MMU at a compile time. Now we dropped the config so that we don't necessarily need wrapper function with #ifdef. Now we have only single caller, I'll eliminate this wrapper function (and related wrapper functions) by open code.

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

PATCH v19 59/130 KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory. Also currently, page migration isn't supported for TDX yet. (TDX architecturally supports page migration. it's KVM and kernel implementation issue.)

Regarding memory type change (mtrr virtualization and lapic page mapping change), pages are zapped by kvm_zap_gfn_range(). On the next KVM page fault, the SPTE entry with a new memory type for the page is populated. Regarding page migration, pages are zapped by the mmu notifier. On the next KVM page fault, the new migrated page is populated. Don't zap private pages on unmapping for those two cases.

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM. Don't invalidate private page tables. i.e. zap only leaf SPTEs for KVM mmu that has a shared bit mask. 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 and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table from the hardware and then allocate a new one for it. i.e. replacing a protected root page table. Instead, zap only leaf SPTEs for KVM mmu with a shared bit mask set.

---
 arch/x86/kvm/mmu/mmu.c     | 61 ++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 37 +++++++++++++++++++----
 arch/x86/kvm/mmu/tdp_mmu.h |  5 ++--
 3 files changed, 92 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +58 -3
index 0d6d4506ec97..30c86e858ae4 100644
@@ -6339,7 +6339,7 @@ static void kvm_mmu_zap_all_fast(struct kvm *kvm)
 	 * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock and yield.
 	 */
 	if (tdp_mmu_enabled)
-		kvm_tdp_mmu_invalidate_all_roots(kvm);
+		kvm_tdp_mmu_invalidate_all_roots(kvm, true);
 
 	/*
 	 * Notify all vcpus to reload its shadow page table and flush TLB.
@@ -6459,7 +6459,16 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
 	flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);
 
 	if (tdp_mmu_enabled)
-		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
+		/*
+		 * zap_private = false. Zap only shared pages.
+		 *
+		 * kvm_zap_gfn_range() is used when MTRR or PAT memory
+		 * type was changed.  Later on the next kvm page fault,
+		 * populate it with updated spte entry.
+		 * Because only WB is supported for private pages, don't
+		 * care of private pages.
+		 */
+		flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush, false);
 
 	if (flush)
 		kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);
@@ -6905,10 +6914,56 @@ void kvm_arch_flush_shadow_all(struct kvm *kvm)
 	kvm_mmu_zap_all(kvm);
 }
 
+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.
+	 */
+	if (tdp_mmu_enabled) {
+		struct kvm_gfn_range range = {
+		      .slot = slot,
+		      .start = slot->base_gfn,
+		      .end = slot->base_gfn + slot->npages,
+		      .may_block = true,
+
+		      /*
+		       * This handles both private gfn and shared gfn.
+		       * All private page should be zapped on memslot deletion.
+		       */
+		      .only_private = true,
+		      .only_shared = true,
+		};
+
+		flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);
+	} else {
+		/* TDX supports only TDP-MMU case. */
+		WARN_ON_ONCE(1);
+		flush = true;
+	}
+	if (flush)
+		kvm_flush_remote_tlbs(kvm);
+
+	write_unlock(&kvm->mmu_lock);
+}
+
 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
 				   struct kvm_memory_slot *slot)
 {
-	kvm_mmu_zap_all_fast(kvm);
+	if (kvm_gfn_shared_mask(kvm))
+		/*
+		 * Secure-EPT requires to release PTs from the leaf.  The
+		 * optimization to zap root PT first with child PT doesn't
+		 * work.
+		 */
+		kvm_mmu_zap_memslot(kvm, slot);
+	else
+		kvm_mmu_zap_all_fast(kvm);
 }
 
 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
arch/x86/kvm/mmu/tdp_mmu.c +31 -6
index d47f0daf1b03..e7514a807134 100644
@@ -37,7 +37,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
 	 * for zapping and thus puts the TDP MMU's reference to each root, i.e.
 	 * ultimately frees all roots.
 	 */
-	kvm_tdp_mmu_invalidate_all_roots(kvm);
+	kvm_tdp_mmu_invalidate_all_roots(kvm, false);
 	kvm_tdp_mmu_zap_invalidated_roots(kvm);
 
 	WARN_ON(atomic64_read(&kvm->arch.tdp_mmu_pages));
@@ -771,7 +771,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
  * operation can cause a soft lockup.
  */
 static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
-			      gfn_t start, gfn_t end, bool can_yield, bool flush)
+			      gfn_t start, gfn_t end, bool can_yield, bool flush,
+			      bool zap_private)
 {
 	struct tdp_iter iter;
 
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 
+	WARN_ON_ONCE(zap_private && !is_private_sp(root));
+	if (!zap_private && is_private_sp(root))
+		return false;
+
 	rcu_read_lock();
 
 	for_each_tdp_pte_min_level(iter, root, PG_LEVEL_4K, start, end) {
@@ -810,13 +815,15 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
  * true if a TLB flush is needed before releasing the MMU lock, i.e. if one or
  * more SPTEs were zapped since the MMU lock was last acquired.
  */
-bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush)
+bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush,
+			   bool zap_private)
 {
 	struct kvm_mmu_page *root;
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 	for_each_tdp_mmu_root_yield_safe(kvm, root)
-		flush = tdp_mmu_zap_leafs(kvm, root, start, end, true, flush);
+		flush = tdp_mmu_zap_leafs(kvm, root, start, end, true, flush,
+					  zap_private && is_private_sp(root));
 
 	return flush;
 }
@@ -891,7 +898,7 @@ void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm)
  * Note, kvm_tdp_mmu_zap_invalidated_roots() is gifted the TDP MMU's reference.
  * See kvm_tdp_mmu_get_vcpu_root_hpa().
  */
-void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
+void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm, bool skip_private)
 {
 	struct kvm_mmu_page *root;
 
@@ -916,6 +923,12 @@ void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
 	 * or get/put references to roots.
 	 */
 	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 (skip_private && is_private_sp(root))
+			continue;
 		/*
 		 * Note, invalid roots can outlive a memslot update!  Invalid
 		 * roots must be *zapped* before the memslot update completes,
@@ -1104,14 +1117,26 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 	return ret;
 }
 
+/* Used by mmu notifier via kvm_unmap_gfn_range() */
 bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
 				 bool flush)
 {
 	struct kvm_mmu_page *root;
+	bool zap_private = false;
+
+	if (kvm_gfn_shared_mask(kvm)) {
+		if (!range->only_private && !range->only_shared)
+			/* attributes change */
+			zap_private = !(range->arg.attributes &
+					KVM_MEMORY_ATTRIBUTE_PRIVATE);
+		else
+			zap_private = range->only_private;
+	}
 
 	__for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id, false)
 		flush = tdp_mmu_zap_leafs(kvm, root, range->start, range->end,
-					  range->may_block, flush);
+					  range->may_block, flush,
+					  zap_private && is_private_sp(root));
 
 	return flush;
 }
arch/x86/kvm/mmu/tdp_mmu.h +3 -2
index 20d97aa46c49..b3cf58a50357 100644
@@ -19,10 +19,11 @@ __must_check static inline bool kvm_tdp_mmu_get_root(struct kvm_mmu_page *root)
 
 void kvm_tdp_mmu_put_root(struct kvm *kvm, struct kvm_mmu_page *root);
 
-bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush);
+bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush,
+			   bool zap_private);
 bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp);
 void kvm_tdp_mmu_zap_all(struct kvm *kvm);
-void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm);
+void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm, bool skip_private);
 void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm);
 
 int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault);
Signature · 1 line
2.25.1
#376 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense
for private memory.  Also currently, page migration isn't supported for TDX
yet. (TDX architecturally supports page migration. it's KVM and kernel
implementation issue.)

Quoted 11 lines

Regarding memory type change (mtrr virtualization and lapic page mapping
change), pages are zapped by kvm_zap_gfn_range().  On the next KVM page
fault, the SPTE entry with a new memory type for the page is populated.
Regarding page migration, pages are zapped by the mmu notifier. On the next
KVM page fault, the new migrated page is populated.  Don't zap private
pages on unmapping for those two cases.

Is the migration case relevant to TDX?

Quoted 17 lines

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM.  Don't invalidate private page tables. i.e. zap only leaf
SPTEs for KVM mmu that has a shared bit mask. 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 and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table
from the hardware and then allocate a new one for it. i.e. replacing a
protected root page table.  Instead, zap only leaf SPTEs for KVM mmu with a
shared bit mask set.

I get the part about only zapping leafs and not the root and mid-level PTEs. But why the MTRR, lapic page and migration part? Why should those not be zapped? Why is migration a consideration when it is not supported?

Quoted 55 lines

---
 arch/x86/kvm/mmu/mmu.c     | 61
++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 37 +++++++++++++++++++---- arch/x86/kvm/mmu/tdp_mmu.h |  5 ++--

 3 files changed, 92 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index 0d6d4506ec97..30c86e858ae4 100644
@@ -6339,7 +6339,7 @@ static void kvm_mmu_zap_all_fast(struct kvm
 *kvm)
          * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock

and yield.
         */
        if (tdp_mmu_enabled)
-               kvm_tdp_mmu_invalidate_all_roots(kvm);
+               kvm_tdp_mmu_invalidate_all_roots(kvm, true);
        /*
         * Notify all vcpus to reload its shadow page table and flush TLB.

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6459,7 +6459,16 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t
 gfn_start, gfn_t gfn_end)
         flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);


        if (tdp_mmu_enabled)
-               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
+               /*
+                * zap_private = false. Zap only shared pages. +                *
+                * kvm_zap_gfn_range() is used when MTRR or PAT memory
+                * type was changed.  Later on the next kvm page fault,
+                * populate it with updated spte entry.
+                * Because only WB is supported for private pages, don't
+                * care of private pages.
+                */
+               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush, false);

        if (flush)
                kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6905,10 +6914,56 @@ void kvm_arch_flush_shadow_all(struct kvm
 *kvm)
         kvm_mmu_zap_all(kvm);
  }
Quoted 3 lines


+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)

What about kvm_mmu_zap_memslot_leafs() instead?

Quoted 2 lines

+{
+       bool flush = false;

It doesn't need to be initialized if it passes false directly into kvm_tdp_mmu_unmap_gfn_range(). It would make the code easier to understand.

Quoted 17 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+
+       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. +        */
+       if (tdp_mmu_enabled) {
+               struct kvm_gfn_range range = {
+                     .slot = slot,
+                     .start = slot->base_gfn,
+                     .end = slot->base_gfn + slot->npages, +                     .may_block = true,
+

Quoted 8 lines

+                     /*
+                      * This handles both private gfn and shared gfn.
+                      * All private page should be zapped on memslot deletion.
+                      */
+                     .only_private = true,
+                     .only_shared = true,

only_private and only_shared are both true? Shouldn't they both be false? (or just unset)

Quoted 7 lines

+               };
+
+               flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);
+       } else {
+               /* TDX supports only TDP-MMU case. */ +               WARN_ON_ONCE(1);

How about a KVM_BUG_ON() instead? If somehow this is reached, we don't want the caller thinking the pages are zapped, then enter the guest with pages mapped that have gone elsewhere.

Quoted 1 line

+               flush = true;

Why flush?

Quoted 7 lines

+       }
+       if (flush)
+               kvm_flush_remote_tlbs(kvm);

arch/x86/kvm/mmu/mmu.c +4 -0
+
+       write_unlock(&kvm->mmu_lock);
+}
+
Quoted 5 lines

 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) {
-       kvm_mmu_zap_all_fast(kvm);
+       if (kvm_gfn_shared_mask(kvm))

There seems to be an attempt to abstract away the existence of Secure- EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping in a way specific needed by S-EPT. It ends up being a little confusing because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong, but is more honest about what we are getting up to here. I'm not sure though, what do you think?

Quoted 43 lines

+               /*
+                * Secure-EPT requires to release PTs from the leaf. The
+                * optimization to zap root PT first with child PT doesn't
+                * work.
+                */
+               kvm_mmu_zap_memslot(kvm, slot);
+       else
+               kvm_mmu_zap_all_fast(kvm);
 }

 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index d47f0daf1b03..e7514a807134 100644
@@ -37,7 +37,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
          * for zapping and thus puts the TDP MMU's reference to each

root, i.e.
         * ultimately frees all roots.
         */
-       kvm_tdp_mmu_invalidate_all_roots(kvm);
+       kvm_tdp_mmu_invalidate_all_roots(kvm, false); kvm_tdp_mmu_zap_invalidated_roots(kvm);
WARN_ON(atomic64_read(&kvm->arch.tdp_mmu_pages));

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -771,7 +771,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct
 kvm_mmu_page *sp)
   * operation can cause a soft lockup.
   */

 static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
-                             gfn_t start, gfn_t end, bool can_yield, bool flush)
+                             gfn_t start, gfn_t end, bool can_yield, bool flush,
+                             bool zap_private)
 {
        struct tdp_iter iter;

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm,
 struct kvm_mmu_page *root,
Quoted 4 lines


        lockdep_assert_held_write(&kvm->mmu_lock);
+       WARN_ON_ONCE(zap_private && !is_private_sp(root));

All the callers have zap_private as zap_private && is_private_sp(root). What badness is it trying to uncover?

Quoted 3 lines

+       if (!zap_private && is_private_sp(root))
+               return false;
+

#377 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 24 lines · Rick P
Quoted 11 lines · On Mon, 2024-02-26 at 00:26 -0800, [email protected] wrote:

From: Sean Christopherson <[email protected]>

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense
for private memory.  Also currently, page migration isn't supported for TDX
yet. (TDX architecturally supports page migration. it's KVM and kernel
implementation issue.)

Quoted 11 lines

Regarding memory type change (mtrr virtualization and lapic page mapping
change), pages are zapped by kvm_zap_gfn_range().  On the next KVM page
fault, the SPTE entry with a new memory type for the page is populated.
Regarding page migration, pages are zapped by the mmu notifier. On the next
KVM page fault, the new migrated page is populated.  Don't zap private
pages on unmapping for those two cases.

Quoted 1 line

Is the migration case relevant to TDX?

We can forget about it because the page migration isn't supported yet.

Quoted 17 lines
Quoted 8 lines

When deleting/moving a KVM memory slot, zap private pages. Typically tearing down VM.  Don't invalidate private page tables. i.e. zap only leaf
SPTEs for KVM mmu that has a shared bit mask. 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

Quoted 8 lines

marks the root page table invalid and zaps SPTEs of the root page tables. The TDX module doesn't allow to unlink a protected root page table
from the hardware and then allocate a new one for it. i.e. replacing a
protected root page table.  Instead, zap only leaf SPTEs for KVM mmu with a
shared bit mask set.

Quoted 4 lines

I get the part about only zapping leafs and not the root and mid-level PTEs. But why the MTRR, lapic page and migration part? Why should those not be zapped? Why is migration a consideration when it is not supported?

When we zap a page from the guest, and add it again on TDX even with the same GPA, the page is zeroed. We'd like to keep memory contents for those cases.

Ok, let me add those whys and drop migration part. Here is the updated one.

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory. When we remove the private page from the guest and re-add it with the same GPA, the page is zeroed.

Regarding memory type change (mtrr virtualization and lapic page mapping change), the current implementation zaps pages, and populate the page with new memory type on the next KVM page fault. It doesn't work for TDX to have zeroed pages. Because TDX supports only WB, we ignore the request for MTRR and lapic page change to not zap private pages on unmapping for those two cases

TDX Secure-EPT requires removing the guest pages first and leaf Secure-EPT pages in order. It doesn't allow zap a Secure-EPT entry that has child pages. It doesn't work with the current TDP MMU zapping logic that zaps the root page table without touching child pages. Instead, zap only leaf SPTEs for KVM mmu that has a shared bit mask.

Quoted 53 lines
Quoted 53 lines

---
 arch/x86/kvm/mmu/mmu.c     | 61
++++++++++++++++++++++++++++++++++++--
 arch/x86/kvm/mmu/tdp_mmu.c | 37 +++++++++++++++++++---- arch/x86/kvm/mmu/tdp_mmu.h |  5 ++--

 3 files changed, 92 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/mmu.c +0 -0
index 0d6d4506ec97..30c86e858ae4 100644
@@ -6339,7 +6339,7 @@ static void kvm_mmu_zap_all_fast(struct kvm
 *kvm)
          * e.g. before kvm_zap_obsolete_pages() could drop mmu_lock

and yield.
         */
        if (tdp_mmu_enabled)
-               kvm_tdp_mmu_invalidate_all_roots(kvm);
+               kvm_tdp_mmu_invalidate_all_roots(kvm, true);
        /*
         * Notify all vcpus to reload its shadow page table and flush TLB.

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6459,7 +6459,16 @@ void kvm_zap_gfn_range(struct kvm *kvm, gfn_t
 gfn_start, gfn_t gfn_end)
         flush = kvm_rmap_zap_gfn_range(kvm, gfn_start, gfn_end);


        if (tdp_mmu_enabled)
-               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush);
+               /*
+                * zap_private = false. Zap only shared pages. +                *
+                * kvm_zap_gfn_range() is used when MTRR or PAT memory
+                * type was changed.  Later on the next kvm page fault,
+                * populate it with updated spte entry.
+                * Because only WB is supported for private pages, don't
+                * care of private pages.
+                */
+               flush = kvm_tdp_mmu_zap_leafs(kvm, gfn_start, gfn_end, flush, false);

        if (flush)
                kvm_flush_remote_tlbs_range(kvm, gfn_start, gfn_end - gfn_start);

arch/x86/kvm/mmu/mmu.c +0 -0
@@ -6905,10 +6914,56 @@ void kvm_arch_flush_shadow_all(struct kvm
Quoted 8 lines
Quoted 6 lines
arch/x86/kvm/mmu/mmu.c +0 -0
 *kvm)
         kvm_mmu_zap_all(kvm);
  }


+static void kvm_mmu_zap_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)

What about kvm_mmu_zap_memslot_leafs() instead?

Ok.

Quoted 27 lines
Quoted 2 lines

+{
+       bool flush = false;

It doesn't need to be initialized if it passes false directly into kvm_tdp_mmu_unmap_gfn_range(). It would make the code easier to understand.

Quoted 20 lines
arch/x86/kvm/mmu/mmu.c +5 -0
+
+       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. +        */
+       if (tdp_mmu_enabled) {
+               struct kvm_gfn_range range = {
+                     .slot = slot,
+                     .start = slot->base_gfn,
+                     .end = slot->base_gfn + slot->npages, +                     .may_block = true,
+
+                     /*
+                      * This handles both private gfn and shared gfn.

Quoted 8 lines
Quoted 5 lines

+                      * All private page should be zapped on memslot deletion.
+                      */
+                     .only_private = true,
+                     .only_shared = true,

only_private and only_shared are both true? Shouldn't they both be false? (or just unset)

I replied at.
https://lore.kernel.org/kvm/[email protected]/

Quoted 9 lines
Quoted 8 lines

+               };
+
+               flush = kvm_tdp_mmu_unmap_gfn_range(kvm, &range, flush);
+       } else {
+               /* TDX supports only TDP-MMU case. */ +               WARN_ON_ONCE(1);

Quoted 7 lines

How about a KVM_BUG_ON() instead? If somehow this is reached, we don't want the caller thinking the pages are zapped, then enter the guest with pages mapped that have gone elsewhere.

Quoted 1 line

+               flush = true;

Why flush?

Those are only safe guard. TDX supports only TDP MMU. Let me drop them.

Quoted 21 lines
Quoted 7 lines

+       }
+       if (flush)
+               kvm_flush_remote_tlbs(kvm);

arch/x86/kvm/mmu/mmu.c +4 -0
+
+       write_unlock(&kvm->mmu_lock);
+}
+
Quoted 5 lines

 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) {
-       kvm_mmu_zap_all_fast(kvm);
+       if (kvm_gfn_shared_mask(kvm))

There seems to be an attempt to abstract away the existence of Secure- EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping in a way specific needed by S-EPT. It ends up being a little confusing because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Quoted 3 lines

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong, but is more honest about what we are getting up to here. I'm not sure though, what do you think?

Right, I attempted and failed in zapping case. This is due to the restriction that the Secure-EPT pages must be removed from the leaves. the VMX case (also NPT, even SNP) heavily depends on zapping root entry as optimization.

I can think of
- add TDX check. Looks wrong
- Use kvm_gfn_shared_mask(kvm). confusing
- Give other name for this check like zap_from_leafs (or better name?) The implementation is same to kvm_gfn_shared_mask() with comment.
- Or we can add a boolean variable to struct kvm

Quoted 30 lines
Quoted 30 lines

 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index d47f0daf1b03..e7514a807134 100644
@@ -37,7 +37,7 @@ void kvm_mmu_uninit_tdp_mmu(struct kvm *kvm)
          * for zapping and thus puts the TDP MMU's reference to each

root, i.e.
         * ultimately frees all roots.
         */
-       kvm_tdp_mmu_invalidate_all_roots(kvm);
+       kvm_tdp_mmu_invalidate_all_roots(kvm, false); kvm_tdp_mmu_zap_invalidated_roots(kvm);
WARN_ON(atomic64_read(&kvm->arch.tdp_mmu_pages));

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -771,7 +771,8 @@ bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct
 kvm_mmu_page *sp)
   * operation can cause a soft lockup.
   */

 static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
-                             gfn_t start, gfn_t end, bool can_yield, bool flush)
+                             gfn_t start, gfn_t end, bool can_yield, bool flush,
+                             bool zap_private)
 {
        struct tdp_iter iter;

arch/x86/kvm/mmu/tdp_mmu.c +0 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm,
Quoted 8 lines
Quoted 5 lines
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
 struct kvm_mmu_page *root,


        lockdep_assert_held_write(&kvm->mmu_lock);
+       WARN_ON_ONCE(zap_private && !is_private_sp(root));

All the callers have zap_private as zap_private && is_private_sp(root). What badness is it trying to uncover?

I added this during debug. Let me drop it.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 8 lines · Isaku Yamahata

When we zap a page from the guest, and add it again on TDX even with the same
GPA, the page is zeroed.  We'd like to keep memory contents for those cases.

Ok, let me add those whys and drop migration part. Here is the updated one.

Quoted 8 lines

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory.  When we remove the private page from the guest
and re-add it with the same GPA, the page is zeroed.

Regarding memory type change (mtrr virtualization and lapic page mapping change), the current implementation zaps pages, and populate

                                                                     s^
Quoted 1 line

the page with new memory type on the next KVM page fault.

                               ^s
Quoted 1 line

It doesn't work for TDX to have zeroed pages.

What does this mean? Above you mention how all the pages are zeroed. Do you mean it doesn't work for TDX to zero a running guest's pages. Which would happen for the operations that would expect the pages could get faulted in again just fine.

Quoted 3 lines

Because TDX supports only WB, we
ignore the request for MTRR and lapic page change to not zap private pages on unmapping for those two cases

Hmm. I need to go back and look at this again. It's not clear from the description why it is safe for the host to not zap pages if requested to. I see why the guest wouldn't want them to be zapped.

Quoted 8 lines

TDX Secure-EPT requires removing the guest pages first and leaf Secure-EPT pages in order. It doesn't allow zap a Secure-EPT entry that has child pages.  It doesn't work with the current TDP MMU zapping logic that zaps the root page table without touching child pages.  Instead, zap only leaf SPTEs for KVM mmu that has a shared bit
mask.

Could this be better as two patches that each address a separate thing?
1. Leaf only zapping
2. Don't zap for MTRR, etc.

Quoted 24 lines
Quoted 12 lines

There seems to be an attempt to abstract away the existence of Secure-
EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping
in a way specific needed by S-EPT. It ends up being a little confusing
because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Quoted 5 lines

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong,
but is more honest about what we are getting up to here. I'm not sure
though, what do you think?

Right, I attempted and failed in zapping case.  This is due to the restriction
that the Secure-EPT pages must be removed from the leaves.  the VMX case (also
NPT, even SNP) heavily depends on zapping root entry as optimization.

Quoted 7 lines

I can think of
- add TDX check. Looks wrong
- Use kvm_gfn_shared_mask(kvm). confusing
- Give other name for this check like zap_from_leafs (or better name?)
  The implementation is same to kvm_gfn_shared_mask() with comment.
  - Or we can add a boolean variable to struct kvm

Hmm, maybe wrap it in a function like:
static inline bool kvm_can_only_zap_leafs(const struct kvm *kvm)

{
	/* A comment explaining what is going on */
	return kvm->arch.vm_type == KVM_X86_TDX_VM;
}

But KVM seems to be a bit more on the open coded side when it comes to things like this, so not sure what maintainers would prefer. My opinion is the kvm_gfn_shared_mask() check is too strange and it's worth a new helper. If that is bad, then just open coded kvm->arch.vm_type == KVM_X86_TDX_VM is the second best I think.

I feel both strongly that it should be changed, and unsure what maintainers would prefer. Hopefully one will chime in.

#379 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 9 lines · Rick Edgecombe
Quoted 4 lines

Because TDX supports only WB, we
ignore the request for MTRR and lapic page change to not zap private
pages on unmapping for those two cases

Hmm. I need to go back and look at this again. It's not clear from the
description why it is safe for the host to not zap pages if requested to. I see why the guest wouldn't want them to be zapped.

Ok, I see now how this works. MTRRs and APIC zapping happen to use the same function: kvm_zap_gfn_range(). So restricting that function from zapping private pages has the desired affect. I think it's not ideal that kvm_zap_gfn_range() silently skips zapping some ranges. I wonder if we could pass something in, so it's more clear to the caller.

But can these code paths even get reaches in TDX? It sounded like MTRRs basically weren't supported.

#380 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 11 lines · Rick P
Quoted 9 lines · Rick Edgecombe
Quoted 4 lines

Because TDX supports only WB, we
ignore the request for MTRR and lapic page change to not zap private
pages on unmapping for those two cases

Hmm. I need to go back and look at this again. It's not clear from the
description why it is safe for the host to not zap pages if requested to. I see why the guest wouldn't want them to be zapped.

Quoted 8 lines

Ok, I see now how this works. MTRRs and APIC zapping happen to use the same function: kvm_zap_gfn_range(). So restricting that function from zapping private pages has the desired affect. I think it's not ideal that kvm_zap_gfn_range() silently skips zapping some ranges. I wonder if we could pass something in, so it's more clear to the caller.

But can these code paths even get reaches in TDX? It sounded like MTRRs basically weren't supported.

We can make the code paths so with the (new) assumption that guest MTRR can be disabled cleanly.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 11 lines · Isaku Yamahata
Quoted 11 lines

Ok, I see now how this works. MTRRs and APIC zapping happen to use the
same function: kvm_zap_gfn_range(). So restricting that function from
zapping private pages has the desired affect. I think it's not ideal
that kvm_zap_gfn_range() silently skips zapping some ranges. I wonder
if we could pass something in, so it's more clear to the caller.

Quoted 7 lines
Quoted 3 lines

But can these code paths even get reaches in TDX? It sounded like MTRRs
basically weren't supported.

We can make the code paths so with the (new) assumption that guest MTRR can
be disabled cleanly.

So the situation is (please correct):
KVM has a no "making up architectural behavior" rule, which is an important one. But TDX module doesn't support MTRRs. So TD guests can't have architectural behavior for MTRRs. So this patch is trying as best as possible to match what MTRR behavior it can (not crash the guest if someone tries).

First of all, if the guest unmaps the private memory, doesn't it have to accept it again when gets re-added? So will the guest not crash anyway?

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD... But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

#382 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 27 lines · Rick P
Quoted 11 lines · Isaku Yamahata
Quoted 11 lines

Ok, I see now how this works. MTRRs and APIC zapping happen to use the
same function: kvm_zap_gfn_range(). So restricting that function from
zapping private pages has the desired affect. I think it's not ideal
that kvm_zap_gfn_range() silently skips zapping some ranges. I wonder
if we could pass something in, so it's more clear to the caller.

Quoted 7 lines
Quoted 3 lines

But can these code paths even get reaches in TDX? It sounded like MTRRs
basically weren't supported.

We can make the code paths so with the (new) assumption that guest MTRR can
be disabled cleanly.

So the situation is (please correct):
KVM has a no "making up architectural behavior" rule, which is an important one. But TDX module doesn't support MTRRs. So TD guests can't have architectural behavior for MTRRs. So this patch is trying as best as possible to match what MTRR behavior it can (not crash the guest if someone tries).

Quoted 3 lines

First of all, if the guest unmaps the private memory, doesn't it have to accept it again when gets re-added? So will the guest not crash anyway?

Right, the guest has to accept it on VE. If the unmap was intentional by guest, that's fine. The unmap is unintentional (with vMTRR), the guest doesn't expect VE with the GPA.

Quoted 9 lines

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD... But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

For lapic, it's safe guard. Because TDX KVM disables APICv with APICV_INHIBIT_REASON_TDX, apicv won't call kvm_zap_gfn_range().

For MTRR, the purpose is to make the guest boot (without the guest kernel command line like clearcpuid=mtrr) .
If we can assume the guest won't touch MTRR registers somehow, KVM can return an error to TDG.VP.VMCALL<RDMSR, WRMSR>(MTRR registers). So it doesn't call kvm_zap_gfn_range(). Or we can use KVM_EXIT_X86_{RDMSR, WRMSR} as you suggested.

Signature · 1 line
isaku Yamahata <[email protected]>
#383 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 10 lines · Isaku Yamahata

Right, the guest has to accept it on VE.  If the unmap was intentional by guest, that's fine.  The unmap is unintentional (with vMTRR), the guest doesn't expect VE with the GPA.

Quoted 5 lines

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD...  But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

Quoted 7 lines
Quoted 4 lines

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

For lapic, it's safe guard. Because TDX KVM disables APICv with APICV_INHIBIT_REASON_TDX, apicv won't call kvm_zap_gfn_range().

Ah, I see it:
https://lore.kernel.org/lkml/38e2f8a77e89301534d82325946eb74db3e47815.1708933498.git.isaku.yamahata@intel.com/

Then it seems a warning would be more appropriate if we are worried there might be a way to still call it. If we are confident it can't, then we can just ignore this case.

Quoted 6 lines

For MTRR, the purpose is to make the guest boot (without the guest kernel command line like clearcpuid=mtrr) .
If we can assume the guest won't touch MTRR registers somehow, KVM can return an error to TDG.VP.VMCALL<RDMSR, WRMSR>(MTRR registers). So it doesn't call kvm_zap_gfn_range(). Or we can use KVM_EXIT_X86_{RDMSR, WRMSR} as you suggested.

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus making up behavior that keeps known guests alive. So I would think we should change this patch to only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

#384 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 31 lines · Rick P
Quoted 10 lines · Isaku Yamahata

Right, the guest has to accept it on VE.  If the unmap was intentional by guest, that's fine.  The unmap is unintentional (with vMTRR), the guest doesn't expect VE with the GPA.

Quoted 5 lines

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD...  But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

Quoted 7 lines
Quoted 4 lines

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

For lapic, it's safe guard. Because TDX KVM disables APICv with APICV_INHIBIT_REASON_TDX, apicv won't call kvm_zap_gfn_range().

Ah, I see it:
https://lore.kernel.org/lkml/38e2f8a77e89301534d82325946eb74db3e47815.1708933498.git.isaku.yamahata@intel.com/

Then it seems a warning would be more appropriate if we are worried there might be a way to still call it. If we are confident it can't, then we can just ignore this case.

Quoted 6 lines

For MTRR, the purpose is to make the guest boot (without the guest kernel command line like clearcpuid=mtrr) .
If we can assume the guest won't touch MTRR registers somehow, KVM can return an error to TDG.VP.VMCALL<RDMSR, WRMSR>(MTRR registers). So it doesn't call kvm_zap_gfn_range(). Or we can use KVM_EXIT_X86_{RDMSR, WRMSR} as you suggested.

Quoted 6 lines

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus making up behavior that keeps known guests alive. So I would think we should change this patch to only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

When we hit KVM_MSR_FILTER, the current implementation ignores it and makes it error to guest. Surely we should make it KVM_EXIT_X86_{RDMSR, WRMSR}, instead. It's aligns with the existing implementation(default VM and SW-protected) and more flexible.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 39 lines · Isaku Yamahata
Quoted 36 lines · Rick P
Quoted 10 lines · Isaku Yamahata

Right, the guest has to accept it on VE.  If the unmap was intentional by guest, that's fine.  The unmap is unintentional (with vMTRR), the guest doesn't expect VE with the GPA.

Quoted 5 lines

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD...  But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

Quoted 7 lines
Quoted 4 lines

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

For lapic, it's safe guard. Because TDX KVM disables APICv with APICV_INHIBIT_REASON_TDX, apicv won't call kvm_zap_gfn_range().

Ah, I see it:
https://lore.kernel.org/lkml/38e2f8a77e89301534d82325946eb74db3e47815.1708933498.git.isaku.yamahata@intel.com/

Then it seems a warning would be more appropriate if we are worried there might be a way to still call it. If we are confident it can't, then we can just ignore this case.

Quoted 6 lines

For MTRR, the purpose is to make the guest boot (without the guest kernel command line like clearcpuid=mtrr) .
If we can assume the guest won't touch MTRR registers somehow, KVM can return an error to TDG.VP.VMCALL<RDMSR, WRMSR>(MTRR registers). So it doesn't call kvm_zap_gfn_range(). Or we can use KVM_EXIT_X86_{RDMSR, WRMSR} as you suggested.

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus making up behavior that keeps known guests alive. So I would think we should change this patch to only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

Quoted 6 lines
Quoted 1 line

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

When we hit KVM_MSR_FILTER, the current implementation ignores it and makes it error to guest. Surely we should make it KVM_EXIT_X86_{RDMSR, WRMSR}, instead. It's aligns with the existing implementation(default VM and SW-protected) and more flexible.

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

arch/x86/kvm/vmx/tdx.c +41 -5
index f891de30a2dd..4d9ae5743e24 100644
@@ -1388,31 +1388,67 @@ static int tdx_emulate_mmio(struct kvm_vcpu *vcpu)
 	return 1;
 }
 
+static int tdx_complete_rdmsr(struct kvm_vcpu *vcpu)
+{
+	if (vcpu->run->msr.error)
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+	else {
+		tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+		tdvmcall_set_return_val(vcpu, vcpu->run->msr.data);
+	}
+	return 1;
+}
+
 static int tdx_emulate_rdmsr(struct kvm_vcpu *vcpu)
 {
 	u32 index = tdvmcall_a0_read(vcpu);
 	u64 data;
 
-	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ) ||
-	    kvm_get_msr(vcpu, index, &data)) {
+	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_READ)) {
+		trace_kvm_msr_read_ex(index);
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+		return kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_RDMSR, 0,
+					  tdx_complete_rdmsr,
+					  KVM_MSR_RET_FILTERED);
+	}
+
+	if (kvm_get_msr(vcpu, index, &data)) {
 		trace_kvm_msr_read_ex(index);
 		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
 		return 1;
 	}
-	trace_kvm_msr_read(index, data);
 
+	trace_kvm_msr_read(index, data);
 	tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
 	tdvmcall_set_return_val(vcpu, data);
 	return 1;
 }
 
+static int tdx_complete_wrmsr(struct kvm_vcpu *vcpu)
+{
+	if (vcpu->run->msr.error)
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+	else
+		tdvmcall_set_return_code(vcpu, TDVMCALL_SUCCESS);
+	return 1;
+}
+
 static int tdx_emulate_wrmsr(struct kvm_vcpu *vcpu)
 {
 	u32 index = tdvmcall_a0_read(vcpu);
 	u64 data = tdvmcall_a1_read(vcpu);
 
-	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE) ||
-	    kvm_set_msr(vcpu, index, data)) {
+	if (!kvm_msr_allowed(vcpu, index, KVM_MSR_FILTER_WRITE)) {
+		trace_kvm_msr_write_ex(index, data);
+		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
+		if (kvm_msr_user_space(vcpu, index, KVM_EXIT_X86_WRMSR, data,
+				       tdx_complete_wrmsr,
+				       KVM_MSR_RET_FILTERED))
+			return 1;
+		return 0;
+	}
+
+	if (kvm_set_msr(vcpu, index, data)) {
 		trace_kvm_msr_write_ex(index, data);
 		tdvmcall_set_return_code(vcpu, TDVMCALL_INVALID_OPERAND);
 		return 1;
Signature · 1 line
Isaku Yamahata <[email protected]>
#386 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 9 lines · Isaku Yamahata
Quoted 9 lines
Quoted 8 lines

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus
making up behavior that keeps known guests alive. So I would think we should change this patch to
only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

Quoted 7 lines
Quoted 4 lines

When we hit KVM_MSR_FILTER, the current implementation ignores it and makes it error to guest.  Surely we should make it KVM_EXIT_X86_{RDMSR, WRMSR}, instead. It's aligns with the existing implementation(default VM and SW-protected) and more flexible.

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

#387 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 15 lines · Rick P
Quoted 14 lines · Isaku Yamahata
Quoted 13 lines
Quoted 8 lines

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus
making up behavior that keeps known guests alive. So I would think we should change this patch to
only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

When we hit KVM_MSR_FILTER, the current implementation ignores it and makes it error to guest.  Surely we should make it KVM_EXIT_X86_{RDMSR, WRMSR}, instead. It's aligns with the existing implementation(default VM and SW-protected) and more flexible.

Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

No for TDX at the moment. We need to add such logic.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 18 lines · Isaku Yamahata
Quoted 15 lines · Rick P
Quoted 14 lines · Isaku Yamahata
Quoted 13 lines
Quoted 8 lines

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus
making up behavior that keeps known guests alive. So I would think we should change this patch to
only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

When we hit KVM_MSR_FILTER, the current implementation ignores it and makes it error to guest.  Surely we should make it KVM_EXIT_X86_{RDMSR, WRMSR}, instead. It's aligns with the existing implementation(default VM and SW-protected) and more flexible.

Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

No for TDX at the moment. We need to add such logic.

What if QEMU doesn't configure the set of MSRs to filter? In this case, KVM still needs to handle the MSR accesses.

#389 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 9 lines · Chao Gao
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

No for TDX at the moment.  We need to add such logic.

What if QEMU doesn't configure the set of MSRs to filter? In this case, KVM still needs to handle the MSR accesses.

Do you see a problem for the kernel? I think if any issues are limited to only the guest, then we should count on userspace to configure the msr list.

Today if the MSR access is not allowed by the filter, or the MSR access otherwise fails, an error is returned to the guest. I think Isaku's proposal is to return to userspace if the filter list fails, and return an error to the guest if the access otherwise fails. So the accessible MSRs are the same. It's just change in how error is reported.

#390 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 6 lines · Rick P
Quoted 5 lines · Chao Gao
Quoted 5 lines
Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

No for TDX at the moment.  We need to add such logic.

What if QEMU doesn't configure the set of MSRs to filter? In this case, KVM still needs to handle the MSR accesses.

Do you see a problem for the kernel? I think if any issues are limited to only the guest, then we should count on userspace to configure the msr list.

How can QEMU handle MTRR MSR accesses if KVM exits to QEMU? I am not sure if QEMU needs to do a lot of work to virtualize MTRR.

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings. But guests won't accept memory again because no one currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Quoted 5 lines

Today if the MSR access is not allowed by the filter, or the MSR access otherwise fails, an error is returned to the guest. I think Isaku's proposal is to return to userspace if the filter list fails, and return an error to the guest if the access otherwise fails. So the accessible MSRs are the same. It's just change in how error is reported.

#391 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 9 lines · Chao Gao
Quoted 8 lines · Rick P
Quoted 7 lines · Chao Gao
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

No for TDX at the moment.  We need to add such logic.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

What if QEMU doesn't configure the set of MSRs to filter? In this case, KVM still needs to handle the MSR accesses.

Do you see a problem for the kernel? I think if any issues are limited to only the guest, then we should count on userspace to configure the msr list.

How can QEMU handle MTRR MSR accesses if KVM exits to QEMU? I am not sure if QEMU needs to do a lot of work to virtualize MTRR.

The default kernel logic will to return error for TDG.VP.VMCALL<RDMSR or WRMSR MTRR registers>. Qemu can have mostly same in the current kernel logic.

rdmsr:
MTRRCAP: 0
MTRRDEFTYPE: MTRR_TYPE_WRBACK

wrmsr:
MTRRDEFTYPE: If write back, nop. Otherwise error.

Quoted 8 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings. But guests won't accept memory again because no one currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly. There are manyways for userspace to go wrong. This isn't specific to MTRR MSR.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 42 lines · Isaku Yamahata
Quoted 9 lines · Chao Gao
Quoted 8 lines · Rick P
Quoted 7 lines · Chao Gao
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Something like this for "112/130 KVM: TDX: Handle TDX PV rdmsr/wrmsr hypercall" Compile only tested at this point.

Seems reasonable to me. Does QEMU configure a special set of MSRs to filter for TDX currently?

No for TDX at the moment.  We need to add such logic.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

What if QEMU doesn't configure the set of MSRs to filter? In this case, KVM still needs to handle the MSR accesses.

Do you see a problem for the kernel? I think if any issues are limited to only the guest, then we should count on userspace to configure the msr list.

How can QEMU handle MTRR MSR accesses if KVM exits to QEMU? I am not sure if QEMU needs to do a lot of work to virtualize MTRR.

The default kernel logic will to return error for TDG.VP.VMCALL<RDMSR or WRMSR MTRR registers>. Qemu can have mostly same in the current kernel logic.

rdmsr:
MTRRCAP: 0
MTRRDEFTYPE: MTRR_TYPE_WRBACK

wrmsr:
MTRRDEFTYPE: If write back, nop. Otherwise error.

Quoted 8 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings. But guests won't accept memory again because no one currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Quoted 2 lines

Qemu is expected to do it correctly. There are manyways for userspace to go wrong. This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

#393 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 9 lines · Xiaoyao Li
Quoted 9 lines
Quoted 8 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings. But guests won't accept memory again because no one currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Quoted 6 lines
Quoted 2 lines

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the MSR list. At least I don't see the problem.

#394 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 13 lines · Rick P
Quoted 12 lines · Xiaoyao Li
Quoted 11 lines
Quoted 8 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings. But guests won't accept memory again because no one currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

Quoted 6 lines
Quoted 3 lines

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the MSR list. At least I don't see the problem.

KVM doesn't force it. KVM allows QEMU to use the MSR filter for TDX. (v19 doesn't allow it.) If QEMU chooses to use the MSR filter, QEMU has to handle the MSR access correctly.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Edgecombe, Rick P
Quoted 3 lines · Rick P
Quoted 2 lines · Xiaoyao Li
Quoted 2 lines
Quoted 2 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle
guest's MTRR MSR accesses. In my understanding, the suggestion is KVM zap private memory mappings.

TDX spec states that

18.2.1.4.1 Memory Type for Private and Opaque Access

The memory type for private and opaque access semantics, which use a private HKID, is WB.

18.2.1.4.2 Memory Type for Shared Accesses

Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
• For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
• For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
o Else, the effective memory type for the access is UC.

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

Quoted 10 lines
Quoted 10 lines
Quoted 9 lines
Quoted 6 lines

But guests won't accept memory again because no one
currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

Quoted 6 lines
Quoted 3 lines

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the MSR list. At least I don't see the problem.

What is the exit reason in vcpu->run->exit_reason? KVM_EXIT_X86_RDMSR/WRMSR? If so, it breaks the ABI on KVM_EXIT_X86_RDMSR/WRMSR.

#396 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 32 lines · Xiaoyao Li
Quoted 4 lines · Rick P
Quoted 3 lines · Xiaoyao Li
Quoted 3 lines
Quoted 3 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the
suggestion is KVM zap private memory mappings.

TDX spec states that

18.2.1.4.1 Memory Type for Private and Opaque Access

The memory type for private and opaque access semantics, which use a private HKID, is WB.

18.2.1.4.2 Memory Type for Shared Accesses

Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
• For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
• For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
o Else, the effective memory type for the access is UC.

Quoted 2 lines

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

So, there is no point to (try to) emulate MTRR. The direction is, don't advertise MTRR to the guest (new TDX module is needed.) or enforce the guest to not use MTRR (guest command line clearcpuid=mtrr). KVM will simply return error to guest access to MTRR related registers.

QEMU or user space VMM can use the MSR filter if they want.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
Quoted 9 lines
Quoted 6 lines

But guests won't accept memory again because no one
currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

Quoted 5 lines
Quoted 2 lines

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the MSR list. At least I don't see the problem.

What is the exit reason in vcpu->run->exit_reason? KVM_EXIT_X86_RDMSR/WRMSR? If so, it breaks the ABI on KVM_EXIT_X86_RDMSR/WRMSR.

It's only when the user space requested it with the MSR filter.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 35 lines · Isaku Yamahata
Quoted 32 lines · Xiaoyao Li
Quoted 4 lines · Rick P
Quoted 3 lines · Xiaoyao Li
Quoted 3 lines
Quoted 3 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the
suggestion is KVM zap private memory mappings.

TDX spec states that

18.2.1.4.1 Memory Type for Private and Opaque Access

The memory type for private and opaque access semantics, which use a private HKID, is WB.

18.2.1.4.2 Memory Type for Shared Accesses

Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
• For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
• For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
o Else, the effective memory type for the access is UC.

Quoted 6 lines
Quoted 2 lines

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

So, there is no point to (try to) emulate MTRR. The direction is, don't advertise MTRR to the guest (new TDX module is needed.) or enforce the guest to not use MTRR (guest command line clearcpuid=mtrr).

Ideally, it would be better if TD guest learns to disable/not use MTRR itself.

Quoted 20 lines

KVM will
simply return error to guest access to MTRR related registers.

QEMU or user space VMM can use the MSR filter if they want.

Quoted 14 lines
Quoted 14 lines
Quoted 13 lines
Quoted 9 lines
Quoted 6 lines

But guests won't accept memory again because no one
currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

Quoted 7 lines
Quoted 5 lines
Quoted 2 lines

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the MSR list. At least I don't see the problem.

What is the exit reason in vcpu->run->exit_reason? KVM_EXIT_X86_RDMSR/WRMSR? If so, it breaks the ABI on KVM_EXIT_X86_RDMSR/WRMSR.

It's only when the user space requested it with the MSR filter.

right. But userspace has no reason to filter them because userspace can do nothing except 1) either kill the TD, or 2) eat the instruction.

#398 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Xiaoyao Li
Quoted 27 lines · Xiaoyao Li

TDX spec states that

   18.2.1.4.1 Memory Type for Private and Opaque Access

   The memory type for private and opaque access semantics, which use a private HKID, is WB.

   18.2.1.4.2 Memory Type for Shared Accesses

   Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

   The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
     • For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
     • For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
       o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
       o Else, the effective memory type for the access is UC.

Quoted 2 lines

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

Right, KVM can't zap the private side.

But why does KVM have to support a "best effort" MTRR virtualization for TDs? Kai pointed me to this today and I haven't looked through it in depth yet:
https://lore.kernel.org/kvm/[email protected]/

An alternative could be to mirror that behavior, but normal VMs have to work with existing userspace setup. KVM doesn't support any TDs yet, so we can take the opportunity to not introduce weird things.

Quoted 15 lines
Quoted 15 lines
Quoted 14 lines
Quoted 10 lines
Quoted 7 lines

But guests won't accept memory again because no one
currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

Quoted 7 lines
Quoted 3 lines

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the
MSR list. At least I don't see the problem.

What is the exit reason in vcpu->run->exit_reason? KVM_EXIT_X86_RDMSR/WRMSR? If so, it breaks the ABI on KVM_EXIT_X86_RDMSR/WRMSR.

How so? Userspace needs to learn to create a TD first.

#399 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 33 lines · Rick P
Quoted 27 lines · Xiaoyao Li

TDX spec states that

   18.2.1.4.1 Memory Type for Private and Opaque Access

   The memory type for private and opaque access semantics, which use a private HKID, is WB.

   18.2.1.4.2 Memory Type for Shared Accesses

   Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

   The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
     • For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
     • For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
       o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
       o Else, the effective memory type for the access is UC.

Quoted 2 lines

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

Right, KVM can't zap the private side.

Quoted 7 lines

But why does KVM have to support a "best effort" MTRR virtualization for TDs? Kai pointed me to this today and I haven't looked through it in depth yet:
https://lore.kernel.org/kvm/[email protected]/

An alternative could be to mirror that behavior, but normal VMs have to work with existing userspace setup. KVM doesn't support any TDs yet, so we can take the opportunity to not introduce weird things.

Not to provide any MTRR support for TD is what I prefer.

Quoted 19 lines
Quoted 19 lines
Quoted 18 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines

But guests won't accept memory again because no one
currently requests guests to do this after writes to MTRR MSRs. In this case, guests may access unaccepted memory, causing infinite EPT violation loop (assume SEPT_VE_DISABLE is set). This won't impact other guests/workloads on the host. But I think it would be better if we can avoid wasting CPU resource on the useless EPT violation loop.

Quoted 6 lines
Quoted 2 lines

Qemu is expected to do it correctly.  There are manyways for userspace to go wrong.  This isn't specific to MTRR MSR.

This seems incorrect. KVM shouldn't force userspace to filter some specific MSRs. The semantic of MSR filter is userspace configures it on its own will, not KVM requires to do so.

I'm ok just always doing the exit to userspace on attempt to use MTRRs in a TD, and not rely on the
MSR list. At least I don't see the problem.

Quoted 5 lines
Quoted 3 lines

What is the exit reason in vcpu->run->exit_reason? KVM_EXIT_X86_RDMSR/WRMSR? If so, it breaks the ABI on KVM_EXIT_X86_RDMSR/WRMSR.

How so? Userspace needs to learn to create a TD first.

The current ABI of KVM_EXIT_X86_RDMSR/WRMSR is that userspace itself sets up MSR fitler at first, then it will get such EXIT_REASON when guest accesses the MSRs being filtered.

If you want to use this EXIT reason, then you need to enforce userspace setting up the MSR filter. How to enforce? If not enforce, but exit with KVM_EXIT_X86_RDMSR/WRMSR no matter usersapce sets up MSR filter or not. Then you are trying to introduce divergent behavior in KVM.

#400 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 8 lines · Xiaoyao Li
Quoted 1 line

How so? Userspace needs to learn to create a TD first.

The current ABI of KVM_EXIT_X86_RDMSR/WRMSR is that userspace itself sets up MSR fitler at first, then it will get such EXIT_REASON when guest accesses the MSRs being filtered.

If you want to use this EXIT reason, then you need to enforce userspace setting up the MSR filter. How to enforce?

I think Isaku's proposal was to let userspace configure it.

For the sake of conversation, what if we don't enforce it? The downside of not enforcing it is that we then need to worry about code paths in KVM the MTRRs would call. But what goes wrong functionally? If userspace doesn't fully setup a TD things can go wrong for the TD.

A plus side of using the MSR filter stuff is it reuses existing functionality.

Quoted 3 lines

If not enforce, but exit with
KVM_EXIT_X86_RDMSR/WRMSR no matter usersapce sets up MSR filter or not. Then you are trying to introduce divergent behavior in KVM.

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit reason or behavior in mind?

#401 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 18 lines · Rick P
Quoted 8 lines · Xiaoyao Li
Quoted 1 line

How so? Userspace needs to learn to create a TD first.

The current ABI of KVM_EXIT_X86_RDMSR/WRMSR is that userspace itself sets up MSR fitler at first, then it will get such EXIT_REASON when guest accesses the MSRs being filtered.

If you want to use this EXIT reason, then you need to enforce userspace setting up the MSR filter. How to enforce?

I think Isaku's proposal was to let userspace configure it.

For the sake of conversation, what if we don't enforce it? The downside of not enforcing it is that we then need to worry about code paths in KVM the MTRRs would call. But what goes wrong functionally? If userspace doesn't fully setup a TD things can go wrong for the TD.

A plus side of using the MSR filter stuff is it reuses existing functionality.

Quoted 7 lines
Quoted 3 lines

If not enforce, but exit with
KVM_EXIT_X86_RDMSR/WRMSR no matter usersapce sets up MSR filter or not. Then you are trying to introduce divergent behavior in KVM.

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

#402 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

        {
          "MSB": "12",
          "LSB": "12",
          "Field Size": "1",
          "Field Name": "MTRR",
          "Configuration Details": null,
          "Bit or Field Virtualization Type": "Fixed",
          "Virtualization Details": "0x1"
        },

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR. So that is why I lean towards returning to userspace and giving the VMM the option to ignore it, return an error to the guest or show an error to the user. If KVM can't support the behavior, better to get an actual error in userspace than a mysterious guest hang, right?

Outside of what kind of exit it is, do you object to the general plan to punt to userspace?

Since this is a TDX specific limitation, I guess there is KVM_EXIT_TDX_VMCALL as a general category of TDVMCALLs that cannot be handled by KVM.

#403 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 22 lines · Rick P
Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

         {
           "MSB": "12",
           "LSB": "12",
           "Field Size": "1",
           "Field Name": "MTRR",
           "Configuration Details": null,
           "Bit or Field Virtualization Type": "Fixed",
           "Virtualization Details": "0x1"
         },
Quoted 3 lines

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR.

The root cause is that it's a bad design of TDX to make MTRR fixed1. When guest reads MTRR CPUID as 1 while getting #VE on MTRR MSRs, it already breaks the architectural behavior. (MAC faces the similar issue , MCA is fixed1 as well while accessing MCA related MSRs gets #VE. This is why TDX is going to fix them by introducing new feature and make them configurable)

Quoted 3 lines

So that is why I lean towards
returning to userspace and giving the VMM the option to ignore it, return an error to the guest or show an error to the user.

"show an error to the user" doesn't help at all. Because user cannot fix it, nor does QEMU.

Quoted 2 lines

If KVM can't support the behavior, better to get an actual error in userspace than a mysterious guest hang, right?

What behavior do you mean?

Quoted 4 lines

Outside of what kind of exit it is, do you object to the general plan to punt to userspace?

Since this is a TDX specific limitation, I guess there is KVM_EXIT_TDX_VMCALL as a general category of TDVMCALLs that cannot be handled by KVM.

I just don't see any difference between handling it in KVM and handling it in userspace: either a) return error to guest or b) ignore the WRMSR.

#404 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 23 lines · Xiaoyao Li
Quoted 22 lines · Rick P
Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

         {
           "MSB": "12",
           "LSB": "12",
           "Field Size": "1",
           "Field Name": "MTRR",
           "Configuration Details": null,
           "Bit or Field Virtualization Type": "Fixed",
           "Virtualization Details": "0x1"
         },
Quoted 7 lines
Quoted 3 lines

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR.

The root cause is that it's a bad design of TDX to make MTRR fixed1. When guest reads MTRR CPUID as 1 while getting #VE on MTRR MSRs, it already breaks the architectural behavior. (MAC faces the similar issue , MCA is fixed1 as

I won't say #VE on MTRR MSRs breaks anything. Writes to other MSRs (e.g. TSC_DEADLINE MSR) also lead to #VE. If KVM can emulate the MSR accesses, #VE should be fine.

The problem is: MTRR CPUID feature is fixed 1 while KVM/QEMU doesn't know how to virtualize MTRR especially given that KVM cannot control the memory type in secure-EPT entries.

Quoted 9 lines

well while accessing MCA related MSRs gets #VE. This is why TDX is going to fix them by introducing new feature and make them configurable)

Quoted 3 lines

So that is why I lean towards
returning to userspace and giving the VMM the option to ignore it, return an error to the guest or show an error to the user.

"show an error to the user" doesn't help at all. Because user cannot fix it, nor does QEMU.

The key point isn't who can fix/emulate MTRR MSRs. It is just KVM doesn't know how to handle this situation and ask userspace for help.

Whether or how userspace can handle the MSR writes isn't KVM's problem. It may be better if KVM can tell userspace exactly in which cases KVM will exit to userspace. But there is no such an infrastructure.

An example is: in KVM CET series, we find it is complex for KVM instruction emulator to emulate control flow instructions when CET is enabled. The suggestion is also to punt to userspace (w/o any indication to userspace that KVM would do this).

Quoted 9 lines
Quoted 3 lines

If KVM can't support the behavior, better to get an actual error in userspace than a mysterious guest hang, right?

What behavior do you mean?

Quoted 4 lines

Outside of what kind of exit it is, do you object to the general plan to punt to userspace?

Since this is a TDX specific limitation, I guess there is KVM_EXIT_TDX_VMCALL as a general category of TDVMCALLs that cannot be handled by KVM.

Using KVM_EXIT_TDX_VMCALL looks fine.

We need to explain why MTRR MSRs are handled in this way unlike other MSRs.

It is better if KVM can tell userspace that MTRR virtualization isn't supported by KVM for TDs. Then userspace should resolve the conflict between KVM and TDX module on MTRR. But to report MTRR as unsupported, we need to make GET_SUPPORTED_CPUID a vm-scope ioctl. I am not sure if it is worth the effort.

Quoted 3 lines

I just don't see any difference between handling it in KVM and handling it in
userspace: either a) return error to guest or b) ignore the WRMSR.

#405 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 32 lines · Chao Gao
Quoted 23 lines · Xiaoyao Li
Quoted 22 lines · Rick P
Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

          {
            "MSB": "12",
            "LSB": "12",
            "Field Size": "1",
            "Field Name": "MTRR",
            "Configuration Details": null,
            "Bit or Field Virtualization Type": "Fixed",
            "Virtualization Details": "0x1"
          },
Quoted 7 lines
Quoted 3 lines

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR.

The root cause is that it's a bad design of TDX to make MTRR fixed1. When guest reads MTRR CPUID as 1 while getting #VE on MTRR MSRs, it already breaks the architectural behavior. (MAC faces the similar issue , MCA is fixed1 as

Quoted 7 lines

I won't say #VE on MTRR MSRs breaks anything. Writes to other MSRs (e.g. TSC_DEADLINE MSR) also lead to #VE. If KVM can emulate the MSR accesses, #VE should be fine.

The problem is: MTRR CPUID feature is fixed 1 while KVM/QEMU doesn't know how to virtualize MTRR especially given that KVM cannot control the memory type in secure-EPT entries.

yes, I partly agree on that "#VE on MTRR MSRs breaks anything". #VE is not a problem, the problem is if the #VE is opt-in or unconditional.

For the TSC_DEADLINE_MSR, #VE is opt-in actually. CPUID(1).EXC[24].TSC_DEADLINE is configurable by VMM. Only when VMM configures the bit to 1, will the TD guest get #VE. If VMM configures it to 0, TD guest just gets #GP. This is the reasonable design.

Quoted 13 lines
Quoted 9 lines

well while accessing MCA related MSRs gets #VE. This is why TDX is going to fix them by introducing new feature and make them configurable)

Quoted 3 lines

So that is why I lean towards
returning to userspace and giving the VMM the option to ignore it, return an error to the guest or show an error to the user.

"show an error to the user" doesn't help at all. Because user cannot fix it, nor does QEMU.

The key point isn't who can fix/emulate MTRR MSRs. It is just KVM doesn't know how to handle this situation and ask userspace for help.

Quoted 8 lines

Whether or how userspace can handle the MSR writes isn't KVM's problem. It may be better if KVM can tell userspace exactly in which cases KVM will exit to userspace. But there is no such an infrastructure.

An example is: in KVM CET series, we find it is complex for KVM instruction emulator to emulate control flow instructions when CET is enabled. The suggestion is also to punt to userspace (w/o any indication to userspace that KVM would do this).

Please point me to decision of CET? I'm interested in how userspace can help on that.

Quoted 10 lines
Quoted 9 lines
Quoted 3 lines

If KVM can't support the behavior, better to get an actual error in userspace than a mysterious guest hang, right?

What behavior do you mean?

Quoted 4 lines

Outside of what kind of exit it is, do you object to the general plan to punt to userspace?

Since this is a TDX specific limitation, I guess there is KVM_EXIT_TDX_VMCALL as a general category of TDVMCALLs that cannot be handled by KVM.

Quoted 8 lines

Using KVM_EXIT_TDX_VMCALL looks fine.

We need to explain why MTRR MSRs are handled in this way unlike other MSRs.

It is better if KVM can tell userspace that MTRR virtualization isn't supported by KVM for TDs. Then userspace should resolve the conflict between KVM and TDX module on MTRR. But to report MTRR as unsupported, we need to make GET_SUPPORTED_CPUID a vm-scope ioctl. I am not sure if it is worth the effort.

My memory is that Sean dislike the vm-scope GET_SUPPORTED_CPUID for TDX when he was at Intel.

Anyway, we can provide TDX specific interface to report SUPPORTED_CPUID in KVM_TDX_CAPABILITIES, if we really need it.

Quoted 4 lines
Quoted 4 lines

I just don't see any difference between handling it in KVM and handling it in
userspace: either a) return error to guest or b) ignore the WRMSR.

#406 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 37 lines · Xiaoyao Li
Quoted 36 lines · Chao Gao
Quoted 23 lines · Xiaoyao Li
Quoted 22 lines · Rick P
Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

          {
            "MSB": "12",
            "LSB": "12",
            "Field Size": "1",
            "Field Name": "MTRR",
            "Configuration Details": null,
            "Bit or Field Virtualization Type": "Fixed",
            "Virtualization Details": "0x1"
          },
Quoted 7 lines
Quoted 3 lines

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR.

The root cause is that it's a bad design of TDX to make MTRR fixed1. When guest reads MTRR CPUID as 1 while getting #VE on MTRR MSRs, it already breaks the architectural behavior. (MAC faces the similar issue , MCA is fixed1 as

I won't say #VE on MTRR MSRs breaks anything. Writes to other MSRs (e.g. TSC_DEADLINE MSR) also lead to #VE. If KVM can emulate the MSR accesses, #VE should be fine.

Quoted 6 lines
Quoted 3 lines

The problem is: MTRR CPUID feature is fixed 1 while KVM/QEMU doesn't know how to virtualize MTRR especially given that KVM cannot control the memory type in secure-EPT entries.

yes, I partly agree on that "#VE on MTRR MSRs breaks anything". #VE is not a problem, the problem is if the #VE is opt-in or unconditional.

From guest's p.o.v, there is no difference: the guest doesn't know whether a feature is opted in or not.

Quoted 23 lines

For the TSC_DEADLINE_MSR, #VE is opt-in actually. CPUID(1).EXC[24].TSC_DEADLINE is configurable by VMM. Only when VMM configures the bit to 1, will the TD guest get #VE. If VMM configures it to 0, TD guest just gets #GP. This is the reasonable design.

Quoted 17 lines
Quoted 9 lines

well while accessing MCA related MSRs gets #VE. This is why TDX is going to fix them by introducing new feature and make them configurable)

Quoted 3 lines

So that is why I lean towards
returning to userspace and giving the VMM the option to ignore it, return an error to the guest or show an error to the user.

"show an error to the user" doesn't help at all. Because user cannot fix it, nor does QEMU.

The key point isn't who can fix/emulate MTRR MSRs. It is just KVM doesn't know how to handle this situation and ask userspace for help.

Whether or how userspace can handle the MSR writes isn't KVM's problem. It may be better if KVM can tell userspace exactly in which cases KVM will exit to userspace. But there is no such an infrastructure.

Quoted 7 lines
Quoted 4 lines

An example is: in KVM CET series, we find it is complex for KVM instruction emulator to emulate control flow instructions when CET is enabled. The suggestion is also to punt to userspace (w/o any indication to userspace that KVM would do this).

Please point me to decision of CET? I'm interested in how userspace can help on that.

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

Quoted 15 lines
Quoted 15 lines
Quoted 10 lines
Quoted 4 lines

If KVM can't support the behavior, better to get an actual error in userspace than a mysterious guest hang, right?

What behavior do you mean?

Quoted 4 lines

Outside of what kind of exit it is, do you object to the general plan to punt to userspace?

Since this is a TDX specific limitation, I guess there is KVM_EXIT_TDX_VMCALL as a general category of TDVMCALLs that cannot be handled by KVM.

Using KVM_EXIT_TDX_VMCALL looks fine.

We need to explain why MTRR MSRs are handled in this way unlike other MSRs.

Quoted 7 lines
Quoted 4 lines

It is better if KVM can tell userspace that MTRR virtualization isn't supported by KVM for TDs. Then userspace should resolve the conflict between KVM and TDX module on MTRR. But to report MTRR as unsupported, we need to make GET_SUPPORTED_CPUID a vm-scope ioctl. I am not sure if it is worth the effort.

My memory is that Sean dislike the vm-scope GET_SUPPORTED_CPUID for TDX when he was at Intel.

Ok. No strong opinion on this.

#407 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 42 lines · Chao Gao
Quoted 41 lines · Xiaoyao Li
Quoted 39 lines · Chao Gao
Quoted 23 lines · Xiaoyao Li
Quoted 22 lines · Rick P
Quoted 7 lines · Xiaoyao Li
Quoted 5 lines

The current ABI of KVM_EXIT_X86_RDMSR when TDs are created is nothing. So I don't see how this is
any kind of ABI break. If you agree we shouldn't try to support MTRRs, do you have a different exit
reason or behavior in mind?

Just return error on TDVMCALL of RDMSR/WRMSR on TD's access of MTRR MSRs.

MTRR appears to be configured to be type "Fixed" in the TDX module. So the guest could expect to be able to use it and be surprised by a #GP.

           {
             "MSB": "12",
             "LSB": "12",
             "Field Size": "1",
             "Field Name": "MTRR",
             "Configuration Details": null,
             "Bit or Field Virtualization Type": "Fixed",
             "Virtualization Details": "0x1"
           },
Quoted 7 lines
Quoted 3 lines

If KVM does not support MTRRs in TDX, then it has to return the error somewhere or pretend to support it (do nothing but not return an error). Returning an error to the guest would be making up arch behavior, and to a lesser degree so would ignoring the WRMSR.

The root cause is that it's a bad design of TDX to make MTRR fixed1. When guest reads MTRR CPUID as 1 while getting #VE on MTRR MSRs, it already breaks the architectural behavior. (MAC faces the similar issue , MCA is fixed1 as

I won't say #VE on MTRR MSRs breaks anything. Writes to other MSRs (e.g. TSC_DEADLINE MSR) also lead to #VE. If KVM can emulate the MSR accesses, #VE should be fine.

The problem is: MTRR CPUID feature is fixed 1 while KVM/QEMU doesn't know how to virtualize MTRR especially given that KVM cannot control the memory type in secure-EPT entries.

Quoted 5 lines
Quoted 2 lines

yes, I partly agree on that "#VE on MTRR MSRs breaks anything". #VE is not a problem, the problem is if the #VE is opt-in or unconditional.

From guest's p.o.v, there is no difference: the guest doesn't know whether a feature
is opted in or not.

I don't argue it makes any difference to guest. I argue that it is a bad design of TDX to make MTRR fixed1, which leaves the tough problem to VMM. TDX architecture is one should be blamed.

Though TDX is going to change it, we have to come up something to handle with current existing TDX if we want to support them.

I have no objection of leaving it to userspace, via KVM_EXIT_TDX_VMCALL. If we go this path, I would suggest return error to TD guest on QEMU side (when I prepare the QEMU patch for it) because QEMU cannot emulate it neither.

#408 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 3 lines · Xiaoyao Li

I don't argue it makes any difference to guest. I argue that it is a bad design of TDX to make MTRR fixed1, which leaves the tough problem to VMM. TDX architecture is one should be blamed.

I didn't see anyone arguing against this point. It does seems strange to force something to be exposed that can't be fully handled. I wonder what the history is.

Quoted 3 lines

Though TDX is going to change it, we have to come up something to handle with current existing TDX if we want to support them.

Right. The things being discussed are untenable as long term solutions. The question is, is there anything acceptable in the meantime. That is the goal of this thread.

We do have the other option of waiting for a new TDX module that could fix it better, but I thought exiting to userspace for the time being would be way to move forward.

Would be great to have a maintainer chime in on this point.

Quoted 5 lines

I have no objection of leaving it to userspace, via KVM_EXIT_TDX_VMCALL. If we go this path, I would suggest return error to TD guest on QEMU side (when I prepare the QEMU patch for it) because QEMU cannot emulate it neither.

It would be nice to give the user (user of qemu) some sort of notice of what was going on. For Linux the workaround is clearcpuid=mtrr. If qemu can print something like "MTRRs not supported", or I don't know what message fits. Then the user can see what the problem is and add that to the kernel command line. If they just see a guest crash because it can't handle the error, they will have to debug.

#409 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Xiaoyao Li
Quoted 32 lines · Xiaoyao Li
Quoted 4 lines · Rick P
Quoted 3 lines · Xiaoyao Li
Quoted 3 lines
Quoted 3 lines

If QEMU doesn't configure the msr filter list correctly, KVM has to handle guest's MTRR MSR accesses. In my understanding, the
suggestion is KVM zap private memory mappings.

TDX spec states that

18.2.1.4.1 Memory Type for Private and Opaque Access

The memory type for private and opaque access semantics, which use a private HKID, is WB.

18.2.1.4.2 Memory Type for Shared Accesses

Intel SDM, Vol. 3, 28.2.7.2 Memory Type Used for Translated Guest- Physical Addresses

The memory type for shared access semantics, which use a shared HKID, is determined as described below. Note that this is different from the way memory type is determined by the hardware during non-root mode operation. Rather, it is a best-effort approximation that is designed to still allow the host VMM some control over memory type.
• For shared access during host-side (SEAMCALL) flows, the memory type is determined by MTRRs.
• For shared access during guest-side flows (VM exit from the guest TD), the memory type is determined by a combination of the Shared EPT and MTRRs.
o If the memory type determined during Shared EPT walk is WB, then the effective memory type for the access is determined by MTRRs.
o Else, the effective memory type for the access is UC.

Quoted 2 lines

My understanding is that guest MTRR doesn't affect the memory type for private memory. So we don't need to zap private memory mappings.

This isn't related to the discussion. IIUC, this is the memory type used by TDX module code to access shared/private memory.

I didn't suggest zapping private memory. It is my understanding about what we will end up with, if KVM relies on QEMU to filter MTRR MSRs but somehow QEMU fails to do that.

#410 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Edgecombe, Rick P
Quoted 31 lines · Rick P
Quoted 10 lines · Isaku Yamahata

Right, the guest has to accept it on VE.  If the unmap was intentional by guest, that's fine.  The unmap is unintentional (with vMTRR), the guest doesn't expect VE with the GPA.

Quoted 5 lines

But, I guess we should punt to userspace is the guest tries to use MTRRs, not that userspace can handle it happening in a TD...  But it seems cleaner and safer then skipping zapping some pages inside the zapping code.

Quoted 7 lines
Quoted 4 lines

I'm still not sure if I understand the intention and constraints fully. So please correct. This (the skipping the zapping for some operations) is a theoretical correctness issue right? It doesn't resolve a TD crash?

For lapic, it's safe guard. Because TDX KVM disables APICv with APICV_INHIBIT_REASON_TDX, apicv won't call kvm_zap_gfn_range().

Ah, I see it:
https://lore.kernel.org/lkml/38e2f8a77e89301534d82325946eb74db3e47815.1708933498.git.isaku.yamahata@intel.com/

Then it seems a warning would be more appropriate if we are worried there might be a way to still call it. If we are confident it can't, then we can just ignore this case.

Quoted 6 lines

For MTRR, the purpose is to make the guest boot (without the guest kernel command line like clearcpuid=mtrr) .
If we can assume the guest won't touch MTRR registers somehow, KVM can return an error to TDG.VP.VMCALL<RDMSR, WRMSR>(MTRR registers). So it doesn't call kvm_zap_gfn_range(). Or we can use KVM_EXIT_X86_{RDMSR, WRMSR} as you suggested.

Quoted 4 lines

My understanding is that Sean prefers to exit to userspace when KVM can't handle something, versus making up behavior that keeps known guests alive. So I would think we should change this patch to only be about not using the zapping roots optimization. Then a separate patch should exit to userspace on attempt to use MTRRs. And we ignore the APIC one.

Certainly no. If exit to userspace, what is the exit reason and what is expected for userspace to do? userspace can do nothing, except either kill the TD or eat the RDMSR/WRMSR.

There is nothing to do with userspace. MTRR is virtualized as fixed1 for TD (by current TDX architecture). Userspace can do nothing on it and it's not userspace's fault to let TD guest manipulate on MTRR MSRs.

This is the bad design of current TDX, what KVM should do is return error to TD on TDVMCALL of WR/RDMSR on MTRR MSRs. This should be a known flaw of TDX that MTRR is not supported though TD guest reads the MTRR CPUID as 1.

This flaw should be fixed by TDX architecture that making MTRR configurable. At that time, userspace is responsible to set MSR filter on MTRR MSRs if it wants to configure the MTRR CPUID to 1.

Quoted 1 line

This is trying to guess what maintainers would want here. I'm less sure what Paolo prefers.

#411 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to Edgecombe, Rick P
Quoted 18 lines · Rick P
Quoted 8 lines · Isaku Yamahata

When we zap a page from the guest, and add it again on TDX even with the same
GPA, the page is zeroed.  We'd like to keep memory contents for those cases.

Ok, let me add those whys and drop migration part. Here is the updated one.

Quoted 8 lines

TDX supports only write-back(WB) memory type for private memory architecturally so that (virtualized) memory type change doesn't make sense for private memory.  When we remove the private page from the guest
and re-add it with the same GPA, the page is zeroed.

Regarding memory type change (mtrr virtualization and lapic page mapping change), the current implementation zaps pages, and populate

                                                                     s^
Quoted 8 lines
Quoted 1 line

the page with new memory type on the next KVM page fault.

                               ^s
Quoted 1 line

It doesn't work for TDX to have zeroed pages.

What does this mean? Above you mention how all the pages are zeroed. Do you mean it doesn't work for TDX to zero a running guest's pages. Which would happen for the operations that would expect the pages could get faulted in again just fine.

(non-TDX part of) KVM assumes that page contents are preserved after zapping and re-populate. This isn't true for TDX. The guest would suddenly see zero pages instead of the old memory contents and would be upset.

Quoted 7 lines
Quoted 3 lines

Because TDX supports only WB, we
ignore the request for MTRR and lapic page change to not zap private pages on unmapping for those two cases

Hmm. I need to go back and look at this again. It's not clear from the description why it is safe for the host to not zap pages if requested to. I see why the guest wouldn't want them to be zapped.

KVM siltently ignores the request to change memory types.

Quoted 11 lines
Quoted 7 lines

TDX Secure-EPT requires removing the guest pages first and leaf Secure-EPT pages in order. It doesn't allow zap a Secure-EPT entry that has child pages.  It doesn't work with the current TDP MMU zapping logic that zaps the root page table without touching child pages.  Instead, zap only leaf SPTEs for KVM mmu that has a shared bit
mask.

Could this be better as two patches that each address a separate thing?
1. Leaf only zapping
2. Don't zap for MTRR, etc.

Makes sense. Let's split it.

Quoted 38 lines
Quoted 23 lines
Quoted 11 lines

There seems to be an attempt to abstract away the existence of Secure-
EPT in mmu.c, that is not fully successful. In this case the code checks kvm_gfn_shared_mask() to see if it needs to handle the zapping
in a way specific needed by S-EPT. It ends up being a little confusing
because the actual check is about whether there is a shared bit. It only works because only S-EPT is the only thing that has a kvm_gfn_shared_mask().

Quoted 5 lines

Doing something like (kvm->arch.vm_type == KVM_X86_TDX_VM) looks wrong,
but is more honest about what we are getting up to here. I'm not sure
though, what do you think?

Right, I attempted and failed in zapping case.  This is due to the restriction
that the Secure-EPT pages must be removed from the leaves.  the VMX case (also
NPT, even SNP) heavily depends on zapping root entry as optimization.

Quoted 7 lines

I can think of
- add TDX check. Looks wrong
- Use kvm_gfn_shared_mask(kvm). confusing
- Give other name for this check like zap_from_leafs (or better name?)
  The implementation is same to kvm_gfn_shared_mask() with comment.
  - Or we can add a boolean variable to struct kvm

Hmm, maybe wrap it in a function like:
static inline bool kvm_can_only_zap_leafs(const struct kvm *kvm)

{
	/* A comment explaining what is going on */
	return kvm->arch.vm_type == KVM_X86_TDX_VM;
}
Quoted 8 lines

But KVM seems to be a bit more on the open coded side when it comes to things like this, so not sure what maintainers would prefer. My opinion is the kvm_gfn_shared_mask() check is too strange and it's worth a new helper. If that is bad, then just open coded kvm->arch.vm_type == KVM_X86_TDX_VM is the second best I think.

I feel both strongly that it should be changed, and unsure what maintainers would prefer. Hopefully one will chime in.

Now compile time config is dropped, open code is option.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]

arch/x86/kvm/mmu/tdp_mmu.c static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, · line 785

Quoted 7 lines · On Mon, Feb 26, 2024 at 12:26:01AM -0800, [email protected] wrote:
arch/x86/kvm/mmu/tdp_mmu.c +3 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 
+	WARN_ON_ONCE(zap_private && !is_private_sp(root));
+	if (!zap_private && is_private_sp(root))
+		return false;

Should be "return flush;".

Fengwei and I spent one week chasing a bug where virtio-net in the TD guest may stop working at some point after bootup if the host enables numad. We finally found that the bug was introduced by the 'return false' statement, which left some stale EPT entries unflushed.

I am wondering if we can refactor related functions slightly to make it harder to make such mistakes and make it easier to identify them. e.g., we could make "@flush" an in/out parameter of tdp_mmu_zap_leafs(), kvm_tdp_mmu_zap_leafs() and kvm_tdp_mmu_unmap_gfn_range(). It looks more apparent that "*flush = false" below could be problematic if the changes were something like:

	if (!zap_private && is_private_sp(root)) {
		*flush = false;
		return;
	}
Quoted 94 lines
arch/x86/kvm/mmu/tdp_mmu.c +25 -4
+
 	rcu_read_lock();
 
 	for_each_tdp_pte_min_level(iter, root, PG_LEVEL_4K, start, end) {
@@ -810,13 +815,15 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 * true if a TLB flush is needed before releasing the MMU lock, i.e. if one or
 * more SPTEs were zapped since the MMU lock was last acquired.
 */
-bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush)
+bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush,
+			   bool zap_private)
 {
 	struct kvm_mmu_page *root;
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 	for_each_tdp_mmu_root_yield_safe(kvm, root)
-		flush = tdp_mmu_zap_leafs(kvm, root, start, end, true, flush);
+		flush = tdp_mmu_zap_leafs(kvm, root, start, end, true, flush,
+					  zap_private && is_private_sp(root));
 
 	return flush;
 }
@@ -891,7 +898,7 @@ void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm)
 * Note, kvm_tdp_mmu_zap_invalidated_roots() is gifted the TDP MMU's reference.
 * See kvm_tdp_mmu_get_vcpu_root_hpa().
 */
-void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
+void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm, bool skip_private)
 {
 	struct kvm_mmu_page *root;
 
@@ -916,6 +923,12 @@ void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm)
 	 * or get/put references to roots.
 	 */
 	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 (skip_private && is_private_sp(root))
+			continue;
 		/*
 		 * Note, invalid roots can outlive a memslot update!  Invalid
 		 * roots must be *zapped* before the memslot update completes,
@@ -1104,14 +1117,26 @@ int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault)
 	return ret;
 }
 
+/* Used by mmu notifier via kvm_unmap_gfn_range() */
 bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
 				 bool flush)
 {
 	struct kvm_mmu_page *root;
+	bool zap_private = false;
+
+	if (kvm_gfn_shared_mask(kvm)) {
+		if (!range->only_private && !range->only_shared)
+			/* attributes change */
+			zap_private = !(range->arg.attributes &
+					KVM_MEMORY_ATTRIBUTE_PRIVATE);
+		else
+			zap_private = range->only_private;
+	}
 
 	__for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id, false)
 		flush = tdp_mmu_zap_leafs(kvm, root, range->start, range->end,
-					  range->may_block, flush);
+					  range->may_block, flush,
+					  zap_private && is_private_sp(root));
 
 	return flush;
 }
arch/x86/kvm/mmu/tdp_mmu.h +3 -2
index 20d97aa46c49..b3cf58a50357 100644
@@ -19,10 +19,11 @@ __must_check static inline bool kvm_tdp_mmu_get_root(struct kvm_mmu_page *root)
 
 void kvm_tdp_mmu_put_root(struct kvm *kvm, struct kvm_mmu_page *root);
 
-bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush);
+bool kvm_tdp_mmu_zap_leafs(struct kvm *kvm, gfn_t start, gfn_t end, bool flush,
+			   bool zap_private);
 bool kvm_tdp_mmu_zap_sp(struct kvm *kvm, struct kvm_mmu_page *sp);
 void kvm_tdp_mmu_zap_all(struct kvm *kvm);
-void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm);
+void kvm_tdp_mmu_invalidate_all_roots(struct kvm *kvm, bool skip_private);
 void kvm_tdp_mmu_zap_invalidated_roots(struct kvm *kvm);
 
 int kvm_tdp_mmu_map(struct kvm_vcpu *vcpu, struct kvm_page_fault *fault);
Signature · 1 line
2.25.1
#413 lore raw

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

Quoted 11 lines · Chao Gao

arch/x86/kvm/mmu/tdp_mmu.c static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root, · line 785

Quoted 7 lines · On Mon, Feb 26, 2024 at 12:26:01AM -0800, [email protected] wrote:
arch/x86/kvm/mmu/tdp_mmu.c +3 -0
@@ -779,6 +780,10 @@ static bool tdp_mmu_zap_leafs(struct kvm *kvm, struct kvm_mmu_page *root,
 
 	lockdep_assert_held_write(&kvm->mmu_lock);
 
+	WARN_ON_ONCE(zap_private && !is_private_sp(root));
+	if (!zap_private && is_private_sp(root))
+		return false;

Should be "return flush;".

Quoted 4 lines

Fengwei and I spent one week chasing a bug where virtio-net in the TD guest may stop working at some point after bootup if the host enables numad. We finally found that the bug was introduced by the 'return false' statement, which left some stale EPT entries unflushed.

Thank you for chasing it down.

Quoted 10 lines

I am wondering if we can refactor related functions slightly to make it harder to make such mistakes and make it easier to identify them. e.g., we could make "@flush" an in/out parameter of tdp_mmu_zap_leafs(), kvm_tdp_mmu_zap_leafs() and kvm_tdp_mmu_unmap_gfn_range(). It looks more apparent that "*flush = false" below could be problematic if the changes were something like:

	if (!zap_private && is_private_sp(root)) {
		*flush = false;
		return;
	}

Yes, let me look into it.

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

Re: [PATCH v19 059/130] KVM: x86/tdp_mmu: Don't zap private pages for unsupported cases

In reply to [email protected]
Quoted 16 lines · On Mon, 2024-02-26 at 00:26 -0800, [email protected] wrote:

+/* Used by mmu notifier via kvm_unmap_gfn_range() */
 bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
                                 bool flush)
 {
        struct kvm_mmu_page *root;
+       bool zap_private = false;
+
+       if (kvm_gfn_shared_mask(kvm)) {
+               if (!range->only_private && !range->only_shared) +                       /* attributes change */
+                       zap_private = !(range->arg.attributes & +                                       KVM_MEMORY_ATTRIBUTE_PRIVATE); +               else
+                       zap_private = range->only_private;
+       }

Quoted 8 lines


        __for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id, false)
                flush = tdp_mmu_zap_leafs(kvm, root, range->start, range->end, -                                         range->may_block, flush); +                                         range->may_block, flush, +                                         zap_private && is_private_sp(root));

I'm trying to apply the feedback:
- Drop MTRR support
- Changing only_private/shared to exclude_private/shared
...and update the log accordingly. These changes are all intersect in this function and I'm having a hard time trying to justify the resulting logic.

It seems the point of passing the the attributes is because:
"However, looking at kvm_mem_attrs_changed() again, I think invoking kvm_unmap_gfn_range() from generic KVM code is a mistake and shortsighted. Zapping in response to *any* attribute change is very private/shared centric. E.g. if/when we extend attributes to provide per-page RWX protections, zapping existing SPTEs in response to granting *more* permissions may not be necessary or even desirable."
https://lore.kernel.org/all/[email protected]/

But I think shoving the logic for how to handle the attribute changes deep into the zapping code is the opposite extreme. It results in this confusing logic with the decision on what to zap is spread all around.

Instead we should have kvm_arch_pre_set_memory_attributes() adjust the range so it can tell kvm_unmap_gfn_range() which ranges to zap (private/shared).

So:
kvm_vm_set_mem_attributes() - passes attributes kvm_arch_pre_set_memory_attributes() - chooses which private/shared alias to
zap based on attribute.
kvm_unmap_gfn_range/kvm_tdp_mmu_unmap_gfn_range - zaps the private/shared alias tdp_mmu_zap_leafs() - doesn't care about the root type, just zaps leafs

This zapping function can then just do the simple thing it's told to do. It ends up looking like:

bool kvm_tdp_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range,
bool flush)

{
	struct kvm_mmu_page *root;
	bool exclude_private = false;
	bool exclude_shared = false;

	if (kvm_gfn_shared_mask(kvm)) {
		exclude_private = range->exclude_private;
		exclude_shared = range->exclude_shared;
	}

	__for_each_tdp_mmu_root_yield_safe(kvm, root, range->slot->as_id,
false) {
		if (exclude_private && is_private_sp(root))
			continue;
		if (exclude_shared && !is_private_sp(root))
			continue;

		flush = tdp_mmu_zap_leafs(kvm, root, range->start, range->end,
					  range->may_block, flush);
	}

	return flush;
}

The resulting logic should be the same. Separately, we might be able to simplify it further if we change the behavior a bit (lose the kvm_gfn_shared_mask() check or the exclude_shared member), but in the meantime this seems a lot easier to explain and review for what I think is equivalent behavior.

#415 lore raw

PATCH v19 60/130 KVM: x86/tdp_mmu: Apply mmu notifier callback to only shared GPA

In reply to [email protected]

From: Isaku Yamahata <[email protected]>

The private GPAs that typically guest memfd backs aren't subject to MMU notifier because it isn't mapped into virtual address of user process. kvm_tdp_mmu_handle_gfn() handles the callback of the MMU notifier, clear_flush_young(), clear_young(), test_young()() and change_pte(). Make kvm_tdp_mmu_handle_gfn() aware of private mapping and skip private mapping.

Even with AS_UNMOVABLE set, those mmu notifier are called. For example, ksmd triggers change_pte().

---
v19:
- type: test_gfn() => test_young()

v18:
- newly added

---
 arch/x86/kvm/mmu/tdp_mmu.c | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/tdp_mmu.c +21 -1
index e7514a807134..10507920f36b 100644
@@ -1157,9 +1157,29 @@ 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, end;
+
+		/*
+		 * This function is called on behalf of mmu_notifier of
+		 * clear_flush_young(), clear_young(), test_young()(), and
+		 * change_pte().  They apply to only shared GPAs.
+		 */
+		WARN_ON_ONCE(range->only_private);
+		WARN_ON_ONCE(!range->only_shared);
+		if (is_private_sp(root))
+			continue;
+
+		/*
+		 * 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_to_shared(kvm, range->start);
+		end = kvm_gfn_to_shared(kvm, range->end);
+
 		rcu_read_lock();
 
-		tdp_root_for_each_leaf_pte(iter, root, range->start, range->end)
+		tdp_root_for_each_leaf_pte(iter, root, start, end)
 			ret |= handler(kvm, &iter, range);
 
 		rcu_read_unlock();
Signature · 1 line
2.25.1
#416 lore raw

Re: [PATCH v19 060/130] KVM: x86/tdp_mmu: Apply mmu notifier callback to only shared GPA

Quoted 6 lines · On 2/26/2024 4:26 PM, [email protected] wrote:

From: Isaku Yamahata <[email protected]>

The private GPAs that typically guest memfd backs aren't subject to MMU notifier because it isn't mapped into virtual address of user process. kvm_tdp_mmu_handle_gfn() handles the callback of the MMU notifier, clear_flush_young(), clear_young(), test_young()() and change_pte(). Make

                                                   ^ an extra "()"

Quoted 4 lines

kvm_tdp_mmu_handle_gfn() aware of private mapping and skip private mapping.

Even with AS_UNMOVABLE set, those mmu notifier are called. For example, ksmd triggers change_pte().

The description about the "AS_UNMOVABLE", you are refering to shared memory, right? Then, it seems not related to the change of this patch.

Quoted 20 lines

---
v19:
- type: test_gfn() => test_young()

v18:
- newly added

---
  arch/x86/kvm/mmu/tdp_mmu.c | 22 +++++++++++++++++++++-
  1 file changed, 21 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/tdp_mmu.c +0 -0
index e7514a807134..10507920f36b 100644

arch/x86/kvm/mmu/tdp_mmu.c static __always_inline bool kvm_tdp_mmu_handle_gfn(struct kvm *kvm, · line 1164

Quoted 8 lines
arch/x86/kvm/mmu/tdp_mmu.c +5 -0
@@ -1157,9 +1157,29 @@ 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, end;
+
+		/*
+		 * This function is called on behalf of mmu_notifier of
+		 * clear_flush_young(), clear_young(), test_young()(), and

^
                                                               an extra "()""

Quoted 22 lines
arch/x86/kvm/mmu/tdp_mmu.c +16 -1
+		 * change_pte().  They apply to only shared GPAs.
+		 */
+		WARN_ON_ONCE(range->only_private);
+		WARN_ON_ONCE(!range->only_shared);
+		if (is_private_sp(root))
+			continue;
+
+		/*
+		 * 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_to_shared(kvm, range->start);
+		end = kvm_gfn_to_shared(kvm, range->end);
+
  		rcu_read_lock();
 
-		tdp_root_for_each_leaf_pte(iter, root, range->start, range->end)
+		tdp_root_for_each_leaf_pte(iter, root, start, end)
  			ret |= handler(kvm, &iter, range);
 
  		rcu_read_unlock();