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/microcode.h>
53 #include <asm/nospec-branch.h>
55 #include <asm/virtext.h>
58 #define __ex(x) __kvm_handle_fault_on_reboot(x)
60 MODULE_AUTHOR("Qumranet");
61 MODULE_LICENSE("GPL");
63 static const struct x86_cpu_id svm_cpu_id[] = {
64 X86_FEATURE_MATCH(X86_FEATURE_SVM),
67 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
69 #define IOPM_ALLOC_ORDER 2
70 #define MSRPM_ALLOC_ORDER 1
72 #define SEG_TYPE_LDT 2
73 #define SEG_TYPE_BUSY_TSS16 3
75 #define SVM_FEATURE_NPT (1 << 0)
76 #define SVM_FEATURE_LBRV (1 << 1)
77 #define SVM_FEATURE_SVML (1 << 2)
78 #define SVM_FEATURE_NRIP (1 << 3)
79 #define SVM_FEATURE_TSC_RATE (1 << 4)
80 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
81 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
82 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
83 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
85 #define SVM_AVIC_DOORBELL 0xc001011b
87 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
88 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
89 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
91 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
93 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
94 #define TSC_RATIO_MIN 0x0000000000000001ULL
95 #define TSC_RATIO_MAX 0x000000ffffffffffULL
97 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
100 * 0xff is broadcast, so the max index allowed for physical APIC ID
101 * table is 0xfe. APIC IDs above 0xff are reserved.
103 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
105 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
106 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
107 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
109 /* AVIC GATAG is encoded using VM and VCPU IDs */
110 #define AVIC_VCPU_ID_BITS 8
111 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
113 #define AVIC_VM_ID_BITS 24
114 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
115 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
117 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
118 (y & AVIC_VCPU_ID_MASK))
119 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
120 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
122 static bool erratum_383_found __read_mostly;
124 static const u32 host_save_user_msrs[] = {
126 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
129 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
133 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
135 struct kvm_sev_info {
136 bool active; /* SEV enabled guest */
137 unsigned int asid; /* ASID used for this guest */
138 unsigned int handle; /* SEV firmware handle */
139 int fd; /* SEV device fd */
140 unsigned long pages_locked; /* Number of pages locked */
141 struct list_head regions_list; /* List of registered regions */
147 /* Struct members for AVIC */
150 struct page *avic_logical_id_table_page;
151 struct page *avic_physical_id_table_page;
152 struct hlist_node hnode;
154 struct kvm_sev_info sev_info;
159 struct nested_state {
165 /* These are the merged vectors */
168 /* gpa pointers to the real vectors */
172 /* A VMEXIT is required but not yet emulated */
175 /* cache for intercepts of the guest */
178 u32 intercept_exceptions;
181 /* Nested Paging related state */
185 #define MSRPM_OFFSETS 16
186 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
189 * Set osvw_len to higher value when updated Revision Guides
190 * are published and we know what the new status bits are
192 static uint64_t osvw_len = 4, osvw_status;
195 struct kvm_vcpu vcpu;
197 unsigned long vmcb_pa;
198 struct svm_cpu_data *svm_data;
199 uint64_t asid_generation;
200 uint64_t sysenter_esp;
201 uint64_t sysenter_eip;
208 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
222 struct nested_state nested;
225 u64 nmi_singlestep_guest_rflags;
227 unsigned int3_injected;
228 unsigned long int3_rip;
230 /* cached guest cpuid flags for faster access */
231 bool nrips_enabled : 1;
234 struct page *avic_backing_page;
235 u64 *avic_physical_id_cache;
236 bool avic_is_running;
239 * Per-vcpu list of struct amd_svm_iommu_ir:
240 * This is used mainly to store interrupt remapping information used
241 * when update the vcpu affinity. This avoids the need to scan for
242 * IRTE and try to match ga_tag in the IOMMU driver.
244 struct list_head ir_list;
245 spinlock_t ir_list_lock;
247 /* which host CPU was used for running this vcpu */
248 unsigned int last_cpu;
252 * This is a wrapper of struct amd_iommu_ir_data.
254 struct amd_svm_iommu_ir {
255 struct list_head node; /* Used by SVM for per-vcpu ir_list */
256 void *data; /* Storing pointer to struct amd_ir_data */
259 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
260 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
262 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
263 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
264 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
265 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
267 static DEFINE_PER_CPU(u64, current_tsc_ratio);
268 #define TSC_RATIO_DEFAULT 0x0100000000ULL
270 #define MSR_INVALID 0xffffffffU
272 static const struct svm_direct_access_msrs {
273 u32 index; /* Index of the MSR */
274 bool always; /* True if intercept is always on */
275 } direct_access_msrs[] = {
276 { .index = MSR_STAR, .always = true },
277 { .index = MSR_IA32_SYSENTER_CS, .always = true },
279 { .index = MSR_GS_BASE, .always = true },
280 { .index = MSR_FS_BASE, .always = true },
281 { .index = MSR_KERNEL_GS_BASE, .always = true },
282 { .index = MSR_LSTAR, .always = true },
283 { .index = MSR_CSTAR, .always = true },
284 { .index = MSR_SYSCALL_MASK, .always = true },
286 { .index = MSR_IA32_SPEC_CTRL, .always = false },
287 { .index = MSR_IA32_PRED_CMD, .always = false },
288 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
289 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
290 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
291 { .index = MSR_IA32_LASTINTTOIP, .always = false },
292 { .index = MSR_INVALID, .always = false },
295 /* enable NPT for AMD64 and X86 with PAE */
296 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
297 static bool npt_enabled = true;
299 static bool npt_enabled;
302 /* allow nested paging (virtualized MMU) for all guests */
303 static int npt = true;
304 module_param(npt, int, S_IRUGO);
306 /* allow nested virtualization in KVM/SVM */
307 static int nested = true;
308 module_param(nested, int, S_IRUGO);
310 /* enable / disable AVIC */
312 #ifdef CONFIG_X86_LOCAL_APIC
313 module_param(avic, int, S_IRUGO);
316 /* enable/disable Virtual VMLOAD VMSAVE */
317 static int vls = true;
318 module_param(vls, int, 0444);
320 /* enable/disable Virtual GIF */
321 static int vgif = true;
322 module_param(vgif, int, 0444);
324 /* enable/disable SEV support */
325 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
326 module_param(sev, int, 0444);
328 static u8 rsm_ins_bytes[] = "\x0f\xaa";
330 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
331 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
332 static void svm_complete_interrupts(struct vcpu_svm *svm);
334 static int nested_svm_exit_handled(struct vcpu_svm *svm);
335 static int nested_svm_intercept(struct vcpu_svm *svm);
336 static int nested_svm_vmexit(struct vcpu_svm *svm);
337 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
338 bool has_error_code, u32 error_code);
341 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
342 pause filter count */
343 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
344 VMCB_ASID, /* ASID */
345 VMCB_INTR, /* int_ctl, int_vector */
346 VMCB_NPT, /* npt_en, nCR3, gPAT */
347 VMCB_CR, /* CR0, CR3, CR4, EFER */
348 VMCB_DR, /* DR6, DR7 */
349 VMCB_DT, /* GDT, IDT */
350 VMCB_SEG, /* CS, DS, SS, ES, CPL */
351 VMCB_CR2, /* CR2 only */
352 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
353 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
354 * AVIC PHYSICAL_TABLE pointer,
355 * AVIC LOGICAL_TABLE pointer
360 /* TPR and CR2 are always written before VMRUN */
361 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
363 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
365 static unsigned int max_sev_asid;
366 static unsigned int min_sev_asid;
367 static unsigned long *sev_asid_bitmap;
368 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
371 struct list_head list;
372 unsigned long npages;
379 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
381 return container_of(kvm, struct kvm_svm, kvm);
384 static inline bool svm_sev_enabled(void)
389 static inline bool sev_guest(struct kvm *kvm)
391 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
396 static inline int sev_get_asid(struct kvm *kvm)
398 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
403 static inline void mark_all_dirty(struct vmcb *vmcb)
405 vmcb->control.clean = 0;
408 static inline void mark_all_clean(struct vmcb *vmcb)
410 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
411 & ~VMCB_ALWAYS_DIRTY_MASK;
414 static inline void mark_dirty(struct vmcb *vmcb, int bit)
416 vmcb->control.clean &= ~(1 << bit);
419 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
421 return container_of(vcpu, struct vcpu_svm, vcpu);
424 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
426 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
427 mark_dirty(svm->vmcb, VMCB_AVIC);
430 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
432 struct vcpu_svm *svm = to_svm(vcpu);
433 u64 *entry = svm->avic_physical_id_cache;
438 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
441 static void recalc_intercepts(struct vcpu_svm *svm)
443 struct vmcb_control_area *c, *h;
444 struct nested_state *g;
446 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
448 if (!is_guest_mode(&svm->vcpu))
451 c = &svm->vmcb->control;
452 h = &svm->nested.hsave->control;
455 c->intercept_cr = h->intercept_cr | g->intercept_cr;
456 c->intercept_dr = h->intercept_dr | g->intercept_dr;
457 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
458 c->intercept = h->intercept | g->intercept;
461 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
463 if (is_guest_mode(&svm->vcpu))
464 return svm->nested.hsave;
469 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
471 struct vmcb *vmcb = get_host_vmcb(svm);
473 vmcb->control.intercept_cr |= (1U << bit);
475 recalc_intercepts(svm);
478 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
480 struct vmcb *vmcb = get_host_vmcb(svm);
482 vmcb->control.intercept_cr &= ~(1U << bit);
484 recalc_intercepts(svm);
487 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
489 struct vmcb *vmcb = get_host_vmcb(svm);
491 return vmcb->control.intercept_cr & (1U << bit);
494 static inline void set_dr_intercepts(struct vcpu_svm *svm)
496 struct vmcb *vmcb = get_host_vmcb(svm);
498 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
499 | (1 << INTERCEPT_DR1_READ)
500 | (1 << INTERCEPT_DR2_READ)
501 | (1 << INTERCEPT_DR3_READ)
502 | (1 << INTERCEPT_DR4_READ)
503 | (1 << INTERCEPT_DR5_READ)
504 | (1 << INTERCEPT_DR6_READ)
505 | (1 << INTERCEPT_DR7_READ)
506 | (1 << INTERCEPT_DR0_WRITE)
507 | (1 << INTERCEPT_DR1_WRITE)
508 | (1 << INTERCEPT_DR2_WRITE)
509 | (1 << INTERCEPT_DR3_WRITE)
510 | (1 << INTERCEPT_DR4_WRITE)
511 | (1 << INTERCEPT_DR5_WRITE)
512 | (1 << INTERCEPT_DR6_WRITE)
513 | (1 << INTERCEPT_DR7_WRITE);
515 recalc_intercepts(svm);
518 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
520 struct vmcb *vmcb = get_host_vmcb(svm);
522 vmcb->control.intercept_dr = 0;
524 recalc_intercepts(svm);
527 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
529 struct vmcb *vmcb = get_host_vmcb(svm);
531 vmcb->control.intercept_exceptions |= (1U << bit);
533 recalc_intercepts(svm);
536 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
538 struct vmcb *vmcb = get_host_vmcb(svm);
540 vmcb->control.intercept_exceptions &= ~(1U << bit);
542 recalc_intercepts(svm);
545 static inline void set_intercept(struct vcpu_svm *svm, int bit)
547 struct vmcb *vmcb = get_host_vmcb(svm);
549 vmcb->control.intercept |= (1ULL << bit);
551 recalc_intercepts(svm);
554 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
556 struct vmcb *vmcb = get_host_vmcb(svm);
558 vmcb->control.intercept &= ~(1ULL << bit);
560 recalc_intercepts(svm);
563 static inline bool vgif_enabled(struct vcpu_svm *svm)
565 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
568 static inline void enable_gif(struct vcpu_svm *svm)
570 if (vgif_enabled(svm))
571 svm->vmcb->control.int_ctl |= V_GIF_MASK;
573 svm->vcpu.arch.hflags |= HF_GIF_MASK;
576 static inline void disable_gif(struct vcpu_svm *svm)
578 if (vgif_enabled(svm))
579 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
581 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
584 static inline bool gif_set(struct vcpu_svm *svm)
586 if (vgif_enabled(svm))
587 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
589 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
592 static unsigned long iopm_base;
594 struct kvm_ldttss_desc {
597 unsigned base1:8, type:5, dpl:2, p:1;
598 unsigned limit1:4, zero0:3, g:1, base2:8;
601 } __attribute__((packed));
603 struct svm_cpu_data {
610 struct kvm_ldttss_desc *tss_desc;
612 struct page *save_area;
613 struct vmcb *current_vmcb;
615 /* index = sev_asid, value = vmcb pointer */
616 struct vmcb **sev_vmcbs;
619 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
621 struct svm_init_data {
626 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
628 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
629 #define MSRS_RANGE_SIZE 2048
630 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
632 static u32 svm_msrpm_offset(u32 msr)
637 for (i = 0; i < NUM_MSR_MAPS; i++) {
638 if (msr < msrpm_ranges[i] ||
639 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
642 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
643 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
645 /* Now we have the u8 offset - but need the u32 offset */
649 /* MSR not in any range */
653 #define MAX_INST_SIZE 15
655 static inline void clgi(void)
657 asm volatile (__ex(SVM_CLGI));
660 static inline void stgi(void)
662 asm volatile (__ex(SVM_STGI));
665 static inline void invlpga(unsigned long addr, u32 asid)
667 asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
670 static int get_npt_level(struct kvm_vcpu *vcpu)
673 return PT64_ROOT_4LEVEL;
675 return PT32E_ROOT_LEVEL;
679 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
681 vcpu->arch.efer = efer;
682 if (!npt_enabled && !(efer & EFER_LMA))
685 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
686 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
689 static int is_external_interrupt(u32 info)
691 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
692 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
695 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
697 struct vcpu_svm *svm = to_svm(vcpu);
700 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
701 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
705 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
707 struct vcpu_svm *svm = to_svm(vcpu);
710 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
712 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
716 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
718 struct vcpu_svm *svm = to_svm(vcpu);
720 if (svm->vmcb->control.next_rip != 0) {
721 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
722 svm->next_rip = svm->vmcb->control.next_rip;
725 if (!svm->next_rip) {
726 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
728 printk(KERN_DEBUG "%s: NOP\n", __func__);
731 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
732 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
733 __func__, kvm_rip_read(vcpu), svm->next_rip);
735 kvm_rip_write(vcpu, svm->next_rip);
736 svm_set_interrupt_shadow(vcpu, 0);
739 static void svm_queue_exception(struct kvm_vcpu *vcpu)
741 struct vcpu_svm *svm = to_svm(vcpu);
742 unsigned nr = vcpu->arch.exception.nr;
743 bool has_error_code = vcpu->arch.exception.has_error_code;
744 bool reinject = vcpu->arch.exception.injected;
745 u32 error_code = vcpu->arch.exception.error_code;
748 * If we are within a nested VM we'd better #VMEXIT and let the guest
749 * handle the exception
752 nested_svm_check_exception(svm, nr, has_error_code, error_code))
755 if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
756 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
759 * For guest debugging where we have to reinject #BP if some
760 * INT3 is guest-owned:
761 * Emulate nRIP by moving RIP forward. Will fail if injection
762 * raises a fault that is not intercepted. Still better than
763 * failing in all cases.
765 skip_emulated_instruction(&svm->vcpu);
766 rip = kvm_rip_read(&svm->vcpu);
767 svm->int3_rip = rip + svm->vmcb->save.cs.base;
768 svm->int3_injected = rip - old_rip;
771 svm->vmcb->control.event_inj = nr
773 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
774 | SVM_EVTINJ_TYPE_EXEPT;
775 svm->vmcb->control.event_inj_err = error_code;
778 static void svm_init_erratum_383(void)
784 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
787 /* Use _safe variants to not break nested virtualization */
788 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
794 low = lower_32_bits(val);
795 high = upper_32_bits(val);
797 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
799 erratum_383_found = true;
802 static void svm_init_osvw(struct kvm_vcpu *vcpu)
805 * Guests should see errata 400 and 415 as fixed (assuming that
806 * HLT and IO instructions are intercepted).
808 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
809 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
812 * By increasing VCPU's osvw.length to 3 we are telling the guest that
813 * all osvw.status bits inside that length, including bit 0 (which is
814 * reserved for erratum 298), are valid. However, if host processor's
815 * osvw_len is 0 then osvw_status[0] carries no information. We need to
816 * be conservative here and therefore we tell the guest that erratum 298
817 * is present (because we really don't know).
819 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
820 vcpu->arch.osvw.status |= 1;
823 static int has_svm(void)
827 if (!cpu_has_svm(&msg)) {
828 printk(KERN_INFO "has_svm: %s\n", msg);
835 static void svm_hardware_disable(void)
837 /* Make sure we clean up behind us */
838 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
839 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
843 amd_pmu_disable_virt();
846 static int svm_hardware_enable(void)
849 struct svm_cpu_data *sd;
851 struct desc_struct *gdt;
852 int me = raw_smp_processor_id();
854 rdmsrl(MSR_EFER, efer);
855 if (efer & EFER_SVME)
859 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
862 sd = per_cpu(svm_data, me);
864 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
868 sd->asid_generation = 1;
869 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
870 sd->next_asid = sd->max_asid + 1;
871 sd->min_asid = max_sev_asid + 1;
873 gdt = get_current_gdt_rw();
874 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
876 wrmsrl(MSR_EFER, efer | EFER_SVME);
878 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
880 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
881 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
882 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
889 * Note that it is possible to have a system with mixed processor
890 * revisions and therefore different OSVW bits. If bits are not the same
891 * on different processors then choose the worst case (i.e. if erratum
892 * is present on one processor and not on another then assume that the
893 * erratum is present everywhere).
895 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
896 uint64_t len, status = 0;
899 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
901 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
905 osvw_status = osvw_len = 0;
909 osvw_status |= status;
910 osvw_status &= (1ULL << osvw_len) - 1;
913 osvw_status = osvw_len = 0;
915 svm_init_erratum_383();
917 amd_pmu_enable_virt();
922 static void svm_cpu_uninit(int cpu)
924 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
929 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
930 kfree(sd->sev_vmcbs);
931 __free_page(sd->save_area);
935 static int svm_cpu_init(int cpu)
937 struct svm_cpu_data *sd;
940 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
945 sd->save_area = alloc_page(GFP_KERNEL);
949 if (svm_sev_enabled()) {
951 sd->sev_vmcbs = kmalloc((max_sev_asid + 1) * sizeof(void *), GFP_KERNEL);
956 per_cpu(svm_data, cpu) = sd;
966 static bool valid_msr_intercept(u32 index)
970 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
971 if (direct_access_msrs[i].index == index)
977 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
984 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
987 offset = svm_msrpm_offset(msr);
988 bit_write = 2 * (msr & 0x0f) + 1;
991 BUG_ON(offset == MSR_INVALID);
993 return !!test_bit(bit_write, &tmp);
996 static void set_msr_interception(u32 *msrpm, unsigned msr,
999 u8 bit_read, bit_write;
1004 * If this warning triggers extend the direct_access_msrs list at the
1005 * beginning of the file
1007 WARN_ON(!valid_msr_intercept(msr));
1009 offset = svm_msrpm_offset(msr);
1010 bit_read = 2 * (msr & 0x0f);
1011 bit_write = 2 * (msr & 0x0f) + 1;
1012 tmp = msrpm[offset];
1014 BUG_ON(offset == MSR_INVALID);
1016 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
1017 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1019 msrpm[offset] = tmp;
1022 static void svm_vcpu_init_msrpm(u32 *msrpm)
1026 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1028 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1029 if (!direct_access_msrs[i].always)
1032 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1036 static void add_msr_offset(u32 offset)
1040 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1042 /* Offset already in list? */
1043 if (msrpm_offsets[i] == offset)
1046 /* Slot used by another offset? */
1047 if (msrpm_offsets[i] != MSR_INVALID)
1050 /* Add offset to list */
1051 msrpm_offsets[i] = offset;
1057 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1058 * increase MSRPM_OFFSETS in this case.
1063 static void init_msrpm_offsets(void)
1067 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1069 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1072 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1073 BUG_ON(offset == MSR_INVALID);
1075 add_msr_offset(offset);
1079 static void svm_enable_lbrv(struct vcpu_svm *svm)
1081 u32 *msrpm = svm->msrpm;
1083 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1084 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1085 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1086 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1087 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1090 static void svm_disable_lbrv(struct vcpu_svm *svm)
1092 u32 *msrpm = svm->msrpm;
1094 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1095 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1096 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1097 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1098 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1101 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1103 svm->nmi_singlestep = false;
1105 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1106 /* Clear our flags if they were not set by the guest */
1107 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1108 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1109 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1110 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1115 * This hash table is used to map VM_ID to a struct kvm_svm,
1116 * when handling AMD IOMMU GALOG notification to schedule in
1117 * a particular vCPU.
1119 #define SVM_VM_DATA_HASH_BITS 8
1120 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1121 static u32 next_vm_id = 0;
1122 static bool next_vm_id_wrapped = 0;
1123 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1126 * This function is called from IOMMU driver to notify
1127 * SVM to schedule in a particular vCPU of a particular VM.
1129 static int avic_ga_log_notifier(u32 ga_tag)
1131 unsigned long flags;
1132 struct kvm_svm *kvm_svm;
1133 struct kvm_vcpu *vcpu = NULL;
1134 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1135 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1137 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1139 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1140 hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1141 if (kvm_svm->avic_vm_id != vm_id)
1143 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1146 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1149 * At this point, the IOMMU should have already set the pending
1150 * bit in the vAPIC backing page. So, we just need to schedule
1154 kvm_vcpu_wake_up(vcpu);
1159 static __init int sev_hardware_setup(void)
1161 struct sev_user_data_status *status;
1164 /* Maximum number of encrypted guests supported simultaneously */
1165 max_sev_asid = cpuid_ecx(0x8000001F);
1170 /* Minimum ASID value that should be used for SEV guest */
1171 min_sev_asid = cpuid_edx(0x8000001F);
1173 /* Initialize SEV ASID bitmap */
1174 sev_asid_bitmap = kcalloc(BITS_TO_LONGS(max_sev_asid),
1175 sizeof(unsigned long), GFP_KERNEL);
1176 if (!sev_asid_bitmap)
1179 status = kmalloc(sizeof(*status), GFP_KERNEL);
1184 * Check SEV platform status.
1186 * PLATFORM_STATUS can be called in any state, if we failed to query
1187 * the PLATFORM status then either PSP firmware does not support SEV
1188 * feature or SEV firmware is dead.
1190 rc = sev_platform_status(status, NULL);
1194 pr_info("SEV supported\n");
1201 static __init int svm_hardware_setup(void)
1204 struct page *iopm_pages;
1208 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1213 iopm_va = page_address(iopm_pages);
1214 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1215 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1217 init_msrpm_offsets();
1219 if (boot_cpu_has(X86_FEATURE_NX))
1220 kvm_enable_efer_bits(EFER_NX);
1222 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1223 kvm_enable_efer_bits(EFER_FFXSR);
1225 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1226 kvm_has_tsc_control = true;
1227 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1228 kvm_tsc_scaling_ratio_frac_bits = 32;
1232 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1233 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1237 if (boot_cpu_has(X86_FEATURE_SEV) &&
1238 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1239 r = sev_hardware_setup();
1247 for_each_possible_cpu(cpu) {
1248 r = svm_cpu_init(cpu);
1253 if (!boot_cpu_has(X86_FEATURE_NPT))
1254 npt_enabled = false;
1256 if (npt_enabled && !npt) {
1257 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1258 npt_enabled = false;
1262 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1269 !boot_cpu_has(X86_FEATURE_AVIC) ||
1270 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1273 pr_info("AVIC enabled\n");
1275 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1281 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1282 !IS_ENABLED(CONFIG_X86_64)) {
1285 pr_info("Virtual VMLOAD VMSAVE supported\n");
1290 if (!boot_cpu_has(X86_FEATURE_VGIF))
1293 pr_info("Virtual GIF supported\n");
1299 __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1304 static __exit void svm_hardware_unsetup(void)
1308 if (svm_sev_enabled())
1309 kfree(sev_asid_bitmap);
1311 for_each_possible_cpu(cpu)
1312 svm_cpu_uninit(cpu);
1314 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1318 static void init_seg(struct vmcb_seg *seg)
1321 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1322 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1323 seg->limit = 0xffff;
1327 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1330 seg->attrib = SVM_SELECTOR_P_MASK | type;
1331 seg->limit = 0xffff;
1335 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1337 struct vcpu_svm *svm = to_svm(vcpu);
1338 u64 g_tsc_offset = 0;
1340 if (is_guest_mode(vcpu)) {
1341 g_tsc_offset = svm->vmcb->control.tsc_offset -
1342 svm->nested.hsave->control.tsc_offset;
1343 svm->nested.hsave->control.tsc_offset = offset;
1345 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1346 svm->vmcb->control.tsc_offset,
1349 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1351 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1354 static void avic_init_vmcb(struct vcpu_svm *svm)
1356 struct vmcb *vmcb = svm->vmcb;
1357 struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1358 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1359 phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1360 phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1362 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1363 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1364 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1365 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1366 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1369 static void init_vmcb(struct vcpu_svm *svm)
1371 struct vmcb_control_area *control = &svm->vmcb->control;
1372 struct vmcb_save_area *save = &svm->vmcb->save;
1374 svm->vcpu.arch.hflags = 0;
1376 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1377 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1378 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1379 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1380 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1381 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1382 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1383 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1385 set_dr_intercepts(svm);
1387 set_exception_intercept(svm, PF_VECTOR);
1388 set_exception_intercept(svm, UD_VECTOR);
1389 set_exception_intercept(svm, MC_VECTOR);
1390 set_exception_intercept(svm, AC_VECTOR);
1391 set_exception_intercept(svm, DB_VECTOR);
1393 * Guest access to VMware backdoor ports could legitimately
1394 * trigger #GP because of TSS I/O permission bitmap.
1395 * We intercept those #GP and allow access to them anyway
1398 if (enable_vmware_backdoor)
1399 set_exception_intercept(svm, GP_VECTOR);
1401 set_intercept(svm, INTERCEPT_INTR);
1402 set_intercept(svm, INTERCEPT_NMI);
1403 set_intercept(svm, INTERCEPT_SMI);
1404 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1405 set_intercept(svm, INTERCEPT_RDPMC);
1406 set_intercept(svm, INTERCEPT_CPUID);
1407 set_intercept(svm, INTERCEPT_INVD);
1408 set_intercept(svm, INTERCEPT_INVLPG);
1409 set_intercept(svm, INTERCEPT_INVLPGA);
1410 set_intercept(svm, INTERCEPT_IOIO_PROT);
1411 set_intercept(svm, INTERCEPT_MSR_PROT);
1412 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1413 set_intercept(svm, INTERCEPT_SHUTDOWN);
1414 set_intercept(svm, INTERCEPT_VMRUN);
1415 set_intercept(svm, INTERCEPT_VMMCALL);
1416 set_intercept(svm, INTERCEPT_VMLOAD);
1417 set_intercept(svm, INTERCEPT_VMSAVE);
1418 set_intercept(svm, INTERCEPT_STGI);
1419 set_intercept(svm, INTERCEPT_CLGI);
1420 set_intercept(svm, INTERCEPT_SKINIT);
1421 set_intercept(svm, INTERCEPT_WBINVD);
1422 set_intercept(svm, INTERCEPT_XSETBV);
1423 set_intercept(svm, INTERCEPT_RSM);
1425 if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1426 set_intercept(svm, INTERCEPT_MONITOR);
1427 set_intercept(svm, INTERCEPT_MWAIT);
1430 if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1431 set_intercept(svm, INTERCEPT_HLT);
1433 control->iopm_base_pa = __sme_set(iopm_base);
1434 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1435 control->int_ctl = V_INTR_MASKING_MASK;
1437 init_seg(&save->es);
1438 init_seg(&save->ss);
1439 init_seg(&save->ds);
1440 init_seg(&save->fs);
1441 init_seg(&save->gs);
1443 save->cs.selector = 0xf000;
1444 save->cs.base = 0xffff0000;
1445 /* Executable/Readable Code Segment */
1446 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1447 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1448 save->cs.limit = 0xffff;
1450 save->gdtr.limit = 0xffff;
1451 save->idtr.limit = 0xffff;
1453 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1454 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1456 svm_set_efer(&svm->vcpu, 0);
1457 save->dr6 = 0xffff0ff0;
1458 kvm_set_rflags(&svm->vcpu, 2);
1459 save->rip = 0x0000fff0;
1460 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1463 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1464 * It also updates the guest-visible cr0 value.
1466 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1467 kvm_mmu_reset_context(&svm->vcpu);
1469 save->cr4 = X86_CR4_PAE;
1473 /* Setup VMCB for Nested Paging */
1474 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1475 clr_intercept(svm, INTERCEPT_INVLPG);
1476 clr_exception_intercept(svm, PF_VECTOR);
1477 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1478 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1479 save->g_pat = svm->vcpu.arch.pat;
1483 svm->asid_generation = 0;
1485 svm->nested.vmcb = 0;
1486 svm->vcpu.arch.hflags = 0;
1488 if (boot_cpu_has(X86_FEATURE_PAUSEFILTER) &&
1489 !kvm_pause_in_guest(svm->vcpu.kvm)) {
1490 control->pause_filter_count = 3000;
1491 set_intercept(svm, INTERCEPT_PAUSE);
1494 if (kvm_vcpu_apicv_active(&svm->vcpu))
1495 avic_init_vmcb(svm);
1498 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1499 * in VMCB and clear intercepts to avoid #VMEXIT.
1502 clr_intercept(svm, INTERCEPT_VMLOAD);
1503 clr_intercept(svm, INTERCEPT_VMSAVE);
1504 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1508 clr_intercept(svm, INTERCEPT_STGI);
1509 clr_intercept(svm, INTERCEPT_CLGI);
1510 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1513 if (sev_guest(svm->vcpu.kvm)) {
1514 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1515 clr_exception_intercept(svm, UD_VECTOR);
1518 mark_all_dirty(svm->vmcb);
1524 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1527 u64 *avic_physical_id_table;
1528 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1530 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1533 avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1535 return &avic_physical_id_table[index];
1540 * AVIC hardware walks the nested page table to check permissions,
1541 * but does not use the SPA address specified in the leaf page
1542 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1543 * field of the VMCB. Therefore, we set up the
1544 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1546 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1548 struct kvm *kvm = vcpu->kvm;
1551 if (kvm->arch.apic_access_page_done)
1554 ret = x86_set_memory_region(kvm,
1555 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1556 APIC_DEFAULT_PHYS_BASE,
1561 kvm->arch.apic_access_page_done = true;
1565 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1568 u64 *entry, new_entry;
1569 int id = vcpu->vcpu_id;
1570 struct vcpu_svm *svm = to_svm(vcpu);
1572 ret = avic_init_access_page(vcpu);
1576 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1579 if (!svm->vcpu.arch.apic->regs)
1582 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1584 /* Setting AVIC backing page address in the phy APIC ID table */
1585 entry = avic_get_physical_id_entry(vcpu, id);
1589 new_entry = READ_ONCE(*entry);
1590 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1591 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1592 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1593 WRITE_ONCE(*entry, new_entry);
1595 svm->avic_physical_id_cache = entry;
1600 static void __sev_asid_free(int asid)
1602 struct svm_cpu_data *sd;
1606 clear_bit(pos, sev_asid_bitmap);
1608 for_each_possible_cpu(cpu) {
1609 sd = per_cpu(svm_data, cpu);
1610 sd->sev_vmcbs[pos] = NULL;
1614 static void sev_asid_free(struct kvm *kvm)
1616 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1618 __sev_asid_free(sev->asid);
1621 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1623 struct sev_data_decommission *decommission;
1624 struct sev_data_deactivate *data;
1629 data = kzalloc(sizeof(*data), GFP_KERNEL);
1633 /* deactivate handle */
1634 data->handle = handle;
1635 sev_guest_deactivate(data, NULL);
1637 wbinvd_on_all_cpus();
1638 sev_guest_df_flush(NULL);
1641 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1645 /* decommission handle */
1646 decommission->handle = handle;
1647 sev_guest_decommission(decommission, NULL);
1649 kfree(decommission);
1652 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1653 unsigned long ulen, unsigned long *n,
1656 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1657 unsigned long npages, npinned, size;
1658 unsigned long locked, lock_limit;
1659 struct page **pages;
1662 /* Calculate number of pages. */
1663 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1664 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1665 npages = (last - first + 1);
1667 locked = sev->pages_locked + npages;
1668 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1669 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1670 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1674 /* Avoid using vmalloc for smaller buffers. */
1675 size = npages * sizeof(struct page *);
1676 if (size > PAGE_SIZE)
1677 pages = vmalloc(size);
1679 pages = kmalloc(size, GFP_KERNEL);
1684 /* Pin the user virtual address. */
1685 npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1686 if (npinned != npages) {
1687 pr_err("SEV: Failure locking %lu pages.\n", npages);
1692 sev->pages_locked = locked;
1698 release_pages(pages, npinned);
1704 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1705 unsigned long npages)
1707 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1709 release_pages(pages, npages);
1711 sev->pages_locked -= npages;
1714 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1716 uint8_t *page_virtual;
1719 if (npages == 0 || pages == NULL)
1722 for (i = 0; i < npages; i++) {
1723 page_virtual = kmap_atomic(pages[i]);
1724 clflush_cache_range(page_virtual, PAGE_SIZE);
1725 kunmap_atomic(page_virtual);
1729 static void __unregister_enc_region_locked(struct kvm *kvm,
1730 struct enc_region *region)
1733 * The guest may change the memory encryption attribute from C=0 -> C=1
1734 * or vice versa for this memory range. Lets make sure caches are
1735 * flushed to ensure that guest data gets written into memory with
1738 sev_clflush_pages(region->pages, region->npages);
1740 sev_unpin_memory(kvm, region->pages, region->npages);
1741 list_del(®ion->list);
1745 static struct kvm *svm_vm_alloc(void)
1747 struct kvm_svm *kvm_svm = kzalloc(sizeof(struct kvm_svm), GFP_KERNEL);
1748 return &kvm_svm->kvm;
1751 static void svm_vm_free(struct kvm *kvm)
1753 kfree(to_kvm_svm(kvm));
1756 static void sev_vm_destroy(struct kvm *kvm)
1758 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1759 struct list_head *head = &sev->regions_list;
1760 struct list_head *pos, *q;
1762 if (!sev_guest(kvm))
1765 mutex_lock(&kvm->lock);
1768 * if userspace was terminated before unregistering the memory regions
1769 * then lets unpin all the registered memory.
1771 if (!list_empty(head)) {
1772 list_for_each_safe(pos, q, head) {
1773 __unregister_enc_region_locked(kvm,
1774 list_entry(pos, struct enc_region, list));
1778 mutex_unlock(&kvm->lock);
1780 sev_unbind_asid(kvm, sev->handle);
1784 static void avic_vm_destroy(struct kvm *kvm)
1786 unsigned long flags;
1787 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1792 if (kvm_svm->avic_logical_id_table_page)
1793 __free_page(kvm_svm->avic_logical_id_table_page);
1794 if (kvm_svm->avic_physical_id_table_page)
1795 __free_page(kvm_svm->avic_physical_id_table_page);
1797 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1798 hash_del(&kvm_svm->hnode);
1799 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1802 static void svm_vm_destroy(struct kvm *kvm)
1804 avic_vm_destroy(kvm);
1805 sev_vm_destroy(kvm);
1808 static int avic_vm_init(struct kvm *kvm)
1810 unsigned long flags;
1812 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1814 struct page *p_page;
1815 struct page *l_page;
1821 /* Allocating physical APIC ID table (4KB) */
1822 p_page = alloc_page(GFP_KERNEL);
1826 kvm_svm->avic_physical_id_table_page = p_page;
1827 clear_page(page_address(p_page));
1829 /* Allocating logical APIC ID table (4KB) */
1830 l_page = alloc_page(GFP_KERNEL);
1834 kvm_svm->avic_logical_id_table_page = l_page;
1835 clear_page(page_address(l_page));
1837 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1839 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1840 if (vm_id == 0) { /* id is 1-based, zero is not okay */
1841 next_vm_id_wrapped = 1;
1844 /* Is it still in use? Only possible if wrapped at least once */
1845 if (next_vm_id_wrapped) {
1846 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
1847 if (k2->avic_vm_id == vm_id)
1851 kvm_svm->avic_vm_id = vm_id;
1852 hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
1853 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1858 avic_vm_destroy(kvm);
1863 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1866 unsigned long flags;
1867 struct amd_svm_iommu_ir *ir;
1868 struct vcpu_svm *svm = to_svm(vcpu);
1870 if (!kvm_arch_has_assigned_device(vcpu->kvm))
1874 * Here, we go through the per-vcpu ir_list to update all existing
1875 * interrupt remapping table entry targeting this vcpu.
1877 spin_lock_irqsave(&svm->ir_list_lock, flags);
1879 if (list_empty(&svm->ir_list))
1882 list_for_each_entry(ir, &svm->ir_list, node) {
1883 ret = amd_iommu_update_ga(cpu, r, ir->data);
1888 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1892 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1895 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
1896 int h_physical_id = kvm_cpu_get_apicid(cpu);
1897 struct vcpu_svm *svm = to_svm(vcpu);
1899 if (!kvm_vcpu_apicv_active(vcpu))
1902 if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
1905 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1906 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1908 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1909 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1911 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1912 if (svm->avic_is_running)
1913 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1915 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1916 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
1917 svm->avic_is_running);
1920 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
1923 struct vcpu_svm *svm = to_svm(vcpu);
1925 if (!kvm_vcpu_apicv_active(vcpu))
1928 entry = READ_ONCE(*(svm->avic_physical_id_cache));
1929 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
1930 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1932 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1933 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1937 * This function is called during VCPU halt/unhalt.
1939 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
1941 struct vcpu_svm *svm = to_svm(vcpu);
1943 svm->avic_is_running = is_run;
1945 avic_vcpu_load(vcpu, vcpu->cpu);
1947 avic_vcpu_put(vcpu);
1950 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1952 struct vcpu_svm *svm = to_svm(vcpu);
1956 vcpu->arch.microcode_version = 0x01000065;
1960 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1961 MSR_IA32_APICBASE_ENABLE;
1962 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1963 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1967 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
1968 kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1970 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
1971 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
1974 static int avic_init_vcpu(struct vcpu_svm *svm)
1978 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1981 ret = avic_init_backing_page(&svm->vcpu);
1985 INIT_LIST_HEAD(&svm->ir_list);
1986 spin_lock_init(&svm->ir_list_lock);
1991 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1993 struct vcpu_svm *svm;
1995 struct page *msrpm_pages;
1996 struct page *hsave_page;
1997 struct page *nested_msrpm_pages;
2000 svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
2006 err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2011 page = alloc_page(GFP_KERNEL);
2015 msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2019 nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
2020 if (!nested_msrpm_pages)
2023 hsave_page = alloc_page(GFP_KERNEL);
2027 err = avic_init_vcpu(svm);
2031 /* We initialize this flag to true to make sure that the is_running
2032 * bit would be set the first time the vcpu is loaded.
2034 svm->avic_is_running = true;
2036 svm->nested.hsave = page_address(hsave_page);
2038 svm->msrpm = page_address(msrpm_pages);
2039 svm_vcpu_init_msrpm(svm->msrpm);
2041 svm->nested.msrpm = page_address(nested_msrpm_pages);
2042 svm_vcpu_init_msrpm(svm->nested.msrpm);
2044 svm->vmcb = page_address(page);
2045 clear_page(svm->vmcb);
2046 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2047 svm->asid_generation = 0;
2050 svm_init_osvw(&svm->vcpu);
2055 __free_page(hsave_page);
2057 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2059 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2063 kvm_vcpu_uninit(&svm->vcpu);
2065 kmem_cache_free(kvm_vcpu_cache, svm);
2067 return ERR_PTR(err);
2070 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2072 struct vcpu_svm *svm = to_svm(vcpu);
2074 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2075 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2076 __free_page(virt_to_page(svm->nested.hsave));
2077 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2078 kvm_vcpu_uninit(vcpu);
2079 kmem_cache_free(kvm_vcpu_cache, svm);
2081 * The vmcb page can be recycled, causing a false negative in
2082 * svm_vcpu_load(). So do a full IBPB now.
2084 indirect_branch_prediction_barrier();
2087 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2089 struct vcpu_svm *svm = to_svm(vcpu);
2090 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2093 if (unlikely(cpu != vcpu->cpu)) {
2094 svm->asid_generation = 0;
2095 mark_all_dirty(svm->vmcb);
2098 #ifdef CONFIG_X86_64
2099 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2101 savesegment(fs, svm->host.fs);
2102 savesegment(gs, svm->host.gs);
2103 svm->host.ldt = kvm_read_ldt();
2105 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2106 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2108 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2109 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2110 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2111 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2112 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2115 /* This assumes that the kernel never uses MSR_TSC_AUX */
2116 if (static_cpu_has(X86_FEATURE_RDTSCP))
2117 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2119 if (sd->current_vmcb != svm->vmcb) {
2120 sd->current_vmcb = svm->vmcb;
2121 indirect_branch_prediction_barrier();
2123 avic_vcpu_load(vcpu, cpu);
2126 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2128 struct vcpu_svm *svm = to_svm(vcpu);
2131 avic_vcpu_put(vcpu);
2133 ++vcpu->stat.host_state_reload;
2134 kvm_load_ldt(svm->host.ldt);
2135 #ifdef CONFIG_X86_64
2136 loadsegment(fs, svm->host.fs);
2137 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2138 load_gs_index(svm->host.gs);
2140 #ifdef CONFIG_X86_32_LAZY_GS
2141 loadsegment(gs, svm->host.gs);
2144 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2145 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2148 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2150 avic_set_running(vcpu, false);
2153 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2155 avic_set_running(vcpu, true);
2158 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2160 struct vcpu_svm *svm = to_svm(vcpu);
2161 unsigned long rflags = svm->vmcb->save.rflags;
2163 if (svm->nmi_singlestep) {
2164 /* Hide our flags if they were not set by the guest */
2165 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2166 rflags &= ~X86_EFLAGS_TF;
2167 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2168 rflags &= ~X86_EFLAGS_RF;
2173 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2175 if (to_svm(vcpu)->nmi_singlestep)
2176 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2179 * Any change of EFLAGS.VM is accompanied by a reload of SS
2180 * (caused by either a task switch or an inter-privilege IRET),
2181 * so we do not need to update the CPL here.
2183 to_svm(vcpu)->vmcb->save.rflags = rflags;
2186 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2189 case VCPU_EXREG_PDPTR:
2190 BUG_ON(!npt_enabled);
2191 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2198 static void svm_set_vintr(struct vcpu_svm *svm)
2200 set_intercept(svm, INTERCEPT_VINTR);
2203 static void svm_clear_vintr(struct vcpu_svm *svm)
2205 clr_intercept(svm, INTERCEPT_VINTR);
2208 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2210 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2213 case VCPU_SREG_CS: return &save->cs;
2214 case VCPU_SREG_DS: return &save->ds;
2215 case VCPU_SREG_ES: return &save->es;
2216 case VCPU_SREG_FS: return &save->fs;
2217 case VCPU_SREG_GS: return &save->gs;
2218 case VCPU_SREG_SS: return &save->ss;
2219 case VCPU_SREG_TR: return &save->tr;
2220 case VCPU_SREG_LDTR: return &save->ldtr;
2226 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2228 struct vmcb_seg *s = svm_seg(vcpu, seg);
2233 static void svm_get_segment(struct kvm_vcpu *vcpu,
2234 struct kvm_segment *var, int seg)
2236 struct vmcb_seg *s = svm_seg(vcpu, seg);
2238 var->base = s->base;
2239 var->limit = s->limit;
2240 var->selector = s->selector;
2241 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2242 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2243 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2244 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2245 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2246 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2247 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2250 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2251 * However, the SVM spec states that the G bit is not observed by the
2252 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2253 * So let's synthesize a legal G bit for all segments, this helps
2254 * running KVM nested. It also helps cross-vendor migration, because
2255 * Intel's vmentry has a check on the 'G' bit.
2257 var->g = s->limit > 0xfffff;
2260 * AMD's VMCB does not have an explicit unusable field, so emulate it
2261 * for cross vendor migration purposes by "not present"
2263 var->unusable = !var->present;
2268 * Work around a bug where the busy flag in the tr selector
2278 * The accessed bit must always be set in the segment
2279 * descriptor cache, although it can be cleared in the
2280 * descriptor, the cached bit always remains at 1. Since
2281 * Intel has a check on this, set it here to support
2282 * cross-vendor migration.
2289 * On AMD CPUs sometimes the DB bit in the segment
2290 * descriptor is left as 1, although the whole segment has
2291 * been made unusable. Clear it here to pass an Intel VMX
2292 * entry check when cross vendor migrating.
2296 /* This is symmetric with svm_set_segment() */
2297 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2302 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2304 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2309 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2311 struct vcpu_svm *svm = to_svm(vcpu);
2313 dt->size = svm->vmcb->save.idtr.limit;
2314 dt->address = svm->vmcb->save.idtr.base;
2317 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2319 struct vcpu_svm *svm = to_svm(vcpu);
2321 svm->vmcb->save.idtr.limit = dt->size;
2322 svm->vmcb->save.idtr.base = dt->address ;
2323 mark_dirty(svm->vmcb, VMCB_DT);
2326 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2328 struct vcpu_svm *svm = to_svm(vcpu);
2330 dt->size = svm->vmcb->save.gdtr.limit;
2331 dt->address = svm->vmcb->save.gdtr.base;
2334 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2336 struct vcpu_svm *svm = to_svm(vcpu);
2338 svm->vmcb->save.gdtr.limit = dt->size;
2339 svm->vmcb->save.gdtr.base = dt->address ;
2340 mark_dirty(svm->vmcb, VMCB_DT);
2343 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2347 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2351 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2355 static void update_cr0_intercept(struct vcpu_svm *svm)
2357 ulong gcr0 = svm->vcpu.arch.cr0;
2358 u64 *hcr0 = &svm->vmcb->save.cr0;
2360 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2361 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2363 mark_dirty(svm->vmcb, VMCB_CR);
2365 if (gcr0 == *hcr0) {
2366 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2367 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2369 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2370 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2374 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2376 struct vcpu_svm *svm = to_svm(vcpu);
2378 #ifdef CONFIG_X86_64
2379 if (vcpu->arch.efer & EFER_LME) {
2380 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2381 vcpu->arch.efer |= EFER_LMA;
2382 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2385 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2386 vcpu->arch.efer &= ~EFER_LMA;
2387 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2391 vcpu->arch.cr0 = cr0;
2394 cr0 |= X86_CR0_PG | X86_CR0_WP;
2397 * re-enable caching here because the QEMU bios
2398 * does not do it - this results in some delay at
2401 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2402 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2403 svm->vmcb->save.cr0 = cr0;
2404 mark_dirty(svm->vmcb, VMCB_CR);
2405 update_cr0_intercept(svm);
2408 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2410 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2411 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2413 if (cr4 & X86_CR4_VMXE)
2416 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2417 svm_flush_tlb(vcpu, true);
2419 vcpu->arch.cr4 = cr4;
2422 cr4 |= host_cr4_mce;
2423 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2424 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2428 static void svm_set_segment(struct kvm_vcpu *vcpu,
2429 struct kvm_segment *var, int seg)
2431 struct vcpu_svm *svm = to_svm(vcpu);
2432 struct vmcb_seg *s = svm_seg(vcpu, seg);
2434 s->base = var->base;
2435 s->limit = var->limit;
2436 s->selector = var->selector;
2437 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2438 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2439 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2440 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2441 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2442 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2443 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2444 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2447 * This is always accurate, except if SYSRET returned to a segment
2448 * with SS.DPL != 3. Intel does not have this quirk, and always
2449 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2450 * would entail passing the CPL to userspace and back.
2452 if (seg == VCPU_SREG_SS)
2453 /* This is symmetric with svm_get_segment() */
2454 svm->vmcb->save.cpl = (var->dpl & 3);
2456 mark_dirty(svm->vmcb, VMCB_SEG);
2459 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2461 struct vcpu_svm *svm = to_svm(vcpu);
2463 clr_exception_intercept(svm, BP_VECTOR);
2465 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2466 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2467 set_exception_intercept(svm, BP_VECTOR);
2469 vcpu->guest_debug = 0;
2472 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2474 if (sd->next_asid > sd->max_asid) {
2475 ++sd->asid_generation;
2476 sd->next_asid = sd->min_asid;
2477 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2480 svm->asid_generation = sd->asid_generation;
2481 svm->vmcb->control.asid = sd->next_asid++;
2483 mark_dirty(svm->vmcb, VMCB_ASID);
2486 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2488 return to_svm(vcpu)->vmcb->save.dr6;
2491 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2493 struct vcpu_svm *svm = to_svm(vcpu);
2495 svm->vmcb->save.dr6 = value;
2496 mark_dirty(svm->vmcb, VMCB_DR);
2499 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2501 struct vcpu_svm *svm = to_svm(vcpu);
2503 get_debugreg(vcpu->arch.db[0], 0);
2504 get_debugreg(vcpu->arch.db[1], 1);
2505 get_debugreg(vcpu->arch.db[2], 2);
2506 get_debugreg(vcpu->arch.db[3], 3);
2507 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2508 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2510 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2511 set_dr_intercepts(svm);
2514 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2516 struct vcpu_svm *svm = to_svm(vcpu);
2518 svm->vmcb->save.dr7 = value;
2519 mark_dirty(svm->vmcb, VMCB_DR);
2522 static int pf_interception(struct vcpu_svm *svm)
2524 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2525 u64 error_code = svm->vmcb->control.exit_info_1;
2527 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2528 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2529 svm->vmcb->control.insn_bytes : NULL,
2530 svm->vmcb->control.insn_len);
2533 static int npf_interception(struct vcpu_svm *svm)
2535 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2536 u64 error_code = svm->vmcb->control.exit_info_1;
2538 trace_kvm_page_fault(fault_address, error_code);
2539 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2540 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2541 svm->vmcb->control.insn_bytes : NULL,
2542 svm->vmcb->control.insn_len);
2545 static int db_interception(struct vcpu_svm *svm)
2547 struct kvm_run *kvm_run = svm->vcpu.run;
2549 if (!(svm->vcpu.guest_debug &
2550 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2551 !svm->nmi_singlestep) {
2552 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2556 if (svm->nmi_singlestep) {
2557 disable_nmi_singlestep(svm);
2560 if (svm->vcpu.guest_debug &
2561 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2562 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2563 kvm_run->debug.arch.pc =
2564 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2565 kvm_run->debug.arch.exception = DB_VECTOR;
2572 static int bp_interception(struct vcpu_svm *svm)
2574 struct kvm_run *kvm_run = svm->vcpu.run;
2576 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2577 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2578 kvm_run->debug.arch.exception = BP_VECTOR;
2582 static int ud_interception(struct vcpu_svm *svm)
2586 er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
2587 if (er == EMULATE_USER_EXIT)
2589 if (er != EMULATE_DONE)
2590 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2594 static int ac_interception(struct vcpu_svm *svm)
2596 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2600 static int gp_interception(struct vcpu_svm *svm)
2602 struct kvm_vcpu *vcpu = &svm->vcpu;
2603 u32 error_code = svm->vmcb->control.exit_info_1;
2606 WARN_ON_ONCE(!enable_vmware_backdoor);
2608 er = emulate_instruction(vcpu,
2609 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
2610 if (er == EMULATE_USER_EXIT)
2612 else if (er != EMULATE_DONE)
2613 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2617 static bool is_erratum_383(void)
2622 if (!erratum_383_found)
2625 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2629 /* Bit 62 may or may not be set for this mce */
2630 value &= ~(1ULL << 62);
2632 if (value != 0xb600000000010015ULL)
2635 /* Clear MCi_STATUS registers */
2636 for (i = 0; i < 6; ++i)
2637 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2639 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2643 value &= ~(1ULL << 2);
2644 low = lower_32_bits(value);
2645 high = upper_32_bits(value);
2647 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2650 /* Flush tlb to evict multi-match entries */
2656 static void svm_handle_mce(struct vcpu_svm *svm)
2658 if (is_erratum_383()) {
2660 * Erratum 383 triggered. Guest state is corrupt so kill the
2663 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2665 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2671 * On an #MC intercept the MCE handler is not called automatically in
2672 * the host. So do it by hand here.
2676 /* not sure if we ever come back to this point */
2681 static int mc_interception(struct vcpu_svm *svm)
2686 static int shutdown_interception(struct vcpu_svm *svm)
2688 struct kvm_run *kvm_run = svm->vcpu.run;
2691 * VMCB is undefined after a SHUTDOWN intercept
2692 * so reinitialize it.
2694 clear_page(svm->vmcb);
2697 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2701 static int io_interception(struct vcpu_svm *svm)
2703 struct kvm_vcpu *vcpu = &svm->vcpu;
2704 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2705 int size, in, string;
2708 ++svm->vcpu.stat.io_exits;
2709 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2710 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2712 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
2714 port = io_info >> 16;
2715 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2716 svm->next_rip = svm->vmcb->control.exit_info_2;
2718 return kvm_fast_pio(&svm->vcpu, size, port, in);
2721 static int nmi_interception(struct vcpu_svm *svm)
2726 static int intr_interception(struct vcpu_svm *svm)
2728 ++svm->vcpu.stat.irq_exits;
2732 static int nop_on_interception(struct vcpu_svm *svm)
2737 static int halt_interception(struct vcpu_svm *svm)
2739 svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2740 return kvm_emulate_halt(&svm->vcpu);
2743 static int vmmcall_interception(struct vcpu_svm *svm)
2745 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2746 return kvm_emulate_hypercall(&svm->vcpu);
2749 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2751 struct vcpu_svm *svm = to_svm(vcpu);
2753 return svm->nested.nested_cr3;
2756 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2758 struct vcpu_svm *svm = to_svm(vcpu);
2759 u64 cr3 = svm->nested.nested_cr3;
2763 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2764 offset_in_page(cr3) + index * 8, 8);
2770 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2773 struct vcpu_svm *svm = to_svm(vcpu);
2775 svm->vmcb->control.nested_cr3 = __sme_set(root);
2776 mark_dirty(svm->vmcb, VMCB_NPT);
2777 svm_flush_tlb(vcpu, true);
2780 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2781 struct x86_exception *fault)
2783 struct vcpu_svm *svm = to_svm(vcpu);
2785 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2787 * TODO: track the cause of the nested page fault, and
2788 * correctly fill in the high bits of exit_info_1.
2790 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2791 svm->vmcb->control.exit_code_hi = 0;
2792 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2793 svm->vmcb->control.exit_info_2 = fault->address;
2796 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2797 svm->vmcb->control.exit_info_1 |= fault->error_code;
2800 * The present bit is always zero for page structure faults on real
2803 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2804 svm->vmcb->control.exit_info_1 &= ~1;
2806 nested_svm_vmexit(svm);
2809 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2811 WARN_ON(mmu_is_nested(vcpu));
2812 kvm_init_shadow_mmu(vcpu);
2813 vcpu->arch.mmu.set_cr3 = nested_svm_set_tdp_cr3;
2814 vcpu->arch.mmu.get_cr3 = nested_svm_get_tdp_cr3;
2815 vcpu->arch.mmu.get_pdptr = nested_svm_get_tdp_pdptr;
2816 vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
2817 vcpu->arch.mmu.shadow_root_level = get_npt_level(vcpu);
2818 reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
2819 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2822 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2824 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
2827 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2829 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2830 !is_paging(&svm->vcpu)) {
2831 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2835 if (svm->vmcb->save.cpl) {
2836 kvm_inject_gp(&svm->vcpu, 0);
2843 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2844 bool has_error_code, u32 error_code)
2848 if (!is_guest_mode(&svm->vcpu))
2851 vmexit = nested_svm_intercept(svm);
2852 if (vmexit != NESTED_EXIT_DONE)
2855 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2856 svm->vmcb->control.exit_code_hi = 0;
2857 svm->vmcb->control.exit_info_1 = error_code;
2860 * FIXME: we should not write CR2 when L1 intercepts an L2 #PF exception.
2861 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2862 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6 can be
2863 * written only when inject_pending_event runs (DR6 would written here
2864 * too). This should be conditional on a new capability---if the
2865 * capability is disabled, kvm_multiple_exception would write the
2866 * ancillary information to CR2 or DR6, for backwards ABI-compatibility.
2868 if (svm->vcpu.arch.exception.nested_apf)
2869 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
2871 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2873 svm->nested.exit_required = true;
2877 /* This function returns true if it is save to enable the irq window */
2878 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2880 if (!is_guest_mode(&svm->vcpu))
2883 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2886 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2890 * if vmexit was already requested (by intercepted exception
2891 * for instance) do not overwrite it with "external interrupt"
2894 if (svm->nested.exit_required)
2897 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
2898 svm->vmcb->control.exit_info_1 = 0;
2899 svm->vmcb->control.exit_info_2 = 0;
2901 if (svm->nested.intercept & 1ULL) {
2903 * The #vmexit can't be emulated here directly because this
2904 * code path runs with irqs and preemption disabled. A
2905 * #vmexit emulation might sleep. Only signal request for
2908 svm->nested.exit_required = true;
2909 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2916 /* This function returns true if it is save to enable the nmi window */
2917 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2919 if (!is_guest_mode(&svm->vcpu))
2922 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2925 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2926 svm->nested.exit_required = true;
2931 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2937 page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2938 if (is_error_page(page))
2946 kvm_inject_gp(&svm->vcpu, 0);
2951 static void nested_svm_unmap(struct page *page)
2954 kvm_release_page_dirty(page);
2957 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2959 unsigned port, size, iopm_len;
2964 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2965 return NESTED_EXIT_HOST;
2967 port = svm->vmcb->control.exit_info_1 >> 16;
2968 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2969 SVM_IOIO_SIZE_SHIFT;
2970 gpa = svm->nested.vmcb_iopm + (port / 8);
2971 start_bit = port % 8;
2972 iopm_len = (start_bit + size > 8) ? 2 : 1;
2973 mask = (0xf >> (4 - size)) << start_bit;
2976 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2977 return NESTED_EXIT_DONE;
2979 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2982 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2984 u32 offset, msr, value;
2987 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2988 return NESTED_EXIT_HOST;
2990 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2991 offset = svm_msrpm_offset(msr);
2992 write = svm->vmcb->control.exit_info_1 & 1;
2993 mask = 1 << ((2 * (msr & 0xf)) + write);
2995 if (offset == MSR_INVALID)
2996 return NESTED_EXIT_DONE;
2998 /* Offset is in 32 bit units but need in 8 bit units */
3001 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3002 return NESTED_EXIT_DONE;
3004 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3007 /* DB exceptions for our internal use must not cause vmexit */
3008 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3012 /* if we're not singlestepping, it's not ours */
3013 if (!svm->nmi_singlestep)
3014 return NESTED_EXIT_DONE;
3016 /* if it's not a singlestep exception, it's not ours */
3017 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3018 return NESTED_EXIT_DONE;
3019 if (!(dr6 & DR6_BS))
3020 return NESTED_EXIT_DONE;
3022 /* if the guest is singlestepping, it should get the vmexit */
3023 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3024 disable_nmi_singlestep(svm);
3025 return NESTED_EXIT_DONE;
3028 /* it's ours, the nested hypervisor must not see this one */
3029 return NESTED_EXIT_HOST;
3032 static int nested_svm_exit_special(struct vcpu_svm *svm)
3034 u32 exit_code = svm->vmcb->control.exit_code;
3036 switch (exit_code) {
3039 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3040 return NESTED_EXIT_HOST;
3042 /* For now we are always handling NPFs when using them */
3044 return NESTED_EXIT_HOST;
3046 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3047 /* When we're shadowing, trap PFs, but not async PF */
3048 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3049 return NESTED_EXIT_HOST;
3055 return NESTED_EXIT_CONTINUE;
3059 * If this function returns true, this #vmexit was already handled
3061 static int nested_svm_intercept(struct vcpu_svm *svm)
3063 u32 exit_code = svm->vmcb->control.exit_code;
3064 int vmexit = NESTED_EXIT_HOST;
3066 switch (exit_code) {
3068 vmexit = nested_svm_exit_handled_msr(svm);
3071 vmexit = nested_svm_intercept_ioio(svm);
3073 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3074 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3075 if (svm->nested.intercept_cr & bit)
3076 vmexit = NESTED_EXIT_DONE;
3079 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3080 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3081 if (svm->nested.intercept_dr & bit)
3082 vmexit = NESTED_EXIT_DONE;
3085 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3086 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3087 if (svm->nested.intercept_exceptions & excp_bits) {
3088 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3089 vmexit = nested_svm_intercept_db(svm);
3091 vmexit = NESTED_EXIT_DONE;
3093 /* async page fault always cause vmexit */
3094 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3095 svm->vcpu.arch.exception.nested_apf != 0)
3096 vmexit = NESTED_EXIT_DONE;
3099 case SVM_EXIT_ERR: {
3100 vmexit = NESTED_EXIT_DONE;
3104 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3105 if (svm->nested.intercept & exit_bits)
3106 vmexit = NESTED_EXIT_DONE;
3113 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3117 vmexit = nested_svm_intercept(svm);
3119 if (vmexit == NESTED_EXIT_DONE)
3120 nested_svm_vmexit(svm);
3125 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3127 struct vmcb_control_area *dst = &dst_vmcb->control;
3128 struct vmcb_control_area *from = &from_vmcb->control;
3130 dst->intercept_cr = from->intercept_cr;
3131 dst->intercept_dr = from->intercept_dr;
3132 dst->intercept_exceptions = from->intercept_exceptions;
3133 dst->intercept = from->intercept;
3134 dst->iopm_base_pa = from->iopm_base_pa;
3135 dst->msrpm_base_pa = from->msrpm_base_pa;
3136 dst->tsc_offset = from->tsc_offset;
3137 dst->asid = from->asid;
3138 dst->tlb_ctl = from->tlb_ctl;
3139 dst->int_ctl = from->int_ctl;
3140 dst->int_vector = from->int_vector;
3141 dst->int_state = from->int_state;
3142 dst->exit_code = from->exit_code;
3143 dst->exit_code_hi = from->exit_code_hi;
3144 dst->exit_info_1 = from->exit_info_1;
3145 dst->exit_info_2 = from->exit_info_2;
3146 dst->exit_int_info = from->exit_int_info;
3147 dst->exit_int_info_err = from->exit_int_info_err;
3148 dst->nested_ctl = from->nested_ctl;
3149 dst->event_inj = from->event_inj;
3150 dst->event_inj_err = from->event_inj_err;
3151 dst->nested_cr3 = from->nested_cr3;
3152 dst->virt_ext = from->virt_ext;
3155 static int nested_svm_vmexit(struct vcpu_svm *svm)
3157 struct vmcb *nested_vmcb;
3158 struct vmcb *hsave = svm->nested.hsave;
3159 struct vmcb *vmcb = svm->vmcb;
3162 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3163 vmcb->control.exit_info_1,
3164 vmcb->control.exit_info_2,
3165 vmcb->control.exit_int_info,
3166 vmcb->control.exit_int_info_err,
3169 nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3173 /* Exit Guest-Mode */
3174 leave_guest_mode(&svm->vcpu);
3175 svm->nested.vmcb = 0;
3177 /* Give the current vmcb to the guest */
3180 nested_vmcb->save.es = vmcb->save.es;
3181 nested_vmcb->save.cs = vmcb->save.cs;
3182 nested_vmcb->save.ss = vmcb->save.ss;
3183 nested_vmcb->save.ds = vmcb->save.ds;
3184 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3185 nested_vmcb->save.idtr = vmcb->save.idtr;
3186 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3187 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3188 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3189 nested_vmcb->save.cr2 = vmcb->save.cr2;
3190 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3191 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3192 nested_vmcb->save.rip = vmcb->save.rip;
3193 nested_vmcb->save.rsp = vmcb->save.rsp;
3194 nested_vmcb->save.rax = vmcb->save.rax;
3195 nested_vmcb->save.dr7 = vmcb->save.dr7;
3196 nested_vmcb->save.dr6 = vmcb->save.dr6;
3197 nested_vmcb->save.cpl = vmcb->save.cpl;
3199 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3200 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3201 nested_vmcb->control.int_state = vmcb->control.int_state;
3202 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3203 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3204 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3205 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3206 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3207 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3209 if (svm->nrips_enabled)
3210 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3213 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3214 * to make sure that we do not lose injected events. So check event_inj
3215 * here and copy it to exit_int_info if it is valid.
3216 * Exit_int_info and event_inj can't be both valid because the case
3217 * below only happens on a VMRUN instruction intercept which has
3218 * no valid exit_int_info set.
3220 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3221 struct vmcb_control_area *nc = &nested_vmcb->control;
3223 nc->exit_int_info = vmcb->control.event_inj;
3224 nc->exit_int_info_err = vmcb->control.event_inj_err;
3227 nested_vmcb->control.tlb_ctl = 0;
3228 nested_vmcb->control.event_inj = 0;
3229 nested_vmcb->control.event_inj_err = 0;
3231 /* We always set V_INTR_MASKING and remember the old value in hflags */
3232 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3233 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3235 /* Restore the original control entries */
3236 copy_vmcb_control_area(vmcb, hsave);
3238 kvm_clear_exception_queue(&svm->vcpu);
3239 kvm_clear_interrupt_queue(&svm->vcpu);
3241 svm->nested.nested_cr3 = 0;
3243 /* Restore selected save entries */
3244 svm->vmcb->save.es = hsave->save.es;
3245 svm->vmcb->save.cs = hsave->save.cs;
3246 svm->vmcb->save.ss = hsave->save.ss;
3247 svm->vmcb->save.ds = hsave->save.ds;
3248 svm->vmcb->save.gdtr = hsave->save.gdtr;
3249 svm->vmcb->save.idtr = hsave->save.idtr;
3250 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3251 svm_set_efer(&svm->vcpu, hsave->save.efer);
3252 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3253 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3255 svm->vmcb->save.cr3 = hsave->save.cr3;
3256 svm->vcpu.arch.cr3 = hsave->save.cr3;
3258 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3260 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3261 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3262 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3263 svm->vmcb->save.dr7 = 0;
3264 svm->vmcb->save.cpl = 0;
3265 svm->vmcb->control.exit_int_info = 0;
3267 mark_all_dirty(svm->vmcb);
3269 nested_svm_unmap(page);
3271 nested_svm_uninit_mmu_context(&svm->vcpu);
3272 kvm_mmu_reset_context(&svm->vcpu);
3273 kvm_mmu_load(&svm->vcpu);
3278 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3281 * This function merges the msr permission bitmaps of kvm and the
3282 * nested vmcb. It is optimized in that it only merges the parts where
3283 * the kvm msr permission bitmap may contain zero bits
3287 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3290 for (i = 0; i < MSRPM_OFFSETS; i++) {
3294 if (msrpm_offsets[i] == 0xffffffff)
3297 p = msrpm_offsets[i];
3298 offset = svm->nested.vmcb_msrpm + (p * 4);
3300 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3303 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3306 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3311 static bool nested_vmcb_checks(struct vmcb *vmcb)
3313 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3316 if (vmcb->control.asid == 0)
3319 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3326 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3327 struct vmcb *nested_vmcb, struct page *page)
3329 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3330 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3332 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3334 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3335 kvm_mmu_unload(&svm->vcpu);
3336 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3337 nested_svm_init_mmu_context(&svm->vcpu);
3340 /* Load the nested guest state */
3341 svm->vmcb->save.es = nested_vmcb->save.es;
3342 svm->vmcb->save.cs = nested_vmcb->save.cs;
3343 svm->vmcb->save.ss = nested_vmcb->save.ss;
3344 svm->vmcb->save.ds = nested_vmcb->save.ds;
3345 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3346 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3347 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3348 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3349 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3350 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3352 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3353 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3355 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3357 /* Guest paging mode is active - reset mmu */
3358 kvm_mmu_reset_context(&svm->vcpu);
3360 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3361 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3362 kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3363 kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3365 /* In case we don't even reach vcpu_run, the fields are not updated */
3366 svm->vmcb->save.rax = nested_vmcb->save.rax;
3367 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3368 svm->vmcb->save.rip = nested_vmcb->save.rip;
3369 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3370 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3371 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3373 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3374 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3376 /* cache intercepts */
3377 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3378 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3379 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3380 svm->nested.intercept = nested_vmcb->control.intercept;
3382 svm_flush_tlb(&svm->vcpu, true);
3383 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3384 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3385 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3387 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3389 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3390 /* We only want the cr8 intercept bits of the guest */
3391 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3392 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3395 /* We don't want to see VMMCALLs from a nested guest */
3396 clr_intercept(svm, INTERCEPT_VMMCALL);
3398 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3399 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3400 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3401 svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
3402 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3403 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3405 nested_svm_unmap(page);
3407 /* Enter Guest-Mode */
3408 enter_guest_mode(&svm->vcpu);
3411 * Merge guest and host intercepts - must be called with vcpu in
3412 * guest-mode to take affect here
3414 recalc_intercepts(svm);
3416 svm->nested.vmcb = vmcb_gpa;
3420 mark_all_dirty(svm->vmcb);
3423 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3425 struct vmcb *nested_vmcb;
3426 struct vmcb *hsave = svm->nested.hsave;
3427 struct vmcb *vmcb = svm->vmcb;
3431 vmcb_gpa = svm->vmcb->save.rax;
3433 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3437 if (!nested_vmcb_checks(nested_vmcb)) {
3438 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3439 nested_vmcb->control.exit_code_hi = 0;
3440 nested_vmcb->control.exit_info_1 = 0;
3441 nested_vmcb->control.exit_info_2 = 0;
3443 nested_svm_unmap(page);
3448 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3449 nested_vmcb->save.rip,
3450 nested_vmcb->control.int_ctl,
3451 nested_vmcb->control.event_inj,
3452 nested_vmcb->control.nested_ctl);
3454 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3455 nested_vmcb->control.intercept_cr >> 16,
3456 nested_vmcb->control.intercept_exceptions,
3457 nested_vmcb->control.intercept);
3459 /* Clear internal status */
3460 kvm_clear_exception_queue(&svm->vcpu);
3461 kvm_clear_interrupt_queue(&svm->vcpu);
3464 * Save the old vmcb, so we don't need to pick what we save, but can
3465 * restore everything when a VMEXIT occurs
3467 hsave->save.es = vmcb->save.es;
3468 hsave->save.cs = vmcb->save.cs;
3469 hsave->save.ss = vmcb->save.ss;
3470 hsave->save.ds = vmcb->save.ds;
3471 hsave->save.gdtr = vmcb->save.gdtr;
3472 hsave->save.idtr = vmcb->save.idtr;
3473 hsave->save.efer = svm->vcpu.arch.efer;
3474 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3475 hsave->save.cr4 = svm->vcpu.arch.cr4;
3476 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3477 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3478 hsave->save.rsp = vmcb->save.rsp;
3479 hsave->save.rax = vmcb->save.rax;
3481 hsave->save.cr3 = vmcb->save.cr3;
3483 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3485 copy_vmcb_control_area(hsave, vmcb);
3487 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3492 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3494 to_vmcb->save.fs = from_vmcb->save.fs;
3495 to_vmcb->save.gs = from_vmcb->save.gs;
3496 to_vmcb->save.tr = from_vmcb->save.tr;
3497 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3498 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3499 to_vmcb->save.star = from_vmcb->save.star;
3500 to_vmcb->save.lstar = from_vmcb->save.lstar;
3501 to_vmcb->save.cstar = from_vmcb->save.cstar;
3502 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3503 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3504 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3505 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3508 static int vmload_interception(struct vcpu_svm *svm)
3510 struct vmcb *nested_vmcb;
3514 if (nested_svm_check_permissions(svm))
3517 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3521 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3522 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3524 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3525 nested_svm_unmap(page);
3530 static int vmsave_interception(struct vcpu_svm *svm)
3532 struct vmcb *nested_vmcb;
3536 if (nested_svm_check_permissions(svm))
3539 nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3543 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3544 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3546 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3547 nested_svm_unmap(page);
3552 static int vmrun_interception(struct vcpu_svm *svm)
3554 if (nested_svm_check_permissions(svm))
3557 /* Save rip after vmrun instruction */
3558 kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
3560 if (!nested_svm_vmrun(svm))
3563 if (!nested_svm_vmrun_msrpm(svm))
3570 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3571 svm->vmcb->control.exit_code_hi = 0;
3572 svm->vmcb->control.exit_info_1 = 0;
3573 svm->vmcb->control.exit_info_2 = 0;
3575 nested_svm_vmexit(svm);
3580 static int stgi_interception(struct vcpu_svm *svm)
3584 if (nested_svm_check_permissions(svm))
3588 * If VGIF is enabled, the STGI intercept is only added to
3589 * detect the opening of the SMI/NMI window; remove it now.
3591 if (vgif_enabled(svm))
3592 clr_intercept(svm, INTERCEPT_STGI);
3594 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3595 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3596 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3603 static int clgi_interception(struct vcpu_svm *svm)
3607 if (nested_svm_check_permissions(svm))
3610 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3611 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3615 /* After a CLGI no interrupts should come */
3616 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3617 svm_clear_vintr(svm);
3618 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3619 mark_dirty(svm->vmcb, VMCB_INTR);
3625 static int invlpga_interception(struct vcpu_svm *svm)
3627 struct kvm_vcpu *vcpu = &svm->vcpu;
3629 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
3630 kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3632 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3633 kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3635 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3636 return kvm_skip_emulated_instruction(&svm->vcpu);
3639 static int skinit_interception(struct vcpu_svm *svm)
3641 trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
3643 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3647 static int wbinvd_interception(struct vcpu_svm *svm)
3649 return kvm_emulate_wbinvd(&svm->vcpu);
3652 static int xsetbv_interception(struct vcpu_svm *svm)
3654 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3655 u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3657 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3658 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
3659 return kvm_skip_emulated_instruction(&svm->vcpu);
3665 static int task_switch_interception(struct vcpu_svm *svm)
3669 int int_type = svm->vmcb->control.exit_int_info &
3670 SVM_EXITINTINFO_TYPE_MASK;
3671 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3673 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3675 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3676 bool has_error_code = false;
3679 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3681 if (svm->vmcb->control.exit_info_2 &
3682 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3683 reason = TASK_SWITCH_IRET;
3684 else if (svm->vmcb->control.exit_info_2 &
3685 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3686 reason = TASK_SWITCH_JMP;
3688 reason = TASK_SWITCH_GATE;
3690 reason = TASK_SWITCH_CALL;
3692 if (reason == TASK_SWITCH_GATE) {
3694 case SVM_EXITINTINFO_TYPE_NMI:
3695 svm->vcpu.arch.nmi_injected = false;
3697 case SVM_EXITINTINFO_TYPE_EXEPT:
3698 if (svm->vmcb->control.exit_info_2 &
3699 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3700 has_error_code = true;
3702 (u32)svm->vmcb->control.exit_info_2;
3704 kvm_clear_exception_queue(&svm->vcpu);
3706 case SVM_EXITINTINFO_TYPE_INTR:
3707 kvm_clear_interrupt_queue(&svm->vcpu);
3714 if (reason != TASK_SWITCH_GATE ||
3715 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3716 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3717 (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
3718 skip_emulated_instruction(&svm->vcpu);
3720 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3723 if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3724 has_error_code, error_code) == EMULATE_FAIL) {
3725 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
3726 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
3727 svm->vcpu.run->internal.ndata = 0;
3733 static int cpuid_interception(struct vcpu_svm *svm)
3735 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3736 return kvm_emulate_cpuid(&svm->vcpu);
3739 static int iret_interception(struct vcpu_svm *svm)
3741 ++svm->vcpu.stat.nmi_window_exits;
3742 clr_intercept(svm, INTERCEPT_IRET);
3743 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3744 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3745 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3749 static int invlpg_interception(struct vcpu_svm *svm)
3751 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3752 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3754 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3755 return kvm_skip_emulated_instruction(&svm->vcpu);
3758 static int emulate_on_interception(struct vcpu_svm *svm)
3760 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
3763 static int rsm_interception(struct vcpu_svm *svm)
3765 return x86_emulate_instruction(&svm->vcpu, 0, 0,
3766 rsm_ins_bytes, 2) == EMULATE_DONE;
3769 static int rdpmc_interception(struct vcpu_svm *svm)
3773 if (!static_cpu_has(X86_FEATURE_NRIPS))
3774 return emulate_on_interception(svm);
3776 err = kvm_rdpmc(&svm->vcpu);
3777 return kvm_complete_insn_gp(&svm->vcpu, err);
3780 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3783 unsigned long cr0 = svm->vcpu.arch.cr0;
3787 intercept = svm->nested.intercept;
3789 if (!is_guest_mode(&svm->vcpu) ||
3790 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3793 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3794 val &= ~SVM_CR0_SELECTIVE_MASK;
3797 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3798 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3804 #define CR_VALID (1ULL << 63)
3806 static int cr_interception(struct vcpu_svm *svm)
3812 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3813 return emulate_on_interception(svm);
3815 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3816 return emulate_on_interception(svm);
3818 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3819 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3820 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
3822 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
3825 if (cr >= 16) { /* mov to cr */
3827 val = kvm_register_read(&svm->vcpu, reg);
3830 if (!check_selective_cr0_intercepted(svm, val))
3831 err = kvm_set_cr0(&svm->vcpu, val);
3837 err = kvm_set_cr3(&svm->vcpu, val);
3840 err = kvm_set_cr4(&svm->vcpu, val);
3843 err = kvm_set_cr8(&svm->vcpu, val);
3846 WARN(1, "unhandled write to CR%d", cr);
3847 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3850 } else { /* mov from cr */
3853 val = kvm_read_cr0(&svm->vcpu);
3856 val = svm->vcpu.arch.cr2;
3859 val = kvm_read_cr3(&svm->vcpu);
3862 val = kvm_read_cr4(&svm->vcpu);
3865 val = kvm_get_cr8(&svm->vcpu);
3868 WARN(1, "unhandled read from CR%d", cr);
3869 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3872 kvm_register_write(&svm->vcpu, reg, val);
3874 return kvm_complete_insn_gp(&svm->vcpu, err);
3877 static int dr_interception(struct vcpu_svm *svm)
3882 if (svm->vcpu.guest_debug == 0) {
3884 * No more DR vmexits; force a reload of the debug registers
3885 * and reenter on this instruction. The next vmexit will
3886 * retrieve the full state of the debug registers.
3888 clr_dr_intercepts(svm);
3889 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
3893 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
3894 return emulate_on_interception(svm);
3896 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3897 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3899 if (dr >= 16) { /* mov to DRn */
3900 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3902 val = kvm_register_read(&svm->vcpu, reg);
3903 kvm_set_dr(&svm->vcpu, dr - 16, val);
3905 if (!kvm_require_dr(&svm->vcpu, dr))
3907 kvm_get_dr(&svm->vcpu, dr, &val);
3908 kvm_register_write(&svm->vcpu, reg, val);
3911 return kvm_skip_emulated_instruction(&svm->vcpu);
3914 static int cr8_write_interception(struct vcpu_svm *svm)
3916 struct kvm_run *kvm_run = svm->vcpu.run;
3919 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3920 /* instruction emulation calls kvm_set_cr8() */
3921 r = cr_interception(svm);
3922 if (lapic_in_kernel(&svm->vcpu))
3924 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3926 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3930 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
3934 switch (msr->index) {
3935 case MSR_F10H_DECFG:
3936 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
3937 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
3946 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3948 struct vcpu_svm *svm = to_svm(vcpu);
3950 switch (msr_info->index) {
3951 case MSR_IA32_TSC: {
3952 msr_info->data = svm->vmcb->control.tsc_offset +
3953 kvm_scale_tsc(vcpu, rdtsc());
3958 msr_info->data = svm->vmcb->save.star;
3960 #ifdef CONFIG_X86_64
3962 msr_info->data = svm->vmcb->save.lstar;
3965 msr_info->data = svm->vmcb->save.cstar;
3967 case MSR_KERNEL_GS_BASE:
3968 msr_info->data = svm->vmcb->save.kernel_gs_base;
3970 case MSR_SYSCALL_MASK:
3971 msr_info->data = svm->vmcb->save.sfmask;
3974 case MSR_IA32_SYSENTER_CS:
3975 msr_info->data = svm->vmcb->save.sysenter_cs;
3977 case MSR_IA32_SYSENTER_EIP:
3978 msr_info->data = svm->sysenter_eip;
3980 case MSR_IA32_SYSENTER_ESP:
3981 msr_info->data = svm->sysenter_esp;
3984 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
3986 msr_info->data = svm->tsc_aux;
3989 * Nobody will change the following 5 values in the VMCB so we can
3990 * safely return them on rdmsr. They will always be 0 until LBRV is
3993 case MSR_IA32_DEBUGCTLMSR:
3994 msr_info->data = svm->vmcb->save.dbgctl;
3996 case MSR_IA32_LASTBRANCHFROMIP:
3997 msr_info->data = svm->vmcb->save.br_from;
3999 case MSR_IA32_LASTBRANCHTOIP:
4000 msr_info->data = svm->vmcb->save.br_to;
4002 case MSR_IA32_LASTINTFROMIP:
4003 msr_info->data = svm->vmcb->save.last_excp_from;
4005 case MSR_IA32_LASTINTTOIP:
4006 msr_info->data = svm->vmcb->save.last_excp_to;
4008 case MSR_VM_HSAVE_PA:
4009 msr_info->data = svm->nested.hsave_msr;
4012 msr_info->data = svm->nested.vm_cr_msr;
4014 case MSR_IA32_SPEC_CTRL:
4015 if (!msr_info->host_initiated &&
4016 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
4019 msr_info->data = svm->spec_ctrl;
4021 case MSR_F15H_IC_CFG: {
4025 family = guest_cpuid_family(vcpu);
4026 model = guest_cpuid_model(vcpu);
4028 if (family < 0 || model < 0)
4029 return kvm_get_msr_common(vcpu, msr_info);
4033 if (family == 0x15 &&
4034 (model >= 0x2 && model < 0x20))
4035 msr_info->data = 0x1E;
4038 case MSR_F10H_DECFG:
4039 msr_info->data = svm->msr_decfg;
4042 return kvm_get_msr_common(vcpu, msr_info);
4047 static int rdmsr_interception(struct vcpu_svm *svm)
4049 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4050 struct msr_data msr_info;
4052 msr_info.index = ecx;
4053 msr_info.host_initiated = false;
4054 if (svm_get_msr(&svm->vcpu, &msr_info)) {
4055 trace_kvm_msr_read_ex(ecx);
4056 kvm_inject_gp(&svm->vcpu, 0);
4059 trace_kvm_msr_read(ecx, msr_info.data);
4061 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
4062 msr_info.data & 0xffffffff);
4063 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
4064 msr_info.data >> 32);
4065 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4066 return kvm_skip_emulated_instruction(&svm->vcpu);
4070 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4072 struct vcpu_svm *svm = to_svm(vcpu);
4073 int svm_dis, chg_mask;
4075 if (data & ~SVM_VM_CR_VALID_MASK)
4078 chg_mask = SVM_VM_CR_VALID_MASK;
4080 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4081 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4083 svm->nested.vm_cr_msr &= ~chg_mask;
4084 svm->nested.vm_cr_msr |= (data & chg_mask);
4086 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4088 /* check for svm_disable while efer.svme is set */
4089 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4095 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4097 struct vcpu_svm *svm = to_svm(vcpu);
4099 u32 ecx = msr->index;
4100 u64 data = msr->data;
4102 case MSR_IA32_CR_PAT:
4103 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4105 vcpu->arch.pat = data;
4106 svm->vmcb->save.g_pat = data;
4107 mark_dirty(svm->vmcb, VMCB_NPT);
4110 kvm_write_tsc(vcpu, msr);
4112 case MSR_IA32_SPEC_CTRL:
4113 if (!msr->host_initiated &&
4114 !guest_cpuid_has(vcpu, X86_FEATURE_IBRS))
4117 /* The STIBP bit doesn't fault even if it's not advertised */
4118 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP))
4121 svm->spec_ctrl = data;
4128 * When it's written (to non-zero) for the first time, pass
4132 * The handling of the MSR bitmap for L2 guests is done in
4133 * nested_svm_vmrun_msrpm.
4134 * We update the L1 MSR bit as well since it will end up
4135 * touching the MSR anyway now.
4137 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4139 case MSR_IA32_PRED_CMD:
4140 if (!msr->host_initiated &&
4141 !guest_cpuid_has(vcpu, X86_FEATURE_IBPB))
4144 if (data & ~PRED_CMD_IBPB)
4150 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4151 if (is_guest_mode(vcpu))
4153 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4156 svm->vmcb->save.star = data;
4158 #ifdef CONFIG_X86_64
4160 svm->vmcb->save.lstar = data;
4163 svm->vmcb->save.cstar = data;
4165 case MSR_KERNEL_GS_BASE:
4166 svm->vmcb->save.kernel_gs_base = data;
4168 case MSR_SYSCALL_MASK:
4169 svm->vmcb->save.sfmask = data;
4172 case MSR_IA32_SYSENTER_CS:
4173 svm->vmcb->save.sysenter_cs = data;
4175 case MSR_IA32_SYSENTER_EIP:
4176 svm->sysenter_eip = data;
4177 svm->vmcb->save.sysenter_eip = data;
4179 case MSR_IA32_SYSENTER_ESP:
4180 svm->sysenter_esp = data;
4181 svm->vmcb->save.sysenter_esp = data;
4184 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4188 * This is rare, so we update the MSR here instead of using
4189 * direct_access_msrs. Doing that would require a rdmsr in
4192 svm->tsc_aux = data;
4193 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4195 case MSR_IA32_DEBUGCTLMSR:
4196 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4197 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4201 if (data & DEBUGCTL_RESERVED_BITS)
4204 svm->vmcb->save.dbgctl = data;
4205 mark_dirty(svm->vmcb, VMCB_LBR);
4206 if (data & (1ULL<<0))
4207 svm_enable_lbrv(svm);
4209 svm_disable_lbrv(svm);
4211 case MSR_VM_HSAVE_PA:
4212 svm->nested.hsave_msr = data;
4215 return svm_set_vm_cr(vcpu, data);
4217 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4219 case MSR_F10H_DECFG: {
4220 struct kvm_msr_entry msr_entry;
4222 msr_entry.index = msr->index;
4223 if (svm_get_msr_feature(&msr_entry))
4226 /* Check the supported bits */
4227 if (data & ~msr_entry.data)
4230 /* Don't allow the guest to change a bit, #GP */
4231 if (!msr->host_initiated && (data ^ msr_entry.data))
4234 svm->msr_decfg = data;
4237 case MSR_IA32_APICBASE:
4238 if (kvm_vcpu_apicv_active(vcpu))
4239 avic_update_vapic_bar(to_svm(vcpu), data);
4240 /* Follow through */
4242 return kvm_set_msr_common(vcpu, msr);
4247 static int wrmsr_interception(struct vcpu_svm *svm)
4249 struct msr_data msr;
4250 u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
4251 u64 data = kvm_read_edx_eax(&svm->vcpu);
4255 msr.host_initiated = false;
4257 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
4258 if (kvm_set_msr(&svm->vcpu, &msr)) {
4259 trace_kvm_msr_write_ex(ecx, data);
4260 kvm_inject_gp(&svm->vcpu, 0);
4263 trace_kvm_msr_write(ecx, data);
4264 return kvm_skip_emulated_instruction(&svm->vcpu);
4268 static int msr_interception(struct vcpu_svm *svm)
4270 if (svm->vmcb->control.exit_info_1)
4271 return wrmsr_interception(svm);
4273 return rdmsr_interception(svm);
4276 static int interrupt_window_interception(struct vcpu_svm *svm)
4278 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4279 svm_clear_vintr(svm);
4280 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4281 mark_dirty(svm->vmcb, VMCB_INTR);
4282 ++svm->vcpu.stat.irq_window_exits;
4286 static int pause_interception(struct vcpu_svm *svm)
4288 struct kvm_vcpu *vcpu = &svm->vcpu;
4289 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4291 kvm_vcpu_on_spin(vcpu, in_kernel);
4295 static int nop_interception(struct vcpu_svm *svm)
4297 return kvm_skip_emulated_instruction(&(svm->vcpu));
4300 static int monitor_interception(struct vcpu_svm *svm)
4302 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4303 return nop_interception(svm);
4306 static int mwait_interception(struct vcpu_svm *svm)
4308 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4309 return nop_interception(svm);
4312 enum avic_ipi_failure_cause {
4313 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4314 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4315 AVIC_IPI_FAILURE_INVALID_TARGET,
4316 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4319 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4321 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4322 u32 icrl = svm->vmcb->control.exit_info_1;
4323 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4324 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4325 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4327 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4330 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4332 * AVIC hardware handles the generation of
4333 * IPIs when the specified Message Type is Fixed
4334 * (also known as fixed delivery mode) and
4335 * the Trigger Mode is edge-triggered. The hardware
4336 * also supports self and broadcast delivery modes
4337 * specified via the Destination Shorthand(DSH)
4338 * field of the ICRL. Logical and physical APIC ID
4339 * formats are supported. All other IPI types cause
4340 * a #VMEXIT, which needs to emulated.
4342 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4343 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4345 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4347 struct kvm_vcpu *vcpu;
4348 struct kvm *kvm = svm->vcpu.kvm;
4349 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4352 * At this point, we expect that the AVIC HW has already
4353 * set the appropriate IRR bits on the valid target
4354 * vcpus. So, we just need to kick the appropriate vcpu.
4356 kvm_for_each_vcpu(i, vcpu, kvm) {
4357 bool m = kvm_apic_match_dest(vcpu, apic,
4358 icrl & KVM_APIC_SHORT_MASK,
4359 GET_APIC_DEST_FIELD(icrh),
4360 icrl & KVM_APIC_DEST_MASK);
4362 if (m && !avic_vcpu_is_running(vcpu))
4363 kvm_vcpu_wake_up(vcpu);
4367 case AVIC_IPI_FAILURE_INVALID_TARGET:
4369 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4370 WARN_ONCE(1, "Invalid backing page\n");
4373 pr_err("Unknown IPI interception\n");
4379 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4381 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4383 u32 *logical_apic_id_table;
4384 int dlid = GET_APIC_LOGICAL_ID(ldr);
4389 if (flat) { /* flat */
4390 index = ffs(dlid) - 1;
4393 } else { /* cluster */
4394 int cluster = (dlid & 0xf0) >> 4;
4395 int apic = ffs(dlid & 0x0f) - 1;
4397 if ((apic < 0) || (apic > 7) ||
4400 index = (cluster << 2) + apic;
4403 logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4405 return &logical_apic_id_table[index];
4408 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr,
4412 u32 *entry, new_entry;
4414 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4415 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4419 new_entry = READ_ONCE(*entry);
4420 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4421 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4423 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4425 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4426 WRITE_ONCE(*entry, new_entry);
4431 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4434 struct vcpu_svm *svm = to_svm(vcpu);
4435 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4440 ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr, true);
4441 if (ret && svm->ldr_reg) {
4442 avic_ldr_write(vcpu, 0, svm->ldr_reg, false);
4450 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4453 struct vcpu_svm *svm = to_svm(vcpu);
4454 u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4455 u32 id = (apic_id_reg >> 24) & 0xff;
4457 if (vcpu->vcpu_id == id)
4460 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4461 new = avic_get_physical_id_entry(vcpu, id);
4465 /* We need to move physical_id_entry to new offset */
4468 to_svm(vcpu)->avic_physical_id_cache = new;
4471 * Also update the guest physical APIC ID in the logical
4472 * APIC ID table entry if already setup the LDR.
4475 avic_handle_ldr_update(vcpu);
4480 static int avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4482 struct vcpu_svm *svm = to_svm(vcpu);
4483 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4484 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4485 u32 mod = (dfr >> 28) & 0xf;
4488 * We assume that all local APICs are using the same type.
4489 * If this changes, we need to flush the AVIC logical
4492 if (kvm_svm->ldr_mode == mod)
4495 clear_page(page_address(kvm_svm->avic_logical_id_table_page));
4496 kvm_svm->ldr_mode = mod;
4499 avic_handle_ldr_update(vcpu);
4503 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4505 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4506 u32 offset = svm->vmcb->control.exit_info_1 &
4507 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4511 if (avic_handle_apic_id_update(&svm->vcpu))
4515 if (avic_handle_ldr_update(&svm->vcpu))
4519 avic_handle_dfr_update(&svm->vcpu);
4525 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4530 static bool is_avic_unaccelerated_access_trap(u32 offset)
4559 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4562 u32 offset = svm->vmcb->control.exit_info_1 &
4563 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4564 u32 vector = svm->vmcb->control.exit_info_2 &
4565 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4566 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4567 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4568 bool trap = is_avic_unaccelerated_access_trap(offset);
4570 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4571 trap, write, vector);
4574 WARN_ONCE(!write, "svm: Handling trap read.\n");
4575 ret = avic_unaccel_trap_write(svm);
4577 /* Handling Fault */
4578 ret = (emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE);
4584 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4585 [SVM_EXIT_READ_CR0] = cr_interception,
4586 [SVM_EXIT_READ_CR3] = cr_interception,
4587 [SVM_EXIT_READ_CR4] = cr_interception,
4588 [SVM_EXIT_READ_CR8] = cr_interception,
4589 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4590 [SVM_EXIT_WRITE_CR0] = cr_interception,
4591 [SVM_EXIT_WRITE_CR3] = cr_interception,
4592 [SVM_EXIT_WRITE_CR4] = cr_interception,
4593 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4594 [SVM_EXIT_READ_DR0] = dr_interception,
4595 [SVM_EXIT_READ_DR1] = dr_interception,
4596 [SVM_EXIT_READ_DR2] = dr_interception,
4597 [SVM_EXIT_READ_DR3] = dr_interception,
4598 [SVM_EXIT_READ_DR4] = dr_interception,
4599 [SVM_EXIT_READ_DR5] = dr_interception,
4600 [SVM_EXIT_READ_DR6] = dr_interception,
4601 [SVM_EXIT_READ_DR7] = dr_interception,
4602 [SVM_EXIT_WRITE_DR0] = dr_interception,
4603 [SVM_EXIT_WRITE_DR1] = dr_interception,
4604 [SVM_EXIT_WRITE_DR2] = dr_interception,
4605 [SVM_EXIT_WRITE_DR3] = dr_interception,
4606 [SVM_EXIT_WRITE_DR4] = dr_interception,
4607 [SVM_EXIT_WRITE_DR5] = dr_interception,
4608 [SVM_EXIT_WRITE_DR6] = dr_interception,
4609 [SVM_EXIT_WRITE_DR7] = dr_interception,
4610 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4611 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4612 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4613 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4614 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4615 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4616 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
4617 [SVM_EXIT_INTR] = intr_interception,
4618 [SVM_EXIT_NMI] = nmi_interception,
4619 [SVM_EXIT_SMI] = nop_on_interception,
4620 [SVM_EXIT_INIT] = nop_on_interception,
4621 [SVM_EXIT_VINTR] = interrupt_window_interception,
4622 [SVM_EXIT_RDPMC] = rdpmc_interception,
4623 [SVM_EXIT_CPUID] = cpuid_interception,
4624 [SVM_EXIT_IRET] = iret_interception,
4625 [SVM_EXIT_INVD] = emulate_on_interception,
4626 [SVM_EXIT_PAUSE] = pause_interception,
4627 [SVM_EXIT_HLT] = halt_interception,
4628 [SVM_EXIT_INVLPG] = invlpg_interception,
4629 [SVM_EXIT_INVLPGA] = invlpga_interception,
4630 [SVM_EXIT_IOIO] = io_interception,
4631 [SVM_EXIT_MSR] = msr_interception,
4632 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4633 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4634 [SVM_EXIT_VMRUN] = vmrun_interception,
4635 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4636 [SVM_EXIT_VMLOAD] = vmload_interception,
4637 [SVM_EXIT_VMSAVE] = vmsave_interception,
4638 [SVM_EXIT_STGI] = stgi_interception,
4639 [SVM_EXIT_CLGI] = clgi_interception,
4640 [SVM_EXIT_SKINIT] = skinit_interception,
4641 [SVM_EXIT_WBINVD] = wbinvd_interception,
4642 [SVM_EXIT_MONITOR] = monitor_interception,
4643 [SVM_EXIT_MWAIT] = mwait_interception,
4644 [SVM_EXIT_XSETBV] = xsetbv_interception,
4645 [SVM_EXIT_NPF] = npf_interception,
4646 [SVM_EXIT_RSM] = rsm_interception,
4647 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4648 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4651 static void dump_vmcb(struct kvm_vcpu *vcpu)
4653 struct vcpu_svm *svm = to_svm(vcpu);
4654 struct vmcb_control_area *control = &svm->vmcb->control;
4655 struct vmcb_save_area *save = &svm->vmcb->save;
4657 pr_err("VMCB Control Area:\n");
4658 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4659 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4660 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4661 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4662 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4663 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4664 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4665 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4666 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4667 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4668 pr_err("%-20s%d\n", "asid:", control->asid);
4669 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4670 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4671 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4672 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4673 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4674 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4675 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4676 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4677 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4678 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4679 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4680 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4681 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4682 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4683 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4684 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4685 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4686 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4687 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4688 pr_err("VMCB State Save Area:\n");
4689 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4691 save->es.selector, save->es.attrib,
4692 save->es.limit, save->es.base);
4693 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4695 save->cs.selector, save->cs.attrib,
4696 save->cs.limit, save->cs.base);
4697 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4699 save->ss.selector, save->ss.attrib,
4700 save->ss.limit, save->ss.base);
4701 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4703 save->ds.selector, save->ds.attrib,
4704 save->ds.limit, save->ds.base);
4705 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4707 save->fs.selector, save->fs.attrib,
4708 save->fs.limit, save->fs.base);
4709 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4711 save->gs.selector, save->gs.attrib,
4712 save->gs.limit, save->gs.base);
4713 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4715 save->gdtr.selector, save->gdtr.attrib,
4716 save->gdtr.limit, save->gdtr.base);
4717 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4719 save->ldtr.selector, save->ldtr.attrib,
4720 save->ldtr.limit, save->ldtr.base);
4721 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4723 save->idtr.selector, save->idtr.attrib,
4724 save->idtr.limit, save->idtr.base);
4725 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4727 save->tr.selector, save->tr.attrib,
4728 save->tr.limit, save->tr.base);
4729 pr_err("cpl: %d efer: %016llx\n",
4730 save->cpl, save->efer);
4731 pr_err("%-15s %016llx %-13s %016llx\n",
4732 "cr0:", save->cr0, "cr2:", save->cr2);
4733 pr_err("%-15s %016llx %-13s %016llx\n",
4734 "cr3:", save->cr3, "cr4:", save->cr4);
4735 pr_err("%-15s %016llx %-13s %016llx\n",
4736 "dr6:", save->dr6, "dr7:", save->dr7);
4737 pr_err("%-15s %016llx %-13s %016llx\n",
4738 "rip:", save->rip, "rflags:", save->rflags);
4739 pr_err("%-15s %016llx %-13s %016llx\n",
4740 "rsp:", save->rsp, "rax:", save->rax);
4741 pr_err("%-15s %016llx %-13s %016llx\n",
4742 "star:", save->star, "lstar:", save->lstar);
4743 pr_err("%-15s %016llx %-13s %016llx\n",
4744 "cstar:", save->cstar, "sfmask:", save->sfmask);
4745 pr_err("%-15s %016llx %-13s %016llx\n",
4746 "kernel_gs_base:", save->kernel_gs_base,
4747 "sysenter_cs:", save->sysenter_cs);
4748 pr_err("%-15s %016llx %-13s %016llx\n",
4749 "sysenter_esp:", save->sysenter_esp,
4750 "sysenter_eip:", save->sysenter_eip);
4751 pr_err("%-15s %016llx %-13s %016llx\n",
4752 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4753 pr_err("%-15s %016llx %-13s %016llx\n",
4754 "br_from:", save->br_from, "br_to:", save->br_to);
4755 pr_err("%-15s %016llx %-13s %016llx\n",
4756 "excp_from:", save->last_excp_from,
4757 "excp_to:", save->last_excp_to);
4760 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4762 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4764 *info1 = control->exit_info_1;
4765 *info2 = control->exit_info_2;
4768 static int handle_exit(struct kvm_vcpu *vcpu)
4770 struct vcpu_svm *svm = to_svm(vcpu);
4771 struct kvm_run *kvm_run = vcpu->run;
4772 u32 exit_code = svm->vmcb->control.exit_code;
4774 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4776 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4777 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4779 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4781 if (unlikely(svm->nested.exit_required)) {
4782 nested_svm_vmexit(svm);
4783 svm->nested.exit_required = false;
4788 if (is_guest_mode(vcpu)) {
4791 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4792 svm->vmcb->control.exit_info_1,
4793 svm->vmcb->control.exit_info_2,
4794 svm->vmcb->control.exit_int_info,
4795 svm->vmcb->control.exit_int_info_err,
4798 vmexit = nested_svm_exit_special(svm);
4800 if (vmexit == NESTED_EXIT_CONTINUE)
4801 vmexit = nested_svm_exit_handled(svm);
4803 if (vmexit == NESTED_EXIT_DONE)
4807 svm_complete_interrupts(svm);
4809 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4810 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4811 kvm_run->fail_entry.hardware_entry_failure_reason
4812 = svm->vmcb->control.exit_code;
4813 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
4818 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4819 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4820 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4821 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4822 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4824 __func__, svm->vmcb->control.exit_int_info,
4827 if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4828 || !svm_exit_handlers[exit_code]) {
4829 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
4830 kvm_queue_exception(vcpu, UD_VECTOR);
4834 return svm_exit_handlers[exit_code](svm);
4837 static void reload_tss(struct kvm_vcpu *vcpu)
4839 int cpu = raw_smp_processor_id();
4841 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4842 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
4846 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
4848 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4849 int asid = sev_get_asid(svm->vcpu.kvm);
4851 /* Assign the asid allocated with this SEV guest */
4852 svm->vmcb->control.asid = asid;
4857 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
4858 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
4860 if (sd->sev_vmcbs[asid] == svm->vmcb &&
4861 svm->last_cpu == cpu)
4864 svm->last_cpu = cpu;
4865 sd->sev_vmcbs[asid] = svm->vmcb;
4866 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
4867 mark_dirty(svm->vmcb, VMCB_ASID);
4870 static void pre_svm_run(struct vcpu_svm *svm)
4872 int cpu = raw_smp_processor_id();
4874 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
4876 if (sev_guest(svm->vcpu.kvm))
4877 return pre_sev_run(svm, cpu);
4879 /* FIXME: handle wraparound of asid_generation */
4880 if (svm->asid_generation != sd->asid_generation)
4884 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
4886 struct vcpu_svm *svm = to_svm(vcpu);
4888 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
4889 vcpu->arch.hflags |= HF_NMI_MASK;
4890 set_intercept(svm, INTERCEPT_IRET);
4891 ++vcpu->stat.nmi_injections;
4894 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
4896 struct vmcb_control_area *control;
4898 /* The following fields are ignored when AVIC is enabled */
4899 control = &svm->vmcb->control;
4900 control->int_vector = irq;
4901 control->int_ctl &= ~V_INTR_PRIO_MASK;
4902 control->int_ctl |= V_IRQ_MASK |
4903 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
4904 mark_dirty(svm->vmcb, VMCB_INTR);
4907 static void svm_set_irq(struct kvm_vcpu *vcpu)
4909 struct vcpu_svm *svm = to_svm(vcpu);
4911 BUG_ON(!(gif_set(svm)));
4913 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
4914 ++vcpu->stat.irq_injections;
4916 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
4917 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
4920 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
4922 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
4925 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
4927 struct vcpu_svm *svm = to_svm(vcpu);
4929 if (svm_nested_virtualize_tpr(vcpu) ||
4930 kvm_vcpu_apicv_active(vcpu))
4933 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4939 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
4942 static void svm_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
4947 static bool svm_get_enable_apicv(struct kvm_vcpu *vcpu)
4949 return avic && irqchip_split(vcpu->kvm);
4952 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
4956 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
4960 /* Note: Currently only used by Hyper-V. */
4961 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
4963 struct vcpu_svm *svm = to_svm(vcpu);
4964 struct vmcb *vmcb = svm->vmcb;
4966 if (!kvm_vcpu_apicv_active(&svm->vcpu))
4969 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
4970 mark_dirty(vmcb, VMCB_INTR);
4973 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
4978 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
4980 kvm_lapic_set_irr(vec, vcpu->arch.apic);
4981 smp_mb__after_atomic();
4983 if (avic_vcpu_is_running(vcpu))
4984 wrmsrl(SVM_AVIC_DOORBELL,
4985 kvm_cpu_get_apicid(vcpu->cpu));
4987 kvm_vcpu_wake_up(vcpu);
4990 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
4992 unsigned long flags;
4993 struct amd_svm_iommu_ir *cur;
4995 spin_lock_irqsave(&svm->ir_list_lock, flags);
4996 list_for_each_entry(cur, &svm->ir_list, node) {
4997 if (cur->data != pi->ir_data)
4999 list_del(&cur->node);
5003 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5006 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5009 unsigned long flags;
5010 struct amd_svm_iommu_ir *ir;
5013 * In some cases, the existing irte is updaed and re-set,
5014 * so we need to check here if it's already been * added
5017 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5018 struct kvm *kvm = svm->vcpu.kvm;
5019 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5020 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5021 struct vcpu_svm *prev_svm;
5028 prev_svm = to_svm(prev_vcpu);
5029 svm_ir_list_del(prev_svm, pi);
5033 * Allocating new amd_iommu_pi_data, which will get
5034 * add to the per-vcpu ir_list.
5036 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL);
5041 ir->data = pi->ir_data;
5043 spin_lock_irqsave(&svm->ir_list_lock, flags);
5044 list_add(&ir->node, &svm->ir_list);
5045 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5052 * The HW cannot support posting multicast/broadcast
5053 * interrupts to a vCPU. So, we still use legacy interrupt
5054 * remapping for these kind of interrupts.
5056 * For lowest-priority interrupts, we only support
5057 * those with single CPU as the destination, e.g. user
5058 * configures the interrupts via /proc/irq or uses
5059 * irqbalance to make the interrupts single-CPU.
5062 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5063 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5065 struct kvm_lapic_irq irq;
5066 struct kvm_vcpu *vcpu = NULL;
5068 kvm_set_msi_irq(kvm, e, &irq);
5070 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
5071 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5072 __func__, irq.vector);
5076 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5078 *svm = to_svm(vcpu);
5079 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5080 vcpu_info->vector = irq.vector;
5086 * svm_update_pi_irte - set IRTE for Posted-Interrupts
5089 * @host_irq: host irq of the interrupt
5090 * @guest_irq: gsi of the interrupt
5091 * @set: set or unset PI
5092 * returns 0 on success, < 0 on failure
5094 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5095 uint32_t guest_irq, bool set)
5097 struct kvm_kernel_irq_routing_entry *e;
5098 struct kvm_irq_routing_table *irq_rt;
5099 int idx, ret = -EINVAL;
5101 if (!kvm_arch_has_assigned_device(kvm) ||
5102 !irq_remapping_cap(IRQ_POSTING_CAP))
5105 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5106 __func__, host_irq, guest_irq, set);
5108 idx = srcu_read_lock(&kvm->irq_srcu);
5109 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5110 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5112 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5113 struct vcpu_data vcpu_info;
5114 struct vcpu_svm *svm = NULL;
5116 if (e->type != KVM_IRQ_ROUTING_MSI)
5120 * Here, we setup with legacy mode in the following cases:
5121 * 1. When cannot target interrupt to a specific vcpu.
5122 * 2. Unsetting posted interrupt.
5123 * 3. APIC virtialization is disabled for the vcpu.
5125 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5126 kvm_vcpu_apicv_active(&svm->vcpu)) {
5127 struct amd_iommu_pi_data pi;
5129 /* Try to enable guest_mode in IRTE */
5130 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5132 pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5134 pi.is_guest_mode = true;
5135 pi.vcpu_data = &vcpu_info;
5136 ret = irq_set_vcpu_affinity(host_irq, &pi);
5139 * Here, we successfully setting up vcpu affinity in
5140 * IOMMU guest mode. Now, we need to store the posted
5141 * interrupt information in a per-vcpu ir_list so that
5142 * we can reference to them directly when we update vcpu
5143 * scheduling information in IOMMU irte.
5145 if (!ret && pi.is_guest_mode)
5146 svm_ir_list_add(svm, &pi);
5148 /* Use legacy mode in IRTE */
5149 struct amd_iommu_pi_data pi;
5152 * Here, pi is used to:
5153 * - Tell IOMMU to use legacy mode for this interrupt.
5154 * - Retrieve ga_tag of prior interrupt remapping data.
5156 pi.is_guest_mode = false;
5157 ret = irq_set_vcpu_affinity(host_irq, &pi);
5160 * Check if the posted interrupt was previously
5161 * setup with the guest_mode by checking if the ga_tag
5162 * was cached. If so, we need to clean up the per-vcpu
5165 if (!ret && pi.prev_ga_tag) {
5166 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5167 struct kvm_vcpu *vcpu;
5169 vcpu = kvm_get_vcpu_by_id(kvm, id);
5171 svm_ir_list_del(to_svm(vcpu), &pi);
5176 trace_kvm_pi_irte_update(svm->vcpu.vcpu_id,
5179 vcpu_info.pi_desc_addr, set);
5183 pr_err("%s: failed to update PI IRTE\n", __func__);
5190 srcu_read_unlock(&kvm->irq_srcu, idx);
5194 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5196 struct vcpu_svm *svm = to_svm(vcpu);
5197 struct vmcb *vmcb = svm->vmcb;
5199 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5200 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5201 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5206 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5208 struct vcpu_svm *svm = to_svm(vcpu);
5210 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5213 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5215 struct vcpu_svm *svm = to_svm(vcpu);
5218 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5219 set_intercept(svm, INTERCEPT_IRET);
5221 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5222 clr_intercept(svm, INTERCEPT_IRET);
5226 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5228 struct vcpu_svm *svm = to_svm(vcpu);
5229 struct vmcb *vmcb = svm->vmcb;
5232 if (!gif_set(svm) ||
5233 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5236 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5238 if (is_guest_mode(vcpu))
5239 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5244 static void enable_irq_window(struct kvm_vcpu *vcpu)
5246 struct vcpu_svm *svm = to_svm(vcpu);
5248 if (kvm_vcpu_apicv_active(vcpu))
5252 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5253 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5254 * get that intercept, this function will be called again though and
5255 * we'll get the vintr intercept. However, if the vGIF feature is
5256 * enabled, the STGI interception will not occur. Enable the irq
5257 * window under the assumption that the hardware will set the GIF.
5259 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5261 svm_inject_irq(svm, 0x0);
5265 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5267 struct vcpu_svm *svm = to_svm(vcpu);
5269 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5271 return; /* IRET will cause a vm exit */
5273 if (!gif_set(svm)) {
5274 if (vgif_enabled(svm))
5275 set_intercept(svm, INTERCEPT_STGI);
5276 return; /* STGI will cause a vm exit */
5279 if (svm->nested.exit_required)
5280 return; /* we're not going to run the guest yet */
5283 * Something prevents NMI from been injected. Single step over possible
5284 * problem (IRET or exception injection or interrupt shadow)
5286 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5287 svm->nmi_singlestep = true;
5288 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5291 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5296 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5301 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5303 struct vcpu_svm *svm = to_svm(vcpu);
5305 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5306 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5308 svm->asid_generation--;
5311 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5315 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5317 struct vcpu_svm *svm = to_svm(vcpu);
5319 if (svm_nested_virtualize_tpr(vcpu))
5322 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5323 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5324 kvm_set_cr8(vcpu, cr8);
5328 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5330 struct vcpu_svm *svm = to_svm(vcpu);
5333 if (svm_nested_virtualize_tpr(vcpu) ||
5334 kvm_vcpu_apicv_active(vcpu))
5337 cr8 = kvm_get_cr8(vcpu);
5338 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5339 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5342 static void svm_complete_interrupts(struct vcpu_svm *svm)
5346 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5347 unsigned int3_injected = svm->int3_injected;
5349 svm->int3_injected = 0;
5352 * If we've made progress since setting HF_IRET_MASK, we've
5353 * executed an IRET and can allow NMI injection.
5355 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5356 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5357 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5358 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5361 svm->vcpu.arch.nmi_injected = false;
5362 kvm_clear_exception_queue(&svm->vcpu);
5363 kvm_clear_interrupt_queue(&svm->vcpu);
5365 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5368 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5370 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5371 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5374 case SVM_EXITINTINFO_TYPE_NMI:
5375 svm->vcpu.arch.nmi_injected = true;
5377 case SVM_EXITINTINFO_TYPE_EXEPT:
5379 * In case of software exceptions, do not reinject the vector,
5380 * but re-execute the instruction instead. Rewind RIP first
5381 * if we emulated INT3 before.
5383 if (kvm_exception_is_soft(vector)) {
5384 if (vector == BP_VECTOR && int3_injected &&
5385 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5386 kvm_rip_write(&svm->vcpu,
5387 kvm_rip_read(&svm->vcpu) -
5391 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5392 u32 err = svm->vmcb->control.exit_int_info_err;
5393 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5396 kvm_requeue_exception(&svm->vcpu, vector);
5398 case SVM_EXITINTINFO_TYPE_INTR:
5399 kvm_queue_interrupt(&svm->vcpu, vector, false);
5406 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5408 struct vcpu_svm *svm = to_svm(vcpu);
5409 struct vmcb_control_area *control = &svm->vmcb->control;
5411 control->exit_int_info = control->event_inj;
5412 control->exit_int_info_err = control->event_inj_err;
5413 control->event_inj = 0;
5414 svm_complete_interrupts(svm);
5417 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5419 struct vcpu_svm *svm = to_svm(vcpu);
5421 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5422 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5423 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5426 * A vmexit emulation is required before the vcpu can be executed
5429 if (unlikely(svm->nested.exit_required))
5433 * Disable singlestep if we're injecting an interrupt/exception.
5434 * We don't want our modified rflags to be pushed on the stack where
5435 * we might not be able to easily reset them if we disabled NMI
5438 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5440 * Event injection happens before external interrupts cause a
5441 * vmexit and interrupts are disabled here, so smp_send_reschedule
5442 * is enough to force an immediate vmexit.
5444 disable_nmi_singlestep(svm);
5445 smp_send_reschedule(vcpu->cpu);
5450 sync_lapic_to_cr8(vcpu);
5452 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5459 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5460 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5461 * is no need to worry about the conditional branch over the wrmsr
5462 * being speculatively taken.
5465 native_wrmsrl(MSR_IA32_SPEC_CTRL, svm->spec_ctrl);
5468 "push %%" _ASM_BP "; \n\t"
5469 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5470 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5471 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5472 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5473 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5474 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5475 #ifdef CONFIG_X86_64
5476 "mov %c[r8](%[svm]), %%r8 \n\t"
5477 "mov %c[r9](%[svm]), %%r9 \n\t"
5478 "mov %c[r10](%[svm]), %%r10 \n\t"
5479 "mov %c[r11](%[svm]), %%r11 \n\t"
5480 "mov %c[r12](%[svm]), %%r12 \n\t"
5481 "mov %c[r13](%[svm]), %%r13 \n\t"
5482 "mov %c[r14](%[svm]), %%r14 \n\t"
5483 "mov %c[r15](%[svm]), %%r15 \n\t"
5486 /* Enter guest mode */
5487 "push %%" _ASM_AX " \n\t"
5488 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5489 __ex(SVM_VMLOAD) "\n\t"
5490 __ex(SVM_VMRUN) "\n\t"
5491 __ex(SVM_VMSAVE) "\n\t"
5492 "pop %%" _ASM_AX " \n\t"
5494 /* Save guest registers, load host registers */
5495 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5496 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5497 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5498 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5499 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5500 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5501 #ifdef CONFIG_X86_64
5502 "mov %%r8, %c[r8](%[svm]) \n\t"
5503 "mov %%r9, %c[r9](%[svm]) \n\t"
5504 "mov %%r10, %c[r10](%[svm]) \n\t"
5505 "mov %%r11, %c[r11](%[svm]) \n\t"
5506 "mov %%r12, %c[r12](%[svm]) \n\t"
5507 "mov %%r13, %c[r13](%[svm]) \n\t"
5508 "mov %%r14, %c[r14](%[svm]) \n\t"
5509 "mov %%r15, %c[r15](%[svm]) \n\t"
5512 * Clear host registers marked as clobbered to prevent
5515 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
5516 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
5517 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
5518 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
5519 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
5520 #ifdef CONFIG_X86_64
5521 "xor %%r8, %%r8 \n\t"
5522 "xor %%r9, %%r9 \n\t"
5523 "xor %%r10, %%r10 \n\t"
5524 "xor %%r11, %%r11 \n\t"
5525 "xor %%r12, %%r12 \n\t"
5526 "xor %%r13, %%r13 \n\t"
5527 "xor %%r14, %%r14 \n\t"
5528 "xor %%r15, %%r15 \n\t"
5533 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5534 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5535 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5536 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5537 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5538 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5539 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5540 #ifdef CONFIG_X86_64
5541 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5542 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5543 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5544 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5545 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5546 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5547 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5548 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5551 #ifdef CONFIG_X86_64
5552 , "rbx", "rcx", "rdx", "rsi", "rdi"
5553 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5555 , "ebx", "ecx", "edx", "esi", "edi"
5560 * We do not use IBRS in the kernel. If this vCPU has used the
5561 * SPEC_CTRL MSR it may have left it on; save the value and
5562 * turn it off. This is much more efficient than blindly adding
5563 * it to the atomic save/restore list. Especially as the former
5564 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5566 * For non-nested case:
5567 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5571 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5574 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5575 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5578 native_wrmsrl(MSR_IA32_SPEC_CTRL, 0);
5580 /* Eliminate branch target predictions from guest mode */
5583 #ifdef CONFIG_X86_64
5584 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5586 loadsegment(fs, svm->host.fs);
5587 #ifndef CONFIG_X86_32_LAZY_GS
5588 loadsegment(gs, svm->host.gs);
5594 local_irq_disable();
5596 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5597 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5598 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5599 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5601 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5602 kvm_before_interrupt(&svm->vcpu);
5606 /* Any pending NMI will happen here */
5608 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5609 kvm_after_interrupt(&svm->vcpu);
5611 sync_cr8_to_lapic(vcpu);
5615 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5617 /* if exit due to PF check for async PF */
5618 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5619 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5622 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5623 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5627 * We need to handle MC intercepts here before the vcpu has a chance to
5628 * change the physical cpu
5630 if (unlikely(svm->vmcb->control.exit_code ==
5631 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5632 svm_handle_mce(svm);
5634 mark_all_clean(svm->vmcb);
5636 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5638 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5640 struct vcpu_svm *svm = to_svm(vcpu);
5642 svm->vmcb->save.cr3 = __sme_set(root);
5643 mark_dirty(svm->vmcb, VMCB_CR);
5644 svm_flush_tlb(vcpu, true);
5647 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5649 struct vcpu_svm *svm = to_svm(vcpu);
5651 svm->vmcb->control.nested_cr3 = __sme_set(root);
5652 mark_dirty(svm->vmcb, VMCB_NPT);
5654 /* Also sync guest cr3 here in case we live migrate */
5655 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5656 mark_dirty(svm->vmcb, VMCB_CR);
5658 svm_flush_tlb(vcpu, true);
5661 static int is_disabled(void)
5665 rdmsrl(MSR_VM_CR, vm_cr);
5666 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5673 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5676 * Patch in the VMMCALL instruction:
5678 hypercall[0] = 0x0f;
5679 hypercall[1] = 0x01;
5680 hypercall[2] = 0xd9;
5683 static void svm_check_processor_compat(void *rtn)
5688 static bool svm_cpu_has_accelerated_tpr(void)
5693 static bool svm_has_high_real_mode_segbase(void)
5698 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5703 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5705 struct vcpu_svm *svm = to_svm(vcpu);
5707 /* Update nrips enabled cache */
5708 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5710 if (!kvm_vcpu_apicv_active(vcpu))
5713 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5716 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5721 entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5725 entry->ecx |= (1 << 2); /* Set SVM bit */
5728 entry->eax = 1; /* SVM revision 1 */
5729 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5730 ASID emulation to nested SVM */
5731 entry->ecx = 0; /* Reserved */
5732 entry->edx = 0; /* Per default do not support any
5733 additional features */
5735 /* Support next_rip if host supports it */
5736 if (boot_cpu_has(X86_FEATURE_NRIPS))
5737 entry->edx |= SVM_FEATURE_NRIP;
5739 /* Support NPT for the guest if enabled */
5741 entry->edx |= SVM_FEATURE_NPT;
5745 /* Support memory encryption cpuid if host supports it */
5746 if (boot_cpu_has(X86_FEATURE_SEV))
5747 cpuid(0x8000001f, &entry->eax, &entry->ebx,
5748 &entry->ecx, &entry->edx);
5753 static int svm_get_lpage_level(void)
5755 return PT_PDPE_LEVEL;
5758 static bool svm_rdtscp_supported(void)
5760 return boot_cpu_has(X86_FEATURE_RDTSCP);
5763 static bool svm_invpcid_supported(void)
5768 static bool svm_mpx_supported(void)
5773 static bool svm_xsaves_supported(void)
5778 static bool svm_umip_emulated(void)
5783 static bool svm_has_wbinvd_exit(void)
5788 #define PRE_EX(exit) { .exit_code = (exit), \
5789 .stage = X86_ICPT_PRE_EXCEPT, }
5790 #define POST_EX(exit) { .exit_code = (exit), \
5791 .stage = X86_ICPT_POST_EXCEPT, }
5792 #define POST_MEM(exit) { .exit_code = (exit), \
5793 .stage = X86_ICPT_POST_MEMACCESS, }
5795 static const struct __x86_intercept {
5797 enum x86_intercept_stage stage;
5798 } x86_intercept_map[] = {
5799 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
5800 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
5801 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
5802 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
5803 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
5804 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
5805 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
5806 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
5807 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
5808 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
5809 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
5810 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
5811 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
5812 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
5813 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
5814 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
5815 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
5816 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
5817 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
5818 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
5819 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
5820 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
5821 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
5822 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
5823 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
5824 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
5825 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
5826 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
5827 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
5828 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
5829 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
5830 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
5831 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
5832 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
5833 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
5834 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
5835 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
5836 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
5837 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
5838 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
5839 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
5840 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
5841 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
5842 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
5843 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
5844 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
5851 static int svm_check_intercept(struct kvm_vcpu *vcpu,
5852 struct x86_instruction_info *info,
5853 enum x86_intercept_stage stage)
5855 struct vcpu_svm *svm = to_svm(vcpu);
5856 int vmexit, ret = X86EMUL_CONTINUE;
5857 struct __x86_intercept icpt_info;
5858 struct vmcb *vmcb = svm->vmcb;
5860 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
5863 icpt_info = x86_intercept_map[info->intercept];
5865 if (stage != icpt_info.stage)
5868 switch (icpt_info.exit_code) {
5869 case SVM_EXIT_READ_CR0:
5870 if (info->intercept == x86_intercept_cr_read)
5871 icpt_info.exit_code += info->modrm_reg;
5873 case SVM_EXIT_WRITE_CR0: {
5874 unsigned long cr0, val;
5877 if (info->intercept == x86_intercept_cr_write)
5878 icpt_info.exit_code += info->modrm_reg;
5880 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
5881 info->intercept == x86_intercept_clts)
5884 intercept = svm->nested.intercept;
5886 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
5889 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
5890 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
5892 if (info->intercept == x86_intercept_lmsw) {
5895 /* lmsw can't clear PE - catch this here */
5896 if (cr0 & X86_CR0_PE)
5901 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
5905 case SVM_EXIT_READ_DR0:
5906 case SVM_EXIT_WRITE_DR0:
5907 icpt_info.exit_code += info->modrm_reg;
5910 if (info->intercept == x86_intercept_wrmsr)
5911 vmcb->control.exit_info_1 = 1;
5913 vmcb->control.exit_info_1 = 0;
5915 case SVM_EXIT_PAUSE:
5917 * We get this for NOP only, but pause
5918 * is rep not, check this here
5920 if (info->rep_prefix != REPE_PREFIX)
5923 case SVM_EXIT_IOIO: {
5927 if (info->intercept == x86_intercept_in ||
5928 info->intercept == x86_intercept_ins) {
5929 exit_info = ((info->src_val & 0xffff) << 16) |
5931 bytes = info->dst_bytes;
5933 exit_info = (info->dst_val & 0xffff) << 16;
5934 bytes = info->src_bytes;
5937 if (info->intercept == x86_intercept_outs ||
5938 info->intercept == x86_intercept_ins)
5939 exit_info |= SVM_IOIO_STR_MASK;
5941 if (info->rep_prefix)
5942 exit_info |= SVM_IOIO_REP_MASK;
5944 bytes = min(bytes, 4u);
5946 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
5948 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
5950 vmcb->control.exit_info_1 = exit_info;
5951 vmcb->control.exit_info_2 = info->next_rip;
5959 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
5960 if (static_cpu_has(X86_FEATURE_NRIPS))
5961 vmcb->control.next_rip = info->next_rip;
5962 vmcb->control.exit_code = icpt_info.exit_code;
5963 vmexit = nested_svm_exit_handled(svm);
5965 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
5972 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
5976 * We must have an instruction with interrupts enabled, so
5977 * the timer interrupt isn't delayed by the interrupt shadow.
5980 local_irq_disable();
5983 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
5987 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
5989 if (avic_handle_apic_id_update(vcpu) != 0)
5991 if (avic_handle_dfr_update(vcpu) != 0)
5993 avic_handle_ldr_update(vcpu);
5996 static void svm_setup_mce(struct kvm_vcpu *vcpu)
5998 /* [63:9] are reserved. */
5999 vcpu->arch.mcg_cap &= 0x1ff;
6002 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6004 struct vcpu_svm *svm = to_svm(vcpu);
6006 /* Per APM Vol.2 15.22.2 "Response to SMI" */
6010 if (is_guest_mode(&svm->vcpu) &&
6011 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6012 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
6013 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6014 svm->nested.exit_required = true;
6021 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6023 struct vcpu_svm *svm = to_svm(vcpu);
6026 if (is_guest_mode(vcpu)) {
6027 /* FED8h - SVM Guest */
6028 put_smstate(u64, smstate, 0x7ed8, 1);
6029 /* FEE0h - SVM Guest VMCB Physical Address */
6030 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6032 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6033 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6034 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6036 ret = nested_svm_vmexit(svm);
6043 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
6045 struct vcpu_svm *svm = to_svm(vcpu);
6046 struct vmcb *nested_vmcb;
6054 ret = kvm_vcpu_read_guest(vcpu, smbase + 0xfed8, &svm_state_save,
6055 sizeof(svm_state_save));
6059 if (svm_state_save.guest) {
6060 vcpu->arch.hflags &= ~HF_SMM_MASK;
6061 nested_vmcb = nested_svm_map(svm, svm_state_save.vmcb, &page);
6063 enter_svm_guest_mode(svm, svm_state_save.vmcb, nested_vmcb, page);
6066 vcpu->arch.hflags |= HF_SMM_MASK;
6071 static int enable_smi_window(struct kvm_vcpu *vcpu)
6073 struct vcpu_svm *svm = to_svm(vcpu);
6075 if (!gif_set(svm)) {
6076 if (vgif_enabled(svm))
6077 set_intercept(svm, INTERCEPT_STGI);
6078 /* STGI will cause a vm exit */
6084 static int sev_asid_new(void)
6089 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6091 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6092 if (pos >= max_sev_asid)
6095 set_bit(pos, sev_asid_bitmap);
6099 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6101 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6105 asid = sev_asid_new();
6109 ret = sev_platform_init(&argp->error);
6115 INIT_LIST_HEAD(&sev->regions_list);
6120 __sev_asid_free(asid);
6124 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6126 struct sev_data_activate *data;
6127 int asid = sev_get_asid(kvm);
6130 wbinvd_on_all_cpus();
6132 ret = sev_guest_df_flush(error);
6136 data = kzalloc(sizeof(*data), GFP_KERNEL);
6140 /* activate ASID on the given handle */
6141 data->handle = handle;
6143 ret = sev_guest_activate(data, error);
6149 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6158 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6164 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6166 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6168 return __sev_issue_cmd(sev->fd, id, data, error);
6171 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6173 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6174 struct sev_data_launch_start *start;
6175 struct kvm_sev_launch_start params;
6176 void *dh_blob, *session_blob;
6177 int *error = &argp->error;
6180 if (!sev_guest(kvm))
6183 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6186 start = kzalloc(sizeof(*start), GFP_KERNEL);
6191 if (params.dh_uaddr) {
6192 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6193 if (IS_ERR(dh_blob)) {
6194 ret = PTR_ERR(dh_blob);
6198 start->dh_cert_address = __sme_set(__pa(dh_blob));
6199 start->dh_cert_len = params.dh_len;
6202 session_blob = NULL;
6203 if (params.session_uaddr) {
6204 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6205 if (IS_ERR(session_blob)) {
6206 ret = PTR_ERR(session_blob);
6210 start->session_address = __sme_set(__pa(session_blob));
6211 start->session_len = params.session_len;
6214 start->handle = params.handle;
6215 start->policy = params.policy;
6217 /* create memory encryption context */
6218 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6220 goto e_free_session;
6222 /* Bind ASID to this guest */
6223 ret = sev_bind_asid(kvm, start->handle, error);
6225 goto e_free_session;
6227 /* return handle to userspace */
6228 params.handle = start->handle;
6229 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6230 sev_unbind_asid(kvm, start->handle);
6232 goto e_free_session;
6235 sev->handle = start->handle;
6236 sev->fd = argp->sev_fd;
6239 kfree(session_blob);
6247 static int get_num_contig_pages(int idx, struct page **inpages,
6248 unsigned long npages)
6250 unsigned long paddr, next_paddr;
6251 int i = idx + 1, pages = 1;
6253 /* find the number of contiguous pages starting from idx */
6254 paddr = __sme_page_pa(inpages[idx]);
6255 while (i < npages) {
6256 next_paddr = __sme_page_pa(inpages[i++]);
6257 if ((paddr + PAGE_SIZE) == next_paddr) {
6268 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6270 unsigned long vaddr, vaddr_end, next_vaddr, npages, size;
6271 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6272 struct kvm_sev_launch_update_data params;
6273 struct sev_data_launch_update_data *data;
6274 struct page **inpages;
6277 if (!sev_guest(kvm))
6280 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6283 data = kzalloc(sizeof(*data), GFP_KERNEL);
6287 vaddr = params.uaddr;
6289 vaddr_end = vaddr + size;
6291 /* Lock the user memory. */
6292 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6299 * The LAUNCH_UPDATE command will perform in-place encryption of the
6300 * memory content (i.e it will write the same memory region with C=1).
6301 * It's possible that the cache may contain the data with C=0, i.e.,
6302 * unencrypted so invalidate it first.
6304 sev_clflush_pages(inpages, npages);
6306 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6310 * If the user buffer is not page-aligned, calculate the offset
6313 offset = vaddr & (PAGE_SIZE - 1);
6315 /* Calculate the number of pages that can be encrypted in one go. */
6316 pages = get_num_contig_pages(i, inpages, npages);
6318 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6320 data->handle = sev->handle;
6322 data->address = __sme_page_pa(inpages[i]) + offset;
6323 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6328 next_vaddr = vaddr + len;
6332 /* content of memory is updated, mark pages dirty */
6333 for (i = 0; i < npages; i++) {
6334 set_page_dirty_lock(inpages[i]);
6335 mark_page_accessed(inpages[i]);
6337 /* unlock the user pages */
6338 sev_unpin_memory(kvm, inpages, npages);
6344 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6346 void __user *measure = (void __user *)(uintptr_t)argp->data;
6347 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6348 struct sev_data_launch_measure *data;
6349 struct kvm_sev_launch_measure params;
6350 void __user *p = NULL;
6354 if (!sev_guest(kvm))
6357 if (copy_from_user(¶ms, measure, sizeof(params)))
6360 data = kzalloc(sizeof(*data), GFP_KERNEL);
6364 /* User wants to query the blob length */
6368 p = (void __user *)(uintptr_t)params.uaddr;
6370 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6376 blob = kmalloc(params.len, GFP_KERNEL);
6380 data->address = __psp_pa(blob);
6381 data->len = params.len;
6385 data->handle = sev->handle;
6386 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6389 * If we query the session length, FW responded with expected data.
6398 if (copy_to_user(p, blob, params.len))
6403 params.len = data->len;
6404 if (copy_to_user(measure, ¶ms, sizeof(params)))
6413 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6415 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6416 struct sev_data_launch_finish *data;
6419 if (!sev_guest(kvm))
6422 data = kzalloc(sizeof(*data), GFP_KERNEL);
6426 data->handle = sev->handle;
6427 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6433 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6435 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6436 struct kvm_sev_guest_status params;
6437 struct sev_data_guest_status *data;
6440 if (!sev_guest(kvm))
6443 data = kzalloc(sizeof(*data), GFP_KERNEL);
6447 data->handle = sev->handle;
6448 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6452 params.policy = data->policy;
6453 params.state = data->state;
6454 params.handle = data->handle;
6456 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6463 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6464 unsigned long dst, int size,
6465 int *error, bool enc)
6467 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6468 struct sev_data_dbg *data;
6471 data = kzalloc(sizeof(*data), GFP_KERNEL);
6475 data->handle = sev->handle;
6476 data->dst_addr = dst;
6477 data->src_addr = src;
6480 ret = sev_issue_cmd(kvm,
6481 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6487 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6488 unsigned long dst_paddr, int sz, int *err)
6493 * Its safe to read more than we are asked, caller should ensure that
6494 * destination has enough space.
6496 src_paddr = round_down(src_paddr, 16);
6497 offset = src_paddr & 15;
6498 sz = round_up(sz + offset, 16);
6500 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6503 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6504 unsigned long __user dst_uaddr,
6505 unsigned long dst_paddr,
6508 struct page *tpage = NULL;
6511 /* if inputs are not 16-byte then use intermediate buffer */
6512 if (!IS_ALIGNED(dst_paddr, 16) ||
6513 !IS_ALIGNED(paddr, 16) ||
6514 !IS_ALIGNED(size, 16)) {
6515 tpage = (void *)alloc_page(GFP_KERNEL);
6519 dst_paddr = __sme_page_pa(tpage);
6522 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6527 offset = paddr & 15;
6528 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6529 page_address(tpage) + offset, size))
6540 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6541 unsigned long __user vaddr,
6542 unsigned long dst_paddr,
6543 unsigned long __user dst_vaddr,
6544 int size, int *error)
6546 struct page *src_tpage = NULL;
6547 struct page *dst_tpage = NULL;
6548 int ret, len = size;
6550 /* If source buffer is not aligned then use an intermediate buffer */
6551 if (!IS_ALIGNED(vaddr, 16)) {
6552 src_tpage = alloc_page(GFP_KERNEL);
6556 if (copy_from_user(page_address(src_tpage),
6557 (void __user *)(uintptr_t)vaddr, size)) {
6558 __free_page(src_tpage);
6562 paddr = __sme_page_pa(src_tpage);
6566 * If destination buffer or length is not aligned then do read-modify-write:
6567 * - decrypt destination in an intermediate buffer
6568 * - copy the source buffer in an intermediate buffer
6569 * - use the intermediate buffer as source buffer
6571 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6574 dst_tpage = alloc_page(GFP_KERNEL);
6580 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6581 __sme_page_pa(dst_tpage), size, error);
6586 * If source is kernel buffer then use memcpy() otherwise
6589 dst_offset = dst_paddr & 15;
6592 memcpy(page_address(dst_tpage) + dst_offset,
6593 page_address(src_tpage), size);
6595 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6596 (void __user *)(uintptr_t)vaddr, size)) {
6602 paddr = __sme_page_pa(dst_tpage);
6603 dst_paddr = round_down(dst_paddr, 16);
6604 len = round_up(size, 16);
6607 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6611 __free_page(src_tpage);
6613 __free_page(dst_tpage);
6617 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6619 unsigned long vaddr, vaddr_end, next_vaddr;
6620 unsigned long dst_vaddr, dst_vaddr_end;
6621 struct page **src_p, **dst_p;
6622 struct kvm_sev_dbg debug;
6626 if (!sev_guest(kvm))
6629 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6632 vaddr = debug.src_uaddr;
6634 vaddr_end = vaddr + size;
6635 dst_vaddr = debug.dst_uaddr;
6636 dst_vaddr_end = dst_vaddr + size;
6638 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6639 int len, s_off, d_off;
6641 /* lock userspace source and destination page */
6642 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6646 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6648 sev_unpin_memory(kvm, src_p, n);
6653 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6654 * memory content (i.e it will write the same memory region with C=1).
6655 * It's possible that the cache may contain the data with C=0, i.e.,
6656 * unencrypted so invalidate it first.
6658 sev_clflush_pages(src_p, 1);
6659 sev_clflush_pages(dst_p, 1);
6662 * Since user buffer may not be page aligned, calculate the
6663 * offset within the page.
6665 s_off = vaddr & ~PAGE_MASK;
6666 d_off = dst_vaddr & ~PAGE_MASK;
6667 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6670 ret = __sev_dbg_decrypt_user(kvm,
6671 __sme_page_pa(src_p[0]) + s_off,
6673 __sme_page_pa(dst_p[0]) + d_off,
6676 ret = __sev_dbg_encrypt_user(kvm,
6677 __sme_page_pa(src_p[0]) + s_off,
6679 __sme_page_pa(dst_p[0]) + d_off,
6683 sev_unpin_memory(kvm, src_p, 1);
6684 sev_unpin_memory(kvm, dst_p, 1);
6689 next_vaddr = vaddr + len;
6690 dst_vaddr = dst_vaddr + len;
6697 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6699 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6700 struct sev_data_launch_secret *data;
6701 struct kvm_sev_launch_secret params;
6702 struct page **pages;
6707 if (!sev_guest(kvm))
6710 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6713 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6718 * The secret must be copied into contiguous memory region, lets verify
6719 * that userspace memory pages are contiguous before we issue command.
6721 if (get_num_contig_pages(0, pages, n) != n) {
6723 goto e_unpin_memory;
6727 data = kzalloc(sizeof(*data), GFP_KERNEL);
6729 goto e_unpin_memory;
6731 offset = params.guest_uaddr & (PAGE_SIZE - 1);
6732 data->guest_address = __sme_page_pa(pages[0]) + offset;
6733 data->guest_len = params.guest_len;
6735 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6737 ret = PTR_ERR(blob);
6741 data->trans_address = __psp_pa(blob);
6742 data->trans_len = params.trans_len;
6744 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6749 data->hdr_address = __psp_pa(hdr);
6750 data->hdr_len = params.hdr_len;
6752 data->handle = sev->handle;
6753 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
6762 sev_unpin_memory(kvm, pages, n);
6766 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
6768 struct kvm_sev_cmd sev_cmd;
6771 if (!svm_sev_enabled())
6774 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
6777 mutex_lock(&kvm->lock);
6779 switch (sev_cmd.id) {
6781 r = sev_guest_init(kvm, &sev_cmd);
6783 case KVM_SEV_LAUNCH_START:
6784 r = sev_launch_start(kvm, &sev_cmd);
6786 case KVM_SEV_LAUNCH_UPDATE_DATA:
6787 r = sev_launch_update_data(kvm, &sev_cmd);
6789 case KVM_SEV_LAUNCH_MEASURE:
6790 r = sev_launch_measure(kvm, &sev_cmd);
6792 case KVM_SEV_LAUNCH_FINISH:
6793 r = sev_launch_finish(kvm, &sev_cmd);
6795 case KVM_SEV_GUEST_STATUS:
6796 r = sev_guest_status(kvm, &sev_cmd);
6798 case KVM_SEV_DBG_DECRYPT:
6799 r = sev_dbg_crypt(kvm, &sev_cmd, true);
6801 case KVM_SEV_DBG_ENCRYPT:
6802 r = sev_dbg_crypt(kvm, &sev_cmd, false);
6804 case KVM_SEV_LAUNCH_SECRET:
6805 r = sev_launch_secret(kvm, &sev_cmd);
6812 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
6816 mutex_unlock(&kvm->lock);
6820 static int svm_register_enc_region(struct kvm *kvm,
6821 struct kvm_enc_region *range)
6823 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6824 struct enc_region *region;
6827 if (!sev_guest(kvm))
6830 region = kzalloc(sizeof(*region), GFP_KERNEL);
6834 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
6835 if (!region->pages) {
6841 * The guest may change the memory encryption attribute from C=0 -> C=1
6842 * or vice versa for this memory range. Lets make sure caches are
6843 * flushed to ensure that guest data gets written into memory with
6846 sev_clflush_pages(region->pages, region->npages);
6848 region->uaddr = range->addr;
6849 region->size = range->size;
6851 mutex_lock(&kvm->lock);
6852 list_add_tail(®ion->list, &sev->regions_list);
6853 mutex_unlock(&kvm->lock);
6862 static struct enc_region *
6863 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
6865 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6866 struct list_head *head = &sev->regions_list;
6867 struct enc_region *i;
6869 list_for_each_entry(i, head, list) {
6870 if (i->uaddr == range->addr &&
6871 i->size == range->size)
6879 static int svm_unregister_enc_region(struct kvm *kvm,
6880 struct kvm_enc_region *range)
6882 struct enc_region *region;
6885 mutex_lock(&kvm->lock);
6887 if (!sev_guest(kvm)) {
6892 region = find_enc_region(kvm, range);
6898 __unregister_enc_region_locked(kvm, region);
6900 mutex_unlock(&kvm->lock);
6904 mutex_unlock(&kvm->lock);
6908 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
6909 .cpu_has_kvm_support = has_svm,
6910 .disabled_by_bios = is_disabled,
6911 .hardware_setup = svm_hardware_setup,
6912 .hardware_unsetup = svm_hardware_unsetup,
6913 .check_processor_compatibility = svm_check_processor_compat,
6914 .hardware_enable = svm_hardware_enable,
6915 .hardware_disable = svm_hardware_disable,
6916 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
6917 .cpu_has_high_real_mode_segbase = svm_has_high_real_mode_segbase,
6919 .vcpu_create = svm_create_vcpu,
6920 .vcpu_free = svm_free_vcpu,
6921 .vcpu_reset = svm_vcpu_reset,
6923 .vm_alloc = svm_vm_alloc,
6924 .vm_free = svm_vm_free,
6925 .vm_init = avic_vm_init,
6926 .vm_destroy = svm_vm_destroy,
6928 .prepare_guest_switch = svm_prepare_guest_switch,
6929 .vcpu_load = svm_vcpu_load,
6930 .vcpu_put = svm_vcpu_put,
6931 .vcpu_blocking = svm_vcpu_blocking,
6932 .vcpu_unblocking = svm_vcpu_unblocking,
6934 .update_bp_intercept = update_bp_intercept,
6935 .get_msr_feature = svm_get_msr_feature,
6936 .get_msr = svm_get_msr,
6937 .set_msr = svm_set_msr,
6938 .get_segment_base = svm_get_segment_base,
6939 .get_segment = svm_get_segment,
6940 .set_segment = svm_set_segment,
6941 .get_cpl = svm_get_cpl,
6942 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
6943 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
6944 .decache_cr3 = svm_decache_cr3,
6945 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
6946 .set_cr0 = svm_set_cr0,
6947 .set_cr3 = svm_set_cr3,
6948 .set_cr4 = svm_set_cr4,
6949 .set_efer = svm_set_efer,
6950 .get_idt = svm_get_idt,
6951 .set_idt = svm_set_idt,
6952 .get_gdt = svm_get_gdt,
6953 .set_gdt = svm_set_gdt,
6954 .get_dr6 = svm_get_dr6,
6955 .set_dr6 = svm_set_dr6,
6956 .set_dr7 = svm_set_dr7,
6957 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
6958 .cache_reg = svm_cache_reg,
6959 .get_rflags = svm_get_rflags,
6960 .set_rflags = svm_set_rflags,
6962 .tlb_flush = svm_flush_tlb,
6964 .run = svm_vcpu_run,
6965 .handle_exit = handle_exit,
6966 .skip_emulated_instruction = skip_emulated_instruction,
6967 .set_interrupt_shadow = svm_set_interrupt_shadow,
6968 .get_interrupt_shadow = svm_get_interrupt_shadow,
6969 .patch_hypercall = svm_patch_hypercall,
6970 .set_irq = svm_set_irq,
6971 .set_nmi = svm_inject_nmi,
6972 .queue_exception = svm_queue_exception,
6973 .cancel_injection = svm_cancel_injection,
6974 .interrupt_allowed = svm_interrupt_allowed,
6975 .nmi_allowed = svm_nmi_allowed,
6976 .get_nmi_mask = svm_get_nmi_mask,
6977 .set_nmi_mask = svm_set_nmi_mask,
6978 .enable_nmi_window = enable_nmi_window,
6979 .enable_irq_window = enable_irq_window,
6980 .update_cr8_intercept = update_cr8_intercept,
6981 .set_virtual_x2apic_mode = svm_set_virtual_x2apic_mode,
6982 .get_enable_apicv = svm_get_enable_apicv,
6983 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
6984 .load_eoi_exitmap = svm_load_eoi_exitmap,
6985 .hwapic_irr_update = svm_hwapic_irr_update,
6986 .hwapic_isr_update = svm_hwapic_isr_update,
6987 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
6988 .apicv_post_state_restore = avic_post_state_restore,
6990 .set_tss_addr = svm_set_tss_addr,
6991 .set_identity_map_addr = svm_set_identity_map_addr,
6992 .get_tdp_level = get_npt_level,
6993 .get_mt_mask = svm_get_mt_mask,
6995 .get_exit_info = svm_get_exit_info,
6997 .get_lpage_level = svm_get_lpage_level,
6999 .cpuid_update = svm_cpuid_update,
7001 .rdtscp_supported = svm_rdtscp_supported,
7002 .invpcid_supported = svm_invpcid_supported,
7003 .mpx_supported = svm_mpx_supported,
7004 .xsaves_supported = svm_xsaves_supported,
7005 .umip_emulated = svm_umip_emulated,
7007 .set_supported_cpuid = svm_set_supported_cpuid,
7009 .has_wbinvd_exit = svm_has_wbinvd_exit,
7011 .write_tsc_offset = svm_write_tsc_offset,
7013 .set_tdp_cr3 = set_tdp_cr3,
7015 .check_intercept = svm_check_intercept,
7016 .handle_external_intr = svm_handle_external_intr,
7018 .sched_in = svm_sched_in,
7020 .pmu_ops = &amd_pmu_ops,
7021 .deliver_posted_interrupt = svm_deliver_avic_intr,
7022 .update_pi_irte = svm_update_pi_irte,
7023 .setup_mce = svm_setup_mce,
7025 .smi_allowed = svm_smi_allowed,
7026 .pre_enter_smm = svm_pre_enter_smm,
7027 .pre_leave_smm = svm_pre_leave_smm,
7028 .enable_smi_window = enable_smi_window,
7030 .mem_enc_op = svm_mem_enc_op,
7031 .mem_enc_reg_region = svm_register_enc_region,
7032 .mem_enc_unreg_region = svm_unregister_enc_region,
7035 static int __init svm_init(void)
7037 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7038 __alignof__(struct vcpu_svm), THIS_MODULE);
7041 static void __exit svm_exit(void)
7046 module_init(svm_init)
7047 module_exit(svm_exit)