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