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