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