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