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