1 // SPDX-License-Identifier: GPL-2.0-only
3 * AMD Memory Encryption Support
5 * Copyright (C) 2019 SUSE
7 * Author: Joerg Roedel <jroedel@suse.de>
10 #define pr_fmt(fmt) "SEV-ES: " fmt
12 #include <linux/sched/debug.h> /* For show_regs() */
13 #include <linux/percpu-defs.h>
14 #include <linux/mem_encrypt.h>
15 #include <linux/lockdep.h>
16 #include <linux/printk.h>
17 #include <linux/mm_types.h>
18 #include <linux/set_memory.h>
19 #include <linux/memblock.h>
20 #include <linux/kernel.h>
23 #include <asm/cpu_entry_area.h>
24 #include <asm/stacktrace.h>
26 #include <asm/insn-eval.h>
27 #include <asm/fpu/internal.h>
28 #include <asm/processor.h>
29 #include <asm/realmode.h>
30 #include <asm/traps.h>
35 #define DR7_RESET_VALUE 0x400
37 /* For early boot hypervisor communication in SEV-ES enabled guests */
38 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
41 * Needs to be in the .data section because we need it NULL before bss is
44 static struct ghcb __initdata *boot_ghcb;
46 /* #VC handler runtime per-CPU data */
47 struct sev_es_runtime_data {
48 struct ghcb ghcb_page;
50 /* Physical storage for the per-CPU IST stack of the #VC handler */
51 char ist_stack[EXCEPTION_STKSZ] __aligned(PAGE_SIZE);
54 * Physical storage for the per-CPU fall-back stack of the #VC handler.
55 * The fall-back stack is used when it is not safe to switch back to the
56 * interrupted stack in the #VC entry code.
58 char fallback_stack[EXCEPTION_STKSZ] __aligned(PAGE_SIZE);
61 * Reserve one page per CPU as backup storage for the unencrypted GHCB.
62 * It is needed when an NMI happens while the #VC handler uses the real
63 * GHCB, and the NMI handler itself is causing another #VC exception. In
64 * that case the GHCB content of the first handler needs to be backed up
67 struct ghcb backup_ghcb;
70 * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
71 * There is no need for it to be atomic, because nothing is written to
72 * the GHCB between the read and the write of ghcb_active. So it is safe
73 * to use it when a nested #VC exception happens before the write.
75 * This is necessary for example in the #VC->NMI->#VC case when the NMI
76 * happens while the first #VC handler uses the GHCB. When the NMI code
77 * raises a second #VC handler it might overwrite the contents of the
78 * GHCB written by the first handler. To avoid this the content of the
79 * GHCB is saved and restored when the GHCB is detected to be in use
83 bool backup_ghcb_active;
86 * Cached DR7 value - write it on DR7 writes and return it on reads.
87 * That value will never make it to the real hardware DR7 as debugging
88 * is currently unsupported in SEV-ES guests.
97 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
98 DEFINE_STATIC_KEY_FALSE(sev_es_enable_key);
100 /* Needed in vc_early_forward_exception */
101 void do_early_exception(struct pt_regs *regs, int trapnr);
103 static void __init setup_vc_stacks(int cpu)
105 struct sev_es_runtime_data *data;
106 struct cpu_entry_area *cea;
110 data = per_cpu(runtime_data, cpu);
111 cea = get_cpu_entry_area(cpu);
113 /* Map #VC IST stack */
114 vaddr = CEA_ESTACK_BOT(&cea->estacks, VC);
115 pa = __pa(data->ist_stack);
116 cea_set_pte((void *)vaddr, pa, PAGE_KERNEL);
118 /* Map VC fall-back stack */
119 vaddr = CEA_ESTACK_BOT(&cea->estacks, VC2);
120 pa = __pa(data->fallback_stack);
121 cea_set_pte((void *)vaddr, pa, PAGE_KERNEL);
124 static __always_inline bool on_vc_stack(struct pt_regs *regs)
126 unsigned long sp = regs->sp;
128 /* User-mode RSP is not trusted */
132 /* SYSCALL gap still has user-mode RSP */
133 if (ip_within_syscall_gap(regs))
136 return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
140 * This function handles the case when an NMI is raised in the #VC
141 * exception handler entry code, before the #VC handler has switched off
142 * its IST stack. In this case, the IST entry for #VC must be adjusted,
143 * so that any nested #VC exception will not overwrite the stack
144 * contents of the interrupted #VC handler.
146 * The IST entry is adjusted unconditionally so that it can be also be
147 * unconditionally adjusted back in __sev_es_ist_exit(). Otherwise a
148 * nested sev_es_ist_exit() call may adjust back the IST entry too
151 * The __sev_es_ist_enter() and __sev_es_ist_exit() functions always run
152 * on the NMI IST stack, as they are only called from NMI handling code
155 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
157 unsigned long old_ist, new_ist;
159 /* Read old IST entry */
160 new_ist = old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
163 * If NMI happened while on the #VC IST stack, set the new IST
164 * value below regs->sp, so that the interrupted stack frame is
165 * not overwritten by subsequent #VC exceptions.
167 if (on_vc_stack(regs))
171 * Reserve additional 8 bytes and store old IST value so this
172 * adjustment can be unrolled in __sev_es_ist_exit().
174 new_ist -= sizeof(old_ist);
175 *(unsigned long *)new_ist = old_ist;
177 /* Set new IST entry */
178 this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
181 void noinstr __sev_es_ist_exit(void)
186 ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
188 if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
191 /* Read back old IST entry and write it to the TSS */
192 this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
195 static __always_inline struct ghcb *sev_es_get_ghcb(struct ghcb_state *state)
197 struct sev_es_runtime_data *data;
200 data = this_cpu_read(runtime_data);
201 ghcb = &data->ghcb_page;
203 if (unlikely(data->ghcb_active)) {
204 /* GHCB is already in use - save its contents */
206 if (unlikely(data->backup_ghcb_active)) {
208 * Backup-GHCB is also already in use. There is no way
209 * to continue here so just kill the machine. To make
210 * panic() work, mark GHCBs inactive so that messages
211 * can be printed out.
213 data->ghcb_active = false;
214 data->backup_ghcb_active = false;
216 panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
219 /* Mark backup_ghcb active before writing to it */
220 data->backup_ghcb_active = true;
222 state->ghcb = &data->backup_ghcb;
224 /* Backup GHCB content */
225 *state->ghcb = *ghcb;
228 data->ghcb_active = true;
234 /* Needed in vc_early_forward_exception */
235 void do_early_exception(struct pt_regs *regs, int trapnr);
237 static inline u64 sev_es_rd_ghcb_msr(void)
239 return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
242 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
247 high = (u32)(val >> 32);
249 native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
252 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
253 unsigned char *buffer)
255 return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
258 static enum es_result __vc_decode_user_insn(struct es_em_ctxt *ctxt)
260 char buffer[MAX_INSN_SIZE];
263 res = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
265 ctxt->fi.vector = X86_TRAP_PF;
266 ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
267 ctxt->fi.cr2 = ctxt->regs->ip;
271 if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, res))
272 return ES_DECODE_FAILED;
274 if (ctxt->insn.immediate.got)
277 return ES_DECODE_FAILED;
280 static enum es_result __vc_decode_kern_insn(struct es_em_ctxt *ctxt)
282 char buffer[MAX_INSN_SIZE];
285 res = vc_fetch_insn_kernel(ctxt, buffer);
287 ctxt->fi.vector = X86_TRAP_PF;
288 ctxt->fi.error_code = X86_PF_INSTR;
289 ctxt->fi.cr2 = ctxt->regs->ip;
293 ret = insn_decode(&ctxt->insn, buffer, MAX_INSN_SIZE, INSN_MODE_64);
295 return ES_DECODE_FAILED;
300 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
302 if (user_mode(ctxt->regs))
303 return __vc_decode_user_insn(ctxt);
305 return __vc_decode_kern_insn(ctxt);
308 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
309 char *dst, char *buf, size_t size)
311 unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
312 char __user *target = (char __user *)dst;
319 * This function uses __put_user() independent of whether kernel or user
320 * memory is accessed. This works fine because __put_user() does no
321 * sanity checks of the pointer being accessed. All that it does is
322 * to report when the access failed.
324 * Also, this function runs in atomic context, so __put_user() is not
325 * allowed to sleep. The page-fault handler detects that it is running
326 * in atomic context and will not try to take mmap_sem and handle the
327 * fault, so additional pagefault_enable()/disable() calls are not
330 * The access can't be done via copy_to_user() here because
331 * vc_write_mem() must not use string instructions to access unsafe
332 * memory. The reason is that MOVS is emulated by the #VC handler by
333 * splitting the move up into a read and a write and taking a nested #VC
334 * exception on whatever of them is the MMIO access. Using string
335 * instructions here would cause infinite nesting.
340 if (__put_user(d1, target))
345 if (__put_user(d2, target))
350 if (__put_user(d4, target))
355 if (__put_user(d8, target))
359 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
360 return ES_UNSUPPORTED;
366 if (user_mode(ctxt->regs))
367 error_code |= X86_PF_USER;
369 ctxt->fi.vector = X86_TRAP_PF;
370 ctxt->fi.error_code = error_code;
371 ctxt->fi.cr2 = (unsigned long)dst;
376 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
377 char *src, char *buf, size_t size)
379 unsigned long error_code = X86_PF_PROT;
380 char __user *s = (char __user *)src;
387 * This function uses __get_user() independent of whether kernel or user
388 * memory is accessed. This works fine because __get_user() does no
389 * sanity checks of the pointer being accessed. All that it does is
390 * to report when the access failed.
392 * Also, this function runs in atomic context, so __get_user() is not
393 * allowed to sleep. The page-fault handler detects that it is running
394 * in atomic context and will not try to take mmap_sem and handle the
395 * fault, so additional pagefault_enable()/disable() calls are not
398 * The access can't be done via copy_from_user() here because
399 * vc_read_mem() must not use string instructions to access unsafe
400 * memory. The reason is that MOVS is emulated by the #VC handler by
401 * splitting the move up into a read and a write and taking a nested #VC
402 * exception on whatever of them is the MMIO access. Using string
403 * instructions here would cause infinite nesting.
407 if (__get_user(d1, s))
412 if (__get_user(d2, s))
417 if (__get_user(d4, s))
422 if (__get_user(d8, s))
427 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
428 return ES_UNSUPPORTED;
434 if (user_mode(ctxt->regs))
435 error_code |= X86_PF_USER;
437 ctxt->fi.vector = X86_TRAP_PF;
438 ctxt->fi.error_code = error_code;
439 ctxt->fi.cr2 = (unsigned long)src;
444 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
445 unsigned long vaddr, phys_addr_t *paddr)
447 unsigned long va = (unsigned long)vaddr;
453 pgd = __va(read_cr3_pa());
454 pgd = &pgd[pgd_index(va)];
455 pte = lookup_address_in_pgd(pgd, va, &level);
457 ctxt->fi.vector = X86_TRAP_PF;
458 ctxt->fi.cr2 = vaddr;
459 ctxt->fi.error_code = 0;
461 if (user_mode(ctxt->regs))
462 ctxt->fi.error_code |= X86_PF_USER;
467 if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
468 /* Emulated MMIO to/from encrypted memory not supported */
469 return ES_UNSUPPORTED;
471 pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
472 pa |= va & ~page_level_mask(level);
479 /* Include code shared with pre-decompression boot stage */
480 #include "sev-shared.c"
482 static __always_inline void sev_es_put_ghcb(struct ghcb_state *state)
484 struct sev_es_runtime_data *data;
487 data = this_cpu_read(runtime_data);
488 ghcb = &data->ghcb_page;
491 /* Restore GHCB from Backup */
492 *ghcb = *state->ghcb;
493 data->backup_ghcb_active = false;
497 * Invalidate the GHCB so a VMGEXIT instruction issued
498 * from userspace won't appear to be valid.
500 vc_ghcb_invalidate(ghcb);
501 data->ghcb_active = false;
505 void noinstr __sev_es_nmi_complete(void)
507 struct ghcb_state state;
510 ghcb = sev_es_get_ghcb(&state);
512 vc_ghcb_invalidate(ghcb);
513 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
514 ghcb_set_sw_exit_info_1(ghcb, 0);
515 ghcb_set_sw_exit_info_2(ghcb, 0);
517 sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
520 sev_es_put_ghcb(&state);
523 static u64 get_jump_table_addr(void)
525 struct ghcb_state state;
530 local_irq_save(flags);
532 ghcb = sev_es_get_ghcb(&state);
534 vc_ghcb_invalidate(ghcb);
535 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
536 ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
537 ghcb_set_sw_exit_info_2(ghcb, 0);
539 sev_es_wr_ghcb_msr(__pa(ghcb));
542 if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
543 ghcb_sw_exit_info_2_is_valid(ghcb))
544 ret = ghcb->save.sw_exit_info_2;
546 sev_es_put_ghcb(&state);
548 local_irq_restore(flags);
553 int sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
555 u16 startup_cs, startup_ip;
556 phys_addr_t jump_table_pa;
558 u16 __iomem *jump_table;
560 jump_table_addr = get_jump_table_addr();
562 /* On UP guests there is no jump table so this is not a failure */
563 if (!jump_table_addr)
566 /* Check if AP Jump Table is page-aligned */
567 if (jump_table_addr & ~PAGE_MASK)
570 jump_table_pa = jump_table_addr & PAGE_MASK;
572 startup_cs = (u16)(rmh->trampoline_start >> 4);
573 startup_ip = (u16)(rmh->sev_es_trampoline_start -
574 rmh->trampoline_start);
576 jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
580 writew(startup_ip, &jump_table[0]);
581 writew(startup_cs, &jump_table[1]);
589 * This is needed by the OVMF UEFI firmware which will use whatever it finds in
590 * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
591 * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
593 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
595 struct sev_es_runtime_data *data;
596 unsigned long address, pflags;
600 if (!sev_es_active())
603 pflags = _PAGE_NX | _PAGE_RW;
605 for_each_possible_cpu(cpu) {
606 data = per_cpu(runtime_data, cpu);
608 address = __pa(&data->ghcb_page);
609 pfn = address >> PAGE_SHIFT;
611 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
618 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
620 struct pt_regs *regs = ctxt->regs;
625 exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
627 ghcb_set_rcx(ghcb, regs->cx);
629 ghcb_set_rax(ghcb, regs->ax);
630 ghcb_set_rdx(ghcb, regs->dx);
633 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
635 if ((ret == ES_OK) && (!exit_info_1)) {
636 regs->ax = ghcb->save.rax;
637 regs->dx = ghcb->save.rdx;
644 * This function runs on the first #VC exception after the kernel
645 * switched to virtual addresses.
647 static bool __init sev_es_setup_ghcb(void)
649 /* First make sure the hypervisor talks a supported protocol. */
650 if (!sev_es_negotiate_protocol())
654 * Clear the boot_ghcb. The first exception comes in before the bss
655 * section is cleared.
657 memset(&boot_ghcb_page, 0, PAGE_SIZE);
659 /* Alright - Make the boot-ghcb public */
660 boot_ghcb = &boot_ghcb_page;
665 #ifdef CONFIG_HOTPLUG_CPU
666 static void sev_es_ap_hlt_loop(void)
668 struct ghcb_state state;
671 ghcb = sev_es_get_ghcb(&state);
674 vc_ghcb_invalidate(ghcb);
675 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
676 ghcb_set_sw_exit_info_1(ghcb, 0);
677 ghcb_set_sw_exit_info_2(ghcb, 0);
679 sev_es_wr_ghcb_msr(__pa(ghcb));
683 if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
684 ghcb->save.sw_exit_info_2)
688 sev_es_put_ghcb(&state);
692 * Play_dead handler when running under SEV-ES. This is needed because
693 * the hypervisor can't deliver an SIPI request to restart the AP.
694 * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
695 * hypervisor wakes it up again.
697 static void sev_es_play_dead(void)
701 /* IRQs now disabled */
703 sev_es_ap_hlt_loop();
706 * If we get here, the VCPU was woken up again. Jump to CPU
707 * startup code to get it back online.
711 #else /* CONFIG_HOTPLUG_CPU */
712 #define sev_es_play_dead native_play_dead
713 #endif /* CONFIG_HOTPLUG_CPU */
716 static void __init sev_es_setup_play_dead(void)
718 smp_ops.play_dead = sev_es_play_dead;
721 static inline void sev_es_setup_play_dead(void) { }
724 static void __init alloc_runtime_data(int cpu)
726 struct sev_es_runtime_data *data;
728 data = memblock_alloc(sizeof(*data), PAGE_SIZE);
730 panic("Can't allocate SEV-ES runtime data");
732 per_cpu(runtime_data, cpu) = data;
735 static void __init init_ghcb(int cpu)
737 struct sev_es_runtime_data *data;
740 data = per_cpu(runtime_data, cpu);
742 err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
743 sizeof(data->ghcb_page));
745 panic("Can't map GHCBs unencrypted");
747 memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
749 data->ghcb_active = false;
750 data->backup_ghcb_active = false;
753 void __init sev_es_init_vc_handling(void)
757 BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
759 if (!sev_es_active())
762 if (!sev_es_check_cpu_features())
763 panic("SEV-ES CPU Features missing");
765 /* Enable SEV-ES special handling */
766 static_branch_enable(&sev_es_enable_key);
768 /* Initialize per-cpu GHCB pages */
769 for_each_possible_cpu(cpu) {
770 alloc_runtime_data(cpu);
772 setup_vc_stacks(cpu);
775 sev_es_setup_play_dead();
777 /* Secondary CPUs use the runtime #VC handler */
778 initial_vc_handler = (unsigned long)safe_stack_exc_vmm_communication;
781 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
783 int trapnr = ctxt->fi.vector;
785 if (trapnr == X86_TRAP_PF)
786 native_write_cr2(ctxt->fi.cr2);
788 ctxt->regs->orig_ax = ctxt->fi.error_code;
789 do_early_exception(ctxt->regs, trapnr);
792 static long *vc_insn_get_reg(struct es_em_ctxt *ctxt)
797 reg_array = (long *)ctxt->regs;
798 offset = insn_get_modrm_reg_off(&ctxt->insn, ctxt->regs);
803 offset /= sizeof(long);
805 return reg_array + offset;
808 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
813 reg_array = (long *)ctxt->regs;
814 offset = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
819 offset /= sizeof(long);
821 return reg_array + offset;
823 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
824 unsigned int bytes, bool read)
826 u64 exit_code, exit_info_1, exit_info_2;
827 unsigned long ghcb_pa = __pa(ghcb);
832 ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
833 if (ref == (void __user *)-1L)
834 return ES_UNSUPPORTED;
836 exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
838 res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
840 if (res == ES_EXCEPTION && !read)
841 ctxt->fi.error_code |= X86_PF_WRITE;
847 /* Can never be greater than 8 */
850 ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
852 return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
855 static enum es_result vc_handle_mmio_twobyte_ops(struct ghcb *ghcb,
856 struct es_em_ctxt *ctxt)
858 struct insn *insn = &ctxt->insn;
859 unsigned int bytes = 0;
864 switch (insn->opcode.bytes[1]) {
865 /* MMIO Read w/ zero-extension */
873 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
877 /* Zero extend based on operand size */
878 reg_data = vc_insn_get_reg(ctxt);
880 return ES_DECODE_FAILED;
882 memset(reg_data, 0, insn->opnd_bytes);
884 memcpy(reg_data, ghcb->shared_buffer, bytes);
887 /* MMIO Read w/ sign-extension */
895 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
899 /* Sign extend based on operand size */
900 reg_data = vc_insn_get_reg(ctxt);
902 return ES_DECODE_FAILED;
905 u8 *val = (u8 *)ghcb->shared_buffer;
907 sign_byte = (*val & 0x80) ? 0xff : 0x00;
909 u16 *val = (u16 *)ghcb->shared_buffer;
911 sign_byte = (*val & 0x8000) ? 0xff : 0x00;
913 memset(reg_data, sign_byte, insn->opnd_bytes);
915 memcpy(reg_data, ghcb->shared_buffer, bytes);
919 ret = ES_UNSUPPORTED;
926 * The MOVS instruction has two memory operands, which raises the
927 * problem that it is not known whether the access to the source or the
928 * destination caused the #VC exception (and hence whether an MMIO read
929 * or write operation needs to be emulated).
931 * Instead of playing games with walking page-tables and trying to guess
932 * whether the source or destination is an MMIO range, split the move
933 * into two operations, a read and a write with only one memory operand.
934 * This will cause a nested #VC exception on the MMIO address which can
937 * This implementation has the benefit that it also supports MOVS where
938 * source _and_ destination are MMIO regions.
940 * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
941 * rare operation. If it turns out to be a performance problem the split
942 * operations can be moved to memcpy_fromio() and memcpy_toio().
944 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
947 unsigned long ds_base, es_base;
948 unsigned char *src, *dst;
949 unsigned char buffer[8];
954 ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
955 es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
957 if (ds_base == -1L || es_base == -1L) {
958 ctxt->fi.vector = X86_TRAP_GP;
959 ctxt->fi.error_code = 0;
963 src = ds_base + (unsigned char *)ctxt->regs->si;
964 dst = es_base + (unsigned char *)ctxt->regs->di;
966 ret = vc_read_mem(ctxt, src, buffer, bytes);
970 ret = vc_write_mem(ctxt, dst, buffer, bytes);
974 if (ctxt->regs->flags & X86_EFLAGS_DF)
979 ctxt->regs->si += off;
980 ctxt->regs->di += off;
982 rep = insn_has_rep_prefix(&ctxt->insn);
986 if (!rep || ctxt->regs->cx == 0)
992 static enum es_result vc_handle_mmio(struct ghcb *ghcb,
993 struct es_em_ctxt *ctxt)
995 struct insn *insn = &ctxt->insn;
996 unsigned int bytes = 0;
1000 switch (insn->opcode.bytes[0]) {
1007 bytes = insn->opnd_bytes;
1009 reg_data = vc_insn_get_reg(ctxt);
1011 return ES_DECODE_FAILED;
1013 memcpy(ghcb->shared_buffer, reg_data, bytes);
1015 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1023 bytes = insn->opnd_bytes;
1025 memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
1027 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1036 bytes = insn->opnd_bytes;
1038 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1042 reg_data = vc_insn_get_reg(ctxt);
1044 return ES_DECODE_FAILED;
1046 /* Zero-extend for 32-bit operation */
1050 memcpy(reg_data, ghcb->shared_buffer, bytes);
1053 /* MOVS instruction */
1059 bytes = insn->opnd_bytes;
1061 ret = vc_handle_mmio_movs(ctxt, bytes);
1063 /* Two-Byte Opcodes */
1065 ret = vc_handle_mmio_twobyte_ops(ghcb, ctxt);
1068 ret = ES_UNSUPPORTED;
1074 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1075 struct es_em_ctxt *ctxt)
1077 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1078 long val, *reg = vc_insn_get_rm(ctxt);
1082 return ES_DECODE_FAILED;
1086 /* Upper 32 bits must be written as zeroes */
1088 ctxt->fi.vector = X86_TRAP_GP;
1089 ctxt->fi.error_code = 0;
1090 return ES_EXCEPTION;
1093 /* Clear out other reserved bits and set bit 10 */
1094 val = (val & 0xffff23ffL) | BIT(10);
1096 /* Early non-zero writes to DR7 are not supported */
1097 if (!data && (val & ~DR7_RESET_VALUE))
1098 return ES_UNSUPPORTED;
1100 /* Using a value of 0 for ExitInfo1 means RAX holds the value */
1101 ghcb_set_rax(ghcb, val);
1102 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1112 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1113 struct es_em_ctxt *ctxt)
1115 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1116 long *reg = vc_insn_get_rm(ctxt);
1119 return ES_DECODE_FAILED;
1124 *reg = DR7_RESET_VALUE;
1129 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1130 struct es_em_ctxt *ctxt)
1132 return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1135 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1139 ghcb_set_rcx(ghcb, ctxt->regs->cx);
1141 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1145 if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1146 return ES_VMM_ERROR;
1148 ctxt->regs->ax = ghcb->save.rax;
1149 ctxt->regs->dx = ghcb->save.rdx;
1154 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1155 struct es_em_ctxt *ctxt)
1158 * Treat it as a NOP and do not leak a physical address to the
1164 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1165 struct es_em_ctxt *ctxt)
1167 /* Treat the same as MONITOR/MONITORX */
1171 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1172 struct es_em_ctxt *ctxt)
1176 ghcb_set_rax(ghcb, ctxt->regs->ax);
1177 ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1179 if (x86_platform.hyper.sev_es_hcall_prepare)
1180 x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1182 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1186 if (!ghcb_rax_is_valid(ghcb))
1187 return ES_VMM_ERROR;
1189 ctxt->regs->ax = ghcb->save.rax;
1192 * Call sev_es_hcall_finish() after regs->ax is already set.
1193 * This allows the hypervisor handler to overwrite it again if
1196 if (x86_platform.hyper.sev_es_hcall_finish &&
1197 !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1198 return ES_VMM_ERROR;
1203 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1204 struct es_em_ctxt *ctxt)
1207 * Calling ecx_alignment_check() directly does not work, because it
1208 * enables IRQs and the GHCB is active. Forward the exception and call
1209 * it later from vc_forward_exception().
1211 ctxt->fi.vector = X86_TRAP_AC;
1212 ctxt->fi.error_code = 0;
1213 return ES_EXCEPTION;
1216 static __always_inline void vc_handle_trap_db(struct pt_regs *regs)
1218 if (user_mode(regs))
1219 noist_exc_debug(regs);
1224 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1226 unsigned long exit_code)
1228 enum es_result result;
1230 switch (exit_code) {
1231 case SVM_EXIT_READ_DR7:
1232 result = vc_handle_dr7_read(ghcb, ctxt);
1234 case SVM_EXIT_WRITE_DR7:
1235 result = vc_handle_dr7_write(ghcb, ctxt);
1237 case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1238 result = vc_handle_trap_ac(ghcb, ctxt);
1240 case SVM_EXIT_RDTSC:
1241 case SVM_EXIT_RDTSCP:
1242 result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1244 case SVM_EXIT_RDPMC:
1245 result = vc_handle_rdpmc(ghcb, ctxt);
1248 pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1249 result = ES_UNSUPPORTED;
1251 case SVM_EXIT_CPUID:
1252 result = vc_handle_cpuid(ghcb, ctxt);
1255 result = vc_handle_ioio(ghcb, ctxt);
1258 result = vc_handle_msr(ghcb, ctxt);
1260 case SVM_EXIT_VMMCALL:
1261 result = vc_handle_vmmcall(ghcb, ctxt);
1263 case SVM_EXIT_WBINVD:
1264 result = vc_handle_wbinvd(ghcb, ctxt);
1266 case SVM_EXIT_MONITOR:
1267 result = vc_handle_monitor(ghcb, ctxt);
1269 case SVM_EXIT_MWAIT:
1270 result = vc_handle_mwait(ghcb, ctxt);
1273 result = vc_handle_mmio(ghcb, ctxt);
1277 * Unexpected #VC exception
1279 result = ES_UNSUPPORTED;
1285 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1287 long error_code = ctxt->fi.error_code;
1288 int trapnr = ctxt->fi.vector;
1290 ctxt->regs->orig_ax = ctxt->fi.error_code;
1294 exc_general_protection(ctxt->regs, error_code);
1297 exc_invalid_op(ctxt->regs);
1300 write_cr2(ctxt->fi.cr2);
1301 exc_page_fault(ctxt->regs, error_code);
1304 exc_alignment_check(ctxt->regs, error_code);
1307 pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1312 static __always_inline bool on_vc_fallback_stack(struct pt_regs *regs)
1314 unsigned long sp = (unsigned long)regs;
1316 return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1320 * Main #VC exception handler. It is called when the entry code was able to
1321 * switch off the IST to a safe kernel stack.
1323 * With the current implementation it is always possible to switch to a safe
1324 * stack because #VC exceptions only happen at known places, like intercepted
1325 * instructions or accesses to MMIO areas/IO ports. They can also happen with
1326 * code instrumentation when the hypervisor intercepts #DB, but the critical
1327 * paths are forbidden to be instrumented, so #DB exceptions currently also
1328 * only happen in safe places.
1330 DEFINE_IDTENTRY_VC_SAFE_STACK(exc_vmm_communication)
1332 irqentry_state_t irq_state;
1333 struct ghcb_state state;
1334 struct es_em_ctxt ctxt;
1335 enum es_result result;
1339 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1341 if (error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB) {
1342 vc_handle_trap_db(regs);
1346 irq_state = irqentry_nmi_enter(regs);
1347 lockdep_assert_irqs_disabled();
1348 instrumentation_begin();
1351 * This is invoked through an interrupt gate, so IRQs are disabled. The
1352 * code below might walk page-tables for user or kernel addresses, so
1353 * keep the IRQs disabled to protect us against concurrent TLB flushes.
1356 ghcb = sev_es_get_ghcb(&state);
1358 vc_ghcb_invalidate(ghcb);
1359 result = vc_init_em_ctxt(&ctxt, regs, error_code);
1361 if (result == ES_OK)
1362 result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1364 sev_es_put_ghcb(&state);
1366 /* Done - now check the result */
1369 vc_finish_insn(&ctxt);
1371 case ES_UNSUPPORTED:
1372 pr_err_ratelimited("Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1373 error_code, regs->ip);
1376 pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1377 error_code, regs->ip);
1379 case ES_DECODE_FAILED:
1380 pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1381 error_code, regs->ip);
1384 vc_forward_exception(&ctxt);
1390 pr_emerg("Unknown result in %s():%d\n", __func__, result);
1392 * Emulating the instruction which caused the #VC exception
1393 * failed - can't continue so print debug information
1399 instrumentation_end();
1400 irqentry_nmi_exit(regs, irq_state);
1405 if (user_mode(regs)) {
1407 * Do not kill the machine if user-space triggered the
1408 * exception. Send SIGBUS instead and let user-space deal with
1411 force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1413 pr_emerg("PANIC: Unhandled #VC exception in kernel space (result=%d)\n",
1416 /* Show some debug info */
1419 /* Ask hypervisor to sev_es_terminate */
1420 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1422 /* If that fails and we get here - just panic */
1423 panic("Returned from Terminate-Request to Hypervisor\n");
1429 /* This handler runs on the #VC fall-back stack. It can cause further #VC exceptions */
1430 DEFINE_IDTENTRY_VC_IST(exc_vmm_communication)
1432 instrumentation_begin();
1433 panic("Can't handle #VC exception from unsupported context\n");
1434 instrumentation_end();
1437 DEFINE_IDTENTRY_VC(exc_vmm_communication)
1439 if (likely(!on_vc_fallback_stack(regs)))
1440 safe_stack_exc_vmm_communication(regs, error_code);
1442 ist_exc_vmm_communication(regs, error_code);
1445 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1447 unsigned long exit_code = regs->orig_ax;
1448 struct es_em_ctxt ctxt;
1449 enum es_result result;
1451 /* Do initial setup or terminate the guest */
1452 if (unlikely(boot_ghcb == NULL && !sev_es_setup_ghcb()))
1453 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1455 vc_ghcb_invalidate(boot_ghcb);
1457 result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1458 if (result == ES_OK)
1459 result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1461 /* Done - now check the result */
1464 vc_finish_insn(&ctxt);
1466 case ES_UNSUPPORTED:
1467 early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1468 exit_code, regs->ip);
1471 early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1472 exit_code, regs->ip);
1474 case ES_DECODE_FAILED:
1475 early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1476 exit_code, regs->ip);
1479 vc_early_forward_exception(&ctxt);