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