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