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

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

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