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