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;
185 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
199 struct nested_state nested;
202 u64 nmi_singlestep_guest_rflags;
204 unsigned int3_injected;
205 unsigned long int3_rip;
207 /* cached guest cpuid flags for faster access */
208 bool nrips_enabled : 1;
211 struct page *avic_backing_page;
212 u64 *avic_physical_id_cache;
213 bool avic_is_running;
216 * Per-vcpu list of struct amd_svm_iommu_ir:
217 * This is used mainly to store interrupt remapping information used
218 * when update the vcpu affinity. This avoids the need to scan for
219 * IRTE and try to match ga_tag in the IOMMU driver.
221 struct list_head ir_list;
222 spinlock_t ir_list_lock;
224 /* which host CPU was used for running this vcpu */
225 unsigned int last_cpu;
229 * This is a wrapper of struct amd_iommu_ir_data.
231 struct amd_svm_iommu_ir {
232 struct list_head node; /* Used by SVM for per-vcpu ir_list */
233 void *data; /* Storing pointer to struct amd_ir_data */
236 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
237 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
239 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
240 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
241 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
242 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
244 static DEFINE_PER_CPU(u64, current_tsc_ratio);
245 #define TSC_RATIO_DEFAULT 0x0100000000ULL
247 #define MSR_INVALID 0xffffffffU
249 static const struct svm_direct_access_msrs {
250 u32 index; /* Index of the MSR */
251 bool always; /* True if intercept is always on */
252 } direct_access_msrs[] = {
253 { .index = MSR_STAR, .always = true },
254 { .index = MSR_IA32_SYSENTER_CS, .always = true },
256 { .index = MSR_GS_BASE, .always = true },
257 { .index = MSR_FS_BASE, .always = true },
258 { .index = MSR_KERNEL_GS_BASE, .always = true },
259 { .index = MSR_LSTAR, .always = true },
260 { .index = MSR_CSTAR, .always = true },
261 { .index = MSR_SYSCALL_MASK, .always = true },
263 { .index = MSR_IA32_SPEC_CTRL, .always = false },
264 { .index = MSR_IA32_PRED_CMD, .always = false },
265 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
266 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
267 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
268 { .index = MSR_IA32_LASTINTTOIP, .always = false },
269 { .index = MSR_INVALID, .always = false },
272 /* enable NPT for AMD64 and X86 with PAE */
273 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
274 static bool npt_enabled = true;
276 static bool npt_enabled;
279 /* allow nested paging (virtualized MMU) for all guests */
280 static int npt = true;
281 module_param(npt, int, S_IRUGO);
283 /* allow nested virtualization in KVM/SVM */
284 static int nested = true;
285 module_param(nested, int, S_IRUGO);
287 /* enable / disable AVIC */
289 #ifdef CONFIG_X86_LOCAL_APIC
290 module_param(avic, int, S_IRUGO);
293 /* enable/disable Virtual VMLOAD VMSAVE */
294 static int vls = true;
295 module_param(vls, int, 0444);
297 /* enable/disable Virtual GIF */
298 static int vgif = true;
299 module_param(vgif, int, 0444);
301 /* enable/disable SEV support */
302 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
303 module_param(sev, int, 0444);
305 static u8 rsm_ins_bytes[] = "\x0f\xaa";
307 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
308 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
309 static void svm_complete_interrupts(struct vcpu_svm *svm);
311 static int nested_svm_exit_handled(struct vcpu_svm *svm);
312 static int nested_svm_intercept(struct vcpu_svm *svm);
313 static int nested_svm_vmexit(struct vcpu_svm *svm);
314 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
315 bool has_error_code, u32 error_code);
318 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
319 pause filter count */
320 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
321 VMCB_ASID, /* ASID */
322 VMCB_INTR, /* int_ctl, int_vector */
323 VMCB_NPT, /* npt_en, nCR3, gPAT */
324 VMCB_CR, /* CR0, CR3, CR4, EFER */
325 VMCB_DR, /* DR6, DR7 */
326 VMCB_DT, /* GDT, IDT */
327 VMCB_SEG, /* CS, DS, SS, ES, CPL */
328 VMCB_CR2, /* CR2 only */
329 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
330 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
331 * AVIC PHYSICAL_TABLE pointer,
332 * AVIC LOGICAL_TABLE pointer
337 /* TPR and CR2 are always written before VMRUN */
338 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
340 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
342 static unsigned int max_sev_asid;
343 static unsigned int min_sev_asid;
344 static unsigned long *sev_asid_bitmap;
345 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
348 struct list_head list;
349 unsigned long npages;
355 static inline bool svm_sev_enabled(void)
360 static inline bool sev_guest(struct kvm *kvm)
362 struct kvm_sev_info *sev = &kvm->arch.sev_info;
367 static inline int sev_get_asid(struct kvm *kvm)
369 struct kvm_sev_info *sev = &kvm->arch.sev_info;
374 static inline void mark_all_dirty(struct vmcb *vmcb)
376 vmcb->control.clean = 0;
379 static inline void mark_all_clean(struct vmcb *vmcb)
381 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
382 & ~VMCB_ALWAYS_DIRTY_MASK;
385 static inline void mark_dirty(struct vmcb *vmcb, int bit)
387 vmcb->control.clean &= ~(1 << bit);
390 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
392 return container_of(vcpu, struct vcpu_svm, vcpu);
395 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
397 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
398 mark_dirty(svm->vmcb, VMCB_AVIC);
401 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
403 struct vcpu_svm *svm = to_svm(vcpu);
404 u64 *entry = svm->avic_physical_id_cache;
409 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
412 static void recalc_intercepts(struct vcpu_svm *svm)
414 struct vmcb_control_area *c, *h;
415 struct nested_state *g;
417 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
419 if (!is_guest_mode(&svm->vcpu))
422 c = &svm->vmcb->control;
423 h = &svm->nested.hsave->control;
426 c->intercept_cr = h->intercept_cr | g->intercept_cr;
427 c->intercept_dr = h->intercept_dr | g->intercept_dr;
428 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
429 c->intercept = h->intercept | g->intercept;
432 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
434 if (is_guest_mode(&svm->vcpu))
435 return svm->nested.hsave;
440 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
442 struct vmcb *vmcb = get_host_vmcb(svm);
444 vmcb->control.intercept_cr |= (1U << bit);
446 recalc_intercepts(svm);
449 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
451 struct vmcb *vmcb = get_host_vmcb(svm);
453 vmcb->control.intercept_cr &= ~(1U << bit);
455 recalc_intercepts(svm);
458 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
460 struct vmcb *vmcb = get_host_vmcb(svm);
462 return vmcb->control.intercept_cr & (1U << bit);
465 static inline void set_dr_intercepts(struct vcpu_svm *svm)
467 struct vmcb *vmcb = get_host_vmcb(svm);
469 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
470 | (1 << INTERCEPT_DR1_READ)
471 | (1 << INTERCEPT_DR2_READ)
472 | (1 << INTERCEPT_DR3_READ)
473 | (1 << INTERCEPT_DR4_READ)
474 | (1 << INTERCEPT_DR5_READ)
475 | (1 << INTERCEPT_DR6_READ)
476 | (1 << INTERCEPT_DR7_READ)
477 | (1 << INTERCEPT_DR0_WRITE)
478 | (1 << INTERCEPT_DR1_WRITE)
479 | (1 << INTERCEPT_DR2_WRITE)
480 | (1 << INTERCEPT_DR3_WRITE)
481 | (1 << INTERCEPT_DR4_WRITE)
482 | (1 << INTERCEPT_DR5_WRITE)
483 | (1 << INTERCEPT_DR6_WRITE)
484 | (1 << INTERCEPT_DR7_WRITE);
486 recalc_intercepts(svm);
489 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
491 struct vmcb *vmcb = get_host_vmcb(svm);
493 vmcb->control.intercept_dr = 0;
495 recalc_intercepts(svm);
498 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
500 struct vmcb *vmcb = get_host_vmcb(svm);
502 vmcb->control.intercept_exceptions |= (1U << bit);
504 recalc_intercepts(svm);
507 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
509 struct vmcb *vmcb = get_host_vmcb(svm);
511 vmcb->control.intercept_exceptions &= ~(1U << bit);
513 recalc_intercepts(svm);
516 static inline void set_intercept(struct vcpu_svm *svm, int bit)
518 struct vmcb *vmcb = get_host_vmcb(svm);
520 vmcb->control.intercept |= (1ULL << bit);
522 recalc_intercepts(svm);
525 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
527 struct vmcb *vmcb = get_host_vmcb(svm);
529 vmcb->control.intercept &= ~(1ULL << bit);
531 recalc_intercepts(svm);
534 static inline bool vgif_enabled(struct vcpu_svm *svm)
536 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
539 static inline void enable_gif(struct vcpu_svm *svm)
541 if (vgif_enabled(svm))
542 svm->vmcb->control.int_ctl |= V_GIF_MASK;
544 svm->vcpu.arch.hflags |= HF_GIF_MASK;
547 static inline void disable_gif(struct vcpu_svm *svm)
549 if (vgif_enabled(svm))
550 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
552 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
555 static inline bool gif_set(struct vcpu_svm *svm)
557 if (vgif_enabled(svm))
558 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
560 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
563 static unsigned long iopm_base;
565 struct kvm_ldttss_desc {
568 unsigned base1:8, type:5, dpl:2, p:1;
569 unsigned limit1:4, zero0:3, g:1, base2:8;
572 } __attribute__((packed));
574 struct svm_cpu_data {
581 struct kvm_ldttss_desc *tss_desc;
583 struct page *save_area;
584 struct vmcb *current_vmcb;
586 /* index = sev_asid, value = vmcb pointer */
587 struct vmcb **sev_vmcbs;
590 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
592 struct svm_init_data {
597 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
599 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
600 #define MSRS_RANGE_SIZE 2048
601 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
603 static u32 svm_msrpm_offset(u32 msr)
608 for (i = 0; i < NUM_MSR_MAPS; i++) {
609 if (msr < msrpm_ranges[i] ||
610 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
613 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
614 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
616 /* Now we have the u8 offset - but need the u32 offset */
620 /* MSR not in any range */
624 #define MAX_INST_SIZE 15
626 static inline void clgi(void)
628 asm volatile (__ex(SVM_CLGI));
631 static inline void stgi(void)
633 asm volatile (__ex(SVM_STGI));
636 static inline void invlpga(unsigned long addr, u32 asid)
638 asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
641 static int get_npt_level(struct kvm_vcpu *vcpu)
644 return PT64_ROOT_4LEVEL;
646 return PT32E_ROOT_LEVEL;
650 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
652 vcpu->arch.efer = efer;
653 if (!npt_enabled && !(efer & EFER_LMA))
656 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
657 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
660 static int is_external_interrupt(u32 info)
662 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
663 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
666 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
668 struct vcpu_svm *svm = to_svm(vcpu);
671 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
672 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
676 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
678 struct vcpu_svm *svm = to_svm(vcpu);
681 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
683 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
687 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
689 struct vcpu_svm *svm = to_svm(vcpu);
691 if (svm->vmcb->control.next_rip != 0) {
692 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
693 svm->next_rip = svm->vmcb->control.next_rip;
696 if (!svm->next_rip) {
697 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
699 printk(KERN_DEBUG "%s: NOP\n", __func__);
702 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
703 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
704 __func__, kvm_rip_read(vcpu), svm->next_rip);
706 kvm_rip_write(vcpu, svm->next_rip);
707 svm_set_interrupt_shadow(vcpu, 0);
710 static void svm_queue_exception(struct kvm_vcpu *vcpu)
712 struct vcpu_svm *svm = to_svm(vcpu);
713 unsigned nr = vcpu->arch.exception.nr;
714 bool has_error_code = vcpu->arch.exception.has_error_code;
715 bool reinject = vcpu->arch.exception.injected;
716 u32 error_code = vcpu->arch.exception.error_code;
719 * If we are within a nested VM we'd better #VMEXIT and let the guest
720 * handle the exception
723 nested_svm_check_exception(svm, nr, has_error_code, error_code))
726 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
727 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
730 * For guest debugging where we have to reinject #BP if some
731 * INT3 is guest-owned:
732 * Emulate nRIP by moving RIP forward. Will fail if injection
733 * raises a fault that is not intercepted. Still better than
734 * failing in all cases.
736 skip_emulated_instruction(&svm->vcpu);
737 rip = kvm_rip_read(&svm->vcpu);
738 svm->int3_rip = rip + svm->vmcb->save.cs.base;
739 svm->int3_injected = rip - old_rip;
742 svm->vmcb->control.event_inj = nr
744 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
745 | SVM_EVTINJ_TYPE_EXEPT;
746 svm->vmcb->control.event_inj_err = error_code;
749 static void svm_init_erratum_383(void)
755 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
758 /* Use _safe variants to not break nested virtualization */
759 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
765 low = lower_32_bits(val);
766 high = upper_32_bits(val);
768 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
770 erratum_383_found = true;
773 static void svm_init_osvw(struct kvm_vcpu *vcpu)
776 * Guests should see errata 400 and 415 as fixed (assuming that
777 * HLT and IO instructions are intercepted).
779 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
780 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
783 * By increasing VCPU's osvw.length to 3 we are telling the guest that
784 * all osvw.status bits inside that length, including bit 0 (which is
785 * reserved for erratum 298), are valid. However, if host processor's
786 * osvw_len is 0 then osvw_status[0] carries no information. We need to
787 * be conservative here and therefore we tell the guest that erratum 298
788 * is present (because we really don't know).
790 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
791 vcpu->arch.osvw.status |= 1;
794 static int has_svm(void)
798 if (!cpu_has_svm(&msg)) {
799 printk(KERN_INFO "has_svm: %s\n", msg);
806 static void svm_hardware_disable(void)
808 /* Make sure we clean up behind us */
809 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
810 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
814 amd_pmu_disable_virt();
817 static int svm_hardware_enable(void)
820 struct svm_cpu_data *sd;
822 struct desc_struct *gdt;
823 int me = raw_smp_processor_id();
825 rdmsrl(MSR_EFER, efer);
826 if (efer & EFER_SVME)
830 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
833 sd = per_cpu(svm_data, me);
835 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
839 sd->asid_generation = 1;
840 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
841 sd->next_asid = sd->max_asid + 1;
842 sd->min_asid = max_sev_asid + 1;
844 gdt = get_current_gdt_rw();
845 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
847 wrmsrl(MSR_EFER, efer | EFER_SVME);
849 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
851 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
852 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
853 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
860 * Note that it is possible to have a system with mixed processor
861 * revisions and therefore different OSVW bits. If bits are not the same
862 * on different processors then choose the worst case (i.e. if erratum
863 * is present on one processor and not on another then assume that the
864 * erratum is present everywhere).
866 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
867 uint64_t len, status = 0;
870 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
872 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
876 osvw_status = osvw_len = 0;
880 osvw_status |= status;
881 osvw_status &= (1ULL << osvw_len) - 1;
884 osvw_status = osvw_len = 0;
886 svm_init_erratum_383();
888 amd_pmu_enable_virt();
893 static void svm_cpu_uninit(int cpu)
895 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
900 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
901 kfree(sd->sev_vmcbs);
902 __free_page(sd->save_area);
906 static int svm_cpu_init(int cpu)
908 struct svm_cpu_data *sd;
911 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
916 sd->save_area = alloc_page(GFP_KERNEL);
920 if (svm_sev_enabled()) {
922 sd->sev_vmcbs = kmalloc((max_sev_asid + 1) * sizeof(void *), GFP_KERNEL);
927 per_cpu(svm_data, cpu) = sd;
937 static bool valid_msr_intercept(u32 index)
941 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
942 if (direct_access_msrs[i].index == index)
948 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
955 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
958 offset = svm_msrpm_offset(msr);
959 bit_write = 2 * (msr & 0x0f) + 1;
962 BUG_ON(offset == MSR_INVALID);
964 return !!test_bit(bit_write, &tmp);
967 static void set_msr_interception(u32 *msrpm, unsigned msr,
970 u8 bit_read, bit_write;
975 * If this warning triggers extend the direct_access_msrs list at the
976 * beginning of the file
978 WARN_ON(!valid_msr_intercept(msr));
980 offset = svm_msrpm_offset(msr);
981 bit_read = 2 * (msr & 0x0f);
982 bit_write = 2 * (msr & 0x0f) + 1;
985 BUG_ON(offset == MSR_INVALID);
987 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
988 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
993 static void svm_vcpu_init_msrpm(u32 *msrpm)
997 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
999 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1000 if (!direct_access_msrs[i].always)
1003 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1007 static void add_msr_offset(u32 offset)
1011 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1013 /* Offset already in list? */
1014 if (msrpm_offsets[i] == offset)
1017 /* Slot used by another offset? */
1018 if (msrpm_offsets[i] != MSR_INVALID)
1021 /* Add offset to list */
1022 msrpm_offsets[i] = offset;
1028 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1029 * increase MSRPM_OFFSETS in this case.
1034 static void init_msrpm_offsets(void)
1038 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1040 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1043 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1044 BUG_ON(offset == MSR_INVALID);
1046 add_msr_offset(offset);
1050 static void svm_enable_lbrv(struct vcpu_svm *svm)
1052 u32 *msrpm = svm->msrpm;
1054 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1055 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1056 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1057 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1058 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1061 static void svm_disable_lbrv(struct vcpu_svm *svm)
1063 u32 *msrpm = svm->msrpm;
1065 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1066 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1067 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1068 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1069 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1072 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1074 svm->nmi_singlestep = false;
1076 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1077 /* Clear our flags if they were not set by the guest */
1078 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1079 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1080 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1081 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1086 * This hash table is used to map VM_ID to a struct kvm_arch,
1087 * when handling AMD IOMMU GALOG notification to schedule in
1088 * a particular vCPU.
1090 #define SVM_VM_DATA_HASH_BITS 8
1091 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1092 static u32 next_vm_id = 0;
1093 static bool next_vm_id_wrapped = 0;
1094 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1097 * This function is called from IOMMU driver to notify
1098 * SVM to schedule in a particular vCPU of a particular VM.
1100 static int avic_ga_log_notifier(u32 ga_tag)
1102 unsigned long flags;
1103 struct kvm_arch *ka = NULL;
1104 struct kvm_vcpu *vcpu = NULL;
1105 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1106 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1108 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1110 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1111 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1112 struct kvm *kvm = container_of(ka, struct kvm, arch);
1113 struct kvm_arch *vm_data = &kvm->arch;
1115 if (vm_data->avic_vm_id != vm_id)
1117 vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
1120 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1123 * At this point, the IOMMU should have already set the pending
1124 * bit in the vAPIC backing page. So, we just need to schedule
1128 kvm_vcpu_wake_up(vcpu);
1133 static __init int sev_hardware_setup(void)
1135 struct sev_user_data_status *status;
1138 /* Maximum number of encrypted guests supported simultaneously */
1139 max_sev_asid = cpuid_ecx(0x8000001F);
1144 /* Minimum ASID value that should be used for SEV guest */
1145 min_sev_asid = cpuid_edx(0x8000001F);
1147 /* Initialize SEV ASID bitmap */
1148 sev_asid_bitmap = kcalloc(BITS_TO_LONGS(max_sev_asid),
1149 sizeof(unsigned long), GFP_KERNEL);
1150 if (!sev_asid_bitmap)
1153 status = kmalloc(sizeof(*status), GFP_KERNEL);
1158 * Check SEV platform status.
1160 * PLATFORM_STATUS can be called in any state, if we failed to query
1161 * the PLATFORM status then either PSP firmware does not support SEV
1162 * feature or SEV firmware is dead.
1164 rc = sev_platform_status(status, NULL);
1168 pr_info("SEV supported\n");
1175 static __init int svm_hardware_setup(void)
1178 struct page *iopm_pages;
1182 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1187 iopm_va = page_address(iopm_pages);
1188 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1189 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1191 init_msrpm_offsets();
1193 if (boot_cpu_has(X86_FEATURE_NX))
1194 kvm_enable_efer_bits(EFER_NX);
1196 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1197 kvm_enable_efer_bits(EFER_FFXSR);
1199 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1200 kvm_has_tsc_control = true;
1201 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1202 kvm_tsc_scaling_ratio_frac_bits = 32;
1206 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1207 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1211 if (boot_cpu_has(X86_FEATURE_SEV) &&
1212 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1213 r = sev_hardware_setup();
1221 for_each_possible_cpu(cpu) {
1222 r = svm_cpu_init(cpu);
1227 if (!boot_cpu_has(X86_FEATURE_NPT))
1228 npt_enabled = false;
1230 if (npt_enabled && !npt) {
1231 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1232 npt_enabled = false;
1236 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1243 !boot_cpu_has(X86_FEATURE_AVIC) ||
1244 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1247 pr_info("AVIC enabled\n");
1249 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1255 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1256 !IS_ENABLED(CONFIG_X86_64)) {
1259 pr_info("Virtual VMLOAD VMSAVE supported\n");
1264 if (!boot_cpu_has(X86_FEATURE_VGIF))
1267 pr_info("Virtual GIF supported\n");
1273 __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1278 static __exit void svm_hardware_unsetup(void)
1282 if (svm_sev_enabled())
1283 kfree(sev_asid_bitmap);
1285 for_each_possible_cpu(cpu)
1286 svm_cpu_uninit(cpu);
1288 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1292 static void init_seg(struct vmcb_seg *seg)
1295 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1296 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1297 seg->limit = 0xffff;
1301 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1304 seg->attrib = SVM_SELECTOR_P_MASK | type;
1305 seg->limit = 0xffff;
1309 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1311 struct vcpu_svm *svm = to_svm(vcpu);
1312 u64 g_tsc_offset = 0;
1314 if (is_guest_mode(vcpu)) {
1315 g_tsc_offset = svm->vmcb->control.tsc_offset -
1316 svm->nested.hsave->control.tsc_offset;
1317 svm->nested.hsave->control.tsc_offset = offset;
1319 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1320 svm->vmcb->control.tsc_offset,
1323 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1325 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1328 static void avic_init_vmcb(struct vcpu_svm *svm)
1330 struct vmcb *vmcb = svm->vmcb;
1331 struct kvm_arch *vm_data = &svm->vcpu.kvm->arch;
1332 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1333 phys_addr_t lpa = __sme_set(page_to_phys(vm_data->avic_logical_id_table_page));
1334 phys_addr_t ppa = __sme_set(page_to_phys(vm_data->avic_physical_id_table_page));
1336 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1337 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1338 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1339 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1340 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1343 static void init_vmcb(struct vcpu_svm *svm)
1345 struct vmcb_control_area *control = &svm->vmcb->control;
1346 struct vmcb_save_area *save = &svm->vmcb->save;
1348 svm->vcpu.arch.hflags = 0;
1350 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1351 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1352 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1353 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1354 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1355 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1356 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1357 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1359 set_dr_intercepts(svm);
1361 set_exception_intercept(svm, PF_VECTOR);
1362 set_exception_intercept(svm, UD_VECTOR);
1363 set_exception_intercept(svm, MC_VECTOR);
1364 set_exception_intercept(svm, AC_VECTOR);
1365 set_exception_intercept(svm, DB_VECTOR);
1367 set_intercept(svm, INTERCEPT_INTR);
1368 set_intercept(svm, INTERCEPT_NMI);
1369 set_intercept(svm, INTERCEPT_SMI);
1370 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1371 set_intercept(svm, INTERCEPT_RDPMC);
1372 set_intercept(svm, INTERCEPT_CPUID);
1373 set_intercept(svm, INTERCEPT_INVD);
1374 set_intercept(svm, INTERCEPT_HLT);
1375 set_intercept(svm, INTERCEPT_INVLPG);
1376 set_intercept(svm, INTERCEPT_INVLPGA);
1377 set_intercept(svm, INTERCEPT_IOIO_PROT);
1378 set_intercept(svm, INTERCEPT_MSR_PROT);
1379 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1380 set_intercept(svm, INTERCEPT_SHUTDOWN);
1381 set_intercept(svm, INTERCEPT_VMRUN);
1382 set_intercept(svm, INTERCEPT_VMMCALL);
1383 set_intercept(svm, INTERCEPT_VMLOAD);
1384 set_intercept(svm, INTERCEPT_VMSAVE);
1385 set_intercept(svm, INTERCEPT_STGI);
1386 set_intercept(svm, INTERCEPT_CLGI);
1387 set_intercept(svm, INTERCEPT_SKINIT);
1388 set_intercept(svm, INTERCEPT_WBINVD);
1389 set_intercept(svm, INTERCEPT_XSETBV);
1390 set_intercept(svm, INTERCEPT_RSM);
1392 if (!kvm_mwait_in_guest()) {
1393 set_intercept(svm, INTERCEPT_MONITOR);
1394 set_intercept(svm, INTERCEPT_MWAIT);
1397 control->iopm_base_pa = __sme_set(iopm_base);
1398 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1399 control->int_ctl = V_INTR_MASKING_MASK;
1401 init_seg(&save->es);
1402 init_seg(&save->ss);
1403 init_seg(&save->ds);
1404 init_seg(&save->fs);
1405 init_seg(&save->gs);
1407 save->cs.selector = 0xf000;
1408 save->cs.base = 0xffff0000;
1409 /* Executable/Readable Code Segment */
1410 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1411 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1412 save->cs.limit = 0xffff;
1414 save->gdtr.limit = 0xffff;
1415 save->idtr.limit = 0xffff;
1417 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1418 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1420 svm_set_efer(&svm->vcpu, 0);
1421 save->dr6 = 0xffff0ff0;
1422 kvm_set_rflags(&svm->vcpu, 2);
1423 save->rip = 0x0000fff0;
1424 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1427 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1428 * It also updates the guest-visible cr0 value.
1430 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1431 kvm_mmu_reset_context(&svm->vcpu);
1433 save->cr4 = X86_CR4_PAE;
1437 /* Setup VMCB for Nested Paging */
1438 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1439 clr_intercept(svm, INTERCEPT_INVLPG);
1440 clr_exception_intercept(svm, PF_VECTOR);
1441 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1442 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1443 save->g_pat = svm->vcpu.arch.pat;
1447 svm->asid_generation = 0;
1449 svm->nested.vmcb = 0;
1450 svm->vcpu.arch.hflags = 0;
1452 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1453 control->pause_filter_count = 3000;
1454 set_intercept(svm, INTERCEPT_PAUSE);
1457 if (kvm_vcpu_apicv_active(&svm->vcpu))
1458 avic_init_vmcb(svm);
1461 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1462 * in VMCB and clear intercepts to avoid #VMEXIT.
1465 clr_intercept(svm, INTERCEPT_VMLOAD);
1466 clr_intercept(svm, INTERCEPT_VMSAVE);
1467 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1471 clr_intercept(svm, INTERCEPT_STGI);
1472 clr_intercept(svm, INTERCEPT_CLGI);
1473 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1476 if (sev_guest(svm->vcpu.kvm)) {
1477 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1478 clr_exception_intercept(svm, UD_VECTOR);
1481 mark_all_dirty(svm->vmcb);
1487 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1490 u64 *avic_physical_id_table;
1491 struct kvm_arch *vm_data = &vcpu->kvm->arch;
1493 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1496 avic_physical_id_table = page_address(vm_data->avic_physical_id_table_page);
1498 return &avic_physical_id_table[index];
1503 * AVIC hardware walks the nested page table to check permissions,
1504 * but does not use the SPA address specified in the leaf page
1505 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1506 * field of the VMCB. Therefore, we set up the
1507 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1509 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1511 struct kvm *kvm = vcpu->kvm;
1514 if (kvm->arch.apic_access_page_done)
1517 ret = x86_set_memory_region(kvm,
1518 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1519 APIC_DEFAULT_PHYS_BASE,
1524 kvm->arch.apic_access_page_done = true;
1528 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1531 u64 *entry, new_entry;
1532 int id = vcpu->vcpu_id;
1533 struct vcpu_svm *svm = to_svm(vcpu);
1535 ret = avic_init_access_page(vcpu);
1539 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1542 if (!svm->vcpu.arch.apic->regs)
1545 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1547 /* Setting AVIC backing page address in the phy APIC ID table */
1548 entry = avic_get_physical_id_entry(vcpu, id);
1552 new_entry = READ_ONCE(*entry);
1553 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1554 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1555 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1556 WRITE_ONCE(*entry, new_entry);
1558 svm->avic_physical_id_cache = entry;
1563 static void __sev_asid_free(int asid)
1565 struct svm_cpu_data *sd;
1569 clear_bit(pos, sev_asid_bitmap);
1571 for_each_possible_cpu(cpu) {
1572 sd = per_cpu(svm_data, cpu);
1573 sd->sev_vmcbs[pos] = NULL;
1577 static void sev_asid_free(struct kvm *kvm)
1579 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1581 __sev_asid_free(sev->asid);
1584 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1586 struct sev_data_decommission *decommission;
1587 struct sev_data_deactivate *data;
1592 data = kzalloc(sizeof(*data), GFP_KERNEL);
1596 /* deactivate handle */
1597 data->handle = handle;
1598 sev_guest_deactivate(data, NULL);
1600 wbinvd_on_all_cpus();
1601 sev_guest_df_flush(NULL);
1604 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1608 /* decommission handle */
1609 decommission->handle = handle;
1610 sev_guest_decommission(decommission, NULL);
1612 kfree(decommission);
1615 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1616 unsigned long ulen, unsigned long *n,
1619 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1620 unsigned long npages, npinned, size;
1621 unsigned long locked, lock_limit;
1622 struct page **pages;
1625 /* Calculate number of pages. */
1626 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1627 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1628 npages = (last - first + 1);
1630 locked = sev->pages_locked + npages;
1631 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1632 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1633 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1637 /* Avoid using vmalloc for smaller buffers. */
1638 size = npages * sizeof(struct page *);
1639 if (size > PAGE_SIZE)
1640 pages = vmalloc(size);
1642 pages = kmalloc(size, GFP_KERNEL);
1647 /* Pin the user virtual address. */
1648 npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1649 if (npinned != npages) {
1650 pr_err("SEV: Failure locking %lu pages.\n", npages);
1655 sev->pages_locked = locked;
1661 release_pages(pages, npinned);
1667 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1668 unsigned long npages)
1670 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1672 release_pages(pages, npages);
1674 sev->pages_locked -= npages;
1677 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1679 uint8_t *page_virtual;
1682 if (npages == 0 || pages == NULL)
1685 for (i = 0; i < npages; i++) {
1686 page_virtual = kmap_atomic(pages[i]);
1687 clflush_cache_range(page_virtual, PAGE_SIZE);
1688 kunmap_atomic(page_virtual);
1692 static void __unregister_enc_region_locked(struct kvm *kvm,
1693 struct enc_region *region)
1696 * The guest may change the memory encryption attribute from C=0 -> C=1
1697 * or vice versa for this memory range. Lets make sure caches are
1698 * flushed to ensure that guest data gets written into memory with
1701 sev_clflush_pages(region->pages, region->npages);
1703 sev_unpin_memory(kvm, region->pages, region->npages);
1704 list_del(®ion->list);
1708 static void sev_vm_destroy(struct kvm *kvm)
1710 struct kvm_sev_info *sev = &kvm->arch.sev_info;
1711 struct list_head *head = &sev->regions_list;
1712 struct list_head *pos, *q;
1714 if (!sev_guest(kvm))
1717 mutex_lock(&kvm->lock);
1720 * if userspace was terminated before unregistering the memory regions
1721 * then lets unpin all the registered memory.
1723 if (!list_empty(head)) {
1724 list_for_each_safe(pos, q, head) {
1725 __unregister_enc_region_locked(kvm,
1726 list_entry(pos, struct enc_region, list));
1730 mutex_unlock(&kvm->lock);
1732 sev_unbind_asid(kvm, sev->handle);
1736 static void avic_vm_destroy(struct kvm *kvm)
1738 unsigned long flags;
1739 struct kvm_arch *vm_data = &kvm->arch;
1744 if (vm_data->avic_logical_id_table_page)
1745 __free_page(vm_data->avic_logical_id_table_page);
1746 if (vm_data->avic_physical_id_table_page)
1747 __free_page(vm_data->avic_physical_id_table_page);
1749 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1750 hash_del(&vm_data->hnode);
1751 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1754 static void svm_vm_destroy(struct kvm *kvm)
1756 avic_vm_destroy(kvm);
1757 sev_vm_destroy(kvm);
1760 static int avic_vm_init(struct kvm *kvm)
1762 unsigned long flags;
1764 struct kvm_arch *vm_data = &kvm->arch;
1765 struct page *p_page;
1766 struct page *l_page;
1767 struct kvm_arch *ka;
1773 /* Allocating physical APIC ID table (4KB) */
1774 p_page = alloc_page(GFP_KERNEL);
1778 vm_data->avic_physical_id_table_page = p_page;
1779 clear_page(page_address(p_page));
1781 /* Allocating logical APIC ID table (4KB) */
1782 l_page = alloc_page(GFP_KERNEL);
1786 vm_data->avic_logical_id_table_page = l_page;
1787 clear_page(page_address(l_page));
1789 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1791 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1792 if (vm_id == 0) { /* id is 1-based, zero is not okay */
1793 next_vm_id_wrapped = 1;
1796 /* Is it still in use? Only possible if wrapped at least once */
1797 if (next_vm_id_wrapped) {
1798 hash_for_each_possible(svm_vm_data_hash, ka, hnode, vm_id) {
1799 struct kvm *k2 = container_of(ka, struct kvm, arch);
1800 struct kvm_arch *vd2 = &k2->arch;
1801 if (vd2->avic_vm_id == vm_id)
1805 vm_data->avic_vm_id = vm_id;
1806 hash_add(svm_vm_data_hash, &vm_data->hnode, vm_data->avic_vm_id);
1807 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1812 avic_vm_destroy(kvm);
1817 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1820 unsigned long flags;
1821 struct amd_svm_iommu_ir *ir;
1822 struct vcpu_svm *svm = to_svm(vcpu);
1824 if (!kvm_arch_has_assigned_device(vcpu->kvm))
1828 * Here, we go through the per-vcpu ir_list to update all existing
1829 * interrupt remapping table entry targeting this vcpu.
1831 spin_lock_irqsave(&svm->ir_list_lock, flags);
1833 if (list_empty(&svm->ir_list))
1836 list_for_each_entry(ir, &svm->ir_list, node) {
1837 ret = amd_iommu_update_ga(cpu, r, ir->data);
1842 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1846 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1849 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
1850 int h_physical_id = kvm_cpu_get_apicid(cpu);
1851 struct vcpu_svm *svm = to_svm(vcpu);
1853 if (!kvm_vcpu_apicv_active(vcpu))
1856 if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
1859 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1860 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1862 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1863 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1865 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1866 if (svm->avic_is_running)
1867 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1869 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1870 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
1871 svm->avic_is_running);
1874 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
1877 struct vcpu_svm *svm = to_svm(vcpu);
1879 if (!kvm_vcpu_apicv_active(vcpu))
1882 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1883 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
1884 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1886 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1887 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1891 * This function is called during VCPU halt/unhalt.
1893 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
1895 struct vcpu_svm *svm = to_svm(vcpu);
1897 svm->avic_is_running = is_run;
1899 avic_vcpu_load(vcpu, vcpu->cpu);
1901 avic_vcpu_put(vcpu);
1904 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1906 struct vcpu_svm *svm = to_svm(vcpu);
1913 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1914 MSR_IA32_APICBASE_ENABLE;
1915 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1916 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1920 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
1921 kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1923 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1924 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1927 static int avic_init_vcpu(struct vcpu_svm *svm)
1931 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1934 ret = avic_init_backing_page(&svm->vcpu);
1938 INIT_LIST_HEAD(&svm->ir_list);
1939 spin_lock_init(&svm->ir_list_lock);
1944 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1946 struct vcpu_svm *svm;
1948 struct page *msrpm_pages;
1949 struct page *hsave_page;
1950 struct page *nested_msrpm_pages;
1953 svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1959 err = kvm_vcpu_init(&svm->vcpu, kvm, id);
1964 page = alloc_page(GFP_KERNEL);
1968 msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1972 nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1973 if (!nested_msrpm_pages)
1976 hsave_page = alloc_page(GFP_KERNEL);
1980 err = avic_init_vcpu(svm);
1984 /* We initialize this flag to true to make sure that the is_running
1985 * bit would be set the first time the vcpu is loaded.
1987 svm->avic_is_running = true;
1989 svm->nested.hsave = page_address(hsave_page);
1991 svm->msrpm = page_address(msrpm_pages);
1992 svm_vcpu_init_msrpm(svm->msrpm);
1994 svm->nested.msrpm = page_address(nested_msrpm_pages);
1995 svm_vcpu_init_msrpm(svm->nested.msrpm);
1997 svm->vmcb = page_address(page);
1998 clear_page(svm->vmcb);
1999 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2000 svm->asid_generation = 0;
2003 svm_init_osvw(&svm->vcpu);
2008 __free_page(hsave_page);
2010 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2012 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2016 kvm_vcpu_uninit(&svm->vcpu);
2018 kmem_cache_free(kvm_vcpu_cache, svm);
2020 return ERR_PTR(err);
2023 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2025 struct vcpu_svm *svm = to_svm(vcpu);
2027 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2028 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2029 __free_page(virt_to_page(svm->nested.hsave));
2030 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2031 kvm_vcpu_uninit(vcpu);
2032 kmem_cache_free(kvm_vcpu_cache, svm);
2034 * The vmcb page can be recycled, causing a false negative in
2035 * svm_vcpu_load(). So do a full IBPB now.
2037 indirect_branch_prediction_barrier();
2040 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2042 struct vcpu_svm *svm = to_svm(vcpu);
2043 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2046 if (unlikely(cpu != vcpu->cpu)) {
2047 svm->asid_generation = 0;
2048 mark_all_dirty(svm->vmcb);
2051 #ifdef CONFIG_X86_64
2052 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2054 savesegment(fs, svm->host.fs);
2055 savesegment(gs, svm->host.gs);
2056 svm->host.ldt = kvm_read_ldt();
2058 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2059 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2061 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2062 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2063 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2064 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2065 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2068 /* This assumes that the kernel never uses MSR_TSC_AUX */
2069 if (static_cpu_has(X86_FEATURE_RDTSCP))
2070 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2072 if (sd->current_vmcb != svm->vmcb) {
2073 sd->current_vmcb = svm->vmcb;
2074 indirect_branch_prediction_barrier();
2076 avic_vcpu_load(vcpu, cpu);
2079 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2081 struct vcpu_svm *svm = to_svm(vcpu);
2084 avic_vcpu_put(vcpu);
2086 ++vcpu->stat.host_state_reload;
2087 kvm_load_ldt(svm->host.ldt);
2088 #ifdef CONFIG_X86_64
2089 loadsegment(fs, svm->host.fs);
2090 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2091 load_gs_index(svm->host.gs);
2093 #ifdef CONFIG_X86_32_LAZY_GS
2094 loadsegment(gs, svm->host.gs);
2097 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2098 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2101 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2103 avic_set_running(vcpu, false);
2106 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2108 avic_set_running(vcpu, true);
2111 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2113 struct vcpu_svm *svm = to_svm(vcpu);
2114 unsigned long rflags = svm->vmcb->save.rflags;
2116 if (svm->nmi_singlestep) {
2117 /* Hide our flags if they were not set by the guest */
2118 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2119 rflags &= ~X86_EFLAGS_TF;
2120 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2121 rflags &= ~X86_EFLAGS_RF;
2126 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2128 if (to_svm(vcpu)->nmi_singlestep)
2129 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2132 * Any change of EFLAGS.VM is accompanied by a reload of SS
2133 * (caused by either a task switch or an inter-privilege IRET),
2134 * so we do not need to update the CPL here.
2136 to_svm(vcpu)->vmcb->save.rflags = rflags;
2139 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2142 case VCPU_EXREG_PDPTR:
2143 BUG_ON(!npt_enabled);
2144 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2151 static void svm_set_vintr(struct vcpu_svm *svm)
2153 set_intercept(svm, INTERCEPT_VINTR);
2156 static void svm_clear_vintr(struct vcpu_svm *svm)
2158 clr_intercept(svm, INTERCEPT_VINTR);
2161 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2163 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2166 case VCPU_SREG_CS: return &save->cs;
2167 case VCPU_SREG_DS: return &save->ds;
2168 case VCPU_SREG_ES: return &save->es;
2169 case VCPU_SREG_FS: return &save->fs;
2170 case VCPU_SREG_GS: return &save->gs;
2171 case VCPU_SREG_SS: return &save->ss;
2172 case VCPU_SREG_TR: return &save->tr;
2173 case VCPU_SREG_LDTR: return &save->ldtr;
2179 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2181 struct vmcb_seg *s = svm_seg(vcpu, seg);
2186 static void svm_get_segment(struct kvm_vcpu *vcpu,
2187 struct kvm_segment *var, int seg)
2189 struct vmcb_seg *s = svm_seg(vcpu, seg);
2191 var->base = s->base;
2192 var->limit = s->limit;
2193 var->selector = s->selector;
2194 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2195 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2196 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2197 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2198 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2199 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2200 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2203 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2204 * However, the SVM spec states that the G bit is not observed by the
2205 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2206 * So let's synthesize a legal G bit for all segments, this helps
2207 * running KVM nested. It also helps cross-vendor migration, because
2208 * Intel's vmentry has a check on the 'G' bit.
2210 var->g = s->limit > 0xfffff;
2213 * AMD's VMCB does not have an explicit unusable field, so emulate it
2214 * for cross vendor migration purposes by "not present"
2216 var->unusable = !var->present;
2221 * Work around a bug where the busy flag in the tr selector
2231 * The accessed bit must always be set in the segment
2232 * descriptor cache, although it can be cleared in the
2233 * descriptor, the cached bit always remains at 1. Since
2234 * Intel has a check on this, set it here to support
2235 * cross-vendor migration.
2242 * On AMD CPUs sometimes the DB bit in the segment
2243 * descriptor is left as 1, although the whole segment has
2244 * been made unusable. Clear it here to pass an Intel VMX
2245 * entry check when cross vendor migrating.
2249 /* This is symmetric with svm_set_segment() */
2250 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2255 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2257 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2262 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2264 struct vcpu_svm *svm = to_svm(vcpu);
2266 dt->size = svm->vmcb->save.idtr.limit;
2267 dt->address = svm->vmcb->save.idtr.base;
2270 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2272 struct vcpu_svm *svm = to_svm(vcpu);
2274 svm->vmcb->save.idtr.limit = dt->size;
2275 svm->vmcb->save.idtr.base = dt->address ;
2276 mark_dirty(svm->vmcb, VMCB_DT);
2279 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2281 struct vcpu_svm *svm = to_svm(vcpu);
2283 dt->size = svm->vmcb->save.gdtr.limit;
2284 dt->address = svm->vmcb->save.gdtr.base;
2287 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2289 struct vcpu_svm *svm = to_svm(vcpu);
2291 svm->vmcb->save.gdtr.limit = dt->size;
2292 svm->vmcb->save.gdtr.base = dt->address ;
2293 mark_dirty(svm->vmcb, VMCB_DT);
2296 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2300 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2304 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2308 static void update_cr0_intercept(struct vcpu_svm *svm)
2310 ulong gcr0 = svm->vcpu.arch.cr0;
2311 u64 *hcr0 = &svm->vmcb->save.cr0;
2313 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2314 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2316 mark_dirty(svm->vmcb, VMCB_CR);
2318 if (gcr0 == *hcr0) {
2319 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2320 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2322 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2323 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2327 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2329 struct vcpu_svm *svm = to_svm(vcpu);
2331 #ifdef CONFIG_X86_64
2332 if (vcpu->arch.efer & EFER_LME) {
2333 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2334 vcpu->arch.efer |= EFER_LMA;
2335 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2338 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2339 vcpu->arch.efer &= ~EFER_LMA;
2340 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2344 vcpu->arch.cr0 = cr0;
2347 cr0 |= X86_CR0_PG | X86_CR0_WP;
2350 * re-enable caching here because the QEMU bios
2351 * does not do it - this results in some delay at
2354 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2355 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2356 svm->vmcb->save.cr0 = cr0;
2357 mark_dirty(svm->vmcb, VMCB_CR);
2358 update_cr0_intercept(svm);
2361 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2363 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2364 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2366 if (cr4 & X86_CR4_VMXE)
2369 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2370 svm_flush_tlb(vcpu, true);
2372 vcpu->arch.cr4 = cr4;
2375 cr4 |= host_cr4_mce;
2376 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2377 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2381 static void svm_set_segment(struct kvm_vcpu *vcpu,
2382 struct kvm_segment *var, int seg)
2384 struct vcpu_svm *svm = to_svm(vcpu);
2385 struct vmcb_seg *s = svm_seg(vcpu, seg);
2387 s->base = var->base;
2388 s->limit = var->limit;
2389 s->selector = var->selector;
2390 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2391 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2392 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2393 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2394 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2395 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2396 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2397 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2400 * This is always accurate, except if SYSRET returned to a segment
2401 * with SS.DPL != 3. Intel does not have this quirk, and always
2402 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2403 * would entail passing the CPL to userspace and back.
2405 if (seg == VCPU_SREG_SS)
2406 /* This is symmetric with svm_get_segment() */
2407 svm->vmcb->save.cpl = (var->dpl & 3);
2409 mark_dirty(svm->vmcb, VMCB_SEG);
2412 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2414 struct vcpu_svm *svm = to_svm(vcpu);
2416 clr_exception_intercept(svm, BP_VECTOR);
2418 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2419 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2420 set_exception_intercept(svm, BP_VECTOR);
2422 vcpu->guest_debug = 0;
2425 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2427 if (sd->next_asid > sd->max_asid) {
2428 ++sd->asid_generation;
2429 sd->next_asid = sd->min_asid;
2430 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2433 svm->asid_generation = sd->asid_generation;
2434 svm->vmcb->control.asid = sd->next_asid++;
2436 mark_dirty(svm->vmcb, VMCB_ASID);
2439 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2441 return to_svm(vcpu)->vmcb->save.dr6;
2444 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2446 struct vcpu_svm *svm = to_svm(vcpu);
2448 svm->vmcb->save.dr6 = value;
2449 mark_dirty(svm->vmcb, VMCB_DR);
2452 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2454 struct vcpu_svm *svm = to_svm(vcpu);
2456 get_debugreg(vcpu->arch.db[0], 0);
2457 get_debugreg(vcpu->arch.db[1], 1);
2458 get_debugreg(vcpu->arch.db[2], 2);
2459 get_debugreg(vcpu->arch.db[3], 3);
2460 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2461 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2463 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2464 set_dr_intercepts(svm);
2467 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2469 struct vcpu_svm *svm = to_svm(vcpu);
2471 svm->vmcb->save.dr7 = value;
2472 mark_dirty(svm->vmcb, VMCB_DR);
2475 static int pf_interception(struct vcpu_svm *svm)
2477 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2478 u64 error_code = svm->vmcb->control.exit_info_1;
2480 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2481 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2482 svm->vmcb->control.insn_bytes : NULL,
2483 svm->vmcb->control.insn_len);
2486 static int npf_interception(struct vcpu_svm *svm)
2488 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2489 u64 error_code = svm->vmcb->control.exit_info_1;
2491 trace_kvm_page_fault(fault_address, error_code);
2492 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2493 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2494 svm->vmcb->control.insn_bytes : NULL,
2495 svm->vmcb->control.insn_len);
2498 static int db_interception(struct vcpu_svm *svm)
2500 struct kvm_run *kvm_run = svm->vcpu.run;
2502 if (!(svm->vcpu.guest_debug &
2503 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2504 !svm->nmi_singlestep) {
2505 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2509 if (svm->nmi_singlestep) {
2510 disable_nmi_singlestep(svm);
2513 if (svm->vcpu.guest_debug &
2514 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2515 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2516 kvm_run->debug.arch.pc =
2517 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2518 kvm_run->debug.arch.exception = DB_VECTOR;
2525 static int bp_interception(struct vcpu_svm *svm)
2527 struct kvm_run *kvm_run = svm->vcpu.run;
2529 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2530 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2531 kvm_run->debug.arch.exception = BP_VECTOR;
2535 static int ud_interception(struct vcpu_svm *svm)
2539 er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
2540 if (er == EMULATE_USER_EXIT)
2542 if (er != EMULATE_DONE)
2543 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2547 static int ac_interception(struct vcpu_svm *svm)
2549 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2553 static bool is_erratum_383(void)
2558 if (!erratum_383_found)
2561 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2565 /* Bit 62 may or may not be set for this mce */
2566 value &= ~(1ULL << 62);
2568 if (value != 0xb600000000010015ULL)
2571 /* Clear MCi_STATUS registers */
2572 for (i = 0; i < 6; ++i)
2573 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2575 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2579 value &= ~(1ULL << 2);
2580 low = lower_32_bits(value);
2581 high = upper_32_bits(value);
2583 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2586 /* Flush tlb to evict multi-match entries */
2592 static void svm_handle_mce(struct vcpu_svm *svm)
2594 if (is_erratum_383()) {
2596 * Erratum 383 triggered. Guest state is corrupt so kill the
2599 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2601 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2607 * On an #MC intercept the MCE handler is not called automatically in
2608 * the host. So do it by hand here.
2612 /* not sure if we ever come back to this point */
2617 static int mc_interception(struct vcpu_svm *svm)
2622 static int shutdown_interception(struct vcpu_svm *svm)
2624 struct kvm_run *kvm_run = svm->vcpu.run;
2627 * VMCB is undefined after a SHUTDOWN intercept
2628 * so reinitialize it.
2630 clear_page(svm->vmcb);
2633 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2637 static int io_interception(struct vcpu_svm *svm)
2639 struct kvm_vcpu *vcpu = &svm->vcpu;
2640 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2641 int size, in, string, ret;
2644 ++svm->vcpu.stat.io_exits;
2645 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2646 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2648 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2650 port = io_info >> 16;
2651 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2652 svm->next_rip = svm->vmcb->control.exit_info_2;
2653 ret = kvm_skip_emulated_instruction(&svm->vcpu);
2656 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
2657 * KVM_EXIT_DEBUG here.
2660 return kvm_fast_pio_in(vcpu, size, port) && ret;
2662 return kvm_fast_pio_out(vcpu, size, port) && ret;
2665 static int nmi_interception(struct vcpu_svm *svm)
2670 static int intr_interception(struct vcpu_svm *svm)
2672 ++svm->vcpu.stat.irq_exits;
2676 static int nop_on_interception(struct vcpu_svm *svm)
2681 static int halt_interception(struct vcpu_svm *svm)
2683 svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2684 return kvm_emulate_halt(&svm->vcpu);
2687 static int vmmcall_interception(struct vcpu_svm *svm)
2689 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2690 return kvm_emulate_hypercall(&svm->vcpu);
2693 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2695 struct vcpu_svm *svm = to_svm(vcpu);
2697 return svm->nested.nested_cr3;
2700 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2702 struct vcpu_svm *svm = to_svm(vcpu);
2703 u64 cr3 = svm->nested.nested_cr3;
2707 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2708 offset_in_page(cr3) + index * 8, 8);
2714 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2717 struct vcpu_svm *svm = to_svm(vcpu);
2719 svm->vmcb->control.nested_cr3 = __sme_set(root);
2720 mark_dirty(svm->vmcb, VMCB_NPT);
2721 svm_flush_tlb(vcpu, true);
2724 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2725 struct x86_exception *fault)
2727 struct vcpu_svm *svm = to_svm(vcpu);
2729 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2731 * TODO: track the cause of the nested page fault, and
2732 * correctly fill in the high bits of exit_info_1.
2734 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2735 svm->vmcb->control.exit_code_hi = 0;
2736 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2737 svm->vmcb->control.exit_info_2 = fault->address;
2740 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2741 svm->vmcb->control.exit_info_1 |= fault->error_code;
2744 * The present bit is always zero for page structure faults on real
2747 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2748 svm->vmcb->control.exit_info_1 &= ~1;
2750 nested_svm_vmexit(svm);
2753 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2755 WARN_ON(mmu_is_nested(vcpu));
2756 kvm_init_shadow_mmu(vcpu);
2757 vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
2758 vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
2759 vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr;
2760 vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2761 vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2762 reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2763 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2766 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2768 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2771 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2773 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2774 !is_paging(&svm->vcpu)) {
2775 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2779 if (svm->vmcb->save.cpl) {
2780 kvm_inject_gp(&svm->vcpu, 0);
2787 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2788 bool has_error_code, u32 error_code)
2792 if (!is_guest_mode(&svm->vcpu))
2795 vmexit = nested_svm_intercept(svm);
2796 if (vmexit != NESTED_EXIT_DONE)
2799 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2800 svm->vmcb->control.exit_code_hi = 0;
2801 svm->vmcb->control.exit_info_1 = error_code;
2804 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2805 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2806 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2807 * written only when inject_pending_event runs (DR6 would written here
2808 * too). This should be conditional on a new capability---if the
2809 * capability is disabled, kvm_multiple_exception would write the
2810 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2812 if (svm->vcpu.arch.exception.nested_apf)
2813 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2815 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2817 svm->nested.exit_required = true;
2821 /* This function returns true if it is save to enable the irq window */
2822 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2824 if (!is_guest_mode(&svm->vcpu))
2827 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2830 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2834 * if vmexit was already requested (by intercepted exception
2835 * for instance) do not overwrite it with "external interrupt"
2838 if (svm->nested.exit_required)
2841 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
2842 svm->vmcb->control.exit_info_1 = 0;
2843 svm->vmcb->control.exit_info_2 = 0;
2845 if (svm->nested.intercept & 1ULL) {
2847 * The #vmexit can't be emulated here directly because this
2848 * code path runs with irqs and preemption disabled. A
2849 * #vmexit emulation might sleep. Only signal request for
2852 svm->nested.exit_required = true;
2853 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2860 /* This function returns true if it is save to enable the nmi window */
2861 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2863 if (!is_guest_mode(&svm->vcpu))
2866 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2869 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2870 svm->nested.exit_required = true;
2875 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2881 page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2882 if (is_error_page(page))
2890 kvm_inject_gp(&svm->vcpu, 0);
2895 static void nested_svm_unmap(struct page *page)
2898 kvm_release_page_dirty(page);
2901 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2903 unsigned port, size, iopm_len;
2908 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2909 return NESTED_EXIT_HOST;
2911 port = svm->vmcb->control.exit_info_1 >> 16;
2912 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2913 SVM_IOIO_SIZE_SHIFT;
2914 gpa = svm->nested.vmcb_iopm + (port / 8);
2915 start_bit = port % 8;
2916 iopm_len = (start_bit + size > 8) ? 2 : 1;
2917 mask = (0xf >> (4 - size)) << start_bit;
2920 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2921 return NESTED_EXIT_DONE;
2923 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2926 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2928 u32 offset, msr, value;
2931 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2932 return NESTED_EXIT_HOST;
2934 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2935 offset = svm_msrpm_offset(msr);
2936 write = svm->vmcb->control.exit_info_1 & 1;
2937 mask = 1 << ((2 * (msr & 0xf)) + write);
2939 if (offset == MSR_INVALID)
2940 return NESTED_EXIT_DONE;
2942 /* Offset is in 32 bit units but need in 8 bit units */
2945 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
2946 return NESTED_EXIT_DONE;
2948 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2951 /* DB exceptions for our internal use must not cause vmexit */
2952 static int nested_svm_intercept_db(struct vcpu_svm *svm)
2956 /* if we're not singlestepping, it's not ours */
2957 if (!svm->nmi_singlestep)
2958 return NESTED_EXIT_DONE;
2960 /* if it's not a singlestep exception, it's not ours */
2961 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
2962 return NESTED_EXIT_DONE;
2963 if (!(dr6 & DR6_BS))
2964 return NESTED_EXIT_DONE;
2966 /* if the guest is singlestepping, it should get the vmexit */
2967 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
2968 disable_nmi_singlestep(svm);
2969 return NESTED_EXIT_DONE;
2972 /* it's ours, the nested hypervisor must not see this one */
2973 return NESTED_EXIT_HOST;
2976 static int nested_svm_exit_special(struct vcpu_svm *svm)
2978 u32 exit_code = svm->vmcb->control.exit_code;
2980 switch (exit_code) {
2983 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
2984 return NESTED_EXIT_HOST;
2986 /* For now we are always handling NPFs when using them */
2988 return NESTED_EXIT_HOST;
2990 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
2991 /* When we're shadowing, trap PFs, but not async PF */
2992 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
2993 return NESTED_EXIT_HOST;
2999 return NESTED_EXIT_CONTINUE;
3003 * If this function returns true, this #vmexit was already handled
3005 static int nested_svm_intercept(struct vcpu_svm *svm)
3007 u32 exit_code = svm->vmcb->control.exit_code;
3008 int vmexit = NESTED_EXIT_HOST;
3010 switch (exit_code) {
3012 vmexit = nested_svm_exit_handled_msr(svm);
3015 vmexit = nested_svm_intercept_ioio(svm);
3017 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3018 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3019 if (svm->nested.intercept_cr & bit)
3020 vmexit = NESTED_EXIT_DONE;
3023 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3024 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3025 if (svm->nested.intercept_dr & bit)
3026 vmexit = NESTED_EXIT_DONE;
3029 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3030 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3031 if (svm->nested.intercept_exceptions & excp_bits) {
3032 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3033 vmexit = nested_svm_intercept_db(svm);
3035 vmexit = NESTED_EXIT_DONE;
3037 /* async page fault always cause vmexit */
3038 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3039 svm->vcpu.arch.exception.nested_apf != 0)
3040 vmexit = NESTED_EXIT_DONE;
3043 case SVM_EXIT_ERR: {
3044 vmexit = NESTED_EXIT_DONE;
3048 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3049 if (svm->nested.intercept & exit_bits)
3050 vmexit = NESTED_EXIT_DONE;
3057 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3061 vmexit = nested_svm_intercept(svm);
3063 if (vmexit == NESTED_EXIT_DONE)
3064 nested_svm_vmexit(svm);
3069 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3071 struct vmcb_control_area *dst = &dst_vmcb->control;
3072 struct vmcb_control_area *from = &from_vmcb->control;
3074 dst->intercept_cr = from->intercept_cr;
3075 dst->intercept_dr = from->intercept_dr;
3076 dst->intercept_exceptions = from->intercept_exceptions;
3077 dst->intercept = from->intercept;
3078 dst->iopm_base_pa = from->iopm_base_pa;
3079 dst->msrpm_base_pa = from->msrpm_base_pa;
3080 dst->tsc_offset = from->tsc_offset;
3081 dst->asid = from->asid;
3082 dst->tlb_ctl = from->tlb_ctl;
3083 dst->int_ctl = from->int_ctl;
3084 dst->int_vector = from->int_vector;
3085 dst->int_state = from->int_state;
3086 dst->exit_code = from->exit_code;
3087 dst->exit_code_hi = from->exit_code_hi;
3088 dst->exit_info_1 = from->exit_info_1;
3089 dst->exit_info_2 = from->exit_info_2;
3090 dst->exit_int_info = from->exit_int_info;
3091 dst->exit_int_info_err = from->exit_int_info_err;
3092 dst->nested_ctl = from->nested_ctl;
3093 dst->event_inj = from->event_inj;
3094 dst->event_inj_err = from->event_inj_err;
3095 dst->nested_cr3 = from->nested_cr3;
3096 dst->virt_ext = from->virt_ext;
3099 static int nested_svm_vmexit(struct vcpu_svm *svm)
3101 struct vmcb *nested_vmcb;
3102 struct vmcb *hsave = svm->nested.hsave;
3103 struct vmcb *vmcb = svm->vmcb;
3106 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3107 vmcb->control.exit_info_1,
3108 vmcb->control.exit_info_2,
3109 vmcb->control.exit_int_info,
3110 vmcb->control.exit_int_info_err,
3113 nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3117 /* Exit Guest-Mode */
3118 leave_guest_mode(&svm->vcpu);
3119 svm->nested.vmcb = 0;
3121 /* Give the current vmcb to the guest */
3124 nested_vmcb->save.es = vmcb->save.es;
3125 nested_vmcb->save.cs = vmcb->save.cs;
3126 nested_vmcb->save.ss = vmcb->save.ss;
3127 nested_vmcb->save.ds = vmcb->save.ds;
3128 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3129 nested_vmcb->save.idtr = vmcb->save.idtr;
3130 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3131 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3132 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3133 nested_vmcb->save.cr2 = vmcb->save.cr2;
3134 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3135 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3136 nested_vmcb->save.rip = vmcb->save.rip;
3137 nested_vmcb->save.rsp = vmcb->save.rsp;
3138 nested_vmcb->save.rax = vmcb->save.rax;
3139 nested_vmcb->save.dr7 = vmcb->save.dr7;
3140 nested_vmcb->save.dr6 = vmcb->save.dr6;
3141 nested_vmcb->save.cpl = vmcb->save.cpl;
3143 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3144 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3145 nested_vmcb->control.int_state = vmcb->control.int_state;
3146 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3147 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3148 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3149 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3150 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3151 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3153 if (svm->nrips_enabled)
3154 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3157 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3158 * to make sure that we do not lose injected events. So check event_inj
3159 * here and copy it to exit_int_info if it is valid.
3160 * Exit_int_info and event_inj can't be both valid because the case
3161 * below only happens on a VMRUN instruction intercept which has
3162 * no valid exit_int_info set.
3164 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3165 struct vmcb_control_area *nc = &nested_vmcb->control;
3167 nc->exit_int_info = vmcb->control.event_inj;
3168 nc->exit_int_info_err = vmcb->control.event_inj_err;
3171 nested_vmcb->control.tlb_ctl = 0;
3172 nested_vmcb->control.event_inj = 0;
3173 nested_vmcb->control.event_inj_err = 0;
3175 /* We always set V_INTR_MASKING and remember the old value in hflags */
3176 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3177 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3179 /* Restore the original control entries */
3180 copy_vmcb_control_area(vmcb, hsave);
3182 kvm_clear_exception_queue(&svm->vcpu);
3183 kvm_clear_interrupt_queue(&svm->vcpu);
3185 svm->nested.nested_cr3 = 0;
3187 /* Restore selected save entries */
3188 svm->vmcb->save.es = hsave->save.es;
3189 svm->vmcb->save.cs = hsave->save.cs;
3190 svm->vmcb->save.ss = hsave->save.ss;
3191 svm->vmcb->save.ds = hsave->save.ds;
3192 svm->vmcb->save.gdtr = hsave->save.gdtr;
3193 svm->vmcb->save.idtr = hsave->save.idtr;
3194 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3195 svm_set_efer(&svm->vcpu, hsave->save.efer);
3196 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3197 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3199 svm->vmcb->save.cr3 = hsave->save.cr3;
3200 svm->vcpu.arch.cr3 = hsave->save.cr3;
3202 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3204 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3205 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3206 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3207 svm->vmcb->save.dr7 = 0;
3208 svm->vmcb->save.cpl = 0;
3209 svm->vmcb->control.exit_int_info = 0;
3211 mark_all_dirty(svm->vmcb);
3213 nested_svm_unmap(page);
3215 nested_svm_uninit_mmu_context(&svm->vcpu);
3216 kvm_mmu_reset_context(&svm->vcpu);
3217 kvm_mmu_load(&svm->vcpu);
3222 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3225 * This function merges the msr permission bitmaps of kvm and the
3226 * nested vmcb. It is optimized in that it only merges the parts where
3227 * the kvm msr permission bitmap may contain zero bits
3231 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3234 for (i = 0; i < MSRPM_OFFSETS; i++) {
3238 if (msrpm_offsets[i] == 0xffffffff)
3241 p = msrpm_offsets[i];
3242 offset = svm->nested.vmcb_msrpm + (p * 4);
3244 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3247 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3250 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3255 static bool nested_vmcb_checks(struct vmcb *vmcb)
3257 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3260 if (vmcb->control.asid == 0)
3263 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3270 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3271 struct vmcb *nested_vmcb, struct page *page)
3273 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3274 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3276 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3278 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3279 kvm_mmu_unload(&svm->vcpu);
3280 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3281 nested_svm_init_mmu_context(&svm->vcpu);
3284 /* Load the nested guest state */
3285 svm->vmcb->save.es = nested_vmcb->save.es;
3286 svm->vmcb->save.cs = nested_vmcb->save.cs;
3287 svm->vmcb->save.ss = nested_vmcb->save.ss;
3288 svm->vmcb->save.ds = nested_vmcb->save.ds;
3289 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3290 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3291 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3292 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3293 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3294 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3296 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3297 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3299 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3301 /* Guest paging mode is active - reset mmu */
3302 kvm_mmu_reset_context(&svm->vcpu);
3304 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3305 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3306 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3307 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3309 /* In case we don't even reach vcpu_run, the fields are not updated */
3310 svm->vmcb->save.rax = nested_vmcb->save.rax;
3311 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3312 svm->vmcb->save.rip = nested_vmcb->save.rip;
3313 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3314 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3315 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3317 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3318 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3320 /* cache intercepts */
3321 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3322 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3323 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3324 svm->nested.intercept = nested_vmcb->control.intercept;
3326 svm_flush_tlb(&svm->vcpu, true);
3327 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3328 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3329 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3331 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3333 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3334 /* We only want the cr8 intercept bits of the guest */
3335 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3336 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3339 /* We don't want to see VMMCALLs from a nested guest */
3340 clr_intercept(svm, INTERCEPT_VMMCALL);
3342 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3343 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3344 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3345 svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
3346 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3347 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3349 nested_svm_unmap(page);
3351 /* Enter Guest-Mode */
3352 enter_guest_mode(&svm->vcpu);
3355 * Merge guest and host intercepts - must be called with vcpu in
3356 * guest-mode to take affect here
3358 recalc_intercepts(svm);
3360 svm->nested.vmcb = vmcb_gpa;
3364 mark_all_dirty(svm->vmcb);
3367 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3369 struct vmcb *nested_vmcb;
3370 struct vmcb *hsave = svm->nested.hsave;
3371 struct vmcb *vmcb = svm->vmcb;
3375 vmcb_gpa = svm->vmcb->save.rax;
3377 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3381 if (!nested_vmcb_checks(nested_vmcb)) {
3382 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3383 nested_vmcb->control.exit_code_hi = 0;
3384 nested_vmcb->control.exit_info_1 = 0;
3385 nested_vmcb->control.exit_info_2 = 0;
3387 nested_svm_unmap(page);
3392 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3393 nested_vmcb->save.rip,
3394 nested_vmcb->control.int_ctl,
3395 nested_vmcb->control.event_inj,
3396 nested_vmcb->control.nested_ctl);
3398 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3399 nested_vmcb->control.intercept_cr >> 16,
3400 nested_vmcb->control.intercept_exceptions,
3401 nested_vmcb->control.intercept);
3403 /* Clear internal status */
3404 kvm_clear_exception_queue(&svm->vcpu);
3405 kvm_clear_interrupt_queue(&svm->vcpu);
3408 * Save the old vmcb, so we don't need to pick what we save, but can
3409 * restore everything when a VMEXIT occurs
3411 hsave->save.es = vmcb->save.es;
3412 hsave->save.cs = vmcb->save.cs;
3413 hsave->save.ss = vmcb->save.ss;
3414 hsave->save.ds = vmcb->save.ds;
3415 hsave->save.gdtr = vmcb->save.gdtr;
3416 hsave->save.idtr = vmcb->save.idtr;
3417 hsave->save.efer = svm->vcpu.arch.efer;
3418 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3419 hsave->save.cr4 = svm->vcpu.arch.cr4;
3420 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3421 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3422 hsave->save.rsp = vmcb->save.rsp;
3423 hsave->save.rax = vmcb->save.rax;
3425 hsave->save.cr3 = vmcb->save.cr3;
3427 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3429 copy_vmcb_control_area(hsave, vmcb);
3431 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3436 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3438 to_vmcb->save.fs = from_vmcb->save.fs;
3439 to_vmcb->save.gs = from_vmcb->save.gs;
3440 to_vmcb->save.tr = from_vmcb->save.tr;
3441 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3442 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3443 to_vmcb->save.star = from_vmcb->save.star;
3444 to_vmcb->save.lstar = from_vmcb->save.lstar;
3445 to_vmcb->save.cstar = from_vmcb->save.cstar;
3446 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3447 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3448 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3449 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3452 static int vmload_interception(struct vcpu_svm *svm)
3454 struct vmcb *nested_vmcb;
3458 if (nested_svm_check_permissions(svm))
3461 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3465 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3466 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3468 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3469 nested_svm_unmap(page);
3474 static int vmsave_interception(struct vcpu_svm *svm)
3476 struct vmcb *nested_vmcb;
3480 if (nested_svm_check_permissions(svm))
3483 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3487 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3488 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3490 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3491 nested_svm_unmap(page);
3496 static int vmrun_interception(struct vcpu_svm *svm)
3498 if (nested_svm_check_permissions(svm))
3501 /* Save rip after vmrun instruction */
3502 kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3504 if (!nested_svm_vmrun(svm))
3507 if (!nested_svm_vmrun_msrpm(svm))
3514 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3515 svm->vmcb->control.exit_code_hi = 0;
3516 svm->vmcb->control.exit_info_1 = 0;
3517 svm->vmcb->control.exit_info_2 = 0;
3519 nested_svm_vmexit(svm);
3524 static int stgi_interception(struct vcpu_svm *svm)
3528 if (nested_svm_check_permissions(svm))
3532 * If VGIF is enabled, the STGI intercept is only added to
3533 * detect the opening of the SMI/NMI window; remove it now.
3535 if (vgif_enabled(svm))
3536 clr_intercept(svm, INTERCEPT_STGI);
3538 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3539 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3540 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3547 static int clgi_interception(struct vcpu_svm *svm)
3551 if (nested_svm_check_permissions(svm))
3554 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3555 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3559 /* After a CLGI no interrupts should come */
3560 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3561 svm_clear_vintr(svm);
3562 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3563 mark_dirty(svm->vmcb, VMCB_INTR);
3569 static int invlpga_interception(struct vcpu_svm *svm)
3571 struct kvm_vcpu *vcpu = &svm->vcpu;
3573 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3574 kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3576 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3577 kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3579 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3580 return kvm_skip_emulated_instruction(&svm->vcpu);
3583 static int skinit_interception(struct vcpu_svm *svm)
3585 trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3587 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3591 static int wbinvd_interception(struct vcpu_svm *svm)
3593 return kvm_emulate_wbinvd(&svm->vcpu);
3596 static int xsetbv_interception(struct vcpu_svm *svm)
3598 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3599 u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3601 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3602 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3603 return kvm_skip_emulated_instruction(&svm->vcpu);
3609 static int task_switch_interception(struct vcpu_svm *svm)
3613 int int_type = svm->vmcb->control.exit_int_info &
3614 SVM_EXITINTINFO_TYPE_MASK;
3615 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3617 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3619 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3620 bool has_error_code = false;
3623 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3625 if (svm->vmcb->control.exit_info_2 &
3626 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3627 reason = TASK_SWITCH_IRET;
3628 else if (svm->vmcb->control.exit_info_2 &
3629 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3630 reason = TASK_SWITCH_JMP;
3632 reason = TASK_SWITCH_GATE;
3634 reason = TASK_SWITCH_CALL;
3636 if (reason == TASK_SWITCH_GATE) {
3638 case SVM_EXITINTINFO_TYPE_NMI:
3639 svm->vcpu.arch.nmi_injected = false;
3641 case SVM_EXITINTINFO_TYPE_EXEPT:
3642 if (svm->vmcb->control.exit_info_2 &
3643 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3644 has_error_code = true;
3646 (u32)svm->vmcb->control.exit_info_2;
3648 kvm_clear_exception_queue(&svm->vcpu);
3650 case SVM_EXITINTINFO_TYPE_INTR:
3651 kvm_clear_interrupt_queue(&svm->vcpu);
3658 if (reason != TASK_SWITCH_GATE ||
3659 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3660 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3661 (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3662 skip_emulated_instruction(&svm->vcpu);
3664 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3667 if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3668 has_error_code, error_code) == EMULATE_FAIL) {
3669 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3670 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3671 svm->vcpu.run->internal.ndata = 0;
3677 static int cpuid_interception(struct vcpu_svm *svm)
3679 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3680 return kvm_emulate_cpuid(&svm->vcpu);
3683 static int iret_interception(struct vcpu_svm *svm)
3685 ++svm->vcpu.stat.nmi_window_exits;
3686 clr_intercept(svm, INTERCEPT_IRET);
3687 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3688 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3689 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3693 static int invlpg_interception(struct vcpu_svm *svm)
3695 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3696 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3698 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3699 return kvm_skip_emulated_instruction(&svm->vcpu);
3702 static int emulate_on_interception(struct vcpu_svm *svm)
3704 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3707 static int rsm_interception(struct vcpu_svm *svm)
3709 return x86_emulate_instruction(&svm->vcpu, 0, 0,
3710 rsm_ins_bytes, 2) == EMULATE_DONE;
3713 static int rdpmc_interception(struct vcpu_svm *svm)
3717 if (!static_cpu_has(X86_FEATURE_NRIPS))
3718 return emulate_on_interception(svm);
3720 err = kvm_rdpmc(&svm->vcpu);
3721 return kvm_complete_insn_gp(&svm->vcpu, err);
3724 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3727 unsigned long cr0 = svm->vcpu.arch.cr0;
3731 intercept = svm->nested.intercept;
3733 if (!is_guest_mode(&svm->vcpu) ||
3734 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3737 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3738 val &= ~SVM_CR0_SELECTIVE_MASK;
3741 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3742 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3748 #define CR_VALID (1ULL << 63)
3750 static int cr_interception(struct vcpu_svm *svm)
3756 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3757 return emulate_on_interception(svm);
3759 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3760 return emulate_on_interception(svm);
3762 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3763 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3764 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3766 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3769 if (cr >= 16) { /* mov to cr */
3771 val = kvm_register_read(&svm->vcpu, reg);
3774 if (!check_selective_cr0_intercepted(svm, val))
3775 err = kvm_set_cr0(&svm->vcpu, val);
3781 err = kvm_set_cr3(&svm->vcpu, val);
3784 err = kvm_set_cr4(&svm->vcpu, val);
3787 err = kvm_set_cr8(&svm->vcpu, val);
3790 WARN(1, "unhandled write to CR%d", cr);
3791 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3794 } else { /* mov from cr */
3797 val = kvm_read_cr0(&svm->vcpu);
3800 val = svm->vcpu.arch.cr2;
3803 val = kvm_read_cr3(&svm->vcpu);
3806 val = kvm_read_cr4(&svm->vcpu);
3809 val = kvm_get_cr8(&svm->vcpu);
3812 WARN(1, "unhandled read from CR%d", cr);
3813 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3816 kvm_register_write(&svm->vcpu, reg, val);
3818 return kvm_complete_insn_gp(&svm->vcpu, err);
3821 static int dr_interception(struct vcpu_svm *svm)
3826 if (svm->vcpu.guest_debug == 0) {
3828 * No more DR vmexits; force a reload of the debug registers
3829 * and reenter on this instruction. The next vmexit will
3830 * retrieve the full state of the debug registers.
3832 clr_dr_intercepts(svm);
3833 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
3837 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
3838 return emulate_on_interception(svm);
3840 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3841 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3843 if (dr >= 16) { /* mov to DRn */
3844 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3846 val = kvm_register_read(&svm->vcpu, reg);
3847 kvm_set_dr(&svm->vcpu, dr - 16, val);
3849 if (!kvm_require_dr(&svm->vcpu, dr))
3851 kvm_get_dr(&svm->vcpu, dr, &val);
3852 kvm_register_write(&svm->vcpu, reg, val);
3855 return kvm_skip_emulated_instruction(&svm->vcpu);
3858 static int cr8_write_interception(struct vcpu_svm *svm)
3860 struct kvm_run *kvm_run = svm->vcpu.run;
3863 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3864 /* instruction emulation calls kvm_set_cr8() */
3865 r = cr_interception(svm);
3866 if (lapic_in_kernel(&svm->vcpu))
3868 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3870 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3874 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
3878 switch (msr->index) {
3879 case MSR_F10H_DECFG:
3880 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
3881 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
3890 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3892 struct vcpu_svm *svm = to_svm(vcpu);
3894 switch (msr_info->index) {
3895 case MSR_IA32_TSC: {
3896 msr_info->data = svm->vmcb->control.tsc_offset +
3897 kvm_scale_tsc(vcpu, rdtsc());
3902 msr_info->data = svm->vmcb->save.star;
3904 #ifdef CONFIG_X86_64
3906 msr_info->data = svm->vmcb->save.lstar;
3909 msr_info->data = svm->vmcb->save.cstar;
3911 case MSR_KERNEL_GS_BASE:
3912 msr_info->data = svm->vmcb->save.kernel_gs_base;
3914 case MSR_SYSCALL_MASK:
3915 msr_info->data = svm->vmcb->save.sfmask;
3918 case MSR_IA32_SYSENTER_CS:
3919 msr_info->data = svm->vmcb->save.sysenter_cs;
3921 case MSR_IA32_SYSENTER_EIP:
3922 msr_info->data = svm->sysenter_eip;
3924 case MSR_IA32_SYSENTER_ESP:
3925 msr_info->data = svm->sysenter_esp;
3928 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3930 msr_info->data = svm->tsc_aux;
3933 * Nobody will change the following 5 values in the VMCB so we can
3934 * safely return them on rdmsr. They will always be 0 until LBRV is
3937 case MSR_IA32_DEBUGCTLMSR:
3938 msr_info->data = svm->vmcb->save.dbgctl;
3940 case MSR_IA32_LASTBRANCHFROMIP:
3941 msr_info->data = svm->vmcb->save.br_from;
3943 case MSR_IA32_LASTBRANCHTOIP:
3944 msr_info->data = svm->vmcb->save.br_to;
3946 case MSR_IA32_LASTINTFROMIP:
3947 msr_info->data = svm->vmcb->save.last_excp_from;
3949 case MSR_IA32_LASTINTTOIP:
3950 msr_info->data = svm->vmcb->save.last_excp_to;
3952 case MSR_VM_HSAVE_PA:
3953 msr_info->data = svm->nested.hsave_msr;
3956 msr_info->data = svm->nested.vm_cr_msr;
3958 case MSR_IA32_SPEC_CTRL:
3959 if (!msr_info->host_initiated &&
3960 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
3963 msr_info->data = svm->spec_ctrl;
3965 case MSR_IA32_UCODE_REV:
3966 msr_info->data = 0x01000065;
3968 case MSR_F15H_IC_CFG: {
3972 family = guest_cpuid_family(vcpu);
3973 model = guest_cpuid_model(vcpu);
3975 if (family < 0 || model < 0)
3976 return kvm_get_msr_common(vcpu, msr_info);
3980 if (family == 0x15 &&
3981 (model >= 0x2 && model < 0x20))
3982 msr_info->data = 0x1E;
3985 case MSR_F10H_DECFG:
3986 msr_info->data = svm->msr_decfg;
3989 return kvm_get_msr_common(vcpu, msr_info);
3994 static int rdmsr_interception(struct vcpu_svm *svm)
3996 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3997 struct msr_data msr_info;
3999 msr_info.index = ecx;
4000 msr_info.host_initiated = false;
4001 if (svm_get_msr(&svm->vcpu, &msr_info)) {
4002 trace_kvm_msr_read_ex(ecx);
4003 kvm_inject_gp(&svm->vcpu, 0);
4006 trace_kvm_msr_read(ecx, msr_info.data);
4008 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
4009 msr_info.data & 0xffffffff);
4010 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
4011 msr_info.data >> 32);
4012 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4013 return kvm_skip_emulated_instruction(&svm->vcpu);
4017 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4019 struct vcpu_svm *svm = to_svm(vcpu);
4020 int svm_dis, chg_mask;
4022 if (data & ~SVM_VM_CR_VALID_MASK)
4025 chg_mask = SVM_VM_CR_VALID_MASK;
4027 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4028 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4030 svm->nested.vm_cr_msr &= ~chg_mask;
4031 svm->nested.vm_cr_msr |= (data & chg_mask);
4033 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4035 /* check for svm_disable while efer.svme is set */
4036 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4042 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4044 struct vcpu_svm *svm = to_svm(vcpu);
4046 u32 ecx = msr->index;
4047 u64 data = msr->data;
4049 case MSR_IA32_CR_PAT:
4050 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4052 vcpu->arch.pat = data;
4053 svm->vmcb->save.g_pat = data;
4054 mark_dirty(svm->vmcb, VMCB_NPT);
4057 kvm_write_tsc(vcpu, msr);
4059 case MSR_IA32_SPEC_CTRL:
4060 if (!msr->host_initiated &&
4061 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
4064 /* The STIBP bit doesn't fault even if it's not advertised */
4065 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
4068 svm->spec_ctrl = data;
4075 * When it's written (to non-zero) for the first time, pass
4079 * The handling of the MSR bitmap for L2 guests is done in
4080 * nested_svm_vmrun_msrpm.
4081 * We update the L1 MSR bit as well since it will end up
4082 * touching the MSR anyway now.
4084 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4086 case MSR_IA32_PRED_CMD:
4087 if (!msr->host_initiated &&
4088 !guest_cpuid_has(vcpu, X86_FEATURE_IBPB))
4091 if (data & ~PRED_CMD_IBPB)
4097 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4098 if (is_guest_mode(vcpu))
4100 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4103 svm->vmcb->save.star = data;
4105 #ifdef CONFIG_X86_64
4107 svm->vmcb->save.lstar = data;
4110 svm->vmcb->save.cstar = data;
4112 case MSR_KERNEL_GS_BASE:
4113 svm->vmcb->save.kernel_gs_base = data;
4115 case MSR_SYSCALL_MASK:
4116 svm->vmcb->save.sfmask = data;
4119 case MSR_IA32_SYSENTER_CS:
4120 svm->vmcb->save.sysenter_cs = data;
4122 case MSR_IA32_SYSENTER_EIP:
4123 svm->sysenter_eip = data;
4124 svm->vmcb->save.sysenter_eip = data;
4126 case MSR_IA32_SYSENTER_ESP:
4127 svm->sysenter_esp = data;
4128 svm->vmcb->save.sysenter_esp = data;
4131 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4135 * This is rare, so we update the MSR here instead of using
4136 * direct_access_msrs. Doing that would require a rdmsr in
4139 svm->tsc_aux = data;
4140 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4142 case MSR_IA32_DEBUGCTLMSR:
4143 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4144 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4148 if (data & DEBUGCTL_RESERVED_BITS)
4151 svm->vmcb->save.dbgctl = data;
4152 mark_dirty(svm->vmcb, VMCB_LBR);
4153 if (data & (1ULL<<0))
4154 svm_enable_lbrv(svm);
4156 svm_disable_lbrv(svm);
4158 case MSR_VM_HSAVE_PA:
4159 svm->nested.hsave_msr = data;
4162 return svm_set_vm_cr(vcpu, data);
4164 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4166 case MSR_F10H_DECFG: {
4167 struct kvm_msr_entry msr_entry;
4169 msr_entry.index = msr->index;
4170 if (svm_get_msr_feature(&msr_entry))
4173 /* Check the supported bits */
4174 if (data & ~msr_entry.data)
4177 /* Don't allow the guest to change a bit, #GP */
4178 if (!msr->host_initiated && (data ^ msr_entry.data))
4181 svm->msr_decfg = data;
4184 case MSR_IA32_APICBASE:
4185 if (kvm_vcpu_apicv_active(vcpu))
4186 avic_update_vapic_bar(to_svm(vcpu), data);
4187 /* Follow through */
4189 return kvm_set_msr_common(vcpu, msr);
4194 static int wrmsr_interception(struct vcpu_svm *svm)
4196 struct msr_data msr;
4197 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4198 u64 data = kvm_read_edx_eax(&svm->vcpu);
4202 msr.host_initiated = false;
4204 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4205 if (kvm_set_msr(&svm->vcpu, &msr)) {
4206 trace_kvm_msr_write_ex(ecx, data);
4207 kvm_inject_gp(&svm->vcpu, 0);
4210 trace_kvm_msr_write(ecx, data);
4211 return kvm_skip_emulated_instruction(&svm->vcpu);
4215 static int msr_interception(struct vcpu_svm *svm)
4217 if (svm->vmcb->control.exit_info_1)
4218 return wrmsr_interception(svm);
4220 return rdmsr_interception(svm);
4223 static int interrupt_window_interception(struct vcpu_svm *svm)
4225 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4226 svm_clear_vintr(svm);
4227 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4228 mark_dirty(svm->vmcb, VMCB_INTR);
4229 ++svm->vcpu.stat.irq_window_exits;
4233 static int pause_interception(struct vcpu_svm *svm)
4235 struct kvm_vcpu *vcpu = &svm->vcpu;
4236 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4238 kvm_vcpu_on_spin(vcpu, in_kernel);
4242 static int nop_interception(struct vcpu_svm *svm)
4244 return kvm_skip_emulated_instruction(&(svm->vcpu));
4247 static int monitor_interception(struct vcpu_svm *svm)
4249 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4250 return nop_interception(svm);
4253 static int mwait_interception(struct vcpu_svm *svm)
4255 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4256 return nop_interception(svm);
4259 enum avic_ipi_failure_cause {
4260 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4261 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4262 AVIC_IPI_FAILURE_INVALID_TARGET,
4263 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4266 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4268 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4269 u32 icrl = svm->vmcb->control.exit_info_1;
4270 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4271 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4272 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4274 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4277 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4279 * AVIC hardware handles the generation of
4280 * IPIs when the specified Message Type is Fixed
4281 * (also known as fixed delivery mode) and
4282 * the Trigger Mode is edge-triggered. The hardware
4283 * also supports self and broadcast delivery modes
4284 * specified via the Destination Shorthand(DSH)
4285 * field of the ICRL. Logical and physical APIC ID
4286 * formats are supported. All other IPI types cause
4287 * a #VMEXIT, which needs to emulated.
4289 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4290 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4292 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4294 struct kvm_vcpu *vcpu;
4295 struct kvm *kvm = svm->vcpu.kvm;
4296 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4299 * At this point, we expect that the AVIC HW has already
4300 * set the appropriate IRR bits on the valid target
4301 * vcpus. So, we just need to kick the appropriate vcpu.
4303 kvm_for_each_vcpu(i, vcpu, kvm) {
4304 bool m = kvm_apic_match_dest(vcpu, apic,
4305 icrl & KVM_APIC_SHORT_MASK,
4306 GET_APIC_DEST_FIELD(icrh),
4307 icrl & KVM_APIC_DEST_MASK);
4309 if (m && !avic_vcpu_is_running(vcpu))
4310 kvm_vcpu_wake_up(vcpu);
4314 case AVIC_IPI_FAILURE_INVALID_TARGET:
4316 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4317 WARN_ONCE(1, "Invalid backing page\n");
4320 pr_err("Unknown IPI interception\n");
4326 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4328 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4330 u32 *logical_apic_id_table;
4331 int dlid = GET_APIC_LOGICAL_ID(ldr);
4336 if (flat) { /* flat */
4337 index = ffs(dlid) - 1;
4340 } else { /* cluster */
4341 int cluster = (dlid & 0xf0) >> 4;
4342 int apic = ffs(dlid & 0x0f) - 1;
4344 if ((apic < 0) || (apic > 7) ||
4347 index = (cluster << 2) + apic;
4350 logical_apic_id_table = (u32 *) page_address(vm_data->avic_logical_id_table_page);
4352 return &logical_apic_id_table[index];
4355 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4359 u32 *entry, new_entry;
4361 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4362 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4366 new_entry = READ_ONCE(*entry);
4367 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4368 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4370 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4372 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4373 WRITE_ONCE(*entry, new_entry);
4378 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4381 struct vcpu_svm *svm = to_svm(vcpu);
4382 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4387 ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4388 if (ret && svm->ldr_reg) {
4389 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4397 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4400 struct vcpu_svm *svm = to_svm(vcpu);
4401 u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4402 u32 id = (apic_id_reg >> 24) & 0xff;
4404 if (vcpu->vcpu_id == id)
4407 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4408 new = avic_get_physical_id_entry(vcpu, id);
4412 /* We need to move physical_id_entry to new offset */
4415 to_svm(vcpu)->avic_physical_id_cache = new;
4418 * Also update the guest physical APIC ID in the logical
4419 * APIC ID table entry if already setup the LDR.
4422 avic_handle_ldr_update(vcpu);
4427 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4429 struct vcpu_svm *svm = to_svm(vcpu);
4430 struct kvm_arch *vm_data = &vcpu->kvm->arch;
4431 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4432 u32 mod = (dfr >> 28) & 0xf;
4435 * We assume that all local APICs are using the same type.
4436 * If this changes, we need to flush the AVIC logical
4439 if (vm_data->ldr_mode == mod)
4442 clear_page(page_address(vm_data->avic_logical_id_table_page));
4443 vm_data->ldr_mode = mod;
4446 avic_handle_ldr_update(vcpu);
4450 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4452 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4453 u32 offset = svm->vmcb->control.exit_info_1 &
4454 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4458 if (avic_handle_apic_id_update(&svm->vcpu))
4462 if (avic_handle_ldr_update(&svm->vcpu))
4466 avic_handle_dfr_update(&svm->vcpu);
4472 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4477 static bool is_avic_unaccelerated_access_trap(u32 offset)
4506 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4509 u32 offset = svm->vmcb->control.exit_info_1 &
4510 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4511 u32 vector = svm->vmcb->control.exit_info_2 &
4512 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4513 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4514 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4515 bool trap = is_avic_unaccelerated_access_trap(offset);
4517 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4518 trap, write, vector);
4521 WARN_ONCE(!write, "svm: Handling trap read.\n");
4522 ret = avic_unaccel_trap_write(svm);
4524 /* Handling Fault */
4525 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4531 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4532 [SVM_EXIT_READ_CR0] = cr_interception,
4533 [SVM_EXIT_READ_CR3] = cr_interception,
4534 [SVM_EXIT_READ_CR4] = cr_interception,
4535 [SVM_EXIT_READ_CR8] = cr_interception,
4536 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4537 [SVM_EXIT_WRITE_CR0] = cr_interception,
4538 [SVM_EXIT_WRITE_CR3] = cr_interception,
4539 [SVM_EXIT_WRITE_CR4] = cr_interception,
4540 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4541 [SVM_EXIT_READ_DR0] = dr_interception,
4542 [SVM_EXIT_READ_DR1] = dr_interception,
4543 [SVM_EXIT_READ_DR2] = dr_interception,
4544 [SVM_EXIT_READ_DR3] = dr_interception,
4545 [SVM_EXIT_READ_DR4] = dr_interception,
4546 [SVM_EXIT_READ_DR5] = dr_interception,
4547 [SVM_EXIT_READ_DR6] = dr_interception,
4548 [SVM_EXIT_READ_DR7] = dr_interception,
4549 [SVM_EXIT_WRITE_DR0] = dr_interception,
4550 [SVM_EXIT_WRITE_DR1] = dr_interception,
4551 [SVM_EXIT_WRITE_DR2] = dr_interception,
4552 [SVM_EXIT_WRITE_DR3] = dr_interception,
4553 [SVM_EXIT_WRITE_DR4] = dr_interception,
4554 [SVM_EXIT_WRITE_DR5] = dr_interception,
4555 [SVM_EXIT_WRITE_DR6] = dr_interception,
4556 [SVM_EXIT_WRITE_DR7] = dr_interception,
4557 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4558 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4559 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4560 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4561 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4562 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4563 [SVM_EXIT_INTR] = intr_interception,
4564 [SVM_EXIT_NMI] = nmi_interception,
4565 [SVM_EXIT_SMI] = nop_on_interception,
4566 [SVM_EXIT_INIT] = nop_on_interception,
4567 [SVM_EXIT_VINTR] = interrupt_window_interception,
4568 [SVM_EXIT_RDPMC] = rdpmc_interception,
4569 [SVM_EXIT_CPUID] = cpuid_interception,
4570 [SVM_EXIT_IRET] = iret_interception,
4571 [SVM_EXIT_INVD] = emulate_on_interception,
4572 [SVM_EXIT_PAUSE] = pause_interception,
4573 [SVM_EXIT_HLT] = halt_interception,
4574 [SVM_EXIT_INVLPG] = invlpg_interception,
4575 [SVM_EXIT_INVLPGA] = invlpga_interception,
4576 [SVM_EXIT_IOIO] = io_interception,
4577 [SVM_EXIT_MSR] = msr_interception,
4578 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4579 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4580 [SVM_EXIT_VMRUN] = vmrun_interception,
4581 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4582 [SVM_EXIT_VMLOAD] = vmload_interception,
4583 [SVM_EXIT_VMSAVE] = vmsave_interception,
4584 [SVM_EXIT_STGI] = stgi_interception,
4585 [SVM_EXIT_CLGI] = clgi_interception,
4586 [SVM_EXIT_SKINIT] = skinit_interception,
4587 [SVM_EXIT_WBINVD] = wbinvd_interception,
4588 [SVM_EXIT_MONITOR] = monitor_interception,
4589 [SVM_EXIT_MWAIT] = mwait_interception,
4590 [SVM_EXIT_XSETBV] = xsetbv_interception,
4591 [SVM_EXIT_NPF] = npf_interception,
4592 [SVM_EXIT_RSM] = rsm_interception,
4593 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4594 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4597 static void dump_vmcb(struct kvm_vcpu *vcpu)
4599 struct vcpu_svm *svm = to_svm(vcpu);
4600 struct vmcb_control_area *control = &svm->vmcb->control;
4601 struct vmcb_save_area *save = &svm->vmcb->save;
4603 pr_err("VMCB Control Area:\n");
4604 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4605 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4606 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4607 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4608 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4609 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4610 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4611 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4612 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4613 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4614 pr_err("%-20s%d\n", "asid:", control->asid);
4615 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4616 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4617 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4618 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4619 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4620 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4621 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4622 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4623 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4624 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4625 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4626 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4627 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4628 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4629 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4630 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4631 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4632 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4633 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4634 pr_err("VMCB State Save Area:\n");
4635 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4637 save->es.selector, save->es.attrib,
4638 save->es.limit, save->es.base);
4639 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4641 save->cs.selector, save->cs.attrib,
4642 save->cs.limit, save->cs.base);
4643 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4645 save->ss.selector, save->ss.attrib,
4646 save->ss.limit, save->ss.base);
4647 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4649 save->ds.selector, save->ds.attrib,
4650 save->ds.limit, save->ds.base);
4651 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4653 save->fs.selector, save->fs.attrib,
4654 save->fs.limit, save->fs.base);
4655 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4657 save->gs.selector, save->gs.attrib,
4658 save->gs.limit, save->gs.base);
4659 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4661 save->gdtr.selector, save->gdtr.attrib,
4662 save->gdtr.limit, save->gdtr.base);
4663 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4665 save->ldtr.selector, save->ldtr.attrib,
4666 save->ldtr.limit, save->ldtr.base);
4667 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4669 save->idtr.selector, save->idtr.attrib,
4670 save->idtr.limit, save->idtr.base);
4671 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4673 save->tr.selector, save->tr.attrib,
4674 save->tr.limit, save->tr.base);
4675 pr_err("cpl: %d efer: %016llx\n",
4676 save->cpl, save->efer);
4677 pr_err("%-15s %016llx %-13s %016llx\n",
4678 "cr0:", save->cr0, "cr2:", save->cr2);
4679 pr_err("%-15s %016llx %-13s %016llx\n",
4680 "cr3:", save->cr3, "cr4:", save->cr4);
4681 pr_err("%-15s %016llx %-13s %016llx\n",
4682 "dr6:", save->dr6, "dr7:", save->dr7);
4683 pr_err("%-15s %016llx %-13s %016llx\n",
4684 "rip:", save->rip, "rflags:", save->rflags);
4685 pr_err("%-15s %016llx %-13s %016llx\n",
4686 "rsp:", save->rsp, "rax:", save->rax);
4687 pr_err("%-15s %016llx %-13s %016llx\n",
4688 "star:", save->star, "lstar:", save->lstar);
4689 pr_err("%-15s %016llx %-13s %016llx\n",
4690 "cstar:", save->cstar, "sfmask:", save->sfmask);
4691 pr_err("%-15s %016llx %-13s %016llx\n",
4692 "kernel_gs_base:", save->kernel_gs_base,
4693 "sysenter_cs:", save->sysenter_cs);
4694 pr_err("%-15s %016llx %-13s %016llx\n",
4695 "sysenter_esp:", save->sysenter_esp,
4696 "sysenter_eip:", save->sysenter_eip);
4697 pr_err("%-15s %016llx %-13s %016llx\n",
4698 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4699 pr_err("%-15s %016llx %-13s %016llx\n",
4700 "br_from:", save->br_from, "br_to:", save->br_to);
4701 pr_err("%-15s %016llx %-13s %016llx\n",
4702 "excp_from:", save->last_excp_from,
4703 "excp_to:", save->last_excp_to);
4706 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4708 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4710 *info1 = control->exit_info_1;
4711 *info2 = control->exit_info_2;
4714 static int handle_exit(struct kvm_vcpu *vcpu)
4716 struct vcpu_svm *svm = to_svm(vcpu);
4717 struct kvm_run *kvm_run = vcpu->run;
4718 u32 exit_code = svm->vmcb->control.exit_code;
4720 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4722 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4723 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4725 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4727 if (unlikely(svm->nested.exit_required)) {
4728 nested_svm_vmexit(svm);
4729 svm->nested.exit_required = false;
4734 if (is_guest_mode(vcpu)) {
4737 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4738 svm->vmcb->control.exit_info_1,
4739 svm->vmcb->control.exit_info_2,
4740 svm->vmcb->control.exit_int_info,
4741 svm->vmcb->control.exit_int_info_err,
4744 vmexit = nested_svm_exit_special(svm);
4746 if (vmexit == NESTED_EXIT_CONTINUE)
4747 vmexit = nested_svm_exit_handled(svm);
4749 if (vmexit == NESTED_EXIT_DONE)
4753 svm_complete_interrupts(svm);
4755 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4756 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4757 kvm_run->fail_entry.hardware_entry_failure_reason
4758 = svm->vmcb->control.exit_code;
4759 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4764 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4765 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4766 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4767 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4768 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4770 __func__, svm->vmcb->control.exit_int_info,
4773 if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4774 || !svm_exit_handlers[exit_code]) {
4775 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4776 kvm_queue_exception(vcpu, UD_VECTOR);
4780 return svm_exit_handlers[exit_code](svm);
4783 static void reload_tss(struct kvm_vcpu *vcpu)
4785 int cpu = raw_smp_processor_id();
4787 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4788 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4792 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
4794 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4795 int asid = sev_get_asid(svm->vcpu.kvm);
4797 /* Assign the asid allocated with this SEV guest */
4798 svm->vmcb->control.asid = asid;
4803 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
4804 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
4806 if (sd->sev_vmcbs[asid] == svm->vmcb &&
4807 svm->last_cpu == cpu)
4810 svm->last_cpu = cpu;
4811 sd->sev_vmcbs[asid] = svm->vmcb;
4812 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4813 mark_dirty(svm->vmcb, VMCB_ASID);
4816 static void pre_svm_run(struct vcpu_svm *svm)
4818 int cpu = raw_smp_processor_id();
4820 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4822 if (sev_guest(svm->vcpu.kvm))
4823 return pre_sev_run(svm, cpu);
4825 /* FIXME: handle wraparound of asid_generation */
4826 if (svm->asid_generation != sd->asid_generation)
4830 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
4832 struct vcpu_svm *svm = to_svm(vcpu);
4834 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
4835 vcpu->arch.hflags |= HF_NMI_MASK;
4836 set_intercept(svm, INTERCEPT_IRET);
4837 ++vcpu->stat.nmi_injections;
4840 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
4842 struct vmcb_control_area *control;
4844 /* The following fields are ignored when AVIC is enabled */
4845 control = &svm->vmcb->control;
4846 control->int_vector = irq;
4847 control->int_ctl &= ~V_INTR_PRIO_MASK;
4848 control->int_ctl |= V_IRQ_MASK |
4849 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
4850 mark_dirty(svm->vmcb, VMCB_INTR);
4853 static void svm_set_irq(struct kvm_vcpu *vcpu)
4855 struct vcpu_svm *svm = to_svm(vcpu);
4857 BUG_ON(!(gif_set(svm)));
4859 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
4860 ++vcpu->stat.irq_injections;
4862 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
4863 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
4866 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
4868 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
4871 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4873 struct vcpu_svm *svm = to_svm(vcpu);
4875 if (svm_nested_virtualize_tpr(vcpu) ||
4876 kvm_vcpu_apicv_active(vcpu))
4879 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4885 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4888 static void svm_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
4893 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
4895 return avic && irqchip_split(vcpu->kvm);
4898 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
4902 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
4906 /* Note: Currently only used by Hyper-V. */
4907 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4909 struct vcpu_svm *svm = to_svm(vcpu);
4910 struct vmcb *vmcb = svm->vmcb;
4912 if (!kvm_vcpu_apicv_active(&svm->vcpu))
4915 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
4916 mark_dirty(vmcb, VMCB_INTR);
4919 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
4924 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
4926 kvm_lapic_set_irr(vec, vcpu->arch.apic);
4927 smp_mb__after_atomic();
4929 if (avic_vcpu_is_running(vcpu))
4930 wrmsrl(SVM_AVIC_DOORBELL,
4931 kvm_cpu_get_apicid(vcpu->cpu));
4933 kvm_vcpu_wake_up(vcpu);
4936 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4938 unsigned long flags;
4939 struct amd_svm_iommu_ir *cur;
4941 spin_lock_irqsave(&svm->ir_list_lock, flags);
4942 list_for_each_entry(cur, &svm->ir_list, node) {
4943 if (cur->data != pi->ir_data)
4945 list_del(&cur->node);
4949 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4952 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4955 unsigned long flags;
4956 struct amd_svm_iommu_ir *ir;
4959 * In some cases, the existing irte is updaed and re-set,
4960 * so we need to check here if it's already been * added
4963 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
4964 struct kvm *kvm = svm->vcpu.kvm;
4965 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
4966 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
4967 struct vcpu_svm *prev_svm;
4974 prev_svm = to_svm(prev_vcpu);
4975 svm_ir_list_del(prev_svm, pi);
4979 * Allocating new amd_iommu_pi_data, which will get
4980 * add to the per-vcpu ir_list.
4982 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
4987 ir->data = pi->ir_data;
4989 spin_lock_irqsave(&svm->ir_list_lock, flags);
4990 list_add(&ir->node, &svm->ir_list);
4991 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
4998 * The HW cannot support posting multicast/broadcast
4999 * interrupts to a vCPU. So, we still use legacy interrupt
5000 * remapping for these kind of interrupts.
5002 * For lowest-priority interrupts, we only support
5003 * those with single CPU as the destination, e.g. user
5004 * configures the interrupts via /proc/irq or uses
5005 * irqbalance to make the interrupts single-CPU.
5008 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5009 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5011 struct kvm_lapic_irq irq;
5012 struct kvm_vcpu *vcpu = NULL;
5014 kvm_set_msi_irq(kvm, e, &irq);
5016 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
5017 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5018 __func__, irq.vector);
5022 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5024 *svm = to_svm(vcpu);
5025 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5026 vcpu_info->vector = irq.vector;
5032 * svm_update_pi_irte - set IRTE for Posted-Interrupts
5035 * @host_irq: host irq of the interrupt
5036 * @guest_irq: gsi of the interrupt
5037 * @set: set or unset PI
5038 * returns 0 on success, < 0 on failure
5040 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5041 uint32_t guest_irq, bool set)
5043 struct kvm_kernel_irq_routing_entry *e;
5044 struct kvm_irq_routing_table *irq_rt;
5045 int idx, ret = -EINVAL;
5047 if (!kvm_arch_has_assigned_device(kvm) ||
5048 !irq_remapping_cap(IRQ_POSTING_CAP))
5051 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5052 __func__, host_irq, guest_irq, set);
5054 idx = srcu_read_lock(&kvm->irq_srcu);
5055 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5056 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5058 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5059 struct vcpu_data vcpu_info;
5060 struct vcpu_svm *svm = NULL;
5062 if (e->type != KVM_IRQ_ROUTING_MSI)
5066 * Here, we setup with legacy mode in the following cases:
5067 * 1. When cannot target interrupt to a specific vcpu.
5068 * 2. Unsetting posted interrupt.
5069 * 3. APIC virtialization is disabled for the vcpu.
5071 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5072 kvm_vcpu_apicv_active(&svm->vcpu)) {
5073 struct amd_iommu_pi_data pi;
5075 /* Try to enable guest_mode in IRTE */
5076 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5078 pi.ga_tag = AVIC_GATAG(kvm->arch.avic_vm_id,
5080 pi.is_guest_mode = true;
5081 pi.vcpu_data = &vcpu_info;
5082 ret = irq_set_vcpu_affinity(host_irq, &pi);
5085 * Here, we successfully setting up vcpu affinity in
5086 * IOMMU guest mode. Now, we need to store the posted
5087 * interrupt information in a per-vcpu ir_list so that
5088 * we can reference to them directly when we update vcpu
5089 * scheduling information in IOMMU irte.
5091 if (!ret && pi.is_guest_mode)
5092 svm_ir_list_add(svm, &pi);
5094 /* Use legacy mode in IRTE */
5095 struct amd_iommu_pi_data pi;
5098 * Here, pi is used to:
5099 * - Tell IOMMU to use legacy mode for this interrupt.
5100 * - Retrieve ga_tag of prior interrupt remapping data.
5102 pi.is_guest_mode = false;
5103 ret = irq_set_vcpu_affinity(host_irq, &pi);
5106 * Check if the posted interrupt was previously
5107 * setup with the guest_mode by checking if the ga_tag
5108 * was cached. If so, we need to clean up the per-vcpu
5111 if (!ret && pi.prev_ga_tag) {
5112 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5113 struct kvm_vcpu *vcpu;
5115 vcpu = kvm_get_vcpu_by_id(kvm, id);
5117 svm_ir_list_del(to_svm(vcpu), &pi);
5122 trace_kvm_pi_irte_update(svm->vcpu.vcpu_id,
5125 vcpu_info.pi_desc_addr, set);
5129 pr_err("%s: failed to update PI IRTE\n", __func__);
5136 srcu_read_unlock(&kvm->irq_srcu, idx);
5140 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5142 struct vcpu_svm *svm = to_svm(vcpu);
5143 struct vmcb *vmcb = svm->vmcb;
5145 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5146 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5147 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5152 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5154 struct vcpu_svm *svm = to_svm(vcpu);
5156 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5159 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5161 struct vcpu_svm *svm = to_svm(vcpu);
5164 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5165 set_intercept(svm, INTERCEPT_IRET);
5167 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5168 clr_intercept(svm, INTERCEPT_IRET);
5172 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5174 struct vcpu_svm *svm = to_svm(vcpu);
5175 struct vmcb *vmcb = svm->vmcb;
5178 if (!gif_set(svm) ||
5179 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5182 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5184 if (is_guest_mode(vcpu))
5185 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5190 static void enable_irq_window(struct kvm_vcpu *vcpu)
5192 struct vcpu_svm *svm = to_svm(vcpu);
5194 if (kvm_vcpu_apicv_active(vcpu))
5198 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5199 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5200 * get that intercept, this function will be called again though and
5201 * we'll get the vintr intercept. However, if the vGIF feature is
5202 * enabled, the STGI interception will not occur. Enable the irq
5203 * window under the assumption that the hardware will set the GIF.
5205 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5207 svm_inject_irq(svm, 0x0);
5211 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5213 struct vcpu_svm *svm = to_svm(vcpu);
5215 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5217 return; /* IRET will cause a vm exit */
5219 if (!gif_set(svm)) {
5220 if (vgif_enabled(svm))
5221 set_intercept(svm, INTERCEPT_STGI);
5222 return; /* STGI will cause a vm exit */
5225 if (svm->nested.exit_required)
5226 return; /* we're not going to run the guest yet */
5229 * Something prevents NMI from been injected. Single step over possible
5230 * problem (IRET or exception injection or interrupt shadow)
5232 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5233 svm->nmi_singlestep = true;
5234 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5237 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5242 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5244 struct vcpu_svm *svm = to_svm(vcpu);
5246 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5247 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5249 svm->asid_generation--;
5252 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5256 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5258 struct vcpu_svm *svm = to_svm(vcpu);
5260 if (svm_nested_virtualize_tpr(vcpu))
5263 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5264 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5265 kvm_set_cr8(vcpu, cr8);
5269 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5271 struct vcpu_svm *svm = to_svm(vcpu);
5274 if (svm_nested_virtualize_tpr(vcpu) ||
5275 kvm_vcpu_apicv_active(vcpu))
5278 cr8 = kvm_get_cr8(vcpu);
5279 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5280 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5283 static void svm_complete_interrupts(struct vcpu_svm *svm)
5287 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5288 unsigned int3_injected = svm->int3_injected;
5290 svm->int3_injected = 0;
5293 * If we've made progress since setting HF_IRET_MASK, we've
5294 * executed an IRET and can allow NMI injection.
5296 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5297 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5298 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5299 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5302 svm->vcpu.arch.nmi_injected = false;
5303 kvm_clear_exception_queue(&svm->vcpu);
5304 kvm_clear_interrupt_queue(&svm->vcpu);
5306 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5309 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5311 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5312 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5315 case SVM_EXITINTINFO_TYPE_NMI:
5316 svm->vcpu.arch.nmi_injected = true;
5318 case SVM_EXITINTINFO_TYPE_EXEPT:
5320 * In case of software exceptions, do not reinject the vector,
5321 * but re-execute the instruction instead. Rewind RIP first
5322 * if we emulated INT3 before.
5324 if (kvm_exception_is_soft(vector)) {
5325 if (vector == BP_VECTOR && int3_injected &&
5326 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5327 kvm_rip_write(&svm->vcpu,
5328 kvm_rip_read(&svm->vcpu) -
5332 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5333 u32 err = svm->vmcb->control.exit_int_info_err;
5334 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5337 kvm_requeue_exception(&svm->vcpu, vector);
5339 case SVM_EXITINTINFO_TYPE_INTR:
5340 kvm_queue_interrupt(&svm->vcpu, vector, false);
5347 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5349 struct vcpu_svm *svm = to_svm(vcpu);
5350 struct vmcb_control_area *control = &svm->vmcb->control;
5352 control->exit_int_info = control->event_inj;
5353 control->exit_int_info_err = control->event_inj_err;
5354 control->event_inj = 0;
5355 svm_complete_interrupts(svm);
5358 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5360 struct vcpu_svm *svm = to_svm(vcpu);
5362 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5363 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5364 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5367 * A vmexit emulation is required before the vcpu can be executed
5370 if (unlikely(svm->nested.exit_required))
5374 * Disable singlestep if we're injecting an interrupt/exception.
5375 * We don't want our modified rflags to be pushed on the stack where
5376 * we might not be able to easily reset them if we disabled NMI
5379 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5381 * Event injection happens before external interrupts cause a
5382 * vmexit and interrupts are disabled here, so smp_send_reschedule
5383 * is enough to force an immediate vmexit.
5385 disable_nmi_singlestep(svm);
5386 smp_send_reschedule(vcpu->cpu);
5391 sync_lapic_to_cr8(vcpu);
5393 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5400 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5401 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5402 * is no need to worry about the conditional branch over the wrmsr
5403 * being speculatively taken.
5406 wrmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5409 "push %%" _ASM_BP "; \n\t"
5410 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5411 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5412 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5413 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5414 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5415 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5416 #ifdef CONFIG_X86_64
5417 "mov %c[r8](%[svm]), %%r8 \n\t"
5418 "mov %c[r9](%[svm]), %%r9 \n\t"
5419 "mov %c[r10](%[svm]), %%r10 \n\t"
5420 "mov %c[r11](%[svm]), %%r11 \n\t"
5421 "mov %c[r12](%[svm]), %%r12 \n\t"
5422 "mov %c[r13](%[svm]), %%r13 \n\t"
5423 "mov %c[r14](%[svm]), %%r14 \n\t"
5424 "mov %c[r15](%[svm]), %%r15 \n\t"
5427 /* Enter guest mode */
5428 "push %%" _ASM_AX " \n\t"
5429 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5430 __ex(SVM_VMLOAD) "\n\t"
5431 __ex(SVM_VMRUN) "\n\t"
5432 __ex(SVM_VMSAVE) "\n\t"
5433 "pop %%" _ASM_AX " \n\t"
5435 /* Save guest registers, load host registers */
5436 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5437 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5438 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5439 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5440 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5441 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5442 #ifdef CONFIG_X86_64
5443 "mov %%r8, %c[r8](%[svm]) \n\t"
5444 "mov %%r9, %c[r9](%[svm]) \n\t"
5445 "mov %%r10, %c[r10](%[svm]) \n\t"
5446 "mov %%r11, %c[r11](%[svm]) \n\t"
5447 "mov %%r12, %c[r12](%[svm]) \n\t"
5448 "mov %%r13, %c[r13](%[svm]) \n\t"
5449 "mov %%r14, %c[r14](%[svm]) \n\t"
5450 "mov %%r15, %c[r15](%[svm]) \n\t"
5453 * Clear host registers marked as clobbered to prevent
5456 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5457 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5458 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5459 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5460 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5461 #ifdef CONFIG_X86_64
5462 "xor %%r8, %%r8 \n\t"
5463 "xor %%r9, %%r9 \n\t"
5464 "xor %%r10, %%r10 \n\t"
5465 "xor %%r11, %%r11 \n\t"
5466 "xor %%r12, %%r12 \n\t"
5467 "xor %%r13, %%r13 \n\t"
5468 "xor %%r14, %%r14 \n\t"
5469 "xor %%r15, %%r15 \n\t"
5474 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5475 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5476 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5477 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5478 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5479 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5480 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5481 #ifdef CONFIG_X86_64
5482 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5483 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5484 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5485 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5486 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5487 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5488 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5489 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5492 #ifdef CONFIG_X86_64
5493 , "rbx", "rcx", "rdx", "rsi", "rdi"
5494 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5496 , "ebx", "ecx", "edx", "esi", "edi"
5501 * We do not use IBRS in the kernel. If this vCPU has used the
5502 * SPEC_CTRL MSR it may have left it on; save the value and
5503 * turn it off. This is much more efficient than blindly adding
5504 * it to the atomic save/restore list. Especially as the former
5505 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5507 * For non-nested case:
5508 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5512 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5515 if (!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL))
5516 rdmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5519 wrmsrl(MSR_IA32_SPEC_CTRL, 0);
5521 /* Eliminate branch target predictions from guest mode */
5524 #ifdef CONFIG_X86_64
5525 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5527 loadsegment(fs, svm->host.fs);
5528 #ifndef CONFIG_X86_32_LAZY_GS
5529 loadsegment(gs, svm->host.gs);
5535 local_irq_disable();
5537 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5538 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5539 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5540 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5542 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5543 kvm_before_handle_nmi(&svm->vcpu);
5547 /* Any pending NMI will happen here */
5549 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5550 kvm_after_handle_nmi(&svm->vcpu);
5552 sync_cr8_to_lapic(vcpu);
5556 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5558 /* if exit due to PF check for async PF */
5559 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5560 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5563 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5564 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5568 * We need to handle MC intercepts here before the vcpu has a chance to
5569 * change the physical cpu
5571 if (unlikely(svm->vmcb->control.exit_code ==
5572 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5573 svm_handle_mce(svm);
5575 mark_all_clean(svm->vmcb);
5577 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5579 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5581 struct vcpu_svm *svm = to_svm(vcpu);
5583 svm->vmcb->save.cr3 = __sme_set(root);
5584 mark_dirty(svm->vmcb, VMCB_CR);
5585 svm_flush_tlb(vcpu, true);
5588 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5590 struct vcpu_svm *svm = to_svm(vcpu);
5592 svm->vmcb->control.nested_cr3 = __sme_set(root);
5593 mark_dirty(svm->vmcb, VMCB_NPT);
5595 /* Also sync guest cr3 here in case we live migrate */
5596 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5597 mark_dirty(svm->vmcb, VMCB_CR);
5599 svm_flush_tlb(vcpu, true);
5602 static int is_disabled(void)
5606 rdmsrl(MSR_VM_CR, vm_cr);
5607 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5614 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5617 * Patch in the VMMCALL instruction:
5619 hypercall[0] = 0x0f;
5620 hypercall[1] = 0x01;
5621 hypercall[2] = 0xd9;
5624 static void svm_check_processor_compat(void *rtn)
5629 static bool svm_cpu_has_accelerated_tpr(void)
5634 static bool svm_has_high_real_mode_segbase(void)
5639 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5644 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5646 struct vcpu_svm *svm = to_svm(vcpu);
5648 /* Update nrips enabled cache */
5649 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5651 if (!kvm_vcpu_apicv_active(vcpu))
5654 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5657 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5662 entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5666 entry->ecx |= (1 << 2); /* Set SVM bit */
5669 entry->eax = 1; /* SVM revision 1 */
5670 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5671 ASID emulation to nested SVM */
5672 entry->ecx = 0; /* Reserved */
5673 entry->edx = 0; /* Per default do not support any
5674 additional features */
5676 /* Support next_rip if host supports it */
5677 if (boot_cpu_has(X86_FEATURE_NRIPS))
5678 entry->edx |= SVM_FEATURE_NRIP;
5680 /* Support NPT for the guest if enabled */
5682 entry->edx |= SVM_FEATURE_NPT;
5686 /* Support memory encryption cpuid if host supports it */
5687 if (boot_cpu_has(X86_FEATURE_SEV))
5688 cpuid(0x8000001f, &entry->eax, &entry->ebx,
5689 &entry->ecx, &entry->edx);
5694 static int svm_get_lpage_level(void)
5696 return PT_PDPE_LEVEL;
5699 static bool svm_rdtscp_supported(void)
5701 return boot_cpu_has(X86_FEATURE_RDTSCP);
5704 static bool svm_invpcid_supported(void)
5709 static bool svm_mpx_supported(void)
5714 static bool svm_xsaves_supported(void)
5719 static bool svm_umip_emulated(void)
5724 static bool svm_has_wbinvd_exit(void)
5729 #define PRE_EX(exit) { .exit_code = (exit), \
5730 .stage = X86_ICPT_PRE_EXCEPT, }
5731 #define POST_EX(exit) { .exit_code = (exit), \
5732 .stage = X86_ICPT_POST_EXCEPT, }
5733 #define POST_MEM(exit) { .exit_code = (exit), \
5734 .stage = X86_ICPT_POST_MEMACCESS, }
5736 static const struct __x86_intercept {
5738 enum x86_intercept_stage stage;
5739 } x86_intercept_map[] = {
5740 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
5741 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
5742 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
5743 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
5744 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
5745 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
5746 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
5747 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
5748 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
5749 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
5750 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
5751 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
5752 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
5753 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
5754 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
5755 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
5756 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
5757 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
5758 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
5759 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
5760 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
5761 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
5762 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
5763 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
5764 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
5765 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
5766 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
5767 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
5768 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
5769 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
5770 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
5771 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
5772 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
5773 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
5774 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
5775 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
5776 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
5777 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
5778 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
5779 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
5780 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
5781 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
5782 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
5783 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
5784 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
5785 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
5792 static int svm_check_intercept(struct kvm_vcpu *vcpu,
5793 struct x86_instruction_info *info,
5794 enum x86_intercept_stage stage)
5796 struct vcpu_svm *svm = to_svm(vcpu);
5797 int vmexit, ret = X86EMUL_CONTINUE;
5798 struct __x86_intercept icpt_info;
5799 struct vmcb *vmcb = svm->vmcb;
5801 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
5804 icpt_info = x86_intercept_map[info->intercept];
5806 if (stage != icpt_info.stage)
5809 switch (icpt_info.exit_code) {
5810 case SVM_EXIT_READ_CR0:
5811 if (info->intercept == x86_intercept_cr_read)
5812 icpt_info.exit_code += info->modrm_reg;
5814 case SVM_EXIT_WRITE_CR0: {
5815 unsigned long cr0, val;
5818 if (info->intercept == x86_intercept_cr_write)
5819 icpt_info.exit_code += info->modrm_reg;
5821 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
5822 info->intercept == x86_intercept_clts)
5825 intercept = svm->nested.intercept;
5827 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
5830 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5831 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
5833 if (info->intercept == x86_intercept_lmsw) {
5836 /* lmsw can't clear PE - catch this here */
5837 if (cr0 & X86_CR0_PE)
5842 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5846 case SVM_EXIT_READ_DR0:
5847 case SVM_EXIT_WRITE_DR0:
5848 icpt_info.exit_code += info->modrm_reg;
5851 if (info->intercept == x86_intercept_wrmsr)
5852 vmcb->control.exit_info_1 = 1;
5854 vmcb->control.exit_info_1 = 0;
5856 case SVM_EXIT_PAUSE:
5858 * We get this for NOP only, but pause
5859 * is rep not, check this here
5861 if (info->rep_prefix != REPE_PREFIX)
5864 case SVM_EXIT_IOIO: {
5868 if (info->intercept == x86_intercept_in ||
5869 info->intercept == x86_intercept_ins) {
5870 exit_info = ((info->src_val & 0xffff) << 16) |
5872 bytes = info->dst_bytes;
5874 exit_info = (info->dst_val & 0xffff) << 16;
5875 bytes = info->src_bytes;
5878 if (info->intercept == x86_intercept_outs ||
5879 info->intercept == x86_intercept_ins)
5880 exit_info |= SVM_IOIO_STR_MASK;
5882 if (info->rep_prefix)
5883 exit_info |= SVM_IOIO_REP_MASK;
5885 bytes = min(bytes, 4u);
5887 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5889 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5891 vmcb->control.exit_info_1 = exit_info;
5892 vmcb->control.exit_info_2 = info->next_rip;
5900 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5901 if (static_cpu_has(X86_FEATURE_NRIPS))
5902 vmcb->control.next_rip = info->next_rip;
5903 vmcb->control.exit_code = icpt_info.exit_code;
5904 vmexit = nested_svm_exit_handled(svm);
5906 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5913 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
5917 * We must have an instruction with interrupts enabled, so
5918 * the timer interrupt isn't delayed by the interrupt shadow.
5921 local_irq_disable();
5924 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
5928 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
5930 if (avic_handle_apic_id_update(vcpu) != 0)
5932 if (avic_handle_dfr_update(vcpu) != 0)
5934 avic_handle_ldr_update(vcpu);
5937 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5939 /* [63:9] are reserved. */
5940 vcpu->arch.mcg_cap &= 0x1ff;
5943 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
5945 struct vcpu_svm *svm = to_svm(vcpu);
5947 /* Per APM Vol.2 15.22.2 "Response to SMI" */
5951 if (is_guest_mode(&svm->vcpu) &&
5952 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
5953 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
5954 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
5955 svm->nested.exit_required = true;
5962 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
5964 struct vcpu_svm *svm = to_svm(vcpu);
5967 if (is_guest_mode(vcpu)) {
5968 /* FED8h - SVM Guest */
5969 put_smstate(u64, smstate, 0x7ed8, 1);
5970 /* FEE0h - SVM Guest VMCB Physical Address */
5971 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
5973 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5974 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5975 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5977 ret = nested_svm_vmexit(svm);
5984 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
5986 struct vcpu_svm *svm = to_svm(vcpu);
5987 struct vmcb *nested_vmcb;
5995 ret = kvm_vcpu_read_guest(vcpu, smbase + 0xfed8, &svm_state_save,
5996 sizeof(svm_state_save));
6000 if (svm_state_save.guest) {
6001 vcpu->arch.hflags &= ~HF_SMM_MASK;
6002 nested_vmcb = nested_svm_map(svm, svm_state_save.vmcb, &page);
6004 enter_svm_guest_mode(svm, svm_state_save.vmcb, nested_vmcb, page);
6007 vcpu->arch.hflags |= HF_SMM_MASK;
6012 static int enable_smi_window(struct kvm_vcpu *vcpu)
6014 struct vcpu_svm *svm = to_svm(vcpu);
6016 if (!gif_set(svm)) {
6017 if (vgif_enabled(svm))
6018 set_intercept(svm, INTERCEPT_STGI);
6019 /* STGI will cause a vm exit */
6025 static int sev_asid_new(void)
6030 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6032 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6033 if (pos >= max_sev_asid)
6036 set_bit(pos, sev_asid_bitmap);
6040 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6042 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6046 asid = sev_asid_new();
6050 ret = sev_platform_init(&argp->error);
6056 INIT_LIST_HEAD(&sev->regions_list);
6061 __sev_asid_free(asid);
6065 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6067 struct sev_data_activate *data;
6068 int asid = sev_get_asid(kvm);
6071 wbinvd_on_all_cpus();
6073 ret = sev_guest_df_flush(error);
6077 data = kzalloc(sizeof(*data), GFP_KERNEL);
6081 /* activate ASID on the given handle */
6082 data->handle = handle;
6084 ret = sev_guest_activate(data, error);
6090 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6099 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6105 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6107 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6109 return __sev_issue_cmd(sev->fd, id, data, error);
6112 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6114 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6115 struct sev_data_launch_start *start;
6116 struct kvm_sev_launch_start params;
6117 void *dh_blob, *session_blob;
6118 int *error = &argp->error;
6121 if (!sev_guest(kvm))
6124 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6127 start = kzalloc(sizeof(*start), GFP_KERNEL);
6132 if (params.dh_uaddr) {
6133 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6134 if (IS_ERR(dh_blob)) {
6135 ret = PTR_ERR(dh_blob);
6139 start->dh_cert_address = __sme_set(__pa(dh_blob));
6140 start->dh_cert_len = params.dh_len;
6143 session_blob = NULL;
6144 if (params.session_uaddr) {
6145 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6146 if (IS_ERR(session_blob)) {
6147 ret = PTR_ERR(session_blob);
6151 start->session_address = __sme_set(__pa(session_blob));
6152 start->session_len = params.session_len;
6155 start->handle = params.handle;
6156 start->policy = params.policy;
6158 /* create memory encryption context */
6159 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6161 goto e_free_session;
6163 /* Bind ASID to this guest */
6164 ret = sev_bind_asid(kvm, start->handle, error);
6166 goto e_free_session;
6168 /* return handle to userspace */
6169 params.handle = start->handle;
6170 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6171 sev_unbind_asid(kvm, start->handle);
6173 goto e_free_session;
6176 sev->handle = start->handle;
6177 sev->fd = argp->sev_fd;
6180 kfree(session_blob);
6188 static int get_num_contig_pages(int idx, struct page **inpages,
6189 unsigned long npages)
6191 unsigned long paddr, next_paddr;
6192 int i = idx + 1, pages = 1;
6194 /* find the number of contiguous pages starting from idx */
6195 paddr = __sme_page_pa(inpages[idx]);
6196 while (i < npages) {
6197 next_paddr = __sme_page_pa(inpages[i++]);
6198 if ((paddr + PAGE_SIZE) == next_paddr) {
6209 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6211 unsigned long vaddr, vaddr_end, next_vaddr, npages, size;
6212 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6213 struct kvm_sev_launch_update_data params;
6214 struct sev_data_launch_update_data *data;
6215 struct page **inpages;
6218 if (!sev_guest(kvm))
6221 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6224 data = kzalloc(sizeof(*data), GFP_KERNEL);
6228 vaddr = params.uaddr;
6230 vaddr_end = vaddr + size;
6232 /* Lock the user memory. */
6233 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6240 * The LAUNCH_UPDATE command will perform in-place encryption of the
6241 * memory content (i.e it will write the same memory region with C=1).
6242 * It's possible that the cache may contain the data with C=0, i.e.,
6243 * unencrypted so invalidate it first.
6245 sev_clflush_pages(inpages, npages);
6247 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6251 * If the user buffer is not page-aligned, calculate the offset
6254 offset = vaddr & (PAGE_SIZE - 1);
6256 /* Calculate the number of pages that can be encrypted in one go. */
6257 pages = get_num_contig_pages(i, inpages, npages);
6259 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6261 data->handle = sev->handle;
6263 data->address = __sme_page_pa(inpages[i]) + offset;
6264 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6269 next_vaddr = vaddr + len;
6273 /* content of memory is updated, mark pages dirty */
6274 for (i = 0; i < npages; i++) {
6275 set_page_dirty_lock(inpages[i]);
6276 mark_page_accessed(inpages[i]);
6278 /* unlock the user pages */
6279 sev_unpin_memory(kvm, inpages, npages);
6285 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6287 void __user *measure = (void __user *)(uintptr_t)argp->data;
6288 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6289 struct sev_data_launch_measure *data;
6290 struct kvm_sev_launch_measure params;
6291 void __user *p = NULL;
6295 if (!sev_guest(kvm))
6298 if (copy_from_user(¶ms, measure, sizeof(params)))
6301 data = kzalloc(sizeof(*data), GFP_KERNEL);
6305 /* User wants to query the blob length */
6309 p = (void __user *)(uintptr_t)params.uaddr;
6311 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6317 blob = kmalloc(params.len, GFP_KERNEL);
6321 data->address = __psp_pa(blob);
6322 data->len = params.len;
6326 data->handle = sev->handle;
6327 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6330 * If we query the session length, FW responded with expected data.
6339 if (copy_to_user(p, blob, params.len))
6344 params.len = data->len;
6345 if (copy_to_user(measure, ¶ms, sizeof(params)))
6354 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6356 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6357 struct sev_data_launch_finish *data;
6360 if (!sev_guest(kvm))
6363 data = kzalloc(sizeof(*data), GFP_KERNEL);
6367 data->handle = sev->handle;
6368 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6374 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6376 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6377 struct kvm_sev_guest_status params;
6378 struct sev_data_guest_status *data;
6381 if (!sev_guest(kvm))
6384 data = kzalloc(sizeof(*data), GFP_KERNEL);
6388 data->handle = sev->handle;
6389 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6393 params.policy = data->policy;
6394 params.state = data->state;
6395 params.handle = data->handle;
6397 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6404 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6405 unsigned long dst, int size,
6406 int *error, bool enc)
6408 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6409 struct sev_data_dbg *data;
6412 data = kzalloc(sizeof(*data), GFP_KERNEL);
6416 data->handle = sev->handle;
6417 data->dst_addr = dst;
6418 data->src_addr = src;
6421 ret = sev_issue_cmd(kvm,
6422 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6428 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6429 unsigned long dst_paddr, int sz, int *err)
6434 * Its safe to read more than we are asked, caller should ensure that
6435 * destination has enough space.
6437 src_paddr = round_down(src_paddr, 16);
6438 offset = src_paddr & 15;
6439 sz = round_up(sz + offset, 16);
6441 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6444 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6445 unsigned long __user dst_uaddr,
6446 unsigned long dst_paddr,
6449 struct page *tpage = NULL;
6452 /* if inputs are not 16-byte then use intermediate buffer */
6453 if (!IS_ALIGNED(dst_paddr, 16) ||
6454 !IS_ALIGNED(paddr, 16) ||
6455 !IS_ALIGNED(size, 16)) {
6456 tpage = (void *)alloc_page(GFP_KERNEL);
6460 dst_paddr = __sme_page_pa(tpage);
6463 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6468 offset = paddr & 15;
6469 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6470 page_address(tpage) + offset, size))
6481 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6482 unsigned long __user vaddr,
6483 unsigned long dst_paddr,
6484 unsigned long __user dst_vaddr,
6485 int size, int *error)
6487 struct page *src_tpage = NULL;
6488 struct page *dst_tpage = NULL;
6489 int ret, len = size;
6491 /* If source buffer is not aligned then use an intermediate buffer */
6492 if (!IS_ALIGNED(vaddr, 16)) {
6493 src_tpage = alloc_page(GFP_KERNEL);
6497 if (copy_from_user(page_address(src_tpage),
6498 (void __user *)(uintptr_t)vaddr, size)) {
6499 __free_page(src_tpage);
6503 paddr = __sme_page_pa(src_tpage);
6507 * If destination buffer or length is not aligned then do read-modify-write:
6508 * - decrypt destination in an intermediate buffer
6509 * - copy the source buffer in an intermediate buffer
6510 * - use the intermediate buffer as source buffer
6512 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6515 dst_tpage = alloc_page(GFP_KERNEL);
6521 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6522 __sme_page_pa(dst_tpage), size, error);
6527 * If source is kernel buffer then use memcpy() otherwise
6530 dst_offset = dst_paddr & 15;
6533 memcpy(page_address(dst_tpage) + dst_offset,
6534 page_address(src_tpage), size);
6536 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6537 (void __user *)(uintptr_t)vaddr, size)) {
6543 paddr = __sme_page_pa(dst_tpage);
6544 dst_paddr = round_down(dst_paddr, 16);
6545 len = round_up(size, 16);
6548 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6552 __free_page(src_tpage);
6554 __free_page(dst_tpage);
6558 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6560 unsigned long vaddr, vaddr_end, next_vaddr;
6561 unsigned long dst_vaddr, dst_vaddr_end;
6562 struct page **src_p, **dst_p;
6563 struct kvm_sev_dbg debug;
6567 if (!sev_guest(kvm))
6570 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6573 vaddr = debug.src_uaddr;
6575 vaddr_end = vaddr + size;
6576 dst_vaddr = debug.dst_uaddr;
6577 dst_vaddr_end = dst_vaddr + size;
6579 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6580 int len, s_off, d_off;
6582 /* lock userspace source and destination page */
6583 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6587 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6589 sev_unpin_memory(kvm, src_p, n);
6594 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6595 * memory content (i.e it will write the same memory region with C=1).
6596 * It's possible that the cache may contain the data with C=0, i.e.,
6597 * unencrypted so invalidate it first.
6599 sev_clflush_pages(src_p, 1);
6600 sev_clflush_pages(dst_p, 1);
6603 * Since user buffer may not be page aligned, calculate the
6604 * offset within the page.
6606 s_off = vaddr & ~PAGE_MASK;
6607 d_off = dst_vaddr & ~PAGE_MASK;
6608 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6611 ret = __sev_dbg_decrypt_user(kvm,
6612 __sme_page_pa(src_p[0]) + s_off,
6614 __sme_page_pa(dst_p[0]) + d_off,
6617 ret = __sev_dbg_encrypt_user(kvm,
6618 __sme_page_pa(src_p[0]) + s_off,
6620 __sme_page_pa(dst_p[0]) + d_off,
6624 sev_unpin_memory(kvm, src_p, 1);
6625 sev_unpin_memory(kvm, dst_p, 1);
6630 next_vaddr = vaddr + len;
6631 dst_vaddr = dst_vaddr + len;
6638 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6640 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6641 struct sev_data_launch_secret *data;
6642 struct kvm_sev_launch_secret params;
6643 struct page **pages;
6648 if (!sev_guest(kvm))
6651 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6654 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6659 * The secret must be copied into contiguous memory region, lets verify
6660 * that userspace memory pages are contiguous before we issue command.
6662 if (get_num_contig_pages(0, pages, n) != n) {
6664 goto e_unpin_memory;
6668 data = kzalloc(sizeof(*data), GFP_KERNEL);
6670 goto e_unpin_memory;
6672 offset = params.guest_uaddr & (PAGE_SIZE - 1);
6673 data->guest_address = __sme_page_pa(pages[0]) + offset;
6674 data->guest_len = params.guest_len;
6676 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6678 ret = PTR_ERR(blob);
6682 data->trans_address = __psp_pa(blob);
6683 data->trans_len = params.trans_len;
6685 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6690 data->hdr_address = __psp_pa(hdr);
6691 data->hdr_len = params.hdr_len;
6693 data->handle = sev->handle;
6694 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
6703 sev_unpin_memory(kvm, pages, n);
6707 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
6709 struct kvm_sev_cmd sev_cmd;
6712 if (!svm_sev_enabled())
6715 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
6718 mutex_lock(&kvm->lock);
6720 switch (sev_cmd.id) {
6722 r = sev_guest_init(kvm, &sev_cmd);
6724 case KVM_SEV_LAUNCH_START:
6725 r = sev_launch_start(kvm, &sev_cmd);
6727 case KVM_SEV_LAUNCH_UPDATE_DATA:
6728 r = sev_launch_update_data(kvm, &sev_cmd);
6730 case KVM_SEV_LAUNCH_MEASURE:
6731 r = sev_launch_measure(kvm, &sev_cmd);
6733 case KVM_SEV_LAUNCH_FINISH:
6734 r = sev_launch_finish(kvm, &sev_cmd);
6736 case KVM_SEV_GUEST_STATUS:
6737 r = sev_guest_status(kvm, &sev_cmd);
6739 case KVM_SEV_DBG_DECRYPT:
6740 r = sev_dbg_crypt(kvm, &sev_cmd, true);
6742 case KVM_SEV_DBG_ENCRYPT:
6743 r = sev_dbg_crypt(kvm, &sev_cmd, false);
6745 case KVM_SEV_LAUNCH_SECRET:
6746 r = sev_launch_secret(kvm, &sev_cmd);
6753 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
6757 mutex_unlock(&kvm->lock);
6761 static int svm_register_enc_region(struct kvm *kvm,
6762 struct kvm_enc_region *range)
6764 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6765 struct enc_region *region;
6768 if (!sev_guest(kvm))
6771 region = kzalloc(sizeof(*region), GFP_KERNEL);
6775 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
6776 if (!region->pages) {
6782 * The guest may change the memory encryption attribute from C=0 -> C=1
6783 * or vice versa for this memory range. Lets make sure caches are
6784 * flushed to ensure that guest data gets written into memory with
6787 sev_clflush_pages(region->pages, region->npages);
6789 region->uaddr = range->addr;
6790 region->size = range->size;
6792 mutex_lock(&kvm->lock);
6793 list_add_tail(®ion->list, &sev->regions_list);
6794 mutex_unlock(&kvm->lock);
6803 static struct enc_region *
6804 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
6806 struct kvm_sev_info *sev = &kvm->arch.sev_info;
6807 struct list_head *head = &sev->regions_list;
6808 struct enc_region *i;
6810 list_for_each_entry(i, head, list) {
6811 if (i->uaddr == range->addr &&
6812 i->size == range->size)
6820 static int svm_unregister_enc_region(struct kvm *kvm,
6821 struct kvm_enc_region *range)
6823 struct enc_region *region;
6826 mutex_lock(&kvm->lock);
6828 if (!sev_guest(kvm)) {
6833 region = find_enc_region(kvm, range);
6839 __unregister_enc_region_locked(kvm, region);
6841 mutex_unlock(&kvm->lock);
6845 mutex_unlock(&kvm->lock);
6849 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
6850 .cpu_has_kvm_support = has_svm,
6851 .disabled_by_bios = is_disabled,
6852 .hardware_setup = svm_hardware_setup,
6853 .hardware_unsetup = svm_hardware_unsetup,
6854 .check_processor_compatibility = svm_check_processor_compat,
6855 .hardware_enable = svm_hardware_enable,
6856 .hardware_disable = svm_hardware_disable,
6857 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
6858 .cpu_has_high_real_mode_segbase = svm_has_high_real_mode_segbase,
6860 .vcpu_create = svm_create_vcpu,
6861 .vcpu_free = svm_free_vcpu,
6862 .vcpu_reset = svm_vcpu_reset,
6864 .vm_init = avic_vm_init,
6865 .vm_destroy = svm_vm_destroy,
6867 .prepare_guest_switch = svm_prepare_guest_switch,
6868 .vcpu_load = svm_vcpu_load,
6869 .vcpu_put = svm_vcpu_put,
6870 .vcpu_blocking = svm_vcpu_blocking,
6871 .vcpu_unblocking = svm_vcpu_unblocking,
6873 .update_bp_intercept = update_bp_intercept,
6874 .get_msr_feature = svm_get_msr_feature,
6875 .get_msr = svm_get_msr,
6876 .set_msr = svm_set_msr,
6877 .get_segment_base = svm_get_segment_base,
6878 .get_segment = svm_get_segment,
6879 .set_segment = svm_set_segment,
6880 .get_cpl = svm_get_cpl,
6881 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
6882 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
6883 .decache_cr3 = svm_decache_cr3,
6884 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
6885 .set_cr0 = svm_set_cr0,
6886 .set_cr3 = svm_set_cr3,
6887 .set_cr4 = svm_set_cr4,
6888 .set_efer = svm_set_efer,
6889 .get_idt = svm_get_idt,
6890 .set_idt = svm_set_idt,
6891 .get_gdt = svm_get_gdt,
6892 .set_gdt = svm_set_gdt,
6893 .get_dr6 = svm_get_dr6,
6894 .set_dr6 = svm_set_dr6,
6895 .set_dr7 = svm_set_dr7,
6896 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
6897 .cache_reg = svm_cache_reg,
6898 .get_rflags = svm_get_rflags,
6899 .set_rflags = svm_set_rflags,
6901 .tlb_flush = svm_flush_tlb,
6903 .run = svm_vcpu_run,
6904 .handle_exit = handle_exit,
6905 .skip_emulated_instruction = skip_emulated_instruction,
6906 .set_interrupt_shadow = svm_set_interrupt_shadow,
6907 .get_interrupt_shadow = svm_get_interrupt_shadow,
6908 .patch_hypercall = svm_patch_hypercall,
6909 .set_irq = svm_set_irq,
6910 .set_nmi = svm_inject_nmi,
6911 .queue_exception = svm_queue_exception,
6912 .cancel_injection = svm_cancel_injection,
6913 .interrupt_allowed = svm_interrupt_allowed,
6914 .nmi_allowed = svm_nmi_allowed,
6915 .get_nmi_mask = svm_get_nmi_mask,
6916 .set_nmi_mask = svm_set_nmi_mask,
6917 .enable_nmi_window = enable_nmi_window,
6918 .enable_irq_window = enable_irq_window,
6919 .update_cr8_intercept = update_cr8_intercept,
6920 .set_virtual_x2apic_mode = svm_set_virtual_x2apic_mode,
6921 .get_enable_apicv = svm_get_enable_apicv,
6922 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
6923 .load_eoi_exitmap = svm_load_eoi_exitmap,
6924 .hwapic_irr_update = svm_hwapic_irr_update,
6925 .hwapic_isr_update = svm_hwapic_isr_update,
6926 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
6927 .apicv_post_state_restore = avic_post_state_restore,
6929 .set_tss_addr = svm_set_tss_addr,
6930 .get_tdp_level = get_npt_level,
6931 .get_mt_mask = svm_get_mt_mask,
6933 .get_exit_info = svm_get_exit_info,
6935 .get_lpage_level = svm_get_lpage_level,
6937 .cpuid_update = svm_cpuid_update,
6939 .rdtscp_supported = svm_rdtscp_supported,
6940 .invpcid_supported = svm_invpcid_supported,
6941 .mpx_supported = svm_mpx_supported,
6942 .xsaves_supported = svm_xsaves_supported,
6943 .umip_emulated = svm_umip_emulated,
6945 .set_supported_cpuid = svm_set_supported_cpuid,
6947 .has_wbinvd_exit = svm_has_wbinvd_exit,
6949 .write_tsc_offset = svm_write_tsc_offset,
6951 .set_tdp_cr3 = set_tdp_cr3,
6953 .check_intercept = svm_check_intercept,
6954 .handle_external_intr = svm_handle_external_intr,
6956 .sched_in = svm_sched_in,
6958 .pmu_ops = &amd_pmu_ops,
6959 .deliver_posted_interrupt = svm_deliver_avic_intr,
6960 .update_pi_irte = svm_update_pi_irte,
6961 .setup_mce = svm_setup_mce,
6963 .smi_allowed = svm_smi_allowed,
6964 .pre_enter_smm = svm_pre_enter_smm,
6965 .pre_leave_smm = svm_pre_leave_smm,
6966 .enable_smi_window = enable_smi_window,
6968 .mem_enc_op = svm_mem_enc_op,
6969 .mem_enc_reg_region = svm_register_enc_region,
6970 .mem_enc_unreg_region = svm_unregister_enc_region,
6973 static int __init svm_init(void)
6975 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
6976 __alignof__(struct vcpu_svm), THIS_MODULE);
6979 static void __exit svm_exit(void)
6984 module_init(svm_init)
6985 module_exit(svm_exit)