xref: /linux/arch/x86/kvm/vmx/tdx.c (revision 4a8bdffce502d70405391a7ac38bac6dcef94749)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/cleanup.h>
3 #include <linux/cpu.h>
4 #include <asm/cpufeature.h>
5 #include <asm/fpu/xcr.h>
6 #include <linux/misc_cgroup.h>
7 #include <linux/mmu_context.h>
8 #include <asm/tdx.h>
9 #include <asm/virt.h>
10 #include "capabilities.h"
11 #include "mmu.h"
12 #include "x86_ops.h"
13 #include "lapic.h"
14 #include "tdx.h"
15 #include "vmx.h"
16 #include "mmu/spte.h"
17 #include "common.h"
18 #include "posted_intr.h"
19 #include "irq.h"
20 #include <trace/events/kvm.h>
21 #include "trace.h"
22 
23 #pragma GCC poison to_vmx
24 
25 #undef pr_fmt
26 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
27 
28 #define __TDX_BUG_ON(__err, __f, __kvm, __fmt, __args...)			\
29 ({										\
30 	struct kvm *_kvm = (__kvm);						\
31 	bool __ret = !!(__err);							\
32 										\
33 	if (WARN_ON_ONCE(__ret && (!_kvm || !_kvm->vm_bugged))) {		\
34 		if (_kvm)							\
35 			kvm_vm_bugged(_kvm);					\
36 		pr_err_ratelimited("SEAMCALL " __f " failed: 0x%llx" __fmt "\n",\
37 				   __err,  __args);				\
38 	}									\
39 	unlikely(__ret);							\
40 })
41 
42 #define TDX_BUG_ON(__err, __fn, __kvm)				\
43 	__TDX_BUG_ON(__err, #__fn, __kvm, "%s", "")
44 
45 #define TDX_BUG_ON_1(__err, __fn, a1, __kvm)			\
46 	__TDX_BUG_ON(__err, #__fn, __kvm, ", " #a1 " 0x%llx", a1)
47 
48 #define TDX_BUG_ON_2(__err, __fn, a1, a2, __kvm)	\
49 	__TDX_BUG_ON(__err, #__fn, __kvm, ", " #a1 " 0x%llx, " #a2 " 0x%llx", a1, a2)
50 
51 #define TDX_BUG_ON_3(__err, __fn, a1, a2, a3, __kvm)	\
52 	__TDX_BUG_ON(__err, #__fn, __kvm, ", " #a1 " 0x%llx, " #a2 ", 0x%llx, " #a3 " 0x%llx", \
53 		     a1, a2, a3)
54 
55 
56 bool enable_tdx __ro_after_init;
57 module_param_named(tdx, enable_tdx, bool, 0444);
58 
59 #define TDX_SHARED_BIT_PWL_5 gpa_to_gfn(BIT_ULL(51))
60 #define TDX_SHARED_BIT_PWL_4 gpa_to_gfn(BIT_ULL(47))
61 
62 static const struct tdx_sys_info *tdx_sysinfo;
63 
tdh_vp_rd_failed(struct vcpu_tdx * tdx,char * uclass,u32 field,u64 err)64 void tdh_vp_rd_failed(struct vcpu_tdx *tdx, char *uclass, u32 field, u64 err)
65 {
66 	KVM_BUG_ON(1, tdx->vcpu.kvm);
67 	pr_err("TDH_VP_RD[%s.0x%x] failed 0x%llx\n", uclass, field, err);
68 }
69 
tdh_vp_wr_failed(struct vcpu_tdx * tdx,char * uclass,char * op,u32 field,u64 val,u64 err)70 void tdh_vp_wr_failed(struct vcpu_tdx *tdx, char *uclass, char *op, u32 field,
71 		      u64 val, u64 err)
72 {
73 	KVM_BUG_ON(1, tdx->vcpu.kvm);
74 	pr_err("TDH_VP_WR[%s.0x%x]%s0x%llx failed: 0x%llx\n", uclass, field, op, val, err);
75 }
76 
77 #define KVM_SUPPORTED_TDX_TD_ATTRS (TDX_TD_ATTR_SEPT_VE_DISABLE)
78 
to_kvm_tdx(struct kvm * kvm)79 static __always_inline struct kvm_tdx *to_kvm_tdx(struct kvm *kvm)
80 {
81 	return container_of(kvm, struct kvm_tdx, kvm);
82 }
83 
to_tdx(struct kvm_vcpu * vcpu)84 static __always_inline struct vcpu_tdx *to_tdx(struct kvm_vcpu *vcpu)
85 {
86 	return container_of(vcpu, struct vcpu_tdx, vcpu);
87 }
88 
tdx_get_supported_attrs(const struct tdx_sys_info_td_conf * td_conf)89 static u64 tdx_get_supported_attrs(const struct tdx_sys_info_td_conf *td_conf)
90 {
91 	u64 val = KVM_SUPPORTED_TDX_TD_ATTRS;
92 
93 	if ((val & td_conf->attributes_fixed1) != td_conf->attributes_fixed1)
94 		return 0;
95 
96 	val &= td_conf->attributes_fixed0;
97 
98 	return val;
99 }
100 
tdx_get_supported_xfam(const struct tdx_sys_info_td_conf * td_conf)101 static u64 tdx_get_supported_xfam(const struct tdx_sys_info_td_conf *td_conf)
102 {
103 	u64 val = kvm_caps.supported_xcr0 | kvm_caps.supported_xss;
104 
105 	if ((val & td_conf->xfam_fixed1) != td_conf->xfam_fixed1)
106 		return 0;
107 
108 	val &= td_conf->xfam_fixed0;
109 
110 	return val;
111 }
112 
tdx_get_guest_phys_addr_bits(const u32 eax)113 static int tdx_get_guest_phys_addr_bits(const u32 eax)
114 {
115 	return (eax & GENMASK(23, 16)) >> 16;
116 }
117 
tdx_set_guest_phys_addr_bits(const u32 eax,int addr_bits)118 static u32 tdx_set_guest_phys_addr_bits(const u32 eax, int addr_bits)
119 {
120 	return (eax & ~GENMASK(23, 16)) | (addr_bits & 0xff) << 16;
121 }
122 
123 #define TDX_FEATURE_TSX (__feature_bit(X86_FEATURE_HLE) | __feature_bit(X86_FEATURE_RTM))
124 
has_tsx(const struct kvm_cpuid_entry2 * entry)125 static bool has_tsx(const struct kvm_cpuid_entry2 *entry)
126 {
127 	return entry->function == 7 && entry->index == 0 &&
128 	       (entry->ebx & TDX_FEATURE_TSX);
129 }
130 
clear_tsx(struct kvm_cpuid_entry2 * entry)131 static void clear_tsx(struct kvm_cpuid_entry2 *entry)
132 {
133 	entry->ebx &= ~TDX_FEATURE_TSX;
134 }
135 
has_waitpkg(const struct kvm_cpuid_entry2 * entry)136 static bool has_waitpkg(const struct kvm_cpuid_entry2 *entry)
137 {
138 	return entry->function == 7 && entry->index == 0 &&
139 	       (entry->ecx & __feature_bit(X86_FEATURE_WAITPKG));
140 }
141 
clear_waitpkg(struct kvm_cpuid_entry2 * entry)142 static void clear_waitpkg(struct kvm_cpuid_entry2 *entry)
143 {
144 	entry->ecx &= ~__feature_bit(X86_FEATURE_WAITPKG);
145 }
146 
tdx_clear_unsupported_cpuid(struct kvm_cpuid_entry2 * entry)147 static void tdx_clear_unsupported_cpuid(struct kvm_cpuid_entry2 *entry)
148 {
149 	if (has_tsx(entry))
150 		clear_tsx(entry);
151 
152 	if (has_waitpkg(entry))
153 		clear_waitpkg(entry);
154 }
155 
tdx_unsupported_cpuid(const struct kvm_cpuid_entry2 * entry)156 static bool tdx_unsupported_cpuid(const struct kvm_cpuid_entry2 *entry)
157 {
158 	return has_tsx(entry) || has_waitpkg(entry);
159 }
160 
161 #define KVM_TDX_CPUID_NO_SUBLEAF	((__u32)-1)
162 
td_init_cpuid_entry2(struct kvm_cpuid_entry2 * entry,unsigned char idx)163 static void td_init_cpuid_entry2(struct kvm_cpuid_entry2 *entry, unsigned char idx)
164 {
165 	const struct tdx_sys_info_td_conf *td_conf = &tdx_sysinfo->td_conf;
166 
167 	entry->function = (u32)td_conf->cpuid_config_leaves[idx];
168 	entry->index = td_conf->cpuid_config_leaves[idx] >> 32;
169 	entry->eax = (u32)td_conf->cpuid_config_values[idx][0];
170 	entry->ebx = td_conf->cpuid_config_values[idx][0] >> 32;
171 	entry->ecx = (u32)td_conf->cpuid_config_values[idx][1];
172 	entry->edx = td_conf->cpuid_config_values[idx][1] >> 32;
173 
174 	if (entry->index == KVM_TDX_CPUID_NO_SUBLEAF)
175 		entry->index = 0;
176 
177 	/*
178 	 * The TDX module doesn't allow configuring the guest phys addr bits
179 	 * (EAX[23:16]).  However, KVM uses it as an interface to the userspace
180 	 * to configure the GPAW.  Report these bits as configurable.
181 	 */
182 	if (entry->function == 0x80000008)
183 		entry->eax = tdx_set_guest_phys_addr_bits(entry->eax, 0xff);
184 
185 	tdx_clear_unsupported_cpuid(entry);
186 }
187 
188 #define TDVMCALLINFO_SETUP_EVENT_NOTIFY_INTERRUPT	BIT(1)
189 
init_kvm_tdx_caps(const struct tdx_sys_info_td_conf * td_conf,struct kvm_tdx_capabilities * caps)190 static int init_kvm_tdx_caps(const struct tdx_sys_info_td_conf *td_conf,
191 			     struct kvm_tdx_capabilities *caps)
192 {
193 	int i;
194 
195 	caps->supported_attrs = tdx_get_supported_attrs(td_conf);
196 	if (!caps->supported_attrs)
197 		return -EIO;
198 
199 	caps->supported_xfam = tdx_get_supported_xfam(td_conf);
200 	if (!caps->supported_xfam)
201 		return -EIO;
202 
203 	caps->cpuid.nent = td_conf->num_cpuid_config;
204 
205 	caps->user_tdvmcallinfo_1_r11 =
206 		TDVMCALLINFO_SETUP_EVENT_NOTIFY_INTERRUPT;
207 
208 	for (i = 0; i < td_conf->num_cpuid_config; i++)
209 		td_init_cpuid_entry2(&caps->cpuid.entries[i], i);
210 
211 	return 0;
212 }
213 
214 /*
215  * Some SEAMCALLs acquire the TDX module globally, and can fail with
216  * TDX_OPERAND_BUSY.  Use a global mutex to serialize these SEAMCALLs.
217  */
218 static DEFINE_MUTEX(tdx_lock);
219 
tdx_operand_busy(u64 err)220 static bool tdx_operand_busy(u64 err)
221 {
222 	return (err & TDX_SEAMCALL_STATUS_MASK) == TDX_OPERAND_BUSY;
223 }
224 
225 
226 /*
227  * A per-CPU list of TD vCPUs associated with a given CPU.
228  * Protected by interrupt mask. Only manipulated by the CPU owning this per-CPU
229  * list.
230  * - When a vCPU is loaded onto a CPU, it is removed from the per-CPU list of
231  *   the old CPU during the IPI callback running on the old CPU, and then added
232  *   to the per-CPU list of the new CPU.
233  * - When a TD is tearing down, all vCPUs are disassociated from their current
234  *   running CPUs and removed from the per-CPU list during the IPI callback
235  *   running on those CPUs.
236  * - When a CPU is brought down, traverse the per-CPU list to disassociate all
237  *   associated TD vCPUs and remove them from the per-CPU list.
238  */
239 static DEFINE_PER_CPU(struct list_head, associated_tdvcpus);
240 
tdvmcall_exit_type(struct kvm_vcpu * vcpu)241 static __always_inline unsigned long tdvmcall_exit_type(struct kvm_vcpu *vcpu)
242 {
243 	return to_tdx(vcpu)->vp_enter_args.r10;
244 }
245 
tdvmcall_leaf(struct kvm_vcpu * vcpu)246 static __always_inline unsigned long tdvmcall_leaf(struct kvm_vcpu *vcpu)
247 {
248 	return to_tdx(vcpu)->vp_enter_args.r11;
249 }
250 
tdvmcall_set_return_code(struct kvm_vcpu * vcpu,long val)251 static __always_inline void tdvmcall_set_return_code(struct kvm_vcpu *vcpu,
252 						     long val)
253 {
254 	to_tdx(vcpu)->vp_enter_args.r10 = val;
255 }
256 
tdvmcall_set_return_val(struct kvm_vcpu * vcpu,unsigned long val)257 static __always_inline void tdvmcall_set_return_val(struct kvm_vcpu *vcpu,
258 						    unsigned long val)
259 {
260 	to_tdx(vcpu)->vp_enter_args.r11 = val;
261 }
262 
tdx_hkid_free(struct kvm_tdx * kvm_tdx)263 static inline void tdx_hkid_free(struct kvm_tdx *kvm_tdx)
264 {
265 	tdx_guest_keyid_free(kvm_tdx->hkid);
266 	kvm_tdx->hkid = -1;
267 	misc_cg_uncharge(MISC_CG_RES_TDX, kvm_tdx->misc_cg, 1);
268 	put_misc_cg(kvm_tdx->misc_cg);
269 	kvm_tdx->misc_cg = NULL;
270 }
271 
is_hkid_assigned(struct kvm_tdx * kvm_tdx)272 static inline bool is_hkid_assigned(struct kvm_tdx *kvm_tdx)
273 {
274 	return kvm_tdx->hkid > 0;
275 }
276 
tdx_disassociate_vp(struct kvm_vcpu * vcpu)277 static inline void tdx_disassociate_vp(struct kvm_vcpu *vcpu)
278 {
279 	lockdep_assert_irqs_disabled();
280 
281 	list_del(&to_tdx(vcpu)->cpu_list);
282 
283 	/*
284 	 * Ensure tdx->cpu_list is updated before setting vcpu->cpu to -1,
285 	 * otherwise, a different CPU can see vcpu->cpu = -1 and add the vCPU
286 	 * to its list before it's deleted from this CPU's list.
287 	 */
288 	smp_wmb();
289 
290 	vcpu->cpu = -1;
291 }
292 
293 /*
294  * Execute a SEAMCALL related to removing/blocking S-EPT entries, with a single
295  * retry (if necessary) after forcing vCPUs to exit and wait for the operation
296  * to complete.  All flows that remove/block S-EPT entries run with mmu_lock
297  * held for write, i.e. are mutually exclusive with each other, but they aren't
298  * mutually exclusive with running vCPUs, and so can fail with "operand busy"
299  * if a vCPU acquires a relevant lock in the TDX-Module, e.g. when doing TDCALL.
300  *
301  * Note, the retry is guaranteed to succeed, absent KVM and/or TDX-Module bugs.
302  */
303 #define tdh_do_no_vcpus(tdh_func, kvm, args...)					\
304 ({										\
305 	struct kvm_tdx *__kvm_tdx = to_kvm_tdx(kvm);				\
306 	u64 __err;								\
307 										\
308 	lockdep_assert_held_write(&kvm->mmu_lock);				\
309 										\
310 	__err = tdh_func(args);							\
311 	if (unlikely(tdx_operand_busy(__err))) {				\
312 		WRITE_ONCE(__kvm_tdx->wait_for_sept_zap, true);			\
313 		kvm_make_all_cpus_request(kvm, KVM_REQ_OUTSIDE_GUEST_MODE);	\
314 										\
315 		__err = tdh_func(args);						\
316 										\
317 		WRITE_ONCE(__kvm_tdx->wait_for_sept_zap, false);		\
318 	}									\
319 	__err;									\
320 })
321 
322 /* TDH.PHYMEM.PAGE.RECLAIM is allowed only when destroying the TD. */
__tdx_reclaim_page(struct page * page)323 static int __tdx_reclaim_page(struct page *page)
324 {
325 	u64 err, rcx, rdx, r8;
326 
327 	err = tdh_phymem_page_reclaim(page, &rcx, &rdx, &r8);
328 
329 	/*
330 	 * No need to check for TDX_OPERAND_BUSY; all TD pages are freed
331 	 * before the HKID is released and control pages have also been
332 	 * released at this point, so there is no possibility of contention.
333 	 */
334 	if (TDX_BUG_ON_3(err, TDH_PHYMEM_PAGE_RECLAIM, rcx, rdx, r8, NULL))
335 		return -EIO;
336 
337 	return 0;
338 }
339 
tdx_reclaim_page(struct page * page)340 static int tdx_reclaim_page(struct page *page)
341 {
342 	int r;
343 
344 	r = __tdx_reclaim_page(page);
345 	if (!r)
346 		tdx_quirk_reset_paddr(page_to_phys(page), PAGE_SIZE);
347 	return r;
348 }
349 
350 
351 /*
352  * Reclaim the TD control page(s) which are crypto-protected by TDX guest's
353  * private KeyID.  Assume the cache associated with the TDX private KeyID has
354  * been flushed.
355  */
tdx_reclaim_control_page(struct page * ctrl_page)356 static void tdx_reclaim_control_page(struct page *ctrl_page)
357 {
358 	/*
359 	 * Leak the page if the kernel failed to reclaim the page.
360 	 * The kernel cannot use it safely anymore.
361 	 */
362 	if (tdx_reclaim_page(ctrl_page))
363 		return;
364 
365 	tdx_free_control_page(ctrl_page);
366 }
367 
368 struct tdx_flush_vp_arg {
369 	struct kvm_vcpu *vcpu;
370 	u64 err;
371 };
372 
tdx_flush_vp(void * _arg)373 static void tdx_flush_vp(void *_arg)
374 {
375 	struct tdx_flush_vp_arg *arg = _arg;
376 	struct kvm_vcpu *vcpu = arg->vcpu;
377 	u64 err;
378 
379 	arg->err = 0;
380 	lockdep_assert_irqs_disabled();
381 
382 	/* Task migration can race with CPU offlining. */
383 	if (unlikely(vcpu->cpu != raw_smp_processor_id()))
384 		return;
385 
386 	/*
387 	 * No need to do TDH_VP_FLUSH if the vCPU hasn't been initialized.  The
388 	 * list tracking still needs to be updated so that it's correct if/when
389 	 * the vCPU does get initialized.
390 	 */
391 	if (to_tdx(vcpu)->state != VCPU_TD_STATE_UNINITIALIZED) {
392 		/*
393 		 * No need to retry.  TDX Resources needed for TDH.VP.FLUSH are:
394 		 * TDVPR as exclusive, TDR as shared, and TDCS as shared.  This
395 		 * vp flush function is called when destructing vCPU/TD or vCPU
396 		 * migration.  No other thread uses TDVPR in those cases.
397 		 */
398 		err = tdh_vp_flush(&to_tdx(vcpu)->vp);
399 		if (unlikely(err && err != TDX_VCPU_NOT_ASSOCIATED)) {
400 			/*
401 			 * This function is called in IPI context. Do not use
402 			 * printk to avoid console semaphore.
403 			 * The caller prints out the error message, instead.
404 			 */
405 			if (err)
406 				arg->err = err;
407 		}
408 	}
409 
410 	tdx_disassociate_vp(vcpu);
411 }
412 
tdx_flush_vp_on_cpu(struct kvm_vcpu * vcpu)413 static void tdx_flush_vp_on_cpu(struct kvm_vcpu *vcpu)
414 {
415 	struct tdx_flush_vp_arg arg = {
416 		.vcpu = vcpu,
417 	};
418 	int cpu = vcpu->cpu;
419 
420 	if (unlikely(cpu == -1))
421 		return;
422 
423 	smp_call_function_single(cpu, tdx_flush_vp, &arg, 1);
424 
425 	TDX_BUG_ON(arg.err, TDH_VP_FLUSH, vcpu->kvm);
426 }
427 
tdx_disable_virtualization_cpu(void)428 void tdx_disable_virtualization_cpu(void)
429 {
430 	int cpu = raw_smp_processor_id();
431 	struct list_head *tdvcpus = &per_cpu(associated_tdvcpus, cpu);
432 	struct tdx_flush_vp_arg arg;
433 	struct vcpu_tdx *tdx, *tmp;
434 	unsigned long flags;
435 
436 	local_irq_save(flags);
437 	/* Safe variant needed as tdx_disassociate_vp() deletes the entry. */
438 	list_for_each_entry_safe(tdx, tmp, tdvcpus, cpu_list) {
439 		arg.vcpu = &tdx->vcpu;
440 		tdx_flush_vp(&arg);
441 	}
442 	local_irq_restore(flags);
443 }
444 
445 #define TDX_SEAMCALL_RETRIES 10000
446 
smp_func_do_phymem_cache_wb(void * unused)447 static void smp_func_do_phymem_cache_wb(void *unused)
448 {
449 	u64 err = 0;
450 	bool resume;
451 	int i;
452 
453 	/*
454 	 * TDH.PHYMEM.CACHE.WB flushes caches associated with any TDX private
455 	 * KeyID on the package or core.  The TDX module may not finish the
456 	 * cache flush but return TDX_INTERRUPTED_RESUMEABLE instead.  The
457 	 * kernel should retry it until it returns success w/o rescheduling.
458 	 */
459 	for (i = TDX_SEAMCALL_RETRIES; i > 0; i--) {
460 		resume = !!err;
461 		err = tdh_phymem_cache_wb(resume);
462 		switch (err) {
463 		case TDX_INTERRUPTED_RESUMABLE:
464 			continue;
465 		case TDX_NO_HKID_READY_TO_WBCACHE:
466 			err = TDX_SUCCESS; /* Already done by other thread */
467 			fallthrough;
468 		default:
469 			goto out;
470 		}
471 	}
472 
473 out:
474 	TDX_BUG_ON(err, TDH_PHYMEM_CACHE_WB, NULL);
475 }
476 
tdx_mmu_release_hkid(struct kvm * kvm)477 void tdx_mmu_release_hkid(struct kvm *kvm)
478 {
479 	bool packages_allocated, targets_allocated;
480 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
481 	cpumask_var_t packages, targets;
482 	struct kvm_vcpu *vcpu;
483 	unsigned long j;
484 	int i;
485 	u64 err;
486 
487 	if (!is_hkid_assigned(kvm_tdx))
488 		return;
489 
490 	packages_allocated = zalloc_cpumask_var(&packages, GFP_KERNEL);
491 	targets_allocated = zalloc_cpumask_var(&targets, GFP_KERNEL);
492 	cpus_read_lock();
493 
494 	kvm_for_each_vcpu(j, vcpu, kvm)
495 		tdx_flush_vp_on_cpu(vcpu);
496 
497 	/*
498 	 * TDH.PHYMEM.CACHE.WB tries to acquire the TDX module global lock
499 	 * and can fail with TDX_OPERAND_BUSY when it fails to get the lock.
500 	 * Multiple TDX guests can be destroyed simultaneously. Take the
501 	 * mutex to prevent it from getting error.
502 	 */
503 	mutex_lock(&tdx_lock);
504 
505 	/*
506 	 * Releasing HKID is in vm_destroy().
507 	 * After the above flushing vps, there should be no more vCPU
508 	 * associations, as all vCPU fds have been released at this stage.
509 	 */
510 	err = tdh_mng_vpflushdone(&kvm_tdx->td);
511 	if (err == TDX_FLUSHVP_NOT_DONE)
512 		goto out;
513 	if (TDX_BUG_ON(err, TDH_MNG_VPFLUSHDONE, kvm)) {
514 		pr_err("tdh_mng_vpflushdone() failed. HKID %d is leaked.\n",
515 		       kvm_tdx->hkid);
516 		goto out;
517 	}
518 
519 	for_each_online_cpu(i) {
520 		if (packages_allocated &&
521 		    cpumask_test_and_set_cpu(topology_physical_package_id(i),
522 					     packages))
523 			continue;
524 		if (targets_allocated)
525 			cpumask_set_cpu(i, targets);
526 	}
527 	if (targets_allocated)
528 		on_each_cpu_mask(targets, smp_func_do_phymem_cache_wb, NULL, true);
529 	else
530 		on_each_cpu(smp_func_do_phymem_cache_wb, NULL, true);
531 	/*
532 	 * In the case of error in smp_func_do_phymem_cache_wb(), the following
533 	 * tdh_mng_key_freeid() will fail.
534 	 */
535 	err = tdh_mng_key_freeid(&kvm_tdx->td);
536 	if (TDX_BUG_ON(err, TDH_MNG_KEY_FREEID, kvm)) {
537 		pr_err("tdh_mng_key_freeid() failed. HKID %d is leaked.\n",
538 		       kvm_tdx->hkid);
539 	} else {
540 		tdx_hkid_free(kvm_tdx);
541 	}
542 
543 out:
544 	mutex_unlock(&tdx_lock);
545 	cpus_read_unlock();
546 	free_cpumask_var(targets);
547 	free_cpumask_var(packages);
548 }
549 
tdx_reclaim_td_control_pages(struct kvm * kvm)550 static void tdx_reclaim_td_control_pages(struct kvm *kvm)
551 {
552 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
553 	u64 err;
554 	int i;
555 
556 	/*
557 	 * tdx_mmu_release_hkid() failed to reclaim HKID.  Something went wrong
558 	 * heavily with TDX module.  Give up freeing TD pages.  As the function
559 	 * already warned, don't warn it again.
560 	 */
561 	if (is_hkid_assigned(kvm_tdx))
562 		return;
563 
564 	if (kvm_tdx->td.tdcs_pages) {
565 		for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++) {
566 			if (!kvm_tdx->td.tdcs_pages[i])
567 				continue;
568 
569 			tdx_reclaim_control_page(kvm_tdx->td.tdcs_pages[i]);
570 		}
571 		kfree(kvm_tdx->td.tdcs_pages);
572 		kvm_tdx->td.tdcs_pages = NULL;
573 	}
574 
575 	if (!kvm_tdx->td.tdr_page)
576 		return;
577 
578 	if (__tdx_reclaim_page(kvm_tdx->td.tdr_page))
579 		return;
580 
581 	/*
582 	 * Use a SEAMCALL to ask the TDX module to flush the cache based on the
583 	 * KeyID. TDX module may access TDR while operating on TD (Especially
584 	 * when it is reclaiming TDCS).
585 	 */
586 	err = tdh_phymem_page_wbinvd_tdr(&kvm_tdx->td);
587 	if (TDX_BUG_ON(err, TDH_PHYMEM_PAGE_WBINVD, kvm))
588 		return;
589 
590 	tdx_quirk_reset_paddr(page_to_phys(kvm_tdx->td.tdr_page), PAGE_SIZE);
591 
592 	tdx_free_control_page(kvm_tdx->td.tdr_page);
593 	kvm_tdx->td.tdr_page = NULL;
594 }
595 
tdx_vm_destroy(struct kvm * kvm)596 void tdx_vm_destroy(struct kvm *kvm)
597 {
598 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
599 
600 	tdx_reclaim_td_control_pages(kvm);
601 
602 	kvm_tdx->state = TD_STATE_UNINITIALIZED;
603 }
604 
tdx_do_tdh_mng_key_config(void * param)605 static int tdx_do_tdh_mng_key_config(void *param)
606 {
607 	struct kvm_tdx *kvm_tdx = param;
608 	u64 err;
609 
610 	/* TDX_RND_NO_ENTROPY related retries are handled by sc_retry() */
611 	err = tdh_mng_key_config(&kvm_tdx->td);
612 	if (TDX_BUG_ON(err, TDH_MNG_KEY_CONFIG, &kvm_tdx->kvm))
613 		return -EIO;
614 
615 	return 0;
616 }
617 
tdx_vm_init(struct kvm * kvm)618 int tdx_vm_init(struct kvm *kvm)
619 {
620 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
621 
622 	kvm->arch.has_protected_state = true;
623 	/*
624 	 * TDX Module doesn't allow the hypervisor to modify the EOI-bitmap,
625 	 * i.e. all EOIs are accelerated and never trigger exits.
626 	 */
627 	kvm->arch.has_protected_eoi = true;
628 	kvm->arch.has_private_mem = true;
629 	kvm->arch.disabled_quirks |= KVM_X86_QUIRK_IGNORE_GUEST_PAT;
630 
631 	/*
632 	 * PMU support is provided by the TDX-Module (if enabled for the VM).
633 	 * From KVM's perspective, the VM doesn't have a virtual PMU.
634 	 */
635 	kvm->arch.has_protected_pmu = true;
636 
637 	/*
638 	 * Because guest TD is protected, VMM can't parse the instruction in TD.
639 	 * Instead, guest uses MMIO hypercall.  For unmodified device driver,
640 	 * #VE needs to be injected for MMIO and #VE handler in TD converts MMIO
641 	 * instruction into MMIO hypercall.
642 	 *
643 	 * SPTE value for MMIO needs to be setup so that #VE is injected into
644 	 * TD instead of triggering EPT MISCONFIG.
645 	 * - RWX=0 so that EPT violation is triggered.
646 	 * - suppress #VE bit is cleared to inject #VE.
647 	 */
648 	kvm_mmu_set_mmio_spte_value(kvm, 0);
649 
650 	/*
651 	 * TDX has its own limit of maximum vCPUs it can support for all
652 	 * TDX guests in addition to KVM_MAX_VCPUS.  TDX module reports
653 	 * such limit via the MAX_VCPU_PER_TD global metadata.  In
654 	 * practice, it reflects the number of logical CPUs that ALL
655 	 * platforms that the TDX module supports can possibly have.
656 	 *
657 	 * Limit TDX guest's maximum vCPUs to the number of logical CPUs
658 	 * the platform has.  Simply forwarding the MAX_VCPU_PER_TD to
659 	 * userspace would result in an unpredictable ABI.
660 	 */
661 	kvm->max_vcpus = min_t(int, kvm->max_vcpus, num_present_cpus());
662 
663 	kvm_tdx->state = TD_STATE_UNINITIALIZED;
664 
665 	return 0;
666 }
667 
tdx_vcpu_create(struct kvm_vcpu * vcpu)668 int tdx_vcpu_create(struct kvm_vcpu *vcpu)
669 {
670 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
671 	struct vcpu_tdx *tdx = to_tdx(vcpu);
672 
673 	if (kvm_tdx->state != TD_STATE_INITIALIZED)
674 		return -EIO;
675 
676 	/*
677 	 * TDX module mandates APICv, which requires an in-kernel local APIC.
678 	 * Disallow an in-kernel I/O APIC, because level-triggered interrupts
679 	 * and thus the I/O APIC as a whole can't be faithfully emulated in KVM.
680 	 */
681 	if (!irqchip_split(vcpu->kvm))
682 		return -EINVAL;
683 
684 	tdx_init_pamt_cache(&tdx->pamt_cache);
685 
686 	fpstate_set_confidential(&vcpu->arch.guest_fpu);
687 	vcpu->arch.apic->guest_apic_protected = true;
688 	INIT_LIST_HEAD(&tdx->vt.pi_wakeup_list);
689 
690 	vcpu->arch.efer = EFER_SCE | EFER_LME | EFER_LMA | EFER_NX;
691 
692 	vcpu->arch.switch_db_regs = KVM_DEBUGREG_AUTO_SWITCH;
693 	vcpu->arch.cr0_guest_owned_bits = -1ul;
694 	vcpu->arch.cr4_guest_owned_bits = -1ul;
695 
696 	/* KVM can't change TSC offset/multiplier as TDX module manages them. */
697 	vcpu->arch.guest_tsc_protected = true;
698 	vcpu->arch.tsc_offset = kvm_tdx->tsc_offset;
699 	vcpu->arch.l1_tsc_offset = vcpu->arch.tsc_offset;
700 	vcpu->arch.tsc_scaling_ratio = kvm_tdx->tsc_multiplier;
701 	vcpu->arch.l1_tsc_scaling_ratio = kvm_tdx->tsc_multiplier;
702 
703 	vcpu->arch.guest_state_protected =
704 		!(to_kvm_tdx(vcpu->kvm)->attributes & TDX_TD_ATTR_DEBUG);
705 
706 	if ((kvm_tdx->xfam & XFEATURE_MASK_XTILE) == XFEATURE_MASK_XTILE)
707 		vcpu->arch.xfd_no_write_intercept = true;
708 
709 	tdx->vt.pi_desc.nv = POSTED_INTR_VECTOR;
710 	__pi_set_sn(&tdx->vt.pi_desc);
711 
712 	tdx->state = VCPU_TD_STATE_UNINITIALIZED;
713 
714 	return 0;
715 }
716 
tdx_vcpu_load(struct kvm_vcpu * vcpu,int cpu)717 void tdx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
718 {
719 	struct vcpu_tdx *tdx = to_tdx(vcpu);
720 
721 	vmx_vcpu_pi_load(vcpu, cpu);
722 	if (vcpu->cpu == cpu || !is_hkid_assigned(to_kvm_tdx(vcpu->kvm)))
723 		return;
724 
725 	tdx_flush_vp_on_cpu(vcpu);
726 
727 	KVM_BUG_ON(cpu != raw_smp_processor_id(), vcpu->kvm);
728 	local_irq_disable();
729 	/*
730 	 * Pairs with the smp_wmb() in tdx_disassociate_vp() to ensure
731 	 * vcpu->cpu is read before tdx->cpu_list.
732 	 */
733 	smp_rmb();
734 
735 	list_add(&tdx->cpu_list, &per_cpu(associated_tdvcpus, cpu));
736 	local_irq_enable();
737 }
738 
tdx_interrupt_allowed(struct kvm_vcpu * vcpu)739 bool tdx_interrupt_allowed(struct kvm_vcpu *vcpu)
740 {
741 	/*
742 	 * KVM can't get the interrupt status of TDX guest and it assumes
743 	 * interrupt is always allowed unless TDX guest calls TDVMCALL with HLT,
744 	 * which passes the interrupt blocked flag.
745 	 */
746 	return vmx_get_exit_reason(vcpu).basic != EXIT_REASON_HLT ||
747 	       !to_tdx(vcpu)->vp_enter_args.r12;
748 }
749 
tdx_protected_apic_has_interrupt(struct kvm_vcpu * vcpu)750 static bool tdx_protected_apic_has_interrupt(struct kvm_vcpu *vcpu)
751 {
752 	u64 vcpu_state_details;
753 
754 	if (pi_has_pending_interrupt(vcpu))
755 		return true;
756 
757 	/*
758 	 * Only check RVI pending for HALTED case with IRQ enabled.
759 	 * For non-HLT cases, KVM doesn't care about STI/SS shadows.  And if the
760 	 * interrupt was pending before TD exit, then it _must_ be blocked,
761 	 * otherwise the interrupt would have been serviced at the instruction
762 	 * boundary.
763 	 */
764 	if (vmx_get_exit_reason(vcpu).basic != EXIT_REASON_HLT ||
765 	    to_tdx(vcpu)->vp_enter_args.r12)
766 		return false;
767 
768 	vcpu_state_details =
769 		td_state_non_arch_read64(to_tdx(vcpu), TD_VCPU_STATE_DETAILS_NON_ARCH);
770 
771 	return tdx_vcpu_state_details_intr_pending(vcpu_state_details);
772 }
773 
774 struct tdx_uret_msr {
775 	u32 msr;
776 	unsigned int slot;
777 	u64 defval;
778 };
779 
780 static struct tdx_uret_msr tdx_uret_msrs[] = {
781 	{.msr = MSR_SYSCALL_MASK, .defval = 0x20200 },
782 	{.msr = MSR_STAR,},
783 	{.msr = MSR_LSTAR,},
784 	{.msr = MSR_TSC_AUX,},
785 };
786 
tdx_prepare_switch_to_guest(struct kvm_vcpu * vcpu)787 void tdx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
788 {
789 	struct vcpu_vt *vt = to_vt(vcpu);
790 	int i;
791 
792 	if (vt->guest_state_loaded)
793 		return;
794 
795 	if (likely(is_64bit_mm(current->mm)))
796 		vt->msr_host_kernel_gs_base = current->thread.gsbase;
797 	else
798 		vt->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
799 
800 	vt->guest_state_loaded = true;
801 
802 	/*
803 	 * Explicitly set user-return MSRs that are clobbered by the TDX-Module
804 	 * if VP.ENTER succeeds, i.e. on TD-Exit, with the values that would be
805 	 * written by the TDX-Module.  Don't rely on the TDX-Module to actually
806 	 * clobber the MSRs, as the contract is poorly defined and not upheld.
807 	 * E.g. the TDX-Module will synthesize an EPT Violation without doing
808 	 * VM-Enter if it suspects a zero-step attack, and never "restore" VMM
809 	 * state.
810 	 */
811 	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++)
812 		kvm_set_user_return_msr(tdx_uret_msrs[i].slot,
813 					tdx_uret_msrs[i].defval, -1ull);
814 }
815 
tdx_prepare_switch_to_host(struct kvm_vcpu * vcpu)816 static void tdx_prepare_switch_to_host(struct kvm_vcpu *vcpu)
817 {
818 	struct vcpu_vt *vt = to_vt(vcpu);
819 
820 	if (!vt->guest_state_loaded)
821 		return;
822 
823 	++vcpu->stat.host_state_reload;
824 	wrmsrq(MSR_KERNEL_GS_BASE, vt->msr_host_kernel_gs_base);
825 
826 	vt->guest_state_loaded = false;
827 }
828 
tdx_vcpu_put(struct kvm_vcpu * vcpu)829 void tdx_vcpu_put(struct kvm_vcpu *vcpu)
830 {
831 	vmx_vcpu_pi_put(vcpu);
832 	tdx_prepare_switch_to_host(vcpu);
833 }
834 
835 /*
836  * Life cycles for a TD and a vCPU:
837  * 1. KVM_CREATE_VM ioctl.
838  *    TD state is TD_STATE_UNINITIALIZED.
839  *    hkid is not assigned at this stage.
840  * 2. KVM_TDX_INIT_VM ioctl.
841  *    TD transitions to TD_STATE_INITIALIZED.
842  *    hkid is assigned after this stage.
843  * 3. KVM_CREATE_VCPU ioctl. (only when TD is TD_STATE_INITIALIZED).
844  *    3.1 tdx_vcpu_create() transitions vCPU state to VCPU_TD_STATE_UNINITIALIZED.
845  *    3.2 vcpu_load() and vcpu_put() in kvm_arch_vcpu_create().
846  *    3.3 (conditional) if any error encountered after kvm_arch_vcpu_create()
847  *        kvm_arch_vcpu_destroy() --> tdx_vcpu_free().
848  * 4. KVM_TDX_INIT_VCPU ioctl.
849  *    tdx_vcpu_init() transitions vCPU state to VCPU_TD_STATE_INITIALIZED.
850  *    vCPU control structures are allocated at this stage.
851  * 5. kvm_destroy_vm().
852  *    5.1 tdx_mmu_release_hkid(): (1) tdh_vp_flush(), disassociates all vCPUs.
853  *                                (2) puts hkid to !assigned state.
854  *    5.2 kvm_destroy_vcpus() --> tdx_vcpu_free():
855  *        transitions vCPU to VCPU_TD_STATE_UNINITIALIZED state.
856  *    5.3 tdx_vm_destroy()
857  *        transitions TD to TD_STATE_UNINITIALIZED state.
858  *
859  * tdx_vcpu_free() can be invoked only at 3.3 or 5.2.
860  * - If at 3.3, hkid is still assigned, but the vCPU must be in
861  *   VCPU_TD_STATE_UNINITIALIZED state.
862  * - if at 5.2, hkid must be !assigned and all vCPUs must be in
863  *   VCPU_TD_STATE_INITIALIZED state and have been dissociated.
864  */
tdx_vcpu_free(struct kvm_vcpu * vcpu)865 void tdx_vcpu_free(struct kvm_vcpu *vcpu)
866 {
867 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
868 	struct vcpu_tdx *tdx = to_tdx(vcpu);
869 	int i;
870 
871 	tdx_free_pamt_cache(&tdx->pamt_cache);
872 
873 	if (vcpu->cpu != -1) {
874 		KVM_BUG_ON(tdx->state == VCPU_TD_STATE_INITIALIZED, vcpu->kvm);
875 		tdx_flush_vp_on_cpu(vcpu);
876 		return;
877 	}
878 
879 	/*
880 	 * It is not possible to reclaim pages while hkid is assigned. It might
881 	 * be assigned if the TD VM is being destroyed but freeing hkid failed,
882 	 * in which case the pages are leaked.
883 	 */
884 	if (is_hkid_assigned(kvm_tdx))
885 		return;
886 
887 	if (tdx->vp.tdcx_pages) {
888 		for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
889 			if (tdx->vp.tdcx_pages[i])
890 				tdx_reclaim_control_page(tdx->vp.tdcx_pages[i]);
891 		}
892 		kfree(tdx->vp.tdcx_pages);
893 		tdx->vp.tdcx_pages = NULL;
894 	}
895 	if (tdx->vp.tdvpr_page) {
896 		tdx_reclaim_control_page(tdx->vp.tdvpr_page);
897 		tdx->vp.tdvpr_page = NULL;
898 		tdx->vp.tdvpr_pa = 0;
899 	}
900 
901 	tdx->state = VCPU_TD_STATE_UNINITIALIZED;
902 }
903 
tdx_vcpu_needs_initialization(struct kvm_vcpu * vcpu)904 bool tdx_vcpu_needs_initialization(struct kvm_vcpu *vcpu)
905 {
906 	return to_tdx(vcpu)->state != VCPU_TD_STATE_INITIALIZED ||
907 	       to_kvm_tdx(vcpu->kvm)->state != TD_STATE_RUNNABLE;
908 }
909 
tdcall_to_vmx_exit_reason(struct kvm_vcpu * vcpu)910 static __always_inline u32 tdcall_to_vmx_exit_reason(struct kvm_vcpu *vcpu)
911 {
912 	switch (tdvmcall_leaf(vcpu)) {
913 	case EXIT_REASON_CPUID:
914 	case EXIT_REASON_HLT:
915 	case EXIT_REASON_IO_INSTRUCTION:
916 	case EXIT_REASON_MSR_READ:
917 	case EXIT_REASON_MSR_WRITE:
918 		return tdvmcall_leaf(vcpu);
919 	case EXIT_REASON_EPT_VIOLATION:
920 		return EXIT_REASON_EPT_MISCONFIG;
921 	default:
922 		break;
923 	}
924 
925 	return EXIT_REASON_TDCALL;
926 }
927 
tdx_to_vmx_exit_reason(struct kvm_vcpu * vcpu)928 static __always_inline u32 tdx_to_vmx_exit_reason(struct kvm_vcpu *vcpu)
929 {
930 	struct vcpu_tdx *tdx = to_tdx(vcpu);
931 	u32 exit_reason;
932 
933 	switch (tdx->vp_enter_ret & TDX_SEAMCALL_STATUS_MASK) {
934 	case TDX_SUCCESS:
935 	case TDX_NON_RECOVERABLE_VCPU:
936 	case TDX_NON_RECOVERABLE_TD:
937 	case TDX_NON_RECOVERABLE_TD_NON_ACCESSIBLE:
938 	case TDX_NON_RECOVERABLE_TD_WRONG_APIC_MODE:
939 		break;
940 	default:
941 		return -1u;
942 	}
943 
944 	exit_reason = tdx->vp_enter_ret;
945 
946 	switch (exit_reason) {
947 	case EXIT_REASON_TDCALL:
948 		if (tdvmcall_exit_type(vcpu))
949 			return EXIT_REASON_VMCALL;
950 
951 		return tdcall_to_vmx_exit_reason(vcpu);
952 	case EXIT_REASON_EPT_MISCONFIG:
953 		/*
954 		 * Defer KVM_BUG_ON() until tdx_handle_exit() because this is in
955 		 * non-instrumentable code with interrupts disabled.
956 		 */
957 		return -1u;
958 	default:
959 		break;
960 	}
961 
962 	return exit_reason;
963 }
964 
tdx_vcpu_enter_exit(struct kvm_vcpu * vcpu)965 static noinstr void tdx_vcpu_enter_exit(struct kvm_vcpu *vcpu)
966 {
967 	struct vcpu_tdx *tdx = to_tdx(vcpu);
968 	struct vcpu_vt *vt = to_vt(vcpu);
969 
970 	guest_state_enter_irqoff();
971 
972 	tdx->vp_enter_ret = tdh_vp_enter(&tdx->vp, &tdx->vp_enter_args);
973 
974 	vt->exit_reason.full = tdx_to_vmx_exit_reason(vcpu);
975 
976 	vt->exit_qualification = tdx->vp_enter_args.rcx;
977 	tdx->ext_exit_qualification = tdx->vp_enter_args.rdx;
978 	tdx->exit_gpa = tdx->vp_enter_args.r8;
979 	vt->exit_intr_info = tdx->vp_enter_args.r9;
980 
981 	vmx_handle_nmi(vcpu);
982 
983 	guest_state_exit_irqoff();
984 }
985 
tdx_failed_vmentry(struct kvm_vcpu * vcpu)986 static bool tdx_failed_vmentry(struct kvm_vcpu *vcpu)
987 {
988 	return vmx_get_exit_reason(vcpu).failed_vmentry &&
989 	       vmx_get_exit_reason(vcpu).full != -1u;
990 }
991 
tdx_exit_handlers_fastpath(struct kvm_vcpu * vcpu)992 static fastpath_t tdx_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
993 {
994 	u64 vp_enter_ret = to_tdx(vcpu)->vp_enter_ret;
995 
996 	/*
997 	 * TDX_OPERAND_BUSY could be returned for SEPT due to 0-step mitigation
998 	 * or for TD EPOCH due to contention with TDH.MEM.TRACK on TDH.VP.ENTER.
999 	 *
1000 	 * When KVM requests KVM_REQ_OUTSIDE_GUEST_MODE, which has both
1001 	 * KVM_REQUEST_WAIT and KVM_REQUEST_NO_ACTION set, it requires target
1002 	 * vCPUs leaving fastpath so that interrupt can be enabled to ensure the
1003 	 * IPIs can be delivered. Return EXIT_FASTPATH_EXIT_HANDLED instead of
1004 	 * EXIT_FASTPATH_REENTER_GUEST to exit fastpath, otherwise, the
1005 	 * requester may be blocked endlessly.
1006 	 */
1007 	if (unlikely(tdx_operand_busy(vp_enter_ret)))
1008 		return EXIT_FASTPATH_EXIT_HANDLED;
1009 
1010 	return EXIT_FASTPATH_NONE;
1011 }
1012 
1013 #define TDX_REGS_AVAIL_SET	(BIT(VCPU_REG_EXIT_INFO_1) | \
1014 				 BIT(VCPU_REG_EXIT_INFO_2) | \
1015 				 BIT(VCPU_REGS_RAX) | \
1016 				 BIT(VCPU_REGS_RBX) | \
1017 				 BIT(VCPU_REGS_RCX) | \
1018 				 BIT(VCPU_REGS_RDX) | \
1019 				 BIT(VCPU_REGS_RBP) | \
1020 				 BIT(VCPU_REGS_RSI) | \
1021 				 BIT(VCPU_REGS_RDI) | \
1022 				 BIT(VCPU_REGS_R8) | \
1023 				 BIT(VCPU_REGS_R9) | \
1024 				 BIT(VCPU_REGS_R10) | \
1025 				 BIT(VCPU_REGS_R11) | \
1026 				 BIT(VCPU_REGS_R12) | \
1027 				 BIT(VCPU_REGS_R13) | \
1028 				 BIT(VCPU_REGS_R14) | \
1029 				 BIT(VCPU_REGS_R15))
1030 
tdx_load_host_xsave_state(struct kvm_vcpu * vcpu)1031 static void tdx_load_host_xsave_state(struct kvm_vcpu *vcpu)
1032 {
1033 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
1034 
1035 	/*
1036 	 * All TDX hosts support PKRU; but even if they didn't,
1037 	 * vcpu->arch.host_pkru would be 0 and the wrpkru would be
1038 	 * skipped.
1039 	 */
1040 	if (vcpu->arch.host_pkru != 0)
1041 		wrpkru(vcpu->arch.host_pkru);
1042 
1043 	if (kvm_host.xcr0 != (kvm_tdx->xfam & kvm_caps.supported_xcr0))
1044 		xsetbv(XCR_XFEATURE_ENABLED_MASK, kvm_host.xcr0);
1045 
1046 	/*
1047 	 * Likewise, even if a TDX hosts didn't support XSS both arms of
1048 	 * the comparison would be 0 and the wrmsrq would be skipped.
1049 	 */
1050 	if (kvm_host.xss != (kvm_tdx->xfam & kvm_caps.supported_xss))
1051 		wrmsrq(MSR_IA32_XSS, kvm_host.xss);
1052 }
1053 
1054 #define TDX_DEBUGCTL_PRESERVED (DEBUGCTLMSR_BTF | \
1055 				DEBUGCTLMSR_FREEZE_PERFMON_ON_PMI | \
1056 				DEBUGCTLMSR_FREEZE_IN_SMM)
1057 
tdx_vcpu_run(struct kvm_vcpu * vcpu,u64 run_flags)1058 fastpath_t tdx_vcpu_run(struct kvm_vcpu *vcpu, u64 run_flags)
1059 {
1060 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1061 	struct vcpu_vt *vt = to_vt(vcpu);
1062 
1063 	/*
1064 	 * WARN if KVM wants to force an immediate exit, as the TDX module does
1065 	 * not guarantee entry into the guest, i.e. it's possible for KVM to
1066 	 * _think_ it completed entry to the guest and forced an immediate exit
1067 	 * without actually having done so.  Luckily, KVM never needs to force
1068 	 * an immediate exit for TDX (KVM can't do direct event injection, so
1069 	 * just WARN and continue on.
1070 	 */
1071 	WARN_ON_ONCE(run_flags);
1072 
1073 	/*
1074 	 * Wait until retry of SEPT-zap-related SEAMCALL completes before
1075 	 * allowing vCPU entry to avoid contention with tdh_vp_enter() and
1076 	 * TDCALLs.
1077 	 */
1078 	if (unlikely(READ_ONCE(to_kvm_tdx(vcpu->kvm)->wait_for_sept_zap)))
1079 		return EXIT_FASTPATH_EXIT_HANDLED;
1080 
1081 	trace_kvm_entry(vcpu, run_flags & KVM_RUN_FORCE_IMMEDIATE_EXIT);
1082 
1083 	if (pi_test_on(&vt->pi_desc)) {
1084 		apic->send_IPI_self(POSTED_INTR_VECTOR);
1085 
1086 		if (pi_test_pir(kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVTT) &
1087 			       APIC_VECTOR_MASK, &vt->pi_desc))
1088 			kvm_wait_lapic_expire(vcpu);
1089 	}
1090 
1091 	tdx_vcpu_enter_exit(vcpu);
1092 
1093 	if (vcpu->arch.host_debugctl & ~TDX_DEBUGCTL_PRESERVED)
1094 		update_debugctlmsr(vcpu->arch.host_debugctl);
1095 
1096 	tdx_load_host_xsave_state(vcpu);
1097 
1098 	kvm_clear_available_registers(vcpu, ~TDX_REGS_AVAIL_SET);
1099 
1100 	if (unlikely(tdx->vp_enter_ret == EXIT_REASON_EPT_MISCONFIG))
1101 		return EXIT_FASTPATH_NONE;
1102 
1103 	if (unlikely((tdx->vp_enter_ret & TDX_SW_ERROR) == TDX_SW_ERROR))
1104 		return EXIT_FASTPATH_NONE;
1105 
1106 	trace_kvm_exit(vcpu, KVM_ISA_VMX);
1107 
1108 	if (unlikely(tdx_failed_vmentry(vcpu)))
1109 		return EXIT_FASTPATH_NONE;
1110 
1111 	return tdx_exit_handlers_fastpath(vcpu);
1112 }
1113 
tdx_inject_nmi(struct kvm_vcpu * vcpu)1114 void tdx_inject_nmi(struct kvm_vcpu *vcpu)
1115 {
1116 	++vcpu->stat.nmi_injections;
1117 	td_management_write8(to_tdx(vcpu), TD_VCPU_PEND_NMI, 1);
1118 	/*
1119 	 * From KVM's perspective, NMI injection is completed right after
1120 	 * writing to PEND_NMI.  KVM doesn't care whether an NMI is injected by
1121 	 * the TDX module or not.
1122 	 */
1123 	vcpu->arch.nmi_injected = false;
1124 	/*
1125 	 * TDX doesn't support KVM to request NMI window exit.  If there is
1126 	 * still a pending vNMI, KVM is not able to inject it along with the
1127 	 * one pending in TDX module in a back-to-back way.  Since the previous
1128 	 * vNMI is still pending in TDX module, i.e. it has not been delivered
1129 	 * to TDX guest yet, it's OK to collapse the pending vNMI into the
1130 	 * previous one.  The guest is expected to handle all the NMI sources
1131 	 * when handling the first vNMI.
1132 	 */
1133 	vcpu->arch.nmi_pending = 0;
1134 }
1135 
tdx_handle_exception_nmi(struct kvm_vcpu * vcpu)1136 static int tdx_handle_exception_nmi(struct kvm_vcpu *vcpu)
1137 {
1138 	u32 intr_info = vmx_get_intr_info(vcpu);
1139 
1140 	/*
1141 	 * Machine checks are handled by handle_exception_irqoff(), or by
1142 	 * tdx_handle_exit() with TDX_NON_RECOVERABLE set if a #MC occurs on
1143 	 * VM-Entry.  NMIs are handled by tdx_vcpu_enter_exit().
1144 	 */
1145 	if (is_nmi(intr_info) || is_machine_check(intr_info))
1146 		return 1;
1147 
1148 	vcpu->run->exit_reason = KVM_EXIT_EXCEPTION;
1149 	vcpu->run->ex.exception = intr_info & INTR_INFO_VECTOR_MASK;
1150 	vcpu->run->ex.error_code = 0;
1151 
1152 	return 0;
1153 }
1154 
complete_hypercall_exit(struct kvm_vcpu * vcpu)1155 static int complete_hypercall_exit(struct kvm_vcpu *vcpu)
1156 {
1157 	tdvmcall_set_return_code(vcpu, vcpu->run->hypercall.ret);
1158 	return 1;
1159 }
1160 
tdx_emulate_vmcall(struct kvm_vcpu * vcpu)1161 static int tdx_emulate_vmcall(struct kvm_vcpu *vcpu)
1162 {
1163 	kvm_rax_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r10);
1164 	kvm_rbx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r11);
1165 	kvm_rcx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r12);
1166 	kvm_rdx_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r13);
1167 	kvm_rsi_write_raw(vcpu, to_tdx(vcpu)->vp_enter_args.r14);
1168 
1169 	return __kvm_emulate_hypercall(vcpu, 0, complete_hypercall_exit);
1170 }
1171 
1172 /*
1173  * Split into chunks and check interrupt pending between chunks.  This allows
1174  * for timely injection of interrupts to prevent issues with guest lockup
1175  * detection.
1176  */
1177 #define TDX_MAP_GPA_MAX_LEN (2 * 1024 * 1024)
1178 static void __tdx_map_gpa(struct vcpu_tdx *tdx);
1179 
tdx_complete_vmcall_map_gpa(struct kvm_vcpu * vcpu)1180 static int tdx_complete_vmcall_map_gpa(struct kvm_vcpu *vcpu)
1181 {
1182 	u64 hypercall_ret = READ_ONCE(vcpu->run->hypercall.ret);
1183 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1184 	long rc;
1185 
1186 	switch (hypercall_ret) {
1187 	case 0:
1188 		break;
1189 	case EAGAIN:
1190 		rc = TDVMCALL_STATUS_RETRY;
1191 		goto propagate_error;
1192 	case EINVAL:
1193 		rc = TDVMCALL_STATUS_INVALID_OPERAND;
1194 		goto propagate_error;
1195 	default:
1196 		WARN_ON_ONCE(kvm_is_valid_map_gpa_range_ret(hypercall_ret));
1197 		return -EINVAL;
1198 	}
1199 
1200 	tdx->map_gpa_next += TDX_MAP_GPA_MAX_LEN;
1201 	if (tdx->map_gpa_next >= tdx->map_gpa_end)
1202 		return 1;
1203 
1204 	/*
1205 	 * Stop processing the remaining part if there is a pending interrupt,
1206 	 * which could be qualified to deliver.  Skip checking pending RVI for
1207 	 * TDVMCALL_MAP_GPA, see comments in tdx_protected_apic_has_interrupt().
1208 	 */
1209 	if (kvm_vcpu_has_events(vcpu)) {
1210 		rc = TDVMCALL_STATUS_RETRY;
1211 		goto propagate_error;
1212 	}
1213 
1214 	__tdx_map_gpa(tdx);
1215 	return 0;
1216 
1217 propagate_error:
1218 	tdvmcall_set_return_code(vcpu, rc);
1219 	tdx->vp_enter_args.r11 = tdx->map_gpa_next;
1220 	return 1;
1221 }
1222 
__tdx_map_gpa(struct vcpu_tdx * tdx)1223 static void __tdx_map_gpa(struct vcpu_tdx *tdx)
1224 {
1225 	u64 gpa = tdx->map_gpa_next;
1226 	u64 size = tdx->map_gpa_end - tdx->map_gpa_next;
1227 
1228 	if (size > TDX_MAP_GPA_MAX_LEN)
1229 		size = TDX_MAP_GPA_MAX_LEN;
1230 
1231 	tdx->vcpu.run->exit_reason       = KVM_EXIT_HYPERCALL;
1232 	tdx->vcpu.run->hypercall.nr      = KVM_HC_MAP_GPA_RANGE;
1233 	/*
1234 	 * In principle this should have been -KVM_ENOSYS, but userspace (QEMU <=9.2)
1235 	 * assumed that vcpu->run->hypercall.ret is never changed by KVM and thus that
1236 	 * it was always zero on KVM_EXIT_HYPERCALL.  Since KVM is now overwriting
1237 	 * vcpu->run->hypercall.ret, ensuring that it is zero to not break QEMU.
1238 	 */
1239 	tdx->vcpu.run->hypercall.ret = 0;
1240 	tdx->vcpu.run->hypercall.args[0] = gpa & ~gfn_to_gpa(kvm_gfn_direct_bits(tdx->vcpu.kvm));
1241 	tdx->vcpu.run->hypercall.args[1] = size / PAGE_SIZE;
1242 	tdx->vcpu.run->hypercall.args[2] = vt_is_tdx_private_gpa(tdx->vcpu.kvm, gpa) ?
1243 					   KVM_MAP_GPA_RANGE_ENCRYPTED :
1244 					   KVM_MAP_GPA_RANGE_DECRYPTED;
1245 	tdx->vcpu.run->hypercall.flags   = KVM_EXIT_HYPERCALL_LONG_MODE;
1246 
1247 	tdx->vcpu.arch.complete_userspace_io = tdx_complete_vmcall_map_gpa;
1248 }
1249 
tdx_map_gpa(struct kvm_vcpu * vcpu)1250 static int tdx_map_gpa(struct kvm_vcpu *vcpu)
1251 {
1252 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1253 	u64 gpa = tdx->vp_enter_args.r12;
1254 	u64 size = tdx->vp_enter_args.r13;
1255 	u64 ret;
1256 
1257 	/*
1258 	 * Converting TDVMCALL_MAP_GPA to KVM_HC_MAP_GPA_RANGE requires
1259 	 * userspace to enable KVM_CAP_EXIT_HYPERCALL with KVM_HC_MAP_GPA_RANGE
1260 	 * bit set.  This is a base call so it should always be supported, but
1261 	 * KVM has no way to ensure that userspace implements the GHCI correctly.
1262 	 * So if KVM_HC_MAP_GPA_RANGE does not cause a VMEXIT, return an error
1263 	 * to the guest.
1264 	 */
1265 	if (!user_exit_on_hypercall(vcpu->kvm, KVM_HC_MAP_GPA_RANGE)) {
1266 		ret = TDVMCALL_STATUS_SUBFUNC_UNSUPPORTED;
1267 		goto error;
1268 	}
1269 
1270 	if (gpa + size <= gpa || !kvm_vcpu_is_legal_gpa(vcpu, gpa) ||
1271 	    !kvm_vcpu_is_legal_gpa(vcpu, gpa + size - 1) ||
1272 	    (vt_is_tdx_private_gpa(vcpu->kvm, gpa) !=
1273 	     vt_is_tdx_private_gpa(vcpu->kvm, gpa + size - 1))) {
1274 		ret = TDVMCALL_STATUS_INVALID_OPERAND;
1275 		goto error;
1276 	}
1277 
1278 	if (!PAGE_ALIGNED(gpa) || !PAGE_ALIGNED(size)) {
1279 		ret = TDVMCALL_STATUS_ALIGN_ERROR;
1280 		goto error;
1281 	}
1282 
1283 	tdx->map_gpa_end = gpa + size;
1284 	tdx->map_gpa_next = gpa;
1285 
1286 	__tdx_map_gpa(tdx);
1287 	return 0;
1288 
1289 error:
1290 	tdvmcall_set_return_code(vcpu, ret);
1291 	tdx->vp_enter_args.r11 = gpa;
1292 	return 1;
1293 }
1294 
tdx_report_fatal_error(struct kvm_vcpu * vcpu)1295 static int tdx_report_fatal_error(struct kvm_vcpu *vcpu)
1296 {
1297 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1298 	u64 *regs = vcpu->run->system_event.data;
1299 	u64 *module_regs = &tdx->vp_enter_args.r8;
1300 	int index = VCPU_REGS_RAX;
1301 
1302 	vcpu->run->exit_reason = KVM_EXIT_SYSTEM_EVENT;
1303 	vcpu->run->system_event.type = KVM_SYSTEM_EVENT_TDX_FATAL;
1304 	vcpu->run->system_event.ndata = 16;
1305 
1306 	/* Dump 16 general-purpose registers to userspace in ascending order. */
1307 	regs[index++] = tdx->vp_enter_ret;
1308 	regs[index++] = tdx->vp_enter_args.rcx;
1309 	regs[index++] = tdx->vp_enter_args.rdx;
1310 	regs[index++] = tdx->vp_enter_args.rbx;
1311 	regs[index++] = 0;
1312 	regs[index++] = 0;
1313 	regs[index++] = tdx->vp_enter_args.rsi;
1314 	regs[index] = tdx->vp_enter_args.rdi;
1315 	for (index = 0; index < 8; index++)
1316 		regs[VCPU_REGS_R8 + index] = module_regs[index];
1317 
1318 	return 0;
1319 }
1320 
tdx_emulate_cpuid(struct kvm_vcpu * vcpu)1321 static int tdx_emulate_cpuid(struct kvm_vcpu *vcpu)
1322 {
1323 	u32 eax, ebx, ecx, edx;
1324 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1325 
1326 	/* EAX and ECX for cpuid is stored in R12 and R13. */
1327 	eax = tdx->vp_enter_args.r12;
1328 	ecx = tdx->vp_enter_args.r13;
1329 
1330 	kvm_cpuid(vcpu, &eax, &ebx, &ecx, &edx, false);
1331 
1332 	tdx->vp_enter_args.r12 = eax;
1333 	tdx->vp_enter_args.r13 = ebx;
1334 	tdx->vp_enter_args.r14 = ecx;
1335 	tdx->vp_enter_args.r15 = edx;
1336 
1337 	return 1;
1338 }
1339 
tdx_complete_pio_out(struct kvm_vcpu * vcpu)1340 static int tdx_complete_pio_out(struct kvm_vcpu *vcpu)
1341 {
1342 	vcpu->arch.pio.count = 0;
1343 	return 1;
1344 }
1345 
tdx_complete_pio_in(struct kvm_vcpu * vcpu)1346 static int tdx_complete_pio_in(struct kvm_vcpu *vcpu)
1347 {
1348 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
1349 	unsigned long val = 0;
1350 	int ret;
1351 
1352 	ret = ctxt->ops->pio_in_emulated(ctxt, vcpu->arch.pio.size,
1353 					 vcpu->arch.pio.port, &val, 1);
1354 
1355 	WARN_ON_ONCE(!ret);
1356 
1357 	tdvmcall_set_return_val(vcpu, val);
1358 
1359 	return 1;
1360 }
1361 
tdx_emulate_io(struct kvm_vcpu * vcpu)1362 static int tdx_emulate_io(struct kvm_vcpu *vcpu)
1363 {
1364 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1365 	struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
1366 	unsigned long val = 0;
1367 	unsigned int port;
1368 	u64 size, write;
1369 	int ret;
1370 
1371 	++vcpu->stat.io_exits;
1372 
1373 	size = tdx->vp_enter_args.r12;
1374 	write = tdx->vp_enter_args.r13;
1375 	port = tdx->vp_enter_args.r14;
1376 
1377 	if ((write != 0 && write != 1) || (size != 1 && size != 2 && size != 4)) {
1378 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
1379 		return 1;
1380 	}
1381 
1382 	if (write) {
1383 		val = tdx->vp_enter_args.r15;
1384 		ret = ctxt->ops->pio_out_emulated(ctxt, size, port, &val, 1);
1385 	} else {
1386 		ret = ctxt->ops->pio_in_emulated(ctxt, size, port, &val, 1);
1387 	}
1388 
1389 	if (!ret)
1390 		vcpu->arch.complete_userspace_io = write ? tdx_complete_pio_out :
1391 							   tdx_complete_pio_in;
1392 	else if (!write)
1393 		tdvmcall_set_return_val(vcpu, val);
1394 
1395 	return ret;
1396 }
1397 
tdx_complete_mmio_read(struct kvm_vcpu * vcpu)1398 static int tdx_complete_mmio_read(struct kvm_vcpu *vcpu)
1399 {
1400 	unsigned long val = 0;
1401 	gpa_t gpa;
1402 	int size;
1403 
1404 	gpa = vcpu->mmio_fragments[0].gpa;
1405 	size = vcpu->mmio_fragments[0].len;
1406 
1407 	memcpy(&val, vcpu->run->mmio.data, size);
1408 	tdvmcall_set_return_val(vcpu, val);
1409 	trace_kvm_mmio(KVM_TRACE_MMIO_READ, size, gpa, &val);
1410 	return 1;
1411 }
1412 
tdx_mmio_write(struct kvm_vcpu * vcpu,gpa_t gpa,int size,unsigned long val)1413 static inline int tdx_mmio_write(struct kvm_vcpu *vcpu, gpa_t gpa, int size,
1414 				 unsigned long val)
1415 {
1416 	if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
1417 		trace_kvm_fast_mmio(gpa);
1418 		return 0;
1419 	}
1420 
1421 	trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, size, gpa, &val);
1422 	if (kvm_io_bus_write(vcpu, KVM_MMIO_BUS, gpa, size, &val))
1423 		return -EOPNOTSUPP;
1424 
1425 	return 0;
1426 }
1427 
tdx_mmio_read(struct kvm_vcpu * vcpu,gpa_t gpa,int size)1428 static inline int tdx_mmio_read(struct kvm_vcpu *vcpu, gpa_t gpa, int size)
1429 {
1430 	unsigned long val;
1431 
1432 	if (kvm_io_bus_read(vcpu, KVM_MMIO_BUS, gpa, size, &val))
1433 		return -EOPNOTSUPP;
1434 
1435 	tdvmcall_set_return_val(vcpu, val);
1436 	trace_kvm_mmio(KVM_TRACE_MMIO_READ, size, gpa, &val);
1437 	return 0;
1438 }
1439 
tdx_emulate_mmio(struct kvm_vcpu * vcpu)1440 static int tdx_emulate_mmio(struct kvm_vcpu *vcpu)
1441 {
1442 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1443 	int size, write, r;
1444 	unsigned long val;
1445 	gpa_t gpa;
1446 
1447 	size = tdx->vp_enter_args.r12;
1448 	write = tdx->vp_enter_args.r13;
1449 	gpa = tdx->vp_enter_args.r14;
1450 	val = write ? tdx->vp_enter_args.r15 : 0;
1451 
1452 	if (size != 1 && size != 2 && size != 4 && size != 8)
1453 		goto error;
1454 	if (write != 0 && write != 1)
1455 		goto error;
1456 
1457 	/*
1458 	 * TDG.VP.VMCALL<MMIO> allows only shared GPA, it makes no sense to
1459 	 * do MMIO emulation for private GPA.
1460 	 */
1461 	if (vt_is_tdx_private_gpa(vcpu->kvm, gpa) ||
1462 	    vt_is_tdx_private_gpa(vcpu->kvm, gpa + size - 1))
1463 		goto error;
1464 
1465 	gpa = gpa & ~gfn_to_gpa(kvm_gfn_direct_bits(vcpu->kvm));
1466 
1467 	if (write)
1468 		r = tdx_mmio_write(vcpu, gpa, size, val);
1469 	else
1470 		r = tdx_mmio_read(vcpu, gpa, size);
1471 	if (!r)
1472 		/* Kernel completed device emulation. */
1473 		return 1;
1474 
1475 	/* Request the device emulation to userspace device model. */
1476 	vcpu->mmio_is_write = write;
1477 
1478 	__kvm_prepare_emulated_mmio_exit(vcpu, gpa, size, &val, write);
1479 
1480 	if (!write) {
1481 		vcpu->arch.complete_userspace_io = tdx_complete_mmio_read;
1482 		vcpu->mmio_fragments[0].gpa = gpa;
1483 		vcpu->mmio_fragments[0].len = size;
1484 		trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, size, gpa, NULL);
1485 	}
1486 	return 0;
1487 
1488 error:
1489 	tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
1490 	return 1;
1491 }
1492 
tdx_complete_get_td_vm_call_info(struct kvm_vcpu * vcpu)1493 static int tdx_complete_get_td_vm_call_info(struct kvm_vcpu *vcpu)
1494 {
1495 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1496 
1497 	tdvmcall_set_return_code(vcpu, vcpu->run->tdx.get_tdvmcall_info.ret);
1498 
1499 	/*
1500 	 * For now, there is no TDVMCALL beyond GHCI base API supported by KVM
1501 	 * directly without the support from userspace, just set the value
1502 	 * returned from userspace.
1503 	 */
1504 	tdx->vp_enter_args.r11 = vcpu->run->tdx.get_tdvmcall_info.r11;
1505 	tdx->vp_enter_args.r12 = vcpu->run->tdx.get_tdvmcall_info.r12;
1506 	tdx->vp_enter_args.r13 = vcpu->run->tdx.get_tdvmcall_info.r13;
1507 	tdx->vp_enter_args.r14 = vcpu->run->tdx.get_tdvmcall_info.r14;
1508 
1509 	return 1;
1510 }
1511 
tdx_get_td_vm_call_info(struct kvm_vcpu * vcpu)1512 static int tdx_get_td_vm_call_info(struct kvm_vcpu *vcpu)
1513 {
1514 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1515 
1516 	switch (tdx->vp_enter_args.r12) {
1517 	case 0:
1518 		tdx->vp_enter_args.r11 = 0;
1519 		tdx->vp_enter_args.r12 = 0;
1520 		tdx->vp_enter_args.r13 = 0;
1521 		tdx->vp_enter_args.r14 = 0;
1522 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_SUCCESS);
1523 		return 1;
1524 	case 1:
1525 		vcpu->run->tdx.get_tdvmcall_info.leaf = tdx->vp_enter_args.r12;
1526 		vcpu->run->exit_reason = KVM_EXIT_TDX;
1527 		vcpu->run->tdx.flags = 0;
1528 		vcpu->run->tdx.nr = TDVMCALL_GET_TD_VM_CALL_INFO;
1529 		vcpu->run->tdx.get_tdvmcall_info.ret = TDVMCALL_STATUS_SUCCESS;
1530 		vcpu->run->tdx.get_tdvmcall_info.r11 = 0;
1531 		vcpu->run->tdx.get_tdvmcall_info.r12 = 0;
1532 		vcpu->run->tdx.get_tdvmcall_info.r13 = 0;
1533 		vcpu->run->tdx.get_tdvmcall_info.r14 = 0;
1534 		vcpu->arch.complete_userspace_io = tdx_complete_get_td_vm_call_info;
1535 		return 0;
1536 	default:
1537 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
1538 		return 1;
1539 	}
1540 }
1541 
tdx_complete_simple(struct kvm_vcpu * vcpu)1542 static int tdx_complete_simple(struct kvm_vcpu *vcpu)
1543 {
1544 	tdvmcall_set_return_code(vcpu, vcpu->run->tdx.unknown.ret);
1545 	return 1;
1546 }
1547 
tdx_get_quote(struct kvm_vcpu * vcpu)1548 static int tdx_get_quote(struct kvm_vcpu *vcpu)
1549 {
1550 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1551 	u64 gpa = tdx->vp_enter_args.r12;
1552 	u64 size = tdx->vp_enter_args.r13;
1553 
1554 	/* The gpa of buffer must have shared bit set. */
1555 	if (vt_is_tdx_private_gpa(vcpu->kvm, gpa)) {
1556 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
1557 		return 1;
1558 	}
1559 
1560 	vcpu->run->exit_reason = KVM_EXIT_TDX;
1561 	vcpu->run->tdx.flags = 0;
1562 	vcpu->run->tdx.nr = TDVMCALL_GET_QUOTE;
1563 	vcpu->run->tdx.get_quote.ret = TDVMCALL_STATUS_SUBFUNC_UNSUPPORTED;
1564 	vcpu->run->tdx.get_quote.gpa = gpa & ~gfn_to_gpa(kvm_gfn_direct_bits(tdx->vcpu.kvm));
1565 	vcpu->run->tdx.get_quote.size = size;
1566 
1567 	vcpu->arch.complete_userspace_io = tdx_complete_simple;
1568 
1569 	return 0;
1570 }
1571 
tdx_setup_event_notify_interrupt(struct kvm_vcpu * vcpu)1572 static int tdx_setup_event_notify_interrupt(struct kvm_vcpu *vcpu)
1573 {
1574 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1575 	u64 vector = tdx->vp_enter_args.r12;
1576 
1577 	if (vector < 32 || vector > 255) {
1578 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
1579 		return 1;
1580 	}
1581 
1582 	vcpu->run->exit_reason = KVM_EXIT_TDX;
1583 	vcpu->run->tdx.flags = 0;
1584 	vcpu->run->tdx.nr = TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT;
1585 	vcpu->run->tdx.setup_event_notify.ret = TDVMCALL_STATUS_SUBFUNC_UNSUPPORTED;
1586 	vcpu->run->tdx.setup_event_notify.vector = vector;
1587 
1588 	vcpu->arch.complete_userspace_io = tdx_complete_simple;
1589 
1590 	return 0;
1591 }
1592 
handle_tdvmcall(struct kvm_vcpu * vcpu)1593 static int handle_tdvmcall(struct kvm_vcpu *vcpu)
1594 {
1595 	switch (tdvmcall_leaf(vcpu)) {
1596 	case TDVMCALL_MAP_GPA:
1597 		return tdx_map_gpa(vcpu);
1598 	case TDVMCALL_REPORT_FATAL_ERROR:
1599 		return tdx_report_fatal_error(vcpu);
1600 	case TDVMCALL_GET_TD_VM_CALL_INFO:
1601 		return tdx_get_td_vm_call_info(vcpu);
1602 	case TDVMCALL_GET_QUOTE:
1603 		return tdx_get_quote(vcpu);
1604 	case TDVMCALL_SETUP_EVENT_NOTIFY_INTERRUPT:
1605 		return tdx_setup_event_notify_interrupt(vcpu);
1606 	default:
1607 		break;
1608 	}
1609 
1610 	tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_SUBFUNC_UNSUPPORTED);
1611 	return 1;
1612 }
1613 
tdx_load_mmu_pgd(struct kvm_vcpu * vcpu,hpa_t root_hpa,int pgd_level)1614 void tdx_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa, int pgd_level)
1615 {
1616 	u64 shared_bit = (pgd_level == 5) ? TDX_SHARED_BIT_PWL_5 :
1617 			  TDX_SHARED_BIT_PWL_4;
1618 
1619 	if (KVM_BUG_ON(shared_bit != kvm_gfn_direct_bits(vcpu->kvm), vcpu->kvm))
1620 		return;
1621 
1622 	td_vmcs_write64(to_tdx(vcpu), SHARED_EPT_POINTER, root_hpa);
1623 }
1624 
tdx_topup_external_pamt_cache(struct kvm_vcpu * vcpu,int min_nr_spts)1625 static int tdx_topup_external_pamt_cache(struct kvm_vcpu *vcpu, int min_nr_spts)
1626 {
1627 	/*
1628 	 * Minus one page to exclude the root SPT, but plus one page for a
1629 	 * possible 4KB private mapping.
1630 	 */
1631 	min_nr_spts += -1 + 1;
1632 
1633 	return tdx_topup_pamt_cache(&to_tdx(vcpu)->pamt_cache, min_nr_spts);
1634 }
1635 
tdx_mem_page_add(struct kvm * kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn)1636 static int tdx_mem_page_add(struct kvm *kvm, gfn_t gfn, enum pg_level level,
1637 			    kvm_pfn_t pfn)
1638 {
1639 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
1640 	u64 err, entry, level_state;
1641 	gpa_t gpa = gfn_to_gpa(gfn);
1642 
1643 	lockdep_assert_held(&kvm->slots_lock);
1644 
1645 	if (KVM_BUG_ON(kvm->arch.pre_fault_allowed, kvm) ||
1646 	    KVM_BUG_ON(!kvm_tdx->page_add_src, kvm))
1647 		return -EIO;
1648 
1649 	err = tdh_mem_page_add(&kvm_tdx->td, gpa, pfn, kvm_tdx->page_add_src,
1650 			       &entry, &level_state);
1651 	if (unlikely(tdx_operand_busy(err)))
1652 		return -EBUSY;
1653 
1654 	if (TDX_BUG_ON_2(err, TDH_MEM_PAGE_ADD, entry, level_state, kvm))
1655 		return -EIO;
1656 
1657 	return 0;
1658 }
1659 
tdx_mem_page_aug(struct kvm * kvm,gfn_t gfn,enum pg_level level,kvm_pfn_t pfn)1660 static int tdx_mem_page_aug(struct kvm *kvm, gfn_t gfn,
1661 			    enum pg_level level, kvm_pfn_t pfn)
1662 {
1663 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
1664 	gpa_t gpa = gfn_to_gpa(gfn);
1665 	u64 entry, level_state;
1666 	u64 err;
1667 
1668 	err = tdh_mem_page_aug(&kvm_tdx->td, gpa, level, pfn, &entry, &level_state);
1669 	if (unlikely(tdx_operand_busy(err)))
1670 		return -EBUSY;
1671 
1672 	if (TDX_BUG_ON_2(err, TDH_MEM_PAGE_AUG, entry, level_state, kvm))
1673 		return -EIO;
1674 
1675 	return 0;
1676 }
1677 
tdx_spte_to_sept_pt(struct kvm * kvm,gfn_t gfn,u64 new_spte,enum pg_level level)1678 static struct page *tdx_spte_to_sept_pt(struct kvm *kvm, gfn_t gfn,
1679 					u64 new_spte, enum pg_level level)
1680 {
1681 	struct kvm_mmu_page *sp = spte_to_child_sp(new_spte);
1682 
1683 	if (KVM_BUG_ON(!sp->external_spt, kvm) ||
1684 	    KVM_BUG_ON(sp->role.level + 1 != level, kvm) ||
1685 	    KVM_BUG_ON(sp->gfn != gfn, kvm))
1686 		return NULL;
1687 
1688 	return virt_to_page(sp->external_spt);
1689 }
1690 
tdx_sept_map_nonleaf_spte(struct kvm * kvm,gfn_t gfn,enum pg_level level,u64 new_spte)1691 static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
1692 				     enum pg_level level, u64 new_spte)
1693 {
1694 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
1695 	gpa_t gpa = gfn_to_gpa(gfn);
1696 	u64 err, entry, level_state;
1697 	struct page *sept_pt;
1698 	int ret;
1699 
1700 	if (KVM_BUG_ON(!vcpu, kvm))
1701 		return -EIO;
1702 
1703 	sept_pt = tdx_spte_to_sept_pt(kvm, gfn, new_spte, level);
1704 	if (!sept_pt)
1705 		return -EIO;
1706 
1707 	ret = tdx_pamt_get(page_to_pfn(sept_pt), &to_tdx(vcpu)->pamt_cache);
1708 	if (KVM_BUG_ON(ret, kvm))
1709 		return ret;
1710 
1711 	err = tdh_mem_sept_add(&to_kvm_tdx(kvm)->td, gpa, level, sept_pt,
1712 			       &entry, &level_state);
1713 	if (err)
1714 		tdx_pamt_put(page_to_pfn(sept_pt));
1715 
1716 	if (unlikely(tdx_operand_busy(err)))
1717 		return -EBUSY;
1718 
1719 	if (TDX_BUG_ON_2(err, TDH_MEM_SEPT_ADD, entry, level_state, kvm))
1720 		return -EIO;
1721 
1722 	return 0;
1723 }
1724 
tdx_sept_map_leaf_spte(struct kvm * kvm,gfn_t gfn,enum pg_level level,u64 new_spte)1725 static int tdx_sept_map_leaf_spte(struct kvm *kvm, gfn_t gfn, enum pg_level level,
1726 				  u64 new_spte)
1727 {
1728 	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
1729 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
1730 	kvm_pfn_t pfn = spte_to_pfn(new_spte);
1731 	int ret;
1732 
1733 	if (KVM_BUG_ON(!vcpu, kvm))
1734 		return -EIO;
1735 
1736 	/* TODO: handle large pages. */
1737 	if (KVM_BUG_ON(level != PG_LEVEL_4K, kvm))
1738 		return -EIO;
1739 
1740 	WARN_ON_ONCE((new_spte & VMX_EPT_RWX_MASK) != VMX_EPT_RWX_MASK);
1741 
1742 	ret = tdx_pamt_get(pfn, &to_tdx(vcpu)->pamt_cache);
1743 	if (KVM_BUG_ON(ret, kvm))
1744 		return ret;
1745 
1746 	/*
1747 	 * Ensure pre_fault_allowed is read by kvm_arch_vcpu_pre_fault_memory()
1748 	 * before kvm_tdx->state.  Userspace must not be allowed to pre-fault
1749 	 * arbitrary memory until the initial memory image is finalized.  Pairs
1750 	 * with the smp_wmb() in tdx_td_finalize().
1751 	 */
1752 	smp_rmb();
1753 
1754 	/*
1755 	 * If the TD isn't finalized/runnable, then userspace is initializing
1756 	 * the VM image via KVM_TDX_INIT_MEM_REGION; ADD the page to the TD.
1757 	 */
1758 	if (likely(kvm_tdx->state == TD_STATE_RUNNABLE))
1759 		ret = tdx_mem_page_aug(kvm, gfn, level, pfn);
1760 	else
1761 		ret = tdx_mem_page_add(kvm, gfn, level, pfn);
1762 
1763 	if (ret)
1764 		tdx_pamt_put(pfn);
1765 
1766 	return ret;
1767 }
1768 
1769 /*
1770  * Ensure shared and private EPTs to be flushed on all vCPUs.
1771  * tdh_mem_track() is the only caller that increases TD epoch. An increase in
1772  * the TD epoch (e.g., to value "N + 1") is successful only if no vCPUs are
1773  * running in guest mode with the value "N - 1".
1774  *
1775  * A successful execution of tdh_mem_track() ensures that vCPUs can only run in
1776  * guest mode with TD epoch value "N" if no TD exit occurs after the TD epoch
1777  * being increased to "N + 1".
1778  *
1779  * Kicking off all vCPUs after that further results in no vCPUs can run in guest
1780  * mode with TD epoch value "N", which unblocks the next tdh_mem_track() (e.g.
1781  * to increase TD epoch to "N + 2").
1782  *
1783  * TDX module will flush EPT on the next TD enter and make vCPUs to run in
1784  * guest mode with TD epoch value "N + 1".
1785  *
1786  * kvm_make_all_cpus_request() guarantees all vCPUs are out of guest mode by
1787  * waiting empty IPI handler ack_kick().
1788  *
1789  * No action is required to the vCPUs being kicked off since the kicking off
1790  * occurs certainly after TD epoch increment and before the next
1791  * tdh_mem_track().
1792  */
tdx_track(struct kvm * kvm)1793 static void tdx_track(struct kvm *kvm)
1794 {
1795 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
1796 	u64 err;
1797 
1798 	/* If TD isn't finalized, it's before any vcpu running. */
1799 	if (unlikely(kvm_tdx->state != TD_STATE_RUNNABLE))
1800 		return;
1801 
1802 	/*
1803 	 * The full sequence of TDH.MEM.TRACK and forcing vCPUs out of guest
1804 	 * mode must be serialized, as TDH.MEM.TRACK will fail if the previous
1805 	 * tracking epoch hasn't completed.
1806 	 */
1807 	lockdep_assert_held_write(&kvm->mmu_lock);
1808 
1809 	err = tdh_do_no_vcpus(tdh_mem_track, kvm, &kvm_tdx->td);
1810 	TDX_BUG_ON(err, TDH_MEM_TRACK, kvm);
1811 
1812 	kvm_make_all_cpus_request(kvm, KVM_REQ_OUTSIDE_GUEST_MODE);
1813 }
1814 
tdx_sept_remove_leaf_spte(struct kvm * kvm,gfn_t gfn,enum pg_level level,u64 old_spte)1815 static int tdx_sept_remove_leaf_spte(struct kvm *kvm, gfn_t gfn,
1816 				     enum pg_level level, u64 old_spte)
1817 {
1818 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
1819 	kvm_pfn_t pfn = spte_to_pfn(old_spte);
1820 	gpa_t gpa = gfn_to_gpa(gfn);
1821 	u64 err, entry, level_state;
1822 
1823 	lockdep_assert_held_write(&kvm->mmu_lock);
1824 
1825 	/*
1826 	 * HKID is released after all private pages have been removed, and set
1827 	 * before any might be populated. Warn if zapping is attempted when
1828 	 * there can't be anything populated in the private EPT.
1829 	 */
1830 	if (KVM_BUG_ON(!is_hkid_assigned(to_kvm_tdx(kvm)), kvm))
1831 		return -EIO;
1832 
1833 	/* TODO: handle large pages. */
1834 	if (KVM_BUG_ON(level != PG_LEVEL_4K, kvm))
1835 		return -EIO;
1836 
1837 	err = tdh_do_no_vcpus(tdh_mem_range_block, kvm, &kvm_tdx->td, gpa,
1838 			      level, &entry, &level_state);
1839 	if (TDX_BUG_ON_2(err, TDH_MEM_RANGE_BLOCK, entry, level_state, kvm))
1840 		return -EIO;
1841 
1842 	/*
1843 	 * TDX requires TLB tracking before dropping private page.  Do
1844 	 * it here, although it is also done later.
1845 	 */
1846 	tdx_track(kvm);
1847 
1848 	/*
1849 	 * When zapping private page, write lock is held. So no race condition
1850 	 * with other vcpu sept operation.
1851 	 * Race with TDH.VP.ENTER due to (0-step mitigation) and Guest TDCALLs.
1852 	 */
1853 	err = tdh_do_no_vcpus(tdh_mem_page_remove, kvm, &kvm_tdx->td, gpa,
1854 			      level, &entry, &level_state);
1855 	if (TDX_BUG_ON_2(err, TDH_MEM_PAGE_REMOVE, entry, level_state, kvm))
1856 		return -EIO;
1857 
1858 	err = tdh_phymem_page_wbinvd_hkid((u16)kvm_tdx->hkid, pfn);
1859 	if (TDX_BUG_ON(err, TDH_PHYMEM_PAGE_WBINVD, kvm))
1860 		return -EIO;
1861 
1862 	tdx_quirk_reset_paddr(PFN_PHYS(pfn), PAGE_SIZE);
1863 	tdx_pamt_put(pfn);
1864 	return 0;
1865 }
1866 
1867 /*
1868  * Handle changes for
1869  * (1) leaf SPTEs from non-present to present
1870  * (2) non-leaf SPTEs from non-present to present
1871  * (3) leaf SPTEs from present to non-present
1872  *
1873  * - (1) and (2) must be under shared mmu_lock. If (1) and (2) are under
1874  *   exclusive mmu_lock (currently impossible), contention errors may lead to
1875  *   KVM_BUG_ON() in handle_changed_spte(), e.g., due to tdx_mem_page_aug(),
1876  *   tdx_mem_page_add(), or tdh_mem_sept_add() contending with tdh_vp_enter()
1877  *   due to zero-step mitigation or contending with TDCALLs.
1878  * - (3) must be under write mmu_lock. If (3) is under shared mmu_lock
1879  *   (currently impossible), warnings will be generated due to
1880  *   lockdep_assert_held_write() or TDX_BUG_ON() caused by concurrent BLOCK,
1881  *   TRACK, REMOVE.
1882  * - Promotion/demotion is not yet supported.
1883  */
tdx_sept_set_private_spte(struct kvm * kvm,gfn_t gfn,u64 old_spte,u64 new_spte,enum pg_level level)1884 static int tdx_sept_set_private_spte(struct kvm *kvm, gfn_t gfn, u64 old_spte,
1885 				     u64 new_spte, enum pg_level level)
1886 {
1887 	lockdep_assert_held(&kvm->mmu_lock);
1888 
1889 	if (is_shadow_present_pte(old_spte))
1890 		return tdx_sept_remove_leaf_spte(kvm, gfn, level, old_spte);
1891 
1892 	if (KVM_BUG_ON(!is_shadow_present_pte(new_spte), kvm))
1893 		return -EIO;
1894 
1895 	if (!is_last_spte(new_spte, level))
1896 		return tdx_sept_map_nonleaf_spte(kvm, gfn, level, new_spte);
1897 
1898 	return tdx_sept_map_leaf_spte(kvm, gfn, level, new_spte);
1899 }
1900 
1901 /*
1902  * Handle changes for non-leaf SPTEs from present to non-present.
1903  * Must be under exclusive mmu_lock and cannot fail.
1904  */
tdx_sept_free_private_spt(struct kvm * kvm,struct kvm_mmu_page * sp)1905 static void tdx_sept_free_private_spt(struct kvm *kvm, struct kvm_mmu_page *sp)
1906 {
1907 	struct page *sept_pt = virt_to_page(sp->external_spt);
1908 
1909 	/*
1910 	 * KVM doesn't (yet) zap page table pages in mirror page table while
1911 	 * TD is active, though guest pages mapped in mirror page table could be
1912 	 * zapped during TD is active, e.g. for shared <-> private conversion
1913 	 * and slot move/deletion.
1914 	 *
1915 	 * In other words, KVM should only free mirror page tables after the
1916 	 * TD's hkid is freed, when the TD is being torn down.
1917 	 *
1918 	 * If the S-EPT PTE can't be removed for any reason, intentionally leak
1919 	 * the page to prevent the kernel from accessing the encrypted page.
1920 	 */
1921 	if (KVM_BUG_ON(is_hkid_assigned(to_kvm_tdx(kvm)), kvm) ||
1922 	    tdx_reclaim_page(sept_pt))
1923 		goto out;
1924 
1925 	/*
1926 	 * Immediately free the S-EPT page as the TDX subsystem doesn't support
1927 	 * freeing pages from RCU callbacks, and more importantly because
1928 	 * TDH.PHYMEM.PAGE.RECLAIM ensures there are no outstanding readers.
1929 	 */
1930 	tdx_free_control_page(sept_pt);
1931 out:
1932 	sp->external_spt = NULL;
1933 }
1934 
tdx_deliver_interrupt(struct kvm_lapic * apic,int delivery_mode,int trig_mode,int vector)1935 void tdx_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
1936 			   int trig_mode, int vector)
1937 {
1938 	struct kvm_vcpu *vcpu = apic->vcpu;
1939 	struct vcpu_tdx *tdx = to_tdx(vcpu);
1940 
1941 	/* TDX supports only posted interrupt.  No lapic emulation. */
1942 	__vmx_deliver_posted_interrupt(vcpu, &tdx->vt.pi_desc, vector);
1943 
1944 	trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, trig_mode, vector);
1945 }
1946 
tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu * vcpu)1947 static inline bool tdx_is_sept_violation_unexpected_pending(struct kvm_vcpu *vcpu)
1948 {
1949 	u64 eeq_type = to_tdx(vcpu)->ext_exit_qualification & TDX_EXT_EXIT_QUAL_TYPE_MASK;
1950 	u64 eq = vmx_get_exit_qual(vcpu);
1951 
1952 	if (eeq_type != TDX_EXT_EXIT_QUAL_TYPE_PENDING_EPT_VIOLATION)
1953 		return false;
1954 
1955 	return !(eq & EPT_VIOLATION_PROT_MASK);
1956 }
1957 
tdx_handle_ept_violation(struct kvm_vcpu * vcpu)1958 static int tdx_handle_ept_violation(struct kvm_vcpu *vcpu)
1959 {
1960 	unsigned long exit_qual;
1961 	gpa_t gpa = to_tdx(vcpu)->exit_gpa;
1962 	bool local_retry = false;
1963 	int ret;
1964 
1965 	if (vt_is_tdx_private_gpa(vcpu->kvm, gpa)) {
1966 		if (tdx_is_sept_violation_unexpected_pending(vcpu)) {
1967 			pr_warn("Guest access before accepting 0x%llx on vCPU %d\n",
1968 				gpa, vcpu->vcpu_id);
1969 			kvm_vm_dead(vcpu->kvm);
1970 			return -EIO;
1971 		}
1972 		/*
1973 		 * Always treat SEPT violations as write faults.  Ignore the
1974 		 * EXIT_QUALIFICATION reported by TDX-SEAM for SEPT violations.
1975 		 * TD private pages are always RWX in the SEPT tables,
1976 		 * i.e. they're always mapped writable.  Just as importantly,
1977 		 * treating SEPT violations as write faults is necessary to
1978 		 * avoid COW allocations, which will cause TDAUGPAGE failures
1979 		 * due to aliasing a single HPA to multiple GPAs.
1980 		 */
1981 		exit_qual = EPT_VIOLATION_ACC_WRITE;
1982 
1983 		/* Only private GPA triggers zero-step mitigation */
1984 		local_retry = true;
1985 	} else {
1986 		exit_qual = vmx_get_exit_qual(vcpu);
1987 		/*
1988 		 * EPT violation due to instruction fetch should never be
1989 		 * triggered from shared memory in TDX guest.  If such EPT
1990 		 * violation occurs, treat it as broken hardware.
1991 		 */
1992 		if (KVM_BUG_ON(exit_qual & EPT_VIOLATION_ACC_INSTR, vcpu->kvm))
1993 			return -EIO;
1994 	}
1995 
1996 	trace_kvm_page_fault(vcpu, gpa, exit_qual);
1997 
1998 	/*
1999 	 * To minimize TDH.VP.ENTER invocations, retry locally for private GPA
2000 	 * mapping in TDX.
2001 	 *
2002 	 * KVM may return RET_PF_RETRY for private GPA due to
2003 	 * - contentions when atomically updating SPTEs of the mirror page table
2004 	 * - in-progress GFN invalidation or memslot removal.
2005 	 * - TDX_OPERAND_BUSY error from TDH.MEM.PAGE.AUG or TDH.MEM.SEPT.ADD,
2006 	 *   caused by contentions with TDH.VP.ENTER (with zero-step mitigation)
2007 	 *   or certain TDCALLs.
2008 	 *
2009 	 * If TDH.VP.ENTER is invoked more times than the threshold set by the
2010 	 * TDX module before KVM resolves the private GPA mapping, the TDX
2011 	 * module will activate zero-step mitigation during TDH.VP.ENTER. This
2012 	 * process acquires an SEPT tree lock in the TDX module, leading to
2013 	 * further contentions with TDH.MEM.PAGE.AUG or TDH.MEM.SEPT.ADD
2014 	 * operations on other vCPUs.
2015 	 *
2016 	 * Breaking out of local retries for kvm_vcpu_has_events() is for
2017 	 * interrupt injection. kvm_vcpu_has_events() should not see pending
2018 	 * events for TDX. Since KVM can't determine if IRQs (or NMIs) are
2019 	 * blocked by TDs, false positives are inevitable i.e., KVM may re-enter
2020 	 * the guest even if the IRQ/NMI can't be delivered.
2021 	 *
2022 	 * Note: even without breaking out of local retries, zero-step
2023 	 * mitigation may still occur due to
2024 	 * - invoking of TDH.VP.ENTER after KVM_EXIT_MEMORY_FAULT,
2025 	 * - a single RIP causing EPT violations for more GFNs than the
2026 	 *   threshold count.
2027 	 * This is safe, as triggering zero-step mitigation only introduces
2028 	 * contentions to page installation SEAMCALLs on other vCPUs, which will
2029 	 * handle retries locally in their EPT violation handlers.
2030 	 */
2031 	while (1) {
2032 		struct kvm_memory_slot *slot;
2033 
2034 		ret = __vmx_handle_ept_violation(vcpu, gpa, exit_qual);
2035 
2036 		if (ret != RET_PF_RETRY || !local_retry)
2037 			break;
2038 
2039 		if (kvm_vcpu_has_events(vcpu) || signal_pending(current))
2040 			break;
2041 
2042 		if (kvm_test_request(KVM_REQ_VM_DEAD, vcpu)) {
2043 			ret = -EIO;
2044 			break;
2045 		}
2046 
2047 		/*
2048 		 * Bail if the memslot is invalid, i.e. is being deleted, as
2049 		 * faulting in will never succeed and this task needs to drop
2050 		 * SRCU in order to let memslot deletion complete.
2051 		 */
2052 		slot = kvm_vcpu_gfn_to_memslot(vcpu, gpa_to_gfn(gpa));
2053 		if (slot && slot->flags & KVM_MEMSLOT_INVALID)
2054 			break;
2055 
2056 		cond_resched();
2057 	}
2058 	return ret;
2059 }
2060 
tdx_complete_emulated_msr(struct kvm_vcpu * vcpu,int err)2061 int tdx_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2062 {
2063 	if (err) {
2064 		tdvmcall_set_return_code(vcpu, TDVMCALL_STATUS_INVALID_OPERAND);
2065 		return 1;
2066 	}
2067 
2068 	if (vmx_get_exit_reason(vcpu).basic == EXIT_REASON_MSR_READ)
2069 		tdvmcall_set_return_val(vcpu, kvm_read_edx_eax(vcpu));
2070 
2071 	return 1;
2072 }
2073 
2074 
tdx_handle_exit(struct kvm_vcpu * vcpu,fastpath_t fastpath)2075 int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath)
2076 {
2077 	struct vcpu_tdx *tdx = to_tdx(vcpu);
2078 	u64 vp_enter_ret = tdx->vp_enter_ret;
2079 	union vmx_exit_reason exit_reason = vmx_get_exit_reason(vcpu);
2080 
2081 	if (fastpath != EXIT_FASTPATH_NONE)
2082 		return 1;
2083 
2084 	if (unlikely(vp_enter_ret == EXIT_REASON_EPT_MISCONFIG)) {
2085 		KVM_BUG_ON(1, vcpu->kvm);
2086 		return -EIO;
2087 	}
2088 
2089 	/*
2090 	 * Handle TDX SW errors, including TDX_SEAMCALL_UD, TDX_SEAMCALL_GP and
2091 	 * TDX_SEAMCALL_VMFAILINVALID.
2092 	 */
2093 	if (unlikely((vp_enter_ret & TDX_SW_ERROR) == TDX_SW_ERROR)) {
2094 		KVM_BUG_ON(!virt_rebooting, vcpu->kvm);
2095 		goto unhandled_exit;
2096 	}
2097 
2098 	if (unlikely(tdx_failed_vmentry(vcpu))) {
2099 		/*
2100 		 * If the guest state is protected, that means off-TD debug is
2101 		 * not enabled, TDX_NON_RECOVERABLE must be set.
2102 		 */
2103 		WARN_ON_ONCE(vcpu->arch.guest_state_protected &&
2104 				!(vp_enter_ret & TDX_NON_RECOVERABLE));
2105 		vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
2106 		vcpu->run->fail_entry.hardware_entry_failure_reason = exit_reason.full;
2107 		vcpu->run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
2108 		return 0;
2109 	}
2110 
2111 	if (unlikely(vp_enter_ret & (TDX_ERROR | TDX_NON_RECOVERABLE)) &&
2112 		exit_reason.basic != EXIT_REASON_TRIPLE_FAULT) {
2113 		kvm_pr_unimpl("TD vp_enter_ret 0x%llx\n", vp_enter_ret);
2114 		goto unhandled_exit;
2115 	}
2116 
2117 	WARN_ON_ONCE(exit_reason.basic != EXIT_REASON_TRIPLE_FAULT &&
2118 		     (vp_enter_ret & TDX_SEAMCALL_STATUS_MASK) != TDX_SUCCESS);
2119 
2120 	switch (exit_reason.basic) {
2121 	case EXIT_REASON_TRIPLE_FAULT:
2122 		vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
2123 		vcpu->mmio_needed = 0;
2124 		return 0;
2125 	case EXIT_REASON_EXCEPTION_NMI:
2126 		return tdx_handle_exception_nmi(vcpu);
2127 	case EXIT_REASON_EXTERNAL_INTERRUPT:
2128 		++vcpu->stat.irq_exits;
2129 		return 1;
2130 	case EXIT_REASON_CPUID:
2131 		return tdx_emulate_cpuid(vcpu);
2132 	case EXIT_REASON_HLT:
2133 		return kvm_emulate_halt_noskip(vcpu);
2134 	case EXIT_REASON_TDCALL:
2135 		return handle_tdvmcall(vcpu);
2136 	case EXIT_REASON_VMCALL:
2137 		return tdx_emulate_vmcall(vcpu);
2138 	case EXIT_REASON_IO_INSTRUCTION:
2139 		return tdx_emulate_io(vcpu);
2140 	case EXIT_REASON_MSR_READ:
2141 		kvm_ecx_write(vcpu, tdx->vp_enter_args.r12);
2142 		return kvm_emulate_rdmsr(vcpu);
2143 	case EXIT_REASON_MSR_WRITE:
2144 		kvm_ecx_write(vcpu, tdx->vp_enter_args.r12);
2145 		kvm_eax_write(vcpu, tdx->vp_enter_args.r13);
2146 		kvm_edx_write(vcpu, tdx->vp_enter_args.r13 >> 32);
2147 		return kvm_emulate_wrmsr(vcpu);
2148 	case EXIT_REASON_EPT_MISCONFIG:
2149 		return tdx_emulate_mmio(vcpu);
2150 	case EXIT_REASON_EPT_VIOLATION:
2151 		return tdx_handle_ept_violation(vcpu);
2152 	case EXIT_REASON_OTHER_SMI:
2153 		/*
2154 		 * Unlike VMX, SMI in SEAM non-root mode (i.e. when
2155 		 * TD guest vCPU is running) will cause VM exit to TDX module,
2156 		 * then SEAMRET to KVM.  Once it exits to KVM, SMI is delivered
2157 		 * and handled by kernel handler right away.
2158 		 *
2159 		 * The Other SMI exit can also be caused by the SEAM non-root
2160 		 * machine check delivered via Machine Check System Management
2161 		 * Interrupt (MSMI), but it has already been handled by the
2162 		 * kernel machine check handler, i.e., the memory page has been
2163 		 * marked as poisoned and it won't be freed to the free list
2164 		 * when the TDX guest is terminated (the TDX module marks the
2165 		 * guest as dead and prevent it from further running when
2166 		 * machine check happens in SEAM non-root).
2167 		 *
2168 		 * - A MSMI will not reach here, it's handled as non_recoverable
2169 		 *   case above.
2170 		 * - If it's not an MSMI, no need to do anything here.
2171 		 */
2172 		return 1;
2173 	default:
2174 		break;
2175 	}
2176 
2177 unhandled_exit:
2178 	kvm_prepare_unexpected_reason_exit(vcpu, vp_enter_ret);
2179 	return 0;
2180 }
2181 
tdx_get_exit_info(struct kvm_vcpu * vcpu,u32 * reason,u64 * info1,u64 * info2,u32 * intr_info,u32 * error_code)2182 void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
2183 		u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code)
2184 {
2185 	struct vcpu_tdx *tdx = to_tdx(vcpu);
2186 
2187 	*reason = tdx->vt.exit_reason.full;
2188 	if (*reason != -1u) {
2189 		*info1 = vmx_get_exit_qual(vcpu);
2190 		*info2 = tdx->ext_exit_qualification;
2191 		*intr_info = vmx_get_intr_info(vcpu);
2192 	} else {
2193 		*info1 = 0;
2194 		*info2 = 0;
2195 		*intr_info = 0;
2196 	}
2197 
2198 	*error_code = 0;
2199 }
2200 
tdx_has_emulated_msr(u32 index)2201 bool tdx_has_emulated_msr(u32 index)
2202 {
2203 	switch (index) {
2204 	case MSR_IA32_UCODE_REV:
2205 	case MSR_IA32_ARCH_CAPABILITIES:
2206 	case MSR_IA32_POWER_CTL:
2207 	case MSR_IA32_CR_PAT:
2208 	case MSR_MTRRcap:
2209 	case MTRRphysBase_MSR(0) ... MSR_MTRRfix4K_F8000:
2210 	case MSR_MTRRdefType:
2211 	case MSR_IA32_TSC_DEADLINE:
2212 	case MSR_IA32_MISC_ENABLE:
2213 	case MSR_PLATFORM_INFO:
2214 	case MSR_MISC_FEATURES_ENABLES:
2215 	case MSR_IA32_APICBASE:
2216 	case MSR_EFER:
2217 	case MSR_IA32_FEAT_CTL:
2218 	case MSR_IA32_MCG_CAP:
2219 	case MSR_IA32_MCG_STATUS:
2220 	case MSR_IA32_MCG_CTL:
2221 	case MSR_IA32_MCG_EXT_CTL:
2222 	case MSR_IA32_MC0_CTL ... MSR_IA32_MCx_CTL(KVM_MAX_MCE_BANKS) - 1:
2223 	case MSR_IA32_MC0_CTL2 ... MSR_IA32_MCx_CTL2(KVM_MAX_MCE_BANKS) - 1:
2224 		/* MSR_IA32_MCx_{CTL, STATUS, ADDR, MISC, CTL2} */
2225 	case MSR_KVM_POLL_CONTROL:
2226 	/*
2227 	 * Except for x2APIC registers that are virtualized by the CPU, which
2228 	 * KVM can't emulate as KVM doesn't have access to the virtual APIC
2229 	 * page, KVM emulates the same set of x2APIC registers for TDX versus
2230 	 * non-TDX guests.
2231 	 */
2232 	case X2APIC_MSR(APIC_ID):
2233 	case X2APIC_MSR(APIC_LVR):
2234 	case X2APIC_MSR(APIC_LDR):
2235 	case X2APIC_MSR(APIC_SPIV):
2236 	case X2APIC_MSR(APIC_ESR):
2237 	case X2APIC_MSR(APIC_LVTCMCI):
2238 	case X2APIC_MSR(APIC_ICR):
2239 	case X2APIC_MSR(APIC_LVTT):
2240 	case X2APIC_MSR(APIC_LVTTHMR):
2241 	case X2APIC_MSR(APIC_LVTPC):
2242 	case X2APIC_MSR(APIC_LVT0):
2243 	case X2APIC_MSR(APIC_LVT1):
2244 	case X2APIC_MSR(APIC_LVTERR):
2245 	case X2APIC_MSR(APIC_TMICT):
2246 	case X2APIC_MSR(APIC_TMCCT):
2247 	case X2APIC_MSR(APIC_TDCR):
2248 		return true;
2249 	default:
2250 		return false;
2251 	}
2252 }
2253 
tdx_is_read_only_msr(u32 index)2254 static bool tdx_is_read_only_msr(u32 index)
2255 {
2256 	return  index == MSR_IA32_APICBASE || index == MSR_EFER ||
2257 		index == MSR_IA32_FEAT_CTL;
2258 }
2259 
tdx_get_msr(struct kvm_vcpu * vcpu,struct msr_data * msr)2260 int tdx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2261 {
2262 	switch (msr->index) {
2263 	case MSR_IA32_FEAT_CTL:
2264 		/*
2265 		 * MCE and MCA are advertised via cpuid. Guest kernel could
2266 		 * check if LMCE is enabled or not.
2267 		 */
2268 		msr->data = FEAT_CTL_LOCKED;
2269 		if (vcpu->arch.mcg_cap & MCG_LMCE_P)
2270 			msr->data |= FEAT_CTL_LMCE_ENABLED;
2271 		return 0;
2272 	case MSR_IA32_MCG_EXT_CTL:
2273 		if (!msr->host_initiated && !(vcpu->arch.mcg_cap & MCG_LMCE_P))
2274 			return 1;
2275 		msr->data = vcpu->arch.mcg_ext_ctl;
2276 		return 0;
2277 	default:
2278 		if (!tdx_has_emulated_msr(msr->index))
2279 			return 1;
2280 
2281 		return kvm_get_msr_common(vcpu, msr);
2282 	}
2283 }
2284 
tdx_set_msr(struct kvm_vcpu * vcpu,struct msr_data * msr)2285 int tdx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2286 {
2287 	switch (msr->index) {
2288 	case MSR_IA32_MCG_EXT_CTL:
2289 		if ((!msr->host_initiated && !(vcpu->arch.mcg_cap & MCG_LMCE_P)) ||
2290 		    (msr->data & ~MCG_EXT_CTL_LMCE_EN))
2291 			return 1;
2292 		vcpu->arch.mcg_ext_ctl = msr->data;
2293 		return 0;
2294 	default:
2295 		if (tdx_is_read_only_msr(msr->index))
2296 			return 1;
2297 
2298 		if (!tdx_has_emulated_msr(msr->index))
2299 			return 1;
2300 
2301 		return kvm_set_msr_common(vcpu, msr);
2302 	}
2303 }
2304 
tdx_get_capabilities(struct kvm_tdx_cmd * cmd)2305 static int tdx_get_capabilities(struct kvm_tdx_cmd *cmd)
2306 {
2307 	const struct tdx_sys_info_td_conf *td_conf = &tdx_sysinfo->td_conf;
2308 	struct kvm_tdx_capabilities __user *user_caps;
2309 	struct kvm_tdx_capabilities *caps = NULL;
2310 	u32 nr_user_entries;
2311 	int ret = 0;
2312 
2313 	/* flags is reserved for future use */
2314 	if (cmd->flags)
2315 		return -EINVAL;
2316 
2317 	user_caps = u64_to_user_ptr(cmd->data);
2318 	if (get_user(nr_user_entries, &user_caps->cpuid.nent))
2319 		return -EFAULT;
2320 
2321 	if (nr_user_entries < td_conf->num_cpuid_config)
2322 		return -E2BIG;
2323 
2324 	caps = kzalloc_flex(*caps, cpuid.entries, td_conf->num_cpuid_config);
2325 	if (!caps)
2326 		return -ENOMEM;
2327 
2328 	ret = init_kvm_tdx_caps(td_conf, caps);
2329 	if (ret)
2330 		goto out;
2331 
2332 	if (copy_to_user(user_caps, caps, struct_size(caps, cpuid.entries,
2333 						      caps->cpuid.nent))) {
2334 		ret = -EFAULT;
2335 		goto out;
2336 	}
2337 
2338 out:
2339 	/* kfree() accepts NULL. */
2340 	kfree(caps);
2341 	return ret;
2342 }
2343 
2344 /*
2345  * KVM reports guest physical address in CPUID.0x800000008.EAX[23:16], which is
2346  * similar to TDX's GPAW. Use this field as the interface for userspace to
2347  * configure the GPAW and EPT level for TDs.
2348  *
2349  * Only values 48 and 52 are supported. Value 52 means GPAW-52 and EPT level
2350  * 5, Value 48 means GPAW-48 and EPT level 4. For value 48, GPAW-48 is always
2351  * supported. Value 52 is only supported when the platform supports 5 level
2352  * EPT.
2353  */
setup_tdparams_eptp_controls(struct kvm_cpuid2 * cpuid,struct td_params * td_params)2354 static int setup_tdparams_eptp_controls(struct kvm_cpuid2 *cpuid,
2355 					struct td_params *td_params)
2356 {
2357 	const struct kvm_cpuid_entry2 *entry;
2358 	int guest_pa;
2359 
2360 	entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent, 0x80000008, 0);
2361 	if (!entry)
2362 		return -EINVAL;
2363 
2364 	guest_pa = tdx_get_guest_phys_addr_bits(entry->eax);
2365 
2366 	if (guest_pa != 48 && guest_pa != 52)
2367 		return -EINVAL;
2368 
2369 	if (guest_pa == 52 && !cpu_has_vmx_ept_5levels())
2370 		return -EINVAL;
2371 
2372 	td_params->eptp_controls = VMX_EPTP_MT_WB;
2373 	if (guest_pa == 52) {
2374 		td_params->eptp_controls |= VMX_EPTP_PWL_5;
2375 		td_params->config_flags |= TDX_CONFIG_FLAGS_MAX_GPAW;
2376 	} else {
2377 		td_params->eptp_controls |= VMX_EPTP_PWL_4;
2378 	}
2379 
2380 	return 0;
2381 }
2382 
setup_tdparams_cpuids(struct kvm_cpuid2 * cpuid,struct td_params * td_params)2383 static int setup_tdparams_cpuids(struct kvm_cpuid2 *cpuid,
2384 				 struct td_params *td_params)
2385 {
2386 	const struct tdx_sys_info_td_conf *td_conf = &tdx_sysinfo->td_conf;
2387 	const struct kvm_cpuid_entry2 *entry;
2388 	struct tdx_cpuid_value *value;
2389 	int i, copy_cnt = 0;
2390 
2391 	/*
2392 	 * td_params.cpuid_values: The number and the order of cpuid_value must
2393 	 * be same to the one of struct tdsysinfo.{num_cpuid_config, cpuid_configs}
2394 	 * It's assumed that td_params was zeroed.
2395 	 */
2396 	for (i = 0; i < td_conf->num_cpuid_config; i++) {
2397 		struct kvm_cpuid_entry2 tmp;
2398 
2399 		td_init_cpuid_entry2(&tmp, i);
2400 
2401 		entry = kvm_find_cpuid_entry2(cpuid->entries, cpuid->nent,
2402 					      tmp.function, tmp.index);
2403 		if (!entry)
2404 			continue;
2405 
2406 		if (tdx_unsupported_cpuid(entry))
2407 			return -EINVAL;
2408 
2409 		copy_cnt++;
2410 
2411 		value = &td_params->cpuid_values[i];
2412 		value->eax = entry->eax;
2413 		value->ebx = entry->ebx;
2414 		value->ecx = entry->ecx;
2415 		value->edx = entry->edx;
2416 
2417 		/*
2418 		 * TDX module does not accept nonzero bits 16..23 for the
2419 		 * CPUID[0x80000008].EAX, see setup_tdparams_eptp_controls().
2420 		 */
2421 		if (tmp.function == 0x80000008)
2422 			value->eax = tdx_set_guest_phys_addr_bits(value->eax, 0);
2423 	}
2424 
2425 	/*
2426 	 * Rely on the TDX module to reject invalid configuration, but it can't
2427 	 * check of leafs that don't have a proper slot in td_params->cpuid_values
2428 	 * to stick then. So fail if there were entries that didn't get copied to
2429 	 * td_params.
2430 	 */
2431 	if (copy_cnt != cpuid->nent)
2432 		return -EINVAL;
2433 
2434 	return 0;
2435 }
2436 
setup_tdparams(struct kvm * kvm,struct td_params * td_params,struct kvm_tdx_init_vm * init_vm)2437 static int setup_tdparams(struct kvm *kvm, struct td_params *td_params,
2438 			struct kvm_tdx_init_vm *init_vm)
2439 {
2440 	const struct tdx_sys_info_td_conf *td_conf = &tdx_sysinfo->td_conf;
2441 	struct kvm_cpuid2 *cpuid = &init_vm->cpuid;
2442 	int ret;
2443 
2444 	if (kvm->created_vcpus)
2445 		return -EBUSY;
2446 
2447 	if (init_vm->attributes & ~tdx_get_supported_attrs(td_conf))
2448 		return -EINVAL;
2449 
2450 	if (init_vm->xfam & ~tdx_get_supported_xfam(td_conf))
2451 		return -EINVAL;
2452 
2453 	td_params->max_vcpus = kvm->max_vcpus;
2454 	td_params->attributes = init_vm->attributes | td_conf->attributes_fixed1;
2455 	td_params->xfam = init_vm->xfam | td_conf->xfam_fixed1;
2456 
2457 	td_params->config_flags = TDX_CONFIG_FLAGS_NO_RBP_MOD;
2458 	td_params->tsc_frequency = TDX_TSC_KHZ_TO_25MHZ(kvm->arch.default_tsc_khz);
2459 
2460 	ret = setup_tdparams_eptp_controls(cpuid, td_params);
2461 	if (ret)
2462 		return ret;
2463 
2464 	ret = setup_tdparams_cpuids(cpuid, td_params);
2465 	if (ret)
2466 		return ret;
2467 
2468 #define MEMCPY_SAME_SIZE(dst, src)				\
2469 	do {							\
2470 		BUILD_BUG_ON(sizeof(dst) != sizeof(src));	\
2471 		memcpy((dst), (src), sizeof(dst));		\
2472 	} while (0)
2473 
2474 	MEMCPY_SAME_SIZE(td_params->mrconfigid, init_vm->mrconfigid);
2475 	MEMCPY_SAME_SIZE(td_params->mrowner, init_vm->mrowner);
2476 	MEMCPY_SAME_SIZE(td_params->mrownerconfig, init_vm->mrownerconfig);
2477 
2478 	return 0;
2479 }
2480 
__tdx_td_init(struct kvm * kvm,struct td_params * td_params,u64 * seamcall_err)2481 static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
2482 			 u64 *seamcall_err)
2483 {
2484 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
2485 	cpumask_var_t packages;
2486 	struct page **tdcs_pages = NULL;
2487 	struct page *tdr_page;
2488 	int ret, i;
2489 	u64 err, rcx;
2490 
2491 	*seamcall_err = 0;
2492 	ret = tdx_guest_keyid_alloc();
2493 	if (ret < 0)
2494 		return ret;
2495 	kvm_tdx->hkid = ret;
2496 	kvm_tdx->misc_cg = get_current_misc_cg();
2497 	ret = misc_cg_try_charge(MISC_CG_RES_TDX, kvm_tdx->misc_cg, 1);
2498 	if (ret)
2499 		goto free_hkid;
2500 
2501 	ret = -ENOMEM;
2502 
2503 	tdr_page = tdx_alloc_control_page();
2504 	if (!tdr_page)
2505 		goto free_hkid;
2506 
2507 	kvm_tdx->td.tdcs_nr_pages = tdx_sysinfo->td_ctrl.tdcs_base_size / PAGE_SIZE;
2508 	/* TDVPS = TDVPR(4K page) + TDCX(multiple 4K pages), -1 for TDVPR. */
2509 	kvm_tdx->td.tdcx_nr_pages = tdx_sysinfo->td_ctrl.tdvps_base_size / PAGE_SIZE - 1;
2510 	tdcs_pages = kzalloc_objs(*kvm_tdx->td.tdcs_pages, kvm_tdx->td.tdcs_nr_pages,
2511 				  GFP_KERNEL_ACCOUNT);
2512 	if (!tdcs_pages)
2513 		goto free_tdr;
2514 
2515 	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++) {
2516 		tdcs_pages[i] = tdx_alloc_control_page();
2517 		if (!tdcs_pages[i])
2518 			goto free_tdcs;
2519 	}
2520 
2521 	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
2522 		goto free_tdcs;
2523 
2524 	cpus_read_lock();
2525 
2526 	/*
2527 	 * Need at least one CPU of the package to be online in order to
2528 	 * program all packages for host key id.  Check it.
2529 	 */
2530 	for_each_present_cpu(i)
2531 		cpumask_set_cpu(topology_physical_package_id(i), packages);
2532 	for_each_online_cpu(i)
2533 		cpumask_clear_cpu(topology_physical_package_id(i), packages);
2534 	if (!cpumask_empty(packages)) {
2535 		ret = -EIO;
2536 		/*
2537 		 * Because it's hard for human operator to figure out the
2538 		 * reason, warn it.
2539 		 */
2540 #define MSG_ALLPKG	"All packages need to have online CPU to create TD. Online CPU and retry.\n"
2541 		pr_warn_ratelimited(MSG_ALLPKG);
2542 		goto free_packages;
2543 	}
2544 
2545 	/*
2546 	 * TDH.MNG.CREATE tries to grab the global TDX module and fails
2547 	 * with TDX_OPERAND_BUSY when it fails to grab.  Take the global
2548 	 * lock to prevent it from failure.
2549 	 */
2550 	mutex_lock(&tdx_lock);
2551 	kvm_tdx->td.tdr_page = tdr_page;
2552 	err = tdh_mng_create(&kvm_tdx->td, kvm_tdx->hkid);
2553 	mutex_unlock(&tdx_lock);
2554 
2555 	if (err == TDX_RND_NO_ENTROPY) {
2556 		ret = -EAGAIN;
2557 		goto free_packages;
2558 	}
2559 
2560 	if (TDX_BUG_ON(err, TDH_MNG_CREATE, kvm)) {
2561 		ret = -EIO;
2562 		goto free_packages;
2563 	}
2564 
2565 	for_each_online_cpu(i) {
2566 		int pkg = topology_physical_package_id(i);
2567 
2568 		if (cpumask_test_and_set_cpu(pkg, packages))
2569 			continue;
2570 
2571 		/*
2572 		 * Program the memory controller in the package with an
2573 		 * encryption key associated to a TDX private host key id
2574 		 * assigned to this TDR.  Concurrent operations on same memory
2575 		 * controller results in TDX_OPERAND_BUSY. No locking needed
2576 		 * beyond the cpus_read_lock() above as it serializes against
2577 		 * hotplug and the first online CPU of the package is always
2578 		 * used. We never have two CPUs in the same socket trying to
2579 		 * program the key.
2580 		 */
2581 		ret = smp_call_on_cpu(i, tdx_do_tdh_mng_key_config,
2582 				      kvm_tdx, true);
2583 		if (ret)
2584 			break;
2585 	}
2586 	cpus_read_unlock();
2587 	free_cpumask_var(packages);
2588 	if (ret) {
2589 		i = 0;
2590 		goto teardown;
2591 	}
2592 
2593 	kvm_tdx->td.tdcs_pages = tdcs_pages;
2594 	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++) {
2595 		err = tdh_mng_addcx(&kvm_tdx->td, tdcs_pages[i]);
2596 		if (err == TDX_RND_NO_ENTROPY) {
2597 			/* Here it's hard to allow userspace to retry. */
2598 			ret = -EAGAIN;
2599 			goto teardown;
2600 		}
2601 		if (TDX_BUG_ON(err, TDH_MNG_ADDCX, kvm)) {
2602 			ret = -EIO;
2603 			goto teardown;
2604 		}
2605 	}
2606 
2607 	err = tdh_mng_init(&kvm_tdx->td, __pa(td_params), &rcx);
2608 	if ((err & TDX_SEAMCALL_STATUS_MASK) == TDX_OPERAND_INVALID) {
2609 		/*
2610 		 * Because a user gives operands, don't warn.
2611 		 * Return a hint to the user because it's sometimes hard for the
2612 		 * user to figure out which operand is invalid.  SEAMCALL status
2613 		 * code includes which operand caused invalid operand error.
2614 		 */
2615 		*seamcall_err = err;
2616 		ret = -EINVAL;
2617 		goto teardown;
2618 	} else if (TDX_BUG_ON_1(err, TDH_MNG_INIT, rcx, kvm)) {
2619 		ret = -EIO;
2620 		goto teardown;
2621 	}
2622 
2623 	return 0;
2624 
2625 	/*
2626 	 * The sequence for freeing resources from a partially initialized TD
2627 	 * varies based on where in the initialization flow failure occurred.
2628 	 * Simply use the full teardown and destroy, which naturally play nice
2629 	 * with partial initialization.
2630 	 */
2631 teardown:
2632 	/* Only free pages not yet added, so start at 'i' */
2633 	for (; i < kvm_tdx->td.tdcs_nr_pages; i++) {
2634 		tdx_free_control_page(tdcs_pages[i]);
2635 		tdcs_pages[i] = NULL;
2636 	}
2637 	if (!kvm_tdx->td.tdcs_pages)
2638 		kfree(tdcs_pages);
2639 
2640 	tdx_mmu_release_hkid(kvm);
2641 	tdx_reclaim_td_control_pages(kvm);
2642 
2643 	return ret;
2644 
2645 free_packages:
2646 	cpus_read_unlock();
2647 	free_cpumask_var(packages);
2648 
2649 free_tdcs:
2650 	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++)
2651 		tdx_free_control_page(tdcs_pages[i]);
2652 	kfree(tdcs_pages);
2653 	kvm_tdx->td.tdcs_pages = NULL;
2654 
2655 free_tdr:
2656 	tdx_free_control_page(tdr_page);
2657 	kvm_tdx->td.tdr_page = NULL;
2658 
2659 free_hkid:
2660 	tdx_hkid_free(kvm_tdx);
2661 
2662 	return ret;
2663 }
2664 
tdx_td_metadata_field_read(struct kvm_tdx * tdx,u64 field_id,u64 * data)2665 static u64 tdx_td_metadata_field_read(struct kvm_tdx *tdx, u64 field_id,
2666 				      u64 *data)
2667 {
2668 	u64 err;
2669 
2670 	err = tdh_mng_rd(&tdx->td, field_id, data);
2671 
2672 	return err;
2673 }
2674 
2675 #define TDX_MD_UNREADABLE_LEAF_MASK	GENMASK(30, 7)
2676 #define TDX_MD_UNREADABLE_SUBLEAF_MASK	GENMASK(31, 7)
2677 
tdx_read_cpuid(struct kvm_vcpu * vcpu,u32 leaf,u32 sub_leaf,bool sub_leaf_set,int * entry_index,struct kvm_cpuid_entry2 * out)2678 static int tdx_read_cpuid(struct kvm_vcpu *vcpu, u32 leaf, u32 sub_leaf,
2679 			  bool sub_leaf_set, int *entry_index,
2680 			  struct kvm_cpuid_entry2 *out)
2681 {
2682 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
2683 	u64 field_id = TD_MD_FIELD_ID_CPUID_VALUES;
2684 	u64 ebx_eax, edx_ecx;
2685 	u64 err = 0;
2686 
2687 	if (sub_leaf > 0b1111111)
2688 		return -EINVAL;
2689 
2690 	if (*entry_index >= KVM_MAX_CPUID_ENTRIES)
2691 		return -EINVAL;
2692 
2693 	if (leaf & TDX_MD_UNREADABLE_LEAF_MASK ||
2694 	    sub_leaf & TDX_MD_UNREADABLE_SUBLEAF_MASK)
2695 		return -EINVAL;
2696 
2697 	/*
2698 	 * bit 23:17, REVSERVED: reserved, must be 0;
2699 	 * bit 16,    LEAF_31: leaf number bit 31;
2700 	 * bit 15:9,  LEAF_6_0: leaf number bits 6:0, leaf bits 30:7 are
2701 	 *                      implicitly 0;
2702 	 * bit 8,     SUBLEAF_NA: sub-leaf not applicable flag;
2703 	 * bit 7:1,   SUBLEAF_6_0: sub-leaf number bits 6:0. If SUBLEAF_NA is 1,
2704 	 *                         the SUBLEAF_6_0 is all-1.
2705 	 *                         sub-leaf bits 31:7 are implicitly 0;
2706 	 * bit 0,     ELEMENT_I: Element index within field;
2707 	 */
2708 	field_id |= ((leaf & 0x80000000) ? 1 : 0) << 16;
2709 	field_id |= (leaf & 0x7f) << 9;
2710 	if (sub_leaf_set)
2711 		field_id |= (sub_leaf & 0x7f) << 1;
2712 	else
2713 		field_id |= 0x1fe;
2714 
2715 	err = tdx_td_metadata_field_read(kvm_tdx, field_id, &ebx_eax);
2716 	if (err) //TODO check for specific errors
2717 		goto err_out;
2718 
2719 	out->eax = (u32) ebx_eax;
2720 	out->ebx = (u32) (ebx_eax >> 32);
2721 
2722 	field_id++;
2723 	err = tdx_td_metadata_field_read(kvm_tdx, field_id, &edx_ecx);
2724 	/*
2725 	 * It's weird that reading edx_ecx fails while reading ebx_eax
2726 	 * succeeded.
2727 	 */
2728 	if (WARN_ON_ONCE(err))
2729 		goto err_out;
2730 
2731 	out->ecx = (u32) edx_ecx;
2732 	out->edx = (u32) (edx_ecx >> 32);
2733 
2734 	out->function = leaf;
2735 	out->index = sub_leaf;
2736 	out->flags |= sub_leaf_set ? KVM_CPUID_FLAG_SIGNIFCANT_INDEX : 0;
2737 
2738 	/*
2739 	 * Work around missing support on old TDX modules, fetch
2740 	 * guest maxpa from gfn_direct_bits.
2741 	 */
2742 	if (leaf == 0x80000008) {
2743 		gpa_t gpa_bits = gfn_to_gpa(kvm_gfn_direct_bits(vcpu->kvm));
2744 		unsigned int g_maxpa = __ffs(gpa_bits) + 1;
2745 
2746 		out->eax = tdx_set_guest_phys_addr_bits(out->eax, g_maxpa);
2747 	}
2748 
2749 	(*entry_index)++;
2750 
2751 	return 0;
2752 
2753 err_out:
2754 	out->eax = 0;
2755 	out->ebx = 0;
2756 	out->ecx = 0;
2757 	out->edx = 0;
2758 
2759 	return -EIO;
2760 }
2761 
2762 typedef void *tdx_vm_state_guard_t;
2763 
tdx_acquire_vm_state_locks(struct kvm * kvm)2764 static tdx_vm_state_guard_t tdx_acquire_vm_state_locks(struct kvm *kvm)
2765 {
2766 	int r;
2767 
2768 	mutex_lock(&kvm->lock);
2769 
2770 	r = kvm_lock_all_vcpus(kvm);
2771 	if (r)
2772 		goto out_err;
2773 
2774 	/*
2775 	 * Note the unintuitive ordering!  vcpu->mutex must be taken outside
2776 	 * kvm->slots_lock!
2777 	 */
2778 	mutex_lock(&kvm->slots_lock);
2779 	return kvm;
2780 
2781 out_err:
2782 	mutex_unlock(&kvm->lock);
2783 	return ERR_PTR(r);
2784 }
2785 
tdx_release_vm_state_locks(struct kvm * kvm)2786 static void tdx_release_vm_state_locks(struct kvm *kvm)
2787 {
2788 	mutex_unlock(&kvm->slots_lock);
2789 	kvm_unlock_all_vcpus(kvm);
2790 	mutex_unlock(&kvm->lock);
2791 }
2792 
2793 DEFINE_CLASS(tdx_vm_state_guard, tdx_vm_state_guard_t,
2794 	     if (!IS_ERR(_T)) tdx_release_vm_state_locks(_T),
2795 	     tdx_acquire_vm_state_locks(kvm), struct kvm *kvm);
2796 
tdx_td_init(struct kvm * kvm,struct kvm_tdx_cmd * cmd)2797 static int tdx_td_init(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
2798 {
2799 	struct kvm_tdx_init_vm __user *user_data = u64_to_user_ptr(cmd->data);
2800 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
2801 	struct kvm_tdx_init_vm *init_vm;
2802 	struct td_params *td_params = NULL;
2803 	u32 nr_user_entries;
2804 	int ret;
2805 
2806 	BUILD_BUG_ON(sizeof(*init_vm) != 256 + sizeof_field(struct kvm_tdx_init_vm, cpuid));
2807 	BUILD_BUG_ON(sizeof(struct td_params) != 1024);
2808 
2809 	if (kvm_tdx->state != TD_STATE_UNINITIALIZED)
2810 		return -EINVAL;
2811 
2812 	if (cmd->flags)
2813 		return -EINVAL;
2814 
2815 	if (get_user(nr_user_entries, &user_data->cpuid.nent))
2816 		return -EFAULT;
2817 
2818 	if (nr_user_entries > KVM_MAX_CPUID_ENTRIES)
2819 		return -E2BIG;
2820 
2821 	init_vm = memdup_user(user_data,
2822 			      struct_size(user_data, cpuid.entries, nr_user_entries));
2823 	if (IS_ERR(init_vm))
2824 		return PTR_ERR(init_vm);
2825 
2826 	if (memchr_inv(init_vm->reserved, 0, sizeof(init_vm->reserved))) {
2827 		ret = -EINVAL;
2828 		goto out;
2829 	}
2830 
2831 	/*
2832 	 * Reject the request if userspace changes cpuid.nent between the
2833 	 * initial read and the subsequent copy.
2834 	 */
2835 	if (init_vm->cpuid.padding || init_vm->cpuid.nent != nr_user_entries) {
2836 		ret = -EINVAL;
2837 		goto out;
2838 	}
2839 
2840 	td_params = kzalloc_obj(struct td_params);
2841 	if (!td_params) {
2842 		ret = -ENOMEM;
2843 		goto out;
2844 	}
2845 
2846 	ret = setup_tdparams(kvm, td_params, init_vm);
2847 	if (ret)
2848 		goto out;
2849 
2850 	ret = __tdx_td_init(kvm, td_params, &cmd->hw_error);
2851 	if (ret)
2852 		goto out;
2853 
2854 	kvm_tdx->tsc_offset = td_tdcs_exec_read64(kvm_tdx, TD_TDCS_EXEC_TSC_OFFSET);
2855 	kvm_tdx->tsc_multiplier = td_tdcs_exec_read64(kvm_tdx, TD_TDCS_EXEC_TSC_MULTIPLIER);
2856 	kvm_tdx->attributes = td_params->attributes;
2857 	kvm_tdx->xfam = td_params->xfam;
2858 
2859 	if (td_params->config_flags & TDX_CONFIG_FLAGS_MAX_GPAW)
2860 		kvm->arch.gfn_direct_bits = TDX_SHARED_BIT_PWL_5;
2861 	else
2862 		kvm->arch.gfn_direct_bits = TDX_SHARED_BIT_PWL_4;
2863 
2864 	kvm_tdx->state = TD_STATE_INITIALIZED;
2865 out:
2866 	/* kfree() accepts NULL. */
2867 	kfree(init_vm);
2868 	kfree(td_params);
2869 
2870 	return ret;
2871 }
2872 
tdx_flush_tlb_current(struct kvm_vcpu * vcpu)2873 void tdx_flush_tlb_current(struct kvm_vcpu *vcpu)
2874 {
2875 	/*
2876 	 * flush_tlb_current() is invoked when the first time for the vcpu to
2877 	 * run or when root of shared EPT is invalidated.
2878 	 * KVM only needs to flush shared EPT because the TDX module handles TLB
2879 	 * invalidation for private EPT in tdh_vp_enter();
2880 	 *
2881 	 * A single context invalidation for shared EPT can be performed here.
2882 	 * However, this single context invalidation requires the private EPTP
2883 	 * rather than the shared EPTP to flush shared EPT, as shared EPT uses
2884 	 * private EPTP as its ASID for TLB invalidation.
2885 	 *
2886 	 * To avoid reading back private EPTP, perform a global invalidation for
2887 	 * shared EPT instead to keep this function simple.
2888 	 */
2889 	ept_sync_global();
2890 }
2891 
tdx_flush_tlb_all(struct kvm_vcpu * vcpu)2892 void tdx_flush_tlb_all(struct kvm_vcpu *vcpu)
2893 {
2894 	/*
2895 	 * TDX has called tdx_track() in tdx_sept_remove_leaf_spte() to
2896 	 * ensure that private EPT will be flushed on the next TD enter. No need
2897 	 * to call tdx_track() here again even when this callback is a result of
2898 	 * zapping private EPT.
2899 	 *
2900 	 * Due to the lack of the context to determine which EPT has been
2901 	 * affected by zapping, invoke invept() directly here for both shared
2902 	 * EPT and private EPT for simplicity, though it's not necessary for
2903 	 * private EPT.
2904 	 */
2905 	ept_sync_global();
2906 }
2907 
tdx_td_finalize(struct kvm * kvm,struct kvm_tdx_cmd * cmd)2908 static int tdx_td_finalize(struct kvm *kvm, struct kvm_tdx_cmd *cmd)
2909 {
2910 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
2911 
2912 	if (!is_hkid_assigned(kvm_tdx) || kvm_tdx->state == TD_STATE_RUNNABLE)
2913 		return -EINVAL;
2914 
2915 	cmd->hw_error = tdh_mr_finalize(&kvm_tdx->td);
2916 	if (tdx_operand_busy(cmd->hw_error))
2917 		return -EBUSY;
2918 	if (TDX_BUG_ON(cmd->hw_error, TDH_MR_FINALIZE, kvm))
2919 		return -EIO;
2920 
2921 	kvm_tdx->state = TD_STATE_RUNNABLE;
2922 	/* TD_STATE_RUNNABLE must be set before 'pre_fault_allowed' */
2923 	smp_wmb();
2924 	kvm->arch.pre_fault_allowed = true;
2925 	return 0;
2926 }
2927 
tdx_get_cmd(void __user * argp,struct kvm_tdx_cmd * cmd)2928 static int tdx_get_cmd(void __user *argp, struct kvm_tdx_cmd *cmd)
2929 {
2930 	if (copy_from_user(cmd, argp, sizeof(*cmd)))
2931 		return -EFAULT;
2932 
2933 	/*
2934 	 * Userspace should never set hw_error.  KVM writes hw_error to report
2935 	 * hardware-defined error back to userspace.
2936 	 */
2937 	if (cmd->hw_error)
2938 		return -EINVAL;
2939 
2940 	return 0;
2941 }
2942 
tdx_vm_ioctl(struct kvm * kvm,void __user * argp)2943 int tdx_vm_ioctl(struct kvm *kvm, void __user *argp)
2944 {
2945 	struct kvm_tdx_cmd tdx_cmd;
2946 	int r;
2947 
2948 	r = tdx_get_cmd(argp, &tdx_cmd);
2949 	if (r)
2950 		return r;
2951 
2952 	if (tdx_cmd.id == KVM_TDX_CAPABILITIES)
2953 		return tdx_get_capabilities(&tdx_cmd);
2954 
2955 	CLASS(tdx_vm_state_guard, guard)(kvm);
2956 	if (IS_ERR(guard))
2957 		return PTR_ERR(guard);
2958 
2959 	switch (tdx_cmd.id) {
2960 	case KVM_TDX_INIT_VM:
2961 		r = tdx_td_init(kvm, &tdx_cmd);
2962 		break;
2963 	case KVM_TDX_FINALIZE_VM:
2964 		r = tdx_td_finalize(kvm, &tdx_cmd);
2965 		break;
2966 	default:
2967 		return -EINVAL;
2968 	}
2969 
2970 	if (copy_to_user(argp, &tdx_cmd, sizeof(struct kvm_tdx_cmd)))
2971 		return -EFAULT;
2972 
2973 	return r;
2974 }
2975 
2976 /* VMM can pass one 64bit auxiliary data to vcpu via RCX for guest BIOS. */
tdx_td_vcpu_init(struct kvm_vcpu * vcpu,u64 vcpu_rcx)2977 static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
2978 {
2979 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
2980 	struct vcpu_tdx *tdx = to_tdx(vcpu);
2981 	struct page *page;
2982 	int ret, i;
2983 	u64 err;
2984 
2985 	page = tdx_alloc_control_page();
2986 	if (!page)
2987 		return -ENOMEM;
2988 	tdx->vp.tdvpr_page = page;
2989 
2990 	/*
2991 	 * page_to_phys() does not work in 'noinstr' code, like guest
2992 	 * entry via tdh_vp_enter(). Precalculate and store it instead
2993 	 * of doing it at runtime later.
2994 	 */
2995 	tdx->vp.tdvpr_pa = page_to_phys(tdx->vp.tdvpr_page);
2996 
2997 	tdx->vp.tdcx_pages = kcalloc(kvm_tdx->td.tdcx_nr_pages, sizeof(*tdx->vp.tdcx_pages),
2998 				     GFP_KERNEL_ACCOUNT);
2999 	if (!tdx->vp.tdcx_pages) {
3000 		ret = -ENOMEM;
3001 		goto free_tdvpr;
3002 	}
3003 
3004 	for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
3005 		page = tdx_alloc_control_page();
3006 		if (!page) {
3007 			ret = -ENOMEM;
3008 			goto free_tdcx;
3009 		}
3010 		tdx->vp.tdcx_pages[i] = page;
3011 	}
3012 
3013 	err = tdh_vp_create(&kvm_tdx->td, &tdx->vp);
3014 	if (TDX_BUG_ON(err, TDH_VP_CREATE, vcpu->kvm)) {
3015 		ret = -EIO;
3016 		goto free_tdcx;
3017 	}
3018 
3019 	for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
3020 		err = tdh_vp_addcx(&tdx->vp, tdx->vp.tdcx_pages[i]);
3021 		if (TDX_BUG_ON(err, TDH_VP_ADDCX, vcpu->kvm)) {
3022 			/*
3023 			 * Pages already added are reclaimed by the vcpu_free
3024 			 * method, but the rest are freed here.
3025 			 */
3026 			for (; i < kvm_tdx->td.tdcx_nr_pages; i++) {
3027 				tdx_free_control_page(tdx->vp.tdcx_pages[i]);
3028 				tdx->vp.tdcx_pages[i] = NULL;
3029 			}
3030 			return -EIO;
3031 		}
3032 	}
3033 
3034 	/*
3035 	 * tdh_vp_init() can take an exclusive lock of the TDR resource inside
3036 	 * the TDX-Module.  The TDR resource is also taken as shared in several
3037 	 * no-fail MMU paths, which could return TDX_OPERAND_BUSY on contention
3038 	 * (TDX-Module locks are try-lock implementations with no slow path).
3039 	 * Take mmu_lock for write to reflect the nature of the lock taken by
3040 	 * the TDX-Module, and to ensure the no-fail MMU paths succeed, e.g. if
3041 	 * a concurrent PUNCH_HOLE on guest_memfd triggers removal of SPTEs.
3042 	 */
3043 	scoped_guard(write_lock, &vcpu->kvm->mmu_lock) {
3044 		err = tdh_vp_init(&tdx->vp, vcpu_rcx, vcpu->vcpu_id);
3045 		if (TDX_BUG_ON(err, TDH_VP_INIT, vcpu->kvm))
3046 			return -EIO;
3047 	}
3048 
3049 	vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3050 
3051 	return 0;
3052 
3053 free_tdcx:
3054 	for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
3055 		tdx_free_control_page(tdx->vp.tdcx_pages[i]);
3056 		tdx->vp.tdcx_pages[i] = NULL;
3057 	}
3058 	kfree(tdx->vp.tdcx_pages);
3059 	tdx->vp.tdcx_pages = NULL;
3060 
3061 free_tdvpr:
3062 	tdx_free_control_page(tdx->vp.tdvpr_page);
3063 	tdx->vp.tdvpr_page = NULL;
3064 	tdx->vp.tdvpr_pa = 0;
3065 
3066 	return ret;
3067 }
3068 
3069 /* Sometimes reads multipple subleafs. Return how many enties were written. */
tdx_vcpu_get_cpuid_leaf(struct kvm_vcpu * vcpu,u32 leaf,int * entry_index,struct kvm_cpuid_entry2 * output_e)3070 static int tdx_vcpu_get_cpuid_leaf(struct kvm_vcpu *vcpu, u32 leaf, int *entry_index,
3071 				   struct kvm_cpuid_entry2 *output_e)
3072 {
3073 	int sub_leaf = 0;
3074 	int ret;
3075 
3076 	/* First try without a subleaf */
3077 	ret = tdx_read_cpuid(vcpu, leaf, 0, false, entry_index, output_e);
3078 
3079 	/* If success, or invalid leaf, just give up */
3080 	if (ret != -EIO)
3081 		return ret;
3082 
3083 	/*
3084 	 * If the try without a subleaf failed, try reading subleafs until
3085 	 * failure. The TDX module only supports 6 bits of subleaf index.
3086 	 */
3087 	while (1) {
3088 		/* Keep reading subleafs until there is a failure. */
3089 		if (tdx_read_cpuid(vcpu, leaf, sub_leaf, true, entry_index, output_e))
3090 			return !sub_leaf;
3091 
3092 		sub_leaf++;
3093 		output_e++;
3094 	}
3095 
3096 	return 0;
3097 }
3098 
tdx_vcpu_get_cpuid(struct kvm_vcpu * vcpu,struct kvm_tdx_cmd * cmd)3099 static int tdx_vcpu_get_cpuid(struct kvm_vcpu *vcpu, struct kvm_tdx_cmd *cmd)
3100 {
3101 	struct kvm_cpuid2 __user *output;
3102 	struct kvm_cpuid2 *td_cpuid;
3103 	int r = 0, i = 0, leaf;
3104 	u32 level;
3105 
3106 	output = u64_to_user_ptr(cmd->data);
3107 	td_cpuid = kzalloc(sizeof(*td_cpuid) +
3108 			sizeof(output->entries[0]) * KVM_MAX_CPUID_ENTRIES,
3109 			GFP_KERNEL);
3110 	if (!td_cpuid)
3111 		return -ENOMEM;
3112 
3113 	if (copy_from_user(td_cpuid, output, sizeof(*output))) {
3114 		r = -EFAULT;
3115 		goto out;
3116 	}
3117 
3118 	/* Read max CPUID for normal range */
3119 	if (tdx_vcpu_get_cpuid_leaf(vcpu, 0, &i, &td_cpuid->entries[i])) {
3120 		r = -EIO;
3121 		goto out;
3122 	}
3123 	level = td_cpuid->entries[0].eax;
3124 
3125 	for (leaf = 1; leaf <= level; leaf++)
3126 		tdx_vcpu_get_cpuid_leaf(vcpu, leaf, &i, &td_cpuid->entries[i]);
3127 
3128 	/* Read max CPUID for extended range */
3129 	if (tdx_vcpu_get_cpuid_leaf(vcpu, 0x80000000, &i, &td_cpuid->entries[i])) {
3130 		r = -EIO;
3131 		goto out;
3132 	}
3133 	level = td_cpuid->entries[i - 1].eax;
3134 
3135 	for (leaf = 0x80000001; leaf <= level; leaf++)
3136 		tdx_vcpu_get_cpuid_leaf(vcpu, leaf, &i, &td_cpuid->entries[i]);
3137 
3138 	if (td_cpuid->nent < i)
3139 		r = -E2BIG;
3140 	td_cpuid->nent = i;
3141 
3142 	if (copy_to_user(output, td_cpuid, sizeof(*output))) {
3143 		r = -EFAULT;
3144 		goto out;
3145 	}
3146 
3147 	if (r == -E2BIG)
3148 		goto out;
3149 
3150 	if (copy_to_user(output->entries, td_cpuid->entries,
3151 			 td_cpuid->nent * sizeof(struct kvm_cpuid_entry2)))
3152 		r = -EFAULT;
3153 
3154 out:
3155 	kfree(td_cpuid);
3156 
3157 	return r;
3158 }
3159 
tdx_vcpu_init(struct kvm_vcpu * vcpu,struct kvm_tdx_cmd * cmd)3160 static int tdx_vcpu_init(struct kvm_vcpu *vcpu, struct kvm_tdx_cmd *cmd)
3161 {
3162 	u64 apic_base;
3163 	struct vcpu_tdx *tdx = to_tdx(vcpu);
3164 	int ret;
3165 
3166 	if (cmd->flags)
3167 		return -EINVAL;
3168 
3169 	if (tdx->state != VCPU_TD_STATE_UNINITIALIZED)
3170 		return -EINVAL;
3171 
3172 	/*
3173 	 * TDX requires X2APIC, userspace is responsible for configuring guest
3174 	 * CPUID accordingly.
3175 	 */
3176 	apic_base = APIC_DEFAULT_PHYS_BASE | LAPIC_MODE_X2APIC |
3177 		(kvm_vcpu_is_reset_bsp(vcpu) ? MSR_IA32_APICBASE_BSP : 0);
3178 	if (kvm_apic_set_base(vcpu, apic_base, true))
3179 		return -EINVAL;
3180 
3181 	ret = tdx_td_vcpu_init(vcpu, (u64)cmd->data);
3182 	if (ret)
3183 		return ret;
3184 
3185 	td_vmcs_write16(tdx, POSTED_INTR_NV, POSTED_INTR_VECTOR);
3186 	td_vmcs_write64(tdx, POSTED_INTR_DESC_ADDR, __pa(&tdx->vt.pi_desc));
3187 	td_vmcs_setbit32(tdx, PIN_BASED_VM_EXEC_CONTROL, PIN_BASED_POSTED_INTR);
3188 
3189 	tdx->state = VCPU_TD_STATE_INITIALIZED;
3190 
3191 	return 0;
3192 }
3193 
tdx_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)3194 void tdx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
3195 {
3196 	/*
3197 	 * Yell on INIT, as TDX doesn't support INIT, i.e. KVM should drop all
3198 	 * INIT events.
3199 	 *
3200 	 * Defer initializing vCPU for RESET state until KVM_TDX_INIT_VCPU, as
3201 	 * userspace needs to define the vCPU model before KVM can initialize
3202 	 * vCPU state, e.g. to enable x2APIC.
3203 	 */
3204 	WARN_ON_ONCE(init_event);
3205 }
3206 
3207 struct tdx_gmem_post_populate_arg {
3208 	struct kvm_vcpu *vcpu;
3209 	__u32 flags;
3210 };
3211 
tdx_gmem_post_populate(struct kvm * kvm,gfn_t gfn,kvm_pfn_t pfn,struct page * src_page,void * _arg)3212 static int tdx_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
3213 				  struct page *src_page, void *_arg)
3214 {
3215 	struct tdx_gmem_post_populate_arg *arg = _arg;
3216 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
3217 	u64 err, entry, level_state;
3218 	gpa_t gpa = gfn_to_gpa(gfn);
3219 	int ret, i;
3220 
3221 	if (KVM_BUG_ON(kvm_tdx->page_add_src, kvm))
3222 		return -EIO;
3223 
3224 	kvm_tdx->page_add_src = src_page;
3225 	ret = kvm_tdp_mmu_map_private_pfn(arg->vcpu, gfn, pfn);
3226 	kvm_tdx->page_add_src = NULL;
3227 
3228 	if (ret || !(arg->flags & KVM_TDX_MEASURE_MEMORY_REGION))
3229 		return ret;
3230 
3231 	/*
3232 	 * Note, MR.EXTEND can fail if the S-EPT mapping is somehow removed
3233 	 * between mapping the pfn and now, but slots_lock prevents memslot
3234 	 * updates, filemap_invalidate_lock() prevents guest_memfd updates,
3235 	 * mmu_notifier events can't reach S-EPT entries, and KVM's internal
3236 	 * zapping flows are mutually exclusive with S-EPT mappings.
3237 	 */
3238 	for (i = 0; i < PAGE_SIZE; i += TDX_EXTENDMR_CHUNKSIZE) {
3239 		err = tdh_mr_extend(&kvm_tdx->td, gpa + i, &entry, &level_state);
3240 		if (TDX_BUG_ON_2(err, TDH_MR_EXTEND, entry, level_state, kvm))
3241 			return -EIO;
3242 	}
3243 
3244 	return 0;
3245 }
3246 
tdx_vcpu_init_mem_region(struct kvm_vcpu * vcpu,struct kvm_tdx_cmd * cmd)3247 static int tdx_vcpu_init_mem_region(struct kvm_vcpu *vcpu, struct kvm_tdx_cmd *cmd)
3248 {
3249 	struct vcpu_tdx *tdx = to_tdx(vcpu);
3250 	struct kvm *kvm = vcpu->kvm;
3251 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
3252 	struct kvm_tdx_init_mem_region region;
3253 	struct tdx_gmem_post_populate_arg arg;
3254 	long gmem_ret;
3255 	int ret;
3256 
3257 	if (tdx->state != VCPU_TD_STATE_INITIALIZED)
3258 		return -EINVAL;
3259 
3260 	/* Once TD is finalized, the initial guest memory is fixed. */
3261 	if (kvm_tdx->state == TD_STATE_RUNNABLE)
3262 		return -EINVAL;
3263 
3264 	if (cmd->flags & ~KVM_TDX_MEASURE_MEMORY_REGION)
3265 		return -EINVAL;
3266 
3267 	if (copy_from_user(&region, u64_to_user_ptr(cmd->data), sizeof(region)))
3268 		return -EFAULT;
3269 
3270 	if (!PAGE_ALIGNED(region.source_addr) || !region.source_addr ||
3271 	    !PAGE_ALIGNED(region.gpa) || !region.nr_pages ||
3272 	    region.gpa + (region.nr_pages << PAGE_SHIFT) <= region.gpa ||
3273 	    !vt_is_tdx_private_gpa(kvm, region.gpa) ||
3274 	    !vt_is_tdx_private_gpa(kvm, region.gpa + (region.nr_pages << PAGE_SHIFT) - 1))
3275 		return -EINVAL;
3276 
3277 	ret = 0;
3278 	while (region.nr_pages) {
3279 		if (signal_pending(current)) {
3280 			ret = -EINTR;
3281 			break;
3282 		}
3283 
3284 		arg = (struct tdx_gmem_post_populate_arg) {
3285 			.vcpu = vcpu,
3286 			.flags = cmd->flags,
3287 		};
3288 		gmem_ret = kvm_gmem_populate(kvm, gpa_to_gfn(region.gpa),
3289 					     u64_to_user_ptr(region.source_addr),
3290 					     1, false, tdx_gmem_post_populate, &arg);
3291 		if (gmem_ret < 0) {
3292 			ret = gmem_ret;
3293 			break;
3294 		}
3295 
3296 		if (gmem_ret != 1) {
3297 			ret = -EIO;
3298 			break;
3299 		}
3300 
3301 		region.source_addr += PAGE_SIZE;
3302 		region.gpa += PAGE_SIZE;
3303 		region.nr_pages--;
3304 
3305 		cond_resched();
3306 	}
3307 
3308 	if (copy_to_user(u64_to_user_ptr(cmd->data), &region, sizeof(region)))
3309 		ret = -EFAULT;
3310 	return ret;
3311 }
3312 
tdx_vcpu_unlocked_ioctl(struct kvm_vcpu * vcpu,void __user * argp)3313 int tdx_vcpu_unlocked_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
3314 {
3315 	struct kvm *kvm = vcpu->kvm;
3316 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
3317 	struct kvm_tdx_cmd cmd;
3318 	int r;
3319 
3320 	r = tdx_get_cmd(argp, &cmd);
3321 	if (r)
3322 		return r;
3323 
3324 	CLASS(tdx_vm_state_guard, guard)(kvm);
3325 	if (IS_ERR(guard))
3326 		return PTR_ERR(guard);
3327 
3328 	if (!is_hkid_assigned(kvm_tdx) || kvm_tdx->state == TD_STATE_RUNNABLE)
3329 		return -EINVAL;
3330 
3331 	vcpu_load(vcpu);
3332 
3333 	switch (cmd.id) {
3334 	case KVM_TDX_INIT_MEM_REGION:
3335 		r = tdx_vcpu_init_mem_region(vcpu, &cmd);
3336 		break;
3337 	case KVM_TDX_INIT_VCPU:
3338 		r = tdx_vcpu_init(vcpu, &cmd);
3339 		break;
3340 	default:
3341 		r = -ENOIOCTLCMD;
3342 		break;
3343 	}
3344 
3345 	vcpu_put(vcpu);
3346 
3347 	return r;
3348 }
3349 
tdx_vcpu_ioctl(struct kvm_vcpu * vcpu,void __user * argp)3350 int tdx_vcpu_ioctl(struct kvm_vcpu *vcpu, void __user *argp)
3351 {
3352 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(vcpu->kvm);
3353 	struct kvm_tdx_cmd cmd;
3354 	int ret;
3355 
3356 	if (!is_hkid_assigned(kvm_tdx) || kvm_tdx->state == TD_STATE_RUNNABLE)
3357 		return -EINVAL;
3358 
3359 	ret = tdx_get_cmd(argp, &cmd);
3360 	if (ret)
3361 		return ret;
3362 
3363 	switch (cmd.id) {
3364 	case KVM_TDX_GET_CPUID:
3365 		ret = tdx_vcpu_get_cpuid(vcpu, &cmd);
3366 		break;
3367 	default:
3368 		ret = -EINVAL;
3369 		break;
3370 	}
3371 
3372 	return ret;
3373 }
3374 
tdx_gmem_max_mapping_level(struct kvm * kvm,kvm_pfn_t pfn,bool is_private)3375 int tdx_gmem_max_mapping_level(struct kvm *kvm, kvm_pfn_t pfn, bool is_private)
3376 {
3377 	if (!is_private)
3378 		return 0;
3379 
3380 	return PG_LEVEL_4K;
3381 }
3382 
tdx_hardware_unsetup(void)3383 void tdx_hardware_unsetup(void)
3384 {
3385 	misc_cg_set_capacity(MISC_CG_RES_TDX, 0);
3386 }
3387 
__tdx_hardware_setup(void)3388 static int __init __tdx_hardware_setup(void)
3389 {
3390 	const struct tdx_sys_info_td_conf *td_conf;
3391 	int i;
3392 
3393 	for (i = 0; i < ARRAY_SIZE(tdx_uret_msrs); i++) {
3394 		/*
3395 		 * Check if MSRs (tdx_uret_msrs) can be saved/restored
3396 		 * before returning to user space.
3397 		 */
3398 		tdx_uret_msrs[i].slot = kvm_find_user_return_msr(tdx_uret_msrs[i].msr);
3399 		if (tdx_uret_msrs[i].slot == -1) {
3400 			/* If any MSR isn't supported, it is a KVM bug */
3401 			pr_err("MSR %x isn't included by kvm_find_user_return_msr\n",
3402 				tdx_uret_msrs[i].msr);
3403 			return -EIO;
3404 		}
3405 	}
3406 
3407 	/* Get TDX global information for later use */
3408 	tdx_sysinfo = tdx_get_sysinfo();
3409 	if (!tdx_sysinfo)
3410 		return -ENODEV;
3411 
3412 	/* Check TDX module and KVM capabilities */
3413 	if (!tdx_get_supported_attrs(&tdx_sysinfo->td_conf) ||
3414 	    !tdx_get_supported_xfam(&tdx_sysinfo->td_conf))
3415 		return -EINVAL;
3416 
3417 	if (!(tdx_sysinfo->features.tdx_features0 & MD_FIELD_ID_FEATURES0_TOPOLOGY_ENUM))
3418 		return -EINVAL;
3419 
3420 	/*
3421 	 * TDX has its own limit of maximum vCPUs it can support for all
3422 	 * TDX guests in addition to KVM_MAX_VCPUS.  Userspace needs to
3423 	 * query TDX guest's maximum vCPUs by checking KVM_CAP_MAX_VCPU
3424 	 * extension on per-VM basis.
3425 	 *
3426 	 * TDX module reports such limit via the MAX_VCPU_PER_TD global
3427 	 * metadata.  Different modules may report different values.
3428 	 * Some old module may also not support this metadata (in which
3429 	 * case this limit is U16_MAX).
3430 	 *
3431 	 * In practice, the reported value reflects the maximum logical
3432 	 * CPUs that ALL the platforms that the module supports can
3433 	 * possibly have.
3434 	 *
3435 	 * Simply forwarding the MAX_VCPU_PER_TD to userspace could
3436 	 * result in an unpredictable ABI.  KVM instead always advertise
3437 	 * the number of logical CPUs the platform has as the maximum
3438 	 * vCPUs for TDX guests.
3439 	 *
3440 	 * Make sure MAX_VCPU_PER_TD reported by TDX module is not
3441 	 * smaller than the number of logical CPUs, otherwise KVM will
3442 	 * report an unsupported value to userspace.
3443 	 *
3444 	 * Note, a platform with TDX enabled in the BIOS cannot support
3445 	 * physical CPU hotplug, and TDX requires the BIOS has marked
3446 	 * all logical CPUs in MADT table as enabled.  Just use
3447 	 * num_present_cpus() for the number of logical CPUs.
3448 	 */
3449 	td_conf = &tdx_sysinfo->td_conf;
3450 	if (td_conf->max_vcpus_per_td < num_present_cpus()) {
3451 		pr_err("Disable TDX: MAX_VCPU_PER_TD (%u) smaller than number of logical CPUs (%u).\n",
3452 				td_conf->max_vcpus_per_td, num_present_cpus());
3453 		return -EINVAL;
3454 	}
3455 
3456 	if (misc_cg_set_capacity(MISC_CG_RES_TDX, tdx_get_nr_guest_keyids()))
3457 		return -EINVAL;
3458 
3459 	return 0;
3460 }
3461 
tdx_hardware_setup(void)3462 int __init tdx_hardware_setup(void)
3463 {
3464 	int r, i;
3465 
3466 	/* tdx_disable_virtualization_cpu() uses associated_tdvcpus. */
3467 	for_each_possible_cpu(i)
3468 		INIT_LIST_HEAD(&per_cpu(associated_tdvcpus, i));
3469 
3470 	if (!enable_tdx)
3471 		return 0;
3472 
3473 	if (!enable_ept) {
3474 		pr_err("EPT is required for TDX\n");
3475 		goto success_disable_tdx;
3476 	}
3477 
3478 	if (!tdp_mmu_enabled || !enable_mmio_caching || !enable_ept_ad_bits) {
3479 		pr_err("TDP MMU and MMIO caching and EPT A/D bit is required for TDX\n");
3480 		goto success_disable_tdx;
3481 	}
3482 
3483 	if (!enable_apicv) {
3484 		pr_err("APICv is required for TDX\n");
3485 		goto success_disable_tdx;
3486 	}
3487 
3488 	if (!cpu_feature_enabled(X86_FEATURE_OSXSAVE)) {
3489 		pr_err("tdx: OSXSAVE is required for TDX\n");
3490 		goto success_disable_tdx;
3491 	}
3492 
3493 	if (!cpu_feature_enabled(X86_FEATURE_TDX_HOST_PLATFORM)) {
3494 		pr_err("TDX not supported by the host platform\n");
3495 		goto success_disable_tdx;
3496 	}
3497 
3498 	r = __tdx_hardware_setup();
3499 	if (r) {
3500 		/*
3501 		 * Disable TDX only but don't fail to load module if the TDX
3502 		 * module could not be loaded.  No need to print message saying
3503 		 * "module is not loaded" because it was printed when the first
3504 		 * SEAMCALL failed.  Don't bother unwinding the S-EPT hooks or
3505 		 * vm_size, as kvm_x86_ops have already been finalized (and are
3506 		 * intentionally not exported).  The S-EPT code is unreachable,
3507 		 * and allocating a few more bytes per VM in a should-be-rare
3508 		 * failure scenario is a non-issue.
3509 		 */
3510 		if (r == -ENODEV)
3511 			goto success_disable_tdx;
3512 
3513 		return r;
3514 	}
3515 
3516 	KVM_SANITY_CHECK_VM_STRUCT_SIZE(kvm_tdx);
3517 
3518 	vt_x86_ops.vm_size = max_t(unsigned int, vt_x86_ops.vm_size, sizeof(struct kvm_tdx));
3519 
3520 	vt_x86_ops.set_external_spte = tdx_sept_set_private_spte;
3521 	vt_x86_ops.free_external_spt = tdx_sept_free_private_spt;
3522 
3523 	if (tdx_supports_dynamic_pamt(tdx_sysinfo))
3524 		vt_x86_ops.topup_external_cache = tdx_topup_external_pamt_cache;
3525 
3526 	vt_x86_ops.protected_apic_has_interrupt = tdx_protected_apic_has_interrupt;
3527 	return 0;
3528 
3529 success_disable_tdx:
3530 	enable_tdx = 0;
3531 	return 0;
3532 }
3533