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