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