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