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