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