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