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>
25 #include <asm/sev-es.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))
209 /* Mark backup_ghcb active before writing to it */
210 data->backup_ghcb_active = true;
212 state->ghcb = &data->backup_ghcb;
214 /* Backup GHCB content */
215 *state->ghcb = *ghcb;
218 data->ghcb_active = true;
224 static __always_inline void sev_es_put_ghcb(struct ghcb_state *state)
226 struct sev_es_runtime_data *data;
229 data = this_cpu_read(runtime_data);
230 ghcb = &data->ghcb_page;
233 /* Restore GHCB from Backup */
234 *ghcb = *state->ghcb;
235 data->backup_ghcb_active = false;
238 data->ghcb_active = false;
242 /* Needed in vc_early_forward_exception */
243 void do_early_exception(struct pt_regs *regs, int trapnr);
245 static inline u64 sev_es_rd_ghcb_msr(void)
247 return __rdmsr(MSR_AMD64_SEV_ES_GHCB);
250 static __always_inline void sev_es_wr_ghcb_msr(u64 val)
255 high = (u32)(val >> 32);
257 native_wrmsr(MSR_AMD64_SEV_ES_GHCB, low, high);
260 static int vc_fetch_insn_kernel(struct es_em_ctxt *ctxt,
261 unsigned char *buffer)
263 return copy_from_kernel_nofault(buffer, (unsigned char *)ctxt->regs->ip, MAX_INSN_SIZE);
266 static enum es_result vc_decode_insn(struct es_em_ctxt *ctxt)
268 char buffer[MAX_INSN_SIZE];
272 if (user_mode(ctxt->regs)) {
273 res = insn_fetch_from_user_inatomic(ctxt->regs, buffer);
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;
281 if (!insn_decode(&ctxt->insn, ctxt->regs, buffer, res))
282 return ES_DECODE_FAILED;
284 res = vc_fetch_insn_kernel(ctxt, buffer);
286 ctxt->fi.vector = X86_TRAP_PF;
287 ctxt->fi.error_code = X86_PF_INSTR;
288 ctxt->fi.cr2 = ctxt->regs->ip;
292 insn_init(&ctxt->insn, buffer, MAX_INSN_SIZE, 1);
293 insn_get_length(&ctxt->insn);
296 ret = ctxt->insn.immediate.got ? ES_OK : ES_DECODE_FAILED;
301 static enum es_result vc_write_mem(struct es_em_ctxt *ctxt,
302 char *dst, char *buf, size_t size)
304 unsigned long error_code = X86_PF_PROT | X86_PF_WRITE;
305 char __user *target = (char __user *)dst;
311 /* If instruction ran in kernel mode and the I/O buffer is in kernel space */
312 if (!user_mode(ctxt->regs) && !access_ok(target, size)) {
313 memcpy(dst, buf, size);
320 if (put_user(d1, target))
325 if (put_user(d2, target))
330 if (put_user(d4, target))
335 if (put_user(d8, target))
339 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
340 return ES_UNSUPPORTED;
346 if (user_mode(ctxt->regs))
347 error_code |= X86_PF_USER;
349 ctxt->fi.vector = X86_TRAP_PF;
350 ctxt->fi.error_code = error_code;
351 ctxt->fi.cr2 = (unsigned long)dst;
356 static enum es_result vc_read_mem(struct es_em_ctxt *ctxt,
357 char *src, char *buf, size_t size)
359 unsigned long error_code = X86_PF_PROT;
360 char __user *s = (char __user *)src;
366 /* If instruction ran in kernel mode and the I/O buffer is in kernel space */
367 if (!user_mode(ctxt->regs) && !access_ok(s, size)) {
368 memcpy(buf, src, size);
394 WARN_ONCE(1, "%s: Invalid size: %zu\n", __func__, size);
395 return ES_UNSUPPORTED;
401 if (user_mode(ctxt->regs))
402 error_code |= X86_PF_USER;
404 ctxt->fi.vector = X86_TRAP_PF;
405 ctxt->fi.error_code = error_code;
406 ctxt->fi.cr2 = (unsigned long)src;
411 static enum es_result vc_slow_virt_to_phys(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
412 unsigned long vaddr, phys_addr_t *paddr)
414 unsigned long va = (unsigned long)vaddr;
420 pgd = __va(read_cr3_pa());
421 pgd = &pgd[pgd_index(va)];
422 pte = lookup_address_in_pgd(pgd, va, &level);
424 ctxt->fi.vector = X86_TRAP_PF;
425 ctxt->fi.cr2 = vaddr;
426 ctxt->fi.error_code = 0;
428 if (user_mode(ctxt->regs))
429 ctxt->fi.error_code |= X86_PF_USER;
434 if (WARN_ON_ONCE(pte_val(*pte) & _PAGE_ENC))
435 /* Emulated MMIO to/from encrypted memory not supported */
436 return ES_UNSUPPORTED;
438 pa = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
439 pa |= va & ~page_level_mask(level);
446 /* Include code shared with pre-decompression boot stage */
447 #include "sev-es-shared.c"
449 void noinstr __sev_es_nmi_complete(void)
451 struct ghcb_state state;
454 ghcb = sev_es_get_ghcb(&state);
456 vc_ghcb_invalidate(ghcb);
457 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_NMI_COMPLETE);
458 ghcb_set_sw_exit_info_1(ghcb, 0);
459 ghcb_set_sw_exit_info_2(ghcb, 0);
461 sev_es_wr_ghcb_msr(__pa_nodebug(ghcb));
464 sev_es_put_ghcb(&state);
467 static u64 get_jump_table_addr(void)
469 struct ghcb_state state;
474 local_irq_save(flags);
476 ghcb = sev_es_get_ghcb(&state);
478 vc_ghcb_invalidate(ghcb);
479 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_JUMP_TABLE);
480 ghcb_set_sw_exit_info_1(ghcb, SVM_VMGEXIT_GET_AP_JUMP_TABLE);
481 ghcb_set_sw_exit_info_2(ghcb, 0);
483 sev_es_wr_ghcb_msr(__pa(ghcb));
486 if (ghcb_sw_exit_info_1_is_valid(ghcb) &&
487 ghcb_sw_exit_info_2_is_valid(ghcb))
488 ret = ghcb->save.sw_exit_info_2;
490 sev_es_put_ghcb(&state);
492 local_irq_restore(flags);
497 int sev_es_setup_ap_jump_table(struct real_mode_header *rmh)
499 u16 startup_cs, startup_ip;
500 phys_addr_t jump_table_pa;
502 u16 __iomem *jump_table;
504 jump_table_addr = get_jump_table_addr();
506 /* On UP guests there is no jump table so this is not a failure */
507 if (!jump_table_addr)
510 /* Check if AP Jump Table is page-aligned */
511 if (jump_table_addr & ~PAGE_MASK)
514 jump_table_pa = jump_table_addr & PAGE_MASK;
516 startup_cs = (u16)(rmh->trampoline_start >> 4);
517 startup_ip = (u16)(rmh->sev_es_trampoline_start -
518 rmh->trampoline_start);
520 jump_table = ioremap_encrypted(jump_table_pa, PAGE_SIZE);
524 writew(startup_ip, &jump_table[0]);
525 writew(startup_cs, &jump_table[1]);
533 * This is needed by the OVMF UEFI firmware which will use whatever it finds in
534 * the GHCB MSR as its GHCB to talk to the hypervisor. So make sure the per-cpu
535 * runtime GHCBs used by the kernel are also mapped in the EFI page-table.
537 int __init sev_es_efi_map_ghcbs(pgd_t *pgd)
539 struct sev_es_runtime_data *data;
540 unsigned long address, pflags;
544 if (!sev_es_active())
547 pflags = _PAGE_NX | _PAGE_RW;
549 for_each_possible_cpu(cpu) {
550 data = per_cpu(runtime_data, cpu);
552 address = __pa(&data->ghcb_page);
553 pfn = address >> PAGE_SHIFT;
555 if (kernel_map_pages_in_pgd(pgd, pfn, address, 1, pflags))
562 static enum es_result vc_handle_msr(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
564 struct pt_regs *regs = ctxt->regs;
569 exit_info_1 = (ctxt->insn.opcode.bytes[1] == 0x30) ? 1 : 0;
571 ghcb_set_rcx(ghcb, regs->cx);
573 ghcb_set_rax(ghcb, regs->ax);
574 ghcb_set_rdx(ghcb, regs->dx);
577 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_MSR, exit_info_1, 0);
579 if ((ret == ES_OK) && (!exit_info_1)) {
580 regs->ax = ghcb->save.rax;
581 regs->dx = ghcb->save.rdx;
588 * This function runs on the first #VC exception after the kernel
589 * switched to virtual addresses.
591 static bool __init sev_es_setup_ghcb(void)
593 /* First make sure the hypervisor talks a supported protocol. */
594 if (!sev_es_negotiate_protocol())
598 * Clear the boot_ghcb. The first exception comes in before the bss
599 * section is cleared.
601 memset(&boot_ghcb_page, 0, PAGE_SIZE);
603 /* Alright - Make the boot-ghcb public */
604 boot_ghcb = &boot_ghcb_page;
609 #ifdef CONFIG_HOTPLUG_CPU
610 static void sev_es_ap_hlt_loop(void)
612 struct ghcb_state state;
615 ghcb = sev_es_get_ghcb(&state);
618 vc_ghcb_invalidate(ghcb);
619 ghcb_set_sw_exit_code(ghcb, SVM_VMGEXIT_AP_HLT_LOOP);
620 ghcb_set_sw_exit_info_1(ghcb, 0);
621 ghcb_set_sw_exit_info_2(ghcb, 0);
623 sev_es_wr_ghcb_msr(__pa(ghcb));
627 if (ghcb_sw_exit_info_2_is_valid(ghcb) &&
628 ghcb->save.sw_exit_info_2)
632 sev_es_put_ghcb(&state);
636 * Play_dead handler when running under SEV-ES. This is needed because
637 * the hypervisor can't deliver an SIPI request to restart the AP.
638 * Instead the kernel has to issue a VMGEXIT to halt the VCPU until the
639 * hypervisor wakes it up again.
641 static void sev_es_play_dead(void)
645 /* IRQs now disabled */
647 sev_es_ap_hlt_loop();
650 * If we get here, the VCPU was woken up again. Jump to CPU
651 * startup code to get it back online.
655 #else /* CONFIG_HOTPLUG_CPU */
656 #define sev_es_play_dead native_play_dead
657 #endif /* CONFIG_HOTPLUG_CPU */
660 static void __init sev_es_setup_play_dead(void)
662 smp_ops.play_dead = sev_es_play_dead;
665 static inline void sev_es_setup_play_dead(void) { }
668 static void __init alloc_runtime_data(int cpu)
670 struct sev_es_runtime_data *data;
672 data = memblock_alloc(sizeof(*data), PAGE_SIZE);
674 panic("Can't allocate SEV-ES runtime data");
676 per_cpu(runtime_data, cpu) = data;
679 static void __init init_ghcb(int cpu)
681 struct sev_es_runtime_data *data;
684 data = per_cpu(runtime_data, cpu);
686 err = early_set_memory_decrypted((unsigned long)&data->ghcb_page,
687 sizeof(data->ghcb_page));
689 panic("Can't map GHCBs unencrypted");
691 memset(&data->ghcb_page, 0, sizeof(data->ghcb_page));
693 data->ghcb_active = false;
694 data->backup_ghcb_active = false;
697 void __init sev_es_init_vc_handling(void)
701 BUILD_BUG_ON(offsetof(struct sev_es_runtime_data, ghcb_page) % PAGE_SIZE);
703 if (!sev_es_active())
706 if (!sev_es_check_cpu_features())
707 panic("SEV-ES CPU Features missing");
709 /* Enable SEV-ES special handling */
710 static_branch_enable(&sev_es_enable_key);
712 /* Initialize per-cpu GHCB pages */
713 for_each_possible_cpu(cpu) {
714 alloc_runtime_data(cpu);
716 setup_vc_stacks(cpu);
719 sev_es_setup_play_dead();
721 /* Secondary CPUs use the runtime #VC handler */
722 initial_vc_handler = (unsigned long)safe_stack_exc_vmm_communication;
725 static void __init vc_early_forward_exception(struct es_em_ctxt *ctxt)
727 int trapnr = ctxt->fi.vector;
729 if (trapnr == X86_TRAP_PF)
730 native_write_cr2(ctxt->fi.cr2);
732 ctxt->regs->orig_ax = ctxt->fi.error_code;
733 do_early_exception(ctxt->regs, trapnr);
736 static long *vc_insn_get_reg(struct es_em_ctxt *ctxt)
741 reg_array = (long *)ctxt->regs;
742 offset = insn_get_modrm_reg_off(&ctxt->insn, ctxt->regs);
747 offset /= sizeof(long);
749 return reg_array + offset;
752 static long *vc_insn_get_rm(struct es_em_ctxt *ctxt)
757 reg_array = (long *)ctxt->regs;
758 offset = insn_get_modrm_rm_off(&ctxt->insn, ctxt->regs);
763 offset /= sizeof(long);
765 return reg_array + offset;
767 static enum es_result vc_do_mmio(struct ghcb *ghcb, struct es_em_ctxt *ctxt,
768 unsigned int bytes, bool read)
770 u64 exit_code, exit_info_1, exit_info_2;
771 unsigned long ghcb_pa = __pa(ghcb);
776 ref = insn_get_addr_ref(&ctxt->insn, ctxt->regs);
777 if (ref == (void __user *)-1L)
778 return ES_UNSUPPORTED;
780 exit_code = read ? SVM_VMGEXIT_MMIO_READ : SVM_VMGEXIT_MMIO_WRITE;
782 res = vc_slow_virt_to_phys(ghcb, ctxt, (unsigned long)ref, &paddr);
784 if (res == ES_EXCEPTION && !read)
785 ctxt->fi.error_code |= X86_PF_WRITE;
791 /* Can never be greater than 8 */
794 ghcb_set_sw_scratch(ghcb, ghcb_pa + offsetof(struct ghcb, shared_buffer));
796 return sev_es_ghcb_hv_call(ghcb, ctxt, exit_code, exit_info_1, exit_info_2);
799 static enum es_result vc_handle_mmio_twobyte_ops(struct ghcb *ghcb,
800 struct es_em_ctxt *ctxt)
802 struct insn *insn = &ctxt->insn;
803 unsigned int bytes = 0;
808 switch (insn->opcode.bytes[1]) {
809 /* MMIO Read w/ zero-extension */
817 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
821 /* Zero extend based on operand size */
822 reg_data = vc_insn_get_reg(ctxt);
824 return ES_DECODE_FAILED;
826 memset(reg_data, 0, insn->opnd_bytes);
828 memcpy(reg_data, ghcb->shared_buffer, bytes);
831 /* MMIO Read w/ sign-extension */
839 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
843 /* Sign extend based on operand size */
844 reg_data = vc_insn_get_reg(ctxt);
846 return ES_DECODE_FAILED;
849 u8 *val = (u8 *)ghcb->shared_buffer;
851 sign_byte = (*val & 0x80) ? 0xff : 0x00;
853 u16 *val = (u16 *)ghcb->shared_buffer;
855 sign_byte = (*val & 0x8000) ? 0xff : 0x00;
857 memset(reg_data, sign_byte, insn->opnd_bytes);
859 memcpy(reg_data, ghcb->shared_buffer, bytes);
863 ret = ES_UNSUPPORTED;
870 * The MOVS instruction has two memory operands, which raises the
871 * problem that it is not known whether the access to the source or the
872 * destination caused the #VC exception (and hence whether an MMIO read
873 * or write operation needs to be emulated).
875 * Instead of playing games with walking page-tables and trying to guess
876 * whether the source or destination is an MMIO range, split the move
877 * into two operations, a read and a write with only one memory operand.
878 * This will cause a nested #VC exception on the MMIO address which can
881 * This implementation has the benefit that it also supports MOVS where
882 * source _and_ destination are MMIO regions.
884 * It will slow MOVS on MMIO down a lot, but in SEV-ES guests it is a
885 * rare operation. If it turns out to be a performance problem the split
886 * operations can be moved to memcpy_fromio() and memcpy_toio().
888 static enum es_result vc_handle_mmio_movs(struct es_em_ctxt *ctxt,
891 unsigned long ds_base, es_base;
892 unsigned char *src, *dst;
893 unsigned char buffer[8];
898 ds_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_DS);
899 es_base = insn_get_seg_base(ctxt->regs, INAT_SEG_REG_ES);
901 if (ds_base == -1L || es_base == -1L) {
902 ctxt->fi.vector = X86_TRAP_GP;
903 ctxt->fi.error_code = 0;
907 src = ds_base + (unsigned char *)ctxt->regs->si;
908 dst = es_base + (unsigned char *)ctxt->regs->di;
910 ret = vc_read_mem(ctxt, src, buffer, bytes);
914 ret = vc_write_mem(ctxt, dst, buffer, bytes);
918 if (ctxt->regs->flags & X86_EFLAGS_DF)
923 ctxt->regs->si += off;
924 ctxt->regs->di += off;
926 rep = insn_has_rep_prefix(&ctxt->insn);
930 if (!rep || ctxt->regs->cx == 0)
936 static enum es_result vc_handle_mmio(struct ghcb *ghcb,
937 struct es_em_ctxt *ctxt)
939 struct insn *insn = &ctxt->insn;
940 unsigned int bytes = 0;
944 switch (insn->opcode.bytes[0]) {
951 bytes = insn->opnd_bytes;
953 reg_data = vc_insn_get_reg(ctxt);
955 return ES_DECODE_FAILED;
957 memcpy(ghcb->shared_buffer, reg_data, bytes);
959 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
967 bytes = insn->opnd_bytes;
969 memcpy(ghcb->shared_buffer, insn->immediate1.bytes, bytes);
971 ret = vc_do_mmio(ghcb, ctxt, bytes, false);
980 bytes = insn->opnd_bytes;
982 ret = vc_do_mmio(ghcb, ctxt, bytes, true);
986 reg_data = vc_insn_get_reg(ctxt);
988 return ES_DECODE_FAILED;
990 /* Zero-extend for 32-bit operation */
994 memcpy(reg_data, ghcb->shared_buffer, bytes);
997 /* MOVS instruction */
1003 bytes = insn->opnd_bytes;
1005 ret = vc_handle_mmio_movs(ctxt, bytes);
1007 /* Two-Byte Opcodes */
1009 ret = vc_handle_mmio_twobyte_ops(ghcb, ctxt);
1012 ret = ES_UNSUPPORTED;
1018 static enum es_result vc_handle_dr7_write(struct ghcb *ghcb,
1019 struct es_em_ctxt *ctxt)
1021 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1022 long val, *reg = vc_insn_get_rm(ctxt);
1026 return ES_DECODE_FAILED;
1030 /* Upper 32 bits must be written as zeroes */
1032 ctxt->fi.vector = X86_TRAP_GP;
1033 ctxt->fi.error_code = 0;
1034 return ES_EXCEPTION;
1037 /* Clear out other reserved bits and set bit 10 */
1038 val = (val & 0xffff23ffL) | BIT(10);
1040 /* Early non-zero writes to DR7 are not supported */
1041 if (!data && (val & ~DR7_RESET_VALUE))
1042 return ES_UNSUPPORTED;
1044 /* Using a value of 0 for ExitInfo1 means RAX holds the value */
1045 ghcb_set_rax(ghcb, val);
1046 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WRITE_DR7, 0, 0);
1056 static enum es_result vc_handle_dr7_read(struct ghcb *ghcb,
1057 struct es_em_ctxt *ctxt)
1059 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1060 long *reg = vc_insn_get_rm(ctxt);
1063 return ES_DECODE_FAILED;
1068 *reg = DR7_RESET_VALUE;
1073 static enum es_result vc_handle_wbinvd(struct ghcb *ghcb,
1074 struct es_em_ctxt *ctxt)
1076 return sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_WBINVD, 0, 0);
1079 static enum es_result vc_handle_rdpmc(struct ghcb *ghcb, struct es_em_ctxt *ctxt)
1083 ghcb_set_rcx(ghcb, ctxt->regs->cx);
1085 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_RDPMC, 0, 0);
1089 if (!(ghcb_rax_is_valid(ghcb) && ghcb_rdx_is_valid(ghcb)))
1090 return ES_VMM_ERROR;
1092 ctxt->regs->ax = ghcb->save.rax;
1093 ctxt->regs->dx = ghcb->save.rdx;
1098 static enum es_result vc_handle_monitor(struct ghcb *ghcb,
1099 struct es_em_ctxt *ctxt)
1102 * Treat it as a NOP and do not leak a physical address to the
1108 static enum es_result vc_handle_mwait(struct ghcb *ghcb,
1109 struct es_em_ctxt *ctxt)
1111 /* Treat the same as MONITOR/MONITORX */
1115 static enum es_result vc_handle_vmmcall(struct ghcb *ghcb,
1116 struct es_em_ctxt *ctxt)
1120 ghcb_set_rax(ghcb, ctxt->regs->ax);
1121 ghcb_set_cpl(ghcb, user_mode(ctxt->regs) ? 3 : 0);
1123 if (x86_platform.hyper.sev_es_hcall_prepare)
1124 x86_platform.hyper.sev_es_hcall_prepare(ghcb, ctxt->regs);
1126 ret = sev_es_ghcb_hv_call(ghcb, ctxt, SVM_EXIT_VMMCALL, 0, 0);
1130 if (!ghcb_rax_is_valid(ghcb))
1131 return ES_VMM_ERROR;
1133 ctxt->regs->ax = ghcb->save.rax;
1136 * Call sev_es_hcall_finish() after regs->ax is already set.
1137 * This allows the hypervisor handler to overwrite it again if
1140 if (x86_platform.hyper.sev_es_hcall_finish &&
1141 !x86_platform.hyper.sev_es_hcall_finish(ghcb, ctxt->regs))
1142 return ES_VMM_ERROR;
1147 static enum es_result vc_handle_trap_ac(struct ghcb *ghcb,
1148 struct es_em_ctxt *ctxt)
1151 * Calling ecx_alignment_check() directly does not work, because it
1152 * enables IRQs and the GHCB is active. Forward the exception and call
1153 * it later from vc_forward_exception().
1155 ctxt->fi.vector = X86_TRAP_AC;
1156 ctxt->fi.error_code = 0;
1157 return ES_EXCEPTION;
1160 static __always_inline void vc_handle_trap_db(struct pt_regs *regs)
1162 if (user_mode(regs))
1163 noist_exc_debug(regs);
1168 static enum es_result vc_handle_exitcode(struct es_em_ctxt *ctxt,
1170 unsigned long exit_code)
1172 enum es_result result;
1174 switch (exit_code) {
1175 case SVM_EXIT_READ_DR7:
1176 result = vc_handle_dr7_read(ghcb, ctxt);
1178 case SVM_EXIT_WRITE_DR7:
1179 result = vc_handle_dr7_write(ghcb, ctxt);
1181 case SVM_EXIT_EXCP_BASE + X86_TRAP_AC:
1182 result = vc_handle_trap_ac(ghcb, ctxt);
1184 case SVM_EXIT_RDTSC:
1185 case SVM_EXIT_RDTSCP:
1186 result = vc_handle_rdtsc(ghcb, ctxt, exit_code);
1188 case SVM_EXIT_RDPMC:
1189 result = vc_handle_rdpmc(ghcb, ctxt);
1192 pr_err_ratelimited("#VC exception for INVD??? Seriously???\n");
1193 result = ES_UNSUPPORTED;
1195 case SVM_EXIT_CPUID:
1196 result = vc_handle_cpuid(ghcb, ctxt);
1199 result = vc_handle_ioio(ghcb, ctxt);
1202 result = vc_handle_msr(ghcb, ctxt);
1204 case SVM_EXIT_VMMCALL:
1205 result = vc_handle_vmmcall(ghcb, ctxt);
1207 case SVM_EXIT_WBINVD:
1208 result = vc_handle_wbinvd(ghcb, ctxt);
1210 case SVM_EXIT_MONITOR:
1211 result = vc_handle_monitor(ghcb, ctxt);
1213 case SVM_EXIT_MWAIT:
1214 result = vc_handle_mwait(ghcb, ctxt);
1217 result = vc_handle_mmio(ghcb, ctxt);
1221 * Unexpected #VC exception
1223 result = ES_UNSUPPORTED;
1229 static __always_inline void vc_forward_exception(struct es_em_ctxt *ctxt)
1231 long error_code = ctxt->fi.error_code;
1232 int trapnr = ctxt->fi.vector;
1234 ctxt->regs->orig_ax = ctxt->fi.error_code;
1238 exc_general_protection(ctxt->regs, error_code);
1241 exc_invalid_op(ctxt->regs);
1244 exc_alignment_check(ctxt->regs, error_code);
1247 pr_emerg("Unsupported exception in #VC instruction emulation - can't continue\n");
1252 static __always_inline bool on_vc_fallback_stack(struct pt_regs *regs)
1254 unsigned long sp = (unsigned long)regs;
1256 return (sp >= __this_cpu_ist_bottom_va(VC2) && sp < __this_cpu_ist_top_va(VC2));
1260 * Main #VC exception handler. It is called when the entry code was able to
1261 * switch off the IST to a safe kernel stack.
1263 * With the current implementation it is always possible to switch to a safe
1264 * stack because #VC exceptions only happen at known places, like intercepted
1265 * instructions or accesses to MMIO areas/IO ports. They can also happen with
1266 * code instrumentation when the hypervisor intercepts #DB, but the critical
1267 * paths are forbidden to be instrumented, so #DB exceptions currently also
1268 * only happen in safe places.
1270 DEFINE_IDTENTRY_VC_SAFE_STACK(exc_vmm_communication)
1272 struct sev_es_runtime_data *data = this_cpu_read(runtime_data);
1273 irqentry_state_t irq_state;
1274 struct ghcb_state state;
1275 struct es_em_ctxt ctxt;
1276 enum es_result result;
1280 * Handle #DB before calling into !noinstr code to avoid recursive #DB.
1282 if (error_code == SVM_EXIT_EXCP_BASE + X86_TRAP_DB) {
1283 vc_handle_trap_db(regs);
1287 irq_state = irqentry_nmi_enter(regs);
1288 lockdep_assert_irqs_disabled();
1289 instrumentation_begin();
1292 * This is invoked through an interrupt gate, so IRQs are disabled. The
1293 * code below might walk page-tables for user or kernel addresses, so
1294 * keep the IRQs disabled to protect us against concurrent TLB flushes.
1297 ghcb = sev_es_get_ghcb(&state);
1300 * Mark GHCBs inactive so that panic() is able to print the
1303 data->ghcb_active = false;
1304 data->backup_ghcb_active = false;
1306 panic("Unable to handle #VC exception! GHCB and Backup GHCB are already in use");
1309 vc_ghcb_invalidate(ghcb);
1310 result = vc_init_em_ctxt(&ctxt, regs, error_code);
1312 if (result == ES_OK)
1313 result = vc_handle_exitcode(&ctxt, ghcb, error_code);
1315 sev_es_put_ghcb(&state);
1317 /* Done - now check the result */
1320 vc_finish_insn(&ctxt);
1322 case ES_UNSUPPORTED:
1323 pr_err_ratelimited("Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1324 error_code, regs->ip);
1327 pr_err_ratelimited("Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1328 error_code, regs->ip);
1330 case ES_DECODE_FAILED:
1331 pr_err_ratelimited("Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1332 error_code, regs->ip);
1335 vc_forward_exception(&ctxt);
1341 pr_emerg("Unknown result in %s():%d\n", __func__, result);
1343 * Emulating the instruction which caused the #VC exception
1344 * failed - can't continue so print debug information
1350 instrumentation_end();
1351 irqentry_nmi_exit(regs, irq_state);
1356 if (user_mode(regs)) {
1358 * Do not kill the machine if user-space triggered the
1359 * exception. Send SIGBUS instead and let user-space deal with
1362 force_sig_fault(SIGBUS, BUS_OBJERR, (void __user *)0);
1364 pr_emerg("PANIC: Unhandled #VC exception in kernel space (result=%d)\n",
1367 /* Show some debug info */
1370 /* Ask hypervisor to sev_es_terminate */
1371 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1373 /* If that fails and we get here - just panic */
1374 panic("Returned from Terminate-Request to Hypervisor\n");
1380 /* This handler runs on the #VC fall-back stack. It can cause further #VC exceptions */
1381 DEFINE_IDTENTRY_VC_IST(exc_vmm_communication)
1383 instrumentation_begin();
1384 panic("Can't handle #VC exception from unsupported context\n");
1385 instrumentation_end();
1388 DEFINE_IDTENTRY_VC(exc_vmm_communication)
1390 if (likely(!on_vc_fallback_stack(regs)))
1391 safe_stack_exc_vmm_communication(regs, error_code);
1393 ist_exc_vmm_communication(regs, error_code);
1396 bool __init handle_vc_boot_ghcb(struct pt_regs *regs)
1398 unsigned long exit_code = regs->orig_ax;
1399 struct es_em_ctxt ctxt;
1400 enum es_result result;
1402 /* Do initial setup or terminate the guest */
1403 if (unlikely(boot_ghcb == NULL && !sev_es_setup_ghcb()))
1404 sev_es_terminate(GHCB_SEV_ES_REASON_GENERAL_REQUEST);
1406 vc_ghcb_invalidate(boot_ghcb);
1408 result = vc_init_em_ctxt(&ctxt, regs, exit_code);
1409 if (result == ES_OK)
1410 result = vc_handle_exitcode(&ctxt, boot_ghcb, exit_code);
1412 /* Done - now check the result */
1415 vc_finish_insn(&ctxt);
1417 case ES_UNSUPPORTED:
1418 early_printk("PANIC: Unsupported exit-code 0x%02lx in early #VC exception (IP: 0x%lx)\n",
1419 exit_code, regs->ip);
1422 early_printk("PANIC: Failure in communication with VMM (exit-code 0x%02lx IP: 0x%lx)\n",
1423 exit_code, regs->ip);
1425 case ES_DECODE_FAILED:
1426 early_printk("PANIC: Failed to decode instruction (exit-code 0x%02lx IP: 0x%lx)\n",
1427 exit_code, regs->ip);
1430 vc_early_forward_exception(&ctxt);