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