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