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