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