OSDN Git Service

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