]> Git Repo - J-linux.git/blob - arch/x86/kernel/sev.c
Merge tag 'kbuild-v6.9' of git://git.kernel.org/pub/scm/linux/kernel/git/masahiroy...
[J-linux.git] / arch / x86 / kernel / sev.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AMD Memory Encryption Support
4  *
5  * Copyright (C) 2019 SUSE
6  *
7  * Author: Joerg Roedel <[email protected]>
8  */
9
10 #define pr_fmt(fmt)     "SEV: " fmt
11
12 #include <linux/sched/debug.h>  /* For show_regs() */
13 #include <linux/percpu-defs.h>
14 #include <linux/cc_platform.h>
15 #include <linux/printk.h>
16 #include <linux/mm_types.h>
17 #include <linux/set_memory.h>
18 #include <linux/memblock.h>
19 #include <linux/kernel.h>
20 #include <linux/mm.h>
21 #include <linux/cpumask.h>
22 #include <linux/efi.h>
23 #include <linux/platform_device.h>
24 #include <linux/io.h>
25 #include <linux/psp-sev.h>
26 #include <uapi/linux/sev-guest.h>
27
28 #include <asm/init.h>
29 #include <asm/cpu_entry_area.h>
30 #include <asm/stacktrace.h>
31 #include <asm/sev.h>
32 #include <asm/insn-eval.h>
33 #include <asm/fpu/xcr.h>
34 #include <asm/processor.h>
35 #include <asm/realmode.h>
36 #include <asm/setup.h>
37 #include <asm/traps.h>
38 #include <asm/svm.h>
39 #include <asm/smp.h>
40 #include <asm/cpu.h>
41 #include <asm/apic.h>
42 #include <asm/cpuid.h>
43 #include <asm/cmdline.h>
44
45 #define DR7_RESET_VALUE        0x400
46
47 /* AP INIT values as documented in the APM2  section "Processor Initialization State" */
48 #define AP_INIT_CS_LIMIT                0xffff
49 #define AP_INIT_DS_LIMIT                0xffff
50 #define AP_INIT_LDTR_LIMIT              0xffff
51 #define AP_INIT_GDTR_LIMIT              0xffff
52 #define AP_INIT_IDTR_LIMIT              0xffff
53 #define AP_INIT_TR_LIMIT                0xffff
54 #define AP_INIT_RFLAGS_DEFAULT          0x2
55 #define AP_INIT_DR6_DEFAULT             0xffff0ff0
56 #define AP_INIT_GPAT_DEFAULT            0x0007040600070406ULL
57 #define AP_INIT_XCR0_DEFAULT            0x1
58 #define AP_INIT_X87_FTW_DEFAULT         0x5555
59 #define AP_INIT_X87_FCW_DEFAULT         0x0040
60 #define AP_INIT_CR0_DEFAULT             0x60000010
61 #define AP_INIT_MXCSR_DEFAULT           0x1f80
62
63 static const char * const sev_status_feat_names[] = {
64         [MSR_AMD64_SEV_ENABLED_BIT]             = "SEV",
65         [MSR_AMD64_SEV_ES_ENABLED_BIT]          = "SEV-ES",
66         [MSR_AMD64_SEV_SNP_ENABLED_BIT]         = "SEV-SNP",
67         [MSR_AMD64_SNP_VTOM_BIT]                = "vTom",
68         [MSR_AMD64_SNP_REFLECT_VC_BIT]          = "ReflectVC",
69         [MSR_AMD64_SNP_RESTRICTED_INJ_BIT]      = "RI",
70         [MSR_AMD64_SNP_ALT_INJ_BIT]             = "AI",
71         [MSR_AMD64_SNP_DEBUG_SWAP_BIT]          = "DebugSwap",
72         [MSR_AMD64_SNP_PREVENT_HOST_IBS_BIT]    = "NoHostIBS",
73         [MSR_AMD64_SNP_BTB_ISOLATION_BIT]       = "BTBIsol",
74         [MSR_AMD64_SNP_VMPL_SSS_BIT]            = "VmplSSS",
75         [MSR_AMD64_SNP_SECURE_TSC_BIT]          = "SecureTSC",
76         [MSR_AMD64_SNP_VMGEXIT_PARAM_BIT]       = "VMGExitParam",
77         [MSR_AMD64_SNP_IBS_VIRT_BIT]            = "IBSVirt",
78         [MSR_AMD64_SNP_VMSA_REG_PROT_BIT]       = "VMSARegProt",
79         [MSR_AMD64_SNP_SMT_PROT_BIT]            = "SMTProt",
80 };
81
82 /* For early boot hypervisor communication in SEV-ES enabled guests */
83 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
84
85 /*
86  * Needs to be in the .data section because we need it NULL before bss is
87  * cleared
88  */
89 static struct ghcb *boot_ghcb __section(".data");
90
91 /* Bitmap of SEV features supported by the hypervisor */
92 static u64 sev_hv_features __ro_after_init;
93
94 /* #VC handler runtime per-CPU data */
95 struct sev_es_runtime_data {
96         struct ghcb ghcb_page;
97
98         /*
99          * Reserve one page per CPU as backup storage for the unencrypted GHCB.
100          * It is needed when an NMI happens while the #VC handler uses the real
101          * GHCB, and the NMI handler itself is causing another #VC exception. In
102          * that case the GHCB content of the first handler needs to be backed up
103          * and restored.
104          */
105         struct ghcb backup_ghcb;
106
107         /*
108          * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
109          * There is no need for it to be atomic, because nothing is written to
110          * the GHCB between the read and the write of ghcb_active. So it is safe
111          * to use it when a nested #VC exception happens before the write.
112          *
113          * This is necessary for example in the #VC->NMI->#VC case when the NMI
114          * happens while the first #VC handler uses the GHCB. When the NMI code
115          * raises a second #VC handler it might overwrite the contents of the
116          * GHCB written by the first handler. To avoid this the content of the
117          * GHCB is saved and restored when the GHCB is detected to be in use
118          * already.
119          */
120         bool ghcb_active;
121         bool backup_ghcb_active;
122
123         /*
124          * Cached DR7 value - write it on DR7 writes and return it on reads.
125          * That value will never make it to the real hardware DR7 as debugging
126          * is currently unsupported in SEV-ES guests.
127          */
128         unsigned long dr7;
129 };
130
131 struct ghcb_state {
132         struct ghcb *ghcb;
133 };
134
135 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
136 static DEFINE_PER_CPU(struct sev_es_save_area *, sev_vmsa);
137
138 struct sev_config {
139         __u64 debug             : 1,
140
141               /*
142                * A flag used by __set_pages_state() that indicates when the
143                * per-CPU GHCB has been created and registered and thus can be
144                * used by the BSP instead of the early boot GHCB.
145                *
146                * For APs, the per-CPU GHCB is created before they are started
147                * and registered upon startup, so this flag can be used globally
148                * for the BSP and APs.
149                */
150               ghcbs_initialized : 1,
151
152               __reserved        : 62;
153 };
154
155 static struct sev_config sev_cfg __read_mostly;
156
157 static __always_inline bool on_vc_stack(struct pt_regs *regs)
158 {
159         unsigned long sp = regs->sp;
160
161         /* User-mode RSP is not trusted */
162         if (user_mode(regs))
163                 return false;
164
165         /* SYSCALL gap still has user-mode RSP */
166         if (ip_within_syscall_gap(regs))
167                 return false;
168
169         return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
170 }
171
172 /*
173  * This function handles the case when an NMI is raised in the #VC
174  * exception handler entry code, before the #VC handler has switched off
175  * its IST stack. In this case, the IST entry for #VC must be adjusted,
176  * so that any nested #VC exception will not overwrite the stack
177  * contents of the interrupted #VC handler.
178  *
179  * The IST entry is adjusted unconditionally so that it can be also be
180  * unconditionally adjusted back in __sev_es_ist_exit(). Otherwise a
181  * nested sev_es_ist_exit() call may adjust back the IST entry too
182  * early.
183  *
184  * The __sev_es_ist_enter() and __sev_es_ist_exit() functions always run
185  * on the NMI IST stack, as they are only called from NMI handling code
186  * right now.
187  */
188 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
189 {
190         unsigned long old_ist, new_ist;
191
192         /* Read old IST entry */
193         new_ist = old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
194
195         /*
196          * If NMI happened while on the #VC IST stack, set the new IST
197          * value below regs->sp, so that the interrupted stack frame is
198          * not overwritten by subsequent #VC exceptions.
199          */
200         if (on_vc_stack(regs))
201                 new_ist = regs->sp;
202
203         /*
204          * Reserve additional 8 bytes and store old IST value so this
205          * adjustment can be unrolled in __sev_es_ist_exit().
206          */
207         new_ist -= sizeof(old_ist);
208         *(unsigned long *)new_ist = old_ist;
209
210         /* Set new IST entry */
211         this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
212 }
213
214 void noinstr __sev_es_ist_exit(void)
215 {
216         unsigned long ist;
217
218         /* Read IST entry */
219         ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
220
221         if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
222                 return;
223
224         /* Read back old IST entry and write it to the TSS */
225         this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
226 }
227
228 /*
229  * Nothing shall interrupt this code path while holding the per-CPU
230  * GHCB. The backup GHCB is only for NMIs interrupting this path.
231  *
232  * Callers must disable local interrupts around it.
233  */
234 static noinstr struct ghcb *__sev_get_ghcb(struct ghcb_state *state)
235 {
236         struct sev_es_runtime_data *data;
237         struct ghcb *ghcb;
238
239         WARN_ON(!irqs_disabled());
240
241         data = this_cpu_read(runtime_data);
242         ghcb = &data->ghcb_page;
243
244         if (unlikely(data->ghcb_active)) {
245                 /* GHCB is already in use - save its contents */
246
247                 if (unlikely(data->backup_ghcb_active)) {
248                         /*
249                          * Backup-GHCB is also already in use. There is no way
250                          * to continue here so just kill the machine. To make
251                          * panic() work, mark GHCBs inactive so that messages
252                          * can be printed out.
253                          */
254                         data->ghcb_active        = false;
255                         data->backup_ghcb_active = false;
256
257                         instrumentation_begin();
258                         panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
259                         instrumentation_end();
260                 }
261
262                 /* Mark backup_ghcb active before writing to it */
263                 data->backup_ghcb_active = true;
264
265                 state->ghcb = &data->backup_ghcb;
266
267                 /* Backup GHCB content */
268                 *state->ghcb = *ghcb;
269         } else {
270                 state->ghcb = NULL;
271                 data->ghcb_active = true;
272         }
273
274         return ghcb;
275 }
276
277 static inline u64 sev_es_rd_ghcb_msr(void)
278 {
279         return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
280 }
281
282 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
283 {
284         u32 low, high;
285
286         low  = (u32)(val);
287         high = (u32)(val >> 32);
288
289         native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
290 }
291
292 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
293                                 unsigned char *buffer)
294 {
295         return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
296 }
297
298 static enum es_result __vc_decode_user_insn(struct es_em_ctxt *ctxt)
299 {
300         char buffer[MAX_INSN_SIZE];
301         int insn_bytes;
302
303         insn_bytes = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
304         if (insn_bytes == 0) {
305                 /* Nothing could be copied */
306                 ctxt->fi.vector     = X86_TRAP_PF;
307                 ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
308                 ctxt->fi.cr2        = ctxt->regs->ip;
309                 return ES_EXCEPTION;
310         } else if (insn_bytes == -EINVAL) {
311                 /* Effective RIP could not be calculated */
312                 ctxt->fi.vector     = X86_TRAP_GP;
313                 ctxt->fi.error_code = 0;
314                 ctxt->fi.cr2        = 0;
315                 return ES_EXCEPTION;
316         }
317
318         if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, insn_bytes))
319                 return ES_DECODE_FAILED;
320
321         if (ctxt->insn.immediate.got)
322                 return ES_OK;
323         else
324                 return ES_DECODE_FAILED;
325 }
326
327 static enum es_result __vc_decode_kern_insn(struct es_em_ctxt *ctxt)
328 {
329         char buffer[MAX_INSN_SIZE];
330         int res, ret;
331
332         res = vc_fetch_insn_kernel(ctxt, buffer);
333         if (res) {
334                 ctxt->fi.vector     = X86_TRAP_PF;
335                 ctxt->fi.error_code = X86_PF_INSTR;
336                 ctxt->fi.cr2        = ctxt->regs->ip;
337                 return ES_EXCEPTION;
338         }
339
340         ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
341         if (ret < 0)
342                 return ES_DECODE_FAILED;
343         else
344                 return ES_OK;
345 }
346
347 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
348 {
349         if (user_mode(ctxt->regs))
350                 return __vc_decode_user_insn(ctxt);
351         else
352                 return __vc_decode_kern_insn(ctxt);
353 }
354
355 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
356                                    char *dst, char *buf, size_t size)
357 {
358         unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
359
360         /*
361          * This function uses __put_user() independent of whether kernel or user
362          * memory is accessed. This works fine because __put_user() does no
363          * sanity checks of the pointer being accessed. All that it does is
364          * to report when the access failed.
365          *
366          * Also, this function runs in atomic context, so __put_user() is not
367          * allowed to sleep. The page-fault handler detects that it is running
368          * in atomic context and will not try to take mmap_sem and handle the
369          * fault, so additional pagefault_enable()/disable() calls are not
370          * needed.
371          *
372          * The access can't be done via copy_to_user() here because
373          * vc_write_mem() must not use string instructions to access unsafe
374          * memory. The reason is that MOVS is emulated by the #VC handler by
375          * splitting the move up into a read and a write and taking a nested #VC
376          * exception on whatever of them is the MMIO access. Using string
377          * instructions here would cause infinite nesting.
378          */
379         switch (size) {
380         case 1: {
381                 u8 d1;
382                 u8 __user *target = (u8 __user *)dst;
383
384                 memcpy(&d1, buf, 1);
385                 if (__put_user(d1, target))
386                         goto fault;
387                 break;
388         }
389         case 2: {
390                 u16 d2;
391                 u16 __user *target = (u16 __user *)dst;
392
393                 memcpy(&d2, buf, 2);
394                 if (__put_user(d2, target))
395                         goto fault;
396                 break;
397         }
398         case 4: {
399                 u32 d4;
400                 u32 __user *target = (u32 __user *)dst;
401
402                 memcpy(&d4, buf, 4);
403                 if (__put_user(d4, target))
404                         goto fault;
405                 break;
406         }
407         case 8: {
408                 u64 d8;
409                 u64 __user *target = (u64 __user *)dst;
410
411                 memcpy(&d8, buf, 8);
412                 if (__put_user(d8, target))
413                         goto fault;
414                 break;
415         }
416         default:
417                 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
418                 return ES_UNSUPPORTED;
419         }
420
421         return ES_OK;
422
423 fault:
424         if (user_mode(ctxt->regs))
425                 error_code |= X86_PF_USER;
426
427         ctxt->fi.vector = X86_TRAP_PF;
428         ctxt->fi.error_code = error_code;
429         ctxt->fi.cr2 = (unsigned long)dst;
430
431         return ES_EXCEPTION;
432 }
433
434 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
435                                   char *src, char *buf, size_t size)
436 {
437         unsigned long error_code = X86_PF_PROT;
438
439         /*
440          * This function uses __get_user() independent of whether kernel or user
441          * memory is accessed. This works fine because __get_user() does no
442          * sanity checks of the pointer being accessed. All that it does is
443          * to report when the access failed.
444          *
445          * Also, this function runs in atomic context, so __get_user() is not
446          * allowed to sleep. The page-fault handler detects that it is running
447          * in atomic context and will not try to take mmap_sem and handle the
448          * fault, so additional pagefault_enable()/disable() calls are not
449          * needed.
450          *
451          * The access can't be done via copy_from_user() here because
452          * vc_read_mem() must not use string instructions to access unsafe
453          * memory. The reason is that MOVS is emulated by the #VC handler by
454          * splitting the move up into a read and a write and taking a nested #VC
455          * exception on whatever of them is the MMIO access. Using string
456          * instructions here would cause infinite nesting.
457          */
458         switch (size) {
459         case 1: {
460                 u8 d1;
461                 u8 __user *s = (u8 __user *)src;
462
463                 if (__get_user(d1, s))
464                         goto fault;
465                 memcpy(buf, &d1, 1);
466                 break;
467         }
468         case 2: {
469                 u16 d2;
470                 u16 __user *s = (u16 __user *)src;
471
472                 if (__get_user(d2, s))
473                         goto fault;
474                 memcpy(buf, &d2, 2);
475                 break;
476         }
477         case 4: {
478                 u32 d4;
479                 u32 __user *s = (u32 __user *)src;
480
481                 if (__get_user(d4, s))
482                         goto fault;
483                 memcpy(buf, &d4, 4);
484                 break;
485         }
486         case 8: {
487                 u64 d8;
488                 u64 __user *s = (u64 __user *)src;
489                 if (__get_user(d8, s))
490                         goto fault;
491                 memcpy(buf, &d8, 8);
492                 break;
493         }
494         default:
495                 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
496                 return ES_UNSUPPORTED;
497         }
498
499         return ES_OK;
500
501 fault:
502         if (user_mode(ctxt->regs))
503                 error_code |= X86_PF_USER;
504
505         ctxt->fi.vector = X86_TRAP_PF;
506         ctxt->fi.error_code = error_code;
507         ctxt->fi.cr2 = (unsigned long)src;
508
509         return ES_EXCEPTION;
510 }
511
512 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
513                                            unsigned long vaddr, phys_addr_t *paddr)
514 {
515         unsigned long va = (unsigned long)vaddr;
516         unsigned int level;
517         phys_addr_t pa;
518         pgd_t *pgd;
519         pte_t *pte;
520
521         pgd = __va(read_cr3_pa());
522         pgd = &pgd[pgd_index(va)];
523         pte = lookup_address_in_pgd(pgd, va, &level);
524         if (!pte) {
525                 ctxt->fi.vector     = X86_TRAP_PF;
526                 ctxt->fi.cr2        = vaddr;
527                 ctxt->fi.error_code = 0;
528
529                 if (user_mode(ctxt->regs))
530                         ctxt->fi.error_code |= X86_PF_USER;
531
532                 return ES_EXCEPTION;
533         }
534
535         if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
536                 /* Emulated MMIO to/from encrypted memory not supported */
537                 return ES_UNSUPPORTED;
538
539         pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
540         pa |= va & ~page_level_mask(level);
541
542         *paddr = pa;
543
544         return ES_OK;
545 }
546
547 static enum es_result vc_ioio_check(struct es_em_ctxt *ctxt, u16 port, size_t size)
548 {
549         BUG_ON(size > 4);
550
551         if (user_mode(ctxt->regs)) {
552                 struct thread_struct *t = &current->thread;
553                 struct io_bitmap *iobm = t->io_bitmap;
554                 size_t idx;
555
556                 if (!iobm)
557                         goto fault;
558
559                 for (idx = port; idx < port + size; ++idx) {
560                         if (test_bit(idx, iobm->bitmap))
561                                 goto fault;
562                 }
563         }
564
565         return ES_OK;
566
567 fault:
568         ctxt->fi.vector = X86_TRAP_GP;
569         ctxt->fi.error_code = 0;
570
571         return ES_EXCEPTION;
572 }
573
574 /* Include code shared with pre-decompression boot stage */
575 #include "sev-shared.c"
576
577 static noinstr void __sev_put_ghcb(struct ghcb_state *state)
578 {
579         struct sev_es_runtime_data *data;
580         struct ghcb *ghcb;
581
582         WARN_ON(!irqs_disabled());
583
584         data = this_cpu_read(runtime_data);
585         ghcb = &data->ghcb_page;
586
587         if (state->ghcb) {
588                 /* Restore GHCB from Backup */
589                 *ghcb = *state->ghcb;
590                 data->backup_ghcb_active = false;
591                 state->ghcb = NULL;
592         } else {
593                 /*
594                  * Invalidate the GHCB so a VMGEXIT instruction issued
595                  * from userspace won't appear to be valid.
596                  */
597                 vc_ghcb_invalidate(ghcb);
598                 data->ghcb_active = false;
599         }
600 }
601
602 void noinstr __sev_es_nmi_complete(void)
603 {
604         struct ghcb_state state;
605         struct ghcb *ghcb;
606
607         ghcb = __sev_get_ghcb(&state);
608
609         vc_ghcb_invalidate(ghcb);
610         ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
611         ghcb_set_sw_exit_info_1(ghcb, 0);
612         ghcb_set_sw_exit_info_2(ghcb, 0);
613
614         sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
615         VMGEXIT();
616
617         __sev_put_ghcb(&state);
618 }
619
620 static u64 __init get_secrets_page(void)
621 {
622         u64 pa_data = boot_params.cc_blob_address;
623         struct cc_blob_sev_info info;
624         void *map;
625
626         /*
627          * The CC blob contains the address of the secrets page, check if the
628          * blob is present.
629          */
630         if (!pa_data)
631                 return 0;
632
633         map = early_memremap(pa_data, sizeof(info));
634         if (!map) {
635                 pr_err("Unable to locate SNP secrets page: failed to map the Confidential Computing blob.\n");
636                 return 0;
637         }
638         memcpy(&info, map, sizeof(info));
639         early_memunmap(map, sizeof(info));
640
641         /* smoke-test the secrets page passed */
642         if (!info.secrets_phys || info.secrets_len != PAGE_SIZE)
643                 return 0;
644
645         return info.secrets_phys;
646 }
647
648 static u64 __init get_snp_jump_table_addr(void)
649 {
650         struct snp_secrets_page_layout *layout;
651         void __iomem *mem;
652         u64 pa, addr;
653
654         pa = get_secrets_page();
655         if (!pa)
656                 return 0;
657
658         mem = ioremap_encrypted(pa, PAGE_SIZE);
659         if (!mem) {
660                 pr_err("Unable to locate AP jump table address: failed to map the SNP secrets page.\n");
661                 return 0;
662         }
663
664         layout = (__force struct snp_secrets_page_layout *)mem;
665
666         addr = layout->os_area.ap_jump_table_pa;
667         iounmap(mem);
668
669         return addr;
670 }
671
672 static u64 __init get_jump_table_addr(void)
673 {
674         struct ghcb_state state;
675         unsigned long flags;
676         struct ghcb *ghcb;
677         u64 ret = 0;
678
679         if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
680                 return get_snp_jump_table_addr();
681
682         local_irq_save(flags);
683
684         ghcb = __sev_get_ghcb(&state);
685
686         vc_ghcb_invalidate(ghcb);
687         ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
688         ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
689         ghcb_set_sw_exit_info_2(ghcb, 0);
690
691         sev_es_wr_ghcb_msr(__pa(ghcb));
692         VMGEXIT();
693
694         if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
695             ghcb_sw_exit_info_2_is_valid(ghcb))
696                 ret = ghcb->save.sw_exit_info_2;
697
698         __sev_put_ghcb(&state);
699
700         local_irq_restore(flags);
701
702         return ret;
703 }
704
705 static void __head
706 early_set_pages_state(unsigned long vaddr, unsigned long paddr,
707                       unsigned long npages, enum psc_op op)
708 {
709         unsigned long paddr_end;
710         u64 val;
711         int ret;
712
713         vaddr = vaddr & PAGE_MASK;
714
715         paddr = paddr & PAGE_MASK;
716         paddr_end = paddr + (npages << PAGE_SHIFT);
717
718         while (paddr < paddr_end) {
719                 if (op == SNP_PAGE_STATE_SHARED) {
720                         /* Page validation must be rescinded before changing to shared */
721                         ret = pvalidate(vaddr, RMP_PG_SIZE_4K, false);
722                         if (WARN(ret, "Failed to validate address 0x%lx ret %d", paddr, ret))
723                                 goto e_term;
724                 }
725
726                 /*
727                  * Use the MSR protocol because this function can be called before
728                  * the GHCB is established.
729                  */
730                 sev_es_wr_ghcb_msr(GHCB_MSR_PSC_REQ_GFN(paddr >> PAGE_SHIFT, op));
731                 VMGEXIT();
732
733                 val = sev_es_rd_ghcb_msr();
734
735                 if (WARN(GHCB_RESP_CODE(val) != GHCB_MSR_PSC_RESP,
736                          "Wrong PSC response code: 0x%x\n",
737                          (unsigned int)GHCB_RESP_CODE(val)))
738                         goto e_term;
739
740                 if (WARN(GHCB_MSR_PSC_RESP_VAL(val),
741                          "Failed to change page state to '%s' paddr 0x%lx error 0x%llx\n",
742                          op == SNP_PAGE_STATE_PRIVATE ? "private" : "shared",
743                          paddr, GHCB_MSR_PSC_RESP_VAL(val)))
744                         goto e_term;
745
746                 if (op == SNP_PAGE_STATE_PRIVATE) {
747                         /* Page validation must be performed after changing to private */
748                         ret = pvalidate(vaddr, RMP_PG_SIZE_4K, true);
749                         if (WARN(ret, "Failed to validate address 0x%lx ret %d", paddr, ret))
750                                 goto e_term;
751                 }
752
753                 vaddr += PAGE_SIZE;
754                 paddr += PAGE_SIZE;
755         }
756
757         return;
758
759 e_term:
760         sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
761 }
762
763 void __head early_snp_set_memory_private(unsigned long vaddr, unsigned long paddr,
764                                          unsigned long npages)
765 {
766         /*
767          * This can be invoked in early boot while running identity mapped, so
768          * use an open coded check for SNP instead of using cc_platform_has().
769          * This eliminates worries about jump tables or checking boot_cpu_data
770          * in the cc_platform_has() function.
771          */
772         if (!(RIP_REL_REF(sev_status) & MSR_AMD64_SEV_SNP_ENABLED))
773                 return;
774
775          /*
776           * Ask the hypervisor to mark the memory pages as private in the RMP
777           * table.
778           */
779         early_set_pages_state(vaddr, paddr, npages, SNP_PAGE_STATE_PRIVATE);
780 }
781
782 void __init early_snp_set_memory_shared(unsigned long vaddr, unsigned long paddr,
783                                         unsigned long npages)
784 {
785         /*
786          * This can be invoked in early boot while running identity mapped, so
787          * use an open coded check for SNP instead of using cc_platform_has().
788          * This eliminates worries about jump tables or checking boot_cpu_data
789          * in the cc_platform_has() function.
790          */
791         if (!(RIP_REL_REF(sev_status) & MSR_AMD64_SEV_SNP_ENABLED))
792                 return;
793
794          /* Ask hypervisor to mark the memory pages shared in the RMP table. */
795         early_set_pages_state(vaddr, paddr, npages, SNP_PAGE_STATE_SHARED);
796 }
797
798 void __init snp_prep_memory(unsigned long paddr, unsigned int sz, enum psc_op op)
799 {
800         unsigned long vaddr, npages;
801
802         vaddr = (unsigned long)__va(paddr);
803         npages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
804
805         if (op == SNP_PAGE_STATE_PRIVATE)
806                 early_snp_set_memory_private(vaddr, paddr, npages);
807         else if (op == SNP_PAGE_STATE_SHARED)
808                 early_snp_set_memory_shared(vaddr, paddr, npages);
809         else
810                 WARN(1, "invalid memory op %d\n", op);
811 }
812
813 static unsigned long __set_pages_state(struct snp_psc_desc *data, unsigned long vaddr,
814                                        unsigned long vaddr_end, int op)
815 {
816         struct ghcb_state state;
817         bool use_large_entry;
818         struct psc_hdr *hdr;
819         struct psc_entry *e;
820         unsigned long flags;
821         unsigned long pfn;
822         struct ghcb *ghcb;
823         int i;
824
825         hdr = &data->hdr;
826         e = data->entries;
827
828         memset(data, 0, sizeof(*data));
829         i = 0;
830
831         while (vaddr < vaddr_end && i < ARRAY_SIZE(data->entries)) {
832                 hdr->end_entry = i;
833
834                 if (is_vmalloc_addr((void *)vaddr)) {
835                         pfn = vmalloc_to_pfn((void *)vaddr);
836                         use_large_entry = false;
837                 } else {
838                         pfn = __pa(vaddr) >> PAGE_SHIFT;
839                         use_large_entry = true;
840                 }
841
842                 e->gfn = pfn;
843                 e->operation = op;
844
845                 if (use_large_entry && IS_ALIGNED(vaddr, PMD_SIZE) &&
846                     (vaddr_end - vaddr) >= PMD_SIZE) {
847                         e->pagesize = RMP_PG_SIZE_2M;
848                         vaddr += PMD_SIZE;
849                 } else {
850                         e->pagesize = RMP_PG_SIZE_4K;
851                         vaddr += PAGE_SIZE;
852                 }
853
854                 e++;
855                 i++;
856         }
857
858         /* Page validation must be rescinded before changing to shared */
859         if (op == SNP_PAGE_STATE_SHARED)
860                 pvalidate_pages(data);
861
862         local_irq_save(flags);
863
864         if (sev_cfg.ghcbs_initialized)
865                 ghcb = __sev_get_ghcb(&state);
866         else
867                 ghcb = boot_ghcb;
868
869         /* Invoke the hypervisor to perform the page state changes */
870         if (!ghcb || vmgexit_psc(ghcb, data))
871                 sev_es_terminate(SEV_TERM_SET_LINUX, GHCB_TERM_PSC);
872
873         if (sev_cfg.ghcbs_initialized)
874                 __sev_put_ghcb(&state);
875
876         local_irq_restore(flags);
877
878         /* Page validation must be performed after changing to private */
879         if (op == SNP_PAGE_STATE_PRIVATE)
880                 pvalidate_pages(data);
881
882         return vaddr;
883 }
884
885 static void set_pages_state(unsigned long vaddr, unsigned long npages, int op)
886 {
887         struct snp_psc_desc desc;
888         unsigned long vaddr_end;
889
890         /* Use the MSR protocol when a GHCB is not available. */
891         if (!boot_ghcb)
892                 return early_set_pages_state(vaddr, __pa(vaddr), npages, op);
893
894         vaddr = vaddr & PAGE_MASK;
895         vaddr_end = vaddr + (npages << PAGE_SHIFT);
896
897         while (vaddr < vaddr_end)
898                 vaddr = __set_pages_state(&desc, vaddr, vaddr_end, op);
899 }
900
901 void snp_set_memory_shared(unsigned long vaddr, unsigned long npages)
902 {
903         if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
904                 return;
905
906         set_pages_state(vaddr, npages, SNP_PAGE_STATE_SHARED);
907 }
908
909 void snp_set_memory_private(unsigned long vaddr, unsigned long npages)
910 {
911         if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
912                 return;
913
914         set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
915 }
916
917 void snp_accept_memory(phys_addr_t start, phys_addr_t end)
918 {
919         unsigned long vaddr, npages;
920
921         if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
922                 return;
923
924         vaddr = (unsigned long)__va(start);
925         npages = (end - start) >> PAGE_SHIFT;
926
927         set_pages_state(vaddr, npages, SNP_PAGE_STATE_PRIVATE);
928 }
929
930 static int snp_set_vmsa(void *va, bool vmsa)
931 {
932         u64 attrs;
933
934         /*
935          * Running at VMPL0 allows the kernel to change the VMSA bit for a page
936          * using the RMPADJUST instruction. However, for the instruction to
937          * succeed it must target the permissions of a lesser privileged
938          * (higher numbered) VMPL level, so use VMPL1 (refer to the RMPADJUST
939          * instruction in the AMD64 APM Volume 3).
940          */
941         attrs = 1;
942         if (vmsa)
943                 attrs |= RMPADJUST_VMSA_PAGE_BIT;
944
945         return rmpadjust((unsigned long)va, RMP_PG_SIZE_4K, attrs);
946 }
947
948 #define __ATTR_BASE             (SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK)
949 #define INIT_CS_ATTRIBS         (__ATTR_BASE | SVM_SELECTOR_READ_MASK | SVM_SELECTOR_CODE_MASK)
950 #define INIT_DS_ATTRIBS         (__ATTR_BASE | SVM_SELECTOR_WRITE_MASK)
951
952 #define INIT_LDTR_ATTRIBS       (SVM_SELECTOR_P_MASK | 2)
953 #define INIT_TR_ATTRIBS         (SVM_SELECTOR_P_MASK | 3)
954
955 static void *snp_alloc_vmsa_page(void)
956 {
957         struct page *p;
958
959         /*
960          * Allocate VMSA page to work around the SNP erratum where the CPU will
961          * incorrectly signal an RMP violation #PF if a large page (2MB or 1GB)
962          * collides with the RMP entry of VMSA page. The recommended workaround
963          * is to not use a large page.
964          *
965          * Allocate an 8k page which is also 8k-aligned.
966          */
967         p = alloc_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO, 1);
968         if (!p)
969                 return NULL;
970
971         split_page(p, 1);
972
973         /* Free the first 4k. This page may be 2M/1G aligned and cannot be used. */
974         __free_page(p);
975
976         return page_address(p + 1);
977 }
978
979 static void snp_cleanup_vmsa(struct sev_es_save_area *vmsa)
980 {
981         int err;
982
983         err = snp_set_vmsa(vmsa, false);
984         if (err)
985                 pr_err("clear VMSA page failed (%u), leaking page\n", err);
986         else
987                 free_page((unsigned long)vmsa);
988 }
989
990 static int wakeup_cpu_via_vmgexit(u32 apic_id, unsigned long start_ip)
991 {
992         struct sev_es_save_area *cur_vmsa, *vmsa;
993         struct ghcb_state state;
994         unsigned long flags;
995         struct ghcb *ghcb;
996         u8 sipi_vector;
997         int cpu, ret;
998         u64 cr4;
999
1000         /*
1001          * The hypervisor SNP feature support check has happened earlier, just check
1002          * the AP_CREATION one here.
1003          */
1004         if (!(sev_hv_features & GHCB_HV_FT_SNP_AP_CREATION))
1005                 return -EOPNOTSUPP;
1006
1007         /*
1008          * Verify the desired start IP against the known trampoline start IP
1009          * to catch any future new trampolines that may be introduced that
1010          * would require a new protected guest entry point.
1011          */
1012         if (WARN_ONCE(start_ip != real_mode_header->trampoline_start,
1013                       "Unsupported SNP start_ip: %lx\n", start_ip))
1014                 return -EINVAL;
1015
1016         /* Override start_ip with known protected guest start IP */
1017         start_ip = real_mode_header->sev_es_trampoline_start;
1018
1019         /* Find the logical CPU for the APIC ID */
1020         for_each_present_cpu(cpu) {
1021                 if (arch_match_cpu_phys_id(cpu, apic_id))
1022                         break;
1023         }
1024         if (cpu >= nr_cpu_ids)
1025                 return -EINVAL;
1026
1027         cur_vmsa = per_cpu(sev_vmsa, cpu);
1028
1029         /*
1030          * A new VMSA is created each time because there is no guarantee that
1031          * the current VMSA is the kernels or that the vCPU is not running. If
1032          * an attempt was done to use the current VMSA with a running vCPU, a
1033          * #VMEXIT of that vCPU would wipe out all of the settings being done
1034          * here.
1035          */
1036         vmsa = (struct sev_es_save_area *)snp_alloc_vmsa_page();
1037         if (!vmsa)
1038                 return -ENOMEM;
1039
1040         /* CR4 should maintain the MCE value */
1041         cr4 = native_read_cr4() & X86_CR4_MCE;
1042
1043         /* Set the CS value based on the start_ip converted to a SIPI vector */
1044         sipi_vector             = (start_ip >> 12);
1045         vmsa->cs.base           = sipi_vector << 12;
1046         vmsa->cs.limit          = AP_INIT_CS_LIMIT;
1047         vmsa->cs.attrib         = INIT_CS_ATTRIBS;
1048         vmsa->cs.selector       = sipi_vector << 8;
1049
1050         /* Set the RIP value based on start_ip */
1051         vmsa->rip               = start_ip & 0xfff;
1052
1053         /* Set AP INIT defaults as documented in the APM */
1054         vmsa->ds.limit          = AP_INIT_DS_LIMIT;
1055         vmsa->ds.attrib         = INIT_DS_ATTRIBS;
1056         vmsa->es                = vmsa->ds;
1057         vmsa->fs                = vmsa->ds;
1058         vmsa->gs                = vmsa->ds;
1059         vmsa->ss                = vmsa->ds;
1060
1061         vmsa->gdtr.limit        = AP_INIT_GDTR_LIMIT;
1062         vmsa->ldtr.limit        = AP_INIT_LDTR_LIMIT;
1063         vmsa->ldtr.attrib       = INIT_LDTR_ATTRIBS;
1064         vmsa->idtr.limit        = AP_INIT_IDTR_LIMIT;
1065         vmsa->tr.limit          = AP_INIT_TR_LIMIT;
1066         vmsa->tr.attrib         = INIT_TR_ATTRIBS;
1067
1068         vmsa->cr4               = cr4;
1069         vmsa->cr0               = AP_INIT_CR0_DEFAULT;
1070         vmsa->dr7               = DR7_RESET_VALUE;
1071         vmsa->dr6               = AP_INIT_DR6_DEFAULT;
1072         vmsa->rflags            = AP_INIT_RFLAGS_DEFAULT;
1073         vmsa->g_pat             = AP_INIT_GPAT_DEFAULT;
1074         vmsa->xcr0              = AP_INIT_XCR0_DEFAULT;
1075         vmsa->mxcsr             = AP_INIT_MXCSR_DEFAULT;
1076         vmsa->x87_ftw           = AP_INIT_X87_FTW_DEFAULT;
1077         vmsa->x87_fcw           = AP_INIT_X87_FCW_DEFAULT;
1078
1079         /* SVME must be set. */
1080         vmsa->efer              = EFER_SVME;
1081
1082         /*
1083          * Set the SNP-specific fields for this VMSA:
1084          *   VMPL level
1085          *   SEV_FEATURES (matches the SEV STATUS MSR right shifted 2 bits)
1086          */
1087         vmsa->vmpl              = 0;
1088         vmsa->sev_features      = sev_status >> 2;
1089
1090         /* Switch the page over to a VMSA page now that it is initialized */
1091         ret = snp_set_vmsa(vmsa, true);
1092         if (ret) {
1093                 pr_err("set VMSA page failed (%u)\n", ret);
1094                 free_page((unsigned long)vmsa);
1095
1096                 return -EINVAL;
1097         }
1098
1099         /* Issue VMGEXIT AP Creation NAE event */
1100         local_irq_save(flags);
1101
1102         ghcb = __sev_get_ghcb(&state);
1103
1104         vc_ghcb_invalidate(ghcb);
1105         ghcb_set_rax(ghcb, vmsa->sev_features);
1106         ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_CREATION);
1107         ghcb_set_sw_exit_info_1(ghcb, ((u64)apic_id << 32) | SVM_VMGEXIT_AP_CREATE);
1108         ghcb_set_sw_exit_info_2(ghcb, __pa(vmsa));
1109
1110         sev_es_wr_ghcb_msr(__pa(ghcb));
1111         VMGEXIT();
1112
1113         if (!ghcb_sw_exit_info_1_is_valid(ghcb) ||
1114             lower_32_bits(ghcb->save.sw_exit_info_1)) {
1115                 pr_err("SNP AP Creation error\n");
1116                 ret = -EINVAL;
1117         }
1118
1119         __sev_put_ghcb(&state);
1120
1121         local_irq_restore(flags);
1122
1123         /* Perform cleanup if there was an error */
1124         if (ret) {
1125                 snp_cleanup_vmsa(vmsa);
1126                 vmsa = NULL;
1127         }
1128
1129         /* Free up any previous VMSA page */
1130         if (cur_vmsa)
1131                 snp_cleanup_vmsa(cur_vmsa);
1132
1133         /* Record the current VMSA page */
1134         per_cpu(sev_vmsa, cpu) = vmsa;
1135
1136         return ret;
1137 }
1138
1139 void __init snp_set_wakeup_secondary_cpu(void)
1140 {
1141         if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1142                 return;
1143
1144         /*
1145          * Always set this override if SNP is enabled. This makes it the
1146          * required method to start APs under SNP. If the hypervisor does
1147          * not support AP creation, then no APs will be started.
1148          */
1149         apic_update_callback(wakeup_secondary_cpu, wakeup_cpu_via_vmgexit);
1150 }
1151
1152 int __init sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
1153 {
1154         u16 startup_cs, startup_ip;
1155         phys_addr_t jump_table_pa;
1156         u64 jump_table_addr;
1157         u16 __iomem *jump_table;
1158
1159         jump_table_addr = get_jump_table_addr();
1160
1161         /* On UP guests there is no jump table so this is not a failure */
1162         if (!jump_table_addr)
1163                 return 0;
1164
1165         /* Check if AP Jump Table is page-aligned */
1166         if (jump_table_addr & ~PAGE_MASK)
1167                 return -EINVAL;
1168
1169         jump_table_pa = jump_table_addr & PAGE_MASK;
1170
1171         startup_cs = (u16)(rmh->trampoline_start >> 4);
1172         startup_ip = (u16)(rmh->sev_es_trampoline_start -
1173                            rmh->trampoline_start);
1174
1175         jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
1176         if (!jump_table)
1177                 return -EIO;
1178
1179         writew(startup_ip, &jump_table[0]);
1180         writew(startup_cs, &jump_table[1]);
1181
1182         iounmap(jump_table);
1183
1184         return 0;
1185 }
1186
1187 /*
1188  * This is needed by the OVMF UEFI firmware which will use whatever it finds in
1189  * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
1190  * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
1191  */
1192 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
1193 {
1194         struct sev_es_runtime_data *data;
1195         unsigned long address, pflags;
1196         int cpu;
1197         u64 pfn;
1198
1199         if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1200                 return 0;
1201
1202         pflags = _PAGE_NX | _PAGE_RW;
1203
1204         for_each_possible_cpu(cpu) {
1205                 data = per_cpu(runtime_data, cpu);
1206
1207                 address = __pa(&data->ghcb_page);
1208                 pfn = address >> PAGE_SHIFT;
1209
1210                 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
1211                         return 1;
1212         }
1213
1214         return 0;
1215 }
1216
1217 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1218 {
1219         struct pt_regs *regs = ctxt->regs;
1220         enum es_result ret;
1221         u64 exit_info_1;
1222
1223         /* Is it a WRMSR? */
1224         exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
1225
1226         ghcb_set_rcx(ghcb, regs->cx);
1227         if (exit_info_1) {
1228                 ghcb_set_rax(ghcb, regs->ax);
1229                 ghcb_set_rdx(ghcb, regs->dx);
1230         }
1231
1232         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
1233
1234         if ((ret == ES_OK) && (!exit_info_1)) {
1235                 regs->ax = ghcb->save.rax;
1236                 regs->dx = ghcb->save.rdx;
1237         }
1238
1239         return ret;
1240 }
1241
1242 static void snp_register_per_cpu_ghcb(void)
1243 {
1244         struct sev_es_runtime_data *data;
1245         struct ghcb *ghcb;
1246
1247         data = this_cpu_read(runtime_data);
1248         ghcb = &data->ghcb_page;
1249
1250         snp_register_ghcb_early(__pa(ghcb));
1251 }
1252
1253 void setup_ghcb(void)
1254 {
1255         if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1256                 return;
1257
1258         /*
1259          * Check whether the runtime #VC exception handler is active. It uses
1260          * the per-CPU GHCB page which is set up by sev_es_init_vc_handling().
1261          *
1262          * If SNP is active, register the per-CPU GHCB page so that the runtime
1263          * exception handler can use it.
1264          */
1265         if (initial_vc_handler == (unsigned long)kernel_exc_vmm_communication) {
1266                 if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1267                         snp_register_per_cpu_ghcb();
1268
1269                 sev_cfg.ghcbs_initialized = true;
1270
1271                 return;
1272         }
1273
1274         /*
1275          * Make sure the hypervisor talks a supported protocol.
1276          * This gets called only in the BSP boot phase.
1277          */
1278         if (!sev_es_negotiate_protocol())
1279                 sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1280
1281         /*
1282          * Clear the boot_ghcb. The first exception comes in before the bss
1283          * section is cleared.
1284          */
1285         memset(&boot_ghcb_page, 0, PAGE_SIZE);
1286
1287         /* Alright - Make the boot-ghcb public */
1288         boot_ghcb = &boot_ghcb_page;
1289
1290         /* SNP guest requires that GHCB GPA must be registered. */
1291         if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
1292                 snp_register_ghcb_early(__pa(&boot_ghcb_page));
1293 }
1294
1295 #ifdef CONFIG_HOTPLUG_CPU
1296 static void sev_es_ap_hlt_loop(void)
1297 {
1298         struct ghcb_state state;
1299         struct ghcb *ghcb;
1300
1301         ghcb = __sev_get_ghcb(&state);
1302
1303         while (true) {
1304                 vc_ghcb_invalidate(ghcb);
1305                 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
1306                 ghcb_set_sw_exit_info_1(ghcb, 0);
1307                 ghcb_set_sw_exit_info_2(ghcb, 0);
1308
1309                 sev_es_wr_ghcb_msr(__pa(ghcb));
1310                 VMGEXIT();
1311
1312                 /* Wakeup signal? */
1313                 if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
1314                     ghcb->save.sw_exit_info_2)
1315                         break;
1316         }
1317
1318         __sev_put_ghcb(&state);
1319 }
1320
1321 /*
1322  * Play_dead handler when running under SEV-ES. This is needed because
1323  * the hypervisor can't deliver an SIPI request to restart the AP.
1324  * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
1325  * hypervisor wakes it up again.
1326  */
1327 static void sev_es_play_dead(void)
1328 {
1329         play_dead_common();
1330
1331         /* IRQs now disabled */
1332
1333         sev_es_ap_hlt_loop();
1334
1335         /*
1336          * If we get here, the VCPU was woken up again. Jump to CPU
1337          * startup code to get it back online.
1338          */
1339         soft_restart_cpu();
1340 }
1341 #else  /* CONFIG_HOTPLUG_CPU */
1342 #define sev_es_play_dead        native_play_dead
1343 #endif /* CONFIG_HOTPLUG_CPU */
1344
1345 #ifdef CONFIG_SMP
1346 static void __init sev_es_setup_play_dead(void)
1347 {
1348         smp_ops.play_dead = sev_es_play_dead;
1349 }
1350 #else
1351 static inline void sev_es_setup_play_dead(void) { }
1352 #endif
1353
1354 static void __init alloc_runtime_data(int cpu)
1355 {
1356         struct sev_es_runtime_data *data;
1357
1358         data = memblock_alloc(sizeof(*data), PAGE_SIZE);
1359         if (!data)
1360                 panic("Can't allocate SEV-ES runtime data");
1361
1362         per_cpu(runtime_data, cpu) = data;
1363 }
1364
1365 static void __init init_ghcb(int cpu)
1366 {
1367         struct sev_es_runtime_data *data;
1368         int err;
1369
1370         data = per_cpu(runtime_data, cpu);
1371
1372         err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
1373                                          sizeof(data->ghcb_page));
1374         if (err)
1375                 panic("Can't map GHCBs unencrypted");
1376
1377         memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
1378
1379         data->ghcb_active = false;
1380         data->backup_ghcb_active = false;
1381 }
1382
1383 void __init sev_es_init_vc_handling(void)
1384 {
1385         int cpu;
1386
1387         BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
1388
1389         if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
1390                 return;
1391
1392         if (!sev_es_check_cpu_features())
1393                 panic("SEV-ES CPU Features missing");
1394
1395         /*
1396          * SNP is supported in v2 of the GHCB spec which mandates support for HV
1397          * features.
1398          */
1399         if (cc_platform_has(CC_ATTR_GUEST_SEV_SNP)) {
1400                 sev_hv_features = get_hv_features();
1401
1402                 if (!(sev_hv_features & GHCB_HV_FT_SNP))
1403                         sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
1404         }
1405
1406         /* Initialize per-cpu GHCB pages */
1407         for_each_possible_cpu(cpu) {
1408                 alloc_runtime_data(cpu);
1409                 init_ghcb(cpu);
1410         }
1411
1412         sev_es_setup_play_dead();
1413
1414         /* Secondary CPUs use the runtime #VC handler */
1415         initial_vc_handler = (unsigned long)kernel_exc_vmm_communication;
1416 }
1417
1418 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
1419 {
1420         int trapnr = ctxt->fi.vector;
1421
1422         if (trapnr == X86_TRAP_PF)
1423                 native_write_cr2(ctxt->fi.cr2);
1424
1425         ctxt->regs->orig_ax = ctxt->fi.error_code;
1426         do_early_exception(ctxt->regs, trapnr);
1427 }
1428
1429 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
1430 {
1431         long *reg_array;
1432         int offset;
1433
1434         reg_array = (long *)ctxt->regs;
1435         offset    = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
1436
1437         if (offset < 0)
1438                 return NULL;
1439
1440         offset /= sizeof(long);
1441
1442         return reg_array + offset;
1443 }
1444 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
1445                                  unsigned int bytes, bool read)
1446 {
1447         u64 exit_code, exit_info_1, exit_info_2;
1448         unsigned long ghcb_pa = __pa(ghcb);
1449         enum es_result res;
1450         phys_addr_t paddr;
1451         void __user *ref;
1452
1453         ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
1454         if (ref == (void __user *)-1L)
1455                 return ES_UNSUPPORTED;
1456
1457         exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
1458
1459         res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
1460         if (res != ES_OK) {
1461                 if (res == ES_EXCEPTION && !read)
1462                         ctxt->fi.error_code |= X86_PF_WRITE;
1463
1464                 return res;
1465         }
1466
1467         exit_info_1 = paddr;
1468         /* Can never be greater than 8 */
1469         exit_info_2 = bytes;
1470
1471         ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
1472
1473         return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
1474 }
1475
1476 /*
1477  * The MOVS instruction has two memory operands, which raises the
1478  * problem that it is not known whether the access to the source or the
1479  * destination caused the #VC exception (and hence whether an MMIO read
1480  * or write operation needs to be emulated).
1481  *
1482  * Instead of playing games with walking page-tables and trying to guess
1483  * whether the source or destination is an MMIO range, split the move
1484  * into two operations, a read and a write with only one memory operand.
1485  * This will cause a nested #VC exception on the MMIO address which can
1486  * then be handled.
1487  *
1488  * This implementation has the benefit that it also supports MOVS where
1489  * source _and_ destination are MMIO regions.
1490  *
1491  * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
1492  * rare operation. If it turns out to be a performance problem the split
1493  * operations can be moved to memcpy_fromio() and memcpy_toio().
1494  */
1495 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
1496                                           unsigned int bytes)
1497 {
1498         unsigned long ds_base, es_base;
1499         unsigned char *src, *dst;
1500         unsigned char buffer[8];
1501         enum es_result ret;
1502         bool rep;
1503         int off;
1504
1505         ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
1506         es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
1507
1508         if (ds_base == -1L || es_base == -1L) {
1509                 ctxt->fi.vector = X86_TRAP_GP;
1510                 ctxt->fi.error_code = 0;
1511                 return ES_EXCEPTION;
1512         }
1513
1514         src = ds_base + (unsigned char *)ctxt->regs->si;
1515         dst = es_base + (unsigned char *)ctxt->regs->di;
1516
1517         ret = vc_read_mem(ctxt, src, buffer, bytes);
1518         if (ret != ES_OK)
1519                 return ret;
1520
1521         ret = vc_write_mem(ctxt, dst, buffer, bytes);
1522         if (ret != ES_OK)
1523                 return ret;
1524
1525         if (ctxt->regs->flags & X86_EFLAGS_DF)
1526                 off = -bytes;
1527         else
1528                 off =  bytes;
1529
1530         ctxt->regs->si += off;
1531         ctxt->regs->di += off;
1532
1533         rep = insn_has_rep_prefix(&ctxt->insn);
1534         if (rep)
1535                 ctxt->regs->cx -= 1;
1536
1537         if (!rep || ctxt->regs->cx == 0)
1538                 return ES_OK;
1539         else
1540                 return ES_RETRY;
1541 }
1542
1543 static enum es_result vc_handle_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1544 {
1545         struct insn *insn = &ctxt->insn;
1546         enum insn_mmio_type mmio;
1547         unsigned int bytes = 0;
1548         enum es_result ret;
1549         u8 sign_byte;
1550         long *reg_data;
1551
1552         mmio = insn_decode_mmio(insn, &bytes);
1553         if (mmio == INSN_MMIO_DECODE_FAILED)
1554                 return ES_DECODE_FAILED;
1555
1556         if (mmio != INSN_MMIO_WRITE_IMM && mmio != INSN_MMIO_MOVS) {
1557                 reg_data = insn_get_modrm_reg_ptr(insn, ctxt->regs);
1558                 if (!reg_data)
1559                         return ES_DECODE_FAILED;
1560         }
1561
1562         if (user_mode(ctxt->regs))
1563                 return ES_UNSUPPORTED;
1564
1565         switch (mmio) {
1566         case INSN_MMIO_WRITE:
1567                 memcpy(ghcb->shared_buffer, reg_data, bytes);
1568                 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1569                 break;
1570         case INSN_MMIO_WRITE_IMM:
1571                 memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
1572                 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1573                 break;
1574         case INSN_MMIO_READ:
1575                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1576                 if (ret)
1577                         break;
1578
1579                 /* Zero-extend for 32-bit operation */
1580                 if (bytes == 4)
1581                         *reg_data = 0;
1582
1583                 memcpy(reg_data, ghcb->shared_buffer, bytes);
1584                 break;
1585         case INSN_MMIO_READ_ZERO_EXTEND:
1586                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1587                 if (ret)
1588                         break;
1589
1590                 /* Zero extend based on operand size */
1591                 memset(reg_data, 0, insn->opnd_bytes);
1592                 memcpy(reg_data, ghcb->shared_buffer, bytes);
1593                 break;
1594         case INSN_MMIO_READ_SIGN_EXTEND:
1595                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1596                 if (ret)
1597                         break;
1598
1599                 if (bytes == 1) {
1600                         u8 *val = (u8 *)ghcb->shared_buffer;
1601
1602                         sign_byte = (*val & 0x80) ? 0xff : 0x00;
1603                 } else {
1604                         u16 *val = (u16 *)ghcb->shared_buffer;
1605
1606                         sign_byte = (*val & 0x8000) ? 0xff : 0x00;
1607                 }
1608
1609                 /* Sign extend based on operand size */
1610                 memset(reg_data, sign_byte, insn->opnd_bytes);
1611                 memcpy(reg_data, ghcb->shared_buffer, bytes);
1612                 break;
1613         case INSN_MMIO_MOVS:
1614                 ret = vc_handle_mmio_movs(ctxt, bytes);
1615                 break;
1616         default:
1617                 ret = ES_UNSUPPORTED;
1618                 break;
1619         }
1620
1621         return ret;
1622 }
1623
1624 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1625                                           struct es_em_ctxt *ctxt)
1626 {
1627         struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1628         long val, *reg = vc_insn_get_rm(ctxt);
1629         enum es_result ret;
1630
1631         if (sev_status & MSR_AMD64_SNP_DEBUG_SWAP)
1632                 return ES_VMM_ERROR;
1633
1634         if (!reg)
1635                 return ES_DECODE_FAILED;
1636
1637         val = *reg;
1638
1639         /* Upper 32 bits must be written as zeroes */
1640         if (val >> 32) {
1641                 ctxt->fi.vector = X86_TRAP_GP;
1642                 ctxt->fi.error_code = 0;
1643                 return ES_EXCEPTION;
1644         }
1645
1646         /* Clear out other reserved bits and set bit 10 */
1647         val = (val & 0xffff23ffL) | BIT(10);
1648
1649         /* Early non-zero writes to DR7 are not supported */
1650         if (!data && (val & ~DR7_RESET_VALUE))
1651                 return ES_UNSUPPORTED;
1652
1653         /* Using a value of 0 for ExitInfo1 means RAX holds the value */
1654         ghcb_set_rax(ghcb, val);
1655         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1656         if (ret != ES_OK)
1657                 return ret;
1658
1659         if (data)
1660                 data->dr7 = val;
1661
1662         return ES_OK;
1663 }
1664
1665 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1666                                          struct es_em_ctxt *ctxt)
1667 {
1668         struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1669         long *reg = vc_insn_get_rm(ctxt);
1670
1671         if (sev_status & MSR_AMD64_SNP_DEBUG_SWAP)
1672                 return ES_VMM_ERROR;
1673
1674         if (!reg)
1675                 return ES_DECODE_FAILED;
1676
1677         if (data)
1678                 *reg = data->dr7;
1679         else
1680                 *reg = DR7_RESET_VALUE;
1681
1682         return ES_OK;
1683 }
1684
1685 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1686                                        struct es_em_ctxt *ctxt)
1687 {
1688         return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1689 }
1690
1691 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1692 {
1693         enum es_result ret;
1694
1695         ghcb_set_rcx(ghcb, ctxt->regs->cx);
1696
1697         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1698         if (ret != ES_OK)
1699                 return ret;
1700
1701         if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1702                 return ES_VMM_ERROR;
1703
1704         ctxt->regs->ax = ghcb->save.rax;
1705         ctxt->regs->dx = ghcb->save.rdx;
1706
1707         return ES_OK;
1708 }
1709
1710 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1711                                         struct es_em_ctxt *ctxt)
1712 {
1713         /*
1714          * Treat it as a NOP and do not leak a physical address to the
1715          * hypervisor.
1716          */
1717         return ES_OK;
1718 }
1719
1720 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1721                                       struct es_em_ctxt *ctxt)
1722 {
1723         /* Treat the same as MONITOR/MONITORX */
1724         return ES_OK;
1725 }
1726
1727 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1728                                         struct es_em_ctxt *ctxt)
1729 {
1730         enum es_result ret;
1731
1732         ghcb_set_rax(ghcb, ctxt->regs->ax);
1733         ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1734
1735         if (x86_platform.hyper.sev_es_hcall_prepare)
1736                 x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1737
1738         ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1739         if (ret != ES_OK)
1740                 return ret;
1741
1742         if (!ghcb_rax_is_valid(ghcb))
1743                 return ES_VMM_ERROR;
1744
1745         ctxt->regs->ax = ghcb->save.rax;
1746
1747         /*
1748          * Call sev_es_hcall_finish() after regs->ax is already set.
1749          * This allows the hypervisor handler to overwrite it again if
1750          * necessary.
1751          */
1752         if (x86_platform.hyper.sev_es_hcall_finish &&
1753             !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1754                 return ES_VMM_ERROR;
1755
1756         return ES_OK;
1757 }
1758
1759 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1760                                         struct es_em_ctxt *ctxt)
1761 {
1762         /*
1763          * Calling ecx_alignment_check() directly does not work, because it
1764          * enables IRQs and the GHCB is active. Forward the exception and call
1765          * it later from vc_forward_exception().
1766          */
1767         ctxt->fi.vector = X86_TRAP_AC;
1768         ctxt->fi.error_code = 0;
1769         return ES_EXCEPTION;
1770 }
1771
1772 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1773                                          struct ghcb *ghcb,
1774                                          unsigned long exit_code)
1775 {
1776         enum es_result result = vc_check_opcode_bytes(ctxt, exit_code);
1777
1778         if (result != ES_OK)
1779                 return result;
1780
1781         switch (exit_code) {
1782         case SVM_EXIT_READ_DR7:
1783                 result = vc_handle_dr7_read(ghcb, ctxt);
1784                 break;
1785         case SVM_EXIT_WRITE_DR7:
1786                 result = vc_handle_dr7_write(ghcb, ctxt);
1787                 break;
1788         case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1789                 result = vc_handle_trap_ac(ghcb, ctxt);
1790                 break;
1791         case SVM_EXIT_RDTSC:
1792         case SVM_EXIT_RDTSCP:
1793                 result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1794                 break;
1795         case SVM_EXIT_RDPMC:
1796                 result = vc_handle_rdpmc(ghcb, ctxt);
1797                 break;
1798         case SVM_EXIT_INVD:
1799                 pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1800                 result = ES_UNSUPPORTED;
1801                 break;
1802         case SVM_EXIT_CPUID:
1803                 result = vc_handle_cpuid(ghcb, ctxt);
1804                 break;
1805         case SVM_EXIT_IOIO:
1806                 result = vc_handle_ioio(ghcb, ctxt);
1807                 break;
1808         case SVM_EXIT_MSR:
1809                 result = vc_handle_msr(ghcb, ctxt);
1810                 break;
1811         case SVM_EXIT_VMMCALL:
1812                 result = vc_handle_vmmcall(ghcb, ctxt);
1813                 break;
1814         case SVM_EXIT_WBINVD:
1815                 result = vc_handle_wbinvd(ghcb, ctxt);
1816                 break;
1817         case SVM_EXIT_MONITOR:
1818                 result = vc_handle_monitor(ghcb, ctxt);
1819                 break;
1820         case SVM_EXIT_MWAIT:
1821                 result = vc_handle_mwait(ghcb, ctxt);
1822                 break;
1823         case SVM_EXIT_NPF:
1824                 result = vc_handle_mmio(ghcb, ctxt);
1825                 break;
1826         default:
1827                 /*
1828                  * Unexpected #VC exception
1829                  */
1830                 result = ES_UNSUPPORTED;
1831         }
1832
1833         return result;
1834 }
1835
1836 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1837 {
1838         long error_code = ctxt->fi.error_code;
1839         int trapnr = ctxt->fi.vector;
1840
1841         ctxt->regs->orig_ax = ctxt->fi.error_code;
1842
1843         switch (trapnr) {
1844         case X86_TRAP_GP:
1845                 exc_general_protection(ctxt->regs, error_code);
1846                 break;
1847         case X86_TRAP_UD:
1848                 exc_invalid_op(ctxt->regs);
1849                 break;
1850         case X86_TRAP_PF:
1851                 write_cr2(ctxt->fi.cr2);
1852                 exc_page_fault(ctxt->regs, error_code);
1853                 break;
1854         case X86_TRAP_AC:
1855                 exc_alignment_check(ctxt->regs, error_code);
1856                 break;
1857         default:
1858                 pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1859                 BUG();
1860         }
1861 }
1862
1863 static __always_inline bool is_vc2_stack(unsigned long sp)
1864 {
1865         return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1866 }
1867
1868 static __always_inline bool vc_from_invalid_context(struct pt_regs *regs)
1869 {
1870         unsigned long sp, prev_sp;
1871
1872         sp      = (unsigned long)regs;
1873         prev_sp = regs->sp;
1874
1875         /*
1876          * If the code was already executing on the VC2 stack when the #VC
1877          * happened, let it proceed to the normal handling routine. This way the
1878          * code executing on the VC2 stack can cause #VC exceptions to get handled.
1879          */
1880         return is_vc2_stack(sp) && !is_vc2_stack(prev_sp);
1881 }
1882
1883 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
1884 {
1885         struct ghcb_state state;
1886         struct es_em_ctxt ctxt;
1887         enum es_result result;
1888         struct ghcb *ghcb;
1889         bool ret = true;
1890
1891         ghcb = __sev_get_ghcb(&state);
1892
1893         vc_ghcb_invalidate(ghcb);
1894         result = vc_init_em_ctxt(&ctxt, regs, error_code);
1895
1896         if (result == ES_OK)
1897                 result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1898
1899         __sev_put_ghcb(&state);
1900
1901         /* Done - now check the result */
1902         switch (result) {
1903         case ES_OK:
1904                 vc_finish_insn(&ctxt);
1905                 break;
1906         case ES_UNSUPPORTED:
1907                 pr_err_ratelimited("Unsupported exit-code 0x%02lx in #VC exception (IP: 0x%lx)\n",
1908                                    error_code, regs->ip);
1909                 ret = false;
1910                 break;
1911         case ES_VMM_ERROR:
1912                 pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1913                                    error_code, regs->ip);
1914                 ret = false;
1915                 break;
1916         case ES_DECODE_FAILED:
1917                 pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1918                                    error_code, regs->ip);
1919                 ret = false;
1920                 break;
1921         case ES_EXCEPTION:
1922                 vc_forward_exception(&ctxt);
1923                 break;
1924         case ES_RETRY:
1925                 /* Nothing to do */
1926                 break;
1927         default:
1928                 pr_emerg("Unknown result in %s():%d\n", __func__, result);
1929                 /*
1930                  * Emulating the instruction which caused the #VC exception
1931                  * failed - can't continue so print debug information
1932                  */
1933                 BUG();
1934         }
1935
1936         return ret;
1937 }
1938
1939 static __always_inline bool vc_is_db(unsigned long error_code)
1940 {
1941         return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
1942 }
1943
1944 /*
1945  * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
1946  * and will panic when an error happens.
1947  */
1948 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
1949 {
1950         irqentry_state_t irq_state;
1951
1952         /*
1953          * With the current implementation it is always possible to switch to a
1954          * safe stack because #VC exceptions only happen at known places, like
1955          * intercepted instructions or accesses to MMIO areas/IO ports. They can
1956          * also happen with code instrumentation when the hypervisor intercepts
1957          * #DB, but the critical paths are forbidden to be instrumented, so #DB
1958          * exceptions currently also only happen in safe places.
1959          *
1960          * But keep this here in case the noinstr annotations are violated due
1961          * to bug elsewhere.
1962          */
1963         if (unlikely(vc_from_invalid_context(regs))) {
1964                 instrumentation_begin();
1965                 panic("Can't handle #VC exception from unsupported context\n");
1966                 instrumentation_end();
1967         }
1968
1969         /*
1970          * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1971          */
1972         if (vc_is_db(error_code)) {
1973                 exc_debug(regs);
1974                 return;
1975         }
1976
1977         irq_state = irqentry_nmi_enter(regs);
1978
1979         instrumentation_begin();
1980
1981         if (!vc_raw_handle_exception(regs, error_code)) {
1982                 /* Show some debug info */
1983                 show_regs(regs);
1984
1985                 /* Ask hypervisor to sev_es_terminate */
1986                 sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
1987
1988                 /* If that fails and we get here - just panic */
1989                 panic("Returned from Terminate-Request to Hypervisor\n");
1990         }
1991
1992         instrumentation_end();
1993         irqentry_nmi_exit(regs, irq_state);
1994 }
1995
1996 /*
1997  * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
1998  * and will kill the current task with SIGBUS when an error happens.
1999  */
2000 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
2001 {
2002         /*
2003          * Handle #DB before calling into !noinstr code to avoid recursive #DB.
2004          */
2005         if (vc_is_db(error_code)) {
2006                 noist_exc_debug(regs);
2007                 return;
2008         }
2009
2010         irqentry_enter_from_user_mode(regs);
2011         instrumentation_begin();
2012
2013         if (!vc_raw_handle_exception(regs, error_code)) {
2014                 /*
2015                  * Do not kill the machine if user-space triggered the
2016                  * exception. Send SIGBUS instead and let user-space deal with
2017                  * it.
2018                  */
2019                 force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
2020         }
2021
2022         instrumentation_end();
2023         irqentry_exit_to_user_mode(regs);
2024 }
2025
2026 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
2027 {
2028         unsigned long exit_code = regs->orig_ax;
2029         struct es_em_ctxt ctxt;
2030         enum es_result result;
2031
2032         vc_ghcb_invalidate(boot_ghcb);
2033
2034         result = vc_init_em_ctxt(&ctxt, regs, exit_code);
2035         if (result == ES_OK)
2036                 result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
2037
2038         /* Done - now check the result */
2039         switch (result) {
2040         case ES_OK:
2041                 vc_finish_insn(&ctxt);
2042                 break;
2043         case ES_UNSUPPORTED:
2044                 early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
2045                                 exit_code, regs->ip);
2046                 goto fail;
2047         case ES_VMM_ERROR:
2048                 early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
2049                                 exit_code, regs->ip);
2050                 goto fail;
2051         case ES_DECODE_FAILED:
2052                 early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
2053                                 exit_code, regs->ip);
2054                 goto fail;
2055         case ES_EXCEPTION:
2056                 vc_early_forward_exception(&ctxt);
2057                 break;
2058         case ES_RETRY:
2059                 /* Nothing to do */
2060                 break;
2061         default:
2062                 BUG();
2063         }
2064
2065         return true;
2066
2067 fail:
2068         show_regs(regs);
2069
2070         sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SEV_ES_GEN_REQ);
2071 }
2072
2073 /*
2074  * Initial set up of SNP relies on information provided by the
2075  * Confidential Computing blob, which can be passed to the kernel
2076  * in the following ways, depending on how it is booted:
2077  *
2078  * - when booted via the boot/decompress kernel:
2079  *   - via boot_params
2080  *
2081  * - when booted directly by firmware/bootloader (e.g. CONFIG_PVH):
2082  *   - via a setup_data entry, as defined by the Linux Boot Protocol
2083  *
2084  * Scan for the blob in that order.
2085  */
2086 static __head struct cc_blob_sev_info *find_cc_blob(struct boot_params *bp)
2087 {
2088         struct cc_blob_sev_info *cc_info;
2089
2090         /* Boot kernel would have passed the CC blob via boot_params. */
2091         if (bp->cc_blob_address) {
2092                 cc_info = (struct cc_blob_sev_info *)(unsigned long)bp->cc_blob_address;
2093                 goto found_cc_info;
2094         }
2095
2096         /*
2097          * If kernel was booted directly, without the use of the
2098          * boot/decompression kernel, the CC blob may have been passed via
2099          * setup_data instead.
2100          */
2101         cc_info = find_cc_blob_setup_data(bp);
2102         if (!cc_info)
2103                 return NULL;
2104
2105 found_cc_info:
2106         if (cc_info->magic != CC_BLOB_SEV_HDR_MAGIC)
2107                 snp_abort();
2108
2109         return cc_info;
2110 }
2111
2112 bool __head snp_init(struct boot_params *bp)
2113 {
2114         struct cc_blob_sev_info *cc_info;
2115
2116         if (!bp)
2117                 return false;
2118
2119         cc_info = find_cc_blob(bp);
2120         if (!cc_info)
2121                 return false;
2122
2123         setup_cpuid_table(cc_info);
2124
2125         /*
2126          * The CC blob will be used later to access the secrets page. Cache
2127          * it here like the boot kernel does.
2128          */
2129         bp->cc_blob_address = (u32)(unsigned long)cc_info;
2130
2131         return true;
2132 }
2133
2134 void __head __noreturn snp_abort(void)
2135 {
2136         sev_es_terminate(SEV_TERM_SET_GEN, GHCB_SNP_UNSUPPORTED);
2137 }
2138
2139 static void dump_cpuid_table(void)
2140 {
2141         const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
2142         int i = 0;
2143
2144         pr_info("count=%d reserved=0x%x reserved2=0x%llx\n",
2145                 cpuid_table->count, cpuid_table->__reserved1, cpuid_table->__reserved2);
2146
2147         for (i = 0; i < SNP_CPUID_COUNT_MAX; i++) {
2148                 const struct snp_cpuid_fn *fn = &cpuid_table->fn[i];
2149
2150                 pr_info("index=%3d fn=0x%08x subfn=0x%08x: eax=0x%08x ebx=0x%08x ecx=0x%08x edx=0x%08x xcr0_in=0x%016llx xss_in=0x%016llx reserved=0x%016llx\n",
2151                         i, fn->eax_in, fn->ecx_in, fn->eax, fn->ebx, fn->ecx,
2152                         fn->edx, fn->xcr0_in, fn->xss_in, fn->__reserved);
2153         }
2154 }
2155
2156 /*
2157  * It is useful from an auditing/testing perspective to provide an easy way
2158  * for the guest owner to know that the CPUID table has been initialized as
2159  * expected, but that initialization happens too early in boot to print any
2160  * sort of indicator, and there's not really any other good place to do it,
2161  * so do it here.
2162  */
2163 static int __init report_cpuid_table(void)
2164 {
2165         const struct snp_cpuid_table *cpuid_table = snp_cpuid_get_table();
2166
2167         if (!cpuid_table->count)
2168                 return 0;
2169
2170         pr_info("Using SNP CPUID table, %d entries present.\n",
2171                 cpuid_table->count);
2172
2173         if (sev_cfg.debug)
2174                 dump_cpuid_table();
2175
2176         return 0;
2177 }
2178 arch_initcall(report_cpuid_table);
2179
2180 static int __init init_sev_config(char *str)
2181 {
2182         char *s;
2183
2184         while ((s = strsep(&str, ","))) {
2185                 if (!strcmp(s, "debug")) {
2186                         sev_cfg.debug = true;
2187                         continue;
2188                 }
2189
2190                 pr_info("SEV command-line option '%s' was not recognized\n", s);
2191         }
2192
2193         return 1;
2194 }
2195 __setup("sev=", init_sev_config);
2196
2197 int snp_issue_guest_request(u64 exit_code, struct snp_req_data *input, struct snp_guest_request_ioctl *rio)
2198 {
2199         struct ghcb_state state;
2200         struct es_em_ctxt ctxt;
2201         unsigned long flags;
2202         struct ghcb *ghcb;
2203         int ret;
2204
2205         rio->exitinfo2 = SEV_RET_NO_FW_CALL;
2206
2207         /*
2208          * __sev_get_ghcb() needs to run with IRQs disabled because it is using
2209          * a per-CPU GHCB.
2210          */
2211         local_irq_save(flags);
2212
2213         ghcb = __sev_get_ghcb(&state);
2214         if (!ghcb) {
2215                 ret = -EIO;
2216                 goto e_restore_irq;
2217         }
2218
2219         vc_ghcb_invalidate(ghcb);
2220
2221         if (exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
2222                 ghcb_set_rax(ghcb, input->data_gpa);
2223                 ghcb_set_rbx(ghcb, input->data_npages);
2224         }
2225
2226         ret = sev_es_ghcb_hv_call(ghcb, &ctxt, exit_code, input->req_gpa, input->resp_gpa);
2227         if (ret)
2228                 goto e_put;
2229
2230         rio->exitinfo2 = ghcb->save.sw_exit_info_2;
2231         switch (rio->exitinfo2) {
2232         case 0:
2233                 break;
2234
2235         case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_BUSY):
2236                 ret = -EAGAIN;
2237                 break;
2238
2239         case SNP_GUEST_VMM_ERR(SNP_GUEST_VMM_ERR_INVALID_LEN):
2240                 /* Number of expected pages are returned in RBX */
2241                 if (exit_code == SVM_VMGEXIT_EXT_GUEST_REQUEST) {
2242                         input->data_npages = ghcb_get_rbx(ghcb);
2243                         ret = -ENOSPC;
2244                         break;
2245                 }
2246                 fallthrough;
2247         default:
2248                 ret = -EIO;
2249                 break;
2250         }
2251
2252 e_put:
2253         __sev_put_ghcb(&state);
2254 e_restore_irq:
2255         local_irq_restore(flags);
2256
2257         return ret;
2258 }
2259 EXPORT_SYMBOL_GPL(snp_issue_guest_request);
2260
2261 static struct platform_device sev_guest_device = {
2262         .name           = "sev-guest",
2263         .id             = -1,
2264 };
2265
2266 static int __init snp_init_platform_device(void)
2267 {
2268         struct sev_guest_platform_data data;
2269         u64 gpa;
2270
2271         if (!cc_platform_has(CC_ATTR_GUEST_SEV_SNP))
2272                 return -ENODEV;
2273
2274         gpa = get_secrets_page();
2275         if (!gpa)
2276                 return -ENODEV;
2277
2278         data.secrets_gpa = gpa;
2279         if (platform_device_add_data(&sev_guest_device, &data, sizeof(data)))
2280                 return -ENODEV;
2281
2282         if (platform_device_register(&sev_guest_device))
2283                 return -ENODEV;
2284
2285         pr_info("SNP guest platform device initialized.\n");
2286         return 0;
2287 }
2288 device_initcall(snp_init_platform_device);
2289
2290 void kdump_sev_callback(void)
2291 {
2292         /*
2293          * Do wbinvd() on remote CPUs when SNP is enabled in order to
2294          * safely do SNP_SHUTDOWN on the local CPU.
2295          */
2296         if (cpu_feature_enabled(X86_FEATURE_SEV_SNP))
2297                 wbinvd();
2298 }
2299
2300 void sev_show_status(void)
2301 {
2302         int i;
2303
2304         pr_info("Status: ");
2305         for (i = 0; i < MSR_AMD64_SNP_RESV_BIT; i++) {
2306                 if (sev_status & BIT_ULL(i)) {
2307                         if (!sev_status_feat_names[i])
2308                                 continue;
2309
2310                         pr_cont("%s ", sev_status_feat_names[i]);
2311                 }
2312         }
2313         pr_cont("\n");
2314 }
This page took 0.16849 seconds and 4 git commands to generate.