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