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/printk.h>
16 #include <linux/mm_types.h>
17 #include <linux/set_memory.h>
18 #include <linux/memblock.h>
19 #include <linux/kernel.h>
22 #include <asm/cpu_entry_area.h>
23 #include <asm/stacktrace.h>
24 #include <asm/sev-es.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>
34 #define DR7_RESET_VALUE 0x400
36 /* For early boot hypervisor communication in SEV-ES enabled guests */
37 static struct ghcb boot_ghcb_page __bss_decrypted __aligned(PAGE_SIZE);
40 * Needs to be in the .data section because we need it NULL before bss is
43 static struct ghcb __initdata *boot_ghcb;
45 /* #VC handler runtime per-CPU data */
46 struct sev_es_runtime_data {
47 struct ghcb ghcb_page;
50 * Reserve one page per CPU as backup storage for the unencrypted GHCB.
51 * It is needed when an NMI happens while the #VC handler uses the real
52 * GHCB, and the NMI handler itself is causing another #VC exception. In
53 * that case the GHCB content of the first handler needs to be backed up
56 struct ghcb backup_ghcb;
59 * Mark the per-cpu GHCBs as in-use to detect nested #VC exceptions.
60 * There is no need for it to be atomic, because nothing is written to
61 * the GHCB between the read and the write of ghcb_active. So it is safe
62 * to use it when a nested #VC exception happens before the write.
64 * This is necessary for example in the #VC->NMI->#VC case when the NMI
65 * happens while the first #VC handler uses the GHCB. When the NMI code
66 * raises a second #VC handler it might overwrite the contents of the
67 * GHCB written by the first handler. To avoid this the content of the
68 * GHCB is saved and restored when the GHCB is detected to be in use
72 bool backup_ghcb_active;
75 * Cached DR7 value - write it on DR7 writes and return it on reads.
76 * That value will never make it to the real hardware DR7 as debugging
77 * is currently unsupported in SEV-ES guests.
86 static DEFINE_PER_CPU(struct sev_es_runtime_data*, runtime_data);
87 DEFINE_STATIC_KEY_FALSE(sev_es_enable_key);
89 /* Needed in vc_early_forward_exception */
90 void do_early_exception(struct pt_regs *regs, int trapnr);
92 static __always_inline bool on_vc_stack(struct pt_regs *regs)
94 unsigned long sp = regs->sp;
96 /* User-mode RSP is not trusted */
100 /* SYSCALL gap still has user-mode RSP */
101 if (ip_within_syscall_gap(regs))
104 return ((sp >= __this_cpu_ist_bottom_va(VC)) && (sp < __this_cpu_ist_top_va(VC)));
108 * This function handles the case when an NMI is raised in the #VC exception
109 * handler entry code. In this case, the IST entry for #VC must be adjusted, so
110 * that any subsequent #VC exception will not overwrite the stack contents of the
111 * interrupted #VC handler.
113 * The IST entry is adjusted unconditionally so that it can be also be
114 * unconditionally adjusted back in sev_es_ist_exit(). Otherwise a nested
115 * sev_es_ist_exit() call may adjust back the IST entry too early.
117 void noinstr __sev_es_ist_enter(struct pt_regs *regs)
119 unsigned long old_ist, new_ist;
121 /* Read old IST entry */
122 old_ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
124 /* Make room on the IST stack */
125 if (on_vc_stack(regs))
126 new_ist = ALIGN_DOWN(regs->sp, 8) - sizeof(old_ist);
128 new_ist = old_ist - sizeof(old_ist);
130 /* Store old IST entry */
131 *(unsigned long *)new_ist = old_ist;
133 /* Set new IST entry */
134 this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], new_ist);
137 void noinstr __sev_es_ist_exit(void)
142 ist = __this_cpu_read(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC]);
144 if (WARN_ON(ist == __this_cpu_ist_top_va(VC)))
147 /* Read back old IST entry and write it to the TSS */
148 this_cpu_write(cpu_tss_rw.x86_tss.ist[IST_INDEX_VC], *(unsigned long *)ist);
152 * Nothing shall interrupt this code path while holding the per-CPU
153 * GHCB. The backup GHCB is only for NMIs interrupting this path.
155 * Callers must disable local interrupts around it.
157 static noinstr struct ghcb *__sev_get_ghcb(struct ghcb_state *state)
159 struct sev_es_runtime_data *data;
162 WARN_ON(!irqs_disabled());
164 data = this_cpu_read(runtime_data);
165 ghcb = &data->ghcb_page;
167 if (unlikely(data->ghcb_active)) {
168 /* GHCB is already in use - save its contents */
170 if (unlikely(data->backup_ghcb_active)) {
172 * Backup-GHCB is also already in use. There is no way
173 * to continue here so just kill the machine. To make
174 * panic() work, mark GHCBs inactive so that messages
175 * can be printed out.
177 data->ghcb_active = false;
178 data->backup_ghcb_active = false;
180 instrumentation_begin();
181 panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
182 instrumentation_end();
185 /* Mark backup_ghcb active before writing to it */
186 data->backup_ghcb_active = true;
188 state->ghcb = &data->backup_ghcb;
190 /* Backup GHCB content */
191 *state->ghcb = *ghcb;
194 data->ghcb_active = true;
200 /* Needed in vc_early_forward_exception */
201 void do_early_exception(struct pt_regs *regs, int trapnr);
203 static inline u64 sev_es_rd_ghcb_msr(void)
205 return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
208 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
213 high = (u32)(val >> 32);
215 native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
218 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
219 unsigned char *buffer)
221 return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
224 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
226 char buffer[MAX_INSN_SIZE];
230 if (user_mode(ctxt->regs)) {
231 res = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
233 ctxt->fi.vector = X86_TRAP_PF;
234 ctxt->fi.error_code = X86_PF_INSTR | X86_PF_USER;
235 ctxt->fi.cr2 = ctxt->regs->ip;
239 if (!insn_decode_from_regs(&ctxt->insn, ctxt->regs, buffer, res))
240 return ES_DECODE_FAILED;
242 res = vc_fetch_insn_kernel(ctxt, buffer);
244 ctxt->fi.vector = X86_TRAP_PF;
245 ctxt->fi.error_code = X86_PF_INSTR;
246 ctxt->fi.cr2 = ctxt->regs->ip;
250 insn_init(&ctxt->insn, buffer, MAX_INSN_SIZE - res, 1);
251 insn_get_length(&ctxt->insn);
254 ret = ctxt->insn.immediate.got ? ES_OK : ES_DECODE_FAILED;
259 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
260 char *dst, char *buf, size_t size)
262 unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
265 * This function uses __put_user() independent of whether kernel or user
266 * memory is accessed. This works fine because __put_user() does no
267 * sanity checks of the pointer being accessed. All that it does is
268 * to report when the access failed.
270 * Also, this function runs in atomic context, so __put_user() is not
271 * allowed to sleep. The page-fault handler detects that it is running
272 * in atomic context and will not try to take mmap_sem and handle the
273 * fault, so additional pagefault_enable()/disable() calls are not
276 * The access can't be done via copy_to_user() here because
277 * vc_write_mem() must not use string instructions to access unsafe
278 * memory. The reason is that MOVS is emulated by the #VC handler by
279 * splitting the move up into a read and a write and taking a nested #VC
280 * exception on whatever of them is the MMIO access. Using string
281 * instructions here would cause infinite nesting.
286 u8 __user *target = (u8 __user *)dst;
289 if (__put_user(d1, target))
295 u16 __user *target = (u16 __user *)dst;
298 if (__put_user(d2, target))
304 u32 __user *target = (u32 __user *)dst;
307 if (__put_user(d4, target))
313 u64 __user *target = (u64 __user *)dst;
316 if (__put_user(d8, target))
321 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
322 return ES_UNSUPPORTED;
328 if (user_mode(ctxt->regs))
329 error_code |= X86_PF_USER;
331 ctxt->fi.vector = X86_TRAP_PF;
332 ctxt->fi.error_code = error_code;
333 ctxt->fi.cr2 = (unsigned long)dst;
338 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
339 char *src, char *buf, size_t size)
341 unsigned long error_code = X86_PF_PROT;
344 * This function uses __get_user() independent of whether kernel or user
345 * memory is accessed. This works fine because __get_user() does no
346 * sanity checks of the pointer being accessed. All that it does is
347 * to report when the access failed.
349 * Also, this function runs in atomic context, so __get_user() is not
350 * allowed to sleep. The page-fault handler detects that it is running
351 * in atomic context and will not try to take mmap_sem and handle the
352 * fault, so additional pagefault_enable()/disable() calls are not
355 * The access can't be done via copy_from_user() here because
356 * vc_read_mem() must not use string instructions to access unsafe
357 * memory. The reason is that MOVS is emulated by the #VC handler by
358 * splitting the move up into a read and a write and taking a nested #VC
359 * exception on whatever of them is the MMIO access. Using string
360 * instructions here would cause infinite nesting.
365 u8 __user *s = (u8 __user *)src;
367 if (__get_user(d1, s))
374 u16 __user *s = (u16 __user *)src;
376 if (__get_user(d2, s))
383 u32 __user *s = (u32 __user *)src;
385 if (__get_user(d4, s))
392 u64 __user *s = (u64 __user *)src;
393 if (__get_user(d8, s))
399 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
400 return ES_UNSUPPORTED;
406 if (user_mode(ctxt->regs))
407 error_code |= X86_PF_USER;
409 ctxt->fi.vector = X86_TRAP_PF;
410 ctxt->fi.error_code = error_code;
411 ctxt->fi.cr2 = (unsigned long)src;
416 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
417 unsigned long vaddr, phys_addr_t *paddr)
419 unsigned long va = (unsigned long)vaddr;
425 pgd = __va(read_cr3_pa());
426 pgd = &pgd[pgd_index(va)];
427 pte = lookup_address_in_pgd(pgd, va, &level);
429 ctxt->fi.vector = X86_TRAP_PF;
430 ctxt->fi.cr2 = vaddr;
431 ctxt->fi.error_code = 0;
433 if (user_mode(ctxt->regs))
434 ctxt->fi.error_code |= X86_PF_USER;
439 if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
440 /* Emulated MMIO to/from encrypted memory not supported */
441 return ES_UNSUPPORTED;
443 pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
444 pa |= va & ~page_level_mask(level);
451 static enum es_result vc_ioio_check(struct es_em_ctxt *ctxt, u16 port, size_t size)
455 if (user_mode(ctxt->regs)) {
456 struct thread_struct *t = ¤t->thread;
457 struct io_bitmap *iobm = t->io_bitmap;
463 for (idx = port; idx < port + size; ++idx) {
464 if (test_bit(idx, iobm->bitmap))
472 ctxt->fi.vector = X86_TRAP_GP;
473 ctxt->fi.error_code = 0;
478 /* Include code shared with pre-decompression boot stage */
479 #include "sev-es-shared.c"
481 static noinstr void __sev_put_ghcb(struct ghcb_state *state)
483 struct sev_es_runtime_data *data;
486 WARN_ON(!irqs_disabled());
488 data = this_cpu_read(runtime_data);
489 ghcb = &data->ghcb_page;
492 /* Restore GHCB from Backup */
493 *ghcb = *state->ghcb;
494 data->backup_ghcb_active = false;
498 * Invalidate the GHCB so a VMGEXIT instruction issued
499 * from userspace won't appear to be valid.
501 vc_ghcb_invalidate(ghcb);
502 data->ghcb_active = false;
506 void noinstr __sev_es_nmi_complete(void)
508 struct ghcb_state state;
511 ghcb = __sev_get_ghcb(&state);
513 vc_ghcb_invalidate(ghcb);
514 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
515 ghcb_set_sw_exit_info_1(ghcb, 0);
516 ghcb_set_sw_exit_info_2(ghcb, 0);
518 sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
521 __sev_put_ghcb(&state);
524 static u64 get_jump_table_addr(void)
526 struct ghcb_state state;
531 local_irq_save(flags);
533 ghcb = __sev_get_ghcb(&state);
535 vc_ghcb_invalidate(ghcb);
536 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
537 ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
538 ghcb_set_sw_exit_info_2(ghcb, 0);
540 sev_es_wr_ghcb_msr(__pa(ghcb));
543 if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
544 ghcb_sw_exit_info_2_is_valid(ghcb))
545 ret = ghcb->save.sw_exit_info_2;
547 __sev_put_ghcb(&state);
549 local_irq_restore(flags);
554 int sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
556 u16 startup_cs, startup_ip;
557 phys_addr_t jump_table_pa;
559 u16 __iomem *jump_table;
561 jump_table_addr = get_jump_table_addr();
563 /* On UP guests there is no jump table so this is not a failure */
564 if (!jump_table_addr)
567 /* Check if AP Jump Table is page-aligned */
568 if (jump_table_addr & ~PAGE_MASK)
571 jump_table_pa = jump_table_addr & PAGE_MASK;
573 startup_cs = (u16)(rmh->trampoline_start >> 4);
574 startup_ip = (u16)(rmh->sev_es_trampoline_start -
575 rmh->trampoline_start);
577 jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
581 writew(startup_ip, &jump_table[0]);
582 writew(startup_cs, &jump_table[1]);
590 * This is needed by the OVMF UEFI firmware which will use whatever it finds in
591 * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
592 * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
594 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
596 struct sev_es_runtime_data *data;
597 unsigned long address, pflags;
601 if (!sev_es_active())
604 pflags = _PAGE_NX | _PAGE_RW;
606 for_each_possible_cpu(cpu) {
607 data = per_cpu(runtime_data, cpu);
609 address = __pa(&data->ghcb_page);
610 pfn = address >> PAGE_SHIFT;
612 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
619 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
621 struct pt_regs *regs = ctxt->regs;
626 exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
628 ghcb_set_rcx(ghcb, regs->cx);
630 ghcb_set_rax(ghcb, regs->ax);
631 ghcb_set_rdx(ghcb, regs->dx);
634 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
636 if ((ret == ES_OK) && (!exit_info_1)) {
637 regs->ax = ghcb->save.rax;
638 regs->dx = ghcb->save.rdx;
645 * This function runs on the first #VC exception after the kernel
646 * switched to virtual addresses.
648 static bool __init sev_es_setup_ghcb(void)
650 /* First make sure the hypervisor talks a supported protocol. */
651 if (!sev_es_negotiate_protocol())
655 * Clear the boot_ghcb. The first exception comes in before the bss
656 * section is cleared.
658 memset(&boot_ghcb_page, 0, PAGE_SIZE);
660 /* Alright - Make the boot-ghcb public */
661 boot_ghcb = &boot_ghcb_page;
666 #ifdef CONFIG_HOTPLUG_CPU
667 static void sev_es_ap_hlt_loop(void)
669 struct ghcb_state state;
672 ghcb = __sev_get_ghcb(&state);
675 vc_ghcb_invalidate(ghcb);
676 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
677 ghcb_set_sw_exit_info_1(ghcb, 0);
678 ghcb_set_sw_exit_info_2(ghcb, 0);
680 sev_es_wr_ghcb_msr(__pa(ghcb));
684 if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
685 ghcb->save.sw_exit_info_2)
689 __sev_put_ghcb(&state);
693 * Play_dead handler when running under SEV-ES. This is needed because
694 * the hypervisor can't deliver an SIPI request to restart the AP.
695 * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
696 * hypervisor wakes it up again.
698 static void sev_es_play_dead(void)
702 /* IRQs now disabled */
704 sev_es_ap_hlt_loop();
707 * If we get here, the VCPU was woken up again. Jump to CPU
708 * startup code to get it back online.
712 #else /* CONFIG_HOTPLUG_CPU */
713 #define sev_es_play_dead native_play_dead
714 #endif /* CONFIG_HOTPLUG_CPU */
717 static void __init sev_es_setup_play_dead(void)
719 smp_ops.play_dead = sev_es_play_dead;
722 static inline void sev_es_setup_play_dead(void) { }
725 static void __init alloc_runtime_data(int cpu)
727 struct sev_es_runtime_data *data;
729 data = memblock_alloc(sizeof(*data), PAGE_SIZE);
731 panic("Can't allocate SEV-ES runtime data");
733 per_cpu(runtime_data, cpu) = data;
736 static void __init init_ghcb(int cpu)
738 struct sev_es_runtime_data *data;
741 data = per_cpu(runtime_data, cpu);
743 err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
744 sizeof(data->ghcb_page));
746 panic("Can't map GHCBs unencrypted");
748 memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
750 data->ghcb_active = false;
751 data->backup_ghcb_active = false;
754 void __init sev_es_init_vc_handling(void)
758 BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
760 if (!sev_es_active())
763 if (!sev_es_check_cpu_features())
764 panic("SEV-ES CPU Features missing");
766 /* Enable SEV-ES special handling */
767 static_branch_enable(&sev_es_enable_key);
769 /* Initialize per-cpu GHCB pages */
770 for_each_possible_cpu(cpu) {
771 alloc_runtime_data(cpu);
775 sev_es_setup_play_dead();
777 /* Secondary CPUs use the runtime #VC handler */
778 initial_vc_handler = (unsigned long)kernel_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 if (user_mode(ctxt->regs))
1001 return ES_UNSUPPORTED;
1003 switch (insn->opcode.bytes[0]) {
1010 bytes = insn->opnd_bytes;
1012 reg_data = vc_insn_get_reg(ctxt);
1014 return ES_DECODE_FAILED;
1016 memcpy(ghcb->shared_buffer, reg_data, bytes);
1018 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1026 bytes = insn->opnd_bytes;
1028 memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
1030 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
1039 bytes = insn->opnd_bytes;
1041 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
1045 reg_data = vc_insn_get_reg(ctxt);
1047 return ES_DECODE_FAILED;
1049 /* Zero-extend for 32-bit operation */
1053 memcpy(reg_data, ghcb->shared_buffer, bytes);
1056 /* MOVS instruction */
1062 bytes = insn->opnd_bytes;
1064 ret = vc_handle_mmio_movs(ctxt, bytes);
1066 /* Two-Byte Opcodes */
1068 ret = vc_handle_mmio_twobyte_ops(ghcb, ctxt);
1071 ret = ES_UNSUPPORTED;
1077 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1078 struct es_em_ctxt *ctxt)
1080 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1081 long val, *reg = vc_insn_get_rm(ctxt);
1085 return ES_DECODE_FAILED;
1089 /* Upper 32 bits must be written as zeroes */
1091 ctxt->fi.vector = X86_TRAP_GP;
1092 ctxt->fi.error_code = 0;
1093 return ES_EXCEPTION;
1096 /* Clear out other reserved bits and set bit 10 */
1097 val = (val & 0xffff23ffL) | BIT(10);
1099 /* Early non-zero writes to DR7 are not supported */
1100 if (!data && (val & ~DR7_RESET_VALUE))
1101 return ES_UNSUPPORTED;
1103 /* Using a value of 0 for ExitInfo1 means RAX holds the value */
1104 ghcb_set_rax(ghcb, val);
1105 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1115 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1116 struct es_em_ctxt *ctxt)
1118 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1119 long *reg = vc_insn_get_rm(ctxt);
1122 return ES_DECODE_FAILED;
1127 *reg = DR7_RESET_VALUE;
1132 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1133 struct es_em_ctxt *ctxt)
1135 return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1138 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1142 ghcb_set_rcx(ghcb, ctxt->regs->cx);
1144 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1148 if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1149 return ES_VMM_ERROR;
1151 ctxt->regs->ax = ghcb->save.rax;
1152 ctxt->regs->dx = ghcb->save.rdx;
1157 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1158 struct es_em_ctxt *ctxt)
1161 * Treat it as a NOP and do not leak a physical address to the
1167 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1168 struct es_em_ctxt *ctxt)
1170 /* Treat the same as MONITOR/MONITORX */
1174 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1175 struct es_em_ctxt *ctxt)
1179 ghcb_set_rax(ghcb, ctxt->regs->ax);
1180 ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1182 if (x86_platform.hyper.sev_es_hcall_prepare)
1183 x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1185 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1189 if (!ghcb_rax_is_valid(ghcb))
1190 return ES_VMM_ERROR;
1192 ctxt->regs->ax = ghcb->save.rax;
1195 * Call sev_es_hcall_finish() after regs->ax is already set.
1196 * This allows the hypervisor handler to overwrite it again if
1199 if (x86_platform.hyper.sev_es_hcall_finish &&
1200 !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1201 return ES_VMM_ERROR;
1206 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1207 struct es_em_ctxt *ctxt)
1210 * Calling ecx_alignment_check() directly does not work, because it
1211 * enables IRQs and the GHCB is active. Forward the exception and call
1212 * it later from vc_forward_exception().
1214 ctxt->fi.vector = X86_TRAP_AC;
1215 ctxt->fi.error_code = 0;
1216 return ES_EXCEPTION;
1219 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1221 unsigned long exit_code)
1223 enum es_result result;
1225 switch (exit_code) {
1226 case SVM_EXIT_READ_DR7:
1227 result = vc_handle_dr7_read(ghcb, ctxt);
1229 case SVM_EXIT_WRITE_DR7:
1230 result = vc_handle_dr7_write(ghcb, ctxt);
1232 case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1233 result = vc_handle_trap_ac(ghcb, ctxt);
1235 case SVM_EXIT_RDTSC:
1236 case SVM_EXIT_RDTSCP:
1237 result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1239 case SVM_EXIT_RDPMC:
1240 result = vc_handle_rdpmc(ghcb, ctxt);
1243 pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1244 result = ES_UNSUPPORTED;
1246 case SVM_EXIT_CPUID:
1247 result = vc_handle_cpuid(ghcb, ctxt);
1250 result = vc_handle_ioio(ghcb, ctxt);
1253 result = vc_handle_msr(ghcb, ctxt);
1255 case SVM_EXIT_VMMCALL:
1256 result = vc_handle_vmmcall(ghcb, ctxt);
1258 case SVM_EXIT_WBINVD:
1259 result = vc_handle_wbinvd(ghcb, ctxt);
1261 case SVM_EXIT_MONITOR:
1262 result = vc_handle_monitor(ghcb, ctxt);
1264 case SVM_EXIT_MWAIT:
1265 result = vc_handle_mwait(ghcb, ctxt);
1268 result = vc_handle_mmio(ghcb, ctxt);
1272 * Unexpected #VC exception
1274 result = ES_UNSUPPORTED;
1280 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1282 long error_code = ctxt->fi.error_code;
1283 int trapnr = ctxt->fi.vector;
1285 ctxt->regs->orig_ax = ctxt->fi.error_code;
1289 exc_general_protection(ctxt->regs, error_code);
1292 exc_invalid_op(ctxt->regs);
1295 write_cr2(ctxt->fi.cr2);
1296 exc_page_fault(ctxt->regs, error_code);
1299 exc_alignment_check(ctxt->regs, error_code);
1302 pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1307 static __always_inline bool on_vc_fallback_stack(struct pt_regs *regs)
1309 unsigned long sp = (unsigned long)regs;
1311 return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1314 static bool vc_raw_handle_exception(struct pt_regs *regs, unsigned long error_code)
1316 struct ghcb_state state;
1317 struct es_em_ctxt ctxt;
1318 enum es_result result;
1322 ghcb = __sev_get_ghcb(&state);
1324 vc_ghcb_invalidate(ghcb);
1325 result = vc_init_em_ctxt(&ctxt, regs, error_code);
1327 if (result == ES_OK)
1328 result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1330 __sev_put_ghcb(&state);
1332 /* Done - now check the result */
1335 vc_finish_insn(&ctxt);
1337 case ES_UNSUPPORTED:
1338 pr_err_ratelimited("Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1339 error_code, regs->ip);
1343 pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1344 error_code, regs->ip);
1347 case ES_DECODE_FAILED:
1348 pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1349 error_code, regs->ip);
1353 vc_forward_exception(&ctxt);
1359 pr_emerg("Unknown result in %s():%d\n", __func__, result);
1361 * Emulating the instruction which caused the #VC exception
1362 * failed - can't continue so print debug information
1370 static __always_inline bool vc_is_db(unsigned long error_code)
1372 return error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB;
1376 * Runtime #VC exception handler when raised from kernel mode. Runs in NMI mode
1377 * and will panic when an error happens.
1379 DEFINE_IDTENTRY_VC_KERNEL(exc_vmm_communication)
1381 irqentry_state_t irq_state;
1384 * With the current implementation it is always possible to switch to a
1385 * safe stack because #VC exceptions only happen at known places, like
1386 * intercepted instructions or accesses to MMIO areas/IO ports. They can
1387 * also happen with code instrumentation when the hypervisor intercepts
1388 * #DB, but the critical paths are forbidden to be instrumented, so #DB
1389 * exceptions currently also only happen in safe places.
1391 * But keep this here in case the noinstr annotations are violated due
1394 if (unlikely(on_vc_fallback_stack(regs))) {
1395 instrumentation_begin();
1396 panic("Can't handle #VC exception from unsupported context\n");
1397 instrumentation_end();
1401 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1403 if (vc_is_db(error_code)) {
1408 irq_state = irqentry_nmi_enter(regs);
1410 instrumentation_begin();
1412 if (!vc_raw_handle_exception(regs, error_code)) {
1413 /* Show some debug info */
1416 /* Ask hypervisor to sev_es_terminate */
1417 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1419 /* If that fails and we get here - just panic */
1420 panic("Returned from Terminate-Request to Hypervisor\n");
1423 instrumentation_end();
1424 irqentry_nmi_exit(regs, irq_state);
1428 * Runtime #VC exception handler when raised from user mode. Runs in IRQ mode
1429 * and will kill the current task with SIGBUS when an error happens.
1431 DEFINE_IDTENTRY_VC_USER(exc_vmm_communication)
1434 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1436 if (vc_is_db(error_code)) {
1437 noist_exc_debug(regs);
1441 irqentry_enter_from_user_mode(regs);
1442 instrumentation_begin();
1444 if (!vc_raw_handle_exception(regs, error_code)) {
1446 * Do not kill the machine if user-space triggered the
1447 * exception. Send SIGBUS instead and let user-space deal with
1450 force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1453 instrumentation_end();
1454 irqentry_exit_to_user_mode(regs);
1457 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1459 unsigned long exit_code = regs->orig_ax;
1460 struct es_em_ctxt ctxt;
1461 enum es_result result;
1463 /* Do initial setup or terminate the guest */
1464 if (unlikely(boot_ghcb == NULL && !sev_es_setup_ghcb()))
1465 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1467 vc_ghcb_invalidate(boot_ghcb);
1469 result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1470 if (result == ES_OK)
1471 result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1473 /* Done - now check the result */
1476 vc_finish_insn(&ctxt);
1478 case ES_UNSUPPORTED:
1479 early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1480 exit_code, regs->ip);
1483 early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1484 exit_code, regs->ip);
1486 case ES_DECODE_FAILED:
1487 early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1488 exit_code, regs->ip);
1491 vc_early_forward_exception(&ctxt);