Merge remote-tracking branch 'tip/x86/cc' into hyperv-next
[linux-2.6-microblaze.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 <jroedel@suse.de>
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
22 #include <asm/cpu_entry_area.h>
23 #include <asm/stacktrace.h>
24 #include <asm/sev.h>
25 #include <asm/insn-eval.h>
26 #include <asm/fpu/internal.h>
27 #include <asm/processor.h>
28 #include <asm/realmode.h>
29 #include <asm/traps.h>
30 #include <asm/svm.h>
31 #include <asm/smp.h>
32 #include <asm/cpu.h>
33
34 #define DR7_RESET_VALUE        0x400
35
36 /* For early boot hypervisor communication in SEV-ES enabled guests */
37 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
38
39 /*
40  * Needs to be in the .data section because we need it NULL before bss is
41  * cleared
42  */
43 static struct ghcb __initdata *boot_ghcb;
44
45 /* #VC handler runtime per-CPU data */
46 struct sev_es_runtime_data {
47         struct ghcb ghcb_page;
48
49         /* Physical storage for the per-CPU IST stack of the #VC handler */
50         char ist_stack[EXCEPTION_STKSZ] __aligned(PAGE_SIZE);
51
52         /*
53          * Physical storage for the per-CPU fall-back stack of the #VC handler.
54          * The fall-back stack is used when it is not safe to switch back to the
55          * interrupted stack in the #VC entry code.
56          */
57         char fallback_stack[EXCEPTION_STKSZ] __aligned(PAGE_SIZE);
58
59         /*
60          * Reserve one page per CPU as backup storage for the unencrypted GHCB.
61          * It is needed when an NMI happens while the #VC handler uses the real
62          * GHCB, and the NMI handler itself is causing another #VC exception. In
63          * that case the GHCB content of the first handler needs to be backed up
64          * and restored.
65          */
66         struct ghcb backup_ghcb;
67
68         /*
69          * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
70          * There is no need for it to be atomic, because nothing is written to
71          * the GHCB between the read and the write of ghcb_active. So it is safe
72          * to use it when a nested #VC exception happens before the write.
73          *
74          * This is necessary for example in the #VC->NMI->#VC case when the NMI
75          * happens while the first #VC handler uses the GHCB. When the NMI code
76          * raises a second #VC handler it might overwrite the contents of the
77          * GHCB written by the first handler. To avoid this the content of the
78          * GHCB is saved and restored when the GHCB is detected to be in use
79          * already.
80          */
81         bool ghcb_active;
82         bool backup_ghcb_active;
83
84         /*
85          * Cached DR7 value - write it on DR7 writes and return it on reads.
86          * That value will never make it to the real hardware DR7 as debugging
87          * is currently unsupported in SEV-ES guests.
88          */
89         unsigned long dr7;
90 };
91
92 struct ghcb_state {
93         struct ghcb *ghcb;
94 };
95
96 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
97 DEFINE_STATIC_KEY_FALSE(sev_es_enable_key);
98
99 /* Needed in vc_early_forward_exception */
100 void do_early_exception(struct pt_regs *regs, int trapnr);
101
102 static void __init setup_vc_stacks(int cpu)
103 {
104         struct sev_es_runtime_data *data;
105         struct cpu_entry_area *cea;
106         unsigned long vaddr;
107         phys_addr_t pa;
108
109         data = per_cpu(runtime_data, cpu);
110         cea  = get_cpu_entry_area(cpu);
111
112         /* Map #VC IST stack */
113         vaddr = CEA_ESTACK_BOT(&cea->estacks, VC);
114         pa    = __pa(data->ist_stack);
115         cea_set_pte((void *)vaddr, pa, PAGE_KERNEL);
116
117         /* Map VC fall-back stack */
118         vaddr = CEA_ESTACK_BOT(&cea->estacks, VC2);
119         pa    = __pa(data->fallback_stack);
120         cea_set_pte((void *)vaddr, pa, PAGE_KERNEL);
121 }
122
123 static __always_inline bool on_vc_stack(struct pt_regs *regs)
124 {
125         unsigned long sp = regs->sp;
126
127         /* User-mode RSP is not trusted */
128         if (user_mode(regs))
129                 return false;
130
131         /* SYSCALL gap still has user-mode RSP */
132         if (ip_within_syscall_gap(regs))
133                 return false;
134
135         return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
136 }
137
138 /*
139  * This function handles the case when an NMI is raised in the #VC
140  * exception handler entry code, before the #VC handler has switched off
141  * its IST stack. In this case, the IST entry for #VC must be adjusted,
142  * so that any nested #VC exception will not overwrite the stack
143  * contents of the interrupted #VC handler.
144  *
145  * The IST entry is adjusted unconditionally so that it can be also be
146  * unconditionally adjusted back in __sev_es_ist_exit(). Otherwise a
147  * nested sev_es_ist_exit() call may adjust back the IST entry too
148  * early.
149  *
150  * The __sev_es_ist_enter() and __sev_es_ist_exit() functions always run
151  * on the NMI IST stack, as they are only called from NMI handling code
152  * right now.
153  */
154 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
155 {
156         unsigned long old_ist, new_ist;
157
158         /* Read old IST entry */
159         new_ist = old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
160
161         /*
162          * If NMI happened while on the #VC IST stack, set the new IST
163          * value below regs->sp, so that the interrupted stack frame is
164          * not overwritten by subsequent #VC exceptions.
165          */
166         if (on_vc_stack(regs))
167                 new_ist = regs->sp;
168
169         /*
170          * Reserve additional 8 bytes and store old IST value so this
171          * adjustment can be unrolled in __sev_es_ist_exit().
172          */
173         new_ist -= sizeof(old_ist);
174         *(unsigned long *)new_ist = old_ist;
175
176         /* Set new IST entry */
177         this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
178 }
179
180 void noinstr __sev_es_ist_exit(void)
181 {
182         unsigned long ist;
183
184         /* Read IST entry */
185         ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
186
187         if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
188                 return;
189
190         /* Read back old IST entry and write it to the TSS */
191         this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
192 }
193
194 /*
195  * Nothing shall interrupt this code path while holding the per-CPU
196  * GHCB. The backup GHCB is only for NMIs interrupting this path.
197  *
198  * Callers must disable local interrupts around it.
199  */
200 static noinstr struct ghcb *__sev_get_ghcb(struct ghcb_state *state)
201 {
202         struct sev_es_runtime_data *data;
203         struct ghcb *ghcb;
204
205         WARN_ON(!irqs_disabled());
206
207         data = this_cpu_read(runtime_data);
208         ghcb = &data->ghcb_page;
209
210         if (unlikely(data->ghcb_active)) {
211                 /* GHCB is already in use - save its contents */
212
213                 if (unlikely(data->backup_ghcb_active)) {
214                         /*
215                          * Backup-GHCB is also already in use. There is no way
216                          * to continue here so just kill the machine. To make
217                          * panic() work, mark GHCBs inactive so that messages
218                          * can be printed out.
219                          */
220                         data->ghcb_active        = false;
221                         data->backup_ghcb_active = false;
222
223                         instrumentation_begin();
224                         panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
225                         instrumentation_end();
226                 }
227
228                 /* Mark backup_ghcb active before writing to it */
229                 data->backup_ghcb_active = true;
230
231                 state->ghcb = &data->backup_ghcb;
232
233                 /* Backup GHCB content */
234                 *state->ghcb = *ghcb;
235         } else {
236                 state->ghcb = NULL;
237                 data->ghcb_active = true;
238         }
239
240         return ghcb;
241 }
242
243 /* Needed in vc_early_forward_exception */
244 void do_early_exception(struct pt_regs *regs, int trapnr);
245
246 static inline u64 sev_es_rd_ghcb_msr(void)
247 {
248         return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
249 }
250
251 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
252 {
253         u32 low, high;
254
255         low  = (u32)(val);
256         high = (u32)(val >> 32);
257
258         native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
259 }
260
261 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
262                                 unsigned char *buffer)
263 {
264         return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
265 }
266
267 static enum es_result __vc_decode_user_insn(struct es_em_ctxt *ctxt)
268 {
269         char buffer[MAX_INSN_SIZE];
270         int insn_bytes;
271
272         insn_bytes = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
273         if (insn_bytes == 0) {
274                 /* Nothing could be copied */
275                 ctxt->fi.vector     = X86_TRAP_PF;
276                 ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
277                 ctxt->fi.cr2        = ctxt->regs->ip;
278                 return ES_EXCEPTION;
279         } else if (insn_bytes == -EINVAL) {
280                 /* Effective RIP could not be calculated */
281                 ctxt->fi.vector     = X86_TRAP_GP;
282                 ctxt->fi.error_code = 0;
283                 ctxt->fi.cr2        = 0;
284                 return ES_EXCEPTION;
285         }
286
287         if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, insn_bytes))
288                 return ES_DECODE_FAILED;
289
290         if (ctxt->insn.immediate.got)
291                 return ES_OK;
292         else
293                 return ES_DECODE_FAILED;
294 }
295
296 static enum es_result __vc_decode_kern_insn(struct es_em_ctxt *ctxt)
297 {
298         char buffer[MAX_INSN_SIZE];
299         int res, ret;
300
301         res = vc_fetch_insn_kernel(ctxt, buffer);
302         if (res) {
303                 ctxt->fi.vector     = X86_TRAP_PF;
304                 ctxt->fi.error_code = X86_PF_INSTR;
305                 ctxt->fi.cr2        = ctxt->regs->ip;
306                 return ES_EXCEPTION;
307         }
308
309         ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
310         if (ret < 0)
311                 return ES_DECODE_FAILED;
312         else
313                 return ES_OK;
314 }
315
316 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
317 {
318         if (user_mode(ctxt->regs))
319                 return __vc_decode_user_insn(ctxt);
320         else
321                 return __vc_decode_kern_insn(ctxt);
322 }
323
324 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
325                                    char *dst, char *buf, size_t size)
326 {
327         unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
328         char __user *target = (char __user *)dst;
329         u64 d8;
330         u32 d4;
331         u16 d2;
332         u8  d1;
333
334         /*
335          * This function uses __put_user() independent of whether kernel or user
336          * memory is accessed. This works fine because __put_user() does no
337          * sanity checks of the pointer being accessed. All that it does is
338          * to report when the access failed.
339          *
340          * Also, this function runs in atomic context, so __put_user() is not
341          * allowed to sleep. The page-fault handler detects that it is running
342          * in atomic context and will not try to take mmap_sem and handle the
343          * fault, so additional pagefault_enable()/disable() calls are not
344          * needed.
345          *
346          * The access can't be done via copy_to_user() here because
347          * vc_write_mem() must not use string instructions to access unsafe
348          * memory. The reason is that MOVS is emulated by the #VC handler by
349          * splitting the move up into a read and a write and taking a nested #VC
350          * exception on whatever of them is the MMIO access. Using string
351          * instructions here would cause infinite nesting.
352          */
353         switch (size) {
354         case 1:
355                 memcpy(&d1, buf, 1);
356                 if (__put_user(d1, target))
357                         goto fault;
358                 break;
359         case 2:
360                 memcpy(&d2, buf, 2);
361                 if (__put_user(d2, target))
362                         goto fault;
363                 break;
364         case 4:
365                 memcpy(&d4, buf, 4);
366                 if (__put_user(d4, target))
367                         goto fault;
368                 break;
369         case 8:
370                 memcpy(&d8, buf, 8);
371                 if (__put_user(d8, target))
372                         goto fault;
373                 break;
374         default:
375                 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
376                 return ES_UNSUPPORTED;
377         }
378
379         return ES_OK;
380
381 fault:
382         if (user_mode(ctxt->regs))
383                 error_code |= X86_PF_USER;
384
385         ctxt->fi.vector = X86_TRAP_PF;
386         ctxt->fi.error_code = error_code;
387         ctxt->fi.cr2 = (unsigned long)dst;
388
389         return ES_EXCEPTION;
390 }
391
392 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
393                                   char *src, char *buf, size_t size)
394 {
395         unsigned long error_code = X86_PF_PROT;
396         char __user *s = (char __user *)src;
397         u64 d8;
398         u32 d4;
399         u16 d2;
400         u8  d1;
401
402         /*
403          * This function uses __get_user() independent of whether kernel or user
404          * memory is accessed. This works fine because __get_user() does no
405          * sanity checks of the pointer being accessed. All that it does is
406          * to report when the access failed.
407          *
408          * Also, this function runs in atomic context, so __get_user() is not
409          * allowed to sleep. The page-fault handler detects that it is running
410          * in atomic context and will not try to take mmap_sem and handle the
411          * fault, so additional pagefault_enable()/disable() calls are not
412          * needed.
413          *
414          * The access can't be done via copy_from_user() here because
415          * vc_read_mem() must not use string instructions to access unsafe
416          * memory. The reason is that MOVS is emulated by the #VC handler by
417          * splitting the move up into a read and a write and taking a nested #VC
418          * exception on whatever of them is the MMIO access. Using string
419          * instructions here would cause infinite nesting.
420          */
421         switch (size) {
422         case 1:
423                 if (__get_user(d1, s))
424                         goto fault;
425                 memcpy(buf, &d1, 1);
426                 break;
427         case 2:
428                 if (__get_user(d2, s))
429                         goto fault;
430                 memcpy(buf, &d2, 2);
431                 break;
432         case 4:
433                 if (__get_user(d4, s))
434                         goto fault;
435                 memcpy(buf, &d4, 4);
436                 break;
437         case 8:
438                 if (__get_user(d8, s))
439                         goto fault;
440                 memcpy(buf, &d8, 8);
441                 break;
442         default:
443                 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
444                 return ES_UNSUPPORTED;
445         }
446
447         return ES_OK;
448
449 fault:
450         if (user_mode(ctxt->regs))
451                 error_code |= X86_PF_USER;
452
453         ctxt->fi.vector = X86_TRAP_PF;
454         ctxt->fi.error_code = error_code;
455         ctxt->fi.cr2 = (unsigned long)src;
456
457         return ES_EXCEPTION;
458 }
459
460 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
461                                            unsigned long vaddr, phys_addr_t *paddr)
462 {
463         unsigned long va = (unsigned long)vaddr;
464         unsigned int level;
465         phys_addr_t pa;
466         pgd_t *pgd;
467         pte_t *pte;
468
469         pgd = __va(read_cr3_pa());
470         pgd = &pgd[pgd_index(va)];
471         pte = lookup_address_in_pgd(pgd, va, &level);
472         if (!pte) {
473                 ctxt->fi.vector     = X86_TRAP_PF;
474                 ctxt->fi.cr2        = vaddr;
475                 ctxt->fi.error_code = 0;
476
477                 if (user_mode(ctxt->regs))
478                         ctxt->fi.error_code |= X86_PF_USER;
479
480                 return ES_EXCEPTION;
481         }
482
483         if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
484                 /* Emulated MMIO to/from encrypted memory not supported */
485                 return ES_UNSUPPORTED;
486
487         pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
488         pa |= va & ~page_level_mask(level);
489
490         *paddr = pa;
491
492         return ES_OK;
493 }
494
495 /* Include code shared with pre-decompression boot stage */
496 #include "sev-shared.c"
497
498 static noinstr void __sev_put_ghcb(struct ghcb_state *state)
499 {
500         struct sev_es_runtime_data *data;
501         struct ghcb *ghcb;
502
503         WARN_ON(!irqs_disabled());
504
505         data = this_cpu_read(runtime_data);
506         ghcb = &data->ghcb_page;
507
508         if (state->ghcb) {
509                 /* Restore GHCB from Backup */
510                 *ghcb = *state->ghcb;
511                 data->backup_ghcb_active = false;
512                 state->ghcb = NULL;
513         } else {
514                 /*
515                  * Invalidate the GHCB so a VMGEXIT instruction issued
516                  * from userspace won't appear to be valid.
517                  */
518                 vc_ghcb_invalidate(ghcb);
519                 data->ghcb_active = false;
520         }
521 }
522
523 void noinstr __sev_es_nmi_complete(void)
524 {
525         struct ghcb_state state;
526         struct ghcb *ghcb;
527
528         ghcb = __sev_get_ghcb(&state);
529
530         vc_ghcb_invalidate(ghcb);
531         ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
532         ghcb_set_sw_exit_info_1(ghcb, 0);
533         ghcb_set_sw_exit_info_2(ghcb, 0);
534
535         sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
536         VMGEXIT();
537
538         __sev_put_ghcb(&state);
539 }
540
541 static u64 get_jump_table_addr(void)
542 {
543         struct ghcb_state state;
544         unsigned long flags;
545         struct ghcb *ghcb;
546         u64 ret = 0;
547
548         local_irq_save(flags);
549
550         ghcb = __sev_get_ghcb(&state);
551
552         vc_ghcb_invalidate(ghcb);
553         ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
554         ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
555         ghcb_set_sw_exit_info_2(ghcb, 0);
556
557         sev_es_wr_ghcb_msr(__pa(ghcb));
558         VMGEXIT();
559
560         if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
561             ghcb_sw_exit_info_2_is_valid(ghcb))
562                 ret = ghcb->save.sw_exit_info_2;
563
564         __sev_put_ghcb(&state);
565
566         local_irq_restore(flags);
567
568         return ret;
569 }
570
571 int sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
572 {
573         u16 startup_cs, startup_ip;
574         phys_addr_t jump_table_pa;
575         u64 jump_table_addr;
576         u16 __iomem *jump_table;
577
578         jump_table_addr = get_jump_table_addr();
579
580         /* On UP guests there is no jump table so this is not a failure */
581         if (!jump_table_addr)
582                 return 0;
583
584         /* Check if AP Jump Table is page-aligned */
585         if (jump_table_addr & ~PAGE_MASK)
586                 return -EINVAL;
587
588         jump_table_pa = jump_table_addr & PAGE_MASK;
589
590         startup_cs = (u16)(rmh->trampoline_start >> 4);
591         startup_ip = (u16)(rmh->sev_es_trampoline_start -
592                            rmh->trampoline_start);
593
594         jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
595         if (!jump_table)
596                 return -EIO;
597
598         writew(startup_ip, &jump_table[0]);
599         writew(startup_cs, &jump_table[1]);
600
601         iounmap(jump_table);
602
603         return 0;
604 }
605
606 /*
607  * This is needed by the OVMF UEFI firmware which will use whatever it finds in
608  * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
609  * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
610  */
611 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
612 {
613         struct sev_es_runtime_data *data;
614         unsigned long address, pflags;
615         int cpu;
616         u64 pfn;
617
618         if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
619                 return 0;
620
621         pflags = _PAGE_NX | _PAGE_RW;
622
623         for_each_possible_cpu(cpu) {
624                 data = per_cpu(runtime_data, cpu);
625
626                 address = __pa(&data->ghcb_page);
627                 pfn = address >> PAGE_SHIFT;
628
629                 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
630                         return 1;
631         }
632
633         return 0;
634 }
635
636 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
637 {
638         struct pt_regs *regs = ctxt->regs;
639         enum es_result ret;
640         u64 exit_info_1;
641
642         /* Is it a WRMSR? */
643         exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
644
645         ghcb_set_rcx(ghcb, regs->cx);
646         if (exit_info_1) {
647                 ghcb_set_rax(ghcb, regs->ax);
648                 ghcb_set_rdx(ghcb, regs->dx);
649         }
650
651         ret = sev_es_ghcb_hv_call(ghcb, true, ctxt, SVM_EXIT_MSR,
652                                   exit_info_1, 0);
653
654         if ((ret == ES_OK) && (!exit_info_1)) {
655                 regs->ax = ghcb->save.rax;
656                 regs->dx = ghcb->save.rdx;
657         }
658
659         return ret;
660 }
661
662 /*
663  * This function runs on the first #VC exception after the kernel
664  * switched to virtual addresses.
665  */
666 static bool __init sev_es_setup_ghcb(void)
667 {
668         /* First make sure the hypervisor talks a supported protocol. */
669         if (!sev_es_negotiate_protocol())
670                 return false;
671
672         /*
673          * Clear the boot_ghcb. The first exception comes in before the bss
674          * section is cleared.
675          */
676         memset(&boot_ghcb_page, 0, PAGE_SIZE);
677
678         /* Alright - Make the boot-ghcb public */
679         boot_ghcb = &boot_ghcb_page;
680
681         return true;
682 }
683
684 #ifdef CONFIG_HOTPLUG_CPU
685 static void sev_es_ap_hlt_loop(void)
686 {
687         struct ghcb_state state;
688         struct ghcb *ghcb;
689
690         ghcb = __sev_get_ghcb(&state);
691
692         while (true) {
693                 vc_ghcb_invalidate(ghcb);
694                 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
695                 ghcb_set_sw_exit_info_1(ghcb, 0);
696                 ghcb_set_sw_exit_info_2(ghcb, 0);
697
698                 sev_es_wr_ghcb_msr(__pa(ghcb));
699                 VMGEXIT();
700
701                 /* Wakeup signal? */
702                 if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
703                     ghcb->save.sw_exit_info_2)
704                         break;
705         }
706
707         __sev_put_ghcb(&state);
708 }
709
710 /*
711  * Play_dead handler when running under SEV-ES. This is needed because
712  * the hypervisor can't deliver an SIPI request to restart the AP.
713  * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
714  * hypervisor wakes it up again.
715  */
716 static void sev_es_play_dead(void)
717 {
718         play_dead_common();
719
720         /* IRQs now disabled */
721
722         sev_es_ap_hlt_loop();
723
724         /*
725          * If we get here, the VCPU was woken up again. Jump to CPU
726          * startup code to get it back online.
727          */
728         start_cpu0();
729 }
730 #else  /* CONFIG_HOTPLUG_CPU */
731 #define sev_es_play_dead        native_play_dead
732 #endif /* CONFIG_HOTPLUG_CPU */
733
734 #ifdef CONFIG_SMP
735 static void __init sev_es_setup_play_dead(void)
736 {
737         smp_ops.play_dead = sev_es_play_dead;
738 }
739 #else
740 static inline void sev_es_setup_play_dead(void) { }
741 #endif
742
743 static void __init alloc_runtime_data(int cpu)
744 {
745         struct sev_es_runtime_data *data;
746
747         data = memblock_alloc(sizeof(*data), PAGE_SIZE);
748         if (!data)
749                 panic("Can't allocate SEV-ES runtime data");
750
751         per_cpu(runtime_data, cpu) = data;
752 }
753
754 static void __init init_ghcb(int cpu)
755 {
756         struct sev_es_runtime_data *data;
757         int err;
758
759         data = per_cpu(runtime_data, cpu);
760
761         err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
762                                          sizeof(data->ghcb_page));
763         if (err)
764                 panic("Can't map GHCBs unencrypted");
765
766         memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
767
768         data->ghcb_active = false;
769         data->backup_ghcb_active = false;
770 }
771
772 void __init sev_es_init_vc_handling(void)
773 {
774         int cpu;
775
776         BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
777
778         if (!cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT))
779                 return;
780
781         if (!sev_es_check_cpu_features())
782                 panic("SEV-ES CPU Features missing");
783
784         /* Enable SEV-ES special handling */
785         static_branch_enable(&sev_es_enable_key);
786
787         /* Initialize per-cpu GHCB pages */
788         for_each_possible_cpu(cpu) {
789                 alloc_runtime_data(cpu);
790                 init_ghcb(cpu);
791                 setup_vc_stacks(cpu);
792         }
793
794         sev_es_setup_play_dead();
795
796         /* Secondary CPUs use the runtime #VC handler */
797         initial_vc_handler = (unsigned long)kernel_exc_vmm_communication;
798 }
799
800 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
801 {
802         int trapnr = ctxt->fi.vector;
803
804         if (trapnr == X86_TRAP_PF)
805                 native_write_cr2(ctxt->fi.cr2);
806
807         ctxt->regs->orig_ax = ctxt->fi.error_code;
808         do_early_exception(ctxt->regs, trapnr);
809 }
810
811 static long *vc_insn_get_reg(struct es_em_ctxt *ctxt)
812 {
813         long *reg_array;
814         int offset;
815
816         reg_array = (long *)ctxt->regs;
817         offset    = insn_get_modrm_reg_off(&ctxt->insn, ctxt->regs);
818
819         if (offset < 0)
820                 return NULL;
821
822         offset /= sizeof(long);
823
824         return reg_array + offset;
825 }
826
827 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
828 {
829         long *reg_array;
830         int offset;
831
832         reg_array = (long *)ctxt->regs;
833         offset    = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
834
835         if (offset < 0)
836                 return NULL;
837
838         offset /= sizeof(long);
839
840         return reg_array + offset;
841 }
842 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
843                                  unsigned int bytes, bool read)
844 {
845         u64 exit_code, exit_info_1, exit_info_2;
846         unsigned long ghcb_pa = __pa(ghcb);
847         enum es_result res;
848         phys_addr_t paddr;
849         void __user *ref;
850
851         ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
852         if (ref == (void __user *)-1L)
853                 return ES_UNSUPPORTED;
854
855         exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
856
857         res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
858         if (res != ES_OK) {
859                 if (res == ES_EXCEPTION && !read)
860                         ctxt->fi.error_code |= X86_PF_WRITE;
861
862                 return res;
863         }
864
865         exit_info_1 = paddr;
866         /* Can never be greater than 8 */
867         exit_info_2 = bytes;
868
869         ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
870
871         return sev_es_ghcb_hv_call(ghcb, true, ctxt, exit_code, exit_info_1, exit_info_2);
872 }
873
874 static enum es_result vc_handle_mmio_twobyte_ops(struct ghcb *ghcb,
875                                                  struct es_em_ctxt *ctxt)
876 {
877         struct insn *insn = &ctxt->insn;
878         unsigned int bytes = 0;
879         enum es_result ret;
880         int sign_byte;
881         long *reg_data;
882
883         switch (insn->opcode.bytes[1]) {
884                 /* MMIO Read w/ zero-extension */
885         case 0xb6:
886                 bytes = 1;
887                 fallthrough;
888         case 0xb7:
889                 if (!bytes)
890                         bytes = 2;
891
892                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
893                 if (ret)
894                         break;
895
896                 /* Zero extend based on operand size */
897                 reg_data = vc_insn_get_reg(ctxt);
898                 if (!reg_data)
899                         return ES_DECODE_FAILED;
900
901                 memset(reg_data, 0, insn->opnd_bytes);
902
903                 memcpy(reg_data, ghcb->shared_buffer, bytes);
904                 break;
905
906                 /* MMIO Read w/ sign-extension */
907         case 0xbe:
908                 bytes = 1;
909                 fallthrough;
910         case 0xbf:
911                 if (!bytes)
912                         bytes = 2;
913
914                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
915                 if (ret)
916                         break;
917
918                 /* Sign extend based on operand size */
919                 reg_data = vc_insn_get_reg(ctxt);
920                 if (!reg_data)
921                         return ES_DECODE_FAILED;
922
923                 if (bytes == 1) {
924                         u8 *val = (u8 *)ghcb->shared_buffer;
925
926                         sign_byte = (*val & 0x80) ? 0xff : 0x00;
927                 } else {
928                         u16 *val = (u16 *)ghcb->shared_buffer;
929
930                         sign_byte = (*val & 0x8000) ? 0xff : 0x00;
931                 }
932                 memset(reg_data, sign_byte, insn->opnd_bytes);
933
934                 memcpy(reg_data, ghcb->shared_buffer, bytes);
935                 break;
936
937         default:
938                 ret = ES_UNSUPPORTED;
939         }
940
941         return ret;
942 }
943
944 /*
945  * The MOVS instruction has two memory operands, which raises the
946  * problem that it is not known whether the access to the source or the
947  * destination caused the #VC exception (and hence whether an MMIO read
948  * or write operation needs to be emulated).
949  *
950  * Instead of playing games with walking page-tables and trying to guess
951  * whether the source or destination is an MMIO range, split the move
952  * into two operations, a read and a write with only one memory operand.
953  * This will cause a nested #VC exception on the MMIO address which can
954  * then be handled.
955  *
956  * This implementation has the benefit that it also supports MOVS where
957  * source _and_ destination are MMIO regions.
958  *
959  * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
960  * rare operation. If it turns out to be a performance problem the split
961  * operations can be moved to memcpy_fromio() and memcpy_toio().
962  */
963 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
964                                           unsigned int bytes)
965 {
966         unsigned long ds_base, es_base;
967         unsigned char *src, *dst;
968         unsigned char buffer[8];
969         enum es_result ret;
970         bool rep;
971         int off;
972
973         ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
974         es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
975
976         if (ds_base == -1L || es_base == -1L) {
977                 ctxt->fi.vector = X86_TRAP_GP;
978                 ctxt->fi.error_code = 0;
979                 return ES_EXCEPTION;
980         }
981
982         src = ds_base + (unsigned char *)ctxt->regs->si;
983         dst = es_base + (unsigned char *)ctxt->regs->di;
984
985         ret = vc_read_mem(ctxt, src, buffer, bytes);
986         if (ret != ES_OK)
987                 return ret;
988
989         ret = vc_write_mem(ctxt, dst, buffer, bytes);
990         if (ret != ES_OK)
991                 return ret;
992
993         if (ctxt->regs->flags & X86_EFLAGS_DF)
994                 off = -bytes;
995         else
996                 off =  bytes;
997
998         ctxt->regs->si += off;
999         ctxt->regs->di += off;
1000
1001         rep = insn_has_rep_prefix(&ctxt->insn);
1002         if (rep)
1003                 ctxt->regs->cx -= 1;
1004
1005         if (!rep || ctxt->regs->cx == 0)
1006                 return ES_OK;
1007         else
1008                 return ES_RETRY;
1009 }
1010
1011 static enum es_result vc_handle_mmio(struct ghcb *ghcb,
1012                                      struct es_em_ctxt *ctxt)
1013 {
1014         struct insn *insn = &ctxt->insn;
1015         unsigned int bytes = 0;
1016         enum es_result ret;
1017         long *reg_data;
1018
1019         switch (insn->opcode.bytes[0]) {
1020         /* MMIO Write */
1021         case 0x88:
1022                 bytes = 1;
1023                 fallthrough;
1024         case 0x89:
1025                 if (!bytes)
1026                         bytes = insn->opnd_bytes;
1027
1028                 reg_data = vc_insn_get_reg(ctxt);
1029                 if (!reg_data)
1030                         return ES_DECODE_FAILED;
1031
1032                 memcpy(ghcb->shared_buffer, reg_data, bytes);
1033
1034                 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1035                 break;
1036
1037         case 0xc6:
1038                 bytes = 1;
1039                 fallthrough;
1040         case 0xc7:
1041                 if (!bytes)
1042                         bytes = insn->opnd_bytes;
1043
1044                 memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
1045
1046                 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1047                 break;
1048
1049                 /* MMIO Read */
1050         case 0x8a:
1051                 bytes = 1;
1052                 fallthrough;
1053         case 0x8b:
1054                 if (!bytes)
1055                         bytes = insn->opnd_bytes;
1056
1057                 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1058                 if (ret)
1059                         break;
1060
1061                 reg_data = vc_insn_get_reg(ctxt);
1062                 if (!reg_data)
1063                         return ES_DECODE_FAILED;
1064
1065                 /* Zero-extend for 32-bit operation */
1066                 if (bytes == 4)
1067                         *reg_data = 0;
1068
1069                 memcpy(reg_data, ghcb->shared_buffer, bytes);
1070                 break;
1071
1072                 /* MOVS instruction */
1073         case 0xa4:
1074                 bytes = 1;
1075                 fallthrough;
1076         case 0xa5:
1077                 if (!bytes)
1078                         bytes = insn->opnd_bytes;
1079
1080                 ret = vc_handle_mmio_movs(ctxt, bytes);
1081                 break;
1082                 /* Two-Byte Opcodes */
1083         case 0x0f:
1084                 ret = vc_handle_mmio_twobyte_ops(ghcb, ctxt);
1085                 break;
1086         default:
1087                 ret = ES_UNSUPPORTED;
1088         }
1089
1090         return ret;
1091 }
1092
1093 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1094                                           struct es_em_ctxt *ctxt)
1095 {
1096         struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1097         long val, *reg = vc_insn_get_rm(ctxt);
1098         enum es_result ret;
1099
1100         if (!reg)
1101                 return ES_DECODE_FAILED;
1102
1103         val = *reg;
1104
1105         /* Upper 32 bits must be written as zeroes */
1106         if (val >> 32) {
1107                 ctxt->fi.vector = X86_TRAP_GP;
1108                 ctxt->fi.error_code = 0;
1109                 return ES_EXCEPTION;
1110         }
1111
1112         /* Clear out other reserved bits and set bit 10 */
1113         val = (val & 0xffff23ffL) | BIT(10);
1114
1115         /* Early non-zero writes to DR7 are not supported */
1116         if (!data && (val & ~DR7_RESET_VALUE))
1117                 return ES_UNSUPPORTED;
1118
1119         /* Using a value of 0 for ExitInfo1 means RAX holds the value */
1120         ghcb_set_rax(ghcb, val);
1121         ret = sev_es_ghcb_hv_call(ghcb, true, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1122         if (ret != ES_OK)
1123                 return ret;
1124
1125         if (data)
1126                 data->dr7 = val;
1127
1128         return ES_OK;
1129 }
1130
1131 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1132                                          struct es_em_ctxt *ctxt)
1133 {
1134         struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1135         long *reg = vc_insn_get_rm(ctxt);
1136
1137         if (!reg)
1138                 return ES_DECODE_FAILED;
1139
1140         if (data)
1141                 *reg = data->dr7;
1142         else
1143                 *reg = DR7_RESET_VALUE;
1144
1145         return ES_OK;
1146 }
1147
1148 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1149                                        struct es_em_ctxt *ctxt)
1150 {
1151         return sev_es_ghcb_hv_call(ghcb, true, ctxt, SVM_EXIT_WBINVD, 0, 0);
1152 }
1153
1154 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1155 {
1156         enum es_result ret;
1157
1158         ghcb_set_rcx(ghcb, ctxt->regs->cx);
1159
1160         ret = sev_es_ghcb_hv_call(ghcb, true, ctxt, SVM_EXIT_RDPMC, 0, 0);
1161         if (ret != ES_OK)
1162                 return ret;
1163
1164         if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1165                 return ES_VMM_ERROR;
1166
1167         ctxt->regs->ax = ghcb->save.rax;
1168         ctxt->regs->dx = ghcb->save.rdx;
1169
1170         return ES_OK;
1171 }
1172
1173 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1174                                         struct es_em_ctxt *ctxt)
1175 {
1176         /*
1177          * Treat it as a NOP and do not leak a physical address to the
1178          * hypervisor.
1179          */
1180         return ES_OK;
1181 }
1182
1183 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1184                                       struct es_em_ctxt *ctxt)
1185 {
1186         /* Treat the same as MONITOR/MONITORX */
1187         return ES_OK;
1188 }
1189
1190 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1191                                         struct es_em_ctxt *ctxt)
1192 {
1193         enum es_result ret;
1194
1195         ghcb_set_rax(ghcb, ctxt->regs->ax);
1196         ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1197
1198         if (x86_platform.hyper.sev_es_hcall_prepare)
1199                 x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1200
1201         ret = sev_es_ghcb_hv_call(ghcb, true, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1202         if (ret != ES_OK)
1203                 return ret;
1204
1205         if (!ghcb_rax_is_valid(ghcb))
1206                 return ES_VMM_ERROR;
1207
1208         ctxt->regs->ax = ghcb->save.rax;
1209
1210         /*
1211          * Call sev_es_hcall_finish() after regs->ax is already set.
1212          * This allows the hypervisor handler to overwrite it again if
1213          * necessary.
1214          */
1215         if (x86_platform.hyper.sev_es_hcall_finish &&
1216             !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1217                 return ES_VMM_ERROR;
1218
1219         return ES_OK;
1220 }
1221
1222 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1223                                         struct es_em_ctxt *ctxt)
1224 {
1225         /*
1226          * Calling ecx_alignment_check() directly does not work, because it
1227          * enables IRQs and the GHCB is active. Forward the exception and call
1228          * it later from vc_forward_exception().
1229          */
1230         ctxt->fi.vector = X86_TRAP_AC;
1231         ctxt->fi.error_code = 0;
1232         return ES_EXCEPTION;
1233 }
1234
1235 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1236                                          struct ghcb *ghcb,
1237                                          unsigned long exit_code)
1238 {
1239         enum es_result result;
1240
1241         switch (exit_code) {
1242         case SVM_EXIT_READ_DR7:
1243                 result = vc_handle_dr7_read(ghcb, ctxt);
1244                 break;
1245         case SVM_EXIT_WRITE_DR7:
1246                 result = vc_handle_dr7_write(ghcb, ctxt);
1247                 break;
1248         case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1249                 result = vc_handle_trap_ac(ghcb, ctxt);
1250                 break;
1251         case SVM_EXIT_RDTSC:
1252         case SVM_EXIT_RDTSCP:
1253                 result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1254                 break;
1255         case SVM_EXIT_RDPMC:
1256                 result = vc_handle_rdpmc(ghcb, ctxt);
1257                 break;
1258         case SVM_EXIT_INVD:
1259                 pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1260                 result = ES_UNSUPPORTED;
1261                 break;
1262         case SVM_EXIT_CPUID:
1263                 result = vc_handle_cpuid(ghcb, ctxt);
1264                 break;
1265         case SVM_EXIT_IOIO:
1266                 result = vc_handle_ioio(ghcb, ctxt);
1267                 break;
1268         case SVM_EXIT_MSR:
1269                 result = vc_handle_msr(ghcb, ctxt);
1270                 break;
1271         case SVM_EXIT_VMMCALL:
1272                 result = vc_handle_vmmcall(ghcb, ctxt);
1273                 break;
1274         case SVM_EXIT_WBINVD:
1275                 result = vc_handle_wbinvd(ghcb, ctxt);
1276                 break;
1277         case SVM_EXIT_MONITOR:
1278                 result = vc_handle_monitor(ghcb, ctxt);
1279                 break;
1280         case SVM_EXIT_MWAIT:
1281                 result = vc_handle_mwait(ghcb, ctxt);
1282                 break;
1283         case SVM_EXIT_NPF:
1284                 result = vc_handle_mmio(ghcb, ctxt);
1285                 break;
1286         default:
1287                 /*
1288                  * Unexpected #VC exception
1289                  */
1290                 result = ES_UNSUPPORTED;
1291         }
1292
1293         return result;
1294 }
1295
1296 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1297 {
1298         long error_code = ctxt->fi.error_code;
1299         int trapnr = ctxt->fi.vector;
1300
1301         ctxt->regs->orig_ax = ctxt->fi.error_code;
1302
1303         switch (trapnr) {
1304         case X86_TRAP_GP:
1305                 exc_general_protection(ctxt->regs, error_code);
1306                 break;
1307         case X86_TRAP_UD:
1308                 exc_invalid_op(ctxt->regs);
1309                 break;
1310         case X86_TRAP_PF:
1311                 write_cr2(ctxt->fi.cr2);
1312                 exc_page_fault(ctxt->regs, error_code);
1313                 break;
1314         case X86_TRAP_AC:
1315                 exc_alignment_check(ctxt->regs, error_code);
1316                 break;
1317         default:
1318                 pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1319                 BUG();
1320         }
1321 }
1322
1323 static __always_inline bool is_vc2_stack(unsigned long sp)
1324 {
1325         return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1326 }
1327
1328 static __always_inline bool vc_from_invalid_context(struct pt_regs *regs)
1329 {
1330         unsigned long sp, prev_sp;
1331
1332         sp      = (unsigned long)regs;
1333         prev_sp = regs->sp;
1334
1335         /*
1336          * If the code was already executing on the VC2 stack when the #VC
1337          * happened, let it proceed to the normal handling routine. This way the
1338          * code executing on the VC2 stack can cause #VC exceptions to get handled.
1339          */
1340         return is_vc2_stack(sp) && !is_vc2_stack(prev_sp);
1341 }
1342
1343 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
1344 {
1345         struct ghcb_state state;
1346         struct es_em_ctxt ctxt;
1347         enum es_result result;
1348         struct ghcb *ghcb;
1349         bool ret = true;
1350
1351         ghcb = __sev_get_ghcb(&state);
1352
1353         vc_ghcb_invalidate(ghcb);
1354         result = vc_init_em_ctxt(&ctxt, regs, error_code);
1355
1356         if (result == ES_OK)
1357                 result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1358
1359         __sev_put_ghcb(&state);
1360
1361         /* Done - now check the result */
1362         switch (result) {
1363         case ES_OK:
1364                 vc_finish_insn(&ctxt);
1365                 break;
1366         case ES_UNSUPPORTED:
1367                 pr_err_ratelimited("Unsupported exit-code 0x%02lx in #VC exception (IP: 0x%lx)\n",
1368                                    error_code, regs->ip);
1369                 ret = false;
1370                 break;
1371         case ES_VMM_ERROR:
1372                 pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1373                                    error_code, regs->ip);
1374                 ret = false;
1375                 break;
1376         case ES_DECODE_FAILED:
1377                 pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1378                                    error_code, regs->ip);
1379                 ret = false;
1380                 break;
1381         case ES_EXCEPTION:
1382                 vc_forward_exception(&ctxt);
1383                 break;
1384         case ES_RETRY:
1385                 /* Nothing to do */
1386                 break;
1387         default:
1388                 pr_emerg("Unknown result in %s():%d\n", __func__, result);
1389                 /*
1390                  * Emulating the instruction which caused the #VC exception
1391                  * failed - can't continue so print debug information
1392                  */
1393                 BUG();
1394         }
1395
1396         return ret;
1397 }
1398
1399 static __always_inline bool vc_is_db(unsigned long error_code)
1400 {
1401         return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
1402 }
1403
1404 /*
1405  * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
1406  * and will panic when an error happens.
1407  */
1408 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
1409 {
1410         irqentry_state_t irq_state;
1411
1412         /*
1413          * With the current implementation it is always possible to switch to a
1414          * safe stack because #VC exceptions only happen at known places, like
1415          * intercepted instructions or accesses to MMIO areas/IO ports. They can
1416          * also happen with code instrumentation when the hypervisor intercepts
1417          * #DB, but the critical paths are forbidden to be instrumented, so #DB
1418          * exceptions currently also only happen in safe places.
1419          *
1420          * But keep this here in case the noinstr annotations are violated due
1421          * to bug elsewhere.
1422          */
1423         if (unlikely(vc_from_invalid_context(regs))) {
1424                 instrumentation_begin();
1425                 panic("Can't handle #VC exception from unsupported context\n");
1426                 instrumentation_end();
1427         }
1428
1429         /*
1430          * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1431          */
1432         if (vc_is_db(error_code)) {
1433                 exc_debug(regs);
1434                 return;
1435         }
1436
1437         irq_state = irqentry_nmi_enter(regs);
1438
1439         instrumentation_begin();
1440
1441         if (!vc_raw_handle_exception(regs, error_code)) {
1442                 /* Show some debug info */
1443                 show_regs(regs);
1444
1445                 /* Ask hypervisor to sev_es_terminate */
1446                 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1447
1448                 /* If that fails and we get here - just panic */
1449                 panic("Returned from Terminate-Request to Hypervisor\n");
1450         }
1451
1452         instrumentation_end();
1453         irqentry_nmi_exit(regs, irq_state);
1454 }
1455
1456 /*
1457  * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
1458  * and will kill the current task with SIGBUS when an error happens.
1459  */
1460 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
1461 {
1462         /*
1463          * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1464          */
1465         if (vc_is_db(error_code)) {
1466                 noist_exc_debug(regs);
1467                 return;
1468         }
1469
1470         irqentry_enter_from_user_mode(regs);
1471         instrumentation_begin();
1472
1473         if (!vc_raw_handle_exception(regs, error_code)) {
1474                 /*
1475                  * Do not kill the machine if user-space triggered the
1476                  * exception. Send SIGBUS instead and let user-space deal with
1477                  * it.
1478                  */
1479                 force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1480         }
1481
1482         instrumentation_end();
1483         irqentry_exit_to_user_mode(regs);
1484 }
1485
1486 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1487 {
1488         unsigned long exit_code = regs->orig_ax;
1489         struct es_em_ctxt ctxt;
1490         enum es_result result;
1491
1492         /* Do initial setup or terminate the guest */
1493         if (unlikely(boot_ghcb == NULL && !sev_es_setup_ghcb()))
1494                 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1495
1496         vc_ghcb_invalidate(boot_ghcb);
1497
1498         result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1499         if (result == ES_OK)
1500                 result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1501
1502         /* Done - now check the result */
1503         switch (result) {
1504         case ES_OK:
1505                 vc_finish_insn(&ctxt);
1506                 break;
1507         case ES_UNSUPPORTED:
1508                 early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1509                                 exit_code, regs->ip);
1510                 goto fail;
1511         case ES_VMM_ERROR:
1512                 early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1513                                 exit_code, regs->ip);
1514                 goto fail;
1515         case ES_DECODE_FAILED:
1516                 early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1517                                 exit_code, regs->ip);
1518                 goto fail;
1519         case ES_EXCEPTION:
1520                 vc_early_forward_exception(&ctxt);
1521                 break;
1522         case ES_RETRY:
1523                 /* Nothing to do */
1524                 break;
1525         default:
1526                 BUG();
1527         }
1528
1529         return true;
1530
1531 fail:
1532         show_regs(regs);
1533
1534         while (true)
1535                 halt();
1536 }