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