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>
30 #include <asm/perf_event.h>
31 #include <asm/tlbflush.h>
33 #include <asm/debugreg.h>
34 #include <asm/kvm_para.h>
35 #include <asm/irq_remapping.h>
36 #include <asm/spec-ctrl.h>
37 #include <asm/cpu_device_id.h>
38 #include <asm/traps.h>
40 #include <asm/virtext.h>
46 #include "kvm_onhyperv.h"
47 #include "svm_onhyperv.h"
49 MODULE_AUTHOR("Qumranet");
50 MODULE_LICENSE("GPL");
53 static const struct x86_cpu_id svm_cpu_id[] = {
54 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
57 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
60 #define SEG_TYPE_LDT 2
61 #define SEG_TYPE_BUSY_TSS16 3
63 #define SVM_FEATURE_LBRV (1 << 1)
64 #define SVM_FEATURE_SVML (1 << 2)
65 #define SVM_FEATURE_TSC_RATE (1 << 4)
66 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
67 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
68 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
69 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
71 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
73 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
74 #define TSC_RATIO_MIN 0x0000000000000001ULL
75 #define TSC_RATIO_MAX 0x000000ffffffffffULL
77 static bool erratum_383_found __read_mostly;
79 u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
82 * Set osvw_len to higher value when updated Revision Guides
83 * are published and we know what the new status bits are
85 static uint64_t osvw_len = 4, osvw_status;
87 static DEFINE_PER_CPU(u64, current_tsc_ratio);
88 #define TSC_RATIO_DEFAULT 0x0100000000ULL
90 static const struct svm_direct_access_msrs {
91 u32 index; /* Index of the MSR */
92 bool always; /* True if intercept is initially cleared */
93 } direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
94 { .index = MSR_STAR, .always = true },
95 { .index = MSR_IA32_SYSENTER_CS, .always = true },
96 { .index = MSR_IA32_SYSENTER_EIP, .always = false },
97 { .index = MSR_IA32_SYSENTER_ESP, .always = false },
99 { .index = MSR_GS_BASE, .always = true },
100 { .index = MSR_FS_BASE, .always = true },
101 { .index = MSR_KERNEL_GS_BASE, .always = true },
102 { .index = MSR_LSTAR, .always = true },
103 { .index = MSR_CSTAR, .always = true },
104 { .index = MSR_SYSCALL_MASK, .always = true },
106 { .index = MSR_IA32_SPEC_CTRL, .always = false },
107 { .index = MSR_IA32_PRED_CMD, .always = false },
108 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
109 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
110 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
111 { .index = MSR_IA32_LASTINTTOIP, .always = false },
112 { .index = MSR_EFER, .always = false },
113 { .index = MSR_IA32_CR_PAT, .always = false },
114 { .index = MSR_AMD64_SEV_ES_GHCB, .always = true },
115 { .index = MSR_INVALID, .always = false },
119 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
120 * pause_filter_count: On processors that support Pause filtering(indicated
121 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
122 * count value. On VMRUN this value is loaded into an internal counter.
123 * Each time a pause instruction is executed, this counter is decremented
124 * until it reaches zero at which time a #VMEXIT is generated if pause
125 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
126 * Intercept Filtering for more details.
127 * This also indicate if ple logic enabled.
129 * pause_filter_thresh: In addition, some processor families support advanced
130 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
131 * the amount of time a guest is allowed to execute in a pause loop.
132 * In this mode, a 16-bit pause filter threshold field is added in the
133 * VMCB. The threshold value is a cycle count that is used to reset the
134 * pause counter. As with simple pause filtering, VMRUN loads the pause
135 * count value from VMCB into an internal counter. Then, on each pause
136 * instruction the hardware checks the elapsed number of cycles since
137 * the most recent pause instruction against the pause filter threshold.
138 * If the elapsed cycle count is greater than the pause filter threshold,
139 * then the internal pause count is reloaded from the VMCB and execution
140 * continues. If the elapsed cycle count is less than the pause filter
141 * threshold, then the internal pause count is decremented. If the count
142 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
143 * triggered. If advanced pause filtering is supported and pause filter
144 * threshold field is set to zero, the filter will operate in the simpler,
148 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
149 module_param(pause_filter_thresh, ushort, 0444);
151 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
152 module_param(pause_filter_count, ushort, 0444);
154 /* Default doubles per-vcpu window every exit. */
155 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
156 module_param(pause_filter_count_grow, ushort, 0444);
158 /* Default resets per-vcpu window every exit to pause_filter_count. */
159 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
160 module_param(pause_filter_count_shrink, ushort, 0444);
162 /* Default is to compute the maximum so we can never overflow. */
163 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
164 module_param(pause_filter_count_max, ushort, 0444);
167 * Use nested page tables by default. Note, NPT may get forced off by
168 * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
170 bool npt_enabled = true;
171 module_param_named(npt, npt_enabled, bool, 0444);
173 /* allow nested virtualization in KVM/SVM */
174 static int nested = true;
175 module_param(nested, int, S_IRUGO);
177 /* enable/disable Next RIP Save */
178 static int nrips = true;
179 module_param(nrips, int, 0444);
181 /* enable/disable Virtual VMLOAD VMSAVE */
182 static int vls = true;
183 module_param(vls, int, 0444);
185 /* enable/disable Virtual GIF */
186 static int vgif = true;
187 module_param(vgif, int, 0444);
190 * enable / disable AVIC. Because the defaults differ for APICv
191 * support between VMX and SVM we cannot use module_param_named.
194 module_param(avic, bool, 0444);
196 bool __read_mostly dump_invalid_vmcb;
197 module_param(dump_invalid_vmcb, bool, 0644);
200 bool intercept_smi = true;
201 module_param(intercept_smi, bool, 0444);
204 static bool svm_gp_erratum_intercept = true;
206 static u8 rsm_ins_bytes[] = "\x0f\xaa";
208 static unsigned long iopm_base;
210 struct kvm_ldttss_desc {
213 unsigned base1:8, type:5, dpl:2, p:1;
214 unsigned limit1:4, zero0:3, g:1, base2:8;
217 } __attribute__((packed));
219 DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
222 * Only MSR_TSC_AUX is switched via the user return hook. EFER is switched via
223 * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
225 * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
226 * defer the restoration of TSC_AUX until the CPU returns to userspace.
228 static int tsc_aux_uret_slot __read_mostly = -1;
230 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
232 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
233 #define MSRS_RANGE_SIZE 2048
234 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
236 u32 svm_msrpm_offset(u32 msr)
241 for (i = 0; i < NUM_MSR_MAPS; i++) {
242 if (msr < msrpm_ranges[i] ||
243 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
246 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
247 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
249 /* Now we have the u8 offset - but need the u32 offset */
253 /* MSR not in any range */
257 #define MAX_INST_SIZE 15
259 static int get_max_npt_level(void)
262 return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
264 return PT32E_ROOT_LEVEL;
268 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
270 struct vcpu_svm *svm = to_svm(vcpu);
271 u64 old_efer = vcpu->arch.efer;
272 vcpu->arch.efer = efer;
275 /* Shadow paging assumes NX to be available. */
278 if (!(efer & EFER_LMA))
282 if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
283 if (!(efer & EFER_SVME)) {
284 svm_leave_nested(vcpu);
285 svm_set_gif(svm, true);
286 /* #GP intercept is still needed for vmware backdoor */
287 if (!enable_vmware_backdoor)
288 clr_exception_intercept(svm, GP_VECTOR);
291 * Free the nested guest state, unless we are in SMM.
292 * In this case we will return to the nested guest
293 * as soon as we leave SMM.
296 svm_free_nested(svm);
299 int ret = svm_allocate_nested(svm);
302 vcpu->arch.efer = old_efer;
307 * Never intercept #GP for SEV guests, KVM can't
308 * decrypt guest memory to workaround the erratum.
310 if (svm_gp_erratum_intercept && !sev_guest(vcpu->kvm))
311 set_exception_intercept(svm, GP_VECTOR);
315 svm->vmcb->save.efer = efer | EFER_SVME;
316 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
320 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
322 struct vcpu_svm *svm = to_svm(vcpu);
325 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
326 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
330 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
332 struct vcpu_svm *svm = to_svm(vcpu);
335 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
337 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
341 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
343 struct vcpu_svm *svm = to_svm(vcpu);
346 * SEV-ES does not expose the next RIP. The RIP update is controlled by
347 * the type of exit and the #VC handler in the guest.
349 if (sev_es_guest(vcpu->kvm))
352 if (nrips && svm->vmcb->control.next_rip != 0) {
353 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
354 svm->next_rip = svm->vmcb->control.next_rip;
357 if (!svm->next_rip) {
358 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
361 kvm_rip_write(vcpu, svm->next_rip);
365 svm_set_interrupt_shadow(vcpu, 0);
370 static void svm_queue_exception(struct kvm_vcpu *vcpu)
372 struct vcpu_svm *svm = to_svm(vcpu);
373 unsigned nr = vcpu->arch.exception.nr;
374 bool has_error_code = vcpu->arch.exception.has_error_code;
375 u32 error_code = vcpu->arch.exception.error_code;
377 kvm_deliver_exception_payload(vcpu);
379 if (nr == BP_VECTOR && !nrips) {
380 unsigned long rip, old_rip = kvm_rip_read(vcpu);
383 * For guest debugging where we have to reinject #BP if some
384 * INT3 is guest-owned:
385 * Emulate nRIP by moving RIP forward. Will fail if injection
386 * raises a fault that is not intercepted. Still better than
387 * failing in all cases.
389 (void)skip_emulated_instruction(vcpu);
390 rip = kvm_rip_read(vcpu);
392 if (boot_cpu_has(X86_FEATURE_NRIPS))
393 svm->vmcb->control.next_rip = rip;
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);
461 pr_info("KVM is unsupported when running as an SEV guest\n");
468 void __svm_write_tsc_multiplier(u64 multiplier)
472 if (multiplier == __this_cpu_read(current_tsc_ratio))
475 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
476 __this_cpu_write(current_tsc_ratio, multiplier);
481 static void svm_hardware_disable(void)
483 /* Make sure we clean up behind us */
484 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
485 __svm_write_tsc_multiplier(TSC_RATIO_DEFAULT);
489 amd_pmu_disable_virt();
492 static int svm_hardware_enable(void)
495 struct svm_cpu_data *sd;
497 struct desc_struct *gdt;
498 int me = raw_smp_processor_id();
500 rdmsrl(MSR_EFER, efer);
501 if (efer & EFER_SVME)
505 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
508 sd = per_cpu(svm_data, me);
510 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
514 sd->asid_generation = 1;
515 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
516 sd->next_asid = sd->max_asid + 1;
517 sd->min_asid = max_sev_asid + 1;
519 gdt = get_current_gdt_rw();
520 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
522 wrmsrl(MSR_EFER, efer | EFER_SVME);
524 wrmsrl(MSR_VM_HSAVE_PA, __sme_page_pa(sd->save_area));
526 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
528 * Set the default value, even if we don't use TSC scaling
529 * to avoid having stale value in the msr
531 __svm_write_tsc_multiplier(TSC_RATIO_DEFAULT);
538 * Note that it is possible to have a system with mixed processor
539 * revisions and therefore different OSVW bits. If bits are not the same
540 * on different processors then choose the worst case (i.e. if erratum
541 * is present on one processor and not on another then assume that the
542 * erratum is present everywhere).
544 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
545 uint64_t len, status = 0;
548 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
550 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
554 osvw_status = osvw_len = 0;
558 osvw_status |= status;
559 osvw_status &= (1ULL << osvw_len) - 1;
562 osvw_status = osvw_len = 0;
564 svm_init_erratum_383();
566 amd_pmu_enable_virt();
571 static void svm_cpu_uninit(int cpu)
573 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
578 per_cpu(svm_data, cpu) = NULL;
579 kfree(sd->sev_vmcbs);
580 __free_page(sd->save_area);
584 static int svm_cpu_init(int cpu)
586 struct svm_cpu_data *sd;
589 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
593 sd->save_area = alloc_page(GFP_KERNEL);
597 clear_page(page_address(sd->save_area));
599 ret = sev_cpu_init(sd);
603 per_cpu(svm_data, cpu) = sd;
608 __free_page(sd->save_area);
615 static int direct_access_msr_slot(u32 msr)
619 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
620 if (direct_access_msrs[i].index == msr)
626 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
629 struct vcpu_svm *svm = to_svm(vcpu);
630 int slot = direct_access_msr_slot(msr);
635 /* Set the shadow bitmaps to the desired intercept states */
637 set_bit(slot, svm->shadow_msr_intercept.read);
639 clear_bit(slot, svm->shadow_msr_intercept.read);
642 set_bit(slot, svm->shadow_msr_intercept.write);
644 clear_bit(slot, svm->shadow_msr_intercept.write);
647 static bool valid_msr_intercept(u32 index)
649 return direct_access_msr_slot(index) != -ENOENT;
652 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
659 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
662 offset = svm_msrpm_offset(msr);
663 bit_write = 2 * (msr & 0x0f) + 1;
666 BUG_ON(offset == MSR_INVALID);
668 return !!test_bit(bit_write, &tmp);
671 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
672 u32 msr, int read, int write)
674 u8 bit_read, bit_write;
679 * If this warning triggers extend the direct_access_msrs list at the
680 * beginning of the file
682 WARN_ON(!valid_msr_intercept(msr));
684 /* Enforce non allowed MSRs to trap */
685 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
688 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
691 offset = svm_msrpm_offset(msr);
692 bit_read = 2 * (msr & 0x0f);
693 bit_write = 2 * (msr & 0x0f) + 1;
696 BUG_ON(offset == MSR_INVALID);
698 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
699 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
703 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
707 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
710 set_shadow_msr_intercept(vcpu, msr, read, write);
711 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
714 u32 *svm_vcpu_alloc_msrpm(void)
716 unsigned int order = get_order(MSRPM_SIZE);
717 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
723 msrpm = page_address(pages);
724 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
729 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
733 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
734 if (!direct_access_msrs[i].always)
736 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
741 void svm_vcpu_free_msrpm(u32 *msrpm)
743 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
746 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
748 struct vcpu_svm *svm = to_svm(vcpu);
752 * Set intercept permissions for all direct access MSRs again. They
753 * will automatically get filtered through the MSR filter, so we are
754 * back in sync after this.
756 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
757 u32 msr = direct_access_msrs[i].index;
758 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
759 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
761 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
765 static void add_msr_offset(u32 offset)
769 for (i = 0; i < MSRPM_OFFSETS; ++i) {
771 /* Offset already in list? */
772 if (msrpm_offsets[i] == offset)
775 /* Slot used by another offset? */
776 if (msrpm_offsets[i] != MSR_INVALID)
779 /* Add offset to list */
780 msrpm_offsets[i] = offset;
786 * If this BUG triggers the msrpm_offsets table has an overflow. Just
787 * increase MSRPM_OFFSETS in this case.
792 static void init_msrpm_offsets(void)
796 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
798 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
801 offset = svm_msrpm_offset(direct_access_msrs[i].index);
802 BUG_ON(offset == MSR_INVALID);
804 add_msr_offset(offset);
808 static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
810 struct vcpu_svm *svm = to_svm(vcpu);
812 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
813 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
814 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
815 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
816 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
819 static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
821 struct vcpu_svm *svm = to_svm(vcpu);
823 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
824 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
825 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
826 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
827 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
830 void disable_nmi_singlestep(struct vcpu_svm *svm)
832 svm->nmi_singlestep = false;
834 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
835 /* Clear our flags if they were not set by the guest */
836 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
837 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
838 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
839 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
843 static void grow_ple_window(struct kvm_vcpu *vcpu)
845 struct vcpu_svm *svm = to_svm(vcpu);
846 struct vmcb_control_area *control = &svm->vmcb->control;
847 int old = control->pause_filter_count;
849 control->pause_filter_count = __grow_ple_window(old,
851 pause_filter_count_grow,
852 pause_filter_count_max);
854 if (control->pause_filter_count != old) {
855 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
856 trace_kvm_ple_window_update(vcpu->vcpu_id,
857 control->pause_filter_count, old);
861 static void shrink_ple_window(struct kvm_vcpu *vcpu)
863 struct vcpu_svm *svm = to_svm(vcpu);
864 struct vmcb_control_area *control = &svm->vmcb->control;
865 int old = control->pause_filter_count;
867 control->pause_filter_count =
868 __shrink_ple_window(old,
870 pause_filter_count_shrink,
872 if (control->pause_filter_count != old) {
873 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
874 trace_kvm_ple_window_update(vcpu->vcpu_id,
875 control->pause_filter_count, old);
880 * The default MMIO mask is a single bit (excluding the present bit),
881 * which could conflict with the memory encryption bit. Check for
882 * memory encryption support and override the default MMIO mask if
883 * memory encryption is enabled.
885 static __init void svm_adjust_mmio_mask(void)
887 unsigned int enc_bit, mask_bit;
890 /* If there is no memory encryption support, use existing mask */
891 if (cpuid_eax(0x80000000) < 0x8000001f)
894 /* If memory encryption is not enabled, use existing mask */
895 rdmsrl(MSR_AMD64_SYSCFG, msr);
896 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
899 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
900 mask_bit = boot_cpu_data.x86_phys_bits;
902 /* Increment the mask bit if it is the same as the encryption bit */
903 if (enc_bit == mask_bit)
907 * If the mask bit location is below 52, then some bits above the
908 * physical addressing limit will always be reserved, so use the
909 * rsvd_bits() function to generate the mask. This mask, along with
910 * the present bit, will be used to generate a page fault with
913 * If the mask bit location is 52 (or above), then clear the mask.
915 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
917 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
920 static void svm_hardware_teardown(void)
924 sev_hardware_teardown();
926 for_each_possible_cpu(cpu)
929 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
930 get_order(IOPM_SIZE));
934 static __init void svm_set_cpu_caps(void)
940 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
942 kvm_cpu_cap_set(X86_FEATURE_SVM);
945 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
948 kvm_cpu_cap_set(X86_FEATURE_NPT);
950 /* Nested VM can receive #VMEXIT instead of triggering #GP */
951 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
954 /* CPUID 0x80000008 */
955 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
956 boot_cpu_has(X86_FEATURE_AMD_SSBD))
957 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
959 /* CPUID 0x8000001F (SME/SEV features) */
963 static __init int svm_hardware_setup(void)
966 struct page *iopm_pages;
969 unsigned int order = get_order(IOPM_SIZE);
972 * NX is required for shadow paging and for NPT if the NX huge pages
973 * mitigation is enabled.
975 if (!boot_cpu_has(X86_FEATURE_NX)) {
976 pr_err_ratelimited("NX (Execute Disable) not supported\n");
979 kvm_enable_efer_bits(EFER_NX);
981 iopm_pages = alloc_pages(GFP_KERNEL, order);
986 iopm_va = page_address(iopm_pages);
987 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
988 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
990 init_msrpm_offsets();
992 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
994 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
995 kvm_enable_efer_bits(EFER_FFXSR);
997 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
998 kvm_has_tsc_control = true;
999 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1000 kvm_tsc_scaling_ratio_frac_bits = 32;
1003 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
1005 /* Check for pause filtering support */
1006 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1007 pause_filter_count = 0;
1008 pause_filter_thresh = 0;
1009 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1010 pause_filter_thresh = 0;
1014 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1015 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1019 * KVM's MMU doesn't support using 2-level paging for itself, and thus
1020 * NPT isn't supported if the host is using 2-level paging since host
1021 * CR4 is unchanged on VMRUN.
1023 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
1024 npt_enabled = false;
1026 if (!boot_cpu_has(X86_FEATURE_NPT))
1027 npt_enabled = false;
1029 /* Force VM NPT level equal to the host's max NPT level */
1030 kvm_configure_mmu(npt_enabled, get_max_npt_level(),
1031 get_max_npt_level(), PG_LEVEL_1G);
1032 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
1034 /* Note, SEV setup consumes npt_enabled. */
1035 sev_hardware_setup();
1037 svm_hv_hardware_setup();
1039 svm_adjust_mmio_mask();
1041 for_each_possible_cpu(cpu) {
1042 r = svm_cpu_init(cpu);
1048 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1052 enable_apicv = avic = avic && npt_enabled && boot_cpu_has(X86_FEATURE_AVIC);
1055 pr_info("AVIC enabled\n");
1057 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1062 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1063 !IS_ENABLED(CONFIG_X86_64)) {
1066 pr_info("Virtual VMLOAD VMSAVE supported\n");
1070 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
1071 svm_gp_erratum_intercept = false;
1074 if (!boot_cpu_has(X86_FEATURE_VGIF))
1077 pr_info("Virtual GIF supported\n");
1083 * It seems that on AMD processors PTE's accessed bit is
1084 * being set by the CPU hardware before the NPF vmexit.
1085 * This is not expected behaviour and our tests fail because
1087 * A workaround here is to disable support for
1088 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
1089 * In this case userspace can know if there is support using
1090 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
1092 * If future AMD CPU models change the behaviour described above,
1093 * this variable can be changed accordingly
1095 allow_smaller_maxphyaddr = !npt_enabled;
1100 svm_hardware_teardown();
1104 static void init_seg(struct vmcb_seg *seg)
1107 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1108 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1109 seg->limit = 0xffff;
1113 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1116 seg->attrib = SVM_SELECTOR_P_MASK | type;
1117 seg->limit = 0xffff;
1121 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1123 struct vcpu_svm *svm = to_svm(vcpu);
1125 return svm->nested.ctl.tsc_offset;
1128 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1130 return kvm_default_tsc_scaling_ratio;
1133 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1135 struct vcpu_svm *svm = to_svm(vcpu);
1137 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1138 svm->vmcb->control.tsc_offset = offset;
1139 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1142 static void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1144 __svm_write_tsc_multiplier(multiplier);
1148 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1149 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1150 struct vcpu_svm *svm)
1153 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1154 * roots, or if INVPCID is disabled in the guest to inject #UD.
1156 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1158 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1159 svm_set_intercept(svm, INTERCEPT_INVPCID);
1161 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1164 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1165 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1166 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1168 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1172 static void init_vmcb(struct kvm_vcpu *vcpu)
1174 struct vcpu_svm *svm = to_svm(vcpu);
1175 struct vmcb_control_area *control = &svm->vmcb->control;
1176 struct vmcb_save_area *save = &svm->vmcb->save;
1178 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1179 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1180 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1181 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1182 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1183 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1184 if (!kvm_vcpu_apicv_active(vcpu))
1185 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1187 set_dr_intercepts(svm);
1189 set_exception_intercept(svm, PF_VECTOR);
1190 set_exception_intercept(svm, UD_VECTOR);
1191 set_exception_intercept(svm, MC_VECTOR);
1192 set_exception_intercept(svm, AC_VECTOR);
1193 set_exception_intercept(svm, DB_VECTOR);
1195 * Guest access to VMware backdoor ports could legitimately
1196 * trigger #GP because of TSS I/O permission bitmap.
1197 * We intercept those #GP and allow access to them anyway
1198 * as VMware does. Don't intercept #GP for SEV guests as KVM can't
1199 * decrypt guest memory to decode the faulting instruction.
1201 if (enable_vmware_backdoor && !sev_guest(vcpu->kvm))
1202 set_exception_intercept(svm, GP_VECTOR);
1204 svm_set_intercept(svm, INTERCEPT_INTR);
1205 svm_set_intercept(svm, INTERCEPT_NMI);
1208 svm_set_intercept(svm, INTERCEPT_SMI);
1210 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1211 svm_set_intercept(svm, INTERCEPT_RDPMC);
1212 svm_set_intercept(svm, INTERCEPT_CPUID);
1213 svm_set_intercept(svm, INTERCEPT_INVD);
1214 svm_set_intercept(svm, INTERCEPT_INVLPG);
1215 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1216 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1217 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1218 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1219 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1220 svm_set_intercept(svm, INTERCEPT_VMRUN);
1221 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1222 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1223 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1224 svm_set_intercept(svm, INTERCEPT_STGI);
1225 svm_set_intercept(svm, INTERCEPT_CLGI);
1226 svm_set_intercept(svm, INTERCEPT_SKINIT);
1227 svm_set_intercept(svm, INTERCEPT_WBINVD);
1228 svm_set_intercept(svm, INTERCEPT_XSETBV);
1229 svm_set_intercept(svm, INTERCEPT_RDPRU);
1230 svm_set_intercept(svm, INTERCEPT_RSM);
1232 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1233 svm_set_intercept(svm, INTERCEPT_MONITOR);
1234 svm_set_intercept(svm, INTERCEPT_MWAIT);
1237 if (!kvm_hlt_in_guest(vcpu->kvm))
1238 svm_set_intercept(svm, INTERCEPT_HLT);
1240 control->iopm_base_pa = __sme_set(iopm_base);
1241 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1242 control->int_ctl = V_INTR_MASKING_MASK;
1244 init_seg(&save->es);
1245 init_seg(&save->ss);
1246 init_seg(&save->ds);
1247 init_seg(&save->fs);
1248 init_seg(&save->gs);
1250 save->cs.selector = 0xf000;
1251 save->cs.base = 0xffff0000;
1252 /* Executable/Readable Code Segment */
1253 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1254 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1255 save->cs.limit = 0xffff;
1257 save->gdtr.base = 0;
1258 save->gdtr.limit = 0xffff;
1259 save->idtr.base = 0;
1260 save->idtr.limit = 0xffff;
1262 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1263 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1266 /* Setup VMCB for Nested Paging */
1267 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1268 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1269 clr_exception_intercept(svm, PF_VECTOR);
1270 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1271 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1272 save->g_pat = vcpu->arch.pat;
1275 svm->current_vmcb->asid_generation = 0;
1278 svm->nested.vmcb12_gpa = INVALID_GPA;
1279 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1281 if (!kvm_pause_in_guest(vcpu->kvm)) {
1282 control->pause_filter_count = pause_filter_count;
1283 if (pause_filter_thresh)
1284 control->pause_filter_thresh = pause_filter_thresh;
1285 svm_set_intercept(svm, INTERCEPT_PAUSE);
1287 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1290 svm_recalc_instruction_intercepts(vcpu, svm);
1293 * If the host supports V_SPEC_CTRL then disable the interception
1294 * of MSR_IA32_SPEC_CTRL.
1296 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1297 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1299 if (kvm_vcpu_apicv_active(vcpu))
1300 avic_init_vmcb(svm);
1303 svm_clr_intercept(svm, INTERCEPT_STGI);
1304 svm_clr_intercept(svm, INTERCEPT_CLGI);
1305 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1308 if (sev_guest(vcpu->kvm)) {
1309 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1310 clr_exception_intercept(svm, UD_VECTOR);
1312 if (sev_es_guest(vcpu->kvm)) {
1313 /* Perform SEV-ES specific VMCB updates */
1314 sev_es_init_vmcb(svm);
1318 svm_hv_init_vmcb(svm->vmcb);
1320 vmcb_mark_all_dirty(svm->vmcb);
1326 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1328 struct vcpu_svm *svm = to_svm(vcpu);
1331 svm->virt_spec_ctrl = 0;
1336 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1338 svm->current_vmcb = target_vmcb;
1339 svm->vmcb = target_vmcb->ptr;
1342 static int svm_create_vcpu(struct kvm_vcpu *vcpu)
1344 struct vcpu_svm *svm;
1345 struct page *vmcb01_page;
1346 struct page *vmsa_page = NULL;
1349 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1353 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1357 if (sev_es_guest(vcpu->kvm)) {
1359 * SEV-ES guests require a separate VMSA page used to contain
1360 * the encrypted register state of the guest.
1362 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1364 goto error_free_vmcb_page;
1367 * SEV-ES guests maintain an encrypted version of their FPU
1368 * state which is restored and saved on VMRUN and VMEXIT.
1369 * Free the fpu structure to prevent KVM from attempting to
1370 * access the FPU state.
1372 kvm_free_guest_fpu(vcpu);
1375 err = avic_init_vcpu(svm);
1377 goto error_free_vmsa_page;
1379 /* We initialize this flag to true to make sure that the is_running
1380 * bit would be set the first time the vcpu is loaded.
1382 if (irqchip_in_kernel(vcpu->kvm) && kvm_apicv_activated(vcpu->kvm))
1383 svm->avic_is_running = true;
1385 svm->msrpm = svm_vcpu_alloc_msrpm();
1388 goto error_free_vmsa_page;
1391 svm->vmcb01.ptr = page_address(vmcb01_page);
1392 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1395 svm->vmsa = page_address(vmsa_page);
1397 svm->guest_state_loaded = false;
1399 svm_switch_vmcb(svm, &svm->vmcb01);
1402 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1404 svm_init_osvw(vcpu);
1405 vcpu->arch.microcode_version = 0x01000065;
1407 if (sev_es_guest(vcpu->kvm))
1408 /* Perform SEV-ES specific VMCB creation updates */
1409 sev_es_create_vcpu(svm);
1413 error_free_vmsa_page:
1415 __free_page(vmsa_page);
1416 error_free_vmcb_page:
1417 __free_page(vmcb01_page);
1422 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1426 for_each_online_cpu(i)
1427 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
1430 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
1432 struct vcpu_svm *svm = to_svm(vcpu);
1435 * The vmcb page can be recycled, causing a false negative in
1436 * svm_vcpu_load(). So, ensure that no logical CPU has this
1437 * vmcb page recorded as its current vmcb.
1439 svm_clear_current_vmcb(svm->vmcb);
1441 svm_leave_nested(vcpu);
1442 svm_free_nested(svm);
1444 sev_free_vcpu(vcpu);
1446 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1447 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1450 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
1452 struct vcpu_svm *svm = to_svm(vcpu);
1453 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
1455 amd_clear_divider();
1457 if (sev_es_guest(vcpu->kvm))
1458 sev_es_unmap_ghcb(svm);
1460 if (svm->guest_state_loaded)
1464 * Save additional host state that will be restored on VMEXIT (sev-es)
1465 * or subsequent vmload of host save area.
1467 if (sev_es_guest(vcpu->kvm)) {
1468 sev_es_prepare_guest_switch(svm, vcpu->cpu);
1470 vmsave(__sme_page_pa(sd->save_area));
1473 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
1474 __svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1476 if (likely(tsc_aux_uret_slot >= 0))
1477 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1479 svm->guest_state_loaded = true;
1482 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1484 to_svm(vcpu)->guest_state_loaded = false;
1487 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1489 struct vcpu_svm *svm = to_svm(vcpu);
1490 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1492 if (sd->current_vmcb != svm->vmcb) {
1493 sd->current_vmcb = svm->vmcb;
1495 if (!cpu_feature_enabled(X86_FEATURE_IBPB_ON_VMEXIT))
1496 indirect_branch_prediction_barrier();
1498 if (kvm_vcpu_apicv_active(vcpu))
1499 avic_vcpu_load(vcpu, cpu);
1502 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1504 if (kvm_vcpu_apicv_active(vcpu))
1505 avic_vcpu_put(vcpu);
1507 svm_prepare_host_switch(vcpu);
1509 ++vcpu->stat.host_state_reload;
1512 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1514 struct vcpu_svm *svm = to_svm(vcpu);
1515 unsigned long rflags = svm->vmcb->save.rflags;
1517 if (svm->nmi_singlestep) {
1518 /* Hide our flags if they were not set by the guest */
1519 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1520 rflags &= ~X86_EFLAGS_TF;
1521 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1522 rflags &= ~X86_EFLAGS_RF;
1527 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1529 if (to_svm(vcpu)->nmi_singlestep)
1530 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1533 * Any change of EFLAGS.VM is accompanied by a reload of SS
1534 * (caused by either a task switch or an inter-privilege IRET),
1535 * so we do not need to update the CPL here.
1537 to_svm(vcpu)->vmcb->save.rflags = rflags;
1540 static bool svm_get_if_flag(struct kvm_vcpu *vcpu)
1542 struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1544 return sev_es_guest(vcpu->kvm)
1545 ? vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK
1546 : kvm_get_rflags(vcpu) & X86_EFLAGS_IF;
1549 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1552 case VCPU_EXREG_PDPTR:
1553 BUG_ON(!npt_enabled);
1554 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
1557 KVM_BUG_ON(1, vcpu->kvm);
1561 static void svm_set_vintr(struct vcpu_svm *svm)
1563 struct vmcb_control_area *control;
1566 * The following fields are ignored when AVIC is enabled
1568 WARN_ON(kvm_apicv_activated(svm->vcpu.kvm));
1570 svm_set_intercept(svm, INTERCEPT_VINTR);
1573 * This is just a dummy VINTR to actually cause a vmexit to happen.
1574 * Actual injection of virtual interrupts happens through EVENTINJ.
1576 control = &svm->vmcb->control;
1577 control->int_vector = 0x0;
1578 control->int_ctl &= ~V_INTR_PRIO_MASK;
1579 control->int_ctl |= V_IRQ_MASK |
1580 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1581 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1584 static void svm_clear_vintr(struct vcpu_svm *svm)
1586 svm_clr_intercept(svm, INTERCEPT_VINTR);
1588 /* Drop int_ctl fields related to VINTR injection. */
1589 svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1590 if (is_guest_mode(&svm->vcpu)) {
1591 svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1593 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1594 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1596 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1597 V_IRQ_INJECTION_BITS_MASK;
1599 svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1602 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1605 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1607 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1608 struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1611 case VCPU_SREG_CS: return &save->cs;
1612 case VCPU_SREG_DS: return &save->ds;
1613 case VCPU_SREG_ES: return &save->es;
1614 case VCPU_SREG_FS: return &save01->fs;
1615 case VCPU_SREG_GS: return &save01->gs;
1616 case VCPU_SREG_SS: return &save->ss;
1617 case VCPU_SREG_TR: return &save01->tr;
1618 case VCPU_SREG_LDTR: return &save01->ldtr;
1624 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1626 struct vmcb_seg *s = svm_seg(vcpu, seg);
1631 static void svm_get_segment(struct kvm_vcpu *vcpu,
1632 struct kvm_segment *var, int seg)
1634 struct vmcb_seg *s = svm_seg(vcpu, seg);
1636 var->base = s->base;
1637 var->limit = s->limit;
1638 var->selector = s->selector;
1639 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1640 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1641 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1642 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1643 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1644 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1645 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1648 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1649 * However, the SVM spec states that the G bit is not observed by the
1650 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1651 * So let's synthesize a legal G bit for all segments, this helps
1652 * running KVM nested. It also helps cross-vendor migration, because
1653 * Intel's vmentry has a check on the 'G' bit.
1655 var->g = s->limit > 0xfffff;
1658 * AMD's VMCB does not have an explicit unusable field, so emulate it
1659 * for cross vendor migration purposes by "not present"
1661 var->unusable = !var->present;
1666 * Work around a bug where the busy flag in the tr selector
1676 * The accessed bit must always be set in the segment
1677 * descriptor cache, although it can be cleared in the
1678 * descriptor, the cached bit always remains at 1. Since
1679 * Intel has a check on this, set it here to support
1680 * cross-vendor migration.
1687 * On AMD CPUs sometimes the DB bit in the segment
1688 * descriptor is left as 1, although the whole segment has
1689 * been made unusable. Clear it here to pass an Intel VMX
1690 * entry check when cross vendor migrating.
1694 /* This is symmetric with svm_set_segment() */
1695 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1700 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1702 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1707 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1709 struct vcpu_svm *svm = to_svm(vcpu);
1711 dt->size = svm->vmcb->save.idtr.limit;
1712 dt->address = svm->vmcb->save.idtr.base;
1715 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1717 struct vcpu_svm *svm = to_svm(vcpu);
1719 svm->vmcb->save.idtr.limit = dt->size;
1720 svm->vmcb->save.idtr.base = dt->address ;
1721 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1724 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1726 struct vcpu_svm *svm = to_svm(vcpu);
1728 dt->size = svm->vmcb->save.gdtr.limit;
1729 dt->address = svm->vmcb->save.gdtr.base;
1732 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1734 struct vcpu_svm *svm = to_svm(vcpu);
1736 svm->vmcb->save.gdtr.limit = dt->size;
1737 svm->vmcb->save.gdtr.base = dt->address ;
1738 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1741 static bool svm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1746 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1748 struct vcpu_svm *svm = to_svm(vcpu);
1750 bool old_paging = is_paging(vcpu);
1752 #ifdef CONFIG_X86_64
1753 if (vcpu->arch.efer & EFER_LME && !vcpu->arch.guest_state_protected) {
1754 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1755 vcpu->arch.efer |= EFER_LMA;
1756 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1759 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1760 vcpu->arch.efer &= ~EFER_LMA;
1761 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1765 vcpu->arch.cr0 = cr0;
1768 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1769 if (old_paging != is_paging(vcpu))
1770 svm_set_cr4(vcpu, kvm_read_cr4(vcpu));
1774 * re-enable caching here because the QEMU bios
1775 * does not do it - this results in some delay at
1778 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1779 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1781 svm->vmcb->save.cr0 = hcr0;
1782 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1785 * SEV-ES guests must always keep the CR intercepts cleared. CR
1786 * tracking is done using the CR write traps.
1788 if (sev_es_guest(vcpu->kvm))
1792 /* Selective CR0 write remains on. */
1793 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1794 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1796 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1797 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1801 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1806 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1808 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1809 unsigned long old_cr4 = vcpu->arch.cr4;
1811 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1812 svm_flush_tlb(vcpu);
1814 vcpu->arch.cr4 = cr4;
1818 if (!is_paging(vcpu))
1819 cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
1821 cr4 |= host_cr4_mce;
1822 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1823 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1825 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1826 kvm_update_cpuid_runtime(vcpu);
1829 static void svm_set_segment(struct kvm_vcpu *vcpu,
1830 struct kvm_segment *var, int seg)
1832 struct vcpu_svm *svm = to_svm(vcpu);
1833 struct vmcb_seg *s = svm_seg(vcpu, seg);
1835 s->base = var->base;
1836 s->limit = var->limit;
1837 s->selector = var->selector;
1838 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1839 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1840 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1841 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1842 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1843 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1844 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1845 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1848 * This is always accurate, except if SYSRET returned to a segment
1849 * with SS.DPL != 3. Intel does not have this quirk, and always
1850 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1851 * would entail passing the CPL to userspace and back.
1853 if (seg == VCPU_SREG_SS)
1854 /* This is symmetric with svm_get_segment() */
1855 svm->vmcb->save.cpl = (var->dpl & 3);
1857 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1860 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1862 struct vcpu_svm *svm = to_svm(vcpu);
1864 clr_exception_intercept(svm, BP_VECTOR);
1866 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1867 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1868 set_exception_intercept(svm, BP_VECTOR);
1872 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1874 if (sd->next_asid > sd->max_asid) {
1875 ++sd->asid_generation;
1876 sd->next_asid = sd->min_asid;
1877 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1878 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1881 svm->current_vmcb->asid_generation = sd->asid_generation;
1882 svm->asid = sd->next_asid++;
1885 static void svm_set_dr6(struct vcpu_svm *svm, unsigned long value)
1887 struct vmcb *vmcb = svm->vmcb;
1889 if (svm->vcpu.arch.guest_state_protected)
1892 if (unlikely(value != vmcb->save.dr6)) {
1893 vmcb->save.dr6 = value;
1894 vmcb_mark_dirty(vmcb, VMCB_DR);
1898 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1900 struct vcpu_svm *svm = to_svm(vcpu);
1902 if (vcpu->arch.guest_state_protected)
1905 get_debugreg(vcpu->arch.db[0], 0);
1906 get_debugreg(vcpu->arch.db[1], 1);
1907 get_debugreg(vcpu->arch.db[2], 2);
1908 get_debugreg(vcpu->arch.db[3], 3);
1910 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1911 * because db_interception might need it. We can do it before vmentry.
1913 vcpu->arch.dr6 = svm->vmcb->save.dr6;
1914 vcpu->arch.dr7 = svm->vmcb->save.dr7;
1915 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1916 set_dr_intercepts(svm);
1919 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1921 struct vcpu_svm *svm = to_svm(vcpu);
1923 if (vcpu->arch.guest_state_protected)
1926 svm->vmcb->save.dr7 = value;
1927 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
1930 static int pf_interception(struct kvm_vcpu *vcpu)
1932 struct vcpu_svm *svm = to_svm(vcpu);
1934 u64 fault_address = svm->vmcb->control.exit_info_2;
1935 u64 error_code = svm->vmcb->control.exit_info_1;
1937 return kvm_handle_page_fault(vcpu, error_code, fault_address,
1938 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1939 svm->vmcb->control.insn_bytes : NULL,
1940 svm->vmcb->control.insn_len);
1943 static int npf_interception(struct kvm_vcpu *vcpu)
1945 struct vcpu_svm *svm = to_svm(vcpu);
1947 u64 fault_address = svm->vmcb->control.exit_info_2;
1948 u64 error_code = svm->vmcb->control.exit_info_1;
1950 trace_kvm_page_fault(fault_address, error_code);
1951 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
1952 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1953 svm->vmcb->control.insn_bytes : NULL,
1954 svm->vmcb->control.insn_len);
1957 static int db_interception(struct kvm_vcpu *vcpu)
1959 struct kvm_run *kvm_run = vcpu->run;
1960 struct vcpu_svm *svm = to_svm(vcpu);
1962 if (!(vcpu->guest_debug &
1963 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1964 !svm->nmi_singlestep) {
1965 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
1966 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
1970 if (svm->nmi_singlestep) {
1971 disable_nmi_singlestep(svm);
1972 /* Make sure we check for pending NMIs upon entry */
1973 kvm_make_request(KVM_REQ_EVENT, vcpu);
1976 if (vcpu->guest_debug &
1977 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
1978 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1979 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
1980 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
1981 kvm_run->debug.arch.pc =
1982 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1983 kvm_run->debug.arch.exception = DB_VECTOR;
1990 static int bp_interception(struct kvm_vcpu *vcpu)
1992 struct vcpu_svm *svm = to_svm(vcpu);
1993 struct kvm_run *kvm_run = vcpu->run;
1995 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1996 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1997 kvm_run->debug.arch.exception = BP_VECTOR;
2001 static int ud_interception(struct kvm_vcpu *vcpu)
2003 return handle_ud(vcpu);
2006 static int ac_interception(struct kvm_vcpu *vcpu)
2008 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
2012 static bool is_erratum_383(void)
2017 if (!erratum_383_found)
2020 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2024 /* Bit 62 may or may not be set for this mce */
2025 value &= ~(1ULL << 62);
2027 if (value != 0xb600000000010015ULL)
2030 /* Clear MCi_STATUS registers */
2031 for (i = 0; i < 6; ++i)
2032 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2034 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2038 value &= ~(1ULL << 2);
2039 low = lower_32_bits(value);
2040 high = upper_32_bits(value);
2042 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2045 /* Flush tlb to evict multi-match entries */
2051 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2053 if (is_erratum_383()) {
2055 * Erratum 383 triggered. Guest state is corrupt so kill the
2058 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2060 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2066 * On an #MC intercept the MCE handler is not called automatically in
2067 * the host. So do it by hand here.
2069 kvm_machine_check();
2072 static int mc_interception(struct kvm_vcpu *vcpu)
2077 static int shutdown_interception(struct kvm_vcpu *vcpu)
2079 struct kvm_run *kvm_run = vcpu->run;
2080 struct vcpu_svm *svm = to_svm(vcpu);
2083 * The VM save area has already been encrypted so it
2084 * cannot be reinitialized - just terminate.
2086 if (sev_es_guest(vcpu->kvm))
2090 * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put
2091 * the VMCB in a known good state. Unfortuately, KVM doesn't have
2092 * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking
2093 * userspace. At a platform view, INIT is acceptable behavior as
2094 * there exist bare metal platforms that automatically INIT the CPU
2095 * in response to shutdown.
2097 clear_page(svm->vmcb);
2098 kvm_vcpu_reset(vcpu, true);
2100 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2104 static int io_interception(struct kvm_vcpu *vcpu)
2106 struct vcpu_svm *svm = to_svm(vcpu);
2107 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2108 int size, in, string;
2111 ++vcpu->stat.io_exits;
2112 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2113 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2114 port = io_info >> 16;
2115 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2118 if (sev_es_guest(vcpu->kvm))
2119 return sev_es_string_io(svm, size, port, in);
2121 return kvm_emulate_instruction(vcpu, 0);
2124 svm->next_rip = svm->vmcb->control.exit_info_2;
2126 return kvm_fast_pio(vcpu, size, port, in);
2129 static int nmi_interception(struct kvm_vcpu *vcpu)
2134 static int smi_interception(struct kvm_vcpu *vcpu)
2139 static int intr_interception(struct kvm_vcpu *vcpu)
2141 ++vcpu->stat.irq_exits;
2145 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2147 struct vcpu_svm *svm = to_svm(vcpu);
2148 struct vmcb *vmcb12;
2149 struct kvm_host_map map;
2152 if (nested_svm_check_permissions(vcpu))
2155 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2158 kvm_inject_gp(vcpu, 0);
2164 ret = kvm_skip_emulated_instruction(vcpu);
2167 svm_copy_vmloadsave_state(svm->vmcb, vmcb12);
2168 svm->sysenter_eip_hi = 0;
2169 svm->sysenter_esp_hi = 0;
2171 svm_copy_vmloadsave_state(vmcb12, svm->vmcb);
2174 kvm_vcpu_unmap(vcpu, &map, true);
2179 static int vmload_interception(struct kvm_vcpu *vcpu)
2181 return vmload_vmsave_interception(vcpu, true);
2184 static int vmsave_interception(struct kvm_vcpu *vcpu)
2186 return vmload_vmsave_interception(vcpu, false);
2189 static int vmrun_interception(struct kvm_vcpu *vcpu)
2191 if (nested_svm_check_permissions(vcpu))
2194 return nested_svm_vmrun(vcpu);
2204 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
2205 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2207 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2209 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2210 return NONE_SVM_INSTR;
2212 switch (ctxt->modrm) {
2213 case 0xd8: /* VMRUN */
2214 return SVM_INSTR_VMRUN;
2215 case 0xda: /* VMLOAD */
2216 return SVM_INSTR_VMLOAD;
2217 case 0xdb: /* VMSAVE */
2218 return SVM_INSTR_VMSAVE;
2223 return NONE_SVM_INSTR;
2226 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2228 const int guest_mode_exit_codes[] = {
2229 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2230 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2231 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2233 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2234 [SVM_INSTR_VMRUN] = vmrun_interception,
2235 [SVM_INSTR_VMLOAD] = vmload_interception,
2236 [SVM_INSTR_VMSAVE] = vmsave_interception,
2238 struct vcpu_svm *svm = to_svm(vcpu);
2241 if (is_guest_mode(vcpu)) {
2242 /* Returns '1' or -errno on failure, '0' on success. */
2243 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2248 return svm_instr_handlers[opcode](vcpu);
2252 * #GP handling code. Note that #GP can be triggered under the following two
2254 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2255 * some AMD CPUs when EAX of these instructions are in the reserved memory
2256 * regions (e.g. SMM memory on host).
2257 * 2) VMware backdoor
2259 static int gp_interception(struct kvm_vcpu *vcpu)
2261 struct vcpu_svm *svm = to_svm(vcpu);
2262 u32 error_code = svm->vmcb->control.exit_info_1;
2265 /* Both #GP cases have zero error_code */
2269 /* Decode the instruction for usage later */
2270 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2273 opcode = svm_instr_opcode(vcpu);
2275 if (opcode == NONE_SVM_INSTR) {
2276 if (!enable_vmware_backdoor)
2280 * VMware backdoor emulation on #GP interception only handles
2281 * IN{S}, OUT{S}, and RDPMC.
2283 if (!is_guest_mode(vcpu))
2284 return kvm_emulate_instruction(vcpu,
2285 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2287 /* All SVM instructions expect page aligned RAX */
2288 if (svm->vmcb->save.rax & ~PAGE_MASK)
2291 return emulate_svm_instr(vcpu, opcode);
2295 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2299 void svm_set_gif(struct vcpu_svm *svm, bool value)
2303 * If VGIF is enabled, the STGI intercept is only added to
2304 * detect the opening of the SMI/NMI window; remove it now.
2305 * Likewise, clear the VINTR intercept, we will set it
2306 * again while processing KVM_REQ_EVENT if needed.
2308 if (vgif_enabled(svm))
2309 svm_clr_intercept(svm, INTERCEPT_STGI);
2310 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2311 svm_clear_vintr(svm);
2314 if (svm->vcpu.arch.smi_pending ||
2315 svm->vcpu.arch.nmi_pending ||
2316 kvm_cpu_has_injectable_intr(&svm->vcpu))
2317 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2322 * After a CLGI no interrupts should come. But if vGIF is
2323 * in use, we still rely on the VINTR intercept (rather than
2324 * STGI) to detect an open interrupt window.
2326 if (!vgif_enabled(svm))
2327 svm_clear_vintr(svm);
2331 static int stgi_interception(struct kvm_vcpu *vcpu)
2335 if (nested_svm_check_permissions(vcpu))
2338 ret = kvm_skip_emulated_instruction(vcpu);
2339 svm_set_gif(to_svm(vcpu), true);
2343 static int clgi_interception(struct kvm_vcpu *vcpu)
2347 if (nested_svm_check_permissions(vcpu))
2350 ret = kvm_skip_emulated_instruction(vcpu);
2351 svm_set_gif(to_svm(vcpu), false);
2355 static int invlpga_interception(struct kvm_vcpu *vcpu)
2357 gva_t gva = kvm_rax_read(vcpu);
2358 u32 asid = kvm_rcx_read(vcpu);
2360 /* FIXME: Handle an address size prefix. */
2361 if (!is_long_mode(vcpu))
2364 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2366 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2367 kvm_mmu_invlpg(vcpu, gva);
2369 return kvm_skip_emulated_instruction(vcpu);
2372 static int skinit_interception(struct kvm_vcpu *vcpu)
2374 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2376 kvm_queue_exception(vcpu, UD_VECTOR);
2380 static int task_switch_interception(struct kvm_vcpu *vcpu)
2382 struct vcpu_svm *svm = to_svm(vcpu);
2385 int int_type = svm->vmcb->control.exit_int_info &
2386 SVM_EXITINTINFO_TYPE_MASK;
2387 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2389 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2391 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2392 bool has_error_code = false;
2395 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2397 if (svm->vmcb->control.exit_info_2 &
2398 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2399 reason = TASK_SWITCH_IRET;
2400 else if (svm->vmcb->control.exit_info_2 &
2401 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2402 reason = TASK_SWITCH_JMP;
2404 reason = TASK_SWITCH_GATE;
2406 reason = TASK_SWITCH_CALL;
2408 if (reason == TASK_SWITCH_GATE) {
2410 case SVM_EXITINTINFO_TYPE_NMI:
2411 vcpu->arch.nmi_injected = false;
2413 case SVM_EXITINTINFO_TYPE_EXEPT:
2414 if (svm->vmcb->control.exit_info_2 &
2415 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2416 has_error_code = true;
2418 (u32)svm->vmcb->control.exit_info_2;
2420 kvm_clear_exception_queue(vcpu);
2422 case SVM_EXITINTINFO_TYPE_INTR:
2423 kvm_clear_interrupt_queue(vcpu);
2430 if (reason != TASK_SWITCH_GATE ||
2431 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2432 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2433 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2434 if (!skip_emulated_instruction(vcpu))
2438 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2441 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2442 has_error_code, error_code);
2445 static int iret_interception(struct kvm_vcpu *vcpu)
2447 struct vcpu_svm *svm = to_svm(vcpu);
2449 ++vcpu->stat.nmi_window_exits;
2450 vcpu->arch.hflags |= HF_IRET_MASK;
2451 if (!sev_es_guest(vcpu->kvm)) {
2452 svm_clr_intercept(svm, INTERCEPT_IRET);
2453 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2455 kvm_make_request(KVM_REQ_EVENT, vcpu);
2459 static int invlpg_interception(struct kvm_vcpu *vcpu)
2461 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2462 return kvm_emulate_instruction(vcpu, 0);
2464 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2465 return kvm_skip_emulated_instruction(vcpu);
2468 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2470 return kvm_emulate_instruction(vcpu, 0);
2473 static int rsm_interception(struct kvm_vcpu *vcpu)
2475 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2478 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2481 struct vcpu_svm *svm = to_svm(vcpu);
2482 unsigned long cr0 = vcpu->arch.cr0;
2485 if (!is_guest_mode(vcpu) ||
2486 (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2489 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2490 val &= ~SVM_CR0_SELECTIVE_MASK;
2493 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2494 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2500 #define CR_VALID (1ULL << 63)
2502 static int cr_interception(struct kvm_vcpu *vcpu)
2504 struct vcpu_svm *svm = to_svm(vcpu);
2509 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2510 return emulate_on_interception(vcpu);
2512 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2513 return emulate_on_interception(vcpu);
2515 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2516 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2517 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2519 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2522 if (cr >= 16) { /* mov to cr */
2524 val = kvm_register_read(vcpu, reg);
2525 trace_kvm_cr_write(cr, val);
2528 if (!check_selective_cr0_intercepted(vcpu, val))
2529 err = kvm_set_cr0(vcpu, val);
2535 err = kvm_set_cr3(vcpu, val);
2538 err = kvm_set_cr4(vcpu, val);
2541 err = kvm_set_cr8(vcpu, val);
2544 WARN(1, "unhandled write to CR%d", cr);
2545 kvm_queue_exception(vcpu, UD_VECTOR);
2548 } else { /* mov from cr */
2551 val = kvm_read_cr0(vcpu);
2554 val = vcpu->arch.cr2;
2557 val = kvm_read_cr3(vcpu);
2560 val = kvm_read_cr4(vcpu);
2563 val = kvm_get_cr8(vcpu);
2566 WARN(1, "unhandled read from CR%d", cr);
2567 kvm_queue_exception(vcpu, UD_VECTOR);
2570 kvm_register_write(vcpu, reg, val);
2571 trace_kvm_cr_read(cr, val);
2573 return kvm_complete_insn_gp(vcpu, err);
2576 static int cr_trap(struct kvm_vcpu *vcpu)
2578 struct vcpu_svm *svm = to_svm(vcpu);
2579 unsigned long old_value, new_value;
2583 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2585 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2588 old_value = kvm_read_cr0(vcpu);
2589 svm_set_cr0(vcpu, new_value);
2591 kvm_post_set_cr0(vcpu, old_value, new_value);
2594 old_value = kvm_read_cr4(vcpu);
2595 svm_set_cr4(vcpu, new_value);
2597 kvm_post_set_cr4(vcpu, old_value, new_value);
2600 ret = kvm_set_cr8(vcpu, new_value);
2603 WARN(1, "unhandled CR%d write trap", cr);
2604 kvm_queue_exception(vcpu, UD_VECTOR);
2608 return kvm_complete_insn_gp(vcpu, ret);
2611 static int dr_interception(struct kvm_vcpu *vcpu)
2613 struct vcpu_svm *svm = to_svm(vcpu);
2618 if (vcpu->guest_debug == 0) {
2620 * No more DR vmexits; force a reload of the debug registers
2621 * and reenter on this instruction. The next vmexit will
2622 * retrieve the full state of the debug registers.
2624 clr_dr_intercepts(svm);
2625 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2629 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2630 return emulate_on_interception(vcpu);
2632 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2633 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2634 if (dr >= 16) { /* mov to DRn */
2636 val = kvm_register_read(vcpu, reg);
2637 err = kvm_set_dr(vcpu, dr, val);
2639 kvm_get_dr(vcpu, dr, &val);
2640 kvm_register_write(vcpu, reg, val);
2643 return kvm_complete_insn_gp(vcpu, err);
2646 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2650 u8 cr8_prev = kvm_get_cr8(vcpu);
2651 /* instruction emulation calls kvm_set_cr8() */
2652 r = cr_interception(vcpu);
2653 if (lapic_in_kernel(vcpu))
2655 if (cr8_prev <= kvm_get_cr8(vcpu))
2657 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2661 static int efer_trap(struct kvm_vcpu *vcpu)
2663 struct msr_data msr_info;
2667 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2668 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2669 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2670 * the guest doesn't have X86_FEATURE_SVM.
2672 msr_info.host_initiated = false;
2673 msr_info.index = MSR_EFER;
2674 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2675 ret = kvm_set_msr_common(vcpu, &msr_info);
2677 return kvm_complete_insn_gp(vcpu, ret);
2680 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2684 switch (msr->index) {
2685 case MSR_AMD64_DE_CFG:
2686 if (cpu_feature_enabled(X86_FEATURE_LFENCE_RDTSC))
2687 msr->data |= MSR_AMD64_DE_CFG_LFENCE_SERIALIZE;
2689 case MSR_IA32_PERF_CAPABILITIES:
2692 return KVM_MSR_RET_INVALID;
2698 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2700 struct vcpu_svm *svm = to_svm(vcpu);
2702 switch (msr_info->index) {
2704 msr_info->data = svm->vmcb01.ptr->save.star;
2706 #ifdef CONFIG_X86_64
2708 msr_info->data = svm->vmcb01.ptr->save.lstar;
2711 msr_info->data = svm->vmcb01.ptr->save.cstar;
2713 case MSR_KERNEL_GS_BASE:
2714 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2716 case MSR_SYSCALL_MASK:
2717 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2720 case MSR_IA32_SYSENTER_CS:
2721 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2723 case MSR_IA32_SYSENTER_EIP:
2724 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2725 if (guest_cpuid_is_intel(vcpu))
2726 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2728 case MSR_IA32_SYSENTER_ESP:
2729 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2730 if (guest_cpuid_is_intel(vcpu))
2731 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2734 msr_info->data = svm->tsc_aux;
2737 * Nobody will change the following 5 values in the VMCB so we can
2738 * safely return them on rdmsr. They will always be 0 until LBRV is
2741 case MSR_IA32_DEBUGCTLMSR:
2742 msr_info->data = svm->vmcb->save.dbgctl;
2744 case MSR_IA32_LASTBRANCHFROMIP:
2745 msr_info->data = svm->vmcb->save.br_from;
2747 case MSR_IA32_LASTBRANCHTOIP:
2748 msr_info->data = svm->vmcb->save.br_to;
2750 case MSR_IA32_LASTINTFROMIP:
2751 msr_info->data = svm->vmcb->save.last_excp_from;
2753 case MSR_IA32_LASTINTTOIP:
2754 msr_info->data = svm->vmcb->save.last_excp_to;
2756 case MSR_VM_HSAVE_PA:
2757 msr_info->data = svm->nested.hsave_msr;
2760 msr_info->data = svm->nested.vm_cr_msr;
2762 case MSR_IA32_SPEC_CTRL:
2763 if (!msr_info->host_initiated &&
2764 !guest_has_spec_ctrl_msr(vcpu))
2767 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2768 msr_info->data = svm->vmcb->save.spec_ctrl;
2770 msr_info->data = svm->spec_ctrl;
2772 case MSR_AMD64_VIRT_SPEC_CTRL:
2773 if (!msr_info->host_initiated &&
2774 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2777 msr_info->data = svm->virt_spec_ctrl;
2779 case MSR_F15H_IC_CFG: {
2783 family = guest_cpuid_family(vcpu);
2784 model = guest_cpuid_model(vcpu);
2786 if (family < 0 || model < 0)
2787 return kvm_get_msr_common(vcpu, msr_info);
2791 if (family == 0x15 &&
2792 (model >= 0x2 && model < 0x20))
2793 msr_info->data = 0x1E;
2796 case MSR_AMD64_DE_CFG:
2797 msr_info->data = svm->msr_decfg;
2800 return kvm_get_msr_common(vcpu, msr_info);
2805 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2807 struct vcpu_svm *svm = to_svm(vcpu);
2808 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->ghcb))
2809 return kvm_complete_insn_gp(vcpu, err);
2811 ghcb_set_sw_exit_info_1(svm->ghcb, 1);
2812 ghcb_set_sw_exit_info_2(svm->ghcb,
2814 SVM_EVTINJ_TYPE_EXEPT |
2819 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2821 struct vcpu_svm *svm = to_svm(vcpu);
2822 int svm_dis, chg_mask;
2824 if (data & ~SVM_VM_CR_VALID_MASK)
2827 chg_mask = SVM_VM_CR_VALID_MASK;
2829 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2830 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2832 svm->nested.vm_cr_msr &= ~chg_mask;
2833 svm->nested.vm_cr_msr |= (data & chg_mask);
2835 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2837 /* check for svm_disable while efer.svme is set */
2838 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
2844 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2846 struct vcpu_svm *svm = to_svm(vcpu);
2849 u32 ecx = msr->index;
2850 u64 data = msr->data;
2852 case MSR_IA32_CR_PAT:
2853 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2855 vcpu->arch.pat = data;
2856 svm->vmcb01.ptr->save.g_pat = data;
2857 if (is_guest_mode(vcpu))
2858 nested_vmcb02_compute_g_pat(svm);
2859 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
2861 case MSR_IA32_SPEC_CTRL:
2862 if (!msr->host_initiated &&
2863 !guest_has_spec_ctrl_msr(vcpu))
2866 if (kvm_spec_ctrl_test_value(data))
2869 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2870 svm->vmcb->save.spec_ctrl = data;
2872 svm->spec_ctrl = data;
2878 * When it's written (to non-zero) for the first time, pass
2882 * The handling of the MSR bitmap for L2 guests is done in
2883 * nested_svm_vmrun_msrpm.
2884 * We update the L1 MSR bit as well since it will end up
2885 * touching the MSR anyway now.
2887 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
2889 case MSR_IA32_PRED_CMD:
2890 if (!msr->host_initiated &&
2891 !guest_has_pred_cmd_msr(vcpu))
2894 if (data & ~PRED_CMD_IBPB)
2896 if (!boot_cpu_has(X86_FEATURE_IBPB))
2901 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2902 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
2904 case MSR_AMD64_VIRT_SPEC_CTRL:
2905 if (!msr->host_initiated &&
2906 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2909 if (data & ~SPEC_CTRL_SSBD)
2912 svm->virt_spec_ctrl = data;
2915 svm->vmcb01.ptr->save.star = data;
2917 #ifdef CONFIG_X86_64
2919 svm->vmcb01.ptr->save.lstar = data;
2922 svm->vmcb01.ptr->save.cstar = data;
2924 case MSR_KERNEL_GS_BASE:
2925 svm->vmcb01.ptr->save.kernel_gs_base = data;
2927 case MSR_SYSCALL_MASK:
2928 svm->vmcb01.ptr->save.sfmask = data;
2931 case MSR_IA32_SYSENTER_CS:
2932 svm->vmcb01.ptr->save.sysenter_cs = data;
2934 case MSR_IA32_SYSENTER_EIP:
2935 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
2937 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
2938 * when we spoof an Intel vendor ID (for cross vendor migration).
2939 * In this case we use this intercept to track the high
2940 * 32 bit part of these msrs to support Intel's
2941 * implementation of SYSENTER/SYSEXIT.
2943 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2945 case MSR_IA32_SYSENTER_ESP:
2946 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
2947 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2951 * TSC_AUX is usually changed only during boot and never read
2952 * directly. Intercept TSC_AUX instead of exposing it to the
2953 * guest via direct_access_msrs, and switch it via user return.
2956 r = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
2961 svm->tsc_aux = data;
2963 case MSR_IA32_DEBUGCTLMSR:
2964 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
2965 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
2969 if (data & DEBUGCTL_RESERVED_BITS)
2972 svm->vmcb->save.dbgctl = data;
2973 vmcb_mark_dirty(svm->vmcb, VMCB_LBR);
2974 if (data & (1ULL<<0))
2975 svm_enable_lbrv(vcpu);
2977 svm_disable_lbrv(vcpu);
2979 case MSR_VM_HSAVE_PA:
2981 * Old kernels did not validate the value written to
2982 * MSR_VM_HSAVE_PA. Allow KVM_SET_MSR to set an invalid
2983 * value to allow live migrating buggy or malicious guests
2984 * originating from those kernels.
2986 if (!msr->host_initiated && !page_address_valid(vcpu, data))
2989 svm->nested.hsave_msr = data & PAGE_MASK;
2992 return svm_set_vm_cr(vcpu, data);
2994 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
2996 case MSR_AMD64_DE_CFG: {
2997 struct kvm_msr_entry msr_entry;
2999 msr_entry.index = msr->index;
3000 if (svm_get_msr_feature(&msr_entry))
3003 /* Check the supported bits */
3004 if (data & ~msr_entry.data)
3007 /* Don't allow the guest to change a bit, #GP */
3008 if (!msr->host_initiated && (data ^ msr_entry.data))
3011 svm->msr_decfg = data;
3015 return kvm_set_msr_common(vcpu, msr);
3020 static int msr_interception(struct kvm_vcpu *vcpu)
3022 if (to_svm(vcpu)->vmcb->control.exit_info_1)
3023 return kvm_emulate_wrmsr(vcpu);
3025 return kvm_emulate_rdmsr(vcpu);
3028 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
3030 kvm_make_request(KVM_REQ_EVENT, vcpu);
3031 svm_clear_vintr(to_svm(vcpu));
3034 * For AVIC, the only reason to end up here is ExtINTs.
3035 * In this case AVIC was temporarily disabled for
3036 * requesting the IRQ window and we have to re-enable it.
3038 kvm_request_apicv_update(vcpu->kvm, true, APICV_INHIBIT_REASON_IRQWIN);
3040 ++vcpu->stat.irq_window_exits;
3044 static int pause_interception(struct kvm_vcpu *vcpu)
3049 * CPL is not made available for an SEV-ES guest, therefore
3050 * vcpu->arch.preempted_in_kernel can never be true. Just
3051 * set in_kernel to false as well.
3053 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3055 if (!kvm_pause_in_guest(vcpu->kvm))
3056 grow_ple_window(vcpu);
3058 kvm_vcpu_on_spin(vcpu, in_kernel);
3059 return kvm_skip_emulated_instruction(vcpu);
3062 static int invpcid_interception(struct kvm_vcpu *vcpu)
3064 struct vcpu_svm *svm = to_svm(vcpu);
3068 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3069 kvm_queue_exception(vcpu, UD_VECTOR);
3074 * For an INVPCID intercept:
3075 * EXITINFO1 provides the linear address of the memory operand.
3076 * EXITINFO2 provides the contents of the register operand.
3078 type = svm->vmcb->control.exit_info_2;
3079 gva = svm->vmcb->control.exit_info_1;
3082 kvm_inject_gp(vcpu, 0);
3086 return kvm_handle_invpcid(vcpu, type, gva);
3089 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3090 [SVM_EXIT_READ_CR0] = cr_interception,
3091 [SVM_EXIT_READ_CR3] = cr_interception,
3092 [SVM_EXIT_READ_CR4] = cr_interception,
3093 [SVM_EXIT_READ_CR8] = cr_interception,
3094 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3095 [SVM_EXIT_WRITE_CR0] = cr_interception,
3096 [SVM_EXIT_WRITE_CR3] = cr_interception,
3097 [SVM_EXIT_WRITE_CR4] = cr_interception,
3098 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3099 [SVM_EXIT_READ_DR0] = dr_interception,
3100 [SVM_EXIT_READ_DR1] = dr_interception,
3101 [SVM_EXIT_READ_DR2] = dr_interception,
3102 [SVM_EXIT_READ_DR3] = dr_interception,
3103 [SVM_EXIT_READ_DR4] = dr_interception,
3104 [SVM_EXIT_READ_DR5] = dr_interception,
3105 [SVM_EXIT_READ_DR6] = dr_interception,
3106 [SVM_EXIT_READ_DR7] = dr_interception,
3107 [SVM_EXIT_WRITE_DR0] = dr_interception,
3108 [SVM_EXIT_WRITE_DR1] = dr_interception,
3109 [SVM_EXIT_WRITE_DR2] = dr_interception,
3110 [SVM_EXIT_WRITE_DR3] = dr_interception,
3111 [SVM_EXIT_WRITE_DR4] = dr_interception,
3112 [SVM_EXIT_WRITE_DR5] = dr_interception,
3113 [SVM_EXIT_WRITE_DR6] = dr_interception,
3114 [SVM_EXIT_WRITE_DR7] = dr_interception,
3115 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3116 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3117 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3118 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3119 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3120 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3121 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3122 [SVM_EXIT_INTR] = intr_interception,
3123 [SVM_EXIT_NMI] = nmi_interception,
3124 [SVM_EXIT_SMI] = smi_interception,
3125 [SVM_EXIT_VINTR] = interrupt_window_interception,
3126 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3127 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3128 [SVM_EXIT_IRET] = iret_interception,
3129 [SVM_EXIT_INVD] = kvm_emulate_invd,
3130 [SVM_EXIT_PAUSE] = pause_interception,
3131 [SVM_EXIT_HLT] = kvm_emulate_halt,
3132 [SVM_EXIT_INVLPG] = invlpg_interception,
3133 [SVM_EXIT_INVLPGA] = invlpga_interception,
3134 [SVM_EXIT_IOIO] = io_interception,
3135 [SVM_EXIT_MSR] = msr_interception,
3136 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3137 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3138 [SVM_EXIT_VMRUN] = vmrun_interception,
3139 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3140 [SVM_EXIT_VMLOAD] = vmload_interception,
3141 [SVM_EXIT_VMSAVE] = vmsave_interception,
3142 [SVM_EXIT_STGI] = stgi_interception,
3143 [SVM_EXIT_CLGI] = clgi_interception,
3144 [SVM_EXIT_SKINIT] = skinit_interception,
3145 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3146 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3147 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3148 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3149 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3150 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3151 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3152 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3153 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3154 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3155 [SVM_EXIT_INVPCID] = invpcid_interception,
3156 [SVM_EXIT_NPF] = npf_interception,
3157 [SVM_EXIT_RSM] = rsm_interception,
3158 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3159 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3160 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3163 static void dump_vmcb(struct kvm_vcpu *vcpu)
3165 struct vcpu_svm *svm = to_svm(vcpu);
3166 struct vmcb_control_area *control = &svm->vmcb->control;
3167 struct vmcb_save_area *save = &svm->vmcb->save;
3168 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3170 if (!dump_invalid_vmcb) {
3171 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3175 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3176 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3177 pr_err("VMCB Control Area:\n");
3178 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3179 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3180 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3181 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3182 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3183 pr_err("%-20s%08x %08x\n", "intercepts:",
3184 control->intercepts[INTERCEPT_WORD3],
3185 control->intercepts[INTERCEPT_WORD4]);
3186 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3187 pr_err("%-20s%d\n", "pause filter threshold:",
3188 control->pause_filter_thresh);
3189 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3190 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3191 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3192 pr_err("%-20s%d\n", "asid:", control->asid);
3193 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3194 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3195 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3196 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3197 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3198 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3199 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3200 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3201 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3202 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3203 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3204 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3205 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3206 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3207 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3208 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3209 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3210 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3211 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3212 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3213 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3214 pr_err("VMCB State Save Area:\n");
3215 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3217 save->es.selector, save->es.attrib,
3218 save->es.limit, save->es.base);
3219 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3221 save->cs.selector, save->cs.attrib,
3222 save->cs.limit, save->cs.base);
3223 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3225 save->ss.selector, save->ss.attrib,
3226 save->ss.limit, save->ss.base);
3227 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3229 save->ds.selector, save->ds.attrib,
3230 save->ds.limit, save->ds.base);
3231 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3233 save01->fs.selector, save01->fs.attrib,
3234 save01->fs.limit, save01->fs.base);
3235 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3237 save01->gs.selector, save01->gs.attrib,
3238 save01->gs.limit, save01->gs.base);
3239 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3241 save->gdtr.selector, save->gdtr.attrib,
3242 save->gdtr.limit, save->gdtr.base);
3243 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3245 save01->ldtr.selector, save01->ldtr.attrib,
3246 save01->ldtr.limit, save01->ldtr.base);
3247 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3249 save->idtr.selector, save->idtr.attrib,
3250 save->idtr.limit, save->idtr.base);
3251 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3253 save01->tr.selector, save01->tr.attrib,
3254 save01->tr.limit, save01->tr.base);
3255 pr_err("cpl: %d efer: %016llx\n",
3256 save->cpl, save->efer);
3257 pr_err("%-15s %016llx %-13s %016llx\n",
3258 "cr0:", save->cr0, "cr2:", save->cr2);
3259 pr_err("%-15s %016llx %-13s %016llx\n",
3260 "cr3:", save->cr3, "cr4:", save->cr4);
3261 pr_err("%-15s %016llx %-13s %016llx\n",
3262 "dr6:", save->dr6, "dr7:", save->dr7);
3263 pr_err("%-15s %016llx %-13s %016llx\n",
3264 "rip:", save->rip, "rflags:", save->rflags);
3265 pr_err("%-15s %016llx %-13s %016llx\n",
3266 "rsp:", save->rsp, "rax:", save->rax);
3267 pr_err("%-15s %016llx %-13s %016llx\n",
3268 "star:", save01->star, "lstar:", save01->lstar);
3269 pr_err("%-15s %016llx %-13s %016llx\n",
3270 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3271 pr_err("%-15s %016llx %-13s %016llx\n",
3272 "kernel_gs_base:", save01->kernel_gs_base,
3273 "sysenter_cs:", save01->sysenter_cs);
3274 pr_err("%-15s %016llx %-13s %016llx\n",
3275 "sysenter_esp:", save01->sysenter_esp,
3276 "sysenter_eip:", save01->sysenter_eip);
3277 pr_err("%-15s %016llx %-13s %016llx\n",
3278 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3279 pr_err("%-15s %016llx %-13s %016llx\n",
3280 "br_from:", save->br_from, "br_to:", save->br_to);
3281 pr_err("%-15s %016llx %-13s %016llx\n",
3282 "excp_from:", save->last_excp_from,
3283 "excp_to:", save->last_excp_to);
3286 static bool svm_check_exit_valid(struct kvm_vcpu *vcpu, u64 exit_code)
3288 return (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3289 svm_exit_handlers[exit_code]);
3292 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3294 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3296 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3297 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3298 vcpu->run->internal.ndata = 2;
3299 vcpu->run->internal.data[0] = exit_code;
3300 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3304 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3306 if (!svm_check_exit_valid(vcpu, exit_code))
3307 return svm_handle_invalid_exit(vcpu, exit_code);
3309 #ifdef CONFIG_RETPOLINE
3310 if (exit_code == SVM_EXIT_MSR)
3311 return msr_interception(vcpu);
3312 else if (exit_code == SVM_EXIT_VINTR)
3313 return interrupt_window_interception(vcpu);
3314 else if (exit_code == SVM_EXIT_INTR)
3315 return intr_interception(vcpu);
3316 else if (exit_code == SVM_EXIT_HLT)
3317 return kvm_emulate_halt(vcpu);
3318 else if (exit_code == SVM_EXIT_NPF)
3319 return npf_interception(vcpu);
3321 return svm_exit_handlers[exit_code](vcpu);
3324 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
3325 u32 *intr_info, u32 *error_code)
3327 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3329 *info1 = control->exit_info_1;
3330 *info2 = control->exit_info_2;
3331 *intr_info = control->exit_int_info;
3332 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3333 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3334 *error_code = control->exit_int_info_err;
3339 static int handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3341 struct vcpu_svm *svm = to_svm(vcpu);
3342 struct kvm_run *kvm_run = vcpu->run;
3343 u32 exit_code = svm->vmcb->control.exit_code;
3345 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
3347 /* SEV-ES guests must use the CR write traps to track CR registers. */
3348 if (!sev_es_guest(vcpu->kvm)) {
3349 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3350 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3352 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3355 if (is_guest_mode(vcpu)) {
3358 trace_kvm_nested_vmexit(exit_code, vcpu, KVM_ISA_SVM);
3360 vmexit = nested_svm_exit_special(svm);
3362 if (vmexit == NESTED_EXIT_CONTINUE)
3363 vmexit = nested_svm_exit_handled(svm);
3365 if (vmexit == NESTED_EXIT_DONE)
3369 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3370 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3371 kvm_run->fail_entry.hardware_entry_failure_reason
3372 = svm->vmcb->control.exit_code;
3373 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3378 if (exit_fastpath != EXIT_FASTPATH_NONE)
3381 return svm_invoke_exit_handler(vcpu, exit_code);
3384 static void reload_tss(struct kvm_vcpu *vcpu)
3386 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3388 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3392 static void pre_svm_run(struct kvm_vcpu *vcpu)
3394 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3395 struct vcpu_svm *svm = to_svm(vcpu);
3398 * If the previous vmrun of the vmcb occurred on a different physical
3399 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3400 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3402 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3403 svm->current_vmcb->asid_generation = 0;
3404 vmcb_mark_all_dirty(svm->vmcb);
3405 svm->current_vmcb->cpu = vcpu->cpu;
3408 if (sev_guest(vcpu->kvm))
3409 return pre_sev_run(svm, vcpu->cpu);
3411 /* FIXME: handle wraparound of asid_generation */
3412 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3416 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3418 struct vcpu_svm *svm = to_svm(vcpu);
3420 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3421 vcpu->arch.hflags |= HF_NMI_MASK;
3422 if (!sev_es_guest(vcpu->kvm))
3423 svm_set_intercept(svm, INTERCEPT_IRET);
3424 ++vcpu->stat.nmi_injections;
3427 static void svm_set_irq(struct kvm_vcpu *vcpu)
3429 struct vcpu_svm *svm = to_svm(vcpu);
3431 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
3432 ++vcpu->stat.irq_injections;
3434 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3435 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
3438 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3440 struct vcpu_svm *svm = to_svm(vcpu);
3443 * SEV-ES guests must always keep the CR intercepts cleared. CR
3444 * tracking is done using the CR write traps.
3446 if (sev_es_guest(vcpu->kvm))
3449 if (nested_svm_virtualize_tpr(vcpu))
3452 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3458 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3461 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3463 struct vcpu_svm *svm = to_svm(vcpu);
3464 struct vmcb *vmcb = svm->vmcb;
3470 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3473 ret = (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) ||
3474 (vcpu->arch.hflags & HF_NMI_MASK);
3479 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3481 struct vcpu_svm *svm = to_svm(vcpu);
3482 if (svm->nested.nested_run_pending)
3485 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3486 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3489 return !svm_nmi_blocked(vcpu);
3492 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3494 return !!(vcpu->arch.hflags & HF_NMI_MASK);
3497 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3499 struct vcpu_svm *svm = to_svm(vcpu);
3502 vcpu->arch.hflags |= HF_NMI_MASK;
3503 if (!sev_es_guest(vcpu->kvm))
3504 svm_set_intercept(svm, INTERCEPT_IRET);
3506 vcpu->arch.hflags &= ~HF_NMI_MASK;
3507 if (!sev_es_guest(vcpu->kvm))
3508 svm_clr_intercept(svm, INTERCEPT_IRET);
3512 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3514 struct vcpu_svm *svm = to_svm(vcpu);
3515 struct vmcb *vmcb = svm->vmcb;
3520 if (is_guest_mode(vcpu)) {
3521 /* As long as interrupts are being delivered... */
3522 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3523 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3524 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3527 /* ... vmexits aren't blocked by the interrupt shadow */
3528 if (nested_exit_on_intr(svm))
3531 if (!svm_get_if_flag(vcpu))
3535 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3538 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3540 struct vcpu_svm *svm = to_svm(vcpu);
3541 if (svm->nested.nested_run_pending)
3545 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3546 * e.g. if the IRQ arrived asynchronously after checking nested events.
3548 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3551 return !svm_interrupt_blocked(vcpu);
3554 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3556 struct vcpu_svm *svm = to_svm(vcpu);
3559 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3560 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3561 * get that intercept, this function will be called again though and
3562 * we'll get the vintr intercept. However, if the vGIF feature is
3563 * enabled, the STGI interception will not occur. Enable the irq
3564 * window under the assumption that the hardware will set the GIF.
3566 if (vgif_enabled(svm) || gif_set(svm)) {
3568 * IRQ window is not needed when AVIC is enabled,
3569 * unless we have pending ExtINT since it cannot be injected
3570 * via AVIC. In such case, we need to temporarily disable AVIC,
3571 * and fallback to injecting IRQ via V_IRQ.
3573 kvm_request_apicv_update(vcpu->kvm, false, APICV_INHIBIT_REASON_IRQWIN);
3578 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3580 struct vcpu_svm *svm = to_svm(vcpu);
3582 if ((vcpu->arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK)
3583 return; /* IRET will cause a vm exit */
3585 if (!gif_set(svm)) {
3586 if (vgif_enabled(svm))
3587 svm_set_intercept(svm, INTERCEPT_STGI);
3588 return; /* STGI will cause a vm exit */
3592 * Something prevents NMI from been injected. Single step over possible
3593 * problem (IRET or exception injection or interrupt shadow)
3595 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3596 svm->nmi_singlestep = true;
3597 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3600 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
3605 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
3610 void svm_flush_tlb(struct kvm_vcpu *vcpu)
3612 struct vcpu_svm *svm = to_svm(vcpu);
3615 * Flush only the current ASID even if the TLB flush was invoked via
3616 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3617 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3618 * unconditionally does a TLB flush on both nested VM-Enter and nested
3619 * VM-Exit (via kvm_mmu_reset_context()).
3621 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3622 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3624 svm->current_vmcb->asid_generation--;
3627 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
3629 struct vcpu_svm *svm = to_svm(vcpu);
3631 invlpga(gva, svm->vmcb->control.asid);
3634 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3636 struct vcpu_svm *svm = to_svm(vcpu);
3638 if (nested_svm_virtualize_tpr(vcpu))
3641 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
3642 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3643 kvm_set_cr8(vcpu, cr8);
3647 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3649 struct vcpu_svm *svm = to_svm(vcpu);
3652 if (nested_svm_virtualize_tpr(vcpu) ||
3653 kvm_vcpu_apicv_active(vcpu))
3656 cr8 = kvm_get_cr8(vcpu);
3657 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3658 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3661 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
3663 struct vcpu_svm *svm = to_svm(vcpu);
3666 u32 exitintinfo = svm->vmcb->control.exit_int_info;
3667 unsigned int3_injected = svm->int3_injected;
3669 svm->int3_injected = 0;
3672 * If we've made progress since setting HF_IRET_MASK, we've
3673 * executed an IRET and can allow NMI injection.
3675 if ((vcpu->arch.hflags & HF_IRET_MASK) &&
3676 (sev_es_guest(vcpu->kvm) ||
3677 kvm_rip_read(vcpu) != svm->nmi_iret_rip)) {
3678 vcpu->arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3679 kvm_make_request(KVM_REQ_EVENT, vcpu);
3682 vcpu->arch.nmi_injected = false;
3683 kvm_clear_exception_queue(vcpu);
3684 kvm_clear_interrupt_queue(vcpu);
3686 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3689 kvm_make_request(KVM_REQ_EVENT, vcpu);
3691 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3692 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3695 * If NextRIP isn't enabled, KVM must manually advance RIP prior to
3696 * injecting the soft exception/interrupt. That advancement needs to
3697 * be unwound if vectoring didn't complete. Note, the new event may
3698 * not be the injected event, e.g. if KVM injected an INTn, the INTn
3699 * hit a #NP in the guest, and the #NP encountered a #PF, the #NP will
3700 * be the reported vectored event, but RIP still needs to be unwound.
3702 if (int3_injected && type == SVM_EXITINTINFO_TYPE_EXEPT &&
3703 kvm_is_linear_rip(vcpu, svm->int3_rip))
3704 kvm_rip_write(vcpu, kvm_rip_read(vcpu) - int3_injected);
3707 case SVM_EXITINTINFO_TYPE_NMI:
3708 vcpu->arch.nmi_injected = true;
3710 case SVM_EXITINTINFO_TYPE_EXEPT:
3712 * Never re-inject a #VC exception.
3714 if (vector == X86_TRAP_VC)
3718 * In case of software exceptions, do not reinject the vector,
3719 * but re-execute the instruction instead.
3721 if (kvm_exception_is_soft(vector))
3724 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3725 u32 err = svm->vmcb->control.exit_int_info_err;
3726 kvm_requeue_exception_e(vcpu, vector, err);
3729 kvm_requeue_exception(vcpu, vector);
3731 case SVM_EXITINTINFO_TYPE_INTR:
3732 kvm_queue_interrupt(vcpu, vector, false);
3739 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3741 struct vcpu_svm *svm = to_svm(vcpu);
3742 struct vmcb_control_area *control = &svm->vmcb->control;
3744 control->exit_int_info = control->event_inj;
3745 control->exit_int_info_err = control->event_inj_err;
3746 control->event_inj = 0;
3747 svm_complete_interrupts(vcpu);
3750 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
3752 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3755 * Note, the next RIP must be provided as SRCU isn't held, i.e. KVM
3756 * can't read guest memory (dereference memslots) to decode the WRMSR.
3758 if (control->exit_code == SVM_EXIT_MSR && control->exit_info_1 &&
3759 nrips && control->next_rip)
3760 return handle_fastpath_set_msr_irqoff(vcpu);
3762 return EXIT_FASTPATH_NONE;
3765 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
3767 struct vcpu_svm *svm = to_svm(vcpu);
3768 unsigned long vmcb_pa = svm->current_vmcb->pa;
3770 kvm_guest_enter_irqoff();
3772 if (sev_es_guest(vcpu->kvm)) {
3773 __svm_sev_es_vcpu_run(vmcb_pa);
3775 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3778 * Use a single vmcb (vmcb01 because it's always valid) for
3779 * context switching guest state via VMLOAD/VMSAVE, that way
3780 * the state doesn't need to be copied between vmcb01 and
3781 * vmcb02 when switching vmcbs for nested virtualization.
3783 vmload(svm->vmcb01.pa);
3784 __svm_vcpu_run(vmcb_pa, (unsigned long *)&vcpu->arch.regs);
3785 vmsave(svm->vmcb01.pa);
3787 vmload(__sme_page_pa(sd->save_area));
3790 kvm_guest_exit_irqoff();
3793 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
3795 struct vcpu_svm *svm = to_svm(vcpu);
3797 trace_kvm_entry(vcpu);
3799 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3800 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3801 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3804 * Disable singlestep if we're injecting an interrupt/exception.
3805 * We don't want our modified rflags to be pushed on the stack where
3806 * we might not be able to easily reset them if we disabled NMI
3809 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
3811 * Event injection happens before external interrupts cause a
3812 * vmexit and interrupts are disabled here, so smp_send_reschedule
3813 * is enough to force an immediate vmexit.
3815 disable_nmi_singlestep(svm);
3816 smp_send_reschedule(vcpu->cpu);
3821 WARN_ON_ONCE(kvm_apicv_activated(vcpu->kvm) != kvm_vcpu_apicv_active(vcpu));
3823 sync_lapic_to_cr8(vcpu);
3825 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
3826 svm->vmcb->control.asid = svm->asid;
3827 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3829 svm->vmcb->save.cr2 = vcpu->arch.cr2;
3831 svm_hv_update_vp_id(svm->vmcb, vcpu);
3834 * Run with all-zero DR6 unless needed, so that we can get the exact cause
3837 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
3838 svm_set_dr6(svm, vcpu->arch.dr6);
3840 svm_set_dr6(svm, DR6_ACTIVE_LOW);
3843 kvm_load_guest_xsave_state(vcpu);
3845 kvm_wait_lapic_expire(vcpu);
3848 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3849 * it's non-zero. Since vmentry is serialising on affected CPUs, there
3850 * is no need to worry about the conditional branch over the wrmsr
3851 * being speculatively taken.
3853 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3854 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
3856 svm_vcpu_enter_exit(vcpu);
3859 * We do not use IBRS in the kernel. If this vCPU has used the
3860 * SPEC_CTRL MSR it may have left it on; save the value and
3861 * turn it off. This is much more efficient than blindly adding
3862 * it to the atomic save/restore list. Especially as the former
3863 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
3865 * For non-nested case:
3866 * If the L01 MSR bitmap does not intercept the MSR, then we need to
3870 * If the L02 MSR bitmap does not intercept the MSR, then we need to
3873 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL) &&
3874 unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
3875 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
3877 if (!sev_es_guest(vcpu->kvm))
3880 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3881 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
3883 if (!sev_es_guest(vcpu->kvm)) {
3884 vcpu->arch.cr2 = svm->vmcb->save.cr2;
3885 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
3886 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
3887 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
3890 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3891 kvm_before_interrupt(vcpu);
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();
3924 kvm_register_clear_available(vcpu, VCPU_EXREG_PDPTR);
3927 * We need to handle MC intercepts here before the vcpu has a chance to
3928 * change the physical cpu
3930 if (unlikely(svm->vmcb->control.exit_code ==
3931 SVM_EXIT_EXCP_BASE + MC_VECTOR))
3932 svm_handle_mce(vcpu);
3934 svm_complete_interrupts(vcpu);
3936 if (is_guest_mode(vcpu))
3937 return EXIT_FASTPATH_NONE;
3939 return svm_exit_handlers_fastpath(vcpu);
3942 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3945 struct vcpu_svm *svm = to_svm(vcpu);
3949 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
3950 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
3952 hv_track_root_tdp(vcpu, root_hpa);
3954 /* Loading L2's CR3 is handled by enter_svm_guest_mode. */
3955 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3957 cr3 = vcpu->arch.cr3;
3958 } else if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3959 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
3961 /* PCID in the guest should be impossible with a 32-bit MMU. */
3962 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
3966 svm->vmcb->save.cr3 = cr3;
3967 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
3970 static int is_disabled(void)
3974 rdmsrl(MSR_VM_CR, vm_cr);
3975 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
3982 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
3985 * Patch in the VMMCALL instruction:
3987 hypercall[0] = 0x0f;
3988 hypercall[1] = 0x01;
3989 hypercall[2] = 0xd9;
3992 static int __init svm_check_processor_compat(void)
3997 static bool svm_cpu_has_accelerated_tpr(void)
4003 * The kvm parameter can be NULL (module initialization, or invocation before
4004 * VM creation). Be sure to check the kvm parameter before using it.
4006 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4009 case MSR_IA32_MCG_EXT_CTL:
4010 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4012 case MSR_IA32_SMBASE:
4013 /* SEV-ES guests do not support SMM, so report false */
4014 if (kvm && sev_es_guest(kvm))
4024 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4029 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4031 struct vcpu_svm *svm = to_svm(vcpu);
4032 struct kvm_cpuid_entry2 *best;
4034 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4035 boot_cpu_has(X86_FEATURE_XSAVE) &&
4036 boot_cpu_has(X86_FEATURE_XSAVES);
4038 /* Update nrips enabled cache */
4039 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
4040 guest_cpuid_has(vcpu, X86_FEATURE_NRIPS);
4042 svm_recalc_instruction_intercepts(vcpu, svm);
4044 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4045 if (sev_guest(vcpu->kvm)) {
4046 best = kvm_find_cpuid_entry(vcpu, 0x8000001F, 0);
4048 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4051 if (kvm_vcpu_apicv_active(vcpu)) {
4053 * AVIC does not work with an x2APIC mode guest. If the X2APIC feature
4054 * is exposed to the guest, disable AVIC.
4056 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC))
4057 kvm_request_apicv_update(vcpu->kvm, false,
4058 APICV_INHIBIT_REASON_X2APIC);
4061 * Currently, AVIC does not work with nested virtualization.
4062 * So, we disable AVIC when cpuid for SVM is set in the L1 guest.
4064 if (nested && guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4065 kvm_request_apicv_update(vcpu->kvm, false,
4066 APICV_INHIBIT_REASON_NESTED);
4069 if (guest_cpuid_is_intel(vcpu)) {
4071 * We must intercept SYSENTER_EIP and SYSENTER_ESP
4072 * accesses because the processor only stores 32 bits.
4073 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
4075 svm_set_intercept(svm, INTERCEPT_VMLOAD);
4076 svm_set_intercept(svm, INTERCEPT_VMSAVE);
4077 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
4079 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
4080 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
4083 * If hardware supports Virtual VMLOAD VMSAVE then enable it
4084 * in VMCB and clear intercepts to avoid #VMEXIT.
4087 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
4088 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
4089 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
4091 /* No need to intercept these MSRs */
4092 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
4093 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
4097 static bool svm_has_wbinvd_exit(void)
4102 #define PRE_EX(exit) { .exit_code = (exit), \
4103 .stage = X86_ICPT_PRE_EXCEPT, }
4104 #define POST_EX(exit) { .exit_code = (exit), \
4105 .stage = X86_ICPT_POST_EXCEPT, }
4106 #define POST_MEM(exit) { .exit_code = (exit), \
4107 .stage = X86_ICPT_POST_MEMACCESS, }
4109 static const struct __x86_intercept {
4111 enum x86_intercept_stage stage;
4112 } x86_intercept_map[] = {
4113 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4114 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4115 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4116 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4117 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4118 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4119 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4120 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4121 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4122 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4123 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4124 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4125 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4126 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4127 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4128 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4129 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4130 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4131 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4132 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4133 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4134 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4135 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4136 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4137 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4138 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4139 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4140 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4141 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4142 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4143 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4144 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4145 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4146 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4147 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4148 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4149 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4150 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4151 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4152 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4153 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4154 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4155 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4156 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4157 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4158 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4159 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4166 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4167 struct x86_instruction_info *info,
4168 enum x86_intercept_stage stage,
4169 struct x86_exception *exception)
4171 struct vcpu_svm *svm = to_svm(vcpu);
4172 int vmexit, ret = X86EMUL_CONTINUE;
4173 struct __x86_intercept icpt_info;
4174 struct vmcb *vmcb = svm->vmcb;
4176 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4179 icpt_info = x86_intercept_map[info->intercept];
4181 if (stage != icpt_info.stage)
4184 switch (icpt_info.exit_code) {
4185 case SVM_EXIT_READ_CR0:
4186 if (info->intercept == x86_intercept_cr_read)
4187 icpt_info.exit_code += info->modrm_reg;
4189 case SVM_EXIT_WRITE_CR0: {
4190 unsigned long cr0, val;
4192 if (info->intercept == x86_intercept_cr_write)
4193 icpt_info.exit_code += info->modrm_reg;
4195 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4196 info->intercept == x86_intercept_clts)
4199 if (!(vmcb_is_intercept(&svm->nested.ctl,
4200 INTERCEPT_SELECTIVE_CR0)))
4203 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4204 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4206 if (info->intercept == x86_intercept_lmsw) {
4209 /* lmsw can't clear PE - catch this here */
4210 if (cr0 & X86_CR0_PE)
4215 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4219 case SVM_EXIT_READ_DR0:
4220 case SVM_EXIT_WRITE_DR0:
4221 icpt_info.exit_code += info->modrm_reg;
4224 if (info->intercept == x86_intercept_wrmsr)
4225 vmcb->control.exit_info_1 = 1;
4227 vmcb->control.exit_info_1 = 0;
4229 case SVM_EXIT_PAUSE:
4231 * We get this for NOP only, but pause
4232 * is rep not, check this here
4234 if (info->rep_prefix != REPE_PREFIX)
4237 case SVM_EXIT_IOIO: {
4241 if (info->intercept == x86_intercept_in ||
4242 info->intercept == x86_intercept_ins) {
4243 exit_info = ((info->src_val & 0xffff) << 16) |
4245 bytes = info->dst_bytes;
4247 exit_info = (info->dst_val & 0xffff) << 16;
4248 bytes = info->src_bytes;
4251 if (info->intercept == x86_intercept_outs ||
4252 info->intercept == x86_intercept_ins)
4253 exit_info |= SVM_IOIO_STR_MASK;
4255 if (info->rep_prefix)
4256 exit_info |= SVM_IOIO_REP_MASK;
4258 bytes = min(bytes, 4u);
4260 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4262 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4264 vmcb->control.exit_info_1 = exit_info;
4265 vmcb->control.exit_info_2 = info->next_rip;
4273 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4274 if (static_cpu_has(X86_FEATURE_NRIPS))
4275 vmcb->control.next_rip = info->next_rip;
4276 vmcb->control.exit_code = icpt_info.exit_code;
4277 vmexit = nested_svm_exit_handled(svm);
4279 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4286 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4288 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_INTR)
4289 vcpu->arch.at_instruction_boundary = true;
4292 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4294 if (!kvm_pause_in_guest(vcpu->kvm))
4295 shrink_ple_window(vcpu);
4298 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4300 /* [63:9] are reserved. */
4301 vcpu->arch.mcg_cap &= 0x1ff;
4304 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4306 struct vcpu_svm *svm = to_svm(vcpu);
4308 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4312 return is_smm(vcpu);
4315 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4317 struct vcpu_svm *svm = to_svm(vcpu);
4318 if (svm->nested.nested_run_pending)
4321 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4322 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4325 return !svm_smi_blocked(vcpu);
4328 static int svm_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
4330 struct vcpu_svm *svm = to_svm(vcpu);
4331 struct kvm_host_map map_save;
4334 if (!is_guest_mode(vcpu))
4337 /* FED8h - SVM Guest */
4338 put_smstate(u64, smstate, 0x7ed8, 1);
4339 /* FEE0h - SVM Guest VMCB Physical Address */
4340 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb12_gpa);
4342 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4343 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4344 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4346 ret = nested_svm_vmexit(svm);
4351 * KVM uses VMCB01 to store L1 host state while L2 runs but
4352 * VMCB01 is going to be used during SMM and thus the state will
4353 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4354 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4355 * format of the area is identical to guest save area offsetted
4356 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4357 * within 'struct vmcb'). Note: HSAVE area may also be used by
4358 * L1 hypervisor to save additional host context (e.g. KVM does
4359 * that, see svm_prepare_guest_switch()) which must be
4362 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4363 &map_save) == -EINVAL)
4366 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4368 svm_copy_vmrun_state(map_save.hva + 0x400,
4369 &svm->vmcb01.ptr->save);
4371 kvm_vcpu_unmap(vcpu, &map_save, true);
4375 static int svm_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
4377 struct vcpu_svm *svm = to_svm(vcpu);
4378 struct kvm_host_map map, map_save;
4379 u64 saved_efer, vmcb12_gpa;
4380 struct vmcb *vmcb12;
4383 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4386 /* Non-zero if SMI arrived while vCPU was in guest mode. */
4387 if (!GET_SMSTATE(u64, smstate, 0x7ed8))
4390 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4393 saved_efer = GET_SMSTATE(u64, smstate, 0x7ed0);
4394 if (!(saved_efer & EFER_SVME))
4397 vmcb12_gpa = GET_SMSTATE(u64, smstate, 0x7ee0);
4398 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map) == -EINVAL)
4402 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save) == -EINVAL)
4405 if (svm_allocate_nested(svm))
4409 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4410 * used during SMM (see svm_enter_smm())
4413 svm_copy_vmrun_state(&svm->vmcb01.ptr->save, map_save.hva + 0x400);
4416 * Enter the nested guest now
4419 vmcb_mark_all_dirty(svm->vmcb01.ptr);
4422 nested_load_control_from_vmcb12(svm, &vmcb12->control);
4423 ret = enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, false);
4428 svm->nested.nested_run_pending = 1;
4431 kvm_vcpu_unmap(vcpu, &map_save, true);
4433 kvm_vcpu_unmap(vcpu, &map, true);
4437 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4439 struct vcpu_svm *svm = to_svm(vcpu);
4441 if (!gif_set(svm)) {
4442 if (vgif_enabled(svm))
4443 svm_set_intercept(svm, INTERCEPT_STGI);
4444 /* STGI will cause a vm exit */
4446 /* We must be in SMM; RSM will cause a vmexit anyway. */
4450 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
4452 bool smep, smap, is_user;
4455 /* Emulation is always possible when KVM has access to all guest state. */
4456 if (!sev_guest(vcpu->kvm))
4460 * Emulation is impossible for SEV-ES guests as KVM doesn't have access
4461 * to guest register state.
4463 if (sev_es_guest(vcpu->kvm))
4467 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4470 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
4471 * possible that CPU microcode implementing DecodeAssist will fail
4472 * to read bytes of instruction which caused #NPF. In this case,
4473 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
4474 * return 0 instead of the correct guest instruction bytes.
4476 * This happens because CPU microcode reading instruction bytes
4477 * uses a special opcode which attempts to read data using CPL=0
4478 * privileges. The microcode reads CS:RIP and if it hits a SMAP
4479 * fault, it gives up and returns no instruction bytes.
4482 * We reach here in case CPU supports DecodeAssist, raised #NPF and
4483 * returned 0 in GuestIntrBytes field of the VMCB.
4484 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
4485 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
4486 * in case vCPU CPL==3 (Because otherwise guest would have triggered
4487 * a SMEP fault instead of #NPF).
4488 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
4489 * As most guests enable SMAP if they have also enabled SMEP, use above
4490 * logic in order to attempt minimize false-positive of detecting errata
4491 * while still preserving all cases semantic correctness.
4494 * To determine what instruction the guest was executing, the hypervisor
4495 * will have to decode the instruction at the instruction pointer.
4497 * In non SEV guest, hypervisor will be able to read the guest
4498 * memory to decode the instruction pointer when insn_len is zero
4499 * so we return true to indicate that decoding is possible.
4501 * But in the SEV guest, the guest memory is encrypted with the
4502 * guest specific key and hypervisor will not be able to decode the
4503 * instruction pointer so we will not able to workaround it. Lets
4504 * print the error and request to kill the guest.
4506 if (likely(!insn || insn_len))
4509 cr4 = kvm_read_cr4(vcpu);
4510 smep = cr4 & X86_CR4_SMEP;
4511 smap = cr4 & X86_CR4_SMAP;
4512 is_user = svm_get_cpl(vcpu) == 3;
4513 if (smap && (!smep || is_user)) {
4514 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
4517 * If the fault occurred in userspace, arbitrarily inject #GP
4518 * to avoid killing the guest and to hopefully avoid confusing
4519 * the guest kernel too much, e.g. injecting #PF would not be
4520 * coherent with respect to the guest's page tables. Request
4521 * triple fault if the fault occurred in the kernel as there's
4522 * no fault that KVM can inject without confusing the guest.
4523 * In practice, the triple fault is moot as no sane SEV kernel
4524 * will execute from user memory while also running with SMAP=1.
4527 kvm_inject_gp(vcpu, 0);
4529 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4535 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4537 struct vcpu_svm *svm = to_svm(vcpu);
4540 * TODO: Last condition latch INIT signals on vCPU when
4541 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
4542 * To properly emulate the INIT intercept,
4543 * svm_check_nested_events() should call nested_svm_vmexit()
4544 * if an INIT signal is pending.
4546 return !gif_set(svm) ||
4547 (vmcb_is_intercept(&svm->vmcb->control, INTERCEPT_INIT));
4550 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4552 if (!sev_es_guest(vcpu->kvm))
4553 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4555 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4558 static void svm_vm_destroy(struct kvm *kvm)
4560 avic_vm_destroy(kvm);
4561 sev_vm_destroy(kvm);
4564 static int svm_vm_init(struct kvm *kvm)
4566 if (!pause_filter_count || !pause_filter_thresh)
4567 kvm->arch.pause_in_guest = true;
4570 int ret = avic_vm_init(kvm);
4578 static struct kvm_x86_ops svm_x86_ops __initdata = {
4579 .hardware_unsetup = svm_hardware_teardown,
4580 .hardware_enable = svm_hardware_enable,
4581 .hardware_disable = svm_hardware_disable,
4582 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
4583 .has_emulated_msr = svm_has_emulated_msr,
4585 .vcpu_create = svm_create_vcpu,
4586 .vcpu_free = svm_free_vcpu,
4587 .vcpu_reset = svm_vcpu_reset,
4589 .vm_size = sizeof(struct kvm_svm),
4590 .vm_init = svm_vm_init,
4591 .vm_destroy = svm_vm_destroy,
4593 .prepare_guest_switch = svm_prepare_guest_switch,
4594 .vcpu_load = svm_vcpu_load,
4595 .vcpu_put = svm_vcpu_put,
4596 .vcpu_blocking = svm_vcpu_blocking,
4597 .vcpu_unblocking = svm_vcpu_unblocking,
4599 .update_exception_bitmap = svm_update_exception_bitmap,
4600 .get_msr_feature = svm_get_msr_feature,
4601 .get_msr = svm_get_msr,
4602 .set_msr = svm_set_msr,
4603 .get_segment_base = svm_get_segment_base,
4604 .get_segment = svm_get_segment,
4605 .set_segment = svm_set_segment,
4606 .get_cpl = svm_get_cpl,
4607 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
4608 .is_valid_cr0 = svm_is_valid_cr0,
4609 .set_cr0 = svm_set_cr0,
4610 .is_valid_cr4 = svm_is_valid_cr4,
4611 .set_cr4 = svm_set_cr4,
4612 .set_efer = svm_set_efer,
4613 .get_idt = svm_get_idt,
4614 .set_idt = svm_set_idt,
4615 .get_gdt = svm_get_gdt,
4616 .set_gdt = svm_set_gdt,
4617 .set_dr7 = svm_set_dr7,
4618 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4619 .cache_reg = svm_cache_reg,
4620 .get_rflags = svm_get_rflags,
4621 .set_rflags = svm_set_rflags,
4622 .get_if_flag = svm_get_if_flag,
4624 .tlb_flush_all = svm_flush_tlb,
4625 .tlb_flush_current = svm_flush_tlb,
4626 .tlb_flush_gva = svm_flush_tlb_gva,
4627 .tlb_flush_guest = svm_flush_tlb,
4629 .run = svm_vcpu_run,
4630 .handle_exit = handle_exit,
4631 .skip_emulated_instruction = skip_emulated_instruction,
4632 .update_emulated_instruction = NULL,
4633 .set_interrupt_shadow = svm_set_interrupt_shadow,
4634 .get_interrupt_shadow = svm_get_interrupt_shadow,
4635 .patch_hypercall = svm_patch_hypercall,
4636 .set_irq = svm_set_irq,
4637 .set_nmi = svm_inject_nmi,
4638 .queue_exception = svm_queue_exception,
4639 .cancel_injection = svm_cancel_injection,
4640 .interrupt_allowed = svm_interrupt_allowed,
4641 .nmi_allowed = svm_nmi_allowed,
4642 .get_nmi_mask = svm_get_nmi_mask,
4643 .set_nmi_mask = svm_set_nmi_mask,
4644 .enable_nmi_window = svm_enable_nmi_window,
4645 .enable_irq_window = svm_enable_irq_window,
4646 .update_cr8_intercept = svm_update_cr8_intercept,
4647 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
4648 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
4649 .check_apicv_inhibit_reasons = svm_check_apicv_inhibit_reasons,
4650 .load_eoi_exitmap = svm_load_eoi_exitmap,
4651 .hwapic_irr_update = svm_hwapic_irr_update,
4652 .hwapic_isr_update = svm_hwapic_isr_update,
4653 .apicv_post_state_restore = avic_post_state_restore,
4655 .set_tss_addr = svm_set_tss_addr,
4656 .set_identity_map_addr = svm_set_identity_map_addr,
4657 .get_mt_mask = svm_get_mt_mask,
4659 .get_exit_info = svm_get_exit_info,
4661 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
4663 .has_wbinvd_exit = svm_has_wbinvd_exit,
4665 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
4666 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
4667 .write_tsc_offset = svm_write_tsc_offset,
4668 .write_tsc_multiplier = svm_write_tsc_multiplier,
4670 .load_mmu_pgd = svm_load_mmu_pgd,
4672 .check_intercept = svm_check_intercept,
4673 .handle_exit_irqoff = svm_handle_exit_irqoff,
4675 .request_immediate_exit = __kvm_request_immediate_exit,
4677 .sched_in = svm_sched_in,
4679 .pmu_ops = &amd_pmu_ops,
4680 .nested_ops = &svm_nested_ops,
4682 .deliver_posted_interrupt = svm_deliver_avic_intr,
4683 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
4684 .update_pi_irte = svm_update_pi_irte,
4685 .setup_mce = svm_setup_mce,
4687 .smi_allowed = svm_smi_allowed,
4688 .enter_smm = svm_enter_smm,
4689 .leave_smm = svm_leave_smm,
4690 .enable_smi_window = svm_enable_smi_window,
4692 .mem_enc_op = svm_mem_enc_op,
4693 .mem_enc_reg_region = svm_register_enc_region,
4694 .mem_enc_unreg_region = svm_unregister_enc_region,
4695 .guest_memory_reclaimed = sev_guest_memory_reclaimed,
4697 .vm_copy_enc_context_from = svm_vm_copy_asid_from,
4699 .can_emulate_instruction = svm_can_emulate_instruction,
4701 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
4703 .msr_filter_changed = svm_msr_filter_changed,
4704 .complete_emulated_msr = svm_complete_emulated_msr,
4706 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
4709 static struct kvm_x86_init_ops svm_init_ops __initdata = {
4710 .cpu_has_kvm_support = has_svm,
4711 .disabled_by_bios = is_disabled,
4712 .hardware_setup = svm_hardware_setup,
4713 .check_processor_compatibility = svm_check_processor_compat,
4715 .runtime_ops = &svm_x86_ops,
4718 static int __init svm_init(void)
4720 __unused_size_checks();
4722 return kvm_init(&svm_init_ops, sizeof(struct vcpu_svm),
4723 __alignof__(struct vcpu_svm), THIS_MODULE);
4726 static void __exit svm_exit(void)
4731 module_init(svm_init)
4732 module_exit(svm_exit)