KVM: VMX: Always VMCLEAR in-use VMCSes during crash with kexec support
[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         return &kvm_svm->kvm;
1930 }
1931
1932 static void svm_vm_free(struct kvm *kvm)
1933 {
1934         vfree(to_kvm_svm(kvm));
1935 }
1936
1937 static void sev_vm_destroy(struct kvm *kvm)
1938 {
1939         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1940         struct list_head *head = &sev->regions_list;
1941         struct list_head *pos, *q;
1942
1943         if (!sev_guest(kvm))
1944                 return;
1945
1946         mutex_lock(&kvm->lock);
1947
1948         /*
1949          * if userspace was terminated before unregistering the memory regions
1950          * then lets unpin all the registered memory.
1951          */
1952         if (!list_empty(head)) {
1953                 list_for_each_safe(pos, q, head) {
1954                         __unregister_enc_region_locked(kvm,
1955                                 list_entry(pos, struct enc_region, list));
1956                 }
1957         }
1958
1959         mutex_unlock(&kvm->lock);
1960
1961         sev_unbind_asid(kvm, sev->handle);
1962         sev_asid_free(kvm);
1963 }
1964
1965 static void avic_vm_destroy(struct kvm *kvm)
1966 {
1967         unsigned long flags;
1968         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1969
1970         if (!avic)
1971                 return;
1972
1973         if (kvm_svm->avic_logical_id_table_page)
1974                 __free_page(kvm_svm->avic_logical_id_table_page);
1975         if (kvm_svm->avic_physical_id_table_page)
1976                 __free_page(kvm_svm->avic_physical_id_table_page);
1977
1978         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1979         hash_del(&kvm_svm->hnode);
1980         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1981 }
1982
1983 static void svm_vm_destroy(struct kvm *kvm)
1984 {
1985         avic_vm_destroy(kvm);
1986         sev_vm_destroy(kvm);
1987 }
1988
1989 static int avic_vm_init(struct kvm *kvm)
1990 {
1991         unsigned long flags;
1992         int err = -ENOMEM;
1993         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1994         struct kvm_svm *k2;
1995         struct page *p_page;
1996         struct page *l_page;
1997         u32 vm_id;
1998
1999         if (!avic)
2000                 return 0;
2001
2002         /* Allocating physical APIC ID table (4KB) */
2003         p_page = alloc_page(GFP_KERNEL_ACCOUNT);
2004         if (!p_page)
2005                 goto free_avic;
2006
2007         kvm_svm->avic_physical_id_table_page = p_page;
2008         clear_page(page_address(p_page));
2009
2010         /* Allocating logical APIC ID table (4KB) */
2011         l_page = alloc_page(GFP_KERNEL_ACCOUNT);
2012         if (!l_page)
2013                 goto free_avic;
2014
2015         kvm_svm->avic_logical_id_table_page = l_page;
2016         clear_page(page_address(l_page));
2017
2018         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2019  again:
2020         vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
2021         if (vm_id == 0) { /* id is 1-based, zero is not okay */
2022                 next_vm_id_wrapped = 1;
2023                 goto again;
2024         }
2025         /* Is it still in use? Only possible if wrapped at least once */
2026         if (next_vm_id_wrapped) {
2027                 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
2028                         if (k2->avic_vm_id == vm_id)
2029                                 goto again;
2030                 }
2031         }
2032         kvm_svm->avic_vm_id = vm_id;
2033         hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
2034         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2035
2036         return 0;
2037
2038 free_avic:
2039         avic_vm_destroy(kvm);
2040         return err;
2041 }
2042
2043 static inline int
2044 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
2045 {
2046         int ret = 0;
2047         unsigned long flags;
2048         struct amd_svm_iommu_ir *ir;
2049         struct vcpu_svm *svm = to_svm(vcpu);
2050
2051         if (!kvm_arch_has_assigned_device(vcpu->kvm))
2052                 return 0;
2053
2054         /*
2055          * Here, we go through the per-vcpu ir_list to update all existing
2056          * interrupt remapping table entry targeting this vcpu.
2057          */
2058         spin_lock_irqsave(&svm->ir_list_lock, flags);
2059
2060         if (list_empty(&svm->ir_list))
2061                 goto out;
2062
2063         list_for_each_entry(ir, &svm->ir_list, node) {
2064                 ret = amd_iommu_update_ga(cpu, r, ir->data);
2065                 if (ret)
2066                         break;
2067         }
2068 out:
2069         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2070         return ret;
2071 }
2072
2073 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2074 {
2075         u64 entry;
2076         /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2077         int h_physical_id = kvm_cpu_get_apicid(cpu);
2078         struct vcpu_svm *svm = to_svm(vcpu);
2079
2080         if (!kvm_vcpu_apicv_active(vcpu))
2081                 return;
2082
2083         /*
2084          * Since the host physical APIC id is 8 bits,
2085          * we can support host APIC ID upto 255.
2086          */
2087         if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
2088                 return;
2089
2090         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2091         WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2092
2093         entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2094         entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2095
2096         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2097         if (svm->avic_is_running)
2098                 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2099
2100         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2101         avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2102                                         svm->avic_is_running);
2103 }
2104
2105 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2106 {
2107         u64 entry;
2108         struct vcpu_svm *svm = to_svm(vcpu);
2109
2110         if (!kvm_vcpu_apicv_active(vcpu))
2111                 return;
2112
2113         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2114         if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2115                 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2116
2117         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2118         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2119 }
2120
2121 /**
2122  * This function is called during VCPU halt/unhalt.
2123  */
2124 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2125 {
2126         struct vcpu_svm *svm = to_svm(vcpu);
2127
2128         svm->avic_is_running = is_run;
2129         if (is_run)
2130                 avic_vcpu_load(vcpu, vcpu->cpu);
2131         else
2132                 avic_vcpu_put(vcpu);
2133 }
2134
2135 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2136 {
2137         struct vcpu_svm *svm = to_svm(vcpu);
2138         u32 dummy;
2139         u32 eax = 1;
2140
2141         vcpu->arch.microcode_version = 0x01000065;
2142         svm->spec_ctrl = 0;
2143         svm->virt_spec_ctrl = 0;
2144
2145         if (!init_event) {
2146                 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2147                                            MSR_IA32_APICBASE_ENABLE;
2148                 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2149                         svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2150         }
2151         init_vmcb(svm);
2152
2153         kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2154         kvm_rdx_write(vcpu, eax);
2155
2156         if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2157                 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2158 }
2159
2160 static int avic_init_vcpu(struct vcpu_svm *svm)
2161 {
2162         int ret;
2163
2164         if (!kvm_vcpu_apicv_active(&svm->vcpu))
2165                 return 0;
2166
2167         ret = avic_init_backing_page(&svm->vcpu);
2168         if (ret)
2169                 return ret;
2170
2171         INIT_LIST_HEAD(&svm->ir_list);
2172         spin_lock_init(&svm->ir_list_lock);
2173         svm->dfr_reg = APIC_DFR_FLAT;
2174
2175         return ret;
2176 }
2177
2178 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
2179 {
2180         struct vcpu_svm *svm;
2181         struct page *page;
2182         struct page *msrpm_pages;
2183         struct page *hsave_page;
2184         struct page *nested_msrpm_pages;
2185         int err;
2186
2187         BUILD_BUG_ON_MSG(offsetof(struct vcpu_svm, vcpu) != 0,
2188                 "struct kvm_vcpu must be at offset 0 for arch usercopy region");
2189
2190         svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
2191         if (!svm) {
2192                 err = -ENOMEM;
2193                 goto out;
2194         }
2195
2196         svm->vcpu.arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
2197                                                      GFP_KERNEL_ACCOUNT);
2198         if (!svm->vcpu.arch.user_fpu) {
2199                 printk(KERN_ERR "kvm: failed to allocate kvm userspace's fpu\n");
2200                 err = -ENOMEM;
2201                 goto free_partial_svm;
2202         }
2203
2204         svm->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
2205                                                      GFP_KERNEL_ACCOUNT);
2206         if (!svm->vcpu.arch.guest_fpu) {
2207                 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
2208                 err = -ENOMEM;
2209                 goto free_user_fpu;
2210         }
2211
2212         err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2213         if (err)
2214                 goto free_svm;
2215
2216         err = -ENOMEM;
2217         page = alloc_page(GFP_KERNEL_ACCOUNT);
2218         if (!page)
2219                 goto uninit;
2220
2221         msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2222         if (!msrpm_pages)
2223                 goto free_page1;
2224
2225         nested_msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2226         if (!nested_msrpm_pages)
2227                 goto free_page2;
2228
2229         hsave_page = alloc_page(GFP_KERNEL_ACCOUNT);
2230         if (!hsave_page)
2231                 goto free_page3;
2232
2233         err = avic_init_vcpu(svm);
2234         if (err)
2235                 goto free_page4;
2236
2237         /* We initialize this flag to true to make sure that the is_running
2238          * bit would be set the first time the vcpu is loaded.
2239          */
2240         svm->avic_is_running = true;
2241
2242         svm->nested.hsave = page_address(hsave_page);
2243
2244         svm->msrpm = page_address(msrpm_pages);
2245         svm_vcpu_init_msrpm(svm->msrpm);
2246
2247         svm->nested.msrpm = page_address(nested_msrpm_pages);
2248         svm_vcpu_init_msrpm(svm->nested.msrpm);
2249
2250         svm->vmcb = page_address(page);
2251         clear_page(svm->vmcb);
2252         svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2253         svm->asid_generation = 0;
2254         init_vmcb(svm);
2255
2256         svm_init_osvw(&svm->vcpu);
2257
2258         return &svm->vcpu;
2259
2260 free_page4:
2261         __free_page(hsave_page);
2262 free_page3:
2263         __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2264 free_page2:
2265         __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2266 free_page1:
2267         __free_page(page);
2268 uninit:
2269         kvm_vcpu_uninit(&svm->vcpu);
2270 free_svm:
2271         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2272 free_user_fpu:
2273         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.user_fpu);
2274 free_partial_svm:
2275         kmem_cache_free(kvm_vcpu_cache, svm);
2276 out:
2277         return ERR_PTR(err);
2278 }
2279
2280 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2281 {
2282         int i;
2283
2284         for_each_online_cpu(i)
2285                 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2286 }
2287
2288 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2289 {
2290         struct vcpu_svm *svm = to_svm(vcpu);
2291
2292         /*
2293          * The vmcb page can be recycled, causing a false negative in
2294          * svm_vcpu_load(). So, ensure that no logical CPU has this
2295          * vmcb page recorded as its current vmcb.
2296          */
2297         svm_clear_current_vmcb(svm->vmcb);
2298
2299         __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2300         __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2301         __free_page(virt_to_page(svm->nested.hsave));
2302         __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2303         kvm_vcpu_uninit(vcpu);
2304         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.user_fpu);
2305         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2306         kmem_cache_free(kvm_vcpu_cache, svm);
2307 }
2308
2309 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2310 {
2311         struct vcpu_svm *svm = to_svm(vcpu);
2312         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2313         int i;
2314
2315         if (unlikely(cpu != vcpu->cpu)) {
2316                 svm->asid_generation = 0;
2317                 mark_all_dirty(svm->vmcb);
2318         }
2319
2320 #ifdef CONFIG_X86_64
2321         rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2322 #endif
2323         savesegment(fs, svm->host.fs);
2324         savesegment(gs, svm->host.gs);
2325         svm->host.ldt = kvm_read_ldt();
2326
2327         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2328                 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2329
2330         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2331                 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2332                 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2333                         __this_cpu_write(current_tsc_ratio, tsc_ratio);
2334                         wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2335                 }
2336         }
2337         /* This assumes that the kernel never uses MSR_TSC_AUX */
2338         if (static_cpu_has(X86_FEATURE_RDTSCP))
2339                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2340
2341         if (sd->current_vmcb != svm->vmcb) {
2342                 sd->current_vmcb = svm->vmcb;
2343                 indirect_branch_prediction_barrier();
2344         }
2345         avic_vcpu_load(vcpu, cpu);
2346 }
2347
2348 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2349 {
2350         struct vcpu_svm *svm = to_svm(vcpu);
2351         int i;
2352
2353         avic_vcpu_put(vcpu);
2354
2355         ++vcpu->stat.host_state_reload;
2356         kvm_load_ldt(svm->host.ldt);
2357 #ifdef CONFIG_X86_64
2358         loadsegment(fs, svm->host.fs);
2359         wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2360         load_gs_index(svm->host.gs);
2361 #else
2362 #ifdef CONFIG_X86_32_LAZY_GS
2363         loadsegment(gs, svm->host.gs);
2364 #endif
2365 #endif
2366         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2367                 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2368 }
2369
2370 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2371 {
2372         avic_set_running(vcpu, false);
2373 }
2374
2375 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2376 {
2377         avic_set_running(vcpu, true);
2378 }
2379
2380 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2381 {
2382         struct vcpu_svm *svm = to_svm(vcpu);
2383         unsigned long rflags = svm->vmcb->save.rflags;
2384
2385         if (svm->nmi_singlestep) {
2386                 /* Hide our flags if they were not set by the guest */
2387                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2388                         rflags &= ~X86_EFLAGS_TF;
2389                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2390                         rflags &= ~X86_EFLAGS_RF;
2391         }
2392         return rflags;
2393 }
2394
2395 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2396 {
2397         if (to_svm(vcpu)->nmi_singlestep)
2398                 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2399
2400        /*
2401         * Any change of EFLAGS.VM is accompanied by a reload of SS
2402         * (caused by either a task switch or an inter-privilege IRET),
2403         * so we do not need to update the CPL here.
2404         */
2405         to_svm(vcpu)->vmcb->save.rflags = rflags;
2406 }
2407
2408 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2409 {
2410         switch (reg) {
2411         case VCPU_EXREG_PDPTR:
2412                 BUG_ON(!npt_enabled);
2413                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2414                 break;
2415         default:
2416                 BUG();
2417         }
2418 }
2419
2420 static void svm_set_vintr(struct vcpu_svm *svm)
2421 {
2422         set_intercept(svm, INTERCEPT_VINTR);
2423 }
2424
2425 static void svm_clear_vintr(struct vcpu_svm *svm)
2426 {
2427         clr_intercept(svm, INTERCEPT_VINTR);
2428 }
2429
2430 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2431 {
2432         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2433
2434         switch (seg) {
2435         case VCPU_SREG_CS: return &save->cs;
2436         case VCPU_SREG_DS: return &save->ds;
2437         case VCPU_SREG_ES: return &save->es;
2438         case VCPU_SREG_FS: return &save->fs;
2439         case VCPU_SREG_GS: return &save->gs;
2440         case VCPU_SREG_SS: return &save->ss;
2441         case VCPU_SREG_TR: return &save->tr;
2442         case VCPU_SREG_LDTR: return &save->ldtr;
2443         }
2444         BUG();
2445         return NULL;
2446 }
2447
2448 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2449 {
2450         struct vmcb_seg *s = svm_seg(vcpu, seg);
2451
2452         return s->base;
2453 }
2454
2455 static void svm_get_segment(struct kvm_vcpu *vcpu,
2456                             struct kvm_segment *var, int seg)
2457 {
2458         struct vmcb_seg *s = svm_seg(vcpu, seg);
2459
2460         var->base = s->base;
2461         var->limit = s->limit;
2462         var->selector = s->selector;
2463         var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2464         var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2465         var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2466         var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2467         var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2468         var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2469         var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2470
2471         /*
2472          * AMD CPUs circa 2014 track the G bit for all segments except CS.
2473          * However, the SVM spec states that the G bit is not observed by the
2474          * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2475          * So let's synthesize a legal G bit for all segments, this helps
2476          * running KVM nested. It also helps cross-vendor migration, because
2477          * Intel's vmentry has a check on the 'G' bit.
2478          */
2479         var->g = s->limit > 0xfffff;
2480
2481         /*
2482          * AMD's VMCB does not have an explicit unusable field, so emulate it
2483          * for cross vendor migration purposes by "not present"
2484          */
2485         var->unusable = !var->present;
2486
2487         switch (seg) {
2488         case VCPU_SREG_TR:
2489                 /*
2490                  * Work around a bug where the busy flag in the tr selector
2491                  * isn't exposed
2492                  */
2493                 var->type |= 0x2;
2494                 break;
2495         case VCPU_SREG_DS:
2496         case VCPU_SREG_ES:
2497         case VCPU_SREG_FS:
2498         case VCPU_SREG_GS:
2499                 /*
2500                  * The accessed bit must always be set in the segment
2501                  * descriptor cache, although it can be cleared in the
2502                  * descriptor, the cached bit always remains at 1. Since
2503                  * Intel has a check on this, set it here to support
2504                  * cross-vendor migration.
2505                  */
2506                 if (!var->unusable)
2507                         var->type |= 0x1;
2508                 break;
2509         case VCPU_SREG_SS:
2510                 /*
2511                  * On AMD CPUs sometimes the DB bit in the segment
2512                  * descriptor is left as 1, although the whole segment has
2513                  * been made unusable. Clear it here to pass an Intel VMX
2514                  * entry check when cross vendor migrating.
2515                  */
2516                 if (var->unusable)
2517                         var->db = 0;
2518                 /* This is symmetric with svm_set_segment() */
2519                 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2520                 break;
2521         }
2522 }
2523
2524 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2525 {
2526         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2527
2528         return save->cpl;
2529 }
2530
2531 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2532 {
2533         struct vcpu_svm *svm = to_svm(vcpu);
2534
2535         dt->size = svm->vmcb->save.idtr.limit;
2536         dt->address = svm->vmcb->save.idtr.base;
2537 }
2538
2539 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2540 {
2541         struct vcpu_svm *svm = to_svm(vcpu);
2542
2543         svm->vmcb->save.idtr.limit = dt->size;
2544         svm->vmcb->save.idtr.base = dt->address ;
2545         mark_dirty(svm->vmcb, VMCB_DT);
2546 }
2547
2548 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2549 {
2550         struct vcpu_svm *svm = to_svm(vcpu);
2551
2552         dt->size = svm->vmcb->save.gdtr.limit;
2553         dt->address = svm->vmcb->save.gdtr.base;
2554 }
2555
2556 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2557 {
2558         struct vcpu_svm *svm = to_svm(vcpu);
2559
2560         svm->vmcb->save.gdtr.limit = dt->size;
2561         svm->vmcb->save.gdtr.base = dt->address ;
2562         mark_dirty(svm->vmcb, VMCB_DT);
2563 }
2564
2565 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2566 {
2567 }
2568
2569 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2570 {
2571 }
2572
2573 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2574 {
2575 }
2576
2577 static void update_cr0_intercept(struct vcpu_svm *svm)
2578 {
2579         ulong gcr0 = svm->vcpu.arch.cr0;
2580         u64 *hcr0 = &svm->vmcb->save.cr0;
2581
2582         *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2583                 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2584
2585         mark_dirty(svm->vmcb, VMCB_CR);
2586
2587         if (gcr0 == *hcr0) {
2588                 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2589                 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2590         } else {
2591                 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2592                 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2593         }
2594 }
2595
2596 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2597 {
2598         struct vcpu_svm *svm = to_svm(vcpu);
2599
2600 #ifdef CONFIG_X86_64
2601         if (vcpu->arch.efer & EFER_LME) {
2602                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2603                         vcpu->arch.efer |= EFER_LMA;
2604                         svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2605                 }
2606
2607                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2608                         vcpu->arch.efer &= ~EFER_LMA;
2609                         svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2610                 }
2611         }
2612 #endif
2613         vcpu->arch.cr0 = cr0;
2614
2615         if (!npt_enabled)
2616                 cr0 |= X86_CR0_PG | X86_CR0_WP;
2617
2618         /*
2619          * re-enable caching here because the QEMU bios
2620          * does not do it - this results in some delay at
2621          * reboot
2622          */
2623         if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2624                 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2625         svm->vmcb->save.cr0 = cr0;
2626         mark_dirty(svm->vmcb, VMCB_CR);
2627         update_cr0_intercept(svm);
2628 }
2629
2630 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2631 {
2632         unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2633         unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2634
2635         if (cr4 & X86_CR4_VMXE)
2636                 return 1;
2637
2638         if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2639                 svm_flush_tlb(vcpu, true);
2640
2641         vcpu->arch.cr4 = cr4;
2642         if (!npt_enabled)
2643                 cr4 |= X86_CR4_PAE;
2644         cr4 |= host_cr4_mce;
2645         to_svm(vcpu)->vmcb->save.cr4 = cr4;
2646         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2647         return 0;
2648 }
2649
2650 static void svm_set_segment(struct kvm_vcpu *vcpu,
2651                             struct kvm_segment *var, int seg)
2652 {
2653         struct vcpu_svm *svm = to_svm(vcpu);
2654         struct vmcb_seg *s = svm_seg(vcpu, seg);
2655
2656         s->base = var->base;
2657         s->limit = var->limit;
2658         s->selector = var->selector;
2659         s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2660         s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2661         s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2662         s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2663         s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2664         s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2665         s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2666         s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2667
2668         /*
2669          * This is always accurate, except if SYSRET returned to a segment
2670          * with SS.DPL != 3.  Intel does not have this quirk, and always
2671          * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2672          * would entail passing the CPL to userspace and back.
2673          */
2674         if (seg == VCPU_SREG_SS)
2675                 /* This is symmetric with svm_get_segment() */
2676                 svm->vmcb->save.cpl = (var->dpl & 3);
2677
2678         mark_dirty(svm->vmcb, VMCB_SEG);
2679 }
2680
2681 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2682 {
2683         struct vcpu_svm *svm = to_svm(vcpu);
2684
2685         clr_exception_intercept(svm, BP_VECTOR);
2686
2687         if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2688                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2689                         set_exception_intercept(svm, BP_VECTOR);
2690         } else
2691                 vcpu->guest_debug = 0;
2692 }
2693
2694 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2695 {
2696         if (sd->next_asid > sd->max_asid) {
2697                 ++sd->asid_generation;
2698                 sd->next_asid = sd->min_asid;
2699                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2700         }
2701
2702         svm->asid_generation = sd->asid_generation;
2703         svm->vmcb->control.asid = sd->next_asid++;
2704
2705         mark_dirty(svm->vmcb, VMCB_ASID);
2706 }
2707
2708 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2709 {
2710         return to_svm(vcpu)->vmcb->save.dr6;
2711 }
2712
2713 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2714 {
2715         struct vcpu_svm *svm = to_svm(vcpu);
2716
2717         svm->vmcb->save.dr6 = value;
2718         mark_dirty(svm->vmcb, VMCB_DR);
2719 }
2720
2721 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2722 {
2723         struct vcpu_svm *svm = to_svm(vcpu);
2724
2725         get_debugreg(vcpu->arch.db[0], 0);
2726         get_debugreg(vcpu->arch.db[1], 1);
2727         get_debugreg(vcpu->arch.db[2], 2);
2728         get_debugreg(vcpu->arch.db[3], 3);
2729         vcpu->arch.dr6 = svm_get_dr6(vcpu);
2730         vcpu->arch.dr7 = svm->vmcb->save.dr7;
2731
2732         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2733         set_dr_intercepts(svm);
2734 }
2735
2736 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2737 {
2738         struct vcpu_svm *svm = to_svm(vcpu);
2739
2740         svm->vmcb->save.dr7 = value;
2741         mark_dirty(svm->vmcb, VMCB_DR);
2742 }
2743
2744 static int pf_interception(struct vcpu_svm *svm)
2745 {
2746         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2747         u64 error_code = svm->vmcb->control.exit_info_1;
2748
2749         return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2750                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2751                         svm->vmcb->control.insn_bytes : NULL,
2752                         svm->vmcb->control.insn_len);
2753 }
2754
2755 static int npf_interception(struct vcpu_svm *svm)
2756 {
2757         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2758         u64 error_code = svm->vmcb->control.exit_info_1;
2759
2760         trace_kvm_page_fault(fault_address, error_code);
2761         return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2762                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2763                         svm->vmcb->control.insn_bytes : NULL,
2764                         svm->vmcb->control.insn_len);
2765 }
2766
2767 static int db_interception(struct vcpu_svm *svm)
2768 {
2769         struct kvm_run *kvm_run = svm->vcpu.run;
2770         struct kvm_vcpu *vcpu = &svm->vcpu;
2771
2772         if (!(svm->vcpu.guest_debug &
2773               (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2774                 !svm->nmi_singlestep) {
2775                 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2776                 return 1;
2777         }
2778
2779         if (svm->nmi_singlestep) {
2780                 disable_nmi_singlestep(svm);
2781                 /* Make sure we check for pending NMIs upon entry */
2782                 kvm_make_request(KVM_REQ_EVENT, vcpu);
2783         }
2784
2785         if (svm->vcpu.guest_debug &
2786             (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2787                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2788                 kvm_run->debug.arch.pc =
2789                         svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2790                 kvm_run->debug.arch.exception = DB_VECTOR;
2791                 return 0;
2792         }
2793
2794         return 1;
2795 }
2796
2797 static int bp_interception(struct vcpu_svm *svm)
2798 {
2799         struct kvm_run *kvm_run = svm->vcpu.run;
2800
2801         kvm_run->exit_reason = KVM_EXIT_DEBUG;
2802         kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2803         kvm_run->debug.arch.exception = BP_VECTOR;
2804         return 0;
2805 }
2806
2807 static int ud_interception(struct vcpu_svm *svm)
2808 {
2809         return handle_ud(&svm->vcpu);
2810 }
2811
2812 static int ac_interception(struct vcpu_svm *svm)
2813 {
2814         kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2815         return 1;
2816 }
2817
2818 static int gp_interception(struct vcpu_svm *svm)
2819 {
2820         struct kvm_vcpu *vcpu = &svm->vcpu;
2821         u32 error_code = svm->vmcb->control.exit_info_1;
2822
2823         WARN_ON_ONCE(!enable_vmware_backdoor);
2824
2825         /*
2826          * VMware backdoor emulation on #GP interception only handles IN{S},
2827          * OUT{S}, and RDPMC, none of which generate a non-zero error code.
2828          */
2829         if (error_code) {
2830                 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2831                 return 1;
2832         }
2833         return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
2834 }
2835
2836 static bool is_erratum_383(void)
2837 {
2838         int err, i;
2839         u64 value;
2840
2841         if (!erratum_383_found)
2842                 return false;
2843
2844         value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2845         if (err)
2846                 return false;
2847
2848         /* Bit 62 may or may not be set for this mce */
2849         value &= ~(1ULL << 62);
2850
2851         if (value != 0xb600000000010015ULL)
2852                 return false;
2853
2854         /* Clear MCi_STATUS registers */
2855         for (i = 0; i < 6; ++i)
2856                 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2857
2858         value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2859         if (!err) {
2860                 u32 low, high;
2861
2862                 value &= ~(1ULL << 2);
2863                 low    = lower_32_bits(value);
2864                 high   = upper_32_bits(value);
2865
2866                 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2867         }
2868
2869         /* Flush tlb to evict multi-match entries */
2870         __flush_tlb_all();
2871
2872         return true;
2873 }
2874
2875 static void svm_handle_mce(struct vcpu_svm *svm)
2876 {
2877         if (is_erratum_383()) {
2878                 /*
2879                  * Erratum 383 triggered. Guest state is corrupt so kill the
2880                  * guest.
2881                  */
2882                 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2883
2884                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2885
2886                 return;
2887         }
2888
2889         /*
2890          * On an #MC intercept the MCE handler is not called automatically in
2891          * the host. So do it by hand here.
2892          */
2893         asm volatile (
2894                 "int $0x12\n");
2895         /* not sure if we ever come back to this point */
2896
2897         return;
2898 }
2899
2900 static int mc_interception(struct vcpu_svm *svm)
2901 {
2902         return 1;
2903 }
2904
2905 static int shutdown_interception(struct vcpu_svm *svm)
2906 {
2907         struct kvm_run *kvm_run = svm->vcpu.run;
2908
2909         /*
2910          * VMCB is undefined after a SHUTDOWN intercept
2911          * so reinitialize it.
2912          */
2913         clear_page(svm->vmcb);
2914         init_vmcb(svm);
2915
2916         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2917         return 0;
2918 }
2919
2920 static int io_interception(struct vcpu_svm *svm)
2921 {
2922         struct kvm_vcpu *vcpu = &svm->vcpu;
2923         u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2924         int size, in, string;
2925         unsigned port;
2926
2927         ++svm->vcpu.stat.io_exits;
2928         string = (io_info & SVM_IOIO_STR_MASK) != 0;
2929         in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2930         if (string)
2931                 return kvm_emulate_instruction(vcpu, 0);
2932
2933         port = io_info >> 16;
2934         size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2935         svm->next_rip = svm->vmcb->control.exit_info_2;
2936
2937         return kvm_fast_pio(&svm->vcpu, size, port, in);
2938 }
2939
2940 static int nmi_interception(struct vcpu_svm *svm)
2941 {
2942         return 1;
2943 }
2944
2945 static int intr_interception(struct vcpu_svm *svm)
2946 {
2947         ++svm->vcpu.stat.irq_exits;
2948         return 1;
2949 }
2950
2951 static int nop_on_interception(struct vcpu_svm *svm)
2952 {
2953         return 1;
2954 }
2955
2956 static int halt_interception(struct vcpu_svm *svm)
2957 {
2958         return kvm_emulate_halt(&svm->vcpu);
2959 }
2960
2961 static int vmmcall_interception(struct vcpu_svm *svm)
2962 {
2963         return kvm_emulate_hypercall(&svm->vcpu);
2964 }
2965
2966 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2967 {
2968         struct vcpu_svm *svm = to_svm(vcpu);
2969
2970         return svm->nested.nested_cr3;
2971 }
2972
2973 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2974 {
2975         struct vcpu_svm *svm = to_svm(vcpu);
2976         u64 cr3 = svm->nested.nested_cr3;
2977         u64 pdpte;
2978         int ret;
2979
2980         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2981                                        offset_in_page(cr3) + index * 8, 8);
2982         if (ret)
2983                 return 0;
2984         return pdpte;
2985 }
2986
2987 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2988                                    unsigned long root)
2989 {
2990         struct vcpu_svm *svm = to_svm(vcpu);
2991
2992         svm->vmcb->control.nested_cr3 = __sme_set(root);
2993         mark_dirty(svm->vmcb, VMCB_NPT);
2994 }
2995
2996 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2997                                        struct x86_exception *fault)
2998 {
2999         struct vcpu_svm *svm = to_svm(vcpu);
3000
3001         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
3002                 /*
3003                  * TODO: track the cause of the nested page fault, and
3004                  * correctly fill in the high bits of exit_info_1.
3005                  */
3006                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
3007                 svm->vmcb->control.exit_code_hi = 0;
3008                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
3009                 svm->vmcb->control.exit_info_2 = fault->address;
3010         }
3011
3012         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
3013         svm->vmcb->control.exit_info_1 |= fault->error_code;
3014
3015         /*
3016          * The present bit is always zero for page structure faults on real
3017          * hardware.
3018          */
3019         if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
3020                 svm->vmcb->control.exit_info_1 &= ~1;
3021
3022         nested_svm_vmexit(svm);
3023 }
3024
3025 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
3026 {
3027         WARN_ON(mmu_is_nested(vcpu));
3028
3029         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
3030         kvm_init_shadow_mmu(vcpu);
3031         vcpu->arch.mmu->set_cr3           = nested_svm_set_tdp_cr3;
3032         vcpu->arch.mmu->get_cr3           = nested_svm_get_tdp_cr3;
3033         vcpu->arch.mmu->get_pdptr         = nested_svm_get_tdp_pdptr;
3034         vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
3035         vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
3036         reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
3037         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
3038 }
3039
3040 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
3041 {
3042         vcpu->arch.mmu = &vcpu->arch.root_mmu;
3043         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
3044 }
3045
3046 static int nested_svm_check_permissions(struct vcpu_svm *svm)
3047 {
3048         if (!(svm->vcpu.arch.efer & EFER_SVME) ||
3049             !is_paging(&svm->vcpu)) {
3050                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3051                 return 1;
3052         }
3053
3054         if (svm->vmcb->save.cpl) {
3055                 kvm_inject_gp(&svm->vcpu, 0);
3056                 return 1;
3057         }
3058
3059         return 0;
3060 }
3061
3062 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
3063                                       bool has_error_code, u32 error_code)
3064 {
3065         int vmexit;
3066
3067         if (!is_guest_mode(&svm->vcpu))
3068                 return 0;
3069
3070         vmexit = nested_svm_intercept(svm);
3071         if (vmexit != NESTED_EXIT_DONE)
3072                 return 0;
3073
3074         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
3075         svm->vmcb->control.exit_code_hi = 0;
3076         svm->vmcb->control.exit_info_1 = error_code;
3077
3078         /*
3079          * EXITINFO2 is undefined for all exception intercepts other
3080          * than #PF.
3081          */
3082         if (svm->vcpu.arch.exception.nested_apf)
3083                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3084         else if (svm->vcpu.arch.exception.has_payload)
3085                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
3086         else
3087                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3088
3089         svm->nested.exit_required = true;
3090         return vmexit;
3091 }
3092
3093 /* This function returns true if it is save to enable the irq window */
3094 static inline bool nested_svm_intr(struct vcpu_svm *svm)
3095 {
3096         if (!is_guest_mode(&svm->vcpu))
3097                 return true;
3098
3099         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3100                 return true;
3101
3102         if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3103                 return false;
3104
3105         /*
3106          * if vmexit was already requested (by intercepted exception
3107          * for instance) do not overwrite it with "external interrupt"
3108          * vmexit.
3109          */
3110         if (svm->nested.exit_required)
3111                 return false;
3112
3113         svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
3114         svm->vmcb->control.exit_info_1 = 0;
3115         svm->vmcb->control.exit_info_2 = 0;
3116
3117         if (svm->nested.intercept & 1ULL) {
3118                 /*
3119                  * The #vmexit can't be emulated here directly because this
3120                  * code path runs with irqs and preemption disabled. A
3121                  * #vmexit emulation might sleep. Only signal request for
3122                  * the #vmexit here.
3123                  */
3124                 svm->nested.exit_required = true;
3125                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3126                 return false;
3127         }
3128
3129         return true;
3130 }
3131
3132 /* This function returns true if it is save to enable the nmi window */
3133 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3134 {
3135         if (!is_guest_mode(&svm->vcpu))
3136                 return true;
3137
3138         if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3139                 return true;
3140
3141         svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3142         svm->nested.exit_required = true;
3143
3144         return false;
3145 }
3146
3147 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3148 {
3149         unsigned port, size, iopm_len;
3150         u16 val, mask;
3151         u8 start_bit;
3152         u64 gpa;
3153
3154         if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3155                 return NESTED_EXIT_HOST;
3156
3157         port = svm->vmcb->control.exit_info_1 >> 16;
3158         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3159                 SVM_IOIO_SIZE_SHIFT;
3160         gpa  = svm->nested.vmcb_iopm + (port / 8);
3161         start_bit = port % 8;
3162         iopm_len = (start_bit + size > 8) ? 2 : 1;
3163         mask = (0xf >> (4 - size)) << start_bit;
3164         val = 0;
3165
3166         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3167                 return NESTED_EXIT_DONE;
3168
3169         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3170 }
3171
3172 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3173 {
3174         u32 offset, msr, value;
3175         int write, mask;
3176
3177         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3178                 return NESTED_EXIT_HOST;
3179
3180         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3181         offset = svm_msrpm_offset(msr);
3182         write  = svm->vmcb->control.exit_info_1 & 1;
3183         mask   = 1 << ((2 * (msr & 0xf)) + write);
3184
3185         if (offset == MSR_INVALID)
3186                 return NESTED_EXIT_DONE;
3187
3188         /* Offset is in 32 bit units but need in 8 bit units */
3189         offset *= 4;
3190
3191         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3192                 return NESTED_EXIT_DONE;
3193
3194         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3195 }
3196
3197 /* DB exceptions for our internal use must not cause vmexit */
3198 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3199 {
3200         unsigned long dr6;
3201
3202         /* if we're not singlestepping, it's not ours */
3203         if (!svm->nmi_singlestep)
3204                 return NESTED_EXIT_DONE;
3205
3206         /* if it's not a singlestep exception, it's not ours */
3207         if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3208                 return NESTED_EXIT_DONE;
3209         if (!(dr6 & DR6_BS))
3210                 return NESTED_EXIT_DONE;
3211
3212         /* if the guest is singlestepping, it should get the vmexit */
3213         if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3214                 disable_nmi_singlestep(svm);
3215                 return NESTED_EXIT_DONE;
3216         }
3217
3218         /* it's ours, the nested hypervisor must not see this one */
3219         return NESTED_EXIT_HOST;
3220 }
3221
3222 static int nested_svm_exit_special(struct vcpu_svm *svm)
3223 {
3224         u32 exit_code = svm->vmcb->control.exit_code;
3225
3226         switch (exit_code) {
3227         case SVM_EXIT_INTR:
3228         case SVM_EXIT_NMI:
3229         case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3230                 return NESTED_EXIT_HOST;
3231         case SVM_EXIT_NPF:
3232                 /* For now we are always handling NPFs when using them */
3233                 if (npt_enabled)
3234                         return NESTED_EXIT_HOST;
3235                 break;
3236         case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3237                 /* When we're shadowing, trap PFs, but not async PF */
3238                 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3239                         return NESTED_EXIT_HOST;
3240                 break;
3241         default:
3242                 break;
3243         }
3244
3245         return NESTED_EXIT_CONTINUE;
3246 }
3247
3248 /*
3249  * If this function returns true, this #vmexit was already handled
3250  */
3251 static int nested_svm_intercept(struct vcpu_svm *svm)
3252 {
3253         u32 exit_code = svm->vmcb->control.exit_code;
3254         int vmexit = NESTED_EXIT_HOST;
3255
3256         switch (exit_code) {
3257         case SVM_EXIT_MSR:
3258                 vmexit = nested_svm_exit_handled_msr(svm);
3259                 break;
3260         case SVM_EXIT_IOIO:
3261                 vmexit = nested_svm_intercept_ioio(svm);
3262                 break;
3263         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3264                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3265                 if (svm->nested.intercept_cr & bit)
3266                         vmexit = NESTED_EXIT_DONE;
3267                 break;
3268         }
3269         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3270                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3271                 if (svm->nested.intercept_dr & bit)
3272                         vmexit = NESTED_EXIT_DONE;
3273                 break;
3274         }
3275         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3276                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3277                 if (svm->nested.intercept_exceptions & excp_bits) {
3278                         if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3279                                 vmexit = nested_svm_intercept_db(svm);
3280                         else
3281                                 vmexit = NESTED_EXIT_DONE;
3282                 }
3283                 /* async page fault always cause vmexit */
3284                 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3285                          svm->vcpu.arch.exception.nested_apf != 0)
3286                         vmexit = NESTED_EXIT_DONE;
3287                 break;
3288         }
3289         case SVM_EXIT_ERR: {
3290                 vmexit = NESTED_EXIT_DONE;
3291                 break;
3292         }
3293         default: {
3294                 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3295                 if (svm->nested.intercept & exit_bits)
3296                         vmexit = NESTED_EXIT_DONE;
3297         }
3298         }
3299
3300         return vmexit;
3301 }
3302
3303 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3304 {
3305         int vmexit;
3306
3307         vmexit = nested_svm_intercept(svm);
3308
3309         if (vmexit == NESTED_EXIT_DONE)
3310                 nested_svm_vmexit(svm);
3311
3312         return vmexit;
3313 }
3314
3315 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3316 {
3317         struct vmcb_control_area *dst  = &dst_vmcb->control;
3318         struct vmcb_control_area *from = &from_vmcb->control;
3319
3320         dst->intercept_cr         = from->intercept_cr;
3321         dst->intercept_dr         = from->intercept_dr;
3322         dst->intercept_exceptions = from->intercept_exceptions;
3323         dst->intercept            = from->intercept;
3324         dst->iopm_base_pa         = from->iopm_base_pa;
3325         dst->msrpm_base_pa        = from->msrpm_base_pa;
3326         dst->tsc_offset           = from->tsc_offset;
3327         dst->asid                 = from->asid;
3328         dst->tlb_ctl              = from->tlb_ctl;
3329         dst->int_ctl              = from->int_ctl;
3330         dst->int_vector           = from->int_vector;
3331         dst->int_state            = from->int_state;
3332         dst->exit_code            = from->exit_code;
3333         dst->exit_code_hi         = from->exit_code_hi;
3334         dst->exit_info_1          = from->exit_info_1;
3335         dst->exit_info_2          = from->exit_info_2;
3336         dst->exit_int_info        = from->exit_int_info;
3337         dst->exit_int_info_err    = from->exit_int_info_err;
3338         dst->nested_ctl           = from->nested_ctl;
3339         dst->event_inj            = from->event_inj;
3340         dst->event_inj_err        = from->event_inj_err;
3341         dst->nested_cr3           = from->nested_cr3;
3342         dst->virt_ext              = from->virt_ext;
3343         dst->pause_filter_count   = from->pause_filter_count;
3344         dst->pause_filter_thresh  = from->pause_filter_thresh;
3345 }
3346
3347 static int nested_svm_vmexit(struct vcpu_svm *svm)
3348 {
3349         int rc;
3350         struct vmcb *nested_vmcb;
3351         struct vmcb *hsave = svm->nested.hsave;
3352         struct vmcb *vmcb = svm->vmcb;
3353         struct kvm_host_map map;
3354
3355         trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3356                                        vmcb->control.exit_info_1,
3357                                        vmcb->control.exit_info_2,
3358                                        vmcb->control.exit_int_info,
3359                                        vmcb->control.exit_int_info_err,
3360                                        KVM_ISA_SVM);
3361
3362         rc = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->nested.vmcb), &map);
3363         if (rc) {
3364                 if (rc == -EINVAL)
3365                         kvm_inject_gp(&svm->vcpu, 0);
3366                 return 1;
3367         }
3368
3369         nested_vmcb = map.hva;
3370
3371         /* Exit Guest-Mode */
3372         leave_guest_mode(&svm->vcpu);
3373         svm->nested.vmcb = 0;
3374
3375         /* Give the current vmcb to the guest */
3376         disable_gif(svm);
3377
3378         nested_vmcb->save.es     = vmcb->save.es;
3379         nested_vmcb->save.cs     = vmcb->save.cs;
3380         nested_vmcb->save.ss     = vmcb->save.ss;
3381         nested_vmcb->save.ds     = vmcb->save.ds;
3382         nested_vmcb->save.gdtr   = vmcb->save.gdtr;
3383         nested_vmcb->save.idtr   = vmcb->save.idtr;
3384         nested_vmcb->save.efer   = svm->vcpu.arch.efer;
3385         nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
3386         nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
3387         nested_vmcb->save.cr2    = vmcb->save.cr2;
3388         nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
3389         nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3390         nested_vmcb->save.rip    = vmcb->save.rip;
3391         nested_vmcb->save.rsp    = vmcb->save.rsp;
3392         nested_vmcb->save.rax    = vmcb->save.rax;
3393         nested_vmcb->save.dr7    = vmcb->save.dr7;
3394         nested_vmcb->save.dr6    = vmcb->save.dr6;
3395         nested_vmcb->save.cpl    = vmcb->save.cpl;
3396
3397         nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
3398         nested_vmcb->control.int_vector        = vmcb->control.int_vector;
3399         nested_vmcb->control.int_state         = vmcb->control.int_state;
3400         nested_vmcb->control.exit_code         = vmcb->control.exit_code;
3401         nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
3402         nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
3403         nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
3404         nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
3405         nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3406
3407         if (svm->nrips_enabled)
3408                 nested_vmcb->control.next_rip  = vmcb->control.next_rip;
3409
3410         /*
3411          * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3412          * to make sure that we do not lose injected events. So check event_inj
3413          * here and copy it to exit_int_info if it is valid.
3414          * Exit_int_info and event_inj can't be both valid because the case
3415          * below only happens on a VMRUN instruction intercept which has
3416          * no valid exit_int_info set.
3417          */
3418         if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3419                 struct vmcb_control_area *nc = &nested_vmcb->control;
3420
3421                 nc->exit_int_info     = vmcb->control.event_inj;
3422                 nc->exit_int_info_err = vmcb->control.event_inj_err;
3423         }
3424
3425         nested_vmcb->control.tlb_ctl           = 0;
3426         nested_vmcb->control.event_inj         = 0;
3427         nested_vmcb->control.event_inj_err     = 0;
3428
3429         nested_vmcb->control.pause_filter_count =
3430                 svm->vmcb->control.pause_filter_count;
3431         nested_vmcb->control.pause_filter_thresh =
3432                 svm->vmcb->control.pause_filter_thresh;
3433
3434         /* We always set V_INTR_MASKING and remember the old value in hflags */
3435         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3436                 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3437
3438         /* Restore the original control entries */
3439         copy_vmcb_control_area(vmcb, hsave);
3440
3441         svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3442         kvm_clear_exception_queue(&svm->vcpu);
3443         kvm_clear_interrupt_queue(&svm->vcpu);
3444
3445         svm->nested.nested_cr3 = 0;
3446
3447         /* Restore selected save entries */
3448         svm->vmcb->save.es = hsave->save.es;
3449         svm->vmcb->save.cs = hsave->save.cs;
3450         svm->vmcb->save.ss = hsave->save.ss;
3451         svm->vmcb->save.ds = hsave->save.ds;
3452         svm->vmcb->save.gdtr = hsave->save.gdtr;
3453         svm->vmcb->save.idtr = hsave->save.idtr;
3454         kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3455         svm_set_efer(&svm->vcpu, hsave->save.efer);
3456         svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3457         svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3458         if (npt_enabled) {
3459                 svm->vmcb->save.cr3 = hsave->save.cr3;
3460                 svm->vcpu.arch.cr3 = hsave->save.cr3;
3461         } else {
3462                 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3463         }
3464         kvm_rax_write(&svm->vcpu, hsave->save.rax);
3465         kvm_rsp_write(&svm->vcpu, hsave->save.rsp);
3466         kvm_rip_write(&svm->vcpu, hsave->save.rip);
3467         svm->vmcb->save.dr7 = 0;
3468         svm->vmcb->save.cpl = 0;
3469         svm->vmcb->control.exit_int_info = 0;
3470
3471         mark_all_dirty(svm->vmcb);
3472
3473         kvm_vcpu_unmap(&svm->vcpu, &map, true);
3474
3475         nested_svm_uninit_mmu_context(&svm->vcpu);
3476         kvm_mmu_reset_context(&svm->vcpu);
3477         kvm_mmu_load(&svm->vcpu);
3478
3479         /*
3480          * Drop what we picked up for L2 via svm_complete_interrupts() so it
3481          * doesn't end up in L1.
3482          */
3483         svm->vcpu.arch.nmi_injected = false;
3484         kvm_clear_exception_queue(&svm->vcpu);
3485         kvm_clear_interrupt_queue(&svm->vcpu);
3486
3487         return 0;
3488 }
3489
3490 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3491 {
3492         /*
3493          * This function merges the msr permission bitmaps of kvm and the
3494          * nested vmcb. It is optimized in that it only merges the parts where
3495          * the kvm msr permission bitmap may contain zero bits
3496          */
3497         int i;
3498
3499         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3500                 return true;
3501
3502         for (i = 0; i < MSRPM_OFFSETS; i++) {
3503                 u32 value, p;
3504                 u64 offset;
3505
3506                 if (msrpm_offsets[i] == 0xffffffff)
3507                         break;
3508
3509                 p      = msrpm_offsets[i];
3510                 offset = svm->nested.vmcb_msrpm + (p * 4);
3511
3512                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3513                         return false;
3514
3515                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3516         }
3517
3518         svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3519
3520         return true;
3521 }
3522
3523 static bool nested_vmcb_checks(struct vmcb *vmcb)
3524 {
3525         if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3526                 return false;
3527
3528         if (vmcb->control.asid == 0)
3529                 return false;
3530
3531         if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3532             !npt_enabled)
3533                 return false;
3534
3535         return true;
3536 }
3537
3538 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3539                                  struct vmcb *nested_vmcb, struct kvm_host_map *map)
3540 {
3541         if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3542                 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3543         else
3544                 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3545
3546         if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3547                 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3548                 nested_svm_init_mmu_context(&svm->vcpu);
3549         }
3550
3551         /* Load the nested guest state */
3552         svm->vmcb->save.es = nested_vmcb->save.es;
3553         svm->vmcb->save.cs = nested_vmcb->save.cs;
3554         svm->vmcb->save.ss = nested_vmcb->save.ss;
3555         svm->vmcb->save.ds = nested_vmcb->save.ds;
3556         svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3557         svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3558         kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3559         svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3560         svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3561         svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3562         if (npt_enabled) {
3563                 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3564                 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3565         } else
3566                 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3567
3568         /* Guest paging mode is active - reset mmu */
3569         kvm_mmu_reset_context(&svm->vcpu);
3570
3571         svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3572         kvm_rax_write(&svm->vcpu, nested_vmcb->save.rax);
3573         kvm_rsp_write(&svm->vcpu, nested_vmcb->save.rsp);
3574         kvm_rip_write(&svm->vcpu, nested_vmcb->save.rip);
3575
3576         /* In case we don't even reach vcpu_run, the fields are not updated */
3577         svm->vmcb->save.rax = nested_vmcb->save.rax;
3578         svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3579         svm->vmcb->save.rip = nested_vmcb->save.rip;
3580         svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3581         svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3582         svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3583
3584         svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3585         svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
3586
3587         /* cache intercepts */
3588         svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
3589         svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
3590         svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3591         svm->nested.intercept            = nested_vmcb->control.intercept;
3592
3593         svm_flush_tlb(&svm->vcpu, true);
3594         svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3595         if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3596                 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3597         else
3598                 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3599
3600         if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3601                 /* We only want the cr8 intercept bits of the guest */
3602                 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3603                 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3604         }
3605
3606         /* We don't want to see VMMCALLs from a nested guest */
3607         clr_intercept(svm, INTERCEPT_VMMCALL);
3608
3609         svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3610         svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3611
3612         svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3613         svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3614         svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3615         svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3616         svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3617
3618         svm->vmcb->control.pause_filter_count =
3619                 nested_vmcb->control.pause_filter_count;
3620         svm->vmcb->control.pause_filter_thresh =
3621                 nested_vmcb->control.pause_filter_thresh;
3622
3623         kvm_vcpu_unmap(&svm->vcpu, map, true);
3624
3625         /* Enter Guest-Mode */
3626         enter_guest_mode(&svm->vcpu);
3627
3628         /*
3629          * Merge guest and host intercepts - must be called  with vcpu in
3630          * guest-mode to take affect here
3631          */
3632         recalc_intercepts(svm);
3633
3634         svm->nested.vmcb = vmcb_gpa;
3635
3636         enable_gif(svm);
3637
3638         mark_all_dirty(svm->vmcb);
3639 }
3640
3641 static int nested_svm_vmrun(struct vcpu_svm *svm)
3642 {
3643         int ret;
3644         struct vmcb *nested_vmcb;
3645         struct vmcb *hsave = svm->nested.hsave;
3646         struct vmcb *vmcb = svm->vmcb;
3647         struct kvm_host_map map;
3648         u64 vmcb_gpa;
3649
3650         vmcb_gpa = svm->vmcb->save.rax;
3651
3652         ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb_gpa), &map);
3653         if (ret == -EINVAL) {
3654                 kvm_inject_gp(&svm->vcpu, 0);
3655                 return 1;
3656         } else if (ret) {
3657                 return kvm_skip_emulated_instruction(&svm->vcpu);
3658         }
3659
3660         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3661
3662         nested_vmcb = map.hva;
3663
3664         if (!nested_vmcb_checks(nested_vmcb)) {
3665                 nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
3666                 nested_vmcb->control.exit_code_hi = 0;
3667                 nested_vmcb->control.exit_info_1  = 0;
3668                 nested_vmcb->control.exit_info_2  = 0;
3669
3670                 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3671
3672                 return ret;
3673         }
3674
3675         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3676                                nested_vmcb->save.rip,
3677                                nested_vmcb->control.int_ctl,
3678                                nested_vmcb->control.event_inj,
3679                                nested_vmcb->control.nested_ctl);
3680
3681         trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3682                                     nested_vmcb->control.intercept_cr >> 16,
3683                                     nested_vmcb->control.intercept_exceptions,
3684                                     nested_vmcb->control.intercept);
3685
3686         /* Clear internal status */
3687         kvm_clear_exception_queue(&svm->vcpu);
3688         kvm_clear_interrupt_queue(&svm->vcpu);
3689
3690         /*
3691          * Save the old vmcb, so we don't need to pick what we save, but can
3692          * restore everything when a VMEXIT occurs
3693          */
3694         hsave->save.es     = vmcb->save.es;
3695         hsave->save.cs     = vmcb->save.cs;
3696         hsave->save.ss     = vmcb->save.ss;
3697         hsave->save.ds     = vmcb->save.ds;
3698         hsave->save.gdtr   = vmcb->save.gdtr;
3699         hsave->save.idtr   = vmcb->save.idtr;
3700         hsave->save.efer   = svm->vcpu.arch.efer;
3701         hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
3702         hsave->save.cr4    = svm->vcpu.arch.cr4;
3703         hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3704         hsave->save.rip    = kvm_rip_read(&svm->vcpu);
3705         hsave->save.rsp    = vmcb->save.rsp;
3706         hsave->save.rax    = vmcb->save.rax;
3707         if (npt_enabled)
3708                 hsave->save.cr3    = vmcb->save.cr3;
3709         else
3710                 hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
3711
3712         copy_vmcb_control_area(hsave, vmcb);
3713
3714         enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, &map);
3715
3716         if (!nested_svm_vmrun_msrpm(svm)) {
3717                 svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
3718                 svm->vmcb->control.exit_code_hi = 0;
3719                 svm->vmcb->control.exit_info_1  = 0;
3720                 svm->vmcb->control.exit_info_2  = 0;
3721
3722                 nested_svm_vmexit(svm);
3723         }
3724
3725         return ret;
3726 }
3727
3728 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3729 {
3730         to_vmcb->save.fs = from_vmcb->save.fs;
3731         to_vmcb->save.gs = from_vmcb->save.gs;
3732         to_vmcb->save.tr = from_vmcb->save.tr;
3733         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3734         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3735         to_vmcb->save.star = from_vmcb->save.star;
3736         to_vmcb->save.lstar = from_vmcb->save.lstar;
3737         to_vmcb->save.cstar = from_vmcb->save.cstar;
3738         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3739         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3740         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3741         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3742 }
3743
3744 static int vmload_interception(struct vcpu_svm *svm)
3745 {
3746         struct vmcb *nested_vmcb;
3747         struct kvm_host_map map;
3748         int ret;
3749
3750         if (nested_svm_check_permissions(svm))
3751                 return 1;
3752
3753         ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3754         if (ret) {
3755                 if (ret == -EINVAL)
3756                         kvm_inject_gp(&svm->vcpu, 0);
3757                 return 1;
3758         }
3759
3760         nested_vmcb = map.hva;
3761
3762         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3763
3764         nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3765         kvm_vcpu_unmap(&svm->vcpu, &map, true);
3766
3767         return ret;
3768 }
3769
3770 static int vmsave_interception(struct vcpu_svm *svm)
3771 {
3772         struct vmcb *nested_vmcb;
3773         struct kvm_host_map map;
3774         int ret;
3775
3776         if (nested_svm_check_permissions(svm))
3777                 return 1;
3778
3779         ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3780         if (ret) {
3781                 if (ret == -EINVAL)
3782                         kvm_inject_gp(&svm->vcpu, 0);
3783                 return 1;
3784         }
3785
3786         nested_vmcb = map.hva;
3787
3788         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3789
3790         nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3791         kvm_vcpu_unmap(&svm->vcpu, &map, true);
3792
3793         return ret;
3794 }
3795
3796 static int vmrun_interception(struct vcpu_svm *svm)
3797 {
3798         if (nested_svm_check_permissions(svm))
3799                 return 1;
3800
3801         return nested_svm_vmrun(svm);
3802 }
3803
3804 static int stgi_interception(struct vcpu_svm *svm)
3805 {
3806         int ret;
3807
3808         if (nested_svm_check_permissions(svm))
3809                 return 1;
3810
3811         /*
3812          * If VGIF is enabled, the STGI intercept is only added to
3813          * detect the opening of the SMI/NMI window; remove it now.
3814          */
3815         if (vgif_enabled(svm))
3816                 clr_intercept(svm, INTERCEPT_STGI);
3817
3818         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3819         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3820
3821         enable_gif(svm);
3822
3823         return ret;
3824 }
3825
3826 static int clgi_interception(struct vcpu_svm *svm)
3827 {
3828         int ret;
3829
3830         if (nested_svm_check_permissions(svm))
3831                 return 1;
3832
3833         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3834
3835         disable_gif(svm);
3836
3837         /* After a CLGI no interrupts should come */
3838         if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3839                 svm_clear_vintr(svm);
3840                 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3841                 mark_dirty(svm->vmcb, VMCB_INTR);
3842         }
3843
3844         return ret;
3845 }
3846
3847 static int invlpga_interception(struct vcpu_svm *svm)
3848 {
3849         struct kvm_vcpu *vcpu = &svm->vcpu;
3850
3851         trace_kvm_invlpga(svm->vmcb->save.rip, kvm_rcx_read(&svm->vcpu),
3852                           kvm_rax_read(&svm->vcpu));
3853
3854         /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3855         kvm_mmu_invlpg(vcpu, kvm_rax_read(&svm->vcpu));
3856
3857         return kvm_skip_emulated_instruction(&svm->vcpu);
3858 }
3859
3860 static int skinit_interception(struct vcpu_svm *svm)
3861 {
3862         trace_kvm_skinit(svm->vmcb->save.rip, kvm_rax_read(&svm->vcpu));
3863
3864         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3865         return 1;
3866 }
3867
3868 static int wbinvd_interception(struct vcpu_svm *svm)
3869 {
3870         return kvm_emulate_wbinvd(&svm->vcpu);
3871 }
3872
3873 static int xsetbv_interception(struct vcpu_svm *svm)
3874 {
3875         u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3876         u32 index = kvm_rcx_read(&svm->vcpu);
3877
3878         if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3879                 return kvm_skip_emulated_instruction(&svm->vcpu);
3880         }
3881
3882         return 1;
3883 }
3884
3885 static int rdpru_interception(struct vcpu_svm *svm)
3886 {
3887         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3888         return 1;
3889 }
3890
3891 static int task_switch_interception(struct vcpu_svm *svm)
3892 {
3893         u16 tss_selector;
3894         int reason;
3895         int int_type = svm->vmcb->control.exit_int_info &
3896                 SVM_EXITINTINFO_TYPE_MASK;
3897         int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3898         uint32_t type =
3899                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3900         uint32_t idt_v =
3901                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3902         bool has_error_code = false;
3903         u32 error_code = 0;
3904
3905         tss_selector = (u16)svm->vmcb->control.exit_info_1;
3906
3907         if (svm->vmcb->control.exit_info_2 &
3908             (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3909                 reason = TASK_SWITCH_IRET;
3910         else if (svm->vmcb->control.exit_info_2 &
3911                  (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3912                 reason = TASK_SWITCH_JMP;
3913         else if (idt_v)
3914                 reason = TASK_SWITCH_GATE;
3915         else
3916                 reason = TASK_SWITCH_CALL;
3917
3918         if (reason == TASK_SWITCH_GATE) {
3919                 switch (type) {
3920                 case SVM_EXITINTINFO_TYPE_NMI:
3921                         svm->vcpu.arch.nmi_injected = false;
3922                         break;
3923                 case SVM_EXITINTINFO_TYPE_EXEPT:
3924                         if (svm->vmcb->control.exit_info_2 &
3925                             (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3926                                 has_error_code = true;
3927                                 error_code =
3928                                         (u32)svm->vmcb->control.exit_info_2;
3929                         }
3930                         kvm_clear_exception_queue(&svm->vcpu);
3931                         break;
3932                 case SVM_EXITINTINFO_TYPE_INTR:
3933                         kvm_clear_interrupt_queue(&svm->vcpu);
3934                         break;
3935                 default:
3936                         break;
3937                 }
3938         }
3939
3940         if (reason != TASK_SWITCH_GATE ||
3941             int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3942             (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3943              (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
3944                 if (!skip_emulated_instruction(&svm->vcpu))
3945                         return 0;
3946         }
3947
3948         if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3949                 int_vec = -1;
3950
3951         return kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3952                                has_error_code, error_code);
3953 }
3954
3955 static int cpuid_interception(struct vcpu_svm *svm)
3956 {
3957         return kvm_emulate_cpuid(&svm->vcpu);
3958 }
3959
3960 static int iret_interception(struct vcpu_svm *svm)
3961 {
3962         ++svm->vcpu.stat.nmi_window_exits;
3963         clr_intercept(svm, INTERCEPT_IRET);
3964         svm->vcpu.arch.hflags |= HF_IRET_MASK;
3965         svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3966         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3967         return 1;
3968 }
3969
3970 static int invlpg_interception(struct vcpu_svm *svm)
3971 {
3972         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3973                 return kvm_emulate_instruction(&svm->vcpu, 0);
3974
3975         kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3976         return kvm_skip_emulated_instruction(&svm->vcpu);
3977 }
3978
3979 static int emulate_on_interception(struct vcpu_svm *svm)
3980 {
3981         return kvm_emulate_instruction(&svm->vcpu, 0);
3982 }
3983
3984 static int rsm_interception(struct vcpu_svm *svm)
3985 {
3986         return kvm_emulate_instruction_from_buffer(&svm->vcpu, rsm_ins_bytes, 2);
3987 }
3988
3989 static int rdpmc_interception(struct vcpu_svm *svm)
3990 {
3991         int err;
3992
3993         if (!nrips)
3994                 return emulate_on_interception(svm);
3995
3996         err = kvm_rdpmc(&svm->vcpu);
3997         return kvm_complete_insn_gp(&svm->vcpu, err);
3998 }
3999
4000 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
4001                                             unsigned long val)
4002 {
4003         unsigned long cr0 = svm->vcpu.arch.cr0;
4004         bool ret = false;
4005         u64 intercept;
4006
4007         intercept = svm->nested.intercept;
4008
4009         if (!is_guest_mode(&svm->vcpu) ||
4010             (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
4011                 return false;
4012
4013         cr0 &= ~SVM_CR0_SELECTIVE_MASK;
4014         val &= ~SVM_CR0_SELECTIVE_MASK;
4015
4016         if (cr0 ^ val) {
4017                 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4018                 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
4019         }
4020
4021         return ret;
4022 }
4023
4024 #define CR_VALID (1ULL << 63)
4025
4026 static int cr_interception(struct vcpu_svm *svm)
4027 {
4028         int reg, cr;
4029         unsigned long val;
4030         int err;
4031
4032         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
4033                 return emulate_on_interception(svm);
4034
4035         if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
4036                 return emulate_on_interception(svm);
4037
4038         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4039         if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
4040                 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
4041         else
4042                 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
4043
4044         err = 0;
4045         if (cr >= 16) { /* mov to cr */
4046                 cr -= 16;
4047                 val = kvm_register_read(&svm->vcpu, reg);
4048                 switch (cr) {
4049                 case 0:
4050                         if (!check_selective_cr0_intercepted(svm, val))
4051                                 err = kvm_set_cr0(&svm->vcpu, val);
4052                         else
4053                                 return 1;
4054
4055                         break;
4056                 case 3:
4057                         err = kvm_set_cr3(&svm->vcpu, val);
4058                         break;
4059                 case 4:
4060                         err = kvm_set_cr4(&svm->vcpu, val);
4061                         break;
4062                 case 8:
4063                         err = kvm_set_cr8(&svm->vcpu, val);
4064                         break;
4065                 default:
4066                         WARN(1, "unhandled write to CR%d", cr);
4067                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4068                         return 1;
4069                 }
4070         } else { /* mov from cr */
4071                 switch (cr) {
4072                 case 0:
4073                         val = kvm_read_cr0(&svm->vcpu);
4074                         break;
4075                 case 2:
4076                         val = svm->vcpu.arch.cr2;
4077                         break;
4078                 case 3:
4079                         val = kvm_read_cr3(&svm->vcpu);
4080                         break;
4081                 case 4:
4082                         val = kvm_read_cr4(&svm->vcpu);
4083                         break;
4084                 case 8:
4085                         val = kvm_get_cr8(&svm->vcpu);
4086                         break;
4087                 default:
4088                         WARN(1, "unhandled read from CR%d", cr);
4089                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4090                         return 1;
4091                 }
4092                 kvm_register_write(&svm->vcpu, reg, val);
4093         }
4094         return kvm_complete_insn_gp(&svm->vcpu, err);
4095 }
4096
4097 static int dr_interception(struct vcpu_svm *svm)
4098 {
4099         int reg, dr;
4100         unsigned long val;
4101
4102         if (svm->vcpu.guest_debug == 0) {
4103                 /*
4104                  * No more DR vmexits; force a reload of the debug registers
4105                  * and reenter on this instruction.  The next vmexit will
4106                  * retrieve the full state of the debug registers.
4107                  */
4108                 clr_dr_intercepts(svm);
4109                 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4110                 return 1;
4111         }
4112
4113         if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4114                 return emulate_on_interception(svm);
4115
4116         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4117         dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4118
4119         if (dr >= 16) { /* mov to DRn */
4120                 if (!kvm_require_dr(&svm->vcpu, dr - 16))
4121                         return 1;
4122                 val = kvm_register_read(&svm->vcpu, reg);
4123                 kvm_set_dr(&svm->vcpu, dr - 16, val);
4124         } else {
4125                 if (!kvm_require_dr(&svm->vcpu, dr))
4126                         return 1;
4127                 kvm_get_dr(&svm->vcpu, dr, &val);
4128                 kvm_register_write(&svm->vcpu, reg, val);
4129         }
4130
4131         return kvm_skip_emulated_instruction(&svm->vcpu);
4132 }
4133
4134 static int cr8_write_interception(struct vcpu_svm *svm)
4135 {
4136         struct kvm_run *kvm_run = svm->vcpu.run;
4137         int r;
4138
4139         u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4140         /* instruction emulation calls kvm_set_cr8() */
4141         r = cr_interception(svm);
4142         if (lapic_in_kernel(&svm->vcpu))
4143                 return r;
4144         if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4145                 return r;
4146         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4147         return 0;
4148 }
4149
4150 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4151 {
4152         msr->data = 0;
4153
4154         switch (msr->index) {
4155         case MSR_F10H_DECFG:
4156                 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4157                         msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4158                 break;
4159         default:
4160                 return 1;
4161         }
4162
4163         return 0;
4164 }
4165
4166 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4167 {
4168         struct vcpu_svm *svm = to_svm(vcpu);
4169
4170         switch (msr_info->index) {
4171         case MSR_STAR:
4172                 msr_info->data = svm->vmcb->save.star;
4173                 break;
4174 #ifdef CONFIG_X86_64
4175         case MSR_LSTAR:
4176                 msr_info->data = svm->vmcb->save.lstar;
4177                 break;
4178         case MSR_CSTAR:
4179                 msr_info->data = svm->vmcb->save.cstar;
4180                 break;
4181         case MSR_KERNEL_GS_BASE:
4182                 msr_info->data = svm->vmcb->save.kernel_gs_base;
4183                 break;
4184         case MSR_SYSCALL_MASK:
4185                 msr_info->data = svm->vmcb->save.sfmask;
4186                 break;
4187 #endif
4188         case MSR_IA32_SYSENTER_CS:
4189                 msr_info->data = svm->vmcb->save.sysenter_cs;
4190                 break;
4191         case MSR_IA32_SYSENTER_EIP:
4192                 msr_info->data = svm->sysenter_eip;
4193                 break;
4194         case MSR_IA32_SYSENTER_ESP:
4195                 msr_info->data = svm->sysenter_esp;
4196                 break;
4197         case MSR_TSC_AUX:
4198                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4199                         return 1;
4200                 msr_info->data = svm->tsc_aux;
4201                 break;
4202         /*
4203          * Nobody will change the following 5 values in the VMCB so we can
4204          * safely return them on rdmsr. They will always be 0 until LBRV is
4205          * implemented.
4206          */
4207         case MSR_IA32_DEBUGCTLMSR:
4208                 msr_info->data = svm->vmcb->save.dbgctl;
4209                 break;
4210         case MSR_IA32_LASTBRANCHFROMIP:
4211                 msr_info->data = svm->vmcb->save.br_from;
4212                 break;
4213         case MSR_IA32_LASTBRANCHTOIP:
4214                 msr_info->data = svm->vmcb->save.br_to;
4215                 break;
4216         case MSR_IA32_LASTINTFROMIP:
4217                 msr_info->data = svm->vmcb->save.last_excp_from;
4218                 break;
4219         case MSR_IA32_LASTINTTOIP:
4220                 msr_info->data = svm->vmcb->save.last_excp_to;
4221                 break;
4222         case MSR_VM_HSAVE_PA:
4223                 msr_info->data = svm->nested.hsave_msr;
4224                 break;
4225         case MSR_VM_CR:
4226                 msr_info->data = svm->nested.vm_cr_msr;
4227                 break;
4228         case MSR_IA32_SPEC_CTRL:
4229                 if (!msr_info->host_initiated &&
4230                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4231                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4232                         return 1;
4233
4234                 msr_info->data = svm->spec_ctrl;
4235                 break;
4236         case MSR_AMD64_VIRT_SPEC_CTRL:
4237                 if (!msr_info->host_initiated &&
4238                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4239                         return 1;
4240
4241                 msr_info->data = svm->virt_spec_ctrl;
4242                 break;
4243         case MSR_F15H_IC_CFG: {
4244
4245                 int family, model;
4246
4247                 family = guest_cpuid_family(vcpu);
4248                 model  = guest_cpuid_model(vcpu);
4249
4250                 if (family < 0 || model < 0)
4251                         return kvm_get_msr_common(vcpu, msr_info);
4252
4253                 msr_info->data = 0;
4254
4255                 if (family == 0x15 &&
4256                     (model >= 0x2 && model < 0x20))
4257                         msr_info->data = 0x1E;
4258                 }
4259                 break;
4260         case MSR_F10H_DECFG:
4261                 msr_info->data = svm->msr_decfg;
4262                 break;
4263         default:
4264                 return kvm_get_msr_common(vcpu, msr_info);
4265         }
4266         return 0;
4267 }
4268
4269 static int rdmsr_interception(struct vcpu_svm *svm)
4270 {
4271         return kvm_emulate_rdmsr(&svm->vcpu);
4272 }
4273
4274 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4275 {
4276         struct vcpu_svm *svm = to_svm(vcpu);
4277         int svm_dis, chg_mask;
4278
4279         if (data & ~SVM_VM_CR_VALID_MASK)
4280                 return 1;
4281
4282         chg_mask = SVM_VM_CR_VALID_MASK;
4283
4284         if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4285                 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4286
4287         svm->nested.vm_cr_msr &= ~chg_mask;
4288         svm->nested.vm_cr_msr |= (data & chg_mask);
4289
4290         svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4291
4292         /* check for svm_disable while efer.svme is set */
4293         if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4294                 return 1;
4295
4296         return 0;
4297 }
4298
4299 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4300 {
4301         struct vcpu_svm *svm = to_svm(vcpu);
4302
4303         u32 ecx = msr->index;
4304         u64 data = msr->data;
4305         switch (ecx) {
4306         case MSR_IA32_CR_PAT:
4307                 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4308                         return 1;
4309                 vcpu->arch.pat = data;
4310                 svm->vmcb->save.g_pat = data;
4311                 mark_dirty(svm->vmcb, VMCB_NPT);
4312                 break;
4313         case MSR_IA32_SPEC_CTRL:
4314                 if (!msr->host_initiated &&
4315                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4316                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4317                         return 1;
4318
4319                 /* The STIBP bit doesn't fault even if it's not advertised */
4320                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4321                         return 1;
4322
4323                 svm->spec_ctrl = data;
4324
4325                 if (!data)
4326                         break;
4327
4328                 /*
4329                  * For non-nested:
4330                  * When it's written (to non-zero) for the first time, pass
4331                  * it through.
4332                  *
4333                  * For nested:
4334                  * The handling of the MSR bitmap for L2 guests is done in
4335                  * nested_svm_vmrun_msrpm.
4336                  * We update the L1 MSR bit as well since it will end up
4337                  * touching the MSR anyway now.
4338                  */
4339                 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4340                 break;
4341         case MSR_IA32_PRED_CMD:
4342                 if (!msr->host_initiated &&
4343                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4344                         return 1;
4345
4346                 if (data & ~PRED_CMD_IBPB)
4347                         return 1;
4348
4349                 if (!data)
4350                         break;
4351
4352                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4353                 if (is_guest_mode(vcpu))
4354                         break;
4355                 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4356                 break;
4357         case MSR_AMD64_VIRT_SPEC_CTRL:
4358                 if (!msr->host_initiated &&
4359                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4360                         return 1;
4361
4362                 if (data & ~SPEC_CTRL_SSBD)
4363                         return 1;
4364
4365                 svm->virt_spec_ctrl = data;
4366                 break;
4367         case MSR_STAR:
4368                 svm->vmcb->save.star = data;
4369                 break;
4370 #ifdef CONFIG_X86_64
4371         case MSR_LSTAR:
4372                 svm->vmcb->save.lstar = data;
4373                 break;
4374         case MSR_CSTAR:
4375                 svm->vmcb->save.cstar = data;
4376                 break;
4377         case MSR_KERNEL_GS_BASE:
4378                 svm->vmcb->save.kernel_gs_base = data;
4379                 break;
4380         case MSR_SYSCALL_MASK:
4381                 svm->vmcb->save.sfmask = data;
4382                 break;
4383 #endif
4384         case MSR_IA32_SYSENTER_CS:
4385                 svm->vmcb->save.sysenter_cs = data;
4386                 break;
4387         case MSR_IA32_SYSENTER_EIP:
4388                 svm->sysenter_eip = data;
4389                 svm->vmcb->save.sysenter_eip = data;
4390                 break;
4391         case MSR_IA32_SYSENTER_ESP:
4392                 svm->sysenter_esp = data;
4393                 svm->vmcb->save.sysenter_esp = data;
4394                 break;
4395         case MSR_TSC_AUX:
4396                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4397                         return 1;
4398
4399                 /*
4400                  * This is rare, so we update the MSR here instead of using
4401                  * direct_access_msrs.  Doing that would require a rdmsr in
4402                  * svm_vcpu_put.
4403                  */
4404                 svm->tsc_aux = data;
4405                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4406                 break;
4407         case MSR_IA32_DEBUGCTLMSR:
4408                 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4409                         vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4410                                     __func__, data);
4411                         break;
4412                 }
4413                 if (data & DEBUGCTL_RESERVED_BITS)
4414                         return 1;
4415
4416                 svm->vmcb->save.dbgctl = data;
4417                 mark_dirty(svm->vmcb, VMCB_LBR);
4418                 if (data & (1ULL<<0))
4419                         svm_enable_lbrv(svm);
4420                 else
4421                         svm_disable_lbrv(svm);
4422                 break;
4423         case MSR_VM_HSAVE_PA:
4424                 svm->nested.hsave_msr = data;
4425                 break;
4426         case MSR_VM_CR:
4427                 return svm_set_vm_cr(vcpu, data);
4428         case MSR_VM_IGNNE:
4429                 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4430                 break;
4431         case MSR_F10H_DECFG: {
4432                 struct kvm_msr_entry msr_entry;
4433
4434                 msr_entry.index = msr->index;
4435                 if (svm_get_msr_feature(&msr_entry))
4436                         return 1;
4437
4438                 /* Check the supported bits */
4439                 if (data & ~msr_entry.data)
4440                         return 1;
4441
4442                 /* Don't allow the guest to change a bit, #GP */
4443                 if (!msr->host_initiated && (data ^ msr_entry.data))
4444                         return 1;
4445
4446                 svm->msr_decfg = data;
4447                 break;
4448         }
4449         case MSR_IA32_APICBASE:
4450                 if (kvm_vcpu_apicv_active(vcpu))
4451                         avic_update_vapic_bar(to_svm(vcpu), data);
4452                 /* Fall through */
4453         default:
4454                 return kvm_set_msr_common(vcpu, msr);
4455         }
4456         return 0;
4457 }
4458
4459 static int wrmsr_interception(struct vcpu_svm *svm)
4460 {
4461         return kvm_emulate_wrmsr(&svm->vcpu);
4462 }
4463
4464 static int msr_interception(struct vcpu_svm *svm)
4465 {
4466         if (svm->vmcb->control.exit_info_1)
4467                 return wrmsr_interception(svm);
4468         else
4469                 return rdmsr_interception(svm);
4470 }
4471
4472 static int interrupt_window_interception(struct vcpu_svm *svm)
4473 {
4474         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4475         svm_clear_vintr(svm);
4476         svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4477         mark_dirty(svm->vmcb, VMCB_INTR);
4478         ++svm->vcpu.stat.irq_window_exits;
4479         return 1;
4480 }
4481
4482 static int pause_interception(struct vcpu_svm *svm)
4483 {
4484         struct kvm_vcpu *vcpu = &svm->vcpu;
4485         bool in_kernel = (svm_get_cpl(vcpu) == 0);
4486
4487         if (pause_filter_thresh)
4488                 grow_ple_window(vcpu);
4489
4490         kvm_vcpu_on_spin(vcpu, in_kernel);
4491         return 1;
4492 }
4493
4494 static int nop_interception(struct vcpu_svm *svm)
4495 {
4496         return kvm_skip_emulated_instruction(&(svm->vcpu));
4497 }
4498
4499 static int monitor_interception(struct vcpu_svm *svm)
4500 {
4501         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4502         return nop_interception(svm);
4503 }
4504
4505 static int mwait_interception(struct vcpu_svm *svm)
4506 {
4507         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4508         return nop_interception(svm);
4509 }
4510
4511 enum avic_ipi_failure_cause {
4512         AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4513         AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4514         AVIC_IPI_FAILURE_INVALID_TARGET,
4515         AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4516 };
4517
4518 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4519 {
4520         u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4521         u32 icrl = svm->vmcb->control.exit_info_1;
4522         u32 id = svm->vmcb->control.exit_info_2 >> 32;
4523         u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4524         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4525
4526         trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4527
4528         switch (id) {
4529         case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4530                 /*
4531                  * AVIC hardware handles the generation of
4532                  * IPIs when the specified Message Type is Fixed
4533                  * (also known as fixed delivery mode) and
4534                  * the Trigger Mode is edge-triggered. The hardware
4535                  * also supports self and broadcast delivery modes
4536                  * specified via the Destination Shorthand(DSH)
4537                  * field of the ICRL. Logical and physical APIC ID
4538                  * formats are supported. All other IPI types cause
4539                  * a #VMEXIT, which needs to emulated.
4540                  */
4541                 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4542                 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4543                 break;
4544         case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4545                 int i;
4546                 struct kvm_vcpu *vcpu;
4547                 struct kvm *kvm = svm->vcpu.kvm;
4548                 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4549
4550                 /*
4551                  * At this point, we expect that the AVIC HW has already
4552                  * set the appropriate IRR bits on the valid target
4553                  * vcpus. So, we just need to kick the appropriate vcpu.
4554                  */
4555                 kvm_for_each_vcpu(i, vcpu, kvm) {
4556                         bool m = kvm_apic_match_dest(vcpu, apic,
4557                                                      icrl & KVM_APIC_SHORT_MASK,
4558                                                      GET_APIC_DEST_FIELD(icrh),
4559                                                      icrl & KVM_APIC_DEST_MASK);
4560
4561                         if (m && !avic_vcpu_is_running(vcpu))
4562                                 kvm_vcpu_wake_up(vcpu);
4563                 }
4564                 break;
4565         }
4566         case AVIC_IPI_FAILURE_INVALID_TARGET:
4567                 WARN_ONCE(1, "Invalid IPI target: index=%u, vcpu=%d, icr=%#0x:%#0x\n",
4568                           index, svm->vcpu.vcpu_id, icrh, icrl);
4569                 break;
4570         case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4571                 WARN_ONCE(1, "Invalid backing page\n");
4572                 break;
4573         default:
4574                 pr_err("Unknown IPI interception\n");
4575         }
4576
4577         return 1;
4578 }
4579
4580 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4581 {
4582         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4583         int index;
4584         u32 *logical_apic_id_table;
4585         int dlid = GET_APIC_LOGICAL_ID(ldr);
4586
4587         if (!dlid)
4588                 return NULL;
4589
4590         if (flat) { /* flat */
4591                 index = ffs(dlid) - 1;
4592                 if (index > 7)
4593                         return NULL;
4594         } else { /* cluster */
4595                 int cluster = (dlid & 0xf0) >> 4;
4596                 int apic = ffs(dlid & 0x0f) - 1;
4597
4598                 if ((apic < 0) || (apic > 7) ||
4599                     (cluster >= 0xf))
4600                         return NULL;
4601                 index = (cluster << 2) + apic;
4602         }
4603
4604         logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4605
4606         return &logical_apic_id_table[index];
4607 }
4608
4609 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
4610 {
4611         bool flat;
4612         u32 *entry, new_entry;
4613
4614         flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4615         entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4616         if (!entry)
4617                 return -EINVAL;
4618
4619         new_entry = READ_ONCE(*entry);
4620         new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4621         new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4622         new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4623         WRITE_ONCE(*entry, new_entry);
4624
4625         return 0;
4626 }
4627
4628 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
4629 {
4630         struct vcpu_svm *svm = to_svm(vcpu);
4631         bool flat = svm->dfr_reg == APIC_DFR_FLAT;
4632         u32 *entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
4633
4634         if (entry)
4635                 clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
4636 }
4637
4638 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4639 {
4640         int ret = 0;
4641         struct vcpu_svm *svm = to_svm(vcpu);
4642         u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4643         u32 id = kvm_xapic_id(vcpu->arch.apic);
4644
4645         if (ldr == svm->ldr_reg)
4646                 return 0;
4647
4648         avic_invalidate_logical_id_entry(vcpu);
4649
4650         if (ldr)
4651                 ret = avic_ldr_write(vcpu, id, ldr);
4652
4653         if (!ret)
4654                 svm->ldr_reg = ldr;
4655
4656         return ret;
4657 }
4658
4659 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4660 {
4661         u64 *old, *new;
4662         struct vcpu_svm *svm = to_svm(vcpu);
4663         u32 id = kvm_xapic_id(vcpu->arch.apic);
4664
4665         if (vcpu->vcpu_id == id)
4666                 return 0;
4667
4668         old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4669         new = avic_get_physical_id_entry(vcpu, id);
4670         if (!new || !old)
4671                 return 1;
4672
4673         /* We need to move physical_id_entry to new offset */
4674         *new = *old;
4675         *old = 0ULL;
4676         to_svm(vcpu)->avic_physical_id_cache = new;
4677
4678         /*
4679          * Also update the guest physical APIC ID in the logical
4680          * APIC ID table entry if already setup the LDR.
4681          */
4682         if (svm->ldr_reg)
4683                 avic_handle_ldr_update(vcpu);
4684
4685         return 0;
4686 }
4687
4688 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4689 {
4690         struct vcpu_svm *svm = to_svm(vcpu);
4691         u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4692
4693         if (svm->dfr_reg == dfr)
4694                 return;
4695
4696         avic_invalidate_logical_id_entry(vcpu);
4697         svm->dfr_reg = dfr;
4698 }
4699
4700 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4701 {
4702         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4703         u32 offset = svm->vmcb->control.exit_info_1 &
4704                                 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4705
4706         switch (offset) {
4707         case APIC_ID:
4708                 if (avic_handle_apic_id_update(&svm->vcpu))
4709                         return 0;
4710                 break;
4711         case APIC_LDR:
4712                 if (avic_handle_ldr_update(&svm->vcpu))
4713                         return 0;
4714                 break;
4715         case APIC_DFR:
4716                 avic_handle_dfr_update(&svm->vcpu);
4717                 break;
4718         default:
4719                 break;
4720         }
4721
4722         kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4723
4724         return 1;
4725 }
4726
4727 static bool is_avic_unaccelerated_access_trap(u32 offset)
4728 {
4729         bool ret = false;
4730
4731         switch (offset) {
4732         case APIC_ID:
4733         case APIC_EOI:
4734         case APIC_RRR:
4735         case APIC_LDR:
4736         case APIC_DFR:
4737         case APIC_SPIV:
4738         case APIC_ESR:
4739         case APIC_ICR:
4740         case APIC_LVTT:
4741         case APIC_LVTTHMR:
4742         case APIC_LVTPC:
4743         case APIC_LVT0:
4744         case APIC_LVT1:
4745         case APIC_LVTERR:
4746         case APIC_TMICT:
4747         case APIC_TDCR:
4748                 ret = true;
4749                 break;
4750         default:
4751                 break;
4752         }
4753         return ret;
4754 }
4755
4756 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4757 {
4758         int ret = 0;
4759         u32 offset = svm->vmcb->control.exit_info_1 &
4760                      AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4761         u32 vector = svm->vmcb->control.exit_info_2 &
4762                      AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4763         bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4764                      AVIC_UNACCEL_ACCESS_WRITE_MASK;
4765         bool trap = is_avic_unaccelerated_access_trap(offset);
4766
4767         trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4768                                             trap, write, vector);
4769         if (trap) {
4770                 /* Handling Trap */
4771                 WARN_ONCE(!write, "svm: Handling trap read.\n");
4772                 ret = avic_unaccel_trap_write(svm);
4773         } else {
4774                 /* Handling Fault */
4775                 ret = kvm_emulate_instruction(&svm->vcpu, 0);
4776         }
4777
4778         return ret;
4779 }
4780
4781 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4782         [SVM_EXIT_READ_CR0]                     = cr_interception,
4783         [SVM_EXIT_READ_CR3]                     = cr_interception,
4784         [SVM_EXIT_READ_CR4]                     = cr_interception,
4785         [SVM_EXIT_READ_CR8]                     = cr_interception,
4786         [SVM_EXIT_CR0_SEL_WRITE]                = cr_interception,
4787         [SVM_EXIT_WRITE_CR0]                    = cr_interception,
4788         [SVM_EXIT_WRITE_CR3]                    = cr_interception,
4789         [SVM_EXIT_WRITE_CR4]                    = cr_interception,
4790         [SVM_EXIT_WRITE_CR8]                    = cr8_write_interception,
4791         [SVM_EXIT_READ_DR0]                     = dr_interception,
4792         [SVM_EXIT_READ_DR1]                     = dr_interception,
4793         [SVM_EXIT_READ_DR2]                     = dr_interception,
4794         [SVM_EXIT_READ_DR3]                     = dr_interception,
4795         [SVM_EXIT_READ_DR4]                     = dr_interception,
4796         [SVM_EXIT_READ_DR5]                     = dr_interception,
4797         [SVM_EXIT_READ_DR6]                     = dr_interception,
4798         [SVM_EXIT_READ_DR7]                     = dr_interception,
4799         [SVM_EXIT_WRITE_DR0]                    = dr_interception,
4800         [SVM_EXIT_WRITE_DR1]                    = dr_interception,
4801         [SVM_EXIT_WRITE_DR2]                    = dr_interception,
4802         [SVM_EXIT_WRITE_DR3]                    = dr_interception,
4803         [SVM_EXIT_WRITE_DR4]                    = dr_interception,
4804         [SVM_EXIT_WRITE_DR5]                    = dr_interception,
4805         [SVM_EXIT_WRITE_DR6]                    = dr_interception,
4806         [SVM_EXIT_WRITE_DR7]                    = dr_interception,
4807         [SVM_EXIT_EXCP_BASE + DB_VECTOR]        = db_interception,
4808         [SVM_EXIT_EXCP_BASE + BP_VECTOR]        = bp_interception,
4809         [SVM_EXIT_EXCP_BASE + UD_VECTOR]        = ud_interception,
4810         [SVM_EXIT_EXCP_BASE + PF_VECTOR]        = pf_interception,
4811         [SVM_EXIT_EXCP_BASE + MC_VECTOR]        = mc_interception,
4812         [SVM_EXIT_EXCP_BASE + AC_VECTOR]        = ac_interception,
4813         [SVM_EXIT_EXCP_BASE + GP_VECTOR]        = gp_interception,
4814         [SVM_EXIT_INTR]                         = intr_interception,
4815         [SVM_EXIT_NMI]                          = nmi_interception,
4816         [SVM_EXIT_SMI]                          = nop_on_interception,
4817         [SVM_EXIT_INIT]                         = nop_on_interception,
4818         [SVM_EXIT_VINTR]                        = interrupt_window_interception,
4819         [SVM_EXIT_RDPMC]                        = rdpmc_interception,
4820         [SVM_EXIT_CPUID]                        = cpuid_interception,
4821         [SVM_EXIT_IRET]                         = iret_interception,
4822         [SVM_EXIT_INVD]                         = emulate_on_interception,
4823         [SVM_EXIT_PAUSE]                        = pause_interception,
4824         [SVM_EXIT_HLT]                          = halt_interception,
4825         [SVM_EXIT_INVLPG]                       = invlpg_interception,
4826         [SVM_EXIT_INVLPGA]                      = invlpga_interception,
4827         [SVM_EXIT_IOIO]                         = io_interception,
4828         [SVM_EXIT_MSR]                          = msr_interception,
4829         [SVM_EXIT_TASK_SWITCH]                  = task_switch_interception,
4830         [SVM_EXIT_SHUTDOWN]                     = shutdown_interception,
4831         [SVM_EXIT_VMRUN]                        = vmrun_interception,
4832         [SVM_EXIT_VMMCALL]                      = vmmcall_interception,
4833         [SVM_EXIT_VMLOAD]                       = vmload_interception,
4834         [SVM_EXIT_VMSAVE]                       = vmsave_interception,
4835         [SVM_EXIT_STGI]                         = stgi_interception,
4836         [SVM_EXIT_CLGI]                         = clgi_interception,
4837         [SVM_EXIT_SKINIT]                       = skinit_interception,
4838         [SVM_EXIT_WBINVD]                       = wbinvd_interception,
4839         [SVM_EXIT_MONITOR]                      = monitor_interception,
4840         [SVM_EXIT_MWAIT]                        = mwait_interception,
4841         [SVM_EXIT_XSETBV]                       = xsetbv_interception,
4842         [SVM_EXIT_RDPRU]                        = rdpru_interception,
4843         [SVM_EXIT_NPF]                          = npf_interception,
4844         [SVM_EXIT_RSM]                          = rsm_interception,
4845         [SVM_EXIT_AVIC_INCOMPLETE_IPI]          = avic_incomplete_ipi_interception,
4846         [SVM_EXIT_AVIC_UNACCELERATED_ACCESS]    = avic_unaccelerated_access_interception,
4847 };
4848
4849 static void dump_vmcb(struct kvm_vcpu *vcpu)
4850 {
4851         struct vcpu_svm *svm = to_svm(vcpu);
4852         struct vmcb_control_area *control = &svm->vmcb->control;
4853         struct vmcb_save_area *save = &svm->vmcb->save;
4854
4855         if (!dump_invalid_vmcb) {
4856                 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
4857                 return;
4858         }
4859
4860         pr_err("VMCB Control Area:\n");
4861         pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4862         pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4863         pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4864         pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4865         pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4866         pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4867         pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4868         pr_err("%-20s%d\n", "pause filter threshold:",
4869                control->pause_filter_thresh);
4870         pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4871         pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4872         pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4873         pr_err("%-20s%d\n", "asid:", control->asid);
4874         pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4875         pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4876         pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4877         pr_err("%-20s%08x\n", "int_state:", control->int_state);
4878         pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4879         pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4880         pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4881         pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4882         pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4883         pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4884         pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4885         pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4886         pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4887         pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4888         pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4889         pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4890         pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4891         pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4892         pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4893         pr_err("VMCB State Save Area:\n");
4894         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4895                "es:",
4896                save->es.selector, save->es.attrib,
4897                save->es.limit, save->es.base);
4898         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4899                "cs:",
4900                save->cs.selector, save->cs.attrib,
4901                save->cs.limit, save->cs.base);
4902         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4903                "ss:",
4904                save->ss.selector, save->ss.attrib,
4905                save->ss.limit, save->ss.base);
4906         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4907                "ds:",
4908                save->ds.selector, save->ds.attrib,
4909                save->ds.limit, save->ds.base);
4910         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4911                "fs:",
4912                save->fs.selector, save->fs.attrib,
4913                save->fs.limit, save->fs.base);
4914         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4915                "gs:",
4916                save->gs.selector, save->gs.attrib,
4917                save->gs.limit, save->gs.base);
4918         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4919                "gdtr:",
4920                save->gdtr.selector, save->gdtr.attrib,
4921                save->gdtr.limit, save->gdtr.base);
4922         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4923                "ldtr:",
4924                save->ldtr.selector, save->ldtr.attrib,
4925                save->ldtr.limit, save->ldtr.base);
4926         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4927                "idtr:",
4928                save->idtr.selector, save->idtr.attrib,
4929                save->idtr.limit, save->idtr.base);
4930         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4931                "tr:",
4932                save->tr.selector, save->tr.attrib,
4933                save->tr.limit, save->tr.base);
4934         pr_err("cpl:            %d                efer:         %016llx\n",
4935                 save->cpl, save->efer);
4936         pr_err("%-15s %016llx %-13s %016llx\n",
4937                "cr0:", save->cr0, "cr2:", save->cr2);
4938         pr_err("%-15s %016llx %-13s %016llx\n",
4939                "cr3:", save->cr3, "cr4:", save->cr4);
4940         pr_err("%-15s %016llx %-13s %016llx\n",
4941                "dr6:", save->dr6, "dr7:", save->dr7);
4942         pr_err("%-15s %016llx %-13s %016llx\n",
4943                "rip:", save->rip, "rflags:", save->rflags);
4944         pr_err("%-15s %016llx %-13s %016llx\n",
4945                "rsp:", save->rsp, "rax:", save->rax);
4946         pr_err("%-15s %016llx %-13s %016llx\n",
4947                "star:", save->star, "lstar:", save->lstar);
4948         pr_err("%-15s %016llx %-13s %016llx\n",
4949                "cstar:", save->cstar, "sfmask:", save->sfmask);
4950         pr_err("%-15s %016llx %-13s %016llx\n",
4951                "kernel_gs_base:", save->kernel_gs_base,
4952                "sysenter_cs:", save->sysenter_cs);
4953         pr_err("%-15s %016llx %-13s %016llx\n",
4954                "sysenter_esp:", save->sysenter_esp,
4955                "sysenter_eip:", save->sysenter_eip);
4956         pr_err("%-15s %016llx %-13s %016llx\n",
4957                "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4958         pr_err("%-15s %016llx %-13s %016llx\n",
4959                "br_from:", save->br_from, "br_to:", save->br_to);
4960         pr_err("%-15s %016llx %-13s %016llx\n",
4961                "excp_from:", save->last_excp_from,
4962                "excp_to:", save->last_excp_to);
4963 }
4964
4965 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4966 {
4967         struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4968
4969         *info1 = control->exit_info_1;
4970         *info2 = control->exit_info_2;
4971 }
4972
4973 static int handle_exit(struct kvm_vcpu *vcpu)
4974 {
4975         struct vcpu_svm *svm = to_svm(vcpu);
4976         struct kvm_run *kvm_run = vcpu->run;
4977         u32 exit_code = svm->vmcb->control.exit_code;
4978
4979         trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4980
4981         if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4982                 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4983         if (npt_enabled)
4984                 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4985
4986         if (unlikely(svm->nested.exit_required)) {
4987                 nested_svm_vmexit(svm);
4988                 svm->nested.exit_required = false;
4989
4990                 return 1;
4991         }
4992
4993         if (is_guest_mode(vcpu)) {
4994                 int vmexit;
4995
4996                 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4997                                         svm->vmcb->control.exit_info_1,
4998                                         svm->vmcb->control.exit_info_2,
4999                                         svm->vmcb->control.exit_int_info,
5000                                         svm->vmcb->control.exit_int_info_err,
5001                                         KVM_ISA_SVM);
5002
5003                 vmexit = nested_svm_exit_special(svm);
5004
5005                 if (vmexit == NESTED_EXIT_CONTINUE)
5006                         vmexit = nested_svm_exit_handled(svm);
5007
5008                 if (vmexit == NESTED_EXIT_DONE)
5009                         return 1;
5010         }
5011
5012         svm_complete_interrupts(svm);
5013
5014         if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
5015                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5016                 kvm_run->fail_entry.hardware_entry_failure_reason
5017                         = svm->vmcb->control.exit_code;
5018                 dump_vmcb(vcpu);
5019                 return 0;
5020         }
5021
5022         if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
5023             exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
5024             exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
5025             exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
5026                 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
5027                        "exit_code 0x%x\n",
5028                        __func__, svm->vmcb->control.exit_int_info,
5029                        exit_code);
5030
5031         if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
5032             || !svm_exit_handlers[exit_code]) {
5033                 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%x\n", exit_code);
5034                 dump_vmcb(vcpu);
5035                 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5036                 vcpu->run->internal.suberror =
5037                         KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
5038                 vcpu->run->internal.ndata = 1;
5039                 vcpu->run->internal.data[0] = exit_code;
5040                 return 0;
5041         }
5042
5043         return svm_exit_handlers[exit_code](svm);
5044 }
5045
5046 static void reload_tss(struct kvm_vcpu *vcpu)
5047 {
5048         int cpu = raw_smp_processor_id();
5049
5050         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5051         sd->tss_desc->type = 9; /* available 32/64-bit TSS */
5052         load_TR_desc();
5053 }
5054
5055 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
5056 {
5057         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5058         int asid = sev_get_asid(svm->vcpu.kvm);
5059
5060         /* Assign the asid allocated with this SEV guest */
5061         svm->vmcb->control.asid = asid;
5062
5063         /*
5064          * Flush guest TLB:
5065          *
5066          * 1) when different VMCB for the same ASID is to be run on the same host CPU.
5067          * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
5068          */
5069         if (sd->sev_vmcbs[asid] == svm->vmcb &&
5070             svm->last_cpu == cpu)
5071                 return;
5072
5073         svm->last_cpu = cpu;
5074         sd->sev_vmcbs[asid] = svm->vmcb;
5075         svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5076         mark_dirty(svm->vmcb, VMCB_ASID);
5077 }
5078
5079 static void pre_svm_run(struct vcpu_svm *svm)
5080 {
5081         int cpu = raw_smp_processor_id();
5082
5083         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5084
5085         if (sev_guest(svm->vcpu.kvm))
5086                 return pre_sev_run(svm, cpu);
5087
5088         /* FIXME: handle wraparound of asid_generation */
5089         if (svm->asid_generation != sd->asid_generation)
5090                 new_asid(svm, sd);
5091 }
5092
5093 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5094 {
5095         struct vcpu_svm *svm = to_svm(vcpu);
5096
5097         svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5098         vcpu->arch.hflags |= HF_NMI_MASK;
5099         set_intercept(svm, INTERCEPT_IRET);
5100         ++vcpu->stat.nmi_injections;
5101 }
5102
5103 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
5104 {
5105         struct vmcb_control_area *control;
5106
5107         /* The following fields are ignored when AVIC is enabled */
5108         control = &svm->vmcb->control;
5109         control->int_vector = irq;
5110         control->int_ctl &= ~V_INTR_PRIO_MASK;
5111         control->int_ctl |= V_IRQ_MASK |
5112                 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
5113         mark_dirty(svm->vmcb, VMCB_INTR);
5114 }
5115
5116 static void svm_set_irq(struct kvm_vcpu *vcpu)
5117 {
5118         struct vcpu_svm *svm = to_svm(vcpu);
5119
5120         BUG_ON(!(gif_set(svm)));
5121
5122         trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5123         ++vcpu->stat.irq_injections;
5124
5125         svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5126                 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5127 }
5128
5129 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5130 {
5131         return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5132 }
5133
5134 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5135 {
5136         struct vcpu_svm *svm = to_svm(vcpu);
5137
5138         if (svm_nested_virtualize_tpr(vcpu) ||
5139             kvm_vcpu_apicv_active(vcpu))
5140                 return;
5141
5142         clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5143
5144         if (irr == -1)
5145                 return;
5146
5147         if (tpr >= irr)
5148                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5149 }
5150
5151 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5152 {
5153         return;
5154 }
5155
5156 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
5157 {
5158         return avic && irqchip_split(vcpu->kvm);
5159 }
5160
5161 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5162 {
5163 }
5164
5165 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5166 {
5167 }
5168
5169 /* Note: Currently only used by Hyper-V. */
5170 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5171 {
5172         struct vcpu_svm *svm = to_svm(vcpu);
5173         struct vmcb *vmcb = svm->vmcb;
5174
5175         if (kvm_vcpu_apicv_active(vcpu))
5176                 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
5177         else
5178                 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5179         mark_dirty(vmcb, VMCB_AVIC);
5180 }
5181
5182 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5183 {
5184         return;
5185 }
5186
5187 static int svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5188 {
5189         if (!vcpu->arch.apicv_active)
5190                 return -1;
5191
5192         kvm_lapic_set_irr(vec, vcpu->arch.apic);
5193         smp_mb__after_atomic();
5194
5195         if (avic_vcpu_is_running(vcpu)) {
5196                 int cpuid = vcpu->cpu;
5197
5198                 if (cpuid != get_cpu())
5199                         wrmsrl(SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpuid));
5200                 put_cpu();
5201         } else
5202                 kvm_vcpu_wake_up(vcpu);
5203
5204         return 0;
5205 }
5206
5207 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
5208 {
5209         return false;
5210 }
5211
5212 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5213 {
5214         unsigned long flags;
5215         struct amd_svm_iommu_ir *cur;
5216
5217         spin_lock_irqsave(&svm->ir_list_lock, flags);
5218         list_for_each_entry(cur, &svm->ir_list, node) {
5219                 if (cur->data != pi->ir_data)
5220                         continue;
5221                 list_del(&cur->node);
5222                 kfree(cur);
5223                 break;
5224         }
5225         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5226 }
5227
5228 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5229 {
5230         int ret = 0;
5231         unsigned long flags;
5232         struct amd_svm_iommu_ir *ir;
5233
5234         /**
5235          * In some cases, the existing irte is updaed and re-set,
5236          * so we need to check here if it's already been * added
5237          * to the ir_list.
5238          */
5239         if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5240                 struct kvm *kvm = svm->vcpu.kvm;
5241                 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5242                 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5243                 struct vcpu_svm *prev_svm;
5244
5245                 if (!prev_vcpu) {
5246                         ret = -EINVAL;
5247                         goto out;
5248                 }
5249
5250                 prev_svm = to_svm(prev_vcpu);
5251                 svm_ir_list_del(prev_svm, pi);
5252         }
5253
5254         /**
5255          * Allocating new amd_iommu_pi_data, which will get
5256          * add to the per-vcpu ir_list.
5257          */
5258         ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL_ACCOUNT);
5259         if (!ir) {
5260                 ret = -ENOMEM;
5261                 goto out;
5262         }
5263         ir->data = pi->ir_data;
5264
5265         spin_lock_irqsave(&svm->ir_list_lock, flags);
5266         list_add(&ir->node, &svm->ir_list);
5267         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5268 out:
5269         return ret;
5270 }
5271
5272 /**
5273  * Note:
5274  * The HW cannot support posting multicast/broadcast
5275  * interrupts to a vCPU. So, we still use legacy interrupt
5276  * remapping for these kind of interrupts.
5277  *
5278  * For lowest-priority interrupts, we only support
5279  * those with single CPU as the destination, e.g. user
5280  * configures the interrupts via /proc/irq or uses
5281  * irqbalance to make the interrupts single-CPU.
5282  */
5283 static int
5284 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5285                  struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5286 {
5287         struct kvm_lapic_irq irq;
5288         struct kvm_vcpu *vcpu = NULL;
5289
5290         kvm_set_msi_irq(kvm, e, &irq);
5291
5292         if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
5293             !kvm_irq_is_postable(&irq)) {
5294                 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5295                          __func__, irq.vector);
5296                 return -1;
5297         }
5298
5299         pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5300                  irq.vector);
5301         *svm = to_svm(vcpu);
5302         vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5303         vcpu_info->vector = irq.vector;
5304
5305         return 0;
5306 }
5307
5308 /*
5309  * svm_update_pi_irte - set IRTE for Posted-Interrupts
5310  *
5311  * @kvm: kvm
5312  * @host_irq: host irq of the interrupt
5313  * @guest_irq: gsi of the interrupt
5314  * @set: set or unset PI
5315  * returns 0 on success, < 0 on failure
5316  */
5317 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5318                               uint32_t guest_irq, bool set)
5319 {
5320         struct kvm_kernel_irq_routing_entry *e;
5321         struct kvm_irq_routing_table *irq_rt;
5322         int idx, ret = -EINVAL;
5323
5324         if (!kvm_arch_has_assigned_device(kvm) ||
5325             !irq_remapping_cap(IRQ_POSTING_CAP))
5326                 return 0;
5327
5328         pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5329                  __func__, host_irq, guest_irq, set);
5330
5331         idx = srcu_read_lock(&kvm->irq_srcu);
5332         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5333         WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5334
5335         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5336                 struct vcpu_data vcpu_info;
5337                 struct vcpu_svm *svm = NULL;
5338
5339                 if (e->type != KVM_IRQ_ROUTING_MSI)
5340                         continue;
5341
5342                 /**
5343                  * Here, we setup with legacy mode in the following cases:
5344                  * 1. When cannot target interrupt to a specific vcpu.
5345                  * 2. Unsetting posted interrupt.
5346                  * 3. APIC virtialization is disabled for the vcpu.
5347                  * 4. IRQ has incompatible delivery mode (SMI, INIT, etc)
5348                  */
5349                 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5350                     kvm_vcpu_apicv_active(&svm->vcpu)) {
5351                         struct amd_iommu_pi_data pi;
5352
5353                         /* Try to enable guest_mode in IRTE */
5354                         pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5355                                             AVIC_HPA_MASK);
5356                         pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5357                                                      svm->vcpu.vcpu_id);
5358                         pi.is_guest_mode = true;
5359                         pi.vcpu_data = &vcpu_info;
5360                         ret = irq_set_vcpu_affinity(host_irq, &pi);
5361
5362                         /**
5363                          * Here, we successfully setting up vcpu affinity in
5364                          * IOMMU guest mode. Now, we need to store the posted
5365                          * interrupt information in a per-vcpu ir_list so that
5366                          * we can reference to them directly when we update vcpu
5367                          * scheduling information in IOMMU irte.
5368                          */
5369                         if (!ret && pi.is_guest_mode)
5370                                 svm_ir_list_add(svm, &pi);
5371                 } else {
5372                         /* Use legacy mode in IRTE */
5373                         struct amd_iommu_pi_data pi;
5374
5375                         /**
5376                          * Here, pi is used to:
5377                          * - Tell IOMMU to use legacy mode for this interrupt.
5378                          * - Retrieve ga_tag of prior interrupt remapping data.
5379                          */
5380                         pi.is_guest_mode = false;
5381                         ret = irq_set_vcpu_affinity(host_irq, &pi);
5382
5383                         /**
5384                          * Check if the posted interrupt was previously
5385                          * setup with the guest_mode by checking if the ga_tag
5386                          * was cached. If so, we need to clean up the per-vcpu
5387                          * ir_list.
5388                          */
5389                         if (!ret && pi.prev_ga_tag) {
5390                                 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5391                                 struct kvm_vcpu *vcpu;
5392
5393                                 vcpu = kvm_get_vcpu_by_id(kvm, id);
5394                                 if (vcpu)
5395                                         svm_ir_list_del(to_svm(vcpu), &pi);
5396                         }
5397                 }
5398
5399                 if (!ret && svm) {
5400                         trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5401                                                  e->gsi, vcpu_info.vector,
5402                                                  vcpu_info.pi_desc_addr, set);
5403                 }
5404
5405                 if (ret < 0) {
5406                         pr_err("%s: failed to update PI IRTE\n", __func__);
5407                         goto out;
5408                 }
5409         }
5410
5411         ret = 0;
5412 out:
5413         srcu_read_unlock(&kvm->irq_srcu, idx);
5414         return ret;
5415 }
5416
5417 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5418 {
5419         struct vcpu_svm *svm = to_svm(vcpu);
5420         struct vmcb *vmcb = svm->vmcb;
5421         int ret;
5422         ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5423               !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5424         ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5425
5426         return ret;
5427 }
5428
5429 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5430 {
5431         struct vcpu_svm *svm = to_svm(vcpu);
5432
5433         return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5434 }
5435
5436 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5437 {
5438         struct vcpu_svm *svm = to_svm(vcpu);
5439
5440         if (masked) {
5441                 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5442                 set_intercept(svm, INTERCEPT_IRET);
5443         } else {
5444                 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5445                 clr_intercept(svm, INTERCEPT_IRET);
5446         }
5447 }
5448
5449 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5450 {
5451         struct vcpu_svm *svm = to_svm(vcpu);
5452         struct vmcb *vmcb = svm->vmcb;
5453         int ret;
5454
5455         if (!gif_set(svm) ||
5456              (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5457                 return 0;
5458
5459         ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5460
5461         if (is_guest_mode(vcpu))
5462                 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5463
5464         return ret;
5465 }
5466
5467 static void enable_irq_window(struct kvm_vcpu *vcpu)
5468 {
5469         struct vcpu_svm *svm = to_svm(vcpu);
5470
5471         if (kvm_vcpu_apicv_active(vcpu))
5472                 return;
5473
5474         /*
5475          * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5476          * 1, because that's a separate STGI/VMRUN intercept.  The next time we
5477          * get that intercept, this function will be called again though and
5478          * we'll get the vintr intercept. However, if the vGIF feature is
5479          * enabled, the STGI interception will not occur. Enable the irq
5480          * window under the assumption that the hardware will set the GIF.
5481          */
5482         if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5483                 svm_set_vintr(svm);
5484                 svm_inject_irq(svm, 0x0);
5485         }
5486 }
5487
5488 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5489 {
5490         struct vcpu_svm *svm = to_svm(vcpu);
5491
5492         if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5493             == HF_NMI_MASK)
5494                 return; /* IRET will cause a vm exit */
5495
5496         if (!gif_set(svm)) {
5497                 if (vgif_enabled(svm))
5498                         set_intercept(svm, INTERCEPT_STGI);
5499                 return; /* STGI will cause a vm exit */
5500         }
5501
5502         if (svm->nested.exit_required)
5503                 return; /* we're not going to run the guest yet */
5504
5505         /*
5506          * Something prevents NMI from been injected. Single step over possible
5507          * problem (IRET or exception injection or interrupt shadow)
5508          */
5509         svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5510         svm->nmi_singlestep = true;
5511         svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5512 }
5513
5514 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5515 {
5516         return 0;
5517 }
5518
5519 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5520 {
5521         return 0;
5522 }
5523
5524 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5525 {
5526         struct vcpu_svm *svm = to_svm(vcpu);
5527
5528         if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5529                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5530         else
5531                 svm->asid_generation--;
5532 }
5533
5534 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
5535 {
5536         struct vcpu_svm *svm = to_svm(vcpu);
5537
5538         invlpga(gva, svm->vmcb->control.asid);
5539 }
5540
5541 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5542 {
5543 }
5544
5545 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5546 {
5547         struct vcpu_svm *svm = to_svm(vcpu);
5548
5549         if (svm_nested_virtualize_tpr(vcpu))
5550                 return;
5551
5552         if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5553                 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5554                 kvm_set_cr8(vcpu, cr8);
5555         }
5556 }
5557
5558 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5559 {
5560         struct vcpu_svm *svm = to_svm(vcpu);
5561         u64 cr8;
5562
5563         if (svm_nested_virtualize_tpr(vcpu) ||
5564             kvm_vcpu_apicv_active(vcpu))
5565                 return;
5566
5567         cr8 = kvm_get_cr8(vcpu);
5568         svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5569         svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5570 }
5571
5572 static void svm_complete_interrupts(struct vcpu_svm *svm)
5573 {
5574         u8 vector;
5575         int type;
5576         u32 exitintinfo = svm->vmcb->control.exit_int_info;
5577         unsigned int3_injected = svm->int3_injected;
5578
5579         svm->int3_injected = 0;
5580
5581         /*
5582          * If we've made progress since setting HF_IRET_MASK, we've
5583          * executed an IRET and can allow NMI injection.
5584          */
5585         if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5586             && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5587                 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5588                 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5589         }
5590
5591         svm->vcpu.arch.nmi_injected = false;
5592         kvm_clear_exception_queue(&svm->vcpu);
5593         kvm_clear_interrupt_queue(&svm->vcpu);
5594
5595         if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5596                 return;
5597
5598         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5599
5600         vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5601         type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5602
5603         switch (type) {
5604         case SVM_EXITINTINFO_TYPE_NMI:
5605                 svm->vcpu.arch.nmi_injected = true;
5606                 break;
5607         case SVM_EXITINTINFO_TYPE_EXEPT:
5608                 /*
5609                  * In case of software exceptions, do not reinject the vector,
5610                  * but re-execute the instruction instead. Rewind RIP first
5611                  * if we emulated INT3 before.
5612                  */
5613                 if (kvm_exception_is_soft(vector)) {
5614                         if (vector == BP_VECTOR && int3_injected &&
5615                             kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5616                                 kvm_rip_write(&svm->vcpu,
5617                                               kvm_rip_read(&svm->vcpu) -
5618                                               int3_injected);
5619                         break;
5620                 }
5621                 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5622                         u32 err = svm->vmcb->control.exit_int_info_err;
5623                         kvm_requeue_exception_e(&svm->vcpu, vector, err);
5624
5625                 } else
5626                         kvm_requeue_exception(&svm->vcpu, vector);
5627                 break;
5628         case SVM_EXITINTINFO_TYPE_INTR:
5629                 kvm_queue_interrupt(&svm->vcpu, vector, false);
5630                 break;
5631         default:
5632                 break;
5633         }
5634 }
5635
5636 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5637 {
5638         struct vcpu_svm *svm = to_svm(vcpu);
5639         struct vmcb_control_area *control = &svm->vmcb->control;
5640
5641         control->exit_int_info = control->event_inj;
5642         control->exit_int_info_err = control->event_inj_err;
5643         control->event_inj = 0;
5644         svm_complete_interrupts(svm);
5645 }
5646
5647 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5648 {
5649         struct vcpu_svm *svm = to_svm(vcpu);
5650
5651         svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5652         svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5653         svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5654
5655         /*
5656          * A vmexit emulation is required before the vcpu can be executed
5657          * again.
5658          */
5659         if (unlikely(svm->nested.exit_required))
5660                 return;
5661
5662         /*
5663          * Disable singlestep if we're injecting an interrupt/exception.
5664          * We don't want our modified rflags to be pushed on the stack where
5665          * we might not be able to easily reset them if we disabled NMI
5666          * singlestep later.
5667          */
5668         if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5669                 /*
5670                  * Event injection happens before external interrupts cause a
5671                  * vmexit and interrupts are disabled here, so smp_send_reschedule
5672                  * is enough to force an immediate vmexit.
5673                  */
5674                 disable_nmi_singlestep(svm);
5675                 smp_send_reschedule(vcpu->cpu);
5676         }
5677
5678         pre_svm_run(svm);
5679
5680         sync_lapic_to_cr8(vcpu);
5681
5682         svm->vmcb->save.cr2 = vcpu->arch.cr2;
5683
5684         clgi();
5685         kvm_load_guest_xcr0(vcpu);
5686
5687         if (lapic_in_kernel(vcpu) &&
5688                 vcpu->arch.apic->lapic_timer.timer_advance_ns)
5689                 kvm_wait_lapic_expire(vcpu);
5690
5691         /*
5692          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5693          * it's non-zero. Since vmentry is serialising on affected CPUs, there
5694          * is no need to worry about the conditional branch over the wrmsr
5695          * being speculatively taken.
5696          */
5697         x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5698
5699         local_irq_enable();
5700
5701         asm volatile (
5702                 "push %%" _ASM_BP "; \n\t"
5703                 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5704                 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5705                 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5706                 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5707                 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5708                 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5709 #ifdef CONFIG_X86_64
5710                 "mov %c[r8](%[svm]),  %%r8  \n\t"
5711                 "mov %c[r9](%[svm]),  %%r9  \n\t"
5712                 "mov %c[r10](%[svm]), %%r10 \n\t"
5713                 "mov %c[r11](%[svm]), %%r11 \n\t"
5714                 "mov %c[r12](%[svm]), %%r12 \n\t"
5715                 "mov %c[r13](%[svm]), %%r13 \n\t"
5716                 "mov %c[r14](%[svm]), %%r14 \n\t"
5717                 "mov %c[r15](%[svm]), %%r15 \n\t"
5718 #endif
5719
5720                 /* Enter guest mode */
5721                 "push %%" _ASM_AX " \n\t"
5722                 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5723                 __ex("vmload %%" _ASM_AX) "\n\t"
5724                 __ex("vmrun %%" _ASM_AX) "\n\t"
5725                 __ex("vmsave %%" _ASM_AX) "\n\t"
5726                 "pop %%" _ASM_AX " \n\t"
5727
5728                 /* Save guest registers, load host registers */
5729                 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5730                 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5731                 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5732                 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5733                 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5734                 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5735 #ifdef CONFIG_X86_64
5736                 "mov %%r8,  %c[r8](%[svm]) \n\t"
5737                 "mov %%r9,  %c[r9](%[svm]) \n\t"
5738                 "mov %%r10, %c[r10](%[svm]) \n\t"
5739                 "mov %%r11, %c[r11](%[svm]) \n\t"
5740                 "mov %%r12, %c[r12](%[svm]) \n\t"
5741                 "mov %%r13, %c[r13](%[svm]) \n\t"
5742                 "mov %%r14, %c[r14](%[svm]) \n\t"
5743                 "mov %%r15, %c[r15](%[svm]) \n\t"
5744                 /*
5745                 * Clear host registers marked as clobbered to prevent
5746                 * speculative use.
5747                 */
5748                 "xor %%r8d, %%r8d \n\t"
5749                 "xor %%r9d, %%r9d \n\t"
5750                 "xor %%r10d, %%r10d \n\t"
5751                 "xor %%r11d, %%r11d \n\t"
5752                 "xor %%r12d, %%r12d \n\t"
5753                 "xor %%r13d, %%r13d \n\t"
5754                 "xor %%r14d, %%r14d \n\t"
5755                 "xor %%r15d, %%r15d \n\t"
5756 #endif
5757                 "xor %%ebx, %%ebx \n\t"
5758                 "xor %%ecx, %%ecx \n\t"
5759                 "xor %%edx, %%edx \n\t"
5760                 "xor %%esi, %%esi \n\t"
5761                 "xor %%edi, %%edi \n\t"
5762                 "pop %%" _ASM_BP
5763                 :
5764                 : [svm]"a"(svm),
5765                   [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5766                   [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5767                   [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5768                   [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5769                   [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5770                   [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5771                   [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5772 #ifdef CONFIG_X86_64
5773                   , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5774                   [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5775                   [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5776                   [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5777                   [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5778                   [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5779                   [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5780                   [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5781 #endif
5782                 : "cc", "memory"
5783 #ifdef CONFIG_X86_64
5784                 , "rbx", "rcx", "rdx", "rsi", "rdi"
5785                 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5786 #else
5787                 , "ebx", "ecx", "edx", "esi", "edi"
5788 #endif
5789                 );
5790
5791         /* Eliminate branch target predictions from guest mode */
5792         vmexit_fill_RSB();
5793
5794 #ifdef CONFIG_X86_64
5795         wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5796 #else
5797         loadsegment(fs, svm->host.fs);
5798 #ifndef CONFIG_X86_32_LAZY_GS
5799         loadsegment(gs, svm->host.gs);
5800 #endif
5801 #endif
5802
5803         /*
5804          * We do not use IBRS in the kernel. If this vCPU has used the
5805          * SPEC_CTRL MSR it may have left it on; save the value and
5806          * turn it off. This is much more efficient than blindly adding
5807          * it to the atomic save/restore list. Especially as the former
5808          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5809          *
5810          * For non-nested case:
5811          * If the L01 MSR bitmap does not intercept the MSR, then we need to
5812          * save it.
5813          *
5814          * For nested case:
5815          * If the L02 MSR bitmap does not intercept the MSR, then we need to
5816          * save it.
5817          */
5818         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5819                 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5820
5821         reload_tss(vcpu);
5822
5823         local_irq_disable();
5824
5825         x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5826
5827         vcpu->arch.cr2 = svm->vmcb->save.cr2;
5828         vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5829         vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5830         vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5831
5832         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5833                 kvm_before_interrupt(&svm->vcpu);
5834
5835         kvm_put_guest_xcr0(vcpu);
5836         stgi();
5837
5838         /* Any pending NMI will happen here */
5839
5840         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5841                 kvm_after_interrupt(&svm->vcpu);
5842
5843         sync_cr8_to_lapic(vcpu);
5844
5845         svm->next_rip = 0;
5846
5847         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5848
5849         /* if exit due to PF check for async PF */
5850         if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5851                 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5852
5853         if (npt_enabled) {
5854                 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5855                 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5856         }
5857
5858         /*
5859          * We need to handle MC intercepts here before the vcpu has a chance to
5860          * change the physical cpu
5861          */
5862         if (unlikely(svm->vmcb->control.exit_code ==
5863                      SVM_EXIT_EXCP_BASE + MC_VECTOR))
5864                 svm_handle_mce(svm);
5865
5866         mark_all_clean(svm->vmcb);
5867 }
5868 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5869
5870 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5871 {
5872         struct vcpu_svm *svm = to_svm(vcpu);
5873
5874         svm->vmcb->save.cr3 = __sme_set(root);
5875         mark_dirty(svm->vmcb, VMCB_CR);
5876 }
5877
5878 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5879 {
5880         struct vcpu_svm *svm = to_svm(vcpu);
5881
5882         svm->vmcb->control.nested_cr3 = __sme_set(root);
5883         mark_dirty(svm->vmcb, VMCB_NPT);
5884
5885         /* Also sync guest cr3 here in case we live migrate */
5886         svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5887         mark_dirty(svm->vmcb, VMCB_CR);
5888 }
5889
5890 static int is_disabled(void)
5891 {
5892         u64 vm_cr;
5893
5894         rdmsrl(MSR_VM_CR, vm_cr);
5895         if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5896                 return 1;
5897
5898         return 0;
5899 }
5900
5901 static void
5902 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5903 {
5904         /*
5905          * Patch in the VMMCALL instruction:
5906          */
5907         hypercall[0] = 0x0f;
5908         hypercall[1] = 0x01;
5909         hypercall[2] = 0xd9;
5910 }
5911
5912 static int __init svm_check_processor_compat(void)
5913 {
5914         return 0;
5915 }
5916
5917 static bool svm_cpu_has_accelerated_tpr(void)
5918 {
5919         return false;
5920 }
5921
5922 static bool svm_has_emulated_msr(int index)
5923 {
5924         switch (index) {
5925         case MSR_IA32_MCG_EXT_CTL:
5926         case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
5927                 return false;
5928         default:
5929                 break;
5930         }
5931
5932         return true;
5933 }
5934
5935 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5936 {
5937         return 0;
5938 }
5939
5940 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5941 {
5942         struct vcpu_svm *svm = to_svm(vcpu);
5943
5944         /* Update nrips enabled cache */
5945         svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5946
5947         if (!kvm_vcpu_apicv_active(vcpu))
5948                 return;
5949
5950         guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5951 }
5952
5953 #define F(x) bit(X86_FEATURE_##x)
5954
5955 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5956 {
5957         switch (func) {
5958         case 0x1:
5959                 if (avic)
5960                         entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5961                 break;
5962         case 0x80000001:
5963                 if (nested)
5964                         entry->ecx |= (1 << 2); /* Set SVM bit */
5965                 break;
5966         case 0x80000008:
5967                 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
5968                      boot_cpu_has(X86_FEATURE_AMD_SSBD))
5969                         entry->ebx |= F(VIRT_SSBD);
5970                 break;
5971         case 0x8000000A:
5972                 entry->eax = 1; /* SVM revision 1 */
5973                 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5974                                    ASID emulation to nested SVM */
5975                 entry->ecx = 0; /* Reserved */
5976                 entry->edx = 0; /* Per default do not support any
5977                                    additional features */
5978
5979                 /* Support next_rip if host supports it */
5980                 if (boot_cpu_has(X86_FEATURE_NRIPS))
5981                         entry->edx |= F(NRIPS);
5982
5983                 /* Support NPT for the guest if enabled */
5984                 if (npt_enabled)
5985                         entry->edx |= F(NPT);
5986
5987                 break;
5988         case 0x8000001F:
5989                 /* Support memory encryption cpuid if host supports it */
5990                 if (boot_cpu_has(X86_FEATURE_SEV))
5991                         cpuid(0x8000001f, &entry->eax, &entry->ebx,
5992                                 &entry->ecx, &entry->edx);
5993
5994         }
5995 }
5996
5997 static int svm_get_lpage_level(void)
5998 {
5999         return PT_PDPE_LEVEL;
6000 }
6001
6002 static bool svm_rdtscp_supported(void)
6003 {
6004         return boot_cpu_has(X86_FEATURE_RDTSCP);
6005 }
6006
6007 static bool svm_invpcid_supported(void)
6008 {
6009         return false;
6010 }
6011
6012 static bool svm_mpx_supported(void)
6013 {
6014         return false;
6015 }
6016
6017 static bool svm_xsaves_supported(void)
6018 {
6019         return false;
6020 }
6021
6022 static bool svm_umip_emulated(void)
6023 {
6024         return false;
6025 }
6026
6027 static bool svm_pt_supported(void)
6028 {
6029         return false;
6030 }
6031
6032 static bool svm_has_wbinvd_exit(void)
6033 {
6034         return true;
6035 }
6036
6037 static bool svm_pku_supported(void)
6038 {
6039         return false;
6040 }
6041
6042 #define PRE_EX(exit)  { .exit_code = (exit), \
6043                         .stage = X86_ICPT_PRE_EXCEPT, }
6044 #define POST_EX(exit) { .exit_code = (exit), \
6045                         .stage = X86_ICPT_POST_EXCEPT, }
6046 #define POST_MEM(exit) { .exit_code = (exit), \
6047                         .stage = X86_ICPT_POST_MEMACCESS, }
6048
6049 static const struct __x86_intercept {
6050         u32 exit_code;
6051         enum x86_intercept_stage stage;
6052 } x86_intercept_map[] = {
6053         [x86_intercept_cr_read]         = POST_EX(SVM_EXIT_READ_CR0),
6054         [x86_intercept_cr_write]        = POST_EX(SVM_EXIT_WRITE_CR0),
6055         [x86_intercept_clts]            = POST_EX(SVM_EXIT_WRITE_CR0),
6056         [x86_intercept_lmsw]            = POST_EX(SVM_EXIT_WRITE_CR0),
6057         [x86_intercept_smsw]            = POST_EX(SVM_EXIT_READ_CR0),
6058         [x86_intercept_dr_read]         = POST_EX(SVM_EXIT_READ_DR0),
6059         [x86_intercept_dr_write]        = POST_EX(SVM_EXIT_WRITE_DR0),
6060         [x86_intercept_sldt]            = POST_EX(SVM_EXIT_LDTR_READ),
6061         [x86_intercept_str]             = POST_EX(SVM_EXIT_TR_READ),
6062         [x86_intercept_lldt]            = POST_EX(SVM_EXIT_LDTR_WRITE),
6063         [x86_intercept_ltr]             = POST_EX(SVM_EXIT_TR_WRITE),
6064         [x86_intercept_sgdt]            = POST_EX(SVM_EXIT_GDTR_READ),
6065         [x86_intercept_sidt]            = POST_EX(SVM_EXIT_IDTR_READ),
6066         [x86_intercept_lgdt]            = POST_EX(SVM_EXIT_GDTR_WRITE),
6067         [x86_intercept_lidt]            = POST_EX(SVM_EXIT_IDTR_WRITE),
6068         [x86_intercept_vmrun]           = POST_EX(SVM_EXIT_VMRUN),
6069         [x86_intercept_vmmcall]         = POST_EX(SVM_EXIT_VMMCALL),
6070         [x86_intercept_vmload]          = POST_EX(SVM_EXIT_VMLOAD),
6071         [x86_intercept_vmsave]          = POST_EX(SVM_EXIT_VMSAVE),
6072         [x86_intercept_stgi]            = POST_EX(SVM_EXIT_STGI),
6073         [x86_intercept_clgi]            = POST_EX(SVM_EXIT_CLGI),
6074         [x86_intercept_skinit]          = POST_EX(SVM_EXIT_SKINIT),
6075         [x86_intercept_invlpga]         = POST_EX(SVM_EXIT_INVLPGA),
6076         [x86_intercept_rdtscp]          = POST_EX(SVM_EXIT_RDTSCP),
6077         [x86_intercept_monitor]         = POST_MEM(SVM_EXIT_MONITOR),
6078         [x86_intercept_mwait]           = POST_EX(SVM_EXIT_MWAIT),
6079         [x86_intercept_invlpg]          = POST_EX(SVM_EXIT_INVLPG),
6080         [x86_intercept_invd]            = POST_EX(SVM_EXIT_INVD),
6081         [x86_intercept_wbinvd]          = POST_EX(SVM_EXIT_WBINVD),
6082         [x86_intercept_wrmsr]           = POST_EX(SVM_EXIT_MSR),
6083         [x86_intercept_rdtsc]           = POST_EX(SVM_EXIT_RDTSC),
6084         [x86_intercept_rdmsr]           = POST_EX(SVM_EXIT_MSR),
6085         [x86_intercept_rdpmc]           = POST_EX(SVM_EXIT_RDPMC),
6086         [x86_intercept_cpuid]           = PRE_EX(SVM_EXIT_CPUID),
6087         [x86_intercept_rsm]             = PRE_EX(SVM_EXIT_RSM),
6088         [x86_intercept_pause]           = PRE_EX(SVM_EXIT_PAUSE),
6089         [x86_intercept_pushf]           = PRE_EX(SVM_EXIT_PUSHF),
6090         [x86_intercept_popf]            = PRE_EX(SVM_EXIT_POPF),
6091         [x86_intercept_intn]            = PRE_EX(SVM_EXIT_SWINT),
6092         [x86_intercept_iret]            = PRE_EX(SVM_EXIT_IRET),
6093         [x86_intercept_icebp]           = PRE_EX(SVM_EXIT_ICEBP),
6094         [x86_intercept_hlt]             = POST_EX(SVM_EXIT_HLT),
6095         [x86_intercept_in]              = POST_EX(SVM_EXIT_IOIO),
6096         [x86_intercept_ins]             = POST_EX(SVM_EXIT_IOIO),
6097         [x86_intercept_out]             = POST_EX(SVM_EXIT_IOIO),
6098         [x86_intercept_outs]            = POST_EX(SVM_EXIT_IOIO),
6099         [x86_intercept_xsetbv]          = PRE_EX(SVM_EXIT_XSETBV),
6100 };
6101
6102 #undef PRE_EX
6103 #undef POST_EX
6104 #undef POST_MEM
6105
6106 static int svm_check_intercept(struct kvm_vcpu *vcpu,
6107                                struct x86_instruction_info *info,
6108                                enum x86_intercept_stage stage)
6109 {
6110         struct vcpu_svm *svm = to_svm(vcpu);
6111         int vmexit, ret = X86EMUL_CONTINUE;
6112         struct __x86_intercept icpt_info;
6113         struct vmcb *vmcb = svm->vmcb;
6114
6115         if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
6116                 goto out;
6117
6118         icpt_info = x86_intercept_map[info->intercept];
6119
6120         if (stage != icpt_info.stage)
6121                 goto out;
6122
6123         switch (icpt_info.exit_code) {
6124         case SVM_EXIT_READ_CR0:
6125                 if (info->intercept == x86_intercept_cr_read)
6126                         icpt_info.exit_code += info->modrm_reg;
6127                 break;
6128         case SVM_EXIT_WRITE_CR0: {
6129                 unsigned long cr0, val;
6130                 u64 intercept;
6131
6132                 if (info->intercept == x86_intercept_cr_write)
6133                         icpt_info.exit_code += info->modrm_reg;
6134
6135                 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
6136                     info->intercept == x86_intercept_clts)
6137                         break;
6138
6139                 intercept = svm->nested.intercept;
6140
6141                 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
6142                         break;
6143
6144                 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
6145                 val = info->src_val  & ~SVM_CR0_SELECTIVE_MASK;
6146
6147                 if (info->intercept == x86_intercept_lmsw) {
6148                         cr0 &= 0xfUL;
6149                         val &= 0xfUL;
6150                         /* lmsw can't clear PE - catch this here */
6151                         if (cr0 & X86_CR0_PE)
6152                                 val |= X86_CR0_PE;
6153                 }
6154
6155                 if (cr0 ^ val)
6156                         icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
6157
6158                 break;
6159         }
6160         case SVM_EXIT_READ_DR0:
6161         case SVM_EXIT_WRITE_DR0:
6162                 icpt_info.exit_code += info->modrm_reg;
6163                 break;
6164         case SVM_EXIT_MSR:
6165                 if (info->intercept == x86_intercept_wrmsr)
6166                         vmcb->control.exit_info_1 = 1;
6167                 else
6168                         vmcb->control.exit_info_1 = 0;
6169                 break;
6170         case SVM_EXIT_PAUSE:
6171                 /*
6172                  * We get this for NOP only, but pause
6173                  * is rep not, check this here
6174                  */
6175                 if (info->rep_prefix != REPE_PREFIX)
6176                         goto out;
6177                 break;
6178         case SVM_EXIT_IOIO: {
6179                 u64 exit_info;
6180                 u32 bytes;
6181
6182                 if (info->intercept == x86_intercept_in ||
6183                     info->intercept == x86_intercept_ins) {
6184                         exit_info = ((info->src_val & 0xffff) << 16) |
6185                                 SVM_IOIO_TYPE_MASK;
6186                         bytes = info->dst_bytes;
6187                 } else {
6188                         exit_info = (info->dst_val & 0xffff) << 16;
6189                         bytes = info->src_bytes;
6190                 }
6191
6192                 if (info->intercept == x86_intercept_outs ||
6193                     info->intercept == x86_intercept_ins)
6194                         exit_info |= SVM_IOIO_STR_MASK;
6195
6196                 if (info->rep_prefix)
6197                         exit_info |= SVM_IOIO_REP_MASK;
6198
6199                 bytes = min(bytes, 4u);
6200
6201                 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
6202
6203                 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
6204
6205                 vmcb->control.exit_info_1 = exit_info;
6206                 vmcb->control.exit_info_2 = info->next_rip;
6207
6208                 break;
6209         }
6210         default:
6211                 break;
6212         }
6213
6214         /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
6215         if (static_cpu_has(X86_FEATURE_NRIPS))
6216                 vmcb->control.next_rip  = info->next_rip;
6217         vmcb->control.exit_code = icpt_info.exit_code;
6218         vmexit = nested_svm_exit_handled(svm);
6219
6220         ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
6221                                            : X86EMUL_CONTINUE;
6222
6223 out:
6224         return ret;
6225 }
6226
6227 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6228 {
6229
6230 }
6231
6232 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
6233 {
6234         if (pause_filter_thresh)
6235                 shrink_ple_window(vcpu);
6236 }
6237
6238 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
6239 {
6240         if (avic_handle_apic_id_update(vcpu) != 0)
6241                 return;
6242         avic_handle_dfr_update(vcpu);
6243         avic_handle_ldr_update(vcpu);
6244 }
6245
6246 static void svm_setup_mce(struct kvm_vcpu *vcpu)
6247 {
6248         /* [63:9] are reserved. */
6249         vcpu->arch.mcg_cap &= 0x1ff;
6250 }
6251
6252 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6253 {
6254         struct vcpu_svm *svm = to_svm(vcpu);
6255
6256         /* Per APM Vol.2 15.22.2 "Response to SMI" */
6257         if (!gif_set(svm))
6258                 return 0;
6259
6260         if (is_guest_mode(&svm->vcpu) &&
6261             svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6262                 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
6263                 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6264                 svm->nested.exit_required = true;
6265                 return 0;
6266         }
6267
6268         return 1;
6269 }
6270
6271 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6272 {
6273         struct vcpu_svm *svm = to_svm(vcpu);
6274         int ret;
6275
6276         if (is_guest_mode(vcpu)) {
6277                 /* FED8h - SVM Guest */
6278                 put_smstate(u64, smstate, 0x7ed8, 1);
6279                 /* FEE0h - SVM Guest VMCB Physical Address */
6280                 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6281
6282                 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6283                 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6284                 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6285
6286                 ret = nested_svm_vmexit(svm);
6287                 if (ret)
6288                         return ret;
6289         }
6290         return 0;
6291 }
6292
6293 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
6294 {
6295         struct vcpu_svm *svm = to_svm(vcpu);
6296         struct vmcb *nested_vmcb;
6297         struct kvm_host_map map;
6298         u64 guest;
6299         u64 vmcb;
6300
6301         guest = GET_SMSTATE(u64, smstate, 0x7ed8);
6302         vmcb = GET_SMSTATE(u64, smstate, 0x7ee0);
6303
6304         if (guest) {
6305                 if (kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb), &map) == -EINVAL)
6306                         return 1;
6307                 nested_vmcb = map.hva;
6308                 enter_svm_guest_mode(svm, vmcb, nested_vmcb, &map);
6309         }
6310         return 0;
6311 }
6312
6313 static int enable_smi_window(struct kvm_vcpu *vcpu)
6314 {
6315         struct vcpu_svm *svm = to_svm(vcpu);
6316
6317         if (!gif_set(svm)) {
6318                 if (vgif_enabled(svm))
6319                         set_intercept(svm, INTERCEPT_STGI);
6320                 /* STGI will cause a vm exit */
6321                 return 1;
6322         }
6323         return 0;
6324 }
6325
6326 static int sev_asid_new(void)
6327 {
6328         int pos;
6329
6330         /*
6331          * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6332          */
6333         pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6334         if (pos >= max_sev_asid)
6335                 return -EBUSY;
6336
6337         set_bit(pos, sev_asid_bitmap);
6338         return pos + 1;
6339 }
6340
6341 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6342 {
6343         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6344         int asid, ret;
6345
6346         ret = -EBUSY;
6347         if (unlikely(sev->active))
6348                 return ret;
6349
6350         asid = sev_asid_new();
6351         if (asid < 0)
6352                 return ret;
6353
6354         ret = sev_platform_init(&argp->error);
6355         if (ret)
6356                 goto e_free;
6357
6358         sev->active = true;
6359         sev->asid = asid;
6360         INIT_LIST_HEAD(&sev->regions_list);
6361
6362         return 0;
6363
6364 e_free:
6365         __sev_asid_free(asid);
6366         return ret;
6367 }
6368
6369 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6370 {
6371         struct sev_data_activate *data;
6372         int asid = sev_get_asid(kvm);
6373         int ret;
6374
6375         wbinvd_on_all_cpus();
6376
6377         ret = sev_guest_df_flush(error);
6378         if (ret)
6379                 return ret;
6380
6381         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6382         if (!data)
6383                 return -ENOMEM;
6384
6385         /* activate ASID on the given handle */
6386         data->handle = handle;
6387         data->asid   = asid;
6388         ret = sev_guest_activate(data, error);
6389         kfree(data);
6390
6391         return ret;
6392 }
6393
6394 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6395 {
6396         struct fd f;
6397         int ret;
6398
6399         f = fdget(fd);
6400         if (!f.file)
6401                 return -EBADF;
6402
6403         ret = sev_issue_cmd_external_user(f.file, id, data, error);
6404
6405         fdput(f);
6406         return ret;
6407 }
6408
6409 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6410 {
6411         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6412
6413         return __sev_issue_cmd(sev->fd, id, data, error);
6414 }
6415
6416 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6417 {
6418         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6419         struct sev_data_launch_start *start;
6420         struct kvm_sev_launch_start params;
6421         void *dh_blob, *session_blob;
6422         int *error = &argp->error;
6423         int ret;
6424
6425         if (!sev_guest(kvm))
6426                 return -ENOTTY;
6427
6428         if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6429                 return -EFAULT;
6430
6431         start = kzalloc(sizeof(*start), GFP_KERNEL_ACCOUNT);
6432         if (!start)
6433                 return -ENOMEM;
6434
6435         dh_blob = NULL;
6436         if (params.dh_uaddr) {
6437                 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6438                 if (IS_ERR(dh_blob)) {
6439                         ret = PTR_ERR(dh_blob);
6440                         goto e_free;
6441                 }
6442
6443                 start->dh_cert_address = __sme_set(__pa(dh_blob));
6444                 start->dh_cert_len = params.dh_len;
6445         }
6446
6447         session_blob = NULL;
6448         if (params.session_uaddr) {
6449                 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6450                 if (IS_ERR(session_blob)) {
6451                         ret = PTR_ERR(session_blob);
6452                         goto e_free_dh;
6453                 }
6454
6455                 start->session_address = __sme_set(__pa(session_blob));
6456                 start->session_len = params.session_len;
6457         }
6458
6459         start->handle = params.handle;
6460         start->policy = params.policy;
6461
6462         /* create memory encryption context */
6463         ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6464         if (ret)
6465                 goto e_free_session;
6466
6467         /* Bind ASID to this guest */
6468         ret = sev_bind_asid(kvm, start->handle, error);
6469         if (ret)
6470                 goto e_free_session;
6471
6472         /* return handle to userspace */
6473         params.handle = start->handle;
6474         if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
6475                 sev_unbind_asid(kvm, start->handle);
6476                 ret = -EFAULT;
6477                 goto e_free_session;
6478         }
6479
6480         sev->handle = start->handle;
6481         sev->fd = argp->sev_fd;
6482
6483 e_free_session:
6484         kfree(session_blob);
6485 e_free_dh:
6486         kfree(dh_blob);
6487 e_free:
6488         kfree(start);
6489         return ret;
6490 }
6491
6492 static unsigned long get_num_contig_pages(unsigned long idx,
6493                                 struct page **inpages, unsigned long npages)
6494 {
6495         unsigned long paddr, next_paddr;
6496         unsigned long i = idx + 1, pages = 1;
6497
6498         /* find the number of contiguous pages starting from idx */
6499         paddr = __sme_page_pa(inpages[idx]);
6500         while (i < npages) {
6501                 next_paddr = __sme_page_pa(inpages[i++]);
6502                 if ((paddr + PAGE_SIZE) == next_paddr) {
6503                         pages++;
6504                         paddr = next_paddr;
6505                         continue;
6506                 }
6507                 break;
6508         }
6509
6510         return pages;
6511 }
6512
6513 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6514 {
6515         unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
6516         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6517         struct kvm_sev_launch_update_data params;
6518         struct sev_data_launch_update_data *data;
6519         struct page **inpages;
6520         int ret;
6521
6522         if (!sev_guest(kvm))
6523                 return -ENOTTY;
6524
6525         if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6526                 return -EFAULT;
6527
6528         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6529         if (!data)
6530                 return -ENOMEM;
6531
6532         vaddr = params.uaddr;
6533         size = params.len;
6534         vaddr_end = vaddr + size;
6535
6536         /* Lock the user memory. */
6537         inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6538         if (!inpages) {
6539                 ret = -ENOMEM;
6540                 goto e_free;
6541         }
6542
6543         /*
6544          * The LAUNCH_UPDATE command will perform in-place encryption of the
6545          * memory content (i.e it will write the same memory region with C=1).
6546          * It's possible that the cache may contain the data with C=0, i.e.,
6547          * unencrypted so invalidate it first.
6548          */
6549         sev_clflush_pages(inpages, npages);
6550
6551         for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6552                 int offset, len;
6553
6554                 /*
6555                  * If the user buffer is not page-aligned, calculate the offset
6556                  * within the page.
6557                  */
6558                 offset = vaddr & (PAGE_SIZE - 1);
6559
6560                 /* Calculate the number of pages that can be encrypted in one go. */
6561                 pages = get_num_contig_pages(i, inpages, npages);
6562
6563                 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6564
6565                 data->handle = sev->handle;
6566                 data->len = len;
6567                 data->address = __sme_page_pa(inpages[i]) + offset;
6568                 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6569                 if (ret)
6570                         goto e_unpin;
6571
6572                 size -= len;
6573                 next_vaddr = vaddr + len;
6574         }
6575
6576 e_unpin:
6577         /* content of memory is updated, mark pages dirty */
6578         for (i = 0; i < npages; i++) {
6579                 set_page_dirty_lock(inpages[i]);
6580                 mark_page_accessed(inpages[i]);
6581         }
6582         /* unlock the user pages */
6583         sev_unpin_memory(kvm, inpages, npages);
6584 e_free:
6585         kfree(data);
6586         return ret;
6587 }
6588
6589 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6590 {
6591         void __user *measure = (void __user *)(uintptr_t)argp->data;
6592         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6593         struct sev_data_launch_measure *data;
6594         struct kvm_sev_launch_measure params;
6595         void __user *p = NULL;
6596         void *blob = NULL;
6597         int ret;
6598
6599         if (!sev_guest(kvm))
6600                 return -ENOTTY;
6601
6602         if (copy_from_user(&params, measure, sizeof(params)))
6603                 return -EFAULT;
6604
6605         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6606         if (!data)
6607                 return -ENOMEM;
6608
6609         /* User wants to query the blob length */
6610         if (!params.len)
6611                 goto cmd;
6612
6613         p = (void __user *)(uintptr_t)params.uaddr;
6614         if (p) {
6615                 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6616                         ret = -EINVAL;
6617                         goto e_free;
6618                 }
6619
6620                 ret = -ENOMEM;
6621                 blob = kmalloc(params.len, GFP_KERNEL);
6622                 if (!blob)
6623                         goto e_free;
6624
6625                 data->address = __psp_pa(blob);
6626                 data->len = params.len;
6627         }
6628
6629 cmd:
6630         data->handle = sev->handle;
6631         ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6632
6633         /*
6634          * If we query the session length, FW responded with expected data.
6635          */
6636         if (!params.len)
6637                 goto done;
6638
6639         if (ret)
6640                 goto e_free_blob;
6641
6642         if (blob) {
6643                 if (copy_to_user(p, blob, params.len))
6644                         ret = -EFAULT;
6645         }
6646
6647 done:
6648         params.len = data->len;
6649         if (copy_to_user(measure, &params, sizeof(params)))
6650                 ret = -EFAULT;
6651 e_free_blob:
6652         kfree(blob);
6653 e_free:
6654         kfree(data);
6655         return ret;
6656 }
6657
6658 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6659 {
6660         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6661         struct sev_data_launch_finish *data;
6662         int ret;
6663
6664         if (!sev_guest(kvm))
6665                 return -ENOTTY;
6666
6667         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6668         if (!data)
6669                 return -ENOMEM;
6670
6671         data->handle = sev->handle;
6672         ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6673
6674         kfree(data);
6675         return ret;
6676 }
6677
6678 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6679 {
6680         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6681         struct kvm_sev_guest_status params;
6682         struct sev_data_guest_status *data;
6683         int ret;
6684
6685         if (!sev_guest(kvm))
6686                 return -ENOTTY;
6687
6688         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6689         if (!data)
6690                 return -ENOMEM;
6691
6692         data->handle = sev->handle;
6693         ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6694         if (ret)
6695                 goto e_free;
6696
6697         params.policy = data->policy;
6698         params.state = data->state;
6699         params.handle = data->handle;
6700
6701         if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
6702                 ret = -EFAULT;
6703 e_free:
6704         kfree(data);
6705         return ret;
6706 }
6707
6708 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6709                                unsigned long dst, int size,
6710                                int *error, bool enc)
6711 {
6712         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6713         struct sev_data_dbg *data;
6714         int ret;
6715
6716         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6717         if (!data)
6718                 return -ENOMEM;
6719
6720         data->handle = sev->handle;
6721         data->dst_addr = dst;
6722         data->src_addr = src;
6723         data->len = size;
6724
6725         ret = sev_issue_cmd(kvm,
6726                             enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6727                             data, error);
6728         kfree(data);
6729         return ret;
6730 }
6731
6732 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6733                              unsigned long dst_paddr, int sz, int *err)
6734 {
6735         int offset;
6736
6737         /*
6738          * Its safe to read more than we are asked, caller should ensure that
6739          * destination has enough space.
6740          */
6741         src_paddr = round_down(src_paddr, 16);
6742         offset = src_paddr & 15;
6743         sz = round_up(sz + offset, 16);
6744
6745         return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6746 }
6747
6748 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6749                                   unsigned long __user dst_uaddr,
6750                                   unsigned long dst_paddr,
6751                                   int size, int *err)
6752 {
6753         struct page *tpage = NULL;
6754         int ret, offset;
6755
6756         /* if inputs are not 16-byte then use intermediate buffer */
6757         if (!IS_ALIGNED(dst_paddr, 16) ||
6758             !IS_ALIGNED(paddr,     16) ||
6759             !IS_ALIGNED(size,      16)) {
6760                 tpage = (void *)alloc_page(GFP_KERNEL);
6761                 if (!tpage)
6762                         return -ENOMEM;
6763
6764                 dst_paddr = __sme_page_pa(tpage);
6765         }
6766
6767         ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6768         if (ret)
6769                 goto e_free;
6770
6771         if (tpage) {
6772                 offset = paddr & 15;
6773                 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6774                                  page_address(tpage) + offset, size))
6775                         ret = -EFAULT;
6776         }
6777
6778 e_free:
6779         if (tpage)
6780                 __free_page(tpage);
6781
6782         return ret;
6783 }
6784
6785 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6786                                   unsigned long __user vaddr,
6787                                   unsigned long dst_paddr,
6788                                   unsigned long __user dst_vaddr,
6789                                   int size, int *error)
6790 {
6791         struct page *src_tpage = NULL;
6792         struct page *dst_tpage = NULL;
6793         int ret, len = size;
6794
6795         /* If source buffer is not aligned then use an intermediate buffer */
6796         if (!IS_ALIGNED(vaddr, 16)) {
6797                 src_tpage = alloc_page(GFP_KERNEL);
6798                 if (!src_tpage)
6799                         return -ENOMEM;
6800
6801                 if (copy_from_user(page_address(src_tpage),
6802                                 (void __user *)(uintptr_t)vaddr, size)) {
6803                         __free_page(src_tpage);
6804                         return -EFAULT;
6805                 }
6806
6807                 paddr = __sme_page_pa(src_tpage);
6808         }
6809
6810         /*
6811          *  If destination buffer or length is not aligned then do read-modify-write:
6812          *   - decrypt destination in an intermediate buffer
6813          *   - copy the source buffer in an intermediate buffer
6814          *   - use the intermediate buffer as source buffer
6815          */
6816         if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6817                 int dst_offset;
6818
6819                 dst_tpage = alloc_page(GFP_KERNEL);
6820                 if (!dst_tpage) {
6821                         ret = -ENOMEM;
6822                         goto e_free;
6823                 }
6824
6825                 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6826                                         __sme_page_pa(dst_tpage), size, error);
6827                 if (ret)
6828                         goto e_free;
6829
6830                 /*
6831                  *  If source is kernel buffer then use memcpy() otherwise
6832                  *  copy_from_user().
6833                  */
6834                 dst_offset = dst_paddr & 15;
6835
6836                 if (src_tpage)
6837                         memcpy(page_address(dst_tpage) + dst_offset,
6838                                page_address(src_tpage), size);
6839                 else {
6840                         if (copy_from_user(page_address(dst_tpage) + dst_offset,
6841                                            (void __user *)(uintptr_t)vaddr, size)) {
6842                                 ret = -EFAULT;
6843                                 goto e_free;
6844                         }
6845                 }
6846
6847                 paddr = __sme_page_pa(dst_tpage);
6848                 dst_paddr = round_down(dst_paddr, 16);
6849                 len = round_up(size, 16);
6850         }
6851
6852         ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6853
6854 e_free:
6855         if (src_tpage)
6856                 __free_page(src_tpage);
6857         if (dst_tpage)
6858                 __free_page(dst_tpage);
6859         return ret;
6860 }
6861
6862 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6863 {
6864         unsigned long vaddr, vaddr_end, next_vaddr;
6865         unsigned long dst_vaddr;
6866         struct page **src_p, **dst_p;
6867         struct kvm_sev_dbg debug;
6868         unsigned long n;
6869         unsigned int size;
6870         int ret;
6871
6872         if (!sev_guest(kvm))
6873                 return -ENOTTY;
6874
6875         if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6876                 return -EFAULT;
6877
6878         if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
6879                 return -EINVAL;
6880         if (!debug.dst_uaddr)
6881                 return -EINVAL;
6882
6883         vaddr = debug.src_uaddr;
6884         size = debug.len;
6885         vaddr_end = vaddr + size;
6886         dst_vaddr = debug.dst_uaddr;
6887
6888         for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6889                 int len, s_off, d_off;
6890
6891                 /* lock userspace source and destination page */
6892                 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6893                 if (!src_p)
6894                         return -EFAULT;
6895
6896                 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6897                 if (!dst_p) {
6898                         sev_unpin_memory(kvm, src_p, n);
6899                         return -EFAULT;
6900                 }
6901
6902                 /*
6903                  * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6904                  * memory content (i.e it will write the same memory region with C=1).
6905                  * It's possible that the cache may contain the data with C=0, i.e.,
6906                  * unencrypted so invalidate it first.
6907                  */
6908                 sev_clflush_pages(src_p, 1);
6909                 sev_clflush_pages(dst_p, 1);
6910
6911                 /*
6912                  * Since user buffer may not be page aligned, calculate the
6913                  * offset within the page.
6914                  */
6915                 s_off = vaddr & ~PAGE_MASK;
6916                 d_off = dst_vaddr & ~PAGE_MASK;
6917                 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6918
6919                 if (dec)
6920                         ret = __sev_dbg_decrypt_user(kvm,
6921                                                      __sme_page_pa(src_p[0]) + s_off,
6922                                                      dst_vaddr,
6923                                                      __sme_page_pa(dst_p[0]) + d_off,
6924                                                      len, &argp->error);
6925                 else
6926                         ret = __sev_dbg_encrypt_user(kvm,
6927                                                      __sme_page_pa(src_p[0]) + s_off,
6928                                                      vaddr,
6929                                                      __sme_page_pa(dst_p[0]) + d_off,
6930                                                      dst_vaddr,
6931                                                      len, &argp->error);
6932
6933                 sev_unpin_memory(kvm, src_p, n);
6934                 sev_unpin_memory(kvm, dst_p, n);
6935
6936                 if (ret)
6937                         goto err;
6938
6939                 next_vaddr = vaddr + len;
6940                 dst_vaddr = dst_vaddr + len;
6941                 size -= len;
6942         }
6943 err:
6944         return ret;
6945 }
6946
6947 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6948 {
6949         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6950         struct sev_data_launch_secret *data;
6951         struct kvm_sev_launch_secret params;
6952         struct page **pages;
6953         void *blob, *hdr;
6954         unsigned long n;
6955         int ret, offset;
6956
6957         if (!sev_guest(kvm))
6958                 return -ENOTTY;
6959
6960         if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6961                 return -EFAULT;
6962
6963         pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6964         if (!pages)
6965                 return -ENOMEM;
6966
6967         /*
6968          * The secret must be copied into contiguous memory region, lets verify
6969          * that userspace memory pages are contiguous before we issue command.
6970          */
6971         if (get_num_contig_pages(0, pages, n) != n) {
6972                 ret = -EINVAL;
6973                 goto e_unpin_memory;
6974         }
6975
6976         ret = -ENOMEM;
6977         data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6978         if (!data)
6979                 goto e_unpin_memory;
6980
6981         offset = params.guest_uaddr & (PAGE_SIZE - 1);
6982         data->guest_address = __sme_page_pa(pages[0]) + offset;
6983         data->guest_len = params.guest_len;
6984
6985         blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6986         if (IS_ERR(blob)) {
6987                 ret = PTR_ERR(blob);
6988                 goto e_free;
6989         }
6990
6991         data->trans_address = __psp_pa(blob);
6992         data->trans_len = params.trans_len;
6993
6994         hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6995         if (IS_ERR(hdr)) {
6996                 ret = PTR_ERR(hdr);
6997                 goto e_free_blob;
6998         }
6999         data->hdr_address = __psp_pa(hdr);
7000         data->hdr_len = params.hdr_len;
7001
7002         data->handle = sev->handle;
7003         ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
7004
7005         kfree(hdr);
7006
7007 e_free_blob:
7008         kfree(blob);
7009 e_free:
7010         kfree(data);
7011 e_unpin_memory:
7012         sev_unpin_memory(kvm, pages, n);
7013         return ret;
7014 }
7015
7016 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
7017 {
7018         struct kvm_sev_cmd sev_cmd;
7019         int r;
7020
7021         if (!svm_sev_enabled())
7022                 return -ENOTTY;
7023
7024         if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
7025                 return -EFAULT;
7026
7027         mutex_lock(&kvm->lock);
7028
7029         switch (sev_cmd.id) {
7030         case KVM_SEV_INIT:
7031                 r = sev_guest_init(kvm, &sev_cmd);
7032                 break;
7033         case KVM_SEV_LAUNCH_START:
7034                 r = sev_launch_start(kvm, &sev_cmd);
7035                 break;
7036         case KVM_SEV_LAUNCH_UPDATE_DATA:
7037                 r = sev_launch_update_data(kvm, &sev_cmd);
7038                 break;
7039         case KVM_SEV_LAUNCH_MEASURE:
7040                 r = sev_launch_measure(kvm, &sev_cmd);
7041                 break;
7042         case KVM_SEV_LAUNCH_FINISH:
7043                 r = sev_launch_finish(kvm, &sev_cmd);
7044                 break;
7045         case KVM_SEV_GUEST_STATUS:
7046                 r = sev_guest_status(kvm, &sev_cmd);
7047                 break;
7048         case KVM_SEV_DBG_DECRYPT:
7049                 r = sev_dbg_crypt(kvm, &sev_cmd, true);
7050                 break;
7051         case KVM_SEV_DBG_ENCRYPT:
7052                 r = sev_dbg_crypt(kvm, &sev_cmd, false);
7053                 break;
7054         case KVM_SEV_LAUNCH_SECRET:
7055                 r = sev_launch_secret(kvm, &sev_cmd);
7056                 break;
7057         default:
7058                 r = -EINVAL;
7059                 goto out;
7060         }
7061
7062         if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
7063                 r = -EFAULT;
7064
7065 out:
7066         mutex_unlock(&kvm->lock);
7067         return r;
7068 }
7069
7070 static int svm_register_enc_region(struct kvm *kvm,
7071                                    struct kvm_enc_region *range)
7072 {
7073         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7074         struct enc_region *region;
7075         int ret = 0;
7076
7077         if (!sev_guest(kvm))
7078                 return -ENOTTY;
7079
7080         if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
7081                 return -EINVAL;
7082
7083         region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
7084         if (!region)
7085                 return -ENOMEM;
7086
7087         region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
7088         if (!region->pages) {
7089                 ret = -ENOMEM;
7090                 goto e_free;
7091         }
7092
7093         /*
7094          * The guest may change the memory encryption attribute from C=0 -> C=1
7095          * or vice versa for this memory range. Lets make sure caches are
7096          * flushed to ensure that guest data gets written into memory with
7097          * correct C-bit.
7098          */
7099         sev_clflush_pages(region->pages, region->npages);
7100
7101         region->uaddr = range->addr;
7102         region->size = range->size;
7103
7104         mutex_lock(&kvm->lock);
7105         list_add_tail(&region->list, &sev->regions_list);
7106         mutex_unlock(&kvm->lock);
7107
7108         return ret;
7109
7110 e_free:
7111         kfree(region);
7112         return ret;
7113 }
7114
7115 static struct enc_region *
7116 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
7117 {
7118         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7119         struct list_head *head = &sev->regions_list;
7120         struct enc_region *i;
7121
7122         list_for_each_entry(i, head, list) {
7123                 if (i->uaddr == range->addr &&
7124                     i->size == range->size)
7125                         return i;
7126         }
7127
7128         return NULL;
7129 }
7130
7131
7132 static int svm_unregister_enc_region(struct kvm *kvm,
7133                                      struct kvm_enc_region *range)
7134 {
7135         struct enc_region *region;
7136         int ret;
7137
7138         mutex_lock(&kvm->lock);
7139
7140         if (!sev_guest(kvm)) {
7141                 ret = -ENOTTY;
7142                 goto failed;
7143         }
7144
7145         region = find_enc_region(kvm, range);
7146         if (!region) {
7147                 ret = -EINVAL;
7148                 goto failed;
7149         }
7150
7151         __unregister_enc_region_locked(kvm, region);
7152
7153         mutex_unlock(&kvm->lock);
7154         return 0;
7155
7156 failed:
7157         mutex_unlock(&kvm->lock);
7158         return ret;
7159 }
7160
7161 static bool svm_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7162 {
7163         unsigned long cr4 = kvm_read_cr4(vcpu);
7164         bool smep = cr4 & X86_CR4_SMEP;
7165         bool smap = cr4 & X86_CR4_SMAP;
7166         bool is_user = svm_get_cpl(vcpu) == 3;
7167
7168         /*
7169          * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
7170          *
7171          * Errata:
7172          * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
7173          * possible that CPU microcode implementing DecodeAssist will fail
7174          * to read bytes of instruction which caused #NPF. In this case,
7175          * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
7176          * return 0 instead of the correct guest instruction bytes.
7177          *
7178          * This happens because CPU microcode reading instruction bytes
7179          * uses a special opcode which attempts to read data using CPL=0
7180          * priviledges. The microcode reads CS:RIP and if it hits a SMAP
7181          * fault, it gives up and returns no instruction bytes.
7182          *
7183          * Detection:
7184          * We reach here in case CPU supports DecodeAssist, raised #NPF and
7185          * returned 0 in GuestIntrBytes field of the VMCB.
7186          * First, errata can only be triggered in case vCPU CR4.SMAP=1.
7187          * Second, if vCPU CR4.SMEP=1, errata could only be triggered
7188          * in case vCPU CPL==3 (Because otherwise guest would have triggered
7189          * a SMEP fault instead of #NPF).
7190          * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
7191          * As most guests enable SMAP if they have also enabled SMEP, use above
7192          * logic in order to attempt minimize false-positive of detecting errata
7193          * while still preserving all cases semantic correctness.
7194          *
7195          * Workaround:
7196          * To determine what instruction the guest was executing, the hypervisor
7197          * will have to decode the instruction at the instruction pointer.
7198          *
7199          * In non SEV guest, hypervisor will be able to read the guest
7200          * memory to decode the instruction pointer when insn_len is zero
7201          * so we return true to indicate that decoding is possible.
7202          *
7203          * But in the SEV guest, the guest memory is encrypted with the
7204          * guest specific key and hypervisor will not be able to decode the
7205          * instruction pointer so we will not able to workaround it. Lets
7206          * print the error and request to kill the guest.
7207          */
7208         if (smap && (!smep || is_user)) {
7209                 if (!sev_guest(vcpu->kvm))
7210                         return true;
7211
7212                 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
7213                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7214         }
7215
7216         return false;
7217 }
7218
7219 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7220 {
7221         struct vcpu_svm *svm = to_svm(vcpu);
7222
7223         /*
7224          * TODO: Last condition latch INIT signals on vCPU when
7225          * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
7226          * To properly emulate the INIT intercept, SVM should implement
7227          * kvm_x86_ops->check_nested_events() and call nested_svm_vmexit()
7228          * there if an INIT signal is pending.
7229          */
7230         return !gif_set(svm) ||
7231                    (svm->vmcb->control.intercept & (1ULL << INTERCEPT_INIT));
7232 }
7233
7234 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7235         .cpu_has_kvm_support = has_svm,
7236         .disabled_by_bios = is_disabled,
7237         .hardware_setup = svm_hardware_setup,
7238         .hardware_unsetup = svm_hardware_unsetup,
7239         .check_processor_compatibility = svm_check_processor_compat,
7240         .hardware_enable = svm_hardware_enable,
7241         .hardware_disable = svm_hardware_disable,
7242         .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
7243         .has_emulated_msr = svm_has_emulated_msr,
7244
7245         .vcpu_create = svm_create_vcpu,
7246         .vcpu_free = svm_free_vcpu,
7247         .vcpu_reset = svm_vcpu_reset,
7248
7249         .vm_alloc = svm_vm_alloc,
7250         .vm_free = svm_vm_free,
7251         .vm_init = avic_vm_init,
7252         .vm_destroy = svm_vm_destroy,
7253
7254         .prepare_guest_switch = svm_prepare_guest_switch,
7255         .vcpu_load = svm_vcpu_load,
7256         .vcpu_put = svm_vcpu_put,
7257         .vcpu_blocking = svm_vcpu_blocking,
7258         .vcpu_unblocking = svm_vcpu_unblocking,
7259
7260         .update_bp_intercept = update_bp_intercept,
7261         .get_msr_feature = svm_get_msr_feature,
7262         .get_msr = svm_get_msr,
7263         .set_msr = svm_set_msr,
7264         .get_segment_base = svm_get_segment_base,
7265         .get_segment = svm_get_segment,
7266         .set_segment = svm_set_segment,
7267         .get_cpl = svm_get_cpl,
7268         .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
7269         .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
7270         .decache_cr3 = svm_decache_cr3,
7271         .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
7272         .set_cr0 = svm_set_cr0,
7273         .set_cr3 = svm_set_cr3,
7274         .set_cr4 = svm_set_cr4,
7275         .set_efer = svm_set_efer,
7276         .get_idt = svm_get_idt,
7277         .set_idt = svm_set_idt,
7278         .get_gdt = svm_get_gdt,
7279         .set_gdt = svm_set_gdt,
7280         .get_dr6 = svm_get_dr6,
7281         .set_dr6 = svm_set_dr6,
7282         .set_dr7 = svm_set_dr7,
7283         .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
7284         .cache_reg = svm_cache_reg,
7285         .get_rflags = svm_get_rflags,
7286         .set_rflags = svm_set_rflags,
7287
7288         .tlb_flush = svm_flush_tlb,
7289         .tlb_flush_gva = svm_flush_tlb_gva,
7290
7291         .run = svm_vcpu_run,
7292         .handle_exit = handle_exit,
7293         .skip_emulated_instruction = skip_emulated_instruction,
7294         .set_interrupt_shadow = svm_set_interrupt_shadow,
7295         .get_interrupt_shadow = svm_get_interrupt_shadow,
7296         .patch_hypercall = svm_patch_hypercall,
7297         .set_irq = svm_set_irq,
7298         .set_nmi = svm_inject_nmi,
7299         .queue_exception = svm_queue_exception,
7300         .cancel_injection = svm_cancel_injection,
7301         .interrupt_allowed = svm_interrupt_allowed,
7302         .nmi_allowed = svm_nmi_allowed,
7303         .get_nmi_mask = svm_get_nmi_mask,
7304         .set_nmi_mask = svm_set_nmi_mask,
7305         .enable_nmi_window = enable_nmi_window,
7306         .enable_irq_window = enable_irq_window,
7307         .update_cr8_intercept = update_cr8_intercept,
7308         .set_virtual_apic_mode = svm_set_virtual_apic_mode,
7309         .get_enable_apicv = svm_get_enable_apicv,
7310         .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
7311         .load_eoi_exitmap = svm_load_eoi_exitmap,
7312         .hwapic_irr_update = svm_hwapic_irr_update,
7313         .hwapic_isr_update = svm_hwapic_isr_update,
7314         .sync_pir_to_irr = kvm_lapic_find_highest_irr,
7315         .apicv_post_state_restore = avic_post_state_restore,
7316
7317         .set_tss_addr = svm_set_tss_addr,
7318         .set_identity_map_addr = svm_set_identity_map_addr,
7319         .get_tdp_level = get_npt_level,
7320         .get_mt_mask = svm_get_mt_mask,
7321
7322         .get_exit_info = svm_get_exit_info,
7323
7324         .get_lpage_level = svm_get_lpage_level,
7325
7326         .cpuid_update = svm_cpuid_update,
7327
7328         .rdtscp_supported = svm_rdtscp_supported,
7329         .invpcid_supported = svm_invpcid_supported,
7330         .mpx_supported = svm_mpx_supported,
7331         .xsaves_supported = svm_xsaves_supported,
7332         .umip_emulated = svm_umip_emulated,
7333         .pt_supported = svm_pt_supported,
7334         .pku_supported = svm_pku_supported,
7335
7336         .set_supported_cpuid = svm_set_supported_cpuid,
7337
7338         .has_wbinvd_exit = svm_has_wbinvd_exit,
7339
7340         .read_l1_tsc_offset = svm_read_l1_tsc_offset,
7341         .write_l1_tsc_offset = svm_write_l1_tsc_offset,
7342
7343         .set_tdp_cr3 = set_tdp_cr3,
7344
7345         .check_intercept = svm_check_intercept,
7346         .handle_exit_irqoff = svm_handle_exit_irqoff,
7347
7348         .request_immediate_exit = __kvm_request_immediate_exit,
7349
7350         .sched_in = svm_sched_in,
7351
7352         .pmu_ops = &amd_pmu_ops,
7353         .deliver_posted_interrupt = svm_deliver_avic_intr,
7354         .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
7355         .update_pi_irte = svm_update_pi_irte,
7356         .setup_mce = svm_setup_mce,
7357
7358         .smi_allowed = svm_smi_allowed,
7359         .pre_enter_smm = svm_pre_enter_smm,
7360         .pre_leave_smm = svm_pre_leave_smm,
7361         .enable_smi_window = enable_smi_window,
7362
7363         .mem_enc_op = svm_mem_enc_op,
7364         .mem_enc_reg_region = svm_register_enc_region,
7365         .mem_enc_unreg_region = svm_unregister_enc_region,
7366
7367         .nested_enable_evmcs = NULL,
7368         .nested_get_evmcs_version = NULL,
7369
7370         .need_emulation_on_page_fault = svm_need_emulation_on_page_fault,
7371
7372         .apic_init_signal_blocked = svm_apic_init_signal_blocked,
7373 };
7374
7375 static int __init svm_init(void)
7376 {
7377         return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7378                         __alignof__(struct vcpu_svm), THIS_MODULE);
7379 }
7380
7381 static void __exit svm_exit(void)
7382 {
7383         kvm_exit();
7384 }
7385
7386 module_init(svm_init)
7387 module_exit(svm_exit)