xref: /openbmc/linux/arch/x86/coco/tdx/tdx.c (revision 6486a57f)
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 <asm/coco.h>
11 #include <asm/tdx.h>
12 #include <asm/vmx.h>
13 #include <asm/insn.h>
14 #include <asm/insn-eval.h>
15 #include <asm/pgtable.h>
16 
17 /* TDX module Call Leaf IDs */
18 #define TDX_GET_INFO			1
19 #define TDX_GET_VEINFO			3
20 #define TDX_GET_REPORT			4
21 #define TDX_ACCEPT_PAGE			6
22 
23 /* TDX hypercall Leaf IDs */
24 #define TDVMCALL_MAP_GPA		0x10001
25 
26 /* MMIO direction */
27 #define EPT_READ	0
28 #define EPT_WRITE	1
29 
30 /* Port I/O direction */
31 #define PORT_READ	0
32 #define PORT_WRITE	1
33 
34 /* See Exit Qualification for I/O Instructions in VMX documentation */
35 #define VE_IS_IO_IN(e)		((e) & BIT(3))
36 #define VE_GET_IO_SIZE(e)	(((e) & GENMASK(2, 0)) + 1)
37 #define VE_GET_PORT_NUM(e)	((e) >> 16)
38 #define VE_IS_IO_STRING(e)	((e) & BIT(4))
39 
40 #define ATTR_SEPT_VE_DISABLE	BIT(28)
41 
42 /* TDX Module call error codes */
43 #define TDCALL_RETURN_CODE(a)	((a) >> 32)
44 #define TDCALL_INVALID_OPERAND	0xc0000100
45 
46 #define TDREPORT_SUBTYPE_0	0
47 
48 /*
49  * Wrapper for standard use of __tdx_hypercall with no output aside from
50  * return code.
51  */
52 static inline u64 _tdx_hypercall(u64 fn, u64 r12, u64 r13, u64 r14, u64 r15)
53 {
54 	struct tdx_hypercall_args args = {
55 		.r10 = TDX_HYPERCALL_STANDARD,
56 		.r11 = fn,
57 		.r12 = r12,
58 		.r13 = r13,
59 		.r14 = r14,
60 		.r15 = r15,
61 	};
62 
63 	return __tdx_hypercall(&args, 0);
64 }
65 
66 /* Called from __tdx_hypercall() for unrecoverable failure */
67 noinstr void __tdx_hypercall_failed(void)
68 {
69 	instrumentation_begin();
70 	panic("TDVMCALL failed. TDX module bug?");
71 }
72 
73 /*
74  * The TDG.VP.VMCALL-Instruction-execution sub-functions are defined
75  * independently from but are currently matched 1:1 with VMX EXIT_REASONs.
76  * Reusing the KVM EXIT_REASON macros makes it easier to connect the host and
77  * guest sides of these calls.
78  */
79 static __always_inline u64 hcall_func(u64 exit_reason)
80 {
81 	return exit_reason;
82 }
83 
84 #ifdef CONFIG_KVM_GUEST
85 long tdx_kvm_hypercall(unsigned int nr, unsigned long p1, unsigned long p2,
86 		       unsigned long p3, unsigned long p4)
87 {
88 	struct tdx_hypercall_args args = {
89 		.r10 = nr,
90 		.r11 = p1,
91 		.r12 = p2,
92 		.r13 = p3,
93 		.r14 = p4,
94 	};
95 
96 	return __tdx_hypercall(&args, 0);
97 }
98 EXPORT_SYMBOL_GPL(tdx_kvm_hypercall);
99 #endif
100 
101 /*
102  * Used for TDX guests to make calls directly to the TD module.  This
103  * should only be used for calls that have no legitimate reason to fail
104  * or where the kernel can not survive the call failing.
105  */
106 static inline void tdx_module_call(u64 fn, u64 rcx, u64 rdx, u64 r8, u64 r9,
107 				   struct tdx_module_output *out)
108 {
109 	if (__tdx_module_call(fn, rcx, rdx, r8, r9, out))
110 		panic("TDCALL %lld failed (Buggy TDX module!)\n", fn);
111 }
112 
113 /**
114  * tdx_mcall_get_report0() - Wrapper to get TDREPORT0 (a.k.a. TDREPORT
115  *                           subtype 0) using TDG.MR.REPORT TDCALL.
116  * @reportdata: Address of the input buffer which contains user-defined
117  *              REPORTDATA to be included into TDREPORT.
118  * @tdreport: Address of the output buffer to store TDREPORT.
119  *
120  * Refer to section titled "TDG.MR.REPORT leaf" in the TDX Module
121  * v1.0 specification for more information on TDG.MR.REPORT TDCALL.
122  * It is used in the TDX guest driver module to get the TDREPORT0.
123  *
124  * Return 0 on success, -EINVAL for invalid operands, or -EIO on
125  * other TDCALL failures.
126  */
127 int tdx_mcall_get_report0(u8 *reportdata, u8 *tdreport)
128 {
129 	u64 ret;
130 
131 	ret = __tdx_module_call(TDX_GET_REPORT, virt_to_phys(tdreport),
132 				virt_to_phys(reportdata), TDREPORT_SUBTYPE_0,
133 				0, NULL);
134 	if (ret) {
135 		if (TDCALL_RETURN_CODE(ret) == TDCALL_INVALID_OPERAND)
136 			return -EINVAL;
137 		return -EIO;
138 	}
139 
140 	return 0;
141 }
142 EXPORT_SYMBOL_GPL(tdx_mcall_get_report0);
143 
144 static void tdx_parse_tdinfo(u64 *cc_mask)
145 {
146 	struct tdx_module_output out;
147 	unsigned int gpa_width;
148 	u64 td_attr;
149 
150 	/*
151 	 * TDINFO TDX module call is used to get the TD execution environment
152 	 * information like GPA width, number of available vcpus, debug mode
153 	 * information, etc. More details about the ABI can be found in TDX
154 	 * Guest-Host-Communication Interface (GHCI), section 2.4.2 TDCALL
155 	 * [TDG.VP.INFO].
156 	 */
157 	tdx_module_call(TDX_GET_INFO, 0, 0, 0, 0, &out);
158 
159 	/*
160 	 * The highest bit of a guest physical address is the "sharing" bit.
161 	 * Set it for shared pages and clear it for private pages.
162 	 *
163 	 * The GPA width that comes out of this call is critical. TDX guests
164 	 * can not meaningfully run without it.
165 	 */
166 	gpa_width = out.rcx & GENMASK(5, 0);
167 	*cc_mask = BIT_ULL(gpa_width - 1);
168 
169 	/*
170 	 * The kernel can not handle #VE's when accessing normal kernel
171 	 * memory.  Ensure that no #VE will be delivered for accesses to
172 	 * TD-private memory.  Only VMM-shared memory (MMIO) will #VE.
173 	 */
174 	td_attr = out.rdx;
175 	if (!(td_attr & ATTR_SEPT_VE_DISABLE))
176 		panic("TD misconfiguration: SEPT_VE_DISABLE attibute must be set.\n");
177 }
178 
179 /*
180  * The TDX module spec states that #VE may be injected for a limited set of
181  * reasons:
182  *
183  *  - Emulation of the architectural #VE injection on EPT violation;
184  *
185  *  - As a result of guest TD execution of a disallowed instruction,
186  *    a disallowed MSR access, or CPUID virtualization;
187  *
188  *  - A notification to the guest TD about anomalous behavior;
189  *
190  * The last one is opt-in and is not used by the kernel.
191  *
192  * The Intel Software Developer's Manual describes cases when instruction
193  * length field can be used in section "Information for VM Exits Due to
194  * Instruction Execution".
195  *
196  * For TDX, it ultimately means GET_VEINFO provides reliable instruction length
197  * information if #VE occurred due to instruction execution, but not for EPT
198  * violations.
199  */
200 static int ve_instr_len(struct ve_info *ve)
201 {
202 	switch (ve->exit_reason) {
203 	case EXIT_REASON_HLT:
204 	case EXIT_REASON_MSR_READ:
205 	case EXIT_REASON_MSR_WRITE:
206 	case EXIT_REASON_CPUID:
207 	case EXIT_REASON_IO_INSTRUCTION:
208 		/* It is safe to use ve->instr_len for #VE due instructions */
209 		return ve->instr_len;
210 	case EXIT_REASON_EPT_VIOLATION:
211 		/*
212 		 * For EPT violations, ve->insn_len is not defined. For those,
213 		 * the kernel must decode instructions manually and should not
214 		 * be using this function.
215 		 */
216 		WARN_ONCE(1, "ve->instr_len is not defined for EPT violations");
217 		return 0;
218 	default:
219 		WARN_ONCE(1, "Unexpected #VE-type: %lld\n", ve->exit_reason);
220 		return ve->instr_len;
221 	}
222 }
223 
224 static u64 __cpuidle __halt(const bool irq_disabled)
225 {
226 	struct tdx_hypercall_args args = {
227 		.r10 = TDX_HYPERCALL_STANDARD,
228 		.r11 = hcall_func(EXIT_REASON_HLT),
229 		.r12 = irq_disabled,
230 	};
231 
232 	/*
233 	 * Emulate HLT operation via hypercall. More info about ABI
234 	 * can be found in TDX Guest-Host-Communication Interface
235 	 * (GHCI), section 3.8 TDG.VP.VMCALL<Instruction.HLT>.
236 	 *
237 	 * The VMM uses the "IRQ disabled" param to understand IRQ
238 	 * enabled status (RFLAGS.IF) of the TD guest and to determine
239 	 * whether or not it should schedule the halted vCPU if an
240 	 * IRQ becomes pending. E.g. if IRQs are disabled, the VMM
241 	 * can keep the vCPU in virtual HLT, even if an IRQ is
242 	 * pending, without hanging/breaking the guest.
243 	 */
244 	return __tdx_hypercall(&args, 0);
245 }
246 
247 static int handle_halt(struct ve_info *ve)
248 {
249 	const bool irq_disabled = irqs_disabled();
250 
251 	if (__halt(irq_disabled))
252 		return -EIO;
253 
254 	return ve_instr_len(ve);
255 }
256 
257 void __cpuidle tdx_safe_halt(void)
258 {
259 	const bool irq_disabled = false;
260 
261 	/*
262 	 * Use WARN_ONCE() to report the failure.
263 	 */
264 	if (__halt(irq_disabled))
265 		WARN_ONCE(1, "HLT instruction emulation failed\n");
266 }
267 
268 static int read_msr(struct pt_regs *regs, struct ve_info *ve)
269 {
270 	struct tdx_hypercall_args args = {
271 		.r10 = TDX_HYPERCALL_STANDARD,
272 		.r11 = hcall_func(EXIT_REASON_MSR_READ),
273 		.r12 = regs->cx,
274 	};
275 
276 	/*
277 	 * Emulate the MSR read via hypercall. More info about ABI
278 	 * can be found in TDX Guest-Host-Communication Interface
279 	 * (GHCI), section titled "TDG.VP.VMCALL<Instruction.RDMSR>".
280 	 */
281 	if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
282 		return -EIO;
283 
284 	regs->ax = lower_32_bits(args.r11);
285 	regs->dx = upper_32_bits(args.r11);
286 	return ve_instr_len(ve);
287 }
288 
289 static int write_msr(struct pt_regs *regs, struct ve_info *ve)
290 {
291 	struct tdx_hypercall_args args = {
292 		.r10 = TDX_HYPERCALL_STANDARD,
293 		.r11 = hcall_func(EXIT_REASON_MSR_WRITE),
294 		.r12 = regs->cx,
295 		.r13 = (u64)regs->dx << 32 | regs->ax,
296 	};
297 
298 	/*
299 	 * Emulate the MSR write via hypercall. More info about ABI
300 	 * can be found in TDX Guest-Host-Communication Interface
301 	 * (GHCI) section titled "TDG.VP.VMCALL<Instruction.WRMSR>".
302 	 */
303 	if (__tdx_hypercall(&args, 0))
304 		return -EIO;
305 
306 	return ve_instr_len(ve);
307 }
308 
309 static int handle_cpuid(struct pt_regs *regs, struct ve_info *ve)
310 {
311 	struct tdx_hypercall_args args = {
312 		.r10 = TDX_HYPERCALL_STANDARD,
313 		.r11 = hcall_func(EXIT_REASON_CPUID),
314 		.r12 = regs->ax,
315 		.r13 = regs->cx,
316 	};
317 
318 	/*
319 	 * Only allow VMM to control range reserved for hypervisor
320 	 * communication.
321 	 *
322 	 * Return all-zeros for any CPUID outside the range. It matches CPU
323 	 * behaviour for non-supported leaf.
324 	 */
325 	if (regs->ax < 0x40000000 || regs->ax > 0x4FFFFFFF) {
326 		regs->ax = regs->bx = regs->cx = regs->dx = 0;
327 		return ve_instr_len(ve);
328 	}
329 
330 	/*
331 	 * Emulate the CPUID instruction via a hypercall. More info about
332 	 * ABI can be found in TDX Guest-Host-Communication Interface
333 	 * (GHCI), section titled "VP.VMCALL<Instruction.CPUID>".
334 	 */
335 	if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
336 		return -EIO;
337 
338 	/*
339 	 * As per TDX GHCI CPUID ABI, r12-r15 registers contain contents of
340 	 * EAX, EBX, ECX, EDX registers after the CPUID instruction execution.
341 	 * So copy the register contents back to pt_regs.
342 	 */
343 	regs->ax = args.r12;
344 	regs->bx = args.r13;
345 	regs->cx = args.r14;
346 	regs->dx = args.r15;
347 
348 	return ve_instr_len(ve);
349 }
350 
351 static bool mmio_read(int size, unsigned long addr, unsigned long *val)
352 {
353 	struct tdx_hypercall_args args = {
354 		.r10 = TDX_HYPERCALL_STANDARD,
355 		.r11 = hcall_func(EXIT_REASON_EPT_VIOLATION),
356 		.r12 = size,
357 		.r13 = EPT_READ,
358 		.r14 = addr,
359 		.r15 = *val,
360 	};
361 
362 	if (__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT))
363 		return false;
364 	*val = args.r11;
365 	return true;
366 }
367 
368 static bool mmio_write(int size, unsigned long addr, unsigned long val)
369 {
370 	return !_tdx_hypercall(hcall_func(EXIT_REASON_EPT_VIOLATION), size,
371 			       EPT_WRITE, addr, val);
372 }
373 
374 static int handle_mmio(struct pt_regs *regs, struct ve_info *ve)
375 {
376 	unsigned long *reg, val, vaddr;
377 	char buffer[MAX_INSN_SIZE];
378 	enum insn_mmio_type mmio;
379 	struct insn insn = {};
380 	int size, extend_size;
381 	u8 extend_val = 0;
382 
383 	/* Only in-kernel MMIO is supported */
384 	if (WARN_ON_ONCE(user_mode(regs)))
385 		return -EFAULT;
386 
387 	if (copy_from_kernel_nofault(buffer, (void *)regs->ip, MAX_INSN_SIZE))
388 		return -EFAULT;
389 
390 	if (insn_decode(&insn, buffer, MAX_INSN_SIZE, INSN_MODE_64))
391 		return -EINVAL;
392 
393 	mmio = insn_decode_mmio(&insn, &size);
394 	if (WARN_ON_ONCE(mmio == INSN_MMIO_DECODE_FAILED))
395 		return -EINVAL;
396 
397 	if (mmio != INSN_MMIO_WRITE_IMM && mmio != INSN_MMIO_MOVS) {
398 		reg = insn_get_modrm_reg_ptr(&insn, regs);
399 		if (!reg)
400 			return -EINVAL;
401 	}
402 
403 	/*
404 	 * Reject EPT violation #VEs that split pages.
405 	 *
406 	 * MMIO accesses are supposed to be naturally aligned and therefore
407 	 * never cross page boundaries. Seeing split page accesses indicates
408 	 * a bug or a load_unaligned_zeropad() that stepped into an MMIO page.
409 	 *
410 	 * load_unaligned_zeropad() will recover using exception fixups.
411 	 */
412 	vaddr = (unsigned long)insn_get_addr_ref(&insn, regs);
413 	if (vaddr / PAGE_SIZE != (vaddr + size - 1) / PAGE_SIZE)
414 		return -EFAULT;
415 
416 	/* Handle writes first */
417 	switch (mmio) {
418 	case INSN_MMIO_WRITE:
419 		memcpy(&val, reg, size);
420 		if (!mmio_write(size, ve->gpa, val))
421 			return -EIO;
422 		return insn.length;
423 	case INSN_MMIO_WRITE_IMM:
424 		val = insn.immediate.value;
425 		if (!mmio_write(size, ve->gpa, val))
426 			return -EIO;
427 		return insn.length;
428 	case INSN_MMIO_READ:
429 	case INSN_MMIO_READ_ZERO_EXTEND:
430 	case INSN_MMIO_READ_SIGN_EXTEND:
431 		/* Reads are handled below */
432 		break;
433 	case INSN_MMIO_MOVS:
434 	case INSN_MMIO_DECODE_FAILED:
435 		/*
436 		 * MMIO was accessed with an instruction that could not be
437 		 * decoded or handled properly. It was likely not using io.h
438 		 * helpers or accessed MMIO accidentally.
439 		 */
440 		return -EINVAL;
441 	default:
442 		WARN_ONCE(1, "Unknown insn_decode_mmio() decode value?");
443 		return -EINVAL;
444 	}
445 
446 	/* Handle reads */
447 	if (!mmio_read(size, ve->gpa, &val))
448 		return -EIO;
449 
450 	switch (mmio) {
451 	case INSN_MMIO_READ:
452 		/* Zero-extend for 32-bit operation */
453 		extend_size = size == 4 ? sizeof(*reg) : 0;
454 		break;
455 	case INSN_MMIO_READ_ZERO_EXTEND:
456 		/* Zero extend based on operand size */
457 		extend_size = insn.opnd_bytes;
458 		break;
459 	case INSN_MMIO_READ_SIGN_EXTEND:
460 		/* Sign extend based on operand size */
461 		extend_size = insn.opnd_bytes;
462 		if (size == 1 && val & BIT(7))
463 			extend_val = 0xFF;
464 		else if (size > 1 && val & BIT(15))
465 			extend_val = 0xFF;
466 		break;
467 	default:
468 		/* All other cases has to be covered with the first switch() */
469 		WARN_ON_ONCE(1);
470 		return -EINVAL;
471 	}
472 
473 	if (extend_size)
474 		memset(reg, extend_val, extend_size);
475 	memcpy(reg, &val, size);
476 	return insn.length;
477 }
478 
479 static bool handle_in(struct pt_regs *regs, int size, int port)
480 {
481 	struct tdx_hypercall_args args = {
482 		.r10 = TDX_HYPERCALL_STANDARD,
483 		.r11 = hcall_func(EXIT_REASON_IO_INSTRUCTION),
484 		.r12 = size,
485 		.r13 = PORT_READ,
486 		.r14 = port,
487 	};
488 	u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
489 	bool success;
490 
491 	/*
492 	 * Emulate the I/O read via hypercall. More info about ABI can be found
493 	 * in TDX Guest-Host-Communication Interface (GHCI) section titled
494 	 * "TDG.VP.VMCALL<Instruction.IO>".
495 	 */
496 	success = !__tdx_hypercall(&args, TDX_HCALL_HAS_OUTPUT);
497 
498 	/* Update part of the register affected by the emulated instruction */
499 	regs->ax &= ~mask;
500 	if (success)
501 		regs->ax |= args.r11 & mask;
502 
503 	return success;
504 }
505 
506 static bool handle_out(struct pt_regs *regs, int size, int port)
507 {
508 	u64 mask = GENMASK(BITS_PER_BYTE * size, 0);
509 
510 	/*
511 	 * Emulate the I/O write via hypercall. More info about ABI can be found
512 	 * in TDX Guest-Host-Communication Interface (GHCI) section titled
513 	 * "TDG.VP.VMCALL<Instruction.IO>".
514 	 */
515 	return !_tdx_hypercall(hcall_func(EXIT_REASON_IO_INSTRUCTION), size,
516 			       PORT_WRITE, port, regs->ax & mask);
517 }
518 
519 /*
520  * Emulate I/O using hypercall.
521  *
522  * Assumes the IO instruction was using ax, which is enforced
523  * by the standard io.h macros.
524  *
525  * Return True on success or False on failure.
526  */
527 static int handle_io(struct pt_regs *regs, struct ve_info *ve)
528 {
529 	u32 exit_qual = ve->exit_qual;
530 	int size, port;
531 	bool in, ret;
532 
533 	if (VE_IS_IO_STRING(exit_qual))
534 		return -EIO;
535 
536 	in   = VE_IS_IO_IN(exit_qual);
537 	size = VE_GET_IO_SIZE(exit_qual);
538 	port = VE_GET_PORT_NUM(exit_qual);
539 
540 
541 	if (in)
542 		ret = handle_in(regs, size, port);
543 	else
544 		ret = handle_out(regs, size, port);
545 	if (!ret)
546 		return -EIO;
547 
548 	return ve_instr_len(ve);
549 }
550 
551 /*
552  * Early #VE exception handler. Only handles a subset of port I/O.
553  * Intended only for earlyprintk. If failed, return false.
554  */
555 __init bool tdx_early_handle_ve(struct pt_regs *regs)
556 {
557 	struct ve_info ve;
558 	int insn_len;
559 
560 	tdx_get_ve_info(&ve);
561 
562 	if (ve.exit_reason != EXIT_REASON_IO_INSTRUCTION)
563 		return false;
564 
565 	insn_len = handle_io(regs, &ve);
566 	if (insn_len < 0)
567 		return false;
568 
569 	regs->ip += insn_len;
570 	return true;
571 }
572 
573 void tdx_get_ve_info(struct ve_info *ve)
574 {
575 	struct tdx_module_output out;
576 
577 	/*
578 	 * Called during #VE handling to retrieve the #VE info from the
579 	 * TDX module.
580 	 *
581 	 * This has to be called early in #VE handling.  A "nested" #VE which
582 	 * occurs before this will raise a #DF and is not recoverable.
583 	 *
584 	 * The call retrieves the #VE info from the TDX module, which also
585 	 * clears the "#VE valid" flag. This must be done before anything else
586 	 * because any #VE that occurs while the valid flag is set will lead to
587 	 * #DF.
588 	 *
589 	 * Note, the TDX module treats virtual NMIs as inhibited if the #VE
590 	 * valid flag is set. It means that NMI=>#VE will not result in a #DF.
591 	 */
592 	tdx_module_call(TDX_GET_VEINFO, 0, 0, 0, 0, &out);
593 
594 	/* Transfer the output parameters */
595 	ve->exit_reason = out.rcx;
596 	ve->exit_qual   = out.rdx;
597 	ve->gla         = out.r8;
598 	ve->gpa         = out.r9;
599 	ve->instr_len   = lower_32_bits(out.r10);
600 	ve->instr_info  = upper_32_bits(out.r10);
601 }
602 
603 /*
604  * Handle the user initiated #VE.
605  *
606  * On success, returns the number of bytes RIP should be incremented (>=0)
607  * or -errno on error.
608  */
609 static int virt_exception_user(struct pt_regs *regs, struct ve_info *ve)
610 {
611 	switch (ve->exit_reason) {
612 	case EXIT_REASON_CPUID:
613 		return handle_cpuid(regs, ve);
614 	default:
615 		pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
616 		return -EIO;
617 	}
618 }
619 
620 /*
621  * Handle the kernel #VE.
622  *
623  * On success, returns the number of bytes RIP should be incremented (>=0)
624  * or -errno on error.
625  */
626 static int virt_exception_kernel(struct pt_regs *regs, struct ve_info *ve)
627 {
628 	switch (ve->exit_reason) {
629 	case EXIT_REASON_HLT:
630 		return handle_halt(ve);
631 	case EXIT_REASON_MSR_READ:
632 		return read_msr(regs, ve);
633 	case EXIT_REASON_MSR_WRITE:
634 		return write_msr(regs, ve);
635 	case EXIT_REASON_CPUID:
636 		return handle_cpuid(regs, ve);
637 	case EXIT_REASON_EPT_VIOLATION:
638 		return handle_mmio(regs, ve);
639 	case EXIT_REASON_IO_INSTRUCTION:
640 		return handle_io(regs, ve);
641 	default:
642 		pr_warn("Unexpected #VE: %lld\n", ve->exit_reason);
643 		return -EIO;
644 	}
645 }
646 
647 bool tdx_handle_virt_exception(struct pt_regs *regs, struct ve_info *ve)
648 {
649 	int insn_len;
650 
651 	if (user_mode(regs))
652 		insn_len = virt_exception_user(regs, ve);
653 	else
654 		insn_len = virt_exception_kernel(regs, ve);
655 	if (insn_len < 0)
656 		return false;
657 
658 	/* After successful #VE handling, move the IP */
659 	regs->ip += insn_len;
660 
661 	return true;
662 }
663 
664 static bool tdx_tlb_flush_required(bool private)
665 {
666 	/*
667 	 * TDX guest is responsible for flushing TLB on private->shared
668 	 * transition. VMM is responsible for flushing on shared->private.
669 	 *
670 	 * The VMM _can't_ flush private addresses as it can't generate PAs
671 	 * with the guest's HKID.  Shared memory isn't subject to integrity
672 	 * checking, i.e. the VMM doesn't need to flush for its own protection.
673 	 *
674 	 * There's no need to flush when converting from shared to private,
675 	 * as flushing is the VMM's responsibility in this case, e.g. it must
676 	 * flush to avoid integrity failures in the face of a buggy or
677 	 * malicious guest.
678 	 */
679 	return !private;
680 }
681 
682 static bool tdx_cache_flush_required(void)
683 {
684 	/*
685 	 * AMD SME/SEV can avoid cache flushing if HW enforces cache coherence.
686 	 * TDX doesn't have such capability.
687 	 *
688 	 * Flush cache unconditionally.
689 	 */
690 	return true;
691 }
692 
693 static bool try_accept_one(phys_addr_t *start, unsigned long len,
694 			  enum pg_level pg_level)
695 {
696 	unsigned long accept_size = page_level_size(pg_level);
697 	u64 tdcall_rcx;
698 	u8 page_size;
699 
700 	if (!IS_ALIGNED(*start, accept_size))
701 		return false;
702 
703 	if (len < accept_size)
704 		return false;
705 
706 	/*
707 	 * Pass the page physical address to the TDX module to accept the
708 	 * pending, private page.
709 	 *
710 	 * Bits 2:0 of RCX encode page size: 0 - 4K, 1 - 2M, 2 - 1G.
711 	 */
712 	switch (pg_level) {
713 	case PG_LEVEL_4K:
714 		page_size = 0;
715 		break;
716 	case PG_LEVEL_2M:
717 		page_size = 1;
718 		break;
719 	case PG_LEVEL_1G:
720 		page_size = 2;
721 		break;
722 	default:
723 		return false;
724 	}
725 
726 	tdcall_rcx = *start | page_size;
727 	if (__tdx_module_call(TDX_ACCEPT_PAGE, tdcall_rcx, 0, 0, 0, NULL))
728 		return false;
729 
730 	*start += accept_size;
731 	return true;
732 }
733 
734 /*
735  * Inform the VMM of the guest's intent for this physical page: shared with
736  * the VMM or private to the guest.  The VMM is expected to change its mapping
737  * of the page in response.
738  */
739 static bool tdx_enc_status_changed(unsigned long vaddr, int numpages, bool enc)
740 {
741 	phys_addr_t start = __pa(vaddr);
742 	phys_addr_t end   = __pa(vaddr + numpages * PAGE_SIZE);
743 
744 	if (!enc) {
745 		/* Set the shared (decrypted) bits: */
746 		start |= cc_mkdec(0);
747 		end   |= cc_mkdec(0);
748 	}
749 
750 	/*
751 	 * Notify the VMM about page mapping conversion. More info about ABI
752 	 * can be found in TDX Guest-Host-Communication Interface (GHCI),
753 	 * section "TDG.VP.VMCALL<MapGPA>"
754 	 */
755 	if (_tdx_hypercall(TDVMCALL_MAP_GPA, start, end - start, 0, 0))
756 		return false;
757 
758 	/* private->shared conversion  requires only MapGPA call */
759 	if (!enc)
760 		return true;
761 
762 	/*
763 	 * For shared->private conversion, accept the page using
764 	 * TDX_ACCEPT_PAGE TDX module call.
765 	 */
766 	while (start < end) {
767 		unsigned long len = end - start;
768 
769 		/*
770 		 * Try larger accepts first. It gives chance to VMM to keep
771 		 * 1G/2M SEPT entries where possible and speeds up process by
772 		 * cutting number of hypercalls (if successful).
773 		 */
774 
775 		if (try_accept_one(&start, len, PG_LEVEL_1G))
776 			continue;
777 
778 		if (try_accept_one(&start, len, PG_LEVEL_2M))
779 			continue;
780 
781 		if (!try_accept_one(&start, len, PG_LEVEL_4K))
782 			return false;
783 	}
784 
785 	return true;
786 }
787 
788 void __init tdx_early_init(void)
789 {
790 	u64 cc_mask;
791 	u32 eax, sig[3];
792 
793 	cpuid_count(TDX_CPUID_LEAF_ID, 0, &eax, &sig[0], &sig[2],  &sig[1]);
794 
795 	if (memcmp(TDX_IDENT, sig, sizeof(sig)))
796 		return;
797 
798 	setup_force_cpu_cap(X86_FEATURE_TDX_GUEST);
799 
800 	cc_set_vendor(CC_VENDOR_INTEL);
801 	tdx_parse_tdinfo(&cc_mask);
802 	cc_set_mask(cc_mask);
803 
804 	/*
805 	 * All bits above GPA width are reserved and kernel treats shared bit
806 	 * as flag, not as part of physical address.
807 	 *
808 	 * Adjust physical mask to only cover valid GPA bits.
809 	 */
810 	physical_mask &= cc_mask - 1;
811 
812 	x86_platform.guest.enc_cache_flush_required = tdx_cache_flush_required;
813 	x86_platform.guest.enc_tlb_flush_required   = tdx_tlb_flush_required;
814 	x86_platform.guest.enc_status_change_finish = tdx_enc_status_changed;
815 
816 	pr_info("Guest detected\n");
817 }
818