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/sched/smt.h>
31 #include <linux/moduleparam.h>
32 #include <linux/mod_devicetable.h>
33 #include <linux/trace_events.h>
34 #include <linux/slab.h>
35 #include <linux/tboot.h>
36 #include <linux/hrtimer.h>
37 #include <linux/frame.h>
38 #include <linux/nospec.h>
39 #include "kvm_cache_regs.h"
46 #include <asm/virtext.h>
48 #include <asm/fpu/internal.h>
49 #include <asm/perf_event.h>
50 #include <asm/debugreg.h>
51 #include <asm/kexec.h>
53 #include <asm/irq_remapping.h>
54 #include <asm/mmu_context.h>
55 #include <asm/microcode.h>
56 #include <asm/spec-ctrl.h>
61 #define __ex(x) __kvm_handle_fault_on_reboot(x)
62 #define __ex_clear(x, reg) \
63 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
65 MODULE_AUTHOR("Qumranet");
66 MODULE_LICENSE("GPL");
68 static const struct x86_cpu_id vmx_cpu_id[] = {
69 X86_FEATURE_MATCH(X86_FEATURE_VMX),
72 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
74 static bool __read_mostly enable_vpid = 1;
75 module_param_named(vpid, enable_vpid, bool, 0444);
77 static bool __read_mostly flexpriority_enabled = 1;
78 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
80 static bool __read_mostly enable_ept = 1;
81 module_param_named(ept, enable_ept, bool, S_IRUGO);
83 static bool __read_mostly enable_unrestricted_guest = 1;
84 module_param_named(unrestricted_guest,
85 enable_unrestricted_guest, bool, S_IRUGO);
87 static bool __read_mostly enable_ept_ad_bits = 1;
88 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
90 static bool __read_mostly emulate_invalid_guest_state = true;
91 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
93 static bool __read_mostly fasteoi = 1;
94 module_param(fasteoi, bool, S_IRUGO);
96 static bool __read_mostly enable_apicv = 1;
97 module_param(enable_apicv, bool, S_IRUGO);
99 static bool __read_mostly enable_shadow_vmcs = 1;
100 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
102 * If nested=1, nested virtualization is supported, i.e., guests may use
103 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
104 * use VMX instructions.
106 static bool __read_mostly nested = 0;
107 module_param(nested, bool, S_IRUGO);
109 static u64 __read_mostly host_xss;
111 static bool __read_mostly enable_pml = 1;
112 module_param_named(pml, enable_pml, bool, S_IRUGO);
116 #define MSR_TYPE_RW 3
118 #define MSR_BITMAP_MODE_X2APIC 1
119 #define MSR_BITMAP_MODE_X2APIC_APICV 2
120 #define MSR_BITMAP_MODE_LM 4
122 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
124 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
125 static int __read_mostly cpu_preemption_timer_multi;
126 static bool __read_mostly enable_preemption_timer = 1;
128 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
131 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
132 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
133 #define KVM_VM_CR0_ALWAYS_ON \
134 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
135 #define KVM_CR4_GUEST_OWNED_BITS \
136 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
137 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
139 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
140 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
142 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
144 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
147 * Hyper-V requires all of these, so mark them as supported even though
148 * they are just treated the same as all-context.
150 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
151 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
152 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
153 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
154 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
157 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
158 * ple_gap: upper bound on the amount of time between two successive
159 * executions of PAUSE in a loop. Also indicate if ple enabled.
160 * According to test, this time is usually smaller than 128 cycles.
161 * ple_window: upper bound on the amount of time a guest is allowed to execute
162 * in a PAUSE loop. Tests indicate that most spinlocks are held for
163 * less than 2^12 cycles
164 * Time is measured based on a counter that runs at the same rate as the TSC,
165 * refer SDM volume 3b section 21.6.13 & 22.1.3.
167 #define KVM_VMX_DEFAULT_PLE_GAP 128
168 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
169 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
170 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
171 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
172 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
174 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
175 module_param(ple_gap, int, S_IRUGO);
177 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
178 module_param(ple_window, int, S_IRUGO);
180 /* Default doubles per-vcpu window every exit. */
181 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
182 module_param(ple_window_grow, int, S_IRUGO);
184 /* Default resets per-vcpu window every exit to ple_window. */
185 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
186 module_param(ple_window_shrink, int, S_IRUGO);
188 /* Default is to compute the maximum so we can never overflow. */
189 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
190 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
191 module_param(ple_window_max, int, S_IRUGO);
193 extern const ulong vmx_return;
195 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
196 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
197 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
199 /* Storage for pre module init parameter parsing */
200 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
202 static const struct {
205 } vmentry_l1d_param[] = {
206 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
207 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
208 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
209 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
210 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
211 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
214 #define L1D_CACHE_ORDER 4
215 static void *vmx_l1d_flush_pages;
217 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
223 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
227 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
230 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
231 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
232 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
237 /* If set to auto use the default l1tf mitigation method */
238 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
239 switch (l1tf_mitigation) {
240 case L1TF_MITIGATION_OFF:
241 l1tf = VMENTER_L1D_FLUSH_NEVER;
243 case L1TF_MITIGATION_FLUSH_NOWARN:
244 case L1TF_MITIGATION_FLUSH:
245 case L1TF_MITIGATION_FLUSH_NOSMT:
246 l1tf = VMENTER_L1D_FLUSH_COND;
248 case L1TF_MITIGATION_FULL:
249 case L1TF_MITIGATION_FULL_FORCE:
250 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
253 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
254 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
257 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
258 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
259 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
262 vmx_l1d_flush_pages = page_address(page);
265 * Initialize each page with a different pattern in
266 * order to protect against KSM in the nested
267 * virtualization case.
269 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
270 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
275 l1tf_vmx_mitigation = l1tf;
277 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
278 static_branch_enable(&vmx_l1d_should_flush);
280 static_branch_disable(&vmx_l1d_should_flush);
282 if (l1tf == VMENTER_L1D_FLUSH_COND)
283 static_branch_enable(&vmx_l1d_flush_cond);
285 static_branch_disable(&vmx_l1d_flush_cond);
289 static int vmentry_l1d_flush_parse(const char *s)
294 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
295 if (vmentry_l1d_param[i].for_parse &&
296 sysfs_streq(s, vmentry_l1d_param[i].option))
303 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
307 l1tf = vmentry_l1d_flush_parse(s);
311 if (!boot_cpu_has(X86_BUG_L1TF))
315 * Has vmx_init() run already? If not then this is the pre init
316 * parameter parsing. In that case just store the value and let
317 * vmx_init() do the proper setup after enable_ept has been
320 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
321 vmentry_l1d_flush_param = l1tf;
325 mutex_lock(&vmx_l1d_flush_mutex);
326 ret = vmx_setup_l1d_flush(l1tf);
327 mutex_unlock(&vmx_l1d_flush_mutex);
331 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
333 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
334 return sprintf(s, "???\n");
336 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
339 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
340 .set = vmentry_l1d_flush_set,
341 .get = vmentry_l1d_flush_get,
343 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
345 #define NR_AUTOLOAD_MSRS 8
354 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
355 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
356 * loaded on this CPU (so we can clear them if the CPU goes down).
360 struct vmcs *shadow_vmcs;
363 bool nmi_known_unmasked;
364 unsigned long vmcs_host_cr3; /* May not match real cr3 */
365 unsigned long vmcs_host_cr4; /* May not match real cr4 */
366 /* Support for vnmi-less CPUs */
367 int soft_vnmi_blocked;
369 s64 vnmi_blocked_time;
370 unsigned long *msr_bitmap;
371 struct list_head loaded_vmcss_on_cpu_link;
374 struct shared_msr_entry {
381 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
382 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
383 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
384 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
385 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
386 * More than one of these structures may exist, if L1 runs multiple L2 guests.
387 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
388 * underlying hardware which will be used to run L2.
389 * This structure is packed to ensure that its layout is identical across
390 * machines (necessary for live migration).
391 * If there are changes in this struct, VMCS12_REVISION must be changed.
393 typedef u64 natural_width;
394 struct __packed vmcs12 {
395 /* According to the Intel spec, a VMCS region must start with the
396 * following two fields. Then follow implementation-specific data.
401 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
402 u32 padding[7]; /* room for future expansion */
407 u64 vm_exit_msr_store_addr;
408 u64 vm_exit_msr_load_addr;
409 u64 vm_entry_msr_load_addr;
411 u64 virtual_apic_page_addr;
412 u64 apic_access_addr;
413 u64 posted_intr_desc_addr;
414 u64 vm_function_control;
416 u64 eoi_exit_bitmap0;
417 u64 eoi_exit_bitmap1;
418 u64 eoi_exit_bitmap2;
419 u64 eoi_exit_bitmap3;
420 u64 eptp_list_address;
422 u64 guest_physical_address;
423 u64 vmcs_link_pointer;
425 u64 guest_ia32_debugctl;
428 u64 guest_ia32_perf_global_ctrl;
436 u64 host_ia32_perf_global_ctrl;
437 u64 padding64[8]; /* room for future expansion */
439 * To allow migration of L1 (complete with its L2 guests) between
440 * machines of different natural widths (32 or 64 bit), we cannot have
441 * unsigned long fields with no explict size. We use u64 (aliased
442 * natural_width) instead. Luckily, x86 is little-endian.
444 natural_width cr0_guest_host_mask;
445 natural_width cr4_guest_host_mask;
446 natural_width cr0_read_shadow;
447 natural_width cr4_read_shadow;
448 natural_width cr3_target_value0;
449 natural_width cr3_target_value1;
450 natural_width cr3_target_value2;
451 natural_width cr3_target_value3;
452 natural_width exit_qualification;
453 natural_width guest_linear_address;
454 natural_width guest_cr0;
455 natural_width guest_cr3;
456 natural_width guest_cr4;
457 natural_width guest_es_base;
458 natural_width guest_cs_base;
459 natural_width guest_ss_base;
460 natural_width guest_ds_base;
461 natural_width guest_fs_base;
462 natural_width guest_gs_base;
463 natural_width guest_ldtr_base;
464 natural_width guest_tr_base;
465 natural_width guest_gdtr_base;
466 natural_width guest_idtr_base;
467 natural_width guest_dr7;
468 natural_width guest_rsp;
469 natural_width guest_rip;
470 natural_width guest_rflags;
471 natural_width guest_pending_dbg_exceptions;
472 natural_width guest_sysenter_esp;
473 natural_width guest_sysenter_eip;
474 natural_width host_cr0;
475 natural_width host_cr3;
476 natural_width host_cr4;
477 natural_width host_fs_base;
478 natural_width host_gs_base;
479 natural_width host_tr_base;
480 natural_width host_gdtr_base;
481 natural_width host_idtr_base;
482 natural_width host_ia32_sysenter_esp;
483 natural_width host_ia32_sysenter_eip;
484 natural_width host_rsp;
485 natural_width host_rip;
486 natural_width paddingl[8]; /* room for future expansion */
487 u32 pin_based_vm_exec_control;
488 u32 cpu_based_vm_exec_control;
489 u32 exception_bitmap;
490 u32 page_fault_error_code_mask;
491 u32 page_fault_error_code_match;
492 u32 cr3_target_count;
493 u32 vm_exit_controls;
494 u32 vm_exit_msr_store_count;
495 u32 vm_exit_msr_load_count;
496 u32 vm_entry_controls;
497 u32 vm_entry_msr_load_count;
498 u32 vm_entry_intr_info_field;
499 u32 vm_entry_exception_error_code;
500 u32 vm_entry_instruction_len;
502 u32 secondary_vm_exec_control;
503 u32 vm_instruction_error;
505 u32 vm_exit_intr_info;
506 u32 vm_exit_intr_error_code;
507 u32 idt_vectoring_info_field;
508 u32 idt_vectoring_error_code;
509 u32 vm_exit_instruction_len;
510 u32 vmx_instruction_info;
517 u32 guest_ldtr_limit;
519 u32 guest_gdtr_limit;
520 u32 guest_idtr_limit;
521 u32 guest_es_ar_bytes;
522 u32 guest_cs_ar_bytes;
523 u32 guest_ss_ar_bytes;
524 u32 guest_ds_ar_bytes;
525 u32 guest_fs_ar_bytes;
526 u32 guest_gs_ar_bytes;
527 u32 guest_ldtr_ar_bytes;
528 u32 guest_tr_ar_bytes;
529 u32 guest_interruptibility_info;
530 u32 guest_activity_state;
531 u32 guest_sysenter_cs;
532 u32 host_ia32_sysenter_cs;
533 u32 vmx_preemption_timer_value;
534 u32 padding32[7]; /* room for future expansion */
535 u16 virtual_processor_id;
537 u16 guest_es_selector;
538 u16 guest_cs_selector;
539 u16 guest_ss_selector;
540 u16 guest_ds_selector;
541 u16 guest_fs_selector;
542 u16 guest_gs_selector;
543 u16 guest_ldtr_selector;
544 u16 guest_tr_selector;
545 u16 guest_intr_status;
547 u16 host_es_selector;
548 u16 host_cs_selector;
549 u16 host_ss_selector;
550 u16 host_ds_selector;
551 u16 host_fs_selector;
552 u16 host_gs_selector;
553 u16 host_tr_selector;
557 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
558 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
559 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
561 #define VMCS12_REVISION 0x11e57ed0
564 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
565 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
566 * current implementation, 4K are reserved to avoid future complications.
568 #define VMCS12_SIZE 0x1000
571 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
572 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
575 /* Has the level1 guest done vmxon? */
580 /* The guest-physical address of the current VMCS L1 keeps for L2 */
583 * Cache of the guest's VMCS, existing outside of guest memory.
584 * Loaded from guest memory during VMPTRLD. Flushed to guest
585 * memory during VMCLEAR and VMPTRLD.
587 struct vmcs12 *cached_vmcs12;
589 * Indicates if the shadow vmcs must be updated with the
590 * data hold by vmcs12
592 bool sync_shadow_vmcs;
594 bool change_vmcs01_virtual_apic_mode;
596 /* L2 must run next, and mustn't decide to exit to L1. */
597 bool nested_run_pending;
599 struct loaded_vmcs vmcs02;
602 * Guest pages referred to in the vmcs02 with host-physical
603 * pointers, so we must keep them pinned while L2 runs.
605 struct page *apic_access_page;
606 struct page *virtual_apic_page;
607 struct page *pi_desc_page;
608 struct pi_desc *pi_desc;
612 struct hrtimer preemption_timer;
613 bool preemption_timer_expired;
615 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
622 * We only store the "true" versions of the VMX capability MSRs. We
623 * generate the "non-true" versions by setting the must-be-1 bits
624 * according to the SDM.
626 u32 nested_vmx_procbased_ctls_low;
627 u32 nested_vmx_procbased_ctls_high;
628 u32 nested_vmx_secondary_ctls_low;
629 u32 nested_vmx_secondary_ctls_high;
630 u32 nested_vmx_pinbased_ctls_low;
631 u32 nested_vmx_pinbased_ctls_high;
632 u32 nested_vmx_exit_ctls_low;
633 u32 nested_vmx_exit_ctls_high;
634 u32 nested_vmx_entry_ctls_low;
635 u32 nested_vmx_entry_ctls_high;
636 u32 nested_vmx_misc_low;
637 u32 nested_vmx_misc_high;
638 u32 nested_vmx_ept_caps;
639 u32 nested_vmx_vpid_caps;
640 u64 nested_vmx_basic;
641 u64 nested_vmx_cr0_fixed0;
642 u64 nested_vmx_cr0_fixed1;
643 u64 nested_vmx_cr4_fixed0;
644 u64 nested_vmx_cr4_fixed1;
645 u64 nested_vmx_vmcs_enum;
646 u64 nested_vmx_vmfunc_controls;
649 #define POSTED_INTR_ON 0
650 #define POSTED_INTR_SN 1
652 /* Posted-Interrupt Descriptor */
654 u32 pir[8]; /* Posted interrupt requested */
657 /* bit 256 - Outstanding Notification */
659 /* bit 257 - Suppress Notification */
661 /* bit 271:258 - Reserved */
663 /* bit 279:272 - Notification Vector */
665 /* bit 287:280 - Reserved */
667 /* bit 319:288 - Notification Destination */
675 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
677 return test_and_set_bit(POSTED_INTR_ON,
678 (unsigned long *)&pi_desc->control);
681 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
683 return test_and_clear_bit(POSTED_INTR_ON,
684 (unsigned long *)&pi_desc->control);
687 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
689 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
692 static inline void pi_clear_sn(struct pi_desc *pi_desc)
694 return clear_bit(POSTED_INTR_SN,
695 (unsigned long *)&pi_desc->control);
698 static inline void pi_set_sn(struct pi_desc *pi_desc)
700 return set_bit(POSTED_INTR_SN,
701 (unsigned long *)&pi_desc->control);
704 static inline void pi_clear_on(struct pi_desc *pi_desc)
706 clear_bit(POSTED_INTR_ON,
707 (unsigned long *)&pi_desc->control);
710 static inline int pi_test_on(struct pi_desc *pi_desc)
712 return test_bit(POSTED_INTR_ON,
713 (unsigned long *)&pi_desc->control);
716 static inline int pi_test_sn(struct pi_desc *pi_desc)
718 return test_bit(POSTED_INTR_SN,
719 (unsigned long *)&pi_desc->control);
724 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
728 struct kvm_vcpu vcpu;
729 unsigned long host_rsp;
733 u32 idt_vectoring_info;
735 struct shared_msr_entry *guest_msrs;
738 unsigned long host_idt_base;
740 u64 msr_host_kernel_gs_base;
741 u64 msr_guest_kernel_gs_base;
746 u32 vm_entry_controls_shadow;
747 u32 vm_exit_controls_shadow;
748 u32 secondary_exec_control;
751 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
752 * non-nested (L1) guest, it always points to vmcs01. For a nested
753 * guest (L2), it points to a different VMCS. loaded_cpu_state points
754 * to the VMCS whose state is loaded into the CPU registers that only
755 * need to be switched when transitioning to/from the kernel; a NULL
756 * value indicates that host state is loaded.
758 struct loaded_vmcs vmcs01;
759 struct loaded_vmcs *loaded_vmcs;
760 struct loaded_vmcs *loaded_cpu_state;
761 bool __launched; /* temporary, used in vmx_vcpu_run */
762 struct msr_autoload {
763 struct vmx_msrs guest;
764 struct vmx_msrs host;
768 u16 fs_sel, gs_sel, ldt_sel;
772 int gs_ldt_reload_needed;
773 int fs_reload_needed;
774 u64 msr_host_bndcfgs;
779 struct kvm_segment segs[8];
782 u32 bitmask; /* 4 bits per segment (1 bit per field) */
783 struct kvm_save_segment {
791 bool emulation_required;
795 /* Posted interrupt descriptor */
796 struct pi_desc pi_desc;
798 /* Support for a guest hypervisor (nested VMX) */
799 struct nested_vmx nested;
801 /* Dynamic PLE window. */
803 bool ple_window_dirty;
805 /* Support for PML */
806 #define PML_ENTITY_NUM 512
809 /* apic deadline value in host tsc */
812 u64 current_tsc_ratio;
817 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
818 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
819 * in msr_ia32_feature_control_valid_bits.
821 u64 msr_ia32_feature_control;
822 u64 msr_ia32_feature_control_valid_bits;
825 enum segment_cache_field {
834 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
836 return container_of(vcpu, struct vcpu_vmx, vcpu);
839 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
841 return &(to_vmx(vcpu)->pi_desc);
844 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
845 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
846 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
847 [number##_HIGH] = VMCS12_OFFSET(name)+4
850 static unsigned long shadow_read_only_fields[] = {
852 * We do NOT shadow fields that are modified when L0
853 * traps and emulates any vmx instruction (e.g. VMPTRLD,
854 * VMXON...) executed by L1.
855 * For example, VM_INSTRUCTION_ERROR is read
856 * by L1 if a vmx instruction fails (part of the error path).
857 * Note the code assumes this logic. If for some reason
858 * we start shadowing these fields then we need to
859 * force a shadow sync when L0 emulates vmx instructions
860 * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
861 * by nested_vmx_failValid)
865 VM_EXIT_INSTRUCTION_LEN,
866 IDT_VECTORING_INFO_FIELD,
867 IDT_VECTORING_ERROR_CODE,
868 VM_EXIT_INTR_ERROR_CODE,
870 GUEST_LINEAR_ADDRESS,
871 GUEST_PHYSICAL_ADDRESS
873 static int max_shadow_read_only_fields =
874 ARRAY_SIZE(shadow_read_only_fields);
876 static unsigned long shadow_read_write_fields[] = {
883 GUEST_INTERRUPTIBILITY_INFO,
896 CPU_BASED_VM_EXEC_CONTROL,
897 VM_ENTRY_EXCEPTION_ERROR_CODE,
898 VM_ENTRY_INTR_INFO_FIELD,
899 VM_ENTRY_INSTRUCTION_LEN,
900 VM_ENTRY_EXCEPTION_ERROR_CODE,
906 static int max_shadow_read_write_fields =
907 ARRAY_SIZE(shadow_read_write_fields);
909 static const unsigned short vmcs_field_to_offset_table[] = {
910 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
911 FIELD(POSTED_INTR_NV, posted_intr_nv),
912 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
913 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
914 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
915 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
916 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
917 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
918 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
919 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
920 FIELD(GUEST_INTR_STATUS, guest_intr_status),
921 FIELD(GUEST_PML_INDEX, guest_pml_index),
922 FIELD(HOST_ES_SELECTOR, host_es_selector),
923 FIELD(HOST_CS_SELECTOR, host_cs_selector),
924 FIELD(HOST_SS_SELECTOR, host_ss_selector),
925 FIELD(HOST_DS_SELECTOR, host_ds_selector),
926 FIELD(HOST_FS_SELECTOR, host_fs_selector),
927 FIELD(HOST_GS_SELECTOR, host_gs_selector),
928 FIELD(HOST_TR_SELECTOR, host_tr_selector),
929 FIELD64(IO_BITMAP_A, io_bitmap_a),
930 FIELD64(IO_BITMAP_B, io_bitmap_b),
931 FIELD64(MSR_BITMAP, msr_bitmap),
932 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
933 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
934 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
935 FIELD64(TSC_OFFSET, tsc_offset),
936 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
937 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
938 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
939 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
940 FIELD64(EPT_POINTER, ept_pointer),
941 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
942 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
943 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
944 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
945 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
946 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
947 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
948 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
949 FIELD64(PML_ADDRESS, pml_address),
950 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
951 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
952 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
953 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
954 FIELD64(GUEST_PDPTR0, guest_pdptr0),
955 FIELD64(GUEST_PDPTR1, guest_pdptr1),
956 FIELD64(GUEST_PDPTR2, guest_pdptr2),
957 FIELD64(GUEST_PDPTR3, guest_pdptr3),
958 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
959 FIELD64(HOST_IA32_PAT, host_ia32_pat),
960 FIELD64(HOST_IA32_EFER, host_ia32_efer),
961 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
962 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
963 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
964 FIELD(EXCEPTION_BITMAP, exception_bitmap),
965 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
966 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
967 FIELD(CR3_TARGET_COUNT, cr3_target_count),
968 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
969 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
970 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
971 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
972 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
973 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
974 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
975 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
976 FIELD(TPR_THRESHOLD, tpr_threshold),
977 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
978 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
979 FIELD(VM_EXIT_REASON, vm_exit_reason),
980 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
981 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
982 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
983 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
984 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
985 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
986 FIELD(GUEST_ES_LIMIT, guest_es_limit),
987 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
988 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
989 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
990 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
991 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
992 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
993 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
994 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
995 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
996 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
997 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
998 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
999 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1000 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1001 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1002 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1003 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1004 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1005 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1006 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1007 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1008 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1009 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1010 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1011 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1012 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1013 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1014 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1015 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1016 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1017 FIELD(EXIT_QUALIFICATION, exit_qualification),
1018 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1019 FIELD(GUEST_CR0, guest_cr0),
1020 FIELD(GUEST_CR3, guest_cr3),
1021 FIELD(GUEST_CR4, guest_cr4),
1022 FIELD(GUEST_ES_BASE, guest_es_base),
1023 FIELD(GUEST_CS_BASE, guest_cs_base),
1024 FIELD(GUEST_SS_BASE, guest_ss_base),
1025 FIELD(GUEST_DS_BASE, guest_ds_base),
1026 FIELD(GUEST_FS_BASE, guest_fs_base),
1027 FIELD(GUEST_GS_BASE, guest_gs_base),
1028 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1029 FIELD(GUEST_TR_BASE, guest_tr_base),
1030 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1031 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1032 FIELD(GUEST_DR7, guest_dr7),
1033 FIELD(GUEST_RSP, guest_rsp),
1034 FIELD(GUEST_RIP, guest_rip),
1035 FIELD(GUEST_RFLAGS, guest_rflags),
1036 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1037 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1038 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1039 FIELD(HOST_CR0, host_cr0),
1040 FIELD(HOST_CR3, host_cr3),
1041 FIELD(HOST_CR4, host_cr4),
1042 FIELD(HOST_FS_BASE, host_fs_base),
1043 FIELD(HOST_GS_BASE, host_gs_base),
1044 FIELD(HOST_TR_BASE, host_tr_base),
1045 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1046 FIELD(HOST_IDTR_BASE, host_idtr_base),
1047 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1048 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1049 FIELD(HOST_RSP, host_rsp),
1050 FIELD(HOST_RIP, host_rip),
1053 static inline short vmcs_field_to_offset(unsigned long field)
1055 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1056 unsigned short offset;
1058 BUILD_BUG_ON(size > SHRT_MAX);
1062 field = array_index_nospec(field, size);
1063 offset = vmcs_field_to_offset_table[field];
1069 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1071 return to_vmx(vcpu)->nested.cached_vmcs12;
1074 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1075 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1076 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1077 static bool vmx_xsaves_supported(void);
1078 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
1079 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1080 struct kvm_segment *var, int seg);
1081 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1082 struct kvm_segment *var, int seg);
1083 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1084 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1085 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
1086 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1087 static int alloc_identity_pagetable(struct kvm *kvm);
1088 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1089 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1090 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1092 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1093 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1096 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1097 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1099 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1100 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1102 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1105 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1106 * can find which vCPU should be waken up.
1108 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1109 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1119 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1121 #define vmx_io_bitmap_a (vmx_bitmap[VMX_IO_BITMAP_A])
1122 #define vmx_io_bitmap_b (vmx_bitmap[VMX_IO_BITMAP_B])
1123 #define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
1124 #define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
1126 static bool cpu_has_load_ia32_efer;
1127 static bool cpu_has_load_perf_global_ctrl;
1129 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1130 static DEFINE_SPINLOCK(vmx_vpid_lock);
1132 static struct vmcs_config {
1137 u32 pin_based_exec_ctrl;
1138 u32 cpu_based_exec_ctrl;
1139 u32 cpu_based_2nd_exec_ctrl;
1144 static struct vmx_capability {
1149 #define VMX_SEGMENT_FIELD(seg) \
1150 [VCPU_SREG_##seg] = { \
1151 .selector = GUEST_##seg##_SELECTOR, \
1152 .base = GUEST_##seg##_BASE, \
1153 .limit = GUEST_##seg##_LIMIT, \
1154 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1157 static const struct kvm_vmx_segment_field {
1162 } kvm_vmx_segment_fields[] = {
1163 VMX_SEGMENT_FIELD(CS),
1164 VMX_SEGMENT_FIELD(DS),
1165 VMX_SEGMENT_FIELD(ES),
1166 VMX_SEGMENT_FIELD(FS),
1167 VMX_SEGMENT_FIELD(GS),
1168 VMX_SEGMENT_FIELD(SS),
1169 VMX_SEGMENT_FIELD(TR),
1170 VMX_SEGMENT_FIELD(LDTR),
1173 static u64 host_efer;
1175 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1178 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1179 * away by decrementing the array size.
1181 static const u32 vmx_msr_index[] = {
1182 #ifdef CONFIG_X86_64
1183 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1185 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1188 static inline bool is_exception_n(u32 intr_info, u8 vector)
1190 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1191 INTR_INFO_VALID_MASK)) ==
1192 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1195 static inline bool is_debug(u32 intr_info)
1197 return is_exception_n(intr_info, DB_VECTOR);
1200 static inline bool is_breakpoint(u32 intr_info)
1202 return is_exception_n(intr_info, BP_VECTOR);
1205 static inline bool is_page_fault(u32 intr_info)
1207 return is_exception_n(intr_info, PF_VECTOR);
1210 static inline bool is_no_device(u32 intr_info)
1212 return is_exception_n(intr_info, NM_VECTOR);
1215 static inline bool is_invalid_opcode(u32 intr_info)
1217 return is_exception_n(intr_info, UD_VECTOR);
1220 static inline bool is_external_interrupt(u32 intr_info)
1222 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1223 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1226 static inline bool is_machine_check(u32 intr_info)
1228 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1229 INTR_INFO_VALID_MASK)) ==
1230 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1233 /* Undocumented: icebp/int1 */
1234 static inline bool is_icebp(u32 intr_info)
1236 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1237 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1240 static inline bool cpu_has_vmx_msr_bitmap(void)
1242 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1245 static inline bool cpu_has_vmx_tpr_shadow(void)
1247 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1250 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1252 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1255 static inline bool cpu_has_secondary_exec_ctrls(void)
1257 return vmcs_config.cpu_based_exec_ctrl &
1258 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1261 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1263 return vmcs_config.cpu_based_2nd_exec_ctrl &
1264 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1267 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1269 return vmcs_config.cpu_based_2nd_exec_ctrl &
1270 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1273 static inline bool cpu_has_vmx_apic_register_virt(void)
1275 return vmcs_config.cpu_based_2nd_exec_ctrl &
1276 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1279 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1281 return vmcs_config.cpu_based_2nd_exec_ctrl &
1282 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1286 * Comment's format: document - errata name - stepping - processor name.
1288 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1290 static u32 vmx_preemption_cpu_tfms[] = {
1291 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1293 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1294 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1295 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1297 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1299 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1300 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1302 * 320767.pdf - AAP86 - B1 -
1303 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1306 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1308 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1310 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1312 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1313 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1314 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1318 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1320 u32 eax = cpuid_eax(0x00000001), i;
1322 /* Clear the reserved bits */
1323 eax &= ~(0x3U << 14 | 0xfU << 28);
1324 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1325 if (eax == vmx_preemption_cpu_tfms[i])
1331 static inline bool cpu_has_vmx_preemption_timer(void)
1333 return vmcs_config.pin_based_exec_ctrl &
1334 PIN_BASED_VMX_PREEMPTION_TIMER;
1337 static inline bool cpu_has_vmx_posted_intr(void)
1339 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1340 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1343 static inline bool cpu_has_vmx_apicv(void)
1345 return cpu_has_vmx_apic_register_virt() &&
1346 cpu_has_vmx_virtual_intr_delivery() &&
1347 cpu_has_vmx_posted_intr();
1350 static inline bool cpu_has_vmx_flexpriority(void)
1352 return cpu_has_vmx_tpr_shadow() &&
1353 cpu_has_vmx_virtualize_apic_accesses();
1356 static inline bool cpu_has_vmx_ept_execute_only(void)
1358 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1361 static inline bool cpu_has_vmx_ept_2m_page(void)
1363 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1366 static inline bool cpu_has_vmx_ept_1g_page(void)
1368 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1371 static inline bool cpu_has_vmx_ept_4levels(void)
1373 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1376 static inline bool cpu_has_vmx_ept_mt_wb(void)
1378 return vmx_capability.ept & VMX_EPTP_WB_BIT;
1381 static inline bool cpu_has_vmx_ept_5levels(void)
1383 return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1386 static inline bool cpu_has_vmx_ept_ad_bits(void)
1388 return vmx_capability.ept & VMX_EPT_AD_BIT;
1391 static inline bool cpu_has_vmx_invept_context(void)
1393 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1396 static inline bool cpu_has_vmx_invept_global(void)
1398 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1401 static inline bool cpu_has_vmx_invvpid_single(void)
1403 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1406 static inline bool cpu_has_vmx_invvpid_global(void)
1408 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1411 static inline bool cpu_has_vmx_invvpid(void)
1413 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1416 static inline bool cpu_has_vmx_ept(void)
1418 return vmcs_config.cpu_based_2nd_exec_ctrl &
1419 SECONDARY_EXEC_ENABLE_EPT;
1422 static inline bool cpu_has_vmx_unrestricted_guest(void)
1424 return vmcs_config.cpu_based_2nd_exec_ctrl &
1425 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1428 static inline bool cpu_has_vmx_ple(void)
1430 return vmcs_config.cpu_based_2nd_exec_ctrl &
1431 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1434 static inline bool cpu_has_vmx_basic_inout(void)
1436 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1439 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1441 return flexpriority_enabled && lapic_in_kernel(vcpu);
1444 static inline bool cpu_has_vmx_vpid(void)
1446 return vmcs_config.cpu_based_2nd_exec_ctrl &
1447 SECONDARY_EXEC_ENABLE_VPID;
1450 static inline bool cpu_has_vmx_rdtscp(void)
1452 return vmcs_config.cpu_based_2nd_exec_ctrl &
1453 SECONDARY_EXEC_RDTSCP;
1456 static inline bool cpu_has_vmx_invpcid(void)
1458 return vmcs_config.cpu_based_2nd_exec_ctrl &
1459 SECONDARY_EXEC_ENABLE_INVPCID;
1462 static inline bool cpu_has_virtual_nmis(void)
1464 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1467 static inline bool cpu_has_vmx_wbinvd_exit(void)
1469 return vmcs_config.cpu_based_2nd_exec_ctrl &
1470 SECONDARY_EXEC_WBINVD_EXITING;
1473 static inline bool cpu_has_vmx_shadow_vmcs(void)
1476 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1477 /* check if the cpu supports writing r/o exit information fields */
1478 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1481 return vmcs_config.cpu_based_2nd_exec_ctrl &
1482 SECONDARY_EXEC_SHADOW_VMCS;
1485 static inline bool cpu_has_vmx_pml(void)
1487 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1490 static inline bool cpu_has_vmx_tsc_scaling(void)
1492 return vmcs_config.cpu_based_2nd_exec_ctrl &
1493 SECONDARY_EXEC_TSC_SCALING;
1496 static inline bool cpu_has_vmx_vmfunc(void)
1498 return vmcs_config.cpu_based_2nd_exec_ctrl &
1499 SECONDARY_EXEC_ENABLE_VMFUNC;
1502 static inline bool report_flexpriority(void)
1504 return flexpriority_enabled;
1507 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1509 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.nested_vmx_misc_low);
1512 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1514 return vmcs12->cpu_based_vm_exec_control & bit;
1517 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1519 return (vmcs12->cpu_based_vm_exec_control &
1520 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1521 (vmcs12->secondary_vm_exec_control & bit);
1524 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1526 return vmcs12->pin_based_vm_exec_control &
1527 PIN_BASED_VMX_PREEMPTION_TIMER;
1530 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1532 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1535 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1537 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
1540 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
1542 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
1545 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1547 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1550 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1552 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1555 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1557 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1560 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1562 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1565 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1567 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1570 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
1572 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
1575 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
1577 return nested_cpu_has_vmfunc(vmcs12) &&
1578 (vmcs12->vm_function_control &
1579 VMX_VMFUNC_EPTP_SWITCHING);
1582 static inline bool is_nmi(u32 intr_info)
1584 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1585 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1588 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1590 unsigned long exit_qualification);
1591 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1592 struct vmcs12 *vmcs12,
1593 u32 reason, unsigned long qualification);
1595 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1599 for (i = 0; i < vmx->nmsrs; ++i)
1600 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1605 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
1611 } operand = { vpid, 0, gva };
1613 asm volatile (__ex(ASM_VMX_INVVPID)
1614 /* CF==1 or ZF==1 --> rc = -1 */
1615 "; ja 1f ; ud2 ; 1:"
1616 : : "a"(&operand), "c"(ext) : "cc", "memory");
1619 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
1623 } operand = {eptp, gpa};
1625 asm volatile (__ex(ASM_VMX_INVEPT)
1626 /* CF==1 or ZF==1 --> rc = -1 */
1627 "; ja 1f ; ud2 ; 1:\n"
1628 : : "a" (&operand), "c" (ext) : "cc", "memory");
1631 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1635 i = __find_msr_index(vmx, msr);
1637 return &vmx->guest_msrs[i];
1641 static void vmcs_clear(struct vmcs *vmcs)
1643 u64 phys_addr = __pa(vmcs);
1646 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1647 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1650 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1654 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1656 vmcs_clear(loaded_vmcs->vmcs);
1657 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1658 vmcs_clear(loaded_vmcs->shadow_vmcs);
1659 loaded_vmcs->cpu = -1;
1660 loaded_vmcs->launched = 0;
1663 static void vmcs_load(struct vmcs *vmcs)
1665 u64 phys_addr = __pa(vmcs);
1668 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1669 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1672 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1676 #ifdef CONFIG_KEXEC_CORE
1677 static void crash_vmclear_local_loaded_vmcss(void)
1679 int cpu = raw_smp_processor_id();
1680 struct loaded_vmcs *v;
1682 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1683 loaded_vmcss_on_cpu_link)
1684 vmcs_clear(v->vmcs);
1686 #endif /* CONFIG_KEXEC_CORE */
1688 static void __loaded_vmcs_clear(void *arg)
1690 struct loaded_vmcs *loaded_vmcs = arg;
1691 int cpu = raw_smp_processor_id();
1693 if (loaded_vmcs->cpu != cpu)
1694 return; /* vcpu migration can race with cpu offline */
1695 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1696 per_cpu(current_vmcs, cpu) = NULL;
1698 vmcs_clear(loaded_vmcs->vmcs);
1699 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1700 vmcs_clear(loaded_vmcs->shadow_vmcs);
1702 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1705 * Ensure all writes to loaded_vmcs, including deleting it from its
1706 * current percpu list, complete before setting loaded_vmcs->vcpu to
1707 * -1, otherwise a different cpu can see vcpu == -1 first and add
1708 * loaded_vmcs to its percpu list before it's deleted from this cpu's
1709 * list. Pairs with the smp_rmb() in vmx_vcpu_load_vmcs().
1713 loaded_vmcs->cpu = -1;
1714 loaded_vmcs->launched = 0;
1717 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1719 int cpu = loaded_vmcs->cpu;
1722 smp_call_function_single(cpu,
1723 __loaded_vmcs_clear, loaded_vmcs, 1);
1726 static inline void vpid_sync_vcpu_single(int vpid)
1731 if (cpu_has_vmx_invvpid_single())
1732 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1735 static inline void vpid_sync_vcpu_global(void)
1737 if (cpu_has_vmx_invvpid_global())
1738 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1741 static inline void vpid_sync_context(int vpid)
1743 if (cpu_has_vmx_invvpid_single())
1744 vpid_sync_vcpu_single(vpid);
1746 vpid_sync_vcpu_global();
1749 static inline void ept_sync_global(void)
1751 if (cpu_has_vmx_invept_global())
1752 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1755 static inline void ept_sync_context(u64 eptp)
1758 if (cpu_has_vmx_invept_context())
1759 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1765 static __always_inline void vmcs_check16(unsigned long field)
1767 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1768 "16-bit accessor invalid for 64-bit field");
1769 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1770 "16-bit accessor invalid for 64-bit high field");
1771 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1772 "16-bit accessor invalid for 32-bit high field");
1773 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1774 "16-bit accessor invalid for natural width field");
1777 static __always_inline void vmcs_check32(unsigned long field)
1779 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1780 "32-bit accessor invalid for 16-bit field");
1781 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1782 "32-bit accessor invalid for natural width field");
1785 static __always_inline void vmcs_check64(unsigned long field)
1787 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1788 "64-bit accessor invalid for 16-bit field");
1789 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1790 "64-bit accessor invalid for 64-bit high field");
1791 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1792 "64-bit accessor invalid for 32-bit field");
1793 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1794 "64-bit accessor invalid for natural width field");
1797 static __always_inline void vmcs_checkl(unsigned long field)
1799 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1800 "Natural width accessor invalid for 16-bit field");
1801 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1802 "Natural width accessor invalid for 64-bit field");
1803 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1804 "Natural width accessor invalid for 64-bit high field");
1805 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1806 "Natural width accessor invalid for 32-bit field");
1809 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1811 unsigned long value;
1813 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1814 : "=a"(value) : "d"(field) : "cc");
1818 static __always_inline u16 vmcs_read16(unsigned long field)
1820 vmcs_check16(field);
1821 return __vmcs_readl(field);
1824 static __always_inline u32 vmcs_read32(unsigned long field)
1826 vmcs_check32(field);
1827 return __vmcs_readl(field);
1830 static __always_inline u64 vmcs_read64(unsigned long field)
1832 vmcs_check64(field);
1833 #ifdef CONFIG_X86_64
1834 return __vmcs_readl(field);
1836 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1840 static __always_inline unsigned long vmcs_readl(unsigned long field)
1843 return __vmcs_readl(field);
1846 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1848 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1849 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1853 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1857 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1858 : "=q"(error) : "a"(value), "d"(field) : "cc");
1859 if (unlikely(error))
1860 vmwrite_error(field, value);
1863 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1865 vmcs_check16(field);
1866 __vmcs_writel(field, value);
1869 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1871 vmcs_check32(field);
1872 __vmcs_writel(field, value);
1875 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1877 vmcs_check64(field);
1878 __vmcs_writel(field, value);
1879 #ifndef CONFIG_X86_64
1881 __vmcs_writel(field+1, value >> 32);
1885 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1888 __vmcs_writel(field, value);
1891 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1893 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1894 "vmcs_clear_bits does not support 64-bit fields");
1895 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1898 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1900 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1901 "vmcs_set_bits does not support 64-bit fields");
1902 __vmcs_writel(field, __vmcs_readl(field) | mask);
1905 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1907 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1910 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1912 vmcs_write32(VM_ENTRY_CONTROLS, val);
1913 vmx->vm_entry_controls_shadow = val;
1916 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1918 if (vmx->vm_entry_controls_shadow != val)
1919 vm_entry_controls_init(vmx, val);
1922 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1924 return vmx->vm_entry_controls_shadow;
1928 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1930 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1933 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1935 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1938 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1940 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1943 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1945 vmcs_write32(VM_EXIT_CONTROLS, val);
1946 vmx->vm_exit_controls_shadow = val;
1949 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1951 if (vmx->vm_exit_controls_shadow != val)
1952 vm_exit_controls_init(vmx, val);
1955 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1957 return vmx->vm_exit_controls_shadow;
1961 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1963 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1966 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1968 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1971 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1973 vmx->segment_cache.bitmask = 0;
1976 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1980 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1982 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1983 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1984 vmx->segment_cache.bitmask = 0;
1986 ret = vmx->segment_cache.bitmask & mask;
1987 vmx->segment_cache.bitmask |= mask;
1991 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1993 u16 *p = &vmx->segment_cache.seg[seg].selector;
1995 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1996 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2000 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2002 ulong *p = &vmx->segment_cache.seg[seg].base;
2004 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2005 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2009 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2011 u32 *p = &vmx->segment_cache.seg[seg].limit;
2013 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2014 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2018 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2020 u32 *p = &vmx->segment_cache.seg[seg].ar;
2022 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2023 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2027 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2031 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2032 (1u << DB_VECTOR) | (1u << AC_VECTOR);
2033 if ((vcpu->guest_debug &
2034 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2035 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2036 eb |= 1u << BP_VECTOR;
2037 if (to_vmx(vcpu)->rmode.vm86_active)
2040 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2042 /* When we are running a nested L2 guest and L1 specified for it a
2043 * certain exception bitmap, we must trap the same exceptions and pass
2044 * them to L1. When running L2, we will only handle the exceptions
2045 * specified above if L1 did not want them.
2047 if (is_guest_mode(vcpu))
2048 eb |= get_vmcs12(vcpu)->exception_bitmap;
2050 vmcs_write32(EXCEPTION_BITMAP, eb);
2054 * Check if MSR is intercepted for currently loaded MSR bitmap.
2056 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2058 unsigned long *msr_bitmap;
2059 int f = sizeof(unsigned long);
2061 if (!cpu_has_vmx_msr_bitmap())
2064 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2066 if (msr <= 0x1fff) {
2067 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2068 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2070 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2077 * Check if MSR is intercepted for L01 MSR bitmap.
2079 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2081 unsigned long *msr_bitmap;
2082 int f = sizeof(unsigned long);
2084 if (!cpu_has_vmx_msr_bitmap())
2087 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2089 if (msr <= 0x1fff) {
2090 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2091 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2093 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2099 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2100 unsigned long entry, unsigned long exit)
2102 vm_entry_controls_clearbit(vmx, entry);
2103 vm_exit_controls_clearbit(vmx, exit);
2106 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2110 for (i = 0; i < m->nr; ++i) {
2111 if (m->val[i].index == msr)
2117 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2120 struct msr_autoload *m = &vmx->msr_autoload;
2124 if (cpu_has_load_ia32_efer) {
2125 clear_atomic_switch_msr_special(vmx,
2126 VM_ENTRY_LOAD_IA32_EFER,
2127 VM_EXIT_LOAD_IA32_EFER);
2131 case MSR_CORE_PERF_GLOBAL_CTRL:
2132 if (cpu_has_load_perf_global_ctrl) {
2133 clear_atomic_switch_msr_special(vmx,
2134 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2135 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2140 i = find_msr(&m->guest, msr);
2144 m->guest.val[i] = m->guest.val[m->guest.nr];
2145 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2148 i = find_msr(&m->host, msr);
2153 m->host.val[i] = m->host.val[m->host.nr];
2154 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2157 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2158 unsigned long entry, unsigned long exit,
2159 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2160 u64 guest_val, u64 host_val)
2162 vmcs_write64(guest_val_vmcs, guest_val);
2163 vmcs_write64(host_val_vmcs, host_val);
2164 vm_entry_controls_setbit(vmx, entry);
2165 vm_exit_controls_setbit(vmx, exit);
2168 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2169 u64 guest_val, u64 host_val, bool entry_only)
2172 struct msr_autoload *m = &vmx->msr_autoload;
2176 if (cpu_has_load_ia32_efer) {
2177 add_atomic_switch_msr_special(vmx,
2178 VM_ENTRY_LOAD_IA32_EFER,
2179 VM_EXIT_LOAD_IA32_EFER,
2182 guest_val, host_val);
2186 case MSR_CORE_PERF_GLOBAL_CTRL:
2187 if (cpu_has_load_perf_global_ctrl) {
2188 add_atomic_switch_msr_special(vmx,
2189 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2190 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2191 GUEST_IA32_PERF_GLOBAL_CTRL,
2192 HOST_IA32_PERF_GLOBAL_CTRL,
2193 guest_val, host_val);
2197 case MSR_IA32_PEBS_ENABLE:
2198 /* PEBS needs a quiescent period after being disabled (to write
2199 * a record). Disabling PEBS through VMX MSR swapping doesn't
2200 * provide that period, so a CPU could write host's record into
2203 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2206 i = find_msr(&m->guest, msr);
2208 j = find_msr(&m->host, msr);
2210 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
2211 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
2212 printk_once(KERN_WARNING "Not enough msr switch entries. "
2213 "Can't add msr %x\n", msr);
2218 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2220 m->guest.val[i].index = msr;
2221 m->guest.val[i].value = guest_val;
2228 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2230 m->host.val[j].index = msr;
2231 m->host.val[j].value = host_val;
2234 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2236 u64 guest_efer = vmx->vcpu.arch.efer;
2237 u64 ignore_bits = 0;
2239 /* Shadow paging assumes NX to be available. */
2241 guest_efer |= EFER_NX;
2244 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2246 ignore_bits |= EFER_SCE;
2247 #ifdef CONFIG_X86_64
2248 ignore_bits |= EFER_LMA | EFER_LME;
2249 /* SCE is meaningful only in long mode on Intel */
2250 if (guest_efer & EFER_LMA)
2251 ignore_bits &= ~(u64)EFER_SCE;
2254 clear_atomic_switch_msr(vmx, MSR_EFER);
2257 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2258 * On CPUs that support "load IA32_EFER", always switch EFER
2259 * atomically, since it's faster than switching it manually.
2261 if (cpu_has_load_ia32_efer ||
2262 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2263 if (!(guest_efer & EFER_LMA))
2264 guest_efer &= ~EFER_LME;
2265 if (guest_efer != host_efer)
2266 add_atomic_switch_msr(vmx, MSR_EFER,
2267 guest_efer, host_efer, false);
2270 guest_efer &= ~ignore_bits;
2271 guest_efer |= host_efer & ignore_bits;
2273 vmx->guest_msrs[efer_offset].data = guest_efer;
2274 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2280 #ifdef CONFIG_X86_32
2282 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2283 * VMCS rather than the segment table. KVM uses this helper to figure
2284 * out the current bases to poke them into the VMCS before entry.
2286 static unsigned long segment_base(u16 selector)
2288 struct desc_struct *table;
2291 if (!(selector & ~SEGMENT_RPL_MASK))
2294 table = get_current_gdt_ro();
2296 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2297 u16 ldt_selector = kvm_read_ldt();
2299 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2302 table = (struct desc_struct *)segment_base(ldt_selector);
2304 v = get_desc_base(&table[selector >> 3]);
2309 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2311 struct vcpu_vmx *vmx = to_vmx(vcpu);
2314 if (vmx->loaded_cpu_state)
2317 vmx->loaded_cpu_state = vmx->loaded_vmcs;
2320 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2321 * allow segment selectors with cpl > 0 or ti == 1.
2323 vmx->host_state.ldt_sel = kvm_read_ldt();
2324 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2325 savesegment(fs, vmx->host_state.fs_sel);
2326 if (!(vmx->host_state.fs_sel & 7)) {
2327 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2328 vmx->host_state.fs_reload_needed = 0;
2330 vmcs_write16(HOST_FS_SELECTOR, 0);
2331 vmx->host_state.fs_reload_needed = 1;
2333 savesegment(gs, vmx->host_state.gs_sel);
2334 if (!(vmx->host_state.gs_sel & 7))
2335 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2337 vmcs_write16(HOST_GS_SELECTOR, 0);
2338 vmx->host_state.gs_ldt_reload_needed = 1;
2341 #ifdef CONFIG_X86_64
2342 savesegment(ds, vmx->host_state.ds_sel);
2343 savesegment(es, vmx->host_state.es_sel);
2346 #ifdef CONFIG_X86_64
2347 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2348 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2350 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2351 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2354 #ifdef CONFIG_X86_64
2355 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2356 if (is_long_mode(&vmx->vcpu))
2357 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2359 if (boot_cpu_has(X86_FEATURE_MPX))
2360 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2361 for (i = 0; i < vmx->save_nmsrs; ++i)
2362 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2363 vmx->guest_msrs[i].data,
2364 vmx->guest_msrs[i].mask);
2367 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2369 if (!vmx->loaded_cpu_state)
2372 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2374 ++vmx->vcpu.stat.host_state_reload;
2375 vmx->loaded_cpu_state = NULL;
2377 #ifdef CONFIG_X86_64
2378 if (is_long_mode(&vmx->vcpu))
2379 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2381 if (vmx->host_state.gs_ldt_reload_needed) {
2382 kvm_load_ldt(vmx->host_state.ldt_sel);
2383 #ifdef CONFIG_X86_64
2384 load_gs_index(vmx->host_state.gs_sel);
2386 loadsegment(gs, vmx->host_state.gs_sel);
2389 if (vmx->host_state.fs_reload_needed)
2390 loadsegment(fs, vmx->host_state.fs_sel);
2391 #ifdef CONFIG_X86_64
2392 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2393 loadsegment(ds, vmx->host_state.ds_sel);
2394 loadsegment(es, vmx->host_state.es_sel);
2397 invalidate_tss_limit();
2398 #ifdef CONFIG_X86_64
2399 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2401 if (vmx->host_state.msr_host_bndcfgs)
2402 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2403 load_fixmap_gdt(raw_smp_processor_id());
2406 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2409 __vmx_load_host_state(vmx);
2413 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2415 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2416 struct pi_desc old, new;
2420 * In case of hot-plug or hot-unplug, we may have to undo
2421 * vmx_vcpu_pi_put even if there is no assigned device. And we
2422 * always keep PI.NDST up to date for simplicity: it makes the
2423 * code easier, and CPU migration is not a fast path.
2425 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2429 * First handle the simple case where no cmpxchg is necessary; just
2430 * allow posting non-urgent interrupts.
2432 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2433 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2434 * expects the VCPU to be on the blocked_vcpu_list that matches
2437 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2439 pi_clear_sn(pi_desc);
2443 /* The full case. */
2445 old.control = new.control = pi_desc->control;
2447 dest = cpu_physical_id(cpu);
2449 if (x2apic_enabled())
2452 new.ndst = (dest << 8) & 0xFF00;
2455 } while (cmpxchg64(&pi_desc->control, old.control,
2456 new.control) != old.control);
2459 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2461 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2462 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2466 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2467 * vcpu mutex is already taken.
2469 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2471 struct vcpu_vmx *vmx = to_vmx(vcpu);
2472 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2474 if (!already_loaded) {
2475 loaded_vmcs_clear(vmx->loaded_vmcs);
2476 local_irq_disable();
2479 * Ensure loaded_vmcs->cpu is read before adding loaded_vmcs to
2480 * this cpu's percpu list, otherwise it may not yet be deleted
2481 * from its previous cpu's percpu list. Pairs with the
2482 * smb_wmb() in __loaded_vmcs_clear().
2486 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2487 &per_cpu(loaded_vmcss_on_cpu, cpu));
2491 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2492 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2493 vmcs_load(vmx->loaded_vmcs->vmcs);
2494 indirect_branch_prediction_barrier();
2497 if (!already_loaded) {
2498 void *gdt = get_current_gdt_ro();
2499 unsigned long sysenter_esp;
2501 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2504 * Linux uses per-cpu TSS and GDT, so set these when switching
2505 * processors. See 22.2.4.
2507 vmcs_writel(HOST_TR_BASE,
2508 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
2509 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
2512 * VM exits change the host TR limit to 0x67 after a VM
2513 * exit. This is okay, since 0x67 covers everything except
2514 * the IO bitmap and have have code to handle the IO bitmap
2515 * being lost after a VM exit.
2517 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
2519 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2520 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2522 vmx->loaded_vmcs->cpu = cpu;
2525 /* Setup TSC multiplier */
2526 if (kvm_has_tsc_control &&
2527 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2528 decache_tsc_multiplier(vmx);
2530 vmx_vcpu_pi_load(vcpu, cpu);
2531 vmx->host_pkru = read_pkru();
2534 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2536 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2538 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2539 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2540 !kvm_vcpu_apicv_active(vcpu))
2543 /* Set SN when the vCPU is preempted */
2544 if (vcpu->preempted)
2548 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2550 vmx_vcpu_pi_put(vcpu);
2552 __vmx_load_host_state(to_vmx(vcpu));
2555 static bool emulation_required(struct kvm_vcpu *vcpu)
2557 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
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 unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2580 unsigned long rflags, save_rflags;
2582 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2583 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2584 rflags = vmcs_readl(GUEST_RFLAGS);
2585 if (to_vmx(vcpu)->rmode.vm86_active) {
2586 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2587 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2588 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2590 to_vmx(vcpu)->rflags = rflags;
2592 return to_vmx(vcpu)->rflags;
2595 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2597 unsigned long old_rflags = vmx_get_rflags(vcpu);
2599 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2600 to_vmx(vcpu)->rflags = rflags;
2601 if (to_vmx(vcpu)->rmode.vm86_active) {
2602 to_vmx(vcpu)->rmode.save_rflags = rflags;
2603 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2605 vmcs_writel(GUEST_RFLAGS, rflags);
2607 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
2608 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
2611 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2613 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2616 if (interruptibility & GUEST_INTR_STATE_STI)
2617 ret |= KVM_X86_SHADOW_INT_STI;
2618 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2619 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2624 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2626 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2627 u32 interruptibility = interruptibility_old;
2629 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2631 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2632 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2633 else if (mask & KVM_X86_SHADOW_INT_STI)
2634 interruptibility |= GUEST_INTR_STATE_STI;
2636 if ((interruptibility != interruptibility_old))
2637 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2640 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2644 rip = kvm_rip_read(vcpu);
2645 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2646 kvm_rip_write(vcpu, rip);
2648 /* skipping an emulated instruction also counts */
2649 vmx_set_interrupt_shadow(vcpu, 0);
2652 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
2653 unsigned long exit_qual)
2655 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2656 unsigned int nr = vcpu->arch.exception.nr;
2657 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2659 if (vcpu->arch.exception.has_error_code) {
2660 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
2661 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2664 if (kvm_exception_is_soft(nr))
2665 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2667 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2669 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
2670 vmx_get_nmi_mask(vcpu))
2671 intr_info |= INTR_INFO_UNBLOCK_NMI;
2673 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
2677 * KVM wants to inject page-faults which it got to the guest. This function
2678 * checks whether in a nested guest, we need to inject them to L1 or L2.
2680 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
2682 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2683 unsigned int nr = vcpu->arch.exception.nr;
2685 if (nr == PF_VECTOR) {
2686 if (vcpu->arch.exception.nested_apf) {
2687 *exit_qual = vcpu->arch.apf.nested_apf_token;
2691 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
2692 * The fix is to add the ancillary datum (CR2 or DR6) to structs
2693 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
2694 * can be written only when inject_pending_event runs. This should be
2695 * conditional on a new capability---if the capability is disabled,
2696 * kvm_multiple_exception would write the ancillary information to
2697 * CR2 or DR6, for backwards ABI-compatibility.
2699 if (nested_vmx_is_page_fault_vmexit(vmcs12,
2700 vcpu->arch.exception.error_code)) {
2701 *exit_qual = vcpu->arch.cr2;
2705 if (vmcs12->exception_bitmap & (1u << nr)) {
2706 if (nr == DB_VECTOR) {
2707 *exit_qual = vcpu->arch.dr6;
2708 *exit_qual &= ~(DR6_FIXED_1 | DR6_BT);
2709 *exit_qual ^= DR6_RTM;
2720 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
2722 struct vcpu_vmx *vmx = to_vmx(vcpu);
2723 unsigned nr = vcpu->arch.exception.nr;
2724 bool has_error_code = vcpu->arch.exception.has_error_code;
2725 u32 error_code = vcpu->arch.exception.error_code;
2726 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2728 if (has_error_code) {
2729 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2730 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2733 if (vmx->rmode.vm86_active) {
2735 if (kvm_exception_is_soft(nr))
2736 inc_eip = vcpu->arch.event_exit_inst_len;
2737 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2738 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2742 WARN_ON_ONCE(vmx->emulation_required);
2744 if (kvm_exception_is_soft(nr)) {
2745 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2746 vmx->vcpu.arch.event_exit_inst_len);
2747 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2749 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2751 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2754 static bool vmx_rdtscp_supported(void)
2756 return cpu_has_vmx_rdtscp();
2759 static bool vmx_invpcid_supported(void)
2761 return cpu_has_vmx_invpcid() && enable_ept;
2765 * Swap MSR entry in host/guest MSR entry array.
2767 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2769 struct shared_msr_entry tmp;
2771 tmp = vmx->guest_msrs[to];
2772 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2773 vmx->guest_msrs[from] = tmp;
2777 * Set up the vmcs to automatically save and restore system
2778 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2779 * mode, as fiddling with msrs is very expensive.
2781 static void setup_msrs(struct vcpu_vmx *vmx)
2783 int save_nmsrs, index;
2786 #ifdef CONFIG_X86_64
2787 if (is_long_mode(&vmx->vcpu)) {
2788 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2790 move_msr_up(vmx, index, save_nmsrs++);
2791 index = __find_msr_index(vmx, MSR_LSTAR);
2793 move_msr_up(vmx, index, save_nmsrs++);
2794 index = __find_msr_index(vmx, MSR_CSTAR);
2796 move_msr_up(vmx, index, save_nmsrs++);
2798 * MSR_STAR is only needed on long mode guests, and only
2799 * if efer.sce is enabled.
2801 index = __find_msr_index(vmx, MSR_STAR);
2802 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2803 move_msr_up(vmx, index, save_nmsrs++);
2806 index = __find_msr_index(vmx, MSR_EFER);
2807 if (index >= 0 && update_transition_efer(vmx, index))
2808 move_msr_up(vmx, index, save_nmsrs++);
2809 index = __find_msr_index(vmx, MSR_TSC_AUX);
2810 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
2811 move_msr_up(vmx, index, save_nmsrs++);
2813 vmx->save_nmsrs = save_nmsrs;
2815 if (cpu_has_vmx_msr_bitmap())
2816 vmx_update_msr_bitmap(&vmx->vcpu);
2820 * reads and returns guest's timestamp counter "register"
2821 * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2822 * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2824 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2826 u64 host_tsc, tsc_offset;
2829 tsc_offset = vmcs_read64(TSC_OFFSET);
2830 return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2834 * writes 'offset' into guest's timestamp counter offset register
2836 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2838 if (is_guest_mode(vcpu)) {
2840 * We're here if L1 chose not to trap WRMSR to TSC. According
2841 * to the spec, this should set L1's TSC; The offset that L1
2842 * set for L2 remains unchanged, and still needs to be added
2843 * to the newly set TSC to get L2's TSC.
2845 struct vmcs12 *vmcs12;
2846 /* recalculate vmcs02.TSC_OFFSET: */
2847 vmcs12 = get_vmcs12(vcpu);
2848 vmcs_write64(TSC_OFFSET, offset +
2849 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2850 vmcs12->tsc_offset : 0));
2852 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2853 vmcs_read64(TSC_OFFSET), offset);
2854 vmcs_write64(TSC_OFFSET, offset);
2859 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2860 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2861 * all guests if the "nested" module option is off, and can also be disabled
2862 * for a single guest by disabling its VMX cpuid bit.
2864 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2866 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
2870 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2871 * returned for the various VMX controls MSRs when nested VMX is enabled.
2872 * The same values should also be used to verify that vmcs12 control fields are
2873 * valid during nested entry from L1 to L2.
2874 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2875 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2876 * bit in the high half is on if the corresponding bit in the control field
2877 * may be on. See also vmx_control_verify().
2879 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2882 * Note that as a general rule, the high half of the MSRs (bits in
2883 * the control fields which may be 1) should be initialized by the
2884 * intersection of the underlying hardware's MSR (i.e., features which
2885 * can be supported) and the list of features we want to expose -
2886 * because they are known to be properly supported in our code.
2887 * Also, usually, the low half of the MSRs (bits which must be 1) can
2888 * be set to 0, meaning that L1 may turn off any of these bits. The
2889 * reason is that if one of these bits is necessary, it will appear
2890 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2891 * fields of vmcs01 and vmcs02, will turn these bits off - and
2892 * nested_vmx_exit_reflected() will not pass related exits to L1.
2893 * These rules have exceptions below.
2896 /* pin-based controls */
2897 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2898 vmx->nested.nested_vmx_pinbased_ctls_low,
2899 vmx->nested.nested_vmx_pinbased_ctls_high);
2900 vmx->nested.nested_vmx_pinbased_ctls_low |=
2901 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2902 vmx->nested.nested_vmx_pinbased_ctls_high &=
2903 PIN_BASED_EXT_INTR_MASK |
2904 PIN_BASED_NMI_EXITING |
2905 PIN_BASED_VIRTUAL_NMIS;
2906 vmx->nested.nested_vmx_pinbased_ctls_high |=
2907 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2908 PIN_BASED_VMX_PREEMPTION_TIMER;
2909 if (kvm_vcpu_apicv_active(&vmx->vcpu))
2910 vmx->nested.nested_vmx_pinbased_ctls_high |=
2911 PIN_BASED_POSTED_INTR;
2914 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2915 vmx->nested.nested_vmx_exit_ctls_low,
2916 vmx->nested.nested_vmx_exit_ctls_high);
2917 vmx->nested.nested_vmx_exit_ctls_low =
2918 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2920 vmx->nested.nested_vmx_exit_ctls_high &=
2921 #ifdef CONFIG_X86_64
2922 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2924 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2925 vmx->nested.nested_vmx_exit_ctls_high |=
2926 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2927 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2928 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2930 if (kvm_mpx_supported())
2931 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2933 /* We support free control of debug control saving. */
2934 vmx->nested.nested_vmx_exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2936 /* entry controls */
2937 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2938 vmx->nested.nested_vmx_entry_ctls_low,
2939 vmx->nested.nested_vmx_entry_ctls_high);
2940 vmx->nested.nested_vmx_entry_ctls_low =
2941 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2942 vmx->nested.nested_vmx_entry_ctls_high &=
2943 #ifdef CONFIG_X86_64
2944 VM_ENTRY_IA32E_MODE |
2946 VM_ENTRY_LOAD_IA32_PAT;
2947 vmx->nested.nested_vmx_entry_ctls_high |=
2948 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2949 if (kvm_mpx_supported())
2950 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2952 /* We support free control of debug control loading. */
2953 vmx->nested.nested_vmx_entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2955 /* cpu-based controls */
2956 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2957 vmx->nested.nested_vmx_procbased_ctls_low,
2958 vmx->nested.nested_vmx_procbased_ctls_high);
2959 vmx->nested.nested_vmx_procbased_ctls_low =
2960 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2961 vmx->nested.nested_vmx_procbased_ctls_high &=
2962 CPU_BASED_VIRTUAL_INTR_PENDING |
2963 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2964 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2965 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2966 CPU_BASED_CR3_STORE_EXITING |
2967 #ifdef CONFIG_X86_64
2968 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2970 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2971 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2972 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2973 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2974 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2976 * We can allow some features even when not supported by the
2977 * hardware. For example, L1 can specify an MSR bitmap - and we
2978 * can use it to avoid exits to L1 - even when L0 runs L2
2979 * without MSR bitmaps.
2981 vmx->nested.nested_vmx_procbased_ctls_high |=
2982 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2983 CPU_BASED_USE_MSR_BITMAPS;
2985 /* We support free control of CR3 access interception. */
2986 vmx->nested.nested_vmx_procbased_ctls_low &=
2987 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2990 * secondary cpu-based controls. Do not include those that
2991 * depend on CPUID bits, they are added later by vmx_cpuid_update.
2993 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2994 vmx->nested.nested_vmx_secondary_ctls_low,
2995 vmx->nested.nested_vmx_secondary_ctls_high);
2996 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2997 vmx->nested.nested_vmx_secondary_ctls_high &=
2998 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2999 SECONDARY_EXEC_DESC |
3000 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3001 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3002 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3003 SECONDARY_EXEC_WBINVD_EXITING;
3006 /* nested EPT: emulate EPT also to L1 */
3007 vmx->nested.nested_vmx_secondary_ctls_high |=
3008 SECONDARY_EXEC_ENABLE_EPT;
3009 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3010 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3011 if (cpu_has_vmx_ept_execute_only())
3012 vmx->nested.nested_vmx_ept_caps |=
3013 VMX_EPT_EXECUTE_ONLY_BIT;
3014 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
3015 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3016 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3017 VMX_EPT_1GB_PAGE_BIT;
3018 if (enable_ept_ad_bits) {
3019 vmx->nested.nested_vmx_secondary_ctls_high |=
3020 SECONDARY_EXEC_ENABLE_PML;
3021 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_AD_BIT;
3024 vmx->nested.nested_vmx_ept_caps = 0;
3026 if (cpu_has_vmx_vmfunc()) {
3027 vmx->nested.nested_vmx_secondary_ctls_high |=
3028 SECONDARY_EXEC_ENABLE_VMFUNC;
3030 * Advertise EPTP switching unconditionally
3031 * since we emulate it
3034 vmx->nested.nested_vmx_vmfunc_controls =
3035 VMX_VMFUNC_EPTP_SWITCHING;
3039 * Old versions of KVM use the single-context version without
3040 * checking for support, so declare that it is supported even
3041 * though it is treated as global context. The alternative is
3042 * not failing the single-context invvpid, and it is worse.
3045 vmx->nested.nested_vmx_secondary_ctls_high |=
3046 SECONDARY_EXEC_ENABLE_VPID;
3047 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
3048 VMX_VPID_EXTENT_SUPPORTED_MASK;
3050 vmx->nested.nested_vmx_vpid_caps = 0;
3052 if (enable_unrestricted_guest)
3053 vmx->nested.nested_vmx_secondary_ctls_high |=
3054 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3056 /* miscellaneous data */
3057 rdmsr(MSR_IA32_VMX_MISC,
3058 vmx->nested.nested_vmx_misc_low,
3059 vmx->nested.nested_vmx_misc_high);
3060 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
3061 vmx->nested.nested_vmx_misc_low |=
3062 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3063 VMX_MISC_ACTIVITY_HLT;
3064 vmx->nested.nested_vmx_misc_high = 0;
3067 * This MSR reports some information about VMX support. We
3068 * should return information about the VMX we emulate for the
3069 * guest, and the VMCS structure we give it - not about the
3070 * VMX support of the underlying hardware.
3072 vmx->nested.nested_vmx_basic =
3074 VMX_BASIC_TRUE_CTLS |
3075 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3076 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3078 if (cpu_has_vmx_basic_inout())
3079 vmx->nested.nested_vmx_basic |= VMX_BASIC_INOUT;
3082 * These MSRs specify bits which the guest must keep fixed on
3083 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3084 * We picked the standard core2 setting.
3086 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3087 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3088 vmx->nested.nested_vmx_cr0_fixed0 = VMXON_CR0_ALWAYSON;
3089 vmx->nested.nested_vmx_cr4_fixed0 = VMXON_CR4_ALWAYSON;
3091 /* These MSRs specify bits which the guest must keep fixed off. */
3092 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, vmx->nested.nested_vmx_cr0_fixed1);
3093 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, vmx->nested.nested_vmx_cr4_fixed1);
3095 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3096 vmx->nested.nested_vmx_vmcs_enum = 0x2e;
3100 * if fixed0[i] == 1: val[i] must be 1
3101 * if fixed1[i] == 0: val[i] must be 0
3103 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3105 return ((val & fixed1) | fixed0) == val;
3108 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3110 return fixed_bits_valid(control, low, high);
3113 static inline u64 vmx_control_msr(u32 low, u32 high)
3115 return low | ((u64)high << 32);
3118 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3123 return (superset | subset) == superset;
3126 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3128 const u64 feature_and_reserved =
3129 /* feature (except bit 48; see below) */
3130 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3132 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3133 u64 vmx_basic = vmx->nested.nested_vmx_basic;
3135 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3139 * KVM does not emulate a version of VMX that constrains physical
3140 * addresses of VMX structures (e.g. VMCS) to 32-bits.
3142 if (data & BIT_ULL(48))
3145 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3146 vmx_basic_vmcs_revision_id(data))
3149 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3152 vmx->nested.nested_vmx_basic = data;
3157 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3162 switch (msr_index) {
3163 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3164 lowp = &vmx->nested.nested_vmx_pinbased_ctls_low;
3165 highp = &vmx->nested.nested_vmx_pinbased_ctls_high;
3167 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3168 lowp = &vmx->nested.nested_vmx_procbased_ctls_low;
3169 highp = &vmx->nested.nested_vmx_procbased_ctls_high;
3171 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3172 lowp = &vmx->nested.nested_vmx_exit_ctls_low;
3173 highp = &vmx->nested.nested_vmx_exit_ctls_high;
3175 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3176 lowp = &vmx->nested.nested_vmx_entry_ctls_low;
3177 highp = &vmx->nested.nested_vmx_entry_ctls_high;
3179 case MSR_IA32_VMX_PROCBASED_CTLS2:
3180 lowp = &vmx->nested.nested_vmx_secondary_ctls_low;
3181 highp = &vmx->nested.nested_vmx_secondary_ctls_high;
3187 supported = vmx_control_msr(*lowp, *highp);
3189 /* Check must-be-1 bits are still 1. */
3190 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3193 /* Check must-be-0 bits are still 0. */
3194 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3198 *highp = data >> 32;
3202 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3204 const u64 feature_and_reserved_bits =
3206 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3207 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3209 GENMASK_ULL(13, 9) | BIT_ULL(31);
3212 vmx_misc = vmx_control_msr(vmx->nested.nested_vmx_misc_low,
3213 vmx->nested.nested_vmx_misc_high);
3215 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3218 if ((vmx->nested.nested_vmx_pinbased_ctls_high &
3219 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3220 vmx_misc_preemption_timer_rate(data) !=
3221 vmx_misc_preemption_timer_rate(vmx_misc))
3224 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3227 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3230 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3233 vmx->nested.nested_vmx_misc_low = data;
3234 vmx->nested.nested_vmx_misc_high = data >> 32;
3238 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3240 u64 vmx_ept_vpid_cap;
3242 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.nested_vmx_ept_caps,
3243 vmx->nested.nested_vmx_vpid_caps);
3245 /* Every bit is either reserved or a feature bit. */
3246 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3249 vmx->nested.nested_vmx_ept_caps = data;
3250 vmx->nested.nested_vmx_vpid_caps = data >> 32;
3254 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3258 switch (msr_index) {
3259 case MSR_IA32_VMX_CR0_FIXED0:
3260 msr = &vmx->nested.nested_vmx_cr0_fixed0;
3262 case MSR_IA32_VMX_CR4_FIXED0:
3263 msr = &vmx->nested.nested_vmx_cr4_fixed0;
3270 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3271 * must be 1 in the restored value.
3273 if (!is_bitwise_subset(data, *msr, -1ULL))
3281 * Called when userspace is restoring VMX MSRs.
3283 * Returns 0 on success, non-0 otherwise.
3285 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3287 struct vcpu_vmx *vmx = to_vmx(vcpu);
3289 switch (msr_index) {
3290 case MSR_IA32_VMX_BASIC:
3291 return vmx_restore_vmx_basic(vmx, data);
3292 case MSR_IA32_VMX_PINBASED_CTLS:
3293 case MSR_IA32_VMX_PROCBASED_CTLS:
3294 case MSR_IA32_VMX_EXIT_CTLS:
3295 case MSR_IA32_VMX_ENTRY_CTLS:
3297 * The "non-true" VMX capability MSRs are generated from the
3298 * "true" MSRs, so we do not support restoring them directly.
3300 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3301 * should restore the "true" MSRs with the must-be-1 bits
3302 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3303 * DEFAULT SETTINGS".
3306 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3307 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3308 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3309 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3310 case MSR_IA32_VMX_PROCBASED_CTLS2:
3311 return vmx_restore_control_msr(vmx, msr_index, data);
3312 case MSR_IA32_VMX_MISC:
3313 return vmx_restore_vmx_misc(vmx, data);
3314 case MSR_IA32_VMX_CR0_FIXED0:
3315 case MSR_IA32_VMX_CR4_FIXED0:
3316 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3317 case MSR_IA32_VMX_CR0_FIXED1:
3318 case MSR_IA32_VMX_CR4_FIXED1:
3320 * These MSRs are generated based on the vCPU's CPUID, so we
3321 * do not support restoring them directly.
3324 case MSR_IA32_VMX_EPT_VPID_CAP:
3325 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3326 case MSR_IA32_VMX_VMCS_ENUM:
3327 vmx->nested.nested_vmx_vmcs_enum = data;
3331 * The rest of the VMX capability MSRs do not support restore.
3337 /* Returns 0 on success, non-0 otherwise. */
3338 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3340 struct vcpu_vmx *vmx = to_vmx(vcpu);
3342 switch (msr_index) {
3343 case MSR_IA32_VMX_BASIC:
3344 *pdata = vmx->nested.nested_vmx_basic;
3346 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3347 case MSR_IA32_VMX_PINBASED_CTLS:
3348 *pdata = vmx_control_msr(
3349 vmx->nested.nested_vmx_pinbased_ctls_low,
3350 vmx->nested.nested_vmx_pinbased_ctls_high);
3351 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3352 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3354 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3355 case MSR_IA32_VMX_PROCBASED_CTLS:
3356 *pdata = vmx_control_msr(
3357 vmx->nested.nested_vmx_procbased_ctls_low,
3358 vmx->nested.nested_vmx_procbased_ctls_high);
3359 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3360 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3362 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3363 case MSR_IA32_VMX_EXIT_CTLS:
3364 *pdata = vmx_control_msr(
3365 vmx->nested.nested_vmx_exit_ctls_low,
3366 vmx->nested.nested_vmx_exit_ctls_high);
3367 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
3368 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3370 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3371 case MSR_IA32_VMX_ENTRY_CTLS:
3372 *pdata = vmx_control_msr(
3373 vmx->nested.nested_vmx_entry_ctls_low,
3374 vmx->nested.nested_vmx_entry_ctls_high);
3375 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
3376 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3378 case MSR_IA32_VMX_MISC:
3379 *pdata = vmx_control_msr(
3380 vmx->nested.nested_vmx_misc_low,
3381 vmx->nested.nested_vmx_misc_high);
3383 case MSR_IA32_VMX_CR0_FIXED0:
3384 *pdata = vmx->nested.nested_vmx_cr0_fixed0;
3386 case MSR_IA32_VMX_CR0_FIXED1:
3387 *pdata = vmx->nested.nested_vmx_cr0_fixed1;
3389 case MSR_IA32_VMX_CR4_FIXED0:
3390 *pdata = vmx->nested.nested_vmx_cr4_fixed0;
3392 case MSR_IA32_VMX_CR4_FIXED1:
3393 *pdata = vmx->nested.nested_vmx_cr4_fixed1;
3395 case MSR_IA32_VMX_VMCS_ENUM:
3396 *pdata = vmx->nested.nested_vmx_vmcs_enum;
3398 case MSR_IA32_VMX_PROCBASED_CTLS2:
3399 *pdata = vmx_control_msr(
3400 vmx->nested.nested_vmx_secondary_ctls_low,
3401 vmx->nested.nested_vmx_secondary_ctls_high);
3403 case MSR_IA32_VMX_EPT_VPID_CAP:
3404 *pdata = vmx->nested.nested_vmx_ept_caps |
3405 ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3407 case MSR_IA32_VMX_VMFUNC:
3408 *pdata = vmx->nested.nested_vmx_vmfunc_controls;
3417 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3420 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3422 return !(val & ~valid_bits);
3425 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3431 * Reads an msr value (of 'msr_index') into 'pdata'.
3432 * Returns 0 on success, non-0 otherwise.
3433 * Assumes vcpu_load() was already called.
3435 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3437 struct shared_msr_entry *msr;
3439 switch (msr_info->index) {
3440 #ifdef CONFIG_X86_64
3442 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3445 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3447 case MSR_KERNEL_GS_BASE:
3448 vmx_load_host_state(to_vmx(vcpu));
3449 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3453 return kvm_get_msr_common(vcpu, msr_info);
3455 msr_info->data = guest_read_tsc(vcpu);
3457 case MSR_IA32_SPEC_CTRL:
3458 if (!msr_info->host_initiated &&
3459 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3462 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3464 case MSR_IA32_SYSENTER_CS:
3465 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3467 case MSR_IA32_SYSENTER_EIP:
3468 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3470 case MSR_IA32_SYSENTER_ESP:
3471 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3473 case MSR_IA32_BNDCFGS:
3474 if (!kvm_mpx_supported() ||
3475 (!msr_info->host_initiated &&
3476 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3478 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3480 case MSR_IA32_MCG_EXT_CTL:
3481 if (!msr_info->host_initiated &&
3482 !(to_vmx(vcpu)->msr_ia32_feature_control &
3483 FEATURE_CONTROL_LMCE))
3485 msr_info->data = vcpu->arch.mcg_ext_ctl;
3487 case MSR_IA32_FEATURE_CONTROL:
3488 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3490 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3491 if (!nested_vmx_allowed(vcpu))
3493 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3495 if (!vmx_xsaves_supported())
3497 msr_info->data = vcpu->arch.ia32_xss;
3500 if (!msr_info->host_initiated &&
3501 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3503 /* Otherwise falls through */
3505 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3507 msr_info->data = msr->data;
3510 return kvm_get_msr_common(vcpu, msr_info);
3516 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3519 * Writes msr value into into the appropriate "register".
3520 * Returns 0 on success, non-0 otherwise.
3521 * Assumes vcpu_load() was already called.
3523 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3525 struct vcpu_vmx *vmx = to_vmx(vcpu);
3526 struct shared_msr_entry *msr;
3528 u32 msr_index = msr_info->index;
3529 u64 data = msr_info->data;
3531 switch (msr_index) {
3533 ret = kvm_set_msr_common(vcpu, msr_info);
3535 #ifdef CONFIG_X86_64
3537 vmx_segment_cache_clear(vmx);
3538 vmcs_writel(GUEST_FS_BASE, data);
3541 vmx_segment_cache_clear(vmx);
3542 vmcs_writel(GUEST_GS_BASE, data);
3544 case MSR_KERNEL_GS_BASE:
3545 vmx_load_host_state(vmx);
3546 vmx->msr_guest_kernel_gs_base = data;
3549 case MSR_IA32_SYSENTER_CS:
3550 vmcs_write32(GUEST_SYSENTER_CS, data);
3552 case MSR_IA32_SYSENTER_EIP:
3553 vmcs_writel(GUEST_SYSENTER_EIP, data);
3555 case MSR_IA32_SYSENTER_ESP:
3556 vmcs_writel(GUEST_SYSENTER_ESP, data);
3558 case MSR_IA32_BNDCFGS:
3559 if (!kvm_mpx_supported() ||
3560 (!msr_info->host_initiated &&
3561 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
3563 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
3564 (data & MSR_IA32_BNDCFGS_RSVD))
3566 vmcs_write64(GUEST_BNDCFGS, data);
3569 kvm_write_tsc(vcpu, msr_info);
3571 case MSR_IA32_SPEC_CTRL:
3572 if (!msr_info->host_initiated &&
3573 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3576 /* The STIBP bit doesn't fault even if it's not advertised */
3577 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3580 vmx->spec_ctrl = data;
3587 * When it's written (to non-zero) for the first time, pass
3591 * The handling of the MSR bitmap for L2 guests is done in
3592 * nested_vmx_merge_msr_bitmap. We should not touch the
3593 * vmcs02.msr_bitmap here since it gets completely overwritten
3594 * in the merging. We update the vmcs01 here for L1 as well
3595 * since it will end up touching the MSR anyway now.
3597 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3601 case MSR_IA32_PRED_CMD:
3602 if (!msr_info->host_initiated &&
3603 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
3606 if (data & ~PRED_CMD_IBPB)
3612 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3616 * When it's written (to non-zero) for the first time, pass
3620 * The handling of the MSR bitmap for L2 guests is done in
3621 * nested_vmx_merge_msr_bitmap. We should not touch the
3622 * vmcs02.msr_bitmap here since it gets completely overwritten
3625 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3628 case MSR_IA32_CR_PAT:
3629 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3630 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3632 vmcs_write64(GUEST_IA32_PAT, data);
3633 vcpu->arch.pat = data;
3636 ret = kvm_set_msr_common(vcpu, msr_info);
3638 case MSR_IA32_TSC_ADJUST:
3639 ret = kvm_set_msr_common(vcpu, msr_info);
3641 case MSR_IA32_MCG_EXT_CTL:
3642 if ((!msr_info->host_initiated &&
3643 !(to_vmx(vcpu)->msr_ia32_feature_control &
3644 FEATURE_CONTROL_LMCE)) ||
3645 (data & ~MCG_EXT_CTL_LMCE_EN))
3647 vcpu->arch.mcg_ext_ctl = data;
3649 case MSR_IA32_FEATURE_CONTROL:
3650 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3651 (to_vmx(vcpu)->msr_ia32_feature_control &
3652 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3654 vmx->msr_ia32_feature_control = data;
3655 if (msr_info->host_initiated && data == 0)
3656 vmx_leave_nested(vcpu);
3658 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3659 if (!msr_info->host_initiated)
3660 return 1; /* they are read-only */
3661 if (!nested_vmx_allowed(vcpu))
3663 return vmx_set_vmx_msr(vcpu, msr_index, data);
3665 if (!vmx_xsaves_supported())
3668 * The only supported bit as of Skylake is bit 8, but
3669 * it is not supported on KVM.
3673 vcpu->arch.ia32_xss = data;
3674 if (vcpu->arch.ia32_xss != host_xss)
3675 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3676 vcpu->arch.ia32_xss, host_xss, false);
3678 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3681 if (!msr_info->host_initiated &&
3682 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
3684 /* Check reserved bit, higher 32 bits should be zero */
3685 if ((data >> 32) != 0)
3687 /* Otherwise falls through */
3689 msr = find_msr_entry(vmx, msr_index);
3691 u64 old_msr_data = msr->data;
3693 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3695 ret = kvm_set_shared_msr(msr->index, msr->data,
3699 msr->data = old_msr_data;
3703 ret = kvm_set_msr_common(vcpu, msr_info);
3709 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3711 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3714 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3717 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3719 case VCPU_EXREG_PDPTR:
3721 ept_save_pdptrs(vcpu);
3728 static __init int cpu_has_kvm_support(void)
3730 return cpu_has_vmx();
3733 static __init int vmx_disabled_by_bios(void)
3737 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3738 if (msr & FEATURE_CONTROL_LOCKED) {
3739 /* launched w/ TXT and VMX disabled */
3740 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3743 /* launched w/o TXT and VMX only enabled w/ TXT */
3744 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3745 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3746 && !tboot_enabled()) {
3747 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3748 "activate TXT before enabling KVM\n");
3751 /* launched w/o TXT and VMX disabled */
3752 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3753 && !tboot_enabled())
3760 static void kvm_cpu_vmxon(u64 addr)
3762 cr4_set_bits(X86_CR4_VMXE);
3763 intel_pt_handle_vmx(1);
3765 asm volatile (ASM_VMX_VMXON_RAX
3766 : : "a"(&addr), "m"(addr)
3770 static int hardware_enable(void)
3772 int cpu = raw_smp_processor_id();
3773 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3776 if (cr4_read_shadow() & X86_CR4_VMXE)
3779 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3781 test_bits = FEATURE_CONTROL_LOCKED;
3782 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3783 if (tboot_enabled())
3784 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3786 if ((old & test_bits) != test_bits) {
3787 /* enable and lock */
3788 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3790 kvm_cpu_vmxon(phys_addr);
3796 static void vmclear_local_loaded_vmcss(void)
3798 int cpu = raw_smp_processor_id();
3799 struct loaded_vmcs *v, *n;
3801 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3802 loaded_vmcss_on_cpu_link)
3803 __loaded_vmcs_clear(v);
3807 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3810 static void kvm_cpu_vmxoff(void)
3812 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3814 intel_pt_handle_vmx(0);
3815 cr4_clear_bits(X86_CR4_VMXE);
3818 static void hardware_disable(void)
3820 vmclear_local_loaded_vmcss();
3824 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3825 u32 msr, u32 *result)
3827 u32 vmx_msr_low, vmx_msr_high;
3828 u32 ctl = ctl_min | ctl_opt;
3830 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3832 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3833 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
3835 /* Ensure minimum (required) set of control bits are supported. */
3843 static __init bool allow_1_setting(u32 msr, u32 ctl)
3845 u32 vmx_msr_low, vmx_msr_high;
3847 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3848 return vmx_msr_high & ctl;
3851 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3853 u32 vmx_msr_low, vmx_msr_high;
3854 u32 min, opt, min2, opt2;
3855 u32 _pin_based_exec_control = 0;
3856 u32 _cpu_based_exec_control = 0;
3857 u32 _cpu_based_2nd_exec_control = 0;
3858 u32 _vmexit_control = 0;
3859 u32 _vmentry_control = 0;
3861 min = CPU_BASED_HLT_EXITING |
3862 #ifdef CONFIG_X86_64
3863 CPU_BASED_CR8_LOAD_EXITING |
3864 CPU_BASED_CR8_STORE_EXITING |
3866 CPU_BASED_CR3_LOAD_EXITING |
3867 CPU_BASED_CR3_STORE_EXITING |
3868 CPU_BASED_USE_IO_BITMAPS |
3869 CPU_BASED_MOV_DR_EXITING |
3870 CPU_BASED_USE_TSC_OFFSETING |
3871 CPU_BASED_INVLPG_EXITING |
3872 CPU_BASED_RDPMC_EXITING;
3874 if (!kvm_mwait_in_guest())
3875 min |= CPU_BASED_MWAIT_EXITING |
3876 CPU_BASED_MONITOR_EXITING;
3878 opt = CPU_BASED_TPR_SHADOW |
3879 CPU_BASED_USE_MSR_BITMAPS |
3880 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3881 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3882 &_cpu_based_exec_control) < 0)
3884 #ifdef CONFIG_X86_64
3885 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3886 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3887 ~CPU_BASED_CR8_STORE_EXITING;
3889 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3891 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3892 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3893 SECONDARY_EXEC_WBINVD_EXITING |
3894 SECONDARY_EXEC_ENABLE_VPID |
3895 SECONDARY_EXEC_ENABLE_EPT |
3896 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3897 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3898 SECONDARY_EXEC_RDTSCP |
3899 SECONDARY_EXEC_ENABLE_INVPCID |
3900 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3901 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3902 SECONDARY_EXEC_SHADOW_VMCS |
3903 SECONDARY_EXEC_XSAVES |
3904 SECONDARY_EXEC_RDSEED |
3905 SECONDARY_EXEC_RDRAND |
3906 SECONDARY_EXEC_ENABLE_PML |
3907 SECONDARY_EXEC_TSC_SCALING |
3908 SECONDARY_EXEC_ENABLE_VMFUNC;
3909 if (adjust_vmx_controls(min2, opt2,
3910 MSR_IA32_VMX_PROCBASED_CTLS2,
3911 &_cpu_based_2nd_exec_control) < 0)
3914 #ifndef CONFIG_X86_64
3915 if (!(_cpu_based_2nd_exec_control &
3916 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3917 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3920 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3921 _cpu_based_2nd_exec_control &= ~(
3922 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3923 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3924 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3926 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3927 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3929 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3930 CPU_BASED_CR3_STORE_EXITING |
3931 CPU_BASED_INVLPG_EXITING);
3932 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3933 vmx_capability.ept, vmx_capability.vpid);
3936 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3937 #ifdef CONFIG_X86_64
3938 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3940 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3941 VM_EXIT_CLEAR_BNDCFGS;
3942 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3943 &_vmexit_control) < 0)
3946 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3947 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3948 PIN_BASED_VMX_PREEMPTION_TIMER;
3949 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3950 &_pin_based_exec_control) < 0)
3953 if (cpu_has_broken_vmx_preemption_timer())
3954 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3955 if (!(_cpu_based_2nd_exec_control &
3956 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3957 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3959 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3960 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3961 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3962 &_vmentry_control) < 0)
3965 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3967 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3968 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3971 #ifdef CONFIG_X86_64
3972 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3973 if (vmx_msr_high & (1u<<16))
3977 /* Require Write-Back (WB) memory type for VMCS accesses. */
3978 if (((vmx_msr_high >> 18) & 15) != 6)
3981 vmcs_conf->size = vmx_msr_high & 0x1fff;
3982 vmcs_conf->order = get_order(vmcs_conf->size);
3983 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3984 vmcs_conf->revision_id = vmx_msr_low;
3986 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3987 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3988 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3989 vmcs_conf->vmexit_ctrl = _vmexit_control;
3990 vmcs_conf->vmentry_ctrl = _vmentry_control;
3992 cpu_has_load_ia32_efer =
3993 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3994 VM_ENTRY_LOAD_IA32_EFER)
3995 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3996 VM_EXIT_LOAD_IA32_EFER);
3998 cpu_has_load_perf_global_ctrl =
3999 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4000 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4001 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4002 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4005 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4006 * but due to errata below it can't be used. Workaround is to use
4007 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4009 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4014 * BC86,AAY89,BD102 (model 44)
4018 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4019 switch (boot_cpu_data.x86_model) {
4025 cpu_has_load_perf_global_ctrl = false;
4026 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4027 "does not work properly. Using workaround\n");
4034 if (boot_cpu_has(X86_FEATURE_XSAVES))
4035 rdmsrl(MSR_IA32_XSS, host_xss);
4040 static struct vmcs *alloc_vmcs_cpu(int cpu)
4042 int node = cpu_to_node(cpu);
4046 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4049 vmcs = page_address(pages);
4050 memset(vmcs, 0, vmcs_config.size);
4051 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
4055 static void free_vmcs(struct vmcs *vmcs)
4057 free_pages((unsigned long)vmcs, vmcs_config.order);
4061 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4063 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4065 if (!loaded_vmcs->vmcs)
4067 loaded_vmcs_clear(loaded_vmcs);
4068 free_vmcs(loaded_vmcs->vmcs);
4069 loaded_vmcs->vmcs = NULL;
4070 if (loaded_vmcs->msr_bitmap)
4071 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4072 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4075 static struct vmcs *alloc_vmcs(void)
4077 return alloc_vmcs_cpu(raw_smp_processor_id());
4080 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4082 loaded_vmcs->vmcs = alloc_vmcs();
4083 if (!loaded_vmcs->vmcs)
4086 loaded_vmcs->shadow_vmcs = NULL;
4087 loaded_vmcs_init(loaded_vmcs);
4089 if (cpu_has_vmx_msr_bitmap()) {
4090 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4091 if (!loaded_vmcs->msr_bitmap)
4093 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4098 free_loaded_vmcs(loaded_vmcs);
4102 static void free_kvm_area(void)
4106 for_each_possible_cpu(cpu) {
4107 free_vmcs(per_cpu(vmxarea, cpu));
4108 per_cpu(vmxarea, cpu) = NULL;
4112 enum vmcs_field_type {
4113 VMCS_FIELD_TYPE_U16 = 0,
4114 VMCS_FIELD_TYPE_U64 = 1,
4115 VMCS_FIELD_TYPE_U32 = 2,
4116 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
4119 static inline int vmcs_field_type(unsigned long field)
4121 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
4122 return VMCS_FIELD_TYPE_U32;
4123 return (field >> 13) & 0x3 ;
4126 static inline int vmcs_field_readonly(unsigned long field)
4128 return (((field >> 10) & 0x3) == 1);
4131 static void init_vmcs_shadow_fields(void)
4135 /* No checks for read only fields yet */
4137 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4138 switch (shadow_read_write_fields[i]) {
4140 if (!kvm_mpx_supported())
4148 shadow_read_write_fields[j] =
4149 shadow_read_write_fields[i];
4152 max_shadow_read_write_fields = j;
4154 /* shadowed fields guest access without vmexit */
4155 for (i = 0; i < max_shadow_read_write_fields; i++) {
4156 unsigned long field = shadow_read_write_fields[i];
4158 clear_bit(field, vmx_vmwrite_bitmap);
4159 clear_bit(field, vmx_vmread_bitmap);
4160 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64) {
4161 clear_bit(field + 1, vmx_vmwrite_bitmap);
4162 clear_bit(field + 1, vmx_vmread_bitmap);
4165 for (i = 0; i < max_shadow_read_only_fields; i++) {
4166 unsigned long field = shadow_read_only_fields[i];
4168 clear_bit(field, vmx_vmread_bitmap);
4169 if (vmcs_field_type(field) == VMCS_FIELD_TYPE_U64)
4170 clear_bit(field + 1, vmx_vmread_bitmap);
4174 static __init int alloc_kvm_area(void)
4178 for_each_possible_cpu(cpu) {
4181 vmcs = alloc_vmcs_cpu(cpu);
4187 per_cpu(vmxarea, cpu) = vmcs;
4192 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4193 struct kvm_segment *save)
4195 if (!emulate_invalid_guest_state) {
4197 * CS and SS RPL should be equal during guest entry according
4198 * to VMX spec, but in reality it is not always so. Since vcpu
4199 * is in the middle of the transition from real mode to
4200 * protected mode it is safe to assume that RPL 0 is a good
4203 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4204 save->selector &= ~SEGMENT_RPL_MASK;
4205 save->dpl = save->selector & SEGMENT_RPL_MASK;
4208 vmx_set_segment(vcpu, save, seg);
4211 static void enter_pmode(struct kvm_vcpu *vcpu)
4213 unsigned long flags;
4214 struct vcpu_vmx *vmx = to_vmx(vcpu);
4217 * Update real mode segment cache. It may be not up-to-date if sement
4218 * register was written while vcpu was in a guest mode.
4220 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4221 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4222 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4223 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4224 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4225 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4227 vmx->rmode.vm86_active = 0;
4229 vmx_segment_cache_clear(vmx);
4231 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4233 flags = vmcs_readl(GUEST_RFLAGS);
4234 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4235 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4236 vmcs_writel(GUEST_RFLAGS, flags);
4238 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4239 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4241 update_exception_bitmap(vcpu);
4243 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4244 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4245 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4246 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4247 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4248 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4251 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4253 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4254 struct kvm_segment var = *save;
4257 if (seg == VCPU_SREG_CS)
4260 if (!emulate_invalid_guest_state) {
4261 var.selector = var.base >> 4;
4262 var.base = var.base & 0xffff0;
4272 if (save->base & 0xf)
4273 printk_once(KERN_WARNING "kvm: segment base is not "
4274 "paragraph aligned when entering "
4275 "protected mode (seg=%d)", seg);
4278 vmcs_write16(sf->selector, var.selector);
4279 vmcs_writel(sf->base, var.base);
4280 vmcs_write32(sf->limit, var.limit);
4281 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4284 static void enter_rmode(struct kvm_vcpu *vcpu)
4286 unsigned long flags;
4287 struct vcpu_vmx *vmx = to_vmx(vcpu);
4289 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4290 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4291 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4292 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4293 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4294 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4295 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4297 vmx->rmode.vm86_active = 1;
4300 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4301 * vcpu. Warn the user that an update is overdue.
4303 if (!vcpu->kvm->arch.tss_addr)
4304 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4305 "called before entering vcpu\n");
4307 vmx_segment_cache_clear(vmx);
4309 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4310 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4311 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4313 flags = vmcs_readl(GUEST_RFLAGS);
4314 vmx->rmode.save_rflags = flags;
4316 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4318 vmcs_writel(GUEST_RFLAGS, flags);
4319 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4320 update_exception_bitmap(vcpu);
4322 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4323 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4324 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4325 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4326 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4327 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4329 kvm_mmu_reset_context(vcpu);
4332 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4334 struct vcpu_vmx *vmx = to_vmx(vcpu);
4335 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4341 * Force kernel_gs_base reloading before EFER changes, as control
4342 * of this msr depends on is_long_mode().
4344 vmx_load_host_state(to_vmx(vcpu));
4345 vcpu->arch.efer = efer;
4346 if (efer & EFER_LMA) {
4347 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4350 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4352 msr->data = efer & ~EFER_LME;
4357 #ifdef CONFIG_X86_64
4359 static void enter_lmode(struct kvm_vcpu *vcpu)
4363 vmx_segment_cache_clear(to_vmx(vcpu));
4365 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4366 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4367 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4369 vmcs_write32(GUEST_TR_AR_BYTES,
4370 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4371 | VMX_AR_TYPE_BUSY_64_TSS);
4373 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4376 static void exit_lmode(struct kvm_vcpu *vcpu)
4378 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4379 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4384 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
4385 bool invalidate_gpa)
4387 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
4388 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4390 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
4392 vpid_sync_context(vpid);
4396 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
4398 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
4401 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4403 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4405 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4406 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4409 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4411 if (enable_ept && is_paging(vcpu))
4412 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4413 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4416 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4418 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4420 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4421 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4424 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4426 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4428 if (!test_bit(VCPU_EXREG_PDPTR,
4429 (unsigned long *)&vcpu->arch.regs_dirty))
4432 if (is_pae_paging(vcpu)) {
4433 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4434 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4435 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4436 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4440 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4442 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4444 if (is_pae_paging(vcpu)) {
4445 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4446 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4447 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4448 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4451 __set_bit(VCPU_EXREG_PDPTR,
4452 (unsigned long *)&vcpu->arch.regs_avail);
4453 __set_bit(VCPU_EXREG_PDPTR,
4454 (unsigned long *)&vcpu->arch.regs_dirty);
4457 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4459 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4460 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4461 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
4463 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
4464 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
4465 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
4466 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
4468 return fixed_bits_valid(val, fixed0, fixed1);
4471 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
4473 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed0;
4474 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr0_fixed1;
4476 return fixed_bits_valid(val, fixed0, fixed1);
4479 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
4481 u64 fixed0 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed0;
4482 u64 fixed1 = to_vmx(vcpu)->nested.nested_vmx_cr4_fixed1;
4484 return fixed_bits_valid(val, fixed0, fixed1);
4487 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
4488 #define nested_guest_cr4_valid nested_cr4_valid
4489 #define nested_host_cr4_valid nested_cr4_valid
4491 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4493 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4495 struct kvm_vcpu *vcpu)
4497 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4498 vmx_decache_cr3(vcpu);
4499 if (!(cr0 & X86_CR0_PG)) {
4500 /* From paging/starting to nonpaging */
4501 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4502 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4503 (CPU_BASED_CR3_LOAD_EXITING |
4504 CPU_BASED_CR3_STORE_EXITING));
4505 vcpu->arch.cr0 = cr0;
4506 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4507 } else if (!is_paging(vcpu)) {
4508 /* From nonpaging to paging */
4509 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4510 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4511 ~(CPU_BASED_CR3_LOAD_EXITING |
4512 CPU_BASED_CR3_STORE_EXITING));
4513 vcpu->arch.cr0 = cr0;
4514 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4517 if (!(cr0 & X86_CR0_WP))
4518 *hw_cr0 &= ~X86_CR0_WP;
4521 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4523 struct vcpu_vmx *vmx = to_vmx(vcpu);
4524 unsigned long hw_cr0;
4526 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4527 if (enable_unrestricted_guest)
4528 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4530 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4532 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4535 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4539 #ifdef CONFIG_X86_64
4540 if (vcpu->arch.efer & EFER_LME) {
4541 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4543 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4549 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4551 vmcs_writel(CR0_READ_SHADOW, cr0);
4552 vmcs_writel(GUEST_CR0, hw_cr0);
4553 vcpu->arch.cr0 = cr0;
4555 /* depends on vcpu->arch.cr0 to be set to a new value */
4556 vmx->emulation_required = emulation_required(vcpu);
4559 static int get_ept_level(struct kvm_vcpu *vcpu)
4561 /* Nested EPT currently only supports 4-level walks. */
4562 if (is_guest_mode(vcpu) && nested_cpu_has_ept(get_vmcs12(vcpu)))
4564 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
4569 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
4571 u64 eptp = VMX_EPTP_MT_WB;
4573 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
4575 if (enable_ept_ad_bits &&
4576 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
4577 eptp |= VMX_EPTP_AD_ENABLE_BIT;
4578 eptp |= (root_hpa & PAGE_MASK);
4583 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4585 unsigned long guest_cr3;
4590 eptp = construct_eptp(vcpu, cr3);
4591 vmcs_write64(EPT_POINTER, eptp);
4592 if (is_paging(vcpu) || is_guest_mode(vcpu))
4593 guest_cr3 = kvm_read_cr3(vcpu);
4595 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4596 ept_load_pdptrs(vcpu);
4599 vmx_flush_tlb(vcpu, true);
4600 vmcs_writel(GUEST_CR3, guest_cr3);
4603 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4606 * Pass through host's Machine Check Enable value to hw_cr4, which
4607 * is in force while we are in guest mode. Do not let guests control
4608 * this bit, even if host CR4.MCE == 0.
4610 unsigned long hw_cr4 =
4611 (cr4_read_shadow() & X86_CR4_MCE) |
4612 (cr4 & ~X86_CR4_MCE) |
4613 (to_vmx(vcpu)->rmode.vm86_active ?
4614 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4616 if (cr4 & X86_CR4_VMXE) {
4618 * To use VMXON (and later other VMX instructions), a guest
4619 * must first be able to turn on cr4.VMXE (see handle_vmon()).
4620 * So basically the check on whether to allow nested VMX
4623 if (!nested_vmx_allowed(vcpu))
4627 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
4630 vcpu->arch.cr4 = cr4;
4632 if (!is_paging(vcpu)) {
4633 hw_cr4 &= ~X86_CR4_PAE;
4634 hw_cr4 |= X86_CR4_PSE;
4635 } else if (!(cr4 & X86_CR4_PAE)) {
4636 hw_cr4 &= ~X86_CR4_PAE;
4640 if (!enable_unrestricted_guest && !is_paging(vcpu))
4642 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4643 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
4644 * to be manually disabled when guest switches to non-paging
4647 * If !enable_unrestricted_guest, the CPU is always running
4648 * with CR0.PG=1 and CR4 needs to be modified.
4649 * If enable_unrestricted_guest, the CPU automatically
4650 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4652 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4654 vmcs_writel(CR4_READ_SHADOW, cr4);
4655 vmcs_writel(GUEST_CR4, hw_cr4);
4659 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4660 struct kvm_segment *var, int seg)
4662 struct vcpu_vmx *vmx = to_vmx(vcpu);
4665 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4666 *var = vmx->rmode.segs[seg];
4667 if (seg == VCPU_SREG_TR
4668 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4670 var->base = vmx_read_guest_seg_base(vmx, seg);
4671 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4674 var->base = vmx_read_guest_seg_base(vmx, seg);
4675 var->limit = vmx_read_guest_seg_limit(vmx, seg);
4676 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4677 ar = vmx_read_guest_seg_ar(vmx, seg);
4678 var->unusable = (ar >> 16) & 1;
4679 var->type = ar & 15;
4680 var->s = (ar >> 4) & 1;
4681 var->dpl = (ar >> 5) & 3;
4683 * Some userspaces do not preserve unusable property. Since usable
4684 * segment has to be present according to VMX spec we can use present
4685 * property to amend userspace bug by making unusable segment always
4686 * nonpresent. vmx_segment_access_rights() already marks nonpresent
4687 * segment as unusable.
4689 var->present = !var->unusable;
4690 var->avl = (ar >> 12) & 1;
4691 var->l = (ar >> 13) & 1;
4692 var->db = (ar >> 14) & 1;
4693 var->g = (ar >> 15) & 1;
4696 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4698 struct kvm_segment s;
4700 if (to_vmx(vcpu)->rmode.vm86_active) {
4701 vmx_get_segment(vcpu, &s, seg);
4704 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4707 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4709 struct vcpu_vmx *vmx = to_vmx(vcpu);
4711 if (unlikely(vmx->rmode.vm86_active))
4714 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4715 return VMX_AR_DPL(ar);
4719 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4723 if (var->unusable || !var->present)
4726 ar = var->type & 15;
4727 ar |= (var->s & 1) << 4;
4728 ar |= (var->dpl & 3) << 5;
4729 ar |= (var->present & 1) << 7;
4730 ar |= (var->avl & 1) << 12;
4731 ar |= (var->l & 1) << 13;
4732 ar |= (var->db & 1) << 14;
4733 ar |= (var->g & 1) << 15;
4739 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4740 struct kvm_segment *var, int seg)
4742 struct vcpu_vmx *vmx = to_vmx(vcpu);
4743 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4745 vmx_segment_cache_clear(vmx);
4747 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4748 vmx->rmode.segs[seg] = *var;
4749 if (seg == VCPU_SREG_TR)
4750 vmcs_write16(sf->selector, var->selector);
4752 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4756 vmcs_writel(sf->base, var->base);
4757 vmcs_write32(sf->limit, var->limit);
4758 vmcs_write16(sf->selector, var->selector);
4761 * Fix the "Accessed" bit in AR field of segment registers for older
4763 * IA32 arch specifies that at the time of processor reset the
4764 * "Accessed" bit in the AR field of segment registers is 1. And qemu
4765 * is setting it to 0 in the userland code. This causes invalid guest
4766 * state vmexit when "unrestricted guest" mode is turned on.
4767 * Fix for this setup issue in cpu_reset is being pushed in the qemu
4768 * tree. Newer qemu binaries with that qemu fix would not need this
4771 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4772 var->type |= 0x1; /* Accessed */
4774 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4777 vmx->emulation_required = emulation_required(vcpu);
4780 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4782 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4784 *db = (ar >> 14) & 1;
4785 *l = (ar >> 13) & 1;
4788 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4790 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4791 dt->address = vmcs_readl(GUEST_IDTR_BASE);
4794 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4796 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4797 vmcs_writel(GUEST_IDTR_BASE, dt->address);
4800 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4802 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4803 dt->address = vmcs_readl(GUEST_GDTR_BASE);
4806 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4808 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4809 vmcs_writel(GUEST_GDTR_BASE, dt->address);
4812 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4814 struct kvm_segment var;
4817 vmx_get_segment(vcpu, &var, seg);
4819 if (seg == VCPU_SREG_CS)
4821 ar = vmx_segment_access_rights(&var);
4823 if (var.base != (var.selector << 4))
4825 if (var.limit != 0xffff)
4833 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4835 struct kvm_segment cs;
4836 unsigned int cs_rpl;
4838 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4839 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4843 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4847 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4848 if (cs.dpl > cs_rpl)
4851 if (cs.dpl != cs_rpl)
4857 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4861 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4863 struct kvm_segment ss;
4864 unsigned int ss_rpl;
4866 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4867 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4871 if (ss.type != 3 && ss.type != 7)
4875 if (ss.dpl != ss_rpl) /* DPL != RPL */
4883 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4885 struct kvm_segment var;
4888 vmx_get_segment(vcpu, &var, seg);
4889 rpl = var.selector & SEGMENT_RPL_MASK;
4897 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4898 if (var.dpl < rpl) /* DPL < RPL */
4902 /* TODO: Add other members to kvm_segment_field to allow checking for other access
4908 static bool tr_valid(struct kvm_vcpu *vcpu)
4910 struct kvm_segment tr;
4912 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4916 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4918 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4926 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4928 struct kvm_segment ldtr;
4930 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4934 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4944 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4946 struct kvm_segment cs, ss;
4948 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4949 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4951 return ((cs.selector & SEGMENT_RPL_MASK) ==
4952 (ss.selector & SEGMENT_RPL_MASK));
4955 static bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu,
4956 unsigned int port, int size);
4957 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
4958 struct vmcs12 *vmcs12)
4960 unsigned long exit_qualification;
4961 unsigned short port;
4964 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
4965 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
4967 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
4969 port = exit_qualification >> 16;
4970 size = (exit_qualification & 7) + 1;
4972 return nested_vmx_check_io_bitmaps(vcpu, port, size);
4976 * Check if guest state is valid. Returns true if valid, false if
4978 * We assume that registers are always usable
4980 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4982 if (enable_unrestricted_guest)
4985 /* real mode guest state checks */
4986 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4987 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4989 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4991 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4993 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4995 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4997 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5000 /* protected mode guest state checks */
5001 if (!cs_ss_rpl_check(vcpu))
5003 if (!code_segment_valid(vcpu))
5005 if (!stack_segment_valid(vcpu))
5007 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5009 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5011 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5013 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5015 if (!tr_valid(vcpu))
5017 if (!ldtr_valid(vcpu))
5021 * - Add checks on RIP
5022 * - Add checks on RFLAGS
5028 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5030 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5033 static int init_rmode_tss(struct kvm *kvm)
5039 idx = srcu_read_lock(&kvm->srcu);
5040 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
5041 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5044 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5045 r = kvm_write_guest_page(kvm, fn++, &data,
5046 TSS_IOPB_BASE_OFFSET, sizeof(u16));
5049 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5052 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5056 r = kvm_write_guest_page(kvm, fn, &data,
5057 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5060 srcu_read_unlock(&kvm->srcu, idx);
5064 static int init_rmode_identity_map(struct kvm *kvm)
5067 kvm_pfn_t identity_map_pfn;
5073 /* Protect kvm->arch.ept_identity_pagetable_done. */
5074 mutex_lock(&kvm->slots_lock);
5076 if (likely(kvm->arch.ept_identity_pagetable_done))
5079 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
5081 r = alloc_identity_pagetable(kvm);
5085 idx = srcu_read_lock(&kvm->srcu);
5086 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5089 /* Set up identity-mapping pagetable for EPT in real mode */
5090 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5091 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5092 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5093 r = kvm_write_guest_page(kvm, identity_map_pfn,
5094 &tmp, i * sizeof(tmp), sizeof(tmp));
5098 kvm->arch.ept_identity_pagetable_done = true;
5101 srcu_read_unlock(&kvm->srcu, idx);
5104 mutex_unlock(&kvm->slots_lock);
5108 static void seg_setup(int seg)
5110 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5113 vmcs_write16(sf->selector, 0);
5114 vmcs_writel(sf->base, 0);
5115 vmcs_write32(sf->limit, 0xffff);
5117 if (seg == VCPU_SREG_CS)
5118 ar |= 0x08; /* code segment */
5120 vmcs_write32(sf->ar_bytes, ar);
5123 static int alloc_apic_access_page(struct kvm *kvm)
5128 mutex_lock(&kvm->slots_lock);
5129 if (kvm->arch.apic_access_page_done)
5131 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5132 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5136 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5137 if (is_error_page(page)) {
5143 * Do not pin the page in memory, so that memory hot-unplug
5144 * is able to migrate it.
5147 kvm->arch.apic_access_page_done = true;
5149 mutex_unlock(&kvm->slots_lock);
5153 static int alloc_identity_pagetable(struct kvm *kvm)
5155 /* Called with kvm->slots_lock held. */
5159 BUG_ON(kvm->arch.ept_identity_pagetable_done);
5161 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5162 kvm->arch.ept_identity_map_addr, PAGE_SIZE);
5167 static int allocate_vpid(void)
5173 spin_lock(&vmx_vpid_lock);
5174 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5175 if (vpid < VMX_NR_VPIDS)
5176 __set_bit(vpid, vmx_vpid_bitmap);
5179 spin_unlock(&vmx_vpid_lock);
5183 static void free_vpid(int vpid)
5185 if (!enable_vpid || vpid == 0)
5187 spin_lock(&vmx_vpid_lock);
5188 __clear_bit(vpid, vmx_vpid_bitmap);
5189 spin_unlock(&vmx_vpid_lock);
5192 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5195 int f = sizeof(unsigned long);
5197 if (!cpu_has_vmx_msr_bitmap())
5201 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5202 * have the write-low and read-high bitmap offsets the wrong way round.
5203 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5205 if (msr <= 0x1fff) {
5206 if (type & MSR_TYPE_R)
5208 __clear_bit(msr, msr_bitmap + 0x000 / f);
5210 if (type & MSR_TYPE_W)
5212 __clear_bit(msr, msr_bitmap + 0x800 / f);
5214 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5216 if (type & MSR_TYPE_R)
5218 __clear_bit(msr, msr_bitmap + 0x400 / f);
5220 if (type & MSR_TYPE_W)
5222 __clear_bit(msr, msr_bitmap + 0xc00 / f);
5227 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5230 int f = sizeof(unsigned long);
5232 if (!cpu_has_vmx_msr_bitmap())
5236 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5237 * have the write-low and read-high bitmap offsets the wrong way round.
5238 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5240 if (msr <= 0x1fff) {
5241 if (type & MSR_TYPE_R)
5243 __set_bit(msr, msr_bitmap + 0x000 / f);
5245 if (type & MSR_TYPE_W)
5247 __set_bit(msr, msr_bitmap + 0x800 / f);
5249 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5251 if (type & MSR_TYPE_R)
5253 __set_bit(msr, msr_bitmap + 0x400 / f);
5255 if (type & MSR_TYPE_W)
5257 __set_bit(msr, msr_bitmap + 0xc00 / f);
5262 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
5263 u32 msr, int type, bool value)
5266 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
5268 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
5272 * If a msr is allowed by L0, we should check whether it is allowed by L1.
5273 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
5275 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
5276 unsigned long *msr_bitmap_nested,
5279 int f = sizeof(unsigned long);
5281 if (!cpu_has_vmx_msr_bitmap()) {
5287 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5288 * have the write-low and read-high bitmap offsets the wrong way round.
5289 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5291 if (msr <= 0x1fff) {
5292 if (type & MSR_TYPE_R &&
5293 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
5295 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
5297 if (type & MSR_TYPE_W &&
5298 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
5300 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
5302 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5304 if (type & MSR_TYPE_R &&
5305 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
5307 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
5309 if (type & MSR_TYPE_W &&
5310 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
5312 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
5317 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
5321 if (cpu_has_secondary_exec_ctrls() &&
5322 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
5323 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
5324 mode |= MSR_BITMAP_MODE_X2APIC;
5325 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
5326 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
5329 if (is_long_mode(vcpu))
5330 mode |= MSR_BITMAP_MODE_LM;
5335 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5337 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5342 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5343 unsigned word = msr / BITS_PER_LONG;
5344 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5345 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5348 if (mode & MSR_BITMAP_MODE_X2APIC) {
5350 * TPR reads and writes can be virtualized even if virtual interrupt
5351 * delivery is not in use.
5353 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5354 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5355 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5356 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5357 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5362 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5364 struct vcpu_vmx *vmx = to_vmx(vcpu);
5365 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5366 u8 mode = vmx_msr_bitmap_mode(vcpu);
5367 u8 changed = mode ^ vmx->msr_bitmap_mode;
5372 vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5373 !(mode & MSR_BITMAP_MODE_LM));
5375 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5376 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5378 vmx->msr_bitmap_mode = mode;
5381 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
5383 return enable_apicv;
5386 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5388 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5392 * Don't need to mark the APIC access page dirty; it is never
5393 * written to by the CPU during APIC virtualization.
5396 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5397 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5398 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5401 if (nested_cpu_has_posted_intr(vmcs12)) {
5402 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5403 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5408 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5410 struct vcpu_vmx *vmx = to_vmx(vcpu);
5415 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5418 vmx->nested.pi_pending = false;
5419 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5422 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5423 if (max_irr != 256) {
5424 vapic_page = kmap(vmx->nested.virtual_apic_page);
5425 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5426 kunmap(vmx->nested.virtual_apic_page);
5428 status = vmcs_read16(GUEST_INTR_STATUS);
5429 if ((u8)max_irr > ((u8)status & 0xff)) {
5431 status |= (u8)max_irr;
5432 vmcs_write16(GUEST_INTR_STATUS, status);
5436 nested_mark_vmcs12_pages_dirty(vcpu);
5439 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
5443 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
5445 if (vcpu->mode == IN_GUEST_MODE) {
5447 * The vector of interrupt to be delivered to vcpu had
5448 * been set in PIR before this function.
5450 * Following cases will be reached in this block, and
5451 * we always send a notification event in all cases as
5454 * Case 1: vcpu keeps in non-root mode. Sending a
5455 * notification event posts the interrupt to vcpu.
5457 * Case 2: vcpu exits to root mode and is still
5458 * runnable. PIR will be synced to vIRR before the
5459 * next vcpu entry. Sending a notification event in
5460 * this case has no effect, as vcpu is not in root
5463 * Case 3: vcpu exits to root mode and is blocked.
5464 * vcpu_block() has already synced PIR to vIRR and
5465 * never blocks vcpu if vIRR is not cleared. Therefore,
5466 * a blocked vcpu here does not wait for any requested
5467 * interrupts in PIR, and sending a notification event
5468 * which has no effect is safe here.
5471 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
5478 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5481 struct vcpu_vmx *vmx = to_vmx(vcpu);
5483 if (is_guest_mode(vcpu) &&
5484 vector == vmx->nested.posted_intr_nv) {
5486 * If a posted intr is not recognized by hardware,
5487 * we will accomplish it in the next vmentry.
5489 vmx->nested.pi_pending = true;
5490 kvm_make_request(KVM_REQ_EVENT, vcpu);
5491 /* the PIR and ON have been set by L1. */
5492 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
5493 kvm_vcpu_kick(vcpu);
5499 * Send interrupt to vcpu via posted interrupt way.
5500 * 1. If target vcpu is running(non-root mode), send posted interrupt
5501 * notification to vcpu and hardware will sync PIR to vIRR atomically.
5502 * 2. If target vcpu isn't running(root mode), kick it to pick up the
5503 * interrupt from PIR in next vmentry.
5505 static int vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5507 struct vcpu_vmx *vmx = to_vmx(vcpu);
5510 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5514 if (!vcpu->arch.apicv_active)
5517 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5520 /* If a previous notification has sent the IPI, nothing to do. */
5521 if (pi_test_and_set_on(&vmx->pi_desc))
5524 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
5525 kvm_vcpu_kick(vcpu);
5531 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5532 * will not change in the lifetime of the guest.
5533 * Note that host-state that does change is set elsewhere. E.g., host-state
5534 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5536 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5541 unsigned long cr0, cr3, cr4;
5544 WARN_ON(cr0 & X86_CR0_TS);
5545 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
5548 * Save the most likely value for this task's CR3 in the VMCS.
5549 * We can't use __get_current_cr3_fast() because we're not atomic.
5552 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
5553 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
5555 /* Save the most likely value for this task's CR4 in the VMCS. */
5556 cr4 = cr4_read_shadow();
5557 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
5558 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
5560 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
5561 #ifdef CONFIG_X86_64
5563 * Load null selectors, so we can avoid reloading them in
5564 * __vmx_load_host_state(), in case userspace uses the null selectors
5565 * too (the expected case).
5567 vmcs_write16(HOST_DS_SELECTOR, 0);
5568 vmcs_write16(HOST_ES_SELECTOR, 0);
5570 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5571 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5573 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5574 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
5577 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
5578 vmx->host_idt_base = dt.address;
5580 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5582 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5583 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5584 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5585 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
5587 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5588 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5589 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5593 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5595 BUILD_BUG_ON(KVM_CR4_GUEST_OWNED_BITS & ~KVM_POSSIBLE_CR4_GUEST_BITS);
5597 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5599 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5600 if (is_guest_mode(&vmx->vcpu))
5601 vmx->vcpu.arch.cr4_guest_owned_bits &=
5602 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5603 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5606 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5608 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5610 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5611 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5612 /* Enable the preemption timer dynamically */
5613 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5614 return pin_based_exec_ctrl;
5617 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5619 struct vcpu_vmx *vmx = to_vmx(vcpu);
5621 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5622 if (cpu_has_secondary_exec_ctrls()) {
5623 if (kvm_vcpu_apicv_active(vcpu))
5624 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5625 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5626 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5628 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5629 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5630 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5633 if (cpu_has_vmx_msr_bitmap())
5634 vmx_update_msr_bitmap(vcpu);
5637 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5639 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5641 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5642 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5644 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5645 exec_control &= ~CPU_BASED_TPR_SHADOW;
5646 #ifdef CONFIG_X86_64
5647 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5648 CPU_BASED_CR8_LOAD_EXITING;
5652 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5653 CPU_BASED_CR3_LOAD_EXITING |
5654 CPU_BASED_INVLPG_EXITING;
5655 return exec_control;
5658 static bool vmx_rdrand_supported(void)
5660 return vmcs_config.cpu_based_2nd_exec_ctrl &
5661 SECONDARY_EXEC_RDRAND;
5664 static bool vmx_rdseed_supported(void)
5666 return vmcs_config.cpu_based_2nd_exec_ctrl &
5667 SECONDARY_EXEC_RDSEED;
5670 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
5672 struct kvm_vcpu *vcpu = &vmx->vcpu;
5674 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5675 if (!cpu_need_virtualize_apic_accesses(vcpu))
5676 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5678 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5680 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5681 enable_unrestricted_guest = 0;
5682 /* Enable INVPCID for non-ept guests may cause performance regression. */
5683 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5685 if (!enable_unrestricted_guest)
5686 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5688 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5689 if (!kvm_vcpu_apicv_active(vcpu))
5690 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5691 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5692 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5693 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5695 We can NOT enable shadow_vmcs here because we don't have yet
5698 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5701 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5703 if (vmx_xsaves_supported()) {
5704 /* Exposing XSAVES only when XSAVE is exposed */
5705 bool xsaves_enabled =
5706 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
5707 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
5709 if (!xsaves_enabled)
5710 exec_control &= ~SECONDARY_EXEC_XSAVES;
5714 vmx->nested.nested_vmx_secondary_ctls_high |=
5715 SECONDARY_EXEC_XSAVES;
5717 vmx->nested.nested_vmx_secondary_ctls_high &=
5718 ~SECONDARY_EXEC_XSAVES;
5722 if (vmx_rdtscp_supported()) {
5723 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
5724 if (!rdtscp_enabled)
5725 exec_control &= ~SECONDARY_EXEC_RDTSCP;
5729 vmx->nested.nested_vmx_secondary_ctls_high |=
5730 SECONDARY_EXEC_RDTSCP;
5732 vmx->nested.nested_vmx_secondary_ctls_high &=
5733 ~SECONDARY_EXEC_RDTSCP;
5737 if (vmx_invpcid_supported()) {
5738 /* Exposing INVPCID only when PCID is exposed */
5739 bool invpcid_enabled =
5740 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
5741 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
5743 if (!invpcid_enabled) {
5744 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5745 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
5749 if (invpcid_enabled)
5750 vmx->nested.nested_vmx_secondary_ctls_high |=
5751 SECONDARY_EXEC_ENABLE_INVPCID;
5753 vmx->nested.nested_vmx_secondary_ctls_high &=
5754 ~SECONDARY_EXEC_ENABLE_INVPCID;
5758 if (vmx_rdrand_supported()) {
5759 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
5761 exec_control &= ~SECONDARY_EXEC_RDRAND;
5765 vmx->nested.nested_vmx_secondary_ctls_high |=
5766 SECONDARY_EXEC_RDRAND;
5768 vmx->nested.nested_vmx_secondary_ctls_high &=
5769 ~SECONDARY_EXEC_RDRAND;
5773 if (vmx_rdseed_supported()) {
5774 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
5776 exec_control &= ~SECONDARY_EXEC_RDSEED;
5780 vmx->nested.nested_vmx_secondary_ctls_high |=
5781 SECONDARY_EXEC_RDSEED;
5783 vmx->nested.nested_vmx_secondary_ctls_high &=
5784 ~SECONDARY_EXEC_RDSEED;
5788 vmx->secondary_exec_control = exec_control;
5791 static void ept_set_mmio_spte_mask(void)
5794 * EPT Misconfigurations can be generated if the value of bits 2:0
5795 * of an EPT paging-structure entry is 110b (write/execute).
5797 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
5798 VMX_EPT_MISCONFIG_WX_VALUE);
5801 #define VMX_XSS_EXIT_BITMAP 0
5803 * Sets up the vmcs for emulated real mode.
5805 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
5807 #ifdef CONFIG_X86_64
5813 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5814 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5816 if (enable_shadow_vmcs) {
5817 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5818 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5820 if (cpu_has_vmx_msr_bitmap())
5821 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5823 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5826 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5827 vmx->hv_deadline_tsc = -1;
5829 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5831 if (cpu_has_secondary_exec_ctrls()) {
5832 vmx_compute_secondary_exec_control(vmx);
5833 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5834 vmx->secondary_exec_control);
5837 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5838 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5839 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5840 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5841 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5843 vmcs_write16(GUEST_INTR_STATUS, 0);
5845 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5846 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5850 vmcs_write32(PLE_GAP, ple_gap);
5851 vmx->ple_window = ple_window;
5852 vmx->ple_window_dirty = true;
5855 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5856 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5857 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
5859 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
5860 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
5861 vmx_set_constant_host_state(vmx);
5862 #ifdef CONFIG_X86_64
5863 rdmsrl(MSR_FS_BASE, a);
5864 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5865 rdmsrl(MSR_GS_BASE, a);
5866 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5868 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5869 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5872 if (cpu_has_vmx_vmfunc())
5873 vmcs_write64(VM_FUNCTION_CONTROL, 0);
5875 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5876 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5877 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
5878 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5879 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
5881 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5882 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5884 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5885 u32 index = vmx_msr_index[i];
5886 u32 data_low, data_high;
5889 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5891 if (wrmsr_safe(index, data_low, data_high) < 0)
5893 vmx->guest_msrs[j].index = i;
5894 vmx->guest_msrs[j].data = 0;
5895 vmx->guest_msrs[j].mask = -1ull;
5899 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5901 /* 22.2.1, 20.8.1 */
5902 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5904 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
5905 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
5907 set_cr4_guest_host_mask(vmx);
5909 if (vmx_xsaves_supported())
5910 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5913 ASSERT(vmx->pml_pg);
5914 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5915 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5921 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5923 struct vcpu_vmx *vmx = to_vmx(vcpu);
5924 struct msr_data apic_base_msr;
5927 vmx->rmode.vm86_active = 0;
5930 vcpu->arch.microcode_version = 0x100000000ULL;
5931 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5932 kvm_set_cr8(vcpu, 0);
5935 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5936 MSR_IA32_APICBASE_ENABLE;
5937 if (kvm_vcpu_is_reset_bsp(vcpu))
5938 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5939 apic_base_msr.host_initiated = true;
5940 kvm_set_apic_base(vcpu, &apic_base_msr);
5943 vmx_segment_cache_clear(vmx);
5945 seg_setup(VCPU_SREG_CS);
5946 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5947 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5949 seg_setup(VCPU_SREG_DS);
5950 seg_setup(VCPU_SREG_ES);
5951 seg_setup(VCPU_SREG_FS);
5952 seg_setup(VCPU_SREG_GS);
5953 seg_setup(VCPU_SREG_SS);
5955 vmcs_write16(GUEST_TR_SELECTOR, 0);
5956 vmcs_writel(GUEST_TR_BASE, 0);
5957 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5958 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5960 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5961 vmcs_writel(GUEST_LDTR_BASE, 0);
5962 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5963 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5966 vmcs_write32(GUEST_SYSENTER_CS, 0);
5967 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5968 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5969 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5972 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5973 kvm_rip_write(vcpu, 0xfff0);
5975 vmcs_writel(GUEST_GDTR_BASE, 0);
5976 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5978 vmcs_writel(GUEST_IDTR_BASE, 0);
5979 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5981 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5982 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5983 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5987 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
5989 if (cpu_has_vmx_tpr_shadow() && !init_event) {
5990 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5991 if (cpu_need_tpr_shadow(vcpu))
5992 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5993 __pa(vcpu->arch.apic->regs));
5994 vmcs_write32(TPR_THRESHOLD, 0);
5997 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6000 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6002 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6003 vmx->vcpu.arch.cr0 = cr0;
6004 vmx_set_cr0(vcpu, cr0); /* enter rmode */
6005 vmx_set_cr4(vcpu, 0);
6006 vmx_set_efer(vcpu, 0);
6008 update_exception_bitmap(vcpu);
6010 vpid_sync_context(vmx->vpid);
6014 * In nested virtualization, check if L1 asked to exit on external interrupts.
6015 * For most existing hypervisors, this will always return true.
6017 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6019 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6020 PIN_BASED_EXT_INTR_MASK;
6024 * In nested virtualization, check if L1 has set
6025 * VM_EXIT_ACK_INTR_ON_EXIT
6027 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6029 return get_vmcs12(vcpu)->vm_exit_controls &
6030 VM_EXIT_ACK_INTR_ON_EXIT;
6033 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6035 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6036 PIN_BASED_NMI_EXITING;
6039 static void enable_irq_window(struct kvm_vcpu *vcpu)
6041 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6042 CPU_BASED_VIRTUAL_INTR_PENDING);
6045 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6047 if (!cpu_has_virtual_nmis() ||
6048 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6049 enable_irq_window(vcpu);
6053 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6054 CPU_BASED_VIRTUAL_NMI_PENDING);
6057 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6059 struct vcpu_vmx *vmx = to_vmx(vcpu);
6061 int irq = vcpu->arch.interrupt.nr;
6063 trace_kvm_inj_virq(irq);
6065 ++vcpu->stat.irq_injections;
6066 if (vmx->rmode.vm86_active) {
6068 if (vcpu->arch.interrupt.soft)
6069 inc_eip = vcpu->arch.event_exit_inst_len;
6070 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6071 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6074 intr = irq | INTR_INFO_VALID_MASK;
6075 if (vcpu->arch.interrupt.soft) {
6076 intr |= INTR_TYPE_SOFT_INTR;
6077 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6078 vmx->vcpu.arch.event_exit_inst_len);
6080 intr |= INTR_TYPE_EXT_INTR;
6081 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6084 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6086 struct vcpu_vmx *vmx = to_vmx(vcpu);
6088 if (!cpu_has_virtual_nmis()) {
6090 * Tracking the NMI-blocked state in software is built upon
6091 * finding the next open IRQ window. This, in turn, depends on
6092 * well-behaving guests: They have to keep IRQs disabled at
6093 * least as long as the NMI handler runs. Otherwise we may
6094 * cause NMI nesting, maybe breaking the guest. But as this is
6095 * highly unlikely, we can live with the residual risk.
6097 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6098 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6101 ++vcpu->stat.nmi_injections;
6102 vmx->loaded_vmcs->nmi_known_unmasked = false;
6104 if (vmx->rmode.vm86_active) {
6105 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6106 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6110 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6111 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6114 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6116 struct vcpu_vmx *vmx = to_vmx(vcpu);
6119 if (!cpu_has_virtual_nmis())
6120 return vmx->loaded_vmcs->soft_vnmi_blocked;
6121 if (vmx->loaded_vmcs->nmi_known_unmasked)
6123 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6124 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6128 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6130 struct vcpu_vmx *vmx = to_vmx(vcpu);
6132 if (!cpu_has_virtual_nmis()) {
6133 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6134 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6135 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6138 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6140 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6141 GUEST_INTR_STATE_NMI);
6143 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6144 GUEST_INTR_STATE_NMI);
6148 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6150 if (to_vmx(vcpu)->nested.nested_run_pending)
6153 if (!cpu_has_virtual_nmis() &&
6154 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6157 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6158 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6159 | GUEST_INTR_STATE_NMI));
6162 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6164 if (to_vmx(vcpu)->nested.nested_run_pending)
6167 if (is_guest_mode(vcpu) && nested_exit_on_intr(vcpu))
6170 return (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6171 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6172 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6175 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6179 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6183 kvm->arch.tss_addr = addr;
6184 return init_rmode_tss(kvm);
6187 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6192 * Update instruction length as we may reinject the exception
6193 * from user space while in guest debugging mode.
6195 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6196 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6197 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6201 if (vcpu->guest_debug &
6202 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6219 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6220 int vec, u32 err_code)
6223 * Instruction with address size override prefix opcode 0x67
6224 * Cause the #SS fault with 0 error code in VM86 mode.
6226 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6227 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6228 if (vcpu->arch.halt_request) {
6229 vcpu->arch.halt_request = 0;
6230 return kvm_vcpu_halt(vcpu);
6238 * Forward all other exceptions that are valid in real mode.
6239 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
6240 * the required debugging infrastructure rework.
6242 kvm_queue_exception(vcpu, vec);
6247 * Trigger machine check on the host. We assume all the MSRs are already set up
6248 * by the CPU and that we still run on the same CPU as the MCE occurred on.
6249 * We pass a fake environment to the machine check handler because we want
6250 * the guest to be always treated like user space, no matter what context
6251 * it used internally.
6253 static void kvm_machine_check(void)
6255 #if defined(CONFIG_X86_MCE)
6256 struct pt_regs regs = {
6257 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
6258 .flags = X86_EFLAGS_IF,
6261 do_machine_check(®s, 0);
6265 static int handle_machine_check(struct kvm_vcpu *vcpu)
6267 /* already handled by vcpu_run */
6271 static int handle_exception(struct kvm_vcpu *vcpu)
6273 struct vcpu_vmx *vmx = to_vmx(vcpu);
6274 struct kvm_run *kvm_run = vcpu->run;
6275 u32 intr_info, ex_no, error_code;
6276 unsigned long cr2, rip, dr6;
6278 enum emulation_result er;
6280 vect_info = vmx->idt_vectoring_info;
6281 intr_info = vmx->exit_intr_info;
6283 if (is_machine_check(intr_info))
6284 return handle_machine_check(vcpu);
6286 if (is_nmi(intr_info))
6287 return 1; /* already handled by vmx_vcpu_run() */
6289 if (is_invalid_opcode(intr_info)) {
6290 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
6291 if (er == EMULATE_USER_EXIT)
6293 if (er != EMULATE_DONE)
6294 kvm_queue_exception(vcpu, UD_VECTOR);
6299 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
6300 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
6303 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
6304 * MMIO, it is better to report an internal error.
6305 * See the comments in vmx_handle_exit.
6307 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
6308 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
6309 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6310 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
6311 vcpu->run->internal.ndata = 3;
6312 vcpu->run->internal.data[0] = vect_info;
6313 vcpu->run->internal.data[1] = intr_info;
6314 vcpu->run->internal.data[2] = error_code;
6318 if (is_page_fault(intr_info)) {
6319 cr2 = vmcs_readl(EXIT_QUALIFICATION);
6320 /* EPT won't cause page fault directly */
6321 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
6322 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0,
6326 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
6328 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
6329 return handle_rmode_exception(vcpu, ex_no, error_code);
6333 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
6336 dr6 = vmcs_readl(EXIT_QUALIFICATION);
6337 if (!(vcpu->guest_debug &
6338 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
6339 vcpu->arch.dr6 &= ~15;
6340 vcpu->arch.dr6 |= dr6 | DR6_RTM;
6341 if (is_icebp(intr_info))
6342 skip_emulated_instruction(vcpu);
6344 kvm_queue_exception(vcpu, DB_VECTOR);
6347 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
6348 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
6352 * Update instruction length as we may reinject #BP from
6353 * user space while in guest debugging mode. Reading it for
6354 * #DB as well causes no harm, it is not used in that case.
6356 vmx->vcpu.arch.event_exit_inst_len =
6357 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6358 kvm_run->exit_reason = KVM_EXIT_DEBUG;
6359 rip = kvm_rip_read(vcpu);
6360 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
6361 kvm_run->debug.arch.exception = ex_no;
6364 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
6365 kvm_run->ex.exception = ex_no;
6366 kvm_run->ex.error_code = error_code;
6372 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
6374 ++vcpu->stat.irq_exits;
6378 static int handle_triple_fault(struct kvm_vcpu *vcpu)
6380 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
6381 vcpu->mmio_needed = 0;
6385 static int handle_io(struct kvm_vcpu *vcpu)
6387 unsigned long exit_qualification;
6388 int size, in, string, ret;
6391 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6392 string = (exit_qualification & 16) != 0;
6393 in = (exit_qualification & 8) != 0;
6395 ++vcpu->stat.io_exits;
6398 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6400 port = exit_qualification >> 16;
6401 size = (exit_qualification & 7) + 1;
6403 ret = kvm_skip_emulated_instruction(vcpu);
6406 * TODO: we might be squashing a KVM_GUESTDBG_SINGLESTEP-triggered
6407 * KVM_EXIT_DEBUG here.
6409 return kvm_fast_pio_out(vcpu, size, port) && ret;
6413 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
6416 * Patch in the VMCALL instruction:
6418 hypercall[0] = 0x0f;
6419 hypercall[1] = 0x01;
6420 hypercall[2] = 0xc1;
6423 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
6424 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
6426 if (is_guest_mode(vcpu)) {
6427 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6428 unsigned long orig_val = val;
6431 * We get here when L2 changed cr0 in a way that did not change
6432 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6433 * but did change L0 shadowed bits. So we first calculate the
6434 * effective cr0 value that L1 would like to write into the
6435 * hardware. It consists of the L2-owned bits from the new
6436 * value combined with the L1-owned bits from L1's guest_cr0.
6438 val = (val & ~vmcs12->cr0_guest_host_mask) |
6439 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6441 if (!nested_guest_cr0_valid(vcpu, val))
6444 if (kvm_set_cr0(vcpu, val))
6446 vmcs_writel(CR0_READ_SHADOW, orig_val);
6449 if (to_vmx(vcpu)->nested.vmxon &&
6450 !nested_host_cr0_valid(vcpu, val))
6453 return kvm_set_cr0(vcpu, val);
6457 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6459 if (is_guest_mode(vcpu)) {
6460 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6461 unsigned long orig_val = val;
6463 /* analogously to handle_set_cr0 */
6464 val = (val & ~vmcs12->cr4_guest_host_mask) |
6465 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6466 if (kvm_set_cr4(vcpu, val))
6468 vmcs_writel(CR4_READ_SHADOW, orig_val);
6471 return kvm_set_cr4(vcpu, val);
6474 static int handle_cr(struct kvm_vcpu *vcpu)
6476 unsigned long exit_qualification, val;
6482 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6483 cr = exit_qualification & 15;
6484 reg = (exit_qualification >> 8) & 15;
6485 switch ((exit_qualification >> 4) & 3) {
6486 case 0: /* mov to cr */
6487 val = kvm_register_readl(vcpu, reg);
6488 trace_kvm_cr_write(cr, val);
6491 err = handle_set_cr0(vcpu, val);
6492 return kvm_complete_insn_gp(vcpu, err);
6494 err = kvm_set_cr3(vcpu, val);
6495 return kvm_complete_insn_gp(vcpu, err);
6497 err = handle_set_cr4(vcpu, val);
6498 return kvm_complete_insn_gp(vcpu, err);
6500 u8 cr8_prev = kvm_get_cr8(vcpu);
6502 err = kvm_set_cr8(vcpu, cr8);
6503 ret = kvm_complete_insn_gp(vcpu, err);
6504 if (lapic_in_kernel(vcpu))
6506 if (cr8_prev <= cr8)
6509 * TODO: we might be squashing a
6510 * KVM_GUESTDBG_SINGLESTEP-triggered
6511 * KVM_EXIT_DEBUG here.
6513 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6519 WARN_ONCE(1, "Guest should always own CR0.TS");
6520 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6521 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6522 return kvm_skip_emulated_instruction(vcpu);
6523 case 1: /*mov from cr*/
6526 val = kvm_read_cr3(vcpu);
6527 kvm_register_write(vcpu, reg, val);
6528 trace_kvm_cr_read(cr, val);
6529 return kvm_skip_emulated_instruction(vcpu);
6531 val = kvm_get_cr8(vcpu);
6532 kvm_register_write(vcpu, reg, val);
6533 trace_kvm_cr_read(cr, val);
6534 return kvm_skip_emulated_instruction(vcpu);
6538 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6539 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6540 kvm_lmsw(vcpu, val);
6542 return kvm_skip_emulated_instruction(vcpu);
6546 vcpu->run->exit_reason = 0;
6547 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6548 (int)(exit_qualification >> 4) & 3, cr);
6552 static int handle_dr(struct kvm_vcpu *vcpu)
6554 unsigned long exit_qualification;
6557 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6558 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6560 /* First, if DR does not exist, trigger UD */
6561 if (!kvm_require_dr(vcpu, dr))
6564 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6565 if (!kvm_require_cpl(vcpu, 0))
6567 dr7 = vmcs_readl(GUEST_DR7);
6570 * As the vm-exit takes precedence over the debug trap, we
6571 * need to emulate the latter, either for the host or the
6572 * guest debugging itself.
6574 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6575 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6576 vcpu->run->debug.arch.dr7 = dr7;
6577 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6578 vcpu->run->debug.arch.exception = DB_VECTOR;
6579 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6582 vcpu->arch.dr6 &= ~15;
6583 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6584 kvm_queue_exception(vcpu, DB_VECTOR);
6589 if (vcpu->guest_debug == 0) {
6590 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6591 CPU_BASED_MOV_DR_EXITING);
6594 * No more DR vmexits; force a reload of the debug registers
6595 * and reenter on this instruction. The next vmexit will
6596 * retrieve the full state of the debug registers.
6598 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6602 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6603 if (exit_qualification & TYPE_MOV_FROM_DR) {
6606 if (kvm_get_dr(vcpu, dr, &val))
6608 kvm_register_write(vcpu, reg, val);
6610 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6613 return kvm_skip_emulated_instruction(vcpu);
6616 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6618 return vcpu->arch.dr6;
6621 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6625 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6627 get_debugreg(vcpu->arch.db[0], 0);
6628 get_debugreg(vcpu->arch.db[1], 1);
6629 get_debugreg(vcpu->arch.db[2], 2);
6630 get_debugreg(vcpu->arch.db[3], 3);
6631 get_debugreg(vcpu->arch.dr6, 6);
6632 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6634 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6635 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6638 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6640 vmcs_writel(GUEST_DR7, val);
6643 static int handle_cpuid(struct kvm_vcpu *vcpu)
6645 return kvm_emulate_cpuid(vcpu);
6648 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6650 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6651 struct msr_data msr_info;
6653 msr_info.index = ecx;
6654 msr_info.host_initiated = false;
6655 if (vmx_get_msr(vcpu, &msr_info)) {
6656 trace_kvm_msr_read_ex(ecx);
6657 kvm_inject_gp(vcpu, 0);
6661 trace_kvm_msr_read(ecx, msr_info.data);
6663 /* FIXME: handling of bits 32:63 of rax, rdx */
6664 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6665 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6666 return kvm_skip_emulated_instruction(vcpu);
6669 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6671 struct msr_data msr;
6672 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6673 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6674 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6678 msr.host_initiated = false;
6679 if (kvm_set_msr(vcpu, &msr) != 0) {
6680 trace_kvm_msr_write_ex(ecx, data);
6681 kvm_inject_gp(vcpu, 0);
6685 trace_kvm_msr_write(ecx, data);
6686 return kvm_skip_emulated_instruction(vcpu);
6689 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6691 kvm_apic_update_ppr(vcpu);
6695 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6697 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6698 CPU_BASED_VIRTUAL_INTR_PENDING);
6700 kvm_make_request(KVM_REQ_EVENT, vcpu);
6702 ++vcpu->stat.irq_window_exits;
6706 static int handle_halt(struct kvm_vcpu *vcpu)
6708 return kvm_emulate_halt(vcpu);
6711 static int handle_vmcall(struct kvm_vcpu *vcpu)
6713 return kvm_emulate_hypercall(vcpu);
6716 static int handle_invd(struct kvm_vcpu *vcpu)
6718 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6721 static int handle_invlpg(struct kvm_vcpu *vcpu)
6723 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6725 kvm_mmu_invlpg(vcpu, exit_qualification);
6726 return kvm_skip_emulated_instruction(vcpu);
6729 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6733 err = kvm_rdpmc(vcpu);
6734 return kvm_complete_insn_gp(vcpu, err);
6737 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6739 return kvm_emulate_wbinvd(vcpu);
6742 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6744 u64 new_bv = kvm_read_edx_eax(vcpu);
6745 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6747 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6748 return kvm_skip_emulated_instruction(vcpu);
6752 static int handle_xsaves(struct kvm_vcpu *vcpu)
6754 kvm_skip_emulated_instruction(vcpu);
6755 WARN(1, "this should never happen\n");
6759 static int handle_xrstors(struct kvm_vcpu *vcpu)
6761 kvm_skip_emulated_instruction(vcpu);
6762 WARN(1, "this should never happen\n");
6766 static int handle_apic_access(struct kvm_vcpu *vcpu)
6768 if (likely(fasteoi)) {
6769 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6770 int access_type, offset;
6772 access_type = exit_qualification & APIC_ACCESS_TYPE;
6773 offset = exit_qualification & APIC_ACCESS_OFFSET;
6775 * Sane guest uses MOV to write EOI, with written value
6776 * not cared. So make a short-circuit here by avoiding
6777 * heavy instruction emulation.
6779 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6780 (offset == APIC_EOI)) {
6781 kvm_lapic_set_eoi(vcpu);
6782 return kvm_skip_emulated_instruction(vcpu);
6785 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6788 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6790 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6791 int vector = exit_qualification & 0xff;
6793 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6794 kvm_apic_set_eoi_accelerated(vcpu, vector);
6798 static int handle_apic_write(struct kvm_vcpu *vcpu)
6800 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6801 u32 offset = exit_qualification & 0xfff;
6803 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6804 kvm_apic_write_nodecode(vcpu, offset);
6808 static int handle_task_switch(struct kvm_vcpu *vcpu)
6810 struct vcpu_vmx *vmx = to_vmx(vcpu);
6811 unsigned long exit_qualification;
6812 bool has_error_code = false;
6815 int reason, type, idt_v, idt_index;
6817 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6818 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6819 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6821 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6823 reason = (u32)exit_qualification >> 30;
6824 if (reason == TASK_SWITCH_GATE && idt_v) {
6826 case INTR_TYPE_NMI_INTR:
6827 vcpu->arch.nmi_injected = false;
6828 vmx_set_nmi_mask(vcpu, true);
6830 case INTR_TYPE_EXT_INTR:
6831 case INTR_TYPE_SOFT_INTR:
6832 kvm_clear_interrupt_queue(vcpu);
6834 case INTR_TYPE_HARD_EXCEPTION:
6835 if (vmx->idt_vectoring_info &
6836 VECTORING_INFO_DELIVER_CODE_MASK) {
6837 has_error_code = true;
6839 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6842 case INTR_TYPE_SOFT_EXCEPTION:
6843 kvm_clear_exception_queue(vcpu);
6849 tss_selector = exit_qualification;
6851 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6852 type != INTR_TYPE_EXT_INTR &&
6853 type != INTR_TYPE_NMI_INTR))
6854 skip_emulated_instruction(vcpu);
6856 if (kvm_task_switch(vcpu, tss_selector,
6857 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6858 has_error_code, error_code) == EMULATE_FAIL) {
6859 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6860 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6861 vcpu->run->internal.ndata = 0;
6866 * TODO: What about debug traps on tss switch?
6867 * Are we supposed to inject them and update dr6?
6873 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6875 unsigned long exit_qualification;
6879 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6882 * EPT violation happened while executing iret from NMI,
6883 * "blocked by NMI" bit has to be set before next VM entry.
6884 * There are errata that may cause this bit to not be set:
6887 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6888 cpu_has_virtual_nmis() &&
6889 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6890 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6892 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6893 trace_kvm_page_fault(gpa, exit_qualification);
6895 /* Is it a read fault? */
6896 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
6897 ? PFERR_USER_MASK : 0;
6898 /* Is it a write fault? */
6899 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
6900 ? PFERR_WRITE_MASK : 0;
6901 /* Is it a fetch fault? */
6902 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
6903 ? PFERR_FETCH_MASK : 0;
6904 /* ept page table entry is present? */
6905 error_code |= (exit_qualification &
6906 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
6907 EPT_VIOLATION_EXECUTABLE))
6908 ? PFERR_PRESENT_MASK : 0;
6910 error_code |= (exit_qualification & 0x100) != 0 ?
6911 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
6913 vcpu->arch.exit_qualification = exit_qualification;
6914 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6917 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6923 * A nested guest cannot optimize MMIO vmexits, because we have an
6924 * nGPA here instead of the required GPA.
6926 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6927 if (!is_guest_mode(vcpu) &&
6928 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6929 trace_kvm_fast_mmio(gpa);
6931 * Doing kvm_skip_emulated_instruction() depends on undefined
6932 * behavior: Intel's manual doesn't mandate
6933 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
6934 * occurs and while on real hardware it was observed to be set,
6935 * other hypervisors (namely Hyper-V) don't set it, we end up
6936 * advancing IP with some random value. Disable fast mmio when
6937 * running nested and keep it for real hardware in hope that
6938 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
6940 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
6941 return kvm_skip_emulated_instruction(vcpu);
6943 return emulate_instruction(vcpu, EMULTYPE_SKIP) ==
6947 ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6951 /* It is the real ept misconfig */
6954 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6955 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6960 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6962 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6963 CPU_BASED_VIRTUAL_NMI_PENDING);
6964 ++vcpu->stat.nmi_window_exits;
6965 kvm_make_request(KVM_REQ_EVENT, vcpu);
6970 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6972 struct vcpu_vmx *vmx = to_vmx(vcpu);
6973 enum emulation_result err = EMULATE_DONE;
6976 bool intr_window_requested;
6977 unsigned count = 130;
6979 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6980 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6982 while (vmx->emulation_required && count-- != 0) {
6983 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6984 return handle_interrupt_window(&vmx->vcpu);
6986 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
6989 err = emulate_instruction(vcpu, 0);
6991 if (err == EMULATE_USER_EXIT) {
6992 ++vcpu->stat.mmio_exits;
6997 if (err != EMULATE_DONE)
6998 goto emulation_error;
7000 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7001 vcpu->arch.exception.pending)
7002 goto emulation_error;
7004 if (vcpu->arch.halt_request) {
7005 vcpu->arch.halt_request = 0;
7006 ret = kvm_vcpu_halt(vcpu);
7010 if (signal_pending(current))
7020 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7021 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7022 vcpu->run->internal.ndata = 0;
7026 static int __grow_ple_window(int val)
7028 if (ple_window_grow < 1)
7031 val = min(val, ple_window_actual_max);
7033 if (ple_window_grow < ple_window)
7034 val *= ple_window_grow;
7036 val += ple_window_grow;
7041 static int __shrink_ple_window(int val, int modifier, int minimum)
7046 if (modifier < ple_window)
7051 return max(val, minimum);
7054 static void grow_ple_window(struct kvm_vcpu *vcpu)
7056 struct vcpu_vmx *vmx = to_vmx(vcpu);
7057 int old = vmx->ple_window;
7059 vmx->ple_window = __grow_ple_window(old);
7061 if (vmx->ple_window != old)
7062 vmx->ple_window_dirty = true;
7064 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7067 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7069 struct vcpu_vmx *vmx = to_vmx(vcpu);
7070 int old = vmx->ple_window;
7072 vmx->ple_window = __shrink_ple_window(old,
7073 ple_window_shrink, ple_window);
7075 if (vmx->ple_window != old)
7076 vmx->ple_window_dirty = true;
7078 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7082 * ple_window_actual_max is computed to be one grow_ple_window() below
7083 * ple_window_max. (See __grow_ple_window for the reason.)
7084 * This prevents overflows, because ple_window_max is int.
7085 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
7087 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
7089 static void update_ple_window_actual_max(void)
7091 ple_window_actual_max =
7092 __shrink_ple_window(max(ple_window_max, ple_window),
7093 ple_window_grow, INT_MIN);
7097 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7099 static void wakeup_handler(void)
7101 struct kvm_vcpu *vcpu;
7102 int cpu = smp_processor_id();
7104 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7105 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7106 blocked_vcpu_list) {
7107 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7109 if (pi_test_on(pi_desc) == 1)
7110 kvm_vcpu_kick(vcpu);
7112 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7115 void vmx_enable_tdp(void)
7117 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7118 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7119 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7120 0ull, VMX_EPT_EXECUTABLE_MASK,
7121 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7122 VMX_EPT_RWX_MASK, 0ull);
7124 ept_set_mmio_spte_mask();
7128 static __init int hardware_setup(void)
7132 rdmsrl_safe(MSR_EFER, &host_efer);
7134 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7135 kvm_define_shared_msr(i, vmx_msr_index[i]);
7137 for (i = 0; i < VMX_BITMAP_NR; i++) {
7138 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7143 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7144 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7146 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
7148 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
7150 if (setup_vmcs_config(&vmcs_config) < 0) {
7155 if (boot_cpu_has(X86_FEATURE_NX))
7156 kvm_enable_efer_bits(EFER_NX);
7158 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7159 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7162 if (!cpu_has_vmx_shadow_vmcs())
7163 enable_shadow_vmcs = 0;
7164 if (enable_shadow_vmcs)
7165 init_vmcs_shadow_fields();
7167 if (!cpu_has_vmx_ept() ||
7168 !cpu_has_vmx_ept_4levels() ||
7169 !cpu_has_vmx_ept_mt_wb()) {
7171 enable_unrestricted_guest = 0;
7172 enable_ept_ad_bits = 0;
7175 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7176 enable_ept_ad_bits = 0;
7178 if (!cpu_has_vmx_unrestricted_guest())
7179 enable_unrestricted_guest = 0;
7181 if (!cpu_has_vmx_flexpriority())
7182 flexpriority_enabled = 0;
7185 * set_apic_access_page_addr() is used to reload apic access
7186 * page upon invalidation. No need to do anything if not
7187 * using the APIC_ACCESS_ADDR VMCS field.
7189 if (!flexpriority_enabled)
7190 kvm_x86_ops->set_apic_access_page_addr = NULL;
7192 if (!cpu_has_vmx_tpr_shadow())
7193 kvm_x86_ops->update_cr8_intercept = NULL;
7195 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7196 kvm_disable_largepages();
7198 if (!cpu_has_vmx_ple())
7201 if (!cpu_has_vmx_apicv()) {
7203 kvm_x86_ops->sync_pir_to_irr = NULL;
7206 if (cpu_has_vmx_tsc_scaling()) {
7207 kvm_has_tsc_control = true;
7208 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7209 kvm_tsc_scaling_ratio_frac_bits = 48;
7212 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7219 update_ple_window_actual_max();
7222 * Only enable PML when hardware supports PML feature, and both EPT
7223 * and EPT A/D bit features are enabled -- PML depends on them to work.
7225 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7229 kvm_x86_ops->slot_enable_log_dirty = NULL;
7230 kvm_x86_ops->slot_disable_log_dirty = NULL;
7231 kvm_x86_ops->flush_log_dirty = NULL;
7232 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7235 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7238 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7239 cpu_preemption_timer_multi =
7240 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7242 kvm_x86_ops->set_hv_timer = NULL;
7243 kvm_x86_ops->cancel_hv_timer = NULL;
7246 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
7248 kvm_mce_cap_supported |= MCG_LMCE_P;
7250 r = alloc_kvm_area();
7256 for (i = 0; i < VMX_BITMAP_NR; i++)
7257 free_page((unsigned long)vmx_bitmap[i]);
7262 static __exit void hardware_unsetup(void)
7266 for (i = 0; i < VMX_BITMAP_NR; i++)
7267 free_page((unsigned long)vmx_bitmap[i]);
7273 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
7274 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
7276 static int handle_pause(struct kvm_vcpu *vcpu)
7279 grow_ple_window(vcpu);
7282 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
7283 * VM-execution control is ignored if CPL > 0. OTOH, KVM
7284 * never set PAUSE_EXITING and just set PLE if supported,
7285 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
7287 kvm_vcpu_on_spin(vcpu, true);
7288 return kvm_skip_emulated_instruction(vcpu);
7291 static int handle_nop(struct kvm_vcpu *vcpu)
7293 return kvm_skip_emulated_instruction(vcpu);
7296 static int handle_mwait(struct kvm_vcpu *vcpu)
7298 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
7299 return handle_nop(vcpu);
7302 static int handle_invalid_op(struct kvm_vcpu *vcpu)
7304 kvm_queue_exception(vcpu, UD_VECTOR);
7308 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
7313 static int handle_monitor(struct kvm_vcpu *vcpu)
7315 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
7316 return handle_nop(vcpu);
7320 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
7321 * set the success or error code of an emulated VMX instruction, as specified
7322 * by Vol 2B, VMX Instruction Reference, "Conventions".
7324 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
7326 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
7327 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7328 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
7331 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
7333 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7334 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
7335 X86_EFLAGS_SF | X86_EFLAGS_OF))
7339 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
7340 u32 vm_instruction_error)
7342 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
7344 * failValid writes the error number to the current VMCS, which
7345 * can't be done there isn't a current VMCS.
7347 nested_vmx_failInvalid(vcpu);
7350 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
7351 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
7352 X86_EFLAGS_SF | X86_EFLAGS_OF))
7354 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
7356 * We don't need to force a shadow sync because
7357 * VM_INSTRUCTION_ERROR is not shadowed
7361 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
7363 /* TODO: not to reset guest simply here. */
7364 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7365 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
7368 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
7370 struct vcpu_vmx *vmx =
7371 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
7373 vmx->nested.preemption_timer_expired = true;
7374 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
7375 kvm_vcpu_kick(&vmx->vcpu);
7377 return HRTIMER_NORESTART;
7381 * Decode the memory-address operand of a vmx instruction, as recorded on an
7382 * exit caused by such an instruction (run by a guest hypervisor).
7383 * On success, returns 0. When the operand is invalid, returns 1 and throws
7386 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
7387 unsigned long exit_qualification,
7388 u32 vmx_instruction_info, bool wr, gva_t *ret)
7392 struct kvm_segment s;
7395 * According to Vol. 3B, "Information for VM Exits Due to Instruction
7396 * Execution", on an exit, vmx_instruction_info holds most of the
7397 * addressing components of the operand. Only the displacement part
7398 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7399 * For how an actual address is calculated from all these components,
7400 * refer to Vol. 1, "Operand Addressing".
7402 int scaling = vmx_instruction_info & 3;
7403 int addr_size = (vmx_instruction_info >> 7) & 7;
7404 bool is_reg = vmx_instruction_info & (1u << 10);
7405 int seg_reg = (vmx_instruction_info >> 15) & 7;
7406 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7407 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7408 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7409 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7412 kvm_queue_exception(vcpu, UD_VECTOR);
7416 /* Addr = segment_base + offset */
7417 /* offset = base + [index * scale] + displacement */
7418 off = exit_qualification; /* holds the displacement */
7420 off = (gva_t)sign_extend64(off, 31);
7421 else if (addr_size == 0)
7422 off = (gva_t)sign_extend64(off, 15);
7424 off += kvm_register_read(vcpu, base_reg);
7426 off += kvm_register_read(vcpu, index_reg)<<scaling;
7427 vmx_get_segment(vcpu, &s, seg_reg);
7430 * The effective address, i.e. @off, of a memory operand is truncated
7431 * based on the address size of the instruction. Note that this is
7432 * the *effective address*, i.e. the address prior to accounting for
7433 * the segment's base.
7435 if (addr_size == 1) /* 32 bit */
7437 else if (addr_size == 0) /* 16 bit */
7440 /* Checks for #GP/#SS exceptions. */
7442 if (is_long_mode(vcpu)) {
7444 * The virtual/linear address is never truncated in 64-bit
7445 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
7446 * address when using FS/GS with a non-zero base.
7448 *ret = s.base + off;
7450 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7451 * non-canonical form. This is the only check on the memory
7452 * destination for long mode!
7454 exn = is_noncanonical_address(*ret, vcpu);
7455 } else if (is_protmode(vcpu)) {
7457 * When not in long mode, the virtual/linear address is
7458 * unconditionally truncated to 32 bits regardless of the
7461 *ret = (s.base + off) & 0xffffffff;
7463 /* Protected mode: apply checks for segment validity in the
7465 * - segment type check (#GP(0) may be thrown)
7466 * - usability check (#GP(0)/#SS(0))
7467 * - limit check (#GP(0)/#SS(0))
7470 /* #GP(0) if the destination operand is located in a
7471 * read-only data segment or any code segment.
7473 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7475 /* #GP(0) if the source operand is located in an
7476 * execute-only code segment
7478 exn = ((s.type & 0xa) == 8);
7480 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7483 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7485 exn = (s.unusable != 0);
7488 * Protected mode: #GP(0)/#SS(0) if the memory operand is
7489 * outside the segment limit. All CPUs that support VMX ignore
7490 * limit checks for flat segments, i.e. segments with base==0,
7491 * limit==0xffffffff and of type expand-up data or code.
7493 if (!(s.base == 0 && s.limit == 0xffffffff &&
7494 ((s.type & 8) || !(s.type & 4))))
7495 exn = exn || (off + sizeof(u64) > s.limit);
7498 kvm_queue_exception_e(vcpu,
7499 seg_reg == VCPU_SREG_SS ?
7500 SS_VECTOR : GP_VECTOR,
7508 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
7511 struct x86_exception e;
7513 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7514 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7517 if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
7518 kvm_inject_page_fault(vcpu, &e);
7525 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
7527 struct vcpu_vmx *vmx = to_vmx(vcpu);
7528 struct vmcs *shadow_vmcs;
7531 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
7535 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7536 if (!vmx->nested.cached_vmcs12)
7537 goto out_cached_vmcs12;
7539 if (enable_shadow_vmcs) {
7540 shadow_vmcs = alloc_vmcs();
7542 goto out_shadow_vmcs;
7543 /* mark vmcs as shadow */
7544 shadow_vmcs->revision_id |= (1u << 31);
7545 /* init shadow vmcs */
7546 vmcs_clear(shadow_vmcs);
7547 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7550 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7551 HRTIMER_MODE_REL_PINNED);
7552 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7554 vmx->nested.vpid02 = allocate_vpid();
7556 vmx->nested.vmxon = true;
7560 kfree(vmx->nested.cached_vmcs12);
7563 free_loaded_vmcs(&vmx->nested.vmcs02);
7570 * Emulate the VMXON instruction.
7571 * Currently, we just remember that VMX is active, and do not save or even
7572 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7573 * do not currently need to store anything in that guest-allocated memory
7574 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7575 * argument is different from the VMXON pointer (which the spec says they do).
7577 static int handle_vmon(struct kvm_vcpu *vcpu)
7582 struct vcpu_vmx *vmx = to_vmx(vcpu);
7583 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7584 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7587 * The Intel VMX Instruction Reference lists a bunch of bits that are
7588 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
7589 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
7590 * Otherwise, we should fail with #UD. But most faulting conditions
7591 * have already been checked by hardware, prior to the VM-exit for
7592 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
7593 * that bit set to 1 in non-root mode.
7595 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
7596 kvm_queue_exception(vcpu, UD_VECTOR);
7600 /* CPL=0 must be checked manually. */
7601 if (vmx_get_cpl(vcpu)) {
7602 kvm_inject_gp(vcpu, 0);
7606 if (vmx->nested.vmxon) {
7607 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7608 return kvm_skip_emulated_instruction(vcpu);
7611 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7612 != VMXON_NEEDED_FEATURES) {
7613 kvm_inject_gp(vcpu, 0);
7617 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7622 * The first 4 bytes of VMXON region contain the supported
7623 * VMCS revision identifier
7625 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
7626 * which replaces physical address width with 32
7628 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7629 nested_vmx_failInvalid(vcpu);
7630 return kvm_skip_emulated_instruction(vcpu);
7633 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
7634 if (is_error_page(page)) {
7635 nested_vmx_failInvalid(vcpu);
7636 return kvm_skip_emulated_instruction(vcpu);
7638 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7640 kvm_release_page_clean(page);
7641 nested_vmx_failInvalid(vcpu);
7642 return kvm_skip_emulated_instruction(vcpu);
7645 kvm_release_page_clean(page);
7647 vmx->nested.vmxon_ptr = vmptr;
7648 ret = enter_vmx_operation(vcpu);
7652 nested_vmx_succeed(vcpu);
7653 return kvm_skip_emulated_instruction(vcpu);
7657 * Intel's VMX Instruction Reference specifies a common set of prerequisites
7658 * for running VMX instructions (except VMXON, whose prerequisites are
7659 * slightly different). It also specifies what exception to inject otherwise.
7660 * Note that many of these exceptions have priority over VM exits, so they
7661 * don't have to be checked again here.
7663 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7665 if (vmx_get_cpl(vcpu)) {
7666 kvm_inject_gp(vcpu, 0);
7670 if (!to_vmx(vcpu)->nested.vmxon) {
7671 kvm_queue_exception(vcpu, UD_VECTOR);
7677 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
7679 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
7680 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7681 vmx->nested.sync_shadow_vmcs = false;
7684 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7686 if (vmx->nested.current_vmptr == -1ull)
7689 if (enable_shadow_vmcs) {
7690 /* copy to memory all shadowed fields in case
7691 they were modified */
7692 copy_shadow_to_vmcs12(vmx);
7693 vmx_disable_shadow_vmcs(vmx);
7695 vmx->nested.posted_intr_nv = -1;
7697 /* Flush VMCS12 to guest memory */
7698 kvm_vcpu_write_guest_page(&vmx->vcpu,
7699 vmx->nested.current_vmptr >> PAGE_SHIFT,
7700 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
7702 vmx->nested.current_vmptr = -1ull;
7706 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7707 * just stops using VMX.
7709 static void free_nested(struct vcpu_vmx *vmx)
7711 if (!vmx->nested.vmxon)
7714 hrtimer_cancel(&vmx->nested.preemption_timer);
7715 vmx->nested.vmxon = false;
7716 free_vpid(vmx->nested.vpid02);
7717 vmx->nested.posted_intr_nv = -1;
7718 vmx->nested.current_vmptr = -1ull;
7719 if (enable_shadow_vmcs) {
7720 vmx_disable_shadow_vmcs(vmx);
7721 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7722 free_vmcs(vmx->vmcs01.shadow_vmcs);
7723 vmx->vmcs01.shadow_vmcs = NULL;
7725 kfree(vmx->nested.cached_vmcs12);
7726 /* Unpin physical memory we referred to in the vmcs02 */
7727 if (vmx->nested.apic_access_page) {
7728 kvm_release_page_dirty(vmx->nested.apic_access_page);
7729 vmx->nested.apic_access_page = NULL;
7731 if (vmx->nested.virtual_apic_page) {
7732 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
7733 vmx->nested.virtual_apic_page = NULL;
7735 if (vmx->nested.pi_desc_page) {
7736 kunmap(vmx->nested.pi_desc_page);
7737 kvm_release_page_dirty(vmx->nested.pi_desc_page);
7738 vmx->nested.pi_desc_page = NULL;
7739 vmx->nested.pi_desc = NULL;
7742 free_loaded_vmcs(&vmx->nested.vmcs02);
7745 /* Emulate the VMXOFF instruction */
7746 static int handle_vmoff(struct kvm_vcpu *vcpu)
7748 if (!nested_vmx_check_permission(vcpu))
7750 free_nested(to_vmx(vcpu));
7751 nested_vmx_succeed(vcpu);
7752 return kvm_skip_emulated_instruction(vcpu);
7755 /* Emulate the VMCLEAR instruction */
7756 static int handle_vmclear(struct kvm_vcpu *vcpu)
7758 struct vcpu_vmx *vmx = to_vmx(vcpu);
7762 if (!nested_vmx_check_permission(vcpu))
7765 if (nested_vmx_get_vmptr(vcpu, &vmptr))
7768 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
7769 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
7770 return kvm_skip_emulated_instruction(vcpu);
7773 if (vmptr == vmx->nested.vmxon_ptr) {
7774 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
7775 return kvm_skip_emulated_instruction(vcpu);
7778 if (vmptr == vmx->nested.current_vmptr)
7779 nested_release_vmcs12(vmx);
7781 kvm_vcpu_write_guest(vcpu,
7782 vmptr + offsetof(struct vmcs12, launch_state),
7783 &zero, sizeof(zero));
7785 nested_vmx_succeed(vcpu);
7786 return kvm_skip_emulated_instruction(vcpu);
7789 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7791 /* Emulate the VMLAUNCH instruction */
7792 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7794 return nested_vmx_run(vcpu, true);
7797 /* Emulate the VMRESUME instruction */
7798 static int handle_vmresume(struct kvm_vcpu *vcpu)
7801 return nested_vmx_run(vcpu, false);
7805 * Read a vmcs12 field. Since these can have varying lengths and we return
7806 * one type, we chose the biggest type (u64) and zero-extend the return value
7807 * to that size. Note that the caller, handle_vmread, might need to use only
7808 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7809 * 64-bit fields are to be returned).
7811 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7812 unsigned long field, u64 *ret)
7814 short offset = vmcs_field_to_offset(field);
7820 p = ((char *)(get_vmcs12(vcpu))) + offset;
7822 switch (vmcs_field_type(field)) {
7823 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7824 *ret = *((natural_width *)p);
7826 case VMCS_FIELD_TYPE_U16:
7829 case VMCS_FIELD_TYPE_U32:
7832 case VMCS_FIELD_TYPE_U64:
7842 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7843 unsigned long field, u64 field_value){
7844 short offset = vmcs_field_to_offset(field);
7845 char *p = ((char *) get_vmcs12(vcpu)) + offset;
7849 switch (vmcs_field_type(field)) {
7850 case VMCS_FIELD_TYPE_U16:
7851 *(u16 *)p = field_value;
7853 case VMCS_FIELD_TYPE_U32:
7854 *(u32 *)p = field_value;
7856 case VMCS_FIELD_TYPE_U64:
7857 *(u64 *)p = field_value;
7859 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7860 *(natural_width *)p = field_value;
7869 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7872 unsigned long field;
7874 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7875 const unsigned long *fields = shadow_read_write_fields;
7876 const int num_fields = max_shadow_read_write_fields;
7878 if (WARN_ON(!shadow_vmcs))
7883 vmcs_load(shadow_vmcs);
7885 for (i = 0; i < num_fields; i++) {
7887 switch (vmcs_field_type(field)) {
7888 case VMCS_FIELD_TYPE_U16:
7889 field_value = vmcs_read16(field);
7891 case VMCS_FIELD_TYPE_U32:
7892 field_value = vmcs_read32(field);
7894 case VMCS_FIELD_TYPE_U64:
7895 field_value = vmcs_read64(field);
7897 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7898 field_value = vmcs_readl(field);
7904 vmcs12_write_any(&vmx->vcpu, field, field_value);
7907 vmcs_clear(shadow_vmcs);
7908 vmcs_load(vmx->loaded_vmcs->vmcs);
7913 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7915 const unsigned long *fields[] = {
7916 shadow_read_write_fields,
7917 shadow_read_only_fields
7919 const int max_fields[] = {
7920 max_shadow_read_write_fields,
7921 max_shadow_read_only_fields
7924 unsigned long field;
7925 u64 field_value = 0;
7926 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7928 if (WARN_ON(!shadow_vmcs))
7931 vmcs_load(shadow_vmcs);
7933 for (q = 0; q < ARRAY_SIZE(fields); q++) {
7934 for (i = 0; i < max_fields[q]; i++) {
7935 field = fields[q][i];
7936 vmcs12_read_any(&vmx->vcpu, field, &field_value);
7938 switch (vmcs_field_type(field)) {
7939 case VMCS_FIELD_TYPE_U16:
7940 vmcs_write16(field, (u16)field_value);
7942 case VMCS_FIELD_TYPE_U32:
7943 vmcs_write32(field, (u32)field_value);
7945 case VMCS_FIELD_TYPE_U64:
7946 vmcs_write64(field, (u64)field_value);
7948 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7949 vmcs_writel(field, (long)field_value);
7958 vmcs_clear(shadow_vmcs);
7959 vmcs_load(vmx->loaded_vmcs->vmcs);
7963 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7964 * used before) all generate the same failure when it is missing.
7966 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7968 struct vcpu_vmx *vmx = to_vmx(vcpu);
7969 if (vmx->nested.current_vmptr == -1ull) {
7970 nested_vmx_failInvalid(vcpu);
7976 static int handle_vmread(struct kvm_vcpu *vcpu)
7978 unsigned long field;
7980 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7981 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7983 struct x86_exception e;
7985 if (!nested_vmx_check_permission(vcpu))
7988 if (!nested_vmx_check_vmcs12(vcpu))
7989 return kvm_skip_emulated_instruction(vcpu);
7991 /* Decode instruction info and find the field to read */
7992 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7993 /* Read the field, zero-extended to a u64 field_value */
7994 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7995 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7996 return kvm_skip_emulated_instruction(vcpu);
7999 * Now copy part of this value to register or memory, as requested.
8000 * Note that the number of bits actually copied is 32 or 64 depending
8001 * on the guest's mode (32 or 64 bit), not on the given field's length.
8003 if (vmx_instruction_info & (1u << 10)) {
8004 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8007 if (get_vmx_mem_address(vcpu, exit_qualification,
8008 vmx_instruction_info, true, &gva))
8010 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
8011 if (kvm_write_guest_virt_system(vcpu, gva, &field_value,
8012 (is_long_mode(vcpu) ? 8 : 4),
8014 kvm_inject_page_fault(vcpu, &e);
8019 nested_vmx_succeed(vcpu);
8020 return kvm_skip_emulated_instruction(vcpu);
8024 static int handle_vmwrite(struct kvm_vcpu *vcpu)
8026 unsigned long field;
8028 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8029 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8030 /* The value to write might be 32 or 64 bits, depending on L1's long
8031 * mode, and eventually we need to write that into a field of several
8032 * possible lengths. The code below first zero-extends the value to 64
8033 * bit (field_value), and then copies only the appropriate number of
8034 * bits into the vmcs12 field.
8036 u64 field_value = 0;
8037 struct x86_exception e;
8039 if (!nested_vmx_check_permission(vcpu))
8042 if (!nested_vmx_check_vmcs12(vcpu))
8043 return kvm_skip_emulated_instruction(vcpu);
8045 if (vmx_instruction_info & (1u << 10))
8046 field_value = kvm_register_readl(vcpu,
8047 (((vmx_instruction_info) >> 3) & 0xf));
8049 if (get_vmx_mem_address(vcpu, exit_qualification,
8050 vmx_instruction_info, false, &gva))
8052 if (kvm_read_guest_virt(vcpu, gva, &field_value,
8053 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8054 kvm_inject_page_fault(vcpu, &e);
8060 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8061 if (vmcs_field_readonly(field)) {
8062 nested_vmx_failValid(vcpu,
8063 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8064 return kvm_skip_emulated_instruction(vcpu);
8067 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
8068 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8069 return kvm_skip_emulated_instruction(vcpu);
8072 nested_vmx_succeed(vcpu);
8073 return kvm_skip_emulated_instruction(vcpu);
8076 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8078 vmx->nested.current_vmptr = vmptr;
8079 if (enable_shadow_vmcs) {
8080 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
8081 SECONDARY_EXEC_SHADOW_VMCS);
8082 vmcs_write64(VMCS_LINK_POINTER,
8083 __pa(vmx->vmcs01.shadow_vmcs));
8084 vmx->nested.sync_shadow_vmcs = true;
8088 /* Emulate the VMPTRLD instruction */
8089 static int handle_vmptrld(struct kvm_vcpu *vcpu)
8091 struct vcpu_vmx *vmx = to_vmx(vcpu);
8094 if (!nested_vmx_check_permission(vcpu))
8097 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8100 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8101 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
8102 return kvm_skip_emulated_instruction(vcpu);
8105 if (vmptr == vmx->nested.vmxon_ptr) {
8106 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
8107 return kvm_skip_emulated_instruction(vcpu);
8110 if (vmx->nested.current_vmptr != vmptr) {
8111 struct vmcs12 *new_vmcs12;
8113 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8114 if (is_error_page(page)) {
8115 nested_vmx_failInvalid(vcpu);
8116 return kvm_skip_emulated_instruction(vcpu);
8118 new_vmcs12 = kmap(page);
8119 if (new_vmcs12->revision_id != VMCS12_REVISION) {
8121 kvm_release_page_clean(page);
8122 nested_vmx_failValid(vcpu,
8123 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8124 return kvm_skip_emulated_instruction(vcpu);
8127 nested_release_vmcs12(vmx);
8129 * Load VMCS12 from guest memory since it is not already
8132 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
8134 kvm_release_page_clean(page);
8136 set_current_vmptr(vmx, vmptr);
8139 nested_vmx_succeed(vcpu);
8140 return kvm_skip_emulated_instruction(vcpu);
8143 /* Emulate the VMPTRST instruction */
8144 static int handle_vmptrst(struct kvm_vcpu *vcpu)
8146 unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
8147 u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8148 gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
8149 struct x86_exception e;
8152 if (!nested_vmx_check_permission(vcpu))
8155 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
8157 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
8158 if (kvm_write_guest_virt_system(vcpu, gva, (void *)¤t_vmptr,
8159 sizeof(gpa_t), &e)) {
8160 kvm_inject_page_fault(vcpu, &e);
8163 nested_vmx_succeed(vcpu);
8164 return kvm_skip_emulated_instruction(vcpu);
8167 /* Emulate the INVEPT instruction */
8168 static int handle_invept(struct kvm_vcpu *vcpu)
8170 struct vcpu_vmx *vmx = to_vmx(vcpu);
8171 u32 vmx_instruction_info, types;
8174 struct x86_exception e;
8179 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
8180 SECONDARY_EXEC_ENABLE_EPT) ||
8181 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
8182 kvm_queue_exception(vcpu, UD_VECTOR);
8186 if (!nested_vmx_check_permission(vcpu))
8189 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8190 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8192 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
8194 if (type >= 32 || !(types & (1 << type))) {
8195 nested_vmx_failValid(vcpu,
8196 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8197 return kvm_skip_emulated_instruction(vcpu);
8200 /* According to the Intel VMX instruction reference, the memory
8201 * operand is read even if it isn't needed (e.g., for type==global)
8203 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8204 vmx_instruction_info, false, &gva))
8206 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8207 kvm_inject_page_fault(vcpu, &e);
8212 case VMX_EPT_EXTENT_GLOBAL:
8214 * TODO: track mappings and invalidate
8215 * single context requests appropriately
8217 case VMX_EPT_EXTENT_CONTEXT:
8218 kvm_mmu_sync_roots(vcpu);
8219 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
8220 nested_vmx_succeed(vcpu);
8227 return kvm_skip_emulated_instruction(vcpu);
8230 static int handle_invvpid(struct kvm_vcpu *vcpu)
8232 struct vcpu_vmx *vmx = to_vmx(vcpu);
8233 u32 vmx_instruction_info;
8234 unsigned long type, types;
8236 struct x86_exception e;
8242 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
8243 SECONDARY_EXEC_ENABLE_VPID) ||
8244 !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
8245 kvm_queue_exception(vcpu, UD_VECTOR);
8249 if (!nested_vmx_check_permission(vcpu))
8252 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8253 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
8255 types = (vmx->nested.nested_vmx_vpid_caps &
8256 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
8258 if (type >= 32 || !(types & (1 << type))) {
8259 nested_vmx_failValid(vcpu,
8260 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8261 return kvm_skip_emulated_instruction(vcpu);
8264 /* according to the intel vmx instruction reference, the memory
8265 * operand is read even if it isn't needed (e.g., for type==global)
8267 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8268 vmx_instruction_info, false, &gva))
8270 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
8271 kvm_inject_page_fault(vcpu, &e);
8274 if (operand.vpid >> 16) {
8275 nested_vmx_failValid(vcpu,
8276 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8277 return kvm_skip_emulated_instruction(vcpu);
8281 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
8282 if (is_noncanonical_address(operand.gla, vcpu)) {
8283 nested_vmx_failValid(vcpu,
8284 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8285 return kvm_skip_emulated_instruction(vcpu);
8288 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
8289 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
8290 if (!operand.vpid) {
8291 nested_vmx_failValid(vcpu,
8292 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
8293 return kvm_skip_emulated_instruction(vcpu);
8296 case VMX_VPID_EXTENT_ALL_CONTEXT:
8300 return kvm_skip_emulated_instruction(vcpu);
8303 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
8304 nested_vmx_succeed(vcpu);
8306 return kvm_skip_emulated_instruction(vcpu);
8309 static int handle_pml_full(struct kvm_vcpu *vcpu)
8311 unsigned long exit_qualification;
8313 trace_kvm_pml_full(vcpu->vcpu_id);
8315 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8318 * PML buffer FULL happened while executing iret from NMI,
8319 * "blocked by NMI" bit has to be set before next VM entry.
8321 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
8322 cpu_has_virtual_nmis() &&
8323 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
8324 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
8325 GUEST_INTR_STATE_NMI);
8328 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
8329 * here.., and there's no userspace involvement needed for PML.
8334 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
8336 kvm_lapic_expired_hv_timer(vcpu);
8340 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
8342 struct vcpu_vmx *vmx = to_vmx(vcpu);
8343 int maxphyaddr = cpuid_maxphyaddr(vcpu);
8345 /* Check for memory type validity */
8346 switch (address & VMX_EPTP_MT_MASK) {
8347 case VMX_EPTP_MT_UC:
8348 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_UC_BIT))
8351 case VMX_EPTP_MT_WB:
8352 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPTP_WB_BIT))
8359 /* only 4 levels page-walk length are valid */
8360 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
8363 /* Reserved bits should not be set */
8364 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
8367 /* AD, if set, should be supported */
8368 if (address & VMX_EPTP_AD_ENABLE_BIT) {
8369 if (!(vmx->nested.nested_vmx_ept_caps & VMX_EPT_AD_BIT))
8376 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
8377 struct vmcs12 *vmcs12)
8379 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
8381 bool accessed_dirty;
8382 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
8384 if (!nested_cpu_has_eptp_switching(vmcs12) ||
8385 !nested_cpu_has_ept(vmcs12))
8388 if (index >= VMFUNC_EPTP_ENTRIES)
8392 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
8393 &address, index * 8, 8))
8396 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
8399 * If the (L2) guest does a vmfunc to the currently
8400 * active ept pointer, we don't have to do anything else
8402 if (vmcs12->ept_pointer != address) {
8403 if (!valid_ept_address(vcpu, address))
8406 kvm_mmu_unload(vcpu);
8407 mmu->ept_ad = accessed_dirty;
8408 mmu->base_role.ad_disabled = !accessed_dirty;
8409 vmcs12->ept_pointer = address;
8411 * TODO: Check what's the correct approach in case
8412 * mmu reload fails. Currently, we just let the next
8413 * reload potentially fail
8415 kvm_mmu_reload(vcpu);
8421 static int handle_vmfunc(struct kvm_vcpu *vcpu)
8423 struct vcpu_vmx *vmx = to_vmx(vcpu);
8424 struct vmcs12 *vmcs12;
8425 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
8428 * VMFUNC is only supported for nested guests, but we always enable the
8429 * secondary control for simplicity; for non-nested mode, fake that we
8430 * didn't by injecting #UD.
8432 if (!is_guest_mode(vcpu)) {
8433 kvm_queue_exception(vcpu, UD_VECTOR);
8437 vmcs12 = get_vmcs12(vcpu);
8438 if ((vmcs12->vm_function_control & (1 << function)) == 0)
8443 if (nested_vmx_eptp_switching(vcpu, vmcs12))
8449 return kvm_skip_emulated_instruction(vcpu);
8452 nested_vmx_vmexit(vcpu, vmx->exit_reason,
8453 vmcs_read32(VM_EXIT_INTR_INFO),
8454 vmcs_readl(EXIT_QUALIFICATION));
8459 * The exit handlers return 1 if the exit was handled fully and guest execution
8460 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
8461 * to be done to userspace and return 0.
8463 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
8464 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
8465 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
8466 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
8467 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
8468 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
8469 [EXIT_REASON_CR_ACCESS] = handle_cr,
8470 [EXIT_REASON_DR_ACCESS] = handle_dr,
8471 [EXIT_REASON_CPUID] = handle_cpuid,
8472 [EXIT_REASON_MSR_READ] = handle_rdmsr,
8473 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
8474 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
8475 [EXIT_REASON_HLT] = handle_halt,
8476 [EXIT_REASON_INVD] = handle_invd,
8477 [EXIT_REASON_INVLPG] = handle_invlpg,
8478 [EXIT_REASON_RDPMC] = handle_rdpmc,
8479 [EXIT_REASON_VMCALL] = handle_vmcall,
8480 [EXIT_REASON_VMCLEAR] = handle_vmclear,
8481 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
8482 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
8483 [EXIT_REASON_VMPTRST] = handle_vmptrst,
8484 [EXIT_REASON_VMREAD] = handle_vmread,
8485 [EXIT_REASON_VMRESUME] = handle_vmresume,
8486 [EXIT_REASON_VMWRITE] = handle_vmwrite,
8487 [EXIT_REASON_VMOFF] = handle_vmoff,
8488 [EXIT_REASON_VMON] = handle_vmon,
8489 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
8490 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
8491 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
8492 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
8493 [EXIT_REASON_WBINVD] = handle_wbinvd,
8494 [EXIT_REASON_XSETBV] = handle_xsetbv,
8495 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
8496 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
8497 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
8498 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
8499 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
8500 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
8501 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
8502 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
8503 [EXIT_REASON_INVEPT] = handle_invept,
8504 [EXIT_REASON_INVVPID] = handle_invvpid,
8505 [EXIT_REASON_RDRAND] = handle_invalid_op,
8506 [EXIT_REASON_RDSEED] = handle_invalid_op,
8507 [EXIT_REASON_XSAVES] = handle_xsaves,
8508 [EXIT_REASON_XRSTORS] = handle_xrstors,
8509 [EXIT_REASON_PML_FULL] = handle_pml_full,
8510 [EXIT_REASON_VMFUNC] = handle_vmfunc,
8511 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
8514 static const int kvm_vmx_max_exit_handlers =
8515 ARRAY_SIZE(kvm_vmx_exit_handlers);
8518 * Return true if an IO instruction with the specified port and size should cause
8519 * a VM-exit into L1.
8521 bool nested_vmx_check_io_bitmaps(struct kvm_vcpu *vcpu, unsigned int port,
8524 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8525 gpa_t bitmap, last_bitmap;
8528 last_bitmap = (gpa_t)-1;
8533 bitmap = vmcs12->io_bitmap_a;
8534 else if (port < 0x10000)
8535 bitmap = vmcs12->io_bitmap_b;
8538 bitmap += (port & 0x7fff) / 8;
8540 if (last_bitmap != bitmap)
8541 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8543 if (b & (1 << (port & 7)))
8548 last_bitmap = bitmap;
8555 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8556 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8557 * disinterest in the current event (read or write a specific MSR) by using an
8558 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8560 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8561 struct vmcs12 *vmcs12, u32 exit_reason)
8563 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8566 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8570 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8571 * for the four combinations of read/write and low/high MSR numbers.
8572 * First we need to figure out which of the four to use:
8574 bitmap = vmcs12->msr_bitmap;
8575 if (exit_reason == EXIT_REASON_MSR_WRITE)
8577 if (msr_index >= 0xc0000000) {
8578 msr_index -= 0xc0000000;
8582 /* Then read the msr_index'th bit from this bitmap: */
8583 if (msr_index < 1024*8) {
8585 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8587 return 1 & (b >> (msr_index & 7));
8589 return true; /* let L1 handle the wrong parameter */
8593 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8594 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8595 * intercept (via guest_host_mask etc.) the current event.
8597 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8598 struct vmcs12 *vmcs12)
8600 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8601 int cr = exit_qualification & 15;
8605 switch ((exit_qualification >> 4) & 3) {
8606 case 0: /* mov to cr */
8607 reg = (exit_qualification >> 8) & 15;
8608 val = kvm_register_readl(vcpu, reg);
8611 if (vmcs12->cr0_guest_host_mask &
8612 (val ^ vmcs12->cr0_read_shadow))
8616 if ((vmcs12->cr3_target_count >= 1 &&
8617 vmcs12->cr3_target_value0 == val) ||
8618 (vmcs12->cr3_target_count >= 2 &&
8619 vmcs12->cr3_target_value1 == val) ||
8620 (vmcs12->cr3_target_count >= 3 &&
8621 vmcs12->cr3_target_value2 == val) ||
8622 (vmcs12->cr3_target_count >= 4 &&
8623 vmcs12->cr3_target_value3 == val))
8625 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8629 if (vmcs12->cr4_guest_host_mask &
8630 (vmcs12->cr4_read_shadow ^ val))
8634 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8640 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8641 (vmcs12->cr0_read_shadow & X86_CR0_TS))
8644 case 1: /* mov from cr */
8647 if (vmcs12->cpu_based_vm_exec_control &
8648 CPU_BASED_CR3_STORE_EXITING)
8652 if (vmcs12->cpu_based_vm_exec_control &
8653 CPU_BASED_CR8_STORE_EXITING)
8660 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8661 * cr0. Other attempted changes are ignored, with no exit.
8663 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8664 if (vmcs12->cr0_guest_host_mask & 0xe &
8665 (val ^ vmcs12->cr0_read_shadow))
8667 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8668 !(vmcs12->cr0_read_shadow & 0x1) &&
8677 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8678 * should handle it ourselves in L0 (and then continue L2). Only call this
8679 * when in is_guest_mode (L2).
8681 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
8683 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8684 struct vcpu_vmx *vmx = to_vmx(vcpu);
8685 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8687 if (vmx->nested.nested_run_pending)
8690 if (unlikely(vmx->fail)) {
8691 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8692 vmcs_read32(VM_INSTRUCTION_ERROR));
8697 * The host physical addresses of some pages of guest memory
8698 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
8699 * Page). The CPU may write to these pages via their host
8700 * physical address while L2 is running, bypassing any
8701 * address-translation-based dirty tracking (e.g. EPT write
8704 * Mark them dirty on every exit from L2 to prevent them from
8705 * getting out of sync with dirty tracking.
8707 nested_mark_vmcs12_pages_dirty(vcpu);
8709 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8710 vmcs_readl(EXIT_QUALIFICATION),
8711 vmx->idt_vectoring_info,
8713 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8716 switch ((u16)exit_reason) {
8717 case EXIT_REASON_EXCEPTION_NMI:
8718 if (is_nmi(intr_info))
8720 else if (is_page_fault(intr_info))
8721 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
8722 else if (is_no_device(intr_info) &&
8723 !(vmcs12->guest_cr0 & X86_CR0_TS))
8725 else if (is_debug(intr_info) &&
8727 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8729 else if (is_breakpoint(intr_info) &&
8730 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8732 return vmcs12->exception_bitmap &
8733 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8734 case EXIT_REASON_EXTERNAL_INTERRUPT:
8736 case EXIT_REASON_TRIPLE_FAULT:
8738 case EXIT_REASON_PENDING_INTERRUPT:
8739 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8740 case EXIT_REASON_NMI_WINDOW:
8741 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8742 case EXIT_REASON_TASK_SWITCH:
8744 case EXIT_REASON_CPUID:
8746 case EXIT_REASON_HLT:
8747 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8748 case EXIT_REASON_INVD:
8750 case EXIT_REASON_INVLPG:
8751 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8752 case EXIT_REASON_RDPMC:
8753 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8754 case EXIT_REASON_RDRAND:
8755 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND);
8756 case EXIT_REASON_RDSEED:
8757 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED);
8758 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8759 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8760 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8761 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8762 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8763 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8764 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8765 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8767 * VMX instructions trap unconditionally. This allows L1 to
8768 * emulate them for its L2 guest, i.e., allows 3-level nesting!
8771 case EXIT_REASON_CR_ACCESS:
8772 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8773 case EXIT_REASON_DR_ACCESS:
8774 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8775 case EXIT_REASON_IO_INSTRUCTION:
8776 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8777 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
8778 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
8779 case EXIT_REASON_MSR_READ:
8780 case EXIT_REASON_MSR_WRITE:
8781 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8782 case EXIT_REASON_INVALID_STATE:
8784 case EXIT_REASON_MWAIT_INSTRUCTION:
8785 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8786 case EXIT_REASON_MONITOR_TRAP_FLAG:
8787 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8788 case EXIT_REASON_MONITOR_INSTRUCTION:
8789 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8790 case EXIT_REASON_PAUSE_INSTRUCTION:
8791 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8792 nested_cpu_has2(vmcs12,
8793 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8794 case EXIT_REASON_MCE_DURING_VMENTRY:
8796 case EXIT_REASON_TPR_BELOW_THRESHOLD:
8797 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8798 case EXIT_REASON_APIC_ACCESS:
8799 return nested_cpu_has2(vmcs12,
8800 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8801 case EXIT_REASON_APIC_WRITE:
8802 case EXIT_REASON_EOI_INDUCED:
8803 /* apic_write and eoi_induced should exit unconditionally. */
8805 case EXIT_REASON_EPT_VIOLATION:
8807 * L0 always deals with the EPT violation. If nested EPT is
8808 * used, and the nested mmu code discovers that the address is
8809 * missing in the guest EPT table (EPT12), the EPT violation
8810 * will be injected with nested_ept_inject_page_fault()
8813 case EXIT_REASON_EPT_MISCONFIG:
8815 * L2 never uses directly L1's EPT, but rather L0's own EPT
8816 * table (shadow on EPT) or a merged EPT table that L0 built
8817 * (EPT on EPT). So any problems with the structure of the
8818 * table is L0's fault.
8821 case EXIT_REASON_INVPCID:
8823 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
8824 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8825 case EXIT_REASON_WBINVD:
8826 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8827 case EXIT_REASON_XSETBV:
8829 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8831 * This should never happen, since it is not possible to
8832 * set XSS to a non-zero value---neither in L1 nor in L2.
8833 * If if it were, XSS would have to be checked against
8834 * the XSS exit bitmap in vmcs12.
8836 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8837 case EXIT_REASON_PREEMPTION_TIMER:
8839 case EXIT_REASON_PML_FULL:
8840 /* We emulate PML support to L1. */
8842 case EXIT_REASON_VMFUNC:
8843 /* VM functions are emulated through L2->L0 vmexits. */
8850 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
8852 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8855 * At this point, the exit interruption info in exit_intr_info
8856 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
8857 * we need to query the in-kernel LAPIC.
8859 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
8860 if ((exit_intr_info &
8861 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
8862 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
8863 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8864 vmcs12->vm_exit_intr_error_code =
8865 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
8868 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
8869 vmcs_readl(EXIT_QUALIFICATION));
8873 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8875 *info1 = vmcs_readl(EXIT_QUALIFICATION);
8876 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8879 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8882 __free_page(vmx->pml_pg);
8887 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8889 struct vcpu_vmx *vmx = to_vmx(vcpu);
8893 pml_idx = vmcs_read16(GUEST_PML_INDEX);
8895 /* Do nothing if PML buffer is empty */
8896 if (pml_idx == (PML_ENTITY_NUM - 1))
8899 /* PML index always points to next available PML buffer entity */
8900 if (pml_idx >= PML_ENTITY_NUM)
8905 pml_buf = page_address(vmx->pml_pg);
8906 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8909 gpa = pml_buf[pml_idx];
8910 WARN_ON(gpa & (PAGE_SIZE - 1));
8911 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8914 /* reset PML index */
8915 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8919 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8920 * Called before reporting dirty_bitmap to userspace.
8922 static void kvm_flush_pml_buffers(struct kvm *kvm)
8925 struct kvm_vcpu *vcpu;
8927 * We only need to kick vcpu out of guest mode here, as PML buffer
8928 * is flushed at beginning of all VMEXITs, and it's obvious that only
8929 * vcpus running in guest are possible to have unflushed GPAs in PML
8932 kvm_for_each_vcpu(i, vcpu, kvm)
8933 kvm_vcpu_kick(vcpu);
8936 static void vmx_dump_sel(char *name, uint32_t sel)
8938 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8939 name, vmcs_read16(sel),
8940 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8941 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8942 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8945 static void vmx_dump_dtsel(char *name, uint32_t limit)
8947 pr_err("%s limit=0x%08x, base=0x%016lx\n",
8948 name, vmcs_read32(limit),
8949 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8952 static void dump_vmcs(void)
8954 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8955 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8956 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8957 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8958 u32 secondary_exec_control = 0;
8959 unsigned long cr4 = vmcs_readl(GUEST_CR4);
8960 u64 efer = vmcs_read64(GUEST_IA32_EFER);
8963 if (cpu_has_secondary_exec_ctrls())
8964 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8966 pr_err("*** Guest State ***\n");
8967 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8968 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8969 vmcs_readl(CR0_GUEST_HOST_MASK));
8970 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8971 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8972 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8973 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8974 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8976 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
8977 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8978 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
8979 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8981 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
8982 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8983 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
8984 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8985 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8986 vmcs_readl(GUEST_SYSENTER_ESP),
8987 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8988 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
8989 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
8990 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
8991 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
8992 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
8993 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
8994 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8995 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8996 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8997 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
8998 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8999 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
9000 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
9001 efer, vmcs_read64(GUEST_IA32_PAT));
9002 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
9003 vmcs_read64(GUEST_IA32_DEBUGCTL),
9004 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
9005 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
9006 pr_err("PerfGlobCtl = 0x%016llx\n",
9007 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
9008 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
9009 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
9010 pr_err("Interruptibility = %08x ActivityState = %08x\n",
9011 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
9012 vmcs_read32(GUEST_ACTIVITY_STATE));
9013 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
9014 pr_err("InterruptStatus = %04x\n",
9015 vmcs_read16(GUEST_INTR_STATUS));
9017 pr_err("*** Host State ***\n");
9018 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
9019 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
9020 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
9021 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
9022 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
9023 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
9024 vmcs_read16(HOST_TR_SELECTOR));
9025 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
9026 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
9027 vmcs_readl(HOST_TR_BASE));
9028 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
9029 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
9030 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
9031 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
9032 vmcs_readl(HOST_CR4));
9033 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9034 vmcs_readl(HOST_IA32_SYSENTER_ESP),
9035 vmcs_read32(HOST_IA32_SYSENTER_CS),
9036 vmcs_readl(HOST_IA32_SYSENTER_EIP));
9037 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
9038 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
9039 vmcs_read64(HOST_IA32_EFER),
9040 vmcs_read64(HOST_IA32_PAT));
9041 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
9042 pr_err("PerfGlobCtl = 0x%016llx\n",
9043 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
9045 pr_err("*** Control State ***\n");
9046 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
9047 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
9048 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
9049 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
9050 vmcs_read32(EXCEPTION_BITMAP),
9051 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
9052 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
9053 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
9054 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9055 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
9056 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
9057 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
9058 vmcs_read32(VM_EXIT_INTR_INFO),
9059 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9060 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
9061 pr_err(" reason=%08x qualification=%016lx\n",
9062 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
9063 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
9064 vmcs_read32(IDT_VECTORING_INFO_FIELD),
9065 vmcs_read32(IDT_VECTORING_ERROR_CODE));
9066 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
9067 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
9068 pr_err("TSC Multiplier = 0x%016llx\n",
9069 vmcs_read64(TSC_MULTIPLIER));
9070 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
9071 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
9072 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
9073 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
9074 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
9075 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
9076 n = vmcs_read32(CR3_TARGET_COUNT);
9077 for (i = 0; i + 1 < n; i += 4)
9078 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
9079 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
9080 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
9082 pr_err("CR3 target%u=%016lx\n",
9083 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
9084 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
9085 pr_err("PLE Gap=%08x Window=%08x\n",
9086 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
9087 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
9088 pr_err("Virtual processor ID = 0x%04x\n",
9089 vmcs_read16(VIRTUAL_PROCESSOR_ID));
9093 * The guest has exited. See if we can fix it or if we need userspace
9096 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
9098 struct vcpu_vmx *vmx = to_vmx(vcpu);
9099 u32 exit_reason = vmx->exit_reason;
9100 u32 vectoring_info = vmx->idt_vectoring_info;
9102 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
9105 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
9106 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
9107 * querying dirty_bitmap, we only need to kick all vcpus out of guest
9108 * mode as if vcpus is in root mode, the PML buffer must has been
9112 vmx_flush_pml_buffer(vcpu);
9114 /* If guest state is invalid, start emulating */
9115 if (vmx->emulation_required)
9116 return handle_invalid_guest_state(vcpu);
9118 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
9119 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
9121 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
9123 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
9124 vcpu->run->fail_entry.hardware_entry_failure_reason
9129 if (unlikely(vmx->fail)) {
9130 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
9131 vcpu->run->fail_entry.hardware_entry_failure_reason
9132 = vmcs_read32(VM_INSTRUCTION_ERROR);
9138 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
9139 * delivery event since it indicates guest is accessing MMIO.
9140 * The vm-exit can be triggered again after return to guest that
9141 * will cause infinite loop.
9143 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
9144 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
9145 exit_reason != EXIT_REASON_EPT_VIOLATION &&
9146 exit_reason != EXIT_REASON_PML_FULL &&
9147 exit_reason != EXIT_REASON_APIC_ACCESS &&
9148 exit_reason != EXIT_REASON_TASK_SWITCH)) {
9149 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
9150 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
9151 vcpu->run->internal.ndata = 3;
9152 vcpu->run->internal.data[0] = vectoring_info;
9153 vcpu->run->internal.data[1] = exit_reason;
9154 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
9155 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
9156 vcpu->run->internal.ndata++;
9157 vcpu->run->internal.data[3] =
9158 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
9163 if (unlikely(!cpu_has_virtual_nmis() &&
9164 vmx->loaded_vmcs->soft_vnmi_blocked)) {
9165 if (vmx_interrupt_allowed(vcpu)) {
9166 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
9167 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
9168 vcpu->arch.nmi_pending) {
9170 * This CPU don't support us in finding the end of an
9171 * NMI-blocked window if the guest runs with IRQs
9172 * disabled. So we pull the trigger after 1 s of
9173 * futile waiting, but inform the user about this.
9175 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
9176 "state on VCPU %d after 1 s timeout\n",
9177 __func__, vcpu->vcpu_id);
9178 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
9182 if (exit_reason < kvm_vmx_max_exit_handlers
9183 && kvm_vmx_exit_handlers[exit_reason])
9184 return kvm_vmx_exit_handlers[exit_reason](vcpu);
9186 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
9188 kvm_queue_exception(vcpu, UD_VECTOR);
9194 * Software based L1D cache flush which is used when microcode providing
9195 * the cache control MSR is not loaded.
9197 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
9198 * flush it is required to read in 64 KiB because the replacement algorithm
9199 * is not exactly LRU. This could be sized at runtime via topology
9200 * information but as all relevant affected CPUs have 32KiB L1D cache size
9201 * there is no point in doing so.
9203 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
9205 int size = PAGE_SIZE << L1D_CACHE_ORDER;
9208 * This code is only executed when the the flush mode is 'cond' or
9211 if (static_branch_likely(&vmx_l1d_flush_cond)) {
9215 * Clear the per-vcpu flush bit, it gets set again
9216 * either from vcpu_run() or from one of the unsafe
9219 flush_l1d = vcpu->arch.l1tf_flush_l1d;
9220 vcpu->arch.l1tf_flush_l1d = false;
9223 * Clear the per-cpu flush bit, it gets set again from
9224 * the interrupt handlers.
9226 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
9227 kvm_clear_cpu_l1tf_flush_l1d();
9233 vcpu->stat.l1d_flush++;
9235 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
9236 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
9241 /* First ensure the pages are in the TLB */
9242 "xorl %%eax, %%eax\n"
9243 ".Lpopulate_tlb:\n\t"
9244 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
9245 "addl $4096, %%eax\n\t"
9246 "cmpl %%eax, %[size]\n\t"
9247 "jne .Lpopulate_tlb\n\t"
9248 "xorl %%eax, %%eax\n\t"
9250 /* Now fill the cache */
9251 "xorl %%eax, %%eax\n"
9253 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
9254 "addl $64, %%eax\n\t"
9255 "cmpl %%eax, %[size]\n\t"
9256 "jne .Lfill_cache\n\t"
9258 :: [flush_pages] "r" (vmx_l1d_flush_pages),
9260 : "eax", "ebx", "ecx", "edx");
9263 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
9265 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9267 if (is_guest_mode(vcpu) &&
9268 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
9271 if (irr == -1 || tpr < irr) {
9272 vmcs_write32(TPR_THRESHOLD, 0);
9276 vmcs_write32(TPR_THRESHOLD, irr);
9279 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
9281 u32 sec_exec_control;
9283 if (!lapic_in_kernel(vcpu))
9286 if (!flexpriority_enabled &&
9287 !cpu_has_vmx_virtualize_x2apic_mode())
9290 /* Postpone execution until vmcs01 is the current VMCS. */
9291 if (is_guest_mode(vcpu)) {
9292 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
9296 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9297 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
9298 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
9300 switch (kvm_get_apic_mode(vcpu)) {
9301 case LAPIC_MODE_INVALID:
9302 WARN_ONCE(true, "Invalid local APIC state");
9303 case LAPIC_MODE_DISABLED:
9305 case LAPIC_MODE_XAPIC:
9306 if (flexpriority_enabled) {
9308 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9309 vmx_flush_tlb(vcpu, true);
9312 case LAPIC_MODE_X2APIC:
9313 if (cpu_has_vmx_virtualize_x2apic_mode())
9315 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
9318 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
9320 vmx_update_msr_bitmap(vcpu);
9323 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
9325 struct vcpu_vmx *vmx = to_vmx(vcpu);
9328 * Currently we do not handle the nested case where L2 has an
9329 * APIC access page of its own; that page is still pinned.
9330 * Hence, we skip the case where the VCPU is in guest mode _and_
9331 * L1 prepared an APIC access page for L2.
9333 * For the case where L1 and L2 share the same APIC access page
9334 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
9335 * in the vmcs12), this function will only update either the vmcs01
9336 * or the vmcs02. If the former, the vmcs02 will be updated by
9337 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
9338 * the next L2->L1 exit.
9340 if (!is_guest_mode(vcpu) ||
9341 !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
9342 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9343 vmcs_write64(APIC_ACCESS_ADDR, hpa);
9344 vmx_flush_tlb(vcpu, true);
9348 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
9356 status = vmcs_read16(GUEST_INTR_STATUS);
9358 if (max_isr != old) {
9360 status |= max_isr << 8;
9361 vmcs_write16(GUEST_INTR_STATUS, status);
9365 static void vmx_set_rvi(int vector)
9373 status = vmcs_read16(GUEST_INTR_STATUS);
9374 old = (u8)status & 0xff;
9375 if ((u8)vector != old) {
9377 status |= (u8)vector;
9378 vmcs_write16(GUEST_INTR_STATUS, status);
9382 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
9384 if (!is_guest_mode(vcpu)) {
9385 vmx_set_rvi(max_irr);
9393 * In guest mode. If a vmexit is needed, vmx_check_nested_events
9396 if (nested_exit_on_intr(vcpu))
9400 * Else, fall back to pre-APICv interrupt injection since L2
9401 * is run without virtual interrupt delivery.
9403 if (!kvm_event_needs_reinjection(vcpu) &&
9404 vmx_interrupt_allowed(vcpu)) {
9405 kvm_queue_interrupt(vcpu, max_irr, false);
9406 vmx_inject_irq(vcpu);
9410 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
9412 struct vcpu_vmx *vmx = to_vmx(vcpu);
9415 WARN_ON(!vcpu->arch.apicv_active);
9416 if (pi_test_on(&vmx->pi_desc)) {
9417 pi_clear_on(&vmx->pi_desc);
9419 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
9420 * But on x86 this is just a compiler barrier anyway.
9422 smp_mb__after_atomic();
9423 max_irr = kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
9425 max_irr = kvm_lapic_find_highest_irr(vcpu);
9427 vmx_hwapic_irr_update(vcpu, max_irr);
9431 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
9433 return pi_test_on(vcpu_to_pi_desc(vcpu));
9436 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
9438 if (!kvm_vcpu_apicv_active(vcpu))
9441 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
9442 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
9443 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
9444 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
9447 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
9449 struct vcpu_vmx *vmx = to_vmx(vcpu);
9451 pi_clear_on(&vmx->pi_desc);
9452 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
9455 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
9457 u32 exit_intr_info = 0;
9458 u16 basic_exit_reason = (u16)vmx->exit_reason;
9460 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
9461 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
9464 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9465 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9466 vmx->exit_intr_info = exit_intr_info;
9468 /* if exit due to PF check for async PF */
9469 if (is_page_fault(exit_intr_info))
9470 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
9472 /* Handle machine checks before interrupts are enabled */
9473 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
9474 is_machine_check(exit_intr_info))
9475 kvm_machine_check();
9477 /* We need to handle NMIs before interrupts are enabled */
9478 if (is_nmi(exit_intr_info)) {
9479 kvm_before_handle_nmi(&vmx->vcpu);
9481 kvm_after_handle_nmi(&vmx->vcpu);
9485 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
9487 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9489 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
9490 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
9491 unsigned int vector;
9492 unsigned long entry;
9494 struct vcpu_vmx *vmx = to_vmx(vcpu);
9495 #ifdef CONFIG_X86_64
9499 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9500 desc = (gate_desc *)vmx->host_idt_base + vector;
9501 entry = gate_offset(desc);
9503 #ifdef CONFIG_X86_64
9504 "mov %%" _ASM_SP ", %[sp]\n\t"
9505 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
9510 __ASM_SIZE(push) " $%c[cs]\n\t"
9513 #ifdef CONFIG_X86_64
9518 THUNK_TARGET(entry),
9519 [ss]"i"(__KERNEL_DS),
9520 [cs]"i"(__KERNEL_CS)
9524 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
9526 static bool vmx_has_emulated_msr(int index)
9529 case MSR_IA32_SMBASE:
9531 * We cannot do SMM unless we can run the guest in big
9534 return enable_unrestricted_guest || emulate_invalid_guest_state;
9535 case MSR_AMD64_VIRT_SPEC_CTRL:
9536 /* This is AMD only. */
9543 static bool vmx_mpx_supported(void)
9545 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
9546 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
9549 static bool vmx_xsaves_supported(void)
9551 return vmcs_config.cpu_based_2nd_exec_ctrl &
9552 SECONDARY_EXEC_XSAVES;
9555 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
9560 bool idtv_info_valid;
9562 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9564 if (cpu_has_virtual_nmis()) {
9565 if (vmx->loaded_vmcs->nmi_known_unmasked)
9568 * Can't use vmx->exit_intr_info since we're not sure what
9569 * the exit reason is.
9571 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9572 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9573 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9575 * SDM 3: 27.7.1.2 (September 2008)
9576 * Re-set bit "block by NMI" before VM entry if vmexit caused by
9577 * a guest IRET fault.
9578 * SDM 3: 23.2.2 (September 2008)
9579 * Bit 12 is undefined in any of the following cases:
9580 * If the VM exit sets the valid bit in the IDT-vectoring
9581 * information field.
9582 * If the VM exit is due to a double fault.
9584 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9585 vector != DF_VECTOR && !idtv_info_valid)
9586 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9587 GUEST_INTR_STATE_NMI);
9589 vmx->loaded_vmcs->nmi_known_unmasked =
9590 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9591 & GUEST_INTR_STATE_NMI);
9592 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
9593 vmx->loaded_vmcs->vnmi_blocked_time +=
9594 ktime_to_ns(ktime_sub(ktime_get(),
9595 vmx->loaded_vmcs->entry_time));
9598 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9599 u32 idt_vectoring_info,
9600 int instr_len_field,
9601 int error_code_field)
9605 bool idtv_info_valid;
9607 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9609 vcpu->arch.nmi_injected = false;
9610 kvm_clear_exception_queue(vcpu);
9611 kvm_clear_interrupt_queue(vcpu);
9613 if (!idtv_info_valid)
9616 kvm_make_request(KVM_REQ_EVENT, vcpu);
9618 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9619 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9622 case INTR_TYPE_NMI_INTR:
9623 vcpu->arch.nmi_injected = true;
9625 * SDM 3: 27.7.1.2 (September 2008)
9626 * Clear bit "block by NMI" before VM entry if a NMI
9629 vmx_set_nmi_mask(vcpu, false);
9631 case INTR_TYPE_SOFT_EXCEPTION:
9632 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9634 case INTR_TYPE_HARD_EXCEPTION:
9635 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9636 u32 err = vmcs_read32(error_code_field);
9637 kvm_requeue_exception_e(vcpu, vector, err);
9639 kvm_requeue_exception(vcpu, vector);
9641 case INTR_TYPE_SOFT_INTR:
9642 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9644 case INTR_TYPE_EXT_INTR:
9645 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9652 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9654 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9655 VM_EXIT_INSTRUCTION_LEN,
9656 IDT_VECTORING_ERROR_CODE);
9659 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9661 __vmx_complete_interrupts(vcpu,
9662 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9663 VM_ENTRY_INSTRUCTION_LEN,
9664 VM_ENTRY_EXCEPTION_ERROR_CODE);
9666 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9669 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9672 struct perf_guest_switch_msr *msrs;
9674 msrs = perf_guest_get_msrs(&nr_msrs);
9679 for (i = 0; i < nr_msrs; i++)
9680 if (msrs[i].host == msrs[i].guest)
9681 clear_atomic_switch_msr(vmx, msrs[i].msr);
9683 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9684 msrs[i].host, false);
9687 static void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9689 struct vcpu_vmx *vmx = to_vmx(vcpu);
9693 if (vmx->hv_deadline_tsc == -1)
9697 if (vmx->hv_deadline_tsc > tscl)
9698 /* sure to be 32 bit only because checked on set_hv_timer */
9699 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9700 cpu_preemption_timer_multi);
9704 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9707 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9709 struct vcpu_vmx *vmx = to_vmx(vcpu);
9710 unsigned long debugctlmsr, cr3, cr4;
9712 /* Record the guest's net vcpu time for enforced NMI injections. */
9713 if (unlikely(!cpu_has_virtual_nmis() &&
9714 vmx->loaded_vmcs->soft_vnmi_blocked))
9715 vmx->loaded_vmcs->entry_time = ktime_get();
9717 /* Don't enter VMX if guest state is invalid, let the exit handler
9718 start emulation until we arrive back to a valid state */
9719 if (vmx->emulation_required)
9722 if (vmx->ple_window_dirty) {
9723 vmx->ple_window_dirty = false;
9724 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9727 if (vmx->nested.sync_shadow_vmcs) {
9728 copy_vmcs12_to_shadow(vmx);
9729 vmx->nested.sync_shadow_vmcs = false;
9732 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9733 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9734 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9735 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9737 cr3 = __get_current_cr3_fast();
9738 if (unlikely(cr3 != vmx->loaded_vmcs->vmcs_host_cr3)) {
9739 vmcs_writel(HOST_CR3, cr3);
9740 vmx->loaded_vmcs->vmcs_host_cr3 = cr3;
9743 cr4 = cr4_read_shadow();
9744 if (unlikely(cr4 != vmx->loaded_vmcs->vmcs_host_cr4)) {
9745 vmcs_writel(HOST_CR4, cr4);
9746 vmx->loaded_vmcs->vmcs_host_cr4 = cr4;
9749 /* When single-stepping over STI and MOV SS, we must clear the
9750 * corresponding interruptibility bits in the guest state. Otherwise
9751 * vmentry fails as it then expects bit 14 (BS) in pending debug
9752 * exceptions being set, but that's not correct for the guest debugging
9754 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9755 vmx_set_interrupt_shadow(vcpu, 0);
9757 if (static_cpu_has(X86_FEATURE_PKU) &&
9758 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
9759 vcpu->arch.pkru != vmx->host_pkru)
9760 __write_pkru(vcpu->arch.pkru);
9762 atomic_switch_perf_msrs(vmx);
9763 debugctlmsr = get_debugctlmsr();
9765 vmx_arm_hv_timer(vcpu);
9768 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
9769 * it's non-zero. Since vmentry is serialising on affected CPUs, there
9770 * is no need to worry about the conditional branch over the wrmsr
9771 * being speculatively taken.
9773 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
9775 vmx->__launched = vmx->loaded_vmcs->launched;
9777 /* L1D Flush includes CPU buffer clear to mitigate MDS */
9778 if (static_branch_unlikely(&vmx_l1d_should_flush))
9779 vmx_l1d_flush(vcpu);
9780 else if (static_branch_unlikely(&mds_user_clear))
9781 mds_clear_cpu_buffers();
9784 /* Store host registers */
9785 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9786 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9787 "push %%" _ASM_CX " \n\t"
9788 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9790 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9791 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9793 /* Reload cr2 if changed */
9794 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9795 "mov %%cr2, %%" _ASM_DX " \n\t"
9796 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9798 "mov %%" _ASM_AX", %%cr2 \n\t"
9800 /* Check if vmlaunch of vmresume is needed */
9801 "cmpl $0, %c[launched](%0) \n\t"
9802 /* Load guest registers. Don't clobber flags. */
9803 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9804 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9805 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9806 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9807 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9808 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9809 #ifdef CONFIG_X86_64
9810 "mov %c[r8](%0), %%r8 \n\t"
9811 "mov %c[r9](%0), %%r9 \n\t"
9812 "mov %c[r10](%0), %%r10 \n\t"
9813 "mov %c[r11](%0), %%r11 \n\t"
9814 "mov %c[r12](%0), %%r12 \n\t"
9815 "mov %c[r13](%0), %%r13 \n\t"
9816 "mov %c[r14](%0), %%r14 \n\t"
9817 "mov %c[r15](%0), %%r15 \n\t"
9819 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9821 /* Enter guest mode */
9823 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9825 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9827 /* Save guest registers, load host registers, keep flags */
9828 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9830 "setbe %c[fail](%0)\n\t"
9831 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9832 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9833 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9834 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9835 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9836 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9837 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9838 #ifdef CONFIG_X86_64
9839 "mov %%r8, %c[r8](%0) \n\t"
9840 "mov %%r9, %c[r9](%0) \n\t"
9841 "mov %%r10, %c[r10](%0) \n\t"
9842 "mov %%r11, %c[r11](%0) \n\t"
9843 "mov %%r12, %c[r12](%0) \n\t"
9844 "mov %%r13, %c[r13](%0) \n\t"
9845 "mov %%r14, %c[r14](%0) \n\t"
9846 "mov %%r15, %c[r15](%0) \n\t"
9847 "xor %%r8d, %%r8d \n\t"
9848 "xor %%r9d, %%r9d \n\t"
9849 "xor %%r10d, %%r10d \n\t"
9850 "xor %%r11d, %%r11d \n\t"
9851 "xor %%r12d, %%r12d \n\t"
9852 "xor %%r13d, %%r13d \n\t"
9853 "xor %%r14d, %%r14d \n\t"
9854 "xor %%r15d, %%r15d \n\t"
9856 "mov %%cr2, %%" _ASM_AX " \n\t"
9857 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9859 "xor %%eax, %%eax \n\t"
9860 "xor %%ebx, %%ebx \n\t"
9861 "xor %%esi, %%esi \n\t"
9862 "xor %%edi, %%edi \n\t"
9863 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
9864 ".pushsection .rodata \n\t"
9865 ".global vmx_return \n\t"
9866 "vmx_return: " _ASM_PTR " 2b \n\t"
9868 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9869 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9870 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9871 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9872 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9873 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9874 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9875 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9876 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9877 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9878 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9879 #ifdef CONFIG_X86_64
9880 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9881 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9882 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9883 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9884 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9885 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9886 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9887 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9889 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9890 [wordsize]"i"(sizeof(ulong))
9892 #ifdef CONFIG_X86_64
9893 , "rax", "rbx", "rdi", "rsi"
9894 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9896 , "eax", "ebx", "edi", "esi"
9901 * We do not use IBRS in the kernel. If this vCPU has used the
9902 * SPEC_CTRL MSR it may have left it on; save the value and
9903 * turn it off. This is much more efficient than blindly adding
9904 * it to the atomic save/restore list. Especially as the former
9905 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
9907 * For non-nested case:
9908 * If the L01 MSR bitmap does not intercept the MSR, then we need to
9912 * If the L02 MSR bitmap does not intercept the MSR, then we need to
9915 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
9916 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
9918 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
9920 /* Eliminate branch target predictions from guest mode */
9923 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9925 update_debugctlmsr(debugctlmsr);
9927 #ifndef CONFIG_X86_64
9929 * The sysexit path does not restore ds/es, so we must set them to
9930 * a reasonable value ourselves.
9932 * We can't defer this to vmx_load_host_state() since that function
9933 * may be executed in interrupt context, which saves and restore segments
9934 * around it, nullifying its effect.
9936 loadsegment(ds, __USER_DS);
9937 loadsegment(es, __USER_DS);
9940 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9941 | (1 << VCPU_EXREG_RFLAGS)
9942 | (1 << VCPU_EXREG_PDPTR)
9943 | (1 << VCPU_EXREG_SEGMENTS)
9944 | (1 << VCPU_EXREG_CR3));
9945 vcpu->arch.regs_dirty = 0;
9948 * eager fpu is enabled if PKEY is supported and CR4 is switched
9949 * back on host, so it is safe to read guest PKRU from current
9952 if (static_cpu_has(X86_FEATURE_PKU) &&
9953 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
9954 vcpu->arch.pkru = __read_pkru();
9955 if (vcpu->arch.pkru != vmx->host_pkru)
9956 __write_pkru(vmx->host_pkru);
9960 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9961 * we did not inject a still-pending event to L1 now because of
9962 * nested_run_pending, we need to re-enable this bit.
9964 if (vmx->nested.nested_run_pending)
9965 kvm_make_request(KVM_REQ_EVENT, vcpu);
9967 vmx->nested.nested_run_pending = 0;
9968 vmx->idt_vectoring_info = 0;
9970 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
9971 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
9974 vmx->loaded_vmcs->launched = 1;
9975 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9977 vmx_complete_atomic_exit(vmx);
9978 vmx_recover_nmi_blocking(vmx);
9979 vmx_complete_interrupts(vmx);
9981 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9983 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
9985 struct vcpu_vmx *vmx = to_vmx(vcpu);
9988 if (vmx->loaded_vmcs == vmcs)
9993 vmx->loaded_vmcs = vmcs;
9994 vmx_vcpu_load(vcpu, cpu);
10000 * Ensure that the current vmcs of the logical processor is the
10001 * vmcs01 of the vcpu before calling free_nested().
10003 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
10005 struct vcpu_vmx *vmx = to_vmx(vcpu);
10008 r = vcpu_load(vcpu);
10010 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
10015 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
10017 struct vcpu_vmx *vmx = to_vmx(vcpu);
10020 vmx_destroy_pml_buffer(vmx);
10021 free_vpid(vmx->vpid);
10022 leave_guest_mode(vcpu);
10023 vmx_free_vcpu_nested(vcpu);
10024 free_loaded_vmcs(vmx->loaded_vmcs);
10025 kfree(vmx->guest_msrs);
10026 kvm_vcpu_uninit(vcpu);
10027 kmem_cache_free(kvm_vcpu_cache, vmx);
10030 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
10033 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
10034 unsigned long *msr_bitmap;
10038 return ERR_PTR(-ENOMEM);
10040 vmx->vpid = allocate_vpid();
10042 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
10049 * If PML is turned on, failure on enabling PML just results in failure
10050 * of creating the vcpu, therefore we can simplify PML logic (by
10051 * avoiding dealing with cases, such as enabling PML partially on vcpus
10052 * for the guest, etc.
10055 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
10060 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
10061 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
10064 if (!vmx->guest_msrs)
10067 err = alloc_loaded_vmcs(&vmx->vmcs01);
10071 msr_bitmap = vmx->vmcs01.msr_bitmap;
10072 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
10073 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
10074 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
10075 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
10076 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
10077 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
10078 vmx->msr_bitmap_mode = 0;
10080 vmx->loaded_vmcs = &vmx->vmcs01;
10082 vmx_vcpu_load(&vmx->vcpu, cpu);
10083 vmx->vcpu.cpu = cpu;
10084 err = vmx_vcpu_setup(vmx);
10085 vmx_vcpu_put(&vmx->vcpu);
10089 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10090 err = alloc_apic_access_page(kvm);
10096 if (!kvm->arch.ept_identity_map_addr)
10097 kvm->arch.ept_identity_map_addr =
10098 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
10099 err = init_rmode_identity_map(kvm);
10105 nested_vmx_setup_ctls_msrs(vmx);
10107 vmx->nested.posted_intr_nv = -1;
10108 vmx->nested.current_vmptr = -1ull;
10110 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
10113 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
10114 * or POSTED_INTR_WAKEUP_VECTOR.
10116 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
10117 vmx->pi_desc.sn = 1;
10122 free_loaded_vmcs(vmx->loaded_vmcs);
10124 kfree(vmx->guest_msrs);
10126 vmx_destroy_pml_buffer(vmx);
10128 kvm_vcpu_uninit(&vmx->vcpu);
10130 free_vpid(vmx->vpid);
10131 kmem_cache_free(kvm_vcpu_cache, vmx);
10132 return ERR_PTR(err);
10135 #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/hw-vuln/l1tf.html for details.\n"
10136 #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/hw-vuln/l1tf.html for details.\n"
10138 static int vmx_vm_init(struct kvm *kvm)
10140 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
10141 switch (l1tf_mitigation) {
10142 case L1TF_MITIGATION_OFF:
10143 case L1TF_MITIGATION_FLUSH_NOWARN:
10144 /* 'I explicitly don't care' is set */
10146 case L1TF_MITIGATION_FLUSH:
10147 case L1TF_MITIGATION_FLUSH_NOSMT:
10148 case L1TF_MITIGATION_FULL:
10150 * Warn upon starting the first VM in a potentially
10151 * insecure environment.
10153 if (sched_smt_active())
10154 pr_warn_once(L1TF_MSG_SMT);
10155 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
10156 pr_warn_once(L1TF_MSG_L1D);
10158 case L1TF_MITIGATION_FULL_FORCE:
10159 /* Flush is enforced */
10166 static void __init vmx_check_processor_compat(void *rtn)
10168 struct vmcs_config vmcs_conf;
10171 if (setup_vmcs_config(&vmcs_conf) < 0)
10172 *(int *)rtn = -EIO;
10173 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
10174 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
10175 smp_processor_id());
10176 *(int *)rtn = -EIO;
10180 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
10185 /* For VT-d and EPT combination
10186 * 1. MMIO: always map as UC
10187 * 2. EPT with VT-d:
10188 * a. VT-d without snooping control feature: can't guarantee the
10189 * result, try to trust guest.
10190 * b. VT-d with snooping control feature: snooping control feature of
10191 * VT-d engine can guarantee the cache correctness. Just set it
10192 * to WB to keep consistent with host. So the same as item 3.
10193 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
10194 * consistent with host MTRR
10197 cache = MTRR_TYPE_UNCACHABLE;
10201 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
10202 ipat = VMX_EPT_IPAT_BIT;
10203 cache = MTRR_TYPE_WRBACK;
10207 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
10208 ipat = VMX_EPT_IPAT_BIT;
10209 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
10210 cache = MTRR_TYPE_WRBACK;
10212 cache = MTRR_TYPE_UNCACHABLE;
10216 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
10219 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
10222 static int vmx_get_lpage_level(void)
10224 if (enable_ept && !cpu_has_vmx_ept_1g_page())
10225 return PT_DIRECTORY_LEVEL;
10227 /* For shadow and EPT supported 1GB page */
10228 return PT_PDPE_LEVEL;
10231 static void vmcs_set_secondary_exec_control(u32 new_ctl)
10234 * These bits in the secondary execution controls field
10235 * are dynamic, the others are mostly based on the hypervisor
10236 * architecture and the guest's CPUID. Do not touch the
10240 SECONDARY_EXEC_SHADOW_VMCS |
10241 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
10242 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10244 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10246 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
10247 (new_ctl & ~mask) | (cur_ctl & mask));
10251 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
10252 * (indicating "allowed-1") if they are supported in the guest's CPUID.
10254 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
10256 struct vcpu_vmx *vmx = to_vmx(vcpu);
10257 struct kvm_cpuid_entry2 *entry;
10259 vmx->nested.nested_vmx_cr0_fixed1 = 0xffffffff;
10260 vmx->nested.nested_vmx_cr4_fixed1 = X86_CR4_PCE;
10262 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
10263 if (entry && (entry->_reg & (_cpuid_mask))) \
10264 vmx->nested.nested_vmx_cr4_fixed1 |= (_cr4_mask); \
10267 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
10268 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
10269 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
10270 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
10271 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
10272 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
10273 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
10274 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
10275 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
10276 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
10277 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
10278 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
10279 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
10280 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
10281 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
10283 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
10284 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
10285 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
10286 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
10287 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
10288 /* TODO: Use X86_CR4_UMIP and X86_FEATURE_UMIP macros */
10289 cr4_fixed1_update(bit(11), ecx, bit(2));
10291 #undef cr4_fixed1_update
10294 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
10296 struct vcpu_vmx *vmx = to_vmx(vcpu);
10298 if (cpu_has_secondary_exec_ctrls()) {
10299 vmx_compute_secondary_exec_control(vmx);
10300 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
10303 if (nested_vmx_allowed(vcpu))
10304 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
10305 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10307 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
10308 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
10310 if (nested_vmx_allowed(vcpu))
10311 nested_vmx_cr_fixed1_bits_update(vcpu);
10314 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
10316 if (func == 1 && nested)
10317 entry->ecx |= bit(X86_FEATURE_VMX);
10320 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
10321 struct x86_exception *fault)
10323 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10324 struct vcpu_vmx *vmx = to_vmx(vcpu);
10326 unsigned long exit_qualification = vcpu->arch.exit_qualification;
10328 if (vmx->nested.pml_full) {
10329 exit_reason = EXIT_REASON_PML_FULL;
10330 vmx->nested.pml_full = false;
10331 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
10332 } else if (fault->error_code & PFERR_RSVD_MASK)
10333 exit_reason = EXIT_REASON_EPT_MISCONFIG;
10335 exit_reason = EXIT_REASON_EPT_VIOLATION;
10337 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
10338 vmcs12->guest_physical_address = fault->address;
10341 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
10343 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
10346 /* Callbacks for nested_ept_init_mmu_context: */
10348 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
10350 /* return the page table to be shadowed - in our case, EPT12 */
10351 return get_vmcs12(vcpu)->ept_pointer;
10354 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
10356 WARN_ON(mmu_is_nested(vcpu));
10357 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
10360 kvm_mmu_unload(vcpu);
10361 kvm_init_shadow_ept_mmu(vcpu,
10362 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
10363 VMX_EPT_EXECUTE_ONLY_BIT,
10364 nested_ept_ad_enabled(vcpu));
10365 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
10366 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
10367 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
10369 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
10373 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
10375 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
10378 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
10381 bool inequality, bit;
10383 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
10385 (error_code & vmcs12->page_fault_error_code_mask) !=
10386 vmcs12->page_fault_error_code_match;
10387 return inequality ^ bit;
10390 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
10391 struct x86_exception *fault)
10393 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10395 WARN_ON(!is_guest_mode(vcpu));
10397 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
10398 !to_vmx(vcpu)->nested.nested_run_pending) {
10399 vmcs12->vm_exit_intr_error_code = fault->error_code;
10400 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10401 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
10402 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
10405 kvm_inject_page_fault(vcpu, fault);
10409 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10410 struct vmcs12 *vmcs12);
10412 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
10413 struct vmcs12 *vmcs12)
10415 struct vcpu_vmx *vmx = to_vmx(vcpu);
10419 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10421 * Translate L1 physical address to host physical
10422 * address for vmcs02. Keep the page pinned, so this
10423 * physical address remains valid. We keep a reference
10424 * to it so we can release it later.
10426 if (vmx->nested.apic_access_page) { /* shouldn't happen */
10427 kvm_release_page_dirty(vmx->nested.apic_access_page);
10428 vmx->nested.apic_access_page = NULL;
10430 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
10432 * If translation failed, no matter: This feature asks
10433 * to exit when accessing the given address, and if it
10434 * can never be accessed, this feature won't do
10437 if (!is_error_page(page)) {
10438 vmx->nested.apic_access_page = page;
10439 hpa = page_to_phys(vmx->nested.apic_access_page);
10440 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10442 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
10443 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10445 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
10446 cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10447 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
10448 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
10449 kvm_vcpu_reload_apic_access_page(vcpu);
10452 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
10453 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
10454 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
10455 vmx->nested.virtual_apic_page = NULL;
10457 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
10460 * If translation failed, VM entry will fail because
10461 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
10462 * Failing the vm entry is _not_ what the processor
10463 * does but it's basically the only possibility we
10464 * have. We could still enter the guest if CR8 load
10465 * exits are enabled, CR8 store exits are enabled, and
10466 * virtualize APIC access is disabled; in this case
10467 * the processor would never use the TPR shadow and we
10468 * could simply clear the bit from the execution
10469 * control. But such a configuration is useless, so
10470 * let's keep the code simple.
10472 if (!is_error_page(page)) {
10473 vmx->nested.virtual_apic_page = page;
10474 hpa = page_to_phys(vmx->nested.virtual_apic_page);
10475 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
10479 if (nested_cpu_has_posted_intr(vmcs12)) {
10480 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
10481 kunmap(vmx->nested.pi_desc_page);
10482 kvm_release_page_dirty(vmx->nested.pi_desc_page);
10483 vmx->nested.pi_desc_page = NULL;
10484 vmx->nested.pi_desc = NULL;
10485 vmcs_write64(POSTED_INTR_DESC_ADDR, -1ull);
10487 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
10488 if (is_error_page(page))
10490 vmx->nested.pi_desc_page = page;
10491 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
10492 vmx->nested.pi_desc =
10493 (struct pi_desc *)((void *)vmx->nested.pi_desc +
10494 (unsigned long)(vmcs12->posted_intr_desc_addr &
10496 vmcs_write64(POSTED_INTR_DESC_ADDR,
10497 page_to_phys(vmx->nested.pi_desc_page) +
10498 (unsigned long)(vmcs12->posted_intr_desc_addr &
10501 if (cpu_has_vmx_msr_bitmap() &&
10502 nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS) &&
10503 nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10504 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
10505 CPU_BASED_USE_MSR_BITMAPS);
10507 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
10508 CPU_BASED_USE_MSR_BITMAPS);
10511 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
10513 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
10514 struct vcpu_vmx *vmx = to_vmx(vcpu);
10516 if (vcpu->arch.virtual_tsc_khz == 0)
10519 /* Make sure short timeouts reliably trigger an immediate vmexit.
10520 * hrtimer_start does not guarantee this. */
10521 if (preemption_timeout <= 1) {
10522 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
10526 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10527 preemption_timeout *= 1000000;
10528 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
10529 hrtimer_start(&vmx->nested.preemption_timer,
10530 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
10533 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
10534 struct vmcs12 *vmcs12)
10536 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
10539 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
10540 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
10546 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
10547 struct vmcs12 *vmcs12)
10549 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
10552 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
10558 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
10559 struct vmcs12 *vmcs12)
10561 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10564 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
10571 * Merge L0's and L1's MSR bitmap, return false to indicate that
10572 * we do not use the hardware.
10574 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
10575 struct vmcs12 *vmcs12)
10579 unsigned long *msr_bitmap_l1;
10580 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
10582 * pred_cmd & spec_ctrl are trying to verify two things:
10584 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
10585 * ensures that we do not accidentally generate an L02 MSR bitmap
10586 * from the L12 MSR bitmap that is too permissive.
10587 * 2. That L1 or L2s have actually used the MSR. This avoids
10588 * unnecessarily merging of the bitmap if the MSR is unused. This
10589 * works properly because we only update the L01 MSR bitmap lazily.
10590 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
10591 * updated to reflect this when L1 (or its L2s) actually write to
10594 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
10595 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
10597 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10598 !pred_cmd && !spec_ctrl)
10601 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
10602 if (is_error_page(page))
10604 msr_bitmap_l1 = (unsigned long *)kmap(page);
10606 memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
10608 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
10609 if (nested_cpu_has_apic_reg_virt(vmcs12))
10610 for (msr = 0x800; msr <= 0x8ff; msr++)
10611 nested_vmx_disable_intercept_for_msr(
10612 msr_bitmap_l1, msr_bitmap_l0,
10615 nested_vmx_disable_intercept_for_msr(
10616 msr_bitmap_l1, msr_bitmap_l0,
10617 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
10618 MSR_TYPE_R | MSR_TYPE_W);
10620 if (nested_cpu_has_vid(vmcs12)) {
10621 nested_vmx_disable_intercept_for_msr(
10622 msr_bitmap_l1, msr_bitmap_l0,
10623 APIC_BASE_MSR + (APIC_EOI >> 4),
10625 nested_vmx_disable_intercept_for_msr(
10626 msr_bitmap_l1, msr_bitmap_l0,
10627 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
10633 nested_vmx_disable_intercept_for_msr(
10634 msr_bitmap_l1, msr_bitmap_l0,
10635 MSR_IA32_SPEC_CTRL,
10636 MSR_TYPE_R | MSR_TYPE_W);
10639 nested_vmx_disable_intercept_for_msr(
10640 msr_bitmap_l1, msr_bitmap_l0,
10645 kvm_release_page_clean(page);
10650 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
10651 struct vmcs12 *vmcs12)
10653 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
10654 !page_address_valid(vcpu, vmcs12->apic_access_addr))
10660 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
10661 struct vmcs12 *vmcs12)
10663 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10664 !nested_cpu_has_apic_reg_virt(vmcs12) &&
10665 !nested_cpu_has_vid(vmcs12) &&
10666 !nested_cpu_has_posted_intr(vmcs12))
10670 * If virtualize x2apic mode is enabled,
10671 * virtualize apic access must be disabled.
10673 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10674 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10678 * If virtual interrupt delivery is enabled,
10679 * we must exit on external interrupts.
10681 if (nested_cpu_has_vid(vmcs12) &&
10682 !nested_exit_on_intr(vcpu))
10686 * bits 15:8 should be zero in posted_intr_nv,
10687 * the descriptor address has been already checked
10688 * in nested_get_vmcs12_pages.
10690 if (nested_cpu_has_posted_intr(vmcs12) &&
10691 (!nested_cpu_has_vid(vmcs12) ||
10692 !nested_exit_intr_ack_set(vcpu) ||
10693 vmcs12->posted_intr_nv & 0xff00))
10696 /* tpr shadow is needed by all apicv features. */
10697 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10703 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10704 unsigned long count_field,
10705 unsigned long addr_field)
10710 if (vmcs12_read_any(vcpu, count_field, &count) ||
10711 vmcs12_read_any(vcpu, addr_field, &addr)) {
10717 maxphyaddr = cpuid_maxphyaddr(vcpu);
10718 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10719 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10720 pr_debug_ratelimited(
10721 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10722 addr_field, maxphyaddr, count, addr);
10728 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10729 struct vmcs12 *vmcs12)
10731 if (vmcs12->vm_exit_msr_load_count == 0 &&
10732 vmcs12->vm_exit_msr_store_count == 0 &&
10733 vmcs12->vm_entry_msr_load_count == 0)
10734 return 0; /* Fast path */
10735 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10736 VM_EXIT_MSR_LOAD_ADDR) ||
10737 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10738 VM_EXIT_MSR_STORE_ADDR) ||
10739 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10740 VM_ENTRY_MSR_LOAD_ADDR))
10745 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
10746 struct vmcs12 *vmcs12)
10748 u64 address = vmcs12->pml_address;
10749 int maxphyaddr = cpuid_maxphyaddr(vcpu);
10751 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
10752 if (!nested_cpu_has_ept(vmcs12) ||
10753 !IS_ALIGNED(address, 4096) ||
10754 address >> maxphyaddr)
10761 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10762 struct vmx_msr_entry *e)
10764 /* x2APIC MSR accesses are not allowed */
10765 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10767 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10768 e->index == MSR_IA32_UCODE_REV)
10770 if (e->reserved != 0)
10775 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10776 struct vmx_msr_entry *e)
10778 if (e->index == MSR_FS_BASE ||
10779 e->index == MSR_GS_BASE ||
10780 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10781 nested_vmx_msr_check_common(vcpu, e))
10786 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10787 struct vmx_msr_entry *e)
10789 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10790 nested_vmx_msr_check_common(vcpu, e))
10796 * Load guest's/host's msr at nested entry/exit.
10797 * return 0 for success, entry index for failure.
10799 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10802 struct vmx_msr_entry e;
10803 struct msr_data msr;
10805 msr.host_initiated = false;
10806 for (i = 0; i < count; i++) {
10807 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10809 pr_debug_ratelimited(
10810 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10811 __func__, i, gpa + i * sizeof(e));
10814 if (nested_vmx_load_msr_check(vcpu, &e)) {
10815 pr_debug_ratelimited(
10816 "%s check failed (%u, 0x%x, 0x%x)\n",
10817 __func__, i, e.index, e.reserved);
10820 msr.index = e.index;
10821 msr.data = e.value;
10822 if (kvm_set_msr(vcpu, &msr)) {
10823 pr_debug_ratelimited(
10824 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10825 __func__, i, e.index, e.value);
10834 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10837 struct vmx_msr_entry e;
10839 for (i = 0; i < count; i++) {
10840 struct msr_data msr_info;
10841 if (kvm_vcpu_read_guest(vcpu,
10842 gpa + i * sizeof(e),
10843 &e, 2 * sizeof(u32))) {
10844 pr_debug_ratelimited(
10845 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10846 __func__, i, gpa + i * sizeof(e));
10849 if (nested_vmx_store_msr_check(vcpu, &e)) {
10850 pr_debug_ratelimited(
10851 "%s check failed (%u, 0x%x, 0x%x)\n",
10852 __func__, i, e.index, e.reserved);
10855 msr_info.host_initiated = false;
10856 msr_info.index = e.index;
10857 if (kvm_get_msr(vcpu, &msr_info)) {
10858 pr_debug_ratelimited(
10859 "%s cannot read MSR (%u, 0x%x)\n",
10860 __func__, i, e.index);
10863 if (kvm_vcpu_write_guest(vcpu,
10864 gpa + i * sizeof(e) +
10865 offsetof(struct vmx_msr_entry, value),
10866 &msr_info.data, sizeof(msr_info.data))) {
10867 pr_debug_ratelimited(
10868 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10869 __func__, i, e.index, msr_info.data);
10876 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
10878 unsigned long invalid_mask;
10880 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
10881 return (val & invalid_mask) == 0;
10885 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
10886 * emulating VM entry into a guest with EPT enabled.
10887 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10888 * is assigned to entry_failure_code on failure.
10890 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
10891 u32 *entry_failure_code)
10893 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
10894 if (!nested_cr3_valid(vcpu, cr3)) {
10895 *entry_failure_code = ENTRY_FAIL_DEFAULT;
10900 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
10901 * must not be dereferenced.
10903 if (is_pae_paging(vcpu) && !nested_ept) {
10904 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
10905 *entry_failure_code = ENTRY_FAIL_PDPTE;
10910 vcpu->arch.cr3 = cr3;
10911 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
10914 kvm_mmu_reset_context(vcpu);
10919 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10920 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10921 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10922 * guest in a way that will both be appropriate to L1's requests, and our
10923 * needs. In addition to modifying the active vmcs (which is vmcs02), this
10924 * function also has additional necessary side-effects, like setting various
10925 * vcpu->arch fields.
10926 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
10927 * is assigned to entry_failure_code on failure.
10929 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10930 bool from_vmentry, u32 *entry_failure_code)
10932 struct vcpu_vmx *vmx = to_vmx(vcpu);
10933 u32 exec_control, vmcs12_exec_ctrl;
10935 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10936 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10937 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10938 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10939 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10940 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10941 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10942 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10943 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10944 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10945 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10946 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10947 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10948 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10949 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10950 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10951 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10952 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10953 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10954 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10955 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10956 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10957 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10958 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10959 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10960 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10961 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10962 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10963 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10964 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10965 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10966 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10967 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10968 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10969 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10970 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10972 if (from_vmentry &&
10973 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
10974 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10975 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10977 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10978 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10980 if (from_vmentry) {
10981 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10982 vmcs12->vm_entry_intr_info_field);
10983 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10984 vmcs12->vm_entry_exception_error_code);
10985 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10986 vmcs12->vm_entry_instruction_len);
10987 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10988 vmcs12->guest_interruptibility_info);
10989 vmx->loaded_vmcs->nmi_known_unmasked =
10990 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
10992 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10994 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10995 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10996 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10997 vmcs12->guest_pending_dbg_exceptions);
10998 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10999 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
11001 if (nested_cpu_has_xsaves(vmcs12))
11002 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
11003 vmcs_write64(VMCS_LINK_POINTER, -1ull);
11005 exec_control = vmcs12->pin_based_vm_exec_control;
11007 /* Preemption timer setting is only taken from vmcs01. */
11008 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
11009 exec_control |= vmcs_config.pin_based_exec_ctrl;
11010 if (vmx->hv_deadline_tsc == -1)
11011 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
11013 /* Posted interrupts setting is only taken from vmcs12. */
11014 if (nested_cpu_has_posted_intr(vmcs12)) {
11015 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
11016 vmx->nested.pi_pending = false;
11017 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
11019 exec_control &= ~PIN_BASED_POSTED_INTR;
11022 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
11024 vmx->nested.preemption_timer_expired = false;
11025 if (nested_cpu_has_preemption_timer(vmcs12))
11026 vmx_start_preemption_timer(vcpu);
11029 * Whether page-faults are trapped is determined by a combination of
11030 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
11031 * If enable_ept, L0 doesn't care about page faults and we should
11032 * set all of these to L1's desires. However, if !enable_ept, L0 does
11033 * care about (at least some) page faults, and because it is not easy
11034 * (if at all possible?) to merge L0 and L1's desires, we simply ask
11035 * to exit on each and every L2 page fault. This is done by setting
11036 * MASK=MATCH=0 and (see below) EB.PF=1.
11037 * Note that below we don't need special code to set EB.PF beyond the
11038 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
11039 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
11040 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
11042 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
11043 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
11044 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
11045 enable_ept ? vmcs12->page_fault_error_code_match : 0);
11047 if (cpu_has_secondary_exec_ctrls()) {
11048 exec_control = vmx->secondary_exec_control;
11050 /* Take the following fields only from vmcs12 */
11051 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11052 SECONDARY_EXEC_ENABLE_INVPCID |
11053 SECONDARY_EXEC_RDTSCP |
11054 SECONDARY_EXEC_XSAVES |
11055 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
11056 SECONDARY_EXEC_APIC_REGISTER_VIRT |
11057 SECONDARY_EXEC_ENABLE_VMFUNC);
11058 if (nested_cpu_has(vmcs12,
11059 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
11060 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
11061 ~SECONDARY_EXEC_ENABLE_PML;
11062 exec_control |= vmcs12_exec_ctrl;
11065 /* All VMFUNCs are currently emulated through L0 vmexits. */
11066 if (exec_control & SECONDARY_EXEC_ENABLE_VMFUNC)
11067 vmcs_write64(VM_FUNCTION_CONTROL, 0);
11069 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
11070 vmcs_write64(EOI_EXIT_BITMAP0,
11071 vmcs12->eoi_exit_bitmap0);
11072 vmcs_write64(EOI_EXIT_BITMAP1,
11073 vmcs12->eoi_exit_bitmap1);
11074 vmcs_write64(EOI_EXIT_BITMAP2,
11075 vmcs12->eoi_exit_bitmap2);
11076 vmcs_write64(EOI_EXIT_BITMAP3,
11077 vmcs12->eoi_exit_bitmap3);
11078 vmcs_write16(GUEST_INTR_STATUS,
11079 vmcs12->guest_intr_status);
11083 * Write an illegal value to APIC_ACCESS_ADDR. Later,
11084 * nested_get_vmcs12_pages will either fix it up or
11085 * remove the VM execution control.
11087 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
11088 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
11090 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
11095 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
11096 * Some constant fields are set here by vmx_set_constant_host_state().
11097 * Other fields are different per CPU, and will be set later when
11098 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
11100 vmx_set_constant_host_state(vmx);
11103 * Set the MSR load/store lists to match L0's settings.
11105 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
11106 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
11107 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
11108 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
11109 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
11112 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
11113 * entry, but only if the current (host) sp changed from the value
11114 * we wrote last (vmx->host_rsp). This cache is no longer relevant
11115 * if we switch vmcs, and rather than hold a separate cache per vmcs,
11116 * here we just force the write to happen on entry.
11120 exec_control = vmx_exec_control(vmx); /* L0's desires */
11121 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
11122 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
11123 exec_control &= ~CPU_BASED_TPR_SHADOW;
11124 exec_control |= vmcs12->cpu_based_vm_exec_control;
11127 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
11128 * nested_get_vmcs12_pages can't fix it up, the illegal value
11129 * will result in a VM entry failure.
11131 if (exec_control & CPU_BASED_TPR_SHADOW) {
11132 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
11133 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
11135 #ifdef CONFIG_X86_64
11136 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
11137 CPU_BASED_CR8_STORE_EXITING;
11142 * Merging of IO bitmap not currently supported.
11143 * Rather, exit every time.
11145 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
11146 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
11148 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
11150 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
11151 * bitwise-or of what L1 wants to trap for L2, and what we want to
11152 * trap. Note that CR0.TS also needs updating - we do this later.
11154 update_exception_bitmap(vcpu);
11155 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
11156 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
11158 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
11159 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
11160 * bits are further modified by vmx_set_efer() below.
11162 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
11164 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
11165 * emulated by vmx_set_efer(), below.
11167 vm_entry_controls_init(vmx,
11168 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
11169 ~VM_ENTRY_IA32E_MODE) |
11170 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
11172 if (from_vmentry &&
11173 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
11174 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
11175 vcpu->arch.pat = vmcs12->guest_ia32_pat;
11176 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
11177 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
11180 set_cr4_guest_host_mask(vmx);
11182 if (from_vmentry &&
11183 vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
11184 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
11186 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
11187 vmcs_write64(TSC_OFFSET,
11188 vcpu->arch.tsc_offset + vmcs12->tsc_offset);
11190 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11191 if (kvm_has_tsc_control)
11192 decache_tsc_multiplier(vmx);
11194 if (cpu_has_vmx_msr_bitmap())
11195 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
11199 * There is no direct mapping between vpid02 and vpid12, the
11200 * vpid02 is per-vCPU for L0 and reused while the value of
11201 * vpid12 is changed w/ one invvpid during nested vmentry.
11202 * The vpid12 is allocated by L1 for L2, so it will not
11203 * influence global bitmap(for vpid01 and vpid02 allocation)
11204 * even if spawn a lot of nested vCPUs.
11206 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
11207 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
11208 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
11209 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
11210 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02, true);
11213 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
11214 vmx_flush_tlb(vcpu, true);
11221 * Conceptually we want to copy the PML address and index from
11222 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
11223 * since we always flush the log on each vmexit, this happens
11224 * to be equivalent to simply resetting the fields in vmcs02.
11226 ASSERT(vmx->pml_pg);
11227 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
11228 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
11231 if (nested_cpu_has_ept(vmcs12)) {
11232 if (nested_ept_init_mmu_context(vcpu)) {
11233 *entry_failure_code = ENTRY_FAIL_DEFAULT;
11236 } else if (nested_cpu_has2(vmcs12,
11237 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11238 vmx_flush_tlb(vcpu, true);
11242 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
11243 * bits which we consider mandatory enabled.
11244 * The CR0_READ_SHADOW is what L2 should have expected to read given
11245 * the specifications by L1; It's not enough to take
11246 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
11247 * have more bits than L1 expected.
11249 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
11250 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
11252 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
11253 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
11255 if (from_vmentry &&
11256 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
11257 vcpu->arch.efer = vmcs12->guest_ia32_efer;
11258 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
11259 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11261 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11262 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
11263 vmx_set_efer(vcpu, vcpu->arch.efer);
11265 /* Shadow page tables on either EPT or shadow page tables. */
11266 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
11267 entry_failure_code))
11271 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
11274 * L1 may access the L2's PDPTR, so save them to construct vmcs12
11277 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
11278 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
11279 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
11280 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
11283 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
11284 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
11288 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11290 struct vcpu_vmx *vmx = to_vmx(vcpu);
11292 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
11293 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
11294 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11296 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
11297 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11299 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
11300 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11302 if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
11303 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11305 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
11306 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11308 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
11309 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11311 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
11312 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11314 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
11315 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11317 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
11318 vmx->nested.nested_vmx_procbased_ctls_low,
11319 vmx->nested.nested_vmx_procbased_ctls_high) ||
11320 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
11321 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
11322 vmx->nested.nested_vmx_secondary_ctls_low,
11323 vmx->nested.nested_vmx_secondary_ctls_high)) ||
11324 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
11325 vmx->nested.nested_vmx_pinbased_ctls_low,
11326 vmx->nested.nested_vmx_pinbased_ctls_high) ||
11327 !vmx_control_verify(vmcs12->vm_exit_controls,
11328 vmx->nested.nested_vmx_exit_ctls_low,
11329 vmx->nested.nested_vmx_exit_ctls_high) ||
11330 !vmx_control_verify(vmcs12->vm_entry_controls,
11331 vmx->nested.nested_vmx_entry_ctls_low,
11332 vmx->nested.nested_vmx_entry_ctls_high))
11333 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11335 if (nested_cpu_has_vmfunc(vmcs12)) {
11336 if (vmcs12->vm_function_control &
11337 ~vmx->nested.nested_vmx_vmfunc_controls)
11338 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11340 if (nested_cpu_has_eptp_switching(vmcs12)) {
11341 if (!nested_cpu_has_ept(vmcs12) ||
11342 !page_address_valid(vcpu, vmcs12->eptp_list_address))
11343 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11347 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
11348 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
11350 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
11351 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
11352 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
11353 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
11358 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11363 *exit_qual = ENTRY_FAIL_DEFAULT;
11365 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
11366 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
11369 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS) &&
11370 vmcs12->vmcs_link_pointer != -1ull) {
11371 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
11376 * If the load IA32_EFER VM-entry control is 1, the following checks
11377 * are performed on the field for the IA32_EFER MSR:
11378 * - Bits reserved in the IA32_EFER MSR must be 0.
11379 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
11380 * the IA-32e mode guest VM-exit control. It must also be identical
11381 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
11384 if (to_vmx(vcpu)->nested.nested_run_pending &&
11385 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
11386 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
11387 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
11388 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
11389 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
11390 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
11395 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
11396 * IA32_EFER MSR must be 0 in the field for that register. In addition,
11397 * the values of the LMA and LME bits in the field must each be that of
11398 * the host address-space size VM-exit control.
11400 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
11401 ia32e = (vmcs12->vm_exit_controls &
11402 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
11403 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
11404 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
11405 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
11412 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, bool from_vmentry)
11414 struct vcpu_vmx *vmx = to_vmx(vcpu);
11415 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11419 enter_guest_mode(vcpu);
11421 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
11422 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11424 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
11425 vmx_segment_cache_clear(vmx);
11427 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry, &exit_qual)) {
11428 leave_guest_mode(vcpu);
11429 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11430 nested_vmx_entry_failure(vcpu, vmcs12,
11431 EXIT_REASON_INVALID_STATE, exit_qual);
11435 nested_get_vmcs12_pages(vcpu, vmcs12);
11437 msr_entry_idx = nested_vmx_load_msr(vcpu,
11438 vmcs12->vm_entry_msr_load_addr,
11439 vmcs12->vm_entry_msr_load_count);
11440 if (msr_entry_idx) {
11441 leave_guest_mode(vcpu);
11442 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11443 nested_vmx_entry_failure(vcpu, vmcs12,
11444 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
11449 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
11450 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
11451 * returned as far as L1 is concerned. It will only return (and set
11452 * the success flag) when L2 exits (see nested_vmx_vmexit()).
11458 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
11459 * for running an L2 nested guest.
11461 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
11463 struct vmcs12 *vmcs12;
11464 struct vcpu_vmx *vmx = to_vmx(vcpu);
11465 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
11469 if (!nested_vmx_check_permission(vcpu))
11472 if (!nested_vmx_check_vmcs12(vcpu))
11475 vmcs12 = get_vmcs12(vcpu);
11477 if (enable_shadow_vmcs)
11478 copy_shadow_to_vmcs12(vmx);
11481 * The nested entry process starts with enforcing various prerequisites
11482 * on vmcs12 as required by the Intel SDM, and act appropriately when
11483 * they fail: As the SDM explains, some conditions should cause the
11484 * instruction to fail, while others will cause the instruction to seem
11485 * to succeed, but return an EXIT_REASON_INVALID_STATE.
11486 * To speed up the normal (success) code path, we should avoid checking
11487 * for misconfigurations which will anyway be caught by the processor
11488 * when using the merged vmcs02.
11490 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
11491 nested_vmx_failValid(vcpu,
11492 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
11496 if (vmcs12->launch_state == launch) {
11497 nested_vmx_failValid(vcpu,
11498 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
11499 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
11503 ret = check_vmentry_prereqs(vcpu, vmcs12);
11505 nested_vmx_failValid(vcpu, ret);
11510 * After this point, the trap flag no longer triggers a singlestep trap
11511 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
11512 * This is not 100% correct; for performance reasons, we delegate most
11513 * of the checks on host state to the processor. If those fail,
11514 * the singlestep trap is missed.
11516 skip_emulated_instruction(vcpu);
11518 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
11520 nested_vmx_entry_failure(vcpu, vmcs12,
11521 EXIT_REASON_INVALID_STATE, exit_qual);
11526 * We're finally done with prerequisite checking, and can start with
11527 * the nested entry.
11530 ret = enter_vmx_non_root_mode(vcpu, true);
11534 /* Hide L1D cache contents from the nested guest. */
11535 vmx->vcpu.arch.l1tf_flush_l1d = true;
11538 * If we're entering a halted L2 vcpu and the L2 vcpu won't be woken
11539 * by event injection, halt vcpu.
11541 if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
11542 !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK))
11543 return kvm_vcpu_halt(vcpu);
11545 vmx->nested.nested_run_pending = 1;
11550 return kvm_skip_emulated_instruction(vcpu);
11554 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
11555 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
11556 * This function returns the new value we should put in vmcs12.guest_cr0.
11557 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
11558 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
11559 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
11560 * didn't trap the bit, because if L1 did, so would L0).
11561 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
11562 * been modified by L2, and L1 knows it. So just leave the old value of
11563 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
11564 * isn't relevant, because if L0 traps this bit it can set it to anything.
11565 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
11566 * changed these bits, and therefore they need to be updated, but L0
11567 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
11568 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
11570 static inline unsigned long
11571 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11574 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
11575 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
11576 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
11577 vcpu->arch.cr0_guest_owned_bits));
11580 static inline unsigned long
11581 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11584 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
11585 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
11586 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
11587 vcpu->arch.cr4_guest_owned_bits));
11590 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
11591 struct vmcs12 *vmcs12)
11596 if (vcpu->arch.exception.injected) {
11597 nr = vcpu->arch.exception.nr;
11598 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11600 if (kvm_exception_is_soft(nr)) {
11601 vmcs12->vm_exit_instruction_len =
11602 vcpu->arch.event_exit_inst_len;
11603 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
11605 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
11607 if (vcpu->arch.exception.has_error_code) {
11608 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
11609 vmcs12->idt_vectoring_error_code =
11610 vcpu->arch.exception.error_code;
11613 vmcs12->idt_vectoring_info_field = idt_vectoring;
11614 } else if (vcpu->arch.nmi_injected) {
11615 vmcs12->idt_vectoring_info_field =
11616 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
11617 } else if (vcpu->arch.interrupt.pending) {
11618 nr = vcpu->arch.interrupt.nr;
11619 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
11621 if (vcpu->arch.interrupt.soft) {
11622 idt_vectoring |= INTR_TYPE_SOFT_INTR;
11623 vmcs12->vm_entry_instruction_len =
11624 vcpu->arch.event_exit_inst_len;
11626 idt_vectoring |= INTR_TYPE_EXT_INTR;
11628 vmcs12->idt_vectoring_info_field = idt_vectoring;
11632 static int vmx_check_nested_events(struct kvm_vcpu *vcpu)
11634 struct vcpu_vmx *vmx = to_vmx(vcpu);
11635 unsigned long exit_qual;
11636 bool block_nested_events =
11637 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
11639 if (vcpu->arch.exception.pending &&
11640 nested_vmx_check_exception(vcpu, &exit_qual)) {
11641 if (block_nested_events)
11643 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
11647 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
11648 vmx->nested.preemption_timer_expired) {
11649 if (block_nested_events)
11651 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
11655 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
11656 if (block_nested_events)
11658 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11659 NMI_VECTOR | INTR_TYPE_NMI_INTR |
11660 INTR_INFO_VALID_MASK, 0);
11662 * The NMI-triggered VM exit counts as injection:
11663 * clear this one and block further NMIs.
11665 vcpu->arch.nmi_pending = 0;
11666 vmx_set_nmi_mask(vcpu, true);
11670 if (kvm_cpu_has_interrupt(vcpu) && nested_exit_on_intr(vcpu)) {
11671 if (block_nested_events)
11673 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
11677 vmx_complete_nested_posted_interrupt(vcpu);
11681 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
11683 ktime_t remaining =
11684 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
11687 if (ktime_to_ns(remaining) <= 0)
11690 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
11691 do_div(value, 1000000);
11692 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11696 * Update the guest state fields of vmcs12 to reflect changes that
11697 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
11698 * VM-entry controls is also updated, since this is really a guest
11701 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
11703 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
11704 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
11706 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
11707 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
11708 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
11710 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
11711 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
11712 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
11713 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
11714 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
11715 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
11716 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
11717 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
11718 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
11719 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
11720 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
11721 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
11722 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
11723 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
11724 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
11725 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
11726 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
11727 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
11728 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
11729 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
11730 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
11731 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
11732 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
11733 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
11734 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
11735 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
11736 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
11737 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
11738 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
11739 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
11740 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
11741 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
11742 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
11743 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
11744 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
11745 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
11747 vmcs12->guest_interruptibility_info =
11748 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
11749 vmcs12->guest_pending_dbg_exceptions =
11750 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
11751 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
11752 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
11754 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
11756 if (nested_cpu_has_preemption_timer(vmcs12)) {
11757 if (vmcs12->vm_exit_controls &
11758 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
11759 vmcs12->vmx_preemption_timer_value =
11760 vmx_get_preemption_timer_value(vcpu);
11761 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
11765 * In some cases (usually, nested EPT), L2 is allowed to change its
11766 * own CR3 without exiting. If it has changed it, we must keep it.
11767 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
11768 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
11770 * Additionally, restore L2's PDPTR to vmcs12.
11773 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
11774 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
11775 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
11776 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
11777 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
11780 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
11782 if (nested_cpu_has_vid(vmcs12))
11783 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
11785 vmcs12->vm_entry_controls =
11786 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
11787 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
11789 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
11790 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
11791 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11794 /* TODO: These cannot have changed unless we have MSR bitmaps and
11795 * the relevant bit asks not to trap the change */
11796 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11797 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11798 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11799 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11800 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11801 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11802 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11803 if (kvm_mpx_supported())
11804 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11808 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
11809 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
11810 * and this function updates it to reflect the changes to the guest state while
11811 * L2 was running (and perhaps made some exits which were handled directly by L0
11812 * without going back to L1), and to reflect the exit reason.
11813 * Note that we do not have to copy here all VMCS fields, just those that
11814 * could have changed by the L2 guest or the exit - i.e., the guest-state and
11815 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
11816 * which already writes to vmcs12 directly.
11818 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
11819 u32 exit_reason, u32 exit_intr_info,
11820 unsigned long exit_qualification)
11822 /* update guest state fields: */
11823 sync_vmcs12(vcpu, vmcs12);
11825 /* update exit information fields: */
11827 vmcs12->vm_exit_reason = exit_reason;
11828 vmcs12->exit_qualification = exit_qualification;
11829 vmcs12->vm_exit_intr_info = exit_intr_info;
11831 vmcs12->idt_vectoring_info_field = 0;
11832 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11833 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11835 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11836 vmcs12->launch_state = 1;
11838 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11839 * instead of reading the real value. */
11840 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11843 * Transfer the event that L0 or L1 may wanted to inject into
11844 * L2 to IDT_VECTORING_INFO_FIELD.
11846 vmcs12_save_pending_event(vcpu, vmcs12);
11850 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11851 * preserved above and would only end up incorrectly in L1.
11853 vcpu->arch.nmi_injected = false;
11854 kvm_clear_exception_queue(vcpu);
11855 kvm_clear_interrupt_queue(vcpu);
11859 * A part of what we need to when the nested L2 guest exits and we want to
11860 * run its L1 parent, is to reset L1's guest state to the host state specified
11862 * This function is to be called not only on normal nested exit, but also on
11863 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11864 * Failures During or After Loading Guest State").
11865 * This function should be called when the active VMCS is L1's (vmcs01).
11867 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11868 struct vmcs12 *vmcs12)
11870 struct kvm_segment seg;
11871 u32 entry_failure_code;
11873 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11874 vcpu->arch.efer = vmcs12->host_ia32_efer;
11875 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11876 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11878 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11879 vmx_set_efer(vcpu, vcpu->arch.efer);
11881 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11882 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11883 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11885 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11886 * actually changed, because vmx_set_cr0 refers to efer set above.
11888 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
11889 * (KVM doesn't change it);
11891 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
11892 vmx_set_cr0(vcpu, vmcs12->host_cr0);
11894 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
11895 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11896 vmx_set_cr4(vcpu, vmcs12->host_cr4);
11898 nested_ept_uninit_mmu_context(vcpu);
11901 * Only PDPTE load can fail as the value of cr3 was checked on entry and
11902 * couldn't have changed.
11904 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
11905 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
11908 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11912 * Trivially support vpid by letting L2s share their parent
11913 * L1's vpid. TODO: move to a more elaborate solution, giving
11914 * each L2 its own vpid and exposing the vpid feature to L1.
11916 vmx_flush_tlb(vcpu, true);
11918 /* Restore posted intr vector. */
11919 if (nested_cpu_has_posted_intr(vmcs12))
11920 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
11922 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11923 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11924 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11925 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11926 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11927 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11928 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11930 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
11931 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11932 vmcs_write64(GUEST_BNDCFGS, 0);
11934 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11935 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11936 vcpu->arch.pat = vmcs12->host_ia32_pat;
11938 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11939 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11940 vmcs12->host_ia32_perf_global_ctrl);
11942 /* Set L1 segment info according to Intel SDM
11943 27.5.2 Loading Host Segment and Descriptor-Table Registers */
11944 seg = (struct kvm_segment) {
11946 .limit = 0xFFFFFFFF,
11947 .selector = vmcs12->host_cs_selector,
11953 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11957 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11958 seg = (struct kvm_segment) {
11960 .limit = 0xFFFFFFFF,
11967 seg.selector = vmcs12->host_ds_selector;
11968 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11969 seg.selector = vmcs12->host_es_selector;
11970 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11971 seg.selector = vmcs12->host_ss_selector;
11972 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11973 seg.selector = vmcs12->host_fs_selector;
11974 seg.base = vmcs12->host_fs_base;
11975 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11976 seg.selector = vmcs12->host_gs_selector;
11977 seg.base = vmcs12->host_gs_base;
11978 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11979 seg = (struct kvm_segment) {
11980 .base = vmcs12->host_tr_base,
11982 .selector = vmcs12->host_tr_selector,
11986 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11988 kvm_set_dr(vcpu, 7, 0x400);
11989 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11991 if (cpu_has_vmx_msr_bitmap())
11992 vmx_update_msr_bitmap(vcpu);
11994 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11995 vmcs12->vm_exit_msr_load_count))
11996 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11999 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
12001 struct shared_msr_entry *efer_msr;
12004 if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
12005 return vmcs_read64(GUEST_IA32_EFER);
12007 if (cpu_has_load_ia32_efer)
12010 for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
12011 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
12012 return vmx->msr_autoload.guest.val[i].value;
12015 efer_msr = find_msr_entry(vmx, MSR_EFER);
12017 return efer_msr->data;
12022 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
12024 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12025 struct vcpu_vmx *vmx = to_vmx(vcpu);
12026 struct vmx_msr_entry g, h;
12027 struct msr_data msr;
12031 vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
12033 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
12035 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
12036 * as vmcs01.GUEST_DR7 contains a userspace defined value
12037 * and vcpu->arch.dr7 is not squirreled away before the
12038 * nested VMENTER (not worth adding a variable in nested_vmx).
12040 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
12041 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
12043 WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
12047 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
12048 * handle a variety of side effects to KVM's software model.
12050 vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
12052 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
12053 vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
12055 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
12056 vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
12058 nested_ept_uninit_mmu_context(vcpu);
12059 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
12060 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12063 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
12064 * from vmcs01 (if necessary). The PDPTRs are not loaded on
12065 * VMFail, like everything else we just need to ensure our
12066 * software model is up-to-date.
12068 ept_save_pdptrs(vcpu);
12070 kvm_mmu_reset_context(vcpu);
12072 if (cpu_has_vmx_msr_bitmap())
12073 vmx_update_msr_bitmap(vcpu);
12076 * This nasty bit of open coding is a compromise between blindly
12077 * loading L1's MSRs using the exit load lists (incorrect emulation
12078 * of VMFail), leaving the nested VM's MSRs in the software model
12079 * (incorrect behavior) and snapshotting the modified MSRs (too
12080 * expensive since the lists are unbound by hardware). For each
12081 * MSR that was (prematurely) loaded from the nested VMEntry load
12082 * list, reload it from the exit load list if it exists and differs
12083 * from the guest value. The intent is to stuff host state as
12084 * silently as possible, not to fully process the exit load list.
12086 msr.host_initiated = false;
12087 for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
12088 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
12089 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
12090 pr_debug_ratelimited(
12091 "%s read MSR index failed (%u, 0x%08llx)\n",
12096 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
12097 gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
12098 if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
12099 pr_debug_ratelimited(
12100 "%s read MSR failed (%u, 0x%08llx)\n",
12104 if (h.index != g.index)
12106 if (h.value == g.value)
12109 if (nested_vmx_load_msr_check(vcpu, &h)) {
12110 pr_debug_ratelimited(
12111 "%s check failed (%u, 0x%x, 0x%x)\n",
12112 __func__, j, h.index, h.reserved);
12116 msr.index = h.index;
12117 msr.data = h.value;
12118 if (kvm_set_msr(vcpu, &msr)) {
12119 pr_debug_ratelimited(
12120 "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
12121 __func__, j, h.index, h.value);
12130 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
12134 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
12135 * and modify vmcs12 to make it see what it would expect to see there if
12136 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
12138 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
12139 u32 exit_intr_info,
12140 unsigned long exit_qualification)
12142 struct vcpu_vmx *vmx = to_vmx(vcpu);
12143 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12145 /* trying to cancel vmlaunch/vmresume is a bug */
12146 WARN_ON_ONCE(vmx->nested.nested_run_pending);
12149 * The only expected VM-instruction error is "VM entry with
12150 * invalid control field(s)." Anything else indicates a
12153 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
12154 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
12156 leave_guest_mode(vcpu);
12158 if (likely(!vmx->fail)) {
12159 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
12160 exit_qualification);
12162 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
12163 vmcs12->vm_exit_msr_store_count))
12164 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
12167 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12168 vm_entry_controls_reset_shadow(vmx);
12169 vm_exit_controls_reset_shadow(vmx);
12170 vmx_segment_cache_clear(vmx);
12172 /* Update any VMCS fields that might have changed while L2 ran */
12173 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12174 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12175 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12176 if (vmx->hv_deadline_tsc == -1)
12177 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
12178 PIN_BASED_VMX_PREEMPTION_TIMER);
12180 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
12181 PIN_BASED_VMX_PREEMPTION_TIMER);
12182 if (kvm_has_tsc_control)
12183 decache_tsc_multiplier(vmx);
12185 if (vmx->nested.change_vmcs01_virtual_apic_mode) {
12186 vmx->nested.change_vmcs01_virtual_apic_mode = false;
12187 vmx_set_virtual_apic_mode(vcpu);
12188 } else if (!nested_cpu_has_ept(vmcs12) &&
12189 nested_cpu_has2(vmcs12,
12190 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12191 vmx_flush_tlb(vcpu, true);
12194 /* This is needed for same reason as it was needed in prepare_vmcs02 */
12197 /* Unpin physical memory we referred to in vmcs02 */
12198 if (vmx->nested.apic_access_page) {
12199 kvm_release_page_dirty(vmx->nested.apic_access_page);
12200 vmx->nested.apic_access_page = NULL;
12202 if (vmx->nested.virtual_apic_page) {
12203 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
12204 vmx->nested.virtual_apic_page = NULL;
12206 if (vmx->nested.pi_desc_page) {
12207 kunmap(vmx->nested.pi_desc_page);
12208 kvm_release_page_dirty(vmx->nested.pi_desc_page);
12209 vmx->nested.pi_desc_page = NULL;
12210 vmx->nested.pi_desc = NULL;
12214 * We are now running in L2, mmu_notifier will force to reload the
12215 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
12217 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
12219 if (enable_shadow_vmcs)
12220 vmx->nested.sync_shadow_vmcs = true;
12222 /* in case we halted in L2 */
12223 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
12225 if (likely(!vmx->fail)) {
12226 if (exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
12227 nested_exit_intr_ack_set(vcpu)) {
12228 int irq = kvm_cpu_get_interrupt(vcpu);
12230 vmcs12->vm_exit_intr_info = irq |
12231 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
12234 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
12235 vmcs12->exit_qualification,
12236 vmcs12->idt_vectoring_info_field,
12237 vmcs12->vm_exit_intr_info,
12238 vmcs12->vm_exit_intr_error_code,
12241 load_vmcs12_host_state(vcpu, vmcs12);
12247 * After an early L2 VM-entry failure, we're now back
12248 * in L1 which thinks it just finished a VMLAUNCH or
12249 * VMRESUME instruction, so we need to set the failure
12250 * flag and the VM-instruction error field of the VMCS
12253 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
12256 * Restore L1's host state to KVM's software model. We're here
12257 * because a consistency check was caught by hardware, which
12258 * means some amount of guest state has been propagated to KVM's
12259 * model and needs to be unwound to the host's state.
12261 nested_vmx_restore_host_state(vcpu);
12264 * The emulated instruction was already skipped in
12265 * nested_vmx_run, but the updated RIP was never
12266 * written back to the vmcs01.
12268 skip_emulated_instruction(vcpu);
12273 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
12275 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
12277 if (is_guest_mode(vcpu)) {
12278 to_vmx(vcpu)->nested.nested_run_pending = 0;
12279 nested_vmx_vmexit(vcpu, -1, 0, 0);
12281 free_nested(to_vmx(vcpu));
12285 * L1's failure to enter L2 is a subset of a normal exit, as explained in
12286 * 23.7 "VM-entry failures during or after loading guest state" (this also
12287 * lists the acceptable exit-reason and exit-qualification parameters).
12288 * It should only be called before L2 actually succeeded to run, and when
12289 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
12291 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
12292 struct vmcs12 *vmcs12,
12293 u32 reason, unsigned long qualification)
12295 load_vmcs12_host_state(vcpu, vmcs12);
12296 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
12297 vmcs12->exit_qualification = qualification;
12298 nested_vmx_succeed(vcpu);
12299 if (enable_shadow_vmcs)
12300 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
12303 static int vmx_check_intercept_io(struct kvm_vcpu *vcpu,
12304 struct x86_instruction_info *info)
12306 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12307 unsigned short port;
12311 if (info->intercept == x86_intercept_in ||
12312 info->intercept == x86_intercept_ins) {
12313 port = info->src_val;
12314 size = info->dst_bytes;
12316 port = info->dst_val;
12317 size = info->src_bytes;
12321 * If the 'use IO bitmaps' VM-execution control is 0, IO instruction
12322 * VM-exits depend on the 'unconditional IO exiting' VM-execution
12325 * Otherwise, IO instruction VM-exits are controlled by the IO bitmaps.
12327 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
12328 intercept = nested_cpu_has(vmcs12,
12329 CPU_BASED_UNCOND_IO_EXITING);
12331 intercept = nested_vmx_check_io_bitmaps(vcpu, port, size);
12333 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
12334 return intercept ? X86EMUL_UNHANDLEABLE : X86EMUL_CONTINUE;
12337 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
12338 struct x86_instruction_info *info,
12339 enum x86_intercept_stage stage)
12341 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12342 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
12344 switch (info->intercept) {
12346 * RDPID causes #UD if disabled through secondary execution controls.
12347 * Because it is marked as EmulateOnUD, we need to intercept it here.
12349 case x86_intercept_rdtscp:
12350 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
12351 ctxt->exception.vector = UD_VECTOR;
12352 ctxt->exception.error_code_valid = false;
12353 return X86EMUL_PROPAGATE_FAULT;
12357 case x86_intercept_in:
12358 case x86_intercept_ins:
12359 case x86_intercept_out:
12360 case x86_intercept_outs:
12361 return vmx_check_intercept_io(vcpu, info);
12363 case x86_intercept_lgdt:
12364 case x86_intercept_lidt:
12365 case x86_intercept_lldt:
12366 case x86_intercept_ltr:
12367 case x86_intercept_sgdt:
12368 case x86_intercept_sidt:
12369 case x86_intercept_sldt:
12370 case x86_intercept_str:
12371 if (!nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC))
12372 return X86EMUL_CONTINUE;
12374 /* FIXME: produce nested vmexit and return X86EMUL_INTERCEPTED. */
12377 /* TODO: check more intercepts... */
12382 return X86EMUL_UNHANDLEABLE;
12385 #ifdef CONFIG_X86_64
12386 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
12387 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
12388 u64 divisor, u64 *result)
12390 u64 low = a << shift, high = a >> (64 - shift);
12392 /* To avoid the overflow on divq */
12393 if (high >= divisor)
12396 /* Low hold the result, high hold rem which is discarded */
12397 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
12398 "rm" (divisor), "0" (low), "1" (high));
12404 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
12406 struct vcpu_vmx *vmx = to_vmx(vcpu);
12407 u64 tscl = rdtsc();
12408 u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
12409 u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
12411 /* Convert to host delta tsc if tsc scaling is enabled */
12412 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
12413 u64_shl_div_u64(delta_tsc,
12414 kvm_tsc_scaling_ratio_frac_bits,
12415 vcpu->arch.tsc_scaling_ratio,
12420 * If the delta tsc can't fit in the 32 bit after the multi shift,
12421 * we can't use the preemption timer.
12422 * It's possible that it fits on later vmentries, but checking
12423 * on every vmentry is costly so we just use an hrtimer.
12425 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
12428 vmx->hv_deadline_tsc = tscl + delta_tsc;
12429 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
12430 PIN_BASED_VMX_PREEMPTION_TIMER);
12432 return delta_tsc == 0;
12435 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
12437 struct vcpu_vmx *vmx = to_vmx(vcpu);
12438 vmx->hv_deadline_tsc = -1;
12439 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
12440 PIN_BASED_VMX_PREEMPTION_TIMER);
12444 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
12447 shrink_ple_window(vcpu);
12450 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
12451 struct kvm_memory_slot *slot)
12453 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
12454 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
12457 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
12458 struct kvm_memory_slot *slot)
12460 kvm_mmu_slot_set_dirty(kvm, slot);
12463 static void vmx_flush_log_dirty(struct kvm *kvm)
12465 kvm_flush_pml_buffers(kvm);
12468 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu, gpa_t gpa)
12470 struct vmcs12 *vmcs12;
12471 struct vcpu_vmx *vmx = to_vmx(vcpu);
12472 struct page *page = NULL;
12475 if (is_guest_mode(vcpu)) {
12476 WARN_ON_ONCE(vmx->nested.pml_full);
12479 * Check if PML is enabled for the nested guest.
12480 * Whether eptp bit 6 is set is already checked
12481 * as part of A/D emulation.
12483 vmcs12 = get_vmcs12(vcpu);
12484 if (!nested_cpu_has_pml(vmcs12))
12487 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
12488 vmx->nested.pml_full = true;
12494 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
12495 if (is_error_page(page))
12498 pml_address = kmap(page);
12499 pml_address[vmcs12->guest_pml_index--] = gpa;
12501 kvm_release_page_clean(page);
12507 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
12508 struct kvm_memory_slot *memslot,
12509 gfn_t offset, unsigned long mask)
12511 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
12514 static void __pi_post_block(struct kvm_vcpu *vcpu)
12516 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12517 struct pi_desc old, new;
12521 old.control = new.control = pi_desc->control;
12522 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
12523 "Wakeup handler not enabled while the VCPU is blocked\n");
12525 dest = cpu_physical_id(vcpu->cpu);
12527 if (x2apic_enabled())
12530 new.ndst = (dest << 8) & 0xFF00;
12532 /* set 'NV' to 'notification vector' */
12533 new.nv = POSTED_INTR_VECTOR;
12534 } while (cmpxchg64(&pi_desc->control, old.control,
12535 new.control) != old.control);
12537 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
12538 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12539 list_del(&vcpu->blocked_vcpu_list);
12540 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12541 vcpu->pre_pcpu = -1;
12546 * This routine does the following things for vCPU which is going
12547 * to be blocked if VT-d PI is enabled.
12548 * - Store the vCPU to the wakeup list, so when interrupts happen
12549 * we can find the right vCPU to wake up.
12550 * - Change the Posted-interrupt descriptor as below:
12551 * 'NDST' <-- vcpu->pre_pcpu
12552 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
12553 * - If 'ON' is set during this process, which means at least one
12554 * interrupt is posted for this vCPU, we cannot block it, in
12555 * this case, return 1, otherwise, return 0.
12558 static int pi_pre_block(struct kvm_vcpu *vcpu)
12561 struct pi_desc old, new;
12562 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
12564 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
12565 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12566 !kvm_vcpu_apicv_active(vcpu))
12569 WARN_ON(irqs_disabled());
12570 local_irq_disable();
12571 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
12572 vcpu->pre_pcpu = vcpu->cpu;
12573 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12574 list_add_tail(&vcpu->blocked_vcpu_list,
12575 &per_cpu(blocked_vcpu_on_cpu,
12577 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
12581 old.control = new.control = pi_desc->control;
12583 WARN((pi_desc->sn == 1),
12584 "Warning: SN field of posted-interrupts "
12585 "is set before blocking\n");
12588 * Since vCPU can be preempted during this process,
12589 * vcpu->cpu could be different with pre_pcpu, we
12590 * need to set pre_pcpu as the destination of wakeup
12591 * notification event, then we can find the right vCPU
12592 * to wakeup in wakeup handler if interrupts happen
12593 * when the vCPU is in blocked state.
12595 dest = cpu_physical_id(vcpu->pre_pcpu);
12597 if (x2apic_enabled())
12600 new.ndst = (dest << 8) & 0xFF00;
12602 /* set 'NV' to 'wakeup vector' */
12603 new.nv = POSTED_INTR_WAKEUP_VECTOR;
12604 } while (cmpxchg64(&pi_desc->control, old.control,
12605 new.control) != old.control);
12607 /* We should not block the vCPU if an interrupt is posted for it. */
12608 if (pi_test_on(pi_desc) == 1)
12609 __pi_post_block(vcpu);
12611 local_irq_enable();
12612 return (vcpu->pre_pcpu == -1);
12615 static int vmx_pre_block(struct kvm_vcpu *vcpu)
12617 if (pi_pre_block(vcpu))
12620 if (kvm_lapic_hv_timer_in_use(vcpu))
12621 kvm_lapic_switch_to_sw_timer(vcpu);
12626 static void pi_post_block(struct kvm_vcpu *vcpu)
12628 if (vcpu->pre_pcpu == -1)
12631 WARN_ON(irqs_disabled());
12632 local_irq_disable();
12633 __pi_post_block(vcpu);
12634 local_irq_enable();
12637 static void vmx_post_block(struct kvm_vcpu *vcpu)
12639 if (kvm_x86_ops->set_hv_timer)
12640 kvm_lapic_switch_to_hv_timer(vcpu);
12642 pi_post_block(vcpu);
12646 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
12649 * @host_irq: host irq of the interrupt
12650 * @guest_irq: gsi of the interrupt
12651 * @set: set or unset PI
12652 * returns 0 on success, < 0 on failure
12654 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
12655 uint32_t guest_irq, bool set)
12657 struct kvm_kernel_irq_routing_entry *e;
12658 struct kvm_irq_routing_table *irq_rt;
12659 struct kvm_lapic_irq irq;
12660 struct kvm_vcpu *vcpu;
12661 struct vcpu_data vcpu_info;
12664 if (!kvm_arch_has_assigned_device(kvm) ||
12665 !irq_remapping_cap(IRQ_POSTING_CAP) ||
12666 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
12669 idx = srcu_read_lock(&kvm->irq_srcu);
12670 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
12671 if (guest_irq >= irq_rt->nr_rt_entries ||
12672 hlist_empty(&irq_rt->map[guest_irq])) {
12673 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
12674 guest_irq, irq_rt->nr_rt_entries);
12678 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
12679 if (e->type != KVM_IRQ_ROUTING_MSI)
12682 * VT-d PI cannot support posting multicast/broadcast
12683 * interrupts to a vCPU, we still use interrupt remapping
12684 * for these kind of interrupts.
12686 * For lowest-priority interrupts, we only support
12687 * those with single CPU as the destination, e.g. user
12688 * configures the interrupts via /proc/irq or uses
12689 * irqbalance to make the interrupts single-CPU.
12691 * We will support full lowest-priority interrupt later.
12694 kvm_set_msi_irq(kvm, e, &irq);
12695 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
12697 * Make sure the IRTE is in remapped mode if
12698 * we don't handle it in posted mode.
12700 ret = irq_set_vcpu_affinity(host_irq, NULL);
12703 "failed to back to remapped mode, irq: %u\n",
12711 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
12712 vcpu_info.vector = irq.vector;
12714 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
12715 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
12718 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
12720 ret = irq_set_vcpu_affinity(host_irq, NULL);
12723 printk(KERN_INFO "%s: failed to update PI IRTE\n",
12731 srcu_read_unlock(&kvm->irq_srcu, idx);
12735 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
12737 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
12738 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
12739 FEATURE_CONTROL_LMCE;
12741 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
12742 ~FEATURE_CONTROL_LMCE;
12745 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
12746 .cpu_has_kvm_support = cpu_has_kvm_support,
12747 .disabled_by_bios = vmx_disabled_by_bios,
12748 .hardware_setup = hardware_setup,
12749 .hardware_unsetup = hardware_unsetup,
12750 .check_processor_compatibility = vmx_check_processor_compat,
12751 .hardware_enable = hardware_enable,
12752 .hardware_disable = hardware_disable,
12753 .cpu_has_accelerated_tpr = report_flexpriority,
12754 .has_emulated_msr = vmx_has_emulated_msr,
12756 .vm_init = vmx_vm_init,
12758 .vcpu_create = vmx_create_vcpu,
12759 .vcpu_free = vmx_free_vcpu,
12760 .vcpu_reset = vmx_vcpu_reset,
12762 .prepare_guest_switch = vmx_save_host_state,
12763 .vcpu_load = vmx_vcpu_load,
12764 .vcpu_put = vmx_vcpu_put,
12766 .update_bp_intercept = update_exception_bitmap,
12767 .get_msr_feature = vmx_get_msr_feature,
12768 .get_msr = vmx_get_msr,
12769 .set_msr = vmx_set_msr,
12770 .get_segment_base = vmx_get_segment_base,
12771 .get_segment = vmx_get_segment,
12772 .set_segment = vmx_set_segment,
12773 .get_cpl = vmx_get_cpl,
12774 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
12775 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
12776 .decache_cr3 = vmx_decache_cr3,
12777 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
12778 .set_cr0 = vmx_set_cr0,
12779 .set_cr3 = vmx_set_cr3,
12780 .set_cr4 = vmx_set_cr4,
12781 .set_efer = vmx_set_efer,
12782 .get_idt = vmx_get_idt,
12783 .set_idt = vmx_set_idt,
12784 .get_gdt = vmx_get_gdt,
12785 .set_gdt = vmx_set_gdt,
12786 .get_dr6 = vmx_get_dr6,
12787 .set_dr6 = vmx_set_dr6,
12788 .set_dr7 = vmx_set_dr7,
12789 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
12790 .cache_reg = vmx_cache_reg,
12791 .get_rflags = vmx_get_rflags,
12792 .set_rflags = vmx_set_rflags,
12794 .tlb_flush = vmx_flush_tlb,
12796 .run = vmx_vcpu_run,
12797 .handle_exit = vmx_handle_exit,
12798 .skip_emulated_instruction = skip_emulated_instruction,
12799 .set_interrupt_shadow = vmx_set_interrupt_shadow,
12800 .get_interrupt_shadow = vmx_get_interrupt_shadow,
12801 .patch_hypercall = vmx_patch_hypercall,
12802 .set_irq = vmx_inject_irq,
12803 .set_nmi = vmx_inject_nmi,
12804 .queue_exception = vmx_queue_exception,
12805 .cancel_injection = vmx_cancel_injection,
12806 .interrupt_allowed = vmx_interrupt_allowed,
12807 .nmi_allowed = vmx_nmi_allowed,
12808 .get_nmi_mask = vmx_get_nmi_mask,
12809 .set_nmi_mask = vmx_set_nmi_mask,
12810 .enable_nmi_window = enable_nmi_window,
12811 .enable_irq_window = enable_irq_window,
12812 .update_cr8_intercept = update_cr8_intercept,
12813 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
12814 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
12815 .get_enable_apicv = vmx_get_enable_apicv,
12816 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
12817 .load_eoi_exitmap = vmx_load_eoi_exitmap,
12818 .apicv_post_state_restore = vmx_apicv_post_state_restore,
12819 .hwapic_irr_update = vmx_hwapic_irr_update,
12820 .hwapic_isr_update = vmx_hwapic_isr_update,
12821 .sync_pir_to_irr = vmx_sync_pir_to_irr,
12822 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
12823 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
12825 .set_tss_addr = vmx_set_tss_addr,
12826 .get_tdp_level = get_ept_level,
12827 .get_mt_mask = vmx_get_mt_mask,
12829 .get_exit_info = vmx_get_exit_info,
12831 .get_lpage_level = vmx_get_lpage_level,
12833 .cpuid_update = vmx_cpuid_update,
12835 .rdtscp_supported = vmx_rdtscp_supported,
12836 .invpcid_supported = vmx_invpcid_supported,
12838 .set_supported_cpuid = vmx_set_supported_cpuid,
12840 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
12842 .write_tsc_offset = vmx_write_tsc_offset,
12844 .set_tdp_cr3 = vmx_set_cr3,
12846 .check_intercept = vmx_check_intercept,
12847 .handle_external_intr = vmx_handle_external_intr,
12848 .mpx_supported = vmx_mpx_supported,
12849 .xsaves_supported = vmx_xsaves_supported,
12851 .check_nested_events = vmx_check_nested_events,
12853 .sched_in = vmx_sched_in,
12855 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
12856 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
12857 .flush_log_dirty = vmx_flush_log_dirty,
12858 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
12859 .write_log_dirty = vmx_write_pml_buffer,
12861 .pre_block = vmx_pre_block,
12862 .post_block = vmx_post_block,
12864 .pmu_ops = &intel_pmu_ops,
12866 .update_pi_irte = vmx_update_pi_irte,
12868 #ifdef CONFIG_X86_64
12869 .set_hv_timer = vmx_set_hv_timer,
12870 .cancel_hv_timer = vmx_cancel_hv_timer,
12873 .setup_mce = vmx_setup_mce,
12876 static void vmx_cleanup_l1d_flush(void)
12878 if (vmx_l1d_flush_pages) {
12879 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
12880 vmx_l1d_flush_pages = NULL;
12882 /* Restore state so sysfs ignores VMX */
12883 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
12887 static void vmx_exit(void)
12889 #ifdef CONFIG_KEXEC_CORE
12890 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
12896 vmx_cleanup_l1d_flush();
12898 module_exit(vmx_exit)
12900 static int __init vmx_init(void)
12904 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
12905 __alignof__(struct vcpu_vmx), THIS_MODULE);
12910 * Must be called after kvm_init() so enable_ept is properly set
12911 * up. Hand the parameter mitigation value in which was stored in
12912 * the pre module init parser. If no parameter was given, it will
12913 * contain 'auto' which will be turned into the default 'cond'
12916 if (boot_cpu_has(X86_BUG_L1TF)) {
12917 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
12924 for_each_possible_cpu(cpu) {
12925 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
12926 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
12927 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
12930 #ifdef CONFIG_KEXEC_CORE
12931 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
12932 crash_vmclear_local_loaded_vmcss);
12937 module_init(vmx_init)