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 #define __ex(x) __kvm_handle_fault_on_reboot(x)
51 MODULE_AUTHOR("Qumranet");
52 MODULE_LICENSE("GPL");
55 static const struct x86_cpu_id svm_cpu_id[] = {
56 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
59 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
62 #define SEG_TYPE_LDT 2
63 #define SEG_TYPE_BUSY_TSS16 3
65 #define SVM_FEATURE_LBRV (1 << 1)
66 #define SVM_FEATURE_SVML (1 << 2)
67 #define SVM_FEATURE_TSC_RATE (1 << 4)
68 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
69 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
70 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
71 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
73 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
75 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
76 #define TSC_RATIO_MIN 0x0000000000000001ULL
77 #define TSC_RATIO_MAX 0x000000ffffffffffULL
79 static bool erratum_383_found __read_mostly;
81 u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
84 * Set osvw_len to higher value when updated Revision Guides
85 * are published and we know what the new status bits are
87 static uint64_t osvw_len = 4, osvw_status;
89 static DEFINE_PER_CPU(u64, current_tsc_ratio);
90 #define TSC_RATIO_DEFAULT 0x0100000000ULL
92 static const struct svm_direct_access_msrs {
93 u32 index; /* Index of the MSR */
94 bool always; /* True if intercept is initially cleared */
95 } direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
96 { .index = MSR_STAR, .always = true },
97 { .index = MSR_IA32_SYSENTER_CS, .always = true },
98 { .index = MSR_IA32_SYSENTER_EIP, .always = false },
99 { .index = MSR_IA32_SYSENTER_ESP, .always = false },
101 { .index = MSR_GS_BASE, .always = true },
102 { .index = MSR_FS_BASE, .always = true },
103 { .index = MSR_KERNEL_GS_BASE, .always = true },
104 { .index = MSR_LSTAR, .always = true },
105 { .index = MSR_CSTAR, .always = true },
106 { .index = MSR_SYSCALL_MASK, .always = true },
108 { .index = MSR_IA32_SPEC_CTRL, .always = false },
109 { .index = MSR_IA32_PRED_CMD, .always = false },
110 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
111 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
112 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
113 { .index = MSR_IA32_LASTINTTOIP, .always = false },
114 { .index = MSR_EFER, .always = false },
115 { .index = MSR_IA32_CR_PAT, .always = false },
116 { .index = MSR_AMD64_SEV_ES_GHCB, .always = true },
117 { .index = MSR_INVALID, .always = false },
121 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
122 * pause_filter_count: On processors that support Pause filtering(indicated
123 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
124 * count value. On VMRUN this value is loaded into an internal counter.
125 * Each time a pause instruction is executed, this counter is decremented
126 * until it reaches zero at which time a #VMEXIT is generated if pause
127 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
128 * Intercept Filtering for more details.
129 * This also indicate if ple logic enabled.
131 * pause_filter_thresh: In addition, some processor families support advanced
132 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
133 * the amount of time a guest is allowed to execute in a pause loop.
134 * In this mode, a 16-bit pause filter threshold field is added in the
135 * VMCB. The threshold value is a cycle count that is used to reset the
136 * pause counter. As with simple pause filtering, VMRUN loads the pause
137 * count value from VMCB into an internal counter. Then, on each pause
138 * instruction the hardware checks the elapsed number of cycles since
139 * the most recent pause instruction against the pause filter threshold.
140 * If the elapsed cycle count is greater than the pause filter threshold,
141 * then the internal pause count is reloaded from the VMCB and execution
142 * continues. If the elapsed cycle count is less than the pause filter
143 * threshold, then the internal pause count is decremented. If the count
144 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
145 * triggered. If advanced pause filtering is supported and pause filter
146 * threshold field is set to zero, the filter will operate in the simpler,
150 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
151 module_param(pause_filter_thresh, ushort, 0444);
153 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
154 module_param(pause_filter_count, ushort, 0444);
156 /* Default doubles per-vcpu window every exit. */
157 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
158 module_param(pause_filter_count_grow, ushort, 0444);
160 /* Default resets per-vcpu window every exit to pause_filter_count. */
161 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
162 module_param(pause_filter_count_shrink, ushort, 0444);
164 /* Default is to compute the maximum so we can never overflow. */
165 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
166 module_param(pause_filter_count_max, ushort, 0444);
169 * Use nested page tables by default. Note, NPT may get forced off by
170 * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
172 bool npt_enabled = true;
173 module_param_named(npt, npt_enabled, bool, 0444);
175 /* allow nested virtualization in KVM/SVM */
176 static int nested = true;
177 module_param(nested, int, S_IRUGO);
179 /* enable/disable Next RIP Save */
180 static int nrips = true;
181 module_param(nrips, int, 0444);
183 /* enable/disable Virtual VMLOAD VMSAVE */
184 static int vls = true;
185 module_param(vls, int, 0444);
187 /* enable/disable Virtual GIF */
188 static int vgif = true;
189 module_param(vgif, int, 0444);
192 * enable / disable AVIC. Because the defaults differ for APICv
193 * support between VMX and SVM we cannot use module_param_named.
196 module_param(avic, bool, 0444);
198 bool __read_mostly dump_invalid_vmcb;
199 module_param(dump_invalid_vmcb, bool, 0644);
202 bool intercept_smi = true;
203 module_param(intercept_smi, bool, 0444);
206 static bool svm_gp_erratum_intercept = true;
208 static u8 rsm_ins_bytes[] = "\x0f\xaa";
210 static unsigned long iopm_base;
212 struct kvm_ldttss_desc {
215 unsigned base1:8, type:5, dpl:2, p:1;
216 unsigned limit1:4, zero0:3, g:1, base2:8;
219 } __attribute__((packed));
221 DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
224 * Only MSR_TSC_AUX is switched via the user return hook. EFER is switched via
225 * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
227 * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
228 * defer the restoration of TSC_AUX until the CPU returns to userspace.
230 static int tsc_aux_uret_slot __read_mostly = -1;
232 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
234 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
235 #define MSRS_RANGE_SIZE 2048
236 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
238 u32 svm_msrpm_offset(u32 msr)
243 for (i = 0; i < NUM_MSR_MAPS; i++) {
244 if (msr < msrpm_ranges[i] ||
245 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
248 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
249 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
251 /* Now we have the u8 offset - but need the u32 offset */
255 /* MSR not in any range */
259 #define MAX_INST_SIZE 15
261 static int get_max_npt_level(void)
264 return PT64_ROOT_4LEVEL;
266 return PT32E_ROOT_LEVEL;
270 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
272 struct vcpu_svm *svm = to_svm(vcpu);
273 u64 old_efer = vcpu->arch.efer;
274 vcpu->arch.efer = efer;
277 /* Shadow paging assumes NX to be available. */
280 if (!(efer & EFER_LMA))
284 if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
285 if (!(efer & EFER_SVME)) {
286 svm_leave_nested(svm);
287 svm_set_gif(svm, true);
288 /* #GP intercept is still needed for vmware backdoor */
289 if (!enable_vmware_backdoor)
290 clr_exception_intercept(svm, GP_VECTOR);
293 * Free the nested guest state, unless we are in SMM.
294 * In this case we will return to the nested guest
295 * as soon as we leave SMM.
298 svm_free_nested(svm);
301 int ret = svm_allocate_nested(svm);
304 vcpu->arch.efer = old_efer;
308 if (svm_gp_erratum_intercept)
309 set_exception_intercept(svm, GP_VECTOR);
313 svm->vmcb->save.efer = efer | EFER_SVME;
314 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
318 static int is_external_interrupt(u32 info)
320 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
321 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
324 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
326 struct vcpu_svm *svm = to_svm(vcpu);
329 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
330 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
334 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
336 struct vcpu_svm *svm = to_svm(vcpu);
339 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
341 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
345 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
347 struct vcpu_svm *svm = to_svm(vcpu);
350 * SEV-ES does not expose the next RIP. The RIP update is controlled by
351 * the type of exit and the #VC handler in the guest.
353 if (sev_es_guest(vcpu->kvm))
356 if (nrips && svm->vmcb->control.next_rip != 0) {
357 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
358 svm->next_rip = svm->vmcb->control.next_rip;
361 if (!svm->next_rip) {
362 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
365 kvm_rip_write(vcpu, svm->next_rip);
369 svm_set_interrupt_shadow(vcpu, 0);
374 static void svm_queue_exception(struct kvm_vcpu *vcpu)
376 struct vcpu_svm *svm = to_svm(vcpu);
377 unsigned nr = vcpu->arch.exception.nr;
378 bool has_error_code = vcpu->arch.exception.has_error_code;
379 u32 error_code = vcpu->arch.exception.error_code;
381 kvm_deliver_exception_payload(vcpu);
383 if (nr == BP_VECTOR && !nrips) {
384 unsigned long rip, old_rip = kvm_rip_read(vcpu);
387 * For guest debugging where we have to reinject #BP if some
388 * INT3 is guest-owned:
389 * Emulate nRIP by moving RIP forward. Will fail if injection
390 * raises a fault that is not intercepted. Still better than
391 * failing in all cases.
393 (void)skip_emulated_instruction(vcpu);
394 rip = kvm_rip_read(vcpu);
395 svm->int3_rip = rip + svm->vmcb->save.cs.base;
396 svm->int3_injected = rip - old_rip;
399 svm->vmcb->control.event_inj = nr
401 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
402 | SVM_EVTINJ_TYPE_EXEPT;
403 svm->vmcb->control.event_inj_err = error_code;
406 static void svm_init_erratum_383(void)
412 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
415 /* Use _safe variants to not break nested virtualization */
416 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
422 low = lower_32_bits(val);
423 high = upper_32_bits(val);
425 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
427 erratum_383_found = true;
430 static void svm_init_osvw(struct kvm_vcpu *vcpu)
433 * Guests should see errata 400 and 415 as fixed (assuming that
434 * HLT and IO instructions are intercepted).
436 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
437 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
440 * By increasing VCPU's osvw.length to 3 we are telling the guest that
441 * all osvw.status bits inside that length, including bit 0 (which is
442 * reserved for erratum 298), are valid. However, if host processor's
443 * osvw_len is 0 then osvw_status[0] carries no information. We need to
444 * be conservative here and therefore we tell the guest that erratum 298
445 * is present (because we really don't know).
447 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
448 vcpu->arch.osvw.status |= 1;
451 static int has_svm(void)
455 if (!cpu_has_svm(&msg)) {
456 printk(KERN_INFO "has_svm: %s\n", msg);
461 pr_info("KVM is unsupported when running as an SEV guest\n");
465 if (pgtable_l5_enabled()) {
466 pr_info("KVM doesn't yet support 5-level paging on AMD SVM\n");
473 static void svm_hardware_disable(void)
475 /* Make sure we clean up behind us */
476 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
477 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
481 amd_pmu_disable_virt();
484 static int svm_hardware_enable(void)
487 struct svm_cpu_data *sd;
489 struct desc_struct *gdt;
490 int me = raw_smp_processor_id();
492 rdmsrl(MSR_EFER, efer);
493 if (efer & EFER_SVME)
497 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
500 sd = per_cpu(svm_data, me);
502 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
506 sd->asid_generation = 1;
507 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
508 sd->next_asid = sd->max_asid + 1;
509 sd->min_asid = max_sev_asid + 1;
511 gdt = get_current_gdt_rw();
512 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
514 wrmsrl(MSR_EFER, efer | EFER_SVME);
516 wrmsrl(MSR_VM_HSAVE_PA, __sme_page_pa(sd->save_area));
518 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
519 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
520 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
527 * Note that it is possible to have a system with mixed processor
528 * revisions and therefore different OSVW bits. If bits are not the same
529 * on different processors then choose the worst case (i.e. if erratum
530 * is present on one processor and not on another then assume that the
531 * erratum is present everywhere).
533 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
534 uint64_t len, status = 0;
537 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
539 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
543 osvw_status = osvw_len = 0;
547 osvw_status |= status;
548 osvw_status &= (1ULL << osvw_len) - 1;
551 osvw_status = osvw_len = 0;
553 svm_init_erratum_383();
555 amd_pmu_enable_virt();
560 static void svm_cpu_uninit(int cpu)
562 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
567 per_cpu(svm_data, cpu) = NULL;
568 kfree(sd->sev_vmcbs);
569 __free_page(sd->save_area);
573 static int svm_cpu_init(int cpu)
575 struct svm_cpu_data *sd;
578 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
582 sd->save_area = alloc_page(GFP_KERNEL);
586 clear_page(page_address(sd->save_area));
588 ret = sev_cpu_init(sd);
592 per_cpu(svm_data, cpu) = sd;
597 __free_page(sd->save_area);
604 static int direct_access_msr_slot(u32 msr)
608 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
609 if (direct_access_msrs[i].index == msr)
615 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
618 struct vcpu_svm *svm = to_svm(vcpu);
619 int slot = direct_access_msr_slot(msr);
624 /* Set the shadow bitmaps to the desired intercept states */
626 set_bit(slot, svm->shadow_msr_intercept.read);
628 clear_bit(slot, svm->shadow_msr_intercept.read);
631 set_bit(slot, svm->shadow_msr_intercept.write);
633 clear_bit(slot, svm->shadow_msr_intercept.write);
636 static bool valid_msr_intercept(u32 index)
638 return direct_access_msr_slot(index) != -ENOENT;
641 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
648 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
651 offset = svm_msrpm_offset(msr);
652 bit_write = 2 * (msr & 0x0f) + 1;
655 BUG_ON(offset == MSR_INVALID);
657 return !!test_bit(bit_write, &tmp);
660 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
661 u32 msr, int read, int write)
663 u8 bit_read, bit_write;
668 * If this warning triggers extend the direct_access_msrs list at the
669 * beginning of the file
671 WARN_ON(!valid_msr_intercept(msr));
673 /* Enforce non allowed MSRs to trap */
674 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
677 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
680 offset = svm_msrpm_offset(msr);
681 bit_read = 2 * (msr & 0x0f);
682 bit_write = 2 * (msr & 0x0f) + 1;
685 BUG_ON(offset == MSR_INVALID);
687 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
688 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
692 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
696 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
699 set_shadow_msr_intercept(vcpu, msr, read, write);
700 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
703 u32 *svm_vcpu_alloc_msrpm(void)
705 unsigned int order = get_order(MSRPM_SIZE);
706 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
712 msrpm = page_address(pages);
713 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
718 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
722 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
723 if (!direct_access_msrs[i].always)
725 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
730 void svm_vcpu_free_msrpm(u32 *msrpm)
732 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
735 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
737 struct vcpu_svm *svm = to_svm(vcpu);
741 * Set intercept permissions for all direct access MSRs again. They
742 * will automatically get filtered through the MSR filter, so we are
743 * back in sync after this.
745 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
746 u32 msr = direct_access_msrs[i].index;
747 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
748 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
750 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
754 static void add_msr_offset(u32 offset)
758 for (i = 0; i < MSRPM_OFFSETS; ++i) {
760 /* Offset already in list? */
761 if (msrpm_offsets[i] == offset)
764 /* Slot used by another offset? */
765 if (msrpm_offsets[i] != MSR_INVALID)
768 /* Add offset to list */
769 msrpm_offsets[i] = offset;
775 * If this BUG triggers the msrpm_offsets table has an overflow. Just
776 * increase MSRPM_OFFSETS in this case.
781 static void init_msrpm_offsets(void)
785 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
787 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
790 offset = svm_msrpm_offset(direct_access_msrs[i].index);
791 BUG_ON(offset == MSR_INVALID);
793 add_msr_offset(offset);
797 static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
799 struct vcpu_svm *svm = to_svm(vcpu);
801 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
802 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
803 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
804 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
805 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
808 static void svm_disable_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, 0, 0);
814 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
815 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
816 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
819 void disable_nmi_singlestep(struct vcpu_svm *svm)
821 svm->nmi_singlestep = false;
823 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
824 /* Clear our flags if they were not set by the guest */
825 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
826 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
827 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
828 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
832 static void grow_ple_window(struct kvm_vcpu *vcpu)
834 struct vcpu_svm *svm = to_svm(vcpu);
835 struct vmcb_control_area *control = &svm->vmcb->control;
836 int old = control->pause_filter_count;
838 control->pause_filter_count = __grow_ple_window(old,
840 pause_filter_count_grow,
841 pause_filter_count_max);
843 if (control->pause_filter_count != old) {
844 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
845 trace_kvm_ple_window_update(vcpu->vcpu_id,
846 control->pause_filter_count, old);
850 static void shrink_ple_window(struct kvm_vcpu *vcpu)
852 struct vcpu_svm *svm = to_svm(vcpu);
853 struct vmcb_control_area *control = &svm->vmcb->control;
854 int old = control->pause_filter_count;
856 control->pause_filter_count =
857 __shrink_ple_window(old,
859 pause_filter_count_shrink,
861 if (control->pause_filter_count != old) {
862 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
863 trace_kvm_ple_window_update(vcpu->vcpu_id,
864 control->pause_filter_count, old);
869 * The default MMIO mask is a single bit (excluding the present bit),
870 * which could conflict with the memory encryption bit. Check for
871 * memory encryption support and override the default MMIO mask if
872 * memory encryption is enabled.
874 static __init void svm_adjust_mmio_mask(void)
876 unsigned int enc_bit, mask_bit;
879 /* If there is no memory encryption support, use existing mask */
880 if (cpuid_eax(0x80000000) < 0x8000001f)
883 /* If memory encryption is not enabled, use existing mask */
884 rdmsrl(MSR_AMD64_SYSCFG, msr);
885 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
888 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
889 mask_bit = boot_cpu_data.x86_phys_bits;
891 /* Increment the mask bit if it is the same as the encryption bit */
892 if (enc_bit == mask_bit)
896 * If the mask bit location is below 52, then some bits above the
897 * physical addressing limit will always be reserved, so use the
898 * rsvd_bits() function to generate the mask. This mask, along with
899 * the present bit, will be used to generate a page fault with
902 * If the mask bit location is 52 (or above), then clear the mask.
904 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
906 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
909 static void svm_hardware_teardown(void)
913 sev_hardware_teardown();
915 for_each_possible_cpu(cpu)
918 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
919 get_order(IOPM_SIZE));
923 static __init void svm_set_cpu_caps(void)
929 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
931 kvm_cpu_cap_set(X86_FEATURE_SVM);
934 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
937 kvm_cpu_cap_set(X86_FEATURE_NPT);
939 /* Nested VM can receive #VMEXIT instead of triggering #GP */
940 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
943 /* CPUID 0x80000008 */
944 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
945 boot_cpu_has(X86_FEATURE_AMD_SSBD))
946 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
948 /* CPUID 0x8000001F (SME/SEV features) */
952 static __init int svm_hardware_setup(void)
955 struct page *iopm_pages;
958 unsigned int order = get_order(IOPM_SIZE);
961 * NX is required for shadow paging and for NPT if the NX huge pages
962 * mitigation is enabled.
964 if (!boot_cpu_has(X86_FEATURE_NX)) {
965 pr_err_ratelimited("NX (Execute Disable) not supported\n");
968 kvm_enable_efer_bits(EFER_NX);
970 iopm_pages = alloc_pages(GFP_KERNEL, order);
975 iopm_va = page_address(iopm_pages);
976 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
977 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
979 init_msrpm_offsets();
981 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
983 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
984 kvm_enable_efer_bits(EFER_FFXSR);
986 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
987 kvm_has_tsc_control = true;
988 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
989 kvm_tsc_scaling_ratio_frac_bits = 32;
992 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
994 /* Check for pause filtering support */
995 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
996 pause_filter_count = 0;
997 pause_filter_thresh = 0;
998 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
999 pause_filter_thresh = 0;
1003 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1004 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1008 * KVM's MMU doesn't support using 2-level paging for itself, and thus
1009 * NPT isn't supported if the host is using 2-level paging since host
1010 * CR4 is unchanged on VMRUN.
1012 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
1013 npt_enabled = false;
1015 if (!boot_cpu_has(X86_FEATURE_NPT))
1016 npt_enabled = false;
1018 kvm_configure_mmu(npt_enabled, get_max_npt_level(), PG_LEVEL_1G);
1019 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
1021 /* Note, SEV setup consumes npt_enabled. */
1022 sev_hardware_setup();
1024 svm_hv_hardware_setup();
1026 svm_adjust_mmio_mask();
1028 for_each_possible_cpu(cpu) {
1029 r = svm_cpu_init(cpu);
1035 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1039 enable_apicv = avic = avic && npt_enabled && boot_cpu_has(X86_FEATURE_AVIC);
1042 pr_info("AVIC enabled\n");
1044 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1049 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1050 !IS_ENABLED(CONFIG_X86_64)) {
1053 pr_info("Virtual VMLOAD VMSAVE supported\n");
1057 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
1058 svm_gp_erratum_intercept = false;
1061 if (!boot_cpu_has(X86_FEATURE_VGIF))
1064 pr_info("Virtual GIF supported\n");
1070 * It seems that on AMD processors PTE's accessed bit is
1071 * being set by the CPU hardware before the NPF vmexit.
1072 * This is not expected behaviour and our tests fail because
1074 * A workaround here is to disable support for
1075 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
1076 * In this case userspace can know if there is support using
1077 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
1079 * If future AMD CPU models change the behaviour described above,
1080 * this variable can be changed accordingly
1082 allow_smaller_maxphyaddr = !npt_enabled;
1087 svm_hardware_teardown();
1091 static void init_seg(struct vmcb_seg *seg)
1094 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1095 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1096 seg->limit = 0xffff;
1100 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1103 seg->attrib = SVM_SELECTOR_P_MASK | type;
1104 seg->limit = 0xffff;
1108 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1110 struct vcpu_svm *svm = to_svm(vcpu);
1112 return svm->nested.ctl.tsc_offset;
1115 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1117 return kvm_default_tsc_scaling_ratio;
1120 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1122 struct vcpu_svm *svm = to_svm(vcpu);
1124 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1125 svm->vmcb->control.tsc_offset = offset;
1126 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1129 static void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1131 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
1134 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1135 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1136 struct vcpu_svm *svm)
1139 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1140 * roots, or if INVPCID is disabled in the guest to inject #UD.
1142 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1144 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1145 svm_set_intercept(svm, INTERCEPT_INVPCID);
1147 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1150 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1151 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1152 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1154 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1158 static void init_vmcb(struct kvm_vcpu *vcpu)
1160 struct vcpu_svm *svm = to_svm(vcpu);
1161 struct vmcb_control_area *control = &svm->vmcb->control;
1162 struct vmcb_save_area *save = &svm->vmcb->save;
1164 vcpu->arch.hflags = 0;
1166 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1167 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1168 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1169 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1170 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1171 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1172 if (!kvm_vcpu_apicv_active(vcpu))
1173 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1175 set_dr_intercepts(svm);
1177 set_exception_intercept(svm, PF_VECTOR);
1178 set_exception_intercept(svm, UD_VECTOR);
1179 set_exception_intercept(svm, MC_VECTOR);
1180 set_exception_intercept(svm, AC_VECTOR);
1181 set_exception_intercept(svm, DB_VECTOR);
1183 * Guest access to VMware backdoor ports could legitimately
1184 * trigger #GP because of TSS I/O permission bitmap.
1185 * We intercept those #GP and allow access to them anyway
1188 if (enable_vmware_backdoor)
1189 set_exception_intercept(svm, GP_VECTOR);
1191 svm_set_intercept(svm, INTERCEPT_INTR);
1192 svm_set_intercept(svm, INTERCEPT_NMI);
1195 svm_set_intercept(svm, INTERCEPT_SMI);
1197 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1198 svm_set_intercept(svm, INTERCEPT_RDPMC);
1199 svm_set_intercept(svm, INTERCEPT_CPUID);
1200 svm_set_intercept(svm, INTERCEPT_INVD);
1201 svm_set_intercept(svm, INTERCEPT_INVLPG);
1202 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1203 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1204 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1205 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1206 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1207 svm_set_intercept(svm, INTERCEPT_VMRUN);
1208 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1209 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1210 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1211 svm_set_intercept(svm, INTERCEPT_STGI);
1212 svm_set_intercept(svm, INTERCEPT_CLGI);
1213 svm_set_intercept(svm, INTERCEPT_SKINIT);
1214 svm_set_intercept(svm, INTERCEPT_WBINVD);
1215 svm_set_intercept(svm, INTERCEPT_XSETBV);
1216 svm_set_intercept(svm, INTERCEPT_RDPRU);
1217 svm_set_intercept(svm, INTERCEPT_RSM);
1219 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1220 svm_set_intercept(svm, INTERCEPT_MONITOR);
1221 svm_set_intercept(svm, INTERCEPT_MWAIT);
1224 if (!kvm_hlt_in_guest(vcpu->kvm))
1225 svm_set_intercept(svm, INTERCEPT_HLT);
1227 control->iopm_base_pa = __sme_set(iopm_base);
1228 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1229 control->int_ctl = V_INTR_MASKING_MASK;
1231 init_seg(&save->es);
1232 init_seg(&save->ss);
1233 init_seg(&save->ds);
1234 init_seg(&save->fs);
1235 init_seg(&save->gs);
1237 save->cs.selector = 0xf000;
1238 save->cs.base = 0xffff0000;
1239 /* Executable/Readable Code Segment */
1240 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1241 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1242 save->cs.limit = 0xffff;
1244 save->gdtr.limit = 0xffff;
1245 save->idtr.limit = 0xffff;
1247 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1248 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1250 svm_set_cr4(vcpu, 0);
1251 svm_set_efer(vcpu, 0);
1252 save->dr6 = 0xffff0ff0;
1253 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
1254 save->rip = 0x0000fff0;
1255 vcpu->arch.regs[VCPU_REGS_RIP] = save->rip;
1258 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1259 * It also updates the guest-visible cr0 value.
1261 svm_set_cr0(vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1262 kvm_mmu_reset_context(vcpu);
1264 save->cr4 = X86_CR4_PAE;
1268 /* Setup VMCB for Nested Paging */
1269 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1270 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1271 clr_exception_intercept(svm, PF_VECTOR);
1272 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1273 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1274 save->g_pat = vcpu->arch.pat;
1278 svm->current_vmcb->asid_generation = 0;
1281 svm->nested.vmcb12_gpa = INVALID_GPA;
1282 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1283 vcpu->arch.hflags = 0;
1285 if (!kvm_pause_in_guest(vcpu->kvm)) {
1286 control->pause_filter_count = pause_filter_count;
1287 if (pause_filter_thresh)
1288 control->pause_filter_thresh = pause_filter_thresh;
1289 svm_set_intercept(svm, INTERCEPT_PAUSE);
1291 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1294 svm_recalc_instruction_intercepts(vcpu, svm);
1297 * If the host supports V_SPEC_CTRL then disable the interception
1298 * of MSR_IA32_SPEC_CTRL.
1300 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1301 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1303 if (kvm_vcpu_apicv_active(vcpu))
1304 avic_init_vmcb(svm);
1307 svm_clr_intercept(svm, INTERCEPT_STGI);
1308 svm_clr_intercept(svm, INTERCEPT_CLGI);
1309 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1312 if (sev_guest(vcpu->kvm)) {
1313 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1314 clr_exception_intercept(svm, UD_VECTOR);
1316 if (sev_es_guest(vcpu->kvm)) {
1317 /* Perform SEV-ES specific VMCB updates */
1318 sev_es_init_vmcb(svm);
1322 svm_hv_init_vmcb(svm->vmcb);
1324 vmcb_mark_all_dirty(svm->vmcb);
1330 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1332 struct vcpu_svm *svm = to_svm(vcpu);
1337 svm->virt_spec_ctrl = 0;
1340 vcpu->arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1341 MSR_IA32_APICBASE_ENABLE;
1342 if (kvm_vcpu_is_reset_bsp(vcpu))
1343 vcpu->arch.apic_base |= MSR_IA32_APICBASE_BSP;
1347 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, false);
1348 kvm_rdx_write(vcpu, eax);
1350 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1351 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1354 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1356 svm->current_vmcb = target_vmcb;
1357 svm->vmcb = target_vmcb->ptr;
1360 static int svm_create_vcpu(struct kvm_vcpu *vcpu)
1362 struct vcpu_svm *svm;
1363 struct page *vmcb01_page;
1364 struct page *vmsa_page = NULL;
1367 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1371 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1375 if (sev_es_guest(vcpu->kvm)) {
1377 * SEV-ES guests require a separate VMSA page used to contain
1378 * the encrypted register state of the guest.
1380 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1382 goto error_free_vmcb_page;
1385 * SEV-ES guests maintain an encrypted version of their FPU
1386 * state which is restored and saved on VMRUN and VMEXIT.
1387 * Free the fpu structure to prevent KVM from attempting to
1388 * access the FPU state.
1390 kvm_free_guest_fpu(vcpu);
1393 err = avic_init_vcpu(svm);
1395 goto error_free_vmsa_page;
1397 /* We initialize this flag to true to make sure that the is_running
1398 * bit would be set the first time the vcpu is loaded.
1400 if (irqchip_in_kernel(vcpu->kvm) && kvm_apicv_activated(vcpu->kvm))
1401 svm->avic_is_running = true;
1403 svm->msrpm = svm_vcpu_alloc_msrpm();
1406 goto error_free_vmsa_page;
1409 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1411 svm->vmcb01.ptr = page_address(vmcb01_page);
1412 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1415 svm->vmsa = page_address(vmsa_page);
1417 svm->guest_state_loaded = false;
1419 svm_switch_vmcb(svm, &svm->vmcb01);
1422 svm_init_osvw(vcpu);
1423 vcpu->arch.microcode_version = 0x01000065;
1425 if (sev_es_guest(vcpu->kvm))
1426 /* Perform SEV-ES specific VMCB creation updates */
1427 sev_es_create_vcpu(svm);
1431 error_free_vmsa_page:
1433 __free_page(vmsa_page);
1434 error_free_vmcb_page:
1435 __free_page(vmcb01_page);
1440 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1444 for_each_online_cpu(i)
1445 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
1448 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
1450 struct vcpu_svm *svm = to_svm(vcpu);
1453 * The vmcb page can be recycled, causing a false negative in
1454 * svm_vcpu_load(). So, ensure that no logical CPU has this
1455 * vmcb page recorded as its current vmcb.
1457 svm_clear_current_vmcb(svm->vmcb);
1459 svm_free_nested(svm);
1461 sev_free_vcpu(vcpu);
1463 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1464 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1467 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
1469 struct vcpu_svm *svm = to_svm(vcpu);
1470 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
1472 if (sev_es_guest(vcpu->kvm))
1473 sev_es_unmap_ghcb(svm);
1475 if (svm->guest_state_loaded)
1479 * Save additional host state that will be restored on VMEXIT (sev-es)
1480 * or subsequent vmload of host save area.
1482 if (sev_es_guest(vcpu->kvm)) {
1483 sev_es_prepare_guest_switch(svm, vcpu->cpu);
1485 vmsave(__sme_page_pa(sd->save_area));
1488 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1489 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
1490 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
1491 __this_cpu_write(current_tsc_ratio, tsc_ratio);
1492 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
1496 if (likely(tsc_aux_uret_slot >= 0))
1497 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1499 svm->guest_state_loaded = true;
1502 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1504 to_svm(vcpu)->guest_state_loaded = false;
1507 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1509 struct vcpu_svm *svm = to_svm(vcpu);
1510 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1512 if (sd->current_vmcb != svm->vmcb) {
1513 sd->current_vmcb = svm->vmcb;
1514 indirect_branch_prediction_barrier();
1516 avic_vcpu_load(vcpu, cpu);
1519 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1521 avic_vcpu_put(vcpu);
1522 svm_prepare_host_switch(vcpu);
1524 ++vcpu->stat.host_state_reload;
1527 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1529 struct vcpu_svm *svm = to_svm(vcpu);
1530 unsigned long rflags = svm->vmcb->save.rflags;
1532 if (svm->nmi_singlestep) {
1533 /* Hide our flags if they were not set by the guest */
1534 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1535 rflags &= ~X86_EFLAGS_TF;
1536 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1537 rflags &= ~X86_EFLAGS_RF;
1542 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1544 if (to_svm(vcpu)->nmi_singlestep)
1545 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1548 * Any change of EFLAGS.VM is accompanied by a reload of SS
1549 * (caused by either a task switch or an inter-privilege IRET),
1550 * so we do not need to update the CPL here.
1552 to_svm(vcpu)->vmcb->save.rflags = rflags;
1555 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1558 case VCPU_EXREG_PDPTR:
1559 BUG_ON(!npt_enabled);
1560 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
1567 static void svm_set_vintr(struct vcpu_svm *svm)
1569 struct vmcb_control_area *control;
1571 /* The following fields are ignored when AVIC is enabled */
1572 WARN_ON(kvm_vcpu_apicv_active(&svm->vcpu));
1573 svm_set_intercept(svm, INTERCEPT_VINTR);
1576 * This is just a dummy VINTR to actually cause a vmexit to happen.
1577 * Actual injection of virtual interrupts happens through EVENTINJ.
1579 control = &svm->vmcb->control;
1580 control->int_vector = 0x0;
1581 control->int_ctl &= ~V_INTR_PRIO_MASK;
1582 control->int_ctl |= V_IRQ_MASK |
1583 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1584 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1587 static void svm_clear_vintr(struct vcpu_svm *svm)
1589 const u32 mask = V_TPR_MASK | V_GIF_ENABLE_MASK | V_GIF_MASK | V_INTR_MASKING_MASK;
1590 svm_clr_intercept(svm, INTERCEPT_VINTR);
1592 /* Drop int_ctl fields related to VINTR injection. */
1593 svm->vmcb->control.int_ctl &= mask;
1594 if (is_guest_mode(&svm->vcpu)) {
1595 svm->vmcb01.ptr->control.int_ctl &= mask;
1597 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1598 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1599 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl & ~mask;
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 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1743 struct vcpu_svm *svm = to_svm(vcpu);
1746 #ifdef CONFIG_X86_64
1747 if (vcpu->arch.efer & EFER_LME && !vcpu->arch.guest_state_protected) {
1748 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1749 vcpu->arch.efer |= EFER_LMA;
1750 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1753 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1754 vcpu->arch.efer &= ~EFER_LMA;
1755 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1759 vcpu->arch.cr0 = cr0;
1762 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1765 * re-enable caching here because the QEMU bios
1766 * does not do it - this results in some delay at
1769 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1770 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1772 svm->vmcb->save.cr0 = hcr0;
1773 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1776 * SEV-ES guests must always keep the CR intercepts cleared. CR
1777 * tracking is done using the CR write traps.
1779 if (sev_es_guest(vcpu->kvm))
1783 /* Selective CR0 write remains on. */
1784 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1785 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1787 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1788 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1792 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1797 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1799 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1800 unsigned long old_cr4 = vcpu->arch.cr4;
1802 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1803 svm_flush_tlb(vcpu);
1805 vcpu->arch.cr4 = cr4;
1808 cr4 |= host_cr4_mce;
1809 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1810 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1812 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1813 kvm_update_cpuid_runtime(vcpu);
1816 static void svm_set_segment(struct kvm_vcpu *vcpu,
1817 struct kvm_segment *var, int seg)
1819 struct vcpu_svm *svm = to_svm(vcpu);
1820 struct vmcb_seg *s = svm_seg(vcpu, seg);
1822 s->base = var->base;
1823 s->limit = var->limit;
1824 s->selector = var->selector;
1825 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1826 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1827 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1828 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1829 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1830 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1831 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1832 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1835 * This is always accurate, except if SYSRET returned to a segment
1836 * with SS.DPL != 3. Intel does not have this quirk, and always
1837 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1838 * would entail passing the CPL to userspace and back.
1840 if (seg == VCPU_SREG_SS)
1841 /* This is symmetric with svm_get_segment() */
1842 svm->vmcb->save.cpl = (var->dpl & 3);
1844 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1847 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1849 struct vcpu_svm *svm = to_svm(vcpu);
1851 clr_exception_intercept(svm, BP_VECTOR);
1853 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1854 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1855 set_exception_intercept(svm, BP_VECTOR);
1859 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1861 if (sd->next_asid > sd->max_asid) {
1862 ++sd->asid_generation;
1863 sd->next_asid = sd->min_asid;
1864 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1865 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1868 svm->current_vmcb->asid_generation = sd->asid_generation;
1869 svm->asid = sd->next_asid++;
1872 static void svm_set_dr6(struct vcpu_svm *svm, unsigned long value)
1874 struct vmcb *vmcb = svm->vmcb;
1876 if (svm->vcpu.arch.guest_state_protected)
1879 if (unlikely(value != vmcb->save.dr6)) {
1880 vmcb->save.dr6 = value;
1881 vmcb_mark_dirty(vmcb, VMCB_DR);
1885 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1887 struct vcpu_svm *svm = to_svm(vcpu);
1889 if (vcpu->arch.guest_state_protected)
1892 get_debugreg(vcpu->arch.db[0], 0);
1893 get_debugreg(vcpu->arch.db[1], 1);
1894 get_debugreg(vcpu->arch.db[2], 2);
1895 get_debugreg(vcpu->arch.db[3], 3);
1897 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1898 * because db_interception might need it. We can do it before vmentry.
1900 vcpu->arch.dr6 = svm->vmcb->save.dr6;
1901 vcpu->arch.dr7 = svm->vmcb->save.dr7;
1902 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1903 set_dr_intercepts(svm);
1906 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1908 struct vcpu_svm *svm = to_svm(vcpu);
1910 if (vcpu->arch.guest_state_protected)
1913 svm->vmcb->save.dr7 = value;
1914 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
1917 static int pf_interception(struct kvm_vcpu *vcpu)
1919 struct vcpu_svm *svm = to_svm(vcpu);
1921 u64 fault_address = svm->vmcb->control.exit_info_2;
1922 u64 error_code = svm->vmcb->control.exit_info_1;
1924 return kvm_handle_page_fault(vcpu, error_code, fault_address,
1925 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1926 svm->vmcb->control.insn_bytes : NULL,
1927 svm->vmcb->control.insn_len);
1930 static int npf_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 trace_kvm_page_fault(fault_address, error_code);
1938 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
1939 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1940 svm->vmcb->control.insn_bytes : NULL,
1941 svm->vmcb->control.insn_len);
1944 static int db_interception(struct kvm_vcpu *vcpu)
1946 struct kvm_run *kvm_run = vcpu->run;
1947 struct vcpu_svm *svm = to_svm(vcpu);
1949 if (!(vcpu->guest_debug &
1950 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1951 !svm->nmi_singlestep) {
1952 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
1953 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
1957 if (svm->nmi_singlestep) {
1958 disable_nmi_singlestep(svm);
1959 /* Make sure we check for pending NMIs upon entry */
1960 kvm_make_request(KVM_REQ_EVENT, vcpu);
1963 if (vcpu->guest_debug &
1964 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
1965 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1966 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
1967 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
1968 kvm_run->debug.arch.pc =
1969 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1970 kvm_run->debug.arch.exception = DB_VECTOR;
1977 static int bp_interception(struct kvm_vcpu *vcpu)
1979 struct vcpu_svm *svm = to_svm(vcpu);
1980 struct kvm_run *kvm_run = vcpu->run;
1982 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1983 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1984 kvm_run->debug.arch.exception = BP_VECTOR;
1988 static int ud_interception(struct kvm_vcpu *vcpu)
1990 return handle_ud(vcpu);
1993 static int ac_interception(struct kvm_vcpu *vcpu)
1995 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
1999 static bool is_erratum_383(void)
2004 if (!erratum_383_found)
2007 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2011 /* Bit 62 may or may not be set for this mce */
2012 value &= ~(1ULL << 62);
2014 if (value != 0xb600000000010015ULL)
2017 /* Clear MCi_STATUS registers */
2018 for (i = 0; i < 6; ++i)
2019 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2021 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2025 value &= ~(1ULL << 2);
2026 low = lower_32_bits(value);
2027 high = upper_32_bits(value);
2029 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2032 /* Flush tlb to evict multi-match entries */
2038 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2040 if (is_erratum_383()) {
2042 * Erratum 383 triggered. Guest state is corrupt so kill the
2045 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2047 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2053 * On an #MC intercept the MCE handler is not called automatically in
2054 * the host. So do it by hand here.
2056 kvm_machine_check();
2059 static int mc_interception(struct kvm_vcpu *vcpu)
2064 static int shutdown_interception(struct kvm_vcpu *vcpu)
2066 struct kvm_run *kvm_run = vcpu->run;
2067 struct vcpu_svm *svm = to_svm(vcpu);
2070 * The VM save area has already been encrypted so it
2071 * cannot be reinitialized - just terminate.
2073 if (sev_es_guest(vcpu->kvm))
2077 * VMCB is undefined after a SHUTDOWN intercept
2078 * so reinitialize it.
2080 clear_page(svm->vmcb);
2083 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2087 static int io_interception(struct kvm_vcpu *vcpu)
2089 struct vcpu_svm *svm = to_svm(vcpu);
2090 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2091 int size, in, string;
2094 ++vcpu->stat.io_exits;
2095 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2096 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2097 port = io_info >> 16;
2098 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2101 if (sev_es_guest(vcpu->kvm))
2102 return sev_es_string_io(svm, size, port, in);
2104 return kvm_emulate_instruction(vcpu, 0);
2107 svm->next_rip = svm->vmcb->control.exit_info_2;
2109 return kvm_fast_pio(vcpu, size, port, in);
2112 static int nmi_interception(struct kvm_vcpu *vcpu)
2117 static int smi_interception(struct kvm_vcpu *vcpu)
2122 static int intr_interception(struct kvm_vcpu *vcpu)
2124 ++vcpu->stat.irq_exits;
2128 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2130 struct vcpu_svm *svm = to_svm(vcpu);
2131 struct vmcb *vmcb12;
2132 struct kvm_host_map map;
2135 if (nested_svm_check_permissions(vcpu))
2138 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2141 kvm_inject_gp(vcpu, 0);
2147 ret = kvm_skip_emulated_instruction(vcpu);
2150 nested_svm_vmloadsave(vmcb12, svm->vmcb);
2151 svm->sysenter_eip_hi = 0;
2152 svm->sysenter_esp_hi = 0;
2154 nested_svm_vmloadsave(svm->vmcb, vmcb12);
2156 kvm_vcpu_unmap(vcpu, &map, true);
2161 static int vmload_interception(struct kvm_vcpu *vcpu)
2163 return vmload_vmsave_interception(vcpu, true);
2166 static int vmsave_interception(struct kvm_vcpu *vcpu)
2168 return vmload_vmsave_interception(vcpu, false);
2171 static int vmrun_interception(struct kvm_vcpu *vcpu)
2173 if (nested_svm_check_permissions(vcpu))
2176 return nested_svm_vmrun(vcpu);
2186 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
2187 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2189 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2191 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2192 return NONE_SVM_INSTR;
2194 switch (ctxt->modrm) {
2195 case 0xd8: /* VMRUN */
2196 return SVM_INSTR_VMRUN;
2197 case 0xda: /* VMLOAD */
2198 return SVM_INSTR_VMLOAD;
2199 case 0xdb: /* VMSAVE */
2200 return SVM_INSTR_VMSAVE;
2205 return NONE_SVM_INSTR;
2208 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2210 const int guest_mode_exit_codes[] = {
2211 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2212 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2213 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2215 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2216 [SVM_INSTR_VMRUN] = vmrun_interception,
2217 [SVM_INSTR_VMLOAD] = vmload_interception,
2218 [SVM_INSTR_VMSAVE] = vmsave_interception,
2220 struct vcpu_svm *svm = to_svm(vcpu);
2223 if (is_guest_mode(vcpu)) {
2224 /* Returns '1' or -errno on failure, '0' on success. */
2225 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2230 return svm_instr_handlers[opcode](vcpu);
2234 * #GP handling code. Note that #GP can be triggered under the following two
2236 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2237 * some AMD CPUs when EAX of these instructions are in the reserved memory
2238 * regions (e.g. SMM memory on host).
2239 * 2) VMware backdoor
2241 static int gp_interception(struct kvm_vcpu *vcpu)
2243 struct vcpu_svm *svm = to_svm(vcpu);
2244 u32 error_code = svm->vmcb->control.exit_info_1;
2247 /* Both #GP cases have zero error_code */
2251 /* Decode the instruction for usage later */
2252 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2255 opcode = svm_instr_opcode(vcpu);
2257 if (opcode == NONE_SVM_INSTR) {
2258 if (!enable_vmware_backdoor)
2262 * VMware backdoor emulation on #GP interception only handles
2263 * IN{S}, OUT{S}, and RDPMC.
2265 if (!is_guest_mode(vcpu))
2266 return kvm_emulate_instruction(vcpu,
2267 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2269 return emulate_svm_instr(vcpu, opcode);
2272 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2276 void svm_set_gif(struct vcpu_svm *svm, bool value)
2280 * If VGIF is enabled, the STGI intercept is only added to
2281 * detect the opening of the SMI/NMI window; remove it now.
2282 * Likewise, clear the VINTR intercept, we will set it
2283 * again while processing KVM_REQ_EVENT if needed.
2285 if (vgif_enabled(svm))
2286 svm_clr_intercept(svm, INTERCEPT_STGI);
2287 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2288 svm_clear_vintr(svm);
2291 if (svm->vcpu.arch.smi_pending ||
2292 svm->vcpu.arch.nmi_pending ||
2293 kvm_cpu_has_injectable_intr(&svm->vcpu))
2294 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2299 * After a CLGI no interrupts should come. But if vGIF is
2300 * in use, we still rely on the VINTR intercept (rather than
2301 * STGI) to detect an open interrupt window.
2303 if (!vgif_enabled(svm))
2304 svm_clear_vintr(svm);
2308 static int stgi_interception(struct kvm_vcpu *vcpu)
2312 if (nested_svm_check_permissions(vcpu))
2315 ret = kvm_skip_emulated_instruction(vcpu);
2316 svm_set_gif(to_svm(vcpu), true);
2320 static int clgi_interception(struct kvm_vcpu *vcpu)
2324 if (nested_svm_check_permissions(vcpu))
2327 ret = kvm_skip_emulated_instruction(vcpu);
2328 svm_set_gif(to_svm(vcpu), false);
2332 static int invlpga_interception(struct kvm_vcpu *vcpu)
2334 gva_t gva = kvm_rax_read(vcpu);
2335 u32 asid = kvm_rcx_read(vcpu);
2337 /* FIXME: Handle an address size prefix. */
2338 if (!is_long_mode(vcpu))
2341 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2343 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2344 kvm_mmu_invlpg(vcpu, gva);
2346 return kvm_skip_emulated_instruction(vcpu);
2349 static int skinit_interception(struct kvm_vcpu *vcpu)
2351 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2353 kvm_queue_exception(vcpu, UD_VECTOR);
2357 static int task_switch_interception(struct kvm_vcpu *vcpu)
2359 struct vcpu_svm *svm = to_svm(vcpu);
2362 int int_type = svm->vmcb->control.exit_int_info &
2363 SVM_EXITINTINFO_TYPE_MASK;
2364 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2366 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2368 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2369 bool has_error_code = false;
2372 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2374 if (svm->vmcb->control.exit_info_2 &
2375 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2376 reason = TASK_SWITCH_IRET;
2377 else if (svm->vmcb->control.exit_info_2 &
2378 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2379 reason = TASK_SWITCH_JMP;
2381 reason = TASK_SWITCH_GATE;
2383 reason = TASK_SWITCH_CALL;
2385 if (reason == TASK_SWITCH_GATE) {
2387 case SVM_EXITINTINFO_TYPE_NMI:
2388 vcpu->arch.nmi_injected = false;
2390 case SVM_EXITINTINFO_TYPE_EXEPT:
2391 if (svm->vmcb->control.exit_info_2 &
2392 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2393 has_error_code = true;
2395 (u32)svm->vmcb->control.exit_info_2;
2397 kvm_clear_exception_queue(vcpu);
2399 case SVM_EXITINTINFO_TYPE_INTR:
2400 kvm_clear_interrupt_queue(vcpu);
2407 if (reason != TASK_SWITCH_GATE ||
2408 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2409 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2410 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2411 if (!skip_emulated_instruction(vcpu))
2415 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2418 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2419 has_error_code, error_code);
2422 static int iret_interception(struct kvm_vcpu *vcpu)
2424 struct vcpu_svm *svm = to_svm(vcpu);
2426 ++vcpu->stat.nmi_window_exits;
2427 vcpu->arch.hflags |= HF_IRET_MASK;
2428 if (!sev_es_guest(vcpu->kvm)) {
2429 svm_clr_intercept(svm, INTERCEPT_IRET);
2430 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2432 kvm_make_request(KVM_REQ_EVENT, vcpu);
2436 static int invlpg_interception(struct kvm_vcpu *vcpu)
2438 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2439 return kvm_emulate_instruction(vcpu, 0);
2441 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2442 return kvm_skip_emulated_instruction(vcpu);
2445 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2447 return kvm_emulate_instruction(vcpu, 0);
2450 static int rsm_interception(struct kvm_vcpu *vcpu)
2452 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2455 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2458 struct vcpu_svm *svm = to_svm(vcpu);
2459 unsigned long cr0 = vcpu->arch.cr0;
2462 if (!is_guest_mode(vcpu) ||
2463 (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2466 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2467 val &= ~SVM_CR0_SELECTIVE_MASK;
2470 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2471 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2477 #define CR_VALID (1ULL << 63)
2479 static int cr_interception(struct kvm_vcpu *vcpu)
2481 struct vcpu_svm *svm = to_svm(vcpu);
2486 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2487 return emulate_on_interception(vcpu);
2489 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2490 return emulate_on_interception(vcpu);
2492 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2493 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2494 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2496 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2499 if (cr >= 16) { /* mov to cr */
2501 val = kvm_register_read(vcpu, reg);
2502 trace_kvm_cr_write(cr, val);
2505 if (!check_selective_cr0_intercepted(vcpu, val))
2506 err = kvm_set_cr0(vcpu, val);
2512 err = kvm_set_cr3(vcpu, val);
2515 err = kvm_set_cr4(vcpu, val);
2518 err = kvm_set_cr8(vcpu, val);
2521 WARN(1, "unhandled write to CR%d", cr);
2522 kvm_queue_exception(vcpu, UD_VECTOR);
2525 } else { /* mov from cr */
2528 val = kvm_read_cr0(vcpu);
2531 val = vcpu->arch.cr2;
2534 val = kvm_read_cr3(vcpu);
2537 val = kvm_read_cr4(vcpu);
2540 val = kvm_get_cr8(vcpu);
2543 WARN(1, "unhandled read from CR%d", cr);
2544 kvm_queue_exception(vcpu, UD_VECTOR);
2547 kvm_register_write(vcpu, reg, val);
2548 trace_kvm_cr_read(cr, val);
2550 return kvm_complete_insn_gp(vcpu, err);
2553 static int cr_trap(struct kvm_vcpu *vcpu)
2555 struct vcpu_svm *svm = to_svm(vcpu);
2556 unsigned long old_value, new_value;
2560 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2562 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2565 old_value = kvm_read_cr0(vcpu);
2566 svm_set_cr0(vcpu, new_value);
2568 kvm_post_set_cr0(vcpu, old_value, new_value);
2571 old_value = kvm_read_cr4(vcpu);
2572 svm_set_cr4(vcpu, new_value);
2574 kvm_post_set_cr4(vcpu, old_value, new_value);
2577 ret = kvm_set_cr8(vcpu, new_value);
2580 WARN(1, "unhandled CR%d write trap", cr);
2581 kvm_queue_exception(vcpu, UD_VECTOR);
2585 return kvm_complete_insn_gp(vcpu, ret);
2588 static int dr_interception(struct kvm_vcpu *vcpu)
2590 struct vcpu_svm *svm = to_svm(vcpu);
2595 if (vcpu->guest_debug == 0) {
2597 * No more DR vmexits; force a reload of the debug registers
2598 * and reenter on this instruction. The next vmexit will
2599 * retrieve the full state of the debug registers.
2601 clr_dr_intercepts(svm);
2602 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2606 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2607 return emulate_on_interception(vcpu);
2609 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2610 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2611 if (dr >= 16) { /* mov to DRn */
2613 val = kvm_register_read(vcpu, reg);
2614 err = kvm_set_dr(vcpu, dr, val);
2616 kvm_get_dr(vcpu, dr, &val);
2617 kvm_register_write(vcpu, reg, val);
2620 return kvm_complete_insn_gp(vcpu, err);
2623 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2627 u8 cr8_prev = kvm_get_cr8(vcpu);
2628 /* instruction emulation calls kvm_set_cr8() */
2629 r = cr_interception(vcpu);
2630 if (lapic_in_kernel(vcpu))
2632 if (cr8_prev <= kvm_get_cr8(vcpu))
2634 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2638 static int efer_trap(struct kvm_vcpu *vcpu)
2640 struct msr_data msr_info;
2644 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2645 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2646 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2647 * the guest doesn't have X86_FEATURE_SVM.
2649 msr_info.host_initiated = false;
2650 msr_info.index = MSR_EFER;
2651 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2652 ret = kvm_set_msr_common(vcpu, &msr_info);
2654 return kvm_complete_insn_gp(vcpu, ret);
2657 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2661 switch (msr->index) {
2662 case MSR_F10H_DECFG:
2663 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
2664 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
2666 case MSR_IA32_PERF_CAPABILITIES:
2669 return KVM_MSR_RET_INVALID;
2675 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2677 struct vcpu_svm *svm = to_svm(vcpu);
2679 switch (msr_info->index) {
2681 msr_info->data = svm->vmcb01.ptr->save.star;
2683 #ifdef CONFIG_X86_64
2685 msr_info->data = svm->vmcb01.ptr->save.lstar;
2688 msr_info->data = svm->vmcb01.ptr->save.cstar;
2690 case MSR_KERNEL_GS_BASE:
2691 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2693 case MSR_SYSCALL_MASK:
2694 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2697 case MSR_IA32_SYSENTER_CS:
2698 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2700 case MSR_IA32_SYSENTER_EIP:
2701 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2702 if (guest_cpuid_is_intel(vcpu))
2703 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2705 case MSR_IA32_SYSENTER_ESP:
2706 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2707 if (guest_cpuid_is_intel(vcpu))
2708 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2711 msr_info->data = svm->tsc_aux;
2714 * Nobody will change the following 5 values in the VMCB so we can
2715 * safely return them on rdmsr. They will always be 0 until LBRV is
2718 case MSR_IA32_DEBUGCTLMSR:
2719 msr_info->data = svm->vmcb->save.dbgctl;
2721 case MSR_IA32_LASTBRANCHFROMIP:
2722 msr_info->data = svm->vmcb->save.br_from;
2724 case MSR_IA32_LASTBRANCHTOIP:
2725 msr_info->data = svm->vmcb->save.br_to;
2727 case MSR_IA32_LASTINTFROMIP:
2728 msr_info->data = svm->vmcb->save.last_excp_from;
2730 case MSR_IA32_LASTINTTOIP:
2731 msr_info->data = svm->vmcb->save.last_excp_to;
2733 case MSR_VM_HSAVE_PA:
2734 msr_info->data = svm->nested.hsave_msr;
2737 msr_info->data = svm->nested.vm_cr_msr;
2739 case MSR_IA32_SPEC_CTRL:
2740 if (!msr_info->host_initiated &&
2741 !guest_has_spec_ctrl_msr(vcpu))
2744 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2745 msr_info->data = svm->vmcb->save.spec_ctrl;
2747 msr_info->data = svm->spec_ctrl;
2749 case MSR_AMD64_VIRT_SPEC_CTRL:
2750 if (!msr_info->host_initiated &&
2751 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2754 msr_info->data = svm->virt_spec_ctrl;
2756 case MSR_F15H_IC_CFG: {
2760 family = guest_cpuid_family(vcpu);
2761 model = guest_cpuid_model(vcpu);
2763 if (family < 0 || model < 0)
2764 return kvm_get_msr_common(vcpu, msr_info);
2768 if (family == 0x15 &&
2769 (model >= 0x2 && model < 0x20))
2770 msr_info->data = 0x1E;
2773 case MSR_F10H_DECFG:
2774 msr_info->data = svm->msr_decfg;
2777 return kvm_get_msr_common(vcpu, msr_info);
2782 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2784 struct vcpu_svm *svm = to_svm(vcpu);
2785 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->ghcb))
2786 return kvm_complete_insn_gp(vcpu, err);
2788 ghcb_set_sw_exit_info_1(svm->ghcb, 1);
2789 ghcb_set_sw_exit_info_2(svm->ghcb,
2791 SVM_EVTINJ_TYPE_EXEPT |
2796 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2798 struct vcpu_svm *svm = to_svm(vcpu);
2799 int svm_dis, chg_mask;
2801 if (data & ~SVM_VM_CR_VALID_MASK)
2804 chg_mask = SVM_VM_CR_VALID_MASK;
2806 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2807 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2809 svm->nested.vm_cr_msr &= ~chg_mask;
2810 svm->nested.vm_cr_msr |= (data & chg_mask);
2812 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2814 /* check for svm_disable while efer.svme is set */
2815 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
2821 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2823 struct vcpu_svm *svm = to_svm(vcpu);
2826 u32 ecx = msr->index;
2827 u64 data = msr->data;
2829 case MSR_IA32_CR_PAT:
2830 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2832 vcpu->arch.pat = data;
2833 svm->vmcb01.ptr->save.g_pat = data;
2834 if (is_guest_mode(vcpu))
2835 nested_vmcb02_compute_g_pat(svm);
2836 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
2838 case MSR_IA32_SPEC_CTRL:
2839 if (!msr->host_initiated &&
2840 !guest_has_spec_ctrl_msr(vcpu))
2843 if (kvm_spec_ctrl_test_value(data))
2846 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2847 svm->vmcb->save.spec_ctrl = data;
2849 svm->spec_ctrl = data;
2855 * When it's written (to non-zero) for the first time, pass
2859 * The handling of the MSR bitmap for L2 guests is done in
2860 * nested_svm_vmrun_msrpm.
2861 * We update the L1 MSR bit as well since it will end up
2862 * touching the MSR anyway now.
2864 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
2866 case MSR_IA32_PRED_CMD:
2867 if (!msr->host_initiated &&
2868 !guest_has_pred_cmd_msr(vcpu))
2871 if (data & ~PRED_CMD_IBPB)
2873 if (!boot_cpu_has(X86_FEATURE_IBPB))
2878 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2879 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
2881 case MSR_AMD64_VIRT_SPEC_CTRL:
2882 if (!msr->host_initiated &&
2883 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2886 if (data & ~SPEC_CTRL_SSBD)
2889 svm->virt_spec_ctrl = data;
2892 svm->vmcb01.ptr->save.star = data;
2894 #ifdef CONFIG_X86_64
2896 svm->vmcb01.ptr->save.lstar = data;
2899 svm->vmcb01.ptr->save.cstar = data;
2901 case MSR_KERNEL_GS_BASE:
2902 svm->vmcb01.ptr->save.kernel_gs_base = data;
2904 case MSR_SYSCALL_MASK:
2905 svm->vmcb01.ptr->save.sfmask = data;
2908 case MSR_IA32_SYSENTER_CS:
2909 svm->vmcb01.ptr->save.sysenter_cs = data;
2911 case MSR_IA32_SYSENTER_EIP:
2912 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
2914 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
2915 * when we spoof an Intel vendor ID (for cross vendor migration).
2916 * In this case we use this intercept to track the high
2917 * 32 bit part of these msrs to support Intel's
2918 * implementation of SYSENTER/SYSEXIT.
2920 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2922 case MSR_IA32_SYSENTER_ESP:
2923 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
2924 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2928 * TSC_AUX is usually changed only during boot and never read
2929 * directly. Intercept TSC_AUX instead of exposing it to the
2930 * guest via direct_access_msrs, and switch it via user return.
2933 r = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
2938 svm->tsc_aux = data;
2940 case MSR_IA32_DEBUGCTLMSR:
2941 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
2942 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
2946 if (data & DEBUGCTL_RESERVED_BITS)
2949 svm->vmcb->save.dbgctl = data;
2950 vmcb_mark_dirty(svm->vmcb, VMCB_LBR);
2951 if (data & (1ULL<<0))
2952 svm_enable_lbrv(vcpu);
2954 svm_disable_lbrv(vcpu);
2956 case MSR_VM_HSAVE_PA:
2958 * Old kernels did not validate the value written to
2959 * MSR_VM_HSAVE_PA. Allow KVM_SET_MSR to set an invalid
2960 * value to allow live migrating buggy or malicious guests
2961 * originating from those kernels.
2963 if (!msr->host_initiated && !page_address_valid(vcpu, data))
2966 svm->nested.hsave_msr = data & PAGE_MASK;
2969 return svm_set_vm_cr(vcpu, data);
2971 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
2973 case MSR_F10H_DECFG: {
2974 struct kvm_msr_entry msr_entry;
2976 msr_entry.index = msr->index;
2977 if (svm_get_msr_feature(&msr_entry))
2980 /* Check the supported bits */
2981 if (data & ~msr_entry.data)
2984 /* Don't allow the guest to change a bit, #GP */
2985 if (!msr->host_initiated && (data ^ msr_entry.data))
2988 svm->msr_decfg = data;
2991 case MSR_IA32_APICBASE:
2992 if (kvm_vcpu_apicv_active(vcpu))
2993 avic_update_vapic_bar(to_svm(vcpu), data);
2996 return kvm_set_msr_common(vcpu, msr);
3001 static int msr_interception(struct kvm_vcpu *vcpu)
3003 if (to_svm(vcpu)->vmcb->control.exit_info_1)
3004 return kvm_emulate_wrmsr(vcpu);
3006 return kvm_emulate_rdmsr(vcpu);
3009 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
3011 kvm_make_request(KVM_REQ_EVENT, vcpu);
3012 svm_clear_vintr(to_svm(vcpu));
3015 * For AVIC, the only reason to end up here is ExtINTs.
3016 * In this case AVIC was temporarily disabled for
3017 * requesting the IRQ window and we have to re-enable it.
3019 svm_toggle_avic_for_irq_window(vcpu, true);
3021 ++vcpu->stat.irq_window_exits;
3025 static int pause_interception(struct kvm_vcpu *vcpu)
3030 * CPL is not made available for an SEV-ES guest, therefore
3031 * vcpu->arch.preempted_in_kernel can never be true. Just
3032 * set in_kernel to false as well.
3034 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3036 if (!kvm_pause_in_guest(vcpu->kvm))
3037 grow_ple_window(vcpu);
3039 kvm_vcpu_on_spin(vcpu, in_kernel);
3040 return kvm_skip_emulated_instruction(vcpu);
3043 static int invpcid_interception(struct kvm_vcpu *vcpu)
3045 struct vcpu_svm *svm = to_svm(vcpu);
3049 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3050 kvm_queue_exception(vcpu, UD_VECTOR);
3055 * For an INVPCID intercept:
3056 * EXITINFO1 provides the linear address of the memory operand.
3057 * EXITINFO2 provides the contents of the register operand.
3059 type = svm->vmcb->control.exit_info_2;
3060 gva = svm->vmcb->control.exit_info_1;
3063 kvm_inject_gp(vcpu, 0);
3067 return kvm_handle_invpcid(vcpu, type, gva);
3070 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3071 [SVM_EXIT_READ_CR0] = cr_interception,
3072 [SVM_EXIT_READ_CR3] = cr_interception,
3073 [SVM_EXIT_READ_CR4] = cr_interception,
3074 [SVM_EXIT_READ_CR8] = cr_interception,
3075 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3076 [SVM_EXIT_WRITE_CR0] = cr_interception,
3077 [SVM_EXIT_WRITE_CR3] = cr_interception,
3078 [SVM_EXIT_WRITE_CR4] = cr_interception,
3079 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3080 [SVM_EXIT_READ_DR0] = dr_interception,
3081 [SVM_EXIT_READ_DR1] = dr_interception,
3082 [SVM_EXIT_READ_DR2] = dr_interception,
3083 [SVM_EXIT_READ_DR3] = dr_interception,
3084 [SVM_EXIT_READ_DR4] = dr_interception,
3085 [SVM_EXIT_READ_DR5] = dr_interception,
3086 [SVM_EXIT_READ_DR6] = dr_interception,
3087 [SVM_EXIT_READ_DR7] = dr_interception,
3088 [SVM_EXIT_WRITE_DR0] = dr_interception,
3089 [SVM_EXIT_WRITE_DR1] = dr_interception,
3090 [SVM_EXIT_WRITE_DR2] = dr_interception,
3091 [SVM_EXIT_WRITE_DR3] = dr_interception,
3092 [SVM_EXIT_WRITE_DR4] = dr_interception,
3093 [SVM_EXIT_WRITE_DR5] = dr_interception,
3094 [SVM_EXIT_WRITE_DR6] = dr_interception,
3095 [SVM_EXIT_WRITE_DR7] = dr_interception,
3096 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3097 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3098 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3099 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3100 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3101 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3102 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3103 [SVM_EXIT_INTR] = intr_interception,
3104 [SVM_EXIT_NMI] = nmi_interception,
3105 [SVM_EXIT_SMI] = smi_interception,
3106 [SVM_EXIT_VINTR] = interrupt_window_interception,
3107 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3108 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3109 [SVM_EXIT_IRET] = iret_interception,
3110 [SVM_EXIT_INVD] = kvm_emulate_invd,
3111 [SVM_EXIT_PAUSE] = pause_interception,
3112 [SVM_EXIT_HLT] = kvm_emulate_halt,
3113 [SVM_EXIT_INVLPG] = invlpg_interception,
3114 [SVM_EXIT_INVLPGA] = invlpga_interception,
3115 [SVM_EXIT_IOIO] = io_interception,
3116 [SVM_EXIT_MSR] = msr_interception,
3117 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3118 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3119 [SVM_EXIT_VMRUN] = vmrun_interception,
3120 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3121 [SVM_EXIT_VMLOAD] = vmload_interception,
3122 [SVM_EXIT_VMSAVE] = vmsave_interception,
3123 [SVM_EXIT_STGI] = stgi_interception,
3124 [SVM_EXIT_CLGI] = clgi_interception,
3125 [SVM_EXIT_SKINIT] = skinit_interception,
3126 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3127 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3128 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3129 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3130 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3131 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3132 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3133 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3134 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3135 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3136 [SVM_EXIT_INVPCID] = invpcid_interception,
3137 [SVM_EXIT_NPF] = npf_interception,
3138 [SVM_EXIT_RSM] = rsm_interception,
3139 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3140 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3141 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3144 static void dump_vmcb(struct kvm_vcpu *vcpu)
3146 struct vcpu_svm *svm = to_svm(vcpu);
3147 struct vmcb_control_area *control = &svm->vmcb->control;
3148 struct vmcb_save_area *save = &svm->vmcb->save;
3149 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3151 if (!dump_invalid_vmcb) {
3152 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3156 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3157 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3158 pr_err("VMCB Control Area:\n");
3159 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3160 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3161 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3162 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3163 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3164 pr_err("%-20s%08x %08x\n", "intercepts:",
3165 control->intercepts[INTERCEPT_WORD3],
3166 control->intercepts[INTERCEPT_WORD4]);
3167 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3168 pr_err("%-20s%d\n", "pause filter threshold:",
3169 control->pause_filter_thresh);
3170 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3171 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3172 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3173 pr_err("%-20s%d\n", "asid:", control->asid);
3174 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3175 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3176 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3177 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3178 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3179 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3180 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3181 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3182 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3183 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3184 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3185 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3186 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3187 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3188 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3189 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3190 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3191 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3192 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3193 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3194 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3195 pr_err("VMCB State Save Area:\n");
3196 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3198 save->es.selector, save->es.attrib,
3199 save->es.limit, save->es.base);
3200 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3202 save->cs.selector, save->cs.attrib,
3203 save->cs.limit, save->cs.base);
3204 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3206 save->ss.selector, save->ss.attrib,
3207 save->ss.limit, save->ss.base);
3208 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3210 save->ds.selector, save->ds.attrib,
3211 save->ds.limit, save->ds.base);
3212 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3214 save01->fs.selector, save01->fs.attrib,
3215 save01->fs.limit, save01->fs.base);
3216 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3218 save01->gs.selector, save01->gs.attrib,
3219 save01->gs.limit, save01->gs.base);
3220 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3222 save->gdtr.selector, save->gdtr.attrib,
3223 save->gdtr.limit, save->gdtr.base);
3224 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3226 save01->ldtr.selector, save01->ldtr.attrib,
3227 save01->ldtr.limit, save01->ldtr.base);
3228 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3230 save->idtr.selector, save->idtr.attrib,
3231 save->idtr.limit, save->idtr.base);
3232 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3234 save01->tr.selector, save01->tr.attrib,
3235 save01->tr.limit, save01->tr.base);
3236 pr_err("cpl: %d efer: %016llx\n",
3237 save->cpl, save->efer);
3238 pr_err("%-15s %016llx %-13s %016llx\n",
3239 "cr0:", save->cr0, "cr2:", save->cr2);
3240 pr_err("%-15s %016llx %-13s %016llx\n",
3241 "cr3:", save->cr3, "cr4:", save->cr4);
3242 pr_err("%-15s %016llx %-13s %016llx\n",
3243 "dr6:", save->dr6, "dr7:", save->dr7);
3244 pr_err("%-15s %016llx %-13s %016llx\n",
3245 "rip:", save->rip, "rflags:", save->rflags);
3246 pr_err("%-15s %016llx %-13s %016llx\n",
3247 "rsp:", save->rsp, "rax:", save->rax);
3248 pr_err("%-15s %016llx %-13s %016llx\n",
3249 "star:", save01->star, "lstar:", save01->lstar);
3250 pr_err("%-15s %016llx %-13s %016llx\n",
3251 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3252 pr_err("%-15s %016llx %-13s %016llx\n",
3253 "kernel_gs_base:", save01->kernel_gs_base,
3254 "sysenter_cs:", save01->sysenter_cs);
3255 pr_err("%-15s %016llx %-13s %016llx\n",
3256 "sysenter_esp:", save01->sysenter_esp,
3257 "sysenter_eip:", save01->sysenter_eip);
3258 pr_err("%-15s %016llx %-13s %016llx\n",
3259 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3260 pr_err("%-15s %016llx %-13s %016llx\n",
3261 "br_from:", save->br_from, "br_to:", save->br_to);
3262 pr_err("%-15s %016llx %-13s %016llx\n",
3263 "excp_from:", save->last_excp_from,
3264 "excp_to:", save->last_excp_to);
3267 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3269 if (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3270 svm_exit_handlers[exit_code])
3273 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3275 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3276 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3277 vcpu->run->internal.ndata = 2;
3278 vcpu->run->internal.data[0] = exit_code;
3279 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3284 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3286 if (svm_handle_invalid_exit(vcpu, exit_code))
3289 #ifdef CONFIG_RETPOLINE
3290 if (exit_code == SVM_EXIT_MSR)
3291 return msr_interception(vcpu);
3292 else if (exit_code == SVM_EXIT_VINTR)
3293 return interrupt_window_interception(vcpu);
3294 else if (exit_code == SVM_EXIT_INTR)
3295 return intr_interception(vcpu);
3296 else if (exit_code == SVM_EXIT_HLT)
3297 return kvm_emulate_halt(vcpu);
3298 else if (exit_code == SVM_EXIT_NPF)
3299 return npf_interception(vcpu);
3301 return svm_exit_handlers[exit_code](vcpu);
3304 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2,
3305 u32 *intr_info, u32 *error_code)
3307 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3309 *info1 = control->exit_info_1;
3310 *info2 = control->exit_info_2;
3311 *intr_info = control->exit_int_info;
3312 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3313 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3314 *error_code = control->exit_int_info_err;
3319 static int handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3321 struct vcpu_svm *svm = to_svm(vcpu);
3322 struct kvm_run *kvm_run = vcpu->run;
3323 u32 exit_code = svm->vmcb->control.exit_code;
3325 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
3327 /* SEV-ES guests must use the CR write traps to track CR registers. */
3328 if (!sev_es_guest(vcpu->kvm)) {
3329 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3330 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3332 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3335 if (is_guest_mode(vcpu)) {
3338 trace_kvm_nested_vmexit(exit_code, vcpu, KVM_ISA_SVM);
3340 vmexit = nested_svm_exit_special(svm);
3342 if (vmexit == NESTED_EXIT_CONTINUE)
3343 vmexit = nested_svm_exit_handled(svm);
3345 if (vmexit == NESTED_EXIT_DONE)
3349 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3350 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3351 kvm_run->fail_entry.hardware_entry_failure_reason
3352 = svm->vmcb->control.exit_code;
3353 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3358 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
3359 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
3360 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
3361 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
3362 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
3364 __func__, svm->vmcb->control.exit_int_info,
3367 if (exit_fastpath != EXIT_FASTPATH_NONE)
3370 return svm_invoke_exit_handler(vcpu, exit_code);
3373 static void reload_tss(struct kvm_vcpu *vcpu)
3375 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3377 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3381 static void pre_svm_run(struct kvm_vcpu *vcpu)
3383 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3384 struct vcpu_svm *svm = to_svm(vcpu);
3387 * If the previous vmrun of the vmcb occurred on a different physical
3388 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3389 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3391 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3392 svm->current_vmcb->asid_generation = 0;
3393 vmcb_mark_all_dirty(svm->vmcb);
3394 svm->current_vmcb->cpu = vcpu->cpu;
3397 if (sev_guest(vcpu->kvm))
3398 return pre_sev_run(svm, vcpu->cpu);
3400 /* FIXME: handle wraparound of asid_generation */
3401 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3405 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3407 struct vcpu_svm *svm = to_svm(vcpu);
3409 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3410 vcpu->arch.hflags |= HF_NMI_MASK;
3411 if (!sev_es_guest(vcpu->kvm))
3412 svm_set_intercept(svm, INTERCEPT_IRET);
3413 ++vcpu->stat.nmi_injections;
3416 static void svm_set_irq(struct kvm_vcpu *vcpu)
3418 struct vcpu_svm *svm = to_svm(vcpu);
3420 BUG_ON(!(gif_set(svm)));
3422 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
3423 ++vcpu->stat.irq_injections;
3425 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3426 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
3429 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3431 struct vcpu_svm *svm = to_svm(vcpu);
3434 * SEV-ES guests must always keep the CR intercepts cleared. CR
3435 * tracking is done using the CR write traps.
3437 if (sev_es_guest(vcpu->kvm))
3440 if (nested_svm_virtualize_tpr(vcpu))
3443 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3449 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3452 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3454 struct vcpu_svm *svm = to_svm(vcpu);
3455 struct vmcb *vmcb = svm->vmcb;
3461 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3464 ret = (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) ||
3465 (vcpu->arch.hflags & HF_NMI_MASK);
3470 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3472 struct vcpu_svm *svm = to_svm(vcpu);
3473 if (svm->nested.nested_run_pending)
3476 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3477 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3480 return !svm_nmi_blocked(vcpu);
3483 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3485 return !!(vcpu->arch.hflags & HF_NMI_MASK);
3488 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3490 struct vcpu_svm *svm = to_svm(vcpu);
3493 vcpu->arch.hflags |= HF_NMI_MASK;
3494 if (!sev_es_guest(vcpu->kvm))
3495 svm_set_intercept(svm, INTERCEPT_IRET);
3497 vcpu->arch.hflags &= ~HF_NMI_MASK;
3498 if (!sev_es_guest(vcpu->kvm))
3499 svm_clr_intercept(svm, INTERCEPT_IRET);
3503 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3505 struct vcpu_svm *svm = to_svm(vcpu);
3506 struct vmcb *vmcb = svm->vmcb;
3511 if (sev_es_guest(vcpu->kvm)) {
3513 * SEV-ES guests to not expose RFLAGS. Use the VMCB interrupt mask
3514 * bit to determine the state of the IF flag.
3516 if (!(vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK))
3518 } else if (is_guest_mode(vcpu)) {
3519 /* As long as interrupts are being delivered... */
3520 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3521 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3522 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3525 /* ... vmexits aren't blocked by the interrupt shadow */
3526 if (nested_exit_on_intr(svm))
3529 if (!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3533 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3536 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3538 struct vcpu_svm *svm = to_svm(vcpu);
3539 if (svm->nested.nested_run_pending)
3543 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3544 * e.g. if the IRQ arrived asynchronously after checking nested events.
3546 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3549 return !svm_interrupt_blocked(vcpu);
3552 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3554 struct vcpu_svm *svm = to_svm(vcpu);
3557 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3558 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3559 * get that intercept, this function will be called again though and
3560 * we'll get the vintr intercept. However, if the vGIF feature is
3561 * enabled, the STGI interception will not occur. Enable the irq
3562 * window under the assumption that the hardware will set the GIF.
3564 if (vgif_enabled(svm) || gif_set(svm)) {
3566 * IRQ window is not needed when AVIC is enabled,
3567 * unless we have pending ExtINT since it cannot be injected
3568 * via AVIC. In such case, we need to temporarily disable AVIC,
3569 * and fallback to injecting IRQ via V_IRQ.
3571 svm_toggle_avic_for_irq_window(vcpu, false);
3576 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3578 struct vcpu_svm *svm = to_svm(vcpu);
3580 if ((vcpu->arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK)
3581 return; /* IRET will cause a vm exit */
3583 if (!gif_set(svm)) {
3584 if (vgif_enabled(svm))
3585 svm_set_intercept(svm, INTERCEPT_STGI);
3586 return; /* STGI will cause a vm exit */
3590 * Something prevents NMI from been injected. Single step over possible
3591 * problem (IRET or exception injection or interrupt shadow)
3593 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3594 svm->nmi_singlestep = true;
3595 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3598 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
3603 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
3608 void svm_flush_tlb(struct kvm_vcpu *vcpu)
3610 struct vcpu_svm *svm = to_svm(vcpu);
3613 * Flush only the current ASID even if the TLB flush was invoked via
3614 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3615 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3616 * unconditionally does a TLB flush on both nested VM-Enter and nested
3617 * VM-Exit (via kvm_mmu_reset_context()).
3619 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3620 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3622 svm->current_vmcb->asid_generation--;
3625 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
3627 struct vcpu_svm *svm = to_svm(vcpu);
3629 invlpga(gva, svm->vmcb->control.asid);
3632 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3634 struct vcpu_svm *svm = to_svm(vcpu);
3636 if (nested_svm_virtualize_tpr(vcpu))
3639 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
3640 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3641 kvm_set_cr8(vcpu, cr8);
3645 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3647 struct vcpu_svm *svm = to_svm(vcpu);
3650 if (nested_svm_virtualize_tpr(vcpu) ||
3651 kvm_vcpu_apicv_active(vcpu))
3654 cr8 = kvm_get_cr8(vcpu);
3655 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3656 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3659 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
3661 struct vcpu_svm *svm = to_svm(vcpu);
3664 u32 exitintinfo = svm->vmcb->control.exit_int_info;
3665 unsigned int3_injected = svm->int3_injected;
3667 svm->int3_injected = 0;
3670 * If we've made progress since setting HF_IRET_MASK, we've
3671 * executed an IRET and can allow NMI injection.
3673 if ((vcpu->arch.hflags & HF_IRET_MASK) &&
3674 (sev_es_guest(vcpu->kvm) ||
3675 kvm_rip_read(vcpu) != svm->nmi_iret_rip)) {
3676 vcpu->arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3677 kvm_make_request(KVM_REQ_EVENT, vcpu);
3680 vcpu->arch.nmi_injected = false;
3681 kvm_clear_exception_queue(vcpu);
3682 kvm_clear_interrupt_queue(vcpu);
3684 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3687 kvm_make_request(KVM_REQ_EVENT, vcpu);
3689 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3690 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3693 case SVM_EXITINTINFO_TYPE_NMI:
3694 vcpu->arch.nmi_injected = true;
3696 case SVM_EXITINTINFO_TYPE_EXEPT:
3698 * Never re-inject a #VC exception.
3700 if (vector == X86_TRAP_VC)
3704 * In case of software exceptions, do not reinject the vector,
3705 * but re-execute the instruction instead. Rewind RIP first
3706 * if we emulated INT3 before.
3708 if (kvm_exception_is_soft(vector)) {
3709 if (vector == BP_VECTOR && int3_injected &&
3710 kvm_is_linear_rip(vcpu, svm->int3_rip))
3712 kvm_rip_read(vcpu) - int3_injected);
3715 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3716 u32 err = svm->vmcb->control.exit_int_info_err;
3717 kvm_requeue_exception_e(vcpu, vector, err);
3720 kvm_requeue_exception(vcpu, vector);
3722 case SVM_EXITINTINFO_TYPE_INTR:
3723 kvm_queue_interrupt(vcpu, vector, false);
3730 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3732 struct vcpu_svm *svm = to_svm(vcpu);
3733 struct vmcb_control_area *control = &svm->vmcb->control;
3735 control->exit_int_info = control->event_inj;
3736 control->exit_int_info_err = control->event_inj_err;
3737 control->event_inj = 0;
3738 svm_complete_interrupts(vcpu);
3741 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
3743 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_MSR &&
3744 to_svm(vcpu)->vmcb->control.exit_info_1)
3745 return handle_fastpath_set_msr_irqoff(vcpu);
3747 return EXIT_FASTPATH_NONE;
3750 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
3752 struct vcpu_svm *svm = to_svm(vcpu);
3753 unsigned long vmcb_pa = svm->current_vmcb->pa;
3755 kvm_guest_enter_irqoff();
3757 if (sev_es_guest(vcpu->kvm)) {
3758 __svm_sev_es_vcpu_run(vmcb_pa);
3760 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3763 * Use a single vmcb (vmcb01 because it's always valid) for
3764 * context switching guest state via VMLOAD/VMSAVE, that way
3765 * the state doesn't need to be copied between vmcb01 and
3766 * vmcb02 when switching vmcbs for nested virtualization.
3768 vmload(svm->vmcb01.pa);
3769 __svm_vcpu_run(vmcb_pa, (unsigned long *)&vcpu->arch.regs);
3770 vmsave(svm->vmcb01.pa);
3772 vmload(__sme_page_pa(sd->save_area));
3775 kvm_guest_exit_irqoff();
3778 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
3780 struct vcpu_svm *svm = to_svm(vcpu);
3782 trace_kvm_entry(vcpu);
3784 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3785 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3786 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3789 * Disable singlestep if we're injecting an interrupt/exception.
3790 * We don't want our modified rflags to be pushed on the stack where
3791 * we might not be able to easily reset them if we disabled NMI
3794 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
3796 * Event injection happens before external interrupts cause a
3797 * vmexit and interrupts are disabled here, so smp_send_reschedule
3798 * is enough to force an immediate vmexit.
3800 disable_nmi_singlestep(svm);
3801 smp_send_reschedule(vcpu->cpu);
3806 sync_lapic_to_cr8(vcpu);
3808 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
3809 svm->vmcb->control.asid = svm->asid;
3810 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3812 svm->vmcb->save.cr2 = vcpu->arch.cr2;
3814 svm_hv_update_vp_id(svm->vmcb, vcpu);
3817 * Run with all-zero DR6 unless needed, so that we can get the exact cause
3820 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
3821 svm_set_dr6(svm, vcpu->arch.dr6);
3823 svm_set_dr6(svm, DR6_ACTIVE_LOW);
3826 kvm_load_guest_xsave_state(vcpu);
3828 kvm_wait_lapic_expire(vcpu);
3831 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3832 * it's non-zero. Since vmentry is serialising on affected CPUs, there
3833 * is no need to worry about the conditional branch over the wrmsr
3834 * being speculatively taken.
3836 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3837 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
3839 svm_vcpu_enter_exit(vcpu);
3842 * We do not use IBRS in the kernel. If this vCPU has used the
3843 * SPEC_CTRL MSR it may have left it on; save the value and
3844 * turn it off. This is much more efficient than blindly adding
3845 * it to the atomic save/restore list. Especially as the former
3846 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
3848 * For non-nested case:
3849 * If the L01 MSR bitmap does not intercept the MSR, then we need to
3853 * If the L02 MSR bitmap does not intercept the MSR, then we need to
3856 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL) &&
3857 unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
3858 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
3860 if (!sev_es_guest(vcpu->kvm))
3863 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3864 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
3866 if (!sev_es_guest(vcpu->kvm)) {
3867 vcpu->arch.cr2 = svm->vmcb->save.cr2;
3868 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
3869 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
3870 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
3873 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3874 kvm_before_interrupt(vcpu);
3876 kvm_load_host_xsave_state(vcpu);
3879 /* Any pending NMI will happen here */
3881 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3882 kvm_after_interrupt(vcpu);
3884 sync_cr8_to_lapic(vcpu);
3887 if (is_guest_mode(vcpu)) {
3888 nested_sync_control_from_vmcb02(svm);
3890 /* Track VMRUNs that have made past consistency checking */
3891 if (svm->nested.nested_run_pending &&
3892 svm->vmcb->control.exit_code != SVM_EXIT_ERR)
3893 ++vcpu->stat.nested_run;
3895 svm->nested.nested_run_pending = 0;
3898 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
3899 vmcb_mark_all_clean(svm->vmcb);
3901 /* if exit due to PF check for async PF */
3902 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
3903 vcpu->arch.apf.host_apf_flags =
3904 kvm_read_and_reset_apf_flags();
3907 kvm_register_clear_available(vcpu, VCPU_EXREG_PDPTR);
3910 * We need to handle MC intercepts here before the vcpu has a chance to
3911 * change the physical cpu
3913 if (unlikely(svm->vmcb->control.exit_code ==
3914 SVM_EXIT_EXCP_BASE + MC_VECTOR))
3915 svm_handle_mce(vcpu);
3917 svm_complete_interrupts(vcpu);
3919 if (is_guest_mode(vcpu))
3920 return EXIT_FASTPATH_NONE;
3922 return svm_exit_handlers_fastpath(vcpu);
3925 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3928 struct vcpu_svm *svm = to_svm(vcpu);
3932 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
3933 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
3935 hv_track_root_tdp(vcpu, root_hpa);
3937 /* Loading L2's CR3 is handled by enter_svm_guest_mode. */
3938 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
3940 cr3 = vcpu->arch.cr3;
3941 } else if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
3942 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
3944 /* PCID in the guest should be impossible with a 32-bit MMU. */
3945 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
3949 svm->vmcb->save.cr3 = cr3;
3950 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
3953 static int is_disabled(void)
3957 rdmsrl(MSR_VM_CR, vm_cr);
3958 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
3965 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
3968 * Patch in the VMMCALL instruction:
3970 hypercall[0] = 0x0f;
3971 hypercall[1] = 0x01;
3972 hypercall[2] = 0xd9;
3975 static int __init svm_check_processor_compat(void)
3980 static bool svm_cpu_has_accelerated_tpr(void)
3986 * The kvm parameter can be NULL (module initialization, or invocation before
3987 * VM creation). Be sure to check the kvm parameter before using it.
3989 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
3992 case MSR_IA32_MCG_EXT_CTL:
3993 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3995 case MSR_IA32_SMBASE:
3996 /* SEV-ES guests do not support SMM, so report false */
3997 if (kvm && sev_es_guest(kvm))
4007 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4012 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4014 struct vcpu_svm *svm = to_svm(vcpu);
4015 struct kvm_cpuid_entry2 *best;
4017 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4018 boot_cpu_has(X86_FEATURE_XSAVE) &&
4019 boot_cpu_has(X86_FEATURE_XSAVES);
4021 /* Update nrips enabled cache */
4022 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
4023 guest_cpuid_has(vcpu, X86_FEATURE_NRIPS);
4025 svm_recalc_instruction_intercepts(vcpu, svm);
4027 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4028 if (sev_guest(vcpu->kvm)) {
4029 best = kvm_find_cpuid_entry(vcpu, 0x8000001F, 0);
4031 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4034 if (kvm_vcpu_apicv_active(vcpu)) {
4036 * AVIC does not work with an x2APIC mode guest. If the X2APIC feature
4037 * is exposed to the guest, disable AVIC.
4039 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC))
4040 kvm_request_apicv_update(vcpu->kvm, false,
4041 APICV_INHIBIT_REASON_X2APIC);
4044 * Currently, AVIC does not work with nested virtualization.
4045 * So, we disable AVIC when cpuid for SVM is set in the L1 guest.
4047 if (nested && guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4048 kvm_request_apicv_update(vcpu->kvm, false,
4049 APICV_INHIBIT_REASON_NESTED);
4052 if (guest_cpuid_is_intel(vcpu)) {
4054 * We must intercept SYSENTER_EIP and SYSENTER_ESP
4055 * accesses because the processor only stores 32 bits.
4056 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
4058 svm_set_intercept(svm, INTERCEPT_VMLOAD);
4059 svm_set_intercept(svm, INTERCEPT_VMSAVE);
4060 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
4062 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
4063 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
4066 * If hardware supports Virtual VMLOAD VMSAVE then enable it
4067 * in VMCB and clear intercepts to avoid #VMEXIT.
4070 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
4071 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
4072 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
4074 /* No need to intercept these MSRs */
4075 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
4076 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
4080 static bool svm_has_wbinvd_exit(void)
4085 #define PRE_EX(exit) { .exit_code = (exit), \
4086 .stage = X86_ICPT_PRE_EXCEPT, }
4087 #define POST_EX(exit) { .exit_code = (exit), \
4088 .stage = X86_ICPT_POST_EXCEPT, }
4089 #define POST_MEM(exit) { .exit_code = (exit), \
4090 .stage = X86_ICPT_POST_MEMACCESS, }
4092 static const struct __x86_intercept {
4094 enum x86_intercept_stage stage;
4095 } x86_intercept_map[] = {
4096 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4097 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4098 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4099 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4100 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4101 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4102 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4103 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4104 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4105 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4106 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4107 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4108 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4109 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4110 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4111 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4112 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4113 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4114 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4115 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4116 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4117 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4118 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4119 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4120 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4121 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4122 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4123 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4124 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4125 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4126 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4127 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4128 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4129 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4130 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4131 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4132 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4133 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4134 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4135 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4136 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4137 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4138 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4139 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4140 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4141 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4142 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4149 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4150 struct x86_instruction_info *info,
4151 enum x86_intercept_stage stage,
4152 struct x86_exception *exception)
4154 struct vcpu_svm *svm = to_svm(vcpu);
4155 int vmexit, ret = X86EMUL_CONTINUE;
4156 struct __x86_intercept icpt_info;
4157 struct vmcb *vmcb = svm->vmcb;
4159 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4162 icpt_info = x86_intercept_map[info->intercept];
4164 if (stage != icpt_info.stage)
4167 switch (icpt_info.exit_code) {
4168 case SVM_EXIT_READ_CR0:
4169 if (info->intercept == x86_intercept_cr_read)
4170 icpt_info.exit_code += info->modrm_reg;
4172 case SVM_EXIT_WRITE_CR0: {
4173 unsigned long cr0, val;
4175 if (info->intercept == x86_intercept_cr_write)
4176 icpt_info.exit_code += info->modrm_reg;
4178 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4179 info->intercept == x86_intercept_clts)
4182 if (!(vmcb_is_intercept(&svm->nested.ctl,
4183 INTERCEPT_SELECTIVE_CR0)))
4186 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4187 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4189 if (info->intercept == x86_intercept_lmsw) {
4192 /* lmsw can't clear PE - catch this here */
4193 if (cr0 & X86_CR0_PE)
4198 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4202 case SVM_EXIT_READ_DR0:
4203 case SVM_EXIT_WRITE_DR0:
4204 icpt_info.exit_code += info->modrm_reg;
4207 if (info->intercept == x86_intercept_wrmsr)
4208 vmcb->control.exit_info_1 = 1;
4210 vmcb->control.exit_info_1 = 0;
4212 case SVM_EXIT_PAUSE:
4214 * We get this for NOP only, but pause
4215 * is rep not, check this here
4217 if (info->rep_prefix != REPE_PREFIX)
4220 case SVM_EXIT_IOIO: {
4224 if (info->intercept == x86_intercept_in ||
4225 info->intercept == x86_intercept_ins) {
4226 exit_info = ((info->src_val & 0xffff) << 16) |
4228 bytes = info->dst_bytes;
4230 exit_info = (info->dst_val & 0xffff) << 16;
4231 bytes = info->src_bytes;
4234 if (info->intercept == x86_intercept_outs ||
4235 info->intercept == x86_intercept_ins)
4236 exit_info |= SVM_IOIO_STR_MASK;
4238 if (info->rep_prefix)
4239 exit_info |= SVM_IOIO_REP_MASK;
4241 bytes = min(bytes, 4u);
4243 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4245 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4247 vmcb->control.exit_info_1 = exit_info;
4248 vmcb->control.exit_info_2 = info->next_rip;
4256 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4257 if (static_cpu_has(X86_FEATURE_NRIPS))
4258 vmcb->control.next_rip = info->next_rip;
4259 vmcb->control.exit_code = icpt_info.exit_code;
4260 vmexit = nested_svm_exit_handled(svm);
4262 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4269 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4273 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4275 if (!kvm_pause_in_guest(vcpu->kvm))
4276 shrink_ple_window(vcpu);
4279 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4281 /* [63:9] are reserved. */
4282 vcpu->arch.mcg_cap &= 0x1ff;
4285 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4287 struct vcpu_svm *svm = to_svm(vcpu);
4289 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4293 return is_smm(vcpu);
4296 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4298 struct vcpu_svm *svm = to_svm(vcpu);
4299 if (svm->nested.nested_run_pending)
4302 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4303 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4306 return !svm_smi_blocked(vcpu);
4309 static int svm_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
4311 struct vcpu_svm *svm = to_svm(vcpu);
4312 struct kvm_host_map map_save;
4315 if (is_guest_mode(vcpu)) {
4316 /* FED8h - SVM Guest */
4317 put_smstate(u64, smstate, 0x7ed8, 1);
4318 /* FEE0h - SVM Guest VMCB Physical Address */
4319 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb12_gpa);
4321 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4322 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4323 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4325 ret = nested_svm_vmexit(svm);
4330 * KVM uses VMCB01 to store L1 host state while L2 runs but
4331 * VMCB01 is going to be used during SMM and thus the state will
4332 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4333 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4334 * format of the area is identical to guest save area offsetted
4335 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4336 * within 'struct vmcb'). Note: HSAVE area may also be used by
4337 * L1 hypervisor to save additional host context (e.g. KVM does
4338 * that, see svm_prepare_guest_switch()) which must be
4341 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4342 &map_save) == -EINVAL)
4345 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4347 svm_copy_vmrun_state(&svm->vmcb01.ptr->save,
4348 map_save.hva + 0x400);
4350 kvm_vcpu_unmap(vcpu, &map_save, true);
4355 static int svm_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
4357 struct vcpu_svm *svm = to_svm(vcpu);
4358 struct kvm_host_map map, map_save;
4361 if (guest_cpuid_has(vcpu, X86_FEATURE_LM)) {
4362 u64 saved_efer = GET_SMSTATE(u64, smstate, 0x7ed0);
4363 u64 guest = GET_SMSTATE(u64, smstate, 0x7ed8);
4364 u64 vmcb12_gpa = GET_SMSTATE(u64, smstate, 0x7ee0);
4365 struct vmcb *vmcb12;
4368 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4371 if (!(saved_efer & EFER_SVME))
4374 if (kvm_vcpu_map(vcpu,
4375 gpa_to_gfn(vmcb12_gpa), &map) == -EINVAL)
4378 if (svm_allocate_nested(svm))
4383 nested_load_control_from_vmcb12(svm, &vmcb12->control);
4385 ret = enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12);
4386 kvm_vcpu_unmap(vcpu, &map, true);
4389 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4390 * used during SMM (see svm_enter_smm())
4392 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4393 &map_save) == -EINVAL)
4396 svm_copy_vmrun_state(map_save.hva + 0x400,
4397 &svm->vmcb01.ptr->save);
4399 kvm_vcpu_unmap(vcpu, &map_save, true);
4406 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4408 struct vcpu_svm *svm = to_svm(vcpu);
4410 if (!gif_set(svm)) {
4411 if (vgif_enabled(svm))
4412 svm_set_intercept(svm, INTERCEPT_STGI);
4413 /* STGI will cause a vm exit */
4415 /* We must be in SMM; RSM will cause a vmexit anyway. */
4419 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
4421 bool smep, smap, is_user;
4425 * When the guest is an SEV-ES guest, emulation is not possible.
4427 if (sev_es_guest(vcpu->kvm))
4431 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4434 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
4435 * possible that CPU microcode implementing DecodeAssist will fail
4436 * to read bytes of instruction which caused #NPF. In this case,
4437 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
4438 * return 0 instead of the correct guest instruction bytes.
4440 * This happens because CPU microcode reading instruction bytes
4441 * uses a special opcode which attempts to read data using CPL=0
4442 * privileges. The microcode reads CS:RIP and if it hits a SMAP
4443 * fault, it gives up and returns no instruction bytes.
4446 * We reach here in case CPU supports DecodeAssist, raised #NPF and
4447 * returned 0 in GuestIntrBytes field of the VMCB.
4448 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
4449 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
4450 * in case vCPU CPL==3 (Because otherwise guest would have triggered
4451 * a SMEP fault instead of #NPF).
4452 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
4453 * As most guests enable SMAP if they have also enabled SMEP, use above
4454 * logic in order to attempt minimize false-positive of detecting errata
4455 * while still preserving all cases semantic correctness.
4458 * To determine what instruction the guest was executing, the hypervisor
4459 * will have to decode the instruction at the instruction pointer.
4461 * In non SEV guest, hypervisor will be able to read the guest
4462 * memory to decode the instruction pointer when insn_len is zero
4463 * so we return true to indicate that decoding is possible.
4465 * But in the SEV guest, the guest memory is encrypted with the
4466 * guest specific key and hypervisor will not be able to decode the
4467 * instruction pointer so we will not able to workaround it. Lets
4468 * print the error and request to kill the guest.
4470 if (likely(!insn || insn_len))
4474 * If RIP is invalid, go ahead with emulation which will cause an
4475 * internal error exit.
4477 if (!kvm_vcpu_gfn_to_memslot(vcpu, kvm_rip_read(vcpu) >> PAGE_SHIFT))
4480 cr4 = kvm_read_cr4(vcpu);
4481 smep = cr4 & X86_CR4_SMEP;
4482 smap = cr4 & X86_CR4_SMAP;
4483 is_user = svm_get_cpl(vcpu) == 3;
4484 if (smap && (!smep || is_user)) {
4485 if (!sev_guest(vcpu->kvm))
4488 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
4489 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4495 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4497 struct vcpu_svm *svm = to_svm(vcpu);
4500 * TODO: Last condition latch INIT signals on vCPU when
4501 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
4502 * To properly emulate the INIT intercept,
4503 * svm_check_nested_events() should call nested_svm_vmexit()
4504 * if an INIT signal is pending.
4506 return !gif_set(svm) ||
4507 (vmcb_is_intercept(&svm->vmcb->control, INTERCEPT_INIT));
4510 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4512 if (!sev_es_guest(vcpu->kvm))
4513 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4515 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4518 static void svm_vm_destroy(struct kvm *kvm)
4520 avic_vm_destroy(kvm);
4521 sev_vm_destroy(kvm);
4524 static int svm_vm_init(struct kvm *kvm)
4526 if (!pause_filter_count || !pause_filter_thresh)
4527 kvm->arch.pause_in_guest = true;
4530 int ret = avic_vm_init(kvm);
4538 static struct kvm_x86_ops svm_x86_ops __initdata = {
4539 .hardware_unsetup = svm_hardware_teardown,
4540 .hardware_enable = svm_hardware_enable,
4541 .hardware_disable = svm_hardware_disable,
4542 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
4543 .has_emulated_msr = svm_has_emulated_msr,
4545 .vcpu_create = svm_create_vcpu,
4546 .vcpu_free = svm_free_vcpu,
4547 .vcpu_reset = svm_vcpu_reset,
4549 .vm_size = sizeof(struct kvm_svm),
4550 .vm_init = svm_vm_init,
4551 .vm_destroy = svm_vm_destroy,
4553 .prepare_guest_switch = svm_prepare_guest_switch,
4554 .vcpu_load = svm_vcpu_load,
4555 .vcpu_put = svm_vcpu_put,
4556 .vcpu_blocking = svm_vcpu_blocking,
4557 .vcpu_unblocking = svm_vcpu_unblocking,
4559 .update_exception_bitmap = svm_update_exception_bitmap,
4560 .get_msr_feature = svm_get_msr_feature,
4561 .get_msr = svm_get_msr,
4562 .set_msr = svm_set_msr,
4563 .get_segment_base = svm_get_segment_base,
4564 .get_segment = svm_get_segment,
4565 .set_segment = svm_set_segment,
4566 .get_cpl = svm_get_cpl,
4567 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
4568 .set_cr0 = svm_set_cr0,
4569 .is_valid_cr4 = svm_is_valid_cr4,
4570 .set_cr4 = svm_set_cr4,
4571 .set_efer = svm_set_efer,
4572 .get_idt = svm_get_idt,
4573 .set_idt = svm_set_idt,
4574 .get_gdt = svm_get_gdt,
4575 .set_gdt = svm_set_gdt,
4576 .set_dr7 = svm_set_dr7,
4577 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4578 .cache_reg = svm_cache_reg,
4579 .get_rflags = svm_get_rflags,
4580 .set_rflags = svm_set_rflags,
4582 .tlb_flush_all = svm_flush_tlb,
4583 .tlb_flush_current = svm_flush_tlb,
4584 .tlb_flush_gva = svm_flush_tlb_gva,
4585 .tlb_flush_guest = svm_flush_tlb,
4587 .run = svm_vcpu_run,
4588 .handle_exit = handle_exit,
4589 .skip_emulated_instruction = skip_emulated_instruction,
4590 .update_emulated_instruction = NULL,
4591 .set_interrupt_shadow = svm_set_interrupt_shadow,
4592 .get_interrupt_shadow = svm_get_interrupt_shadow,
4593 .patch_hypercall = svm_patch_hypercall,
4594 .set_irq = svm_set_irq,
4595 .set_nmi = svm_inject_nmi,
4596 .queue_exception = svm_queue_exception,
4597 .cancel_injection = svm_cancel_injection,
4598 .interrupt_allowed = svm_interrupt_allowed,
4599 .nmi_allowed = svm_nmi_allowed,
4600 .get_nmi_mask = svm_get_nmi_mask,
4601 .set_nmi_mask = svm_set_nmi_mask,
4602 .enable_nmi_window = svm_enable_nmi_window,
4603 .enable_irq_window = svm_enable_irq_window,
4604 .update_cr8_intercept = svm_update_cr8_intercept,
4605 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
4606 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
4607 .check_apicv_inhibit_reasons = svm_check_apicv_inhibit_reasons,
4608 .pre_update_apicv_exec_ctrl = svm_pre_update_apicv_exec_ctrl,
4609 .load_eoi_exitmap = svm_load_eoi_exitmap,
4610 .hwapic_irr_update = svm_hwapic_irr_update,
4611 .hwapic_isr_update = svm_hwapic_isr_update,
4612 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
4613 .apicv_post_state_restore = avic_post_state_restore,
4615 .set_tss_addr = svm_set_tss_addr,
4616 .set_identity_map_addr = svm_set_identity_map_addr,
4617 .get_mt_mask = svm_get_mt_mask,
4619 .get_exit_info = svm_get_exit_info,
4621 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
4623 .has_wbinvd_exit = svm_has_wbinvd_exit,
4625 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
4626 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
4627 .write_tsc_offset = svm_write_tsc_offset,
4628 .write_tsc_multiplier = svm_write_tsc_multiplier,
4630 .load_mmu_pgd = svm_load_mmu_pgd,
4632 .check_intercept = svm_check_intercept,
4633 .handle_exit_irqoff = svm_handle_exit_irqoff,
4635 .request_immediate_exit = __kvm_request_immediate_exit,
4637 .sched_in = svm_sched_in,
4639 .pmu_ops = &amd_pmu_ops,
4640 .nested_ops = &svm_nested_ops,
4642 .deliver_posted_interrupt = svm_deliver_avic_intr,
4643 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
4644 .update_pi_irte = svm_update_pi_irte,
4645 .setup_mce = svm_setup_mce,
4647 .smi_allowed = svm_smi_allowed,
4648 .enter_smm = svm_enter_smm,
4649 .leave_smm = svm_leave_smm,
4650 .enable_smi_window = svm_enable_smi_window,
4652 .mem_enc_op = svm_mem_enc_op,
4653 .mem_enc_reg_region = svm_register_enc_region,
4654 .mem_enc_unreg_region = svm_unregister_enc_region,
4656 .vm_copy_enc_context_from = svm_vm_copy_asid_from,
4658 .can_emulate_instruction = svm_can_emulate_instruction,
4660 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
4662 .msr_filter_changed = svm_msr_filter_changed,
4663 .complete_emulated_msr = svm_complete_emulated_msr,
4665 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
4668 static struct kvm_x86_init_ops svm_init_ops __initdata = {
4669 .cpu_has_kvm_support = has_svm,
4670 .disabled_by_bios = is_disabled,
4671 .hardware_setup = svm_hardware_setup,
4672 .check_processor_compatibility = svm_check_processor_compat,
4674 .runtime_ops = &svm_x86_ops,
4677 static int __init svm_init(void)
4679 __unused_size_checks();
4681 return kvm_init(&svm_init_ops, sizeof(struct vcpu_svm),
4682 __alignof__(struct vcpu_svm), THIS_MODULE);
4685 static void __exit svm_exit(void)
4690 module_init(svm_init)
4691 module_exit(svm_exit)