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