~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/arch/x86/kvm/svm.c

Version: ~ [ linux-5.16 ] ~ [ linux-5.15.13 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.90 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.170 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.224 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.261 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.296 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.298 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.18.140 ] ~ [ linux-3.16.85 ] ~ [ linux-3.14.79 ] ~ [ linux-3.12.74 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  1 /*
  2  * Kernel-based Virtual Machine driver for Linux
  3  *
  4  * AMD SVM support
  5  *
  6  * Copyright (C) 2006 Qumranet, Inc.
  7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  8  *
  9  * Authors:
 10  *   Yaniv Kamay  <yaniv@qumranet.com>
 11  *   Avi Kivity   <avi@qumranet.com>
 12  *
 13  * This work is licensed under the terms of the GNU GPL, version 2.  See
 14  * the COPYING file in the top-level directory.
 15  *
 16  */
 17 
 18 #define pr_fmt(fmt) "SVM: " fmt
 19 
 20 #include <linux/kvm_host.h>
 21 
 22 #include "irq.h"
 23 #include "mmu.h"
 24 #include "kvm_cache_regs.h"
 25 #include "x86.h"
 26 #include "cpuid.h"
 27 #include "pmu.h"
 28 
 29 #include <linux/module.h>
 30 #include <linux/mod_devicetable.h>
 31 #include <linux/kernel.h>
 32 #include <linux/vmalloc.h>
 33 #include <linux/highmem.h>
 34 #include <linux/sched.h>
 35 #include <linux/trace_events.h>
 36 #include <linux/slab.h>
 37 #include <linux/amd-iommu.h>
 38 #include <linux/hashtable.h>
 39 #include <linux/frame.h>
 40 #include <linux/psp-sev.h>
 41 #include <linux/file.h>
 42 #include <linux/pagemap.h>
 43 #include <linux/swap.h>
 44 
 45 #include <asm/apic.h>
 46 #include <asm/perf_event.h>
 47 #include <asm/tlbflush.h>
 48 #include <asm/desc.h>
 49 #include <asm/debugreg.h>
 50 #include <asm/kvm_para.h>
 51 #include <asm/irq_remapping.h>
 52 #include <asm/spec-ctrl.h>
 53 
 54 #include <asm/virtext.h>
 55 #include "trace.h"
 56 
 57 #define __ex(x) __kvm_handle_fault_on_reboot(x)
 58 
 59 MODULE_AUTHOR("Qumranet");
 60 MODULE_LICENSE("GPL");
 61 
 62 static const struct x86_cpu_id svm_cpu_id[] = {
 63         X86_FEATURE_MATCH(X86_FEATURE_SVM),
 64         {}
 65 };
 66 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
 67 
 68 #define IOPM_ALLOC_ORDER 2
 69 #define MSRPM_ALLOC_ORDER 1
 70 
 71 #define SEG_TYPE_LDT 2
 72 #define SEG_TYPE_BUSY_TSS16 3
 73 
 74 #define SVM_FEATURE_NPT            (1 <<  0)
 75 #define SVM_FEATURE_LBRV           (1 <<  1)
 76 #define SVM_FEATURE_SVML           (1 <<  2)
 77 #define SVM_FEATURE_NRIP           (1 <<  3)
 78 #define SVM_FEATURE_TSC_RATE       (1 <<  4)
 79 #define SVM_FEATURE_VMCB_CLEAN     (1 <<  5)
 80 #define SVM_FEATURE_FLUSH_ASID     (1 <<  6)
 81 #define SVM_FEATURE_DECODE_ASSIST  (1 <<  7)
 82 #define SVM_FEATURE_PAUSE_FILTER   (1 << 10)
 83 
 84 #define SVM_AVIC_DOORBELL       0xc001011b
 85 
 86 #define NESTED_EXIT_HOST        0       /* Exit handled on host level */
 87 #define NESTED_EXIT_DONE        1       /* Exit caused nested vmexit  */
 88 #define NESTED_EXIT_CONTINUE    2       /* Further checks needed      */
 89 
 90 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
 91 
 92 #define TSC_RATIO_RSVD          0xffffff0000000000ULL
 93 #define TSC_RATIO_MIN           0x0000000000000001ULL
 94 #define TSC_RATIO_MAX           0x000000ffffffffffULL
 95 
 96 #define AVIC_HPA_MASK   ~((0xFFFULL << 52) | 0xFFF)
 97 
 98 /*
 99  * 0xff is broadcast, so the max index allowed for physical APIC ID
100  * table is 0xfe.  APIC IDs above 0xff are reserved.
101  */
102 #define AVIC_MAX_PHYSICAL_ID_COUNT      255
103 
104 #define AVIC_UNACCEL_ACCESS_WRITE_MASK          1
105 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK         0xFF0
106 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK         0xFFFFFFFF
107 
108 /* AVIC GATAG is encoded using VM and VCPU IDs */
109 #define AVIC_VCPU_ID_BITS               8
110 #define AVIC_VCPU_ID_MASK               ((1 << AVIC_VCPU_ID_BITS) - 1)
111 
112 #define AVIC_VM_ID_BITS                 24
113 #define AVIC_VM_ID_NR                   (1 << AVIC_VM_ID_BITS)
114 #define AVIC_VM_ID_MASK                 ((1 << AVIC_VM_ID_BITS) - 1)
115 
116 #define AVIC_GATAG(x, y)                (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
117                                                 (y & AVIC_VCPU_ID_MASK))
118 #define AVIC_GATAG_TO_VMID(x)           ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
119 #define AVIC_GATAG_TO_VCPUID(x)         (x & AVIC_VCPU_ID_MASK)
120 
121 static bool erratum_383_found __read_mostly;
122 
123 static const u32 host_save_user_msrs[] = {
124 #ifdef CONFIG_X86_64
125         MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
126         MSR_FS_BASE,
127 #endif
128         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
129         MSR_TSC_AUX,
130 };
131 
132 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
133 
134 struct kvm_sev_info {
135         bool active;            /* SEV enabled guest */
136         unsigned int asid;      /* ASID used for this guest */
137         unsigned int handle;    /* SEV firmware handle */
138         int fd;                 /* SEV device fd */
139         unsigned long pages_locked; /* Number of pages locked */
140         struct list_head regions_list;  /* List of registered regions */
141 };
142 
143 struct kvm_svm {
144         struct kvm kvm;
145 
146         /* Struct members for AVIC */
147         u32 avic_vm_id;
148         u32 ldr_mode;
149         struct page *avic_logical_id_table_page;
150         struct page *avic_physical_id_table_page;
151         struct hlist_node hnode;
152 
153         struct kvm_sev_info sev_info;
154 };
155 
156 struct kvm_vcpu;
157 
158 struct nested_state {
159         struct vmcb *hsave;
160         u64 hsave_msr;
161         u64 vm_cr_msr;
162         u64 vmcb;
163 
164         /* These are the merged vectors */
165         u32 *msrpm;
166 
167         /* gpa pointers to the real vectors */
168         u64 vmcb_msrpm;
169         u64 vmcb_iopm;
170 
171         /* A VMEXIT is required but not yet emulated */
172         bool exit_required;
173 
174         /* cache for intercepts of the guest */
175         u32 intercept_cr;
176         u32 intercept_dr;
177         u32 intercept_exceptions;
178         u64 intercept;
179 
180         /* Nested Paging related state */
181         u64 nested_cr3;
182 };
183 
184 #define MSRPM_OFFSETS   16
185 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
186 
187 /*
188  * Set osvw_len to higher value when updated Revision Guides
189  * are published and we know what the new status bits are
190  */
191 static uint64_t osvw_len = 4, osvw_status;
192 
193 struct vcpu_svm {
194         struct kvm_vcpu vcpu;
195         struct vmcb *vmcb;
196         unsigned long vmcb_pa;
197         struct svm_cpu_data *svm_data;
198         uint64_t asid_generation;
199         uint64_t sysenter_esp;
200         uint64_t sysenter_eip;
201         uint64_t tsc_aux;
202 
203         u64 msr_decfg;
204 
205         u64 next_rip;
206 
207         u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
208         struct {
209                 u16 fs;
210                 u16 gs;
211                 u16 ldt;
212                 u64 gs_base;
213         } host;
214 
215         u64 spec_ctrl;
216         /*
217          * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
218          * translated into the appropriate L2_CFG bits on the host to
219          * perform speculative control.
220          */
221         u64 virt_spec_ctrl;
222 
223         u32 *msrpm;
224 
225         ulong nmi_iret_rip;
226 
227         struct nested_state nested;
228 
229         bool nmi_singlestep;
230         u64 nmi_singlestep_guest_rflags;
231 
232         unsigned int3_injected;
233         unsigned long int3_rip;
234 
235         /* cached guest cpuid flags for faster access */
236         bool nrips_enabled      : 1;
237 
238         u32 ldr_reg;
239         struct page *avic_backing_page;
240         u64 *avic_physical_id_cache;
241         bool avic_is_running;
242 
243         /*
244          * Per-vcpu list of struct amd_svm_iommu_ir:
245          * This is used mainly to store interrupt remapping information used
246          * when update the vcpu affinity. This avoids the need to scan for
247          * IRTE and try to match ga_tag in the IOMMU driver.
248          */
249         struct list_head ir_list;
250         spinlock_t ir_list_lock;
251 
252         /* which host CPU was used for running this vcpu */
253         unsigned int last_cpu;
254 };
255 
256 /*
257  * This is a wrapper of struct amd_iommu_ir_data.
258  */
259 struct amd_svm_iommu_ir {
260         struct list_head node;  /* Used by SVM for per-vcpu ir_list */
261         void *data;             /* Storing pointer to struct amd_ir_data */
262 };
263 
264 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK    (0xFF)
265 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK                (1 << 31)
266 
267 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK    (0xFFULL)
268 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK        (0xFFFFFFFFFFULL << 12)
269 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK          (1ULL << 62)
270 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK               (1ULL << 63)
271 
272 static DEFINE_PER_CPU(u64, current_tsc_ratio);
273 #define TSC_RATIO_DEFAULT       0x0100000000ULL
274 
275 #define MSR_INVALID                     0xffffffffU
276 
277 static const struct svm_direct_access_msrs {
278         u32 index;   /* Index of the MSR */
279         bool always; /* True if intercept is always on */
280 } direct_access_msrs[] = {
281         { .index = MSR_STAR,                            .always = true  },
282         { .index = MSR_IA32_SYSENTER_CS,                .always = true  },
283 #ifdef CONFIG_X86_64
284         { .index = MSR_GS_BASE,                         .always = true  },
285         { .index = MSR_FS_BASE,                         .always = true  },
286         { .index = MSR_KERNEL_GS_BASE,                  .always = true  },
287         { .index = MSR_LSTAR,                           .always = true  },
288         { .index = MSR_CSTAR,                           .always = true  },
289         { .index = MSR_SYSCALL_MASK,                    .always = true  },
290 #endif
291         { .index = MSR_IA32_SPEC_CTRL,                  .always = false },
292         { .index = MSR_IA32_PRED_CMD,                   .always = false },
293         { .index = MSR_IA32_LASTBRANCHFROMIP,           .always = false },
294         { .index = MSR_IA32_LASTBRANCHTOIP,             .always = false },
295         { .index = MSR_IA32_LASTINTFROMIP,              .always = false },
296         { .index = MSR_IA32_LASTINTTOIP,                .always = false },
297         { .index = MSR_INVALID,                         .always = false },
298 };
299 
300 /* enable NPT for AMD64 and X86 with PAE */
301 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
302 static bool npt_enabled = true;
303 #else
304 static bool npt_enabled;
305 #endif
306 
307 /*
308  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
309  * pause_filter_count: On processors that support Pause filtering(indicated
310  *      by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
311  *      count value. On VMRUN this value is loaded into an internal counter.
312  *      Each time a pause instruction is executed, this counter is decremented
313  *      until it reaches zero at which time a #VMEXIT is generated if pause
314  *      intercept is enabled. Refer to  AMD APM Vol 2 Section 15.14.4 Pause
315  *      Intercept Filtering for more details.
316  *      This also indicate if ple logic enabled.
317  *
318  * pause_filter_thresh: In addition, some processor families support advanced
319  *      pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
320  *      the amount of time a guest is allowed to execute in a pause loop.
321  *      In this mode, a 16-bit pause filter threshold field is added in the
322  *      VMCB. The threshold value is a cycle count that is used to reset the
323  *      pause counter. As with simple pause filtering, VMRUN loads the pause
324  *      count value from VMCB into an internal counter. Then, on each pause
325  *      instruction the hardware checks the elapsed number of cycles since
326  *      the most recent pause instruction against the pause filter threshold.
327  *      If the elapsed cycle count is greater than the pause filter threshold,
328  *      then the internal pause count is reloaded from the VMCB and execution
329  *      continues. If the elapsed cycle count is less than the pause filter
330  *      threshold, then the internal pause count is decremented. If the count
331  *      value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
332  *      triggered. If advanced pause filtering is supported and pause filter
333  *      threshold field is set to zero, the filter will operate in the simpler,
334  *      count only mode.
335  */
336 
337 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
338 module_param(pause_filter_thresh, ushort, 0444);
339 
340 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
341 module_param(pause_filter_count, ushort, 0444);
342 
343 /* Default doubles per-vcpu window every exit. */
344 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
345 module_param(pause_filter_count_grow, ushort, 0444);
346 
347 /* Default resets per-vcpu window every exit to pause_filter_count. */
348 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
349 module_param(pause_filter_count_shrink, ushort, 0444);
350 
351 /* Default is to compute the maximum so we can never overflow. */
352 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
353 module_param(pause_filter_count_max, ushort, 0444);
354 
355 /* allow nested paging (virtualized MMU) for all guests */
356 static int npt = true;
357 module_param(npt, int, S_IRUGO);
358 
359 /* allow nested virtualization in KVM/SVM */
360 static int nested = true;
361 module_param(nested, int, S_IRUGO);
362 
363 /* enable / disable AVIC */
364 static int avic;
365 #ifdef CONFIG_X86_LOCAL_APIC
366 module_param(avic, int, S_IRUGO);
367 #endif
368 
369 /* enable/disable Virtual VMLOAD VMSAVE */
370 static int vls = true;
371 module_param(vls, int, 0444);
372 
373 /* enable/disable Virtual GIF */
374 static int vgif = true;
375 module_param(vgif, int, 0444);
376 
377 /* enable/disable SEV support */
378 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
379 module_param(sev, int, 0444);
380 
381 static u8 rsm_ins_bytes[] = "\x0f\xaa";
382 
383 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
384 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
385 static void svm_complete_interrupts(struct vcpu_svm *svm);
386 
387 static int nested_svm_exit_handled(struct vcpu_svm *svm);
388 static int nested_svm_intercept(struct vcpu_svm *svm);
389 static int nested_svm_vmexit(struct vcpu_svm *svm);
390 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
391                                       bool has_error_code, u32 error_code);
392 
393 enum {
394         VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
395                             pause filter count */
396         VMCB_PERM_MAP,   /* IOPM Base and MSRPM Base */
397         VMCB_ASID,       /* ASID */
398         VMCB_INTR,       /* int_ctl, int_vector */
399         VMCB_NPT,        /* npt_en, nCR3, gPAT */
400         VMCB_CR,         /* CR0, CR3, CR4, EFER */
401         VMCB_DR,         /* DR6, DR7 */
402         VMCB_DT,         /* GDT, IDT */
403         VMCB_SEG,        /* CS, DS, SS, ES, CPL */
404         VMCB_CR2,        /* CR2 only */
405         VMCB_LBR,        /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
406         VMCB_AVIC,       /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
407                           * AVIC PHYSICAL_TABLE pointer,
408                           * AVIC LOGICAL_TABLE pointer
409                           */
410         VMCB_DIRTY_MAX,
411 };
412 
413 /* TPR and CR2 are always written before VMRUN */
414 #define VMCB_ALWAYS_DIRTY_MASK  ((1U << VMCB_INTR) | (1U << VMCB_CR2))
415 
416 #define VMCB_AVIC_APIC_BAR_MASK         0xFFFFFFFFFF000ULL
417 
418 static unsigned int max_sev_asid;
419 static unsigned int min_sev_asid;
420 static unsigned long *sev_asid_bitmap;
421 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
422 
423 struct enc_region {
424         struct list_head list;
425         unsigned long npages;
426         struct page **pages;
427         unsigned long uaddr;
428         unsigned long size;
429 };
430 
431 
432 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
433 {
434         return container_of(kvm, struct kvm_svm, kvm);
435 }
436 
437 static inline bool svm_sev_enabled(void)
438 {
439         return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
440 }
441 
442 static inline bool sev_guest(struct kvm *kvm)
443 {
444 #ifdef CONFIG_KVM_AMD_SEV
445         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
446 
447         return sev->active;
448 #else
449         return false;
450 #endif
451 }
452 
453 static inline int sev_get_asid(struct kvm *kvm)
454 {
455         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
456 
457         return sev->asid;
458 }
459 
460 static inline void mark_all_dirty(struct vmcb *vmcb)
461 {
462         vmcb->control.clean = 0;
463 }
464 
465 static inline void mark_all_clean(struct vmcb *vmcb)
466 {
467         vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
468                                & ~VMCB_ALWAYS_DIRTY_MASK;
469 }
470 
471 static inline void mark_dirty(struct vmcb *vmcb, int bit)
472 {
473         vmcb->control.clean &= ~(1 << bit);
474 }
475 
476 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
477 {
478         return container_of(vcpu, struct vcpu_svm, vcpu);
479 }
480 
481 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
482 {
483         svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
484         mark_dirty(svm->vmcb, VMCB_AVIC);
485 }
486 
487 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
488 {
489         struct vcpu_svm *svm = to_svm(vcpu);
490         u64 *entry = svm->avic_physical_id_cache;
491 
492         if (!entry)
493                 return false;
494 
495         return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
496 }
497 
498 static void recalc_intercepts(struct vcpu_svm *svm)
499 {
500         struct vmcb_control_area *c, *h;
501         struct nested_state *g;
502 
503         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
504 
505         if (!is_guest_mode(&svm->vcpu))
506                 return;
507 
508         c = &svm->vmcb->control;
509         h = &svm->nested.hsave->control;
510         g = &svm->nested;
511 
512         c->intercept_cr = h->intercept_cr | g->intercept_cr;
513         c->intercept_dr = h->intercept_dr | g->intercept_dr;
514         c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
515         c->intercept = h->intercept | g->intercept;
516 }
517 
518 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
519 {
520         if (is_guest_mode(&svm->vcpu))
521                 return svm->nested.hsave;
522         else
523                 return svm->vmcb;
524 }
525 
526 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
527 {
528         struct vmcb *vmcb = get_host_vmcb(svm);
529 
530         vmcb->control.intercept_cr |= (1U << bit);
531 
532         recalc_intercepts(svm);
533 }
534 
535 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
536 {
537         struct vmcb *vmcb = get_host_vmcb(svm);
538 
539         vmcb->control.intercept_cr &= ~(1U << bit);
540 
541         recalc_intercepts(svm);
542 }
543 
544 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
545 {
546         struct vmcb *vmcb = get_host_vmcb(svm);
547 
548         return vmcb->control.intercept_cr & (1U << bit);
549 }
550 
551 static inline void set_dr_intercepts(struct vcpu_svm *svm)
552 {
553         struct vmcb *vmcb = get_host_vmcb(svm);
554 
555         vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
556                 | (1 << INTERCEPT_DR1_READ)
557                 | (1 << INTERCEPT_DR2_READ)
558                 | (1 << INTERCEPT_DR3_READ)
559                 | (1 << INTERCEPT_DR4_READ)
560                 | (1 << INTERCEPT_DR5_READ)
561                 | (1 << INTERCEPT_DR6_READ)
562                 | (1 << INTERCEPT_DR7_READ)
563                 | (1 << INTERCEPT_DR0_WRITE)
564                 | (1 << INTERCEPT_DR1_WRITE)
565                 | (1 << INTERCEPT_DR2_WRITE)
566                 | (1 << INTERCEPT_DR3_WRITE)
567                 | (1 << INTERCEPT_DR4_WRITE)
568                 | (1 << INTERCEPT_DR5_WRITE)
569                 | (1 << INTERCEPT_DR6_WRITE)
570                 | (1 << INTERCEPT_DR7_WRITE);
571 
572         recalc_intercepts(svm);
573 }
574 
575 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
576 {
577         struct vmcb *vmcb = get_host_vmcb(svm);
578 
579         vmcb->control.intercept_dr = 0;
580 
581         recalc_intercepts(svm);
582 }
583 
584 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
585 {
586         struct vmcb *vmcb = get_host_vmcb(svm);
587 
588         vmcb->control.intercept_exceptions |= (1U << bit);
589 
590         recalc_intercepts(svm);
591 }
592 
593 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
594 {
595         struct vmcb *vmcb = get_host_vmcb(svm);
596 
597         vmcb->control.intercept_exceptions &= ~(1U << bit);
598 
599         recalc_intercepts(svm);
600 }
601 
602 static inline void set_intercept(struct vcpu_svm *svm, int bit)
603 {
604         struct vmcb *vmcb = get_host_vmcb(svm);
605 
606         vmcb->control.intercept |= (1ULL << bit);
607 
608         recalc_intercepts(svm);
609 }
610 
611 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
612 {
613         struct vmcb *vmcb = get_host_vmcb(svm);
614 
615         vmcb->control.intercept &= ~(1ULL << bit);
616 
617         recalc_intercepts(svm);
618 }
619 
620 static inline bool vgif_enabled(struct vcpu_svm *svm)
621 {
622         return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
623 }
624 
625 static inline void enable_gif(struct vcpu_svm *svm)
626 {
627         if (vgif_enabled(svm))
628                 svm->vmcb->control.int_ctl |= V_GIF_MASK;
629         else
630                 svm->vcpu.arch.hflags |= HF_GIF_MASK;
631 }
632 
633 static inline void disable_gif(struct vcpu_svm *svm)
634 {
635         if (vgif_enabled(svm))
636                 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
637         else
638                 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
639 }
640 
641 static inline bool gif_set(struct vcpu_svm *svm)
642 {
643         if (vgif_enabled(svm))
644                 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
645         else
646                 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
647 }
648 
649 static unsigned long iopm_base;
650 
651 struct kvm_ldttss_desc {
652         u16 limit0;
653         u16 base0;
654         unsigned base1:8, type:5, dpl:2, p:1;
655         unsigned limit1:4, zero0:3, g:1, base2:8;
656         u32 base3;
657         u32 zero1;
658 } __attribute__((packed));
659 
660 struct svm_cpu_data {
661         int cpu;
662 
663         u64 asid_generation;
664         u32 max_asid;
665         u32 next_asid;
666         u32 min_asid;
667         struct kvm_ldttss_desc *tss_desc;
668 
669         struct page *save_area;
670         struct vmcb *current_vmcb;
671 
672         /* index = sev_asid, value = vmcb pointer */
673         struct vmcb **sev_vmcbs;
674 };
675 
676 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
677 
678 struct svm_init_data {
679         int cpu;
680         int r;
681 };
682 
683 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
684 
685 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
686 #define MSRS_RANGE_SIZE 2048
687 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
688 
689 static u32 svm_msrpm_offset(u32 msr)
690 {
691         u32 offset;
692         int i;
693 
694         for (i = 0; i < NUM_MSR_MAPS; i++) {
695                 if (msr < msrpm_ranges[i] ||
696                     msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
697                         continue;
698 
699                 offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
700                 offset += (i * MSRS_RANGE_SIZE);       /* add range offset */
701 
702                 /* Now we have the u8 offset - but need the u32 offset */
703                 return offset / 4;
704         }
705 
706         /* MSR not in any range */
707         return MSR_INVALID;
708 }
709 
710 #define MAX_INST_SIZE 15
711 
712 static inline void clgi(void)
713 {
714         asm volatile (__ex(SVM_CLGI));
715 }
716 
717 static inline void stgi(void)
718 {
719         asm volatile (__ex(SVM_STGI));
720 }
721 
722 static inline void invlpga(unsigned long addr, u32 asid)
723 {
724         asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
725 }
726 
727 static int get_npt_level(struct kvm_vcpu *vcpu)
728 {
729 #ifdef CONFIG_X86_64
730         return PT64_ROOT_4LEVEL;
731 #else
732         return PT32E_ROOT_LEVEL;
733 #endif
734 }
735 
736 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
737 {
738         vcpu->arch.efer = efer;
739         if (!npt_enabled && !(efer & EFER_LMA))
740                 efer &= ~EFER_LME;
741 
742         to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
743         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
744 }
745 
746 static int is_external_interrupt(u32 info)
747 {
748         info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
749         return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
750 }
751 
752 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
753 {
754         struct vcpu_svm *svm = to_svm(vcpu);
755         u32 ret = 0;
756 
757         if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
758                 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
759         return ret;
760 }
761 
762 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
763 {
764         struct vcpu_svm *svm = to_svm(vcpu);
765 
766         if (mask == 0)
767                 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
768         else
769                 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
770 
771 }
772 
773 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
774 {
775         struct vcpu_svm *svm = to_svm(vcpu);
776 
777         if (svm->vmcb->control.next_rip != 0) {
778                 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
779                 svm->next_rip = svm->vmcb->control.next_rip;
780         }
781 
782         if (!svm->next_rip) {
783                 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
784                                 EMULATE_DONE)
785                         printk(KERN_DEBUG "%s: NOP\n", __func__);
786                 return;
787         }
788         if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
789                 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
790                        __func__, kvm_rip_read(vcpu), svm->next_rip);
791 
792         kvm_rip_write(vcpu, svm->next_rip);
793         svm_set_interrupt_shadow(vcpu, 0);
794 }
795 
796 static void svm_queue_exception(struct kvm_vcpu *vcpu)
797 {
798         struct vcpu_svm *svm = to_svm(vcpu);
799         unsigned nr = vcpu->arch.exception.nr;
800         bool has_error_code = vcpu->arch.exception.has_error_code;
801         bool reinject = vcpu->arch.exception.injected;
802         u32 error_code = vcpu->arch.exception.error_code;
803 
804         /*
805          * If we are within a nested VM we'd better #VMEXIT and let the guest
806          * handle the exception
807          */
808         if (!reinject &&
809             nested_svm_check_exception(svm, nr, has_error_code, error_code))
810                 return;
811 
812         if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
813                 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
814 
815                 /*
816                  * For guest debugging where we have to reinject #BP if some
817                  * INT3 is guest-owned:
818                  * Emulate nRIP by moving RIP forward. Will fail if injection
819                  * raises a fault that is not intercepted. Still better than
820                  * failing in all cases.
821                  */
822                 skip_emulated_instruction(&svm->vcpu);
823                 rip = kvm_rip_read(&svm->vcpu);
824                 svm->int3_rip = rip + svm->vmcb->save.cs.base;
825                 svm->int3_injected = rip - old_rip;
826         }
827 
828         svm->vmcb->control.event_inj = nr
829                 | SVM_EVTINJ_VALID
830                 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
831                 | SVM_EVTINJ_TYPE_EXEPT;
832         svm->vmcb->control.event_inj_err = error_code;
833 }
834 
835 static void svm_init_erratum_383(void)
836 {
837         u32 low, high;
838         int err;
839         u64 val;
840 
841         if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
842                 return;
843 
844         /* Use _safe variants to not break nested virtualization */
845         val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
846         if (err)
847                 return;
848 
849         val |= (1ULL << 47);
850 
851         low  = lower_32_bits(val);
852         high = upper_32_bits(val);
853 
854         native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
855 
856         erratum_383_found = true;
857 }
858 
859 static void svm_init_osvw(struct kvm_vcpu *vcpu)
860 {
861         /*
862          * Guests should see errata 400 and 415 as fixed (assuming that
863          * HLT and IO instructions are intercepted).
864          */
865         vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
866         vcpu->arch.osvw.status = osvw_status & ~(6ULL);
867 
868         /*
869          * By increasing VCPU's osvw.length to 3 we are telling the guest that
870          * all osvw.status bits inside that length, including bit 0 (which is
871          * reserved for erratum 298), are valid. However, if host processor's
872          * osvw_len is 0 then osvw_status[0] carries no information. We need to
873          * be conservative here and therefore we tell the guest that erratum 298
874          * is present (because we really don't know).
875          */
876         if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
877                 vcpu->arch.osvw.status |= 1;
878 }
879 
880 static int has_svm(void)
881 {
882         const char *msg;
883 
884         if (!cpu_has_svm(&msg)) {
885                 printk(KERN_INFO "has_svm: %s\n", msg);
886                 return 0;
887         }
888 
889         return 1;
890 }
891 
892 static void svm_hardware_disable(void)
893 {
894         /* Make sure we clean up behind us */
895         if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
896                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
897 
898         cpu_svm_disable();
899 
900         amd_pmu_disable_virt();
901 }
902 
903 static int svm_hardware_enable(void)
904 {
905 
906         struct svm_cpu_data *sd;
907         uint64_t efer;
908         struct desc_struct *gdt;
909         int me = raw_smp_processor_id();
910 
911         rdmsrl(MSR_EFER, efer);
912         if (efer & EFER_SVME)
913                 return -EBUSY;
914 
915         if (!has_svm()) {
916                 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
917                 return -EINVAL;
918         }
919         sd = per_cpu(svm_data, me);
920         if (!sd) {
921                 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
922                 return -EINVAL;
923         }
924 
925         sd->asid_generation = 1;
926         sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
927         sd->next_asid = sd->max_asid + 1;
928         sd->min_asid = max_sev_asid + 1;
929 
930         gdt = get_current_gdt_rw();
931         sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
932 
933         wrmsrl(MSR_EFER, efer | EFER_SVME);
934 
935         wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
936 
937         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
938                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
939                 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
940         }
941 
942 
943         /*
944          * Get OSVW bits.
945          *
946          * Note that it is possible to have a system with mixed processor
947          * revisions and therefore different OSVW bits. If bits are not the same
948          * on different processors then choose the worst case (i.e. if erratum
949          * is present on one processor and not on another then assume that the
950          * erratum is present everywhere).
951          */
952         if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
953                 uint64_t len, status = 0;
954                 int err;
955 
956                 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
957                 if (!err)
958                         status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
959                                                       &err);
960 
961                 if (err)
962                         osvw_status = osvw_len = 0;
963                 else {
964                         if (len < osvw_len)
965                                 osvw_len = len;
966                         osvw_status |= status;
967                         osvw_status &= (1ULL << osvw_len) - 1;
968                 }
969         } else
970                 osvw_status = osvw_len = 0;
971 
972         svm_init_erratum_383();
973 
974         amd_pmu_enable_virt();
975 
976         return 0;
977 }
978 
979 static void svm_cpu_uninit(int cpu)
980 {
981         struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
982 
983         if (!sd)
984                 return;
985 
986         per_cpu(svm_data, raw_smp_processor_id()) = NULL;
987         kfree(sd->sev_vmcbs);
988         __free_page(sd->save_area);
989         kfree(sd);
990 }
991 
992 static int svm_cpu_init(int cpu)
993 {
994         struct svm_cpu_data *sd;
995         int r;
996 
997         sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
998         if (!sd)
999                 return -ENOMEM;
1000         sd->cpu = cpu;
1001         r = -ENOMEM;
1002         sd->save_area = alloc_page(GFP_KERNEL);
1003         if (!sd->save_area)
1004                 goto err_1;
1005 
1006         if (svm_sev_enabled()) {
1007                 r = -ENOMEM;
1008                 sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1009                                               sizeof(void *),
1010                                               GFP_KERNEL);
1011                 if (!sd->sev_vmcbs)
1012                         goto err_1;
1013         }
1014 
1015         per_cpu(svm_data, cpu) = sd;
1016 
1017         return 0;
1018 
1019 err_1:
1020         kfree(sd);
1021         return r;
1022 
1023 }
1024 
1025 static bool valid_msr_intercept(u32 index)
1026 {
1027         int i;
1028 
1029         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1030                 if (direct_access_msrs[i].index == index)
1031                         return true;
1032 
1033         return false;
1034 }
1035 
1036 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1037 {
1038         u8 bit_write;
1039         unsigned long tmp;
1040         u32 offset;
1041         u32 *msrpm;
1042 
1043         msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1044                                       to_svm(vcpu)->msrpm;
1045 
1046         offset    = svm_msrpm_offset(msr);
1047         bit_write = 2 * (msr & 0x0f) + 1;
1048         tmp       = msrpm[offset];
1049 
1050         BUG_ON(offset == MSR_INVALID);
1051 
1052         return !!test_bit(bit_write,  &tmp);
1053 }
1054 
1055 static void set_msr_interception(u32 *msrpm, unsigned msr,
1056                                  int read, int write)
1057 {
1058         u8 bit_read, bit_write;
1059         unsigned long tmp;
1060         u32 offset;
1061 
1062         /*
1063          * If this warning triggers extend the direct_access_msrs list at the
1064          * beginning of the file
1065          */
1066         WARN_ON(!valid_msr_intercept(msr));
1067 
1068         offset    = svm_msrpm_offset(msr);
1069         bit_read  = 2 * (msr & 0x0f);
1070         bit_write = 2 * (msr & 0x0f) + 1;
1071         tmp       = msrpm[offset];
1072 
1073         BUG_ON(offset == MSR_INVALID);
1074 
1075         read  ? clear_bit(bit_read,  &tmp) : set_bit(bit_read,  &tmp);
1076         write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1077 
1078         msrpm[offset] = tmp;
1079 }
1080 
1081 static void svm_vcpu_init_msrpm(u32 *msrpm)
1082 {
1083         int i;
1084 
1085         memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1086 
1087         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1088                 if (!direct_access_msrs[i].always)
1089                         continue;
1090 
1091                 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1092         }
1093 }
1094 
1095 static void add_msr_offset(u32 offset)
1096 {
1097         int i;
1098 
1099         for (i = 0; i < MSRPM_OFFSETS; ++i) {
1100 
1101                 /* Offset already in list? */
1102                 if (msrpm_offsets[i] == offset)
1103                         return;
1104 
1105                 /* Slot used by another offset? */
1106                 if (msrpm_offsets[i] != MSR_INVALID)
1107                         continue;
1108 
1109                 /* Add offset to list */
1110                 msrpm_offsets[i] = offset;
1111 
1112                 return;
1113         }
1114 
1115         /*
1116          * If this BUG triggers the msrpm_offsets table has an overflow. Just
1117          * increase MSRPM_OFFSETS in this case.
1118          */
1119         BUG();
1120 }
1121 
1122 static void init_msrpm_offsets(void)
1123 {
1124         int i;
1125 
1126         memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1127 
1128         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1129                 u32 offset;
1130 
1131                 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1132                 BUG_ON(offset == MSR_INVALID);
1133 
1134                 add_msr_offset(offset);
1135         }
1136 }
1137 
1138 static void svm_enable_lbrv(struct vcpu_svm *svm)
1139 {
1140         u32 *msrpm = svm->msrpm;
1141 
1142         svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1143         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1144         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1145         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1146         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1147 }
1148 
1149 static void svm_disable_lbrv(struct vcpu_svm *svm)
1150 {
1151         u32 *msrpm = svm->msrpm;
1152 
1153         svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1154         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1155         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1156         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1157         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1158 }
1159 
1160 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1161 {
1162         svm->nmi_singlestep = false;
1163 
1164         if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1165                 /* Clear our flags if they were not set by the guest */
1166                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1167                         svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1168                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1169                         svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1170         }
1171 }
1172 
1173 /* Note:
1174  * This hash table is used to map VM_ID to a struct kvm_svm,
1175  * when handling AMD IOMMU GALOG notification to schedule in
1176  * a particular vCPU.
1177  */
1178 #define SVM_VM_DATA_HASH_BITS   8
1179 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1180 static u32 next_vm_id = 0;
1181 static bool next_vm_id_wrapped = 0;
1182 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1183 
1184 /* Note:
1185  * This function is called from IOMMU driver to notify
1186  * SVM to schedule in a particular vCPU of a particular VM.
1187  */
1188 static int avic_ga_log_notifier(u32 ga_tag)
1189 {
1190         unsigned long flags;
1191         struct kvm_svm *kvm_svm;
1192         struct kvm_vcpu *vcpu = NULL;
1193         u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1194         u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1195 
1196         pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1197 
1198         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1199         hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1200                 if (kvm_svm->avic_vm_id != vm_id)
1201                         continue;
1202                 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1203                 break;
1204         }
1205         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1206 
1207         /* Note:
1208          * At this point, the IOMMU should have already set the pending
1209          * bit in the vAPIC backing page. So, we just need to schedule
1210          * in the vcpu.
1211          */
1212         if (vcpu)
1213                 kvm_vcpu_wake_up(vcpu);
1214 
1215         return 0;
1216 }
1217 
1218 static __init int sev_hardware_setup(void)
1219 {
1220         struct sev_user_data_status *status;
1221         int rc;
1222 
1223         /* Maximum number of encrypted guests supported simultaneously */
1224         max_sev_asid = cpuid_ecx(0x8000001F);
1225 
1226         if (!max_sev_asid)
1227                 return 1;
1228 
1229         /* Minimum ASID value that should be used for SEV guest */
1230         min_sev_asid = cpuid_edx(0x8000001F);
1231 
1232         /* Initialize SEV ASID bitmap */
1233         sev_asid_bitmap = kcalloc(BITS_TO_LONGS(max_sev_asid),
1234                                 sizeof(unsigned long), GFP_KERNEL);
1235         if (!sev_asid_bitmap)
1236                 return 1;
1237 
1238         status = kmalloc(sizeof(*status), GFP_KERNEL);
1239         if (!status)
1240                 return 1;
1241 
1242         /*
1243          * Check SEV platform status.
1244          *
1245          * PLATFORM_STATUS can be called in any state, if we failed to query
1246          * the PLATFORM status then either PSP firmware does not support SEV
1247          * feature or SEV firmware is dead.
1248          */
1249         rc = sev_platform_status(status, NULL);
1250         if (rc)
1251                 goto err;
1252 
1253         pr_info("SEV supported\n");
1254 
1255 err:
1256         kfree(status);
1257         return rc;
1258 }
1259 
1260 static void grow_ple_window(struct kvm_vcpu *vcpu)
1261 {
1262         struct vcpu_svm *svm = to_svm(vcpu);
1263         struct vmcb_control_area *control = &svm->vmcb->control;
1264         int old = control->pause_filter_count;
1265 
1266         control->pause_filter_count = __grow_ple_window(old,
1267                                                         pause_filter_count,
1268                                                         pause_filter_count_grow,
1269                                                         pause_filter_count_max);
1270 
1271         if (control->pause_filter_count != old)
1272                 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1273 
1274         trace_kvm_ple_window_grow(vcpu->vcpu_id,
1275                                   control->pause_filter_count, old);
1276 }
1277 
1278 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1279 {
1280         struct vcpu_svm *svm = to_svm(vcpu);
1281         struct vmcb_control_area *control = &svm->vmcb->control;
1282         int old = control->pause_filter_count;
1283 
1284         control->pause_filter_count =
1285                                 __shrink_ple_window(old,
1286                                                     pause_filter_count,
1287                                                     pause_filter_count_shrink,
1288                                                     pause_filter_count);
1289         if (control->pause_filter_count != old)
1290                 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1291 
1292         trace_kvm_ple_window_shrink(vcpu->vcpu_id,
1293                                     control->pause_filter_count, old);
1294 }
1295 
1296 static __init int svm_hardware_setup(void)
1297 {
1298         int cpu;
1299         struct page *iopm_pages;
1300         void *iopm_va;
1301         int r;
1302 
1303         iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1304 
1305         if (!iopm_pages)
1306                 return -ENOMEM;
1307 
1308         iopm_va = page_address(iopm_pages);
1309         memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1310         iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1311 
1312         init_msrpm_offsets();
1313 
1314         if (boot_cpu_has(X86_FEATURE_NX))
1315                 kvm_enable_efer_bits(EFER_NX);
1316 
1317         if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1318                 kvm_enable_efer_bits(EFER_FFXSR);
1319 
1320         if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1321                 kvm_has_tsc_control = true;
1322                 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1323                 kvm_tsc_scaling_ratio_frac_bits = 32;
1324         }
1325 
1326         /* Check for pause filtering support */
1327         if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1328                 pause_filter_count = 0;
1329                 pause_filter_thresh = 0;
1330         } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1331                 pause_filter_thresh = 0;
1332         }
1333 
1334         if (nested) {
1335                 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1336                 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1337         }
1338 
1339         if (sev) {
1340                 if (boot_cpu_has(X86_FEATURE_SEV) &&
1341                     IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1342                         r = sev_hardware_setup();
1343                         if (r)
1344                                 sev = false;
1345                 } else {
1346                         sev = false;
1347                 }
1348         }
1349 
1350         for_each_possible_cpu(cpu) {
1351                 r = svm_cpu_init(cpu);
1352                 if (r)
1353                         goto err;
1354         }
1355 
1356         if (!boot_cpu_has(X86_FEATURE_NPT))
1357                 npt_enabled = false;
1358 
1359         if (npt_enabled && !npt) {
1360                 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1361                 npt_enabled = false;
1362         }
1363 
1364         if (npt_enabled) {
1365                 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1366                 kvm_enable_tdp();
1367         } else
1368                 kvm_disable_tdp();
1369 
1370         if (avic) {
1371                 if (!npt_enabled ||
1372                     !boot_cpu_has(X86_FEATURE_AVIC) ||
1373                     !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1374                         avic = false;
1375                 } else {
1376                         pr_info("AVIC enabled\n");
1377 
1378                         amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1379                 }
1380         }
1381 
1382         if (vls) {
1383                 if (!npt_enabled ||
1384                     !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1385                     !IS_ENABLED(CONFIG_X86_64)) {
1386                         vls = false;
1387                 } else {
1388                         pr_info("Virtual VMLOAD VMSAVE supported\n");
1389                 }
1390         }
1391 
1392         if (vgif) {
1393                 if (!boot_cpu_has(X86_FEATURE_VGIF))
1394                         vgif = false;
1395                 else
1396                         pr_info("Virtual GIF supported\n");
1397         }
1398 
1399         return 0;
1400 
1401 err:
1402         __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1403         iopm_base = 0;
1404         return r;
1405 }
1406 
1407 static __exit void svm_hardware_unsetup(void)
1408 {
1409         int cpu;
1410 
1411         if (svm_sev_enabled())
1412                 kfree(sev_asid_bitmap);
1413 
1414         for_each_possible_cpu(cpu)
1415                 svm_cpu_uninit(cpu);
1416 
1417         __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1418         iopm_base = 0;
1419 }
1420 
1421 static void init_seg(struct vmcb_seg *seg)
1422 {
1423         seg->selector = 0;
1424         seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1425                       SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1426         seg->limit = 0xffff;
1427         seg->base = 0;
1428 }
1429 
1430 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1431 {
1432         seg->selector = 0;
1433         seg->attrib = SVM_SELECTOR_P_MASK | type;
1434         seg->limit = 0xffff;
1435         seg->base = 0;
1436 }
1437 
1438 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1439 {
1440         struct vcpu_svm *svm = to_svm(vcpu);
1441 
1442         if (is_guest_mode(vcpu))
1443                 return svm->nested.hsave->control.tsc_offset;
1444 
1445         return vcpu->arch.tsc_offset;
1446 }
1447 
1448 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1449 {
1450         struct vcpu_svm *svm = to_svm(vcpu);
1451         u64 g_tsc_offset = 0;
1452 
1453         if (is_guest_mode(vcpu)) {
1454                 /* Write L1's TSC offset.  */
1455                 g_tsc_offset = svm->vmcb->control.tsc_offset -
1456                                svm->nested.hsave->control.tsc_offset;
1457                 svm->nested.hsave->control.tsc_offset = offset;
1458         } else
1459                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1460                                            svm->vmcb->control.tsc_offset,
1461                                            offset);
1462 
1463         svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1464 
1465         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1466 }
1467 
1468 static void avic_init_vmcb(struct vcpu_svm *svm)
1469 {
1470         struct vmcb *vmcb = svm->vmcb;
1471         struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1472         phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1473         phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1474         phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1475 
1476         vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1477         vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1478         vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1479         vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1480         vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1481 }
1482 
1483 static void init_vmcb(struct vcpu_svm *svm)
1484 {
1485         struct vmcb_control_area *control = &svm->vmcb->control;
1486         struct vmcb_save_area *save = &svm->vmcb->save;
1487 
1488         svm->vcpu.arch.hflags = 0;
1489 
1490         set_cr_intercept(svm, INTERCEPT_CR0_READ);
1491         set_cr_intercept(svm, INTERCEPT_CR3_READ);
1492         set_cr_intercept(svm, INTERCEPT_CR4_READ);
1493         set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1494         set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1495         set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1496         if (!kvm_vcpu_apicv_active(&svm->vcpu))
1497                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1498 
1499         set_dr_intercepts(svm);
1500 
1501         set_exception_intercept(svm, PF_VECTOR);
1502         set_exception_intercept(svm, UD_VECTOR);
1503         set_exception_intercept(svm, MC_VECTOR);
1504         set_exception_intercept(svm, AC_VECTOR);
1505         set_exception_intercept(svm, DB_VECTOR);
1506         /*
1507          * Guest access to VMware backdoor ports could legitimately
1508          * trigger #GP because of TSS I/O permission bitmap.
1509          * We intercept those #GP and allow access to them anyway
1510          * as VMware does.
1511          */
1512         if (enable_vmware_backdoor)
1513                 set_exception_intercept(svm, GP_VECTOR);
1514 
1515         set_intercept(svm, INTERCEPT_INTR);
1516         set_intercept(svm, INTERCEPT_NMI);
1517         set_intercept(svm, INTERCEPT_SMI);
1518         set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1519         set_intercept(svm, INTERCEPT_RDPMC);
1520         set_intercept(svm, INTERCEPT_CPUID);
1521         set_intercept(svm, INTERCEPT_INVD);
1522         set_intercept(svm, INTERCEPT_INVLPG);
1523         set_intercept(svm, INTERCEPT_INVLPGA);
1524         set_intercept(svm, INTERCEPT_IOIO_PROT);
1525         set_intercept(svm, INTERCEPT_MSR_PROT);
1526         set_intercept(svm, INTERCEPT_TASK_SWITCH);
1527         set_intercept(svm, INTERCEPT_SHUTDOWN);
1528         set_intercept(svm, INTERCEPT_VMRUN);
1529         set_intercept(svm, INTERCEPT_VMMCALL);
1530         set_intercept(svm, INTERCEPT_VMLOAD);
1531         set_intercept(svm, INTERCEPT_VMSAVE);
1532         set_intercept(svm, INTERCEPT_STGI);
1533         set_intercept(svm, INTERCEPT_CLGI);
1534         set_intercept(svm, INTERCEPT_SKINIT);
1535         set_intercept(svm, INTERCEPT_WBINVD);
1536         set_intercept(svm, INTERCEPT_XSETBV);
1537         set_intercept(svm, INTERCEPT_RSM);
1538 
1539         if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1540                 set_intercept(svm, INTERCEPT_MONITOR);
1541                 set_intercept(svm, INTERCEPT_MWAIT);
1542         }
1543 
1544         if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1545                 set_intercept(svm, INTERCEPT_HLT);
1546 
1547         control->iopm_base_pa = __sme_set(iopm_base);
1548         control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1549         control->int_ctl = V_INTR_MASKING_MASK;
1550 
1551         init_seg(&save->es);
1552         init_seg(&save->ss);
1553         init_seg(&save->ds);
1554         init_seg(&save->fs);
1555         init_seg(&save->gs);
1556 
1557         save->cs.selector = 0xf000;
1558         save->cs.base = 0xffff0000;
1559         /* Executable/Readable Code Segment */
1560         save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1561                 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1562         save->cs.limit = 0xffff;
1563 
1564         save->gdtr.limit = 0xffff;
1565         save->idtr.limit = 0xffff;
1566 
1567         init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1568         init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1569 
1570         svm_set_efer(&svm->vcpu, 0);
1571         save->dr6 = 0xffff0ff0;
1572         kvm_set_rflags(&svm->vcpu, 2);
1573         save->rip = 0x0000fff0;
1574         svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1575 
1576         /*
1577          * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1578          * It also updates the guest-visible cr0 value.
1579          */
1580         svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1581         kvm_mmu_reset_context(&svm->vcpu);
1582 
1583         save->cr4 = X86_CR4_PAE;
1584         /* rdx = ?? */
1585 
1586         if (npt_enabled) {
1587                 /* Setup VMCB for Nested Paging */
1588                 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1589                 clr_intercept(svm, INTERCEPT_INVLPG);
1590                 clr_exception_intercept(svm, PF_VECTOR);
1591                 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1592                 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1593                 save->g_pat = svm->vcpu.arch.pat;
1594                 save->cr3 = 0;
1595                 save->cr4 = 0;
1596         }
1597         svm->asid_generation = 0;
1598 
1599         svm->nested.vmcb = 0;
1600         svm->vcpu.arch.hflags = 0;
1601 
1602         if (pause_filter_count) {
1603                 control->pause_filter_count = pause_filter_count;
1604                 if (pause_filter_thresh)
1605                         control->pause_filter_thresh = pause_filter_thresh;
1606                 set_intercept(svm, INTERCEPT_PAUSE);
1607         } else {
1608                 clr_intercept(svm, INTERCEPT_PAUSE);
1609         }
1610 
1611         if (kvm_vcpu_apicv_active(&svm->vcpu))
1612                 avic_init_vmcb(svm);
1613 
1614         /*
1615          * If hardware supports Virtual VMLOAD VMSAVE then enable it
1616          * in VMCB and clear intercepts to avoid #VMEXIT.
1617          */
1618         if (vls) {
1619                 clr_intercept(svm, INTERCEPT_VMLOAD);
1620                 clr_intercept(svm, INTERCEPT_VMSAVE);
1621                 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1622         }
1623 
1624         if (vgif) {
1625                 clr_intercept(svm, INTERCEPT_STGI);
1626                 clr_intercept(svm, INTERCEPT_CLGI);
1627                 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1628         }
1629 
1630         if (sev_guest(svm->vcpu.kvm)) {
1631                 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1632                 clr_exception_intercept(svm, UD_VECTOR);
1633         }
1634 
1635         mark_all_dirty(svm->vmcb);
1636 
1637         enable_gif(svm);
1638 
1639 }
1640 
1641 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1642                                        unsigned int index)
1643 {
1644         u64 *avic_physical_id_table;
1645         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1646 
1647         if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1648                 return NULL;
1649 
1650         avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1651 
1652         return &avic_physical_id_table[index];
1653 }
1654 
1655 /**
1656  * Note:
1657  * AVIC hardware walks the nested page table to check permissions,
1658  * but does not use the SPA address specified in the leaf page
1659  * table entry since it uses  address in the AVIC_BACKING_PAGE pointer
1660  * field of the VMCB. Therefore, we set up the
1661  * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1662  */
1663 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1664 {
1665         struct kvm *kvm = vcpu->kvm;
1666         int ret;
1667 
1668         if (kvm->arch.apic_access_page_done)
1669                 return 0;
1670 
1671         ret = x86_set_memory_region(kvm,
1672                                     APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1673                                     APIC_DEFAULT_PHYS_BASE,
1674                                     PAGE_SIZE);
1675         if (ret)
1676                 return ret;
1677 
1678         kvm->arch.apic_access_page_done = true;
1679         return 0;
1680 }
1681 
1682 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1683 {
1684         int ret;
1685         u64 *entry, new_entry;
1686         int id = vcpu->vcpu_id;
1687         struct vcpu_svm *svm = to_svm(vcpu);
1688 
1689         ret = avic_init_access_page(vcpu);
1690         if (ret)
1691                 return ret;
1692 
1693         if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1694                 return -EINVAL;
1695 
1696         if (!svm->vcpu.arch.apic->regs)
1697                 return -EINVAL;
1698 
1699         svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1700 
1701         /* Setting AVIC backing page address in the phy APIC ID table */
1702         entry = avic_get_physical_id_entry(vcpu, id);
1703         if (!entry)
1704                 return -EINVAL;
1705 
1706         new_entry = READ_ONCE(*entry);
1707         new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1708                               AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1709                               AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1710         WRITE_ONCE(*entry, new_entry);
1711 
1712         svm->avic_physical_id_cache = entry;
1713 
1714         return 0;
1715 }
1716 
1717 static void __sev_asid_free(int asid)
1718 {
1719         struct svm_cpu_data *sd;
1720         int cpu, pos;
1721 
1722         pos = asid - 1;
1723         clear_bit(pos, sev_asid_bitmap);
1724 
1725         for_each_possible_cpu(cpu) {
1726                 sd = per_cpu(svm_data, cpu);
1727                 sd->sev_vmcbs[pos] = NULL;
1728         }
1729 }
1730 
1731 static void sev_asid_free(struct kvm *kvm)
1732 {
1733         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1734 
1735         __sev_asid_free(sev->asid);
1736 }
1737 
1738 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1739 {
1740         struct sev_data_decommission *decommission;
1741         struct sev_data_deactivate *data;
1742 
1743         if (!handle)
1744                 return;
1745 
1746         data = kzalloc(sizeof(*data), GFP_KERNEL);
1747         if (!data)
1748                 return;
1749 
1750         /* deactivate handle */
1751         data->handle = handle;
1752         sev_guest_deactivate(data, NULL);
1753 
1754         wbinvd_on_all_cpus();
1755         sev_guest_df_flush(NULL);
1756         kfree(data);
1757 
1758         decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1759         if (!decommission)
1760                 return;
1761 
1762         /* decommission handle */
1763         decommission->handle = handle;
1764         sev_guest_decommission(decommission, NULL);
1765 
1766         kfree(decommission);
1767 }
1768 
1769 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1770                                     unsigned long ulen, unsigned long *n,
1771                                     int write)
1772 {
1773         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1774         unsigned long npages, npinned, size;
1775         unsigned long locked, lock_limit;
1776         struct page **pages;
1777         unsigned long first, last;
1778 
1779         if (ulen == 0 || uaddr + ulen < uaddr)
1780                 return NULL;
1781 
1782         /* Calculate number of pages. */
1783         first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1784         last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1785         npages = (last - first + 1);
1786 
1787         locked = sev->pages_locked + npages;
1788         lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1789         if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1790                 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1791                 return NULL;
1792         }
1793 
1794         /* Avoid using vmalloc for smaller buffers. */
1795         size = npages * sizeof(struct page *);
1796         if (size > PAGE_SIZE)
1797                 pages = vmalloc(size);
1798         else
1799                 pages = kmalloc(size, GFP_KERNEL);
1800 
1801         if (!pages)
1802                 return NULL;
1803 
1804         /* Pin the user virtual address. */
1805         npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1806         if (npinned != npages) {
1807                 pr_err("SEV: Failure locking %lu pages.\n", npages);
1808                 goto err;
1809         }
1810 
1811         *n = npages;
1812         sev->pages_locked = locked;
1813 
1814         return pages;
1815 
1816 err:
1817         if (npinned > 0)
1818                 release_pages(pages, npinned);
1819 
1820         kvfree(pages);
1821         return NULL;
1822 }
1823 
1824 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1825                              unsigned long npages)
1826 {
1827         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1828 
1829         release_pages(pages, npages);
1830         kvfree(pages);
1831         sev->pages_locked -= npages;
1832 }
1833 
1834 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1835 {
1836         uint8_t *page_virtual;
1837         unsigned long i;
1838 
1839         if (npages == 0 || pages == NULL)
1840                 return;
1841 
1842         for (i = 0; i < npages; i++) {
1843                 page_virtual = kmap_atomic(pages[i]);
1844                 clflush_cache_range(page_virtual, PAGE_SIZE);
1845                 kunmap_atomic(page_virtual);
1846         }
1847 }
1848 
1849 static void __unregister_enc_region_locked(struct kvm *kvm,
1850                                            struct enc_region *region)
1851 {
1852         /*
1853          * The guest may change the memory encryption attribute from C=0 -> C=1
1854          * or vice versa for this memory range. Lets make sure caches are
1855          * flushed to ensure that guest data gets written into memory with
1856          * correct C-bit.
1857          */
1858         sev_clflush_pages(region->pages, region->npages);
1859 
1860         sev_unpin_memory(kvm, region->pages, region->npages);
1861         list_del(&region->list);
1862         kfree(region);
1863 }
1864 
1865 static struct kvm *svm_vm_alloc(void)
1866 {
1867         struct kvm_svm *kvm_svm = vzalloc(sizeof(struct kvm_svm));
1868         return &kvm_svm->kvm;
1869 }
1870 
1871 static void svm_vm_free(struct kvm *kvm)
1872 {
1873         vfree(to_kvm_svm(kvm));
1874 }
1875 
1876 static void sev_vm_destroy(struct kvm *kvm)
1877 {
1878         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1879         struct list_head *head = &sev->regions_list;
1880         struct list_head *pos, *q;
1881 
1882         if (!sev_guest(kvm))
1883                 return;
1884 
1885         mutex_lock(&kvm->lock);
1886 
1887         /*
1888          * if userspace was terminated before unregistering the memory regions
1889          * then lets unpin all the registered memory.
1890          */
1891         if (!list_empty(head)) {
1892                 list_for_each_safe(pos, q, head) {
1893                         __unregister_enc_region_locked(kvm,
1894                                 list_entry(pos, struct enc_region, list));
1895                 }
1896         }
1897 
1898         mutex_unlock(&kvm->lock);
1899 
1900         sev_unbind_asid(kvm, sev->handle);
1901         sev_asid_free(kvm);
1902 }
1903 
1904 static void avic_vm_destroy(struct kvm *kvm)
1905 {
1906         unsigned long flags;
1907         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1908 
1909         if (!avic)
1910                 return;
1911 
1912         if (kvm_svm->avic_logical_id_table_page)
1913                 __free_page(kvm_svm->avic_logical_id_table_page);
1914         if (kvm_svm->avic_physical_id_table_page)
1915                 __free_page(kvm_svm->avic_physical_id_table_page);
1916 
1917         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1918         hash_del(&kvm_svm->hnode);
1919         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1920 }
1921 
1922 static void svm_vm_destroy(struct kvm *kvm)
1923 {
1924         avic_vm_destroy(kvm);
1925         sev_vm_destroy(kvm);
1926 }
1927 
1928 static int avic_vm_init(struct kvm *kvm)
1929 {
1930         unsigned long flags;
1931         int err = -ENOMEM;
1932         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1933         struct kvm_svm *k2;
1934         struct page *p_page;
1935         struct page *l_page;
1936         u32 vm_id;
1937 
1938         if (!avic)
1939                 return 0;
1940 
1941         /* Allocating physical APIC ID table (4KB) */
1942         p_page = alloc_page(GFP_KERNEL);
1943         if (!p_page)
1944                 goto free_avic;
1945 
1946         kvm_svm->avic_physical_id_table_page = p_page;
1947         clear_page(page_address(p_page));
1948 
1949         /* Allocating logical APIC ID table (4KB) */
1950         l_page = alloc_page(GFP_KERNEL);
1951         if (!l_page)
1952                 goto free_avic;
1953 
1954         kvm_svm->avic_logical_id_table_page = l_page;
1955         clear_page(page_address(l_page));
1956 
1957         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1958  again:
1959         vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1960         if (vm_id == 0) { /* id is 1-based, zero is not okay */
1961                 next_vm_id_wrapped = 1;
1962                 goto again;
1963         }
1964         /* Is it still in use? Only possible if wrapped at least once */
1965         if (next_vm_id_wrapped) {
1966                 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
1967                         if (k2->avic_vm_id == vm_id)
1968                                 goto again;
1969                 }
1970         }
1971         kvm_svm->avic_vm_id = vm_id;
1972         hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
1973         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1974 
1975         return 0;
1976 
1977 free_avic:
1978         avic_vm_destroy(kvm);
1979         return err;
1980 }
1981 
1982 static inline int
1983 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1984 {
1985         int ret = 0;
1986         unsigned long flags;
1987         struct amd_svm_iommu_ir *ir;
1988         struct vcpu_svm *svm = to_svm(vcpu);
1989 
1990         if (!kvm_arch_has_assigned_device(vcpu->kvm))
1991                 return 0;
1992 
1993         /*
1994          * Here, we go through the per-vcpu ir_list to update all existing
1995          * interrupt remapping table entry targeting this vcpu.
1996          */
1997         spin_lock_irqsave(&svm->ir_list_lock, flags);
1998 
1999         if (list_empty(&svm->ir_list))
2000                 goto out;
2001 
2002         list_for_each_entry(ir, &svm->ir_list, node) {
2003                 ret = amd_iommu_update_ga(cpu, r, ir->data);
2004                 if (ret)
2005                         break;
2006         }
2007 out:
2008         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2009         return ret;
2010 }
2011 
2012 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2013 {
2014         u64 entry;
2015         /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2016         int h_physical_id = kvm_cpu_get_apicid(cpu);
2017         struct vcpu_svm *svm = to_svm(vcpu);
2018 
2019         if (!kvm_vcpu_apicv_active(vcpu))
2020                 return;
2021 
2022         if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
2023                 return;
2024 
2025         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2026         WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2027 
2028         entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2029         entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2030 
2031         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2032         if (svm->avic_is_running)
2033                 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2034 
2035         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2036         avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2037                                         svm->avic_is_running);
2038 }
2039 
2040 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2041 {
2042         u64 entry;
2043         struct vcpu_svm *svm = to_svm(vcpu);
2044 
2045         if (!kvm_vcpu_apicv_active(vcpu))
2046                 return;
2047 
2048         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2049         if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2050                 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2051 
2052         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2053         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2054 }
2055 
2056 /**
2057  * This function is called during VCPU halt/unhalt.
2058  */
2059 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2060 {
2061         struct vcpu_svm *svm = to_svm(vcpu);
2062 
2063         svm->avic_is_running = is_run;
2064         if (is_run)
2065                 avic_vcpu_load(vcpu, vcpu->cpu);
2066         else
2067                 avic_vcpu_put(vcpu);
2068 }
2069 
2070 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2071 {
2072         struct vcpu_svm *svm = to_svm(vcpu);
2073         u32 dummy;
2074         u32 eax = 1;
2075 
2076         vcpu->arch.microcode_version = 0x01000065;
2077         svm->spec_ctrl = 0;
2078         svm->virt_spec_ctrl = 0;
2079 
2080         if (!init_event) {
2081                 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2082                                            MSR_IA32_APICBASE_ENABLE;
2083                 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2084                         svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2085         }
2086         init_vmcb(svm);
2087 
2088         kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2089         kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
2090 
2091         if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2092                 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2093 }
2094 
2095 static int avic_init_vcpu(struct vcpu_svm *svm)
2096 {
2097         int ret;
2098 
2099         if (!kvm_vcpu_apicv_active(&svm->vcpu))
2100                 return 0;
2101 
2102         ret = avic_init_backing_page(&svm->vcpu);
2103         if (ret)
2104                 return ret;
2105 
2106         INIT_LIST_HEAD(&svm->ir_list);
2107         spin_lock_init(&svm->ir_list_lock);
2108 
2109         return ret;
2110 }
2111 
2112 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
2113 {
2114         struct vcpu_svm *svm;
2115         struct page *page;
2116         struct page *msrpm_pages;
2117         struct page *hsave_page;
2118         struct page *nested_msrpm_pages;
2119         int err;
2120 
2121         svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2122         if (!svm) {
2123                 err = -ENOMEM;
2124                 goto out;
2125         }
2126 
2127         err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2128         if (err)
2129                 goto free_svm;
2130 
2131         err = -ENOMEM;
2132         page = alloc_page(GFP_KERNEL);
2133         if (!page)
2134                 goto uninit;
2135 
2136         msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2137         if (!msrpm_pages)
2138                 goto free_page1;
2139 
2140         nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2141         if (!nested_msrpm_pages)
2142                 goto free_page2;
2143 
2144         hsave_page = alloc_page(GFP_KERNEL);
2145         if (!hsave_page)
2146                 goto free_page3;
2147 
2148         err = avic_init_vcpu(svm);
2149         if (err)
2150                 goto free_page4;
2151 
2152         /* We initialize this flag to true to make sure that the is_running
2153          * bit would be set the first time the vcpu is loaded.
2154          */
2155         svm->avic_is_running = true;
2156 
2157         svm->nested.hsave = page_address(hsave_page);
2158 
2159         svm->msrpm = page_address(msrpm_pages);
2160         svm_vcpu_init_msrpm(svm->msrpm);
2161 
2162         svm->nested.msrpm = page_address(nested_msrpm_pages);
2163         svm_vcpu_init_msrpm(svm->nested.msrpm);
2164 
2165         svm->vmcb = page_address(page);
2166         clear_page(svm->vmcb);
2167         svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2168         svm->asid_generation = 0;
2169         init_vmcb(svm);
2170 
2171         svm_init_osvw(&svm->vcpu);
2172 
2173         return &svm->vcpu;
2174 
2175 free_page4:
2176         __free_page(hsave_page);
2177 free_page3:
2178         __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2179 free_page2:
2180         __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2181 free_page1:
2182         __free_page(page);
2183 uninit:
2184         kvm_vcpu_uninit(&svm->vcpu);
2185 free_svm:
2186         kmem_cache_free(kvm_vcpu_cache, svm);
2187 out:
2188         return ERR_PTR(err);
2189 }
2190 
2191 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2192 {
2193         struct vcpu_svm *svm = to_svm(vcpu);
2194 
2195         __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2196         __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2197         __free_page(virt_to_page(svm->nested.hsave));
2198         __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2199         kvm_vcpu_uninit(vcpu);
2200         kmem_cache_free(kvm_vcpu_cache, svm);
2201         /*
2202          * The vmcb page can be recycled, causing a false negative in
2203          * svm_vcpu_load(). So do a full IBPB now.
2204          */
2205         indirect_branch_prediction_barrier();
2206 }
2207 
2208 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2209 {
2210         struct vcpu_svm *svm = to_svm(vcpu);
2211         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2212         int i;
2213 
2214         if (unlikely(cpu != vcpu->cpu)) {
2215                 svm->asid_generation = 0;
2216                 mark_all_dirty(svm->vmcb);
2217         }
2218 
2219 #ifdef CONFIG_X86_64
2220         rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2221 #endif
2222         savesegment(fs, svm->host.fs);
2223         savesegment(gs, svm->host.gs);
2224         svm->host.ldt = kvm_read_ldt();
2225 
2226         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2227                 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2228 
2229         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2230                 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2231                 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2232                         __this_cpu_write(current_tsc_ratio, tsc_ratio);
2233                         wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2234                 }
2235         }
2236         /* This assumes that the kernel never uses MSR_TSC_AUX */
2237         if (static_cpu_has(X86_FEATURE_RDTSCP))
2238                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2239 
2240         if (sd->current_vmcb != svm->vmcb) {
2241                 sd->current_vmcb = svm->vmcb;
2242                 indirect_branch_prediction_barrier();
2243         }
2244         avic_vcpu_load(vcpu, cpu);
2245 }
2246 
2247 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2248 {
2249         struct vcpu_svm *svm = to_svm(vcpu);
2250         int i;
2251 
2252         avic_vcpu_put(vcpu);
2253 
2254         ++vcpu->stat.host_state_reload;
2255         kvm_load_ldt(svm->host.ldt);
2256 #ifdef CONFIG_X86_64
2257         loadsegment(fs, svm->host.fs);
2258         wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2259         load_gs_index(svm->host.gs);
2260 #else
2261 #ifdef CONFIG_X86_32_LAZY_GS
2262         loadsegment(gs, svm->host.gs);
2263 #endif
2264 #endif
2265         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2266                 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2267 }
2268 
2269 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2270 {
2271         avic_set_running(vcpu, false);
2272 }
2273 
2274 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2275 {
2276         avic_set_running(vcpu, true);
2277 }
2278 
2279 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2280 {
2281         struct vcpu_svm *svm = to_svm(vcpu);
2282         unsigned long rflags = svm->vmcb->save.rflags;
2283 
2284         if (svm->nmi_singlestep) {
2285                 /* Hide our flags if they were not set by the guest */
2286                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2287                         rflags &= ~X86_EFLAGS_TF;
2288                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2289                         rflags &= ~X86_EFLAGS_RF;
2290         }
2291         return rflags;
2292 }
2293 
2294 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2295 {
2296         if (to_svm(vcpu)->nmi_singlestep)
2297                 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2298 
2299        /*
2300         * Any change of EFLAGS.VM is accompanied by a reload of SS
2301         * (caused by either a task switch or an inter-privilege IRET),
2302         * so we do not need to update the CPL here.
2303         */
2304         to_svm(vcpu)->vmcb->save.rflags = rflags;
2305 }
2306 
2307 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2308 {
2309         switch (reg) {
2310         case VCPU_EXREG_PDPTR:
2311                 BUG_ON(!npt_enabled);
2312                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2313                 break;
2314         default:
2315                 BUG();
2316         }
2317 }
2318 
2319 static void svm_set_vintr(struct vcpu_svm *svm)
2320 {
2321         set_intercept(svm, INTERCEPT_VINTR);
2322 }
2323 
2324 static void svm_clear_vintr(struct vcpu_svm *svm)
2325 {
2326         clr_intercept(svm, INTERCEPT_VINTR);
2327 }
2328 
2329 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2330 {
2331         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2332 
2333         switch (seg) {
2334         case VCPU_SREG_CS: return &save->cs;
2335         case VCPU_SREG_DS: return &save->ds;
2336         case VCPU_SREG_ES: return &save->es;
2337         case VCPU_SREG_FS: return &save->fs;
2338         case VCPU_SREG_GS: return &save->gs;
2339         case VCPU_SREG_SS: return &save->ss;
2340         case VCPU_SREG_TR: return &save->tr;
2341         case VCPU_SREG_LDTR: return &save->ldtr;
2342         }
2343         BUG();
2344         return NULL;
2345 }
2346 
2347 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2348 {
2349         struct vmcb_seg *s = svm_seg(vcpu, seg);
2350 
2351         return s->base;
2352 }
2353 
2354 static void svm_get_segment(struct kvm_vcpu *vcpu,
2355                             struct kvm_segment *var, int seg)
2356 {
2357         struct vmcb_seg *s = svm_seg(vcpu, seg);
2358 
2359         var->base = s->base;
2360         var->limit = s->limit;
2361         var->selector = s->selector;
2362         var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2363         var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2364         var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2365         var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2366         var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2367         var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2368         var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2369 
2370         /*
2371          * AMD CPUs circa 2014 track the G bit for all segments except CS.
2372          * However, the SVM spec states that the G bit is not observed by the
2373          * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2374          * So let's synthesize a legal G bit for all segments, this helps
2375          * running KVM nested. It also helps cross-vendor migration, because
2376          * Intel's vmentry has a check on the 'G' bit.
2377          */
2378         var->g = s->limit > 0xfffff;
2379 
2380         /*
2381          * AMD's VMCB does not have an explicit unusable field, so emulate it
2382          * for cross vendor migration purposes by "not present"
2383          */
2384         var->unusable = !var->present;
2385 
2386         switch (seg) {
2387         case VCPU_SREG_TR:
2388                 /*
2389                  * Work around a bug where the busy flag in the tr selector
2390                  * isn't exposed
2391                  */
2392                 var->type |= 0x2;
2393                 break;
2394         case VCPU_SREG_DS:
2395         case VCPU_SREG_ES:
2396         case VCPU_SREG_FS:
2397         case VCPU_SREG_GS:
2398                 /*
2399                  * The accessed bit must always be set in the segment
2400                  * descriptor cache, although it can be cleared in the
2401                  * descriptor, the cached bit always remains at 1. Since
2402                  * Intel has a check on this, set it here to support
2403                  * cross-vendor migration.
2404                  */
2405                 if (!var->unusable)
2406                         var->type |= 0x1;
2407                 break;
2408         case VCPU_SREG_SS:
2409                 /*
2410                  * On AMD CPUs sometimes the DB bit in the segment
2411                  * descriptor is left as 1, although the whole segment has
2412                  * been made unusable. Clear it here to pass an Intel VMX
2413                  * entry check when cross vendor migrating.
2414                  */
2415                 if (var->unusable)
2416                         var->db = 0;
2417                 /* This is symmetric with svm_set_segment() */
2418                 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2419                 break;
2420         }
2421 }
2422 
2423 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2424 {
2425         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2426 
2427         return save->cpl;
2428 }
2429 
2430 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2431 {
2432         struct vcpu_svm *svm = to_svm(vcpu);
2433 
2434         dt->size = svm->vmcb->save.idtr.limit;
2435         dt->address = svm->vmcb->save.idtr.base;
2436 }
2437 
2438 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2439 {
2440         struct vcpu_svm *svm = to_svm(vcpu);
2441 
2442         svm->vmcb->save.idtr.limit = dt->size;
2443         svm->vmcb->save.idtr.base = dt->address ;
2444         mark_dirty(svm->vmcb, VMCB_DT);
2445 }
2446 
2447 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2448 {
2449         struct vcpu_svm *svm = to_svm(vcpu);
2450 
2451         dt->size = svm->vmcb->save.gdtr.limit;
2452         dt->address = svm->vmcb->save.gdtr.base;
2453 }
2454 
2455 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2456 {
2457         struct vcpu_svm *svm = to_svm(vcpu);
2458 
2459         svm->vmcb->save.gdtr.limit = dt->size;
2460         svm->vmcb->save.gdtr.base = dt->address ;
2461         mark_dirty(svm->vmcb, VMCB_DT);
2462 }
2463 
2464 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2465 {
2466 }
2467 
2468 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2469 {
2470 }
2471 
2472 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2473 {
2474 }
2475 
2476 static void update_cr0_intercept(struct vcpu_svm *svm)
2477 {
2478         ulong gcr0 = svm->vcpu.arch.cr0;
2479         u64 *hcr0 = &svm->vmcb->save.cr0;
2480 
2481         *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2482                 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2483 
2484         mark_dirty(svm->vmcb, VMCB_CR);
2485 
2486         if (gcr0 == *hcr0) {
2487                 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2488                 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2489         } else {
2490                 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2491                 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2492         }
2493 }
2494 
2495 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2496 {
2497         struct vcpu_svm *svm = to_svm(vcpu);
2498 
2499 #ifdef CONFIG_X86_64
2500         if (vcpu->arch.efer & EFER_LME) {
2501                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2502                         vcpu->arch.efer |= EFER_LMA;
2503                         svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2504                 }
2505 
2506                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2507                         vcpu->arch.efer &= ~EFER_LMA;
2508                         svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2509                 }
2510         }
2511 #endif
2512         vcpu->arch.cr0 = cr0;
2513 
2514         if (!npt_enabled)
2515                 cr0 |= X86_CR0_PG | X86_CR0_WP;
2516 
2517         /*
2518          * re-enable caching here because the QEMU bios
2519          * does not do it - this results in some delay at
2520          * reboot
2521          */
2522         if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2523                 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2524         svm->vmcb->save.cr0 = cr0;
2525         mark_dirty(svm->vmcb, VMCB_CR);
2526         update_cr0_intercept(svm);
2527 }
2528 
2529 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2530 {
2531         unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2532         unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2533 
2534         if (cr4 & X86_CR4_VMXE)
2535                 return 1;
2536 
2537         if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2538                 svm_flush_tlb(vcpu, true);
2539 
2540         vcpu->arch.cr4 = cr4;
2541         if (!npt_enabled)
2542                 cr4 |= X86_CR4_PAE;
2543         cr4 |= host_cr4_mce;
2544         to_svm(vcpu)->vmcb->save.cr4 = cr4;
2545         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2546         return 0;
2547 }
2548 
2549 static void svm_set_segment(struct kvm_vcpu *vcpu,
2550                             struct kvm_segment *var, int seg)
2551 {
2552         struct vcpu_svm *svm = to_svm(vcpu);
2553         struct vmcb_seg *s = svm_seg(vcpu, seg);
2554 
2555         s->base = var->base;
2556         s->limit = var->limit;
2557         s->selector = var->selector;
2558         s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2559         s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2560         s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2561         s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2562         s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2563         s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2564         s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2565         s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2566 
2567         /*
2568          * This is always accurate, except if SYSRET returned to a segment
2569          * with SS.DPL != 3.  Intel does not have this quirk, and always
2570          * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2571          * would entail passing the CPL to userspace and back.
2572          */
2573         if (seg == VCPU_SREG_SS)
2574                 /* This is symmetric with svm_get_segment() */
2575                 svm->vmcb->save.cpl = (var->dpl & 3);
2576 
2577         mark_dirty(svm->vmcb, VMCB_SEG);
2578 }
2579 
2580 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2581 {
2582         struct vcpu_svm *svm = to_svm(vcpu);
2583 
2584         clr_exception_intercept(svm, BP_VECTOR);
2585 
2586         if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2587                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2588                         set_exception_intercept(svm, BP_VECTOR);
2589         } else
2590                 vcpu->guest_debug = 0;
2591 }
2592 
2593 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2594 {
2595         if (sd->next_asid > sd->max_asid) {
2596                 ++sd->asid_generation;
2597                 sd->next_asid = sd->min_asid;
2598                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2599         }
2600 
2601         svm->asid_generation = sd->asid_generation;
2602         svm->vmcb->control.asid = sd->next_asid++;
2603 
2604         mark_dirty(svm->vmcb, VMCB_ASID);
2605 }
2606 
2607 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2608 {
2609         return to_svm(vcpu)->vmcb->save.dr6;
2610 }
2611 
2612 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2613 {
2614         struct vcpu_svm *svm = to_svm(vcpu);
2615 
2616         svm->vmcb->save.dr6 = value;
2617         mark_dirty(svm->vmcb, VMCB_DR);
2618 }
2619 
2620 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2621 {
2622         struct vcpu_svm *svm = to_svm(vcpu);
2623 
2624         get_debugreg(vcpu->arch.db[0], 0);
2625         get_debugreg(vcpu->arch.db[1], 1);
2626         get_debugreg(vcpu->arch.db[2], 2);
2627         get_debugreg(vcpu->arch.db[3], 3);
2628         vcpu->arch.dr6 = svm_get_dr6(vcpu);
2629         vcpu->arch.dr7 = svm->vmcb->save.dr7;
2630 
2631         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2632         set_dr_intercepts(svm);
2633 }
2634 
2635 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2636 {
2637         struct vcpu_svm *svm = to_svm(vcpu);
2638 
2639         svm->vmcb->save.dr7 = value;
2640         mark_dirty(svm->vmcb, VMCB_DR);
2641 }
2642 
2643 static int pf_interception(struct vcpu_svm *svm)
2644 {
2645         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2646         u64 error_code = svm->vmcb->control.exit_info_1;
2647 
2648         return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2649                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2650                         svm->vmcb->control.insn_bytes : NULL,
2651                         svm->vmcb->control.insn_len);
2652 }
2653 
2654 static int npf_interception(struct vcpu_svm *svm)
2655 {
2656         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2657         u64 error_code = svm->vmcb->control.exit_info_1;
2658 
2659         trace_kvm_page_fault(fault_address, error_code);
2660         return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2661                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2662                         svm->vmcb->control.insn_bytes : NULL,
2663                         svm->vmcb->control.insn_len);
2664 }
2665 
2666 static int db_interception(struct vcpu_svm *svm)
2667 {
2668         struct kvm_run *kvm_run = svm->vcpu.run;
2669 
2670         if (!(svm->vcpu.guest_debug &
2671               (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2672                 !svm->nmi_singlestep) {
2673                 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2674                 return 1;
2675         }
2676 
2677         if (svm->nmi_singlestep) {
2678                 disable_nmi_singlestep(svm);
2679         }
2680 
2681         if (svm->vcpu.guest_debug &
2682             (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2683                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2684                 kvm_run->debug.arch.pc =
2685                         svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2686                 kvm_run->debug.arch.exception = DB_VECTOR;
2687                 return 0;
2688         }
2689 
2690         return 1;
2691 }
2692 
2693 static int bp_interception(struct vcpu_svm *svm)
2694 {
2695         struct kvm_run *kvm_run = svm->vcpu.run;
2696 
2697         kvm_run->exit_reason = KVM_EXIT_DEBUG;
2698         kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2699         kvm_run->debug.arch.exception = BP_VECTOR;
2700         return 0;
2701 }
2702 
2703 static int ud_interception(struct vcpu_svm *svm)
2704 {
2705         return handle_ud(&svm->vcpu);
2706 }
2707 
2708 static int ac_interception(struct vcpu_svm *svm)
2709 {
2710         kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2711         return 1;
2712 }
2713 
2714 static int gp_interception(struct vcpu_svm *svm)
2715 {
2716         struct kvm_vcpu *vcpu = &svm->vcpu;
2717         u32 error_code = svm->vmcb->control.exit_info_1;
2718         int er;
2719 
2720         WARN_ON_ONCE(!enable_vmware_backdoor);
2721 
2722         er = emulate_instruction(vcpu,
2723                 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
2724         if (er == EMULATE_USER_EXIT)
2725                 return 0;
2726         else if (er != EMULATE_DONE)
2727                 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2728         return 1;
2729 }
2730 
2731 static bool is_erratum_383(void)
2732 {
2733         int err, i;
2734         u64 value;
2735 
2736         if (!erratum_383_found)
2737                 return false;
2738 
2739         value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2740         if (err)
2741                 return false;
2742 
2743         /* Bit 62 may or may not be set for this mce */
2744         value &= ~(1ULL << 62);
2745 
2746         if (value != 0xb600000000010015ULL)
2747                 return false;
2748 
2749         /* Clear MCi_STATUS registers */
2750         for (i = 0; i < 6; ++i)
2751                 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2752 
2753         value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2754         if (!err) {
2755                 u32 low, high;
2756 
2757                 value &= ~(1ULL << 2);
2758                 low    = lower_32_bits(value);
2759                 high   = upper_32_bits(value);
2760 
2761                 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2762         }
2763 
2764         /* Flush tlb to evict multi-match entries */
2765         __flush_tlb_all();
2766 
2767         return true;
2768 }
2769 
2770 static void svm_handle_mce(struct vcpu_svm *svm)
2771 {
2772         if (is_erratum_383()) {
2773                 /*
2774                  * Erratum 383 triggered. Guest state is corrupt so kill the
2775                  * guest.
2776                  */
2777                 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2778 
2779                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2780 
2781                 return;
2782         }
2783 
2784         /*
2785          * On an #MC intercept the MCE handler is not called automatically in
2786          * the host. So do it by hand here.
2787          */
2788         asm volatile (
2789                 "int $0x12\n");
2790         /* not sure if we ever come back to this point */
2791 
2792         return;
2793 }
2794 
2795 static int mc_interception(struct vcpu_svm *svm)
2796 {
2797         return 1;
2798 }
2799 
2800 static int shutdown_interception(struct vcpu_svm *svm)
2801 {
2802         struct kvm_run *kvm_run = svm->vcpu.run;
2803 
2804         /*
2805          * VMCB is undefined after a SHUTDOWN intercept
2806          * so reinitialize it.
2807          */
2808         clear_page(svm->vmcb);
2809         init_vmcb(svm);
2810 
2811         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2812         return 0;
2813 }
2814 
2815 static int io_interception(struct vcpu_svm *svm)
2816 {
2817         struct kvm_vcpu *vcpu = &svm->vcpu;
2818         u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2819         int size, in, string;
2820         unsigned port;
2821 
2822         ++svm->vcpu.stat.io_exits;
2823         string = (io_info & SVM_IOIO_STR_MASK) != 0;
2824         in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2825         if (string)
2826                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2827 
2828         port = io_info >> 16;
2829         size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2830         svm->next_rip = svm->vmcb->control.exit_info_2;
2831 
2832         return kvm_fast_pio(&svm->vcpu, size, port, in);
2833 }
2834 
2835 static int nmi_interception(struct vcpu_svm *svm)
2836 {
2837         return 1;
2838 }
2839 
2840 static int intr_interception(struct vcpu_svm *svm)
2841 {
2842         ++svm->vcpu.stat.irq_exits;
2843         return 1;
2844 }
2845 
2846 static int nop_on_interception(struct vcpu_svm *svm)
2847 {
2848         return 1;
2849 }
2850 
2851 static int halt_interception(struct vcpu_svm *svm)
2852 {
2853         svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2854         return kvm_emulate_halt(&svm->vcpu);
2855 }
2856 
2857 static int vmmcall_interception(struct vcpu_svm *svm)
2858 {
2859         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2860         return kvm_emulate_hypercall(&svm->vcpu);
2861 }
2862 
2863 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2864 {
2865         struct vcpu_svm *svm = to_svm(vcpu);
2866 
2867         return svm->nested.nested_cr3;
2868 }
2869 
2870 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2871 {
2872         struct vcpu_svm *svm = to_svm(vcpu);
2873         u64 cr3 = svm->nested.nested_cr3;
2874         u64 pdpte;
2875         int ret;
2876 
2877         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2878                                        offset_in_page(cr3) + index * 8, 8);
2879         if (ret)
2880                 return 0;
2881         return pdpte;
2882 }
2883 
2884 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2885                                    unsigned long root)
2886 {
2887         struct vcpu_svm *svm = to_svm(vcpu);
2888 
2889         svm->vmcb->control.nested_cr3 = __sme_set(root);
2890         mark_dirty(svm->vmcb, VMCB_NPT);
2891         svm_flush_tlb(vcpu, true);
2892 }
2893 
2894 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2895                                        struct x86_exception *fault)
2896 {
2897         struct vcpu_svm *svm = to_svm(vcpu);
2898 
2899         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2900                 /*
2901                  * TODO: track the cause of the nested page fault, and
2902                  * correctly fill in the high bits of exit_info_1.
2903                  */
2904                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2905                 svm->vmcb->control.exit_code_hi = 0;
2906                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2907                 svm->vmcb->control.exit_info_2 = fault->address;
2908         }
2909 
2910         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2911         svm->vmcb->control.exit_info_1 |= fault->error_code;
2912 
2913         /*
2914          * The present bit is always zero for page structure faults on real
2915          * hardware.
2916          */
2917         if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2918                 svm->vmcb->control.exit_info_1 &= ~1;
2919 
2920         nested_svm_vmexit(svm);
2921 }
2922 
2923 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2924 {
2925         WARN_ON(mmu_is_nested(vcpu));
2926         kvm_init_shadow_mmu(vcpu);
2927         vcpu->arch.mmu.set_cr3           = nested_svm_set_tdp_cr3;
2928         vcpu->arch.mmu.get_cr3           = nested_svm_get_tdp_cr3;
2929         vcpu->arch.mmu.get_pdptr         = nested_svm_get_tdp_pdptr;
2930         vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2931         vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2932         reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2933         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
2934 }
2935 
2936 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2937 {
2938         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2939 }
2940 
2941 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2942 {
2943         if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2944             !is_paging(&svm->vcpu)) {
2945                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2946                 return 1;
2947         }
2948 
2949         if (svm->vmcb->save.cpl) {
2950                 kvm_inject_gp(&svm->vcpu, 0);
2951                 return 1;
2952         }
2953 
2954         return 0;
2955 }
2956 
2957 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2958                                       bool has_error_code, u32 error_code)
2959 {
2960         int vmexit;
2961 
2962         if (!is_guest_mode(&svm->vcpu))
2963                 return 0;
2964 
2965         vmexit = nested_svm_intercept(svm);
2966         if (vmexit != NESTED_EXIT_DONE)
2967                 return 0;
2968 
2969         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2970         svm->vmcb->control.exit_code_hi = 0;
2971         svm->vmcb->control.exit_info_1 = error_code;
2972 
2973         /*
2974          * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2975          * The fix is to add the ancillary datum (CR2 or DR6) to structs
2976          * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2977          * written only when inject_pending_event runs (DR6 would written here
2978          * too).  This should be conditional on a new capability---if the
2979          * capability is disabled, kvm_multiple_exception would write the
2980          * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2981          */
2982         if (svm->vcpu.arch.exception.nested_apf)
2983                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2984         else
2985                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2986 
2987         svm->nested.exit_required = true;
2988         return vmexit;
2989 }
2990 
2991 /* This function returns true if it is save to enable the irq window */
2992 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2993 {
2994         if (!is_guest_mode(&svm->vcpu))
2995                 return true;
2996 
2997         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2998                 return true;
2999 
3000         if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3001                 return false;
3002 
3003         /*
3004          * if vmexit was already requested (by intercepted exception
3005          * for instance) do not overwrite it with "external interrupt"
3006          * vmexit.
3007          */
3008         if (svm->nested.exit_required)
3009                 return false;
3010 
3011         svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
3012         svm->vmcb->control.exit_info_1 = 0;
3013         svm->vmcb->control.exit_info_2 = 0;
3014 
3015         if (svm->nested.intercept & 1ULL) {
3016                 /*
3017                  * The #vmexit can't be emulated here directly because this
3018                  * code path runs with irqs and preemption disabled. A
3019                  * #vmexit emulation might sleep. Only signal request for
3020                  * the #vmexit here.
3021                  */
3022                 svm->nested.exit_required = true;
3023                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3024                 return false;
3025         }
3026 
3027         return true;
3028 }
3029 
3030 /* This function returns true if it is save to enable the nmi window */
3031 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3032 {
3033         if (!is_guest_mode(&svm->vcpu))
3034                 return true;
3035 
3036         if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3037                 return true;
3038 
3039         svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3040         svm->nested.exit_required = true;
3041 
3042         return false;
3043 }
3044 
3045 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
3046 {
3047         struct page *page;
3048 
3049         might_sleep();
3050 
3051         page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
3052         if (is_error_page(page))
3053                 goto error;
3054 
3055         *_page = page;
3056 
3057         return kmap(page);
3058 
3059 error:
3060         kvm_inject_gp(&svm->vcpu, 0);
3061 
3062         return NULL;
3063 }
3064 
3065 static void nested_svm_unmap(struct page *page)
3066 {
3067         kunmap(page);
3068         kvm_release_page_dirty(page);
3069 }
3070 
3071 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3072 {
3073         unsigned port, size, iopm_len;
3074         u16 val, mask;
3075         u8 start_bit;
3076         u64 gpa;
3077 
3078         if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3079                 return NESTED_EXIT_HOST;
3080 
3081         port = svm->vmcb->control.exit_info_1 >> 16;
3082         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3083                 SVM_IOIO_SIZE_SHIFT;
3084         gpa  = svm->nested.vmcb_iopm + (port / 8);
3085         start_bit = port % 8;
3086         iopm_len = (start_bit + size > 8) ? 2 : 1;
3087         mask = (0xf >> (4 - size)) << start_bit;
3088         val = 0;
3089 
3090         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3091                 return NESTED_EXIT_DONE;
3092 
3093         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3094 }
3095 
3096 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3097 {
3098         u32 offset, msr, value;
3099         int write, mask;
3100 
3101         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3102                 return NESTED_EXIT_HOST;
3103 
3104         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3105         offset = svm_msrpm_offset(msr);
3106         write  = svm->vmcb->control.exit_info_1 & 1;
3107         mask   = 1 << ((2 * (msr & 0xf)) + write);
3108 
3109         if (offset == MSR_INVALID)
3110                 return NESTED_EXIT_DONE;
3111 
3112         /* Offset is in 32 bit units but need in 8 bit units */
3113         offset *= 4;
3114 
3115         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3116                 return NESTED_EXIT_DONE;
3117 
3118         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3119 }
3120 
3121 /* DB exceptions for our internal use must not cause vmexit */
3122 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3123 {
3124         unsigned long dr6;
3125 
3126         /* if we're not singlestepping, it's not ours */
3127         if (!svm->nmi_singlestep)
3128                 return NESTED_EXIT_DONE;
3129 
3130         /* if it's not a singlestep exception, it's not ours */
3131         if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3132                 return NESTED_EXIT_DONE;
3133         if (!(dr6 & DR6_BS))
3134                 return NESTED_EXIT_DONE;
3135 
3136         /* if the guest is singlestepping, it should get the vmexit */
3137         if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3138                 disable_nmi_singlestep(svm);
3139                 return NESTED_EXIT_DONE;
3140         }
3141 
3142         /* it's ours, the nested hypervisor must not see this one */
3143         return NESTED_EXIT_HOST;
3144 }
3145 
3146 static int nested_svm_exit_special(struct vcpu_svm *svm)
3147 {
3148         u32 exit_code = svm->vmcb->control.exit_code;
3149 
3150         switch (exit_code) {
3151         case SVM_EXIT_INTR:
3152         case SVM_EXIT_NMI:
3153         case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3154                 return NESTED_EXIT_HOST;
3155         case SVM_EXIT_NPF:
3156                 /* For now we are always handling NPFs when using them */
3157                 if (npt_enabled)
3158                         return NESTED_EXIT_HOST;
3159                 break;
3160         case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3161                 /* When we're shadowing, trap PFs, but not async PF */
3162                 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3163                         return NESTED_EXIT_HOST;
3164                 break;
3165         default:
3166                 break;
3167         }
3168 
3169         return NESTED_EXIT_CONTINUE;
3170 }
3171 
3172 /*
3173  * If this function returns true, this #vmexit was already handled
3174  */
3175 static int nested_svm_intercept(struct vcpu_svm *svm)
3176 {
3177         u32 exit_code = svm->vmcb->control.exit_code;
3178         int vmexit = NESTED_EXIT_HOST;
3179 
3180         switch (exit_code) {
3181         case SVM_EXIT_MSR:
3182                 vmexit = nested_svm_exit_handled_msr(svm);
3183                 break;
3184         case SVM_EXIT_IOIO:
3185                 vmexit = nested_svm_intercept_ioio(svm);
3186                 break;
3187         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3188                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3189                 if (svm->nested.intercept_cr & bit)
3190                         vmexit = NESTED_EXIT_DONE;
3191                 break;
3192         }
3193         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3194                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3195                 if (svm->nested.intercept_dr & bit)
3196                         vmexit = NESTED_EXIT_DONE;
3197                 break;
3198         }
3199         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3200                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3201                 if (svm->nested.intercept_exceptions & excp_bits) {
3202                         if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3203                                 vmexit = nested_svm_intercept_db(svm);
3204                         else
3205                                 vmexit = NESTED_EXIT_DONE;
3206                 }
3207                 /* async page fault always cause vmexit */
3208                 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3209                          svm->vcpu.arch.exception.nested_apf != 0)
3210                         vmexit = NESTED_EXIT_DONE;
3211                 break;
3212         }
3213         case SVM_EXIT_ERR: {
3214                 vmexit = NESTED_EXIT_DONE;
3215                 break;
3216         }
3217         default: {
3218                 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3219                 if (svm->nested.intercept & exit_bits)
3220                         vmexit = NESTED_EXIT_DONE;
3221         }
3222         }
3223 
3224         return vmexit;
3225 }
3226 
3227 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3228 {
3229         int vmexit;
3230 
3231         vmexit = nested_svm_intercept(svm);
3232 
3233         if (vmexit == NESTED_EXIT_DONE)
3234                 nested_svm_vmexit(svm);
3235 
3236         return vmexit;
3237 }
3238 
3239 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3240 {
3241         struct vmcb_control_area *dst  = &dst_vmcb->control;
3242         struct vmcb_control_area *from = &from_vmcb->control;
3243 
3244         dst->intercept_cr         = from->intercept_cr;
3245         dst->intercept_dr         = from->intercept_dr;
3246         dst->intercept_exceptions = from->intercept_exceptions;
3247         dst->intercept            = from->intercept;
3248         dst->iopm_base_pa         = from->iopm_base_pa;
3249         dst->msrpm_base_pa        = from->msrpm_base_pa;
3250         dst->tsc_offset           = from->tsc_offset;
3251         dst->asid                 = from->asid;
3252         dst->tlb_ctl              = from->tlb_ctl;
3253         dst->int_ctl              = from->int_ctl;
3254         dst->int_vector           = from->int_vector;
3255         dst->int_state            = from->int_state;
3256         dst->exit_code            = from->exit_code;
3257         dst->exit_code_hi         = from->exit_code_hi;
3258         dst->exit_info_1          = from->exit_info_1;
3259         dst->exit_info_2          = from->exit_info_2;
3260         dst->exit_int_info        = from->exit_int_info;
3261         dst->exit_int_info_err    = from->exit_int_info_err;
3262         dst->nested_ctl           = from->nested_ctl;
3263         dst->event_inj            = from->event_inj;
3264         dst->event_inj_err        = from->event_inj_err;
3265         dst->nested_cr3           = from->nested_cr3;
3266         dst->virt_ext              = from->virt_ext;
3267 }
3268 
3269 static int nested_svm_vmexit(struct vcpu_svm *svm)
3270 {
3271         struct vmcb *nested_vmcb;
3272         struct vmcb *hsave = svm->nested.hsave;
3273         struct vmcb *vmcb = svm->vmcb;
3274         struct page *page;
3275 
3276         trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3277                                        vmcb->control.exit_info_1,
3278                                        vmcb->control.exit_info_2,
3279                                        vmcb->control.exit_int_info,
3280                                        vmcb->control.exit_int_info_err,
3281                                        KVM_ISA_SVM);
3282 
3283         nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3284         if (!nested_vmcb)
3285                 return 1;
3286 
3287         /* Exit Guest-Mode */
3288         leave_guest_mode(&svm->vcpu);
3289         svm->nested.vmcb = 0;
3290 
3291         /* Give the current vmcb to the guest */
3292         disable_gif(svm);
3293 
3294         nested_vmcb->save.es     = vmcb->save.es;
3295         nested_vmcb->save.cs     = vmcb->save.cs;
3296         nested_vmcb->save.ss     = vmcb->save.ss;
3297         nested_vmcb->save.ds     = vmcb->save.ds;
3298         nested_vmcb->save.gdtr   = vmcb->save.gdtr;
3299         nested_vmcb->save.idtr   = vmcb->save.idtr;
3300         nested_vmcb->save.efer   = svm->vcpu.arch.efer;
3301         nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
3302         nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
3303         nested_vmcb->save.cr2    = vmcb->save.cr2;
3304         nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
3305         nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3306         nested_vmcb->save.rip    = vmcb->save.rip;
3307         nested_vmcb->save.rsp    = vmcb->save.rsp;
3308         nested_vmcb->save.rax    = vmcb->save.rax;
3309         nested_vmcb->save.dr7    = vmcb->save.dr7;
3310         nested_vmcb->save.dr6    = vmcb->save.dr6;
3311         nested_vmcb->save.cpl    = vmcb->save.cpl;
3312 
3313         nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
3314         nested_vmcb->control.int_vector        = vmcb->control.int_vector;
3315         nested_vmcb->control.int_state         = vmcb->control.int_state;
3316         nested_vmcb->control.exit_code         = vmcb->control.exit_code;
3317         nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
3318         nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
3319         nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
3320         nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
3321         nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3322 
3323         if (svm->nrips_enabled)
3324                 nested_vmcb->control.next_rip  = vmcb->control.next_rip;
3325 
3326         /*
3327          * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3328          * to make sure that we do not lose injected events. So check event_inj
3329          * here and copy it to exit_int_info if it is valid.
3330          * Exit_int_info and event_inj can't be both valid because the case
3331          * below only happens on a VMRUN instruction intercept which has
3332          * no valid exit_int_info set.
3333          */
3334         if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3335                 struct vmcb_control_area *nc = &nested_vmcb->control;
3336 
3337                 nc->exit_int_info     = vmcb->control.event_inj;
3338                 nc->exit_int_info_err = vmcb->control.event_inj_err;
3339         }
3340 
3341         nested_vmcb->control.tlb_ctl           = 0;
3342         nested_vmcb->control.event_inj         = 0;
3343         nested_vmcb->control.event_inj_err     = 0;
3344 
3345         /* We always set V_INTR_MASKING and remember the old value in hflags */
3346         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3347                 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3348 
3349         /* Restore the original control entries */
3350         copy_vmcb_control_area(vmcb, hsave);
3351 
3352         svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3353         kvm_clear_exception_queue(&svm->vcpu);
3354         kvm_clear_interrupt_queue(&svm->vcpu);
3355 
3356         svm->nested.nested_cr3 = 0;
3357 
3358         /* Restore selected save entries */
3359         svm->vmcb->save.es = hsave->save.es;
3360         svm->vmcb->save.cs = hsave->save.cs;
3361         svm->vmcb->save.ss = hsave->save.ss;
3362         svm->vmcb->save.ds = hsave->save.ds;
3363         svm->vmcb->save.gdtr = hsave->save.gdtr;
3364         svm->vmcb->save.idtr = hsave->save.idtr;
3365         kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3366         svm_set_efer(&svm->vcpu, hsave->save.efer);
3367         svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3368         svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3369         if (npt_enabled) {
3370                 svm->vmcb->save.cr3 = hsave->save.cr3;
3371                 svm->vcpu.arch.cr3 = hsave->save.cr3;
3372         } else {
3373                 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3374         }
3375         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3376         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3377         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3378         svm->vmcb->save.dr7 = 0;
3379         svm->vmcb->save.cpl = 0;
3380         svm->vmcb->control.exit_int_info = 0;
3381 
3382         mark_all_dirty(svm->vmcb);
3383 
3384         nested_svm_unmap(page);
3385 
3386         nested_svm_uninit_mmu_context(&svm->vcpu);
3387         kvm_mmu_reset_context(&svm->vcpu);
3388         kvm_mmu_load(&svm->vcpu);
3389 
3390         return 0;
3391 }
3392 
3393 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3394 {
3395         /*
3396          * This function merges the msr permission bitmaps of kvm and the
3397          * nested vmcb. It is optimized in that it only merges the parts where
3398          * the kvm msr permission bitmap may contain zero bits
3399          */
3400         int i;
3401 
3402         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3403                 return true;
3404 
3405         for (i = 0; i < MSRPM_OFFSETS; i++) {
3406                 u32 value, p;
3407                 u64 offset;
3408 
3409                 if (msrpm_offsets[i] == 0xffffffff)
3410                         break;
3411 
3412                 p      = msrpm_offsets[i];
3413                 offset = svm->nested.vmcb_msrpm + (p * 4);
3414 
3415                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3416                         return false;
3417 
3418                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3419         }
3420 
3421         svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3422 
3423         return true;
3424 }
3425 
3426 static bool nested_vmcb_checks(struct vmcb *vmcb)
3427 {
3428         if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3429                 return false;
3430 
3431         if (vmcb->control.asid == 0)
3432                 return false;
3433 
3434         if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3435             !npt_enabled)
3436                 return false;
3437 
3438         return true;
3439 }
3440 
3441 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3442                                  struct vmcb *nested_vmcb, struct page *page)
3443 {
3444         if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3445                 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3446         else
3447                 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3448 
3449         if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3450                 kvm_mmu_unload(&svm->vcpu);
3451                 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3452                 nested_svm_init_mmu_context(&svm->vcpu);
3453         }
3454 
3455         /* Load the nested guest state */
3456         svm->vmcb->save.es = nested_vmcb->save.es;
3457         svm->vmcb->save.cs = nested_vmcb->save.cs;
3458         svm->vmcb->save.ss = nested_vmcb->save.ss;
3459         svm->vmcb->save.ds = nested_vmcb->save.ds;
3460         svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3461         svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3462         kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3463         svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3464         svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3465         svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3466         if (npt_enabled) {
3467                 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3468                 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3469         } else
3470                 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3471 
3472         /* Guest paging mode is active - reset mmu */
3473         kvm_mmu_reset_context(&svm->vcpu);
3474 
3475         svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3476         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3477         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3478         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3479 
3480         /* In case we don't even reach vcpu_run, the fields are not updated */
3481         svm->vmcb->save.rax = nested_vmcb->save.rax;
3482         svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3483         svm->vmcb->save.rip = nested_vmcb->save.rip;
3484         svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3485         svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3486         svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3487 
3488         svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3489         svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
3490 
3491         /* cache intercepts */
3492         svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
3493         svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
3494         svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3495         svm->nested.intercept            = nested_vmcb->control.intercept;
3496 
3497         svm_flush_tlb(&svm->vcpu, true);
3498         svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3499         if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3500                 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3501         else
3502                 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3503 
3504         if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3505                 /* We only want the cr8 intercept bits of the guest */
3506                 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3507                 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3508         }
3509 
3510         /* We don't want to see VMMCALLs from a nested guest */
3511         clr_intercept(svm, INTERCEPT_VMMCALL);
3512 
3513         svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3514         svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3515 
3516         svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3517         svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3518         svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3519         svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3520         svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3521 
3522         nested_svm_unmap(page);
3523 
3524         /* Enter Guest-Mode */
3525         enter_guest_mode(&svm->vcpu);
3526 
3527         /*
3528          * Merge guest and host intercepts - must be called  with vcpu in
3529          * guest-mode to take affect here
3530          */
3531         recalc_intercepts(svm);
3532 
3533         svm->nested.vmcb = vmcb_gpa;
3534 
3535         enable_gif(svm);
3536 
3537         mark_all_dirty(svm->vmcb);
3538 }
3539 
3540 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3541 {
3542         struct vmcb *nested_vmcb;
3543         struct vmcb *hsave = svm->nested.hsave;
3544         struct vmcb *vmcb = svm->vmcb;
3545         struct page *page;
3546         u64 vmcb_gpa;
3547 
3548         vmcb_gpa = svm->vmcb->save.rax;
3549 
3550         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3551         if (!nested_vmcb)
3552                 return false;
3553 
3554         if (!nested_vmcb_checks(nested_vmcb)) {
3555                 nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
3556                 nested_vmcb->control.exit_code_hi = 0;
3557                 nested_vmcb->control.exit_info_1  = 0;
3558                 nested_vmcb->control.exit_info_2  = 0;
3559 
3560                 nested_svm_unmap(page);
3561 
3562                 return false;
3563         }
3564 
3565         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3566                                nested_vmcb->save.rip,
3567                                nested_vmcb->control.int_ctl,
3568                                nested_vmcb->control.event_inj,
3569                                nested_vmcb->control.nested_ctl);
3570 
3571         trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3572                                     nested_vmcb->control.intercept_cr >> 16,
3573                                     nested_vmcb->control.intercept_exceptions,
3574                                     nested_vmcb->control.intercept);
3575 
3576         /* Clear internal status */
3577         kvm_clear_exception_queue(&svm->vcpu);
3578         kvm_clear_interrupt_queue(&svm->vcpu);
3579 
3580         /*
3581          * Save the old vmcb, so we don't need to pick what we save, but can
3582          * restore everything when a VMEXIT occurs
3583          */
3584         hsave->save.es     = vmcb->save.es;
3585         hsave->save.cs     = vmcb->save.cs;
3586         hsave->save.ss     = vmcb->save.ss;
3587         hsave->save.ds     = vmcb->save.ds;
3588         hsave->save.gdtr   = vmcb->save.gdtr;
3589         hsave->save.idtr   = vmcb->save.idtr;
3590         hsave->save.efer   = svm->vcpu.arch.efer;
3591         hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
3592         hsave->save.cr4    = svm->vcpu.arch.cr4;
3593         hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3594         hsave->save.rip    = kvm_rip_read(&svm->vcpu);
3595         hsave->save.rsp    = vmcb->save.rsp;
3596         hsave->save.rax    = vmcb->save.rax;
3597         if (npt_enabled)
3598                 hsave->save.cr3    = vmcb->save.cr3;
3599         else
3600                 hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
3601 
3602         copy_vmcb_control_area(hsave, vmcb);
3603 
3604         enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3605 
3606         return true;
3607 }
3608 
3609 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3610 {
3611         to_vmcb->save.fs = from_vmcb->save.fs;
3612         to_vmcb->save.gs = from_vmcb->save.gs;
3613         to_vmcb->save.tr = from_vmcb->save.tr;
3614         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3615         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3616         to_vmcb->save.star = from_vmcb->save.star;
3617         to_vmcb->save.lstar = from_vmcb->save.lstar;
3618         to_vmcb->save.cstar = from_vmcb->save.cstar;
3619         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3620         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3621         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3622         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3623 }
3624 
3625 static int vmload_interception(struct vcpu_svm *svm)
3626 {
3627         struct vmcb *nested_vmcb;
3628         struct page *page;
3629         int ret;
3630 
3631         if (nested_svm_check_permissions(svm))
3632                 return 1;
3633 
3634         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3635         if (!nested_vmcb)
3636                 return 1;
3637 
3638         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3639         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3640 
3641         nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3642         nested_svm_unmap(page);
3643 
3644         return ret;
3645 }
3646 
3647 static int vmsave_interception(struct vcpu_svm *svm)
3648 {
3649         struct vmcb *nested_vmcb;
3650         struct page *page;
3651         int ret;
3652 
3653         if (nested_svm_check_permissions(svm))
3654                 return 1;
3655 
3656         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3657         if (!nested_vmcb)
3658                 return 1;
3659 
3660         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3661         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3662 
3663         nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3664         nested_svm_unmap(page);
3665 
3666         return ret;
3667 }
3668 
3669 static int vmrun_interception(struct vcpu_svm *svm)
3670 {
3671         if (nested_svm_check_permissions(svm))
3672                 return 1;
3673 
3674         /* Save rip after vmrun instruction */
3675         kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3676 
3677         if (!nested_svm_vmrun(svm))
3678                 return 1;
3679 
3680         if (!nested_svm_vmrun_msrpm(svm))
3681                 goto failed;
3682 
3683         return 1;
3684 
3685 failed:
3686 
3687         svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
3688         svm->vmcb->control.exit_code_hi = 0;
3689         svm->vmcb->control.exit_info_1  = 0;
3690         svm->vmcb->control.exit_info_2  = 0;
3691 
3692         nested_svm_vmexit(svm);
3693 
3694         return 1;
3695 }
3696 
3697 static int stgi_interception(struct vcpu_svm *svm)
3698 {
3699         int ret;
3700 
3701         if (nested_svm_check_permissions(svm))
3702                 return 1;
3703 
3704         /*
3705          * If VGIF is enabled, the STGI intercept is only added to
3706          * detect the opening of the SMI/NMI window; remove it now.
3707          */
3708         if (vgif_enabled(svm))
3709                 clr_intercept(svm, INTERCEPT_STGI);
3710 
3711         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3712         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3713         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3714 
3715         enable_gif(svm);
3716 
3717         return ret;
3718 }
3719 
3720 static int clgi_interception(struct vcpu_svm *svm)
3721 {
3722         int ret;
3723 
3724         if (nested_svm_check_permissions(svm))
3725                 return 1;
3726 
3727         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3728         ret = kvm_skip_emulated_instruction(&svm->vcpu);
3729 
3730         disable_gif(svm);
3731 
3732         /* After a CLGI no interrupts should come */
3733         if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3734                 svm_clear_vintr(svm);
3735                 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3736                 mark_dirty(svm->vmcb, VMCB_INTR);
3737         }
3738 
3739         return ret;
3740 }
3741 
3742 static int invlpga_interception(struct vcpu_svm *svm)
3743 {
3744         struct kvm_vcpu *vcpu = &svm->vcpu;
3745 
3746         trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3747                           kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3748 
3749         /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3750         kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3751 
3752         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3753         return kvm_skip_emulated_instruction(&svm->vcpu);
3754 }
3755 
3756 static int skinit_interception(struct vcpu_svm *svm)
3757 {
3758         trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3759 
3760         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3761         return 1;
3762 }
3763 
3764 static int wbinvd_interception(struct vcpu_svm *svm)
3765 {
3766         return kvm_emulate_wbinvd(&svm->vcpu);
3767 }
3768 
3769 static int xsetbv_interception(struct vcpu_svm *svm)
3770 {
3771         u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3772         u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3773 
3774         if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3775                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3776                 return kvm_skip_emulated_instruction(&svm->vcpu);
3777         }
3778 
3779         return 1;
3780 }
3781 
3782 static int task_switch_interception(struct vcpu_svm *svm)
3783 {
3784         u16 tss_selector;
3785         int reason;
3786         int int_type = svm->vmcb->control.exit_int_info &
3787                 SVM_EXITINTINFO_TYPE_MASK;
3788         int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3789         uint32_t type =
3790                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3791         uint32_t idt_v =
3792                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3793         bool has_error_code = false;
3794         u32 error_code = 0;
3795 
3796         tss_selector = (u16)svm->vmcb->control.exit_info_1;
3797 
3798         if (svm->vmcb->control.exit_info_2 &
3799             (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3800                 reason = TASK_SWITCH_IRET;
3801         else if (svm->vmcb->control.exit_info_2 &
3802                  (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3803                 reason = TASK_SWITCH_JMP;
3804         else if (idt_v)
3805                 reason = TASK_SWITCH_GATE;
3806         else
3807                 reason = TASK_SWITCH_CALL;
3808 
3809         if (reason == TASK_SWITCH_GATE) {
3810                 switch (type) {
3811                 case SVM_EXITINTINFO_TYPE_NMI:
3812                         svm->vcpu.arch.nmi_injected = false;
3813                         break;
3814                 case SVM_EXITINTINFO_TYPE_EXEPT:
3815                         if (svm->vmcb->control.exit_info_2 &
3816                             (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3817                                 has_error_code = true;
3818                                 error_code =
3819                                         (u32)svm->vmcb->control.exit_info_2;
3820                         }
3821                         kvm_clear_exception_queue(&svm->vcpu);
3822                         break;
3823                 case SVM_EXITINTINFO_TYPE_INTR:
3824                         kvm_clear_interrupt_queue(&svm->vcpu);
3825                         break;
3826                 default:
3827                         break;
3828                 }
3829         }
3830 
3831         if (reason != TASK_SWITCH_GATE ||
3832             int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3833             (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3834              (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3835                 skip_emulated_instruction(&svm->vcpu);
3836 
3837         if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3838                 int_vec = -1;
3839 
3840         if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3841                                 has_error_code, error_code) == EMULATE_FAIL) {
3842                 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3843                 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3844                 svm->vcpu.run->internal.ndata = 0;
3845                 return 0;
3846         }
3847         return 1;
3848 }
3849 
3850 static int cpuid_interception(struct vcpu_svm *svm)
3851 {
3852         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3853         return kvm_emulate_cpuid(&svm->vcpu);
3854 }
3855 
3856 static int iret_interception(struct vcpu_svm *svm)
3857 {
3858         ++svm->vcpu.stat.nmi_window_exits;
3859         clr_intercept(svm, INTERCEPT_IRET);
3860         svm->vcpu.arch.hflags |= HF_IRET_MASK;
3861         svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3862         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3863         return 1;
3864 }
3865 
3866 static int invlpg_interception(struct vcpu_svm *svm)
3867 {
3868         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3869                 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3870 
3871         kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3872         return kvm_skip_emulated_instruction(&svm->vcpu);
3873 }
3874 
3875 static int emulate_on_interception(struct vcpu_svm *svm)
3876 {
3877         return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3878 }
3879 
3880 static int rsm_interception(struct vcpu_svm *svm)
3881 {
3882         return kvm_emulate_instruction_from_buffer(&svm->vcpu,
3883                                         rsm_ins_bytes, 2) == EMULATE_DONE;
3884 }
3885 
3886 static int rdpmc_interception(struct vcpu_svm *svm)
3887 {
3888         int err;
3889 
3890         if (!static_cpu_has(X86_FEATURE_NRIPS))
3891                 return emulate_on_interception(svm);
3892 
3893         err = kvm_rdpmc(&svm->vcpu);
3894         return kvm_complete_insn_gp(&svm->vcpu, err);
3895 }
3896 
3897 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3898                                             unsigned long val)
3899 {
3900         unsigned long cr0 = svm->vcpu.arch.cr0;
3901         bool ret = false;
3902         u64 intercept;
3903 
3904         intercept = svm->nested.intercept;
3905 
3906         if (!is_guest_mode(&svm->vcpu) ||
3907             (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3908                 return false;
3909 
3910         cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3911         val &= ~SVM_CR0_SELECTIVE_MASK;
3912 
3913         if (cr0 ^ val) {
3914                 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3915                 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3916         }
3917 
3918         return ret;
3919 }
3920 
3921 #define CR_VALID (1ULL << 63)
3922 
3923 static int cr_interception(struct vcpu_svm *svm)
3924 {
3925         int reg, cr;
3926         unsigned long val;
3927         int err;
3928 
3929         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3930                 return emulate_on_interception(svm);
3931 
3932         if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3933                 return emulate_on_interception(svm);
3934 
3935         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3936         if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3937                 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3938         else
3939                 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3940 
3941         err = 0;
3942         if (cr >= 16) { /* mov to cr */
3943                 cr -= 16;
3944                 val = kvm_register_read(&svm->vcpu, reg);
3945                 switch (cr) {
3946                 case 0:
3947                         if (!check_selective_cr0_intercepted(svm, val))
3948                                 err = kvm_set_cr0(&svm->vcpu, val);
3949                         else
3950                                 return 1;
3951 
3952                         break;
3953                 case 3:
3954                         err = kvm_set_cr3(&svm->vcpu, val);
3955                         break;
3956                 case 4:
3957                         err = kvm_set_cr4(&svm->vcpu, val);
3958                         break;
3959                 case 8:
3960                         err = kvm_set_cr8(&svm->vcpu, val);
3961                         break;
3962                 default:
3963                         WARN(1, "unhandled write to CR%d", cr);
3964                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3965                         return 1;
3966                 }
3967         } else { /* mov from cr */
3968                 switch (cr) {
3969                 case 0:
3970                         val = kvm_read_cr0(&svm->vcpu);
3971                         break;
3972                 case 2:
3973                         val = svm->vcpu.arch.cr2;
3974                         break;
3975                 case 3:
3976                         val = kvm_read_cr3(&svm->vcpu);
3977                         break;
3978                 case 4:
3979                         val = kvm_read_cr4(&svm->vcpu);
3980                         break;
3981                 case 8:
3982                         val = kvm_get_cr8(&svm->vcpu);
3983                         break;
3984                 default:
3985                         WARN(1, "unhandled read from CR%d", cr);
3986                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3987                         return 1;
3988                 }
3989                 kvm_register_write(&svm->vcpu, reg, val);
3990         }
3991         return kvm_complete_insn_gp(&svm->vcpu, err);
3992 }
3993 
3994 static int dr_interception(struct vcpu_svm *svm)
3995 {
3996         int reg, dr;
3997         unsigned long val;
3998 
3999         if (svm->vcpu.guest_debug == 0) {
4000                 /*
4001                  * No more DR vmexits; force a reload of the debug registers
4002                  * and reenter on this instruction.  The next vmexit will
4003                  * retrieve the full state of the debug registers.
4004                  */
4005                 clr_dr_intercepts(svm);
4006                 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4007                 return 1;
4008         }
4009 
4010         if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4011                 return emulate_on_interception(svm);
4012 
4013         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4014         dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4015 
4016         if (dr >= 16) { /* mov to DRn */
4017                 if (!kvm_require_dr(&svm->vcpu, dr - 16))
4018                         return 1;
4019                 val = kvm_register_read(&svm->vcpu, reg);
4020                 kvm_set_dr(&svm->vcpu, dr - 16, val);
4021         } else {
4022                 if (!kvm_require_dr(&svm->vcpu, dr))
4023                         return 1;
4024                 kvm_get_dr(&svm->vcpu, dr, &val);
4025                 kvm_register_write(&svm->vcpu, reg, val);
4026         }
4027 
4028         return kvm_skip_emulated_instruction(&svm->vcpu);
4029 }
4030 
4031 static int cr8_write_interception(struct vcpu_svm *svm)
4032 {
4033         struct kvm_run *kvm_run = svm->vcpu.run;
4034         int r;
4035 
4036         u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4037         /* instruction emulation calls kvm_set_cr8() */
4038         r = cr_interception(svm);
4039         if (lapic_in_kernel(&svm->vcpu))
4040                 return r;
4041         if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4042                 return r;
4043         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4044         return 0;
4045 }
4046 
4047 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4048 {
4049         msr->data = 0;
4050 
4051         switch (msr->index) {
4052         case MSR_F10H_DECFG:
4053                 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4054                         msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4055                 break;
4056         default:
4057                 return 1;
4058         }
4059 
4060         return 0;
4061 }
4062 
4063 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4064 {
4065         struct vcpu_svm *svm = to_svm(vcpu);
4066 
4067         switch (msr_info->index) {
4068         case MSR_STAR:
4069                 msr_info->data = svm->vmcb->save.star;
4070                 break;
4071 #ifdef CONFIG_X86_64
4072         case MSR_LSTAR:
4073                 msr_info->data = svm->vmcb->save.lstar;
4074                 break;
4075         case MSR_CSTAR:
4076                 msr_info->data = svm->vmcb->save.cstar;
4077                 break;
4078         case MSR_KERNEL_GS_BASE:
4079                 msr_info->data = svm->vmcb->save.kernel_gs_base;
4080                 break;
4081         case MSR_SYSCALL_MASK:
4082                 msr_info->data = svm->vmcb->save.sfmask;
4083                 break;
4084 #endif
4085         case MSR_IA32_SYSENTER_CS:
4086                 msr_info->data = svm->vmcb->save.sysenter_cs;
4087                 break;
4088         case MSR_IA32_SYSENTER_EIP:
4089                 msr_info->data = svm->sysenter_eip;
4090                 break;
4091         case MSR_IA32_SYSENTER_ESP:
4092                 msr_info->data = svm->sysenter_esp;
4093                 break;
4094         case MSR_TSC_AUX:
4095                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4096                         return 1;
4097                 msr_info->data = svm->tsc_aux;
4098                 break;
4099         /*
4100          * Nobody will change the following 5 values in the VMCB so we can
4101          * safely return them on rdmsr. They will always be 0 until LBRV is
4102          * implemented.
4103          */
4104         case MSR_IA32_DEBUGCTLMSR:
4105                 msr_info->data = svm->vmcb->save.dbgctl;
4106                 break;
4107         case MSR_IA32_LASTBRANCHFROMIP:
4108                 msr_info->data = svm->vmcb->save.br_from;
4109                 break;
4110         case MSR_IA32_LASTBRANCHTOIP:
4111                 msr_info->data = svm->vmcb->save.br_to;
4112                 break;
4113         case MSR_IA32_LASTINTFROMIP:
4114                 msr_info->data = svm->vmcb->save.last_excp_from;
4115                 break;
4116         case MSR_IA32_LASTINTTOIP:
4117                 msr_info->data = svm->vmcb->save.last_excp_to;
4118                 break;
4119         case MSR_VM_HSAVE_PA:
4120                 msr_info->data = svm->nested.hsave_msr;
4121                 break;
4122         case MSR_VM_CR:
4123                 msr_info->data = svm->nested.vm_cr_msr;
4124                 break;
4125         case MSR_IA32_SPEC_CTRL:
4126                 if (!msr_info->host_initiated &&
4127                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4128                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4129                         return 1;
4130 
4131                 msr_info->data = svm->spec_ctrl;
4132                 break;
4133         case MSR_AMD64_VIRT_SPEC_CTRL:
4134                 if (!msr_info->host_initiated &&
4135                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4136                         return 1;
4137 
4138                 msr_info->data = svm->virt_spec_ctrl;
4139                 break;
4140         case MSR_F15H_IC_CFG: {
4141 
4142                 int family, model;
4143 
4144                 family = guest_cpuid_family(vcpu);
4145                 model  = guest_cpuid_model(vcpu);
4146 
4147                 if (family < 0 || model < 0)
4148                         return kvm_get_msr_common(vcpu, msr_info);
4149 
4150                 msr_info->data = 0;
4151 
4152                 if (family == 0x15 &&
4153                     (model >= 0x2 && model < 0x20))
4154                         msr_info->data = 0x1E;
4155                 }
4156                 break;
4157         case MSR_F10H_DECFG:
4158                 msr_info->data = svm->msr_decfg;
4159                 break;
4160         default:
4161                 return kvm_get_msr_common(vcpu, msr_info);
4162         }
4163         return 0;
4164 }
4165 
4166 static int rdmsr_interception(struct vcpu_svm *svm)
4167 {
4168         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4169         struct msr_data msr_info;
4170 
4171         msr_info.index = ecx;
4172         msr_info.host_initiated = false;
4173         if (svm_get_msr(&svm->vcpu, &msr_info)) {
4174                 trace_kvm_msr_read_ex(ecx);
4175                 kvm_inject_gp(&svm->vcpu, 0);
4176                 return 1;
4177         } else {
4178                 trace_kvm_msr_read(ecx, msr_info.data);
4179 
4180                 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
4181                                    msr_info.data & 0xffffffff);
4182                 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
4183                                    msr_info.data >> 32);
4184                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4185                 return kvm_skip_emulated_instruction(&svm->vcpu);
4186         }
4187 }
4188 
4189 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4190 {
4191         struct vcpu_svm *svm = to_svm(vcpu);
4192         int svm_dis, chg_mask;
4193 
4194         if (data & ~SVM_VM_CR_VALID_MASK)
4195                 return 1;
4196 
4197         chg_mask = SVM_VM_CR_VALID_MASK;
4198 
4199         if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4200                 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4201 
4202         svm->nested.vm_cr_msr &= ~chg_mask;
4203         svm->nested.vm_cr_msr |= (data & chg_mask);
4204 
4205         svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4206 
4207         /* check for svm_disable while efer.svme is set */
4208         if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4209                 return 1;
4210 
4211         return 0;
4212 }
4213 
4214 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4215 {
4216         struct vcpu_svm *svm = to_svm(vcpu);
4217 
4218         u32 ecx = msr->index;
4219         u64 data = msr->data;
4220         switch (ecx) {
4221         case MSR_IA32_CR_PAT:
4222                 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4223                         return 1;
4224                 vcpu->arch.pat = data;
4225                 svm->vmcb->save.g_pat = data;
4226                 mark_dirty(svm->vmcb, VMCB_NPT);
4227                 break;
4228         case MSR_IA32_SPEC_CTRL:
4229                 if (!msr->host_initiated &&
4230                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4231                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4232                         return 1;
4233 
4234                 /* The STIBP bit doesn't fault even if it's not advertised */
4235                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4236                         return 1;
4237 
4238                 svm->spec_ctrl = data;
4239 
4240                 if (!data)
4241                         break;
4242 
4243                 /*
4244                  * For non-nested:
4245                  * When it's written (to non-zero) for the first time, pass
4246                  * it through.
4247                  *
4248                  * For nested:
4249                  * The handling of the MSR bitmap for L2 guests is done in
4250                  * nested_svm_vmrun_msrpm.
4251                  * We update the L1 MSR bit as well since it will end up
4252                  * touching the MSR anyway now.
4253                  */
4254                 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4255                 break;
4256         case MSR_IA32_PRED_CMD:
4257                 if (!msr->host_initiated &&
4258                     !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4259                         return 1;
4260 
4261                 if (data & ~PRED_CMD_IBPB)
4262                         return 1;
4263 
4264                 if (!data)
4265                         break;
4266 
4267                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4268                 if (is_guest_mode(vcpu))
4269                         break;
4270                 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4271                 break;
4272         case MSR_AMD64_VIRT_SPEC_CTRL:
4273                 if (!msr->host_initiated &&
4274                     !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4275                         return 1;
4276 
4277                 if (data & ~SPEC_CTRL_SSBD)
4278                         return 1;
4279 
4280                 svm->virt_spec_ctrl = data;
4281                 break;
4282         case MSR_STAR:
4283                 svm->vmcb->save.star = data;
4284                 break;
4285 #ifdef CONFIG_X86_64
4286         case MSR_LSTAR:
4287                 svm->vmcb->save.lstar = data;
4288                 break;
4289         case MSR_CSTAR:
4290                 svm->vmcb->save.cstar = data;
4291                 break;
4292         case MSR_KERNEL_GS_BASE:
4293                 svm->vmcb->save.kernel_gs_base = data;
4294                 break;
4295         case MSR_SYSCALL_MASK:
4296                 svm->vmcb->save.sfmask = data;
4297                 break;
4298 #endif
4299         case MSR_IA32_SYSENTER_CS:
4300                 svm->vmcb->save.sysenter_cs = data;
4301                 break;
4302         case MSR_IA32_SYSENTER_EIP:
4303                 svm->sysenter_eip = data;
4304                 svm->vmcb->save.sysenter_eip = data;
4305                 break;
4306         case MSR_IA32_SYSENTER_ESP:
4307                 svm->sysenter_esp = data;
4308                 svm->vmcb->save.sysenter_esp = data;
4309                 break;
4310         case MSR_TSC_AUX:
4311                 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4312                         return 1;
4313 
4314                 /*
4315                  * This is rare, so we update the MSR here instead of using
4316                  * direct_access_msrs.  Doing that would require a rdmsr in
4317                  * svm_vcpu_put.
4318                  */
4319                 svm->tsc_aux = data;
4320                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4321                 break;
4322         case MSR_IA32_DEBUGCTLMSR:
4323                 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4324                         vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4325                                     __func__, data);
4326                         break;
4327                 }
4328                 if (data & DEBUGCTL_RESERVED_BITS)
4329                         return 1;
4330 
4331                 svm->vmcb->save.dbgctl = data;
4332                 mark_dirty(svm->vmcb, VMCB_LBR);
4333                 if (data & (1ULL<<0))
4334                         svm_enable_lbrv(svm);
4335                 else
4336                         svm_disable_lbrv(svm);
4337                 break;
4338         case MSR_VM_HSAVE_PA:
4339                 svm->nested.hsave_msr = data;
4340                 break;
4341         case MSR_VM_CR:
4342                 return svm_set_vm_cr(vcpu, data);
4343         case MSR_VM_IGNNE:
4344                 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4345                 break;
4346         case MSR_F10H_DECFG: {
4347                 struct kvm_msr_entry msr_entry;
4348 
4349                 msr_entry.index = msr->index;
4350                 if (svm_get_msr_feature(&msr_entry))
4351                         return 1;
4352 
4353                 /* Check the supported bits */
4354                 if (data & ~msr_entry.data)
4355                         return 1;
4356 
4357                 /* Don't allow the guest to change a bit, #GP */
4358                 if (!msr->host_initiated && (data ^ msr_entry.data))
4359                         return 1;
4360 
4361                 svm->msr_decfg = data;
4362                 break;
4363         }
4364         case MSR_IA32_APICBASE:
4365                 if (kvm_vcpu_apicv_active(vcpu))
4366                         avic_update_vapic_bar(to_svm(vcpu), data);
4367                 /* Follow through */
4368         default:
4369                 return kvm_set_msr_common(vcpu, msr);
4370         }
4371         return 0;
4372 }
4373 
4374 static int wrmsr_interception(struct vcpu_svm *svm)
4375 {
4376         struct msr_data msr;
4377         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4378         u64 data = kvm_read_edx_eax(&svm->vcpu);
4379 
4380         msr.data = data;
4381         msr.index = ecx;
4382         msr.host_initiated = false;
4383 
4384         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4385         if (kvm_set_msr(&svm->vcpu, &msr)) {
4386                 trace_kvm_msr_write_ex(ecx, data);
4387                 kvm_inject_gp(&svm->vcpu, 0);
4388                 return 1;
4389         } else {
4390                 trace_kvm_msr_write(ecx, data);
4391                 return kvm_skip_emulated_instruction(&svm->vcpu);
4392         }
4393 }
4394 
4395 static int msr_interception(struct vcpu_svm *svm)
4396 {
4397         if (svm->vmcb->control.exit_info_1)
4398                 return wrmsr_interception(svm);
4399         else
4400                 return rdmsr_interception(svm);
4401 }
4402 
4403 static int interrupt_window_interception(struct vcpu_svm *svm)
4404 {
4405         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4406         svm_clear_vintr(svm);
4407         svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4408         mark_dirty(svm->vmcb, VMCB_INTR);
4409         ++svm->vcpu.stat.irq_window_exits;
4410         return 1;
4411 }
4412 
4413 static int pause_interception(struct vcpu_svm *svm)
4414 {
4415         struct kvm_vcpu *vcpu = &svm->vcpu;
4416         bool in_kernel = (svm_get_cpl(vcpu) == 0);
4417 
4418         if (pause_filter_thresh)
4419                 grow_ple_window(vcpu);
4420 
4421         kvm_vcpu_on_spin(vcpu, in_kernel);
4422         return 1;
4423 }
4424 
4425 static int nop_interception(struct vcpu_svm *svm)
4426 {
4427         return kvm_skip_emulated_instruction(&(svm->vcpu));
4428 }
4429 
4430 static int monitor_interception(struct vcpu_svm *svm)
4431 {
4432         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4433         return nop_interception(svm);
4434 }
4435 
4436 static int mwait_interception(struct vcpu_svm *svm)
4437 {
4438         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4439         return nop_interception(svm);
4440 }
4441 
4442 enum avic_ipi_failure_cause {
4443         AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4444         AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4445         AVIC_IPI_FAILURE_INVALID_TARGET,
4446         AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4447 };
4448 
4449 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4450 {
4451         u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4452         u32 icrl = svm->vmcb->control.exit_info_1;
4453         u32 id = svm->vmcb->control.exit_info_2 >> 32;
4454         u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4455         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4456 
4457         trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4458 
4459         switch (id) {
4460         case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4461                 /*
4462                  * AVIC hardware handles the generation of
4463                  * IPIs when the specified Message Type is Fixed
4464                  * (also known as fixed delivery mode) and
4465                  * the Trigger Mode is edge-triggered. The hardware
4466                  * also supports self and broadcast delivery modes
4467                  * specified via the Destination Shorthand(DSH)
4468                  * field of the ICRL. Logical and physical APIC ID
4469                  * formats are supported. All other IPI types cause
4470                  * a #VMEXIT, which needs to emulated.
4471                  */
4472                 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4473                 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4474                 break;
4475         case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4476                 int i;
4477                 struct kvm_vcpu *vcpu;
4478                 struct kvm *kvm = svm->vcpu.kvm;
4479                 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4480 
4481                 /*
4482                  * At this point, we expect that the AVIC HW has already
4483                  * set the appropriate IRR bits on the valid target
4484                  * vcpus. So, we just need to kick the appropriate vcpu.
4485                  */
4486                 kvm_for_each_vcpu(i, vcpu, kvm) {
4487                         bool m = kvm_apic_match_dest(vcpu, apic,
4488                                                      icrl & KVM_APIC_SHORT_MASK,
4489                                                      GET_APIC_DEST_FIELD(icrh),
4490                                                      icrl & KVM_APIC_DEST_MASK);
4491 
4492                         if (m && !avic_vcpu_is_running(vcpu))
4493                                 kvm_vcpu_wake_up(vcpu);
4494                 }
4495                 break;
4496         }
4497         case AVIC_IPI_FAILURE_INVALID_TARGET:
4498                 break;
4499         case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4500                 WARN_ONCE(1, "Invalid backing page\n");
4501                 break;
4502         default:
4503                 pr_err("Unknown IPI interception\n");
4504         }
4505 
4506         return 1;
4507 }
4508 
4509 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4510 {
4511         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4512         int index;
4513         u32 *logical_apic_id_table;
4514         int dlid = GET_APIC_LOGICAL_ID(ldr);
4515 
4516         if (!dlid)
4517                 return NULL;
4518 
4519         if (flat) { /* flat */
4520                 index = ffs(dlid) - 1;
4521                 if (index > 7)
4522                         return NULL;
4523         } else { /* cluster */
4524                 int cluster = (dlid & 0xf0) >> 4;
4525                 int apic = ffs(dlid & 0x0f) - 1;
4526 
4527                 if ((apic < 0) || (apic > 7) ||
4528                     (cluster >= 0xf))
4529                         return NULL;
4530                 index = (cluster << 2) + apic;
4531         }
4532 
4533         logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4534 
4535         return &logical_apic_id_table[index];
4536 }
4537 
4538 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4539                           bool valid)
4540 {
4541         bool flat;
4542         u32 *entry, new_entry;
4543 
4544         flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4545         entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4546         if (!entry)
4547                 return -EINVAL;
4548 
4549         new_entry = READ_ONCE(*entry);
4550         new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4551         new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4552         if (valid)
4553                 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4554         else
4555                 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4556         WRITE_ONCE(*entry, new_entry);
4557 
4558         return 0;
4559 }
4560 
4561 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4562 {
4563         int ret;
4564         struct vcpu_svm *svm = to_svm(vcpu);
4565         u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4566 
4567         if (!ldr)
4568                 return 1;
4569 
4570         ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4571         if (ret && svm->ldr_reg) {
4572                 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4573                 svm->ldr_reg = 0;
4574         } else {
4575                 svm->ldr_reg = ldr;
4576         }
4577         return ret;
4578 }
4579 
4580 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4581 {
4582         u64 *old, *new;
4583         struct vcpu_svm *svm = to_svm(vcpu);
4584         u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4585         u32 id = (apic_id_reg >> 24) & 0xff;
4586 
4587         if (vcpu->vcpu_id == id)
4588                 return 0;
4589 
4590         old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4591         new = avic_get_physical_id_entry(vcpu, id);
4592         if (!new || !old)
4593                 return 1;
4594 
4595         /* We need to move physical_id_entry to new offset */
4596         *new = *old;
4597         *old = 0ULL;
4598         to_svm(vcpu)->avic_physical_id_cache = new;
4599 
4600         /*
4601          * Also update the guest physical APIC ID in the logical
4602          * APIC ID table entry if already setup the LDR.
4603          */
4604         if (svm->ldr_reg)
4605                 avic_handle_ldr_update(vcpu);
4606 
4607         return 0;
4608 }
4609 
4610 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4611 {
4612         struct vcpu_svm *svm = to_svm(vcpu);
4613         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4614         u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4615         u32 mod = (dfr >> 28) & 0xf;
4616 
4617         /*
4618          * We assume that all local APICs are using the same type.
4619          * If this changes, we need to flush the AVIC logical
4620          * APID id table.
4621          */
4622         if (kvm_svm->ldr_mode == mod)
4623                 return 0;
4624 
4625         clear_page(page_address(kvm_svm->avic_logical_id_table_page));
4626         kvm_svm->ldr_mode = mod;
4627 
4628         if (svm->ldr_reg)
4629                 avic_handle_ldr_update(vcpu);
4630         return 0;
4631 }
4632 
4633 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4634 {
4635         struct kvm_lapic *apic = svm->vcpu.arch.apic;
4636         u32 offset = svm->vmcb->control.exit_info_1 &
4637                                 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4638 
4639         switch (offset) {
4640         case APIC_ID:
4641                 if (avic_handle_apic_id_update(&svm->vcpu))
4642                         return 0;
4643                 break;
4644         case APIC_LDR:
4645                 if (avic_handle_ldr_update(&svm->vcpu))
4646                         return 0;
4647                 break;
4648         case APIC_DFR:
4649                 avic_handle_dfr_update(&svm->vcpu);
4650                 break;
4651         default:
4652                 break;
4653         }
4654 
4655         kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4656 
4657         return 1;
4658 }
4659 
4660 static bool is_avic_unaccelerated_access_trap(u32 offset)
4661 {
4662         bool ret = false;
4663 
4664         switch (offset) {
4665         case APIC_ID:
4666         case APIC_EOI:
4667         case APIC_RRR:
4668         case APIC_LDR:
4669         case APIC_DFR:
4670         case APIC_SPIV:
4671         case APIC_ESR:
4672         case APIC_ICR:
4673         case APIC_LVTT:
4674         case APIC_LVTTHMR:
4675         case APIC_LVTPC:
4676         case APIC_LVT0:
4677         case APIC_LVT1:
4678         case APIC_LVTERR:
4679         case APIC_TMICT:
4680         case APIC_TDCR:
4681                 ret = true;
4682                 break;
4683         default:
4684                 break;
4685         }
4686         return ret;
4687 }
4688 
4689 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4690 {
4691         int ret = 0;
4692         u32 offset = svm->vmcb->control.exit_info_1 &
4693                      AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4694         u32 vector = svm->vmcb->control.exit_info_2 &
4695                      AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4696         bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4697                      AVIC_UNACCEL_ACCESS_WRITE_MASK;
4698         bool trap = is_avic_unaccelerated_access_trap(offset);
4699 
4700         trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4701                                             trap, write, vector);
4702         if (trap) {
4703                 /* Handling Trap */
4704                 WARN_ONCE(!write, "svm: Handling trap read.\n");
4705                 ret = avic_unaccel_trap_write(svm);
4706         } else {
4707                 /* Handling Fault */
4708                 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4709         }
4710 
4711         return ret;
4712 }
4713 
4714 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4715         [SVM_EXIT_READ_CR0]                     = cr_interception,
4716         [SVM_EXIT_READ_CR3]                     = cr_interception,
4717         [SVM_EXIT_READ_CR4]                     = cr_interception,
4718         [SVM_EXIT_READ_CR8]                     = cr_interception,
4719         [SVM_EXIT_CR0_SEL_WRITE]                = cr_interception,
4720         [SVM_EXIT_WRITE_CR0]                    = cr_interception,
4721         [SVM_EXIT_WRITE_CR3]                    = cr_interception,
4722         [SVM_EXIT_WRITE_CR4]                    = cr_interception,
4723         [SVM_EXIT_WRITE_CR8]                    = cr8_write_interception,
4724         [SVM_EXIT_READ_DR0]                     = dr_interception,
4725         [SVM_EXIT_READ_DR1]                     = dr_interception,
4726         [SVM_EXIT_READ_DR2]                     = dr_interception,
4727         [SVM_EXIT_READ_DR3]                     = dr_interception,
4728         [SVM_EXIT_READ_DR4]                     = dr_interception,
4729         [SVM_EXIT_READ_DR5]                     = dr_interception,
4730         [SVM_EXIT_READ_DR6]                     = dr_interception,
4731         [SVM_EXIT_READ_DR7]                     = dr_interception,
4732         [SVM_EXIT_WRITE_DR0]                    = dr_interception,
4733         [SVM_EXIT_WRITE_DR1]                    = dr_interception,
4734         [SVM_EXIT_WRITE_DR2]                    = dr_interception,
4735         [SVM_EXIT_WRITE_DR3]                    = dr_interception,
4736         [SVM_EXIT_WRITE_DR4]                    = dr_interception,
4737         [SVM_EXIT_WRITE_DR5]                    = dr_interception,
4738         [SVM_EXIT_WRITE_DR6]                    = dr_interception,
4739         [SVM_EXIT_WRITE_DR7]                    = dr_interception,
4740         [SVM_EXIT_EXCP_BASE + DB_VECTOR]        = db_interception,
4741         [SVM_EXIT_EXCP_BASE + BP_VECTOR]        = bp_interception,
4742         [SVM_EXIT_EXCP_BASE + UD_VECTOR]        = ud_interception,
4743         [SVM_EXIT_EXCP_BASE + PF_VECTOR]        = pf_interception,
4744         [SVM_EXIT_EXCP_BASE + MC_VECTOR]        = mc_interception,
4745         [SVM_EXIT_EXCP_BASE + AC_VECTOR]        = ac_interception,
4746         [SVM_EXIT_EXCP_BASE + GP_VECTOR]        = gp_interception,
4747         [SVM_EXIT_INTR]                         = intr_interception,
4748         [SVM_EXIT_NMI]                          = nmi_interception,
4749         [SVM_EXIT_SMI]                          = nop_on_interception,
4750         [SVM_EXIT_INIT]                         = nop_on_interception,
4751         [SVM_EXIT_VINTR]                        = interrupt_window_interception,
4752         [SVM_EXIT_RDPMC]                        = rdpmc_interception,
4753         [SVM_EXIT_CPUID]                        = cpuid_interception,
4754         [SVM_EXIT_IRET]                         = iret_interception,
4755         [SVM_EXIT_INVD]                         = emulate_on_interception,
4756         [SVM_EXIT_PAUSE]                        = pause_interception,
4757         [SVM_EXIT_HLT]                          = halt_interception,
4758         [SVM_EXIT_INVLPG]                       = invlpg_interception,
4759         [SVM_EXIT_INVLPGA]                      = invlpga_interception,
4760         [SVM_EXIT_IOIO]                         = io_interception,
4761         [SVM_EXIT_MSR]                          = msr_interception,
4762         [SVM_EXIT_TASK_SWITCH]                  = task_switch_interception,
4763         [SVM_EXIT_SHUTDOWN]                     = shutdown_interception,
4764         [SVM_EXIT_VMRUN]                        = vmrun_interception,
4765         [SVM_EXIT_VMMCALL]                      = vmmcall_interception,
4766         [SVM_EXIT_VMLOAD]                       = vmload_interception,
4767         [SVM_EXIT_VMSAVE]                       = vmsave_interception,
4768         [SVM_EXIT_STGI]                         = stgi_interception,
4769         [SVM_EXIT_CLGI]                         = clgi_interception,
4770         [SVM_EXIT_SKINIT]                       = skinit_interception,
4771         [SVM_EXIT_WBINVD]                       = wbinvd_interception,
4772         [SVM_EXIT_MONITOR]                      = monitor_interception,
4773         [SVM_EXIT_MWAIT]                        = mwait_interception,
4774         [SVM_EXIT_XSETBV]                       = xsetbv_interception,
4775         [SVM_EXIT_NPF]                          = npf_interception,
4776         [SVM_EXIT_RSM]                          = rsm_interception,
4777         [SVM_EXIT_AVIC_INCOMPLETE_IPI]          = avic_incomplete_ipi_interception,
4778         [SVM_EXIT_AVIC_UNACCELERATED_ACCESS]    = avic_unaccelerated_access_interception,
4779 };
4780 
4781 static void dump_vmcb(struct kvm_vcpu *vcpu)
4782 {
4783         struct vcpu_svm *svm = to_svm(vcpu);
4784         struct vmcb_control_area *control = &svm->vmcb->control;
4785         struct vmcb_save_area *save = &svm->vmcb->save;
4786 
4787         pr_err("VMCB Control Area:\n");
4788         pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4789         pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4790         pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4791         pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4792         pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4793         pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4794         pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4795         pr_err("%-20s%d\n", "pause filter threshold:",
4796                control->pause_filter_thresh);
4797         pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4798         pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4799         pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4800         pr_err("%-20s%d\n", "asid:", control->asid);
4801         pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4802         pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4803         pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4804         pr_err("%-20s%08x\n", "int_state:", control->int_state);
4805         pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4806         pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4807         pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4808         pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4809         pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4810         pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4811         pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4812         pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4813         pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4814         pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4815         pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4816         pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4817         pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4818         pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4819         pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4820         pr_err("VMCB State Save Area:\n");
4821         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4822                "es:",
4823                save->es.selector, save->es.attrib,
4824                save->es.limit, save->es.base);
4825         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4826                "cs:",
4827                save->cs.selector, save->cs.attrib,
4828                save->cs.limit, save->cs.base);
4829         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4830                "ss:",
4831                save->ss.selector, save->ss.attrib,
4832                save->ss.limit, save->ss.base);
4833         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4834                "ds:",
4835                save->ds.selector, save->ds.attrib,
4836                save->ds.limit, save->ds.base);
4837         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4838                "fs:",
4839                save->fs.selector, save->fs.attrib,
4840                save->fs.limit, save->fs.base);
4841         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4842                "gs:",
4843                save->gs.selector, save->gs.attrib,
4844                save->gs.limit, save->gs.base);
4845         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4846                "gdtr:",
4847                save->gdtr.selector, save->gdtr.attrib,
4848                save->gdtr.limit, save->gdtr.base);
4849         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4850                "ldtr:",
4851                save->ldtr.selector, save->ldtr.attrib,
4852                save->ldtr.limit, save->ldtr.base);
4853         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4854                "idtr:",
4855                save->idtr.selector, save->idtr.attrib,
4856                save->idtr.limit, save->idtr.base);
4857         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4858                "tr:",
4859                save->tr.selector, save->tr.attrib,
4860                save->tr.limit, save->tr.base);
4861         pr_err("cpl:            %d                efer:         %016llx\n",
4862                 save->cpl, save->efer);
4863         pr_err("%-15s %016llx %-13s %016llx\n",
4864                "cr0:", save->cr0, "cr2:", save->cr2);
4865         pr_err("%-15s %016llx %-13s %016llx\n",
4866                "cr3:", save->cr3, "cr4:", save->cr4);
4867         pr_err("%-15s %016llx %-13s %016llx\n",
4868                "dr6:", save->dr6, "dr7:", save->dr7);
4869         pr_err("%-15s %016llx %-13s %016llx\n",
4870                "rip:", save->rip, "rflags:", save->rflags);
4871         pr_err("%-15s %016llx %-13s %016llx\n",
4872                "rsp:", save->rsp, "rax:", save->rax);
4873         pr_err("%-15s %016llx %-13s %016llx\n",
4874                "star:", save->star, "lstar:", save->lstar);
4875         pr_err("%-15s %016llx %-13s %016llx\n",
4876                "cstar:", save->cstar, "sfmask:", save->sfmask);
4877         pr_err("%-15s %016llx %-13s %016llx\n",
4878                "kernel_gs_base:", save->kernel_gs_base,
4879                "sysenter_cs:", save->sysenter_cs);
4880         pr_err("%-15s %016llx %-13s %016llx\n",
4881                "sysenter_esp:", save->sysenter_esp,
4882                "sysenter_eip:", save->sysenter_eip);
4883         pr_err("%-15s %016llx %-13s %016llx\n",
4884                "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4885         pr_err("%-15s %016llx %-13s %016llx\n",
4886                "br_from:", save->br_from, "br_to:", save->br_to);
4887         pr_err("%-15s %016llx %-13s %016llx\n",
4888                "excp_from:", save->last_excp_from,
4889                "excp_to:", save->last_excp_to);
4890 }
4891 
4892 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4893 {
4894         struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4895 
4896         *info1 = control->exit_info_1;
4897         *info2 = control->exit_info_2;
4898 }
4899 
4900 static int handle_exit(struct kvm_vcpu *vcpu)
4901 {
4902         struct vcpu_svm *svm = to_svm(vcpu);
4903         struct kvm_run *kvm_run = vcpu->run;
4904         u32 exit_code = svm->vmcb->control.exit_code;
4905 
4906         trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4907 
4908         if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4909                 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4910         if (npt_enabled)
4911                 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4912 
4913         if (unlikely(svm->nested.exit_required)) {
4914                 nested_svm_vmexit(svm);
4915                 svm->nested.exit_required = false;
4916 
4917                 return 1;
4918         }
4919 
4920         if (is_guest_mode(vcpu)) {
4921                 int vmexit;
4922 
4923                 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4924                                         svm->vmcb->control.exit_info_1,
4925                                         svm->vmcb->control.exit_info_2,
4926                                         svm->vmcb->control.exit_int_info,
4927                                         svm->vmcb->control.exit_int_info_err,
4928                                         KVM_ISA_SVM);
4929 
4930                 vmexit = nested_svm_exit_special(svm);
4931 
4932                 if (vmexit == NESTED_EXIT_CONTINUE)
4933                         vmexit = nested_svm_exit_handled(svm);
4934 
4935                 if (vmexit == NESTED_EXIT_DONE)
4936                         return 1;
4937         }
4938 
4939         svm_complete_interrupts(svm);
4940 
4941         if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4942                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4943                 kvm_run->fail_entry.hardware_entry_failure_reason
4944                         = svm->vmcb->control.exit_code;
4945                 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4946                 dump_vmcb(vcpu);
4947                 return 0;
4948         }
4949 
4950         if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4951             exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4952             exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4953             exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4954                 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4955                        "exit_code 0x%x\n",
4956                        __func__, svm->vmcb->control.exit_int_info,
4957                        exit_code);
4958 
4959         if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4960             || !svm_exit_handlers[exit_code]) {
4961                 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4962                 kvm_queue_exception(vcpu, UD_VECTOR);
4963                 return 1;
4964         }
4965 
4966         return svm_exit_handlers[exit_code](svm);
4967 }
4968 
4969 static void reload_tss(struct kvm_vcpu *vcpu)
4970 {
4971         int cpu = raw_smp_processor_id();
4972 
4973         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4974         sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4975         load_TR_desc();
4976 }
4977 
4978 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
4979 {
4980         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4981         int asid = sev_get_asid(svm->vcpu.kvm);
4982 
4983         /* Assign the asid allocated with this SEV guest */
4984         svm->vmcb->control.asid = asid;
4985 
4986         /*
4987          * Flush guest TLB:
4988          *
4989          * 1) when different VMCB for the same ASID is to be run on the same host CPU.
4990          * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
4991          */
4992         if (sd->sev_vmcbs[asid] == svm->vmcb &&
4993             svm->last_cpu == cpu)
4994                 return;
4995 
4996         svm->last_cpu = cpu;
4997         sd->sev_vmcbs[asid] = svm->vmcb;
4998         svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4999         mark_dirty(svm->vmcb, VMCB_ASID);
5000 }
5001 
5002 static void pre_svm_run(struct vcpu_svm *svm)
5003 {
5004         int cpu = raw_smp_processor_id();
5005 
5006         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5007 
5008         if (sev_guest(svm->vcpu.kvm))
5009                 return pre_sev_run(svm, cpu);
5010 
5011         /* FIXME: handle wraparound of asid_generation */
5012         if (svm->asid_generation != sd->asid_generation)
5013                 new_asid(svm, sd);
5014 }
5015 
5016 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5017 {
5018         struct vcpu_svm *svm = to_svm(vcpu);
5019 
5020         svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5021         vcpu->arch.hflags |= HF_NMI_MASK;
5022         set_intercept(svm, INTERCEPT_IRET);
5023         ++vcpu->stat.nmi_injections;
5024 }
5025 
5026 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
5027 {
5028         struct vmcb_control_area *control;
5029 
5030         /* The following fields are ignored when AVIC is enabled */
5031         control = &svm->vmcb->control;
5032         control->int_vector = irq;
5033         control->int_ctl &= ~V_INTR_PRIO_MASK;
5034         control->int_ctl |= V_IRQ_MASK |
5035                 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
5036         mark_dirty(svm->vmcb, VMCB_INTR);
5037 }
5038 
5039 static void svm_set_irq(struct kvm_vcpu *vcpu)
5040 {
5041         struct vcpu_svm *svm = to_svm(vcpu);
5042 
5043         BUG_ON(!(gif_set(svm)));
5044 
5045         trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5046         ++vcpu->stat.irq_injections;
5047 
5048         svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5049                 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5050 }
5051 
5052 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5053 {
5054         return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5055 }
5056 
5057 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5058 {
5059         struct vcpu_svm *svm = to_svm(vcpu);
5060 
5061         if (svm_nested_virtualize_tpr(vcpu) ||
5062             kvm_vcpu_apicv_active(vcpu))
5063                 return;
5064 
5065         clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5066 
5067         if (irr == -1)
5068                 return;
5069 
5070         if (tpr >= irr)
5071                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5072 }
5073 
5074 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5075 {
5076         return;
5077 }
5078 
5079 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
5080 {
5081         return avic && irqchip_split(vcpu->kvm);
5082 }
5083 
5084 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5085 {
5086 }
5087 
5088 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5089 {
5090 }
5091 
5092 /* Note: Currently only used by Hyper-V. */
5093 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5094 {
5095         struct vcpu_svm *svm = to_svm(vcpu);
5096         struct vmcb *vmcb = svm->vmcb;
5097 
5098         if (!kvm_vcpu_apicv_active(&svm->vcpu))
5099                 return;
5100 
5101         vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5102         mark_dirty(vmcb, VMCB_INTR);
5103 }
5104 
5105 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5106 {
5107         return;
5108 }
5109 
5110 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5111 {
5112         kvm_lapic_set_irr(vec, vcpu->arch.apic);
5113         smp_mb__after_atomic();
5114 
5115         if (avic_vcpu_is_running(vcpu))
5116                 wrmsrl(SVM_AVIC_DOORBELL,
5117                        kvm_cpu_get_apicid(vcpu->cpu));
5118         else
5119                 kvm_vcpu_wake_up(vcpu);
5120 }
5121 
5122 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5123 {
5124         unsigned long flags;
5125         struct amd_svm_iommu_ir *cur;
5126 
5127         spin_lock_irqsave(&svm->ir_list_lock, flags);
5128         list_for_each_entry(cur, &svm->ir_list, node) {
5129                 if (cur->data != pi->ir_data)
5130                         continue;
5131                 list_del(&cur->node);
5132                 kfree(cur);
5133                 break;
5134         }
5135         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5136 }
5137 
5138 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5139 {
5140         int ret = 0;
5141         unsigned long flags;
5142         struct amd_svm_iommu_ir *ir;
5143 
5144         /**
5145          * In some cases, the existing irte is updaed and re-set,
5146          * so we need to check here if it's already been * added
5147          * to the ir_list.
5148          */
5149         if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5150                 struct kvm *kvm = svm->vcpu.kvm;
5151                 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5152                 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5153                 struct vcpu_svm *prev_svm;
5154 
5155                 if (!prev_vcpu) {
5156                         ret = -EINVAL;
5157                         goto out;
5158                 }
5159 
5160                 prev_svm = to_svm(prev_vcpu);
5161                 svm_ir_list_del(prev_svm, pi);
5162         }
5163 
5164         /**
5165          * Allocating new amd_iommu_pi_data, which will get
5166          * add to the per-vcpu ir_list.
5167          */
5168         ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
5169         if (!ir) {
5170                 ret = -ENOMEM;
5171                 goto out;
5172         }
5173         ir->data = pi->ir_data;
5174 
5175         spin_lock_irqsave(&svm->ir_list_lock, flags);
5176         list_add(&ir->node, &svm->ir_list);
5177         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5178 out:
5179         return ret;
5180 }
5181 
5182 /**
5183  * Note:
5184  * The HW cannot support posting multicast/broadcast
5185  * interrupts to a vCPU. So, we still use legacy interrupt
5186  * remapping for these kind of interrupts.
5187  *
5188  * For lowest-priority interrupts, we only support
5189  * those with single CPU as the destination, e.g. user
5190  * configures the interrupts via /proc/irq or uses
5191  * irqbalance to make the interrupts single-CPU.
5192  */
5193 static int
5194 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5195                  struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5196 {
5197         struct kvm_lapic_irq irq;
5198         struct kvm_vcpu *vcpu = NULL;
5199 
5200         kvm_set_msi_irq(kvm, e, &irq);
5201 
5202         if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
5203                 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5204                          __func__, irq.vector);
5205                 return -1;
5206         }
5207 
5208         pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5209                  irq.vector);
5210         *svm = to_svm(vcpu);
5211         vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5212         vcpu_info->vector = irq.vector;
5213 
5214         return 0;
5215 }
5216 
5217 /*
5218  * svm_update_pi_irte - set IRTE for Posted-Interrupts
5219  *
5220  * @kvm: kvm
5221  * @host_irq: host irq of the interrupt
5222  * @guest_irq: gsi of the interrupt
5223  * @set: set or unset PI
5224  * returns 0 on success, < 0 on failure
5225  */
5226 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5227                               uint32_t guest_irq, bool set)
5228 {
5229         struct kvm_kernel_irq_routing_entry *e;
5230         struct kvm_irq_routing_table *irq_rt;
5231         int idx, ret = -EINVAL;
5232 
5233         if (!kvm_arch_has_assigned_device(kvm) ||
5234             !irq_remapping_cap(IRQ_POSTING_CAP))
5235                 return 0;
5236 
5237         pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5238                  __func__, host_irq, guest_irq, set);
5239 
5240         idx = srcu_read_lock(&kvm->irq_srcu);
5241         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5242         WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5243 
5244         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5245                 struct vcpu_data vcpu_info;
5246                 struct vcpu_svm *svm = NULL;
5247 
5248                 if (e->type != KVM_IRQ_ROUTING_MSI)
5249                         continue;
5250 
5251                 /**
5252                  * Here, we setup with legacy mode in the following cases:
5253                  * 1. When cannot target interrupt to a specific vcpu.
5254                  * 2. Unsetting posted interrupt.
5255                  * 3. APIC virtialization is disabled for the vcpu.
5256                  */
5257                 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5258                     kvm_vcpu_apicv_active(&svm->vcpu)) {
5259                         struct amd_iommu_pi_data pi;
5260 
5261                         /* Try to enable guest_mode in IRTE */
5262                         pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5263                                             AVIC_HPA_MASK);
5264                         pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5265                                                      svm->vcpu.vcpu_id);
5266                         pi.is_guest_mode = true;
5267                         pi.vcpu_data = &vcpu_info;
5268                         ret = irq_set_vcpu_affinity(host_irq, &pi);
5269 
5270                         /**
5271                          * Here, we successfully setting up vcpu affinity in
5272                          * IOMMU guest mode. Now, we need to store the posted
5273                          * interrupt information in a per-vcpu ir_list so that
5274                          * we can reference to them directly when we update vcpu
5275                          * scheduling information in IOMMU irte.
5276                          */
5277                         if (!ret && pi.is_guest_mode)
5278                                 svm_ir_list_add(svm, &pi);
5279                 } else {
5280                         /* Use legacy mode in IRTE */
5281                         struct amd_iommu_pi_data pi;
5282 
5283                         /**
5284                          * Here, pi is used to:
5285                          * - Tell IOMMU to use legacy mode for this interrupt.
5286                          * - Retrieve ga_tag of prior interrupt remapping data.
5287                          */
5288                         pi.is_guest_mode = false;
5289                         ret = irq_set_vcpu_affinity(host_irq, &pi);
5290 
5291                         /**
5292                          * Check if the posted interrupt was previously
5293                          * setup with the guest_mode by checking if the ga_tag
5294                          * was cached. If so, we need to clean up the per-vcpu
5295                          * ir_list.
5296                          */
5297                         if (!ret && pi.prev_ga_tag) {
5298                                 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5299                                 struct kvm_vcpu *vcpu;
5300 
5301                                 vcpu = kvm_get_vcpu_by_id(kvm, id);
5302                                 if (vcpu)
5303                                         svm_ir_list_del(to_svm(vcpu), &pi);
5304                         }
5305                 }
5306 
5307                 if (!ret && svm) {
5308                         trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5309                                                  e->gsi, vcpu_info.vector,
5310                                                  vcpu_info.pi_desc_addr, set);
5311                 }
5312 
5313                 if (ret < 0) {
5314                         pr_err("%s: failed to update PI IRTE\n", __func__);
5315                         goto out;
5316                 }
5317         }
5318 
5319         ret = 0;
5320 out:
5321         srcu_read_unlock(&kvm->irq_srcu, idx);
5322         return ret;
5323 }
5324 
5325 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5326 {
5327         struct vcpu_svm *svm = to_svm(vcpu);
5328         struct vmcb *vmcb = svm->vmcb;
5329         int ret;
5330         ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5331               !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5332         ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5333 
5334         return ret;
5335 }
5336 
5337 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5338 {
5339         struct vcpu_svm *svm = to_svm(vcpu);
5340 
5341         return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5342 }
5343 
5344 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5345 {
5346         struct vcpu_svm *svm = to_svm(vcpu);
5347 
5348         if (masked) {
5349                 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5350                 set_intercept(svm, INTERCEPT_IRET);
5351         } else {
5352                 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5353                 clr_intercept(svm, INTERCEPT_IRET);
5354         }
5355 }
5356 
5357 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5358 {
5359         struct vcpu_svm *svm = to_svm(vcpu);
5360         struct vmcb *vmcb = svm->vmcb;
5361         int ret;
5362 
5363         if (!gif_set(svm) ||
5364              (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5365                 return 0;
5366 
5367         ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5368 
5369         if (is_guest_mode(vcpu))
5370                 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5371 
5372         return ret;
5373 }
5374 
5375 static void enable_irq_window(struct kvm_vcpu *vcpu)
5376 {
5377         struct vcpu_svm *svm = to_svm(vcpu);
5378 
5379         if (kvm_vcpu_apicv_active(vcpu))
5380                 return;
5381 
5382         /*
5383          * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5384          * 1, because that's a separate STGI/VMRUN intercept.  The next time we
5385          * get that intercept, this function will be called again though and
5386          * we'll get the vintr intercept. However, if the vGIF feature is
5387          * enabled, the STGI interception will not occur. Enable the irq
5388          * window under the assumption that the hardware will set the GIF.
5389          */
5390         if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5391                 svm_set_vintr(svm);
5392                 svm_inject_irq(svm, 0x0);
5393         }
5394 }
5395 
5396 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5397 {
5398         struct vcpu_svm *svm = to_svm(vcpu);
5399 
5400         if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5401             == HF_NMI_MASK)
5402                 return; /* IRET will cause a vm exit */
5403 
5404         if (!gif_set(svm)) {
5405                 if (vgif_enabled(svm))
5406                         set_intercept(svm, INTERCEPT_STGI);
5407                 return; /* STGI will cause a vm exit */
5408         }
5409 
5410         if (svm->nested.exit_required)
5411                 return; /* we're not going to run the guest yet */
5412 
5413         /*
5414          * Something prevents NMI from been injected. Single step over possible
5415          * problem (IRET or exception injection or interrupt shadow)
5416          */
5417         svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5418         svm->nmi_singlestep = true;
5419         svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5420 }
5421 
5422 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5423 {
5424         return 0;
5425 }
5426 
5427 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5428 {
5429         return 0;
5430 }
5431 
5432 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5433 {
5434         struct vcpu_svm *svm = to_svm(vcpu);
5435 
5436         if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5437                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5438         else
5439                 svm->asid_generation--;
5440 }
5441 
5442 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5443 {
5444 }
5445 
5446 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5447 {
5448         struct vcpu_svm *svm = to_svm(vcpu);
5449 
5450         if (svm_nested_virtualize_tpr(vcpu))
5451                 return;
5452 
5453         if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5454                 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5455                 kvm_set_cr8(vcpu, cr8);
5456         }
5457 }
5458 
5459 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5460 {
5461         struct vcpu_svm *svm = to_svm(vcpu);
5462         u64 cr8;
5463 
5464         if (svm_nested_virtualize_tpr(vcpu) ||
5465             kvm_vcpu_apicv_active(vcpu))
5466                 return;
5467 
5468         cr8 = kvm_get_cr8(vcpu);
5469         svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5470         svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5471 }
5472 
5473 static void svm_complete_interrupts(struct vcpu_svm *svm)
5474 {
5475         u8 vector;
5476         int type;
5477         u32 exitintinfo = svm->vmcb->control.exit_int_info;
5478         unsigned int3_injected = svm->int3_injected;
5479 
5480         svm->int3_injected = 0;
5481 
5482         /*
5483          * If we've made progress since setting HF_IRET_MASK, we've
5484          * executed an IRET and can allow NMI injection.
5485          */
5486         if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5487             && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5488                 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5489                 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5490         }
5491 
5492         svm->vcpu.arch.nmi_injected = false;
5493         kvm_clear_exception_queue(&svm->vcpu);
5494         kvm_clear_interrupt_queue(&svm->vcpu);
5495 
5496         if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5497                 return;
5498 
5499         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5500 
5501         vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5502         type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5503 
5504         switch (type) {
5505         case SVM_EXITINTINFO_TYPE_NMI:
5506                 svm->vcpu.arch.nmi_injected = true;
5507                 break;
5508         case SVM_EXITINTINFO_TYPE_EXEPT:
5509                 /*
5510                  * In case of software exceptions, do not reinject the vector,
5511                  * but re-execute the instruction instead. Rewind RIP first
5512                  * if we emulated INT3 before.
5513                  */
5514                 if (kvm_exception_is_soft(vector)) {
5515                         if (vector == BP_VECTOR && int3_injected &&
5516                             kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5517                                 kvm_rip_write(&svm->vcpu,
5518                                               kvm_rip_read(&svm->vcpu) -
5519                                               int3_injected);
5520                         break;
5521                 }
5522                 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5523                         u32 err = svm->vmcb->control.exit_int_info_err;
5524                         kvm_requeue_exception_e(&svm->vcpu, vector, err);
5525 
5526                 } else
5527                         kvm_requeue_exception(&svm->vcpu, vector);
5528                 break;
5529         case SVM_EXITINTINFO_TYPE_INTR:
5530                 kvm_queue_interrupt(&svm->vcpu, vector, false);
5531                 break;
5532         default:
5533                 break;
5534         }
5535 }
5536 
5537 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5538 {
5539         struct vcpu_svm *svm = to_svm(vcpu);
5540         struct vmcb_control_area *control = &svm->vmcb->control;
5541 
5542         control->exit_int_info = control->event_inj;
5543         control->exit_int_info_err = control->event_inj_err;
5544         control->event_inj = 0;
5545         svm_complete_interrupts(svm);
5546 }
5547 
5548 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5549 {
5550         struct vcpu_svm *svm = to_svm(vcpu);
5551 
5552         svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5553         svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5554         svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5555 
5556         /*
5557          * A vmexit emulation is required before the vcpu can be executed
5558          * again.
5559          */
5560         if (unlikely(svm->nested.exit_required))
5561                 return;
5562 
5563         /*
5564          * Disable singlestep if we're injecting an interrupt/exception.
5565          * We don't want our modified rflags to be pushed on the stack where
5566          * we might not be able to easily reset them if we disabled NMI
5567          * singlestep later.
5568          */
5569         if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5570                 /*
5571                  * Event injection happens before external interrupts cause a
5572                  * vmexit and interrupts are disabled here, so smp_send_reschedule
5573                  * is enough to force an immediate vmexit.
5574                  */
5575                 disable_nmi_singlestep(svm);
5576                 smp_send_reschedule(vcpu->cpu);
5577         }
5578 
5579         pre_svm_run(svm);
5580 
5581         sync_lapic_to_cr8(vcpu);
5582 
5583         svm->vmcb->save.cr2 = vcpu->arch.cr2;
5584 
5585         clgi();
5586 
5587         /*
5588          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5589          * it's non-zero. Since vmentry is serialising on affected CPUs, there
5590          * is no need to worry about the conditional branch over the wrmsr
5591          * being speculatively taken.
5592          */
5593         x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5594 
5595         local_irq_enable();
5596 
5597         asm volatile (
5598                 "push %%" _ASM_BP "; \n\t"
5599                 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5600                 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5601                 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5602                 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5603                 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5604                 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5605 #ifdef CONFIG_X86_64
5606                 "mov %c[r8](%[svm]),  %%r8  \n\t"
5607                 "mov %c[r9](%[svm]),  %%r9  \n\t"
5608                 "mov %c[r10](%[svm]), %%r10 \n\t"
5609                 "mov %c[r11](%[svm]), %%r11 \n\t"
5610                 "mov %c[r12](%[svm]), %%r12 \n\t"
5611                 "mov %c[r13](%[svm]), %%r13 \n\t"
5612                 "mov %c[r14](%[svm]), %%r14 \n\t"
5613                 "mov %c[r15](%[svm]), %%r15 \n\t"
5614 #endif
5615 
5616                 /* Enter guest mode */
5617                 "push %%" _ASM_AX " \n\t"
5618                 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5619                 __ex(SVM_VMLOAD) "\n\t"
5620                 __ex(SVM_VMRUN) "\n\t"
5621                 __ex(SVM_VMSAVE) "\n\t"
5622                 "pop %%" _ASM_AX " \n\t"
5623 
5624                 /* Save guest registers, load host registers */
5625                 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5626                 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5627                 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5628                 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5629                 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5630                 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5631 #ifdef CONFIG_X86_64
5632                 "mov %%r8,  %c[r8](%[svm]) \n\t"
5633                 "mov %%r9,  %c[r9](%[svm]) \n\t"
5634                 "mov %%r10, %c[r10](%[svm]) \n\t"
5635                 "mov %%r11, %c[r11](%[svm]) \n\t"
5636                 "mov %%r12, %c[r12](%[svm]) \n\t"
5637                 "mov %%r13, %c[r13](%[svm]) \n\t"
5638                 "mov %%r14, %c[r14](%[svm]) \n\t"
5639                 "mov %%r15, %c[r15](%[svm]) \n\t"
5640 #endif
5641                 /*
5642                 * Clear host registers marked as clobbered to prevent
5643                 * speculative use.
5644                 */
5645                 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5646                 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5647                 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5648                 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5649                 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5650 #ifdef CONFIG_X86_64
5651                 "xor %%r8, %%r8 \n\t"
5652                 "xor %%r9, %%r9 \n\t"
5653                 "xor %%r10, %%r10 \n\t"
5654                 "xor %%r11, %%r11 \n\t"
5655                 "xor %%r12, %%r12 \n\t"
5656                 "xor %%r13, %%r13 \n\t"
5657                 "xor %%r14, %%r14 \n\t"
5658                 "xor %%r15, %%r15 \n\t"
5659 #endif
5660                 "pop %%" _ASM_BP
5661                 :
5662                 : [svm]"a"(svm),
5663                   [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5664                   [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5665                   [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5666                   [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5667                   [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5668                   [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5669                   [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5670 #ifdef CONFIG_X86_64
5671                   , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5672                   [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5673                   [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5674                   [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5675                   [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5676                   [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5677                   [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5678                   [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5679 #endif
5680                 : "cc", "memory"
5681 #ifdef CONFIG_X86_64
5682                 , "rbx", "rcx", "rdx", "rsi", "rdi"
5683                 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5684 #else
5685                 , "ebx", "ecx", "edx", "esi", "edi"
5686 #endif
5687                 );
5688 
5689         /* Eliminate branch target predictions from guest mode */
5690         vmexit_fill_RSB();
5691 
5692 #ifdef CONFIG_X86_64
5693         wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5694 #else
5695         loadsegment(fs, svm->host.fs);
5696 #ifndef CONFIG_X86_32_LAZY_GS
5697         loadsegment(gs, svm->host.gs);
5698 #endif
5699 #endif
5700 
5701         /*
5702          * We do not use IBRS in the kernel. If this vCPU has used the
5703          * SPEC_CTRL MSR it may have left it on; save the value and
5704          * turn it off. This is much more efficient than blindly adding
5705          * it to the atomic save/restore list. Especially as the former
5706          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5707          *
5708          * For non-nested case:
5709          * If the L01 MSR bitmap does not intercept the MSR, then we need to
5710          * save it.
5711          *
5712          * For nested case:
5713          * If the L02 MSR bitmap does not intercept the MSR, then we need to
5714          * save it.
5715          */
5716         if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5717                 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5718 
5719         reload_tss(vcpu);
5720 
5721         local_irq_disable();
5722 
5723         x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5724 
5725         vcpu->arch.cr2 = svm->vmcb->save.cr2;
5726         vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5727         vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5728         vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5729 
5730         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5731                 kvm_before_interrupt(&svm->vcpu);
5732 
5733         stgi();
5734 
5735         /* Any pending NMI will happen here */
5736 
5737         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5738                 kvm_after_interrupt(&svm->vcpu);
5739 
5740         sync_cr8_to_lapic(vcpu);
5741 
5742         svm->next_rip = 0;
5743 
5744         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5745 
5746         /* if exit due to PF check for async PF */
5747         if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5748                 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5749 
5750         if (npt_enabled) {