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