2 * Kernel-based Virtual Machine driver for Linux
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
10 * Yaniv Kamay <yaniv@qumranet.com>
11 * Avi Kivity <avi@qumranet.com>
13 * This work is licensed under the terms of the GNU GPL, version 2. See
14 * the COPYING file in the top-level directory.
18 #define pr_fmt(fmt) "SVM: " fmt
20 #include <linux/kvm_host.h>
24 #include "kvm_cache_regs.h"
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>
46 #include <asm/perf_event.h>
47 #include <asm/tlbflush.h>
49 #include <asm/debugreg.h>
50 #include <asm/kvm_para.h>
51 #include <asm/irq_remapping.h>
52 #include <asm/nospec-branch.h>
54 #include <asm/virtext.h>
57 #define __ex(x) __kvm_handle_fault_on_reboot(x)
59 MODULE_AUTHOR("Qumranet");
60 MODULE_LICENSE("GPL");
62 static const struct x86_cpu_id svm_cpu_id[] = {
63 X86_FEATURE_MATCH(X86_FEATURE_SVM),
66 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
68 #define IOPM_ALLOC_ORDER 2
69 #define MSRPM_ALLOC_ORDER 1
71 #define SEG_TYPE_LDT 2
72 #define SEG_TYPE_BUSY_TSS16 3
74 #define SVM_FEATURE_NPT (1 << 0)
75 #define SVM_FEATURE_LBRV (1 << 1)
76 #define SVM_FEATURE_SVML (1 << 2)
77 #define SVM_FEATURE_NRIP (1 << 3)
78 #define SVM_FEATURE_TSC_RATE (1 << 4)
79 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
80 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
81 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
82 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
84 #define SVM_AVIC_DOORBELL 0xc001011b
86 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
87 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
88 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
90 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
92 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
93 #define TSC_RATIO_MIN 0x0000000000000001ULL
94 #define TSC_RATIO_MAX 0x000000ffffffffffULL
96 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
99 * 0xff is broadcast, so the max index allowed for physical APIC ID
100 * table is 0xfe. APIC IDs above 0xff are reserved.
102 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
104 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
105 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
106 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
108 /* AVIC GATAG is encoded using VM and VCPU IDs */
109 #define AVIC_VCPU_ID_BITS 8
110 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
112 #define AVIC_VM_ID_BITS 24
113 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
114 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
116 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
117 (y & AVIC_VCPU_ID_MASK))
118 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
119 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
121 static bool erratum_383_found __read_mostly;
123 static const u32 host_save_user_msrs[] = {
125 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
128 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
132 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
136 struct nested_state {
142 /* These are the merged vectors */
145 /* gpa pointers to the real vectors */
149 /* A VMEXIT is required but not yet emulated */
152 /* cache for intercepts of the guest */
155 u32 intercept_exceptions;
158 /* Nested Paging related state */
162 #define MSRPM_OFFSETS 16
163 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
166 * Set osvw_len to higher value when updated Revision Guides
167 * are published and we know what the new status bits are
169 static uint64_t osvw_len = 4, osvw_status;
172 struct kvm_vcpu vcpu;
174 unsigned long vmcb_pa;
175 struct svm_cpu_data *svm_data;
176 uint64_t asid_generation;
177 uint64_t sysenter_esp;
178 uint64_t sysenter_eip;
183 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
197 struct nested_state nested;
200 u64 nmi_singlestep_guest_rflags;
202 unsigned int3_injected;
203 unsigned long int3_rip;
205 /* cached guest cpuid flags for faster access */
206 bool nrips_enabled : 1;
209 struct page *avic_backing_page;
210 u64 *avic_physical_id_cache;
211 bool avic_is_running;
214 * Per-vcpu list of struct amd_svm_iommu_ir:
215 * This is used mainly to store interrupt remapping information used
216 * when update the vcpu affinity. This avoids the need to scan for
217 * IRTE and try to match ga_tag in the IOMMU driver.
219 struct list_head ir_list;
220 spinlock_t ir_list_lock;
222 /* which host CPU was used for running this vcpu */
223 unsigned int last_cpu;
227 * This is a wrapper of struct amd_iommu_ir_data.
229 struct amd_svm_iommu_ir {
230 struct list_head node; /* Used by SVM for per-vcpu ir_list */
231 void *data; /* Storing pointer to struct amd_ir_data */
234 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
235 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
237 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
238 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
239 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
240 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
242 static DEFINE_PER_CPU(u64, current_tsc_ratio);
243 #define TSC_RATIO_DEFAULT 0x0100000000ULL
245 #define MSR_INVALID 0xffffffffU
247 static const struct svm_direct_access_msrs {
248 u32 index; /* Index of the MSR */
249 bool always; /* True if intercept is always on */
250 } direct_access_msrs[] = {
251 { .index = MSR_STAR, .always = true },
252 { .index = MSR_IA32_SYSENTER_CS, .always = true },
254 { .index = MSR_GS_BASE, .always = true },
255 { .index = MSR_FS_BASE, .always = true },
256 { .index = MSR_KERNEL_GS_BASE, .always = true },
257 { .index = MSR_LSTAR, .always = true },
258 { .index = MSR_CSTAR, .always = true },
259 { .index = MSR_SYSCALL_MASK, .always = true },
261 { .index = MSR_IA32_SPEC_CTRL, .always = false },
262 { .index = MSR_IA32_PRED_CMD, .always = false },
263 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
264 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
265 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
266 { .index = MSR_IA32_LASTINTTOIP, .always = false },
267 { .index = MSR_INVALID, .always = false },
270 /* enable NPT for AMD64 and X86 with PAE */
271 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
272 static bool npt_enabled = true;
274 static bool npt_enabled;
277 /* allow nested paging (virtualized MMU) for all guests */
278 static int npt = true;
279 module_param(npt, int, S_IRUGO);
281 /* allow nested virtualization in KVM/SVM */
282 static int nested = true;
283 module_param(nested, int, S_IRUGO);
285 /* enable / disable AVIC */
287 #ifdef CONFIG_X86_LOCAL_APIC
288 module_param(avic, int, S_IRUGO);
291 /* enable/disable Virtual VMLOAD VMSAVE */
292 static int vls = true;
293 module_param(vls, int, 0444);
295 /* enable/disable Virtual GIF */
296 static int vgif = true;
297 module_param(vgif, int, 0444);
299 /* enable/disable SEV support */
300 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
301 module_param(sev, int, 0444);
303 static u8 rsm_ins_bytes[] = "\x0f\xaa";
305 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
306 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
307 static void svm_complete_interrupts(struct vcpu_svm *svm);
309 static int nested_svm_exit_handled(struct vcpu_svm *svm);
310 static int nested_svm_intercept(struct vcpu_svm *svm);
311 static int nested_svm_vmexit(struct vcpu_svm *svm);
312 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
313 bool has_error_code, u32 error_code);
316 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
317 pause filter count */
318 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
319 VMCB_ASID, /* ASID */
320 VMCB_INTR, /* int_ctl, int_vector */
321 VMCB_NPT, /* npt_en, nCR3, gPAT */
322 VMCB_CR, /* CR0, CR3, CR4, EFER */
323 VMCB_DR, /* DR6, DR7 */
324 VMCB_DT, /* GDT, IDT */
325 VMCB_SEG, /* CS, DS, SS, ES, CPL */
326 VMCB_CR2, /* CR2 only */
327 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
328 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
329 * AVIC PHYSICAL_TABLE pointer,
330 * AVIC LOGICAL_TABLE pointer
335 /* TPR and CR2 are always written before VMRUN */
336 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
338 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
340 static unsigned int max_sev_asid;
341 static unsigned int min_sev_asid;
342 static unsigned long *sev_asid_bitmap;
343 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
346 struct list_head list;
347 unsigned long npages;
353 static inline bool svm_sev_enabled(void)
358 static inline bool sev_guest(struct kvm *kvm)
360 struct kvm_sev_info *sev = &kvm->arch.sev_info;
365 static inline int sev_get_asid(struct kvm *kvm)
367 struct kvm_sev_info *sev = &kvm->arch.sev_info;
372 static inline void mark_all_dirty(struct vmcb *vmcb)
374 vmcb->control.clean = 0;
377 static inline void mark_all_clean(struct vmcb *vmcb)
379 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
380 & ~VMCB_ALWAYS_DIRTY_MASK;
383 static inline void mark_dirty(struct vmcb *vmcb, int bit)
385 vmcb->control.clean &= ~(1 << bit);
388 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
390 return container_of(vcpu, struct vcpu_svm, vcpu);
393 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
395 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
396 mark_dirty(svm->vmcb, VMCB_AVIC);
399 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
401 struct vcpu_svm *svm = to_svm(vcpu);
402 u64 *entry = svm->avic_physical_id_cache;
407 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
410 static void recalc_intercepts(struct vcpu_svm *svm)
412 struct vmcb_control_area *c, *h;
413 struct nested_state *g;
415 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
417 if (!is_guest_mode(&svm->vcpu))
420 c = &svm->vmcb->control;
421 h = &svm->nested.hsave->control;
424 c->intercept_cr = h->intercept_cr | g->intercept_cr;
425 c->intercept_dr = h->intercept_dr | g->intercept_dr;
426 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
427 c->intercept = h->intercept | g->intercept;
430 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
432 if (is_guest_mode(&svm->vcpu))
433 return svm->nested.hsave;
438 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
440 struct vmcb *vmcb = get_host_vmcb(svm);
442 vmcb->control.intercept_cr |= (1U << bit);
444 recalc_intercepts(svm);
447 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
449 struct vmcb *vmcb = get_host_vmcb(svm);
451 vmcb->control.intercept_cr &= ~(1U << bit);
453 recalc_intercepts(svm);
456 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
458 struct vmcb *vmcb = get_host_vmcb(svm);
460 return vmcb->control.intercept_cr & (1U << bit);
463 static inline void set_dr_intercepts(struct vcpu_svm *svm)
465 struct vmcb *vmcb = get_host_vmcb(svm);
467 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
468 | (1 << INTERCEPT_DR1_READ)
469 | (1 << INTERCEPT_DR2_READ)
470 | (1 << INTERCEPT_DR3_READ)
471 | (1 << INTERCEPT_DR4_READ)
472 | (1 << INTERCEPT_DR5_READ)
473 | (1 << INTERCEPT_DR6_READ)
474 | (1 << INTERCEPT_DR7_READ)
475 | (1 << INTERCEPT_DR0_WRITE)
476 | (1 << INTERCEPT_DR1_WRITE)
477 | (1 << INTERCEPT_DR2_WRITE)
478 | (1 << INTERCEPT_DR3_WRITE)
479 | (1 << INTERCEPT_DR4_WRITE)
480 | (1 << INTERCEPT_DR5_WRITE)
481 | (1 << INTERCEPT_DR6_WRITE)
482 | (1 << INTERCEPT_DR7_WRITE);
484 recalc_intercepts(svm);
487 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
489 struct vmcb *vmcb = get_host_vmcb(svm);
491 vmcb->control.intercept_dr = 0;
493 recalc_intercepts(svm);
496 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
498 struct vmcb *vmcb = get_host_vmcb(svm);
500 vmcb->control.intercept_exceptions |= (1U << bit);
502 recalc_intercepts(svm);
505 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
507 struct vmcb *vmcb = get_host_vmcb(svm);
509 vmcb->control.intercept_exceptions &= ~(1U << bit);
511 recalc_intercepts(svm);
514 static inline void set_intercept(struct vcpu_svm *svm, int bit)
516 struct vmcb *vmcb = get_host_vmcb(svm);
518 vmcb->control.intercept |= (1ULL << bit);
520 recalc_intercepts(svm);
523 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
525 struct vmcb *vmcb = get_host_vmcb(svm);
527 vmcb->control.intercept &= ~(1ULL << bit);
529 recalc_intercepts(svm);
532 static inline bool vgif_enabled(struct vcpu_svm *svm)
534 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
537 static inline void enable_gif(struct vcpu_svm *svm)
539 if (vgif_enabled(svm))
540 svm->vmcb->control.int_ctl |= V_GIF_MASK;
542 svm->vcpu.arch.hflags |= HF_GIF_MASK;
545 static inline void disable_gif(struct vcpu_svm *svm)
547 if (vgif_enabled(svm))
548 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
550 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
553 static inline bool gif_set(struct vcpu_svm *svm)
555 if (vgif_enabled(svm))
556 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
558 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
561 static unsigned long iopm_base;
563 struct kvm_ldttss_desc {
566 unsigned base1:8, type:5, dpl:2, p:1;
567 unsigned limit1:4, zero0:3, g:1, base2:8;
570 } __attribute__((packed));
572 struct svm_cpu_data {
579 struct kvm_ldttss_desc *tss_desc;
581 struct page *save_area;
582 struct vmcb *current_vmcb;
584 /* index = sev_asid, value = vmcb pointer */
585 struct vmcb **sev_vmcbs;
588 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
590 struct svm_init_data {
595 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
597 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
598 #define MSRS_RANGE_SIZE 2048
599 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
601 static u32 svm_msrpm_offset(u32 msr)
606 for (i = 0; i < NUM_MSR_MAPS; i++) {
607 if (msr < msrpm_ranges[i] ||
608 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
611 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
612 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
614 /* Now we have the u8 offset - but need the u32 offset */
618 /* MSR not in any range */
622 #define MAX_INST_SIZE 15
624 static inline void clgi(void)
626 asm volatile (__ex(SVM_CLGI));
629 static inline void stgi(void)
631 asm volatile (__ex(SVM_STGI));
634 static inline void invlpga(unsigned long addr, u32 asid)
636 asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
639 static int get_npt_level(struct kvm_vcpu *vcpu)
642 return PT64_ROOT_4LEVEL;
644 return PT32E_ROOT_LEVEL;
648 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
650 vcpu->arch.efer = efer;
651 if (!npt_enabled && !(efer & EFER_LMA))
654 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
655 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
658 static int is_external_interrupt(u32 info)
660 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
661 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
664 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
666 struct vcpu_svm *svm = to_svm(vcpu);
669 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
670 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
674 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
676 struct vcpu_svm *svm = to_svm(vcpu);
679 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
681 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
685 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
687 struct vcpu_svm *svm = to_svm(vcpu);
689 if (svm->vmcb->control.next_rip != 0) {
690 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
691 svm->next_rip = svm->vmcb->control.next_rip;
694 if (!svm->next_rip) {
695 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
697 printk(KERN_DEBUG "%s: NOP\n", __func__);
700 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
701 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
702 __func__, kvm_rip_read(vcpu), svm->next_rip);
704 kvm_rip_write(vcpu, svm->next_rip);
705 svm_set_interrupt_shadow(vcpu, 0);
708 static void svm_queue_exception(struct kvm_vcpu *vcpu)
710 struct vcpu_svm *svm = to_svm(vcpu);
711 unsigned nr = vcpu->arch.exception.nr;
712 bool has_error_code = vcpu->arch.exception.has_error_code;
713 bool reinject = vcpu->arch.exception.injected;
714 u32 error_code = vcpu->arch.exception.error_code;
717 * If we are within a nested VM we'd better #VMEXIT and let the guest
718 * handle the exception
721 nested_svm_check_exception(svm, nr, has_error_code, error_code))
724 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
725 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
728 * For guest debugging where we have to reinject #BP if some
729 * INT3 is guest-owned:
730 * Emulate nRIP by moving RIP forward. Will fail if injection
731 * raises a fault that is not intercepted. Still better than
732 * failing in all cases.
734 skip_emulated_instruction(&svm->vcpu);
735 rip = kvm_rip_read(&svm->vcpu);
736 svm->int3_rip = rip + svm->vmcb->save.cs.base;
737 svm->int3_injected = rip - old_rip;
740 svm->vmcb->control.event_inj = nr
742 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
743 | SVM_EVTINJ_TYPE_EXEPT;
744 svm->vmcb->control.event_inj_err = error_code;
747 static void svm_init_erratum_383(void)
753 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
756 /* Use _safe variants to not break nested virtualization */
757 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
763 low = lower_32_bits(val);
764 high = upper_32_bits(val);
766 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
768 erratum_383_found = true;
771 static void svm_init_osvw(struct kvm_vcpu *vcpu)
774 * Guests should see errata 400 and 415 as fixed (assuming that
775 * HLT and IO instructions are intercepted).
777 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
778 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
781 * By increasing VCPU's osvw.length to 3 we are telling the guest that
782 * all osvw.status bits inside that length, including bit 0 (which is
783 * reserved for erratum 298), are valid. However, if host processor's
784 * osvw_len is 0 then osvw_status[0] carries no information. We need to
785 * be conservative here and therefore we tell the guest that erratum 298
786 * is present (because we really don't know).
788 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
789 vcpu->arch.osvw.status |= 1;
792 static int has_svm(void)
796 if (!cpu_has_svm(&msg)) {
797 printk(KERN_INFO "has_svm: %s\n", msg);
804 static void svm_hardware_disable(void)
806 /* Make sure we clean up behind us */
807 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
808 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
812 amd_pmu_disable_virt();
815 static int svm_hardware_enable(void)
818 struct svm_cpu_data *sd;
820 struct desc_struct *gdt;
821 int me = raw_smp_processor_id();
823 rdmsrl(MSR_EFER, efer);
824 if (efer & EFER_SVME)
828 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
831 sd = per_cpu(svm_data, me);
833 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
837 sd->asid_generation = 1;
838 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
839 sd->next_asid = sd->max_asid + 1;
840 sd->min_asid = max_sev_asid + 1;
842 gdt = get_current_gdt_rw();
843 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
845 wrmsrl(MSR_EFER, efer | EFER_SVME);
847 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
849 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
850 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
851 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
858 * Note that it is possible to have a system with mixed processor
859 * revisions and therefore different OSVW bits. If bits are not the same
860 * on different processors then choose the worst case (i.e. if erratum
861 * is present on one processor and not on another then assume that the
862 * erratum is present everywhere).
864 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
865 uint64_t len, status = 0;
868 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
870 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
874 osvw_status = osvw_len = 0;
878 osvw_status |= status;
879 osvw_status &= (1ULL << osvw_len) - 1;
882 osvw_status = osvw_len = 0;
884 svm_init_erratum_383();
886 amd_pmu_enable_virt();
891 static void svm_cpu_uninit(int cpu)
893 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
898 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
899 kfree(sd->sev_vmcbs);
900 __free_page(sd->save_area);
904 static int svm_cpu_init(int cpu)
906 struct svm_cpu_data *sd;
909 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
914 sd->save_area = alloc_page(GFP_KERNEL);
918 if (svm_sev_enabled()) {
920 sd->sev_vmcbs = kmalloc((max_sev_asid + 1) * sizeof(void *), GFP_KERNEL);
925 per_cpu(svm_data, cpu) = sd;
935 static bool valid_msr_intercept(u32 index)
939 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
940 if (direct_access_msrs[i].index == index)
946 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
953 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
956 offset = svm_msrpm_offset(msr);
957 bit_write = 2 * (msr & 0x0f) + 1;
960 BUG_ON(offset == MSR_INVALID);
962 return !!test_bit(bit_write, &tmp);
965 static void set_msr_interception(u32 *msrpm, unsigned msr,
968 u8 bit_read, bit_write;
973 * If this warning triggers extend the direct_access_msrs list at the
974 * beginning of the file
976 WARN_ON(!valid_msr_intercept(msr));
978 offset = svm_msrpm_offset(msr);
979 bit_read = 2 * (msr & 0x0f);
980 bit_write = 2 * (msr & 0x0f) + 1;
983 BUG_ON(offset == MSR_INVALID);
985 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
986 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
991 static void svm_vcpu_init_msrpm(u32 *msrpm)
995 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
997 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
998 if (!direct_access_msrs[i].always)
1001 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1005 static void add_msr_offset(u32 offset)
1009 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1011 /* Offset already in list? */
1012 if (msrpm_offsets[i] == offset)
1015 /* Slot used by another offset? */
1016 if (msrpm_offsets[i] != MSR_INVALID)
1019 /* Add offset to list */
1020 msrpm_offsets[i] = offset;
1026 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1027 * increase MSRPM_OFFSETS in this case.
1032 static void init_msrpm_offsets(void)
1036 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1038 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1041 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1042 BUG_ON(offset == MSR_INVALID);
1044 add_msr_offset(offset);
1048 static void svm_enable_lbrv(struct vcpu_svm *svm)
1050 u32 *msrpm = svm->msrpm;
1052 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1053 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1054 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1055 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1056 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1059 static void svm_disable_lbrv(struct vcpu_svm *svm)
1061 u32 *msrpm = svm->msrpm;
1063 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1064 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1065 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1066 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1067 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1070 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1072 svm->nmi_singlestep = false;
1074 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1075 /* Clear our flags if they were not set by the guest */
1076 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1077 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1078 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1079 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1084 * This hash table is used to map VM_ID to a struct kvm_arch,
1085 * when handling AMD IOMMU GALOG notification to schedule in
1086 * a particular vCPU.
1088 #define SVM_VM_DATA_HASH_BITS 8
1089 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1090 static u32 next_vm_id = 0;
1091 static bool next_vm_id_wrapped = 0;
1092 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1095 * This function is called from IOMMU driver to notify
1096 * SVM to schedule in a particular vCPU of a particular VM.
1098 static int avic_ga_log_notifier(u32 ga_tag)
1100 unsigned long flags;
1101 struct kvm_arch *ka = NULL;
1102 struct kvm_vcpu *vcpu = NULL;
1103 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1104 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1106 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1108 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1109 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1110 struct kvm *kvm = container_of(ka, struct kvm, arch);
1111 struct kvm_arch *vm_data = &kvm->arch;
1113 if (vm_data->avic_vm_id != vm_id)
1115 vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1118 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1121 * At this point, the IOMMU should have already set the pending
1122 * bit in the vAPIC backing page. So, we just need to schedule
1126 kvm_vcpu_wake_up(vcpu);
1131 static __init int sev_hardware_setup(void)
1133 struct sev_user_data_status *status;
1136 /* Maximum number of encrypted guests supported simultaneously */
1137 max_sev_asid = cpuid_ecx(0x8000001F);
1142 /* Minimum ASID value that should be used for SEV guest */
1143 min_sev_asid = cpuid_edx(0x8000001F);
1145 /* Initialize SEV ASID bitmap */
1146 sev_asid_bitmap = kcalloc(BITS_TO_LONGS(max_sev_asid),
1147 sizeof(unsigned long), GFP_KERNEL);
1148 if (!sev_asid_bitmap)
1151 status = kmalloc(sizeof(*status), GFP_KERNEL);
1156 * Check SEV platform status.
1158 * PLATFORM_STATUS can be called in any state, if we failed to query
1159 * the PLATFORM status then either PSP firmware does not support SEV
1160 * feature or SEV firmware is dead.
1162 rc = sev_platform_status(status, NULL);
1166 pr_info("SEV supported\n");
1173 static __init int svm_hardware_setup(void)
1176 struct page *iopm_pages;
1180 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1185 iopm_va = page_address(iopm_pages);
1186 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1187 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1189 init_msrpm_offsets();
1191 if (boot_cpu_has(X86_FEATURE_NX))
1192 kvm_enable_efer_bits(EFER_NX);
1194 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1195 kvm_enable_efer_bits(EFER_FFXSR);
1197 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1198 kvm_has_tsc_control = true;
1199 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1200 kvm_tsc_scaling_ratio_frac_bits = 32;
1204 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1205 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1209 if (boot_cpu_has(X86_FEATURE_SEV) &&
1210 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1211 r = sev_hardware_setup();
1219 for_each_possible_cpu(cpu) {
1220 r = svm_cpu_init(cpu);
1225 if (!boot_cpu_has(X86_FEATURE_NPT))
1226 npt_enabled = false;
1228 if (npt_enabled && !npt) {
1229 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1230 npt_enabled = false;
1234 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1241 !boot_cpu_has(X86_FEATURE_AVIC) ||
1242 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1245 pr_info("AVIC enabled\n");
1247 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1253 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1254 !IS_ENABLED(CONFIG_X86_64)) {
1257 pr_info("Virtual VMLOAD VMSAVE supported\n");
1262 if (!boot_cpu_has(X86_FEATURE_VGIF))
1265 pr_info("Virtual GIF supported\n");
1271 __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1276 static __exit void svm_hardware_unsetup(void)
1280 if (svm_sev_enabled())
1281 kfree(sev_asid_bitmap);
1283 for_each_possible_cpu(cpu)
1284 svm_cpu_uninit(cpu);
1286 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1290 static void init_seg(struct vmcb_seg *seg)
1293 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1294 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1295 seg->limit = 0xffff;
1299 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1302 seg->attrib = SVM_SELECTOR_P_MASK | type;
1303 seg->limit = 0xffff;
1307 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1309 struct vcpu_svm *svm = to_svm(vcpu);
1310 u64 g_tsc_offset = 0;
1312 if (is_guest_mode(vcpu)) {
1313 g_tsc_offset = svm->vmcb->control.tsc_offset -
1314 svm->nested.hsave->control.tsc_offset;
1315 svm->nested.hsave->control.tsc_offset = offset;
1317 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1318 svm->vmcb->control.tsc_offset,
1321 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1323 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1326 static void avic_init_vmcb(struct vcpu_svm *svm)
1328 struct vmcb *vmcb = svm->vmcb;
1329 struct kvm_arch *vm_data = &svm->vcpu.kvm->arch;
1330 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1331 phys_addr_t lpa = __sme_set(page_to_phys(vm_data->avic_logical_id_table_page));
1332 phys_addr_t ppa = __sme_set(page_to_phys(vm_data->avic_physical_id_table_page));
1334 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1335 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1336 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1337 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1338 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1341 static void init_vmcb(struct vcpu_svm *svm)
1343 struct vmcb_control_area *control = &svm->vmcb->control;
1344 struct vmcb_save_area *save = &svm->vmcb->save;
1346 svm->vcpu.arch.hflags = 0;
1348 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1349 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1350 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1351 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1352 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1353 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1354 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1355 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1357 set_dr_intercepts(svm);
1359 set_exception_intercept(svm, PF_VECTOR);
1360 set_exception_intercept(svm, UD_VECTOR);
1361 set_exception_intercept(svm, MC_VECTOR);
1362 set_exception_intercept(svm, AC_VECTOR);
1363 set_exception_intercept(svm, DB_VECTOR);
1365 set_intercept(svm, INTERCEPT_INTR);
1366 set_intercept(svm, INTERCEPT_NMI);
1367 set_intercept(svm, INTERCEPT_SMI);
1368 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1369 set_intercept(svm, INTERCEPT_RDPMC);
1370 set_intercept(svm, INTERCEPT_CPUID);
1371 set_intercept(svm, INTERCEPT_INVD);
1372 set_intercept(svm, INTERCEPT_HLT);
1373 set_intercept(svm, INTERCEPT_INVLPG);
1374 set_intercept(svm, INTERCEPT_INVLPGA);
1375 set_intercept(svm, INTERCEPT_IOIO_PROT);
1376 set_intercept(svm, INTERCEPT_MSR_PROT);
1377 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1378 set_intercept(svm, INTERCEPT_SHUTDOWN);
1379 set_intercept(svm, INTERCEPT_VMRUN);
1380 set_intercept(svm, INTERCEPT_VMMCALL);
1381 set_intercept(svm, INTERCEPT_VMLOAD);
1382 set_intercept(svm, INTERCEPT_VMSAVE);
1383 set_intercept(svm, INTERCEPT_STGI);
1384 set_intercept(svm, INTERCEPT_CLGI);
1385 set_intercept(svm, INTERCEPT_SKINIT);
1386 set_intercept(svm, INTERCEPT_WBINVD);
1387 set_intercept(svm, INTERCEPT_XSETBV);
1388 set_intercept(svm, INTERCEPT_RSM);
1390 if (!kvm_mwait_in_guest()) {
1391 set_intercept(svm, INTERCEPT_MONITOR);
1392 set_intercept(svm, INTERCEPT_MWAIT);
1395 control->iopm_base_pa = __sme_set(iopm_base);
1396 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1397 control->int_ctl = V_INTR_MASKING_MASK;
1399 init_seg(&save->es);
1400 init_seg(&save->ss);
1401 init_seg(&save->ds);
1402 init_seg(&save->fs);
1403 init_seg(&save->gs);
1405 save->cs.selector = 0xf000;
1406 save->cs.base = 0xffff0000;
1407 /* Executable/Readable Code Segment */
1408 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1409 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1410 save->cs.limit = 0xffff;
1412 save->gdtr.limit = 0xffff;
1413 save->idtr.limit = 0xffff;
1415 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1416 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1418 svm_set_efer(&svm->vcpu, 0);
1419 save->dr6 = 0xffff0ff0;
1420 kvm_set_rflags(&svm->vcpu, 2);
1421 save->rip = 0x0000fff0;
1422 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1425 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1426 * It also updates the guest-visible cr0 value.
1428 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1429 kvm_mmu_reset_context(&svm->vcpu);
1431 save->cr4 = X86_CR4_PAE;
1435 /* Setup VMCB for Nested Paging */
1436 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1437 clr_intercept(svm, INTERCEPT_INVLPG);
1438 clr_exception_intercept(svm, PF_VECTOR);
1439 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1440 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1441 save->g_pat = svm->vcpu.arch.pat;
1445 svm->asid_generation = 0;
1447 svm->nested.vmcb = 0;
1448 svm->vcpu.arch.hflags = 0;
1450 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1451 control->pause_filter_count = 3000;
1452 set_intercept(svm, INTERCEPT_PAUSE);
1455 if (kvm_vcpu_apicv_active(&svm->vcpu))
1456 avic_init_vmcb(svm);
1459 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1460 * in VMCB and clear intercepts to avoid #VMEXIT.
1463 clr_intercept(svm, INTERCEPT_VMLOAD);
1464 clr_intercept(svm, INTERCEPT_VMSAVE);
1465 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1469 clr_intercept(svm, INTERCEPT_STGI);
1470 clr_intercept(svm, INTERCEPT_CLGI);
1471 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1474 if (sev_guest(svm->vcpu.kvm)) {
1475 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1476 clr_exception_intercept(svm, UD_VECTOR);
1479 mark_all_dirty(svm->vmcb);
1485 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1488 u64 *avic_physical_id_table;
1489 struct kvm_arch *vm_data = &vcpu->kvm->arch;
1491 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1494 avic_physical_id_table = page_address(vm_data->avic_physical_id_table_page);
1496 return &avic_physical_id_table[index];
1501 * AVIC hardware walks the nested page table to check permissions,
1502 * but does not use the SPA address specified in the leaf page
1503 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1504 * field of the VMCB. Therefore, we set up the
1505 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1507 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1509 struct kvm *kvm = vcpu->kvm;
1512 if (kvm->arch.apic_access_page_done)
1515 ret = x86_set_memory_region(kvm,
1516 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1517 APIC_DEFAULT_PHYS_BASE,
1522 kvm->arch.apic_access_page_done = true;
1526 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1529 u64 *entry, new_entry;
1530 int id = vcpu->vcpu_id;
1531 struct vcpu_svm *svm = to_svm(vcpu);
1533 ret = avic_init_access_page(vcpu);
1537 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1540 if (!svm->vcpu.arch.apic->regs)
1543 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1545 /* Setting AVIC backing page address in the phy APIC ID table */
1546 entry = avic_get_physical_id_entry(vcpu, id);
1550 new_entry = READ_ONCE(*entry);
1551 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1552 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1553 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1554 WRITE_ONCE(*entry, new_entry);
1556 svm->avic_physical_id_cache = entry;
1561 static void __sev_asid_free(int asid)
1563 struct svm_cpu_data *sd;
1567 clear_bit(pos, sev_asid_bitmap);
1569 for_each_possible_cpu(cpu) {
1570 sd = per_cpu(svm_data, cpu);
1571 sd->sev_vmcbs[pos] = NULL;
1575 static void sev_asid_free(struct kvm *kvm)
1577 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1579 __sev_asid_free(sev->asid);
1582 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1584 struct sev_data_decommission *decommission;
1585 struct sev_data_deactivate *data;
1590 data = kzalloc(sizeof(*data), GFP_KERNEL);
1594 /* deactivate handle */
1595 data->handle = handle;
1596 sev_guest_deactivate(data, NULL);
1598 wbinvd_on_all_cpus();
1599 sev_guest_df_flush(NULL);
1602 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1606 /* decommission handle */
1607 decommission->handle = handle;
1608 sev_guest_decommission(decommission, NULL);
1610 kfree(decommission);
1613 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1614 unsigned long ulen, unsigned long *n,
1617 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1618 unsigned long npages, npinned, size;
1619 unsigned long locked, lock_limit;
1620 struct page **pages;
1623 /* Calculate number of pages. */
1624 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1625 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1626 npages = (last - first + 1);
1628 locked = sev->pages_locked + npages;
1629 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1630 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1631 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1635 /* Avoid using vmalloc for smaller buffers. */
1636 size = npages * sizeof(struct page *);
1637 if (size > PAGE_SIZE)
1638 pages = vmalloc(size);
1640 pages = kmalloc(size, GFP_KERNEL);
1645 /* Pin the user virtual address. */
1646 npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1647 if (npinned != npages) {
1648 pr_err("SEV: Failure locking %lu pages.\n", npages);
1653 sev->pages_locked = locked;
1659 release_pages(pages, npinned);
1665 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1666 unsigned long npages)
1668 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1670 release_pages(pages, npages);
1672 sev->pages_locked -= npages;
1675 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1677 uint8_t *page_virtual;
1680 if (npages == 0 || pages == NULL)
1683 for (i = 0; i < npages; i++) {
1684 page_virtual = kmap_atomic(pages[i]);
1685 clflush_cache_range(page_virtual, PAGE_SIZE);
1686 kunmap_atomic(page_virtual);
1690 static void __unregister_enc_region_locked(struct kvm *kvm,
1691 struct enc_region *region)
1694 * The guest may change the memory encryption attribute from C=0 -> C=1
1695 * or vice versa for this memory range. Lets make sure caches are
1696 * flushed to ensure that guest data gets written into memory with
1699 sev_clflush_pages(region->pages, region->npages);
1701 sev_unpin_memory(kvm, region->pages, region->npages);
1702 list_del(®ion->list);
1706 static void sev_vm_destroy(struct kvm *kvm)
1708 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1709 struct list_head *head = &sev->regions_list;
1710 struct list_head *pos, *q;
1712 if (!sev_guest(kvm))
1715 mutex_lock(&kvm->lock);
1718 * if userspace was terminated before unregistering the memory regions
1719 * then lets unpin all the registered memory.
1721 if (!list_empty(head)) {
1722 list_for_each_safe(pos, q, head) {
1723 __unregister_enc_region_locked(kvm,
1724 list_entry(pos, struct enc_region, list));
1728 mutex_unlock(&kvm->lock);
1730 sev_unbind_asid(kvm, sev->handle);
1734 static void avic_vm_destroy(struct kvm *kvm)
1736 unsigned long flags;
1737 struct kvm_arch *vm_data = &kvm->arch;
1742 if (vm_data->avic_logical_id_table_page)
1743 __free_page(vm_data->avic_logical_id_table_page);
1744 if (vm_data->avic_physical_id_table_page)
1745 __free_page(vm_data->avic_physical_id_table_page);
1747 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1748 hash_del(&vm_data->hnode);
1749 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1752 static void svm_vm_destroy(struct kvm *kvm)
1754 avic_vm_destroy(kvm);
1755 sev_vm_destroy(kvm);
1758 static int avic_vm_init(struct kvm *kvm)
1760 unsigned long flags;
1762 struct kvm_arch *vm_data = &kvm->arch;
1763 struct page *p_page;
1764 struct page *l_page;
1765 struct kvm_arch *ka;
1771 /* Allocating physical APIC ID table (4KB) */
1772 p_page = alloc_page(GFP_KERNEL);
1776 vm_data->avic_physical_id_table_page = p_page;
1777 clear_page(page_address(p_page));
1779 /* Allocating logical APIC ID table (4KB) */
1780 l_page = alloc_page(GFP_KERNEL);
1784 vm_data->avic_logical_id_table_page = l_page;
1785 clear_page(page_address(l_page));
1787 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1789 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1790 if (vm_id == 0) { /* id is 1-based, zero is not okay */
1791 next_vm_id_wrapped = 1;
1794 /* Is it still in use? Only possible if wrapped at least once */
1795 if (next_vm_id_wrapped) {
1796 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1797 struct kvm *k2 = container_of(ka, struct kvm, arch);
1798 struct kvm_arch *vd2 = &k2->arch;
1799 if (vd2->avic_vm_id == vm_id)
1803 vm_data->avic_vm_id = vm_id;
1804 hash_add(svm_vm_data_hash, &vm_data->hnode, vm_data->avic_vm_id);
1805 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1810 avic_vm_destroy(kvm);
1815 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1818 unsigned long flags;
1819 struct amd_svm_iommu_ir *ir;
1820 struct vcpu_svm *svm = to_svm(vcpu);
1822 if (!kvm_arch_has_assigned_device(vcpu->kvm))
1826 * Here, we go through the per-vcpu ir_list to update all existing
1827 * interrupt remapping table entry targeting this vcpu.
1829 spin_lock_irqsave(&svm->ir_list_lock, flags);
1831 if (list_empty(&svm->ir_list))
1834 list_for_each_entry(ir, &svm->ir_list, node) {
1835 ret = amd_iommu_update_ga(cpu, r, ir->data);
1840 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1844 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1847 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
1848 int h_physical_id = kvm_cpu_get_apicid(cpu);
1849 struct vcpu_svm *svm = to_svm(vcpu);
1851 if (!kvm_vcpu_apicv_active(vcpu))
1854 if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
1857 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1858 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1860 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1861 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1863 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1864 if (svm->avic_is_running)
1865 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1867 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1868 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
1869 svm->avic_is_running);
1872 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
1875 struct vcpu_svm *svm = to_svm(vcpu);
1877 if (!kvm_vcpu_apicv_active(vcpu))
1880 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1881 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
1882 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1884 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1885 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1889 * This function is called during VCPU halt/unhalt.
1891 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
1893 struct vcpu_svm *svm = to_svm(vcpu);
1895 svm->avic_is_running = is_run;
1897 avic_vcpu_load(vcpu, vcpu->cpu);
1899 avic_vcpu_put(vcpu);
1902 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1904 struct vcpu_svm *svm = to_svm(vcpu);
1911 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1912 MSR_IA32_APICBASE_ENABLE;
1913 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1914 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1918 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
1919 kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1921 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1922 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1925 static int avic_init_vcpu(struct vcpu_svm *svm)
1929 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1932 ret = avic_init_backing_page(&svm->vcpu);
1936 INIT_LIST_HEAD(&svm->ir_list);
1937 spin_lock_init(&svm->ir_list_lock);
1942 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1944 struct vcpu_svm *svm;
1946 struct page *msrpm_pages;
1947 struct page *hsave_page;
1948 struct page *nested_msrpm_pages;
1951 svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1957 err = kvm_vcpu_init(&svm->vcpu, kvm, id);
1962 page = alloc_page(GFP_KERNEL);
1966 msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1970 nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1971 if (!nested_msrpm_pages)
1974 hsave_page = alloc_page(GFP_KERNEL);
1978 err = avic_init_vcpu(svm);
1982 /* We initialize this flag to true to make sure that the is_running
1983 * bit would be set the first time the vcpu is loaded.
1985 svm->avic_is_running = true;
1987 svm->nested.hsave = page_address(hsave_page);
1989 svm->msrpm = page_address(msrpm_pages);
1990 svm_vcpu_init_msrpm(svm->msrpm);
1992 svm->nested.msrpm = page_address(nested_msrpm_pages);
1993 svm_vcpu_init_msrpm(svm->nested.msrpm);
1995 svm->vmcb = page_address(page);
1996 clear_page(svm->vmcb);
1997 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
1998 svm->asid_generation = 0;
2001 svm_init_osvw(&svm->vcpu);
2006 __free_page(hsave_page);
2008 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2010 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2014 kvm_vcpu_uninit(&svm->vcpu);
2016 kmem_cache_free(kvm_vcpu_cache, svm);
2018 return ERR_PTR(err);
2021 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2023 struct vcpu_svm *svm = to_svm(vcpu);
2025 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2026 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2027 __free_page(virt_to_page(svm->nested.hsave));
2028 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2029 kvm_vcpu_uninit(vcpu);
2030 kmem_cache_free(kvm_vcpu_cache, svm);
2032 * The vmcb page can be recycled, causing a false negative in
2033 * svm_vcpu_load(). So do a full IBPB now.
2035 indirect_branch_prediction_barrier();
2038 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2040 struct vcpu_svm *svm = to_svm(vcpu);
2041 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2044 if (unlikely(cpu != vcpu->cpu)) {
2045 svm->asid_generation = 0;
2046 mark_all_dirty(svm->vmcb);
2049 #ifdef CONFIG_X86_64
2050 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2052 savesegment(fs, svm->host.fs);
2053 savesegment(gs, svm->host.gs);
2054 svm->host.ldt = kvm_read_ldt();
2056 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2057 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2059 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2060 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2061 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2062 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2063 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2066 /* This assumes that the kernel never uses MSR_TSC_AUX */
2067 if (static_cpu_has(X86_FEATURE_RDTSCP))
2068 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2070 if (sd->current_vmcb != svm->vmcb) {
2071 sd->current_vmcb = svm->vmcb;
2072 indirect_branch_prediction_barrier();
2074 avic_vcpu_load(vcpu, cpu);
2077 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2079 struct vcpu_svm *svm = to_svm(vcpu);
2082 avic_vcpu_put(vcpu);
2084 ++vcpu->stat.host_state_reload;
2085 kvm_load_ldt(svm->host.ldt);
2086 #ifdef CONFIG_X86_64
2087 loadsegment(fs, svm->host.fs);
2088 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2089 load_gs_index(svm->host.gs);
2091 #ifdef CONFIG_X86_32_LAZY_GS
2092 loadsegment(gs, svm->host.gs);
2095 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2096 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2099 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2101 avic_set_running(vcpu, false);
2104 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2106 avic_set_running(vcpu, true);
2109 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2111 struct vcpu_svm *svm = to_svm(vcpu);
2112 unsigned long rflags = svm->vmcb->save.rflags;
2114 if (svm->nmi_singlestep) {
2115 /* Hide our flags if they were not set by the guest */
2116 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2117 rflags &= ~X86_EFLAGS_TF;
2118 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2119 rflags &= ~X86_EFLAGS_RF;
2124 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2126 if (to_svm(vcpu)->nmi_singlestep)
2127 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2130 * Any change of EFLAGS.VM is accompanied by a reload of SS
2131 * (caused by either a task switch or an inter-privilege IRET),
2132 * so we do not need to update the CPL here.
2134 to_svm(vcpu)->vmcb->save.rflags = rflags;
2137 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2140 case VCPU_EXREG_PDPTR:
2141 BUG_ON(!npt_enabled);
2142 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2149 static void svm_set_vintr(struct vcpu_svm *svm)
2151 set_intercept(svm, INTERCEPT_VINTR);
2154 static void svm_clear_vintr(struct vcpu_svm *svm)
2156 clr_intercept(svm, INTERCEPT_VINTR);
2159 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2161 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2164 case VCPU_SREG_CS: return &save->cs;
2165 case VCPU_SREG_DS: return &save->ds;
2166 case VCPU_SREG_ES: return &save->es;
2167 case VCPU_SREG_FS: return &save->fs;
2168 case VCPU_SREG_GS: return &save->gs;
2169 case VCPU_SREG_SS: return &save->ss;
2170 case VCPU_SREG_TR: return &save->tr;
2171 case VCPU_SREG_LDTR: return &save->ldtr;
2177 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2179 struct vmcb_seg *s = svm_seg(vcpu, seg);
2184 static void svm_get_segment(struct kvm_vcpu *vcpu,
2185 struct kvm_segment *var, int seg)
2187 struct vmcb_seg *s = svm_seg(vcpu, seg);
2189 var->base = s->base;
2190 var->limit = s->limit;
2191 var->selector = s->selector;
2192 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2193 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2194 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2195 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2196 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2197 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2198 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2201 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2202 * However, the SVM spec states that the G bit is not observed by the
2203 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2204 * So let's synthesize a legal G bit for all segments, this helps
2205 * running KVM nested. It also helps cross-vendor migration, because
2206 * Intel's vmentry has a check on the 'G' bit.
2208 var->g = s->limit > 0xfffff;
2211 * AMD's VMCB does not have an explicit unusable field, so emulate it
2212 * for cross vendor migration purposes by "not present"
2214 var->unusable = !var->present;
2219 * Work around a bug where the busy flag in the tr selector
2229 * The accessed bit must always be set in the segment
2230 * descriptor cache, although it can be cleared in the
2231 * descriptor, the cached bit always remains at 1. Since
2232 * Intel has a check on this, set it here to support
2233 * cross-vendor migration.
2240 * On AMD CPUs sometimes the DB bit in the segment
2241 * descriptor is left as 1, although the whole segment has
2242 * been made unusable. Clear it here to pass an Intel VMX
2243 * entry check when cross vendor migrating.
2247 /* This is symmetric with svm_set_segment() */
2248 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2253 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2255 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2260 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2262 struct vcpu_svm *svm = to_svm(vcpu);
2264 dt->size = svm->vmcb->save.idtr.limit;
2265 dt->address = svm->vmcb->save.idtr.base;
2268 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2270 struct vcpu_svm *svm = to_svm(vcpu);
2272 svm->vmcb->save.idtr.limit = dt->size;
2273 svm->vmcb->save.idtr.base = dt->address ;
2274 mark_dirty(svm->vmcb, VMCB_DT);
2277 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2279 struct vcpu_svm *svm = to_svm(vcpu);
2281 dt->size = svm->vmcb->save.gdtr.limit;
2282 dt->address = svm->vmcb->save.gdtr.base;
2285 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2287 struct vcpu_svm *svm = to_svm(vcpu);
2289 svm->vmcb->save.gdtr.limit = dt->size;
2290 svm->vmcb->save.gdtr.base = dt->address ;
2291 mark_dirty(svm->vmcb, VMCB_DT);
2294 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2298 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2302 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2306 static void update_cr0_intercept(struct vcpu_svm *svm)
2308 ulong gcr0 = svm->vcpu.arch.cr0;
2309 u64 *hcr0 = &svm->vmcb->save.cr0;
2311 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2312 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2314 mark_dirty(svm->vmcb, VMCB_CR);
2316 if (gcr0 == *hcr0) {
2317 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2318 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2320 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2321 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2325 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2327 struct vcpu_svm *svm = to_svm(vcpu);
2329 #ifdef CONFIG_X86_64
2330 if (vcpu->arch.efer & EFER_LME) {
2331 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2332 vcpu->arch.efer |= EFER_LMA;
2333 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2336 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2337 vcpu->arch.efer &= ~EFER_LMA;
2338 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2342 vcpu->arch.cr0 = cr0;
2345 cr0 |= X86_CR0_PG | X86_CR0_WP;
2348 * re-enable caching here because the QEMU bios
2349 * does not do it - this results in some delay at
2352 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2353 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2354 svm->vmcb->save.cr0 = cr0;
2355 mark_dirty(svm->vmcb, VMCB_CR);
2356 update_cr0_intercept(svm);
2359 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2361 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2362 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2364 if (cr4 & X86_CR4_VMXE)
2367 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2368 svm_flush_tlb(vcpu, true);
2370 vcpu->arch.cr4 = cr4;
2373 cr4 |= host_cr4_mce;
2374 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2375 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2379 static void svm_set_segment(struct kvm_vcpu *vcpu,
2380 struct kvm_segment *var, int seg)
2382 struct vcpu_svm *svm = to_svm(vcpu);
2383 struct vmcb_seg *s = svm_seg(vcpu, seg);
2385 s->base = var->base;
2386 s->limit = var->limit;
2387 s->selector = var->selector;
2388 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2389 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2390 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2391 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2392 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2393 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2394 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2395 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2398 * This is always accurate, except if SYSRET returned to a segment
2399 * with SS.DPL != 3. Intel does not have this quirk, and always
2400 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2401 * would entail passing the CPL to userspace and back.
2403 if (seg == VCPU_SREG_SS)
2404 /* This is symmetric with svm_get_segment() */
2405 svm->vmcb->save.cpl = (var->dpl & 3);
2407 mark_dirty(svm->vmcb, VMCB_SEG);
2410 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2412 struct vcpu_svm *svm = to_svm(vcpu);
2414 clr_exception_intercept(svm, BP_VECTOR);
2416 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2417 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2418 set_exception_intercept(svm, BP_VECTOR);
2420 vcpu->guest_debug = 0;
2423 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2425 if (sd->next_asid > sd->max_asid) {
2426 ++sd->asid_generation;
2427 sd->next_asid = sd->min_asid;
2428 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2431 svm->asid_generation = sd->asid_generation;
2432 svm->vmcb->control.asid = sd->next_asid++;
2434 mark_dirty(svm->vmcb, VMCB_ASID);
2437 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2439 return to_svm(vcpu)->vmcb->save.dr6;
2442 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2444 struct vcpu_svm *svm = to_svm(vcpu);
2446 svm->vmcb->save.dr6 = value;
2447 mark_dirty(svm->vmcb, VMCB_DR);
2450 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2452 struct vcpu_svm *svm = to_svm(vcpu);
2454 get_debugreg(vcpu->arch.db[0], 0);
2455 get_debugreg(vcpu->arch.db[1], 1);
2456 get_debugreg(vcpu->arch.db[2], 2);
2457 get_debugreg(vcpu->arch.db[3], 3);
2458 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2459 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2461 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2462 set_dr_intercepts(svm);
2465 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2467 struct vcpu_svm *svm = to_svm(vcpu);
2469 svm->vmcb->save.dr7 = value;
2470 mark_dirty(svm->vmcb, VMCB_DR);
2473 static int pf_interception(struct vcpu_svm *svm)
2475 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2476 u64 error_code = svm->vmcb->control.exit_info_1;
2478 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2479 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2480 svm->vmcb->control.insn_bytes : NULL,
2481 svm->vmcb->control.insn_len);
2484 static int npf_interception(struct vcpu_svm *svm)
2486 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2487 u64 error_code = svm->vmcb->control.exit_info_1;
2489 trace_kvm_page_fault(fault_address, error_code);
2490 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2491 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2492 svm->vmcb->control.insn_bytes : NULL,
2493 svm->vmcb->control.insn_len);
2496 static int db_interception(struct vcpu_svm *svm)
2498 struct kvm_run *kvm_run = svm->vcpu.run;
2500 if (!(svm->vcpu.guest_debug &
2501 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2502 !svm->nmi_singlestep) {
2503 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2507 if (svm->nmi_singlestep) {
2508 disable_nmi_singlestep(svm);
2511 if (svm->vcpu.guest_debug &
2512 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2513 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2514 kvm_run->debug.arch.pc =
2515 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2516 kvm_run->debug.arch.exception = DB_VECTOR;
2523 static int bp_interception(struct vcpu_svm *svm)
2525 struct kvm_run *kvm_run = svm->vcpu.run;
2527 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2528 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2529 kvm_run->debug.arch.exception = BP_VECTOR;
2533 static int ud_interception(struct vcpu_svm *svm)
2537 er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
2538 if (er == EMULATE_USER_EXIT)
2540 if (er != EMULATE_DONE)
2541 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2545 static int ac_interception(struct vcpu_svm *svm)
2547 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2551 static bool is_erratum_383(void)
2556 if (!erratum_383_found)
2559 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2563 /* Bit 62 may or may not be set for this mce */
2564 value &= ~(1ULL << 62);
2566 if (value != 0xb600000000010015ULL)
2569 /* Clear MCi_STATUS registers */
2570 for (i = 0; i < 6; ++i)
2571 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2573 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2577 value &= ~(1ULL << 2);
2578 low = lower_32_bits(value);
2579 high = upper_32_bits(value);
2581 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2584 /* Flush tlb to evict multi-match entries */
2590 static void svm_handle_mce(struct vcpu_svm *svm)
2592 if (is_erratum_383()) {
2594 * Erratum 383 triggered. Guest state is corrupt so kill the
2597 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2599 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2605 * On an #MC intercept the MCE handler is not called automatically in
2606 * the host. So do it by hand here.
2610 /* not sure if we ever come back to this point */
2615 static int mc_interception(struct vcpu_svm *svm)
2620 static int shutdown_interception(struct vcpu_svm *svm)
2622 struct kvm_run *kvm_run = svm->vcpu.run;
2625 * VMCB is undefined after a SHUTDOWN intercept
2626 * so reinitialize it.
2628 clear_page(svm->vmcb);
2631 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2635 static int io_interception(struct vcpu_svm *svm)
2637 struct kvm_vcpu *vcpu = &svm->vcpu;
2638 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2639 int size, in, string, ret;
2642 ++svm->vcpu.stat.io_exits;
2643 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2644 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2646 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2648 port = io_info >> 16;
2649 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2650 svm->next_rip = svm->vmcb->control.exit_info_2;
2651 ret = kvm_skip_emulated_instruction(&svm->vcpu);
2654 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
2655 * KVM_EXIT_DEBUG here.
2658 return kvm_fast_pio_in(vcpu, size, port) && ret;
2660 return kvm_fast_pio_out(vcpu, size, port) && ret;
2663 static int nmi_interception(struct vcpu_svm *svm)
2668 static int intr_interception(struct vcpu_svm *svm)
2670 ++svm->vcpu.stat.irq_exits;
2674 static int nop_on_interception(struct vcpu_svm *svm)
2679 static int halt_interception(struct vcpu_svm *svm)
2681 svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2682 return kvm_emulate_halt(&svm->vcpu);
2685 static int vmmcall_interception(struct vcpu_svm *svm)
2687 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2688 return kvm_emulate_hypercall(&svm->vcpu);
2691 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2693 struct vcpu_svm *svm = to_svm(vcpu);
2695 return svm->nested.nested_cr3;
2698 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2700 struct vcpu_svm *svm = to_svm(vcpu);
2701 u64 cr3 = svm->nested.nested_cr3;
2705 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2706 offset_in_page(cr3) + index * 8, 8);
2712 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2715 struct vcpu_svm *svm = to_svm(vcpu);
2717 svm->vmcb->control.nested_cr3 = __sme_set(root);
2718 mark_dirty(svm->vmcb, VMCB_NPT);
2719 svm_flush_tlb(vcpu, true);
2722 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2723 struct x86_exception *fault)
2725 struct vcpu_svm *svm = to_svm(vcpu);
2727 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2729 * TODO: track the cause of the nested page fault, and
2730 * correctly fill in the high bits of exit_info_1.
2732 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2733 svm->vmcb->control.exit_code_hi = 0;
2734 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2735 svm->vmcb->control.exit_info_2 = fault->address;
2738 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2739 svm->vmcb->control.exit_info_1 |= fault->error_code;
2742 * The present bit is always zero for page structure faults on real
2745 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2746 svm->vmcb->control.exit_info_1 &= ~1;
2748 nested_svm_vmexit(svm);
2751 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2753 WARN_ON(mmu_is_nested(vcpu));
2754 kvm_init_shadow_mmu(vcpu);
2755 vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
2756 vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
2757 vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr;
2758 vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2759 vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2760 reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2761 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2764 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2766 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2769 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2771 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2772 !is_paging(&svm->vcpu)) {
2773 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2777 if (svm->vmcb->save.cpl) {
2778 kvm_inject_gp(&svm->vcpu, 0);
2785 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2786 bool has_error_code, u32 error_code)
2790 if (!is_guest_mode(&svm->vcpu))
2793 vmexit = nested_svm_intercept(svm);
2794 if (vmexit != NESTED_EXIT_DONE)
2797 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2798 svm->vmcb->control.exit_code_hi = 0;
2799 svm->vmcb->control.exit_info_1 = error_code;
2802 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2803 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2804 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2805 * written only when inject_pending_event runs (DR6 would written here
2806 * too). This should be conditional on a new capability---if the
2807 * capability is disabled, kvm_multiple_exception would write the
2808 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2810 if (svm->vcpu.arch.exception.nested_apf)
2811 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2813 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2815 svm->nested.exit_required = true;
2819 /* This function returns true if it is save to enable the irq window */
2820 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2822 if (!is_guest_mode(&svm->vcpu))
2825 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2828 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2832 * if vmexit was already requested (by intercepted exception
2833 * for instance) do not overwrite it with "external interrupt"
2836 if (svm->nested.exit_required)
2839 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
2840 svm->vmcb->control.exit_info_1 = 0;
2841 svm->vmcb->control.exit_info_2 = 0;
2843 if (svm->nested.intercept & 1ULL) {
2845 * The #vmexit can't be emulated here directly because this
2846 * code path runs with irqs and preemption disabled. A
2847 * #vmexit emulation might sleep. Only signal request for
2850 svm->nested.exit_required = true;
2851 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2858 /* This function returns true if it is save to enable the nmi window */
2859 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2861 if (!is_guest_mode(&svm->vcpu))
2864 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2867 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2868 svm->nested.exit_required = true;
2873 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2879 page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2880 if (is_error_page(page))
2888 kvm_inject_gp(&svm->vcpu, 0);
2893 static void nested_svm_unmap(struct page *page)
2896 kvm_release_page_dirty(page);
2899 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2901 unsigned port, size, iopm_len;
2906 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2907 return NESTED_EXIT_HOST;
2909 port = svm->vmcb->control.exit_info_1 >> 16;
2910 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2911 SVM_IOIO_SIZE_SHIFT;
2912 gpa = svm->nested.vmcb_iopm + (port / 8);
2913 start_bit = port % 8;
2914 iopm_len = (start_bit + size > 8) ? 2 : 1;
2915 mask = (0xf >> (4 - size)) << start_bit;
2918 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2919 return NESTED_EXIT_DONE;
2921 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2924 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2926 u32 offset, msr, value;
2929 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2930 return NESTED_EXIT_HOST;
2932 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2933 offset = svm_msrpm_offset(msr);
2934 write = svm->vmcb->control.exit_info_1 & 1;
2935 mask = 1 << ((2 * (msr & 0xf)) + write);
2937 if (offset == MSR_INVALID)
2938 return NESTED_EXIT_DONE;
2940 /* Offset is in 32 bit units but need in 8 bit units */
2943 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
2944 return NESTED_EXIT_DONE;
2946 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2949 /* DB exceptions for our internal use must not cause vmexit */
2950 static int nested_svm_intercept_db(struct vcpu_svm *svm)
2954 /* if we're not singlestepping, it's not ours */
2955 if (!svm->nmi_singlestep)
2956 return NESTED_EXIT_DONE;
2958 /* if it's not a singlestep exception, it's not ours */
2959 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
2960 return NESTED_EXIT_DONE;
2961 if (!(dr6 & DR6_BS))
2962 return NESTED_EXIT_DONE;
2964 /* if the guest is singlestepping, it should get the vmexit */
2965 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
2966 disable_nmi_singlestep(svm);
2967 return NESTED_EXIT_DONE;
2970 /* it's ours, the nested hypervisor must not see this one */
2971 return NESTED_EXIT_HOST;
2974 static int nested_svm_exit_special(struct vcpu_svm *svm)
2976 u32 exit_code = svm->vmcb->control.exit_code;
2978 switch (exit_code) {
2981 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
2982 return NESTED_EXIT_HOST;
2984 /* For now we are always handling NPFs when using them */
2986 return NESTED_EXIT_HOST;
2988 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
2989 /* When we're shadowing, trap PFs, but not async PF */
2990 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
2991 return NESTED_EXIT_HOST;
2997 return NESTED_EXIT_CONTINUE;
3001 * If this function returns true, this #vmexit was already handled
3003 static int nested_svm_intercept(struct vcpu_svm *svm)
3005 u32 exit_code = svm->vmcb->control.exit_code;
3006 int vmexit = NESTED_EXIT_HOST;
3008 switch (exit_code) {
3010 vmexit = nested_svm_exit_handled_msr(svm);
3013 vmexit = nested_svm_intercept_ioio(svm);
3015 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3016 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3017 if (svm->nested.intercept_cr & bit)
3018 vmexit = NESTED_EXIT_DONE;
3021 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3022 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3023 if (svm->nested.intercept_dr & bit)
3024 vmexit = NESTED_EXIT_DONE;
3027 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3028 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3029 if (svm->nested.intercept_exceptions & excp_bits) {
3030 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3031 vmexit = nested_svm_intercept_db(svm);
3033 vmexit = NESTED_EXIT_DONE;
3035 /* async page fault always cause vmexit */
3036 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3037 svm->vcpu.arch.exception.nested_apf != 0)
3038 vmexit = NESTED_EXIT_DONE;
3041 case SVM_EXIT_ERR: {
3042 vmexit = NESTED_EXIT_DONE;
3046 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3047 if (svm->nested.intercept & exit_bits)
3048 vmexit = NESTED_EXIT_DONE;
3055 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3059 vmexit = nested_svm_intercept(svm);
3061 if (vmexit == NESTED_EXIT_DONE)
3062 nested_svm_vmexit(svm);
3067 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3069 struct vmcb_control_area *dst = &dst_vmcb->control;
3070 struct vmcb_control_area *from = &from_vmcb->control;
3072 dst->intercept_cr = from->intercept_cr;
3073 dst->intercept_dr = from->intercept_dr;
3074 dst->intercept_exceptions = from->intercept_exceptions;
3075 dst->intercept = from->intercept;
3076 dst->iopm_base_pa = from->iopm_base_pa;
3077 dst->msrpm_base_pa = from->msrpm_base_pa;
3078 dst->tsc_offset = from->tsc_offset;
3079 dst->asid = from->asid;
3080 dst->tlb_ctl = from->tlb_ctl;
3081 dst->int_ctl = from->int_ctl;
3082 dst->int_vector = from->int_vector;
3083 dst->int_state = from->int_state;
3084 dst->exit_code = from->exit_code;
3085 dst->exit_code_hi = from->exit_code_hi;
3086 dst->exit_info_1 = from->exit_info_1;
3087 dst->exit_info_2 = from->exit_info_2;
3088 dst->exit_int_info = from->exit_int_info;
3089 dst->exit_int_info_err = from->exit_int_info_err;
3090 dst->nested_ctl = from->nested_ctl;
3091 dst->event_inj = from->event_inj;
3092 dst->event_inj_err = from->event_inj_err;
3093 dst->nested_cr3 = from->nested_cr3;
3094 dst->virt_ext = from->virt_ext;
3097 static int nested_svm_vmexit(struct vcpu_svm *svm)
3099 struct vmcb *nested_vmcb;
3100 struct vmcb *hsave = svm->nested.hsave;
3101 struct vmcb *vmcb = svm->vmcb;
3104 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3105 vmcb->control.exit_info_1,
3106 vmcb->control.exit_info_2,
3107 vmcb->control.exit_int_info,
3108 vmcb->control.exit_int_info_err,
3111 nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3115 /* Exit Guest-Mode */
3116 leave_guest_mode(&svm->vcpu);
3117 svm->nested.vmcb = 0;
3119 /* Give the current vmcb to the guest */
3122 nested_vmcb->save.es = vmcb->save.es;
3123 nested_vmcb->save.cs = vmcb->save.cs;
3124 nested_vmcb->save.ss = vmcb->save.ss;
3125 nested_vmcb->save.ds = vmcb->save.ds;
3126 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3127 nested_vmcb->save.idtr = vmcb->save.idtr;
3128 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3129 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3130 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3131 nested_vmcb->save.cr2 = vmcb->save.cr2;
3132 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3133 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3134 nested_vmcb->save.rip = vmcb->save.rip;
3135 nested_vmcb->save.rsp = vmcb->save.rsp;
3136 nested_vmcb->save.rax = vmcb->save.rax;
3137 nested_vmcb->save.dr7 = vmcb->save.dr7;
3138 nested_vmcb->save.dr6 = vmcb->save.dr6;
3139 nested_vmcb->save.cpl = vmcb->save.cpl;
3141 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3142 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3143 nested_vmcb->control.int_state = vmcb->control.int_state;
3144 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3145 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3146 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3147 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3148 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3149 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3151 if (svm->nrips_enabled)
3152 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3155 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3156 * to make sure that we do not lose injected events. So check event_inj
3157 * here and copy it to exit_int_info if it is valid.
3158 * Exit_int_info and event_inj can't be both valid because the case
3159 * below only happens on a VMRUN instruction intercept which has
3160 * no valid exit_int_info set.
3162 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3163 struct vmcb_control_area *nc = &nested_vmcb->control;
3165 nc->exit_int_info = vmcb->control.event_inj;
3166 nc->exit_int_info_err = vmcb->control.event_inj_err;
3169 nested_vmcb->control.tlb_ctl = 0;
3170 nested_vmcb->control.event_inj = 0;
3171 nested_vmcb->control.event_inj_err = 0;
3173 /* We always set V_INTR_MASKING and remember the old value in hflags */
3174 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3175 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3177 /* Restore the original control entries */
3178 copy_vmcb_control_area(vmcb, hsave);
3180 kvm_clear_exception_queue(&svm->vcpu);
3181 kvm_clear_interrupt_queue(&svm->vcpu);
3183 svm->nested.nested_cr3 = 0;
3185 /* Restore selected save entries */
3186 svm->vmcb->save.es = hsave->save.es;
3187 svm->vmcb->save.cs = hsave->save.cs;
3188 svm->vmcb->save.ss = hsave->save.ss;
3189 svm->vmcb->save.ds = hsave->save.ds;
3190 svm->vmcb->save.gdtr = hsave->save.gdtr;
3191 svm->vmcb->save.idtr = hsave->save.idtr;
3192 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3193 svm_set_efer(&svm->vcpu, hsave->save.efer);
3194 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3195 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3197 svm->vmcb->save.cr3 = hsave->save.cr3;
3198 svm->vcpu.arch.cr3 = hsave->save.cr3;
3200 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3202 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3203 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3204 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3205 svm->vmcb->save.dr7 = 0;
3206 svm->vmcb->save.cpl = 0;
3207 svm->vmcb->control.exit_int_info = 0;
3209 mark_all_dirty(svm->vmcb);
3211 nested_svm_unmap(page);
3213 nested_svm_uninit_mmu_context(&svm->vcpu);
3214 kvm_mmu_reset_context(&svm->vcpu);
3215 kvm_mmu_load(&svm->vcpu);
3220 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3223 * This function merges the msr permission bitmaps of kvm and the
3224 * nested vmcb. It is optimized in that it only merges the parts where
3225 * the kvm msr permission bitmap may contain zero bits
3229 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3232 for (i = 0; i < MSRPM_OFFSETS; i++) {
3236 if (msrpm_offsets[i] == 0xffffffff)
3239 p = msrpm_offsets[i];
3240 offset = svm->nested.vmcb_msrpm + (p * 4);
3242 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3245 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3248 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3253 static bool nested_vmcb_checks(struct vmcb *vmcb)
3255 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3258 if (vmcb->control.asid == 0)
3261 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3268 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3269 struct vmcb *nested_vmcb, struct page *page)
3271 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3272 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3274 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3276 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3277 kvm_mmu_unload(&svm->vcpu);
3278 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3279 nested_svm_init_mmu_context(&svm->vcpu);
3282 /* Load the nested guest state */
3283 svm->vmcb->save.es = nested_vmcb->save.es;
3284 svm->vmcb->save.cs = nested_vmcb->save.cs;
3285 svm->vmcb->save.ss = nested_vmcb->save.ss;
3286 svm->vmcb->save.ds = nested_vmcb->save.ds;
3287 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3288 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3289 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3290 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3291 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3292 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3294 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3295 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3297 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3299 /* Guest paging mode is active - reset mmu */
3300 kvm_mmu_reset_context(&svm->vcpu);
3302 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3303 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3304 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3305 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3307 /* In case we don't even reach vcpu_run, the fields are not updated */
3308 svm->vmcb->save.rax = nested_vmcb->save.rax;
3309 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3310 svm->vmcb->save.rip = nested_vmcb->save.rip;
3311 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3312 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3313 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3315 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3316 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3318 /* cache intercepts */
3319 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3320 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3321 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3322 svm->nested.intercept = nested_vmcb->control.intercept;
3324 svm_flush_tlb(&svm->vcpu, true);
3325 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3326 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3327 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3329 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3331 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3332 /* We only want the cr8 intercept bits of the guest */
3333 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3334 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3337 /* We don't want to see VMMCALLs from a nested guest */
3338 clr_intercept(svm, INTERCEPT_VMMCALL);
3340 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3341 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3342 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3343 svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
3344 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3345 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3347 nested_svm_unmap(page);
3349 /* Enter Guest-Mode */
3350 enter_guest_mode(&svm->vcpu);
3353 * Merge guest and host intercepts - must be called with vcpu in
3354 * guest-mode to take affect here
3356 recalc_intercepts(svm);
3358 svm->nested.vmcb = vmcb_gpa;
3362 mark_all_dirty(svm->vmcb);
3365 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3367 struct vmcb *nested_vmcb;
3368 struct vmcb *hsave = svm->nested.hsave;
3369 struct vmcb *vmcb = svm->vmcb;
3373 vmcb_gpa = svm->vmcb->save.rax;
3375 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3379 if (!nested_vmcb_checks(nested_vmcb)) {
3380 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3381 nested_vmcb->control.exit_code_hi = 0;
3382 nested_vmcb->control.exit_info_1 = 0;
3383 nested_vmcb->control.exit_info_2 = 0;
3385 nested_svm_unmap(page);
3390 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3391 nested_vmcb->save.rip,
3392 nested_vmcb->control.int_ctl,
3393 nested_vmcb->control.event_inj,
3394 nested_vmcb->control.nested_ctl);
3396 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3397 nested_vmcb->control.intercept_cr >> 16,
3398 nested_vmcb->control.intercept_exceptions,
3399 nested_vmcb->control.intercept);
3401 /* Clear internal status */
3402 kvm_clear_exception_queue(&svm->vcpu);
3403 kvm_clear_interrupt_queue(&svm->vcpu);
3406 * Save the old vmcb, so we don't need to pick what we save, but can
3407 * restore everything when a VMEXIT occurs
3409 hsave->save.es = vmcb->save.es;
3410 hsave->save.cs = vmcb->save.cs;
3411 hsave->save.ss = vmcb->save.ss;
3412 hsave->save.ds = vmcb->save.ds;
3413 hsave->save.gdtr = vmcb->save.gdtr;
3414 hsave->save.idtr = vmcb->save.idtr;
3415 hsave->save.efer = svm->vcpu.arch.efer;
3416 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3417 hsave->save.cr4 = svm->vcpu.arch.cr4;
3418 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3419 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3420 hsave->save.rsp = vmcb->save.rsp;
3421 hsave->save.rax = vmcb->save.rax;
3423 hsave->save.cr3 = vmcb->save.cr3;
3425 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3427 copy_vmcb_control_area(hsave, vmcb);
3429 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3434 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3436 to_vmcb->save.fs = from_vmcb->save.fs;
3437 to_vmcb->save.gs = from_vmcb->save.gs;
3438 to_vmcb->save.tr = from_vmcb->save.tr;
3439 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3440 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3441 to_vmcb->save.star = from_vmcb->save.star;
3442 to_vmcb->save.lstar = from_vmcb->save.lstar;
3443 to_vmcb->save.cstar = from_vmcb->save.cstar;
3444 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3445 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3446 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3447 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3450 static int vmload_interception(struct vcpu_svm *svm)
3452 struct vmcb *nested_vmcb;
3456 if (nested_svm_check_permissions(svm))
3459 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3463 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3464 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3466 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3467 nested_svm_unmap(page);
3472 static int vmsave_interception(struct vcpu_svm *svm)
3474 struct vmcb *nested_vmcb;
3478 if (nested_svm_check_permissions(svm))
3481 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3485 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3486 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3488 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3489 nested_svm_unmap(page);
3494 static int vmrun_interception(struct vcpu_svm *svm)
3496 if (nested_svm_check_permissions(svm))
3499 /* Save rip after vmrun instruction */
3500 kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3502 if (!nested_svm_vmrun(svm))
3505 if (!nested_svm_vmrun_msrpm(svm))
3512 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3513 svm->vmcb->control.exit_code_hi = 0;
3514 svm->vmcb->control.exit_info_1 = 0;
3515 svm->vmcb->control.exit_info_2 = 0;
3517 nested_svm_vmexit(svm);
3522 static int stgi_interception(struct vcpu_svm *svm)
3526 if (nested_svm_check_permissions(svm))
3530 * If VGIF is enabled, the STGI intercept is only added to
3531 * detect the opening of the SMI/NMI window; remove it now.
3533 if (vgif_enabled(svm))
3534 clr_intercept(svm, INTERCEPT_STGI);
3536 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3537 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3538 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3545 static int clgi_interception(struct vcpu_svm *svm)
3549 if (nested_svm_check_permissions(svm))
3552 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3553 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3557 /* After a CLGI no interrupts should come */
3558 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3559 svm_clear_vintr(svm);
3560 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3561 mark_dirty(svm->vmcb, VMCB_INTR);
3567 static int invlpga_interception(struct vcpu_svm *svm)
3569 struct kvm_vcpu *vcpu = &svm->vcpu;
3571 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3572 kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3574 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3575 kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3577 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3578 return kvm_skip_emulated_instruction(&svm->vcpu);
3581 static int skinit_interception(struct vcpu_svm *svm)
3583 trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3585 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3589 static int wbinvd_interception(struct vcpu_svm *svm)
3591 return kvm_emulate_wbinvd(&svm->vcpu);
3594 static int xsetbv_interception(struct vcpu_svm *svm)
3596 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3597 u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3599 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3600 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3601 return kvm_skip_emulated_instruction(&svm->vcpu);
3607 static int task_switch_interception(struct vcpu_svm *svm)
3611 int int_type = svm->vmcb->control.exit_int_info &
3612 SVM_EXITINTINFO_TYPE_MASK;
3613 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3615 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3617 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3618 bool has_error_code = false;
3621 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3623 if (svm->vmcb->control.exit_info_2 &
3624 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3625 reason = TASK_SWITCH_IRET;
3626 else if (svm->vmcb->control.exit_info_2 &
3627 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3628 reason = TASK_SWITCH_JMP;
3630 reason = TASK_SWITCH_GATE;
3632 reason = TASK_SWITCH_CALL;
3634 if (reason == TASK_SWITCH_GATE) {
3636 case SVM_EXITINTINFO_TYPE_NMI:
3637 svm->vcpu.arch.nmi_injected = false;
3639 case SVM_EXITINTINFO_TYPE_EXEPT:
3640 if (svm->vmcb->control.exit_info_2 &
3641 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3642 has_error_code = true;
3644 (u32)svm->vmcb->control.exit_info_2;
3646 kvm_clear_exception_queue(&svm->vcpu);
3648 case SVM_EXITINTINFO_TYPE_INTR:
3649 kvm_clear_interrupt_queue(&svm->vcpu);
3656 if (reason != TASK_SWITCH_GATE ||
3657 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3658 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3659 (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3660 skip_emulated_instruction(&svm->vcpu);
3662 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3665 if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3666 has_error_code, error_code) == EMULATE_FAIL) {
3667 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3668 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3669 svm->vcpu.run->internal.ndata = 0;
3675 static int cpuid_interception(struct vcpu_svm *svm)
3677 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3678 return kvm_emulate_cpuid(&svm->vcpu);
3681 static int iret_interception(struct vcpu_svm *svm)
3683 ++svm->vcpu.stat.nmi_window_exits;
3684 clr_intercept(svm, INTERCEPT_IRET);
3685 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3686 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3687 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3691 static int invlpg_interception(struct vcpu_svm *svm)
3693 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3694 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3696 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3697 return kvm_skip_emulated_instruction(&svm->vcpu);
3700 static int emulate_on_interception(struct vcpu_svm *svm)
3702 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3705 static int rsm_interception(struct vcpu_svm *svm)
3707 return x86_emulate_instruction(&svm->vcpu, 0, 0,
3708 rsm_ins_bytes, 2) == EMULATE_DONE;
3711 static int rdpmc_interception(struct vcpu_svm *svm)
3715 if (!static_cpu_has(X86_FEATURE_NRIPS))
3716 return emulate_on_interception(svm);
3718 err = kvm_rdpmc(&svm->vcpu);
3719 return kvm_complete_insn_gp(&svm->vcpu, err);
3722 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3725 unsigned long cr0 = svm->vcpu.arch.cr0;
3729 intercept = svm->nested.intercept;
3731 if (!is_guest_mode(&svm->vcpu) ||
3732 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3735 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3736 val &= ~SVM_CR0_SELECTIVE_MASK;
3739 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3740 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3746 #define CR_VALID (1ULL << 63)
3748 static int cr_interception(struct vcpu_svm *svm)
3754 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3755 return emulate_on_interception(svm);
3757 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3758 return emulate_on_interception(svm);
3760 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3761 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3762 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3764 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3767 if (cr >= 16) { /* mov to cr */
3769 val = kvm_register_read(&svm->vcpu, reg);
3772 if (!check_selective_cr0_intercepted(svm, val))
3773 err = kvm_set_cr0(&svm->vcpu, val);
3779 err = kvm_set_cr3(&svm->vcpu, val);
3782 err = kvm_set_cr4(&svm->vcpu, val);
3785 err = kvm_set_cr8(&svm->vcpu, val);
3788 WARN(1, "unhandled write to CR%d", cr);
3789 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3792 } else { /* mov from cr */
3795 val = kvm_read_cr0(&svm->vcpu);
3798 val = svm->vcpu.arch.cr2;
3801 val = kvm_read_cr3(&svm->vcpu);
3804 val = kvm_read_cr4(&svm->vcpu);
3807 val = kvm_get_cr8(&svm->vcpu);
3810 WARN(1, "unhandled read from CR%d", cr);
3811 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3814 kvm_register_write(&svm->vcpu, reg, val);
3816 return kvm_complete_insn_gp(&svm->vcpu, err);
3819 static int dr_interception(struct vcpu_svm *svm)
3824 if (svm->vcpu.guest_debug == 0) {
3826 * No more DR vmexits; force a reload of the debug registers
3827 * and reenter on this instruction. The next vmexit will
3828 * retrieve the full state of the debug registers.
3830 clr_dr_intercepts(svm);
3831 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
3835 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
3836 return emulate_on_interception(svm);
3838 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3839 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3841 if (dr >= 16) { /* mov to DRn */
3842 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3844 val = kvm_register_read(&svm->vcpu, reg);
3845 kvm_set_dr(&svm->vcpu, dr - 16, val);
3847 if (!kvm_require_dr(&svm->vcpu, dr))
3849 kvm_get_dr(&svm->vcpu, dr, &val);
3850 kvm_register_write(&svm->vcpu, reg, val);
3853 return kvm_skip_emulated_instruction(&svm->vcpu);
3856 static int cr8_write_interception(struct vcpu_svm *svm)
3858 struct kvm_run *kvm_run = svm->vcpu.run;
3861 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3862 /* instruction emulation calls kvm_set_cr8() */
3863 r = cr_interception(svm);
3864 if (lapic_in_kernel(&svm->vcpu))
3866 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3868 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3872 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3874 struct vcpu_svm *svm = to_svm(vcpu);
3876 switch (msr_info->index) {
3877 case MSR_IA32_TSC: {
3878 msr_info->data = svm->vmcb->control.tsc_offset +
3879 kvm_scale_tsc(vcpu, rdtsc());
3884 msr_info->data = svm->vmcb->save.star;
3886 #ifdef CONFIG_X86_64
3888 msr_info->data = svm->vmcb->save.lstar;
3891 msr_info->data = svm->vmcb->save.cstar;
3893 case MSR_KERNEL_GS_BASE:
3894 msr_info->data = svm->vmcb->save.kernel_gs_base;
3896 case MSR_SYSCALL_MASK:
3897 msr_info->data = svm->vmcb->save.sfmask;
3900 case MSR_IA32_SYSENTER_CS:
3901 msr_info->data = svm->vmcb->save.sysenter_cs;
3903 case MSR_IA32_SYSENTER_EIP:
3904 msr_info->data = svm->sysenter_eip;
3906 case MSR_IA32_SYSENTER_ESP:
3907 msr_info->data = svm->sysenter_esp;
3910 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3912 msr_info->data = svm->tsc_aux;
3915 * Nobody will change the following 5 values in the VMCB so we can
3916 * safely return them on rdmsr. They will always be 0 until LBRV is
3919 case MSR_IA32_DEBUGCTLMSR:
3920 msr_info->data = svm->vmcb->save.dbgctl;
3922 case MSR_IA32_LASTBRANCHFROMIP:
3923 msr_info->data = svm->vmcb->save.br_from;
3925 case MSR_IA32_LASTBRANCHTOIP:
3926 msr_info->data = svm->vmcb->save.br_to;
3928 case MSR_IA32_LASTINTFROMIP:
3929 msr_info->data = svm->vmcb->save.last_excp_from;
3931 case MSR_IA32_LASTINTTOIP:
3932 msr_info->data = svm->vmcb->save.last_excp_to;
3934 case MSR_VM_HSAVE_PA:
3935 msr_info->data = svm->nested.hsave_msr;
3938 msr_info->data = svm->nested.vm_cr_msr;
3940 case MSR_IA32_SPEC_CTRL:
3941 if (!msr_info->host_initiated &&
3942 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
3945 msr_info->data = svm->spec_ctrl;
3947 case MSR_IA32_UCODE_REV:
3948 msr_info->data = 0x01000065;
3950 case MSR_F15H_IC_CFG: {
3954 family = guest_cpuid_family(vcpu);
3955 model = guest_cpuid_model(vcpu);
3957 if (family < 0 || model < 0)
3958 return kvm_get_msr_common(vcpu, msr_info);
3962 if (family == 0x15 &&
3963 (model >= 0x2 && model < 0x20))
3964 msr_info->data = 0x1E;
3968 return kvm_get_msr_common(vcpu, msr_info);
3973 static int rdmsr_interception(struct vcpu_svm *svm)
3975 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3976 struct msr_data msr_info;
3978 msr_info.index = ecx;
3979 msr_info.host_initiated = false;
3980 if (svm_get_msr(&svm->vcpu, &msr_info)) {
3981 trace_kvm_msr_read_ex(ecx);
3982 kvm_inject_gp(&svm->vcpu, 0);
3985 trace_kvm_msr_read(ecx, msr_info.data);
3987 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
3988 msr_info.data & 0xffffffff);
3989 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
3990 msr_info.data >> 32);
3991 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3992 return kvm_skip_emulated_instruction(&svm->vcpu);
3996 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
3998 struct vcpu_svm *svm = to_svm(vcpu);
3999 int svm_dis, chg_mask;
4001 if (data & ~SVM_VM_CR_VALID_MASK)
4004 chg_mask = SVM_VM_CR_VALID_MASK;
4006 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4007 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4009 svm->nested.vm_cr_msr &= ~chg_mask;
4010 svm->nested.vm_cr_msr |= (data & chg_mask);
4012 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4014 /* check for svm_disable while efer.svme is set */
4015 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4021 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4023 struct vcpu_svm *svm = to_svm(vcpu);
4025 u32 ecx = msr->index;
4026 u64 data = msr->data;
4028 case MSR_IA32_CR_PAT:
4029 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4031 vcpu->arch.pat = data;
4032 svm->vmcb->save.g_pat = data;
4033 mark_dirty(svm->vmcb, VMCB_NPT);
4036 kvm_write_tsc(vcpu, msr);
4038 case MSR_IA32_SPEC_CTRL:
4039 if (!msr->host_initiated &&
4040 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
4043 /* The STIBP bit doesn't fault even if it's not advertised */
4044 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
4047 svm->spec_ctrl = data;
4054 * When it's written (to non-zero) for the first time, pass
4058 * The handling of the MSR bitmap for L2 guests is done in
4059 * nested_svm_vmrun_msrpm.
4060 * We update the L1 MSR bit as well since it will end up
4061 * touching the MSR anyway now.
4063 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4065 case MSR_IA32_PRED_CMD:
4066 if (!msr->host_initiated &&
4067 !guest_cpuid_has(vcpu, X86_FEATURE_IBPB))
4070 if (data & ~PRED_CMD_IBPB)
4076 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4077 if (is_guest_mode(vcpu))
4079 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4082 svm->vmcb->save.star = data;
4084 #ifdef CONFIG_X86_64
4086 svm->vmcb->save.lstar = data;
4089 svm->vmcb->save.cstar = data;
4091 case MSR_KERNEL_GS_BASE:
4092 svm->vmcb->save.kernel_gs_base = data;
4094 case MSR_SYSCALL_MASK:
4095 svm->vmcb->save.sfmask = data;
4098 case MSR_IA32_SYSENTER_CS:
4099 svm->vmcb->save.sysenter_cs = data;
4101 case MSR_IA32_SYSENTER_EIP:
4102 svm->sysenter_eip = data;
4103 svm->vmcb->save.sysenter_eip = data;
4105 case MSR_IA32_SYSENTER_ESP:
4106 svm->sysenter_esp = data;
4107 svm->vmcb->save.sysenter_esp = data;
4110 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4114 * This is rare, so we update the MSR here instead of using
4115 * direct_access_msrs. Doing that would require a rdmsr in
4118 svm->tsc_aux = data;
4119 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4121 case MSR_IA32_DEBUGCTLMSR:
4122 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4123 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4127 if (data & DEBUGCTL_RESERVED_BITS)
4130 svm->vmcb->save.dbgctl = data;
4131 mark_dirty(svm->vmcb, VMCB_LBR);
4132 if (data & (1ULL<<0))
4133 svm_enable_lbrv(svm);
4135 svm_disable_lbrv(svm);
4137 case MSR_VM_HSAVE_PA:
4138 svm->nested.hsave_msr = data;
4141 return svm_set_vm_cr(vcpu, data);
4143 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4145 case MSR_IA32_APICBASE:
4146 if (kvm_vcpu_apicv_active(vcpu))
4147 avic_update_vapic_bar(to_svm(vcpu), data);
4148 /* Follow through */
4150 return kvm_set_msr_common(vcpu, msr);
4155 static int wrmsr_interception(struct vcpu_svm *svm)
4157 struct msr_data msr;
4158 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4159 u64 data = kvm_read_edx_eax(&svm->vcpu);
4163 msr.host_initiated = false;
4165 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4166 if (kvm_set_msr(&svm->vcpu, &msr)) {
4167 trace_kvm_msr_write_ex(ecx, data);
4168 kvm_inject_gp(&svm->vcpu, 0);
4171 trace_kvm_msr_write(ecx, data);
4172 return kvm_skip_emulated_instruction(&svm->vcpu);
4176 static int msr_interception(struct vcpu_svm *svm)
4178 if (svm->vmcb->control.exit_info_1)
4179 return wrmsr_interception(svm);
4181 return rdmsr_interception(svm);
4184 static int interrupt_window_interception(struct vcpu_svm *svm)
4186 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4187 svm_clear_vintr(svm);
4188 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4189 mark_dirty(svm->vmcb, VMCB_INTR);
4190 ++svm->vcpu.stat.irq_window_exits;
4194 static int pause_interception(struct vcpu_svm *svm)
4196 struct kvm_vcpu *vcpu = &svm->vcpu;
4197 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4199 kvm_vcpu_on_spin(vcpu, in_kernel);
4203 static int nop_interception(struct vcpu_svm *svm)
4205 return kvm_skip_emulated_instruction(&(svm->vcpu));
4208 static int monitor_interception(struct vcpu_svm *svm)
4210 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4211 return nop_interception(svm);
4214 static int mwait_interception(struct vcpu_svm *svm)
4216 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4217 return nop_interception(svm);
4220 enum avic_ipi_failure_cause {
4221 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4222 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4223 AVIC_IPI_FAILURE_INVALID_TARGET,
4224 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4227 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4229 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4230 u32 icrl = svm->vmcb->control.exit_info_1;
4231 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4232 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4233 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4235 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4238 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4240 * AVIC hardware handles the generation of
4241 * IPIs when the specified Message Type is Fixed
4242 * (also known as fixed delivery mode) and
4243 * the Trigger Mode is edge-triggered. The hardware
4244 * also supports self and broadcast delivery modes
4245 * specified via the Destination Shorthand(DSH)
4246 * field of the ICRL. Logical and physical APIC ID
4247 * formats are supported. All other IPI types cause
4248 * a #VMEXIT, which needs to emulated.
4250 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4251 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4253 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4255 struct kvm_vcpu *vcpu;
4256 struct kvm *kvm = svm->vcpu.kvm;
4257 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4260 * At this point, we expect that the AVIC HW has already
4261 * set the appropriate IRR bits on the valid target
4262 * vcpus. So, we just need to kick the appropriate vcpu.
4264 kvm_for_each_vcpu(i, vcpu, kvm) {
4265 bool m = kvm_apic_match_dest(vcpu, apic,
4266 icrl & KVM_APIC_SHORT_MASK,
4267 GET_APIC_DEST_FIELD(icrh),
4268 icrl & KVM_APIC_DEST_MASK);
4270 if (m && !avic_vcpu_is_running(vcpu))
4271 kvm_vcpu_wake_up(vcpu);
4275 case AVIC_IPI_FAILURE_INVALID_TARGET:
4277 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4278 WARN_ONCE(1, "Invalid backing page\n");
4281 pr_err("Unknown IPI interception\n");
4287 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4289 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4291 u32 *logical_apic_id_table;
4292 int dlid = GET_APIC_LOGICAL_ID(ldr);
4297 if (flat) { /* flat */
4298 index = ffs(dlid) - 1;
4301 } else { /* cluster */
4302 int cluster = (dlid & 0xf0) >> 4;
4303 int apic = ffs(dlid & 0x0f) - 1;
4305 if ((apic < 0) || (apic > 7) ||
4308 index = (cluster << 2) + apic;
4311 logical_apic_id_table = (u32 *) page_address(vm_data->avic_logical_id_table_page);
4313 return &logical_apic_id_table[index];
4316 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4320 u32 *entry, new_entry;
4322 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4323 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4327 new_entry = READ_ONCE(*entry);
4328 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4329 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4331 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4333 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4334 WRITE_ONCE(*entry, new_entry);
4339 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4342 struct vcpu_svm *svm = to_svm(vcpu);
4343 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4348 ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4349 if (ret && svm->ldr_reg) {
4350 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4358 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4361 struct vcpu_svm *svm = to_svm(vcpu);
4362 u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4363 u32 id = (apic_id_reg >> 24) & 0xff;
4365 if (vcpu->vcpu_id == id)
4368 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4369 new = avic_get_physical_id_entry(vcpu, id);
4373 /* We need to move physical_id_entry to new offset */
4376 to_svm(vcpu)->avic_physical_id_cache = new;
4379 * Also update the guest physical APIC ID in the logical
4380 * APIC ID table entry if already setup the LDR.
4383 avic_handle_ldr_update(vcpu);
4388 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4390 struct vcpu_svm *svm = to_svm(vcpu);
4391 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4392 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4393 u32 mod = (dfr >> 28) & 0xf;
4396 * We assume that all local APICs are using the same type.
4397 * If this changes, we need to flush the AVIC logical
4400 if (vm_data->ldr_mode == mod)
4403 clear_page(page_address(vm_data->avic_logical_id_table_page));
4404 vm_data->ldr_mode = mod;
4407 avic_handle_ldr_update(vcpu);
4411 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4413 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4414 u32 offset = svm->vmcb->control.exit_info_1 &
4415 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4419 if (avic_handle_apic_id_update(&svm->vcpu))
4423 if (avic_handle_ldr_update(&svm->vcpu))
4427 avic_handle_dfr_update(&svm->vcpu);
4433 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4438 static bool is_avic_unaccelerated_access_trap(u32 offset)
4467 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4470 u32 offset = svm->vmcb->control.exit_info_1 &
4471 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4472 u32 vector = svm->vmcb->control.exit_info_2 &
4473 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4474 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4475 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4476 bool trap = is_avic_unaccelerated_access_trap(offset);
4478 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4479 trap, write, vector);
4482 WARN_ONCE(!write, "svm: Handling trap read.\n");
4483 ret = avic_unaccel_trap_write(svm);
4485 /* Handling Fault */
4486 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4492 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4493 [SVM_EXIT_READ_CR0] = cr_interception,
4494 [SVM_EXIT_READ_CR3] = cr_interception,
4495 [SVM_EXIT_READ_CR4] = cr_interception,
4496 [SVM_EXIT_READ_CR8] = cr_interception,
4497 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4498 [SVM_EXIT_WRITE_CR0] = cr_interception,
4499 [SVM_EXIT_WRITE_CR3] = cr_interception,
4500 [SVM_EXIT_WRITE_CR4] = cr_interception,
4501 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4502 [SVM_EXIT_READ_DR0] = dr_interception,
4503 [SVM_EXIT_READ_DR1] = dr_interception,
4504 [SVM_EXIT_READ_DR2] = dr_interception,
4505 [SVM_EXIT_READ_DR3] = dr_interception,
4506 [SVM_EXIT_READ_DR4] = dr_interception,
4507 [SVM_EXIT_READ_DR5] = dr_interception,
4508 [SVM_EXIT_READ_DR6] = dr_interception,
4509 [SVM_EXIT_READ_DR7] = dr_interception,
4510 [SVM_EXIT_WRITE_DR0] = dr_interception,
4511 [SVM_EXIT_WRITE_DR1] = dr_interception,
4512 [SVM_EXIT_WRITE_DR2] = dr_interception,
4513 [SVM_EXIT_WRITE_DR3] = dr_interception,
4514 [SVM_EXIT_WRITE_DR4] = dr_interception,
4515 [SVM_EXIT_WRITE_DR5] = dr_interception,
4516 [SVM_EXIT_WRITE_DR6] = dr_interception,
4517 [SVM_EXIT_WRITE_DR7] = dr_interception,
4518 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4519 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4520 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4521 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4522 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4523 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4524 [SVM_EXIT_INTR] = intr_interception,
4525 [SVM_EXIT_NMI] = nmi_interception,
4526 [SVM_EXIT_SMI] = nop_on_interception,
4527 [SVM_EXIT_INIT] = nop_on_interception,
4528 [SVM_EXIT_VINTR] = interrupt_window_interception,
4529 [SVM_EXIT_RDPMC] = rdpmc_interception,
4530 [SVM_EXIT_CPUID] = cpuid_interception,
4531 [SVM_EXIT_IRET] = iret_interception,
4532 [SVM_EXIT_INVD] = emulate_on_interception,
4533 [SVM_EXIT_PAUSE] = pause_interception,
4534 [SVM_EXIT_HLT] = halt_interception,
4535 [SVM_EXIT_INVLPG] = invlpg_interception,
4536 [SVM_EXIT_INVLPGA] = invlpga_interception,
4537 [SVM_EXIT_IOIO] = io_interception,
4538 [SVM_EXIT_MSR] = msr_interception,
4539 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4540 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4541 [SVM_EXIT_VMRUN] = vmrun_interception,
4542 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4543 [SVM_EXIT_VMLOAD] = vmload_interception,
4544 [SVM_EXIT_VMSAVE] = vmsave_interception,
4545 [SVM_EXIT_STGI] = stgi_interception,
4546 [SVM_EXIT_CLGI] = clgi_interception,
4547 [SVM_EXIT_SKINIT] = skinit_interception,
4548 [SVM_EXIT_WBINVD] = wbinvd_interception,
4549 [SVM_EXIT_MONITOR] = monitor_interception,
4550 [SVM_EXIT_MWAIT] = mwait_interception,
4551 [SVM_EXIT_XSETBV] = xsetbv_interception,
4552 [SVM_EXIT_NPF] = npf_interception,
4553 [SVM_EXIT_RSM] = rsm_interception,
4554 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4555 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4558 static void dump_vmcb(struct kvm_vcpu *vcpu)
4560 struct vcpu_svm *svm = to_svm(vcpu);
4561 struct vmcb_control_area *control = &svm->vmcb->control;
4562 struct vmcb_save_area *save = &svm->vmcb->save;
4564 pr_err("VMCB Control Area:\n");
4565 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4566 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4567 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4568 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4569 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4570 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4571 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4572 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4573 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4574 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4575 pr_err("%-20s%d\n", "asid:", control->asid);
4576 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4577 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4578 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4579 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4580 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4581 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4582 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4583 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4584 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4585 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4586 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4587 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4588 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4589 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4590 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4591 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4592 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4593 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4594 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4595 pr_err("VMCB State Save Area:\n");
4596 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4598 save->es.selector, save->es.attrib,
4599 save->es.limit, save->es.base);
4600 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4602 save->cs.selector, save->cs.attrib,
4603 save->cs.limit, save->cs.base);
4604 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4606 save->ss.selector, save->ss.attrib,
4607 save->ss.limit, save->ss.base);
4608 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4610 save->ds.selector, save->ds.attrib,
4611 save->ds.limit, save->ds.base);
4612 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4614 save->fs.selector, save->fs.attrib,
4615 save->fs.limit, save->fs.base);
4616 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4618 save->gs.selector, save->gs.attrib,
4619 save->gs.limit, save->gs.base);
4620 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4622 save->gdtr.selector, save->gdtr.attrib,
4623 save->gdtr.limit, save->gdtr.base);
4624 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4626 save->ldtr.selector, save->ldtr.attrib,
4627 save->ldtr.limit, save->ldtr.base);
4628 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4630 save->idtr.selector, save->idtr.attrib,
4631 save->idtr.limit, save->idtr.base);
4632 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4634 save->tr.selector, save->tr.attrib,
4635 save->tr.limit, save->tr.base);
4636 pr_err("cpl: %d efer: %016llx\n",
4637 save->cpl, save->efer);
4638 pr_err("%-15s %016llx %-13s %016llx\n",
4639 "cr0:", save->cr0, "cr2:", save->cr2);
4640 pr_err("%-15s %016llx %-13s %016llx\n",
4641 "cr3:", save->cr3, "cr4:", save->cr4);
4642 pr_err("%-15s %016llx %-13s %016llx\n",
4643 "dr6:", save->dr6, "dr7:", save->dr7);
4644 pr_err("%-15s %016llx %-13s %016llx\n",
4645 "rip:", save->rip, "rflags:", save->rflags);
4646 pr_err("%-15s %016llx %-13s %016llx\n",
4647 "rsp:", save->rsp, "rax:", save->rax);
4648 pr_err("%-15s %016llx %-13s %016llx\n",
4649 "star:", save->star, "lstar:", save->lstar);
4650 pr_err("%-15s %016llx %-13s %016llx\n",
4651 "cstar:", save->cstar, "sfmask:", save->sfmask);
4652 pr_err("%-15s %016llx %-13s %016llx\n",
4653 "kernel_gs_base:", save->kernel_gs_base,
4654 "sysenter_cs:", save->sysenter_cs);
4655 pr_err("%-15s %016llx %-13s %016llx\n",
4656 "sysenter_esp:", save->sysenter_esp,
4657 "sysenter_eip:", save->sysenter_eip);
4658 pr_err("%-15s %016llx %-13s %016llx\n",
4659 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4660 pr_err("%-15s %016llx %-13s %016llx\n",
4661 "br_from:", save->br_from, "br_to:", save->br_to);
4662 pr_err("%-15s %016llx %-13s %016llx\n",
4663 "excp_from:", save->last_excp_from,
4664 "excp_to:", save->last_excp_to);
4667 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4669 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4671 *info1 = control->exit_info_1;
4672 *info2 = control->exit_info_2;
4675 static int handle_exit(struct kvm_vcpu *vcpu)
4677 struct vcpu_svm *svm = to_svm(vcpu);
4678 struct kvm_run *kvm_run = vcpu->run;
4679 u32 exit_code = svm->vmcb->control.exit_code;
4681 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4683 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4684 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4686 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4688 if (unlikely(svm->nested.exit_required)) {
4689 nested_svm_vmexit(svm);
4690 svm->nested.exit_required = false;
4695 if (is_guest_mode(vcpu)) {
4698 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4699 svm->vmcb->control.exit_info_1,
4700 svm->vmcb->control.exit_info_2,
4701 svm->vmcb->control.exit_int_info,
4702 svm->vmcb->control.exit_int_info_err,
4705 vmexit = nested_svm_exit_special(svm);
4707 if (vmexit == NESTED_EXIT_CONTINUE)
4708 vmexit = nested_svm_exit_handled(svm);
4710 if (vmexit == NESTED_EXIT_DONE)
4714 svm_complete_interrupts(svm);
4716 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4717 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4718 kvm_run->fail_entry.hardware_entry_failure_reason
4719 = svm->vmcb->control.exit_code;
4720 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4725 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4726 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4727 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4728 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4729 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4731 __func__, svm->vmcb->control.exit_int_info,
4734 if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4735 || !svm_exit_handlers[exit_code]) {
4736 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4737 kvm_queue_exception(vcpu, UD_VECTOR);
4741 return svm_exit_handlers[exit_code](svm);
4744 static void reload_tss(struct kvm_vcpu *vcpu)
4746 int cpu = raw_smp_processor_id();
4748 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4749 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4753 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
4755 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4756 int asid = sev_get_asid(svm->vcpu.kvm);
4758 /* Assign the asid allocated with this SEV guest */
4759 svm->vmcb->control.asid = asid;
4764 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
4765 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
4767 if (sd->sev_vmcbs[asid] == svm->vmcb &&
4768 svm->last_cpu == cpu)
4771 svm->last_cpu = cpu;
4772 sd->sev_vmcbs[asid] = svm->vmcb;
4773 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4774 mark_dirty(svm->vmcb, VMCB_ASID);
4777 static void pre_svm_run(struct vcpu_svm *svm)
4779 int cpu = raw_smp_processor_id();
4781 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4783 if (sev_guest(svm->vcpu.kvm))
4784 return pre_sev_run(svm, cpu);
4786 /* FIXME: handle wraparound of asid_generation */
4787 if (svm->asid_generation != sd->asid_generation)
4791 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
4793 struct vcpu_svm *svm = to_svm(vcpu);
4795 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
4796 vcpu->arch.hflags |= HF_NMI_MASK;
4797 set_intercept(svm, INTERCEPT_IRET);
4798 ++vcpu->stat.nmi_injections;
4801 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
4803 struct vmcb_control_area *control;
4805 /* The following fields are ignored when AVIC is enabled */
4806 control = &svm->vmcb->control;
4807 control->int_vector = irq;
4808 control->int_ctl &= ~V_INTR_PRIO_MASK;
4809 control->int_ctl |= V_IRQ_MASK |
4810 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
4811 mark_dirty(svm->vmcb, VMCB_INTR);
4814 static void svm_set_irq(struct kvm_vcpu *vcpu)
4816 struct vcpu_svm *svm = to_svm(vcpu);
4818 BUG_ON(!(gif_set(svm)));
4820 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
4821 ++vcpu->stat.irq_injections;
4823 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
4824 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
4827 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
4829 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
4832 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4834 struct vcpu_svm *svm = to_svm(vcpu);
4836 if (svm_nested_virtualize_tpr(vcpu) ||
4837 kvm_vcpu_apicv_active(vcpu))
4840 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4846 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4849 static void svm_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
4854 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
4856 return avic && irqchip_split(vcpu->kvm);
4859 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
4863 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
4867 /* Note: Currently only used by Hyper-V. */
4868 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4870 struct vcpu_svm *svm = to_svm(vcpu);
4871 struct vmcb *vmcb = svm->vmcb;
4873 if (!kvm_vcpu_apicv_active(&svm->vcpu))
4876 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
4877 mark_dirty(vmcb, VMCB_INTR);
4880 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
4885 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
4887 kvm_lapic_set_irr(vec, vcpu->arch.apic);
4888 smp_mb__after_atomic();
4890 if (avic_vcpu_is_running(vcpu))
4891 wrmsrl(SVM_AVIC_DOORBELL,
4892 kvm_cpu_get_apicid(vcpu->cpu));
4894 kvm_vcpu_wake_up(vcpu);
4897 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4899 unsigned long flags;
4900 struct amd_svm_iommu_ir *cur;
4902 spin_lock_irqsave(&svm->ir_list_lock, flags);
4903 list_for_each_entry(cur, &svm->ir_list, node) {
4904 if (cur->data != pi->ir_data)
4906 list_del(&cur->node);
4910 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4913 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4916 unsigned long flags;
4917 struct amd_svm_iommu_ir *ir;
4920 * In some cases, the existing irte is updaed and re-set,
4921 * so we need to check here if it's already been * added
4924 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
4925 struct kvm *kvm = svm->vcpu.kvm;
4926 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
4927 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
4928 struct vcpu_svm *prev_svm;
4935 prev_svm = to_svm(prev_vcpu);
4936 svm_ir_list_del(prev_svm, pi);
4940 * Allocating new amd_iommu_pi_data, which will get
4941 * add to the per-vcpu ir_list.
4943 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
4948 ir->data = pi->ir_data;
4950 spin_lock_irqsave(&svm->ir_list_lock, flags);
4951 list_add(&ir->node, &svm->ir_list);
4952 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4959 * The HW cannot support posting multicast/broadcast
4960 * interrupts to a vCPU. So, we still use legacy interrupt
4961 * remapping for these kind of interrupts.
4963 * For lowest-priority interrupts, we only support
4964 * those with single CPU as the destination, e.g. user
4965 * configures the interrupts via /proc/irq or uses
4966 * irqbalance to make the interrupts single-CPU.
4969 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
4970 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
4972 struct kvm_lapic_irq irq;
4973 struct kvm_vcpu *vcpu = NULL;
4975 kvm_set_msi_irq(kvm, e, &irq);
4977 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
4978 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
4979 __func__, irq.vector);
4983 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
4985 *svm = to_svm(vcpu);
4986 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
4987 vcpu_info->vector = irq.vector;
4993 * svm_update_pi_irte - set IRTE for Posted-Interrupts
4996 * @host_irq: host irq of the interrupt
4997 * @guest_irq: gsi of the interrupt
4998 * @set: set or unset PI
4999 * returns 0 on success, < 0 on failure
5001 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5002 uint32_t guest_irq, bool set)
5004 struct kvm_kernel_irq_routing_entry *e;
5005 struct kvm_irq_routing_table *irq_rt;
5006 int idx, ret = -EINVAL;
5008 if (!kvm_arch_has_assigned_device(kvm) ||
5009 !irq_remapping_cap(IRQ_POSTING_CAP))
5012 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5013 __func__, host_irq, guest_irq, set);
5015 idx = srcu_read_lock(&kvm->irq_srcu);
5016 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5017 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5019 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5020 struct vcpu_data vcpu_info;
5021 struct vcpu_svm *svm = NULL;
5023 if (e->type != KVM_IRQ_ROUTING_MSI)
5027 * Here, we setup with legacy mode in the following cases:
5028 * 1. When cannot target interrupt to a specific vcpu.
5029 * 2. Unsetting posted interrupt.
5030 * 3. APIC virtialization is disabled for the vcpu.
5032 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5033 kvm_vcpu_apicv_active(&svm->vcpu)) {
5034 struct amd_iommu_pi_data pi;
5036 /* Try to enable guest_mode in IRTE */
5037 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5039 pi.ga_tag = AVIC_GATAG(kvm->arch.avic_vm_id,
5041 pi.is_guest_mode = true;
5042 pi.vcpu_data = &vcpu_info;
5043 ret = irq_set_vcpu_affinity(host_irq, &pi);
5046 * Here, we successfully setting up vcpu affinity in
5047 * IOMMU guest mode. Now, we need to store the posted
5048 * interrupt information in a per-vcpu ir_list so that
5049 * we can reference to them directly when we update vcpu
5050 * scheduling information in IOMMU irte.
5052 if (!ret && pi.is_guest_mode)
5053 svm_ir_list_add(svm, &pi);
5055 /* Use legacy mode in IRTE */
5056 struct amd_iommu_pi_data pi;
5059 * Here, pi is used to:
5060 * - Tell IOMMU to use legacy mode for this interrupt.
5061 * - Retrieve ga_tag of prior interrupt remapping data.
5063 pi.is_guest_mode = false;
5064 ret = irq_set_vcpu_affinity(host_irq, &pi);
5067 * Check if the posted interrupt was previously
5068 * setup with the guest_mode by checking if the ga_tag
5069 * was cached. If so, we need to clean up the per-vcpu
5072 if (!ret && pi.prev_ga_tag) {
5073 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5074 struct kvm_vcpu *vcpu;
5076 vcpu = kvm_get_vcpu_by_id(kvm, id);
5078 svm_ir_list_del(to_svm(vcpu), &pi);
5083 trace_kvm_pi_irte_update(svm->vcpu.vcpu_id,
5086 vcpu_info.pi_desc_addr, set);
5090 pr_err("%s: failed to update PI IRTE\n", __func__);
5097 srcu_read_unlock(&kvm->irq_srcu, idx);
5101 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5103 struct vcpu_svm *svm = to_svm(vcpu);
5104 struct vmcb *vmcb = svm->vmcb;
5106 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5107 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5108 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5113 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5115 struct vcpu_svm *svm = to_svm(vcpu);
5117 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5120 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5122 struct vcpu_svm *svm = to_svm(vcpu);
5125 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5126 set_intercept(svm, INTERCEPT_IRET);
5128 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5129 clr_intercept(svm, INTERCEPT_IRET);
5133 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5135 struct vcpu_svm *svm = to_svm(vcpu);
5136 struct vmcb *vmcb = svm->vmcb;
5139 if (!gif_set(svm) ||
5140 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5143 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5145 if (is_guest_mode(vcpu))
5146 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5151 static void enable_irq_window(struct kvm_vcpu *vcpu)
5153 struct vcpu_svm *svm = to_svm(vcpu);
5155 if (kvm_vcpu_apicv_active(vcpu))
5159 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5160 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5161 * get that intercept, this function will be called again though and
5162 * we'll get the vintr intercept. However, if the vGIF feature is
5163 * enabled, the STGI interception will not occur. Enable the irq
5164 * window under the assumption that the hardware will set the GIF.
5166 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5168 svm_inject_irq(svm, 0x0);
5172 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5174 struct vcpu_svm *svm = to_svm(vcpu);
5176 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5178 return; /* IRET will cause a vm exit */
5180 if (!gif_set(svm)) {
5181 if (vgif_enabled(svm))
5182 set_intercept(svm, INTERCEPT_STGI);
5183 return; /* STGI will cause a vm exit */
5186 if (svm->nested.exit_required)
5187 return; /* we're not going to run the guest yet */
5190 * Something prevents NMI from been injected. Single step over possible
5191 * problem (IRET or exception injection or interrupt shadow)
5193 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5194 svm->nmi_singlestep = true;
5195 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5198 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5203 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5205 struct vcpu_svm *svm = to_svm(vcpu);
5207 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5208 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5210 svm->asid_generation--;
5213 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5217 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5219 struct vcpu_svm *svm = to_svm(vcpu);
5221 if (svm_nested_virtualize_tpr(vcpu))
5224 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5225 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5226 kvm_set_cr8(vcpu, cr8);
5230 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5232 struct vcpu_svm *svm = to_svm(vcpu);
5235 if (svm_nested_virtualize_tpr(vcpu) ||
5236 kvm_vcpu_apicv_active(vcpu))
5239 cr8 = kvm_get_cr8(vcpu);
5240 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5241 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5244 static void svm_complete_interrupts(struct vcpu_svm *svm)
5248 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5249 unsigned int3_injected = svm->int3_injected;
5251 svm->int3_injected = 0;
5254 * If we've made progress since setting HF_IRET_MASK, we've
5255 * executed an IRET and can allow NMI injection.
5257 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5258 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5259 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5260 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5263 svm->vcpu.arch.nmi_injected = false;
5264 kvm_clear_exception_queue(&svm->vcpu);
5265 kvm_clear_interrupt_queue(&svm->vcpu);
5267 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5270 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5272 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5273 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5276 case SVM_EXITINTINFO_TYPE_NMI:
5277 svm->vcpu.arch.nmi_injected = true;
5279 case SVM_EXITINTINFO_TYPE_EXEPT:
5281 * In case of software exceptions, do not reinject the vector,
5282 * but re-execute the instruction instead. Rewind RIP first
5283 * if we emulated INT3 before.
5285 if (kvm_exception_is_soft(vector)) {
5286 if (vector == BP_VECTOR && int3_injected &&
5287 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5288 kvm_rip_write(&svm->vcpu,
5289 kvm_rip_read(&svm->vcpu) -
5293 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5294 u32 err = svm->vmcb->control.exit_int_info_err;
5295 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5298 kvm_requeue_exception(&svm->vcpu, vector);
5300 case SVM_EXITINTINFO_TYPE_INTR:
5301 kvm_queue_interrupt(&svm->vcpu, vector, false);
5308 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5310 struct vcpu_svm *svm = to_svm(vcpu);
5311 struct vmcb_control_area *control = &svm->vmcb->control;
5313 control->exit_int_info = control->event_inj;
5314 control->exit_int_info_err = control->event_inj_err;
5315 control->event_inj = 0;
5316 svm_complete_interrupts(svm);
5319 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5321 struct vcpu_svm *svm = to_svm(vcpu);
5323 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5324 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5325 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5328 * A vmexit emulation is required before the vcpu can be executed
5331 if (unlikely(svm->nested.exit_required))
5335 * Disable singlestep if we're injecting an interrupt/exception.
5336 * We don't want our modified rflags to be pushed on the stack where
5337 * we might not be able to easily reset them if we disabled NMI
5340 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5342 * Event injection happens before external interrupts cause a
5343 * vmexit and interrupts are disabled here, so smp_send_reschedule
5344 * is enough to force an immediate vmexit.
5346 disable_nmi_singlestep(svm);
5347 smp_send_reschedule(vcpu->cpu);
5352 sync_lapic_to_cr8(vcpu);
5354 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5361 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5362 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5363 * is no need to worry about the conditional branch over the wrmsr
5364 * being speculatively taken.
5367 wrmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5370 "push %%" _ASM_BP "; \n\t"
5371 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5372 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5373 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5374 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5375 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5376 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5377 #ifdef CONFIG_X86_64
5378 "mov %c[r8](%[svm]), %%r8 \n\t"
5379 "mov %c[r9](%[svm]), %%r9 \n\t"
5380 "mov %c[r10](%[svm]), %%r10 \n\t"
5381 "mov %c[r11](%[svm]), %%r11 \n\t"
5382 "mov %c[r12](%[svm]), %%r12 \n\t"
5383 "mov %c[r13](%[svm]), %%r13 \n\t"
5384 "mov %c[r14](%[svm]), %%r14 \n\t"
5385 "mov %c[r15](%[svm]), %%r15 \n\t"
5388 /* Enter guest mode */
5389 "push %%" _ASM_AX " \n\t"
5390 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5391 __ex(SVM_VMLOAD) "\n\t"
5392 __ex(SVM_VMRUN) "\n\t"
5393 __ex(SVM_VMSAVE) "\n\t"
5394 "pop %%" _ASM_AX " \n\t"
5396 /* Save guest registers, load host registers */
5397 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5398 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5399 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5400 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5401 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5402 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5403 #ifdef CONFIG_X86_64
5404 "mov %%r8, %c[r8](%[svm]) \n\t"
5405 "mov %%r9, %c[r9](%[svm]) \n\t"
5406 "mov %%r10, %c[r10](%[svm]) \n\t"
5407 "mov %%r11, %c[r11](%[svm]) \n\t"
5408 "mov %%r12, %c[r12](%[svm]) \n\t"
5409 "mov %%r13, %c[r13](%[svm]) \n\t"
5410 "mov %%r14, %c[r14](%[svm]) \n\t"
5411 "mov %%r15, %c[r15](%[svm]) \n\t"
5414 * Clear host registers marked as clobbered to prevent
5417 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5418 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5419 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5420 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5421 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5422 #ifdef CONFIG_X86_64
5423 "xor %%r8, %%r8 \n\t"
5424 "xor %%r9, %%r9 \n\t"
5425 "xor %%r10, %%r10 \n\t"
5426 "xor %%r11, %%r11 \n\t"
5427 "xor %%r12, %%r12 \n\t"
5428 "xor %%r13, %%r13 \n\t"
5429 "xor %%r14, %%r14 \n\t"
5430 "xor %%r15, %%r15 \n\t"
5435 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5436 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5437 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5438 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5439 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5440 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5441 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5442 #ifdef CONFIG_X86_64
5443 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5444 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5445 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5446 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5447 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5448 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5449 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5450 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5453 #ifdef CONFIG_X86_64
5454 , "rbx", "rcx", "rdx", "rsi", "rdi"
5455 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5457 , "ebx", "ecx", "edx", "esi", "edi"
5462 * We do not use IBRS in the kernel. If this vCPU has used the
5463 * SPEC_CTRL MSR it may have left it on; save the value and
5464 * turn it off. This is much more efficient than blindly adding
5465 * it to the atomic save/restore list. Especially as the former
5466 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5468 * For non-nested case:
5469 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5473 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5476 if (!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL))
5477 rdmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5480 wrmsrl(MSR_IA32_SPEC_CTRL, 0);
5482 /* Eliminate branch target predictions from guest mode */
5485 #ifdef CONFIG_X86_64
5486 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5488 loadsegment(fs, svm->host.fs);
5489 #ifndef CONFIG_X86_32_LAZY_GS
5490 loadsegment(gs, svm->host.gs);
5496 local_irq_disable();
5498 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5499 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5500 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5501 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5503 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5504 kvm_before_handle_nmi(&svm->vcpu);
5508 /* Any pending NMI will happen here */
5510 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5511 kvm_after_handle_nmi(&svm->vcpu);
5513 sync_cr8_to_lapic(vcpu);
5517 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5519 /* if exit due to PF check for async PF */
5520 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5521 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5524 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5525 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5529 * We need to handle MC intercepts here before the vcpu has a chance to
5530 * change the physical cpu
5532 if (unlikely(svm->vmcb->control.exit_code ==
5533 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5534 svm_handle_mce(svm);
5536 mark_all_clean(svm->vmcb);
5538 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5540 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5542 struct vcpu_svm *svm = to_svm(vcpu);
5544 svm->vmcb->save.cr3 = __sme_set(root);
5545 mark_dirty(svm->vmcb, VMCB_CR);
5546 svm_flush_tlb(vcpu, true);
5549 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5551 struct vcpu_svm *svm = to_svm(vcpu);
5553 svm->vmcb->control.nested_cr3 = __sme_set(root);
5554 mark_dirty(svm->vmcb, VMCB_NPT);
5556 /* Also sync guest cr3 here in case we live migrate */
5557 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5558 mark_dirty(svm->vmcb, VMCB_CR);
5560 svm_flush_tlb(vcpu, true);
5563 static int is_disabled(void)
5567 rdmsrl(MSR_VM_CR, vm_cr);
5568 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5575 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5578 * Patch in the VMMCALL instruction:
5580 hypercall[0] = 0x0f;
5581 hypercall[1] = 0x01;
5582 hypercall[2] = 0xd9;
5585 static void svm_check_processor_compat(void *rtn)
5590 static bool svm_cpu_has_accelerated_tpr(void)
5595 static bool svm_has_high_real_mode_segbase(void)
5600 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5605 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5607 struct vcpu_svm *svm = to_svm(vcpu);
5609 /* Update nrips enabled cache */
5610 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5612 if (!kvm_vcpu_apicv_active(vcpu))
5615 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5618 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5623 entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5627 entry->ecx |= (1 << 2); /* Set SVM bit */
5630 entry->eax = 1; /* SVM revision 1 */
5631 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5632 ASID emulation to nested SVM */
5633 entry->ecx = 0; /* Reserved */
5634 entry->edx = 0; /* Per default do not support any
5635 additional features */
5637 /* Support next_rip if host supports it */
5638 if (boot_cpu_has(X86_FEATURE_NRIPS))
5639 entry->edx |= SVM_FEATURE_NRIP;
5641 /* Support NPT for the guest if enabled */
5643 entry->edx |= SVM_FEATURE_NPT;
5647 /* Support memory encryption cpuid if host supports it */
5648 if (boot_cpu_has(X86_FEATURE_SEV))
5649 cpuid(0x8000001f, &entry->eax, &entry->ebx,
5650 &entry->ecx, &entry->edx);
5655 static int svm_get_lpage_level(void)
5657 return PT_PDPE_LEVEL;
5660 static bool svm_rdtscp_supported(void)
5662 return boot_cpu_has(X86_FEATURE_RDTSCP);
5665 static bool svm_invpcid_supported(void)
5670 static bool svm_mpx_supported(void)
5675 static bool svm_xsaves_supported(void)
5680 static bool svm_umip_emulated(void)
5685 static bool svm_has_wbinvd_exit(void)
5690 #define PRE_EX(exit) { .exit_code = (exit), \
5691 .stage = X86_ICPT_PRE_EXCEPT, }
5692 #define POST_EX(exit) { .exit_code = (exit), \
5693 .stage = X86_ICPT_POST_EXCEPT, }
5694 #define POST_MEM(exit) { .exit_code = (exit), \
5695 .stage = X86_ICPT_POST_MEMACCESS, }
5697 static const struct __x86_intercept {
5699 enum x86_intercept_stage stage;
5700 } x86_intercept_map[] = {
5701 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
5702 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
5703 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
5704 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
5705 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
5706 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
5707 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
5708 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
5709 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
5710 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
5711 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
5712 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
5713 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
5714 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
5715 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
5716 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
5717 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
5718 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
5719 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
5720 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
5721 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
5722 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
5723 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
5724 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
5725 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
5726 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
5727 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
5728 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
5729 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
5730 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
5731 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
5732 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
5733 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
5734 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
5735 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
5736 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
5737 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
5738 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
5739 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
5740 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
5741 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
5742 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
5743 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
5744 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
5745 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
5746 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
5753 static int svm_check_intercept(struct kvm_vcpu *vcpu,
5754 struct x86_instruction_info *info,
5755 enum x86_intercept_stage stage)
5757 struct vcpu_svm *svm = to_svm(vcpu);
5758 int vmexit, ret = X86EMUL_CONTINUE;
5759 struct __x86_intercept icpt_info;
5760 struct vmcb *vmcb = svm->vmcb;
5762 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
5765 icpt_info = x86_intercept_map[info->intercept];
5767 if (stage != icpt_info.stage)
5770 switch (icpt_info.exit_code) {
5771 case SVM_EXIT_READ_CR0:
5772 if (info->intercept == x86_intercept_cr_read)
5773 icpt_info.exit_code += info->modrm_reg;
5775 case SVM_EXIT_WRITE_CR0: {
5776 unsigned long cr0, val;
5779 if (info->intercept == x86_intercept_cr_write)
5780 icpt_info.exit_code += info->modrm_reg;
5782 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
5783 info->intercept == x86_intercept_clts)
5786 intercept = svm->nested.intercept;
5788 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
5791 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5792 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
5794 if (info->intercept == x86_intercept_lmsw) {
5797 /* lmsw can't clear PE - catch this here */
5798 if (cr0 & X86_CR0_PE)
5803 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5807 case SVM_EXIT_READ_DR0:
5808 case SVM_EXIT_WRITE_DR0:
5809 icpt_info.exit_code += info->modrm_reg;
5812 if (info->intercept == x86_intercept_wrmsr)
5813 vmcb->control.exit_info_1 = 1;
5815 vmcb->control.exit_info_1 = 0;
5817 case SVM_EXIT_PAUSE:
5819 * We get this for NOP only, but pause
5820 * is rep not, check this here
5822 if (info->rep_prefix != REPE_PREFIX)
5825 case SVM_EXIT_IOIO: {
5829 if (info->intercept == x86_intercept_in ||
5830 info->intercept == x86_intercept_ins) {
5831 exit_info = ((info->src_val & 0xffff) << 16) |
5833 bytes = info->dst_bytes;
5835 exit_info = (info->dst_val & 0xffff) << 16;
5836 bytes = info->src_bytes;
5839 if (info->intercept == x86_intercept_outs ||
5840 info->intercept == x86_intercept_ins)
5841 exit_info |= SVM_IOIO_STR_MASK;
5843 if (info->rep_prefix)
5844 exit_info |= SVM_IOIO_REP_MASK;
5846 bytes = min(bytes, 4u);
5848 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5850 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5852 vmcb->control.exit_info_1 = exit_info;
5853 vmcb->control.exit_info_2 = info->next_rip;
5861 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5862 if (static_cpu_has(X86_FEATURE_NRIPS))
5863 vmcb->control.next_rip = info->next_rip;
5864 vmcb->control.exit_code = icpt_info.exit_code;
5865 vmexit = nested_svm_exit_handled(svm);
5867 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5874 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
5878 * We must have an instruction with interrupts enabled, so
5879 * the timer interrupt isn't delayed by the interrupt shadow.
5882 local_irq_disable();
5885 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
5889 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
5891 if (avic_handle_apic_id_update(vcpu) != 0)
5893 if (avic_handle_dfr_update(vcpu) != 0)
5895 avic_handle_ldr_update(vcpu);
5898 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5900 /* [63:9] are reserved. */
5901 vcpu->arch.mcg_cap &= 0x1ff;
5904 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
5906 struct vcpu_svm *svm = to_svm(vcpu);
5908 /* Per APM Vol.2 15.22.2 "Response to SMI" */
5912 if (is_guest_mode(&svm->vcpu) &&
5913 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
5914 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
5915 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
5916 svm->nested.exit_required = true;
5923 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
5925 struct vcpu_svm *svm = to_svm(vcpu);
5928 if (is_guest_mode(vcpu)) {
5929 /* FED8h - SVM Guest */
5930 put_smstate(u64, smstate, 0x7ed8, 1);
5931 /* FEE0h - SVM Guest VMCB Physical Address */
5932 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
5934 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5935 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5936 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5938 ret = nested_svm_vmexit(svm);
5945 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
5947 struct vcpu_svm *svm = to_svm(vcpu);
5948 struct vmcb *nested_vmcb;
5956 ret = kvm_vcpu_read_guest(vcpu, smbase + 0xfed8, &svm_state_save,
5957 sizeof(svm_state_save));
5961 if (svm_state_save.guest) {
5962 vcpu->arch.hflags &= ~HF_SMM_MASK;
5963 nested_vmcb = nested_svm_map(svm, svm_state_save.vmcb, &page);
5965 enter_svm_guest_mode(svm, svm_state_save.vmcb, nested_vmcb, page);
5968 vcpu->arch.hflags |= HF_SMM_MASK;
5973 static int enable_smi_window(struct kvm_vcpu *vcpu)
5975 struct vcpu_svm *svm = to_svm(vcpu);
5977 if (!gif_set(svm)) {
5978 if (vgif_enabled(svm))
5979 set_intercept(svm, INTERCEPT_STGI);
5980 /* STGI will cause a vm exit */
5986 static int sev_asid_new(void)
5991 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
5993 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
5994 if (pos >= max_sev_asid)
5997 set_bit(pos, sev_asid_bitmap);
6001 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6003 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6007 asid = sev_asid_new();
6011 ret = sev_platform_init(&argp->error);
6017 INIT_LIST_HEAD(&sev->regions_list);
6022 __sev_asid_free(asid);
6026 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6028 struct sev_data_activate *data;
6029 int asid = sev_get_asid(kvm);
6032 wbinvd_on_all_cpus();
6034 ret = sev_guest_df_flush(error);
6038 data = kzalloc(sizeof(*data), GFP_KERNEL);
6042 /* activate ASID on the given handle */
6043 data->handle = handle;
6045 ret = sev_guest_activate(data, error);
6051 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6060 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6066 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6068 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6070 return __sev_issue_cmd(sev->fd, id, data, error);
6073 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6075 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6076 struct sev_data_launch_start *start;
6077 struct kvm_sev_launch_start params;
6078 void *dh_blob, *session_blob;
6079 int *error = &argp->error;
6082 if (!sev_guest(kvm))
6085 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6088 start = kzalloc(sizeof(*start), GFP_KERNEL);
6093 if (params.dh_uaddr) {
6094 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6095 if (IS_ERR(dh_blob)) {
6096 ret = PTR_ERR(dh_blob);
6100 start->dh_cert_address = __sme_set(__pa(dh_blob));
6101 start->dh_cert_len = params.dh_len;
6104 session_blob = NULL;
6105 if (params.session_uaddr) {
6106 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6107 if (IS_ERR(session_blob)) {
6108 ret = PTR_ERR(session_blob);
6112 start->session_address = __sme_set(__pa(session_blob));
6113 start->session_len = params.session_len;
6116 start->handle = params.handle;
6117 start->policy = params.policy;
6119 /* create memory encryption context */
6120 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6122 goto e_free_session;
6124 /* Bind ASID to this guest */
6125 ret = sev_bind_asid(kvm, start->handle, error);
6127 goto e_free_session;
6129 /* return handle to userspace */
6130 params.handle = start->handle;
6131 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6132 sev_unbind_asid(kvm, start->handle);
6134 goto e_free_session;
6137 sev->handle = start->handle;
6138 sev->fd = argp->sev_fd;
6141 kfree(session_blob);
6149 static int get_num_contig_pages(int idx, struct page **inpages,
6150 unsigned long npages)
6152 unsigned long paddr, next_paddr;
6153 int i = idx + 1, pages = 1;
6155 /* find the number of contiguous pages starting from idx */
6156 paddr = __sme_page_pa(inpages[idx]);
6157 while (i < npages) {
6158 next_paddr = __sme_page_pa(inpages[i++]);
6159 if ((paddr + PAGE_SIZE) == next_paddr) {
6170 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6172 unsigned long vaddr, vaddr_end, next_vaddr, npages, size;
6173 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6174 struct kvm_sev_launch_update_data params;
6175 struct sev_data_launch_update_data *data;
6176 struct page **inpages;
6179 if (!sev_guest(kvm))
6182 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6185 data = kzalloc(sizeof(*data), GFP_KERNEL);
6189 vaddr = params.uaddr;
6191 vaddr_end = vaddr + size;
6193 /* Lock the user memory. */
6194 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6201 * The LAUNCH_UPDATE command will perform in-place encryption of the
6202 * memory content (i.e it will write the same memory region with C=1).
6203 * It's possible that the cache may contain the data with C=0, i.e.,
6204 * unencrypted so invalidate it first.
6206 sev_clflush_pages(inpages, npages);
6208 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6212 * If the user buffer is not page-aligned, calculate the offset
6215 offset = vaddr & (PAGE_SIZE - 1);
6217 /* Calculate the number of pages that can be encrypted in one go. */
6218 pages = get_num_contig_pages(i, inpages, npages);
6220 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6222 data->handle = sev->handle;
6224 data->address = __sme_page_pa(inpages[i]) + offset;
6225 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6230 next_vaddr = vaddr + len;
6234 /* content of memory is updated, mark pages dirty */
6235 for (i = 0; i < npages; i++) {
6236 set_page_dirty_lock(inpages[i]);
6237 mark_page_accessed(inpages[i]);
6239 /* unlock the user pages */
6240 sev_unpin_memory(kvm, inpages, npages);
6246 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6248 void __user *measure = (void __user *)(uintptr_t)argp->data;
6249 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6250 struct sev_data_launch_measure *data;
6251 struct kvm_sev_launch_measure params;
6252 void __user *p = NULL;
6256 if (!sev_guest(kvm))
6259 if (copy_from_user(¶ms, measure, sizeof(params)))
6262 data = kzalloc(sizeof(*data), GFP_KERNEL);
6266 /* User wants to query the blob length */
6270 p = (void __user *)(uintptr_t)params.uaddr;
6272 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6278 blob = kmalloc(params.len, GFP_KERNEL);
6282 data->address = __psp_pa(blob);
6283 data->len = params.len;
6287 data->handle = sev->handle;
6288 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6291 * If we query the session length, FW responded with expected data.
6300 if (copy_to_user(p, blob, params.len))
6305 params.len = data->len;
6306 if (copy_to_user(measure, ¶ms, sizeof(params)))
6315 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6317 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6318 struct sev_data_launch_finish *data;
6321 if (!sev_guest(kvm))
6324 data = kzalloc(sizeof(*data), GFP_KERNEL);
6328 data->handle = sev->handle;
6329 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6335 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6337 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6338 struct kvm_sev_guest_status params;
6339 struct sev_data_guest_status *data;
6342 if (!sev_guest(kvm))
6345 data = kzalloc(sizeof(*data), GFP_KERNEL);
6349 data->handle = sev->handle;
6350 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6354 params.policy = data->policy;
6355 params.state = data->state;
6356 params.handle = data->handle;
6358 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6365 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6366 unsigned long dst, int size,
6367 int *error, bool enc)
6369 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6370 struct sev_data_dbg *data;
6373 data = kzalloc(sizeof(*data), GFP_KERNEL);
6377 data->handle = sev->handle;
6378 data->dst_addr = dst;
6379 data->src_addr = src;
6382 ret = sev_issue_cmd(kvm,
6383 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6389 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6390 unsigned long dst_paddr, int sz, int *err)
6395 * Its safe to read more than we are asked, caller should ensure that
6396 * destination has enough space.
6398 src_paddr = round_down(src_paddr, 16);
6399 offset = src_paddr & 15;
6400 sz = round_up(sz + offset, 16);
6402 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6405 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6406 unsigned long __user dst_uaddr,
6407 unsigned long dst_paddr,
6410 struct page *tpage = NULL;
6413 /* if inputs are not 16-byte then use intermediate buffer */
6414 if (!IS_ALIGNED(dst_paddr, 16) ||
6415 !IS_ALIGNED(paddr, 16) ||
6416 !IS_ALIGNED(size, 16)) {
6417 tpage = (void *)alloc_page(GFP_KERNEL);
6421 dst_paddr = __sme_page_pa(tpage);
6424 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6429 offset = paddr & 15;
6430 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6431 page_address(tpage) + offset, size))
6442 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6443 unsigned long __user vaddr,
6444 unsigned long dst_paddr,
6445 unsigned long __user dst_vaddr,
6446 int size, int *error)
6448 struct page *src_tpage = NULL;
6449 struct page *dst_tpage = NULL;
6450 int ret, len = size;
6452 /* If source buffer is not aligned then use an intermediate buffer */
6453 if (!IS_ALIGNED(vaddr, 16)) {
6454 src_tpage = alloc_page(GFP_KERNEL);
6458 if (copy_from_user(page_address(src_tpage),
6459 (void __user *)(uintptr_t)vaddr, size)) {
6460 __free_page(src_tpage);
6464 paddr = __sme_page_pa(src_tpage);
6468 * If destination buffer or length is not aligned then do read-modify-write:
6469 * - decrypt destination in an intermediate buffer
6470 * - copy the source buffer in an intermediate buffer
6471 * - use the intermediate buffer as source buffer
6473 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6476 dst_tpage = alloc_page(GFP_KERNEL);
6482 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6483 __sme_page_pa(dst_tpage), size, error);
6488 * If source is kernel buffer then use memcpy() otherwise
6491 dst_offset = dst_paddr & 15;
6494 memcpy(page_address(dst_tpage) + dst_offset,
6495 page_address(src_tpage), size);
6497 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6498 (void __user *)(uintptr_t)vaddr, size)) {
6504 paddr = __sme_page_pa(dst_tpage);
6505 dst_paddr = round_down(dst_paddr, 16);
6506 len = round_up(size, 16);
6509 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6513 __free_page(src_tpage);
6515 __free_page(dst_tpage);
6519 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6521 unsigned long vaddr, vaddr_end, next_vaddr;
6522 unsigned long dst_vaddr, dst_vaddr_end;
6523 struct page **src_p, **dst_p;
6524 struct kvm_sev_dbg debug;
6528 if (!sev_guest(kvm))
6531 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6534 vaddr = debug.src_uaddr;
6536 vaddr_end = vaddr + size;
6537 dst_vaddr = debug.dst_uaddr;
6538 dst_vaddr_end = dst_vaddr + size;
6540 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6541 int len, s_off, d_off;
6543 /* lock userspace source and destination page */
6544 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6548 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6550 sev_unpin_memory(kvm, src_p, n);
6555 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6556 * memory content (i.e it will write the same memory region with C=1).
6557 * It's possible that the cache may contain the data with C=0, i.e.,
6558 * unencrypted so invalidate it first.
6560 sev_clflush_pages(src_p, 1);
6561 sev_clflush_pages(dst_p, 1);
6564 * Since user buffer may not be page aligned, calculate the
6565 * offset within the page.
6567 s_off = vaddr & ~PAGE_MASK;
6568 d_off = dst_vaddr & ~PAGE_MASK;
6569 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6572 ret = __sev_dbg_decrypt_user(kvm,
6573 __sme_page_pa(src_p[0]) + s_off,
6575 __sme_page_pa(dst_p[0]) + d_off,
6578 ret = __sev_dbg_encrypt_user(kvm,
6579 __sme_page_pa(src_p[0]) + s_off,
6581 __sme_page_pa(dst_p[0]) + d_off,
6585 sev_unpin_memory(kvm, src_p, 1);
6586 sev_unpin_memory(kvm, dst_p, 1);
6591 next_vaddr = vaddr + len;
6592 dst_vaddr = dst_vaddr + len;
6599 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6601 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6602 struct sev_data_launch_secret *data;
6603 struct kvm_sev_launch_secret params;
6604 struct page **pages;
6609 if (!sev_guest(kvm))
6612 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6615 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6620 * The secret must be copied into contiguous memory region, lets verify
6621 * that userspace memory pages are contiguous before we issue command.
6623 if (get_num_contig_pages(0, pages, n) != n) {
6625 goto e_unpin_memory;
6629 data = kzalloc(sizeof(*data), GFP_KERNEL);
6631 goto e_unpin_memory;
6633 offset = params.guest_uaddr & (PAGE_SIZE - 1);
6634 data->guest_address = __sme_page_pa(pages[0]) + offset;
6635 data->guest_len = params.guest_len;
6637 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6639 ret = PTR_ERR(blob);
6643 data->trans_address = __psp_pa(blob);
6644 data->trans_len = params.trans_len;
6646 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6651 data->hdr_address = __psp_pa(hdr);
6652 data->hdr_len = params.hdr_len;
6654 data->handle = sev->handle;
6655 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
6664 sev_unpin_memory(kvm, pages, n);
6668 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
6670 struct kvm_sev_cmd sev_cmd;
6673 if (!svm_sev_enabled())
6676 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
6679 mutex_lock(&kvm->lock);
6681 switch (sev_cmd.id) {
6683 r = sev_guest_init(kvm, &sev_cmd);
6685 case KVM_SEV_LAUNCH_START:
6686 r = sev_launch_start(kvm, &sev_cmd);
6688 case KVM_SEV_LAUNCH_UPDATE_DATA:
6689 r = sev_launch_update_data(kvm, &sev_cmd);
6691 case KVM_SEV_LAUNCH_MEASURE:
6692 r = sev_launch_measure(kvm, &sev_cmd);
6694 case KVM_SEV_LAUNCH_FINISH:
6695 r = sev_launch_finish(kvm, &sev_cmd);
6697 case KVM_SEV_GUEST_STATUS:
6698 r = sev_guest_status(kvm, &sev_cmd);
6700 case KVM_SEV_DBG_DECRYPT:
6701 r = sev_dbg_crypt(kvm, &sev_cmd, true);
6703 case KVM_SEV_DBG_ENCRYPT:
6704 r = sev_dbg_crypt(kvm, &sev_cmd, false);
6706 case KVM_SEV_LAUNCH_SECRET:
6707 r = sev_launch_secret(kvm, &sev_cmd);
6714 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
6718 mutex_unlock(&kvm->lock);
6722 static int svm_register_enc_region(struct kvm *kvm,
6723 struct kvm_enc_region *range)
6725 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6726 struct enc_region *region;
6729 if (!sev_guest(kvm))
6732 region = kzalloc(sizeof(*region), GFP_KERNEL);
6736 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
6737 if (!region->pages) {
6743 * The guest may change the memory encryption attribute from C=0 -> C=1
6744 * or vice versa for this memory range. Lets make sure caches are
6745 * flushed to ensure that guest data gets written into memory with
6748 sev_clflush_pages(region->pages, region->npages);
6750 region->uaddr = range->addr;
6751 region->size = range->size;
6753 mutex_lock(&kvm->lock);
6754 list_add_tail(®ion->list, &sev->regions_list);
6755 mutex_unlock(&kvm->lock);
6764 static struct enc_region *
6765 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
6767 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6768 struct list_head *head = &sev->regions_list;
6769 struct enc_region *i;
6771 list_for_each_entry(i, head, list) {
6772 if (i->uaddr == range->addr &&
6773 i->size == range->size)
6781 static int svm_unregister_enc_region(struct kvm *kvm,
6782 struct kvm_enc_region *range)
6784 struct enc_region *region;
6787 mutex_lock(&kvm->lock);
6789 if (!sev_guest(kvm)) {
6794 region = find_enc_region(kvm, range);
6800 __unregister_enc_region_locked(kvm, region);
6802 mutex_unlock(&kvm->lock);
6806 mutex_unlock(&kvm->lock);
6810 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
6811 .cpu_has_kvm_support = has_svm,
6812 .disabled_by_bios = is_disabled,
6813 .hardware_setup = svm_hardware_setup,
6814 .hardware_unsetup = svm_hardware_unsetup,
6815 .check_processor_compatibility = svm_check_processor_compat,
6816 .hardware_enable = svm_hardware_enable,
6817 .hardware_disable = svm_hardware_disable,
6818 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
6819 .cpu_has_high_real_mode_segbase = svm_has_high_real_mode_segbase,
6821 .vcpu_create = svm_create_vcpu,
6822 .vcpu_free = svm_free_vcpu,
6823 .vcpu_reset = svm_vcpu_reset,
6825 .vm_init = avic_vm_init,
6826 .vm_destroy = svm_vm_destroy,
6828 .prepare_guest_switch = svm_prepare_guest_switch,
6829 .vcpu_load = svm_vcpu_load,
6830 .vcpu_put = svm_vcpu_put,
6831 .vcpu_blocking = svm_vcpu_blocking,
6832 .vcpu_unblocking = svm_vcpu_unblocking,
6834 .update_bp_intercept = update_bp_intercept,
6835 .get_msr = svm_get_msr,
6836 .set_msr = svm_set_msr,
6837 .get_segment_base = svm_get_segment_base,
6838 .get_segment = svm_get_segment,
6839 .set_segment = svm_set_segment,
6840 .get_cpl = svm_get_cpl,
6841 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
6842 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
6843 .decache_cr3 = svm_decache_cr3,
6844 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
6845 .set_cr0 = svm_set_cr0,
6846 .set_cr3 = svm_set_cr3,
6847 .set_cr4 = svm_set_cr4,
6848 .set_efer = svm_set_efer,
6849 .get_idt = svm_get_idt,
6850 .set_idt = svm_set_idt,
6851 .get_gdt = svm_get_gdt,
6852 .set_gdt = svm_set_gdt,
6853 .get_dr6 = svm_get_dr6,
6854 .set_dr6 = svm_set_dr6,
6855 .set_dr7 = svm_set_dr7,
6856 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
6857 .cache_reg = svm_cache_reg,
6858 .get_rflags = svm_get_rflags,
6859 .set_rflags = svm_set_rflags,
6861 .tlb_flush = svm_flush_tlb,
6863 .run = svm_vcpu_run,
6864 .handle_exit = handle_exit,
6865 .skip_emulated_instruction = skip_emulated_instruction,
6866 .set_interrupt_shadow = svm_set_interrupt_shadow,
6867 .get_interrupt_shadow = svm_get_interrupt_shadow,
6868 .patch_hypercall = svm_patch_hypercall,
6869 .set_irq = svm_set_irq,
6870 .set_nmi = svm_inject_nmi,
6871 .queue_exception = svm_queue_exception,
6872 .cancel_injection = svm_cancel_injection,
6873 .interrupt_allowed = svm_interrupt_allowed,
6874 .nmi_allowed = svm_nmi_allowed,
6875 .get_nmi_mask = svm_get_nmi_mask,
6876 .set_nmi_mask = svm_set_nmi_mask,
6877 .enable_nmi_window = enable_nmi_window,
6878 .enable_irq_window = enable_irq_window,
6879 .update_cr8_intercept = update_cr8_intercept,
6880 .set_virtual_x2apic_mode = svm_set_virtual_x2apic_mode,
6881 .get_enable_apicv = svm_get_enable_apicv,
6882 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
6883 .load_eoi_exitmap = svm_load_eoi_exitmap,
6884 .hwapic_irr_update = svm_hwapic_irr_update,
6885 .hwapic_isr_update = svm_hwapic_isr_update,
6886 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
6887 .apicv_post_state_restore = avic_post_state_restore,
6889 .set_tss_addr = svm_set_tss_addr,
6890 .get_tdp_level = get_npt_level,
6891 .get_mt_mask = svm_get_mt_mask,
6893 .get_exit_info = svm_get_exit_info,
6895 .get_lpage_level = svm_get_lpage_level,
6897 .cpuid_update = svm_cpuid_update,
6899 .rdtscp_supported = svm_rdtscp_supported,
6900 .invpcid_supported = svm_invpcid_supported,
6901 .mpx_supported = svm_mpx_supported,
6902 .xsaves_supported = svm_xsaves_supported,
6903 .umip_emulated = svm_umip_emulated,
6905 .set_supported_cpuid = svm_set_supported_cpuid,
6907 .has_wbinvd_exit = svm_has_wbinvd_exit,
6909 .write_tsc_offset = svm_write_tsc_offset,
6911 .set_tdp_cr3 = set_tdp_cr3,
6913 .check_intercept = svm_check_intercept,
6914 .handle_external_intr = svm_handle_external_intr,
6916 .sched_in = svm_sched_in,
6918 .pmu_ops = &amd_pmu_ops,
6919 .deliver_posted_interrupt = svm_deliver_avic_intr,
6920 .update_pi_irte = svm_update_pi_irte,
6921 .setup_mce = svm_setup_mce,
6923 .smi_allowed = svm_smi_allowed,
6924 .pre_enter_smm = svm_pre_enter_smm,
6925 .pre_leave_smm = svm_pre_leave_smm,
6926 .enable_smi_window = enable_smi_window,
6928 .mem_enc_op = svm_mem_enc_op,
6929 .mem_enc_reg_region = svm_register_enc_region,
6930 .mem_enc_unreg_region = svm_unregister_enc_region,
6933 static int __init svm_init(void)
6935 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
6936 __alignof__(struct vcpu_svm), THIS_MODULE);
6939 static void __exit svm_exit(void)
6944 module_init(svm_init)
6945 module_exit(svm_exit)