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