2 * Kernel-based Virtual Machine driver for Linux
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 * Yaniv Kamay <yaniv@qumranet.com>
11 * Avi Kivity <avi@qumranet.com>
13 * This work is licensed under the terms of the GNU GPL, version 2. See
14 * the COPYING file in the top-level directory.
18 #define pr_fmt(fmt) "SVM: " fmt
20 #include <linux/kvm_host.h>
24 #include "kvm_cache_regs.h"
29 #include <linux/module.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/kernel.h>
32 #include <linux/vmalloc.h>
33 #include <linux/highmem.h>
34 #include <linux/sched.h>
35 #include <linux/trace_events.h>
36 #include <linux/slab.h>
37 #include <linux/amd-iommu.h>
38 #include <linux/hashtable.h>
39 #include <linux/frame.h>
40 #include <linux/psp-sev.h>
41 #include <linux/file.h>
42 #include <linux/pagemap.h>
43 #include <linux/swap.h>
46 #include <asm/perf_event.h>
47 #include <asm/tlbflush.h>
49 #include <asm/debugreg.h>
50 #include <asm/kvm_para.h>
51 #include <asm/irq_remapping.h>
52 #include <asm/microcode.h>
53 #include <asm/nospec-branch.h>
55 #include <asm/virtext.h>
58 #define __ex(x) __kvm_handle_fault_on_reboot(x)
60 MODULE_AUTHOR("Qumranet");
61 MODULE_LICENSE("GPL");
63 static const struct x86_cpu_id svm_cpu_id[] = {
64 X86_FEATURE_MATCH(X86_FEATURE_SVM),
67 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
69 #define IOPM_ALLOC_ORDER 2
70 #define MSRPM_ALLOC_ORDER 1
72 #define SEG_TYPE_LDT 2
73 #define SEG_TYPE_BUSY_TSS16 3
75 #define SVM_FEATURE_NPT (1 << 0)
76 #define SVM_FEATURE_LBRV (1 << 1)
77 #define SVM_FEATURE_SVML (1 << 2)
78 #define SVM_FEATURE_NRIP (1 << 3)
79 #define SVM_FEATURE_TSC_RATE (1 << 4)
80 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
81 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
82 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
83 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
85 #define SVM_AVIC_DOORBELL 0xc001011b
87 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
88 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
89 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
91 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
93 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
94 #define TSC_RATIO_MIN 0x0000000000000001ULL
95 #define TSC_RATIO_MAX 0x000000ffffffffffULL
97 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
100 * 0xff is broadcast, so the max index allowed for physical APIC ID
101 * table is 0xfe. APIC IDs above 0xff are reserved.
103 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
105 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
106 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
107 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
109 /* AVIC GATAG is encoded using VM and VCPU IDs */
110 #define AVIC_VCPU_ID_BITS 8
111 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
113 #define AVIC_VM_ID_BITS 24
114 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
115 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
117 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
118 (y & AVIC_VCPU_ID_MASK))
119 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
120 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
122 static bool erratum_383_found __read_mostly;
124 static const u32 host_save_user_msrs[] = {
126 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
129 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
133 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
137 struct nested_state {
143 /* These are the merged vectors */
146 /* gpa pointers to the real vectors */
150 /* A VMEXIT is required but not yet emulated */
153 /* cache for intercepts of the guest */
156 u32 intercept_exceptions;
159 /* Nested Paging related state */
163 #define MSRPM_OFFSETS 16
164 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
167 * Set osvw_len to higher value when updated Revision Guides
168 * are published and we know what the new status bits are
170 static uint64_t osvw_len = 4, osvw_status;
173 struct kvm_vcpu vcpu;
175 unsigned long vmcb_pa;
176 struct svm_cpu_data *svm_data;
177 uint64_t asid_generation;
178 uint64_t sysenter_esp;
179 uint64_t sysenter_eip;
184 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
198 struct nested_state nested;
201 u64 nmi_singlestep_guest_rflags;
203 unsigned int3_injected;
204 unsigned long int3_rip;
206 /* cached guest cpuid flags for faster access */
207 bool nrips_enabled : 1;
210 struct page *avic_backing_page;
211 u64 *avic_physical_id_cache;
212 bool avic_is_running;
215 * Per-vcpu list of struct amd_svm_iommu_ir:
216 * This is used mainly to store interrupt remapping information used
217 * when update the vcpu affinity. This avoids the need to scan for
218 * IRTE and try to match ga_tag in the IOMMU driver.
220 struct list_head ir_list;
221 spinlock_t ir_list_lock;
223 /* which host CPU was used for running this vcpu */
224 unsigned int last_cpu;
228 * This is a wrapper of struct amd_iommu_ir_data.
230 struct amd_svm_iommu_ir {
231 struct list_head node; /* Used by SVM for per-vcpu ir_list */
232 void *data; /* Storing pointer to struct amd_ir_data */
235 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
236 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
238 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
239 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
240 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
241 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
243 static DEFINE_PER_CPU(u64, current_tsc_ratio);
244 #define TSC_RATIO_DEFAULT 0x0100000000ULL
246 #define MSR_INVALID 0xffffffffU
248 static const struct svm_direct_access_msrs {
249 u32 index; /* Index of the MSR */
250 bool always; /* True if intercept is always on */
251 } direct_access_msrs[] = {
252 { .index = MSR_STAR, .always = true },
253 { .index = MSR_IA32_SYSENTER_CS, .always = true },
255 { .index = MSR_GS_BASE, .always = true },
256 { .index = MSR_FS_BASE, .always = true },
257 { .index = MSR_KERNEL_GS_BASE, .always = true },
258 { .index = MSR_LSTAR, .always = true },
259 { .index = MSR_CSTAR, .always = true },
260 { .index = MSR_SYSCALL_MASK, .always = true },
262 { .index = MSR_IA32_SPEC_CTRL, .always = false },
263 { .index = MSR_IA32_PRED_CMD, .always = false },
264 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
265 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
266 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
267 { .index = MSR_IA32_LASTINTTOIP, .always = false },
268 { .index = MSR_INVALID, .always = false },
271 /* enable NPT for AMD64 and X86 with PAE */
272 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
273 static bool npt_enabled = true;
275 static bool npt_enabled;
278 /* allow nested paging (virtualized MMU) for all guests */
279 static int npt = true;
280 module_param(npt, int, S_IRUGO);
282 /* allow nested virtualization in KVM/SVM */
283 static int nested = true;
284 module_param(nested, int, S_IRUGO);
286 /* enable / disable AVIC */
288 #ifdef CONFIG_X86_LOCAL_APIC
289 module_param(avic, int, S_IRUGO);
292 /* enable/disable Virtual VMLOAD VMSAVE */
293 static int vls = true;
294 module_param(vls, int, 0444);
296 /* enable/disable Virtual GIF */
297 static int vgif = true;
298 module_param(vgif, int, 0444);
300 /* enable/disable SEV support */
301 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
302 module_param(sev, int, 0444);
304 static u8 rsm_ins_bytes[] = "\x0f\xaa";
306 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
307 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
308 static void svm_complete_interrupts(struct vcpu_svm *svm);
310 static int nested_svm_exit_handled(struct vcpu_svm *svm);
311 static int nested_svm_intercept(struct vcpu_svm *svm);
312 static int nested_svm_vmexit(struct vcpu_svm *svm);
313 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
314 bool has_error_code, u32 error_code);
317 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
318 pause filter count */
319 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
320 VMCB_ASID, /* ASID */
321 VMCB_INTR, /* int_ctl, int_vector */
322 VMCB_NPT, /* npt_en, nCR3, gPAT */
323 VMCB_CR, /* CR0, CR3, CR4, EFER */
324 VMCB_DR, /* DR6, DR7 */
325 VMCB_DT, /* GDT, IDT */
326 VMCB_SEG, /* CS, DS, SS, ES, CPL */
327 VMCB_CR2, /* CR2 only */
328 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
329 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
330 * AVIC PHYSICAL_TABLE pointer,
331 * AVIC LOGICAL_TABLE pointer
336 /* TPR and CR2 are always written before VMRUN */
337 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
339 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
341 static unsigned int max_sev_asid;
342 static unsigned int min_sev_asid;
343 static unsigned long *sev_asid_bitmap;
344 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
347 struct list_head list;
348 unsigned long npages;
354 static inline bool svm_sev_enabled(void)
359 static inline bool sev_guest(struct kvm *kvm)
361 struct kvm_sev_info *sev = &kvm->arch.sev_info;
366 static inline int sev_get_asid(struct kvm *kvm)
368 struct kvm_sev_info *sev = &kvm->arch.sev_info;
373 static inline void mark_all_dirty(struct vmcb *vmcb)
375 vmcb->control.clean = 0;
378 static inline void mark_all_clean(struct vmcb *vmcb)
380 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
381 & ~VMCB_ALWAYS_DIRTY_MASK;
384 static inline void mark_dirty(struct vmcb *vmcb, int bit)
386 vmcb->control.clean &= ~(1 << bit);
389 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
391 return container_of(vcpu, struct vcpu_svm, vcpu);
394 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
396 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
397 mark_dirty(svm->vmcb, VMCB_AVIC);
400 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
402 struct vcpu_svm *svm = to_svm(vcpu);
403 u64 *entry = svm->avic_physical_id_cache;
408 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
411 static void recalc_intercepts(struct vcpu_svm *svm)
413 struct vmcb_control_area *c, *h;
414 struct nested_state *g;
416 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
418 if (!is_guest_mode(&svm->vcpu))
421 c = &svm->vmcb->control;
422 h = &svm->nested.hsave->control;
425 c->intercept_cr = h->intercept_cr | g->intercept_cr;
426 c->intercept_dr = h->intercept_dr | g->intercept_dr;
427 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
428 c->intercept = h->intercept | g->intercept;
431 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
433 if (is_guest_mode(&svm->vcpu))
434 return svm->nested.hsave;
439 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
441 struct vmcb *vmcb = get_host_vmcb(svm);
443 vmcb->control.intercept_cr |= (1U << bit);
445 recalc_intercepts(svm);
448 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
450 struct vmcb *vmcb = get_host_vmcb(svm);
452 vmcb->control.intercept_cr &= ~(1U << bit);
454 recalc_intercepts(svm);
457 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
459 struct vmcb *vmcb = get_host_vmcb(svm);
461 return vmcb->control.intercept_cr & (1U << bit);
464 static inline void set_dr_intercepts(struct vcpu_svm *svm)
466 struct vmcb *vmcb = get_host_vmcb(svm);
468 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
469 | (1 << INTERCEPT_DR1_READ)
470 | (1 << INTERCEPT_DR2_READ)
471 | (1 << INTERCEPT_DR3_READ)
472 | (1 << INTERCEPT_DR4_READ)
473 | (1 << INTERCEPT_DR5_READ)
474 | (1 << INTERCEPT_DR6_READ)
475 | (1 << INTERCEPT_DR7_READ)
476 | (1 << INTERCEPT_DR0_WRITE)
477 | (1 << INTERCEPT_DR1_WRITE)
478 | (1 << INTERCEPT_DR2_WRITE)
479 | (1 << INTERCEPT_DR3_WRITE)
480 | (1 << INTERCEPT_DR4_WRITE)
481 | (1 << INTERCEPT_DR5_WRITE)
482 | (1 << INTERCEPT_DR6_WRITE)
483 | (1 << INTERCEPT_DR7_WRITE);
485 recalc_intercepts(svm);
488 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
490 struct vmcb *vmcb = get_host_vmcb(svm);
492 vmcb->control.intercept_dr = 0;
494 recalc_intercepts(svm);
497 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
499 struct vmcb *vmcb = get_host_vmcb(svm);
501 vmcb->control.intercept_exceptions |= (1U << bit);
503 recalc_intercepts(svm);
506 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
508 struct vmcb *vmcb = get_host_vmcb(svm);
510 vmcb->control.intercept_exceptions &= ~(1U << bit);
512 recalc_intercepts(svm);
515 static inline void set_intercept(struct vcpu_svm *svm, int bit)
517 struct vmcb *vmcb = get_host_vmcb(svm);
519 vmcb->control.intercept |= (1ULL << bit);
521 recalc_intercepts(svm);
524 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
526 struct vmcb *vmcb = get_host_vmcb(svm);
528 vmcb->control.intercept &= ~(1ULL << bit);
530 recalc_intercepts(svm);
533 static inline bool vgif_enabled(struct vcpu_svm *svm)
535 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
538 static inline void enable_gif(struct vcpu_svm *svm)
540 if (vgif_enabled(svm))
541 svm->vmcb->control.int_ctl |= V_GIF_MASK;
543 svm->vcpu.arch.hflags |= HF_GIF_MASK;
546 static inline void disable_gif(struct vcpu_svm *svm)
548 if (vgif_enabled(svm))
549 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
551 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
554 static inline bool gif_set(struct vcpu_svm *svm)
556 if (vgif_enabled(svm))
557 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
559 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
562 static unsigned long iopm_base;
564 struct kvm_ldttss_desc {
567 unsigned base1:8, type:5, dpl:2, p:1;
568 unsigned limit1:4, zero0:3, g:1, base2:8;
571 } __attribute__((packed));
573 struct svm_cpu_data {
580 struct kvm_ldttss_desc *tss_desc;
582 struct page *save_area;
583 struct vmcb *current_vmcb;
585 /* index = sev_asid, value = vmcb pointer */
586 struct vmcb **sev_vmcbs;
589 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
591 struct svm_init_data {
596 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
598 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
599 #define MSRS_RANGE_SIZE 2048
600 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
602 static u32 svm_msrpm_offset(u32 msr)
607 for (i = 0; i < NUM_MSR_MAPS; i++) {
608 if (msr < msrpm_ranges[i] ||
609 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
612 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
613 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
615 /* Now we have the u8 offset - but need the u32 offset */
619 /* MSR not in any range */
623 #define MAX_INST_SIZE 15
625 static inline void clgi(void)
627 asm volatile (__ex(SVM_CLGI));
630 static inline void stgi(void)
632 asm volatile (__ex(SVM_STGI));
635 static inline void invlpga(unsigned long addr, u32 asid)
637 asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
640 static int get_npt_level(struct kvm_vcpu *vcpu)
643 return PT64_ROOT_4LEVEL;
645 return PT32E_ROOT_LEVEL;
649 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
651 vcpu->arch.efer = efer;
652 if (!npt_enabled && !(efer & EFER_LMA))
655 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
656 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
659 static int is_external_interrupt(u32 info)
661 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
662 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
665 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
667 struct vcpu_svm *svm = to_svm(vcpu);
670 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
671 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
675 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
677 struct vcpu_svm *svm = to_svm(vcpu);
680 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
682 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
686 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
688 struct vcpu_svm *svm = to_svm(vcpu);
690 if (svm->vmcb->control.next_rip != 0) {
691 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
692 svm->next_rip = svm->vmcb->control.next_rip;
695 if (!svm->next_rip) {
696 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
698 printk(KERN_DEBUG "%s: NOP\n", __func__);
701 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
702 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
703 __func__, kvm_rip_read(vcpu), svm->next_rip);
705 kvm_rip_write(vcpu, svm->next_rip);
706 svm_set_interrupt_shadow(vcpu, 0);
709 static void svm_queue_exception(struct kvm_vcpu *vcpu)
711 struct vcpu_svm *svm = to_svm(vcpu);
712 unsigned nr = vcpu->arch.exception.nr;
713 bool has_error_code = vcpu->arch.exception.has_error_code;
714 bool reinject = vcpu->arch.exception.injected;
715 u32 error_code = vcpu->arch.exception.error_code;
718 * If we are within a nested VM we'd better #VMEXIT and let the guest
719 * handle the exception
722 nested_svm_check_exception(svm, nr, has_error_code, error_code))
725 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
726 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
729 * For guest debugging where we have to reinject #BP if some
730 * INT3 is guest-owned:
731 * Emulate nRIP by moving RIP forward. Will fail if injection
732 * raises a fault that is not intercepted. Still better than
733 * failing in all cases.
735 skip_emulated_instruction(&svm->vcpu);
736 rip = kvm_rip_read(&svm->vcpu);
737 svm->int3_rip = rip + svm->vmcb->save.cs.base;
738 svm->int3_injected = rip - old_rip;
741 svm->vmcb->control.event_inj = nr
743 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
744 | SVM_EVTINJ_TYPE_EXEPT;
745 svm->vmcb->control.event_inj_err = error_code;
748 static void svm_init_erratum_383(void)
754 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
757 /* Use _safe variants to not break nested virtualization */
758 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
764 low = lower_32_bits(val);
765 high = upper_32_bits(val);
767 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
769 erratum_383_found = true;
772 static void svm_init_osvw(struct kvm_vcpu *vcpu)
775 * Guests should see errata 400 and 415 as fixed (assuming that
776 * HLT and IO instructions are intercepted).
778 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
779 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
782 * By increasing VCPU's osvw.length to 3 we are telling the guest that
783 * all osvw.status bits inside that length, including bit 0 (which is
784 * reserved for erratum 298), are valid. However, if host processor's
785 * osvw_len is 0 then osvw_status[0] carries no information. We need to
786 * be conservative here and therefore we tell the guest that erratum 298
787 * is present (because we really don't know).
789 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
790 vcpu->arch.osvw.status |= 1;
793 static int has_svm(void)
797 if (!cpu_has_svm(&msg)) {
798 printk(KERN_INFO "has_svm: %s\n", msg);
805 static void svm_hardware_disable(void)
807 /* Make sure we clean up behind us */
808 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
809 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
813 amd_pmu_disable_virt();
816 static int svm_hardware_enable(void)
819 struct svm_cpu_data *sd;
821 struct desc_struct *gdt;
822 int me = raw_smp_processor_id();
824 rdmsrl(MSR_EFER, efer);
825 if (efer & EFER_SVME)
829 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
832 sd = per_cpu(svm_data, me);
834 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
838 sd->asid_generation = 1;
839 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
840 sd->next_asid = sd->max_asid + 1;
841 sd->min_asid = max_sev_asid + 1;
843 gdt = get_current_gdt_rw();
844 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
846 wrmsrl(MSR_EFER, efer | EFER_SVME);
848 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
850 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
851 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
852 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
859 * Note that it is possible to have a system with mixed processor
860 * revisions and therefore different OSVW bits. If bits are not the same
861 * on different processors then choose the worst case (i.e. if erratum
862 * is present on one processor and not on another then assume that the
863 * erratum is present everywhere).
865 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
866 uint64_t len, status = 0;
869 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
871 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
875 osvw_status = osvw_len = 0;
879 osvw_status |= status;
880 osvw_status &= (1ULL << osvw_len) - 1;
883 osvw_status = osvw_len = 0;
885 svm_init_erratum_383();
887 amd_pmu_enable_virt();
892 static void svm_cpu_uninit(int cpu)
894 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
899 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
900 kfree(sd->sev_vmcbs);
901 __free_page(sd->save_area);
905 static int svm_cpu_init(int cpu)
907 struct svm_cpu_data *sd;
910 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
915 sd->save_area = alloc_page(GFP_KERNEL);
919 if (svm_sev_enabled()) {
921 sd->sev_vmcbs = kmalloc((max_sev_asid + 1) * sizeof(void *), GFP_KERNEL);
926 per_cpu(svm_data, cpu) = sd;
936 static bool valid_msr_intercept(u32 index)
940 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
941 if (direct_access_msrs[i].index == index)
947 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
954 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
957 offset = svm_msrpm_offset(msr);
958 bit_write = 2 * (msr & 0x0f) + 1;
961 BUG_ON(offset == MSR_INVALID);
963 return !!test_bit(bit_write, &tmp);
966 static void set_msr_interception(u32 *msrpm, unsigned msr,
969 u8 bit_read, bit_write;
974 * If this warning triggers extend the direct_access_msrs list at the
975 * beginning of the file
977 WARN_ON(!valid_msr_intercept(msr));
979 offset = svm_msrpm_offset(msr);
980 bit_read = 2 * (msr & 0x0f);
981 bit_write = 2 * (msr & 0x0f) + 1;
984 BUG_ON(offset == MSR_INVALID);
986 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
987 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
992 static void svm_vcpu_init_msrpm(u32 *msrpm)
996 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
998 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
999 if (!direct_access_msrs[i].always)
1002 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1006 static void add_msr_offset(u32 offset)
1010 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1012 /* Offset already in list? */
1013 if (msrpm_offsets[i] == offset)
1016 /* Slot used by another offset? */
1017 if (msrpm_offsets[i] != MSR_INVALID)
1020 /* Add offset to list */
1021 msrpm_offsets[i] = offset;
1027 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1028 * increase MSRPM_OFFSETS in this case.
1033 static void init_msrpm_offsets(void)
1037 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1039 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1042 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1043 BUG_ON(offset == MSR_INVALID);
1045 add_msr_offset(offset);
1049 static void svm_enable_lbrv(struct vcpu_svm *svm)
1051 u32 *msrpm = svm->msrpm;
1053 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1054 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1055 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1056 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1057 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1060 static void svm_disable_lbrv(struct vcpu_svm *svm)
1062 u32 *msrpm = svm->msrpm;
1064 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1065 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1066 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1067 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1068 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1071 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1073 svm->nmi_singlestep = false;
1075 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1076 /* Clear our flags if they were not set by the guest */
1077 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1078 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1079 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1080 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1085 * This hash table is used to map VM_ID to a struct kvm_arch,
1086 * when handling AMD IOMMU GALOG notification to schedule in
1087 * a particular vCPU.
1089 #define SVM_VM_DATA_HASH_BITS 8
1090 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1091 static u32 next_vm_id = 0;
1092 static bool next_vm_id_wrapped = 0;
1093 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1096 * This function is called from IOMMU driver to notify
1097 * SVM to schedule in a particular vCPU of a particular VM.
1099 static int avic_ga_log_notifier(u32 ga_tag)
1101 unsigned long flags;
1102 struct kvm_arch *ka = NULL;
1103 struct kvm_vcpu *vcpu = NULL;
1104 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1105 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1107 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1109 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1110 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1111 struct kvm *kvm = container_of(ka, struct kvm, arch);
1112 struct kvm_arch *vm_data = &kvm->arch;
1114 if (vm_data->avic_vm_id != vm_id)
1116 vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1119 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1122 * At this point, the IOMMU should have already set the pending
1123 * bit in the vAPIC backing page. So, we just need to schedule
1127 kvm_vcpu_wake_up(vcpu);
1132 static __init int sev_hardware_setup(void)
1134 struct sev_user_data_status *status;
1137 /* Maximum number of encrypted guests supported simultaneously */
1138 max_sev_asid = cpuid_ecx(0x8000001F);
1143 /* Minimum ASID value that should be used for SEV guest */
1144 min_sev_asid = cpuid_edx(0x8000001F);
1146 /* Initialize SEV ASID bitmap */
1147 sev_asid_bitmap = kcalloc(BITS_TO_LONGS(max_sev_asid),
1148 sizeof(unsigned long), GFP_KERNEL);
1149 if (!sev_asid_bitmap)
1152 status = kmalloc(sizeof(*status), GFP_KERNEL);
1157 * Check SEV platform status.
1159 * PLATFORM_STATUS can be called in any state, if we failed to query
1160 * the PLATFORM status then either PSP firmware does not support SEV
1161 * feature or SEV firmware is dead.
1163 rc = sev_platform_status(status, NULL);
1167 pr_info("SEV supported\n");
1174 static __init int svm_hardware_setup(void)
1177 struct page *iopm_pages;
1181 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1186 iopm_va = page_address(iopm_pages);
1187 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1188 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1190 init_msrpm_offsets();
1192 if (boot_cpu_has(X86_FEATURE_NX))
1193 kvm_enable_efer_bits(EFER_NX);
1195 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1196 kvm_enable_efer_bits(EFER_FFXSR);
1198 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1199 kvm_has_tsc_control = true;
1200 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1201 kvm_tsc_scaling_ratio_frac_bits = 32;
1205 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1206 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1210 if (boot_cpu_has(X86_FEATURE_SEV) &&
1211 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1212 r = sev_hardware_setup();
1220 for_each_possible_cpu(cpu) {
1221 r = svm_cpu_init(cpu);
1226 if (!boot_cpu_has(X86_FEATURE_NPT))
1227 npt_enabled = false;
1229 if (npt_enabled && !npt) {
1230 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1231 npt_enabled = false;
1235 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1242 !boot_cpu_has(X86_FEATURE_AVIC) ||
1243 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1246 pr_info("AVIC enabled\n");
1248 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1254 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1255 !IS_ENABLED(CONFIG_X86_64)) {
1258 pr_info("Virtual VMLOAD VMSAVE supported\n");
1263 if (!boot_cpu_has(X86_FEATURE_VGIF))
1266 pr_info("Virtual GIF supported\n");
1272 __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1277 static __exit void svm_hardware_unsetup(void)
1281 if (svm_sev_enabled())
1282 kfree(sev_asid_bitmap);
1284 for_each_possible_cpu(cpu)
1285 svm_cpu_uninit(cpu);
1287 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1291 static void init_seg(struct vmcb_seg *seg)
1294 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1295 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1296 seg->limit = 0xffff;
1300 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1303 seg->attrib = SVM_SELECTOR_P_MASK | type;
1304 seg->limit = 0xffff;
1308 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1310 struct vcpu_svm *svm = to_svm(vcpu);
1311 u64 g_tsc_offset = 0;
1313 if (is_guest_mode(vcpu)) {
1314 g_tsc_offset = svm->vmcb->control.tsc_offset -
1315 svm->nested.hsave->control.tsc_offset;
1316 svm->nested.hsave->control.tsc_offset = offset;
1318 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1319 svm->vmcb->control.tsc_offset,
1322 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1324 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1327 static void avic_init_vmcb(struct vcpu_svm *svm)
1329 struct vmcb *vmcb = svm->vmcb;
1330 struct kvm_arch *vm_data = &svm->vcpu.kvm->arch;
1331 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1332 phys_addr_t lpa = __sme_set(page_to_phys(vm_data->avic_logical_id_table_page));
1333 phys_addr_t ppa = __sme_set(page_to_phys(vm_data->avic_physical_id_table_page));
1335 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1336 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1337 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1338 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1339 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1342 static void init_vmcb(struct vcpu_svm *svm)
1344 struct vmcb_control_area *control = &svm->vmcb->control;
1345 struct vmcb_save_area *save = &svm->vmcb->save;
1347 svm->vcpu.arch.hflags = 0;
1349 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1350 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1351 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1352 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1353 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1354 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1355 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1356 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1358 set_dr_intercepts(svm);
1360 set_exception_intercept(svm, PF_VECTOR);
1361 set_exception_intercept(svm, UD_VECTOR);
1362 set_exception_intercept(svm, MC_VECTOR);
1363 set_exception_intercept(svm, AC_VECTOR);
1364 set_exception_intercept(svm, DB_VECTOR);
1366 set_intercept(svm, INTERCEPT_INTR);
1367 set_intercept(svm, INTERCEPT_NMI);
1368 set_intercept(svm, INTERCEPT_SMI);
1369 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1370 set_intercept(svm, INTERCEPT_RDPMC);
1371 set_intercept(svm, INTERCEPT_CPUID);
1372 set_intercept(svm, INTERCEPT_INVD);
1373 set_intercept(svm, INTERCEPT_HLT);
1374 set_intercept(svm, INTERCEPT_INVLPG);
1375 set_intercept(svm, INTERCEPT_INVLPGA);
1376 set_intercept(svm, INTERCEPT_IOIO_PROT);
1377 set_intercept(svm, INTERCEPT_MSR_PROT);
1378 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1379 set_intercept(svm, INTERCEPT_SHUTDOWN);
1380 set_intercept(svm, INTERCEPT_VMRUN);
1381 set_intercept(svm, INTERCEPT_VMMCALL);
1382 set_intercept(svm, INTERCEPT_VMLOAD);
1383 set_intercept(svm, INTERCEPT_VMSAVE);
1384 set_intercept(svm, INTERCEPT_STGI);
1385 set_intercept(svm, INTERCEPT_CLGI);
1386 set_intercept(svm, INTERCEPT_SKINIT);
1387 set_intercept(svm, INTERCEPT_WBINVD);
1388 set_intercept(svm, INTERCEPT_XSETBV);
1389 set_intercept(svm, INTERCEPT_RSM);
1391 if (!kvm_mwait_in_guest()) {
1392 set_intercept(svm, INTERCEPT_MONITOR);
1393 set_intercept(svm, INTERCEPT_MWAIT);
1396 control->iopm_base_pa = __sme_set(iopm_base);
1397 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1398 control->int_ctl = V_INTR_MASKING_MASK;
1400 init_seg(&save->es);
1401 init_seg(&save->ss);
1402 init_seg(&save->ds);
1403 init_seg(&save->fs);
1404 init_seg(&save->gs);
1406 save->cs.selector = 0xf000;
1407 save->cs.base = 0xffff0000;
1408 /* Executable/Readable Code Segment */
1409 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1410 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1411 save->cs.limit = 0xffff;
1413 save->gdtr.limit = 0xffff;
1414 save->idtr.limit = 0xffff;
1416 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1417 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1419 svm_set_efer(&svm->vcpu, 0);
1420 save->dr6 = 0xffff0ff0;
1421 kvm_set_rflags(&svm->vcpu, 2);
1422 save->rip = 0x0000fff0;
1423 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1426 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1427 * It also updates the guest-visible cr0 value.
1429 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1430 kvm_mmu_reset_context(&svm->vcpu);
1432 save->cr4 = X86_CR4_PAE;
1436 /* Setup VMCB for Nested Paging */
1437 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1438 clr_intercept(svm, INTERCEPT_INVLPG);
1439 clr_exception_intercept(svm, PF_VECTOR);
1440 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1441 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1442 save->g_pat = svm->vcpu.arch.pat;
1446 svm->asid_generation = 0;
1448 svm->nested.vmcb = 0;
1449 svm->vcpu.arch.hflags = 0;
1451 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1452 control->pause_filter_count = 3000;
1453 set_intercept(svm, INTERCEPT_PAUSE);
1456 if (kvm_vcpu_apicv_active(&svm->vcpu))
1457 avic_init_vmcb(svm);
1460 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1461 * in VMCB and clear intercepts to avoid #VMEXIT.
1464 clr_intercept(svm, INTERCEPT_VMLOAD);
1465 clr_intercept(svm, INTERCEPT_VMSAVE);
1466 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1470 clr_intercept(svm, INTERCEPT_STGI);
1471 clr_intercept(svm, INTERCEPT_CLGI);
1472 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1475 if (sev_guest(svm->vcpu.kvm)) {
1476 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1477 clr_exception_intercept(svm, UD_VECTOR);
1480 mark_all_dirty(svm->vmcb);
1486 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1489 u64 *avic_physical_id_table;
1490 struct kvm_arch *vm_data = &vcpu->kvm->arch;
1492 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1495 avic_physical_id_table = page_address(vm_data->avic_physical_id_table_page);
1497 return &avic_physical_id_table[index];
1502 * AVIC hardware walks the nested page table to check permissions,
1503 * but does not use the SPA address specified in the leaf page
1504 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1505 * field of the VMCB. Therefore, we set up the
1506 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1508 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1510 struct kvm *kvm = vcpu->kvm;
1513 if (kvm->arch.apic_access_page_done)
1516 ret = x86_set_memory_region(kvm,
1517 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1518 APIC_DEFAULT_PHYS_BASE,
1523 kvm->arch.apic_access_page_done = true;
1527 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1530 u64 *entry, new_entry;
1531 int id = vcpu->vcpu_id;
1532 struct vcpu_svm *svm = to_svm(vcpu);
1534 ret = avic_init_access_page(vcpu);
1538 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1541 if (!svm->vcpu.arch.apic->regs)
1544 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1546 /* Setting AVIC backing page address in the phy APIC ID table */
1547 entry = avic_get_physical_id_entry(vcpu, id);
1551 new_entry = READ_ONCE(*entry);
1552 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1553 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1554 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1555 WRITE_ONCE(*entry, new_entry);
1557 svm->avic_physical_id_cache = entry;
1562 static void __sev_asid_free(int asid)
1564 struct svm_cpu_data *sd;
1568 clear_bit(pos, sev_asid_bitmap);
1570 for_each_possible_cpu(cpu) {
1571 sd = per_cpu(svm_data, cpu);
1572 sd->sev_vmcbs[pos] = NULL;
1576 static void sev_asid_free(struct kvm *kvm)
1578 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1580 __sev_asid_free(sev->asid);
1583 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1585 struct sev_data_decommission *decommission;
1586 struct sev_data_deactivate *data;
1591 data = kzalloc(sizeof(*data), GFP_KERNEL);
1595 /* deactivate handle */
1596 data->handle = handle;
1597 sev_guest_deactivate(data, NULL);
1599 wbinvd_on_all_cpus();
1600 sev_guest_df_flush(NULL);
1603 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1607 /* decommission handle */
1608 decommission->handle = handle;
1609 sev_guest_decommission(decommission, NULL);
1611 kfree(decommission);
1614 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1615 unsigned long ulen, unsigned long *n,
1618 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1619 unsigned long npages, npinned, size;
1620 unsigned long locked, lock_limit;
1621 struct page **pages;
1624 /* Calculate number of pages. */
1625 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1626 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1627 npages = (last - first + 1);
1629 locked = sev->pages_locked + npages;
1630 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1631 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1632 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1636 /* Avoid using vmalloc for smaller buffers. */
1637 size = npages * sizeof(struct page *);
1638 if (size > PAGE_SIZE)
1639 pages = vmalloc(size);
1641 pages = kmalloc(size, GFP_KERNEL);
1646 /* Pin the user virtual address. */
1647 npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1648 if (npinned != npages) {
1649 pr_err("SEV: Failure locking %lu pages.\n", npages);
1654 sev->pages_locked = locked;
1660 release_pages(pages, npinned);
1666 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1667 unsigned long npages)
1669 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1671 release_pages(pages, npages);
1673 sev->pages_locked -= npages;
1676 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1678 uint8_t *page_virtual;
1681 if (npages == 0 || pages == NULL)
1684 for (i = 0; i < npages; i++) {
1685 page_virtual = kmap_atomic(pages[i]);
1686 clflush_cache_range(page_virtual, PAGE_SIZE);
1687 kunmap_atomic(page_virtual);
1691 static void __unregister_enc_region_locked(struct kvm *kvm,
1692 struct enc_region *region)
1695 * The guest may change the memory encryption attribute from C=0 -> C=1
1696 * or vice versa for this memory range. Lets make sure caches are
1697 * flushed to ensure that guest data gets written into memory with
1700 sev_clflush_pages(region->pages, region->npages);
1702 sev_unpin_memory(kvm, region->pages, region->npages);
1703 list_del(®ion->list);
1707 static void sev_vm_destroy(struct kvm *kvm)
1709 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1710 struct list_head *head = &sev->regions_list;
1711 struct list_head *pos, *q;
1713 if (!sev_guest(kvm))
1716 mutex_lock(&kvm->lock);
1719 * if userspace was terminated before unregistering the memory regions
1720 * then lets unpin all the registered memory.
1722 if (!list_empty(head)) {
1723 list_for_each_safe(pos, q, head) {
1724 __unregister_enc_region_locked(kvm,
1725 list_entry(pos, struct enc_region, list));
1729 mutex_unlock(&kvm->lock);
1731 sev_unbind_asid(kvm, sev->handle);
1735 static void avic_vm_destroy(struct kvm *kvm)
1737 unsigned long flags;
1738 struct kvm_arch *vm_data = &kvm->arch;
1743 if (vm_data->avic_logical_id_table_page)
1744 __free_page(vm_data->avic_logical_id_table_page);
1745 if (vm_data->avic_physical_id_table_page)
1746 __free_page(vm_data->avic_physical_id_table_page);
1748 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1749 hash_del(&vm_data->hnode);
1750 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1753 static void svm_vm_destroy(struct kvm *kvm)
1755 avic_vm_destroy(kvm);
1756 sev_vm_destroy(kvm);
1759 static int avic_vm_init(struct kvm *kvm)
1761 unsigned long flags;
1763 struct kvm_arch *vm_data = &kvm->arch;
1764 struct page *p_page;
1765 struct page *l_page;
1766 struct kvm_arch *ka;
1772 /* Allocating physical APIC ID table (4KB) */
1773 p_page = alloc_page(GFP_KERNEL);
1777 vm_data->avic_physical_id_table_page = p_page;
1778 clear_page(page_address(p_page));
1780 /* Allocating logical APIC ID table (4KB) */
1781 l_page = alloc_page(GFP_KERNEL);
1785 vm_data->avic_logical_id_table_page = l_page;
1786 clear_page(page_address(l_page));
1788 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1790 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1791 if (vm_id == 0) { /* id is 1-based, zero is not okay */
1792 next_vm_id_wrapped = 1;
1795 /* Is it still in use? Only possible if wrapped at least once */
1796 if (next_vm_id_wrapped) {
1797 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1798 struct kvm *k2 = container_of(ka, struct kvm, arch);
1799 struct kvm_arch *vd2 = &k2->arch;
1800 if (vd2->avic_vm_id == vm_id)
1804 vm_data->avic_vm_id = vm_id;
1805 hash_add(svm_vm_data_hash, &vm_data->hnode, vm_data->avic_vm_id);
1806 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1811 avic_vm_destroy(kvm);
1816 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1819 unsigned long flags;
1820 struct amd_svm_iommu_ir *ir;
1821 struct vcpu_svm *svm = to_svm(vcpu);
1823 if (!kvm_arch_has_assigned_device(vcpu->kvm))
1827 * Here, we go through the per-vcpu ir_list to update all existing
1828 * interrupt remapping table entry targeting this vcpu.
1830 spin_lock_irqsave(&svm->ir_list_lock, flags);
1832 if (list_empty(&svm->ir_list))
1835 list_for_each_entry(ir, &svm->ir_list, node) {
1836 ret = amd_iommu_update_ga(cpu, r, ir->data);
1841 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1845 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1848 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
1849 int h_physical_id = kvm_cpu_get_apicid(cpu);
1850 struct vcpu_svm *svm = to_svm(vcpu);
1852 if (!kvm_vcpu_apicv_active(vcpu))
1855 if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
1858 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1859 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1861 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1862 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1864 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1865 if (svm->avic_is_running)
1866 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1868 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1869 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
1870 svm->avic_is_running);
1873 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
1876 struct vcpu_svm *svm = to_svm(vcpu);
1878 if (!kvm_vcpu_apicv_active(vcpu))
1881 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1882 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
1883 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1885 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1886 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1890 * This function is called during VCPU halt/unhalt.
1892 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
1894 struct vcpu_svm *svm = to_svm(vcpu);
1896 svm->avic_is_running = is_run;
1898 avic_vcpu_load(vcpu, vcpu->cpu);
1900 avic_vcpu_put(vcpu);
1903 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1905 struct vcpu_svm *svm = to_svm(vcpu);
1912 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1913 MSR_IA32_APICBASE_ENABLE;
1914 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1915 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1919 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
1920 kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1922 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1923 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1926 static int avic_init_vcpu(struct vcpu_svm *svm)
1930 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1933 ret = avic_init_backing_page(&svm->vcpu);
1937 INIT_LIST_HEAD(&svm->ir_list);
1938 spin_lock_init(&svm->ir_list_lock);
1943 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1945 struct vcpu_svm *svm;
1947 struct page *msrpm_pages;
1948 struct page *hsave_page;
1949 struct page *nested_msrpm_pages;
1952 svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1958 err = kvm_vcpu_init(&svm->vcpu, kvm, id);
1963 page = alloc_page(GFP_KERNEL);
1967 msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1971 nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1972 if (!nested_msrpm_pages)
1975 hsave_page = alloc_page(GFP_KERNEL);
1979 err = avic_init_vcpu(svm);
1983 /* We initialize this flag to true to make sure that the is_running
1984 * bit would be set the first time the vcpu is loaded.
1986 svm->avic_is_running = true;
1988 svm->nested.hsave = page_address(hsave_page);
1990 svm->msrpm = page_address(msrpm_pages);
1991 svm_vcpu_init_msrpm(svm->msrpm);
1993 svm->nested.msrpm = page_address(nested_msrpm_pages);
1994 svm_vcpu_init_msrpm(svm->nested.msrpm);
1996 svm->vmcb = page_address(page);
1997 clear_page(svm->vmcb);
1998 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
1999 svm->asid_generation = 0;
2002 svm_init_osvw(&svm->vcpu);
2007 __free_page(hsave_page);
2009 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2011 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2015 kvm_vcpu_uninit(&svm->vcpu);
2017 kmem_cache_free(kvm_vcpu_cache, svm);
2019 return ERR_PTR(err);
2022 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2024 struct vcpu_svm *svm = to_svm(vcpu);
2026 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2027 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2028 __free_page(virt_to_page(svm->nested.hsave));
2029 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2030 kvm_vcpu_uninit(vcpu);
2031 kmem_cache_free(kvm_vcpu_cache, svm);
2033 * The vmcb page can be recycled, causing a false negative in
2034 * svm_vcpu_load(). So do a full IBPB now.
2036 indirect_branch_prediction_barrier();
2039 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2041 struct vcpu_svm *svm = to_svm(vcpu);
2042 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2045 if (unlikely(cpu != vcpu->cpu)) {
2046 svm->asid_generation = 0;
2047 mark_all_dirty(svm->vmcb);
2050 #ifdef CONFIG_X86_64
2051 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2053 savesegment(fs, svm->host.fs);
2054 savesegment(gs, svm->host.gs);
2055 svm->host.ldt = kvm_read_ldt();
2057 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2058 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2060 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2061 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2062 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2063 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2064 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2067 /* This assumes that the kernel never uses MSR_TSC_AUX */
2068 if (static_cpu_has(X86_FEATURE_RDTSCP))
2069 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2071 if (sd->current_vmcb != svm->vmcb) {
2072 sd->current_vmcb = svm->vmcb;
2073 indirect_branch_prediction_barrier();
2075 avic_vcpu_load(vcpu, cpu);
2078 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2080 struct vcpu_svm *svm = to_svm(vcpu);
2083 avic_vcpu_put(vcpu);
2085 ++vcpu->stat.host_state_reload;
2086 kvm_load_ldt(svm->host.ldt);
2087 #ifdef CONFIG_X86_64
2088 loadsegment(fs, svm->host.fs);
2089 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2090 load_gs_index(svm->host.gs);
2092 #ifdef CONFIG_X86_32_LAZY_GS
2093 loadsegment(gs, svm->host.gs);
2096 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2097 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2100 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2102 avic_set_running(vcpu, false);
2105 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2107 avic_set_running(vcpu, true);
2110 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2112 struct vcpu_svm *svm = to_svm(vcpu);
2113 unsigned long rflags = svm->vmcb->save.rflags;
2115 if (svm->nmi_singlestep) {
2116 /* Hide our flags if they were not set by the guest */
2117 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2118 rflags &= ~X86_EFLAGS_TF;
2119 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2120 rflags &= ~X86_EFLAGS_RF;
2125 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2127 if (to_svm(vcpu)->nmi_singlestep)
2128 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2131 * Any change of EFLAGS.VM is accompanied by a reload of SS
2132 * (caused by either a task switch or an inter-privilege IRET),
2133 * so we do not need to update the CPL here.
2135 to_svm(vcpu)->vmcb->save.rflags = rflags;
2138 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2141 case VCPU_EXREG_PDPTR:
2142 BUG_ON(!npt_enabled);
2143 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2150 static void svm_set_vintr(struct vcpu_svm *svm)
2152 set_intercept(svm, INTERCEPT_VINTR);
2155 static void svm_clear_vintr(struct vcpu_svm *svm)
2157 clr_intercept(svm, INTERCEPT_VINTR);
2160 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2162 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2165 case VCPU_SREG_CS: return &save->cs;
2166 case VCPU_SREG_DS: return &save->ds;
2167 case VCPU_SREG_ES: return &save->es;
2168 case VCPU_SREG_FS: return &save->fs;
2169 case VCPU_SREG_GS: return &save->gs;
2170 case VCPU_SREG_SS: return &save->ss;
2171 case VCPU_SREG_TR: return &save->tr;
2172 case VCPU_SREG_LDTR: return &save->ldtr;
2178 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2180 struct vmcb_seg *s = svm_seg(vcpu, seg);
2185 static void svm_get_segment(struct kvm_vcpu *vcpu,
2186 struct kvm_segment *var, int seg)
2188 struct vmcb_seg *s = svm_seg(vcpu, seg);
2190 var->base = s->base;
2191 var->limit = s->limit;
2192 var->selector = s->selector;
2193 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2194 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2195 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2196 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2197 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2198 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2199 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2202 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2203 * However, the SVM spec states that the G bit is not observed by the
2204 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2205 * So let's synthesize a legal G bit for all segments, this helps
2206 * running KVM nested. It also helps cross-vendor migration, because
2207 * Intel's vmentry has a check on the 'G' bit.
2209 var->g = s->limit > 0xfffff;
2212 * AMD's VMCB does not have an explicit unusable field, so emulate it
2213 * for cross vendor migration purposes by "not present"
2215 var->unusable = !var->present;
2220 * Work around a bug where the busy flag in the tr selector
2230 * The accessed bit must always be set in the segment
2231 * descriptor cache, although it can be cleared in the
2232 * descriptor, the cached bit always remains at 1. Since
2233 * Intel has a check on this, set it here to support
2234 * cross-vendor migration.
2241 * On AMD CPUs sometimes the DB bit in the segment
2242 * descriptor is left as 1, although the whole segment has
2243 * been made unusable. Clear it here to pass an Intel VMX
2244 * entry check when cross vendor migrating.
2248 /* This is symmetric with svm_set_segment() */
2249 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2254 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2256 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2261 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2263 struct vcpu_svm *svm = to_svm(vcpu);
2265 dt->size = svm->vmcb->save.idtr.limit;
2266 dt->address = svm->vmcb->save.idtr.base;
2269 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2271 struct vcpu_svm *svm = to_svm(vcpu);
2273 svm->vmcb->save.idtr.limit = dt->size;
2274 svm->vmcb->save.idtr.base = dt->address ;
2275 mark_dirty(svm->vmcb, VMCB_DT);
2278 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2280 struct vcpu_svm *svm = to_svm(vcpu);
2282 dt->size = svm->vmcb->save.gdtr.limit;
2283 dt->address = svm->vmcb->save.gdtr.base;
2286 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2288 struct vcpu_svm *svm = to_svm(vcpu);
2290 svm->vmcb->save.gdtr.limit = dt->size;
2291 svm->vmcb->save.gdtr.base = dt->address ;
2292 mark_dirty(svm->vmcb, VMCB_DT);
2295 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2299 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2303 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2307 static void update_cr0_intercept(struct vcpu_svm *svm)
2309 ulong gcr0 = svm->vcpu.arch.cr0;
2310 u64 *hcr0 = &svm->vmcb->save.cr0;
2312 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2313 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2315 mark_dirty(svm->vmcb, VMCB_CR);
2317 if (gcr0 == *hcr0) {
2318 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2319 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2321 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2322 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2326 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2328 struct vcpu_svm *svm = to_svm(vcpu);
2330 #ifdef CONFIG_X86_64
2331 if (vcpu->arch.efer & EFER_LME) {
2332 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2333 vcpu->arch.efer |= EFER_LMA;
2334 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2337 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2338 vcpu->arch.efer &= ~EFER_LMA;
2339 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2343 vcpu->arch.cr0 = cr0;
2346 cr0 |= X86_CR0_PG | X86_CR0_WP;
2349 * re-enable caching here because the QEMU bios
2350 * does not do it - this results in some delay at
2353 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2354 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2355 svm->vmcb->save.cr0 = cr0;
2356 mark_dirty(svm->vmcb, VMCB_CR);
2357 update_cr0_intercept(svm);
2360 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2362 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2363 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2365 if (cr4 & X86_CR4_VMXE)
2368 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2369 svm_flush_tlb(vcpu, true);
2371 vcpu->arch.cr4 = cr4;
2374 cr4 |= host_cr4_mce;
2375 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2376 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2380 static void svm_set_segment(struct kvm_vcpu *vcpu,
2381 struct kvm_segment *var, int seg)
2383 struct vcpu_svm *svm = to_svm(vcpu);
2384 struct vmcb_seg *s = svm_seg(vcpu, seg);
2386 s->base = var->base;
2387 s->limit = var->limit;
2388 s->selector = var->selector;
2389 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2390 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2391 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2392 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2393 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2394 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2395 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2396 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2399 * This is always accurate, except if SYSRET returned to a segment
2400 * with SS.DPL != 3. Intel does not have this quirk, and always
2401 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2402 * would entail passing the CPL to userspace and back.
2404 if (seg == VCPU_SREG_SS)
2405 /* This is symmetric with svm_get_segment() */
2406 svm->vmcb->save.cpl = (var->dpl & 3);
2408 mark_dirty(svm->vmcb, VMCB_SEG);
2411 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2413 struct vcpu_svm *svm = to_svm(vcpu);
2415 clr_exception_intercept(svm, BP_VECTOR);
2417 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2418 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2419 set_exception_intercept(svm, BP_VECTOR);
2421 vcpu->guest_debug = 0;
2424 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2426 if (sd->next_asid > sd->max_asid) {
2427 ++sd->asid_generation;
2428 sd->next_asid = sd->min_asid;
2429 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2432 svm->asid_generation = sd->asid_generation;
2433 svm->vmcb->control.asid = sd->next_asid++;
2435 mark_dirty(svm->vmcb, VMCB_ASID);
2438 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2440 return to_svm(vcpu)->vmcb->save.dr6;
2443 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2445 struct vcpu_svm *svm = to_svm(vcpu);
2447 svm->vmcb->save.dr6 = value;
2448 mark_dirty(svm->vmcb, VMCB_DR);
2451 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2453 struct vcpu_svm *svm = to_svm(vcpu);
2455 get_debugreg(vcpu->arch.db[0], 0);
2456 get_debugreg(vcpu->arch.db[1], 1);
2457 get_debugreg(vcpu->arch.db[2], 2);
2458 get_debugreg(vcpu->arch.db[3], 3);
2459 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2460 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2462 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2463 set_dr_intercepts(svm);
2466 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2468 struct vcpu_svm *svm = to_svm(vcpu);
2470 svm->vmcb->save.dr7 = value;
2471 mark_dirty(svm->vmcb, VMCB_DR);
2474 static int pf_interception(struct vcpu_svm *svm)
2476 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2477 u64 error_code = svm->vmcb->control.exit_info_1;
2479 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2480 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2481 svm->vmcb->control.insn_bytes : NULL,
2482 svm->vmcb->control.insn_len);
2485 static int npf_interception(struct vcpu_svm *svm)
2487 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2488 u64 error_code = svm->vmcb->control.exit_info_1;
2490 trace_kvm_page_fault(fault_address, error_code);
2491 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2492 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2493 svm->vmcb->control.insn_bytes : NULL,
2494 svm->vmcb->control.insn_len);
2497 static int db_interception(struct vcpu_svm *svm)
2499 struct kvm_run *kvm_run = svm->vcpu.run;
2501 if (!(svm->vcpu.guest_debug &
2502 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2503 !svm->nmi_singlestep) {
2504 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2508 if (svm->nmi_singlestep) {
2509 disable_nmi_singlestep(svm);
2512 if (svm->vcpu.guest_debug &
2513 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2514 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2515 kvm_run->debug.arch.pc =
2516 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2517 kvm_run->debug.arch.exception = DB_VECTOR;
2524 static int bp_interception(struct vcpu_svm *svm)
2526 struct kvm_run *kvm_run = svm->vcpu.run;
2528 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2529 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2530 kvm_run->debug.arch.exception = BP_VECTOR;
2534 static int ud_interception(struct vcpu_svm *svm)
2538 er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
2539 if (er == EMULATE_USER_EXIT)
2541 if (er != EMULATE_DONE)
2542 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2546 static int ac_interception(struct vcpu_svm *svm)
2548 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2552 static bool is_erratum_383(void)
2557 if (!erratum_383_found)
2560 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2564 /* Bit 62 may or may not be set for this mce */
2565 value &= ~(1ULL << 62);
2567 if (value != 0xb600000000010015ULL)
2570 /* Clear MCi_STATUS registers */
2571 for (i = 0; i < 6; ++i)
2572 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2574 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2578 value &= ~(1ULL << 2);
2579 low = lower_32_bits(value);
2580 high = upper_32_bits(value);
2582 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2585 /* Flush tlb to evict multi-match entries */
2591 static void svm_handle_mce(struct vcpu_svm *svm)
2593 if (is_erratum_383()) {
2595 * Erratum 383 triggered. Guest state is corrupt so kill the
2598 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2600 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2606 * On an #MC intercept the MCE handler is not called automatically in
2607 * the host. So do it by hand here.
2611 /* not sure if we ever come back to this point */
2616 static int mc_interception(struct vcpu_svm *svm)
2621 static int shutdown_interception(struct vcpu_svm *svm)
2623 struct kvm_run *kvm_run = svm->vcpu.run;
2626 * VMCB is undefined after a SHUTDOWN intercept
2627 * so reinitialize it.
2629 clear_page(svm->vmcb);
2632 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2636 static int io_interception(struct vcpu_svm *svm)
2638 struct kvm_vcpu *vcpu = &svm->vcpu;
2639 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2640 int size, in, string, ret;
2643 ++svm->vcpu.stat.io_exits;
2644 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2645 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2647 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2649 port = io_info >> 16;
2650 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2651 svm->next_rip = svm->vmcb->control.exit_info_2;
2652 ret = kvm_skip_emulated_instruction(&svm->vcpu);
2655 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
2656 * KVM_EXIT_DEBUG here.
2659 return kvm_fast_pio_in(vcpu, size, port) && ret;
2661 return kvm_fast_pio_out(vcpu, size, port) && ret;
2664 static int nmi_interception(struct vcpu_svm *svm)
2669 static int intr_interception(struct vcpu_svm *svm)
2671 ++svm->vcpu.stat.irq_exits;
2675 static int nop_on_interception(struct vcpu_svm *svm)
2680 static int halt_interception(struct vcpu_svm *svm)
2682 svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2683 return kvm_emulate_halt(&svm->vcpu);
2686 static int vmmcall_interception(struct vcpu_svm *svm)
2688 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2689 return kvm_emulate_hypercall(&svm->vcpu);
2692 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2694 struct vcpu_svm *svm = to_svm(vcpu);
2696 return svm->nested.nested_cr3;
2699 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2701 struct vcpu_svm *svm = to_svm(vcpu);
2702 u64 cr3 = svm->nested.nested_cr3;
2706 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2707 offset_in_page(cr3) + index * 8, 8);
2713 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2716 struct vcpu_svm *svm = to_svm(vcpu);
2718 svm->vmcb->control.nested_cr3 = __sme_set(root);
2719 mark_dirty(svm->vmcb, VMCB_NPT);
2720 svm_flush_tlb(vcpu, true);
2723 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2724 struct x86_exception *fault)
2726 struct vcpu_svm *svm = to_svm(vcpu);
2728 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2730 * TODO: track the cause of the nested page fault, and
2731 * correctly fill in the high bits of exit_info_1.
2733 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2734 svm->vmcb->control.exit_code_hi = 0;
2735 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2736 svm->vmcb->control.exit_info_2 = fault->address;
2739 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2740 svm->vmcb->control.exit_info_1 |= fault->error_code;
2743 * The present bit is always zero for page structure faults on real
2746 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2747 svm->vmcb->control.exit_info_1 &= ~1;
2749 nested_svm_vmexit(svm);
2752 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2754 WARN_ON(mmu_is_nested(vcpu));
2755 kvm_init_shadow_mmu(vcpu);
2756 vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
2757 vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
2758 vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr;
2759 vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2760 vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2761 reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2762 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2765 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2767 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2770 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2772 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2773 !is_paging(&svm->vcpu)) {
2774 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2778 if (svm->vmcb->save.cpl) {
2779 kvm_inject_gp(&svm->vcpu, 0);
2786 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2787 bool has_error_code, u32 error_code)
2791 if (!is_guest_mode(&svm->vcpu))
2794 vmexit = nested_svm_intercept(svm);
2795 if (vmexit != NESTED_EXIT_DONE)
2798 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2799 svm->vmcb->control.exit_code_hi = 0;
2800 svm->vmcb->control.exit_info_1 = error_code;
2803 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2804 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2805 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2806 * written only when inject_pending_event runs (DR6 would written here
2807 * too). This should be conditional on a new capability---if the
2808 * capability is disabled, kvm_multiple_exception would write the
2809 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2811 if (svm->vcpu.arch.exception.nested_apf)
2812 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2814 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2816 svm->nested.exit_required = true;
2820 /* This function returns true if it is save to enable the irq window */
2821 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2823 if (!is_guest_mode(&svm->vcpu))
2826 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2829 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2833 * if vmexit was already requested (by intercepted exception
2834 * for instance) do not overwrite it with "external interrupt"
2837 if (svm->nested.exit_required)
2840 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
2841 svm->vmcb->control.exit_info_1 = 0;
2842 svm->vmcb->control.exit_info_2 = 0;
2844 if (svm->nested.intercept & 1ULL) {
2846 * The #vmexit can't be emulated here directly because this
2847 * code path runs with irqs and preemption disabled. A
2848 * #vmexit emulation might sleep. Only signal request for
2851 svm->nested.exit_required = true;
2852 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2859 /* This function returns true if it is save to enable the nmi window */
2860 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2862 if (!is_guest_mode(&svm->vcpu))
2865 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2868 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2869 svm->nested.exit_required = true;
2874 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2880 page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2881 if (is_error_page(page))
2889 kvm_inject_gp(&svm->vcpu, 0);
2894 static void nested_svm_unmap(struct page *page)
2897 kvm_release_page_dirty(page);
2900 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2902 unsigned port, size, iopm_len;
2907 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2908 return NESTED_EXIT_HOST;
2910 port = svm->vmcb->control.exit_info_1 >> 16;
2911 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2912 SVM_IOIO_SIZE_SHIFT;
2913 gpa = svm->nested.vmcb_iopm + (port / 8);
2914 start_bit = port % 8;
2915 iopm_len = (start_bit + size > 8) ? 2 : 1;
2916 mask = (0xf >> (4 - size)) << start_bit;
2919 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2920 return NESTED_EXIT_DONE;
2922 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2925 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2927 u32 offset, msr, value;
2930 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2931 return NESTED_EXIT_HOST;
2933 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2934 offset = svm_msrpm_offset(msr);
2935 write = svm->vmcb->control.exit_info_1 & 1;
2936 mask = 1 << ((2 * (msr & 0xf)) + write);
2938 if (offset == MSR_INVALID)
2939 return NESTED_EXIT_DONE;
2941 /* Offset is in 32 bit units but need in 8 bit units */
2944 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
2945 return NESTED_EXIT_DONE;
2947 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2950 /* DB exceptions for our internal use must not cause vmexit */
2951 static int nested_svm_intercept_db(struct vcpu_svm *svm)
2955 /* if we're not singlestepping, it's not ours */
2956 if (!svm->nmi_singlestep)
2957 return NESTED_EXIT_DONE;
2959 /* if it's not a singlestep exception, it's not ours */
2960 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
2961 return NESTED_EXIT_DONE;
2962 if (!(dr6 & DR6_BS))
2963 return NESTED_EXIT_DONE;
2965 /* if the guest is singlestepping, it should get the vmexit */
2966 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
2967 disable_nmi_singlestep(svm);
2968 return NESTED_EXIT_DONE;
2971 /* it's ours, the nested hypervisor must not see this one */
2972 return NESTED_EXIT_HOST;
2975 static int nested_svm_exit_special(struct vcpu_svm *svm)
2977 u32 exit_code = svm->vmcb->control.exit_code;
2979 switch (exit_code) {
2982 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
2983 return NESTED_EXIT_HOST;
2985 /* For now we are always handling NPFs when using them */
2987 return NESTED_EXIT_HOST;
2989 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
2990 /* When we're shadowing, trap PFs, but not async PF */
2991 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
2992 return NESTED_EXIT_HOST;
2998 return NESTED_EXIT_CONTINUE;
3002 * If this function returns true, this #vmexit was already handled
3004 static int nested_svm_intercept(struct vcpu_svm *svm)
3006 u32 exit_code = svm->vmcb->control.exit_code;
3007 int vmexit = NESTED_EXIT_HOST;
3009 switch (exit_code) {
3011 vmexit = nested_svm_exit_handled_msr(svm);
3014 vmexit = nested_svm_intercept_ioio(svm);
3016 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3017 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3018 if (svm->nested.intercept_cr & bit)
3019 vmexit = NESTED_EXIT_DONE;
3022 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3023 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3024 if (svm->nested.intercept_dr & bit)
3025 vmexit = NESTED_EXIT_DONE;
3028 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3029 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3030 if (svm->nested.intercept_exceptions & excp_bits) {
3031 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3032 vmexit = nested_svm_intercept_db(svm);
3034 vmexit = NESTED_EXIT_DONE;
3036 /* async page fault always cause vmexit */
3037 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3038 svm->vcpu.arch.exception.nested_apf != 0)
3039 vmexit = NESTED_EXIT_DONE;
3042 case SVM_EXIT_ERR: {
3043 vmexit = NESTED_EXIT_DONE;
3047 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3048 if (svm->nested.intercept & exit_bits)
3049 vmexit = NESTED_EXIT_DONE;
3056 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3060 vmexit = nested_svm_intercept(svm);
3062 if (vmexit == NESTED_EXIT_DONE)
3063 nested_svm_vmexit(svm);
3068 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3070 struct vmcb_control_area *dst = &dst_vmcb->control;
3071 struct vmcb_control_area *from = &from_vmcb->control;
3073 dst->intercept_cr = from->intercept_cr;
3074 dst->intercept_dr = from->intercept_dr;
3075 dst->intercept_exceptions = from->intercept_exceptions;
3076 dst->intercept = from->intercept;
3077 dst->iopm_base_pa = from->iopm_base_pa;
3078 dst->msrpm_base_pa = from->msrpm_base_pa;
3079 dst->tsc_offset = from->tsc_offset;
3080 dst->asid = from->asid;
3081 dst->tlb_ctl = from->tlb_ctl;
3082 dst->int_ctl = from->int_ctl;
3083 dst->int_vector = from->int_vector;
3084 dst->int_state = from->int_state;
3085 dst->exit_code = from->exit_code;
3086 dst->exit_code_hi = from->exit_code_hi;
3087 dst->exit_info_1 = from->exit_info_1;
3088 dst->exit_info_2 = from->exit_info_2;
3089 dst->exit_int_info = from->exit_int_info;
3090 dst->exit_int_info_err = from->exit_int_info_err;
3091 dst->nested_ctl = from->nested_ctl;
3092 dst->event_inj = from->event_inj;
3093 dst->event_inj_err = from->event_inj_err;
3094 dst->nested_cr3 = from->nested_cr3;
3095 dst->virt_ext = from->virt_ext;
3098 static int nested_svm_vmexit(struct vcpu_svm *svm)
3100 struct vmcb *nested_vmcb;
3101 struct vmcb *hsave = svm->nested.hsave;
3102 struct vmcb *vmcb = svm->vmcb;
3105 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3106 vmcb->control.exit_info_1,
3107 vmcb->control.exit_info_2,
3108 vmcb->control.exit_int_info,
3109 vmcb->control.exit_int_info_err,
3112 nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3116 /* Exit Guest-Mode */
3117 leave_guest_mode(&svm->vcpu);
3118 svm->nested.vmcb = 0;
3120 /* Give the current vmcb to the guest */
3123 nested_vmcb->save.es = vmcb->save.es;
3124 nested_vmcb->save.cs = vmcb->save.cs;
3125 nested_vmcb->save.ss = vmcb->save.ss;
3126 nested_vmcb->save.ds = vmcb->save.ds;
3127 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3128 nested_vmcb->save.idtr = vmcb->save.idtr;
3129 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3130 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3131 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3132 nested_vmcb->save.cr2 = vmcb->save.cr2;
3133 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3134 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3135 nested_vmcb->save.rip = vmcb->save.rip;
3136 nested_vmcb->save.rsp = vmcb->save.rsp;
3137 nested_vmcb->save.rax = vmcb->save.rax;
3138 nested_vmcb->save.dr7 = vmcb->save.dr7;
3139 nested_vmcb->save.dr6 = vmcb->save.dr6;
3140 nested_vmcb->save.cpl = vmcb->save.cpl;
3142 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3143 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3144 nested_vmcb->control.int_state = vmcb->control.int_state;
3145 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3146 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3147 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3148 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3149 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3150 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3152 if (svm->nrips_enabled)
3153 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3156 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3157 * to make sure that we do not lose injected events. So check event_inj
3158 * here and copy it to exit_int_info if it is valid.
3159 * Exit_int_info and event_inj can't be both valid because the case
3160 * below only happens on a VMRUN instruction intercept which has
3161 * no valid exit_int_info set.
3163 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3164 struct vmcb_control_area *nc = &nested_vmcb->control;
3166 nc->exit_int_info = vmcb->control.event_inj;
3167 nc->exit_int_info_err = vmcb->control.event_inj_err;
3170 nested_vmcb->control.tlb_ctl = 0;
3171 nested_vmcb->control.event_inj = 0;
3172 nested_vmcb->control.event_inj_err = 0;
3174 /* We always set V_INTR_MASKING and remember the old value in hflags */
3175 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3176 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3178 /* Restore the original control entries */
3179 copy_vmcb_control_area(vmcb, hsave);
3181 kvm_clear_exception_queue(&svm->vcpu);
3182 kvm_clear_interrupt_queue(&svm->vcpu);
3184 svm->nested.nested_cr3 = 0;
3186 /* Restore selected save entries */
3187 svm->vmcb->save.es = hsave->save.es;
3188 svm->vmcb->save.cs = hsave->save.cs;
3189 svm->vmcb->save.ss = hsave->save.ss;
3190 svm->vmcb->save.ds = hsave->save.ds;
3191 svm->vmcb->save.gdtr = hsave->save.gdtr;
3192 svm->vmcb->save.idtr = hsave->save.idtr;
3193 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3194 svm_set_efer(&svm->vcpu, hsave->save.efer);
3195 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3196 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3198 svm->vmcb->save.cr3 = hsave->save.cr3;
3199 svm->vcpu.arch.cr3 = hsave->save.cr3;
3201 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3203 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3204 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3205 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3206 svm->vmcb->save.dr7 = 0;
3207 svm->vmcb->save.cpl = 0;
3208 svm->vmcb->control.exit_int_info = 0;
3210 mark_all_dirty(svm->vmcb);
3212 nested_svm_unmap(page);
3214 nested_svm_uninit_mmu_context(&svm->vcpu);
3215 kvm_mmu_reset_context(&svm->vcpu);
3216 kvm_mmu_load(&svm->vcpu);
3221 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3224 * This function merges the msr permission bitmaps of kvm and the
3225 * nested vmcb. It is optimized in that it only merges the parts where
3226 * the kvm msr permission bitmap may contain zero bits
3230 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3233 for (i = 0; i < MSRPM_OFFSETS; i++) {
3237 if (msrpm_offsets[i] == 0xffffffff)
3240 p = msrpm_offsets[i];
3241 offset = svm->nested.vmcb_msrpm + (p * 4);
3243 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3246 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3249 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3254 static bool nested_vmcb_checks(struct vmcb *vmcb)
3256 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3259 if (vmcb->control.asid == 0)
3262 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3269 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3270 struct vmcb *nested_vmcb, struct page *page)
3272 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3273 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3275 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3277 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3278 kvm_mmu_unload(&svm->vcpu);
3279 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3280 nested_svm_init_mmu_context(&svm->vcpu);
3283 /* Load the nested guest state */
3284 svm->vmcb->save.es = nested_vmcb->save.es;
3285 svm->vmcb->save.cs = nested_vmcb->save.cs;
3286 svm->vmcb->save.ss = nested_vmcb->save.ss;
3287 svm->vmcb->save.ds = nested_vmcb->save.ds;
3288 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3289 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3290 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3291 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3292 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3293 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3295 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3296 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3298 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3300 /* Guest paging mode is active - reset mmu */
3301 kvm_mmu_reset_context(&svm->vcpu);
3303 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3304 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3305 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3306 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3308 /* In case we don't even reach vcpu_run, the fields are not updated */
3309 svm->vmcb->save.rax = nested_vmcb->save.rax;
3310 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3311 svm->vmcb->save.rip = nested_vmcb->save.rip;
3312 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3313 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3314 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3316 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3317 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3319 /* cache intercepts */
3320 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3321 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3322 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3323 svm->nested.intercept = nested_vmcb->control.intercept;
3325 svm_flush_tlb(&svm->vcpu, true);
3326 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3327 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3328 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3330 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3332 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3333 /* We only want the cr8 intercept bits of the guest */
3334 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3335 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3338 /* We don't want to see VMMCALLs from a nested guest */
3339 clr_intercept(svm, INTERCEPT_VMMCALL);
3341 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3342 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3343 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3344 svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
3345 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3346 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3348 nested_svm_unmap(page);
3350 /* Enter Guest-Mode */
3351 enter_guest_mode(&svm->vcpu);
3354 * Merge guest and host intercepts - must be called with vcpu in
3355 * guest-mode to take affect here
3357 recalc_intercepts(svm);
3359 svm->nested.vmcb = vmcb_gpa;
3363 mark_all_dirty(svm->vmcb);
3366 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3368 struct vmcb *nested_vmcb;
3369 struct vmcb *hsave = svm->nested.hsave;
3370 struct vmcb *vmcb = svm->vmcb;
3374 vmcb_gpa = svm->vmcb->save.rax;
3376 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3380 if (!nested_vmcb_checks(nested_vmcb)) {
3381 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3382 nested_vmcb->control.exit_code_hi = 0;
3383 nested_vmcb->control.exit_info_1 = 0;
3384 nested_vmcb->control.exit_info_2 = 0;
3386 nested_svm_unmap(page);
3391 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3392 nested_vmcb->save.rip,
3393 nested_vmcb->control.int_ctl,
3394 nested_vmcb->control.event_inj,
3395 nested_vmcb->control.nested_ctl);
3397 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3398 nested_vmcb->control.intercept_cr >> 16,
3399 nested_vmcb->control.intercept_exceptions,
3400 nested_vmcb->control.intercept);
3402 /* Clear internal status */
3403 kvm_clear_exception_queue(&svm->vcpu);
3404 kvm_clear_interrupt_queue(&svm->vcpu);
3407 * Save the old vmcb, so we don't need to pick what we save, but can
3408 * restore everything when a VMEXIT occurs
3410 hsave->save.es = vmcb->save.es;
3411 hsave->save.cs = vmcb->save.cs;
3412 hsave->save.ss = vmcb->save.ss;
3413 hsave->save.ds = vmcb->save.ds;
3414 hsave->save.gdtr = vmcb->save.gdtr;
3415 hsave->save.idtr = vmcb->save.idtr;
3416 hsave->save.efer = svm->vcpu.arch.efer;
3417 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3418 hsave->save.cr4 = svm->vcpu.arch.cr4;
3419 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3420 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3421 hsave->save.rsp = vmcb->save.rsp;
3422 hsave->save.rax = vmcb->save.rax;
3424 hsave->save.cr3 = vmcb->save.cr3;
3426 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3428 copy_vmcb_control_area(hsave, vmcb);
3430 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3435 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3437 to_vmcb->save.fs = from_vmcb->save.fs;
3438 to_vmcb->save.gs = from_vmcb->save.gs;
3439 to_vmcb->save.tr = from_vmcb->save.tr;
3440 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3441 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3442 to_vmcb->save.star = from_vmcb->save.star;
3443 to_vmcb->save.lstar = from_vmcb->save.lstar;
3444 to_vmcb->save.cstar = from_vmcb->save.cstar;
3445 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3446 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3447 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3448 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3451 static int vmload_interception(struct vcpu_svm *svm)
3453 struct vmcb *nested_vmcb;
3457 if (nested_svm_check_permissions(svm))
3460 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3464 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3465 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3467 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3468 nested_svm_unmap(page);
3473 static int vmsave_interception(struct vcpu_svm *svm)
3475 struct vmcb *nested_vmcb;
3479 if (nested_svm_check_permissions(svm))
3482 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3486 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3487 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3489 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3490 nested_svm_unmap(page);
3495 static int vmrun_interception(struct vcpu_svm *svm)
3497 if (nested_svm_check_permissions(svm))
3500 /* Save rip after vmrun instruction */
3501 kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3503 if (!nested_svm_vmrun(svm))
3506 if (!nested_svm_vmrun_msrpm(svm))
3513 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3514 svm->vmcb->control.exit_code_hi = 0;
3515 svm->vmcb->control.exit_info_1 = 0;
3516 svm->vmcb->control.exit_info_2 = 0;
3518 nested_svm_vmexit(svm);
3523 static int stgi_interception(struct vcpu_svm *svm)
3527 if (nested_svm_check_permissions(svm))
3531 * If VGIF is enabled, the STGI intercept is only added to
3532 * detect the opening of the SMI/NMI window; remove it now.
3534 if (vgif_enabled(svm))
3535 clr_intercept(svm, INTERCEPT_STGI);
3537 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3538 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3539 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3546 static int clgi_interception(struct vcpu_svm *svm)
3550 if (nested_svm_check_permissions(svm))
3553 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3554 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3558 /* After a CLGI no interrupts should come */
3559 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3560 svm_clear_vintr(svm);
3561 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3562 mark_dirty(svm->vmcb, VMCB_INTR);
3568 static int invlpga_interception(struct vcpu_svm *svm)
3570 struct kvm_vcpu *vcpu = &svm->vcpu;
3572 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3573 kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3575 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3576 kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3578 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3579 return kvm_skip_emulated_instruction(&svm->vcpu);
3582 static int skinit_interception(struct vcpu_svm *svm)
3584 trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3586 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3590 static int wbinvd_interception(struct vcpu_svm *svm)
3592 return kvm_emulate_wbinvd(&svm->vcpu);
3595 static int xsetbv_interception(struct vcpu_svm *svm)
3597 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3598 u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3600 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3601 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3602 return kvm_skip_emulated_instruction(&svm->vcpu);
3608 static int task_switch_interception(struct vcpu_svm *svm)
3612 int int_type = svm->vmcb->control.exit_int_info &
3613 SVM_EXITINTINFO_TYPE_MASK;
3614 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3616 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3618 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3619 bool has_error_code = false;
3622 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3624 if (svm->vmcb->control.exit_info_2 &
3625 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3626 reason = TASK_SWITCH_IRET;
3627 else if (svm->vmcb->control.exit_info_2 &
3628 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3629 reason = TASK_SWITCH_JMP;
3631 reason = TASK_SWITCH_GATE;
3633 reason = TASK_SWITCH_CALL;
3635 if (reason == TASK_SWITCH_GATE) {
3637 case SVM_EXITINTINFO_TYPE_NMI:
3638 svm->vcpu.arch.nmi_injected = false;
3640 case SVM_EXITINTINFO_TYPE_EXEPT:
3641 if (svm->vmcb->control.exit_info_2 &
3642 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3643 has_error_code = true;
3645 (u32)svm->vmcb->control.exit_info_2;
3647 kvm_clear_exception_queue(&svm->vcpu);
3649 case SVM_EXITINTINFO_TYPE_INTR:
3650 kvm_clear_interrupt_queue(&svm->vcpu);
3657 if (reason != TASK_SWITCH_GATE ||
3658 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3659 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3660 (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3661 skip_emulated_instruction(&svm->vcpu);
3663 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3666 if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3667 has_error_code, error_code) == EMULATE_FAIL) {
3668 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3669 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3670 svm->vcpu.run->internal.ndata = 0;
3676 static int cpuid_interception(struct vcpu_svm *svm)
3678 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3679 return kvm_emulate_cpuid(&svm->vcpu);
3682 static int iret_interception(struct vcpu_svm *svm)
3684 ++svm->vcpu.stat.nmi_window_exits;
3685 clr_intercept(svm, INTERCEPT_IRET);
3686 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3687 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3688 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3692 static int invlpg_interception(struct vcpu_svm *svm)
3694 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3695 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3697 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3698 return kvm_skip_emulated_instruction(&svm->vcpu);
3701 static int emulate_on_interception(struct vcpu_svm *svm)
3703 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3706 static int rsm_interception(struct vcpu_svm *svm)
3708 return x86_emulate_instruction(&svm->vcpu, 0, 0,
3709 rsm_ins_bytes, 2) == EMULATE_DONE;
3712 static int rdpmc_interception(struct vcpu_svm *svm)
3716 if (!static_cpu_has(X86_FEATURE_NRIPS))
3717 return emulate_on_interception(svm);
3719 err = kvm_rdpmc(&svm->vcpu);
3720 return kvm_complete_insn_gp(&svm->vcpu, err);
3723 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3726 unsigned long cr0 = svm->vcpu.arch.cr0;
3730 intercept = svm->nested.intercept;
3732 if (!is_guest_mode(&svm->vcpu) ||
3733 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3736 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3737 val &= ~SVM_CR0_SELECTIVE_MASK;
3740 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3741 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3747 #define CR_VALID (1ULL << 63)
3749 static int cr_interception(struct vcpu_svm *svm)
3755 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3756 return emulate_on_interception(svm);
3758 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3759 return emulate_on_interception(svm);
3761 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3762 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3763 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3765 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3768 if (cr >= 16) { /* mov to cr */
3770 val = kvm_register_read(&svm->vcpu, reg);
3773 if (!check_selective_cr0_intercepted(svm, val))
3774 err = kvm_set_cr0(&svm->vcpu, val);
3780 err = kvm_set_cr3(&svm->vcpu, val);
3783 err = kvm_set_cr4(&svm->vcpu, val);
3786 err = kvm_set_cr8(&svm->vcpu, val);
3789 WARN(1, "unhandled write to CR%d", cr);
3790 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3793 } else { /* mov from cr */
3796 val = kvm_read_cr0(&svm->vcpu);
3799 val = svm->vcpu.arch.cr2;
3802 val = kvm_read_cr3(&svm->vcpu);
3805 val = kvm_read_cr4(&svm->vcpu);
3808 val = kvm_get_cr8(&svm->vcpu);
3811 WARN(1, "unhandled read from CR%d", cr);
3812 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3815 kvm_register_write(&svm->vcpu, reg, val);
3817 return kvm_complete_insn_gp(&svm->vcpu, err);
3820 static int dr_interception(struct vcpu_svm *svm)
3825 if (svm->vcpu.guest_debug == 0) {
3827 * No more DR vmexits; force a reload of the debug registers
3828 * and reenter on this instruction. The next vmexit will
3829 * retrieve the full state of the debug registers.
3831 clr_dr_intercepts(svm);
3832 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
3836 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
3837 return emulate_on_interception(svm);
3839 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3840 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3842 if (dr >= 16) { /* mov to DRn */
3843 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3845 val = kvm_register_read(&svm->vcpu, reg);
3846 kvm_set_dr(&svm->vcpu, dr - 16, val);
3848 if (!kvm_require_dr(&svm->vcpu, dr))
3850 kvm_get_dr(&svm->vcpu, dr, &val);
3851 kvm_register_write(&svm->vcpu, reg, val);
3854 return kvm_skip_emulated_instruction(&svm->vcpu);
3857 static int cr8_write_interception(struct vcpu_svm *svm)
3859 struct kvm_run *kvm_run = svm->vcpu.run;
3862 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3863 /* instruction emulation calls kvm_set_cr8() */
3864 r = cr_interception(svm);
3865 if (lapic_in_kernel(&svm->vcpu))
3867 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3869 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3873 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3875 struct vcpu_svm *svm = to_svm(vcpu);
3877 switch (msr_info->index) {
3878 case MSR_IA32_TSC: {
3879 msr_info->data = svm->vmcb->control.tsc_offset +
3880 kvm_scale_tsc(vcpu, rdtsc());
3885 msr_info->data = svm->vmcb->save.star;
3887 #ifdef CONFIG_X86_64
3889 msr_info->data = svm->vmcb->save.lstar;
3892 msr_info->data = svm->vmcb->save.cstar;
3894 case MSR_KERNEL_GS_BASE:
3895 msr_info->data = svm->vmcb->save.kernel_gs_base;
3897 case MSR_SYSCALL_MASK:
3898 msr_info->data = svm->vmcb->save.sfmask;
3901 case MSR_IA32_SYSENTER_CS:
3902 msr_info->data = svm->vmcb->save.sysenter_cs;
3904 case MSR_IA32_SYSENTER_EIP:
3905 msr_info->data = svm->sysenter_eip;
3907 case MSR_IA32_SYSENTER_ESP:
3908 msr_info->data = svm->sysenter_esp;
3911 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3913 msr_info->data = svm->tsc_aux;
3916 * Nobody will change the following 5 values in the VMCB so we can
3917 * safely return them on rdmsr. They will always be 0 until LBRV is
3920 case MSR_IA32_DEBUGCTLMSR:
3921 msr_info->data = svm->vmcb->save.dbgctl;
3923 case MSR_IA32_LASTBRANCHFROMIP:
3924 msr_info->data = svm->vmcb->save.br_from;
3926 case MSR_IA32_LASTBRANCHTOIP:
3927 msr_info->data = svm->vmcb->save.br_to;
3929 case MSR_IA32_LASTINTFROMIP:
3930 msr_info->data = svm->vmcb->save.last_excp_from;
3932 case MSR_IA32_LASTINTTOIP:
3933 msr_info->data = svm->vmcb->save.last_excp_to;
3935 case MSR_VM_HSAVE_PA:
3936 msr_info->data = svm->nested.hsave_msr;
3939 msr_info->data = svm->nested.vm_cr_msr;
3941 case MSR_IA32_SPEC_CTRL:
3942 if (!msr_info->host_initiated &&
3943 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
3946 msr_info->data = svm->spec_ctrl;
3948 case MSR_IA32_UCODE_REV:
3949 msr_info->data = 0x01000065;
3951 case MSR_F15H_IC_CFG: {
3955 family = guest_cpuid_family(vcpu);
3956 model = guest_cpuid_model(vcpu);
3958 if (family < 0 || model < 0)
3959 return kvm_get_msr_common(vcpu, msr_info);
3963 if (family == 0x15 &&
3964 (model >= 0x2 && model < 0x20))
3965 msr_info->data = 0x1E;
3969 return kvm_get_msr_common(vcpu, msr_info);
3974 static int rdmsr_interception(struct vcpu_svm *svm)
3976 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3977 struct msr_data msr_info;
3979 msr_info.index = ecx;
3980 msr_info.host_initiated = false;
3981 if (svm_get_msr(&svm->vcpu, &msr_info)) {
3982 trace_kvm_msr_read_ex(ecx);
3983 kvm_inject_gp(&svm->vcpu, 0);
3986 trace_kvm_msr_read(ecx, msr_info.data);
3988 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
3989 msr_info.data & 0xffffffff);
3990 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
3991 msr_info.data >> 32);
3992 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3993 return kvm_skip_emulated_instruction(&svm->vcpu);
3997 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
3999 struct vcpu_svm *svm = to_svm(vcpu);
4000 int svm_dis, chg_mask;
4002 if (data & ~SVM_VM_CR_VALID_MASK)
4005 chg_mask = SVM_VM_CR_VALID_MASK;
4007 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4008 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4010 svm->nested.vm_cr_msr &= ~chg_mask;
4011 svm->nested.vm_cr_msr |= (data & chg_mask);
4013 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4015 /* check for svm_disable while efer.svme is set */
4016 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4022 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4024 struct vcpu_svm *svm = to_svm(vcpu);
4026 u32 ecx = msr->index;
4027 u64 data = msr->data;
4029 case MSR_IA32_CR_PAT:
4030 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4032 vcpu->arch.pat = data;
4033 svm->vmcb->save.g_pat = data;
4034 mark_dirty(svm->vmcb, VMCB_NPT);
4037 kvm_write_tsc(vcpu, msr);
4039 case MSR_IA32_SPEC_CTRL:
4040 if (!msr->host_initiated &&
4041 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
4044 /* The STIBP bit doesn't fault even if it's not advertised */
4045 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
4048 svm->spec_ctrl = data;
4055 * When it's written (to non-zero) for the first time, pass
4059 * The handling of the MSR bitmap for L2 guests is done in
4060 * nested_svm_vmrun_msrpm.
4061 * We update the L1 MSR bit as well since it will end up
4062 * touching the MSR anyway now.
4064 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4066 case MSR_IA32_PRED_CMD:
4067 if (!msr->host_initiated &&
4068 !guest_cpuid_has(vcpu, X86_FEATURE_IBPB))
4071 if (data & ~PRED_CMD_IBPB)
4077 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4078 if (is_guest_mode(vcpu))
4080 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4083 svm->vmcb->save.star = data;
4085 #ifdef CONFIG_X86_64
4087 svm->vmcb->save.lstar = data;
4090 svm->vmcb->save.cstar = data;
4092 case MSR_KERNEL_GS_BASE:
4093 svm->vmcb->save.kernel_gs_base = data;
4095 case MSR_SYSCALL_MASK:
4096 svm->vmcb->save.sfmask = data;
4099 case MSR_IA32_SYSENTER_CS:
4100 svm->vmcb->save.sysenter_cs = data;
4102 case MSR_IA32_SYSENTER_EIP:
4103 svm->sysenter_eip = data;
4104 svm->vmcb->save.sysenter_eip = data;
4106 case MSR_IA32_SYSENTER_ESP:
4107 svm->sysenter_esp = data;
4108 svm->vmcb->save.sysenter_esp = data;
4111 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4115 * This is rare, so we update the MSR here instead of using
4116 * direct_access_msrs. Doing that would require a rdmsr in
4119 svm->tsc_aux = data;
4120 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4122 case MSR_IA32_DEBUGCTLMSR:
4123 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4124 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4128 if (data & DEBUGCTL_RESERVED_BITS)
4131 svm->vmcb->save.dbgctl = data;
4132 mark_dirty(svm->vmcb, VMCB_LBR);
4133 if (data & (1ULL<<0))
4134 svm_enable_lbrv(svm);
4136 svm_disable_lbrv(svm);
4138 case MSR_VM_HSAVE_PA:
4139 svm->nested.hsave_msr = data;
4142 return svm_set_vm_cr(vcpu, data);
4144 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4146 case MSR_IA32_APICBASE:
4147 if (kvm_vcpu_apicv_active(vcpu))
4148 avic_update_vapic_bar(to_svm(vcpu), data);
4149 /* Follow through */
4151 return kvm_set_msr_common(vcpu, msr);
4156 static int wrmsr_interception(struct vcpu_svm *svm)
4158 struct msr_data msr;
4159 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4160 u64 data = kvm_read_edx_eax(&svm->vcpu);
4164 msr.host_initiated = false;
4166 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4167 if (kvm_set_msr(&svm->vcpu, &msr)) {
4168 trace_kvm_msr_write_ex(ecx, data);
4169 kvm_inject_gp(&svm->vcpu, 0);
4172 trace_kvm_msr_write(ecx, data);
4173 return kvm_skip_emulated_instruction(&svm->vcpu);
4177 static int msr_interception(struct vcpu_svm *svm)
4179 if (svm->vmcb->control.exit_info_1)
4180 return wrmsr_interception(svm);
4182 return rdmsr_interception(svm);
4185 static int interrupt_window_interception(struct vcpu_svm *svm)
4187 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4188 svm_clear_vintr(svm);
4189 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4190 mark_dirty(svm->vmcb, VMCB_INTR);
4191 ++svm->vcpu.stat.irq_window_exits;
4195 static int pause_interception(struct vcpu_svm *svm)
4197 struct kvm_vcpu *vcpu = &svm->vcpu;
4198 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4200 kvm_vcpu_on_spin(vcpu, in_kernel);
4204 static int nop_interception(struct vcpu_svm *svm)
4206 return kvm_skip_emulated_instruction(&(svm->vcpu));
4209 static int monitor_interception(struct vcpu_svm *svm)
4211 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4212 return nop_interception(svm);
4215 static int mwait_interception(struct vcpu_svm *svm)
4217 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4218 return nop_interception(svm);
4221 enum avic_ipi_failure_cause {
4222 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4223 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4224 AVIC_IPI_FAILURE_INVALID_TARGET,
4225 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4228 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4230 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4231 u32 icrl = svm->vmcb->control.exit_info_1;
4232 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4233 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4234 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4236 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4239 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4241 * AVIC hardware handles the generation of
4242 * IPIs when the specified Message Type is Fixed
4243 * (also known as fixed delivery mode) and
4244 * the Trigger Mode is edge-triggered. The hardware
4245 * also supports self and broadcast delivery modes
4246 * specified via the Destination Shorthand(DSH)
4247 * field of the ICRL. Logical and physical APIC ID
4248 * formats are supported. All other IPI types cause
4249 * a #VMEXIT, which needs to emulated.
4251 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4252 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4254 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4256 struct kvm_vcpu *vcpu;
4257 struct kvm *kvm = svm->vcpu.kvm;
4258 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4261 * At this point, we expect that the AVIC HW has already
4262 * set the appropriate IRR bits on the valid target
4263 * vcpus. So, we just need to kick the appropriate vcpu.
4265 kvm_for_each_vcpu(i, vcpu, kvm) {
4266 bool m = kvm_apic_match_dest(vcpu, apic,
4267 icrl & KVM_APIC_SHORT_MASK,
4268 GET_APIC_DEST_FIELD(icrh),
4269 icrl & KVM_APIC_DEST_MASK);
4271 if (m && !avic_vcpu_is_running(vcpu))
4272 kvm_vcpu_wake_up(vcpu);
4276 case AVIC_IPI_FAILURE_INVALID_TARGET:
4278 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4279 WARN_ONCE(1, "Invalid backing page\n");
4282 pr_err("Unknown IPI interception\n");
4288 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4290 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4292 u32 *logical_apic_id_table;
4293 int dlid = GET_APIC_LOGICAL_ID(ldr);
4298 if (flat) { /* flat */
4299 index = ffs(dlid) - 1;
4302 } else { /* cluster */
4303 int cluster = (dlid & 0xf0) >> 4;
4304 int apic = ffs(dlid & 0x0f) - 1;
4306 if ((apic < 0) || (apic > 7) ||
4309 index = (cluster << 2) + apic;
4312 logical_apic_id_table = (u32 *) page_address(vm_data->avic_logical_id_table_page);
4314 return &logical_apic_id_table[index];
4317 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4321 u32 *entry, new_entry;
4323 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4324 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4328 new_entry = READ_ONCE(*entry);
4329 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4330 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4332 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4334 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4335 WRITE_ONCE(*entry, new_entry);
4340 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4343 struct vcpu_svm *svm = to_svm(vcpu);
4344 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4349 ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4350 if (ret && svm->ldr_reg) {
4351 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4359 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4362 struct vcpu_svm *svm = to_svm(vcpu);
4363 u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4364 u32 id = (apic_id_reg >> 24) & 0xff;
4366 if (vcpu->vcpu_id == id)
4369 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4370 new = avic_get_physical_id_entry(vcpu, id);
4374 /* We need to move physical_id_entry to new offset */
4377 to_svm(vcpu)->avic_physical_id_cache = new;
4380 * Also update the guest physical APIC ID in the logical
4381 * APIC ID table entry if already setup the LDR.
4384 avic_handle_ldr_update(vcpu);
4389 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4391 struct vcpu_svm *svm = to_svm(vcpu);
4392 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4393 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4394 u32 mod = (dfr >> 28) & 0xf;
4397 * We assume that all local APICs are using the same type.
4398 * If this changes, we need to flush the AVIC logical
4401 if (vm_data->ldr_mode == mod)
4404 clear_page(page_address(vm_data->avic_logical_id_table_page));
4405 vm_data->ldr_mode = mod;
4408 avic_handle_ldr_update(vcpu);
4412 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4414 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4415 u32 offset = svm->vmcb->control.exit_info_1 &
4416 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4420 if (avic_handle_apic_id_update(&svm->vcpu))
4424 if (avic_handle_ldr_update(&svm->vcpu))
4428 avic_handle_dfr_update(&svm->vcpu);
4434 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4439 static bool is_avic_unaccelerated_access_trap(u32 offset)
4468 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4471 u32 offset = svm->vmcb->control.exit_info_1 &
4472 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4473 u32 vector = svm->vmcb->control.exit_info_2 &
4474 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4475 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4476 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4477 bool trap = is_avic_unaccelerated_access_trap(offset);
4479 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4480 trap, write, vector);
4483 WARN_ONCE(!write, "svm: Handling trap read.\n");
4484 ret = avic_unaccel_trap_write(svm);
4486 /* Handling Fault */
4487 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4493 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4494 [SVM_EXIT_READ_CR0] = cr_interception,
4495 [SVM_EXIT_READ_CR3] = cr_interception,
4496 [SVM_EXIT_READ_CR4] = cr_interception,
4497 [SVM_EXIT_READ_CR8] = cr_interception,
4498 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4499 [SVM_EXIT_WRITE_CR0] = cr_interception,
4500 [SVM_EXIT_WRITE_CR3] = cr_interception,
4501 [SVM_EXIT_WRITE_CR4] = cr_interception,
4502 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4503 [SVM_EXIT_READ_DR0] = dr_interception,
4504 [SVM_EXIT_READ_DR1] = dr_interception,
4505 [SVM_EXIT_READ_DR2] = dr_interception,
4506 [SVM_EXIT_READ_DR3] = dr_interception,
4507 [SVM_EXIT_READ_DR4] = dr_interception,
4508 [SVM_EXIT_READ_DR5] = dr_interception,
4509 [SVM_EXIT_READ_DR6] = dr_interception,
4510 [SVM_EXIT_READ_DR7] = dr_interception,
4511 [SVM_EXIT_WRITE_DR0] = dr_interception,
4512 [SVM_EXIT_WRITE_DR1] = dr_interception,
4513 [SVM_EXIT_WRITE_DR2] = dr_interception,
4514 [SVM_EXIT_WRITE_DR3] = dr_interception,
4515 [SVM_EXIT_WRITE_DR4] = dr_interception,
4516 [SVM_EXIT_WRITE_DR5] = dr_interception,
4517 [SVM_EXIT_WRITE_DR6] = dr_interception,
4518 [SVM_EXIT_WRITE_DR7] = dr_interception,
4519 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4520 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4521 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4522 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4523 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4524 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4525 [SVM_EXIT_INTR] = intr_interception,
4526 [SVM_EXIT_NMI] = nmi_interception,
4527 [SVM_EXIT_SMI] = nop_on_interception,
4528 [SVM_EXIT_INIT] = nop_on_interception,
4529 [SVM_EXIT_VINTR] = interrupt_window_interception,
4530 [SVM_EXIT_RDPMC] = rdpmc_interception,
4531 [SVM_EXIT_CPUID] = cpuid_interception,
4532 [SVM_EXIT_IRET] = iret_interception,
4533 [SVM_EXIT_INVD] = emulate_on_interception,
4534 [SVM_EXIT_PAUSE] = pause_interception,
4535 [SVM_EXIT_HLT] = halt_interception,
4536 [SVM_EXIT_INVLPG] = invlpg_interception,
4537 [SVM_EXIT_INVLPGA] = invlpga_interception,
4538 [SVM_EXIT_IOIO] = io_interception,
4539 [SVM_EXIT_MSR] = msr_interception,
4540 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4541 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4542 [SVM_EXIT_VMRUN] = vmrun_interception,
4543 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4544 [SVM_EXIT_VMLOAD] = vmload_interception,
4545 [SVM_EXIT_VMSAVE] = vmsave_interception,
4546 [SVM_EXIT_STGI] = stgi_interception,
4547 [SVM_EXIT_CLGI] = clgi_interception,
4548 [SVM_EXIT_SKINIT] = skinit_interception,
4549 [SVM_EXIT_WBINVD] = wbinvd_interception,
4550 [SVM_EXIT_MONITOR] = monitor_interception,
4551 [SVM_EXIT_MWAIT] = mwait_interception,
4552 [SVM_EXIT_XSETBV] = xsetbv_interception,
4553 [SVM_EXIT_NPF] = npf_interception,
4554 [SVM_EXIT_RSM] = rsm_interception,
4555 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4556 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4559 static void dump_vmcb(struct kvm_vcpu *vcpu)
4561 struct vcpu_svm *svm = to_svm(vcpu);
4562 struct vmcb_control_area *control = &svm->vmcb->control;
4563 struct vmcb_save_area *save = &svm->vmcb->save;
4565 pr_err("VMCB Control Area:\n");
4566 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4567 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4568 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4569 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4570 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4571 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4572 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4573 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4574 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4575 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4576 pr_err("%-20s%d\n", "asid:", control->asid);
4577 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4578 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4579 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4580 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4581 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4582 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4583 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4584 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4585 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4586 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4587 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4588 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4589 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4590 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4591 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4592 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4593 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4594 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4595 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4596 pr_err("VMCB State Save Area:\n");
4597 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4599 save->es.selector, save->es.attrib,
4600 save->es.limit, save->es.base);
4601 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4603 save->cs.selector, save->cs.attrib,
4604 save->cs.limit, save->cs.base);
4605 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4607 save->ss.selector, save->ss.attrib,
4608 save->ss.limit, save->ss.base);
4609 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4611 save->ds.selector, save->ds.attrib,
4612 save->ds.limit, save->ds.base);
4613 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4615 save->fs.selector, save->fs.attrib,
4616 save->fs.limit, save->fs.base);
4617 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4619 save->gs.selector, save->gs.attrib,
4620 save->gs.limit, save->gs.base);
4621 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4623 save->gdtr.selector, save->gdtr.attrib,
4624 save->gdtr.limit, save->gdtr.base);
4625 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4627 save->ldtr.selector, save->ldtr.attrib,
4628 save->ldtr.limit, save->ldtr.base);
4629 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4631 save->idtr.selector, save->idtr.attrib,
4632 save->idtr.limit, save->idtr.base);
4633 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4635 save->tr.selector, save->tr.attrib,
4636 save->tr.limit, save->tr.base);
4637 pr_err("cpl: %d efer: %016llx\n",
4638 save->cpl, save->efer);
4639 pr_err("%-15s %016llx %-13s %016llx\n",
4640 "cr0:", save->cr0, "cr2:", save->cr2);
4641 pr_err("%-15s %016llx %-13s %016llx\n",
4642 "cr3:", save->cr3, "cr4:", save->cr4);
4643 pr_err("%-15s %016llx %-13s %016llx\n",
4644 "dr6:", save->dr6, "dr7:", save->dr7);
4645 pr_err("%-15s %016llx %-13s %016llx\n",
4646 "rip:", save->rip, "rflags:", save->rflags);
4647 pr_err("%-15s %016llx %-13s %016llx\n",
4648 "rsp:", save->rsp, "rax:", save->rax);
4649 pr_err("%-15s %016llx %-13s %016llx\n",
4650 "star:", save->star, "lstar:", save->lstar);
4651 pr_err("%-15s %016llx %-13s %016llx\n",
4652 "cstar:", save->cstar, "sfmask:", save->sfmask);
4653 pr_err("%-15s %016llx %-13s %016llx\n",
4654 "kernel_gs_base:", save->kernel_gs_base,
4655 "sysenter_cs:", save->sysenter_cs);
4656 pr_err("%-15s %016llx %-13s %016llx\n",
4657 "sysenter_esp:", save->sysenter_esp,
4658 "sysenter_eip:", save->sysenter_eip);
4659 pr_err("%-15s %016llx %-13s %016llx\n",
4660 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4661 pr_err("%-15s %016llx %-13s %016llx\n",
4662 "br_from:", save->br_from, "br_to:", save->br_to);
4663 pr_err("%-15s %016llx %-13s %016llx\n",
4664 "excp_from:", save->last_excp_from,
4665 "excp_to:", save->last_excp_to);
4668 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4670 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4672 *info1 = control->exit_info_1;
4673 *info2 = control->exit_info_2;
4676 static int handle_exit(struct kvm_vcpu *vcpu)
4678 struct vcpu_svm *svm = to_svm(vcpu);
4679 struct kvm_run *kvm_run = vcpu->run;
4680 u32 exit_code = svm->vmcb->control.exit_code;
4682 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4684 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4685 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4687 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4689 if (unlikely(svm->nested.exit_required)) {
4690 nested_svm_vmexit(svm);
4691 svm->nested.exit_required = false;
4696 if (is_guest_mode(vcpu)) {
4699 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4700 svm->vmcb->control.exit_info_1,
4701 svm->vmcb->control.exit_info_2,
4702 svm->vmcb->control.exit_int_info,
4703 svm->vmcb->control.exit_int_info_err,
4706 vmexit = nested_svm_exit_special(svm);
4708 if (vmexit == NESTED_EXIT_CONTINUE)
4709 vmexit = nested_svm_exit_handled(svm);
4711 if (vmexit == NESTED_EXIT_DONE)
4715 svm_complete_interrupts(svm);
4717 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4718 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4719 kvm_run->fail_entry.hardware_entry_failure_reason
4720 = svm->vmcb->control.exit_code;
4721 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4726 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4727 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4728 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4729 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4730 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4732 __func__, svm->vmcb->control.exit_int_info,
4735 if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4736 || !svm_exit_handlers[exit_code]) {
4737 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4738 kvm_queue_exception(vcpu, UD_VECTOR);
4742 return svm_exit_handlers[exit_code](svm);
4745 static void reload_tss(struct kvm_vcpu *vcpu)
4747 int cpu = raw_smp_processor_id();
4749 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4750 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4754 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
4756 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4757 int asid = sev_get_asid(svm->vcpu.kvm);
4759 /* Assign the asid allocated with this SEV guest */
4760 svm->vmcb->control.asid = asid;
4765 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
4766 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
4768 if (sd->sev_vmcbs[asid] == svm->vmcb &&
4769 svm->last_cpu == cpu)
4772 svm->last_cpu = cpu;
4773 sd->sev_vmcbs[asid] = svm->vmcb;
4774 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4775 mark_dirty(svm->vmcb, VMCB_ASID);
4778 static void pre_svm_run(struct vcpu_svm *svm)
4780 int cpu = raw_smp_processor_id();
4782 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4784 if (sev_guest(svm->vcpu.kvm))
4785 return pre_sev_run(svm, cpu);
4787 /* FIXME: handle wraparound of asid_generation */
4788 if (svm->asid_generation != sd->asid_generation)
4792 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
4794 struct vcpu_svm *svm = to_svm(vcpu);
4796 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
4797 vcpu->arch.hflags |= HF_NMI_MASK;
4798 set_intercept(svm, INTERCEPT_IRET);
4799 ++vcpu->stat.nmi_injections;
4802 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
4804 struct vmcb_control_area *control;
4806 /* The following fields are ignored when AVIC is enabled */
4807 control = &svm->vmcb->control;
4808 control->int_vector = irq;
4809 control->int_ctl &= ~V_INTR_PRIO_MASK;
4810 control->int_ctl |= V_IRQ_MASK |
4811 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
4812 mark_dirty(svm->vmcb, VMCB_INTR);
4815 static void svm_set_irq(struct kvm_vcpu *vcpu)
4817 struct vcpu_svm *svm = to_svm(vcpu);
4819 BUG_ON(!(gif_set(svm)));
4821 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
4822 ++vcpu->stat.irq_injections;
4824 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
4825 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
4828 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
4830 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
4833 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4835 struct vcpu_svm *svm = to_svm(vcpu);
4837 if (svm_nested_virtualize_tpr(vcpu) ||
4838 kvm_vcpu_apicv_active(vcpu))
4841 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4847 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4850 static void svm_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
4855 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
4857 return avic && irqchip_split(vcpu->kvm);
4860 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
4864 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
4868 /* Note: Currently only used by Hyper-V. */
4869 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4871 struct vcpu_svm *svm = to_svm(vcpu);
4872 struct vmcb *vmcb = svm->vmcb;
4874 if (!kvm_vcpu_apicv_active(&svm->vcpu))
4877 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
4878 mark_dirty(vmcb, VMCB_INTR);
4881 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
4886 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
4888 kvm_lapic_set_irr(vec, vcpu->arch.apic);
4889 smp_mb__after_atomic();
4891 if (avic_vcpu_is_running(vcpu))
4892 wrmsrl(SVM_AVIC_DOORBELL,
4893 kvm_cpu_get_apicid(vcpu->cpu));
4895 kvm_vcpu_wake_up(vcpu);
4898 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4900 unsigned long flags;
4901 struct amd_svm_iommu_ir *cur;
4903 spin_lock_irqsave(&svm->ir_list_lock, flags);
4904 list_for_each_entry(cur, &svm->ir_list, node) {
4905 if (cur->data != pi->ir_data)
4907 list_del(&cur->node);
4911 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4914 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4917 unsigned long flags;
4918 struct amd_svm_iommu_ir *ir;
4921 * In some cases, the existing irte is updaed and re-set,
4922 * so we need to check here if it's already been * added
4925 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
4926 struct kvm *kvm = svm->vcpu.kvm;
4927 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
4928 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
4929 struct vcpu_svm *prev_svm;
4936 prev_svm = to_svm(prev_vcpu);
4937 svm_ir_list_del(prev_svm, pi);
4941 * Allocating new amd_iommu_pi_data, which will get
4942 * add to the per-vcpu ir_list.
4944 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
4949 ir->data = pi->ir_data;
4951 spin_lock_irqsave(&svm->ir_list_lock, flags);
4952 list_add(&ir->node, &svm->ir_list);
4953 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4960 * The HW cannot support posting multicast/broadcast
4961 * interrupts to a vCPU. So, we still use legacy interrupt
4962 * remapping for these kind of interrupts.
4964 * For lowest-priority interrupts, we only support
4965 * those with single CPU as the destination, e.g. user
4966 * configures the interrupts via /proc/irq or uses
4967 * irqbalance to make the interrupts single-CPU.
4970 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
4971 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
4973 struct kvm_lapic_irq irq;
4974 struct kvm_vcpu *vcpu = NULL;
4976 kvm_set_msi_irq(kvm, e, &irq);
4978 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
4979 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
4980 __func__, irq.vector);
4984 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
4986 *svm = to_svm(vcpu);
4987 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
4988 vcpu_info->vector = irq.vector;
4994 * svm_update_pi_irte - set IRTE for Posted-Interrupts
4997 * @host_irq: host irq of the interrupt
4998 * @guest_irq: gsi of the interrupt
4999 * @set: set or unset PI
5000 * returns 0 on success, < 0 on failure
5002 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5003 uint32_t guest_irq, bool set)
5005 struct kvm_kernel_irq_routing_entry *e;
5006 struct kvm_irq_routing_table *irq_rt;
5007 int idx, ret = -EINVAL;
5009 if (!kvm_arch_has_assigned_device(kvm) ||
5010 !irq_remapping_cap(IRQ_POSTING_CAP))
5013 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5014 __func__, host_irq, guest_irq, set);
5016 idx = srcu_read_lock(&kvm->irq_srcu);
5017 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5018 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5020 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5021 struct vcpu_data vcpu_info;
5022 struct vcpu_svm *svm = NULL;
5024 if (e->type != KVM_IRQ_ROUTING_MSI)
5028 * Here, we setup with legacy mode in the following cases:
5029 * 1. When cannot target interrupt to a specific vcpu.
5030 * 2. Unsetting posted interrupt.
5031 * 3. APIC virtialization is disabled for the vcpu.
5033 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5034 kvm_vcpu_apicv_active(&svm->vcpu)) {
5035 struct amd_iommu_pi_data pi;
5037 /* Try to enable guest_mode in IRTE */
5038 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5040 pi.ga_tag = AVIC_GATAG(kvm->arch.avic_vm_id,
5042 pi.is_guest_mode = true;
5043 pi.vcpu_data = &vcpu_info;
5044 ret = irq_set_vcpu_affinity(host_irq, &pi);
5047 * Here, we successfully setting up vcpu affinity in
5048 * IOMMU guest mode. Now, we need to store the posted
5049 * interrupt information in a per-vcpu ir_list so that
5050 * we can reference to them directly when we update vcpu
5051 * scheduling information in IOMMU irte.
5053 if (!ret && pi.is_guest_mode)
5054 svm_ir_list_add(svm, &pi);
5056 /* Use legacy mode in IRTE */
5057 struct amd_iommu_pi_data pi;
5060 * Here, pi is used to:
5061 * - Tell IOMMU to use legacy mode for this interrupt.
5062 * - Retrieve ga_tag of prior interrupt remapping data.
5064 pi.is_guest_mode = false;
5065 ret = irq_set_vcpu_affinity(host_irq, &pi);
5068 * Check if the posted interrupt was previously
5069 * setup with the guest_mode by checking if the ga_tag
5070 * was cached. If so, we need to clean up the per-vcpu
5073 if (!ret && pi.prev_ga_tag) {
5074 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5075 struct kvm_vcpu *vcpu;
5077 vcpu = kvm_get_vcpu_by_id(kvm, id);
5079 svm_ir_list_del(to_svm(vcpu), &pi);
5084 trace_kvm_pi_irte_update(svm->vcpu.vcpu_id,
5087 vcpu_info.pi_desc_addr, set);
5091 pr_err("%s: failed to update PI IRTE\n", __func__);
5098 srcu_read_unlock(&kvm->irq_srcu, idx);
5102 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5104 struct vcpu_svm *svm = to_svm(vcpu);
5105 struct vmcb *vmcb = svm->vmcb;
5107 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5108 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5109 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5114 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5116 struct vcpu_svm *svm = to_svm(vcpu);
5118 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5121 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5123 struct vcpu_svm *svm = to_svm(vcpu);
5126 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5127 set_intercept(svm, INTERCEPT_IRET);
5129 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5130 clr_intercept(svm, INTERCEPT_IRET);
5134 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5136 struct vcpu_svm *svm = to_svm(vcpu);
5137 struct vmcb *vmcb = svm->vmcb;
5140 if (!gif_set(svm) ||
5141 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5144 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5146 if (is_guest_mode(vcpu))
5147 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5152 static void enable_irq_window(struct kvm_vcpu *vcpu)
5154 struct vcpu_svm *svm = to_svm(vcpu);
5156 if (kvm_vcpu_apicv_active(vcpu))
5160 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5161 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5162 * get that intercept, this function will be called again though and
5163 * we'll get the vintr intercept. However, if the vGIF feature is
5164 * enabled, the STGI interception will not occur. Enable the irq
5165 * window under the assumption that the hardware will set the GIF.
5167 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5169 svm_inject_irq(svm, 0x0);
5173 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5175 struct vcpu_svm *svm = to_svm(vcpu);
5177 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5179 return; /* IRET will cause a vm exit */
5181 if (!gif_set(svm)) {
5182 if (vgif_enabled(svm))
5183 set_intercept(svm, INTERCEPT_STGI);
5184 return; /* STGI will cause a vm exit */
5187 if (svm->nested.exit_required)
5188 return; /* we're not going to run the guest yet */
5191 * Something prevents NMI from been injected. Single step over possible
5192 * problem (IRET or exception injection or interrupt shadow)
5194 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5195 svm->nmi_singlestep = true;
5196 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5199 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5204 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5206 struct vcpu_svm *svm = to_svm(vcpu);
5208 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5209 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5211 svm->asid_generation--;
5214 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5218 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5220 struct vcpu_svm *svm = to_svm(vcpu);
5222 if (svm_nested_virtualize_tpr(vcpu))
5225 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5226 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5227 kvm_set_cr8(vcpu, cr8);
5231 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5233 struct vcpu_svm *svm = to_svm(vcpu);
5236 if (svm_nested_virtualize_tpr(vcpu) ||
5237 kvm_vcpu_apicv_active(vcpu))
5240 cr8 = kvm_get_cr8(vcpu);
5241 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5242 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5245 static void svm_complete_interrupts(struct vcpu_svm *svm)
5249 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5250 unsigned int3_injected = svm->int3_injected;
5252 svm->int3_injected = 0;
5255 * If we've made progress since setting HF_IRET_MASK, we've
5256 * executed an IRET and can allow NMI injection.
5258 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5259 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5260 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5261 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5264 svm->vcpu.arch.nmi_injected = false;
5265 kvm_clear_exception_queue(&svm->vcpu);
5266 kvm_clear_interrupt_queue(&svm->vcpu);
5268 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5271 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5273 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5274 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5277 case SVM_EXITINTINFO_TYPE_NMI:
5278 svm->vcpu.arch.nmi_injected = true;
5280 case SVM_EXITINTINFO_TYPE_EXEPT:
5282 * In case of software exceptions, do not reinject the vector,
5283 * but re-execute the instruction instead. Rewind RIP first
5284 * if we emulated INT3 before.
5286 if (kvm_exception_is_soft(vector)) {
5287 if (vector == BP_VECTOR && int3_injected &&
5288 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5289 kvm_rip_write(&svm->vcpu,
5290 kvm_rip_read(&svm->vcpu) -
5294 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5295 u32 err = svm->vmcb->control.exit_int_info_err;
5296 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5299 kvm_requeue_exception(&svm->vcpu, vector);
5301 case SVM_EXITINTINFO_TYPE_INTR:
5302 kvm_queue_interrupt(&svm->vcpu, vector, false);
5309 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5311 struct vcpu_svm *svm = to_svm(vcpu);
5312 struct vmcb_control_area *control = &svm->vmcb->control;
5314 control->exit_int_info = control->event_inj;
5315 control->exit_int_info_err = control->event_inj_err;
5316 control->event_inj = 0;
5317 svm_complete_interrupts(svm);
5320 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5322 struct vcpu_svm *svm = to_svm(vcpu);
5324 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5325 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5326 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5329 * A vmexit emulation is required before the vcpu can be executed
5332 if (unlikely(svm->nested.exit_required))
5336 * Disable singlestep if we're injecting an interrupt/exception.
5337 * We don't want our modified rflags to be pushed on the stack where
5338 * we might not be able to easily reset them if we disabled NMI
5341 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5343 * Event injection happens before external interrupts cause a
5344 * vmexit and interrupts are disabled here, so smp_send_reschedule
5345 * is enough to force an immediate vmexit.
5347 disable_nmi_singlestep(svm);
5348 smp_send_reschedule(vcpu->cpu);
5353 sync_lapic_to_cr8(vcpu);
5355 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5362 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5363 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5364 * is no need to worry about the conditional branch over the wrmsr
5365 * being speculatively taken.
5368 native_wrmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5371 "push %%" _ASM_BP "; \n\t"
5372 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5373 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5374 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5375 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5376 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5377 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5378 #ifdef CONFIG_X86_64
5379 "mov %c[r8](%[svm]), %%r8 \n\t"
5380 "mov %c[r9](%[svm]), %%r9 \n\t"
5381 "mov %c[r10](%[svm]), %%r10 \n\t"
5382 "mov %c[r11](%[svm]), %%r11 \n\t"
5383 "mov %c[r12](%[svm]), %%r12 \n\t"
5384 "mov %c[r13](%[svm]), %%r13 \n\t"
5385 "mov %c[r14](%[svm]), %%r14 \n\t"
5386 "mov %c[r15](%[svm]), %%r15 \n\t"
5389 /* Enter guest mode */
5390 "push %%" _ASM_AX " \n\t"
5391 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5392 __ex(SVM_VMLOAD) "\n\t"
5393 __ex(SVM_VMRUN) "\n\t"
5394 __ex(SVM_VMSAVE) "\n\t"
5395 "pop %%" _ASM_AX " \n\t"
5397 /* Save guest registers, load host registers */
5398 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5399 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5400 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5401 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5402 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5403 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5404 #ifdef CONFIG_X86_64
5405 "mov %%r8, %c[r8](%[svm]) \n\t"
5406 "mov %%r9, %c[r9](%[svm]) \n\t"
5407 "mov %%r10, %c[r10](%[svm]) \n\t"
5408 "mov %%r11, %c[r11](%[svm]) \n\t"
5409 "mov %%r12, %c[r12](%[svm]) \n\t"
5410 "mov %%r13, %c[r13](%[svm]) \n\t"
5411 "mov %%r14, %c[r14](%[svm]) \n\t"
5412 "mov %%r15, %c[r15](%[svm]) \n\t"
5415 * Clear host registers marked as clobbered to prevent
5418 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5419 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5420 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5421 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5422 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5423 #ifdef CONFIG_X86_64
5424 "xor %%r8, %%r8 \n\t"
5425 "xor %%r9, %%r9 \n\t"
5426 "xor %%r10, %%r10 \n\t"
5427 "xor %%r11, %%r11 \n\t"
5428 "xor %%r12, %%r12 \n\t"
5429 "xor %%r13, %%r13 \n\t"
5430 "xor %%r14, %%r14 \n\t"
5431 "xor %%r15, %%r15 \n\t"
5436 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5437 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5438 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5439 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5440 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5441 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5442 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5443 #ifdef CONFIG_X86_64
5444 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5445 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5446 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5447 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5448 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5449 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5450 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5451 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5454 #ifdef CONFIG_X86_64
5455 , "rbx", "rcx", "rdx", "rsi", "rdi"
5456 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5458 , "ebx", "ecx", "edx", "esi", "edi"
5463 * We do not use IBRS in the kernel. If this vCPU has used the
5464 * SPEC_CTRL MSR it may have left it on; save the value and
5465 * turn it off. This is much more efficient than blindly adding
5466 * it to the atomic save/restore list. Especially as the former
5467 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5469 * For non-nested case:
5470 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5474 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5477 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5478 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5481 native_wrmsrl(MSR_IA32_SPEC_CTRL, 0);
5483 /* Eliminate branch target predictions from guest mode */
5486 #ifdef CONFIG_X86_64
5487 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5489 loadsegment(fs, svm->host.fs);
5490 #ifndef CONFIG_X86_32_LAZY_GS
5491 loadsegment(gs, svm->host.gs);
5497 local_irq_disable();
5499 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5500 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5501 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5502 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5504 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5505 kvm_before_handle_nmi(&svm->vcpu);
5509 /* Any pending NMI will happen here */
5511 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5512 kvm_after_handle_nmi(&svm->vcpu);
5514 sync_cr8_to_lapic(vcpu);
5518 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5520 /* if exit due to PF check for async PF */
5521 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5522 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5525 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5526 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5530 * We need to handle MC intercepts here before the vcpu has a chance to
5531 * change the physical cpu
5533 if (unlikely(svm->vmcb->control.exit_code ==
5534 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5535 svm_handle_mce(svm);
5537 mark_all_clean(svm->vmcb);
5539 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5541 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5543 struct vcpu_svm *svm = to_svm(vcpu);
5545 svm->vmcb->save.cr3 = __sme_set(root);
5546 mark_dirty(svm->vmcb, VMCB_CR);
5547 svm_flush_tlb(vcpu, true);
5550 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5552 struct vcpu_svm *svm = to_svm(vcpu);
5554 svm->vmcb->control.nested_cr3 = __sme_set(root);
5555 mark_dirty(svm->vmcb, VMCB_NPT);
5557 /* Also sync guest cr3 here in case we live migrate */
5558 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5559 mark_dirty(svm->vmcb, VMCB_CR);
5561 svm_flush_tlb(vcpu, true);
5564 static int is_disabled(void)
5568 rdmsrl(MSR_VM_CR, vm_cr);
5569 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5576 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5579 * Patch in the VMMCALL instruction:
5581 hypercall[0] = 0x0f;
5582 hypercall[1] = 0x01;
5583 hypercall[2] = 0xd9;
5586 static void svm_check_processor_compat(void *rtn)
5591 static bool svm_cpu_has_accelerated_tpr(void)
5596 static bool svm_has_high_real_mode_segbase(void)
5601 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5606 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5608 struct vcpu_svm *svm = to_svm(vcpu);
5610 /* Update nrips enabled cache */
5611 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5613 if (!kvm_vcpu_apicv_active(vcpu))
5616 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5619 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5624 entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5628 entry->ecx |= (1 << 2); /* Set SVM bit */
5631 entry->eax = 1; /* SVM revision 1 */
5632 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5633 ASID emulation to nested SVM */
5634 entry->ecx = 0; /* Reserved */
5635 entry->edx = 0; /* Per default do not support any
5636 additional features */
5638 /* Support next_rip if host supports it */
5639 if (boot_cpu_has(X86_FEATURE_NRIPS))
5640 entry->edx |= SVM_FEATURE_NRIP;
5642 /* Support NPT for the guest if enabled */
5644 entry->edx |= SVM_FEATURE_NPT;
5648 /* Support memory encryption cpuid if host supports it */
5649 if (boot_cpu_has(X86_FEATURE_SEV))
5650 cpuid(0x8000001f, &entry->eax, &entry->ebx,
5651 &entry->ecx, &entry->edx);
5656 static int svm_get_lpage_level(void)
5658 return PT_PDPE_LEVEL;
5661 static bool svm_rdtscp_supported(void)
5663 return boot_cpu_has(X86_FEATURE_RDTSCP);
5666 static bool svm_invpcid_supported(void)
5671 static bool svm_mpx_supported(void)
5676 static bool svm_xsaves_supported(void)
5681 static bool svm_umip_emulated(void)
5686 static bool svm_has_wbinvd_exit(void)
5691 #define PRE_EX(exit) { .exit_code = (exit), \
5692 .stage = X86_ICPT_PRE_EXCEPT, }
5693 #define POST_EX(exit) { .exit_code = (exit), \
5694 .stage = X86_ICPT_POST_EXCEPT, }
5695 #define POST_MEM(exit) { .exit_code = (exit), \
5696 .stage = X86_ICPT_POST_MEMACCESS, }
5698 static const struct __x86_intercept {
5700 enum x86_intercept_stage stage;
5701 } x86_intercept_map[] = {
5702 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
5703 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
5704 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
5705 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
5706 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
5707 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
5708 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
5709 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
5710 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
5711 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
5712 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
5713 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
5714 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
5715 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
5716 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
5717 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
5718 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
5719 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
5720 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
5721 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
5722 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
5723 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
5724 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
5725 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
5726 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
5727 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
5728 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
5729 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
5730 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
5731 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
5732 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
5733 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
5734 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
5735 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
5736 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
5737 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
5738 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
5739 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
5740 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
5741 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
5742 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
5743 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
5744 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
5745 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
5746 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
5747 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
5754 static int svm_check_intercept(struct kvm_vcpu *vcpu,
5755 struct x86_instruction_info *info,
5756 enum x86_intercept_stage stage)
5758 struct vcpu_svm *svm = to_svm(vcpu);
5759 int vmexit, ret = X86EMUL_CONTINUE;
5760 struct __x86_intercept icpt_info;
5761 struct vmcb *vmcb = svm->vmcb;
5763 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
5766 icpt_info = x86_intercept_map[info->intercept];
5768 if (stage != icpt_info.stage)
5771 switch (icpt_info.exit_code) {
5772 case SVM_EXIT_READ_CR0:
5773 if (info->intercept == x86_intercept_cr_read)
5774 icpt_info.exit_code += info->modrm_reg;
5776 case SVM_EXIT_WRITE_CR0: {
5777 unsigned long cr0, val;
5780 if (info->intercept == x86_intercept_cr_write)
5781 icpt_info.exit_code += info->modrm_reg;
5783 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
5784 info->intercept == x86_intercept_clts)
5787 intercept = svm->nested.intercept;
5789 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
5792 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5793 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
5795 if (info->intercept == x86_intercept_lmsw) {
5798 /* lmsw can't clear PE - catch this here */
5799 if (cr0 & X86_CR0_PE)
5804 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5808 case SVM_EXIT_READ_DR0:
5809 case SVM_EXIT_WRITE_DR0:
5810 icpt_info.exit_code += info->modrm_reg;
5813 if (info->intercept == x86_intercept_wrmsr)
5814 vmcb->control.exit_info_1 = 1;
5816 vmcb->control.exit_info_1 = 0;
5818 case SVM_EXIT_PAUSE:
5820 * We get this for NOP only, but pause
5821 * is rep not, check this here
5823 if (info->rep_prefix != REPE_PREFIX)
5826 case SVM_EXIT_IOIO: {
5830 if (info->intercept == x86_intercept_in ||
5831 info->intercept == x86_intercept_ins) {
5832 exit_info = ((info->src_val & 0xffff) << 16) |
5834 bytes = info->dst_bytes;
5836 exit_info = (info->dst_val & 0xffff) << 16;
5837 bytes = info->src_bytes;
5840 if (info->intercept == x86_intercept_outs ||
5841 info->intercept == x86_intercept_ins)
5842 exit_info |= SVM_IOIO_STR_MASK;
5844 if (info->rep_prefix)
5845 exit_info |= SVM_IOIO_REP_MASK;
5847 bytes = min(bytes, 4u);
5849 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5851 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5853 vmcb->control.exit_info_1 = exit_info;
5854 vmcb->control.exit_info_2 = info->next_rip;
5862 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5863 if (static_cpu_has(X86_FEATURE_NRIPS))
5864 vmcb->control.next_rip = info->next_rip;
5865 vmcb->control.exit_code = icpt_info.exit_code;
5866 vmexit = nested_svm_exit_handled(svm);
5868 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5875 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
5879 * We must have an instruction with interrupts enabled, so
5880 * the timer interrupt isn't delayed by the interrupt shadow.
5883 local_irq_disable();
5886 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
5890 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
5892 if (avic_handle_apic_id_update(vcpu) != 0)
5894 if (avic_handle_dfr_update(vcpu) != 0)
5896 avic_handle_ldr_update(vcpu);
5899 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5901 /* [63:9] are reserved. */
5902 vcpu->arch.mcg_cap &= 0x1ff;
5905 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
5907 struct vcpu_svm *svm = to_svm(vcpu);
5909 /* Per APM Vol.2 15.22.2 "Response to SMI" */
5913 if (is_guest_mode(&svm->vcpu) &&
5914 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
5915 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
5916 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
5917 svm->nested.exit_required = true;
5924 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
5926 struct vcpu_svm *svm = to_svm(vcpu);
5929 if (is_guest_mode(vcpu)) {
5930 /* FED8h - SVM Guest */
5931 put_smstate(u64, smstate, 0x7ed8, 1);
5932 /* FEE0h - SVM Guest VMCB Physical Address */
5933 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
5935 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5936 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5937 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5939 ret = nested_svm_vmexit(svm);
5946 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
5948 struct vcpu_svm *svm = to_svm(vcpu);
5949 struct vmcb *nested_vmcb;
5957 ret = kvm_vcpu_read_guest(vcpu, smbase + 0xfed8, &svm_state_save,
5958 sizeof(svm_state_save));
5962 if (svm_state_save.guest) {
5963 vcpu->arch.hflags &= ~HF_SMM_MASK;
5964 nested_vmcb = nested_svm_map(svm, svm_state_save.vmcb, &page);
5966 enter_svm_guest_mode(svm, svm_state_save.vmcb, nested_vmcb, page);
5969 vcpu->arch.hflags |= HF_SMM_MASK;
5974 static int enable_smi_window(struct kvm_vcpu *vcpu)
5976 struct vcpu_svm *svm = to_svm(vcpu);
5978 if (!gif_set(svm)) {
5979 if (vgif_enabled(svm))
5980 set_intercept(svm, INTERCEPT_STGI);
5981 /* STGI will cause a vm exit */
5987 static int sev_asid_new(void)
5992 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
5994 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
5995 if (pos >= max_sev_asid)
5998 set_bit(pos, sev_asid_bitmap);
6002 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6004 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6008 asid = sev_asid_new();
6012 ret = sev_platform_init(&argp->error);
6018 INIT_LIST_HEAD(&sev->regions_list);
6023 __sev_asid_free(asid);
6027 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6029 struct sev_data_activate *data;
6030 int asid = sev_get_asid(kvm);
6033 wbinvd_on_all_cpus();
6035 ret = sev_guest_df_flush(error);
6039 data = kzalloc(sizeof(*data), GFP_KERNEL);
6043 /* activate ASID on the given handle */
6044 data->handle = handle;
6046 ret = sev_guest_activate(data, error);
6052 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6061 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6067 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6069 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6071 return __sev_issue_cmd(sev->fd, id, data, error);
6074 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6076 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6077 struct sev_data_launch_start *start;
6078 struct kvm_sev_launch_start params;
6079 void *dh_blob, *session_blob;
6080 int *error = &argp->error;
6083 if (!sev_guest(kvm))
6086 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6089 start = kzalloc(sizeof(*start), GFP_KERNEL);
6094 if (params.dh_uaddr) {
6095 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6096 if (IS_ERR(dh_blob)) {
6097 ret = PTR_ERR(dh_blob);
6101 start->dh_cert_address = __sme_set(__pa(dh_blob));
6102 start->dh_cert_len = params.dh_len;
6105 session_blob = NULL;
6106 if (params.session_uaddr) {
6107 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6108 if (IS_ERR(session_blob)) {
6109 ret = PTR_ERR(session_blob);
6113 start->session_address = __sme_set(__pa(session_blob));
6114 start->session_len = params.session_len;
6117 start->handle = params.handle;
6118 start->policy = params.policy;
6120 /* create memory encryption context */
6121 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6123 goto e_free_session;
6125 /* Bind ASID to this guest */
6126 ret = sev_bind_asid(kvm, start->handle, error);
6128 goto e_free_session;
6130 /* return handle to userspace */
6131 params.handle = start->handle;
6132 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6133 sev_unbind_asid(kvm, start->handle);
6135 goto e_free_session;
6138 sev->handle = start->handle;
6139 sev->fd = argp->sev_fd;
6142 kfree(session_blob);
6150 static int get_num_contig_pages(int idx, struct page **inpages,
6151 unsigned long npages)
6153 unsigned long paddr, next_paddr;
6154 int i = idx + 1, pages = 1;
6156 /* find the number of contiguous pages starting from idx */
6157 paddr = __sme_page_pa(inpages[idx]);
6158 while (i < npages) {
6159 next_paddr = __sme_page_pa(inpages[i++]);
6160 if ((paddr + PAGE_SIZE) == next_paddr) {
6171 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6173 unsigned long vaddr, vaddr_end, next_vaddr, npages, size;
6174 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6175 struct kvm_sev_launch_update_data params;
6176 struct sev_data_launch_update_data *data;
6177 struct page **inpages;
6180 if (!sev_guest(kvm))
6183 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6186 data = kzalloc(sizeof(*data), GFP_KERNEL);
6190 vaddr = params.uaddr;
6192 vaddr_end = vaddr + size;
6194 /* Lock the user memory. */
6195 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6202 * The LAUNCH_UPDATE command will perform in-place encryption of the
6203 * memory content (i.e it will write the same memory region with C=1).
6204 * It's possible that the cache may contain the data with C=0, i.e.,
6205 * unencrypted so invalidate it first.
6207 sev_clflush_pages(inpages, npages);
6209 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6213 * If the user buffer is not page-aligned, calculate the offset
6216 offset = vaddr & (PAGE_SIZE - 1);
6218 /* Calculate the number of pages that can be encrypted in one go. */
6219 pages = get_num_contig_pages(i, inpages, npages);
6221 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6223 data->handle = sev->handle;
6225 data->address = __sme_page_pa(inpages[i]) + offset;
6226 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6231 next_vaddr = vaddr + len;
6235 /* content of memory is updated, mark pages dirty */
6236 for (i = 0; i < npages; i++) {
6237 set_page_dirty_lock(inpages[i]);
6238 mark_page_accessed(inpages[i]);
6240 /* unlock the user pages */
6241 sev_unpin_memory(kvm, inpages, npages);
6247 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6249 void __user *measure = (void __user *)(uintptr_t)argp->data;
6250 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6251 struct sev_data_launch_measure *data;
6252 struct kvm_sev_launch_measure params;
6253 void __user *p = NULL;
6257 if (!sev_guest(kvm))
6260 if (copy_from_user(¶ms, measure, sizeof(params)))
6263 data = kzalloc(sizeof(*data), GFP_KERNEL);
6267 /* User wants to query the blob length */
6271 p = (void __user *)(uintptr_t)params.uaddr;
6273 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6279 blob = kmalloc(params.len, GFP_KERNEL);
6283 data->address = __psp_pa(blob);
6284 data->len = params.len;
6288 data->handle = sev->handle;
6289 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6292 * If we query the session length, FW responded with expected data.
6301 if (copy_to_user(p, blob, params.len))
6306 params.len = data->len;
6307 if (copy_to_user(measure, ¶ms, sizeof(params)))
6316 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6318 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6319 struct sev_data_launch_finish *data;
6322 if (!sev_guest(kvm))
6325 data = kzalloc(sizeof(*data), GFP_KERNEL);
6329 data->handle = sev->handle;
6330 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6336 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6338 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6339 struct kvm_sev_guest_status params;
6340 struct sev_data_guest_status *data;
6343 if (!sev_guest(kvm))
6346 data = kzalloc(sizeof(*data), GFP_KERNEL);
6350 data->handle = sev->handle;
6351 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6355 params.policy = data->policy;
6356 params.state = data->state;
6357 params.handle = data->handle;
6359 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6366 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6367 unsigned long dst, int size,
6368 int *error, bool enc)
6370 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6371 struct sev_data_dbg *data;
6374 data = kzalloc(sizeof(*data), GFP_KERNEL);
6378 data->handle = sev->handle;
6379 data->dst_addr = dst;
6380 data->src_addr = src;
6383 ret = sev_issue_cmd(kvm,
6384 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6390 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6391 unsigned long dst_paddr, int sz, int *err)
6396 * Its safe to read more than we are asked, caller should ensure that
6397 * destination has enough space.
6399 src_paddr = round_down(src_paddr, 16);
6400 offset = src_paddr & 15;
6401 sz = round_up(sz + offset, 16);
6403 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6406 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6407 unsigned long __user dst_uaddr,
6408 unsigned long dst_paddr,
6411 struct page *tpage = NULL;
6414 /* if inputs are not 16-byte then use intermediate buffer */
6415 if (!IS_ALIGNED(dst_paddr, 16) ||
6416 !IS_ALIGNED(paddr, 16) ||
6417 !IS_ALIGNED(size, 16)) {
6418 tpage = (void *)alloc_page(GFP_KERNEL);
6422 dst_paddr = __sme_page_pa(tpage);
6425 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6430 offset = paddr & 15;
6431 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6432 page_address(tpage) + offset, size))
6443 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6444 unsigned long __user vaddr,
6445 unsigned long dst_paddr,
6446 unsigned long __user dst_vaddr,
6447 int size, int *error)
6449 struct page *src_tpage = NULL;
6450 struct page *dst_tpage = NULL;
6451 int ret, len = size;
6453 /* If source buffer is not aligned then use an intermediate buffer */
6454 if (!IS_ALIGNED(vaddr, 16)) {
6455 src_tpage = alloc_page(GFP_KERNEL);
6459 if (copy_from_user(page_address(src_tpage),
6460 (void __user *)(uintptr_t)vaddr, size)) {
6461 __free_page(src_tpage);
6465 paddr = __sme_page_pa(src_tpage);
6469 * If destination buffer or length is not aligned then do read-modify-write:
6470 * - decrypt destination in an intermediate buffer
6471 * - copy the source buffer in an intermediate buffer
6472 * - use the intermediate buffer as source buffer
6474 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6477 dst_tpage = alloc_page(GFP_KERNEL);
6483 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6484 __sme_page_pa(dst_tpage), size, error);
6489 * If source is kernel buffer then use memcpy() otherwise
6492 dst_offset = dst_paddr & 15;
6495 memcpy(page_address(dst_tpage) + dst_offset,
6496 page_address(src_tpage), size);
6498 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6499 (void __user *)(uintptr_t)vaddr, size)) {
6505 paddr = __sme_page_pa(dst_tpage);
6506 dst_paddr = round_down(dst_paddr, 16);
6507 len = round_up(size, 16);
6510 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6514 __free_page(src_tpage);
6516 __free_page(dst_tpage);
6520 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6522 unsigned long vaddr, vaddr_end, next_vaddr;
6523 unsigned long dst_vaddr, dst_vaddr_end;
6524 struct page **src_p, **dst_p;
6525 struct kvm_sev_dbg debug;
6529 if (!sev_guest(kvm))
6532 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6535 vaddr = debug.src_uaddr;
6537 vaddr_end = vaddr + size;
6538 dst_vaddr = debug.dst_uaddr;
6539 dst_vaddr_end = dst_vaddr + size;
6541 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6542 int len, s_off, d_off;
6544 /* lock userspace source and destination page */
6545 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6549 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6551 sev_unpin_memory(kvm, src_p, n);
6556 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6557 * memory content (i.e it will write the same memory region with C=1).
6558 * It's possible that the cache may contain the data with C=0, i.e.,
6559 * unencrypted so invalidate it first.
6561 sev_clflush_pages(src_p, 1);
6562 sev_clflush_pages(dst_p, 1);
6565 * Since user buffer may not be page aligned, calculate the
6566 * offset within the page.
6568 s_off = vaddr & ~PAGE_MASK;
6569 d_off = dst_vaddr & ~PAGE_MASK;
6570 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6573 ret = __sev_dbg_decrypt_user(kvm,
6574 __sme_page_pa(src_p[0]) + s_off,
6576 __sme_page_pa(dst_p[0]) + d_off,
6579 ret = __sev_dbg_encrypt_user(kvm,
6580 __sme_page_pa(src_p[0]) + s_off,
6582 __sme_page_pa(dst_p[0]) + d_off,
6586 sev_unpin_memory(kvm, src_p, 1);
6587 sev_unpin_memory(kvm, dst_p, 1);
6592 next_vaddr = vaddr + len;
6593 dst_vaddr = dst_vaddr + len;
6600 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6602 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6603 struct sev_data_launch_secret *data;
6604 struct kvm_sev_launch_secret params;
6605 struct page **pages;
6610 if (!sev_guest(kvm))
6613 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6616 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6621 * The secret must be copied into contiguous memory region, lets verify
6622 * that userspace memory pages are contiguous before we issue command.
6624 if (get_num_contig_pages(0, pages, n) != n) {
6626 goto e_unpin_memory;
6630 data = kzalloc(sizeof(*data), GFP_KERNEL);
6632 goto e_unpin_memory;
6634 offset = params.guest_uaddr & (PAGE_SIZE - 1);
6635 data->guest_address = __sme_page_pa(pages[0]) + offset;
6636 data->guest_len = params.guest_len;
6638 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6640 ret = PTR_ERR(blob);
6644 data->trans_address = __psp_pa(blob);
6645 data->trans_len = params.trans_len;
6647 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6652 data->hdr_address = __psp_pa(hdr);
6653 data->hdr_len = params.hdr_len;
6655 data->handle = sev->handle;
6656 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
6665 sev_unpin_memory(kvm, pages, n);
6669 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
6671 struct kvm_sev_cmd sev_cmd;
6674 if (!svm_sev_enabled())
6677 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
6680 mutex_lock(&kvm->lock);
6682 switch (sev_cmd.id) {
6684 r = sev_guest_init(kvm, &sev_cmd);
6686 case KVM_SEV_LAUNCH_START:
6687 r = sev_launch_start(kvm, &sev_cmd);
6689 case KVM_SEV_LAUNCH_UPDATE_DATA:
6690 r = sev_launch_update_data(kvm, &sev_cmd);
6692 case KVM_SEV_LAUNCH_MEASURE:
6693 r = sev_launch_measure(kvm, &sev_cmd);
6695 case KVM_SEV_LAUNCH_FINISH:
6696 r = sev_launch_finish(kvm, &sev_cmd);
6698 case KVM_SEV_GUEST_STATUS:
6699 r = sev_guest_status(kvm, &sev_cmd);
6701 case KVM_SEV_DBG_DECRYPT:
6702 r = sev_dbg_crypt(kvm, &sev_cmd, true);
6704 case KVM_SEV_DBG_ENCRYPT:
6705 r = sev_dbg_crypt(kvm, &sev_cmd, false);
6707 case KVM_SEV_LAUNCH_SECRET:
6708 r = sev_launch_secret(kvm, &sev_cmd);
6715 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
6719 mutex_unlock(&kvm->lock);
6723 static int svm_register_enc_region(struct kvm *kvm,
6724 struct kvm_enc_region *range)
6726 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6727 struct enc_region *region;
6730 if (!sev_guest(kvm))
6733 region = kzalloc(sizeof(*region), GFP_KERNEL);
6737 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
6738 if (!region->pages) {
6744 * The guest may change the memory encryption attribute from C=0 -> C=1
6745 * or vice versa for this memory range. Lets make sure caches are
6746 * flushed to ensure that guest data gets written into memory with
6749 sev_clflush_pages(region->pages, region->npages);
6751 region->uaddr = range->addr;
6752 region->size = range->size;
6754 mutex_lock(&kvm->lock);
6755 list_add_tail(®ion->list, &sev->regions_list);
6756 mutex_unlock(&kvm->lock);
6765 static struct enc_region *
6766 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
6768 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6769 struct list_head *head = &sev->regions_list;
6770 struct enc_region *i;
6772 list_for_each_entry(i, head, list) {
6773 if (i->uaddr == range->addr &&
6774 i->size == range->size)
6782 static int svm_unregister_enc_region(struct kvm *kvm,
6783 struct kvm_enc_region *range)
6785 struct enc_region *region;
6788 mutex_lock(&kvm->lock);
6790 if (!sev_guest(kvm)) {
6795 region = find_enc_region(kvm, range);
6801 __unregister_enc_region_locked(kvm, region);
6803 mutex_unlock(&kvm->lock);
6807 mutex_unlock(&kvm->lock);
6811 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
6812 .cpu_has_kvm_support = has_svm,
6813 .disabled_by_bios = is_disabled,
6814 .hardware_setup = svm_hardware_setup,
6815 .hardware_unsetup = svm_hardware_unsetup,
6816 .check_processor_compatibility = svm_check_processor_compat,
6817 .hardware_enable = svm_hardware_enable,
6818 .hardware_disable = svm_hardware_disable,
6819 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
6820 .cpu_has_high_real_mode_segbase = svm_has_high_real_mode_segbase,
6822 .vcpu_create = svm_create_vcpu,
6823 .vcpu_free = svm_free_vcpu,
6824 .vcpu_reset = svm_vcpu_reset,
6826 .vm_init = avic_vm_init,
6827 .vm_destroy = svm_vm_destroy,
6829 .prepare_guest_switch = svm_prepare_guest_switch,
6830 .vcpu_load = svm_vcpu_load,
6831 .vcpu_put = svm_vcpu_put,
6832 .vcpu_blocking = svm_vcpu_blocking,
6833 .vcpu_unblocking = svm_vcpu_unblocking,
6835 .update_bp_intercept = update_bp_intercept,
6836 .get_msr = svm_get_msr,
6837 .set_msr = svm_set_msr,
6838 .get_segment_base = svm_get_segment_base,
6839 .get_segment = svm_get_segment,
6840 .set_segment = svm_set_segment,
6841 .get_cpl = svm_get_cpl,
6842 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
6843 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
6844 .decache_cr3 = svm_decache_cr3,
6845 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
6846 .set_cr0 = svm_set_cr0,
6847 .set_cr3 = svm_set_cr3,
6848 .set_cr4 = svm_set_cr4,
6849 .set_efer = svm_set_efer,
6850 .get_idt = svm_get_idt,
6851 .set_idt = svm_set_idt,
6852 .get_gdt = svm_get_gdt,
6853 .set_gdt = svm_set_gdt,
6854 .get_dr6 = svm_get_dr6,
6855 .set_dr6 = svm_set_dr6,
6856 .set_dr7 = svm_set_dr7,
6857 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
6858 .cache_reg = svm_cache_reg,
6859 .get_rflags = svm_get_rflags,
6860 .set_rflags = svm_set_rflags,
6862 .tlb_flush = svm_flush_tlb,
6864 .run = svm_vcpu_run,
6865 .handle_exit = handle_exit,
6866 .skip_emulated_instruction = skip_emulated_instruction,
6867 .set_interrupt_shadow = svm_set_interrupt_shadow,
6868 .get_interrupt_shadow = svm_get_interrupt_shadow,
6869 .patch_hypercall = svm_patch_hypercall,
6870 .set_irq = svm_set_irq,
6871 .set_nmi = svm_inject_nmi,
6872 .queue_exception = svm_queue_exception,
6873 .cancel_injection = svm_cancel_injection,
6874 .interrupt_allowed = svm_interrupt_allowed,
6875 .nmi_allowed = svm_nmi_allowed,
6876 .get_nmi_mask = svm_get_nmi_mask,
6877 .set_nmi_mask = svm_set_nmi_mask,
6878 .enable_nmi_window = enable_nmi_window,
6879 .enable_irq_window = enable_irq_window,
6880 .update_cr8_intercept = update_cr8_intercept,
6881 .set_virtual_x2apic_mode = svm_set_virtual_x2apic_mode,
6882 .get_enable_apicv = svm_get_enable_apicv,
6883 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
6884 .load_eoi_exitmap = svm_load_eoi_exitmap,
6885 .hwapic_irr_update = svm_hwapic_irr_update,
6886 .hwapic_isr_update = svm_hwapic_isr_update,
6887 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
6888 .apicv_post_state_restore = avic_post_state_restore,
6890 .set_tss_addr = svm_set_tss_addr,
6891 .get_tdp_level = get_npt_level,
6892 .get_mt_mask = svm_get_mt_mask,
6894 .get_exit_info = svm_get_exit_info,
6896 .get_lpage_level = svm_get_lpage_level,
6898 .cpuid_update = svm_cpuid_update,
6900 .rdtscp_supported = svm_rdtscp_supported,
6901 .invpcid_supported = svm_invpcid_supported,
6902 .mpx_supported = svm_mpx_supported,
6903 .xsaves_supported = svm_xsaves_supported,
6904 .umip_emulated = svm_umip_emulated,
6906 .set_supported_cpuid = svm_set_supported_cpuid,
6908 .has_wbinvd_exit = svm_has_wbinvd_exit,
6910 .write_tsc_offset = svm_write_tsc_offset,
6912 .set_tdp_cr3 = set_tdp_cr3,
6914 .check_intercept = svm_check_intercept,
6915 .handle_external_intr = svm_handle_external_intr,
6917 .sched_in = svm_sched_in,
6919 .pmu_ops = &amd_pmu_ops,
6920 .deliver_posted_interrupt = svm_deliver_avic_intr,
6921 .update_pi_irte = svm_update_pi_irte,
6922 .setup_mce = svm_setup_mce,
6924 .smi_allowed = svm_smi_allowed,
6925 .pre_enter_smm = svm_pre_enter_smm,
6926 .pre_leave_smm = svm_pre_leave_smm,
6927 .enable_smi_window = enable_smi_window,
6929 .mem_enc_op = svm_mem_enc_op,
6930 .mem_enc_reg_region = svm_register_enc_region,
6931 .mem_enc_unreg_region = svm_unregister_enc_region,
6934 static int __init svm_init(void)
6936 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
6937 __alignof__(struct vcpu_svm), THIS_MODULE);
6940 static void __exit svm_exit(void)
6945 module_init(svm_init)
6946 module_exit(svm_exit)