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