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