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