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