1 #define pr_fmt(fmt) "SVM: " fmt
3 #include <linux/kvm_host.h>
7 #include "kvm_cache_regs.h"
12 #include <linux/module.h>
13 #include <linux/mod_devicetable.h>
14 #include <linux/kernel.h>
15 #include <linux/vmalloc.h>
16 #include <linux/highmem.h>
17 #include <linux/amd-iommu.h>
18 #include <linux/sched.h>
19 #include <linux/trace_events.h>
20 #include <linux/slab.h>
21 #include <linux/hashtable.h>
22 #include <linux/objtool.h>
23 #include <linux/psp-sev.h>
24 #include <linux/file.h>
25 #include <linux/pagemap.h>
26 #include <linux/swap.h>
27 #include <linux/rwsem.h>
28 #include <linux/cc_platform.h>
31 #include <asm/perf_event.h>
32 #include <asm/tlbflush.h>
34 #include <asm/debugreg.h>
35 #include <asm/kvm_para.h>
36 #include <asm/irq_remapping.h>
37 #include <asm/spec-ctrl.h>
38 #include <asm/cpu_device_id.h>
39 #include <asm/traps.h>
40 #include <asm/fpu/api.h>
42 #include <asm/virtext.h>
48 #include "kvm_onhyperv.h"
49 #include "svm_onhyperv.h"
51 MODULE_AUTHOR("Qumranet");
52 MODULE_LICENSE("GPL");
55 static const struct x86_cpu_id svm_cpu_id[] = {
56 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
59 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
62 #define SEG_TYPE_LDT 2
63 #define SEG_TYPE_BUSY_TSS16 3
65 #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);
191 /* enable/disable LBR virtualization */
192 static int lbrv = true;
193 module_param(lbrv, int, 0444);
195 static int tsc_scaling = true;
196 module_param(tsc_scaling, int, 0444);
199 * enable / disable AVIC. Because the defaults differ for APICv
200 * support between VMX and SVM we cannot use module_param_named.
203 module_param(avic, bool, 0444);
205 bool __read_mostly dump_invalid_vmcb;
206 module_param(dump_invalid_vmcb, bool, 0644);
209 bool intercept_smi = true;
210 module_param(intercept_smi, bool, 0444);
213 static bool svm_gp_erratum_intercept = true;
215 static u8 rsm_ins_bytes[] = "\x0f\xaa";
217 static unsigned long iopm_base;
219 struct kvm_ldttss_desc {
222 unsigned base1:8, type:5, dpl:2, p:1;
223 unsigned limit1:4, zero0:3, g:1, base2:8;
226 } __attribute__((packed));
228 DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
231 * Only MSR_TSC_AUX is switched via the user return hook. EFER is switched via
232 * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
234 * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
235 * defer the restoration of TSC_AUX until the CPU returns to userspace.
237 static int tsc_aux_uret_slot __read_mostly = -1;
239 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
241 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
242 #define MSRS_RANGE_SIZE 2048
243 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
245 u32 svm_msrpm_offset(u32 msr)
250 for (i = 0; i < NUM_MSR_MAPS; i++) {
251 if (msr < msrpm_ranges[i] ||
252 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
255 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
256 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
258 /* Now we have the u8 offset - but need the u32 offset */
262 /* MSR not in any range */
266 #define MAX_INST_SIZE 15
268 static int get_max_npt_level(void)
271 return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
273 return PT32E_ROOT_LEVEL;
277 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
279 struct vcpu_svm *svm = to_svm(vcpu);
280 u64 old_efer = vcpu->arch.efer;
281 vcpu->arch.efer = efer;
284 /* Shadow paging assumes NX to be available. */
287 if (!(efer & EFER_LMA))
291 if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
292 if (!(efer & EFER_SVME)) {
293 svm_leave_nested(svm);
294 svm_set_gif(svm, true);
295 /* #GP intercept is still needed for vmware backdoor */
296 if (!enable_vmware_backdoor)
297 clr_exception_intercept(svm, GP_VECTOR);
300 * Free the nested guest state, unless we are in SMM.
301 * In this case we will return to the nested guest
302 * as soon as we leave SMM.
305 svm_free_nested(svm);
308 int ret = svm_allocate_nested(svm);
311 vcpu->arch.efer = old_efer;
315 if (svm_gp_erratum_intercept)
316 set_exception_intercept(svm, GP_VECTOR);
320 svm->vmcb->save.efer = efer | EFER_SVME;
321 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
325 static int is_external_interrupt(u32 info)
327 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
328 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
331 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
333 struct vcpu_svm *svm = to_svm(vcpu);
336 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
337 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
341 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
343 struct vcpu_svm *svm = to_svm(vcpu);
346 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
348 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
352 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
354 struct vcpu_svm *svm = to_svm(vcpu);
357 * SEV-ES does not expose the next RIP. The RIP update is controlled by
358 * the type of exit and the #VC handler in the guest.
360 if (sev_es_guest(vcpu->kvm))
363 if (nrips && svm->vmcb->control.next_rip != 0) {
364 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
365 svm->next_rip = svm->vmcb->control.next_rip;
368 if (!svm->next_rip) {
369 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
372 kvm_rip_write(vcpu, svm->next_rip);
376 svm_set_interrupt_shadow(vcpu, 0);
381 static void svm_queue_exception(struct kvm_vcpu *vcpu)
383 struct vcpu_svm *svm = to_svm(vcpu);
384 unsigned nr = vcpu->arch.exception.nr;
385 bool has_error_code = vcpu->arch.exception.has_error_code;
386 u32 error_code = vcpu->arch.exception.error_code;
388 kvm_deliver_exception_payload(vcpu);
390 if (nr == BP_VECTOR && !nrips) {
391 unsigned long rip, old_rip = kvm_rip_read(vcpu);
394 * For guest debugging where we have to reinject #BP if some
395 * INT3 is guest-owned:
396 * Emulate nRIP by moving RIP forward. Will fail if injection
397 * raises a fault that is not intercepted. Still better than
398 * failing in all cases.
400 (void)skip_emulated_instruction(vcpu);
401 rip = kvm_rip_read(vcpu);
402 svm->int3_rip = rip + svm->vmcb->save.cs.base;
403 svm->int3_injected = rip - old_rip;
406 svm->vmcb->control.event_inj = nr
408 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
409 | SVM_EVTINJ_TYPE_EXEPT;
410 svm->vmcb->control.event_inj_err = error_code;
413 static void svm_init_erratum_383(void)
419 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
422 /* Use _safe variants to not break nested virtualization */
423 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
429 low = lower_32_bits(val);
430 high = upper_32_bits(val);
432 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
434 erratum_383_found = true;
437 static void svm_init_osvw(struct kvm_vcpu *vcpu)
440 * Guests should see errata 400 and 415 as fixed (assuming that
441 * HLT and IO instructions are intercepted).
443 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
444 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
447 * By increasing VCPU's osvw.length to 3 we are telling the guest that
448 * all osvw.status bits inside that length, including bit 0 (which is
449 * reserved for erratum 298), are valid. However, if host processor's
450 * osvw_len is 0 then osvw_status[0] carries no information. We need to
451 * be conservative here and therefore we tell the guest that erratum 298
452 * is present (because we really don't know).
454 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
455 vcpu->arch.osvw.status |= 1;
458 static int has_svm(void)
462 if (!cpu_has_svm(&msg)) {
463 printk(KERN_INFO "has_svm: %s\n", msg);
467 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
468 pr_info("KVM is unsupported when running as an SEV guest\n");
475 static void svm_hardware_disable(void)
477 /* Make sure we clean up behind us */
479 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
483 amd_pmu_disable_virt();
486 static int svm_hardware_enable(void)
489 struct svm_cpu_data *sd;
491 struct desc_struct *gdt;
492 int me = raw_smp_processor_id();
494 rdmsrl(MSR_EFER, efer);
495 if (efer & EFER_SVME)
499 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
502 sd = per_cpu(svm_data, me);
504 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
508 sd->asid_generation = 1;
509 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
510 sd->next_asid = sd->max_asid + 1;
511 sd->min_asid = max_sev_asid + 1;
513 gdt = get_current_gdt_rw();
514 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
516 wrmsrl(MSR_EFER, efer | EFER_SVME);
518 wrmsrl(MSR_VM_HSAVE_PA, __sme_page_pa(sd->save_area));
520 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
522 * Set the default value, even if we don't use TSC scaling
523 * to avoid having stale value in the msr
525 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
526 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
533 * Note that it is possible to have a system with mixed processor
534 * revisions and therefore different OSVW bits. If bits are not the same
535 * on different processors then choose the worst case (i.e. if erratum
536 * is present on one processor and not on another then assume that the
537 * erratum is present everywhere).
539 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
540 uint64_t len, status = 0;
543 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
545 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
549 osvw_status = osvw_len = 0;
553 osvw_status |= status;
554 osvw_status &= (1ULL << osvw_len) - 1;
557 osvw_status = osvw_len = 0;
559 svm_init_erratum_383();
561 amd_pmu_enable_virt();
566 static void svm_cpu_uninit(int cpu)
568 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
573 per_cpu(svm_data, cpu) = NULL;
574 kfree(sd->sev_vmcbs);
575 __free_page(sd->save_area);
579 static int svm_cpu_init(int cpu)
581 struct svm_cpu_data *sd;
584 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
588 sd->save_area = alloc_page(GFP_KERNEL);
592 clear_page(page_address(sd->save_area));
594 ret = sev_cpu_init(sd);
598 per_cpu(svm_data, cpu) = sd;
603 __free_page(sd->save_area);
610 static int direct_access_msr_slot(u32 msr)
614 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
615 if (direct_access_msrs[i].index == msr)
621 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
624 struct vcpu_svm *svm = to_svm(vcpu);
625 int slot = direct_access_msr_slot(msr);
630 /* Set the shadow bitmaps to the desired intercept states */
632 set_bit(slot, svm->shadow_msr_intercept.read);
634 clear_bit(slot, svm->shadow_msr_intercept.read);
637 set_bit(slot, svm->shadow_msr_intercept.write);
639 clear_bit(slot, svm->shadow_msr_intercept.write);
642 static bool valid_msr_intercept(u32 index)
644 return direct_access_msr_slot(index) != -ENOENT;
647 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
654 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
657 offset = svm_msrpm_offset(msr);
658 bit_write = 2 * (msr & 0x0f) + 1;
661 BUG_ON(offset == MSR_INVALID);
663 return !!test_bit(bit_write, &tmp);
666 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
667 u32 msr, int read, int write)
669 u8 bit_read, bit_write;
674 * If this warning triggers extend the direct_access_msrs list at the
675 * beginning of the file
677 WARN_ON(!valid_msr_intercept(msr));
679 /* Enforce non allowed MSRs to trap */
680 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
683 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
686 offset = svm_msrpm_offset(msr);
687 bit_read = 2 * (msr & 0x0f);
688 bit_write = 2 * (msr & 0x0f) + 1;
691 BUG_ON(offset == MSR_INVALID);
693 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
694 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
698 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
702 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
705 set_shadow_msr_intercept(vcpu, msr, read, write);
706 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
709 u32 *svm_vcpu_alloc_msrpm(void)
711 unsigned int order = get_order(MSRPM_SIZE);
712 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
718 msrpm = page_address(pages);
719 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
724 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
728 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
729 if (!direct_access_msrs[i].always)
731 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
736 void svm_vcpu_free_msrpm(u32 *msrpm)
738 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
741 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
743 struct vcpu_svm *svm = to_svm(vcpu);
747 * Set intercept permissions for all direct access MSRs again. They
748 * will automatically get filtered through the MSR filter, so we are
749 * back in sync after this.
751 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
752 u32 msr = direct_access_msrs[i].index;
753 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
754 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
756 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
760 static void add_msr_offset(u32 offset)
764 for (i = 0; i < MSRPM_OFFSETS; ++i) {
766 /* Offset already in list? */
767 if (msrpm_offsets[i] == offset)
770 /* Slot used by another offset? */
771 if (msrpm_offsets[i] != MSR_INVALID)
774 /* Add offset to list */
775 msrpm_offsets[i] = offset;
781 * If this BUG triggers the msrpm_offsets table has an overflow. Just
782 * increase MSRPM_OFFSETS in this case.
787 static void init_msrpm_offsets(void)
791 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
793 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
796 offset = svm_msrpm_offset(direct_access_msrs[i].index);
797 BUG_ON(offset == MSR_INVALID);
799 add_msr_offset(offset);
803 static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
805 struct vcpu_svm *svm = to_svm(vcpu);
807 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
808 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
809 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
810 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
811 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
814 static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
816 struct vcpu_svm *svm = to_svm(vcpu);
818 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
819 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
820 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
821 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
822 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
825 void disable_nmi_singlestep(struct vcpu_svm *svm)
827 svm->nmi_singlestep = false;
829 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
830 /* Clear our flags if they were not set by the guest */
831 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
832 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
833 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
834 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
838 static void grow_ple_window(struct kvm_vcpu *vcpu)
840 struct vcpu_svm *svm = to_svm(vcpu);
841 struct vmcb_control_area *control = &svm->vmcb->control;
842 int old = control->pause_filter_count;
844 control->pause_filter_count = __grow_ple_window(old,
846 pause_filter_count_grow,
847 pause_filter_count_max);
849 if (control->pause_filter_count != old) {
850 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
851 trace_kvm_ple_window_update(vcpu->vcpu_id,
852 control->pause_filter_count, old);
856 static void shrink_ple_window(struct kvm_vcpu *vcpu)
858 struct vcpu_svm *svm = to_svm(vcpu);
859 struct vmcb_control_area *control = &svm->vmcb->control;
860 int old = control->pause_filter_count;
862 control->pause_filter_count =
863 __shrink_ple_window(old,
865 pause_filter_count_shrink,
867 if (control->pause_filter_count != old) {
868 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
869 trace_kvm_ple_window_update(vcpu->vcpu_id,
870 control->pause_filter_count, old);
875 * The default MMIO mask is a single bit (excluding the present bit),
876 * which could conflict with the memory encryption bit. Check for
877 * memory encryption support and override the default MMIO mask if
878 * memory encryption is enabled.
880 static __init void svm_adjust_mmio_mask(void)
882 unsigned int enc_bit, mask_bit;
885 /* If there is no memory encryption support, use existing mask */
886 if (cpuid_eax(0x80000000) < 0x8000001f)
889 /* If memory encryption is not enabled, use existing mask */
890 rdmsrl(MSR_AMD64_SYSCFG, msr);
891 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
894 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
895 mask_bit = boot_cpu_data.x86_phys_bits;
897 /* Increment the mask bit if it is the same as the encryption bit */
898 if (enc_bit == mask_bit)
902 * If the mask bit location is below 52, then some bits above the
903 * physical addressing limit will always be reserved, so use the
904 * rsvd_bits() function to generate the mask. This mask, along with
905 * the present bit, will be used to generate a page fault with
908 * If the mask bit location is 52 (or above), then clear the mask.
910 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
912 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
915 static void svm_hardware_teardown(void)
919 sev_hardware_teardown();
921 for_each_possible_cpu(cpu)
924 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
925 get_order(IOPM_SIZE));
929 static __init void svm_set_cpu_caps(void)
935 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
937 kvm_cpu_cap_set(X86_FEATURE_SVM);
940 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
943 kvm_cpu_cap_set(X86_FEATURE_NPT);
946 kvm_cpu_cap_set(X86_FEATURE_TSCRATEMSR);
948 /* Nested VM can receive #VMEXIT instead of triggering #GP */
949 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
952 /* CPUID 0x80000008 */
953 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
954 boot_cpu_has(X86_FEATURE_AMD_SSBD))
955 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
957 /* CPUID 0x8000001F (SME/SEV features) */
961 static __init int svm_hardware_setup(void)
964 struct page *iopm_pages;
967 unsigned int order = get_order(IOPM_SIZE);
970 * NX is required for shadow paging and for NPT if the NX huge pages
971 * mitigation is enabled.
973 if (!boot_cpu_has(X86_FEATURE_NX)) {
974 pr_err_ratelimited("NX (Execute Disable) not supported\n");
977 kvm_enable_efer_bits(EFER_NX);
979 iopm_pages = alloc_pages(GFP_KERNEL, order);
984 iopm_va = page_address(iopm_pages);
985 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
986 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
988 init_msrpm_offsets();
990 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
992 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
993 kvm_enable_efer_bits(EFER_FFXSR);
996 if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
999 pr_info("TSC scaling supported\n");
1000 kvm_has_tsc_control = true;
1001 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1002 kvm_tsc_scaling_ratio_frac_bits = 32;
1006 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
1008 /* Check for pause filtering support */
1009 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1010 pause_filter_count = 0;
1011 pause_filter_thresh = 0;
1012 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1013 pause_filter_thresh = 0;
1017 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1018 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1022 * KVM's MMU doesn't support using 2-level paging for itself, and thus
1023 * NPT isn't supported if the host is using 2-level paging since host
1024 * CR4 is unchanged on VMRUN.
1026 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
1027 npt_enabled = false;
1029 if (!boot_cpu_has(X86_FEATURE_NPT))
1030 npt_enabled = false;
1032 /* Force VM NPT level equal to the host's max NPT level */
1033 kvm_configure_mmu(npt_enabled, get_max_npt_level(),
1034 get_max_npt_level(), PG_LEVEL_1G);
1035 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
1037 /* Note, SEV setup consumes npt_enabled. */
1038 sev_hardware_setup();
1040 svm_hv_hardware_setup();
1042 svm_adjust_mmio_mask();
1044 for_each_possible_cpu(cpu) {
1045 r = svm_cpu_init(cpu);
1051 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1055 enable_apicv = avic = avic && npt_enabled && boot_cpu_has(X86_FEATURE_AVIC);
1058 pr_info("AVIC enabled\n");
1060 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1065 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1066 !IS_ENABLED(CONFIG_X86_64)) {
1069 pr_info("Virtual VMLOAD VMSAVE supported\n");
1073 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
1074 svm_gp_erratum_intercept = false;
1077 if (!boot_cpu_has(X86_FEATURE_VGIF))
1080 pr_info("Virtual GIF supported\n");
1084 if (!boot_cpu_has(X86_FEATURE_LBRV))
1087 pr_info("LBR virtualization supported\n");
1093 * It seems that on AMD processors PTE's accessed bit is
1094 * being set by the CPU hardware before the NPF vmexit.
1095 * This is not expected behaviour and our tests fail because
1097 * A workaround here is to disable support for
1098 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
1099 * In this case userspace can know if there is support using
1100 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
1102 * If future AMD CPU models change the behaviour described above,
1103 * this variable can be changed accordingly
1105 allow_smaller_maxphyaddr = !npt_enabled;
1110 svm_hardware_teardown();
1114 static void init_seg(struct vmcb_seg *seg)
1117 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1118 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1119 seg->limit = 0xffff;
1123 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1126 seg->attrib = SVM_SELECTOR_P_MASK | type;
1127 seg->limit = 0xffff;
1131 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1133 struct vcpu_svm *svm = to_svm(vcpu);
1135 return svm->nested.ctl.tsc_offset;
1138 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1140 struct vcpu_svm *svm = to_svm(vcpu);
1142 return svm->tsc_ratio_msr;
1145 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1147 struct vcpu_svm *svm = to_svm(vcpu);
1149 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1150 svm->vmcb->control.tsc_offset = offset;
1151 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1154 void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1156 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
1159 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1160 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1161 struct vcpu_svm *svm)
1164 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1165 * roots, or if INVPCID is disabled in the guest to inject #UD.
1167 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1169 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1170 svm_set_intercept(svm, INTERCEPT_INVPCID);
1172 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1175 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1176 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1177 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1179 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1183 static inline void init_vmcb_after_set_cpuid(struct kvm_vcpu *vcpu)
1185 struct vcpu_svm *svm = to_svm(vcpu);
1187 if (guest_cpuid_is_intel(vcpu)) {
1189 * We must intercept SYSENTER_EIP and SYSENTER_ESP
1190 * accesses because the processor only stores 32 bits.
1191 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
1193 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1194 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1195 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1197 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
1198 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
1201 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1202 * in VMCB and clear intercepts to avoid #VMEXIT.
1205 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
1206 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
1207 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1209 /* No need to intercept these MSRs */
1210 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
1211 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
1215 static void init_vmcb(struct kvm_vcpu *vcpu)
1217 struct vcpu_svm *svm = to_svm(vcpu);
1218 struct vmcb_control_area *control = &svm->vmcb->control;
1219 struct vmcb_save_area *save = &svm->vmcb->save;
1221 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1222 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1223 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1224 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1225 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1226 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1227 if (!kvm_vcpu_apicv_active(vcpu))
1228 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1230 set_dr_intercepts(svm);
1232 set_exception_intercept(svm, PF_VECTOR);
1233 set_exception_intercept(svm, UD_VECTOR);
1234 set_exception_intercept(svm, MC_VECTOR);
1235 set_exception_intercept(svm, AC_VECTOR);
1236 set_exception_intercept(svm, DB_VECTOR);
1238 * Guest access to VMware backdoor ports could legitimately
1239 * trigger #GP because of TSS I/O permission bitmap.
1240 * We intercept those #GP and allow access to them anyway
1243 if (enable_vmware_backdoor)
1244 set_exception_intercept(svm, GP_VECTOR);
1246 svm_set_intercept(svm, INTERCEPT_INTR);
1247 svm_set_intercept(svm, INTERCEPT_NMI);
1250 svm_set_intercept(svm, INTERCEPT_SMI);
1252 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1253 svm_set_intercept(svm, INTERCEPT_RDPMC);
1254 svm_set_intercept(svm, INTERCEPT_CPUID);
1255 svm_set_intercept(svm, INTERCEPT_INVD);
1256 svm_set_intercept(svm, INTERCEPT_INVLPG);
1257 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1258 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1259 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1260 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1261 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1262 svm_set_intercept(svm, INTERCEPT_VMRUN);
1263 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1264 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1265 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1266 svm_set_intercept(svm, INTERCEPT_STGI);
1267 svm_set_intercept(svm, INTERCEPT_CLGI);
1268 svm_set_intercept(svm, INTERCEPT_SKINIT);
1269 svm_set_intercept(svm, INTERCEPT_WBINVD);
1270 svm_set_intercept(svm, INTERCEPT_XSETBV);
1271 svm_set_intercept(svm, INTERCEPT_RDPRU);
1272 svm_set_intercept(svm, INTERCEPT_RSM);
1274 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1275 svm_set_intercept(svm, INTERCEPT_MONITOR);
1276 svm_set_intercept(svm, INTERCEPT_MWAIT);
1279 if (!kvm_hlt_in_guest(vcpu->kvm))
1280 svm_set_intercept(svm, INTERCEPT_HLT);
1282 control->iopm_base_pa = __sme_set(iopm_base);
1283 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1284 control->int_ctl = V_INTR_MASKING_MASK;
1286 init_seg(&save->es);
1287 init_seg(&save->ss);
1288 init_seg(&save->ds);
1289 init_seg(&save->fs);
1290 init_seg(&save->gs);
1292 save->cs.selector = 0xf000;
1293 save->cs.base = 0xffff0000;
1294 /* Executable/Readable Code Segment */
1295 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1296 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1297 save->cs.limit = 0xffff;
1299 save->gdtr.base = 0;
1300 save->gdtr.limit = 0xffff;
1301 save->idtr.base = 0;
1302 save->idtr.limit = 0xffff;
1304 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1305 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1308 /* Setup VMCB for Nested Paging */
1309 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1310 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1311 clr_exception_intercept(svm, PF_VECTOR);
1312 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1313 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1314 save->g_pat = vcpu->arch.pat;
1317 svm->current_vmcb->asid_generation = 0;
1320 svm->nested.vmcb12_gpa = INVALID_GPA;
1321 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1323 if (!kvm_pause_in_guest(vcpu->kvm)) {
1324 control->pause_filter_count = pause_filter_count;
1325 if (pause_filter_thresh)
1326 control->pause_filter_thresh = pause_filter_thresh;
1327 svm_set_intercept(svm, INTERCEPT_PAUSE);
1329 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1332 svm_recalc_instruction_intercepts(vcpu, svm);
1335 * If the host supports V_SPEC_CTRL then disable the interception
1336 * of MSR_IA32_SPEC_CTRL.
1338 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1339 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1341 if (kvm_vcpu_apicv_active(vcpu))
1342 avic_init_vmcb(svm);
1345 svm_clr_intercept(svm, INTERCEPT_STGI);
1346 svm_clr_intercept(svm, INTERCEPT_CLGI);
1347 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1350 if (sev_guest(vcpu->kvm)) {
1351 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1352 clr_exception_intercept(svm, UD_VECTOR);
1354 if (sev_es_guest(vcpu->kvm)) {
1355 /* Perform SEV-ES specific VMCB updates */
1356 sev_es_init_vmcb(svm);
1360 svm_hv_init_vmcb(svm->vmcb);
1361 init_vmcb_after_set_cpuid(vcpu);
1363 vmcb_mark_all_dirty(svm->vmcb);
1368 static void __svm_vcpu_reset(struct kvm_vcpu *vcpu)
1370 struct vcpu_svm *svm = to_svm(vcpu);
1372 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1374 svm_init_osvw(vcpu);
1375 vcpu->arch.microcode_version = 0x01000065;
1376 svm->tsc_ratio_msr = kvm_default_tsc_scaling_ratio;
1378 if (sev_es_guest(vcpu->kvm))
1379 sev_es_vcpu_reset(svm);
1382 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1384 struct vcpu_svm *svm = to_svm(vcpu);
1387 svm->virt_spec_ctrl = 0;
1392 __svm_vcpu_reset(vcpu);
1395 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1397 svm->current_vmcb = target_vmcb;
1398 svm->vmcb = target_vmcb->ptr;
1401 static int svm_create_vcpu(struct kvm_vcpu *vcpu)
1403 struct vcpu_svm *svm;
1404 struct page *vmcb01_page;
1405 struct page *vmsa_page = NULL;
1408 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1412 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1416 if (sev_es_guest(vcpu->kvm)) {
1418 * SEV-ES guests require a separate VMSA page used to contain
1419 * the encrypted register state of the guest.
1421 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1423 goto error_free_vmcb_page;
1426 * SEV-ES guests maintain an encrypted version of their FPU
1427 * state which is restored and saved on VMRUN and VMEXIT.
1428 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
1429 * do xsave/xrstor on it.
1431 fpstate_set_confidential(&vcpu->arch.guest_fpu);
1434 err = avic_init_vcpu(svm);
1436 goto error_free_vmsa_page;
1438 /* We initialize this flag to true to make sure that the is_running
1439 * bit would be set the first time the vcpu is loaded.
1441 if (irqchip_in_kernel(vcpu->kvm) && kvm_apicv_activated(vcpu->kvm))
1442 svm->avic_is_running = true;
1444 svm->msrpm = svm_vcpu_alloc_msrpm();
1447 goto error_free_vmsa_page;
1450 svm->vmcb01.ptr = page_address(vmcb01_page);
1451 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1452 svm_switch_vmcb(svm, &svm->vmcb01);
1455 svm->sev_es.vmsa = page_address(vmsa_page);
1457 svm->guest_state_loaded = false;
1461 error_free_vmsa_page:
1463 __free_page(vmsa_page);
1464 error_free_vmcb_page:
1465 __free_page(vmcb01_page);
1470 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1474 for_each_online_cpu(i)
1475 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
1478 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
1480 struct vcpu_svm *svm = to_svm(vcpu);
1483 * The vmcb page can be recycled, causing a false negative in
1484 * svm_vcpu_load(). So, ensure that no logical CPU has this
1485 * vmcb page recorded as its current vmcb.
1487 svm_clear_current_vmcb(svm->vmcb);
1489 svm_free_nested(svm);
1491 sev_free_vcpu(vcpu);
1493 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1494 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1497 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
1499 struct vcpu_svm *svm = to_svm(vcpu);
1500 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
1502 if (sev_es_guest(vcpu->kvm))
1503 sev_es_unmap_ghcb(svm);
1505 if (svm->guest_state_loaded)
1509 * Save additional host state that will be restored on VMEXIT (sev-es)
1510 * or subsequent vmload of host save area.
1512 if (sev_es_guest(vcpu->kvm)) {
1513 sev_es_prepare_guest_switch(svm, vcpu->cpu);
1515 vmsave(__sme_page_pa(sd->save_area));
1519 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
1520 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
1521 __this_cpu_write(current_tsc_ratio, tsc_ratio);
1522 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
1526 if (likely(tsc_aux_uret_slot >= 0))
1527 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1529 svm->guest_state_loaded = true;
1532 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1534 to_svm(vcpu)->guest_state_loaded = false;
1537 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1539 struct vcpu_svm *svm = to_svm(vcpu);
1540 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1542 if (sd->current_vmcb != svm->vmcb) {
1543 sd->current_vmcb = svm->vmcb;
1544 indirect_branch_prediction_barrier();
1546 if (kvm_vcpu_apicv_active(vcpu))
1547 avic_vcpu_load(vcpu, cpu);
1550 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1552 if (kvm_vcpu_apicv_active(vcpu))
1553 avic_vcpu_put(vcpu);
1555 svm_prepare_host_switch(vcpu);
1557 ++vcpu->stat.host_state_reload;
1560 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1562 struct vcpu_svm *svm = to_svm(vcpu);
1563 unsigned long rflags = svm->vmcb->save.rflags;
1565 if (svm->nmi_singlestep) {
1566 /* Hide our flags if they were not set by the guest */
1567 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1568 rflags &= ~X86_EFLAGS_TF;
1569 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1570 rflags &= ~X86_EFLAGS_RF;
1575 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1577 if (to_svm(vcpu)->nmi_singlestep)
1578 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1581 * Any change of EFLAGS.VM is accompanied by a reload of SS
1582 * (caused by either a task switch or an inter-privilege IRET),
1583 * so we do not need to update the CPL here.
1585 to_svm(vcpu)->vmcb->save.rflags = rflags;
1588 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1591 case VCPU_EXREG_PDPTR:
1592 BUG_ON(!npt_enabled);
1593 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
1596 KVM_BUG_ON(1, vcpu->kvm);
1600 static void svm_set_vintr(struct vcpu_svm *svm)
1602 struct vmcb_control_area *control;
1605 * The following fields are ignored when AVIC is enabled
1607 WARN_ON(kvm_apicv_activated(svm->vcpu.kvm));
1609 svm_set_intercept(svm, INTERCEPT_VINTR);
1612 * This is just a dummy VINTR to actually cause a vmexit to happen.
1613 * Actual injection of virtual interrupts happens through EVENTINJ.
1615 control = &svm->vmcb->control;
1616 control->int_vector = 0x0;
1617 control->int_ctl &= ~V_INTR_PRIO_MASK;
1618 control->int_ctl |= V_IRQ_MASK |
1619 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1620 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1623 static void svm_clear_vintr(struct vcpu_svm *svm)
1625 svm_clr_intercept(svm, INTERCEPT_VINTR);
1627 /* Drop int_ctl fields related to VINTR injection. */
1628 svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1629 if (is_guest_mode(&svm->vcpu)) {
1630 svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1632 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1633 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1635 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1636 V_IRQ_INJECTION_BITS_MASK;
1638 svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1641 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1644 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1646 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1647 struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1650 case VCPU_SREG_CS: return &save->cs;
1651 case VCPU_SREG_DS: return &save->ds;
1652 case VCPU_SREG_ES: return &save->es;
1653 case VCPU_SREG_FS: return &save01->fs;
1654 case VCPU_SREG_GS: return &save01->gs;
1655 case VCPU_SREG_SS: return &save->ss;
1656 case VCPU_SREG_TR: return &save01->tr;
1657 case VCPU_SREG_LDTR: return &save01->ldtr;
1663 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1665 struct vmcb_seg *s = svm_seg(vcpu, seg);
1670 static void svm_get_segment(struct kvm_vcpu *vcpu,
1671 struct kvm_segment *var, int seg)
1673 struct vmcb_seg *s = svm_seg(vcpu, seg);
1675 var->base = s->base;
1676 var->limit = s->limit;
1677 var->selector = s->selector;
1678 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1679 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1680 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1681 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1682 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1683 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1684 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1687 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1688 * However, the SVM spec states that the G bit is not observed by the
1689 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1690 * So let's synthesize a legal G bit for all segments, this helps
1691 * running KVM nested. It also helps cross-vendor migration, because
1692 * Intel's vmentry has a check on the 'G' bit.
1694 var->g = s->limit > 0xfffff;
1697 * AMD's VMCB does not have an explicit unusable field, so emulate it
1698 * for cross vendor migration purposes by "not present"
1700 var->unusable = !var->present;
1705 * Work around a bug where the busy flag in the tr selector
1715 * The accessed bit must always be set in the segment
1716 * descriptor cache, although it can be cleared in the
1717 * descriptor, the cached bit always remains at 1. Since
1718 * Intel has a check on this, set it here to support
1719 * cross-vendor migration.
1726 * On AMD CPUs sometimes the DB bit in the segment
1727 * descriptor is left as 1, although the whole segment has
1728 * been made unusable. Clear it here to pass an Intel VMX
1729 * entry check when cross vendor migrating.
1733 /* This is symmetric with svm_set_segment() */
1734 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1739 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1741 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1746 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1748 struct vcpu_svm *svm = to_svm(vcpu);
1750 dt->size = svm->vmcb->save.idtr.limit;
1751 dt->address = svm->vmcb->save.idtr.base;
1754 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1756 struct vcpu_svm *svm = to_svm(vcpu);
1758 svm->vmcb->save.idtr.limit = dt->size;
1759 svm->vmcb->save.idtr.base = dt->address ;
1760 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1763 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1765 struct vcpu_svm *svm = to_svm(vcpu);
1767 dt->size = svm->vmcb->save.gdtr.limit;
1768 dt->address = svm->vmcb->save.gdtr.base;
1771 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1773 struct vcpu_svm *svm = to_svm(vcpu);
1775 svm->vmcb->save.gdtr.limit = dt->size;
1776 svm->vmcb->save.gdtr.base = dt->address ;
1777 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1780 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1782 struct vcpu_svm *svm = to_svm(vcpu);
1785 #ifdef CONFIG_X86_64
1786 if (vcpu->arch.efer & EFER_LME && !vcpu->arch.guest_state_protected) {
1787 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1788 vcpu->arch.efer |= EFER_LMA;
1789 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1792 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1793 vcpu->arch.efer &= ~EFER_LMA;
1794 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1798 vcpu->arch.cr0 = cr0;
1801 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1804 * re-enable caching here because the QEMU bios
1805 * does not do it - this results in some delay at
1808 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1809 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1811 svm->vmcb->save.cr0 = hcr0;
1812 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1815 * SEV-ES guests must always keep the CR intercepts cleared. CR
1816 * tracking is done using the CR write traps.
1818 if (sev_es_guest(vcpu->kvm))
1822 /* Selective CR0 write remains on. */
1823 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1824 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1826 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1827 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1831 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1836 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1838 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1839 unsigned long old_cr4 = vcpu->arch.cr4;
1841 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1842 svm_flush_tlb(vcpu);
1844 vcpu->arch.cr4 = cr4;
1847 cr4 |= host_cr4_mce;
1848 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1849 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1851 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1852 kvm_update_cpuid_runtime(vcpu);
1855 static void svm_set_segment(struct kvm_vcpu *vcpu,
1856 struct kvm_segment *var, int seg)
1858 struct vcpu_svm *svm = to_svm(vcpu);
1859 struct vmcb_seg *s = svm_seg(vcpu, seg);
1861 s->base = var->base;
1862 s->limit = var->limit;
1863 s->selector = var->selector;
1864 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1865 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1866 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1867 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1868 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1869 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1870 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1871 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1874 * This is always accurate, except if SYSRET returned to a segment
1875 * with SS.DPL != 3. Intel does not have this quirk, and always
1876 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1877 * would entail passing the CPL to userspace and back.
1879 if (seg == VCPU_SREG_SS)
1880 /* This is symmetric with svm_get_segment() */
1881 svm->vmcb->save.cpl = (var->dpl & 3);
1883 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1886 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1888 struct vcpu_svm *svm = to_svm(vcpu);
1890 clr_exception_intercept(svm, BP_VECTOR);
1892 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1893 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1894 set_exception_intercept(svm, BP_VECTOR);
1898 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1900 if (sd->next_asid > sd->max_asid) {
1901 ++sd->asid_generation;
1902 sd->next_asid = sd->min_asid;
1903 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1904 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1907 svm->current_vmcb->asid_generation = sd->asid_generation;
1908 svm->asid = sd->next_asid++;
1911 static void svm_set_dr6(struct vcpu_svm *svm, unsigned long value)
1913 struct vmcb *vmcb = svm->vmcb;
1915 if (svm->vcpu.arch.guest_state_protected)
1918 if (unlikely(value != vmcb->save.dr6)) {
1919 vmcb->save.dr6 = value;
1920 vmcb_mark_dirty(vmcb, VMCB_DR);
1924 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1926 struct vcpu_svm *svm = to_svm(vcpu);
1928 if (vcpu->arch.guest_state_protected)
1931 get_debugreg(vcpu->arch.db[0], 0);
1932 get_debugreg(vcpu->arch.db[1], 1);
1933 get_debugreg(vcpu->arch.db[2], 2);
1934 get_debugreg(vcpu->arch.db[3], 3);
1936 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1937 * because db_interception might need it. We can do it before vmentry.
1939 vcpu->arch.dr6 = svm->vmcb->save.dr6;
1940 vcpu->arch.dr7 = svm->vmcb->save.dr7;
1941 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1942 set_dr_intercepts(svm);
1945 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1947 struct vcpu_svm *svm = to_svm(vcpu);
1949 if (vcpu->arch.guest_state_protected)
1952 svm->vmcb->save.dr7 = value;
1953 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
1956 static int pf_interception(struct kvm_vcpu *vcpu)
1958 struct vcpu_svm *svm = to_svm(vcpu);
1960 u64 fault_address = svm->vmcb->control.exit_info_2;
1961 u64 error_code = svm->vmcb->control.exit_info_1;
1963 return kvm_handle_page_fault(vcpu, error_code, fault_address,
1964 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1965 svm->vmcb->control.insn_bytes : NULL,
1966 svm->vmcb->control.insn_len);
1969 static int npf_interception(struct kvm_vcpu *vcpu)
1971 struct vcpu_svm *svm = to_svm(vcpu);
1973 u64 fault_address = svm->vmcb->control.exit_info_2;
1974 u64 error_code = svm->vmcb->control.exit_info_1;
1976 trace_kvm_page_fault(fault_address, error_code);
1977 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
1978 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1979 svm->vmcb->control.insn_bytes : NULL,
1980 svm->vmcb->control.insn_len);
1983 static int db_interception(struct kvm_vcpu *vcpu)
1985 struct kvm_run *kvm_run = vcpu->run;
1986 struct vcpu_svm *svm = to_svm(vcpu);
1988 if (!(vcpu->guest_debug &
1989 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1990 !svm->nmi_singlestep) {
1991 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
1992 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
1996 if (svm->nmi_singlestep) {
1997 disable_nmi_singlestep(svm);
1998 /* Make sure we check for pending NMIs upon entry */
1999 kvm_make_request(KVM_REQ_EVENT, vcpu);
2002 if (vcpu->guest_debug &
2003 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2004 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2005 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
2006 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
2007 kvm_run->debug.arch.pc =
2008 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2009 kvm_run->debug.arch.exception = DB_VECTOR;
2016 static int bp_interception(struct kvm_vcpu *vcpu)
2018 struct vcpu_svm *svm = to_svm(vcpu);
2019 struct kvm_run *kvm_run = vcpu->run;
2021 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2022 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2023 kvm_run->debug.arch.exception = BP_VECTOR;
2027 static int ud_interception(struct kvm_vcpu *vcpu)
2029 return handle_ud(vcpu);
2032 static int ac_interception(struct kvm_vcpu *vcpu)
2034 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
2038 static bool is_erratum_383(void)
2043 if (!erratum_383_found)
2046 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2050 /* Bit 62 may or may not be set for this mce */
2051 value &= ~(1ULL << 62);
2053 if (value != 0xb600000000010015ULL)
2056 /* Clear MCi_STATUS registers */
2057 for (i = 0; i < 6; ++i)
2058 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2060 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2064 value &= ~(1ULL << 2);
2065 low = lower_32_bits(value);
2066 high = upper_32_bits(value);
2068 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2071 /* Flush tlb to evict multi-match entries */
2077 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2079 if (is_erratum_383()) {
2081 * Erratum 383 triggered. Guest state is corrupt so kill the
2084 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2086 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2092 * On an #MC intercept the MCE handler is not called automatically in
2093 * the host. So do it by hand here.
2095 kvm_machine_check();
2098 static int mc_interception(struct kvm_vcpu *vcpu)
2103 static int shutdown_interception(struct kvm_vcpu *vcpu)
2105 struct kvm_run *kvm_run = vcpu->run;
2106 struct vcpu_svm *svm = to_svm(vcpu);
2109 * The VM save area has already been encrypted so it
2110 * cannot be reinitialized - just terminate.
2112 if (sev_es_guest(vcpu->kvm))
2116 * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put
2117 * the VMCB in a known good state. Unfortuately, KVM doesn't have
2118 * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking
2119 * userspace. At a platform view, INIT is acceptable behavior as
2120 * there exist bare metal platforms that automatically INIT the CPU
2121 * in response to shutdown.
2123 clear_page(svm->vmcb);
2124 kvm_vcpu_reset(vcpu, true);
2126 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2130 static int io_interception(struct kvm_vcpu *vcpu)
2132 struct vcpu_svm *svm = to_svm(vcpu);
2133 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2134 int size, in, string;
2137 ++vcpu->stat.io_exits;
2138 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2139 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2140 port = io_info >> 16;
2141 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2144 if (sev_es_guest(vcpu->kvm))
2145 return sev_es_string_io(svm, size, port, in);
2147 return kvm_emulate_instruction(vcpu, 0);
2150 svm->next_rip = svm->vmcb->control.exit_info_2;
2152 return kvm_fast_pio(vcpu, size, port, in);
2155 static int nmi_interception(struct kvm_vcpu *vcpu)
2160 static int smi_interception(struct kvm_vcpu *vcpu)
2165 static int intr_interception(struct kvm_vcpu *vcpu)
2167 ++vcpu->stat.irq_exits;
2171 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2173 struct vcpu_svm *svm = to_svm(vcpu);
2174 struct vmcb *vmcb12;
2175 struct kvm_host_map map;
2178 if (nested_svm_check_permissions(vcpu))
2181 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2184 kvm_inject_gp(vcpu, 0);
2190 ret = kvm_skip_emulated_instruction(vcpu);
2193 svm_copy_vmloadsave_state(svm->vmcb, vmcb12);
2194 svm->sysenter_eip_hi = 0;
2195 svm->sysenter_esp_hi = 0;
2197 svm_copy_vmloadsave_state(vmcb12, svm->vmcb);
2200 kvm_vcpu_unmap(vcpu, &map, true);
2205 static int vmload_interception(struct kvm_vcpu *vcpu)
2207 return vmload_vmsave_interception(vcpu, true);
2210 static int vmsave_interception(struct kvm_vcpu *vcpu)
2212 return vmload_vmsave_interception(vcpu, false);
2215 static int vmrun_interception(struct kvm_vcpu *vcpu)
2217 if (nested_svm_check_permissions(vcpu))
2220 return nested_svm_vmrun(vcpu);
2230 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
2231 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2233 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2235 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2236 return NONE_SVM_INSTR;
2238 switch (ctxt->modrm) {
2239 case 0xd8: /* VMRUN */
2240 return SVM_INSTR_VMRUN;
2241 case 0xda: /* VMLOAD */
2242 return SVM_INSTR_VMLOAD;
2243 case 0xdb: /* VMSAVE */
2244 return SVM_INSTR_VMSAVE;
2249 return NONE_SVM_INSTR;
2252 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2254 const int guest_mode_exit_codes[] = {
2255 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2256 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2257 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2259 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2260 [SVM_INSTR_VMRUN] = vmrun_interception,
2261 [SVM_INSTR_VMLOAD] = vmload_interception,
2262 [SVM_INSTR_VMSAVE] = vmsave_interception,
2264 struct vcpu_svm *svm = to_svm(vcpu);
2267 if (is_guest_mode(vcpu)) {
2268 /* Returns '1' or -errno on failure, '0' on success. */
2269 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2274 return svm_instr_handlers[opcode](vcpu);
2278 * #GP handling code. Note that #GP can be triggered under the following two
2280 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2281 * some AMD CPUs when EAX of these instructions are in the reserved memory
2282 * regions (e.g. SMM memory on host).
2283 * 2) VMware backdoor
2285 static int gp_interception(struct kvm_vcpu *vcpu)
2287 struct vcpu_svm *svm = to_svm(vcpu);
2288 u32 error_code = svm->vmcb->control.exit_info_1;
2291 /* Both #GP cases have zero error_code */
2295 /* All SVM instructions expect page aligned RAX */
2296 if (svm->vmcb->save.rax & ~PAGE_MASK)
2299 /* Decode the instruction for usage later */
2300 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2303 opcode = svm_instr_opcode(vcpu);
2305 if (opcode == NONE_SVM_INSTR) {
2306 if (!enable_vmware_backdoor)
2310 * VMware backdoor emulation on #GP interception only handles
2311 * IN{S}, OUT{S}, and RDPMC.
2313 if (!is_guest_mode(vcpu))
2314 return kvm_emulate_instruction(vcpu,
2315 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2317 return emulate_svm_instr(vcpu, opcode);
2320 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2324 void svm_set_gif(struct vcpu_svm *svm, bool value)
2328 * If VGIF is enabled, the STGI intercept is only added to
2329 * detect the opening of the SMI/NMI window; remove it now.
2330 * Likewise, clear the VINTR intercept, we will set it
2331 * again while processing KVM_REQ_EVENT if needed.
2333 if (vgif_enabled(svm))
2334 svm_clr_intercept(svm, INTERCEPT_STGI);
2335 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2336 svm_clear_vintr(svm);
2339 if (svm->vcpu.arch.smi_pending ||
2340 svm->vcpu.arch.nmi_pending ||
2341 kvm_cpu_has_injectable_intr(&svm->vcpu))
2342 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2347 * After a CLGI no interrupts should come. But if vGIF is
2348 * in use, we still rely on the VINTR intercept (rather than
2349 * STGI) to detect an open interrupt window.
2351 if (!vgif_enabled(svm))
2352 svm_clear_vintr(svm);
2356 static int stgi_interception(struct kvm_vcpu *vcpu)
2360 if (nested_svm_check_permissions(vcpu))
2363 ret = kvm_skip_emulated_instruction(vcpu);
2364 svm_set_gif(to_svm(vcpu), true);
2368 static int clgi_interception(struct kvm_vcpu *vcpu)
2372 if (nested_svm_check_permissions(vcpu))
2375 ret = kvm_skip_emulated_instruction(vcpu);
2376 svm_set_gif(to_svm(vcpu), false);
2380 static int invlpga_interception(struct kvm_vcpu *vcpu)
2382 gva_t gva = kvm_rax_read(vcpu);
2383 u32 asid = kvm_rcx_read(vcpu);
2385 /* FIXME: Handle an address size prefix. */
2386 if (!is_long_mode(vcpu))
2389 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2391 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2392 kvm_mmu_invlpg(vcpu, gva);
2394 return kvm_skip_emulated_instruction(vcpu);
2397 static int skinit_interception(struct kvm_vcpu *vcpu)
2399 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2401 kvm_queue_exception(vcpu, UD_VECTOR);
2405 static int task_switch_interception(struct kvm_vcpu *vcpu)
2407 struct vcpu_svm *svm = to_svm(vcpu);
2410 int int_type = svm->vmcb->control.exit_int_info &
2411 SVM_EXITINTINFO_TYPE_MASK;
2412 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2414 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2416 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2417 bool has_error_code = false;
2420 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2422 if (svm->vmcb->control.exit_info_2 &
2423 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2424 reason = TASK_SWITCH_IRET;
2425 else if (svm->vmcb->control.exit_info_2 &
2426 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2427 reason = TASK_SWITCH_JMP;
2429 reason = TASK_SWITCH_GATE;
2431 reason = TASK_SWITCH_CALL;
2433 if (reason == TASK_SWITCH_GATE) {
2435 case SVM_EXITINTINFO_TYPE_NMI:
2436 vcpu->arch.nmi_injected = false;
2438 case SVM_EXITINTINFO_TYPE_EXEPT:
2439 if (svm->vmcb->control.exit_info_2 &
2440 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2441 has_error_code = true;
2443 (u32)svm->vmcb->control.exit_info_2;
2445 kvm_clear_exception_queue(vcpu);
2447 case SVM_EXITINTINFO_TYPE_INTR:
2448 kvm_clear_interrupt_queue(vcpu);
2455 if (reason != TASK_SWITCH_GATE ||
2456 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2457 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2458 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2459 if (!skip_emulated_instruction(vcpu))
2463 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2466 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2467 has_error_code, error_code);
2470 static int iret_interception(struct kvm_vcpu *vcpu)
2472 struct vcpu_svm *svm = to_svm(vcpu);
2474 ++vcpu->stat.nmi_window_exits;
2475 vcpu->arch.hflags |= HF_IRET_MASK;
2476 if (!sev_es_guest(vcpu->kvm)) {
2477 svm_clr_intercept(svm, INTERCEPT_IRET);
2478 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2480 kvm_make_request(KVM_REQ_EVENT, vcpu);
2484 static int invlpg_interception(struct kvm_vcpu *vcpu)
2486 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2487 return kvm_emulate_instruction(vcpu, 0);
2489 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2490 return kvm_skip_emulated_instruction(vcpu);
2493 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2495 return kvm_emulate_instruction(vcpu, 0);
2498 static int rsm_interception(struct kvm_vcpu *vcpu)
2500 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2503 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2506 struct vcpu_svm *svm = to_svm(vcpu);
2507 unsigned long cr0 = vcpu->arch.cr0;
2510 if (!is_guest_mode(vcpu) ||
2511 (!(vmcb_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2514 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2515 val &= ~SVM_CR0_SELECTIVE_MASK;
2518 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2519 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2525 #define CR_VALID (1ULL << 63)
2527 static int cr_interception(struct kvm_vcpu *vcpu)
2529 struct vcpu_svm *svm = to_svm(vcpu);
2534 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2535 return emulate_on_interception(vcpu);
2537 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2538 return emulate_on_interception(vcpu);
2540 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2541 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2542 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2544 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2547 if (cr >= 16) { /* mov to cr */
2549 val = kvm_register_read(vcpu, reg);
2550 trace_kvm_cr_write(cr, val);
2553 if (!check_selective_cr0_intercepted(vcpu, val))
2554 err = kvm_set_cr0(vcpu, val);
2560 err = kvm_set_cr3(vcpu, val);
2563 err = kvm_set_cr4(vcpu, val);
2566 err = kvm_set_cr8(vcpu, val);
2569 WARN(1, "unhandled write to CR%d", cr);
2570 kvm_queue_exception(vcpu, UD_VECTOR);
2573 } else { /* mov from cr */
2576 val = kvm_read_cr0(vcpu);
2579 val = vcpu->arch.cr2;
2582 val = kvm_read_cr3(vcpu);
2585 val = kvm_read_cr4(vcpu);
2588 val = kvm_get_cr8(vcpu);
2591 WARN(1, "unhandled read from CR%d", cr);
2592 kvm_queue_exception(vcpu, UD_VECTOR);
2595 kvm_register_write(vcpu, reg, val);
2596 trace_kvm_cr_read(cr, val);
2598 return kvm_complete_insn_gp(vcpu, err);
2601 static int cr_trap(struct kvm_vcpu *vcpu)
2603 struct vcpu_svm *svm = to_svm(vcpu);
2604 unsigned long old_value, new_value;
2608 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2610 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2613 old_value = kvm_read_cr0(vcpu);
2614 svm_set_cr0(vcpu, new_value);
2616 kvm_post_set_cr0(vcpu, old_value, new_value);
2619 old_value = kvm_read_cr4(vcpu);
2620 svm_set_cr4(vcpu, new_value);
2622 kvm_post_set_cr4(vcpu, old_value, new_value);
2625 ret = kvm_set_cr8(vcpu, new_value);
2628 WARN(1, "unhandled CR%d write trap", cr);
2629 kvm_queue_exception(vcpu, UD_VECTOR);
2633 return kvm_complete_insn_gp(vcpu, ret);
2636 static int dr_interception(struct kvm_vcpu *vcpu)
2638 struct vcpu_svm *svm = to_svm(vcpu);
2643 if (vcpu->guest_debug == 0) {
2645 * No more DR vmexits; force a reload of the debug registers
2646 * and reenter on this instruction. The next vmexit will
2647 * retrieve the full state of the debug registers.
2649 clr_dr_intercepts(svm);
2650 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2654 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2655 return emulate_on_interception(vcpu);
2657 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2658 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2659 if (dr >= 16) { /* mov to DRn */
2661 val = kvm_register_read(vcpu, reg);
2662 err = kvm_set_dr(vcpu, dr, val);
2664 kvm_get_dr(vcpu, dr, &val);
2665 kvm_register_write(vcpu, reg, val);
2668 return kvm_complete_insn_gp(vcpu, err);
2671 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2675 u8 cr8_prev = kvm_get_cr8(vcpu);
2676 /* instruction emulation calls kvm_set_cr8() */
2677 r = cr_interception(vcpu);
2678 if (lapic_in_kernel(vcpu))
2680 if (cr8_prev <= kvm_get_cr8(vcpu))
2682 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2686 static int efer_trap(struct kvm_vcpu *vcpu)
2688 struct msr_data msr_info;
2692 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2693 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2694 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2695 * the guest doesn't have X86_FEATURE_SVM.
2697 msr_info.host_initiated = false;
2698 msr_info.index = MSR_EFER;
2699 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2700 ret = kvm_set_msr_common(vcpu, &msr_info);
2702 return kvm_complete_insn_gp(vcpu, ret);
2705 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2709 switch (msr->index) {
2710 case MSR_F10H_DECFG:
2711 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
2712 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
2714 case MSR_IA32_PERF_CAPABILITIES:
2717 return KVM_MSR_RET_INVALID;
2723 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2725 struct vcpu_svm *svm = to_svm(vcpu);
2727 switch (msr_info->index) {
2728 case MSR_AMD64_TSC_RATIO:
2729 if (!msr_info->host_initiated && !svm->tsc_scaling_enabled)
2731 msr_info->data = svm->tsc_ratio_msr;
2734 msr_info->data = svm->vmcb01.ptr->save.star;
2736 #ifdef CONFIG_X86_64
2738 msr_info->data = svm->vmcb01.ptr->save.lstar;
2741 msr_info->data = svm->vmcb01.ptr->save.cstar;
2743 case MSR_KERNEL_GS_BASE:
2744 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2746 case MSR_SYSCALL_MASK:
2747 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2750 case MSR_IA32_SYSENTER_CS:
2751 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2753 case MSR_IA32_SYSENTER_EIP:
2754 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2755 if (guest_cpuid_is_intel(vcpu))
2756 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2758 case MSR_IA32_SYSENTER_ESP:
2759 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2760 if (guest_cpuid_is_intel(vcpu))
2761 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2764 msr_info->data = svm->tsc_aux;
2767 * Nobody will change the following 5 values in the VMCB so we can
2768 * safely return them on rdmsr. They will always be 0 until LBRV is
2771 case MSR_IA32_DEBUGCTLMSR:
2772 msr_info->data = svm->vmcb->save.dbgctl;
2774 case MSR_IA32_LASTBRANCHFROMIP:
2775 msr_info->data = svm->vmcb->save.br_from;
2777 case MSR_IA32_LASTBRANCHTOIP:
2778 msr_info->data = svm->vmcb->save.br_to;
2780 case MSR_IA32_LASTINTFROMIP:
2781 msr_info->data = svm->vmcb->save.last_excp_from;
2783 case MSR_IA32_LASTINTTOIP:
2784 msr_info->data = svm->vmcb->save.last_excp_to;
2786 case MSR_VM_HSAVE_PA:
2787 msr_info->data = svm->nested.hsave_msr;
2790 msr_info->data = svm->nested.vm_cr_msr;
2792 case MSR_IA32_SPEC_CTRL:
2793 if (!msr_info->host_initiated &&
2794 !guest_has_spec_ctrl_msr(vcpu))
2797 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2798 msr_info->data = svm->vmcb->save.spec_ctrl;
2800 msr_info->data = svm->spec_ctrl;
2802 case MSR_AMD64_VIRT_SPEC_CTRL:
2803 if (!msr_info->host_initiated &&
2804 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2807 msr_info->data = svm->virt_spec_ctrl;
2809 case MSR_F15H_IC_CFG: {
2813 family = guest_cpuid_family(vcpu);
2814 model = guest_cpuid_model(vcpu);
2816 if (family < 0 || model < 0)
2817 return kvm_get_msr_common(vcpu, msr_info);
2821 if (family == 0x15 &&
2822 (model >= 0x2 && model < 0x20))
2823 msr_info->data = 0x1E;
2826 case MSR_F10H_DECFG:
2827 msr_info->data = svm->msr_decfg;
2830 return kvm_get_msr_common(vcpu, msr_info);
2835 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2837 struct vcpu_svm *svm = to_svm(vcpu);
2838 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->sev_es.ghcb))
2839 return kvm_complete_insn_gp(vcpu, err);
2841 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 1);
2842 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb,
2844 SVM_EVTINJ_TYPE_EXEPT |
2849 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2851 struct vcpu_svm *svm = to_svm(vcpu);
2852 int svm_dis, chg_mask;
2854 if (data & ~SVM_VM_CR_VALID_MASK)
2857 chg_mask = SVM_VM_CR_VALID_MASK;
2859 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2860 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2862 svm->nested.vm_cr_msr &= ~chg_mask;
2863 svm->nested.vm_cr_msr |= (data & chg_mask);
2865 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2867 /* check for svm_disable while efer.svme is set */
2868 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
2874 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2876 struct vcpu_svm *svm = to_svm(vcpu);
2879 u32 ecx = msr->index;
2880 u64 data = msr->data;
2882 case MSR_AMD64_TSC_RATIO:
2883 if (!msr->host_initiated && !svm->tsc_scaling_enabled)
2886 if (data & TSC_RATIO_RSVD)
2889 svm->tsc_ratio_msr = data;
2891 if (svm->tsc_scaling_enabled && is_guest_mode(vcpu))
2892 nested_svm_update_tsc_ratio_msr(vcpu);
2895 case MSR_IA32_CR_PAT:
2896 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2898 vcpu->arch.pat = data;
2899 svm->vmcb01.ptr->save.g_pat = data;
2900 if (is_guest_mode(vcpu))
2901 nested_vmcb02_compute_g_pat(svm);
2902 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
2904 case MSR_IA32_SPEC_CTRL:
2905 if (!msr->host_initiated &&
2906 !guest_has_spec_ctrl_msr(vcpu))
2909 if (kvm_spec_ctrl_test_value(data))
2912 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2913 svm->vmcb->save.spec_ctrl = data;
2915 svm->spec_ctrl = data;
2921 * When it's written (to non-zero) for the first time, pass
2925 * The handling of the MSR bitmap for L2 guests is done in
2926 * nested_svm_vmrun_msrpm.
2927 * We update the L1 MSR bit as well since it will end up
2928 * touching the MSR anyway now.
2930 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
2932 case MSR_IA32_PRED_CMD:
2933 if (!msr->host_initiated &&
2934 !guest_has_pred_cmd_msr(vcpu))
2937 if (data & ~PRED_CMD_IBPB)
2939 if (!boot_cpu_has(X86_FEATURE_IBPB))
2944 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2945 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
2947 case MSR_AMD64_VIRT_SPEC_CTRL:
2948 if (!msr->host_initiated &&
2949 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2952 if (data & ~SPEC_CTRL_SSBD)
2955 svm->virt_spec_ctrl = data;
2958 svm->vmcb01.ptr->save.star = data;
2960 #ifdef CONFIG_X86_64
2962 svm->vmcb01.ptr->save.lstar = data;
2965 svm->vmcb01.ptr->save.cstar = data;
2967 case MSR_KERNEL_GS_BASE:
2968 svm->vmcb01.ptr->save.kernel_gs_base = data;
2970 case MSR_SYSCALL_MASK:
2971 svm->vmcb01.ptr->save.sfmask = data;
2974 case MSR_IA32_SYSENTER_CS:
2975 svm->vmcb01.ptr->save.sysenter_cs = data;
2977 case MSR_IA32_SYSENTER_EIP:
2978 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
2980 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
2981 * when we spoof an Intel vendor ID (for cross vendor migration).
2982 * In this case we use this intercept to track the high
2983 * 32 bit part of these msrs to support Intel's
2984 * implementation of SYSENTER/SYSEXIT.
2986 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2988 case MSR_IA32_SYSENTER_ESP:
2989 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
2990 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2994 * TSC_AUX is usually changed only during boot and never read
2995 * directly. Intercept TSC_AUX instead of exposing it to the
2996 * guest via direct_access_msrs, and switch it via user return.
2999 r = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
3004 svm->tsc_aux = data;
3006 case MSR_IA32_DEBUGCTLMSR:
3008 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
3012 if (data & DEBUGCTL_RESERVED_BITS)
3015 svm->vmcb->save.dbgctl = data;
3016 vmcb_mark_dirty(svm->vmcb, VMCB_LBR);
3017 if (data & (1ULL<<0))
3018 svm_enable_lbrv(vcpu);
3020 svm_disable_lbrv(vcpu);
3022 case MSR_VM_HSAVE_PA:
3024 * Old kernels did not validate the value written to
3025 * MSR_VM_HSAVE_PA. Allow KVM_SET_MSR to set an invalid
3026 * value to allow live migrating buggy or malicious guests
3027 * originating from those kernels.
3029 if (!msr->host_initiated && !page_address_valid(vcpu, data))
3032 svm->nested.hsave_msr = data & PAGE_MASK;
3035 return svm_set_vm_cr(vcpu, data);
3037 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
3039 case MSR_F10H_DECFG: {
3040 struct kvm_msr_entry msr_entry;
3042 msr_entry.index = msr->index;
3043 if (svm_get_msr_feature(&msr_entry))
3046 /* Check the supported bits */
3047 if (data & ~msr_entry.data)
3050 /* Don't allow the guest to change a bit, #GP */
3051 if (!msr->host_initiated && (data ^ msr_entry.data))
3054 svm->msr_decfg = data;
3058 return kvm_set_msr_common(vcpu, msr);
3063 static int msr_interception(struct kvm_vcpu *vcpu)
3065 if (to_svm(vcpu)->vmcb->control.exit_info_1)
3066 return kvm_emulate_wrmsr(vcpu);
3068 return kvm_emulate_rdmsr(vcpu);
3071 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
3073 kvm_make_request(KVM_REQ_EVENT, vcpu);
3074 svm_clear_vintr(to_svm(vcpu));
3077 * For AVIC, the only reason to end up here is ExtINTs.
3078 * In this case AVIC was temporarily disabled for
3079 * requesting the IRQ window and we have to re-enable it.
3081 kvm_request_apicv_update(vcpu->kvm, true, APICV_INHIBIT_REASON_IRQWIN);
3083 ++vcpu->stat.irq_window_exits;
3087 static int pause_interception(struct kvm_vcpu *vcpu)
3092 * CPL is not made available for an SEV-ES guest, therefore
3093 * vcpu->arch.preempted_in_kernel can never be true. Just
3094 * set in_kernel to false as well.
3096 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3098 if (!kvm_pause_in_guest(vcpu->kvm))
3099 grow_ple_window(vcpu);
3101 kvm_vcpu_on_spin(vcpu, in_kernel);
3102 return kvm_skip_emulated_instruction(vcpu);
3105 static int invpcid_interception(struct kvm_vcpu *vcpu)
3107 struct vcpu_svm *svm = to_svm(vcpu);
3111 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3112 kvm_queue_exception(vcpu, UD_VECTOR);
3117 * For an INVPCID intercept:
3118 * EXITINFO1 provides the linear address of the memory operand.
3119 * EXITINFO2 provides the contents of the register operand.
3121 type = svm->vmcb->control.exit_info_2;
3122 gva = svm->vmcb->control.exit_info_1;
3124 return kvm_handle_invpcid(vcpu, type, gva);
3127 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3128 [SVM_EXIT_READ_CR0] = cr_interception,
3129 [SVM_EXIT_READ_CR3] = cr_interception,
3130 [SVM_EXIT_READ_CR4] = cr_interception,
3131 [SVM_EXIT_READ_CR8] = cr_interception,
3132 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3133 [SVM_EXIT_WRITE_CR0] = cr_interception,
3134 [SVM_EXIT_WRITE_CR3] = cr_interception,
3135 [SVM_EXIT_WRITE_CR4] = cr_interception,
3136 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3137 [SVM_EXIT_READ_DR0] = dr_interception,
3138 [SVM_EXIT_READ_DR1] = dr_interception,
3139 [SVM_EXIT_READ_DR2] = dr_interception,
3140 [SVM_EXIT_READ_DR3] = dr_interception,
3141 [SVM_EXIT_READ_DR4] = dr_interception,
3142 [SVM_EXIT_READ_DR5] = dr_interception,
3143 [SVM_EXIT_READ_DR6] = dr_interception,
3144 [SVM_EXIT_READ_DR7] = dr_interception,
3145 [SVM_EXIT_WRITE_DR0] = dr_interception,
3146 [SVM_EXIT_WRITE_DR1] = dr_interception,
3147 [SVM_EXIT_WRITE_DR2] = dr_interception,
3148 [SVM_EXIT_WRITE_DR3] = dr_interception,
3149 [SVM_EXIT_WRITE_DR4] = dr_interception,
3150 [SVM_EXIT_WRITE_DR5] = dr_interception,
3151 [SVM_EXIT_WRITE_DR6] = dr_interception,
3152 [SVM_EXIT_WRITE_DR7] = dr_interception,
3153 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3154 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3155 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3156 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3157 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3158 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3159 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3160 [SVM_EXIT_INTR] = intr_interception,
3161 [SVM_EXIT_NMI] = nmi_interception,
3162 [SVM_EXIT_SMI] = smi_interception,
3163 [SVM_EXIT_VINTR] = interrupt_window_interception,
3164 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3165 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3166 [SVM_EXIT_IRET] = iret_interception,
3167 [SVM_EXIT_INVD] = kvm_emulate_invd,
3168 [SVM_EXIT_PAUSE] = pause_interception,
3169 [SVM_EXIT_HLT] = kvm_emulate_halt,
3170 [SVM_EXIT_INVLPG] = invlpg_interception,
3171 [SVM_EXIT_INVLPGA] = invlpga_interception,
3172 [SVM_EXIT_IOIO] = io_interception,
3173 [SVM_EXIT_MSR] = msr_interception,
3174 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3175 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3176 [SVM_EXIT_VMRUN] = vmrun_interception,
3177 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3178 [SVM_EXIT_VMLOAD] = vmload_interception,
3179 [SVM_EXIT_VMSAVE] = vmsave_interception,
3180 [SVM_EXIT_STGI] = stgi_interception,
3181 [SVM_EXIT_CLGI] = clgi_interception,
3182 [SVM_EXIT_SKINIT] = skinit_interception,
3183 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3184 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3185 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3186 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3187 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3188 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3189 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3190 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3191 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3192 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3193 [SVM_EXIT_INVPCID] = invpcid_interception,
3194 [SVM_EXIT_NPF] = npf_interception,
3195 [SVM_EXIT_RSM] = rsm_interception,
3196 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3197 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3198 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3201 static void dump_vmcb(struct kvm_vcpu *vcpu)
3203 struct vcpu_svm *svm = to_svm(vcpu);
3204 struct vmcb_control_area *control = &svm->vmcb->control;
3205 struct vmcb_save_area *save = &svm->vmcb->save;
3206 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3208 if (!dump_invalid_vmcb) {
3209 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3213 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3214 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3215 pr_err("VMCB Control Area:\n");
3216 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3217 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3218 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3219 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3220 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3221 pr_err("%-20s%08x %08x\n", "intercepts:",
3222 control->intercepts[INTERCEPT_WORD3],
3223 control->intercepts[INTERCEPT_WORD4]);
3224 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3225 pr_err("%-20s%d\n", "pause filter threshold:",
3226 control->pause_filter_thresh);
3227 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3228 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3229 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3230 pr_err("%-20s%d\n", "asid:", control->asid);
3231 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3232 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3233 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3234 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3235 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3236 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3237 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3238 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3239 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3240 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3241 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3242 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3243 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3244 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3245 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3246 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3247 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3248 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3249 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3250 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3251 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3252 pr_err("VMCB State Save Area:\n");
3253 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3255 save->es.selector, save->es.attrib,
3256 save->es.limit, save->es.base);
3257 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3259 save->cs.selector, save->cs.attrib,
3260 save->cs.limit, save->cs.base);
3261 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3263 save->ss.selector, save->ss.attrib,
3264 save->ss.limit, save->ss.base);
3265 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3267 save->ds.selector, save->ds.attrib,
3268 save->ds.limit, save->ds.base);
3269 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3271 save01->fs.selector, save01->fs.attrib,
3272 save01->fs.limit, save01->fs.base);
3273 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3275 save01->gs.selector, save01->gs.attrib,
3276 save01->gs.limit, save01->gs.base);
3277 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3279 save->gdtr.selector, save->gdtr.attrib,
3280 save->gdtr.limit, save->gdtr.base);
3281 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3283 save01->ldtr.selector, save01->ldtr.attrib,
3284 save01->ldtr.limit, save01->ldtr.base);
3285 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3287 save->idtr.selector, save->idtr.attrib,
3288 save->idtr.limit, save->idtr.base);
3289 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3291 save01->tr.selector, save01->tr.attrib,
3292 save01->tr.limit, save01->tr.base);
3293 pr_err("cpl: %d efer: %016llx\n",
3294 save->cpl, save->efer);
3295 pr_err("%-15s %016llx %-13s %016llx\n",
3296 "cr0:", save->cr0, "cr2:", save->cr2);
3297 pr_err("%-15s %016llx %-13s %016llx\n",
3298 "cr3:", save->cr3, "cr4:", save->cr4);
3299 pr_err("%-15s %016llx %-13s %016llx\n",
3300 "dr6:", save->dr6, "dr7:", save->dr7);
3301 pr_err("%-15s %016llx %-13s %016llx\n",
3302 "rip:", save->rip, "rflags:", save->rflags);
3303 pr_err("%-15s %016llx %-13s %016llx\n",
3304 "rsp:", save->rsp, "rax:", save->rax);
3305 pr_err("%-15s %016llx %-13s %016llx\n",
3306 "star:", save01->star, "lstar:", save01->lstar);
3307 pr_err("%-15s %016llx %-13s %016llx\n",
3308 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3309 pr_err("%-15s %016llx %-13s %016llx\n",
3310 "kernel_gs_base:", save01->kernel_gs_base,
3311 "sysenter_cs:", save01->sysenter_cs);
3312 pr_err("%-15s %016llx %-13s %016llx\n",
3313 "sysenter_esp:", save01->sysenter_esp,
3314 "sysenter_eip:", save01->sysenter_eip);
3315 pr_err("%-15s %016llx %-13s %016llx\n",
3316 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3317 pr_err("%-15s %016llx %-13s %016llx\n",
3318 "br_from:", save->br_from, "br_to:", save->br_to);
3319 pr_err("%-15s %016llx %-13s %016llx\n",
3320 "excp_from:", save->last_excp_from,
3321 "excp_to:", save->last_excp_to);
3324 static bool svm_check_exit_valid(struct kvm_vcpu *vcpu, u64 exit_code)
3326 return (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3327 svm_exit_handlers[exit_code]);
3330 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3332 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3334 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3335 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3336 vcpu->run->internal.ndata = 2;
3337 vcpu->run->internal.data[0] = exit_code;
3338 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3342 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3344 if (!svm_check_exit_valid(vcpu, exit_code))
3345 return svm_handle_invalid_exit(vcpu, exit_code);
3347 #ifdef CONFIG_RETPOLINE
3348 if (exit_code == SVM_EXIT_MSR)
3349 return msr_interception(vcpu);
3350 else if (exit_code == SVM_EXIT_VINTR)
3351 return interrupt_window_interception(vcpu);
3352 else if (exit_code == SVM_EXIT_INTR)
3353 return intr_interception(vcpu);
3354 else if (exit_code == SVM_EXIT_HLT)
3355 return kvm_emulate_halt(vcpu);
3356 else if (exit_code == SVM_EXIT_NPF)
3357 return npf_interception(vcpu);
3359 return svm_exit_handlers[exit_code](vcpu);
3362 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
3363 u64 *info1, u64 *info2,
3364 u32 *intr_info, u32 *error_code)
3366 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3368 *reason = control->exit_code;
3369 *info1 = control->exit_info_1;
3370 *info2 = control->exit_info_2;
3371 *intr_info = control->exit_int_info;
3372 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3373 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3374 *error_code = control->exit_int_info_err;
3379 static int handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3381 struct vcpu_svm *svm = to_svm(vcpu);
3382 struct kvm_run *kvm_run = vcpu->run;
3383 u32 exit_code = svm->vmcb->control.exit_code;
3385 trace_kvm_exit(vcpu, KVM_ISA_SVM);
3387 /* SEV-ES guests must use the CR write traps to track CR registers. */
3388 if (!sev_es_guest(vcpu->kvm)) {
3389 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3390 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3392 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3395 if (is_guest_mode(vcpu)) {
3398 trace_kvm_nested_vmexit(vcpu, KVM_ISA_SVM);
3400 vmexit = nested_svm_exit_special(svm);
3402 if (vmexit == NESTED_EXIT_CONTINUE)
3403 vmexit = nested_svm_exit_handled(svm);
3405 if (vmexit == NESTED_EXIT_DONE)
3409 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3410 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3411 kvm_run->fail_entry.hardware_entry_failure_reason
3412 = svm->vmcb->control.exit_code;
3413 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3418 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
3419 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
3420 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
3421 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
3422 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
3424 __func__, svm->vmcb->control.exit_int_info,
3427 if (exit_fastpath != EXIT_FASTPATH_NONE)
3430 return svm_invoke_exit_handler(vcpu, exit_code);
3433 static void reload_tss(struct kvm_vcpu *vcpu)
3435 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3437 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3441 static void pre_svm_run(struct kvm_vcpu *vcpu)
3443 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3444 struct vcpu_svm *svm = to_svm(vcpu);
3447 * If the previous vmrun of the vmcb occurred on a different physical
3448 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3449 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3451 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3452 svm->current_vmcb->asid_generation = 0;
3453 vmcb_mark_all_dirty(svm->vmcb);
3454 svm->current_vmcb->cpu = vcpu->cpu;
3457 if (sev_guest(vcpu->kvm))
3458 return pre_sev_run(svm, vcpu->cpu);
3460 /* FIXME: handle wraparound of asid_generation */
3461 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3465 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3467 struct vcpu_svm *svm = to_svm(vcpu);
3469 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3470 vcpu->arch.hflags |= HF_NMI_MASK;
3471 if (!sev_es_guest(vcpu->kvm))
3472 svm_set_intercept(svm, INTERCEPT_IRET);
3473 ++vcpu->stat.nmi_injections;
3476 static void svm_set_irq(struct kvm_vcpu *vcpu)
3478 struct vcpu_svm *svm = to_svm(vcpu);
3480 BUG_ON(!(gif_set(svm)));
3482 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
3483 ++vcpu->stat.irq_injections;
3485 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3486 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
3489 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3491 struct vcpu_svm *svm = to_svm(vcpu);
3494 * SEV-ES guests must always keep the CR intercepts cleared. CR
3495 * tracking is done using the CR write traps.
3497 if (sev_es_guest(vcpu->kvm))
3500 if (nested_svm_virtualize_tpr(vcpu))
3503 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3509 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3512 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3514 struct vcpu_svm *svm = to_svm(vcpu);
3515 struct vmcb *vmcb = svm->vmcb;
3521 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3524 ret = (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) ||
3525 (vcpu->arch.hflags & HF_NMI_MASK);
3530 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3532 struct vcpu_svm *svm = to_svm(vcpu);
3533 if (svm->nested.nested_run_pending)
3536 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3537 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3540 return !svm_nmi_blocked(vcpu);
3543 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3545 return !!(vcpu->arch.hflags & HF_NMI_MASK);
3548 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3550 struct vcpu_svm *svm = to_svm(vcpu);
3553 vcpu->arch.hflags |= HF_NMI_MASK;
3554 if (!sev_es_guest(vcpu->kvm))
3555 svm_set_intercept(svm, INTERCEPT_IRET);
3557 vcpu->arch.hflags &= ~HF_NMI_MASK;
3558 if (!sev_es_guest(vcpu->kvm))
3559 svm_clr_intercept(svm, INTERCEPT_IRET);
3563 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3565 struct vcpu_svm *svm = to_svm(vcpu);
3566 struct vmcb *vmcb = svm->vmcb;
3571 if (sev_es_guest(vcpu->kvm)) {
3573 * SEV-ES guests to not expose RFLAGS. Use the VMCB interrupt mask
3574 * bit to determine the state of the IF flag.
3576 if (!(vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK))
3578 } else if (is_guest_mode(vcpu)) {
3579 /* As long as interrupts are being delivered... */
3580 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3581 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3582 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3585 /* ... vmexits aren't blocked by the interrupt shadow */
3586 if (nested_exit_on_intr(svm))
3589 if (!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3593 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3596 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3598 struct vcpu_svm *svm = to_svm(vcpu);
3599 if (svm->nested.nested_run_pending)
3603 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3604 * e.g. if the IRQ arrived asynchronously after checking nested events.
3606 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3609 return !svm_interrupt_blocked(vcpu);
3612 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3614 struct vcpu_svm *svm = to_svm(vcpu);
3617 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3618 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3619 * get that intercept, this function will be called again though and
3620 * we'll get the vintr intercept. However, if the vGIF feature is
3621 * enabled, the STGI interception will not occur. Enable the irq
3622 * window under the assumption that the hardware will set the GIF.
3624 if (vgif_enabled(svm) || gif_set(svm)) {
3626 * IRQ window is not needed when AVIC is enabled,
3627 * unless we have pending ExtINT since it cannot be injected
3628 * via AVIC. In such case, we need to temporarily disable AVIC,
3629 * and fallback to injecting IRQ via V_IRQ.
3631 kvm_request_apicv_update(vcpu->kvm, false, APICV_INHIBIT_REASON_IRQWIN);
3636 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3638 struct vcpu_svm *svm = to_svm(vcpu);
3640 if ((vcpu->arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK)
3641 return; /* IRET will cause a vm exit */
3643 if (!gif_set(svm)) {
3644 if (vgif_enabled(svm))
3645 svm_set_intercept(svm, INTERCEPT_STGI);
3646 return; /* STGI will cause a vm exit */
3650 * Something prevents NMI from been injected. Single step over possible
3651 * problem (IRET or exception injection or interrupt shadow)
3653 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3654 svm->nmi_singlestep = true;
3655 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3658 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
3663 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
3668 void svm_flush_tlb(struct kvm_vcpu *vcpu)
3670 struct vcpu_svm *svm = to_svm(vcpu);
3673 * Flush only the current ASID even if the TLB flush was invoked via
3674 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3675 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3676 * unconditionally does a TLB flush on both nested VM-Enter and nested
3677 * VM-Exit (via kvm_mmu_reset_context()).
3679 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3680 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3682 svm->current_vmcb->asid_generation--;
3685 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
3687 struct vcpu_svm *svm = to_svm(vcpu);
3689 invlpga(gva, svm->vmcb->control.asid);
3692 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3694 struct vcpu_svm *svm = to_svm(vcpu);
3696 if (nested_svm_virtualize_tpr(vcpu))
3699 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
3700 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3701 kvm_set_cr8(vcpu, cr8);
3705 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3707 struct vcpu_svm *svm = to_svm(vcpu);
3710 if (nested_svm_virtualize_tpr(vcpu) ||
3711 kvm_vcpu_apicv_active(vcpu))
3714 cr8 = kvm_get_cr8(vcpu);
3715 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3716 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3719 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
3721 struct vcpu_svm *svm = to_svm(vcpu);
3724 u32 exitintinfo = svm->vmcb->control.exit_int_info;
3725 unsigned int3_injected = svm->int3_injected;
3727 svm->int3_injected = 0;
3730 * If we've made progress since setting HF_IRET_MASK, we've
3731 * executed an IRET and can allow NMI injection.
3733 if ((vcpu->arch.hflags & HF_IRET_MASK) &&
3734 (sev_es_guest(vcpu->kvm) ||
3735 kvm_rip_read(vcpu) != svm->nmi_iret_rip)) {
3736 vcpu->arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3737 kvm_make_request(KVM_REQ_EVENT, vcpu);
3740 vcpu->arch.nmi_injected = false;
3741 kvm_clear_exception_queue(vcpu);
3742 kvm_clear_interrupt_queue(vcpu);
3744 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3747 kvm_make_request(KVM_REQ_EVENT, vcpu);
3749 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3750 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3753 case SVM_EXITINTINFO_TYPE_NMI:
3754 vcpu->arch.nmi_injected = true;
3756 case SVM_EXITINTINFO_TYPE_EXEPT:
3758 * Never re-inject a #VC exception.
3760 if (vector == X86_TRAP_VC)
3764 * In case of software exceptions, do not reinject the vector,
3765 * but re-execute the instruction instead. Rewind RIP first
3766 * if we emulated INT3 before.
3768 if (kvm_exception_is_soft(vector)) {
3769 if (vector == BP_VECTOR && int3_injected &&
3770 kvm_is_linear_rip(vcpu, svm->int3_rip))
3772 kvm_rip_read(vcpu) - int3_injected);
3775 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3776 u32 err = svm->vmcb->control.exit_int_info_err;
3777 kvm_requeue_exception_e(vcpu, vector, err);
3780 kvm_requeue_exception(vcpu, vector);
3782 case SVM_EXITINTINFO_TYPE_INTR:
3783 kvm_queue_interrupt(vcpu, vector, false);
3790 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3792 struct vcpu_svm *svm = to_svm(vcpu);
3793 struct vmcb_control_area *control = &svm->vmcb->control;
3795 control->exit_int_info = control->event_inj;
3796 control->exit_int_info_err = control->event_inj_err;
3797 control->event_inj = 0;
3798 svm_complete_interrupts(vcpu);
3801 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
3803 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_MSR &&
3804 to_svm(vcpu)->vmcb->control.exit_info_1)
3805 return handle_fastpath_set_msr_irqoff(vcpu);
3807 return EXIT_FASTPATH_NONE;
3810 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu)
3812 struct vcpu_svm *svm = to_svm(vcpu);
3813 unsigned long vmcb_pa = svm->current_vmcb->pa;
3815 kvm_guest_enter_irqoff();
3817 if (sev_es_guest(vcpu->kvm)) {
3818 __svm_sev_es_vcpu_run(vmcb_pa);
3820 struct svm_cpu_data *sd = per_cpu(svm_data, vcpu->cpu);
3823 * Use a single vmcb (vmcb01 because it's always valid) for
3824 * context switching guest state via VMLOAD/VMSAVE, that way
3825 * the state doesn't need to be copied between vmcb01 and
3826 * vmcb02 when switching vmcbs for nested virtualization.
3828 vmload(svm->vmcb01.pa);
3829 __svm_vcpu_run(vmcb_pa, (unsigned long *)&vcpu->arch.regs);
3830 vmsave(svm->vmcb01.pa);
3832 vmload(__sme_page_pa(sd->save_area));
3835 kvm_guest_exit_irqoff();
3838 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
3840 struct vcpu_svm *svm = to_svm(vcpu);
3842 trace_kvm_entry(vcpu);
3844 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3845 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3846 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3849 * Disable singlestep if we're injecting an interrupt/exception.
3850 * We don't want our modified rflags to be pushed on the stack where
3851 * we might not be able to easily reset them if we disabled NMI
3854 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
3856 * Event injection happens before external interrupts cause a
3857 * vmexit and interrupts are disabled here, so smp_send_reschedule
3858 * is enough to force an immediate vmexit.
3860 disable_nmi_singlestep(svm);
3861 smp_send_reschedule(vcpu->cpu);
3866 sync_lapic_to_cr8(vcpu);
3868 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
3869 svm->vmcb->control.asid = svm->asid;
3870 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3872 svm->vmcb->save.cr2 = vcpu->arch.cr2;
3874 svm_hv_update_vp_id(svm->vmcb, vcpu);
3877 * Run with all-zero DR6 unless needed, so that we can get the exact cause
3880 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
3881 svm_set_dr6(svm, vcpu->arch.dr6);
3883 svm_set_dr6(svm, DR6_ACTIVE_LOW);
3886 kvm_load_guest_xsave_state(vcpu);
3888 kvm_wait_lapic_expire(vcpu);
3891 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3892 * it's non-zero. Since vmentry is serialising on affected CPUs, there
3893 * is no need to worry about the conditional branch over the wrmsr
3894 * being speculatively taken.
3896 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3897 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
3899 svm_vcpu_enter_exit(vcpu);
3902 * We do not use IBRS in the kernel. If this vCPU has used the
3903 * SPEC_CTRL MSR it may have left it on; save the value and
3904 * turn it off. This is much more efficient than blindly adding
3905 * it to the atomic save/restore list. Especially as the former
3906 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
3908 * For non-nested case:
3909 * If the L01 MSR bitmap does not intercept the MSR, then we need to
3913 * If the L02 MSR bitmap does not intercept the MSR, then we need to
3916 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL) &&
3917 unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
3918 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
3920 if (!sev_es_guest(vcpu->kvm))
3923 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3924 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
3926 if (!sev_es_guest(vcpu->kvm)) {
3927 vcpu->arch.cr2 = svm->vmcb->save.cr2;
3928 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
3929 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
3930 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
3933 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3934 kvm_before_interrupt(vcpu);
3936 kvm_load_host_xsave_state(vcpu);
3939 /* Any pending NMI will happen here */
3941 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3942 kvm_after_interrupt(vcpu);
3944 sync_cr8_to_lapic(vcpu);
3947 if (is_guest_mode(vcpu)) {
3948 nested_sync_control_from_vmcb02(svm);
3950 /* Track VMRUNs that have made past consistency checking */
3951 if (svm->nested.nested_run_pending &&
3952 svm->vmcb->control.exit_code != SVM_EXIT_ERR)
3953 ++vcpu->stat.nested_run;
3955 svm->nested.nested_run_pending = 0;
3958 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
3959 vmcb_mark_all_clean(svm->vmcb);
3961 /* if exit due to PF check for async PF */
3962 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
3963 vcpu->arch.apf.host_apf_flags =
3964 kvm_read_and_reset_apf_flags();
3967 kvm_register_clear_available(vcpu, VCPU_EXREG_PDPTR);
3970 * We need to handle MC intercepts here before the vcpu has a chance to
3971 * change the physical cpu
3973 if (unlikely(svm->vmcb->control.exit_code ==
3974 SVM_EXIT_EXCP_BASE + MC_VECTOR))
3975 svm_handle_mce(vcpu);
3977 svm_complete_interrupts(vcpu);
3979 if (is_guest_mode(vcpu))
3980 return EXIT_FASTPATH_NONE;
3982 return svm_exit_handlers_fastpath(vcpu);
3985 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
3988 struct vcpu_svm *svm = to_svm(vcpu);
3992 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
3993 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
3995 hv_track_root_tdp(vcpu, root_hpa);
3997 /* Loading L2's CR3 is handled by enter_svm_guest_mode. */
3998 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4000 cr3 = vcpu->arch.cr3;
4001 } else if (vcpu->arch.mmu->shadow_root_level >= PT64_ROOT_4LEVEL) {
4002 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
4004 /* PCID in the guest should be impossible with a 32-bit MMU. */
4005 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
4009 svm->vmcb->save.cr3 = cr3;
4010 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
4013 static int is_disabled(void)
4017 rdmsrl(MSR_VM_CR, vm_cr);
4018 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
4025 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4028 * Patch in the VMMCALL instruction:
4030 hypercall[0] = 0x0f;
4031 hypercall[1] = 0x01;
4032 hypercall[2] = 0xd9;
4035 static int __init svm_check_processor_compat(void)
4040 static bool svm_cpu_has_accelerated_tpr(void)
4046 * The kvm parameter can be NULL (module initialization, or invocation before
4047 * VM creation). Be sure to check the kvm parameter before using it.
4049 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4052 case MSR_IA32_MCG_EXT_CTL:
4053 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4055 case MSR_IA32_SMBASE:
4056 /* SEV-ES guests do not support SMM, so report false */
4057 if (kvm && sev_es_guest(kvm))
4067 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4072 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4074 struct vcpu_svm *svm = to_svm(vcpu);
4075 struct kvm_cpuid_entry2 *best;
4077 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4078 boot_cpu_has(X86_FEATURE_XSAVE) &&
4079 boot_cpu_has(X86_FEATURE_XSAVES);
4081 /* Update nrips enabled cache */
4082 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
4083 guest_cpuid_has(vcpu, X86_FEATURE_NRIPS);
4085 svm->tsc_scaling_enabled = tsc_scaling && guest_cpuid_has(vcpu, X86_FEATURE_TSCRATEMSR);
4087 svm_recalc_instruction_intercepts(vcpu, svm);
4089 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4090 if (sev_guest(vcpu->kvm)) {
4091 best = kvm_find_cpuid_entry(vcpu, 0x8000001F, 0);
4093 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4096 if (kvm_vcpu_apicv_active(vcpu)) {
4098 * AVIC does not work with an x2APIC mode guest. If the X2APIC feature
4099 * is exposed to the guest, disable AVIC.
4101 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC))
4102 kvm_request_apicv_update(vcpu->kvm, false,
4103 APICV_INHIBIT_REASON_X2APIC);
4106 * Currently, AVIC does not work with nested virtualization.
4107 * So, we disable AVIC when cpuid for SVM is set in the L1 guest.
4109 if (nested && guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4110 kvm_request_apicv_update(vcpu->kvm, false,
4111 APICV_INHIBIT_REASON_NESTED);
4113 init_vmcb_after_set_cpuid(vcpu);
4116 static bool svm_has_wbinvd_exit(void)
4121 #define PRE_EX(exit) { .exit_code = (exit), \
4122 .stage = X86_ICPT_PRE_EXCEPT, }
4123 #define POST_EX(exit) { .exit_code = (exit), \
4124 .stage = X86_ICPT_POST_EXCEPT, }
4125 #define POST_MEM(exit) { .exit_code = (exit), \
4126 .stage = X86_ICPT_POST_MEMACCESS, }
4128 static const struct __x86_intercept {
4130 enum x86_intercept_stage stage;
4131 } x86_intercept_map[] = {
4132 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4133 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4134 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4135 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4136 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4137 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4138 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4139 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4140 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4141 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4142 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4143 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4144 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4145 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4146 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4147 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4148 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4149 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4150 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4151 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4152 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4153 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4154 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4155 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4156 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4157 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4158 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4159 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4160 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4161 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4162 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4163 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4164 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4165 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4166 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4167 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4168 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4169 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4170 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4171 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4172 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4173 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4174 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4175 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4176 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4177 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4178 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4185 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4186 struct x86_instruction_info *info,
4187 enum x86_intercept_stage stage,
4188 struct x86_exception *exception)
4190 struct vcpu_svm *svm = to_svm(vcpu);
4191 int vmexit, ret = X86EMUL_CONTINUE;
4192 struct __x86_intercept icpt_info;
4193 struct vmcb *vmcb = svm->vmcb;
4195 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4198 icpt_info = x86_intercept_map[info->intercept];
4200 if (stage != icpt_info.stage)
4203 switch (icpt_info.exit_code) {
4204 case SVM_EXIT_READ_CR0:
4205 if (info->intercept == x86_intercept_cr_read)
4206 icpt_info.exit_code += info->modrm_reg;
4208 case SVM_EXIT_WRITE_CR0: {
4209 unsigned long cr0, val;
4211 if (info->intercept == x86_intercept_cr_write)
4212 icpt_info.exit_code += info->modrm_reg;
4214 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4215 info->intercept == x86_intercept_clts)
4218 if (!(vmcb_is_intercept(&svm->nested.ctl,
4219 INTERCEPT_SELECTIVE_CR0)))
4222 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4223 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4225 if (info->intercept == x86_intercept_lmsw) {
4228 /* lmsw can't clear PE - catch this here */
4229 if (cr0 & X86_CR0_PE)
4234 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4238 case SVM_EXIT_READ_DR0:
4239 case SVM_EXIT_WRITE_DR0:
4240 icpt_info.exit_code += info->modrm_reg;
4243 if (info->intercept == x86_intercept_wrmsr)
4244 vmcb->control.exit_info_1 = 1;
4246 vmcb->control.exit_info_1 = 0;
4248 case SVM_EXIT_PAUSE:
4250 * We get this for NOP only, but pause
4251 * is rep not, check this here
4253 if (info->rep_prefix != REPE_PREFIX)
4256 case SVM_EXIT_IOIO: {
4260 if (info->intercept == x86_intercept_in ||
4261 info->intercept == x86_intercept_ins) {
4262 exit_info = ((info->src_val & 0xffff) << 16) |
4264 bytes = info->dst_bytes;
4266 exit_info = (info->dst_val & 0xffff) << 16;
4267 bytes = info->src_bytes;
4270 if (info->intercept == x86_intercept_outs ||
4271 info->intercept == x86_intercept_ins)
4272 exit_info |= SVM_IOIO_STR_MASK;
4274 if (info->rep_prefix)
4275 exit_info |= SVM_IOIO_REP_MASK;
4277 bytes = min(bytes, 4u);
4279 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4281 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4283 vmcb->control.exit_info_1 = exit_info;
4284 vmcb->control.exit_info_2 = info->next_rip;
4292 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4293 if (static_cpu_has(X86_FEATURE_NRIPS))
4294 vmcb->control.next_rip = info->next_rip;
4295 vmcb->control.exit_code = icpt_info.exit_code;
4296 vmexit = nested_svm_exit_handled(svm);
4298 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4305 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4309 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4311 if (!kvm_pause_in_guest(vcpu->kvm))
4312 shrink_ple_window(vcpu);
4315 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4317 /* [63:9] are reserved. */
4318 vcpu->arch.mcg_cap &= 0x1ff;
4321 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4323 struct vcpu_svm *svm = to_svm(vcpu);
4325 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4329 return is_smm(vcpu);
4332 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4334 struct vcpu_svm *svm = to_svm(vcpu);
4335 if (svm->nested.nested_run_pending)
4338 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4339 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4342 return !svm_smi_blocked(vcpu);
4345 static int svm_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
4347 struct vcpu_svm *svm = to_svm(vcpu);
4348 struct kvm_host_map map_save;
4351 if (!is_guest_mode(vcpu))
4354 /* FED8h - SVM Guest */
4355 put_smstate(u64, smstate, 0x7ed8, 1);
4356 /* FEE0h - SVM Guest VMCB Physical Address */
4357 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb12_gpa);
4359 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4360 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4361 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4363 ret = nested_svm_vmexit(svm);
4368 * KVM uses VMCB01 to store L1 host state while L2 runs but
4369 * VMCB01 is going to be used during SMM and thus the state will
4370 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4371 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4372 * format of the area is identical to guest save area offsetted
4373 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4374 * within 'struct vmcb'). Note: HSAVE area may also be used by
4375 * L1 hypervisor to save additional host context (e.g. KVM does
4376 * that, see svm_prepare_guest_switch()) which must be
4379 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4380 &map_save) == -EINVAL)
4383 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4385 svm_copy_vmrun_state(map_save.hva + 0x400,
4386 &svm->vmcb01.ptr->save);
4388 kvm_vcpu_unmap(vcpu, &map_save, true);
4392 static int svm_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
4394 struct vcpu_svm *svm = to_svm(vcpu);
4395 struct kvm_host_map map, map_save;
4396 u64 saved_efer, vmcb12_gpa;
4397 struct vmcb *vmcb12;
4400 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4403 /* Non-zero if SMI arrived while vCPU was in guest mode. */
4404 if (!GET_SMSTATE(u64, smstate, 0x7ed8))
4407 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4410 saved_efer = GET_SMSTATE(u64, smstate, 0x7ed0);
4411 if (!(saved_efer & EFER_SVME))
4414 vmcb12_gpa = GET_SMSTATE(u64, smstate, 0x7ee0);
4415 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map) == -EINVAL)
4419 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save) == -EINVAL)
4422 if (svm_allocate_nested(svm))
4426 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4427 * used during SMM (see svm_enter_smm())
4430 svm_copy_vmrun_state(&svm->vmcb01.ptr->save, map_save.hva + 0x400);
4433 * Enter the nested guest now
4437 nested_load_control_from_vmcb12(svm, &vmcb12->control);
4438 ret = enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, false);
4441 kvm_vcpu_unmap(vcpu, &map_save, true);
4443 kvm_vcpu_unmap(vcpu, &map, true);
4447 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4449 struct vcpu_svm *svm = to_svm(vcpu);
4451 if (!gif_set(svm)) {
4452 if (vgif_enabled(svm))
4453 svm_set_intercept(svm, INTERCEPT_STGI);
4454 /* STGI will cause a vm exit */
4456 /* We must be in SMM; RSM will cause a vmexit anyway. */
4460 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, void *insn, int insn_len)
4462 bool smep, smap, is_user;
4466 * When the guest is an SEV-ES guest, emulation is not possible.
4468 if (sev_es_guest(vcpu->kvm))
4472 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4475 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
4476 * possible that CPU microcode implementing DecodeAssist will fail
4477 * to read bytes of instruction which caused #NPF. In this case,
4478 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
4479 * return 0 instead of the correct guest instruction bytes.
4481 * This happens because CPU microcode reading instruction bytes
4482 * uses a special opcode which attempts to read data using CPL=0
4483 * privileges. The microcode reads CS:RIP and if it hits a SMAP
4484 * fault, it gives up and returns no instruction bytes.
4487 * We reach here in case CPU supports DecodeAssist, raised #NPF and
4488 * returned 0 in GuestIntrBytes field of the VMCB.
4489 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
4490 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
4491 * in case vCPU CPL==3 (Because otherwise guest would have triggered
4492 * a SMEP fault instead of #NPF).
4493 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
4494 * As most guests enable SMAP if they have also enabled SMEP, use above
4495 * logic in order to attempt minimize false-positive of detecting errata
4496 * while still preserving all cases semantic correctness.
4499 * To determine what instruction the guest was executing, the hypervisor
4500 * will have to decode the instruction at the instruction pointer.
4502 * In non SEV guest, hypervisor will be able to read the guest
4503 * memory to decode the instruction pointer when insn_len is zero
4504 * so we return true to indicate that decoding is possible.
4506 * But in the SEV guest, the guest memory is encrypted with the
4507 * guest specific key and hypervisor will not be able to decode the
4508 * instruction pointer so we will not able to workaround it. Lets
4509 * print the error and request to kill the guest.
4511 if (likely(!insn || insn_len))
4515 * If RIP is invalid, go ahead with emulation which will cause an
4516 * internal error exit.
4518 if (!kvm_vcpu_gfn_to_memslot(vcpu, kvm_rip_read(vcpu) >> PAGE_SHIFT))
4521 cr4 = kvm_read_cr4(vcpu);
4522 smep = cr4 & X86_CR4_SMEP;
4523 smap = cr4 & X86_CR4_SMAP;
4524 is_user = svm_get_cpl(vcpu) == 3;
4525 if (smap && (!smep || is_user)) {
4526 if (!sev_guest(vcpu->kvm))
4529 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
4530 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4536 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4538 struct vcpu_svm *svm = to_svm(vcpu);
4541 * TODO: Last condition latch INIT signals on vCPU when
4542 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
4543 * To properly emulate the INIT intercept,
4544 * svm_check_nested_events() should call nested_svm_vmexit()
4545 * if an INIT signal is pending.
4547 return !gif_set(svm) ||
4548 (vmcb_is_intercept(&svm->vmcb->control, INTERCEPT_INIT));
4551 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4553 if (!sev_es_guest(vcpu->kvm))
4554 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4556 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4559 static void svm_vm_destroy(struct kvm *kvm)
4561 avic_vm_destroy(kvm);
4562 sev_vm_destroy(kvm);
4565 static int svm_vm_init(struct kvm *kvm)
4567 if (!pause_filter_count || !pause_filter_thresh)
4568 kvm->arch.pause_in_guest = true;
4571 int ret = avic_vm_init(kvm);
4579 static struct kvm_x86_ops svm_x86_ops __initdata = {
4582 .hardware_unsetup = svm_hardware_teardown,
4583 .hardware_enable = svm_hardware_enable,
4584 .hardware_disable = svm_hardware_disable,
4585 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
4586 .has_emulated_msr = svm_has_emulated_msr,
4588 .vcpu_create = svm_create_vcpu,
4589 .vcpu_free = svm_free_vcpu,
4590 .vcpu_reset = svm_vcpu_reset,
4592 .vm_size = sizeof(struct kvm_svm),
4593 .vm_init = svm_vm_init,
4594 .vm_destroy = svm_vm_destroy,
4596 .prepare_guest_switch = svm_prepare_guest_switch,
4597 .vcpu_load = svm_vcpu_load,
4598 .vcpu_put = svm_vcpu_put,
4599 .vcpu_blocking = svm_vcpu_blocking,
4600 .vcpu_unblocking = svm_vcpu_unblocking,
4602 .update_exception_bitmap = svm_update_exception_bitmap,
4603 .get_msr_feature = svm_get_msr_feature,
4604 .get_msr = svm_get_msr,
4605 .set_msr = svm_set_msr,
4606 .get_segment_base = svm_get_segment_base,
4607 .get_segment = svm_get_segment,
4608 .set_segment = svm_set_segment,
4609 .get_cpl = svm_get_cpl,
4610 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
4611 .set_cr0 = svm_set_cr0,
4612 .is_valid_cr4 = svm_is_valid_cr4,
4613 .set_cr4 = svm_set_cr4,
4614 .set_efer = svm_set_efer,
4615 .get_idt = svm_get_idt,
4616 .set_idt = svm_set_idt,
4617 .get_gdt = svm_get_gdt,
4618 .set_gdt = svm_set_gdt,
4619 .set_dr7 = svm_set_dr7,
4620 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4621 .cache_reg = svm_cache_reg,
4622 .get_rflags = svm_get_rflags,
4623 .set_rflags = svm_set_rflags,
4625 .tlb_flush_all = svm_flush_tlb,
4626 .tlb_flush_current = svm_flush_tlb,
4627 .tlb_flush_gva = svm_flush_tlb_gva,
4628 .tlb_flush_guest = svm_flush_tlb,
4630 .run = svm_vcpu_run,
4631 .handle_exit = handle_exit,
4632 .skip_emulated_instruction = skip_emulated_instruction,
4633 .update_emulated_instruction = NULL,
4634 .set_interrupt_shadow = svm_set_interrupt_shadow,
4635 .get_interrupt_shadow = svm_get_interrupt_shadow,
4636 .patch_hypercall = svm_patch_hypercall,
4637 .set_irq = svm_set_irq,
4638 .set_nmi = svm_inject_nmi,
4639 .queue_exception = svm_queue_exception,
4640 .cancel_injection = svm_cancel_injection,
4641 .interrupt_allowed = svm_interrupt_allowed,
4642 .nmi_allowed = svm_nmi_allowed,
4643 .get_nmi_mask = svm_get_nmi_mask,
4644 .set_nmi_mask = svm_set_nmi_mask,
4645 .enable_nmi_window = svm_enable_nmi_window,
4646 .enable_irq_window = svm_enable_irq_window,
4647 .update_cr8_intercept = svm_update_cr8_intercept,
4648 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
4649 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
4650 .check_apicv_inhibit_reasons = svm_check_apicv_inhibit_reasons,
4651 .load_eoi_exitmap = svm_load_eoi_exitmap,
4652 .hwapic_irr_update = svm_hwapic_irr_update,
4653 .hwapic_isr_update = svm_hwapic_isr_update,
4654 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
4655 .apicv_post_state_restore = avic_post_state_restore,
4657 .set_tss_addr = svm_set_tss_addr,
4658 .set_identity_map_addr = svm_set_identity_map_addr,
4659 .get_mt_mask = svm_get_mt_mask,
4661 .get_exit_info = svm_get_exit_info,
4663 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
4665 .has_wbinvd_exit = svm_has_wbinvd_exit,
4667 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
4668 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
4669 .write_tsc_offset = svm_write_tsc_offset,
4670 .write_tsc_multiplier = svm_write_tsc_multiplier,
4672 .load_mmu_pgd = svm_load_mmu_pgd,
4674 .check_intercept = svm_check_intercept,
4675 .handle_exit_irqoff = svm_handle_exit_irqoff,
4677 .request_immediate_exit = __kvm_request_immediate_exit,
4679 .sched_in = svm_sched_in,
4681 .pmu_ops = &amd_pmu_ops,
4682 .nested_ops = &svm_nested_ops,
4684 .deliver_posted_interrupt = svm_deliver_avic_intr,
4685 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
4686 .update_pi_irte = svm_update_pi_irte,
4687 .setup_mce = svm_setup_mce,
4689 .smi_allowed = svm_smi_allowed,
4690 .enter_smm = svm_enter_smm,
4691 .leave_smm = svm_leave_smm,
4692 .enable_smi_window = svm_enable_smi_window,
4694 .mem_enc_op = svm_mem_enc_op,
4695 .mem_enc_reg_region = svm_register_enc_region,
4696 .mem_enc_unreg_region = svm_unregister_enc_region,
4698 .vm_copy_enc_context_from = svm_vm_copy_asid_from,
4699 .vm_move_enc_context_from = svm_vm_migrate_from,
4701 .can_emulate_instruction = svm_can_emulate_instruction,
4703 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
4705 .msr_filter_changed = svm_msr_filter_changed,
4706 .complete_emulated_msr = svm_complete_emulated_msr,
4708 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
4711 static struct kvm_x86_init_ops svm_init_ops __initdata = {
4712 .cpu_has_kvm_support = has_svm,
4713 .disabled_by_bios = is_disabled,
4714 .hardware_setup = svm_hardware_setup,
4715 .check_processor_compatibility = svm_check_processor_compat,
4717 .runtime_ops = &svm_x86_ops,
4720 static int __init svm_init(void)
4722 __unused_size_checks();
4724 return kvm_init(&svm_init_ops, sizeof(struct vcpu_svm),
4725 __alignof__(struct vcpu_svm), THIS_MODULE);
4728 static void __exit svm_exit(void)
4733 module_init(svm_init)
4734 module_exit(svm_exit)