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