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