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