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");
61 static const struct x86_cpu_id svm_cpu_id[] = {
62 X86_FEATURE_MATCH(X86_FEATURE_SVM),
65 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
68 #define IOPM_ALLOC_ORDER 2
69 #define MSRPM_ALLOC_ORDER 1
71 #define SEG_TYPE_LDT 2
72 #define SEG_TYPE_BUSY_TSS16 3
74 #define SVM_FEATURE_LBRV (1 << 1)
75 #define SVM_FEATURE_SVML (1 << 2)
76 #define SVM_FEATURE_TSC_RATE (1 << 4)
77 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
78 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
79 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
80 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
82 #define SVM_AVIC_DOORBELL 0xc001011b
84 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
85 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
86 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
88 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
90 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
91 #define TSC_RATIO_MIN 0x0000000000000001ULL
92 #define TSC_RATIO_MAX 0x000000ffffffffffULL
94 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
97 * 0xff is broadcast, so the max index allowed for physical APIC ID
98 * table is 0xfe. APIC IDs above 0xff are reserved.
100 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
102 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
103 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
104 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
106 /* AVIC GATAG is encoded using VM and VCPU IDs */
107 #define AVIC_VCPU_ID_BITS 8
108 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
110 #define AVIC_VM_ID_BITS 24
111 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
112 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
114 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
115 (y & AVIC_VCPU_ID_MASK))
116 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
117 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
119 static bool erratum_383_found __read_mostly;
121 static const u32 host_save_user_msrs[] = {
123 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
126 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
130 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
132 struct kvm_sev_info {
133 bool active; /* SEV enabled guest */
134 unsigned int asid; /* ASID used for this guest */
135 unsigned int handle; /* SEV firmware handle */
136 int fd; /* SEV device fd */
137 unsigned long pages_locked; /* Number of pages locked */
138 struct list_head regions_list; /* List of registered regions */
144 /* Struct members for AVIC */
146 struct page *avic_logical_id_table_page;
147 struct page *avic_physical_id_table_page;
148 struct hlist_node hnode;
150 struct kvm_sev_info sev_info;
155 struct nested_state {
161 /* These are the merged vectors */
164 /* gpa pointers to the real vectors */
168 /* A VMEXIT is required but not yet emulated */
171 /* cache for intercepts of the guest */
174 u32 intercept_exceptions;
177 /* Nested Paging related state */
181 #define MSRPM_OFFSETS 16
182 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
185 * Set osvw_len to higher value when updated Revision Guides
186 * are published and we know what the new status bits are
188 static uint64_t osvw_len = 4, osvw_status;
191 struct kvm_vcpu vcpu;
193 unsigned long vmcb_pa;
194 struct svm_cpu_data *svm_data;
195 uint64_t asid_generation;
196 uint64_t sysenter_esp;
197 uint64_t sysenter_eip;
204 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
214 * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
215 * translated into the appropriate L2_CFG bits on the host to
216 * perform speculative control.
224 struct nested_state nested;
227 u64 nmi_singlestep_guest_rflags;
229 unsigned int3_injected;
230 unsigned long int3_rip;
232 /* cached guest cpuid flags for faster access */
233 bool nrips_enabled : 1;
237 struct page *avic_backing_page;
238 u64 *avic_physical_id_cache;
239 bool avic_is_running;
242 * Per-vcpu list of struct amd_svm_iommu_ir:
243 * This is used mainly to store interrupt remapping information used
244 * when update the vcpu affinity. This avoids the need to scan for
245 * IRTE and try to match ga_tag in the IOMMU driver.
247 struct list_head ir_list;
248 spinlock_t ir_list_lock;
250 /* which host CPU was used for running this vcpu */
251 unsigned int last_cpu;
255 * This is a wrapper of struct amd_iommu_ir_data.
257 struct amd_svm_iommu_ir {
258 struct list_head node; /* Used by SVM for per-vcpu ir_list */
259 void *data; /* Storing pointer to struct amd_ir_data */
262 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
263 #define AVIC_LOGICAL_ID_ENTRY_VALID_BIT 31
264 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
266 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
267 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
268 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
269 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
271 static DEFINE_PER_CPU(u64, current_tsc_ratio);
272 #define TSC_RATIO_DEFAULT 0x0100000000ULL
274 #define MSR_INVALID 0xffffffffU
276 static const struct svm_direct_access_msrs {
277 u32 index; /* Index of the MSR */
278 bool always; /* True if intercept is always on */
279 } direct_access_msrs[] = {
280 { .index = MSR_STAR, .always = true },
281 { .index = MSR_IA32_SYSENTER_CS, .always = true },
283 { .index = MSR_GS_BASE, .always = true },
284 { .index = MSR_FS_BASE, .always = true },
285 { .index = MSR_KERNEL_GS_BASE, .always = true },
286 { .index = MSR_LSTAR, .always = true },
287 { .index = MSR_CSTAR, .always = true },
288 { .index = MSR_SYSCALL_MASK, .always = true },
290 { .index = MSR_IA32_SPEC_CTRL, .always = false },
291 { .index = MSR_IA32_PRED_CMD, .always = false },
292 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
293 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
294 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
295 { .index = MSR_IA32_LASTINTTOIP, .always = false },
296 { .index = MSR_INVALID, .always = false },
299 /* enable NPT for AMD64 and X86 with PAE */
300 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
301 static bool npt_enabled = true;
303 static bool npt_enabled;
307 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
308 * pause_filter_count: On processors that support Pause filtering(indicated
309 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
310 * count value. On VMRUN this value is loaded into an internal counter.
311 * Each time a pause instruction is executed, this counter is decremented
312 * until it reaches zero at which time a #VMEXIT is generated if pause
313 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
314 * Intercept Filtering for more details.
315 * This also indicate if ple logic enabled.
317 * pause_filter_thresh: In addition, some processor families support advanced
318 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
319 * the amount of time a guest is allowed to execute in a pause loop.
320 * In this mode, a 16-bit pause filter threshold field is added in the
321 * VMCB. The threshold value is a cycle count that is used to reset the
322 * pause counter. As with simple pause filtering, VMRUN loads the pause
323 * count value from VMCB into an internal counter. Then, on each pause
324 * instruction the hardware checks the elapsed number of cycles since
325 * the most recent pause instruction against the pause filter threshold.
326 * If the elapsed cycle count is greater than the pause filter threshold,
327 * then the internal pause count is reloaded from the VMCB and execution
328 * continues. If the elapsed cycle count is less than the pause filter
329 * threshold, then the internal pause count is decremented. If the count
330 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
331 * triggered. If advanced pause filtering is supported and pause filter
332 * threshold field is set to zero, the filter will operate in the simpler,
336 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
337 module_param(pause_filter_thresh, ushort, 0444);
339 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
340 module_param(pause_filter_count, ushort, 0444);
342 /* Default doubles per-vcpu window every exit. */
343 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
344 module_param(pause_filter_count_grow, ushort, 0444);
346 /* Default resets per-vcpu window every exit to pause_filter_count. */
347 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
348 module_param(pause_filter_count_shrink, ushort, 0444);
350 /* Default is to compute the maximum so we can never overflow. */
351 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
352 module_param(pause_filter_count_max, ushort, 0444);
354 /* allow nested paging (virtualized MMU) for all guests */
355 static int npt = true;
356 module_param(npt, int, S_IRUGO);
358 /* allow nested virtualization in KVM/SVM */
359 static int nested = true;
360 module_param(nested, int, S_IRUGO);
362 /* enable / disable AVIC */
364 #ifdef CONFIG_X86_LOCAL_APIC
365 module_param(avic, int, S_IRUGO);
368 /* enable/disable Next RIP Save */
369 static int nrips = true;
370 module_param(nrips, int, 0444);
372 /* enable/disable Virtual VMLOAD VMSAVE */
373 static int vls = true;
374 module_param(vls, int, 0444);
376 /* enable/disable Virtual GIF */
377 static int vgif = true;
378 module_param(vgif, int, 0444);
380 /* enable/disable SEV support */
381 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
382 module_param(sev, int, 0444);
384 static bool __read_mostly dump_invalid_vmcb = 0;
385 module_param(dump_invalid_vmcb, bool, 0644);
387 static u8 rsm_ins_bytes[] = "\x0f\xaa";
389 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
390 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
391 static void svm_complete_interrupts(struct vcpu_svm *svm);
392 static void svm_toggle_avic_for_irq_window(struct kvm_vcpu *vcpu, bool activate);
393 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu);
395 static int nested_svm_exit_handled(struct vcpu_svm *svm);
396 static int nested_svm_intercept(struct vcpu_svm *svm);
397 static int nested_svm_vmexit(struct vcpu_svm *svm);
398 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
399 bool has_error_code, u32 error_code);
402 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
403 pause filter count */
404 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
405 VMCB_ASID, /* ASID */
406 VMCB_INTR, /* int_ctl, int_vector */
407 VMCB_NPT, /* npt_en, nCR3, gPAT */
408 VMCB_CR, /* CR0, CR3, CR4, EFER */
409 VMCB_DR, /* DR6, DR7 */
410 VMCB_DT, /* GDT, IDT */
411 VMCB_SEG, /* CS, DS, SS, ES, CPL */
412 VMCB_CR2, /* CR2 only */
413 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
414 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
415 * AVIC PHYSICAL_TABLE pointer,
416 * AVIC LOGICAL_TABLE pointer
421 /* TPR and CR2 are always written before VMRUN */
422 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
424 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
426 static int sev_flush_asids(void);
427 static DECLARE_RWSEM(sev_deactivate_lock);
428 static DEFINE_MUTEX(sev_bitmap_lock);
429 static unsigned int max_sev_asid;
430 static unsigned int min_sev_asid;
431 static unsigned long *sev_asid_bitmap;
432 static unsigned long *sev_reclaim_asid_bitmap;
433 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
436 struct list_head list;
437 unsigned long npages;
444 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
446 return container_of(kvm, struct kvm_svm, kvm);
449 static inline bool svm_sev_enabled(void)
451 return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
454 static inline bool sev_guest(struct kvm *kvm)
456 #ifdef CONFIG_KVM_AMD_SEV
457 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
465 static inline int sev_get_asid(struct kvm *kvm)
467 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
472 static inline void mark_all_dirty(struct vmcb *vmcb)
474 vmcb->control.clean = 0;
477 static inline void mark_all_clean(struct vmcb *vmcb)
479 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
480 & ~VMCB_ALWAYS_DIRTY_MASK;
483 static inline void mark_dirty(struct vmcb *vmcb, int bit)
485 vmcb->control.clean &= ~(1 << bit);
488 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
490 return container_of(vcpu, struct vcpu_svm, vcpu);
493 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
495 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
496 mark_dirty(svm->vmcb, VMCB_AVIC);
499 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
501 struct vcpu_svm *svm = to_svm(vcpu);
502 u64 *entry = svm->avic_physical_id_cache;
507 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
510 static void recalc_intercepts(struct vcpu_svm *svm)
512 struct vmcb_control_area *c, *h;
513 struct nested_state *g;
515 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
517 if (!is_guest_mode(&svm->vcpu))
520 c = &svm->vmcb->control;
521 h = &svm->nested.hsave->control;
524 c->intercept_cr = h->intercept_cr;
525 c->intercept_dr = h->intercept_dr;
526 c->intercept_exceptions = h->intercept_exceptions;
527 c->intercept = h->intercept;
529 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
530 /* We only want the cr8 intercept bits of L1 */
531 c->intercept_cr &= ~(1U << INTERCEPT_CR8_READ);
532 c->intercept_cr &= ~(1U << INTERCEPT_CR8_WRITE);
535 * Once running L2 with HF_VINTR_MASK, EFLAGS.IF does not
536 * affect any interrupt we may want to inject; therefore,
537 * interrupt window vmexits are irrelevant to L0.
539 c->intercept &= ~(1ULL << INTERCEPT_VINTR);
542 /* We don't want to see VMMCALLs from a nested guest */
543 c->intercept &= ~(1ULL << INTERCEPT_VMMCALL);
545 c->intercept_cr |= g->intercept_cr;
546 c->intercept_dr |= g->intercept_dr;
547 c->intercept_exceptions |= g->intercept_exceptions;
548 c->intercept |= g->intercept;
551 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
553 if (is_guest_mode(&svm->vcpu))
554 return svm->nested.hsave;
559 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
561 struct vmcb *vmcb = get_host_vmcb(svm);
563 vmcb->control.intercept_cr |= (1U << bit);
565 recalc_intercepts(svm);
568 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
570 struct vmcb *vmcb = get_host_vmcb(svm);
572 vmcb->control.intercept_cr &= ~(1U << bit);
574 recalc_intercepts(svm);
577 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
579 struct vmcb *vmcb = get_host_vmcb(svm);
581 return vmcb->control.intercept_cr & (1U << bit);
584 static inline void set_dr_intercepts(struct vcpu_svm *svm)
586 struct vmcb *vmcb = get_host_vmcb(svm);
588 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
589 | (1 << INTERCEPT_DR1_READ)
590 | (1 << INTERCEPT_DR2_READ)
591 | (1 << INTERCEPT_DR3_READ)
592 | (1 << INTERCEPT_DR4_READ)
593 | (1 << INTERCEPT_DR5_READ)
594 | (1 << INTERCEPT_DR6_READ)
595 | (1 << INTERCEPT_DR7_READ)
596 | (1 << INTERCEPT_DR0_WRITE)
597 | (1 << INTERCEPT_DR1_WRITE)
598 | (1 << INTERCEPT_DR2_WRITE)
599 | (1 << INTERCEPT_DR3_WRITE)
600 | (1 << INTERCEPT_DR4_WRITE)
601 | (1 << INTERCEPT_DR5_WRITE)
602 | (1 << INTERCEPT_DR6_WRITE)
603 | (1 << INTERCEPT_DR7_WRITE);
605 recalc_intercepts(svm);
608 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
610 struct vmcb *vmcb = get_host_vmcb(svm);
612 vmcb->control.intercept_dr = 0;
614 recalc_intercepts(svm);
617 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
619 struct vmcb *vmcb = get_host_vmcb(svm);
621 vmcb->control.intercept_exceptions |= (1U << bit);
623 recalc_intercepts(svm);
626 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
628 struct vmcb *vmcb = get_host_vmcb(svm);
630 vmcb->control.intercept_exceptions &= ~(1U << bit);
632 recalc_intercepts(svm);
635 static inline void set_intercept(struct vcpu_svm *svm, int bit)
637 struct vmcb *vmcb = get_host_vmcb(svm);
639 vmcb->control.intercept |= (1ULL << bit);
641 recalc_intercepts(svm);
644 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
646 struct vmcb *vmcb = get_host_vmcb(svm);
648 vmcb->control.intercept &= ~(1ULL << bit);
650 recalc_intercepts(svm);
653 static inline bool is_intercept(struct vcpu_svm *svm, int bit)
655 return (svm->vmcb->control.intercept & (1ULL << bit)) != 0;
658 static inline bool vgif_enabled(struct vcpu_svm *svm)
660 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
663 static inline void enable_gif(struct vcpu_svm *svm)
665 if (vgif_enabled(svm))
666 svm->vmcb->control.int_ctl |= V_GIF_MASK;
668 svm->vcpu.arch.hflags |= HF_GIF_MASK;
671 static inline void disable_gif(struct vcpu_svm *svm)
673 if (vgif_enabled(svm))
674 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
676 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
679 static inline bool gif_set(struct vcpu_svm *svm)
681 if (vgif_enabled(svm))
682 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
684 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
687 static unsigned long iopm_base;
689 struct kvm_ldttss_desc {
692 unsigned base1:8, type:5, dpl:2, p:1;
693 unsigned limit1:4, zero0:3, g:1, base2:8;
696 } __attribute__((packed));
698 struct svm_cpu_data {
705 struct kvm_ldttss_desc *tss_desc;
707 struct page *save_area;
708 struct vmcb *current_vmcb;
710 /* index = sev_asid, value = vmcb pointer */
711 struct vmcb **sev_vmcbs;
714 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
716 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
718 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
719 #define MSRS_RANGE_SIZE 2048
720 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
722 static u32 svm_msrpm_offset(u32 msr)
727 for (i = 0; i < NUM_MSR_MAPS; i++) {
728 if (msr < msrpm_ranges[i] ||
729 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
732 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
733 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
735 /* Now we have the u8 offset - but need the u32 offset */
739 /* MSR not in any range */
743 #define MAX_INST_SIZE 15
745 static inline void clgi(void)
747 asm volatile (__ex("clgi"));
750 static inline void stgi(void)
752 asm volatile (__ex("stgi"));
755 static inline void invlpga(unsigned long addr, u32 asid)
757 asm volatile (__ex("invlpga %1, %0") : : "c"(asid), "a"(addr));
760 static int get_npt_level(struct kvm_vcpu *vcpu)
763 return PT64_ROOT_4LEVEL;
765 return PT32E_ROOT_LEVEL;
769 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
771 vcpu->arch.efer = efer;
774 /* Shadow paging assumes NX to be available. */
777 if (!(efer & EFER_LMA))
781 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
782 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
785 static int is_external_interrupt(u32 info)
787 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
788 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
791 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
793 struct vcpu_svm *svm = to_svm(vcpu);
796 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
797 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
801 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
803 struct vcpu_svm *svm = to_svm(vcpu);
806 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
808 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
812 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
814 struct vcpu_svm *svm = to_svm(vcpu);
816 if (nrips && svm->vmcb->control.next_rip != 0) {
817 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
818 svm->next_rip = svm->vmcb->control.next_rip;
821 if (!svm->next_rip) {
822 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
825 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
826 pr_err("%s: ip 0x%lx next 0x%llx\n",
827 __func__, kvm_rip_read(vcpu), svm->next_rip);
828 kvm_rip_write(vcpu, svm->next_rip);
830 svm_set_interrupt_shadow(vcpu, 0);
835 static void svm_queue_exception(struct kvm_vcpu *vcpu)
837 struct vcpu_svm *svm = to_svm(vcpu);
838 unsigned nr = vcpu->arch.exception.nr;
839 bool has_error_code = vcpu->arch.exception.has_error_code;
840 bool reinject = vcpu->arch.exception.injected;
841 u32 error_code = vcpu->arch.exception.error_code;
844 * If we are within a nested VM we'd better #VMEXIT and let the guest
845 * handle the exception
848 nested_svm_check_exception(svm, nr, has_error_code, error_code))
851 kvm_deliver_exception_payload(&svm->vcpu);
853 if (nr == BP_VECTOR && !nrips) {
854 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
857 * For guest debugging where we have to reinject #BP if some
858 * INT3 is guest-owned:
859 * Emulate nRIP by moving RIP forward. Will fail if injection
860 * raises a fault that is not intercepted. Still better than
861 * failing in all cases.
863 (void)skip_emulated_instruction(&svm->vcpu);
864 rip = kvm_rip_read(&svm->vcpu);
865 svm->int3_rip = rip + svm->vmcb->save.cs.base;
866 svm->int3_injected = rip - old_rip;
869 svm->vmcb->control.event_inj = nr
871 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
872 | SVM_EVTINJ_TYPE_EXEPT;
873 svm->vmcb->control.event_inj_err = error_code;
876 static void svm_init_erratum_383(void)
882 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
885 /* Use _safe variants to not break nested virtualization */
886 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
892 low = lower_32_bits(val);
893 high = upper_32_bits(val);
895 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
897 erratum_383_found = true;
900 static void svm_init_osvw(struct kvm_vcpu *vcpu)
903 * Guests should see errata 400 and 415 as fixed (assuming that
904 * HLT and IO instructions are intercepted).
906 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
907 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
910 * By increasing VCPU's osvw.length to 3 we are telling the guest that
911 * all osvw.status bits inside that length, including bit 0 (which is
912 * reserved for erratum 298), are valid. However, if host processor's
913 * osvw_len is 0 then osvw_status[0] carries no information. We need to
914 * be conservative here and therefore we tell the guest that erratum 298
915 * is present (because we really don't know).
917 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
918 vcpu->arch.osvw.status |= 1;
921 static int has_svm(void)
925 if (!cpu_has_svm(&msg)) {
926 printk(KERN_INFO "has_svm: %s\n", msg);
933 static void svm_hardware_disable(void)
935 /* Make sure we clean up behind us */
936 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
937 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
941 amd_pmu_disable_virt();
944 static int svm_hardware_enable(void)
947 struct svm_cpu_data *sd;
949 struct desc_struct *gdt;
950 int me = raw_smp_processor_id();
952 rdmsrl(MSR_EFER, efer);
953 if (efer & EFER_SVME)
957 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
960 sd = per_cpu(svm_data, me);
962 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
966 sd->asid_generation = 1;
967 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
968 sd->next_asid = sd->max_asid + 1;
969 sd->min_asid = max_sev_asid + 1;
971 gdt = get_current_gdt_rw();
972 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
974 wrmsrl(MSR_EFER, efer | EFER_SVME);
976 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
978 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
979 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
980 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
987 * Note that it is possible to have a system with mixed processor
988 * revisions and therefore different OSVW bits. If bits are not the same
989 * on different processors then choose the worst case (i.e. if erratum
990 * is present on one processor and not on another then assume that the
991 * erratum is present everywhere).
993 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
994 uint64_t len, status = 0;
997 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
999 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
1003 osvw_status = osvw_len = 0;
1007 osvw_status |= status;
1008 osvw_status &= (1ULL << osvw_len) - 1;
1011 osvw_status = osvw_len = 0;
1013 svm_init_erratum_383();
1015 amd_pmu_enable_virt();
1020 static void svm_cpu_uninit(int cpu)
1022 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
1027 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
1028 kfree(sd->sev_vmcbs);
1029 __free_page(sd->save_area);
1033 static int svm_cpu_init(int cpu)
1035 struct svm_cpu_data *sd;
1037 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
1041 sd->save_area = alloc_page(GFP_KERNEL);
1045 if (svm_sev_enabled()) {
1046 sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1050 goto free_save_area;
1053 per_cpu(svm_data, cpu) = sd;
1058 __free_page(sd->save_area);
1065 static bool valid_msr_intercept(u32 index)
1069 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1070 if (direct_access_msrs[i].index == index)
1076 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1083 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1084 to_svm(vcpu)->msrpm;
1086 offset = svm_msrpm_offset(msr);
1087 bit_write = 2 * (msr & 0x0f) + 1;
1088 tmp = msrpm[offset];
1090 BUG_ON(offset == MSR_INVALID);
1092 return !!test_bit(bit_write, &tmp);
1095 static void set_msr_interception(u32 *msrpm, unsigned msr,
1096 int read, int write)
1098 u8 bit_read, bit_write;
1103 * If this warning triggers extend the direct_access_msrs list at the
1104 * beginning of the file
1106 WARN_ON(!valid_msr_intercept(msr));
1108 offset = svm_msrpm_offset(msr);
1109 bit_read = 2 * (msr & 0x0f);
1110 bit_write = 2 * (msr & 0x0f) + 1;
1111 tmp = msrpm[offset];
1113 BUG_ON(offset == MSR_INVALID);
1115 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
1116 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1118 msrpm[offset] = tmp;
1121 static void svm_vcpu_init_msrpm(u32 *msrpm)
1125 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1127 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1128 if (!direct_access_msrs[i].always)
1131 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1135 static void add_msr_offset(u32 offset)
1139 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1141 /* Offset already in list? */
1142 if (msrpm_offsets[i] == offset)
1145 /* Slot used by another offset? */
1146 if (msrpm_offsets[i] != MSR_INVALID)
1149 /* Add offset to list */
1150 msrpm_offsets[i] = offset;
1156 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1157 * increase MSRPM_OFFSETS in this case.
1162 static void init_msrpm_offsets(void)
1166 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1168 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1171 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1172 BUG_ON(offset == MSR_INVALID);
1174 add_msr_offset(offset);
1178 static void svm_enable_lbrv(struct vcpu_svm *svm)
1180 u32 *msrpm = svm->msrpm;
1182 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1183 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1184 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1185 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1186 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1189 static void svm_disable_lbrv(struct vcpu_svm *svm)
1191 u32 *msrpm = svm->msrpm;
1193 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1194 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1195 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1196 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1197 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1200 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1202 svm->nmi_singlestep = false;
1204 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1205 /* Clear our flags if they were not set by the guest */
1206 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1207 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1208 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1209 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1214 * This hash table is used to map VM_ID to a struct kvm_svm,
1215 * when handling AMD IOMMU GALOG notification to schedule in
1216 * a particular vCPU.
1218 #define SVM_VM_DATA_HASH_BITS 8
1219 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1220 static u32 next_vm_id = 0;
1221 static bool next_vm_id_wrapped = 0;
1222 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1225 * This function is called from IOMMU driver to notify
1226 * SVM to schedule in a particular vCPU of a particular VM.
1228 static int avic_ga_log_notifier(u32 ga_tag)
1230 unsigned long flags;
1231 struct kvm_svm *kvm_svm;
1232 struct kvm_vcpu *vcpu = NULL;
1233 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1234 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1236 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1237 trace_kvm_avic_ga_log(vm_id, vcpu_id);
1239 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1240 hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1241 if (kvm_svm->avic_vm_id != vm_id)
1243 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1246 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1249 * At this point, the IOMMU should have already set the pending
1250 * bit in the vAPIC backing page. So, we just need to schedule
1254 kvm_vcpu_wake_up(vcpu);
1259 static __init int sev_hardware_setup(void)
1261 struct sev_user_data_status *status;
1264 /* Maximum number of encrypted guests supported simultaneously */
1265 max_sev_asid = cpuid_ecx(0x8000001F);
1270 /* Minimum ASID value that should be used for SEV guest */
1271 min_sev_asid = cpuid_edx(0x8000001F);
1273 /* Initialize SEV ASID bitmaps */
1274 sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1275 if (!sev_asid_bitmap)
1278 sev_reclaim_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1279 if (!sev_reclaim_asid_bitmap)
1282 status = kmalloc(sizeof(*status), GFP_KERNEL);
1287 * Check SEV platform status.
1289 * PLATFORM_STATUS can be called in any state, if we failed to query
1290 * the PLATFORM status then either PSP firmware does not support SEV
1291 * feature or SEV firmware is dead.
1293 rc = sev_platform_status(status, NULL);
1297 pr_info("SEV supported\n");
1304 static void grow_ple_window(struct kvm_vcpu *vcpu)
1306 struct vcpu_svm *svm = to_svm(vcpu);
1307 struct vmcb_control_area *control = &svm->vmcb->control;
1308 int old = control->pause_filter_count;
1310 control->pause_filter_count = __grow_ple_window(old,
1312 pause_filter_count_grow,
1313 pause_filter_count_max);
1315 if (control->pause_filter_count != old) {
1316 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1317 trace_kvm_ple_window_update(vcpu->vcpu_id,
1318 control->pause_filter_count, old);
1322 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1324 struct vcpu_svm *svm = to_svm(vcpu);
1325 struct vmcb_control_area *control = &svm->vmcb->control;
1326 int old = control->pause_filter_count;
1328 control->pause_filter_count =
1329 __shrink_ple_window(old,
1331 pause_filter_count_shrink,
1332 pause_filter_count);
1333 if (control->pause_filter_count != old) {
1334 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1335 trace_kvm_ple_window_update(vcpu->vcpu_id,
1336 control->pause_filter_count, old);
1341 * The default MMIO mask is a single bit (excluding the present bit),
1342 * which could conflict with the memory encryption bit. Check for
1343 * memory encryption support and override the default MMIO mask if
1344 * memory encryption is enabled.
1346 static __init void svm_adjust_mmio_mask(void)
1348 unsigned int enc_bit, mask_bit;
1351 /* If there is no memory encryption support, use existing mask */
1352 if (cpuid_eax(0x80000000) < 0x8000001f)
1355 /* If memory encryption is not enabled, use existing mask */
1356 rdmsrl(MSR_K8_SYSCFG, msr);
1357 if (!(msr & MSR_K8_SYSCFG_MEM_ENCRYPT))
1360 enc_bit = cpuid_ebx(0x8000001f) & 0x3f;
1361 mask_bit = boot_cpu_data.x86_phys_bits;
1363 /* Increment the mask bit if it is the same as the encryption bit */
1364 if (enc_bit == mask_bit)
1368 * If the mask bit location is below 52, then some bits above the
1369 * physical addressing limit will always be reserved, so use the
1370 * rsvd_bits() function to generate the mask. This mask, along with
1371 * the present bit, will be used to generate a page fault with
1374 * If the mask bit location is 52 (or above), then clear the mask.
1376 mask = (mask_bit < 52) ? rsvd_bits(mask_bit, 51) | PT_PRESENT_MASK : 0;
1378 kvm_mmu_set_mmio_spte_mask(mask, mask, PT_WRITABLE_MASK | PT_USER_MASK);
1381 static void svm_hardware_teardown(void)
1385 if (svm_sev_enabled()) {
1386 bitmap_free(sev_asid_bitmap);
1387 bitmap_free(sev_reclaim_asid_bitmap);
1392 for_each_possible_cpu(cpu)
1393 svm_cpu_uninit(cpu);
1395 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1399 static __init void svm_set_cpu_caps(void)
1405 /* CPUID 0x80000001 and 0x8000000A (SVM features) */
1407 kvm_cpu_cap_set(X86_FEATURE_SVM);
1410 kvm_cpu_cap_set(X86_FEATURE_NRIPS);
1413 kvm_cpu_cap_set(X86_FEATURE_NPT);
1416 /* CPUID 0x80000008 */
1417 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
1418 boot_cpu_has(X86_FEATURE_AMD_SSBD))
1419 kvm_cpu_cap_set(X86_FEATURE_VIRT_SSBD);
1422 static __init int svm_hardware_setup(void)
1425 struct page *iopm_pages;
1429 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1434 iopm_va = page_address(iopm_pages);
1435 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1436 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1438 init_msrpm_offsets();
1440 supported_xcr0 &= ~(XFEATURE_MASK_BNDREGS | XFEATURE_MASK_BNDCSR);
1442 if (boot_cpu_has(X86_FEATURE_NX))
1443 kvm_enable_efer_bits(EFER_NX);
1445 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1446 kvm_enable_efer_bits(EFER_FFXSR);
1448 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1449 kvm_has_tsc_control = true;
1450 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1451 kvm_tsc_scaling_ratio_frac_bits = 32;
1454 /* Check for pause filtering support */
1455 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1456 pause_filter_count = 0;
1457 pause_filter_thresh = 0;
1458 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1459 pause_filter_thresh = 0;
1463 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1464 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1468 if (boot_cpu_has(X86_FEATURE_SEV) &&
1469 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1470 r = sev_hardware_setup();
1478 svm_adjust_mmio_mask();
1480 for_each_possible_cpu(cpu) {
1481 r = svm_cpu_init(cpu);
1486 if (!boot_cpu_has(X86_FEATURE_NPT))
1487 npt_enabled = false;
1489 if (npt_enabled && !npt)
1490 npt_enabled = false;
1492 kvm_configure_mmu(npt_enabled, PT_PDPE_LEVEL);
1493 pr_info("kvm: Nested Paging %sabled\n", npt_enabled ? "en" : "dis");
1496 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1502 !boot_cpu_has(X86_FEATURE_AVIC) ||
1503 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1506 pr_info("AVIC enabled\n");
1508 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1514 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1515 !IS_ENABLED(CONFIG_X86_64)) {
1518 pr_info("Virtual VMLOAD VMSAVE supported\n");
1523 if (!boot_cpu_has(X86_FEATURE_VGIF))
1526 pr_info("Virtual GIF supported\n");
1534 svm_hardware_teardown();
1538 static void init_seg(struct vmcb_seg *seg)
1541 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1542 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1543 seg->limit = 0xffff;
1547 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1550 seg->attrib = SVM_SELECTOR_P_MASK | type;
1551 seg->limit = 0xffff;
1555 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1557 struct vcpu_svm *svm = to_svm(vcpu);
1559 if (is_guest_mode(vcpu))
1560 return svm->nested.hsave->control.tsc_offset;
1562 return vcpu->arch.tsc_offset;
1565 static u64 svm_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1567 struct vcpu_svm *svm = to_svm(vcpu);
1568 u64 g_tsc_offset = 0;
1570 if (is_guest_mode(vcpu)) {
1571 /* Write L1's TSC offset. */
1572 g_tsc_offset = svm->vmcb->control.tsc_offset -
1573 svm->nested.hsave->control.tsc_offset;
1574 svm->nested.hsave->control.tsc_offset = offset;
1577 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1578 svm->vmcb->control.tsc_offset - g_tsc_offset,
1581 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1583 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1584 return svm->vmcb->control.tsc_offset;
1587 static void avic_init_vmcb(struct vcpu_svm *svm)
1589 struct vmcb *vmcb = svm->vmcb;
1590 struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1591 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1592 phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1593 phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1595 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1596 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1597 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1598 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1599 if (kvm_apicv_activated(svm->vcpu.kvm))
1600 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1602 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
1605 static void init_vmcb(struct vcpu_svm *svm)
1607 struct vmcb_control_area *control = &svm->vmcb->control;
1608 struct vmcb_save_area *save = &svm->vmcb->save;
1610 svm->vcpu.arch.hflags = 0;
1612 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1613 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1614 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1615 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1616 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1617 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1618 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1619 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1621 set_dr_intercepts(svm);
1623 set_exception_intercept(svm, PF_VECTOR);
1624 set_exception_intercept(svm, UD_VECTOR);
1625 set_exception_intercept(svm, MC_VECTOR);
1626 set_exception_intercept(svm, AC_VECTOR);
1627 set_exception_intercept(svm, DB_VECTOR);
1629 * Guest access to VMware backdoor ports could legitimately
1630 * trigger #GP because of TSS I/O permission bitmap.
1631 * We intercept those #GP and allow access to them anyway
1634 if (enable_vmware_backdoor)
1635 set_exception_intercept(svm, GP_VECTOR);
1637 set_intercept(svm, INTERCEPT_INTR);
1638 set_intercept(svm, INTERCEPT_NMI);
1639 set_intercept(svm, INTERCEPT_SMI);
1640 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1641 set_intercept(svm, INTERCEPT_RDPMC);
1642 set_intercept(svm, INTERCEPT_CPUID);
1643 set_intercept(svm, INTERCEPT_INVD);
1644 set_intercept(svm, INTERCEPT_INVLPG);
1645 set_intercept(svm, INTERCEPT_INVLPGA);
1646 set_intercept(svm, INTERCEPT_IOIO_PROT);
1647 set_intercept(svm, INTERCEPT_MSR_PROT);
1648 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1649 set_intercept(svm, INTERCEPT_SHUTDOWN);
1650 set_intercept(svm, INTERCEPT_VMRUN);
1651 set_intercept(svm, INTERCEPT_VMMCALL);
1652 set_intercept(svm, INTERCEPT_VMLOAD);
1653 set_intercept(svm, INTERCEPT_VMSAVE);
1654 set_intercept(svm, INTERCEPT_STGI);
1655 set_intercept(svm, INTERCEPT_CLGI);
1656 set_intercept(svm, INTERCEPT_SKINIT);
1657 set_intercept(svm, INTERCEPT_WBINVD);
1658 set_intercept(svm, INTERCEPT_XSETBV);
1659 set_intercept(svm, INTERCEPT_RDPRU);
1660 set_intercept(svm, INTERCEPT_RSM);
1662 if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1663 set_intercept(svm, INTERCEPT_MONITOR);
1664 set_intercept(svm, INTERCEPT_MWAIT);
1667 if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1668 set_intercept(svm, INTERCEPT_HLT);
1670 control->iopm_base_pa = __sme_set(iopm_base);
1671 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1672 control->int_ctl = V_INTR_MASKING_MASK;
1674 init_seg(&save->es);
1675 init_seg(&save->ss);
1676 init_seg(&save->ds);
1677 init_seg(&save->fs);
1678 init_seg(&save->gs);
1680 save->cs.selector = 0xf000;
1681 save->cs.base = 0xffff0000;
1682 /* Executable/Readable Code Segment */
1683 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1684 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1685 save->cs.limit = 0xffff;
1687 save->gdtr.limit = 0xffff;
1688 save->idtr.limit = 0xffff;
1690 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1691 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1693 svm_set_efer(&svm->vcpu, 0);
1694 save->dr6 = 0xffff0ff0;
1695 kvm_set_rflags(&svm->vcpu, 2);
1696 save->rip = 0x0000fff0;
1697 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1700 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1701 * It also updates the guest-visible cr0 value.
1703 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1704 kvm_mmu_reset_context(&svm->vcpu);
1706 save->cr4 = X86_CR4_PAE;
1710 /* Setup VMCB for Nested Paging */
1711 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1712 clr_intercept(svm, INTERCEPT_INVLPG);
1713 clr_exception_intercept(svm, PF_VECTOR);
1714 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1715 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1716 save->g_pat = svm->vcpu.arch.pat;
1720 svm->asid_generation = 0;
1722 svm->nested.vmcb = 0;
1723 svm->vcpu.arch.hflags = 0;
1725 if (pause_filter_count) {
1726 control->pause_filter_count = pause_filter_count;
1727 if (pause_filter_thresh)
1728 control->pause_filter_thresh = pause_filter_thresh;
1729 set_intercept(svm, INTERCEPT_PAUSE);
1731 clr_intercept(svm, INTERCEPT_PAUSE);
1734 if (kvm_vcpu_apicv_active(&svm->vcpu))
1735 avic_init_vmcb(svm);
1738 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1739 * in VMCB and clear intercepts to avoid #VMEXIT.
1742 clr_intercept(svm, INTERCEPT_VMLOAD);
1743 clr_intercept(svm, INTERCEPT_VMSAVE);
1744 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1748 clr_intercept(svm, INTERCEPT_STGI);
1749 clr_intercept(svm, INTERCEPT_CLGI);
1750 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1753 if (sev_guest(svm->vcpu.kvm)) {
1754 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1755 clr_exception_intercept(svm, UD_VECTOR);
1758 mark_all_dirty(svm->vmcb);
1764 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1767 u64 *avic_physical_id_table;
1768 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1770 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1773 avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1775 return &avic_physical_id_table[index];
1780 * AVIC hardware walks the nested page table to check permissions,
1781 * but does not use the SPA address specified in the leaf page
1782 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1783 * field of the VMCB. Therefore, we set up the
1784 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1786 static int avic_update_access_page(struct kvm *kvm, bool activate)
1790 mutex_lock(&kvm->slots_lock);
1792 * During kvm_destroy_vm(), kvm_pit_set_reinject() could trigger
1793 * APICv mode change, which update APIC_ACCESS_PAGE_PRIVATE_MEMSLOT
1794 * memory region. So, we need to ensure that kvm->mm == current->mm.
1796 if ((kvm->arch.apic_access_page_done == activate) ||
1797 (kvm->mm != current->mm))
1800 ret = __x86_set_memory_region(kvm,
1801 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1802 APIC_DEFAULT_PHYS_BASE,
1803 activate ? PAGE_SIZE : 0);
1807 kvm->arch.apic_access_page_done = activate;
1809 mutex_unlock(&kvm->slots_lock);
1813 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1815 u64 *entry, new_entry;
1816 int id = vcpu->vcpu_id;
1817 struct vcpu_svm *svm = to_svm(vcpu);
1819 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1822 if (!svm->vcpu.arch.apic->regs)
1825 if (kvm_apicv_activated(vcpu->kvm)) {
1828 ret = avic_update_access_page(vcpu->kvm, true);
1833 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1835 /* Setting AVIC backing page address in the phy APIC ID table */
1836 entry = avic_get_physical_id_entry(vcpu, id);
1840 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1841 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1842 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1843 WRITE_ONCE(*entry, new_entry);
1845 svm->avic_physical_id_cache = entry;
1850 static void sev_asid_free(int asid)
1852 struct svm_cpu_data *sd;
1855 mutex_lock(&sev_bitmap_lock);
1858 __set_bit(pos, sev_reclaim_asid_bitmap);
1860 for_each_possible_cpu(cpu) {
1861 sd = per_cpu(svm_data, cpu);
1862 sd->sev_vmcbs[pos] = NULL;
1865 mutex_unlock(&sev_bitmap_lock);
1868 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1870 struct sev_data_decommission *decommission;
1871 struct sev_data_deactivate *data;
1876 data = kzalloc(sizeof(*data), GFP_KERNEL);
1880 /* deactivate handle */
1881 data->handle = handle;
1883 /* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
1884 down_read(&sev_deactivate_lock);
1885 sev_guest_deactivate(data, NULL);
1886 up_read(&sev_deactivate_lock);
1890 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1894 /* decommission handle */
1895 decommission->handle = handle;
1896 sev_guest_decommission(decommission, NULL);
1898 kfree(decommission);
1901 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1902 unsigned long ulen, unsigned long *n,
1905 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1906 unsigned long npages, npinned, size;
1907 unsigned long locked, lock_limit;
1908 struct page **pages;
1909 unsigned long first, last;
1911 if (ulen == 0 || uaddr + ulen < uaddr)
1914 /* Calculate number of pages. */
1915 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1916 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1917 npages = (last - first + 1);
1919 locked = sev->pages_locked + npages;
1920 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1921 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1922 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1926 /* Avoid using vmalloc for smaller buffers. */
1927 size = npages * sizeof(struct page *);
1928 if (size > PAGE_SIZE)
1929 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1932 pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
1937 /* Pin the user virtual address. */
1938 npinned = get_user_pages_fast(uaddr, npages, FOLL_WRITE, pages);
1939 if (npinned != npages) {
1940 pr_err("SEV: Failure locking %lu pages.\n", npages);
1945 sev->pages_locked = locked;
1951 release_pages(pages, npinned);
1957 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1958 unsigned long npages)
1960 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1962 release_pages(pages, npages);
1964 sev->pages_locked -= npages;
1967 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1969 uint8_t *page_virtual;
1972 if (npages == 0 || pages == NULL)
1975 for (i = 0; i < npages; i++) {
1976 page_virtual = kmap_atomic(pages[i]);
1977 clflush_cache_range(page_virtual, PAGE_SIZE);
1978 kunmap_atomic(page_virtual);
1982 static void __unregister_enc_region_locked(struct kvm *kvm,
1983 struct enc_region *region)
1986 * The guest may change the memory encryption attribute from C=0 -> C=1
1987 * or vice versa for this memory range. Lets make sure caches are
1988 * flushed to ensure that guest data gets written into memory with
1991 sev_clflush_pages(region->pages, region->npages);
1993 sev_unpin_memory(kvm, region->pages, region->npages);
1994 list_del(®ion->list);
1998 static void sev_vm_destroy(struct kvm *kvm)
2000 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
2001 struct list_head *head = &sev->regions_list;
2002 struct list_head *pos, *q;
2004 if (!sev_guest(kvm))
2007 mutex_lock(&kvm->lock);
2010 * if userspace was terminated before unregistering the memory regions
2011 * then lets unpin all the registered memory.
2013 if (!list_empty(head)) {
2014 list_for_each_safe(pos, q, head) {
2015 __unregister_enc_region_locked(kvm,
2016 list_entry(pos, struct enc_region, list));
2020 mutex_unlock(&kvm->lock);
2022 sev_unbind_asid(kvm, sev->handle);
2023 sev_asid_free(sev->asid);
2026 static void avic_vm_destroy(struct kvm *kvm)
2028 unsigned long flags;
2029 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
2034 if (kvm_svm->avic_logical_id_table_page)
2035 __free_page(kvm_svm->avic_logical_id_table_page);
2036 if (kvm_svm->avic_physical_id_table_page)
2037 __free_page(kvm_svm->avic_physical_id_table_page);
2039 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2040 hash_del(&kvm_svm->hnode);
2041 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2044 static void svm_vm_destroy(struct kvm *kvm)
2046 avic_vm_destroy(kvm);
2047 sev_vm_destroy(kvm);
2050 static int avic_vm_init(struct kvm *kvm)
2052 unsigned long flags;
2054 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
2056 struct page *p_page;
2057 struct page *l_page;
2063 /* Allocating physical APIC ID table (4KB) */
2064 p_page = alloc_page(GFP_KERNEL_ACCOUNT);
2068 kvm_svm->avic_physical_id_table_page = p_page;
2069 clear_page(page_address(p_page));
2071 /* Allocating logical APIC ID table (4KB) */
2072 l_page = alloc_page(GFP_KERNEL_ACCOUNT);
2076 kvm_svm->avic_logical_id_table_page = l_page;
2077 clear_page(page_address(l_page));
2079 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
2081 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
2082 if (vm_id == 0) { /* id is 1-based, zero is not okay */
2083 next_vm_id_wrapped = 1;
2086 /* Is it still in use? Only possible if wrapped at least once */
2087 if (next_vm_id_wrapped) {
2088 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
2089 if (k2->avic_vm_id == vm_id)
2093 kvm_svm->avic_vm_id = vm_id;
2094 hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
2095 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
2100 avic_vm_destroy(kvm);
2104 static int svm_vm_init(struct kvm *kvm)
2107 int ret = avic_vm_init(kvm);
2112 kvm_apicv_init(kvm, avic);
2117 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
2120 unsigned long flags;
2121 struct amd_svm_iommu_ir *ir;
2122 struct vcpu_svm *svm = to_svm(vcpu);
2124 if (!kvm_arch_has_assigned_device(vcpu->kvm))
2128 * Here, we go through the per-vcpu ir_list to update all existing
2129 * interrupt remapping table entry targeting this vcpu.
2131 spin_lock_irqsave(&svm->ir_list_lock, flags);
2133 if (list_empty(&svm->ir_list))
2136 list_for_each_entry(ir, &svm->ir_list, node) {
2137 ret = amd_iommu_update_ga(cpu, r, ir->data);
2142 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2146 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2149 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2150 int h_physical_id = kvm_cpu_get_apicid(cpu);
2151 struct vcpu_svm *svm = to_svm(vcpu);
2153 if (!kvm_vcpu_apicv_active(vcpu))
2157 * Since the host physical APIC id is 8 bits,
2158 * we can support host APIC ID upto 255.
2160 if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
2163 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2164 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2166 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2167 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2169 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2170 if (svm->avic_is_running)
2171 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2173 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2174 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2175 svm->avic_is_running);
2178 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2181 struct vcpu_svm *svm = to_svm(vcpu);
2183 if (!kvm_vcpu_apicv_active(vcpu))
2186 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2187 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2188 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2190 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2191 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2195 * This function is called during VCPU halt/unhalt.
2197 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2199 struct vcpu_svm *svm = to_svm(vcpu);
2201 svm->avic_is_running = is_run;
2203 avic_vcpu_load(vcpu, vcpu->cpu);
2205 avic_vcpu_put(vcpu);
2208 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2210 struct vcpu_svm *svm = to_svm(vcpu);
2215 svm->virt_spec_ctrl = 0;
2218 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2219 MSR_IA32_APICBASE_ENABLE;
2220 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2221 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2225 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, false);
2226 kvm_rdx_write(vcpu, eax);
2228 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2229 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2232 static int avic_init_vcpu(struct vcpu_svm *svm)
2235 struct kvm_vcpu *vcpu = &svm->vcpu;
2237 if (!avic || !irqchip_in_kernel(vcpu->kvm))
2240 ret = avic_init_backing_page(&svm->vcpu);
2244 INIT_LIST_HEAD(&svm->ir_list);
2245 spin_lock_init(&svm->ir_list_lock);
2246 svm->dfr_reg = APIC_DFR_FLAT;
2251 static int svm_create_vcpu(struct kvm_vcpu *vcpu)
2253 struct vcpu_svm *svm;
2255 struct page *msrpm_pages;
2256 struct page *hsave_page;
2257 struct page *nested_msrpm_pages;
2260 BUILD_BUG_ON(offsetof(struct vcpu_svm, vcpu) != 0);
2264 page = alloc_page(GFP_KERNEL_ACCOUNT);
2268 msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2272 nested_msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2273 if (!nested_msrpm_pages)
2276 hsave_page = alloc_page(GFP_KERNEL_ACCOUNT);
2280 err = avic_init_vcpu(svm);
2284 /* We initialize this flag to true to make sure that the is_running
2285 * bit would be set the first time the vcpu is loaded.
2287 if (irqchip_in_kernel(vcpu->kvm) && kvm_apicv_activated(vcpu->kvm))
2288 svm->avic_is_running = true;
2290 svm->nested.hsave = page_address(hsave_page);
2292 svm->msrpm = page_address(msrpm_pages);
2293 svm_vcpu_init_msrpm(svm->msrpm);
2295 svm->nested.msrpm = page_address(nested_msrpm_pages);
2296 svm_vcpu_init_msrpm(svm->nested.msrpm);
2298 svm->vmcb = page_address(page);
2299 clear_page(svm->vmcb);
2300 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2301 svm->asid_generation = 0;
2304 svm_init_osvw(vcpu);
2305 vcpu->arch.microcode_version = 0x01000065;
2310 __free_page(hsave_page);
2312 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2314 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2321 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2325 for_each_online_cpu(i)
2326 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2329 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2331 struct vcpu_svm *svm = to_svm(vcpu);
2334 * The vmcb page can be recycled, causing a false negative in
2335 * svm_vcpu_load(). So, ensure that no logical CPU has this
2336 * vmcb page recorded as its current vmcb.
2338 svm_clear_current_vmcb(svm->vmcb);
2340 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2341 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2342 __free_page(virt_to_page(svm->nested.hsave));
2343 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2346 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2348 struct vcpu_svm *svm = to_svm(vcpu);
2349 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2352 if (unlikely(cpu != vcpu->cpu)) {
2353 svm->asid_generation = 0;
2354 mark_all_dirty(svm->vmcb);
2357 #ifdef CONFIG_X86_64
2358 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2360 savesegment(fs, svm->host.fs);
2361 savesegment(gs, svm->host.gs);
2362 svm->host.ldt = kvm_read_ldt();
2364 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2365 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2367 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2368 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2369 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2370 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2371 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2374 /* This assumes that the kernel never uses MSR_TSC_AUX */
2375 if (static_cpu_has(X86_FEATURE_RDTSCP))
2376 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2378 if (sd->current_vmcb != svm->vmcb) {
2379 sd->current_vmcb = svm->vmcb;
2380 indirect_branch_prediction_barrier();
2382 avic_vcpu_load(vcpu, cpu);
2385 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2387 struct vcpu_svm *svm = to_svm(vcpu);
2390 avic_vcpu_put(vcpu);
2392 ++vcpu->stat.host_state_reload;
2393 kvm_load_ldt(svm->host.ldt);
2394 #ifdef CONFIG_X86_64
2395 loadsegment(fs, svm->host.fs);
2396 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2397 load_gs_index(svm->host.gs);
2399 #ifdef CONFIG_X86_32_LAZY_GS
2400 loadsegment(gs, svm->host.gs);
2403 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2404 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2407 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2409 avic_set_running(vcpu, false);
2412 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2414 if (kvm_check_request(KVM_REQ_APICV_UPDATE, vcpu))
2415 kvm_vcpu_update_apicv(vcpu);
2416 avic_set_running(vcpu, true);
2419 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2421 struct vcpu_svm *svm = to_svm(vcpu);
2422 unsigned long rflags = svm->vmcb->save.rflags;
2424 if (svm->nmi_singlestep) {
2425 /* Hide our flags if they were not set by the guest */
2426 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2427 rflags &= ~X86_EFLAGS_TF;
2428 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2429 rflags &= ~X86_EFLAGS_RF;
2434 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2436 if (to_svm(vcpu)->nmi_singlestep)
2437 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2440 * Any change of EFLAGS.VM is accompanied by a reload of SS
2441 * (caused by either a task switch or an inter-privilege IRET),
2442 * so we do not need to update the CPL here.
2444 to_svm(vcpu)->vmcb->save.rflags = rflags;
2447 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2450 case VCPU_EXREG_PDPTR:
2451 BUG_ON(!npt_enabled);
2452 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2459 static inline void svm_enable_vintr(struct vcpu_svm *svm)
2461 struct vmcb_control_area *control;
2463 /* The following fields are ignored when AVIC is enabled */
2464 WARN_ON(kvm_vcpu_apicv_active(&svm->vcpu));
2467 * This is just a dummy VINTR to actually cause a vmexit to happen.
2468 * Actual injection of virtual interrupts happens through EVENTINJ.
2470 control = &svm->vmcb->control;
2471 control->int_vector = 0x0;
2472 control->int_ctl &= ~V_INTR_PRIO_MASK;
2473 control->int_ctl |= V_IRQ_MASK |
2474 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
2475 mark_dirty(svm->vmcb, VMCB_INTR);
2478 static void svm_set_vintr(struct vcpu_svm *svm)
2480 set_intercept(svm, INTERCEPT_VINTR);
2481 if (is_intercept(svm, INTERCEPT_VINTR))
2482 svm_enable_vintr(svm);
2485 static void svm_clear_vintr(struct vcpu_svm *svm)
2487 clr_intercept(svm, INTERCEPT_VINTR);
2489 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
2490 mark_dirty(svm->vmcb, VMCB_INTR);
2493 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2495 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2498 case VCPU_SREG_CS: return &save->cs;
2499 case VCPU_SREG_DS: return &save->ds;
2500 case VCPU_SREG_ES: return &save->es;
2501 case VCPU_SREG_FS: return &save->fs;
2502 case VCPU_SREG_GS: return &save->gs;
2503 case VCPU_SREG_SS: return &save->ss;
2504 case VCPU_SREG_TR: return &save->tr;
2505 case VCPU_SREG_LDTR: return &save->ldtr;
2511 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2513 struct vmcb_seg *s = svm_seg(vcpu, seg);
2518 static void svm_get_segment(struct kvm_vcpu *vcpu,
2519 struct kvm_segment *var, int seg)
2521 struct vmcb_seg *s = svm_seg(vcpu, seg);
2523 var->base = s->base;
2524 var->limit = s->limit;
2525 var->selector = s->selector;
2526 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2527 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2528 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2529 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2530 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2531 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2532 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2535 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2536 * However, the SVM spec states that the G bit is not observed by the
2537 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2538 * So let's synthesize a legal G bit for all segments, this helps
2539 * running KVM nested. It also helps cross-vendor migration, because
2540 * Intel's vmentry has a check on the 'G' bit.
2542 var->g = s->limit > 0xfffff;
2545 * AMD's VMCB does not have an explicit unusable field, so emulate it
2546 * for cross vendor migration purposes by "not present"
2548 var->unusable = !var->present;
2553 * Work around a bug where the busy flag in the tr selector
2563 * The accessed bit must always be set in the segment
2564 * descriptor cache, although it can be cleared in the
2565 * descriptor, the cached bit always remains at 1. Since
2566 * Intel has a check on this, set it here to support
2567 * cross-vendor migration.
2574 * On AMD CPUs sometimes the DB bit in the segment
2575 * descriptor is left as 1, although the whole segment has
2576 * been made unusable. Clear it here to pass an Intel VMX
2577 * entry check when cross vendor migrating.
2581 /* This is symmetric with svm_set_segment() */
2582 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2587 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2589 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2594 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2596 struct vcpu_svm *svm = to_svm(vcpu);
2598 dt->size = svm->vmcb->save.idtr.limit;
2599 dt->address = svm->vmcb->save.idtr.base;
2602 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2604 struct vcpu_svm *svm = to_svm(vcpu);
2606 svm->vmcb->save.idtr.limit = dt->size;
2607 svm->vmcb->save.idtr.base = dt->address ;
2608 mark_dirty(svm->vmcb, VMCB_DT);
2611 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2613 struct vcpu_svm *svm = to_svm(vcpu);
2615 dt->size = svm->vmcb->save.gdtr.limit;
2616 dt->address = svm->vmcb->save.gdtr.base;
2619 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2621 struct vcpu_svm *svm = to_svm(vcpu);
2623 svm->vmcb->save.gdtr.limit = dt->size;
2624 svm->vmcb->save.gdtr.base = dt->address ;
2625 mark_dirty(svm->vmcb, VMCB_DT);
2628 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2632 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2636 static void update_cr0_intercept(struct vcpu_svm *svm)
2638 ulong gcr0 = svm->vcpu.arch.cr0;
2639 u64 *hcr0 = &svm->vmcb->save.cr0;
2641 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2642 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2644 mark_dirty(svm->vmcb, VMCB_CR);
2646 if (gcr0 == *hcr0) {
2647 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2648 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2650 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2651 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2655 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2657 struct vcpu_svm *svm = to_svm(vcpu);
2659 #ifdef CONFIG_X86_64
2660 if (vcpu->arch.efer & EFER_LME) {
2661 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2662 vcpu->arch.efer |= EFER_LMA;
2663 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2666 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2667 vcpu->arch.efer &= ~EFER_LMA;
2668 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2672 vcpu->arch.cr0 = cr0;
2675 cr0 |= X86_CR0_PG | X86_CR0_WP;
2678 * re-enable caching here because the QEMU bios
2679 * does not do it - this results in some delay at
2682 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2683 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2684 svm->vmcb->save.cr0 = cr0;
2685 mark_dirty(svm->vmcb, VMCB_CR);
2686 update_cr0_intercept(svm);
2689 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2691 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2692 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2694 if (cr4 & X86_CR4_VMXE)
2697 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2698 svm_flush_tlb(vcpu, true);
2700 vcpu->arch.cr4 = cr4;
2703 cr4 |= host_cr4_mce;
2704 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2705 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2709 static void svm_set_segment(struct kvm_vcpu *vcpu,
2710 struct kvm_segment *var, int seg)
2712 struct vcpu_svm *svm = to_svm(vcpu);
2713 struct vmcb_seg *s = svm_seg(vcpu, seg);
2715 s->base = var->base;
2716 s->limit = var->limit;
2717 s->selector = var->selector;
2718 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2719 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2720 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2721 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2722 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2723 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2724 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2725 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2728 * This is always accurate, except if SYSRET returned to a segment
2729 * with SS.DPL != 3. Intel does not have this quirk, and always
2730 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2731 * would entail passing the CPL to userspace and back.
2733 if (seg == VCPU_SREG_SS)
2734 /* This is symmetric with svm_get_segment() */
2735 svm->vmcb->save.cpl = (var->dpl & 3);
2737 mark_dirty(svm->vmcb, VMCB_SEG);
2740 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2742 struct vcpu_svm *svm = to_svm(vcpu);
2744 clr_exception_intercept(svm, BP_VECTOR);
2746 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2747 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2748 set_exception_intercept(svm, BP_VECTOR);
2750 vcpu->guest_debug = 0;
2753 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2755 if (sd->next_asid > sd->max_asid) {
2756 ++sd->asid_generation;
2757 sd->next_asid = sd->min_asid;
2758 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2761 svm->asid_generation = sd->asid_generation;
2762 svm->vmcb->control.asid = sd->next_asid++;
2764 mark_dirty(svm->vmcb, VMCB_ASID);
2767 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2769 return to_svm(vcpu)->vmcb->save.dr6;
2772 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2774 struct vcpu_svm *svm = to_svm(vcpu);
2776 svm->vmcb->save.dr6 = value;
2777 mark_dirty(svm->vmcb, VMCB_DR);
2780 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2782 struct vcpu_svm *svm = to_svm(vcpu);
2784 get_debugreg(vcpu->arch.db[0], 0);
2785 get_debugreg(vcpu->arch.db[1], 1);
2786 get_debugreg(vcpu->arch.db[2], 2);
2787 get_debugreg(vcpu->arch.db[3], 3);
2788 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2789 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2791 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2792 set_dr_intercepts(svm);
2795 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2797 struct vcpu_svm *svm = to_svm(vcpu);
2799 svm->vmcb->save.dr7 = value;
2800 mark_dirty(svm->vmcb, VMCB_DR);
2803 static int pf_interception(struct vcpu_svm *svm)
2805 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2806 u64 error_code = svm->vmcb->control.exit_info_1;
2808 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2809 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2810 svm->vmcb->control.insn_bytes : NULL,
2811 svm->vmcb->control.insn_len);
2814 static int npf_interception(struct vcpu_svm *svm)
2816 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2817 u64 error_code = svm->vmcb->control.exit_info_1;
2819 trace_kvm_page_fault(fault_address, error_code);
2820 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2821 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2822 svm->vmcb->control.insn_bytes : NULL,
2823 svm->vmcb->control.insn_len);
2826 static int db_interception(struct vcpu_svm *svm)
2828 struct kvm_run *kvm_run = svm->vcpu.run;
2829 struct kvm_vcpu *vcpu = &svm->vcpu;
2831 if (!(svm->vcpu.guest_debug &
2832 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2833 !svm->nmi_singlestep) {
2834 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2838 if (svm->nmi_singlestep) {
2839 disable_nmi_singlestep(svm);
2840 /* Make sure we check for pending NMIs upon entry */
2841 kvm_make_request(KVM_REQ_EVENT, vcpu);
2844 if (svm->vcpu.guest_debug &
2845 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2846 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2847 kvm_run->debug.arch.pc =
2848 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2849 kvm_run->debug.arch.exception = DB_VECTOR;
2856 static int bp_interception(struct vcpu_svm *svm)
2858 struct kvm_run *kvm_run = svm->vcpu.run;
2860 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2861 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2862 kvm_run->debug.arch.exception = BP_VECTOR;
2866 static int ud_interception(struct vcpu_svm *svm)
2868 return handle_ud(&svm->vcpu);
2871 static int ac_interception(struct vcpu_svm *svm)
2873 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2877 static int gp_interception(struct vcpu_svm *svm)
2879 struct kvm_vcpu *vcpu = &svm->vcpu;
2880 u32 error_code = svm->vmcb->control.exit_info_1;
2882 WARN_ON_ONCE(!enable_vmware_backdoor);
2885 * VMware backdoor emulation on #GP interception only handles IN{S},
2886 * OUT{S}, and RDPMC, none of which generate a non-zero error code.
2889 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2892 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
2895 static bool is_erratum_383(void)
2900 if (!erratum_383_found)
2903 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2907 /* Bit 62 may or may not be set for this mce */
2908 value &= ~(1ULL << 62);
2910 if (value != 0xb600000000010015ULL)
2913 /* Clear MCi_STATUS registers */
2914 for (i = 0; i < 6; ++i)
2915 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2917 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2921 value &= ~(1ULL << 2);
2922 low = lower_32_bits(value);
2923 high = upper_32_bits(value);
2925 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2928 /* Flush tlb to evict multi-match entries */
2934 static void svm_handle_mce(struct vcpu_svm *svm)
2936 if (is_erratum_383()) {
2938 * Erratum 383 triggered. Guest state is corrupt so kill the
2941 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2943 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2949 * On an #MC intercept the MCE handler is not called automatically in
2950 * the host. So do it by hand here.
2954 /* not sure if we ever come back to this point */
2959 static int mc_interception(struct vcpu_svm *svm)
2964 static int shutdown_interception(struct vcpu_svm *svm)
2966 struct kvm_run *kvm_run = svm->vcpu.run;
2969 * VMCB is undefined after a SHUTDOWN intercept
2970 * so reinitialize it.
2972 clear_page(svm->vmcb);
2975 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2979 static int io_interception(struct vcpu_svm *svm)
2981 struct kvm_vcpu *vcpu = &svm->vcpu;
2982 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2983 int size, in, string;
2986 ++svm->vcpu.stat.io_exits;
2987 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2988 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2990 return kvm_emulate_instruction(vcpu, 0);
2992 port = io_info >> 16;
2993 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2994 svm->next_rip = svm->vmcb->control.exit_info_2;
2996 return kvm_fast_pio(&svm->vcpu, size, port, in);
2999 static int nmi_interception(struct vcpu_svm *svm)
3004 static int intr_interception(struct vcpu_svm *svm)
3006 ++svm->vcpu.stat.irq_exits;
3010 static int nop_on_interception(struct vcpu_svm *svm)
3015 static int halt_interception(struct vcpu_svm *svm)
3017 return kvm_emulate_halt(&svm->vcpu);
3020 static int vmmcall_interception(struct vcpu_svm *svm)
3022 return kvm_emulate_hypercall(&svm->vcpu);
3025 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
3027 struct vcpu_svm *svm = to_svm(vcpu);
3029 return svm->nested.nested_cr3;
3032 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
3034 struct vcpu_svm *svm = to_svm(vcpu);
3035 u64 cr3 = svm->nested.nested_cr3;
3039 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
3040 offset_in_page(cr3) + index * 8, 8);
3046 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
3047 struct x86_exception *fault)
3049 struct vcpu_svm *svm = to_svm(vcpu);
3051 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
3053 * TODO: track the cause of the nested page fault, and
3054 * correctly fill in the high bits of exit_info_1.
3056 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
3057 svm->vmcb->control.exit_code_hi = 0;
3058 svm->vmcb->control.exit_info_1 = (1ULL << 32);
3059 svm->vmcb->control.exit_info_2 = fault->address;
3062 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
3063 svm->vmcb->control.exit_info_1 |= fault->error_code;
3066 * The present bit is always zero for page structure faults on real
3069 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
3070 svm->vmcb->control.exit_info_1 &= ~1;
3072 nested_svm_vmexit(svm);
3075 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
3077 WARN_ON(mmu_is_nested(vcpu));
3079 vcpu->arch.mmu = &vcpu->arch.guest_mmu;
3080 kvm_init_shadow_mmu(vcpu);
3081 vcpu->arch.mmu->get_guest_pgd = nested_svm_get_tdp_cr3;
3082 vcpu->arch.mmu->get_pdptr = nested_svm_get_tdp_pdptr;
3083 vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
3084 vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
3085 reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
3086 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
3089 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
3091 vcpu->arch.mmu = &vcpu->arch.root_mmu;
3092 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
3095 static int nested_svm_check_permissions(struct vcpu_svm *svm)
3097 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
3098 !is_paging(&svm->vcpu)) {
3099 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3103 if (svm->vmcb->save.cpl) {
3104 kvm_inject_gp(&svm->vcpu, 0);
3111 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
3112 bool has_error_code, u32 error_code)
3116 if (!is_guest_mode(&svm->vcpu))
3119 vmexit = nested_svm_intercept(svm);
3120 if (vmexit != NESTED_EXIT_DONE)
3123 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
3124 svm->vmcb->control.exit_code_hi = 0;
3125 svm->vmcb->control.exit_info_1 = error_code;
3128 * EXITINFO2 is undefined for all exception intercepts other
3131 if (svm->vcpu.arch.exception.nested_apf)
3132 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3133 else if (svm->vcpu.arch.exception.has_payload)
3134 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
3136 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3138 svm->nested.exit_required = true;
3142 static void nested_svm_intr(struct vcpu_svm *svm)
3144 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
3145 svm->vmcb->control.exit_info_1 = 0;
3146 svm->vmcb->control.exit_info_2 = 0;
3148 /* nested_svm_vmexit this gets called afterwards from handle_exit */
3149 svm->nested.exit_required = true;
3150 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3153 static bool nested_exit_on_intr(struct vcpu_svm *svm)
3155 return (svm->nested.intercept & 1ULL);
3158 static int svm_check_nested_events(struct kvm_vcpu *vcpu)
3160 struct vcpu_svm *svm = to_svm(vcpu);
3161 bool block_nested_events =
3162 kvm_event_needs_reinjection(vcpu) || svm->nested.exit_required;
3164 if (kvm_cpu_has_interrupt(vcpu) && nested_exit_on_intr(svm)) {
3165 if (block_nested_events)
3167 nested_svm_intr(svm);
3174 /* This function returns true if it is save to enable the nmi window */
3175 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3177 if (!is_guest_mode(&svm->vcpu))
3180 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3183 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3184 svm->nested.exit_required = true;
3189 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3191 unsigned port, size, iopm_len;
3196 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3197 return NESTED_EXIT_HOST;
3199 port = svm->vmcb->control.exit_info_1 >> 16;
3200 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3201 SVM_IOIO_SIZE_SHIFT;
3202 gpa = svm->nested.vmcb_iopm + (port / 8);
3203 start_bit = port % 8;
3204 iopm_len = (start_bit + size > 8) ? 2 : 1;
3205 mask = (0xf >> (4 - size)) << start_bit;
3208 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3209 return NESTED_EXIT_DONE;
3211 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3214 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3216 u32 offset, msr, value;
3219 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3220 return NESTED_EXIT_HOST;
3222 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3223 offset = svm_msrpm_offset(msr);
3224 write = svm->vmcb->control.exit_info_1 & 1;
3225 mask = 1 << ((2 * (msr & 0xf)) + write);
3227 if (offset == MSR_INVALID)
3228 return NESTED_EXIT_DONE;
3230 /* Offset is in 32 bit units but need in 8 bit units */
3233 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3234 return NESTED_EXIT_DONE;
3236 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3239 /* DB exceptions for our internal use must not cause vmexit */
3240 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3244 /* if we're not singlestepping, it's not ours */
3245 if (!svm->nmi_singlestep)
3246 return NESTED_EXIT_DONE;
3248 /* if it's not a singlestep exception, it's not ours */
3249 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3250 return NESTED_EXIT_DONE;
3251 if (!(dr6 & DR6_BS))
3252 return NESTED_EXIT_DONE;
3254 /* if the guest is singlestepping, it should get the vmexit */
3255 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3256 disable_nmi_singlestep(svm);
3257 return NESTED_EXIT_DONE;
3260 /* it's ours, the nested hypervisor must not see this one */
3261 return NESTED_EXIT_HOST;
3264 static int nested_svm_exit_special(struct vcpu_svm *svm)
3266 u32 exit_code = svm->vmcb->control.exit_code;
3268 switch (exit_code) {
3271 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3272 return NESTED_EXIT_HOST;
3274 /* For now we are always handling NPFs when using them */
3276 return NESTED_EXIT_HOST;
3278 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3279 /* When we're shadowing, trap PFs, but not async PF */
3280 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3281 return NESTED_EXIT_HOST;
3287 return NESTED_EXIT_CONTINUE;
3290 static int nested_svm_intercept(struct vcpu_svm *svm)
3292 u32 exit_code = svm->vmcb->control.exit_code;
3293 int vmexit = NESTED_EXIT_HOST;
3295 switch (exit_code) {
3297 vmexit = nested_svm_exit_handled_msr(svm);
3300 vmexit = nested_svm_intercept_ioio(svm);
3302 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3303 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3304 if (svm->nested.intercept_cr & bit)
3305 vmexit = NESTED_EXIT_DONE;
3308 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3309 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3310 if (svm->nested.intercept_dr & bit)
3311 vmexit = NESTED_EXIT_DONE;
3314 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3315 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3316 if (svm->nested.intercept_exceptions & excp_bits) {
3317 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3318 vmexit = nested_svm_intercept_db(svm);
3320 vmexit = NESTED_EXIT_DONE;
3322 /* async page fault always cause vmexit */
3323 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3324 svm->vcpu.arch.exception.nested_apf != 0)
3325 vmexit = NESTED_EXIT_DONE;
3328 case SVM_EXIT_ERR: {
3329 vmexit = NESTED_EXIT_DONE;
3333 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3334 if (svm->nested.intercept & exit_bits)
3335 vmexit = NESTED_EXIT_DONE;
3342 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3346 vmexit = nested_svm_intercept(svm);
3348 if (vmexit == NESTED_EXIT_DONE)
3349 nested_svm_vmexit(svm);
3354 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3356 struct vmcb_control_area *dst = &dst_vmcb->control;
3357 struct vmcb_control_area *from = &from_vmcb->control;
3359 dst->intercept_cr = from->intercept_cr;
3360 dst->intercept_dr = from->intercept_dr;
3361 dst->intercept_exceptions = from->intercept_exceptions;
3362 dst->intercept = from->intercept;
3363 dst->iopm_base_pa = from->iopm_base_pa;
3364 dst->msrpm_base_pa = from->msrpm_base_pa;
3365 dst->tsc_offset = from->tsc_offset;
3366 dst->asid = from->asid;
3367 dst->tlb_ctl = from->tlb_ctl;
3368 dst->int_ctl = from->int_ctl;
3369 dst->int_vector = from->int_vector;
3370 dst->int_state = from->int_state;
3371 dst->exit_code = from->exit_code;
3372 dst->exit_code_hi = from->exit_code_hi;
3373 dst->exit_info_1 = from->exit_info_1;
3374 dst->exit_info_2 = from->exit_info_2;
3375 dst->exit_int_info = from->exit_int_info;
3376 dst->exit_int_info_err = from->exit_int_info_err;
3377 dst->nested_ctl = from->nested_ctl;
3378 dst->event_inj = from->event_inj;
3379 dst->event_inj_err = from->event_inj_err;
3380 dst->nested_cr3 = from->nested_cr3;
3381 dst->virt_ext = from->virt_ext;
3382 dst->pause_filter_count = from->pause_filter_count;
3383 dst->pause_filter_thresh = from->pause_filter_thresh;
3386 static int nested_svm_vmexit(struct vcpu_svm *svm)
3389 struct vmcb *nested_vmcb;
3390 struct vmcb *hsave = svm->nested.hsave;
3391 struct vmcb *vmcb = svm->vmcb;
3392 struct kvm_host_map map;
3394 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3395 vmcb->control.exit_info_1,
3396 vmcb->control.exit_info_2,
3397 vmcb->control.exit_int_info,
3398 vmcb->control.exit_int_info_err,
3401 rc = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->nested.vmcb), &map);
3404 kvm_inject_gp(&svm->vcpu, 0);
3408 nested_vmcb = map.hva;
3410 /* Exit Guest-Mode */
3411 leave_guest_mode(&svm->vcpu);
3412 svm->nested.vmcb = 0;
3414 /* Give the current vmcb to the guest */
3417 nested_vmcb->save.es = vmcb->save.es;
3418 nested_vmcb->save.cs = vmcb->save.cs;
3419 nested_vmcb->save.ss = vmcb->save.ss;
3420 nested_vmcb->save.ds = vmcb->save.ds;
3421 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3422 nested_vmcb->save.idtr = vmcb->save.idtr;
3423 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3424 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3425 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3426 nested_vmcb->save.cr2 = vmcb->save.cr2;
3427 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3428 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3429 nested_vmcb->save.rip = vmcb->save.rip;
3430 nested_vmcb->save.rsp = vmcb->save.rsp;
3431 nested_vmcb->save.rax = vmcb->save.rax;
3432 nested_vmcb->save.dr7 = vmcb->save.dr7;
3433 nested_vmcb->save.dr6 = vmcb->save.dr6;
3434 nested_vmcb->save.cpl = vmcb->save.cpl;
3436 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3437 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3438 nested_vmcb->control.int_state = vmcb->control.int_state;
3439 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3440 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3441 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3442 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3443 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3444 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3446 if (svm->nrips_enabled)
3447 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3450 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3451 * to make sure that we do not lose injected events. So check event_inj
3452 * here and copy it to exit_int_info if it is valid.
3453 * Exit_int_info and event_inj can't be both valid because the case
3454 * below only happens on a VMRUN instruction intercept which has
3455 * no valid exit_int_info set.
3457 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3458 struct vmcb_control_area *nc = &nested_vmcb->control;
3460 nc->exit_int_info = vmcb->control.event_inj;
3461 nc->exit_int_info_err = vmcb->control.event_inj_err;
3464 nested_vmcb->control.tlb_ctl = 0;
3465 nested_vmcb->control.event_inj = 0;
3466 nested_vmcb->control.event_inj_err = 0;
3468 nested_vmcb->control.pause_filter_count =
3469 svm->vmcb->control.pause_filter_count;
3470 nested_vmcb->control.pause_filter_thresh =
3471 svm->vmcb->control.pause_filter_thresh;
3473 /* We always set V_INTR_MASKING and remember the old value in hflags */
3474 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3475 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3477 /* Restore the original control entries */
3478 copy_vmcb_control_area(vmcb, hsave);
3480 svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3481 kvm_clear_exception_queue(&svm->vcpu);
3482 kvm_clear_interrupt_queue(&svm->vcpu);
3484 svm->nested.nested_cr3 = 0;
3486 /* Restore selected save entries */
3487 svm->vmcb->save.es = hsave->save.es;
3488 svm->vmcb->save.cs = hsave->save.cs;
3489 svm->vmcb->save.ss = hsave->save.ss;
3490 svm->vmcb->save.ds = hsave->save.ds;
3491 svm->vmcb->save.gdtr = hsave->save.gdtr;
3492 svm->vmcb->save.idtr = hsave->save.idtr;
3493 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3494 svm_set_efer(&svm->vcpu, hsave->save.efer);
3495 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3496 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3498 svm->vmcb->save.cr3 = hsave->save.cr3;
3499 svm->vcpu.arch.cr3 = hsave->save.cr3;
3501 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3503 kvm_rax_write(&svm->vcpu, hsave->save.rax);
3504 kvm_rsp_write(&svm->vcpu, hsave->save.rsp);
3505 kvm_rip_write(&svm->vcpu, hsave->save.rip);
3506 svm->vmcb->save.dr7 = 0;
3507 svm->vmcb->save.cpl = 0;
3508 svm->vmcb->control.exit_int_info = 0;
3510 mark_all_dirty(svm->vmcb);
3512 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3514 nested_svm_uninit_mmu_context(&svm->vcpu);
3515 kvm_mmu_reset_context(&svm->vcpu);
3516 kvm_mmu_load(&svm->vcpu);
3519 * Drop what we picked up for L2 via svm_complete_interrupts() so it
3520 * doesn't end up in L1.
3522 svm->vcpu.arch.nmi_injected = false;
3523 kvm_clear_exception_queue(&svm->vcpu);
3524 kvm_clear_interrupt_queue(&svm->vcpu);
3529 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3532 * This function merges the msr permission bitmaps of kvm and the
3533 * nested vmcb. It is optimized in that it only merges the parts where
3534 * the kvm msr permission bitmap may contain zero bits
3538 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3541 for (i = 0; i < MSRPM_OFFSETS; i++) {
3545 if (msrpm_offsets[i] == 0xffffffff)
3548 p = msrpm_offsets[i];
3549 offset = svm->nested.vmcb_msrpm + (p * 4);
3551 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3554 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3557 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3562 static bool nested_vmcb_checks(struct vmcb *vmcb)
3564 if ((vmcb->save.efer & EFER_SVME) == 0)
3567 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3570 if (vmcb->control.asid == 0)
3573 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3580 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3581 struct vmcb *nested_vmcb, struct kvm_host_map *map)
3583 bool evaluate_pending_interrupts =
3584 is_intercept(svm, INTERCEPT_VINTR) ||
3585 is_intercept(svm, INTERCEPT_IRET);
3587 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3588 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3590 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3592 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3593 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3594 nested_svm_init_mmu_context(&svm->vcpu);
3597 /* Load the nested guest state */
3598 svm->vmcb->save.es = nested_vmcb->save.es;
3599 svm->vmcb->save.cs = nested_vmcb->save.cs;
3600 svm->vmcb->save.ss = nested_vmcb->save.ss;
3601 svm->vmcb->save.ds = nested_vmcb->save.ds;
3602 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3603 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3604 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3605 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3606 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3607 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3609 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3610 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3612 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3614 /* Guest paging mode is active - reset mmu */
3615 kvm_mmu_reset_context(&svm->vcpu);
3617 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3618 kvm_rax_write(&svm->vcpu, nested_vmcb->save.rax);
3619 kvm_rsp_write(&svm->vcpu, nested_vmcb->save.rsp);
3620 kvm_rip_write(&svm->vcpu, nested_vmcb->save.rip);
3622 /* In case we don't even reach vcpu_run, the fields are not updated */
3623 svm->vmcb->save.rax = nested_vmcb->save.rax;
3624 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3625 svm->vmcb->save.rip = nested_vmcb->save.rip;
3626 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3627 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3628 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3630 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3631 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3633 /* cache intercepts */
3634 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3635 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3636 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3637 svm->nested.intercept = nested_vmcb->control.intercept;
3639 svm_flush_tlb(&svm->vcpu, true);
3640 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3641 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3642 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3644 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3646 svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3647 svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3649 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3650 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3651 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3652 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3653 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3655 svm->vmcb->control.pause_filter_count =
3656 nested_vmcb->control.pause_filter_count;
3657 svm->vmcb->control.pause_filter_thresh =
3658 nested_vmcb->control.pause_filter_thresh;
3660 kvm_vcpu_unmap(&svm->vcpu, map, true);
3662 /* Enter Guest-Mode */
3663 enter_guest_mode(&svm->vcpu);
3666 * Merge guest and host intercepts - must be called with vcpu in
3667 * guest-mode to take affect here
3669 recalc_intercepts(svm);
3671 svm->nested.vmcb = vmcb_gpa;
3674 * If L1 had a pending IRQ/NMI before executing VMRUN,
3675 * which wasn't delivered because it was disallowed (e.g.
3676 * interrupts disabled), L0 needs to evaluate if this pending
3677 * event should cause an exit from L2 to L1 or be delivered
3680 * Usually this would be handled by the processor noticing an
3681 * IRQ/NMI window request. However, VMRUN can unblock interrupts
3682 * by implicitly setting GIF, so force L0 to perform pending event
3683 * evaluation by requesting a KVM_REQ_EVENT.
3686 if (unlikely(evaluate_pending_interrupts))
3687 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3689 mark_all_dirty(svm->vmcb);
3692 static int nested_svm_vmrun(struct vcpu_svm *svm)
3695 struct vmcb *nested_vmcb;
3696 struct vmcb *hsave = svm->nested.hsave;
3697 struct vmcb *vmcb = svm->vmcb;
3698 struct kvm_host_map map;
3701 vmcb_gpa = svm->vmcb->save.rax;
3703 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb_gpa), &map);
3704 if (ret == -EINVAL) {
3705 kvm_inject_gp(&svm->vcpu, 0);
3708 return kvm_skip_emulated_instruction(&svm->vcpu);
3711 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3713 nested_vmcb = map.hva;
3715 if (!nested_vmcb_checks(nested_vmcb)) {
3716 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3717 nested_vmcb->control.exit_code_hi = 0;
3718 nested_vmcb->control.exit_info_1 = 0;
3719 nested_vmcb->control.exit_info_2 = 0;
3721 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3726 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3727 nested_vmcb->save.rip,
3728 nested_vmcb->control.int_ctl,
3729 nested_vmcb->control.event_inj,
3730 nested_vmcb->control.nested_ctl);
3732 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3733 nested_vmcb->control.intercept_cr >> 16,
3734 nested_vmcb->control.intercept_exceptions,
3735 nested_vmcb->control.intercept);
3737 /* Clear internal status */
3738 kvm_clear_exception_queue(&svm->vcpu);
3739 kvm_clear_interrupt_queue(&svm->vcpu);
3742 * Save the old vmcb, so we don't need to pick what we save, but can
3743 * restore everything when a VMEXIT occurs
3745 hsave->save.es = vmcb->save.es;
3746 hsave->save.cs = vmcb->save.cs;
3747 hsave->save.ss = vmcb->save.ss;
3748 hsave->save.ds = vmcb->save.ds;
3749 hsave->save.gdtr = vmcb->save.gdtr;
3750 hsave->save.idtr = vmcb->save.idtr;
3751 hsave->save.efer = svm->vcpu.arch.efer;
3752 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3753 hsave->save.cr4 = svm->vcpu.arch.cr4;
3754 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3755 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3756 hsave->save.rsp = vmcb->save.rsp;
3757 hsave->save.rax = vmcb->save.rax;
3759 hsave->save.cr3 = vmcb->save.cr3;
3761 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3763 copy_vmcb_control_area(hsave, vmcb);
3765 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, &map);
3767 if (!nested_svm_vmrun_msrpm(svm)) {
3768 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3769 svm->vmcb->control.exit_code_hi = 0;
3770 svm->vmcb->control.exit_info_1 = 0;
3771 svm->vmcb->control.exit_info_2 = 0;
3773 nested_svm_vmexit(svm);
3779 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3781 to_vmcb->save.fs = from_vmcb->save.fs;
3782 to_vmcb->save.gs = from_vmcb->save.gs;
3783 to_vmcb->save.tr = from_vmcb->save.tr;
3784 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3785 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3786 to_vmcb->save.star = from_vmcb->save.star;
3787 to_vmcb->save.lstar = from_vmcb->save.lstar;
3788 to_vmcb->save.cstar = from_vmcb->save.cstar;
3789 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3790 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3791 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3792 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3795 static int vmload_interception(struct vcpu_svm *svm)
3797 struct vmcb *nested_vmcb;
3798 struct kvm_host_map map;
3801 if (nested_svm_check_permissions(svm))
3804 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3807 kvm_inject_gp(&svm->vcpu, 0);
3811 nested_vmcb = map.hva;
3813 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3815 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3816 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3821 static int vmsave_interception(struct vcpu_svm *svm)
3823 struct vmcb *nested_vmcb;
3824 struct kvm_host_map map;
3827 if (nested_svm_check_permissions(svm))
3830 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3833 kvm_inject_gp(&svm->vcpu, 0);
3837 nested_vmcb = map.hva;
3839 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3841 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3842 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3847 static int vmrun_interception(struct vcpu_svm *svm)
3849 if (nested_svm_check_permissions(svm))
3852 return nested_svm_vmrun(svm);
3855 static int stgi_interception(struct vcpu_svm *svm)
3859 if (nested_svm_check_permissions(svm))
3863 * If VGIF is enabled, the STGI intercept is only added to
3864 * detect the opening of the SMI/NMI window; remove it now.
3866 if (vgif_enabled(svm))
3867 clr_intercept(svm, INTERCEPT_STGI);
3869 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3870 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3877 static int clgi_interception(struct vcpu_svm *svm)
3881 if (nested_svm_check_permissions(svm))
3884 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3888 /* After a CLGI no interrupts should come */
3889 if (!kvm_vcpu_apicv_active(&svm->vcpu))
3890 svm_clear_vintr(svm);
3895 static int invlpga_interception(struct vcpu_svm *svm)
3897 struct kvm_vcpu *vcpu = &svm->vcpu;
3899 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_rcx_read(&svm->vcpu),
3900 kvm_rax_read(&svm->vcpu));
3902 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3903 kvm_mmu_invlpg(vcpu, kvm_rax_read(&svm->vcpu));
3905 return kvm_skip_emulated_instruction(&svm->vcpu);
3908 static int skinit_interception(struct vcpu_svm *svm)
3910 trace_kvm_skinit(svm->vmcb->save.rip, kvm_rax_read(&svm->vcpu));
3912 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3916 static int wbinvd_interception(struct vcpu_svm *svm)
3918 return kvm_emulate_wbinvd(&svm->vcpu);
3921 static int xsetbv_interception(struct vcpu_svm *svm)
3923 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3924 u32 index = kvm_rcx_read(&svm->vcpu);
3926 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3927 return kvm_skip_emulated_instruction(&svm->vcpu);
3933 static int rdpru_interception(struct vcpu_svm *svm)
3935 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3939 static int task_switch_interception(struct vcpu_svm *svm)
3943 int int_type = svm->vmcb->control.exit_int_info &
3944 SVM_EXITINTINFO_TYPE_MASK;
3945 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3947 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3949 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3950 bool has_error_code = false;
3953 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3955 if (svm->vmcb->control.exit_info_2 &
3956 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3957 reason = TASK_SWITCH_IRET;
3958 else if (svm->vmcb->control.exit_info_2 &
3959 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3960 reason = TASK_SWITCH_JMP;
3962 reason = TASK_SWITCH_GATE;
3964 reason = TASK_SWITCH_CALL;
3966 if (reason == TASK_SWITCH_GATE) {
3968 case SVM_EXITINTINFO_TYPE_NMI:
3969 svm->vcpu.arch.nmi_injected = false;
3971 case SVM_EXITINTINFO_TYPE_EXEPT:
3972 if (svm->vmcb->control.exit_info_2 &
3973 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3974 has_error_code = true;
3976 (u32)svm->vmcb->control.exit_info_2;
3978 kvm_clear_exception_queue(&svm->vcpu);
3980 case SVM_EXITINTINFO_TYPE_INTR:
3981 kvm_clear_interrupt_queue(&svm->vcpu);
3988 if (reason != TASK_SWITCH_GATE ||
3989 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3990 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3991 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
3992 if (!skip_emulated_instruction(&svm->vcpu))
3996 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3999 return kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
4000 has_error_code, error_code);
4003 static int cpuid_interception(struct vcpu_svm *svm)
4005 return kvm_emulate_cpuid(&svm->vcpu);
4008 static int iret_interception(struct vcpu_svm *svm)
4010 ++svm->vcpu.stat.nmi_window_exits;
4011 clr_intercept(svm, INTERCEPT_IRET);
4012 svm->vcpu.arch.hflags |= HF_IRET_MASK;
4013 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
4014 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4018 static int invlpg_interception(struct vcpu_svm *svm)
4020 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
4021 return kvm_emulate_instruction(&svm->vcpu, 0);
4023 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
4024 return kvm_skip_emulated_instruction(&svm->vcpu);
4027 static int emulate_on_interception(struct vcpu_svm *svm)
4029 return kvm_emulate_instruction(&svm->vcpu, 0);
4032 static int rsm_interception(struct vcpu_svm *svm)
4034 return kvm_emulate_instruction_from_buffer(&svm->vcpu, rsm_ins_bytes, 2);
4037 static int rdpmc_interception(struct vcpu_svm *svm)
4042 return emulate_on_interception(svm);
4044 err = kvm_rdpmc(&svm->vcpu);
4045 return kvm_complete_insn_gp(&svm->vcpu, err);
4048 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
4051 unsigned long cr0 = svm->vcpu.arch.cr0;
4055 intercept = svm->nested.intercept;
4057 if (!is_guest_mode(&svm->vcpu) ||
4058 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
4061 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
4062 val &= ~SVM_CR0_SELECTIVE_MASK;
4065 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4066 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
4072 #define CR_VALID (1ULL << 63)
4074 static int cr_interception(struct vcpu_svm *svm)
4080 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
4081 return emulate_on_interception(svm);
4083 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
4084 return emulate_on_interception(svm);
4086 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4087 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
4088 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
4090 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
4093 if (cr >= 16) { /* mov to cr */
4095 val = kvm_register_read(&svm->vcpu, reg);
4098 if (!check_selective_cr0_intercepted(svm, val))
4099 err = kvm_set_cr0(&svm->vcpu, val);
4105 err = kvm_set_cr3(&svm->vcpu, val);
4108 err = kvm_set_cr4(&svm->vcpu, val);
4111 err = kvm_set_cr8(&svm->vcpu, val);
4114 WARN(1, "unhandled write to CR%d", cr);
4115 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4118 } else { /* mov from cr */
4121 val = kvm_read_cr0(&svm->vcpu);
4124 val = svm->vcpu.arch.cr2;
4127 val = kvm_read_cr3(&svm->vcpu);
4130 val = kvm_read_cr4(&svm->vcpu);
4133 val = kvm_get_cr8(&svm->vcpu);
4136 WARN(1, "unhandled read from CR%d", cr);
4137 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4140 kvm_register_write(&svm->vcpu, reg, val);
4142 return kvm_complete_insn_gp(&svm->vcpu, err);
4145 static int dr_interception(struct vcpu_svm *svm)
4150 if (svm->vcpu.guest_debug == 0) {
4152 * No more DR vmexits; force a reload of the debug registers
4153 * and reenter on this instruction. The next vmexit will
4154 * retrieve the full state of the debug registers.
4156 clr_dr_intercepts(svm);
4157 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4161 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4162 return emulate_on_interception(svm);
4164 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4165 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4167 if (dr >= 16) { /* mov to DRn */
4168 if (!kvm_require_dr(&svm->vcpu, dr - 16))
4170 val = kvm_register_read(&svm->vcpu, reg);
4171 kvm_set_dr(&svm->vcpu, dr - 16, val);
4173 if (!kvm_require_dr(&svm->vcpu, dr))
4175 kvm_get_dr(&svm->vcpu, dr, &val);
4176 kvm_register_write(&svm->vcpu, reg, val);
4179 return kvm_skip_emulated_instruction(&svm->vcpu);
4182 static int cr8_write_interception(struct vcpu_svm *svm)
4184 struct kvm_run *kvm_run = svm->vcpu.run;
4187 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4188 /* instruction emulation calls kvm_set_cr8() */
4189 r = cr_interception(svm);
4190 if (lapic_in_kernel(&svm->vcpu))
4192 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4194 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4198 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4202 switch (msr->index) {
4203 case MSR_F10H_DECFG:
4204 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4205 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4214 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4216 struct vcpu_svm *svm = to_svm(vcpu);
4218 switch (msr_info->index) {
4220 msr_info->data = svm->vmcb->save.star;
4222 #ifdef CONFIG_X86_64
4224 msr_info->data = svm->vmcb->save.lstar;
4227 msr_info->data = svm->vmcb->save.cstar;
4229 case MSR_KERNEL_GS_BASE:
4230 msr_info->data = svm->vmcb->save.kernel_gs_base;
4232 case MSR_SYSCALL_MASK:
4233 msr_info->data = svm->vmcb->save.sfmask;
4236 case MSR_IA32_SYSENTER_CS:
4237 msr_info->data = svm->vmcb->save.sysenter_cs;
4239 case MSR_IA32_SYSENTER_EIP:
4240 msr_info->data = svm->sysenter_eip;
4242 case MSR_IA32_SYSENTER_ESP:
4243 msr_info->data = svm->sysenter_esp;
4246 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4248 msr_info->data = svm->tsc_aux;
4251 * Nobody will change the following 5 values in the VMCB so we can
4252 * safely return them on rdmsr. They will always be 0 until LBRV is
4255 case MSR_IA32_DEBUGCTLMSR:
4256 msr_info->data = svm->vmcb->save.dbgctl;
4258 case MSR_IA32_LASTBRANCHFROMIP:
4259 msr_info->data = svm->vmcb->save.br_from;
4261 case MSR_IA32_LASTBRANCHTOIP:
4262 msr_info->data = svm->vmcb->save.br_to;
4264 case MSR_IA32_LASTINTFROMIP:
4265 msr_info->data = svm->vmcb->save.last_excp_from;
4267 case MSR_IA32_LASTINTTOIP:
4268 msr_info->data = svm->vmcb->save.last_excp_to;
4270 case MSR_VM_HSAVE_PA:
4271 msr_info->data = svm->nested.hsave_msr;
4274 msr_info->data = svm->nested.vm_cr_msr;
4276 case MSR_IA32_SPEC_CTRL:
4277 if (!msr_info->host_initiated &&
4278 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
4279 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_STIBP) &&
4280 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4281 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4284 msr_info->data = svm->spec_ctrl;
4286 case MSR_AMD64_VIRT_SPEC_CTRL:
4287 if (!msr_info->host_initiated &&
4288 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4291 msr_info->data = svm->virt_spec_ctrl;
4293 case MSR_F15H_IC_CFG: {
4297 family = guest_cpuid_family(vcpu);
4298 model = guest_cpuid_model(vcpu);
4300 if (family < 0 || model < 0)
4301 return kvm_get_msr_common(vcpu, msr_info);
4305 if (family == 0x15 &&
4306 (model >= 0x2 && model < 0x20))
4307 msr_info->data = 0x1E;
4310 case MSR_F10H_DECFG:
4311 msr_info->data = svm->msr_decfg;
4314 return kvm_get_msr_common(vcpu, msr_info);
4319 static int rdmsr_interception(struct vcpu_svm *svm)
4321 return kvm_emulate_rdmsr(&svm->vcpu);
4324 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4326 struct vcpu_svm *svm = to_svm(vcpu);
4327 int svm_dis, chg_mask;
4329 if (data & ~SVM_VM_CR_VALID_MASK)
4332 chg_mask = SVM_VM_CR_VALID_MASK;
4334 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4335 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4337 svm->nested.vm_cr_msr &= ~chg_mask;
4338 svm->nested.vm_cr_msr |= (data & chg_mask);
4340 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4342 /* check for svm_disable while efer.svme is set */
4343 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4349 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4351 struct vcpu_svm *svm = to_svm(vcpu);
4353 u32 ecx = msr->index;
4354 u64 data = msr->data;
4356 case MSR_IA32_CR_PAT:
4357 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4359 vcpu->arch.pat = data;
4360 svm->vmcb->save.g_pat = data;
4361 mark_dirty(svm->vmcb, VMCB_NPT);
4363 case MSR_IA32_SPEC_CTRL:
4364 if (!msr->host_initiated &&
4365 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL) &&
4366 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_STIBP) &&
4367 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4368 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4371 if (data & ~kvm_spec_ctrl_valid_bits(vcpu))
4374 svm->spec_ctrl = data;
4380 * When it's written (to non-zero) for the first time, pass
4384 * The handling of the MSR bitmap for L2 guests is done in
4385 * nested_svm_vmrun_msrpm.
4386 * We update the L1 MSR bit as well since it will end up
4387 * touching the MSR anyway now.
4389 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4391 case MSR_IA32_PRED_CMD:
4392 if (!msr->host_initiated &&
4393 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4396 if (data & ~PRED_CMD_IBPB)
4398 if (!boot_cpu_has(X86_FEATURE_AMD_IBPB))
4403 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4404 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4406 case MSR_AMD64_VIRT_SPEC_CTRL:
4407 if (!msr->host_initiated &&
4408 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4411 if (data & ~SPEC_CTRL_SSBD)
4414 svm->virt_spec_ctrl = data;
4417 svm->vmcb->save.star = data;
4419 #ifdef CONFIG_X86_64
4421 svm->vmcb->save.lstar = data;
4424 svm->vmcb->save.cstar = data;
4426 case MSR_KERNEL_GS_BASE:
4427 svm->vmcb->save.kernel_gs_base = data;
4429 case MSR_SYSCALL_MASK:
4430 svm->vmcb->save.sfmask = data;
4433 case MSR_IA32_SYSENTER_CS:
4434 svm->vmcb->save.sysenter_cs = data;
4436 case MSR_IA32_SYSENTER_EIP:
4437 svm->sysenter_eip = data;
4438 svm->vmcb->save.sysenter_eip = data;
4440 case MSR_IA32_SYSENTER_ESP:
4441 svm->sysenter_esp = data;
4442 svm->vmcb->save.sysenter_esp = data;
4445 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4449 * This is rare, so we update the MSR here instead of using
4450 * direct_access_msrs. Doing that would require a rdmsr in
4453 svm->tsc_aux = data;
4454 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4456 case MSR_IA32_DEBUGCTLMSR:
4457 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4458 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4462 if (data & DEBUGCTL_RESERVED_BITS)
4465 svm->vmcb->save.dbgctl = data;
4466 mark_dirty(svm->vmcb, VMCB_LBR);
4467 if (data & (1ULL<<0))
4468 svm_enable_lbrv(svm);
4470 svm_disable_lbrv(svm);
4472 case MSR_VM_HSAVE_PA:
4473 svm->nested.hsave_msr = data;
4476 return svm_set_vm_cr(vcpu, data);
4478 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4480 case MSR_F10H_DECFG: {
4481 struct kvm_msr_entry msr_entry;
4483 msr_entry.index = msr->index;
4484 if (svm_get_msr_feature(&msr_entry))
4487 /* Check the supported bits */
4488 if (data & ~msr_entry.data)
4491 /* Don't allow the guest to change a bit, #GP */
4492 if (!msr->host_initiated && (data ^ msr_entry.data))
4495 svm->msr_decfg = data;
4498 case MSR_IA32_APICBASE:
4499 if (kvm_vcpu_apicv_active(vcpu))
4500 avic_update_vapic_bar(to_svm(vcpu), data);
4503 return kvm_set_msr_common(vcpu, msr);
4508 static int wrmsr_interception(struct vcpu_svm *svm)
4510 return kvm_emulate_wrmsr(&svm->vcpu);
4513 static int msr_interception(struct vcpu_svm *svm)
4515 if (svm->vmcb->control.exit_info_1)
4516 return wrmsr_interception(svm);
4518 return rdmsr_interception(svm);
4521 static int interrupt_window_interception(struct vcpu_svm *svm)
4523 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4524 svm_clear_vintr(svm);
4527 * For AVIC, the only reason to end up here is ExtINTs.
4528 * In this case AVIC was temporarily disabled for
4529 * requesting the IRQ window and we have to re-enable it.
4531 svm_toggle_avic_for_irq_window(&svm->vcpu, true);
4533 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4534 mark_dirty(svm->vmcb, VMCB_INTR);
4535 ++svm->vcpu.stat.irq_window_exits;
4539 static int pause_interception(struct vcpu_svm *svm)
4541 struct kvm_vcpu *vcpu = &svm->vcpu;
4542 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4544 if (pause_filter_thresh)
4545 grow_ple_window(vcpu);
4547 kvm_vcpu_on_spin(vcpu, in_kernel);
4551 static int nop_interception(struct vcpu_svm *svm)
4553 return kvm_skip_emulated_instruction(&(svm->vcpu));
4556 static int monitor_interception(struct vcpu_svm *svm)
4558 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4559 return nop_interception(svm);
4562 static int mwait_interception(struct vcpu_svm *svm)
4564 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4565 return nop_interception(svm);
4568 enum avic_ipi_failure_cause {
4569 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4570 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4571 AVIC_IPI_FAILURE_INVALID_TARGET,
4572 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4575 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4577 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4578 u32 icrl = svm->vmcb->control.exit_info_1;
4579 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4580 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4581 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4583 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4586 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4588 * AVIC hardware handles the generation of
4589 * IPIs when the specified Message Type is Fixed
4590 * (also known as fixed delivery mode) and
4591 * the Trigger Mode is edge-triggered. The hardware
4592 * also supports self and broadcast delivery modes
4593 * specified via the Destination Shorthand(DSH)
4594 * field of the ICRL. Logical and physical APIC ID
4595 * formats are supported. All other IPI types cause
4596 * a #VMEXIT, which needs to emulated.
4598 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4599 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4601 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4603 struct kvm_vcpu *vcpu;
4604 struct kvm *kvm = svm->vcpu.kvm;
4605 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4608 * At this point, we expect that the AVIC HW has already
4609 * set the appropriate IRR bits on the valid target
4610 * vcpus. So, we just need to kick the appropriate vcpu.
4612 kvm_for_each_vcpu(i, vcpu, kvm) {
4613 bool m = kvm_apic_match_dest(vcpu, apic,
4614 icrl & APIC_SHORT_MASK,
4615 GET_APIC_DEST_FIELD(icrh),
4616 icrl & APIC_DEST_MASK);
4618 if (m && !avic_vcpu_is_running(vcpu))
4619 kvm_vcpu_wake_up(vcpu);
4623 case AVIC_IPI_FAILURE_INVALID_TARGET:
4624 WARN_ONCE(1, "Invalid IPI target: index=%u, vcpu=%d, icr=%#0x:%#0x\n",
4625 index, svm->vcpu.vcpu_id, icrh, icrl);
4627 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4628 WARN_ONCE(1, "Invalid backing page\n");
4631 pr_err("Unknown IPI interception\n");
4637 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4639 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4641 u32 *logical_apic_id_table;
4642 int dlid = GET_APIC_LOGICAL_ID(ldr);
4647 if (flat) { /* flat */
4648 index = ffs(dlid) - 1;
4651 } else { /* cluster */
4652 int cluster = (dlid & 0xf0) >> 4;
4653 int apic = ffs(dlid & 0x0f) - 1;
4655 if ((apic < 0) || (apic > 7) ||
4658 index = (cluster << 2) + apic;
4661 logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4663 return &logical_apic_id_table[index];
4666 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
4669 u32 *entry, new_entry;
4671 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4672 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4676 new_entry = READ_ONCE(*entry);
4677 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4678 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4679 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4680 WRITE_ONCE(*entry, new_entry);
4685 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
4687 struct vcpu_svm *svm = to_svm(vcpu);
4688 bool flat = svm->dfr_reg == APIC_DFR_FLAT;
4689 u32 *entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
4692 clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
4695 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4698 struct vcpu_svm *svm = to_svm(vcpu);
4699 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4700 u32 id = kvm_xapic_id(vcpu->arch.apic);
4702 if (ldr == svm->ldr_reg)
4705 avic_invalidate_logical_id_entry(vcpu);
4708 ret = avic_ldr_write(vcpu, id, ldr);
4716 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4719 struct vcpu_svm *svm = to_svm(vcpu);
4720 u32 id = kvm_xapic_id(vcpu->arch.apic);
4722 if (vcpu->vcpu_id == id)
4725 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4726 new = avic_get_physical_id_entry(vcpu, id);
4730 /* We need to move physical_id_entry to new offset */
4733 to_svm(vcpu)->avic_physical_id_cache = new;
4736 * Also update the guest physical APIC ID in the logical
4737 * APIC ID table entry if already setup the LDR.
4740 avic_handle_ldr_update(vcpu);
4745 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4747 struct vcpu_svm *svm = to_svm(vcpu);
4748 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4750 if (svm->dfr_reg == dfr)
4753 avic_invalidate_logical_id_entry(vcpu);
4757 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4759 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4760 u32 offset = svm->vmcb->control.exit_info_1 &
4761 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4765 if (avic_handle_apic_id_update(&svm->vcpu))
4769 if (avic_handle_ldr_update(&svm->vcpu))
4773 avic_handle_dfr_update(&svm->vcpu);
4779 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4784 static bool is_avic_unaccelerated_access_trap(u32 offset)
4813 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4816 u32 offset = svm->vmcb->control.exit_info_1 &
4817 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4818 u32 vector = svm->vmcb->control.exit_info_2 &
4819 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4820 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4821 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4822 bool trap = is_avic_unaccelerated_access_trap(offset);
4824 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4825 trap, write, vector);
4828 WARN_ONCE(!write, "svm: Handling trap read.\n");
4829 ret = avic_unaccel_trap_write(svm);
4831 /* Handling Fault */
4832 ret = kvm_emulate_instruction(&svm->vcpu, 0);
4838 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4839 [SVM_EXIT_READ_CR0] = cr_interception,
4840 [SVM_EXIT_READ_CR3] = cr_interception,
4841 [SVM_EXIT_READ_CR4] = cr_interception,
4842 [SVM_EXIT_READ_CR8] = cr_interception,
4843 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4844 [SVM_EXIT_WRITE_CR0] = cr_interception,
4845 [SVM_EXIT_WRITE_CR3] = cr_interception,
4846 [SVM_EXIT_WRITE_CR4] = cr_interception,
4847 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4848 [SVM_EXIT_READ_DR0] = dr_interception,
4849 [SVM_EXIT_READ_DR1] = dr_interception,
4850 [SVM_EXIT_READ_DR2] = dr_interception,
4851 [SVM_EXIT_READ_DR3] = dr_interception,
4852 [SVM_EXIT_READ_DR4] = dr_interception,
4853 [SVM_EXIT_READ_DR5] = dr_interception,
4854 [SVM_EXIT_READ_DR6] = dr_interception,
4855 [SVM_EXIT_READ_DR7] = dr_interception,
4856 [SVM_EXIT_WRITE_DR0] = dr_interception,
4857 [SVM_EXIT_WRITE_DR1] = dr_interception,
4858 [SVM_EXIT_WRITE_DR2] = dr_interception,
4859 [SVM_EXIT_WRITE_DR3] = dr_interception,
4860 [SVM_EXIT_WRITE_DR4] = dr_interception,
4861 [SVM_EXIT_WRITE_DR5] = dr_interception,
4862 [SVM_EXIT_WRITE_DR6] = dr_interception,
4863 [SVM_EXIT_WRITE_DR7] = dr_interception,
4864 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4865 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4866 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4867 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4868 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4869 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4870 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
4871 [SVM_EXIT_INTR] = intr_interception,
4872 [SVM_EXIT_NMI] = nmi_interception,
4873 [SVM_EXIT_SMI] = nop_on_interception,
4874 [SVM_EXIT_INIT] = nop_on_interception,
4875 [SVM_EXIT_VINTR] = interrupt_window_interception,
4876 [SVM_EXIT_RDPMC] = rdpmc_interception,
4877 [SVM_EXIT_CPUID] = cpuid_interception,
4878 [SVM_EXIT_IRET] = iret_interception,
4879 [SVM_EXIT_INVD] = emulate_on_interception,
4880 [SVM_EXIT_PAUSE] = pause_interception,
4881 [SVM_EXIT_HLT] = halt_interception,
4882 [SVM_EXIT_INVLPG] = invlpg_interception,
4883 [SVM_EXIT_INVLPGA] = invlpga_interception,
4884 [SVM_EXIT_IOIO] = io_interception,
4885 [SVM_EXIT_MSR] = msr_interception,
4886 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4887 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4888 [SVM_EXIT_VMRUN] = vmrun_interception,
4889 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4890 [SVM_EXIT_VMLOAD] = vmload_interception,
4891 [SVM_EXIT_VMSAVE] = vmsave_interception,
4892 [SVM_EXIT_STGI] = stgi_interception,
4893 [SVM_EXIT_CLGI] = clgi_interception,
4894 [SVM_EXIT_SKINIT] = skinit_interception,
4895 [SVM_EXIT_WBINVD] = wbinvd_interception,
4896 [SVM_EXIT_MONITOR] = monitor_interception,
4897 [SVM_EXIT_MWAIT] = mwait_interception,
4898 [SVM_EXIT_XSETBV] = xsetbv_interception,
4899 [SVM_EXIT_RDPRU] = rdpru_interception,
4900 [SVM_EXIT_NPF] = npf_interception,
4901 [SVM_EXIT_RSM] = rsm_interception,
4902 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4903 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4906 static void dump_vmcb(struct kvm_vcpu *vcpu)
4908 struct vcpu_svm *svm = to_svm(vcpu);
4909 struct vmcb_control_area *control = &svm->vmcb->control;
4910 struct vmcb_save_area *save = &svm->vmcb->save;
4912 if (!dump_invalid_vmcb) {
4913 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
4917 pr_err("VMCB Control Area:\n");
4918 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4919 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4920 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4921 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4922 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4923 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4924 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4925 pr_err("%-20s%d\n", "pause filter threshold:",
4926 control->pause_filter_thresh);
4927 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4928 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4929 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4930 pr_err("%-20s%d\n", "asid:", control->asid);
4931 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4932 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4933 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4934 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4935 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4936 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4937 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4938 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4939 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4940 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4941 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4942 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4943 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4944 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4945 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4946 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4947 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4948 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4949 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4950 pr_err("VMCB State Save Area:\n");
4951 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4953 save->es.selector, save->es.attrib,
4954 save->es.limit, save->es.base);
4955 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4957 save->cs.selector, save->cs.attrib,
4958 save->cs.limit, save->cs.base);
4959 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4961 save->ss.selector, save->ss.attrib,
4962 save->ss.limit, save->ss.base);
4963 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4965 save->ds.selector, save->ds.attrib,
4966 save->ds.limit, save->ds.base);
4967 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4969 save->fs.selector, save->fs.attrib,
4970 save->fs.limit, save->fs.base);
4971 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4973 save->gs.selector, save->gs.attrib,
4974 save->gs.limit, save->gs.base);
4975 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4977 save->gdtr.selector, save->gdtr.attrib,
4978 save->gdtr.limit, save->gdtr.base);
4979 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4981 save->ldtr.selector, save->ldtr.attrib,
4982 save->ldtr.limit, save->ldtr.base);
4983 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4985 save->idtr.selector, save->idtr.attrib,
4986 save->idtr.limit, save->idtr.base);
4987 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4989 save->tr.selector, save->tr.attrib,
4990 save->tr.limit, save->tr.base);
4991 pr_err("cpl: %d efer: %016llx\n",
4992 save->cpl, save->efer);
4993 pr_err("%-15s %016llx %-13s %016llx\n",
4994 "cr0:", save->cr0, "cr2:", save->cr2);
4995 pr_err("%-15s %016llx %-13s %016llx\n",
4996 "cr3:", save->cr3, "cr4:", save->cr4);
4997 pr_err("%-15s %016llx %-13s %016llx\n",
4998 "dr6:", save->dr6, "dr7:", save->dr7);
4999 pr_err("%-15s %016llx %-13s %016llx\n",
5000 "rip:", save->rip, "rflags:", save->rflags);
5001 pr_err("%-15s %016llx %-13s %016llx\n",
5002 "rsp:", save->rsp, "rax:", save->rax);
5003 pr_err("%-15s %016llx %-13s %016llx\n",
5004 "star:", save->star, "lstar:", save->lstar);
5005 pr_err("%-15s %016llx %-13s %016llx\n",
5006 "cstar:", save->cstar, "sfmask:", save->sfmask);
5007 pr_err("%-15s %016llx %-13s %016llx\n",
5008 "kernel_gs_base:", save->kernel_gs_base,
5009 "sysenter_cs:", save->sysenter_cs);
5010 pr_err("%-15s %016llx %-13s %016llx\n",
5011 "sysenter_esp:", save->sysenter_esp,
5012 "sysenter_eip:", save->sysenter_eip);
5013 pr_err("%-15s %016llx %-13s %016llx\n",
5014 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
5015 pr_err("%-15s %016llx %-13s %016llx\n",
5016 "br_from:", save->br_from, "br_to:", save->br_to);
5017 pr_err("%-15s %016llx %-13s %016llx\n",
5018 "excp_from:", save->last_excp_from,
5019 "excp_to:", save->last_excp_to);
5022 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
5024 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
5026 *info1 = control->exit_info_1;
5027 *info2 = control->exit_info_2;
5030 static int handle_exit(struct kvm_vcpu *vcpu,
5031 enum exit_fastpath_completion exit_fastpath)
5033 struct vcpu_svm *svm = to_svm(vcpu);
5034 struct kvm_run *kvm_run = vcpu->run;
5035 u32 exit_code = svm->vmcb->control.exit_code;
5037 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
5039 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
5040 vcpu->arch.cr0 = svm->vmcb->save.cr0;
5042 vcpu->arch.cr3 = svm->vmcb->save.cr3;
5044 if (unlikely(svm->nested.exit_required)) {
5045 nested_svm_vmexit(svm);
5046 svm->nested.exit_required = false;
5051 if (is_guest_mode(vcpu)) {
5054 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
5055 svm->vmcb->control.exit_info_1,
5056 svm->vmcb->control.exit_info_2,
5057 svm->vmcb->control.exit_int_info,
5058 svm->vmcb->control.exit_int_info_err,
5061 vmexit = nested_svm_exit_special(svm);
5063 if (vmexit == NESTED_EXIT_CONTINUE)
5064 vmexit = nested_svm_exit_handled(svm);
5066 if (vmexit == NESTED_EXIT_DONE)
5070 svm_complete_interrupts(svm);
5072 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
5073 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
5074 kvm_run->fail_entry.hardware_entry_failure_reason
5075 = svm->vmcb->control.exit_code;
5080 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
5081 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
5082 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
5083 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
5084 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
5086 __func__, svm->vmcb->control.exit_int_info,
5089 if (exit_fastpath == EXIT_FASTPATH_SKIP_EMUL_INS) {
5090 kvm_skip_emulated_instruction(vcpu);
5092 } else if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
5093 || !svm_exit_handlers[exit_code]) {
5094 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%x\n", exit_code);
5096 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5097 vcpu->run->internal.suberror =
5098 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
5099 vcpu->run->internal.ndata = 1;
5100 vcpu->run->internal.data[0] = exit_code;
5104 #ifdef CONFIG_RETPOLINE
5105 if (exit_code == SVM_EXIT_MSR)
5106 return msr_interception(svm);
5107 else if (exit_code == SVM_EXIT_VINTR)
5108 return interrupt_window_interception(svm);
5109 else if (exit_code == SVM_EXIT_INTR)
5110 return intr_interception(svm);
5111 else if (exit_code == SVM_EXIT_HLT)
5112 return halt_interception(svm);
5113 else if (exit_code == SVM_EXIT_NPF)
5114 return npf_interception(svm);
5116 return svm_exit_handlers[exit_code](svm);
5119 static void reload_tss(struct kvm_vcpu *vcpu)
5121 int cpu = raw_smp_processor_id();
5123 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5124 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
5128 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
5130 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5131 int asid = sev_get_asid(svm->vcpu.kvm);
5133 /* Assign the asid allocated with this SEV guest */
5134 svm->vmcb->control.asid = asid;
5139 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
5140 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
5142 if (sd->sev_vmcbs[asid] == svm->vmcb &&
5143 svm->last_cpu == cpu)
5146 svm->last_cpu = cpu;
5147 sd->sev_vmcbs[asid] = svm->vmcb;
5148 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5149 mark_dirty(svm->vmcb, VMCB_ASID);
5152 static void pre_svm_run(struct vcpu_svm *svm)
5154 int cpu = raw_smp_processor_id();
5156 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5158 if (sev_guest(svm->vcpu.kvm))
5159 return pre_sev_run(svm, cpu);
5161 /* FIXME: handle wraparound of asid_generation */
5162 if (svm->asid_generation != sd->asid_generation)
5166 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5168 struct vcpu_svm *svm = to_svm(vcpu);
5170 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5171 vcpu->arch.hflags |= HF_NMI_MASK;
5172 set_intercept(svm, INTERCEPT_IRET);
5173 ++vcpu->stat.nmi_injections;
5176 static void svm_set_irq(struct kvm_vcpu *vcpu)
5178 struct vcpu_svm *svm = to_svm(vcpu);
5180 BUG_ON(!(gif_set(svm)));
5182 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5183 ++vcpu->stat.irq_injections;
5185 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5186 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5189 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5191 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5194 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5196 struct vcpu_svm *svm = to_svm(vcpu);
5198 if (svm_nested_virtualize_tpr(vcpu))
5201 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5207 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5210 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5215 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5219 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5223 static void svm_toggle_avic_for_irq_window(struct kvm_vcpu *vcpu, bool activate)
5225 if (!avic || !lapic_in_kernel(vcpu))
5228 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
5229 kvm_request_apicv_update(vcpu->kvm, activate,
5230 APICV_INHIBIT_REASON_IRQWIN);
5231 vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
5234 static int svm_set_pi_irte_mode(struct kvm_vcpu *vcpu, bool activate)
5237 unsigned long flags;
5238 struct amd_svm_iommu_ir *ir;
5239 struct vcpu_svm *svm = to_svm(vcpu);
5241 if (!kvm_arch_has_assigned_device(vcpu->kvm))
5245 * Here, we go through the per-vcpu ir_list to update all existing
5246 * interrupt remapping table entry targeting this vcpu.
5248 spin_lock_irqsave(&svm->ir_list_lock, flags);
5250 if (list_empty(&svm->ir_list))
5253 list_for_each_entry(ir, &svm->ir_list, node) {
5255 ret = amd_iommu_activate_guest_mode(ir->data);
5257 ret = amd_iommu_deactivate_guest_mode(ir->data);
5262 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5266 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5268 struct vcpu_svm *svm = to_svm(vcpu);
5269 struct vmcb *vmcb = svm->vmcb;
5270 bool activated = kvm_vcpu_apicv_active(vcpu);
5277 * During AVIC temporary deactivation, guest could update
5278 * APIC ID, DFR and LDR registers, which would not be trapped
5279 * by avic_unaccelerated_access_interception(). In this case,
5280 * we need to check and update the AVIC logical APIC ID table
5281 * accordingly before re-activating.
5283 avic_post_state_restore(vcpu);
5284 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
5286 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5288 mark_dirty(vmcb, VMCB_AVIC);
5290 svm_set_pi_irte_mode(vcpu, activated);
5293 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5298 static int svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5300 if (!vcpu->arch.apicv_active)
5303 kvm_lapic_set_irr(vec, vcpu->arch.apic);
5304 smp_mb__after_atomic();
5306 if (avic_vcpu_is_running(vcpu)) {
5307 int cpuid = vcpu->cpu;
5309 if (cpuid != get_cpu())
5310 wrmsrl(SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpuid));
5313 kvm_vcpu_wake_up(vcpu);
5318 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
5323 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5325 unsigned long flags;
5326 struct amd_svm_iommu_ir *cur;
5328 spin_lock_irqsave(&svm->ir_list_lock, flags);
5329 list_for_each_entry(cur, &svm->ir_list, node) {
5330 if (cur->data != pi->ir_data)
5332 list_del(&cur->node);
5336 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5339 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5342 unsigned long flags;
5343 struct amd_svm_iommu_ir *ir;
5346 * In some cases, the existing irte is updaed and re-set,
5347 * so we need to check here if it's already been * added
5350 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5351 struct kvm *kvm = svm->vcpu.kvm;
5352 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5353 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5354 struct vcpu_svm *prev_svm;
5361 prev_svm = to_svm(prev_vcpu);
5362 svm_ir_list_del(prev_svm, pi);
5366 * Allocating new amd_iommu_pi_data, which will get
5367 * add to the per-vcpu ir_list.
5369 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL_ACCOUNT);
5374 ir->data = pi->ir_data;
5376 spin_lock_irqsave(&svm->ir_list_lock, flags);
5377 list_add(&ir->node, &svm->ir_list);
5378 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5385 * The HW cannot support posting multicast/broadcast
5386 * interrupts to a vCPU. So, we still use legacy interrupt
5387 * remapping for these kind of interrupts.
5389 * For lowest-priority interrupts, we only support
5390 * those with single CPU as the destination, e.g. user
5391 * configures the interrupts via /proc/irq or uses
5392 * irqbalance to make the interrupts single-CPU.
5395 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5396 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5398 struct kvm_lapic_irq irq;
5399 struct kvm_vcpu *vcpu = NULL;
5401 kvm_set_msi_irq(kvm, e, &irq);
5403 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
5404 !kvm_irq_is_postable(&irq)) {
5405 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5406 __func__, irq.vector);
5410 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5412 *svm = to_svm(vcpu);
5413 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5414 vcpu_info->vector = irq.vector;
5420 * svm_update_pi_irte - set IRTE for Posted-Interrupts
5423 * @host_irq: host irq of the interrupt
5424 * @guest_irq: gsi of the interrupt
5425 * @set: set or unset PI
5426 * returns 0 on success, < 0 on failure
5428 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5429 uint32_t guest_irq, bool set)
5431 struct kvm_kernel_irq_routing_entry *e;
5432 struct kvm_irq_routing_table *irq_rt;
5433 int idx, ret = -EINVAL;
5435 if (!kvm_arch_has_assigned_device(kvm) ||
5436 !irq_remapping_cap(IRQ_POSTING_CAP))
5439 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5440 __func__, host_irq, guest_irq, set);
5442 idx = srcu_read_lock(&kvm->irq_srcu);
5443 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5444 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5446 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5447 struct vcpu_data vcpu_info;
5448 struct vcpu_svm *svm = NULL;
5450 if (e->type != KVM_IRQ_ROUTING_MSI)
5454 * Here, we setup with legacy mode in the following cases:
5455 * 1. When cannot target interrupt to a specific vcpu.
5456 * 2. Unsetting posted interrupt.
5457 * 3. APIC virtialization is disabled for the vcpu.
5458 * 4. IRQ has incompatible delivery mode (SMI, INIT, etc)
5460 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5461 kvm_vcpu_apicv_active(&svm->vcpu)) {
5462 struct amd_iommu_pi_data pi;
5464 /* Try to enable guest_mode in IRTE */
5465 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5467 pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5469 pi.is_guest_mode = true;
5470 pi.vcpu_data = &vcpu_info;
5471 ret = irq_set_vcpu_affinity(host_irq, &pi);
5474 * Here, we successfully setting up vcpu affinity in
5475 * IOMMU guest mode. Now, we need to store the posted
5476 * interrupt information in a per-vcpu ir_list so that
5477 * we can reference to them directly when we update vcpu
5478 * scheduling information in IOMMU irte.
5480 if (!ret && pi.is_guest_mode)
5481 svm_ir_list_add(svm, &pi);
5483 /* Use legacy mode in IRTE */
5484 struct amd_iommu_pi_data pi;
5487 * Here, pi is used to:
5488 * - Tell IOMMU to use legacy mode for this interrupt.
5489 * - Retrieve ga_tag of prior interrupt remapping data.
5491 pi.is_guest_mode = false;
5492 ret = irq_set_vcpu_affinity(host_irq, &pi);
5495 * Check if the posted interrupt was previously
5496 * setup with the guest_mode by checking if the ga_tag
5497 * was cached. If so, we need to clean up the per-vcpu
5500 if (!ret && pi.prev_ga_tag) {
5501 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5502 struct kvm_vcpu *vcpu;
5504 vcpu = kvm_get_vcpu_by_id(kvm, id);
5506 svm_ir_list_del(to_svm(vcpu), &pi);
5511 trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5512 e->gsi, vcpu_info.vector,
5513 vcpu_info.pi_desc_addr, set);
5517 pr_err("%s: failed to update PI IRTE\n", __func__);
5524 srcu_read_unlock(&kvm->irq_srcu, idx);
5528 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5530 struct vcpu_svm *svm = to_svm(vcpu);
5531 struct vmcb *vmcb = svm->vmcb;
5533 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5534 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5535 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5540 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5542 struct vcpu_svm *svm = to_svm(vcpu);
5544 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5547 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5549 struct vcpu_svm *svm = to_svm(vcpu);
5552 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5553 set_intercept(svm, INTERCEPT_IRET);
5555 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5556 clr_intercept(svm, INTERCEPT_IRET);
5560 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5562 struct vcpu_svm *svm = to_svm(vcpu);
5563 struct vmcb *vmcb = svm->vmcb;
5565 if (!gif_set(svm) ||
5566 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5569 if (is_guest_mode(vcpu) && (svm->vcpu.arch.hflags & HF_VINTR_MASK))
5570 return !!(svm->vcpu.arch.hflags & HF_HIF_MASK);
5572 return !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5575 static void enable_irq_window(struct kvm_vcpu *vcpu)
5577 struct vcpu_svm *svm = to_svm(vcpu);
5580 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5581 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5582 * get that intercept, this function will be called again though and
5583 * we'll get the vintr intercept. However, if the vGIF feature is
5584 * enabled, the STGI interception will not occur. Enable the irq
5585 * window under the assumption that the hardware will set the GIF.
5587 if (vgif_enabled(svm) || gif_set(svm)) {
5589 * IRQ window is not needed when AVIC is enabled,
5590 * unless we have pending ExtINT since it cannot be injected
5591 * via AVIC. In such case, we need to temporarily disable AVIC,
5592 * and fallback to injecting IRQ via V_IRQ.
5594 svm_toggle_avic_for_irq_window(vcpu, false);
5599 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5601 struct vcpu_svm *svm = to_svm(vcpu);
5603 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5605 return; /* IRET will cause a vm exit */
5607 if (!gif_set(svm)) {
5608 if (vgif_enabled(svm))
5609 set_intercept(svm, INTERCEPT_STGI);
5610 return; /* STGI will cause a vm exit */
5613 if (svm->nested.exit_required)
5614 return; /* we're not going to run the guest yet */
5617 * Something prevents NMI from been injected. Single step over possible
5618 * problem (IRET or exception injection or interrupt shadow)
5620 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5621 svm->nmi_singlestep = true;
5622 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5625 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5630 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5635 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5637 struct vcpu_svm *svm = to_svm(vcpu);
5639 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5640 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5642 svm->asid_generation--;
5645 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
5647 struct vcpu_svm *svm = to_svm(vcpu);
5649 invlpga(gva, svm->vmcb->control.asid);
5652 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5656 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5658 struct vcpu_svm *svm = to_svm(vcpu);
5660 if (svm_nested_virtualize_tpr(vcpu))
5663 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5664 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5665 kvm_set_cr8(vcpu, cr8);
5669 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5671 struct vcpu_svm *svm = to_svm(vcpu);
5674 if (svm_nested_virtualize_tpr(vcpu) ||
5675 kvm_vcpu_apicv_active(vcpu))
5678 cr8 = kvm_get_cr8(vcpu);
5679 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5680 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5683 static void svm_complete_interrupts(struct vcpu_svm *svm)
5687 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5688 unsigned int3_injected = svm->int3_injected;
5690 svm->int3_injected = 0;
5693 * If we've made progress since setting HF_IRET_MASK, we've
5694 * executed an IRET and can allow NMI injection.
5696 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5697 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5698 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5699 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5702 svm->vcpu.arch.nmi_injected = false;
5703 kvm_clear_exception_queue(&svm->vcpu);
5704 kvm_clear_interrupt_queue(&svm->vcpu);
5706 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5709 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5711 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5712 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5715 case SVM_EXITINTINFO_TYPE_NMI:
5716 svm->vcpu.arch.nmi_injected = true;
5718 case SVM_EXITINTINFO_TYPE_EXEPT:
5720 * In case of software exceptions, do not reinject the vector,
5721 * but re-execute the instruction instead. Rewind RIP first
5722 * if we emulated INT3 before.
5724 if (kvm_exception_is_soft(vector)) {
5725 if (vector == BP_VECTOR && int3_injected &&
5726 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5727 kvm_rip_write(&svm->vcpu,
5728 kvm_rip_read(&svm->vcpu) -
5732 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5733 u32 err = svm->vmcb->control.exit_int_info_err;
5734 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5737 kvm_requeue_exception(&svm->vcpu, vector);
5739 case SVM_EXITINTINFO_TYPE_INTR:
5740 kvm_queue_interrupt(&svm->vcpu, vector, false);
5747 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5749 struct vcpu_svm *svm = to_svm(vcpu);
5750 struct vmcb_control_area *control = &svm->vmcb->control;
5752 control->exit_int_info = control->event_inj;
5753 control->exit_int_info_err = control->event_inj_err;
5754 control->event_inj = 0;
5755 svm_complete_interrupts(svm);
5758 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5760 struct vcpu_svm *svm = to_svm(vcpu);
5762 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5763 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5764 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5767 * A vmexit emulation is required before the vcpu can be executed
5770 if (unlikely(svm->nested.exit_required))
5774 * Disable singlestep if we're injecting an interrupt/exception.
5775 * We don't want our modified rflags to be pushed on the stack where
5776 * we might not be able to easily reset them if we disabled NMI
5779 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5781 * Event injection happens before external interrupts cause a
5782 * vmexit and interrupts are disabled here, so smp_send_reschedule
5783 * is enough to force an immediate vmexit.
5785 disable_nmi_singlestep(svm);
5786 smp_send_reschedule(vcpu->cpu);
5791 sync_lapic_to_cr8(vcpu);
5793 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5796 kvm_load_guest_xsave_state(vcpu);
5798 if (lapic_in_kernel(vcpu) &&
5799 vcpu->arch.apic->lapic_timer.timer_advance_ns)
5800 kvm_wait_lapic_expire(vcpu);
5803 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5804 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5805 * is no need to worry about the conditional branch over the wrmsr
5806 * being speculatively taken.
5808 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5813 "push %%" _ASM_BP "; \n\t"
5814 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5815 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5816 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5817 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5818 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5819 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5820 #ifdef CONFIG_X86_64
5821 "mov %c[r8](%[svm]), %%r8 \n\t"
5822 "mov %c[r9](%[svm]), %%r9 \n\t"
5823 "mov %c[r10](%[svm]), %%r10 \n\t"
5824 "mov %c[r11](%[svm]), %%r11 \n\t"
5825 "mov %c[r12](%[svm]), %%r12 \n\t"
5826 "mov %c[r13](%[svm]), %%r13 \n\t"
5827 "mov %c[r14](%[svm]), %%r14 \n\t"
5828 "mov %c[r15](%[svm]), %%r15 \n\t"
5831 /* Enter guest mode */
5832 "push %%" _ASM_AX " \n\t"
5833 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5834 __ex("vmload %%" _ASM_AX) "\n\t"
5835 __ex("vmrun %%" _ASM_AX) "\n\t"
5836 __ex("vmsave %%" _ASM_AX) "\n\t"
5837 "pop %%" _ASM_AX " \n\t"
5839 /* Save guest registers, load host registers */
5840 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5841 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5842 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5843 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5844 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5845 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5846 #ifdef CONFIG_X86_64
5847 "mov %%r8, %c[r8](%[svm]) \n\t"
5848 "mov %%r9, %c[r9](%[svm]) \n\t"
5849 "mov %%r10, %c[r10](%[svm]) \n\t"
5850 "mov %%r11, %c[r11](%[svm]) \n\t"
5851 "mov %%r12, %c[r12](%[svm]) \n\t"
5852 "mov %%r13, %c[r13](%[svm]) \n\t"
5853 "mov %%r14, %c[r14](%[svm]) \n\t"
5854 "mov %%r15, %c[r15](%[svm]) \n\t"
5856 * Clear host registers marked as clobbered to prevent
5859 "xor %%r8d, %%r8d \n\t"
5860 "xor %%r9d, %%r9d \n\t"
5861 "xor %%r10d, %%r10d \n\t"
5862 "xor %%r11d, %%r11d \n\t"
5863 "xor %%r12d, %%r12d \n\t"
5864 "xor %%r13d, %%r13d \n\t"
5865 "xor %%r14d, %%r14d \n\t"
5866 "xor %%r15d, %%r15d \n\t"
5868 "xor %%ebx, %%ebx \n\t"
5869 "xor %%ecx, %%ecx \n\t"
5870 "xor %%edx, %%edx \n\t"
5871 "xor %%esi, %%esi \n\t"
5872 "xor %%edi, %%edi \n\t"
5876 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5877 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5878 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5879 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5880 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5881 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5882 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5883 #ifdef CONFIG_X86_64
5884 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5885 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5886 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5887 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5888 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5889 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5890 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5891 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5894 #ifdef CONFIG_X86_64
5895 , "rbx", "rcx", "rdx", "rsi", "rdi"
5896 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5898 , "ebx", "ecx", "edx", "esi", "edi"
5902 /* Eliminate branch target predictions from guest mode */
5905 #ifdef CONFIG_X86_64
5906 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5908 loadsegment(fs, svm->host.fs);
5909 #ifndef CONFIG_X86_32_LAZY_GS
5910 loadsegment(gs, svm->host.gs);
5915 * We do not use IBRS in the kernel. If this vCPU has used the
5916 * SPEC_CTRL MSR it may have left it on; save the value and
5917 * turn it off. This is much more efficient than blindly adding
5918 * it to the atomic save/restore list. Especially as the former
5919 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5921 * For non-nested case:
5922 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5926 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5929 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5930 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5934 local_irq_disable();
5936 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5938 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5939 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5940 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5941 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5943 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5944 kvm_before_interrupt(&svm->vcpu);
5946 kvm_load_host_xsave_state(vcpu);
5949 /* Any pending NMI will happen here */
5951 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5952 kvm_after_interrupt(&svm->vcpu);
5954 sync_cr8_to_lapic(vcpu);
5958 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5960 /* if exit due to PF check for async PF */
5961 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5962 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5965 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5966 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5970 * We need to handle MC intercepts here before the vcpu has a chance to
5971 * change the physical cpu
5973 if (unlikely(svm->vmcb->control.exit_code ==
5974 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5975 svm_handle_mce(svm);
5977 mark_all_clean(svm->vmcb);
5979 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5981 static void svm_load_mmu_pgd(struct kvm_vcpu *vcpu, unsigned long root)
5983 struct vcpu_svm *svm = to_svm(vcpu);
5984 bool update_guest_cr3 = true;
5987 cr3 = __sme_set(root);
5989 svm->vmcb->control.nested_cr3 = cr3;
5990 mark_dirty(svm->vmcb, VMCB_NPT);
5992 /* Loading L2's CR3 is handled by enter_svm_guest_mode. */
5993 if (is_guest_mode(vcpu))
5994 update_guest_cr3 = false;
5995 else if (test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5996 cr3 = vcpu->arch.cr3;
5997 else /* CR3 is already up-to-date. */
5998 update_guest_cr3 = false;
6001 if (update_guest_cr3) {
6002 svm->vmcb->save.cr3 = cr3;
6003 mark_dirty(svm->vmcb, VMCB_CR);
6007 static int is_disabled(void)
6011 rdmsrl(MSR_VM_CR, vm_cr);
6012 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
6019 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6022 * Patch in the VMMCALL instruction:
6024 hypercall[0] = 0x0f;
6025 hypercall[1] = 0x01;
6026 hypercall[2] = 0xd9;
6029 static int __init svm_check_processor_compat(void)
6034 static bool svm_cpu_has_accelerated_tpr(void)
6039 static bool svm_has_emulated_msr(int index)
6042 case MSR_IA32_MCG_EXT_CTL:
6043 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
6052 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
6057 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
6059 struct vcpu_svm *svm = to_svm(vcpu);
6061 vcpu->arch.xsaves_enabled = guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6062 boot_cpu_has(X86_FEATURE_XSAVE) &&
6063 boot_cpu_has(X86_FEATURE_XSAVES);
6065 /* Update nrips enabled cache */
6066 svm->nrips_enabled = kvm_cpu_cap_has(X86_FEATURE_NRIPS) &&
6067 guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
6069 if (!kvm_vcpu_apicv_active(vcpu))
6073 * AVIC does not work with an x2APIC mode guest. If the X2APIC feature
6074 * is exposed to the guest, disable AVIC.
6076 if (guest_cpuid_has(vcpu, X86_FEATURE_X2APIC))
6077 kvm_request_apicv_update(vcpu->kvm, false,
6078 APICV_INHIBIT_REASON_X2APIC);
6081 * Currently, AVIC does not work with nested virtualization.
6082 * So, we disable AVIC when cpuid for SVM is set in the L1 guest.
6084 if (nested && guest_cpuid_has(vcpu, X86_FEATURE_SVM))
6085 kvm_request_apicv_update(vcpu->kvm, false,
6086 APICV_INHIBIT_REASON_NESTED);
6089 static bool svm_has_wbinvd_exit(void)
6094 #define PRE_EX(exit) { .exit_code = (exit), \
6095 .stage = X86_ICPT_PRE_EXCEPT, }
6096 #define POST_EX(exit) { .exit_code = (exit), \
6097 .stage = X86_ICPT_POST_EXCEPT, }
6098 #define POST_MEM(exit) { .exit_code = (exit), \
6099 .stage = X86_ICPT_POST_MEMACCESS, }
6101 static const struct __x86_intercept {
6103 enum x86_intercept_stage stage;
6104 } x86_intercept_map[] = {
6105 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
6106 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
6107 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
6108 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
6109 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
6110 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
6111 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
6112 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
6113 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
6114 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
6115 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
6116 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
6117 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
6118 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
6119 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
6120 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
6121 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
6122 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
6123 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
6124 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
6125 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
6126 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
6127 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
6128 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
6129 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
6130 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
6131 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
6132 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
6133 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
6134 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
6135 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
6136 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
6137 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
6138 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
6139 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
6140 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
6141 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
6142 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
6143 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
6144 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
6145 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
6146 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
6147 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
6148 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
6149 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
6150 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
6151 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
6158 static int svm_check_intercept(struct kvm_vcpu *vcpu,
6159 struct x86_instruction_info *info,
6160 enum x86_intercept_stage stage,
6161 struct x86_exception *exception)
6163 struct vcpu_svm *svm = to_svm(vcpu);
6164 int vmexit, ret = X86EMUL_CONTINUE;
6165 struct __x86_intercept icpt_info;
6166 struct vmcb *vmcb = svm->vmcb;
6168 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
6171 icpt_info = x86_intercept_map[info->intercept];
6173 if (stage != icpt_info.stage)
6176 switch (icpt_info.exit_code) {
6177 case SVM_EXIT_READ_CR0:
6178 if (info->intercept == x86_intercept_cr_read)
6179 icpt_info.exit_code += info->modrm_reg;
6181 case SVM_EXIT_WRITE_CR0: {
6182 unsigned long cr0, val;
6185 if (info->intercept == x86_intercept_cr_write)
6186 icpt_info.exit_code += info->modrm_reg;
6188 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
6189 info->intercept == x86_intercept_clts)
6192 intercept = svm->nested.intercept;
6194 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
6197 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
6198 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
6200 if (info->intercept == x86_intercept_lmsw) {
6203 /* lmsw can't clear PE - catch this here */
6204 if (cr0 & X86_CR0_PE)
6209 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
6213 case SVM_EXIT_READ_DR0:
6214 case SVM_EXIT_WRITE_DR0:
6215 icpt_info.exit_code += info->modrm_reg;
6218 if (info->intercept == x86_intercept_wrmsr)
6219 vmcb->control.exit_info_1 = 1;
6221 vmcb->control.exit_info_1 = 0;
6223 case SVM_EXIT_PAUSE:
6225 * We get this for NOP only, but pause
6226 * is rep not, check this here
6228 if (info->rep_prefix != REPE_PREFIX)
6231 case SVM_EXIT_IOIO: {
6235 if (info->intercept == x86_intercept_in ||
6236 info->intercept == x86_intercept_ins) {
6237 exit_info = ((info->src_val & 0xffff) << 16) |
6239 bytes = info->dst_bytes;
6241 exit_info = (info->dst_val & 0xffff) << 16;
6242 bytes = info->src_bytes;
6245 if (info->intercept == x86_intercept_outs ||
6246 info->intercept == x86_intercept_ins)
6247 exit_info |= SVM_IOIO_STR_MASK;
6249 if (info->rep_prefix)
6250 exit_info |= SVM_IOIO_REP_MASK;
6252 bytes = min(bytes, 4u);
6254 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
6256 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
6258 vmcb->control.exit_info_1 = exit_info;
6259 vmcb->control.exit_info_2 = info->next_rip;
6267 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
6268 if (static_cpu_has(X86_FEATURE_NRIPS))
6269 vmcb->control.next_rip = info->next_rip;
6270 vmcb->control.exit_code = icpt_info.exit_code;
6271 vmexit = nested_svm_exit_handled(svm);
6273 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
6280 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu,
6281 enum exit_fastpath_completion *exit_fastpath)
6283 if (!is_guest_mode(vcpu) &&
6284 to_svm(vcpu)->vmcb->control.exit_code == EXIT_REASON_MSR_WRITE)
6285 *exit_fastpath = handle_fastpath_set_msr_irqoff(vcpu);
6288 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
6290 if (pause_filter_thresh)
6291 shrink_ple_window(vcpu);
6294 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
6296 if (avic_handle_apic_id_update(vcpu) != 0)
6298 avic_handle_dfr_update(vcpu);
6299 avic_handle_ldr_update(vcpu);
6302 static void svm_setup_mce(struct kvm_vcpu *vcpu)
6304 /* [63:9] are reserved. */
6305 vcpu->arch.mcg_cap &= 0x1ff;
6308 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6310 struct vcpu_svm *svm = to_svm(vcpu);
6312 /* Per APM Vol.2 15.22.2 "Response to SMI" */
6316 if (is_guest_mode(&svm->vcpu) &&
6317 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6318 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
6319 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6320 svm->nested.exit_required = true;
6327 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6329 struct vcpu_svm *svm = to_svm(vcpu);
6332 if (is_guest_mode(vcpu)) {
6333 /* FED8h - SVM Guest */
6334 put_smstate(u64, smstate, 0x7ed8, 1);
6335 /* FEE0h - SVM Guest VMCB Physical Address */
6336 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6338 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6339 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6340 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6342 ret = nested_svm_vmexit(svm);
6349 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
6351 struct vcpu_svm *svm = to_svm(vcpu);
6352 struct vmcb *nested_vmcb;
6353 struct kvm_host_map map;
6357 guest = GET_SMSTATE(u64, smstate, 0x7ed8);
6358 vmcb = GET_SMSTATE(u64, smstate, 0x7ee0);
6361 if (kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb), &map) == -EINVAL)
6363 nested_vmcb = map.hva;
6364 enter_svm_guest_mode(svm, vmcb, nested_vmcb, &map);
6369 static int enable_smi_window(struct kvm_vcpu *vcpu)
6371 struct vcpu_svm *svm = to_svm(vcpu);
6373 if (!gif_set(svm)) {
6374 if (vgif_enabled(svm))
6375 set_intercept(svm, INTERCEPT_STGI);
6376 /* STGI will cause a vm exit */
6382 static int sev_flush_asids(void)
6387 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
6388 * so it must be guarded.
6390 down_write(&sev_deactivate_lock);
6392 wbinvd_on_all_cpus();
6393 ret = sev_guest_df_flush(&error);
6395 up_write(&sev_deactivate_lock);
6398 pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
6403 /* Must be called with the sev_bitmap_lock held */
6404 static bool __sev_recycle_asids(void)
6408 /* Check if there are any ASIDs to reclaim before performing a flush */
6409 pos = find_next_bit(sev_reclaim_asid_bitmap,
6410 max_sev_asid, min_sev_asid - 1);
6411 if (pos >= max_sev_asid)
6414 if (sev_flush_asids())
6417 bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
6419 bitmap_zero(sev_reclaim_asid_bitmap, max_sev_asid);
6424 static int sev_asid_new(void)
6429 mutex_lock(&sev_bitmap_lock);
6432 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6435 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6436 if (pos >= max_sev_asid) {
6437 if (retry && __sev_recycle_asids()) {
6441 mutex_unlock(&sev_bitmap_lock);
6445 __set_bit(pos, sev_asid_bitmap);
6447 mutex_unlock(&sev_bitmap_lock);
6452 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6454 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6458 if (unlikely(sev->active))
6461 asid = sev_asid_new();
6465 ret = sev_platform_init(&argp->error);
6471 INIT_LIST_HEAD(&sev->regions_list);
6476 sev_asid_free(asid);
6480 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6482 struct sev_data_activate *data;
6483 int asid = sev_get_asid(kvm);
6486 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6490 /* activate ASID on the given handle */
6491 data->handle = handle;
6493 ret = sev_guest_activate(data, error);
6499 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6508 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6514 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6516 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6518 return __sev_issue_cmd(sev->fd, id, data, error);
6521 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6523 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6524 struct sev_data_launch_start *start;
6525 struct kvm_sev_launch_start params;
6526 void *dh_blob, *session_blob;
6527 int *error = &argp->error;
6530 if (!sev_guest(kvm))
6533 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6536 start = kzalloc(sizeof(*start), GFP_KERNEL_ACCOUNT);
6541 if (params.dh_uaddr) {
6542 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6543 if (IS_ERR(dh_blob)) {
6544 ret = PTR_ERR(dh_blob);
6548 start->dh_cert_address = __sme_set(__pa(dh_blob));
6549 start->dh_cert_len = params.dh_len;
6552 session_blob = NULL;
6553 if (params.session_uaddr) {
6554 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6555 if (IS_ERR(session_blob)) {
6556 ret = PTR_ERR(session_blob);
6560 start->session_address = __sme_set(__pa(session_blob));
6561 start->session_len = params.session_len;
6564 start->handle = params.handle;
6565 start->policy = params.policy;
6567 /* create memory encryption context */
6568 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6570 goto e_free_session;
6572 /* Bind ASID to this guest */
6573 ret = sev_bind_asid(kvm, start->handle, error);
6575 goto e_free_session;
6577 /* return handle to userspace */
6578 params.handle = start->handle;
6579 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params))) {
6580 sev_unbind_asid(kvm, start->handle);
6582 goto e_free_session;
6585 sev->handle = start->handle;
6586 sev->fd = argp->sev_fd;
6589 kfree(session_blob);
6597 static unsigned long get_num_contig_pages(unsigned long idx,
6598 struct page **inpages, unsigned long npages)
6600 unsigned long paddr, next_paddr;
6601 unsigned long i = idx + 1, pages = 1;
6603 /* find the number of contiguous pages starting from idx */
6604 paddr = __sme_page_pa(inpages[idx]);
6605 while (i < npages) {
6606 next_paddr = __sme_page_pa(inpages[i++]);
6607 if ((paddr + PAGE_SIZE) == next_paddr) {
6618 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6620 unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
6621 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6622 struct kvm_sev_launch_update_data params;
6623 struct sev_data_launch_update_data *data;
6624 struct page **inpages;
6627 if (!sev_guest(kvm))
6630 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6633 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6637 vaddr = params.uaddr;
6639 vaddr_end = vaddr + size;
6641 /* Lock the user memory. */
6642 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6649 * The LAUNCH_UPDATE command will perform in-place encryption of the
6650 * memory content (i.e it will write the same memory region with C=1).
6651 * It's possible that the cache may contain the data with C=0, i.e.,
6652 * unencrypted so invalidate it first.
6654 sev_clflush_pages(inpages, npages);
6656 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6660 * If the user buffer is not page-aligned, calculate the offset
6663 offset = vaddr & (PAGE_SIZE - 1);
6665 /* Calculate the number of pages that can be encrypted in one go. */
6666 pages = get_num_contig_pages(i, inpages, npages);
6668 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6670 data->handle = sev->handle;
6672 data->address = __sme_page_pa(inpages[i]) + offset;
6673 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6678 next_vaddr = vaddr + len;
6682 /* content of memory is updated, mark pages dirty */
6683 for (i = 0; i < npages; i++) {
6684 set_page_dirty_lock(inpages[i]);
6685 mark_page_accessed(inpages[i]);
6687 /* unlock the user pages */
6688 sev_unpin_memory(kvm, inpages, npages);
6694 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6696 void __user *measure = (void __user *)(uintptr_t)argp->data;
6697 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6698 struct sev_data_launch_measure *data;
6699 struct kvm_sev_launch_measure params;
6700 void __user *p = NULL;
6704 if (!sev_guest(kvm))
6707 if (copy_from_user(¶ms, measure, sizeof(params)))
6710 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6714 /* User wants to query the blob length */
6718 p = (void __user *)(uintptr_t)params.uaddr;
6720 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6726 blob = kmalloc(params.len, GFP_KERNEL);
6730 data->address = __psp_pa(blob);
6731 data->len = params.len;
6735 data->handle = sev->handle;
6736 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6739 * If we query the session length, FW responded with expected data.
6748 if (copy_to_user(p, blob, params.len))
6753 params.len = data->len;
6754 if (copy_to_user(measure, ¶ms, sizeof(params)))
6763 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6765 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6766 struct sev_data_launch_finish *data;
6769 if (!sev_guest(kvm))
6772 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6776 data->handle = sev->handle;
6777 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6783 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6785 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6786 struct kvm_sev_guest_status params;
6787 struct sev_data_guest_status *data;
6790 if (!sev_guest(kvm))
6793 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6797 data->handle = sev->handle;
6798 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6802 params.policy = data->policy;
6803 params.state = data->state;
6804 params.handle = data->handle;
6806 if (copy_to_user((void __user *)(uintptr_t)argp->data, ¶ms, sizeof(params)))
6813 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6814 unsigned long dst, int size,
6815 int *error, bool enc)
6817 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6818 struct sev_data_dbg *data;
6821 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6825 data->handle = sev->handle;
6826 data->dst_addr = dst;
6827 data->src_addr = src;
6830 ret = sev_issue_cmd(kvm,
6831 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6837 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6838 unsigned long dst_paddr, int sz, int *err)
6843 * Its safe to read more than we are asked, caller should ensure that
6844 * destination has enough space.
6846 src_paddr = round_down(src_paddr, 16);
6847 offset = src_paddr & 15;
6848 sz = round_up(sz + offset, 16);
6850 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6853 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6854 unsigned long __user dst_uaddr,
6855 unsigned long dst_paddr,
6858 struct page *tpage = NULL;
6861 /* if inputs are not 16-byte then use intermediate buffer */
6862 if (!IS_ALIGNED(dst_paddr, 16) ||
6863 !IS_ALIGNED(paddr, 16) ||
6864 !IS_ALIGNED(size, 16)) {
6865 tpage = (void *)alloc_page(GFP_KERNEL);
6869 dst_paddr = __sme_page_pa(tpage);
6872 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6877 offset = paddr & 15;
6878 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6879 page_address(tpage) + offset, size))
6890 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6891 unsigned long __user vaddr,
6892 unsigned long dst_paddr,
6893 unsigned long __user dst_vaddr,
6894 int size, int *error)
6896 struct page *src_tpage = NULL;
6897 struct page *dst_tpage = NULL;
6898 int ret, len = size;
6900 /* If source buffer is not aligned then use an intermediate buffer */
6901 if (!IS_ALIGNED(vaddr, 16)) {
6902 src_tpage = alloc_page(GFP_KERNEL);
6906 if (copy_from_user(page_address(src_tpage),
6907 (void __user *)(uintptr_t)vaddr, size)) {
6908 __free_page(src_tpage);
6912 paddr = __sme_page_pa(src_tpage);
6916 * If destination buffer or length is not aligned then do read-modify-write:
6917 * - decrypt destination in an intermediate buffer
6918 * - copy the source buffer in an intermediate buffer
6919 * - use the intermediate buffer as source buffer
6921 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6924 dst_tpage = alloc_page(GFP_KERNEL);
6930 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6931 __sme_page_pa(dst_tpage), size, error);
6936 * If source is kernel buffer then use memcpy() otherwise
6939 dst_offset = dst_paddr & 15;
6942 memcpy(page_address(dst_tpage) + dst_offset,
6943 page_address(src_tpage), size);
6945 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6946 (void __user *)(uintptr_t)vaddr, size)) {
6952 paddr = __sme_page_pa(dst_tpage);
6953 dst_paddr = round_down(dst_paddr, 16);
6954 len = round_up(size, 16);
6957 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6961 __free_page(src_tpage);
6963 __free_page(dst_tpage);
6967 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6969 unsigned long vaddr, vaddr_end, next_vaddr;
6970 unsigned long dst_vaddr;
6971 struct page **src_p, **dst_p;
6972 struct kvm_sev_dbg debug;
6977 if (!sev_guest(kvm))
6980 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6983 if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
6985 if (!debug.dst_uaddr)
6988 vaddr = debug.src_uaddr;
6990 vaddr_end = vaddr + size;
6991 dst_vaddr = debug.dst_uaddr;
6993 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6994 int len, s_off, d_off;
6996 /* lock userspace source and destination page */
6997 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
7001 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
7003 sev_unpin_memory(kvm, src_p, n);
7008 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
7009 * memory content (i.e it will write the same memory region with C=1).
7010 * It's possible that the cache may contain the data with C=0, i.e.,
7011 * unencrypted so invalidate it first.
7013 sev_clflush_pages(src_p, 1);
7014 sev_clflush_pages(dst_p, 1);
7017 * Since user buffer may not be page aligned, calculate the
7018 * offset within the page.
7020 s_off = vaddr & ~PAGE_MASK;
7021 d_off = dst_vaddr & ~PAGE_MASK;
7022 len = min_t(size_t, (PAGE_SIZE - s_off), size);
7025 ret = __sev_dbg_decrypt_user(kvm,
7026 __sme_page_pa(src_p[0]) + s_off,
7028 __sme_page_pa(dst_p[0]) + d_off,
7031 ret = __sev_dbg_encrypt_user(kvm,
7032 __sme_page_pa(src_p[0]) + s_off,
7034 __sme_page_pa(dst_p[0]) + d_off,
7038 sev_unpin_memory(kvm, src_p, n);
7039 sev_unpin_memory(kvm, dst_p, n);
7044 next_vaddr = vaddr + len;
7045 dst_vaddr = dst_vaddr + len;
7052 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
7054 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7055 struct sev_data_launch_secret *data;
7056 struct kvm_sev_launch_secret params;
7057 struct page **pages;
7062 if (!sev_guest(kvm))
7065 if (copy_from_user(¶ms, (void __user *)(uintptr_t)argp->data, sizeof(params)))
7068 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
7073 * The secret must be copied into contiguous memory region, lets verify
7074 * that userspace memory pages are contiguous before we issue command.
7076 if (get_num_contig_pages(0, pages, n) != n) {
7078 goto e_unpin_memory;
7082 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
7084 goto e_unpin_memory;
7086 offset = params.guest_uaddr & (PAGE_SIZE - 1);
7087 data->guest_address = __sme_page_pa(pages[0]) + offset;
7088 data->guest_len = params.guest_len;
7090 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
7092 ret = PTR_ERR(blob);
7096 data->trans_address = __psp_pa(blob);
7097 data->trans_len = params.trans_len;
7099 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
7104 data->hdr_address = __psp_pa(hdr);
7105 data->hdr_len = params.hdr_len;
7107 data->handle = sev->handle;
7108 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
7117 sev_unpin_memory(kvm, pages, n);
7121 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
7123 struct kvm_sev_cmd sev_cmd;
7126 if (!svm_sev_enabled())
7129 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
7132 mutex_lock(&kvm->lock);
7134 switch (sev_cmd.id) {
7136 r = sev_guest_init(kvm, &sev_cmd);
7138 case KVM_SEV_LAUNCH_START:
7139 r = sev_launch_start(kvm, &sev_cmd);
7141 case KVM_SEV_LAUNCH_UPDATE_DATA:
7142 r = sev_launch_update_data(kvm, &sev_cmd);
7144 case KVM_SEV_LAUNCH_MEASURE:
7145 r = sev_launch_measure(kvm, &sev_cmd);
7147 case KVM_SEV_LAUNCH_FINISH:
7148 r = sev_launch_finish(kvm, &sev_cmd);
7150 case KVM_SEV_GUEST_STATUS:
7151 r = sev_guest_status(kvm, &sev_cmd);
7153 case KVM_SEV_DBG_DECRYPT:
7154 r = sev_dbg_crypt(kvm, &sev_cmd, true);
7156 case KVM_SEV_DBG_ENCRYPT:
7157 r = sev_dbg_crypt(kvm, &sev_cmd, false);
7159 case KVM_SEV_LAUNCH_SECRET:
7160 r = sev_launch_secret(kvm, &sev_cmd);
7167 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
7171 mutex_unlock(&kvm->lock);
7175 static int svm_register_enc_region(struct kvm *kvm,
7176 struct kvm_enc_region *range)
7178 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7179 struct enc_region *region;
7182 if (!sev_guest(kvm))
7185 if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
7188 region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
7192 region->pages = sev_pin_memory(kvm, range->addr, range->size, ®ion->npages, 1);
7193 if (!region->pages) {
7199 * The guest may change the memory encryption attribute from C=0 -> C=1
7200 * or vice versa for this memory range. Lets make sure caches are
7201 * flushed to ensure that guest data gets written into memory with
7204 sev_clflush_pages(region->pages, region->npages);
7206 region->uaddr = range->addr;
7207 region->size = range->size;
7209 mutex_lock(&kvm->lock);
7210 list_add_tail(®ion->list, &sev->regions_list);
7211 mutex_unlock(&kvm->lock);
7220 static struct enc_region *
7221 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
7223 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7224 struct list_head *head = &sev->regions_list;
7225 struct enc_region *i;
7227 list_for_each_entry(i, head, list) {
7228 if (i->uaddr == range->addr &&
7229 i->size == range->size)
7237 static int svm_unregister_enc_region(struct kvm *kvm,
7238 struct kvm_enc_region *range)
7240 struct enc_region *region;
7243 mutex_lock(&kvm->lock);
7245 if (!sev_guest(kvm)) {
7250 region = find_enc_region(kvm, range);
7256 __unregister_enc_region_locked(kvm, region);
7258 mutex_unlock(&kvm->lock);
7262 mutex_unlock(&kvm->lock);
7266 static bool svm_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7268 unsigned long cr4 = kvm_read_cr4(vcpu);
7269 bool smep = cr4 & X86_CR4_SMEP;
7270 bool smap = cr4 & X86_CR4_SMAP;
7271 bool is_user = svm_get_cpl(vcpu) == 3;
7274 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
7277 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
7278 * possible that CPU microcode implementing DecodeAssist will fail
7279 * to read bytes of instruction which caused #NPF. In this case,
7280 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
7281 * return 0 instead of the correct guest instruction bytes.
7283 * This happens because CPU microcode reading instruction bytes
7284 * uses a special opcode which attempts to read data using CPL=0
7285 * priviledges. The microcode reads CS:RIP and if it hits a SMAP
7286 * fault, it gives up and returns no instruction bytes.
7289 * We reach here in case CPU supports DecodeAssist, raised #NPF and
7290 * returned 0 in GuestIntrBytes field of the VMCB.
7291 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
7292 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
7293 * in case vCPU CPL==3 (Because otherwise guest would have triggered
7294 * a SMEP fault instead of #NPF).
7295 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
7296 * As most guests enable SMAP if they have also enabled SMEP, use above
7297 * logic in order to attempt minimize false-positive of detecting errata
7298 * while still preserving all cases semantic correctness.
7301 * To determine what instruction the guest was executing, the hypervisor
7302 * will have to decode the instruction at the instruction pointer.
7304 * In non SEV guest, hypervisor will be able to read the guest
7305 * memory to decode the instruction pointer when insn_len is zero
7306 * so we return true to indicate that decoding is possible.
7308 * But in the SEV guest, the guest memory is encrypted with the
7309 * guest specific key and hypervisor will not be able to decode the
7310 * instruction pointer so we will not able to workaround it. Lets
7311 * print the error and request to kill the guest.
7313 if (smap && (!smep || is_user)) {
7314 if (!sev_guest(vcpu->kvm))
7317 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
7318 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7324 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7326 struct vcpu_svm *svm = to_svm(vcpu);
7329 * TODO: Last condition latch INIT signals on vCPU when
7330 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
7331 * To properly emulate the INIT intercept, SVM should implement
7332 * kvm_x86_ops->check_nested_events() and call nested_svm_vmexit()
7333 * there if an INIT signal is pending.
7335 return !gif_set(svm) ||
7336 (svm->vmcb->control.intercept & (1ULL << INTERCEPT_INIT));
7339 static bool svm_check_apicv_inhibit_reasons(ulong bit)
7341 ulong supported = BIT(APICV_INHIBIT_REASON_DISABLE) |
7342 BIT(APICV_INHIBIT_REASON_HYPERV) |
7343 BIT(APICV_INHIBIT_REASON_NESTED) |
7344 BIT(APICV_INHIBIT_REASON_IRQWIN) |
7345 BIT(APICV_INHIBIT_REASON_PIT_REINJ) |
7346 BIT(APICV_INHIBIT_REASON_X2APIC);
7348 return supported & BIT(bit);
7351 static void svm_pre_update_apicv_exec_ctrl(struct kvm *kvm, bool activate)
7353 avic_update_access_page(kvm, activate);
7356 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7357 .cpu_has_kvm_support = has_svm,
7358 .disabled_by_bios = is_disabled,
7359 .hardware_setup = svm_hardware_setup,
7360 .hardware_unsetup = svm_hardware_teardown,
7361 .check_processor_compatibility = svm_check_processor_compat,
7362 .hardware_enable = svm_hardware_enable,
7363 .hardware_disable = svm_hardware_disable,
7364 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
7365 .has_emulated_msr = svm_has_emulated_msr,
7367 .vcpu_create = svm_create_vcpu,
7368 .vcpu_free = svm_free_vcpu,
7369 .vcpu_reset = svm_vcpu_reset,
7371 .vm_size = sizeof(struct kvm_svm),
7372 .vm_init = svm_vm_init,
7373 .vm_destroy = svm_vm_destroy,
7375 .prepare_guest_switch = svm_prepare_guest_switch,
7376 .vcpu_load = svm_vcpu_load,
7377 .vcpu_put = svm_vcpu_put,
7378 .vcpu_blocking = svm_vcpu_blocking,
7379 .vcpu_unblocking = svm_vcpu_unblocking,
7381 .update_bp_intercept = update_bp_intercept,
7382 .get_msr_feature = svm_get_msr_feature,
7383 .get_msr = svm_get_msr,
7384 .set_msr = svm_set_msr,
7385 .get_segment_base = svm_get_segment_base,
7386 .get_segment = svm_get_segment,
7387 .set_segment = svm_set_segment,
7388 .get_cpl = svm_get_cpl,
7389 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
7390 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
7391 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
7392 .set_cr0 = svm_set_cr0,
7393 .set_cr4 = svm_set_cr4,
7394 .set_efer = svm_set_efer,
7395 .get_idt = svm_get_idt,
7396 .set_idt = svm_set_idt,
7397 .get_gdt = svm_get_gdt,
7398 .set_gdt = svm_set_gdt,
7399 .get_dr6 = svm_get_dr6,
7400 .set_dr6 = svm_set_dr6,
7401 .set_dr7 = svm_set_dr7,
7402 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
7403 .cache_reg = svm_cache_reg,
7404 .get_rflags = svm_get_rflags,
7405 .set_rflags = svm_set_rflags,
7407 .tlb_flush = svm_flush_tlb,
7408 .tlb_flush_gva = svm_flush_tlb_gva,
7410 .run = svm_vcpu_run,
7411 .handle_exit = handle_exit,
7412 .skip_emulated_instruction = skip_emulated_instruction,
7413 .update_emulated_instruction = NULL,
7414 .set_interrupt_shadow = svm_set_interrupt_shadow,
7415 .get_interrupt_shadow = svm_get_interrupt_shadow,
7416 .patch_hypercall = svm_patch_hypercall,
7417 .set_irq = svm_set_irq,
7418 .set_nmi = svm_inject_nmi,
7419 .queue_exception = svm_queue_exception,
7420 .cancel_injection = svm_cancel_injection,
7421 .interrupt_allowed = svm_interrupt_allowed,
7422 .nmi_allowed = svm_nmi_allowed,
7423 .get_nmi_mask = svm_get_nmi_mask,
7424 .set_nmi_mask = svm_set_nmi_mask,
7425 .enable_nmi_window = enable_nmi_window,
7426 .enable_irq_window = enable_irq_window,
7427 .update_cr8_intercept = update_cr8_intercept,
7428 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
7429 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
7430 .check_apicv_inhibit_reasons = svm_check_apicv_inhibit_reasons,
7431 .pre_update_apicv_exec_ctrl = svm_pre_update_apicv_exec_ctrl,
7432 .load_eoi_exitmap = svm_load_eoi_exitmap,
7433 .hwapic_irr_update = svm_hwapic_irr_update,
7434 .hwapic_isr_update = svm_hwapic_isr_update,
7435 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
7436 .apicv_post_state_restore = avic_post_state_restore,
7438 .set_tss_addr = svm_set_tss_addr,
7439 .set_identity_map_addr = svm_set_identity_map_addr,
7440 .get_tdp_level = get_npt_level,
7441 .get_mt_mask = svm_get_mt_mask,
7443 .get_exit_info = svm_get_exit_info,
7445 .cpuid_update = svm_cpuid_update,
7447 .has_wbinvd_exit = svm_has_wbinvd_exit,
7449 .read_l1_tsc_offset = svm_read_l1_tsc_offset,
7450 .write_l1_tsc_offset = svm_write_l1_tsc_offset,
7452 .load_mmu_pgd = svm_load_mmu_pgd,
7454 .check_intercept = svm_check_intercept,
7455 .handle_exit_irqoff = svm_handle_exit_irqoff,
7457 .request_immediate_exit = __kvm_request_immediate_exit,
7459 .sched_in = svm_sched_in,
7461 .pmu_ops = &amd_pmu_ops,
7462 .deliver_posted_interrupt = svm_deliver_avic_intr,
7463 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
7464 .update_pi_irte = svm_update_pi_irte,
7465 .setup_mce = svm_setup_mce,
7467 .smi_allowed = svm_smi_allowed,
7468 .pre_enter_smm = svm_pre_enter_smm,
7469 .pre_leave_smm = svm_pre_leave_smm,
7470 .enable_smi_window = enable_smi_window,
7472 .mem_enc_op = svm_mem_enc_op,
7473 .mem_enc_reg_region = svm_register_enc_region,
7474 .mem_enc_unreg_region = svm_unregister_enc_region,
7476 .nested_enable_evmcs = NULL,
7477 .nested_get_evmcs_version = NULL,
7479 .need_emulation_on_page_fault = svm_need_emulation_on_page_fault,
7481 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
7483 .check_nested_events = svm_check_nested_events,
7486 static int __init svm_init(void)
7488 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7489 __alignof__(struct vcpu_svm), THIS_MODULE);
7492 static void __exit svm_exit(void)
7497 module_init(svm_init)
7498 module_exit(svm_exit)