GNU Linux-libre 4.14.266-gnu1
[releases.git] / arch / x86 / kvm / svm.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * AMD SVM support
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  *
9  * Authors:
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *   Avi Kivity   <avi@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17
18 #define pr_fmt(fmt) "SVM: " fmt
19
20 #include <linux/kvm_host.h>
21
22 #include "irq.h"
23 #include "mmu.h"
24 #include "kvm_cache_regs.h"
25 #include "x86.h"
26 #include "cpuid.h"
27 #include "pmu.h"
28
29 #include <linux/module.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/kernel.h>
32 #include <linux/vmalloc.h>
33 #include <linux/highmem.h>
34 #include <linux/sched.h>
35 #include <linux/trace_events.h>
36 #include <linux/slab.h>
37 #include <linux/amd-iommu.h>
38 #include <linux/hashtable.h>
39 #include <linux/frame.h>
40
41 #include <asm/apic.h>
42 #include <asm/perf_event.h>
43 #include <asm/tlbflush.h>
44 #include <asm/desc.h>
45 #include <asm/debugreg.h>
46 #include <asm/kvm_para.h>
47 #include <asm/irq_remapping.h>
48 #include <asm/microcode.h>
49 #include <asm/spec-ctrl.h>
50
51 #include <asm/virtext.h>
52 #include "trace.h"
53
54 #define __ex(x) __kvm_handle_fault_on_reboot(x)
55
56 MODULE_AUTHOR("Qumranet");
57 MODULE_LICENSE("GPL");
58
59 static const struct x86_cpu_id svm_cpu_id[] = {
60         X86_FEATURE_MATCH(X86_FEATURE_SVM),
61         {}
62 };
63 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
64
65 #define IOPM_ALLOC_ORDER 2
66 #define MSRPM_ALLOC_ORDER 1
67
68 #define SEG_TYPE_LDT 2
69 #define SEG_TYPE_BUSY_TSS16 3
70
71 #define SVM_FEATURE_NPT            (1 <<  0)
72 #define SVM_FEATURE_LBRV           (1 <<  1)
73 #define SVM_FEATURE_SVML           (1 <<  2)
74 #define SVM_FEATURE_NRIP           (1 <<  3)
75 #define SVM_FEATURE_TSC_RATE       (1 <<  4)
76 #define SVM_FEATURE_VMCB_CLEAN     (1 <<  5)
77 #define SVM_FEATURE_FLUSH_ASID     (1 <<  6)
78 #define SVM_FEATURE_DECODE_ASSIST  (1 <<  7)
79 #define SVM_FEATURE_PAUSE_FILTER   (1 << 10)
80
81 #define SVM_AVIC_DOORBELL       0xc001011b
82
83 #define NESTED_EXIT_HOST        0       /* Exit handled on host level */
84 #define NESTED_EXIT_DONE        1       /* Exit caused nested vmexit  */
85 #define NESTED_EXIT_CONTINUE    2       /* Further checks needed      */
86
87 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
88
89 #define TSC_RATIO_RSVD          0xffffff0000000000ULL
90 #define TSC_RATIO_MIN           0x0000000000000001ULL
91 #define TSC_RATIO_MAX           0x000000ffffffffffULL
92
93 #define AVIC_HPA_MASK   ~((0xFFFULL << 52) | 0xFFF)
94
95 /*
96  * 0xff is broadcast, so the max index allowed for physical APIC ID
97  * table is 0xfe.  APIC IDs above 0xff are reserved.
98  */
99 #define AVIC_MAX_PHYSICAL_ID_COUNT      255
100
101 #define AVIC_UNACCEL_ACCESS_WRITE_MASK          1
102 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK         0xFF0
103 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK         0xFFFFFFFF
104
105 /* AVIC GATAG is encoded using VM and VCPU IDs */
106 #define AVIC_VCPU_ID_BITS               8
107 #define AVIC_VCPU_ID_MASK               ((1 << AVIC_VCPU_ID_BITS) - 1)
108
109 #define AVIC_VM_ID_BITS                 24
110 #define AVIC_VM_ID_NR                   (1 << AVIC_VM_ID_BITS)
111 #define AVIC_VM_ID_MASK                 ((1 << AVIC_VM_ID_BITS) - 1)
112
113 #define AVIC_GATAG(x, y)                (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
114                                                 (y & AVIC_VCPU_ID_MASK))
115 #define AVIC_GATAG_TO_VMID(x)           ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
116 #define AVIC_GATAG_TO_VCPUID(x)         (x & AVIC_VCPU_ID_MASK)
117
118 static bool erratum_383_found __read_mostly;
119
120 static const u32 host_save_user_msrs[] = {
121 #ifdef CONFIG_X86_64
122         MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
123         MSR_FS_BASE,
124 #endif
125         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
126         MSR_TSC_AUX,
127 };
128
129 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
130
131 struct kvm_vcpu;
132
133 struct nested_state {
134         struct vmcb *hsave;
135         u64 hsave_msr;
136         u64 vm_cr_msr;
137         u64 vmcb;
138
139         /* These are the merged vectors */
140         u32 *msrpm;
141
142         /* gpa pointers to the real vectors */
143         u64 vmcb_msrpm;
144         u64 vmcb_iopm;
145
146         /* A VMEXIT is required but not yet emulated */
147         bool exit_required;
148
149         /* cache for intercepts of the guest */
150         u32 intercept_cr;
151         u32 intercept_dr;
152         u32 intercept_exceptions;
153         u64 intercept;
154
155         /* Nested Paging related state */
156         u64 nested_cr3;
157 };
158
159 #define MSRPM_OFFSETS   16
160 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
161
162 /*
163  * Set osvw_len to higher value when updated Revision Guides
164  * are published and we know what the new status bits are
165  */
166 static uint64_t osvw_len = 4, osvw_status;
167
168 struct vcpu_svm {
169         struct kvm_vcpu vcpu;
170         struct vmcb *vmcb;
171         unsigned long vmcb_pa;
172         struct svm_cpu_data *svm_data;
173         uint64_t asid_generation;
174         uint64_t sysenter_esp;
175         uint64_t sysenter_eip;
176         uint64_t tsc_aux;
177
178         u64 msr_decfg;
179
180         u64 next_rip;
181
182         u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
183         struct {
184                 u16 fs;
185                 u16 gs;
186                 u16 ldt;
187                 u64 gs_base;
188         } host;
189
190         u64 spec_ctrl;
191         /*
192          * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
193          * translated into the appropriate L2_CFG bits on the host to
194          * perform speculative control.
195          */
196         u64 virt_spec_ctrl;
197
198         u32 *msrpm;
199
200         ulong nmi_iret_rip;
201
202         struct nested_state nested;
203
204         bool nmi_singlestep;
205         u64 nmi_singlestep_guest_rflags;
206
207         unsigned int3_injected;
208         unsigned long int3_rip;
209
210         /* cached guest cpuid flags for faster access */
211         bool nrips_enabled      : 1;
212
213         u32 ldr_reg;
214         struct page *avic_backing_page;
215         u64 *avic_physical_id_cache;
216         bool avic_is_running;
217
218         /*
219          * Per-vcpu list of struct amd_svm_iommu_ir:
220          * This is used mainly to store interrupt remapping information used
221          * when update the vcpu affinity. This avoids the need to scan for
222          * IRTE and try to match ga_tag in the IOMMU driver.
223          */
224         struct list_head ir_list;
225         spinlock_t ir_list_lock;
226 };
227
228 /*
229  * This is a wrapper of struct amd_iommu_ir_data.
230  */
231 struct amd_svm_iommu_ir {
232         struct list_head node;  /* Used by SVM for per-vcpu ir_list */
233         void *data;             /* Storing pointer to struct amd_ir_data */
234 };
235
236 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK    (0xFF)
237 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK                (1 << 31)
238
239 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK    (0xFFULL)
240 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK        (0xFFFFFFFFFFULL << 12)
241 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK          (1ULL << 62)
242 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK               (1ULL << 63)
243
244 static DEFINE_PER_CPU(u64, current_tsc_ratio);
245 #define TSC_RATIO_DEFAULT       0x0100000000ULL
246
247 #define MSR_INVALID                     0xffffffffU
248
249 static const struct svm_direct_access_msrs {
250         u32 index;   /* Index of the MSR */
251         bool always; /* True if intercept is always on */
252 } direct_access_msrs[] = {
253         { .index = MSR_STAR,                            .always = true  },
254         { .index = MSR_IA32_SYSENTER_CS,                .always = true  },
255 #ifdef CONFIG_X86_64
256         { .index = MSR_GS_BASE,                         .always = true  },
257         { .index = MSR_FS_BASE,                         .always = true  },
258         { .index = MSR_KERNEL_GS_BASE,                  .always = true  },
259         { .index = MSR_LSTAR,                           .always = true  },
260         { .index = MSR_CSTAR,                           .always = true  },
261         { .index = MSR_SYSCALL_MASK,                    .always = true  },
262 #endif
263         { .index = MSR_IA32_SPEC_CTRL,                  .always = false },
264         { .index = MSR_IA32_PRED_CMD,                   .always = false },
265         { .index = MSR_IA32_LASTBRANCHFROMIP,           .always = false },
266         { .index = MSR_IA32_LASTBRANCHTOIP,             .always = false },
267         { .index = MSR_IA32_LASTINTFROMIP,              .always = false },
268         { .index = MSR_IA32_LASTINTTOIP,                .always = false },
269         { .index = MSR_INVALID,                         .always = false },
270 };
271
272 /* enable NPT for AMD64 and X86 with PAE */
273 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
274 static bool npt_enabled = true;
275 #else
276 static bool npt_enabled;
277 #endif
278
279 /* allow nested paging (virtualized MMU) for all guests */
280 static int npt = true;
281 module_param(npt, int, S_IRUGO);
282
283 /* allow nested virtualization in KVM/SVM */
284 static int nested = true;
285 module_param(nested, int, S_IRUGO);
286
287 /* enable / disable AVIC */
288 static int avic;
289 #ifdef CONFIG_X86_LOCAL_APIC
290 module_param(avic, int, S_IRUGO);
291 #endif
292
293 /* enable/disable Virtual VMLOAD VMSAVE */
294 static int vls = true;
295 module_param(vls, int, 0444);
296
297 /* enable/disable Virtual GIF */
298 static int vgif = true;
299 module_param(vgif, int, 0444);
300
301 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
302 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
303 static void svm_complete_interrupts(struct vcpu_svm *svm);
304
305 static int nested_svm_exit_handled(struct vcpu_svm *svm);
306 static int nested_svm_intercept(struct vcpu_svm *svm);
307 static int nested_svm_vmexit(struct vcpu_svm *svm);
308 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
309                                       bool has_error_code, u32 error_code);
310
311 enum {
312         VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
313                             pause filter count */
314         VMCB_PERM_MAP,   /* IOPM Base and MSRPM Base */
315         VMCB_ASID,       /* ASID */
316         VMCB_INTR,       /* int_ctl, int_vector */
317         VMCB_NPT,        /* npt_en, nCR3, gPAT */
318         VMCB_CR,         /* CR0, CR3, CR4, EFER */
319         VMCB_DR,         /* DR6, DR7 */
320         VMCB_DT,         /* GDT, IDT */
321         VMCB_SEG,        /* CS, DS, SS, ES, CPL */
322         VMCB_CR2,        /* CR2 only */
323         VMCB_LBR,        /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
324         VMCB_AVIC,       /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
325                           * AVIC PHYSICAL_TABLE pointer,
326                           * AVIC LOGICAL_TABLE pointer
327                           */
328         VMCB_DIRTY_MAX,
329 };
330
331 /* TPR and CR2 are always written before VMRUN */
332 #define VMCB_ALWAYS_DIRTY_MASK  ((1U << VMCB_INTR) | (1U << VMCB_CR2))
333
334 #define VMCB_AVIC_APIC_BAR_MASK         0xFFFFFFFFFF000ULL
335
336 static inline void mark_all_dirty(struct vmcb *vmcb)
337 {
338         vmcb->control.clean = 0;
339 }
340
341 static inline void mark_all_clean(struct vmcb *vmcb)
342 {
343         vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
344                                & ~VMCB_ALWAYS_DIRTY_MASK;
345 }
346
347 static inline void mark_dirty(struct vmcb *vmcb, int bit)
348 {
349         vmcb->control.clean &= ~(1 << bit);
350 }
351
352 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
353 {
354         return container_of(vcpu, struct vcpu_svm, vcpu);
355 }
356
357 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
358 {
359         svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
360         mark_dirty(svm->vmcb, VMCB_AVIC);
361 }
362
363 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
364 {
365         struct vcpu_svm *svm = to_svm(vcpu);
366         u64 *entry = svm->avic_physical_id_cache;
367
368         if (!entry)
369                 return false;
370
371         return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
372 }
373
374 static void recalc_intercepts(struct vcpu_svm *svm)
375 {
376         struct vmcb_control_area *c, *h;
377         struct nested_state *g;
378
379         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
380
381         if (!is_guest_mode(&svm->vcpu))
382                 return;
383
384         c = &svm->vmcb->control;
385         h = &svm->nested.hsave->control;
386         g = &svm->nested;
387
388         c->intercept_cr = h->intercept_cr | g->intercept_cr;
389         c->intercept_dr = h->intercept_dr | g->intercept_dr;
390         c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
391         c->intercept = h->intercept | g->intercept;
392
393         c->intercept |= (1ULL << INTERCEPT_VMLOAD);
394         c->intercept |= (1ULL << INTERCEPT_VMSAVE);
395 }
396
397 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
398 {
399         if (is_guest_mode(&svm->vcpu))
400                 return svm->nested.hsave;
401         else
402                 return svm->vmcb;
403 }
404
405 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
406 {
407         struct vmcb *vmcb = get_host_vmcb(svm);
408
409         vmcb->control.intercept_cr |= (1U << bit);
410
411         recalc_intercepts(svm);
412 }
413
414 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
415 {
416         struct vmcb *vmcb = get_host_vmcb(svm);
417
418         vmcb->control.intercept_cr &= ~(1U << bit);
419
420         recalc_intercepts(svm);
421 }
422
423 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
424 {
425         struct vmcb *vmcb = get_host_vmcb(svm);
426
427         return vmcb->control.intercept_cr & (1U << bit);
428 }
429
430 static inline void set_dr_intercepts(struct vcpu_svm *svm)
431 {
432         struct vmcb *vmcb = get_host_vmcb(svm);
433
434         vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
435                 | (1 << INTERCEPT_DR1_READ)
436                 | (1 << INTERCEPT_DR2_READ)
437                 | (1 << INTERCEPT_DR3_READ)
438                 | (1 << INTERCEPT_DR4_READ)
439                 | (1 << INTERCEPT_DR5_READ)
440                 | (1 << INTERCEPT_DR6_READ)
441                 | (1 << INTERCEPT_DR7_READ)
442                 | (1 << INTERCEPT_DR0_WRITE)
443                 | (1 << INTERCEPT_DR1_WRITE)
444                 | (1 << INTERCEPT_DR2_WRITE)
445                 | (1 << INTERCEPT_DR3_WRITE)
446                 | (1 << INTERCEPT_DR4_WRITE)
447                 | (1 << INTERCEPT_DR5_WRITE)
448                 | (1 << INTERCEPT_DR6_WRITE)
449                 | (1 << INTERCEPT_DR7_WRITE);
450
451         recalc_intercepts(svm);
452 }
453
454 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
455 {
456         struct vmcb *vmcb = get_host_vmcb(svm);
457
458         vmcb->control.intercept_dr = 0;
459
460         recalc_intercepts(svm);
461 }
462
463 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
464 {
465         struct vmcb *vmcb = get_host_vmcb(svm);
466
467         vmcb->control.intercept_exceptions |= (1U << bit);
468
469         recalc_intercepts(svm);
470 }
471
472 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
473 {
474         struct vmcb *vmcb = get_host_vmcb(svm);
475
476         vmcb->control.intercept_exceptions &= ~(1U << bit);
477
478         recalc_intercepts(svm);
479 }
480
481 static inline void set_intercept(struct vcpu_svm *svm, int bit)
482 {
483         struct vmcb *vmcb = get_host_vmcb(svm);
484
485         vmcb->control.intercept |= (1ULL << bit);
486
487         recalc_intercepts(svm);
488 }
489
490 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
491 {
492         struct vmcb *vmcb = get_host_vmcb(svm);
493
494         vmcb->control.intercept &= ~(1ULL << bit);
495
496         recalc_intercepts(svm);
497 }
498
499 static inline bool vgif_enabled(struct vcpu_svm *svm)
500 {
501         return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
502 }
503
504 static inline void enable_gif(struct vcpu_svm *svm)
505 {
506         if (vgif_enabled(svm))
507                 svm->vmcb->control.int_ctl |= V_GIF_MASK;
508         else
509                 svm->vcpu.arch.hflags |= HF_GIF_MASK;
510 }
511
512 static inline void disable_gif(struct vcpu_svm *svm)
513 {
514         if (vgif_enabled(svm))
515                 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
516         else
517                 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
518 }
519
520 static inline bool gif_set(struct vcpu_svm *svm)
521 {
522         if (vgif_enabled(svm))
523                 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
524         else
525                 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
526 }
527
528 static unsigned long iopm_base;
529
530 struct kvm_ldttss_desc {
531         u16 limit0;
532         u16 base0;
533         unsigned base1:8, type:5, dpl:2, p:1;
534         unsigned limit1:4, zero0:3, g:1, base2:8;
535         u32 base3;
536         u32 zero1;
537 } __attribute__((packed));
538
539 struct svm_cpu_data {
540         int cpu;
541
542         u64 asid_generation;
543         u32 max_asid;
544         u32 next_asid;
545         struct kvm_ldttss_desc *tss_desc;
546
547         struct page *save_area;
548         struct vmcb *current_vmcb;
549 };
550
551 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
552
553 struct svm_init_data {
554         int cpu;
555         int r;
556 };
557
558 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
559
560 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
561 #define MSRS_RANGE_SIZE 2048
562 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
563
564 static u32 svm_msrpm_offset(u32 msr)
565 {
566         u32 offset;
567         int i;
568
569         for (i = 0; i < NUM_MSR_MAPS; i++) {
570                 if (msr < msrpm_ranges[i] ||
571                     msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
572                         continue;
573
574                 offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
575                 offset += (i * MSRS_RANGE_SIZE);       /* add range offset */
576
577                 /* Now we have the u8 offset - but need the u32 offset */
578                 return offset / 4;
579         }
580
581         /* MSR not in any range */
582         return MSR_INVALID;
583 }
584
585 #define MAX_INST_SIZE 15
586
587 static inline void clgi(void)
588 {
589         asm volatile (__ex(SVM_CLGI));
590 }
591
592 static inline void stgi(void)
593 {
594         asm volatile (__ex(SVM_STGI));
595 }
596
597 static inline void invlpga(unsigned long addr, u32 asid)
598 {
599         asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
600 }
601
602 static int get_npt_level(struct kvm_vcpu *vcpu)
603 {
604 #ifdef CONFIG_X86_64
605         return PT64_ROOT_4LEVEL;
606 #else
607         return PT32E_ROOT_LEVEL;
608 #endif
609 }
610
611 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
612 {
613         vcpu->arch.efer = efer;
614
615         if (!npt_enabled) {
616                 /* Shadow paging assumes NX to be available.  */
617                 efer |= EFER_NX;
618
619                 if (!(efer & EFER_LMA))
620                         efer &= ~EFER_LME;
621         }
622
623         to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
624         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
625 }
626
627 static int is_external_interrupt(u32 info)
628 {
629         info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
630         return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
631 }
632
633 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
634 {
635         struct vcpu_svm *svm = to_svm(vcpu);
636         u32 ret = 0;
637
638         if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
639                 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
640         return ret;
641 }
642
643 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
644 {
645         struct vcpu_svm *svm = to_svm(vcpu);
646
647         if (mask == 0)
648                 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
649         else
650                 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
651
652 }
653
654 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
655 {
656         struct vcpu_svm *svm = to_svm(vcpu);
657
658         if (svm->vmcb->control.next_rip != 0) {
659                 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
660                 svm->next_rip = svm->vmcb->control.next_rip;
661         }
662
663         if (!svm->next_rip) {
664                 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
665                                 EMULATE_DONE)
666                         printk(KERN_DEBUG "%s: NOP\n", __func__);
667                 return;
668         }
669         if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
670                 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
671                        __func__, kvm_rip_read(vcpu), svm->next_rip);
672
673         kvm_rip_write(vcpu, svm->next_rip);
674         svm_set_interrupt_shadow(vcpu, 0);
675 }
676
677 static void svm_queue_exception(struct kvm_vcpu *vcpu)
678 {
679         struct vcpu_svm *svm = to_svm(vcpu);
680         unsigned nr = vcpu->arch.exception.nr;
681         bool has_error_code = vcpu->arch.exception.has_error_code;
682         bool reinject = vcpu->arch.exception.injected;
683         u32 error_code = vcpu->arch.exception.error_code;
684
685         /*
686          * If we are within a nested VM we'd better #VMEXIT and let the guest
687          * handle the exception
688          */
689         if (!reinject &&
690             nested_svm_check_exception(svm, nr, has_error_code, error_code))
691                 return;
692
693         if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
694                 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
695
696                 /*
697                  * For guest debugging where we have to reinject #BP if some
698                  * INT3 is guest-owned:
699                  * Emulate nRIP by moving RIP forward. Will fail if injection
700                  * raises a fault that is not intercepted. Still better than
701                  * failing in all cases.
702                  */
703                 skip_emulated_instruction(&svm->vcpu);
704                 rip = kvm_rip_read(&svm->vcpu);
705                 svm->int3_rip = rip + svm->vmcb->save.cs.base;
706                 svm->int3_injected = rip - old_rip;
707         }
708
709         svm->vmcb->control.event_inj = nr
710                 | SVM_EVTINJ_VALID
711                 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
712                 | SVM_EVTINJ_TYPE_EXEPT;
713         svm->vmcb->control.event_inj_err = error_code;
714 }
715
716 static void svm_init_erratum_383(void)
717 {
718         u32 low, high;
719         int err;
720         u64 val;
721
722         if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
723                 return;
724
725         /* Use _safe variants to not break nested virtualization */
726         val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
727         if (err)
728                 return;
729
730         val |= (1ULL << 47);
731
732         low  = lower_32_bits(val);
733         high = upper_32_bits(val);
734
735         native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
736
737         erratum_383_found = true;
738 }
739
740 static void svm_init_osvw(struct kvm_vcpu *vcpu)
741 {
742         /*
743          * Guests should see errata 400 and 415 as fixed (assuming that
744          * HLT and IO instructions are intercepted).
745          */
746         vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
747         vcpu->arch.osvw.status = osvw_status & ~(6ULL);
748
749         /*
750          * By increasing VCPU's osvw.length to 3 we are telling the guest that
751          * all osvw.status bits inside that length, including bit 0 (which is
752          * reserved for erratum 298), are valid. However, if host processor's
753          * osvw_len is 0 then osvw_status[0] carries no information. We need to
754          * be conservative here and therefore we tell the guest that erratum 298
755          * is present (because we really don't know).
756          */
757         if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
758                 vcpu->arch.osvw.status |= 1;
759 }
760
761 static int has_svm(void)
762 {
763         const char *msg;
764
765         if (!cpu_has_svm(&msg)) {
766                 printk(KERN_INFO "has_svm: %s\n", msg);
767                 return 0;
768         }
769
770         return 1;
771 }
772
773 static void svm_hardware_disable(void)
774 {
775         /* Make sure we clean up behind us */
776         if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
777                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
778
779         cpu_svm_disable();
780
781         amd_pmu_disable_virt();
782 }
783
784 static int svm_hardware_enable(void)
785 {
786
787         struct svm_cpu_data *sd;
788         uint64_t efer;
789         struct desc_struct *gdt;
790         int me = raw_smp_processor_id();
791
792         rdmsrl(MSR_EFER, efer);
793         if (efer & EFER_SVME)
794                 return -EBUSY;
795
796         if (!has_svm()) {
797                 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
798                 return -EINVAL;
799         }
800         sd = per_cpu(svm_data, me);
801         if (!sd) {
802                 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
803                 return -EINVAL;
804         }
805
806         sd->asid_generation = 1;
807         sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
808         sd->next_asid = sd->max_asid + 1;
809
810         gdt = get_current_gdt_rw();
811         sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
812
813         wrmsrl(MSR_EFER, efer | EFER_SVME);
814
815         wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
816
817         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
818                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
819                 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
820         }
821
822
823         /*
824          * Get OSVW bits.
825          *
826          * Note that it is possible to have a system with mixed processor
827          * revisions and therefore different OSVW bits. If bits are not the same
828          * on different processors then choose the worst case (i.e. if erratum
829          * is present on one processor and not on another then assume that the
830          * erratum is present everywhere).
831          */
832         if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
833                 uint64_t len, status = 0;
834                 int err;
835
836                 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
837                 if (!err)
838                         status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
839                                                       &err);
840
841                 if (err)
842                         osvw_status = osvw_len = 0;
843                 else {
844                         if (len < osvw_len)
845                                 osvw_len = len;
846                         osvw_status |= status;
847                         osvw_status &= (1ULL << osvw_len) - 1;
848                 }
849         } else
850                 osvw_status = osvw_len = 0;
851
852         svm_init_erratum_383();
853
854         amd_pmu_enable_virt();
855
856         return 0;
857 }
858
859 static void svm_cpu_uninit(int cpu)
860 {
861         struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
862
863         if (!sd)
864                 return;
865
866         per_cpu(svm_data, raw_smp_processor_id()) = NULL;
867         __free_page(sd->save_area);
868         kfree(sd);
869 }
870
871 static int svm_cpu_init(int cpu)
872 {
873         struct svm_cpu_data *sd;
874         int r;
875
876         sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
877         if (!sd)
878                 return -ENOMEM;
879         sd->cpu = cpu;
880         sd->save_area = alloc_page(GFP_KERNEL);
881         r = -ENOMEM;
882         if (!sd->save_area)
883                 goto err_1;
884
885         per_cpu(svm_data, cpu) = sd;
886
887         return 0;
888
889 err_1:
890         kfree(sd);
891         return r;
892
893 }
894
895 static bool valid_msr_intercept(u32 index)
896 {
897         int i;
898
899         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
900                 if (direct_access_msrs[i].index == index)
901                         return true;
902
903         return false;
904 }
905
906 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
907 {
908         u8 bit_write;
909         unsigned long tmp;
910         u32 offset;
911         u32 *msrpm;
912
913         msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
914                                       to_svm(vcpu)->msrpm;
915
916         offset    = svm_msrpm_offset(msr);
917         bit_write = 2 * (msr & 0x0f) + 1;
918         tmp       = msrpm[offset];
919
920         BUG_ON(offset == MSR_INVALID);
921
922         return !!test_bit(bit_write,  &tmp);
923 }
924
925 static void set_msr_interception(u32 *msrpm, unsigned msr,
926                                  int read, int write)
927 {
928         u8 bit_read, bit_write;
929         unsigned long tmp;
930         u32 offset;
931
932         /*
933          * If this warning triggers extend the direct_access_msrs list at the
934          * beginning of the file
935          */
936         WARN_ON(!valid_msr_intercept(msr));
937
938         offset    = svm_msrpm_offset(msr);
939         bit_read  = 2 * (msr & 0x0f);
940         bit_write = 2 * (msr & 0x0f) + 1;
941         tmp       = msrpm[offset];
942
943         BUG_ON(offset == MSR_INVALID);
944
945         read  ? clear_bit(bit_read,  &tmp) : set_bit(bit_read,  &tmp);
946         write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
947
948         msrpm[offset] = tmp;
949 }
950
951 static void svm_vcpu_init_msrpm(u32 *msrpm)
952 {
953         int i;
954
955         memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
956
957         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
958                 if (!direct_access_msrs[i].always)
959                         continue;
960
961                 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
962         }
963 }
964
965 static void add_msr_offset(u32 offset)
966 {
967         int i;
968
969         for (i = 0; i < MSRPM_OFFSETS; ++i) {
970
971                 /* Offset already in list? */
972                 if (msrpm_offsets[i] == offset)
973                         return;
974
975                 /* Slot used by another offset? */
976                 if (msrpm_offsets[i] != MSR_INVALID)
977                         continue;
978
979                 /* Add offset to list */
980                 msrpm_offsets[i] = offset;
981
982                 return;
983         }
984
985         /*
986          * If this BUG triggers the msrpm_offsets table has an overflow. Just
987          * increase MSRPM_OFFSETS in this case.
988          */
989         BUG();
990 }
991
992 static void init_msrpm_offsets(void)
993 {
994         int i;
995
996         memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
997
998         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
999                 u32 offset;
1000
1001                 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1002                 BUG_ON(offset == MSR_INVALID);
1003
1004                 add_msr_offset(offset);
1005         }
1006 }
1007
1008 static void svm_enable_lbrv(struct vcpu_svm *svm)
1009 {
1010         u32 *msrpm = svm->msrpm;
1011
1012         svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1013         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1014         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1015         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1016         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1017 }
1018
1019 static void svm_disable_lbrv(struct vcpu_svm *svm)
1020 {
1021         u32 *msrpm = svm->msrpm;
1022
1023         svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1024         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1025         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1026         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1027         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1028 }
1029
1030 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1031 {
1032         svm->nmi_singlestep = false;
1033
1034         if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1035                 /* Clear our flags if they were not set by the guest */
1036                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1037                         svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1038                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1039                         svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1040         }
1041 }
1042
1043 /* Note:
1044  * This hash table is used to map VM_ID to a struct kvm_arch,
1045  * when handling AMD IOMMU GALOG notification to schedule in
1046  * a particular vCPU.
1047  */
1048 #define SVM_VM_DATA_HASH_BITS   8
1049 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1050 static u32 next_vm_id = 0;
1051 static bool next_vm_id_wrapped = 0;
1052 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1053
1054 /* Note:
1055  * This function is called from IOMMU driver to notify
1056  * SVM to schedule in a particular vCPU of a particular VM.
1057  */
1058 static int avic_ga_log_notifier(u32 ga_tag)
1059 {
1060         unsigned long flags;
1061         struct kvm_arch *ka = NULL;
1062         struct kvm_vcpu *vcpu = NULL;
1063         u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1064         u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1065
1066         pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1067
1068         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1069         hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1070                 struct kvm *kvm = container_of(ka, struct kvm, arch);
1071                 struct kvm_arch *vm_data = &kvm->arch;
1072
1073                 if (vm_data->avic_vm_id != vm_id)
1074                         continue;
1075                 vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1076                 break;
1077         }
1078         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1079
1080         if (!vcpu)
1081                 return 0;
1082
1083         /* Note:
1084          * At this point, the IOMMU should have already set the pending
1085          * bit in the vAPIC backing page. So, we just need to schedule
1086          * in the vcpu.
1087          */
1088         if (vcpu->mode == OUTSIDE_GUEST_MODE)
1089                 kvm_vcpu_wake_up(vcpu);
1090
1091         return 0;
1092 }
1093
1094 /*
1095  * The default MMIO mask is a single bit (excluding the present bit),
1096  * which could conflict with the memory encryption bit. Check for
1097  * memory encryption support and override the default MMIO mask if
1098  * memory encryption is enabled.
1099  */
1100 static __init void svm_adjust_mmio_mask(void)
1101 {
1102         unsigned int enc_bit, mask_bit;
1103         u64 msr, mask;
1104
1105         /* If there is no memory encryption support, use existing mask */
1106         if (cpuid_eax(0x80000000) < 0x8000001f)
1107                 return;
1108
1109         /* If memory encryption is not enabled, use existing mask */
1110         rdmsrl(MSR_K8_SYSCFG, msr);
1111         if (!(msr & MSR_K8_SYSCFG_MEM_ENCRYPT))
1112                 return;
1113
1114         enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
1115         mask_bit = boot_cpu_data.x86_phys_bits;
1116
1117         /* Increment the mask bit if it is the same as the encryption bit */
1118         if (enc_bit == mask_bit)
1119                 mask_bit++;
1120
1121         /*
1122          * If the mask bit location is below 52, then some bits above the
1123          * physical addressing limit will always be reserved, so use the
1124          * rsvd_bits() function to generate the mask. This mask, along with
1125          * the present bit, will be used to generate a page fault with
1126          * PFER.RSV = 1.
1127          *
1128          * If the mask bit location is 52 (or above), then clear the mask.
1129          */
1130         mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
1131
1132         kvm_mmu_set_mmio_spte_mask(mask, mask);
1133 }
1134
1135 static __init int svm_hardware_setup(void)
1136 {
1137         int cpu;
1138         struct page *iopm_pages;
1139         void *iopm_va;
1140         int r;
1141
1142         iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1143
1144         if (!iopm_pages)
1145                 return -ENOMEM;
1146
1147         iopm_va = page_address(iopm_pages);
1148         memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1149         iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1150
1151         init_msrpm_offsets();
1152
1153         if (boot_cpu_has(X86_FEATURE_NX))
1154                 kvm_enable_efer_bits(EFER_NX);
1155
1156         if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1157                 kvm_enable_efer_bits(EFER_FFXSR);
1158
1159         if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1160                 kvm_has_tsc_control = true;
1161                 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1162                 kvm_tsc_scaling_ratio_frac_bits = 32;
1163         }
1164
1165         if (nested) {
1166                 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1167                 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1168         }
1169
1170         svm_adjust_mmio_mask();
1171
1172         for_each_possible_cpu(cpu) {
1173                 r = svm_cpu_init(cpu);
1174                 if (r)
1175                         goto err;
1176         }
1177
1178         if (!boot_cpu_has(X86_FEATURE_NPT))
1179                 npt_enabled = false;
1180
1181         if (npt_enabled && !npt) {
1182                 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1183                 npt_enabled = false;
1184         }
1185
1186         if (npt_enabled) {
1187                 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1188                 kvm_enable_tdp();
1189         } else
1190                 kvm_disable_tdp();
1191
1192         if (avic) {
1193                 if (!npt_enabled ||
1194                     !boot_cpu_has(X86_FEATURE_AVIC) ||
1195                     !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1196                         avic = false;
1197                 } else {
1198                         pr_info("AVIC enabled\n");
1199
1200                         amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1201                 }
1202         }
1203
1204         if (vls) {
1205                 if (!npt_enabled ||
1206                     !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1207                     !IS_ENABLED(CONFIG_X86_64)) {
1208                         vls = false;
1209                 } else {
1210                         pr_info("Virtual VMLOAD VMSAVE supported\n");
1211                 }
1212         }
1213
1214         vgif = false; /* Disabled for CVE-2021-3653 */
1215
1216         return 0;
1217
1218 err:
1219         __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1220         iopm_base = 0;
1221         return r;
1222 }
1223
1224 static __exit void svm_hardware_unsetup(void)
1225 {
1226         int cpu;
1227
1228         for_each_possible_cpu(cpu)
1229                 svm_cpu_uninit(cpu);
1230
1231         __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1232         iopm_base = 0;
1233 }
1234
1235 static void init_seg(struct vmcb_seg *seg)
1236 {
1237         seg->selector = 0;
1238         seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1239                       SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1240         seg->limit = 0xffff;
1241         seg->base = 0;
1242 }
1243
1244 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1245 {
1246         seg->selector = 0;
1247         seg->attrib = SVM_SELECTOR_P_MASK | type;
1248         seg->limit = 0xffff;
1249         seg->base = 0;
1250 }
1251
1252 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1253 {
1254         struct vcpu_svm *svm = to_svm(vcpu);
1255         u64 g_tsc_offset = 0;
1256
1257         if (is_guest_mode(vcpu)) {
1258                 g_tsc_offset = svm->vmcb->control.tsc_offset -
1259                                svm->nested.hsave->control.tsc_offset;
1260                 svm->nested.hsave->control.tsc_offset = offset;
1261         } else
1262                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1263                                            svm->vmcb->control.tsc_offset,
1264                                            offset);
1265
1266         svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1267
1268         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1269 }
1270
1271 static void avic_init_vmcb(struct vcpu_svm *svm)
1272 {
1273         struct vmcb *vmcb = svm->vmcb;
1274         struct kvm_arch *vm_data = &svm->vcpu.kvm->arch;
1275         phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1276         phys_addr_t lpa = __sme_set(page_to_phys(vm_data->avic_logical_id_table_page));
1277         phys_addr_t ppa = __sme_set(page_to_phys(vm_data->avic_physical_id_table_page));
1278
1279         vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1280         vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1281         vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1282         vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1283         vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1284 }
1285
1286 static void init_vmcb(struct vcpu_svm *svm)
1287 {
1288         struct vmcb_control_area *control = &svm->vmcb->control;
1289         struct vmcb_save_area *save = &svm->vmcb->save;
1290
1291         svm->vcpu.arch.hflags = 0;
1292
1293         set_cr_intercept(svm, INTERCEPT_CR0_READ);
1294         set_cr_intercept(svm, INTERCEPT_CR3_READ);
1295         set_cr_intercept(svm, INTERCEPT_CR4_READ);
1296         set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1297         set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1298         set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1299         if (!kvm_vcpu_apicv_active(&svm->vcpu))
1300                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1301
1302         set_dr_intercepts(svm);
1303
1304         set_exception_intercept(svm, PF_VECTOR);
1305         set_exception_intercept(svm, UD_VECTOR);
1306         set_exception_intercept(svm, MC_VECTOR);
1307         set_exception_intercept(svm, AC_VECTOR);
1308         set_exception_intercept(svm, DB_VECTOR);
1309
1310         set_intercept(svm, INTERCEPT_INTR);
1311         set_intercept(svm, INTERCEPT_NMI);
1312         set_intercept(svm, INTERCEPT_SMI);
1313         set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1314         set_intercept(svm, INTERCEPT_RDPMC);
1315         set_intercept(svm, INTERCEPT_CPUID);
1316         set_intercept(svm, INTERCEPT_INVD);
1317         set_intercept(svm, INTERCEPT_HLT);
1318         set_intercept(svm, INTERCEPT_INVLPG);
1319         set_intercept(svm, INTERCEPT_INVLPGA);
1320         set_intercept(svm, INTERCEPT_IOIO_PROT);
1321         set_intercept(svm, INTERCEPT_MSR_PROT);
1322         set_intercept(svm, INTERCEPT_TASK_SWITCH);
1323         set_intercept(svm, INTERCEPT_SHUTDOWN);
1324         set_intercept(svm, INTERCEPT_VMRUN);
1325         set_intercept(svm, INTERCEPT_VMMCALL);
1326         set_intercept(svm, INTERCEPT_VMLOAD);
1327         set_intercept(svm, INTERCEPT_VMSAVE);
1328         set_intercept(svm, INTERCEPT_STGI);
1329         set_intercept(svm, INTERCEPT_CLGI);
1330         set_intercept(svm, INTERCEPT_SKINIT);
1331         set_intercept(svm, INTERCEPT_WBINVD);
1332         set_intercept(svm, INTERCEPT_XSETBV);
1333
1334         if (!kvm_mwait_in_guest()) {
1335                 set_intercept(svm, INTERCEPT_MONITOR);
1336                 set_intercept(svm, INTERCEPT_MWAIT);
1337         }
1338
1339         control->iopm_base_pa = __sme_set(iopm_base);
1340         control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1341         control->int_ctl = V_INTR_MASKING_MASK;
1342
1343         init_seg(&save->es);
1344         init_seg(&save->ss);
1345         init_seg(&save->ds);
1346         init_seg(&save->fs);
1347         init_seg(&save->gs);
1348
1349         save->cs.selector = 0xf000;
1350         save->cs.base = 0xffff0000;
1351         /* Executable/Readable Code Segment */
1352         save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1353                 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1354         save->cs.limit = 0xffff;
1355
1356         save->gdtr.limit = 0xffff;
1357         save->idtr.limit = 0xffff;
1358
1359         init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1360         init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1361
1362         svm_set_efer(&svm->vcpu, 0);
1363         save->dr6 = 0xffff0ff0;
1364         kvm_set_rflags(&svm->vcpu, 2);
1365         save->rip = 0x0000fff0;
1366         svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1367
1368         /*
1369          * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1370          * It also updates the guest-visible cr0 value.
1371          */
1372         svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1373         kvm_mmu_reset_context(&svm->vcpu);
1374
1375         save->cr4 = X86_CR4_PAE;
1376         /* rdx = ?? */
1377
1378         if (npt_enabled) {
1379                 /* Setup VMCB for Nested Paging */
1380                 control->nested_ctl = 1;
1381                 clr_intercept(svm, INTERCEPT_INVLPG);
1382                 clr_exception_intercept(svm, PF_VECTOR);
1383                 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1384                 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1385                 save->g_pat = svm->vcpu.arch.pat;
1386                 save->cr3 = 0;
1387                 save->cr4 = 0;
1388         }
1389         svm->asid_generation = 0;
1390
1391         svm->nested.vmcb = 0;
1392         svm->vcpu.arch.hflags = 0;
1393
1394         if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1395                 control->pause_filter_count = 3000;
1396                 set_intercept(svm, INTERCEPT_PAUSE);
1397         }
1398
1399         if (kvm_vcpu_apicv_active(&svm->vcpu))
1400                 avic_init_vmcb(svm);
1401
1402         /*
1403          * If hardware supports Virtual VMLOAD VMSAVE then enable it
1404          * in VMCB and clear intercepts to avoid #VMEXIT.
1405          */
1406         if (vls) {
1407                 clr_intercept(svm, INTERCEPT_VMLOAD);
1408                 clr_intercept(svm, INTERCEPT_VMSAVE);
1409                 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1410         }
1411
1412         if (vgif) {
1413                 clr_intercept(svm, INTERCEPT_STGI);
1414                 clr_intercept(svm, INTERCEPT_CLGI);
1415                 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1416         }
1417
1418         mark_all_dirty(svm->vmcb);
1419
1420         enable_gif(svm);
1421
1422 }
1423
1424 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1425                                        unsigned int index)
1426 {
1427         u64 *avic_physical_id_table;
1428         struct kvm_arch *vm_data = &vcpu->kvm->arch;
1429
1430         if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1431                 return NULL;
1432
1433         avic_physical_id_table = page_address(vm_data->avic_physical_id_table_page);
1434
1435         return &avic_physical_id_table[index];
1436 }
1437
1438 /**
1439  * Note:
1440  * AVIC hardware walks the nested page table to check permissions,
1441  * but does not use the SPA address specified in the leaf page
1442  * table entry since it uses  address in the AVIC_BACKING_PAGE pointer
1443  * field of the VMCB. Therefore, we set up the
1444  * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1445  */
1446 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1447 {
1448         struct kvm *kvm = vcpu->kvm;
1449         int ret = 0;
1450
1451         mutex_lock(&kvm->slots_lock);
1452         if (kvm->arch.apic_access_page_done)
1453                 goto out;
1454
1455         ret = __x86_set_memory_region(kvm,
1456                                       APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1457                                       APIC_DEFAULT_PHYS_BASE,
1458                                       PAGE_SIZE);
1459         if (ret)
1460                 goto out;
1461
1462         kvm->arch.apic_access_page_done = true;
1463 out:
1464         mutex_unlock(&kvm->slots_lock);
1465         return ret;
1466 }
1467
1468 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1469 {
1470         int ret;
1471         u64 *entry, new_entry;
1472         int id = vcpu->vcpu_id;
1473         struct vcpu_svm *svm = to_svm(vcpu);
1474
1475         ret = avic_init_access_page(vcpu);
1476         if (ret)
1477                 return ret;
1478
1479         if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1480                 return -EINVAL;
1481
1482         if (!svm->vcpu.arch.apic->regs)
1483                 return -EINVAL;
1484
1485         svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1486
1487         /* Setting AVIC backing page address in the phy APIC ID table */
1488         entry = avic_get_physical_id_entry(vcpu, id);
1489         if (!entry)
1490                 return -EINVAL;
1491
1492         new_entry = READ_ONCE(*entry);
1493         new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1494                               AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1495                               AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1496         WRITE_ONCE(*entry, new_entry);
1497
1498         svm->avic_physical_id_cache = entry;
1499
1500         return 0;
1501 }
1502
1503 static void avic_vm_destroy(struct kvm *kvm)
1504 {
1505         unsigned long flags;
1506         struct kvm_arch *vm_data = &kvm->arch;
1507
1508         if (!avic)
1509                 return;
1510
1511         if (vm_data->avic_logical_id_table_page)
1512                 __free_page(vm_data->avic_logical_id_table_page);
1513         if (vm_data->avic_physical_id_table_page)
1514                 __free_page(vm_data->avic_physical_id_table_page);
1515
1516         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1517         hash_del(&vm_data->hnode);
1518         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1519 }
1520
1521 static int avic_vm_init(struct kvm *kvm)
1522 {
1523         unsigned long flags;
1524         int err = -ENOMEM;
1525         struct kvm_arch *vm_data = &kvm->arch;
1526         struct page *p_page;
1527         struct page *l_page;
1528         struct kvm_arch *ka;
1529         u32 vm_id;
1530
1531         if (!avic)
1532                 return 0;
1533
1534         /* Allocating physical APIC ID table (4KB) */
1535         p_page = alloc_page(GFP_KERNEL);
1536         if (!p_page)
1537                 goto free_avic;
1538
1539         vm_data->avic_physical_id_table_page = p_page;
1540         clear_page(page_address(p_page));
1541
1542         /* Allocating logical APIC ID table (4KB) */
1543         l_page = alloc_page(GFP_KERNEL);
1544         if (!l_page)
1545                 goto free_avic;
1546
1547         vm_data->avic_logical_id_table_page = l_page;
1548         clear_page(page_address(l_page));
1549
1550         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1551  again:
1552         vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1553         if (vm_id == 0) { /* id is 1-based, zero is not okay */
1554                 next_vm_id_wrapped = 1;
1555                 goto again;
1556         }
1557         /* Is it still in use? Only possible if wrapped at least once */
1558         if (next_vm_id_wrapped) {
1559                 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1560                         struct kvm *k2 = container_of(ka, struct kvm, arch);
1561                         struct kvm_arch *vd2 = &k2->arch;
1562                         if (vd2->avic_vm_id == vm_id)
1563                                 goto again;
1564                 }
1565         }
1566         vm_data->avic_vm_id = vm_id;
1567         hash_add(svm_vm_data_hash, &vm_data->hnode, vm_data->avic_vm_id);
1568         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1569
1570         return 0;
1571
1572 free_avic:
1573         avic_vm_destroy(kvm);
1574         return err;
1575 }
1576
1577 static inline int
1578 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1579 {
1580         int ret = 0;
1581         unsigned long flags;
1582         struct amd_svm_iommu_ir *ir;
1583         struct vcpu_svm *svm = to_svm(vcpu);
1584
1585         if (!kvm_arch_has_assigned_device(vcpu->kvm))
1586                 return 0;
1587
1588         /*
1589          * Here, we go through the per-vcpu ir_list to update all existing
1590          * interrupt remapping table entry targeting this vcpu.
1591          */
1592         spin_lock_irqsave(&svm->ir_list_lock, flags);
1593
1594         if (list_empty(&svm->ir_list))
1595                 goto out;
1596
1597         list_for_each_entry(ir, &svm->ir_list, node) {
1598                 ret = amd_iommu_update_ga(cpu, r, ir->data);
1599                 if (ret)
1600                         break;
1601         }
1602 out:
1603         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1604         return ret;
1605 }
1606
1607 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1608 {
1609         u64 entry;
1610         /* ID = 0xff (broadcast), ID > 0xff (reserved) */
1611         int h_physical_id = kvm_cpu_get_apicid(cpu);
1612         struct vcpu_svm *svm = to_svm(vcpu);
1613
1614         if (!kvm_vcpu_apicv_active(vcpu))
1615                 return;
1616
1617         /*
1618          * Since the host physical APIC id is 8 bits,
1619          * we can support host APIC ID upto 255.
1620          */
1621         if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
1622                 return;
1623
1624         entry = READ_ONCE(*(svm->avic_physical_id_cache));
1625         WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1626
1627         entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1628         entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1629
1630         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1631         if (svm->avic_is_running)
1632                 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1633
1634         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1635         avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
1636                                         svm->avic_is_running);
1637 }
1638
1639 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
1640 {
1641         u64 entry;
1642         struct vcpu_svm *svm = to_svm(vcpu);
1643
1644         if (!kvm_vcpu_apicv_active(vcpu))
1645                 return;
1646
1647         entry = READ_ONCE(*(svm->avic_physical_id_cache));
1648         if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
1649                 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1650
1651         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1652         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1653 }
1654
1655 /**
1656  * This function is called during VCPU halt/unhalt.
1657  */
1658 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
1659 {
1660         struct vcpu_svm *svm = to_svm(vcpu);
1661
1662         svm->avic_is_running = is_run;
1663         if (is_run)
1664                 avic_vcpu_load(vcpu, vcpu->cpu);
1665         else
1666                 avic_vcpu_put(vcpu);
1667 }
1668
1669 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1670 {
1671         struct vcpu_svm *svm = to_svm(vcpu);
1672         u32 dummy;
1673         u32 eax = 1;
1674
1675         vcpu->arch.microcode_version = 0x01000065;
1676         svm->spec_ctrl = 0;
1677         svm->virt_spec_ctrl = 0;
1678
1679         if (!init_event) {
1680                 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1681                                            MSR_IA32_APICBASE_ENABLE;
1682                 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1683                         svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1684         }
1685         init_vmcb(svm);
1686
1687         kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
1688         kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1689
1690         if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1691                 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1692 }
1693
1694 static int avic_init_vcpu(struct vcpu_svm *svm)
1695 {
1696         int ret;
1697
1698         if (!kvm_vcpu_apicv_active(&svm->vcpu))
1699                 return 0;
1700
1701         ret = avic_init_backing_page(&svm->vcpu);
1702         if (ret)
1703                 return ret;
1704
1705         INIT_LIST_HEAD(&svm->ir_list);
1706         spin_lock_init(&svm->ir_list_lock);
1707
1708         return ret;
1709 }
1710
1711 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1712 {
1713         struct vcpu_svm *svm;
1714         struct page *page;
1715         struct page *msrpm_pages;
1716         struct page *hsave_page;
1717         struct page *nested_msrpm_pages;
1718         int err;
1719
1720         svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1721         if (!svm) {
1722                 err = -ENOMEM;
1723                 goto out;
1724         }
1725
1726         err = kvm_vcpu_init(&svm->vcpu, kvm, id);
1727         if (err)
1728                 goto free_svm;
1729
1730         err = -ENOMEM;
1731         page = alloc_page(GFP_KERNEL);
1732         if (!page)
1733                 goto uninit;
1734
1735         msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1736         if (!msrpm_pages)
1737                 goto free_page1;
1738
1739         nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1740         if (!nested_msrpm_pages)
1741                 goto free_page2;
1742
1743         hsave_page = alloc_page(GFP_KERNEL);
1744         if (!hsave_page)
1745                 goto free_page3;
1746
1747         err = avic_init_vcpu(svm);
1748         if (err)
1749                 goto free_page4;
1750
1751         /* We initialize this flag to true to make sure that the is_running
1752          * bit would be set the first time the vcpu is loaded.
1753          */
1754         svm->avic_is_running = true;
1755
1756         svm->nested.hsave = page_address(hsave_page);
1757
1758         svm->msrpm = page_address(msrpm_pages);
1759         svm_vcpu_init_msrpm(svm->msrpm);
1760
1761         svm->nested.msrpm = page_address(nested_msrpm_pages);
1762         svm_vcpu_init_msrpm(svm->nested.msrpm);
1763
1764         svm->vmcb = page_address(page);
1765         clear_page(svm->vmcb);
1766         svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
1767         svm->asid_generation = 0;
1768         init_vmcb(svm);
1769
1770         svm_init_osvw(&svm->vcpu);
1771
1772         return &svm->vcpu;
1773
1774 free_page4:
1775         __free_page(hsave_page);
1776 free_page3:
1777         __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
1778 free_page2:
1779         __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
1780 free_page1:
1781         __free_page(page);
1782 uninit:
1783         kvm_vcpu_uninit(&svm->vcpu);
1784 free_svm:
1785         kmem_cache_free(kvm_vcpu_cache, svm);
1786 out:
1787         return ERR_PTR(err);
1788 }
1789
1790 static void svm_clear_current_vmcb(struct vmcb *vmcb)
1791 {
1792         int i;
1793
1794         for_each_online_cpu(i)
1795                 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
1796 }
1797
1798 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
1799 {
1800         struct vcpu_svm *svm = to_svm(vcpu);
1801
1802         /*
1803          * The vmcb page can be recycled, causing a false negative in
1804          * svm_vcpu_load(). So, ensure that no logical CPU has this
1805          * vmcb page recorded as its current vmcb.
1806          */
1807         svm_clear_current_vmcb(svm->vmcb);
1808
1809         __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
1810         __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
1811         __free_page(virt_to_page(svm->nested.hsave));
1812         __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
1813         kvm_vcpu_uninit(vcpu);
1814         kmem_cache_free(kvm_vcpu_cache, svm);
1815 }
1816
1817 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1818 {
1819         struct vcpu_svm *svm = to_svm(vcpu);
1820         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1821         int i;
1822
1823         if (unlikely(cpu != vcpu->cpu)) {
1824                 svm->asid_generation = 0;
1825                 mark_all_dirty(svm->vmcb);
1826         }
1827
1828 #ifdef CONFIG_X86_64
1829         rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
1830 #endif
1831         savesegment(fs, svm->host.fs);
1832         savesegment(gs, svm->host.gs);
1833         svm->host.ldt = kvm_read_ldt();
1834
1835         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
1836                 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
1837
1838         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1839                 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
1840                 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
1841                         __this_cpu_write(current_tsc_ratio, tsc_ratio);
1842                         wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
1843                 }
1844         }
1845         /* This assumes that the kernel never uses MSR_TSC_AUX */
1846         if (static_cpu_has(X86_FEATURE_RDTSCP))
1847                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
1848
1849         if (sd->current_vmcb != svm->vmcb) {
1850                 sd->current_vmcb = svm->vmcb;
1851                 indirect_branch_prediction_barrier();
1852         }
1853         avic_vcpu_load(vcpu, cpu);
1854 }
1855
1856 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1857 {
1858         struct vcpu_svm *svm = to_svm(vcpu);
1859         int i;
1860
1861         avic_vcpu_put(vcpu);
1862
1863         ++vcpu->stat.host_state_reload;
1864         kvm_load_ldt(svm->host.ldt);
1865 #ifdef CONFIG_X86_64
1866         loadsegment(fs, svm->host.fs);
1867         wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
1868         load_gs_index(svm->host.gs);
1869 #else
1870 #ifdef CONFIG_X86_32_LAZY_GS
1871         loadsegment(gs, svm->host.gs);
1872 #endif
1873 #endif
1874         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
1875                 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
1876 }
1877
1878 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
1879 {
1880         avic_set_running(vcpu, false);
1881 }
1882
1883 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
1884 {
1885         avic_set_running(vcpu, true);
1886 }
1887
1888 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1889 {
1890         struct vcpu_svm *svm = to_svm(vcpu);
1891         unsigned long rflags = svm->vmcb->save.rflags;
1892
1893         if (svm->nmi_singlestep) {
1894                 /* Hide our flags if they were not set by the guest */
1895                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1896                         rflags &= ~X86_EFLAGS_TF;
1897                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1898                         rflags &= ~X86_EFLAGS_RF;
1899         }
1900         return rflags;
1901 }
1902
1903 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1904 {
1905         if (to_svm(vcpu)->nmi_singlestep)
1906                 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
1907
1908        /*
1909         * Any change of EFLAGS.VM is accompanied by a reload of SS
1910         * (caused by either a task switch or an inter-privilege IRET),
1911         * so we do not need to update the CPL here.
1912         */
1913         to_svm(vcpu)->vmcb->save.rflags = rflags;
1914 }
1915
1916 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1917 {
1918         switch (reg) {
1919         case VCPU_EXREG_PDPTR:
1920                 BUG_ON(!npt_enabled);
1921                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
1922                 break;
1923         default:
1924                 BUG();
1925         }
1926 }
1927
1928 static void svm_set_vintr(struct vcpu_svm *svm)
1929 {
1930         set_intercept(svm, INTERCEPT_VINTR);
1931 }
1932
1933 static void svm_clear_vintr(struct vcpu_svm *svm)
1934 {
1935         clr_intercept(svm, INTERCEPT_VINTR);
1936 }
1937
1938 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1939 {
1940         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1941
1942         switch (seg) {
1943         case VCPU_SREG_CS: return &save->cs;
1944         case VCPU_SREG_DS: return &save->ds;
1945         case VCPU_SREG_ES: return &save->es;
1946         case VCPU_SREG_FS: return &save->fs;
1947         case VCPU_SREG_GS: return &save->gs;
1948         case VCPU_SREG_SS: return &save->ss;
1949         case VCPU_SREG_TR: return &save->tr;
1950         case VCPU_SREG_LDTR: return &save->ldtr;
1951         }
1952         BUG();
1953         return NULL;
1954 }
1955
1956 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1957 {
1958         struct vmcb_seg *s = svm_seg(vcpu, seg);
1959
1960         return s->base;
1961 }
1962
1963 static void svm_get_segment(struct kvm_vcpu *vcpu,
1964                             struct kvm_segment *var, int seg)
1965 {
1966         struct vmcb_seg *s = svm_seg(vcpu, seg);
1967
1968         var->base = s->base;
1969         var->limit = s->limit;
1970         var->selector = s->selector;
1971         var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1972         var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1973         var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1974         var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1975         var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1976         var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1977         var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1978
1979         /*
1980          * AMD CPUs circa 2014 track the G bit for all segments except CS.
1981          * However, the SVM spec states that the G bit is not observed by the
1982          * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1983          * So let's synthesize a legal G bit for all segments, this helps
1984          * running KVM nested. It also helps cross-vendor migration, because
1985          * Intel's vmentry has a check on the 'G' bit.
1986          */
1987         var->g = s->limit > 0xfffff;
1988
1989         /*
1990          * AMD's VMCB does not have an explicit unusable field, so emulate it
1991          * for cross vendor migration purposes by "not present"
1992          */
1993         var->unusable = !var->present;
1994
1995         switch (seg) {
1996         case VCPU_SREG_TR:
1997                 /*
1998                  * Work around a bug where the busy flag in the tr selector
1999                  * isn't exposed
2000                  */
2001                 var->type |= 0x2;
2002                 break;
2003         case VCPU_SREG_DS:
2004         case VCPU_SREG_ES:
2005         case VCPU_SREG_FS:
2006         case VCPU_SREG_GS:
2007                 /*
2008                  * The accessed bit must always be set in the segment
2009                  * descriptor cache, although it can be cleared in the
2010                  * descriptor, the cached bit always remains at 1. Since
2011                  * Intel has a check on this, set it here to support
2012                  * cross-vendor migration.
2013                  */
2014                 if (!var->unusable)
2015                         var->type |= 0x1;
2016                 break;
2017         case VCPU_SREG_SS:
2018                 /*
2019                  * On AMD CPUs sometimes the DB bit in the segment
2020                  * descriptor is left as 1, although the whole segment has
2021                  * been made unusable. Clear it here to pass an Intel VMX
2022                  * entry check when cross vendor migrating.
2023                  */
2024                 if (var->unusable)
2025                         var->db = 0;
2026                 /* This is symmetric with svm_set_segment() */
2027                 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2028                 break;
2029         }
2030 }
2031
2032 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2033 {
2034         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2035
2036         return save->cpl;
2037 }
2038
2039 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2040 {
2041         struct vcpu_svm *svm = to_svm(vcpu);
2042
2043         dt->size = svm->vmcb->save.idtr.limit;
2044         dt->address = svm->vmcb->save.idtr.base;
2045 }
2046
2047 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2048 {
2049         struct vcpu_svm *svm = to_svm(vcpu);
2050
2051         svm->vmcb->save.idtr.limit = dt->size;
2052         svm->vmcb->save.idtr.base = dt->address ;
2053         mark_dirty(svm->vmcb, VMCB_DT);
2054 }
2055
2056 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2057 {
2058         struct vcpu_svm *svm = to_svm(vcpu);
2059
2060         dt->size = svm->vmcb->save.gdtr.limit;
2061         dt->address = svm->vmcb->save.gdtr.base;
2062 }
2063
2064 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2065 {
2066         struct vcpu_svm *svm = to_svm(vcpu);
2067
2068         svm->vmcb->save.gdtr.limit = dt->size;
2069         svm->vmcb->save.gdtr.base = dt->address ;
2070         mark_dirty(svm->vmcb, VMCB_DT);
2071 }
2072
2073 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2074 {
2075 }
2076
2077 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2078 {
2079 }
2080
2081 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2082 {
2083 }
2084
2085 static void update_cr0_intercept(struct vcpu_svm *svm)
2086 {
2087         ulong gcr0 = svm->vcpu.arch.cr0;
2088         u64 *hcr0 = &svm->vmcb->save.cr0;
2089
2090         *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2091                 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2092
2093         mark_dirty(svm->vmcb, VMCB_CR);
2094
2095         if (gcr0 == *hcr0) {
2096                 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2097                 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2098         } else {
2099                 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2100                 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2101         }
2102 }
2103
2104 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2105 {
2106         struct vcpu_svm *svm = to_svm(vcpu);
2107
2108 #ifdef CONFIG_X86_64
2109         if (vcpu->arch.efer & EFER_LME) {
2110                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2111                         vcpu->arch.efer |= EFER_LMA;
2112                         svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2113                 }
2114
2115                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2116                         vcpu->arch.efer &= ~EFER_LMA;
2117                         svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2118                 }
2119         }
2120 #endif
2121         vcpu->arch.cr0 = cr0;
2122
2123         if (!npt_enabled)
2124                 cr0 |= X86_CR0_PG | X86_CR0_WP;
2125
2126         /*
2127          * re-enable caching here because the QEMU bios
2128          * does not do it - this results in some delay at
2129          * reboot
2130          */
2131         if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2132                 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2133         svm->vmcb->save.cr0 = cr0;
2134         mark_dirty(svm->vmcb, VMCB_CR);
2135         update_cr0_intercept(svm);
2136 }
2137
2138 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2139 {
2140         unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2141         unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2142
2143         if (cr4 & X86_CR4_VMXE)
2144                 return 1;
2145
2146         if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2147                 svm_flush_tlb(vcpu, true);
2148
2149         vcpu->arch.cr4 = cr4;
2150         if (!npt_enabled)
2151                 cr4 |= X86_CR4_PAE;
2152         cr4 |= host_cr4_mce;
2153         to_svm(vcpu)->vmcb->save.cr4 = cr4;
2154         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2155         return 0;
2156 }
2157
2158 static void svm_set_segment(struct kvm_vcpu *vcpu,
2159                             struct kvm_segment *var, int seg)
2160 {
2161         struct vcpu_svm *svm = to_svm(vcpu);
2162         struct vmcb_seg *s = svm_seg(vcpu, seg);
2163
2164         s->base = var->base;
2165         s->limit = var->limit;
2166         s->selector = var->selector;
2167         s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2168         s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2169         s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2170         s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2171         s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2172         s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2173         s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2174         s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2175
2176         /*
2177          * This is always accurate, except if SYSRET returned to a segment
2178          * with SS.DPL != 3.  Intel does not have this quirk, and always
2179          * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2180          * would entail passing the CPL to userspace and back.
2181          */
2182         if (seg == VCPU_SREG_SS)
2183                 /* This is symmetric with svm_get_segment() */
2184                 svm->vmcb->save.cpl = (var->dpl & 3);
2185
2186         mark_dirty(svm->vmcb, VMCB_SEG);
2187 }
2188
2189 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2190 {
2191         struct vcpu_svm *svm = to_svm(vcpu);
2192
2193         clr_exception_intercept(svm, BP_VECTOR);
2194
2195         if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2196                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2197                         set_exception_intercept(svm, BP_VECTOR);
2198         } else
2199                 vcpu->guest_debug = 0;
2200 }
2201
2202 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2203 {
2204         if (sd->next_asid > sd->max_asid) {
2205                 ++sd->asid_generation;
2206                 sd->next_asid = 1;
2207                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2208         }
2209
2210         svm->asid_generation = sd->asid_generation;
2211         svm->vmcb->control.asid = sd->next_asid++;
2212
2213         mark_dirty(svm->vmcb, VMCB_ASID);
2214 }
2215
2216 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2217 {
2218         return to_svm(vcpu)->vmcb->save.dr6;
2219 }
2220
2221 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2222 {
2223         struct vcpu_svm *svm = to_svm(vcpu);
2224
2225         svm->vmcb->save.dr6 = value;
2226         mark_dirty(svm->vmcb, VMCB_DR);
2227 }
2228
2229 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2230 {
2231         struct vcpu_svm *svm = to_svm(vcpu);
2232
2233         get_debugreg(vcpu->arch.db[0], 0);
2234         get_debugreg(vcpu->arch.db[1], 1);
2235         get_debugreg(vcpu->arch.db[2], 2);
2236         get_debugreg(vcpu->arch.db[3], 3);
2237         vcpu->arch.dr6 = svm_get_dr6(vcpu);
2238         vcpu->arch.dr7 = svm->vmcb->save.dr7;
2239
2240         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2241         set_dr_intercepts(svm);
2242 }
2243
2244 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2245 {
2246         struct vcpu_svm *svm = to_svm(vcpu);
2247
2248         svm->vmcb->save.dr7 = value;
2249         mark_dirty(svm->vmcb, VMCB_DR);
2250 }
2251
2252 static int pf_interception(struct vcpu_svm *svm)
2253 {
2254         u64 fault_address = svm->vmcb->control.exit_info_2;
2255         u64 error_code = svm->vmcb->control.exit_info_1;
2256
2257         return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2258                         svm->vmcb->control.insn_bytes,
2259                         svm->vmcb->control.insn_len, !npt_enabled);
2260 }
2261
2262 static int db_interception(struct vcpu_svm *svm)
2263 {
2264         struct kvm_run *kvm_run = svm->vcpu.run;
2265         struct kvm_vcpu *vcpu = &svm->vcpu;
2266
2267         if (!(svm->vcpu.guest_debug &
2268               (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2269                 !svm->nmi_singlestep) {
2270                 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2271                 return 1;
2272         }
2273
2274         if (svm->nmi_singlestep) {
2275                 disable_nmi_singlestep(svm);
2276                 /* Make sure we check for pending NMIs upon entry */
2277                 kvm_make_request(KVM_REQ_EVENT, vcpu);
2278         }
2279
2280         if (svm->vcpu.guest_debug &
2281             (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2282                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2283                 kvm_run->debug.arch.pc =
2284                         svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2285                 kvm_run->debug.arch.exception = DB_VECTOR;
2286                 return 0;
2287         }
2288
2289         return 1;
2290 }
2291
2292 static int bp_interception(struct vcpu_svm *svm)
2293 {
2294         struct kvm_run *kvm_run = svm->vcpu.run;
2295
2296         kvm_run->exit_reason = KVM_EXIT_DEBUG;
2297         kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2298         kvm_run->debug.arch.exception = BP_VECTOR;
2299         return 0;
2300 }
2301
2302 static int ud_interception(struct vcpu_svm *svm)
2303 {
2304         int er;
2305
2306         er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
2307         if (er == EMULATE_USER_EXIT)
2308                 return 0;
2309         if (er != EMULATE_DONE)
2310                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2311         return 1;
2312 }
2313
2314 static int ac_interception(struct vcpu_svm *svm)
2315 {
2316         kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2317         return 1;
2318 }
2319
2320 static bool is_erratum_383(void)
2321 {
2322         int err, i;
2323         u64 value;
2324
2325         if (!erratum_383_found)
2326                 return false;
2327
2328         value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2329         if (err)
2330                 return false;
2331
2332         /* Bit 62 may or may not be set for this mce */
2333         value &= ~(1ULL << 62);
2334
2335         if (value != 0xb600000000010015ULL)
2336                 return false;
2337
2338         /* Clear MCi_STATUS registers */
2339         for (i = 0; i < 6; ++i)
2340                 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2341
2342         value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2343         if (!err) {
2344                 u32 low, high;
2345
2346                 value &= ~(1ULL << 2);
2347                 low    = lower_32_bits(value);
2348                 high   = upper_32_bits(value);
2349
2350                 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2351         }
2352
2353         /* Flush tlb to evict multi-match entries */
2354         __flush_tlb_all();
2355
2356         return true;
2357 }
2358
2359 static void svm_handle_mce(struct vcpu_svm *svm)
2360 {
2361         if (is_erratum_383()) {
2362                 /*
2363                  * Erratum 383 triggered. Guest state is corrupt so kill the
2364                  * guest.
2365                  */
2366                 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2367
2368                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2369
2370                 return;
2371         }
2372
2373         /*
2374          * On an #MC intercept the MCE handler is not called automatically in
2375          * the host. So do it by hand here.
2376          */
2377         asm volatile (
2378                 "int $0x12\n");
2379         /* not sure if we ever come back to this point */
2380
2381         return;
2382 }
2383
2384 static int mc_interception(struct vcpu_svm *svm)
2385 {
2386         return 1;
2387 }
2388
2389 static int shutdown_interception(struct vcpu_svm *svm)
2390 {
2391         struct kvm_run *kvm_run = svm->vcpu.run;
2392
2393         /*
2394          * VMCB is undefined after a SHUTDOWN intercept
2395          * so reinitialize it.
2396          */
2397         clear_page(svm->vmcb);
2398         init_vmcb(svm);
2399
2400         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2401         return 0;
2402 }
2403
2404 static int io_interception(struct vcpu_svm *svm)
2405 {
2406         struct kvm_vcpu *vcpu = &svm->vcpu;
2407         u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2408         int size, in, string, ret;
2409         unsigned port;
2410
2411         ++svm->vcpu.stat.io_exits;
2412         string = (io_info & SVM_IOIO_STR_MASK) != 0;
2413         in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2414         if (string)
2415                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2416
2417         port = io_info >> 16;
2418         size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2419         svm->next_rip = svm->vmcb->control.exit_info_2;
2420         ret = kvm_skip_emulated_instruction(&svm->vcpu);
2421
2422         /*
2423          * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
2424          * KVM_EXIT_DEBUG here.
2425          */
2426         if (in)
2427                 return kvm_fast_pio_in(vcpu, size, port) && ret;
2428         else
2429                 return kvm_fast_pio_out(vcpu, size, port) && ret;
2430 }
2431
2432 static int nmi_interception(struct vcpu_svm *svm)
2433 {
2434         return 1;
2435 }
2436
2437 static int intr_interception(struct vcpu_svm *svm)
2438 {
2439         ++svm->vcpu.stat.irq_exits;
2440         return 1;
2441 }
2442
2443 static int nop_on_interception(struct vcpu_svm *svm)
2444 {
2445         return 1;
2446 }
2447
2448 static int halt_interception(struct vcpu_svm *svm)
2449 {
2450         svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2451         return kvm_emulate_halt(&svm->vcpu);
2452 }
2453
2454 static int vmmcall_interception(struct vcpu_svm *svm)
2455 {
2456         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2457         return kvm_emulate_hypercall(&svm->vcpu);
2458 }
2459
2460 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2461 {
2462         struct vcpu_svm *svm = to_svm(vcpu);
2463
2464         return svm->nested.nested_cr3;
2465 }
2466
2467 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2468 {
2469         struct vcpu_svm *svm = to_svm(vcpu);
2470         u64 cr3 = svm->nested.nested_cr3;
2471         u64 pdpte;
2472         int ret;
2473
2474         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2475                                        offset_in_page(cr3) + index * 8, 8);
2476         if (ret)
2477                 return 0;
2478         return pdpte;
2479 }
2480
2481 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2482                                    unsigned long root)
2483 {
2484         struct vcpu_svm *svm = to_svm(vcpu);
2485
2486         svm->vmcb->control.nested_cr3 = __sme_set(root);
2487         mark_dirty(svm->vmcb, VMCB_NPT);
2488         svm_flush_tlb(vcpu, true);
2489 }
2490
2491 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2492                                        struct x86_exception *fault)
2493 {
2494         struct vcpu_svm *svm = to_svm(vcpu);
2495
2496         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2497                 /*
2498                  * TODO: track the cause of the nested page fault, and
2499                  * correctly fill in the high bits of exit_info_1.
2500                  */
2501                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2502                 svm->vmcb->control.exit_code_hi = 0;
2503                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2504                 svm->vmcb->control.exit_info_2 = fault->address;
2505         }
2506
2507         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2508         svm->vmcb->control.exit_info_1 |= fault->error_code;
2509
2510         /*
2511          * The present bit is always zero for page structure faults on real
2512          * hardware.
2513          */
2514         if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2515                 svm->vmcb->control.exit_info_1 &= ~1;
2516
2517         nested_svm_vmexit(svm);
2518 }
2519
2520 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2521 {
2522         WARN_ON(mmu_is_nested(vcpu));
2523         kvm_init_shadow_mmu(vcpu);
2524         vcpu->arch.mmu.set_cr3           = nested_svm_set_tdp_cr3;
2525         vcpu->arch.mmu.get_cr3           = nested_svm_get_tdp_cr3;
2526         vcpu->arch.mmu.get_pdptr         = nested_svm_get_tdp_pdptr;
2527         vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2528         vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2529         reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2530         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
2531 }
2532
2533 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2534 {
2535         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2536 }
2537
2538 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2539 {
2540         if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2541             !is_paging(&svm->vcpu)) {
2542                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2543                 return 1;
2544         }
2545
2546         if (svm->vmcb->save.cpl) {
2547                 kvm_inject_gp(&svm->vcpu, 0);
2548                 return 1;
2549         }
2550
2551         return 0;
2552 }
2553
2554 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2555                                       bool has_error_code, u32 error_code)
2556 {
2557         int vmexit;
2558
2559         if (!is_guest_mode(&svm->vcpu))
2560                 return 0;
2561
2562         vmexit = nested_svm_intercept(svm);
2563         if (vmexit != NESTED_EXIT_DONE)
2564                 return 0;
2565
2566         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2567         svm->vmcb->control.exit_code_hi = 0;
2568         svm->vmcb->control.exit_info_1 = error_code;
2569
2570         /*
2571          * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2572          * The fix is to add the ancillary datum (CR2 or DR6) to structs
2573          * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2574          * written only when inject_pending_event runs (DR6 would written here
2575          * too).  This should be conditional on a new capability---if the
2576          * capability is disabled, kvm_multiple_exception would write the
2577          * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2578          */
2579         if (svm->vcpu.arch.exception.nested_apf)
2580                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2581         else
2582                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2583
2584         svm->nested.exit_required = true;
2585         return vmexit;
2586 }
2587
2588 /* This function returns true if it is save to enable the irq window */
2589 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2590 {
2591         if (!is_guest_mode(&svm->vcpu))
2592                 return true;
2593
2594         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2595                 return true;
2596
2597         if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2598                 return false;
2599
2600         /*
2601          * if vmexit was already requested (by intercepted exception
2602          * for instance) do not overwrite it with "external interrupt"
2603          * vmexit.
2604          */
2605         if (svm->nested.exit_required)
2606                 return false;
2607
2608         svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
2609         svm->vmcb->control.exit_info_1 = 0;
2610         svm->vmcb->control.exit_info_2 = 0;
2611
2612         if (svm->nested.intercept & 1ULL) {
2613                 /*
2614                  * The #vmexit can't be emulated here directly because this
2615                  * code path runs with irqs and preemption disabled. A
2616                  * #vmexit emulation might sleep. Only signal request for
2617                  * the #vmexit here.
2618                  */
2619                 svm->nested.exit_required = true;
2620                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2621                 return false;
2622         }
2623
2624         return true;
2625 }
2626
2627 /* This function returns true if it is save to enable the nmi window */
2628 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2629 {
2630         if (!is_guest_mode(&svm->vcpu))
2631                 return true;
2632
2633         if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2634                 return true;
2635
2636         svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2637         svm->nested.exit_required = true;
2638
2639         return false;
2640 }
2641
2642 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2643 {
2644         struct page *page;
2645
2646         might_sleep();
2647
2648         page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2649         if (is_error_page(page))
2650                 goto error;
2651
2652         *_page = page;
2653
2654         return kmap(page);
2655
2656 error:
2657         kvm_inject_gp(&svm->vcpu, 0);
2658
2659         return NULL;
2660 }
2661
2662 static void nested_svm_unmap(struct page *page)
2663 {
2664         kunmap(page);
2665         kvm_release_page_dirty(page);
2666 }
2667
2668 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2669 {
2670         unsigned port, size, iopm_len;
2671         u16 val, mask;
2672         u8 start_bit;
2673         u64 gpa;
2674
2675         if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2676                 return NESTED_EXIT_HOST;
2677
2678         port = svm->vmcb->control.exit_info_1 >> 16;
2679         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2680                 SVM_IOIO_SIZE_SHIFT;
2681         gpa  = svm->nested.vmcb_iopm + (port / 8);
2682         start_bit = port % 8;
2683         iopm_len = (start_bit + size > 8) ? 2 : 1;
2684         mask = (0xf >> (4 - size)) << start_bit;
2685         val = 0;
2686
2687         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2688                 return NESTED_EXIT_DONE;
2689
2690         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2691 }
2692
2693 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2694 {
2695         u32 offset, msr, value;
2696         int write, mask;
2697
2698         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2699                 return NESTED_EXIT_HOST;
2700
2701         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2702         offset = svm_msrpm_offset(msr);
2703         write  = svm->vmcb->control.exit_info_1 & 1;
2704         mask   = 1 << ((2 * (msr & 0xf)) + write);
2705
2706         if (offset == MSR_INVALID)
2707                 return NESTED_EXIT_DONE;
2708
2709         /* Offset is in 32 bit units but need in 8 bit units */
2710         offset *= 4;
2711
2712         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
2713                 return NESTED_EXIT_DONE;
2714
2715         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2716 }
2717
2718 /* DB exceptions for our internal use must not cause vmexit */
2719 static int nested_svm_intercept_db(struct vcpu_svm *svm)
2720 {
2721         unsigned long dr6;
2722
2723         /* if we're not singlestepping, it's not ours */
2724         if (!svm->nmi_singlestep)
2725                 return NESTED_EXIT_DONE;
2726
2727         /* if it's not a singlestep exception, it's not ours */
2728         if (kvm_get_dr(&svm->vcpu, 6, &dr6))
2729                 return NESTED_EXIT_DONE;
2730         if (!(dr6 & DR6_BS))
2731                 return NESTED_EXIT_DONE;
2732
2733         /* if the guest is singlestepping, it should get the vmexit */
2734         if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
2735                 disable_nmi_singlestep(svm);
2736                 return NESTED_EXIT_DONE;
2737         }
2738
2739         /* it's ours, the nested hypervisor must not see this one */
2740         return NESTED_EXIT_HOST;
2741 }
2742
2743 static int nested_svm_exit_special(struct vcpu_svm *svm)
2744 {
2745         u32 exit_code = svm->vmcb->control.exit_code;
2746
2747         switch (exit_code) {
2748         case SVM_EXIT_INTR:
2749         case SVM_EXIT_NMI:
2750         case SVM_EXIT_EXCP_BASE + MC_VECTOR:
2751                 return NESTED_EXIT_HOST;
2752         case SVM_EXIT_NPF:
2753                 /* For now we are always handling NPFs when using them */
2754                 if (npt_enabled)
2755                         return NESTED_EXIT_HOST;
2756                 break;
2757         case SVM_EXIT_EXCP_BASE + PF_VECTOR:
2758                 /* Trap async PF even if not shadowing */
2759                 if (!npt_enabled || svm->vcpu.arch.apf.host_apf_reason)
2760                         return NESTED_EXIT_HOST;
2761                 break;
2762         default:
2763                 break;
2764         }
2765
2766         return NESTED_EXIT_CONTINUE;
2767 }
2768
2769 /*
2770  * If this function returns true, this #vmexit was already handled
2771  */
2772 static int nested_svm_intercept(struct vcpu_svm *svm)
2773 {
2774         u32 exit_code = svm->vmcb->control.exit_code;
2775         int vmexit = NESTED_EXIT_HOST;
2776
2777         switch (exit_code) {
2778         case SVM_EXIT_MSR:
2779                 vmexit = nested_svm_exit_handled_msr(svm);
2780                 break;
2781         case SVM_EXIT_IOIO:
2782                 vmexit = nested_svm_intercept_ioio(svm);
2783                 break;
2784         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
2785                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
2786                 if (svm->nested.intercept_cr & bit)
2787                         vmexit = NESTED_EXIT_DONE;
2788                 break;
2789         }
2790         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
2791                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
2792                 if (svm->nested.intercept_dr & bit)
2793                         vmexit = NESTED_EXIT_DONE;
2794                 break;
2795         }
2796         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
2797                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
2798                 if (svm->nested.intercept_exceptions & excp_bits) {
2799                         if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
2800                                 vmexit = nested_svm_intercept_db(svm);
2801                         else
2802                                 vmexit = NESTED_EXIT_DONE;
2803                 }
2804                 /* async page fault always cause vmexit */
2805                 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
2806                          svm->vcpu.arch.exception.nested_apf != 0)
2807                         vmexit = NESTED_EXIT_DONE;
2808                 break;
2809         }
2810         case SVM_EXIT_ERR: {
2811                 vmexit = NESTED_EXIT_DONE;
2812                 break;
2813         }
2814         default: {
2815                 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
2816                 if (svm->nested.intercept & exit_bits)
2817                         vmexit = NESTED_EXIT_DONE;
2818         }
2819         }
2820
2821         return vmexit;
2822 }
2823
2824 static int nested_svm_exit_handled(struct vcpu_svm *svm)
2825 {
2826         int vmexit;
2827
2828         vmexit = nested_svm_intercept(svm);
2829
2830         if (vmexit == NESTED_EXIT_DONE)
2831                 nested_svm_vmexit(svm);
2832
2833         return vmexit;
2834 }
2835
2836 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
2837 {
2838         struct vmcb_control_area *dst  = &dst_vmcb->control;
2839         struct vmcb_control_area *from = &from_vmcb->control;
2840
2841         dst->intercept_cr         = from->intercept_cr;
2842         dst->intercept_dr         = from->intercept_dr;
2843         dst->intercept_exceptions = from->intercept_exceptions;
2844         dst->intercept            = from->intercept;
2845         dst->iopm_base_pa         = from->iopm_base_pa;
2846         dst->msrpm_base_pa        = from->msrpm_base_pa;
2847         dst->tsc_offset           = from->tsc_offset;
2848         /* asid not copied, it is handled manually for svm->vmcb.  */
2849         dst->tlb_ctl              = from->tlb_ctl;
2850         dst->int_ctl              = from->int_ctl;
2851         dst->int_vector           = from->int_vector;
2852         dst->int_state            = from->int_state;
2853         dst->exit_code            = from->exit_code;
2854         dst->exit_code_hi         = from->exit_code_hi;
2855         dst->exit_info_1          = from->exit_info_1;
2856         dst->exit_info_2          = from->exit_info_2;
2857         dst->exit_int_info        = from->exit_int_info;
2858         dst->exit_int_info_err    = from->exit_int_info_err;
2859         dst->nested_ctl           = from->nested_ctl;
2860         dst->event_inj            = from->event_inj;
2861         dst->event_inj_err        = from->event_inj_err;
2862         dst->nested_cr3           = from->nested_cr3;
2863         dst->virt_ext              = from->virt_ext;
2864 }
2865
2866 static int nested_svm_vmexit(struct vcpu_svm *svm)
2867 {
2868         struct vmcb *nested_vmcb;
2869         struct vmcb *hsave = svm->nested.hsave;
2870         struct vmcb *vmcb = svm->vmcb;
2871         struct page *page;
2872
2873         trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
2874                                        vmcb->control.exit_info_1,
2875                                        vmcb->control.exit_info_2,
2876                                        vmcb->control.exit_int_info,
2877                                        vmcb->control.exit_int_info_err,
2878                                        KVM_ISA_SVM);
2879
2880         nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
2881         if (!nested_vmcb)
2882                 return 1;
2883
2884         /* Exit Guest-Mode */
2885         leave_guest_mode(&svm->vcpu);
2886         svm->nested.vmcb = 0;
2887
2888         /* Give the current vmcb to the guest */
2889         disable_gif(svm);
2890
2891         nested_vmcb->save.es     = vmcb->save.es;
2892         nested_vmcb->save.cs     = vmcb->save.cs;
2893         nested_vmcb->save.ss     = vmcb->save.ss;
2894         nested_vmcb->save.ds     = vmcb->save.ds;
2895         nested_vmcb->save.gdtr   = vmcb->save.gdtr;
2896         nested_vmcb->save.idtr   = vmcb->save.idtr;
2897         nested_vmcb->save.efer   = svm->vcpu.arch.efer;
2898         nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
2899         nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
2900         nested_vmcb->save.cr2    = vmcb->save.cr2;
2901         nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
2902         nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
2903         nested_vmcb->save.rip    = vmcb->save.rip;
2904         nested_vmcb->save.rsp    = vmcb->save.rsp;
2905         nested_vmcb->save.rax    = vmcb->save.rax;
2906         nested_vmcb->save.dr7    = vmcb->save.dr7;
2907         nested_vmcb->save.dr6    = vmcb->save.dr6;
2908         nested_vmcb->save.cpl    = vmcb->save.cpl;
2909
2910         nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
2911         nested_vmcb->control.int_vector        = vmcb->control.int_vector;
2912         nested_vmcb->control.int_state         = vmcb->control.int_state;
2913         nested_vmcb->control.exit_code         = vmcb->control.exit_code;
2914         nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
2915         nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
2916         nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
2917         nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
2918         nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
2919
2920         if (svm->nrips_enabled)
2921                 nested_vmcb->control.next_rip  = vmcb->control.next_rip;
2922
2923         /*
2924          * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
2925          * to make sure that we do not lose injected events. So check event_inj
2926          * here and copy it to exit_int_info if it is valid.
2927          * Exit_int_info and event_inj can't be both valid because the case
2928          * below only happens on a VMRUN instruction intercept which has
2929          * no valid exit_int_info set.
2930          */
2931         if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
2932                 struct vmcb_control_area *nc = &nested_vmcb->control;
2933
2934                 nc->exit_int_info     = vmcb->control.event_inj;
2935                 nc->exit_int_info_err = vmcb->control.event_inj_err;
2936         }
2937
2938         nested_vmcb->control.tlb_ctl           = 0;
2939         nested_vmcb->control.event_inj         = 0;
2940         nested_vmcb->control.event_inj_err     = 0;
2941
2942         /* We always set V_INTR_MASKING and remember the old value in hflags */
2943         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2944                 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
2945
2946         /* Restore the original control entries */
2947         copy_vmcb_control_area(vmcb, hsave);
2948
2949         kvm_clear_exception_queue(&svm->vcpu);
2950         kvm_clear_interrupt_queue(&svm->vcpu);
2951
2952         svm->nested.nested_cr3 = 0;
2953
2954         /* Restore selected save entries */
2955         svm->vmcb->save.es = hsave->save.es;
2956         svm->vmcb->save.cs = hsave->save.cs;
2957         svm->vmcb->save.ss = hsave->save.ss;
2958         svm->vmcb->save.ds = hsave->save.ds;
2959         svm->vmcb->save.gdtr = hsave->save.gdtr;
2960         svm->vmcb->save.idtr = hsave->save.idtr;
2961         kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
2962         svm_set_efer(&svm->vcpu, hsave->save.efer);
2963         svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
2964         svm_set_cr4(&svm->vcpu, hsave->save.cr4);
2965         if (npt_enabled) {
2966                 svm->vmcb->save.cr3 = hsave->save.cr3;
2967                 svm->vcpu.arch.cr3 = hsave->save.cr3;
2968         } else {
2969                 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
2970         }
2971         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
2972         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
2973         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
2974         svm->vmcb->save.dr7 = 0;
2975         svm->vmcb->save.cpl = 0;
2976         svm->vmcb->control.exit_int_info = 0;
2977
2978         mark_all_dirty(svm->vmcb);
2979
2980         nested_svm_unmap(page);
2981
2982         nested_svm_uninit_mmu_context(&svm->vcpu);
2983         kvm_mmu_reset_context(&svm->vcpu);
2984         kvm_mmu_load(&svm->vcpu);
2985
2986         /*
2987          * Drop what we picked up for L2 via svm_complete_interrupts() so it
2988          * doesn't end up in L1.
2989          */
2990         svm->vcpu.arch.nmi_injected = false;
2991         kvm_clear_exception_queue(&svm->vcpu);
2992         kvm_clear_interrupt_queue(&svm->vcpu);
2993
2994         return 0;
2995 }
2996
2997 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
2998 {
2999         /*
3000          * This function merges the msr permission bitmaps of kvm and the
3001          * nested vmcb. It is optimized in that it only merges the parts where
3002          * the kvm msr permission bitmap may contain zero bits
3003          */
3004         int i;
3005
3006         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3007                 return true;
3008
3009         for (i = 0; i < MSRPM_OFFSETS; i++) {
3010                 u32 value, p;
3011                 u64 offset;
3012
3013                 if (msrpm_offsets[i] == 0xffffffff)
3014                         break;
3015
3016                 p      = msrpm_offsets[i];
3017                 offset = svm->nested.vmcb_msrpm + (p * 4);
3018
3019                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3020                         return false;
3021
3022                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3023         }
3024
3025         svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3026
3027         return true;
3028 }
3029
3030 static bool nested_vmcb_checks(struct vmcb *vmcb)
3031 {
3032         if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3033                 return false;
3034
3035         if (vmcb->control.asid == 0)
3036                 return false;
3037
3038         if (vmcb->control.nested_ctl && !npt_enabled)
3039                 return false;
3040
3041         return true;
3042 }
3043
3044 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3045 {
3046         struct vmcb *nested_vmcb;
3047         struct vmcb *hsave = svm->nested.hsave;
3048         struct vmcb *vmcb = svm->vmcb;
3049         struct page *page;
3050         u64 vmcb_gpa;
3051
3052         vmcb_gpa = svm->vmcb->save.rax;
3053
3054         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3055         if (!nested_vmcb)
3056                 return false;
3057
3058         if (!nested_vmcb_checks(nested_vmcb)) {
3059                 nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
3060                 nested_vmcb->control.exit_code_hi = 0;
3061                 nested_vmcb->control.exit_info_1  = 0;
3062                 nested_vmcb->control.exit_info_2  = 0;
3063
3064                 nested_svm_unmap(page);
3065
3066                 return false;
3067         }
3068
3069         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3070                                nested_vmcb->save.rip,
3071                                nested_vmcb->control.int_ctl,
3072                                nested_vmcb->control.event_inj,
3073                                nested_vmcb->control.nested_ctl);
3074
3075         trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3076                                     nested_vmcb->control.intercept_cr >> 16,
3077                                     nested_vmcb->control.intercept_exceptions,
3078                                     nested_vmcb->control.intercept);
3079
3080         /* Clear internal status */
3081         kvm_clear_exception_queue(&svm->vcpu);
3082         kvm_clear_interrupt_queue(&svm->vcpu);
3083
3084         /*
3085          * Save the old vmcb, so we don't need to pick what we save, but can
3086          * restore everything when a VMEXIT occurs
3087          */
3088         hsave->save.es     = vmcb->save.es;
3089         hsave->save.cs     = vmcb->save.cs;
3090         hsave->save.ss     = vmcb->save.ss;
3091         hsave->save.ds     = vmcb->save.ds;
3092         hsave->save.gdtr   = vmcb->save.gdtr;
3093         hsave->save.idtr   = vmcb->save.idtr;
3094         hsave->save.efer   = svm->vcpu.arch.efer;
3095         hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
3096         hsave->save.cr4    = svm->vcpu.arch.cr4;
3097         hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3098         hsave->save.rip    = kvm_rip_read(&svm->vcpu);
3099         hsave->save.rsp    = vmcb->save.rsp;
3100         hsave->save.rax    = vmcb->save.rax;
3101         if (npt_enabled)
3102                 hsave->save.cr3    = vmcb->save.cr3;
3103         else
3104                 hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
3105
3106         copy_vmcb_control_area(hsave, vmcb);
3107
3108         if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3109                 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3110         else
3111                 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3112
3113         if (nested_vmcb->control.nested_ctl) {
3114                 kvm_mmu_unload(&svm->vcpu);
3115                 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3116                 nested_svm_init_mmu_context(&svm->vcpu);
3117         }
3118
3119         /* Load the nested guest state */
3120         svm->vmcb->save.es = nested_vmcb->save.es;
3121         svm->vmcb->save.cs = nested_vmcb->save.cs;
3122         svm->vmcb->save.ss = nested_vmcb->save.ss;
3123         svm->vmcb->save.ds = nested_vmcb->save.ds;
3124         svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3125         svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3126         kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3127         svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3128         svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3129         svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3130         if (npt_enabled) {
3131                 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3132                 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3133         } else
3134                 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3135
3136         /* Guest paging mode is active - reset mmu */
3137         kvm_mmu_reset_context(&svm->vcpu);
3138
3139         svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3140         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3141         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3142         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3143
3144         /* In case we don't even reach vcpu_run, the fields are not updated */
3145         svm->vmcb->save.rax = nested_vmcb->save.rax;
3146         svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3147         svm->vmcb->save.rip = nested_vmcb->save.rip;
3148         svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3149         svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3150         svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3151
3152         svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3153         svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
3154
3155         /* cache intercepts */
3156         svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
3157         svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
3158         svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3159         svm->nested.intercept            = nested_vmcb->control.intercept;
3160
3161         svm_flush_tlb(&svm->vcpu, true);
3162
3163         svm->vmcb->control.int_ctl &=
3164                         V_INTR_MASKING_MASK | V_GIF_ENABLE_MASK | V_GIF_MASK;
3165
3166         svm->vmcb->control.int_ctl |= nested_vmcb->control.int_ctl &
3167                         (V_TPR_MASK | V_IRQ_INJECTION_BITS_MASK);
3168
3169         if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3170                 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3171         else
3172                 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3173
3174         if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3175                 /* We only want the cr8 intercept bits of the guest */
3176                 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3177                 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3178         }
3179
3180         /* We don't want to see VMMCALLs from a nested guest */
3181         clr_intercept(svm, INTERCEPT_VMMCALL);
3182
3183         svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3184         svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3185         svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3186         svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
3187         svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3188         svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3189
3190         nested_svm_unmap(page);
3191
3192         /* Enter Guest-Mode */
3193         enter_guest_mode(&svm->vcpu);
3194
3195         /*
3196          * Merge guest and host intercepts - must be called  with vcpu in
3197          * guest-mode to take affect here
3198          */
3199         recalc_intercepts(svm);
3200
3201         svm->nested.vmcb = vmcb_gpa;
3202
3203         enable_gif(svm);
3204
3205         mark_all_dirty(svm->vmcb);
3206
3207         return true;
3208 }
3209
3210 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3211 {
3212         to_vmcb->save.fs = from_vmcb->save.fs;
3213         to_vmcb->save.gs = from_vmcb->save.gs;
3214         to_vmcb->save.tr = from_vmcb->save.tr;
3215         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3216         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3217         to_vmcb->save.star = from_vmcb->save.star;
3218         to_vmcb->save.lstar = from_vmcb->save.lstar;
3219         to_vmcb->save.cstar = from_vmcb->save.cstar;
3220         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3221         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3222         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3223         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3224 }
3225
3226 static int vmload_interception(struct vcpu_svm *svm)
3227 {
3228         struct vmcb *nested_vmcb;
3229         struct page *page;
3230         int ret;
3231
3232         if (nested_svm_check_permissions(svm))
3233                 return 1;
3234
3235         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3236         if (!nested_vmcb)
3237                 return 1;
3238
3239         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3240         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3241
3242         nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3243         nested_svm_unmap(page);
3244
3245         return ret;
3246 }
3247
3248 static int vmsave_interception(struct vcpu_svm *svm)
3249 {
3250         struct vmcb *nested_vmcb;
3251         struct page *page;
3252         int ret;
3253
3254         if (nested_svm_check_permissions(svm))
3255                 return 1;
3256
3257         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3258         if (!nested_vmcb)
3259                 return 1;
3260
3261         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3262         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3263
3264         nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3265         nested_svm_unmap(page);
3266
3267         return ret;
3268 }
3269
3270 static int vmrun_interception(struct vcpu_svm *svm)
3271 {
3272         if (nested_svm_check_permissions(svm))
3273                 return 1;
3274
3275         /* Save rip after vmrun instruction */
3276         kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3277
3278         if (!nested_svm_vmrun(svm))
3279                 return 1;
3280
3281         if (!nested_svm_vmrun_msrpm(svm))
3282                 goto failed;
3283
3284         return 1;
3285
3286 failed:
3287
3288         svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
3289         svm->vmcb->control.exit_code_hi = 0;
3290         svm->vmcb->control.exit_info_1  = 0;
3291         svm->vmcb->control.exit_info_2  = 0;
3292
3293         nested_svm_vmexit(svm);
3294
3295         return 1;
3296 }
3297
3298 static int stgi_interception(struct vcpu_svm *svm)
3299 {
3300         int ret;
3301
3302         if (nested_svm_check_permissions(svm))
3303                 return 1;
3304
3305         /*
3306          * If VGIF is enabled, the STGI intercept is only added to
3307          * detect the opening of the NMI window; remove it now.
3308          */
3309         if (vgif_enabled(svm))
3310                 clr_intercept(svm, INTERCEPT_STGI);
3311
3312         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3313         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3314         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3315
3316         enable_gif(svm);
3317
3318         return ret;
3319 }
3320
3321 static int clgi_interception(struct vcpu_svm *svm)
3322 {
3323         int ret;
3324
3325         if (nested_svm_check_permissions(svm))
3326                 return 1;
3327
3328         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3329         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3330
3331         disable_gif(svm);
3332
3333         /* After a CLGI no interrupts should come */
3334         if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3335                 svm_clear_vintr(svm);
3336                 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3337                 mark_dirty(svm->vmcb, VMCB_INTR);
3338         }
3339
3340         return ret;
3341 }
3342
3343 static int invlpga_interception(struct vcpu_svm *svm)
3344 {
3345         struct kvm_vcpu *vcpu = &svm->vcpu;
3346
3347         trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3348                           kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3349
3350         /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3351         kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3352
3353         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3354         return kvm_skip_emulated_instruction(&svm->vcpu);
3355 }
3356
3357 static int skinit_interception(struct vcpu_svm *svm)
3358 {
3359         trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3360
3361         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3362         return 1;
3363 }
3364
3365 static int wbinvd_interception(struct vcpu_svm *svm)
3366 {
3367         return kvm_emulate_wbinvd(&svm->vcpu);
3368 }
3369
3370 static int xsetbv_interception(struct vcpu_svm *svm)
3371 {
3372         u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3373         u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3374
3375         if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3376                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3377                 return kvm_skip_emulated_instruction(&svm->vcpu);
3378         }
3379
3380         return 1;
3381 }
3382
3383 static int task_switch_interception(struct vcpu_svm *svm)
3384 {
3385         u16 tss_selector;
3386         int reason;
3387         int int_type = svm->vmcb->control.exit_int_info &
3388                 SVM_EXITINTINFO_TYPE_MASK;
3389         int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3390         uint32_t type =
3391                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3392         uint32_t idt_v =
3393                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3394         bool has_error_code = false;
3395         u32 error_code = 0;
3396
3397         tss_selector = (u16)svm->vmcb->control.exit_info_1;
3398
3399         if (svm->vmcb->control.exit_info_2 &
3400             (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3401                 reason = TASK_SWITCH_IRET;
3402         else if (svm->vmcb->control.exit_info_2 &
3403                  (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3404                 reason = TASK_SWITCH_JMP;
3405         else if (idt_v)
3406                 reason = TASK_SWITCH_GATE;
3407         else
3408                 reason = TASK_SWITCH_CALL;
3409
3410         if (reason == TASK_SWITCH_GATE) {
3411                 switch (type) {
3412                 case SVM_EXITINTINFO_TYPE_NMI:
3413                         svm->vcpu.arch.nmi_injected = false;
3414                         break;
3415                 case SVM_EXITINTINFO_TYPE_EXEPT:
3416                         if (svm->vmcb->control.exit_info_2 &
3417                             (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3418                                 has_error_code = true;
3419                                 error_code =
3420                                         (u32)svm->vmcb->control.exit_info_2;
3421                         }
3422                         kvm_clear_exception_queue(&svm->vcpu);
3423                         break;
3424                 case SVM_EXITINTINFO_TYPE_INTR:
3425                         kvm_clear_interrupt_queue(&svm->vcpu);
3426                         break;
3427                 default:
3428                         break;
3429                 }
3430         }
3431
3432         if (reason != TASK_SWITCH_GATE ||
3433             int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3434             (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3435              (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3436                 skip_emulated_instruction(&svm->vcpu);
3437
3438         if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3439                 int_vec = -1;
3440
3441         if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3442                                 has_error_code, error_code) == EMULATE_FAIL) {
3443                 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3444                 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3445                 svm->vcpu.run->internal.ndata = 0;
3446                 return 0;
3447         }
3448         return 1;
3449 }
3450
3451 static int cpuid_interception(struct vcpu_svm *svm)
3452 {
3453         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3454         return kvm_emulate_cpuid(&svm->vcpu);
3455 }
3456
3457 static int iret_interception(struct vcpu_svm *svm)
3458 {
3459         ++svm->vcpu.stat.nmi_window_exits;
3460         clr_intercept(svm, INTERCEPT_IRET);
3461         svm->vcpu.arch.hflags |= HF_IRET_MASK;
3462         svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3463         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3464         return 1;
3465 }
3466
3467 static int invlpg_interception(struct vcpu_svm *svm)
3468 {
3469         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3470                 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3471
3472         kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3473         return kvm_skip_emulated_instruction(&svm->vcpu);
3474 }
3475
3476 static int emulate_on_interception(struct vcpu_svm *svm)
3477 {
3478         return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3479 }
3480
3481 static int rdpmc_interception(struct vcpu_svm *svm)
3482 {
3483         int err;
3484
3485         if (!static_cpu_has(X86_FEATURE_NRIPS))
3486                 return emulate_on_interception(svm);
3487
3488         err = kvm_rdpmc(&svm->vcpu);
3489         return kvm_complete_insn_gp(&svm->vcpu, err);
3490 }
3491
3492 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3493                                             unsigned long val)
3494 {
3495         unsigned long cr0 = svm->vcpu.arch.cr0;
3496         bool ret = false;
3497         u64 intercept;
3498
3499         intercept = svm->nested.intercept;
3500
3501         if (!is_guest_mode(&svm->vcpu) ||
3502             (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3503                 return false;
3504
3505         cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3506         val &= ~SVM_CR0_SELECTIVE_MASK;
3507
3508         if (cr0 ^ val) {
3509                 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3510                 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3511         }
3512
3513         return ret;
3514 }
3515
3516 #define CR_VALID (1ULL << 63)
3517
3518 static int cr_interception(struct vcpu_svm *svm)
3519 {
3520         int reg, cr;
3521         unsigned long val;
3522         int err;
3523
3524         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3525                 return emulate_on_interception(svm);
3526
3527         if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3528                 return emulate_on_interception(svm);
3529
3530         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3531         if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3532                 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3533         else
3534                 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3535
3536         err = 0;
3537         if (cr >= 16) { /* mov to cr */
3538                 cr -= 16;
3539                 val = kvm_register_readl(&svm->vcpu, reg);
3540                 switch (cr) {
3541                 case 0:
3542                         if (!check_selective_cr0_intercepted(svm, val))
3543                                 err = kvm_set_cr0(&svm->vcpu, val);
3544                         else
3545                                 return 1;
3546
3547                         break;
3548                 case 3:
3549                         err = kvm_set_cr3(&svm->vcpu, val);
3550                         break;
3551                 case 4:
3552                         err = kvm_set_cr4(&svm->vcpu, val);
3553                         break;
3554                 case 8:
3555                         err = kvm_set_cr8(&svm->vcpu, val);
3556                         break;
3557                 default:
3558                         WARN(1, "unhandled write to CR%d", cr);
3559                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3560                         return 1;
3561                 }
3562         } else { /* mov from cr */
3563                 switch (cr) {
3564                 case 0:
3565                         val = kvm_read_cr0(&svm->vcpu);
3566                         break;
3567                 case 2:
3568                         val = svm->vcpu.arch.cr2;
3569                         break;
3570                 case 3:
3571                         val = kvm_read_cr3(&svm->vcpu);
3572                         break;
3573                 case 4:
3574                         val = kvm_read_cr4(&svm->vcpu);
3575                         break;
3576                 case 8:
3577                         val = kvm_get_cr8(&svm->vcpu);
3578                         break;
3579                 default:
3580                         WARN(1, "unhandled read from CR%d", cr);
3581                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3582                         return 1;
3583                 }
3584                 kvm_register_writel(&svm->vcpu, reg, val);
3585         }
3586         return kvm_complete_insn_gp(&svm->vcpu, err);
3587 }
3588
3589 static int dr_interception(struct vcpu_svm *svm)
3590 {
3591         int reg, dr;
3592         unsigned long val;
3593
3594         if (svm->vcpu.guest_debug == 0) {
3595                 /*
3596                  * No more DR vmexits; force a reload of the debug registers
3597                  * and reenter on this instruction.  The next vmexit will
3598                  * retrieve the full state of the debug registers.
3599                  */
3600                 clr_dr_intercepts(svm);
3601                 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
3602                 return 1;
3603         }
3604
3605         if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
3606                 return emulate_on_interception(svm);
3607
3608         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3609         dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3610
3611         if (dr >= 16) { /* mov to DRn */
3612                 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3613                         return 1;
3614                 val = kvm_register_readl(&svm->vcpu, reg);
3615                 kvm_set_dr(&svm->vcpu, dr - 16, val);
3616         } else {
3617                 if (!kvm_require_dr(&svm->vcpu, dr))
3618                         return 1;
3619                 kvm_get_dr(&svm->vcpu, dr, &val);
3620                 kvm_register_writel(&svm->vcpu, reg, val);
3621         }
3622
3623         return kvm_skip_emulated_instruction(&svm->vcpu);
3624 }
3625
3626 static int cr8_write_interception(struct vcpu_svm *svm)
3627 {
3628         struct kvm_run *kvm_run = svm->vcpu.run;
3629         int r;
3630
3631         u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3632         /* instruction emulation calls kvm_set_cr8() */
3633         r = cr_interception(svm);
3634         if (lapic_in_kernel(&svm->vcpu))
3635                 return r;
3636         if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3637                 return r;
3638         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3639         return 0;
3640 }
3641
3642 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
3643 {
3644         msr->data = 0;
3645
3646         switch (msr->index) {
3647         case MSR_F10H_DECFG:
3648                 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
3649                         msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
3650                 break;
3651         default:
3652                 return 1;
3653         }
3654
3655         return 0;
3656 }
3657
3658 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3659 {
3660         struct vcpu_svm *svm = to_svm(vcpu);
3661
3662         switch (msr_info->index) {
3663         case MSR_IA32_TSC: {
3664                 msr_info->data = svm->vmcb->control.tsc_offset +
3665                         kvm_scale_tsc(vcpu, rdtsc());
3666
3667                 break;
3668         }
3669         case MSR_STAR:
3670                 msr_info->data = svm->vmcb->save.star;
3671                 break;
3672 #ifdef CONFIG_X86_64
3673         case MSR_LSTAR:
3674                 msr_info->data = svm->vmcb->save.lstar;
3675                 break;
3676         case MSR_CSTAR:
3677                 msr_info->data = svm->vmcb->save.cstar;
3678                 break;
3679         case MSR_KERNEL_GS_BASE:
3680                 msr_info->data = svm->vmcb->save.kernel_gs_base;
3681                 break;
3682         case MSR_SYSCALL_MASK:
3683                 msr_info->data = svm->vmcb->save.sfmask;
3684                 break;
3685 #endif
3686         case MSR_IA32_SYSENTER_CS:
3687                 msr_info->data = svm->vmcb->save.sysenter_cs;
3688                 break;
3689         case MSR_IA32_SYSENTER_EIP:
3690                 msr_info->data = svm->sysenter_eip;
3691                 break;
3692         case MSR_IA32_SYSENTER_ESP:
3693                 msr_info->data = svm->sysenter_esp;
3694                 break;
3695         case MSR_TSC_AUX:
3696                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3697                         return 1;
3698                 msr_info->data = svm->tsc_aux;
3699                 break;
3700         /*
3701          * Nobody will change the following 5 values in the VMCB so we can
3702          * safely return them on rdmsr. They will always be 0 until LBRV is
3703          * implemented.
3704          */
3705         case MSR_IA32_DEBUGCTLMSR:
3706                 msr_info->data = svm->vmcb->save.dbgctl;
3707                 break;
3708         case MSR_IA32_LASTBRANCHFROMIP:
3709                 msr_info->data = svm->vmcb->save.br_from;
3710                 break;
3711         case MSR_IA32_LASTBRANCHTOIP:
3712                 msr_info->data = svm->vmcb->save.br_to;
3713                 break;
3714         case MSR_IA32_LASTINTFROMIP:
3715                 msr_info->data = svm->vmcb->save.last_excp_from;
3716                 break;
3717         case MSR_IA32_LASTINTTOIP:
3718                 msr_info->data = svm->vmcb->save.last_excp_to;
3719                 break;
3720         case MSR_VM_HSAVE_PA:
3721                 msr_info->data = svm->nested.hsave_msr;
3722                 break;
3723         case MSR_VM_CR:
3724                 msr_info->data = svm->nested.vm_cr_msr;
3725                 break;
3726         case MSR_IA32_SPEC_CTRL:
3727                 if (!msr_info->host_initiated &&
3728                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
3729                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
3730                         return 1;
3731
3732                 msr_info->data = svm->spec_ctrl;
3733                 break;
3734         case MSR_AMD64_VIRT_SPEC_CTRL:
3735                 if (!msr_info->host_initiated &&
3736                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
3737                         return 1;
3738
3739                 msr_info->data = svm->virt_spec_ctrl;
3740                 break;
3741         case MSR_F15H_IC_CFG: {
3742
3743                 int family, model;
3744
3745                 family = guest_cpuid_family(vcpu);
3746                 model  = guest_cpuid_model(vcpu);
3747
3748                 if (family < 0 || model < 0)
3749                         return kvm_get_msr_common(vcpu, msr_info);
3750
3751                 msr_info->data = 0;
3752
3753                 if (family == 0x15 &&
3754                     (model >= 0x2 && model < 0x20))
3755                         msr_info->data = 0x1E;
3756                 }
3757                 break;
3758         case MSR_F10H_DECFG:
3759                 msr_info->data = svm->msr_decfg;
3760                 break;
3761         default:
3762                 return kvm_get_msr_common(vcpu, msr_info);
3763         }
3764         return 0;
3765 }
3766
3767 static int rdmsr_interception(struct vcpu_svm *svm)
3768 {
3769         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3770         struct msr_data msr_info;
3771
3772         msr_info.index = ecx;
3773         msr_info.host_initiated = false;
3774         if (svm_get_msr(&svm->vcpu, &msr_info)) {
3775                 trace_kvm_msr_read_ex(ecx);
3776                 kvm_inject_gp(&svm->vcpu, 0);
3777                 return 1;
3778         } else {
3779                 trace_kvm_msr_read(ecx, msr_info.data);
3780
3781                 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
3782                                    msr_info.data & 0xffffffff);
3783                 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
3784                                    msr_info.data >> 32);
3785                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3786                 return kvm_skip_emulated_instruction(&svm->vcpu);
3787         }
3788 }
3789
3790 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
3791 {
3792         struct vcpu_svm *svm = to_svm(vcpu);
3793         int svm_dis, chg_mask;
3794
3795         if (data & ~SVM_VM_CR_VALID_MASK)
3796                 return 1;
3797
3798         chg_mask = SVM_VM_CR_VALID_MASK;
3799
3800         if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
3801                 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
3802
3803         svm->nested.vm_cr_msr &= ~chg_mask;
3804         svm->nested.vm_cr_msr |= (data & chg_mask);
3805
3806         svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
3807
3808         /* check for svm_disable while efer.svme is set */
3809         if (svm_dis && (vcpu->arch.efer & EFER_SVME))
3810                 return 1;
3811
3812         return 0;
3813 }
3814
3815 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
3816 {
3817         struct vcpu_svm *svm = to_svm(vcpu);
3818
3819         u32 ecx = msr->index;
3820         u64 data = msr->data;
3821         switch (ecx) {
3822         case MSR_IA32_CR_PAT:
3823                 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3824                         return 1;
3825                 vcpu->arch.pat = data;
3826                 svm->vmcb->save.g_pat = data;
3827                 mark_dirty(svm->vmcb, VMCB_NPT);
3828                 break;
3829         case MSR_IA32_TSC:
3830                 kvm_write_tsc(vcpu, msr);
3831                 break;
3832         case MSR_IA32_SPEC_CTRL:
3833                 if (!msr->host_initiated &&
3834                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
3835                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
3836                         return 1;
3837
3838                 /* The STIBP bit doesn't fault even if it's not advertised */
3839                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3840                         return 1;
3841
3842                 svm->spec_ctrl = data;
3843
3844                 if (!data)
3845                         break;
3846
3847                 /*
3848                  * For non-nested:
3849                  * When it's written (to non-zero) for the first time, pass
3850                  * it through.
3851                  *
3852                  * For nested:
3853                  * The handling of the MSR bitmap for L2 guests is done in
3854                  * nested_svm_vmrun_msrpm.
3855                  * We update the L1 MSR bit as well since it will end up
3856                  * touching the MSR anyway now.
3857                  */
3858                 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
3859                 break;
3860         case MSR_IA32_PRED_CMD:
3861                 if (!msr->host_initiated &&
3862                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
3863                         return 1;
3864
3865                 if (data & ~PRED_CMD_IBPB)
3866                         return 1;
3867
3868                 if (!data)
3869                         break;
3870
3871                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3872                 if (is_guest_mode(vcpu))
3873                         break;
3874                 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
3875                 break;
3876         case MSR_AMD64_VIRT_SPEC_CTRL:
3877                 if (!msr->host_initiated &&
3878                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
3879                         return 1;
3880
3881                 if (data & ~SPEC_CTRL_SSBD)
3882                         return 1;
3883
3884                 svm->virt_spec_ctrl = data;
3885                 break;
3886         case MSR_STAR:
3887                 svm->vmcb->save.star = data;
3888                 break;
3889 #ifdef CONFIG_X86_64
3890         case MSR_LSTAR:
3891                 svm->vmcb->save.lstar = data;
3892                 break;
3893         case MSR_CSTAR:
3894                 svm->vmcb->save.cstar = data;
3895                 break;
3896         case MSR_KERNEL_GS_BASE:
3897                 svm->vmcb->save.kernel_gs_base = data;
3898                 break;
3899         case MSR_SYSCALL_MASK:
3900                 svm->vmcb->save.sfmask = data;
3901                 break;
3902 #endif
3903         case MSR_IA32_SYSENTER_CS:
3904                 svm->vmcb->save.sysenter_cs = data;
3905                 break;
3906         case MSR_IA32_SYSENTER_EIP:
3907                 svm->sysenter_eip = data;
3908                 svm->vmcb->save.sysenter_eip = data;
3909                 break;
3910         case MSR_IA32_SYSENTER_ESP:
3911                 svm->sysenter_esp = data;
3912                 svm->vmcb->save.sysenter_esp = data;
3913                 break;
3914         case MSR_TSC_AUX:
3915                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3916                         return 1;
3917
3918                 /*
3919                  * This is rare, so we update the MSR here instead of using
3920                  * direct_access_msrs.  Doing that would require a rdmsr in
3921                  * svm_vcpu_put.
3922                  */
3923                 svm->tsc_aux = data;
3924                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
3925                 break;
3926         case MSR_IA32_DEBUGCTLMSR:
3927                 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
3928                         vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
3929                                     __func__, data);
3930                         break;
3931                 }
3932                 if (data & DEBUGCTL_RESERVED_BITS)
3933                         return 1;
3934
3935                 svm->vmcb->save.dbgctl = data;
3936                 mark_dirty(svm->vmcb, VMCB_LBR);
3937                 if (data & (1ULL<<0))
3938                         svm_enable_lbrv(svm);
3939                 else
3940                         svm_disable_lbrv(svm);
3941                 break;
3942         case MSR_VM_HSAVE_PA:
3943                 svm->nested.hsave_msr = data;
3944                 break;
3945         case MSR_VM_CR:
3946                 return svm_set_vm_cr(vcpu, data);
3947         case MSR_VM_IGNNE:
3948                 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
3949                 break;
3950         case MSR_F10H_DECFG: {
3951                 struct kvm_msr_entry msr_entry;
3952
3953                 msr_entry.index = msr->index;
3954                 if (svm_get_msr_feature(&msr_entry))
3955                         return 1;
3956
3957                 /* Check the supported bits */
3958                 if (data & ~msr_entry.data)
3959                         return 1;
3960
3961                 /* Don't allow the guest to change a bit, #GP */
3962                 if (!msr->host_initiated && (data ^ msr_entry.data))
3963                         return 1;
3964
3965                 svm->msr_decfg = data;
3966                 break;
3967         }
3968         case MSR_IA32_APICBASE:
3969                 if (kvm_vcpu_apicv_active(vcpu))
3970                         avic_update_vapic_bar(to_svm(vcpu), data);
3971                 /* Follow through */
3972         default:
3973                 return kvm_set_msr_common(vcpu, msr);
3974         }
3975         return 0;
3976 }
3977
3978 static int wrmsr_interception(struct vcpu_svm *svm)
3979 {
3980         struct msr_data msr;
3981         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3982         u64 data = kvm_read_edx_eax(&svm->vcpu);
3983
3984         msr.data = data;
3985         msr.index = ecx;
3986         msr.host_initiated = false;
3987
3988         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3989         if (kvm_set_msr(&svm->vcpu, &msr)) {
3990                 trace_kvm_msr_write_ex(ecx, data);
3991                 kvm_inject_gp(&svm->vcpu, 0);
3992                 return 1;
3993         } else {
3994                 trace_kvm_msr_write(ecx, data);
3995                 return kvm_skip_emulated_instruction(&svm->vcpu);
3996         }
3997 }
3998
3999 static int msr_interception(struct vcpu_svm *svm)
4000 {
4001         if (svm->vmcb->control.exit_info_1)
4002                 return wrmsr_interception(svm);
4003         else
4004                 return rdmsr_interception(svm);
4005 }
4006
4007 static int interrupt_window_interception(struct vcpu_svm *svm)
4008 {
4009         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4010         svm_clear_vintr(svm);
4011         svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4012         mark_dirty(svm->vmcb, VMCB_INTR);
4013         ++svm->vcpu.stat.irq_window_exits;
4014         return 1;
4015 }
4016
4017 static int pause_interception(struct vcpu_svm *svm)
4018 {
4019         struct kvm_vcpu *vcpu = &svm->vcpu;
4020         bool in_kernel = (svm_get_cpl(vcpu) == 0);
4021
4022         kvm_vcpu_on_spin(vcpu, in_kernel);
4023         return 1;
4024 }
4025
4026 static int nop_interception(struct vcpu_svm *svm)
4027 {
4028         return kvm_skip_emulated_instruction(&(svm->vcpu));
4029 }
4030
4031 static int monitor_interception(struct vcpu_svm *svm)
4032 {
4033         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4034         return nop_interception(svm);
4035 }
4036
4037 static int mwait_interception(struct vcpu_svm *svm)
4038 {
4039         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4040         return nop_interception(svm);
4041 }
4042
4043 enum avic_ipi_failure_cause {
4044         AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4045         AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4046         AVIC_IPI_FAILURE_INVALID_TARGET,
4047         AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4048 };
4049
4050 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4051 {
4052         u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4053         u32 icrl = svm->vmcb->control.exit_info_1;
4054         u32 id = svm->vmcb->control.exit_info_2 >> 32;
4055         u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4056         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4057
4058         trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4059
4060         switch (id) {
4061         case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4062                 /*
4063                  * AVIC hardware handles the generation of
4064                  * IPIs when the specified Message Type is Fixed
4065                  * (also known as fixed delivery mode) and
4066                  * the Trigger Mode is edge-triggered. The hardware
4067                  * also supports self and broadcast delivery modes
4068                  * specified via the Destination Shorthand(DSH)
4069                  * field of the ICRL. Logical and physical APIC ID
4070                  * formats are supported. All other IPI types cause
4071                  * a #VMEXIT, which needs to emulated.
4072                  */
4073                 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4074                 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4075                 break;
4076         case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4077                 int i;
4078                 struct kvm_vcpu *vcpu;
4079                 struct kvm *kvm = svm->vcpu.kvm;
4080                 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4081
4082                 /*
4083                  * At this point, we expect that the AVIC HW has already
4084                  * set the appropriate IRR bits on the valid target
4085                  * vcpus. So, we just need to kick the appropriate vcpu.
4086                  */
4087                 kvm_for_each_vcpu(i, vcpu, kvm) {
4088                         bool m = kvm_apic_match_dest(vcpu, apic,
4089                                                      icrl & KVM_APIC_SHORT_MASK,
4090                                                      GET_APIC_DEST_FIELD(icrh),
4091                                                      icrl & KVM_APIC_DEST_MASK);
4092
4093                         if (m && !avic_vcpu_is_running(vcpu))
4094                                 kvm_vcpu_wake_up(vcpu);
4095                 }
4096                 break;
4097         }
4098         case AVIC_IPI_FAILURE_INVALID_TARGET:
4099                 break;
4100         case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4101                 WARN_ONCE(1, "Invalid backing page\n");
4102                 break;
4103         default:
4104                 pr_err("Unknown IPI interception\n");
4105         }
4106
4107         return 1;
4108 }
4109
4110 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4111 {
4112         struct kvm_arch *vm_data = &vcpu->kvm->arch;
4113         int index;
4114         u32 *logical_apic_id_table;
4115         int dlid = GET_APIC_LOGICAL_ID(ldr);
4116
4117         if (!dlid)
4118                 return NULL;
4119
4120         if (flat) { /* flat */
4121                 index = ffs(dlid) - 1;
4122                 if (index > 7)
4123                         return NULL;
4124         } else { /* cluster */
4125                 int cluster = (dlid & 0xf0) >> 4;
4126                 int apic = ffs(dlid & 0x0f) - 1;
4127
4128                 if ((apic < 0) || (apic > 7) ||
4129                     (cluster >= 0xf))
4130                         return NULL;
4131                 index = (cluster << 2) + apic;
4132         }
4133
4134         logical_apic_id_table = (u32 *) page_address(vm_data->avic_logical_id_table_page);
4135
4136         return &logical_apic_id_table[index];
4137 }
4138
4139 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4140                           bool valid)
4141 {
4142         bool flat;
4143         u32 *entry, new_entry;
4144
4145         flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4146         entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4147         if (!entry)
4148                 return -EINVAL;
4149
4150         new_entry = READ_ONCE(*entry);
4151         new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4152         new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4153         if (valid)
4154                 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4155         else
4156                 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4157         WRITE_ONCE(*entry, new_entry);
4158
4159         return 0;
4160 }
4161
4162 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4163 {
4164         int ret;
4165         struct vcpu_svm *svm = to_svm(vcpu);
4166         u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4167
4168         if (!ldr)
4169                 return 1;
4170
4171         ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4172         if (ret && svm->ldr_reg) {
4173                 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4174                 svm->ldr_reg = 0;
4175         } else {
4176                 svm->ldr_reg = ldr;
4177         }
4178         return ret;
4179 }
4180
4181 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4182 {
4183         u64 *old, *new;
4184         struct vcpu_svm *svm = to_svm(vcpu);
4185         u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4186         u32 id = (apic_id_reg >> 24) & 0xff;
4187
4188         if (vcpu->vcpu_id == id)
4189                 return 0;
4190
4191         old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4192         new = avic_get_physical_id_entry(vcpu, id);
4193         if (!new || !old)
4194                 return 1;
4195
4196         /* We need to move physical_id_entry to new offset */
4197         *new = *old;
4198         *old = 0ULL;
4199         to_svm(vcpu)->avic_physical_id_cache = new;
4200
4201         /*
4202          * Also update the guest physical APIC ID in the logical
4203          * APIC ID table entry if already setup the LDR.
4204          */
4205         if (svm->ldr_reg)
4206                 avic_handle_ldr_update(vcpu);
4207
4208         return 0;
4209 }
4210
4211 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4212 {
4213         struct vcpu_svm *svm = to_svm(vcpu);
4214         struct kvm_arch *vm_data = &vcpu->kvm->arch;
4215         u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4216         u32 mod = (dfr >> 28) & 0xf;
4217
4218         /*
4219          * We assume that all local APICs are using the same type.
4220          * If this changes, we need to flush the AVIC logical
4221          * APID id table.
4222          */
4223         if (vm_data->ldr_mode == mod)
4224                 return 0;
4225
4226         clear_page(page_address(vm_data->avic_logical_id_table_page));
4227         vm_data->ldr_mode = mod;
4228
4229         if (svm->ldr_reg)
4230                 avic_handle_ldr_update(vcpu);
4231         return 0;
4232 }
4233
4234 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4235 {
4236         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4237         u32 offset = svm->vmcb->control.exit_info_1 &
4238                                 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4239
4240         switch (offset) {
4241         case APIC_ID:
4242                 if (avic_handle_apic_id_update(&svm->vcpu))
4243                         return 0;
4244                 break;
4245         case APIC_LDR:
4246                 if (avic_handle_ldr_update(&svm->vcpu))
4247                         return 0;
4248                 break;
4249         case APIC_DFR:
4250                 avic_handle_dfr_update(&svm->vcpu);
4251                 break;
4252         default:
4253                 break;
4254         }
4255
4256         kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4257
4258         return 1;
4259 }
4260
4261 static bool is_avic_unaccelerated_access_trap(u32 offset)
4262 {
4263         bool ret = false;
4264
4265         switch (offset) {
4266         case APIC_ID:
4267         case APIC_EOI:
4268         case APIC_RRR:
4269         case APIC_LDR:
4270         case APIC_DFR:
4271         case APIC_SPIV:
4272         case APIC_ESR:
4273         case APIC_ICR:
4274         case APIC_LVTT:
4275         case APIC_LVTTHMR:
4276         case APIC_LVTPC:
4277         case APIC_LVT0:
4278         case APIC_LVT1:
4279         case APIC_LVTERR:
4280         case APIC_TMICT:
4281         case APIC_TDCR:
4282                 ret = true;
4283                 break;
4284         default:
4285                 break;
4286         }
4287         return ret;
4288 }
4289
4290 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4291 {
4292         int ret = 0;
4293         u32 offset = svm->vmcb->control.exit_info_1 &
4294                      AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4295         u32 vector = svm->vmcb->control.exit_info_2 &
4296                      AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4297         bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4298                      AVIC_UNACCEL_ACCESS_WRITE_MASK;
4299         bool trap = is_avic_unaccelerated_access_trap(offset);
4300
4301         trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4302                                             trap, write, vector);
4303         if (trap) {
4304                 /* Handling Trap */
4305                 WARN_ONCE(!write, "svm: Handling trap read.\n");
4306                 ret = avic_unaccel_trap_write(svm);
4307         } else {
4308                 /* Handling Fault */
4309                 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4310         }
4311
4312         return ret;
4313 }
4314
4315 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4316         [SVM_EXIT_READ_CR0]                     = cr_interception,
4317         [SVM_EXIT_READ_CR3]                     = cr_interception,
4318         [SVM_EXIT_READ_CR4]                     = cr_interception,
4319         [SVM_EXIT_READ_CR8]                     = cr_interception,
4320         [SVM_EXIT_CR0_SEL_WRITE]                = cr_interception,
4321         [SVM_EXIT_WRITE_CR0]                    = cr_interception,
4322         [SVM_EXIT_WRITE_CR3]                    = cr_interception,
4323         [SVM_EXIT_WRITE_CR4]                    = cr_interception,
4324         [SVM_EXIT_WRITE_CR8]                    = cr8_write_interception,
4325         [SVM_EXIT_READ_DR0]                     = dr_interception,
4326         [SVM_EXIT_READ_DR1]                     = dr_interception,
4327         [SVM_EXIT_READ_DR2]                     = dr_interception,
4328         [SVM_EXIT_READ_DR3]                     = dr_interception,
4329         [SVM_EXIT_READ_DR4]                     = dr_interception,
4330         [SVM_EXIT_READ_DR5]                     = dr_interception,
4331         [SVM_EXIT_READ_DR6]                     = dr_interception,
4332         [SVM_EXIT_READ_DR7]                     = dr_interception,
4333         [SVM_EXIT_WRITE_DR0]                    = dr_interception,
4334         [SVM_EXIT_WRITE_DR1]                    = dr_interception,
4335         [SVM_EXIT_WRITE_DR2]                    = dr_interception,
4336         [SVM_EXIT_WRITE_DR3]                    = dr_interception,
4337         [SVM_EXIT_WRITE_DR4]                    = dr_interception,
4338         [SVM_EXIT_WRITE_DR5]                    = dr_interception,
4339         [SVM_EXIT_WRITE_DR6]                    = dr_interception,
4340         [SVM_EXIT_WRITE_DR7]                    = dr_interception,
4341         [SVM_EXIT_EXCP_BASE + DB_VECTOR]        = db_interception,
4342         [SVM_EXIT_EXCP_BASE + BP_VECTOR]        = bp_interception,
4343         [SVM_EXIT_EXCP_BASE + UD_VECTOR]        = ud_interception,
4344         [SVM_EXIT_EXCP_BASE + PF_VECTOR]        = pf_interception,
4345         [SVM_EXIT_EXCP_BASE + MC_VECTOR]        = mc_interception,
4346         [SVM_EXIT_EXCP_BASE + AC_VECTOR]        = ac_interception,
4347         [SVM_EXIT_INTR]                         = intr_interception,
4348         [SVM_EXIT_NMI]                          = nmi_interception,
4349         [SVM_EXIT_SMI]                          = nop_on_interception,
4350         [SVM_EXIT_INIT]                         = nop_on_interception,
4351         [SVM_EXIT_VINTR]                        = interrupt_window_interception,
4352         [SVM_EXIT_RDPMC]                        = rdpmc_interception,
4353         [SVM_EXIT_CPUID]                        = cpuid_interception,
4354         [SVM_EXIT_IRET]                         = iret_interception,
4355         [SVM_EXIT_INVD]                         = emulate_on_interception,
4356         [SVM_EXIT_PAUSE]                        = pause_interception,
4357         [SVM_EXIT_HLT]                          = halt_interception,
4358         [SVM_EXIT_INVLPG]                       = invlpg_interception,
4359         [SVM_EXIT_INVLPGA]                      = invlpga_interception,
4360         [SVM_EXIT_IOIO]                         = io_interception,
4361         [SVM_EXIT_MSR]                          = msr_interception,
4362         [SVM_EXIT_TASK_SWITCH]                  = task_switch_interception,
4363         [SVM_EXIT_SHUTDOWN]                     = shutdown_interception,
4364         [SVM_EXIT_VMRUN]                        = vmrun_interception,
4365         [SVM_EXIT_VMMCALL]                      = vmmcall_interception,
4366         [SVM_EXIT_VMLOAD]                       = vmload_interception,
4367         [SVM_EXIT_VMSAVE]                       = vmsave_interception,
4368         [SVM_EXIT_STGI]                         = stgi_interception,
4369         [SVM_EXIT_CLGI]                         = clgi_interception,
4370         [SVM_EXIT_SKINIT]                       = skinit_interception,
4371         [SVM_EXIT_WBINVD]                       = wbinvd_interception,
4372         [SVM_EXIT_MONITOR]                      = monitor_interception,
4373         [SVM_EXIT_MWAIT]                        = mwait_interception,
4374         [SVM_EXIT_XSETBV]                       = xsetbv_interception,
4375         [SVM_EXIT_NPF]                          = pf_interception,
4376         [SVM_EXIT_RSM]                          = emulate_on_interception,
4377         [SVM_EXIT_AVIC_INCOMPLETE_IPI]          = avic_incomplete_ipi_interception,
4378         [SVM_EXIT_AVIC_UNACCELERATED_ACCESS]    = avic_unaccelerated_access_interception,
4379 };
4380
4381 static void dump_vmcb(struct kvm_vcpu *vcpu)
4382 {
4383         struct vcpu_svm *svm = to_svm(vcpu);
4384         struct vmcb_control_area *control = &svm->vmcb->control;
4385         struct vmcb_save_area *save = &svm->vmcb->save;
4386
4387         pr_err("VMCB Control Area:\n");
4388         pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4389         pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4390         pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4391         pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4392         pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4393         pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4394         pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4395         pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4396         pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4397         pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4398         pr_err("%-20s%d\n", "asid:", control->asid);
4399         pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4400         pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4401         pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4402         pr_err("%-20s%08x\n", "int_state:", control->int_state);
4403         pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4404         pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4405         pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4406         pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4407         pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4408         pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4409         pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4410         pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4411         pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4412         pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4413         pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4414         pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4415         pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4416         pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4417         pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4418         pr_err("VMCB State Save Area:\n");
4419         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4420                "es:",
4421                save->es.selector, save->es.attrib,
4422                save->es.limit, save->es.base);
4423         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4424                "cs:",
4425                save->cs.selector, save->cs.attrib,
4426                save->cs.limit, save->cs.base);
4427         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4428                "ss:",
4429                save->ss.selector, save->ss.attrib,
4430                save->ss.limit, save->ss.base);
4431         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4432                "ds:",
4433                save->ds.selector, save->ds.attrib,
4434                save->ds.limit, save->ds.base);
4435         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4436                "fs:",
4437                save->fs.selector, save->fs.attrib,
4438                save->fs.limit, save->fs.base);
4439         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4440                "gs:",
4441                save->gs.selector, save->gs.attrib,
4442                save->gs.limit, save->gs.base);
4443         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4444                "gdtr:",
4445                save->gdtr.selector, save->gdtr.attrib,
4446                save->gdtr.limit, save->gdtr.base);
4447         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4448                "ldtr:",
4449                save->ldtr.selector, save->ldtr.attrib,
4450                save->ldtr.limit, save->ldtr.base);
4451         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4452                "idtr:",
4453                save->idtr.selector, save->idtr.attrib,
4454                save->idtr.limit, save->idtr.base);
4455         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4456                "tr:",
4457                save->tr.selector, save->tr.attrib,
4458                save->tr.limit, save->tr.base);
4459         pr_err("cpl:            %d                efer:         %016llx\n",
4460                 save->cpl, save->efer);
4461         pr_err("%-15s %016llx %-13s %016llx\n",
4462                "cr0:", save->cr0, "cr2:", save->cr2);
4463         pr_err("%-15s %016llx %-13s %016llx\n",
4464                "cr3:", save->cr3, "cr4:", save->cr4);
4465         pr_err("%-15s %016llx %-13s %016llx\n",
4466                "dr6:", save->dr6, "dr7:", save->dr7);
4467         pr_err("%-15s %016llx %-13s %016llx\n",
4468                "rip:", save->rip, "rflags:", save->rflags);
4469         pr_err("%-15s %016llx %-13s %016llx\n",
4470                "rsp:", save->rsp, "rax:", save->rax);
4471         pr_err("%-15s %016llx %-13s %016llx\n",
4472                "star:", save->star, "lstar:", save->lstar);
4473         pr_err("%-15s %016llx %-13s %016llx\n",
4474                "cstar:", save->cstar, "sfmask:", save->sfmask);
4475         pr_err("%-15s %016llx %-13s %016llx\n",
4476                "kernel_gs_base:", save->kernel_gs_base,
4477                "sysenter_cs:", save->sysenter_cs);
4478         pr_err("%-15s %016llx %-13s %016llx\n",
4479                "sysenter_esp:", save->sysenter_esp,
4480                "sysenter_eip:", save->sysenter_eip);
4481         pr_err("%-15s %016llx %-13s %016llx\n",
4482                "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4483         pr_err("%-15s %016llx %-13s %016llx\n",
4484                "br_from:", save->br_from, "br_to:", save->br_to);
4485         pr_err("%-15s %016llx %-13s %016llx\n",
4486                "excp_from:", save->last_excp_from,
4487                "excp_to:", save->last_excp_to);
4488 }
4489
4490 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4491 {
4492         struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4493
4494         *info1 = control->exit_info_1;
4495         *info2 = control->exit_info_2;
4496 }
4497
4498 static int handle_exit(struct kvm_vcpu *vcpu)
4499 {
4500         struct vcpu_svm *svm = to_svm(vcpu);
4501         struct kvm_run *kvm_run = vcpu->run;
4502         u32 exit_code = svm->vmcb->control.exit_code;
4503
4504         trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4505
4506         if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4507                 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4508         if (npt_enabled)
4509                 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4510
4511         if (unlikely(svm->nested.exit_required)) {
4512                 nested_svm_vmexit(svm);
4513                 svm->nested.exit_required = false;
4514
4515                 return 1;
4516         }
4517
4518         if (is_guest_mode(vcpu)) {
4519                 int vmexit;
4520
4521                 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4522                                         svm->vmcb->control.exit_info_1,
4523                                         svm->vmcb->control.exit_info_2,
4524                                         svm->vmcb->control.exit_int_info,
4525                                         svm->vmcb->control.exit_int_info_err,
4526                                         KVM_ISA_SVM);
4527
4528                 vmexit = nested_svm_exit_special(svm);
4529
4530                 if (vmexit == NESTED_EXIT_CONTINUE)
4531                         vmexit = nested_svm_exit_handled(svm);
4532
4533                 if (vmexit == NESTED_EXIT_DONE)
4534                         return 1;
4535         }
4536
4537         svm_complete_interrupts(svm);
4538
4539         if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4540                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4541                 kvm_run->fail_entry.hardware_entry_failure_reason
4542                         = svm->vmcb->control.exit_code;
4543                 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4544                 dump_vmcb(vcpu);
4545                 return 0;
4546         }
4547
4548         if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4549             exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4550             exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4551             exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4552                 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4553                        "exit_code 0x%x\n",
4554                        __func__, svm->vmcb->control.exit_int_info,
4555                        exit_code);
4556
4557         if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4558             || !svm_exit_handlers[exit_code]) {
4559                 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4560                 kvm_queue_exception(vcpu, UD_VECTOR);
4561                 return 1;
4562         }
4563
4564         return svm_exit_handlers[exit_code](svm);
4565 }
4566
4567 static void reload_tss(struct kvm_vcpu *vcpu)
4568 {
4569         int cpu = raw_smp_processor_id();
4570
4571         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4572         sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4573         load_TR_desc();
4574 }
4575
4576 static void pre_svm_run(struct vcpu_svm *svm)
4577 {
4578         int cpu = raw_smp_processor_id();
4579
4580         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4581
4582         /* FIXME: handle wraparound of asid_generation */
4583         if (svm->asid_generation != sd->asid_generation)
4584                 new_asid(svm, sd);
4585 }
4586
4587 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
4588 {
4589         struct vcpu_svm *svm = to_svm(vcpu);
4590
4591         svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
4592         vcpu->arch.hflags |= HF_NMI_MASK;
4593         set_intercept(svm, INTERCEPT_IRET);
4594         ++vcpu->stat.nmi_injections;
4595 }
4596
4597 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
4598 {
4599         struct vmcb_control_area *control;
4600
4601         /* The following fields are ignored when AVIC is enabled */
4602         control = &svm->vmcb->control;
4603         control->int_vector = irq;
4604         control->int_ctl &= ~V_INTR_PRIO_MASK;
4605         control->int_ctl |= V_IRQ_MASK |
4606                 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
4607         mark_dirty(svm->vmcb, VMCB_INTR);
4608 }
4609
4610 static void svm_set_irq(struct kvm_vcpu *vcpu)
4611 {
4612         struct vcpu_svm *svm = to_svm(vcpu);
4613
4614         BUG_ON(!(gif_set(svm)));
4615
4616         trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
4617         ++vcpu->stat.irq_injections;
4618
4619         svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
4620                 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
4621 }
4622
4623 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
4624 {
4625         return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
4626 }
4627
4628 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4629 {
4630         struct vcpu_svm *svm = to_svm(vcpu);
4631
4632         if (svm_nested_virtualize_tpr(vcpu) ||
4633             kvm_vcpu_apicv_active(vcpu))
4634                 return;
4635
4636         clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4637
4638         if (irr == -1)
4639                 return;
4640
4641         if (tpr >= irr)
4642                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4643 }
4644
4645 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
4646 {
4647         return;
4648 }
4649
4650 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
4651 {
4652         return avic && irqchip_split(vcpu->kvm);
4653 }
4654
4655 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
4656 {
4657 }
4658
4659 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
4660 {
4661 }
4662
4663 /* Note: Currently only used by Hyper-V. */
4664 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4665 {
4666         struct vcpu_svm *svm = to_svm(vcpu);
4667         struct vmcb *vmcb = svm->vmcb;
4668
4669         if (!kvm_vcpu_apicv_active(&svm->vcpu))
4670                 return;
4671
4672         vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
4673         mark_dirty(vmcb, VMCB_INTR);
4674 }
4675
4676 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
4677 {
4678         return;
4679 }
4680
4681 static int svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
4682 {
4683         if (!vcpu->arch.apicv_active)
4684                 return -1;
4685
4686         kvm_lapic_set_irr(vec, vcpu->arch.apic);
4687         smp_mb__after_atomic();
4688
4689         if (avic_vcpu_is_running(vcpu))
4690                 wrmsrl(SVM_AVIC_DOORBELL,
4691                        kvm_cpu_get_apicid(vcpu->cpu));
4692         else
4693                 kvm_vcpu_wake_up(vcpu);
4694
4695         return 0;
4696 }
4697
4698 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
4699 {
4700         return false;
4701 }
4702
4703 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4704 {
4705         unsigned long flags;
4706         struct amd_svm_iommu_ir *cur;
4707
4708         spin_lock_irqsave(&svm->ir_list_lock, flags);
4709         list_for_each_entry(cur, &svm->ir_list, node) {
4710                 if (cur->data != pi->ir_data)
4711                         continue;
4712                 list_del(&cur->node);
4713                 kfree(cur);
4714                 break;
4715         }
4716         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4717 }
4718
4719 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4720 {
4721         int ret = 0;
4722         unsigned long flags;
4723         struct amd_svm_iommu_ir *ir;
4724
4725         /**
4726          * In some cases, the existing irte is updaed and re-set,
4727          * so we need to check here if it's already been * added
4728          * to the ir_list.
4729          */
4730         if (pi->ir_data && (pi->prev_ga_tag != 0)) {
4731                 struct kvm *kvm = svm->vcpu.kvm;
4732                 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
4733                 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
4734                 struct vcpu_svm *prev_svm;
4735
4736                 if (!prev_vcpu) {
4737                         ret = -EINVAL;
4738                         goto out;
4739                 }
4740
4741                 prev_svm = to_svm(prev_vcpu);
4742                 svm_ir_list_del(prev_svm, pi);
4743         }
4744
4745         /**
4746          * Allocating new amd_iommu_pi_data, which will get
4747          * add to the per-vcpu ir_list.
4748          */
4749         ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
4750         if (!ir) {
4751                 ret = -ENOMEM;
4752                 goto out;
4753         }
4754         ir->data = pi->ir_data;
4755
4756         spin_lock_irqsave(&svm->ir_list_lock, flags);
4757         list_add(&ir->node, &svm->ir_list);
4758         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4759 out:
4760         return ret;
4761 }
4762
4763 /**
4764  * Note:
4765  * The HW cannot support posting multicast/broadcast
4766  * interrupts to a vCPU. So, we still use legacy interrupt
4767  * remapping for these kind of interrupts.
4768  *
4769  * For lowest-priority interrupts, we only support
4770  * those with single CPU as the destination, e.g. user
4771  * configures the interrupts via /proc/irq or uses
4772  * irqbalance to make the interrupts single-CPU.
4773  */
4774 static int
4775 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
4776                  struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
4777 {
4778         struct kvm_lapic_irq irq;
4779         struct kvm_vcpu *vcpu = NULL;
4780
4781         kvm_set_msi_irq(kvm, e, &irq);
4782
4783         if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
4784                 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
4785                          __func__, irq.vector);
4786                 return -1;
4787         }
4788
4789         pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
4790                  irq.vector);
4791         *svm = to_svm(vcpu);
4792         vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
4793         vcpu_info->vector = irq.vector;
4794
4795         return 0;
4796 }
4797
4798 /*
4799  * svm_update_pi_irte - set IRTE for Posted-Interrupts
4800  *
4801  * @kvm: kvm
4802  * @host_irq: host irq of the interrupt
4803  * @guest_irq: gsi of the interrupt
4804  * @set: set or unset PI
4805  * returns 0 on success, < 0 on failure
4806  */
4807 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
4808                               uint32_t guest_irq, bool set)
4809 {
4810         struct kvm_kernel_irq_routing_entry *e;
4811         struct kvm_irq_routing_table *irq_rt;
4812         int idx, ret = -EINVAL;
4813
4814         if (!kvm_arch_has_assigned_device(kvm) ||
4815             !irq_remapping_cap(IRQ_POSTING_CAP))
4816                 return 0;
4817
4818         pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
4819                  __func__, host_irq, guest_irq, set);
4820
4821         idx = srcu_read_lock(&kvm->irq_srcu);
4822         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
4823         WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
4824
4825         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
4826                 struct vcpu_data vcpu_info;
4827                 struct vcpu_svm *svm = NULL;
4828
4829                 if (e->type != KVM_IRQ_ROUTING_MSI)
4830                         continue;
4831
4832                 /**
4833                  * Here, we setup with legacy mode in the following cases:
4834                  * 1. When cannot target interrupt to a specific vcpu.
4835                  * 2. Unsetting posted interrupt.
4836                  * 3. APIC virtialization is disabled for the vcpu.
4837                  */
4838                 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
4839                     kvm_vcpu_apicv_active(&svm->vcpu)) {
4840                         struct amd_iommu_pi_data pi;
4841
4842                         /* Try to enable guest_mode in IRTE */
4843                         pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
4844                                             AVIC_HPA_MASK);
4845                         pi.ga_tag = AVIC_GATAG(kvm->arch.avic_vm_id,
4846                                                      svm->vcpu.vcpu_id);
4847                         pi.is_guest_mode = true;
4848                         pi.vcpu_data = &vcpu_info;
4849                         ret = irq_set_vcpu_affinity(host_irq, &pi);
4850
4851                         /**
4852                          * Here, we successfully setting up vcpu affinity in
4853                          * IOMMU guest mode. Now, we need to store the posted
4854                          * interrupt information in a per-vcpu ir_list so that
4855                          * we can reference to them directly when we update vcpu
4856                          * scheduling information in IOMMU irte.
4857                          */
4858                         if (!ret && pi.is_guest_mode)
4859                                 svm_ir_list_add(svm, &pi);
4860                 } else {
4861                         /* Use legacy mode in IRTE */
4862                         struct amd_iommu_pi_data pi;
4863
4864                         /**
4865                          * Here, pi is used to:
4866                          * - Tell IOMMU to use legacy mode for this interrupt.
4867                          * - Retrieve ga_tag of prior interrupt remapping data.
4868                          */
4869                         pi.prev_ga_tag = 0;
4870                         pi.is_guest_mode = false;
4871                         ret = irq_set_vcpu_affinity(host_irq, &pi);
4872
4873                         /**
4874                          * Check if the posted interrupt was previously
4875                          * setup with the guest_mode by checking if the ga_tag
4876                          * was cached. If so, we need to clean up the per-vcpu
4877                          * ir_list.
4878                          */
4879                         if (!ret && pi.prev_ga_tag) {
4880                                 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
4881                                 struct kvm_vcpu *vcpu;
4882
4883                                 vcpu = kvm_get_vcpu_by_id(kvm, id);
4884                                 if (vcpu)
4885                                         svm_ir_list_del(to_svm(vcpu), &pi);
4886                         }
4887                 }
4888
4889                 if (!ret && svm) {
4890                         trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
4891                                                  e->gsi, vcpu_info.vector,
4892                                                  vcpu_info.pi_desc_addr, set);
4893                 }
4894
4895                 if (ret < 0) {
4896                         pr_err("%s: failed to update PI IRTE\n", __func__);
4897                         goto out;
4898                 }
4899         }
4900
4901         ret = 0;
4902 out:
4903         srcu_read_unlock(&kvm->irq_srcu, idx);
4904         return ret;
4905 }
4906
4907 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
4908 {
4909         struct vcpu_svm *svm = to_svm(vcpu);
4910         struct vmcb *vmcb = svm->vmcb;
4911         int ret;
4912         ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
4913               !(svm->vcpu.arch.hflags & HF_NMI_MASK);
4914         ret = ret && gif_set(svm) && nested_svm_nmi(svm);
4915
4916         return ret;
4917 }
4918
4919 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
4920 {
4921         struct vcpu_svm *svm = to_svm(vcpu);
4922
4923         return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
4924 }
4925
4926 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
4927 {
4928         struct vcpu_svm *svm = to_svm(vcpu);
4929
4930         if (masked) {
4931                 svm->vcpu.arch.hflags |= HF_NMI_MASK;
4932                 set_intercept(svm, INTERCEPT_IRET);
4933         } else {
4934                 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
4935                 clr_intercept(svm, INTERCEPT_IRET);
4936         }
4937 }
4938
4939 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
4940 {
4941         struct vcpu_svm *svm = to_svm(vcpu);
4942         struct vmcb *vmcb = svm->vmcb;
4943         int ret;
4944
4945         if (!gif_set(svm) ||
4946              (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
4947                 return 0;
4948
4949         ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
4950
4951         if (is_guest_mode(vcpu))
4952                 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
4953
4954         return ret;
4955 }
4956
4957 static void enable_irq_window(struct kvm_vcpu *vcpu)
4958 {
4959         struct vcpu_svm *svm = to_svm(vcpu);
4960
4961         if (kvm_vcpu_apicv_active(vcpu))
4962                 return;
4963
4964         /*
4965          * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
4966          * 1, because that's a separate STGI/VMRUN intercept.  The next time we
4967          * get that intercept, this function will be called again though and
4968          * we'll get the vintr intercept. However, if the vGIF feature is
4969          * enabled, the STGI interception will not occur. Enable the irq
4970          * window under the assumption that the hardware will set the GIF.
4971          */
4972         if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
4973                 svm_set_vintr(svm);
4974                 svm_inject_irq(svm, 0x0);
4975         }
4976 }
4977
4978 static void enable_nmi_window(struct kvm_vcpu *vcpu)
4979 {
4980         struct vcpu_svm *svm = to_svm(vcpu);
4981
4982         if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
4983             == HF_NMI_MASK)
4984                 return; /* IRET will cause a vm exit */
4985
4986         if (!gif_set(svm)) {
4987                 if (vgif_enabled(svm))
4988                         set_intercept(svm, INTERCEPT_STGI);
4989                 return; /* STGI will cause a vm exit */
4990         }
4991
4992         if (svm->nested.exit_required)
4993                 return; /* we're not going to run the guest yet */
4994
4995         /*
4996          * Something prevents NMI from been injected. Single step over possible
4997          * problem (IRET or exception injection or interrupt shadow)
4998          */
4999         svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5000         svm->nmi_singlestep = true;
5001         svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5002 }
5003
5004 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5005 {
5006         return 0;
5007 }
5008
5009 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5010 {
5011         struct vcpu_svm *svm = to_svm(vcpu);
5012
5013         if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5014                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5015         else
5016                 svm->asid_generation--;
5017 }
5018
5019 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5020 {
5021 }
5022
5023 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5024 {
5025         struct vcpu_svm *svm = to_svm(vcpu);
5026
5027         if (svm_nested_virtualize_tpr(vcpu))
5028                 return;
5029
5030         if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5031                 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5032                 kvm_set_cr8(vcpu, cr8);
5033         }
5034 }
5035
5036 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5037 {
5038         struct vcpu_svm *svm = to_svm(vcpu);
5039         u64 cr8;
5040
5041         if (svm_nested_virtualize_tpr(vcpu) ||
5042             kvm_vcpu_apicv_active(vcpu))
5043                 return;
5044
5045         cr8 = kvm_get_cr8(vcpu);
5046         svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5047         svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5048 }
5049
5050 static void svm_complete_interrupts(struct vcpu_svm *svm)
5051 {
5052         u8 vector;
5053         int type;
5054         u32 exitintinfo = svm->vmcb->control.exit_int_info;
5055         unsigned int3_injected = svm->int3_injected;
5056
5057         svm->int3_injected = 0;
5058
5059         /*
5060          * If we've made progress since setting HF_IRET_MASK, we've
5061          * executed an IRET and can allow NMI injection.
5062          */
5063         if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5064             && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5065                 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5066                 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5067         }
5068
5069         svm->vcpu.arch.nmi_injected = false;
5070         kvm_clear_exception_queue(&svm->vcpu);
5071         kvm_clear_interrupt_queue(&svm->vcpu);
5072
5073         if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5074                 return;
5075
5076         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5077
5078         vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5079         type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5080
5081         switch (type) {
5082         case SVM_EXITINTINFO_TYPE_NMI:
5083                 svm->vcpu.arch.nmi_injected = true;
5084                 break;
5085         case SVM_EXITINTINFO_TYPE_EXEPT:
5086                 /*
5087                  * In case of software exceptions, do not reinject the vector,
5088                  * but re-execute the instruction instead. Rewind RIP first
5089                  * if we emulated INT3 before.
5090                  */
5091                 if (kvm_exception_is_soft(vector)) {
5092                         if (vector == BP_VECTOR && int3_injected &&
5093                             kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5094                                 kvm_rip_write(&svm->vcpu,
5095                                               kvm_rip_read(&svm->vcpu) -
5096                                               int3_injected);
5097                         break;
5098                 }
5099                 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5100                         u32 err = svm->vmcb->control.exit_int_info_err;
5101                         kvm_requeue_exception_e(&svm->vcpu, vector, err);
5102
5103                 } else
5104                         kvm_requeue_exception(&svm->vcpu, vector);
5105                 break;
5106         case SVM_EXITINTINFO_TYPE_INTR:
5107                 kvm_queue_interrupt(&svm->vcpu, vector, false);
5108                 break;
5109         default:
5110                 break;
5111         }
5112 }
5113
5114 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5115 {
5116         struct vcpu_svm *svm = to_svm(vcpu);
5117         struct vmcb_control_area *control = &svm->vmcb->control;
5118
5119         control->exit_int_info = control->event_inj;
5120         control->exit_int_info_err = control->event_inj_err;
5121         control->event_inj = 0;
5122         svm_complete_interrupts(svm);
5123 }
5124
5125 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5126 {
5127         struct vcpu_svm *svm = to_svm(vcpu);
5128
5129         svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5130         svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5131         svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5132
5133         /*
5134          * A vmexit emulation is required before the vcpu can be executed
5135          * again.
5136          */
5137         if (unlikely(svm->nested.exit_required))
5138                 return;
5139
5140         /*
5141          * Disable singlestep if we're injecting an interrupt/exception.
5142          * We don't want our modified rflags to be pushed on the stack where
5143          * we might not be able to easily reset them if we disabled NMI
5144          * singlestep later.
5145          */
5146         if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5147                 /*
5148                  * Event injection happens before external interrupts cause a
5149                  * vmexit and interrupts are disabled here, so smp_send_reschedule
5150                  * is enough to force an immediate vmexit.
5151                  */
5152                 disable_nmi_singlestep(svm);
5153                 smp_send_reschedule(vcpu->cpu);
5154         }
5155
5156         pre_svm_run(svm);
5157
5158         sync_lapic_to_cr8(vcpu);
5159
5160         svm->vmcb->save.cr2 = vcpu->arch.cr2;
5161
5162         clgi();
5163
5164         /*
5165          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5166          * it's non-zero. Since vmentry is serialising on affected CPUs, there
5167          * is no need to worry about the conditional branch over the wrmsr
5168          * being speculatively taken.
5169          */
5170         x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5171
5172         local_irq_enable();
5173
5174         asm volatile (
5175                 "push %%" _ASM_BP "; \n\t"
5176                 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5177                 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5178                 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5179                 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5180                 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5181                 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5182 #ifdef CONFIG_X86_64
5183                 "mov %c[r8](%[svm]),  %%r8  \n\t"
5184                 "mov %c[r9](%[svm]),  %%r9  \n\t"
5185                 "mov %c[r10](%[svm]), %%r10 \n\t"
5186                 "mov %c[r11](%[svm]), %%r11 \n\t"
5187                 "mov %c[r12](%[svm]), %%r12 \n\t"
5188                 "mov %c[r13](%[svm]), %%r13 \n\t"
5189                 "mov %c[r14](%[svm]), %%r14 \n\t"
5190                 "mov %c[r15](%[svm]), %%r15 \n\t"
5191 #endif
5192
5193                 /* Enter guest mode */
5194                 "push %%" _ASM_AX " \n\t"
5195                 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5196                 __ex(SVM_VMLOAD) "\n\t"
5197                 __ex(SVM_VMRUN) "\n\t"
5198                 __ex(SVM_VMSAVE) "\n\t"
5199                 "pop %%" _ASM_AX " \n\t"
5200
5201                 /* Save guest registers, load host registers */
5202                 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5203                 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5204                 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5205                 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5206                 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5207                 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5208 #ifdef CONFIG_X86_64
5209                 "mov %%r8,  %c[r8](%[svm]) \n\t"
5210                 "mov %%r9,  %c[r9](%[svm]) \n\t"
5211                 "mov %%r10, %c[r10](%[svm]) \n\t"
5212                 "mov %%r11, %c[r11](%[svm]) \n\t"
5213                 "mov %%r12, %c[r12](%[svm]) \n\t"
5214                 "mov %%r13, %c[r13](%[svm]) \n\t"
5215                 "mov %%r14, %c[r14](%[svm]) \n\t"
5216                 "mov %%r15, %c[r15](%[svm]) \n\t"
5217 #endif
5218                 /*
5219                 * Clear host registers marked as clobbered to prevent
5220                 * speculative use.
5221                 */
5222                 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5223                 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5224                 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5225                 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5226                 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5227 #ifdef CONFIG_X86_64
5228                 "xor %%r8, %%r8 \n\t"
5229                 "xor %%r9, %%r9 \n\t"
5230                 "xor %%r10, %%r10 \n\t"
5231                 "xor %%r11, %%r11 \n\t"
5232                 "xor %%r12, %%r12 \n\t"
5233                 "xor %%r13, %%r13 \n\t"
5234                 "xor %%r14, %%r14 \n\t"
5235                 "xor %%r15, %%r15 \n\t"
5236 #endif
5237                 "pop %%" _ASM_BP
5238                 :
5239                 : [svm]"a"(svm),
5240                   [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5241                   [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5242                   [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5243                   [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5244                   [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5245                   [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5246                   [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5247 #ifdef CONFIG_X86_64
5248                   , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5249                   [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5250                   [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5251                   [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5252                   [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5253                   [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5254                   [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5255                   [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5256 #endif
5257                 : "cc", "memory"
5258 #ifdef CONFIG_X86_64
5259                 , "rbx", "rcx", "rdx", "rsi", "rdi"
5260                 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5261 #else
5262                 , "ebx", "ecx", "edx", "esi", "edi"
5263 #endif
5264                 );
5265
5266         /* Eliminate branch target predictions from guest mode */
5267         vmexit_fill_RSB();
5268
5269 #ifdef CONFIG_X86_64
5270         wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5271 #else
5272         loadsegment(fs, svm->host.fs);
5273 #ifndef CONFIG_X86_32_LAZY_GS
5274         loadsegment(gs, svm->host.gs);
5275 #endif
5276 #endif
5277
5278         /*
5279          * We do not use IBRS in the kernel. If this vCPU has used the
5280          * SPEC_CTRL MSR it may have left it on; save the value and
5281          * turn it off. This is much more efficient than blindly adding
5282          * it to the atomic save/restore list. Especially as the former
5283          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5284          *
5285          * For non-nested case:
5286          * If the L01 MSR bitmap does not intercept the MSR, then we need to
5287          * save it.
5288          *
5289          * For nested case:
5290          * If the L02 MSR bitmap does not intercept the MSR, then we need to
5291          * save it.
5292          */
5293         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5294                 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5295
5296         reload_tss(vcpu);
5297
5298         local_irq_disable();
5299
5300         x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5301
5302         vcpu->arch.cr2 = svm->vmcb->save.cr2;
5303         vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5304         vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5305         vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5306
5307         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5308                 kvm_before_handle_nmi(&svm->vcpu);
5309
5310         stgi();
5311
5312         /* Any pending NMI will happen here */
5313
5314         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5315                 kvm_after_handle_nmi(&svm->vcpu);
5316
5317         sync_cr8_to_lapic(vcpu);
5318
5319         svm->next_rip = 0;
5320
5321         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5322
5323         /* if exit due to PF check for async PF */
5324         if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5325                 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5326
5327         if (npt_enabled) {
5328                 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5329                 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5330         }
5331
5332         /*
5333          * We need to handle MC intercepts here before the vcpu has a chance to
5334          * change the physical cpu
5335          */
5336         if (unlikely(svm->vmcb->control.exit_code ==
5337                      SVM_EXIT_EXCP_BASE + MC_VECTOR))
5338                 svm_handle_mce(svm);
5339
5340         mark_all_clean(svm->vmcb);
5341 }
5342 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5343
5344 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5345 {
5346         struct vcpu_svm *svm = to_svm(vcpu);
5347
5348         svm->vmcb->save.cr3 = __sme_set(root);
5349         mark_dirty(svm->vmcb, VMCB_CR);
5350         svm_flush_tlb(vcpu, true);
5351 }
5352
5353 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5354 {
5355         struct vcpu_svm *svm = to_svm(vcpu);
5356
5357         svm->vmcb->control.nested_cr3 = __sme_set(root);
5358         mark_dirty(svm->vmcb, VMCB_NPT);
5359
5360         /* Also sync guest cr3 here in case we live migrate */
5361         svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5362         mark_dirty(svm->vmcb, VMCB_CR);
5363
5364         svm_flush_tlb(vcpu, true);
5365 }
5366
5367 static int is_disabled(void)
5368 {
5369         u64 vm_cr;
5370
5371         rdmsrl(MSR_VM_CR, vm_cr);
5372         if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5373                 return 1;
5374
5375         return 0;
5376 }
5377
5378 static void
5379 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5380 {
5381         /*
5382          * Patch in the VMMCALL instruction:
5383          */
5384         hypercall[0] = 0x0f;
5385         hypercall[1] = 0x01;
5386         hypercall[2] = 0xd9;
5387 }
5388
5389 static void svm_check_processor_compat(void *rtn)
5390 {
5391         *(int *)rtn = 0;
5392 }
5393
5394 static bool svm_cpu_has_accelerated_tpr(void)
5395 {
5396         return false;
5397 }
5398
5399 static bool svm_has_emulated_msr(int index)
5400 {
5401         switch (index) {
5402         case MSR_IA32_MCG_EXT_CTL:
5403                 return false;
5404         default:
5405                 break;
5406         }
5407
5408         return true;
5409 }
5410
5411 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5412 {
5413         return 0;
5414 }
5415
5416 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5417 {
5418         struct vcpu_svm *svm = to_svm(vcpu);
5419
5420         /* Update nrips enabled cache */
5421         svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5422
5423         if (!kvm_vcpu_apicv_active(vcpu))
5424                 return;
5425
5426         guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5427 }
5428
5429 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5430 {
5431         switch (func) {
5432         case 0x1:
5433                 if (avic)
5434                         entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5435                 break;
5436         case 0x80000001:
5437                 if (nested)
5438                         entry->ecx |= (1 << 2); /* Set SVM bit */
5439                 break;
5440         case 0x8000000A:
5441                 entry->eax = 1; /* SVM revision 1 */
5442                 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5443                                    ASID emulation to nested SVM */
5444                 entry->ecx = 0; /* Reserved */
5445                 entry->edx = 0; /* Per default do not support any
5446                                    additional features */
5447
5448                 /* Support next_rip if host supports it */
5449                 if (boot_cpu_has(X86_FEATURE_NRIPS))
5450                         entry->edx |= SVM_FEATURE_NRIP;
5451
5452                 /* Support NPT for the guest if enabled */
5453                 if (npt_enabled)
5454                         entry->edx |= SVM_FEATURE_NPT;
5455
5456                 break;
5457         }
5458 }
5459
5460 static int svm_get_lpage_level(void)
5461 {
5462         return PT_PDPE_LEVEL;
5463 }
5464
5465 static bool svm_rdtscp_supported(void)
5466 {
5467         return boot_cpu_has(X86_FEATURE_RDTSCP);
5468 }
5469
5470 static bool svm_invpcid_supported(void)
5471 {
5472         return false;
5473 }
5474
5475 static bool svm_mpx_supported(void)
5476 {
5477         return false;
5478 }
5479
5480 static bool svm_xsaves_supported(void)
5481 {
5482         return false;
5483 }
5484
5485 static bool svm_has_wbinvd_exit(void)
5486 {
5487         return true;
5488 }
5489
5490 #define PRE_EX(exit)  { .exit_code = (exit), \
5491                         .stage = X86_ICPT_PRE_EXCEPT, }
5492 #define POST_EX(exit) { .exit_code = (exit), \
5493                         .stage = X86_ICPT_POST_EXCEPT, }
5494 #define POST_MEM(exit) { .exit_code = (exit), \
5495                         .stage = X86_ICPT_POST_MEMACCESS, }
5496
5497 static const struct __x86_intercept {
5498         u32 exit_code;
5499         enum x86_intercept_stage stage;
5500 } x86_intercept_map[] = {
5501         [x86_intercept_cr_read]         = POST_EX(SVM_EXIT_READ_CR0),
5502         [x86_intercept_cr_write]        = POST_EX(SVM_EXIT_WRITE_CR0),
5503         [x86_intercept_clts]            = POST_EX(SVM_EXIT_WRITE_CR0),
5504         [x86_intercept_lmsw]            = POST_EX(SVM_EXIT_WRITE_CR0),
5505         [x86_intercept_smsw]            = POST_EX(SVM_EXIT_READ_CR0),
5506         [x86_intercept_dr_read]         = POST_EX(SVM_EXIT_READ_DR0),
5507         [x86_intercept_dr_write]        = POST_EX(SVM_EXIT_WRITE_DR0),
5508         [x86_intercept_sldt]            = POST_EX(SVM_EXIT_LDTR_READ),
5509         [x86_intercept_str]             = POST_EX(SVM_EXIT_TR_READ),
5510         [x86_intercept_lldt]            = POST_EX(SVM_EXIT_LDTR_WRITE),
5511         [x86_intercept_ltr]             = POST_EX(SVM_EXIT_TR_WRITE),
5512         [x86_intercept_sgdt]            = POST_EX(SVM_EXIT_GDTR_READ),
5513         [x86_intercept_sidt]            = POST_EX(SVM_EXIT_IDTR_READ),
5514         [x86_intercept_lgdt]            = POST_EX(SVM_EXIT_GDTR_WRITE),
5515         [x86_intercept_lidt]            = POST_EX(SVM_EXIT_IDTR_WRITE),
5516         [x86_intercept_vmrun]           = POST_EX(SVM_EXIT_VMRUN),
5517         [x86_intercept_vmmcall]         = POST_EX(SVM_EXIT_VMMCALL),
5518         [x86_intercept_vmload]          = POST_EX(SVM_EXIT_VMLOAD),
5519         [x86_intercept_vmsave]          = POST_EX(SVM_EXIT_VMSAVE),
5520         [x86_intercept_stgi]            = POST_EX(SVM_EXIT_STGI),
5521         [x86_intercept_clgi]            = POST_EX(SVM_EXIT_CLGI),
5522         [x86_intercept_skinit]          = POST_EX(SVM_EXIT_SKINIT),
5523         [x86_intercept_invlpga]         = POST_EX(SVM_EXIT_INVLPGA),
5524         [x86_intercept_rdtscp]          = POST_EX(SVM_EXIT_RDTSCP),
5525         [x86_intercept_monitor]         = POST_MEM(SVM_EXIT_MONITOR),
5526         [x86_intercept_mwait]           = POST_EX(SVM_EXIT_MWAIT),
5527         [x86_intercept_invlpg]          = POST_EX(SVM_EXIT_INVLPG),
5528         [x86_intercept_invd]            = POST_EX(SVM_EXIT_INVD),
5529         [x86_intercept_wbinvd]          = POST_EX(SVM_EXIT_WBINVD),
5530         [x86_intercept_wrmsr]           = POST_EX(SVM_EXIT_MSR),
5531         [x86_intercept_rdtsc]           = POST_EX(SVM_EXIT_RDTSC),
5532         [x86_intercept_rdmsr]           = POST_EX(SVM_EXIT_MSR),
5533         [x86_intercept_rdpmc]           = POST_EX(SVM_EXIT_RDPMC),
5534         [x86_intercept_cpuid]           = PRE_EX(SVM_EXIT_CPUID),
5535         [x86_intercept_rsm]             = PRE_EX(SVM_EXIT_RSM),
5536         [x86_intercept_pause]           = PRE_EX(SVM_EXIT_PAUSE),
5537         [x86_intercept_pushf]           = PRE_EX(SVM_EXIT_PUSHF),
5538         [x86_intercept_popf]            = PRE_EX(SVM_EXIT_POPF),
5539         [x86_intercept_intn]            = PRE_EX(SVM_EXIT_SWINT),
5540         [x86_intercept_iret]            = PRE_EX(SVM_EXIT_IRET),
5541         [x86_intercept_icebp]           = PRE_EX(SVM_EXIT_ICEBP),
5542         [x86_intercept_hlt]             = POST_EX(SVM_EXIT_HLT),
5543         [x86_intercept_in]              = POST_EX(SVM_EXIT_IOIO),
5544         [x86_intercept_ins]             = POST_EX(SVM_EXIT_IOIO),
5545         [x86_intercept_out]             = POST_EX(SVM_EXIT_IOIO),
5546         [x86_intercept_outs]            = POST_EX(SVM_EXIT_IOIO),
5547 };
5548
5549 #undef PRE_EX
5550 #undef POST_EX
5551 #undef POST_MEM
5552
5553 static int svm_check_intercept(struct kvm_vcpu *vcpu,
5554                                struct x86_instruction_info *info,
5555                                enum x86_intercept_stage stage)
5556 {
5557         struct vcpu_svm *svm = to_svm(vcpu);
5558         int vmexit, ret = X86EMUL_CONTINUE;
5559         struct __x86_intercept icpt_info;
5560         struct vmcb *vmcb = svm->vmcb;
5561
5562         if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
5563                 goto out;
5564
5565         icpt_info = x86_intercept_map[info->intercept];
5566
5567         if (stage != icpt_info.stage)
5568                 goto out;
5569
5570         switch (icpt_info.exit_code) {
5571         case SVM_EXIT_READ_CR0:
5572                 if (info->intercept == x86_intercept_cr_read)
5573                         icpt_info.exit_code += info->modrm_reg;
5574                 break;
5575         case SVM_EXIT_WRITE_CR0: {
5576                 unsigned long cr0, val;
5577                 u64 intercept;
5578
5579                 if (info->intercept == x86_intercept_cr_write)
5580                         icpt_info.exit_code += info->modrm_reg;
5581
5582                 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
5583                     info->intercept == x86_intercept_clts)
5584                         break;
5585
5586                 intercept = svm->nested.intercept;
5587
5588                 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
5589                         break;
5590
5591                 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5592                 val = info->src_val  & ~SVM_CR0_SELECTIVE_MASK;
5593
5594                 if (info->intercept == x86_intercept_lmsw) {
5595                         cr0 &= 0xfUL;
5596                         val &= 0xfUL;
5597                         /* lmsw can't clear PE - catch this here */
5598                         if (cr0 & X86_CR0_PE)
5599                                 val |= X86_CR0_PE;
5600                 }
5601
5602                 if (cr0 ^ val)
5603                         icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5604
5605                 break;
5606         }
5607         case SVM_EXIT_READ_DR0:
5608         case SVM_EXIT_WRITE_DR0:
5609                 icpt_info.exit_code += info->modrm_reg;
5610                 break;
5611         case SVM_EXIT_MSR:
5612                 if (info->intercept == x86_intercept_wrmsr)
5613                         vmcb->control.exit_info_1 = 1;
5614                 else
5615                         vmcb->control.exit_info_1 = 0;
5616                 break;
5617         case SVM_EXIT_PAUSE:
5618                 /*
5619                  * We get this for NOP only, but pause
5620                  * is rep not, check this here
5621                  */
5622                 if (info->rep_prefix != REPE_PREFIX)
5623                         goto out;
5624                 break;
5625         case SVM_EXIT_IOIO: {
5626                 u64 exit_info;
5627                 u32 bytes;
5628
5629                 if (info->intercept == x86_intercept_in ||
5630                     info->intercept == x86_intercept_ins) {
5631                         exit_info = ((info->src_val & 0xffff) << 16) |
5632                                 SVM_IOIO_TYPE_MASK;
5633                         bytes = info->dst_bytes;
5634                 } else {
5635                         exit_info = (info->dst_val & 0xffff) << 16;
5636                         bytes = info->src_bytes;
5637                 }
5638
5639                 if (info->intercept == x86_intercept_outs ||
5640                     info->intercept == x86_intercept_ins)
5641                         exit_info |= SVM_IOIO_STR_MASK;
5642
5643                 if (info->rep_prefix)
5644                         exit_info |= SVM_IOIO_REP_MASK;
5645
5646                 bytes = min(bytes, 4u);
5647
5648                 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5649
5650                 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5651
5652                 vmcb->control.exit_info_1 = exit_info;
5653                 vmcb->control.exit_info_2 = info->next_rip;
5654
5655                 break;
5656         }
5657         default:
5658                 break;
5659         }
5660
5661         /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5662         if (static_cpu_has(X86_FEATURE_NRIPS))
5663                 vmcb->control.next_rip  = info->next_rip;
5664         vmcb->control.exit_code = icpt_info.exit_code;
5665         vmexit = nested_svm_exit_handled(svm);
5666
5667         ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5668                                            : X86EMUL_CONTINUE;
5669
5670 out:
5671         return ret;
5672 }
5673
5674 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
5675 {
5676         local_irq_enable();
5677         /*
5678          * We must have an instruction with interrupts enabled, so
5679          * the timer interrupt isn't delayed by the interrupt shadow.
5680          */
5681         asm("nop");
5682         local_irq_disable();
5683 }
5684
5685 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
5686 {
5687 }
5688
5689 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
5690 {
5691         if (avic_handle_apic_id_update(vcpu) != 0)
5692                 return;
5693         if (avic_handle_dfr_update(vcpu) != 0)
5694                 return;
5695         avic_handle_ldr_update(vcpu);
5696 }
5697
5698 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5699 {
5700         /* [63:9] are reserved. */
5701         vcpu->arch.mcg_cap &= 0x1ff;
5702 }
5703
5704 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
5705         .cpu_has_kvm_support = has_svm,
5706         .disabled_by_bios = is_disabled,
5707         .hardware_setup = svm_hardware_setup,
5708         .hardware_unsetup = svm_hardware_unsetup,
5709         .check_processor_compatibility = svm_check_processor_compat,
5710         .hardware_enable = svm_hardware_enable,
5711         .hardware_disable = svm_hardware_disable,
5712         .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
5713         .has_emulated_msr = svm_has_emulated_msr,
5714
5715         .vcpu_create = svm_create_vcpu,
5716         .vcpu_free = svm_free_vcpu,
5717         .vcpu_reset = svm_vcpu_reset,
5718
5719         .vm_init = avic_vm_init,
5720         .vm_destroy = avic_vm_destroy,
5721
5722         .prepare_guest_switch = svm_prepare_guest_switch,
5723         .vcpu_load = svm_vcpu_load,
5724         .vcpu_put = svm_vcpu_put,
5725         .vcpu_blocking = svm_vcpu_blocking,
5726         .vcpu_unblocking = svm_vcpu_unblocking,
5727
5728         .update_bp_intercept = update_bp_intercept,
5729         .get_msr_feature = svm_get_msr_feature,
5730         .get_msr = svm_get_msr,
5731         .set_msr = svm_set_msr,
5732         .get_segment_base = svm_get_segment_base,
5733         .get_segment = svm_get_segment,
5734         .set_segment = svm_set_segment,
5735         .get_cpl = svm_get_cpl,
5736         .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
5737         .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
5738         .decache_cr3 = svm_decache_cr3,
5739         .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
5740         .set_cr0 = svm_set_cr0,
5741         .set_cr3 = svm_set_cr3,
5742         .set_cr4 = svm_set_cr4,
5743         .set_efer = svm_set_efer,
5744         .get_idt = svm_get_idt,
5745         .set_idt = svm_set_idt,
5746         .get_gdt = svm_get_gdt,
5747         .set_gdt = svm_set_gdt,
5748         .get_dr6 = svm_get_dr6,
5749         .set_dr6 = svm_set_dr6,
5750         .set_dr7 = svm_set_dr7,
5751         .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
5752         .cache_reg = svm_cache_reg,
5753         .get_rflags = svm_get_rflags,
5754         .set_rflags = svm_set_rflags,
5755
5756         .tlb_flush = svm_flush_tlb,
5757
5758         .run = svm_vcpu_run,
5759         .handle_exit = handle_exit,
5760         .skip_emulated_instruction = skip_emulated_instruction,
5761         .set_interrupt_shadow = svm_set_interrupt_shadow,
5762         .get_interrupt_shadow = svm_get_interrupt_shadow,
5763         .patch_hypercall = svm_patch_hypercall,
5764         .set_irq = svm_set_irq,
5765         .set_nmi = svm_inject_nmi,
5766         .queue_exception = svm_queue_exception,
5767         .cancel_injection = svm_cancel_injection,
5768         .interrupt_allowed = svm_interrupt_allowed,
5769         .nmi_allowed = svm_nmi_allowed,
5770         .get_nmi_mask = svm_get_nmi_mask,
5771         .set_nmi_mask = svm_set_nmi_mask,
5772         .enable_nmi_window = enable_nmi_window,
5773         .enable_irq_window = enable_irq_window,
5774         .update_cr8_intercept = update_cr8_intercept,
5775         .set_virtual_apic_mode = svm_set_virtual_apic_mode,
5776         .get_enable_apicv = svm_get_enable_apicv,
5777         .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
5778         .load_eoi_exitmap = svm_load_eoi_exitmap,
5779         .hwapic_irr_update = svm_hwapic_irr_update,
5780         .hwapic_isr_update = svm_hwapic_isr_update,
5781         .apicv_post_state_restore = avic_post_state_restore,
5782
5783         .set_tss_addr = svm_set_tss_addr,
5784         .get_tdp_level = get_npt_level,
5785         .get_mt_mask = svm_get_mt_mask,
5786
5787         .get_exit_info = svm_get_exit_info,
5788
5789         .get_lpage_level = svm_get_lpage_level,
5790
5791         .cpuid_update = svm_cpuid_update,
5792
5793         .rdtscp_supported = svm_rdtscp_supported,
5794         .invpcid_supported = svm_invpcid_supported,
5795         .mpx_supported = svm_mpx_supported,
5796         .xsaves_supported = svm_xsaves_supported,
5797
5798         .set_supported_cpuid = svm_set_supported_cpuid,
5799
5800         .has_wbinvd_exit = svm_has_wbinvd_exit,
5801
5802         .write_tsc_offset = svm_write_tsc_offset,
5803
5804         .set_tdp_cr3 = set_tdp_cr3,
5805
5806         .check_intercept = svm_check_intercept,
5807         .handle_external_intr = svm_handle_external_intr,
5808
5809         .sched_in = svm_sched_in,
5810
5811         .pmu_ops = &amd_pmu_ops,
5812         .deliver_posted_interrupt = svm_deliver_avic_intr,
5813         .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
5814         .update_pi_irte = svm_update_pi_irte,
5815         .setup_mce = svm_setup_mce,
5816 };
5817
5818 static int __init svm_init(void)
5819 {
5820         return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
5821                         __alignof__(struct vcpu_svm), THIS_MODULE);
5822 }
5823
5824 static void __exit svm_exit(void)
5825 {
5826         kvm_exit();
5827 }
5828
5829 module_init(svm_init)
5830 module_exit(svm_exit)