1 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
2
3 #include <linux/kvm_host.h>
4
5 #include "irq.h"
6 #include "mmu.h"
7 #include "kvm_cache_regs.h"
8 #include "x86.h"
9 #include "smm.h"
10 #include "cpuid.h"
11 #include "pmu.h"
12
13 #include <linux/module.h>
14 #include <linux/mod_devicetable.h>
15 #include <linux/kernel.h>
16 #include <linux/vmalloc.h>
17 #include <linux/highmem.h>
18 #include <linux/amd-iommu.h>
19 #include <linux/sched.h>
20 #include <linux/trace_events.h>
21 #include <linux/slab.h>
22 #include <linux/hashtable.h>
23 #include <linux/objtool.h>
24 #include <linux/psp-sev.h>
25 #include <linux/file.h>
26 #include <linux/pagemap.h>
27 #include <linux/swap.h>
28 #include <linux/rwsem.h>
29 #include <linux/cc_platform.h>
30 #include <linux/smp.h>
31
32 #include <asm/apic.h>
33 #include <asm/perf_event.h>
34 #include <asm/tlbflush.h>
35 #include <asm/desc.h>
36 #include <asm/debugreg.h>
37 #include <asm/kvm_para.h>
38 #include <asm/irq_remapping.h>
39 #include <asm/spec-ctrl.h>
40 #include <asm/cpu_device_id.h>
41 #include <asm/traps.h>
42 #include <asm/reboot.h>
43 #include <asm/fpu/api.h>
44
45 #include <trace/events/ipi.h>
46
47 #include "trace.h"
48
49 #include "svm.h"
50 #include "svm_ops.h"
51
52 #include "kvm_onhyperv.h"
53 #include "svm_onhyperv.h"
54
55 MODULE_AUTHOR("Qumranet");
56 MODULE_LICENSE("GPL");
57
58 #ifdef MODULE
59 static const struct x86_cpu_id svm_cpu_id[] = {
60 X86_MATCH_FEATURE(X86_FEATURE_SVM, NULL),
61 {}
62 };
63 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
64 #endif
65
66 #define SEG_TYPE_LDT 2
67 #define SEG_TYPE_BUSY_TSS16 3
68
69 static bool erratum_383_found __read_mostly;
70
71 u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
72
73 /*
74 * Set osvw_len to higher value when updated Revision Guides
75 * are published and we know what the new status bits are
76 */
77 static uint64_t osvw_len = 4, osvw_status;
78
79 static DEFINE_PER_CPU(u64, current_tsc_ratio);
80
81 #define X2APIC_MSR(x) (APIC_BASE_MSR + (x >> 4))
82
83 static const struct svm_direct_access_msrs {
84 u32 index; /* Index of the MSR */
85 bool always; /* True if intercept is initially cleared */
86 } direct_access_msrs[MAX_DIRECT_ACCESS_MSRS] = {
87 { .index = MSR_STAR, .always = true },
88 { .index = MSR_IA32_SYSENTER_CS, .always = true },
89 { .index = MSR_IA32_SYSENTER_EIP, .always = false },
90 { .index = MSR_IA32_SYSENTER_ESP, .always = false },
91 #ifdef CONFIG_X86_64
92 { .index = MSR_GS_BASE, .always = true },
93 { .index = MSR_FS_BASE, .always = true },
94 { .index = MSR_KERNEL_GS_BASE, .always = true },
95 { .index = MSR_LSTAR, .always = true },
96 { .index = MSR_CSTAR, .always = true },
97 { .index = MSR_SYSCALL_MASK, .always = true },
98 #endif
99 { .index = MSR_IA32_SPEC_CTRL, .always = false },
100 { .index = MSR_IA32_PRED_CMD, .always = false },
101 { .index = MSR_IA32_FLUSH_CMD, .always = false },
102 { .index = MSR_IA32_DEBUGCTLMSR, .always = false },
103 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
104 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
105 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
106 { .index = MSR_IA32_LASTINTTOIP, .always = false },
107 { .index = MSR_IA32_XSS, .always = false },
108 { .index = MSR_EFER, .always = false },
109 { .index = MSR_IA32_CR_PAT, .always = false },
110 { .index = MSR_AMD64_SEV_ES_GHCB, .always = true },
111 { .index = MSR_TSC_AUX, .always = false },
112 { .index = X2APIC_MSR(APIC_ID), .always = false },
113 { .index = X2APIC_MSR(APIC_LVR), .always = false },
114 { .index = X2APIC_MSR(APIC_TASKPRI), .always = false },
115 { .index = X2APIC_MSR(APIC_ARBPRI), .always = false },
116 { .index = X2APIC_MSR(APIC_PROCPRI), .always = false },
117 { .index = X2APIC_MSR(APIC_EOI), .always = false },
118 { .index = X2APIC_MSR(APIC_RRR), .always = false },
119 { .index = X2APIC_MSR(APIC_LDR), .always = false },
120 { .index = X2APIC_MSR(APIC_DFR), .always = false },
121 { .index = X2APIC_MSR(APIC_SPIV), .always = false },
122 { .index = X2APIC_MSR(APIC_ISR), .always = false },
123 { .index = X2APIC_MSR(APIC_TMR), .always = false },
124 { .index = X2APIC_MSR(APIC_IRR), .always = false },
125 { .index = X2APIC_MSR(APIC_ESR), .always = false },
126 { .index = X2APIC_MSR(APIC_ICR), .always = false },
127 { .index = X2APIC_MSR(APIC_ICR2), .always = false },
128
129 /*
130 * Note:
131 * AMD does not virtualize APIC TSC-deadline timer mode, but it is
132 * emulated by KVM. When setting APIC LVTT (0x832) register bit 18,
133 * the AVIC hardware would generate GP fault. Therefore, always
134 * intercept the MSR 0x832, and do not setup direct_access_msr.
135 */
136 { .index = X2APIC_MSR(APIC_LVTTHMR), .always = false },
137 { .index = X2APIC_MSR(APIC_LVTPC), .always = false },
138 { .index = X2APIC_MSR(APIC_LVT0), .always = false },
139 { .index = X2APIC_MSR(APIC_LVT1), .always = false },
140 { .index = X2APIC_MSR(APIC_LVTERR), .always = false },
141 { .index = X2APIC_MSR(APIC_TMICT), .always = false },
142 { .index = X2APIC_MSR(APIC_TMCCT), .always = false },
143 { .index = X2APIC_MSR(APIC_TDCR), .always = false },
144 { .index = MSR_INVALID, .always = false },
145 };
146
147 /*
148 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
149 * pause_filter_count: On processors that support Pause filtering(indicated
150 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
151 * count value. On VMRUN this value is loaded into an internal counter.
152 * Each time a pause instruction is executed, this counter is decremented
153 * until it reaches zero at which time a #VMEXIT is generated if pause
154 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
155 * Intercept Filtering for more details.
156 * This also indicate if ple logic enabled.
157 *
158 * pause_filter_thresh: In addition, some processor families support advanced
159 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
160 * the amount of time a guest is allowed to execute in a pause loop.
161 * In this mode, a 16-bit pause filter threshold field is added in the
162 * VMCB. The threshold value is a cycle count that is used to reset the
163 * pause counter. As with simple pause filtering, VMRUN loads the pause
164 * count value from VMCB into an internal counter. Then, on each pause
165 * instruction the hardware checks the elapsed number of cycles since
166 * the most recent pause instruction against the pause filter threshold.
167 * If the elapsed cycle count is greater than the pause filter threshold,
168 * then the internal pause count is reloaded from the VMCB and execution
169 * continues. If the elapsed cycle count is less than the pause filter
170 * threshold, then the internal pause count is decremented. If the count
171 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
172 * triggered. If advanced pause filtering is supported and pause filter
173 * threshold field is set to zero, the filter will operate in the simpler,
174 * count only mode.
175 */
176
177 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
178 module_param(pause_filter_thresh, ushort, 0444);
179
180 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
181 module_param(pause_filter_count, ushort, 0444);
182
183 /* Default doubles per-vcpu window every exit. */
184 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
185 module_param(pause_filter_count_grow, ushort, 0444);
186
187 /* Default resets per-vcpu window every exit to pause_filter_count. */
188 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
189 module_param(pause_filter_count_shrink, ushort, 0444);
190
191 /* Default is to compute the maximum so we can never overflow. */
192 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
193 module_param(pause_filter_count_max, ushort, 0444);
194
195 /*
196 * Use nested page tables by default. Note, NPT may get forced off by
197 * svm_hardware_setup() if it's unsupported by hardware or the host kernel.
198 */
199 bool npt_enabled = true;
200 module_param_named(npt, npt_enabled, bool, 0444);
201
202 /* allow nested virtualization in KVM/SVM */
203 static int nested = true;
204 module_param(nested, int, S_IRUGO);
205
206 /* enable/disable Next RIP Save */
207 int nrips = true;
208 module_param(nrips, int, 0444);
209
210 /* enable/disable Virtual VMLOAD VMSAVE */
211 static int vls = true;
212 module_param(vls, int, 0444);
213
214 /* enable/disable Virtual GIF */
215 int vgif = true;
216 module_param(vgif, int, 0444);
217
218 /* enable/disable LBR virtualization */
219 int lbrv = true;
220 module_param(lbrv, int, 0444);
221
222 static int tsc_scaling = true;
223 module_param(tsc_scaling, int, 0444);
224
225 /*
226 * enable / disable AVIC. Because the defaults differ for APICv
227 * support between VMX and SVM we cannot use module_param_named.
228 */
229 static bool avic;
230 module_param(avic, bool, 0444);
231
232 bool __read_mostly dump_invalid_vmcb;
233 module_param(dump_invalid_vmcb, bool, 0644);
234
235
236 bool intercept_smi = true;
237 module_param(intercept_smi, bool, 0444);
238
239 bool vnmi = true;
240 module_param(vnmi, bool, 0444);
241
242 static bool svm_gp_erratum_intercept = true;
243
244 static u8 rsm_ins_bytes[] = "\x0f\xaa";
245
246 static unsigned long iopm_base;
247
248 DEFINE_PER_CPU(struct svm_cpu_data, svm_data);
249
250 /*
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.
253 *
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.
256 */
257 static int tsc_aux_uret_slot __read_mostly = -1;
258
259 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
260
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)
264
svm_msrpm_offset(u32 msr)265 u32 svm_msrpm_offset(u32 msr)
266 {
267 u32 offset;
268 int i;
269
270 for (i = 0; i < NUM_MSR_MAPS; i++) {
271 if (msr < msrpm_ranges[i] ||
272 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
273 continue;
274
275 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
276 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
277
278 /* Now we have the u8 offset - but need the u32 offset */
279 return offset / 4;
280 }
281
282 /* MSR not in any range */
283 return MSR_INVALID;
284 }
285
286 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu);
287
get_npt_level(void)288 static int get_npt_level(void)
289 {
290 #ifdef CONFIG_X86_64
291 return pgtable_l5_enabled() ? PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
292 #else
293 return PT32E_ROOT_LEVEL;
294 #endif
295 }
296
svm_set_efer(struct kvm_vcpu * vcpu,u64 efer)297 int svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
298 {
299 struct vcpu_svm *svm = to_svm(vcpu);
300 u64 old_efer = vcpu->arch.efer;
301 vcpu->arch.efer = efer;
302
303 if (!npt_enabled) {
304 /* Shadow paging assumes NX to be available. */
305 efer |= EFER_NX;
306
307 if (!(efer & EFER_LMA))
308 efer &= ~EFER_LME;
309 }
310
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);
318
319 /*
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.
323 */
324 if (!is_smm(vcpu))
325 svm_free_nested(svm);
326
327 } else {
328 int ret = svm_allocate_nested(svm);
329
330 if (ret) {
331 vcpu->arch.efer = old_efer;
332 return ret;
333 }
334
335 /*
336 * Never intercept #GP for SEV guests, KVM can't
337 * decrypt guest memory to workaround the erratum.
338 */
339 if (svm_gp_erratum_intercept && !sev_guest(vcpu->kvm))
340 set_exception_intercept(svm, GP_VECTOR);
341 }
342 }
343
344 svm->vmcb->save.efer = efer | EFER_SVME;
345 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
346 return 0;
347 }
348
svm_get_interrupt_shadow(struct kvm_vcpu * vcpu)349 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
350 {
351 struct vcpu_svm *svm = to_svm(vcpu);
352 u32 ret = 0;
353
354 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
355 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
356 return ret;
357 }
358
svm_set_interrupt_shadow(struct kvm_vcpu * vcpu,int mask)359 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
360 {
361 struct vcpu_svm *svm = to_svm(vcpu);
362
363 if (mask == 0)
364 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
365 else
366 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
367
368 }
369 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
370 void *insn, int insn_len);
371
__svm_skip_emulated_instruction(struct kvm_vcpu * vcpu,bool commit_side_effects)372 static int __svm_skip_emulated_instruction(struct kvm_vcpu *vcpu,
373 bool commit_side_effects)
374 {
375 struct vcpu_svm *svm = to_svm(vcpu);
376 unsigned long old_rflags;
377
378 /*
379 * SEV-ES does not expose the next RIP. The RIP update is controlled by
380 * the type of exit and the #VC handler in the guest.
381 */
382 if (sev_es_guest(vcpu->kvm))
383 goto done;
384
385 if (nrips && svm->vmcb->control.next_rip != 0) {
386 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
387 svm->next_rip = svm->vmcb->control.next_rip;
388 }
389
390 if (!svm->next_rip) {
391 /*
392 * FIXME: Drop this when kvm_emulate_instruction() does the
393 * right thing and treats "can't emulate" as outright failure
394 * for EMULTYPE_SKIP.
395 */
396 if (!svm_can_emulate_instruction(vcpu, EMULTYPE_SKIP, NULL, 0))
397 return 0;
398
399 if (unlikely(!commit_side_effects))
400 old_rflags = svm->vmcb->save.rflags;
401
402 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
403 return 0;
404
405 if (unlikely(!commit_side_effects))
406 svm->vmcb->save.rflags = old_rflags;
407 } else {
408 kvm_rip_write(vcpu, svm->next_rip);
409 }
410
411 done:
412 if (likely(commit_side_effects))
413 svm_set_interrupt_shadow(vcpu, 0);
414
415 return 1;
416 }
417
svm_skip_emulated_instruction(struct kvm_vcpu * vcpu)418 static int svm_skip_emulated_instruction(struct kvm_vcpu *vcpu)
419 {
420 return __svm_skip_emulated_instruction(vcpu, true);
421 }
422
svm_update_soft_interrupt_rip(struct kvm_vcpu * vcpu)423 static int svm_update_soft_interrupt_rip(struct kvm_vcpu *vcpu)
424 {
425 unsigned long rip, old_rip = kvm_rip_read(vcpu);
426 struct vcpu_svm *svm = to_svm(vcpu);
427
428 /*
429 * Due to architectural shortcomings, the CPU doesn't always provide
430 * NextRIP, e.g. if KVM intercepted an exception that occurred while
431 * the CPU was vectoring an INTO/INT3 in the guest. Temporarily skip
432 * the instruction even if NextRIP is supported to acquire the next
433 * RIP so that it can be shoved into the NextRIP field, otherwise
434 * hardware will fail to advance guest RIP during event injection.
435 * Drop the exception/interrupt if emulation fails and effectively
436 * retry the instruction, it's the least awful option. If NRIPS is
437 * in use, the skip must not commit any side effects such as clearing
438 * the interrupt shadow or RFLAGS.RF.
439 */
440 if (!__svm_skip_emulated_instruction(vcpu, !nrips))
441 return -EIO;
442
443 rip = kvm_rip_read(vcpu);
444
445 /*
446 * Save the injection information, even when using next_rip, as the
447 * VMCB's next_rip will be lost (cleared on VM-Exit) if the injection
448 * doesn't complete due to a VM-Exit occurring while the CPU is
449 * vectoring the event. Decoding the instruction isn't guaranteed to
450 * work as there may be no backing instruction, e.g. if the event is
451 * being injected by L1 for L2, or if the guest is patching INT3 into
452 * a different instruction.
453 */
454 svm->soft_int_injected = true;
455 svm->soft_int_csbase = svm->vmcb->save.cs.base;
456 svm->soft_int_old_rip = old_rip;
457 svm->soft_int_next_rip = rip;
458
459 if (nrips)
460 kvm_rip_write(vcpu, old_rip);
461
462 if (static_cpu_has(X86_FEATURE_NRIPS))
463 svm->vmcb->control.next_rip = rip;
464
465 return 0;
466 }
467
svm_inject_exception(struct kvm_vcpu * vcpu)468 static void svm_inject_exception(struct kvm_vcpu *vcpu)
469 {
470 struct kvm_queued_exception *ex = &vcpu->arch.exception;
471 struct vcpu_svm *svm = to_svm(vcpu);
472
473 kvm_deliver_exception_payload(vcpu, ex);
474
475 if (kvm_exception_is_soft(ex->vector) &&
476 svm_update_soft_interrupt_rip(vcpu))
477 return;
478
479 svm->vmcb->control.event_inj = ex->vector
480 | SVM_EVTINJ_VALID
481 | (ex->has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
482 | SVM_EVTINJ_TYPE_EXEPT;
483 svm->vmcb->control.event_inj_err = ex->error_code;
484 }
485
svm_init_erratum_383(void)486 static void svm_init_erratum_383(void)
487 {
488 u32 low, high;
489 int err;
490 u64 val;
491
492 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
493 return;
494
495 /* Use _safe variants to not break nested virtualization */
496 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
497 if (err)
498 return;
499
500 val |= (1ULL << 47);
501
502 low = lower_32_bits(val);
503 high = upper_32_bits(val);
504
505 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
506
507 erratum_383_found = true;
508 }
509
svm_init_osvw(struct kvm_vcpu * vcpu)510 static void svm_init_osvw(struct kvm_vcpu *vcpu)
511 {
512 /*
513 * Guests should see errata 400 and 415 as fixed (assuming that
514 * HLT and IO instructions are intercepted).
515 */
516 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
517 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
518
519 /*
520 * By increasing VCPU's osvw.length to 3 we are telling the guest that
521 * all osvw.status bits inside that length, including bit 0 (which is
522 * reserved for erratum 298), are valid. However, if host processor's
523 * osvw_len is 0 then osvw_status[0] carries no information. We need to
524 * be conservative here and therefore we tell the guest that erratum 298
525 * is present (because we really don't know).
526 */
527 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
528 vcpu->arch.osvw.status |= 1;
529 }
530
__kvm_is_svm_supported(void)531 static bool __kvm_is_svm_supported(void)
532 {
533 int cpu = smp_processor_id();
534 struct cpuinfo_x86 *c = &cpu_data(cpu);
535
536 u64 vm_cr;
537
538 if (c->x86_vendor != X86_VENDOR_AMD &&
539 c->x86_vendor != X86_VENDOR_HYGON) {
540 pr_err("CPU %d isn't AMD or Hygon\n", cpu);
541 return false;
542 }
543
544 if (!cpu_has(c, X86_FEATURE_SVM)) {
545 pr_err("SVM not supported by CPU %d\n", cpu);
546 return false;
547 }
548
549 if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
550 pr_info("KVM is unsupported when running as an SEV guest\n");
551 return false;
552 }
553
554 rdmsrl(MSR_VM_CR, vm_cr);
555 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE)) {
556 pr_err("SVM disabled (by BIOS) in MSR_VM_CR on CPU %d\n", cpu);
557 return false;
558 }
559
560 return true;
561 }
562
kvm_is_svm_supported(void)563 static bool kvm_is_svm_supported(void)
564 {
565 bool supported;
566
567 migrate_disable();
568 supported = __kvm_is_svm_supported();
569 migrate_enable();
570
571 return supported;
572 }
573
svm_check_processor_compat(void)574 static int svm_check_processor_compat(void)
575 {
576 if (!__kvm_is_svm_supported())
577 return -EIO;
578
579 return 0;
580 }
581
__svm_write_tsc_multiplier(u64 multiplier)582 static void __svm_write_tsc_multiplier(u64 multiplier)
583 {
584 if (multiplier == __this_cpu_read(current_tsc_ratio))
585 return;
586
587 wrmsrl(MSR_AMD64_TSC_RATIO, multiplier);
588 __this_cpu_write(current_tsc_ratio, multiplier);
589 }
590
kvm_cpu_svm_disable(void)591 static inline void kvm_cpu_svm_disable(void)
592 {
593 uint64_t efer;
594
595 wrmsrl(MSR_VM_HSAVE_PA, 0);
596 rdmsrl(MSR_EFER, efer);
597 if (efer & EFER_SVME) {
598 /*
599 * Force GIF=1 prior to disabling SVM, e.g. to ensure INIT and
600 * NMI aren't blocked.
601 */
602 stgi();
603 wrmsrl(MSR_EFER, efer & ~EFER_SVME);
604 }
605 }
606
svm_emergency_disable(void)607 static void svm_emergency_disable(void)
608 {
609 kvm_rebooting = true;
610
611 kvm_cpu_svm_disable();
612 }
613
svm_hardware_disable(void)614 static void svm_hardware_disable(void)
615 {
616 /* Make sure we clean up behind us */
617 if (tsc_scaling)
618 __svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
619
620 kvm_cpu_svm_disable();
621
622 amd_pmu_disable_virt();
623 }
624
svm_hardware_enable(void)625 static int svm_hardware_enable(void)
626 {
627
628 struct svm_cpu_data *sd;
629 uint64_t efer;
630 int me = raw_smp_processor_id();
631
632 rdmsrl(MSR_EFER, efer);
633 if (efer & EFER_SVME)
634 return -EBUSY;
635
636 sd = per_cpu_ptr(&svm_data, me);
637 sd->asid_generation = 1;
638 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
639 sd->next_asid = sd->max_asid + 1;
640 sd->min_asid = max_sev_asid + 1;
641
642 wrmsrl(MSR_EFER, efer | EFER_SVME);
643
644 wrmsrl(MSR_VM_HSAVE_PA, sd->save_area_pa);
645
646 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
647 /*
648 * Set the default value, even if we don't use TSC scaling
649 * to avoid having stale value in the msr
650 */
651 __svm_write_tsc_multiplier(SVM_TSC_RATIO_DEFAULT);
652 }
653
654
655 /*
656 * Get OSVW bits.
657 *
658 * Note that it is possible to have a system with mixed processor
659 * revisions and therefore different OSVW bits. If bits are not the same
660 * on different processors then choose the worst case (i.e. if erratum
661 * is present on one processor and not on another then assume that the
662 * erratum is present everywhere).
663 */
664 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
665 uint64_t len, status = 0;
666 int err;
667
668 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
669 if (!err)
670 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
671 &err);
672
673 if (err)
674 osvw_status = osvw_len = 0;
675 else {
676 if (len < osvw_len)
677 osvw_len = len;
678 osvw_status |= status;
679 osvw_status &= (1ULL << osvw_len) - 1;
680 }
681 } else
682 osvw_status = osvw_len = 0;
683
684 svm_init_erratum_383();
685
686 amd_pmu_enable_virt();
687
688 /*
689 * If TSC_AUX virtualization is supported, TSC_AUX becomes a swap type
690 * "B" field (see sev_es_prepare_switch_to_guest()) for SEV-ES guests.
691 * Since Linux does not change the value of TSC_AUX once set, prime the
692 * TSC_AUX field now to avoid a RDMSR on every vCPU run.
693 */
694 if (boot_cpu_has(X86_FEATURE_V_TSC_AUX)) {
695 struct sev_es_save_area *hostsa;
696 u32 __maybe_unused msr_hi;
697
698 hostsa = (struct sev_es_save_area *)(page_address(sd->save_area) + 0x400);
699
700 rdmsr(MSR_TSC_AUX, hostsa->tsc_aux, msr_hi);
701 }
702
703 return 0;
704 }
705
svm_cpu_uninit(int cpu)706 static void svm_cpu_uninit(int cpu)
707 {
708 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
709
710 if (!sd->save_area)
711 return;
712
713 kfree(sd->sev_vmcbs);
714 __free_page(sd->save_area);
715 sd->save_area_pa = 0;
716 sd->save_area = NULL;
717 }
718
svm_cpu_init(int cpu)719 static int svm_cpu_init(int cpu)
720 {
721 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
722 int ret = -ENOMEM;
723
724 memset(sd, 0, sizeof(struct svm_cpu_data));
725 sd->save_area = alloc_page(GFP_KERNEL | __GFP_ZERO);
726 if (!sd->save_area)
727 return ret;
728
729 ret = sev_cpu_init(sd);
730 if (ret)
731 goto free_save_area;
732
733 sd->save_area_pa = __sme_page_pa(sd->save_area);
734 return 0;
735
736 free_save_area:
737 __free_page(sd->save_area);
738 sd->save_area = NULL;
739 return ret;
740
741 }
742
set_dr_intercepts(struct vcpu_svm * svm)743 static void set_dr_intercepts(struct vcpu_svm *svm)
744 {
745 struct vmcb *vmcb = svm->vmcb01.ptr;
746
747 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR0_READ);
748 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR1_READ);
749 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR2_READ);
750 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR3_READ);
751 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR4_READ);
752 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR5_READ);
753 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR6_READ);
754 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR0_WRITE);
755 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR1_WRITE);
756 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR2_WRITE);
757 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR3_WRITE);
758 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR4_WRITE);
759 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR5_WRITE);
760 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR6_WRITE);
761 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_READ);
762 vmcb_set_intercept(&vmcb->control, INTERCEPT_DR7_WRITE);
763
764 recalc_intercepts(svm);
765 }
766
clr_dr_intercepts(struct vcpu_svm * svm)767 static void clr_dr_intercepts(struct vcpu_svm *svm)
768 {
769 struct vmcb *vmcb = svm->vmcb01.ptr;
770
771 vmcb->control.intercepts[INTERCEPT_DR] = 0;
772
773 recalc_intercepts(svm);
774 }
775
direct_access_msr_slot(u32 msr)776 static int direct_access_msr_slot(u32 msr)
777 {
778 u32 i;
779
780 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
781 if (direct_access_msrs[i].index == msr)
782 return i;
783
784 return -ENOENT;
785 }
786
set_shadow_msr_intercept(struct kvm_vcpu * vcpu,u32 msr,int read,int write)787 static void set_shadow_msr_intercept(struct kvm_vcpu *vcpu, u32 msr, int read,
788 int write)
789 {
790 struct vcpu_svm *svm = to_svm(vcpu);
791 int slot = direct_access_msr_slot(msr);
792
793 if (slot == -ENOENT)
794 return;
795
796 /* Set the shadow bitmaps to the desired intercept states */
797 if (read)
798 set_bit(slot, svm->shadow_msr_intercept.read);
799 else
800 clear_bit(slot, svm->shadow_msr_intercept.read);
801
802 if (write)
803 set_bit(slot, svm->shadow_msr_intercept.write);
804 else
805 clear_bit(slot, svm->shadow_msr_intercept.write);
806 }
807
valid_msr_intercept(u32 index)808 static bool valid_msr_intercept(u32 index)
809 {
810 return direct_access_msr_slot(index) != -ENOENT;
811 }
812
msr_write_intercepted(struct kvm_vcpu * vcpu,u32 msr)813 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
814 {
815 u8 bit_write;
816 unsigned long tmp;
817 u32 offset;
818 u32 *msrpm;
819
820 /*
821 * For non-nested case:
822 * If the L01 MSR bitmap does not intercept the MSR, then we need to
823 * save it.
824 *
825 * For nested case:
826 * If the L02 MSR bitmap does not intercept the MSR, then we need to
827 * save it.
828 */
829 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
830 to_svm(vcpu)->msrpm;
831
832 offset = svm_msrpm_offset(msr);
833 bit_write = 2 * (msr & 0x0f) + 1;
834 tmp = msrpm[offset];
835
836 BUG_ON(offset == MSR_INVALID);
837
838 return test_bit(bit_write, &tmp);
839 }
840
set_msr_interception_bitmap(struct kvm_vcpu * vcpu,u32 * msrpm,u32 msr,int read,int write)841 static void set_msr_interception_bitmap(struct kvm_vcpu *vcpu, u32 *msrpm,
842 u32 msr, int read, int write)
843 {
844 struct vcpu_svm *svm = to_svm(vcpu);
845 u8 bit_read, bit_write;
846 unsigned long tmp;
847 u32 offset;
848
849 /*
850 * If this warning triggers extend the direct_access_msrs list at the
851 * beginning of the file
852 */
853 WARN_ON(!valid_msr_intercept(msr));
854
855 /* Enforce non allowed MSRs to trap */
856 if (read && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_READ))
857 read = 0;
858
859 if (write && !kvm_msr_allowed(vcpu, msr, KVM_MSR_FILTER_WRITE))
860 write = 0;
861
862 offset = svm_msrpm_offset(msr);
863 bit_read = 2 * (msr & 0x0f);
864 bit_write = 2 * (msr & 0x0f) + 1;
865 tmp = msrpm[offset];
866
867 BUG_ON(offset == MSR_INVALID);
868
869 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
870 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
871
872 msrpm[offset] = tmp;
873
874 svm_hv_vmcb_dirty_nested_enlightenments(vcpu);
875 svm->nested.force_msr_bitmap_recalc = true;
876 }
877
set_msr_interception(struct kvm_vcpu * vcpu,u32 * msrpm,u32 msr,int read,int write)878 void set_msr_interception(struct kvm_vcpu *vcpu, u32 *msrpm, u32 msr,
879 int read, int write)
880 {
881 set_shadow_msr_intercept(vcpu, msr, read, write);
882 set_msr_interception_bitmap(vcpu, msrpm, msr, read, write);
883 }
884
svm_vcpu_alloc_msrpm(void)885 u32 *svm_vcpu_alloc_msrpm(void)
886 {
887 unsigned int order = get_order(MSRPM_SIZE);
888 struct page *pages = alloc_pages(GFP_KERNEL_ACCOUNT, order);
889 u32 *msrpm;
890
891 if (!pages)
892 return NULL;
893
894 msrpm = page_address(pages);
895 memset(msrpm, 0xff, PAGE_SIZE * (1 << order));
896
897 return msrpm;
898 }
899
svm_vcpu_init_msrpm(struct kvm_vcpu * vcpu,u32 * msrpm)900 void svm_vcpu_init_msrpm(struct kvm_vcpu *vcpu, u32 *msrpm)
901 {
902 int i;
903
904 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
905 if (!direct_access_msrs[i].always)
906 continue;
907 set_msr_interception(vcpu, msrpm, direct_access_msrs[i].index, 1, 1);
908 }
909 }
910
svm_set_x2apic_msr_interception(struct vcpu_svm * svm,bool intercept)911 void svm_set_x2apic_msr_interception(struct vcpu_svm *svm, bool intercept)
912 {
913 int i;
914
915 if (intercept == svm->x2avic_msrs_intercepted)
916 return;
917
918 if (!x2avic_enabled)
919 return;
920
921 for (i = 0; i < MAX_DIRECT_ACCESS_MSRS; i++) {
922 int index = direct_access_msrs[i].index;
923
924 if ((index < APIC_BASE_MSR) ||
925 (index > APIC_BASE_MSR + 0xff))
926 continue;
927 set_msr_interception(&svm->vcpu, svm->msrpm, index,
928 !intercept, !intercept);
929 }
930
931 svm->x2avic_msrs_intercepted = intercept;
932 }
933
svm_vcpu_free_msrpm(u32 * msrpm)934 void svm_vcpu_free_msrpm(u32 *msrpm)
935 {
936 __free_pages(virt_to_page(msrpm), get_order(MSRPM_SIZE));
937 }
938
svm_msr_filter_changed(struct kvm_vcpu * vcpu)939 static void svm_msr_filter_changed(struct kvm_vcpu *vcpu)
940 {
941 struct vcpu_svm *svm = to_svm(vcpu);
942 u32 i;
943
944 /*
945 * Set intercept permissions for all direct access MSRs again. They
946 * will automatically get filtered through the MSR filter, so we are
947 * back in sync after this.
948 */
949 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
950 u32 msr = direct_access_msrs[i].index;
951 u32 read = test_bit(i, svm->shadow_msr_intercept.read);
952 u32 write = test_bit(i, svm->shadow_msr_intercept.write);
953
954 set_msr_interception_bitmap(vcpu, svm->msrpm, msr, read, write);
955 }
956 }
957
add_msr_offset(u32 offset)958 static void add_msr_offset(u32 offset)
959 {
960 int i;
961
962 for (i = 0; i < MSRPM_OFFSETS; ++i) {
963
964 /* Offset already in list? */
965 if (msrpm_offsets[i] == offset)
966 return;
967
968 /* Slot used by another offset? */
969 if (msrpm_offsets[i] != MSR_INVALID)
970 continue;
971
972 /* Add offset to list */
973 msrpm_offsets[i] = offset;
974
975 return;
976 }
977
978 /*
979 * If this BUG triggers the msrpm_offsets table has an overflow. Just
980 * increase MSRPM_OFFSETS in this case.
981 */
982 BUG();
983 }
984
init_msrpm_offsets(void)985 static void init_msrpm_offsets(void)
986 {
987 int i;
988
989 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
990
991 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
992 u32 offset;
993
994 offset = svm_msrpm_offset(direct_access_msrs[i].index);
995 BUG_ON(offset == MSR_INVALID);
996
997 add_msr_offset(offset);
998 }
999 }
1000
svm_copy_lbrs(struct vmcb * to_vmcb,struct vmcb * from_vmcb)1001 void svm_copy_lbrs(struct vmcb *to_vmcb, struct vmcb *from_vmcb)
1002 {
1003 to_vmcb->save.dbgctl = from_vmcb->save.dbgctl;
1004 to_vmcb->save.br_from = from_vmcb->save.br_from;
1005 to_vmcb->save.br_to = from_vmcb->save.br_to;
1006 to_vmcb->save.last_excp_from = from_vmcb->save.last_excp_from;
1007 to_vmcb->save.last_excp_to = from_vmcb->save.last_excp_to;
1008
1009 vmcb_mark_dirty(to_vmcb, VMCB_LBR);
1010 }
1011
svm_enable_lbrv(struct kvm_vcpu * vcpu)1012 void svm_enable_lbrv(struct kvm_vcpu *vcpu)
1013 {
1014 struct vcpu_svm *svm = to_svm(vcpu);
1015
1016 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1017 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1018 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1019 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1020 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1021
1022 if (sev_es_guest(vcpu->kvm))
1023 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_DEBUGCTLMSR, 1, 1);
1024
1025 /* Move the LBR msrs to the vmcb02 so that the guest can see them. */
1026 if (is_guest_mode(vcpu))
1027 svm_copy_lbrs(svm->vmcb, svm->vmcb01.ptr);
1028 }
1029
svm_disable_lbrv(struct kvm_vcpu * vcpu)1030 static void svm_disable_lbrv(struct kvm_vcpu *vcpu)
1031 {
1032 struct vcpu_svm *svm = to_svm(vcpu);
1033
1034 KVM_BUG_ON(sev_es_guest(vcpu->kvm), vcpu->kvm);
1035
1036 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1037 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1038 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1039 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1040 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1041
1042 /*
1043 * Move the LBR msrs back to the vmcb01 to avoid copying them
1044 * on nested guest entries.
1045 */
1046 if (is_guest_mode(vcpu))
1047 svm_copy_lbrs(svm->vmcb01.ptr, svm->vmcb);
1048 }
1049
svm_get_lbr_vmcb(struct vcpu_svm * svm)1050 static struct vmcb *svm_get_lbr_vmcb(struct vcpu_svm *svm)
1051 {
1052 /*
1053 * If LBR virtualization is disabled, the LBR MSRs are always kept in
1054 * vmcb01. If LBR virtualization is enabled and L1 is running VMs of
1055 * its own, the MSRs are moved between vmcb01 and vmcb02 as needed.
1056 */
1057 return svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK ? svm->vmcb :
1058 svm->vmcb01.ptr;
1059 }
1060
svm_update_lbrv(struct kvm_vcpu * vcpu)1061 void svm_update_lbrv(struct kvm_vcpu *vcpu)
1062 {
1063 struct vcpu_svm *svm = to_svm(vcpu);
1064 bool current_enable_lbrv = svm->vmcb->control.virt_ext & LBR_CTL_ENABLE_MASK;
1065 bool enable_lbrv = (svm_get_lbr_vmcb(svm)->save.dbgctl & DEBUGCTLMSR_LBR) ||
1066 (is_guest_mode(vcpu) && guest_can_use(vcpu, X86_FEATURE_LBRV) &&
1067 (svm->nested.ctl.virt_ext & LBR_CTL_ENABLE_MASK));
1068
1069 if (enable_lbrv == current_enable_lbrv)
1070 return;
1071
1072 if (enable_lbrv)
1073 svm_enable_lbrv(vcpu);
1074 else
1075 svm_disable_lbrv(vcpu);
1076 }
1077
disable_nmi_singlestep(struct vcpu_svm * svm)1078 void disable_nmi_singlestep(struct vcpu_svm *svm)
1079 {
1080 svm->nmi_singlestep = false;
1081
1082 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1083 /* Clear our flags if they were not set by the guest */
1084 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1085 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1086 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1087 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1088 }
1089 }
1090
grow_ple_window(struct kvm_vcpu * vcpu)1091 static void grow_ple_window(struct kvm_vcpu *vcpu)
1092 {
1093 struct vcpu_svm *svm = to_svm(vcpu);
1094 struct vmcb_control_area *control = &svm->vmcb->control;
1095 int old = control->pause_filter_count;
1096
1097 if (kvm_pause_in_guest(vcpu->kvm))
1098 return;
1099
1100 control->pause_filter_count = __grow_ple_window(old,
1101 pause_filter_count,
1102 pause_filter_count_grow,
1103 pause_filter_count_max);
1104
1105 if (control->pause_filter_count != old) {
1106 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1107 trace_kvm_ple_window_update(vcpu->vcpu_id,
1108 control->pause_filter_count, old);
1109 }
1110 }
1111
shrink_ple_window(struct kvm_vcpu * vcpu)1112 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1113 {
1114 struct vcpu_svm *svm = to_svm(vcpu);
1115 struct vmcb_control_area *control = &svm->vmcb->control;
1116 int old = control->pause_filter_count;
1117
1118 if (kvm_pause_in_guest(vcpu->kvm))
1119 return;
1120
1121 control->pause_filter_count =
1122 __shrink_ple_window(old,
1123 pause_filter_count,
1124 pause_filter_count_shrink,
1125 pause_filter_count);
1126 if (control->pause_filter_count != old) {
1127 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1128 trace_kvm_ple_window_update(vcpu->vcpu_id,
1129 control->pause_filter_count, old);
1130 }
1131 }
1132
svm_hardware_unsetup(void)1133 static void svm_hardware_unsetup(void)
1134 {
1135 int cpu;
1136
1137 sev_hardware_unsetup();
1138
1139 for_each_possible_cpu(cpu)
1140 svm_cpu_uninit(cpu);
1141
1142 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT),
1143 get_order(IOPM_SIZE));
1144 iopm_base = 0;
1145 }
1146
init_seg(struct vmcb_seg * seg)1147 static void init_seg(struct vmcb_seg *seg)
1148 {
1149 seg->selector = 0;
1150 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1151 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1152 seg->limit = 0xffff;
1153 seg->base = 0;
1154 }
1155
init_sys_seg(struct vmcb_seg * seg,uint32_t type)1156 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1157 {
1158 seg->selector = 0;
1159 seg->attrib = SVM_SELECTOR_P_MASK | type;
1160 seg->limit = 0xffff;
1161 seg->base = 0;
1162 }
1163
svm_get_l2_tsc_offset(struct kvm_vcpu * vcpu)1164 static u64 svm_get_l2_tsc_offset(struct kvm_vcpu *vcpu)
1165 {
1166 struct vcpu_svm *svm = to_svm(vcpu);
1167
1168 return svm->nested.ctl.tsc_offset;
1169 }
1170
svm_get_l2_tsc_multiplier(struct kvm_vcpu * vcpu)1171 static u64 svm_get_l2_tsc_multiplier(struct kvm_vcpu *vcpu)
1172 {
1173 struct vcpu_svm *svm = to_svm(vcpu);
1174
1175 return svm->tsc_ratio_msr;
1176 }
1177
svm_write_tsc_offset(struct kvm_vcpu * vcpu)1178 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu)
1179 {
1180 struct vcpu_svm *svm = to_svm(vcpu);
1181
1182 svm->vmcb01.ptr->control.tsc_offset = vcpu->arch.l1_tsc_offset;
1183 svm->vmcb->control.tsc_offset = vcpu->arch.tsc_offset;
1184 vmcb_mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1185 }
1186
svm_write_tsc_multiplier(struct kvm_vcpu * vcpu)1187 void svm_write_tsc_multiplier(struct kvm_vcpu *vcpu)
1188 {
1189 preempt_disable();
1190 if (to_svm(vcpu)->guest_state_loaded)
1191 __svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1192 preempt_enable();
1193 }
1194
1195 /* Evaluate instruction intercepts that depend on guest CPUID features. */
svm_recalc_instruction_intercepts(struct kvm_vcpu * vcpu,struct vcpu_svm * svm)1196 static void svm_recalc_instruction_intercepts(struct kvm_vcpu *vcpu,
1197 struct vcpu_svm *svm)
1198 {
1199 /*
1200 * Intercept INVPCID if shadow paging is enabled to sync/free shadow
1201 * roots, or if INVPCID is disabled in the guest to inject #UD.
1202 */
1203 if (kvm_cpu_cap_has(X86_FEATURE_INVPCID)) {
1204 if (!npt_enabled ||
1205 !guest_cpuid_has(&svm->vcpu, X86_FEATURE_INVPCID))
1206 svm_set_intercept(svm, INTERCEPT_INVPCID);
1207 else
1208 svm_clr_intercept(svm, INTERCEPT_INVPCID);
1209 }
1210
1211 if (kvm_cpu_cap_has(X86_FEATURE_RDTSCP)) {
1212 if (guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
1213 svm_clr_intercept(svm, INTERCEPT_RDTSCP);
1214 else
1215 svm_set_intercept(svm, INTERCEPT_RDTSCP);
1216 }
1217 }
1218
init_vmcb_after_set_cpuid(struct kvm_vcpu * vcpu)1219 static inline void init_vmcb_after_set_cpuid(struct kvm_vcpu *vcpu)
1220 {
1221 struct vcpu_svm *svm = to_svm(vcpu);
1222
1223 if (guest_cpuid_is_intel(vcpu)) {
1224 /*
1225 * We must intercept SYSENTER_EIP and SYSENTER_ESP
1226 * accesses because the processor only stores 32 bits.
1227 * For the same reason we cannot use virtual VMLOAD/VMSAVE.
1228 */
1229 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1230 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1231 svm->vmcb->control.virt_ext &= ~VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1232
1233 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 0, 0);
1234 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 0, 0);
1235 } else {
1236 /*
1237 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1238 * in VMCB and clear intercepts to avoid #VMEXIT.
1239 */
1240 if (vls) {
1241 svm_clr_intercept(svm, INTERCEPT_VMLOAD);
1242 svm_clr_intercept(svm, INTERCEPT_VMSAVE);
1243 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1244 }
1245 /* No need to intercept these MSRs */
1246 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_EIP, 1, 1);
1247 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SYSENTER_ESP, 1, 1);
1248 }
1249 }
1250
init_vmcb(struct kvm_vcpu * vcpu)1251 static void init_vmcb(struct kvm_vcpu *vcpu)
1252 {
1253 struct vcpu_svm *svm = to_svm(vcpu);
1254 struct vmcb *vmcb = svm->vmcb01.ptr;
1255 struct vmcb_control_area *control = &vmcb->control;
1256 struct vmcb_save_area *save = &vmcb->save;
1257
1258 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1259 svm_set_intercept(svm, INTERCEPT_CR3_READ);
1260 svm_set_intercept(svm, INTERCEPT_CR4_READ);
1261 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1262 svm_set_intercept(svm, INTERCEPT_CR3_WRITE);
1263 svm_set_intercept(svm, INTERCEPT_CR4_WRITE);
1264 if (!kvm_vcpu_apicv_active(vcpu))
1265 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
1266
1267 set_dr_intercepts(svm);
1268
1269 set_exception_intercept(svm, PF_VECTOR);
1270 set_exception_intercept(svm, UD_VECTOR);
1271 set_exception_intercept(svm, MC_VECTOR);
1272 set_exception_intercept(svm, AC_VECTOR);
1273 set_exception_intercept(svm, DB_VECTOR);
1274 /*
1275 * Guest access to VMware backdoor ports could legitimately
1276 * trigger #GP because of TSS I/O permission bitmap.
1277 * We intercept those #GP and allow access to them anyway
1278 * as VMware does.
1279 */
1280 if (enable_vmware_backdoor)
1281 set_exception_intercept(svm, GP_VECTOR);
1282
1283 svm_set_intercept(svm, INTERCEPT_INTR);
1284 svm_set_intercept(svm, INTERCEPT_NMI);
1285
1286 if (intercept_smi)
1287 svm_set_intercept(svm, INTERCEPT_SMI);
1288
1289 svm_set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1290 svm_set_intercept(svm, INTERCEPT_RDPMC);
1291 svm_set_intercept(svm, INTERCEPT_CPUID);
1292 svm_set_intercept(svm, INTERCEPT_INVD);
1293 svm_set_intercept(svm, INTERCEPT_INVLPG);
1294 svm_set_intercept(svm, INTERCEPT_INVLPGA);
1295 svm_set_intercept(svm, INTERCEPT_IOIO_PROT);
1296 svm_set_intercept(svm, INTERCEPT_MSR_PROT);
1297 svm_set_intercept(svm, INTERCEPT_TASK_SWITCH);
1298 svm_set_intercept(svm, INTERCEPT_SHUTDOWN);
1299 svm_set_intercept(svm, INTERCEPT_VMRUN);
1300 svm_set_intercept(svm, INTERCEPT_VMMCALL);
1301 svm_set_intercept(svm, INTERCEPT_VMLOAD);
1302 svm_set_intercept(svm, INTERCEPT_VMSAVE);
1303 svm_set_intercept(svm, INTERCEPT_STGI);
1304 svm_set_intercept(svm, INTERCEPT_CLGI);
1305 svm_set_intercept(svm, INTERCEPT_SKINIT);
1306 svm_set_intercept(svm, INTERCEPT_WBINVD);
1307 svm_set_intercept(svm, INTERCEPT_XSETBV);
1308 svm_set_intercept(svm, INTERCEPT_RDPRU);
1309 svm_set_intercept(svm, INTERCEPT_RSM);
1310
1311 if (!kvm_mwait_in_guest(vcpu->kvm)) {
1312 svm_set_intercept(svm, INTERCEPT_MONITOR);
1313 svm_set_intercept(svm, INTERCEPT_MWAIT);
1314 }
1315
1316 if (!kvm_hlt_in_guest(vcpu->kvm))
1317 svm_set_intercept(svm, INTERCEPT_HLT);
1318
1319 control->iopm_base_pa = __sme_set(iopm_base);
1320 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1321 control->int_ctl = V_INTR_MASKING_MASK;
1322
1323 init_seg(&save->es);
1324 init_seg(&save->ss);
1325 init_seg(&save->ds);
1326 init_seg(&save->fs);
1327 init_seg(&save->gs);
1328
1329 save->cs.selector = 0xf000;
1330 save->cs.base = 0xffff0000;
1331 /* Executable/Readable Code Segment */
1332 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1333 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1334 save->cs.limit = 0xffff;
1335
1336 save->gdtr.base = 0;
1337 save->gdtr.limit = 0xffff;
1338 save->idtr.base = 0;
1339 save->idtr.limit = 0xffff;
1340
1341 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1342 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1343
1344 if (npt_enabled) {
1345 /* Setup VMCB for Nested Paging */
1346 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1347 svm_clr_intercept(svm, INTERCEPT_INVLPG);
1348 clr_exception_intercept(svm, PF_VECTOR);
1349 svm_clr_intercept(svm, INTERCEPT_CR3_READ);
1350 svm_clr_intercept(svm, INTERCEPT_CR3_WRITE);
1351 save->g_pat = vcpu->arch.pat;
1352 save->cr3 = 0;
1353 }
1354 svm->current_vmcb->asid_generation = 0;
1355 svm->asid = 0;
1356
1357 svm->nested.vmcb12_gpa = INVALID_GPA;
1358 svm->nested.last_vmcb12_gpa = INVALID_GPA;
1359
1360 if (!kvm_pause_in_guest(vcpu->kvm)) {
1361 control->pause_filter_count = pause_filter_count;
1362 if (pause_filter_thresh)
1363 control->pause_filter_thresh = pause_filter_thresh;
1364 svm_set_intercept(svm, INTERCEPT_PAUSE);
1365 } else {
1366 svm_clr_intercept(svm, INTERCEPT_PAUSE);
1367 }
1368
1369 svm_recalc_instruction_intercepts(vcpu, svm);
1370
1371 /*
1372 * If the host supports V_SPEC_CTRL then disable the interception
1373 * of MSR_IA32_SPEC_CTRL.
1374 */
1375 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
1376 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
1377
1378 if (kvm_vcpu_apicv_active(vcpu))
1379 avic_init_vmcb(svm, vmcb);
1380
1381 if (vnmi)
1382 svm->vmcb->control.int_ctl |= V_NMI_ENABLE_MASK;
1383
1384 if (vgif) {
1385 svm_clr_intercept(svm, INTERCEPT_STGI);
1386 svm_clr_intercept(svm, INTERCEPT_CLGI);
1387 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1388 }
1389
1390 if (sev_guest(vcpu->kvm))
1391 sev_init_vmcb(svm);
1392
1393 svm_hv_init_vmcb(vmcb);
1394 init_vmcb_after_set_cpuid(vcpu);
1395
1396 vmcb_mark_all_dirty(vmcb);
1397
1398 enable_gif(svm);
1399 }
1400
__svm_vcpu_reset(struct kvm_vcpu * vcpu)1401 static void __svm_vcpu_reset(struct kvm_vcpu *vcpu)
1402 {
1403 struct vcpu_svm *svm = to_svm(vcpu);
1404
1405 svm_vcpu_init_msrpm(vcpu, svm->msrpm);
1406
1407 svm_init_osvw(vcpu);
1408 vcpu->arch.microcode_version = 0x01000065;
1409 svm->tsc_ratio_msr = kvm_caps.default_tsc_scaling_ratio;
1410
1411 svm->nmi_masked = false;
1412 svm->awaiting_iret_completion = false;
1413
1414 if (sev_es_guest(vcpu->kvm))
1415 sev_es_vcpu_reset(svm);
1416 }
1417
svm_vcpu_reset(struct kvm_vcpu * vcpu,bool init_event)1418 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1419 {
1420 struct vcpu_svm *svm = to_svm(vcpu);
1421
1422 svm->spec_ctrl = 0;
1423 svm->virt_spec_ctrl = 0;
1424
1425 init_vmcb(vcpu);
1426
1427 if (!init_event)
1428 __svm_vcpu_reset(vcpu);
1429 }
1430
svm_switch_vmcb(struct vcpu_svm * svm,struct kvm_vmcb_info * target_vmcb)1431 void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb)
1432 {
1433 svm->current_vmcb = target_vmcb;
1434 svm->vmcb = target_vmcb->ptr;
1435 }
1436
svm_vcpu_create(struct kvm_vcpu * vcpu)1437 static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1438 {
1439 struct vcpu_svm *svm;
1440 struct page *vmcb01_page;
1441 struct page *vmsa_page = NULL;
1442 int err;
1443
1444 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
1445 svm = to_svm(vcpu);
1446
1447 err = -ENOMEM;
1448 vmcb01_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1449 if (!vmcb01_page)
1450 goto out;
1451
1452 if (sev_es_guest(vcpu->kvm)) {
1453 /*
1454 * SEV-ES guests require a separate VMSA page used to contain
1455 * the encrypted register state of the guest.
1456 */
1457 vmsa_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
1458 if (!vmsa_page)
1459 goto error_free_vmcb_page;
1460
1461 /*
1462 * SEV-ES guests maintain an encrypted version of their FPU
1463 * state which is restored and saved on VMRUN and VMEXIT.
1464 * Mark vcpu->arch.guest_fpu->fpstate as scratch so it won't
1465 * do xsave/xrstor on it.
1466 */
1467 fpstate_set_confidential(&vcpu->arch.guest_fpu);
1468 }
1469
1470 err = avic_init_vcpu(svm);
1471 if (err)
1472 goto error_free_vmsa_page;
1473
1474 svm->msrpm = svm_vcpu_alloc_msrpm();
1475 if (!svm->msrpm) {
1476 err = -ENOMEM;
1477 goto error_free_vmsa_page;
1478 }
1479
1480 svm->x2avic_msrs_intercepted = true;
1481
1482 svm->vmcb01.ptr = page_address(vmcb01_page);
1483 svm->vmcb01.pa = __sme_set(page_to_pfn(vmcb01_page) << PAGE_SHIFT);
1484 svm_switch_vmcb(svm, &svm->vmcb01);
1485
1486 if (vmsa_page)
1487 svm->sev_es.vmsa = page_address(vmsa_page);
1488
1489 svm->guest_state_loaded = false;
1490
1491 return 0;
1492
1493 error_free_vmsa_page:
1494 if (vmsa_page)
1495 __free_page(vmsa_page);
1496 error_free_vmcb_page:
1497 __free_page(vmcb01_page);
1498 out:
1499 return err;
1500 }
1501
svm_clear_current_vmcb(struct vmcb * vmcb)1502 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1503 {
1504 int i;
1505
1506 for_each_online_cpu(i)
1507 cmpxchg(per_cpu_ptr(&svm_data.current_vmcb, i), vmcb, NULL);
1508 }
1509
svm_vcpu_free(struct kvm_vcpu * vcpu)1510 static void svm_vcpu_free(struct kvm_vcpu *vcpu)
1511 {
1512 struct vcpu_svm *svm = to_svm(vcpu);
1513
1514 /*
1515 * The vmcb page can be recycled, causing a false negative in
1516 * svm_vcpu_load(). So, ensure that no logical CPU has this
1517 * vmcb page recorded as its current vmcb.
1518 */
1519 svm_clear_current_vmcb(svm->vmcb);
1520
1521 svm_leave_nested(vcpu);
1522 svm_free_nested(svm);
1523
1524 sev_free_vcpu(vcpu);
1525
1526 __free_page(pfn_to_page(__sme_clr(svm->vmcb01.pa) >> PAGE_SHIFT));
1527 __free_pages(virt_to_page(svm->msrpm), get_order(MSRPM_SIZE));
1528 }
1529
svm_prepare_switch_to_guest(struct kvm_vcpu * vcpu)1530 static void svm_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
1531 {
1532 struct vcpu_svm *svm = to_svm(vcpu);
1533 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
1534
1535 if (sev_es_guest(vcpu->kvm))
1536 sev_es_unmap_ghcb(svm);
1537
1538 if (svm->guest_state_loaded)
1539 return;
1540
1541 /*
1542 * Save additional host state that will be restored on VMEXIT (sev-es)
1543 * or subsequent vmload of host save area.
1544 */
1545 vmsave(sd->save_area_pa);
1546 if (sev_es_guest(vcpu->kvm)) {
1547 struct sev_es_save_area *hostsa;
1548 hostsa = (struct sev_es_save_area *)(page_address(sd->save_area) + 0x400);
1549
1550 sev_es_prepare_switch_to_guest(hostsa);
1551 }
1552
1553 if (tsc_scaling)
1554 __svm_write_tsc_multiplier(vcpu->arch.tsc_scaling_ratio);
1555
1556 /*
1557 * TSC_AUX is always virtualized for SEV-ES guests when the feature is
1558 * available. The user return MSR support is not required in this case
1559 * because TSC_AUX is restored on #VMEXIT from the host save area
1560 * (which has been initialized in svm_hardware_enable()).
1561 */
1562 if (likely(tsc_aux_uret_slot >= 0) &&
1563 (!boot_cpu_has(X86_FEATURE_V_TSC_AUX) || !sev_es_guest(vcpu->kvm)))
1564 kvm_set_user_return_msr(tsc_aux_uret_slot, svm->tsc_aux, -1ull);
1565
1566 svm->guest_state_loaded = true;
1567 }
1568
svm_prepare_host_switch(struct kvm_vcpu * vcpu)1569 static void svm_prepare_host_switch(struct kvm_vcpu *vcpu)
1570 {
1571 to_svm(vcpu)->guest_state_loaded = false;
1572 }
1573
svm_vcpu_load(struct kvm_vcpu * vcpu,int cpu)1574 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1575 {
1576 struct vcpu_svm *svm = to_svm(vcpu);
1577 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, cpu);
1578
1579 if (sd->current_vmcb != svm->vmcb) {
1580 sd->current_vmcb = svm->vmcb;
1581
1582 if (!cpu_feature_enabled(X86_FEATURE_IBPB_ON_VMEXIT))
1583 indirect_branch_prediction_barrier();
1584 }
1585 if (kvm_vcpu_apicv_active(vcpu))
1586 avic_vcpu_load(vcpu, cpu);
1587 }
1588
svm_vcpu_put(struct kvm_vcpu * vcpu)1589 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1590 {
1591 if (kvm_vcpu_apicv_active(vcpu))
1592 avic_vcpu_put(vcpu);
1593
1594 svm_prepare_host_switch(vcpu);
1595
1596 ++vcpu->stat.host_state_reload;
1597 }
1598
svm_get_rflags(struct kvm_vcpu * vcpu)1599 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1600 {
1601 struct vcpu_svm *svm = to_svm(vcpu);
1602 unsigned long rflags = svm->vmcb->save.rflags;
1603
1604 if (svm->nmi_singlestep) {
1605 /* Hide our flags if they were not set by the guest */
1606 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1607 rflags &= ~X86_EFLAGS_TF;
1608 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1609 rflags &= ~X86_EFLAGS_RF;
1610 }
1611 return rflags;
1612 }
1613
svm_set_rflags(struct kvm_vcpu * vcpu,unsigned long rflags)1614 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1615 {
1616 if (to_svm(vcpu)->nmi_singlestep)
1617 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1618
1619 /*
1620 * Any change of EFLAGS.VM is accompanied by a reload of SS
1621 * (caused by either a task switch or an inter-privilege IRET),
1622 * so we do not need to update the CPL here.
1623 */
1624 to_svm(vcpu)->vmcb->save.rflags = rflags;
1625 }
1626
svm_get_if_flag(struct kvm_vcpu * vcpu)1627 static bool svm_get_if_flag(struct kvm_vcpu *vcpu)
1628 {
1629 struct vmcb *vmcb = to_svm(vcpu)->vmcb;
1630
1631 return sev_es_guest(vcpu->kvm)
1632 ? vmcb->control.int_state & SVM_GUEST_INTERRUPT_MASK
1633 : kvm_get_rflags(vcpu) & X86_EFLAGS_IF;
1634 }
1635
svm_cache_reg(struct kvm_vcpu * vcpu,enum kvm_reg reg)1636 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1637 {
1638 kvm_register_mark_available(vcpu, reg);
1639
1640 switch (reg) {
1641 case VCPU_EXREG_PDPTR:
1642 /*
1643 * When !npt_enabled, mmu->pdptrs[] is already available since
1644 * it is always updated per SDM when moving to CRs.
1645 */
1646 if (npt_enabled)
1647 load_pdptrs(vcpu, kvm_read_cr3(vcpu));
1648 break;
1649 default:
1650 KVM_BUG_ON(1, vcpu->kvm);
1651 }
1652 }
1653
svm_set_vintr(struct vcpu_svm * svm)1654 static void svm_set_vintr(struct vcpu_svm *svm)
1655 {
1656 struct vmcb_control_area *control;
1657
1658 /*
1659 * The following fields are ignored when AVIC is enabled
1660 */
1661 WARN_ON(kvm_vcpu_apicv_activated(&svm->vcpu));
1662
1663 svm_set_intercept(svm, INTERCEPT_VINTR);
1664
1665 /*
1666 * Recalculating intercepts may have cleared the VINTR intercept. If
1667 * V_INTR_MASKING is enabled in vmcb12, then the effective RFLAGS.IF
1668 * for L1 physical interrupts is L1's RFLAGS.IF at the time of VMRUN.
1669 * Requesting an interrupt window if save.RFLAGS.IF=0 is pointless as
1670 * interrupts will never be unblocked while L2 is running.
1671 */
1672 if (!svm_is_intercept(svm, INTERCEPT_VINTR))
1673 return;
1674
1675 /*
1676 * This is just a dummy VINTR to actually cause a vmexit to happen.
1677 * Actual injection of virtual interrupts happens through EVENTINJ.
1678 */
1679 control = &svm->vmcb->control;
1680 control->int_vector = 0x0;
1681 control->int_ctl &= ~V_INTR_PRIO_MASK;
1682 control->int_ctl |= V_IRQ_MASK |
1683 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
1684 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1685 }
1686
svm_clear_vintr(struct vcpu_svm * svm)1687 static void svm_clear_vintr(struct vcpu_svm *svm)
1688 {
1689 svm_clr_intercept(svm, INTERCEPT_VINTR);
1690
1691 /* Drop int_ctl fields related to VINTR injection. */
1692 svm->vmcb->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1693 if (is_guest_mode(&svm->vcpu)) {
1694 svm->vmcb01.ptr->control.int_ctl &= ~V_IRQ_INJECTION_BITS_MASK;
1695
1696 WARN_ON((svm->vmcb->control.int_ctl & V_TPR_MASK) !=
1697 (svm->nested.ctl.int_ctl & V_TPR_MASK));
1698
1699 svm->vmcb->control.int_ctl |= svm->nested.ctl.int_ctl &
1700 V_IRQ_INJECTION_BITS_MASK;
1701
1702 svm->vmcb->control.int_vector = svm->nested.ctl.int_vector;
1703 }
1704
1705 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
1706 }
1707
svm_seg(struct kvm_vcpu * vcpu,int seg)1708 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1709 {
1710 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1711 struct vmcb_save_area *save01 = &to_svm(vcpu)->vmcb01.ptr->save;
1712
1713 switch (seg) {
1714 case VCPU_SREG_CS: return &save->cs;
1715 case VCPU_SREG_DS: return &save->ds;
1716 case VCPU_SREG_ES: return &save->es;
1717 case VCPU_SREG_FS: return &save01->fs;
1718 case VCPU_SREG_GS: return &save01->gs;
1719 case VCPU_SREG_SS: return &save->ss;
1720 case VCPU_SREG_TR: return &save01->tr;
1721 case VCPU_SREG_LDTR: return &save01->ldtr;
1722 }
1723 BUG();
1724 return NULL;
1725 }
1726
svm_get_segment_base(struct kvm_vcpu * vcpu,int seg)1727 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1728 {
1729 struct vmcb_seg *s = svm_seg(vcpu, seg);
1730
1731 return s->base;
1732 }
1733
svm_get_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)1734 static void svm_get_segment(struct kvm_vcpu *vcpu,
1735 struct kvm_segment *var, int seg)
1736 {
1737 struct vmcb_seg *s = svm_seg(vcpu, seg);
1738
1739 var->base = s->base;
1740 var->limit = s->limit;
1741 var->selector = s->selector;
1742 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1743 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1744 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1745 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1746 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1747 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1748 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1749
1750 /*
1751 * AMD CPUs circa 2014 track the G bit for all segments except CS.
1752 * However, the SVM spec states that the G bit is not observed by the
1753 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1754 * So let's synthesize a legal G bit for all segments, this helps
1755 * running KVM nested. It also helps cross-vendor migration, because
1756 * Intel's vmentry has a check on the 'G' bit.
1757 */
1758 var->g = s->limit > 0xfffff;
1759
1760 /*
1761 * AMD's VMCB does not have an explicit unusable field, so emulate it
1762 * for cross vendor migration purposes by "not present"
1763 */
1764 var->unusable = !var->present;
1765
1766 switch (seg) {
1767 case VCPU_SREG_TR:
1768 /*
1769 * Work around a bug where the busy flag in the tr selector
1770 * isn't exposed
1771 */
1772 var->type |= 0x2;
1773 break;
1774 case VCPU_SREG_DS:
1775 case VCPU_SREG_ES:
1776 case VCPU_SREG_FS:
1777 case VCPU_SREG_GS:
1778 /*
1779 * The accessed bit must always be set in the segment
1780 * descriptor cache, although it can be cleared in the
1781 * descriptor, the cached bit always remains at 1. Since
1782 * Intel has a check on this, set it here to support
1783 * cross-vendor migration.
1784 */
1785 if (!var->unusable)
1786 var->type |= 0x1;
1787 break;
1788 case VCPU_SREG_SS:
1789 /*
1790 * On AMD CPUs sometimes the DB bit in the segment
1791 * descriptor is left as 1, although the whole segment has
1792 * been made unusable. Clear it here to pass an Intel VMX
1793 * entry check when cross vendor migrating.
1794 */
1795 if (var->unusable)
1796 var->db = 0;
1797 /* This is symmetric with svm_set_segment() */
1798 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1799 break;
1800 }
1801 }
1802
svm_get_cpl(struct kvm_vcpu * vcpu)1803 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1804 {
1805 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1806
1807 return save->cpl;
1808 }
1809
svm_get_cs_db_l_bits(struct kvm_vcpu * vcpu,int * db,int * l)1810 static void svm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
1811 {
1812 struct kvm_segment cs;
1813
1814 svm_get_segment(vcpu, &cs, VCPU_SREG_CS);
1815 *db = cs.db;
1816 *l = cs.l;
1817 }
1818
svm_get_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)1819 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1820 {
1821 struct vcpu_svm *svm = to_svm(vcpu);
1822
1823 dt->size = svm->vmcb->save.idtr.limit;
1824 dt->address = svm->vmcb->save.idtr.base;
1825 }
1826
svm_set_idt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)1827 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1828 {
1829 struct vcpu_svm *svm = to_svm(vcpu);
1830
1831 svm->vmcb->save.idtr.limit = dt->size;
1832 svm->vmcb->save.idtr.base = dt->address ;
1833 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1834 }
1835
svm_get_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)1836 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1837 {
1838 struct vcpu_svm *svm = to_svm(vcpu);
1839
1840 dt->size = svm->vmcb->save.gdtr.limit;
1841 dt->address = svm->vmcb->save.gdtr.base;
1842 }
1843
svm_set_gdt(struct kvm_vcpu * vcpu,struct desc_ptr * dt)1844 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1845 {
1846 struct vcpu_svm *svm = to_svm(vcpu);
1847
1848 svm->vmcb->save.gdtr.limit = dt->size;
1849 svm->vmcb->save.gdtr.base = dt->address ;
1850 vmcb_mark_dirty(svm->vmcb, VMCB_DT);
1851 }
1852
sev_post_set_cr3(struct kvm_vcpu * vcpu,unsigned long cr3)1853 static void sev_post_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
1854 {
1855 struct vcpu_svm *svm = to_svm(vcpu);
1856
1857 /*
1858 * For guests that don't set guest_state_protected, the cr3 update is
1859 * handled via kvm_mmu_load() while entering the guest. For guests
1860 * that do (SEV-ES/SEV-SNP), the cr3 update needs to be written to
1861 * VMCB save area now, since the save area will become the initial
1862 * contents of the VMSA, and future VMCB save area updates won't be
1863 * seen.
1864 */
1865 if (sev_es_guest(vcpu->kvm)) {
1866 svm->vmcb->save.cr3 = cr3;
1867 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1868 }
1869 }
1870
svm_is_valid_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1871 static bool svm_is_valid_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1872 {
1873 return true;
1874 }
1875
svm_set_cr0(struct kvm_vcpu * vcpu,unsigned long cr0)1876 void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1877 {
1878 struct vcpu_svm *svm = to_svm(vcpu);
1879 u64 hcr0 = cr0;
1880 bool old_paging = is_paging(vcpu);
1881
1882 #ifdef CONFIG_X86_64
1883 if (vcpu->arch.efer & EFER_LME) {
1884 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1885 vcpu->arch.efer |= EFER_LMA;
1886 if (!vcpu->arch.guest_state_protected)
1887 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1888 }
1889
1890 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1891 vcpu->arch.efer &= ~EFER_LMA;
1892 if (!vcpu->arch.guest_state_protected)
1893 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1894 }
1895 }
1896 #endif
1897 vcpu->arch.cr0 = cr0;
1898
1899 if (!npt_enabled) {
1900 hcr0 |= X86_CR0_PG | X86_CR0_WP;
1901 if (old_paging != is_paging(vcpu))
1902 svm_set_cr4(vcpu, kvm_read_cr4(vcpu));
1903 }
1904
1905 /*
1906 * re-enable caching here because the QEMU bios
1907 * does not do it - this results in some delay at
1908 * reboot
1909 */
1910 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1911 hcr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1912
1913 svm->vmcb->save.cr0 = hcr0;
1914 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
1915
1916 /*
1917 * SEV-ES guests must always keep the CR intercepts cleared. CR
1918 * tracking is done using the CR write traps.
1919 */
1920 if (sev_es_guest(vcpu->kvm))
1921 return;
1922
1923 if (hcr0 == cr0) {
1924 /* Selective CR0 write remains on. */
1925 svm_clr_intercept(svm, INTERCEPT_CR0_READ);
1926 svm_clr_intercept(svm, INTERCEPT_CR0_WRITE);
1927 } else {
1928 svm_set_intercept(svm, INTERCEPT_CR0_READ);
1929 svm_set_intercept(svm, INTERCEPT_CR0_WRITE);
1930 }
1931 }
1932
svm_is_valid_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1933 static bool svm_is_valid_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1934 {
1935 return true;
1936 }
1937
svm_set_cr4(struct kvm_vcpu * vcpu,unsigned long cr4)1938 void svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1939 {
1940 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1941 unsigned long old_cr4 = vcpu->arch.cr4;
1942
1943 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1944 svm_flush_tlb_current(vcpu);
1945
1946 vcpu->arch.cr4 = cr4;
1947 if (!npt_enabled) {
1948 cr4 |= X86_CR4_PAE;
1949
1950 if (!is_paging(vcpu))
1951 cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
1952 }
1953 cr4 |= host_cr4_mce;
1954 to_svm(vcpu)->vmcb->save.cr4 = cr4;
1955 vmcb_mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1956
1957 if ((cr4 ^ old_cr4) & (X86_CR4_OSXSAVE | X86_CR4_PKE))
1958 kvm_update_cpuid_runtime(vcpu);
1959 }
1960
svm_set_segment(struct kvm_vcpu * vcpu,struct kvm_segment * var,int seg)1961 static void svm_set_segment(struct kvm_vcpu *vcpu,
1962 struct kvm_segment *var, int seg)
1963 {
1964 struct vcpu_svm *svm = to_svm(vcpu);
1965 struct vmcb_seg *s = svm_seg(vcpu, seg);
1966
1967 s->base = var->base;
1968 s->limit = var->limit;
1969 s->selector = var->selector;
1970 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1971 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1972 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1973 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1974 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1975 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1976 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1977 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1978
1979 /*
1980 * This is always accurate, except if SYSRET returned to a segment
1981 * with SS.DPL != 3. Intel does not have this quirk, and always
1982 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1983 * would entail passing the CPL to userspace and back.
1984 */
1985 if (seg == VCPU_SREG_SS)
1986 /* This is symmetric with svm_get_segment() */
1987 svm->vmcb->save.cpl = (var->dpl & 3);
1988
1989 vmcb_mark_dirty(svm->vmcb, VMCB_SEG);
1990 }
1991
svm_update_exception_bitmap(struct kvm_vcpu * vcpu)1992 static void svm_update_exception_bitmap(struct kvm_vcpu *vcpu)
1993 {
1994 struct vcpu_svm *svm = to_svm(vcpu);
1995
1996 clr_exception_intercept(svm, BP_VECTOR);
1997
1998 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1999 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2000 set_exception_intercept(svm, BP_VECTOR);
2001 }
2002 }
2003
new_asid(struct vcpu_svm * svm,struct svm_cpu_data * sd)2004 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2005 {
2006 if (sd->next_asid > sd->max_asid) {
2007 ++sd->asid_generation;
2008 sd->next_asid = sd->min_asid;
2009 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2010 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
2011 }
2012
2013 svm->current_vmcb->asid_generation = sd->asid_generation;
2014 svm->asid = sd->next_asid++;
2015 }
2016
svm_set_dr6(struct kvm_vcpu * vcpu,unsigned long value)2017 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2018 {
2019 struct vmcb *vmcb = to_svm(vcpu)->vmcb;
2020
2021 if (vcpu->arch.guest_state_protected)
2022 return;
2023
2024 if (unlikely(value != vmcb->save.dr6)) {
2025 vmcb->save.dr6 = value;
2026 vmcb_mark_dirty(vmcb, VMCB_DR);
2027 }
2028 }
2029
svm_sync_dirty_debug_regs(struct kvm_vcpu * vcpu)2030 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2031 {
2032 struct vcpu_svm *svm = to_svm(vcpu);
2033
2034 if (WARN_ON_ONCE(sev_es_guest(vcpu->kvm)))
2035 return;
2036
2037 get_debugreg(vcpu->arch.db[0], 0);
2038 get_debugreg(vcpu->arch.db[1], 1);
2039 get_debugreg(vcpu->arch.db[2], 2);
2040 get_debugreg(vcpu->arch.db[3], 3);
2041 /*
2042 * We cannot reset svm->vmcb->save.dr6 to DR6_ACTIVE_LOW here,
2043 * because db_interception might need it. We can do it before vmentry.
2044 */
2045 vcpu->arch.dr6 = svm->vmcb->save.dr6;
2046 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2047 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2048 set_dr_intercepts(svm);
2049 }
2050
svm_set_dr7(struct kvm_vcpu * vcpu,unsigned long value)2051 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2052 {
2053 struct vcpu_svm *svm = to_svm(vcpu);
2054
2055 if (vcpu->arch.guest_state_protected)
2056 return;
2057
2058 svm->vmcb->save.dr7 = value;
2059 vmcb_mark_dirty(svm->vmcb, VMCB_DR);
2060 }
2061
pf_interception(struct kvm_vcpu * vcpu)2062 static int pf_interception(struct kvm_vcpu *vcpu)
2063 {
2064 struct vcpu_svm *svm = to_svm(vcpu);
2065
2066 u64 fault_address = svm->vmcb->control.exit_info_2;
2067 u64 error_code = svm->vmcb->control.exit_info_1;
2068
2069 return kvm_handle_page_fault(vcpu, error_code, fault_address,
2070 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2071 svm->vmcb->control.insn_bytes : NULL,
2072 svm->vmcb->control.insn_len);
2073 }
2074
npf_interception(struct kvm_vcpu * vcpu)2075 static int npf_interception(struct kvm_vcpu *vcpu)
2076 {
2077 struct vcpu_svm *svm = to_svm(vcpu);
2078
2079 u64 fault_address = svm->vmcb->control.exit_info_2;
2080 u64 error_code = svm->vmcb->control.exit_info_1;
2081
2082 trace_kvm_page_fault(vcpu, fault_address, error_code);
2083 return kvm_mmu_page_fault(vcpu, fault_address, error_code,
2084 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2085 svm->vmcb->control.insn_bytes : NULL,
2086 svm->vmcb->control.insn_len);
2087 }
2088
db_interception(struct kvm_vcpu * vcpu)2089 static int db_interception(struct kvm_vcpu *vcpu)
2090 {
2091 struct kvm_run *kvm_run = vcpu->run;
2092 struct vcpu_svm *svm = to_svm(vcpu);
2093
2094 if (!(vcpu->guest_debug &
2095 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2096 !svm->nmi_singlestep) {
2097 u32 payload = svm->vmcb->save.dr6 ^ DR6_ACTIVE_LOW;
2098 kvm_queue_exception_p(vcpu, DB_VECTOR, payload);
2099 return 1;
2100 }
2101
2102 if (svm->nmi_singlestep) {
2103 disable_nmi_singlestep(svm);
2104 /* Make sure we check for pending NMIs upon entry */
2105 kvm_make_request(KVM_REQ_EVENT, vcpu);
2106 }
2107
2108 if (vcpu->guest_debug &
2109 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2110 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2111 kvm_run->debug.arch.dr6 = svm->vmcb->save.dr6;
2112 kvm_run->debug.arch.dr7 = svm->vmcb->save.dr7;
2113 kvm_run->debug.arch.pc =
2114 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2115 kvm_run->debug.arch.exception = DB_VECTOR;
2116 return 0;
2117 }
2118
2119 return 1;
2120 }
2121
bp_interception(struct kvm_vcpu * vcpu)2122 static int bp_interception(struct kvm_vcpu *vcpu)
2123 {
2124 struct vcpu_svm *svm = to_svm(vcpu);
2125 struct kvm_run *kvm_run = vcpu->run;
2126
2127 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2128 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2129 kvm_run->debug.arch.exception = BP_VECTOR;
2130 return 0;
2131 }
2132
ud_interception(struct kvm_vcpu * vcpu)2133 static int ud_interception(struct kvm_vcpu *vcpu)
2134 {
2135 return handle_ud(vcpu);
2136 }
2137
ac_interception(struct kvm_vcpu * vcpu)2138 static int ac_interception(struct kvm_vcpu *vcpu)
2139 {
2140 kvm_queue_exception_e(vcpu, AC_VECTOR, 0);
2141 return 1;
2142 }
2143
is_erratum_383(void)2144 static bool is_erratum_383(void)
2145 {
2146 int err, i;
2147 u64 value;
2148
2149 if (!erratum_383_found)
2150 return false;
2151
2152 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2153 if (err)
2154 return false;
2155
2156 /* Bit 62 may or may not be set for this mce */
2157 value &= ~(1ULL << 62);
2158
2159 if (value != 0xb600000000010015ULL)
2160 return false;
2161
2162 /* Clear MCi_STATUS registers */
2163 for (i = 0; i < 6; ++i)
2164 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2165
2166 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2167 if (!err) {
2168 u32 low, high;
2169
2170 value &= ~(1ULL << 2);
2171 low = lower_32_bits(value);
2172 high = upper_32_bits(value);
2173
2174 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2175 }
2176
2177 /* Flush tlb to evict multi-match entries */
2178 __flush_tlb_all();
2179
2180 return true;
2181 }
2182
svm_handle_mce(struct kvm_vcpu * vcpu)2183 static void svm_handle_mce(struct kvm_vcpu *vcpu)
2184 {
2185 if (is_erratum_383()) {
2186 /*
2187 * Erratum 383 triggered. Guest state is corrupt so kill the
2188 * guest.
2189 */
2190 pr_err("Guest triggered AMD Erratum 383\n");
2191
2192 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2193
2194 return;
2195 }
2196
2197 /*
2198 * On an #MC intercept the MCE handler is not called automatically in
2199 * the host. So do it by hand here.
2200 */
2201 kvm_machine_check();
2202 }
2203
mc_interception(struct kvm_vcpu * vcpu)2204 static int mc_interception(struct kvm_vcpu *vcpu)
2205 {
2206 return 1;
2207 }
2208
shutdown_interception(struct kvm_vcpu * vcpu)2209 static int shutdown_interception(struct kvm_vcpu *vcpu)
2210 {
2211 struct kvm_run *kvm_run = vcpu->run;
2212 struct vcpu_svm *svm = to_svm(vcpu);
2213
2214
2215 /*
2216 * VMCB is undefined after a SHUTDOWN intercept. INIT the vCPU to put
2217 * the VMCB in a known good state. Unfortuately, KVM doesn't have
2218 * KVM_MP_STATE_SHUTDOWN and can't add it without potentially breaking
2219 * userspace. At a platform view, INIT is acceptable behavior as
2220 * there exist bare metal platforms that automatically INIT the CPU
2221 * in response to shutdown.
2222 *
2223 * The VM save area for SEV-ES guests has already been encrypted so it
2224 * cannot be reinitialized, i.e. synthesizing INIT is futile.
2225 */
2226 if (!sev_es_guest(vcpu->kvm)) {
2227 clear_page(svm->vmcb);
2228 #ifdef CONFIG_KVM_SMM
2229 if (is_smm(vcpu))
2230 kvm_smm_changed(vcpu, false);
2231 #endif
2232 kvm_vcpu_reset(vcpu, true);
2233 }
2234
2235 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2236 return 0;
2237 }
2238
io_interception(struct kvm_vcpu * vcpu)2239 static int io_interception(struct kvm_vcpu *vcpu)
2240 {
2241 struct vcpu_svm *svm = to_svm(vcpu);
2242 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2243 int size, in, string;
2244 unsigned port;
2245
2246 ++vcpu->stat.io_exits;
2247 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2248 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2249 port = io_info >> 16;
2250 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2251
2252 if (string) {
2253 if (sev_es_guest(vcpu->kvm))
2254 return sev_es_string_io(svm, size, port, in);
2255 else
2256 return kvm_emulate_instruction(vcpu, 0);
2257 }
2258
2259 svm->next_rip = svm->vmcb->control.exit_info_2;
2260
2261 return kvm_fast_pio(vcpu, size, port, in);
2262 }
2263
nmi_interception(struct kvm_vcpu * vcpu)2264 static int nmi_interception(struct kvm_vcpu *vcpu)
2265 {
2266 return 1;
2267 }
2268
smi_interception(struct kvm_vcpu * vcpu)2269 static int smi_interception(struct kvm_vcpu *vcpu)
2270 {
2271 return 1;
2272 }
2273
intr_interception(struct kvm_vcpu * vcpu)2274 static int intr_interception(struct kvm_vcpu *vcpu)
2275 {
2276 ++vcpu->stat.irq_exits;
2277 return 1;
2278 }
2279
vmload_vmsave_interception(struct kvm_vcpu * vcpu,bool vmload)2280 static int vmload_vmsave_interception(struct kvm_vcpu *vcpu, bool vmload)
2281 {
2282 struct vcpu_svm *svm = to_svm(vcpu);
2283 struct vmcb *vmcb12;
2284 struct kvm_host_map map;
2285 int ret;
2286
2287 if (nested_svm_check_permissions(vcpu))
2288 return 1;
2289
2290 ret = kvm_vcpu_map(vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
2291 if (ret) {
2292 if (ret == -EINVAL)
2293 kvm_inject_gp(vcpu, 0);
2294 return 1;
2295 }
2296
2297 vmcb12 = map.hva;
2298
2299 ret = kvm_skip_emulated_instruction(vcpu);
2300
2301 if (vmload) {
2302 svm_copy_vmloadsave_state(svm->vmcb, vmcb12);
2303 svm->sysenter_eip_hi = 0;
2304 svm->sysenter_esp_hi = 0;
2305 } else {
2306 svm_copy_vmloadsave_state(vmcb12, svm->vmcb);
2307 }
2308
2309 kvm_vcpu_unmap(vcpu, &map, true);
2310
2311 return ret;
2312 }
2313
vmload_interception(struct kvm_vcpu * vcpu)2314 static int vmload_interception(struct kvm_vcpu *vcpu)
2315 {
2316 return vmload_vmsave_interception(vcpu, true);
2317 }
2318
vmsave_interception(struct kvm_vcpu * vcpu)2319 static int vmsave_interception(struct kvm_vcpu *vcpu)
2320 {
2321 return vmload_vmsave_interception(vcpu, false);
2322 }
2323
vmrun_interception(struct kvm_vcpu * vcpu)2324 static int vmrun_interception(struct kvm_vcpu *vcpu)
2325 {
2326 if (nested_svm_check_permissions(vcpu))
2327 return 1;
2328
2329 return nested_svm_vmrun(vcpu);
2330 }
2331
2332 enum {
2333 NONE_SVM_INSTR,
2334 SVM_INSTR_VMRUN,
2335 SVM_INSTR_VMLOAD,
2336 SVM_INSTR_VMSAVE,
2337 };
2338
2339 /* Return NONE_SVM_INSTR if not SVM instrs, otherwise return decode result */
svm_instr_opcode(struct kvm_vcpu * vcpu)2340 static int svm_instr_opcode(struct kvm_vcpu *vcpu)
2341 {
2342 struct x86_emulate_ctxt *ctxt = vcpu->arch.emulate_ctxt;
2343
2344 if (ctxt->b != 0x1 || ctxt->opcode_len != 2)
2345 return NONE_SVM_INSTR;
2346
2347 switch (ctxt->modrm) {
2348 case 0xd8: /* VMRUN */
2349 return SVM_INSTR_VMRUN;
2350 case 0xda: /* VMLOAD */
2351 return SVM_INSTR_VMLOAD;
2352 case 0xdb: /* VMSAVE */
2353 return SVM_INSTR_VMSAVE;
2354 default:
2355 break;
2356 }
2357
2358 return NONE_SVM_INSTR;
2359 }
2360
emulate_svm_instr(struct kvm_vcpu * vcpu,int opcode)2361 static int emulate_svm_instr(struct kvm_vcpu *vcpu, int opcode)
2362 {
2363 const int guest_mode_exit_codes[] = {
2364 [SVM_INSTR_VMRUN] = SVM_EXIT_VMRUN,
2365 [SVM_INSTR_VMLOAD] = SVM_EXIT_VMLOAD,
2366 [SVM_INSTR_VMSAVE] = SVM_EXIT_VMSAVE,
2367 };
2368 int (*const svm_instr_handlers[])(struct kvm_vcpu *vcpu) = {
2369 [SVM_INSTR_VMRUN] = vmrun_interception,
2370 [SVM_INSTR_VMLOAD] = vmload_interception,
2371 [SVM_INSTR_VMSAVE] = vmsave_interception,
2372 };
2373 struct vcpu_svm *svm = to_svm(vcpu);
2374 int ret;
2375
2376 if (is_guest_mode(vcpu)) {
2377 /* Returns '1' or -errno on failure, '0' on success. */
2378 ret = nested_svm_simple_vmexit(svm, guest_mode_exit_codes[opcode]);
2379 if (ret)
2380 return ret;
2381 return 1;
2382 }
2383 return svm_instr_handlers[opcode](vcpu);
2384 }
2385
2386 /*
2387 * #GP handling code. Note that #GP can be triggered under the following two
2388 * cases:
2389 * 1) SVM VM-related instructions (VMRUN/VMSAVE/VMLOAD) that trigger #GP on
2390 * some AMD CPUs when EAX of these instructions are in the reserved memory
2391 * regions (e.g. SMM memory on host).
2392 * 2) VMware backdoor
2393 */
gp_interception(struct kvm_vcpu * vcpu)2394 static int gp_interception(struct kvm_vcpu *vcpu)
2395 {
2396 struct vcpu_svm *svm = to_svm(vcpu);
2397 u32 error_code = svm->vmcb->control.exit_info_1;
2398 int opcode;
2399
2400 /* Both #GP cases have zero error_code */
2401 if (error_code)
2402 goto reinject;
2403
2404 /* Decode the instruction for usage later */
2405 if (x86_decode_emulated_instruction(vcpu, 0, NULL, 0) != EMULATION_OK)
2406 goto reinject;
2407
2408 opcode = svm_instr_opcode(vcpu);
2409
2410 if (opcode == NONE_SVM_INSTR) {
2411 if (!enable_vmware_backdoor)
2412 goto reinject;
2413
2414 /*
2415 * VMware backdoor emulation on #GP interception only handles
2416 * IN{S}, OUT{S}, and RDPMC.
2417 */
2418 if (!is_guest_mode(vcpu))
2419 return kvm_emulate_instruction(vcpu,
2420 EMULTYPE_VMWARE_GP | EMULTYPE_NO_DECODE);
2421 } else {
2422 /* All SVM instructions expect page aligned RAX */
2423 if (svm->vmcb->save.rax & ~PAGE_MASK)
2424 goto reinject;
2425
2426 return emulate_svm_instr(vcpu, opcode);
2427 }
2428
2429 reinject:
2430 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2431 return 1;
2432 }
2433
svm_set_gif(struct vcpu_svm * svm,bool value)2434 void svm_set_gif(struct vcpu_svm *svm, bool value)
2435 {
2436 if (value) {
2437 /*
2438 * If VGIF is enabled, the STGI intercept is only added to
2439 * detect the opening of the SMI/NMI window; remove it now.
2440 * Likewise, clear the VINTR intercept, we will set it
2441 * again while processing KVM_REQ_EVENT if needed.
2442 */
2443 if (vgif)
2444 svm_clr_intercept(svm, INTERCEPT_STGI);
2445 if (svm_is_intercept(svm, INTERCEPT_VINTR))
2446 svm_clear_vintr(svm);
2447
2448 enable_gif(svm);
2449 if (svm->vcpu.arch.smi_pending ||
2450 svm->vcpu.arch.nmi_pending ||
2451 kvm_cpu_has_injectable_intr(&svm->vcpu) ||
2452 kvm_apic_has_pending_init_or_sipi(&svm->vcpu))
2453 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2454 } else {
2455 disable_gif(svm);
2456
2457 /*
2458 * After a CLGI no interrupts should come. But if vGIF is
2459 * in use, we still rely on the VINTR intercept (rather than
2460 * STGI) to detect an open interrupt window.
2461 */
2462 if (!vgif)
2463 svm_clear_vintr(svm);
2464 }
2465 }
2466
stgi_interception(struct kvm_vcpu * vcpu)2467 static int stgi_interception(struct kvm_vcpu *vcpu)
2468 {
2469 int ret;
2470
2471 if (nested_svm_check_permissions(vcpu))
2472 return 1;
2473
2474 ret = kvm_skip_emulated_instruction(vcpu);
2475 svm_set_gif(to_svm(vcpu), true);
2476 return ret;
2477 }
2478
clgi_interception(struct kvm_vcpu * vcpu)2479 static int clgi_interception(struct kvm_vcpu *vcpu)
2480 {
2481 int ret;
2482
2483 if (nested_svm_check_permissions(vcpu))
2484 return 1;
2485
2486 ret = kvm_skip_emulated_instruction(vcpu);
2487 svm_set_gif(to_svm(vcpu), false);
2488 return ret;
2489 }
2490
invlpga_interception(struct kvm_vcpu * vcpu)2491 static int invlpga_interception(struct kvm_vcpu *vcpu)
2492 {
2493 gva_t gva = kvm_rax_read(vcpu);
2494 u32 asid = kvm_rcx_read(vcpu);
2495
2496 /* FIXME: Handle an address size prefix. */
2497 if (!is_long_mode(vcpu))
2498 gva = (u32)gva;
2499
2500 trace_kvm_invlpga(to_svm(vcpu)->vmcb->save.rip, asid, gva);
2501
2502 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2503 kvm_mmu_invlpg(vcpu, gva);
2504
2505 return kvm_skip_emulated_instruction(vcpu);
2506 }
2507
skinit_interception(struct kvm_vcpu * vcpu)2508 static int skinit_interception(struct kvm_vcpu *vcpu)
2509 {
2510 trace_kvm_skinit(to_svm(vcpu)->vmcb->save.rip, kvm_rax_read(vcpu));
2511
2512 kvm_queue_exception(vcpu, UD_VECTOR);
2513 return 1;
2514 }
2515
task_switch_interception(struct kvm_vcpu * vcpu)2516 static int task_switch_interception(struct kvm_vcpu *vcpu)
2517 {
2518 struct vcpu_svm *svm = to_svm(vcpu);
2519 u16 tss_selector;
2520 int reason;
2521 int int_type = svm->vmcb->control.exit_int_info &
2522 SVM_EXITINTINFO_TYPE_MASK;
2523 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2524 uint32_t type =
2525 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2526 uint32_t idt_v =
2527 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2528 bool has_error_code = false;
2529 u32 error_code = 0;
2530
2531 tss_selector = (u16)svm->vmcb->control.exit_info_1;
2532
2533 if (svm->vmcb->control.exit_info_2 &
2534 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2535 reason = TASK_SWITCH_IRET;
2536 else if (svm->vmcb->control.exit_info_2 &
2537 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2538 reason = TASK_SWITCH_JMP;
2539 else if (idt_v)
2540 reason = TASK_SWITCH_GATE;
2541 else
2542 reason = TASK_SWITCH_CALL;
2543
2544 if (reason == TASK_SWITCH_GATE) {
2545 switch (type) {
2546 case SVM_EXITINTINFO_TYPE_NMI:
2547 vcpu->arch.nmi_injected = false;
2548 break;
2549 case SVM_EXITINTINFO_TYPE_EXEPT:
2550 if (svm->vmcb->control.exit_info_2 &
2551 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2552 has_error_code = true;
2553 error_code =
2554 (u32)svm->vmcb->control.exit_info_2;
2555 }
2556 kvm_clear_exception_queue(vcpu);
2557 break;
2558 case SVM_EXITINTINFO_TYPE_INTR:
2559 case SVM_EXITINTINFO_TYPE_SOFT:
2560 kvm_clear_interrupt_queue(vcpu);
2561 break;
2562 default:
2563 break;
2564 }
2565 }
2566
2567 if (reason != TASK_SWITCH_GATE ||
2568 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2569 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2570 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
2571 if (!svm_skip_emulated_instruction(vcpu))
2572 return 0;
2573 }
2574
2575 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2576 int_vec = -1;
2577
2578 return kvm_task_switch(vcpu, tss_selector, int_vec, reason,
2579 has_error_code, error_code);
2580 }
2581
svm_clr_iret_intercept(struct vcpu_svm * svm)2582 static void svm_clr_iret_intercept(struct vcpu_svm *svm)
2583 {
2584 if (!sev_es_guest(svm->vcpu.kvm))
2585 svm_clr_intercept(svm, INTERCEPT_IRET);
2586 }
2587
svm_set_iret_intercept(struct vcpu_svm * svm)2588 static void svm_set_iret_intercept(struct vcpu_svm *svm)
2589 {
2590 if (!sev_es_guest(svm->vcpu.kvm))
2591 svm_set_intercept(svm, INTERCEPT_IRET);
2592 }
2593
iret_interception(struct kvm_vcpu * vcpu)2594 static int iret_interception(struct kvm_vcpu *vcpu)
2595 {
2596 struct vcpu_svm *svm = to_svm(vcpu);
2597
2598 WARN_ON_ONCE(sev_es_guest(vcpu->kvm));
2599
2600 ++vcpu->stat.nmi_window_exits;
2601 svm->awaiting_iret_completion = true;
2602
2603 svm_clr_iret_intercept(svm);
2604 svm->nmi_iret_rip = kvm_rip_read(vcpu);
2605
2606 kvm_make_request(KVM_REQ_EVENT, vcpu);
2607 return 1;
2608 }
2609
invlpg_interception(struct kvm_vcpu * vcpu)2610 static int invlpg_interception(struct kvm_vcpu *vcpu)
2611 {
2612 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2613 return kvm_emulate_instruction(vcpu, 0);
2614
2615 kvm_mmu_invlpg(vcpu, to_svm(vcpu)->vmcb->control.exit_info_1);
2616 return kvm_skip_emulated_instruction(vcpu);
2617 }
2618
emulate_on_interception(struct kvm_vcpu * vcpu)2619 static int emulate_on_interception(struct kvm_vcpu *vcpu)
2620 {
2621 return kvm_emulate_instruction(vcpu, 0);
2622 }
2623
rsm_interception(struct kvm_vcpu * vcpu)2624 static int rsm_interception(struct kvm_vcpu *vcpu)
2625 {
2626 return kvm_emulate_instruction_from_buffer(vcpu, rsm_ins_bytes, 2);
2627 }
2628
check_selective_cr0_intercepted(struct kvm_vcpu * vcpu,unsigned long val)2629 static bool check_selective_cr0_intercepted(struct kvm_vcpu *vcpu,
2630 unsigned long val)
2631 {
2632 struct vcpu_svm *svm = to_svm(vcpu);
2633 unsigned long cr0 = vcpu->arch.cr0;
2634 bool ret = false;
2635
2636 if (!is_guest_mode(vcpu) ||
2637 (!(vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_SELECTIVE_CR0))))
2638 return false;
2639
2640 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2641 val &= ~SVM_CR0_SELECTIVE_MASK;
2642
2643 if (cr0 ^ val) {
2644 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2645 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2646 }
2647
2648 return ret;
2649 }
2650
2651 #define CR_VALID (1ULL << 63)
2652
cr_interception(struct kvm_vcpu * vcpu)2653 static int cr_interception(struct kvm_vcpu *vcpu)
2654 {
2655 struct vcpu_svm *svm = to_svm(vcpu);
2656 int reg, cr;
2657 unsigned long val;
2658 int err;
2659
2660 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2661 return emulate_on_interception(vcpu);
2662
2663 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2664 return emulate_on_interception(vcpu);
2665
2666 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2667 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2668 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2669 else
2670 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2671
2672 err = 0;
2673 if (cr >= 16) { /* mov to cr */
2674 cr -= 16;
2675 val = kvm_register_read(vcpu, reg);
2676 trace_kvm_cr_write(cr, val);
2677 switch (cr) {
2678 case 0:
2679 if (!check_selective_cr0_intercepted(vcpu, val))
2680 err = kvm_set_cr0(vcpu, val);
2681 else
2682 return 1;
2683
2684 break;
2685 case 3:
2686 err = kvm_set_cr3(vcpu, val);
2687 break;
2688 case 4:
2689 err = kvm_set_cr4(vcpu, val);
2690 break;
2691 case 8:
2692 err = kvm_set_cr8(vcpu, val);
2693 break;
2694 default:
2695 WARN(1, "unhandled write to CR%d", cr);
2696 kvm_queue_exception(vcpu, UD_VECTOR);
2697 return 1;
2698 }
2699 } else { /* mov from cr */
2700 switch (cr) {
2701 case 0:
2702 val = kvm_read_cr0(vcpu);
2703 break;
2704 case 2:
2705 val = vcpu->arch.cr2;
2706 break;
2707 case 3:
2708 val = kvm_read_cr3(vcpu);
2709 break;
2710 case 4:
2711 val = kvm_read_cr4(vcpu);
2712 break;
2713 case 8:
2714 val = kvm_get_cr8(vcpu);
2715 break;
2716 default:
2717 WARN(1, "unhandled read from CR%d", cr);
2718 kvm_queue_exception(vcpu, UD_VECTOR);
2719 return 1;
2720 }
2721 kvm_register_write(vcpu, reg, val);
2722 trace_kvm_cr_read(cr, val);
2723 }
2724 return kvm_complete_insn_gp(vcpu, err);
2725 }
2726
cr_trap(struct kvm_vcpu * vcpu)2727 static int cr_trap(struct kvm_vcpu *vcpu)
2728 {
2729 struct vcpu_svm *svm = to_svm(vcpu);
2730 unsigned long old_value, new_value;
2731 unsigned int cr;
2732 int ret = 0;
2733
2734 new_value = (unsigned long)svm->vmcb->control.exit_info_1;
2735
2736 cr = svm->vmcb->control.exit_code - SVM_EXIT_CR0_WRITE_TRAP;
2737 switch (cr) {
2738 case 0:
2739 old_value = kvm_read_cr0(vcpu);
2740 svm_set_cr0(vcpu, new_value);
2741
2742 kvm_post_set_cr0(vcpu, old_value, new_value);
2743 break;
2744 case 4:
2745 old_value = kvm_read_cr4(vcpu);
2746 svm_set_cr4(vcpu, new_value);
2747
2748 kvm_post_set_cr4(vcpu, old_value, new_value);
2749 break;
2750 case 8:
2751 ret = kvm_set_cr8(vcpu, new_value);
2752 break;
2753 default:
2754 WARN(1, "unhandled CR%d write trap", cr);
2755 kvm_queue_exception(vcpu, UD_VECTOR);
2756 return 1;
2757 }
2758
2759 return kvm_complete_insn_gp(vcpu, ret);
2760 }
2761
dr_interception(struct kvm_vcpu * vcpu)2762 static int dr_interception(struct kvm_vcpu *vcpu)
2763 {
2764 struct vcpu_svm *svm = to_svm(vcpu);
2765 int reg, dr;
2766 unsigned long val;
2767 int err = 0;
2768
2769 /*
2770 * SEV-ES intercepts DR7 only to disable guest debugging and the guest issues a VMGEXIT
2771 * for DR7 write only. KVM cannot change DR7 (always swapped as type 'A') so return early.
2772 */
2773 if (sev_es_guest(vcpu->kvm))
2774 return 1;
2775
2776 if (vcpu->guest_debug == 0) {
2777 /*
2778 * No more DR vmexits; force a reload of the debug registers
2779 * and reenter on this instruction. The next vmexit will
2780 * retrieve the full state of the debug registers.
2781 */
2782 clr_dr_intercepts(svm);
2783 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2784 return 1;
2785 }
2786
2787 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2788 return emulate_on_interception(vcpu);
2789
2790 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2791 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
2792 if (dr >= 16) { /* mov to DRn */
2793 dr -= 16;
2794 val = kvm_register_read(vcpu, reg);
2795 err = kvm_set_dr(vcpu, dr, val);
2796 } else {
2797 kvm_get_dr(vcpu, dr, &val);
2798 kvm_register_write(vcpu, reg, val);
2799 }
2800
2801 return kvm_complete_insn_gp(vcpu, err);
2802 }
2803
cr8_write_interception(struct kvm_vcpu * vcpu)2804 static int cr8_write_interception(struct kvm_vcpu *vcpu)
2805 {
2806 int r;
2807
2808 u8 cr8_prev = kvm_get_cr8(vcpu);
2809 /* instruction emulation calls kvm_set_cr8() */
2810 r = cr_interception(vcpu);
2811 if (lapic_in_kernel(vcpu))
2812 return r;
2813 if (cr8_prev <= kvm_get_cr8(vcpu))
2814 return r;
2815 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
2816 return 0;
2817 }
2818
efer_trap(struct kvm_vcpu * vcpu)2819 static int efer_trap(struct kvm_vcpu *vcpu)
2820 {
2821 struct msr_data msr_info;
2822 int ret;
2823
2824 /*
2825 * Clear the EFER_SVME bit from EFER. The SVM code always sets this
2826 * bit in svm_set_efer(), but __kvm_valid_efer() checks it against
2827 * whether the guest has X86_FEATURE_SVM - this avoids a failure if
2828 * the guest doesn't have X86_FEATURE_SVM.
2829 */
2830 msr_info.host_initiated = false;
2831 msr_info.index = MSR_EFER;
2832 msr_info.data = to_svm(vcpu)->vmcb->control.exit_info_1 & ~EFER_SVME;
2833 ret = kvm_set_msr_common(vcpu, &msr_info);
2834
2835 return kvm_complete_insn_gp(vcpu, ret);
2836 }
2837
svm_get_msr_feature(struct kvm_msr_entry * msr)2838 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
2839 {
2840 msr->data = 0;
2841
2842 switch (msr->index) {
2843 case MSR_AMD64_DE_CFG:
2844 if (cpu_feature_enabled(X86_FEATURE_LFENCE_RDTSC))
2845 msr->data |= MSR_AMD64_DE_CFG_LFENCE_SERIALIZE;
2846 break;
2847 default:
2848 return KVM_MSR_RET_INVALID;
2849 }
2850
2851 return 0;
2852 }
2853
svm_get_msr(struct kvm_vcpu * vcpu,struct msr_data * msr_info)2854 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
2855 {
2856 struct vcpu_svm *svm = to_svm(vcpu);
2857
2858 switch (msr_info->index) {
2859 case MSR_AMD64_TSC_RATIO:
2860 if (!msr_info->host_initiated &&
2861 !guest_can_use(vcpu, X86_FEATURE_TSCRATEMSR))
2862 return 1;
2863 msr_info->data = svm->tsc_ratio_msr;
2864 break;
2865 case MSR_STAR:
2866 msr_info->data = svm->vmcb01.ptr->save.star;
2867 break;
2868 #ifdef CONFIG_X86_64
2869 case MSR_LSTAR:
2870 msr_info->data = svm->vmcb01.ptr->save.lstar;
2871 break;
2872 case MSR_CSTAR:
2873 msr_info->data = svm->vmcb01.ptr->save.cstar;
2874 break;
2875 case MSR_GS_BASE:
2876 msr_info->data = svm->vmcb01.ptr->save.gs.base;
2877 break;
2878 case MSR_FS_BASE:
2879 msr_info->data = svm->vmcb01.ptr->save.fs.base;
2880 break;
2881 case MSR_KERNEL_GS_BASE:
2882 msr_info->data = svm->vmcb01.ptr->save.kernel_gs_base;
2883 break;
2884 case MSR_SYSCALL_MASK:
2885 msr_info->data = svm->vmcb01.ptr->save.sfmask;
2886 break;
2887 #endif
2888 case MSR_IA32_SYSENTER_CS:
2889 msr_info->data = svm->vmcb01.ptr->save.sysenter_cs;
2890 break;
2891 case MSR_IA32_SYSENTER_EIP:
2892 msr_info->data = (u32)svm->vmcb01.ptr->save.sysenter_eip;
2893 if (guest_cpuid_is_intel(vcpu))
2894 msr_info->data |= (u64)svm->sysenter_eip_hi << 32;
2895 break;
2896 case MSR_IA32_SYSENTER_ESP:
2897 msr_info->data = svm->vmcb01.ptr->save.sysenter_esp;
2898 if (guest_cpuid_is_intel(vcpu))
2899 msr_info->data |= (u64)svm->sysenter_esp_hi << 32;
2900 break;
2901 case MSR_TSC_AUX:
2902 msr_info->data = svm->tsc_aux;
2903 break;
2904 case MSR_IA32_DEBUGCTLMSR:
2905 msr_info->data = svm_get_lbr_vmcb(svm)->save.dbgctl;
2906 break;
2907 case MSR_IA32_LASTBRANCHFROMIP:
2908 msr_info->data = svm_get_lbr_vmcb(svm)->save.br_from;
2909 break;
2910 case MSR_IA32_LASTBRANCHTOIP:
2911 msr_info->data = svm_get_lbr_vmcb(svm)->save.br_to;
2912 break;
2913 case MSR_IA32_LASTINTFROMIP:
2914 msr_info->data = svm_get_lbr_vmcb(svm)->save.last_excp_from;
2915 break;
2916 case MSR_IA32_LASTINTTOIP:
2917 msr_info->data = svm_get_lbr_vmcb(svm)->save.last_excp_to;
2918 break;
2919 case MSR_VM_HSAVE_PA:
2920 msr_info->data = svm->nested.hsave_msr;
2921 break;
2922 case MSR_VM_CR:
2923 msr_info->data = svm->nested.vm_cr_msr;
2924 break;
2925 case MSR_IA32_SPEC_CTRL:
2926 if (!msr_info->host_initiated &&
2927 !guest_has_spec_ctrl_msr(vcpu))
2928 return 1;
2929
2930 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
2931 msr_info->data = svm->vmcb->save.spec_ctrl;
2932 else
2933 msr_info->data = svm->spec_ctrl;
2934 break;
2935 case MSR_AMD64_VIRT_SPEC_CTRL:
2936 if (!msr_info->host_initiated &&
2937 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
2938 return 1;
2939
2940 msr_info->data = svm->virt_spec_ctrl;
2941 break;
2942 case MSR_F15H_IC_CFG: {
2943
2944 int family, model;
2945
2946 family = guest_cpuid_family(vcpu);
2947 model = guest_cpuid_model(vcpu);
2948
2949 if (family < 0 || model < 0)
2950 return kvm_get_msr_common(vcpu, msr_info);
2951
2952 msr_info->data = 0;
2953
2954 if (family == 0x15 &&
2955 (model >= 0x2 && model < 0x20))
2956 msr_info->data = 0x1E;
2957 }
2958 break;
2959 case MSR_AMD64_DE_CFG:
2960 msr_info->data = svm->msr_decfg;
2961 break;
2962 default:
2963 return kvm_get_msr_common(vcpu, msr_info);
2964 }
2965 return 0;
2966 }
2967
svm_complete_emulated_msr(struct kvm_vcpu * vcpu,int err)2968 static int svm_complete_emulated_msr(struct kvm_vcpu *vcpu, int err)
2969 {
2970 struct vcpu_svm *svm = to_svm(vcpu);
2971 if (!err || !sev_es_guest(vcpu->kvm) || WARN_ON_ONCE(!svm->sev_es.ghcb))
2972 return kvm_complete_insn_gp(vcpu, err);
2973
2974 ghcb_set_sw_exit_info_1(svm->sev_es.ghcb, 1);
2975 ghcb_set_sw_exit_info_2(svm->sev_es.ghcb,
2976 X86_TRAP_GP |
2977 SVM_EVTINJ_TYPE_EXEPT |
2978 SVM_EVTINJ_VALID);
2979 return 1;
2980 }
2981
svm_set_vm_cr(struct kvm_vcpu * vcpu,u64 data)2982 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
2983 {
2984 struct vcpu_svm *svm = to_svm(vcpu);
2985 int svm_dis, chg_mask;
2986
2987 if (data & ~SVM_VM_CR_VALID_MASK)
2988 return 1;
2989
2990 chg_mask = SVM_VM_CR_VALID_MASK;
2991
2992 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
2993 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
2994
2995 svm->nested.vm_cr_msr &= ~chg_mask;
2996 svm->nested.vm_cr_msr |= (data & chg_mask);
2997
2998 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
2999
3000 /* check for svm_disable while efer.svme is set */
3001 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
3002 return 1;
3003
3004 return 0;
3005 }
3006
svm_set_msr(struct kvm_vcpu * vcpu,struct msr_data * msr)3007 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
3008 {
3009 struct vcpu_svm *svm = to_svm(vcpu);
3010 int ret = 0;
3011
3012 u32 ecx = msr->index;
3013 u64 data = msr->data;
3014 switch (ecx) {
3015 case MSR_AMD64_TSC_RATIO:
3016
3017 if (!guest_can_use(vcpu, X86_FEATURE_TSCRATEMSR)) {
3018
3019 if (!msr->host_initiated)
3020 return 1;
3021 /*
3022 * In case TSC scaling is not enabled, always
3023 * leave this MSR at the default value.
3024 *
3025 * Due to bug in qemu 6.2.0, it would try to set
3026 * this msr to 0 if tsc scaling is not enabled.
3027 * Ignore this value as well.
3028 */
3029 if (data != 0 && data != svm->tsc_ratio_msr)
3030 return 1;
3031 break;
3032 }
3033
3034 if (data & SVM_TSC_RATIO_RSVD)
3035 return 1;
3036
3037 svm->tsc_ratio_msr = data;
3038
3039 if (guest_can_use(vcpu, X86_FEATURE_TSCRATEMSR) &&
3040 is_guest_mode(vcpu))
3041 nested_svm_update_tsc_ratio_msr(vcpu);
3042
3043 break;
3044 case MSR_IA32_CR_PAT:
3045 ret = kvm_set_msr_common(vcpu, msr);
3046 if (ret)
3047 break;
3048
3049 svm->vmcb01.ptr->save.g_pat = data;
3050 if (is_guest_mode(vcpu))
3051 nested_vmcb02_compute_g_pat(svm);
3052 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
3053 break;
3054 case MSR_IA32_SPEC_CTRL:
3055 if (!msr->host_initiated &&
3056 !guest_has_spec_ctrl_msr(vcpu))
3057 return 1;
3058
3059 if (kvm_spec_ctrl_test_value(data))
3060 return 1;
3061
3062 if (boot_cpu_has(X86_FEATURE_V_SPEC_CTRL))
3063 svm->vmcb->save.spec_ctrl = data;
3064 else
3065 svm->spec_ctrl = data;
3066 if (!data)
3067 break;
3068
3069 /*
3070 * For non-nested:
3071 * When it's written (to non-zero) for the first time, pass
3072 * it through.
3073 *
3074 * For nested:
3075 * The handling of the MSR bitmap for L2 guests is done in
3076 * nested_svm_vmrun_msrpm.
3077 * We update the L1 MSR bit as well since it will end up
3078 * touching the MSR anyway now.
3079 */
3080 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
3081 break;
3082 case MSR_AMD64_VIRT_SPEC_CTRL:
3083 if (!msr->host_initiated &&
3084 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
3085 return 1;
3086
3087 if (data & ~SPEC_CTRL_SSBD)
3088 return 1;
3089
3090 svm->virt_spec_ctrl = data;
3091 break;
3092 case MSR_STAR:
3093 svm->vmcb01.ptr->save.star = data;
3094 break;
3095 #ifdef CONFIG_X86_64
3096 case MSR_LSTAR:
3097 svm->vmcb01.ptr->save.lstar = data;
3098 break;
3099 case MSR_CSTAR:
3100 svm->vmcb01.ptr->save.cstar = data;
3101 break;
3102 case MSR_GS_BASE:
3103 svm->vmcb01.ptr->save.gs.base = data;
3104 break;
3105 case MSR_FS_BASE:
3106 svm->vmcb01.ptr->save.fs.base = data;
3107 break;
3108 case MSR_KERNEL_GS_BASE:
3109 svm->vmcb01.ptr->save.kernel_gs_base = data;
3110 break;
3111 case MSR_SYSCALL_MASK:
3112 svm->vmcb01.ptr->save.sfmask = data;
3113 break;
3114 #endif
3115 case MSR_IA32_SYSENTER_CS:
3116 svm->vmcb01.ptr->save.sysenter_cs = data;
3117 break;
3118 case MSR_IA32_SYSENTER_EIP:
3119 svm->vmcb01.ptr->save.sysenter_eip = (u32)data;
3120 /*
3121 * We only intercept the MSR_IA32_SYSENTER_{EIP|ESP} msrs
3122 * when we spoof an Intel vendor ID (for cross vendor migration).
3123 * In this case we use this intercept to track the high
3124 * 32 bit part of these msrs to support Intel's
3125 * implementation of SYSENTER/SYSEXIT.
3126 */
3127 svm->sysenter_eip_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
3128 break;
3129 case MSR_IA32_SYSENTER_ESP:
3130 svm->vmcb01.ptr->save.sysenter_esp = (u32)data;
3131 svm->sysenter_esp_hi = guest_cpuid_is_intel(vcpu) ? (data >> 32) : 0;
3132 break;
3133 case MSR_TSC_AUX:
3134 /*
3135 * TSC_AUX is always virtualized for SEV-ES guests when the
3136 * feature is available. The user return MSR support is not
3137 * required in this case because TSC_AUX is restored on #VMEXIT
3138 * from the host save area (which has been initialized in
3139 * svm_hardware_enable()).
3140 */
3141 if (boot_cpu_has(X86_FEATURE_V_TSC_AUX) && sev_es_guest(vcpu->kvm))
3142 break;
3143
3144 /*
3145 * TSC_AUX is usually changed only during boot and never read
3146 * directly. Intercept TSC_AUX instead of exposing it to the
3147 * guest via direct_access_msrs, and switch it via user return.
3148 */
3149 preempt_disable();
3150 ret = kvm_set_user_return_msr(tsc_aux_uret_slot, data, -1ull);
3151 preempt_enable();
3152 if (ret)
3153 break;
3154
3155 svm->tsc_aux = data;
3156 break;
3157 case MSR_IA32_DEBUGCTLMSR:
3158 if (!lbrv) {
3159 kvm_pr_unimpl_wrmsr(vcpu, ecx, data);
3160 break;
3161 }
3162
3163 /*
3164 * AMD changed the architectural behavior of bits 5:2. On CPUs
3165 * without BusLockTrap, bits 5:2 control "external pins", but
3166 * on CPUs that support BusLockDetect, bit 2 enables BusLockTrap
3167 * and bits 5:3 are reserved-to-zero. Sadly, old KVM allowed
3168 * the guest to set bits 5:2 despite not actually virtualizing
3169 * Performance-Monitoring/Breakpoint external pins. Drop bits
3170 * 5:2 for backwards compatibility.
3171 */
3172 data &= ~GENMASK(5, 2);
3173
3174 /*
3175 * Suppress BTF as KVM doesn't virtualize BTF, but there's no
3176 * way to communicate lack of support to the guest.
3177 */
3178 if (data & DEBUGCTLMSR_BTF) {
3179 kvm_pr_unimpl_wrmsr(vcpu, MSR_IA32_DEBUGCTLMSR, data);
3180 data &= ~DEBUGCTLMSR_BTF;
3181 }
3182
3183 if (data & DEBUGCTL_RESERVED_BITS)
3184 return 1;
3185
3186 svm_get_lbr_vmcb(svm)->save.dbgctl = data;
3187 svm_update_lbrv(vcpu);
3188 break;
3189 case MSR_VM_HSAVE_PA:
3190 /*
3191 * Old kernels did not validate the value written to
3192 * MSR_VM_HSAVE_PA. Allow KVM_SET_MSR to set an invalid
3193 * value to allow live migrating buggy or malicious guests
3194 * originating from those kernels.
3195 */
3196 if (!msr->host_initiated && !page_address_valid(vcpu, data))
3197 return 1;
3198
3199 svm->nested.hsave_msr = data & PAGE_MASK;
3200 break;
3201 case MSR_VM_CR:
3202 return svm_set_vm_cr(vcpu, data);
3203 case MSR_VM_IGNNE:
3204 kvm_pr_unimpl_wrmsr(vcpu, ecx, data);
3205 break;
3206 case MSR_AMD64_DE_CFG: {
3207 struct kvm_msr_entry msr_entry;
3208
3209 msr_entry.index = msr->index;
3210 if (svm_get_msr_feature(&msr_entry))
3211 return 1;
3212
3213 /* Check the supported bits */
3214 if (data & ~msr_entry.data)
3215 return 1;
3216
3217 /* Don't allow the guest to change a bit, #GP */
3218 if (!msr->host_initiated && (data ^ msr_entry.data))
3219 return 1;
3220
3221 svm->msr_decfg = data;
3222 break;
3223 }
3224 default:
3225 return kvm_set_msr_common(vcpu, msr);
3226 }
3227 return ret;
3228 }
3229
msr_interception(struct kvm_vcpu * vcpu)3230 static int msr_interception(struct kvm_vcpu *vcpu)
3231 {
3232 if (to_svm(vcpu)->vmcb->control.exit_info_1)
3233 return kvm_emulate_wrmsr(vcpu);
3234 else
3235 return kvm_emulate_rdmsr(vcpu);
3236 }
3237
interrupt_window_interception(struct kvm_vcpu * vcpu)3238 static int interrupt_window_interception(struct kvm_vcpu *vcpu)
3239 {
3240 kvm_make_request(KVM_REQ_EVENT, vcpu);
3241 svm_clear_vintr(to_svm(vcpu));
3242
3243 /*
3244 * If not running nested, for AVIC, the only reason to end up here is ExtINTs.
3245 * In this case AVIC was temporarily disabled for
3246 * requesting the IRQ window and we have to re-enable it.
3247 *
3248 * If running nested, still remove the VM wide AVIC inhibit to
3249 * support case in which the interrupt window was requested when the
3250 * vCPU was not running nested.
3251
3252 * All vCPUs which run still run nested, will remain to have their
3253 * AVIC still inhibited due to per-cpu AVIC inhibition.
3254 */
3255 kvm_clear_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
3256
3257 ++vcpu->stat.irq_window_exits;
3258 return 1;
3259 }
3260
pause_interception(struct kvm_vcpu * vcpu)3261 static int pause_interception(struct kvm_vcpu *vcpu)
3262 {
3263 bool in_kernel;
3264 /*
3265 * CPL is not made available for an SEV-ES guest, therefore
3266 * vcpu->arch.preempted_in_kernel can never be true. Just
3267 * set in_kernel to false as well.
3268 */
3269 in_kernel = !sev_es_guest(vcpu->kvm) && svm_get_cpl(vcpu) == 0;
3270
3271 grow_ple_window(vcpu);
3272
3273 kvm_vcpu_on_spin(vcpu, in_kernel);
3274 return kvm_skip_emulated_instruction(vcpu);
3275 }
3276
invpcid_interception(struct kvm_vcpu * vcpu)3277 static int invpcid_interception(struct kvm_vcpu *vcpu)
3278 {
3279 struct vcpu_svm *svm = to_svm(vcpu);
3280 unsigned long type;
3281 gva_t gva;
3282
3283 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
3284 kvm_queue_exception(vcpu, UD_VECTOR);
3285 return 1;
3286 }
3287
3288 /*
3289 * For an INVPCID intercept:
3290 * EXITINFO1 provides the linear address of the memory operand.
3291 * EXITINFO2 provides the contents of the register operand.
3292 */
3293 type = svm->vmcb->control.exit_info_2;
3294 gva = svm->vmcb->control.exit_info_1;
3295
3296 return kvm_handle_invpcid(vcpu, type, gva);
3297 }
3298
3299 static int (*const svm_exit_handlers[])(struct kvm_vcpu *vcpu) = {
3300 [SVM_EXIT_READ_CR0] = cr_interception,
3301 [SVM_EXIT_READ_CR3] = cr_interception,
3302 [SVM_EXIT_READ_CR4] = cr_interception,
3303 [SVM_EXIT_READ_CR8] = cr_interception,
3304 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
3305 [SVM_EXIT_WRITE_CR0] = cr_interception,
3306 [SVM_EXIT_WRITE_CR3] = cr_interception,
3307 [SVM_EXIT_WRITE_CR4] = cr_interception,
3308 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
3309 [SVM_EXIT_READ_DR0] = dr_interception,
3310 [SVM_EXIT_READ_DR1] = dr_interception,
3311 [SVM_EXIT_READ_DR2] = dr_interception,
3312 [SVM_EXIT_READ_DR3] = dr_interception,
3313 [SVM_EXIT_READ_DR4] = dr_interception,
3314 [SVM_EXIT_READ_DR5] = dr_interception,
3315 [SVM_EXIT_READ_DR6] = dr_interception,
3316 [SVM_EXIT_READ_DR7] = dr_interception,
3317 [SVM_EXIT_WRITE_DR0] = dr_interception,
3318 [SVM_EXIT_WRITE_DR1] = dr_interception,
3319 [SVM_EXIT_WRITE_DR2] = dr_interception,
3320 [SVM_EXIT_WRITE_DR3] = dr_interception,
3321 [SVM_EXIT_WRITE_DR4] = dr_interception,
3322 [SVM_EXIT_WRITE_DR5] = dr_interception,
3323 [SVM_EXIT_WRITE_DR6] = dr_interception,
3324 [SVM_EXIT_WRITE_DR7] = dr_interception,
3325 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
3326 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
3327 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
3328 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
3329 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
3330 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
3331 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
3332 [SVM_EXIT_INTR] = intr_interception,
3333 [SVM_EXIT_NMI] = nmi_interception,
3334 [SVM_EXIT_SMI] = smi_interception,
3335 [SVM_EXIT_VINTR] = interrupt_window_interception,
3336 [SVM_EXIT_RDPMC] = kvm_emulate_rdpmc,
3337 [SVM_EXIT_CPUID] = kvm_emulate_cpuid,
3338 [SVM_EXIT_IRET] = iret_interception,
3339 [SVM_EXIT_INVD] = kvm_emulate_invd,
3340 [SVM_EXIT_PAUSE] = pause_interception,
3341 [SVM_EXIT_HLT] = kvm_emulate_halt,
3342 [SVM_EXIT_INVLPG] = invlpg_interception,
3343 [SVM_EXIT_INVLPGA] = invlpga_interception,
3344 [SVM_EXIT_IOIO] = io_interception,
3345 [SVM_EXIT_MSR] = msr_interception,
3346 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
3347 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
3348 [SVM_EXIT_VMRUN] = vmrun_interception,
3349 [SVM_EXIT_VMMCALL] = kvm_emulate_hypercall,
3350 [SVM_EXIT_VMLOAD] = vmload_interception,
3351 [SVM_EXIT_VMSAVE] = vmsave_interception,
3352 [SVM_EXIT_STGI] = stgi_interception,
3353 [SVM_EXIT_CLGI] = clgi_interception,
3354 [SVM_EXIT_SKINIT] = skinit_interception,
3355 [SVM_EXIT_RDTSCP] = kvm_handle_invalid_op,
3356 [SVM_EXIT_WBINVD] = kvm_emulate_wbinvd,
3357 [SVM_EXIT_MONITOR] = kvm_emulate_monitor,
3358 [SVM_EXIT_MWAIT] = kvm_emulate_mwait,
3359 [SVM_EXIT_XSETBV] = kvm_emulate_xsetbv,
3360 [SVM_EXIT_RDPRU] = kvm_handle_invalid_op,
3361 [SVM_EXIT_EFER_WRITE_TRAP] = efer_trap,
3362 [SVM_EXIT_CR0_WRITE_TRAP] = cr_trap,
3363 [SVM_EXIT_CR4_WRITE_TRAP] = cr_trap,
3364 [SVM_EXIT_CR8_WRITE_TRAP] = cr_trap,
3365 [SVM_EXIT_INVPCID] = invpcid_interception,
3366 [SVM_EXIT_NPF] = npf_interception,
3367 [SVM_EXIT_RSM] = rsm_interception,
3368 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
3369 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
3370 [SVM_EXIT_VMGEXIT] = sev_handle_vmgexit,
3371 };
3372
dump_vmcb(struct kvm_vcpu * vcpu)3373 static void dump_vmcb(struct kvm_vcpu *vcpu)
3374 {
3375 struct vcpu_svm *svm = to_svm(vcpu);
3376 struct vmcb_control_area *control = &svm->vmcb->control;
3377 struct vmcb_save_area *save = &svm->vmcb->save;
3378 struct vmcb_save_area *save01 = &svm->vmcb01.ptr->save;
3379
3380 if (!dump_invalid_vmcb) {
3381 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
3382 return;
3383 }
3384
3385 pr_err("VMCB %p, last attempted VMRUN on CPU %d\n",
3386 svm->current_vmcb->ptr, vcpu->arch.last_vmentry_cpu);
3387 pr_err("VMCB Control Area:\n");
3388 pr_err("%-20s%04x\n", "cr_read:", control->intercepts[INTERCEPT_CR] & 0xffff);
3389 pr_err("%-20s%04x\n", "cr_write:", control->intercepts[INTERCEPT_CR] >> 16);
3390 pr_err("%-20s%04x\n", "dr_read:", control->intercepts[INTERCEPT_DR] & 0xffff);
3391 pr_err("%-20s%04x\n", "dr_write:", control->intercepts[INTERCEPT_DR] >> 16);
3392 pr_err("%-20s%08x\n", "exceptions:", control->intercepts[INTERCEPT_EXCEPTION]);
3393 pr_err("%-20s%08x %08x\n", "intercepts:",
3394 control->intercepts[INTERCEPT_WORD3],
3395 control->intercepts[INTERCEPT_WORD4]);
3396 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3397 pr_err("%-20s%d\n", "pause filter threshold:",
3398 control->pause_filter_thresh);
3399 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3400 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3401 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3402 pr_err("%-20s%d\n", "asid:", control->asid);
3403 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3404 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3405 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3406 pr_err("%-20s%08x\n", "int_state:", control->int_state);
3407 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3408 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3409 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3410 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3411 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3412 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3413 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3414 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
3415 pr_err("%-20s%016llx\n", "ghcb:", control->ghcb_gpa);
3416 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3417 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3418 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
3419 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3420 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
3421 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
3422 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
3423 pr_err("%-20s%016llx\n", "vmsa_pa:", control->vmsa_pa);
3424 pr_err("VMCB State Save Area:\n");
3425 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3426 "es:",
3427 save->es.selector, save->es.attrib,
3428 save->es.limit, save->es.base);
3429 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3430 "cs:",
3431 save->cs.selector, save->cs.attrib,
3432 save->cs.limit, save->cs.base);
3433 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3434 "ss:",
3435 save->ss.selector, save->ss.attrib,
3436 save->ss.limit, save->ss.base);
3437 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3438 "ds:",
3439 save->ds.selector, save->ds.attrib,
3440 save->ds.limit, save->ds.base);
3441 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3442 "fs:",
3443 save01->fs.selector, save01->fs.attrib,
3444 save01->fs.limit, save01->fs.base);
3445 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3446 "gs:",
3447 save01->gs.selector, save01->gs.attrib,
3448 save01->gs.limit, save01->gs.base);
3449 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3450 "gdtr:",
3451 save->gdtr.selector, save->gdtr.attrib,
3452 save->gdtr.limit, save->gdtr.base);
3453 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3454 "ldtr:",
3455 save01->ldtr.selector, save01->ldtr.attrib,
3456 save01->ldtr.limit, save01->ldtr.base);
3457 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3458 "idtr:",
3459 save->idtr.selector, save->idtr.attrib,
3460 save->idtr.limit, save->idtr.base);
3461 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3462 "tr:",
3463 save01->tr.selector, save01->tr.attrib,
3464 save01->tr.limit, save01->tr.base);
3465 pr_err("vmpl: %d cpl: %d efer: %016llx\n",
3466 save->vmpl, save->cpl, save->efer);
3467 pr_err("%-15s %016llx %-13s %016llx\n",
3468 "cr0:", save->cr0, "cr2:", save->cr2);
3469 pr_err("%-15s %016llx %-13s %016llx\n",
3470 "cr3:", save->cr3, "cr4:", save->cr4);
3471 pr_err("%-15s %016llx %-13s %016llx\n",
3472 "dr6:", save->dr6, "dr7:", save->dr7);
3473 pr_err("%-15s %016llx %-13s %016llx\n",
3474 "rip:", save->rip, "rflags:", save->rflags);
3475 pr_err("%-15s %016llx %-13s %016llx\n",
3476 "rsp:", save->rsp, "rax:", save->rax);
3477 pr_err("%-15s %016llx %-13s %016llx\n",
3478 "star:", save01->star, "lstar:", save01->lstar);
3479 pr_err("%-15s %016llx %-13s %016llx\n",
3480 "cstar:", save01->cstar, "sfmask:", save01->sfmask);
3481 pr_err("%-15s %016llx %-13s %016llx\n",
3482 "kernel_gs_base:", save01->kernel_gs_base,
3483 "sysenter_cs:", save01->sysenter_cs);
3484 pr_err("%-15s %016llx %-13s %016llx\n",
3485 "sysenter_esp:", save01->sysenter_esp,
3486 "sysenter_eip:", save01->sysenter_eip);
3487 pr_err("%-15s %016llx %-13s %016llx\n",
3488 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3489 pr_err("%-15s %016llx %-13s %016llx\n",
3490 "br_from:", save->br_from, "br_to:", save->br_to);
3491 pr_err("%-15s %016llx %-13s %016llx\n",
3492 "excp_from:", save->last_excp_from,
3493 "excp_to:", save->last_excp_to);
3494 }
3495
svm_check_exit_valid(u64 exit_code)3496 static bool svm_check_exit_valid(u64 exit_code)
3497 {
3498 return (exit_code < ARRAY_SIZE(svm_exit_handlers) &&
3499 svm_exit_handlers[exit_code]);
3500 }
3501
svm_handle_invalid_exit(struct kvm_vcpu * vcpu,u64 exit_code)3502 static int svm_handle_invalid_exit(struct kvm_vcpu *vcpu, u64 exit_code)
3503 {
3504 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%llx\n", exit_code);
3505 dump_vmcb(vcpu);
3506 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3507 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
3508 vcpu->run->internal.ndata = 2;
3509 vcpu->run->internal.data[0] = exit_code;
3510 vcpu->run->internal.data[1] = vcpu->arch.last_vmentry_cpu;
3511 return 0;
3512 }
3513
svm_invoke_exit_handler(struct kvm_vcpu * vcpu,u64 exit_code)3514 int svm_invoke_exit_handler(struct kvm_vcpu *vcpu, u64 exit_code)
3515 {
3516 if (!svm_check_exit_valid(exit_code))
3517 return svm_handle_invalid_exit(vcpu, exit_code);
3518
3519 #ifdef CONFIG_RETPOLINE
3520 if (exit_code == SVM_EXIT_MSR)
3521 return msr_interception(vcpu);
3522 else if (exit_code == SVM_EXIT_VINTR)
3523 return interrupt_window_interception(vcpu);
3524 else if (exit_code == SVM_EXIT_INTR)
3525 return intr_interception(vcpu);
3526 else if (exit_code == SVM_EXIT_HLT)
3527 return kvm_emulate_halt(vcpu);
3528 else if (exit_code == SVM_EXIT_NPF)
3529 return npf_interception(vcpu);
3530 #endif
3531 return svm_exit_handlers[exit_code](vcpu);
3532 }
3533
svm_get_exit_info(struct kvm_vcpu * vcpu,u32 * reason,u64 * info1,u64 * info2,u32 * intr_info,u32 * error_code)3534 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason,
3535 u64 *info1, u64 *info2,
3536 u32 *intr_info, u32 *error_code)
3537 {
3538 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3539
3540 *reason = control->exit_code;
3541 *info1 = control->exit_info_1;
3542 *info2 = control->exit_info_2;
3543 *intr_info = control->exit_int_info;
3544 if ((*intr_info & SVM_EXITINTINFO_VALID) &&
3545 (*intr_info & SVM_EXITINTINFO_VALID_ERR))
3546 *error_code = control->exit_int_info_err;
3547 else
3548 *error_code = 0;
3549 }
3550
svm_handle_exit(struct kvm_vcpu * vcpu,fastpath_t exit_fastpath)3551 static int svm_handle_exit(struct kvm_vcpu *vcpu, fastpath_t exit_fastpath)
3552 {
3553 struct vcpu_svm *svm = to_svm(vcpu);
3554 struct kvm_run *kvm_run = vcpu->run;
3555 u32 exit_code = svm->vmcb->control.exit_code;
3556
3557 /* SEV-ES guests must use the CR write traps to track CR registers. */
3558 if (!sev_es_guest(vcpu->kvm)) {
3559 if (!svm_is_intercept(svm, INTERCEPT_CR0_WRITE))
3560 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3561 if (npt_enabled)
3562 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3563 }
3564
3565 if (is_guest_mode(vcpu)) {
3566 int vmexit;
3567
3568 trace_kvm_nested_vmexit(vcpu, KVM_ISA_SVM);
3569
3570 vmexit = nested_svm_exit_special(svm);
3571
3572 if (vmexit == NESTED_EXIT_CONTINUE)
3573 vmexit = nested_svm_exit_handled(svm);
3574
3575 if (vmexit == NESTED_EXIT_DONE)
3576 return 1;
3577 }
3578
3579 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3580 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3581 kvm_run->fail_entry.hardware_entry_failure_reason
3582 = svm->vmcb->control.exit_code;
3583 kvm_run->fail_entry.cpu = vcpu->arch.last_vmentry_cpu;
3584 dump_vmcb(vcpu);
3585 return 0;
3586 }
3587
3588 if (exit_fastpath != EXIT_FASTPATH_NONE)
3589 return 1;
3590
3591 return svm_invoke_exit_handler(vcpu, exit_code);
3592 }
3593
pre_svm_run(struct kvm_vcpu * vcpu)3594 static void pre_svm_run(struct kvm_vcpu *vcpu)
3595 {
3596 struct svm_cpu_data *sd = per_cpu_ptr(&svm_data, vcpu->cpu);
3597 struct vcpu_svm *svm = to_svm(vcpu);
3598
3599 /*
3600 * If the previous vmrun of the vmcb occurred on a different physical
3601 * cpu, then mark the vmcb dirty and assign a new asid. Hardware's
3602 * vmcb clean bits are per logical CPU, as are KVM's asid assignments.
3603 */
3604 if (unlikely(svm->current_vmcb->cpu != vcpu->cpu)) {
3605 svm->current_vmcb->asid_generation = 0;
3606 vmcb_mark_all_dirty(svm->vmcb);
3607 svm->current_vmcb->cpu = vcpu->cpu;
3608 }
3609
3610 if (sev_guest(vcpu->kvm))
3611 return pre_sev_run(svm, vcpu->cpu);
3612
3613 /* FIXME: handle wraparound of asid_generation */
3614 if (svm->current_vmcb->asid_generation != sd->asid_generation)
3615 new_asid(svm, sd);
3616 }
3617
svm_inject_nmi(struct kvm_vcpu * vcpu)3618 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3619 {
3620 struct vcpu_svm *svm = to_svm(vcpu);
3621
3622 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3623
3624 if (svm->nmi_l1_to_l2)
3625 return;
3626
3627 svm->nmi_masked = true;
3628 svm_set_iret_intercept(svm);
3629 ++vcpu->stat.nmi_injections;
3630 }
3631
svm_is_vnmi_pending(struct kvm_vcpu * vcpu)3632 static bool svm_is_vnmi_pending(struct kvm_vcpu *vcpu)
3633 {
3634 struct vcpu_svm *svm = to_svm(vcpu);
3635
3636 if (!is_vnmi_enabled(svm))
3637 return false;
3638
3639 return !!(svm->vmcb->control.int_ctl & V_NMI_PENDING_MASK);
3640 }
3641
svm_set_vnmi_pending(struct kvm_vcpu * vcpu)3642 static bool svm_set_vnmi_pending(struct kvm_vcpu *vcpu)
3643 {
3644 struct vcpu_svm *svm = to_svm(vcpu);
3645
3646 if (!is_vnmi_enabled(svm))
3647 return false;
3648
3649 if (svm->vmcb->control.int_ctl & V_NMI_PENDING_MASK)
3650 return false;
3651
3652 svm->vmcb->control.int_ctl |= V_NMI_PENDING_MASK;
3653 vmcb_mark_dirty(svm->vmcb, VMCB_INTR);
3654
3655 /*
3656 * Because the pending NMI is serviced by hardware, KVM can't know when
3657 * the NMI is "injected", but for all intents and purposes, passing the
3658 * NMI off to hardware counts as injection.
3659 */
3660 ++vcpu->stat.nmi_injections;
3661
3662 return true;
3663 }
3664
svm_inject_irq(struct kvm_vcpu * vcpu,bool reinjected)3665 static void svm_inject_irq(struct kvm_vcpu *vcpu, bool reinjected)
3666 {
3667 struct vcpu_svm *svm = to_svm(vcpu);
3668 u32 type;
3669
3670 if (vcpu->arch.interrupt.soft) {
3671 if (svm_update_soft_interrupt_rip(vcpu))
3672 return;
3673
3674 type = SVM_EVTINJ_TYPE_SOFT;
3675 } else {
3676 type = SVM_EVTINJ_TYPE_INTR;
3677 }
3678
3679 trace_kvm_inj_virq(vcpu->arch.interrupt.nr,
3680 vcpu->arch.interrupt.soft, reinjected);
3681 ++vcpu->stat.irq_injections;
3682
3683 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3684 SVM_EVTINJ_VALID | type;
3685 }
3686
svm_complete_interrupt_delivery(struct kvm_vcpu * vcpu,int delivery_mode,int trig_mode,int vector)3687 void svm_complete_interrupt_delivery(struct kvm_vcpu *vcpu, int delivery_mode,
3688 int trig_mode, int vector)
3689 {
3690 /*
3691 * apic->apicv_active must be read after vcpu->mode.
3692 * Pairs with smp_store_release in vcpu_enter_guest.
3693 */
3694 bool in_guest_mode = (smp_load_acquire(&vcpu->mode) == IN_GUEST_MODE);
3695
3696 /* Note, this is called iff the local APIC is in-kernel. */
3697 if (!READ_ONCE(vcpu->arch.apic->apicv_active)) {
3698 /* Process the interrupt via kvm_check_and_inject_events(). */
3699 kvm_make_request(KVM_REQ_EVENT, vcpu);
3700 kvm_vcpu_kick(vcpu);
3701 return;
3702 }
3703
3704 trace_kvm_apicv_accept_irq(vcpu->vcpu_id, delivery_mode, trig_mode, vector);
3705 if (in_guest_mode) {
3706 /*
3707 * Signal the doorbell to tell hardware to inject the IRQ. If
3708 * the vCPU exits the guest before the doorbell chimes, hardware
3709 * will automatically process AVIC interrupts at the next VMRUN.
3710 */
3711 avic_ring_doorbell(vcpu);
3712 } else {
3713 /*
3714 * Wake the vCPU if it was blocking. KVM will then detect the
3715 * pending IRQ when checking if the vCPU has a wake event.
3716 */
3717 kvm_vcpu_wake_up(vcpu);
3718 }
3719 }
3720
svm_deliver_interrupt(struct kvm_lapic * apic,int delivery_mode,int trig_mode,int vector)3721 static void svm_deliver_interrupt(struct kvm_lapic *apic, int delivery_mode,
3722 int trig_mode, int vector)
3723 {
3724 kvm_lapic_set_irr(vector, apic);
3725
3726 /*
3727 * Pairs with the smp_mb_*() after setting vcpu->guest_mode in
3728 * vcpu_enter_guest() to ensure the write to the vIRR is ordered before
3729 * the read of guest_mode. This guarantees that either VMRUN will see
3730 * and process the new vIRR entry, or that svm_complete_interrupt_delivery
3731 * will signal the doorbell if the CPU has already entered the guest.
3732 */
3733 smp_mb__after_atomic();
3734 svm_complete_interrupt_delivery(apic->vcpu, delivery_mode, trig_mode, vector);
3735 }
3736
svm_update_cr8_intercept(struct kvm_vcpu * vcpu,int tpr,int irr)3737 static void svm_update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3738 {
3739 struct vcpu_svm *svm = to_svm(vcpu);
3740
3741 /*
3742 * SEV-ES guests must always keep the CR intercepts cleared. CR
3743 * tracking is done using the CR write traps.
3744 */
3745 if (sev_es_guest(vcpu->kvm))
3746 return;
3747
3748 if (nested_svm_virtualize_tpr(vcpu))
3749 return;
3750
3751 svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
3752
3753 if (irr == -1)
3754 return;
3755
3756 if (tpr >= irr)
3757 svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
3758 }
3759
svm_get_nmi_mask(struct kvm_vcpu * vcpu)3760 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3761 {
3762 struct vcpu_svm *svm = to_svm(vcpu);
3763
3764 if (is_vnmi_enabled(svm))
3765 return svm->vmcb->control.int_ctl & V_NMI_BLOCKING_MASK;
3766 else
3767 return svm->nmi_masked;
3768 }
3769
svm_set_nmi_mask(struct kvm_vcpu * vcpu,bool masked)3770 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3771 {
3772 struct vcpu_svm *svm = to_svm(vcpu);
3773
3774 if (is_vnmi_enabled(svm)) {
3775 if (masked)
3776 svm->vmcb->control.int_ctl |= V_NMI_BLOCKING_MASK;
3777 else
3778 svm->vmcb->control.int_ctl &= ~V_NMI_BLOCKING_MASK;
3779
3780 } else {
3781 svm->nmi_masked = masked;
3782 if (masked)
3783 svm_set_iret_intercept(svm);
3784 else
3785 svm_clr_iret_intercept(svm);
3786 }
3787 }
3788
svm_nmi_blocked(struct kvm_vcpu * vcpu)3789 bool svm_nmi_blocked(struct kvm_vcpu *vcpu)
3790 {
3791 struct vcpu_svm *svm = to_svm(vcpu);
3792 struct vmcb *vmcb = svm->vmcb;
3793
3794 if (!gif_set(svm))
3795 return true;
3796
3797 if (is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3798 return false;
3799
3800 if (svm_get_nmi_mask(vcpu))
3801 return true;
3802
3803 return vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK;
3804 }
3805
svm_nmi_allowed(struct kvm_vcpu * vcpu,bool for_injection)3806 static int svm_nmi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3807 {
3808 struct vcpu_svm *svm = to_svm(vcpu);
3809 if (svm->nested.nested_run_pending)
3810 return -EBUSY;
3811
3812 if (svm_nmi_blocked(vcpu))
3813 return 0;
3814
3815 /* An NMI must not be injected into L2 if it's supposed to VM-Exit. */
3816 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_nmi(svm))
3817 return -EBUSY;
3818 return 1;
3819 }
3820
svm_interrupt_blocked(struct kvm_vcpu * vcpu)3821 bool svm_interrupt_blocked(struct kvm_vcpu *vcpu)
3822 {
3823 struct vcpu_svm *svm = to_svm(vcpu);
3824 struct vmcb *vmcb = svm->vmcb;
3825
3826 if (!gif_set(svm))
3827 return true;
3828
3829 if (is_guest_mode(vcpu)) {
3830 /* As long as interrupts are being delivered... */
3831 if ((svm->nested.ctl.int_ctl & V_INTR_MASKING_MASK)
3832 ? !(svm->vmcb01.ptr->save.rflags & X86_EFLAGS_IF)
3833 : !(kvm_get_rflags(vcpu) & X86_EFLAGS_IF))
3834 return true;
3835
3836 /* ... vmexits aren't blocked by the interrupt shadow */
3837 if (nested_exit_on_intr(svm))
3838 return false;
3839 } else {
3840 if (!svm_get_if_flag(vcpu))
3841 return true;
3842 }
3843
3844 return (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK);
3845 }
3846
svm_interrupt_allowed(struct kvm_vcpu * vcpu,bool for_injection)3847 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu, bool for_injection)
3848 {
3849 struct vcpu_svm *svm = to_svm(vcpu);
3850
3851 if (svm->nested.nested_run_pending)
3852 return -EBUSY;
3853
3854 if (svm_interrupt_blocked(vcpu))
3855 return 0;
3856
3857 /*
3858 * An IRQ must not be injected into L2 if it's supposed to VM-Exit,
3859 * e.g. if the IRQ arrived asynchronously after checking nested events.
3860 */
3861 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_intr(svm))
3862 return -EBUSY;
3863
3864 return 1;
3865 }
3866
svm_enable_irq_window(struct kvm_vcpu * vcpu)3867 static void svm_enable_irq_window(struct kvm_vcpu *vcpu)
3868 {
3869 struct vcpu_svm *svm = to_svm(vcpu);
3870
3871 /*
3872 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3873 * 1, because that's a separate STGI/VMRUN intercept. The next time we
3874 * get that intercept, this function will be called again though and
3875 * we'll get the vintr intercept. However, if the vGIF feature is
3876 * enabled, the STGI interception will not occur. Enable the irq
3877 * window under the assumption that the hardware will set the GIF.
3878 */
3879 if (vgif || gif_set(svm)) {
3880 /*
3881 * IRQ window is not needed when AVIC is enabled,
3882 * unless we have pending ExtINT since it cannot be injected
3883 * via AVIC. In such case, KVM needs to temporarily disable AVIC,
3884 * and fallback to injecting IRQ via V_IRQ.
3885 *
3886 * If running nested, AVIC is already locally inhibited
3887 * on this vCPU, therefore there is no need to request
3888 * the VM wide AVIC inhibition.
3889 */
3890 if (!is_guest_mode(vcpu))
3891 kvm_set_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_IRQWIN);
3892
3893 svm_set_vintr(svm);
3894 }
3895 }
3896
svm_enable_nmi_window(struct kvm_vcpu * vcpu)3897 static void svm_enable_nmi_window(struct kvm_vcpu *vcpu)
3898 {
3899 struct vcpu_svm *svm = to_svm(vcpu);
3900
3901 /*
3902 * If NMIs are outright masked, i.e. the vCPU is already handling an
3903 * NMI, and KVM has not yet intercepted an IRET, then there is nothing
3904 * more to do at this time as KVM has already enabled IRET intercepts.
3905 * If KVM has already intercepted IRET, then single-step over the IRET,
3906 * as NMIs aren't architecturally unmasked until the IRET completes.
3907 *
3908 * If vNMI is enabled, KVM should never request an NMI window if NMIs
3909 * are masked, as KVM allows at most one to-be-injected NMI and one
3910 * pending NMI. If two NMIs arrive simultaneously, KVM will inject one
3911 * NMI and set V_NMI_PENDING for the other, but if and only if NMIs are
3912 * unmasked. KVM _will_ request an NMI window in some situations, e.g.
3913 * if the vCPU is in an STI shadow or if GIF=0, KVM can't immediately
3914 * inject the NMI. In those situations, KVM needs to single-step over
3915 * the STI shadow or intercept STGI.
3916 */
3917 if (svm_get_nmi_mask(vcpu)) {
3918 WARN_ON_ONCE(is_vnmi_enabled(svm));
3919
3920 if (!svm->awaiting_iret_completion)
3921 return; /* IRET will cause a vm exit */
3922 }
3923
3924 /*
3925 * SEV-ES guests are responsible for signaling when a vCPU is ready to
3926 * receive a new NMI, as SEV-ES guests can't be single-stepped, i.e.
3927 * KVM can't intercept and single-step IRET to detect when NMIs are
3928 * unblocked (architecturally speaking). See SVM_VMGEXIT_NMI_COMPLETE.
3929 *
3930 * Note, GIF is guaranteed to be '1' for SEV-ES guests as hardware
3931 * ignores SEV-ES guest writes to EFER.SVME *and* CLGI/STGI are not
3932 * supported NAEs in the GHCB protocol.
3933 */
3934 if (sev_es_guest(vcpu->kvm))
3935 return;
3936
3937 if (!gif_set(svm)) {
3938 if (vgif)
3939 svm_set_intercept(svm, INTERCEPT_STGI);
3940 return; /* STGI will cause a vm exit */
3941 }
3942
3943 /*
3944 * Something prevents NMI from been injected. Single step over possible
3945 * problem (IRET or exception injection or interrupt shadow)
3946 */
3947 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
3948 svm->nmi_singlestep = true;
3949 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3950 }
3951
svm_flush_tlb_asid(struct kvm_vcpu * vcpu)3952 static void svm_flush_tlb_asid(struct kvm_vcpu *vcpu)
3953 {
3954 struct vcpu_svm *svm = to_svm(vcpu);
3955
3956 /*
3957 * Unlike VMX, SVM doesn't provide a way to flush only NPT TLB entries.
3958 * A TLB flush for the current ASID flushes both "host" and "guest" TLB
3959 * entries, and thus is a superset of Hyper-V's fine grained flushing.
3960 */
3961 kvm_hv_vcpu_purge_flush_tlb(vcpu);
3962
3963 /*
3964 * Flush only the current ASID even if the TLB flush was invoked via
3965 * kvm_flush_remote_tlbs(). Although flushing remote TLBs requires all
3966 * ASIDs to be flushed, KVM uses a single ASID for L1 and L2, and
3967 * unconditionally does a TLB flush on both nested VM-Enter and nested
3968 * VM-Exit (via kvm_mmu_reset_context()).
3969 */
3970 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3971 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3972 else
3973 svm->current_vmcb->asid_generation--;
3974 }
3975
svm_flush_tlb_current(struct kvm_vcpu * vcpu)3976 static void svm_flush_tlb_current(struct kvm_vcpu *vcpu)
3977 {
3978 hpa_t root_tdp = vcpu->arch.mmu->root.hpa;
3979
3980 /*
3981 * When running on Hyper-V with EnlightenedNptTlb enabled, explicitly
3982 * flush the NPT mappings via hypercall as flushing the ASID only
3983 * affects virtual to physical mappings, it does not invalidate guest
3984 * physical to host physical mappings.
3985 */
3986 if (svm_hv_is_enlightened_tlb_enabled(vcpu) && VALID_PAGE(root_tdp))
3987 hyperv_flush_guest_mapping(root_tdp);
3988
3989 svm_flush_tlb_asid(vcpu);
3990 }
3991
svm_flush_tlb_all(struct kvm_vcpu * vcpu)3992 static void svm_flush_tlb_all(struct kvm_vcpu *vcpu)
3993 {
3994 /*
3995 * When running on Hyper-V with EnlightenedNptTlb enabled, remote TLB
3996 * flushes should be routed to hv_flush_remote_tlbs() without requesting
3997 * a "regular" remote flush. Reaching this point means either there's
3998 * a KVM bug or a prior hv_flush_remote_tlbs() call failed, both of
3999 * which might be fatal to the guest. Yell, but try to recover.
4000 */
4001 if (WARN_ON_ONCE(svm_hv_is_enlightened_tlb_enabled(vcpu)))
4002 hv_flush_remote_tlbs(vcpu->kvm);
4003
4004 svm_flush_tlb_asid(vcpu);
4005 }
4006
svm_flush_tlb_gva(struct kvm_vcpu * vcpu,gva_t gva)4007 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
4008 {
4009 struct vcpu_svm *svm = to_svm(vcpu);
4010
4011 invlpga(gva, svm->vmcb->control.asid);
4012 }
4013
sync_cr8_to_lapic(struct kvm_vcpu * vcpu)4014 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
4015 {
4016 struct vcpu_svm *svm = to_svm(vcpu);
4017
4018 if (nested_svm_virtualize_tpr(vcpu))
4019 return;
4020
4021 if (!svm_is_intercept(svm, INTERCEPT_CR8_WRITE)) {
4022 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
4023 kvm_set_cr8(vcpu, cr8);
4024 }
4025 }
4026
sync_lapic_to_cr8(struct kvm_vcpu * vcpu)4027 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
4028 {
4029 struct vcpu_svm *svm = to_svm(vcpu);
4030 u64 cr8;
4031
4032 if (nested_svm_virtualize_tpr(vcpu) ||
4033 kvm_vcpu_apicv_active(vcpu))
4034 return;
4035
4036 cr8 = kvm_get_cr8(vcpu);
4037 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
4038 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
4039 }
4040
svm_complete_soft_interrupt(struct kvm_vcpu * vcpu,u8 vector,int type)4041 static void svm_complete_soft_interrupt(struct kvm_vcpu *vcpu, u8 vector,
4042 int type)
4043 {
4044 bool is_exception = (type == SVM_EXITINTINFO_TYPE_EXEPT);
4045 bool is_soft = (type == SVM_EXITINTINFO_TYPE_SOFT);
4046 struct vcpu_svm *svm = to_svm(vcpu);
4047
4048 /*
4049 * If NRIPS is enabled, KVM must snapshot the pre-VMRUN next_rip that's
4050 * associated with the original soft exception/interrupt. next_rip is
4051 * cleared on all exits that can occur while vectoring an event, so KVM
4052 * needs to manually set next_rip for re-injection. Unlike the !nrips
4053 * case below, this needs to be done if and only if KVM is re-injecting
4054 * the same event, i.e. if the event is a soft exception/interrupt,
4055 * otherwise next_rip is unused on VMRUN.
4056 */
4057 if (nrips && (is_soft || (is_exception && kvm_exception_is_soft(vector))) &&
4058 kvm_is_linear_rip(vcpu, svm->soft_int_old_rip + svm->soft_int_csbase))
4059 svm->vmcb->control.next_rip = svm->soft_int_next_rip;
4060 /*
4061 * If NRIPS isn't enabled, KVM must manually advance RIP prior to
4062 * injecting the soft exception/interrupt. That advancement needs to
4063 * be unwound if vectoring didn't complete. Note, the new event may
4064 * not be the injected event, e.g. if KVM injected an INTn, the INTn
4065 * hit a #NP in the guest, and the #NP encountered a #PF, the #NP will
4066 * be the reported vectored event, but RIP still needs to be unwound.
4067 */
4068 else if (!nrips && (is_soft || is_exception) &&
4069 kvm_is_linear_rip(vcpu, svm->soft_int_next_rip + svm->soft_int_csbase))
4070 kvm_rip_write(vcpu, svm->soft_int_old_rip);
4071 }
4072
svm_complete_interrupts(struct kvm_vcpu * vcpu)4073 static void svm_complete_interrupts(struct kvm_vcpu *vcpu)
4074 {
4075 struct vcpu_svm *svm = to_svm(vcpu);
4076 u8 vector;
4077 int type;
4078 u32 exitintinfo = svm->vmcb->control.exit_int_info;
4079 bool nmi_l1_to_l2 = svm->nmi_l1_to_l2;
4080 bool soft_int_injected = svm->soft_int_injected;
4081
4082 svm->nmi_l1_to_l2 = false;
4083 svm->soft_int_injected = false;
4084
4085 /*
4086 * If we've made progress since setting awaiting_iret_completion, we've
4087 * executed an IRET and can allow NMI injection.
4088 */
4089 if (svm->awaiting_iret_completion &&
4090 kvm_rip_read(vcpu) != svm->nmi_iret_rip) {
4091 svm->awaiting_iret_completion = false;
4092 svm->nmi_masked = false;
4093 kvm_make_request(KVM_REQ_EVENT, vcpu);
4094 }
4095
4096 vcpu->arch.nmi_injected = false;
4097 kvm_clear_exception_queue(vcpu);
4098 kvm_clear_interrupt_queue(vcpu);
4099
4100 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
4101 return;
4102
4103 kvm_make_request(KVM_REQ_EVENT, vcpu);
4104
4105 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
4106 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
4107
4108 if (soft_int_injected)
4109 svm_complete_soft_interrupt(vcpu, vector, type);
4110
4111 switch (type) {
4112 case SVM_EXITINTINFO_TYPE_NMI:
4113 vcpu->arch.nmi_injected = true;
4114 svm->nmi_l1_to_l2 = nmi_l1_to_l2;
4115 break;
4116 case SVM_EXITINTINFO_TYPE_EXEPT:
4117 /*
4118 * Never re-inject a #VC exception.
4119 */
4120 if (vector == X86_TRAP_VC)
4121 break;
4122
4123 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
4124 u32 err = svm->vmcb->control.exit_int_info_err;
4125 kvm_requeue_exception_e(vcpu, vector, err);
4126
4127 } else
4128 kvm_requeue_exception(vcpu, vector);
4129 break;
4130 case SVM_EXITINTINFO_TYPE_INTR:
4131 kvm_queue_interrupt(vcpu, vector, false);
4132 break;
4133 case SVM_EXITINTINFO_TYPE_SOFT:
4134 kvm_queue_interrupt(vcpu, vector, true);
4135 break;
4136 default:
4137 break;
4138 }
4139
4140 }
4141
svm_cancel_injection(struct kvm_vcpu * vcpu)4142 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
4143 {
4144 struct vcpu_svm *svm = to_svm(vcpu);
4145 struct vmcb_control_area *control = &svm->vmcb->control;
4146
4147 control->exit_int_info = control->event_inj;
4148 control->exit_int_info_err = control->event_inj_err;
4149 control->event_inj = 0;
4150 svm_complete_interrupts(vcpu);
4151 }
4152
svm_vcpu_pre_run(struct kvm_vcpu * vcpu)4153 static int svm_vcpu_pre_run(struct kvm_vcpu *vcpu)
4154 {
4155 return 1;
4156 }
4157
svm_exit_handlers_fastpath(struct kvm_vcpu * vcpu)4158 static fastpath_t svm_exit_handlers_fastpath(struct kvm_vcpu *vcpu)
4159 {
4160 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_MSR &&
4161 to_svm(vcpu)->vmcb->control.exit_info_1)
4162 return handle_fastpath_set_msr_irqoff(vcpu);
4163
4164 return EXIT_FASTPATH_NONE;
4165 }
4166
svm_vcpu_enter_exit(struct kvm_vcpu * vcpu,bool spec_ctrl_intercepted)4167 static noinstr void svm_vcpu_enter_exit(struct kvm_vcpu *vcpu, bool spec_ctrl_intercepted)
4168 {
4169 struct vcpu_svm *svm = to_svm(vcpu);
4170
4171 guest_state_enter_irqoff();
4172
4173 amd_clear_divider();
4174
4175 if (sev_es_guest(vcpu->kvm))
4176 __svm_sev_es_vcpu_run(svm, spec_ctrl_intercepted);
4177 else
4178 __svm_vcpu_run(svm, spec_ctrl_intercepted);
4179
4180 guest_state_exit_irqoff();
4181 }
4182
svm_vcpu_run(struct kvm_vcpu * vcpu)4183 static __no_kcsan fastpath_t svm_vcpu_run(struct kvm_vcpu *vcpu)
4184 {
4185 struct vcpu_svm *svm = to_svm(vcpu);
4186 bool spec_ctrl_intercepted = msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL);
4187
4188 trace_kvm_entry(vcpu);
4189
4190 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4191 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4192 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4193
4194 /*
4195 * Disable singlestep if we're injecting an interrupt/exception.
4196 * We don't want our modified rflags to be pushed on the stack where
4197 * we might not be able to easily reset them if we disabled NMI
4198 * singlestep later.
4199 */
4200 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
4201 /*
4202 * Event injection happens before external interrupts cause a
4203 * vmexit and interrupts are disabled here, so smp_send_reschedule
4204 * is enough to force an immediate vmexit.
4205 */
4206 disable_nmi_singlestep(svm);
4207 smp_send_reschedule(vcpu->cpu);
4208 }
4209
4210 pre_svm_run(vcpu);
4211
4212 sync_lapic_to_cr8(vcpu);
4213
4214 if (unlikely(svm->asid != svm->vmcb->control.asid)) {
4215 svm->vmcb->control.asid = svm->asid;
4216 vmcb_mark_dirty(svm->vmcb, VMCB_ASID);
4217 }
4218 svm->vmcb->save.cr2 = vcpu->arch.cr2;
4219
4220 svm_hv_update_vp_id(svm->vmcb, vcpu);
4221
4222 /*
4223 * Run with all-zero DR6 unless needed, so that we can get the exact cause
4224 * of a #DB.
4225 */
4226 if (likely(!(vcpu->arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)))
4227 svm_set_dr6(vcpu, DR6_ACTIVE_LOW);
4228
4229 clgi();
4230 kvm_load_guest_xsave_state(vcpu);
4231
4232 kvm_wait_lapic_expire(vcpu);
4233
4234 /*
4235 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
4236 * it's non-zero. Since vmentry is serialising on affected CPUs, there
4237 * is no need to worry about the conditional branch over the wrmsr
4238 * being speculatively taken.
4239 */
4240 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
4241 x86_spec_ctrl_set_guest(svm->virt_spec_ctrl);
4242
4243 svm_vcpu_enter_exit(vcpu, spec_ctrl_intercepted);
4244
4245 if (!static_cpu_has(X86_FEATURE_V_SPEC_CTRL))
4246 x86_spec_ctrl_restore_host(svm->virt_spec_ctrl);
4247
4248 if (!sev_es_guest(vcpu->kvm)) {
4249 vcpu->arch.cr2 = svm->vmcb->save.cr2;
4250 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
4251 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
4252 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
4253 }
4254 vcpu->arch.regs_dirty = 0;
4255
4256 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4257 kvm_before_interrupt(vcpu, KVM_HANDLING_NMI);
4258
4259 kvm_load_host_xsave_state(vcpu);
4260 stgi();
4261
4262 /* Any pending NMI will happen here */
4263
4264 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4265 kvm_after_interrupt(vcpu);
4266
4267 sync_cr8_to_lapic(vcpu);
4268
4269 svm->next_rip = 0;
4270 if (is_guest_mode(vcpu)) {
4271 nested_sync_control_from_vmcb02(svm);
4272
4273 /* Track VMRUNs that have made past consistency checking */
4274 if (svm->nested.nested_run_pending &&
4275 svm->vmcb->control.exit_code != SVM_EXIT_ERR)
4276 ++vcpu->stat.nested_run;
4277
4278 svm->nested.nested_run_pending = 0;
4279 }
4280
4281 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
4282 vmcb_mark_all_clean(svm->vmcb);
4283
4284 /* if exit due to PF check for async PF */
4285 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
4286 vcpu->arch.apf.host_apf_flags =
4287 kvm_read_and_reset_apf_flags();
4288
4289 vcpu->arch.regs_avail &= ~SVM_REGS_LAZY_LOAD_SET;
4290
4291 /*
4292 * We need to handle MC intercepts here before the vcpu has a chance to
4293 * change the physical cpu
4294 */
4295 if (unlikely(svm->vmcb->control.exit_code ==
4296 SVM_EXIT_EXCP_BASE + MC_VECTOR))
4297 svm_handle_mce(vcpu);
4298
4299 trace_kvm_exit(vcpu, KVM_ISA_SVM);
4300
4301 svm_complete_interrupts(vcpu);
4302
4303 if (is_guest_mode(vcpu))
4304 return EXIT_FASTPATH_NONE;
4305
4306 return svm_exit_handlers_fastpath(vcpu);
4307 }
4308
svm_load_mmu_pgd(struct kvm_vcpu * vcpu,hpa_t root_hpa,int root_level)4309 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, hpa_t root_hpa,
4310 int root_level)
4311 {
4312 struct vcpu_svm *svm = to_svm(vcpu);
4313 unsigned long cr3;
4314
4315 if (npt_enabled) {
4316 svm->vmcb->control.nested_cr3 = __sme_set(root_hpa);
4317 vmcb_mark_dirty(svm->vmcb, VMCB_NPT);
4318
4319 hv_track_root_tdp(vcpu, root_hpa);
4320
4321 cr3 = vcpu->arch.cr3;
4322 } else if (root_level >= PT64_ROOT_4LEVEL) {
4323 cr3 = __sme_set(root_hpa) | kvm_get_active_pcid(vcpu);
4324 } else {
4325 /* PCID in the guest should be impossible with a 32-bit MMU. */
4326 WARN_ON_ONCE(kvm_get_active_pcid(vcpu));
4327 cr3 = root_hpa;
4328 }
4329
4330 svm->vmcb->save.cr3 = cr3;
4331 vmcb_mark_dirty(svm->vmcb, VMCB_CR);
4332 }
4333
4334 static void
svm_patch_hypercall(struct kvm_vcpu * vcpu,unsigned char * hypercall)4335 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4336 {
4337 /*
4338 * Patch in the VMMCALL instruction:
4339 */
4340 hypercall[0] = 0x0f;
4341 hypercall[1] = 0x01;
4342 hypercall[2] = 0xd9;
4343 }
4344
4345 /*
4346 * The kvm parameter can be NULL (module initialization, or invocation before
4347 * VM creation). Be sure to check the kvm parameter before using it.
4348 */
svm_has_emulated_msr(struct kvm * kvm,u32 index)4349 static bool svm_has_emulated_msr(struct kvm *kvm, u32 index)
4350 {
4351 switch (index) {
4352 case MSR_IA32_MCG_EXT_CTL:
4353 case KVM_FIRST_EMULATED_VMX_MSR ... KVM_LAST_EMULATED_VMX_MSR:
4354 return false;
4355 case MSR_IA32_SMBASE:
4356 if (!IS_ENABLED(CONFIG_KVM_SMM))
4357 return false;
4358 /* SEV-ES guests do not support SMM, so report false */
4359 if (kvm && sev_es_guest(kvm))
4360 return false;
4361 break;
4362 default:
4363 break;
4364 }
4365
4366 return true;
4367 }
4368
svm_vcpu_after_set_cpuid(struct kvm_vcpu * vcpu)4369 static void svm_vcpu_after_set_cpuid(struct kvm_vcpu *vcpu)
4370 {
4371 struct vcpu_svm *svm = to_svm(vcpu);
4372
4373 /*
4374 * SVM doesn't provide a way to disable just XSAVES in the guest, KVM
4375 * can only disable all variants of by disallowing CR4.OSXSAVE from
4376 * being set. As a result, if the host has XSAVE and XSAVES, and the
4377 * guest has XSAVE enabled, the guest can execute XSAVES without
4378 * faulting. Treat XSAVES as enabled in this case regardless of
4379 * whether it's advertised to the guest so that KVM context switches
4380 * XSS on VM-Enter/VM-Exit. Failure to do so would effectively give
4381 * the guest read/write access to the host's XSS.
4382 */
4383 if (boot_cpu_has(X86_FEATURE_XSAVE) &&
4384 boot_cpu_has(X86_FEATURE_XSAVES) &&
4385 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE))
4386 kvm_governed_feature_set(vcpu, X86_FEATURE_XSAVES);
4387
4388 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_NRIPS);
4389 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_TSCRATEMSR);
4390 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_LBRV);
4391
4392 /*
4393 * Intercept VMLOAD if the vCPU mode is Intel in order to emulate that
4394 * VMLOAD drops bits 63:32 of SYSENTER (ignoring the fact that exposing
4395 * SVM on Intel is bonkers and extremely unlikely to work).
4396 */
4397 if (!guest_cpuid_is_intel(vcpu))
4398 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_V_VMSAVE_VMLOAD);
4399
4400 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_PAUSEFILTER);
4401 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_PFTHRESHOLD);
4402 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_VGIF);
4403 kvm_governed_feature_check_and_set(vcpu, X86_FEATURE_VNMI);
4404
4405 svm_recalc_instruction_intercepts(vcpu, svm);
4406
4407 if (boot_cpu_has(X86_FEATURE_IBPB))
4408 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_PRED_CMD, 0,
4409 !!guest_has_pred_cmd_msr(vcpu));
4410
4411 if (boot_cpu_has(X86_FEATURE_FLUSH_L1D))
4412 set_msr_interception(vcpu, svm->msrpm, MSR_IA32_FLUSH_CMD, 0,
4413 !!guest_cpuid_has(vcpu, X86_FEATURE_FLUSH_L1D));
4414
4415 if (sev_guest(vcpu->kvm))
4416 sev_vcpu_after_set_cpuid(svm);
4417
4418 init_vmcb_after_set_cpuid(vcpu);
4419 }
4420
svm_has_wbinvd_exit(void)4421 static bool svm_has_wbinvd_exit(void)
4422 {
4423 return true;
4424 }
4425
4426 #define PRE_EX(exit) { .exit_code = (exit), \
4427 .stage = X86_ICPT_PRE_EXCEPT, }
4428 #define POST_EX(exit) { .exit_code = (exit), \
4429 .stage = X86_ICPT_POST_EXCEPT, }
4430 #define POST_MEM(exit) { .exit_code = (exit), \
4431 .stage = X86_ICPT_POST_MEMACCESS, }
4432
4433 static const struct __x86_intercept {
4434 u32 exit_code;
4435 enum x86_intercept_stage stage;
4436 } x86_intercept_map[] = {
4437 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
4438 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
4439 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
4440 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
4441 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
4442 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
4443 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
4444 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
4445 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
4446 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
4447 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
4448 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
4449 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
4450 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
4451 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
4452 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
4453 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
4454 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
4455 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
4456 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
4457 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
4458 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
4459 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
4460 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
4461 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
4462 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
4463 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
4464 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
4465 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
4466 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
4467 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
4468 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
4469 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
4470 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
4471 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
4472 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
4473 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
4474 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
4475 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
4476 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
4477 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
4478 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
4479 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
4480 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
4481 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
4482 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
4483 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
4484 };
4485
4486 #undef PRE_EX
4487 #undef POST_EX
4488 #undef POST_MEM
4489
svm_check_intercept(struct kvm_vcpu * vcpu,struct x86_instruction_info * info,enum x86_intercept_stage stage,struct x86_exception * exception)4490 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4491 struct x86_instruction_info *info,
4492 enum x86_intercept_stage stage,
4493 struct x86_exception *exception)
4494 {
4495 struct vcpu_svm *svm = to_svm(vcpu);
4496 int vmexit, ret = X86EMUL_CONTINUE;
4497 struct __x86_intercept icpt_info;
4498 struct vmcb *vmcb = svm->vmcb;
4499
4500 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4501 goto out;
4502
4503 icpt_info = x86_intercept_map[info->intercept];
4504
4505 if (stage != icpt_info.stage)
4506 goto out;
4507
4508 switch (icpt_info.exit_code) {
4509 case SVM_EXIT_READ_CR0:
4510 if (info->intercept == x86_intercept_cr_read)
4511 icpt_info.exit_code += info->modrm_reg;
4512 break;
4513 case SVM_EXIT_WRITE_CR0: {
4514 unsigned long cr0, val;
4515
4516 if (info->intercept == x86_intercept_cr_write)
4517 icpt_info.exit_code += info->modrm_reg;
4518
4519 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4520 info->intercept == x86_intercept_clts)
4521 break;
4522
4523 if (!(vmcb12_is_intercept(&svm->nested.ctl,
4524 INTERCEPT_SELECTIVE_CR0)))
4525 break;
4526
4527 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4528 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
4529
4530 if (info->intercept == x86_intercept_lmsw) {
4531 cr0 &= 0xfUL;
4532 val &= 0xfUL;
4533 /* lmsw can't clear PE - catch this here */
4534 if (cr0 & X86_CR0_PE)
4535 val |= X86_CR0_PE;
4536 }
4537
4538 if (cr0 ^ val)
4539 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4540
4541 break;
4542 }
4543 case SVM_EXIT_READ_DR0:
4544 case SVM_EXIT_WRITE_DR0:
4545 icpt_info.exit_code += info->modrm_reg;
4546 break;
4547 case SVM_EXIT_MSR:
4548 if (info->intercept == x86_intercept_wrmsr)
4549 vmcb->control.exit_info_1 = 1;
4550 else
4551 vmcb->control.exit_info_1 = 0;
4552 break;
4553 case SVM_EXIT_PAUSE:
4554 /*
4555 * We get this for NOP only, but pause
4556 * is rep not, check this here
4557 */
4558 if (info->rep_prefix != REPE_PREFIX)
4559 goto out;
4560 break;
4561 case SVM_EXIT_IOIO: {
4562 u64 exit_info;
4563 u32 bytes;
4564
4565 if (info->intercept == x86_intercept_in ||
4566 info->intercept == x86_intercept_ins) {
4567 exit_info = ((info->src_val & 0xffff) << 16) |
4568 SVM_IOIO_TYPE_MASK;
4569 bytes = info->dst_bytes;
4570 } else {
4571 exit_info = (info->dst_val & 0xffff) << 16;
4572 bytes = info->src_bytes;
4573 }
4574
4575 if (info->intercept == x86_intercept_outs ||
4576 info->intercept == x86_intercept_ins)
4577 exit_info |= SVM_IOIO_STR_MASK;
4578
4579 if (info->rep_prefix)
4580 exit_info |= SVM_IOIO_REP_MASK;
4581
4582 bytes = min(bytes, 4u);
4583
4584 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4585
4586 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4587
4588 vmcb->control.exit_info_1 = exit_info;
4589 vmcb->control.exit_info_2 = info->next_rip;
4590
4591 break;
4592 }
4593 default:
4594 break;
4595 }
4596
4597 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4598 if (static_cpu_has(X86_FEATURE_NRIPS))
4599 vmcb->control.next_rip = info->next_rip;
4600 vmcb->control.exit_code = icpt_info.exit_code;
4601 vmexit = nested_svm_exit_handled(svm);
4602
4603 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4604 : X86EMUL_CONTINUE;
4605
4606 out:
4607 return ret;
4608 }
4609
svm_handle_exit_irqoff(struct kvm_vcpu * vcpu)4610 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
4611 {
4612 if (to_svm(vcpu)->vmcb->control.exit_code == SVM_EXIT_INTR)
4613 vcpu->arch.at_instruction_boundary = true;
4614 }
4615
svm_sched_in(struct kvm_vcpu * vcpu,int cpu)4616 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4617 {
4618 if (!kvm_pause_in_guest(vcpu->kvm))
4619 shrink_ple_window(vcpu);
4620 }
4621
svm_setup_mce(struct kvm_vcpu * vcpu)4622 static void svm_setup_mce(struct kvm_vcpu *vcpu)
4623 {
4624 /* [63:9] are reserved. */
4625 vcpu->arch.mcg_cap &= 0x1ff;
4626 }
4627
4628 #ifdef CONFIG_KVM_SMM
svm_smi_blocked(struct kvm_vcpu * vcpu)4629 bool svm_smi_blocked(struct kvm_vcpu *vcpu)
4630 {
4631 struct vcpu_svm *svm = to_svm(vcpu);
4632
4633 /* Per APM Vol.2 15.22.2 "Response to SMI" */
4634 if (!gif_set(svm))
4635 return true;
4636
4637 return is_smm(vcpu);
4638 }
4639
svm_smi_allowed(struct kvm_vcpu * vcpu,bool for_injection)4640 static int svm_smi_allowed(struct kvm_vcpu *vcpu, bool for_injection)
4641 {
4642 struct vcpu_svm *svm = to_svm(vcpu);
4643 if (svm->nested.nested_run_pending)
4644 return -EBUSY;
4645
4646 if (svm_smi_blocked(vcpu))
4647 return 0;
4648
4649 /* An SMI must not be injected into L2 if it's supposed to VM-Exit. */
4650 if (for_injection && is_guest_mode(vcpu) && nested_exit_on_smi(svm))
4651 return -EBUSY;
4652
4653 return 1;
4654 }
4655
svm_enter_smm(struct kvm_vcpu * vcpu,union kvm_smram * smram)4656 static int svm_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram)
4657 {
4658 struct vcpu_svm *svm = to_svm(vcpu);
4659 struct kvm_host_map map_save;
4660 int ret;
4661
4662 if (!is_guest_mode(vcpu))
4663 return 0;
4664
4665 /*
4666 * 32-bit SMRAM format doesn't preserve EFER and SVM state. Userspace is
4667 * responsible for ensuring nested SVM and SMIs are mutually exclusive.
4668 */
4669
4670 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4671 return 1;
4672
4673 smram->smram64.svm_guest_flag = 1;
4674 smram->smram64.svm_guest_vmcb_gpa = svm->nested.vmcb12_gpa;
4675
4676 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
4677 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
4678 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
4679
4680 ret = nested_svm_simple_vmexit(svm, SVM_EXIT_SW);
4681 if (ret)
4682 return ret;
4683
4684 /*
4685 * KVM uses VMCB01 to store L1 host state while L2 runs but
4686 * VMCB01 is going to be used during SMM and thus the state will
4687 * be lost. Temporary save non-VMLOAD/VMSAVE state to the host save
4688 * area pointed to by MSR_VM_HSAVE_PA. APM guarantees that the
4689 * format of the area is identical to guest save area offsetted
4690 * by 0x400 (matches the offset of 'struct vmcb_save_area'
4691 * within 'struct vmcb'). Note: HSAVE area may also be used by
4692 * L1 hypervisor to save additional host context (e.g. KVM does
4693 * that, see svm_prepare_switch_to_guest()) which must be
4694 * preserved.
4695 */
4696 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save))
4697 return 1;
4698
4699 BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400);
4700
4701 svm_copy_vmrun_state(map_save.hva + 0x400,
4702 &svm->vmcb01.ptr->save);
4703
4704 kvm_vcpu_unmap(vcpu, &map_save, true);
4705 return 0;
4706 }
4707
svm_leave_smm(struct kvm_vcpu * vcpu,const union kvm_smram * smram)4708 static int svm_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram)
4709 {
4710 struct vcpu_svm *svm = to_svm(vcpu);
4711 struct kvm_host_map map, map_save;
4712 struct vmcb *vmcb12;
4713 int ret;
4714
4715 const struct kvm_smram_state_64 *smram64 = &smram->smram64;
4716
4717 if (!guest_cpuid_has(vcpu, X86_FEATURE_LM))
4718 return 0;
4719
4720 /* Non-zero if SMI arrived while vCPU was in guest mode. */
4721 if (!smram64->svm_guest_flag)
4722 return 0;
4723
4724 if (!guest_cpuid_has(vcpu, X86_FEATURE_SVM))
4725 return 1;
4726
4727 if (!(smram64->efer & EFER_SVME))
4728 return 1;
4729
4730 if (kvm_vcpu_map(vcpu, gpa_to_gfn(smram64->svm_guest_vmcb_gpa), &map))
4731 return 1;
4732
4733 ret = 1;
4734 if (kvm_vcpu_map(vcpu, gpa_to_gfn(svm->nested.hsave_msr), &map_save))
4735 goto unmap_map;
4736
4737 if (svm_allocate_nested(svm))
4738 goto unmap_save;
4739
4740 /*
4741 * Restore L1 host state from L1 HSAVE area as VMCB01 was
4742 * used during SMM (see svm_enter_smm())
4743 */
4744
4745 svm_copy_vmrun_state(&svm->vmcb01.ptr->save, map_save.hva + 0x400);
4746
4747 /*
4748 * Enter the nested guest now
4749 */
4750
4751 vmcb_mark_all_dirty(svm->vmcb01.ptr);
4752
4753 vmcb12 = map.hva;
4754 nested_copy_vmcb_control_to_cache(svm, &vmcb12->control);
4755 nested_copy_vmcb_save_to_cache(svm, &vmcb12->save);
4756 ret = enter_svm_guest_mode(vcpu, smram64->svm_guest_vmcb_gpa, vmcb12, false);
4757
4758 if (ret)
4759 goto unmap_save;
4760
4761 svm->nested.nested_run_pending = 1;
4762
4763 unmap_save:
4764 kvm_vcpu_unmap(vcpu, &map_save, true);
4765 unmap_map:
4766 kvm_vcpu_unmap(vcpu, &map, true);
4767 return ret;
4768 }
4769
svm_enable_smi_window(struct kvm_vcpu * vcpu)4770 static void svm_enable_smi_window(struct kvm_vcpu *vcpu)
4771 {
4772 struct vcpu_svm *svm = to_svm(vcpu);
4773
4774 if (!gif_set(svm)) {
4775 if (vgif)
4776 svm_set_intercept(svm, INTERCEPT_STGI);
4777 /* STGI will cause a vm exit */
4778 } else {
4779 /* We must be in SMM; RSM will cause a vmexit anyway. */
4780 }
4781 }
4782 #endif
4783
svm_can_emulate_instruction(struct kvm_vcpu * vcpu,int emul_type,void * insn,int insn_len)4784 static bool svm_can_emulate_instruction(struct kvm_vcpu *vcpu, int emul_type,
4785 void *insn, int insn_len)
4786 {
4787 bool smep, smap, is_user;
4788 u64 error_code;
4789
4790 /* Emulation is always possible when KVM has access to all guest state. */
4791 if (!sev_guest(vcpu->kvm))
4792 return true;
4793
4794 /* #UD and #GP should never be intercepted for SEV guests. */
4795 WARN_ON_ONCE(emul_type & (EMULTYPE_TRAP_UD |
4796 EMULTYPE_TRAP_UD_FORCED |
4797 EMULTYPE_VMWARE_GP));
4798
4799 /*
4800 * Emulation is impossible for SEV-ES guests as KVM doesn't have access
4801 * to guest register state.
4802 */
4803 if (sev_es_guest(vcpu->kvm))
4804 return false;
4805
4806 /*
4807 * Emulation is possible if the instruction is already decoded, e.g.
4808 * when completing I/O after returning from userspace.
4809 */
4810 if (emul_type & EMULTYPE_NO_DECODE)
4811 return true;
4812
4813 /*
4814 * Emulation is possible for SEV guests if and only if a prefilled
4815 * buffer containing the bytes of the intercepted instruction is
4816 * available. SEV guest memory is encrypted with a guest specific key
4817 * and cannot be decrypted by KVM, i.e. KVM would read cyphertext and
4818 * decode garbage.
4819 *
4820 * If KVM is NOT trying to simply skip an instruction, inject #UD if
4821 * KVM reached this point without an instruction buffer. In practice,
4822 * this path should never be hit by a well-behaved guest, e.g. KVM
4823 * doesn't intercept #UD or #GP for SEV guests, but this path is still
4824 * theoretically reachable, e.g. via unaccelerated fault-like AVIC
4825 * access, and needs to be handled by KVM to avoid putting the guest
4826 * into an infinite loop. Injecting #UD is somewhat arbitrary, but
4827 * its the least awful option given lack of insight into the guest.
4828 *
4829 * If KVM is trying to skip an instruction, simply resume the guest.
4830 * If a #NPF occurs while the guest is vectoring an INT3/INTO, then KVM
4831 * will attempt to re-inject the INT3/INTO and skip the instruction.
4832 * In that scenario, retrying the INT3/INTO and hoping the guest will
4833 * make forward progress is the only option that has a chance of
4834 * success (and in practice it will work the vast majority of the time).
4835 */
4836 if (unlikely(!insn)) {
4837 if (!(emul_type & EMULTYPE_SKIP))
4838 kvm_queue_exception(vcpu, UD_VECTOR);
4839 return false;
4840 }
4841
4842 /*
4843 * Emulate for SEV guests if the insn buffer is not empty. The buffer
4844 * will be empty if the DecodeAssist microcode cannot fetch bytes for
4845 * the faulting instruction because the code fetch itself faulted, e.g.
4846 * the guest attempted to fetch from emulated MMIO or a guest page
4847 * table used to translate CS:RIP resides in emulated MMIO.
4848 */
4849 if (likely(insn_len))
4850 return true;
4851
4852 /*
4853 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
4854 *
4855 * Errata:
4856 * When CPU raises #NPF on guest data access and vCPU CR4.SMAP=1, it is
4857 * possible that CPU microcode implementing DecodeAssist will fail to
4858 * read guest memory at CS:RIP and vmcb.GuestIntrBytes will incorrectly
4859 * be '0'. This happens because microcode reads CS:RIP using a _data_
4860 * loap uop with CPL=0 privileges. If the load hits a SMAP #PF, ucode
4861 * gives up and does not fill the instruction bytes buffer.
4862 *
4863 * As above, KVM reaches this point iff the VM is an SEV guest, the CPU
4864 * supports DecodeAssist, a #NPF was raised, KVM's page fault handler
4865 * triggered emulation (e.g. for MMIO), and the CPU returned 0 in the
4866 * GuestIntrBytes field of the VMCB.
4867 *
4868 * This does _not_ mean that the erratum has been encountered, as the
4869 * DecodeAssist will also fail if the load for CS:RIP hits a legitimate
4870 * #PF, e.g. if the guest attempt to execute from emulated MMIO and
4871 * encountered a reserved/not-present #PF.
4872 *
4873 * To hit the erratum, the following conditions must be true:
4874 * 1. CR4.SMAP=1 (obviously).
4875 * 2. CR4.SMEP=0 || CPL=3. If SMEP=1 and CPL<3, the erratum cannot
4876 * have been hit as the guest would have encountered a SMEP
4877 * violation #PF, not a #NPF.
4878 * 3. The #NPF is not due to a code fetch, in which case failure to
4879 * retrieve the instruction bytes is legitimate (see abvoe).
4880 *
4881 * In addition, don't apply the erratum workaround if the #NPF occurred
4882 * while translating guest page tables (see below).
4883 */
4884 error_code = to_svm(vcpu)->vmcb->control.exit_info_1;
4885 if (error_code & (PFERR_GUEST_PAGE_MASK | PFERR_FETCH_MASK))
4886 goto resume_guest;
4887
4888 smep = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMEP);
4889 smap = kvm_is_cr4_bit_set(vcpu, X86_CR4_SMAP);
4890 is_user = svm_get_cpl(vcpu) == 3;
4891 if (smap && (!smep || is_user)) {
4892 pr_err_ratelimited("SEV Guest triggered AMD Erratum 1096\n");
4893
4894 /*
4895 * If the fault occurred in userspace, arbitrarily inject #GP
4896 * to avoid killing the guest and to hopefully avoid confusing
4897 * the guest kernel too much, e.g. injecting #PF would not be
4898 * coherent with respect to the guest's page tables. Request
4899 * triple fault if the fault occurred in the kernel as there's
4900 * no fault that KVM can inject without confusing the guest.
4901 * In practice, the triple fault is moot as no sane SEV kernel
4902 * will execute from user memory while also running with SMAP=1.
4903 */
4904 if (is_user)
4905 kvm_inject_gp(vcpu, 0);
4906 else
4907 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
4908 }
4909
4910 resume_guest:
4911 /*
4912 * If the erratum was not hit, simply resume the guest and let it fault
4913 * again. While awful, e.g. the vCPU may get stuck in an infinite loop
4914 * if the fault is at CPL=0, it's the lesser of all evils. Exiting to
4915 * userspace will kill the guest, and letting the emulator read garbage
4916 * will yield random behavior and potentially corrupt the guest.
4917 *
4918 * Simply resuming the guest is technically not a violation of the SEV
4919 * architecture. AMD's APM states that all code fetches and page table
4920 * accesses for SEV guest are encrypted, regardless of the C-Bit. The
4921 * APM also states that encrypted accesses to MMIO are "ignored", but
4922 * doesn't explicitly define "ignored", i.e. doing nothing and letting
4923 * the guest spin is technically "ignoring" the access.
4924 */
4925 return false;
4926 }
4927
svm_apic_init_signal_blocked(struct kvm_vcpu * vcpu)4928 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
4929 {
4930 struct vcpu_svm *svm = to_svm(vcpu);
4931
4932 return !gif_set(svm);
4933 }
4934
svm_vcpu_deliver_sipi_vector(struct kvm_vcpu * vcpu,u8 vector)4935 static void svm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, u8 vector)
4936 {
4937 if (!sev_es_guest(vcpu->kvm))
4938 return kvm_vcpu_deliver_sipi_vector(vcpu, vector);
4939
4940 sev_vcpu_deliver_sipi_vector(vcpu, vector);
4941 }
4942
svm_vm_destroy(struct kvm * kvm)4943 static void svm_vm_destroy(struct kvm *kvm)
4944 {
4945 avic_vm_destroy(kvm);
4946 sev_vm_destroy(kvm);
4947 }
4948
svm_vm_init(struct kvm * kvm)4949 static int svm_vm_init(struct kvm *kvm)
4950 {
4951 if (!pause_filter_count || !pause_filter_thresh)
4952 kvm->arch.pause_in_guest = true;
4953
4954 if (enable_apicv) {
4955 int ret = avic_vm_init(kvm);
4956 if (ret)
4957 return ret;
4958 }
4959
4960 return 0;
4961 }
4962
4963 static struct kvm_x86_ops svm_x86_ops __initdata = {
4964 .name = KBUILD_MODNAME,
4965
4966 .check_processor_compatibility = svm_check_processor_compat,
4967
4968 .hardware_unsetup = svm_hardware_unsetup,
4969 .hardware_enable = svm_hardware_enable,
4970 .hardware_disable = svm_hardware_disable,
4971 .has_emulated_msr = svm_has_emulated_msr,
4972
4973 .vcpu_create = svm_vcpu_create,
4974 .vcpu_free = svm_vcpu_free,
4975 .vcpu_reset = svm_vcpu_reset,
4976
4977 .vm_size = sizeof(struct kvm_svm),
4978 .vm_init = svm_vm_init,
4979 .vm_destroy = svm_vm_destroy,
4980
4981 .prepare_switch_to_guest = svm_prepare_switch_to_guest,
4982 .vcpu_load = svm_vcpu_load,
4983 .vcpu_put = svm_vcpu_put,
4984 .vcpu_blocking = avic_vcpu_blocking,
4985 .vcpu_unblocking = avic_vcpu_unblocking,
4986
4987 .update_exception_bitmap = svm_update_exception_bitmap,
4988 .get_msr_feature = svm_get_msr_feature,
4989 .get_msr = svm_get_msr,
4990 .set_msr = svm_set_msr,
4991 .get_segment_base = svm_get_segment_base,
4992 .get_segment = svm_get_segment,
4993 .set_segment = svm_set_segment,
4994 .get_cpl = svm_get_cpl,
4995 .get_cs_db_l_bits = svm_get_cs_db_l_bits,
4996 .is_valid_cr0 = svm_is_valid_cr0,
4997 .set_cr0 = svm_set_cr0,
4998 .post_set_cr3 = sev_post_set_cr3,
4999 .is_valid_cr4 = svm_is_valid_cr4,
5000 .set_cr4 = svm_set_cr4,
5001 .set_efer = svm_set_efer,
5002 .get_idt = svm_get_idt,
5003 .set_idt = svm_set_idt,
5004 .get_gdt = svm_get_gdt,
5005 .set_gdt = svm_set_gdt,
5006 .set_dr6 = svm_set_dr6,
5007 .set_dr7 = svm_set_dr7,
5008 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
5009 .cache_reg = svm_cache_reg,
5010 .get_rflags = svm_get_rflags,
5011 .set_rflags = svm_set_rflags,
5012 .get_if_flag = svm_get_if_flag,
5013
5014 .flush_tlb_all = svm_flush_tlb_all,
5015 .flush_tlb_current = svm_flush_tlb_current,
5016 .flush_tlb_gva = svm_flush_tlb_gva,
5017 .flush_tlb_guest = svm_flush_tlb_asid,
5018
5019 .vcpu_pre_run = svm_vcpu_pre_run,
5020 .vcpu_run = svm_vcpu_run,
5021 .handle_exit = svm_handle_exit,
5022 .skip_emulated_instruction = svm_skip_emulated_instruction,
5023 .update_emulated_instruction = NULL,
5024 .set_interrupt_shadow = svm_set_interrupt_shadow,
5025 .get_interrupt_shadow = svm_get_interrupt_shadow,
5026 .patch_hypercall = svm_patch_hypercall,
5027 .inject_irq = svm_inject_irq,
5028 .inject_nmi = svm_inject_nmi,
5029 .is_vnmi_pending = svm_is_vnmi_pending,
5030 .set_vnmi_pending = svm_set_vnmi_pending,
5031 .inject_exception = svm_inject_exception,
5032 .cancel_injection = svm_cancel_injection,
5033 .interrupt_allowed = svm_interrupt_allowed,
5034 .nmi_allowed = svm_nmi_allowed,
5035 .get_nmi_mask = svm_get_nmi_mask,
5036 .set_nmi_mask = svm_set_nmi_mask,
5037 .enable_nmi_window = svm_enable_nmi_window,
5038 .enable_irq_window = svm_enable_irq_window,
5039 .update_cr8_intercept = svm_update_cr8_intercept,
5040
5041 .x2apic_icr_is_split = true,
5042 .set_virtual_apic_mode = avic_refresh_virtual_apic_mode,
5043 .refresh_apicv_exec_ctrl = avic_refresh_apicv_exec_ctrl,
5044 .apicv_post_state_restore = avic_apicv_post_state_restore,
5045 .required_apicv_inhibits = AVIC_REQUIRED_APICV_INHIBITS,
5046
5047 .get_exit_info = svm_get_exit_info,
5048
5049 .vcpu_after_set_cpuid = svm_vcpu_after_set_cpuid,
5050
5051 .has_wbinvd_exit = svm_has_wbinvd_exit,
5052
5053 .get_l2_tsc_offset = svm_get_l2_tsc_offset,
5054 .get_l2_tsc_multiplier = svm_get_l2_tsc_multiplier,
5055 .write_tsc_offset = svm_write_tsc_offset,
5056 .write_tsc_multiplier = svm_write_tsc_multiplier,
5057
5058 .load_mmu_pgd = svm_load_mmu_pgd,
5059
5060 .check_intercept = svm_check_intercept,
5061 .handle_exit_irqoff = svm_handle_exit_irqoff,
5062
5063 .request_immediate_exit = __kvm_request_immediate_exit,
5064
5065 .sched_in = svm_sched_in,
5066
5067 .nested_ops = &svm_nested_ops,
5068
5069 .deliver_interrupt = svm_deliver_interrupt,
5070 .pi_update_irte = avic_pi_update_irte,
5071 .setup_mce = svm_setup_mce,
5072
5073 #ifdef CONFIG_KVM_SMM
5074 .smi_allowed = svm_smi_allowed,
5075 .enter_smm = svm_enter_smm,
5076 .leave_smm = svm_leave_smm,
5077 .enable_smi_window = svm_enable_smi_window,
5078 #endif
5079
5080 .mem_enc_ioctl = sev_mem_enc_ioctl,
5081 .mem_enc_register_region = sev_mem_enc_register_region,
5082 .mem_enc_unregister_region = sev_mem_enc_unregister_region,
5083 .guest_memory_reclaimed = sev_guest_memory_reclaimed,
5084
5085 .vm_copy_enc_context_from = sev_vm_copy_enc_context_from,
5086 .vm_move_enc_context_from = sev_vm_move_enc_context_from,
5087
5088 .can_emulate_instruction = svm_can_emulate_instruction,
5089
5090 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
5091
5092 .msr_filter_changed = svm_msr_filter_changed,
5093 .complete_emulated_msr = svm_complete_emulated_msr,
5094
5095 .vcpu_deliver_sipi_vector = svm_vcpu_deliver_sipi_vector,
5096 .vcpu_get_apicv_inhibit_reasons = avic_vcpu_get_apicv_inhibit_reasons,
5097 };
5098
5099 /*
5100 * The default MMIO mask is a single bit (excluding the present bit),
5101 * which could conflict with the memory encryption bit. Check for
5102 * memory encryption support and override the default MMIO mask if
5103 * memory encryption is enabled.
5104 */
svm_adjust_mmio_mask(void)5105 static __init void svm_adjust_mmio_mask(void)
5106 {
5107 unsigned int enc_bit, mask_bit;
5108 u64 msr, mask;
5109
5110 /* If there is no memory encryption support, use existing mask */
5111 if (cpuid_eax(0x80000000) < 0x8000001f)
5112 return;
5113
5114 /* If memory encryption is not enabled, use existing mask */
5115 rdmsrl(MSR_AMD64_SYSCFG, msr);
5116 if (!(msr & MSR_AMD64_SYSCFG_MEM_ENCRYPT))
5117 return;
5118
5119 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
5120 mask_bit = boot_cpu_data.x86_phys_bits;
5121
5122 /* Increment the mask bit if it is the same as the encryption bit */
5123 if (enc_bit == mask_bit)
5124 mask_bit++;
5125
5126 /*
5127 * If the mask bit location is below 52, then some bits above the
5128 * physical addressing limit will always be reserved, so use the
5129 * rsvd_bits() function to generate the mask. This mask, along with
5130 * the present bit, will be used to generate a page fault with
5131 * PFER.RSV = 1.
5132 *
5133 * If the mask bit location is 52 (or above), then clear the mask.
5134 */
5135 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
5136
5137 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
5138 }
5139
svm_set_cpu_caps(void)5140 static __init void svm_set_cpu_caps(void)
5141 {
5142 kvm_set_cpu_caps();
5143
5144 kvm_caps.supported_perf_cap = 0;
5145 kvm_caps.supported_xss = 0;
5146
5147 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
5148 if (nested) {
5149 kvm_cpu_cap_set(X86_FEATURE_SVM);
5150 kvm_cpu_cap_set(X86_FEATURE_VMCBCLEAN);
5151
5152 if (nrips)
5153 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
5154
5155 if (npt_enabled)
5156 kvm_cpu_cap_set(X86_FEATURE_NPT);
5157
5158 if (tsc_scaling)
5159 kvm_cpu_cap_set(X86_FEATURE_TSCRATEMSR);
5160
5161 if (vls)
5162 kvm_cpu_cap_set(X86_FEATURE_V_VMSAVE_VMLOAD);
5163 if (lbrv)
5164 kvm_cpu_cap_set(X86_FEATURE_LBRV);
5165
5166 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER))
5167 kvm_cpu_cap_set(X86_FEATURE_PAUSEFILTER);
5168
5169 if (boot_cpu_has(X86_FEATURE_PFTHRESHOLD))
5170 kvm_cpu_cap_set(X86_FEATURE_PFTHRESHOLD);
5171
5172 if (vgif)
5173 kvm_cpu_cap_set(X86_FEATURE_VGIF);
5174
5175 if (vnmi)
5176 kvm_cpu_cap_set(X86_FEATURE_VNMI);
5177
5178 /* Nested VM can receive #VMEXIT instead of triggering #GP */
5179 kvm_cpu_cap_set(X86_FEATURE_SVME_ADDR_CHK);
5180 }
5181
5182 /* CPUID 0x80000008 */
5183 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
5184 boot_cpu_has(X86_FEATURE_AMD_SSBD))
5185 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
5186
5187 if (enable_pmu) {
5188 /*
5189 * Enumerate support for PERFCTR_CORE if and only if KVM has
5190 * access to enough counters to virtualize "core" support,
5191 * otherwise limit vPMU support to the legacy number of counters.
5192 */
5193 if (kvm_pmu_cap.num_counters_gp < AMD64_NUM_COUNTERS_CORE)
5194 kvm_pmu_cap.num_counters_gp = min(AMD64_NUM_COUNTERS,
5195 kvm_pmu_cap.num_counters_gp);
5196 else
5197 kvm_cpu_cap_check_and_set(X86_FEATURE_PERFCTR_CORE);
5198
5199 if (kvm_pmu_cap.version != 2 ||
5200 !kvm_cpu_cap_has(X86_FEATURE_PERFCTR_CORE))
5201 kvm_cpu_cap_clear(X86_FEATURE_PERFMON_V2);
5202 }
5203
5204 /* CPUID 0x8000001F (SME/SEV features) */
5205 sev_set_cpu_caps();
5206
5207 /* Don't advertise Bus Lock Detect to guest if SVM support is absent */
5208 kvm_cpu_cap_clear(X86_FEATURE_BUS_LOCK_DETECT);
5209 }
5210
svm_hardware_setup(void)5211 static __init int svm_hardware_setup(void)
5212 {
5213 int cpu;
5214 struct page *iopm_pages;
5215 void *iopm_va;
5216 int r;
5217 unsigned int order = get_order(IOPM_SIZE);
5218
5219 /*
5220 * NX is required for shadow paging and for NPT if the NX huge pages
5221 * mitigation is enabled.
5222 */
5223 if (!boot_cpu_has(X86_FEATURE_NX)) {
5224 pr_err_ratelimited("NX (Execute Disable) not supported\n");
5225 return -EOPNOTSUPP;
5226 }
5227 kvm_enable_efer_bits(EFER_NX);
5228
5229 iopm_pages = alloc_pages(GFP_KERNEL, order);
5230
5231 if (!iopm_pages)
5232 return -ENOMEM;
5233
5234 iopm_va = page_address(iopm_pages);
5235 memset(iopm_va, 0xff, PAGE_SIZE * (1 << order));
5236 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
5237
5238 init_msrpm_offsets();
5239
5240 kvm_caps.supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS |
5241 XFEATURE_MASK_BNDCSR);
5242
5243 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
5244 kvm_enable_efer_bits(EFER_FFXSR);
5245
5246 if (tsc_scaling) {
5247 if (!boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
5248 tsc_scaling = false;
5249 } else {
5250 pr_info("TSC scaling supported\n");
5251 kvm_caps.has_tsc_control = true;
5252 }
5253 }
5254 kvm_caps.max_tsc_scaling_ratio = SVM_TSC_RATIO_MAX;
5255 kvm_caps.tsc_scaling_ratio_frac_bits = 32;
5256
5257 tsc_aux_uret_slot = kvm_add_user_return_msr(MSR_TSC_AUX);
5258
5259 if (boot_cpu_has(X86_FEATURE_AUTOIBRS))
5260 kvm_enable_efer_bits(EFER_AUTOIBRS);
5261
5262 /* Check for pause filtering support */
5263 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
5264 pause_filter_count = 0;
5265 pause_filter_thresh = 0;
5266 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
5267 pause_filter_thresh = 0;
5268 }
5269
5270 if (nested) {
5271 pr_info("Nested Virtualization enabled\n");
5272 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
5273 }
5274
5275 /*
5276 * KVM's MMU doesn't support using 2-level paging for itself, and thus
5277 * NPT isn't supported if the host is using 2-level paging since host
5278 * CR4 is unchanged on VMRUN.
5279 */
5280 if (!IS_ENABLED(CONFIG_X86_64) && !IS_ENABLED(CONFIG_X86_PAE))
5281 npt_enabled = false;
5282
5283 if (!boot_cpu_has(X86_FEATURE_NPT))
5284 npt_enabled = false;
5285
5286 /* Force VM NPT level equal to the host's paging level */
5287 kvm_configure_mmu(npt_enabled, get_npt_level(),
5288 get_npt_level(), PG_LEVEL_1G);
5289 pr_info("Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
5290
5291 /* Setup shadow_me_value and shadow_me_mask */
5292 kvm_mmu_set_me_spte_mask(sme_me_mask, sme_me_mask);
5293
5294 svm_adjust_mmio_mask();
5295
5296 nrips = nrips && boot_cpu_has(X86_FEATURE_NRIPS);
5297
5298 if (lbrv) {
5299 if (!boot_cpu_has(X86_FEATURE_LBRV))
5300 lbrv = false;
5301 else
5302 pr_info("LBR virtualization supported\n");
5303 }
5304 /*
5305 * Note, SEV setup consumes npt_enabled and enable_mmio_caching (which
5306 * may be modified by svm_adjust_mmio_mask()), as well as nrips.
5307 */
5308 sev_hardware_setup();
5309
5310 svm_hv_hardware_setup();
5311
5312 for_each_possible_cpu(cpu) {
5313 r = svm_cpu_init(cpu);
5314 if (r)
5315 goto err;
5316 }
5317
5318 enable_apicv = avic = avic && avic_hardware_setup();
5319
5320 if (!enable_apicv) {
5321 svm_x86_ops.vcpu_blocking = NULL;
5322 svm_x86_ops.vcpu_unblocking = NULL;
5323 svm_x86_ops.vcpu_get_apicv_inhibit_reasons = NULL;
5324 } else if (!x2avic_enabled) {
5325 svm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization = true;
5326 }
5327
5328 if (vls) {
5329 if (!npt_enabled ||
5330 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
5331 !IS_ENABLED(CONFIG_X86_64)) {
5332 vls = false;
5333 } else {
5334 pr_info("Virtual VMLOAD VMSAVE supported\n");
5335 }
5336 }
5337
5338 if (boot_cpu_has(X86_FEATURE_SVME_ADDR_CHK))
5339 svm_gp_erratum_intercept = false;
5340
5341 if (vgif) {
5342 if (!boot_cpu_has(X86_FEATURE_VGIF))
5343 vgif = false;
5344 else
5345 pr_info("Virtual GIF supported\n");
5346 }
5347
5348 vnmi = vgif && vnmi && boot_cpu_has(X86_FEATURE_VNMI);
5349 if (vnmi)
5350 pr_info("Virtual NMI enabled\n");
5351
5352 if (!vnmi) {
5353 svm_x86_ops.is_vnmi_pending = NULL;
5354 svm_x86_ops.set_vnmi_pending = NULL;
5355 }
5356
5357 if (!enable_pmu)
5358 pr_info("PMU virtualization is disabled\n");
5359
5360 svm_set_cpu_caps();
5361
5362 /*
5363 * It seems that on AMD processors PTE's accessed bit is
5364 * being set by the CPU hardware before the NPF vmexit.
5365 * This is not expected behaviour and our tests fail because
5366 * of it.
5367 * A workaround here is to disable support for
5368 * GUEST_MAXPHYADDR < HOST_MAXPHYADDR if NPT is enabled.
5369 * In this case userspace can know if there is support using
5370 * KVM_CAP_SMALLER_MAXPHYADDR extension and decide how to handle
5371 * it
5372 * If future AMD CPU models change the behaviour described above,
5373 * this variable can be changed accordingly
5374 */
5375 allow_smaller_maxphyaddr = !npt_enabled;
5376
5377 return 0;
5378
5379 err:
5380 svm_hardware_unsetup();
5381 return r;
5382 }
5383
5384
5385 static struct kvm_x86_init_ops svm_init_ops __initdata = {
5386 .hardware_setup = svm_hardware_setup,
5387
5388 .runtime_ops = &svm_x86_ops,
5389 .pmu_ops = &amd_pmu_ops,
5390 };
5391
__svm_exit(void)5392 static void __svm_exit(void)
5393 {
5394 kvm_x86_vendor_exit();
5395
5396 cpu_emergency_unregister_virt_callback(svm_emergency_disable);
5397 }
5398
svm_init(void)5399 static int __init svm_init(void)
5400 {
5401 int r;
5402
5403 __unused_size_checks();
5404
5405 if (!kvm_is_svm_supported())
5406 return -EOPNOTSUPP;
5407
5408 r = kvm_x86_vendor_init(&svm_init_ops);
5409 if (r)
5410 return r;
5411
5412 cpu_emergency_register_virt_callback(svm_emergency_disable);
5413
5414 /*
5415 * Common KVM initialization _must_ come last, after this, /dev/kvm is
5416 * exposed to userspace!
5417 */
5418 r = kvm_init(sizeof(struct vcpu_svm), __alignof__(struct vcpu_svm),
5419 THIS_MODULE);
5420 if (r)
5421 goto err_kvm_init;
5422
5423 return 0;
5424
5425 err_kvm_init:
5426 __svm_exit();
5427 return r;
5428 }
5429
svm_exit(void)5430 static void __exit svm_exit(void)
5431 {
5432 kvm_exit();
5433 __svm_exit();
5434 }
5435
5436 module_init(svm_init)
5437 module_exit(svm_exit)
5438