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