1 // SPDX-License-Identifier: GPL-2.0-only
3 * Kernel-based Virtual Machine driver for Linux
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Yaniv Kamay <yaniv@qumranet.com>
12 * Avi Kivity <avi@qumranet.com>
15 #define pr_fmt(fmt) "SVM: " fmt
17 #include <linux/kvm_host.h>
21 #include "kvm_cache_regs.h"
26 #include <linux/module.h>
27 #include <linux/mod_devicetable.h>
28 #include <linux/kernel.h>
29 #include <linux/vmalloc.h>
30 #include <linux/highmem.h>
31 #include <linux/sched.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/amd-iommu.h>
35 #include <linux/hashtable.h>
36 #include <linux/frame.h>
37 #include <linux/psp-sev.h>
38 #include <linux/file.h>
39 #include <linux/pagemap.h>
40 #include <linux/swap.h>
41 #include <linux/rwsem.h>
44 #include <asm/perf_event.h>
45 #include <asm/tlbflush.h>
47 #include <asm/debugreg.h>
48 #include <asm/kvm_para.h>
49 #include <asm/irq_remapping.h>
50 #include <asm/spec-ctrl.h>
52 #include <asm/virtext.h>
55 #define __ex(x) __kvm_handle_fault_on_reboot(x)
57 MODULE_AUTHOR("Qumranet");
58 MODULE_LICENSE("GPL");
60 static const struct x86_cpu_id svm_cpu_id[] = {
61 X86_FEATURE_MATCH(X86_FEATURE_SVM),
64 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
66 #define IOPM_ALLOC_ORDER 2
67 #define MSRPM_ALLOC_ORDER 1
69 #define SEG_TYPE_LDT 2
70 #define SEG_TYPE_BUSY_TSS16 3
72 #define SVM_FEATURE_LBRV (1 << 1)
73 #define SVM_FEATURE_SVML (1 << 2)
74 #define SVM_FEATURE_TSC_RATE (1 << 4)
75 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
76 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
77 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
78 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
80 #define SVM_AVIC_DOORBELL 0xc001011b
82 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
83 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
84 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
86 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
88 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
89 #define TSC_RATIO_MIN 0x0000000000000001ULL
90 #define TSC_RATIO_MAX 0x000000ffffffffffULL
92 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
95 * 0xff is broadcast, so the max index allowed for physical APIC ID
96 * table is 0xfe. APIC IDs above 0xff are reserved.
98 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
100 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
101 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
102 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
104 /* AVIC GATAG is encoded using VM and VCPU IDs */
105 #define AVIC_VCPU_ID_BITS 8
106 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
108 #define AVIC_VM_ID_BITS 24
109 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
110 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
112 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
113 (y & AVIC_VCPU_ID_MASK))
114 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
115 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
117 static bool erratum_383_found __read_mostly;
119 static const u32 host_save_user_msrs[] = {
121 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
124 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
128 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
130 struct kvm_sev_info {
131 bool active; /* SEV enabled guest */
132 unsigned int asid; /* ASID used for this guest */
133 unsigned int handle; /* SEV firmware handle */
134 int fd; /* SEV device fd */
135 unsigned long pages_locked; /* Number of pages locked */
136 struct list_head regions_list; /* List of registered regions */
142 /* Struct members for AVIC */
144 struct page *avic_logical_id_table_page;
145 struct page *avic_physical_id_table_page;
146 struct hlist_node hnode;
148 struct kvm_sev_info sev_info;
153 struct nested_state {
159 /* These are the merged vectors */
162 /* gpa pointers to the real vectors */
166 /* A VMEXIT is required but not yet emulated */
169 /* cache for intercepts of the guest */
172 u32 intercept_exceptions;
175 /* Nested Paging related state */
179 #define MSRPM_OFFSETS 16
180 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
183 * Set osvw_len to higher value when updated Revision Guides
184 * are published and we know what the new status bits are
186 static uint64_t osvw_len = 4, osvw_status;
189 struct kvm_vcpu vcpu;
191 unsigned long vmcb_pa;
192 struct svm_cpu_data *svm_data;
193 uint64_t asid_generation;
194 uint64_t sysenter_esp;
195 uint64_t sysenter_eip;
202 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
212 * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
213 * translated into the appropriate L2_CFG bits on the host to
214 * perform speculative control.
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;
235 struct page *avic_backing_page;
236 u64 *avic_physical_id_cache;
237 bool avic_is_running;
240 * Per-vcpu list of struct amd_svm_iommu_ir:
241 * This is used mainly to store interrupt remapping information used
242 * when update the vcpu affinity. This avoids the need to scan for
243 * IRTE and try to match ga_tag in the IOMMU driver.
245 struct list_head ir_list;
246 spinlock_t ir_list_lock;
248 /* which host CPU was used for running this vcpu */
249 unsigned int last_cpu;
253 * This is a wrapper of struct amd_iommu_ir_data.
255 struct amd_svm_iommu_ir {
256 struct list_head node; /* Used by SVM for per-vcpu ir_list */
257 void *data; /* Storing pointer to struct amd_ir_data */
260 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
261 #define AVIC_LOGICAL_ID_ENTRY_VALID_BIT 31
262 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
264 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
265 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
266 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
267 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
269 static DEFINE_PER_CPU(u64, current_tsc_ratio);
270 #define TSC_RATIO_DEFAULT 0x0100000000ULL
272 #define MSR_INVALID 0xffffffffU
274 static const struct svm_direct_access_msrs {
275 u32 index; /* Index of the MSR */
276 bool always; /* True if intercept is always on */
277 } direct_access_msrs[] = {
278 { .index = MSR_STAR, .always = true },
279 { .index = MSR_IA32_SYSENTER_CS, .always = true },
281 { .index = MSR_GS_BASE, .always = true },
282 { .index = MSR_FS_BASE, .always = true },
283 { .index = MSR_KERNEL_GS_BASE, .always = true },
284 { .index = MSR_LSTAR, .always = true },
285 { .index = MSR_CSTAR, .always = true },
286 { .index = MSR_SYSCALL_MASK, .always = true },
288 { .index = MSR_IA32_SPEC_CTRL, .always = false },
289 { .index = MSR_IA32_PRED_CMD, .always = false },
290 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
291 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
292 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
293 { .index = MSR_IA32_LASTINTTOIP, .always = false },
294 { .index = MSR_INVALID, .always = false },
297 /* enable NPT for AMD64 and X86 with PAE */
298 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
299 static bool npt_enabled = true;
301 static bool npt_enabled;
305 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
306 * pause_filter_count: On processors that support Pause filtering(indicated
307 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
308 * count value. On VMRUN this value is loaded into an internal counter.
309 * Each time a pause instruction is executed, this counter is decremented
310 * until it reaches zero at which time a #VMEXIT is generated if pause
311 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
312 * Intercept Filtering for more details.
313 * This also indicate if ple logic enabled.
315 * pause_filter_thresh: In addition, some processor families support advanced
316 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
317 * the amount of time a guest is allowed to execute in a pause loop.
318 * In this mode, a 16-bit pause filter threshold field is added in the
319 * VMCB. The threshold value is a cycle count that is used to reset the
320 * pause counter. As with simple pause filtering, VMRUN loads the pause
321 * count value from VMCB into an internal counter. Then, on each pause
322 * instruction the hardware checks the elapsed number of cycles since
323 * the most recent pause instruction against the pause filter threshold.
324 * If the elapsed cycle count is greater than the pause filter threshold,
325 * then the internal pause count is reloaded from the VMCB and execution
326 * continues. If the elapsed cycle count is less than the pause filter
327 * threshold, then the internal pause count is decremented. If the count
328 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
329 * triggered. If advanced pause filtering is supported and pause filter
330 * threshold field is set to zero, the filter will operate in the simpler,
334 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
335 module_param(pause_filter_thresh, ushort, 0444);
337 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
338 module_param(pause_filter_count, ushort, 0444);
340 /* Default doubles per-vcpu window every exit. */
341 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
342 module_param(pause_filter_count_grow, ushort, 0444);
344 /* Default resets per-vcpu window every exit to pause_filter_count. */
345 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
346 module_param(pause_filter_count_shrink, ushort, 0444);
348 /* Default is to compute the maximum so we can never overflow. */
349 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
350 module_param(pause_filter_count_max, ushort, 0444);
352 /* allow nested paging (virtualized MMU) for all guests */
353 static int npt = true;
354 module_param(npt, int, S_IRUGO);
356 /* allow nested virtualization in KVM/SVM */
357 static int nested = true;
358 module_param(nested, int, S_IRUGO);
360 /* enable / disable AVIC */
362 #ifdef CONFIG_X86_LOCAL_APIC
363 module_param(avic, int, S_IRUGO);
366 /* enable/disable Next RIP Save */
367 static int nrips = true;
368 module_param(nrips, int, 0444);
370 /* enable/disable Virtual VMLOAD VMSAVE */
371 static int vls = true;
372 module_param(vls, int, 0444);
374 /* enable/disable Virtual GIF */
375 static int vgif = true;
376 module_param(vgif, int, 0444);
378 /* enable/disable SEV support */
379 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
380 module_param(sev, int, 0444);
382 static bool __read_mostly dump_invalid_vmcb = 0;
383 module_param(dump_invalid_vmcb, bool, 0644);
385 static u8 rsm_ins_bytes[] = "\x0f\xaa";
387 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
388 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
389 static void svm_complete_interrupts(struct vcpu_svm *svm);
390 static void svm_toggle_avic_for_irq_window(struct kvm_vcpu *vcpu, bool activate);
391 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu);
393 static int nested_svm_exit_handled(struct vcpu_svm *svm);
394 static int nested_svm_intercept(struct vcpu_svm *svm);
395 static int nested_svm_vmexit(struct vcpu_svm *svm);
396 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
397 bool has_error_code, u32 error_code);
400 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
401 pause filter count */
402 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
403 VMCB_ASID, /* ASID */
404 VMCB_INTR, /* int_ctl, int_vector */
405 VMCB_NPT, /* npt_en, nCR3, gPAT */
406 VMCB_CR, /* CR0, CR3, CR4, EFER */
407 VMCB_DR, /* DR6, DR7 */
408 VMCB_DT, /* GDT, IDT */
409 VMCB_SEG, /* CS, DS, SS, ES, CPL */
410 VMCB_CR2, /* CR2 only */
411 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
412 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
413 * AVIC PHYSICAL_TABLE pointer,
414 * AVIC LOGICAL_TABLE pointer
419 /* TPR and CR2 are always written before VMRUN */
420 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
422 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
424 static int sev_flush_asids(void);
425 static DECLARE_RWSEM(sev_deactivate_lock);
426 static DEFINE_MUTEX(sev_bitmap_lock);
427 static unsigned int max_sev_asid;
428 static unsigned int min_sev_asid;
429 static unsigned long *sev_asid_bitmap;
430 static unsigned long *sev_reclaim_asid_bitmap;
431 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
434 struct list_head list;
435 unsigned long npages;
442 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
444 return container_of(kvm, struct kvm_svm, kvm);
447 static inline bool svm_sev_enabled(void)
449 return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
452 static inline bool sev_guest(struct kvm *kvm)
454 #ifdef CONFIG_KVM_AMD_SEV
455 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
463 static inline int sev_get_asid(struct kvm *kvm)
465 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
470 static inline void mark_all_dirty(struct vmcb *vmcb)
472 vmcb->control.clean = 0;
475 static inline void mark_all_clean(struct vmcb *vmcb)
477 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
478 & ~VMCB_ALWAYS_DIRTY_MASK;
481 static inline void mark_dirty(struct vmcb *vmcb, int bit)
483 vmcb->control.clean &= ~(1 << bit);
486 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
488 return container_of(vcpu, struct vcpu_svm, vcpu);
491 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
493 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
494 mark_dirty(svm->vmcb, VMCB_AVIC);
497 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
499 struct vcpu_svm *svm = to_svm(vcpu);
500 u64 *entry = svm->avic_physical_id_cache;
505 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
508 static void recalc_intercepts(struct vcpu_svm *svm)
510 struct vmcb_control_area *c, *h;
511 struct nested_state *g;
513 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
515 if (!is_guest_mode(&svm->vcpu))
518 c = &svm->vmcb->control;
519 h = &svm->nested.hsave->control;
522 c->intercept_cr = h->intercept_cr | g->intercept_cr;
523 c->intercept_dr = h->intercept_dr | g->intercept_dr;
524 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
525 c->intercept = h->intercept | g->intercept;
528 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
530 if (is_guest_mode(&svm->vcpu))
531 return svm->nested.hsave;
536 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
538 struct vmcb *vmcb = get_host_vmcb(svm);
540 vmcb->control.intercept_cr |= (1U << bit);
542 recalc_intercepts(svm);
545 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
547 struct vmcb *vmcb = get_host_vmcb(svm);
549 vmcb->control.intercept_cr &= ~(1U << bit);
551 recalc_intercepts(svm);
554 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
556 struct vmcb *vmcb = get_host_vmcb(svm);
558 return vmcb->control.intercept_cr & (1U << bit);
561 static inline void set_dr_intercepts(struct vcpu_svm *svm)
563 struct vmcb *vmcb = get_host_vmcb(svm);
565 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
566 | (1 << INTERCEPT_DR1_READ)
567 | (1 << INTERCEPT_DR2_READ)
568 | (1 << INTERCEPT_DR3_READ)
569 | (1 << INTERCEPT_DR4_READ)
570 | (1 << INTERCEPT_DR5_READ)
571 | (1 << INTERCEPT_DR6_READ)
572 | (1 << INTERCEPT_DR7_READ)
573 | (1 << INTERCEPT_DR0_WRITE)
574 | (1 << INTERCEPT_DR1_WRITE)
575 | (1 << INTERCEPT_DR2_WRITE)
576 | (1 << INTERCEPT_DR3_WRITE)
577 | (1 << INTERCEPT_DR4_WRITE)
578 | (1 << INTERCEPT_DR5_WRITE)
579 | (1 << INTERCEPT_DR6_WRITE)
580 | (1 << INTERCEPT_DR7_WRITE);
582 recalc_intercepts(svm);
585 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
587 struct vmcb *vmcb = get_host_vmcb(svm);
589 vmcb->control.intercept_dr = 0;
591 recalc_intercepts(svm);
594 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
596 struct vmcb *vmcb = get_host_vmcb(svm);
598 vmcb->control.intercept_exceptions |= (1U << bit);
600 recalc_intercepts(svm);
603 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
605 struct vmcb *vmcb = get_host_vmcb(svm);
607 vmcb->control.intercept_exceptions &= ~(1U << bit);
609 recalc_intercepts(svm);
612 static inline void set_intercept(struct vcpu_svm *svm, int bit)
614 struct vmcb *vmcb = get_host_vmcb(svm);
616 vmcb->control.intercept |= (1ULL << bit);
618 recalc_intercepts(svm);
621 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
623 struct vmcb *vmcb = get_host_vmcb(svm);
625 vmcb->control.intercept &= ~(1ULL << bit);
627 recalc_intercepts(svm);
630 static inline bool vgif_enabled(struct vcpu_svm *svm)
632 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
635 static inline void enable_gif(struct vcpu_svm *svm)
637 if (vgif_enabled(svm))
638 svm->vmcb->control.int_ctl |= V_GIF_MASK;
640 svm->vcpu.arch.hflags |= HF_GIF_MASK;
643 static inline void disable_gif(struct vcpu_svm *svm)
645 if (vgif_enabled(svm))
646 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
648 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
651 static inline bool gif_set(struct vcpu_svm *svm)
653 if (vgif_enabled(svm))
654 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
656 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
659 static unsigned long iopm_base;
661 struct kvm_ldttss_desc {
664 unsigned base1:8, type:5, dpl:2, p:1;
665 unsigned limit1:4, zero0:3, g:1, base2:8;
668 } __attribute__((packed));
670 struct svm_cpu_data {
677 struct kvm_ldttss_desc *tss_desc;
679 struct page *save_area;
680 struct vmcb *current_vmcb;
682 /* index = sev_asid, value = vmcb pointer */
683 struct vmcb **sev_vmcbs;
686 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
688 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
690 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
691 #define MSRS_RANGE_SIZE 2048
692 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
694 static u32 svm_msrpm_offset(u32 msr)
699 for (i = 0; i < NUM_MSR_MAPS; i++) {
700 if (msr < msrpm_ranges[i] ||
701 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
704 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
705 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
707 /* Now we have the u8 offset - but need the u32 offset */
711 /* MSR not in any range */
715 #define MAX_INST_SIZE 15
717 static inline void clgi(void)
719 asm volatile (__ex("clgi"));
722 static inline void stgi(void)
724 asm volatile (__ex("stgi"));
727 static inline void invlpga(unsigned long addr, u32 asid)
729 asm volatile (__ex("invlpga %1, %0") : : "c"(asid), "a"(addr));
732 static int get_npt_level(struct kvm_vcpu *vcpu)
735 return PT64_ROOT_4LEVEL;
737 return PT32E_ROOT_LEVEL;
741 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
743 vcpu->arch.efer = efer;
746 /* Shadow paging assumes NX to be available. */
749 if (!(efer & EFER_LMA))
753 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
754 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
757 static int is_external_interrupt(u32 info)
759 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
760 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
763 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
765 struct vcpu_svm *svm = to_svm(vcpu);
768 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
769 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
773 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
775 struct vcpu_svm *svm = to_svm(vcpu);
778 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
780 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
784 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
786 struct vcpu_svm *svm = to_svm(vcpu);
788 if (nrips && svm->vmcb->control.next_rip != 0) {
789 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
790 svm->next_rip = svm->vmcb->control.next_rip;
793 if (!svm->next_rip) {
794 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
797 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
798 pr_err("%s: ip 0x%lx next 0x%llx\n",
799 __func__, kvm_rip_read(vcpu), svm->next_rip);
800 kvm_rip_write(vcpu, svm->next_rip);
802 svm_set_interrupt_shadow(vcpu, 0);
807 static void svm_queue_exception(struct kvm_vcpu *vcpu)
809 struct vcpu_svm *svm = to_svm(vcpu);
810 unsigned nr = vcpu->arch.exception.nr;
811 bool has_error_code = vcpu->arch.exception.has_error_code;
812 bool reinject = vcpu->arch.exception.injected;
813 u32 error_code = vcpu->arch.exception.error_code;
816 * If we are within a nested VM we'd better #VMEXIT and let the guest
817 * handle the exception
820 nested_svm_check_exception(svm, nr, has_error_code, error_code))
823 kvm_deliver_exception_payload(&svm->vcpu);
825 if (nr == BP_VECTOR && !nrips) {
826 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
829 * For guest debugging where we have to reinject #BP if some
830 * INT3 is guest-owned:
831 * Emulate nRIP by moving RIP forward. Will fail if injection
832 * raises a fault that is not intercepted. Still better than
833 * failing in all cases.
835 (void)skip_emulated_instruction(&svm->vcpu);
836 rip = kvm_rip_read(&svm->vcpu);
837 svm->int3_rip = rip + svm->vmcb->save.cs.base;
838 svm->int3_injected = rip - old_rip;
841 svm->vmcb->control.event_inj = nr
843 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
844 | SVM_EVTINJ_TYPE_EXEPT;
845 svm->vmcb->control.event_inj_err = error_code;
848 static void svm_init_erratum_383(void)
854 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
857 /* Use _safe variants to not break nested virtualization */
858 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
864 low = lower_32_bits(val);
865 high = upper_32_bits(val);
867 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
869 erratum_383_found = true;
872 static void svm_init_osvw(struct kvm_vcpu *vcpu)
875 * Guests should see errata 400 and 415 as fixed (assuming that
876 * HLT and IO instructions are intercepted).
878 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
879 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
882 * By increasing VCPU's osvw.length to 3 we are telling the guest that
883 * all osvw.status bits inside that length, including bit 0 (which is
884 * reserved for erratum 298), are valid. However, if host processor's
885 * osvw_len is 0 then osvw_status[0] carries no information. We need to
886 * be conservative here and therefore we tell the guest that erratum 298
887 * is present (because we really don't know).
889 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
890 vcpu->arch.osvw.status |= 1;
893 static int has_svm(void)
897 if (!cpu_has_svm(&msg)) {
898 printk(KERN_INFO "has_svm: %s\n", msg);
905 static void svm_hardware_disable(void)
907 /* Make sure we clean up behind us */
908 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
909 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
913 amd_pmu_disable_virt();
916 static int svm_hardware_enable(void)
919 struct svm_cpu_data *sd;
921 struct desc_struct *gdt;
922 int me = raw_smp_processor_id();
924 rdmsrl(MSR_EFER, efer);
925 if (efer & EFER_SVME)
929 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
932 sd = per_cpu(svm_data, me);
934 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
938 sd->asid_generation = 1;
939 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
940 sd->next_asid = sd->max_asid + 1;
941 sd->min_asid = max_sev_asid + 1;
943 gdt = get_current_gdt_rw();
944 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
946 wrmsrl(MSR_EFER, efer | EFER_SVME);
948 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
950 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
951 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
952 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
959 * Note that it is possible to have a system with mixed processor
960 * revisions and therefore different OSVW bits. If bits are not the same
961 * on different processors then choose the worst case (i.e. if erratum
962 * is present on one processor and not on another then assume that the
963 * erratum is present everywhere).
965 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
966 uint64_t len, status = 0;
969 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
971 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
975 osvw_status = osvw_len = 0;
979 osvw_status |= status;
980 osvw_status &= (1ULL << osvw_len) - 1;
983 osvw_status = osvw_len = 0;
985 svm_init_erratum_383();
987 amd_pmu_enable_virt();
992 static void svm_cpu_uninit(int cpu)
994 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
999 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
1000 kfree(sd->sev_vmcbs);
1001 __free_page(sd->save_area);
1005 static int svm_cpu_init(int cpu)
1007 struct svm_cpu_data *sd;
1009 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
1013 sd->save_area = alloc_page(GFP_KERNEL);
1017 if (svm_sev_enabled()) {
1018 sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1022 goto free_save_area;
1025 per_cpu(svm_data, cpu) = sd;
1030 __free_page(sd->save_area);
1037 static bool valid_msr_intercept(u32 index)
1041 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1042 if (direct_access_msrs[i].index == index)
1048 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1055 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1056 to_svm(vcpu)->msrpm;
1058 offset = svm_msrpm_offset(msr);
1059 bit_write = 2 * (msr & 0x0f) + 1;
1060 tmp = msrpm[offset];
1062 BUG_ON(offset == MSR_INVALID);
1064 return !!test_bit(bit_write, &tmp);
1067 static void set_msr_interception(u32 *msrpm, unsigned msr,
1068 int read, int write)
1070 u8 bit_read, bit_write;
1075 * If this warning triggers extend the direct_access_msrs list at the
1076 * beginning of the file
1078 WARN_ON(!valid_msr_intercept(msr));
1080 offset = svm_msrpm_offset(msr);
1081 bit_read = 2 * (msr & 0x0f);
1082 bit_write = 2 * (msr & 0x0f) + 1;
1083 tmp = msrpm[offset];
1085 BUG_ON(offset == MSR_INVALID);
1087 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
1088 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1090 msrpm[offset] = tmp;
1093 static void svm_vcpu_init_msrpm(u32 *msrpm)
1097 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1099 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1100 if (!direct_access_msrs[i].always)
1103 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1107 static void add_msr_offset(u32 offset)
1111 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1113 /* Offset already in list? */
1114 if (msrpm_offsets[i] == offset)
1117 /* Slot used by another offset? */
1118 if (msrpm_offsets[i] != MSR_INVALID)
1121 /* Add offset to list */
1122 msrpm_offsets[i] = offset;
1128 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1129 * increase MSRPM_OFFSETS in this case.
1134 static void init_msrpm_offsets(void)
1138 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1140 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1143 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1144 BUG_ON(offset == MSR_INVALID);
1146 add_msr_offset(offset);
1150 static void svm_enable_lbrv(struct vcpu_svm *svm)
1152 u32 *msrpm = svm->msrpm;
1154 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1155 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1156 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1157 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1158 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1161 static void svm_disable_lbrv(struct vcpu_svm *svm)
1163 u32 *msrpm = svm->msrpm;
1165 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1166 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1167 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1168 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1169 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1172 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1174 svm->nmi_singlestep = false;
1176 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1177 /* Clear our flags if they were not set by the guest */
1178 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1179 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1180 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1181 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1186 * This hash table is used to map VM_ID to a struct kvm_svm,
1187 * when handling AMD IOMMU GALOG notification to schedule in
1188 * a particular vCPU.
1190 #define SVM_VM_DATA_HASH_BITS 8
1191 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1192 static u32 next_vm_id = 0;
1193 static bool next_vm_id_wrapped = 0;
1194 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1197 * This function is called from IOMMU driver to notify
1198 * SVM to schedule in a particular vCPU of a particular VM.
1200 static int avic_ga_log_notifier(u32 ga_tag)
1202 unsigned long flags;
1203 struct kvm_svm *kvm_svm;
1204 struct kvm_vcpu *vcpu = NULL;
1205 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1206 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1208 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1210 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1211 hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1212 if (kvm_svm->avic_vm_id != vm_id)
1214 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1217 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1220 * At this point, the IOMMU should have already set the pending
1221 * bit in the vAPIC backing page. So, we just need to schedule
1225 kvm_vcpu_wake_up(vcpu);
1230 static __init int sev_hardware_setup(void)
1232 struct sev_user_data_status *status;
1235 /* Maximum number of encrypted guests supported simultaneously */
1236 max_sev_asid = cpuid_ecx(0x8000001F);
1241 /* Minimum ASID value that should be used for SEV guest */
1242 min_sev_asid = cpuid_edx(0x8000001F);
1244 /* Initialize SEV ASID bitmaps */
1245 sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1246 if (!sev_asid_bitmap)
1249 sev_reclaim_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1250 if (!sev_reclaim_asid_bitmap)
1253 status = kmalloc(sizeof(*status), GFP_KERNEL);
1258 * Check SEV platform status.
1260 * PLATFORM_STATUS can be called in any state, if we failed to query
1261 * the PLATFORM status then either PSP firmware does not support SEV
1262 * feature or SEV firmware is dead.
1264 rc = sev_platform_status(status, NULL);
1268 pr_info("SEV supported\n");
1275 static void grow_ple_window(struct kvm_vcpu *vcpu)
1277 struct vcpu_svm *svm = to_svm(vcpu);
1278 struct vmcb_control_area *control = &svm->vmcb->control;
1279 int old = control->pause_filter_count;
1281 control->pause_filter_count = __grow_ple_window(old,
1283 pause_filter_count_grow,
1284 pause_filter_count_max);
1286 if (control->pause_filter_count != old) {
1287 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1288 trace_kvm_ple_window_update(vcpu->vcpu_id,
1289 control->pause_filter_count, old);
1293 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1295 struct vcpu_svm *svm = to_svm(vcpu);
1296 struct vmcb_control_area *control = &svm->vmcb->control;
1297 int old = control->pause_filter_count;
1299 control->pause_filter_count =
1300 __shrink_ple_window(old,
1302 pause_filter_count_shrink,
1303 pause_filter_count);
1304 if (control->pause_filter_count != old) {
1305 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1306 trace_kvm_ple_window_update(vcpu->vcpu_id,
1307 control->pause_filter_count, old);
1312 * The default MMIO mask is a single bit (excluding the present bit),
1313 * which could conflict with the memory encryption bit. Check for
1314 * memory encryption support and override the default MMIO mask if
1315 * memory encryption is enabled.
1317 static __init void svm_adjust_mmio_mask(void)
1319 unsigned int enc_bit, mask_bit;
1322 /* If there is no memory encryption support, use existing mask */
1323 if (cpuid_eax(0x80000000) < 0x8000001f)
1326 /* If memory encryption is not enabled, use existing mask */
1327 rdmsrl(MSR_K8_SYSCFG, msr);
1328 if (!(msr & MSR_K8_SYSCFG_MEM_ENCRYPT))
1331 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
1332 mask_bit = boot_cpu_data.x86_phys_bits;
1334 /* Increment the mask bit if it is the same as the encryption bit */
1335 if (enc_bit == mask_bit)
1339 * If the mask bit location is below 52, then some bits above the
1340 * physical addressing limit will always be reserved, so use the
1341 * rsvd_bits() function to generate the mask. This mask, along with
1342 * the present bit, will be used to generate a page fault with
1345 * If the mask bit location is 52 (or above), then clear the mask.
1347 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
1349 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
1352 static void svm_hardware_teardown(void)
1356 if (svm_sev_enabled()) {
1357 bitmap_free(sev_asid_bitmap);
1358 bitmap_free(sev_reclaim_asid_bitmap);
1363 for_each_possible_cpu(cpu)
1364 svm_cpu_uninit(cpu);
1366 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1370 static __init int svm_hardware_setup(void)
1373 struct page *iopm_pages;
1377 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1382 iopm_va = page_address(iopm_pages);
1383 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1384 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1386 init_msrpm_offsets();
1388 if (boot_cpu_has(X86_FEATURE_NX))
1389 kvm_enable_efer_bits(EFER_NX);
1391 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1392 kvm_enable_efer_bits(EFER_FFXSR);
1394 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1395 kvm_has_tsc_control = true;
1396 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1397 kvm_tsc_scaling_ratio_frac_bits = 32;
1400 /* Check for pause filtering support */
1401 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1402 pause_filter_count = 0;
1403 pause_filter_thresh = 0;
1404 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1405 pause_filter_thresh = 0;
1409 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1410 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1414 if (boot_cpu_has(X86_FEATURE_SEV) &&
1415 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1416 r = sev_hardware_setup();
1424 svm_adjust_mmio_mask();
1426 for_each_possible_cpu(cpu) {
1427 r = svm_cpu_init(cpu);
1432 if (!boot_cpu_has(X86_FEATURE_NPT))
1433 npt_enabled = false;
1435 if (npt_enabled && !npt) {
1436 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1437 npt_enabled = false;
1441 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1447 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1453 !boot_cpu_has(X86_FEATURE_AVIC) ||
1454 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1457 pr_info("AVIC enabled\n");
1459 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1465 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1466 !IS_ENABLED(CONFIG_X86_64)) {
1469 pr_info("Virtual VMLOAD VMSAVE supported\n");
1474 if (!boot_cpu_has(X86_FEATURE_VGIF))
1477 pr_info("Virtual GIF supported\n");
1483 svm_hardware_teardown();
1487 static void init_seg(struct vmcb_seg *seg)
1490 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1491 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1492 seg->limit = 0xffff;
1496 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1499 seg->attrib = SVM_SELECTOR_P_MASK | type;
1500 seg->limit = 0xffff;
1504 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1506 struct vcpu_svm *svm = to_svm(vcpu);
1508 if (is_guest_mode(vcpu))
1509 return svm->nested.hsave->control.tsc_offset;
1511 return vcpu->arch.tsc_offset;
1514 static u64 svm_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1516 struct vcpu_svm *svm = to_svm(vcpu);
1517 u64 g_tsc_offset = 0;
1519 if (is_guest_mode(vcpu)) {
1520 /* Write L1's TSC offset. */
1521 g_tsc_offset = svm->vmcb->control.tsc_offset -
1522 svm->nested.hsave->control.tsc_offset;
1523 svm->nested.hsave->control.tsc_offset = offset;
1526 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1527 svm->vmcb->control.tsc_offset - g_tsc_offset,
1530 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1532 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1533 return svm->vmcb->control.tsc_offset;
1536 static void avic_init_vmcb(struct vcpu_svm *svm)
1538 struct vmcb *vmcb = svm->vmcb;
1539 struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1540 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1541 phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1542 phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1544 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1545 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1546 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1547 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1548 if (kvm_apicv_activated(svm->vcpu.kvm))
1549 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1551 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
1554 static void init_vmcb(struct vcpu_svm *svm)
1556 struct vmcb_control_area *control = &svm->vmcb->control;
1557 struct vmcb_save_area *save = &svm->vmcb->save;
1559 svm->vcpu.arch.hflags = 0;
1561 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1562 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1563 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1564 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1565 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1566 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1567 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1568 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1570 set_dr_intercepts(svm);
1572 set_exception_intercept(svm, PF_VECTOR);
1573 set_exception_intercept(svm, UD_VECTOR);
1574 set_exception_intercept(svm, MC_VECTOR);
1575 set_exception_intercept(svm, AC_VECTOR);
1576 set_exception_intercept(svm, DB_VECTOR);
1578 * Guest access to VMware backdoor ports could legitimately
1579 * trigger #GP because of TSS I/O permission bitmap.
1580 * We intercept those #GP and allow access to them anyway
1583 if (enable_vmware_backdoor)
1584 set_exception_intercept(svm, GP_VECTOR);
1586 set_intercept(svm, INTERCEPT_INTR);
1587 set_intercept(svm, INTERCEPT_NMI);
1588 set_intercept(svm, INTERCEPT_SMI);
1589 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1590 set_intercept(svm, INTERCEPT_RDPMC);
1591 set_intercept(svm, INTERCEPT_CPUID);
1592 set_intercept(svm, INTERCEPT_INVD);
1593 set_intercept(svm, INTERCEPT_INVLPG);
1594 set_intercept(svm, INTERCEPT_INVLPGA);
1595 set_intercept(svm, INTERCEPT_IOIO_PROT);
1596 set_intercept(svm, INTERCEPT_MSR_PROT);
1597 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1598 set_intercept(svm, INTERCEPT_SHUTDOWN);
1599 set_intercept(svm, INTERCEPT_VMRUN);
1600 set_intercept(svm, INTERCEPT_VMMCALL);
1601 set_intercept(svm, INTERCEPT_VMLOAD);
1602 set_intercept(svm, INTERCEPT_VMSAVE);
1603 set_intercept(svm, INTERCEPT_STGI);
1604 set_intercept(svm, INTERCEPT_CLGI);
1605 set_intercept(svm, INTERCEPT_SKINIT);
1606 set_intercept(svm, INTERCEPT_WBINVD);
1607 set_intercept(svm, INTERCEPT_XSETBV);
1608 set_intercept(svm, INTERCEPT_RDPRU);
1609 set_intercept(svm, INTERCEPT_RSM);
1611 if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1612 set_intercept(svm, INTERCEPT_MONITOR);
1613 set_intercept(svm, INTERCEPT_MWAIT);
1616 if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1617 set_intercept(svm, INTERCEPT_HLT);
1619 control->iopm_base_pa = __sme_set(iopm_base);
1620 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1621 control->int_ctl = V_INTR_MASKING_MASK;
1623 init_seg(&save->es);
1624 init_seg(&save->ss);
1625 init_seg(&save->ds);
1626 init_seg(&save->fs);
1627 init_seg(&save->gs);
1629 save->cs.selector = 0xf000;
1630 save->cs.base = 0xffff0000;
1631 /* Executable/Readable Code Segment */
1632 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1633 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1634 save->cs.limit = 0xffff;
1636 save->gdtr.limit = 0xffff;
1637 save->idtr.limit = 0xffff;
1639 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1640 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1642 svm_set_efer(&svm->vcpu, 0);
1643 save->dr6 = 0xffff0ff0;
1644 kvm_set_rflags(&svm->vcpu, 2);
1645 save->rip = 0x0000fff0;
1646 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1649 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1650 * It also updates the guest-visible cr0 value.
1652 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1653 kvm_mmu_reset_context(&svm->vcpu);
1655 save->cr4 = X86_CR4_PAE;
1659 /* Setup VMCB for Nested Paging */
1660 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1661 clr_intercept(svm, INTERCEPT_INVLPG);
1662 clr_exception_intercept(svm, PF_VECTOR);
1663 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1664 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1665 save->g_pat = svm->vcpu.arch.pat;
1669 svm->asid_generation = 0;
1671 svm->nested.vmcb = 0;
1672 svm->vcpu.arch.hflags = 0;
1674 if (pause_filter_count) {
1675 control->pause_filter_count = pause_filter_count;
1676 if (pause_filter_thresh)
1677 control->pause_filter_thresh = pause_filter_thresh;
1678 set_intercept(svm, INTERCEPT_PAUSE);
1680 clr_intercept(svm, INTERCEPT_PAUSE);
1683 if (kvm_vcpu_apicv_active(&svm->vcpu))
1684 avic_init_vmcb(svm);
1687 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1688 * in VMCB and clear intercepts to avoid #VMEXIT.
1691 clr_intercept(svm, INTERCEPT_VMLOAD);
1692 clr_intercept(svm, INTERCEPT_VMSAVE);
1693 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1697 clr_intercept(svm, INTERCEPT_STGI);
1698 clr_intercept(svm, INTERCEPT_CLGI);
1699 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1702 if (sev_guest(svm->vcpu.kvm)) {
1703 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1704 clr_exception_intercept(svm, UD_VECTOR);
1707 mark_all_dirty(svm->vmcb);
1713 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1716 u64 *avic_physical_id_table;
1717 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1719 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1722 avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1724 return &avic_physical_id_table[index];
1729 * AVIC hardware walks the nested page table to check permissions,
1730 * but does not use the SPA address specified in the leaf page
1731 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1732 * field of the VMCB. Therefore, we set up the
1733 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1735 static int avic_update_access_page(struct kvm *kvm, bool activate)
1739 mutex_lock(&kvm->slots_lock);
1741 * During kvm_destroy_vm(), kvm_pit_set_reinject() could trigger
1742 * APICv mode change, which update APIC_ACCESS_PAGE_PRIVATE_MEMSLOT
1743 * memory region. So, we need to ensure that kvm->mm == current->mm.
1745 if ((kvm->arch.apic_access_page_done == activate) ||
1746 (kvm->mm != current->mm))
1749 ret = __x86_set_memory_region(kvm,
1750 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1751 APIC_DEFAULT_PHYS_BASE,
1752 activate ? PAGE_SIZE : 0);
1756 kvm->arch.apic_access_page_done = activate;
1758 mutex_unlock(&kvm->slots_lock);
1762 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1764 u64 *entry, new_entry;
1765 int id = vcpu->vcpu_id;
1766 struct vcpu_svm *svm = to_svm(vcpu);
1768 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1771 if (!svm->vcpu.arch.apic->regs)
1774 if (kvm_apicv_activated(vcpu->kvm)) {
1777 ret = avic_update_access_page(vcpu->kvm, true);
1782 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1784 /* Setting AVIC backing page address in the phy APIC ID table */
1785 entry = avic_get_physical_id_entry(vcpu, id);
1789 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1790 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1791 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1792 WRITE_ONCE(*entry, new_entry);
1794 svm->avic_physical_id_cache = entry;
1799 static void sev_asid_free(int asid)
1801 struct svm_cpu_data *sd;
1804 mutex_lock(&sev_bitmap_lock);
1807 __set_bit(pos, sev_reclaim_asid_bitmap);
1809 for_each_possible_cpu(cpu) {
1810 sd = per_cpu(svm_data, cpu);
1811 sd->sev_vmcbs[pos] = NULL;
1814 mutex_unlock(&sev_bitmap_lock);
1817 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1819 struct sev_data_decommission *decommission;
1820 struct sev_data_deactivate *data;
1825 data = kzalloc(sizeof(*data), GFP_KERNEL);
1829 /* deactivate handle */
1830 data->handle = handle;
1832 /* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
1833 down_read(&sev_deactivate_lock);
1834 sev_guest_deactivate(data, NULL);
1835 up_read(&sev_deactivate_lock);
1839 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1843 /* decommission handle */
1844 decommission->handle = handle;
1845 sev_guest_decommission(decommission, NULL);
1847 kfree(decommission);
1850 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1851 unsigned long ulen, unsigned long *n,
1854 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1855 unsigned long npages, npinned, size;
1856 unsigned long locked, lock_limit;
1857 struct page **pages;
1858 unsigned long first, last;
1860 if (ulen == 0 || uaddr + ulen < uaddr)
1863 /* Calculate number of pages. */
1864 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1865 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1866 npages = (last - first + 1);
1868 locked = sev->pages_locked + npages;
1869 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1870 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1871 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1875 /* Avoid using vmalloc for smaller buffers. */
1876 size = npages * sizeof(struct page *);
1877 if (size > PAGE_SIZE)
1878 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1881 pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
1886 /* Pin the user virtual address. */
1887 npinned = get_user_pages_fast(uaddr, npages, FOLL_WRITE, pages);
1888 if (npinned != npages) {
1889 pr_err("SEV: Failure locking %lu pages.\n", npages);
1894 sev->pages_locked = locked;
1900 release_pages(pages, npinned);
1906 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1907 unsigned long npages)
1909 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1911 release_pages(pages, npages);
1913 sev->pages_locked -= npages;
1916 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1918 uint8_t *page_virtual;
1921 if (npages == 0 || pages == NULL)
1924 for (i = 0; i < npages; i++) {
1925 page_virtual = kmap_atomic(pages[i]);
1926 clflush_cache_range(page_virtual, PAGE_SIZE);
1927 kunmap_atomic(page_virtual);
1931 static void __unregister_enc_region_locked(struct kvm *kvm,
1932 struct enc_region *region)
1935 * The guest may change the memory encryption attribute from C=0 -> C=1
1936 * or vice versa for this memory range. Lets make sure caches are
1937 * flushed to ensure that guest data gets written into memory with
1940 sev_clflush_pages(region->pages, region->npages);
1942 sev_unpin_memory(kvm, region->pages, region->npages);
1943 list_del(®ion->list);
1947 static struct kvm *svm_vm_alloc(void)
1949 struct kvm_svm *kvm_svm = __vmalloc(sizeof(struct kvm_svm),
1950 GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1952 return &kvm_svm->kvm;
1955 static void svm_vm_free(struct kvm *kvm)
1957 vfree(to_kvm_svm(kvm));
1960 static void sev_vm_destroy(struct kvm *kvm)
1962 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1963 struct list_head *head = &sev->regions_list;
1964 struct list_head *pos, *q;
1966 if (!sev_guest(kvm))
1969 mutex_lock(&kvm->lock);
1972 * if userspace was terminated before unregistering the memory regions
1973 * then lets unpin all the registered memory.
1975 if (!list_empty(head)) {
1976 list_for_each_safe(pos, q, head) {
1977 __unregister_enc_region_locked(kvm,
1978 list_entry(pos, struct enc_region, list));
1982 mutex_unlock(&kvm->lock);
1984 sev_unbind_asid(kvm, sev->handle);
1985 sev_asid_free(sev->asid);
1988 static void avic_vm_destroy(struct kvm *kvm)
1990 unsigned long flags;
1991 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1996 if (kvm_svm->avic_logical_id_table_page)
1997 __free_page(kvm_svm->avic_logical_id_table_page);
1998 if (kvm_svm->avic_physical_id_table_page)
1999 __free_page(kvm_svm->avic_physical_id_table_page);
2001 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2002 hash_del(&kvm_svm->hnode);
2003 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2006 static void svm_vm_destroy(struct kvm *kvm)
2008 avic_vm_destroy(kvm);
2009 sev_vm_destroy(kvm);
2012 static int avic_vm_init(struct kvm *kvm)
2014 unsigned long flags;
2016 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
2018 struct page *p_page;
2019 struct page *l_page;
2025 /* Allocating physical APIC ID table (4KB) */
2026 p_page = alloc_page(GFP_KERNEL_ACCOUNT);
2030 kvm_svm->avic_physical_id_table_page = p_page;
2031 clear_page(page_address(p_page));
2033 /* Allocating logical APIC ID table (4KB) */
2034 l_page = alloc_page(GFP_KERNEL_ACCOUNT);
2038 kvm_svm->avic_logical_id_table_page = l_page;
2039 clear_page(page_address(l_page));
2041 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2043 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
2044 if (vm_id == 0) { /* id is 1-based, zero is not okay */
2045 next_vm_id_wrapped = 1;
2048 /* Is it still in use? Only possible if wrapped at least once */
2049 if (next_vm_id_wrapped) {
2050 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
2051 if (k2->avic_vm_id == vm_id)
2055 kvm_svm->avic_vm_id = vm_id;
2056 hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
2057 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2062 avic_vm_destroy(kvm);
2066 static int svm_vm_init(struct kvm *kvm)
2069 int ret = avic_vm_init(kvm);
2074 kvm_apicv_init(kvm, avic);
2079 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
2082 unsigned long flags;
2083 struct amd_svm_iommu_ir *ir;
2084 struct vcpu_svm *svm = to_svm(vcpu);
2086 if (!kvm_arch_has_assigned_device(vcpu->kvm))
2090 * Here, we go through the per-vcpu ir_list to update all existing
2091 * interrupt remapping table entry targeting this vcpu.
2093 spin_lock_irqsave(&svm->ir_list_lock, flags);
2095 if (list_empty(&svm->ir_list))
2098 list_for_each_entry(ir, &svm->ir_list, node) {
2099 ret = amd_iommu_update_ga(cpu, r, ir->data);
2104 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2108 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2111 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2112 int h_physical_id = kvm_cpu_get_apicid(cpu);
2113 struct vcpu_svm *svm = to_svm(vcpu);
2115 if (!kvm_vcpu_apicv_active(vcpu))
2119 * Since the host physical APIC id is 8 bits,
2120 * we can support host APIC ID upto 255.
2122 if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
2125 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2126 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2128 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2129 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2131 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2132 if (svm->avic_is_running)
2133 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2135 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2136 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2137 svm->avic_is_running);
2140 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2143 struct vcpu_svm *svm = to_svm(vcpu);
2145 if (!kvm_vcpu_apicv_active(vcpu))
2148 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2149 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2150 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2152 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2153 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2157 * This function is called during VCPU halt/unhalt.
2159 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2161 struct vcpu_svm *svm = to_svm(vcpu);
2163 svm->avic_is_running = is_run;
2165 avic_vcpu_load(vcpu, vcpu->cpu);
2167 avic_vcpu_put(vcpu);
2170 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2172 struct vcpu_svm *svm = to_svm(vcpu);
2177 svm->virt_spec_ctrl = 0;
2180 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2181 MSR_IA32_APICBASE_ENABLE;
2182 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2183 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2187 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2188 kvm_rdx_write(vcpu, eax);
2190 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2191 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2194 static int avic_init_vcpu(struct vcpu_svm *svm)
2198 if (!kvm_vcpu_apicv_active(&svm->vcpu))
2201 ret = avic_init_backing_page(&svm->vcpu);
2205 INIT_LIST_HEAD(&svm->ir_list);
2206 spin_lock_init(&svm->ir_list_lock);
2207 svm->dfr_reg = APIC_DFR_FLAT;
2212 static int svm_create_vcpu(struct kvm_vcpu *vcpu)
2214 struct vcpu_svm *svm;
2216 struct page *msrpm_pages;
2217 struct page *hsave_page;
2218 struct page *nested_msrpm_pages;
2221 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
2225 page = alloc_page(GFP_KERNEL_ACCOUNT);
2229 msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2233 nested_msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2234 if (!nested_msrpm_pages)
2237 hsave_page = alloc_page(GFP_KERNEL_ACCOUNT);
2241 err = avic_init_vcpu(svm);
2245 /* We initialize this flag to true to make sure that the is_running
2246 * bit would be set the first time the vcpu is loaded.
2248 if (irqchip_in_kernel(vcpu->kvm) && kvm_apicv_activated(vcpu->kvm))
2249 svm->avic_is_running = true;
2251 svm->nested.hsave = page_address(hsave_page);
2253 svm->msrpm = page_address(msrpm_pages);
2254 svm_vcpu_init_msrpm(svm->msrpm);
2256 svm->nested.msrpm = page_address(nested_msrpm_pages);
2257 svm_vcpu_init_msrpm(svm->nested.msrpm);
2259 svm->vmcb = page_address(page);
2260 clear_page(svm->vmcb);
2261 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2262 svm->asid_generation = 0;
2265 svm_init_osvw(vcpu);
2266 vcpu->arch.microcode_version = 0x01000065;
2271 __free_page(hsave_page);
2273 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2275 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2282 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2286 for_each_online_cpu(i)
2287 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2290 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2292 struct vcpu_svm *svm = to_svm(vcpu);
2295 * The vmcb page can be recycled, causing a false negative in
2296 * svm_vcpu_load(). So, ensure that no logical CPU has this
2297 * vmcb page recorded as its current vmcb.
2299 svm_clear_current_vmcb(svm->vmcb);
2301 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2302 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2303 __free_page(virt_to_page(svm->nested.hsave));
2304 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2307 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2309 struct vcpu_svm *svm = to_svm(vcpu);
2310 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2313 if (unlikely(cpu != vcpu->cpu)) {
2314 svm->asid_generation = 0;
2315 mark_all_dirty(svm->vmcb);
2318 #ifdef CONFIG_X86_64
2319 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2321 savesegment(fs, svm->host.fs);
2322 savesegment(gs, svm->host.gs);
2323 svm->host.ldt = kvm_read_ldt();
2325 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2326 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2328 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2329 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2330 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2331 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2332 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2335 /* This assumes that the kernel never uses MSR_TSC_AUX */
2336 if (static_cpu_has(X86_FEATURE_RDTSCP))
2337 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2339 if (sd->current_vmcb != svm->vmcb) {
2340 sd->current_vmcb = svm->vmcb;
2341 indirect_branch_prediction_barrier();
2343 avic_vcpu_load(vcpu, cpu);
2346 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2348 struct vcpu_svm *svm = to_svm(vcpu);
2351 avic_vcpu_put(vcpu);
2353 ++vcpu->stat.host_state_reload;
2354 kvm_load_ldt(svm->host.ldt);
2355 #ifdef CONFIG_X86_64
2356 loadsegment(fs, svm->host.fs);
2357 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2358 load_gs_index(svm->host.gs);
2360 #ifdef CONFIG_X86_32_LAZY_GS
2361 loadsegment(gs, svm->host.gs);
2364 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2365 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2368 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2370 avic_set_running(vcpu, false);
2373 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2375 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
2376 kvm_vcpu_update_apicv(vcpu);
2377 avic_set_running(vcpu, true);
2380 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2382 struct vcpu_svm *svm = to_svm(vcpu);
2383 unsigned long rflags = svm->vmcb->save.rflags;
2385 if (svm->nmi_singlestep) {
2386 /* Hide our flags if they were not set by the guest */
2387 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2388 rflags &= ~X86_EFLAGS_TF;
2389 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2390 rflags &= ~X86_EFLAGS_RF;
2395 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2397 if (to_svm(vcpu)->nmi_singlestep)
2398 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2401 * Any change of EFLAGS.VM is accompanied by a reload of SS
2402 * (caused by either a task switch or an inter-privilege IRET),
2403 * so we do not need to update the CPL here.
2405 to_svm(vcpu)->vmcb->save.rflags = rflags;
2408 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2411 case VCPU_EXREG_PDPTR:
2412 BUG_ON(!npt_enabled);
2413 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2420 static void svm_set_vintr(struct vcpu_svm *svm)
2422 set_intercept(svm, INTERCEPT_VINTR);
2425 static void svm_clear_vintr(struct vcpu_svm *svm)
2427 clr_intercept(svm, INTERCEPT_VINTR);
2430 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2432 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2435 case VCPU_SREG_CS: return &save->cs;
2436 case VCPU_SREG_DS: return &save->ds;
2437 case VCPU_SREG_ES: return &save->es;
2438 case VCPU_SREG_FS: return &save->fs;
2439 case VCPU_SREG_GS: return &save->gs;
2440 case VCPU_SREG_SS: return &save->ss;
2441 case VCPU_SREG_TR: return &save->tr;
2442 case VCPU_SREG_LDTR: return &save->ldtr;
2448 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2450 struct vmcb_seg *s = svm_seg(vcpu, seg);
2455 static void svm_get_segment(struct kvm_vcpu *vcpu,
2456 struct kvm_segment *var, int seg)
2458 struct vmcb_seg *s = svm_seg(vcpu, seg);
2460 var->base = s->base;
2461 var->limit = s->limit;
2462 var->selector = s->selector;
2463 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2464 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2465 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2466 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2467 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2468 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2469 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2472 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2473 * However, the SVM spec states that the G bit is not observed by the
2474 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2475 * So let's synthesize a legal G bit for all segments, this helps
2476 * running KVM nested. It also helps cross-vendor migration, because
2477 * Intel's vmentry has a check on the 'G' bit.
2479 var->g = s->limit > 0xfffff;
2482 * AMD's VMCB does not have an explicit unusable field, so emulate it
2483 * for cross vendor migration purposes by "not present"
2485 var->unusable = !var->present;
2490 * Work around a bug where the busy flag in the tr selector
2500 * The accessed bit must always be set in the segment
2501 * descriptor cache, although it can be cleared in the
2502 * descriptor, the cached bit always remains at 1. Since
2503 * Intel has a check on this, set it here to support
2504 * cross-vendor migration.
2511 * On AMD CPUs sometimes the DB bit in the segment
2512 * descriptor is left as 1, although the whole segment has
2513 * been made unusable. Clear it here to pass an Intel VMX
2514 * entry check when cross vendor migrating.
2518 /* This is symmetric with svm_set_segment() */
2519 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2524 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2526 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2531 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2533 struct vcpu_svm *svm = to_svm(vcpu);
2535 dt->size = svm->vmcb->save.idtr.limit;
2536 dt->address = svm->vmcb->save.idtr.base;
2539 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2541 struct vcpu_svm *svm = to_svm(vcpu);
2543 svm->vmcb->save.idtr.limit = dt->size;
2544 svm->vmcb->save.idtr.base = dt->address ;
2545 mark_dirty(svm->vmcb, VMCB_DT);
2548 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2550 struct vcpu_svm *svm = to_svm(vcpu);
2552 dt->size = svm->vmcb->save.gdtr.limit;
2553 dt->address = svm->vmcb->save.gdtr.base;
2556 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2558 struct vcpu_svm *svm = to_svm(vcpu);
2560 svm->vmcb->save.gdtr.limit = dt->size;
2561 svm->vmcb->save.gdtr.base = dt->address ;
2562 mark_dirty(svm->vmcb, VMCB_DT);
2565 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2569 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2573 static void update_cr0_intercept(struct vcpu_svm *svm)
2575 ulong gcr0 = svm->vcpu.arch.cr0;
2576 u64 *hcr0 = &svm->vmcb->save.cr0;
2578 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2579 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2581 mark_dirty(svm->vmcb, VMCB_CR);
2583 if (gcr0 == *hcr0) {
2584 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2585 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2587 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2588 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2592 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2594 struct vcpu_svm *svm = to_svm(vcpu);
2596 #ifdef CONFIG_X86_64
2597 if (vcpu->arch.efer & EFER_LME) {
2598 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2599 vcpu->arch.efer |= EFER_LMA;
2600 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2603 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2604 vcpu->arch.efer &= ~EFER_LMA;
2605 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2609 vcpu->arch.cr0 = cr0;
2612 cr0 |= X86_CR0_PG | X86_CR0_WP;
2615 * re-enable caching here because the QEMU bios
2616 * does not do it - this results in some delay at
2619 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2620 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2621 svm->vmcb->save.cr0 = cr0;
2622 mark_dirty(svm->vmcb, VMCB_CR);
2623 update_cr0_intercept(svm);
2626 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2628 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2629 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2631 if (cr4 & X86_CR4_VMXE)
2634 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2635 svm_flush_tlb(vcpu, true);
2637 vcpu->arch.cr4 = cr4;
2640 cr4 |= host_cr4_mce;
2641 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2642 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2646 static void svm_set_segment(struct kvm_vcpu *vcpu,
2647 struct kvm_segment *var, int seg)
2649 struct vcpu_svm *svm = to_svm(vcpu);
2650 struct vmcb_seg *s = svm_seg(vcpu, seg);
2652 s->base = var->base;
2653 s->limit = var->limit;
2654 s->selector = var->selector;
2655 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2656 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2657 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2658 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2659 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2660 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2661 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2662 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2665 * This is always accurate, except if SYSRET returned to a segment
2666 * with SS.DPL != 3. Intel does not have this quirk, and always
2667 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2668 * would entail passing the CPL to userspace and back.
2670 if (seg == VCPU_SREG_SS)
2671 /* This is symmetric with svm_get_segment() */
2672 svm->vmcb->save.cpl = (var->dpl & 3);
2674 mark_dirty(svm->vmcb, VMCB_SEG);
2677 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2679 struct vcpu_svm *svm = to_svm(vcpu);
2681 clr_exception_intercept(svm, BP_VECTOR);
2683 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2684 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2685 set_exception_intercept(svm, BP_VECTOR);
2687 vcpu->guest_debug = 0;
2690 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2692 if (sd->next_asid > sd->max_asid) {
2693 ++sd->asid_generation;
2694 sd->next_asid = sd->min_asid;
2695 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2698 svm->asid_generation = sd->asid_generation;
2699 svm->vmcb->control.asid = sd->next_asid++;
2701 mark_dirty(svm->vmcb, VMCB_ASID);
2704 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2706 return to_svm(vcpu)->vmcb->save.dr6;
2709 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2711 struct vcpu_svm *svm = to_svm(vcpu);
2713 svm->vmcb->save.dr6 = value;
2714 mark_dirty(svm->vmcb, VMCB_DR);
2717 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2719 struct vcpu_svm *svm = to_svm(vcpu);
2721 get_debugreg(vcpu->arch.db[0], 0);
2722 get_debugreg(vcpu->arch.db[1], 1);
2723 get_debugreg(vcpu->arch.db[2], 2);
2724 get_debugreg(vcpu->arch.db[3], 3);
2725 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2726 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2728 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2729 set_dr_intercepts(svm);
2732 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2734 struct vcpu_svm *svm = to_svm(vcpu);
2736 svm->vmcb->save.dr7 = value;
2737 mark_dirty(svm->vmcb, VMCB_DR);
2740 static int pf_interception(struct vcpu_svm *svm)
2742 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2743 u64 error_code = svm->vmcb->control.exit_info_1;
2745 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2746 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2747 svm->vmcb->control.insn_bytes : NULL,
2748 svm->vmcb->control.insn_len);
2751 static int npf_interception(struct vcpu_svm *svm)
2753 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2754 u64 error_code = svm->vmcb->control.exit_info_1;
2756 trace_kvm_page_fault(fault_address, error_code);
2757 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2758 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2759 svm->vmcb->control.insn_bytes : NULL,
2760 svm->vmcb->control.insn_len);
2763 static int db_interception(struct vcpu_svm *svm)
2765 struct kvm_run *kvm_run = svm->vcpu.run;
2766 struct kvm_vcpu *vcpu = &svm->vcpu;
2768 if (!(svm->vcpu.guest_debug &
2769 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2770 !svm->nmi_singlestep) {
2771 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2775 if (svm->nmi_singlestep) {
2776 disable_nmi_singlestep(svm);
2777 /* Make sure we check for pending NMIs upon entry */
2778 kvm_make_request(KVM_REQ_EVENT, vcpu);
2781 if (svm->vcpu.guest_debug &
2782 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2783 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2784 kvm_run->debug.arch.pc =
2785 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2786 kvm_run->debug.arch.exception = DB_VECTOR;
2793 static int bp_interception(struct vcpu_svm *svm)
2795 struct kvm_run *kvm_run = svm->vcpu.run;
2797 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2798 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2799 kvm_run->debug.arch.exception = BP_VECTOR;
2803 static int ud_interception(struct vcpu_svm *svm)
2805 return handle_ud(&svm->vcpu);
2808 static int ac_interception(struct vcpu_svm *svm)
2810 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2814 static int gp_interception(struct vcpu_svm *svm)
2816 struct kvm_vcpu *vcpu = &svm->vcpu;
2817 u32 error_code = svm->vmcb->control.exit_info_1;
2819 WARN_ON_ONCE(!enable_vmware_backdoor);
2822 * VMware backdoor emulation on #GP interception only handles IN{S},
2823 * OUT{S}, and RDPMC, none of which generate a non-zero error code.
2826 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2829 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
2832 static bool is_erratum_383(void)
2837 if (!erratum_383_found)
2840 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2844 /* Bit 62 may or may not be set for this mce */
2845 value &= ~(1ULL << 62);
2847 if (value != 0xb600000000010015ULL)
2850 /* Clear MCi_STATUS registers */
2851 for (i = 0; i < 6; ++i)
2852 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2854 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2858 value &= ~(1ULL << 2);
2859 low = lower_32_bits(value);
2860 high = upper_32_bits(value);
2862 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2865 /* Flush tlb to evict multi-match entries */
2871 static void svm_handle_mce(struct vcpu_svm *svm)
2873 if (is_erratum_383()) {
2875 * Erratum 383 triggered. Guest state is corrupt so kill the
2878 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2880 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2886 * On an #MC intercept the MCE handler is not called automatically in
2887 * the host. So do it by hand here.
2891 /* not sure if we ever come back to this point */
2896 static int mc_interception(struct vcpu_svm *svm)
2901 static int shutdown_interception(struct vcpu_svm *svm)
2903 struct kvm_run *kvm_run = svm->vcpu.run;
2906 * VMCB is undefined after a SHUTDOWN intercept
2907 * so reinitialize it.
2909 clear_page(svm->vmcb);
2912 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2916 static int io_interception(struct vcpu_svm *svm)
2918 struct kvm_vcpu *vcpu = &svm->vcpu;
2919 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2920 int size, in, string;
2923 ++svm->vcpu.stat.io_exits;
2924 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2925 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2927 return kvm_emulate_instruction(vcpu, 0);
2929 port = io_info >> 16;
2930 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2931 svm->next_rip = svm->vmcb->control.exit_info_2;
2933 return kvm_fast_pio(&svm->vcpu, size, port, in);
2936 static int nmi_interception(struct vcpu_svm *svm)
2941 static int intr_interception(struct vcpu_svm *svm)
2943 ++svm->vcpu.stat.irq_exits;
2947 static int nop_on_interception(struct vcpu_svm *svm)
2952 static int halt_interception(struct vcpu_svm *svm)
2954 return kvm_emulate_halt(&svm->vcpu);
2957 static int vmmcall_interception(struct vcpu_svm *svm)
2959 return kvm_emulate_hypercall(&svm->vcpu);
2962 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2964 struct vcpu_svm *svm = to_svm(vcpu);
2966 return svm->nested.nested_cr3;
2969 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2971 struct vcpu_svm *svm = to_svm(vcpu);
2972 u64 cr3 = svm->nested.nested_cr3;
2976 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2977 offset_in_page(cr3) + index * 8, 8);
2983 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2986 struct vcpu_svm *svm = to_svm(vcpu);
2988 svm->vmcb->control.nested_cr3 = __sme_set(root);
2989 mark_dirty(svm->vmcb, VMCB_NPT);
2992 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2993 struct x86_exception *fault)
2995 struct vcpu_svm *svm = to_svm(vcpu);
2997 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2999 * TODO: track the cause of the nested page fault, and
3000 * correctly fill in the high bits of exit_info_1.
3002 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
3003 svm->vmcb->control.exit_code_hi = 0;
3004 svm->vmcb->control.exit_info_1 = (1ULL << 32);
3005 svm->vmcb->control.exit_info_2 = fault->address;
3008 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
3009 svm->vmcb->control.exit_info_1 |= fault->error_code;
3012 * The present bit is always zero for page structure faults on real
3015 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
3016 svm->vmcb->control.exit_info_1 &= ~1;
3018 nested_svm_vmexit(svm);
3021 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
3023 WARN_ON(mmu_is_nested(vcpu));
3025 vcpu->arch.mmu = &vcpu->arch.guest_mmu;
3026 kvm_init_shadow_mmu(vcpu);
3027 vcpu->arch.mmu->set_cr3 = nested_svm_set_tdp_cr3;
3028 vcpu->arch.mmu->get_cr3 = nested_svm_get_tdp_cr3;
3029 vcpu->arch.mmu->get_pdptr = nested_svm_get_tdp_pdptr;
3030 vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
3031 vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
3032 reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
3033 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
3036 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
3038 vcpu->arch.mmu = &vcpu->arch.root_mmu;
3039 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
3042 static int nested_svm_check_permissions(struct vcpu_svm *svm)
3044 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
3045 !is_paging(&svm->vcpu)) {
3046 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3050 if (svm->vmcb->save.cpl) {
3051 kvm_inject_gp(&svm->vcpu, 0);
3058 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
3059 bool has_error_code, u32 error_code)
3063 if (!is_guest_mode(&svm->vcpu))
3066 vmexit = nested_svm_intercept(svm);
3067 if (vmexit != NESTED_EXIT_DONE)
3070 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
3071 svm->vmcb->control.exit_code_hi = 0;
3072 svm->vmcb->control.exit_info_1 = error_code;
3075 * EXITINFO2 is undefined for all exception intercepts other
3078 if (svm->vcpu.arch.exception.nested_apf)
3079 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3080 else if (svm->vcpu.arch.exception.has_payload)
3081 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
3083 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3085 svm->nested.exit_required = true;
3089 /* This function returns true if it is save to enable the irq window */
3090 static inline bool nested_svm_intr(struct vcpu_svm *svm)
3092 if (!is_guest_mode(&svm->vcpu))
3095 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3098 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3102 * if vmexit was already requested (by intercepted exception
3103 * for instance) do not overwrite it with "external interrupt"
3106 if (svm->nested.exit_required)
3109 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
3110 svm->vmcb->control.exit_info_1 = 0;
3111 svm->vmcb->control.exit_info_2 = 0;
3113 if (svm->nested.intercept & 1ULL) {
3115 * The #vmexit can't be emulated here directly because this
3116 * code path runs with irqs and preemption disabled. A
3117 * #vmexit emulation might sleep. Only signal request for
3120 svm->nested.exit_required = true;
3121 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3128 /* This function returns true if it is save to enable the nmi window */
3129 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3131 if (!is_guest_mode(&svm->vcpu))
3134 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3137 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3138 svm->nested.exit_required = true;
3143 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3145 unsigned port, size, iopm_len;
3150 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3151 return NESTED_EXIT_HOST;
3153 port = svm->vmcb->control.exit_info_1 >> 16;
3154 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3155 SVM_IOIO_SIZE_SHIFT;
3156 gpa = svm->nested.vmcb_iopm + (port / 8);
3157 start_bit = port % 8;
3158 iopm_len = (start_bit + size > 8) ? 2 : 1;
3159 mask = (0xf >> (4 - size)) << start_bit;
3162 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3163 return NESTED_EXIT_DONE;
3165 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3168 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3170 u32 offset, msr, value;
3173 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3174 return NESTED_EXIT_HOST;
3176 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3177 offset = svm_msrpm_offset(msr);
3178 write = svm->vmcb->control.exit_info_1 & 1;
3179 mask = 1 << ((2 * (msr & 0xf)) + write);
3181 if (offset == MSR_INVALID)
3182 return NESTED_EXIT_DONE;
3184 /* Offset is in 32 bit units but need in 8 bit units */
3187 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3188 return NESTED_EXIT_DONE;
3190 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3193 /* DB exceptions for our internal use must not cause vmexit */
3194 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3198 /* if we're not singlestepping, it's not ours */
3199 if (!svm->nmi_singlestep)
3200 return NESTED_EXIT_DONE;
3202 /* if it's not a singlestep exception, it's not ours */
3203 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3204 return NESTED_EXIT_DONE;
3205 if (!(dr6 & DR6_BS))
3206 return NESTED_EXIT_DONE;
3208 /* if the guest is singlestepping, it should get the vmexit */
3209 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3210 disable_nmi_singlestep(svm);
3211 return NESTED_EXIT_DONE;
3214 /* it's ours, the nested hypervisor must not see this one */
3215 return NESTED_EXIT_HOST;
3218 static int nested_svm_exit_special(struct vcpu_svm *svm)
3220 u32 exit_code = svm->vmcb->control.exit_code;
3222 switch (exit_code) {
3225 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3226 return NESTED_EXIT_HOST;
3228 /* For now we are always handling NPFs when using them */
3230 return NESTED_EXIT_HOST;
3232 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3233 /* When we're shadowing, trap PFs, but not async PF */
3234 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3235 return NESTED_EXIT_HOST;
3241 return NESTED_EXIT_CONTINUE;
3245 * If this function returns true, this #vmexit was already handled
3247 static int nested_svm_intercept(struct vcpu_svm *svm)
3249 u32 exit_code = svm->vmcb->control.exit_code;
3250 int vmexit = NESTED_EXIT_HOST;
3252 switch (exit_code) {
3254 vmexit = nested_svm_exit_handled_msr(svm);
3257 vmexit = nested_svm_intercept_ioio(svm);
3259 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3260 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3261 if (svm->nested.intercept_cr & bit)
3262 vmexit = NESTED_EXIT_DONE;
3265 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3266 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3267 if (svm->nested.intercept_dr & bit)
3268 vmexit = NESTED_EXIT_DONE;
3271 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3272 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3273 if (svm->nested.intercept_exceptions & excp_bits) {
3274 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3275 vmexit = nested_svm_intercept_db(svm);
3277 vmexit = NESTED_EXIT_DONE;
3279 /* async page fault always cause vmexit */
3280 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3281 svm->vcpu.arch.exception.nested_apf != 0)
3282 vmexit = NESTED_EXIT_DONE;
3285 case SVM_EXIT_ERR: {
3286 vmexit = NESTED_EXIT_DONE;
3290 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3291 if (svm->nested.intercept & exit_bits)
3292 vmexit = NESTED_EXIT_DONE;
3299 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3303 vmexit = nested_svm_intercept(svm);
3305 if (vmexit == NESTED_EXIT_DONE)
3306 nested_svm_vmexit(svm);
3311 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3313 struct vmcb_control_area *dst = &dst_vmcb->control;
3314 struct vmcb_control_area *from = &from_vmcb->control;
3316 dst->intercept_cr = from->intercept_cr;
3317 dst->intercept_dr = from->intercept_dr;
3318 dst->intercept_exceptions = from->intercept_exceptions;
3319 dst->intercept = from->intercept;
3320 dst->iopm_base_pa = from->iopm_base_pa;
3321 dst->msrpm_base_pa = from->msrpm_base_pa;
3322 dst->tsc_offset = from->tsc_offset;
3323 dst->asid = from->asid;
3324 dst->tlb_ctl = from->tlb_ctl;
3325 dst->int_ctl = from->int_ctl;
3326 dst->int_vector = from->int_vector;
3327 dst->int_state = from->int_state;
3328 dst->exit_code = from->exit_code;
3329 dst->exit_code_hi = from->exit_code_hi;
3330 dst->exit_info_1 = from->exit_info_1;
3331 dst->exit_info_2 = from->exit_info_2;
3332 dst->exit_int_info = from->exit_int_info;
3333 dst->exit_int_info_err = from->exit_int_info_err;
3334 dst->nested_ctl = from->nested_ctl;
3335 dst->event_inj = from->event_inj;
3336 dst->event_inj_err = from->event_inj_err;
3337 dst->nested_cr3 = from->nested_cr3;
3338 dst->virt_ext = from->virt_ext;
3339 dst->pause_filter_count = from->pause_filter_count;
3340 dst->pause_filter_thresh = from->pause_filter_thresh;
3343 static int nested_svm_vmexit(struct vcpu_svm *svm)
3346 struct vmcb *nested_vmcb;
3347 struct vmcb *hsave = svm->nested.hsave;
3348 struct vmcb *vmcb = svm->vmcb;
3349 struct kvm_host_map map;
3351 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3352 vmcb->control.exit_info_1,
3353 vmcb->control.exit_info_2,
3354 vmcb->control.exit_int_info,
3355 vmcb->control.exit_int_info_err,
3358 rc = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->nested.vmcb), &map);
3361 kvm_inject_gp(&svm->vcpu, 0);
3365 nested_vmcb = map.hva;
3367 /* Exit Guest-Mode */
3368 leave_guest_mode(&svm->vcpu);
3369 svm->nested.vmcb = 0;
3371 /* Give the current vmcb to the guest */
3374 nested_vmcb->save.es = vmcb->save.es;
3375 nested_vmcb->save.cs = vmcb->save.cs;
3376 nested_vmcb->save.ss = vmcb->save.ss;
3377 nested_vmcb->save.ds = vmcb->save.ds;
3378 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3379 nested_vmcb->save.idtr = vmcb->save.idtr;
3380 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3381 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3382 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3383 nested_vmcb->save.cr2 = vmcb->save.cr2;
3384 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3385 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3386 nested_vmcb->save.rip = vmcb->save.rip;
3387 nested_vmcb->save.rsp = vmcb->save.rsp;
3388 nested_vmcb->save.rax = vmcb->save.rax;
3389 nested_vmcb->save.dr7 = vmcb->save.dr7;
3390 nested_vmcb->save.dr6 = vmcb->save.dr6;
3391 nested_vmcb->save.cpl = vmcb->save.cpl;
3393 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3394 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3395 nested_vmcb->control.int_state = vmcb->control.int_state;
3396 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3397 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3398 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3399 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3400 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3401 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3403 if (svm->nrips_enabled)
3404 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3407 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3408 * to make sure that we do not lose injected events. So check event_inj
3409 * here and copy it to exit_int_info if it is valid.
3410 * Exit_int_info and event_inj can't be both valid because the case
3411 * below only happens on a VMRUN instruction intercept which has
3412 * no valid exit_int_info set.
3414 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3415 struct vmcb_control_area *nc = &nested_vmcb->control;
3417 nc->exit_int_info = vmcb->control.event_inj;
3418 nc->exit_int_info_err = vmcb->control.event_inj_err;
3421 nested_vmcb->control.tlb_ctl = 0;
3422 nested_vmcb->control.event_inj = 0;
3423 nested_vmcb->control.event_inj_err = 0;
3425 nested_vmcb->control.pause_filter_count =
3426 svm->vmcb->control.pause_filter_count;
3427 nested_vmcb->control.pause_filter_thresh =
3428 svm->vmcb->control.pause_filter_thresh;
3430 /* We always set V_INTR_MASKING and remember the old value in hflags */
3431 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3432 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3434 /* Restore the original control entries */
3435 copy_vmcb_control_area(vmcb, hsave);
3437 svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3438 kvm_clear_exception_queue(&svm->vcpu);
3439 kvm_clear_interrupt_queue(&svm->vcpu);
3441 svm->nested.nested_cr3 = 0;
3443 /* Restore selected save entries */
3444 svm->vmcb->save.es = hsave->save.es;
3445 svm->vmcb->save.cs = hsave->save.cs;
3446 svm->vmcb->save.ss = hsave->save.ss;
3447 svm->vmcb->save.ds = hsave->save.ds;
3448 svm->vmcb->save.gdtr = hsave->save.gdtr;
3449 svm->vmcb->save.idtr = hsave->save.idtr;
3450 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3451 svm_set_efer(&svm->vcpu, hsave->save.efer);
3452 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3453 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3455 svm->vmcb->save.cr3 = hsave->save.cr3;
3456 svm->vcpu.arch.cr3 = hsave->save.cr3;
3458 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3460 kvm_rax_write(&svm->vcpu, hsave->save.rax);
3461 kvm_rsp_write(&svm->vcpu, hsave->save.rsp);
3462 kvm_rip_write(&svm->vcpu, hsave->save.rip);
3463 svm->vmcb->save.dr7 = 0;
3464 svm->vmcb->save.cpl = 0;
3465 svm->vmcb->control.exit_int_info = 0;
3467 mark_all_dirty(svm->vmcb);
3469 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3471 nested_svm_uninit_mmu_context(&svm->vcpu);
3472 kvm_mmu_reset_context(&svm->vcpu);
3473 kvm_mmu_load(&svm->vcpu);
3476 * Drop what we picked up for L2 via svm_complete_interrupts() so it
3477 * doesn't end up in L1.
3479 svm->vcpu.arch.nmi_injected = false;
3480 kvm_clear_exception_queue(&svm->vcpu);
3481 kvm_clear_interrupt_queue(&svm->vcpu);
3486 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3489 * This function merges the msr permission bitmaps of kvm and the
3490 * nested vmcb. It is optimized in that it only merges the parts where
3491 * the kvm msr permission bitmap may contain zero bits
3495 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3498 for (i = 0; i < MSRPM_OFFSETS; i++) {
3502 if (msrpm_offsets[i] == 0xffffffff)
3505 p = msrpm_offsets[i];
3506 offset = svm->nested.vmcb_msrpm + (p * 4);
3508 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3511 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3514 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3519 static bool nested_vmcb_checks(struct vmcb *vmcb)
3521 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3524 if (vmcb->control.asid == 0)
3527 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3534 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3535 struct vmcb *nested_vmcb, struct kvm_host_map *map)
3537 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3538 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3540 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3542 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3543 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3544 nested_svm_init_mmu_context(&svm->vcpu);
3547 /* Load the nested guest state */
3548 svm->vmcb->save.es = nested_vmcb->save.es;
3549 svm->vmcb->save.cs = nested_vmcb->save.cs;
3550 svm->vmcb->save.ss = nested_vmcb->save.ss;
3551 svm->vmcb->save.ds = nested_vmcb->save.ds;
3552 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3553 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3554 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3555 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3556 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3557 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3559 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3560 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3562 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3564 /* Guest paging mode is active - reset mmu */
3565 kvm_mmu_reset_context(&svm->vcpu);
3567 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3568 kvm_rax_write(&svm->vcpu, nested_vmcb->save.rax);
3569 kvm_rsp_write(&svm->vcpu, nested_vmcb->save.rsp);
3570 kvm_rip_write(&svm->vcpu, nested_vmcb->save.rip);
3572 /* In case we don't even reach vcpu_run, the fields are not updated */
3573 svm->vmcb->save.rax = nested_vmcb->save.rax;
3574 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3575 svm->vmcb->save.rip = nested_vmcb->save.rip;
3576 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3577 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3578 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3580 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3581 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3583 /* cache intercepts */
3584 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3585 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3586 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3587 svm->nested.intercept = nested_vmcb->control.intercept;
3589 svm_flush_tlb(&svm->vcpu, true);
3590 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3591 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3592 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3594 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3596 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3597 /* We only want the cr8 intercept bits of the guest */
3598 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3599 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3602 /* We don't want to see VMMCALLs from a nested guest */
3603 clr_intercept(svm, INTERCEPT_VMMCALL);
3605 svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3606 svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3608 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3609 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3610 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3611 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3612 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3614 svm->vmcb->control.pause_filter_count =
3615 nested_vmcb->control.pause_filter_count;
3616 svm->vmcb->control.pause_filter_thresh =
3617 nested_vmcb->control.pause_filter_thresh;
3619 kvm_vcpu_unmap(&svm->vcpu, map, true);
3621 /* Enter Guest-Mode */
3622 enter_guest_mode(&svm->vcpu);
3625 * Merge guest and host intercepts - must be called with vcpu in
3626 * guest-mode to take affect here
3628 recalc_intercepts(svm);
3630 svm->nested.vmcb = vmcb_gpa;
3634 mark_all_dirty(svm->vmcb);
3637 static int nested_svm_vmrun(struct vcpu_svm *svm)
3640 struct vmcb *nested_vmcb;
3641 struct vmcb *hsave = svm->nested.hsave;
3642 struct vmcb *vmcb = svm->vmcb;
3643 struct kvm_host_map map;
3646 vmcb_gpa = svm->vmcb->save.rax;
3648 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb_gpa), &map);
3649 if (ret == -EINVAL) {
3650 kvm_inject_gp(&svm->vcpu, 0);
3653 return kvm_skip_emulated_instruction(&svm->vcpu);
3656 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3658 nested_vmcb = map.hva;
3660 if (!nested_vmcb_checks(nested_vmcb)) {
3661 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3662 nested_vmcb->control.exit_code_hi = 0;
3663 nested_vmcb->control.exit_info_1 = 0;
3664 nested_vmcb->control.exit_info_2 = 0;
3666 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3671 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3672 nested_vmcb->save.rip,
3673 nested_vmcb->control.int_ctl,
3674 nested_vmcb->control.event_inj,
3675 nested_vmcb->control.nested_ctl);
3677 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3678 nested_vmcb->control.intercept_cr >> 16,
3679 nested_vmcb->control.intercept_exceptions,
3680 nested_vmcb->control.intercept);
3682 /* Clear internal status */
3683 kvm_clear_exception_queue(&svm->vcpu);
3684 kvm_clear_interrupt_queue(&svm->vcpu);
3687 * Save the old vmcb, so we don't need to pick what we save, but can
3688 * restore everything when a VMEXIT occurs
3690 hsave->save.es = vmcb->save.es;
3691 hsave->save.cs = vmcb->save.cs;
3692 hsave->save.ss = vmcb->save.ss;
3693 hsave->save.ds = vmcb->save.ds;
3694 hsave->save.gdtr = vmcb->save.gdtr;
3695 hsave->save.idtr = vmcb->save.idtr;
3696 hsave->save.efer = svm->vcpu.arch.efer;
3697 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3698 hsave->save.cr4 = svm->vcpu.arch.cr4;
3699 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3700 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3701 hsave->save.rsp = vmcb->save.rsp;
3702 hsave->save.rax = vmcb->save.rax;
3704 hsave->save.cr3 = vmcb->save.cr3;
3706 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3708 copy_vmcb_control_area(hsave, vmcb);
3710 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, &map);
3712 if (!nested_svm_vmrun_msrpm(svm)) {
3713 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3714 svm->vmcb->control.exit_code_hi = 0;
3715 svm->vmcb->control.exit_info_1 = 0;
3716 svm->vmcb->control.exit_info_2 = 0;
3718 nested_svm_vmexit(svm);
3724 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3726 to_vmcb->save.fs = from_vmcb->save.fs;
3727 to_vmcb->save.gs = from_vmcb->save.gs;
3728 to_vmcb->save.tr = from_vmcb->save.tr;
3729 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3730 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3731 to_vmcb->save.star = from_vmcb->save.star;
3732 to_vmcb->save.lstar = from_vmcb->save.lstar;
3733 to_vmcb->save.cstar = from_vmcb->save.cstar;
3734 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3735 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3736 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3737 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3740 static int vmload_interception(struct vcpu_svm *svm)
3742 struct vmcb *nested_vmcb;
3743 struct kvm_host_map map;
3746 if (nested_svm_check_permissions(svm))
3749 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3752 kvm_inject_gp(&svm->vcpu, 0);
3756 nested_vmcb = map.hva;
3758 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3760 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3761 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3766 static int vmsave_interception(struct vcpu_svm *svm)
3768 struct vmcb *nested_vmcb;
3769 struct kvm_host_map map;
3772 if (nested_svm_check_permissions(svm))
3775 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3778 kvm_inject_gp(&svm->vcpu, 0);
3782 nested_vmcb = map.hva;
3784 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3786 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3787 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3792 static int vmrun_interception(struct vcpu_svm *svm)
3794 if (nested_svm_check_permissions(svm))
3797 return nested_svm_vmrun(svm);
3800 static int stgi_interception(struct vcpu_svm *svm)
3804 if (nested_svm_check_permissions(svm))
3808 * If VGIF is enabled, the STGI intercept is only added to
3809 * detect the opening of the SMI/NMI window; remove it now.
3811 if (vgif_enabled(svm))
3812 clr_intercept(svm, INTERCEPT_STGI);
3814 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3815 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3822 static int clgi_interception(struct vcpu_svm *svm)
3826 if (nested_svm_check_permissions(svm))
3829 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3833 /* After a CLGI no interrupts should come */
3834 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3835 svm_clear_vintr(svm);
3836 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3837 mark_dirty(svm->vmcb, VMCB_INTR);
3843 static int invlpga_interception(struct vcpu_svm *svm)
3845 struct kvm_vcpu *vcpu = &svm->vcpu;
3847 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_rcx_read(&svm->vcpu),
3848 kvm_rax_read(&svm->vcpu));
3850 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3851 kvm_mmu_invlpg(vcpu, kvm_rax_read(&svm->vcpu));
3853 return kvm_skip_emulated_instruction(&svm->vcpu);
3856 static int skinit_interception(struct vcpu_svm *svm)
3858 trace_kvm_skinit(svm->vmcb->save.rip, kvm_rax_read(&svm->vcpu));
3860 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3864 static int wbinvd_interception(struct vcpu_svm *svm)
3866 return kvm_emulate_wbinvd(&svm->vcpu);
3869 static int xsetbv_interception(struct vcpu_svm *svm)
3871 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3872 u32 index = kvm_rcx_read(&svm->vcpu);
3874 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3875 return kvm_skip_emulated_instruction(&svm->vcpu);
3881 static int rdpru_interception(struct vcpu_svm *svm)
3883 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3887 static int task_switch_interception(struct vcpu_svm *svm)
3891 int int_type = svm->vmcb->control.exit_int_info &
3892 SVM_EXITINTINFO_TYPE_MASK;
3893 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3895 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3897 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3898 bool has_error_code = false;
3901 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3903 if (svm->vmcb->control.exit_info_2 &
3904 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3905 reason = TASK_SWITCH_IRET;
3906 else if (svm->vmcb->control.exit_info_2 &
3907 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3908 reason = TASK_SWITCH_JMP;
3910 reason = TASK_SWITCH_GATE;
3912 reason = TASK_SWITCH_CALL;
3914 if (reason == TASK_SWITCH_GATE) {
3916 case SVM_EXITINTINFO_TYPE_NMI:
3917 svm->vcpu.arch.nmi_injected = false;
3919 case SVM_EXITINTINFO_TYPE_EXEPT:
3920 if (svm->vmcb->control.exit_info_2 &
3921 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3922 has_error_code = true;
3924 (u32)svm->vmcb->control.exit_info_2;
3926 kvm_clear_exception_queue(&svm->vcpu);
3928 case SVM_EXITINTINFO_TYPE_INTR:
3929 kvm_clear_interrupt_queue(&svm->vcpu);
3936 if (reason != TASK_SWITCH_GATE ||
3937 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3938 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3939 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
3940 if (!skip_emulated_instruction(&svm->vcpu))
3944 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3947 return kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3948 has_error_code, error_code);
3951 static int cpuid_interception(struct vcpu_svm *svm)
3953 return kvm_emulate_cpuid(&svm->vcpu);
3956 static int iret_interception(struct vcpu_svm *svm)
3958 ++svm->vcpu.stat.nmi_window_exits;
3959 clr_intercept(svm, INTERCEPT_IRET);
3960 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3961 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3962 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3966 static int invlpg_interception(struct vcpu_svm *svm)
3968 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3969 return kvm_emulate_instruction(&svm->vcpu, 0);
3971 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3972 return kvm_skip_emulated_instruction(&svm->vcpu);
3975 static int emulate_on_interception(struct vcpu_svm *svm)
3977 return kvm_emulate_instruction(&svm->vcpu, 0);
3980 static int rsm_interception(struct vcpu_svm *svm)
3982 return kvm_emulate_instruction_from_buffer(&svm->vcpu, rsm_ins_bytes, 2);
3985 static int rdpmc_interception(struct vcpu_svm *svm)
3990 return emulate_on_interception(svm);
3992 err = kvm_rdpmc(&svm->vcpu);
3993 return kvm_complete_insn_gp(&svm->vcpu, err);
3996 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3999 unsigned long cr0 = svm->vcpu.arch.cr0;
4003 intercept = svm->nested.intercept;
4005 if (!is_guest_mode(&svm->vcpu) ||
4006 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
4009 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
4010 val &= ~SVM_CR0_SELECTIVE_MASK;
4013 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4014 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
4020 #define CR_VALID (1ULL << 63)
4022 static int cr_interception(struct vcpu_svm *svm)
4028 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
4029 return emulate_on_interception(svm);
4031 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
4032 return emulate_on_interception(svm);
4034 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4035 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
4036 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
4038 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
4041 if (cr >= 16) { /* mov to cr */
4043 val = kvm_register_read(&svm->vcpu, reg);
4046 if (!check_selective_cr0_intercepted(svm, val))
4047 err = kvm_set_cr0(&svm->vcpu, val);
4053 err = kvm_set_cr3(&svm->vcpu, val);
4056 err = kvm_set_cr4(&svm->vcpu, val);
4059 err = kvm_set_cr8(&svm->vcpu, val);
4062 WARN(1, "unhandled write to CR%d", cr);
4063 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4066 } else { /* mov from cr */
4069 val = kvm_read_cr0(&svm->vcpu);
4072 val = svm->vcpu.arch.cr2;
4075 val = kvm_read_cr3(&svm->vcpu);
4078 val = kvm_read_cr4(&svm->vcpu);
4081 val = kvm_get_cr8(&svm->vcpu);
4084 WARN(1, "unhandled read from CR%d", cr);
4085 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4088 kvm_register_write(&svm->vcpu, reg, val);
4090 return kvm_complete_insn_gp(&svm->vcpu, err);
4093 static int dr_interception(struct vcpu_svm *svm)
4098 if (svm->vcpu.guest_debug == 0) {
4100 * No more DR vmexits; force a reload of the debug registers
4101 * and reenter on this instruction. The next vmexit will
4102 * retrieve the full state of the debug registers.
4104 clr_dr_intercepts(svm);
4105 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4109 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4110 return emulate_on_interception(svm);
4112 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4113 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4115 if (dr >= 16) { /* mov to DRn */
4116 if (!kvm_require_dr(&svm->vcpu, dr - 16))
4118 val = kvm_register_read(&svm->vcpu, reg);
4119 kvm_set_dr(&svm->vcpu, dr - 16, val);
4121 if (!kvm_require_dr(&svm->vcpu, dr))
4123 kvm_get_dr(&svm->vcpu, dr, &val);
4124 kvm_register_write(&svm->vcpu, reg, val);
4127 return kvm_skip_emulated_instruction(&svm->vcpu);
4130 static int cr8_write_interception(struct vcpu_svm *svm)
4132 struct kvm_run *kvm_run = svm->vcpu.run;
4135 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4136 /* instruction emulation calls kvm_set_cr8() */
4137 r = cr_interception(svm);
4138 if (lapic_in_kernel(&svm->vcpu))
4140 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4142 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4146 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4150 switch (msr->index) {
4151 case MSR_F10H_DECFG:
4152 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4153 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4162 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4164 struct vcpu_svm *svm = to_svm(vcpu);
4166 switch (msr_info->index) {
4168 msr_info->data = svm->vmcb->save.star;
4170 #ifdef CONFIG_X86_64
4172 msr_info->data = svm->vmcb->save.lstar;
4175 msr_info->data = svm->vmcb->save.cstar;
4177 case MSR_KERNEL_GS_BASE:
4178 msr_info->data = svm->vmcb->save.kernel_gs_base;
4180 case MSR_SYSCALL_MASK:
4181 msr_info->data = svm->vmcb->save.sfmask;
4184 case MSR_IA32_SYSENTER_CS:
4185 msr_info->data = svm->vmcb->save.sysenter_cs;
4187 case MSR_IA32_SYSENTER_EIP:
4188 msr_info->data = svm->sysenter_eip;
4190 case MSR_IA32_SYSENTER_ESP:
4191 msr_info->data = svm->sysenter_esp;
4194 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4196 msr_info->data = svm->tsc_aux;
4199 * Nobody will change the following 5 values in the VMCB so we can
4200 * safely return them on rdmsr. They will always be 0 until LBRV is
4203 case MSR_IA32_DEBUGCTLMSR:
4204 msr_info->data = svm->vmcb->save.dbgctl;
4206 case MSR_IA32_LASTBRANCHFROMIP:
4207 msr_info->data = svm->vmcb->save.br_from;
4209 case MSR_IA32_LASTBRANCHTOIP:
4210 msr_info->data = svm->vmcb->save.br_to;
4212 case MSR_IA32_LASTINTFROMIP:
4213 msr_info->data = svm->vmcb->save.last_excp_from;
4215 case MSR_IA32_LASTINTTOIP:
4216 msr_info->data = svm->vmcb->save.last_excp_to;
4218 case MSR_VM_HSAVE_PA:
4219 msr_info->data = svm->nested.hsave_msr;
4222 msr_info->data = svm->nested.vm_cr_msr;
4224 case MSR_IA32_SPEC_CTRL:
4225 if (!msr_info->host_initiated &&
4226 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
4227 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_STIBP) &&
4228 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4229 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4232 msr_info->data = svm->spec_ctrl;
4234 case MSR_AMD64_VIRT_SPEC_CTRL:
4235 if (!msr_info->host_initiated &&
4236 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4239 msr_info->data = svm->virt_spec_ctrl;
4241 case MSR_F15H_IC_CFG: {
4245 family = guest_cpuid_family(vcpu);
4246 model = guest_cpuid_model(vcpu);
4248 if (family < 0 || model < 0)
4249 return kvm_get_msr_common(vcpu, msr_info);
4253 if (family == 0x15 &&
4254 (model >= 0x2 && model < 0x20))
4255 msr_info->data = 0x1E;
4258 case MSR_F10H_DECFG:
4259 msr_info->data = svm->msr_decfg;
4262 return kvm_get_msr_common(vcpu, msr_info);
4267 static int rdmsr_interception(struct vcpu_svm *svm)
4269 return kvm_emulate_rdmsr(&svm->vcpu);
4272 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4274 struct vcpu_svm *svm = to_svm(vcpu);
4275 int svm_dis, chg_mask;
4277 if (data & ~SVM_VM_CR_VALID_MASK)
4280 chg_mask = SVM_VM_CR_VALID_MASK;
4282 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4283 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4285 svm->nested.vm_cr_msr &= ~chg_mask;
4286 svm->nested.vm_cr_msr |= (data & chg_mask);
4288 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4290 /* check for svm_disable while efer.svme is set */
4291 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4297 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4299 struct vcpu_svm *svm = to_svm(vcpu);
4301 u32 ecx = msr->index;
4302 u64 data = msr->data;
4304 case MSR_IA32_CR_PAT:
4305 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4307 vcpu->arch.pat = data;
4308 svm->vmcb->save.g_pat = data;
4309 mark_dirty(svm->vmcb, VMCB_NPT);
4311 case MSR_IA32_SPEC_CTRL:
4312 if (!msr->host_initiated &&
4313 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
4314 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_STIBP) &&
4315 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4316 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4319 if (data & ~kvm_spec_ctrl_valid_bits(vcpu))
4322 svm->spec_ctrl = data;
4328 * When it's written (to non-zero) for the first time, pass
4332 * The handling of the MSR bitmap for L2 guests is done in
4333 * nested_svm_vmrun_msrpm.
4334 * We update the L1 MSR bit as well since it will end up
4335 * touching the MSR anyway now.
4337 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4339 case MSR_IA32_PRED_CMD:
4340 if (!msr->host_initiated &&
4341 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4344 if (data & ~PRED_CMD_IBPB)
4346 if (!boot_cpu_has(X86_FEATURE_AMD_IBPB))
4351 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4352 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4354 case MSR_AMD64_VIRT_SPEC_CTRL:
4355 if (!msr->host_initiated &&
4356 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4359 if (data & ~SPEC_CTRL_SSBD)
4362 svm->virt_spec_ctrl = data;
4365 svm->vmcb->save.star = data;
4367 #ifdef CONFIG_X86_64
4369 svm->vmcb->save.lstar = data;
4372 svm->vmcb->save.cstar = data;
4374 case MSR_KERNEL_GS_BASE:
4375 svm->vmcb->save.kernel_gs_base = data;
4377 case MSR_SYSCALL_MASK:
4378 svm->vmcb->save.sfmask = data;
4381 case MSR_IA32_SYSENTER_CS:
4382 svm->vmcb->save.sysenter_cs = data;
4384 case MSR_IA32_SYSENTER_EIP:
4385 svm->sysenter_eip = data;
4386 svm->vmcb->save.sysenter_eip = data;
4388 case MSR_IA32_SYSENTER_ESP:
4389 svm->sysenter_esp = data;
4390 svm->vmcb->save.sysenter_esp = data;
4393 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4397 * This is rare, so we update the MSR here instead of using
4398 * direct_access_msrs. Doing that would require a rdmsr in
4401 svm->tsc_aux = data;
4402 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4404 case MSR_IA32_DEBUGCTLMSR:
4405 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4406 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4410 if (data & DEBUGCTL_RESERVED_BITS)
4413 svm->vmcb->save.dbgctl = data;
4414 mark_dirty(svm->vmcb, VMCB_LBR);
4415 if (data & (1ULL<<0))
4416 svm_enable_lbrv(svm);
4418 svm_disable_lbrv(svm);
4420 case MSR_VM_HSAVE_PA:
4421 svm->nested.hsave_msr = data;
4424 return svm_set_vm_cr(vcpu, data);
4426 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4428 case MSR_F10H_DECFG: {
4429 struct kvm_msr_entry msr_entry;
4431 msr_entry.index = msr->index;
4432 if (svm_get_msr_feature(&msr_entry))
4435 /* Check the supported bits */
4436 if (data & ~msr_entry.data)
4439 /* Don't allow the guest to change a bit, #GP */
4440 if (!msr->host_initiated && (data ^ msr_entry.data))
4443 svm->msr_decfg = data;
4446 case MSR_IA32_APICBASE:
4447 if (kvm_vcpu_apicv_active(vcpu))
4448 avic_update_vapic_bar(to_svm(vcpu), data);
4451 return kvm_set_msr_common(vcpu, msr);
4456 static int wrmsr_interception(struct vcpu_svm *svm)
4458 return kvm_emulate_wrmsr(&svm->vcpu);
4461 static int msr_interception(struct vcpu_svm *svm)
4463 if (svm->vmcb->control.exit_info_1)
4464 return wrmsr_interception(svm);
4466 return rdmsr_interception(svm);
4469 static int interrupt_window_interception(struct vcpu_svm *svm)
4471 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4472 svm_clear_vintr(svm);
4475 * For AVIC, the only reason to end up here is ExtINTs.
4476 * In this case AVIC was temporarily disabled for
4477 * requesting the IRQ window and we have to re-enable it.
4479 svm_toggle_avic_for_irq_window(&svm->vcpu, true);
4481 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4482 mark_dirty(svm->vmcb, VMCB_INTR);
4483 ++svm->vcpu.stat.irq_window_exits;
4487 static int pause_interception(struct vcpu_svm *svm)
4489 struct kvm_vcpu *vcpu = &svm->vcpu;
4490 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4492 if (pause_filter_thresh)
4493 grow_ple_window(vcpu);
4495 kvm_vcpu_on_spin(vcpu, in_kernel);
4499 static int nop_interception(struct vcpu_svm *svm)
4501 return kvm_skip_emulated_instruction(&(svm->vcpu));
4504 static int monitor_interception(struct vcpu_svm *svm)
4506 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4507 return nop_interception(svm);
4510 static int mwait_interception(struct vcpu_svm *svm)
4512 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4513 return nop_interception(svm);
4516 enum avic_ipi_failure_cause {
4517 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4518 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4519 AVIC_IPI_FAILURE_INVALID_TARGET,
4520 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4523 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4525 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4526 u32 icrl = svm->vmcb->control.exit_info_1;
4527 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4528 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4529 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4531 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4534 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4536 * AVIC hardware handles the generation of
4537 * IPIs when the specified Message Type is Fixed
4538 * (also known as fixed delivery mode) and
4539 * the Trigger Mode is edge-triggered. The hardware
4540 * also supports self and broadcast delivery modes
4541 * specified via the Destination Shorthand(DSH)
4542 * field of the ICRL. Logical and physical APIC ID
4543 * formats are supported. All other IPI types cause
4544 * a #VMEXIT, which needs to emulated.
4546 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4547 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4549 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4551 struct kvm_vcpu *vcpu;
4552 struct kvm *kvm = svm->vcpu.kvm;
4553 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4556 * At this point, we expect that the AVIC HW has already
4557 * set the appropriate IRR bits on the valid target
4558 * vcpus. So, we just need to kick the appropriate vcpu.
4560 kvm_for_each_vcpu(i, vcpu, kvm) {
4561 bool m = kvm_apic_match_dest(vcpu, apic,
4562 icrl & APIC_SHORT_MASK,
4563 GET_APIC_DEST_FIELD(icrh),
4564 icrl & APIC_DEST_MASK);
4566 if (m && !avic_vcpu_is_running(vcpu))
4567 kvm_vcpu_wake_up(vcpu);
4571 case AVIC_IPI_FAILURE_INVALID_TARGET:
4572 WARN_ONCE(1, "Invalid IPI target: index=%u, vcpu=%d, icr=%#0x:%#0x\n",
4573 index, svm->vcpu.vcpu_id, icrh, icrl);
4575 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4576 WARN_ONCE(1, "Invalid backing page\n");
4579 pr_err("Unknown IPI interception\n");
4585 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4587 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4589 u32 *logical_apic_id_table;
4590 int dlid = GET_APIC_LOGICAL_ID(ldr);
4595 if (flat) { /* flat */
4596 index = ffs(dlid) - 1;
4599 } else { /* cluster */
4600 int cluster = (dlid & 0xf0) >> 4;
4601 int apic = ffs(dlid & 0x0f) - 1;
4603 if ((apic < 0) || (apic > 7) ||
4606 index = (cluster << 2) + apic;
4609 logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4611 return &logical_apic_id_table[index];
4614 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
4617 u32 *entry, new_entry;
4619 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4620 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4624 new_entry = READ_ONCE(*entry);
4625 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4626 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4627 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4628 WRITE_ONCE(*entry, new_entry);
4633 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
4635 struct vcpu_svm *svm = to_svm(vcpu);
4636 bool flat = svm->dfr_reg == APIC_DFR_FLAT;
4637 u32 *entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
4640 clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
4643 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4646 struct vcpu_svm *svm = to_svm(vcpu);
4647 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4648 u32 id = kvm_xapic_id(vcpu->arch.apic);
4650 if (ldr == svm->ldr_reg)
4653 avic_invalidate_logical_id_entry(vcpu);
4656 ret = avic_ldr_write(vcpu, id, ldr);
4664 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4667 struct vcpu_svm *svm = to_svm(vcpu);
4668 u32 id = kvm_xapic_id(vcpu->arch.apic);
4670 if (vcpu->vcpu_id == id)
4673 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4674 new = avic_get_physical_id_entry(vcpu, id);
4678 /* We need to move physical_id_entry to new offset */
4681 to_svm(vcpu)->avic_physical_id_cache = new;
4684 * Also update the guest physical APIC ID in the logical
4685 * APIC ID table entry if already setup the LDR.
4688 avic_handle_ldr_update(vcpu);
4693 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4695 struct vcpu_svm *svm = to_svm(vcpu);
4696 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4698 if (svm->dfr_reg == dfr)
4701 avic_invalidate_logical_id_entry(vcpu);
4705 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4707 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4708 u32 offset = svm->vmcb->control.exit_info_1 &
4709 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4713 if (avic_handle_apic_id_update(&svm->vcpu))
4717 if (avic_handle_ldr_update(&svm->vcpu))
4721 avic_handle_dfr_update(&svm->vcpu);
4727 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4732 static bool is_avic_unaccelerated_access_trap(u32 offset)
4761 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4764 u32 offset = svm->vmcb->control.exit_info_1 &
4765 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4766 u32 vector = svm->vmcb->control.exit_info_2 &
4767 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4768 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4769 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4770 bool trap = is_avic_unaccelerated_access_trap(offset);
4772 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4773 trap, write, vector);
4776 WARN_ONCE(!write, "svm: Handling trap read.\n");
4777 ret = avic_unaccel_trap_write(svm);
4779 /* Handling Fault */
4780 ret = kvm_emulate_instruction(&svm->vcpu, 0);
4786 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4787 [SVM_EXIT_READ_CR0] = cr_interception,
4788 [SVM_EXIT_READ_CR3] = cr_interception,
4789 [SVM_EXIT_READ_CR4] = cr_interception,
4790 [SVM_EXIT_READ_CR8] = cr_interception,
4791 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4792 [SVM_EXIT_WRITE_CR0] = cr_interception,
4793 [SVM_EXIT_WRITE_CR3] = cr_interception,
4794 [SVM_EXIT_WRITE_CR4] = cr_interception,
4795 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4796 [SVM_EXIT_READ_DR0] = dr_interception,
4797 [SVM_EXIT_READ_DR1] = dr_interception,
4798 [SVM_EXIT_READ_DR2] = dr_interception,
4799 [SVM_EXIT_READ_DR3] = dr_interception,
4800 [SVM_EXIT_READ_DR4] = dr_interception,
4801 [SVM_EXIT_READ_DR5] = dr_interception,
4802 [SVM_EXIT_READ_DR6] = dr_interception,
4803 [SVM_EXIT_READ_DR7] = dr_interception,
4804 [SVM_EXIT_WRITE_DR0] = dr_interception,
4805 [SVM_EXIT_WRITE_DR1] = dr_interception,
4806 [SVM_EXIT_WRITE_DR2] = dr_interception,
4807 [SVM_EXIT_WRITE_DR3] = dr_interception,
4808 [SVM_EXIT_WRITE_DR4] = dr_interception,
4809 [SVM_EXIT_WRITE_DR5] = dr_interception,
4810 [SVM_EXIT_WRITE_DR6] = dr_interception,
4811 [SVM_EXIT_WRITE_DR7] = dr_interception,
4812 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4813 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4814 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4815 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4816 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4817 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4818 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
4819 [SVM_EXIT_INTR] = intr_interception,
4820 [SVM_EXIT_NMI] = nmi_interception,
4821 [SVM_EXIT_SMI] = nop_on_interception,
4822 [SVM_EXIT_INIT] = nop_on_interception,
4823 [SVM_EXIT_VINTR] = interrupt_window_interception,
4824 [SVM_EXIT_RDPMC] = rdpmc_interception,
4825 [SVM_EXIT_CPUID] = cpuid_interception,
4826 [SVM_EXIT_IRET] = iret_interception,
4827 [SVM_EXIT_INVD] = emulate_on_interception,
4828 [SVM_EXIT_PAUSE] = pause_interception,
4829 [SVM_EXIT_HLT] = halt_interception,
4830 [SVM_EXIT_INVLPG] = invlpg_interception,
4831 [SVM_EXIT_INVLPGA] = invlpga_interception,
4832 [SVM_EXIT_IOIO] = io_interception,
4833 [SVM_EXIT_MSR] = msr_interception,
4834 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4835 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4836 [SVM_EXIT_VMRUN] = vmrun_interception,
4837 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4838 [SVM_EXIT_VMLOAD] = vmload_interception,
4839 [SVM_EXIT_VMSAVE] = vmsave_interception,
4840 [SVM_EXIT_STGI] = stgi_interception,
4841 [SVM_EXIT_CLGI] = clgi_interception,
4842 [SVM_EXIT_SKINIT] = skinit_interception,
4843 [SVM_EXIT_WBINVD] = wbinvd_interception,
4844 [SVM_EXIT_MONITOR] = monitor_interception,
4845 [SVM_EXIT_MWAIT] = mwait_interception,
4846 [SVM_EXIT_XSETBV] = xsetbv_interception,
4847 [SVM_EXIT_RDPRU] = rdpru_interception,
4848 [SVM_EXIT_NPF] = npf_interception,
4849 [SVM_EXIT_RSM] = rsm_interception,
4850 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4851 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4854 static void dump_vmcb(struct kvm_vcpu *vcpu)
4856 struct vcpu_svm *svm = to_svm(vcpu);
4857 struct vmcb_control_area *control = &svm->vmcb->control;
4858 struct vmcb_save_area *save = &svm->vmcb->save;
4860 if (!dump_invalid_vmcb) {
4861 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
4865 pr_err("VMCB Control Area:\n");
4866 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4867 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4868 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4869 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4870 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4871 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4872 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4873 pr_err("%-20s%d\n", "pause filter threshold:",
4874 control->pause_filter_thresh);
4875 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4876 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4877 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4878 pr_err("%-20s%d\n", "asid:", control->asid);
4879 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4880 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4881 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4882 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4883 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4884 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4885 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4886 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4887 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4888 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4889 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4890 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4891 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4892 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4893 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4894 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4895 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4896 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4897 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4898 pr_err("VMCB State Save Area:\n");
4899 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4901 save->es.selector, save->es.attrib,
4902 save->es.limit, save->es.base);
4903 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4905 save->cs.selector, save->cs.attrib,
4906 save->cs.limit, save->cs.base);
4907 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4909 save->ss.selector, save->ss.attrib,
4910 save->ss.limit, save->ss.base);
4911 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4913 save->ds.selector, save->ds.attrib,
4914 save->ds.limit, save->ds.base);
4915 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4917 save->fs.selector, save->fs.attrib,
4918 save->fs.limit, save->fs.base);
4919 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4921 save->gs.selector, save->gs.attrib,
4922 save->gs.limit, save->gs.base);
4923 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4925 save->gdtr.selector, save->gdtr.attrib,
4926 save->gdtr.limit, save->gdtr.base);
4927 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4929 save->ldtr.selector, save->ldtr.attrib,
4930 save->ldtr.limit, save->ldtr.base);
4931 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4933 save->idtr.selector, save->idtr.attrib,
4934 save->idtr.limit, save->idtr.base);
4935 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4937 save->tr.selector, save->tr.attrib,
4938 save->tr.limit, save->tr.base);
4939 pr_err("cpl: %d efer: %016llx\n",
4940 save->cpl, save->efer);
4941 pr_err("%-15s %016llx %-13s %016llx\n",
4942 "cr0:", save->cr0, "cr2:", save->cr2);
4943 pr_err("%-15s %016llx %-13s %016llx\n",
4944 "cr3:", save->cr3, "cr4:", save->cr4);
4945 pr_err("%-15s %016llx %-13s %016llx\n",
4946 "dr6:", save->dr6, "dr7:", save->dr7);
4947 pr_err("%-15s %016llx %-13s %016llx\n",
4948 "rip:", save->rip, "rflags:", save->rflags);
4949 pr_err("%-15s %016llx %-13s %016llx\n",
4950 "rsp:", save->rsp, "rax:", save->rax);
4951 pr_err("%-15s %016llx %-13s %016llx\n",
4952 "star:", save->star, "lstar:", save->lstar);
4953 pr_err("%-15s %016llx %-13s %016llx\n",
4954 "cstar:", save->cstar, "sfmask:", save->sfmask);
4955 pr_err("%-15s %016llx %-13s %016llx\n",
4956 "kernel_gs_base:", save->kernel_gs_base,
4957 "sysenter_cs:", save->sysenter_cs);
4958 pr_err("%-15s %016llx %-13s %016llx\n",
4959 "sysenter_esp:", save->sysenter_esp,
4960 "sysenter_eip:", save->sysenter_eip);
4961 pr_err("%-15s %016llx %-13s %016llx\n",
4962 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4963 pr_err("%-15s %016llx %-13s %016llx\n",
4964 "br_from:", save->br_from, "br_to:", save->br_to);
4965 pr_err("%-15s %016llx %-13s %016llx\n",
4966 "excp_from:", save->last_excp_from,
4967 "excp_to:", save->last_excp_to);
4970 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4972 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4974 *info1 = control->exit_info_1;
4975 *info2 = control->exit_info_2;
4978 static int handle_exit(struct kvm_vcpu *vcpu,
4979 enum exit_fastpath_completion exit_fastpath)
4981 struct vcpu_svm *svm = to_svm(vcpu);
4982 struct kvm_run *kvm_run = vcpu->run;
4983 u32 exit_code = svm->vmcb->control.exit_code;
4985 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4987 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4988 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4990 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4992 if (unlikely(svm->nested.exit_required)) {
4993 nested_svm_vmexit(svm);
4994 svm->nested.exit_required = false;
4999 if (is_guest_mode(vcpu)) {
5002 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
5003 svm->vmcb->control.exit_info_1,
5004 svm->vmcb->control.exit_info_2,
5005 svm->vmcb->control.exit_int_info,
5006 svm->vmcb->control.exit_int_info_err,
5009 vmexit = nested_svm_exit_special(svm);
5011 if (vmexit == NESTED_EXIT_CONTINUE)
5012 vmexit = nested_svm_exit_handled(svm);
5014 if (vmexit == NESTED_EXIT_DONE)
5018 svm_complete_interrupts(svm);
5020 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
5021 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5022 kvm_run->fail_entry.hardware_entry_failure_reason
5023 = svm->vmcb->control.exit_code;
5028 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
5029 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
5030 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
5031 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
5032 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
5034 __func__, svm->vmcb->control.exit_int_info,
5037 if (exit_fastpath == EXIT_FASTPATH_SKIP_EMUL_INS) {
5038 kvm_skip_emulated_instruction(vcpu);
5040 } else if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
5041 || !svm_exit_handlers[exit_code]) {
5042 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%x\n", exit_code);
5044 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5045 vcpu->run->internal.suberror =
5046 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
5047 vcpu->run->internal.ndata = 1;
5048 vcpu->run->internal.data[0] = exit_code;
5052 #ifdef CONFIG_RETPOLINE
5053 if (exit_code == SVM_EXIT_MSR)
5054 return msr_interception(svm);
5055 else if (exit_code == SVM_EXIT_VINTR)
5056 return interrupt_window_interception(svm);
5057 else if (exit_code == SVM_EXIT_INTR)
5058 return intr_interception(svm);
5059 else if (exit_code == SVM_EXIT_HLT)
5060 return halt_interception(svm);
5061 else if (exit_code == SVM_EXIT_NPF)
5062 return npf_interception(svm);
5064 return svm_exit_handlers[exit_code](svm);
5067 static void reload_tss(struct kvm_vcpu *vcpu)
5069 int cpu = raw_smp_processor_id();
5071 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5072 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
5076 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
5078 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5079 int asid = sev_get_asid(svm->vcpu.kvm);
5081 /* Assign the asid allocated with this SEV guest */
5082 svm->vmcb->control.asid = asid;
5087 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
5088 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
5090 if (sd->sev_vmcbs[asid] == svm->vmcb &&
5091 svm->last_cpu == cpu)
5094 svm->last_cpu = cpu;
5095 sd->sev_vmcbs[asid] = svm->vmcb;
5096 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5097 mark_dirty(svm->vmcb, VMCB_ASID);
5100 static void pre_svm_run(struct vcpu_svm *svm)
5102 int cpu = raw_smp_processor_id();
5104 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5106 if (sev_guest(svm->vcpu.kvm))
5107 return pre_sev_run(svm, cpu);
5109 /* FIXME: handle wraparound of asid_generation */
5110 if (svm->asid_generation != sd->asid_generation)
5114 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5116 struct vcpu_svm *svm = to_svm(vcpu);
5118 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5119 vcpu->arch.hflags |= HF_NMI_MASK;
5120 set_intercept(svm, INTERCEPT_IRET);
5121 ++vcpu->stat.nmi_injections;
5124 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
5126 struct vmcb_control_area *control;
5128 /* The following fields are ignored when AVIC is enabled */
5129 control = &svm->vmcb->control;
5130 control->int_vector = irq;
5131 control->int_ctl &= ~V_INTR_PRIO_MASK;
5132 control->int_ctl |= V_IRQ_MASK |
5133 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
5134 mark_dirty(svm->vmcb, VMCB_INTR);
5137 static void svm_set_irq(struct kvm_vcpu *vcpu)
5139 struct vcpu_svm *svm = to_svm(vcpu);
5141 BUG_ON(!(gif_set(svm)));
5143 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5144 ++vcpu->stat.irq_injections;
5146 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5147 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5150 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5152 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5155 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5157 struct vcpu_svm *svm = to_svm(vcpu);
5159 if (svm_nested_virtualize_tpr(vcpu))
5162 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5168 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5171 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5176 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5180 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5184 static void svm_toggle_avic_for_irq_window(struct kvm_vcpu *vcpu, bool activate)
5186 if (!avic || !lapic_in_kernel(vcpu))
5189 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5190 kvm_request_apicv_update(vcpu->kvm, activate,
5191 APICV_INHIBIT_REASON_IRQWIN);
5192 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5195 static int svm_set_pi_irte_mode(struct kvm_vcpu *vcpu, bool activate)
5198 unsigned long flags;
5199 struct amd_svm_iommu_ir *ir;
5200 struct vcpu_svm *svm = to_svm(vcpu);
5202 if (!kvm_arch_has_assigned_device(vcpu->kvm))
5206 * Here, we go through the per-vcpu ir_list to update all existing
5207 * interrupt remapping table entry targeting this vcpu.
5209 spin_lock_irqsave(&svm->ir_list_lock, flags);
5211 if (list_empty(&svm->ir_list))
5214 list_for_each_entry(ir, &svm->ir_list, node) {
5216 ret = amd_iommu_activate_guest_mode(ir->data);
5218 ret = amd_iommu_deactivate_guest_mode(ir->data);
5223 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5227 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5229 struct vcpu_svm *svm = to_svm(vcpu);
5230 struct vmcb *vmcb = svm->vmcb;
5231 bool activated = kvm_vcpu_apicv_active(vcpu);
5238 * During AVIC temporary deactivation, guest could update
5239 * APIC ID, DFR and LDR registers, which would not be trapped
5240 * by avic_unaccelerated_access_interception(). In this case,
5241 * we need to check and update the AVIC logical APIC ID table
5242 * accordingly before re-activating.
5244 avic_post_state_restore(vcpu);
5245 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
5247 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5249 mark_dirty(vmcb, VMCB_AVIC);
5251 svm_set_pi_irte_mode(vcpu, activated);
5254 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5259 static int svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5261 if (!vcpu->arch.apicv_active)
5264 kvm_lapic_set_irr(vec, vcpu->arch.apic);
5265 smp_mb__after_atomic();
5267 if (avic_vcpu_is_running(vcpu)) {
5268 int cpuid = vcpu->cpu;
5270 if (cpuid != get_cpu())
5271 wrmsrl(SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpuid));
5274 kvm_vcpu_wake_up(vcpu);
5279 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
5284 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5286 unsigned long flags;
5287 struct amd_svm_iommu_ir *cur;
5289 spin_lock_irqsave(&svm->ir_list_lock, flags);
5290 list_for_each_entry(cur, &svm->ir_list, node) {
5291 if (cur->data != pi->ir_data)
5293 list_del(&cur->node);
5297 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5300 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5303 unsigned long flags;
5304 struct amd_svm_iommu_ir *ir;
5307 * In some cases, the existing irte is updaed and re-set,
5308 * so we need to check here if it's already been * added
5311 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5312 struct kvm *kvm = svm->vcpu.kvm;
5313 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5314 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5315 struct vcpu_svm *prev_svm;
5322 prev_svm = to_svm(prev_vcpu);
5323 svm_ir_list_del(prev_svm, pi);
5327 * Allocating new amd_iommu_pi_data, which will get
5328 * add to the per-vcpu ir_list.
5330 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL_ACCOUNT);
5335 ir->data = pi->ir_data;
5337 spin_lock_irqsave(&svm->ir_list_lock, flags);
5338 list_add(&ir->node, &svm->ir_list);
5339 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5346 * The HW cannot support posting multicast/broadcast
5347 * interrupts to a vCPU. So, we still use legacy interrupt
5348 * remapping for these kind of interrupts.
5350 * For lowest-priority interrupts, we only support
5351 * those with single CPU as the destination, e.g. user
5352 * configures the interrupts via /proc/irq or uses
5353 * irqbalance to make the interrupts single-CPU.
5356 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5357 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5359 struct kvm_lapic_irq irq;
5360 struct kvm_vcpu *vcpu = NULL;
5362 kvm_set_msi_irq(kvm, e, &irq);
5364 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
5365 !kvm_irq_is_postable(&irq)) {
5366 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5367 __func__, irq.vector);
5371 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5373 *svm = to_svm(vcpu);
5374 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5375 vcpu_info->vector = irq.vector;
5381 * svm_update_pi_irte - set IRTE for Posted-Interrupts
5384 * @host_irq: host irq of the interrupt
5385 * @guest_irq: gsi of the interrupt
5386 * @set: set or unset PI
5387 * returns 0 on success, < 0 on failure
5389 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5390 uint32_t guest_irq, bool set)
5392 struct kvm_kernel_irq_routing_entry *e;
5393 struct kvm_irq_routing_table *irq_rt;
5394 int idx, ret = -EINVAL;
5396 if (!kvm_arch_has_assigned_device(kvm) ||
5397 !irq_remapping_cap(IRQ_POSTING_CAP))
5400 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5401 __func__, host_irq, guest_irq, set);
5403 idx = srcu_read_lock(&kvm->irq_srcu);
5404 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5405 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5407 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5408 struct vcpu_data vcpu_info;
5409 struct vcpu_svm *svm = NULL;
5411 if (e->type != KVM_IRQ_ROUTING_MSI)
5415 * Here, we setup with legacy mode in the following cases:
5416 * 1. When cannot target interrupt to a specific vcpu.
5417 * 2. Unsetting posted interrupt.
5418 * 3. APIC virtialization is disabled for the vcpu.
5419 * 4. IRQ has incompatible delivery mode (SMI, INIT, etc)
5421 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5422 kvm_vcpu_apicv_active(&svm->vcpu)) {
5423 struct amd_iommu_pi_data pi;
5425 /* Try to enable guest_mode in IRTE */
5426 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5428 pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5430 pi.is_guest_mode = true;
5431 pi.vcpu_data = &vcpu_info;
5432 ret = irq_set_vcpu_affinity(host_irq, &pi);
5435 * Here, we successfully setting up vcpu affinity in
5436 * IOMMU guest mode. Now, we need to store the posted
5437 * interrupt information in a per-vcpu ir_list so that
5438 * we can reference to them directly when we update vcpu
5439 * scheduling information in IOMMU irte.
5441 if (!ret && pi.is_guest_mode)
5442 svm_ir_list_add(svm, &pi);
5444 /* Use legacy mode in IRTE */
5445 struct amd_iommu_pi_data pi;
5448 * Here, pi is used to:
5449 * - Tell IOMMU to use legacy mode for this interrupt.
5450 * - Retrieve ga_tag of prior interrupt remapping data.
5452 pi.is_guest_mode = false;
5453 ret = irq_set_vcpu_affinity(host_irq, &pi);
5456 * Check if the posted interrupt was previously
5457 * setup with the guest_mode by checking if the ga_tag
5458 * was cached. If so, we need to clean up the per-vcpu
5461 if (!ret && pi.prev_ga_tag) {
5462 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5463 struct kvm_vcpu *vcpu;
5465 vcpu = kvm_get_vcpu_by_id(kvm, id);
5467 svm_ir_list_del(to_svm(vcpu), &pi);
5472 trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5473 e->gsi, vcpu_info.vector,
5474 vcpu_info.pi_desc_addr, set);
5478 pr_err("%s: failed to update PI IRTE\n", __func__);
5485 srcu_read_unlock(&kvm->irq_srcu, idx);
5489 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5491 struct vcpu_svm *svm = to_svm(vcpu);
5492 struct vmcb *vmcb = svm->vmcb;
5494 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5495 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5496 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5501 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5503 struct vcpu_svm *svm = to_svm(vcpu);
5505 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5508 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5510 struct vcpu_svm *svm = to_svm(vcpu);
5513 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5514 set_intercept(svm, INTERCEPT_IRET);
5516 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5517 clr_intercept(svm, INTERCEPT_IRET);
5521 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5523 struct vcpu_svm *svm = to_svm(vcpu);
5524 struct vmcb *vmcb = svm->vmcb;
5527 if (!gif_set(svm) ||
5528 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5531 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5533 if (is_guest_mode(vcpu))
5534 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5539 static void enable_irq_window(struct kvm_vcpu *vcpu)
5541 struct vcpu_svm *svm = to_svm(vcpu);
5544 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5545 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5546 * get that intercept, this function will be called again though and
5547 * we'll get the vintr intercept. However, if the vGIF feature is
5548 * enabled, the STGI interception will not occur. Enable the irq
5549 * window under the assumption that the hardware will set the GIF.
5551 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5553 * IRQ window is not needed when AVIC is enabled,
5554 * unless we have pending ExtINT since it cannot be injected
5555 * via AVIC. In such case, we need to temporarily disable AVIC,
5556 * and fallback to injecting IRQ via V_IRQ.
5558 svm_toggle_avic_for_irq_window(vcpu, false);
5560 svm_inject_irq(svm, 0x0);
5564 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5566 struct vcpu_svm *svm = to_svm(vcpu);
5568 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5570 return; /* IRET will cause a vm exit */
5572 if (!gif_set(svm)) {
5573 if (vgif_enabled(svm))
5574 set_intercept(svm, INTERCEPT_STGI);
5575 return; /* STGI will cause a vm exit */
5578 if (svm->nested.exit_required)
5579 return; /* we're not going to run the guest yet */
5582 * Something prevents NMI from been injected. Single step over possible
5583 * problem (IRET or exception injection or interrupt shadow)
5585 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5586 svm->nmi_singlestep = true;
5587 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5590 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5595 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5600 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5602 struct vcpu_svm *svm = to_svm(vcpu);
5604 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5605 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5607 svm->asid_generation--;
5610 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
5612 struct vcpu_svm *svm = to_svm(vcpu);
5614 invlpga(gva, svm->vmcb->control.asid);
5617 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5621 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5623 struct vcpu_svm *svm = to_svm(vcpu);
5625 if (svm_nested_virtualize_tpr(vcpu))
5628 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5629 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5630 kvm_set_cr8(vcpu, cr8);
5634 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5636 struct vcpu_svm *svm = to_svm(vcpu);
5639 if (svm_nested_virtualize_tpr(vcpu) ||
5640 kvm_vcpu_apicv_active(vcpu))
5643 cr8 = kvm_get_cr8(vcpu);
5644 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5645 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5648 static void svm_complete_interrupts(struct vcpu_svm *svm)
5652 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5653 unsigned int3_injected = svm->int3_injected;
5655 svm->int3_injected = 0;
5658 * If we've made progress since setting HF_IRET_MASK, we've
5659 * executed an IRET and can allow NMI injection.
5661 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5662 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5663 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5664 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5667 svm->vcpu.arch.nmi_injected = false;
5668 kvm_clear_exception_queue(&svm->vcpu);
5669 kvm_clear_interrupt_queue(&svm->vcpu);
5671 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5674 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5676 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5677 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5680 case SVM_EXITINTINFO_TYPE_NMI:
5681 svm->vcpu.arch.nmi_injected = true;
5683 case SVM_EXITINTINFO_TYPE_EXEPT:
5685 * In case of software exceptions, do not reinject the vector,
5686 * but re-execute the instruction instead. Rewind RIP first
5687 * if we emulated INT3 before.
5689 if (kvm_exception_is_soft(vector)) {
5690 if (vector == BP_VECTOR && int3_injected &&
5691 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5692 kvm_rip_write(&svm->vcpu,
5693 kvm_rip_read(&svm->vcpu) -
5697 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5698 u32 err = svm->vmcb->control.exit_int_info_err;
5699 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5702 kvm_requeue_exception(&svm->vcpu, vector);
5704 case SVM_EXITINTINFO_TYPE_INTR:
5705 kvm_queue_interrupt(&svm->vcpu, vector, false);
5712 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5714 struct vcpu_svm *svm = to_svm(vcpu);
5715 struct vmcb_control_area *control = &svm->vmcb->control;
5717 control->exit_int_info = control->event_inj;
5718 control->exit_int_info_err = control->event_inj_err;
5719 control->event_inj = 0;
5720 svm_complete_interrupts(svm);
5723 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5725 struct vcpu_svm *svm = to_svm(vcpu);
5727 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5728 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5729 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5732 * A vmexit emulation is required before the vcpu can be executed
5735 if (unlikely(svm->nested.exit_required))
5739 * Disable singlestep if we're injecting an interrupt/exception.
5740 * We don't want our modified rflags to be pushed on the stack where
5741 * we might not be able to easily reset them if we disabled NMI
5744 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5746 * Event injection happens before external interrupts cause a
5747 * vmexit and interrupts are disabled here, so smp_send_reschedule
5748 * is enough to force an immediate vmexit.
5750 disable_nmi_singlestep(svm);
5751 smp_send_reschedule(vcpu->cpu);
5756 sync_lapic_to_cr8(vcpu);
5758 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5761 kvm_load_guest_xsave_state(vcpu);
5763 if (lapic_in_kernel(vcpu) &&
5764 vcpu->arch.apic->lapic_timer.timer_advance_ns)
5765 kvm_wait_lapic_expire(vcpu);
5768 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5769 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5770 * is no need to worry about the conditional branch over the wrmsr
5771 * being speculatively taken.
5773 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5778 "push %%" _ASM_BP "; \n\t"
5779 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5780 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5781 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5782 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5783 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5784 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5785 #ifdef CONFIG_X86_64
5786 "mov %c[r8](%[svm]), %%r8 \n\t"
5787 "mov %c[r9](%[svm]), %%r9 \n\t"
5788 "mov %c[r10](%[svm]), %%r10 \n\t"
5789 "mov %c[r11](%[svm]), %%r11 \n\t"
5790 "mov %c[r12](%[svm]), %%r12 \n\t"
5791 "mov %c[r13](%[svm]), %%r13 \n\t"
5792 "mov %c[r14](%[svm]), %%r14 \n\t"
5793 "mov %c[r15](%[svm]), %%r15 \n\t"
5796 /* Enter guest mode */
5797 "push %%" _ASM_AX " \n\t"
5798 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5799 __ex("vmload %%" _ASM_AX) "\n\t"
5800 __ex("vmrun %%" _ASM_AX) "\n\t"
5801 __ex("vmsave %%" _ASM_AX) "\n\t"
5802 "pop %%" _ASM_AX " \n\t"
5804 /* Save guest registers, load host registers */
5805 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5806 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5807 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5808 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5809 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5810 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5811 #ifdef CONFIG_X86_64
5812 "mov %%r8, %c[r8](%[svm]) \n\t"
5813 "mov %%r9, %c[r9](%[svm]) \n\t"
5814 "mov %%r10, %c[r10](%[svm]) \n\t"
5815 "mov %%r11, %c[r11](%[svm]) \n\t"
5816 "mov %%r12, %c[r12](%[svm]) \n\t"
5817 "mov %%r13, %c[r13](%[svm]) \n\t"
5818 "mov %%r14, %c[r14](%[svm]) \n\t"
5819 "mov %%r15, %c[r15](%[svm]) \n\t"
5821 * Clear host registers marked as clobbered to prevent
5824 "xor %%r8d, %%r8d \n\t"
5825 "xor %%r9d, %%r9d \n\t"
5826 "xor %%r10d, %%r10d \n\t"
5827 "xor %%r11d, %%r11d \n\t"
5828 "xor %%r12d, %%r12d \n\t"
5829 "xor %%r13d, %%r13d \n\t"
5830 "xor %%r14d, %%r14d \n\t"
5831 "xor %%r15d, %%r15d \n\t"
5833 "xor %%ebx, %%ebx \n\t"
5834 "xor %%ecx, %%ecx \n\t"
5835 "xor %%edx, %%edx \n\t"
5836 "xor %%esi, %%esi \n\t"
5837 "xor %%edi, %%edi \n\t"
5841 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5842 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5843 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5844 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5845 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5846 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5847 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5848 #ifdef CONFIG_X86_64
5849 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5850 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5851 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5852 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5853 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5854 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5855 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5856 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5859 #ifdef CONFIG_X86_64
5860 , "rbx", "rcx", "rdx", "rsi", "rdi"
5861 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5863 , "ebx", "ecx", "edx", "esi", "edi"
5867 /* Eliminate branch target predictions from guest mode */
5870 #ifdef CONFIG_X86_64
5871 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5873 loadsegment(fs, svm->host.fs);
5874 #ifndef CONFIG_X86_32_LAZY_GS
5875 loadsegment(gs, svm->host.gs);
5880 * We do not use IBRS in the kernel. If this vCPU has used the
5881 * SPEC_CTRL MSR it may have left it on; save the value and
5882 * turn it off. This is much more efficient than blindly adding
5883 * it to the atomic save/restore list. Especially as the former
5884 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5886 * For non-nested case:
5887 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5891 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5894 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5895 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5899 local_irq_disable();
5901 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5903 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5904 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5905 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5906 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5908 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5909 kvm_before_interrupt(&svm->vcpu);
5911 kvm_load_host_xsave_state(vcpu);
5914 /* Any pending NMI will happen here */
5916 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5917 kvm_after_interrupt(&svm->vcpu);
5919 sync_cr8_to_lapic(vcpu);
5923 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5925 /* if exit due to PF check for async PF */
5926 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5927 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5930 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5931 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5935 * We need to handle MC intercepts here before the vcpu has a chance to
5936 * change the physical cpu
5938 if (unlikely(svm->vmcb->control.exit_code ==
5939 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5940 svm_handle_mce(svm);
5942 mark_all_clean(svm->vmcb);
5944 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5946 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5948 struct vcpu_svm *svm = to_svm(vcpu);
5950 svm->vmcb->save.cr3 = __sme_set(root);
5951 mark_dirty(svm->vmcb, VMCB_CR);
5954 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5956 struct vcpu_svm *svm = to_svm(vcpu);
5958 svm->vmcb->control.nested_cr3 = __sme_set(root);
5959 mark_dirty(svm->vmcb, VMCB_NPT);
5961 /* Also sync guest cr3 here in case we live migrate */
5962 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5963 mark_dirty(svm->vmcb, VMCB_CR);
5966 static int is_disabled(void)
5970 rdmsrl(MSR_VM_CR, vm_cr);
5971 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5978 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5981 * Patch in the VMMCALL instruction:
5983 hypercall[0] = 0x0f;
5984 hypercall[1] = 0x01;
5985 hypercall[2] = 0xd9;
5988 static int __init svm_check_processor_compat(void)
5993 static bool svm_cpu_has_accelerated_tpr(void)
5998 static bool svm_has_emulated_msr(int index)
6001 case MSR_IA32_MCG_EXT_CTL:
6002 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6011 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6016 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
6018 struct vcpu_svm *svm = to_svm(vcpu);
6020 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6021 boot_cpu_has(X86_FEATURE_XSAVE) &&
6022 boot_cpu_has(X86_FEATURE_XSAVES);
6024 /* Update nrips enabled cache */
6025 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
6027 if (!kvm_vcpu_apicv_active(vcpu))
6030 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
6033 * Currently, AVIC does not work with nested virtualization.
6034 * So, we disable AVIC when cpuid for SVM is set in the L1 guest.
6036 if (nested && guest_cpuid_has(vcpu, X86_FEATURE_SVM))
6037 kvm_request_apicv_update(vcpu->kvm, false,
6038 APICV_INHIBIT_REASON_NESTED);
6041 #define F feature_bit
6043 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
6048 entry->ecx &= ~F(X2APIC);
6052 entry->ecx |= (1 << 2); /* Set SVM bit */
6055 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
6056 boot_cpu_has(X86_FEATURE_AMD_SSBD))
6057 entry->ebx |= F(VIRT_SSBD);
6060 entry->eax = 1; /* SVM revision 1 */
6061 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
6062 ASID emulation to nested SVM */
6063 entry->ecx = 0; /* Reserved */
6064 entry->edx = 0; /* Per default do not support any
6065 additional features */
6067 /* Support next_rip if host supports it */
6068 if (boot_cpu_has(X86_FEATURE_NRIPS))
6069 entry->edx |= F(NRIPS);
6071 /* Support NPT for the guest if enabled */
6073 entry->edx |= F(NPT);
6078 static int svm_get_lpage_level(void)
6080 return PT_PDPE_LEVEL;
6083 static bool svm_rdtscp_supported(void)
6085 return boot_cpu_has(X86_FEATURE_RDTSCP);
6088 static bool svm_invpcid_supported(void)
6093 static bool svm_mpx_supported(void)
6098 static bool svm_xsaves_supported(void)
6100 return boot_cpu_has(X86_FEATURE_XSAVES);
6103 static bool svm_umip_emulated(void)
6108 static bool svm_pt_supported(void)
6113 static bool svm_has_wbinvd_exit(void)
6118 static bool svm_pku_supported(void)
6123 #define PRE_EX(exit) { .exit_code = (exit), \
6124 .stage = X86_ICPT_PRE_EXCEPT, }
6125 #define POST_EX(exit) { .exit_code = (exit), \
6126 .stage = X86_ICPT_POST_EXCEPT, }
6127 #define POST_MEM(exit) { .exit_code = (exit), \
6128 .stage = X86_ICPT_POST_MEMACCESS, }
6130 static const struct __x86_intercept {
6132 enum x86_intercept_stage stage;
6133 } x86_intercept_map[] = {
6134 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
6135 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
6136 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
6137 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
6138 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
6139 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
6140 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
6141 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
6142 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
6143 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
6144 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
6145 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
6146 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
6147 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
6148 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
6149 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
6150 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
6151 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
6152 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
6153 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
6154 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
6155 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
6156 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
6157 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
6158 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
6159 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
6160 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
6161 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
6162 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
6163 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
6164 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
6165 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
6166 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
6167 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
6168 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
6169 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
6170 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
6171 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
6172 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
6173 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
6174 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
6175 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
6176 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
6177 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
6178 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
6179 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
6180 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
6187 static int svm_check_intercept(struct kvm_vcpu *vcpu,
6188 struct x86_instruction_info *info,
6189 enum x86_intercept_stage stage)
6191 struct vcpu_svm *svm = to_svm(vcpu);
6192 int vmexit, ret = X86EMUL_CONTINUE;
6193 struct __x86_intercept icpt_info;
6194 struct vmcb *vmcb = svm->vmcb;
6196 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
6199 icpt_info = x86_intercept_map[info->intercept];
6201 if (stage != icpt_info.stage)
6204 switch (icpt_info.exit_code) {
6205 case SVM_EXIT_READ_CR0:
6206 if (info->intercept == x86_intercept_cr_read)
6207 icpt_info.exit_code += info->modrm_reg;
6209 case SVM_EXIT_WRITE_CR0: {
6210 unsigned long cr0, val;
6213 if (info->intercept == x86_intercept_cr_write)
6214 icpt_info.exit_code += info->modrm_reg;
6216 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
6217 info->intercept == x86_intercept_clts)
6220 intercept = svm->nested.intercept;
6222 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
6225 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
6226 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
6228 if (info->intercept == x86_intercept_lmsw) {
6231 /* lmsw can't clear PE - catch this here */
6232 if (cr0 & X86_CR0_PE)
6237 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
6241 case SVM_EXIT_READ_DR0:
6242 case SVM_EXIT_WRITE_DR0:
6243 icpt_info.exit_code += info->modrm_reg;
6246 if (info->intercept == x86_intercept_wrmsr)
6247 vmcb->control.exit_info_1 = 1;
6249 vmcb->control.exit_info_1 = 0;
6251 case SVM_EXIT_PAUSE:
6253 * We get this for NOP only, but pause
6254 * is rep not, check this here
6256 if (info->rep_prefix != REPE_PREFIX)
6259 case SVM_EXIT_IOIO: {
6263 if (info->intercept == x86_intercept_in ||
6264 info->intercept == x86_intercept_ins) {
6265 exit_info = ((info->src_val & 0xffff) << 16) |
6267 bytes = info->dst_bytes;
6269 exit_info = (info->dst_val & 0xffff) << 16;
6270 bytes = info->src_bytes;
6273 if (info->intercept == x86_intercept_outs ||
6274 info->intercept == x86_intercept_ins)
6275 exit_info |= SVM_IOIO_STR_MASK;
6277 if (info->rep_prefix)
6278 exit_info |= SVM_IOIO_REP_MASK;
6280 bytes = min(bytes, 4u);
6282 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
6284 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
6286 vmcb->control.exit_info_1 = exit_info;
6287 vmcb->control.exit_info_2 = info->next_rip;
6295 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
6296 if (static_cpu_has(X86_FEATURE_NRIPS))
6297 vmcb->control.next_rip = info->next_rip;
6298 vmcb->control.exit_code = icpt_info.exit_code;
6299 vmexit = nested_svm_exit_handled(svm);
6301 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
6308 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu,
6309 enum exit_fastpath_completion *exit_fastpath)
6311 if (!is_guest_mode(vcpu) &&
6312 to_svm(vcpu)->vmcb->control.exit_code == EXIT_REASON_MSR_WRITE)
6313 *exit_fastpath = handle_fastpath_set_msr_irqoff(vcpu);
6316 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
6318 if (pause_filter_thresh)
6319 shrink_ple_window(vcpu);
6322 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
6324 if (avic_handle_apic_id_update(vcpu) != 0)
6326 avic_handle_dfr_update(vcpu);
6327 avic_handle_ldr_update(vcpu);
6330 static void svm_setup_mce(struct kvm_vcpu *vcpu)
6332 /* [63:9] are reserved. */
6333 vcpu->arch.mcg_cap &= 0x1ff;
6336 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6338 struct vcpu_svm *svm = to_svm(vcpu);
6340 /* Per APM Vol.2 15.22.2 "Response to SMI" */
6344 if (is_guest_mode(&svm->vcpu) &&
6345 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6346 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
6347 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6348 svm->nested.exit_required = true;
6355 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6357 struct vcpu_svm *svm = to_svm(vcpu);
6360 if (is_guest_mode(vcpu)) {
6361 /* FED8h - SVM Guest */
6362 put_smstate(u64, smstate, 0x7ed8, 1);
6363 /* FEE0h - SVM Guest VMCB Physical Address */
6364 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6366 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6367 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6368 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6370 ret = nested_svm_vmexit(svm);
6377 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
6379 struct vcpu_svm *svm = to_svm(vcpu);
6380 struct vmcb *nested_vmcb;
6381 struct kvm_host_map map;
6385 guest = GET_SMSTATE(u64, smstate, 0x7ed8);
6386 vmcb = GET_SMSTATE(u64, smstate, 0x7ee0);
6389 if (kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb), &map) == -EINVAL)
6391 nested_vmcb = map.hva;
6392 enter_svm_guest_mode(svm, vmcb, nested_vmcb, &map);
6397 static int enable_smi_window(struct kvm_vcpu *vcpu)
6399 struct vcpu_svm *svm = to_svm(vcpu);
6401 if (!gif_set(svm)) {
6402 if (vgif_enabled(svm))
6403 set_intercept(svm, INTERCEPT_STGI);
6404 /* STGI will cause a vm exit */
6410 static int sev_flush_asids(void)
6415 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
6416 * so it must be guarded.
6418 down_write(&sev_deactivate_lock);
6420 wbinvd_on_all_cpus();
6421 ret = sev_guest_df_flush(&error);
6423 up_write(&sev_deactivate_lock);
6426 pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
6431 /* Must be called with the sev_bitmap_lock held */
6432 static bool __sev_recycle_asids(void)
6436 /* Check if there are any ASIDs to reclaim before performing a flush */
6437 pos = find_next_bit(sev_reclaim_asid_bitmap,
6438 max_sev_asid, min_sev_asid - 1);
6439 if (pos >= max_sev_asid)
6442 if (sev_flush_asids())
6445 bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
6447 bitmap_zero(sev_reclaim_asid_bitmap, max_sev_asid);
6452 static int sev_asid_new(void)
6457 mutex_lock(&sev_bitmap_lock);
6460 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6463 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6464 if (pos >= max_sev_asid) {
6465 if (retry && __sev_recycle_asids()) {
6469 mutex_unlock(&sev_bitmap_lock);
6473 __set_bit(pos, sev_asid_bitmap);
6475 mutex_unlock(&sev_bitmap_lock);
6480 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6482 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6486 if (unlikely(sev->active))
6489 asid = sev_asid_new();
6493 ret = sev_platform_init(&argp->error);
6499 INIT_LIST_HEAD(&sev->regions_list);
6504 sev_asid_free(asid);
6508 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6510 struct sev_data_activate *data;
6511 int asid = sev_get_asid(kvm);
6514 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6518 /* activate ASID on the given handle */
6519 data->handle = handle;
6521 ret = sev_guest_activate(data, error);
6527 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6536 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6542 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6544 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6546 return __sev_issue_cmd(sev->fd, id, data, error);
6549 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6551 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6552 struct sev_data_launch_start *start;
6553 struct kvm_sev_launch_start params;
6554 void *dh_blob, *session_blob;
6555 int *error = &argp->error;
6558 if (!sev_guest(kvm))
6561 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6564 start = kzalloc(sizeof(*start), GFP_KERNEL_ACCOUNT);
6569 if (params.dh_uaddr) {
6570 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6571 if (IS_ERR(dh_blob)) {
6572 ret = PTR_ERR(dh_blob);
6576 start->dh_cert_address = __sme_set(__pa(dh_blob));
6577 start->dh_cert_len = params.dh_len;
6580 session_blob = NULL;
6581 if (params.session_uaddr) {
6582 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6583 if (IS_ERR(session_blob)) {
6584 ret = PTR_ERR(session_blob);
6588 start->session_address = __sme_set(__pa(session_blob));
6589 start->session_len = params.session_len;
6592 start->handle = params.handle;
6593 start->policy = params.policy;
6595 /* create memory encryption context */
6596 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6598 goto e_free_session;
6600 /* Bind ASID to this guest */
6601 ret = sev_bind_asid(kvm, start->handle, error);
6603 goto e_free_session;
6605 /* return handle to userspace */
6606 params.handle = start->handle;
6607 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6608 sev_unbind_asid(kvm, start->handle);
6610 goto e_free_session;
6613 sev->handle = start->handle;
6614 sev->fd = argp->sev_fd;
6617 kfree(session_blob);
6625 static unsigned long get_num_contig_pages(unsigned long idx,
6626 struct page **inpages, unsigned long npages)
6628 unsigned long paddr, next_paddr;
6629 unsigned long i = idx + 1, pages = 1;
6631 /* find the number of contiguous pages starting from idx */
6632 paddr = __sme_page_pa(inpages[idx]);
6633 while (i < npages) {
6634 next_paddr = __sme_page_pa(inpages[i++]);
6635 if ((paddr + PAGE_SIZE) == next_paddr) {
6646 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6648 unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
6649 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6650 struct kvm_sev_launch_update_data params;
6651 struct sev_data_launch_update_data *data;
6652 struct page **inpages;
6655 if (!sev_guest(kvm))
6658 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6661 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6665 vaddr = params.uaddr;
6667 vaddr_end = vaddr + size;
6669 /* Lock the user memory. */
6670 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6677 * The LAUNCH_UPDATE command will perform in-place encryption of the
6678 * memory content (i.e it will write the same memory region with C=1).
6679 * It's possible that the cache may contain the data with C=0, i.e.,
6680 * unencrypted so invalidate it first.
6682 sev_clflush_pages(inpages, npages);
6684 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6688 * If the user buffer is not page-aligned, calculate the offset
6691 offset = vaddr & (PAGE_SIZE - 1);
6693 /* Calculate the number of pages that can be encrypted in one go. */
6694 pages = get_num_contig_pages(i, inpages, npages);
6696 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6698 data->handle = sev->handle;
6700 data->address = __sme_page_pa(inpages[i]) + offset;
6701 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6706 next_vaddr = vaddr + len;
6710 /* content of memory is updated, mark pages dirty */
6711 for (i = 0; i < npages; i++) {
6712 set_page_dirty_lock(inpages[i]);
6713 mark_page_accessed(inpages[i]);
6715 /* unlock the user pages */
6716 sev_unpin_memory(kvm, inpages, npages);
6722 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6724 void __user *measure = (void __user *)(uintptr_t)argp->data;
6725 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6726 struct sev_data_launch_measure *data;
6727 struct kvm_sev_launch_measure params;
6728 void __user *p = NULL;
6732 if (!sev_guest(kvm))
6735 if (copy_from_user(¶ms, measure, sizeof(params)))
6738 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6742 /* User wants to query the blob length */
6746 p = (void __user *)(uintptr_t)params.uaddr;
6748 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6754 blob = kmalloc(params.len, GFP_KERNEL);
6758 data->address = __psp_pa(blob);
6759 data->len = params.len;
6763 data->handle = sev->handle;
6764 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6767 * If we query the session length, FW responded with expected data.
6776 if (copy_to_user(p, blob, params.len))
6781 params.len = data->len;
6782 if (copy_to_user(measure, ¶ms, sizeof(params)))
6791 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6793 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6794 struct sev_data_launch_finish *data;
6797 if (!sev_guest(kvm))
6800 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6804 data->handle = sev->handle;
6805 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6811 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6813 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6814 struct kvm_sev_guest_status params;
6815 struct sev_data_guest_status *data;
6818 if (!sev_guest(kvm))
6821 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6825 data->handle = sev->handle;
6826 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6830 params.policy = data->policy;
6831 params.state = data->state;
6832 params.handle = data->handle;
6834 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6841 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6842 unsigned long dst, int size,
6843 int *error, bool enc)
6845 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6846 struct sev_data_dbg *data;
6849 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6853 data->handle = sev->handle;
6854 data->dst_addr = dst;
6855 data->src_addr = src;
6858 ret = sev_issue_cmd(kvm,
6859 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6865 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6866 unsigned long dst_paddr, int sz, int *err)
6871 * Its safe to read more than we are asked, caller should ensure that
6872 * destination has enough space.
6874 src_paddr = round_down(src_paddr, 16);
6875 offset = src_paddr & 15;
6876 sz = round_up(sz + offset, 16);
6878 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6881 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6882 unsigned long __user dst_uaddr,
6883 unsigned long dst_paddr,
6886 struct page *tpage = NULL;
6889 /* if inputs are not 16-byte then use intermediate buffer */
6890 if (!IS_ALIGNED(dst_paddr, 16) ||
6891 !IS_ALIGNED(paddr, 16) ||
6892 !IS_ALIGNED(size, 16)) {
6893 tpage = (void *)alloc_page(GFP_KERNEL);
6897 dst_paddr = __sme_page_pa(tpage);
6900 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6905 offset = paddr & 15;
6906 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6907 page_address(tpage) + offset, size))
6918 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6919 unsigned long __user vaddr,
6920 unsigned long dst_paddr,
6921 unsigned long __user dst_vaddr,
6922 int size, int *error)
6924 struct page *src_tpage = NULL;
6925 struct page *dst_tpage = NULL;
6926 int ret, len = size;
6928 /* If source buffer is not aligned then use an intermediate buffer */
6929 if (!IS_ALIGNED(vaddr, 16)) {
6930 src_tpage = alloc_page(GFP_KERNEL);
6934 if (copy_from_user(page_address(src_tpage),
6935 (void __user *)(uintptr_t)vaddr, size)) {
6936 __free_page(src_tpage);
6940 paddr = __sme_page_pa(src_tpage);
6944 * If destination buffer or length is not aligned then do read-modify-write:
6945 * - decrypt destination in an intermediate buffer
6946 * - copy the source buffer in an intermediate buffer
6947 * - use the intermediate buffer as source buffer
6949 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6952 dst_tpage = alloc_page(GFP_KERNEL);
6958 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6959 __sme_page_pa(dst_tpage), size, error);
6964 * If source is kernel buffer then use memcpy() otherwise
6967 dst_offset = dst_paddr & 15;
6970 memcpy(page_address(dst_tpage) + dst_offset,
6971 page_address(src_tpage), size);
6973 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6974 (void __user *)(uintptr_t)vaddr, size)) {
6980 paddr = __sme_page_pa(dst_tpage);
6981 dst_paddr = round_down(dst_paddr, 16);
6982 len = round_up(size, 16);
6985 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6989 __free_page(src_tpage);
6991 __free_page(dst_tpage);
6995 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6997 unsigned long vaddr, vaddr_end, next_vaddr;
6998 unsigned long dst_vaddr;
6999 struct page **src_p, **dst_p;
7000 struct kvm_sev_dbg debug;
7005 if (!sev_guest(kvm))
7008 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
7011 if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
7013 if (!debug.dst_uaddr)
7016 vaddr = debug.src_uaddr;
7018 vaddr_end = vaddr + size;
7019 dst_vaddr = debug.dst_uaddr;
7021 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
7022 int len, s_off, d_off;
7024 /* lock userspace source and destination page */
7025 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
7029 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
7031 sev_unpin_memory(kvm, src_p, n);
7036 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
7037 * memory content (i.e it will write the same memory region with C=1).
7038 * It's possible that the cache may contain the data with C=0, i.e.,
7039 * unencrypted so invalidate it first.
7041 sev_clflush_pages(src_p, 1);
7042 sev_clflush_pages(dst_p, 1);
7045 * Since user buffer may not be page aligned, calculate the
7046 * offset within the page.
7048 s_off = vaddr & ~PAGE_MASK;
7049 d_off = dst_vaddr & ~PAGE_MASK;
7050 len = min_t(size_t, (PAGE_SIZE - s_off), size);
7053 ret = __sev_dbg_decrypt_user(kvm,
7054 __sme_page_pa(src_p[0]) + s_off,
7056 __sme_page_pa(dst_p[0]) + d_off,
7059 ret = __sev_dbg_encrypt_user(kvm,
7060 __sme_page_pa(src_p[0]) + s_off,
7062 __sme_page_pa(dst_p[0]) + d_off,
7066 sev_unpin_memory(kvm, src_p, n);
7067 sev_unpin_memory(kvm, dst_p, n);
7072 next_vaddr = vaddr + len;
7073 dst_vaddr = dst_vaddr + len;
7080 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
7082 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7083 struct sev_data_launch_secret *data;
7084 struct kvm_sev_launch_secret params;
7085 struct page **pages;
7090 if (!sev_guest(kvm))
7093 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
7096 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
7101 * The secret must be copied into contiguous memory region, lets verify
7102 * that userspace memory pages are contiguous before we issue command.
7104 if (get_num_contig_pages(0, pages, n) != n) {
7106 goto e_unpin_memory;
7110 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
7112 goto e_unpin_memory;
7114 offset = params.guest_uaddr & (PAGE_SIZE - 1);
7115 data->guest_address = __sme_page_pa(pages[0]) + offset;
7116 data->guest_len = params.guest_len;
7118 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
7120 ret = PTR_ERR(blob);
7124 data->trans_address = __psp_pa(blob);
7125 data->trans_len = params.trans_len;
7127 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
7132 data->hdr_address = __psp_pa(hdr);
7133 data->hdr_len = params.hdr_len;
7135 data->handle = sev->handle;
7136 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
7145 sev_unpin_memory(kvm, pages, n);
7149 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
7151 struct kvm_sev_cmd sev_cmd;
7154 if (!svm_sev_enabled())
7157 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
7160 mutex_lock(&kvm->lock);
7162 switch (sev_cmd.id) {
7164 r = sev_guest_init(kvm, &sev_cmd);
7166 case KVM_SEV_LAUNCH_START:
7167 r = sev_launch_start(kvm, &sev_cmd);
7169 case KVM_SEV_LAUNCH_UPDATE_DATA:
7170 r = sev_launch_update_data(kvm, &sev_cmd);
7172 case KVM_SEV_LAUNCH_MEASURE:
7173 r = sev_launch_measure(kvm, &sev_cmd);
7175 case KVM_SEV_LAUNCH_FINISH:
7176 r = sev_launch_finish(kvm, &sev_cmd);
7178 case KVM_SEV_GUEST_STATUS:
7179 r = sev_guest_status(kvm, &sev_cmd);
7181 case KVM_SEV_DBG_DECRYPT:
7182 r = sev_dbg_crypt(kvm, &sev_cmd, true);
7184 case KVM_SEV_DBG_ENCRYPT:
7185 r = sev_dbg_crypt(kvm, &sev_cmd, false);
7187 case KVM_SEV_LAUNCH_SECRET:
7188 r = sev_launch_secret(kvm, &sev_cmd);
7195 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
7199 mutex_unlock(&kvm->lock);
7203 static int svm_register_enc_region(struct kvm *kvm,
7204 struct kvm_enc_region *range)
7206 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7207 struct enc_region *region;
7210 if (!sev_guest(kvm))
7213 if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
7216 region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
7220 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
7221 if (!region->pages) {
7227 * The guest may change the memory encryption attribute from C=0 -> C=1
7228 * or vice versa for this memory range. Lets make sure caches are
7229 * flushed to ensure that guest data gets written into memory with
7232 sev_clflush_pages(region->pages, region->npages);
7234 region->uaddr = range->addr;
7235 region->size = range->size;
7237 mutex_lock(&kvm->lock);
7238 list_add_tail(®ion->list, &sev->regions_list);
7239 mutex_unlock(&kvm->lock);
7248 static struct enc_region *
7249 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
7251 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7252 struct list_head *head = &sev->regions_list;
7253 struct enc_region *i;
7255 list_for_each_entry(i, head, list) {
7256 if (i->uaddr == range->addr &&
7257 i->size == range->size)
7265 static int svm_unregister_enc_region(struct kvm *kvm,
7266 struct kvm_enc_region *range)
7268 struct enc_region *region;
7271 mutex_lock(&kvm->lock);
7273 if (!sev_guest(kvm)) {
7278 region = find_enc_region(kvm, range);
7284 __unregister_enc_region_locked(kvm, region);
7286 mutex_unlock(&kvm->lock);
7290 mutex_unlock(&kvm->lock);
7294 static bool svm_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7296 unsigned long cr4 = kvm_read_cr4(vcpu);
7297 bool smep = cr4 & X86_CR4_SMEP;
7298 bool smap = cr4 & X86_CR4_SMAP;
7299 bool is_user = svm_get_cpl(vcpu) == 3;
7302 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
7305 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
7306 * possible that CPU microcode implementing DecodeAssist will fail
7307 * to read bytes of instruction which caused #NPF. In this case,
7308 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
7309 * return 0 instead of the correct guest instruction bytes.
7311 * This happens because CPU microcode reading instruction bytes
7312 * uses a special opcode which attempts to read data using CPL=0
7313 * priviledges. The microcode reads CS:RIP and if it hits a SMAP
7314 * fault, it gives up and returns no instruction bytes.
7317 * We reach here in case CPU supports DecodeAssist, raised #NPF and
7318 * returned 0 in GuestIntrBytes field of the VMCB.
7319 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
7320 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
7321 * in case vCPU CPL==3 (Because otherwise guest would have triggered
7322 * a SMEP fault instead of #NPF).
7323 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
7324 * As most guests enable SMAP if they have also enabled SMEP, use above
7325 * logic in order to attempt minimize false-positive of detecting errata
7326 * while still preserving all cases semantic correctness.
7329 * To determine what instruction the guest was executing, the hypervisor
7330 * will have to decode the instruction at the instruction pointer.
7332 * In non SEV guest, hypervisor will be able to read the guest
7333 * memory to decode the instruction pointer when insn_len is zero
7334 * so we return true to indicate that decoding is possible.
7336 * But in the SEV guest, the guest memory is encrypted with the
7337 * guest specific key and hypervisor will not be able to decode the
7338 * instruction pointer so we will not able to workaround it. Lets
7339 * print the error and request to kill the guest.
7341 if (smap && (!smep || is_user)) {
7342 if (!sev_guest(vcpu->kvm))
7345 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
7346 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7352 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7354 struct vcpu_svm *svm = to_svm(vcpu);
7357 * TODO: Last condition latch INIT signals on vCPU when
7358 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
7359 * To properly emulate the INIT intercept, SVM should implement
7360 * kvm_x86_ops->check_nested_events() and call nested_svm_vmexit()
7361 * there if an INIT signal is pending.
7363 return !gif_set(svm) ||
7364 (svm->vmcb->control.intercept & (1ULL << INTERCEPT_INIT));
7367 static bool svm_check_apicv_inhibit_reasons(ulong bit)
7369 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7370 BIT(APICV_INHIBIT_REASON_HYPERV) |
7371 BIT(APICV_INHIBIT_REASON_NESTED) |
7372 BIT(APICV_INHIBIT_REASON_IRQWIN) |
7373 BIT(APICV_INHIBIT_REASON_PIT_REINJ);
7375 return supported & BIT(bit);
7378 static void svm_pre_update_apicv_exec_ctrl(struct kvm *kvm, bool activate)
7380 avic_update_access_page(kvm, activate);
7383 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7384 .cpu_has_kvm_support = has_svm,
7385 .disabled_by_bios = is_disabled,
7386 .hardware_setup = svm_hardware_setup,
7387 .hardware_unsetup = svm_hardware_teardown,
7388 .check_processor_compatibility = svm_check_processor_compat,
7389 .hardware_enable = svm_hardware_enable,
7390 .hardware_disable = svm_hardware_disable,
7391 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
7392 .has_emulated_msr = svm_has_emulated_msr,
7394 .vcpu_create = svm_create_vcpu,
7395 .vcpu_free = svm_free_vcpu,
7396 .vcpu_reset = svm_vcpu_reset,
7398 .vm_alloc = svm_vm_alloc,
7399 .vm_free = svm_vm_free,
7400 .vm_init = svm_vm_init,
7401 .vm_destroy = svm_vm_destroy,
7403 .prepare_guest_switch = svm_prepare_guest_switch,
7404 .vcpu_load = svm_vcpu_load,
7405 .vcpu_put = svm_vcpu_put,
7406 .vcpu_blocking = svm_vcpu_blocking,
7407 .vcpu_unblocking = svm_vcpu_unblocking,
7409 .update_bp_intercept = update_bp_intercept,
7410 .get_msr_feature = svm_get_msr_feature,
7411 .get_msr = svm_get_msr,
7412 .set_msr = svm_set_msr,
7413 .get_segment_base = svm_get_segment_base,
7414 .get_segment = svm_get_segment,
7415 .set_segment = svm_set_segment,
7416 .get_cpl = svm_get_cpl,
7417 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
7418 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
7419 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
7420 .set_cr0 = svm_set_cr0,
7421 .set_cr3 = svm_set_cr3,
7422 .set_cr4 = svm_set_cr4,
7423 .set_efer = svm_set_efer,
7424 .get_idt = svm_get_idt,
7425 .set_idt = svm_set_idt,
7426 .get_gdt = svm_get_gdt,
7427 .set_gdt = svm_set_gdt,
7428 .get_dr6 = svm_get_dr6,
7429 .set_dr6 = svm_set_dr6,
7430 .set_dr7 = svm_set_dr7,
7431 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
7432 .cache_reg = svm_cache_reg,
7433 .get_rflags = svm_get_rflags,
7434 .set_rflags = svm_set_rflags,
7436 .tlb_flush = svm_flush_tlb,
7437 .tlb_flush_gva = svm_flush_tlb_gva,
7439 .run = svm_vcpu_run,
7440 .handle_exit = handle_exit,
7441 .skip_emulated_instruction = skip_emulated_instruction,
7442 .set_interrupt_shadow = svm_set_interrupt_shadow,
7443 .get_interrupt_shadow = svm_get_interrupt_shadow,
7444 .patch_hypercall = svm_patch_hypercall,
7445 .set_irq = svm_set_irq,
7446 .set_nmi = svm_inject_nmi,
7447 .queue_exception = svm_queue_exception,
7448 .cancel_injection = svm_cancel_injection,
7449 .interrupt_allowed = svm_interrupt_allowed,
7450 .nmi_allowed = svm_nmi_allowed,
7451 .get_nmi_mask = svm_get_nmi_mask,
7452 .set_nmi_mask = svm_set_nmi_mask,
7453 .enable_nmi_window = enable_nmi_window,
7454 .enable_irq_window = enable_irq_window,
7455 .update_cr8_intercept = update_cr8_intercept,
7456 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
7457 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
7458 .check_apicv_inhibit_reasons = svm_check_apicv_inhibit_reasons,
7459 .pre_update_apicv_exec_ctrl = svm_pre_update_apicv_exec_ctrl,
7460 .load_eoi_exitmap = svm_load_eoi_exitmap,
7461 .hwapic_irr_update = svm_hwapic_irr_update,
7462 .hwapic_isr_update = svm_hwapic_isr_update,
7463 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
7464 .apicv_post_state_restore = avic_post_state_restore,
7466 .set_tss_addr = svm_set_tss_addr,
7467 .set_identity_map_addr = svm_set_identity_map_addr,
7468 .get_tdp_level = get_npt_level,
7469 .get_mt_mask = svm_get_mt_mask,
7471 .get_exit_info = svm_get_exit_info,
7473 .get_lpage_level = svm_get_lpage_level,
7475 .cpuid_update = svm_cpuid_update,
7477 .rdtscp_supported = svm_rdtscp_supported,
7478 .invpcid_supported = svm_invpcid_supported,
7479 .mpx_supported = svm_mpx_supported,
7480 .xsaves_supported = svm_xsaves_supported,
7481 .umip_emulated = svm_umip_emulated,
7482 .pt_supported = svm_pt_supported,
7483 .pku_supported = svm_pku_supported,
7485 .set_supported_cpuid = svm_set_supported_cpuid,
7487 .has_wbinvd_exit = svm_has_wbinvd_exit,
7489 .read_l1_tsc_offset = svm_read_l1_tsc_offset,
7490 .write_l1_tsc_offset = svm_write_l1_tsc_offset,
7492 .set_tdp_cr3 = set_tdp_cr3,
7494 .check_intercept = svm_check_intercept,
7495 .handle_exit_irqoff = svm_handle_exit_irqoff,
7497 .request_immediate_exit = __kvm_request_immediate_exit,
7499 .sched_in = svm_sched_in,
7501 .pmu_ops = &amd_pmu_ops,
7502 .deliver_posted_interrupt = svm_deliver_avic_intr,
7503 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
7504 .update_pi_irte = svm_update_pi_irte,
7505 .setup_mce = svm_setup_mce,
7507 .smi_allowed = svm_smi_allowed,
7508 .pre_enter_smm = svm_pre_enter_smm,
7509 .pre_leave_smm = svm_pre_leave_smm,
7510 .enable_smi_window = enable_smi_window,
7512 .mem_enc_op = svm_mem_enc_op,
7513 .mem_enc_reg_region = svm_register_enc_region,
7514 .mem_enc_unreg_region = svm_unregister_enc_region,
7516 .nested_enable_evmcs = NULL,
7517 .nested_get_evmcs_version = NULL,
7519 .need_emulation_on_page_fault = svm_need_emulation_on_page_fault,
7521 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
7524 static int __init svm_init(void)
7526 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7527 __alignof__(struct vcpu_svm), THIS_MODULE);
7530 static void __exit svm_exit(void)
7535 module_init(svm_init)
7536 module_exit(svm_exit)