1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) 2021-2022 Intel Corporation */
3 
4 #undef pr_fmt
5 #define pr_fmt(fmt)     "tdx: " fmt
6 
7 #include <linux/cpufeature.h>
8 #include <linux/export.h>
9 #include <linux/io.h>
10 #include <linux/kexec.h>
11 #include <asm/coco.h>
12 #include <asm/tdx.h>
13 #include <asm/vmx.h>
14 #include <asm/ia32.h>
15 #include <asm/insn.h>
16 #include <asm/insn-eval.h>
17 #include <asm/paravirt_types.h>
18 #include <asm/pgtable.h>
19 #include <asm/set_memory.h>
20 #include <asm/traps.h>
21 
22 /* MMIO direction */
23 #define EPT_READ	0
24 #define EPT_WRITE	1
25 
26 /* Port I/O direction */
27 #define PORT_READ	0
28 #define PORT_WRITE	1
29 
30 /* See Exit Qualification for I/O Instructions in VMX documentation */
31 #define VE_IS_IO_IN(e)		((e) & BIT(3))
32 #define VE_GET_IO_SIZE(e)	(((e) & GENMASK(2, 0)) + 1)
33 #define VE_GET_PORT_NUM(e)	((e) >> 16)
34 #define VE_IS_IO_STRING(e)	((e) & BIT(4))
35 
36 /* TDX Module call error codes */
37 #define TDCALL_RETURN_CODE(a)	((a) >> 32)
38 #define TDCALL_INVALID_OPERAND	0xc0000100
39 
40 #define TDREPORT_SUBTYPE_0	0
41 
42 static atomic_long_t nr_shared;
43 
44 /* Called from __tdx_hypercall() for unrecoverable failure */
__tdx_hypercall_failed(void)45 noinstr void __noreturn __tdx_hypercall_failed(void)
46 {
47 	instrumentation_begin();
48 	panic("TDVMCALL failed. TDX module bug?");
49 }
50 
51 #ifdef CONFIG_KVM_GUEST
tdx_kvm_hypercall(unsigned int nr,unsigned long p1,unsigned long p2,unsigned long p3,unsigned long p4)52 long tdx_kvm_hypercall(unsigned int nr, unsigned long p1, unsigned long p2,
53 		       unsigned long p3, unsigned long p4)
54 {
55 	struct tdx_module_args args = {
56 		.r10 = nr,
57 		.r11 = p1,
58 		.r12 = p2,
59 		.r13 = p3,
60 		.r14 = p4,
61 	};
62 
63 	return __tdx_hypercall(&args);
64 }
65 EXPORT_SYMBOL_GPL(tdx_kvm_hypercall);
66 #endif
67 
68 /*
69  * Used for TDX guests to make calls directly to the TD module.  This
70  * should only be used for calls that have no legitimate reason to fail
71  * or where the kernel can not survive the call failing.
72  */
tdcall(u64 fn,struct tdx_module_args * args)73 static inline void tdcall(u64 fn, struct tdx_module_args *args)
74 {
75 	if (__tdcall_ret(fn, args))
76 		panic("TDCALL %lld failed (Buggy TDX module!)\n", fn);
77 }
78 
79 /* Read TD-scoped metadata */
tdg_vm_rd(u64 field,u64 * value)80 static inline u64 tdg_vm_rd(u64 field, u64 *value)
81 {
82 	struct tdx_module_args args = {
83 		.rdx = field,
84 	};
85 	u64 ret;
86 
87 	ret = __tdcall_ret(TDG_VM_RD, &args);
88 	*value = args.r8;
89 
90 	return ret;
91 }
92 
93 /* Write TD-scoped metadata */
tdg_vm_wr(u64 field,u64 value,u64 mask)94 static inline u64 tdg_vm_wr(u64 field, u64 value, u64 mask)
95 {
96 	struct tdx_module_args args = {
97 		.rdx = field,
98 		.r8 = value,
99 		.r9 = mask,
100 	};
101 
102 	return __tdcall(TDG_VM_WR, &args);
103 }
104 
105 /**
106  * tdx_mcall_get_report0() - Wrapper to get TDREPORT0 (a.k.a. TDREPORT
107  *                           subtype 0) using TDG.MR.REPORT TDCALL.
108  * @reportdata: Address of the input buffer which contains user-defined
109  *              REPORTDATA to be included into TDREPORT.
110  * @tdreport: Address of the output buffer to store TDREPORT.
111  *
112  * Refer to section titled "TDG.MR.REPORT leaf" in the TDX Module
113  * v1.0 specification for more information on TDG.MR.REPORT TDCALL.
114  * It is used in the TDX guest driver module to get the TDREPORT0.
115  *
116  * Return 0 on success, -EINVAL for invalid operands, or -EIO on
117  * other TDCALL failures.
118  */
tdx_mcall_get_report0(u8 * reportdata,u8 * tdreport)119 int tdx_mcall_get_report0(u8 *reportdata, u8 *tdreport)
120 {
121 	struct tdx_module_args args = {
122 		.rcx = virt_to_phys(tdreport),
123 		.rdx = virt_to_phys(reportdata),
124 		.r8 = TDREPORT_SUBTYPE_0,
125 	};
126 	u64 ret;
127 
128 	ret = __tdcall(TDG_MR_REPORT, &args);
129 	if (ret) {
130 		if (TDCALL_RETURN_CODE(ret) == TDCALL_INVALID_OPERAND)
131 			return -EINVAL;
132 		return -EIO;
133 	}
134 
135 	return 0;
136 }
137 EXPORT_SYMBOL_GPL(tdx_mcall_get_report0);
138 
139 /**
140  * tdx_hcall_get_quote() - Wrapper to request TD Quote using GetQuote
141  *                         hypercall.
142  * @buf: Address of the directly mapped shared kernel buffer which
143  *       contains TDREPORT. The same buffer will be used by VMM to
144  *       store the generated TD Quote output.
145  * @size: size of the tdquote buffer (4KB-aligned).
146  *
147  * Refer to section titled "TDG.VP.VMCALL<GetQuote>" in the TDX GHCI
148  * v1.0 specification for more information on GetQuote hypercall.
149  * It is used in the TDX guest driver module to get the TD Quote.
150  *
151  * Return 0 on success or error code on failure.
152  */
tdx_hcall_get_quote(u8 * buf,size_t size)153 u64 tdx_hcall_get_quote(u8 *buf, size_t size)
154 {
155 	/* Since buf is a shared memory, set the shared (decrypted) bits */
156 	return _tdx_hypercall(TDVMCALL_GET_QUOTE, cc_mkdec(virt_to_phys(buf)), size, 0, 0);
157 }
158 EXPORT_SYMBOL_GPL(tdx_hcall_get_quote);
159 
tdx_panic(const char * msg)160 static void __noreturn tdx_panic(const char *msg)
161 {
162 	struct tdx_module_args args = {
163 		.r10 = TDX_HYPERCALL_STANDARD,
164 		.r11 = TDVMCALL_REPORT_FATAL_ERROR,
165 		.r12 = 0, /* Error code: 0 is Panic */
166 	};
167 	union {
168 		/* Define register order according to the GHCI */
169 		struct { u64 r14, r15, rbx, rdi, rsi, r8, r9, rdx; };
170 
171 		char str[64];
172 	} message;
173 
174 	/* VMM assumes '\0' in byte 65, if the message took all 64 bytes */
175 	strtomem_pad(message.str, msg, '\0');
176 
177 	args.r8  = message.r8;
178 	args.r9  = message.r9;
179 	args.r14 = message.r14;
180 	args.r15 = message.r15;
181 	args.rdi = message.rdi;
182 	args.rsi = message.rsi;
183 	args.rbx = message.rbx;
184 	args.rdx = message.rdx;
185 
186 	/*
187 	 * This hypercall should never return and it is not safe
188 	 * to keep the guest running. Call it forever if it
189 	 * happens to return.
190 	 */
191 	while (1)
192 		__tdx_hypercall(&args);
193 }
194 
195 /*
196  * The kernel cannot handle #VEs when accessing normal kernel memory. Ensure
197  * that no #VE will be delivered for accesses to TD-private memory.
198  *
199  * TDX 1.0 does not allow the guest to disable SEPT #VE on its own. The VMM
200  * controls if the guest will receive such #VE with TD attribute
201  * TDX_ATTR_SEPT_VE_DISABLE.
202  *
203  * Newer TDX modules allow the guest to control if it wants to receive SEPT
204  * violation #VEs.
205  *
206  * Check if the feature is available and disable SEPT #VE if possible.
207  *
208  * If the TD is allowed to disable/enable SEPT #VEs, the TDX_ATTR_SEPT_VE_DISABLE
209  * attribute is no longer reliable. It reflects the initial state of the
210  * control for the TD, but it will not be updated if someone (e.g. bootloader)
211  * changes it before the kernel starts. Kernel must check TDCS_TD_CTLS bit to
212  * determine if SEPT #VEs are enabled or disabled.
213  */
disable_sept_ve(u64 td_attr)214 static void disable_sept_ve(u64 td_attr)
215 {
216 	const char *msg = "TD misconfiguration: SEPT #VE has to be disabled";
217 	bool debug = td_attr & TDX_ATTR_DEBUG;
218 	u64 config, controls;
219 
220 	/* Is this TD allowed to disable SEPT #VE */
221 	tdg_vm_rd(TDCS_CONFIG_FLAGS, &config);
222 	if (!(config & TDCS_CONFIG_FLEXIBLE_PENDING_VE)) {
223 		/* No SEPT #VE controls for the guest: check the attribute */
224 		if (td_attr & TDX_ATTR_SEPT_VE_DISABLE)
225 			return;
226 
227 		/* Relax SEPT_VE_DISABLE check for debug TD for backtraces */
228 		if (debug)
229 			pr_warn("%s\n", msg);
230 		else
231 			tdx_panic(msg);
232 		return;
233 	}
234 
235 	/* Check if SEPT #VE has been disabled before us */
236 	tdg_vm_rd(TDCS_TD_CTLS, &controls);
237 	if (controls & TD_CTLS_PENDING_VE_DISABLE)
238 		return;
239 
240 	/* Keep #VEs enabled for splats in debugging environments */
241 	if (debug)
242 		return;
243 
244 	/* Disable SEPT #VEs */
245 	tdg_vm_wr(TDCS_TD_CTLS, TD_CTLS_PENDING_VE_DISABLE,
246 		  TD_CTLS_PENDING_VE_DISABLE);
247 }
248 
249 /*
250  * TDX 1.0 generates a #VE when accessing topology-related CPUID leafs (0xB and
251  * 0x1F) and the X2APIC_APICID MSR. The kernel returns all zeros on CPUID #VEs.
252  * In practice, this means that the kernel can only boot with a plain topology.
253  * Any complications will cause problems.
254  *
255  * The ENUM_TOPOLOGY feature allows the VMM to provide topology information.
256  * Enabling the feature  eliminates topology-related #VEs: the TDX module
257  * virtualizes accesses to the CPUID leafs and the MSR.
258  *
259  * Enable ENUM_TOPOLOGY if it is available.
260  */
enable_cpu_topology_enumeration(void)261 static void enable_cpu_topology_enumeration(void)
262 {
263 	u64 configured;
264 
265 	/* Has the VMM provided a valid topology configuration? */
266 	tdg_vm_rd(TDCS_TOPOLOGY_ENUM_CONFIGURED, &configured);
267 	if (!configured) {
268 		pr_err("VMM did not configure X2APIC_IDs properly\n");
269 		return;
270 	}
271 
272 	tdg_vm_wr(TDCS_TD_CTLS, TD_CTLS_ENUM_TOPOLOGY, TD_CTLS_ENUM_TOPOLOGY);
273 }
274 
reduce_unnecessary_ve(void)275 static void reduce_unnecessary_ve(void)
276 {
277 	u64 err = tdg_vm_wr(TDCS_TD_CTLS, TD_CTLS_REDUCE_VE, TD_CTLS_REDUCE_VE);
278 
279 	if (err == TDX_SUCCESS)
280 		return;
281 
282 	/*
283 	 * Enabling REDUCE_VE includes ENUM_TOPOLOGY. Only try to
284 	 * enable ENUM_TOPOLOGY if REDUCE_VE was not successful.
285 	 */
286 	enable_cpu_topology_enumeration();
287 }
288 
tdx_setup(u64 * cc_mask)289 static void tdx_setup(u64 *cc_mask)
290 {
291 	struct tdx_module_args args = {};
292 	unsigned int gpa_width;
293 	u64 td_attr;
294 
295 	/*
296 	 * TDINFO TDX module call is used to get the TD execution environment
297 	 * information like GPA width, number of available vcpus, debug mode
298 	 * information, etc. More details about the ABI can be found in TDX
299 	 * Guest-Host-Communication Interface (GHCI), section 2.4.2 TDCALL
300 	 * [TDG.VP.INFO].
301 	 */
302 	tdcall(TDG_VP_INFO, &args);
303 
304 	/*
305 	 * The highest bit of a guest physical address is the "sharing" bit.
306 	 * Set it for shared pages and clear it for private pages.
307 	 *
308 	 * The GPA width that comes out of this call is critical. TDX guests
309 	 * can not meaningfully run without it.
310 	 */
311 	gpa_width = args.rcx & GENMASK(5, 0);
312 	*cc_mask = BIT_ULL(gpa_width - 1);
313 
314 	td_attr = args.rdx;
315 
316 	/* Kernel does not use NOTIFY_ENABLES and does not need random #VEs */
317 	tdg_vm_wr(TDCS_NOTIFY_ENABLES, 0, -1ULL);
318 
319 	disable_sept_ve(td_attr);
320 
321 	reduce_unnecessary_ve();
322 }
323 
324 /*
325  * The TDX module spec states that #VE may be injected for a limited set of
326  * reasons:
327  *
328  *  - Emulation of the architectural #VE injection on EPT violation;
329  *
330  *  - As a result of guest TD execution of a disallowed instruction,
331  *    a disallowed MSR access, or CPUID virtualization;
332  *
333  *  - A notification to the guest TD about anomalous behavior;
334  *
335  * The last one is opt-in and is not used by the kernel.
336  *
337  * The Intel Software Developer's Manual describes cases when instruction
338  * length field can be used in section "Information for VM Exits Due to
339  * Instruction Execution".
340  *
341  * For TDX, it ultimately means GET_VEINFO provides reliable instruction length
342  * information if #VE occurred due to instruction execution, but not for EPT
343  * violations.
344  */
ve_instr_len(struct ve_info * ve)345 static int ve_instr_len(struct ve_info *ve)
346 {
347 	switch (ve->exit_reason) {
348 	case EXIT_REASON_HLT:
349 	case EXIT_REASON_MSR_READ:
350 	case EXIT_REASON_MSR_WRITE:
351 	case EXIT_REASON_CPUID:
352 	case EXIT_REASON_IO_INSTRUCTION:
353 		/* It is safe to use ve->instr_len for #VE due instructions */
354 		return ve->instr_len;
355 	case EXIT_REASON_EPT_VIOLATION:
356 		/*
357 		 * For EPT violations, ve->insn_len is not defined. For those,
358 		 * the kernel must decode instructions manually and should not
359 		 * be using this function.
360 		 */
361 		WARN_ONCE(1, "ve->instr_len is not defined for EPT violations");
362 		return 0;
363 	default:
364 		WARN_ONCE(1, "Unexpected #VE-type: %lld\n", ve->exit_reason);
365 		return ve->instr_len;
366 	}
367 }
368 
__halt(const bool irq_disabled)369 static u64 __cpuidle __halt(const bool irq_disabled)
370 {
371 	struct tdx_module_args args = {
372 		.r10 = TDX_HYPERCALL_STANDARD,
373 		.r11 = hcall_func(EXIT_REASON_HLT),
374 		.r12 = irq_disabled,
375 	};
376 
377 	/*
378 	 * Emulate HLT operation via hypercall. More info about ABI
379 	 * can be found in TDX Guest-Host-Communication Interface
380 	 * (GHCI), section 3.8 TDG.VP.VMCALL<Instruction.HLT>.
381 	 *
382 	 * The VMM uses the "IRQ disabled" param to understand IRQ
383 	 * enabled status (RFLAGS.IF) of the TD guest and to determine
384 	 * whether or not it should schedule the halted vCPU if an
385 	 * IRQ becomes pending. E.g. if IRQs are disabled, the VMM
386 	 * can keep the vCPU in virtual HLT, even if an IRQ is
387 	 * pending, without hanging/breaking the guest.
388 	 */
389 	return __tdx_hypercall(&args);
390 }
391 
handle_halt(struct ve_info * ve)392 static int handle_halt(struct ve_info *ve)
393 {
394 	const bool irq_disabled = irqs_disabled();
395 
396 	if (__halt(irq_disabled))
397 		return -EIO;
398 
399 	return ve_instr_len(ve);
400 }
401 
tdx_halt(void)402 void __cpuidle tdx_halt(void)
403 {
404 	const bool irq_disabled = false;
405 
406 	/*
407 	 * Use WARN_ONCE() to report the failure.
408 	 */
409 	if (__halt(irq_disabled))
410 		WARN_ONCE(1, "HLT instruction emulation failed\n");
411 }
412 
tdx_safe_halt(void)413 static void __cpuidle tdx_safe_halt(void)
414 {
415 	tdx_halt();
416 	/*
417 	 * "__cpuidle" section doesn't support instrumentation, so stick
418 	 * with raw_* variant that avoids tracing hooks.
419 	 */
420 	raw_local_irq_enable();
421 }
422 
read_msr(struct pt_regs * regs,struct ve_info * ve)423 static int read_msr(struct pt_regs *regs, struct ve_info *ve)
424 {
425 	struct tdx_module_args args = {
426 		.r10 = TDX_HYPERCALL_STANDARD,
427 		.r11 = hcall_func(EXIT_REASON_MSR_READ),
428 		.r12 = regs->cx,
429 	};
430 
431 	/*
432 	 * Emulate the MSR read via hypercall. More info about ABI
433 	 * can be found in TDX Guest-Host-Communication Interface
434 	 * (GHCI), section titled "TDG.VP.VMCALL<Instruction.RDMSR>".
435 	 */
436 	if (__tdx_hypercall(&args))
437 		return -EIO;
438 
439 	regs->ax = lower_32_bits(args.r11);
440 	regs->dx = upper_32_bits(args.r11);
441 	return ve_instr_len(ve);
442 }
443 
write_msr(struct pt_regs * regs,struct ve_info * ve)444 static int write_msr(struct pt_regs *regs, struct ve_info *ve)
445 {
446 	struct tdx_module_args args = {
447 		.r10 = TDX_HYPERCALL_STANDARD,
448 		.r11 = hcall_func(EXIT_REASON_MSR_WRITE),
449 		.r12 = regs->cx,
450 		.r13 = (u64)regs->dx << 32 | regs->ax,
451 	};
452 
453 	/*
454 	 * Emulate the MSR write via hypercall. More info about ABI
455 	 * can be found in TDX Guest-Host-Communication Interface
456 	 * (GHCI) section titled "TDG.VP.VMCALL<Instruction.WRMSR>".
457 	 */
458 	if (__tdx_hypercall(&args))
459 		return -EIO;
460 
461 	return ve_instr_len(ve);
462 }
463 
handle_cpuid(struct pt_regs * regs,struct ve_info * ve)464 static int handle_cpuid(struct pt_regs *regs, struct ve_info *ve)
465 {
466 	struct tdx_module_args args = {
467 		.r10 = TDX_HYPERCALL_STANDARD,
468 		.r11 = hcall_func(EXIT_REASON_CPUID),
469 		.r12 = regs->ax,
470 		.r13 = regs->cx,
471 	};
472 
473 	/*
474 	 * Only allow VMM to control range reserved for hypervisor
475 	 * communication.
476 	 *
477 	 * Return all-zeros for any CPUID outside the range. It matches CPU
478 	 * behaviour for non-supported leaf.
479 	 */
480 	if (regs->ax < 0x40000000 || regs->ax > 0x4FFFFFFF) {
481 		regs->ax = regs->bx = regs->cx = regs->dx = 0;
482 		return ve_instr_len(ve);
483 	}
484 
485 	/*
486 	 * Emulate the CPUID instruction via a hypercall. More info about
487 	 * ABI can be found in TDX Guest-Host-Communication Interface
488 	 * (GHCI), section titled "VP.VMCALL<Instruction.CPUID>".
489 	 */
490 	if (__tdx_hypercall(&args))
491 		return -EIO;
492 
493 	/*
494 	 * As per TDX GHCI CPUID ABI, r12-r15 registers contain contents of
495 	 * EAX, EBX, ECX, EDX registers after the CPUID instruction execution.
496 	 * So copy the register contents back to pt_regs.
497 	 */
498 	regs->ax = args.r12;
499 	regs->bx = args.r13;
500 	regs->cx = args.r14;
501 	regs->dx = args.r15;
502 
503 	return ve_instr_len(ve);
504 }
505 
mmio_read(int size,unsigned long addr,unsigned long * val)506 static bool mmio_read(int size, unsigned long addr, unsigned long *val)
507 {
508 	struct tdx_module_args args = {
509 		.r10 = TDX_HYPERCALL_STANDARD,
510 		.r11 = hcall_func(EXIT_REASON_EPT_VIOLATION),
511 		.r12 = size,
512 		.r13 = EPT_READ,
513 		.r14 = addr,
514 	};
515 
516 	if (__tdx_hypercall(&args))
517 		return false;
518 
519 	*val = args.r11;
520 	return true;
521 }
522 
mmio_write(int size,unsigned long addr,unsigned long val)523 static bool mmio_write(int size, unsigned long addr, unsigned long val)
524 {
525 	return !_tdx_hypercall(hcall_func(EXIT_REASON_EPT_VIOLATION), size,
526 			       EPT_WRITE, addr, val);
527 }
528 
handle_mmio(struct pt_regs * regs,struct ve_info * ve)529 static int handle_mmio(struct pt_regs *regs, struct ve_info *ve)
530 {
531 	unsigned long *reg, val, vaddr;
532 	char buffer[MAX_INSN_SIZE];
533 	enum insn_mmio_type mmio;
534 	struct insn insn = {};
535 	int size, extend_size;
536 	u8 extend_val = 0;
537 
538 	/* Only in-kernel MMIO is supported */
539 	if (WARN_ON_ONCE(user_mode(regs)))
540 		return -EFAULT;
541 
542 	if (copy_from_kernel_nofault(buffer, (void *)regs->ip, MAX_INSN_SIZE))
543 		return -EFAULT;
544 
545 	if (insn_decode(&insn, buffer, MAX_INSN_SIZE, INSN_MODE_64))
546 		return -EINVAL;
547 
548 	mmio = insn_decode_mmio(&insn, &size);
549 	if (WARN_ON_ONCE(mmio == INSN_MMIO_DECODE_FAILED))
550 		return -EINVAL;
551 
552 	if (mmio != INSN_MMIO_WRITE_IMM && mmio != INSN_MMIO_MOVS) {
553 		reg = insn_get_modrm_reg_ptr(&insn, regs);
554 		if (!reg)
555 			return -EINVAL;
556 	}
557 
558 	if (!fault_in_kernel_space(ve->gla)) {
559 		WARN_ONCE(1, "Access to userspace address is not supported");
560 		return -EINVAL;
561 	}
562 
563 	/*
564 	 * Reject EPT violation #VEs that split pages.
565 	 *
566 	 * MMIO accesses are supposed to be naturally aligned and therefore
567 	 * never cross page boundaries. Seeing split page accesses indicates
568 	 * a bug or a load_unaligned_zeropad() that stepped into an MMIO page.
569 	 *
570 	 * load_unaligned_zeropad() will recover using exception fixups.
571 	 */
572 	vaddr = (unsigned long)insn_get_addr_ref(&insn, regs);
573 	if (vaddr / PAGE_SIZE != (vaddr + size - 1) / PAGE_SIZE)
574 		return -EFAULT;
575 
576 	/* Handle writes first */
577 	switch (mmio) {
578 	case INSN_MMIO_WRITE:
579 		memcpy(&val, reg, size);
580 		if (!mmio_write(size, ve->gpa, val))
581 			return -EIO;
582 		return insn.length;
583 	case INSN_MMIO_WRITE_IMM:
584 		val = insn.immediate.value;
585 		if (!mmio_write(size, ve->gpa, val))
586 			return -EIO;
587 		return insn.length;
588 	case INSN_MMIO_READ:
589 	case INSN_MMIO_READ_ZERO_EXTEND:
590 	case INSN_MMIO_READ_SIGN_EXTEND:
591 		/* Reads are handled below */
592 		break;
593 	case INSN_MMIO_MOVS:
594 	case INSN_MMIO_DECODE_FAILED:
595 		/*
596 		 * MMIO was accessed with an instruction that could not be
597 		 * decoded or handled properly. It was likely not using io.h
598 		 * helpers or accessed MMIO accidentally.
599 		 */
600 		return -EINVAL;
601 	default:
602 		WARN_ONCE(1, "Unknown insn_decode_mmio() decode value?");
603 		return -EINVAL;
604 	}
605 
606 	/* Handle reads */
607 	if (!mmio_read(size, ve->gpa, &val))
608 		return -EIO;
609 
610 	switch (mmio) {
611 	case INSN_MMIO_READ:
612 		/* Zero-extend for 32-bit operation */
613 		extend_size = size == 4 ? sizeof(*reg) : 0;
614 		break;
615 	case INSN_MMIO_READ_ZERO_EXTEND:
616 		/* Zero extend based on operand size */
617 		extend_size = insn.opnd_bytes;
618 		break;
619 	case INSN_MMIO_READ_SIGN_EXTEND:
620 		/* Sign extend based on operand size */
621 		extend_size = insn.opnd_bytes;
622 		if (size == 1 && val & BIT(7))
623 			extend_val = 0xFF;
624 		else if (size > 1 && val & BIT(15))
625 			extend_val = 0xFF;
626 		break;
627 	default:
628 		/* All other cases has to be covered with the first switch() */
629 		WARN_ON_ONCE(1);
630 		return -EINVAL;
631 	}
632 
633 	if (extend_size)
634 		memset(reg, extend_val, extend_size);
635 	memcpy(reg, &val, size);
636 	return insn.length;
637 }
638 
handle_in(struct pt_regs * regs,int size,int port)639 static bool handle_in(struct pt_regs *regs, int size, int port)
640 {
641 	struct tdx_module_args args = {
642 		.r10 = TDX_HYPERCALL_STANDARD,
643 		.r11 = hcall_func(EXIT_REASON_IO_INSTRUCTION),
644 		.r12 = size,
645 		.r13 = PORT_READ,
646 		.r14 = port,
647 	};
648 	u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
649 	bool success;
650 
651 	/*
652 	 * Emulate the I/O read via hypercall. More info about ABI can be found
653 	 * in TDX Guest-Host-Communication Interface (GHCI) section titled
654 	 * "TDG.VP.VMCALL<Instruction.IO>".
655 	 */
656 	success = !__tdx_hypercall(&args);
657 
658 	/* Update part of the register affected by the emulated instruction */
659 	regs->ax &= ~mask;
660 	if (success)
661 		regs->ax |= args.r11 & mask;
662 
663 	return success;
664 }
665 
handle_out(struct pt_regs * regs,int size,int port)666 static bool handle_out(struct pt_regs *regs, int size, int port)
667 {
668 	u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
669 
670 	/*
671 	 * Emulate the I/O write via hypercall. More info about ABI can be found
672 	 * in TDX Guest-Host-Communication Interface (GHCI) section titled
673 	 * "TDG.VP.VMCALL<Instruction.IO>".
674 	 */
675 	return !_tdx_hypercall(hcall_func(EXIT_REASON_IO_INSTRUCTION), size,
676 			       PORT_WRITE, port, regs->ax & mask);
677 }
678 
679 /*
680  * Emulate I/O using hypercall.
681  *
682  * Assumes the IO instruction was using ax, which is enforced
683  * by the standard io.h macros.
684  *
685  * Return True on success or False on failure.
686  */
handle_io(struct pt_regs * regs,struct ve_info * ve)687 static int handle_io(struct pt_regs *regs, struct ve_info *ve)
688 {
689 	u32 exit_qual = ve->exit_qual;
690 	int size, port;
691 	bool in, ret;
692 
693 	if (VE_IS_IO_STRING(exit_qual))
694 		return -EIO;
695 
696 	in   = VE_IS_IO_IN(exit_qual);
697 	size = VE_GET_IO_SIZE(exit_qual);
698 	port = VE_GET_PORT_NUM(exit_qual);
699 
700 
701 	if (in)
702 		ret = handle_in(regs, size, port);
703 	else
704 		ret = handle_out(regs, size, port);
705 	if (!ret)
706 		return -EIO;
707 
708 	return ve_instr_len(ve);
709 }
710 
711 /*
712  * Early #VE exception handler. Only handles a subset of port I/O.
713  * Intended only for earlyprintk. If failed, return false.
714  */
tdx_early_handle_ve(struct pt_regs * regs)715 __init bool tdx_early_handle_ve(struct pt_regs *regs)
716 {
717 	struct ve_info ve;
718 	int insn_len;
719 
720 	tdx_get_ve_info(&ve);
721 
722 	if (ve.exit_reason != EXIT_REASON_IO_INSTRUCTION)
723 		return false;
724 
725 	insn_len = handle_io(regs, &ve);
726 	if (insn_len < 0)
727 		return false;
728 
729 	regs->ip += insn_len;
730 	return true;
731 }
732 
tdx_get_ve_info(struct ve_info * ve)733 void tdx_get_ve_info(struct ve_info *ve)
734 {
735 	struct tdx_module_args args = {};
736 
737 	/*
738 	 * Called during #VE handling to retrieve the #VE info from the
739 	 * TDX module.
740 	 *
741 	 * This has to be called early in #VE handling.  A "nested" #VE which
742 	 * occurs before this will raise a #DF and is not recoverable.
743 	 *
744 	 * The call retrieves the #VE info from the TDX module, which also
745 	 * clears the "#VE valid" flag. This must be done before anything else
746 	 * because any #VE that occurs while the valid flag is set will lead to
747 	 * #DF.
748 	 *
749 	 * Note, the TDX module treats virtual NMIs as inhibited if the #VE
750 	 * valid flag is set. It means that NMI=>#VE will not result in a #DF.
751 	 */
752 	tdcall(TDG_VP_VEINFO_GET, &args);
753 
754 	/* Transfer the output parameters */
755 	ve->exit_reason = args.rcx;
756 	ve->exit_qual   = args.rdx;
757 	ve->gla         = args.r8;
758 	ve->gpa         = args.r9;
759 	ve->instr_len   = lower_32_bits(args.r10);
760 	ve->instr_info  = upper_32_bits(args.r10);
761 }
762 
763 /*
764  * Handle the user initiated #VE.
765  *
766  * On success, returns the number of bytes RIP should be incremented (>=0)
767  * or -errno on error.
768  */
virt_exception_user(struct pt_regs * regs,struct ve_info * ve)769 static int virt_exception_user(struct pt_regs *regs, struct ve_info *ve)
770 {
771 	switch (ve->exit_reason) {
772 	case EXIT_REASON_CPUID:
773 		return handle_cpuid(regs, ve);
774 	default:
775 		pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
776 		return -EIO;
777 	}
778 }
779 
is_private_gpa(u64 gpa)780 static inline bool is_private_gpa(u64 gpa)
781 {
782 	return gpa == cc_mkenc(gpa);
783 }
784 
785 /*
786  * Handle the kernel #VE.
787  *
788  * On success, returns the number of bytes RIP should be incremented (>=0)
789  * or -errno on error.
790  */
virt_exception_kernel(struct pt_regs * regs,struct ve_info * ve)791 static int virt_exception_kernel(struct pt_regs *regs, struct ve_info *ve)
792 {
793 	switch (ve->exit_reason) {
794 	case EXIT_REASON_HLT:
795 		return handle_halt(ve);
796 	case EXIT_REASON_MSR_READ:
797 		return read_msr(regs, ve);
798 	case EXIT_REASON_MSR_WRITE:
799 		return write_msr(regs, ve);
800 	case EXIT_REASON_CPUID:
801 		return handle_cpuid(regs, ve);
802 	case EXIT_REASON_EPT_VIOLATION:
803 		if (is_private_gpa(ve->gpa))
804 			panic("Unexpected EPT-violation on private memory.");
805 		return handle_mmio(regs, ve);
806 	case EXIT_REASON_IO_INSTRUCTION:
807 		return handle_io(regs, ve);
808 	default:
809 		pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
810 		return -EIO;
811 	}
812 }
813 
tdx_handle_virt_exception(struct pt_regs * regs,struct ve_info * ve)814 bool tdx_handle_virt_exception(struct pt_regs *regs, struct ve_info *ve)
815 {
816 	int insn_len;
817 
818 	if (user_mode(regs))
819 		insn_len = virt_exception_user(regs, ve);
820 	else
821 		insn_len = virt_exception_kernel(regs, ve);
822 	if (insn_len < 0)
823 		return false;
824 
825 	/* After successful #VE handling, move the IP */
826 	regs->ip += insn_len;
827 
828 	return true;
829 }
830 
tdx_tlb_flush_required(bool private)831 static bool tdx_tlb_flush_required(bool private)
832 {
833 	/*
834 	 * TDX guest is responsible for flushing TLB on private->shared
835 	 * transition. VMM is responsible for flushing on shared->private.
836 	 *
837 	 * The VMM _can't_ flush private addresses as it can't generate PAs
838 	 * with the guest's HKID.  Shared memory isn't subject to integrity
839 	 * checking, i.e. the VMM doesn't need to flush for its own protection.
840 	 *
841 	 * There's no need to flush when converting from shared to private,
842 	 * as flushing is the VMM's responsibility in this case, e.g. it must
843 	 * flush to avoid integrity failures in the face of a buggy or
844 	 * malicious guest.
845 	 */
846 	return !private;
847 }
848 
tdx_cache_flush_required(void)849 static bool tdx_cache_flush_required(void)
850 {
851 	/*
852 	 * AMD SME/SEV can avoid cache flushing if HW enforces cache coherence.
853 	 * TDX doesn't have such capability.
854 	 *
855 	 * Flush cache unconditionally.
856 	 */
857 	return true;
858 }
859 
860 /*
861  * Notify the VMM about page mapping conversion. More info about ABI
862  * can be found in TDX Guest-Host-Communication Interface (GHCI),
863  * section "TDG.VP.VMCALL<MapGPA>".
864  */
tdx_map_gpa(phys_addr_t start,phys_addr_t end,bool enc)865 static bool tdx_map_gpa(phys_addr_t start, phys_addr_t end, bool enc)
866 {
867 	/* Retrying the hypercall a second time should succeed; use 3 just in case */
868 	const int max_retries_per_page = 3;
869 	int retry_count = 0;
870 
871 	if (!enc) {
872 		/* Set the shared (decrypted) bits: */
873 		start |= cc_mkdec(0);
874 		end   |= cc_mkdec(0);
875 	}
876 
877 	while (retry_count < max_retries_per_page) {
878 		struct tdx_module_args args = {
879 			.r10 = TDX_HYPERCALL_STANDARD,
880 			.r11 = TDVMCALL_MAP_GPA,
881 			.r12 = start,
882 			.r13 = end - start };
883 
884 		u64 map_fail_paddr;
885 		u64 ret = __tdx_hypercall(&args);
886 
887 		if (ret != TDVMCALL_STATUS_RETRY)
888 			return !ret;
889 		/*
890 		 * The guest must retry the operation for the pages in the
891 		 * region starting at the GPA specified in R11. R11 comes
892 		 * from the untrusted VMM. Sanity check it.
893 		 */
894 		map_fail_paddr = args.r11;
895 		if (map_fail_paddr < start || map_fail_paddr >= end)
896 			return false;
897 
898 		/* "Consume" a retry without forward progress */
899 		if (map_fail_paddr == start) {
900 			retry_count++;
901 			continue;
902 		}
903 
904 		start = map_fail_paddr;
905 		retry_count = 0;
906 	}
907 
908 	return false;
909 }
910 
911 /*
912  * Inform the VMM of the guest's intent for this physical page: shared with
913  * the VMM or private to the guest.  The VMM is expected to change its mapping
914  * of the page in response.
915  */
tdx_enc_status_changed(unsigned long vaddr,int numpages,bool enc)916 static bool tdx_enc_status_changed(unsigned long vaddr, int numpages, bool enc)
917 {
918 	phys_addr_t start = __pa(vaddr);
919 	phys_addr_t end   = __pa(vaddr + numpages * PAGE_SIZE);
920 
921 	if (!tdx_map_gpa(start, end, enc))
922 		return false;
923 
924 	/* shared->private conversion requires memory to be accepted before use */
925 	if (enc)
926 		return tdx_accept_memory(start, end);
927 
928 	return true;
929 }
930 
tdx_enc_status_change_prepare(unsigned long vaddr,int numpages,bool enc)931 static int tdx_enc_status_change_prepare(unsigned long vaddr, int numpages,
932 					 bool enc)
933 {
934 	/*
935 	 * Only handle shared->private conversion here.
936 	 * See the comment in tdx_early_init().
937 	 */
938 	if (enc && !tdx_enc_status_changed(vaddr, numpages, enc))
939 		return -EIO;
940 
941 	return 0;
942 }
943 
tdx_enc_status_change_finish(unsigned long vaddr,int numpages,bool enc)944 static int tdx_enc_status_change_finish(unsigned long vaddr, int numpages,
945 					 bool enc)
946 {
947 	/*
948 	 * Only handle private->shared conversion here.
949 	 * See the comment in tdx_early_init().
950 	 */
951 	if (!enc && !tdx_enc_status_changed(vaddr, numpages, enc))
952 		return -EIO;
953 
954 	if (enc)
955 		atomic_long_sub(numpages, &nr_shared);
956 	else
957 		atomic_long_add(numpages, &nr_shared);
958 
959 	return 0;
960 }
961 
962 /* Stop new private<->shared conversions */
tdx_kexec_begin(void)963 static void tdx_kexec_begin(void)
964 {
965 	if (!IS_ENABLED(CONFIG_KEXEC_CORE))
966 		return;
967 
968 	/*
969 	 * Crash kernel reaches here with interrupts disabled: can't wait for
970 	 * conversions to finish.
971 	 *
972 	 * If race happened, just report and proceed.
973 	 */
974 	if (!set_memory_enc_stop_conversion())
975 		pr_warn("Failed to stop shared<->private conversions\n");
976 }
977 
978 /* Walk direct mapping and convert all shared memory back to private */
tdx_kexec_finish(void)979 static void tdx_kexec_finish(void)
980 {
981 	unsigned long addr, end;
982 	long found = 0, shared;
983 
984 	if (!IS_ENABLED(CONFIG_KEXEC_CORE))
985 		return;
986 
987 	lockdep_assert_irqs_disabled();
988 
989 	addr = PAGE_OFFSET;
990 	end  = PAGE_OFFSET + get_max_mapped();
991 
992 	while (addr < end) {
993 		unsigned long size;
994 		unsigned int level;
995 		pte_t *pte;
996 
997 		pte = lookup_address(addr, &level);
998 		size = page_level_size(level);
999 
1000 		if (pte && pte_decrypted(*pte)) {
1001 			int pages = size / PAGE_SIZE;
1002 
1003 			/*
1004 			 * Touching memory with shared bit set triggers implicit
1005 			 * conversion to shared.
1006 			 *
1007 			 * Make sure nobody touches the shared range from
1008 			 * now on.
1009 			 */
1010 			set_pte(pte, __pte(0));
1011 
1012 			/*
1013 			 * Memory encryption state persists across kexec.
1014 			 * If tdx_enc_status_changed() fails in the first
1015 			 * kernel, it leaves memory in an unknown state.
1016 			 *
1017 			 * If that memory remains shared, accessing it in the
1018 			 * *next* kernel through a private mapping will result
1019 			 * in an unrecoverable guest shutdown.
1020 			 *
1021 			 * The kdump kernel boot is not impacted as it uses
1022 			 * a pre-reserved memory range that is always private.
1023 			 * However, gathering crash information could lead to
1024 			 * a crash if it accesses unconverted memory through
1025 			 * a private mapping which is possible when accessing
1026 			 * that memory through /proc/vmcore, for example.
1027 			 *
1028 			 * In all cases, print error info in order to leave
1029 			 * enough bread crumbs for debugging.
1030 			 */
1031 			if (!tdx_enc_status_changed(addr, pages, true)) {
1032 				pr_err("Failed to unshare range %#lx-%#lx\n",
1033 				       addr, addr + size);
1034 			}
1035 
1036 			found += pages;
1037 		}
1038 
1039 		addr += size;
1040 	}
1041 
1042 	__flush_tlb_all();
1043 
1044 	shared = atomic_long_read(&nr_shared);
1045 	if (shared != found) {
1046 		pr_err("shared page accounting is off\n");
1047 		pr_err("nr_shared = %ld, nr_found = %ld\n", shared, found);
1048 	}
1049 }
1050 
tdx_announce(void)1051 static __init void tdx_announce(void)
1052 {
1053 	struct tdx_module_args args = {};
1054 	u64 controls;
1055 
1056 	pr_info("Guest detected\n");
1057 
1058 	tdcall(TDG_VP_INFO, &args);
1059 	tdx_dump_attributes(args.rdx);
1060 
1061 	tdg_vm_rd(TDCS_TD_CTLS, &controls);
1062 	tdx_dump_td_ctls(controls);
1063 }
1064 
tdx_early_init(void)1065 void __init tdx_early_init(void)
1066 {
1067 	u64 cc_mask;
1068 	u32 eax, sig[3];
1069 
1070 	cpuid_count(TDX_CPUID_LEAF_ID, 0, &eax, &sig[0], &sig[2],  &sig[1]);
1071 
1072 	if (memcmp(TDX_IDENT, sig, sizeof(sig)))
1073 		return;
1074 
1075 	setup_force_cpu_cap(X86_FEATURE_TDX_GUEST);
1076 
1077 	/* TSC is the only reliable clock in TDX guest */
1078 	setup_force_cpu_cap(X86_FEATURE_TSC_RELIABLE);
1079 
1080 	cc_vendor = CC_VENDOR_INTEL;
1081 
1082 	/* Configure the TD */
1083 	tdx_setup(&cc_mask);
1084 
1085 	cc_set_mask(cc_mask);
1086 
1087 	/*
1088 	 * All bits above GPA width are reserved and kernel treats shared bit
1089 	 * as flag, not as part of physical address.
1090 	 *
1091 	 * Adjust physical mask to only cover valid GPA bits.
1092 	 */
1093 	physical_mask &= cc_mask - 1;
1094 
1095 	/*
1096 	 * The kernel mapping should match the TDX metadata for the page.
1097 	 * load_unaligned_zeropad() can touch memory *adjacent* to that which is
1098 	 * owned by the caller and can catch even _momentary_ mismatches.  Bad
1099 	 * things happen on mismatch:
1100 	 *
1101 	 *   - Private mapping => Shared Page  == Guest shutdown
1102          *   - Shared mapping  => Private Page == Recoverable #VE
1103 	 *
1104 	 * guest.enc_status_change_prepare() converts the page from
1105 	 * shared=>private before the mapping becomes private.
1106 	 *
1107 	 * guest.enc_status_change_finish() converts the page from
1108 	 * private=>shared after the mapping becomes private.
1109 	 *
1110 	 * In both cases there is a temporary shared mapping to a private page,
1111 	 * which can result in a #VE.  But, there is never a private mapping to
1112 	 * a shared page.
1113 	 */
1114 	x86_platform.guest.enc_status_change_prepare = tdx_enc_status_change_prepare;
1115 	x86_platform.guest.enc_status_change_finish  = tdx_enc_status_change_finish;
1116 
1117 	x86_platform.guest.enc_cache_flush_required  = tdx_cache_flush_required;
1118 	x86_platform.guest.enc_tlb_flush_required    = tdx_tlb_flush_required;
1119 
1120 	x86_platform.guest.enc_kexec_begin	     = tdx_kexec_begin;
1121 	x86_platform.guest.enc_kexec_finish	     = tdx_kexec_finish;
1122 
1123 	/*
1124 	 * Avoid "sti;hlt" execution in TDX guests as HLT induces a #VE that
1125 	 * will enable interrupts before HLT TDCALL invocation if executed
1126 	 * in STI-shadow, possibly resulting in missed wakeup events.
1127 	 *
1128 	 * Modify all possible HLT execution paths to use TDX specific routines
1129 	 * that directly execute TDCALL and toggle the interrupt state as
1130 	 * needed after TDCALL completion. This also reduces HLT related #VEs
1131 	 * in addition to having a reliable halt logic execution.
1132 	 */
1133 	pv_ops.irq.safe_halt = tdx_safe_halt;
1134 	pv_ops.irq.halt = tdx_halt;
1135 
1136 	/*
1137 	 * TDX intercepts the RDMSR to read the X2APIC ID in the parallel
1138 	 * bringup low level code. That raises #VE which cannot be handled
1139 	 * there.
1140 	 *
1141 	 * Intel-TDX has a secure RDMSR hypercall, but that needs to be
1142 	 * implemented separately in the low level startup ASM code.
1143 	 * Until that is in place, disable parallel bringup for TDX.
1144 	 */
1145 	x86_cpuinit.parallel_bringup = false;
1146 
1147 	tdx_announce();
1148 }
1149