1 #define pr_fmt(fmt) "SVM: " fmt
3 #include <linux/kvm_host.h>
7 #include "kvm_cache_regs.h"
12 #include <linux/module.h>
13 #include <linux/mod_devicetable.h>
14 #include <linux/kernel.h>
15 #include <linux/vmalloc.h>
16 #include <linux/highmem.h>
17 #include <linux/amd-iommu.h>
18 #include <linux/sched.h>
19 #include <linux/trace_events.h>
20 #include <linux/slab.h>
21 #include <linux/hashtable.h>
22 #include <linux/objtool.h>
23 #include <linux/psp-sev.h>
24 #include <linux/file.h>
25 #include <linux/pagemap.h>
26 #include <linux/swap.h>
27 #include <linux/rwsem.h>
28 #include <linux/cc_platform.h>
31 #include <asm/perf_event.h>
32 #include <asm/tlbflush.h>
34 #include <asm/debugreg.h>
35 #include <asm/kvm_para.h>
36 #include <asm/irq_remapping.h>
37 #include <asm/spec-ctrl.h>
38 #include <asm/cpu_device_id.h>
39 #include <asm/traps.h>
40 #include <asm/fpu/api.h>
42 #include <asm/virtext.h>
48 #include "kvm_onhyperv.h"
49 #include "svm_onhyperv.h"
51 MODULE_AUTHOR("Qumranet");
52 MODULE_LICENSE("GPL");
55 static const struct x86_cpu_id svm_cpu_id[] = {
56 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
59 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
62 #define SEG_TYPE_LDT 2
63 #define SEG_TYPE_BUSY_TSS16 3
65 static bool erratum_383_found __read_mostly;
67 u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
70 * Set osvw_len to higher value when updated Revision Guides
71 * are published and we know what the new status bits are
73 static uint64_t osvw_len = 4, osvw_status;
75 static DEFINE_PER_CPU(u64, current_tsc_ratio);
77 #define X2APIC_MSR(x) (APIC_BASE_MSR + (x >> 4))
79 static const struct svm_direct_access_msrs {
80 u32 index; /* Index of the MSR */
81 bool always; /* True if intercept is initially cleared */
82 } direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
83 { .index = MSR_STAR, .always = true },
84 { .index = MSR_IA32_SYSENTER_CS, .always = true },
85 { .index = MSR_IA32_SYSENTER_EIP, .always = false },
86 { .index = MSR_IA32_SYSENTER_ESP, .always = false },
88 { .index = MSR_GS_BASE, .always = true },
89 { .index = MSR_FS_BASE, .always = true },
90 { .index = MSR_KERNEL_GS_BASE, .always = true },
91 { .index = MSR_LSTAR, .always = true },
92 { .index = MSR_CSTAR, .always = true },
93 { .index = MSR_SYSCALL_MASK, .always = true },
95 { .index = MSR_IA32_SPEC_CTRL, .always = false },
96 { .index = MSR_IA32_PRED_CMD, .always = false },
97 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
98 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
99 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
100 { .index = MSR_IA32_LASTINTTOIP, .always = false },
101 { .index = MSR_EFER, .always = false },
102 { .index = MSR_IA32_CR_PAT, .always = false },
103 { .index = MSR_AMD64_SEV_ES_GHCB, .always = true },
104 { .index = MSR_TSC_AUX, .always = false },
105 { .index = X2APIC_MSR(APIC_ID), .always = false },
106 { .index = X2APIC_MSR(APIC_LVR), .always = false },
107 { .index = X2APIC_MSR(APIC_TASKPRI), .always = false },
108 { .index = X2APIC_MSR(APIC_ARBPRI), .always = false },
109 { .index = X2APIC_MSR(APIC_PROCPRI), .always = false },
110 { .index = X2APIC_MSR(APIC_EOI), .always = false },
111 { .index = X2APIC_MSR(APIC_RRR), .always = false },
112 { .index = X2APIC_MSR(APIC_LDR), .always = false },
113 { .index = X2APIC_MSR(APIC_DFR), .always = false },
114 { .index = X2APIC_MSR(APIC_SPIV), .always = false },
115 { .index = X2APIC_MSR(APIC_ISR), .always = false },
116 { .index = X2APIC_MSR(APIC_TMR), .always = false },
117 { .index = X2APIC_MSR(APIC_IRR), .always = false },
118 { .index = X2APIC_MSR(APIC_ESR), .always = false },
119 { .index = X2APIC_MSR(APIC_ICR), .always = false },
120 { .index = X2APIC_MSR(APIC_ICR2), .always = false },
124 * AMD does not virtualize APIC TSC-deadline timer mode, but it is
125 * emulated by KVM. When setting APIC LVTT (0x832) register bit 18,
126 * the AVIC hardware would generate GP fault. Therefore, always
127 * intercept the MSR 0x832, and do not setup direct_access_msr.
129 { .index = X2APIC_MSR(APIC_LVTTHMR), .always = false },
130 { .index = X2APIC_MSR(APIC_LVTPC), .always = false },
131 { .index = X2APIC_MSR(APIC_LVT0), .always = false },
132 { .index = X2APIC_MSR(APIC_LVT1), .always = false },
133 { .index = X2APIC_MSR(APIC_LVTERR), .always = false },
134 { .index = X2APIC_MSR(APIC_TMICT), .always = false },
135 { .index = X2APIC_MSR(APIC_TMCCT), .always = false },
136 { .index = X2APIC_MSR(APIC_TDCR), .always = false },
137 { .index = MSR_INVALID, .always = false },
141 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
142 * pause_filter_count: On processors that support Pause filtering(indicated
143 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
144 * count value. On VMRUN this value is loaded into an internal counter.
145 * Each time a pause instruction is executed, this counter is decremented
146 * until it reaches zero at which time a #VMEXIT is generated if pause
147 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
148 * Intercept Filtering for more details.
149 * This also indicate if ple logic enabled.
151 * pause_filter_thresh: In addition, some processor families support advanced
152 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
153 * the amount of time a guest is allowed to execute in a pause loop.
154 * In this mode, a 16-bit pause filter threshold field is added in the
155 * VMCB. The threshold value is a cycle count that is used to reset the
156 * pause counter. As with simple pause filtering, VMRUN loads the pause
157 * count value from VMCB into an internal counter. Then, on each pause
158 * instruction the hardware checks the elapsed number of cycles since
159 * the most recent pause instruction against the pause filter threshold.
160 * If the elapsed cycle count is greater than the pause filter threshold,
161 * then the internal pause count is reloaded from the VMCB and execution
162 * continues. If the elapsed cycle count is less than the pause filter
163 * threshold, then the internal pause count is decremented. If the count
164 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
165 * triggered. If advanced pause filtering is supported and pause filter
166 * threshold field is set to zero, the filter will operate in the simpler,
170 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
171 module_param(pause_filter_thresh, ushort, 0444);
173 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
174 module_param(pause_filter_count, ushort, 0444);
176 /* Default doubles per-vcpu window every exit. */
177 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
178 module_param(pause_filter_count_grow, ushort, 0444);
180 /* Default resets per-vcpu window every exit to pause_filter_count. */
181 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
182 module_param(pause_filter_count_shrink, ushort, 0444);
184 /* Default is to compute the maximum so we can never overflow. */
185 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
186 module_param(pause_filter_count_max, ushort, 0444);
189 * Use nested page tables by default. Note, NPT may get forced off by
190 * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
192 bool npt_enabled = true;
193 module_param_named(npt, npt_enabled, bool, 0444);
195 /* allow nested virtualization in KVM/SVM */
196 static int nested = true;
197 module_param(nested, int, S_IRUGO);
199 /* enable/disable Next RIP Save */
200 static int nrips = true;
201 module_param(nrips, int, 0444);
203 /* enable/disable Virtual VMLOAD VMSAVE */
204 static int vls = true;
205 module_param(vls, int, 0444);
207 /* enable/disable Virtual GIF */
209 module_param(vgif, int, 0444);
211 /* enable/disable LBR virtualization */
212 static int lbrv = true;
213 module_param(lbrv, int, 0444);
215 static int tsc_scaling = true;
216 module_param(tsc_scaling, int, 0444);
219 * enable / disable AVIC. Because the defaults differ for APICv
220 * support between VMX and SVM we cannot use module_param_named.
223 module_param(avic, bool, 0444);
225 bool __read_mostly dump_invalid_vmcb;
226 module_param(dump_invalid_vmcb, bool, 0644);
229 bool intercept_smi = true;
230 module_param(intercept_smi, bool, 0444);
233 static bool svm_gp_erratum_intercept = true;
235 static u8 rsm_ins_bytes[] = "\x0f\xaa";
237 static unsigned long iopm_base;
239 struct kvm_ldttss_desc {
242 unsigned base1:8, type:5, dpl:2, p:1;
243 unsigned limit1:4, zero0:3, g:1, base2:8;
246 } __attribute__((packed));
248 DEFINE_PER_CPU(struct svm_cpu_data, svm_data);
251 * Only MSR_TSC_AUX is switched via the user return hook. EFER is switched via
252 * the VMCB, and the SYSCALL/SYSENTER MSRs are handled by VMLOAD/VMSAVE.
254 * RDTSCP and RDPID are not used in the kernel, specifically to allow KVM to
255 * defer the restoration of TSC_AUX until the CPU returns to userspace.
257 static int tsc_aux_uret_slot __read_mostly = -1;
259 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
261 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
262 #define MSRS_RANGE_SIZE 2048
263 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
265 u32 svm_msrpm_offset(u32 msr)
270 for (i = 0; i < NUM_MSR_MAPS; i++) {
271 if (msr < msrpm_ranges[i] ||
272 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
275 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
276 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
278 /* Now we have the u8 offset - but need the u32 offset */
282 /* MSR not in any range */
286 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu);
288 static int get_npt_level(void)
291 return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
293 return PT32E_ROOT_LEVEL;
297 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
299 struct vcpu_svm *svm = to_svm(vcpu);
300 u64 old_efer = vcpu->arch.efer;
301 vcpu->arch.efer = efer;
304 /* Shadow paging assumes NX to be available. */
307 if (!(efer & EFER_LMA))
311 if ((old_efer & EFER_SVME) != (efer & EFER_SVME)) {
312 if (!(efer & EFER_SVME)) {
313 svm_leave_nested(vcpu);
314 svm_set_gif(svm, true);
315 /* #GP intercept is still needed for vmware backdoor */
316 if (!enable_vmware_backdoor)
317 clr_exception_intercept(svm, GP_VECTOR);
320 * Free the nested guest state, unless we are in SMM.
321 * In this case we will return to the nested guest
322 * as soon as we leave SMM.
325 svm_free_nested(svm);
328 int ret = svm_allocate_nested(svm);
331 vcpu->arch.efer = old_efer;
336 * Never intercept #GP for SEV guests, KVM can't
337 * decrypt guest memory to workaround the erratum.
339 if (svm_gp_erratum_intercept && !sev_guest(vcpu->kvm))
340 set_exception_intercept(svm, GP_VECTOR);
344 svm->vmcb->save.efer = efer | EFER_SVME;
345 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
349 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
351 struct vcpu_svm *svm = to_svm(vcpu);
354 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
355 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
359 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
361 struct vcpu_svm *svm = to_svm(vcpu);
364 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
366 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
370 static int __svm_skip_emulated_instruction(struct kvm_vcpu *vcpu,
371 bool commit_side_effects)
373 struct vcpu_svm *svm = to_svm(vcpu);
374 unsigned long old_rflags;
377 * SEV-ES does not expose the next RIP. The RIP update is controlled by
378 * the type of exit and the #VC handler in the guest.
380 if (sev_es_guest(vcpu->kvm))
383 if (nrips && svm->vmcb->control.next_rip != 0) {
384 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
385 svm->next_rip = svm->vmcb->control.next_rip;
388 if (!svm->next_rip) {
389 if (unlikely(!commit_side_effects))
390 old_rflags = svm->vmcb->save.rflags;
392 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
395 if (unlikely(!commit_side_effects))
396 svm->vmcb->save.rflags = old_rflags;
398 kvm_rip_write(vcpu, svm->next_rip);
402 if (likely(commit_side_effects))
403 svm_set_interrupt_shadow(vcpu, 0);
408 static int svm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
410 return __svm_skip_emulated_instruction(vcpu, true);
413 static int svm_update_soft_interrupt_rip(struct kvm_vcpu *vcpu)
415 unsigned long rip, old_rip = kvm_rip_read(vcpu);
416 struct vcpu_svm *svm = to_svm(vcpu);
419 * Due to architectural shortcomings, the CPU doesn't always provide
420 * NextRIP, e.g. if KVM intercepted an exception that occurred while
421 * the CPU was vectoring an INTO/INT3 in the guest. Temporarily skip
422 * the instruction even if NextRIP is supported to acquire the next
423 * RIP so that it can be shoved into the NextRIP field, otherwise
424 * hardware will fail to advance guest RIP during event injection.
425 * Drop the exception/interrupt if emulation fails and effectively
426 * retry the instruction, it's the least awful option. If NRIPS is
427 * in use, the skip must not commit any side effects such as clearing
428 * the interrupt shadow or RFLAGS.RF.
430 if (!__svm_skip_emulated_instruction(vcpu, !nrips))
433 rip = kvm_rip_read(vcpu);
436 * Save the injection information, even when using next_rip, as the
437 * VMCB's next_rip will be lost (cleared on VM-Exit) if the injection
438 * doesn't complete due to a VM-Exit occurring while the CPU is
439 * vectoring the event. Decoding the instruction isn't guaranteed to
440 * work as there may be no backing instruction, e.g. if the event is
441 * being injected by L1 for L2, or if the guest is patching INT3 into
442 * a different instruction.
444 svm->soft_int_injected = true;
445 svm->soft_int_csbase = svm->vmcb->save.cs.base;
446 svm->soft_int_old_rip = old_rip;
447 svm->soft_int_next_rip = rip;
450 kvm_rip_write(vcpu, old_rip);
452 if (static_cpu_has(X86_FEATURE_NRIPS))
453 svm->vmcb->control.next_rip = rip;
458 static void svm_inject_exception(struct kvm_vcpu *vcpu)
460 struct kvm_queued_exception *ex = &vcpu->arch.exception;
461 struct vcpu_svm *svm = to_svm(vcpu);
463 kvm_deliver_exception_payload(vcpu, ex);
465 if (kvm_exception_is_soft(ex->vector) &&
466 svm_update_soft_interrupt_rip(vcpu))
469 svm->vmcb->control.event_inj = ex->vector
471 | (ex->has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
472 | SVM_EVTINJ_TYPE_EXEPT;
473 svm->vmcb->control.event_inj_err = ex->error_code;
476 static void svm_init_erratum_383(void)
482 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
485 /* Use _safe variants to not break nested virtualization */
486 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
492 low = lower_32_bits(val);
493 high = upper_32_bits(val);
495 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
497 erratum_383_found = true;
500 static void svm_init_osvw(struct kvm_vcpu *vcpu)
503 * Guests should see errata 400 and 415 as fixed (assuming that
504 * HLT and IO instructions are intercepted).
506 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
507 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
510 * By increasing VCPU's osvw.length to 3 we are telling the guest that
511 * all osvw.status bits inside that length, including bit 0 (which is
512 * reserved for erratum 298), are valid. However, if host processor's
513 * osvw_len is 0 then osvw_status[0] carries no information. We need to
514 * be conservative here and therefore we tell the guest that erratum 298
515 * is present (because we really don't know).
517 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
518 vcpu->arch.osvw.status |= 1;
521 static int has_svm(void)
525 if (!cpu_has_svm(&msg)) {
526 printk(KERN_INFO "has_svm: %s\n", msg);
530 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
531 pr_info("KVM is unsupported when running as an SEV guest\n");
538 void __svm_write_tsc_multiplier(u64 multiplier)
542 if (multiplier == __this_cpu_read(current_tsc_ratio))
545 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
546 __this_cpu_write(current_tsc_ratio, multiplier);
551 static void svm_hardware_disable(void)
553 /* Make sure we clean up behind us */
555 __svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
559 amd_pmu_disable_virt();
562 static int svm_hardware_enable(void)
565 struct svm_cpu_data *sd;
567 struct desc_struct *gdt;
568 int me = raw_smp_processor_id();
570 rdmsrl(MSR_EFER, efer);
571 if (efer & EFER_SVME)
575 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
578 sd = per_cpu_ptr(&svm_data, me);
579 sd->asid_generation = 1;
580 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
581 sd->next_asid = sd->max_asid + 1;
582 sd->min_asid = max_sev_asid + 1;
584 gdt = get_current_gdt_rw();
585 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
587 wrmsrl(MSR_EFER, efer | EFER_SVME);
589 wrmsrl(MSR_VM_HSAVE_PA, sd->save_area_pa);
591 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
593 * Set the default value, even if we don't use TSC scaling
594 * to avoid having stale value in the msr
596 __svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
603 * Note that it is possible to have a system with mixed processor
604 * revisions and therefore different OSVW bits. If bits are not the same
605 * on different processors then choose the worst case (i.e. if erratum
606 * is present on one processor and not on another then assume that the
607 * erratum is present everywhere).
609 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
610 uint64_t len, status = 0;
613 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
615 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
619 osvw_status = osvw_len = 0;
623 osvw_status |= status;
624 osvw_status &= (1ULL << osvw_len) - 1;
627 osvw_status = osvw_len = 0;
629 svm_init_erratum_383();
631 amd_pmu_enable_virt();
636 static void svm_cpu_uninit(int cpu)
638 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
643 kfree(sd->sev_vmcbs);
644 __free_page(sd->save_area);
645 sd->save_area_pa = 0;
646 sd->save_area = NULL;
649 static int svm_cpu_init(int cpu)
651 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
654 memset(sd, 0, sizeof(struct svm_cpu_data));
655 sd->save_area = alloc_page(GFP_KERNEL | __GFP_ZERO);
659 ret = sev_cpu_init(sd);
663 sd->save_area_pa = __sme_page_pa(sd->save_area);
667 __free_page(sd->save_area);
668 sd->save_area = NULL;
673 static int direct_access_msr_slot(u32 msr)
677 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
678 if (direct_access_msrs[i].index == msr)
684 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
687 struct vcpu_svm *svm = to_svm(vcpu);
688 int slot = direct_access_msr_slot(msr);
693 /* Set the shadow bitmaps to the desired intercept states */
695 set_bit(slot, svm->shadow_msr_intercept.read);
697 clear_bit(slot, svm->shadow_msr_intercept.read);
700 set_bit(slot, svm->shadow_msr_intercept.write);
702 clear_bit(slot, svm->shadow_msr_intercept.write);
705 static bool valid_msr_intercept(u32 index)
707 return direct_access_msr_slot(index) != -ENOENT;
710 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
718 * For non-nested case:
719 * If the L01 MSR bitmap does not intercept the MSR, then we need to
723 * If the L02 MSR bitmap does not intercept the MSR, then we need to
726 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
729 offset = svm_msrpm_offset(msr);
730 bit_write = 2 * (msr & 0x0f) + 1;
733 BUG_ON(offset == MSR_INVALID);
735 return !!test_bit(bit_write, &tmp);
738 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
739 u32 msr, int read, int write)
741 struct vcpu_svm *svm = to_svm(vcpu);
742 u8 bit_read, bit_write;
747 * If this warning triggers extend the direct_access_msrs list at the
748 * beginning of the file
750 WARN_ON(!valid_msr_intercept(msr));
752 /* Enforce non allowed MSRs to trap */
753 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
756 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
759 offset = svm_msrpm_offset(msr);
760 bit_read = 2 * (msr & 0x0f);
761 bit_write = 2 * (msr & 0x0f) + 1;
764 BUG_ON(offset == MSR_INVALID);
766 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
767 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
771 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
772 svm->nested.force_msr_bitmap_recalc = true;
775 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
778 set_shadow_msr_intercept(vcpu, msr, read, write);
779 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
782 u32 *svm_vcpu_alloc_msrpm(void)
784 unsigned int order = get_order(MSRPM_SIZE);
785 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
791 msrpm = page_address(pages);
792 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
797 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
801 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
802 if (!direct_access_msrs[i].always)
804 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
808 void svm_set_x2apic_msr_interception(struct vcpu_svm *svm, bool intercept)
812 if (intercept == svm->x2avic_msrs_intercepted)
815 if (avic_mode != AVIC_MODE_X2 ||
816 !apic_x2apic_mode(svm->vcpu.arch.apic))
819 for (i = 0; i < MAX_DIRECT_ACCESS_MSRS; i++) {
820 int index = direct_access_msrs[i].index;
822 if ((index < APIC_BASE_MSR) ||
823 (index > APIC_BASE_MSR + 0xff))
825 set_msr_interception(&svm->vcpu, svm->msrpm, index,
826 !intercept, !intercept);
829 svm->x2avic_msrs_intercepted = intercept;
832 void svm_vcpu_free_msrpm(u32 *msrpm)
834 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
837 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
839 struct vcpu_svm *svm = to_svm(vcpu);
843 * Set intercept permissions for all direct access MSRs again. They
844 * will automatically get filtered through the MSR filter, so we are
845 * back in sync after this.
847 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
848 u32 msr = direct_access_msrs[i].index;
849 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
850 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
852 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
856 static void add_msr_offset(u32 offset)
860 for (i = 0; i < MSRPM_OFFSETS; ++i) {
862 /* Offset already in list? */
863 if (msrpm_offsets[i] == offset)
866 /* Slot used by another offset? */
867 if (msrpm_offsets[i] != MSR_INVALID)
870 /* Add offset to list */
871 msrpm_offsets[i] = offset;
877 * If this BUG triggers the msrpm_offsets table has an overflow. Just
878 * increase MSRPM_OFFSETS in this case.
883 static void init_msrpm_offsets(void)
887 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
889 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
892 offset = svm_msrpm_offset(direct_access_msrs[i].index);
893 BUG_ON(offset == MSR_INVALID);
895 add_msr_offset(offset);
899 void svm_copy_lbrs(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
901 to_vmcb->save.dbgctl = from_vmcb->save.dbgctl;
902 to_vmcb->save.br_from = from_vmcb->save.br_from;
903 to_vmcb->save.br_to = from_vmcb->save.br_to;
904 to_vmcb->save.last_excp_from = from_vmcb->save.last_excp_from;
905 to_vmcb->save.last_excp_to = from_vmcb->save.last_excp_to;
907 vmcb_mark_dirty(to_vmcb, VMCB_LBR);
910 static void svm_enable_lbrv(struct kvm_vcpu *vcpu)
912 struct vcpu_svm *svm = to_svm(vcpu);
914 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
915 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
916 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
917 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
918 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
920 /* Move the LBR msrs to the vmcb02 so that the guest can see them. */
921 if (is_guest_mode(vcpu))
922 svm_copy_lbrs(svm->vmcb, svm->vmcb01.ptr);
925 static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
927 struct vcpu_svm *svm = to_svm(vcpu);
929 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
930 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
931 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
932 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
933 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
936 * Move the LBR msrs back to the vmcb01 to avoid copying them
937 * on nested guest entries.
939 if (is_guest_mode(vcpu))
940 svm_copy_lbrs(svm->vmcb01.ptr, svm->vmcb);
943 static int svm_get_lbr_msr(struct vcpu_svm *svm, u32 index)
946 * If the LBR virtualization is disabled, the LBR msrs are always
947 * kept in the vmcb01 to avoid copying them on nested guest entries.
949 * If nested, and the LBR virtualization is enabled/disabled, the msrs
950 * are moved between the vmcb01 and vmcb02 as needed.
953 (svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK) ?
954 svm->vmcb : svm->vmcb01.ptr;
957 case MSR_IA32_DEBUGCTLMSR:
958 return vmcb->save.dbgctl;
959 case MSR_IA32_LASTBRANCHFROMIP:
960 return vmcb->save.br_from;
961 case MSR_IA32_LASTBRANCHTOIP:
962 return vmcb->save.br_to;
963 case MSR_IA32_LASTINTFROMIP:
964 return vmcb->save.last_excp_from;
965 case MSR_IA32_LASTINTTOIP:
966 return vmcb->save.last_excp_to;
968 KVM_BUG(false, svm->vcpu.kvm,
969 "%s: Unknown MSR 0x%x", __func__, index);
974 void svm_update_lbrv(struct kvm_vcpu *vcpu)
976 struct vcpu_svm *svm = to_svm(vcpu);
978 bool enable_lbrv = svm_get_lbr_msr(svm, MSR_IA32_DEBUGCTLMSR) &
981 bool current_enable_lbrv = !!(svm->vmcb->control.virt_ext &
982 LBR_CTL_ENABLE_MASK);
984 if (unlikely(is_guest_mode(vcpu) && svm->lbrv_enabled))
985 if (unlikely(svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK))
988 if (enable_lbrv == current_enable_lbrv)
992 svm_enable_lbrv(vcpu);
994 svm_disable_lbrv(vcpu);
997 void disable_nmi_singlestep(struct vcpu_svm *svm)
999 svm->nmi_singlestep = false;
1001 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1002 /* Clear our flags if they were not set by the guest */
1003 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1004 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1005 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1006 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1010 static void grow_ple_window(struct kvm_vcpu *vcpu)
1012 struct vcpu_svm *svm = to_svm(vcpu);
1013 struct vmcb_control_area *control = &svm->vmcb->control;
1014 int old = control->pause_filter_count;
1016 if (kvm_pause_in_guest(vcpu->kvm))
1019 control->pause_filter_count = __grow_ple_window(old,
1021 pause_filter_count_grow,
1022 pause_filter_count_max);
1024 if (control->pause_filter_count != old) {
1025 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1026 trace_kvm_ple_window_update(vcpu->vcpu_id,
1027 control->pause_filter_count, old);
1031 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1033 struct vcpu_svm *svm = to_svm(vcpu);
1034 struct vmcb_control_area *control = &svm->vmcb->control;
1035 int old = control->pause_filter_count;
1037 if (kvm_pause_in_guest(vcpu->kvm))
1040 control->pause_filter_count =
1041 __shrink_ple_window(old,
1043 pause_filter_count_shrink,
1044 pause_filter_count);
1045 if (control->pause_filter_count != old) {
1046 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1047 trace_kvm_ple_window_update(vcpu->vcpu_id,
1048 control->pause_filter_count, old);
1052 static void svm_hardware_unsetup(void)
1056 sev_hardware_unsetup();
1058 for_each_possible_cpu(cpu)
1059 svm_cpu_uninit(cpu);
1061 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
1062 get_order(IOPM_SIZE));
1066 static void init_seg(struct vmcb_seg *seg)
1069 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1070 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1071 seg->limit = 0xffff;
1075 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1078 seg->attrib = SVM_SELECTOR_P_MASK | type;
1079 seg->limit = 0xffff;
1083 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1085 struct vcpu_svm *svm = to_svm(vcpu);
1087 return svm->nested.ctl.tsc_offset;
1090 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1092 struct vcpu_svm *svm = to_svm(vcpu);
1094 return svm->tsc_ratio_msr;
1097 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1099 struct vcpu_svm *svm = to_svm(vcpu);
1101 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1102 svm->vmcb->control.tsc_offset = offset;
1103 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1106 static void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu, u64 multiplier)
1108 __svm_write_tsc_multiplier(multiplier);
1112 /* Evaluate instruction intercepts that depend on guest CPUID features. */
1113 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1114 struct vcpu_svm *svm)
1117 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1118 * roots, or if INVPCID is disabled in the guest to inject #UD.
1120 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1122 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1123 svm_set_intercept(svm, INTERCEPT_INVPCID);
1125 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1128 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1129 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1130 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1132 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1136 static inline void init_vmcb_after_set_cpuid(struct kvm_vcpu *vcpu)
1138 struct vcpu_svm *svm = to_svm(vcpu);
1140 if (guest_cpuid_is_intel(vcpu)) {
1142 * We must intercept SYSENTER_EIP and SYSENTER_ESP
1143 * accesses because the processor only stores 32 bits.
1144 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
1146 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1147 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1148 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1150 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
1151 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
1153 svm->v_vmload_vmsave_enabled = false;
1156 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1157 * in VMCB and clear intercepts to avoid #VMEXIT.
1160 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
1161 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
1162 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1164 /* No need to intercept these MSRs */
1165 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
1166 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
1170 static void init_vmcb(struct kvm_vcpu *vcpu)
1172 struct vcpu_svm *svm = to_svm(vcpu);
1173 struct vmcb *vmcb = svm->vmcb01.ptr;
1174 struct vmcb_control_area *control = &vmcb->control;
1175 struct vmcb_save_area *save = &vmcb->save;
1177 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1178 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1179 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1180 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1181 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1182 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1183 if (!kvm_vcpu_apicv_active(vcpu))
1184 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1186 set_dr_intercepts(svm);
1188 set_exception_intercept(svm, PF_VECTOR);
1189 set_exception_intercept(svm, UD_VECTOR);
1190 set_exception_intercept(svm, MC_VECTOR);
1191 set_exception_intercept(svm, AC_VECTOR);
1192 set_exception_intercept(svm, DB_VECTOR);
1194 * Guest access to VMware backdoor ports could legitimately
1195 * trigger #GP because of TSS I/O permission bitmap.
1196 * We intercept those #GP and allow access to them anyway
1197 * as VMware does. Don't intercept #GP for SEV guests as KVM can't
1198 * decrypt guest memory to decode the faulting instruction.
1200 if (enable_vmware_backdoor && !sev_guest(vcpu->kvm))
1201 set_exception_intercept(svm, GP_VECTOR);
1203 svm_set_intercept(svm, INTERCEPT_INTR);
1204 svm_set_intercept(svm, INTERCEPT_NMI);
1207 svm_set_intercept(svm, INTERCEPT_SMI);
1209 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1210 svm_set_intercept(svm, INTERCEPT_RDPMC);
1211 svm_set_intercept(svm, INTERCEPT_CPUID);
1212 svm_set_intercept(svm, INTERCEPT_INVD);
1213 svm_set_intercept(svm, INTERCEPT_INVLPG);
1214 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1215 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1216 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1217 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1218 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1219 svm_set_intercept(svm, INTERCEPT_VMRUN);
1220 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1221 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1222 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1223 svm_set_intercept(svm, INTERCEPT_STGI);
1224 svm_set_intercept(svm, INTERCEPT_CLGI);
1225 svm_set_intercept(svm, INTERCEPT_SKINIT);
1226 svm_set_intercept(svm, INTERCEPT_WBINVD);
1227 svm_set_intercept(svm, INTERCEPT_XSETBV);
1228 svm_set_intercept(svm, INTERCEPT_RDPRU);
1229 svm_set_intercept(svm, INTERCEPT_RSM);
1231 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1232 svm_set_intercept(svm, INTERCEPT_MONITOR);
1233 svm_set_intercept(svm, INTERCEPT_MWAIT);
1236 if (!kvm_hlt_in_guest(vcpu->kvm))
1237 svm_set_intercept(svm, INTERCEPT_HLT);
1239 control->iopm_base_pa = __sme_set(iopm_base);
1240 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1241 control->int_ctl = V_INTR_MASKING_MASK;
1243 init_seg(&save->es);
1244 init_seg(&save->ss);
1245 init_seg(&save->ds);
1246 init_seg(&save->fs);
1247 init_seg(&save->gs);
1249 save->cs.selector = 0xf000;
1250 save->cs.base = 0xffff0000;
1251 /* Executable/Readable Code Segment */
1252 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1253 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1254 save->cs.limit = 0xffff;
1256 save->gdtr.base = 0;
1257 save->gdtr.limit = 0xffff;
1258 save->idtr.base = 0;
1259 save->idtr.limit = 0xffff;
1261 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1262 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1265 /* Setup VMCB for Nested Paging */
1266 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1267 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1268 clr_exception_intercept(svm, PF_VECTOR);
1269 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1270 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1271 save->g_pat = vcpu->arch.pat;
1274 svm->current_vmcb->asid_generation = 0;
1277 svm->nested.vmcb12_gpa = INVALID_GPA;
1278 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1280 if (!kvm_pause_in_guest(vcpu->kvm)) {
1281 control->pause_filter_count = pause_filter_count;
1282 if (pause_filter_thresh)
1283 control->pause_filter_thresh = pause_filter_thresh;
1284 svm_set_intercept(svm, INTERCEPT_PAUSE);
1286 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1289 svm_recalc_instruction_intercepts(vcpu, svm);
1292 * If the host supports V_SPEC_CTRL then disable the interception
1293 * of MSR_IA32_SPEC_CTRL.
1295 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1296 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1298 if (kvm_vcpu_apicv_active(vcpu))
1299 avic_init_vmcb(svm, vmcb);
1302 svm_clr_intercept(svm, INTERCEPT_STGI);
1303 svm_clr_intercept(svm, INTERCEPT_CLGI);
1304 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1307 if (sev_guest(vcpu->kvm))
1310 svm_hv_init_vmcb(vmcb);
1311 init_vmcb_after_set_cpuid(vcpu);
1313 vmcb_mark_all_dirty(vmcb);
1318 static void __svm_vcpu_reset(struct kvm_vcpu *vcpu)
1320 struct vcpu_svm *svm = to_svm(vcpu);
1322 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1324 svm_init_osvw(vcpu);
1325 vcpu->arch.microcode_version = 0x01000065;
1326 svm->tsc_ratio_msr = kvm_caps.default_tsc_scaling_ratio;
1328 if (sev_es_guest(vcpu->kvm))
1329 sev_es_vcpu_reset(svm);
1332 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1334 struct vcpu_svm *svm = to_svm(vcpu);
1337 svm->virt_spec_ctrl = 0;
1342 __svm_vcpu_reset(vcpu);
1345 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1347 svm->current_vmcb = target_vmcb;
1348 svm->vmcb = target_vmcb->ptr;
1351 static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1353 struct vcpu_svm *svm;
1354 struct page *vmcb01_page;
1355 struct page *vmsa_page = NULL;
1358 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1362 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1366 if (sev_es_guest(vcpu->kvm)) {
1368 * SEV-ES guests require a separate VMSA page used to contain
1369 * the encrypted register state of the guest.
1371 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1373 goto error_free_vmcb_page;
1376 * SEV-ES guests maintain an encrypted version of their FPU
1377 * state which is restored and saved on VMRUN and VMEXIT.
1378 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
1379 * do xsave/xrstor on it.
1381 fpstate_set_confidential(&vcpu->arch.guest_fpu);
1384 err = avic_init_vcpu(svm);
1386 goto error_free_vmsa_page;
1388 svm->msrpm = svm_vcpu_alloc_msrpm();
1391 goto error_free_vmsa_page;
1394 svm->x2avic_msrs_intercepted = true;
1396 svm->vmcb01.ptr = page_address(vmcb01_page);
1397 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1398 svm_switch_vmcb(svm, &svm->vmcb01);
1401 svm->sev_es.vmsa = page_address(vmsa_page);
1403 svm->guest_state_loaded = false;
1407 error_free_vmsa_page:
1409 __free_page(vmsa_page);
1410 error_free_vmcb_page:
1411 __free_page(vmcb01_page);
1416 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1420 for_each_online_cpu(i)
1421 cmpxchg(per_cpu_ptr(&svm_data.current_vmcb, i), vmcb, NULL);
1424 static void svm_vcpu_free(struct kvm_vcpu *vcpu)
1426 struct vcpu_svm *svm = to_svm(vcpu);
1429 * The vmcb page can be recycled, causing a false negative in
1430 * svm_vcpu_load(). So, ensure that no logical CPU has this
1431 * vmcb page recorded as its current vmcb.
1433 svm_clear_current_vmcb(svm->vmcb);
1435 svm_leave_nested(vcpu);
1436 svm_free_nested(svm);
1438 sev_free_vcpu(vcpu);
1440 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1441 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1444 static void svm_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1446 struct vcpu_svm *svm = to_svm(vcpu);
1447 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
1449 if (sev_es_guest(vcpu->kvm))
1450 sev_es_unmap_ghcb(svm);
1452 if (svm->guest_state_loaded)
1456 * Save additional host state that will be restored on VMEXIT (sev-es)
1457 * or subsequent vmload of host save area.
1459 vmsave(sd->save_area_pa);
1460 if (sev_es_guest(vcpu->kvm)) {
1461 struct sev_es_save_area *hostsa;
1462 hostsa = (struct sev_es_save_area *)(page_address(sd->save_area) + 0x400);
1464 sev_es_prepare_switch_to_guest(hostsa);
1468 __svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1470 if (likely(tsc_aux_uret_slot >= 0))
1471 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1473 svm->guest_state_loaded = true;
1476 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1478 to_svm(vcpu)->guest_state_loaded = false;
1481 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1483 struct vcpu_svm *svm = to_svm(vcpu);
1484 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
1486 if (sd->current_vmcb != svm->vmcb) {
1487 sd->current_vmcb = svm->vmcb;
1488 indirect_branch_prediction_barrier();
1490 if (kvm_vcpu_apicv_active(vcpu))
1491 avic_vcpu_load(vcpu, cpu);
1494 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1496 if (kvm_vcpu_apicv_active(vcpu))
1497 avic_vcpu_put(vcpu);
1499 svm_prepare_host_switch(vcpu);
1501 ++vcpu->stat.host_state_reload;
1504 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1506 struct vcpu_svm *svm = to_svm(vcpu);
1507 unsigned long rflags = svm->vmcb->save.rflags;
1509 if (svm->nmi_singlestep) {
1510 /* Hide our flags if they were not set by the guest */
1511 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1512 rflags &= ~X86_EFLAGS_TF;
1513 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1514 rflags &= ~X86_EFLAGS_RF;
1519 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1521 if (to_svm(vcpu)->nmi_singlestep)
1522 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1525 * Any change of EFLAGS.VM is accompanied by a reload of SS
1526 * (caused by either a task switch or an inter-privilege IRET),
1527 * so we do not need to update the CPL here.
1529 to_svm(vcpu)->vmcb->save.rflags = rflags;
1532 static bool svm_get_if_flag(struct kvm_vcpu *vcpu)
1534 struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1536 return sev_es_guest(vcpu->kvm)
1537 ? vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK
1538 : kvm_get_rflags(vcpu) & X86_EFLAGS_IF;
1541 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1543 kvm_register_mark_available(vcpu, reg);
1546 case VCPU_EXREG_PDPTR:
1548 * When !npt_enabled, mmu->pdptrs[] is already available since
1549 * it is always updated per SDM when moving to CRs.
1552 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
1555 KVM_BUG_ON(1, vcpu->kvm);
1559 static void svm_set_vintr(struct vcpu_svm *svm)
1561 struct vmcb_control_area *control;
1564 * The following fields are ignored when AVIC is enabled
1566 WARN_ON(kvm_vcpu_apicv_activated(&svm->vcpu));
1568 svm_set_intercept(svm, INTERCEPT_VINTR);
1571 * This is just a dummy VINTR to actually cause a vmexit to happen.
1572 * Actual injection of virtual interrupts happens through EVENTINJ.
1574 control = &svm->vmcb->control;
1575 control->int_vector = 0x0;
1576 control->int_ctl &= ~V_INTR_PRIO_MASK;
1577 control->int_ctl |= V_IRQ_MASK |
1578 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1579 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1582 static void svm_clear_vintr(struct vcpu_svm *svm)
1584 svm_clr_intercept(svm, INTERCEPT_VINTR);
1586 /* Drop int_ctl fields related to VINTR injection. */
1587 svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1588 if (is_guest_mode(&svm->vcpu)) {
1589 svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1591 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1592 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1594 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1595 V_IRQ_INJECTION_BITS_MASK;
1597 svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1600 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1603 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1605 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1606 struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1609 case VCPU_SREG_CS: return &save->cs;
1610 case VCPU_SREG_DS: return &save->ds;
1611 case VCPU_SREG_ES: return &save->es;
1612 case VCPU_SREG_FS: return &save01->fs;
1613 case VCPU_SREG_GS: return &save01->gs;
1614 case VCPU_SREG_SS: return &save->ss;
1615 case VCPU_SREG_TR: return &save01->tr;
1616 case VCPU_SREG_LDTR: return &save01->ldtr;
1622 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1624 struct vmcb_seg *s = svm_seg(vcpu, seg);
1629 static void svm_get_segment(struct kvm_vcpu *vcpu,
1630 struct kvm_segment *var, int seg)
1632 struct vmcb_seg *s = svm_seg(vcpu, seg);
1634 var->base = s->base;
1635 var->limit = s->limit;
1636 var->selector = s->selector;
1637 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1638 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1639 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1640 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1641 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1642 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1643 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1646 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1647 * However, the SVM spec states that the G bit is not observed by the
1648 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1649 * So let's synthesize a legal G bit for all segments, this helps
1650 * running KVM nested. It also helps cross-vendor migration, because
1651 * Intel's vmentry has a check on the 'G' bit.
1653 var->g = s->limit > 0xfffff;
1656 * AMD's VMCB does not have an explicit unusable field, so emulate it
1657 * for cross vendor migration purposes by "not present"
1659 var->unusable = !var->present;
1664 * Work around a bug where the busy flag in the tr selector
1674 * The accessed bit must always be set in the segment
1675 * descriptor cache, although it can be cleared in the
1676 * descriptor, the cached bit always remains at 1. Since
1677 * Intel has a check on this, set it here to support
1678 * cross-vendor migration.
1685 * On AMD CPUs sometimes the DB bit in the segment
1686 * descriptor is left as 1, although the whole segment has
1687 * been made unusable. Clear it here to pass an Intel VMX
1688 * entry check when cross vendor migrating.
1692 /* This is symmetric with svm_set_segment() */
1693 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1698 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1700 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1705 static void svm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1707 struct kvm_segment cs;
1709 svm_get_segment(vcpu, &cs, VCPU_SREG_CS);
1714 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1716 struct vcpu_svm *svm = to_svm(vcpu);
1718 dt->size = svm->vmcb->save.idtr.limit;
1719 dt->address = svm->vmcb->save.idtr.base;
1722 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1724 struct vcpu_svm *svm = to_svm(vcpu);
1726 svm->vmcb->save.idtr.limit = dt->size;
1727 svm->vmcb->save.idtr.base = dt->address ;
1728 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1731 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1733 struct vcpu_svm *svm = to_svm(vcpu);
1735 dt->size = svm->vmcb->save.gdtr.limit;
1736 dt->address = svm->vmcb->save.gdtr.base;
1739 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1741 struct vcpu_svm *svm = to_svm(vcpu);
1743 svm->vmcb->save.gdtr.limit = dt->size;
1744 svm->vmcb->save.gdtr.base = dt->address ;
1745 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1748 static void sev_post_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1750 struct vcpu_svm *svm = to_svm(vcpu);
1753 * For guests that don't set guest_state_protected, the cr3 update is
1754 * handled via kvm_mmu_load() while entering the guest. For guests
1755 * that do (SEV-ES/SEV-SNP), the cr3 update needs to be written to
1756 * VMCB save area now, since the save area will become the initial
1757 * contents of the VMSA, and future VMCB save area updates won't be
1760 if (sev_es_guest(vcpu->kvm)) {
1761 svm->vmcb->save.cr3 = cr3;
1762 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1766 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1768 struct vcpu_svm *svm = to_svm(vcpu);
1770 bool old_paging = is_paging(vcpu);
1772 #ifdef CONFIG_X86_64
1773 if (vcpu->arch.efer & EFER_LME && !vcpu->arch.guest_state_protected) {
1774 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1775 vcpu->arch.efer |= EFER_LMA;
1776 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1779 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1780 vcpu->arch.efer &= ~EFER_LMA;
1781 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1785 vcpu->arch.cr0 = cr0;
1788 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1789 if (old_paging != is_paging(vcpu))
1790 svm_set_cr4(vcpu, kvm_read_cr4(vcpu));
1794 * re-enable caching here because the QEMU bios
1795 * does not do it - this results in some delay at
1798 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1799 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1801 svm->vmcb->save.cr0 = hcr0;
1802 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1805 * SEV-ES guests must always keep the CR intercepts cleared. CR
1806 * tracking is done using the CR write traps.
1808 if (sev_es_guest(vcpu->kvm))
1812 /* Selective CR0 write remains on. */
1813 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1814 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1816 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1817 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1821 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1826 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1828 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1829 unsigned long old_cr4 = vcpu->arch.cr4;
1831 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1832 svm_flush_tlb_current(vcpu);
1834 vcpu->arch.cr4 = cr4;
1838 if (!is_paging(vcpu))
1839 cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
1841 cr4 |= host_cr4_mce;
1842 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1843 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1845 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1846 kvm_update_cpuid_runtime(vcpu);
1849 static void svm_set_segment(struct kvm_vcpu *vcpu,
1850 struct kvm_segment *var, int seg)
1852 struct vcpu_svm *svm = to_svm(vcpu);
1853 struct vmcb_seg *s = svm_seg(vcpu, seg);
1855 s->base = var->base;
1856 s->limit = var->limit;
1857 s->selector = var->selector;
1858 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1859 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1860 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1861 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1862 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1863 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1864 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1865 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1868 * This is always accurate, except if SYSRET returned to a segment
1869 * with SS.DPL != 3. Intel does not have this quirk, and always
1870 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1871 * would entail passing the CPL to userspace and back.
1873 if (seg == VCPU_SREG_SS)
1874 /* This is symmetric with svm_get_segment() */
1875 svm->vmcb->save.cpl = (var->dpl & 3);
1877 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1880 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1882 struct vcpu_svm *svm = to_svm(vcpu);
1884 clr_exception_intercept(svm, BP_VECTOR);
1886 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1887 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1888 set_exception_intercept(svm, BP_VECTOR);
1892 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1894 if (sd->next_asid > sd->max_asid) {
1895 ++sd->asid_generation;
1896 sd->next_asid = sd->min_asid;
1897 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1898 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
1901 svm->current_vmcb->asid_generation = sd->asid_generation;
1902 svm->asid = sd->next_asid++;
1905 static void svm_set_dr6(struct vcpu_svm *svm, unsigned long value)
1907 struct vmcb *vmcb = svm->vmcb;
1909 if (svm->vcpu.arch.guest_state_protected)
1912 if (unlikely(value != vmcb->save.dr6)) {
1913 vmcb->save.dr6 = value;
1914 vmcb_mark_dirty(vmcb, VMCB_DR);
1918 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1920 struct vcpu_svm *svm = to_svm(vcpu);
1922 if (vcpu->arch.guest_state_protected)
1925 get_debugreg(vcpu->arch.db[0], 0);
1926 get_debugreg(vcpu->arch.db[1], 1);
1927 get_debugreg(vcpu->arch.db[2], 2);
1928 get_debugreg(vcpu->arch.db[3], 3);
1930 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
1931 * because db_interception might need it. We can do it before vmentry.
1933 vcpu->arch.dr6 = svm->vmcb->save.dr6;
1934 vcpu->arch.dr7 = svm->vmcb->save.dr7;
1935 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1936 set_dr_intercepts(svm);
1939 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1941 struct vcpu_svm *svm = to_svm(vcpu);
1943 if (vcpu->arch.guest_state_protected)
1946 svm->vmcb->save.dr7 = value;
1947 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
1950 static int pf_interception(struct kvm_vcpu *vcpu)
1952 struct vcpu_svm *svm = to_svm(vcpu);
1954 u64 fault_address = svm->vmcb->control.exit_info_2;
1955 u64 error_code = svm->vmcb->control.exit_info_1;
1957 return kvm_handle_page_fault(vcpu, error_code, fault_address,
1958 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1959 svm->vmcb->control.insn_bytes : NULL,
1960 svm->vmcb->control.insn_len);
1963 static int npf_interception(struct kvm_vcpu *vcpu)
1965 struct vcpu_svm *svm = to_svm(vcpu);
1967 u64 fault_address = svm->vmcb->control.exit_info_2;
1968 u64 error_code = svm->vmcb->control.exit_info_1;
1970 trace_kvm_page_fault(vcpu, fault_address, error_code);
1971 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
1972 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
1973 svm->vmcb->control.insn_bytes : NULL,
1974 svm->vmcb->control.insn_len);
1977 static int db_interception(struct kvm_vcpu *vcpu)
1979 struct kvm_run *kvm_run = vcpu->run;
1980 struct vcpu_svm *svm = to_svm(vcpu);
1982 if (!(vcpu->guest_debug &
1983 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1984 !svm->nmi_singlestep) {
1985 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
1986 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
1990 if (svm->nmi_singlestep) {
1991 disable_nmi_singlestep(svm);
1992 /* Make sure we check for pending NMIs upon entry */
1993 kvm_make_request(KVM_REQ_EVENT, vcpu);
1996 if (vcpu->guest_debug &
1997 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
1998 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1999 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
2000 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
2001 kvm_run->debug.arch.pc =
2002 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2003 kvm_run->debug.arch.exception = DB_VECTOR;
2010 static int bp_interception(struct kvm_vcpu *vcpu)
2012 struct vcpu_svm *svm = to_svm(vcpu);
2013 struct kvm_run *kvm_run = vcpu->run;
2015 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2016 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2017 kvm_run->debug.arch.exception = BP_VECTOR;
2021 static int ud_interception(struct kvm_vcpu *vcpu)
2023 return handle_ud(vcpu);
2026 static int ac_interception(struct kvm_vcpu *vcpu)
2028 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
2032 static bool is_erratum_383(void)
2037 if (!erratum_383_found)
2040 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2044 /* Bit 62 may or may not be set for this mce */
2045 value &= ~(1ULL << 62);
2047 if (value != 0xb600000000010015ULL)
2050 /* Clear MCi_STATUS registers */
2051 for (i = 0; i < 6; ++i)
2052 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2054 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2058 value &= ~(1ULL << 2);
2059 low = lower_32_bits(value);
2060 high = upper_32_bits(value);
2062 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2065 /* Flush tlb to evict multi-match entries */
2071 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2073 if (is_erratum_383()) {
2075 * Erratum 383 triggered. Guest state is corrupt so kill the
2078 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2080 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2086 * On an #MC intercept the MCE handler is not called automatically in
2087 * the host. So do it by hand here.
2089 kvm_machine_check();
2092 static int mc_interception(struct kvm_vcpu *vcpu)
2097 static int shutdown_interception(struct kvm_vcpu *vcpu)
2099 struct kvm_run *kvm_run = vcpu->run;
2100 struct vcpu_svm *svm = to_svm(vcpu);
2103 * The VM save area has already been encrypted so it
2104 * cannot be reinitialized - just terminate.
2106 if (sev_es_guest(vcpu->kvm))
2110 * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put
2111 * the VMCB in a known good state. Unfortuately, KVM doesn't have
2112 * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking
2113 * userspace. At a platform view, INIT is acceptable behavior as
2114 * there exist bare metal platforms that automatically INIT the CPU
2115 * in response to shutdown.
2117 clear_page(svm->vmcb);
2118 kvm_vcpu_reset(vcpu, true);
2120 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2124 static int io_interception(struct kvm_vcpu *vcpu)
2126 struct vcpu_svm *svm = to_svm(vcpu);
2127 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2128 int size, in, string;
2131 ++vcpu->stat.io_exits;
2132 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2133 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2134 port = io_info >> 16;
2135 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2138 if (sev_es_guest(vcpu->kvm))
2139 return sev_es_string_io(svm, size, port, in);
2141 return kvm_emulate_instruction(vcpu, 0);
2144 svm->next_rip = svm->vmcb->control.exit_info_2;
2146 return kvm_fast_pio(vcpu, size, port, in);
2149 static int nmi_interception(struct kvm_vcpu *vcpu)
2154 static int smi_interception(struct kvm_vcpu *vcpu)
2159 static int intr_interception(struct kvm_vcpu *vcpu)
2161 ++vcpu->stat.irq_exits;
2165 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2167 struct vcpu_svm *svm = to_svm(vcpu);
2168 struct vmcb *vmcb12;
2169 struct kvm_host_map map;
2172 if (nested_svm_check_permissions(vcpu))
2175 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2178 kvm_inject_gp(vcpu, 0);
2184 ret = kvm_skip_emulated_instruction(vcpu);
2187 svm_copy_vmloadsave_state(svm->vmcb, vmcb12);
2188 svm->sysenter_eip_hi = 0;
2189 svm->sysenter_esp_hi = 0;
2191 svm_copy_vmloadsave_state(vmcb12, svm->vmcb);
2194 kvm_vcpu_unmap(vcpu, &map, true);
2199 static int vmload_interception(struct kvm_vcpu *vcpu)
2201 return vmload_vmsave_interception(vcpu, true);
2204 static int vmsave_interception(struct kvm_vcpu *vcpu)
2206 return vmload_vmsave_interception(vcpu, false);
2209 static int vmrun_interception(struct kvm_vcpu *vcpu)
2211 if (nested_svm_check_permissions(vcpu))
2214 return nested_svm_vmrun(vcpu);
2224 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
2225 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2227 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2229 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2230 return NONE_SVM_INSTR;
2232 switch (ctxt->modrm) {
2233 case 0xd8: /* VMRUN */
2234 return SVM_INSTR_VMRUN;
2235 case 0xda: /* VMLOAD */
2236 return SVM_INSTR_VMLOAD;
2237 case 0xdb: /* VMSAVE */
2238 return SVM_INSTR_VMSAVE;
2243 return NONE_SVM_INSTR;
2246 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2248 const int guest_mode_exit_codes[] = {
2249 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2250 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2251 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2253 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2254 [SVM_INSTR_VMRUN] = vmrun_interception,
2255 [SVM_INSTR_VMLOAD] = vmload_interception,
2256 [SVM_INSTR_VMSAVE] = vmsave_interception,
2258 struct vcpu_svm *svm = to_svm(vcpu);
2261 if (is_guest_mode(vcpu)) {
2262 /* Returns '1' or -errno on failure, '0' on success. */
2263 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2268 return svm_instr_handlers[opcode](vcpu);
2272 * #GP handling code. Note that #GP can be triggered under the following two
2274 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2275 * some AMD CPUs when EAX of these instructions are in the reserved memory
2276 * regions (e.g. SMM memory on host).
2277 * 2) VMware backdoor
2279 static int gp_interception(struct kvm_vcpu *vcpu)
2281 struct vcpu_svm *svm = to_svm(vcpu);
2282 u32 error_code = svm->vmcb->control.exit_info_1;
2285 /* Both #GP cases have zero error_code */
2289 /* Decode the instruction for usage later */
2290 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2293 opcode = svm_instr_opcode(vcpu);
2295 if (opcode == NONE_SVM_INSTR) {
2296 if (!enable_vmware_backdoor)
2300 * VMware backdoor emulation on #GP interception only handles
2301 * IN{S}, OUT{S}, and RDPMC.
2303 if (!is_guest_mode(vcpu))
2304 return kvm_emulate_instruction(vcpu,
2305 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2307 /* All SVM instructions expect page aligned RAX */
2308 if (svm->vmcb->save.rax & ~PAGE_MASK)
2311 return emulate_svm_instr(vcpu, opcode);
2315 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2319 void svm_set_gif(struct vcpu_svm *svm, bool value)
2323 * If VGIF is enabled, the STGI intercept is only added to
2324 * detect the opening of the SMI/NMI window; remove it now.
2325 * Likewise, clear the VINTR intercept, we will set it
2326 * again while processing KVM_REQ_EVENT if needed.
2329 svm_clr_intercept(svm, INTERCEPT_STGI);
2330 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2331 svm_clear_vintr(svm);
2334 if (svm->vcpu.arch.smi_pending ||
2335 svm->vcpu.arch.nmi_pending ||
2336 kvm_cpu_has_injectable_intr(&svm->vcpu) ||
2337 kvm_apic_has_pending_init_or_sipi(&svm->vcpu))
2338 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2343 * After a CLGI no interrupts should come. But if vGIF is
2344 * in use, we still rely on the VINTR intercept (rather than
2345 * STGI) to detect an open interrupt window.
2348 svm_clear_vintr(svm);
2352 static int stgi_interception(struct kvm_vcpu *vcpu)
2356 if (nested_svm_check_permissions(vcpu))
2359 ret = kvm_skip_emulated_instruction(vcpu);
2360 svm_set_gif(to_svm(vcpu), true);
2364 static int clgi_interception(struct kvm_vcpu *vcpu)
2368 if (nested_svm_check_permissions(vcpu))
2371 ret = kvm_skip_emulated_instruction(vcpu);
2372 svm_set_gif(to_svm(vcpu), false);
2376 static int invlpga_interception(struct kvm_vcpu *vcpu)
2378 gva_t gva = kvm_rax_read(vcpu);
2379 u32 asid = kvm_rcx_read(vcpu);
2381 /* FIXME: Handle an address size prefix. */
2382 if (!is_long_mode(vcpu))
2385 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2387 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2388 kvm_mmu_invlpg(vcpu, gva);
2390 return kvm_skip_emulated_instruction(vcpu);
2393 static int skinit_interception(struct kvm_vcpu *vcpu)
2395 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2397 kvm_queue_exception(vcpu, UD_VECTOR);
2401 static int task_switch_interception(struct kvm_vcpu *vcpu)
2403 struct vcpu_svm *svm = to_svm(vcpu);
2406 int int_type = svm->vmcb->control.exit_int_info &
2407 SVM_EXITINTINFO_TYPE_MASK;
2408 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2410 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2412 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2413 bool has_error_code = false;
2416 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2418 if (svm->vmcb->control.exit_info_2 &
2419 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2420 reason = TASK_SWITCH_IRET;
2421 else if (svm->vmcb->control.exit_info_2 &
2422 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2423 reason = TASK_SWITCH_JMP;
2425 reason = TASK_SWITCH_GATE;
2427 reason = TASK_SWITCH_CALL;
2429 if (reason == TASK_SWITCH_GATE) {
2431 case SVM_EXITINTINFO_TYPE_NMI:
2432 vcpu->arch.nmi_injected = false;
2434 case SVM_EXITINTINFO_TYPE_EXEPT:
2435 if (svm->vmcb->control.exit_info_2 &
2436 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2437 has_error_code = true;
2439 (u32)svm->vmcb->control.exit_info_2;
2441 kvm_clear_exception_queue(vcpu);
2443 case SVM_EXITINTINFO_TYPE_INTR:
2444 case SVM_EXITINTINFO_TYPE_SOFT:
2445 kvm_clear_interrupt_queue(vcpu);
2452 if (reason != TASK_SWITCH_GATE ||
2453 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2454 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2455 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2456 if (!svm_skip_emulated_instruction(vcpu))
2460 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2463 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2464 has_error_code, error_code);
2467 static int iret_interception(struct kvm_vcpu *vcpu)
2469 struct vcpu_svm *svm = to_svm(vcpu);
2471 ++vcpu->stat.nmi_window_exits;
2472 vcpu->arch.hflags |= HF_IRET_MASK;
2473 if (!sev_es_guest(vcpu->kvm)) {
2474 svm_clr_intercept(svm, INTERCEPT_IRET);
2475 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2477 kvm_make_request(KVM_REQ_EVENT, vcpu);
2481 static int invlpg_interception(struct kvm_vcpu *vcpu)
2483 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2484 return kvm_emulate_instruction(vcpu, 0);
2486 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2487 return kvm_skip_emulated_instruction(vcpu);
2490 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2492 return kvm_emulate_instruction(vcpu, 0);
2495 static int rsm_interception(struct kvm_vcpu *vcpu)
2497 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2500 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2503 struct vcpu_svm *svm = to_svm(vcpu);
2504 unsigned long cr0 = vcpu->arch.cr0;
2507 if (!is_guest_mode(vcpu) ||
2508 (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2511 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2512 val &= ~SVM_CR0_SELECTIVE_MASK;
2515 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2516 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2522 #define CR_VALID (1ULL << 63)
2524 static int cr_interception(struct kvm_vcpu *vcpu)
2526 struct vcpu_svm *svm = to_svm(vcpu);
2531 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2532 return emulate_on_interception(vcpu);
2534 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2535 return emulate_on_interception(vcpu);
2537 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2538 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2539 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2541 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2544 if (cr >= 16) { /* mov to cr */
2546 val = kvm_register_read(vcpu, reg);
2547 trace_kvm_cr_write(cr, val);
2550 if (!check_selective_cr0_intercepted(vcpu, val))
2551 err = kvm_set_cr0(vcpu, val);
2557 err = kvm_set_cr3(vcpu, val);
2560 err = kvm_set_cr4(vcpu, val);
2563 err = kvm_set_cr8(vcpu, val);
2566 WARN(1, "unhandled write to CR%d", cr);
2567 kvm_queue_exception(vcpu, UD_VECTOR);
2570 } else { /* mov from cr */
2573 val = kvm_read_cr0(vcpu);
2576 val = vcpu->arch.cr2;
2579 val = kvm_read_cr3(vcpu);
2582 val = kvm_read_cr4(vcpu);
2585 val = kvm_get_cr8(vcpu);
2588 WARN(1, "unhandled read from CR%d", cr);
2589 kvm_queue_exception(vcpu, UD_VECTOR);
2592 kvm_register_write(vcpu, reg, val);
2593 trace_kvm_cr_read(cr, val);
2595 return kvm_complete_insn_gp(vcpu, err);
2598 static int cr_trap(struct kvm_vcpu *vcpu)
2600 struct vcpu_svm *svm = to_svm(vcpu);
2601 unsigned long old_value, new_value;
2605 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2607 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2610 old_value = kvm_read_cr0(vcpu);
2611 svm_set_cr0(vcpu, new_value);
2613 kvm_post_set_cr0(vcpu, old_value, new_value);
2616 old_value = kvm_read_cr4(vcpu);
2617 svm_set_cr4(vcpu, new_value);
2619 kvm_post_set_cr4(vcpu, old_value, new_value);
2622 ret = kvm_set_cr8(vcpu, new_value);
2625 WARN(1, "unhandled CR%d write trap", cr);
2626 kvm_queue_exception(vcpu, UD_VECTOR);
2630 return kvm_complete_insn_gp(vcpu, ret);
2633 static int dr_interception(struct kvm_vcpu *vcpu)
2635 struct vcpu_svm *svm = to_svm(vcpu);
2640 if (vcpu->guest_debug == 0) {
2642 * No more DR vmexits; force a reload of the debug registers
2643 * and reenter on this instruction. The next vmexit will
2644 * retrieve the full state of the debug registers.
2646 clr_dr_intercepts(svm);
2647 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2651 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2652 return emulate_on_interception(vcpu);
2654 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2655 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2656 if (dr >= 16) { /* mov to DRn */
2658 val = kvm_register_read(vcpu, reg);
2659 err = kvm_set_dr(vcpu, dr, val);
2661 kvm_get_dr(vcpu, dr, &val);
2662 kvm_register_write(vcpu, reg, val);
2665 return kvm_complete_insn_gp(vcpu, err);
2668 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2672 u8 cr8_prev = kvm_get_cr8(vcpu);
2673 /* instruction emulation calls kvm_set_cr8() */
2674 r = cr_interception(vcpu);
2675 if (lapic_in_kernel(vcpu))
2677 if (cr8_prev <= kvm_get_cr8(vcpu))
2679 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2683 static int efer_trap(struct kvm_vcpu *vcpu)
2685 struct msr_data msr_info;
2689 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2690 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2691 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2692 * the guest doesn't have X86_FEATURE_SVM.
2694 msr_info.host_initiated = false;
2695 msr_info.index = MSR_EFER;
2696 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2697 ret = kvm_set_msr_common(vcpu, &msr_info);
2699 return kvm_complete_insn_gp(vcpu, ret);
2702 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2706 switch (msr->index) {
2707 case MSR_AMD64_DE_CFG:
2708 if (cpu_feature_enabled(X86_FEATURE_LFENCE_RDTSC))
2709 msr->data |= MSR_AMD64_DE_CFG_LFENCE_SERIALIZE;
2711 case MSR_IA32_PERF_CAPABILITIES:
2714 return KVM_MSR_RET_INVALID;
2720 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2722 struct vcpu_svm *svm = to_svm(vcpu);
2724 switch (msr_info->index) {
2725 case MSR_AMD64_TSC_RATIO:
2726 if (!msr_info->host_initiated && !svm->tsc_scaling_enabled)
2728 msr_info->data = svm->tsc_ratio_msr;
2731 msr_info->data = svm->vmcb01.ptr->save.star;
2733 #ifdef CONFIG_X86_64
2735 msr_info->data = svm->vmcb01.ptr->save.lstar;
2738 msr_info->data = svm->vmcb01.ptr->save.cstar;
2740 case MSR_KERNEL_GS_BASE:
2741 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2743 case MSR_SYSCALL_MASK:
2744 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2747 case MSR_IA32_SYSENTER_CS:
2748 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2750 case MSR_IA32_SYSENTER_EIP:
2751 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2752 if (guest_cpuid_is_intel(vcpu))
2753 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2755 case MSR_IA32_SYSENTER_ESP:
2756 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2757 if (guest_cpuid_is_intel(vcpu))
2758 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2761 msr_info->data = svm->tsc_aux;
2763 case MSR_IA32_DEBUGCTLMSR:
2764 case MSR_IA32_LASTBRANCHFROMIP:
2765 case MSR_IA32_LASTBRANCHTOIP:
2766 case MSR_IA32_LASTINTFROMIP:
2767 case MSR_IA32_LASTINTTOIP:
2768 msr_info->data = svm_get_lbr_msr(svm, msr_info->index);
2770 case MSR_VM_HSAVE_PA:
2771 msr_info->data = svm->nested.hsave_msr;
2774 msr_info->data = svm->nested.vm_cr_msr;
2776 case MSR_IA32_SPEC_CTRL:
2777 if (!msr_info->host_initiated &&
2778 !guest_has_spec_ctrl_msr(vcpu))
2781 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2782 msr_info->data = svm->vmcb->save.spec_ctrl;
2784 msr_info->data = svm->spec_ctrl;
2786 case MSR_AMD64_VIRT_SPEC_CTRL:
2787 if (!msr_info->host_initiated &&
2788 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2791 msr_info->data = svm->virt_spec_ctrl;
2793 case MSR_F15H_IC_CFG: {
2797 family = guest_cpuid_family(vcpu);
2798 model = guest_cpuid_model(vcpu);
2800 if (family < 0 || model < 0)
2801 return kvm_get_msr_common(vcpu, msr_info);
2805 if (family == 0x15 &&
2806 (model >= 0x2 && model < 0x20))
2807 msr_info->data = 0x1E;
2810 case MSR_AMD64_DE_CFG:
2811 msr_info->data = svm->msr_decfg;
2814 return kvm_get_msr_common(vcpu, msr_info);
2819 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2821 struct vcpu_svm *svm = to_svm(vcpu);
2822 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->sev_es.ghcb))
2823 return kvm_complete_insn_gp(vcpu, err);
2825 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 1);
2826 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb,
2828 SVM_EVTINJ_TYPE_EXEPT |
2833 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2835 struct vcpu_svm *svm = to_svm(vcpu);
2836 int svm_dis, chg_mask;
2838 if (data & ~SVM_VM_CR_VALID_MASK)
2841 chg_mask = SVM_VM_CR_VALID_MASK;
2843 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2844 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2846 svm->nested.vm_cr_msr &= ~chg_mask;
2847 svm->nested.vm_cr_msr |= (data & chg_mask);
2849 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2851 /* check for svm_disable while efer.svme is set */
2852 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
2858 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
2860 struct vcpu_svm *svm = to_svm(vcpu);
2863 u32 ecx = msr->index;
2864 u64 data = msr->data;
2866 case MSR_AMD64_TSC_RATIO:
2868 if (!svm->tsc_scaling_enabled) {
2870 if (!msr->host_initiated)
2873 * In case TSC scaling is not enabled, always
2874 * leave this MSR at the default value.
2876 * Due to bug in qemu 6.2.0, it would try to set
2877 * this msr to 0 if tsc scaling is not enabled.
2878 * Ignore this value as well.
2880 if (data != 0 && data != svm->tsc_ratio_msr)
2885 if (data & SVM_TSC_RATIO_RSVD)
2888 svm->tsc_ratio_msr = data;
2890 if (svm->tsc_scaling_enabled && is_guest_mode(vcpu))
2891 nested_svm_update_tsc_ratio_msr(vcpu);
2894 case MSR_IA32_CR_PAT:
2895 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
2897 vcpu->arch.pat = data;
2898 svm->vmcb01.ptr->save.g_pat = data;
2899 if (is_guest_mode(vcpu))
2900 nested_vmcb02_compute_g_pat(svm);
2901 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
2903 case MSR_IA32_SPEC_CTRL:
2904 if (!msr->host_initiated &&
2905 !guest_has_spec_ctrl_msr(vcpu))
2908 if (kvm_spec_ctrl_test_value(data))
2911 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2912 svm->vmcb->save.spec_ctrl = data;
2914 svm->spec_ctrl = data;
2920 * When it's written (to non-zero) for the first time, pass
2924 * The handling of the MSR bitmap for L2 guests is done in
2925 * nested_svm_vmrun_msrpm.
2926 * We update the L1 MSR bit as well since it will end up
2927 * touching the MSR anyway now.
2929 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
2931 case MSR_IA32_PRED_CMD:
2932 if (!msr->host_initiated &&
2933 !guest_has_pred_cmd_msr(vcpu))
2936 if (data & ~PRED_CMD_IBPB)
2938 if (!boot_cpu_has(X86_FEATURE_IBPB))
2943 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
2944 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
2946 case MSR_AMD64_VIRT_SPEC_CTRL:
2947 if (!msr->host_initiated &&
2948 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2951 if (data & ~SPEC_CTRL_SSBD)
2954 svm->virt_spec_ctrl = data;
2957 svm->vmcb01.ptr->save.star = data;
2959 #ifdef CONFIG_X86_64
2961 svm->vmcb01.ptr->save.lstar = data;
2964 svm->vmcb01.ptr->save.cstar = data;
2966 case MSR_KERNEL_GS_BASE:
2967 svm->vmcb01.ptr->save.kernel_gs_base = data;
2969 case MSR_SYSCALL_MASK:
2970 svm->vmcb01.ptr->save.sfmask = data;
2973 case MSR_IA32_SYSENTER_CS:
2974 svm->vmcb01.ptr->save.sysenter_cs = data;
2976 case MSR_IA32_SYSENTER_EIP:
2977 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
2979 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
2980 * when we spoof an Intel vendor ID (for cross vendor migration).
2981 * In this case we use this intercept to track the high
2982 * 32 bit part of these msrs to support Intel's
2983 * implementation of SYSENTER/SYSEXIT.
2985 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2987 case MSR_IA32_SYSENTER_ESP:
2988 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
2989 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
2993 * TSC_AUX is usually changed only during boot and never read
2994 * directly. Intercept TSC_AUX instead of exposing it to the
2995 * guest via direct_access_msrs, and switch it via user return.
2998 r = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
3003 svm->tsc_aux = data;
3005 case MSR_IA32_DEBUGCTLMSR:
3007 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
3011 if (data & DEBUGCTL_RESERVED_BITS)
3014 if (svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK)
3015 svm->vmcb->save.dbgctl = data;
3017 svm->vmcb01.ptr->save.dbgctl = data;
3019 svm_update_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_AMD64_DE_CFG: {
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 * If not running nested, 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 * If running nested, still remove the VM wide AVIC inhibit to
3082 * support case in which the interrupt window was requested when the
3083 * vCPU was not running nested.
3085 * All vCPUs which run still run nested, will remain to have their
3086 * AVIC still inhibited due to per-cpu AVIC inhibition.
3088 kvm_clear_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
3090 ++vcpu->stat.irq_window_exits;
3094 static int pause_interception(struct kvm_vcpu *vcpu)
3098 * CPL is not made available for an SEV-ES guest, therefore
3099 * vcpu->arch.preempted_in_kernel can never be true. Just
3100 * set in_kernel to false as well.
3102 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3104 grow_ple_window(vcpu);
3106 kvm_vcpu_on_spin(vcpu, in_kernel);
3107 return kvm_skip_emulated_instruction(vcpu);
3110 static int invpcid_interception(struct kvm_vcpu *vcpu)
3112 struct vcpu_svm *svm = to_svm(vcpu);
3116 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3117 kvm_queue_exception(vcpu, UD_VECTOR);
3122 * For an INVPCID intercept:
3123 * EXITINFO1 provides the linear address of the memory operand.
3124 * EXITINFO2 provides the contents of the register operand.
3126 type = svm->vmcb->control.exit_info_2;
3127 gva = svm->vmcb->control.exit_info_1;
3129 return kvm_handle_invpcid(vcpu, type, gva);
3132 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3133 [SVM_EXIT_READ_CR0] = cr_interception,
3134 [SVM_EXIT_READ_CR3] = cr_interception,
3135 [SVM_EXIT_READ_CR4] = cr_interception,
3136 [SVM_EXIT_READ_CR8] = cr_interception,
3137 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3138 [SVM_EXIT_WRITE_CR0] = cr_interception,
3139 [SVM_EXIT_WRITE_CR3] = cr_interception,
3140 [SVM_EXIT_WRITE_CR4] = cr_interception,
3141 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3142 [SVM_EXIT_READ_DR0] = dr_interception,
3143 [SVM_EXIT_READ_DR1] = dr_interception,
3144 [SVM_EXIT_READ_DR2] = dr_interception,
3145 [SVM_EXIT_READ_DR3] = dr_interception,
3146 [SVM_EXIT_READ_DR4] = dr_interception,
3147 [SVM_EXIT_READ_DR5] = dr_interception,
3148 [SVM_EXIT_READ_DR6] = dr_interception,
3149 [SVM_EXIT_READ_DR7] = dr_interception,
3150 [SVM_EXIT_WRITE_DR0] = dr_interception,
3151 [SVM_EXIT_WRITE_DR1] = dr_interception,
3152 [SVM_EXIT_WRITE_DR2] = dr_interception,
3153 [SVM_EXIT_WRITE_DR3] = dr_interception,
3154 [SVM_EXIT_WRITE_DR4] = dr_interception,
3155 [SVM_EXIT_WRITE_DR5] = dr_interception,
3156 [SVM_EXIT_WRITE_DR6] = dr_interception,
3157 [SVM_EXIT_WRITE_DR7] = dr_interception,
3158 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3159 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3160 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3161 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3162 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3163 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3164 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3165 [SVM_EXIT_INTR] = intr_interception,
3166 [SVM_EXIT_NMI] = nmi_interception,
3167 [SVM_EXIT_SMI] = smi_interception,
3168 [SVM_EXIT_VINTR] = interrupt_window_interception,
3169 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3170 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3171 [SVM_EXIT_IRET] = iret_interception,
3172 [SVM_EXIT_INVD] = kvm_emulate_invd,
3173 [SVM_EXIT_PAUSE] = pause_interception,
3174 [SVM_EXIT_HLT] = kvm_emulate_halt,
3175 [SVM_EXIT_INVLPG] = invlpg_interception,
3176 [SVM_EXIT_INVLPGA] = invlpga_interception,
3177 [SVM_EXIT_IOIO] = io_interception,
3178 [SVM_EXIT_MSR] = msr_interception,
3179 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3180 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3181 [SVM_EXIT_VMRUN] = vmrun_interception,
3182 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3183 [SVM_EXIT_VMLOAD] = vmload_interception,
3184 [SVM_EXIT_VMSAVE] = vmsave_interception,
3185 [SVM_EXIT_STGI] = stgi_interception,
3186 [SVM_EXIT_CLGI] = clgi_interception,
3187 [SVM_EXIT_SKINIT] = skinit_interception,
3188 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3189 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3190 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3191 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3192 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3193 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3194 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3195 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3196 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3197 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3198 [SVM_EXIT_INVPCID] = invpcid_interception,
3199 [SVM_EXIT_NPF] = npf_interception,
3200 [SVM_EXIT_RSM] = rsm_interception,
3201 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3202 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3203 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3206 static void dump_vmcb(struct kvm_vcpu *vcpu)
3208 struct vcpu_svm *svm = to_svm(vcpu);
3209 struct vmcb_control_area *control = &svm->vmcb->control;
3210 struct vmcb_save_area *save = &svm->vmcb->save;
3211 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3213 if (!dump_invalid_vmcb) {
3214 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3218 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3219 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3220 pr_err("VMCB Control Area:\n");
3221 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3222 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3223 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3224 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3225 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3226 pr_err("%-20s%08x %08x\n", "intercepts:",
3227 control->intercepts[INTERCEPT_WORD3],
3228 control->intercepts[INTERCEPT_WORD4]);
3229 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3230 pr_err("%-20s%d\n", "pause filter threshold:",
3231 control->pause_filter_thresh);
3232 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3233 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3234 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3235 pr_err("%-20s%d\n", "asid:", control->asid);
3236 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3237 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3238 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3239 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3240 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3241 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3242 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3243 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3244 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3245 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3246 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3247 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3248 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3249 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3250 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3251 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3252 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3253 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3254 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3255 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3256 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3257 pr_err("VMCB State Save Area:\n");
3258 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3260 save->es.selector, save->es.attrib,
3261 save->es.limit, save->es.base);
3262 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3264 save->cs.selector, save->cs.attrib,
3265 save->cs.limit, save->cs.base);
3266 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3268 save->ss.selector, save->ss.attrib,
3269 save->ss.limit, save->ss.base);
3270 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3272 save->ds.selector, save->ds.attrib,
3273 save->ds.limit, save->ds.base);
3274 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3276 save01->fs.selector, save01->fs.attrib,
3277 save01->fs.limit, save01->fs.base);
3278 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3280 save01->gs.selector, save01->gs.attrib,
3281 save01->gs.limit, save01->gs.base);
3282 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3284 save->gdtr.selector, save->gdtr.attrib,
3285 save->gdtr.limit, save->gdtr.base);
3286 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3288 save01->ldtr.selector, save01->ldtr.attrib,
3289 save01->ldtr.limit, save01->ldtr.base);
3290 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3292 save->idtr.selector, save->idtr.attrib,
3293 save->idtr.limit, save->idtr.base);
3294 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3296 save01->tr.selector, save01->tr.attrib,
3297 save01->tr.limit, save01->tr.base);
3298 pr_err("vmpl: %d cpl: %d efer: %016llx\n",
3299 save->vmpl, save->cpl, save->efer);
3300 pr_err("%-15s %016llx %-13s %016llx\n",
3301 "cr0:", save->cr0, "cr2:", save->cr2);
3302 pr_err("%-15s %016llx %-13s %016llx\n",
3303 "cr3:", save->cr3, "cr4:", save->cr4);
3304 pr_err("%-15s %016llx %-13s %016llx\n",
3305 "dr6:", save->dr6, "dr7:", save->dr7);
3306 pr_err("%-15s %016llx %-13s %016llx\n",
3307 "rip:", save->rip, "rflags:", save->rflags);
3308 pr_err("%-15s %016llx %-13s %016llx\n",
3309 "rsp:", save->rsp, "rax:", save->rax);
3310 pr_err("%-15s %016llx %-13s %016llx\n",
3311 "star:", save01->star, "lstar:", save01->lstar);
3312 pr_err("%-15s %016llx %-13s %016llx\n",
3313 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3314 pr_err("%-15s %016llx %-13s %016llx\n",
3315 "kernel_gs_base:", save01->kernel_gs_base,
3316 "sysenter_cs:", save01->sysenter_cs);
3317 pr_err("%-15s %016llx %-13s %016llx\n",
3318 "sysenter_esp:", save01->sysenter_esp,
3319 "sysenter_eip:", save01->sysenter_eip);
3320 pr_err("%-15s %016llx %-13s %016llx\n",
3321 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3322 pr_err("%-15s %016llx %-13s %016llx\n",
3323 "br_from:", save->br_from, "br_to:", save->br_to);
3324 pr_err("%-15s %016llx %-13s %016llx\n",
3325 "excp_from:", save->last_excp_from,
3326 "excp_to:", save->last_excp_to);
3329 static bool svm_check_exit_valid(u64 exit_code)
3331 return (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3332 svm_exit_handlers[exit_code]);
3335 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3337 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3339 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3340 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3341 vcpu->run->internal.ndata = 2;
3342 vcpu->run->internal.data[0] = exit_code;
3343 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3347 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3349 if (!svm_check_exit_valid(exit_code))
3350 return svm_handle_invalid_exit(vcpu, exit_code);
3352 #ifdef CONFIG_RETPOLINE
3353 if (exit_code == SVM_EXIT_MSR)
3354 return msr_interception(vcpu);
3355 else if (exit_code == SVM_EXIT_VINTR)
3356 return interrupt_window_interception(vcpu);
3357 else if (exit_code == SVM_EXIT_INTR)
3358 return intr_interception(vcpu);
3359 else if (exit_code == SVM_EXIT_HLT)
3360 return kvm_emulate_halt(vcpu);
3361 else if (exit_code == SVM_EXIT_NPF)
3362 return npf_interception(vcpu);
3364 return svm_exit_handlers[exit_code](vcpu);
3367 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
3368 u64 *info1, u64 *info2,
3369 u32 *intr_info, u32 *error_code)
3371 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3373 *reason = control->exit_code;
3374 *info1 = control->exit_info_1;
3375 *info2 = control->exit_info_2;
3376 *intr_info = control->exit_int_info;
3377 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3378 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3379 *error_code = control->exit_int_info_err;
3384 static int svm_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3386 struct vcpu_svm *svm = to_svm(vcpu);
3387 struct kvm_run *kvm_run = vcpu->run;
3388 u32 exit_code = svm->vmcb->control.exit_code;
3390 trace_kvm_exit(vcpu, KVM_ISA_SVM);
3392 /* SEV-ES guests must use the CR write traps to track CR registers. */
3393 if (!sev_es_guest(vcpu->kvm)) {
3394 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3395 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3397 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3400 if (is_guest_mode(vcpu)) {
3403 trace_kvm_nested_vmexit(vcpu, KVM_ISA_SVM);
3405 vmexit = nested_svm_exit_special(svm);
3407 if (vmexit == NESTED_EXIT_CONTINUE)
3408 vmexit = nested_svm_exit_handled(svm);
3410 if (vmexit == NESTED_EXIT_DONE)
3414 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3415 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3416 kvm_run->fail_entry.hardware_entry_failure_reason
3417 = svm->vmcb->control.exit_code;
3418 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3423 if (exit_fastpath != EXIT_FASTPATH_NONE)
3426 return svm_invoke_exit_handler(vcpu, exit_code);
3429 static void reload_tss(struct kvm_vcpu *vcpu)
3431 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
3433 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3437 static void pre_svm_run(struct kvm_vcpu *vcpu)
3439 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
3440 struct vcpu_svm *svm = to_svm(vcpu);
3443 * If the previous vmrun of the vmcb occurred on a different physical
3444 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3445 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3447 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3448 svm->current_vmcb->asid_generation = 0;
3449 vmcb_mark_all_dirty(svm->vmcb);
3450 svm->current_vmcb->cpu = vcpu->cpu;
3453 if (sev_guest(vcpu->kvm))
3454 return pre_sev_run(svm, vcpu->cpu);
3456 /* FIXME: handle wraparound of asid_generation */
3457 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3461 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3463 struct vcpu_svm *svm = to_svm(vcpu);
3465 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3467 if (svm->nmi_l1_to_l2)
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_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
3478 struct vcpu_svm *svm = to_svm(vcpu);
3481 if (vcpu->arch.interrupt.soft) {
3482 if (svm_update_soft_interrupt_rip(vcpu))
3485 type = SVM_EVTINJ_TYPE_SOFT;
3487 type = SVM_EVTINJ_TYPE_INTR;
3490 trace_kvm_inj_virq(vcpu->arch.interrupt.nr,
3491 vcpu->arch.interrupt.soft, reinjected);
3492 ++vcpu->stat.irq_injections;
3494 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3495 SVM_EVTINJ_VALID | type;
3498 void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,
3499 int trig_mode, int vector)
3502 * apic->apicv_active must be read after vcpu->mode.
3503 * Pairs with smp_store_release in vcpu_enter_guest.
3505 bool in_guest_mode = (smp_load_acquire(&vcpu->mode) == IN_GUEST_MODE);
3507 /* Note, this is called iff the local APIC is in-kernel. */
3508 if (!READ_ONCE(vcpu->arch.apic->apicv_active)) {
3509 /* Process the interrupt via kvm_check_and_inject_events(). */
3510 kvm_make_request(KVM_REQ_EVENT, vcpu);
3511 kvm_vcpu_kick(vcpu);
3515 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, trig_mode, vector);
3516 if (in_guest_mode) {
3518 * Signal the doorbell to tell hardware to inject the IRQ. If
3519 * the vCPU exits the guest before the doorbell chimes, hardware
3520 * will automatically process AVIC interrupts at the next VMRUN.
3522 avic_ring_doorbell(vcpu);
3525 * Wake the vCPU if it was blocking. KVM will then detect the
3526 * pending IRQ when checking if the vCPU has a wake event.
3528 kvm_vcpu_wake_up(vcpu);
3532 static void svm_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
3533 int trig_mode, int vector)
3535 kvm_lapic_set_irr(vector, apic);
3538 * Pairs with the smp_mb_*() after setting vcpu->guest_mode in
3539 * vcpu_enter_guest() to ensure the write to the vIRR is ordered before
3540 * the read of guest_mode. This guarantees that either VMRUN will see
3541 * and process the new vIRR entry, or that svm_complete_interrupt_delivery
3542 * will signal the doorbell if the CPU has already entered the guest.
3544 smp_mb__after_atomic();
3545 svm_complete_interrupt_delivery(apic->vcpu, delivery_mode, trig_mode, vector);
3548 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3550 struct vcpu_svm *svm = to_svm(vcpu);
3553 * SEV-ES guests must always keep the CR intercepts cleared. CR
3554 * tracking is done using the CR write traps.
3556 if (sev_es_guest(vcpu->kvm))
3559 if (nested_svm_virtualize_tpr(vcpu))
3562 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3568 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3571 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3573 struct vcpu_svm *svm = to_svm(vcpu);
3574 struct vmcb *vmcb = svm->vmcb;
3580 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3583 ret = (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) ||
3584 (vcpu->arch.hflags & HF_NMI_MASK);
3589 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3591 struct vcpu_svm *svm = to_svm(vcpu);
3592 if (svm->nested.nested_run_pending)
3595 if (svm_nmi_blocked(vcpu))
3598 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3599 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3604 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3606 return !!(vcpu->arch.hflags & HF_NMI_MASK);
3609 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3611 struct vcpu_svm *svm = to_svm(vcpu);
3614 vcpu->arch.hflags |= HF_NMI_MASK;
3615 if (!sev_es_guest(vcpu->kvm))
3616 svm_set_intercept(svm, INTERCEPT_IRET);
3618 vcpu->arch.hflags &= ~HF_NMI_MASK;
3619 if (!sev_es_guest(vcpu->kvm))
3620 svm_clr_intercept(svm, INTERCEPT_IRET);
3624 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3626 struct vcpu_svm *svm = to_svm(vcpu);
3627 struct vmcb *vmcb = svm->vmcb;
3632 if (is_guest_mode(vcpu)) {
3633 /* As long as interrupts are being delivered... */
3634 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3635 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3636 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3639 /* ... vmexits aren't blocked by the interrupt shadow */
3640 if (nested_exit_on_intr(svm))
3643 if (!svm_get_if_flag(vcpu))
3647 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3650 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3652 struct vcpu_svm *svm = to_svm(vcpu);
3654 if (svm->nested.nested_run_pending)
3657 if (svm_interrupt_blocked(vcpu))
3661 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3662 * e.g. if the IRQ arrived asynchronously after checking nested events.
3664 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3670 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3672 struct vcpu_svm *svm = to_svm(vcpu);
3675 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3676 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3677 * get that intercept, this function will be called again though and
3678 * we'll get the vintr intercept. However, if the vGIF feature is
3679 * enabled, the STGI interception will not occur. Enable the irq
3680 * window under the assumption that the hardware will set the GIF.
3682 if (vgif || gif_set(svm)) {
3684 * IRQ window is not needed when AVIC is enabled,
3685 * unless we have pending ExtINT since it cannot be injected
3686 * via AVIC. In such case, KVM needs to temporarily disable AVIC,
3687 * and fallback to injecting IRQ via V_IRQ.
3689 * If running nested, AVIC is already locally inhibited
3690 * on this vCPU, therefore there is no need to request
3691 * the VM wide AVIC inhibition.
3693 if (!is_guest_mode(vcpu))
3694 kvm_set_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
3700 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3702 struct vcpu_svm *svm = to_svm(vcpu);
3704 if ((vcpu->arch.hflags & (HF_NMI_MASK | HF_IRET_MASK)) == HF_NMI_MASK)
3705 return; /* IRET will cause a vm exit */
3707 if (!gif_set(svm)) {
3709 svm_set_intercept(svm, INTERCEPT_STGI);
3710 return; /* STGI will cause a vm exit */
3714 * Something prevents NMI from been injected. Single step over possible
3715 * problem (IRET or exception injection or interrupt shadow)
3717 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3718 svm->nmi_singlestep = true;
3719 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3722 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
3724 struct vcpu_svm *svm = to_svm(vcpu);
3727 * Flush only the current ASID even if the TLB flush was invoked via
3728 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3729 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3730 * unconditionally does a TLB flush on both nested VM-Enter and nested
3731 * VM-Exit (via kvm_mmu_reset_context()).
3733 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3734 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3736 svm->current_vmcb->asid_generation--;
3739 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
3741 struct vcpu_svm *svm = to_svm(vcpu);
3743 invlpga(gva, svm->vmcb->control.asid);
3746 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3748 struct vcpu_svm *svm = to_svm(vcpu);
3750 if (nested_svm_virtualize_tpr(vcpu))
3753 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
3754 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3755 kvm_set_cr8(vcpu, cr8);
3759 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3761 struct vcpu_svm *svm = to_svm(vcpu);
3764 if (nested_svm_virtualize_tpr(vcpu) ||
3765 kvm_vcpu_apicv_active(vcpu))
3768 cr8 = kvm_get_cr8(vcpu);
3769 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3770 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3773 static void svm_complete_soft_interrupt(struct kvm_vcpu *vcpu, u8 vector,
3776 bool is_exception = (type == SVM_EXITINTINFO_TYPE_EXEPT);
3777 bool is_soft = (type == SVM_EXITINTINFO_TYPE_SOFT);
3778 struct vcpu_svm *svm = to_svm(vcpu);
3781 * If NRIPS is enabled, KVM must snapshot the pre-VMRUN next_rip that's
3782 * associated with the original soft exception/interrupt. next_rip is
3783 * cleared on all exits that can occur while vectoring an event, so KVM
3784 * needs to manually set next_rip for re-injection. Unlike the !nrips
3785 * case below, this needs to be done if and only if KVM is re-injecting
3786 * the same event, i.e. if the event is a soft exception/interrupt,
3787 * otherwise next_rip is unused on VMRUN.
3789 if (nrips && (is_soft || (is_exception && kvm_exception_is_soft(vector))) &&
3790 kvm_is_linear_rip(vcpu, svm->soft_int_old_rip + svm->soft_int_csbase))
3791 svm->vmcb->control.next_rip = svm->soft_int_next_rip;
3793 * If NRIPS isn't enabled, KVM must manually advance RIP prior to
3794 * injecting the soft exception/interrupt. That advancement needs to
3795 * be unwound if vectoring didn't complete. Note, the new event may
3796 * not be the injected event, e.g. if KVM injected an INTn, the INTn
3797 * hit a #NP in the guest, and the #NP encountered a #PF, the #NP will
3798 * be the reported vectored event, but RIP still needs to be unwound.
3800 else if (!nrips && (is_soft || is_exception) &&
3801 kvm_is_linear_rip(vcpu, svm->soft_int_next_rip + svm->soft_int_csbase))
3802 kvm_rip_write(vcpu, svm->soft_int_old_rip);
3805 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
3807 struct vcpu_svm *svm = to_svm(vcpu);
3810 u32 exitintinfo = svm->vmcb->control.exit_int_info;
3811 bool nmi_l1_to_l2 = svm->nmi_l1_to_l2;
3812 bool soft_int_injected = svm->soft_int_injected;
3814 svm->nmi_l1_to_l2 = false;
3815 svm->soft_int_injected = false;
3818 * If we've made progress since setting HF_IRET_MASK, we've
3819 * executed an IRET and can allow NMI injection.
3821 if ((vcpu->arch.hflags & HF_IRET_MASK) &&
3822 (sev_es_guest(vcpu->kvm) ||
3823 kvm_rip_read(vcpu) != svm->nmi_iret_rip)) {
3824 vcpu->arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3825 kvm_make_request(KVM_REQ_EVENT, vcpu);
3828 vcpu->arch.nmi_injected = false;
3829 kvm_clear_exception_queue(vcpu);
3830 kvm_clear_interrupt_queue(vcpu);
3832 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3835 kvm_make_request(KVM_REQ_EVENT, vcpu);
3837 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3838 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3840 if (soft_int_injected)
3841 svm_complete_soft_interrupt(vcpu, vector, type);
3844 case SVM_EXITINTINFO_TYPE_NMI:
3845 vcpu->arch.nmi_injected = true;
3846 svm->nmi_l1_to_l2 = nmi_l1_to_l2;
3848 case SVM_EXITINTINFO_TYPE_EXEPT:
3850 * Never re-inject a #VC exception.
3852 if (vector == X86_TRAP_VC)
3855 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3856 u32 err = svm->vmcb->control.exit_int_info_err;
3857 kvm_requeue_exception_e(vcpu, vector, err);
3860 kvm_requeue_exception(vcpu, vector);
3862 case SVM_EXITINTINFO_TYPE_INTR:
3863 kvm_queue_interrupt(vcpu, vector, false);
3865 case SVM_EXITINTINFO_TYPE_SOFT:
3866 kvm_queue_interrupt(vcpu, vector, true);
3874 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3876 struct vcpu_svm *svm = to_svm(vcpu);
3877 struct vmcb_control_area *control = &svm->vmcb->control;
3879 control->exit_int_info = control->event_inj;
3880 control->exit_int_info_err = control->event_inj_err;
3881 control->event_inj = 0;
3882 svm_complete_interrupts(vcpu);
3885 static int svm_vcpu_pre_run(struct kvm_vcpu *vcpu)
3890 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
3892 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3895 * Note, the next RIP must be provided as SRCU isn't held, i.e. KVM
3896 * can't read guest memory (dereference memslots) to decode the WRMSR.
3898 if (control->exit_code == SVM_EXIT_MSR && control->exit_info_1 &&
3899 nrips && control->next_rip)
3900 return handle_fastpath_set_msr_irqoff(vcpu);
3902 return EXIT_FASTPATH_NONE;
3905 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu, bool spec_ctrl_intercepted)
3907 struct vcpu_svm *svm = to_svm(vcpu);
3909 guest_state_enter_irqoff();
3911 if (sev_es_guest(vcpu->kvm))
3912 __svm_sev_es_vcpu_run(svm, spec_ctrl_intercepted);
3914 __svm_vcpu_run(svm, spec_ctrl_intercepted);
3916 guest_state_exit_irqoff();
3919 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
3921 struct vcpu_svm *svm = to_svm(vcpu);
3922 bool spec_ctrl_intercepted = msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL);
3924 trace_kvm_entry(vcpu);
3926 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3927 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3928 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3931 * Disable singlestep if we're injecting an interrupt/exception.
3932 * We don't want our modified rflags to be pushed on the stack where
3933 * we might not be able to easily reset them if we disabled NMI
3936 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
3938 * Event injection happens before external interrupts cause a
3939 * vmexit and interrupts are disabled here, so smp_send_reschedule
3940 * is enough to force an immediate vmexit.
3942 disable_nmi_singlestep(svm);
3943 smp_send_reschedule(vcpu->cpu);
3948 sync_lapic_to_cr8(vcpu);
3950 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
3951 svm->vmcb->control.asid = svm->asid;
3952 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
3954 svm->vmcb->save.cr2 = vcpu->arch.cr2;
3956 svm_hv_update_vp_id(svm->vmcb, vcpu);
3959 * Run with all-zero DR6 unless needed, so that we can get the exact cause
3962 if (unlikely(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT))
3963 svm_set_dr6(svm, vcpu->arch.dr6);
3965 svm_set_dr6(svm, DR6_ACTIVE_LOW);
3968 kvm_load_guest_xsave_state(vcpu);
3970 kvm_wait_lapic_expire(vcpu);
3973 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3974 * it's non-zero. Since vmentry is serialising on affected CPUs, there
3975 * is no need to worry about the conditional branch over the wrmsr
3976 * being speculatively taken.
3978 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3979 x86_spec_ctrl_set_guest(svm->virt_spec_ctrl);
3981 svm_vcpu_enter_exit(vcpu, spec_ctrl_intercepted);
3983 if (!sev_es_guest(vcpu->kvm))
3986 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3987 x86_spec_ctrl_restore_host(svm->virt_spec_ctrl);
3989 if (!sev_es_guest(vcpu->kvm)) {
3990 vcpu->arch.cr2 = svm->vmcb->save.cr2;
3991 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
3992 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
3993 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
3995 vcpu->arch.regs_dirty = 0;
3997 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
3998 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
4000 kvm_load_host_xsave_state(vcpu);
4003 /* Any pending NMI will happen here */
4005 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4006 kvm_after_interrupt(vcpu);
4008 sync_cr8_to_lapic(vcpu);
4011 if (is_guest_mode(vcpu)) {
4012 nested_sync_control_from_vmcb02(svm);
4014 /* Track VMRUNs that have made past consistency checking */
4015 if (svm->nested.nested_run_pending &&
4016 svm->vmcb->control.exit_code != SVM_EXIT_ERR)
4017 ++vcpu->stat.nested_run;
4019 svm->nested.nested_run_pending = 0;
4022 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
4023 vmcb_mark_all_clean(svm->vmcb);
4025 /* if exit due to PF check for async PF */
4026 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
4027 vcpu->arch.apf.host_apf_flags =
4028 kvm_read_and_reset_apf_flags();
4030 vcpu->arch.regs_avail &= ~SVM_REGS_LAZY_LOAD_SET;
4033 * We need to handle MC intercepts here before the vcpu has a chance to
4034 * change the physical cpu
4036 if (unlikely(svm->vmcb->control.exit_code ==
4037 SVM_EXIT_EXCP_BASE + MC_VECTOR))
4038 svm_handle_mce(vcpu);
4040 svm_complete_interrupts(vcpu);
4042 if (is_guest_mode(vcpu))
4043 return EXIT_FASTPATH_NONE;
4045 return svm_exit_handlers_fastpath(vcpu);
4048 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
4051 struct vcpu_svm *svm = to_svm(vcpu);
4055 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
4056 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
4058 hv_track_root_tdp(vcpu, root_hpa);
4060 cr3 = vcpu->arch.cr3;
4061 } else if (root_level >= PT64_ROOT_4LEVEL) {
4062 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
4064 /* PCID in the guest should be impossible with a 32-bit MMU. */
4065 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
4069 svm->vmcb->save.cr3 = cr3;
4070 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
4073 static int is_disabled(void)
4077 rdmsrl(MSR_VM_CR, vm_cr);
4078 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
4085 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4088 * Patch in the VMMCALL instruction:
4090 hypercall[0] = 0x0f;
4091 hypercall[1] = 0x01;
4092 hypercall[2] = 0xd9;
4095 static int __init svm_check_processor_compat(void)
4101 * The kvm parameter can be NULL (module initialization, or invocation before
4102 * VM creation). Be sure to check the kvm parameter before using it.
4104 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4107 case MSR_IA32_MCG_EXT_CTL:
4108 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4110 case MSR_IA32_SMBASE:
4111 /* SEV-ES guests do not support SMM, so report false */
4112 if (kvm && sev_es_guest(kvm))
4122 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4124 struct vcpu_svm *svm = to_svm(vcpu);
4125 struct kvm_cpuid_entry2 *best;
4127 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
4128 boot_cpu_has(X86_FEATURE_XSAVE) &&
4129 boot_cpu_has(X86_FEATURE_XSAVES);
4131 /* Update nrips enabled cache */
4132 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
4133 guest_cpuid_has(vcpu, X86_FEATURE_NRIPS);
4135 svm->tsc_scaling_enabled = tsc_scaling && guest_cpuid_has(vcpu, X86_FEATURE_TSCRATEMSR);
4136 svm->lbrv_enabled = lbrv && guest_cpuid_has(vcpu, X86_FEATURE_LBRV);
4138 svm->v_vmload_vmsave_enabled = vls && guest_cpuid_has(vcpu, X86_FEATURE_V_VMSAVE_VMLOAD);
4140 svm->pause_filter_enabled = kvm_cpu_cap_has(X86_FEATURE_PAUSEFILTER) &&
4141 guest_cpuid_has(vcpu, X86_FEATURE_PAUSEFILTER);
4143 svm->pause_threshold_enabled = kvm_cpu_cap_has(X86_FEATURE_PFTHRESHOLD) &&
4144 guest_cpuid_has(vcpu, X86_FEATURE_PFTHRESHOLD);
4146 svm->vgif_enabled = vgif && guest_cpuid_has(vcpu, X86_FEATURE_VGIF);
4148 svm_recalc_instruction_intercepts(vcpu, svm);
4150 /* For sev guests, the memory encryption bit is not reserved in CR3. */
4151 if (sev_guest(vcpu->kvm)) {
4152 best = kvm_find_cpuid_entry(vcpu, 0x8000001F);
4154 vcpu->arch.reserved_gpa_bits &= ~(1UL << (best->ebx & 0x3f));
4157 init_vmcb_after_set_cpuid(vcpu);
4160 static bool svm_has_wbinvd_exit(void)
4165 #define PRE_EX(exit) { .exit_code = (exit), \
4166 .stage = X86_ICPT_PRE_EXCEPT, }
4167 #define POST_EX(exit) { .exit_code = (exit), \
4168 .stage = X86_ICPT_POST_EXCEPT, }
4169 #define POST_MEM(exit) { .exit_code = (exit), \
4170 .stage = X86_ICPT_POST_MEMACCESS, }
4172 static const struct __x86_intercept {
4174 enum x86_intercept_stage stage;
4175 } x86_intercept_map[] = {
4176 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4177 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4178 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4179 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4180 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4181 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4182 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4183 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4184 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4185 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4186 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4187 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4188 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4189 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4190 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4191 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4192 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4193 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4194 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4195 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4196 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4197 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4198 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4199 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4200 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4201 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4202 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4203 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4204 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4205 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4206 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4207 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4208 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4209 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4210 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4211 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4212 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4213 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4214 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4215 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4216 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4217 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4218 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4219 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4220 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4221 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4222 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4229 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4230 struct x86_instruction_info *info,
4231 enum x86_intercept_stage stage,
4232 struct x86_exception *exception)
4234 struct vcpu_svm *svm = to_svm(vcpu);
4235 int vmexit, ret = X86EMUL_CONTINUE;
4236 struct __x86_intercept icpt_info;
4237 struct vmcb *vmcb = svm->vmcb;
4239 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4242 icpt_info = x86_intercept_map[info->intercept];
4244 if (stage != icpt_info.stage)
4247 switch (icpt_info.exit_code) {
4248 case SVM_EXIT_READ_CR0:
4249 if (info->intercept == x86_intercept_cr_read)
4250 icpt_info.exit_code += info->modrm_reg;
4252 case SVM_EXIT_WRITE_CR0: {
4253 unsigned long cr0, val;
4255 if (info->intercept == x86_intercept_cr_write)
4256 icpt_info.exit_code += info->modrm_reg;
4258 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4259 info->intercept == x86_intercept_clts)
4262 if (!(vmcb12_is_intercept(&svm->nested.ctl,
4263 INTERCEPT_SELECTIVE_CR0)))
4266 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4267 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4269 if (info->intercept == x86_intercept_lmsw) {
4272 /* lmsw can't clear PE - catch this here */
4273 if (cr0 & X86_CR0_PE)
4278 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4282 case SVM_EXIT_READ_DR0:
4283 case SVM_EXIT_WRITE_DR0:
4284 icpt_info.exit_code += info->modrm_reg;
4287 if (info->intercept == x86_intercept_wrmsr)
4288 vmcb->control.exit_info_1 = 1;
4290 vmcb->control.exit_info_1 = 0;
4292 case SVM_EXIT_PAUSE:
4294 * We get this for NOP only, but pause
4295 * is rep not, check this here
4297 if (info->rep_prefix != REPE_PREFIX)
4300 case SVM_EXIT_IOIO: {
4304 if (info->intercept == x86_intercept_in ||
4305 info->intercept == x86_intercept_ins) {
4306 exit_info = ((info->src_val & 0xffff) << 16) |
4308 bytes = info->dst_bytes;
4310 exit_info = (info->dst_val & 0xffff) << 16;
4311 bytes = info->src_bytes;
4314 if (info->intercept == x86_intercept_outs ||
4315 info->intercept == x86_intercept_ins)
4316 exit_info |= SVM_IOIO_STR_MASK;
4318 if (info->rep_prefix)
4319 exit_info |= SVM_IOIO_REP_MASK;
4321 bytes = min(bytes, 4u);
4323 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4325 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4327 vmcb->control.exit_info_1 = exit_info;
4328 vmcb->control.exit_info_2 = info->next_rip;
4336 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4337 if (static_cpu_has(X86_FEATURE_NRIPS))
4338 vmcb->control.next_rip = info->next_rip;
4339 vmcb->control.exit_code = icpt_info.exit_code;
4340 vmexit = nested_svm_exit_handled(svm);
4342 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4349 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4351 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_INTR)
4352 vcpu->arch.at_instruction_boundary = true;
4355 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4357 if (!kvm_pause_in_guest(vcpu->kvm))
4358 shrink_ple_window(vcpu);
4361 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4363 /* [63:9] are reserved. */
4364 vcpu->arch.mcg_cap &= 0x1ff;
4367 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4369 struct vcpu_svm *svm = to_svm(vcpu);
4371 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4375 return is_smm(vcpu);
4378 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4380 struct vcpu_svm *svm = to_svm(vcpu);
4381 if (svm->nested.nested_run_pending)
4384 if (svm_smi_blocked(vcpu))
4387 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4388 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4394 static int svm_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
4396 struct vcpu_svm *svm = to_svm(vcpu);
4397 struct kvm_host_map map_save;
4400 if (!is_guest_mode(vcpu))
4403 /* FED8h - SVM Guest */
4404 put_smstate(u64, smstate, 0x7ed8, 1);
4405 /* FEE0h - SVM Guest VMCB Physical Address */
4406 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb12_gpa);
4408 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4409 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4410 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4412 ret = nested_svm_simple_vmexit(svm, SVM_EXIT_SW);
4417 * KVM uses VMCB01 to store L1 host state while L2 runs but
4418 * VMCB01 is going to be used during SMM and thus the state will
4419 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4420 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4421 * format of the area is identical to guest save area offsetted
4422 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4423 * within 'struct vmcb'). Note: HSAVE area may also be used by
4424 * L1 hypervisor to save additional host context (e.g. KVM does
4425 * that, see svm_prepare_switch_to_guest()) which must be
4428 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr),
4429 &map_save) == -EINVAL)
4432 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4434 svm_copy_vmrun_state(map_save.hva + 0x400,
4435 &svm->vmcb01.ptr->save);
4437 kvm_vcpu_unmap(vcpu, &map_save, true);
4441 static int svm_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
4443 struct vcpu_svm *svm = to_svm(vcpu);
4444 struct kvm_host_map map, map_save;
4445 u64 saved_efer, vmcb12_gpa;
4446 struct vmcb *vmcb12;
4449 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4452 /* Non-zero if SMI arrived while vCPU was in guest mode. */
4453 if (!GET_SMSTATE(u64, smstate, 0x7ed8))
4456 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4459 saved_efer = GET_SMSTATE(u64, smstate, 0x7ed0);
4460 if (!(saved_efer & EFER_SVME))
4463 vmcb12_gpa = GET_SMSTATE(u64, smstate, 0x7ee0);
4464 if (kvm_vcpu_map(vcpu, gpa_to_gfn(vmcb12_gpa), &map) == -EINVAL)
4468 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save) == -EINVAL)
4471 if (svm_allocate_nested(svm))
4475 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4476 * used during SMM (see svm_enter_smm())
4479 svm_copy_vmrun_state(&svm->vmcb01.ptr->save, map_save.hva + 0x400);
4482 * Enter the nested guest now
4485 vmcb_mark_all_dirty(svm->vmcb01.ptr);
4488 nested_copy_vmcb_control_to_cache(svm, &vmcb12->control);
4489 nested_copy_vmcb_save_to_cache(svm, &vmcb12->save);
4490 ret = enter_svm_guest_mode(vcpu, vmcb12_gpa, vmcb12, false);
4495 svm->nested.nested_run_pending = 1;
4498 kvm_vcpu_unmap(vcpu, &map_save, true);
4500 kvm_vcpu_unmap(vcpu, &map, true);
4504 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4506 struct vcpu_svm *svm = to_svm(vcpu);
4508 if (!gif_set(svm)) {
4510 svm_set_intercept(svm, INTERCEPT_STGI);
4511 /* STGI will cause a vm exit */
4513 /* We must be in SMM; RSM will cause a vmexit anyway. */
4517 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
4518 void *insn, int insn_len)
4520 bool smep, smap, is_user;
4524 /* Emulation is always possible when KVM has access to all guest state. */
4525 if (!sev_guest(vcpu->kvm))
4528 /* #UD and #GP should never be intercepted for SEV guests. */
4529 WARN_ON_ONCE(emul_type & (EMULTYPE_TRAP_UD |
4530 EMULTYPE_TRAP_UD_FORCED |
4531 EMULTYPE_VMWARE_GP));
4534 * Emulation is impossible for SEV-ES guests as KVM doesn't have access
4535 * to guest register state.
4537 if (sev_es_guest(vcpu->kvm))
4541 * Emulation is possible if the instruction is already decoded, e.g.
4542 * when completing I/O after returning from userspace.
4544 if (emul_type & EMULTYPE_NO_DECODE)
4548 * Emulation is possible for SEV guests if and only if a prefilled
4549 * buffer containing the bytes of the intercepted instruction is
4550 * available. SEV guest memory is encrypted with a guest specific key
4551 * and cannot be decrypted by KVM, i.e. KVM would read cyphertext and
4554 * Inject #UD if KVM reached this point without an instruction buffer.
4555 * In practice, this path should never be hit by a well-behaved guest,
4556 * e.g. KVM doesn't intercept #UD or #GP for SEV guests, but this path
4557 * is still theoretically reachable, e.g. via unaccelerated fault-like
4558 * AVIC access, and needs to be handled by KVM to avoid putting the
4559 * guest into an infinite loop. Injecting #UD is somewhat arbitrary,
4560 * but its the least awful option given lack of insight into the guest.
4562 if (unlikely(!insn)) {
4563 kvm_queue_exception(vcpu, UD_VECTOR);
4568 * Emulate for SEV guests if the insn buffer is not empty. The buffer
4569 * will be empty if the DecodeAssist microcode cannot fetch bytes for
4570 * the faulting instruction because the code fetch itself faulted, e.g.
4571 * the guest attempted to fetch from emulated MMIO or a guest page
4572 * table used to translate CS:RIP resides in emulated MMIO.
4574 if (likely(insn_len))
4578 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4581 * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is
4582 * possible that CPU microcode implementing DecodeAssist will fail to
4583 * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly
4584 * be '0'. This happens because microcode reads CS:RIP using a _data_
4585 * loap uop with CPL=0 privileges. If the load hits a SMAP #PF, ucode
4586 * gives up and does not fill the instruction bytes buffer.
4588 * As above, KVM reaches this point iff the VM is an SEV guest, the CPU
4589 * supports DecodeAssist, a #NPF was raised, KVM's page fault handler
4590 * triggered emulation (e.g. for MMIO), and the CPU returned 0 in the
4591 * GuestIntrBytes field of the VMCB.
4593 * This does _not_ mean that the erratum has been encountered, as the
4594 * DecodeAssist will also fail if the load for CS:RIP hits a legitimate
4595 * #PF, e.g. if the guest attempt to execute from emulated MMIO and
4596 * encountered a reserved/not-present #PF.
4598 * To hit the erratum, the following conditions must be true:
4599 * 1. CR4.SMAP=1 (obviously).
4600 * 2. CR4.SMEP=0 || CPL=3. If SMEP=1 and CPL<3, the erratum cannot
4601 * have been hit as the guest would have encountered a SMEP
4602 * violation #PF, not a #NPF.
4603 * 3. The #NPF is not due to a code fetch, in which case failure to
4604 * retrieve the instruction bytes is legitimate (see abvoe).
4606 * In addition, don't apply the erratum workaround if the #NPF occurred
4607 * while translating guest page tables (see below).
4609 error_code = to_svm(vcpu)->vmcb->control.exit_info_1;
4610 if (error_code & (PFERR_GUEST_PAGE_MASK | PFERR_FETCH_MASK))
4613 cr4 = kvm_read_cr4(vcpu);
4614 smep = cr4 & X86_CR4_SMEP;
4615 smap = cr4 & X86_CR4_SMAP;
4616 is_user = svm_get_cpl(vcpu) == 3;
4617 if (smap && (!smep || is_user)) {
4618 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
4621 * If the fault occurred in userspace, arbitrarily inject #GP
4622 * to avoid killing the guest and to hopefully avoid confusing
4623 * the guest kernel too much, e.g. injecting #PF would not be
4624 * coherent with respect to the guest's page tables. Request
4625 * triple fault if the fault occurred in the kernel as there's
4626 * no fault that KVM can inject without confusing the guest.
4627 * In practice, the triple fault is moot as no sane SEV kernel
4628 * will execute from user memory while also running with SMAP=1.
4631 kvm_inject_gp(vcpu, 0);
4633 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4638 * If the erratum was not hit, simply resume the guest and let it fault
4639 * again. While awful, e.g. the vCPU may get stuck in an infinite loop
4640 * if the fault is at CPL=0, it's the lesser of all evils. Exiting to
4641 * userspace will kill the guest, and letting the emulator read garbage
4642 * will yield random behavior and potentially corrupt the guest.
4644 * Simply resuming the guest is technically not a violation of the SEV
4645 * architecture. AMD's APM states that all code fetches and page table
4646 * accesses for SEV guest are encrypted, regardless of the C-Bit. The
4647 * APM also states that encrypted accesses to MMIO are "ignored", but
4648 * doesn't explicitly define "ignored", i.e. doing nothing and letting
4649 * the guest spin is technically "ignoring" the access.
4654 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4656 struct vcpu_svm *svm = to_svm(vcpu);
4658 return !gif_set(svm);
4661 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4663 if (!sev_es_guest(vcpu->kvm))
4664 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4666 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4669 static void svm_vm_destroy(struct kvm *kvm)
4671 avic_vm_destroy(kvm);
4672 sev_vm_destroy(kvm);
4675 static int svm_vm_init(struct kvm *kvm)
4677 if (!pause_filter_count || !pause_filter_thresh)
4678 kvm->arch.pause_in_guest = true;
4681 int ret = avic_vm_init(kvm);
4689 static struct kvm_x86_ops svm_x86_ops __initdata = {
4692 .hardware_unsetup = svm_hardware_unsetup,
4693 .hardware_enable = svm_hardware_enable,
4694 .hardware_disable = svm_hardware_disable,
4695 .has_emulated_msr = svm_has_emulated_msr,
4697 .vcpu_create = svm_vcpu_create,
4698 .vcpu_free = svm_vcpu_free,
4699 .vcpu_reset = svm_vcpu_reset,
4701 .vm_size = sizeof(struct kvm_svm),
4702 .vm_init = svm_vm_init,
4703 .vm_destroy = svm_vm_destroy,
4705 .prepare_switch_to_guest = svm_prepare_switch_to_guest,
4706 .vcpu_load = svm_vcpu_load,
4707 .vcpu_put = svm_vcpu_put,
4708 .vcpu_blocking = avic_vcpu_blocking,
4709 .vcpu_unblocking = avic_vcpu_unblocking,
4711 .update_exception_bitmap = svm_update_exception_bitmap,
4712 .get_msr_feature = svm_get_msr_feature,
4713 .get_msr = svm_get_msr,
4714 .set_msr = svm_set_msr,
4715 .get_segment_base = svm_get_segment_base,
4716 .get_segment = svm_get_segment,
4717 .set_segment = svm_set_segment,
4718 .get_cpl = svm_get_cpl,
4719 .get_cs_db_l_bits = svm_get_cs_db_l_bits,
4720 .set_cr0 = svm_set_cr0,
4721 .post_set_cr3 = sev_post_set_cr3,
4722 .is_valid_cr4 = svm_is_valid_cr4,
4723 .set_cr4 = svm_set_cr4,
4724 .set_efer = svm_set_efer,
4725 .get_idt = svm_get_idt,
4726 .set_idt = svm_set_idt,
4727 .get_gdt = svm_get_gdt,
4728 .set_gdt = svm_set_gdt,
4729 .set_dr7 = svm_set_dr7,
4730 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4731 .cache_reg = svm_cache_reg,
4732 .get_rflags = svm_get_rflags,
4733 .set_rflags = svm_set_rflags,
4734 .get_if_flag = svm_get_if_flag,
4736 .flush_tlb_all = svm_flush_tlb_current,
4737 .flush_tlb_current = svm_flush_tlb_current,
4738 .flush_tlb_gva = svm_flush_tlb_gva,
4739 .flush_tlb_guest = svm_flush_tlb_current,
4741 .vcpu_pre_run = svm_vcpu_pre_run,
4742 .vcpu_run = svm_vcpu_run,
4743 .handle_exit = svm_handle_exit,
4744 .skip_emulated_instruction = svm_skip_emulated_instruction,
4745 .update_emulated_instruction = NULL,
4746 .set_interrupt_shadow = svm_set_interrupt_shadow,
4747 .get_interrupt_shadow = svm_get_interrupt_shadow,
4748 .patch_hypercall = svm_patch_hypercall,
4749 .inject_irq = svm_inject_irq,
4750 .inject_nmi = svm_inject_nmi,
4751 .inject_exception = svm_inject_exception,
4752 .cancel_injection = svm_cancel_injection,
4753 .interrupt_allowed = svm_interrupt_allowed,
4754 .nmi_allowed = svm_nmi_allowed,
4755 .get_nmi_mask = svm_get_nmi_mask,
4756 .set_nmi_mask = svm_set_nmi_mask,
4757 .enable_nmi_window = svm_enable_nmi_window,
4758 .enable_irq_window = svm_enable_irq_window,
4759 .update_cr8_intercept = svm_update_cr8_intercept,
4760 .set_virtual_apic_mode = avic_refresh_virtual_apic_mode,
4761 .refresh_apicv_exec_ctrl = avic_refresh_apicv_exec_ctrl,
4762 .check_apicv_inhibit_reasons = avic_check_apicv_inhibit_reasons,
4763 .apicv_post_state_restore = avic_apicv_post_state_restore,
4765 .get_exit_info = svm_get_exit_info,
4767 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
4769 .has_wbinvd_exit = svm_has_wbinvd_exit,
4771 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
4772 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
4773 .write_tsc_offset = svm_write_tsc_offset,
4774 .write_tsc_multiplier = svm_write_tsc_multiplier,
4776 .load_mmu_pgd = svm_load_mmu_pgd,
4778 .check_intercept = svm_check_intercept,
4779 .handle_exit_irqoff = svm_handle_exit_irqoff,
4781 .request_immediate_exit = __kvm_request_immediate_exit,
4783 .sched_in = svm_sched_in,
4785 .nested_ops = &svm_nested_ops,
4787 .deliver_interrupt = svm_deliver_interrupt,
4788 .pi_update_irte = avic_pi_update_irte,
4789 .setup_mce = svm_setup_mce,
4791 .smi_allowed = svm_smi_allowed,
4792 .enter_smm = svm_enter_smm,
4793 .leave_smm = svm_leave_smm,
4794 .enable_smi_window = svm_enable_smi_window,
4796 .mem_enc_ioctl = sev_mem_enc_ioctl,
4797 .mem_enc_register_region = sev_mem_enc_register_region,
4798 .mem_enc_unregister_region = sev_mem_enc_unregister_region,
4799 .guest_memory_reclaimed = sev_guest_memory_reclaimed,
4801 .vm_copy_enc_context_from = sev_vm_copy_enc_context_from,
4802 .vm_move_enc_context_from = sev_vm_move_enc_context_from,
4804 .can_emulate_instruction = svm_can_emulate_instruction,
4806 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
4808 .msr_filter_changed = svm_msr_filter_changed,
4809 .complete_emulated_msr = svm_complete_emulated_msr,
4811 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
4812 .vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
4816 * The default MMIO mask is a single bit (excluding the present bit),
4817 * which could conflict with the memory encryption bit. Check for
4818 * memory encryption support and override the default MMIO mask if
4819 * memory encryption is enabled.
4821 static __init void svm_adjust_mmio_mask(void)
4823 unsigned int enc_bit, mask_bit;
4826 /* If there is no memory encryption support, use existing mask */
4827 if (cpuid_eax(0x80000000) < 0x8000001f)
4830 /* If memory encryption is not enabled, use existing mask */
4831 rdmsrl(MSR_AMD64_SYSCFG, msr);
4832 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
4835 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
4836 mask_bit = boot_cpu_data.x86_phys_bits;
4838 /* Increment the mask bit if it is the same as the encryption bit */
4839 if (enc_bit == mask_bit)
4843 * If the mask bit location is below 52, then some bits above the
4844 * physical addressing limit will always be reserved, so use the
4845 * rsvd_bits() function to generate the mask. This mask, along with
4846 * the present bit, will be used to generate a page fault with
4849 * If the mask bit location is 52 (or above), then clear the mask.
4851 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
4853 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
4856 static __init void svm_set_cpu_caps(void)
4860 kvm_caps.supported_xss = 0;
4862 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
4864 kvm_cpu_cap_set(X86_FEATURE_SVM);
4865 kvm_cpu_cap_set(X86_FEATURE_VMCBCLEAN);
4868 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
4871 kvm_cpu_cap_set(X86_FEATURE_NPT);
4874 kvm_cpu_cap_set(X86_FEATURE_TSCRATEMSR);
4877 kvm_cpu_cap_set(X86_FEATURE_V_VMSAVE_VMLOAD);
4879 kvm_cpu_cap_set(X86_FEATURE_LBRV);
4881 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER))
4882 kvm_cpu_cap_set(X86_FEATURE_PAUSEFILTER);
4884 if (boot_cpu_has(X86_FEATURE_PFTHRESHOLD))
4885 kvm_cpu_cap_set(X86_FEATURE_PFTHRESHOLD);
4888 kvm_cpu_cap_set(X86_FEATURE_VGIF);
4890 /* Nested VM can receive #VMEXIT instead of triggering #GP */
4891 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
4894 /* CPUID 0x80000008 */
4895 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
4896 boot_cpu_has(X86_FEATURE_AMD_SSBD))
4897 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
4899 /* AMD PMU PERFCTR_CORE CPUID */
4900 if (enable_pmu && boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
4901 kvm_cpu_cap_set(X86_FEATURE_PERFCTR_CORE);
4903 /* CPUID 0x8000001F (SME/SEV features) */
4907 static __init int svm_hardware_setup(void)
4910 struct page *iopm_pages;
4913 unsigned int order = get_order(IOPM_SIZE);
4916 * NX is required for shadow paging and for NPT if the NX huge pages
4917 * mitigation is enabled.
4919 if (!boot_cpu_has(X86_FEATURE_NX)) {
4920 pr_err_ratelimited("NX (Execute Disable) not supported\n");
4923 kvm_enable_efer_bits(EFER_NX);
4925 iopm_pages = alloc_pages(GFP_KERNEL, order);
4930 iopm_va = page_address(iopm_pages);
4931 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
4932 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
4934 init_msrpm_offsets();
4936 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
4937 XFEATURE_MASK_BNDCSR);
4939 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
4940 kvm_enable_efer_bits(EFER_FFXSR);
4943 if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
4944 tsc_scaling = false;
4946 pr_info("TSC scaling supported\n");
4947 kvm_caps.has_tsc_control = true;
4950 kvm_caps.max_tsc_scaling_ratio = SVM_TSC_RATIO_MAX;
4951 kvm_caps.tsc_scaling_ratio_frac_bits = 32;
4953 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
4955 /* Check for pause filtering support */
4956 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
4957 pause_filter_count = 0;
4958 pause_filter_thresh = 0;
4959 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
4960 pause_filter_thresh = 0;
4964 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
4965 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
4969 * KVM's MMU doesn't support using 2-level paging for itself, and thus
4970 * NPT isn't supported if the host is using 2-level paging since host
4971 * CR4 is unchanged on VMRUN.
4973 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
4974 npt_enabled = false;
4976 if (!boot_cpu_has(X86_FEATURE_NPT))
4977 npt_enabled = false;
4979 /* Force VM NPT level equal to the host's paging level */
4980 kvm_configure_mmu(npt_enabled, get_npt_level(),
4981 get_npt_level(), PG_LEVEL_1G);
4982 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
4984 /* Setup shadow_me_value and shadow_me_mask */
4985 kvm_mmu_set_me_spte_mask(sme_me_mask, sme_me_mask);
4987 svm_adjust_mmio_mask();
4990 * Note, SEV setup consumes npt_enabled and enable_mmio_caching (which
4991 * may be modified by svm_adjust_mmio_mask()).
4993 sev_hardware_setup();
4995 svm_hv_hardware_setup();
4997 for_each_possible_cpu(cpu) {
4998 r = svm_cpu_init(cpu);
5004 if (!boot_cpu_has(X86_FEATURE_NRIPS))
5008 enable_apicv = avic = avic && avic_hardware_setup(&svm_x86_ops);
5010 if (!enable_apicv) {
5011 svm_x86_ops.vcpu_blocking = NULL;
5012 svm_x86_ops.vcpu_unblocking = NULL;
5013 svm_x86_ops.vcpu_get_apicv_inhibit_reasons = NULL;
5018 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
5019 !IS_ENABLED(CONFIG_X86_64)) {
5022 pr_info("Virtual VMLOAD VMSAVE supported\n");
5026 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
5027 svm_gp_erratum_intercept = false;
5030 if (!boot_cpu_has(X86_FEATURE_VGIF))
5033 pr_info("Virtual GIF supported\n");
5037 if (!boot_cpu_has(X86_FEATURE_LBRV))
5040 pr_info("LBR virtualization supported\n");
5044 pr_info("PMU virtualization is disabled\n");
5049 * It seems that on AMD processors PTE's accessed bit is
5050 * being set by the CPU hardware before the NPF vmexit.
5051 * This is not expected behaviour and our tests fail because
5053 * A workaround here is to disable support for
5054 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
5055 * In this case userspace can know if there is support using
5056 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
5058 * If future AMD CPU models change the behaviour described above,
5059 * this variable can be changed accordingly
5061 allow_smaller_maxphyaddr = !npt_enabled;
5066 svm_hardware_unsetup();
5071 static struct kvm_x86_init_ops svm_init_ops __initdata = {
5072 .cpu_has_kvm_support = has_svm,
5073 .disabled_by_bios = is_disabled,
5074 .hardware_setup = svm_hardware_setup,
5075 .check_processor_compatibility = svm_check_processor_compat,
5077 .runtime_ops = &svm_x86_ops,
5078 .pmu_ops = &amd_pmu_ops,
5081 static int __init svm_init(void)
5085 __unused_size_checks();
5087 r = kvm_x86_vendor_init(&svm_init_ops);
5092 * Common KVM initialization _must_ come last, after this, /dev/kvm is
5093 * exposed to userspace!
5095 r = kvm_init(&svm_init_ops, sizeof(struct vcpu_svm),
5096 __alignof__(struct vcpu_svm), THIS_MODULE);
5103 kvm_x86_vendor_exit();
5107 static void __exit svm_exit(void)
5110 kvm_x86_vendor_exit();
5113 module_init(svm_init)
5114 module_exit(svm_exit)