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