1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) 2021-2022 Intel Corporation */
5 #define pr_fmt(fmt) "tdx: " fmt
7 #include <linux/cpufeature.h>
13 #include <asm/insn-eval.h>
14 #include <asm/pgtable.h>
16 /* TDX module Call Leaf IDs */
17 #define TDX_GET_INFO 1
18 #define TDX_GET_VEINFO 3
19 #define TDX_ACCEPT_PAGE 6
21 /* TDX hypercall Leaf IDs */
22 #define TDVMCALL_MAP_GPA 0x10001
28 /* Port I/O direction */
32 /* See Exit Qualification for I/O Instructions in VMX documentation */
33 #define VE_IS_IO_IN(e) ((e) & BIT(3))
34 #define VE_GET_IO_SIZE(e) (((e) & GENMASK(2, 0)) + 1)
35 #define VE_GET_PORT_NUM(e) ((e) >> 16)
36 #define VE_IS_IO_STRING(e) ((e) & BIT(4))
38 #define ATTR_SEPT_VE_DISABLE BIT(28)
41 * Wrapper for standard use of __tdx_hypercall with no output aside from
44 static inline u64 _tdx_hypercall(u64 fn, u64 r12, u64 r13, u64 r14, u64 r15)
46 struct tdx_hypercall_args args = {
47 .r10 = TDX_HYPERCALL_STANDARD,
55 return __tdx_hypercall(&args, 0);
58 /* Called from __tdx_hypercall() for unrecoverable failure */
59 void __tdx_hypercall_failed(void)
61 panic("TDVMCALL failed. TDX module bug?");
65 * The TDG.VP.VMCALL-Instruction-execution sub-functions are defined
66 * independently from but are currently matched 1:1 with VMX EXIT_REASONs.
67 * Reusing the KVM EXIT_REASON macros makes it easier to connect the host and
68 * guest sides of these calls.
70 static u64 hcall_func(u64 exit_reason)
75 #ifdef CONFIG_KVM_GUEST
76 long tdx_kvm_hypercall(unsigned int nr, unsigned long p1, unsigned long p2,
77 unsigned long p3, unsigned long p4)
79 struct tdx_hypercall_args args = {
87 return __tdx_hypercall(&args, 0);
89 EXPORT_SYMBOL_GPL(tdx_kvm_hypercall);
93 * Used for TDX guests to make calls directly to the TD module. This
94 * should only be used for calls that have no legitimate reason to fail
95 * or where the kernel can not survive the call failing.
97 static inline void tdx_module_call(u64 fn, u64 rcx, u64 rdx, u64 r8, u64 r9,
98 struct tdx_module_output *out)
100 if (__tdx_module_call(fn, rcx, rdx, r8, r9, out))
101 panic("TDCALL %lld failed (Buggy TDX module!)\n", fn);
104 static void tdx_parse_tdinfo(u64 *cc_mask)
106 struct tdx_module_output out;
107 unsigned int gpa_width;
111 * TDINFO TDX module call is used to get the TD execution environment
112 * information like GPA width, number of available vcpus, debug mode
113 * information, etc. More details about the ABI can be found in TDX
114 * Guest-Host-Communication Interface (GHCI), section 2.4.2 TDCALL
117 tdx_module_call(TDX_GET_INFO, 0, 0, 0, 0, &out);
120 * The highest bit of a guest physical address is the "sharing" bit.
121 * Set it for shared pages and clear it for private pages.
123 * The GPA width that comes out of this call is critical. TDX guests
124 * can not meaningfully run without it.
126 gpa_width = out.rcx & GENMASK(5, 0);
127 *cc_mask = BIT_ULL(gpa_width - 1);
130 * The kernel can not handle #VE's when accessing normal kernel
131 * memory. Ensure that no #VE will be delivered for accesses to
132 * TD-private memory. Only VMM-shared memory (MMIO) will #VE.
135 if (!(td_attr & ATTR_SEPT_VE_DISABLE))
136 panic("TD misconfiguration: SEPT_VE_DISABLE attibute must be set.\n");
140 * The TDX module spec states that #VE may be injected for a limited set of
143 * - Emulation of the architectural #VE injection on EPT violation;
145 * - As a result of guest TD execution of a disallowed instruction,
146 * a disallowed MSR access, or CPUID virtualization;
148 * - A notification to the guest TD about anomalous behavior;
150 * The last one is opt-in and is not used by the kernel.
152 * The Intel Software Developer's Manual describes cases when instruction
153 * length field can be used in section "Information for VM Exits Due to
154 * Instruction Execution".
156 * For TDX, it ultimately means GET_VEINFO provides reliable instruction length
157 * information if #VE occurred due to instruction execution, but not for EPT
160 static int ve_instr_len(struct ve_info *ve)
162 switch (ve->exit_reason) {
163 case EXIT_REASON_HLT:
164 case EXIT_REASON_MSR_READ:
165 case EXIT_REASON_MSR_WRITE:
166 case EXIT_REASON_CPUID:
167 case EXIT_REASON_IO_INSTRUCTION:
168 /* It is safe to use ve->instr_len for #VE due instructions */
169 return ve->instr_len;
170 case EXIT_REASON_EPT_VIOLATION:
172 * For EPT violations, ve->insn_len is not defined. For those,
173 * the kernel must decode instructions manually and should not
174 * be using this function.
176 WARN_ONCE(1, "ve->instr_len is not defined for EPT violations");
179 WARN_ONCE(1, "Unexpected #VE-type: %lld\n", ve->exit_reason);
180 return ve->instr_len;
184 static u64 __cpuidle __halt(const bool irq_disabled, const bool do_sti)
186 struct tdx_hypercall_args args = {
187 .r10 = TDX_HYPERCALL_STANDARD,
188 .r11 = hcall_func(EXIT_REASON_HLT),
193 * Emulate HLT operation via hypercall. More info about ABI
194 * can be found in TDX Guest-Host-Communication Interface
195 * (GHCI), section 3.8 TDG.VP.VMCALL<Instruction.HLT>.
197 * The VMM uses the "IRQ disabled" param to understand IRQ
198 * enabled status (RFLAGS.IF) of the TD guest and to determine
199 * whether or not it should schedule the halted vCPU if an
200 * IRQ becomes pending. E.g. if IRQs are disabled, the VMM
201 * can keep the vCPU in virtual HLT, even if an IRQ is
202 * pending, without hanging/breaking the guest.
204 return __tdx_hypercall(&args, do_sti ? TDX_HCALL_ISSUE_STI : 0);
207 static int handle_halt(struct ve_info *ve)
210 * Since non safe halt is mainly used in CPU offlining
211 * and the guest will always stay in the halt state, don't
212 * call the STI instruction (set do_sti as false).
214 const bool irq_disabled = irqs_disabled();
215 const bool do_sti = false;
217 if (__halt(irq_disabled, do_sti))
220 return ve_instr_len(ve);
223 void __cpuidle tdx_safe_halt(void)
226 * For do_sti=true case, __tdx_hypercall() function enables
227 * interrupts using the STI instruction before the TDCALL. So
228 * set irq_disabled as false.
230 const bool irq_disabled = false;
231 const bool do_sti = true;
234 * Use WARN_ONCE() to report the failure.
236 if (__halt(irq_disabled, do_sti))
237 WARN_ONCE(1, "HLT instruction emulation failed\n");
240 static int read_msr(struct pt_regs *regs, struct ve_info *ve)
242 struct tdx_hypercall_args args = {
243 .r10 = TDX_HYPERCALL_STANDARD,
244 .r11 = hcall_func(EXIT_REASON_MSR_READ),
249 * Emulate the MSR read via hypercall. More info about ABI
250 * can be found in TDX Guest-Host-Communication Interface
251 * (GHCI), section titled "TDG.VP.VMCALL<Instruction.RDMSR>".
253 if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
256 regs->ax = lower_32_bits(args.r11);
257 regs->dx = upper_32_bits(args.r11);
258 return ve_instr_len(ve);
261 static int write_msr(struct pt_regs *regs, struct ve_info *ve)
263 struct tdx_hypercall_args args = {
264 .r10 = TDX_HYPERCALL_STANDARD,
265 .r11 = hcall_func(EXIT_REASON_MSR_WRITE),
267 .r13 = (u64)regs->dx << 32 | regs->ax,
271 * Emulate the MSR write via hypercall. More info about ABI
272 * can be found in TDX Guest-Host-Communication Interface
273 * (GHCI) section titled "TDG.VP.VMCALL<Instruction.WRMSR>".
275 if (__tdx_hypercall(&args, 0))
278 return ve_instr_len(ve);
281 static int handle_cpuid(struct pt_regs *regs, struct ve_info *ve)
283 struct tdx_hypercall_args args = {
284 .r10 = TDX_HYPERCALL_STANDARD,
285 .r11 = hcall_func(EXIT_REASON_CPUID),
291 * Only allow VMM to control range reserved for hypervisor
294 * Return all-zeros for any CPUID outside the range. It matches CPU
295 * behaviour for non-supported leaf.
297 if (regs->ax < 0x40000000 || regs->ax > 0x4FFFFFFF) {
298 regs->ax = regs->bx = regs->cx = regs->dx = 0;
299 return ve_instr_len(ve);
303 * Emulate the CPUID instruction via a hypercall. More info about
304 * ABI can be found in TDX Guest-Host-Communication Interface
305 * (GHCI), section titled "VP.VMCALL<Instruction.CPUID>".
307 if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
311 * As per TDX GHCI CPUID ABI, r12-r15 registers contain contents of
312 * EAX, EBX, ECX, EDX registers after the CPUID instruction execution.
313 * So copy the register contents back to pt_regs.
320 return ve_instr_len(ve);
323 static bool mmio_read(int size, unsigned long addr, unsigned long *val)
325 struct tdx_hypercall_args args = {
326 .r10 = TDX_HYPERCALL_STANDARD,
327 .r11 = hcall_func(EXIT_REASON_EPT_VIOLATION),
334 if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
340 static bool mmio_write(int size, unsigned long addr, unsigned long val)
342 return !_tdx_hypercall(hcall_func(EXIT_REASON_EPT_VIOLATION), size,
343 EPT_WRITE, addr, val);
346 static int handle_mmio(struct pt_regs *regs, struct ve_info *ve)
348 unsigned long *reg, val, vaddr;
349 char buffer[MAX_INSN_SIZE];
350 struct insn insn = {};
352 int size, extend_size;
355 /* Only in-kernel MMIO is supported */
356 if (WARN_ON_ONCE(user_mode(regs)))
359 if (copy_from_kernel_nofault(buffer, (void *)regs->ip, MAX_INSN_SIZE))
362 if (insn_decode(&insn, buffer, MAX_INSN_SIZE, INSN_MODE_64))
365 mmio = insn_decode_mmio(&insn, &size);
366 if (WARN_ON_ONCE(mmio == MMIO_DECODE_FAILED))
369 if (mmio != MMIO_WRITE_IMM && mmio != MMIO_MOVS) {
370 reg = insn_get_modrm_reg_ptr(&insn, regs);
376 * Reject EPT violation #VEs that split pages.
378 * MMIO accesses are supposed to be naturally aligned and therefore
379 * never cross page boundaries. Seeing split page accesses indicates
380 * a bug or a load_unaligned_zeropad() that stepped into an MMIO page.
382 * load_unaligned_zeropad() will recover using exception fixups.
384 vaddr = (unsigned long)insn_get_addr_ref(&insn, regs);
385 if (vaddr / PAGE_SIZE != (vaddr + size - 1) / PAGE_SIZE)
388 /* Handle writes first */
391 memcpy(&val, reg, size);
392 if (!mmio_write(size, ve->gpa, val))
396 val = insn.immediate.value;
397 if (!mmio_write(size, ve->gpa, val))
401 case MMIO_READ_ZERO_EXTEND:
402 case MMIO_READ_SIGN_EXTEND:
403 /* Reads are handled below */
406 case MMIO_DECODE_FAILED:
408 * MMIO was accessed with an instruction that could not be
409 * decoded or handled properly. It was likely not using io.h
410 * helpers or accessed MMIO accidentally.
414 WARN_ONCE(1, "Unknown insn_decode_mmio() decode value?");
419 if (!mmio_read(size, ve->gpa, &val))
424 /* Zero-extend for 32-bit operation */
425 extend_size = size == 4 ? sizeof(*reg) : 0;
427 case MMIO_READ_ZERO_EXTEND:
428 /* Zero extend based on operand size */
429 extend_size = insn.opnd_bytes;
431 case MMIO_READ_SIGN_EXTEND:
432 /* Sign extend based on operand size */
433 extend_size = insn.opnd_bytes;
434 if (size == 1 && val & BIT(7))
436 else if (size > 1 && val & BIT(15))
440 /* All other cases has to be covered with the first switch() */
446 memset(reg, extend_val, extend_size);
447 memcpy(reg, &val, size);
451 static bool handle_in(struct pt_regs *regs, int size, int port)
453 struct tdx_hypercall_args args = {
454 .r10 = TDX_HYPERCALL_STANDARD,
455 .r11 = hcall_func(EXIT_REASON_IO_INSTRUCTION),
460 u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
464 * Emulate the I/O read via hypercall. More info about ABI can be found
465 * in TDX Guest-Host-Communication Interface (GHCI) section titled
466 * "TDG.VP.VMCALL<Instruction.IO>".
468 success = !__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT);
470 /* Update part of the register affected by the emulated instruction */
473 regs->ax |= args.r11 & mask;
478 static bool handle_out(struct pt_regs *regs, int size, int port)
480 u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
483 * Emulate the I/O write via hypercall. More info about ABI can be found
484 * in TDX Guest-Host-Communication Interface (GHCI) section titled
485 * "TDG.VP.VMCALL<Instruction.IO>".
487 return !_tdx_hypercall(hcall_func(EXIT_REASON_IO_INSTRUCTION), size,
488 PORT_WRITE, port, regs->ax & mask);
492 * Emulate I/O using hypercall.
494 * Assumes the IO instruction was using ax, which is enforced
495 * by the standard io.h macros.
497 * Return True on success or False on failure.
499 static int handle_io(struct pt_regs *regs, struct ve_info *ve)
501 u32 exit_qual = ve->exit_qual;
505 if (VE_IS_IO_STRING(exit_qual))
508 in = VE_IS_IO_IN(exit_qual);
509 size = VE_GET_IO_SIZE(exit_qual);
510 port = VE_GET_PORT_NUM(exit_qual);
514 ret = handle_in(regs, size, port);
516 ret = handle_out(regs, size, port);
520 return ve_instr_len(ve);
524 * Early #VE exception handler. Only handles a subset of port I/O.
525 * Intended only for earlyprintk. If failed, return false.
527 __init bool tdx_early_handle_ve(struct pt_regs *regs)
532 tdx_get_ve_info(&ve);
534 if (ve.exit_reason != EXIT_REASON_IO_INSTRUCTION)
537 insn_len = handle_io(regs, &ve);
541 regs->ip += insn_len;
545 void tdx_get_ve_info(struct ve_info *ve)
547 struct tdx_module_output out;
550 * Called during #VE handling to retrieve the #VE info from the
553 * This has to be called early in #VE handling. A "nested" #VE which
554 * occurs before this will raise a #DF and is not recoverable.
556 * The call retrieves the #VE info from the TDX module, which also
557 * clears the "#VE valid" flag. This must be done before anything else
558 * because any #VE that occurs while the valid flag is set will lead to
561 * Note, the TDX module treats virtual NMIs as inhibited if the #VE
562 * valid flag is set. It means that NMI=>#VE will not result in a #DF.
564 tdx_module_call(TDX_GET_VEINFO, 0, 0, 0, 0, &out);
566 /* Transfer the output parameters */
567 ve->exit_reason = out.rcx;
568 ve->exit_qual = out.rdx;
571 ve->instr_len = lower_32_bits(out.r10);
572 ve->instr_info = upper_32_bits(out.r10);
576 * Handle the user initiated #VE.
578 * On success, returns the number of bytes RIP should be incremented (>=0)
579 * or -errno on error.
581 static int virt_exception_user(struct pt_regs *regs, struct ve_info *ve)
583 switch (ve->exit_reason) {
584 case EXIT_REASON_CPUID:
585 return handle_cpuid(regs, ve);
587 pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
593 * Handle the kernel #VE.
595 * On success, returns the number of bytes RIP should be incremented (>=0)
596 * or -errno on error.
598 static int virt_exception_kernel(struct pt_regs *regs, struct ve_info *ve)
600 switch (ve->exit_reason) {
601 case EXIT_REASON_HLT:
602 return handle_halt(ve);
603 case EXIT_REASON_MSR_READ:
604 return read_msr(regs, ve);
605 case EXIT_REASON_MSR_WRITE:
606 return write_msr(regs, ve);
607 case EXIT_REASON_CPUID:
608 return handle_cpuid(regs, ve);
609 case EXIT_REASON_EPT_VIOLATION:
610 return handle_mmio(regs, ve);
611 case EXIT_REASON_IO_INSTRUCTION:
612 return handle_io(regs, ve);
614 pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
619 bool tdx_handle_virt_exception(struct pt_regs *regs, struct ve_info *ve)
624 insn_len = virt_exception_user(regs, ve);
626 insn_len = virt_exception_kernel(regs, ve);
630 /* After successful #VE handling, move the IP */
631 regs->ip += insn_len;
636 static bool tdx_tlb_flush_required(bool private)
639 * TDX guest is responsible for flushing TLB on private->shared
640 * transition. VMM is responsible for flushing on shared->private.
642 * The VMM _can't_ flush private addresses as it can't generate PAs
643 * with the guest's HKID. Shared memory isn't subject to integrity
644 * checking, i.e. the VMM doesn't need to flush for its own protection.
646 * There's no need to flush when converting from shared to private,
647 * as flushing is the VMM's responsibility in this case, e.g. it must
648 * flush to avoid integrity failures in the face of a buggy or
654 static bool tdx_cache_flush_required(void)
657 * AMD SME/SEV can avoid cache flushing if HW enforces cache coherence.
658 * TDX doesn't have such capability.
660 * Flush cache unconditionally.
665 static bool try_accept_one(phys_addr_t *start, unsigned long len,
666 enum pg_level pg_level)
668 unsigned long accept_size = page_level_size(pg_level);
672 if (!IS_ALIGNED(*start, accept_size))
675 if (len < accept_size)
679 * Pass the page physical address to the TDX module to accept the
680 * pending, private page.
682 * Bits 2:0 of RCX encode page size: 0 - 4K, 1 - 2M, 2 - 1G.
698 tdcall_rcx = *start | page_size;
699 if (__tdx_module_call(TDX_ACCEPT_PAGE, tdcall_rcx, 0, 0, 0, NULL))
702 *start += accept_size;
707 * Inform the VMM of the guest's intent for this physical page: shared with
708 * the VMM or private to the guest. The VMM is expected to change its mapping
709 * of the page in response.
711 static bool tdx_enc_status_changed(unsigned long vaddr, int numpages, bool enc)
713 phys_addr_t start = __pa(vaddr);
714 phys_addr_t end = __pa(vaddr + numpages * PAGE_SIZE);
717 /* Set the shared (decrypted) bits: */
718 start |= cc_mkdec(0);
723 * Notify the VMM about page mapping conversion. More info about ABI
724 * can be found in TDX Guest-Host-Communication Interface (GHCI),
725 * section "TDG.VP.VMCALL<MapGPA>"
727 if (_tdx_hypercall(TDVMCALL_MAP_GPA, start, end - start, 0, 0))
730 /* private->shared conversion requires only MapGPA call */
735 * For shared->private conversion, accept the page using
736 * TDX_ACCEPT_PAGE TDX module call.
738 while (start < end) {
739 unsigned long len = end - start;
742 * Try larger accepts first. It gives chance to VMM to keep
743 * 1G/2M SEPT entries where possible and speeds up process by
744 * cutting number of hypercalls (if successful).
747 if (try_accept_one(&start, len, PG_LEVEL_1G))
750 if (try_accept_one(&start, len, PG_LEVEL_2M))
753 if (!try_accept_one(&start, len, PG_LEVEL_4K))
760 static bool tdx_enc_status_change_prepare(unsigned long vaddr, int numpages,
764 * Only handle shared->private conversion here.
765 * See the comment in tdx_early_init().
768 return tdx_enc_status_changed(vaddr, numpages, enc);
772 static bool tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
776 * Only handle private->shared conversion here.
777 * See the comment in tdx_early_init().
780 return tdx_enc_status_changed(vaddr, numpages, enc);
784 void __init tdx_early_init(void)
789 cpuid_count(TDX_CPUID_LEAF_ID, 0, &eax, &sig[0], &sig[2], &sig[1]);
791 if (memcmp(TDX_IDENT, sig, sizeof(sig)))
794 setup_force_cpu_cap(X86_FEATURE_TDX_GUEST);
796 cc_vendor = CC_VENDOR_INTEL;
797 tdx_parse_tdinfo(&cc_mask);
798 cc_set_mask(cc_mask);
801 * All bits above GPA width are reserved and kernel treats shared bit
802 * as flag, not as part of physical address.
804 * Adjust physical mask to only cover valid GPA bits.
806 physical_mask &= cc_mask - 1;
809 * The kernel mapping should match the TDX metadata for the page.
810 * load_unaligned_zeropad() can touch memory *adjacent* to that which is
811 * owned by the caller and can catch even _momentary_ mismatches. Bad
812 * things happen on mismatch:
814 * - Private mapping => Shared Page == Guest shutdown
815 * - Shared mapping => Private Page == Recoverable #VE
817 * guest.enc_status_change_prepare() converts the page from
818 * shared=>private before the mapping becomes private.
820 * guest.enc_status_change_finish() converts the page from
821 * private=>shared after the mapping becomes private.
823 * In both cases there is a temporary shared mapping to a private page,
824 * which can result in a #VE. But, there is never a private mapping to
827 x86_platform.guest.enc_status_change_prepare = tdx_enc_status_change_prepare;
828 x86_platform.guest.enc_status_change_finish = tdx_enc_status_change_finish;
830 x86_platform.guest.enc_cache_flush_required = tdx_cache_flush_required;
831 x86_platform.guest.enc_tlb_flush_required = tdx_tlb_flush_required;
833 pr_info("Guest detected\n");