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