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