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