1 #define pr_fmt(fmt) "SVM: " fmt
3 #include <linux/kvm_host.h>
7 #include "kvm_cache_regs.h"
12 #include <linux/module.h>
13 #include <linux/mod_devicetable.h>
14 #include <linux/kernel.h>
15 #include <linux/vmalloc.h>
16 #include <linux/highmem.h>
17 #include <linux/amd-iommu.h>
18 #include <linux/sched.h>
19 #include <linux/trace_events.h>
20 #include <linux/slab.h>
21 #include <linux/hashtable.h>
22 #include <linux/objtool.h>
23 #include <linux/psp-sev.h>
24 #include <linux/file.h>
25 #include <linux/pagemap.h>
26 #include <linux/swap.h>
27 #include <linux/rwsem.h>
28 #include <linux/cc_platform.h>
31 #include <asm/perf_event.h>
32 #include <asm/tlbflush.h>
34 #include <asm/debugreg.h>
35 #include <asm/kvm_para.h>
36 #include <asm/irq_remapping.h>
37 #include <asm/spec-ctrl.h>
38 #include <asm/cpu_device_id.h>
39 #include <asm/traps.h>
40 #include <asm/fpu/api.h>
42 #include <asm/virtext.h>
48 #include "kvm_onhyperv.h"
49 #include "svm_onhyperv.h"
51 MODULE_AUTHOR("Qumranet");
52 MODULE_LICENSE("GPL");
55 static const struct x86_cpu_id svm_cpu_id[] = {
56 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
59 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
62 #define SEG_TYPE_LDT 2
63 #define SEG_TYPE_BUSY_TSS16 3
65 static bool erratum_383_found __read_mostly;
67 u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
70 * Set osvw_len to higher value when updated Revision Guides
71 * are published and we know what the new status bits are
73 static uint64_t osvw_len = 4, osvw_status;
75 static DEFINE_PER_CPU(u64, current_tsc_ratio);
77 static const struct svm_direct_access_msrs {
78 u32 index; /* Index of the MSR */
79 bool always; /* True if intercept is initially cleared */
80 } direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
81 { .index = MSR_STAR, .always = true },
82 { .index = MSR_IA32_SYSENTER_CS, .always = true },
83 { .index = MSR_IA32_SYSENTER_EIP, .always = false },
84 { .index = MSR_IA32_SYSENTER_ESP, .always = false },
86 { .index = MSR_GS_BASE, .always = true },
87 { .index = MSR_FS_BASE, .always = true },
88 { .index = MSR_KERNEL_GS_BASE, .always = true },
89 { .index = MSR_LSTAR, .always = true },
90 { .index = MSR_CSTAR, .always = true },
91 { .index = MSR_SYSCALL_MASK, .always = true },
93 { .index = MSR_IA32_SPEC_CTRL, .always = false },
94 { .index = MSR_IA32_PRED_CMD, .always = false },
95 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
96 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
97 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
98 { .index = MSR_IA32_LASTINTTOIP, .always = false },
99 { .index = MSR_EFER, .always = false },
100 { .index = MSR_IA32_CR_PAT, .always = false },
101 { .index = MSR_AMD64_SEV_ES_GHCB, .always = true },
102 { .index = MSR_TSC_AUX, .always = false },
103 { .index = MSR_INVALID, .always = false },
107 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
108 * pause_filter_count: On processors that support Pause filtering(indicated
109 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
110 * count value. On VMRUN this value is loaded into an internal counter.
111 * Each time a pause instruction is executed, this counter is decremented
112 * until it reaches zero at which time a #VMEXIT is generated if pause
113 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
114 * Intercept Filtering for more details.
115 * This also indicate if ple logic enabled.
117 * pause_filter_thresh: In addition, some processor families support advanced
118 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
119 * the amount of time a guest is allowed to execute in a pause loop.
120 * In this mode, a 16-bit pause filter threshold field is added in the
121 * VMCB. The threshold value is a cycle count that is used to reset the
122 * pause counter. As with simple pause filtering, VMRUN loads the pause
123 * count value from VMCB into an internal counter. Then, on each pause
124 * instruction the hardware checks the elapsed number of cycles since
125 * the most recent pause instruction against the pause filter threshold.
126 * If the elapsed cycle count is greater than the pause filter threshold,
127 * then the internal pause count is reloaded from the VMCB and execution
128 * continues. If the elapsed cycle count is less than the pause filter
129 * threshold, then the internal pause count is decremented. If the count
130 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
131 * triggered. If advanced pause filtering is supported and pause filter
132 * threshold field is set to zero, the filter will operate in the simpler,
136 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
137 module_param(pause_filter_thresh, ushort, 0444);
139 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
140 module_param(pause_filter_count, ushort, 0444);
142 /* Default doubles per-vcpu window every exit. */
143 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
144 module_param(pause_filter_count_grow, ushort, 0444);
146 /* Default resets per-vcpu window every exit to pause_filter_count. */
147 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
148 module_param(pause_filter_count_shrink, ushort, 0444);
150 /* Default is to compute the maximum so we can never overflow. */
151 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
152 module_param(pause_filter_count_max, ushort, 0444);
155 * Use nested page tables by default. Note, NPT may get forced off by
156 * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
158 bool npt_enabled = true;
159 module_param_named(npt, npt_enabled, bool, 0444);
161 /* allow nested virtualization in KVM/SVM */
162 static int nested = true;
163 module_param(nested, int, S_IRUGO);
165 /* enable/disable Next RIP Save */
166 static int nrips = true;
167 module_param(nrips, int, 0444);
169 /* enable/disable Virtual VMLOAD VMSAVE */
170 static int vls = true;
171 module_param(vls, int, 0444);
173 /* enable/disable Virtual GIF */
175 module_param(vgif, int, 0444);
177 /* enable/disable LBR virtualization */
178 static int lbrv = true;
179 module_param(lbrv, int, 0444);
181 static int tsc_scaling = true;
182 module_param(tsc_scaling, int, 0444);
185 * enable / disable AVIC. Because the defaults differ for APICv
186 * support between VMX and SVM we cannot use module_param_named.
189 module_param(avic, bool, 0444);
191 static bool force_avic;
192 module_param_unsafe(force_avic, bool, 0444);
194 bool __read_mostly dump_invalid_vmcb;
195 module_param(dump_invalid_vmcb, bool, 0644);
198 bool intercept_smi = true;
199 module_param(intercept_smi, bool, 0444);
202 static bool svm_gp_erratum_intercept = true;
204 static u8 rsm_ins_bytes[] = "\x0f\xaa";
206 static unsigned long iopm_base;
208 struct kvm_ldttss_desc {
211 unsigned base1:8, type:5, dpl:2, p:1;
212 unsigned limit1:4, zero0:3, g:1, base2:8;
215 } __attribute__((packed));
217 DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
220 * Only MSR_TSC_AUX is switched via the user return hook. EFER is switched via
221 * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
223 * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
224 * defer the restoration of TSC_AUX until the CPU returns to userspace.
226 static int tsc_aux_uret_slot __read_mostly = -1;
228 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
230 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
231 #define MSRS_RANGE_SIZE 2048
232 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
234 u32 svm_msrpm_offset(u32 msr)
239 for (i = 0; i < NUM_MSR_MAPS; i++) {
240 if (msr < msrpm_ranges[i] ||
241 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
244 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
245 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
247 /* Now we have the u8 offset - but need the u32 offset */
251 /* MSR not in any range */
255 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu);
257 static int get_npt_level(void)
260 return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
262 return PT32E_ROOT_LEVEL;
266 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
268 struct vcpu_svm *svm = to_svm(vcpu);
269 u64 old_efer = vcpu->arch.efer;
270 vcpu->arch.efer = efer;
273 /* Shadow paging assumes NX to be available. */
276 if (!(efer & EFER_LMA))
280 if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
281 if (!(efer & EFER_SVME)) {
282 svm_leave_nested(vcpu);
283 svm_set_gif(svm, true);
284 /* #GP intercept is still needed for vmware backdoor */
285 if (!enable_vmware_backdoor)
286 clr_exception_intercept(svm, GP_VECTOR);
289 * Free the nested guest state, unless we are in SMM.
290 * In this case we will return to the nested guest
291 * as soon as we leave SMM.
294 svm_free_nested(svm);
297 int ret = svm_allocate_nested(svm);
300 vcpu->arch.efer = old_efer;
305 * Never intercept #GP for SEV guests, KVM can't
306 * decrypt guest memory to workaround the erratum.
308 if (svm_gp_erratum_intercept && !sev_guest(vcpu->kvm))
309 set_exception_intercept(svm, GP_VECTOR);
313 svm->vmcb->save.efer = efer | EFER_SVME;
314 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
318 static int is_external_interrupt(u32 info)
320 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
321 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
324 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
326 struct vcpu_svm *svm = to_svm(vcpu);
329 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
330 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
334 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
336 struct vcpu_svm *svm = to_svm(vcpu);
339 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
341 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
345 static int svm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
347 struct vcpu_svm *svm = to_svm(vcpu);
350 * SEV-ES does not expose the next RIP. The RIP update is controlled by
351 * the type of exit and the #VC handler in the guest.
353 if (sev_es_guest(vcpu->kvm))
356 if (nrips && svm->vmcb->control.next_rip != 0) {
357 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
358 svm->next_rip = svm->vmcb->control.next_rip;
361 if (!svm->next_rip) {
362 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
365 kvm_rip_write(vcpu, svm->next_rip);
369 svm_set_interrupt_shadow(vcpu, 0);
374 static void svm_queue_exception(struct kvm_vcpu *vcpu)
376 struct vcpu_svm *svm = to_svm(vcpu);
377 unsigned nr = vcpu->arch.exception.nr;
378 bool has_error_code = vcpu->arch.exception.has_error_code;
379 u32 error_code = vcpu->arch.exception.error_code;
381 kvm_deliver_exception_payload(vcpu);
383 if (nr == BP_VECTOR && !nrips) {
384 unsigned long rip, old_rip = kvm_rip_read(vcpu);
387 * For guest debugging where we have to reinject #BP if some
388 * INT3 is guest-owned:
389 * Emulate nRIP by moving RIP forward. Will fail if injection
390 * raises a fault that is not intercepted. Still better than
391 * failing in all cases.
393 (void)svm_skip_emulated_instruction(vcpu);
394 rip = kvm_rip_read(vcpu);
395 svm->int3_rip = rip + svm->vmcb->save.cs.base;
396 svm->int3_injected = rip - old_rip;
399 svm->vmcb->control.event_inj = nr
401 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
402 | SVM_EVTINJ_TYPE_EXEPT;
403 svm->vmcb->control.event_inj_err = error_code;
406 static void svm_init_erratum_383(void)
412 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
415 /* Use _safe variants to not break nested virtualization */
416 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
422 low = lower_32_bits(val);
423 high = upper_32_bits(val);
425 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
427 erratum_383_found = true;
430 static void svm_init_osvw(struct kvm_vcpu *vcpu)
433 * Guests should see errata 400 and 415 as fixed (assuming that
434 * HLT and IO instructions are intercepted).
436 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
437 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
440 * By increasing VCPU's osvw.length to 3 we are telling the guest that
441 * all osvw.status bits inside that length, including bit 0 (which is
442 * reserved for erratum 298), are valid. However, if host processor's
443 * osvw_len is 0 then osvw_status[0] carries no information. We need to
444 * be conservative here and therefore we tell the guest that erratum 298
445 * is present (because we really don't know).
447 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
448 vcpu->arch.osvw.status |= 1;
451 static int has_svm(void)
455 if (!cpu_has_svm(&msg)) {
456 printk(KERN_INFO "has_svm: %s\n", msg);
460 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
461 pr_info("KVM is unsupported when running as an SEV guest\n");
468 static void svm_hardware_disable(void)
470 /* Make sure we clean up behind us */
472 wrmsrl(MSR_AMD64_TSC_RATIO, SVM_TSC_RATIO_DEFAULT);
476 amd_pmu_disable_virt();
479 static int svm_hardware_enable(void)
482 struct svm_cpu_data *sd;
484 struct desc_struct *gdt;
485 int me = raw_smp_processor_id();
487 rdmsrl(MSR_EFER, efer);
488 if (efer & EFER_SVME)
492 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
495 sd = per_cpu(svm_data, me);
497 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
501 sd->asid_generation = 1;
502 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
503 sd->next_asid = sd->max_asid + 1;
504 sd->min_asid = max_sev_asid + 1;
506 gdt = get_current_gdt_rw();
507 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
509 wrmsrl(MSR_EFER, efer | EFER_SVME);
511 wrmsrl(MSR_VM_HSAVE_PA, __sme_page_pa(sd->save_area));
513 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
515 * Set the default value, even if we don't use TSC scaling
516 * to avoid having stale value in the msr
518 wrmsrl(MSR_AMD64_TSC_RATIO, SVM_TSC_RATIO_DEFAULT);
519 __this_cpu_write(current_tsc_ratio, SVM_TSC_RATIO_DEFAULT);
526 * Note that it is possible to have a system with mixed processor
527 * revisions and therefore different OSVW bits. If bits are not the same
528 * on different processors then choose the worst case (i.e. if erratum
529 * is present on one processor and not on another then assume that the
530 * erratum is present everywhere).
532 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
533 uint64_t len, status = 0;
536 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
538 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
542 osvw_status = osvw_len = 0;
546 osvw_status |= status;
547 osvw_status &= (1ULL << osvw_len) - 1;
550 osvw_status = osvw_len = 0;
552 svm_init_erratum_383();
554 amd_pmu_enable_virt();
559 static void svm_cpu_uninit(int cpu)
561 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
566 per_cpu(svm_data, cpu) = NULL;
567 kfree(sd->sev_vmcbs);
568 __free_page(sd->save_area);
572 static int svm_cpu_init(int cpu)
574 struct svm_cpu_data *sd;
577 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
581 sd->save_area = alloc_page(GFP_KERNEL | __GFP_ZERO);
585 ret = sev_cpu_init(sd);
589 per_cpu(svm_data, cpu) = sd;
594 __free_page(sd->save_area);
601 static int direct_access_msr_slot(u32 msr)
605 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
606 if (direct_access_msrs[i].index == msr)
612 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
615 struct vcpu_svm *svm = to_svm(vcpu);
616 int slot = direct_access_msr_slot(msr);
621 /* Set the shadow bitmaps to the desired intercept states */
623 set_bit(slot, svm->shadow_msr_intercept.read);
625 clear_bit(slot, svm->shadow_msr_intercept.read);
628 set_bit(slot, svm->shadow_msr_intercept.write);
630 clear_bit(slot, svm->shadow_msr_intercept.write);
633 static bool valid_msr_intercept(u32 index)
635 return direct_access_msr_slot(index) != -ENOENT;
638 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
645 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
648 offset = svm_msrpm_offset(msr);
649 bit_write = 2 * (msr & 0x0f) + 1;
652 BUG_ON(offset == MSR_INVALID);
654 return !!test_bit(bit_write, &tmp);
657 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
658 u32 msr, int read, int write)
660 struct vcpu_svm *svm = to_svm(vcpu);
661 u8 bit_read, bit_write;
666 * If this warning triggers extend the direct_access_msrs list at the
667 * beginning of the file
669 WARN_ON(!valid_msr_intercept(msr));
671 /* Enforce non allowed MSRs to trap */
672 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
675 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
678 offset = svm_msrpm_offset(msr);
679 bit_read = 2 * (msr & 0x0f);
680 bit_write = 2 * (msr & 0x0f) + 1;
683 BUG_ON(offset == MSR_INVALID);
685 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
686 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
690 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
691 svm->nested.force_msr_bitmap_recalc = true;
694 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
697 set_shadow_msr_intercept(vcpu, msr, read, write);
698 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
701 u32 *svm_vcpu_alloc_msrpm(void)
703 unsigned int order = get_order(MSRPM_SIZE);
704 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
710 msrpm = page_address(pages);
711 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
716 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
720 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
721 if (!direct_access_msrs[i].always)
723 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
728 void svm_vcpu_free_msrpm(u32 *msrpm)
730 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
733 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
735 struct vcpu_svm *svm = to_svm(vcpu);
739 * Set intercept permissions for all direct access MSRs again. They
740 * will automatically get filtered through the MSR filter, so we are
741 * back in sync after this.
743 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
744 u32 msr = direct_access_msrs[i].index;
745 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
746 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
748 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
752 static void add_msr_offset(u32 offset)
756 for (i = 0; i < MSRPM_OFFSETS; ++i) {
758 /* Offset already in list? */
759 if (msrpm_offsets[i] == offset)
762 /* Slot used by another offset? */
763 if (msrpm_offsets[i] != MSR_INVALID)
766 /* Add offset to list */
767 msrpm_offsets[i] = offset;
773 * If this BUG triggers the msrpm_offsets table has an overflow. Just
774 * increase MSRPM_OFFSETS in this case.
779 static void init_msrpm_offsets(void)
783 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
785 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
788 offset = svm_msrpm_offset(direct_access_msrs[i].index);
789 BUG_ON(offset == MSR_INVALID);
791 add_msr_offset(offset);
795 void svm_copy_lbrs(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
797 to_vmcb->save.dbgctl = from_vmcb->save.dbgctl;
798 to_vmcb->save.br_from = from_vmcb->save.br_from;
799 to_vmcb->save.br_to = from_vmcb->save.br_to;
800 to_vmcb->save.last_excp_from = from_vmcb->save.last_excp_from;
801 to_vmcb->save.last_excp_to = from_vmcb->save.last_excp_to;
803 vmcb_mark_dirty(to_vmcb, VMCB_LBR);
806 static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
808 struct vcpu_svm *svm = to_svm(vcpu);
810 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
811 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
812 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
813 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
814 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
816 /* Move the LBR msrs to the vmcb02 so that the guest can see them. */
817 if (is_guest_mode(vcpu))
818 svm_copy_lbrs(svm->vmcb, svm->vmcb01.ptr);
821 static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
823 struct vcpu_svm *svm = to_svm(vcpu);
825 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
826 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
827 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
828 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
829 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
832 * Move the LBR msrs back to the vmcb01 to avoid copying them
833 * on nested guest entries.
835 if (is_guest_mode(vcpu))
836 svm_copy_lbrs(svm->vmcb01.ptr, svm->vmcb);
839 static int svm_get_lbr_msr(struct vcpu_svm *svm, u32 index)
842 * If the LBR virtualization is disabled, the LBR msrs are always
843 * kept in the vmcb01 to avoid copying them on nested guest entries.
845 * If nested, and the LBR virtualization is enabled/disabled, the msrs
846 * are moved between the vmcb01 and vmcb02 as needed.
849 (svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK) ?
850 svm->vmcb : svm->vmcb01.ptr;
853 case MSR_IA32_DEBUGCTLMSR:
854 return vmcb->save.dbgctl;
855 case MSR_IA32_LASTBRANCHFROMIP:
856 return vmcb->save.br_from;
857 case MSR_IA32_LASTBRANCHTOIP:
858 return vmcb->save.br_to;
859 case MSR_IA32_LASTINTFROMIP:
860 return vmcb->save.last_excp_from;
861 case MSR_IA32_LASTINTTOIP:
862 return vmcb->save.last_excp_to;
864 KVM_BUG(false, svm->vcpu.kvm,
865 "%s: Unknown MSR 0x%x", __func__, index);
870 void svm_update_lbrv(struct kvm_vcpu *vcpu)
872 struct vcpu_svm *svm = to_svm(vcpu);
874 bool enable_lbrv = svm_get_lbr_msr(svm, MSR_IA32_DEBUGCTLMSR) &
877 bool current_enable_lbrv = !!(svm->vmcb->control.virt_ext &
878 LBR_CTL_ENABLE_MASK);
880 if (unlikely(is_guest_mode(vcpu) && svm->lbrv_enabled))
881 if (unlikely(svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK))
884 if (enable_lbrv == current_enable_lbrv)
888 svm_enable_lbrv(vcpu);
890 svm_disable_lbrv(vcpu);
893 void disable_nmi_singlestep(struct vcpu_svm *svm)
895 svm->nmi_singlestep = false;
897 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
898 /* Clear our flags if they were not set by the guest */
899 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
900 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
901 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
902 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
906 static void grow_ple_window(struct kvm_vcpu *vcpu)
908 struct vcpu_svm *svm = to_svm(vcpu);
909 struct vmcb_control_area *control = &svm->vmcb->control;
910 int old = control->pause_filter_count;
912 if (kvm_pause_in_guest(vcpu->kvm) || !old)
915 control->pause_filter_count = __grow_ple_window(old,
917 pause_filter_count_grow,
918 pause_filter_count_max);
920 if (control->pause_filter_count != old) {
921 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
922 trace_kvm_ple_window_update(vcpu->vcpu_id,
923 control->pause_filter_count, old);
927 static void shrink_ple_window(struct kvm_vcpu *vcpu)
929 struct vcpu_svm *svm = to_svm(vcpu);
930 struct vmcb_control_area *control = &svm->vmcb->control;
931 int old = control->pause_filter_count;
933 if (kvm_pause_in_guest(vcpu->kvm) || !old)
936 control->pause_filter_count =
937 __shrink_ple_window(old,
939 pause_filter_count_shrink,
941 if (control->pause_filter_count != old) {
942 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
943 trace_kvm_ple_window_update(vcpu->vcpu_id,
944 control->pause_filter_count, old);
948 static void svm_hardware_unsetup(void)
952 sev_hardware_unsetup();
954 for_each_possible_cpu(cpu)
957 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
958 get_order(IOPM_SIZE));
962 static void init_seg(struct vmcb_seg *seg)
965 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
966 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
971 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
974 seg->attrib = SVM_SELECTOR_P_MASK | type;
979 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
981 struct vcpu_svm *svm = to_svm(vcpu);
983 return svm->nested.ctl.tsc_offset;
986 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
988 struct vcpu_svm *svm = to_svm(vcpu);
990 return svm->tsc_ratio_msr;
993 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
995 struct vcpu_svm *svm = to_svm(vcpu);
997 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
998 svm->vmcb->control.tsc_offset = offset;
999 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1002 void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1004 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
1007 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1008 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1009 struct vcpu_svm *svm)
1012 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1013 * roots, or if INVPCID is disabled in the guest to inject #UD.
1015 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1017 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1018 svm_set_intercept(svm, INTERCEPT_INVPCID);
1020 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1023 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1024 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1025 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1027 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1031 static inline void init_vmcb_after_set_cpuid(struct kvm_vcpu *vcpu)
1033 struct vcpu_svm *svm = to_svm(vcpu);
1035 if (guest_cpuid_is_intel(vcpu)) {
1037 * We must intercept SYSENTER_EIP and SYSENTER_ESP
1038 * accesses because the processor only stores 32 bits.
1039 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
1041 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1042 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1043 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1045 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
1046 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
1048 svm->v_vmload_vmsave_enabled = false;
1051 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1052 * in VMCB and clear intercepts to avoid #VMEXIT.
1055 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
1056 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
1057 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1059 /* No need to intercept these MSRs */
1060 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
1061 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
1065 static void init_vmcb(struct kvm_vcpu *vcpu)
1067 struct vcpu_svm *svm = to_svm(vcpu);
1068 struct vmcb *vmcb = svm->vmcb01.ptr;
1069 struct vmcb_control_area *control = &vmcb->control;
1070 struct vmcb_save_area *save = &vmcb->save;
1072 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1073 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1074 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1075 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1076 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1077 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1078 if (!kvm_vcpu_apicv_active(vcpu))
1079 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1081 set_dr_intercepts(svm);
1083 set_exception_intercept(svm, PF_VECTOR);
1084 set_exception_intercept(svm, UD_VECTOR);
1085 set_exception_intercept(svm, MC_VECTOR);
1086 set_exception_intercept(svm, AC_VECTOR);
1087 set_exception_intercept(svm, DB_VECTOR);
1089 * Guest access to VMware backdoor ports could legitimately
1090 * trigger #GP because of TSS I/O permission bitmap.
1091 * We intercept those #GP and allow access to them anyway
1092 * as VMware does. Don't intercept #GP for SEV guests as KVM can't
1093 * decrypt guest memory to decode the faulting instruction.
1095 if (enable_vmware_backdoor && !sev_guest(vcpu->kvm))
1096 set_exception_intercept(svm, GP_VECTOR);
1098 svm_set_intercept(svm, INTERCEPT_INTR);
1099 svm_set_intercept(svm, INTERCEPT_NMI);
1102 svm_set_intercept(svm, INTERCEPT_SMI);
1104 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1105 svm_set_intercept(svm, INTERCEPT_RDPMC);
1106 svm_set_intercept(svm, INTERCEPT_CPUID);
1107 svm_set_intercept(svm, INTERCEPT_INVD);
1108 svm_set_intercept(svm, INTERCEPT_INVLPG);
1109 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1110 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1111 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1112 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1113 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1114 svm_set_intercept(svm, INTERCEPT_VMRUN);
1115 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1116 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1117 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1118 svm_set_intercept(svm, INTERCEPT_STGI);
1119 svm_set_intercept(svm, INTERCEPT_CLGI);
1120 svm_set_intercept(svm, INTERCEPT_SKINIT);
1121 svm_set_intercept(svm, INTERCEPT_WBINVD);
1122 svm_set_intercept(svm, INTERCEPT_XSETBV);
1123 svm_set_intercept(svm, INTERCEPT_RDPRU);
1124 svm_set_intercept(svm, INTERCEPT_RSM);
1126 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1127 svm_set_intercept(svm, INTERCEPT_MONITOR);
1128 svm_set_intercept(svm, INTERCEPT_MWAIT);
1131 if (!kvm_hlt_in_guest(vcpu->kvm))
1132 svm_set_intercept(svm, INTERCEPT_HLT);
1134 control->iopm_base_pa = __sme_set(iopm_base);
1135 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1136 control->int_ctl = V_INTR_MASKING_MASK;
1138 init_seg(&save->es);
1139 init_seg(&save->ss);
1140 init_seg(&save->ds);
1141 init_seg(&save->fs);
1142 init_seg(&save->gs);
1144 save->cs.selector = 0xf000;
1145 save->cs.base = 0xffff0000;
1146 /* Executable/Readable Code Segment */
1147 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1148 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1149 save->cs.limit = 0xffff;
1151 save->gdtr.base = 0;
1152 save->gdtr.limit = 0xffff;
1153 save->idtr.base = 0;
1154 save->idtr.limit = 0xffff;
1156 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1157 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1160 /* Setup VMCB for Nested Paging */
1161 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1162 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1163 clr_exception_intercept(svm, PF_VECTOR);
1164 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1165 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1166 save->g_pat = vcpu->arch.pat;
1169 svm->current_vmcb->asid_generation = 0;
1172 svm->nested.vmcb12_gpa = INVALID_GPA;
1173 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1175 if (!kvm_pause_in_guest(vcpu->kvm)) {
1176 control->pause_filter_count = pause_filter_count;
1177 if (pause_filter_thresh)
1178 control->pause_filter_thresh = pause_filter_thresh;
1179 svm_set_intercept(svm, INTERCEPT_PAUSE);
1181 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1184 svm_recalc_instruction_intercepts(vcpu, svm);
1187 * If the host supports V_SPEC_CTRL then disable the interception
1188 * of MSR_IA32_SPEC_CTRL.
1190 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1191 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1193 if (kvm_vcpu_apicv_active(vcpu))
1194 avic_init_vmcb(svm, vmcb);
1197 svm_clr_intercept(svm, INTERCEPT_STGI);
1198 svm_clr_intercept(svm, INTERCEPT_CLGI);
1199 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1202 if (sev_guest(vcpu->kvm)) {
1203 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1204 clr_exception_intercept(svm, UD_VECTOR);
1206 if (sev_es_guest(vcpu->kvm)) {
1207 /* Perform SEV-ES specific VMCB updates */
1208 sev_es_init_vmcb(svm);
1212 svm_hv_init_vmcb(vmcb);
1213 init_vmcb_after_set_cpuid(vcpu);
1215 vmcb_mark_all_dirty(vmcb);
1220 static void __svm_vcpu_reset(struct kvm_vcpu *vcpu)
1222 struct vcpu_svm *svm = to_svm(vcpu);
1224 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1226 svm_init_osvw(vcpu);
1227 vcpu->arch.microcode_version = 0x01000065;
1228 svm->tsc_ratio_msr = kvm_default_tsc_scaling_ratio;
1230 if (sev_es_guest(vcpu->kvm))
1231 sev_es_vcpu_reset(svm);
1234 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1236 struct vcpu_svm *svm = to_svm(vcpu);
1239 svm->virt_spec_ctrl = 0;
1244 __svm_vcpu_reset(vcpu);
1247 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1249 svm->current_vmcb = target_vmcb;
1250 svm->vmcb = target_vmcb->ptr;
1253 static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1255 struct vcpu_svm *svm;
1256 struct page *vmcb01_page;
1257 struct page *vmsa_page = NULL;
1260 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1264 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1268 if (sev_es_guest(vcpu->kvm)) {
1270 * SEV-ES guests require a separate VMSA page used to contain
1271 * the encrypted register state of the guest.
1273 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1275 goto error_free_vmcb_page;
1278 * SEV-ES guests maintain an encrypted version of their FPU
1279 * state which is restored and saved on VMRUN and VMEXIT.
1280 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
1281 * do xsave/xrstor on it.
1283 fpstate_set_confidential(&vcpu->arch.guest_fpu);
1286 err = avic_init_vcpu(svm);
1288 goto error_free_vmsa_page;
1290 svm->msrpm = svm_vcpu_alloc_msrpm();
1293 goto error_free_vmsa_page;
1296 svm->vmcb01.ptr = page_address(vmcb01_page);
1297 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1298 svm_switch_vmcb(svm, &svm->vmcb01);
1301 svm->sev_es.vmsa = page_address(vmsa_page);
1303 svm->guest_state_loaded = false;
1307 error_free_vmsa_page:
1309 __free_page(vmsa_page);
1310 error_free_vmcb_page:
1311 __free_page(vmcb01_page);
1316 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1320 for_each_online_cpu(i)
1321 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
1324 static void svm_vcpu_free(struct kvm_vcpu *vcpu)
1326 struct vcpu_svm *svm = to_svm(vcpu);
1329 * The vmcb page can be recycled, causing a false negative in
1330 * svm_vcpu_load(). So, ensure that no logical CPU has this
1331 * vmcb page recorded as its current vmcb.
1333 svm_clear_current_vmcb(svm->vmcb);
1335 svm_free_nested(svm);
1337 sev_free_vcpu(vcpu);
1339 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1340 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1343 static void svm_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1345 struct vcpu_svm *svm = to_svm(vcpu);
1346 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
1348 if (sev_es_guest(vcpu->kvm))
1349 sev_es_unmap_ghcb(svm);
1351 if (svm->guest_state_loaded)
1355 * Save additional host state that will be restored on VMEXIT (sev-es)
1356 * or subsequent vmload of host save area.
1358 vmsave(__sme_page_pa(sd->save_area));
1359 if (sev_es_guest(vcpu->kvm)) {
1360 struct sev_es_save_area *hostsa;
1361 hostsa = (struct sev_es_save_area *)(page_address(sd->save_area) + 0x400);
1363 sev_es_prepare_switch_to_guest(hostsa);
1367 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
1368 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
1369 __this_cpu_write(current_tsc_ratio, tsc_ratio);
1370 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
1374 if (likely(tsc_aux_uret_slot >= 0))
1375 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1377 svm->guest_state_loaded = true;
1380 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1382 to_svm(vcpu)->guest_state_loaded = false;
1385 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1387 struct vcpu_svm *svm = to_svm(vcpu);
1388 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1390 if (sd->current_vmcb != svm->vmcb) {
1391 sd->current_vmcb = svm->vmcb;
1392 indirect_branch_prediction_barrier();
1394 if (kvm_vcpu_apicv_active(vcpu))
1395 __avic_vcpu_load(vcpu, cpu);
1398 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1400 if (kvm_vcpu_apicv_active(vcpu))
1401 __avic_vcpu_put(vcpu);
1403 svm_prepare_host_switch(vcpu);
1405 ++vcpu->stat.host_state_reload;
1408 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1410 struct vcpu_svm *svm = to_svm(vcpu);
1411 unsigned long rflags = svm->vmcb->save.rflags;
1413 if (svm->nmi_singlestep) {
1414 /* Hide our flags if they were not set by the guest */
1415 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1416 rflags &= ~X86_EFLAGS_TF;
1417 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1418 rflags &= ~X86_EFLAGS_RF;
1423 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1425 if (to_svm(vcpu)->nmi_singlestep)
1426 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1429 * Any change of EFLAGS.VM is accompanied by a reload of SS
1430 * (caused by either a task switch or an inter-privilege IRET),
1431 * so we do not need to update the CPL here.
1433 to_svm(vcpu)->vmcb->save.rflags = rflags;
1436 static bool svm_get_if_flag(struct kvm_vcpu *vcpu)
1438 struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1440 return sev_es_guest(vcpu->kvm)
1441 ? vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK
1442 : kvm_get_rflags(vcpu) & X86_EFLAGS_IF;
1445 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1447 kvm_register_mark_available(vcpu, reg);
1450 case VCPU_EXREG_PDPTR:
1452 * When !npt_enabled, mmu->pdptrs[] is already available since
1453 * it is always updated per SDM when moving to CRs.
1456 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
1459 KVM_BUG_ON(1, vcpu->kvm);
1463 static void svm_set_vintr(struct vcpu_svm *svm)
1465 struct vmcb_control_area *control;
1468 * The following fields are ignored when AVIC is enabled
1470 WARN_ON(kvm_vcpu_apicv_activated(&svm->vcpu));
1472 svm_set_intercept(svm, INTERCEPT_VINTR);
1475 * This is just a dummy VINTR to actually cause a vmexit to happen.
1476 * Actual injection of virtual interrupts happens through EVENTINJ.
1478 control = &svm->vmcb->control;
1479 control->int_vector = 0x0;
1480 control->int_ctl &= ~V_INTR_PRIO_MASK;
1481 control->int_ctl |= V_IRQ_MASK |
1482 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1483 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1486 static void svm_clear_vintr(struct vcpu_svm *svm)
1488 svm_clr_intercept(svm, INTERCEPT_VINTR);
1490 /* Drop int_ctl fields related to VINTR injection. */
1491 svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1492 if (is_guest_mode(&svm->vcpu)) {
1493 svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1495 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1496 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1498 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1499 V_IRQ_INJECTION_BITS_MASK;
1501 svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1504 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1507 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1509 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1510 struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1513 case VCPU_SREG_CS: return &save->cs;
1514 case VCPU_SREG_DS: return &save->ds;
1515 case VCPU_SREG_ES: return &save->es;
1516 case VCPU_SREG_FS: return &save01->fs;
1517 case VCPU_SREG_GS: return &save01->gs;
1518 case VCPU_SREG_SS: return &save->ss;
1519 case VCPU_SREG_TR: return &save01->tr;
1520 case VCPU_SREG_LDTR: return &save01->ldtr;
1526 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1528 struct vmcb_seg *s = svm_seg(vcpu, seg);
1533 static void svm_get_segment(struct kvm_vcpu *vcpu,
1534 struct kvm_segment *var, int seg)
1536 struct vmcb_seg *s = svm_seg(vcpu, seg);
1538 var->base = s->base;
1539 var->limit = s->limit;
1540 var->selector = s->selector;
1541 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1542 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1543 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1544 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1545 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1546 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1547 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1550 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1551 * However, the SVM spec states that the G bit is not observed by the
1552 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1553 * So let's synthesize a legal G bit for all segments, this helps
1554 * running KVM nested. It also helps cross-vendor migration, because
1555 * Intel's vmentry has a check on the 'G' bit.
1557 var->g = s->limit > 0xfffff;
1560 * AMD's VMCB does not have an explicit unusable field, so emulate it
1561 * for cross vendor migration purposes by "not present"
1563 var->unusable = !var->present;
1568 * Work around a bug where the busy flag in the tr selector
1578 * The accessed bit must always be set in the segment
1579 * descriptor cache, although it can be cleared in the
1580 * descriptor, the cached bit always remains at 1. Since
1581 * Intel has a check on this, set it here to support
1582 * cross-vendor migration.
1589 * On AMD CPUs sometimes the DB bit in the segment
1590 * descriptor is left as 1, although the whole segment has
1591 * been made unusable. Clear it here to pass an Intel VMX
1592 * entry check when cross vendor migrating.
1596 /* This is symmetric with svm_set_segment() */
1597 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1602 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1604 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1609 static void svm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1611 struct kvm_segment cs;
1613 svm_get_segment(vcpu, &cs, VCPU_SREG_CS);
1618 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1620 struct vcpu_svm *svm = to_svm(vcpu);
1622 dt->size = svm->vmcb->save.idtr.limit;
1623 dt->address = svm->vmcb->save.idtr.base;
1626 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1628 struct vcpu_svm *svm = to_svm(vcpu);
1630 svm->vmcb->save.idtr.limit = dt->size;
1631 svm->vmcb->save.idtr.base = dt->address ;
1632 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1635 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1637 struct vcpu_svm *svm = to_svm(vcpu);
1639 dt->size = svm->vmcb->save.gdtr.limit;
1640 dt->address = svm->vmcb->save.gdtr.base;
1643 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1645 struct vcpu_svm *svm = to_svm(vcpu);
1647 svm->vmcb->save.gdtr.limit = dt->size;
1648 svm->vmcb->save.gdtr.base = dt->address ;
1649 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1652 static void sev_post_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1654 struct vcpu_svm *svm = to_svm(vcpu);
1657 * For guests that don't set guest_state_protected, the cr3 update is
1658 * handled via kvm_mmu_load() while entering the guest. For guests
1659 * that do (SEV-ES/SEV-SNP), the cr3 update needs to be written to
1660 * VMCB save area now, since the save area will become the initial
1661 * contents of the VMSA, and future VMCB save area updates won't be
1664 if (sev_es_guest(vcpu->kvm)) {
1665 svm->vmcb->save.cr3 = cr3;
1666 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1670 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1672 struct vcpu_svm *svm = to_svm(vcpu);
1674 bool old_paging = is_paging(vcpu);
1676 #ifdef CONFIG_X86_64
1677 if (vcpu->arch.efer & EFER_LME && !vcpu->arch.guest_state_protected) {
1678 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1679 vcpu->arch.efer |= EFER_LMA;
1680 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1683 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1684 vcpu->arch.efer &= ~EFER_LMA;
1685 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1689 vcpu->arch.cr0 = cr0;
1692 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1693 if (old_paging != is_paging(vcpu))
1694 svm_set_cr4(vcpu, kvm_read_cr4(vcpu));
1698 * re-enable caching here because the QEMU bios
1699 * does not do it - this results in some delay at
1702 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1703 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1705 svm->vmcb->save.cr0 = hcr0;
1706 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1709 * SEV-ES guests must always keep the CR intercepts cleared. CR
1710 * tracking is done using the CR write traps.
1712 if (sev_es_guest(vcpu->kvm))
1716 /* Selective CR0 write remains on. */
1717 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1718 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1720 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1721 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1725 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1730 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1732 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1733 unsigned long old_cr4 = vcpu->arch.cr4;
1735 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1736 svm_flush_tlb_current(vcpu);
1738 vcpu->arch.cr4 = cr4;
1742 if (!is_paging(vcpu))
1743 cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
1745 cr4 |= host_cr4_mce;
1746 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1747 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1749 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1750 kvm_update_cpuid_runtime(vcpu);
1753 static void svm_set_segment(struct kvm_vcpu *vcpu,
1754 struct kvm_segment *var, int seg)
1756 struct vcpu_svm *svm = to_svm(vcpu);
1757 struct vmcb_seg *s = svm_seg(vcpu, seg);
1759 s->base = var->base;
1760 s->limit = var->limit;
1761 s->selector = var->selector;
1762 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1763 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1764 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1765 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1766 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1767 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1768 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1769 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1772 * This is always accurate, except if SYSRET returned to a segment
1773 * with SS.DPL != 3. Intel does not have this quirk, and always
1774 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1775 * would entail passing the CPL to userspace and back.
1777 if (seg == VCPU_SREG_SS)
1778 /* This is symmetric with svm_get_segment() */
1779 svm->vmcb->save.cpl = (var->dpl & 3);
1781 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1784 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1786 struct vcpu_svm *svm = to_svm(vcpu);
1788 clr_exception_intercept(svm, BP_VECTOR);
1790 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1791 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1792 set_exception_intercept(svm, BP_VECTOR);
1796 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1798 if (sd->next_asid > sd->max_asid) {
1799 ++sd->asid_generation;
1800 sd->next_asid = sd->min_asid;
1801 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1802 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1805 svm->current_vmcb->asid_generation = sd->asid_generation;
1806 svm->asid = sd->next_asid++;
1809 static void svm_set_dr6(struct vcpu_svm *svm, unsigned long value)
1811 struct vmcb *vmcb = svm->vmcb;
1813 if (svm->vcpu.arch.guest_state_protected)
1816 if (unlikely(value != vmcb->save.dr6)) {
1817 vmcb->save.dr6 = value;
1818 vmcb_mark_dirty(vmcb, VMCB_DR);
1822 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1824 struct vcpu_svm *svm = to_svm(vcpu);
1826 if (vcpu->arch.guest_state_protected)
1829 get_debugreg(vcpu->arch.db[0], 0);
1830 get_debugreg(vcpu->arch.db[1], 1);
1831 get_debugreg(vcpu->arch.db[2], 2);
1832 get_debugreg(vcpu->arch.db[3], 3);
1834 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1835 * because db_interception might need it. We can do it before vmentry.
1837 vcpu->arch.dr6 = svm->vmcb->save.dr6;
1838 vcpu->arch.dr7 = svm->vmcb->save.dr7;
1839 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1840 set_dr_intercepts(svm);
1843 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1845 struct vcpu_svm *svm = to_svm(vcpu);
1847 if (vcpu->arch.guest_state_protected)
1850 svm->vmcb->save.dr7 = value;
1851 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
1854 static int pf_interception(struct kvm_vcpu *vcpu)
1856 struct vcpu_svm *svm = to_svm(vcpu);
1858 u64 fault_address = svm->vmcb->control.exit_info_2;
1859 u64 error_code = svm->vmcb->control.exit_info_1;
1861 return kvm_handle_page_fault(vcpu, error_code, fault_address,
1862 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1863 svm->vmcb->control.insn_bytes : NULL,
1864 svm->vmcb->control.insn_len);
1867 static int npf_interception(struct kvm_vcpu *vcpu)
1869 struct vcpu_svm *svm = to_svm(vcpu);
1871 u64 fault_address = svm->vmcb->control.exit_info_2;
1872 u64 error_code = svm->vmcb->control.exit_info_1;
1874 trace_kvm_page_fault(fault_address, error_code);
1875 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
1876 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1877 svm->vmcb->control.insn_bytes : NULL,
1878 svm->vmcb->control.insn_len);
1881 static int db_interception(struct kvm_vcpu *vcpu)
1883 struct kvm_run *kvm_run = vcpu->run;
1884 struct vcpu_svm *svm = to_svm(vcpu);
1886 if (!(vcpu->guest_debug &
1887 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1888 !svm->nmi_singlestep) {
1889 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
1890 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
1894 if (svm->nmi_singlestep) {
1895 disable_nmi_singlestep(svm);
1896 /* Make sure we check for pending NMIs upon entry */
1897 kvm_make_request(KVM_REQ_EVENT, vcpu);
1900 if (vcpu->guest_debug &
1901 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
1902 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1903 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
1904 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
1905 kvm_run->debug.arch.pc =
1906 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1907 kvm_run->debug.arch.exception = DB_VECTOR;
1914 static int bp_interception(struct kvm_vcpu *vcpu)
1916 struct vcpu_svm *svm = to_svm(vcpu);
1917 struct kvm_run *kvm_run = vcpu->run;
1919 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1920 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1921 kvm_run->debug.arch.exception = BP_VECTOR;
1925 static int ud_interception(struct kvm_vcpu *vcpu)
1927 return handle_ud(vcpu);
1930 static int ac_interception(struct kvm_vcpu *vcpu)
1932 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
1936 static bool is_erratum_383(void)
1941 if (!erratum_383_found)
1944 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
1948 /* Bit 62 may or may not be set for this mce */
1949 value &= ~(1ULL << 62);
1951 if (value != 0xb600000000010015ULL)
1954 /* Clear MCi_STATUS registers */
1955 for (i = 0; i < 6; ++i)
1956 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
1958 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
1962 value &= ~(1ULL << 2);
1963 low = lower_32_bits(value);
1964 high = upper_32_bits(value);
1966 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
1969 /* Flush tlb to evict multi-match entries */
1975 static void svm_handle_mce(struct kvm_vcpu *vcpu)
1977 if (is_erratum_383()) {
1979 * Erratum 383 triggered. Guest state is corrupt so kill the
1982 pr_err("KVM: Guest triggered AMD Erratum 383\n");
1984 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
1990 * On an #MC intercept the MCE handler is not called automatically in
1991 * the host. So do it by hand here.
1993 kvm_machine_check();
1996 static int mc_interception(struct kvm_vcpu *vcpu)
2001 static int shutdown_interception(struct kvm_vcpu *vcpu)
2003 struct kvm_run *kvm_run = vcpu->run;
2004 struct vcpu_svm *svm = to_svm(vcpu);
2007 * The VM save area has already been encrypted so it
2008 * cannot be reinitialized - just terminate.
2010 if (sev_es_guest(vcpu->kvm))
2014 * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put
2015 * the VMCB in a known good state. Unfortuately, KVM doesn't have
2016 * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking
2017 * userspace. At a platform view, INIT is acceptable behavior as
2018 * there exist bare metal platforms that automatically INIT the CPU
2019 * in response to shutdown.
2021 clear_page(svm->vmcb);
2022 kvm_vcpu_reset(vcpu, true);
2024 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2028 static int io_interception(struct kvm_vcpu *vcpu)
2030 struct vcpu_svm *svm = to_svm(vcpu);
2031 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2032 int size, in, string;
2035 ++vcpu->stat.io_exits;
2036 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2037 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2038 port = io_info >> 16;
2039 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2042 if (sev_es_guest(vcpu->kvm))
2043 return sev_es_string_io(svm, size, port, in);
2045 return kvm_emulate_instruction(vcpu, 0);
2048 svm->next_rip = svm->vmcb->control.exit_info_2;
2050 return kvm_fast_pio(vcpu, size, port, in);
2053 static int nmi_interception(struct kvm_vcpu *vcpu)
2058 static int smi_interception(struct kvm_vcpu *vcpu)
2063 static int intr_interception(struct kvm_vcpu *vcpu)
2065 ++vcpu->stat.irq_exits;
2069 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2071 struct vcpu_svm *svm = to_svm(vcpu);
2072 struct vmcb *vmcb12;
2073 struct kvm_host_map map;
2076 if (nested_svm_check_permissions(vcpu))
2079 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2082 kvm_inject_gp(vcpu, 0);
2088 ret = kvm_skip_emulated_instruction(vcpu);
2091 svm_copy_vmloadsave_state(svm->vmcb, vmcb12);
2092 svm->sysenter_eip_hi = 0;
2093 svm->sysenter_esp_hi = 0;
2095 svm_copy_vmloadsave_state(vmcb12, svm->vmcb);
2098 kvm_vcpu_unmap(vcpu, &map, true);
2103 static int vmload_interception(struct kvm_vcpu *vcpu)
2105 return vmload_vmsave_interception(vcpu, true);
2108 static int vmsave_interception(struct kvm_vcpu *vcpu)
2110 return vmload_vmsave_interception(vcpu, false);
2113 static int vmrun_interception(struct kvm_vcpu *vcpu)
2115 if (nested_svm_check_permissions(vcpu))
2118 return nested_svm_vmrun(vcpu);
2128 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
2129 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2131 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2133 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2134 return NONE_SVM_INSTR;
2136 switch (ctxt->modrm) {
2137 case 0xd8: /* VMRUN */
2138 return SVM_INSTR_VMRUN;
2139 case 0xda: /* VMLOAD */
2140 return SVM_INSTR_VMLOAD;
2141 case 0xdb: /* VMSAVE */
2142 return SVM_INSTR_VMSAVE;
2147 return NONE_SVM_INSTR;
2150 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2152 const int guest_mode_exit_codes[] = {
2153 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2154 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2155 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2157 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2158 [SVM_INSTR_VMRUN] = vmrun_interception,
2159 [SVM_INSTR_VMLOAD] = vmload_interception,
2160 [SVM_INSTR_VMSAVE] = vmsave_interception,
2162 struct vcpu_svm *svm = to_svm(vcpu);
2165 if (is_guest_mode(vcpu)) {
2166 /* Returns '1' or -errno on failure, '0' on success. */
2167 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2172 return svm_instr_handlers[opcode](vcpu);
2176 * #GP handling code. Note that #GP can be triggered under the following two
2178 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2179 * some AMD CPUs when EAX of these instructions are in the reserved memory
2180 * regions (e.g. SMM memory on host).
2181 * 2) VMware backdoor
2183 static int gp_interception(struct kvm_vcpu *vcpu)
2185 struct vcpu_svm *svm = to_svm(vcpu);
2186 u32 error_code = svm->vmcb->control.exit_info_1;
2189 /* Both #GP cases have zero error_code */
2193 /* Decode the instruction for usage later */
2194 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2197 opcode = svm_instr_opcode(vcpu);
2199 if (opcode == NONE_SVM_INSTR) {
2200 if (!enable_vmware_backdoor)
2204 * VMware backdoor emulation on #GP interception only handles
2205 * IN{S}, OUT{S}, and RDPMC.
2207 if (!is_guest_mode(vcpu))
2208 return kvm_emulate_instruction(vcpu,
2209 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2211 /* All SVM instructions expect page aligned RAX */
2212 if (svm->vmcb->save.rax & ~PAGE_MASK)
2215 return emulate_svm_instr(vcpu, opcode);
2219 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2223 void svm_set_gif(struct vcpu_svm *svm, bool value)
2227 * If VGIF is enabled, the STGI intercept is only added to
2228 * detect the opening of the SMI/NMI window; remove it now.
2229 * Likewise, clear the VINTR intercept, we will set it
2230 * again while processing KVM_REQ_EVENT if needed.
2233 svm_clr_intercept(svm, INTERCEPT_STGI);
2234 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2235 svm_clear_vintr(svm);
2238 if (svm->vcpu.arch.smi_pending ||
2239 svm->vcpu.arch.nmi_pending ||
2240 kvm_cpu_has_injectable_intr(&svm->vcpu))
2241 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2246 * After a CLGI no interrupts should come. But if vGIF is
2247 * in use, we still rely on the VINTR intercept (rather than
2248 * STGI) to detect an open interrupt window.
2251 svm_clear_vintr(svm);
2255 static int stgi_interception(struct kvm_vcpu *vcpu)
2259 if (nested_svm_check_permissions(vcpu))
2262 ret = kvm_skip_emulated_instruction(vcpu);
2263 svm_set_gif(to_svm(vcpu), true);
2267 static int clgi_interception(struct kvm_vcpu *vcpu)
2271 if (nested_svm_check_permissions(vcpu))
2274 ret = kvm_skip_emulated_instruction(vcpu);
2275 svm_set_gif(to_svm(vcpu), false);
2279 static int invlpga_interception(struct kvm_vcpu *vcpu)
2281 gva_t gva = kvm_rax_read(vcpu);
2282 u32 asid = kvm_rcx_read(vcpu);
2284 /* FIXME: Handle an address size prefix. */
2285 if (!is_long_mode(vcpu))
2288 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2290 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2291 kvm_mmu_invlpg(vcpu, gva);
2293 return kvm_skip_emulated_instruction(vcpu);
2296 static int skinit_interception(struct kvm_vcpu *vcpu)
2298 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2300 kvm_queue_exception(vcpu, UD_VECTOR);
2304 static int task_switch_interception(struct kvm_vcpu *vcpu)
2306 struct vcpu_svm *svm = to_svm(vcpu);
2309 int int_type = svm->vmcb->control.exit_int_info &
2310 SVM_EXITINTINFO_TYPE_MASK;
2311 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2313 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2315 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2316 bool has_error_code = false;
2319 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2321 if (svm->vmcb->control.exit_info_2 &
2322 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2323 reason = TASK_SWITCH_IRET;
2324 else if (svm->vmcb->control.exit_info_2 &
2325 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2326 reason = TASK_SWITCH_JMP;
2328 reason = TASK_SWITCH_GATE;
2330 reason = TASK_SWITCH_CALL;
2332 if (reason == TASK_SWITCH_GATE) {
2334 case SVM_EXITINTINFO_TYPE_NMI:
2335 vcpu->arch.nmi_injected = false;
2337 case SVM_EXITINTINFO_TYPE_EXEPT:
2338 if (svm->vmcb->control.exit_info_2 &
2339 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2340 has_error_code = true;
2342 (u32)svm->vmcb->control.exit_info_2;
2344 kvm_clear_exception_queue(vcpu);
2346 case SVM_EXITINTINFO_TYPE_INTR:
2347 kvm_clear_interrupt_queue(vcpu);
2354 if (reason != TASK_SWITCH_GATE ||
2355 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2356 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2357 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2358 if (!svm_skip_emulated_instruction(vcpu))
2362 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2365 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2366 has_error_code, error_code);
2369 static int iret_interception(struct kvm_vcpu *vcpu)
2371 struct vcpu_svm *svm = to_svm(vcpu);
2373 ++vcpu->stat.nmi_window_exits;
2374 vcpu->arch.hflags |= HF_IRET_MASK;
2375 if (!sev_es_guest(vcpu->kvm)) {
2376 svm_clr_intercept(svm, INTERCEPT_IRET);
2377 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2379 kvm_make_request(KVM_REQ_EVENT, vcpu);
2383 static int invlpg_interception(struct kvm_vcpu *vcpu)
2385 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2386 return kvm_emulate_instruction(vcpu, 0);
2388 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2389 return kvm_skip_emulated_instruction(vcpu);
2392 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2394 return kvm_emulate_instruction(vcpu, 0);
2397 static int rsm_interception(struct kvm_vcpu *vcpu)
2399 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2402 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2405 struct vcpu_svm *svm = to_svm(vcpu);
2406 unsigned long cr0 = vcpu->arch.cr0;
2409 if (!is_guest_mode(vcpu) ||
2410 (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2413 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2414 val &= ~SVM_CR0_SELECTIVE_MASK;
2417 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2418 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2424 #define CR_VALID (1ULL << 63)
2426 static int cr_interception(struct kvm_vcpu *vcpu)
2428 struct vcpu_svm *svm = to_svm(vcpu);
2433 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2434 return emulate_on_interception(vcpu);
2436 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2437 return emulate_on_interception(vcpu);
2439 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2440 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2441 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2443 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2446 if (cr >= 16) { /* mov to cr */
2448 val = kvm_register_read(vcpu, reg);
2449 trace_kvm_cr_write(cr, val);
2452 if (!check_selective_cr0_intercepted(vcpu, val))
2453 err = kvm_set_cr0(vcpu, val);
2459 err = kvm_set_cr3(vcpu, val);
2462 err = kvm_set_cr4(vcpu, val);
2465 err = kvm_set_cr8(vcpu, val);
2468 WARN(1, "unhandled write to CR%d", cr);
2469 kvm_queue_exception(vcpu, UD_VECTOR);
2472 } else { /* mov from cr */
2475 val = kvm_read_cr0(vcpu);
2478 val = vcpu->arch.cr2;
2481 val = kvm_read_cr3(vcpu);
2484 val = kvm_read_cr4(vcpu);
2487 val = kvm_get_cr8(vcpu);
2490 WARN(1, "unhandled read from CR%d", cr);
2491 kvm_queue_exception(vcpu, UD_VECTOR);
2494 kvm_register_write(vcpu, reg, val);
2495 trace_kvm_cr_read(cr, val);
2497 return kvm_complete_insn_gp(vcpu, err);
2500 static int cr_trap(struct kvm_vcpu *vcpu)
2502 struct vcpu_svm *svm = to_svm(vcpu);
2503 unsigned long old_value, new_value;
2507 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2509 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2512 old_value = kvm_read_cr0(vcpu);
2513 svm_set_cr0(vcpu, new_value);
2515 kvm_post_set_cr0(vcpu, old_value, new_value);
2518 old_value = kvm_read_cr4(vcpu);
2519 svm_set_cr4(vcpu, new_value);
2521 kvm_post_set_cr4(vcpu, old_value, new_value);
2524 ret = kvm_set_cr8(vcpu, new_value);
2527 WARN(1, "unhandled CR%d write trap", cr);
2528 kvm_queue_exception(vcpu, UD_VECTOR);
2532 return kvm_complete_insn_gp(vcpu, ret);
2535 static int dr_interception(struct kvm_vcpu *vcpu)
2537 struct vcpu_svm *svm = to_svm(vcpu);
2542 if (vcpu->guest_debug == 0) {
2544 * No more DR vmexits; force a reload of the debug registers
2545 * and reenter on this instruction. The next vmexit will
2546 * retrieve the full state of the debug registers.
2548 clr_dr_intercepts(svm);
2549 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2553 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2554 return emulate_on_interception(vcpu);
2556 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2557 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2558 if (dr >= 16) { /* mov to DRn */
2560 val = kvm_register_read(vcpu, reg);
2561 err = kvm_set_dr(vcpu, dr, val);
2563 kvm_get_dr(vcpu, dr, &val);
2564 kvm_register_write(vcpu, reg, val);
2567 return kvm_complete_insn_gp(vcpu, err);
2570 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2574 u8 cr8_prev = kvm_get_cr8(vcpu);
2575 /* instruction emulation calls kvm_set_cr8() */
2576 r = cr_interception(vcpu);
2577 if (lapic_in_kernel(vcpu))
2579 if (cr8_prev <= kvm_get_cr8(vcpu))
2581 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2585 static int efer_trap(struct kvm_vcpu *vcpu)
2587 struct msr_data msr_info;
2591 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2592 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2593 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2594 * the guest doesn't have X86_FEATURE_SVM.
2596 msr_info.host_initiated = false;
2597 msr_info.index = MSR_EFER;
2598 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2599 ret = kvm_set_msr_common(vcpu, &msr_info);
2601 return kvm_complete_insn_gp(vcpu, ret);
2604 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2608 switch (msr->index) {
2609 case MSR_F10H_DECFG:
2610 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
2611 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
2613 case MSR_IA32_PERF_CAPABILITIES:
2616 return KVM_MSR_RET_INVALID;
2622 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2624 struct vcpu_svm *svm = to_svm(vcpu);
2626 switch (msr_info->index) {
2627 case MSR_AMD64_TSC_RATIO:
2628 if (!msr_info->host_initiated && !svm->tsc_scaling_enabled)
2630 msr_info->data = svm->tsc_ratio_msr;
2633 msr_info->data = svm->vmcb01.ptr->save.star;
2635 #ifdef CONFIG_X86_64
2637 msr_info->data = svm->vmcb01.ptr->save.lstar;
2640 msr_info->data = svm->vmcb01.ptr->save.cstar;
2642 case MSR_KERNEL_GS_BASE:
2643 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2645 case MSR_SYSCALL_MASK:
2646 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2649 case MSR_IA32_SYSENTER_CS:
2650 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2652 case MSR_IA32_SYSENTER_EIP:
2653 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2654 if (guest_cpuid_is_intel(vcpu))
2655 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2657 case MSR_IA32_SYSENTER_ESP:
2658 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2659 if (guest_cpuid_is_intel(vcpu))
2660 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2663 msr_info->data = svm->tsc_aux;
2665 case MSR_IA32_DEBUGCTLMSR:
2666 case MSR_IA32_LASTBRANCHFROMIP:
2667 case MSR_IA32_LASTBRANCHTOIP:
2668 case MSR_IA32_LASTINTFROMIP:
2669 case MSR_IA32_LASTINTTOIP:
2670 msr_info->data = svm_get_lbr_msr(svm, msr_info->index);
2672 case MSR_VM_HSAVE_PA:
2673 msr_info->data = svm->nested.hsave_msr;
2676 msr_info->data = svm->nested.vm_cr_msr;
2678 case MSR_IA32_SPEC_CTRL:
2679 if (!msr_info->host_initiated &&
2680 !guest_has_spec_ctrl_msr(vcpu))
2683 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2684 msr_info->data = svm->vmcb->save.spec_ctrl;
2686 msr_info->data = svm->spec_ctrl;
2688 case MSR_AMD64_VIRT_SPEC_CTRL:
2689 if (!msr_info->host_initiated &&
2690 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2693 msr_info->data = svm->virt_spec_ctrl;
2695 case MSR_F15H_IC_CFG: {
2699 family = guest_cpuid_family(vcpu);
2700 model = guest_cpuid_model(vcpu);
2702 if (family < 0 || model < 0)
2703 return kvm_get_msr_common(vcpu, msr_info);
2707 if (family == 0x15 &&
2708 (model >= 0x2 && model < 0x20))
2709 msr_info->data = 0x1E;
2712 case MSR_F10H_DECFG:
2713 msr_info->data = svm->msr_decfg;
2716 return kvm_get_msr_common(vcpu, msr_info);
2721 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2723 struct vcpu_svm *svm = to_svm(vcpu);
2724 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->sev_es.ghcb))
2725 return kvm_complete_insn_gp(vcpu, err);
2727 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 1);
2728 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb,
2730 SVM_EVTINJ_TYPE_EXEPT |
2735 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2737 struct vcpu_svm *svm = to_svm(vcpu);
2738 int svm_dis, chg_mask;
2740 if (data & ~SVM_VM_CR_VALID_MASK)
2743 chg_mask = SVM_VM_CR_VALID_MASK;
2745 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2746 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2748 svm->nested.vm_cr_msr &= ~chg_mask;
2749 svm->nested.vm_cr_msr |= (data & chg_mask);
2751 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2753 /* check for svm_disable while efer.svme is set */
2754 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
2760 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2762 struct vcpu_svm *svm = to_svm(vcpu);
2765 u32 ecx = msr->index;
2766 u64 data = msr->data;
2768 case MSR_AMD64_TSC_RATIO:
2770 if (!svm->tsc_scaling_enabled) {
2772 if (!msr->host_initiated)
2775 * In case TSC scaling is not enabled, always
2776 * leave this MSR at the default value.
2778 * Due to bug in qemu 6.2.0, it would try to set
2779 * this msr to 0 if tsc scaling is not enabled.
2780 * Ignore this value as well.
2782 if (data != 0 && data != svm->tsc_ratio_msr)
2787 if (data & SVM_TSC_RATIO_RSVD)
2790 svm->tsc_ratio_msr = data;
2792 if (svm->tsc_scaling_enabled && is_guest_mode(vcpu))
2793 nested_svm_update_tsc_ratio_msr(vcpu);
2796 case MSR_IA32_CR_PAT:
2797 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2799 vcpu->arch.pat = data;
2800 svm->vmcb01.ptr->save.g_pat = data;
2801 if (is_guest_mode(vcpu))
2802 nested_vmcb02_compute_g_pat(svm);
2803 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
2805 case MSR_IA32_SPEC_CTRL:
2806 if (!msr->host_initiated &&
2807 !guest_has_spec_ctrl_msr(vcpu))
2810 if (kvm_spec_ctrl_test_value(data))
2813 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2814 svm->vmcb->save.spec_ctrl = data;
2816 svm->spec_ctrl = data;
2822 * When it's written (to non-zero) for the first time, pass
2826 * The handling of the MSR bitmap for L2 guests is done in
2827 * nested_svm_vmrun_msrpm.
2828 * We update the L1 MSR bit as well since it will end up
2829 * touching the MSR anyway now.
2831 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
2833 case MSR_IA32_PRED_CMD:
2834 if (!msr->host_initiated &&
2835 !guest_has_pred_cmd_msr(vcpu))
2838 if (data & ~PRED_CMD_IBPB)
2840 if (!boot_cpu_has(X86_FEATURE_IBPB))
2845 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2846 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
2848 case MSR_AMD64_VIRT_SPEC_CTRL:
2849 if (!msr->host_initiated &&
2850 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2853 if (data & ~SPEC_CTRL_SSBD)
2856 svm->virt_spec_ctrl = data;
2859 svm->vmcb01.ptr->save.star = data;
2861 #ifdef CONFIG_X86_64
2863 svm->vmcb01.ptr->save.lstar = data;
2866 svm->vmcb01.ptr->save.cstar = data;
2868 case MSR_KERNEL_GS_BASE:
2869 svm->vmcb01.ptr->save.kernel_gs_base = data;
2871 case MSR_SYSCALL_MASK:
2872 svm->vmcb01.ptr->save.sfmask = data;
2875 case MSR_IA32_SYSENTER_CS:
2876 svm->vmcb01.ptr->save.sysenter_cs = data;
2878 case MSR_IA32_SYSENTER_EIP:
2879 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
2881 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
2882 * when we spoof an Intel vendor ID (for cross vendor migration).
2883 * In this case we use this intercept to track the high
2884 * 32 bit part of these msrs to support Intel's
2885 * implementation of SYSENTER/SYSEXIT.
2887 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2889 case MSR_IA32_SYSENTER_ESP:
2890 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
2891 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2895 * TSC_AUX is usually changed only during boot and never read
2896 * directly. Intercept TSC_AUX instead of exposing it to the
2897 * guest via direct_access_msrs, and switch it via user return.
2900 r = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
2905 svm->tsc_aux = data;
2907 case MSR_IA32_DEBUGCTLMSR:
2909 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
2913 if (data & DEBUGCTL_RESERVED_BITS)
2916 if (svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK)
2917 svm->vmcb->save.dbgctl = data;
2919 svm->vmcb01.ptr->save.dbgctl = data;
2921 svm_update_lbrv(vcpu);
2924 case MSR_VM_HSAVE_PA:
2926 * Old kernels did not validate the value written to
2927 * MSR_VM_HSAVE_PA. Allow KVM_SET_MSR to set an invalid
2928 * value to allow live migrating buggy or malicious guests
2929 * originating from those kernels.
2931 if (!msr->host_initiated && !page_address_valid(vcpu, data))
2934 svm->nested.hsave_msr = data & PAGE_MASK;
2937 return svm_set_vm_cr(vcpu, data);
2939 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
2941 case MSR_F10H_DECFG: {
2942 struct kvm_msr_entry msr_entry;
2944 msr_entry.index = msr->index;
2945 if (svm_get_msr_feature(&msr_entry))
2948 /* Check the supported bits */
2949 if (data & ~msr_entry.data)
2952 /* Don't allow the guest to change a bit, #GP */
2953 if (!msr->host_initiated && (data ^ msr_entry.data))
2956 svm->msr_decfg = data;
2960 return kvm_set_msr_common(vcpu, msr);
2965 static int msr_interception(struct kvm_vcpu *vcpu)
2967 if (to_svm(vcpu)->vmcb->control.exit_info_1)
2968 return kvm_emulate_wrmsr(vcpu);
2970 return kvm_emulate_rdmsr(vcpu);
2973 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
2975 kvm_make_request(KVM_REQ_EVENT, vcpu);
2976 svm_clear_vintr(to_svm(vcpu));
2979 * If not running nested, for AVIC, the only reason to end up here is ExtINTs.
2980 * In this case AVIC was temporarily disabled for
2981 * requesting the IRQ window and we have to re-enable it.
2983 * If running nested, still remove the VM wide AVIC inhibit to
2984 * support case in which the interrupt window was requested when the
2985 * vCPU was not running nested.
2987 * All vCPUs which run still run nested, will remain to have their
2988 * AVIC still inhibited due to per-cpu AVIC inhibition.
2990 kvm_clear_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
2992 ++vcpu->stat.irq_window_exits;
2996 static int pause_interception(struct kvm_vcpu *vcpu)
3000 * CPL is not made available for an SEV-ES guest, therefore
3001 * vcpu->arch.preempted_in_kernel can never be true. Just
3002 * set in_kernel to false as well.
3004 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3006 grow_ple_window(vcpu);
3008 kvm_vcpu_on_spin(vcpu, in_kernel);
3009 return kvm_skip_emulated_instruction(vcpu);
3012 static int invpcid_interception(struct kvm_vcpu *vcpu)
3014 struct vcpu_svm *svm = to_svm(vcpu);
3018 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3019 kvm_queue_exception(vcpu, UD_VECTOR);
3024 * For an INVPCID intercept:
3025 * EXITINFO1 provides the linear address of the memory operand.
3026 * EXITINFO2 provides the contents of the register operand.
3028 type = svm->vmcb->control.exit_info_2;
3029 gva = svm->vmcb->control.exit_info_1;
3031 return kvm_handle_invpcid(vcpu, type, gva);
3034 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3035 [SVM_EXIT_READ_CR0] = cr_interception,
3036 [SVM_EXIT_READ_CR3] = cr_interception,
3037 [SVM_EXIT_READ_CR4] = cr_interception,
3038 [SVM_EXIT_READ_CR8] = cr_interception,
3039 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3040 [SVM_EXIT_WRITE_CR0] = cr_interception,
3041 [SVM_EXIT_WRITE_CR3] = cr_interception,
3042 [SVM_EXIT_WRITE_CR4] = cr_interception,
3043 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3044 [SVM_EXIT_READ_DR0] = dr_interception,
3045 [SVM_EXIT_READ_DR1] = dr_interception,
3046 [SVM_EXIT_READ_DR2] = dr_interception,
3047 [SVM_EXIT_READ_DR3] = dr_interception,
3048 [SVM_EXIT_READ_DR4] = dr_interception,
3049 [SVM_EXIT_READ_DR5] = dr_interception,
3050 [SVM_EXIT_READ_DR6] = dr_interception,
3051 [SVM_EXIT_READ_DR7] = dr_interception,
3052 [SVM_EXIT_WRITE_DR0] = dr_interception,
3053 [SVM_EXIT_WRITE_DR1] = dr_interception,
3054 [SVM_EXIT_WRITE_DR2] = dr_interception,
3055 [SVM_EXIT_WRITE_DR3] = dr_interception,
3056 [SVM_EXIT_WRITE_DR4] = dr_interception,
3057 [SVM_EXIT_WRITE_DR5] = dr_interception,
3058 [SVM_EXIT_WRITE_DR6] = dr_interception,
3059 [SVM_EXIT_WRITE_DR7] = dr_interception,
3060 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3061 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3062 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3063 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3064 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3065 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3066 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3067 [SVM_EXIT_INTR] = intr_interception,
3068 [SVM_EXIT_NMI] = nmi_interception,
3069 [SVM_EXIT_SMI] = smi_interception,
3070 [SVM_EXIT_VINTR] = interrupt_window_interception,
3071 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3072 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3073 [SVM_EXIT_IRET] = iret_interception,
3074 [SVM_EXIT_INVD] = kvm_emulate_invd,
3075 [SVM_EXIT_PAUSE] = pause_interception,
3076 [SVM_EXIT_HLT] = kvm_emulate_halt,
3077 [SVM_EXIT_INVLPG] = invlpg_interception,
3078 [SVM_EXIT_INVLPGA] = invlpga_interception,
3079 [SVM_EXIT_IOIO] = io_interception,
3080 [SVM_EXIT_MSR] = msr_interception,
3081 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3082 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3083 [SVM_EXIT_VMRUN] = vmrun_interception,
3084 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3085 [SVM_EXIT_VMLOAD] = vmload_interception,
3086 [SVM_EXIT_VMSAVE] = vmsave_interception,
3087 [SVM_EXIT_STGI] = stgi_interception,
3088 [SVM_EXIT_CLGI] = clgi_interception,
3089 [SVM_EXIT_SKINIT] = skinit_interception,
3090 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3091 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3092 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3093 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3094 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3095 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3096 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3097 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3098 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3099 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3100 [SVM_EXIT_INVPCID] = invpcid_interception,
3101 [SVM_EXIT_NPF] = npf_interception,
3102 [SVM_EXIT_RSM] = rsm_interception,
3103 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3104 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3105 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3108 static void dump_vmcb(struct kvm_vcpu *vcpu)
3110 struct vcpu_svm *svm = to_svm(vcpu);
3111 struct vmcb_control_area *control = &svm->vmcb->control;
3112 struct vmcb_save_area *save = &svm->vmcb->save;
3113 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3115 if (!dump_invalid_vmcb) {
3116 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3120 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3121 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3122 pr_err("VMCB Control Area:\n");
3123 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3124 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3125 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3126 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3127 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3128 pr_err("%-20s%08x %08x\n", "intercepts:",
3129 control->intercepts[INTERCEPT_WORD3],
3130 control->intercepts[INTERCEPT_WORD4]);
3131 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3132 pr_err("%-20s%d\n", "pause filter threshold:",
3133 control->pause_filter_thresh);
3134 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3135 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3136 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3137 pr_err("%-20s%d\n", "asid:", control->asid);
3138 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3139 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3140 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3141 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3142 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3143 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3144 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3145 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3146 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3147 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3148 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3149 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3150 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3151 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3152 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3153 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3154 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3155 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3156 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3157 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3158 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3159 pr_err("VMCB State Save Area:\n");
3160 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3162 save->es.selector, save->es.attrib,
3163 save->es.limit, save->es.base);
3164 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3166 save->cs.selector, save->cs.attrib,
3167 save->cs.limit, save->cs.base);
3168 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3170 save->ss.selector, save->ss.attrib,
3171 save->ss.limit, save->ss.base);
3172 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3174 save->ds.selector, save->ds.attrib,
3175 save->ds.limit, save->ds.base);
3176 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3178 save01->fs.selector, save01->fs.attrib,
3179 save01->fs.limit, save01->fs.base);
3180 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3182 save01->gs.selector, save01->gs.attrib,
3183 save01->gs.limit, save01->gs.base);
3184 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3186 save->gdtr.selector, save->gdtr.attrib,
3187 save->gdtr.limit, save->gdtr.base);
3188 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3190 save01->ldtr.selector, save01->ldtr.attrib,
3191 save01->ldtr.limit, save01->ldtr.base);
3192 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3194 save->idtr.selector, save->idtr.attrib,
3195 save->idtr.limit, save->idtr.base);
3196 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3198 save01->tr.selector, save01->tr.attrib,
3199 save01->tr.limit, save01->tr.base);
3200 pr_err("vmpl: %d cpl: %d efer: %016llx\n",
3201 save->vmpl, save->cpl, save->efer);
3202 pr_err("%-15s %016llx %-13s %016llx\n",
3203 "cr0:", save->cr0, "cr2:", save->cr2);
3204 pr_err("%-15s %016llx %-13s %016llx\n",
3205 "cr3:", save->cr3, "cr4:", save->cr4);
3206 pr_err("%-15s %016llx %-13s %016llx\n",
3207 "dr6:", save->dr6, "dr7:", save->dr7);
3208 pr_err("%-15s %016llx %-13s %016llx\n",
3209 "rip:", save->rip, "rflags:", save->rflags);
3210 pr_err("%-15s %016llx %-13s %016llx\n",
3211 "rsp:", save->rsp, "rax:", save->rax);
3212 pr_err("%-15s %016llx %-13s %016llx\n",
3213 "star:", save01->star, "lstar:", save01->lstar);
3214 pr_err("%-15s %016llx %-13s %016llx\n",
3215 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3216 pr_err("%-15s %016llx %-13s %016llx\n",
3217 "kernel_gs_base:", save01->kernel_gs_base,
3218 "sysenter_cs:", save01->sysenter_cs);
3219 pr_err("%-15s %016llx %-13s %016llx\n",
3220 "sysenter_esp:", save01->sysenter_esp,
3221 "sysenter_eip:", save01->sysenter_eip);
3222 pr_err("%-15s %016llx %-13s %016llx\n",
3223 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3224 pr_err("%-15s %016llx %-13s %016llx\n",
3225 "br_from:", save->br_from, "br_to:", save->br_to);
3226 pr_err("%-15s %016llx %-13s %016llx\n",
3227 "excp_from:", save->last_excp_from,
3228 "excp_to:", save->last_excp_to);
3231 static bool svm_check_exit_valid(u64 exit_code)
3233 return (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3234 svm_exit_handlers[exit_code]);
3237 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3239 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3241 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3242 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3243 vcpu->run->internal.ndata = 2;
3244 vcpu->run->internal.data[0] = exit_code;
3245 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3249 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3251 if (!svm_check_exit_valid(exit_code))
3252 return svm_handle_invalid_exit(vcpu, exit_code);
3254 #ifdef CONFIG_RETPOLINE
3255 if (exit_code == SVM_EXIT_MSR)
3256 return msr_interception(vcpu);
3257 else if (exit_code == SVM_EXIT_VINTR)
3258 return interrupt_window_interception(vcpu);
3259 else if (exit_code == SVM_EXIT_INTR)
3260 return intr_interception(vcpu);
3261 else if (exit_code == SVM_EXIT_HLT)
3262 return kvm_emulate_halt(vcpu);
3263 else if (exit_code == SVM_EXIT_NPF)
3264 return npf_interception(vcpu);
3266 return svm_exit_handlers[exit_code](vcpu);
3269 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
3270 u64 *info1, u64 *info2,
3271 u32 *intr_info, u32 *error_code)
3273 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3275 *reason = control->exit_code;
3276 *info1 = control->exit_info_1;
3277 *info2 = control->exit_info_2;
3278 *intr_info = control->exit_int_info;
3279 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3280 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3281 *error_code = control->exit_int_info_err;
3286 static int svm_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3288 struct vcpu_svm *svm = to_svm(vcpu);
3289 struct kvm_run *kvm_run = vcpu->run;
3290 u32 exit_code = svm->vmcb->control.exit_code;
3292 trace_kvm_exit(vcpu, KVM_ISA_SVM);
3294 /* SEV-ES guests must use the CR write traps to track CR registers. */
3295 if (!sev_es_guest(vcpu->kvm)) {
3296 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3297 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3299 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3302 if (is_guest_mode(vcpu)) {
3305 trace_kvm_nested_vmexit(vcpu, KVM_ISA_SVM);
3307 vmexit = nested_svm_exit_special(svm);
3309 if (vmexit == NESTED_EXIT_CONTINUE)
3310 vmexit = nested_svm_exit_handled(svm);
3312 if (vmexit == NESTED_EXIT_DONE)
3316 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3317 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3318 kvm_run->fail_entry.hardware_entry_failure_reason
3319 = svm->vmcb->control.exit_code;
3320 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3325 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
3326 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
3327 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
3328 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
3329 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
3331 __func__, svm->vmcb->control.exit_int_info,
3334 if (exit_fastpath != EXIT_FASTPATH_NONE)
3337 return svm_invoke_exit_handler(vcpu, exit_code);
3340 static void reload_tss(struct kvm_vcpu *vcpu)
3342 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3344 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3348 static void pre_svm_run(struct kvm_vcpu *vcpu)
3350 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3351 struct vcpu_svm *svm = to_svm(vcpu);
3354 * If the previous vmrun of the vmcb occurred on a different physical
3355 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3356 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3358 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3359 svm->current_vmcb->asid_generation = 0;
3360 vmcb_mark_all_dirty(svm->vmcb);
3361 svm->current_vmcb->cpu = vcpu->cpu;
3364 if (sev_guest(vcpu->kvm))
3365 return pre_sev_run(svm, vcpu->cpu);
3367 /* FIXME: handle wraparound of asid_generation */
3368 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3372 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3374 struct vcpu_svm *svm = to_svm(vcpu);
3376 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3377 vcpu->arch.hflags |= HF_NMI_MASK;
3378 if (!sev_es_guest(vcpu->kvm))
3379 svm_set_intercept(svm, INTERCEPT_IRET);
3380 ++vcpu->stat.nmi_injections;
3383 static void svm_inject_irq(struct kvm_vcpu *vcpu)
3385 struct vcpu_svm *svm = to_svm(vcpu);
3387 BUG_ON(!(gif_set(svm)));
3389 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
3390 ++vcpu->stat.irq_injections;
3392 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3393 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
3396 void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,
3397 int trig_mode, int vector)
3400 * vcpu->arch.apicv_active must be read after vcpu->mode.
3401 * Pairs with smp_store_release in vcpu_enter_guest.
3403 bool in_guest_mode = (smp_load_acquire(&vcpu->mode) == IN_GUEST_MODE);
3405 if (!READ_ONCE(vcpu->arch.apicv_active)) {
3406 /* Process the interrupt via inject_pending_event */
3407 kvm_make_request(KVM_REQ_EVENT, vcpu);
3408 kvm_vcpu_kick(vcpu);
3412 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, trig_mode, vector);
3413 if (in_guest_mode) {
3415 * Signal the doorbell to tell hardware to inject the IRQ. If
3416 * the vCPU exits the guest before the doorbell chimes, hardware
3417 * will automatically process AVIC interrupts at the next VMRUN.
3419 avic_ring_doorbell(vcpu);
3422 * Wake the vCPU if it was blocking. KVM will then detect the
3423 * pending IRQ when checking if the vCPU has a wake event.
3425 kvm_vcpu_wake_up(vcpu);
3429 static void svm_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
3430 int trig_mode, int vector)
3432 kvm_lapic_set_irr(vector, apic);
3435 * Pairs with the smp_mb_*() after setting vcpu->guest_mode in
3436 * vcpu_enter_guest() to ensure the write to the vIRR is ordered before
3437 * the read of guest_mode. This guarantees that either VMRUN will see
3438 * and process the new vIRR entry, or that svm_complete_interrupt_delivery
3439 * will signal the doorbell if the CPU has already entered the guest.
3441 smp_mb__after_atomic();
3442 svm_complete_interrupt_delivery(apic->vcpu, delivery_mode, trig_mode, vector);
3445 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3447 struct vcpu_svm *svm = to_svm(vcpu);
3450 * SEV-ES guests must always keep the CR intercepts cleared. CR
3451 * tracking is done using the CR write traps.
3453 if (sev_es_guest(vcpu->kvm))
3456 if (nested_svm_virtualize_tpr(vcpu))
3459 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3465 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3468 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3470 struct vcpu_svm *svm = to_svm(vcpu);
3471 struct vmcb *vmcb = svm->vmcb;
3477 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3480 ret = (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) ||
3481 (vcpu->arch.hflags & HF_NMI_MASK);
3486 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3488 struct vcpu_svm *svm = to_svm(vcpu);
3489 if (svm->nested.nested_run_pending)
3492 if (svm_nmi_blocked(vcpu))
3495 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3496 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3501 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3503 return !!(vcpu->arch.hflags & HF_NMI_MASK);
3506 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3508 struct vcpu_svm *svm = to_svm(vcpu);
3511 vcpu->arch.hflags |= HF_NMI_MASK;
3512 if (!sev_es_guest(vcpu->kvm))
3513 svm_set_intercept(svm, INTERCEPT_IRET);
3515 vcpu->arch.hflags &= ~HF_NMI_MASK;
3516 if (!sev_es_guest(vcpu->kvm))
3517 svm_clr_intercept(svm, INTERCEPT_IRET);
3521 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3523 struct vcpu_svm *svm = to_svm(vcpu);
3524 struct vmcb *vmcb = svm->vmcb;
3529 if (is_guest_mode(vcpu)) {
3530 /* As long as interrupts are being delivered... */
3531 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3532 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3533 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3536 /* ... vmexits aren't blocked by the interrupt shadow */
3537 if (nested_exit_on_intr(svm))
3540 if (!svm_get_if_flag(vcpu))
3544 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3547 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3549 struct vcpu_svm *svm = to_svm(vcpu);
3551 if (svm->nested.nested_run_pending)
3554 if (svm_interrupt_blocked(vcpu))
3558 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3559 * e.g. if the IRQ arrived asynchronously after checking nested events.
3561 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3567 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3569 struct vcpu_svm *svm = to_svm(vcpu);
3572 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3573 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3574 * get that intercept, this function will be called again though and
3575 * we'll get the vintr intercept. However, if the vGIF feature is
3576 * enabled, the STGI interception will not occur. Enable the irq
3577 * window under the assumption that the hardware will set the GIF.
3579 if (vgif || gif_set(svm)) {
3581 * IRQ window is not needed when AVIC is enabled,
3582 * unless we have pending ExtINT since it cannot be injected
3583 * via AVIC. In such case, KVM needs to temporarily disable AVIC,
3584 * and fallback to injecting IRQ via V_IRQ.
3586 * If running nested, AVIC is already locally inhibited
3587 * on this vCPU, therefore there is no need to request
3588 * the VM wide AVIC inhibition.
3590 if (!is_guest_mode(vcpu))
3591 kvm_set_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
3597 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3599 struct vcpu_svm *svm = to_svm(vcpu);
3601 if ((vcpu->arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK)
3602 return; /* IRET will cause a vm exit */
3604 if (!gif_set(svm)) {
3606 svm_set_intercept(svm, INTERCEPT_STGI);
3607 return; /* STGI will cause a vm exit */
3611 * Something prevents NMI from been injected. Single step over possible
3612 * problem (IRET or exception injection or interrupt shadow)
3614 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3615 svm->nmi_singlestep = true;
3616 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3619 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
3621 struct vcpu_svm *svm = to_svm(vcpu);
3624 * Flush only the current ASID even if the TLB flush was invoked via
3625 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3626 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3627 * unconditionally does a TLB flush on both nested VM-Enter and nested
3628 * VM-Exit (via kvm_mmu_reset_context()).
3630 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3631 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3633 svm->current_vmcb->asid_generation--;
3636 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
3638 struct vcpu_svm *svm = to_svm(vcpu);
3640 invlpga(gva, svm->vmcb->control.asid);
3643 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3645 struct vcpu_svm *svm = to_svm(vcpu);
3647 if (nested_svm_virtualize_tpr(vcpu))
3650 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
3651 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3652 kvm_set_cr8(vcpu, cr8);
3656 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3658 struct vcpu_svm *svm = to_svm(vcpu);
3661 if (nested_svm_virtualize_tpr(vcpu) ||
3662 kvm_vcpu_apicv_active(vcpu))
3665 cr8 = kvm_get_cr8(vcpu);
3666 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3667 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3670 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
3672 struct vcpu_svm *svm = to_svm(vcpu);
3675 u32 exitintinfo = svm->vmcb->control.exit_int_info;
3676 unsigned int3_injected = svm->int3_injected;
3678 svm->int3_injected = 0;
3681 * If we've made progress since setting HF_IRET_MASK, we've
3682 * executed an IRET and can allow NMI injection.
3684 if ((vcpu->arch.hflags & HF_IRET_MASK) &&
3685 (sev_es_guest(vcpu->kvm) ||
3686 kvm_rip_read(vcpu) != svm->nmi_iret_rip)) {
3687 vcpu->arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3688 kvm_make_request(KVM_REQ_EVENT, vcpu);
3691 vcpu->arch.nmi_injected = false;
3692 kvm_clear_exception_queue(vcpu);
3693 kvm_clear_interrupt_queue(vcpu);
3695 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3698 kvm_make_request(KVM_REQ_EVENT, vcpu);
3700 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3701 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3704 case SVM_EXITINTINFO_TYPE_NMI:
3705 vcpu->arch.nmi_injected = true;
3707 case SVM_EXITINTINFO_TYPE_EXEPT:
3709 * Never re-inject a #VC exception.
3711 if (vector == X86_TRAP_VC)
3715 * In case of software exceptions, do not reinject the vector,
3716 * but re-execute the instruction instead. Rewind RIP first
3717 * if we emulated INT3 before.
3719 if (kvm_exception_is_soft(vector)) {
3720 if (vector == BP_VECTOR && int3_injected &&
3721 kvm_is_linear_rip(vcpu, svm->int3_rip))
3723 kvm_rip_read(vcpu) - int3_injected);
3726 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3727 u32 err = svm->vmcb->control.exit_int_info_err;
3728 kvm_requeue_exception_e(vcpu, vector, err);
3731 kvm_requeue_exception(vcpu, vector);
3733 case SVM_EXITINTINFO_TYPE_INTR:
3734 kvm_queue_interrupt(vcpu, vector, false);
3741 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3743 struct vcpu_svm *svm = to_svm(vcpu);
3744 struct vmcb_control_area *control = &svm->vmcb->control;
3746 control->exit_int_info = control->event_inj;
3747 control->exit_int_info_err = control->event_inj_err;
3748 control->event_inj = 0;
3749 svm_complete_interrupts(vcpu);
3752 static int svm_vcpu_pre_run(struct kvm_vcpu *vcpu)
3757 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
3759 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_MSR &&
3760 to_svm(vcpu)->vmcb->control.exit_info_1)
3761 return handle_fastpath_set_msr_irqoff(vcpu);
3763 return EXIT_FASTPATH_NONE;
3766 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
3768 struct vcpu_svm *svm = to_svm(vcpu);
3769 unsigned long vmcb_pa = svm->current_vmcb->pa;
3771 guest_state_enter_irqoff();
3773 if (sev_es_guest(vcpu->kvm)) {
3774 __svm_sev_es_vcpu_run(vmcb_pa);
3776 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3779 * Use a single vmcb (vmcb01 because it's always valid) for
3780 * context switching guest state via VMLOAD/VMSAVE, that way
3781 * the state doesn't need to be copied between vmcb01 and
3782 * vmcb02 when switching vmcbs for nested virtualization.
3784 vmload(svm->vmcb01.pa);
3785 __svm_vcpu_run(vmcb_pa, (unsigned long *)&vcpu->arch.regs);
3786 vmsave(svm->vmcb01.pa);
3788 vmload(__sme_page_pa(sd->save_area));
3791 guest_state_exit_irqoff();
3794 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
3796 struct vcpu_svm *svm = to_svm(vcpu);
3798 trace_kvm_entry(vcpu);
3800 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3801 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3802 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3805 * Disable singlestep if we're injecting an interrupt/exception.
3806 * We don't want our modified rflags to be pushed on the stack where
3807 * we might not be able to easily reset them if we disabled NMI
3810 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
3812 * Event injection happens before external interrupts cause a
3813 * vmexit and interrupts are disabled here, so smp_send_reschedule
3814 * is enough to force an immediate vmexit.
3816 disable_nmi_singlestep(svm);
3817 smp_send_reschedule(vcpu->cpu);
3822 sync_lapic_to_cr8(vcpu);
3824 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
3825 svm->vmcb->control.asid = svm->asid;
3826 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3828 svm->vmcb->save.cr2 = vcpu->arch.cr2;
3830 svm_hv_update_vp_id(svm->vmcb, vcpu);
3833 * Run with all-zero DR6 unless needed, so that we can get the exact cause
3836 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
3837 svm_set_dr6(svm, vcpu->arch.dr6);
3839 svm_set_dr6(svm, DR6_ACTIVE_LOW);
3842 kvm_load_guest_xsave_state(vcpu);
3844 kvm_wait_lapic_expire(vcpu);
3847 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3848 * it's non-zero. Since vmentry is serialising on affected CPUs, there
3849 * is no need to worry about the conditional branch over the wrmsr
3850 * being speculatively taken.
3852 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3853 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
3855 svm_vcpu_enter_exit(vcpu);
3858 * We do not use IBRS in the kernel. If this vCPU has used the
3859 * SPEC_CTRL MSR it may have left it on; save the value and
3860 * turn it off. This is much more efficient than blindly adding
3861 * it to the atomic save/restore list. Especially as the former
3862 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
3864 * For non-nested case:
3865 * If the L01 MSR bitmap does not intercept the MSR, then we need to
3869 * If the L02 MSR bitmap does not intercept the MSR, then we need to
3872 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL) &&
3873 unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
3874 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
3876 if (!sev_es_guest(vcpu->kvm))
3879 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3880 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
3882 if (!sev_es_guest(vcpu->kvm)) {
3883 vcpu->arch.cr2 = svm->vmcb->save.cr2;
3884 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
3885 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
3886 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
3888 vcpu->arch.regs_dirty = 0;
3890 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3891 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
3893 kvm_load_host_xsave_state(vcpu);
3896 /* Any pending NMI will happen here */
3898 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3899 kvm_after_interrupt(vcpu);
3901 sync_cr8_to_lapic(vcpu);
3904 if (is_guest_mode(vcpu)) {
3905 nested_sync_control_from_vmcb02(svm);
3907 /* Track VMRUNs that have made past consistency checking */
3908 if (svm->nested.nested_run_pending &&
3909 svm->vmcb->control.exit_code != SVM_EXIT_ERR)
3910 ++vcpu->stat.nested_run;
3912 svm->nested.nested_run_pending = 0;
3915 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
3916 vmcb_mark_all_clean(svm->vmcb);
3918 /* if exit due to PF check for async PF */
3919 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
3920 vcpu->arch.apf.host_apf_flags =
3921 kvm_read_and_reset_apf_flags();
3923 vcpu->arch.regs_avail &= ~SVM_REGS_LAZY_LOAD_SET;
3926 * We need to handle MC intercepts here before the vcpu has a chance to
3927 * change the physical cpu
3929 if (unlikely(svm->vmcb->control.exit_code ==
3930 SVM_EXIT_EXCP_BASE + MC_VECTOR))
3931 svm_handle_mce(vcpu);
3933 svm_complete_interrupts(vcpu);
3935 if (is_guest_mode(vcpu))
3936 return EXIT_FASTPATH_NONE;
3938 return svm_exit_handlers_fastpath(vcpu);
3941 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3944 struct vcpu_svm *svm = to_svm(vcpu);
3948 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
3949 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
3951 hv_track_root_tdp(vcpu, root_hpa);
3953 cr3 = vcpu->arch.cr3;
3954 } else if (vcpu->arch.mmu->root_role.level >= PT64_ROOT_4LEVEL) {
3955 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
3957 /* PCID in the guest should be impossible with a 32-bit MMU. */
3958 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
3962 svm->vmcb->save.cr3 = cr3;
3963 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
3966 static int is_disabled(void)
3970 rdmsrl(MSR_VM_CR, vm_cr);
3971 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
3978 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
3981 * Patch in the VMMCALL instruction:
3983 hypercall[0] = 0x0f;
3984 hypercall[1] = 0x01;
3985 hypercall[2] = 0xd9;
3988 static int __init svm_check_processor_compat(void)
3994 * The kvm parameter can be NULL (module initialization, or invocation before
3995 * VM creation). Be sure to check the kvm parameter before using it.
3997 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4000 case MSR_IA32_MCG_EXT_CTL:
4001 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4003 case MSR_IA32_SMBASE:
4004 /* SEV-ES guests do not support SMM, so report false */
4005 if (kvm && sev_es_guest(kvm))
4015 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4020 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4022 struct vcpu_svm *svm = to_svm(vcpu);
4023 struct kvm_cpuid_entry2 *best;
4024 struct kvm *kvm = vcpu->kvm;
4026 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4027 boot_cpu_has(X86_FEATURE_XSAVE) &&
4028 boot_cpu_has(X86_FEATURE_XSAVES);
4030 /* Update nrips enabled cache */
4031 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
4032 guest_cpuid_has(vcpu, X86_FEATURE_NRIPS);
4034 svm->tsc_scaling_enabled = tsc_scaling && guest_cpuid_has(vcpu, X86_FEATURE_TSCRATEMSR);
4035 svm->lbrv_enabled = lbrv && guest_cpuid_has(vcpu, X86_FEATURE_LBRV);
4037 svm->v_vmload_vmsave_enabled = vls && guest_cpuid_has(vcpu, X86_FEATURE_V_VMSAVE_VMLOAD);
4039 svm->pause_filter_enabled = kvm_cpu_cap_has(X86_FEATURE_PAUSEFILTER) &&
4040 guest_cpuid_has(vcpu, X86_FEATURE_PAUSEFILTER);
4042 svm->pause_threshold_enabled = kvm_cpu_cap_has(X86_FEATURE_PFTHRESHOLD) &&
4043 guest_cpuid_has(vcpu, X86_FEATURE_PFTHRESHOLD);
4045 svm->vgif_enabled = vgif && guest_cpuid_has(vcpu, X86_FEATURE_VGIF);
4047 svm_recalc_instruction_intercepts(vcpu, svm);
4049 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4050 if (sev_guest(vcpu->kvm)) {
4051 best = kvm_find_cpuid_entry(vcpu, 0x8000001F, 0);
4053 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4056 if (kvm_vcpu_apicv_active(vcpu)) {
4058 * AVIC does not work with an x2APIC mode guest. If the X2APIC feature
4059 * is exposed to the guest, disable AVIC.
4061 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC))
4062 kvm_set_apicv_inhibit(kvm, APICV_INHIBIT_REASON_X2APIC);
4064 init_vmcb_after_set_cpuid(vcpu);
4067 static bool svm_has_wbinvd_exit(void)
4072 #define PRE_EX(exit) { .exit_code = (exit), \
4073 .stage = X86_ICPT_PRE_EXCEPT, }
4074 #define POST_EX(exit) { .exit_code = (exit), \
4075 .stage = X86_ICPT_POST_EXCEPT, }
4076 #define POST_MEM(exit) { .exit_code = (exit), \
4077 .stage = X86_ICPT_POST_MEMACCESS, }
4079 static const struct __x86_intercept {
4081 enum x86_intercept_stage stage;
4082 } x86_intercept_map[] = {
4083 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4084 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4085 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4086 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4087 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4088 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4089 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4090 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4091 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4092 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4093 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4094 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4095 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4096 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4097 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4098 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4099 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4100 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4101 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4102 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4103 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4104 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4105 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4106 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4107 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4108 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4109 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4110 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4111 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4112 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4113 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4114 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4115 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4116 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4117 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4118 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4119 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4120 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4121 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4122 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4123 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4124 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4125 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4126 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4127 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4128 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4129 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4136 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4137 struct x86_instruction_info *info,
4138 enum x86_intercept_stage stage,
4139 struct x86_exception *exception)
4141 struct vcpu_svm *svm = to_svm(vcpu);
4142 int vmexit, ret = X86EMUL_CONTINUE;
4143 struct __x86_intercept icpt_info;
4144 struct vmcb *vmcb = svm->vmcb;
4146 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4149 icpt_info = x86_intercept_map[info->intercept];
4151 if (stage != icpt_info.stage)
4154 switch (icpt_info.exit_code) {
4155 case SVM_EXIT_READ_CR0:
4156 if (info->intercept == x86_intercept_cr_read)
4157 icpt_info.exit_code += info->modrm_reg;
4159 case SVM_EXIT_WRITE_CR0: {
4160 unsigned long cr0, val;
4162 if (info->intercept == x86_intercept_cr_write)
4163 icpt_info.exit_code += info->modrm_reg;
4165 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4166 info->intercept == x86_intercept_clts)
4169 if (!(vmcb12_is_intercept(&svm->nested.ctl,
4170 INTERCEPT_SELECTIVE_CR0)))
4173 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4174 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4176 if (info->intercept == x86_intercept_lmsw) {
4179 /* lmsw can't clear PE - catch this here */
4180 if (cr0 & X86_CR0_PE)
4185 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4189 case SVM_EXIT_READ_DR0:
4190 case SVM_EXIT_WRITE_DR0:
4191 icpt_info.exit_code += info->modrm_reg;
4194 if (info->intercept == x86_intercept_wrmsr)
4195 vmcb->control.exit_info_1 = 1;
4197 vmcb->control.exit_info_1 = 0;
4199 case SVM_EXIT_PAUSE:
4201 * We get this for NOP only, but pause
4202 * is rep not, check this here
4204 if (info->rep_prefix != REPE_PREFIX)
4207 case SVM_EXIT_IOIO: {
4211 if (info->intercept == x86_intercept_in ||
4212 info->intercept == x86_intercept_ins) {
4213 exit_info = ((info->src_val & 0xffff) << 16) |
4215 bytes = info->dst_bytes;
4217 exit_info = (info->dst_val & 0xffff) << 16;
4218 bytes = info->src_bytes;
4221 if (info->intercept == x86_intercept_outs ||
4222 info->intercept == x86_intercept_ins)
4223 exit_info |= SVM_IOIO_STR_MASK;
4225 if (info->rep_prefix)
4226 exit_info |= SVM_IOIO_REP_MASK;
4228 bytes = min(bytes, 4u);
4230 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4232 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4234 vmcb->control.exit_info_1 = exit_info;
4235 vmcb->control.exit_info_2 = info->next_rip;
4243 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4244 if (static_cpu_has(X86_FEATURE_NRIPS))
4245 vmcb->control.next_rip = info->next_rip;
4246 vmcb->control.exit_code = icpt_info.exit_code;
4247 vmexit = nested_svm_exit_handled(svm);
4249 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4256 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4260 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4262 if (!kvm_pause_in_guest(vcpu->kvm))
4263 shrink_ple_window(vcpu);
4266 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4268 /* [63:9] are reserved. */
4269 vcpu->arch.mcg_cap &= 0x1ff;
4272 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4274 struct vcpu_svm *svm = to_svm(vcpu);
4276 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4280 return is_smm(vcpu);
4283 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4285 struct vcpu_svm *svm = to_svm(vcpu);
4286 if (svm->nested.nested_run_pending)
4289 if (svm_smi_blocked(vcpu))
4292 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4293 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4299 static int svm_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
4301 struct vcpu_svm *svm = to_svm(vcpu);
4302 struct kvm_host_map map_save;
4305 if (!is_guest_mode(vcpu))
4308 /* FED8h - SVM Guest */
4309 put_smstate(u64, smstate, 0x7ed8, 1);
4310 /* FEE0h - SVM Guest VMCB Physical Address */
4311 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb12_gpa);
4313 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4314 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4315 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4317 ret = nested_svm_simple_vmexit(svm, SVM_EXIT_SW);
4322 * KVM uses VMCB01 to store L1 host state while L2 runs but
4323 * VMCB01 is going to be used during SMM and thus the state will
4324 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4325 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4326 * format of the area is identical to guest save area offsetted
4327 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4328 * within 'struct vmcb'). Note: HSAVE area may also be used by
4329 * L1 hypervisor to save additional host context (e.g. KVM does
4330 * that, see svm_prepare_switch_to_guest()) which must be
4333 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4334 &map_save) == -EINVAL)
4337 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4339 svm_copy_vmrun_state(map_save.hva + 0x400,
4340 &svm->vmcb01.ptr->save);
4342 kvm_vcpu_unmap(vcpu, &map_save, true);
4346 static int svm_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
4348 struct vcpu_svm *svm = to_svm(vcpu);
4349 struct kvm_host_map map, map_save;
4350 u64 saved_efer, vmcb12_gpa;
4351 struct vmcb *vmcb12;
4354 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4357 /* Non-zero if SMI arrived while vCPU was in guest mode. */
4358 if (!GET_SMSTATE(u64, smstate, 0x7ed8))
4361 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4364 saved_efer = GET_SMSTATE(u64, smstate, 0x7ed0);
4365 if (!(saved_efer & EFER_SVME))
4368 vmcb12_gpa = GET_SMSTATE(u64, smstate, 0x7ee0);
4369 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map) == -EINVAL)
4373 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save) == -EINVAL)
4376 if (svm_allocate_nested(svm))
4380 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4381 * used during SMM (see svm_enter_smm())
4384 svm_copy_vmrun_state(&svm->vmcb01.ptr->save, map_save.hva + 0x400);
4387 * Enter the nested guest now
4390 vmcb_mark_all_dirty(svm->vmcb01.ptr);
4393 nested_copy_vmcb_control_to_cache(svm, &vmcb12->control);
4394 nested_copy_vmcb_save_to_cache(svm, &vmcb12->save);
4395 ret = enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, false);
4400 svm->nested.nested_run_pending = 1;
4403 kvm_vcpu_unmap(vcpu, &map_save, true);
4405 kvm_vcpu_unmap(vcpu, &map, true);
4409 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4411 struct vcpu_svm *svm = to_svm(vcpu);
4413 if (!gif_set(svm)) {
4415 svm_set_intercept(svm, INTERCEPT_STGI);
4416 /* STGI will cause a vm exit */
4418 /* We must be in SMM; RSM will cause a vmexit anyway. */
4422 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
4423 void *insn, int insn_len)
4425 bool smep, smap, is_user;
4429 /* Emulation is always possible when KVM has access to all guest state. */
4430 if (!sev_guest(vcpu->kvm))
4433 /* #UD and #GP should never be intercepted for SEV guests. */
4434 WARN_ON_ONCE(emul_type & (EMULTYPE_TRAP_UD |
4435 EMULTYPE_TRAP_UD_FORCED |
4436 EMULTYPE_VMWARE_GP));
4439 * Emulation is impossible for SEV-ES guests as KVM doesn't have access
4440 * to guest register state.
4442 if (sev_es_guest(vcpu->kvm))
4446 * Emulation is possible if the instruction is already decoded, e.g.
4447 * when completing I/O after returning from userspace.
4449 if (emul_type & EMULTYPE_NO_DECODE)
4453 * Emulation is possible for SEV guests if and only if a prefilled
4454 * buffer containing the bytes of the intercepted instruction is
4455 * available. SEV guest memory is encrypted with a guest specific key
4456 * and cannot be decrypted by KVM, i.e. KVM would read cyphertext and
4459 * Inject #UD if KVM reached this point without an instruction buffer.
4460 * In practice, this path should never be hit by a well-behaved guest,
4461 * e.g. KVM doesn't intercept #UD or #GP for SEV guests, but this path
4462 * is still theoretically reachable, e.g. via unaccelerated fault-like
4463 * AVIC access, and needs to be handled by KVM to avoid putting the
4464 * guest into an infinite loop. Injecting #UD is somewhat arbitrary,
4465 * but its the least awful option given lack of insight into the guest.
4467 if (unlikely(!insn)) {
4468 kvm_queue_exception(vcpu, UD_VECTOR);
4473 * Emulate for SEV guests if the insn buffer is not empty. The buffer
4474 * will be empty if the DecodeAssist microcode cannot fetch bytes for
4475 * the faulting instruction because the code fetch itself faulted, e.g.
4476 * the guest attempted to fetch from emulated MMIO or a guest page
4477 * table used to translate CS:RIP resides in emulated MMIO.
4479 if (likely(insn_len))
4483 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4486 * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is
4487 * possible that CPU microcode implementing DecodeAssist will fail to
4488 * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly
4489 * be '0'. This happens because microcode reads CS:RIP using a _data_
4490 * loap uop with CPL=0 privileges. If the load hits a SMAP #PF, ucode
4491 * gives up and does not fill the instruction bytes buffer.
4493 * As above, KVM reaches this point iff the VM is an SEV guest, the CPU
4494 * supports DecodeAssist, a #NPF was raised, KVM's page fault handler
4495 * triggered emulation (e.g. for MMIO), and the CPU returned 0 in the
4496 * GuestIntrBytes field of the VMCB.
4498 * This does _not_ mean that the erratum has been encountered, as the
4499 * DecodeAssist will also fail if the load for CS:RIP hits a legitimate
4500 * #PF, e.g. if the guest attempt to execute from emulated MMIO and
4501 * encountered a reserved/not-present #PF.
4503 * To hit the erratum, the following conditions must be true:
4504 * 1. CR4.SMAP=1 (obviously).
4505 * 2. CR4.SMEP=0 || CPL=3. If SMEP=1 and CPL<3, the erratum cannot
4506 * have been hit as the guest would have encountered a SMEP
4507 * violation #PF, not a #NPF.
4508 * 3. The #NPF is not due to a code fetch, in which case failure to
4509 * retrieve the instruction bytes is legitimate (see abvoe).
4511 * In addition, don't apply the erratum workaround if the #NPF occurred
4512 * while translating guest page tables (see below).
4514 error_code = to_svm(vcpu)->vmcb->control.exit_info_1;
4515 if (error_code & (PFERR_GUEST_PAGE_MASK | PFERR_FETCH_MASK))
4518 cr4 = kvm_read_cr4(vcpu);
4519 smep = cr4 & X86_CR4_SMEP;
4520 smap = cr4 & X86_CR4_SMAP;
4521 is_user = svm_get_cpl(vcpu) == 3;
4522 if (smap && (!smep || is_user)) {
4523 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
4526 * If the fault occurred in userspace, arbitrarily inject #GP
4527 * to avoid killing the guest and to hopefully avoid confusing
4528 * the guest kernel too much, e.g. injecting #PF would not be
4529 * coherent with respect to the guest's page tables. Request
4530 * triple fault if the fault occurred in the kernel as there's
4531 * no fault that KVM can inject without confusing the guest.
4532 * In practice, the triple fault is moot as no sane SEV kernel
4533 * will execute from user memory while also running with SMAP=1.
4536 kvm_inject_gp(vcpu, 0);
4538 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4543 * If the erratum was not hit, simply resume the guest and let it fault
4544 * again. While awful, e.g. the vCPU may get stuck in an infinite loop
4545 * if the fault is at CPL=0, it's the lesser of all evils. Exiting to
4546 * userspace will kill the guest, and letting the emulator read garbage
4547 * will yield random behavior and potentially corrupt the guest.
4549 * Simply resuming the guest is technically not a violation of the SEV
4550 * architecture. AMD's APM states that all code fetches and page table
4551 * accesses for SEV guest are encrypted, regardless of the C-Bit. The
4552 * APM also states that encrypted accesses to MMIO are "ignored", but
4553 * doesn't explicitly define "ignored", i.e. doing nothing and letting
4554 * the guest spin is technically "ignoring" the access.
4559 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4561 struct vcpu_svm *svm = to_svm(vcpu);
4564 * TODO: Last condition latch INIT signals on vCPU when
4565 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
4566 * To properly emulate the INIT intercept,
4567 * svm_check_nested_events() should call nested_svm_vmexit()
4568 * if an INIT signal is pending.
4570 return !gif_set(svm) ||
4571 (vmcb_is_intercept(&svm->vmcb->control, INTERCEPT_INIT));
4574 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4576 if (!sev_es_guest(vcpu->kvm))
4577 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4579 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4582 static void svm_vm_destroy(struct kvm *kvm)
4584 avic_vm_destroy(kvm);
4585 sev_vm_destroy(kvm);
4588 static int svm_vm_init(struct kvm *kvm)
4590 if (!pause_filter_count || !pause_filter_thresh)
4591 kvm->arch.pause_in_guest = true;
4594 int ret = avic_vm_init(kvm);
4602 static struct kvm_x86_ops svm_x86_ops __initdata = {
4605 .hardware_unsetup = svm_hardware_unsetup,
4606 .hardware_enable = svm_hardware_enable,
4607 .hardware_disable = svm_hardware_disable,
4608 .has_emulated_msr = svm_has_emulated_msr,
4610 .vcpu_create = svm_vcpu_create,
4611 .vcpu_free = svm_vcpu_free,
4612 .vcpu_reset = svm_vcpu_reset,
4614 .vm_size = sizeof(struct kvm_svm),
4615 .vm_init = svm_vm_init,
4616 .vm_destroy = svm_vm_destroy,
4618 .prepare_switch_to_guest = svm_prepare_switch_to_guest,
4619 .vcpu_load = svm_vcpu_load,
4620 .vcpu_put = svm_vcpu_put,
4621 .vcpu_blocking = avic_vcpu_blocking,
4622 .vcpu_unblocking = avic_vcpu_unblocking,
4624 .update_exception_bitmap = svm_update_exception_bitmap,
4625 .get_msr_feature = svm_get_msr_feature,
4626 .get_msr = svm_get_msr,
4627 .set_msr = svm_set_msr,
4628 .get_segment_base = svm_get_segment_base,
4629 .get_segment = svm_get_segment,
4630 .set_segment = svm_set_segment,
4631 .get_cpl = svm_get_cpl,
4632 .get_cs_db_l_bits = svm_get_cs_db_l_bits,
4633 .set_cr0 = svm_set_cr0,
4634 .post_set_cr3 = sev_post_set_cr3,
4635 .is_valid_cr4 = svm_is_valid_cr4,
4636 .set_cr4 = svm_set_cr4,
4637 .set_efer = svm_set_efer,
4638 .get_idt = svm_get_idt,
4639 .set_idt = svm_set_idt,
4640 .get_gdt = svm_get_gdt,
4641 .set_gdt = svm_set_gdt,
4642 .set_dr7 = svm_set_dr7,
4643 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4644 .cache_reg = svm_cache_reg,
4645 .get_rflags = svm_get_rflags,
4646 .set_rflags = svm_set_rflags,
4647 .get_if_flag = svm_get_if_flag,
4649 .flush_tlb_all = svm_flush_tlb_current,
4650 .flush_tlb_current = svm_flush_tlb_current,
4651 .flush_tlb_gva = svm_flush_tlb_gva,
4652 .flush_tlb_guest = svm_flush_tlb_current,
4654 .vcpu_pre_run = svm_vcpu_pre_run,
4655 .vcpu_run = svm_vcpu_run,
4656 .handle_exit = svm_handle_exit,
4657 .skip_emulated_instruction = svm_skip_emulated_instruction,
4658 .update_emulated_instruction = NULL,
4659 .set_interrupt_shadow = svm_set_interrupt_shadow,
4660 .get_interrupt_shadow = svm_get_interrupt_shadow,
4661 .patch_hypercall = svm_patch_hypercall,
4662 .inject_irq = svm_inject_irq,
4663 .inject_nmi = svm_inject_nmi,
4664 .queue_exception = svm_queue_exception,
4665 .cancel_injection = svm_cancel_injection,
4666 .interrupt_allowed = svm_interrupt_allowed,
4667 .nmi_allowed = svm_nmi_allowed,
4668 .get_nmi_mask = svm_get_nmi_mask,
4669 .set_nmi_mask = svm_set_nmi_mask,
4670 .enable_nmi_window = svm_enable_nmi_window,
4671 .enable_irq_window = svm_enable_irq_window,
4672 .update_cr8_intercept = svm_update_cr8_intercept,
4673 .refresh_apicv_exec_ctrl = avic_refresh_apicv_exec_ctrl,
4674 .check_apicv_inhibit_reasons = avic_check_apicv_inhibit_reasons,
4675 .apicv_post_state_restore = avic_apicv_post_state_restore,
4677 .get_mt_mask = svm_get_mt_mask,
4678 .get_exit_info = svm_get_exit_info,
4680 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
4682 .has_wbinvd_exit = svm_has_wbinvd_exit,
4684 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
4685 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
4686 .write_tsc_offset = svm_write_tsc_offset,
4687 .write_tsc_multiplier = svm_write_tsc_multiplier,
4689 .load_mmu_pgd = svm_load_mmu_pgd,
4691 .check_intercept = svm_check_intercept,
4692 .handle_exit_irqoff = svm_handle_exit_irqoff,
4694 .request_immediate_exit = __kvm_request_immediate_exit,
4696 .sched_in = svm_sched_in,
4698 .nested_ops = &svm_nested_ops,
4700 .deliver_interrupt = svm_deliver_interrupt,
4701 .pi_update_irte = avic_pi_update_irte,
4702 .setup_mce = svm_setup_mce,
4704 .smi_allowed = svm_smi_allowed,
4705 .enter_smm = svm_enter_smm,
4706 .leave_smm = svm_leave_smm,
4707 .enable_smi_window = svm_enable_smi_window,
4709 .mem_enc_ioctl = sev_mem_enc_ioctl,
4710 .mem_enc_register_region = sev_mem_enc_register_region,
4711 .mem_enc_unregister_region = sev_mem_enc_unregister_region,
4712 .guest_memory_reclaimed = sev_guest_memory_reclaimed,
4714 .vm_copy_enc_context_from = sev_vm_copy_enc_context_from,
4715 .vm_move_enc_context_from = sev_vm_move_enc_context_from,
4717 .can_emulate_instruction = svm_can_emulate_instruction,
4719 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
4721 .msr_filter_changed = svm_msr_filter_changed,
4722 .complete_emulated_msr = svm_complete_emulated_msr,
4724 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
4725 .vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
4729 * The default MMIO mask is a single bit (excluding the present bit),
4730 * which could conflict with the memory encryption bit. Check for
4731 * memory encryption support and override the default MMIO mask if
4732 * memory encryption is enabled.
4734 static __init void svm_adjust_mmio_mask(void)
4736 unsigned int enc_bit, mask_bit;
4739 /* If there is no memory encryption support, use existing mask */
4740 if (cpuid_eax(0x80000000) < 0x8000001f)
4743 /* If memory encryption is not enabled, use existing mask */
4744 rdmsrl(MSR_AMD64_SYSCFG, msr);
4745 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
4748 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
4749 mask_bit = boot_cpu_data.x86_phys_bits;
4751 /* Increment the mask bit if it is the same as the encryption bit */
4752 if (enc_bit == mask_bit)
4756 * If the mask bit location is below 52, then some bits above the
4757 * physical addressing limit will always be reserved, so use the
4758 * rsvd_bits() function to generate the mask. This mask, along with
4759 * the present bit, will be used to generate a page fault with
4762 * If the mask bit location is 52 (or above), then clear the mask.
4764 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
4766 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
4769 static __init void svm_set_cpu_caps(void)
4775 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
4777 kvm_cpu_cap_set(X86_FEATURE_SVM);
4778 kvm_cpu_cap_set(X86_FEATURE_VMCBCLEAN);
4781 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
4784 kvm_cpu_cap_set(X86_FEATURE_NPT);
4787 kvm_cpu_cap_set(X86_FEATURE_TSCRATEMSR);
4790 kvm_cpu_cap_set(X86_FEATURE_V_VMSAVE_VMLOAD);
4792 kvm_cpu_cap_set(X86_FEATURE_LBRV);
4794 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER))
4795 kvm_cpu_cap_set(X86_FEATURE_PAUSEFILTER);
4797 if (boot_cpu_has(X86_FEATURE_PFTHRESHOLD))
4798 kvm_cpu_cap_set(X86_FEATURE_PFTHRESHOLD);
4801 kvm_cpu_cap_set(X86_FEATURE_VGIF);
4803 /* Nested VM can receive #VMEXIT instead of triggering #GP */
4804 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
4807 /* CPUID 0x80000008 */
4808 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
4809 boot_cpu_has(X86_FEATURE_AMD_SSBD))
4810 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
4812 /* AMD PMU PERFCTR_CORE CPUID */
4813 if (enable_pmu && boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
4814 kvm_cpu_cap_set(X86_FEATURE_PERFCTR_CORE);
4816 /* CPUID 0x8000001F (SME/SEV features) */
4820 static __init int svm_hardware_setup(void)
4823 struct page *iopm_pages;
4826 unsigned int order = get_order(IOPM_SIZE);
4829 * NX is required for shadow paging and for NPT if the NX huge pages
4830 * mitigation is enabled.
4832 if (!boot_cpu_has(X86_FEATURE_NX)) {
4833 pr_err_ratelimited("NX (Execute Disable) not supported\n");
4836 kvm_enable_efer_bits(EFER_NX);
4838 iopm_pages = alloc_pages(GFP_KERNEL, order);
4843 iopm_va = page_address(iopm_pages);
4844 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
4845 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
4847 init_msrpm_offsets();
4849 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
4851 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
4852 kvm_enable_efer_bits(EFER_FFXSR);
4855 if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
4856 tsc_scaling = false;
4858 pr_info("TSC scaling supported\n");
4859 kvm_has_tsc_control = true;
4862 kvm_max_tsc_scaling_ratio = SVM_TSC_RATIO_MAX;
4863 kvm_tsc_scaling_ratio_frac_bits = 32;
4865 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
4867 /* Check for pause filtering support */
4868 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
4869 pause_filter_count = 0;
4870 pause_filter_thresh = 0;
4871 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
4872 pause_filter_thresh = 0;
4876 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
4877 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
4881 * KVM's MMU doesn't support using 2-level paging for itself, and thus
4882 * NPT isn't supported if the host is using 2-level paging since host
4883 * CR4 is unchanged on VMRUN.
4885 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
4886 npt_enabled = false;
4888 if (!boot_cpu_has(X86_FEATURE_NPT))
4889 npt_enabled = false;
4891 /* Force VM NPT level equal to the host's paging level */
4892 kvm_configure_mmu(npt_enabled, get_npt_level(),
4893 get_npt_level(), PG_LEVEL_1G);
4894 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
4896 /* Setup shadow_me_value and shadow_me_mask */
4897 kvm_mmu_set_me_spte_mask(sme_me_mask, sme_me_mask);
4899 /* Note, SEV setup consumes npt_enabled. */
4900 sev_hardware_setup();
4902 svm_hv_hardware_setup();
4904 svm_adjust_mmio_mask();
4906 for_each_possible_cpu(cpu) {
4907 r = svm_cpu_init(cpu);
4913 if (!boot_cpu_has(X86_FEATURE_NRIPS))
4917 enable_apicv = avic = avic && npt_enabled && (boot_cpu_has(X86_FEATURE_AVIC) || force_avic);
4920 if (!boot_cpu_has(X86_FEATURE_AVIC)) {
4921 pr_warn("AVIC is not supported in CPUID but force enabled");
4922 pr_warn("Your system might crash and burn");
4924 pr_info("AVIC enabled\n");
4926 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
4928 svm_x86_ops.vcpu_blocking = NULL;
4929 svm_x86_ops.vcpu_unblocking = NULL;
4930 svm_x86_ops.vcpu_get_apicv_inhibit_reasons = NULL;
4935 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
4936 !IS_ENABLED(CONFIG_X86_64)) {
4939 pr_info("Virtual VMLOAD VMSAVE supported\n");
4943 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
4944 svm_gp_erratum_intercept = false;
4947 if (!boot_cpu_has(X86_FEATURE_VGIF))
4950 pr_info("Virtual GIF supported\n");
4954 if (!boot_cpu_has(X86_FEATURE_LBRV))
4957 pr_info("LBR virtualization supported\n");
4961 pr_info("PMU virtualization is disabled\n");
4966 * It seems that on AMD processors PTE's accessed bit is
4967 * being set by the CPU hardware before the NPF vmexit.
4968 * This is not expected behaviour and our tests fail because
4970 * A workaround here is to disable support for
4971 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
4972 * In this case userspace can know if there is support using
4973 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
4975 * If future AMD CPU models change the behaviour described above,
4976 * this variable can be changed accordingly
4978 allow_smaller_maxphyaddr = !npt_enabled;
4983 svm_hardware_unsetup();
4988 static struct kvm_x86_init_ops svm_init_ops __initdata = {
4989 .cpu_has_kvm_support = has_svm,
4990 .disabled_by_bios = is_disabled,
4991 .hardware_setup = svm_hardware_setup,
4992 .check_processor_compatibility = svm_check_processor_compat,
4994 .runtime_ops = &svm_x86_ops,
4995 .pmu_ops = &amd_pmu_ops,
4998 static int __init svm_init(void)
5000 __unused_size_checks();
5002 return kvm_init(&svm_init_ops, sizeof(struct vcpu_svm),
5003 __alignof__(struct vcpu_svm), THIS_MODULE);
5006 static void __exit svm_exit(void)
5011 module_init(svm_init)
5012 module_exit(svm_exit)