2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
45 #include <asm/virtext.h>
47 #include <asm/fpu/internal.h>
48 #include <asm/perf_event.h>
49 #include <asm/debugreg.h>
50 #include <asm/kexec.h>
52 #include <asm/irq_remapping.h>
53 #include <asm/microcode.h>
54 #include <asm/spec-ctrl.h>
59 #define __ex(x) __kvm_handle_fault_on_reboot(x)
60 #define __ex_clear(x, reg) \
61 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
63 MODULE_AUTHOR("Qumranet");
64 MODULE_LICENSE("GPL");
66 static const struct x86_cpu_id vmx_cpu_id[] = {
67 X86_FEATURE_MATCH(X86_FEATURE_VMX),
70 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
72 static bool __read_mostly enable_vpid = 1;
73 module_param_named(vpid, enable_vpid, bool, 0444);
75 static bool __read_mostly flexpriority_enabled = 1;
76 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
78 static bool __read_mostly enable_ept = 1;
79 module_param_named(ept, enable_ept, bool, S_IRUGO);
81 static bool __read_mostly enable_unrestricted_guest = 1;
82 module_param_named(unrestricted_guest,
83 enable_unrestricted_guest, bool, S_IRUGO);
85 static bool __read_mostly enable_ept_ad_bits = 1;
86 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
88 static bool __read_mostly emulate_invalid_guest_state = true;
89 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
91 static bool __read_mostly vmm_exclusive = 1;
92 module_param(vmm_exclusive, bool, S_IRUGO);
94 static bool __read_mostly fasteoi = 1;
95 module_param(fasteoi, bool, S_IRUGO);
97 static bool __read_mostly enable_apicv = 1;
98 module_param(enable_apicv, bool, S_IRUGO);
100 static bool __read_mostly enable_shadow_vmcs = 1;
101 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
103 * If nested=1, nested virtualization is supported, i.e., guests may use
104 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
105 * use VMX instructions.
107 static bool __read_mostly nested = 0;
108 module_param(nested, bool, S_IRUGO);
110 static u64 __read_mostly host_xss;
112 static bool __read_mostly enable_pml = 1;
113 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 #define MSR_TYPE_RW 3
119 #define MSR_BITMAP_MODE_X2APIC 1
120 #define MSR_BITMAP_MODE_X2APIC_APICV 2
121 #define MSR_BITMAP_MODE_LM 4
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
134 #define KVM_VM_CR0_ALWAYS_ON \
135 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
136 #define KVM_CR4_GUEST_OWNED_BITS \
137 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
138 | X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
140 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
141 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
143 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
145 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
147 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
148 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
149 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
150 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
151 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
154 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
155 * ple_gap: upper bound on the amount of time between two successive
156 * executions of PAUSE in a loop. Also indicate if ple enabled.
157 * According to test, this time is usually smaller than 128 cycles.
158 * ple_window: upper bound on the amount of time a guest is allowed to execute
159 * in a PAUSE loop. Tests indicate that most spinlocks are held for
160 * less than 2^12 cycles
161 * Time is measured based on a counter that runs at the same rate as the TSC,
162 * refer SDM volume 3b section 21.6.13 & 22.1.3.
164 #define KVM_VMX_DEFAULT_PLE_GAP 128
165 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
166 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
167 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
168 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
169 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
171 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
172 module_param(ple_gap, int, S_IRUGO);
174 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
175 module_param(ple_window, int, S_IRUGO);
177 /* Default doubles per-vcpu window every exit. */
178 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
179 module_param(ple_window_grow, int, S_IRUGO);
181 /* Default resets per-vcpu window every exit to ple_window. */
182 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
183 module_param(ple_window_shrink, int, S_IRUGO);
185 /* Default is to compute the maximum so we can never overflow. */
186 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
187 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
188 module_param(ple_window_max, int, S_IRUGO);
190 extern const ulong vmx_return;
192 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
193 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
194 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
196 /* Storage for pre module init parameter parsing */
197 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
199 static const struct {
201 enum vmx_l1d_flush_state cmd;
202 } vmentry_l1d_param[] = {
203 {"auto", VMENTER_L1D_FLUSH_AUTO},
204 {"never", VMENTER_L1D_FLUSH_NEVER},
205 {"cond", VMENTER_L1D_FLUSH_COND},
206 {"always", VMENTER_L1D_FLUSH_ALWAYS},
209 #define L1D_CACHE_ORDER 4
210 static void *vmx_l1d_flush_pages;
212 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
218 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
222 /* If set to auto use the default l1tf mitigation method */
223 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
224 switch (l1tf_mitigation) {
225 case L1TF_MITIGATION_OFF:
226 l1tf = VMENTER_L1D_FLUSH_NEVER;
228 case L1TF_MITIGATION_FLUSH_NOWARN:
229 case L1TF_MITIGATION_FLUSH:
230 case L1TF_MITIGATION_FLUSH_NOSMT:
231 l1tf = VMENTER_L1D_FLUSH_COND;
233 case L1TF_MITIGATION_FULL:
234 case L1TF_MITIGATION_FULL_FORCE:
235 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
238 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
239 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
242 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
243 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
244 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
247 vmx_l1d_flush_pages = page_address(page);
250 * Initialize each page with a different pattern in
251 * order to protect against KSM in the nested
252 * virtualization case.
254 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
255 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
260 l1tf_vmx_mitigation = l1tf;
262 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
263 static_branch_enable(&vmx_l1d_should_flush);
265 static_branch_disable(&vmx_l1d_should_flush);
267 if (l1tf == VMENTER_L1D_FLUSH_COND)
268 static_branch_enable(&vmx_l1d_flush_cond);
270 static_branch_disable(&vmx_l1d_flush_cond);
274 static int vmentry_l1d_flush_parse(const char *s)
279 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
280 if (sysfs_streq(s, vmentry_l1d_param[i].option))
281 return vmentry_l1d_param[i].cmd;
287 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
291 if (!boot_cpu_has(X86_BUG_L1TF))
294 l1tf = vmentry_l1d_flush_parse(s);
299 * Has vmx_init() run already? If not then this is the pre init
300 * parameter parsing. In that case just store the value and let
301 * vmx_init() do the proper setup after enable_ept has been
304 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
305 vmentry_l1d_flush_param = l1tf;
309 mutex_lock(&vmx_l1d_flush_mutex);
310 ret = vmx_setup_l1d_flush(l1tf);
311 mutex_unlock(&vmx_l1d_flush_mutex);
315 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
317 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
320 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
321 .set = vmentry_l1d_flush_set,
322 .get = vmentry_l1d_flush_get,
324 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
326 #define NR_AUTOLOAD_MSRS 8
335 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
336 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
337 * loaded on this CPU (so we can clear them if the CPU goes down).
341 struct vmcs *shadow_vmcs;
344 unsigned long *msr_bitmap;
345 struct list_head loaded_vmcss_on_cpu_link;
348 struct shared_msr_entry {
355 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
356 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
357 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
358 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
359 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
360 * More than one of these structures may exist, if L1 runs multiple L2 guests.
361 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
362 * underlying hardware which will be used to run L2.
363 * This structure is packed to ensure that its layout is identical across
364 * machines (necessary for live migration).
365 * If there are changes in this struct, VMCS12_REVISION must be changed.
367 typedef u64 natural_width;
368 struct __packed vmcs12 {
369 /* According to the Intel spec, a VMCS region must start with the
370 * following two fields. Then follow implementation-specific data.
375 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
376 u32 padding[7]; /* room for future expansion */
381 u64 vm_exit_msr_store_addr;
382 u64 vm_exit_msr_load_addr;
383 u64 vm_entry_msr_load_addr;
385 u64 virtual_apic_page_addr;
386 u64 apic_access_addr;
387 u64 posted_intr_desc_addr;
389 u64 eoi_exit_bitmap0;
390 u64 eoi_exit_bitmap1;
391 u64 eoi_exit_bitmap2;
392 u64 eoi_exit_bitmap3;
394 u64 guest_physical_address;
395 u64 vmcs_link_pointer;
396 u64 guest_ia32_debugctl;
399 u64 guest_ia32_perf_global_ctrl;
407 u64 host_ia32_perf_global_ctrl;
408 u64 padding64[8]; /* room for future expansion */
410 * To allow migration of L1 (complete with its L2 guests) between
411 * machines of different natural widths (32 or 64 bit), we cannot have
412 * unsigned long fields with no explict size. We use u64 (aliased
413 * natural_width) instead. Luckily, x86 is little-endian.
415 natural_width cr0_guest_host_mask;
416 natural_width cr4_guest_host_mask;
417 natural_width cr0_read_shadow;
418 natural_width cr4_read_shadow;
419 natural_width cr3_target_value0;
420 natural_width cr3_target_value1;
421 natural_width cr3_target_value2;
422 natural_width cr3_target_value3;
423 natural_width exit_qualification;
424 natural_width guest_linear_address;
425 natural_width guest_cr0;
426 natural_width guest_cr3;
427 natural_width guest_cr4;
428 natural_width guest_es_base;
429 natural_width guest_cs_base;
430 natural_width guest_ss_base;
431 natural_width guest_ds_base;
432 natural_width guest_fs_base;
433 natural_width guest_gs_base;
434 natural_width guest_ldtr_base;
435 natural_width guest_tr_base;
436 natural_width guest_gdtr_base;
437 natural_width guest_idtr_base;
438 natural_width guest_dr7;
439 natural_width guest_rsp;
440 natural_width guest_rip;
441 natural_width guest_rflags;
442 natural_width guest_pending_dbg_exceptions;
443 natural_width guest_sysenter_esp;
444 natural_width guest_sysenter_eip;
445 natural_width host_cr0;
446 natural_width host_cr3;
447 natural_width host_cr4;
448 natural_width host_fs_base;
449 natural_width host_gs_base;
450 natural_width host_tr_base;
451 natural_width host_gdtr_base;
452 natural_width host_idtr_base;
453 natural_width host_ia32_sysenter_esp;
454 natural_width host_ia32_sysenter_eip;
455 natural_width host_rsp;
456 natural_width host_rip;
457 natural_width paddingl[8]; /* room for future expansion */
458 u32 pin_based_vm_exec_control;
459 u32 cpu_based_vm_exec_control;
460 u32 exception_bitmap;
461 u32 page_fault_error_code_mask;
462 u32 page_fault_error_code_match;
463 u32 cr3_target_count;
464 u32 vm_exit_controls;
465 u32 vm_exit_msr_store_count;
466 u32 vm_exit_msr_load_count;
467 u32 vm_entry_controls;
468 u32 vm_entry_msr_load_count;
469 u32 vm_entry_intr_info_field;
470 u32 vm_entry_exception_error_code;
471 u32 vm_entry_instruction_len;
473 u32 secondary_vm_exec_control;
474 u32 vm_instruction_error;
476 u32 vm_exit_intr_info;
477 u32 vm_exit_intr_error_code;
478 u32 idt_vectoring_info_field;
479 u32 idt_vectoring_error_code;
480 u32 vm_exit_instruction_len;
481 u32 vmx_instruction_info;
488 u32 guest_ldtr_limit;
490 u32 guest_gdtr_limit;
491 u32 guest_idtr_limit;
492 u32 guest_es_ar_bytes;
493 u32 guest_cs_ar_bytes;
494 u32 guest_ss_ar_bytes;
495 u32 guest_ds_ar_bytes;
496 u32 guest_fs_ar_bytes;
497 u32 guest_gs_ar_bytes;
498 u32 guest_ldtr_ar_bytes;
499 u32 guest_tr_ar_bytes;
500 u32 guest_interruptibility_info;
501 u32 guest_activity_state;
502 u32 guest_sysenter_cs;
503 u32 host_ia32_sysenter_cs;
504 u32 vmx_preemption_timer_value;
505 u32 padding32[7]; /* room for future expansion */
506 u16 virtual_processor_id;
508 u16 guest_es_selector;
509 u16 guest_cs_selector;
510 u16 guest_ss_selector;
511 u16 guest_ds_selector;
512 u16 guest_fs_selector;
513 u16 guest_gs_selector;
514 u16 guest_ldtr_selector;
515 u16 guest_tr_selector;
516 u16 guest_intr_status;
517 u16 host_es_selector;
518 u16 host_cs_selector;
519 u16 host_ss_selector;
520 u16 host_ds_selector;
521 u16 host_fs_selector;
522 u16 host_gs_selector;
523 u16 host_tr_selector;
527 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
528 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
529 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
531 #define VMCS12_REVISION 0x11e57ed0
534 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
535 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
536 * current implementation, 4K are reserved to avoid future complications.
538 #define VMCS12_SIZE 0x1000
541 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
542 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
545 /* Has the level1 guest done vmxon? */
549 /* The guest-physical address of the current VMCS L1 keeps for L2 */
551 /* The host-usable pointer to the above */
552 struct page *current_vmcs12_page;
553 struct vmcs12 *current_vmcs12;
555 * Cache of the guest's VMCS, existing outside of guest memory.
556 * Loaded from guest memory during VMPTRLD. Flushed to guest
557 * memory during VMXOFF, VMCLEAR, VMPTRLD.
559 struct vmcs12 *cached_vmcs12;
561 * Indicates if the shadow vmcs must be updated with the
562 * data hold by vmcs12
564 bool sync_shadow_vmcs;
566 bool change_vmcs01_virtual_x2apic_mode;
567 /* L2 must run next, and mustn't decide to exit to L1. */
568 bool nested_run_pending;
570 struct loaded_vmcs vmcs02;
573 * Guest pages referred to in the vmcs02 with host-physical
574 * pointers, so we must keep them pinned while L2 runs.
576 struct page *apic_access_page;
577 struct page *virtual_apic_page;
578 struct page *pi_desc_page;
579 struct pi_desc *pi_desc;
583 struct hrtimer preemption_timer;
584 bool preemption_timer_expired;
586 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
592 u32 nested_vmx_procbased_ctls_low;
593 u32 nested_vmx_procbased_ctls_high;
594 u32 nested_vmx_true_procbased_ctls_low;
595 u32 nested_vmx_secondary_ctls_low;
596 u32 nested_vmx_secondary_ctls_high;
597 u32 nested_vmx_pinbased_ctls_low;
598 u32 nested_vmx_pinbased_ctls_high;
599 u32 nested_vmx_exit_ctls_low;
600 u32 nested_vmx_exit_ctls_high;
601 u32 nested_vmx_true_exit_ctls_low;
602 u32 nested_vmx_entry_ctls_low;
603 u32 nested_vmx_entry_ctls_high;
604 u32 nested_vmx_true_entry_ctls_low;
605 u32 nested_vmx_misc_low;
606 u32 nested_vmx_misc_high;
607 u32 nested_vmx_ept_caps;
608 u32 nested_vmx_vpid_caps;
611 #define POSTED_INTR_ON 0
612 #define POSTED_INTR_SN 1
614 /* Posted-Interrupt Descriptor */
616 u32 pir[8]; /* Posted interrupt requested */
619 /* bit 256 - Outstanding Notification */
621 /* bit 257 - Suppress Notification */
623 /* bit 271:258 - Reserved */
625 /* bit 279:272 - Notification Vector */
627 /* bit 287:280 - Reserved */
629 /* bit 319:288 - Notification Destination */
637 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
639 return test_and_set_bit(POSTED_INTR_ON,
640 (unsigned long *)&pi_desc->control);
643 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
645 return test_and_clear_bit(POSTED_INTR_ON,
646 (unsigned long *)&pi_desc->control);
649 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
651 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
654 static inline void pi_clear_sn(struct pi_desc *pi_desc)
656 return clear_bit(POSTED_INTR_SN,
657 (unsigned long *)&pi_desc->control);
660 static inline void pi_set_sn(struct pi_desc *pi_desc)
662 return set_bit(POSTED_INTR_SN,
663 (unsigned long *)&pi_desc->control);
666 static inline int pi_test_on(struct pi_desc *pi_desc)
668 return test_bit(POSTED_INTR_ON,
669 (unsigned long *)&pi_desc->control);
672 static inline int pi_test_sn(struct pi_desc *pi_desc)
674 return test_bit(POSTED_INTR_SN,
675 (unsigned long *)&pi_desc->control);
680 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
684 struct kvm_vcpu vcpu;
685 unsigned long host_rsp;
687 bool nmi_known_unmasked;
690 u32 idt_vectoring_info;
692 struct shared_msr_entry *guest_msrs;
695 unsigned long host_idt_base;
697 u64 msr_host_kernel_gs_base;
698 u64 msr_guest_kernel_gs_base;
701 u64 arch_capabilities;
704 u32 vm_entry_controls_shadow;
705 u32 vm_exit_controls_shadow;
707 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
708 * non-nested (L1) guest, it always points to vmcs01. For a nested
709 * guest (L2), it points to a different VMCS.
711 struct loaded_vmcs vmcs01;
712 struct loaded_vmcs *loaded_vmcs;
713 bool __launched; /* temporary, used in vmx_vcpu_run */
714 struct msr_autoload {
715 struct vmx_msrs guest;
716 struct vmx_msrs host;
720 u16 fs_sel, gs_sel, ldt_sel;
724 int gs_ldt_reload_needed;
725 int fs_reload_needed;
726 u64 msr_host_bndcfgs;
727 unsigned long vmcs_host_cr4; /* May not match real cr4 */
732 struct kvm_segment segs[8];
735 u32 bitmask; /* 4 bits per segment (1 bit per field) */
736 struct kvm_save_segment {
744 bool emulation_required;
746 /* Support for vnmi-less CPUs */
747 int soft_vnmi_blocked;
749 s64 vnmi_blocked_time;
752 /* Posted interrupt descriptor */
753 struct pi_desc pi_desc;
755 /* Support for a guest hypervisor (nested VMX) */
756 struct nested_vmx nested;
758 /* Dynamic PLE window. */
760 bool ple_window_dirty;
762 /* Support for PML */
763 #define PML_ENTITY_NUM 512
766 /* apic deadline value in host tsc */
769 u64 current_tsc_ratio;
771 bool guest_pkru_valid;
776 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
777 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
778 * in msr_ia32_feature_control_valid_bits.
780 u64 msr_ia32_feature_control;
781 u64 msr_ia32_feature_control_valid_bits;
784 enum segment_cache_field {
793 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
795 return container_of(vcpu, struct vcpu_vmx, vcpu);
798 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
800 return &(to_vmx(vcpu)->pi_desc);
803 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
804 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
805 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
806 [number##_HIGH] = VMCS12_OFFSET(name)+4
809 static unsigned long shadow_read_only_fields[] = {
811 * We do NOT shadow fields that are modified when L0
812 * traps and emulates any vmx instruction (e.g. VMPTRLD,
813 * VMXON...) executed by L1.
814 * For example, VM_INSTRUCTION_ERROR is read
815 * by L1 if a vmx instruction fails (part of the error path).
816 * Note the code assumes this logic. If for some reason
817 * we start shadowing these fields then we need to
818 * force a shadow sync when L0 emulates vmx instructions
819 * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
820 * by nested_vmx_failValid)
824 VM_EXIT_INSTRUCTION_LEN,
825 IDT_VECTORING_INFO_FIELD,
826 IDT_VECTORING_ERROR_CODE,
827 VM_EXIT_INTR_ERROR_CODE,
829 GUEST_LINEAR_ADDRESS,
830 GUEST_PHYSICAL_ADDRESS
832 static int max_shadow_read_only_fields =
833 ARRAY_SIZE(shadow_read_only_fields);
835 static unsigned long shadow_read_write_fields[] = {
842 GUEST_INTERRUPTIBILITY_INFO,
855 CPU_BASED_VM_EXEC_CONTROL,
856 VM_ENTRY_EXCEPTION_ERROR_CODE,
857 VM_ENTRY_INTR_INFO_FIELD,
858 VM_ENTRY_INSTRUCTION_LEN,
859 VM_ENTRY_EXCEPTION_ERROR_CODE,
865 static int max_shadow_read_write_fields =
866 ARRAY_SIZE(shadow_read_write_fields);
868 static const unsigned short vmcs_field_to_offset_table[] = {
869 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
870 FIELD(POSTED_INTR_NV, posted_intr_nv),
871 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
872 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
873 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
874 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
875 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
876 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
877 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
878 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
879 FIELD(GUEST_INTR_STATUS, guest_intr_status),
880 FIELD(HOST_ES_SELECTOR, host_es_selector),
881 FIELD(HOST_CS_SELECTOR, host_cs_selector),
882 FIELD(HOST_SS_SELECTOR, host_ss_selector),
883 FIELD(HOST_DS_SELECTOR, host_ds_selector),
884 FIELD(HOST_FS_SELECTOR, host_fs_selector),
885 FIELD(HOST_GS_SELECTOR, host_gs_selector),
886 FIELD(HOST_TR_SELECTOR, host_tr_selector),
887 FIELD64(IO_BITMAP_A, io_bitmap_a),
888 FIELD64(IO_BITMAP_B, io_bitmap_b),
889 FIELD64(MSR_BITMAP, msr_bitmap),
890 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
891 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
892 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
893 FIELD64(TSC_OFFSET, tsc_offset),
894 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
895 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
896 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
897 FIELD64(EPT_POINTER, ept_pointer),
898 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
899 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
900 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
901 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
902 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
903 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
904 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
905 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
906 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
907 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
908 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
909 FIELD64(GUEST_PDPTR0, guest_pdptr0),
910 FIELD64(GUEST_PDPTR1, guest_pdptr1),
911 FIELD64(GUEST_PDPTR2, guest_pdptr2),
912 FIELD64(GUEST_PDPTR3, guest_pdptr3),
913 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
914 FIELD64(HOST_IA32_PAT, host_ia32_pat),
915 FIELD64(HOST_IA32_EFER, host_ia32_efer),
916 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
917 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
918 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
919 FIELD(EXCEPTION_BITMAP, exception_bitmap),
920 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
921 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
922 FIELD(CR3_TARGET_COUNT, cr3_target_count),
923 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
924 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
925 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
926 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
927 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
928 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
929 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
930 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
931 FIELD(TPR_THRESHOLD, tpr_threshold),
932 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
933 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
934 FIELD(VM_EXIT_REASON, vm_exit_reason),
935 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
936 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
937 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
938 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
939 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
940 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
941 FIELD(GUEST_ES_LIMIT, guest_es_limit),
942 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
943 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
944 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
945 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
946 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
947 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
948 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
949 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
950 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
951 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
952 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
953 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
954 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
955 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
956 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
957 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
958 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
959 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
960 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
961 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
962 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
963 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
964 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
965 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
966 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
967 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
968 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
969 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
970 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
971 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
972 FIELD(EXIT_QUALIFICATION, exit_qualification),
973 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
974 FIELD(GUEST_CR0, guest_cr0),
975 FIELD(GUEST_CR3, guest_cr3),
976 FIELD(GUEST_CR4, guest_cr4),
977 FIELD(GUEST_ES_BASE, guest_es_base),
978 FIELD(GUEST_CS_BASE, guest_cs_base),
979 FIELD(GUEST_SS_BASE, guest_ss_base),
980 FIELD(GUEST_DS_BASE, guest_ds_base),
981 FIELD(GUEST_FS_BASE, guest_fs_base),
982 FIELD(GUEST_GS_BASE, guest_gs_base),
983 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
984 FIELD(GUEST_TR_BASE, guest_tr_base),
985 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
986 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
987 FIELD(GUEST_DR7, guest_dr7),
988 FIELD(GUEST_RSP, guest_rsp),
989 FIELD(GUEST_RIP, guest_rip),
990 FIELD(GUEST_RFLAGS, guest_rflags),
991 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
992 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
993 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
994 FIELD(HOST_CR0, host_cr0),
995 FIELD(HOST_CR3, host_cr3),
996 FIELD(HOST_CR4, host_cr4),
997 FIELD(HOST_FS_BASE, host_fs_base),
998 FIELD(HOST_GS_BASE, host_gs_base),
999 FIELD(HOST_TR_BASE, host_tr_base),
1000 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1001 FIELD(HOST_IDTR_BASE, host_idtr_base),
1002 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1003 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1004 FIELD(HOST_RSP, host_rsp),
1005 FIELD(HOST_RIP, host_rip),
1008 static inline short vmcs_field_to_offset(unsigned long field)
1010 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1011 unsigned short offset;
1013 BUILD_BUG_ON(size > SHRT_MAX);
1017 field = array_index_nospec(field, size);
1018 offset = vmcs_field_to_offset_table[field];
1024 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1026 return to_vmx(vcpu)->nested.cached_vmcs12;
1029 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
1031 struct page *page = kvm_vcpu_gfn_to_page(vcpu, addr >> PAGE_SHIFT);
1032 if (is_error_page(page))
1038 static void nested_release_page(struct page *page)
1040 kvm_release_page_dirty(page);
1043 static void nested_release_page_clean(struct page *page)
1045 kvm_release_page_clean(page);
1048 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1049 static u64 construct_eptp(unsigned long root_hpa);
1050 static void kvm_cpu_vmxon(u64 addr);
1051 static void kvm_cpu_vmxoff(void);
1052 static bool vmx_xsaves_supported(void);
1053 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
1054 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1055 struct kvm_segment *var, int seg);
1056 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1057 struct kvm_segment *var, int seg);
1058 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1059 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1060 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
1061 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1062 static int alloc_identity_pagetable(struct kvm *kvm);
1063 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1064 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1067 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1068 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1070 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1071 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1073 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1074 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
1077 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1078 * can find which vCPU should be waken up.
1080 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1081 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1083 static unsigned long *vmx_io_bitmap_a;
1084 static unsigned long *vmx_io_bitmap_b;
1085 static unsigned long *vmx_vmread_bitmap;
1086 static unsigned long *vmx_vmwrite_bitmap;
1088 static bool cpu_has_load_ia32_efer;
1089 static bool cpu_has_load_perf_global_ctrl;
1091 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1092 static DEFINE_SPINLOCK(vmx_vpid_lock);
1094 static struct vmcs_config {
1099 u32 pin_based_exec_ctrl;
1100 u32 cpu_based_exec_ctrl;
1101 u32 cpu_based_2nd_exec_ctrl;
1106 static struct vmx_capability {
1111 #define VMX_SEGMENT_FIELD(seg) \
1112 [VCPU_SREG_##seg] = { \
1113 .selector = GUEST_##seg##_SELECTOR, \
1114 .base = GUEST_##seg##_BASE, \
1115 .limit = GUEST_##seg##_LIMIT, \
1116 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1119 static const struct kvm_vmx_segment_field {
1124 } kvm_vmx_segment_fields[] = {
1125 VMX_SEGMENT_FIELD(CS),
1126 VMX_SEGMENT_FIELD(DS),
1127 VMX_SEGMENT_FIELD(ES),
1128 VMX_SEGMENT_FIELD(FS),
1129 VMX_SEGMENT_FIELD(GS),
1130 VMX_SEGMENT_FIELD(SS),
1131 VMX_SEGMENT_FIELD(TR),
1132 VMX_SEGMENT_FIELD(LDTR),
1135 static u64 host_efer;
1137 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1140 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1141 * away by decrementing the array size.
1143 static const u32 vmx_msr_index[] = {
1144 #ifdef CONFIG_X86_64
1145 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1147 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1150 static inline bool is_exception_n(u32 intr_info, u8 vector)
1152 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1153 INTR_INFO_VALID_MASK)) ==
1154 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1157 static inline bool is_debug(u32 intr_info)
1159 return is_exception_n(intr_info, DB_VECTOR);
1162 static inline bool is_breakpoint(u32 intr_info)
1164 return is_exception_n(intr_info, BP_VECTOR);
1167 static inline bool is_page_fault(u32 intr_info)
1169 return is_exception_n(intr_info, PF_VECTOR);
1172 static inline bool is_no_device(u32 intr_info)
1174 return is_exception_n(intr_info, NM_VECTOR);
1177 static inline bool is_invalid_opcode(u32 intr_info)
1179 return is_exception_n(intr_info, UD_VECTOR);
1182 static inline bool is_external_interrupt(u32 intr_info)
1184 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1185 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1188 static inline bool is_machine_check(u32 intr_info)
1190 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1191 INTR_INFO_VALID_MASK)) ==
1192 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1195 /* Undocumented: icebp/int1 */
1196 static inline bool is_icebp(u32 intr_info)
1198 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1199 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1202 static inline bool cpu_has_vmx_msr_bitmap(void)
1204 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1207 static inline bool cpu_has_vmx_tpr_shadow(void)
1209 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1212 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1214 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1217 static inline bool cpu_has_secondary_exec_ctrls(void)
1219 return vmcs_config.cpu_based_exec_ctrl &
1220 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1223 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1225 return vmcs_config.cpu_based_2nd_exec_ctrl &
1226 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1229 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1231 return vmcs_config.cpu_based_2nd_exec_ctrl &
1232 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1235 static inline bool cpu_has_vmx_apic_register_virt(void)
1237 return vmcs_config.cpu_based_2nd_exec_ctrl &
1238 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1241 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1243 return vmcs_config.cpu_based_2nd_exec_ctrl &
1244 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1248 * Comment's format: document - errata name - stepping - processor name.
1250 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1252 static u32 vmx_preemption_cpu_tfms[] = {
1253 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1255 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1256 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1257 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1259 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1261 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1262 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1264 * 320767.pdf - AAP86 - B1 -
1265 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1268 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1270 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1272 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1274 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1275 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1276 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1280 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1282 u32 eax = cpuid_eax(0x00000001), i;
1284 /* Clear the reserved bits */
1285 eax &= ~(0x3U << 14 | 0xfU << 28);
1286 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1287 if (eax == vmx_preemption_cpu_tfms[i])
1293 static inline bool cpu_has_vmx_preemption_timer(void)
1295 return vmcs_config.pin_based_exec_ctrl &
1296 PIN_BASED_VMX_PREEMPTION_TIMER;
1299 static inline bool cpu_has_vmx_posted_intr(void)
1301 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1302 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1305 static inline bool cpu_has_vmx_apicv(void)
1307 return cpu_has_vmx_apic_register_virt() &&
1308 cpu_has_vmx_virtual_intr_delivery() &&
1309 cpu_has_vmx_posted_intr();
1312 static inline bool cpu_has_vmx_flexpriority(void)
1314 return cpu_has_vmx_tpr_shadow() &&
1315 cpu_has_vmx_virtualize_apic_accesses();
1318 static inline bool cpu_has_vmx_ept_execute_only(void)
1320 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1323 static inline bool cpu_has_vmx_ept_2m_page(void)
1325 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1328 static inline bool cpu_has_vmx_ept_1g_page(void)
1330 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1333 static inline bool cpu_has_vmx_ept_4levels(void)
1335 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1338 static inline bool cpu_has_vmx_ept_ad_bits(void)
1340 return vmx_capability.ept & VMX_EPT_AD_BIT;
1343 static inline bool cpu_has_vmx_invept_context(void)
1345 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1348 static inline bool cpu_has_vmx_invept_global(void)
1350 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1353 static inline bool cpu_has_vmx_invvpid_single(void)
1355 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1358 static inline bool cpu_has_vmx_invvpid_global(void)
1360 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1363 static inline bool cpu_has_vmx_invvpid(void)
1365 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1368 static inline bool cpu_has_vmx_ept(void)
1370 return vmcs_config.cpu_based_2nd_exec_ctrl &
1371 SECONDARY_EXEC_ENABLE_EPT;
1374 static inline bool cpu_has_vmx_unrestricted_guest(void)
1376 return vmcs_config.cpu_based_2nd_exec_ctrl &
1377 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1380 static inline bool cpu_has_vmx_ple(void)
1382 return vmcs_config.cpu_based_2nd_exec_ctrl &
1383 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1386 static inline bool cpu_has_vmx_basic_inout(void)
1388 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1391 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1393 return flexpriority_enabled && lapic_in_kernel(vcpu);
1396 static inline bool cpu_has_vmx_vpid(void)
1398 return vmcs_config.cpu_based_2nd_exec_ctrl &
1399 SECONDARY_EXEC_ENABLE_VPID;
1402 static inline bool cpu_has_vmx_rdtscp(void)
1404 return vmcs_config.cpu_based_2nd_exec_ctrl &
1405 SECONDARY_EXEC_RDTSCP;
1408 static inline bool cpu_has_vmx_invpcid(void)
1410 return vmcs_config.cpu_based_2nd_exec_ctrl &
1411 SECONDARY_EXEC_ENABLE_INVPCID;
1414 static inline bool cpu_has_virtual_nmis(void)
1416 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1419 static inline bool cpu_has_vmx_wbinvd_exit(void)
1421 return vmcs_config.cpu_based_2nd_exec_ctrl &
1422 SECONDARY_EXEC_WBINVD_EXITING;
1425 static inline bool cpu_has_vmx_shadow_vmcs(void)
1428 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1429 /* check if the cpu supports writing r/o exit information fields */
1430 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1433 return vmcs_config.cpu_based_2nd_exec_ctrl &
1434 SECONDARY_EXEC_SHADOW_VMCS;
1437 static inline bool cpu_has_vmx_pml(void)
1439 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1442 static inline bool cpu_has_vmx_tsc_scaling(void)
1444 return vmcs_config.cpu_based_2nd_exec_ctrl &
1445 SECONDARY_EXEC_TSC_SCALING;
1448 static inline bool report_flexpriority(void)
1450 return flexpriority_enabled;
1453 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1455 return vmcs12->cpu_based_vm_exec_control & bit;
1458 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1460 return (vmcs12->cpu_based_vm_exec_control &
1461 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1462 (vmcs12->secondary_vm_exec_control & bit);
1465 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1467 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1470 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1472 return vmcs12->pin_based_vm_exec_control &
1473 PIN_BASED_VMX_PREEMPTION_TIMER;
1476 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1478 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1481 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1483 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
1484 vmx_xsaves_supported();
1487 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1489 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1492 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1494 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1497 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1499 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1502 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1504 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1507 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1509 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1512 static inline bool is_nmi(u32 intr_info)
1514 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1515 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1518 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1520 unsigned long exit_qualification);
1521 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1522 struct vmcs12 *vmcs12,
1523 u32 reason, unsigned long qualification);
1525 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1529 for (i = 0; i < vmx->nmsrs; ++i)
1530 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1535 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
1541 } operand = { vpid, 0, gva };
1543 asm volatile (__ex(ASM_VMX_INVVPID)
1544 /* CF==1 or ZF==1 --> rc = -1 */
1545 "; ja 1f ; ud2 ; 1:"
1546 : : "a"(&operand), "c"(ext) : "cc", "memory");
1549 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
1553 } operand = {eptp, gpa};
1555 asm volatile (__ex(ASM_VMX_INVEPT)
1556 /* CF==1 or ZF==1 --> rc = -1 */
1557 "; ja 1f ; ud2 ; 1:\n"
1558 : : "a" (&operand), "c" (ext) : "cc", "memory");
1561 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1565 i = __find_msr_index(vmx, msr);
1567 return &vmx->guest_msrs[i];
1571 static void vmcs_clear(struct vmcs *vmcs)
1573 u64 phys_addr = __pa(vmcs);
1576 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1577 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1580 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1584 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1586 vmcs_clear(loaded_vmcs->vmcs);
1587 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1588 vmcs_clear(loaded_vmcs->shadow_vmcs);
1589 loaded_vmcs->cpu = -1;
1590 loaded_vmcs->launched = 0;
1593 static void vmcs_load(struct vmcs *vmcs)
1595 u64 phys_addr = __pa(vmcs);
1598 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1599 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1602 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1606 #ifdef CONFIG_KEXEC_CORE
1608 * This bitmap is used to indicate whether the vmclear
1609 * operation is enabled on all cpus. All disabled by
1612 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1614 static inline void crash_enable_local_vmclear(int cpu)
1616 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1619 static inline void crash_disable_local_vmclear(int cpu)
1621 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1624 static inline int crash_local_vmclear_enabled(int cpu)
1626 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1629 static void crash_vmclear_local_loaded_vmcss(void)
1631 int cpu = raw_smp_processor_id();
1632 struct loaded_vmcs *v;
1634 if (!crash_local_vmclear_enabled(cpu))
1637 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1638 loaded_vmcss_on_cpu_link)
1639 vmcs_clear(v->vmcs);
1642 static inline void crash_enable_local_vmclear(int cpu) { }
1643 static inline void crash_disable_local_vmclear(int cpu) { }
1644 #endif /* CONFIG_KEXEC_CORE */
1646 static void __loaded_vmcs_clear(void *arg)
1648 struct loaded_vmcs *loaded_vmcs = arg;
1649 int cpu = raw_smp_processor_id();
1651 if (loaded_vmcs->cpu != cpu)
1652 return; /* vcpu migration can race with cpu offline */
1653 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1654 per_cpu(current_vmcs, cpu) = NULL;
1655 crash_disable_local_vmclear(cpu);
1656 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1659 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1660 * is before setting loaded_vmcs->vcpu to -1 which is done in
1661 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1662 * then adds the vmcs into percpu list before it is deleted.
1666 loaded_vmcs_init(loaded_vmcs);
1667 crash_enable_local_vmclear(cpu);
1670 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1672 int cpu = loaded_vmcs->cpu;
1675 smp_call_function_single(cpu,
1676 __loaded_vmcs_clear, loaded_vmcs, 1);
1679 static inline void vpid_sync_vcpu_single(int vpid)
1684 if (cpu_has_vmx_invvpid_single())
1685 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1688 static inline void vpid_sync_vcpu_global(void)
1690 if (cpu_has_vmx_invvpid_global())
1691 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1694 static inline void vpid_sync_context(int vpid)
1696 if (cpu_has_vmx_invvpid_single())
1697 vpid_sync_vcpu_single(vpid);
1699 vpid_sync_vcpu_global();
1702 static inline void ept_sync_global(void)
1704 if (cpu_has_vmx_invept_global())
1705 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1708 static inline void ept_sync_context(u64 eptp)
1711 if (cpu_has_vmx_invept_context())
1712 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1718 static __always_inline void vmcs_check16(unsigned long field)
1720 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1721 "16-bit accessor invalid for 64-bit field");
1722 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1723 "16-bit accessor invalid for 64-bit high field");
1724 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1725 "16-bit accessor invalid for 32-bit high field");
1726 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1727 "16-bit accessor invalid for natural width field");
1730 static __always_inline void vmcs_check32(unsigned long field)
1732 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1733 "32-bit accessor invalid for 16-bit field");
1734 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1735 "32-bit accessor invalid for natural width field");
1738 static __always_inline void vmcs_check64(unsigned long field)
1740 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1741 "64-bit accessor invalid for 16-bit field");
1742 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1743 "64-bit accessor invalid for 64-bit high field");
1744 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1745 "64-bit accessor invalid for 32-bit field");
1746 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1747 "64-bit accessor invalid for natural width field");
1750 static __always_inline void vmcs_checkl(unsigned long field)
1752 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1753 "Natural width accessor invalid for 16-bit field");
1754 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1755 "Natural width accessor invalid for 64-bit field");
1756 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1757 "Natural width accessor invalid for 64-bit high field");
1758 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1759 "Natural width accessor invalid for 32-bit field");
1762 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1764 unsigned long value;
1766 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1767 : "=a"(value) : "d"(field) : "cc");
1771 static __always_inline u16 vmcs_read16(unsigned long field)
1773 vmcs_check16(field);
1774 return __vmcs_readl(field);
1777 static __always_inline u32 vmcs_read32(unsigned long field)
1779 vmcs_check32(field);
1780 return __vmcs_readl(field);
1783 static __always_inline u64 vmcs_read64(unsigned long field)
1785 vmcs_check64(field);
1786 #ifdef CONFIG_X86_64
1787 return __vmcs_readl(field);
1789 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1793 static __always_inline unsigned long vmcs_readl(unsigned long field)
1796 return __vmcs_readl(field);
1799 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1801 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1802 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1806 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1810 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1811 : "=q"(error) : "a"(value), "d"(field) : "cc");
1812 if (unlikely(error))
1813 vmwrite_error(field, value);
1816 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1818 vmcs_check16(field);
1819 __vmcs_writel(field, value);
1822 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1824 vmcs_check32(field);
1825 __vmcs_writel(field, value);
1828 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1830 vmcs_check64(field);
1831 __vmcs_writel(field, value);
1832 #ifndef CONFIG_X86_64
1834 __vmcs_writel(field+1, value >> 32);
1838 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1841 __vmcs_writel(field, value);
1844 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1846 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1847 "vmcs_clear_bits does not support 64-bit fields");
1848 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1851 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1853 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1854 "vmcs_set_bits does not support 64-bit fields");
1855 __vmcs_writel(field, __vmcs_readl(field) | mask);
1858 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1860 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1863 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1865 vmcs_write32(VM_ENTRY_CONTROLS, val);
1866 vmx->vm_entry_controls_shadow = val;
1869 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1871 if (vmx->vm_entry_controls_shadow != val)
1872 vm_entry_controls_init(vmx, val);
1875 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1877 return vmx->vm_entry_controls_shadow;
1881 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1883 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1886 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1888 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1891 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1893 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1896 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1898 vmcs_write32(VM_EXIT_CONTROLS, val);
1899 vmx->vm_exit_controls_shadow = val;
1902 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1904 if (vmx->vm_exit_controls_shadow != val)
1905 vm_exit_controls_init(vmx, val);
1908 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1910 return vmx->vm_exit_controls_shadow;
1914 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1916 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1919 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1921 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1924 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1926 vmx->segment_cache.bitmask = 0;
1929 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1933 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1935 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1936 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1937 vmx->segment_cache.bitmask = 0;
1939 ret = vmx->segment_cache.bitmask & mask;
1940 vmx->segment_cache.bitmask |= mask;
1944 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1946 u16 *p = &vmx->segment_cache.seg[seg].selector;
1948 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1949 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1953 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1955 ulong *p = &vmx->segment_cache.seg[seg].base;
1957 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1958 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1962 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1964 u32 *p = &vmx->segment_cache.seg[seg].limit;
1966 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1967 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1971 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1973 u32 *p = &vmx->segment_cache.seg[seg].ar;
1975 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1976 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1980 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1984 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
1985 (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
1986 if ((vcpu->guest_debug &
1987 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
1988 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
1989 eb |= 1u << BP_VECTOR;
1990 if (to_vmx(vcpu)->rmode.vm86_active)
1993 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
1994 if (vcpu->fpu_active)
1995 eb &= ~(1u << NM_VECTOR);
1997 /* When we are running a nested L2 guest and L1 specified for it a
1998 * certain exception bitmap, we must trap the same exceptions and pass
1999 * them to L1. When running L2, we will only handle the exceptions
2000 * specified above if L1 did not want them.
2002 if (is_guest_mode(vcpu))
2003 eb |= get_vmcs12(vcpu)->exception_bitmap;
2005 vmcs_write32(EXCEPTION_BITMAP, eb);
2009 * Check if MSR is intercepted for currently loaded MSR bitmap.
2011 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2013 unsigned long *msr_bitmap;
2014 int f = sizeof(unsigned long);
2016 if (!cpu_has_vmx_msr_bitmap())
2019 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2021 if (msr <= 0x1fff) {
2022 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2023 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2025 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2032 * Check if MSR is intercepted for L01 MSR bitmap.
2034 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2036 unsigned long *msr_bitmap;
2037 int f = sizeof(unsigned long);
2039 if (!cpu_has_vmx_msr_bitmap())
2042 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2044 if (msr <= 0x1fff) {
2045 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2046 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2048 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2054 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2055 unsigned long entry, unsigned long exit)
2057 vm_entry_controls_clearbit(vmx, entry);
2058 vm_exit_controls_clearbit(vmx, exit);
2061 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2065 for (i = 0; i < m->nr; ++i) {
2066 if (m->val[i].index == msr)
2072 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2075 struct msr_autoload *m = &vmx->msr_autoload;
2079 if (cpu_has_load_ia32_efer) {
2080 clear_atomic_switch_msr_special(vmx,
2081 VM_ENTRY_LOAD_IA32_EFER,
2082 VM_EXIT_LOAD_IA32_EFER);
2086 case MSR_CORE_PERF_GLOBAL_CTRL:
2087 if (cpu_has_load_perf_global_ctrl) {
2088 clear_atomic_switch_msr_special(vmx,
2089 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2090 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2095 i = find_msr(&m->guest, msr);
2099 m->guest.val[i] = m->guest.val[m->guest.nr];
2100 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2103 i = find_msr(&m->host, msr);
2108 m->host.val[i] = m->host.val[m->host.nr];
2109 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2112 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2113 unsigned long entry, unsigned long exit,
2114 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2115 u64 guest_val, u64 host_val)
2117 vmcs_write64(guest_val_vmcs, guest_val);
2118 vmcs_write64(host_val_vmcs, host_val);
2119 vm_entry_controls_setbit(vmx, entry);
2120 vm_exit_controls_setbit(vmx, exit);
2123 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2124 u64 guest_val, u64 host_val, bool entry_only)
2127 struct msr_autoload *m = &vmx->msr_autoload;
2131 if (cpu_has_load_ia32_efer) {
2132 add_atomic_switch_msr_special(vmx,
2133 VM_ENTRY_LOAD_IA32_EFER,
2134 VM_EXIT_LOAD_IA32_EFER,
2137 guest_val, host_val);
2141 case MSR_CORE_PERF_GLOBAL_CTRL:
2142 if (cpu_has_load_perf_global_ctrl) {
2143 add_atomic_switch_msr_special(vmx,
2144 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2145 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2146 GUEST_IA32_PERF_GLOBAL_CTRL,
2147 HOST_IA32_PERF_GLOBAL_CTRL,
2148 guest_val, host_val);
2152 case MSR_IA32_PEBS_ENABLE:
2153 /* PEBS needs a quiescent period after being disabled (to write
2154 * a record). Disabling PEBS through VMX MSR swapping doesn't
2155 * provide that period, so a CPU could write host's record into
2158 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2161 i = find_msr(&m->guest, msr);
2163 j = find_msr(&m->host, msr);
2165 if (i == NR_AUTOLOAD_MSRS || j == NR_AUTOLOAD_MSRS) {
2166 printk_once(KERN_WARNING "Not enough msr switch entries. "
2167 "Can't add msr %x\n", msr);
2172 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2174 m->guest.val[i].index = msr;
2175 m->guest.val[i].value = guest_val;
2182 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2184 m->host.val[j].index = msr;
2185 m->host.val[j].value = host_val;
2188 static void reload_tss(void)
2191 * VT restores TR but not its size. Useless.
2193 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2194 struct desc_struct *descs;
2196 descs = (void *)gdt->address;
2197 descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
2201 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2203 u64 guest_efer = vmx->vcpu.arch.efer;
2204 u64 ignore_bits = 0;
2208 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
2209 * host CPUID is more efficient than testing guest CPUID
2210 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
2212 if (boot_cpu_has(X86_FEATURE_SMEP))
2213 guest_efer |= EFER_NX;
2214 else if (!(guest_efer & EFER_NX))
2215 ignore_bits |= EFER_NX;
2219 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2221 ignore_bits |= EFER_SCE;
2222 #ifdef CONFIG_X86_64
2223 ignore_bits |= EFER_LMA | EFER_LME;
2224 /* SCE is meaningful only in long mode on Intel */
2225 if (guest_efer & EFER_LMA)
2226 ignore_bits &= ~(u64)EFER_SCE;
2229 clear_atomic_switch_msr(vmx, MSR_EFER);
2232 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2233 * On CPUs that support "load IA32_EFER", always switch EFER
2234 * atomically, since it's faster than switching it manually.
2236 if (cpu_has_load_ia32_efer ||
2237 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2238 if (!(guest_efer & EFER_LMA))
2239 guest_efer &= ~EFER_LME;
2240 if (guest_efer != host_efer)
2241 add_atomic_switch_msr(vmx, MSR_EFER,
2242 guest_efer, host_efer, false);
2245 guest_efer &= ~ignore_bits;
2246 guest_efer |= host_efer & ignore_bits;
2248 vmx->guest_msrs[efer_offset].data = guest_efer;
2249 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2255 static unsigned long segment_base(u16 selector)
2257 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2258 struct desc_struct *d;
2259 unsigned long table_base;
2262 if (!(selector & ~3))
2265 table_base = gdt->address;
2267 if (selector & 4) { /* from ldt */
2268 u16 ldt_selector = kvm_read_ldt();
2270 if (!(ldt_selector & ~3))
2273 table_base = segment_base(ldt_selector);
2275 d = (struct desc_struct *)(table_base + (selector & ~7));
2276 v = get_desc_base(d);
2277 #ifdef CONFIG_X86_64
2278 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
2279 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
2284 static inline unsigned long kvm_read_tr_base(void)
2287 asm("str %0" : "=g"(tr));
2288 return segment_base(tr);
2291 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2293 struct vcpu_vmx *vmx = to_vmx(vcpu);
2296 if (vmx->host_state.loaded)
2299 vmx->host_state.loaded = 1;
2301 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2302 * allow segment selectors with cpl > 0 or ti == 1.
2304 vmx->host_state.ldt_sel = kvm_read_ldt();
2305 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2306 savesegment(fs, vmx->host_state.fs_sel);
2307 if (!(vmx->host_state.fs_sel & 7)) {
2308 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2309 vmx->host_state.fs_reload_needed = 0;
2311 vmcs_write16(HOST_FS_SELECTOR, 0);
2312 vmx->host_state.fs_reload_needed = 1;
2314 savesegment(gs, vmx->host_state.gs_sel);
2315 if (!(vmx->host_state.gs_sel & 7))
2316 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2318 vmcs_write16(HOST_GS_SELECTOR, 0);
2319 vmx->host_state.gs_ldt_reload_needed = 1;
2322 #ifdef CONFIG_X86_64
2323 savesegment(ds, vmx->host_state.ds_sel);
2324 savesegment(es, vmx->host_state.es_sel);
2327 #ifdef CONFIG_X86_64
2328 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2329 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2331 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2332 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2335 #ifdef CONFIG_X86_64
2336 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2337 if (is_long_mode(&vmx->vcpu))
2338 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2340 if (boot_cpu_has(X86_FEATURE_MPX))
2341 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2342 for (i = 0; i < vmx->save_nmsrs; ++i)
2343 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2344 vmx->guest_msrs[i].data,
2345 vmx->guest_msrs[i].mask);
2348 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2350 if (!vmx->host_state.loaded)
2353 ++vmx->vcpu.stat.host_state_reload;
2354 vmx->host_state.loaded = 0;
2355 #ifdef CONFIG_X86_64
2356 if (is_long_mode(&vmx->vcpu))
2357 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2359 if (vmx->host_state.gs_ldt_reload_needed) {
2360 kvm_load_ldt(vmx->host_state.ldt_sel);
2361 #ifdef CONFIG_X86_64
2362 load_gs_index(vmx->host_state.gs_sel);
2364 loadsegment(gs, vmx->host_state.gs_sel);
2367 if (vmx->host_state.fs_reload_needed)
2368 loadsegment(fs, vmx->host_state.fs_sel);
2369 #ifdef CONFIG_X86_64
2370 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2371 loadsegment(ds, vmx->host_state.ds_sel);
2372 loadsegment(es, vmx->host_state.es_sel);
2376 #ifdef CONFIG_X86_64
2377 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2379 if (vmx->host_state.msr_host_bndcfgs)
2380 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2382 * If the FPU is not active (through the host task or
2383 * the guest vcpu), then restore the cr0.TS bit.
2385 if (!fpregs_active() && !vmx->vcpu.guest_fpu_loaded)
2387 load_gdt(this_cpu_ptr(&host_gdt));
2390 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2393 __vmx_load_host_state(vmx);
2397 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2399 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2400 struct pi_desc old, new;
2404 * In case of hot-plug or hot-unplug, we may have to undo
2405 * vmx_vcpu_pi_put even if there is no assigned device. And we
2406 * always keep PI.NDST up to date for simplicity: it makes the
2407 * code easier, and CPU migration is not a fast path.
2409 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2413 * First handle the simple case where no cmpxchg is necessary; just
2414 * allow posting non-urgent interrupts.
2416 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2417 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2418 * expects the VCPU to be on the blocked_vcpu_list that matches
2421 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2423 pi_clear_sn(pi_desc);
2427 /* The full case. */
2429 old.control = new.control = pi_desc->control;
2431 dest = cpu_physical_id(cpu);
2433 if (x2apic_enabled())
2436 new.ndst = (dest << 8) & 0xFF00;
2439 } while (cmpxchg64(&pi_desc->control, old.control,
2440 new.control) != old.control);
2443 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2445 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2446 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2450 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2451 * vcpu mutex is already taken.
2453 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2455 struct vcpu_vmx *vmx = to_vmx(vcpu);
2456 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2457 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2460 kvm_cpu_vmxon(phys_addr);
2461 else if (!already_loaded)
2462 loaded_vmcs_clear(vmx->loaded_vmcs);
2464 if (!already_loaded) {
2465 local_irq_disable();
2466 crash_disable_local_vmclear(cpu);
2469 * Read loaded_vmcs->cpu should be before fetching
2470 * loaded_vmcs->loaded_vmcss_on_cpu_link.
2471 * See the comments in __loaded_vmcs_clear().
2475 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2476 &per_cpu(loaded_vmcss_on_cpu, cpu));
2477 crash_enable_local_vmclear(cpu);
2481 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2482 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2483 vmcs_load(vmx->loaded_vmcs->vmcs);
2484 indirect_branch_prediction_barrier();
2487 if (!already_loaded) {
2488 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2489 unsigned long sysenter_esp;
2491 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2494 * Linux uses per-cpu TSS and GDT, so set these when switching
2497 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
2498 vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
2500 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2501 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2503 vmx->loaded_vmcs->cpu = cpu;
2506 /* Setup TSC multiplier */
2507 if (kvm_has_tsc_control &&
2508 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2509 decache_tsc_multiplier(vmx);
2511 vmx_vcpu_pi_load(vcpu, cpu);
2512 vmx->host_pkru = read_pkru();
2515 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2517 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2519 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2520 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2521 !kvm_vcpu_apicv_active(vcpu))
2524 /* Set SN when the vCPU is preempted */
2525 if (vcpu->preempted)
2529 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2531 vmx_vcpu_pi_put(vcpu);
2533 __vmx_load_host_state(to_vmx(vcpu));
2534 if (!vmm_exclusive) {
2535 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
2541 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
2545 if (vcpu->fpu_active)
2547 vcpu->fpu_active = 1;
2548 cr0 = vmcs_readl(GUEST_CR0);
2549 cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
2550 cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
2551 vmcs_writel(GUEST_CR0, cr0);
2552 update_exception_bitmap(vcpu);
2553 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
2554 if (is_guest_mode(vcpu))
2555 vcpu->arch.cr0_guest_owned_bits &=
2556 ~get_vmcs12(vcpu)->cr0_guest_host_mask;
2557 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2560 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2563 * Return the cr0 value that a nested guest would read. This is a combination
2564 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2565 * its hypervisor (cr0_read_shadow).
2567 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2569 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2570 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2572 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2574 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2575 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2578 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
2580 /* Note that there is no vcpu->fpu_active = 0 here. The caller must
2581 * set this *before* calling this function.
2583 vmx_decache_cr0_guest_bits(vcpu);
2584 vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
2585 update_exception_bitmap(vcpu);
2586 vcpu->arch.cr0_guest_owned_bits = 0;
2587 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2588 if (is_guest_mode(vcpu)) {
2590 * L1's specified read shadow might not contain the TS bit,
2591 * so now that we turned on shadowing of this bit, we need to
2592 * set this bit of the shadow. Like in nested_vmx_run we need
2593 * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
2594 * up-to-date here because we just decached cr0.TS (and we'll
2595 * only update vmcs12->guest_cr0 on nested exit).
2597 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2598 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
2599 (vcpu->arch.cr0 & X86_CR0_TS);
2600 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2602 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
2605 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2607 unsigned long rflags, save_rflags;
2609 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2610 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2611 rflags = vmcs_readl(GUEST_RFLAGS);
2612 if (to_vmx(vcpu)->rmode.vm86_active) {
2613 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2614 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2615 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2617 to_vmx(vcpu)->rflags = rflags;
2619 return to_vmx(vcpu)->rflags;
2622 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2624 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2625 to_vmx(vcpu)->rflags = rflags;
2626 if (to_vmx(vcpu)->rmode.vm86_active) {
2627 to_vmx(vcpu)->rmode.save_rflags = rflags;
2628 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2630 vmcs_writel(GUEST_RFLAGS, rflags);
2633 static u32 vmx_get_pkru(struct kvm_vcpu *vcpu)
2635 return to_vmx(vcpu)->guest_pkru;
2638 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2640 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2643 if (interruptibility & GUEST_INTR_STATE_STI)
2644 ret |= KVM_X86_SHADOW_INT_STI;
2645 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2646 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2651 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2653 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2654 u32 interruptibility = interruptibility_old;
2656 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2658 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2659 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2660 else if (mask & KVM_X86_SHADOW_INT_STI)
2661 interruptibility |= GUEST_INTR_STATE_STI;
2663 if ((interruptibility != interruptibility_old))
2664 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2667 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2671 rip = kvm_rip_read(vcpu);
2672 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2673 kvm_rip_write(vcpu, rip);
2675 /* skipping an emulated instruction also counts */
2676 vmx_set_interrupt_shadow(vcpu, 0);
2680 * KVM wants to inject page-faults which it got to the guest. This function
2681 * checks whether in a nested guest, we need to inject them to L1 or L2.
2683 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
2685 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2687 if (!(vmcs12->exception_bitmap & (1u << nr)))
2690 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
2691 vmcs_read32(VM_EXIT_INTR_INFO),
2692 vmcs_readl(EXIT_QUALIFICATION));
2696 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
2697 bool has_error_code, u32 error_code,
2700 struct vcpu_vmx *vmx = to_vmx(vcpu);
2701 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2703 if (!reinject && is_guest_mode(vcpu) &&
2704 nested_vmx_check_exception(vcpu, nr))
2707 if (has_error_code) {
2708 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2709 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2712 if (vmx->rmode.vm86_active) {
2714 if (kvm_exception_is_soft(nr))
2715 inc_eip = vcpu->arch.event_exit_inst_len;
2716 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2717 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2721 WARN_ON_ONCE(vmx->emulation_required);
2723 if (kvm_exception_is_soft(nr)) {
2724 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2725 vmx->vcpu.arch.event_exit_inst_len);
2726 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2728 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2730 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2733 static bool vmx_rdtscp_supported(void)
2735 return cpu_has_vmx_rdtscp();
2738 static bool vmx_invpcid_supported(void)
2740 return cpu_has_vmx_invpcid() && enable_ept;
2744 * Swap MSR entry in host/guest MSR entry array.
2746 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2748 struct shared_msr_entry tmp;
2750 tmp = vmx->guest_msrs[to];
2751 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2752 vmx->guest_msrs[from] = tmp;
2756 * Set up the vmcs to automatically save and restore system
2757 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2758 * mode, as fiddling with msrs is very expensive.
2760 static void setup_msrs(struct vcpu_vmx *vmx)
2762 int save_nmsrs, index;
2765 #ifdef CONFIG_X86_64
2766 if (is_long_mode(&vmx->vcpu)) {
2767 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2769 move_msr_up(vmx, index, save_nmsrs++);
2770 index = __find_msr_index(vmx, MSR_LSTAR);
2772 move_msr_up(vmx, index, save_nmsrs++);
2773 index = __find_msr_index(vmx, MSR_CSTAR);
2775 move_msr_up(vmx, index, save_nmsrs++);
2776 index = __find_msr_index(vmx, MSR_TSC_AUX);
2777 if (index >= 0 && guest_cpuid_has_rdtscp(&vmx->vcpu))
2778 move_msr_up(vmx, index, save_nmsrs++);
2780 * MSR_STAR is only needed on long mode guests, and only
2781 * if efer.sce is enabled.
2783 index = __find_msr_index(vmx, MSR_STAR);
2784 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2785 move_msr_up(vmx, index, save_nmsrs++);
2788 index = __find_msr_index(vmx, MSR_EFER);
2789 if (index >= 0 && update_transition_efer(vmx, index))
2790 move_msr_up(vmx, index, save_nmsrs++);
2792 vmx->save_nmsrs = save_nmsrs;
2794 if (cpu_has_vmx_msr_bitmap())
2795 vmx_update_msr_bitmap(&vmx->vcpu);
2799 * reads and returns guest's timestamp counter "register"
2800 * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2801 * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2803 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2805 u64 host_tsc, tsc_offset;
2808 tsc_offset = vmcs_read64(TSC_OFFSET);
2809 return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2813 * writes 'offset' into guest's timestamp counter offset register
2815 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2817 if (is_guest_mode(vcpu)) {
2819 * We're here if L1 chose not to trap WRMSR to TSC. According
2820 * to the spec, this should set L1's TSC; The offset that L1
2821 * set for L2 remains unchanged, and still needs to be added
2822 * to the newly set TSC to get L2's TSC.
2824 struct vmcs12 *vmcs12;
2825 /* recalculate vmcs02.TSC_OFFSET: */
2826 vmcs12 = get_vmcs12(vcpu);
2827 vmcs_write64(TSC_OFFSET, offset +
2828 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2829 vmcs12->tsc_offset : 0));
2831 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2832 vmcs_read64(TSC_OFFSET), offset);
2833 vmcs_write64(TSC_OFFSET, offset);
2837 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2839 struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2840 return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2844 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2845 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2846 * all guests if the "nested" module option is off, and can also be disabled
2847 * for a single guest by disabling its VMX cpuid bit.
2849 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2851 return nested && guest_cpuid_has_vmx(vcpu);
2855 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2856 * returned for the various VMX controls MSRs when nested VMX is enabled.
2857 * The same values should also be used to verify that vmcs12 control fields are
2858 * valid during nested entry from L1 to L2.
2859 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2860 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2861 * bit in the high half is on if the corresponding bit in the control field
2862 * may be on. See also vmx_control_verify().
2864 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2867 * Note that as a general rule, the high half of the MSRs (bits in
2868 * the control fields which may be 1) should be initialized by the
2869 * intersection of the underlying hardware's MSR (i.e., features which
2870 * can be supported) and the list of features we want to expose -
2871 * because they are known to be properly supported in our code.
2872 * Also, usually, the low half of the MSRs (bits which must be 1) can
2873 * be set to 0, meaning that L1 may turn off any of these bits. The
2874 * reason is that if one of these bits is necessary, it will appear
2875 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2876 * fields of vmcs01 and vmcs02, will turn these bits off - and
2877 * nested_vmx_exit_handled() will not pass related exits to L1.
2878 * These rules have exceptions below.
2881 /* pin-based controls */
2882 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2883 vmx->nested.nested_vmx_pinbased_ctls_low,
2884 vmx->nested.nested_vmx_pinbased_ctls_high);
2885 vmx->nested.nested_vmx_pinbased_ctls_low |=
2886 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2887 vmx->nested.nested_vmx_pinbased_ctls_high &=
2888 PIN_BASED_EXT_INTR_MASK |
2889 PIN_BASED_NMI_EXITING |
2890 PIN_BASED_VIRTUAL_NMIS;
2891 vmx->nested.nested_vmx_pinbased_ctls_high |=
2892 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2893 PIN_BASED_VMX_PREEMPTION_TIMER;
2894 if (kvm_vcpu_apicv_active(&vmx->vcpu))
2895 vmx->nested.nested_vmx_pinbased_ctls_high |=
2896 PIN_BASED_POSTED_INTR;
2899 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2900 vmx->nested.nested_vmx_exit_ctls_low,
2901 vmx->nested.nested_vmx_exit_ctls_high);
2902 vmx->nested.nested_vmx_exit_ctls_low =
2903 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2905 vmx->nested.nested_vmx_exit_ctls_high &=
2906 #ifdef CONFIG_X86_64
2907 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2909 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2910 vmx->nested.nested_vmx_exit_ctls_high |=
2911 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2912 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2913 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2915 if (kvm_mpx_supported())
2916 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2918 /* We support free control of debug control saving. */
2919 vmx->nested.nested_vmx_true_exit_ctls_low =
2920 vmx->nested.nested_vmx_exit_ctls_low &
2921 ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2923 /* entry controls */
2924 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2925 vmx->nested.nested_vmx_entry_ctls_low,
2926 vmx->nested.nested_vmx_entry_ctls_high);
2927 vmx->nested.nested_vmx_entry_ctls_low =
2928 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2929 vmx->nested.nested_vmx_entry_ctls_high &=
2930 #ifdef CONFIG_X86_64
2931 VM_ENTRY_IA32E_MODE |
2933 VM_ENTRY_LOAD_IA32_PAT;
2934 vmx->nested.nested_vmx_entry_ctls_high |=
2935 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2936 if (kvm_mpx_supported())
2937 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2939 /* We support free control of debug control loading. */
2940 vmx->nested.nested_vmx_true_entry_ctls_low =
2941 vmx->nested.nested_vmx_entry_ctls_low &
2942 ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2944 /* cpu-based controls */
2945 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2946 vmx->nested.nested_vmx_procbased_ctls_low,
2947 vmx->nested.nested_vmx_procbased_ctls_high);
2948 vmx->nested.nested_vmx_procbased_ctls_low =
2949 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2950 vmx->nested.nested_vmx_procbased_ctls_high &=
2951 CPU_BASED_VIRTUAL_INTR_PENDING |
2952 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2953 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2954 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2955 CPU_BASED_CR3_STORE_EXITING |
2956 #ifdef CONFIG_X86_64
2957 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2959 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2960 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2961 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2962 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2963 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2965 * We can allow some features even when not supported by the
2966 * hardware. For example, L1 can specify an MSR bitmap - and we
2967 * can use it to avoid exits to L1 - even when L0 runs L2
2968 * without MSR bitmaps.
2970 vmx->nested.nested_vmx_procbased_ctls_high |=
2971 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2972 CPU_BASED_USE_MSR_BITMAPS;
2974 /* We support free control of CR3 access interception. */
2975 vmx->nested.nested_vmx_true_procbased_ctls_low =
2976 vmx->nested.nested_vmx_procbased_ctls_low &
2977 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2979 /* secondary cpu-based controls */
2980 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2981 vmx->nested.nested_vmx_secondary_ctls_low,
2982 vmx->nested.nested_vmx_secondary_ctls_high);
2983 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2984 vmx->nested.nested_vmx_secondary_ctls_high &=
2985 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2986 SECONDARY_EXEC_RDTSCP |
2987 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2988 SECONDARY_EXEC_ENABLE_VPID |
2989 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2990 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2991 SECONDARY_EXEC_WBINVD_EXITING |
2992 SECONDARY_EXEC_XSAVES;
2995 /* nested EPT: emulate EPT also to L1 */
2996 vmx->nested.nested_vmx_secondary_ctls_high |=
2997 SECONDARY_EXEC_ENABLE_EPT;
2998 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
2999 VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
3001 if (cpu_has_vmx_ept_execute_only())
3002 vmx->nested.nested_vmx_ept_caps |=
3003 VMX_EPT_EXECUTE_ONLY_BIT;
3004 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
3005 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3006 VMX_EPT_EXTENT_CONTEXT_BIT;
3008 vmx->nested.nested_vmx_ept_caps = 0;
3011 * Old versions of KVM use the single-context version without
3012 * checking for support, so declare that it is supported even
3013 * though it is treated as global context. The alternative is
3014 * not failing the single-context invvpid, and it is worse.
3017 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
3018 VMX_VPID_EXTENT_SUPPORTED_MASK;
3020 vmx->nested.nested_vmx_vpid_caps = 0;
3022 if (enable_unrestricted_guest)
3023 vmx->nested.nested_vmx_secondary_ctls_high |=
3024 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3026 /* miscellaneous data */
3027 rdmsr(MSR_IA32_VMX_MISC,
3028 vmx->nested.nested_vmx_misc_low,
3029 vmx->nested.nested_vmx_misc_high);
3030 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
3031 vmx->nested.nested_vmx_misc_low |=
3032 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3033 VMX_MISC_ACTIVITY_HLT;
3034 vmx->nested.nested_vmx_misc_high = 0;
3037 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3040 * Bits 0 in high must be 0, and bits 1 in low must be 1.
3042 return ((control & high) | low) == control;
3045 static inline u64 vmx_control_msr(u32 low, u32 high)
3047 return low | ((u64)high << 32);
3050 /* Returns 0 on success, non-0 otherwise. */
3051 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3053 struct vcpu_vmx *vmx = to_vmx(vcpu);
3055 switch (msr_index) {
3056 case MSR_IA32_VMX_BASIC:
3058 * This MSR reports some information about VMX support. We
3059 * should return information about the VMX we emulate for the
3060 * guest, and the VMCS structure we give it - not about the
3061 * VMX support of the underlying hardware.
3063 *pdata = VMCS12_REVISION | VMX_BASIC_TRUE_CTLS |
3064 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3065 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3066 if (cpu_has_vmx_basic_inout())
3067 *pdata |= VMX_BASIC_INOUT;
3069 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3070 case MSR_IA32_VMX_PINBASED_CTLS:
3071 *pdata = vmx_control_msr(
3072 vmx->nested.nested_vmx_pinbased_ctls_low,
3073 vmx->nested.nested_vmx_pinbased_ctls_high);
3075 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3076 *pdata = vmx_control_msr(
3077 vmx->nested.nested_vmx_true_procbased_ctls_low,
3078 vmx->nested.nested_vmx_procbased_ctls_high);
3080 case MSR_IA32_VMX_PROCBASED_CTLS:
3081 *pdata = vmx_control_msr(
3082 vmx->nested.nested_vmx_procbased_ctls_low,
3083 vmx->nested.nested_vmx_procbased_ctls_high);
3085 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3086 *pdata = vmx_control_msr(
3087 vmx->nested.nested_vmx_true_exit_ctls_low,
3088 vmx->nested.nested_vmx_exit_ctls_high);
3090 case MSR_IA32_VMX_EXIT_CTLS:
3091 *pdata = vmx_control_msr(
3092 vmx->nested.nested_vmx_exit_ctls_low,
3093 vmx->nested.nested_vmx_exit_ctls_high);
3095 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3096 *pdata = vmx_control_msr(
3097 vmx->nested.nested_vmx_true_entry_ctls_low,
3098 vmx->nested.nested_vmx_entry_ctls_high);
3100 case MSR_IA32_VMX_ENTRY_CTLS:
3101 *pdata = vmx_control_msr(
3102 vmx->nested.nested_vmx_entry_ctls_low,
3103 vmx->nested.nested_vmx_entry_ctls_high);
3105 case MSR_IA32_VMX_MISC:
3106 *pdata = vmx_control_msr(
3107 vmx->nested.nested_vmx_misc_low,
3108 vmx->nested.nested_vmx_misc_high);
3111 * These MSRs specify bits which the guest must keep fixed (on or off)
3112 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3113 * We picked the standard core2 setting.
3115 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3116 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3117 case MSR_IA32_VMX_CR0_FIXED0:
3118 *pdata = VMXON_CR0_ALWAYSON;
3120 case MSR_IA32_VMX_CR0_FIXED1:
3123 case MSR_IA32_VMX_CR4_FIXED0:
3124 *pdata = VMXON_CR4_ALWAYSON;
3126 case MSR_IA32_VMX_CR4_FIXED1:
3129 case MSR_IA32_VMX_VMCS_ENUM:
3130 *pdata = 0x2e; /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3132 case MSR_IA32_VMX_PROCBASED_CTLS2:
3133 *pdata = vmx_control_msr(
3134 vmx->nested.nested_vmx_secondary_ctls_low,
3135 vmx->nested.nested_vmx_secondary_ctls_high);
3137 case MSR_IA32_VMX_EPT_VPID_CAP:
3138 *pdata = vmx->nested.nested_vmx_ept_caps |
3139 ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3148 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3151 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3153 return !(val & ~valid_bits);
3156 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3162 * Reads an msr value (of 'msr_index') into 'pdata'.
3163 * Returns 0 on success, non-0 otherwise.
3164 * Assumes vcpu_load() was already called.
3166 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3168 struct shared_msr_entry *msr;
3170 switch (msr_info->index) {
3171 #ifdef CONFIG_X86_64
3173 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3176 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3178 case MSR_KERNEL_GS_BASE:
3179 vmx_load_host_state(to_vmx(vcpu));
3180 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3184 return kvm_get_msr_common(vcpu, msr_info);
3186 msr_info->data = guest_read_tsc(vcpu);
3188 case MSR_IA32_SPEC_CTRL:
3189 if (!msr_info->host_initiated &&
3190 !guest_cpuid_has_spec_ctrl(vcpu))
3193 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3195 case MSR_IA32_ARCH_CAPABILITIES:
3196 if (!msr_info->host_initiated &&
3197 !guest_cpuid_has_arch_capabilities(vcpu))
3199 msr_info->data = to_vmx(vcpu)->arch_capabilities;
3201 case MSR_IA32_SYSENTER_CS:
3202 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3204 case MSR_IA32_SYSENTER_EIP:
3205 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3207 case MSR_IA32_SYSENTER_ESP:
3208 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3210 case MSR_IA32_BNDCFGS:
3211 if (!kvm_mpx_supported() ||
3212 (!msr_info->host_initiated && !guest_cpuid_has_mpx(vcpu)))
3214 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3216 case MSR_IA32_MCG_EXT_CTL:
3217 if (!msr_info->host_initiated &&
3218 !(to_vmx(vcpu)->msr_ia32_feature_control &
3219 FEATURE_CONTROL_LMCE))
3221 msr_info->data = vcpu->arch.mcg_ext_ctl;
3223 case MSR_IA32_FEATURE_CONTROL:
3224 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3226 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3227 if (!nested_vmx_allowed(vcpu))
3229 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3231 if (!vmx_xsaves_supported())
3233 msr_info->data = vcpu->arch.ia32_xss;
3236 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3238 /* Otherwise falls through */
3240 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3242 msr_info->data = msr->data;
3245 return kvm_get_msr_common(vcpu, msr_info);
3251 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3254 * Writes msr value into into the appropriate "register".
3255 * Returns 0 on success, non-0 otherwise.
3256 * Assumes vcpu_load() was already called.
3258 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3260 struct vcpu_vmx *vmx = to_vmx(vcpu);
3261 struct shared_msr_entry *msr;
3263 u32 msr_index = msr_info->index;
3264 u64 data = msr_info->data;
3266 switch (msr_index) {
3268 ret = kvm_set_msr_common(vcpu, msr_info);
3270 #ifdef CONFIG_X86_64
3272 vmx_segment_cache_clear(vmx);
3273 vmcs_writel(GUEST_FS_BASE, data);
3276 vmx_segment_cache_clear(vmx);
3277 vmcs_writel(GUEST_GS_BASE, data);
3279 case MSR_KERNEL_GS_BASE:
3280 vmx_load_host_state(vmx);
3281 vmx->msr_guest_kernel_gs_base = data;
3284 case MSR_IA32_SYSENTER_CS:
3285 vmcs_write32(GUEST_SYSENTER_CS, data);
3287 case MSR_IA32_SYSENTER_EIP:
3288 vmcs_writel(GUEST_SYSENTER_EIP, data);
3290 case MSR_IA32_SYSENTER_ESP:
3291 vmcs_writel(GUEST_SYSENTER_ESP, data);
3293 case MSR_IA32_BNDCFGS:
3294 if (!kvm_mpx_supported() ||
3295 (!msr_info->host_initiated && !guest_cpuid_has_mpx(vcpu)))
3297 if (is_noncanonical_address(data & PAGE_MASK) ||
3298 (data & MSR_IA32_BNDCFGS_RSVD))
3300 vmcs_write64(GUEST_BNDCFGS, data);
3303 kvm_write_tsc(vcpu, msr_info);
3305 case MSR_IA32_SPEC_CTRL:
3306 if (!msr_info->host_initiated &&
3307 !guest_cpuid_has_spec_ctrl(vcpu))
3310 /* The STIBP bit doesn't fault even if it's not advertised */
3311 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3314 vmx->spec_ctrl = data;
3321 * When it's written (to non-zero) for the first time, pass
3325 * The handling of the MSR bitmap for L2 guests is done in
3326 * nested_vmx_merge_msr_bitmap. We should not touch the
3327 * vmcs02.msr_bitmap here since it gets completely overwritten
3328 * in the merging. We update the vmcs01 here for L1 as well
3329 * since it will end up touching the MSR anyway now.
3331 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3335 case MSR_IA32_PRED_CMD:
3336 if (!msr_info->host_initiated &&
3337 !guest_cpuid_has_ibpb(vcpu))
3340 if (data & ~PRED_CMD_IBPB)
3346 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3350 * When it's written (to non-zero) for the first time, pass
3354 * The handling of the MSR bitmap for L2 guests is done in
3355 * nested_vmx_merge_msr_bitmap. We should not touch the
3356 * vmcs02.msr_bitmap here since it gets completely overwritten
3359 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3362 case MSR_IA32_ARCH_CAPABILITIES:
3363 if (!msr_info->host_initiated)
3365 vmx->arch_capabilities = data;
3367 case MSR_IA32_CR_PAT:
3368 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3369 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3371 vmcs_write64(GUEST_IA32_PAT, data);
3372 vcpu->arch.pat = data;
3375 ret = kvm_set_msr_common(vcpu, msr_info);
3377 case MSR_IA32_TSC_ADJUST:
3378 ret = kvm_set_msr_common(vcpu, msr_info);
3380 case MSR_IA32_MCG_EXT_CTL:
3381 if ((!msr_info->host_initiated &&
3382 !(to_vmx(vcpu)->msr_ia32_feature_control &
3383 FEATURE_CONTROL_LMCE)) ||
3384 (data & ~MCG_EXT_CTL_LMCE_EN))
3386 vcpu->arch.mcg_ext_ctl = data;
3388 case MSR_IA32_FEATURE_CONTROL:
3389 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3390 (to_vmx(vcpu)->msr_ia32_feature_control &
3391 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3393 vmx->msr_ia32_feature_control = data;
3394 if (msr_info->host_initiated && data == 0)
3395 vmx_leave_nested(vcpu);
3397 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3398 return 1; /* they are read-only */
3400 if (!vmx_xsaves_supported())
3403 * The only supported bit as of Skylake is bit 8, but
3404 * it is not supported on KVM.
3408 vcpu->arch.ia32_xss = data;
3409 if (vcpu->arch.ia32_xss != host_xss)
3410 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3411 vcpu->arch.ia32_xss, host_xss, false);
3413 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3416 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3418 /* Check reserved bit, higher 32 bits should be zero */
3419 if ((data >> 32) != 0)
3421 /* Otherwise falls through */
3423 msr = find_msr_entry(vmx, msr_index);
3425 u64 old_msr_data = msr->data;
3427 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3429 ret = kvm_set_shared_msr(msr->index, msr->data,
3433 msr->data = old_msr_data;
3437 ret = kvm_set_msr_common(vcpu, msr_info);
3443 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3445 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3448 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3451 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3453 case VCPU_EXREG_PDPTR:
3455 ept_save_pdptrs(vcpu);
3462 static __init int cpu_has_kvm_support(void)
3464 return cpu_has_vmx();
3467 static __init int vmx_disabled_by_bios(void)
3471 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3472 if (msr & FEATURE_CONTROL_LOCKED) {
3473 /* launched w/ TXT and VMX disabled */
3474 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3477 /* launched w/o TXT and VMX only enabled w/ TXT */
3478 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3479 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3480 && !tboot_enabled()) {
3481 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3482 "activate TXT before enabling KVM\n");
3485 /* launched w/o TXT and VMX disabled */
3486 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3487 && !tboot_enabled())
3494 static void kvm_cpu_vmxon(u64 addr)
3496 intel_pt_handle_vmx(1);
3498 asm volatile (ASM_VMX_VMXON_RAX
3499 : : "a"(&addr), "m"(addr)
3503 static int hardware_enable(void)
3505 int cpu = raw_smp_processor_id();
3506 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3509 if (cr4_read_shadow() & X86_CR4_VMXE)
3512 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3513 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3514 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3517 * Now we can enable the vmclear operation in kdump
3518 * since the loaded_vmcss_on_cpu list on this cpu
3519 * has been initialized.
3521 * Though the cpu is not in VMX operation now, there
3522 * is no problem to enable the vmclear operation
3523 * for the loaded_vmcss_on_cpu list is empty!
3525 crash_enable_local_vmclear(cpu);
3527 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3529 test_bits = FEATURE_CONTROL_LOCKED;
3530 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3531 if (tboot_enabled())
3532 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3534 if ((old & test_bits) != test_bits) {
3535 /* enable and lock */
3536 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3538 cr4_set_bits(X86_CR4_VMXE);
3540 if (vmm_exclusive) {
3541 kvm_cpu_vmxon(phys_addr);
3545 native_store_gdt(this_cpu_ptr(&host_gdt));
3550 static void vmclear_local_loaded_vmcss(void)
3552 int cpu = raw_smp_processor_id();
3553 struct loaded_vmcs *v, *n;
3555 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3556 loaded_vmcss_on_cpu_link)
3557 __loaded_vmcs_clear(v);
3561 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3564 static void kvm_cpu_vmxoff(void)
3566 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3568 intel_pt_handle_vmx(0);
3571 static void hardware_disable(void)
3573 if (vmm_exclusive) {
3574 vmclear_local_loaded_vmcss();
3577 cr4_clear_bits(X86_CR4_VMXE);
3580 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3581 u32 msr, u32 *result)
3583 u32 vmx_msr_low, vmx_msr_high;
3584 u32 ctl = ctl_min | ctl_opt;
3586 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3588 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3589 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
3591 /* Ensure minimum (required) set of control bits are supported. */
3599 static __init bool allow_1_setting(u32 msr, u32 ctl)
3601 u32 vmx_msr_low, vmx_msr_high;
3603 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3604 return vmx_msr_high & ctl;
3607 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3609 u32 vmx_msr_low, vmx_msr_high;
3610 u32 min, opt, min2, opt2;
3611 u32 _pin_based_exec_control = 0;
3612 u32 _cpu_based_exec_control = 0;
3613 u32 _cpu_based_2nd_exec_control = 0;
3614 u32 _vmexit_control = 0;
3615 u32 _vmentry_control = 0;
3617 min = CPU_BASED_HLT_EXITING |
3618 #ifdef CONFIG_X86_64
3619 CPU_BASED_CR8_LOAD_EXITING |
3620 CPU_BASED_CR8_STORE_EXITING |
3622 CPU_BASED_CR3_LOAD_EXITING |
3623 CPU_BASED_CR3_STORE_EXITING |
3624 CPU_BASED_USE_IO_BITMAPS |
3625 CPU_BASED_MOV_DR_EXITING |
3626 CPU_BASED_USE_TSC_OFFSETING |
3627 CPU_BASED_MWAIT_EXITING |
3628 CPU_BASED_MONITOR_EXITING |
3629 CPU_BASED_INVLPG_EXITING |
3630 CPU_BASED_RDPMC_EXITING;
3632 opt = CPU_BASED_TPR_SHADOW |
3633 CPU_BASED_USE_MSR_BITMAPS |
3634 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3635 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3636 &_cpu_based_exec_control) < 0)
3638 #ifdef CONFIG_X86_64
3639 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3640 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3641 ~CPU_BASED_CR8_STORE_EXITING;
3643 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3645 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3646 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3647 SECONDARY_EXEC_WBINVD_EXITING |
3648 SECONDARY_EXEC_ENABLE_VPID |
3649 SECONDARY_EXEC_ENABLE_EPT |
3650 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3651 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3652 SECONDARY_EXEC_RDTSCP |
3653 SECONDARY_EXEC_ENABLE_INVPCID |
3654 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3655 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3656 SECONDARY_EXEC_SHADOW_VMCS |
3657 SECONDARY_EXEC_XSAVES |
3658 SECONDARY_EXEC_ENABLE_PML |
3659 SECONDARY_EXEC_TSC_SCALING;
3660 if (adjust_vmx_controls(min2, opt2,
3661 MSR_IA32_VMX_PROCBASED_CTLS2,
3662 &_cpu_based_2nd_exec_control) < 0)
3665 #ifndef CONFIG_X86_64
3666 if (!(_cpu_based_2nd_exec_control &
3667 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3668 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3671 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3672 _cpu_based_2nd_exec_control &= ~(
3673 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3674 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3675 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3677 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3678 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3680 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3681 CPU_BASED_CR3_STORE_EXITING |
3682 CPU_BASED_INVLPG_EXITING);
3683 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3684 vmx_capability.ept, vmx_capability.vpid);
3687 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3688 #ifdef CONFIG_X86_64
3689 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3691 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3692 VM_EXIT_CLEAR_BNDCFGS;
3693 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3694 &_vmexit_control) < 0)
3697 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3698 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3699 PIN_BASED_VMX_PREEMPTION_TIMER;
3700 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3701 &_pin_based_exec_control) < 0)
3704 if (cpu_has_broken_vmx_preemption_timer())
3705 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3706 if (!(_cpu_based_2nd_exec_control &
3707 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3708 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3710 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3711 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3712 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3713 &_vmentry_control) < 0)
3716 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3718 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3719 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3722 #ifdef CONFIG_X86_64
3723 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3724 if (vmx_msr_high & (1u<<16))
3728 /* Require Write-Back (WB) memory type for VMCS accesses. */
3729 if (((vmx_msr_high >> 18) & 15) != 6)
3732 vmcs_conf->size = vmx_msr_high & 0x1fff;
3733 vmcs_conf->order = get_order(vmcs_conf->size);
3734 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3735 vmcs_conf->revision_id = vmx_msr_low;
3737 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3738 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3739 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3740 vmcs_conf->vmexit_ctrl = _vmexit_control;
3741 vmcs_conf->vmentry_ctrl = _vmentry_control;
3743 cpu_has_load_ia32_efer =
3744 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3745 VM_ENTRY_LOAD_IA32_EFER)
3746 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3747 VM_EXIT_LOAD_IA32_EFER);
3749 cpu_has_load_perf_global_ctrl =
3750 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3751 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3752 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3753 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3756 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3757 * but due to errata below it can't be used. Workaround is to use
3758 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3760 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3765 * BC86,AAY89,BD102 (model 44)
3769 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3770 switch (boot_cpu_data.x86_model) {
3776 cpu_has_load_perf_global_ctrl = false;
3777 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3778 "does not work properly. Using workaround\n");
3785 if (boot_cpu_has(X86_FEATURE_XSAVES))
3786 rdmsrl(MSR_IA32_XSS, host_xss);
3791 static struct vmcs *alloc_vmcs_cpu(int cpu)
3793 int node = cpu_to_node(cpu);
3797 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3800 vmcs = page_address(pages);
3801 memset(vmcs, 0, vmcs_config.size);
3802 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3806 static void free_vmcs(struct vmcs *vmcs)
3808 free_pages((unsigned long)vmcs, vmcs_config.order);
3812 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3814 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3816 if (!loaded_vmcs->vmcs)
3818 loaded_vmcs_clear(loaded_vmcs);
3819 free_vmcs(loaded_vmcs->vmcs);
3820 loaded_vmcs->vmcs = NULL;
3821 if (loaded_vmcs->msr_bitmap)
3822 free_page((unsigned long)loaded_vmcs->msr_bitmap);
3823 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3826 static struct vmcs *alloc_vmcs(void)
3828 return alloc_vmcs_cpu(raw_smp_processor_id());
3831 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3833 loaded_vmcs->vmcs = alloc_vmcs();
3834 if (!loaded_vmcs->vmcs)
3837 loaded_vmcs->shadow_vmcs = NULL;
3838 loaded_vmcs_init(loaded_vmcs);
3840 if (cpu_has_vmx_msr_bitmap()) {
3841 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
3842 if (!loaded_vmcs->msr_bitmap)
3844 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
3849 free_loaded_vmcs(loaded_vmcs);
3853 static void free_kvm_area(void)
3857 for_each_possible_cpu(cpu) {
3858 free_vmcs(per_cpu(vmxarea, cpu));
3859 per_cpu(vmxarea, cpu) = NULL;
3863 static void init_vmcs_shadow_fields(void)
3867 /* No checks for read only fields yet */
3869 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3870 switch (shadow_read_write_fields[i]) {
3872 if (!kvm_mpx_supported())
3880 shadow_read_write_fields[j] =
3881 shadow_read_write_fields[i];
3884 max_shadow_read_write_fields = j;
3886 /* shadowed fields guest access without vmexit */
3887 for (i = 0; i < max_shadow_read_write_fields; i++) {
3888 clear_bit(shadow_read_write_fields[i],
3889 vmx_vmwrite_bitmap);
3890 clear_bit(shadow_read_write_fields[i],
3893 for (i = 0; i < max_shadow_read_only_fields; i++)
3894 clear_bit(shadow_read_only_fields[i],
3898 static __init int alloc_kvm_area(void)
3902 for_each_possible_cpu(cpu) {
3905 vmcs = alloc_vmcs_cpu(cpu);
3911 per_cpu(vmxarea, cpu) = vmcs;
3916 static bool emulation_required(struct kvm_vcpu *vcpu)
3918 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3921 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3922 struct kvm_segment *save)
3924 if (!emulate_invalid_guest_state) {
3926 * CS and SS RPL should be equal during guest entry according
3927 * to VMX spec, but in reality it is not always so. Since vcpu
3928 * is in the middle of the transition from real mode to
3929 * protected mode it is safe to assume that RPL 0 is a good
3932 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3933 save->selector &= ~SEGMENT_RPL_MASK;
3934 save->dpl = save->selector & SEGMENT_RPL_MASK;
3937 vmx_set_segment(vcpu, save, seg);
3940 static void enter_pmode(struct kvm_vcpu *vcpu)
3942 unsigned long flags;
3943 struct vcpu_vmx *vmx = to_vmx(vcpu);
3946 * Update real mode segment cache. It may be not up-to-date if sement
3947 * register was written while vcpu was in a guest mode.
3949 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3950 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3951 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3952 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3953 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3954 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3956 vmx->rmode.vm86_active = 0;
3958 vmx_segment_cache_clear(vmx);
3960 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3962 flags = vmcs_readl(GUEST_RFLAGS);
3963 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3964 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3965 vmcs_writel(GUEST_RFLAGS, flags);
3967 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3968 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3970 update_exception_bitmap(vcpu);
3972 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3973 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3974 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3975 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3976 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3977 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3980 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3982 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3983 struct kvm_segment var = *save;
3986 if (seg == VCPU_SREG_CS)
3989 if (!emulate_invalid_guest_state) {
3990 var.selector = var.base >> 4;
3991 var.base = var.base & 0xffff0;
4001 if (save->base & 0xf)
4002 printk_once(KERN_WARNING "kvm: segment base is not "
4003 "paragraph aligned when entering "
4004 "protected mode (seg=%d)", seg);
4007 vmcs_write16(sf->selector, var.selector);
4008 vmcs_writel(sf->base, var.base);
4009 vmcs_write32(sf->limit, var.limit);
4010 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4013 static void enter_rmode(struct kvm_vcpu *vcpu)
4015 unsigned long flags;
4016 struct vcpu_vmx *vmx = to_vmx(vcpu);
4018 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4019 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4020 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4021 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4022 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4023 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4024 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4026 vmx->rmode.vm86_active = 1;
4029 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4030 * vcpu. Warn the user that an update is overdue.
4032 if (!vcpu->kvm->arch.tss_addr)
4033 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4034 "called before entering vcpu\n");
4036 vmx_segment_cache_clear(vmx);
4038 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4039 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4040 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4042 flags = vmcs_readl(GUEST_RFLAGS);
4043 vmx->rmode.save_rflags = flags;
4045 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4047 vmcs_writel(GUEST_RFLAGS, flags);
4048 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4049 update_exception_bitmap(vcpu);
4051 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4052 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4053 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4054 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4055 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4056 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4058 kvm_mmu_reset_context(vcpu);
4061 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4063 struct vcpu_vmx *vmx = to_vmx(vcpu);
4064 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4070 * Force kernel_gs_base reloading before EFER changes, as control
4071 * of this msr depends on is_long_mode().
4073 vmx_load_host_state(to_vmx(vcpu));
4074 vcpu->arch.efer = efer;
4075 if (efer & EFER_LMA) {
4076 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4079 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4081 msr->data = efer & ~EFER_LME;
4086 #ifdef CONFIG_X86_64
4088 static void enter_lmode(struct kvm_vcpu *vcpu)
4092 vmx_segment_cache_clear(to_vmx(vcpu));
4094 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4095 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4096 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4098 vmcs_write32(GUEST_TR_AR_BYTES,
4099 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4100 | VMX_AR_TYPE_BUSY_64_TSS);
4102 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4105 static void exit_lmode(struct kvm_vcpu *vcpu)
4107 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4108 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4113 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
4115 vpid_sync_context(vpid);
4117 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4119 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
4123 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
4125 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
4128 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4131 vmx_flush_tlb(vcpu);
4134 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4136 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4138 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4139 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4142 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4144 if (enable_ept && is_paging(vcpu))
4145 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4146 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4149 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4151 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4153 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4154 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4157 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4159 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4161 if (!test_bit(VCPU_EXREG_PDPTR,
4162 (unsigned long *)&vcpu->arch.regs_dirty))
4165 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4166 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4167 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4168 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4169 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4173 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4175 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4177 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4178 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4179 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4180 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4181 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4184 __set_bit(VCPU_EXREG_PDPTR,
4185 (unsigned long *)&vcpu->arch.regs_avail);
4186 __set_bit(VCPU_EXREG_PDPTR,
4187 (unsigned long *)&vcpu->arch.regs_dirty);
4190 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4192 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4194 struct kvm_vcpu *vcpu)
4196 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4197 vmx_decache_cr3(vcpu);
4198 if (!(cr0 & X86_CR0_PG)) {
4199 /* From paging/starting to nonpaging */
4200 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4201 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4202 (CPU_BASED_CR3_LOAD_EXITING |
4203 CPU_BASED_CR3_STORE_EXITING));
4204 vcpu->arch.cr0 = cr0;
4205 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4206 } else if (!is_paging(vcpu)) {
4207 /* From nonpaging to paging */
4208 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4209 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4210 ~(CPU_BASED_CR3_LOAD_EXITING |
4211 CPU_BASED_CR3_STORE_EXITING));
4212 vcpu->arch.cr0 = cr0;
4213 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4216 if (!(cr0 & X86_CR0_WP))
4217 *hw_cr0 &= ~X86_CR0_WP;
4220 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4222 struct vcpu_vmx *vmx = to_vmx(vcpu);
4223 unsigned long hw_cr0;
4225 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4226 if (enable_unrestricted_guest)
4227 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4229 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4231 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4234 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4238 #ifdef CONFIG_X86_64
4239 if (vcpu->arch.efer & EFER_LME) {
4240 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4242 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4248 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4250 if (!vcpu->fpu_active)
4251 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
4253 vmcs_writel(CR0_READ_SHADOW, cr0);
4254 vmcs_writel(GUEST_CR0, hw_cr0);
4255 vcpu->arch.cr0 = cr0;
4257 /* depends on vcpu->arch.cr0 to be set to a new value */
4258 vmx->emulation_required = emulation_required(vcpu);
4261 static u64 construct_eptp(unsigned long root_hpa)
4265 /* TODO write the value reading from MSR */
4266 eptp = VMX_EPT_DEFAULT_MT |
4267 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
4268 if (enable_ept_ad_bits)
4269 eptp |= VMX_EPT_AD_ENABLE_BIT;
4270 eptp |= (root_hpa & PAGE_MASK);
4275 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4277 unsigned long guest_cr3;
4282 eptp = construct_eptp(cr3);
4283 vmcs_write64(EPT_POINTER, eptp);
4284 if (is_paging(vcpu) || is_guest_mode(vcpu))
4285 guest_cr3 = kvm_read_cr3(vcpu);
4287 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4288 ept_load_pdptrs(vcpu);
4291 vmx_flush_tlb(vcpu);
4292 vmcs_writel(GUEST_CR3, guest_cr3);
4295 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4298 * Pass through host's Machine Check Enable value to hw_cr4, which
4299 * is in force while we are in guest mode. Do not let guests control
4300 * this bit, even if host CR4.MCE == 0.
4302 unsigned long hw_cr4 =
4303 (cr4_read_shadow() & X86_CR4_MCE) |
4304 (cr4 & ~X86_CR4_MCE) |
4305 (to_vmx(vcpu)->rmode.vm86_active ?
4306 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4308 if (cr4 & X86_CR4_VMXE) {
4310 * To use VMXON (and later other VMX instructions), a guest
4311 * must first be able to turn on cr4.VMXE (see handle_vmon()).
4312 * So basically the check on whether to allow nested VMX
4315 if (!nested_vmx_allowed(vcpu))
4318 if (to_vmx(vcpu)->nested.vmxon &&
4319 ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
4322 vcpu->arch.cr4 = cr4;
4324 if (!is_paging(vcpu)) {
4325 hw_cr4 &= ~X86_CR4_PAE;
4326 hw_cr4 |= X86_CR4_PSE;
4327 } else if (!(cr4 & X86_CR4_PAE)) {
4328 hw_cr4 &= ~X86_CR4_PAE;
4332 if (!enable_unrestricted_guest && !is_paging(vcpu))
4334 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4335 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
4336 * to be manually disabled when guest switches to non-paging
4339 * If !enable_unrestricted_guest, the CPU is always running
4340 * with CR0.PG=1 and CR4 needs to be modified.
4341 * If enable_unrestricted_guest, the CPU automatically
4342 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4344 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4346 vmcs_writel(CR4_READ_SHADOW, cr4);
4347 vmcs_writel(GUEST_CR4, hw_cr4);
4351 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4352 struct kvm_segment *var, int seg)
4354 struct vcpu_vmx *vmx = to_vmx(vcpu);
4357 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4358 *var = vmx->rmode.segs[seg];
4359 if (seg == VCPU_SREG_TR
4360 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4362 var->base = vmx_read_guest_seg_base(vmx, seg);
4363 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4366 var->base = vmx_read_guest_seg_base(vmx, seg);
4367 var->limit = vmx_read_guest_seg_limit(vmx, seg);
4368 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4369 ar = vmx_read_guest_seg_ar(vmx, seg);
4370 var->unusable = (ar >> 16) & 1;
4371 var->type = ar & 15;
4372 var->s = (ar >> 4) & 1;
4373 var->dpl = (ar >> 5) & 3;
4375 * Some userspaces do not preserve unusable property. Since usable
4376 * segment has to be present according to VMX spec we can use present
4377 * property to amend userspace bug by making unusable segment always
4378 * nonpresent. vmx_segment_access_rights() already marks nonpresent
4379 * segment as unusable.
4381 var->present = !var->unusable;
4382 var->avl = (ar >> 12) & 1;
4383 var->l = (ar >> 13) & 1;
4384 var->db = (ar >> 14) & 1;
4385 var->g = (ar >> 15) & 1;
4388 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4390 struct kvm_segment s;
4392 if (to_vmx(vcpu)->rmode.vm86_active) {
4393 vmx_get_segment(vcpu, &s, seg);
4396 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4399 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4401 struct vcpu_vmx *vmx = to_vmx(vcpu);
4403 if (unlikely(vmx->rmode.vm86_active))
4406 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4407 return VMX_AR_DPL(ar);
4411 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4415 if (var->unusable || !var->present)
4418 ar = var->type & 15;
4419 ar |= (var->s & 1) << 4;
4420 ar |= (var->dpl & 3) << 5;
4421 ar |= (var->present & 1) << 7;
4422 ar |= (var->avl & 1) << 12;
4423 ar |= (var->l & 1) << 13;
4424 ar |= (var->db & 1) << 14;
4425 ar |= (var->g & 1) << 15;
4431 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4432 struct kvm_segment *var, int seg)
4434 struct vcpu_vmx *vmx = to_vmx(vcpu);
4435 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4437 vmx_segment_cache_clear(vmx);
4439 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4440 vmx->rmode.segs[seg] = *var;
4441 if (seg == VCPU_SREG_TR)
4442 vmcs_write16(sf->selector, var->selector);
4444 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4448 vmcs_writel(sf->base, var->base);
4449 vmcs_write32(sf->limit, var->limit);
4450 vmcs_write16(sf->selector, var->selector);
4453 * Fix the "Accessed" bit in AR field of segment registers for older
4455 * IA32 arch specifies that at the time of processor reset the
4456 * "Accessed" bit in the AR field of segment registers is 1. And qemu
4457 * is setting it to 0 in the userland code. This causes invalid guest
4458 * state vmexit when "unrestricted guest" mode is turned on.
4459 * Fix for this setup issue in cpu_reset is being pushed in the qemu
4460 * tree. Newer qemu binaries with that qemu fix would not need this
4463 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4464 var->type |= 0x1; /* Accessed */
4466 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4469 vmx->emulation_required = emulation_required(vcpu);
4472 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4474 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4476 *db = (ar >> 14) & 1;
4477 *l = (ar >> 13) & 1;
4480 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4482 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4483 dt->address = vmcs_readl(GUEST_IDTR_BASE);
4486 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4488 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4489 vmcs_writel(GUEST_IDTR_BASE, dt->address);
4492 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4494 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4495 dt->address = vmcs_readl(GUEST_GDTR_BASE);
4498 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4500 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4501 vmcs_writel(GUEST_GDTR_BASE, dt->address);
4504 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4506 struct kvm_segment var;
4509 vmx_get_segment(vcpu, &var, seg);
4511 if (seg == VCPU_SREG_CS)
4513 ar = vmx_segment_access_rights(&var);
4515 if (var.base != (var.selector << 4))
4517 if (var.limit != 0xffff)
4525 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4527 struct kvm_segment cs;
4528 unsigned int cs_rpl;
4530 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4531 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4535 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4539 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4540 if (cs.dpl > cs_rpl)
4543 if (cs.dpl != cs_rpl)
4549 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4553 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4555 struct kvm_segment ss;
4556 unsigned int ss_rpl;
4558 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4559 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4563 if (ss.type != 3 && ss.type != 7)
4567 if (ss.dpl != ss_rpl) /* DPL != RPL */
4575 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4577 struct kvm_segment var;
4580 vmx_get_segment(vcpu, &var, seg);
4581 rpl = var.selector & SEGMENT_RPL_MASK;
4589 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4590 if (var.dpl < rpl) /* DPL < RPL */
4594 /* TODO: Add other members to kvm_segment_field to allow checking for other access
4600 static bool tr_valid(struct kvm_vcpu *vcpu)
4602 struct kvm_segment tr;
4604 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4608 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4610 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4618 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4620 struct kvm_segment ldtr;
4622 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4626 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4636 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4638 struct kvm_segment cs, ss;
4640 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4641 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4643 return ((cs.selector & SEGMENT_RPL_MASK) ==
4644 (ss.selector & SEGMENT_RPL_MASK));
4648 * Check if guest state is valid. Returns true if valid, false if
4650 * We assume that registers are always usable
4652 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4654 if (enable_unrestricted_guest)
4657 /* real mode guest state checks */
4658 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4659 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4661 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4663 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4665 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4667 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4669 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4672 /* protected mode guest state checks */
4673 if (!cs_ss_rpl_check(vcpu))
4675 if (!code_segment_valid(vcpu))
4677 if (!stack_segment_valid(vcpu))
4679 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4681 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4683 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4685 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4687 if (!tr_valid(vcpu))
4689 if (!ldtr_valid(vcpu))
4693 * - Add checks on RIP
4694 * - Add checks on RFLAGS
4700 static int init_rmode_tss(struct kvm *kvm)
4706 idx = srcu_read_lock(&kvm->srcu);
4707 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4708 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4711 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4712 r = kvm_write_guest_page(kvm, fn++, &data,
4713 TSS_IOPB_BASE_OFFSET, sizeof(u16));
4716 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4719 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4723 r = kvm_write_guest_page(kvm, fn, &data,
4724 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4727 srcu_read_unlock(&kvm->srcu, idx);
4731 static int init_rmode_identity_map(struct kvm *kvm)
4734 kvm_pfn_t identity_map_pfn;
4740 /* Protect kvm->arch.ept_identity_pagetable_done. */
4741 mutex_lock(&kvm->slots_lock);
4743 if (likely(kvm->arch.ept_identity_pagetable_done))
4746 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4748 r = alloc_identity_pagetable(kvm);
4752 idx = srcu_read_lock(&kvm->srcu);
4753 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4756 /* Set up identity-mapping pagetable for EPT in real mode */
4757 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4758 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4759 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4760 r = kvm_write_guest_page(kvm, identity_map_pfn,
4761 &tmp, i * sizeof(tmp), sizeof(tmp));
4765 kvm->arch.ept_identity_pagetable_done = true;
4768 srcu_read_unlock(&kvm->srcu, idx);
4771 mutex_unlock(&kvm->slots_lock);
4775 static void seg_setup(int seg)
4777 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4780 vmcs_write16(sf->selector, 0);
4781 vmcs_writel(sf->base, 0);
4782 vmcs_write32(sf->limit, 0xffff);
4784 if (seg == VCPU_SREG_CS)
4785 ar |= 0x08; /* code segment */
4787 vmcs_write32(sf->ar_bytes, ar);
4790 static int alloc_apic_access_page(struct kvm *kvm)
4795 mutex_lock(&kvm->slots_lock);
4796 if (kvm->arch.apic_access_page_done)
4798 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4799 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4803 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4804 if (is_error_page(page)) {
4810 * Do not pin the page in memory, so that memory hot-unplug
4811 * is able to migrate it.
4814 kvm->arch.apic_access_page_done = true;
4816 mutex_unlock(&kvm->slots_lock);
4820 static int alloc_identity_pagetable(struct kvm *kvm)
4822 /* Called with kvm->slots_lock held. */
4826 BUG_ON(kvm->arch.ept_identity_pagetable_done);
4828 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4829 kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4834 static int allocate_vpid(void)
4840 spin_lock(&vmx_vpid_lock);
4841 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4842 if (vpid < VMX_NR_VPIDS)
4843 __set_bit(vpid, vmx_vpid_bitmap);
4846 spin_unlock(&vmx_vpid_lock);
4850 static void free_vpid(int vpid)
4852 if (!enable_vpid || vpid == 0)
4854 spin_lock(&vmx_vpid_lock);
4855 __clear_bit(vpid, vmx_vpid_bitmap);
4856 spin_unlock(&vmx_vpid_lock);
4859 static void __always_inline vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4862 int f = sizeof(unsigned long);
4864 if (!cpu_has_vmx_msr_bitmap())
4868 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4869 * have the write-low and read-high bitmap offsets the wrong way round.
4870 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4872 if (msr <= 0x1fff) {
4873 if (type & MSR_TYPE_R)
4875 __clear_bit(msr, msr_bitmap + 0x000 / f);
4877 if (type & MSR_TYPE_W)
4879 __clear_bit(msr, msr_bitmap + 0x800 / f);
4881 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4883 if (type & MSR_TYPE_R)
4885 __clear_bit(msr, msr_bitmap + 0x400 / f);
4887 if (type & MSR_TYPE_W)
4889 __clear_bit(msr, msr_bitmap + 0xc00 / f);
4894 static void __always_inline vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4897 int f = sizeof(unsigned long);
4899 if (!cpu_has_vmx_msr_bitmap())
4903 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4904 * have the write-low and read-high bitmap offsets the wrong way round.
4905 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4907 if (msr <= 0x1fff) {
4908 if (type & MSR_TYPE_R)
4910 __set_bit(msr, msr_bitmap + 0x000 / f);
4912 if (type & MSR_TYPE_W)
4914 __set_bit(msr, msr_bitmap + 0x800 / f);
4916 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4918 if (type & MSR_TYPE_R)
4920 __set_bit(msr, msr_bitmap + 0x400 / f);
4922 if (type & MSR_TYPE_W)
4924 __set_bit(msr, msr_bitmap + 0xc00 / f);
4929 static void __always_inline vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
4930 u32 msr, int type, bool value)
4933 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
4935 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
4939 * If a msr is allowed by L0, we should check whether it is allowed by L1.
4940 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4942 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4943 unsigned long *msr_bitmap_nested,
4946 int f = sizeof(unsigned long);
4948 if (!cpu_has_vmx_msr_bitmap()) {
4954 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4955 * have the write-low and read-high bitmap offsets the wrong way round.
4956 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4958 if (msr <= 0x1fff) {
4959 if (type & MSR_TYPE_R &&
4960 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4962 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4964 if (type & MSR_TYPE_W &&
4965 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4967 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4969 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4971 if (type & MSR_TYPE_R &&
4972 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4974 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4976 if (type & MSR_TYPE_W &&
4977 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4979 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
4984 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
4988 if (cpu_has_secondary_exec_ctrls() &&
4989 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
4990 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4991 mode |= MSR_BITMAP_MODE_X2APIC;
4992 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4993 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4996 if (is_long_mode(vcpu))
4997 mode |= MSR_BITMAP_MODE_LM;
5002 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5004 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5009 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5010 unsigned word = msr / BITS_PER_LONG;
5011 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5012 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5015 if (mode & MSR_BITMAP_MODE_X2APIC) {
5017 * TPR reads and writes can be virtualized even if virtual interrupt
5018 * delivery is not in use.
5020 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5021 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5022 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5023 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5024 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5029 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5031 struct vcpu_vmx *vmx = to_vmx(vcpu);
5032 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5033 u8 mode = vmx_msr_bitmap_mode(vcpu);
5034 u8 changed = mode ^ vmx->msr_bitmap_mode;
5039 vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5040 !(mode & MSR_BITMAP_MODE_LM));
5042 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5043 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5045 vmx->msr_bitmap_mode = mode;
5048 static bool vmx_get_enable_apicv(void)
5050 return enable_apicv;
5053 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5055 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5059 * Don't need to mark the APIC access page dirty; it is never
5060 * written to by the CPU during APIC virtualization.
5063 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5064 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5065 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5068 if (nested_cpu_has_posted_intr(vmcs12)) {
5069 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5070 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5075 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5077 struct vcpu_vmx *vmx = to_vmx(vcpu);
5082 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5085 vmx->nested.pi_pending = false;
5086 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5089 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5090 if (max_irr != 256) {
5091 vapic_page = kmap(vmx->nested.virtual_apic_page);
5092 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5093 kunmap(vmx->nested.virtual_apic_page);
5095 status = vmcs_read16(GUEST_INTR_STATUS);
5096 if ((u8)max_irr > ((u8)status & 0xff)) {
5098 status |= (u8)max_irr;
5099 vmcs_write16(GUEST_INTR_STATUS, status);
5103 nested_mark_vmcs12_pages_dirty(vcpu);
5106 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
5109 if (vcpu->mode == IN_GUEST_MODE) {
5111 * The vector of interrupt to be delivered to vcpu had
5112 * been set in PIR before this function.
5114 * Following cases will be reached in this block, and
5115 * we always send a notification event in all cases as
5118 * Case 1: vcpu keeps in non-root mode. Sending a
5119 * notification event posts the interrupt to vcpu.
5121 * Case 2: vcpu exits to root mode and is still
5122 * runnable. PIR will be synced to vIRR before the
5123 * next vcpu entry. Sending a notification event in
5124 * this case has no effect, as vcpu is not in root
5127 * Case 3: vcpu exits to root mode and is blocked.
5128 * vcpu_block() has already synced PIR to vIRR and
5129 * never blocks vcpu if vIRR is not cleared. Therefore,
5130 * a blocked vcpu here does not wait for any requested
5131 * interrupts in PIR, and sending a notification event
5132 * which has no effect is safe here.
5135 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
5136 POSTED_INTR_VECTOR);
5143 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5146 struct vcpu_vmx *vmx = to_vmx(vcpu);
5148 if (is_guest_mode(vcpu) &&
5149 vector == vmx->nested.posted_intr_nv) {
5151 * If a posted intr is not recognized by hardware,
5152 * we will accomplish it in the next vmentry.
5154 vmx->nested.pi_pending = true;
5155 kvm_make_request(KVM_REQ_EVENT, vcpu);
5156 /* the PIR and ON have been set by L1. */
5157 if (!kvm_vcpu_trigger_posted_interrupt(vcpu))
5158 kvm_vcpu_kick(vcpu);
5164 * Send interrupt to vcpu via posted interrupt way.
5165 * 1. If target vcpu is running(non-root mode), send posted interrupt
5166 * notification to vcpu and hardware will sync PIR to vIRR atomically.
5167 * 2. If target vcpu isn't running(root mode), kick it to pick up the
5168 * interrupt from PIR in next vmentry.
5170 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5172 struct vcpu_vmx *vmx = to_vmx(vcpu);
5175 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5179 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5182 r = pi_test_and_set_on(&vmx->pi_desc);
5183 kvm_make_request(KVM_REQ_EVENT, vcpu);
5184 if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
5185 kvm_vcpu_kick(vcpu);
5188 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
5190 struct vcpu_vmx *vmx = to_vmx(vcpu);
5192 if (!pi_test_and_clear_on(&vmx->pi_desc))
5195 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
5199 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5200 * will not change in the lifetime of the guest.
5201 * Note that host-state that does change is set elsewhere. E.g., host-state
5202 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5204 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5211 vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
5212 vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
5214 /* Save the most likely value for this task's CR4 in the VMCS. */
5215 cr4 = cr4_read_shadow();
5216 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
5217 vmx->host_state.vmcs_host_cr4 = cr4;
5219 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
5220 #ifdef CONFIG_X86_64
5222 * Load null selectors, so we can avoid reloading them in
5223 * __vmx_load_host_state(), in case userspace uses the null selectors
5224 * too (the expected case).
5226 vmcs_write16(HOST_DS_SELECTOR, 0);
5227 vmcs_write16(HOST_ES_SELECTOR, 0);
5229 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5230 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5232 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5233 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
5235 native_store_idt(&dt);
5236 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
5237 vmx->host_idt_base = dt.address;
5239 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5241 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5242 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5243 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5244 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
5246 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5247 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5248 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5252 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5254 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5256 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5257 if (is_guest_mode(&vmx->vcpu))
5258 vmx->vcpu.arch.cr4_guest_owned_bits &=
5259 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5260 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5263 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5265 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5267 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5268 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5269 /* Enable the preemption timer dynamically */
5270 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5271 return pin_based_exec_ctrl;
5274 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5276 struct vcpu_vmx *vmx = to_vmx(vcpu);
5278 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5279 if (cpu_has_secondary_exec_ctrls()) {
5280 if (kvm_vcpu_apicv_active(vcpu))
5281 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5282 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5283 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5285 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5286 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5287 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5290 if (cpu_has_vmx_msr_bitmap())
5291 vmx_update_msr_bitmap(vcpu);
5294 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5296 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5298 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5299 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5301 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5302 exec_control &= ~CPU_BASED_TPR_SHADOW;
5303 #ifdef CONFIG_X86_64
5304 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5305 CPU_BASED_CR8_LOAD_EXITING;
5309 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5310 CPU_BASED_CR3_LOAD_EXITING |
5311 CPU_BASED_INVLPG_EXITING;
5312 return exec_control;
5315 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
5317 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5318 if (!cpu_need_virtualize_apic_accesses(&vmx->vcpu))
5319 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5321 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5323 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5324 enable_unrestricted_guest = 0;
5325 /* Enable INVPCID for non-ept guests may cause performance regression. */
5326 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5328 if (!enable_unrestricted_guest)
5329 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5331 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5332 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5333 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5334 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5335 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5336 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5338 We can NOT enable shadow_vmcs here because we don't have yet
5341 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5344 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5346 return exec_control;
5349 static void ept_set_mmio_spte_mask(void)
5352 * EPT Misconfigurations can be generated if the value of bits 2:0
5353 * of an EPT paging-structure entry is 110b (write/execute).
5354 * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
5357 kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
5360 #define VMX_XSS_EXIT_BITMAP 0
5362 * Sets up the vmcs for emulated real mode.
5364 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
5366 #ifdef CONFIG_X86_64
5372 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5373 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5375 if (enable_shadow_vmcs) {
5376 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5377 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5379 if (cpu_has_vmx_msr_bitmap())
5380 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5382 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5385 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5386 vmx->hv_deadline_tsc = -1;
5388 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5390 if (cpu_has_secondary_exec_ctrls()) {
5391 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5392 vmx_secondary_exec_control(vmx));
5395 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5396 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5397 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5398 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5399 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5401 vmcs_write16(GUEST_INTR_STATUS, 0);
5403 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5404 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5408 vmcs_write32(PLE_GAP, ple_gap);
5409 vmx->ple_window = ple_window;
5410 vmx->ple_window_dirty = true;
5413 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5414 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5415 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
5417 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
5418 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
5419 vmx_set_constant_host_state(vmx);
5420 #ifdef CONFIG_X86_64
5421 rdmsrl(MSR_FS_BASE, a);
5422 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5423 rdmsrl(MSR_GS_BASE, a);
5424 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5426 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5427 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5430 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5431 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5432 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
5433 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5434 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
5436 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5437 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5439 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5440 u32 index = vmx_msr_index[i];
5441 u32 data_low, data_high;
5444 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5446 if (wrmsr_safe(index, data_low, data_high) < 0)
5448 vmx->guest_msrs[j].index = i;
5449 vmx->guest_msrs[j].data = 0;
5450 vmx->guest_msrs[j].mask = -1ull;
5454 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES))
5455 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, vmx->arch_capabilities);
5457 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5459 /* 22.2.1, 20.8.1 */
5460 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5462 vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
5463 set_cr4_guest_host_mask(vmx);
5465 if (vmx_xsaves_supported())
5466 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5469 ASSERT(vmx->pml_pg);
5470 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5471 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5477 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5479 struct vcpu_vmx *vmx = to_vmx(vcpu);
5480 struct msr_data apic_base_msr;
5483 vmx->rmode.vm86_active = 0;
5486 vmx->soft_vnmi_blocked = 0;
5488 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5489 kvm_set_cr8(vcpu, 0);
5492 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5493 MSR_IA32_APICBASE_ENABLE;
5494 if (kvm_vcpu_is_reset_bsp(vcpu))
5495 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5496 apic_base_msr.host_initiated = true;
5497 kvm_set_apic_base(vcpu, &apic_base_msr);
5500 vmx_segment_cache_clear(vmx);
5502 seg_setup(VCPU_SREG_CS);
5503 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5504 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5506 seg_setup(VCPU_SREG_DS);
5507 seg_setup(VCPU_SREG_ES);
5508 seg_setup(VCPU_SREG_FS);
5509 seg_setup(VCPU_SREG_GS);
5510 seg_setup(VCPU_SREG_SS);
5512 vmcs_write16(GUEST_TR_SELECTOR, 0);
5513 vmcs_writel(GUEST_TR_BASE, 0);
5514 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5515 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5517 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5518 vmcs_writel(GUEST_LDTR_BASE, 0);
5519 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5520 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5523 vmcs_write32(GUEST_SYSENTER_CS, 0);
5524 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5525 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5526 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5529 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5530 kvm_rip_write(vcpu, 0xfff0);
5532 vmcs_writel(GUEST_GDTR_BASE, 0);
5533 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5535 vmcs_writel(GUEST_IDTR_BASE, 0);
5536 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5538 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5539 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5540 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5544 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
5546 if (cpu_has_vmx_tpr_shadow() && !init_event) {
5547 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5548 if (cpu_need_tpr_shadow(vcpu))
5549 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5550 __pa(vcpu->arch.apic->regs));
5551 vmcs_write32(TPR_THRESHOLD, 0);
5554 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5556 if (kvm_vcpu_apicv_active(vcpu))
5557 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
5560 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5562 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5563 vmx->vcpu.arch.cr0 = cr0;
5564 vmx_set_cr0(vcpu, cr0); /* enter rmode */
5565 vmx_set_cr4(vcpu, 0);
5566 vmx_set_efer(vcpu, 0);
5567 vmx_fpu_activate(vcpu);
5568 update_exception_bitmap(vcpu);
5570 vpid_sync_context(vmx->vpid);
5574 * In nested virtualization, check if L1 asked to exit on external interrupts.
5575 * For most existing hypervisors, this will always return true.
5577 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5579 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5580 PIN_BASED_EXT_INTR_MASK;
5584 * In nested virtualization, check if L1 has set
5585 * VM_EXIT_ACK_INTR_ON_EXIT
5587 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5589 return get_vmcs12(vcpu)->vm_exit_controls &
5590 VM_EXIT_ACK_INTR_ON_EXIT;
5593 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5595 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5596 PIN_BASED_NMI_EXITING;
5599 static void enable_irq_window(struct kvm_vcpu *vcpu)
5601 u32 cpu_based_vm_exec_control;
5603 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5604 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
5605 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5608 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5610 u32 cpu_based_vm_exec_control;
5612 if (!cpu_has_virtual_nmis() ||
5613 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5614 enable_irq_window(vcpu);
5618 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5619 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
5620 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5623 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5625 struct vcpu_vmx *vmx = to_vmx(vcpu);
5627 int irq = vcpu->arch.interrupt.nr;
5629 trace_kvm_inj_virq(irq);
5631 ++vcpu->stat.irq_injections;
5632 if (vmx->rmode.vm86_active) {
5634 if (vcpu->arch.interrupt.soft)
5635 inc_eip = vcpu->arch.event_exit_inst_len;
5636 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5637 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5640 intr = irq | INTR_INFO_VALID_MASK;
5641 if (vcpu->arch.interrupt.soft) {
5642 intr |= INTR_TYPE_SOFT_INTR;
5643 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5644 vmx->vcpu.arch.event_exit_inst_len);
5646 intr |= INTR_TYPE_EXT_INTR;
5647 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5650 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5652 struct vcpu_vmx *vmx = to_vmx(vcpu);
5654 if (!is_guest_mode(vcpu)) {
5655 if (!cpu_has_virtual_nmis()) {
5657 * Tracking the NMI-blocked state in software is built upon
5658 * finding the next open IRQ window. This, in turn, depends on
5659 * well-behaving guests: They have to keep IRQs disabled at
5660 * least as long as the NMI handler runs. Otherwise we may
5661 * cause NMI nesting, maybe breaking the guest. But as this is
5662 * highly unlikely, we can live with the residual risk.
5664 vmx->soft_vnmi_blocked = 1;
5665 vmx->vnmi_blocked_time = 0;
5668 ++vcpu->stat.nmi_injections;
5669 vmx->nmi_known_unmasked = false;
5672 if (vmx->rmode.vm86_active) {
5673 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5674 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5678 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5679 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5682 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5684 if (!cpu_has_virtual_nmis())
5685 return to_vmx(vcpu)->soft_vnmi_blocked;
5686 if (to_vmx(vcpu)->nmi_known_unmasked)
5688 return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5691 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5693 struct vcpu_vmx *vmx = to_vmx(vcpu);
5695 if (!cpu_has_virtual_nmis()) {
5696 if (vmx->soft_vnmi_blocked != masked) {
5697 vmx->soft_vnmi_blocked = masked;
5698 vmx->vnmi_blocked_time = 0;
5701 vmx->nmi_known_unmasked = !masked;
5703 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5704 GUEST_INTR_STATE_NMI);
5706 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5707 GUEST_INTR_STATE_NMI);
5711 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5713 if (to_vmx(vcpu)->nested.nested_run_pending)
5716 if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
5719 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5720 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5721 | GUEST_INTR_STATE_NMI));
5724 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5726 return (!to_vmx(vcpu)->nested.nested_run_pending &&
5727 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
5728 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5729 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5732 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5736 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5740 kvm->arch.tss_addr = addr;
5741 return init_rmode_tss(kvm);
5744 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5749 * Update instruction length as we may reinject the exception
5750 * from user space while in guest debugging mode.
5752 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5753 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5754 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5758 if (vcpu->guest_debug &
5759 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5776 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5777 int vec, u32 err_code)
5780 * Instruction with address size override prefix opcode 0x67
5781 * Cause the #SS fault with 0 error code in VM86 mode.
5783 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5784 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5785 if (vcpu->arch.halt_request) {
5786 vcpu->arch.halt_request = 0;
5787 return kvm_vcpu_halt(vcpu);
5795 * Forward all other exceptions that are valid in real mode.
5796 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5797 * the required debugging infrastructure rework.
5799 kvm_queue_exception(vcpu, vec);
5804 * Trigger machine check on the host. We assume all the MSRs are already set up
5805 * by the CPU and that we still run on the same CPU as the MCE occurred on.
5806 * We pass a fake environment to the machine check handler because we want
5807 * the guest to be always treated like user space, no matter what context
5808 * it used internally.
5810 static void kvm_machine_check(void)
5812 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5813 struct pt_regs regs = {
5814 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5815 .flags = X86_EFLAGS_IF,
5818 do_machine_check(®s, 0);
5822 static int handle_machine_check(struct kvm_vcpu *vcpu)
5824 /* already handled by vcpu_run */
5828 static int handle_exception(struct kvm_vcpu *vcpu)
5830 struct vcpu_vmx *vmx = to_vmx(vcpu);
5831 struct kvm_run *kvm_run = vcpu->run;
5832 u32 intr_info, ex_no, error_code;
5833 unsigned long cr2, rip, dr6;
5835 enum emulation_result er;
5837 vect_info = vmx->idt_vectoring_info;
5838 intr_info = vmx->exit_intr_info;
5840 if (is_machine_check(intr_info))
5841 return handle_machine_check(vcpu);
5843 if (is_nmi(intr_info))
5844 return 1; /* already handled by vmx_vcpu_run() */
5846 if (is_no_device(intr_info)) {
5847 vmx_fpu_activate(vcpu);
5851 if (is_invalid_opcode(intr_info)) {
5852 if (is_guest_mode(vcpu)) {
5853 kvm_queue_exception(vcpu, UD_VECTOR);
5856 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5857 if (er == EMULATE_USER_EXIT)
5859 if (er != EMULATE_DONE)
5860 kvm_queue_exception(vcpu, UD_VECTOR);
5865 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5866 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5869 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5870 * MMIO, it is better to report an internal error.
5871 * See the comments in vmx_handle_exit.
5873 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5874 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5875 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5876 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5877 vcpu->run->internal.ndata = 3;
5878 vcpu->run->internal.data[0] = vect_info;
5879 vcpu->run->internal.data[1] = intr_info;
5880 vcpu->run->internal.data[2] = error_code;
5884 if (is_page_fault(intr_info)) {
5885 /* EPT won't cause page fault directly */
5887 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5888 trace_kvm_page_fault(cr2, error_code);
5889 vcpu->arch.l1tf_flush_l1d = true;
5891 if (kvm_event_needs_reinjection(vcpu))
5892 kvm_mmu_unprotect_page_virt(vcpu, cr2);
5893 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
5896 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5898 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5899 return handle_rmode_exception(vcpu, ex_no, error_code);
5903 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5906 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5907 if (!(vcpu->guest_debug &
5908 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5909 vcpu->arch.dr6 &= ~15;
5910 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5911 if (is_icebp(intr_info))
5912 skip_emulated_instruction(vcpu);
5914 kvm_queue_exception(vcpu, DB_VECTOR);
5917 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5918 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5922 * Update instruction length as we may reinject #BP from
5923 * user space while in guest debugging mode. Reading it for
5924 * #DB as well causes no harm, it is not used in that case.
5926 vmx->vcpu.arch.event_exit_inst_len =
5927 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5928 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5929 rip = kvm_rip_read(vcpu);
5930 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5931 kvm_run->debug.arch.exception = ex_no;
5934 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5935 kvm_run->ex.exception = ex_no;
5936 kvm_run->ex.error_code = error_code;
5942 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
5944 ++vcpu->stat.irq_exits;
5948 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5950 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5954 static int handle_io(struct kvm_vcpu *vcpu)
5956 unsigned long exit_qualification;
5957 int size, in, string;
5960 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5961 string = (exit_qualification & 16) != 0;
5962 in = (exit_qualification & 8) != 0;
5964 ++vcpu->stat.io_exits;
5967 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5969 port = exit_qualification >> 16;
5970 size = (exit_qualification & 7) + 1;
5971 skip_emulated_instruction(vcpu);
5973 return kvm_fast_pio_out(vcpu, size, port);
5977 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5980 * Patch in the VMCALL instruction:
5982 hypercall[0] = 0x0f;
5983 hypercall[1] = 0x01;
5984 hypercall[2] = 0xc1;
5987 static bool nested_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5989 unsigned long always_on = VMXON_CR0_ALWAYSON;
5990 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5992 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
5993 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5994 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5995 always_on &= ~(X86_CR0_PE | X86_CR0_PG);
5996 return (val & always_on) == always_on;
5999 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6000 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6002 if (is_guest_mode(vcpu)) {
6003 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6004 unsigned long orig_val = val;
6007 * We get here when L2 changed cr0 in a way that did not change
6008 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6009 * but did change L0 shadowed bits. So we first calculate the
6010 * effective cr0 value that L1 would like to write into the
6011 * hardware. It consists of the L2-owned bits from the new
6012 * value combined with the L1-owned bits from L1's guest_cr0.
6014 val = (val & ~vmcs12->cr0_guest_host_mask) |
6015 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6017 if (!nested_cr0_valid(vcpu, val))
6020 if (kvm_set_cr0(vcpu, val))
6022 vmcs_writel(CR0_READ_SHADOW, orig_val);
6025 if (to_vmx(vcpu)->nested.vmxon &&
6026 ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
6028 return kvm_set_cr0(vcpu, val);
6032 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6034 if (is_guest_mode(vcpu)) {
6035 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6036 unsigned long orig_val = val;
6038 /* analogously to handle_set_cr0 */
6039 val = (val & ~vmcs12->cr4_guest_host_mask) |
6040 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6041 if (kvm_set_cr4(vcpu, val))
6043 vmcs_writel(CR4_READ_SHADOW, orig_val);
6046 return kvm_set_cr4(vcpu, val);
6049 /* called to set cr0 as appropriate for clts instruction exit. */
6050 static void handle_clts(struct kvm_vcpu *vcpu)
6052 if (is_guest_mode(vcpu)) {
6054 * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
6055 * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
6056 * just pretend it's off (also in arch.cr0 for fpu_activate).
6058 vmcs_writel(CR0_READ_SHADOW,
6059 vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
6060 vcpu->arch.cr0 &= ~X86_CR0_TS;
6062 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6065 static int handle_cr(struct kvm_vcpu *vcpu)
6067 unsigned long exit_qualification, val;
6072 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6073 cr = exit_qualification & 15;
6074 reg = (exit_qualification >> 8) & 15;
6075 switch ((exit_qualification >> 4) & 3) {
6076 case 0: /* mov to cr */
6077 val = kvm_register_readl(vcpu, reg);
6078 trace_kvm_cr_write(cr, val);
6081 err = handle_set_cr0(vcpu, val);
6082 kvm_complete_insn_gp(vcpu, err);
6085 err = kvm_set_cr3(vcpu, val);
6086 kvm_complete_insn_gp(vcpu, err);
6089 err = handle_set_cr4(vcpu, val);
6090 kvm_complete_insn_gp(vcpu, err);
6093 u8 cr8_prev = kvm_get_cr8(vcpu);
6095 err = kvm_set_cr8(vcpu, cr8);
6096 kvm_complete_insn_gp(vcpu, err);
6097 if (lapic_in_kernel(vcpu))
6099 if (cr8_prev <= cr8)
6101 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6108 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6109 skip_emulated_instruction(vcpu);
6110 vmx_fpu_activate(vcpu);
6112 case 1: /*mov from cr*/
6115 val = kvm_read_cr3(vcpu);
6116 kvm_register_write(vcpu, reg, val);
6117 trace_kvm_cr_read(cr, val);
6118 skip_emulated_instruction(vcpu);
6121 val = kvm_get_cr8(vcpu);
6122 kvm_register_write(vcpu, reg, val);
6123 trace_kvm_cr_read(cr, val);
6124 skip_emulated_instruction(vcpu);
6129 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6130 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6131 kvm_lmsw(vcpu, val);
6133 skip_emulated_instruction(vcpu);
6138 vcpu->run->exit_reason = 0;
6139 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6140 (int)(exit_qualification >> 4) & 3, cr);
6144 static int handle_dr(struct kvm_vcpu *vcpu)
6146 unsigned long exit_qualification;
6149 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6150 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6152 /* First, if DR does not exist, trigger UD */
6153 if (!kvm_require_dr(vcpu, dr))
6156 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6157 if (!kvm_require_cpl(vcpu, 0))
6159 dr7 = vmcs_readl(GUEST_DR7);
6162 * As the vm-exit takes precedence over the debug trap, we
6163 * need to emulate the latter, either for the host or the
6164 * guest debugging itself.
6166 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6167 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6168 vcpu->run->debug.arch.dr7 = dr7;
6169 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6170 vcpu->run->debug.arch.exception = DB_VECTOR;
6171 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6174 vcpu->arch.dr6 &= ~15;
6175 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6176 kvm_queue_exception(vcpu, DB_VECTOR);
6181 if (vcpu->guest_debug == 0) {
6182 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6183 CPU_BASED_MOV_DR_EXITING);
6186 * No more DR vmexits; force a reload of the debug registers
6187 * and reenter on this instruction. The next vmexit will
6188 * retrieve the full state of the debug registers.
6190 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6194 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6195 if (exit_qualification & TYPE_MOV_FROM_DR) {
6198 if (kvm_get_dr(vcpu, dr, &val))
6200 kvm_register_write(vcpu, reg, val);
6202 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6205 skip_emulated_instruction(vcpu);
6209 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6211 return vcpu->arch.dr6;
6214 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6218 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6220 get_debugreg(vcpu->arch.db[0], 0);
6221 get_debugreg(vcpu->arch.db[1], 1);
6222 get_debugreg(vcpu->arch.db[2], 2);
6223 get_debugreg(vcpu->arch.db[3], 3);
6224 get_debugreg(vcpu->arch.dr6, 6);
6225 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6227 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6228 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6231 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6233 vmcs_writel(GUEST_DR7, val);
6236 static int handle_cpuid(struct kvm_vcpu *vcpu)
6238 kvm_emulate_cpuid(vcpu);
6242 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6244 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6245 struct msr_data msr_info;
6247 msr_info.index = ecx;
6248 msr_info.host_initiated = false;
6249 if (vmx_get_msr(vcpu, &msr_info)) {
6250 trace_kvm_msr_read_ex(ecx);
6251 kvm_inject_gp(vcpu, 0);
6255 trace_kvm_msr_read(ecx, msr_info.data);
6257 /* FIXME: handling of bits 32:63 of rax, rdx */
6258 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6259 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6260 skip_emulated_instruction(vcpu);
6264 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6266 struct msr_data msr;
6267 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6268 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6269 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6273 msr.host_initiated = false;
6274 if (kvm_set_msr(vcpu, &msr) != 0) {
6275 trace_kvm_msr_write_ex(ecx, data);
6276 kvm_inject_gp(vcpu, 0);
6280 trace_kvm_msr_write(ecx, data);
6281 skip_emulated_instruction(vcpu);
6285 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6287 kvm_make_request(KVM_REQ_EVENT, vcpu);
6291 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6293 u32 cpu_based_vm_exec_control;
6295 /* clear pending irq */
6296 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6297 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
6298 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
6300 kvm_make_request(KVM_REQ_EVENT, vcpu);
6302 ++vcpu->stat.irq_window_exits;
6306 static int handle_halt(struct kvm_vcpu *vcpu)
6308 return kvm_emulate_halt(vcpu);
6311 static int handle_vmcall(struct kvm_vcpu *vcpu)
6313 return kvm_emulate_hypercall(vcpu);
6316 static int handle_invd(struct kvm_vcpu *vcpu)
6318 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6321 static int handle_invlpg(struct kvm_vcpu *vcpu)
6323 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6325 kvm_mmu_invlpg(vcpu, exit_qualification);
6326 skip_emulated_instruction(vcpu);
6330 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6334 err = kvm_rdpmc(vcpu);
6335 kvm_complete_insn_gp(vcpu, err);
6340 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6342 kvm_emulate_wbinvd(vcpu);
6346 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6348 u64 new_bv = kvm_read_edx_eax(vcpu);
6349 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6351 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6352 skip_emulated_instruction(vcpu);
6356 static int handle_xsaves(struct kvm_vcpu *vcpu)
6358 skip_emulated_instruction(vcpu);
6359 WARN(1, "this should never happen\n");
6363 static int handle_xrstors(struct kvm_vcpu *vcpu)
6365 skip_emulated_instruction(vcpu);
6366 WARN(1, "this should never happen\n");
6370 static int handle_apic_access(struct kvm_vcpu *vcpu)
6372 if (likely(fasteoi)) {
6373 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6374 int access_type, offset;
6376 access_type = exit_qualification & APIC_ACCESS_TYPE;
6377 offset = exit_qualification & APIC_ACCESS_OFFSET;
6379 * Sane guest uses MOV to write EOI, with written value
6380 * not cared. So make a short-circuit here by avoiding
6381 * heavy instruction emulation.
6383 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6384 (offset == APIC_EOI)) {
6385 kvm_lapic_set_eoi(vcpu);
6386 skip_emulated_instruction(vcpu);
6390 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6393 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6395 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6396 int vector = exit_qualification & 0xff;
6398 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6399 kvm_apic_set_eoi_accelerated(vcpu, vector);
6403 static int handle_apic_write(struct kvm_vcpu *vcpu)
6405 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6406 u32 offset = exit_qualification & 0xfff;
6408 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6409 kvm_apic_write_nodecode(vcpu, offset);
6413 static int handle_task_switch(struct kvm_vcpu *vcpu)
6415 struct vcpu_vmx *vmx = to_vmx(vcpu);
6416 unsigned long exit_qualification;
6417 bool has_error_code = false;
6420 int reason, type, idt_v, idt_index;
6422 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6423 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6424 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6426 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6428 reason = (u32)exit_qualification >> 30;
6429 if (reason == TASK_SWITCH_GATE && idt_v) {
6431 case INTR_TYPE_NMI_INTR:
6432 vcpu->arch.nmi_injected = false;
6433 vmx_set_nmi_mask(vcpu, true);
6435 case INTR_TYPE_EXT_INTR:
6436 case INTR_TYPE_SOFT_INTR:
6437 kvm_clear_interrupt_queue(vcpu);
6439 case INTR_TYPE_HARD_EXCEPTION:
6440 if (vmx->idt_vectoring_info &
6441 VECTORING_INFO_DELIVER_CODE_MASK) {
6442 has_error_code = true;
6444 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6447 case INTR_TYPE_SOFT_EXCEPTION:
6448 kvm_clear_exception_queue(vcpu);
6454 tss_selector = exit_qualification;
6456 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6457 type != INTR_TYPE_EXT_INTR &&
6458 type != INTR_TYPE_NMI_INTR))
6459 skip_emulated_instruction(vcpu);
6461 if (kvm_task_switch(vcpu, tss_selector,
6462 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6463 has_error_code, error_code) == EMULATE_FAIL) {
6464 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6465 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6466 vcpu->run->internal.ndata = 0;
6471 * TODO: What about debug traps on tss switch?
6472 * Are we supposed to inject them and update dr6?
6478 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6480 unsigned long exit_qualification;
6485 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6487 gla_validity = (exit_qualification >> 7) & 0x3;
6488 if (gla_validity == 0x2) {
6489 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
6490 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
6491 (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
6492 vmcs_readl(GUEST_LINEAR_ADDRESS));
6493 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
6494 (long unsigned int)exit_qualification);
6495 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6496 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
6501 * EPT violation happened while executing iret from NMI,
6502 * "blocked by NMI" bit has to be set before next VM entry.
6503 * There are errata that may cause this bit to not be set:
6506 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6507 cpu_has_virtual_nmis() &&
6508 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6509 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6511 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6512 trace_kvm_page_fault(gpa, exit_qualification);
6514 /* it is a read fault? */
6515 error_code = (exit_qualification << 2) & PFERR_USER_MASK;
6516 /* it is a write fault? */
6517 error_code |= exit_qualification & PFERR_WRITE_MASK;
6518 /* It is a fetch fault? */
6519 error_code |= (exit_qualification << 2) & PFERR_FETCH_MASK;
6520 /* ept page table is present? */
6521 error_code |= (exit_qualification & 0x38) != 0;
6523 vcpu->arch.exit_qualification = exit_qualification;
6525 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6528 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6533 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6534 if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6535 skip_emulated_instruction(vcpu);
6536 trace_kvm_fast_mmio(gpa);
6540 ret = handle_mmio_page_fault(vcpu, gpa, true);
6541 if (likely(ret == RET_MMIO_PF_EMULATE))
6542 return x86_emulate_instruction(vcpu, gpa, 0, NULL, 0) ==
6545 if (unlikely(ret == RET_MMIO_PF_INVALID))
6546 return kvm_mmu_page_fault(vcpu, gpa, 0, NULL, 0);
6548 if (unlikely(ret == RET_MMIO_PF_RETRY))
6551 /* It is the real ept misconfig */
6554 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6555 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6560 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6562 u32 cpu_based_vm_exec_control;
6564 /* clear pending NMI */
6565 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6566 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
6567 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
6568 ++vcpu->stat.nmi_window_exits;
6569 kvm_make_request(KVM_REQ_EVENT, vcpu);
6574 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6576 struct vcpu_vmx *vmx = to_vmx(vcpu);
6577 enum emulation_result err = EMULATE_DONE;
6580 bool intr_window_requested;
6581 unsigned count = 130;
6583 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6584 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6586 while (vmx->emulation_required && count-- != 0) {
6587 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6588 return handle_interrupt_window(&vmx->vcpu);
6590 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
6593 err = emulate_instruction(vcpu, 0);
6595 if (err == EMULATE_USER_EXIT) {
6596 ++vcpu->stat.mmio_exits;
6601 if (err != EMULATE_DONE)
6602 goto emulation_error;
6604 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
6605 vcpu->arch.exception.pending)
6606 goto emulation_error;
6608 if (vcpu->arch.halt_request) {
6609 vcpu->arch.halt_request = 0;
6610 ret = kvm_vcpu_halt(vcpu);
6614 if (signal_pending(current))
6624 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6625 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6626 vcpu->run->internal.ndata = 0;
6630 static int __grow_ple_window(int val)
6632 if (ple_window_grow < 1)
6635 val = min(val, ple_window_actual_max);
6637 if (ple_window_grow < ple_window)
6638 val *= ple_window_grow;
6640 val += ple_window_grow;
6645 static int __shrink_ple_window(int val, int modifier, int minimum)
6650 if (modifier < ple_window)
6655 return max(val, minimum);
6658 static void grow_ple_window(struct kvm_vcpu *vcpu)
6660 struct vcpu_vmx *vmx = to_vmx(vcpu);
6661 int old = vmx->ple_window;
6663 vmx->ple_window = __grow_ple_window(old);
6665 if (vmx->ple_window != old)
6666 vmx->ple_window_dirty = true;
6668 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6671 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6673 struct vcpu_vmx *vmx = to_vmx(vcpu);
6674 int old = vmx->ple_window;
6676 vmx->ple_window = __shrink_ple_window(old,
6677 ple_window_shrink, ple_window);
6679 if (vmx->ple_window != old)
6680 vmx->ple_window_dirty = true;
6682 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6686 * ple_window_actual_max is computed to be one grow_ple_window() below
6687 * ple_window_max. (See __grow_ple_window for the reason.)
6688 * This prevents overflows, because ple_window_max is int.
6689 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6691 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6693 static void update_ple_window_actual_max(void)
6695 ple_window_actual_max =
6696 __shrink_ple_window(max(ple_window_max, ple_window),
6697 ple_window_grow, INT_MIN);
6701 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6703 static void wakeup_handler(void)
6705 struct kvm_vcpu *vcpu;
6706 int cpu = smp_processor_id();
6708 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6709 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6710 blocked_vcpu_list) {
6711 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6713 if (pi_test_on(pi_desc) == 1)
6714 kvm_vcpu_kick(vcpu);
6716 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6719 static __init int hardware_setup(void)
6723 rdmsrl_safe(MSR_EFER, &host_efer);
6725 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6726 kvm_define_shared_msr(i, vmx_msr_index[i]);
6728 vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
6729 if (!vmx_io_bitmap_a)
6732 vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
6733 if (!vmx_io_bitmap_b)
6736 vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6737 if (!vmx_vmread_bitmap)
6740 vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6741 if (!vmx_vmwrite_bitmap)
6744 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6745 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6747 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6749 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6751 if (setup_vmcs_config(&vmcs_config) < 0) {
6756 if (boot_cpu_has(X86_FEATURE_NX))
6757 kvm_enable_efer_bits(EFER_NX);
6759 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6760 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6763 if (!cpu_has_vmx_shadow_vmcs())
6764 enable_shadow_vmcs = 0;
6765 if (enable_shadow_vmcs)
6766 init_vmcs_shadow_fields();
6768 if (!cpu_has_vmx_ept() ||
6769 !cpu_has_vmx_ept_4levels()) {
6771 enable_unrestricted_guest = 0;
6772 enable_ept_ad_bits = 0;
6775 if (!cpu_has_vmx_ept_ad_bits())
6776 enable_ept_ad_bits = 0;
6778 if (!cpu_has_vmx_unrestricted_guest())
6779 enable_unrestricted_guest = 0;
6781 if (!cpu_has_vmx_flexpriority())
6782 flexpriority_enabled = 0;
6785 * set_apic_access_page_addr() is used to reload apic access
6786 * page upon invalidation. No need to do anything if not
6787 * using the APIC_ACCESS_ADDR VMCS field.
6789 if (!flexpriority_enabled)
6790 kvm_x86_ops->set_apic_access_page_addr = NULL;
6792 if (!cpu_has_vmx_tpr_shadow())
6793 kvm_x86_ops->update_cr8_intercept = NULL;
6795 if (enable_ept && !cpu_has_vmx_ept_2m_page())
6796 kvm_disable_largepages();
6798 if (!cpu_has_vmx_ple())
6801 if (!cpu_has_vmx_apicv())
6804 if (cpu_has_vmx_tsc_scaling()) {
6805 kvm_has_tsc_control = true;
6806 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
6807 kvm_tsc_scaling_ratio_frac_bits = 48;
6810 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6813 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6814 (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
6815 (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
6816 0ull, VMX_EPT_EXECUTABLE_MASK,
6817 cpu_has_vmx_ept_execute_only() ?
6818 0ull : VMX_EPT_READABLE_MASK);
6819 ept_set_mmio_spte_mask();
6824 update_ple_window_actual_max();
6827 * Only enable PML when hardware supports PML feature, and both EPT
6828 * and EPT A/D bit features are enabled -- PML depends on them to work.
6830 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6834 kvm_x86_ops->slot_enable_log_dirty = NULL;
6835 kvm_x86_ops->slot_disable_log_dirty = NULL;
6836 kvm_x86_ops->flush_log_dirty = NULL;
6837 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6840 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
6843 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
6844 cpu_preemption_timer_multi =
6845 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
6847 kvm_x86_ops->set_hv_timer = NULL;
6848 kvm_x86_ops->cancel_hv_timer = NULL;
6851 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
6853 kvm_mce_cap_supported |= MCG_LMCE_P;
6855 return alloc_kvm_area();
6858 free_page((unsigned long)vmx_vmwrite_bitmap);
6860 free_page((unsigned long)vmx_vmread_bitmap);
6862 free_page((unsigned long)vmx_io_bitmap_b);
6864 free_page((unsigned long)vmx_io_bitmap_a);
6869 static __exit void hardware_unsetup(void)
6871 free_page((unsigned long)vmx_io_bitmap_b);
6872 free_page((unsigned long)vmx_io_bitmap_a);
6873 free_page((unsigned long)vmx_vmwrite_bitmap);
6874 free_page((unsigned long)vmx_vmread_bitmap);
6880 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6881 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6883 static int handle_pause(struct kvm_vcpu *vcpu)
6886 grow_ple_window(vcpu);
6888 skip_emulated_instruction(vcpu);
6889 kvm_vcpu_on_spin(vcpu);
6894 static int handle_nop(struct kvm_vcpu *vcpu)
6896 skip_emulated_instruction(vcpu);
6900 static int handle_mwait(struct kvm_vcpu *vcpu)
6902 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6903 return handle_nop(vcpu);
6906 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
6911 static int handle_monitor(struct kvm_vcpu *vcpu)
6913 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6914 return handle_nop(vcpu);
6918 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
6919 * set the success or error code of an emulated VMX instruction, as specified
6920 * by Vol 2B, VMX Instruction Reference, "Conventions".
6922 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
6924 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
6925 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6926 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
6929 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
6931 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6932 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
6933 X86_EFLAGS_SF | X86_EFLAGS_OF))
6937 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
6938 u32 vm_instruction_error)
6940 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
6942 * failValid writes the error number to the current VMCS, which
6943 * can't be done there isn't a current VMCS.
6945 nested_vmx_failInvalid(vcpu);
6948 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6949 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6950 X86_EFLAGS_SF | X86_EFLAGS_OF))
6952 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
6954 * We don't need to force a shadow sync because
6955 * VM_INSTRUCTION_ERROR is not shadowed
6959 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
6961 /* TODO: not to reset guest simply here. */
6962 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6963 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
6966 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
6968 struct vcpu_vmx *vmx =
6969 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
6971 vmx->nested.preemption_timer_expired = true;
6972 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
6973 kvm_vcpu_kick(&vmx->vcpu);
6975 return HRTIMER_NORESTART;
6979 * Decode the memory-address operand of a vmx instruction, as recorded on an
6980 * exit caused by such an instruction (run by a guest hypervisor).
6981 * On success, returns 0. When the operand is invalid, returns 1 and throws
6984 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
6985 unsigned long exit_qualification,
6986 u32 vmx_instruction_info, bool wr, gva_t *ret)
6990 struct kvm_segment s;
6993 * According to Vol. 3B, "Information for VM Exits Due to Instruction
6994 * Execution", on an exit, vmx_instruction_info holds most of the
6995 * addressing components of the operand. Only the displacement part
6996 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
6997 * For how an actual address is calculated from all these components,
6998 * refer to Vol. 1, "Operand Addressing".
7000 int scaling = vmx_instruction_info & 3;
7001 int addr_size = (vmx_instruction_info >> 7) & 7;
7002 bool is_reg = vmx_instruction_info & (1u << 10);
7003 int seg_reg = (vmx_instruction_info >> 15) & 7;
7004 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7005 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7006 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7007 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7010 kvm_queue_exception(vcpu, UD_VECTOR);
7014 /* Addr = segment_base + offset */
7015 /* offset = base + [index * scale] + displacement */
7016 off = exit_qualification; /* holds the displacement */
7018 off += kvm_register_read(vcpu, base_reg);
7020 off += kvm_register_read(vcpu, index_reg)<<scaling;
7021 vmx_get_segment(vcpu, &s, seg_reg);
7022 *ret = s.base + off;
7024 if (addr_size == 1) /* 32 bit */
7027 /* Checks for #GP/#SS exceptions. */
7029 if (is_long_mode(vcpu)) {
7030 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7031 * non-canonical form. This is the only check on the memory
7032 * destination for long mode!
7034 exn = is_noncanonical_address(*ret);
7035 } else if (is_protmode(vcpu)) {
7036 /* Protected mode: apply checks for segment validity in the
7038 * - segment type check (#GP(0) may be thrown)
7039 * - usability check (#GP(0)/#SS(0))
7040 * - limit check (#GP(0)/#SS(0))
7043 /* #GP(0) if the destination operand is located in a
7044 * read-only data segment or any code segment.
7046 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7048 /* #GP(0) if the source operand is located in an
7049 * execute-only code segment
7051 exn = ((s.type & 0xa) == 8);
7053 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7056 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7058 exn = (s.unusable != 0);
7059 /* Protected mode: #GP(0)/#SS(0) if the memory
7060 * operand is outside the segment limit.
7062 exn = exn || (off + sizeof(u64) > s.limit);
7065 kvm_queue_exception_e(vcpu,
7066 seg_reg == VCPU_SREG_SS ?
7067 SS_VECTOR : GP_VECTOR,
7076 * This function performs the various checks including
7077 * - if it's 4KB aligned
7078 * - No bits beyond the physical address width are set
7079 * - Returns 0 on success or else 1
7080 * (Intel SDM Section 30.3)
7082 static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
7087 struct x86_exception e;
7089 struct vcpu_vmx *vmx = to_vmx(vcpu);
7090 int maxphyaddr = cpuid_maxphyaddr(vcpu);
7092 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7093 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7096 if (kvm_read_guest_virt(vcpu, gva, &vmptr, sizeof(vmptr), &e)) {
7097 kvm_inject_page_fault(vcpu, &e);
7101 switch (exit_reason) {
7102 case EXIT_REASON_VMON:
7105 * The first 4 bytes of VMXON region contain the supported
7106 * VMCS revision identifier
7108 * Note - IA32_VMX_BASIC[48] will never be 1
7109 * for the nested case;
7110 * which replaces physical address width with 32
7113 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7114 nested_vmx_failInvalid(vcpu);
7115 skip_emulated_instruction(vcpu);
7119 page = nested_get_page(vcpu, vmptr);
7121 nested_vmx_failInvalid(vcpu);
7122 skip_emulated_instruction(vcpu);
7125 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7127 nested_release_page_clean(page);
7128 nested_vmx_failInvalid(vcpu);
7129 skip_emulated_instruction(vcpu);
7133 nested_release_page_clean(page);
7134 vmx->nested.vmxon_ptr = vmptr;
7136 case EXIT_REASON_VMCLEAR:
7137 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7138 nested_vmx_failValid(vcpu,
7139 VMXERR_VMCLEAR_INVALID_ADDRESS);
7140 skip_emulated_instruction(vcpu);
7144 if (vmptr == vmx->nested.vmxon_ptr) {
7145 nested_vmx_failValid(vcpu,
7146 VMXERR_VMCLEAR_VMXON_POINTER);
7147 skip_emulated_instruction(vcpu);
7151 case EXIT_REASON_VMPTRLD:
7152 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7153 nested_vmx_failValid(vcpu,
7154 VMXERR_VMPTRLD_INVALID_ADDRESS);
7155 skip_emulated_instruction(vcpu);
7159 if (vmptr == vmx->nested.vmxon_ptr) {
7160 nested_vmx_failValid(vcpu,
7161 VMXERR_VMCLEAR_VMXON_POINTER);
7162 skip_emulated_instruction(vcpu);
7167 return 1; /* shouldn't happen */
7176 * Emulate the VMXON instruction.
7177 * Currently, we just remember that VMX is active, and do not save or even
7178 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7179 * do not currently need to store anything in that guest-allocated memory
7180 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7181 * argument is different from the VMXON pointer (which the spec says they do).
7183 static int handle_vmon(struct kvm_vcpu *vcpu)
7185 struct kvm_segment cs;
7186 struct vcpu_vmx *vmx = to_vmx(vcpu);
7187 struct vmcs *shadow_vmcs;
7188 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7189 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7192 /* The Intel VMX Instruction Reference lists a bunch of bits that
7193 * are prerequisite to running VMXON, most notably cr4.VMXE must be
7194 * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
7195 * Otherwise, we should fail with #UD. We test these now:
7197 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
7198 !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
7199 (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
7200 kvm_queue_exception(vcpu, UD_VECTOR);
7204 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
7205 if (is_long_mode(vcpu) && !cs.l) {
7206 kvm_queue_exception(vcpu, UD_VECTOR);
7210 if (vmx_get_cpl(vcpu)) {
7211 kvm_inject_gp(vcpu, 0);
7215 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
7218 if (vmx->nested.vmxon) {
7219 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7220 skip_emulated_instruction(vcpu);
7224 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7225 != VMXON_NEEDED_FEATURES) {
7226 kvm_inject_gp(vcpu, 0);
7230 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
7234 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7235 if (!vmx->nested.cached_vmcs12)
7236 goto out_cached_vmcs12;
7238 if (enable_shadow_vmcs) {
7239 shadow_vmcs = alloc_vmcs();
7241 goto out_shadow_vmcs;
7242 /* mark vmcs as shadow */
7243 shadow_vmcs->revision_id |= (1u << 31);
7244 /* init shadow vmcs */
7245 vmcs_clear(shadow_vmcs);
7246 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7249 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7250 HRTIMER_MODE_REL_PINNED);
7251 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7253 vmx->nested.vpid02 = allocate_vpid();
7255 vmx->nested.vmxon = true;
7257 skip_emulated_instruction(vcpu);
7258 nested_vmx_succeed(vcpu);
7262 kfree(vmx->nested.cached_vmcs12);
7265 free_loaded_vmcs(&vmx->nested.vmcs02);
7272 * Intel's VMX Instruction Reference specifies a common set of prerequisites
7273 * for running VMX instructions (except VMXON, whose prerequisites are
7274 * slightly different). It also specifies what exception to inject otherwise.
7276 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7278 struct kvm_segment cs;
7279 struct vcpu_vmx *vmx = to_vmx(vcpu);
7281 if (!vmx->nested.vmxon) {
7282 kvm_queue_exception(vcpu, UD_VECTOR);
7286 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
7287 if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
7288 (is_long_mode(vcpu) && !cs.l)) {
7289 kvm_queue_exception(vcpu, UD_VECTOR);
7293 if (vmx_get_cpl(vcpu)) {
7294 kvm_inject_gp(vcpu, 0);
7301 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7303 if (vmx->nested.current_vmptr == -1ull)
7306 /* current_vmptr and current_vmcs12 are always set/reset together */
7307 if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
7310 if (enable_shadow_vmcs) {
7311 /* copy to memory all shadowed fields in case
7312 they were modified */
7313 copy_shadow_to_vmcs12(vmx);
7314 vmx->nested.sync_shadow_vmcs = false;
7315 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
7316 SECONDARY_EXEC_SHADOW_VMCS);
7317 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7319 vmx->nested.posted_intr_nv = -1;
7321 /* Flush VMCS12 to guest memory */
7322 memcpy(vmx->nested.current_vmcs12, vmx->nested.cached_vmcs12,
7325 kunmap(vmx->nested.current_vmcs12_page);
7326 nested_release_page(vmx->nested.current_vmcs12_page);
7327 vmx->nested.current_vmptr = -1ull;
7328 vmx->nested.current_vmcs12 = NULL;
7332 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7333 * just stops using VMX.
7335 static void free_nested(struct vcpu_vmx *vmx)
7337 if (!vmx->nested.vmxon)
7340 vmx->nested.vmxon = false;
7341 free_vpid(vmx->nested.vpid02);
7342 nested_release_vmcs12(vmx);
7343 if (enable_shadow_vmcs) {
7344 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7345 free_vmcs(vmx->vmcs01.shadow_vmcs);
7346 vmx->vmcs01.shadow_vmcs = NULL;
7348 kfree(vmx->nested.cached_vmcs12);
7349 /* Unpin physical memory we referred to in the vmcs02 */
7350 if (vmx->nested.apic_access_page) {
7351 nested_release_page(vmx->nested.apic_access_page);
7352 vmx->nested.apic_access_page = NULL;
7354 if (vmx->nested.virtual_apic_page) {
7355 nested_release_page(vmx->nested.virtual_apic_page);
7356 vmx->nested.virtual_apic_page = NULL;
7358 if (vmx->nested.pi_desc_page) {
7359 kunmap(vmx->nested.pi_desc_page);
7360 nested_release_page(vmx->nested.pi_desc_page);
7361 vmx->nested.pi_desc_page = NULL;
7362 vmx->nested.pi_desc = NULL;
7365 free_loaded_vmcs(&vmx->nested.vmcs02);
7368 /* Emulate the VMXOFF instruction */
7369 static int handle_vmoff(struct kvm_vcpu *vcpu)
7371 if (!nested_vmx_check_permission(vcpu))
7373 free_nested(to_vmx(vcpu));
7374 skip_emulated_instruction(vcpu);
7375 nested_vmx_succeed(vcpu);
7379 /* Emulate the VMCLEAR instruction */
7380 static int handle_vmclear(struct kvm_vcpu *vcpu)
7382 struct vcpu_vmx *vmx = to_vmx(vcpu);
7386 if (!nested_vmx_check_permission(vcpu))
7389 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
7392 if (vmptr == vmx->nested.current_vmptr)
7393 nested_release_vmcs12(vmx);
7395 kvm_vcpu_write_guest(vcpu,
7396 vmptr + offsetof(struct vmcs12, launch_state),
7397 &zero, sizeof(zero));
7399 skip_emulated_instruction(vcpu);
7400 nested_vmx_succeed(vcpu);
7404 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7406 /* Emulate the VMLAUNCH instruction */
7407 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7409 return nested_vmx_run(vcpu, true);
7412 /* Emulate the VMRESUME instruction */
7413 static int handle_vmresume(struct kvm_vcpu *vcpu)
7416 return nested_vmx_run(vcpu, false);
7419 enum vmcs_field_type {
7420 VMCS_FIELD_TYPE_U16 = 0,
7421 VMCS_FIELD_TYPE_U64 = 1,
7422 VMCS_FIELD_TYPE_U32 = 2,
7423 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
7426 static inline int vmcs_field_type(unsigned long field)
7428 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
7429 return VMCS_FIELD_TYPE_U32;
7430 return (field >> 13) & 0x3 ;
7433 static inline int vmcs_field_readonly(unsigned long field)
7435 return (((field >> 10) & 0x3) == 1);
7439 * Read a vmcs12 field. Since these can have varying lengths and we return
7440 * one type, we chose the biggest type (u64) and zero-extend the return value
7441 * to that size. Note that the caller, handle_vmread, might need to use only
7442 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7443 * 64-bit fields are to be returned).
7445 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7446 unsigned long field, u64 *ret)
7448 short offset = vmcs_field_to_offset(field);
7454 p = ((char *)(get_vmcs12(vcpu))) + offset;
7456 switch (vmcs_field_type(field)) {
7457 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7458 *ret = *((natural_width *)p);
7460 case VMCS_FIELD_TYPE_U16:
7463 case VMCS_FIELD_TYPE_U32:
7466 case VMCS_FIELD_TYPE_U64:
7476 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7477 unsigned long field, u64 field_value){
7478 short offset = vmcs_field_to_offset(field);
7479 char *p = ((char *) get_vmcs12(vcpu)) + offset;
7483 switch (vmcs_field_type(field)) {
7484 case VMCS_FIELD_TYPE_U16:
7485 *(u16 *)p = field_value;
7487 case VMCS_FIELD_TYPE_U32:
7488 *(u32 *)p = field_value;
7490 case VMCS_FIELD_TYPE_U64:
7491 *(u64 *)p = field_value;
7493 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7494 *(natural_width *)p = field_value;
7503 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7506 unsigned long field;
7508 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7509 const unsigned long *fields = shadow_read_write_fields;
7510 const int num_fields = max_shadow_read_write_fields;
7514 vmcs_load(shadow_vmcs);
7516 for (i = 0; i < num_fields; i++) {
7518 switch (vmcs_field_type(field)) {
7519 case VMCS_FIELD_TYPE_U16:
7520 field_value = vmcs_read16(field);
7522 case VMCS_FIELD_TYPE_U32:
7523 field_value = vmcs_read32(field);
7525 case VMCS_FIELD_TYPE_U64:
7526 field_value = vmcs_read64(field);
7528 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7529 field_value = vmcs_readl(field);
7535 vmcs12_write_any(&vmx->vcpu, field, field_value);
7538 vmcs_clear(shadow_vmcs);
7539 vmcs_load(vmx->loaded_vmcs->vmcs);
7544 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7546 const unsigned long *fields[] = {
7547 shadow_read_write_fields,
7548 shadow_read_only_fields
7550 const int max_fields[] = {
7551 max_shadow_read_write_fields,
7552 max_shadow_read_only_fields
7555 unsigned long field;
7556 u64 field_value = 0;
7557 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7559 vmcs_load(shadow_vmcs);
7561 for (q = 0; q < ARRAY_SIZE(fields); q++) {
7562 for (i = 0; i < max_fields[q]; i++) {
7563 field = fields[q][i];
7564 vmcs12_read_any(&vmx->vcpu, field, &field_value);
7566 switch (vmcs_field_type(field)) {
7567 case VMCS_FIELD_TYPE_U16:
7568 vmcs_write16(field, (u16)field_value);
7570 case VMCS_FIELD_TYPE_U32:
7571 vmcs_write32(field, (u32)field_value);
7573 case VMCS_FIELD_TYPE_U64:
7574 vmcs_write64(field, (u64)field_value);
7576 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7577 vmcs_writel(field, (long)field_value);
7586 vmcs_clear(shadow_vmcs);
7587 vmcs_load(vmx->loaded_vmcs->vmcs);
7591 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7592 * used before) all generate the same failure when it is missing.
7594 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7596 struct vcpu_vmx *vmx = to_vmx(vcpu);
7597 if (vmx->nested.current_vmptr == -1ull) {
7598 nested_vmx_failInvalid(vcpu);
7599 skip_emulated_instruction(vcpu);
7605 static int handle_vmread(struct kvm_vcpu *vcpu)
7607 unsigned long field;
7609 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7610 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7613 if (!nested_vmx_check_permission(vcpu) ||
7614 !nested_vmx_check_vmcs12(vcpu))
7617 /* Decode instruction info and find the field to read */
7618 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7619 /* Read the field, zero-extended to a u64 field_value */
7620 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7621 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7622 skip_emulated_instruction(vcpu);
7626 * Now copy part of this value to register or memory, as requested.
7627 * Note that the number of bits actually copied is 32 or 64 depending
7628 * on the guest's mode (32 or 64 bit), not on the given field's length.
7630 if (vmx_instruction_info & (1u << 10)) {
7631 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7634 if (get_vmx_mem_address(vcpu, exit_qualification,
7635 vmx_instruction_info, true, &gva))
7637 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
7638 kvm_write_guest_virt_system(vcpu, gva, &field_value,
7639 (is_long_mode(vcpu) ? 8 : 4), NULL);
7642 nested_vmx_succeed(vcpu);
7643 skip_emulated_instruction(vcpu);
7648 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7650 unsigned long field;
7652 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7653 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7654 /* The value to write might be 32 or 64 bits, depending on L1's long
7655 * mode, and eventually we need to write that into a field of several
7656 * possible lengths. The code below first zero-extends the value to 64
7657 * bit (field_value), and then copies only the appropriate number of
7658 * bits into the vmcs12 field.
7660 u64 field_value = 0;
7661 struct x86_exception e;
7663 if (!nested_vmx_check_permission(vcpu) ||
7664 !nested_vmx_check_vmcs12(vcpu))
7667 if (vmx_instruction_info & (1u << 10))
7668 field_value = kvm_register_readl(vcpu,
7669 (((vmx_instruction_info) >> 3) & 0xf));
7671 if (get_vmx_mem_address(vcpu, exit_qualification,
7672 vmx_instruction_info, false, &gva))
7674 if (kvm_read_guest_virt(vcpu, gva, &field_value,
7675 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7676 kvm_inject_page_fault(vcpu, &e);
7682 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7683 if (vmcs_field_readonly(field)) {
7684 nested_vmx_failValid(vcpu,
7685 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7686 skip_emulated_instruction(vcpu);
7690 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7691 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7692 skip_emulated_instruction(vcpu);
7696 nested_vmx_succeed(vcpu);
7697 skip_emulated_instruction(vcpu);
7701 /* Emulate the VMPTRLD instruction */
7702 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7704 struct vcpu_vmx *vmx = to_vmx(vcpu);
7707 if (!nested_vmx_check_permission(vcpu))
7710 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
7713 if (vmx->nested.current_vmptr != vmptr) {
7714 struct vmcs12 *new_vmcs12;
7716 page = nested_get_page(vcpu, vmptr);
7718 nested_vmx_failInvalid(vcpu);
7719 skip_emulated_instruction(vcpu);
7722 new_vmcs12 = kmap(page);
7723 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7725 nested_release_page_clean(page);
7726 nested_vmx_failValid(vcpu,
7727 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7728 skip_emulated_instruction(vcpu);
7732 nested_release_vmcs12(vmx);
7733 vmx->nested.current_vmptr = vmptr;
7734 vmx->nested.current_vmcs12 = new_vmcs12;
7735 vmx->nested.current_vmcs12_page = page;
7737 * Load VMCS12 from guest memory since it is not already
7740 memcpy(vmx->nested.cached_vmcs12,
7741 vmx->nested.current_vmcs12, VMCS12_SIZE);
7743 if (enable_shadow_vmcs) {
7744 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7745 SECONDARY_EXEC_SHADOW_VMCS);
7746 vmcs_write64(VMCS_LINK_POINTER,
7747 __pa(vmx->vmcs01.shadow_vmcs));
7748 vmx->nested.sync_shadow_vmcs = true;
7752 nested_vmx_succeed(vcpu);
7753 skip_emulated_instruction(vcpu);
7757 /* Emulate the VMPTRST instruction */
7758 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7760 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7761 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7763 struct x86_exception e;
7765 if (!nested_vmx_check_permission(vcpu))
7768 if (get_vmx_mem_address(vcpu, exit_qualification,
7769 vmx_instruction_info, true, &vmcs_gva))
7771 /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
7772 if (kvm_write_guest_virt_system(vcpu, vmcs_gva,
7773 (void *)&to_vmx(vcpu)->nested.current_vmptr,
7775 kvm_inject_page_fault(vcpu, &e);
7778 nested_vmx_succeed(vcpu);
7779 skip_emulated_instruction(vcpu);
7783 /* Emulate the INVEPT instruction */
7784 static int handle_invept(struct kvm_vcpu *vcpu)
7786 struct vcpu_vmx *vmx = to_vmx(vcpu);
7787 u32 vmx_instruction_info, types;
7790 struct x86_exception e;
7795 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7796 SECONDARY_EXEC_ENABLE_EPT) ||
7797 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7798 kvm_queue_exception(vcpu, UD_VECTOR);
7802 if (!nested_vmx_check_permission(vcpu))
7805 if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
7806 kvm_queue_exception(vcpu, UD_VECTOR);
7810 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7811 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7813 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7815 if (type >= 32 || !(types & (1 << type))) {
7816 nested_vmx_failValid(vcpu,
7817 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7818 skip_emulated_instruction(vcpu);
7822 /* According to the Intel VMX instruction reference, the memory
7823 * operand is read even if it isn't needed (e.g., for type==global)
7825 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7826 vmx_instruction_info, false, &gva))
7828 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
7829 kvm_inject_page_fault(vcpu, &e);
7834 case VMX_EPT_EXTENT_GLOBAL:
7836 * TODO: track mappings and invalidate
7837 * single context requests appropriately
7839 case VMX_EPT_EXTENT_CONTEXT:
7840 kvm_mmu_sync_roots(vcpu);
7841 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7842 nested_vmx_succeed(vcpu);
7849 skip_emulated_instruction(vcpu);
7853 static int handle_invvpid(struct kvm_vcpu *vcpu)
7855 struct vcpu_vmx *vmx = to_vmx(vcpu);
7856 u32 vmx_instruction_info;
7857 unsigned long type, types;
7859 struct x86_exception e;
7862 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7863 SECONDARY_EXEC_ENABLE_VPID) ||
7864 !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
7865 kvm_queue_exception(vcpu, UD_VECTOR);
7869 if (!nested_vmx_check_permission(vcpu))
7872 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7873 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7875 types = (vmx->nested.nested_vmx_vpid_caps &
7876 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
7878 if (type >= 32 || !(types & (1 << type))) {
7879 nested_vmx_failValid(vcpu,
7880 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7881 skip_emulated_instruction(vcpu);
7885 /* according to the intel vmx instruction reference, the memory
7886 * operand is read even if it isn't needed (e.g., for type==global)
7888 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7889 vmx_instruction_info, false, &gva))
7891 if (kvm_read_guest_virt(vcpu, gva, &vpid, sizeof(u32), &e)) {
7892 kvm_inject_page_fault(vcpu, &e);
7897 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
7898 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
7899 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
7901 nested_vmx_failValid(vcpu,
7902 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7903 skip_emulated_instruction(vcpu);
7907 case VMX_VPID_EXTENT_ALL_CONTEXT:
7911 skip_emulated_instruction(vcpu);
7915 __vmx_flush_tlb(vcpu, vmx->nested.vpid02);
7916 nested_vmx_succeed(vcpu);
7918 skip_emulated_instruction(vcpu);
7922 static int handle_pml_full(struct kvm_vcpu *vcpu)
7924 unsigned long exit_qualification;
7926 trace_kvm_pml_full(vcpu->vcpu_id);
7928 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7931 * PML buffer FULL happened while executing iret from NMI,
7932 * "blocked by NMI" bit has to be set before next VM entry.
7934 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7935 cpu_has_virtual_nmis() &&
7936 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7937 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7938 GUEST_INTR_STATE_NMI);
7941 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
7942 * here.., and there's no userspace involvement needed for PML.
7947 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
7949 kvm_lapic_expired_hv_timer(vcpu);
7954 * The exit handlers return 1 if the exit was handled fully and guest execution
7955 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
7956 * to be done to userspace and return 0.
7958 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
7959 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
7960 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
7961 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
7962 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
7963 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
7964 [EXIT_REASON_CR_ACCESS] = handle_cr,
7965 [EXIT_REASON_DR_ACCESS] = handle_dr,
7966 [EXIT_REASON_CPUID] = handle_cpuid,
7967 [EXIT_REASON_MSR_READ] = handle_rdmsr,
7968 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
7969 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
7970 [EXIT_REASON_HLT] = handle_halt,
7971 [EXIT_REASON_INVD] = handle_invd,
7972 [EXIT_REASON_INVLPG] = handle_invlpg,
7973 [EXIT_REASON_RDPMC] = handle_rdpmc,
7974 [EXIT_REASON_VMCALL] = handle_vmcall,
7975 [EXIT_REASON_VMCLEAR] = handle_vmclear,
7976 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
7977 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
7978 [EXIT_REASON_VMPTRST] = handle_vmptrst,
7979 [EXIT_REASON_VMREAD] = handle_vmread,
7980 [EXIT_REASON_VMRESUME] = handle_vmresume,
7981 [EXIT_REASON_VMWRITE] = handle_vmwrite,
7982 [EXIT_REASON_VMOFF] = handle_vmoff,
7983 [EXIT_REASON_VMON] = handle_vmon,
7984 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
7985 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
7986 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
7987 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
7988 [EXIT_REASON_WBINVD] = handle_wbinvd,
7989 [EXIT_REASON_XSETBV] = handle_xsetbv,
7990 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
7991 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
7992 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
7993 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
7994 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
7995 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
7996 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
7997 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
7998 [EXIT_REASON_INVEPT] = handle_invept,
7999 [EXIT_REASON_INVVPID] = handle_invvpid,
8000 [EXIT_REASON_XSAVES] = handle_xsaves,
8001 [EXIT_REASON_XRSTORS] = handle_xrstors,
8002 [EXIT_REASON_PML_FULL] = handle_pml_full,
8003 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
8006 static const int kvm_vmx_max_exit_handlers =
8007 ARRAY_SIZE(kvm_vmx_exit_handlers);
8009 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8010 struct vmcs12 *vmcs12)
8012 unsigned long exit_qualification;
8013 gpa_t bitmap, last_bitmap;
8018 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8019 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8021 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8023 port = exit_qualification >> 16;
8024 size = (exit_qualification & 7) + 1;
8026 last_bitmap = (gpa_t)-1;
8031 bitmap = vmcs12->io_bitmap_a;
8032 else if (port < 0x10000)
8033 bitmap = vmcs12->io_bitmap_b;
8036 bitmap += (port & 0x7fff) / 8;
8038 if (last_bitmap != bitmap)
8039 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8041 if (b & (1 << (port & 7)))
8046 last_bitmap = bitmap;
8053 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8054 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8055 * disinterest in the current event (read or write a specific MSR) by using an
8056 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8058 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8059 struct vmcs12 *vmcs12, u32 exit_reason)
8061 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8064 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8068 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8069 * for the four combinations of read/write and low/high MSR numbers.
8070 * First we need to figure out which of the four to use:
8072 bitmap = vmcs12->msr_bitmap;
8073 if (exit_reason == EXIT_REASON_MSR_WRITE)
8075 if (msr_index >= 0xc0000000) {
8076 msr_index -= 0xc0000000;
8080 /* Then read the msr_index'th bit from this bitmap: */
8081 if (msr_index < 1024*8) {
8083 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8085 return 1 & (b >> (msr_index & 7));
8087 return true; /* let L1 handle the wrong parameter */
8091 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8092 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8093 * intercept (via guest_host_mask etc.) the current event.
8095 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8096 struct vmcs12 *vmcs12)
8098 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8099 int cr = exit_qualification & 15;
8103 switch ((exit_qualification >> 4) & 3) {
8104 case 0: /* mov to cr */
8105 reg = (exit_qualification >> 8) & 15;
8106 val = kvm_register_readl(vcpu, reg);
8109 if (vmcs12->cr0_guest_host_mask &
8110 (val ^ vmcs12->cr0_read_shadow))
8114 if ((vmcs12->cr3_target_count >= 1 &&
8115 vmcs12->cr3_target_value0 == val) ||
8116 (vmcs12->cr3_target_count >= 2 &&
8117 vmcs12->cr3_target_value1 == val) ||
8118 (vmcs12->cr3_target_count >= 3 &&
8119 vmcs12->cr3_target_value2 == val) ||
8120 (vmcs12->cr3_target_count >= 4 &&
8121 vmcs12->cr3_target_value3 == val))
8123 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8127 if (vmcs12->cr4_guest_host_mask &
8128 (vmcs12->cr4_read_shadow ^ val))
8132 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8138 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8139 (vmcs12->cr0_read_shadow & X86_CR0_TS))
8142 case 1: /* mov from cr */
8145 if (vmcs12->cpu_based_vm_exec_control &
8146 CPU_BASED_CR3_STORE_EXITING)
8150 if (vmcs12->cpu_based_vm_exec_control &
8151 CPU_BASED_CR8_STORE_EXITING)
8158 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8159 * cr0. Other attempted changes are ignored, with no exit.
8161 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8162 if (vmcs12->cr0_guest_host_mask & 0xe &
8163 (val ^ vmcs12->cr0_read_shadow))
8165 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8166 !(vmcs12->cr0_read_shadow & 0x1) &&
8175 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8176 * should handle it ourselves in L0 (and then continue L2). Only call this
8177 * when in is_guest_mode (L2).
8179 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
8181 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8182 struct vcpu_vmx *vmx = to_vmx(vcpu);
8183 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8184 u32 exit_reason = vmx->exit_reason;
8186 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8187 vmcs_readl(EXIT_QUALIFICATION),
8188 vmx->idt_vectoring_info,
8190 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8194 * The host physical addresses of some pages of guest memory
8195 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
8196 * Page). The CPU may write to these pages via their host
8197 * physical address while L2 is running, bypassing any
8198 * address-translation-based dirty tracking (e.g. EPT write
8201 * Mark them dirty on every exit from L2 to prevent them from
8202 * getting out of sync with dirty tracking.
8204 nested_mark_vmcs12_pages_dirty(vcpu);
8206 if (vmx->nested.nested_run_pending)
8209 if (unlikely(vmx->fail)) {
8210 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8211 vmcs_read32(VM_INSTRUCTION_ERROR));
8215 switch (exit_reason) {
8216 case EXIT_REASON_EXCEPTION_NMI:
8217 if (is_nmi(intr_info))
8219 else if (is_page_fault(intr_info))
8221 else if (is_no_device(intr_info) &&
8222 !(vmcs12->guest_cr0 & X86_CR0_TS))
8224 else if (is_debug(intr_info) &&
8226 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8228 else if (is_breakpoint(intr_info) &&
8229 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8231 return vmcs12->exception_bitmap &
8232 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8233 case EXIT_REASON_EXTERNAL_INTERRUPT:
8235 case EXIT_REASON_TRIPLE_FAULT:
8237 case EXIT_REASON_PENDING_INTERRUPT:
8238 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8239 case EXIT_REASON_NMI_WINDOW:
8240 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8241 case EXIT_REASON_TASK_SWITCH:
8243 case EXIT_REASON_CPUID:
8245 case EXIT_REASON_HLT:
8246 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8247 case EXIT_REASON_INVD:
8249 case EXIT_REASON_INVLPG:
8250 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8251 case EXIT_REASON_RDPMC:
8252 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8253 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8254 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8255 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8256 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8257 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8258 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8259 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8260 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8262 * VMX instructions trap unconditionally. This allows L1 to
8263 * emulate them for its L2 guest, i.e., allows 3-level nesting!
8266 case EXIT_REASON_CR_ACCESS:
8267 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8268 case EXIT_REASON_DR_ACCESS:
8269 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8270 case EXIT_REASON_IO_INSTRUCTION:
8271 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8272 case EXIT_REASON_MSR_READ:
8273 case EXIT_REASON_MSR_WRITE:
8274 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8275 case EXIT_REASON_INVALID_STATE:
8277 case EXIT_REASON_MWAIT_INSTRUCTION:
8278 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8279 case EXIT_REASON_MONITOR_TRAP_FLAG:
8280 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8281 case EXIT_REASON_MONITOR_INSTRUCTION:
8282 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8283 case EXIT_REASON_PAUSE_INSTRUCTION:
8284 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8285 nested_cpu_has2(vmcs12,
8286 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8287 case EXIT_REASON_MCE_DURING_VMENTRY:
8289 case EXIT_REASON_TPR_BELOW_THRESHOLD:
8290 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8291 case EXIT_REASON_APIC_ACCESS:
8292 return nested_cpu_has2(vmcs12,
8293 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8294 case EXIT_REASON_APIC_WRITE:
8295 case EXIT_REASON_EOI_INDUCED:
8296 /* apic_write and eoi_induced should exit unconditionally. */
8298 case EXIT_REASON_EPT_VIOLATION:
8300 * L0 always deals with the EPT violation. If nested EPT is
8301 * used, and the nested mmu code discovers that the address is
8302 * missing in the guest EPT table (EPT12), the EPT violation
8303 * will be injected with nested_ept_inject_page_fault()
8306 case EXIT_REASON_EPT_MISCONFIG:
8308 * L2 never uses directly L1's EPT, but rather L0's own EPT
8309 * table (shadow on EPT) or a merged EPT table that L0 built
8310 * (EPT on EPT). So any problems with the structure of the
8311 * table is L0's fault.
8314 case EXIT_REASON_WBINVD:
8315 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8316 case EXIT_REASON_XSETBV:
8318 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8320 * This should never happen, since it is not possible to
8321 * set XSS to a non-zero value---neither in L1 nor in L2.
8322 * If if it were, XSS would have to be checked against
8323 * the XSS exit bitmap in vmcs12.
8325 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8326 case EXIT_REASON_PREEMPTION_TIMER:
8328 case EXIT_REASON_PML_FULL:
8329 /* We don't expose PML support to L1. */
8336 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8338 *info1 = vmcs_readl(EXIT_QUALIFICATION);
8339 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8342 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8345 __free_page(vmx->pml_pg);
8350 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8352 struct vcpu_vmx *vmx = to_vmx(vcpu);
8356 pml_idx = vmcs_read16(GUEST_PML_INDEX);
8358 /* Do nothing if PML buffer is empty */
8359 if (pml_idx == (PML_ENTITY_NUM - 1))
8362 /* PML index always points to next available PML buffer entity */
8363 if (pml_idx >= PML_ENTITY_NUM)
8368 pml_buf = page_address(vmx->pml_pg);
8369 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8372 gpa = pml_buf[pml_idx];
8373 WARN_ON(gpa & (PAGE_SIZE - 1));
8374 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8377 /* reset PML index */
8378 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8382 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8383 * Called before reporting dirty_bitmap to userspace.
8385 static void kvm_flush_pml_buffers(struct kvm *kvm)
8388 struct kvm_vcpu *vcpu;
8390 * We only need to kick vcpu out of guest mode here, as PML buffer
8391 * is flushed at beginning of all VMEXITs, and it's obvious that only
8392 * vcpus running in guest are possible to have unflushed GPAs in PML
8395 kvm_for_each_vcpu(i, vcpu, kvm)
8396 kvm_vcpu_kick(vcpu);
8399 static void vmx_dump_sel(char *name, uint32_t sel)
8401 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8402 name, vmcs_read16(sel),
8403 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8404 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8405 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8408 static void vmx_dump_dtsel(char *name, uint32_t limit)
8410 pr_err("%s limit=0x%08x, base=0x%016lx\n",
8411 name, vmcs_read32(limit),
8412 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8415 static void dump_vmcs(void)
8417 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8418 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8419 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8420 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8421 u32 secondary_exec_control = 0;
8422 unsigned long cr4 = vmcs_readl(GUEST_CR4);
8423 u64 efer = vmcs_read64(GUEST_IA32_EFER);
8426 if (cpu_has_secondary_exec_ctrls())
8427 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8429 pr_err("*** Guest State ***\n");
8430 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8431 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8432 vmcs_readl(CR0_GUEST_HOST_MASK));
8433 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8434 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8435 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8436 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8437 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8439 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
8440 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8441 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
8442 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8444 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
8445 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8446 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
8447 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8448 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8449 vmcs_readl(GUEST_SYSENTER_ESP),
8450 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8451 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
8452 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
8453 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
8454 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
8455 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
8456 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
8457 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8458 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8459 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8460 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
8461 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8462 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8463 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8464 efer, vmcs_read64(GUEST_IA32_PAT));
8465 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
8466 vmcs_read64(GUEST_IA32_DEBUGCTL),
8467 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8468 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8469 pr_err("PerfGlobCtl = 0x%016llx\n",
8470 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8471 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8472 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8473 pr_err("Interruptibility = %08x ActivityState = %08x\n",
8474 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8475 vmcs_read32(GUEST_ACTIVITY_STATE));
8476 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8477 pr_err("InterruptStatus = %04x\n",
8478 vmcs_read16(GUEST_INTR_STATUS));
8480 pr_err("*** Host State ***\n");
8481 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
8482 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8483 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8484 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8485 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8486 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8487 vmcs_read16(HOST_TR_SELECTOR));
8488 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8489 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8490 vmcs_readl(HOST_TR_BASE));
8491 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8492 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8493 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8494 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8495 vmcs_readl(HOST_CR4));
8496 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8497 vmcs_readl(HOST_IA32_SYSENTER_ESP),
8498 vmcs_read32(HOST_IA32_SYSENTER_CS),
8499 vmcs_readl(HOST_IA32_SYSENTER_EIP));
8500 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8501 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8502 vmcs_read64(HOST_IA32_EFER),
8503 vmcs_read64(HOST_IA32_PAT));
8504 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8505 pr_err("PerfGlobCtl = 0x%016llx\n",
8506 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8508 pr_err("*** Control State ***\n");
8509 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8510 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8511 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8512 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8513 vmcs_read32(EXCEPTION_BITMAP),
8514 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8515 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8516 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8517 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8518 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8519 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8520 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8521 vmcs_read32(VM_EXIT_INTR_INFO),
8522 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8523 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8524 pr_err(" reason=%08x qualification=%016lx\n",
8525 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8526 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8527 vmcs_read32(IDT_VECTORING_INFO_FIELD),
8528 vmcs_read32(IDT_VECTORING_ERROR_CODE));
8529 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8530 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8531 pr_err("TSC Multiplier = 0x%016llx\n",
8532 vmcs_read64(TSC_MULTIPLIER));
8533 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8534 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8535 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8536 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8537 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8538 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8539 n = vmcs_read32(CR3_TARGET_COUNT);
8540 for (i = 0; i + 1 < n; i += 4)
8541 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8542 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8543 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8545 pr_err("CR3 target%u=%016lx\n",
8546 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8547 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8548 pr_err("PLE Gap=%08x Window=%08x\n",
8549 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8550 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8551 pr_err("Virtual processor ID = 0x%04x\n",
8552 vmcs_read16(VIRTUAL_PROCESSOR_ID));
8556 * The guest has exited. See if we can fix it or if we need userspace
8559 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8561 struct vcpu_vmx *vmx = to_vmx(vcpu);
8562 u32 exit_reason = vmx->exit_reason;
8563 u32 vectoring_info = vmx->idt_vectoring_info;
8565 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8568 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8569 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8570 * querying dirty_bitmap, we only need to kick all vcpus out of guest
8571 * mode as if vcpus is in root mode, the PML buffer must has been
8575 vmx_flush_pml_buffer(vcpu);
8577 /* If guest state is invalid, start emulating */
8578 if (vmx->emulation_required)
8579 return handle_invalid_guest_state(vcpu);
8581 if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
8582 nested_vmx_vmexit(vcpu, exit_reason,
8583 vmcs_read32(VM_EXIT_INTR_INFO),
8584 vmcs_readl(EXIT_QUALIFICATION));
8588 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8590 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8591 vcpu->run->fail_entry.hardware_entry_failure_reason
8596 if (unlikely(vmx->fail)) {
8597 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8598 vcpu->run->fail_entry.hardware_entry_failure_reason
8599 = vmcs_read32(VM_INSTRUCTION_ERROR);
8605 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8606 * delivery event since it indicates guest is accessing MMIO.
8607 * The vm-exit can be triggered again after return to guest that
8608 * will cause infinite loop.
8610 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8611 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8612 exit_reason != EXIT_REASON_EPT_VIOLATION &&
8613 exit_reason != EXIT_REASON_PML_FULL &&
8614 exit_reason != EXIT_REASON_TASK_SWITCH)) {
8615 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8616 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8617 vcpu->run->internal.ndata = 2;
8618 vcpu->run->internal.data[0] = vectoring_info;
8619 vcpu->run->internal.data[1] = exit_reason;
8623 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
8624 !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
8625 get_vmcs12(vcpu))))) {
8626 if (vmx_interrupt_allowed(vcpu)) {
8627 vmx->soft_vnmi_blocked = 0;
8628 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
8629 vcpu->arch.nmi_pending) {
8631 * This CPU don't support us in finding the end of an
8632 * NMI-blocked window if the guest runs with IRQs
8633 * disabled. So we pull the trigger after 1 s of
8634 * futile waiting, but inform the user about this.
8636 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8637 "state on VCPU %d after 1 s timeout\n",
8638 __func__, vcpu->vcpu_id);
8639 vmx->soft_vnmi_blocked = 0;
8643 if (exit_reason < kvm_vmx_max_exit_handlers
8644 && kvm_vmx_exit_handlers[exit_reason])
8645 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8647 WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
8648 kvm_queue_exception(vcpu, UD_VECTOR);
8654 * Software based L1D cache flush which is used when microcode providing
8655 * the cache control MSR is not loaded.
8657 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
8658 * flush it is required to read in 64 KiB because the replacement algorithm
8659 * is not exactly LRU. This could be sized at runtime via topology
8660 * information but as all relevant affected CPUs have 32KiB L1D cache size
8661 * there is no point in doing so.
8663 #define L1D_CACHE_ORDER 4
8664 static void *vmx_l1d_flush_pages;
8666 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
8668 int size = PAGE_SIZE << L1D_CACHE_ORDER;
8671 * This code is only executed when the the flush mode is 'cond' or
8674 if (static_branch_likely(&vmx_l1d_flush_cond)) {
8678 * Clear the per-vcpu flush bit, it gets set again
8679 * either from vcpu_run() or from one of the unsafe
8682 flush_l1d = vcpu->arch.l1tf_flush_l1d;
8683 vcpu->arch.l1tf_flush_l1d = false;
8686 * Clear the per-cpu flush bit, it gets set again from
8687 * the interrupt handlers.
8689 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
8690 kvm_clear_cpu_l1tf_flush_l1d();
8696 vcpu->stat.l1d_flush++;
8698 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
8699 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
8704 /* First ensure the pages are in the TLB */
8705 "xorl %%eax, %%eax\n"
8706 ".Lpopulate_tlb:\n\t"
8707 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
8708 "addl $4096, %%eax\n\t"
8709 "cmpl %%eax, %[size]\n\t"
8710 "jne .Lpopulate_tlb\n\t"
8711 "xorl %%eax, %%eax\n\t"
8713 /* Now fill the cache */
8714 "xorl %%eax, %%eax\n"
8716 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
8717 "addl $64, %%eax\n\t"
8718 "cmpl %%eax, %[size]\n\t"
8719 "jne .Lfill_cache\n\t"
8721 :: [flush_pages] "r" (vmx_l1d_flush_pages),
8723 : "eax", "ebx", "ecx", "edx");
8726 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8728 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8730 if (is_guest_mode(vcpu) &&
8731 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8734 if (irr == -1 || tpr < irr) {
8735 vmcs_write32(TPR_THRESHOLD, 0);
8739 vmcs_write32(TPR_THRESHOLD, irr);
8742 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8744 u32 sec_exec_control;
8746 /* Postpone execution until vmcs01 is the current VMCS. */
8747 if (is_guest_mode(vcpu)) {
8748 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8752 if (!cpu_has_vmx_virtualize_x2apic_mode())
8755 if (!cpu_need_tpr_shadow(vcpu))
8758 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8761 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8762 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8764 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8765 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8766 vmx_flush_tlb_ept_only(vcpu);
8768 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
8770 vmx_update_msr_bitmap(vcpu);
8773 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
8775 struct vcpu_vmx *vmx = to_vmx(vcpu);
8778 * Currently we do not handle the nested case where L2 has an
8779 * APIC access page of its own; that page is still pinned.
8780 * Hence, we skip the case where the VCPU is in guest mode _and_
8781 * L1 prepared an APIC access page for L2.
8783 * For the case where L1 and L2 share the same APIC access page
8784 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
8785 * in the vmcs12), this function will only update either the vmcs01
8786 * or the vmcs02. If the former, the vmcs02 will be updated by
8787 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
8788 * the next L2->L1 exit.
8790 if (!is_guest_mode(vcpu) ||
8791 !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
8792 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8793 vmcs_write64(APIC_ACCESS_ADDR, hpa);
8794 vmx_flush_tlb_ept_only(vcpu);
8798 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
8806 status = vmcs_read16(GUEST_INTR_STATUS);
8808 if (max_isr != old) {
8810 status |= max_isr << 8;
8811 vmcs_write16(GUEST_INTR_STATUS, status);
8815 static void vmx_set_rvi(int vector)
8823 status = vmcs_read16(GUEST_INTR_STATUS);
8824 old = (u8)status & 0xff;
8825 if ((u8)vector != old) {
8827 status |= (u8)vector;
8828 vmcs_write16(GUEST_INTR_STATUS, status);
8832 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
8834 if (!is_guest_mode(vcpu)) {
8835 vmx_set_rvi(max_irr);
8843 * In guest mode. If a vmexit is needed, vmx_check_nested_events
8846 if (nested_exit_on_intr(vcpu))
8850 * Else, fall back to pre-APICv interrupt injection since L2
8851 * is run without virtual interrupt delivery.
8853 if (!kvm_event_needs_reinjection(vcpu) &&
8854 vmx_interrupt_allowed(vcpu)) {
8855 kvm_queue_interrupt(vcpu, max_irr, false);
8856 vmx_inject_irq(vcpu);
8860 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
8862 if (!kvm_vcpu_apicv_active(vcpu))
8865 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
8866 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
8867 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
8868 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
8871 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
8875 if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
8876 || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
8879 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8880 exit_intr_info = vmx->exit_intr_info;
8882 /* Handle machine checks before interrupts are enabled */
8883 if (is_machine_check(exit_intr_info))
8884 kvm_machine_check();
8886 /* We need to handle NMIs before interrupts are enabled */
8887 if (is_nmi(exit_intr_info)) {
8888 kvm_before_handle_nmi(&vmx->vcpu);
8890 kvm_after_handle_nmi(&vmx->vcpu);
8894 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
8896 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8897 register void *__sp asm(_ASM_SP);
8900 * If external interrupt exists, IF bit is set in rflags/eflags on the
8901 * interrupt stack frame, and interrupt will be enabled on a return
8902 * from interrupt handler.
8904 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
8905 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
8906 unsigned int vector;
8907 unsigned long entry;
8909 struct vcpu_vmx *vmx = to_vmx(vcpu);
8910 #ifdef CONFIG_X86_64
8914 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
8915 desc = (gate_desc *)vmx->host_idt_base + vector;
8916 entry = gate_offset(*desc);
8918 #ifdef CONFIG_X86_64
8919 "mov %%" _ASM_SP ", %[sp]\n\t"
8920 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
8925 __ASM_SIZE(push) " $%c[cs]\n\t"
8928 #ifdef CONFIG_X86_64
8933 THUNK_TARGET(entry),
8934 [ss]"i"(__KERNEL_DS),
8935 [cs]"i"(__KERNEL_CS)
8939 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
8941 static bool vmx_has_emulated_msr(int index)
8944 case MSR_IA32_SMBASE:
8946 * We cannot do SMM unless we can run the guest in big
8949 return enable_unrestricted_guest || emulate_invalid_guest_state;
8950 case MSR_AMD64_VIRT_SPEC_CTRL:
8951 /* This is AMD only. */
8958 static bool vmx_mpx_supported(void)
8960 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
8961 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
8964 static bool vmx_xsaves_supported(void)
8966 return vmcs_config.cpu_based_2nd_exec_ctrl &
8967 SECONDARY_EXEC_XSAVES;
8970 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
8975 bool idtv_info_valid;
8977 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
8979 if (cpu_has_virtual_nmis()) {
8980 if (vmx->nmi_known_unmasked)
8983 * Can't use vmx->exit_intr_info since we're not sure what
8984 * the exit reason is.
8986 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8987 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
8988 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
8990 * SDM 3: 27.7.1.2 (September 2008)
8991 * Re-set bit "block by NMI" before VM entry if vmexit caused by
8992 * a guest IRET fault.
8993 * SDM 3: 23.2.2 (September 2008)
8994 * Bit 12 is undefined in any of the following cases:
8995 * If the VM exit sets the valid bit in the IDT-vectoring
8996 * information field.
8997 * If the VM exit is due to a double fault.
8999 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9000 vector != DF_VECTOR && !idtv_info_valid)
9001 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9002 GUEST_INTR_STATE_NMI);
9004 vmx->nmi_known_unmasked =
9005 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9006 & GUEST_INTR_STATE_NMI);
9007 } else if (unlikely(vmx->soft_vnmi_blocked))
9008 vmx->vnmi_blocked_time +=
9009 ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
9012 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9013 u32 idt_vectoring_info,
9014 int instr_len_field,
9015 int error_code_field)
9019 bool idtv_info_valid;
9021 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9023 vcpu->arch.nmi_injected = false;
9024 kvm_clear_exception_queue(vcpu);
9025 kvm_clear_interrupt_queue(vcpu);
9027 if (!idtv_info_valid)
9030 kvm_make_request(KVM_REQ_EVENT, vcpu);
9032 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9033 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9036 case INTR_TYPE_NMI_INTR:
9037 vcpu->arch.nmi_injected = true;
9039 * SDM 3: 27.7.1.2 (September 2008)
9040 * Clear bit "block by NMI" before VM entry if a NMI
9043 vmx_set_nmi_mask(vcpu, false);
9045 case INTR_TYPE_SOFT_EXCEPTION:
9046 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9048 case INTR_TYPE_HARD_EXCEPTION:
9049 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9050 u32 err = vmcs_read32(error_code_field);
9051 kvm_requeue_exception_e(vcpu, vector, err);
9053 kvm_requeue_exception(vcpu, vector);
9055 case INTR_TYPE_SOFT_INTR:
9056 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9058 case INTR_TYPE_EXT_INTR:
9059 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9066 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9068 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9069 VM_EXIT_INSTRUCTION_LEN,
9070 IDT_VECTORING_ERROR_CODE);
9073 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9075 __vmx_complete_interrupts(vcpu,
9076 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9077 VM_ENTRY_INSTRUCTION_LEN,
9078 VM_ENTRY_EXCEPTION_ERROR_CODE);
9080 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9083 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9086 struct perf_guest_switch_msr *msrs;
9088 msrs = perf_guest_get_msrs(&nr_msrs);
9093 for (i = 0; i < nr_msrs; i++)
9094 if (msrs[i].host == msrs[i].guest)
9095 clear_atomic_switch_msr(vmx, msrs[i].msr);
9097 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9098 msrs[i].host, false);
9101 void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9103 struct vcpu_vmx *vmx = to_vmx(vcpu);
9107 if (vmx->hv_deadline_tsc == -1)
9111 if (vmx->hv_deadline_tsc > tscl)
9112 /* sure to be 32 bit only because checked on set_hv_timer */
9113 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9114 cpu_preemption_timer_multi);
9118 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9121 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9123 struct vcpu_vmx *vmx = to_vmx(vcpu);
9124 unsigned long debugctlmsr, cr4;
9126 /* Record the guest's net vcpu time for enforced NMI injections. */
9127 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
9128 vmx->entry_time = ktime_get();
9130 /* Don't enter VMX if guest state is invalid, let the exit handler
9131 start emulation until we arrive back to a valid state */
9132 if (vmx->emulation_required)
9135 if (vmx->ple_window_dirty) {
9136 vmx->ple_window_dirty = false;
9137 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9140 if (vmx->nested.sync_shadow_vmcs) {
9141 copy_vmcs12_to_shadow(vmx);
9142 vmx->nested.sync_shadow_vmcs = false;
9145 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9146 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9147 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9148 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9150 cr4 = cr4_read_shadow();
9151 if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
9152 vmcs_writel(HOST_CR4, cr4);
9153 vmx->host_state.vmcs_host_cr4 = cr4;
9156 /* When single-stepping over STI and MOV SS, we must clear the
9157 * corresponding interruptibility bits in the guest state. Otherwise
9158 * vmentry fails as it then expects bit 14 (BS) in pending debug
9159 * exceptions being set, but that's not correct for the guest debugging
9161 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9162 vmx_set_interrupt_shadow(vcpu, 0);
9164 if (vmx->guest_pkru_valid)
9165 __write_pkru(vmx->guest_pkru);
9167 atomic_switch_perf_msrs(vmx);
9168 debugctlmsr = get_debugctlmsr();
9170 vmx_arm_hv_timer(vcpu);
9173 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
9174 * it's non-zero. Since vmentry is serialising on affected CPUs, there
9175 * is no need to worry about the conditional branch over the wrmsr
9176 * being speculatively taken.
9178 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
9180 vmx->__launched = vmx->loaded_vmcs->launched;
9182 if (static_branch_unlikely(&vmx_l1d_should_flush))
9183 vmx_l1d_flush(vcpu);
9186 /* Store host registers */
9187 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9188 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9189 "push %%" _ASM_CX " \n\t"
9190 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9192 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9193 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9195 /* Reload cr2 if changed */
9196 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9197 "mov %%cr2, %%" _ASM_DX " \n\t"
9198 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9200 "mov %%" _ASM_AX", %%cr2 \n\t"
9202 /* Check if vmlaunch of vmresume is needed */
9203 "cmpl $0, %c[launched](%0) \n\t"
9204 /* Load guest registers. Don't clobber flags. */
9205 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9206 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9207 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9208 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9209 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9210 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9211 #ifdef CONFIG_X86_64
9212 "mov %c[r8](%0), %%r8 \n\t"
9213 "mov %c[r9](%0), %%r9 \n\t"
9214 "mov %c[r10](%0), %%r10 \n\t"
9215 "mov %c[r11](%0), %%r11 \n\t"
9216 "mov %c[r12](%0), %%r12 \n\t"
9217 "mov %c[r13](%0), %%r13 \n\t"
9218 "mov %c[r14](%0), %%r14 \n\t"
9219 "mov %c[r15](%0), %%r15 \n\t"
9221 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9223 /* Enter guest mode */
9225 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9227 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9229 /* Save guest registers, load host registers, keep flags */
9230 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9232 "setbe %c[fail](%0)\n\t"
9233 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9234 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9235 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9236 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9237 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9238 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9239 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9240 #ifdef CONFIG_X86_64
9241 "mov %%r8, %c[r8](%0) \n\t"
9242 "mov %%r9, %c[r9](%0) \n\t"
9243 "mov %%r10, %c[r10](%0) \n\t"
9244 "mov %%r11, %c[r11](%0) \n\t"
9245 "mov %%r12, %c[r12](%0) \n\t"
9246 "mov %%r13, %c[r13](%0) \n\t"
9247 "mov %%r14, %c[r14](%0) \n\t"
9248 "mov %%r15, %c[r15](%0) \n\t"
9249 "xor %%r8d, %%r8d \n\t"
9250 "xor %%r9d, %%r9d \n\t"
9251 "xor %%r10d, %%r10d \n\t"
9252 "xor %%r11d, %%r11d \n\t"
9253 "xor %%r12d, %%r12d \n\t"
9254 "xor %%r13d, %%r13d \n\t"
9255 "xor %%r14d, %%r14d \n\t"
9256 "xor %%r15d, %%r15d \n\t"
9258 "mov %%cr2, %%" _ASM_AX " \n\t"
9259 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9261 "xor %%eax, %%eax \n\t"
9262 "xor %%ebx, %%ebx \n\t"
9263 "xor %%esi, %%esi \n\t"
9264 "xor %%edi, %%edi \n\t"
9265 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
9266 ".pushsection .rodata \n\t"
9267 ".global vmx_return \n\t"
9268 "vmx_return: " _ASM_PTR " 2b \n\t"
9270 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9271 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9272 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9273 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9274 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9275 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9276 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9277 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9278 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9279 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9280 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9281 #ifdef CONFIG_X86_64
9282 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9283 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9284 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9285 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9286 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9287 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9288 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9289 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9291 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9292 [wordsize]"i"(sizeof(ulong))
9294 #ifdef CONFIG_X86_64
9295 , "rax", "rbx", "rdi", "rsi"
9296 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9298 , "eax", "ebx", "edi", "esi"
9303 * We do not use IBRS in the kernel. If this vCPU has used the
9304 * SPEC_CTRL MSR it may have left it on; save the value and
9305 * turn it off. This is much more efficient than blindly adding
9306 * it to the atomic save/restore list. Especially as the former
9307 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
9309 * For non-nested case:
9310 * If the L01 MSR bitmap does not intercept the MSR, then we need to
9314 * If the L02 MSR bitmap does not intercept the MSR, then we need to
9317 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
9318 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
9320 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
9322 /* Eliminate branch target predictions from guest mode */
9325 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9327 update_debugctlmsr(debugctlmsr);
9329 #ifndef CONFIG_X86_64
9331 * The sysexit path does not restore ds/es, so we must set them to
9332 * a reasonable value ourselves.
9334 * We can't defer this to vmx_load_host_state() since that function
9335 * may be executed in interrupt context, which saves and restore segments
9336 * around it, nullifying its effect.
9338 loadsegment(ds, __USER_DS);
9339 loadsegment(es, __USER_DS);
9342 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9343 | (1 << VCPU_EXREG_RFLAGS)
9344 | (1 << VCPU_EXREG_PDPTR)
9345 | (1 << VCPU_EXREG_SEGMENTS)
9346 | (1 << VCPU_EXREG_CR3));
9347 vcpu->arch.regs_dirty = 0;
9349 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9351 vmx->loaded_vmcs->launched = 1;
9353 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
9356 * eager fpu is enabled if PKEY is supported and CR4 is switched
9357 * back on host, so it is safe to read guest PKRU from current
9360 if (boot_cpu_has(X86_FEATURE_OSPKE)) {
9361 vmx->guest_pkru = __read_pkru();
9362 if (vmx->guest_pkru != vmx->host_pkru) {
9363 vmx->guest_pkru_valid = true;
9364 __write_pkru(vmx->host_pkru);
9366 vmx->guest_pkru_valid = false;
9370 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9371 * we did not inject a still-pending event to L1 now because of
9372 * nested_run_pending, we need to re-enable this bit.
9374 if (vmx->nested.nested_run_pending)
9375 kvm_make_request(KVM_REQ_EVENT, vcpu);
9377 vmx->nested.nested_run_pending = 0;
9379 vmx_complete_atomic_exit(vmx);
9380 vmx_recover_nmi_blocking(vmx);
9381 vmx_complete_interrupts(vmx);
9383 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9385 static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
9387 struct vcpu_vmx *vmx = to_vmx(vcpu);
9390 if (vmx->loaded_vmcs == &vmx->vmcs01)
9394 vmx->loaded_vmcs = &vmx->vmcs01;
9396 vmx_vcpu_load(vcpu, cpu);
9402 * Ensure that the current vmcs of the logical processor is the
9403 * vmcs01 of the vcpu before calling free_nested().
9405 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9407 struct vcpu_vmx *vmx = to_vmx(vcpu);
9410 r = vcpu_load(vcpu);
9412 vmx_load_vmcs01(vcpu);
9417 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9419 struct vcpu_vmx *vmx = to_vmx(vcpu);
9422 vmx_destroy_pml_buffer(vmx);
9423 free_vpid(vmx->vpid);
9424 leave_guest_mode(vcpu);
9425 vmx_free_vcpu_nested(vcpu);
9426 free_loaded_vmcs(vmx->loaded_vmcs);
9427 kfree(vmx->guest_msrs);
9428 kvm_vcpu_uninit(vcpu);
9429 kmem_cache_free(kvm_vcpu_cache, vmx);
9432 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9435 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9436 unsigned long *msr_bitmap;
9440 return ERR_PTR(-ENOMEM);
9442 vmx->vpid = allocate_vpid();
9444 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9451 * If PML is turned on, failure on enabling PML just results in failure
9452 * of creating the vcpu, therefore we can simplify PML logic (by
9453 * avoiding dealing with cases, such as enabling PML partially on vcpus
9454 * for the guest, etc.
9457 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9462 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9463 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9466 if (!vmx->guest_msrs)
9470 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
9471 err = alloc_loaded_vmcs(&vmx->vmcs01);
9477 msr_bitmap = vmx->vmcs01.msr_bitmap;
9478 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
9479 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
9480 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
9481 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
9482 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
9483 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
9484 vmx->msr_bitmap_mode = 0;
9486 vmx->loaded_vmcs = &vmx->vmcs01;
9488 vmx_vcpu_load(&vmx->vcpu, cpu);
9489 vmx->vcpu.cpu = cpu;
9490 err = vmx_vcpu_setup(vmx);
9491 vmx_vcpu_put(&vmx->vcpu);
9495 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9496 err = alloc_apic_access_page(kvm);
9502 if (!kvm->arch.ept_identity_map_addr)
9503 kvm->arch.ept_identity_map_addr =
9504 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
9505 err = init_rmode_identity_map(kvm);
9511 nested_vmx_setup_ctls_msrs(vmx);
9513 vmx->nested.posted_intr_nv = -1;
9514 vmx->nested.current_vmptr = -1ull;
9515 vmx->nested.current_vmcs12 = NULL;
9517 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9520 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9521 * or POSTED_INTR_WAKEUP_VECTOR.
9523 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9524 vmx->pi_desc.sn = 1;
9529 free_loaded_vmcs(vmx->loaded_vmcs);
9531 kfree(vmx->guest_msrs);
9533 vmx_destroy_pml_buffer(vmx);
9535 kvm_vcpu_uninit(&vmx->vcpu);
9537 free_vpid(vmx->vpid);
9538 kmem_cache_free(kvm_vcpu_cache, vmx);
9539 return ERR_PTR(err);
9542 #define L1TF_MSG_SMT "L1TF CPU bug present and SMT on, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
9543 #define L1TF_MSG_L1D "L1TF CPU bug present and virtualization mitigation disabled, data leak possible. See CVE-2018-3646 and https://www.kernel.org/doc/html/latest/admin-guide/l1tf.html for details.\n"
9545 static int vmx_vm_init(struct kvm *kvm)
9547 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
9548 switch (l1tf_mitigation) {
9549 case L1TF_MITIGATION_OFF:
9550 case L1TF_MITIGATION_FLUSH_NOWARN:
9551 /* 'I explicitly don't care' is set */
9553 case L1TF_MITIGATION_FLUSH:
9554 case L1TF_MITIGATION_FLUSH_NOSMT:
9555 case L1TF_MITIGATION_FULL:
9557 * Warn upon starting the first VM in a potentially
9558 * insecure environment.
9560 if (cpu_smt_control == CPU_SMT_ENABLED)
9561 pr_warn_once(L1TF_MSG_SMT);
9562 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
9563 pr_warn_once(L1TF_MSG_L1D);
9565 case L1TF_MITIGATION_FULL_FORCE:
9566 /* Flush is enforced */
9573 static void __init vmx_check_processor_compat(void *rtn)
9575 struct vmcs_config vmcs_conf;
9578 if (setup_vmcs_config(&vmcs_conf) < 0)
9580 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9581 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9582 smp_processor_id());
9587 static int get_ept_level(void)
9589 return VMX_EPT_DEFAULT_GAW + 1;
9592 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9597 /* For VT-d and EPT combination
9598 * 1. MMIO: always map as UC
9600 * a. VT-d without snooping control feature: can't guarantee the
9601 * result, try to trust guest.
9602 * b. VT-d with snooping control feature: snooping control feature of
9603 * VT-d engine can guarantee the cache correctness. Just set it
9604 * to WB to keep consistent with host. So the same as item 3.
9605 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9606 * consistent with host MTRR
9609 cache = MTRR_TYPE_UNCACHABLE;
9613 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9614 ipat = VMX_EPT_IPAT_BIT;
9615 cache = MTRR_TYPE_WRBACK;
9619 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9620 ipat = VMX_EPT_IPAT_BIT;
9621 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9622 cache = MTRR_TYPE_WRBACK;
9624 cache = MTRR_TYPE_UNCACHABLE;
9628 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9631 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9634 static int vmx_get_lpage_level(void)
9636 if (enable_ept && !cpu_has_vmx_ept_1g_page())
9637 return PT_DIRECTORY_LEVEL;
9639 /* For shadow and EPT supported 1GB page */
9640 return PT_PDPE_LEVEL;
9643 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9646 * These bits in the secondary execution controls field
9647 * are dynamic, the others are mostly based on the hypervisor
9648 * architecture and the guest's CPUID. Do not touch the
9652 SECONDARY_EXEC_SHADOW_VMCS |
9653 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9654 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9656 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9658 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9659 (new_ctl & ~mask) | (cur_ctl & mask));
9662 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9664 struct kvm_cpuid_entry2 *best;
9665 struct vcpu_vmx *vmx = to_vmx(vcpu);
9666 u32 secondary_exec_ctl = vmx_secondary_exec_control(vmx);
9668 if (vmx_rdtscp_supported()) {
9669 bool rdtscp_enabled = guest_cpuid_has_rdtscp(vcpu);
9670 if (!rdtscp_enabled)
9671 secondary_exec_ctl &= ~SECONDARY_EXEC_RDTSCP;
9675 vmx->nested.nested_vmx_secondary_ctls_high |=
9676 SECONDARY_EXEC_RDTSCP;
9678 vmx->nested.nested_vmx_secondary_ctls_high &=
9679 ~SECONDARY_EXEC_RDTSCP;
9683 /* Exposing INVPCID only when PCID is exposed */
9684 best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9685 if (vmx_invpcid_supported() &&
9686 (!best || !(best->ebx & bit(X86_FEATURE_INVPCID)) ||
9687 !guest_cpuid_has_pcid(vcpu))) {
9688 secondary_exec_ctl &= ~SECONDARY_EXEC_ENABLE_INVPCID;
9691 best->ebx &= ~bit(X86_FEATURE_INVPCID);
9694 if (cpu_has_secondary_exec_ctrls())
9695 vmcs_set_secondary_exec_control(secondary_exec_ctl);
9697 if (nested_vmx_allowed(vcpu))
9698 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9699 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9701 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9702 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9705 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9707 if (func == 1 && nested)
9708 entry->ecx |= bit(X86_FEATURE_VMX);
9711 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9712 struct x86_exception *fault)
9714 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9717 if (fault->error_code & PFERR_RSVD_MASK)
9718 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9720 exit_reason = EXIT_REASON_EPT_VIOLATION;
9721 nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
9722 vmcs12->guest_physical_address = fault->address;
9725 /* Callbacks for nested_ept_init_mmu_context: */
9727 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9729 /* return the page table to be shadowed - in our case, EPT12 */
9730 return get_vmcs12(vcpu)->ept_pointer;
9733 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
9735 WARN_ON(mmu_is_nested(vcpu));
9736 kvm_init_shadow_ept_mmu(vcpu,
9737 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
9738 VMX_EPT_EXECUTE_ONLY_BIT);
9739 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
9740 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
9741 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
9743 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
9746 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
9748 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
9751 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
9754 bool inequality, bit;
9756 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
9758 (error_code & vmcs12->page_fault_error_code_mask) !=
9759 vmcs12->page_fault_error_code_match;
9760 return inequality ^ bit;
9763 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
9764 struct x86_exception *fault)
9766 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9768 WARN_ON(!is_guest_mode(vcpu));
9770 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code))
9771 nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
9772 vmcs_read32(VM_EXIT_INTR_INFO),
9773 vmcs_readl(EXIT_QUALIFICATION));
9775 kvm_inject_page_fault(vcpu, fault);
9778 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
9779 struct vmcs12 *vmcs12)
9781 struct vcpu_vmx *vmx = to_vmx(vcpu);
9782 int maxphyaddr = cpuid_maxphyaddr(vcpu);
9784 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9785 if (!PAGE_ALIGNED(vmcs12->apic_access_addr) ||
9786 vmcs12->apic_access_addr >> maxphyaddr)
9790 * Translate L1 physical address to host physical
9791 * address for vmcs02. Keep the page pinned, so this
9792 * physical address remains valid. We keep a reference
9793 * to it so we can release it later.
9795 if (vmx->nested.apic_access_page) /* shouldn't happen */
9796 nested_release_page(vmx->nested.apic_access_page);
9797 vmx->nested.apic_access_page =
9798 nested_get_page(vcpu, vmcs12->apic_access_addr);
9801 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
9802 if (!PAGE_ALIGNED(vmcs12->virtual_apic_page_addr) ||
9803 vmcs12->virtual_apic_page_addr >> maxphyaddr)
9806 if (vmx->nested.virtual_apic_page) /* shouldn't happen */
9807 nested_release_page(vmx->nested.virtual_apic_page);
9808 vmx->nested.virtual_apic_page =
9809 nested_get_page(vcpu, vmcs12->virtual_apic_page_addr);
9812 * Failing the vm entry is _not_ what the processor does
9813 * but it's basically the only possibility we have.
9814 * We could still enter the guest if CR8 load exits are
9815 * enabled, CR8 store exits are enabled, and virtualize APIC
9816 * access is disabled; in this case the processor would never
9817 * use the TPR shadow and we could simply clear the bit from
9818 * the execution control. But such a configuration is useless,
9819 * so let's keep the code simple.
9821 if (!vmx->nested.virtual_apic_page)
9825 if (nested_cpu_has_posted_intr(vmcs12)) {
9826 if (!IS_ALIGNED(vmcs12->posted_intr_desc_addr, 64) ||
9827 vmcs12->posted_intr_desc_addr >> maxphyaddr)
9830 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
9831 kunmap(vmx->nested.pi_desc_page);
9832 nested_release_page(vmx->nested.pi_desc_page);
9834 vmx->nested.pi_desc_page =
9835 nested_get_page(vcpu, vmcs12->posted_intr_desc_addr);
9836 if (!vmx->nested.pi_desc_page)
9839 vmx->nested.pi_desc =
9840 (struct pi_desc *)kmap(vmx->nested.pi_desc_page);
9841 if (!vmx->nested.pi_desc) {
9842 nested_release_page_clean(vmx->nested.pi_desc_page);
9845 vmx->nested.pi_desc =
9846 (struct pi_desc *)((void *)vmx->nested.pi_desc +
9847 (unsigned long)(vmcs12->posted_intr_desc_addr &
9854 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
9856 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
9857 struct vcpu_vmx *vmx = to_vmx(vcpu);
9859 if (vcpu->arch.virtual_tsc_khz == 0)
9862 /* Make sure short timeouts reliably trigger an immediate vmexit.
9863 * hrtimer_start does not guarantee this. */
9864 if (preemption_timeout <= 1) {
9865 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
9869 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
9870 preemption_timeout *= 1000000;
9871 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
9872 hrtimer_start(&vmx->nested.preemption_timer,
9873 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
9876 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
9877 struct vmcs12 *vmcs12)
9882 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9885 if (vmcs12_read_any(vcpu, MSR_BITMAP, &addr)) {
9889 maxphyaddr = cpuid_maxphyaddr(vcpu);
9891 if (!PAGE_ALIGNED(vmcs12->msr_bitmap) ||
9892 ((addr + PAGE_SIZE) >> maxphyaddr))
9899 * Merge L0's and L1's MSR bitmap, return false to indicate that
9900 * we do not use the hardware.
9902 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
9903 struct vmcs12 *vmcs12)
9907 unsigned long *msr_bitmap_l1;
9908 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
9910 * pred_cmd & spec_ctrl are trying to verify two things:
9912 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
9913 * ensures that we do not accidentally generate an L02 MSR bitmap
9914 * from the L12 MSR bitmap that is too permissive.
9915 * 2. That L1 or L2s have actually used the MSR. This avoids
9916 * unnecessarily merging of the bitmap if the MSR is unused. This
9917 * works properly because we only update the L01 MSR bitmap lazily.
9918 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
9919 * updated to reflect this when L1 (or its L2s) actually write to
9922 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
9923 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
9925 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
9926 !pred_cmd && !spec_ctrl)
9929 page = nested_get_page(vcpu, vmcs12->msr_bitmap);
9932 msr_bitmap_l1 = (unsigned long *)kmap(page);
9934 memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
9936 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
9937 if (nested_cpu_has_apic_reg_virt(vmcs12))
9938 for (msr = 0x800; msr <= 0x8ff; msr++)
9939 nested_vmx_disable_intercept_for_msr(
9940 msr_bitmap_l1, msr_bitmap_l0,
9943 nested_vmx_disable_intercept_for_msr(
9944 msr_bitmap_l1, msr_bitmap_l0,
9945 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
9946 MSR_TYPE_R | MSR_TYPE_W);
9948 if (nested_cpu_has_vid(vmcs12)) {
9949 nested_vmx_disable_intercept_for_msr(
9950 msr_bitmap_l1, msr_bitmap_l0,
9951 APIC_BASE_MSR + (APIC_EOI >> 4),
9953 nested_vmx_disable_intercept_for_msr(
9954 msr_bitmap_l1, msr_bitmap_l0,
9955 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
9961 nested_vmx_disable_intercept_for_msr(
9962 msr_bitmap_l1, msr_bitmap_l0,
9964 MSR_TYPE_R | MSR_TYPE_W);
9967 nested_vmx_disable_intercept_for_msr(
9968 msr_bitmap_l1, msr_bitmap_l0,
9973 nested_release_page_clean(page);
9978 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
9979 struct vmcs12 *vmcs12)
9981 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
9982 !nested_cpu_has_apic_reg_virt(vmcs12) &&
9983 !nested_cpu_has_vid(vmcs12) &&
9984 !nested_cpu_has_posted_intr(vmcs12))
9988 * If virtualize x2apic mode is enabled,
9989 * virtualize apic access must be disabled.
9991 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
9992 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
9996 * If virtual interrupt delivery is enabled,
9997 * we must exit on external interrupts.
9999 if (nested_cpu_has_vid(vmcs12) &&
10000 !nested_exit_on_intr(vcpu))
10004 * bits 15:8 should be zero in posted_intr_nv,
10005 * the descriptor address has been already checked
10006 * in nested_get_vmcs12_pages.
10008 if (nested_cpu_has_posted_intr(vmcs12) &&
10009 (!nested_cpu_has_vid(vmcs12) ||
10010 !nested_exit_intr_ack_set(vcpu) ||
10011 vmcs12->posted_intr_nv & 0xff00))
10014 /* tpr shadow is needed by all apicv features. */
10015 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10021 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10022 unsigned long count_field,
10023 unsigned long addr_field)
10028 if (vmcs12_read_any(vcpu, count_field, &count) ||
10029 vmcs12_read_any(vcpu, addr_field, &addr)) {
10035 maxphyaddr = cpuid_maxphyaddr(vcpu);
10036 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10037 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10038 pr_debug_ratelimited(
10039 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10040 addr_field, maxphyaddr, count, addr);
10046 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10047 struct vmcs12 *vmcs12)
10049 if (vmcs12->vm_exit_msr_load_count == 0 &&
10050 vmcs12->vm_exit_msr_store_count == 0 &&
10051 vmcs12->vm_entry_msr_load_count == 0)
10052 return 0; /* Fast path */
10053 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10054 VM_EXIT_MSR_LOAD_ADDR) ||
10055 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10056 VM_EXIT_MSR_STORE_ADDR) ||
10057 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10058 VM_ENTRY_MSR_LOAD_ADDR))
10063 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10064 struct vmx_msr_entry *e)
10066 /* x2APIC MSR accesses are not allowed */
10067 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10069 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10070 e->index == MSR_IA32_UCODE_REV)
10072 if (e->reserved != 0)
10077 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10078 struct vmx_msr_entry *e)
10080 if (e->index == MSR_FS_BASE ||
10081 e->index == MSR_GS_BASE ||
10082 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10083 nested_vmx_msr_check_common(vcpu, e))
10088 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10089 struct vmx_msr_entry *e)
10091 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10092 nested_vmx_msr_check_common(vcpu, e))
10098 * Load guest's/host's msr at nested entry/exit.
10099 * return 0 for success, entry index for failure.
10101 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10104 struct vmx_msr_entry e;
10105 struct msr_data msr;
10107 msr.host_initiated = false;
10108 for (i = 0; i < count; i++) {
10109 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10111 pr_debug_ratelimited(
10112 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10113 __func__, i, gpa + i * sizeof(e));
10116 if (nested_vmx_load_msr_check(vcpu, &e)) {
10117 pr_debug_ratelimited(
10118 "%s check failed (%u, 0x%x, 0x%x)\n",
10119 __func__, i, e.index, e.reserved);
10122 msr.index = e.index;
10123 msr.data = e.value;
10124 if (kvm_set_msr(vcpu, &msr)) {
10125 pr_debug_ratelimited(
10126 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10127 __func__, i, e.index, e.value);
10136 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10139 struct vmx_msr_entry e;
10141 for (i = 0; i < count; i++) {
10142 struct msr_data msr_info;
10143 if (kvm_vcpu_read_guest(vcpu,
10144 gpa + i * sizeof(e),
10145 &e, 2 * sizeof(u32))) {
10146 pr_debug_ratelimited(
10147 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10148 __func__, i, gpa + i * sizeof(e));
10151 if (nested_vmx_store_msr_check(vcpu, &e)) {
10152 pr_debug_ratelimited(
10153 "%s check failed (%u, 0x%x, 0x%x)\n",
10154 __func__, i, e.index, e.reserved);
10157 msr_info.host_initiated = false;
10158 msr_info.index = e.index;
10159 if (kvm_get_msr(vcpu, &msr_info)) {
10160 pr_debug_ratelimited(
10161 "%s cannot read MSR (%u, 0x%x)\n",
10162 __func__, i, e.index);
10165 if (kvm_vcpu_write_guest(vcpu,
10166 gpa + i * sizeof(e) +
10167 offsetof(struct vmx_msr_entry, value),
10168 &msr_info.data, sizeof(msr_info.data))) {
10169 pr_debug_ratelimited(
10170 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10171 __func__, i, e.index, msr_info.data);
10179 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10180 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10181 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10182 * guest in a way that will both be appropriate to L1's requests, and our
10183 * needs. In addition to modifying the active vmcs (which is vmcs02), this
10184 * function also has additional necessary side-effects, like setting various
10185 * vcpu->arch fields.
10187 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10189 struct vcpu_vmx *vmx = to_vmx(vcpu);
10192 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10193 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10194 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10195 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10196 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10197 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10198 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10199 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10200 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10201 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10202 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10203 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10204 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10205 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10206 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10207 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10208 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10209 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10210 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10211 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10212 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10213 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10214 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10215 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10216 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10217 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10218 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10219 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10220 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10221 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10222 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10223 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10224 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10225 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10226 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10227 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10229 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
10230 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10231 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10233 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10234 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10236 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10237 vmcs12->vm_entry_intr_info_field);
10238 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10239 vmcs12->vm_entry_exception_error_code);
10240 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10241 vmcs12->vm_entry_instruction_len);
10242 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10243 vmcs12->guest_interruptibility_info);
10244 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10245 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10246 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10247 vmcs12->guest_pending_dbg_exceptions);
10248 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10249 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10251 if (nested_cpu_has_xsaves(vmcs12))
10252 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10253 vmcs_write64(VMCS_LINK_POINTER, -1ull);
10255 exec_control = vmcs12->pin_based_vm_exec_control;
10257 /* Preemption timer setting is only taken from vmcs01. */
10258 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10259 exec_control |= vmcs_config.pin_based_exec_ctrl;
10260 if (vmx->hv_deadline_tsc == -1)
10261 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10263 /* Posted interrupts setting is only taken from vmcs12. */
10264 if (nested_cpu_has_posted_intr(vmcs12)) {
10266 * Note that we use L0's vector here and in
10267 * vmx_deliver_nested_posted_interrupt.
10269 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10270 vmx->nested.pi_pending = false;
10271 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
10272 vmcs_write64(POSTED_INTR_DESC_ADDR,
10273 page_to_phys(vmx->nested.pi_desc_page) +
10274 (unsigned long)(vmcs12->posted_intr_desc_addr &
10277 exec_control &= ~PIN_BASED_POSTED_INTR;
10279 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10281 vmx->nested.preemption_timer_expired = false;
10282 if (nested_cpu_has_preemption_timer(vmcs12))
10283 vmx_start_preemption_timer(vcpu);
10286 * Whether page-faults are trapped is determined by a combination of
10287 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10288 * If enable_ept, L0 doesn't care about page faults and we should
10289 * set all of these to L1's desires. However, if !enable_ept, L0 does
10290 * care about (at least some) page faults, and because it is not easy
10291 * (if at all possible?) to merge L0 and L1's desires, we simply ask
10292 * to exit on each and every L2 page fault. This is done by setting
10293 * MASK=MATCH=0 and (see below) EB.PF=1.
10294 * Note that below we don't need special code to set EB.PF beyond the
10295 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10296 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10297 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10299 * A problem with this approach (when !enable_ept) is that L1 may be
10300 * injected with more page faults than it asked for. This could have
10301 * caused problems, but in practice existing hypervisors don't care.
10302 * To fix this, we will need to emulate the PFEC checking (on the L1
10303 * page tables), using walk_addr(), when injecting PFs to L1.
10305 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10306 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10307 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10308 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10310 if (cpu_has_secondary_exec_ctrls()) {
10311 exec_control = vmx_secondary_exec_control(vmx);
10313 /* Take the following fields only from vmcs12 */
10314 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10315 SECONDARY_EXEC_RDTSCP |
10316 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10317 SECONDARY_EXEC_APIC_REGISTER_VIRT);
10318 if (nested_cpu_has(vmcs12,
10319 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
10320 exec_control |= vmcs12->secondary_vm_exec_control;
10322 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
10324 * If translation failed, no matter: This feature asks
10325 * to exit when accessing the given address, and if it
10326 * can never be accessed, this feature won't do
10329 if (!vmx->nested.apic_access_page)
10331 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10333 vmcs_write64(APIC_ACCESS_ADDR,
10334 page_to_phys(vmx->nested.apic_access_page));
10335 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
10336 cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10338 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10339 kvm_vcpu_reload_apic_access_page(vcpu);
10342 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10343 vmcs_write64(EOI_EXIT_BITMAP0,
10344 vmcs12->eoi_exit_bitmap0);
10345 vmcs_write64(EOI_EXIT_BITMAP1,
10346 vmcs12->eoi_exit_bitmap1);
10347 vmcs_write64(EOI_EXIT_BITMAP2,
10348 vmcs12->eoi_exit_bitmap2);
10349 vmcs_write64(EOI_EXIT_BITMAP3,
10350 vmcs12->eoi_exit_bitmap3);
10351 vmcs_write16(GUEST_INTR_STATUS,
10352 vmcs12->guest_intr_status);
10355 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10360 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10361 * Some constant fields are set here by vmx_set_constant_host_state().
10362 * Other fields are different per CPU, and will be set later when
10363 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10365 vmx_set_constant_host_state(vmx);
10368 * Set the MSR load/store lists to match L0's settings.
10370 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10371 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
10372 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
10373 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
10374 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
10377 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10378 * entry, but only if the current (host) sp changed from the value
10379 * we wrote last (vmx->host_rsp). This cache is no longer relevant
10380 * if we switch vmcs, and rather than hold a separate cache per vmcs,
10381 * here we just force the write to happen on entry.
10385 exec_control = vmx_exec_control(vmx); /* L0's desires */
10386 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10387 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10388 exec_control &= ~CPU_BASED_TPR_SHADOW;
10389 exec_control |= vmcs12->cpu_based_vm_exec_control;
10391 if (exec_control & CPU_BASED_TPR_SHADOW) {
10392 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
10393 page_to_phys(vmx->nested.virtual_apic_page));
10394 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10396 #ifdef CONFIG_X86_64
10397 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10398 CPU_BASED_CR8_STORE_EXITING;
10402 if (cpu_has_vmx_msr_bitmap() &&
10403 exec_control & CPU_BASED_USE_MSR_BITMAPS &&
10404 nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10405 ; /* MSR_BITMAP will be set by following vmx_set_efer. */
10407 exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
10410 * Merging of IO bitmap not currently supported.
10411 * Rather, exit every time.
10413 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10414 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10416 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10418 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10419 * bitwise-or of what L1 wants to trap for L2, and what we want to
10420 * trap. Note that CR0.TS also needs updating - we do this later.
10422 update_exception_bitmap(vcpu);
10423 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10424 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10426 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10427 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10428 * bits are further modified by vmx_set_efer() below.
10430 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10432 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10433 * emulated by vmx_set_efer(), below.
10435 vm_entry_controls_init(vmx,
10436 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10437 ~VM_ENTRY_IA32E_MODE) |
10438 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10440 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
10441 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10442 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10443 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
10444 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10447 set_cr4_guest_host_mask(vmx);
10449 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10450 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10452 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10453 vmcs_write64(TSC_OFFSET,
10454 vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10456 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10457 if (kvm_has_tsc_control)
10458 decache_tsc_multiplier(vmx);
10460 if (cpu_has_vmx_msr_bitmap())
10461 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
10465 * There is no direct mapping between vpid02 and vpid12, the
10466 * vpid02 is per-vCPU for L0 and reused while the value of
10467 * vpid12 is changed w/ one invvpid during nested vmentry.
10468 * The vpid12 is allocated by L1 for L2, so it will not
10469 * influence global bitmap(for vpid01 and vpid02 allocation)
10470 * even if spawn a lot of nested vCPUs.
10472 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10473 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10474 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10475 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10476 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10479 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10480 vmx_flush_tlb(vcpu);
10487 * Conceptually we want to copy the PML address and index from
10488 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10489 * since we always flush the log on each vmexit, this happens
10490 * to be equivalent to simply resetting the fields in vmcs02.
10492 ASSERT(vmx->pml_pg);
10493 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10494 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10497 if (nested_cpu_has_ept(vmcs12)) {
10498 kvm_mmu_unload(vcpu);
10499 nested_ept_init_mmu_context(vcpu);
10500 } else if (nested_cpu_has2(vmcs12,
10501 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10502 vmx_flush_tlb_ept_only(vcpu);
10505 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
10506 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10507 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10508 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10510 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10511 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10512 vmx_set_efer(vcpu, vcpu->arch.efer);
10515 * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
10516 * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
10517 * The CR0_READ_SHADOW is what L2 should have expected to read given
10518 * the specifications by L1; It's not enough to take
10519 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10520 * have more bits than L1 expected.
10522 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10523 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10525 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10526 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10528 /* shadow page tables on either EPT or shadow page tables */
10529 kvm_set_cr3(vcpu, vmcs12->guest_cr3);
10530 kvm_mmu_reset_context(vcpu);
10533 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10536 * L1 may access the L2's PDPTR, so save them to construct vmcs12
10539 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10540 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10541 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10542 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10545 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10546 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10550 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
10551 * for running an L2 nested guest.
10553 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
10555 struct vmcs12 *vmcs12;
10556 struct vcpu_vmx *vmx = to_vmx(vcpu);
10561 if (!nested_vmx_check_permission(vcpu) ||
10562 !nested_vmx_check_vmcs12(vcpu))
10565 skip_emulated_instruction(vcpu);
10566 vmcs12 = get_vmcs12(vcpu);
10568 if (enable_shadow_vmcs)
10569 copy_shadow_to_vmcs12(vmx);
10572 * The nested entry process starts with enforcing various prerequisites
10573 * on vmcs12 as required by the Intel SDM, and act appropriately when
10574 * they fail: As the SDM explains, some conditions should cause the
10575 * instruction to fail, while others will cause the instruction to seem
10576 * to succeed, but return an EXIT_REASON_INVALID_STATE.
10577 * To speed up the normal (success) code path, we should avoid checking
10578 * for misconfigurations which will anyway be caught by the processor
10579 * when using the merged vmcs02.
10581 if (vmcs12->launch_state == launch) {
10582 nested_vmx_failValid(vcpu,
10583 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
10584 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
10588 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10589 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
10590 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10594 if (!nested_get_vmcs12_pages(vcpu, vmcs12)) {
10595 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10599 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12)) {
10600 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10604 if (nested_vmx_check_apicv_controls(vcpu, vmcs12)) {
10605 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10609 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12)) {
10610 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10614 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10615 vmx->nested.nested_vmx_true_procbased_ctls_low,
10616 vmx->nested.nested_vmx_procbased_ctls_high) ||
10617 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10618 vmx->nested.nested_vmx_secondary_ctls_low,
10619 vmx->nested.nested_vmx_secondary_ctls_high) ||
10620 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10621 vmx->nested.nested_vmx_pinbased_ctls_low,
10622 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10623 !vmx_control_verify(vmcs12->vm_exit_controls,
10624 vmx->nested.nested_vmx_true_exit_ctls_low,
10625 vmx->nested.nested_vmx_exit_ctls_high) ||
10626 !vmx_control_verify(vmcs12->vm_entry_controls,
10627 vmx->nested.nested_vmx_true_entry_ctls_low,
10628 vmx->nested.nested_vmx_entry_ctls_high))
10630 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10634 if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
10635 ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
10636 nested_vmx_failValid(vcpu,
10637 VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
10641 if (!nested_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10642 ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
10643 nested_vmx_entry_failure(vcpu, vmcs12,
10644 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10647 if (vmcs12->vmcs_link_pointer != -1ull) {
10648 nested_vmx_entry_failure(vcpu, vmcs12,
10649 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
10654 * If the load IA32_EFER VM-entry control is 1, the following checks
10655 * are performed on the field for the IA32_EFER MSR:
10656 * - Bits reserved in the IA32_EFER MSR must be 0.
10657 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10658 * the IA-32e mode guest VM-exit control. It must also be identical
10659 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10662 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
10663 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
10664 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
10665 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
10666 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
10667 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
10668 nested_vmx_entry_failure(vcpu, vmcs12,
10669 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10675 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
10676 * IA32_EFER MSR must be 0 in the field for that register. In addition,
10677 * the values of the LMA and LME bits in the field must each be that of
10678 * the host address-space size VM-exit control.
10680 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
10681 ia32e = (vmcs12->vm_exit_controls &
10682 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
10683 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
10684 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
10685 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
10686 nested_vmx_entry_failure(vcpu, vmcs12,
10687 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10693 * We're finally done with prerequisite checking, and can start with
10694 * the nested entry.
10697 enter_guest_mode(vcpu);
10699 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
10700 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10703 vmx->loaded_vmcs = &vmx->nested.vmcs02;
10704 vmx_vcpu_put(vcpu);
10705 vmx_vcpu_load(vcpu, cpu);
10709 vmx_segment_cache_clear(vmx);
10711 prepare_vmcs02(vcpu, vmcs12);
10713 msr_entry_idx = nested_vmx_load_msr(vcpu,
10714 vmcs12->vm_entry_msr_load_addr,
10715 vmcs12->vm_entry_msr_load_count);
10716 if (msr_entry_idx) {
10717 leave_guest_mode(vcpu);
10718 vmx_load_vmcs01(vcpu);
10719 nested_vmx_entry_failure(vcpu, vmcs12,
10720 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
10724 vmcs12->launch_state = 1;
10726 /* Hide L1D cache contents from the nested guest. */
10727 vmx->vcpu.arch.l1tf_flush_l1d = true;
10729 if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
10730 return kvm_vcpu_halt(vcpu);
10732 vmx->nested.nested_run_pending = 1;
10735 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
10736 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
10737 * returned as far as L1 is concerned. It will only return (and set
10738 * the success flag) when L2 exits (see nested_vmx_vmexit()).
10744 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
10745 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
10746 * This function returns the new value we should put in vmcs12.guest_cr0.
10747 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
10748 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
10749 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
10750 * didn't trap the bit, because if L1 did, so would L0).
10751 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
10752 * been modified by L2, and L1 knows it. So just leave the old value of
10753 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
10754 * isn't relevant, because if L0 traps this bit it can set it to anything.
10755 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
10756 * changed these bits, and therefore they need to be updated, but L0
10757 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
10758 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
10760 static inline unsigned long
10761 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10764 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
10765 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
10766 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
10767 vcpu->arch.cr0_guest_owned_bits));
10770 static inline unsigned long
10771 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10774 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
10775 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
10776 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
10777 vcpu->arch.cr4_guest_owned_bits));
10780 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
10781 struct vmcs12 *vmcs12)
10786 if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
10787 nr = vcpu->arch.exception.nr;
10788 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
10790 if (kvm_exception_is_soft(nr)) {
10791 vmcs12->vm_exit_instruction_len =
10792 vcpu->arch.event_exit_inst_len;
10793 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
10795 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
10797 if (vcpu->arch.exception.has_error_code) {
10798 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
10799 vmcs12->idt_vectoring_error_code =
10800 vcpu->arch.exception.error_code;
10803 vmcs12->idt_vectoring_info_field = idt_vectoring;
10804 } else if (vcpu->arch.nmi_injected) {
10805 vmcs12->idt_vectoring_info_field =
10806 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
10807 } else if (vcpu->arch.interrupt.pending) {
10808 nr = vcpu->arch.interrupt.nr;
10809 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
10811 if (vcpu->arch.interrupt.soft) {
10812 idt_vectoring |= INTR_TYPE_SOFT_INTR;
10813 vmcs12->vm_entry_instruction_len =
10814 vcpu->arch.event_exit_inst_len;
10816 idt_vectoring |= INTR_TYPE_EXT_INTR;
10818 vmcs12->idt_vectoring_info_field = idt_vectoring;
10822 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
10824 struct vcpu_vmx *vmx = to_vmx(vcpu);
10826 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
10827 vmx->nested.preemption_timer_expired) {
10828 if (vmx->nested.nested_run_pending)
10830 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
10834 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
10835 if (vmx->nested.nested_run_pending ||
10836 vcpu->arch.interrupt.pending)
10838 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10839 NMI_VECTOR | INTR_TYPE_NMI_INTR |
10840 INTR_INFO_VALID_MASK, 0);
10842 * The NMI-triggered VM exit counts as injection:
10843 * clear this one and block further NMIs.
10845 vcpu->arch.nmi_pending = 0;
10846 vmx_set_nmi_mask(vcpu, true);
10850 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
10851 nested_exit_on_intr(vcpu)) {
10852 if (vmx->nested.nested_run_pending)
10854 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
10858 vmx_complete_nested_posted_interrupt(vcpu);
10862 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
10864 ktime_t remaining =
10865 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
10868 if (ktime_to_ns(remaining) <= 0)
10871 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
10872 do_div(value, 1000000);
10873 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10877 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
10878 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
10879 * and this function updates it to reflect the changes to the guest state while
10880 * L2 was running (and perhaps made some exits which were handled directly by L0
10881 * without going back to L1), and to reflect the exit reason.
10882 * Note that we do not have to copy here all VMCS fields, just those that
10883 * could have changed by the L2 guest or the exit - i.e., the guest-state and
10884 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
10885 * which already writes to vmcs12 directly.
10887 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10888 u32 exit_reason, u32 exit_intr_info,
10889 unsigned long exit_qualification)
10891 /* update guest state fields: */
10892 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
10893 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
10895 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
10896 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
10897 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
10899 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
10900 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
10901 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
10902 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
10903 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
10904 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
10905 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
10906 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
10907 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
10908 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
10909 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
10910 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
10911 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
10912 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
10913 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
10914 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
10915 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
10916 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
10917 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
10918 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
10919 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
10920 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
10921 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
10922 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
10923 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
10924 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
10925 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
10926 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
10927 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
10928 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
10929 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
10930 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
10931 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
10932 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
10933 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
10934 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
10936 vmcs12->guest_interruptibility_info =
10937 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
10938 vmcs12->guest_pending_dbg_exceptions =
10939 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
10940 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10941 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
10943 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
10945 if (nested_cpu_has_preemption_timer(vmcs12)) {
10946 if (vmcs12->vm_exit_controls &
10947 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
10948 vmcs12->vmx_preemption_timer_value =
10949 vmx_get_preemption_timer_value(vcpu);
10950 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
10954 * In some cases (usually, nested EPT), L2 is allowed to change its
10955 * own CR3 without exiting. If it has changed it, we must keep it.
10956 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
10957 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
10959 * Additionally, restore L2's PDPTR to vmcs12.
10962 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
10963 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
10964 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
10965 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
10966 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
10969 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
10971 if (nested_cpu_has_vid(vmcs12))
10972 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
10974 vmcs12->vm_entry_controls =
10975 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
10976 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
10978 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
10979 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
10980 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10983 /* TODO: These cannot have changed unless we have MSR bitmaps and
10984 * the relevant bit asks not to trap the change */
10985 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
10986 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
10987 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
10988 vmcs12->guest_ia32_efer = vcpu->arch.efer;
10989 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
10990 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
10991 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
10992 if (kvm_mpx_supported())
10993 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
10994 if (nested_cpu_has_xsaves(vmcs12))
10995 vmcs12->xss_exit_bitmap = vmcs_read64(XSS_EXIT_BITMAP);
10997 /* update exit information fields: */
10999 vmcs12->vm_exit_reason = exit_reason;
11000 vmcs12->exit_qualification = exit_qualification;
11002 vmcs12->vm_exit_intr_info = exit_intr_info;
11003 if ((vmcs12->vm_exit_intr_info &
11004 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
11005 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
11006 vmcs12->vm_exit_intr_error_code =
11007 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
11008 vmcs12->idt_vectoring_info_field = 0;
11009 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11010 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11012 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11013 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11014 * instead of reading the real value. */
11015 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11018 * Transfer the event that L0 or L1 may wanted to inject into
11019 * L2 to IDT_VECTORING_INFO_FIELD.
11021 vmcs12_save_pending_event(vcpu, vmcs12);
11025 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11026 * preserved above and would only end up incorrectly in L1.
11028 vcpu->arch.nmi_injected = false;
11029 kvm_clear_exception_queue(vcpu);
11030 kvm_clear_interrupt_queue(vcpu);
11034 * A part of what we need to when the nested L2 guest exits and we want to
11035 * run its L1 parent, is to reset L1's guest state to the host state specified
11037 * This function is to be called not only on normal nested exit, but also on
11038 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11039 * Failures During or After Loading Guest State").
11040 * This function should be called when the active VMCS is L1's (vmcs01).
11042 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11043 struct vmcs12 *vmcs12)
11045 struct kvm_segment seg;
11047 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11048 vcpu->arch.efer = vmcs12->host_ia32_efer;
11049 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11050 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11052 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11053 vmx_set_efer(vcpu, vcpu->arch.efer);
11055 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11056 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11057 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11059 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11060 * actually changed, because it depends on the current state of
11061 * fpu_active (which may have changed).
11062 * Note that vmx_set_cr0 refers to efer set above.
11064 vmx_set_cr0(vcpu, vmcs12->host_cr0);
11066 * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
11067 * to apply the same changes to L1's vmcs. We just set cr0 correctly,
11068 * but we also need to update cr0_guest_host_mask and exception_bitmap.
11070 update_exception_bitmap(vcpu);
11071 vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
11072 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
11075 * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
11076 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
11078 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11079 vmx_set_cr4(vcpu, vmcs12->host_cr4);
11081 nested_ept_uninit_mmu_context(vcpu);
11083 kvm_set_cr3(vcpu, vmcs12->host_cr3);
11084 kvm_mmu_reset_context(vcpu);
11087 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11091 * Trivially support vpid by letting L2s share their parent
11092 * L1's vpid. TODO: move to a more elaborate solution, giving
11093 * each L2 its own vpid and exposing the vpid feature to L1.
11095 vmx_flush_tlb(vcpu);
11099 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11100 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11101 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11102 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11103 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11104 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11105 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11107 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
11108 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11109 vmcs_write64(GUEST_BNDCFGS, 0);
11111 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11112 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11113 vcpu->arch.pat = vmcs12->host_ia32_pat;
11115 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11116 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11117 vmcs12->host_ia32_perf_global_ctrl);
11119 /* Set L1 segment info according to Intel SDM
11120 27.5.2 Loading Host Segment and Descriptor-Table Registers */
11121 seg = (struct kvm_segment) {
11123 .limit = 0xFFFFFFFF,
11124 .selector = vmcs12->host_cs_selector,
11130 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11134 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11135 seg = (struct kvm_segment) {
11137 .limit = 0xFFFFFFFF,
11144 seg.selector = vmcs12->host_ds_selector;
11145 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11146 seg.selector = vmcs12->host_es_selector;
11147 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11148 seg.selector = vmcs12->host_ss_selector;
11149 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11150 seg.selector = vmcs12->host_fs_selector;
11151 seg.base = vmcs12->host_fs_base;
11152 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11153 seg.selector = vmcs12->host_gs_selector;
11154 seg.base = vmcs12->host_gs_base;
11155 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11156 seg = (struct kvm_segment) {
11157 .base = vmcs12->host_tr_base,
11159 .selector = vmcs12->host_tr_selector,
11163 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11165 kvm_set_dr(vcpu, 7, 0x400);
11166 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11168 if (cpu_has_vmx_msr_bitmap())
11169 vmx_update_msr_bitmap(vcpu);
11171 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11172 vmcs12->vm_exit_msr_load_count))
11173 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11177 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11178 * and modify vmcs12 to make it see what it would expect to see there if
11179 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11181 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11182 u32 exit_intr_info,
11183 unsigned long exit_qualification)
11185 struct vcpu_vmx *vmx = to_vmx(vcpu);
11186 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11188 /* trying to cancel vmlaunch/vmresume is a bug */
11189 WARN_ON_ONCE(vmx->nested.nested_run_pending);
11191 leave_guest_mode(vcpu);
11192 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11193 exit_qualification);
11195 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11196 vmcs12->vm_exit_msr_store_count))
11197 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11199 vmx_load_vmcs01(vcpu);
11201 if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
11202 && nested_exit_intr_ack_set(vcpu)) {
11203 int irq = kvm_cpu_get_interrupt(vcpu);
11205 vmcs12->vm_exit_intr_info = irq |
11206 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11209 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11210 vmcs12->exit_qualification,
11211 vmcs12->idt_vectoring_info_field,
11212 vmcs12->vm_exit_intr_info,
11213 vmcs12->vm_exit_intr_error_code,
11216 vm_entry_controls_reset_shadow(vmx);
11217 vm_exit_controls_reset_shadow(vmx);
11218 vmx_segment_cache_clear(vmx);
11220 load_vmcs12_host_state(vcpu, vmcs12);
11222 /* Update any VMCS fields that might have changed while L2 ran */
11223 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
11224 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
11225 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11226 if (vmx->hv_deadline_tsc == -1)
11227 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11228 PIN_BASED_VMX_PREEMPTION_TIMER);
11230 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11231 PIN_BASED_VMX_PREEMPTION_TIMER);
11232 if (kvm_has_tsc_control)
11233 decache_tsc_multiplier(vmx);
11235 if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11236 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11237 vmx_set_virtual_x2apic_mode(vcpu,
11238 vcpu->arch.apic_base & X2APIC_ENABLE);
11239 } else if (!nested_cpu_has_ept(vmcs12) &&
11240 nested_cpu_has2(vmcs12,
11241 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11242 vmx_flush_tlb_ept_only(vcpu);
11245 /* This is needed for same reason as it was needed in prepare_vmcs02 */
11248 /* Unpin physical memory we referred to in vmcs02 */
11249 if (vmx->nested.apic_access_page) {
11250 nested_release_page(vmx->nested.apic_access_page);
11251 vmx->nested.apic_access_page = NULL;
11253 if (vmx->nested.virtual_apic_page) {
11254 nested_release_page(vmx->nested.virtual_apic_page);
11255 vmx->nested.virtual_apic_page = NULL;
11257 if (vmx->nested.pi_desc_page) {
11258 kunmap(vmx->nested.pi_desc_page);
11259 nested_release_page(vmx->nested.pi_desc_page);
11260 vmx->nested.pi_desc_page = NULL;
11261 vmx->nested.pi_desc = NULL;
11265 * We are now running in L2, mmu_notifier will force to reload the
11266 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11268 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11271 * Exiting from L2 to L1, we're now back to L1 which thinks it just
11272 * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
11273 * success or failure flag accordingly.
11275 if (unlikely(vmx->fail)) {
11277 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
11279 nested_vmx_succeed(vcpu);
11280 if (enable_shadow_vmcs)
11281 vmx->nested.sync_shadow_vmcs = true;
11283 /* in case we halted in L2 */
11284 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11288 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11290 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11292 if (is_guest_mode(vcpu)) {
11293 to_vmx(vcpu)->nested.nested_run_pending = 0;
11294 nested_vmx_vmexit(vcpu, -1, 0, 0);
11296 free_nested(to_vmx(vcpu));
11300 * L1's failure to enter L2 is a subset of a normal exit, as explained in
11301 * 23.7 "VM-entry failures during or after loading guest state" (this also
11302 * lists the acceptable exit-reason and exit-qualification parameters).
11303 * It should only be called before L2 actually succeeded to run, and when
11304 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11306 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11307 struct vmcs12 *vmcs12,
11308 u32 reason, unsigned long qualification)
11310 load_vmcs12_host_state(vcpu, vmcs12);
11311 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11312 vmcs12->exit_qualification = qualification;
11313 nested_vmx_succeed(vcpu);
11314 if (enable_shadow_vmcs)
11315 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11318 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11319 struct x86_instruction_info *info,
11320 enum x86_intercept_stage stage)
11322 return X86EMUL_CONTINUE;
11325 #ifdef CONFIG_X86_64
11326 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11327 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11328 u64 divisor, u64 *result)
11330 u64 low = a << shift, high = a >> (64 - shift);
11332 /* To avoid the overflow on divq */
11333 if (high >= divisor)
11336 /* Low hold the result, high hold rem which is discarded */
11337 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11338 "rm" (divisor), "0" (low), "1" (high));
11344 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11346 struct vcpu_vmx *vmx = to_vmx(vcpu);
11347 u64 tscl = rdtsc();
11348 u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11349 u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11351 /* Convert to host delta tsc if tsc scaling is enabled */
11352 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11353 u64_shl_div_u64(delta_tsc,
11354 kvm_tsc_scaling_ratio_frac_bits,
11355 vcpu->arch.tsc_scaling_ratio,
11360 * If the delta tsc can't fit in the 32 bit after the multi shift,
11361 * we can't use the preemption timer.
11362 * It's possible that it fits on later vmentries, but checking
11363 * on every vmentry is costly so we just use an hrtimer.
11365 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11368 vmx->hv_deadline_tsc = tscl + delta_tsc;
11369 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11370 PIN_BASED_VMX_PREEMPTION_TIMER);
11374 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11376 struct vcpu_vmx *vmx = to_vmx(vcpu);
11377 vmx->hv_deadline_tsc = -1;
11378 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11379 PIN_BASED_VMX_PREEMPTION_TIMER);
11383 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11386 shrink_ple_window(vcpu);
11389 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11390 struct kvm_memory_slot *slot)
11392 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11393 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11396 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11397 struct kvm_memory_slot *slot)
11399 kvm_mmu_slot_set_dirty(kvm, slot);
11402 static void vmx_flush_log_dirty(struct kvm *kvm)
11404 kvm_flush_pml_buffers(kvm);
11407 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11408 struct kvm_memory_slot *memslot,
11409 gfn_t offset, unsigned long mask)
11411 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11414 static void __pi_post_block(struct kvm_vcpu *vcpu)
11416 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11417 struct pi_desc old, new;
11421 old.control = new.control = pi_desc->control;
11422 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11423 "Wakeup handler not enabled while the VCPU is blocked\n");
11425 dest = cpu_physical_id(vcpu->cpu);
11427 if (x2apic_enabled())
11430 new.ndst = (dest << 8) & 0xFF00;
11432 /* set 'NV' to 'notification vector' */
11433 new.nv = POSTED_INTR_VECTOR;
11434 } while (cmpxchg64(&pi_desc->control, old.control,
11435 new.control) != old.control);
11437 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11438 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11439 list_del(&vcpu->blocked_vcpu_list);
11440 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11441 vcpu->pre_pcpu = -1;
11446 * This routine does the following things for vCPU which is going
11447 * to be blocked if VT-d PI is enabled.
11448 * - Store the vCPU to the wakeup list, so when interrupts happen
11449 * we can find the right vCPU to wake up.
11450 * - Change the Posted-interrupt descriptor as below:
11451 * 'NDST' <-- vcpu->pre_pcpu
11452 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11453 * - If 'ON' is set during this process, which means at least one
11454 * interrupt is posted for this vCPU, we cannot block it, in
11455 * this case, return 1, otherwise, return 0.
11458 static int pi_pre_block(struct kvm_vcpu *vcpu)
11461 struct pi_desc old, new;
11462 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11464 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11465 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11466 !kvm_vcpu_apicv_active(vcpu))
11469 WARN_ON(irqs_disabled());
11470 local_irq_disable();
11471 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11472 vcpu->pre_pcpu = vcpu->cpu;
11473 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11474 list_add_tail(&vcpu->blocked_vcpu_list,
11475 &per_cpu(blocked_vcpu_on_cpu,
11477 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11481 old.control = new.control = pi_desc->control;
11483 WARN((pi_desc->sn == 1),
11484 "Warning: SN field of posted-interrupts "
11485 "is set before blocking\n");
11488 * Since vCPU can be preempted during this process,
11489 * vcpu->cpu could be different with pre_pcpu, we
11490 * need to set pre_pcpu as the destination of wakeup
11491 * notification event, then we can find the right vCPU
11492 * to wakeup in wakeup handler if interrupts happen
11493 * when the vCPU is in blocked state.
11495 dest = cpu_physical_id(vcpu->pre_pcpu);
11497 if (x2apic_enabled())
11500 new.ndst = (dest << 8) & 0xFF00;
11502 /* set 'NV' to 'wakeup vector' */
11503 new.nv = POSTED_INTR_WAKEUP_VECTOR;
11504 } while (cmpxchg64(&pi_desc->control, old.control,
11505 new.control) != old.control);
11507 /* We should not block the vCPU if an interrupt is posted for it. */
11508 if (pi_test_on(pi_desc) == 1)
11509 __pi_post_block(vcpu);
11511 local_irq_enable();
11512 return (vcpu->pre_pcpu == -1);
11515 static int vmx_pre_block(struct kvm_vcpu *vcpu)
11517 if (pi_pre_block(vcpu))
11520 if (kvm_lapic_hv_timer_in_use(vcpu))
11521 kvm_lapic_switch_to_sw_timer(vcpu);
11526 static void pi_post_block(struct kvm_vcpu *vcpu)
11528 if (vcpu->pre_pcpu == -1)
11531 WARN_ON(irqs_disabled());
11532 local_irq_disable();
11533 __pi_post_block(vcpu);
11534 local_irq_enable();
11537 static void vmx_post_block(struct kvm_vcpu *vcpu)
11539 if (kvm_x86_ops->set_hv_timer)
11540 kvm_lapic_switch_to_hv_timer(vcpu);
11542 pi_post_block(vcpu);
11546 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
11549 * @host_irq: host irq of the interrupt
11550 * @guest_irq: gsi of the interrupt
11551 * @set: set or unset PI
11552 * returns 0 on success, < 0 on failure
11554 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
11555 uint32_t guest_irq, bool set)
11557 struct kvm_kernel_irq_routing_entry *e;
11558 struct kvm_irq_routing_table *irq_rt;
11559 struct kvm_lapic_irq irq;
11560 struct kvm_vcpu *vcpu;
11561 struct vcpu_data vcpu_info;
11564 if (!kvm_arch_has_assigned_device(kvm) ||
11565 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11566 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
11569 idx = srcu_read_lock(&kvm->irq_srcu);
11570 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
11571 if (guest_irq >= irq_rt->nr_rt_entries ||
11572 hlist_empty(&irq_rt->map[guest_irq])) {
11573 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
11574 guest_irq, irq_rt->nr_rt_entries);
11578 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
11579 if (e->type != KVM_IRQ_ROUTING_MSI)
11582 * VT-d PI cannot support posting multicast/broadcast
11583 * interrupts to a vCPU, we still use interrupt remapping
11584 * for these kind of interrupts.
11586 * For lowest-priority interrupts, we only support
11587 * those with single CPU as the destination, e.g. user
11588 * configures the interrupts via /proc/irq or uses
11589 * irqbalance to make the interrupts single-CPU.
11591 * We will support full lowest-priority interrupt later.
11594 kvm_set_msi_irq(kvm, e, &irq);
11595 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
11597 * Make sure the IRTE is in remapped mode if
11598 * we don't handle it in posted mode.
11600 ret = irq_set_vcpu_affinity(host_irq, NULL);
11603 "failed to back to remapped mode, irq: %u\n",
11611 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
11612 vcpu_info.vector = irq.vector;
11614 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
11615 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
11618 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
11620 ret = irq_set_vcpu_affinity(host_irq, NULL);
11623 printk(KERN_INFO "%s: failed to update PI IRTE\n",
11631 srcu_read_unlock(&kvm->irq_srcu, idx);
11635 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
11637 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
11638 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11639 FEATURE_CONTROL_LMCE;
11641 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11642 ~FEATURE_CONTROL_LMCE;
11645 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
11646 .cpu_has_kvm_support = cpu_has_kvm_support,
11647 .disabled_by_bios = vmx_disabled_by_bios,
11648 .hardware_setup = hardware_setup,
11649 .hardware_unsetup = hardware_unsetup,
11650 .check_processor_compatibility = vmx_check_processor_compat,
11651 .hardware_enable = hardware_enable,
11652 .hardware_disable = hardware_disable,
11653 .cpu_has_accelerated_tpr = report_flexpriority,
11654 .has_emulated_msr = vmx_has_emulated_msr,
11656 .vm_init = vmx_vm_init,
11658 .vcpu_create = vmx_create_vcpu,
11659 .vcpu_free = vmx_free_vcpu,
11660 .vcpu_reset = vmx_vcpu_reset,
11662 .prepare_guest_switch = vmx_save_host_state,
11663 .vcpu_load = vmx_vcpu_load,
11664 .vcpu_put = vmx_vcpu_put,
11666 .update_bp_intercept = update_exception_bitmap,
11667 .get_msr_feature = vmx_get_msr_feature,
11668 .get_msr = vmx_get_msr,
11669 .set_msr = vmx_set_msr,
11670 .get_segment_base = vmx_get_segment_base,
11671 .get_segment = vmx_get_segment,
11672 .set_segment = vmx_set_segment,
11673 .get_cpl = vmx_get_cpl,
11674 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
11675 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
11676 .decache_cr3 = vmx_decache_cr3,
11677 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
11678 .set_cr0 = vmx_set_cr0,
11679 .set_cr3 = vmx_set_cr3,
11680 .set_cr4 = vmx_set_cr4,
11681 .set_efer = vmx_set_efer,
11682 .get_idt = vmx_get_idt,
11683 .set_idt = vmx_set_idt,
11684 .get_gdt = vmx_get_gdt,
11685 .set_gdt = vmx_set_gdt,
11686 .get_dr6 = vmx_get_dr6,
11687 .set_dr6 = vmx_set_dr6,
11688 .set_dr7 = vmx_set_dr7,
11689 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
11690 .cache_reg = vmx_cache_reg,
11691 .get_rflags = vmx_get_rflags,
11692 .set_rflags = vmx_set_rflags,
11694 .get_pkru = vmx_get_pkru,
11696 .fpu_activate = vmx_fpu_activate,
11697 .fpu_deactivate = vmx_fpu_deactivate,
11699 .tlb_flush = vmx_flush_tlb,
11701 .run = vmx_vcpu_run,
11702 .handle_exit = vmx_handle_exit,
11703 .skip_emulated_instruction = skip_emulated_instruction,
11704 .set_interrupt_shadow = vmx_set_interrupt_shadow,
11705 .get_interrupt_shadow = vmx_get_interrupt_shadow,
11706 .patch_hypercall = vmx_patch_hypercall,
11707 .set_irq = vmx_inject_irq,
11708 .set_nmi = vmx_inject_nmi,
11709 .queue_exception = vmx_queue_exception,
11710 .cancel_injection = vmx_cancel_injection,
11711 .interrupt_allowed = vmx_interrupt_allowed,
11712 .nmi_allowed = vmx_nmi_allowed,
11713 .get_nmi_mask = vmx_get_nmi_mask,
11714 .set_nmi_mask = vmx_set_nmi_mask,
11715 .enable_nmi_window = enable_nmi_window,
11716 .enable_irq_window = enable_irq_window,
11717 .update_cr8_intercept = update_cr8_intercept,
11718 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
11719 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
11720 .get_enable_apicv = vmx_get_enable_apicv,
11721 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
11722 .load_eoi_exitmap = vmx_load_eoi_exitmap,
11723 .hwapic_irr_update = vmx_hwapic_irr_update,
11724 .hwapic_isr_update = vmx_hwapic_isr_update,
11725 .sync_pir_to_irr = vmx_sync_pir_to_irr,
11726 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
11728 .set_tss_addr = vmx_set_tss_addr,
11729 .get_tdp_level = get_ept_level,
11730 .get_mt_mask = vmx_get_mt_mask,
11732 .get_exit_info = vmx_get_exit_info,
11734 .get_lpage_level = vmx_get_lpage_level,
11736 .cpuid_update = vmx_cpuid_update,
11738 .rdtscp_supported = vmx_rdtscp_supported,
11739 .invpcid_supported = vmx_invpcid_supported,
11741 .set_supported_cpuid = vmx_set_supported_cpuid,
11743 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
11745 .write_tsc_offset = vmx_write_tsc_offset,
11747 .set_tdp_cr3 = vmx_set_cr3,
11749 .check_intercept = vmx_check_intercept,
11750 .handle_external_intr = vmx_handle_external_intr,
11751 .mpx_supported = vmx_mpx_supported,
11752 .xsaves_supported = vmx_xsaves_supported,
11754 .check_nested_events = vmx_check_nested_events,
11756 .sched_in = vmx_sched_in,
11758 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
11759 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
11760 .flush_log_dirty = vmx_flush_log_dirty,
11761 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
11763 .pre_block = vmx_pre_block,
11764 .post_block = vmx_post_block,
11766 .pmu_ops = &intel_pmu_ops,
11768 .update_pi_irte = vmx_update_pi_irte,
11770 #ifdef CONFIG_X86_64
11771 .set_hv_timer = vmx_set_hv_timer,
11772 .cancel_hv_timer = vmx_cancel_hv_timer,
11775 .setup_mce = vmx_setup_mce,
11778 static void vmx_cleanup_l1d_flush(void)
11780 if (vmx_l1d_flush_pages) {
11781 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
11782 vmx_l1d_flush_pages = NULL;
11784 /* Restore state so sysfs ignores VMX */
11785 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
11789 static void vmx_exit(void)
11791 #ifdef CONFIG_KEXEC_CORE
11792 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
11798 vmx_cleanup_l1d_flush();
11800 module_exit(vmx_exit)
11802 static int __init vmx_init(void)
11806 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
11807 __alignof__(struct vcpu_vmx), THIS_MODULE);
11812 * Must be called after kvm_init() so enable_ept is properly set
11813 * up. Hand the parameter mitigation value in which was stored in
11814 * the pre module init parser. If no parameter was given, it will
11815 * contain 'auto' which will be turned into the default 'cond'
11818 if (boot_cpu_has(X86_BUG_L1TF)) {
11819 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
11826 #ifdef CONFIG_KEXEC_CORE
11827 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
11828 crash_vmclear_local_loaded_vmcss);
11833 module_init(vmx_init)