2 * Kernel-based Virtual Machine driver for Linux
4 * This module enables machines with Intel VT-x extensions to run virtual
5 * machines without emulation or binary translation.
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11 * Avi Kivity <avi@qumranet.com>
12 * Yaniv Kamay <yaniv@qumranet.com>
14 * This work is licensed under the terms of the GNU GPL, version 2. See
15 * the COPYING file in the top-level directory.
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/moduleparam.h>
31 #include <linux/mod_devicetable.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/tboot.h>
35 #include <linux/hrtimer.h>
36 #include <linux/frame.h>
37 #include <linux/nospec.h>
38 #include "kvm_cache_regs.h"
45 #include <asm/virtext.h>
47 #include <asm/fpu/internal.h>
48 #include <asm/perf_event.h>
49 #include <asm/debugreg.h>
50 #include <asm/kexec.h>
52 #include <asm/irq_remapping.h>
53 #include <asm/microcode.h>
54 #include <asm/spec-ctrl.h>
59 #define __ex(x) __kvm_handle_fault_on_reboot(x)
60 #define __ex_clear(x, reg) \
61 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
63 MODULE_AUTHOR("Qumranet");
64 MODULE_LICENSE("GPL");
66 static const struct x86_cpu_id vmx_cpu_id[] = {
67 X86_FEATURE_MATCH(X86_FEATURE_VMX),
70 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
72 static bool __read_mostly enable_vpid = 1;
73 module_param_named(vpid, enable_vpid, bool, 0444);
75 static bool __read_mostly flexpriority_enabled = 1;
76 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
78 static bool __read_mostly enable_ept = 1;
79 module_param_named(ept, enable_ept, bool, S_IRUGO);
81 static bool __read_mostly enable_unrestricted_guest = 1;
82 module_param_named(unrestricted_guest,
83 enable_unrestricted_guest, bool, S_IRUGO);
85 static bool __read_mostly enable_ept_ad_bits = 1;
86 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
88 static bool __read_mostly emulate_invalid_guest_state = true;
89 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
91 static bool __read_mostly vmm_exclusive = 1;
92 module_param(vmm_exclusive, bool, S_IRUGO);
94 static bool __read_mostly fasteoi = 1;
95 module_param(fasteoi, bool, S_IRUGO);
97 static bool __read_mostly enable_apicv = 1;
98 module_param(enable_apicv, bool, S_IRUGO);
100 static bool __read_mostly enable_shadow_vmcs = 1;
101 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
103 * If nested=1, nested virtualization is supported, i.e., guests may use
104 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
105 * use VMX instructions.
107 static bool __read_mostly nested = 0;
108 module_param(nested, bool, S_IRUGO);
110 static u64 __read_mostly host_xss;
112 static bool __read_mostly enable_pml = 1;
113 module_param_named(pml, enable_pml, bool, S_IRUGO);
117 #define MSR_TYPE_RW 3
119 #define MSR_BITMAP_MODE_X2APIC 1
120 #define MSR_BITMAP_MODE_X2APIC_APICV 2
121 #define MSR_BITMAP_MODE_LM 4
123 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
125 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
126 static int __read_mostly cpu_preemption_timer_multi;
127 static bool __read_mostly enable_preemption_timer = 1;
129 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
132 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
133 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST (X86_CR0_WP | X86_CR0_NE)
134 #define KVM_VM_CR0_ALWAYS_ON \
135 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | X86_CR0_PG | X86_CR0_PE)
136 #define KVM_CR4_GUEST_OWNED_BITS \
137 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
138 | X86_CR4_OSXMMEXCPT | X86_CR4_TSD)
140 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
141 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
143 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
145 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
147 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
148 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
149 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
150 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
151 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
154 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
155 * ple_gap: upper bound on the amount of time between two successive
156 * executions of PAUSE in a loop. Also indicate if ple enabled.
157 * According to test, this time is usually smaller than 128 cycles.
158 * ple_window: upper bound on the amount of time a guest is allowed to execute
159 * in a PAUSE loop. Tests indicate that most spinlocks are held for
160 * less than 2^12 cycles
161 * Time is measured based on a counter that runs at the same rate as the TSC,
162 * refer SDM volume 3b section 21.6.13 & 22.1.3.
164 #define KVM_VMX_DEFAULT_PLE_GAP 128
165 #define KVM_VMX_DEFAULT_PLE_WINDOW 4096
166 #define KVM_VMX_DEFAULT_PLE_WINDOW_GROW 2
167 #define KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK 0
168 #define KVM_VMX_DEFAULT_PLE_WINDOW_MAX \
169 INT_MAX / KVM_VMX_DEFAULT_PLE_WINDOW_GROW
171 static int ple_gap = KVM_VMX_DEFAULT_PLE_GAP;
172 module_param(ple_gap, int, S_IRUGO);
174 static int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
175 module_param(ple_window, int, S_IRUGO);
177 /* Default doubles per-vcpu window every exit. */
178 static int ple_window_grow = KVM_VMX_DEFAULT_PLE_WINDOW_GROW;
179 module_param(ple_window_grow, int, S_IRUGO);
181 /* Default resets per-vcpu window every exit to ple_window. */
182 static int ple_window_shrink = KVM_VMX_DEFAULT_PLE_WINDOW_SHRINK;
183 module_param(ple_window_shrink, int, S_IRUGO);
185 /* Default is to compute the maximum so we can never overflow. */
186 static int ple_window_actual_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
187 static int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
188 module_param(ple_window_max, int, S_IRUGO);
190 extern const ulong vmx_return;
192 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
193 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
194 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
196 /* Storage for pre module init parameter parsing */
197 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
199 static const struct {
202 } vmentry_l1d_param[] = {
203 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
204 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
205 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
206 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
207 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
208 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
211 #define L1D_CACHE_ORDER 4
212 static void *vmx_l1d_flush_pages;
214 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
220 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
224 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
227 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
228 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
229 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
234 /* If set to auto use the default l1tf mitigation method */
235 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
236 switch (l1tf_mitigation) {
237 case L1TF_MITIGATION_OFF:
238 l1tf = VMENTER_L1D_FLUSH_NEVER;
240 case L1TF_MITIGATION_FLUSH_NOWARN:
241 case L1TF_MITIGATION_FLUSH:
242 case L1TF_MITIGATION_FLUSH_NOSMT:
243 l1tf = VMENTER_L1D_FLUSH_COND;
245 case L1TF_MITIGATION_FULL:
246 case L1TF_MITIGATION_FULL_FORCE:
247 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
250 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
251 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
254 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
255 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
256 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
259 vmx_l1d_flush_pages = page_address(page);
262 * Initialize each page with a different pattern in
263 * order to protect against KSM in the nested
264 * virtualization case.
266 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
267 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
272 l1tf_vmx_mitigation = l1tf;
274 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
275 static_branch_enable(&vmx_l1d_should_flush);
277 static_branch_disable(&vmx_l1d_should_flush);
279 if (l1tf == VMENTER_L1D_FLUSH_COND)
280 static_branch_enable(&vmx_l1d_flush_cond);
282 static_branch_disable(&vmx_l1d_flush_cond);
286 static int vmentry_l1d_flush_parse(const char *s)
291 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
292 if (vmentry_l1d_param[i].for_parse &&
293 sysfs_streq(s, vmentry_l1d_param[i].option))
300 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
304 l1tf = vmentry_l1d_flush_parse(s);
308 if (!boot_cpu_has(X86_BUG_L1TF))
312 * Has vmx_init() run already? If not then this is the pre init
313 * parameter parsing. In that case just store the value and let
314 * vmx_init() do the proper setup after enable_ept has been
317 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
318 vmentry_l1d_flush_param = l1tf;
322 mutex_lock(&vmx_l1d_flush_mutex);
323 ret = vmx_setup_l1d_flush(l1tf);
324 mutex_unlock(&vmx_l1d_flush_mutex);
328 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
330 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
331 return sprintf(s, "???\n");
333 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
336 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
337 .set = vmentry_l1d_flush_set,
338 .get = vmentry_l1d_flush_get,
340 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
342 #define NR_AUTOLOAD_MSRS 8
351 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
352 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
353 * loaded on this CPU (so we can clear them if the CPU goes down).
357 struct vmcs *shadow_vmcs;
360 unsigned long *msr_bitmap;
361 struct list_head loaded_vmcss_on_cpu_link;
364 struct shared_msr_entry {
371 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
372 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
373 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
374 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
375 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
376 * More than one of these structures may exist, if L1 runs multiple L2 guests.
377 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
378 * underlying hardware which will be used to run L2.
379 * This structure is packed to ensure that its layout is identical across
380 * machines (necessary for live migration).
381 * If there are changes in this struct, VMCS12_REVISION must be changed.
383 typedef u64 natural_width;
384 struct __packed vmcs12 {
385 /* According to the Intel spec, a VMCS region must start with the
386 * following two fields. Then follow implementation-specific data.
391 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
392 u32 padding[7]; /* room for future expansion */
397 u64 vm_exit_msr_store_addr;
398 u64 vm_exit_msr_load_addr;
399 u64 vm_entry_msr_load_addr;
401 u64 virtual_apic_page_addr;
402 u64 apic_access_addr;
403 u64 posted_intr_desc_addr;
405 u64 eoi_exit_bitmap0;
406 u64 eoi_exit_bitmap1;
407 u64 eoi_exit_bitmap2;
408 u64 eoi_exit_bitmap3;
410 u64 guest_physical_address;
411 u64 vmcs_link_pointer;
412 u64 guest_ia32_debugctl;
415 u64 guest_ia32_perf_global_ctrl;
423 u64 host_ia32_perf_global_ctrl;
424 u64 padding64[8]; /* room for future expansion */
426 * To allow migration of L1 (complete with its L2 guests) between
427 * machines of different natural widths (32 or 64 bit), we cannot have
428 * unsigned long fields with no explict size. We use u64 (aliased
429 * natural_width) instead. Luckily, x86 is little-endian.
431 natural_width cr0_guest_host_mask;
432 natural_width cr4_guest_host_mask;
433 natural_width cr0_read_shadow;
434 natural_width cr4_read_shadow;
435 natural_width cr3_target_value0;
436 natural_width cr3_target_value1;
437 natural_width cr3_target_value2;
438 natural_width cr3_target_value3;
439 natural_width exit_qualification;
440 natural_width guest_linear_address;
441 natural_width guest_cr0;
442 natural_width guest_cr3;
443 natural_width guest_cr4;
444 natural_width guest_es_base;
445 natural_width guest_cs_base;
446 natural_width guest_ss_base;
447 natural_width guest_ds_base;
448 natural_width guest_fs_base;
449 natural_width guest_gs_base;
450 natural_width guest_ldtr_base;
451 natural_width guest_tr_base;
452 natural_width guest_gdtr_base;
453 natural_width guest_idtr_base;
454 natural_width guest_dr7;
455 natural_width guest_rsp;
456 natural_width guest_rip;
457 natural_width guest_rflags;
458 natural_width guest_pending_dbg_exceptions;
459 natural_width guest_sysenter_esp;
460 natural_width guest_sysenter_eip;
461 natural_width host_cr0;
462 natural_width host_cr3;
463 natural_width host_cr4;
464 natural_width host_fs_base;
465 natural_width host_gs_base;
466 natural_width host_tr_base;
467 natural_width host_gdtr_base;
468 natural_width host_idtr_base;
469 natural_width host_ia32_sysenter_esp;
470 natural_width host_ia32_sysenter_eip;
471 natural_width host_rsp;
472 natural_width host_rip;
473 natural_width paddingl[8]; /* room for future expansion */
474 u32 pin_based_vm_exec_control;
475 u32 cpu_based_vm_exec_control;
476 u32 exception_bitmap;
477 u32 page_fault_error_code_mask;
478 u32 page_fault_error_code_match;
479 u32 cr3_target_count;
480 u32 vm_exit_controls;
481 u32 vm_exit_msr_store_count;
482 u32 vm_exit_msr_load_count;
483 u32 vm_entry_controls;
484 u32 vm_entry_msr_load_count;
485 u32 vm_entry_intr_info_field;
486 u32 vm_entry_exception_error_code;
487 u32 vm_entry_instruction_len;
489 u32 secondary_vm_exec_control;
490 u32 vm_instruction_error;
492 u32 vm_exit_intr_info;
493 u32 vm_exit_intr_error_code;
494 u32 idt_vectoring_info_field;
495 u32 idt_vectoring_error_code;
496 u32 vm_exit_instruction_len;
497 u32 vmx_instruction_info;
504 u32 guest_ldtr_limit;
506 u32 guest_gdtr_limit;
507 u32 guest_idtr_limit;
508 u32 guest_es_ar_bytes;
509 u32 guest_cs_ar_bytes;
510 u32 guest_ss_ar_bytes;
511 u32 guest_ds_ar_bytes;
512 u32 guest_fs_ar_bytes;
513 u32 guest_gs_ar_bytes;
514 u32 guest_ldtr_ar_bytes;
515 u32 guest_tr_ar_bytes;
516 u32 guest_interruptibility_info;
517 u32 guest_activity_state;
518 u32 guest_sysenter_cs;
519 u32 host_ia32_sysenter_cs;
520 u32 vmx_preemption_timer_value;
521 u32 padding32[7]; /* room for future expansion */
522 u16 virtual_processor_id;
524 u16 guest_es_selector;
525 u16 guest_cs_selector;
526 u16 guest_ss_selector;
527 u16 guest_ds_selector;
528 u16 guest_fs_selector;
529 u16 guest_gs_selector;
530 u16 guest_ldtr_selector;
531 u16 guest_tr_selector;
532 u16 guest_intr_status;
533 u16 host_es_selector;
534 u16 host_cs_selector;
535 u16 host_ss_selector;
536 u16 host_ds_selector;
537 u16 host_fs_selector;
538 u16 host_gs_selector;
539 u16 host_tr_selector;
543 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
544 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
545 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
547 #define VMCS12_REVISION 0x11e57ed0
550 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
551 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
552 * current implementation, 4K are reserved to avoid future complications.
554 #define VMCS12_SIZE 0x1000
557 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
558 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
561 /* Has the level1 guest done vmxon? */
565 /* The guest-physical address of the current VMCS L1 keeps for L2 */
567 /* The host-usable pointer to the above */
568 struct page *current_vmcs12_page;
569 struct vmcs12 *current_vmcs12;
571 * Cache of the guest's VMCS, existing outside of guest memory.
572 * Loaded from guest memory during VMPTRLD. Flushed to guest
573 * memory during VMXOFF, VMCLEAR, VMPTRLD.
575 struct vmcs12 *cached_vmcs12;
577 * Indicates if the shadow vmcs must be updated with the
578 * data hold by vmcs12
580 bool sync_shadow_vmcs;
582 bool change_vmcs01_virtual_x2apic_mode;
583 /* L2 must run next, and mustn't decide to exit to L1. */
584 bool nested_run_pending;
586 struct loaded_vmcs vmcs02;
589 * Guest pages referred to in the vmcs02 with host-physical
590 * pointers, so we must keep them pinned while L2 runs.
592 struct page *apic_access_page;
593 struct page *virtual_apic_page;
594 struct page *pi_desc_page;
595 struct pi_desc *pi_desc;
599 struct hrtimer preemption_timer;
600 bool preemption_timer_expired;
602 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
608 u32 nested_vmx_procbased_ctls_low;
609 u32 nested_vmx_procbased_ctls_high;
610 u32 nested_vmx_true_procbased_ctls_low;
611 u32 nested_vmx_secondary_ctls_low;
612 u32 nested_vmx_secondary_ctls_high;
613 u32 nested_vmx_pinbased_ctls_low;
614 u32 nested_vmx_pinbased_ctls_high;
615 u32 nested_vmx_exit_ctls_low;
616 u32 nested_vmx_exit_ctls_high;
617 u32 nested_vmx_true_exit_ctls_low;
618 u32 nested_vmx_entry_ctls_low;
619 u32 nested_vmx_entry_ctls_high;
620 u32 nested_vmx_true_entry_ctls_low;
621 u32 nested_vmx_misc_low;
622 u32 nested_vmx_misc_high;
623 u32 nested_vmx_ept_caps;
624 u32 nested_vmx_vpid_caps;
627 #define POSTED_INTR_ON 0
628 #define POSTED_INTR_SN 1
630 /* Posted-Interrupt Descriptor */
632 u32 pir[8]; /* Posted interrupt requested */
635 /* bit 256 - Outstanding Notification */
637 /* bit 257 - Suppress Notification */
639 /* bit 271:258 - Reserved */
641 /* bit 279:272 - Notification Vector */
643 /* bit 287:280 - Reserved */
645 /* bit 319:288 - Notification Destination */
653 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
655 return test_and_set_bit(POSTED_INTR_ON,
656 (unsigned long *)&pi_desc->control);
659 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
661 return test_and_clear_bit(POSTED_INTR_ON,
662 (unsigned long *)&pi_desc->control);
665 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
667 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
670 static inline void pi_clear_sn(struct pi_desc *pi_desc)
672 return clear_bit(POSTED_INTR_SN,
673 (unsigned long *)&pi_desc->control);
676 static inline void pi_set_sn(struct pi_desc *pi_desc)
678 return set_bit(POSTED_INTR_SN,
679 (unsigned long *)&pi_desc->control);
682 static inline int pi_test_on(struct pi_desc *pi_desc)
684 return test_bit(POSTED_INTR_ON,
685 (unsigned long *)&pi_desc->control);
688 static inline int pi_test_sn(struct pi_desc *pi_desc)
690 return test_bit(POSTED_INTR_SN,
691 (unsigned long *)&pi_desc->control);
696 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
700 struct kvm_vcpu vcpu;
701 unsigned long host_rsp;
703 bool nmi_known_unmasked;
706 u32 idt_vectoring_info;
708 struct shared_msr_entry *guest_msrs;
711 unsigned long host_idt_base;
713 u64 msr_host_kernel_gs_base;
714 u64 msr_guest_kernel_gs_base;
719 u32 vm_entry_controls_shadow;
720 u32 vm_exit_controls_shadow;
722 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
723 * non-nested (L1) guest, it always points to vmcs01. For a nested
724 * guest (L2), it points to a different VMCS.
726 struct loaded_vmcs vmcs01;
727 struct loaded_vmcs *loaded_vmcs;
728 bool __launched; /* temporary, used in vmx_vcpu_run */
729 struct msr_autoload {
730 struct vmx_msrs guest;
731 struct vmx_msrs host;
735 u16 fs_sel, gs_sel, ldt_sel;
739 int gs_ldt_reload_needed;
740 int fs_reload_needed;
741 u64 msr_host_bndcfgs;
742 unsigned long vmcs_host_cr4; /* May not match real cr4 */
747 struct kvm_segment segs[8];
750 u32 bitmask; /* 4 bits per segment (1 bit per field) */
751 struct kvm_save_segment {
759 bool emulation_required;
761 /* Support for vnmi-less CPUs */
762 int soft_vnmi_blocked;
764 s64 vnmi_blocked_time;
767 /* Posted interrupt descriptor */
768 struct pi_desc pi_desc;
770 /* Support for a guest hypervisor (nested VMX) */
771 struct nested_vmx nested;
773 /* Dynamic PLE window. */
775 bool ple_window_dirty;
777 /* Support for PML */
778 #define PML_ENTITY_NUM 512
781 /* apic deadline value in host tsc */
784 u64 current_tsc_ratio;
786 bool guest_pkru_valid;
791 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
792 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
793 * in msr_ia32_feature_control_valid_bits.
795 u64 msr_ia32_feature_control;
796 u64 msr_ia32_feature_control_valid_bits;
799 enum segment_cache_field {
808 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
810 return container_of(vcpu, struct vcpu_vmx, vcpu);
813 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
815 return &(to_vmx(vcpu)->pi_desc);
818 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
819 #define FIELD(number, name) [number] = VMCS12_OFFSET(name)
820 #define FIELD64(number, name) [number] = VMCS12_OFFSET(name), \
821 [number##_HIGH] = VMCS12_OFFSET(name)+4
824 static unsigned long shadow_read_only_fields[] = {
826 * We do NOT shadow fields that are modified when L0
827 * traps and emulates any vmx instruction (e.g. VMPTRLD,
828 * VMXON...) executed by L1.
829 * For example, VM_INSTRUCTION_ERROR is read
830 * by L1 if a vmx instruction fails (part of the error path).
831 * Note the code assumes this logic. If for some reason
832 * we start shadowing these fields then we need to
833 * force a shadow sync when L0 emulates vmx instructions
834 * (e.g. force a sync if VM_INSTRUCTION_ERROR is modified
835 * by nested_vmx_failValid)
839 VM_EXIT_INSTRUCTION_LEN,
840 IDT_VECTORING_INFO_FIELD,
841 IDT_VECTORING_ERROR_CODE,
842 VM_EXIT_INTR_ERROR_CODE,
844 GUEST_LINEAR_ADDRESS,
845 GUEST_PHYSICAL_ADDRESS
847 static int max_shadow_read_only_fields =
848 ARRAY_SIZE(shadow_read_only_fields);
850 static unsigned long shadow_read_write_fields[] = {
857 GUEST_INTERRUPTIBILITY_INFO,
870 CPU_BASED_VM_EXEC_CONTROL,
871 VM_ENTRY_EXCEPTION_ERROR_CODE,
872 VM_ENTRY_INTR_INFO_FIELD,
873 VM_ENTRY_INSTRUCTION_LEN,
874 VM_ENTRY_EXCEPTION_ERROR_CODE,
880 static int max_shadow_read_write_fields =
881 ARRAY_SIZE(shadow_read_write_fields);
883 static const unsigned short vmcs_field_to_offset_table[] = {
884 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
885 FIELD(POSTED_INTR_NV, posted_intr_nv),
886 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
887 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
888 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
889 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
890 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
891 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
892 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
893 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
894 FIELD(GUEST_INTR_STATUS, guest_intr_status),
895 FIELD(HOST_ES_SELECTOR, host_es_selector),
896 FIELD(HOST_CS_SELECTOR, host_cs_selector),
897 FIELD(HOST_SS_SELECTOR, host_ss_selector),
898 FIELD(HOST_DS_SELECTOR, host_ds_selector),
899 FIELD(HOST_FS_SELECTOR, host_fs_selector),
900 FIELD(HOST_GS_SELECTOR, host_gs_selector),
901 FIELD(HOST_TR_SELECTOR, host_tr_selector),
902 FIELD64(IO_BITMAP_A, io_bitmap_a),
903 FIELD64(IO_BITMAP_B, io_bitmap_b),
904 FIELD64(MSR_BITMAP, msr_bitmap),
905 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
906 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
907 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
908 FIELD64(TSC_OFFSET, tsc_offset),
909 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
910 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
911 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
912 FIELD64(EPT_POINTER, ept_pointer),
913 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
914 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
915 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
916 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
917 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
918 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
919 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
920 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
921 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
922 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
923 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
924 FIELD64(GUEST_PDPTR0, guest_pdptr0),
925 FIELD64(GUEST_PDPTR1, guest_pdptr1),
926 FIELD64(GUEST_PDPTR2, guest_pdptr2),
927 FIELD64(GUEST_PDPTR3, guest_pdptr3),
928 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
929 FIELD64(HOST_IA32_PAT, host_ia32_pat),
930 FIELD64(HOST_IA32_EFER, host_ia32_efer),
931 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
932 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
933 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
934 FIELD(EXCEPTION_BITMAP, exception_bitmap),
935 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
936 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
937 FIELD(CR3_TARGET_COUNT, cr3_target_count),
938 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
939 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
940 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
941 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
942 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
943 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
944 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
945 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
946 FIELD(TPR_THRESHOLD, tpr_threshold),
947 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
948 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
949 FIELD(VM_EXIT_REASON, vm_exit_reason),
950 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
951 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
952 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
953 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
954 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
955 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
956 FIELD(GUEST_ES_LIMIT, guest_es_limit),
957 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
958 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
959 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
960 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
961 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
962 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
963 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
964 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
965 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
966 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
967 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
968 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
969 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
970 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
971 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
972 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
973 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
974 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
975 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
976 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
977 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
978 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
979 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
980 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
981 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
982 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
983 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
984 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
985 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
986 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
987 FIELD(EXIT_QUALIFICATION, exit_qualification),
988 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
989 FIELD(GUEST_CR0, guest_cr0),
990 FIELD(GUEST_CR3, guest_cr3),
991 FIELD(GUEST_CR4, guest_cr4),
992 FIELD(GUEST_ES_BASE, guest_es_base),
993 FIELD(GUEST_CS_BASE, guest_cs_base),
994 FIELD(GUEST_SS_BASE, guest_ss_base),
995 FIELD(GUEST_DS_BASE, guest_ds_base),
996 FIELD(GUEST_FS_BASE, guest_fs_base),
997 FIELD(GUEST_GS_BASE, guest_gs_base),
998 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
999 FIELD(GUEST_TR_BASE, guest_tr_base),
1000 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1001 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1002 FIELD(GUEST_DR7, guest_dr7),
1003 FIELD(GUEST_RSP, guest_rsp),
1004 FIELD(GUEST_RIP, guest_rip),
1005 FIELD(GUEST_RFLAGS, guest_rflags),
1006 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1007 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1008 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1009 FIELD(HOST_CR0, host_cr0),
1010 FIELD(HOST_CR3, host_cr3),
1011 FIELD(HOST_CR4, host_cr4),
1012 FIELD(HOST_FS_BASE, host_fs_base),
1013 FIELD(HOST_GS_BASE, host_gs_base),
1014 FIELD(HOST_TR_BASE, host_tr_base),
1015 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1016 FIELD(HOST_IDTR_BASE, host_idtr_base),
1017 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1018 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1019 FIELD(HOST_RSP, host_rsp),
1020 FIELD(HOST_RIP, host_rip),
1023 static inline short vmcs_field_to_offset(unsigned long field)
1025 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1026 unsigned short offset;
1028 BUILD_BUG_ON(size > SHRT_MAX);
1032 field = array_index_nospec(field, size);
1033 offset = vmcs_field_to_offset_table[field];
1039 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1041 return to_vmx(vcpu)->nested.cached_vmcs12;
1044 static struct page *nested_get_page(struct kvm_vcpu *vcpu, gpa_t addr)
1046 struct page *page = kvm_vcpu_gfn_to_page(vcpu, addr >> PAGE_SHIFT);
1047 if (is_error_page(page))
1053 static void nested_release_page(struct page *page)
1055 kvm_release_page_dirty(page);
1058 static void nested_release_page_clean(struct page *page)
1060 kvm_release_page_clean(page);
1063 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1064 static u64 construct_eptp(unsigned long root_hpa);
1065 static void kvm_cpu_vmxon(u64 addr);
1066 static void kvm_cpu_vmxoff(void);
1067 static bool vmx_xsaves_supported(void);
1068 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr);
1069 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1070 struct kvm_segment *var, int seg);
1071 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1072 struct kvm_segment *var, int seg);
1073 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1074 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1075 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx);
1076 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1077 static int alloc_identity_pagetable(struct kvm *kvm);
1078 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1079 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1082 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1083 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1085 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1086 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1088 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1089 static DEFINE_PER_CPU(struct desc_ptr, host_gdt);
1092 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1093 * can find which vCPU should be waken up.
1095 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1096 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1098 static unsigned long *vmx_io_bitmap_a;
1099 static unsigned long *vmx_io_bitmap_b;
1100 static unsigned long *vmx_vmread_bitmap;
1101 static unsigned long *vmx_vmwrite_bitmap;
1103 static bool cpu_has_load_ia32_efer;
1104 static bool cpu_has_load_perf_global_ctrl;
1106 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1107 static DEFINE_SPINLOCK(vmx_vpid_lock);
1109 static struct vmcs_config {
1114 u32 pin_based_exec_ctrl;
1115 u32 cpu_based_exec_ctrl;
1116 u32 cpu_based_2nd_exec_ctrl;
1121 static struct vmx_capability {
1126 #define VMX_SEGMENT_FIELD(seg) \
1127 [VCPU_SREG_##seg] = { \
1128 .selector = GUEST_##seg##_SELECTOR, \
1129 .base = GUEST_##seg##_BASE, \
1130 .limit = GUEST_##seg##_LIMIT, \
1131 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1134 static const struct kvm_vmx_segment_field {
1139 } kvm_vmx_segment_fields[] = {
1140 VMX_SEGMENT_FIELD(CS),
1141 VMX_SEGMENT_FIELD(DS),
1142 VMX_SEGMENT_FIELD(ES),
1143 VMX_SEGMENT_FIELD(FS),
1144 VMX_SEGMENT_FIELD(GS),
1145 VMX_SEGMENT_FIELD(SS),
1146 VMX_SEGMENT_FIELD(TR),
1147 VMX_SEGMENT_FIELD(LDTR),
1150 static u64 host_efer;
1152 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1155 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1156 * away by decrementing the array size.
1158 static const u32 vmx_msr_index[] = {
1159 #ifdef CONFIG_X86_64
1160 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1162 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1165 static inline bool is_exception_n(u32 intr_info, u8 vector)
1167 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1168 INTR_INFO_VALID_MASK)) ==
1169 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1172 static inline bool is_debug(u32 intr_info)
1174 return is_exception_n(intr_info, DB_VECTOR);
1177 static inline bool is_breakpoint(u32 intr_info)
1179 return is_exception_n(intr_info, BP_VECTOR);
1182 static inline bool is_page_fault(u32 intr_info)
1184 return is_exception_n(intr_info, PF_VECTOR);
1187 static inline bool is_no_device(u32 intr_info)
1189 return is_exception_n(intr_info, NM_VECTOR);
1192 static inline bool is_invalid_opcode(u32 intr_info)
1194 return is_exception_n(intr_info, UD_VECTOR);
1197 static inline bool is_external_interrupt(u32 intr_info)
1199 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1200 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1203 static inline bool is_machine_check(u32 intr_info)
1205 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1206 INTR_INFO_VALID_MASK)) ==
1207 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1210 /* Undocumented: icebp/int1 */
1211 static inline bool is_icebp(u32 intr_info)
1213 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1214 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1217 static inline bool cpu_has_vmx_msr_bitmap(void)
1219 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1222 static inline bool cpu_has_vmx_tpr_shadow(void)
1224 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1227 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1229 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1232 static inline bool cpu_has_secondary_exec_ctrls(void)
1234 return vmcs_config.cpu_based_exec_ctrl &
1235 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1238 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1240 return vmcs_config.cpu_based_2nd_exec_ctrl &
1241 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1244 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1246 return vmcs_config.cpu_based_2nd_exec_ctrl &
1247 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1250 static inline bool cpu_has_vmx_apic_register_virt(void)
1252 return vmcs_config.cpu_based_2nd_exec_ctrl &
1253 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1256 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1258 return vmcs_config.cpu_based_2nd_exec_ctrl &
1259 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1263 * Comment's format: document - errata name - stepping - processor name.
1265 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1267 static u32 vmx_preemption_cpu_tfms[] = {
1268 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1270 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1271 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1272 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1274 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1276 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1277 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1279 * 320767.pdf - AAP86 - B1 -
1280 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1283 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1285 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1287 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1289 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1290 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1291 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1295 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1297 u32 eax = cpuid_eax(0x00000001), i;
1299 /* Clear the reserved bits */
1300 eax &= ~(0x3U << 14 | 0xfU << 28);
1301 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1302 if (eax == vmx_preemption_cpu_tfms[i])
1308 static inline bool cpu_has_vmx_preemption_timer(void)
1310 return vmcs_config.pin_based_exec_ctrl &
1311 PIN_BASED_VMX_PREEMPTION_TIMER;
1314 static inline bool cpu_has_vmx_posted_intr(void)
1316 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1317 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1320 static inline bool cpu_has_vmx_apicv(void)
1322 return cpu_has_vmx_apic_register_virt() &&
1323 cpu_has_vmx_virtual_intr_delivery() &&
1324 cpu_has_vmx_posted_intr();
1327 static inline bool cpu_has_vmx_flexpriority(void)
1329 return cpu_has_vmx_tpr_shadow() &&
1330 cpu_has_vmx_virtualize_apic_accesses();
1333 static inline bool cpu_has_vmx_ept_execute_only(void)
1335 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1338 static inline bool cpu_has_vmx_ept_2m_page(void)
1340 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1343 static inline bool cpu_has_vmx_ept_1g_page(void)
1345 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1348 static inline bool cpu_has_vmx_ept_4levels(void)
1350 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1353 static inline bool cpu_has_vmx_ept_ad_bits(void)
1355 return vmx_capability.ept & VMX_EPT_AD_BIT;
1358 static inline bool cpu_has_vmx_invept_context(void)
1360 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1363 static inline bool cpu_has_vmx_invept_global(void)
1365 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1368 static inline bool cpu_has_vmx_invvpid_single(void)
1370 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1373 static inline bool cpu_has_vmx_invvpid_global(void)
1375 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1378 static inline bool cpu_has_vmx_invvpid(void)
1380 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1383 static inline bool cpu_has_vmx_ept(void)
1385 return vmcs_config.cpu_based_2nd_exec_ctrl &
1386 SECONDARY_EXEC_ENABLE_EPT;
1389 static inline bool cpu_has_vmx_unrestricted_guest(void)
1391 return vmcs_config.cpu_based_2nd_exec_ctrl &
1392 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1395 static inline bool cpu_has_vmx_ple(void)
1397 return vmcs_config.cpu_based_2nd_exec_ctrl &
1398 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1401 static inline bool cpu_has_vmx_basic_inout(void)
1403 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1406 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1408 return flexpriority_enabled && lapic_in_kernel(vcpu);
1411 static inline bool cpu_has_vmx_vpid(void)
1413 return vmcs_config.cpu_based_2nd_exec_ctrl &
1414 SECONDARY_EXEC_ENABLE_VPID;
1417 static inline bool cpu_has_vmx_rdtscp(void)
1419 return vmcs_config.cpu_based_2nd_exec_ctrl &
1420 SECONDARY_EXEC_RDTSCP;
1423 static inline bool cpu_has_vmx_invpcid(void)
1425 return vmcs_config.cpu_based_2nd_exec_ctrl &
1426 SECONDARY_EXEC_ENABLE_INVPCID;
1429 static inline bool cpu_has_virtual_nmis(void)
1431 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1434 static inline bool cpu_has_vmx_wbinvd_exit(void)
1436 return vmcs_config.cpu_based_2nd_exec_ctrl &
1437 SECONDARY_EXEC_WBINVD_EXITING;
1440 static inline bool cpu_has_vmx_shadow_vmcs(void)
1443 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1444 /* check if the cpu supports writing r/o exit information fields */
1445 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1448 return vmcs_config.cpu_based_2nd_exec_ctrl &
1449 SECONDARY_EXEC_SHADOW_VMCS;
1452 static inline bool cpu_has_vmx_pml(void)
1454 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1457 static inline bool cpu_has_vmx_tsc_scaling(void)
1459 return vmcs_config.cpu_based_2nd_exec_ctrl &
1460 SECONDARY_EXEC_TSC_SCALING;
1463 static inline bool report_flexpriority(void)
1465 return flexpriority_enabled;
1468 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1470 return vmcs12->cpu_based_vm_exec_control & bit;
1473 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1475 return (vmcs12->cpu_based_vm_exec_control &
1476 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1477 (vmcs12->secondary_vm_exec_control & bit);
1480 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1482 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
1485 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1487 return vmcs12->pin_based_vm_exec_control &
1488 PIN_BASED_VMX_PREEMPTION_TIMER;
1491 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
1493 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
1496 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
1498 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES) &&
1499 vmx_xsaves_supported();
1502 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
1504 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
1507 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
1509 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
1512 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
1514 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
1517 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
1519 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
1522 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
1524 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
1527 static inline bool is_nmi(u32 intr_info)
1529 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1530 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
1533 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
1535 unsigned long exit_qualification);
1536 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
1537 struct vmcs12 *vmcs12,
1538 u32 reason, unsigned long qualification);
1540 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
1544 for (i = 0; i < vmx->nmsrs; ++i)
1545 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
1550 static inline void __invvpid(unsigned long ext, u16 vpid, gva_t gva)
1556 } operand = { vpid, 0, gva };
1558 asm volatile (__ex(ASM_VMX_INVVPID)
1559 /* CF==1 or ZF==1 --> rc = -1 */
1560 "; ja 1f ; ud2 ; 1:"
1561 : : "a"(&operand), "c"(ext) : "cc", "memory");
1564 static inline void __invept(unsigned long ext, u64 eptp, gpa_t gpa)
1568 } operand = {eptp, gpa};
1570 asm volatile (__ex(ASM_VMX_INVEPT)
1571 /* CF==1 or ZF==1 --> rc = -1 */
1572 "; ja 1f ; ud2 ; 1:\n"
1573 : : "a" (&operand), "c" (ext) : "cc", "memory");
1576 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
1580 i = __find_msr_index(vmx, msr);
1582 return &vmx->guest_msrs[i];
1586 static void vmcs_clear(struct vmcs *vmcs)
1588 u64 phys_addr = __pa(vmcs);
1591 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) "; setna %0"
1592 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1595 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
1599 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
1601 vmcs_clear(loaded_vmcs->vmcs);
1602 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
1603 vmcs_clear(loaded_vmcs->shadow_vmcs);
1604 loaded_vmcs->cpu = -1;
1605 loaded_vmcs->launched = 0;
1608 static void vmcs_load(struct vmcs *vmcs)
1610 u64 phys_addr = __pa(vmcs);
1613 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) "; setna %0"
1614 : "=qm"(error) : "a"(&phys_addr), "m"(phys_addr)
1617 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
1621 #ifdef CONFIG_KEXEC_CORE
1623 * This bitmap is used to indicate whether the vmclear
1624 * operation is enabled on all cpus. All disabled by
1627 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
1629 static inline void crash_enable_local_vmclear(int cpu)
1631 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
1634 static inline void crash_disable_local_vmclear(int cpu)
1636 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
1639 static inline int crash_local_vmclear_enabled(int cpu)
1641 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
1644 static void crash_vmclear_local_loaded_vmcss(void)
1646 int cpu = raw_smp_processor_id();
1647 struct loaded_vmcs *v;
1649 if (!crash_local_vmclear_enabled(cpu))
1652 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
1653 loaded_vmcss_on_cpu_link)
1654 vmcs_clear(v->vmcs);
1657 static inline void crash_enable_local_vmclear(int cpu) { }
1658 static inline void crash_disable_local_vmclear(int cpu) { }
1659 #endif /* CONFIG_KEXEC_CORE */
1661 static void __loaded_vmcs_clear(void *arg)
1663 struct loaded_vmcs *loaded_vmcs = arg;
1664 int cpu = raw_smp_processor_id();
1666 if (loaded_vmcs->cpu != cpu)
1667 return; /* vcpu migration can race with cpu offline */
1668 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
1669 per_cpu(current_vmcs, cpu) = NULL;
1670 crash_disable_local_vmclear(cpu);
1671 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
1674 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
1675 * is before setting loaded_vmcs->vcpu to -1 which is done in
1676 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
1677 * then adds the vmcs into percpu list before it is deleted.
1681 loaded_vmcs_init(loaded_vmcs);
1682 crash_enable_local_vmclear(cpu);
1685 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
1687 int cpu = loaded_vmcs->cpu;
1690 smp_call_function_single(cpu,
1691 __loaded_vmcs_clear, loaded_vmcs, 1);
1694 static inline void vpid_sync_vcpu_single(int vpid)
1699 if (cpu_has_vmx_invvpid_single())
1700 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
1703 static inline void vpid_sync_vcpu_global(void)
1705 if (cpu_has_vmx_invvpid_global())
1706 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
1709 static inline void vpid_sync_context(int vpid)
1711 if (cpu_has_vmx_invvpid_single())
1712 vpid_sync_vcpu_single(vpid);
1714 vpid_sync_vcpu_global();
1717 static inline void ept_sync_global(void)
1719 if (cpu_has_vmx_invept_global())
1720 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
1723 static inline void ept_sync_context(u64 eptp)
1726 if (cpu_has_vmx_invept_context())
1727 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
1733 static __always_inline void vmcs_check16(unsigned long field)
1735 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1736 "16-bit accessor invalid for 64-bit field");
1737 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1738 "16-bit accessor invalid for 64-bit high field");
1739 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1740 "16-bit accessor invalid for 32-bit high field");
1741 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1742 "16-bit accessor invalid for natural width field");
1745 static __always_inline void vmcs_check32(unsigned long field)
1747 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1748 "32-bit accessor invalid for 16-bit field");
1749 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1750 "32-bit accessor invalid for natural width field");
1753 static __always_inline void vmcs_check64(unsigned long field)
1755 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1756 "64-bit accessor invalid for 16-bit field");
1757 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1758 "64-bit accessor invalid for 64-bit high field");
1759 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1760 "64-bit accessor invalid for 32-bit field");
1761 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
1762 "64-bit accessor invalid for natural width field");
1765 static __always_inline void vmcs_checkl(unsigned long field)
1767 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
1768 "Natural width accessor invalid for 16-bit field");
1769 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
1770 "Natural width accessor invalid for 64-bit field");
1771 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
1772 "Natural width accessor invalid for 64-bit high field");
1773 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
1774 "Natural width accessor invalid for 32-bit field");
1777 static __always_inline unsigned long __vmcs_readl(unsigned long field)
1779 unsigned long value;
1781 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
1782 : "=a"(value) : "d"(field) : "cc");
1786 static __always_inline u16 vmcs_read16(unsigned long field)
1788 vmcs_check16(field);
1789 return __vmcs_readl(field);
1792 static __always_inline u32 vmcs_read32(unsigned long field)
1794 vmcs_check32(field);
1795 return __vmcs_readl(field);
1798 static __always_inline u64 vmcs_read64(unsigned long field)
1800 vmcs_check64(field);
1801 #ifdef CONFIG_X86_64
1802 return __vmcs_readl(field);
1804 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
1808 static __always_inline unsigned long vmcs_readl(unsigned long field)
1811 return __vmcs_readl(field);
1814 static noinline void vmwrite_error(unsigned long field, unsigned long value)
1816 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
1817 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
1821 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
1825 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) "; setna %0"
1826 : "=q"(error) : "a"(value), "d"(field) : "cc");
1827 if (unlikely(error))
1828 vmwrite_error(field, value);
1831 static __always_inline void vmcs_write16(unsigned long field, u16 value)
1833 vmcs_check16(field);
1834 __vmcs_writel(field, value);
1837 static __always_inline void vmcs_write32(unsigned long field, u32 value)
1839 vmcs_check32(field);
1840 __vmcs_writel(field, value);
1843 static __always_inline void vmcs_write64(unsigned long field, u64 value)
1845 vmcs_check64(field);
1846 __vmcs_writel(field, value);
1847 #ifndef CONFIG_X86_64
1849 __vmcs_writel(field+1, value >> 32);
1853 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
1856 __vmcs_writel(field, value);
1859 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
1861 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1862 "vmcs_clear_bits does not support 64-bit fields");
1863 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
1866 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
1868 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
1869 "vmcs_set_bits does not support 64-bit fields");
1870 __vmcs_writel(field, __vmcs_readl(field) | mask);
1873 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
1875 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
1878 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
1880 vmcs_write32(VM_ENTRY_CONTROLS, val);
1881 vmx->vm_entry_controls_shadow = val;
1884 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
1886 if (vmx->vm_entry_controls_shadow != val)
1887 vm_entry_controls_init(vmx, val);
1890 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
1892 return vmx->vm_entry_controls_shadow;
1896 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1898 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
1901 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1903 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
1906 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
1908 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
1911 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
1913 vmcs_write32(VM_EXIT_CONTROLS, val);
1914 vmx->vm_exit_controls_shadow = val;
1917 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
1919 if (vmx->vm_exit_controls_shadow != val)
1920 vm_exit_controls_init(vmx, val);
1923 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
1925 return vmx->vm_exit_controls_shadow;
1929 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
1931 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
1934 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
1936 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
1939 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
1941 vmx->segment_cache.bitmask = 0;
1944 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
1948 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
1950 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
1951 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
1952 vmx->segment_cache.bitmask = 0;
1954 ret = vmx->segment_cache.bitmask & mask;
1955 vmx->segment_cache.bitmask |= mask;
1959 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
1961 u16 *p = &vmx->segment_cache.seg[seg].selector;
1963 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
1964 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
1968 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
1970 ulong *p = &vmx->segment_cache.seg[seg].base;
1972 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
1973 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
1977 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
1979 u32 *p = &vmx->segment_cache.seg[seg].limit;
1981 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
1982 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
1986 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
1988 u32 *p = &vmx->segment_cache.seg[seg].ar;
1990 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
1991 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
1995 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
1999 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2000 (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR);
2001 if ((vcpu->guest_debug &
2002 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2003 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2004 eb |= 1u << BP_VECTOR;
2005 if (to_vmx(vcpu)->rmode.vm86_active)
2008 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2009 if (vcpu->fpu_active)
2010 eb &= ~(1u << NM_VECTOR);
2012 /* When we are running a nested L2 guest and L1 specified for it a
2013 * certain exception bitmap, we must trap the same exceptions and pass
2014 * them to L1. When running L2, we will only handle the exceptions
2015 * specified above if L1 did not want them.
2017 if (is_guest_mode(vcpu))
2018 eb |= get_vmcs12(vcpu)->exception_bitmap;
2020 vmcs_write32(EXCEPTION_BITMAP, eb);
2024 * Check if MSR is intercepted for currently loaded MSR bitmap.
2026 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2028 unsigned long *msr_bitmap;
2029 int f = sizeof(unsigned long);
2031 if (!cpu_has_vmx_msr_bitmap())
2034 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2036 if (msr <= 0x1fff) {
2037 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2038 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2040 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2047 * Check if MSR is intercepted for L01 MSR bitmap.
2049 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2051 unsigned long *msr_bitmap;
2052 int f = sizeof(unsigned long);
2054 if (!cpu_has_vmx_msr_bitmap())
2057 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2059 if (msr <= 0x1fff) {
2060 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2061 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2063 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2069 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2070 unsigned long entry, unsigned long exit)
2072 vm_entry_controls_clearbit(vmx, entry);
2073 vm_exit_controls_clearbit(vmx, exit);
2076 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2080 for (i = 0; i < m->nr; ++i) {
2081 if (m->val[i].index == msr)
2087 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2090 struct msr_autoload *m = &vmx->msr_autoload;
2094 if (cpu_has_load_ia32_efer) {
2095 clear_atomic_switch_msr_special(vmx,
2096 VM_ENTRY_LOAD_IA32_EFER,
2097 VM_EXIT_LOAD_IA32_EFER);
2101 case MSR_CORE_PERF_GLOBAL_CTRL:
2102 if (cpu_has_load_perf_global_ctrl) {
2103 clear_atomic_switch_msr_special(vmx,
2104 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2105 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2110 i = find_msr(&m->guest, msr);
2114 m->guest.val[i] = m->guest.val[m->guest.nr];
2115 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2118 i = find_msr(&m->host, msr);
2123 m->host.val[i] = m->host.val[m->host.nr];
2124 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2127 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2128 unsigned long entry, unsigned long exit,
2129 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2130 u64 guest_val, u64 host_val)
2132 vmcs_write64(guest_val_vmcs, guest_val);
2133 vmcs_write64(host_val_vmcs, host_val);
2134 vm_entry_controls_setbit(vmx, entry);
2135 vm_exit_controls_setbit(vmx, exit);
2138 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2139 u64 guest_val, u64 host_val, bool entry_only)
2142 struct msr_autoload *m = &vmx->msr_autoload;
2146 if (cpu_has_load_ia32_efer) {
2147 add_atomic_switch_msr_special(vmx,
2148 VM_ENTRY_LOAD_IA32_EFER,
2149 VM_EXIT_LOAD_IA32_EFER,
2152 guest_val, host_val);
2156 case MSR_CORE_PERF_GLOBAL_CTRL:
2157 if (cpu_has_load_perf_global_ctrl) {
2158 add_atomic_switch_msr_special(vmx,
2159 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2160 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2161 GUEST_IA32_PERF_GLOBAL_CTRL,
2162 HOST_IA32_PERF_GLOBAL_CTRL,
2163 guest_val, host_val);
2167 case MSR_IA32_PEBS_ENABLE:
2168 /* PEBS needs a quiescent period after being disabled (to write
2169 * a record). Disabling PEBS through VMX MSR swapping doesn't
2170 * provide that period, so a CPU could write host's record into
2173 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2176 i = find_msr(&m->guest, msr);
2178 j = find_msr(&m->host, msr);
2180 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
2181 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
2182 printk_once(KERN_WARNING "Not enough msr switch entries. "
2183 "Can't add msr %x\n", msr);
2188 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2190 m->guest.val[i].index = msr;
2191 m->guest.val[i].value = guest_val;
2198 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2200 m->host.val[j].index = msr;
2201 m->host.val[j].value = host_val;
2204 static void reload_tss(void)
2207 * VT restores TR but not its size. Useless.
2209 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2210 struct desc_struct *descs;
2212 descs = (void *)gdt->address;
2213 descs[GDT_ENTRY_TSS].type = 9; /* available TSS */
2217 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2219 u64 guest_efer = vmx->vcpu.arch.efer;
2220 u64 ignore_bits = 0;
2222 /* Shadow paging assumes NX to be available. */
2224 guest_efer |= EFER_NX;
2227 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2229 ignore_bits |= EFER_SCE;
2230 #ifdef CONFIG_X86_64
2231 ignore_bits |= EFER_LMA | EFER_LME;
2232 /* SCE is meaningful only in long mode on Intel */
2233 if (guest_efer & EFER_LMA)
2234 ignore_bits &= ~(u64)EFER_SCE;
2237 clear_atomic_switch_msr(vmx, MSR_EFER);
2240 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2241 * On CPUs that support "load IA32_EFER", always switch EFER
2242 * atomically, since it's faster than switching it manually.
2244 if (cpu_has_load_ia32_efer ||
2245 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2246 if (!(guest_efer & EFER_LMA))
2247 guest_efer &= ~EFER_LME;
2248 if (guest_efer != host_efer)
2249 add_atomic_switch_msr(vmx, MSR_EFER,
2250 guest_efer, host_efer, false);
2253 guest_efer &= ~ignore_bits;
2254 guest_efer |= host_efer & ignore_bits;
2256 vmx->guest_msrs[efer_offset].data = guest_efer;
2257 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2263 static unsigned long segment_base(u16 selector)
2265 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2266 struct desc_struct *d;
2267 unsigned long table_base;
2270 if (!(selector & ~3))
2273 table_base = gdt->address;
2275 if (selector & 4) { /* from ldt */
2276 u16 ldt_selector = kvm_read_ldt();
2278 if (!(ldt_selector & ~3))
2281 table_base = segment_base(ldt_selector);
2283 d = (struct desc_struct *)(table_base + (selector & ~7));
2284 v = get_desc_base(d);
2285 #ifdef CONFIG_X86_64
2286 if (d->s == 0 && (d->type == 2 || d->type == 9 || d->type == 11))
2287 v |= ((unsigned long)((struct ldttss_desc64 *)d)->base3) << 32;
2292 static inline unsigned long kvm_read_tr_base(void)
2295 asm("str %0" : "=g"(tr));
2296 return segment_base(tr);
2299 static void vmx_save_host_state(struct kvm_vcpu *vcpu)
2301 struct vcpu_vmx *vmx = to_vmx(vcpu);
2304 if (vmx->host_state.loaded)
2307 vmx->host_state.loaded = 1;
2309 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2310 * allow segment selectors with cpl > 0 or ti == 1.
2312 vmx->host_state.ldt_sel = kvm_read_ldt();
2313 vmx->host_state.gs_ldt_reload_needed = vmx->host_state.ldt_sel;
2314 savesegment(fs, vmx->host_state.fs_sel);
2315 if (!(vmx->host_state.fs_sel & 7)) {
2316 vmcs_write16(HOST_FS_SELECTOR, vmx->host_state.fs_sel);
2317 vmx->host_state.fs_reload_needed = 0;
2319 vmcs_write16(HOST_FS_SELECTOR, 0);
2320 vmx->host_state.fs_reload_needed = 1;
2322 savesegment(gs, vmx->host_state.gs_sel);
2323 if (!(vmx->host_state.gs_sel & 7))
2324 vmcs_write16(HOST_GS_SELECTOR, vmx->host_state.gs_sel);
2326 vmcs_write16(HOST_GS_SELECTOR, 0);
2327 vmx->host_state.gs_ldt_reload_needed = 1;
2330 #ifdef CONFIG_X86_64
2331 savesegment(ds, vmx->host_state.ds_sel);
2332 savesegment(es, vmx->host_state.es_sel);
2335 #ifdef CONFIG_X86_64
2336 vmcs_writel(HOST_FS_BASE, read_msr(MSR_FS_BASE));
2337 vmcs_writel(HOST_GS_BASE, read_msr(MSR_GS_BASE));
2339 vmcs_writel(HOST_FS_BASE, segment_base(vmx->host_state.fs_sel));
2340 vmcs_writel(HOST_GS_BASE, segment_base(vmx->host_state.gs_sel));
2343 #ifdef CONFIG_X86_64
2344 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2345 if (is_long_mode(&vmx->vcpu))
2346 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2348 if (boot_cpu_has(X86_FEATURE_MPX))
2349 rdmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2350 for (i = 0; i < vmx->save_nmsrs; ++i)
2351 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2352 vmx->guest_msrs[i].data,
2353 vmx->guest_msrs[i].mask);
2356 static void __vmx_load_host_state(struct vcpu_vmx *vmx)
2358 if (!vmx->host_state.loaded)
2361 ++vmx->vcpu.stat.host_state_reload;
2362 vmx->host_state.loaded = 0;
2363 #ifdef CONFIG_X86_64
2364 if (is_long_mode(&vmx->vcpu))
2365 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2367 if (vmx->host_state.gs_ldt_reload_needed) {
2368 kvm_load_ldt(vmx->host_state.ldt_sel);
2369 #ifdef CONFIG_X86_64
2370 load_gs_index(vmx->host_state.gs_sel);
2372 loadsegment(gs, vmx->host_state.gs_sel);
2375 if (vmx->host_state.fs_reload_needed)
2376 loadsegment(fs, vmx->host_state.fs_sel);
2377 #ifdef CONFIG_X86_64
2378 if (unlikely(vmx->host_state.ds_sel | vmx->host_state.es_sel)) {
2379 loadsegment(ds, vmx->host_state.ds_sel);
2380 loadsegment(es, vmx->host_state.es_sel);
2384 #ifdef CONFIG_X86_64
2385 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2387 if (vmx->host_state.msr_host_bndcfgs)
2388 wrmsrl(MSR_IA32_BNDCFGS, vmx->host_state.msr_host_bndcfgs);
2390 * If the FPU is not active (through the host task or
2391 * the guest vcpu), then restore the cr0.TS bit.
2393 if (!fpregs_active() && !vmx->vcpu.guest_fpu_loaded)
2395 load_gdt(this_cpu_ptr(&host_gdt));
2398 static void vmx_load_host_state(struct vcpu_vmx *vmx)
2401 __vmx_load_host_state(vmx);
2405 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
2407 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2408 struct pi_desc old, new;
2412 * In case of hot-plug or hot-unplug, we may have to undo
2413 * vmx_vcpu_pi_put even if there is no assigned device. And we
2414 * always keep PI.NDST up to date for simplicity: it makes the
2415 * code easier, and CPU migration is not a fast path.
2417 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
2421 * First handle the simple case where no cmpxchg is necessary; just
2422 * allow posting non-urgent interrupts.
2424 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
2425 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
2426 * expects the VCPU to be on the blocked_vcpu_list that matches
2429 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
2431 pi_clear_sn(pi_desc);
2435 /* The full case. */
2437 old.control = new.control = pi_desc->control;
2439 dest = cpu_physical_id(cpu);
2441 if (x2apic_enabled())
2444 new.ndst = (dest << 8) & 0xFF00;
2447 } while (cmpxchg64(&pi_desc->control, old.control,
2448 new.control) != old.control);
2451 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
2453 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
2454 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
2458 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
2459 * vcpu mutex is already taken.
2461 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2463 struct vcpu_vmx *vmx = to_vmx(vcpu);
2464 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
2465 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
2468 kvm_cpu_vmxon(phys_addr);
2469 else if (!already_loaded)
2470 loaded_vmcs_clear(vmx->loaded_vmcs);
2472 if (!already_loaded) {
2473 local_irq_disable();
2474 crash_disable_local_vmclear(cpu);
2477 * Read loaded_vmcs->cpu should be before fetching
2478 * loaded_vmcs->loaded_vmcss_on_cpu_link.
2479 * See the comments in __loaded_vmcs_clear().
2483 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
2484 &per_cpu(loaded_vmcss_on_cpu, cpu));
2485 crash_enable_local_vmclear(cpu);
2489 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
2490 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
2491 vmcs_load(vmx->loaded_vmcs->vmcs);
2492 indirect_branch_prediction_barrier();
2495 if (!already_loaded) {
2496 struct desc_ptr *gdt = this_cpu_ptr(&host_gdt);
2497 unsigned long sysenter_esp;
2499 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2502 * Linux uses per-cpu TSS and GDT, so set these when switching
2505 vmcs_writel(HOST_TR_BASE, kvm_read_tr_base()); /* 22.2.4 */
2506 vmcs_writel(HOST_GDTR_BASE, gdt->address); /* 22.2.4 */
2508 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
2509 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
2511 vmx->loaded_vmcs->cpu = cpu;
2514 /* Setup TSC multiplier */
2515 if (kvm_has_tsc_control &&
2516 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
2517 decache_tsc_multiplier(vmx);
2519 vmx_vcpu_pi_load(vcpu, cpu);
2520 vmx->host_pkru = read_pkru();
2523 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
2525 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
2527 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
2528 !irq_remapping_cap(IRQ_POSTING_CAP) ||
2529 !kvm_vcpu_apicv_active(vcpu))
2532 /* Set SN when the vCPU is preempted */
2533 if (vcpu->preempted)
2537 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
2539 vmx_vcpu_pi_put(vcpu);
2541 __vmx_load_host_state(to_vmx(vcpu));
2542 if (!vmm_exclusive) {
2543 __loaded_vmcs_clear(to_vmx(vcpu)->loaded_vmcs);
2549 static void vmx_fpu_activate(struct kvm_vcpu *vcpu)
2553 if (vcpu->fpu_active)
2555 vcpu->fpu_active = 1;
2556 cr0 = vmcs_readl(GUEST_CR0);
2557 cr0 &= ~(X86_CR0_TS | X86_CR0_MP);
2558 cr0 |= kvm_read_cr0_bits(vcpu, X86_CR0_TS | X86_CR0_MP);
2559 vmcs_writel(GUEST_CR0, cr0);
2560 update_exception_bitmap(vcpu);
2561 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
2562 if (is_guest_mode(vcpu))
2563 vcpu->arch.cr0_guest_owned_bits &=
2564 ~get_vmcs12(vcpu)->cr0_guest_host_mask;
2565 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2568 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
2571 * Return the cr0 value that a nested guest would read. This is a combination
2572 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
2573 * its hypervisor (cr0_read_shadow).
2575 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
2577 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
2578 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
2580 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
2582 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
2583 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
2586 static void vmx_fpu_deactivate(struct kvm_vcpu *vcpu)
2588 /* Note that there is no vcpu->fpu_active = 0 here. The caller must
2589 * set this *before* calling this function.
2591 vmx_decache_cr0_guest_bits(vcpu);
2592 vmcs_set_bits(GUEST_CR0, X86_CR0_TS | X86_CR0_MP);
2593 update_exception_bitmap(vcpu);
2594 vcpu->arch.cr0_guest_owned_bits = 0;
2595 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
2596 if (is_guest_mode(vcpu)) {
2598 * L1's specified read shadow might not contain the TS bit,
2599 * so now that we turned on shadowing of this bit, we need to
2600 * set this bit of the shadow. Like in nested_vmx_run we need
2601 * nested_read_cr0(vmcs12), but vmcs12->guest_cr0 is not yet
2602 * up-to-date here because we just decached cr0.TS (and we'll
2603 * only update vmcs12->guest_cr0 on nested exit).
2605 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2606 vmcs12->guest_cr0 = (vmcs12->guest_cr0 & ~X86_CR0_TS) |
2607 (vcpu->arch.cr0 & X86_CR0_TS);
2608 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
2610 vmcs_writel(CR0_READ_SHADOW, vcpu->arch.cr0);
2613 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
2615 unsigned long rflags, save_rflags;
2617 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
2618 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2619 rflags = vmcs_readl(GUEST_RFLAGS);
2620 if (to_vmx(vcpu)->rmode.vm86_active) {
2621 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
2622 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
2623 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
2625 to_vmx(vcpu)->rflags = rflags;
2627 return to_vmx(vcpu)->rflags;
2630 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2632 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
2633 to_vmx(vcpu)->rflags = rflags;
2634 if (to_vmx(vcpu)->rmode.vm86_active) {
2635 to_vmx(vcpu)->rmode.save_rflags = rflags;
2636 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
2638 vmcs_writel(GUEST_RFLAGS, rflags);
2641 static u32 vmx_get_pkru(struct kvm_vcpu *vcpu)
2643 return to_vmx(vcpu)->guest_pkru;
2646 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
2648 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2651 if (interruptibility & GUEST_INTR_STATE_STI)
2652 ret |= KVM_X86_SHADOW_INT_STI;
2653 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
2654 ret |= KVM_X86_SHADOW_INT_MOV_SS;
2659 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
2661 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
2662 u32 interruptibility = interruptibility_old;
2664 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
2666 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
2667 interruptibility |= GUEST_INTR_STATE_MOV_SS;
2668 else if (mask & KVM_X86_SHADOW_INT_STI)
2669 interruptibility |= GUEST_INTR_STATE_STI;
2671 if ((interruptibility != interruptibility_old))
2672 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
2675 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
2679 rip = kvm_rip_read(vcpu);
2680 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
2681 kvm_rip_write(vcpu, rip);
2683 /* skipping an emulated instruction also counts */
2684 vmx_set_interrupt_shadow(vcpu, 0);
2688 * KVM wants to inject page-faults which it got to the guest. This function
2689 * checks whether in a nested guest, we need to inject them to L1 or L2.
2691 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned nr)
2693 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
2695 if (!(vmcs12->exception_bitmap & (1u << nr)))
2698 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
2699 vmcs_read32(VM_EXIT_INTR_INFO),
2700 vmcs_readl(EXIT_QUALIFICATION));
2704 static void vmx_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
2705 bool has_error_code, u32 error_code,
2708 struct vcpu_vmx *vmx = to_vmx(vcpu);
2709 u32 intr_info = nr | INTR_INFO_VALID_MASK;
2711 if (!reinject && is_guest_mode(vcpu) &&
2712 nested_vmx_check_exception(vcpu, nr))
2715 if (has_error_code) {
2716 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
2717 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
2720 if (vmx->rmode.vm86_active) {
2722 if (kvm_exception_is_soft(nr))
2723 inc_eip = vcpu->arch.event_exit_inst_len;
2724 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
2725 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
2729 WARN_ON_ONCE(vmx->emulation_required);
2731 if (kvm_exception_is_soft(nr)) {
2732 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
2733 vmx->vcpu.arch.event_exit_inst_len);
2734 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
2736 intr_info |= INTR_TYPE_HARD_EXCEPTION;
2738 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
2741 static bool vmx_rdtscp_supported(void)
2743 return cpu_has_vmx_rdtscp();
2746 static bool vmx_invpcid_supported(void)
2748 return cpu_has_vmx_invpcid() && enable_ept;
2752 * Swap MSR entry in host/guest MSR entry array.
2754 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
2756 struct shared_msr_entry tmp;
2758 tmp = vmx->guest_msrs[to];
2759 vmx->guest_msrs[to] = vmx->guest_msrs[from];
2760 vmx->guest_msrs[from] = tmp;
2764 * Set up the vmcs to automatically save and restore system
2765 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
2766 * mode, as fiddling with msrs is very expensive.
2768 static void setup_msrs(struct vcpu_vmx *vmx)
2770 int save_nmsrs, index;
2773 #ifdef CONFIG_X86_64
2774 if (is_long_mode(&vmx->vcpu)) {
2775 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
2777 move_msr_up(vmx, index, save_nmsrs++);
2778 index = __find_msr_index(vmx, MSR_LSTAR);
2780 move_msr_up(vmx, index, save_nmsrs++);
2781 index = __find_msr_index(vmx, MSR_CSTAR);
2783 move_msr_up(vmx, index, save_nmsrs++);
2784 index = __find_msr_index(vmx, MSR_TSC_AUX);
2785 if (index >= 0 && guest_cpuid_has_rdtscp(&vmx->vcpu))
2786 move_msr_up(vmx, index, save_nmsrs++);
2788 * MSR_STAR is only needed on long mode guests, and only
2789 * if efer.sce is enabled.
2791 index = __find_msr_index(vmx, MSR_STAR);
2792 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
2793 move_msr_up(vmx, index, save_nmsrs++);
2796 index = __find_msr_index(vmx, MSR_EFER);
2797 if (index >= 0 && update_transition_efer(vmx, index))
2798 move_msr_up(vmx, index, save_nmsrs++);
2800 vmx->save_nmsrs = save_nmsrs;
2802 if (cpu_has_vmx_msr_bitmap())
2803 vmx_update_msr_bitmap(&vmx->vcpu);
2807 * reads and returns guest's timestamp counter "register"
2808 * guest_tsc = (host_tsc * tsc multiplier) >> 48 + tsc_offset
2809 * -- Intel TSC Scaling for Virtualization White Paper, sec 1.3
2811 static u64 guest_read_tsc(struct kvm_vcpu *vcpu)
2813 u64 host_tsc, tsc_offset;
2816 tsc_offset = vmcs_read64(TSC_OFFSET);
2817 return kvm_scale_tsc(vcpu, host_tsc) + tsc_offset;
2821 * writes 'offset' into guest's timestamp counter offset register
2823 static void vmx_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
2825 if (is_guest_mode(vcpu)) {
2827 * We're here if L1 chose not to trap WRMSR to TSC. According
2828 * to the spec, this should set L1's TSC; The offset that L1
2829 * set for L2 remains unchanged, and still needs to be added
2830 * to the newly set TSC to get L2's TSC.
2832 struct vmcs12 *vmcs12;
2833 /* recalculate vmcs02.TSC_OFFSET: */
2834 vmcs12 = get_vmcs12(vcpu);
2835 vmcs_write64(TSC_OFFSET, offset +
2836 (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING) ?
2837 vmcs12->tsc_offset : 0));
2839 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
2840 vmcs_read64(TSC_OFFSET), offset);
2841 vmcs_write64(TSC_OFFSET, offset);
2845 static bool guest_cpuid_has_vmx(struct kvm_vcpu *vcpu)
2847 struct kvm_cpuid_entry2 *best = kvm_find_cpuid_entry(vcpu, 1, 0);
2848 return best && (best->ecx & (1 << (X86_FEATURE_VMX & 31)));
2852 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
2853 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
2854 * all guests if the "nested" module option is off, and can also be disabled
2855 * for a single guest by disabling its VMX cpuid bit.
2857 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
2859 return nested && guest_cpuid_has_vmx(vcpu);
2863 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
2864 * returned for the various VMX controls MSRs when nested VMX is enabled.
2865 * The same values should also be used to verify that vmcs12 control fields are
2866 * valid during nested entry from L1 to L2.
2867 * Each of these control msrs has a low and high 32-bit half: A low bit is on
2868 * if the corresponding bit in the (32-bit) control field *must* be on, and a
2869 * bit in the high half is on if the corresponding bit in the control field
2870 * may be on. See also vmx_control_verify().
2872 static void nested_vmx_setup_ctls_msrs(struct vcpu_vmx *vmx)
2875 * Note that as a general rule, the high half of the MSRs (bits in
2876 * the control fields which may be 1) should be initialized by the
2877 * intersection of the underlying hardware's MSR (i.e., features which
2878 * can be supported) and the list of features we want to expose -
2879 * because they are known to be properly supported in our code.
2880 * Also, usually, the low half of the MSRs (bits which must be 1) can
2881 * be set to 0, meaning that L1 may turn off any of these bits. The
2882 * reason is that if one of these bits is necessary, it will appear
2883 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
2884 * fields of vmcs01 and vmcs02, will turn these bits off - and
2885 * nested_vmx_exit_handled() will not pass related exits to L1.
2886 * These rules have exceptions below.
2889 /* pin-based controls */
2890 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
2891 vmx->nested.nested_vmx_pinbased_ctls_low,
2892 vmx->nested.nested_vmx_pinbased_ctls_high);
2893 vmx->nested.nested_vmx_pinbased_ctls_low |=
2894 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2895 vmx->nested.nested_vmx_pinbased_ctls_high &=
2896 PIN_BASED_EXT_INTR_MASK |
2897 PIN_BASED_NMI_EXITING |
2898 PIN_BASED_VIRTUAL_NMIS;
2899 vmx->nested.nested_vmx_pinbased_ctls_high |=
2900 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2901 PIN_BASED_VMX_PREEMPTION_TIMER;
2902 if (kvm_vcpu_apicv_active(&vmx->vcpu))
2903 vmx->nested.nested_vmx_pinbased_ctls_high |=
2904 PIN_BASED_POSTED_INTR;
2907 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
2908 vmx->nested.nested_vmx_exit_ctls_low,
2909 vmx->nested.nested_vmx_exit_ctls_high);
2910 vmx->nested.nested_vmx_exit_ctls_low =
2911 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
2913 vmx->nested.nested_vmx_exit_ctls_high &=
2914 #ifdef CONFIG_X86_64
2915 VM_EXIT_HOST_ADDR_SPACE_SIZE |
2917 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
2918 vmx->nested.nested_vmx_exit_ctls_high |=
2919 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
2920 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
2921 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
2923 if (kvm_mpx_supported())
2924 vmx->nested.nested_vmx_exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
2926 /* We support free control of debug control saving. */
2927 vmx->nested.nested_vmx_true_exit_ctls_low =
2928 vmx->nested.nested_vmx_exit_ctls_low &
2929 ~VM_EXIT_SAVE_DEBUG_CONTROLS;
2931 /* entry controls */
2932 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
2933 vmx->nested.nested_vmx_entry_ctls_low,
2934 vmx->nested.nested_vmx_entry_ctls_high);
2935 vmx->nested.nested_vmx_entry_ctls_low =
2936 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
2937 vmx->nested.nested_vmx_entry_ctls_high &=
2938 #ifdef CONFIG_X86_64
2939 VM_ENTRY_IA32E_MODE |
2941 VM_ENTRY_LOAD_IA32_PAT;
2942 vmx->nested.nested_vmx_entry_ctls_high |=
2943 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
2944 if (kvm_mpx_supported())
2945 vmx->nested.nested_vmx_entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
2947 /* We support free control of debug control loading. */
2948 vmx->nested.nested_vmx_true_entry_ctls_low =
2949 vmx->nested.nested_vmx_entry_ctls_low &
2950 ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
2952 /* cpu-based controls */
2953 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
2954 vmx->nested.nested_vmx_procbased_ctls_low,
2955 vmx->nested.nested_vmx_procbased_ctls_high);
2956 vmx->nested.nested_vmx_procbased_ctls_low =
2957 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
2958 vmx->nested.nested_vmx_procbased_ctls_high &=
2959 CPU_BASED_VIRTUAL_INTR_PENDING |
2960 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
2961 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
2962 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
2963 CPU_BASED_CR3_STORE_EXITING |
2964 #ifdef CONFIG_X86_64
2965 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
2967 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
2968 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
2969 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
2970 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
2971 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
2973 * We can allow some features even when not supported by the
2974 * hardware. For example, L1 can specify an MSR bitmap - and we
2975 * can use it to avoid exits to L1 - even when L0 runs L2
2976 * without MSR bitmaps.
2978 vmx->nested.nested_vmx_procbased_ctls_high |=
2979 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
2980 CPU_BASED_USE_MSR_BITMAPS;
2982 /* We support free control of CR3 access interception. */
2983 vmx->nested.nested_vmx_true_procbased_ctls_low =
2984 vmx->nested.nested_vmx_procbased_ctls_low &
2985 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
2987 /* secondary cpu-based controls */
2988 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
2989 vmx->nested.nested_vmx_secondary_ctls_low,
2990 vmx->nested.nested_vmx_secondary_ctls_high);
2991 vmx->nested.nested_vmx_secondary_ctls_low = 0;
2992 vmx->nested.nested_vmx_secondary_ctls_high &=
2993 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
2994 SECONDARY_EXEC_RDTSCP |
2995 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
2996 SECONDARY_EXEC_ENABLE_VPID |
2997 SECONDARY_EXEC_APIC_REGISTER_VIRT |
2998 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
2999 SECONDARY_EXEC_WBINVD_EXITING |
3000 SECONDARY_EXEC_XSAVES;
3003 /* nested EPT: emulate EPT also to L1 */
3004 vmx->nested.nested_vmx_secondary_ctls_high |=
3005 SECONDARY_EXEC_ENABLE_EPT;
3006 vmx->nested.nested_vmx_ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3007 VMX_EPTP_WB_BIT | VMX_EPT_2MB_PAGE_BIT |
3009 if (cpu_has_vmx_ept_execute_only())
3010 vmx->nested.nested_vmx_ept_caps |=
3011 VMX_EPT_EXECUTE_ONLY_BIT;
3012 vmx->nested.nested_vmx_ept_caps &= vmx_capability.ept;
3013 vmx->nested.nested_vmx_ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3014 VMX_EPT_EXTENT_CONTEXT_BIT;
3016 vmx->nested.nested_vmx_ept_caps = 0;
3019 * Old versions of KVM use the single-context version without
3020 * checking for support, so declare that it is supported even
3021 * though it is treated as global context. The alternative is
3022 * not failing the single-context invvpid, and it is worse.
3025 vmx->nested.nested_vmx_vpid_caps = VMX_VPID_INVVPID_BIT |
3026 VMX_VPID_EXTENT_SUPPORTED_MASK;
3028 vmx->nested.nested_vmx_vpid_caps = 0;
3030 if (enable_unrestricted_guest)
3031 vmx->nested.nested_vmx_secondary_ctls_high |=
3032 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3034 /* miscellaneous data */
3035 rdmsr(MSR_IA32_VMX_MISC,
3036 vmx->nested.nested_vmx_misc_low,
3037 vmx->nested.nested_vmx_misc_high);
3038 vmx->nested.nested_vmx_misc_low &= VMX_MISC_SAVE_EFER_LMA;
3039 vmx->nested.nested_vmx_misc_low |=
3040 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3041 VMX_MISC_ACTIVITY_HLT;
3042 vmx->nested.nested_vmx_misc_high = 0;
3045 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3048 * Bits 0 in high must be 0, and bits 1 in low must be 1.
3050 return ((control & high) | low) == control;
3053 static inline u64 vmx_control_msr(u32 low, u32 high)
3055 return low | ((u64)high << 32);
3058 /* Returns 0 on success, non-0 otherwise. */
3059 static int vmx_get_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
3061 struct vcpu_vmx *vmx = to_vmx(vcpu);
3063 switch (msr_index) {
3064 case MSR_IA32_VMX_BASIC:
3066 * This MSR reports some information about VMX support. We
3067 * should return information about the VMX we emulate for the
3068 * guest, and the VMCS structure we give it - not about the
3069 * VMX support of the underlying hardware.
3071 *pdata = VMCS12_REVISION | VMX_BASIC_TRUE_CTLS |
3072 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3073 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3074 if (cpu_has_vmx_basic_inout())
3075 *pdata |= VMX_BASIC_INOUT;
3077 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3078 case MSR_IA32_VMX_PINBASED_CTLS:
3079 *pdata = vmx_control_msr(
3080 vmx->nested.nested_vmx_pinbased_ctls_low,
3081 vmx->nested.nested_vmx_pinbased_ctls_high);
3083 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3084 *pdata = vmx_control_msr(
3085 vmx->nested.nested_vmx_true_procbased_ctls_low,
3086 vmx->nested.nested_vmx_procbased_ctls_high);
3088 case MSR_IA32_VMX_PROCBASED_CTLS:
3089 *pdata = vmx_control_msr(
3090 vmx->nested.nested_vmx_procbased_ctls_low,
3091 vmx->nested.nested_vmx_procbased_ctls_high);
3093 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3094 *pdata = vmx_control_msr(
3095 vmx->nested.nested_vmx_true_exit_ctls_low,
3096 vmx->nested.nested_vmx_exit_ctls_high);
3098 case MSR_IA32_VMX_EXIT_CTLS:
3099 *pdata = vmx_control_msr(
3100 vmx->nested.nested_vmx_exit_ctls_low,
3101 vmx->nested.nested_vmx_exit_ctls_high);
3103 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3104 *pdata = vmx_control_msr(
3105 vmx->nested.nested_vmx_true_entry_ctls_low,
3106 vmx->nested.nested_vmx_entry_ctls_high);
3108 case MSR_IA32_VMX_ENTRY_CTLS:
3109 *pdata = vmx_control_msr(
3110 vmx->nested.nested_vmx_entry_ctls_low,
3111 vmx->nested.nested_vmx_entry_ctls_high);
3113 case MSR_IA32_VMX_MISC:
3114 *pdata = vmx_control_msr(
3115 vmx->nested.nested_vmx_misc_low,
3116 vmx->nested.nested_vmx_misc_high);
3119 * These MSRs specify bits which the guest must keep fixed (on or off)
3120 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3121 * We picked the standard core2 setting.
3123 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3124 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3125 case MSR_IA32_VMX_CR0_FIXED0:
3126 *pdata = VMXON_CR0_ALWAYSON;
3128 case MSR_IA32_VMX_CR0_FIXED1:
3131 case MSR_IA32_VMX_CR4_FIXED0:
3132 *pdata = VMXON_CR4_ALWAYSON;
3134 case MSR_IA32_VMX_CR4_FIXED1:
3137 case MSR_IA32_VMX_VMCS_ENUM:
3138 *pdata = 0x2e; /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3140 case MSR_IA32_VMX_PROCBASED_CTLS2:
3141 *pdata = vmx_control_msr(
3142 vmx->nested.nested_vmx_secondary_ctls_low,
3143 vmx->nested.nested_vmx_secondary_ctls_high);
3145 case MSR_IA32_VMX_EPT_VPID_CAP:
3146 *pdata = vmx->nested.nested_vmx_ept_caps |
3147 ((u64)vmx->nested.nested_vmx_vpid_caps << 32);
3156 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
3159 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
3161 return !(val & ~valid_bits);
3164 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
3170 * Reads an msr value (of 'msr_index') into 'pdata'.
3171 * Returns 0 on success, non-0 otherwise.
3172 * Assumes vcpu_load() was already called.
3174 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3176 struct shared_msr_entry *msr;
3178 switch (msr_info->index) {
3179 #ifdef CONFIG_X86_64
3181 msr_info->data = vmcs_readl(GUEST_FS_BASE);
3184 msr_info->data = vmcs_readl(GUEST_GS_BASE);
3186 case MSR_KERNEL_GS_BASE:
3187 vmx_load_host_state(to_vmx(vcpu));
3188 msr_info->data = to_vmx(vcpu)->msr_guest_kernel_gs_base;
3192 return kvm_get_msr_common(vcpu, msr_info);
3194 msr_info->data = guest_read_tsc(vcpu);
3196 case MSR_IA32_SPEC_CTRL:
3197 if (!msr_info->host_initiated &&
3198 !guest_cpuid_has_spec_ctrl(vcpu))
3201 msr_info->data = to_vmx(vcpu)->spec_ctrl;
3203 case MSR_IA32_SYSENTER_CS:
3204 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
3206 case MSR_IA32_SYSENTER_EIP:
3207 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
3209 case MSR_IA32_SYSENTER_ESP:
3210 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
3212 case MSR_IA32_BNDCFGS:
3213 if (!kvm_mpx_supported() ||
3214 (!msr_info->host_initiated && !guest_cpuid_has_mpx(vcpu)))
3216 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
3218 case MSR_IA32_MCG_EXT_CTL:
3219 if (!msr_info->host_initiated &&
3220 !(to_vmx(vcpu)->msr_ia32_feature_control &
3221 FEATURE_CONTROL_LMCE))
3223 msr_info->data = vcpu->arch.mcg_ext_ctl;
3225 case MSR_IA32_FEATURE_CONTROL:
3226 msr_info->data = to_vmx(vcpu)->msr_ia32_feature_control;
3228 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3229 if (!nested_vmx_allowed(vcpu))
3231 return vmx_get_vmx_msr(vcpu, msr_info->index, &msr_info->data);
3233 if (!vmx_xsaves_supported())
3235 msr_info->data = vcpu->arch.ia32_xss;
3238 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3240 /* Otherwise falls through */
3242 msr = find_msr_entry(to_vmx(vcpu), msr_info->index);
3244 msr_info->data = msr->data;
3247 return kvm_get_msr_common(vcpu, msr_info);
3253 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
3256 * Writes msr value into into the appropriate "register".
3257 * Returns 0 on success, non-0 otherwise.
3258 * Assumes vcpu_load() was already called.
3260 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3262 struct vcpu_vmx *vmx = to_vmx(vcpu);
3263 struct shared_msr_entry *msr;
3265 u32 msr_index = msr_info->index;
3266 u64 data = msr_info->data;
3268 switch (msr_index) {
3270 ret = kvm_set_msr_common(vcpu, msr_info);
3272 #ifdef CONFIG_X86_64
3274 vmx_segment_cache_clear(vmx);
3275 vmcs_writel(GUEST_FS_BASE, data);
3278 vmx_segment_cache_clear(vmx);
3279 vmcs_writel(GUEST_GS_BASE, data);
3281 case MSR_KERNEL_GS_BASE:
3282 vmx_load_host_state(vmx);
3283 vmx->msr_guest_kernel_gs_base = data;
3286 case MSR_IA32_SYSENTER_CS:
3287 vmcs_write32(GUEST_SYSENTER_CS, data);
3289 case MSR_IA32_SYSENTER_EIP:
3290 vmcs_writel(GUEST_SYSENTER_EIP, data);
3292 case MSR_IA32_SYSENTER_ESP:
3293 vmcs_writel(GUEST_SYSENTER_ESP, data);
3295 case MSR_IA32_BNDCFGS:
3296 if (!kvm_mpx_supported() ||
3297 (!msr_info->host_initiated && !guest_cpuid_has_mpx(vcpu)))
3299 if (is_noncanonical_address(data & PAGE_MASK) ||
3300 (data & MSR_IA32_BNDCFGS_RSVD))
3302 vmcs_write64(GUEST_BNDCFGS, data);
3305 kvm_write_tsc(vcpu, msr_info);
3307 case MSR_IA32_SPEC_CTRL:
3308 if (!msr_info->host_initiated &&
3309 !guest_cpuid_has_spec_ctrl(vcpu))
3312 /* The STIBP bit doesn't fault even if it's not advertised */
3313 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3316 vmx->spec_ctrl = data;
3323 * When it's written (to non-zero) for the first time, pass
3327 * The handling of the MSR bitmap for L2 guests is done in
3328 * nested_vmx_merge_msr_bitmap. We should not touch the
3329 * vmcs02.msr_bitmap here since it gets completely overwritten
3330 * in the merging. We update the vmcs01 here for L1 as well
3331 * since it will end up touching the MSR anyway now.
3333 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
3337 case MSR_IA32_PRED_CMD:
3338 if (!msr_info->host_initiated &&
3339 !guest_cpuid_has_ibpb(vcpu))
3342 if (data & ~PRED_CMD_IBPB)
3348 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3352 * When it's written (to non-zero) for the first time, pass
3356 * The handling of the MSR bitmap for L2 guests is done in
3357 * nested_vmx_merge_msr_bitmap. We should not touch the
3358 * vmcs02.msr_bitmap here since it gets completely overwritten
3361 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
3364 case MSR_IA32_CR_PAT:
3365 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
3366 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3368 vmcs_write64(GUEST_IA32_PAT, data);
3369 vcpu->arch.pat = data;
3372 ret = kvm_set_msr_common(vcpu, msr_info);
3374 case MSR_IA32_TSC_ADJUST:
3375 ret = kvm_set_msr_common(vcpu, msr_info);
3377 case MSR_IA32_MCG_EXT_CTL:
3378 if ((!msr_info->host_initiated &&
3379 !(to_vmx(vcpu)->msr_ia32_feature_control &
3380 FEATURE_CONTROL_LMCE)) ||
3381 (data & ~MCG_EXT_CTL_LMCE_EN))
3383 vcpu->arch.mcg_ext_ctl = data;
3385 case MSR_IA32_FEATURE_CONTROL:
3386 if (!vmx_feature_control_msr_valid(vcpu, data) ||
3387 (to_vmx(vcpu)->msr_ia32_feature_control &
3388 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
3390 vmx->msr_ia32_feature_control = data;
3391 if (msr_info->host_initiated && data == 0)
3392 vmx_leave_nested(vcpu);
3394 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
3395 return 1; /* they are read-only */
3397 if (!vmx_xsaves_supported())
3400 * The only supported bit as of Skylake is bit 8, but
3401 * it is not supported on KVM.
3405 vcpu->arch.ia32_xss = data;
3406 if (vcpu->arch.ia32_xss != host_xss)
3407 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
3408 vcpu->arch.ia32_xss, host_xss, false);
3410 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
3413 if (!guest_cpuid_has_rdtscp(vcpu) && !msr_info->host_initiated)
3415 /* Check reserved bit, higher 32 bits should be zero */
3416 if ((data >> 32) != 0)
3418 /* Otherwise falls through */
3420 msr = find_msr_entry(vmx, msr_index);
3422 u64 old_msr_data = msr->data;
3424 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
3426 ret = kvm_set_shared_msr(msr->index, msr->data,
3430 msr->data = old_msr_data;
3434 ret = kvm_set_msr_common(vcpu, msr_info);
3440 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
3442 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
3445 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
3448 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
3450 case VCPU_EXREG_PDPTR:
3452 ept_save_pdptrs(vcpu);
3459 static __init int cpu_has_kvm_support(void)
3461 return cpu_has_vmx();
3464 static __init int vmx_disabled_by_bios(void)
3468 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
3469 if (msr & FEATURE_CONTROL_LOCKED) {
3470 /* launched w/ TXT and VMX disabled */
3471 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3474 /* launched w/o TXT and VMX only enabled w/ TXT */
3475 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3476 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
3477 && !tboot_enabled()) {
3478 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
3479 "activate TXT before enabling KVM\n");
3482 /* launched w/o TXT and VMX disabled */
3483 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
3484 && !tboot_enabled())
3491 static void kvm_cpu_vmxon(u64 addr)
3493 intel_pt_handle_vmx(1);
3495 asm volatile (ASM_VMX_VMXON_RAX
3496 : : "a"(&addr), "m"(addr)
3500 static int hardware_enable(void)
3502 int cpu = raw_smp_processor_id();
3503 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
3506 if (cr4_read_shadow() & X86_CR4_VMXE)
3509 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
3510 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
3511 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
3514 * Now we can enable the vmclear operation in kdump
3515 * since the loaded_vmcss_on_cpu list on this cpu
3516 * has been initialized.
3518 * Though the cpu is not in VMX operation now, there
3519 * is no problem to enable the vmclear operation
3520 * for the loaded_vmcss_on_cpu list is empty!
3522 crash_enable_local_vmclear(cpu);
3524 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
3526 test_bits = FEATURE_CONTROL_LOCKED;
3527 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
3528 if (tboot_enabled())
3529 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
3531 if ((old & test_bits) != test_bits) {
3532 /* enable and lock */
3533 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
3535 cr4_set_bits(X86_CR4_VMXE);
3537 if (vmm_exclusive) {
3538 kvm_cpu_vmxon(phys_addr);
3542 native_store_gdt(this_cpu_ptr(&host_gdt));
3547 static void vmclear_local_loaded_vmcss(void)
3549 int cpu = raw_smp_processor_id();
3550 struct loaded_vmcs *v, *n;
3552 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
3553 loaded_vmcss_on_cpu_link)
3554 __loaded_vmcs_clear(v);
3558 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
3561 static void kvm_cpu_vmxoff(void)
3563 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
3565 intel_pt_handle_vmx(0);
3568 static void hardware_disable(void)
3570 if (vmm_exclusive) {
3571 vmclear_local_loaded_vmcss();
3574 cr4_clear_bits(X86_CR4_VMXE);
3577 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
3578 u32 msr, u32 *result)
3580 u32 vmx_msr_low, vmx_msr_high;
3581 u32 ctl = ctl_min | ctl_opt;
3583 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3585 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
3586 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
3588 /* Ensure minimum (required) set of control bits are supported. */
3596 static __init bool allow_1_setting(u32 msr, u32 ctl)
3598 u32 vmx_msr_low, vmx_msr_high;
3600 rdmsr(msr, vmx_msr_low, vmx_msr_high);
3601 return vmx_msr_high & ctl;
3604 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
3606 u32 vmx_msr_low, vmx_msr_high;
3607 u32 min, opt, min2, opt2;
3608 u32 _pin_based_exec_control = 0;
3609 u32 _cpu_based_exec_control = 0;
3610 u32 _cpu_based_2nd_exec_control = 0;
3611 u32 _vmexit_control = 0;
3612 u32 _vmentry_control = 0;
3614 min = CPU_BASED_HLT_EXITING |
3615 #ifdef CONFIG_X86_64
3616 CPU_BASED_CR8_LOAD_EXITING |
3617 CPU_BASED_CR8_STORE_EXITING |
3619 CPU_BASED_CR3_LOAD_EXITING |
3620 CPU_BASED_CR3_STORE_EXITING |
3621 CPU_BASED_USE_IO_BITMAPS |
3622 CPU_BASED_MOV_DR_EXITING |
3623 CPU_BASED_USE_TSC_OFFSETING |
3624 CPU_BASED_MWAIT_EXITING |
3625 CPU_BASED_MONITOR_EXITING |
3626 CPU_BASED_INVLPG_EXITING |
3627 CPU_BASED_RDPMC_EXITING;
3629 opt = CPU_BASED_TPR_SHADOW |
3630 CPU_BASED_USE_MSR_BITMAPS |
3631 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3632 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
3633 &_cpu_based_exec_control) < 0)
3635 #ifdef CONFIG_X86_64
3636 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3637 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
3638 ~CPU_BASED_CR8_STORE_EXITING;
3640 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
3642 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
3643 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3644 SECONDARY_EXEC_WBINVD_EXITING |
3645 SECONDARY_EXEC_ENABLE_VPID |
3646 SECONDARY_EXEC_ENABLE_EPT |
3647 SECONDARY_EXEC_UNRESTRICTED_GUEST |
3648 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
3649 SECONDARY_EXEC_RDTSCP |
3650 SECONDARY_EXEC_ENABLE_INVPCID |
3651 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3652 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3653 SECONDARY_EXEC_SHADOW_VMCS |
3654 SECONDARY_EXEC_XSAVES |
3655 SECONDARY_EXEC_ENABLE_PML |
3656 SECONDARY_EXEC_TSC_SCALING;
3657 if (adjust_vmx_controls(min2, opt2,
3658 MSR_IA32_VMX_PROCBASED_CTLS2,
3659 &_cpu_based_2nd_exec_control) < 0)
3662 #ifndef CONFIG_X86_64
3663 if (!(_cpu_based_2nd_exec_control &
3664 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
3665 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
3668 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
3669 _cpu_based_2nd_exec_control &= ~(
3670 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3671 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3672 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
3674 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
3675 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
3677 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
3678 CPU_BASED_CR3_STORE_EXITING |
3679 CPU_BASED_INVLPG_EXITING);
3680 rdmsr(MSR_IA32_VMX_EPT_VPID_CAP,
3681 vmx_capability.ept, vmx_capability.vpid);
3684 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
3685 #ifdef CONFIG_X86_64
3686 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
3688 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
3689 VM_EXIT_CLEAR_BNDCFGS;
3690 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
3691 &_vmexit_control) < 0)
3694 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
3695 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
3696 PIN_BASED_VMX_PREEMPTION_TIMER;
3697 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
3698 &_pin_based_exec_control) < 0)
3701 if (cpu_has_broken_vmx_preemption_timer())
3702 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
3703 if (!(_cpu_based_2nd_exec_control &
3704 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
3705 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
3707 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
3708 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
3709 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
3710 &_vmentry_control) < 0)
3713 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
3715 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
3716 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
3719 #ifdef CONFIG_X86_64
3720 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
3721 if (vmx_msr_high & (1u<<16))
3725 /* Require Write-Back (WB) memory type for VMCS accesses. */
3726 if (((vmx_msr_high >> 18) & 15) != 6)
3729 vmcs_conf->size = vmx_msr_high & 0x1fff;
3730 vmcs_conf->order = get_order(vmcs_conf->size);
3731 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
3732 vmcs_conf->revision_id = vmx_msr_low;
3734 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
3735 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
3736 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
3737 vmcs_conf->vmexit_ctrl = _vmexit_control;
3738 vmcs_conf->vmentry_ctrl = _vmentry_control;
3740 cpu_has_load_ia32_efer =
3741 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3742 VM_ENTRY_LOAD_IA32_EFER)
3743 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3744 VM_EXIT_LOAD_IA32_EFER);
3746 cpu_has_load_perf_global_ctrl =
3747 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
3748 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
3749 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
3750 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
3753 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
3754 * but due to errata below it can't be used. Workaround is to use
3755 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
3757 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
3762 * BC86,AAY89,BD102 (model 44)
3766 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
3767 switch (boot_cpu_data.x86_model) {
3773 cpu_has_load_perf_global_ctrl = false;
3774 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
3775 "does not work properly. Using workaround\n");
3782 if (boot_cpu_has(X86_FEATURE_XSAVES))
3783 rdmsrl(MSR_IA32_XSS, host_xss);
3788 static struct vmcs *alloc_vmcs_cpu(int cpu)
3790 int node = cpu_to_node(cpu);
3794 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
3797 vmcs = page_address(pages);
3798 memset(vmcs, 0, vmcs_config.size);
3799 vmcs->revision_id = vmcs_config.revision_id; /* vmcs revision id */
3803 static void free_vmcs(struct vmcs *vmcs)
3805 free_pages((unsigned long)vmcs, vmcs_config.order);
3809 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
3811 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3813 if (!loaded_vmcs->vmcs)
3815 loaded_vmcs_clear(loaded_vmcs);
3816 free_vmcs(loaded_vmcs->vmcs);
3817 loaded_vmcs->vmcs = NULL;
3818 if (loaded_vmcs->msr_bitmap)
3819 free_page((unsigned long)loaded_vmcs->msr_bitmap);
3820 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
3823 static struct vmcs *alloc_vmcs(void)
3825 return alloc_vmcs_cpu(raw_smp_processor_id());
3828 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
3830 loaded_vmcs->vmcs = alloc_vmcs();
3831 if (!loaded_vmcs->vmcs)
3834 loaded_vmcs->shadow_vmcs = NULL;
3835 loaded_vmcs_init(loaded_vmcs);
3837 if (cpu_has_vmx_msr_bitmap()) {
3838 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
3839 if (!loaded_vmcs->msr_bitmap)
3841 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
3846 free_loaded_vmcs(loaded_vmcs);
3850 static void free_kvm_area(void)
3854 for_each_possible_cpu(cpu) {
3855 free_vmcs(per_cpu(vmxarea, cpu));
3856 per_cpu(vmxarea, cpu) = NULL;
3860 static void init_vmcs_shadow_fields(void)
3864 /* No checks for read only fields yet */
3866 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
3867 switch (shadow_read_write_fields[i]) {
3869 if (!kvm_mpx_supported())
3877 shadow_read_write_fields[j] =
3878 shadow_read_write_fields[i];
3881 max_shadow_read_write_fields = j;
3883 /* shadowed fields guest access without vmexit */
3884 for (i = 0; i < max_shadow_read_write_fields; i++) {
3885 clear_bit(shadow_read_write_fields[i],
3886 vmx_vmwrite_bitmap);
3887 clear_bit(shadow_read_write_fields[i],
3890 for (i = 0; i < max_shadow_read_only_fields; i++)
3891 clear_bit(shadow_read_only_fields[i],
3895 static __init int alloc_kvm_area(void)
3899 for_each_possible_cpu(cpu) {
3902 vmcs = alloc_vmcs_cpu(cpu);
3908 per_cpu(vmxarea, cpu) = vmcs;
3913 static bool emulation_required(struct kvm_vcpu *vcpu)
3915 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3918 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
3919 struct kvm_segment *save)
3921 if (!emulate_invalid_guest_state) {
3923 * CS and SS RPL should be equal during guest entry according
3924 * to VMX spec, but in reality it is not always so. Since vcpu
3925 * is in the middle of the transition from real mode to
3926 * protected mode it is safe to assume that RPL 0 is a good
3929 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
3930 save->selector &= ~SEGMENT_RPL_MASK;
3931 save->dpl = save->selector & SEGMENT_RPL_MASK;
3934 vmx_set_segment(vcpu, save, seg);
3937 static void enter_pmode(struct kvm_vcpu *vcpu)
3939 unsigned long flags;
3940 struct vcpu_vmx *vmx = to_vmx(vcpu);
3943 * Update real mode segment cache. It may be not up-to-date if sement
3944 * register was written while vcpu was in a guest mode.
3946 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
3947 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
3948 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
3949 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
3950 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
3951 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
3953 vmx->rmode.vm86_active = 0;
3955 vmx_segment_cache_clear(vmx);
3957 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
3959 flags = vmcs_readl(GUEST_RFLAGS);
3960 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3961 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3962 vmcs_writel(GUEST_RFLAGS, flags);
3964 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
3965 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
3967 update_exception_bitmap(vcpu);
3969 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
3970 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
3971 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
3972 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
3973 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
3974 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
3977 static void fix_rmode_seg(int seg, struct kvm_segment *save)
3979 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
3980 struct kvm_segment var = *save;
3983 if (seg == VCPU_SREG_CS)
3986 if (!emulate_invalid_guest_state) {
3987 var.selector = var.base >> 4;
3988 var.base = var.base & 0xffff0;
3998 if (save->base & 0xf)
3999 printk_once(KERN_WARNING "kvm: segment base is not "
4000 "paragraph aligned when entering "
4001 "protected mode (seg=%d)", seg);
4004 vmcs_write16(sf->selector, var.selector);
4005 vmcs_writel(sf->base, var.base);
4006 vmcs_write32(sf->limit, var.limit);
4007 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
4010 static void enter_rmode(struct kvm_vcpu *vcpu)
4012 unsigned long flags;
4013 struct vcpu_vmx *vmx = to_vmx(vcpu);
4015 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4016 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4017 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4018 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4019 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4020 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4021 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4023 vmx->rmode.vm86_active = 1;
4026 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
4027 * vcpu. Warn the user that an update is overdue.
4029 if (!vcpu->kvm->arch.tss_addr)
4030 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
4031 "called before entering vcpu\n");
4033 vmx_segment_cache_clear(vmx);
4035 vmcs_writel(GUEST_TR_BASE, vcpu->kvm->arch.tss_addr);
4036 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
4037 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
4039 flags = vmcs_readl(GUEST_RFLAGS);
4040 vmx->rmode.save_rflags = flags;
4042 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
4044 vmcs_writel(GUEST_RFLAGS, flags);
4045 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
4046 update_exception_bitmap(vcpu);
4048 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4049 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4050 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4051 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4052 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4053 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4055 kvm_mmu_reset_context(vcpu);
4058 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
4060 struct vcpu_vmx *vmx = to_vmx(vcpu);
4061 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
4067 * Force kernel_gs_base reloading before EFER changes, as control
4068 * of this msr depends on is_long_mode().
4070 vmx_load_host_state(to_vmx(vcpu));
4071 vcpu->arch.efer = efer;
4072 if (efer & EFER_LMA) {
4073 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4076 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4078 msr->data = efer & ~EFER_LME;
4083 #ifdef CONFIG_X86_64
4085 static void enter_lmode(struct kvm_vcpu *vcpu)
4089 vmx_segment_cache_clear(to_vmx(vcpu));
4091 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
4092 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
4093 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
4095 vmcs_write32(GUEST_TR_AR_BYTES,
4096 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
4097 | VMX_AR_TYPE_BUSY_64_TSS);
4099 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
4102 static void exit_lmode(struct kvm_vcpu *vcpu)
4104 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
4105 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
4110 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid)
4112 vpid_sync_context(vpid);
4114 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4116 ept_sync_context(construct_eptp(vcpu->arch.mmu.root_hpa));
4120 static void vmx_flush_tlb(struct kvm_vcpu *vcpu)
4122 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid);
4125 static void vmx_flush_tlb_ept_only(struct kvm_vcpu *vcpu)
4128 vmx_flush_tlb(vcpu);
4131 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
4133 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
4135 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
4136 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
4139 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
4141 if (enable_ept && is_paging(vcpu))
4142 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
4143 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
4146 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
4148 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
4150 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
4151 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
4154 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
4156 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4158 if (!test_bit(VCPU_EXREG_PDPTR,
4159 (unsigned long *)&vcpu->arch.regs_dirty))
4162 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4163 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
4164 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
4165 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
4166 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
4170 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
4172 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
4174 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
4175 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
4176 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
4177 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
4178 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
4181 __set_bit(VCPU_EXREG_PDPTR,
4182 (unsigned long *)&vcpu->arch.regs_avail);
4183 __set_bit(VCPU_EXREG_PDPTR,
4184 (unsigned long *)&vcpu->arch.regs_dirty);
4187 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
4189 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
4191 struct kvm_vcpu *vcpu)
4193 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
4194 vmx_decache_cr3(vcpu);
4195 if (!(cr0 & X86_CR0_PG)) {
4196 /* From paging/starting to nonpaging */
4197 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4198 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
4199 (CPU_BASED_CR3_LOAD_EXITING |
4200 CPU_BASED_CR3_STORE_EXITING));
4201 vcpu->arch.cr0 = cr0;
4202 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4203 } else if (!is_paging(vcpu)) {
4204 /* From nonpaging to paging */
4205 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
4206 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
4207 ~(CPU_BASED_CR3_LOAD_EXITING |
4208 CPU_BASED_CR3_STORE_EXITING));
4209 vcpu->arch.cr0 = cr0;
4210 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
4213 if (!(cr0 & X86_CR0_WP))
4214 *hw_cr0 &= ~X86_CR0_WP;
4217 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
4219 struct vcpu_vmx *vmx = to_vmx(vcpu);
4220 unsigned long hw_cr0;
4222 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
4223 if (enable_unrestricted_guest)
4224 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
4226 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
4228 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
4231 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
4235 #ifdef CONFIG_X86_64
4236 if (vcpu->arch.efer & EFER_LME) {
4237 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
4239 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
4245 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
4247 if (!vcpu->fpu_active)
4248 hw_cr0 |= X86_CR0_TS | X86_CR0_MP;
4250 vmcs_writel(CR0_READ_SHADOW, cr0);
4251 vmcs_writel(GUEST_CR0, hw_cr0);
4252 vcpu->arch.cr0 = cr0;
4254 /* depends on vcpu->arch.cr0 to be set to a new value */
4255 vmx->emulation_required = emulation_required(vcpu);
4258 static u64 construct_eptp(unsigned long root_hpa)
4262 /* TODO write the value reading from MSR */
4263 eptp = VMX_EPT_DEFAULT_MT |
4264 VMX_EPT_DEFAULT_GAW << VMX_EPT_GAW_EPTP_SHIFT;
4265 if (enable_ept_ad_bits)
4266 eptp |= VMX_EPT_AD_ENABLE_BIT;
4267 eptp |= (root_hpa & PAGE_MASK);
4272 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
4274 unsigned long guest_cr3;
4279 eptp = construct_eptp(cr3);
4280 vmcs_write64(EPT_POINTER, eptp);
4281 if (is_paging(vcpu) || is_guest_mode(vcpu))
4282 guest_cr3 = kvm_read_cr3(vcpu);
4284 guest_cr3 = vcpu->kvm->arch.ept_identity_map_addr;
4285 ept_load_pdptrs(vcpu);
4288 vmx_flush_tlb(vcpu);
4289 vmcs_writel(GUEST_CR3, guest_cr3);
4292 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
4295 * Pass through host's Machine Check Enable value to hw_cr4, which
4296 * is in force while we are in guest mode. Do not let guests control
4297 * this bit, even if host CR4.MCE == 0.
4299 unsigned long hw_cr4 =
4300 (cr4_read_shadow() & X86_CR4_MCE) |
4301 (cr4 & ~X86_CR4_MCE) |
4302 (to_vmx(vcpu)->rmode.vm86_active ?
4303 KVM_RMODE_VM_CR4_ALWAYS_ON : KVM_PMODE_VM_CR4_ALWAYS_ON);
4305 if (cr4 & X86_CR4_VMXE) {
4307 * To use VMXON (and later other VMX instructions), a guest
4308 * must first be able to turn on cr4.VMXE (see handle_vmon()).
4309 * So basically the check on whether to allow nested VMX
4312 if (!nested_vmx_allowed(vcpu))
4315 if (to_vmx(vcpu)->nested.vmxon &&
4316 ((cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON))
4319 vcpu->arch.cr4 = cr4;
4321 if (!is_paging(vcpu)) {
4322 hw_cr4 &= ~X86_CR4_PAE;
4323 hw_cr4 |= X86_CR4_PSE;
4324 } else if (!(cr4 & X86_CR4_PAE)) {
4325 hw_cr4 &= ~X86_CR4_PAE;
4329 if (!enable_unrestricted_guest && !is_paging(vcpu))
4331 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
4332 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
4333 * to be manually disabled when guest switches to non-paging
4336 * If !enable_unrestricted_guest, the CPU is always running
4337 * with CR0.PG=1 and CR4 needs to be modified.
4338 * If enable_unrestricted_guest, the CPU automatically
4339 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
4341 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
4343 vmcs_writel(CR4_READ_SHADOW, cr4);
4344 vmcs_writel(GUEST_CR4, hw_cr4);
4348 static void vmx_get_segment(struct kvm_vcpu *vcpu,
4349 struct kvm_segment *var, int seg)
4351 struct vcpu_vmx *vmx = to_vmx(vcpu);
4354 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4355 *var = vmx->rmode.segs[seg];
4356 if (seg == VCPU_SREG_TR
4357 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
4359 var->base = vmx_read_guest_seg_base(vmx, seg);
4360 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4363 var->base = vmx_read_guest_seg_base(vmx, seg);
4364 var->limit = vmx_read_guest_seg_limit(vmx, seg);
4365 var->selector = vmx_read_guest_seg_selector(vmx, seg);
4366 ar = vmx_read_guest_seg_ar(vmx, seg);
4367 var->unusable = (ar >> 16) & 1;
4368 var->type = ar & 15;
4369 var->s = (ar >> 4) & 1;
4370 var->dpl = (ar >> 5) & 3;
4372 * Some userspaces do not preserve unusable property. Since usable
4373 * segment has to be present according to VMX spec we can use present
4374 * property to amend userspace bug by making unusable segment always
4375 * nonpresent. vmx_segment_access_rights() already marks nonpresent
4376 * segment as unusable.
4378 var->present = !var->unusable;
4379 var->avl = (ar >> 12) & 1;
4380 var->l = (ar >> 13) & 1;
4381 var->db = (ar >> 14) & 1;
4382 var->g = (ar >> 15) & 1;
4385 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
4387 struct kvm_segment s;
4389 if (to_vmx(vcpu)->rmode.vm86_active) {
4390 vmx_get_segment(vcpu, &s, seg);
4393 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
4396 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
4398 struct vcpu_vmx *vmx = to_vmx(vcpu);
4400 if (unlikely(vmx->rmode.vm86_active))
4403 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
4404 return VMX_AR_DPL(ar);
4408 static u32 vmx_segment_access_rights(struct kvm_segment *var)
4412 if (var->unusable || !var->present)
4415 ar = var->type & 15;
4416 ar |= (var->s & 1) << 4;
4417 ar |= (var->dpl & 3) << 5;
4418 ar |= (var->present & 1) << 7;
4419 ar |= (var->avl & 1) << 12;
4420 ar |= (var->l & 1) << 13;
4421 ar |= (var->db & 1) << 14;
4422 ar |= (var->g & 1) << 15;
4428 static void vmx_set_segment(struct kvm_vcpu *vcpu,
4429 struct kvm_segment *var, int seg)
4431 struct vcpu_vmx *vmx = to_vmx(vcpu);
4432 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4434 vmx_segment_cache_clear(vmx);
4436 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
4437 vmx->rmode.segs[seg] = *var;
4438 if (seg == VCPU_SREG_TR)
4439 vmcs_write16(sf->selector, var->selector);
4441 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
4445 vmcs_writel(sf->base, var->base);
4446 vmcs_write32(sf->limit, var->limit);
4447 vmcs_write16(sf->selector, var->selector);
4450 * Fix the "Accessed" bit in AR field of segment registers for older
4452 * IA32 arch specifies that at the time of processor reset the
4453 * "Accessed" bit in the AR field of segment registers is 1. And qemu
4454 * is setting it to 0 in the userland code. This causes invalid guest
4455 * state vmexit when "unrestricted guest" mode is turned on.
4456 * Fix for this setup issue in cpu_reset is being pushed in the qemu
4457 * tree. Newer qemu binaries with that qemu fix would not need this
4460 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
4461 var->type |= 0x1; /* Accessed */
4463 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
4466 vmx->emulation_required = emulation_required(vcpu);
4469 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
4471 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
4473 *db = (ar >> 14) & 1;
4474 *l = (ar >> 13) & 1;
4477 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4479 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
4480 dt->address = vmcs_readl(GUEST_IDTR_BASE);
4483 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4485 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
4486 vmcs_writel(GUEST_IDTR_BASE, dt->address);
4489 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4491 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
4492 dt->address = vmcs_readl(GUEST_GDTR_BASE);
4495 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
4497 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
4498 vmcs_writel(GUEST_GDTR_BASE, dt->address);
4501 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
4503 struct kvm_segment var;
4506 vmx_get_segment(vcpu, &var, seg);
4508 if (seg == VCPU_SREG_CS)
4510 ar = vmx_segment_access_rights(&var);
4512 if (var.base != (var.selector << 4))
4514 if (var.limit != 0xffff)
4522 static bool code_segment_valid(struct kvm_vcpu *vcpu)
4524 struct kvm_segment cs;
4525 unsigned int cs_rpl;
4527 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4528 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
4532 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
4536 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
4537 if (cs.dpl > cs_rpl)
4540 if (cs.dpl != cs_rpl)
4546 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
4550 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
4552 struct kvm_segment ss;
4553 unsigned int ss_rpl;
4555 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4556 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
4560 if (ss.type != 3 && ss.type != 7)
4564 if (ss.dpl != ss_rpl) /* DPL != RPL */
4572 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
4574 struct kvm_segment var;
4577 vmx_get_segment(vcpu, &var, seg);
4578 rpl = var.selector & SEGMENT_RPL_MASK;
4586 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
4587 if (var.dpl < rpl) /* DPL < RPL */
4591 /* TODO: Add other members to kvm_segment_field to allow checking for other access
4597 static bool tr_valid(struct kvm_vcpu *vcpu)
4599 struct kvm_segment tr;
4601 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
4605 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4607 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
4615 static bool ldtr_valid(struct kvm_vcpu *vcpu)
4617 struct kvm_segment ldtr;
4619 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
4623 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
4633 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
4635 struct kvm_segment cs, ss;
4637 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
4638 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
4640 return ((cs.selector & SEGMENT_RPL_MASK) ==
4641 (ss.selector & SEGMENT_RPL_MASK));
4645 * Check if guest state is valid. Returns true if valid, false if
4647 * We assume that registers are always usable
4649 static bool guest_state_valid(struct kvm_vcpu *vcpu)
4651 if (enable_unrestricted_guest)
4654 /* real mode guest state checks */
4655 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
4656 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
4658 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
4660 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
4662 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
4664 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
4666 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
4669 /* protected mode guest state checks */
4670 if (!cs_ss_rpl_check(vcpu))
4672 if (!code_segment_valid(vcpu))
4674 if (!stack_segment_valid(vcpu))
4676 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
4678 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
4680 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
4682 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
4684 if (!tr_valid(vcpu))
4686 if (!ldtr_valid(vcpu))
4690 * - Add checks on RIP
4691 * - Add checks on RFLAGS
4697 static int init_rmode_tss(struct kvm *kvm)
4703 idx = srcu_read_lock(&kvm->srcu);
4704 fn = kvm->arch.tss_addr >> PAGE_SHIFT;
4705 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4708 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
4709 r = kvm_write_guest_page(kvm, fn++, &data,
4710 TSS_IOPB_BASE_OFFSET, sizeof(u16));
4713 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
4716 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
4720 r = kvm_write_guest_page(kvm, fn, &data,
4721 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
4724 srcu_read_unlock(&kvm->srcu, idx);
4728 static int init_rmode_identity_map(struct kvm *kvm)
4731 kvm_pfn_t identity_map_pfn;
4737 /* Protect kvm->arch.ept_identity_pagetable_done. */
4738 mutex_lock(&kvm->slots_lock);
4740 if (likely(kvm->arch.ept_identity_pagetable_done))
4743 identity_map_pfn = kvm->arch.ept_identity_map_addr >> PAGE_SHIFT;
4745 r = alloc_identity_pagetable(kvm);
4749 idx = srcu_read_lock(&kvm->srcu);
4750 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
4753 /* Set up identity-mapping pagetable for EPT in real mode */
4754 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
4755 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
4756 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
4757 r = kvm_write_guest_page(kvm, identity_map_pfn,
4758 &tmp, i * sizeof(tmp), sizeof(tmp));
4762 kvm->arch.ept_identity_pagetable_done = true;
4765 srcu_read_unlock(&kvm->srcu, idx);
4768 mutex_unlock(&kvm->slots_lock);
4772 static void seg_setup(int seg)
4774 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4777 vmcs_write16(sf->selector, 0);
4778 vmcs_writel(sf->base, 0);
4779 vmcs_write32(sf->limit, 0xffff);
4781 if (seg == VCPU_SREG_CS)
4782 ar |= 0x08; /* code segment */
4784 vmcs_write32(sf->ar_bytes, ar);
4787 static int alloc_apic_access_page(struct kvm *kvm)
4792 mutex_lock(&kvm->slots_lock);
4793 if (kvm->arch.apic_access_page_done)
4795 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
4796 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
4800 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
4801 if (is_error_page(page)) {
4807 * Do not pin the page in memory, so that memory hot-unplug
4808 * is able to migrate it.
4811 kvm->arch.apic_access_page_done = true;
4813 mutex_unlock(&kvm->slots_lock);
4817 static int alloc_identity_pagetable(struct kvm *kvm)
4819 /* Called with kvm->slots_lock held. */
4823 BUG_ON(kvm->arch.ept_identity_pagetable_done);
4825 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
4826 kvm->arch.ept_identity_map_addr, PAGE_SIZE);
4831 static int allocate_vpid(void)
4837 spin_lock(&vmx_vpid_lock);
4838 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
4839 if (vpid < VMX_NR_VPIDS)
4840 __set_bit(vpid, vmx_vpid_bitmap);
4843 spin_unlock(&vmx_vpid_lock);
4847 static void free_vpid(int vpid)
4849 if (!enable_vpid || vpid == 0)
4851 spin_lock(&vmx_vpid_lock);
4852 __clear_bit(vpid, vmx_vpid_bitmap);
4853 spin_unlock(&vmx_vpid_lock);
4856 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
4859 int f = sizeof(unsigned long);
4861 if (!cpu_has_vmx_msr_bitmap())
4865 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4866 * have the write-low and read-high bitmap offsets the wrong way round.
4867 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4869 if (msr <= 0x1fff) {
4870 if (type & MSR_TYPE_R)
4872 __clear_bit(msr, msr_bitmap + 0x000 / f);
4874 if (type & MSR_TYPE_W)
4876 __clear_bit(msr, msr_bitmap + 0x800 / f);
4878 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4880 if (type & MSR_TYPE_R)
4882 __clear_bit(msr, msr_bitmap + 0x400 / f);
4884 if (type & MSR_TYPE_W)
4886 __clear_bit(msr, msr_bitmap + 0xc00 / f);
4891 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
4894 int f = sizeof(unsigned long);
4896 if (!cpu_has_vmx_msr_bitmap())
4900 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4901 * have the write-low and read-high bitmap offsets the wrong way round.
4902 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4904 if (msr <= 0x1fff) {
4905 if (type & MSR_TYPE_R)
4907 __set_bit(msr, msr_bitmap + 0x000 / f);
4909 if (type & MSR_TYPE_W)
4911 __set_bit(msr, msr_bitmap + 0x800 / f);
4913 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4915 if (type & MSR_TYPE_R)
4917 __set_bit(msr, msr_bitmap + 0x400 / f);
4919 if (type & MSR_TYPE_W)
4921 __set_bit(msr, msr_bitmap + 0xc00 / f);
4926 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
4927 u32 msr, int type, bool value)
4930 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
4932 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
4936 * If a msr is allowed by L0, we should check whether it is allowed by L1.
4937 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
4939 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
4940 unsigned long *msr_bitmap_nested,
4943 int f = sizeof(unsigned long);
4945 if (!cpu_has_vmx_msr_bitmap()) {
4951 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
4952 * have the write-low and read-high bitmap offsets the wrong way round.
4953 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
4955 if (msr <= 0x1fff) {
4956 if (type & MSR_TYPE_R &&
4957 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
4959 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
4961 if (type & MSR_TYPE_W &&
4962 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
4964 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
4966 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
4968 if (type & MSR_TYPE_R &&
4969 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
4971 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
4973 if (type & MSR_TYPE_W &&
4974 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
4976 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
4981 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
4985 if (cpu_has_secondary_exec_ctrls() &&
4986 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
4987 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
4988 mode |= MSR_BITMAP_MODE_X2APIC;
4989 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
4990 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
4993 if (is_long_mode(vcpu))
4994 mode |= MSR_BITMAP_MODE_LM;
4999 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
5001 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
5006 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
5007 unsigned word = msr / BITS_PER_LONG;
5008 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
5009 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
5012 if (mode & MSR_BITMAP_MODE_X2APIC) {
5014 * TPR reads and writes can be virtualized even if virtual interrupt
5015 * delivery is not in use.
5017 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
5018 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
5019 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
5020 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
5021 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
5026 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
5028 struct vcpu_vmx *vmx = to_vmx(vcpu);
5029 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
5030 u8 mode = vmx_msr_bitmap_mode(vcpu);
5031 u8 changed = mode ^ vmx->msr_bitmap_mode;
5036 vmx_set_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW,
5037 !(mode & MSR_BITMAP_MODE_LM));
5039 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
5040 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
5042 vmx->msr_bitmap_mode = mode;
5045 static bool vmx_get_enable_apicv(void)
5047 return enable_apicv;
5050 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
5052 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5056 * Don't need to mark the APIC access page dirty; it is never
5057 * written to by the CPU during APIC virtualization.
5060 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
5061 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
5062 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5065 if (nested_cpu_has_posted_intr(vmcs12)) {
5066 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
5067 kvm_vcpu_mark_page_dirty(vcpu, gfn);
5072 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
5074 struct vcpu_vmx *vmx = to_vmx(vcpu);
5079 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
5082 vmx->nested.pi_pending = false;
5083 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
5086 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
5087 if (max_irr != 256) {
5088 vapic_page = kmap(vmx->nested.virtual_apic_page);
5089 __kvm_apic_update_irr(vmx->nested.pi_desc->pir, vapic_page);
5090 kunmap(vmx->nested.virtual_apic_page);
5092 status = vmcs_read16(GUEST_INTR_STATUS);
5093 if ((u8)max_irr > ((u8)status & 0xff)) {
5095 status |= (u8)max_irr;
5096 vmcs_write16(GUEST_INTR_STATUS, status);
5100 nested_mark_vmcs12_pages_dirty(vcpu);
5103 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu)
5106 if (vcpu->mode == IN_GUEST_MODE) {
5108 * The vector of interrupt to be delivered to vcpu had
5109 * been set in PIR before this function.
5111 * Following cases will be reached in this block, and
5112 * we always send a notification event in all cases as
5115 * Case 1: vcpu keeps in non-root mode. Sending a
5116 * notification event posts the interrupt to vcpu.
5118 * Case 2: vcpu exits to root mode and is still
5119 * runnable. PIR will be synced to vIRR before the
5120 * next vcpu entry. Sending a notification event in
5121 * this case has no effect, as vcpu is not in root
5124 * Case 3: vcpu exits to root mode and is blocked.
5125 * vcpu_block() has already synced PIR to vIRR and
5126 * never blocks vcpu if vIRR is not cleared. Therefore,
5127 * a blocked vcpu here does not wait for any requested
5128 * interrupts in PIR, and sending a notification event
5129 * which has no effect is safe here.
5132 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu),
5133 POSTED_INTR_VECTOR);
5140 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
5143 struct vcpu_vmx *vmx = to_vmx(vcpu);
5145 if (is_guest_mode(vcpu) &&
5146 vector == vmx->nested.posted_intr_nv) {
5148 * If a posted intr is not recognized by hardware,
5149 * we will accomplish it in the next vmentry.
5151 vmx->nested.pi_pending = true;
5152 kvm_make_request(KVM_REQ_EVENT, vcpu);
5153 /* the PIR and ON have been set by L1. */
5154 if (!kvm_vcpu_trigger_posted_interrupt(vcpu))
5155 kvm_vcpu_kick(vcpu);
5161 * Send interrupt to vcpu via posted interrupt way.
5162 * 1. If target vcpu is running(non-root mode), send posted interrupt
5163 * notification to vcpu and hardware will sync PIR to vIRR atomically.
5164 * 2. If target vcpu isn't running(root mode), kick it to pick up the
5165 * interrupt from PIR in next vmentry.
5167 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
5169 struct vcpu_vmx *vmx = to_vmx(vcpu);
5172 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
5176 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
5179 r = pi_test_and_set_on(&vmx->pi_desc);
5180 kvm_make_request(KVM_REQ_EVENT, vcpu);
5181 if (r || !kvm_vcpu_trigger_posted_interrupt(vcpu))
5182 kvm_vcpu_kick(vcpu);
5185 static void vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
5187 struct vcpu_vmx *vmx = to_vmx(vcpu);
5189 if (!pi_test_and_clear_on(&vmx->pi_desc))
5192 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir);
5196 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
5197 * will not change in the lifetime of the guest.
5198 * Note that host-state that does change is set elsewhere. E.g., host-state
5199 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
5201 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
5208 vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
5209 vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
5211 /* Save the most likely value for this task's CR4 in the VMCS. */
5212 cr4 = cr4_read_shadow();
5213 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
5214 vmx->host_state.vmcs_host_cr4 = cr4;
5216 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
5217 #ifdef CONFIG_X86_64
5219 * Load null selectors, so we can avoid reloading them in
5220 * __vmx_load_host_state(), in case userspace uses the null selectors
5221 * too (the expected case).
5223 vmcs_write16(HOST_DS_SELECTOR, 0);
5224 vmcs_write16(HOST_ES_SELECTOR, 0);
5226 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5227 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5229 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
5230 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
5232 native_store_idt(&dt);
5233 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
5234 vmx->host_idt_base = dt.address;
5236 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
5238 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
5239 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
5240 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
5241 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
5243 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
5244 rdmsr(MSR_IA32_CR_PAT, low32, high32);
5245 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
5249 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
5251 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
5253 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
5254 if (is_guest_mode(&vmx->vcpu))
5255 vmx->vcpu.arch.cr4_guest_owned_bits &=
5256 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
5257 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
5260 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
5262 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
5264 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5265 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
5266 /* Enable the preemption timer dynamically */
5267 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
5268 return pin_based_exec_ctrl;
5271 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5273 struct vcpu_vmx *vmx = to_vmx(vcpu);
5275 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5276 if (cpu_has_secondary_exec_ctrls()) {
5277 if (kvm_vcpu_apicv_active(vcpu))
5278 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5279 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5280 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5282 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5283 SECONDARY_EXEC_APIC_REGISTER_VIRT |
5284 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5287 if (cpu_has_vmx_msr_bitmap())
5288 vmx_update_msr_bitmap(vcpu);
5291 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
5293 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
5295 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
5296 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
5298 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
5299 exec_control &= ~CPU_BASED_TPR_SHADOW;
5300 #ifdef CONFIG_X86_64
5301 exec_control |= CPU_BASED_CR8_STORE_EXITING |
5302 CPU_BASED_CR8_LOAD_EXITING;
5306 exec_control |= CPU_BASED_CR3_STORE_EXITING |
5307 CPU_BASED_CR3_LOAD_EXITING |
5308 CPU_BASED_INVLPG_EXITING;
5309 return exec_control;
5312 static u32 vmx_secondary_exec_control(struct vcpu_vmx *vmx)
5314 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
5315 if (!cpu_need_virtualize_apic_accesses(&vmx->vcpu))
5316 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
5318 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
5320 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
5321 enable_unrestricted_guest = 0;
5322 /* Enable INVPCID for non-ept guests may cause performance regression. */
5323 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
5325 if (!enable_unrestricted_guest)
5326 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
5328 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
5329 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
5330 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
5331 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
5332 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
5333 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
5335 We can NOT enable shadow_vmcs here because we don't have yet
5338 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
5341 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
5343 return exec_control;
5346 static void ept_set_mmio_spte_mask(void)
5349 * EPT Misconfigurations can be generated if the value of bits 2:0
5350 * of an EPT paging-structure entry is 110b (write/execute).
5351 * Also, magic bits (0x3ull << 62) is set to quickly identify mmio
5354 kvm_mmu_set_mmio_spte_mask((0x3ull << 62) | 0x6ull);
5357 #define VMX_XSS_EXIT_BITMAP 0
5359 * Sets up the vmcs for emulated real mode.
5361 static int vmx_vcpu_setup(struct vcpu_vmx *vmx)
5363 #ifdef CONFIG_X86_64
5369 vmcs_write64(IO_BITMAP_A, __pa(vmx_io_bitmap_a));
5370 vmcs_write64(IO_BITMAP_B, __pa(vmx_io_bitmap_b));
5372 if (enable_shadow_vmcs) {
5373 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
5374 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
5376 if (cpu_has_vmx_msr_bitmap())
5377 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
5379 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
5382 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
5383 vmx->hv_deadline_tsc = -1;
5385 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
5387 if (cpu_has_secondary_exec_ctrls()) {
5388 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
5389 vmx_secondary_exec_control(vmx));
5392 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
5393 vmcs_write64(EOI_EXIT_BITMAP0, 0);
5394 vmcs_write64(EOI_EXIT_BITMAP1, 0);
5395 vmcs_write64(EOI_EXIT_BITMAP2, 0);
5396 vmcs_write64(EOI_EXIT_BITMAP3, 0);
5398 vmcs_write16(GUEST_INTR_STATUS, 0);
5400 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
5401 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
5405 vmcs_write32(PLE_GAP, ple_gap);
5406 vmx->ple_window = ple_window;
5407 vmx->ple_window_dirty = true;
5410 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
5411 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
5412 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
5414 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
5415 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
5416 vmx_set_constant_host_state(vmx);
5417 #ifdef CONFIG_X86_64
5418 rdmsrl(MSR_FS_BASE, a);
5419 vmcs_writel(HOST_FS_BASE, a); /* 22.2.4 */
5420 rdmsrl(MSR_GS_BASE, a);
5421 vmcs_writel(HOST_GS_BASE, a); /* 22.2.4 */
5423 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
5424 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
5427 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
5428 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
5429 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
5430 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
5431 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
5433 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
5434 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
5436 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
5437 u32 index = vmx_msr_index[i];
5438 u32 data_low, data_high;
5441 if (rdmsr_safe(index, &data_low, &data_high) < 0)
5443 if (wrmsr_safe(index, data_low, data_high) < 0)
5445 vmx->guest_msrs[j].index = i;
5446 vmx->guest_msrs[j].data = 0;
5447 vmx->guest_msrs[j].mask = -1ull;
5451 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
5453 /* 22.2.1, 20.8.1 */
5454 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
5456 vmcs_writel(CR0_GUEST_HOST_MASK, ~0UL);
5457 set_cr4_guest_host_mask(vmx);
5459 if (vmx_xsaves_supported())
5460 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
5463 ASSERT(vmx->pml_pg);
5464 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
5465 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
5471 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
5473 struct vcpu_vmx *vmx = to_vmx(vcpu);
5474 struct msr_data apic_base_msr;
5477 vmx->rmode.vm86_active = 0;
5478 vcpu->arch.microcode_version = 0x100000000ULL;
5481 vmx->soft_vnmi_blocked = 0;
5483 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
5484 kvm_set_cr8(vcpu, 0);
5487 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
5488 MSR_IA32_APICBASE_ENABLE;
5489 if (kvm_vcpu_is_reset_bsp(vcpu))
5490 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
5491 apic_base_msr.host_initiated = true;
5492 kvm_set_apic_base(vcpu, &apic_base_msr);
5495 vmx_segment_cache_clear(vmx);
5497 seg_setup(VCPU_SREG_CS);
5498 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
5499 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
5501 seg_setup(VCPU_SREG_DS);
5502 seg_setup(VCPU_SREG_ES);
5503 seg_setup(VCPU_SREG_FS);
5504 seg_setup(VCPU_SREG_GS);
5505 seg_setup(VCPU_SREG_SS);
5507 vmcs_write16(GUEST_TR_SELECTOR, 0);
5508 vmcs_writel(GUEST_TR_BASE, 0);
5509 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
5510 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5512 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
5513 vmcs_writel(GUEST_LDTR_BASE, 0);
5514 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
5515 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
5518 vmcs_write32(GUEST_SYSENTER_CS, 0);
5519 vmcs_writel(GUEST_SYSENTER_ESP, 0);
5520 vmcs_writel(GUEST_SYSENTER_EIP, 0);
5521 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
5524 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
5525 kvm_rip_write(vcpu, 0xfff0);
5527 vmcs_writel(GUEST_GDTR_BASE, 0);
5528 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
5530 vmcs_writel(GUEST_IDTR_BASE, 0);
5531 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
5533 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
5534 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
5535 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
5539 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
5541 if (cpu_has_vmx_tpr_shadow() && !init_event) {
5542 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
5543 if (cpu_need_tpr_shadow(vcpu))
5544 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
5545 __pa(vcpu->arch.apic->regs));
5546 vmcs_write32(TPR_THRESHOLD, 0);
5549 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
5551 if (kvm_vcpu_apicv_active(vcpu))
5552 memset(&vmx->pi_desc, 0, sizeof(struct pi_desc));
5555 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
5557 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
5558 vmx->vcpu.arch.cr0 = cr0;
5559 vmx_set_cr0(vcpu, cr0); /* enter rmode */
5560 vmx_set_cr4(vcpu, 0);
5561 vmx_set_efer(vcpu, 0);
5562 vmx_fpu_activate(vcpu);
5563 update_exception_bitmap(vcpu);
5565 vpid_sync_context(vmx->vpid);
5569 * In nested virtualization, check if L1 asked to exit on external interrupts.
5570 * For most existing hypervisors, this will always return true.
5572 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
5574 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5575 PIN_BASED_EXT_INTR_MASK;
5579 * In nested virtualization, check if L1 has set
5580 * VM_EXIT_ACK_INTR_ON_EXIT
5582 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
5584 return get_vmcs12(vcpu)->vm_exit_controls &
5585 VM_EXIT_ACK_INTR_ON_EXIT;
5588 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
5590 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
5591 PIN_BASED_NMI_EXITING;
5594 static void enable_irq_window(struct kvm_vcpu *vcpu)
5596 u32 cpu_based_vm_exec_control;
5598 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5599 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_INTR_PENDING;
5600 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5603 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5605 u32 cpu_based_vm_exec_control;
5607 if (!cpu_has_virtual_nmis() ||
5608 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
5609 enable_irq_window(vcpu);
5613 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
5614 cpu_based_vm_exec_control |= CPU_BASED_VIRTUAL_NMI_PENDING;
5615 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
5618 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
5620 struct vcpu_vmx *vmx = to_vmx(vcpu);
5622 int irq = vcpu->arch.interrupt.nr;
5624 trace_kvm_inj_virq(irq);
5626 ++vcpu->stat.irq_injections;
5627 if (vmx->rmode.vm86_active) {
5629 if (vcpu->arch.interrupt.soft)
5630 inc_eip = vcpu->arch.event_exit_inst_len;
5631 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
5632 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5635 intr = irq | INTR_INFO_VALID_MASK;
5636 if (vcpu->arch.interrupt.soft) {
5637 intr |= INTR_TYPE_SOFT_INTR;
5638 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
5639 vmx->vcpu.arch.event_exit_inst_len);
5641 intr |= INTR_TYPE_EXT_INTR;
5642 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
5645 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
5647 struct vcpu_vmx *vmx = to_vmx(vcpu);
5649 if (!is_guest_mode(vcpu)) {
5650 if (!cpu_has_virtual_nmis()) {
5652 * Tracking the NMI-blocked state in software is built upon
5653 * finding the next open IRQ window. This, in turn, depends on
5654 * well-behaving guests: They have to keep IRQs disabled at
5655 * least as long as the NMI handler runs. Otherwise we may
5656 * cause NMI nesting, maybe breaking the guest. But as this is
5657 * highly unlikely, we can live with the residual risk.
5659 vmx->soft_vnmi_blocked = 1;
5660 vmx->vnmi_blocked_time = 0;
5663 ++vcpu->stat.nmi_injections;
5664 vmx->nmi_known_unmasked = false;
5667 if (vmx->rmode.vm86_active) {
5668 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
5669 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
5673 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
5674 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
5677 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
5679 if (!cpu_has_virtual_nmis())
5680 return to_vmx(vcpu)->soft_vnmi_blocked;
5681 if (to_vmx(vcpu)->nmi_known_unmasked)
5683 return vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
5686 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5688 struct vcpu_vmx *vmx = to_vmx(vcpu);
5690 if (!cpu_has_virtual_nmis()) {
5691 if (vmx->soft_vnmi_blocked != masked) {
5692 vmx->soft_vnmi_blocked = masked;
5693 vmx->vnmi_blocked_time = 0;
5696 vmx->nmi_known_unmasked = !masked;
5698 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
5699 GUEST_INTR_STATE_NMI);
5701 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
5702 GUEST_INTR_STATE_NMI);
5706 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
5708 if (to_vmx(vcpu)->nested.nested_run_pending)
5711 if (!cpu_has_virtual_nmis() && to_vmx(vcpu)->soft_vnmi_blocked)
5714 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5715 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
5716 | GUEST_INTR_STATE_NMI));
5719 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
5721 return (!to_vmx(vcpu)->nested.nested_run_pending &&
5722 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
5723 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
5724 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
5727 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
5731 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
5735 kvm->arch.tss_addr = addr;
5736 return init_rmode_tss(kvm);
5739 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
5744 * Update instruction length as we may reinject the exception
5745 * from user space while in guest debugging mode.
5747 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
5748 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5749 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
5753 if (vcpu->guest_debug &
5754 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
5771 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
5772 int vec, u32 err_code)
5775 * Instruction with address size override prefix opcode 0x67
5776 * Cause the #SS fault with 0 error code in VM86 mode.
5778 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
5779 if (emulate_instruction(vcpu, 0) == EMULATE_DONE) {
5780 if (vcpu->arch.halt_request) {
5781 vcpu->arch.halt_request = 0;
5782 return kvm_vcpu_halt(vcpu);
5790 * Forward all other exceptions that are valid in real mode.
5791 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
5792 * the required debugging infrastructure rework.
5794 kvm_queue_exception(vcpu, vec);
5799 * Trigger machine check on the host. We assume all the MSRs are already set up
5800 * by the CPU and that we still run on the same CPU as the MCE occurred on.
5801 * We pass a fake environment to the machine check handler because we want
5802 * the guest to be always treated like user space, no matter what context
5803 * it used internally.
5805 static void kvm_machine_check(void)
5807 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
5808 struct pt_regs regs = {
5809 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
5810 .flags = X86_EFLAGS_IF,
5813 do_machine_check(®s, 0);
5817 static int handle_machine_check(struct kvm_vcpu *vcpu)
5819 /* already handled by vcpu_run */
5823 static int handle_exception(struct kvm_vcpu *vcpu)
5825 struct vcpu_vmx *vmx = to_vmx(vcpu);
5826 struct kvm_run *kvm_run = vcpu->run;
5827 u32 intr_info, ex_no, error_code;
5828 unsigned long cr2, rip, dr6;
5830 enum emulation_result er;
5832 vect_info = vmx->idt_vectoring_info;
5833 intr_info = vmx->exit_intr_info;
5835 if (is_machine_check(intr_info))
5836 return handle_machine_check(vcpu);
5838 if (is_nmi(intr_info))
5839 return 1; /* already handled by vmx_vcpu_run() */
5841 if (is_no_device(intr_info)) {
5842 vmx_fpu_activate(vcpu);
5846 if (is_invalid_opcode(intr_info)) {
5847 if (is_guest_mode(vcpu)) {
5848 kvm_queue_exception(vcpu, UD_VECTOR);
5851 er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD);
5852 if (er == EMULATE_USER_EXIT)
5854 if (er != EMULATE_DONE)
5855 kvm_queue_exception(vcpu, UD_VECTOR);
5860 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
5861 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
5864 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
5865 * MMIO, it is better to report an internal error.
5866 * See the comments in vmx_handle_exit.
5868 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
5869 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
5870 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
5871 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
5872 vcpu->run->internal.ndata = 3;
5873 vcpu->run->internal.data[0] = vect_info;
5874 vcpu->run->internal.data[1] = intr_info;
5875 vcpu->run->internal.data[2] = error_code;
5879 if (is_page_fault(intr_info)) {
5880 /* EPT won't cause page fault directly */
5882 cr2 = vmcs_readl(EXIT_QUALIFICATION);
5883 trace_kvm_page_fault(cr2, error_code);
5884 vcpu->arch.l1tf_flush_l1d = true;
5886 if (kvm_event_needs_reinjection(vcpu))
5887 kvm_mmu_unprotect_page_virt(vcpu, cr2);
5888 return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0);
5891 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
5893 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
5894 return handle_rmode_exception(vcpu, ex_no, error_code);
5898 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
5901 dr6 = vmcs_readl(EXIT_QUALIFICATION);
5902 if (!(vcpu->guest_debug &
5903 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
5904 vcpu->arch.dr6 &= ~15;
5905 vcpu->arch.dr6 |= dr6 | DR6_RTM;
5906 if (is_icebp(intr_info))
5907 skip_emulated_instruction(vcpu);
5909 kvm_queue_exception(vcpu, DB_VECTOR);
5912 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
5913 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
5917 * Update instruction length as we may reinject #BP from
5918 * user space while in guest debugging mode. Reading it for
5919 * #DB as well causes no harm, it is not used in that case.
5921 vmx->vcpu.arch.event_exit_inst_len =
5922 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
5923 kvm_run->exit_reason = KVM_EXIT_DEBUG;
5924 rip = kvm_rip_read(vcpu);
5925 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
5926 kvm_run->debug.arch.exception = ex_no;
5929 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
5930 kvm_run->ex.exception = ex_no;
5931 kvm_run->ex.error_code = error_code;
5937 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
5939 ++vcpu->stat.irq_exits;
5943 static int handle_triple_fault(struct kvm_vcpu *vcpu)
5945 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
5946 vcpu->mmio_needed = 0;
5950 static int handle_io(struct kvm_vcpu *vcpu)
5952 unsigned long exit_qualification;
5953 int size, in, string;
5956 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
5957 string = (exit_qualification & 16) != 0;
5958 in = (exit_qualification & 8) != 0;
5960 ++vcpu->stat.io_exits;
5963 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
5965 port = exit_qualification >> 16;
5966 size = (exit_qualification & 7) + 1;
5967 skip_emulated_instruction(vcpu);
5969 return kvm_fast_pio_out(vcpu, size, port);
5973 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5976 * Patch in the VMCALL instruction:
5978 hypercall[0] = 0x0f;
5979 hypercall[1] = 0x01;
5980 hypercall[2] = 0xc1;
5983 static bool nested_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5985 unsigned long always_on = VMXON_CR0_ALWAYSON;
5986 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5988 if (to_vmx(vcpu)->nested.nested_vmx_secondary_ctls_high &
5989 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5990 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5991 always_on &= ~(X86_CR0_PE | X86_CR0_PG);
5992 return (val & always_on) == always_on;
5995 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
5996 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
5998 if (is_guest_mode(vcpu)) {
5999 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6000 unsigned long orig_val = val;
6003 * We get here when L2 changed cr0 in a way that did not change
6004 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
6005 * but did change L0 shadowed bits. So we first calculate the
6006 * effective cr0 value that L1 would like to write into the
6007 * hardware. It consists of the L2-owned bits from the new
6008 * value combined with the L1-owned bits from L1's guest_cr0.
6010 val = (val & ~vmcs12->cr0_guest_host_mask) |
6011 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
6013 if (!nested_cr0_valid(vcpu, val))
6016 if (kvm_set_cr0(vcpu, val))
6018 vmcs_writel(CR0_READ_SHADOW, orig_val);
6021 if (to_vmx(vcpu)->nested.vmxon &&
6022 ((val & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON))
6024 return kvm_set_cr0(vcpu, val);
6028 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
6030 if (is_guest_mode(vcpu)) {
6031 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6032 unsigned long orig_val = val;
6034 /* analogously to handle_set_cr0 */
6035 val = (val & ~vmcs12->cr4_guest_host_mask) |
6036 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
6037 if (kvm_set_cr4(vcpu, val))
6039 vmcs_writel(CR4_READ_SHADOW, orig_val);
6042 return kvm_set_cr4(vcpu, val);
6045 /* called to set cr0 as appropriate for clts instruction exit. */
6046 static void handle_clts(struct kvm_vcpu *vcpu)
6048 if (is_guest_mode(vcpu)) {
6050 * We get here when L2 did CLTS, and L1 didn't shadow CR0.TS
6051 * but we did (!fpu_active). We need to keep GUEST_CR0.TS on,
6052 * just pretend it's off (also in arch.cr0 for fpu_activate).
6054 vmcs_writel(CR0_READ_SHADOW,
6055 vmcs_readl(CR0_READ_SHADOW) & ~X86_CR0_TS);
6056 vcpu->arch.cr0 &= ~X86_CR0_TS;
6058 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
6061 static int handle_cr(struct kvm_vcpu *vcpu)
6063 unsigned long exit_qualification, val;
6068 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6069 cr = exit_qualification & 15;
6070 reg = (exit_qualification >> 8) & 15;
6071 switch ((exit_qualification >> 4) & 3) {
6072 case 0: /* mov to cr */
6073 val = kvm_register_readl(vcpu, reg);
6074 trace_kvm_cr_write(cr, val);
6077 err = handle_set_cr0(vcpu, val);
6078 kvm_complete_insn_gp(vcpu, err);
6081 err = kvm_set_cr3(vcpu, val);
6082 kvm_complete_insn_gp(vcpu, err);
6085 err = handle_set_cr4(vcpu, val);
6086 kvm_complete_insn_gp(vcpu, err);
6089 u8 cr8_prev = kvm_get_cr8(vcpu);
6091 err = kvm_set_cr8(vcpu, cr8);
6092 kvm_complete_insn_gp(vcpu, err);
6093 if (lapic_in_kernel(vcpu))
6095 if (cr8_prev <= cr8)
6097 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
6104 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
6105 skip_emulated_instruction(vcpu);
6106 vmx_fpu_activate(vcpu);
6108 case 1: /*mov from cr*/
6111 val = kvm_read_cr3(vcpu);
6112 kvm_register_write(vcpu, reg, val);
6113 trace_kvm_cr_read(cr, val);
6114 skip_emulated_instruction(vcpu);
6117 val = kvm_get_cr8(vcpu);
6118 kvm_register_write(vcpu, reg, val);
6119 trace_kvm_cr_read(cr, val);
6120 skip_emulated_instruction(vcpu);
6125 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
6126 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
6127 kvm_lmsw(vcpu, val);
6129 skip_emulated_instruction(vcpu);
6134 vcpu->run->exit_reason = 0;
6135 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
6136 (int)(exit_qualification >> 4) & 3, cr);
6140 static int handle_dr(struct kvm_vcpu *vcpu)
6142 unsigned long exit_qualification;
6145 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6146 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
6148 /* First, if DR does not exist, trigger UD */
6149 if (!kvm_require_dr(vcpu, dr))
6152 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
6153 if (!kvm_require_cpl(vcpu, 0))
6155 dr7 = vmcs_readl(GUEST_DR7);
6158 * As the vm-exit takes precedence over the debug trap, we
6159 * need to emulate the latter, either for the host or the
6160 * guest debugging itself.
6162 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
6163 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
6164 vcpu->run->debug.arch.dr7 = dr7;
6165 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
6166 vcpu->run->debug.arch.exception = DB_VECTOR;
6167 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
6170 vcpu->arch.dr6 &= ~15;
6171 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
6172 kvm_queue_exception(vcpu, DB_VECTOR);
6177 if (vcpu->guest_debug == 0) {
6178 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
6179 CPU_BASED_MOV_DR_EXITING);
6182 * No more DR vmexits; force a reload of the debug registers
6183 * and reenter on this instruction. The next vmexit will
6184 * retrieve the full state of the debug registers.
6186 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
6190 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
6191 if (exit_qualification & TYPE_MOV_FROM_DR) {
6194 if (kvm_get_dr(vcpu, dr, &val))
6196 kvm_register_write(vcpu, reg, val);
6198 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
6201 skip_emulated_instruction(vcpu);
6205 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
6207 return vcpu->arch.dr6;
6210 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
6214 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
6216 get_debugreg(vcpu->arch.db[0], 0);
6217 get_debugreg(vcpu->arch.db[1], 1);
6218 get_debugreg(vcpu->arch.db[2], 2);
6219 get_debugreg(vcpu->arch.db[3], 3);
6220 get_debugreg(vcpu->arch.dr6, 6);
6221 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
6223 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
6224 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
6227 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
6229 vmcs_writel(GUEST_DR7, val);
6232 static int handle_cpuid(struct kvm_vcpu *vcpu)
6234 kvm_emulate_cpuid(vcpu);
6238 static int handle_rdmsr(struct kvm_vcpu *vcpu)
6240 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6241 struct msr_data msr_info;
6243 msr_info.index = ecx;
6244 msr_info.host_initiated = false;
6245 if (vmx_get_msr(vcpu, &msr_info)) {
6246 trace_kvm_msr_read_ex(ecx);
6247 kvm_inject_gp(vcpu, 0);
6251 trace_kvm_msr_read(ecx, msr_info.data);
6253 /* FIXME: handling of bits 32:63 of rax, rdx */
6254 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
6255 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
6256 skip_emulated_instruction(vcpu);
6260 static int handle_wrmsr(struct kvm_vcpu *vcpu)
6262 struct msr_data msr;
6263 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
6264 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
6265 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
6269 msr.host_initiated = false;
6270 if (kvm_set_msr(vcpu, &msr) != 0) {
6271 trace_kvm_msr_write_ex(ecx, data);
6272 kvm_inject_gp(vcpu, 0);
6276 trace_kvm_msr_write(ecx, data);
6277 skip_emulated_instruction(vcpu);
6281 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
6283 kvm_make_request(KVM_REQ_EVENT, vcpu);
6287 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
6289 u32 cpu_based_vm_exec_control;
6291 /* clear pending irq */
6292 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6293 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
6294 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
6296 kvm_make_request(KVM_REQ_EVENT, vcpu);
6298 ++vcpu->stat.irq_window_exits;
6302 static int handle_halt(struct kvm_vcpu *vcpu)
6304 return kvm_emulate_halt(vcpu);
6307 static int handle_vmcall(struct kvm_vcpu *vcpu)
6309 return kvm_emulate_hypercall(vcpu);
6312 static int handle_invd(struct kvm_vcpu *vcpu)
6314 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6317 static int handle_invlpg(struct kvm_vcpu *vcpu)
6319 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6321 kvm_mmu_invlpg(vcpu, exit_qualification);
6322 skip_emulated_instruction(vcpu);
6326 static int handle_rdpmc(struct kvm_vcpu *vcpu)
6330 err = kvm_rdpmc(vcpu);
6331 kvm_complete_insn_gp(vcpu, err);
6336 static int handle_wbinvd(struct kvm_vcpu *vcpu)
6338 kvm_emulate_wbinvd(vcpu);
6342 static int handle_xsetbv(struct kvm_vcpu *vcpu)
6344 u64 new_bv = kvm_read_edx_eax(vcpu);
6345 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
6347 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
6348 skip_emulated_instruction(vcpu);
6352 static int handle_xsaves(struct kvm_vcpu *vcpu)
6354 skip_emulated_instruction(vcpu);
6355 WARN(1, "this should never happen\n");
6359 static int handle_xrstors(struct kvm_vcpu *vcpu)
6361 skip_emulated_instruction(vcpu);
6362 WARN(1, "this should never happen\n");
6366 static int handle_apic_access(struct kvm_vcpu *vcpu)
6368 if (likely(fasteoi)) {
6369 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6370 int access_type, offset;
6372 access_type = exit_qualification & APIC_ACCESS_TYPE;
6373 offset = exit_qualification & APIC_ACCESS_OFFSET;
6375 * Sane guest uses MOV to write EOI, with written value
6376 * not cared. So make a short-circuit here by avoiding
6377 * heavy instruction emulation.
6379 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
6380 (offset == APIC_EOI)) {
6381 kvm_lapic_set_eoi(vcpu);
6382 skip_emulated_instruction(vcpu);
6386 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
6389 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
6391 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6392 int vector = exit_qualification & 0xff;
6394 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
6395 kvm_apic_set_eoi_accelerated(vcpu, vector);
6399 static int handle_apic_write(struct kvm_vcpu *vcpu)
6401 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6402 u32 offset = exit_qualification & 0xfff;
6404 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
6405 kvm_apic_write_nodecode(vcpu, offset);
6409 static int handle_task_switch(struct kvm_vcpu *vcpu)
6411 struct vcpu_vmx *vmx = to_vmx(vcpu);
6412 unsigned long exit_qualification;
6413 bool has_error_code = false;
6416 int reason, type, idt_v, idt_index;
6418 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
6419 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
6420 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
6422 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6424 reason = (u32)exit_qualification >> 30;
6425 if (reason == TASK_SWITCH_GATE && idt_v) {
6427 case INTR_TYPE_NMI_INTR:
6428 vcpu->arch.nmi_injected = false;
6429 vmx_set_nmi_mask(vcpu, true);
6431 case INTR_TYPE_EXT_INTR:
6432 case INTR_TYPE_SOFT_INTR:
6433 kvm_clear_interrupt_queue(vcpu);
6435 case INTR_TYPE_HARD_EXCEPTION:
6436 if (vmx->idt_vectoring_info &
6437 VECTORING_INFO_DELIVER_CODE_MASK) {
6438 has_error_code = true;
6440 vmcs_read32(IDT_VECTORING_ERROR_CODE);
6443 case INTR_TYPE_SOFT_EXCEPTION:
6444 kvm_clear_exception_queue(vcpu);
6450 tss_selector = exit_qualification;
6452 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
6453 type != INTR_TYPE_EXT_INTR &&
6454 type != INTR_TYPE_NMI_INTR))
6455 skip_emulated_instruction(vcpu);
6457 if (kvm_task_switch(vcpu, tss_selector,
6458 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
6459 has_error_code, error_code) == EMULATE_FAIL) {
6460 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6461 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6462 vcpu->run->internal.ndata = 0;
6467 * TODO: What about debug traps on tss switch?
6468 * Are we supposed to inject them and update dr6?
6474 static int handle_ept_violation(struct kvm_vcpu *vcpu)
6476 unsigned long exit_qualification;
6481 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
6483 gla_validity = (exit_qualification >> 7) & 0x3;
6484 if (gla_validity == 0x2) {
6485 printk(KERN_ERR "EPT: Handling EPT violation failed!\n");
6486 printk(KERN_ERR "EPT: GPA: 0x%lx, GVA: 0x%lx\n",
6487 (long unsigned int)vmcs_read64(GUEST_PHYSICAL_ADDRESS),
6488 vmcs_readl(GUEST_LINEAR_ADDRESS));
6489 printk(KERN_ERR "EPT: Exit qualification is 0x%lx\n",
6490 (long unsigned int)exit_qualification);
6491 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6492 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_VIOLATION;
6497 * EPT violation happened while executing iret from NMI,
6498 * "blocked by NMI" bit has to be set before next VM entry.
6499 * There are errata that may cause this bit to not be set:
6502 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
6503 cpu_has_virtual_nmis() &&
6504 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
6505 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
6507 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6508 trace_kvm_page_fault(gpa, exit_qualification);
6510 /* it is a read fault? */
6511 error_code = (exit_qualification << 2) & PFERR_USER_MASK;
6512 /* it is a write fault? */
6513 error_code |= exit_qualification & PFERR_WRITE_MASK;
6514 /* It is a fetch fault? */
6515 error_code |= (exit_qualification << 2) & PFERR_FETCH_MASK;
6516 /* ept page table is present? */
6517 error_code |= (exit_qualification & 0x38) != 0;
6519 vcpu->arch.exit_qualification = exit_qualification;
6521 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
6524 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
6529 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
6530 if (!kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
6531 trace_kvm_fast_mmio(gpa);
6533 * Doing kvm_skip_emulated_instruction() depends on undefined
6534 * behavior: Intel's manual doesn't mandate
6535 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
6536 * occurs and while on real hardware it was observed to be set,
6537 * other hypervisors (namely Hyper-V) don't set it, we end up
6538 * advancing IP with some random value. Disable fast mmio when
6539 * running nested and keep it for real hardware in hope that
6540 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
6542 if (!static_cpu_has(X86_FEATURE_HYPERVISOR)) {
6543 skip_emulated_instruction(vcpu);
6547 return x86_emulate_instruction(vcpu, gpa, EMULTYPE_SKIP,
6548 NULL, 0) == EMULATE_DONE;
6551 ret = kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
6555 /* It is the real ept misconfig */
6558 vcpu->run->exit_reason = KVM_EXIT_UNKNOWN;
6559 vcpu->run->hw.hardware_exit_reason = EXIT_REASON_EPT_MISCONFIG;
6564 static int handle_nmi_window(struct kvm_vcpu *vcpu)
6566 u32 cpu_based_vm_exec_control;
6568 /* clear pending NMI */
6569 cpu_based_vm_exec_control = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6570 cpu_based_vm_exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
6571 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control);
6572 ++vcpu->stat.nmi_window_exits;
6573 kvm_make_request(KVM_REQ_EVENT, vcpu);
6578 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
6580 struct vcpu_vmx *vmx = to_vmx(vcpu);
6581 enum emulation_result err = EMULATE_DONE;
6584 bool intr_window_requested;
6585 unsigned count = 130;
6587 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
6588 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
6590 while (vmx->emulation_required && count-- != 0) {
6591 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
6592 return handle_interrupt_window(&vmx->vcpu);
6594 if (test_bit(KVM_REQ_EVENT, &vcpu->requests))
6597 err = emulate_instruction(vcpu, 0);
6599 if (err == EMULATE_USER_EXIT) {
6600 ++vcpu->stat.mmio_exits;
6605 if (err != EMULATE_DONE)
6606 goto emulation_error;
6608 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
6609 vcpu->arch.exception.pending)
6610 goto emulation_error;
6612 if (vcpu->arch.halt_request) {
6613 vcpu->arch.halt_request = 0;
6614 ret = kvm_vcpu_halt(vcpu);
6618 if (signal_pending(current))
6628 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
6629 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
6630 vcpu->run->internal.ndata = 0;
6634 static int __grow_ple_window(int val)
6636 if (ple_window_grow < 1)
6639 val = min(val, ple_window_actual_max);
6641 if (ple_window_grow < ple_window)
6642 val *= ple_window_grow;
6644 val += ple_window_grow;
6649 static int __shrink_ple_window(int val, int modifier, int minimum)
6654 if (modifier < ple_window)
6659 return max(val, minimum);
6662 static void grow_ple_window(struct kvm_vcpu *vcpu)
6664 struct vcpu_vmx *vmx = to_vmx(vcpu);
6665 int old = vmx->ple_window;
6667 vmx->ple_window = __grow_ple_window(old);
6669 if (vmx->ple_window != old)
6670 vmx->ple_window_dirty = true;
6672 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
6675 static void shrink_ple_window(struct kvm_vcpu *vcpu)
6677 struct vcpu_vmx *vmx = to_vmx(vcpu);
6678 int old = vmx->ple_window;
6680 vmx->ple_window = __shrink_ple_window(old,
6681 ple_window_shrink, ple_window);
6683 if (vmx->ple_window != old)
6684 vmx->ple_window_dirty = true;
6686 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
6690 * ple_window_actual_max is computed to be one grow_ple_window() below
6691 * ple_window_max. (See __grow_ple_window for the reason.)
6692 * This prevents overflows, because ple_window_max is int.
6693 * ple_window_max effectively rounded down to a multiple of ple_window_grow in
6695 * ple_window_max is also prevented from setting vmx->ple_window < ple_window.
6697 static void update_ple_window_actual_max(void)
6699 ple_window_actual_max =
6700 __shrink_ple_window(max(ple_window_max, ple_window),
6701 ple_window_grow, INT_MIN);
6705 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
6707 static void wakeup_handler(void)
6709 struct kvm_vcpu *vcpu;
6710 int cpu = smp_processor_id();
6712 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6713 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
6714 blocked_vcpu_list) {
6715 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
6717 if (pi_test_on(pi_desc) == 1)
6718 kvm_vcpu_kick(vcpu);
6720 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
6723 static __init int hardware_setup(void)
6727 rdmsrl_safe(MSR_EFER, &host_efer);
6729 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
6730 kvm_define_shared_msr(i, vmx_msr_index[i]);
6732 vmx_io_bitmap_a = (unsigned long *)__get_free_page(GFP_KERNEL);
6733 if (!vmx_io_bitmap_a)
6736 vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL);
6737 if (!vmx_io_bitmap_b)
6740 vmx_vmread_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6741 if (!vmx_vmread_bitmap)
6744 vmx_vmwrite_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
6745 if (!vmx_vmwrite_bitmap)
6748 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
6749 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
6751 memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE);
6753 memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE);
6755 if (setup_vmcs_config(&vmcs_config) < 0) {
6760 if (boot_cpu_has(X86_FEATURE_NX))
6761 kvm_enable_efer_bits(EFER_NX);
6763 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
6764 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
6767 if (!cpu_has_vmx_shadow_vmcs())
6768 enable_shadow_vmcs = 0;
6769 if (enable_shadow_vmcs)
6770 init_vmcs_shadow_fields();
6772 if (!cpu_has_vmx_ept() ||
6773 !cpu_has_vmx_ept_4levels()) {
6775 enable_unrestricted_guest = 0;
6776 enable_ept_ad_bits = 0;
6779 if (!cpu_has_vmx_ept_ad_bits())
6780 enable_ept_ad_bits = 0;
6782 if (!cpu_has_vmx_unrestricted_guest())
6783 enable_unrestricted_guest = 0;
6785 if (!cpu_has_vmx_flexpriority())
6786 flexpriority_enabled = 0;
6789 * set_apic_access_page_addr() is used to reload apic access
6790 * page upon invalidation. No need to do anything if not
6791 * using the APIC_ACCESS_ADDR VMCS field.
6793 if (!flexpriority_enabled)
6794 kvm_x86_ops->set_apic_access_page_addr = NULL;
6796 if (!cpu_has_vmx_tpr_shadow())
6797 kvm_x86_ops->update_cr8_intercept = NULL;
6799 if (enable_ept && !cpu_has_vmx_ept_2m_page())
6800 kvm_disable_largepages();
6802 if (!cpu_has_vmx_ple())
6805 if (!cpu_has_vmx_apicv())
6808 if (cpu_has_vmx_tsc_scaling()) {
6809 kvm_has_tsc_control = true;
6810 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
6811 kvm_tsc_scaling_ratio_frac_bits = 48;
6814 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
6817 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
6818 (enable_ept_ad_bits) ? VMX_EPT_ACCESS_BIT : 0ull,
6819 (enable_ept_ad_bits) ? VMX_EPT_DIRTY_BIT : 0ull,
6820 0ull, VMX_EPT_EXECUTABLE_MASK,
6821 cpu_has_vmx_ept_execute_only() ?
6822 0ull : VMX_EPT_READABLE_MASK);
6823 ept_set_mmio_spte_mask();
6828 update_ple_window_actual_max();
6831 * Only enable PML when hardware supports PML feature, and both EPT
6832 * and EPT A/D bit features are enabled -- PML depends on them to work.
6834 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
6838 kvm_x86_ops->slot_enable_log_dirty = NULL;
6839 kvm_x86_ops->slot_disable_log_dirty = NULL;
6840 kvm_x86_ops->flush_log_dirty = NULL;
6841 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
6844 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
6847 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
6848 cpu_preemption_timer_multi =
6849 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
6851 kvm_x86_ops->set_hv_timer = NULL;
6852 kvm_x86_ops->cancel_hv_timer = NULL;
6855 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
6857 kvm_mce_cap_supported |= MCG_LMCE_P;
6859 return alloc_kvm_area();
6862 free_page((unsigned long)vmx_vmwrite_bitmap);
6864 free_page((unsigned long)vmx_vmread_bitmap);
6866 free_page((unsigned long)vmx_io_bitmap_b);
6868 free_page((unsigned long)vmx_io_bitmap_a);
6873 static __exit void hardware_unsetup(void)
6875 free_page((unsigned long)vmx_io_bitmap_b);
6876 free_page((unsigned long)vmx_io_bitmap_a);
6877 free_page((unsigned long)vmx_vmwrite_bitmap);
6878 free_page((unsigned long)vmx_vmread_bitmap);
6884 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
6885 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
6887 static int handle_pause(struct kvm_vcpu *vcpu)
6890 grow_ple_window(vcpu);
6892 skip_emulated_instruction(vcpu);
6893 kvm_vcpu_on_spin(vcpu);
6898 static int handle_nop(struct kvm_vcpu *vcpu)
6900 skip_emulated_instruction(vcpu);
6904 static int handle_mwait(struct kvm_vcpu *vcpu)
6906 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
6907 return handle_nop(vcpu);
6910 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
6915 static int handle_monitor(struct kvm_vcpu *vcpu)
6917 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
6918 return handle_nop(vcpu);
6922 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
6923 * set the success or error code of an emulated VMX instruction, as specified
6924 * by Vol 2B, VMX Instruction Reference, "Conventions".
6926 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
6928 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
6929 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6930 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
6933 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
6935 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6936 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
6937 X86_EFLAGS_SF | X86_EFLAGS_OF))
6941 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
6942 u32 vm_instruction_error)
6944 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
6946 * failValid writes the error number to the current VMCS, which
6947 * can't be done there isn't a current VMCS.
6949 nested_vmx_failInvalid(vcpu);
6952 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
6953 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
6954 X86_EFLAGS_SF | X86_EFLAGS_OF))
6956 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
6958 * We don't need to force a shadow sync because
6959 * VM_INSTRUCTION_ERROR is not shadowed
6963 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
6965 /* TODO: not to reset guest simply here. */
6966 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6967 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
6970 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
6972 struct vcpu_vmx *vmx =
6973 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
6975 vmx->nested.preemption_timer_expired = true;
6976 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
6977 kvm_vcpu_kick(&vmx->vcpu);
6979 return HRTIMER_NORESTART;
6983 * Decode the memory-address operand of a vmx instruction, as recorded on an
6984 * exit caused by such an instruction (run by a guest hypervisor).
6985 * On success, returns 0. When the operand is invalid, returns 1 and throws
6988 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
6989 unsigned long exit_qualification,
6990 u32 vmx_instruction_info, bool wr, gva_t *ret)
6994 struct kvm_segment s;
6997 * According to Vol. 3B, "Information for VM Exits Due to Instruction
6998 * Execution", on an exit, vmx_instruction_info holds most of the
6999 * addressing components of the operand. Only the displacement part
7000 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
7001 * For how an actual address is calculated from all these components,
7002 * refer to Vol. 1, "Operand Addressing".
7004 int scaling = vmx_instruction_info & 3;
7005 int addr_size = (vmx_instruction_info >> 7) & 7;
7006 bool is_reg = vmx_instruction_info & (1u << 10);
7007 int seg_reg = (vmx_instruction_info >> 15) & 7;
7008 int index_reg = (vmx_instruction_info >> 18) & 0xf;
7009 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
7010 int base_reg = (vmx_instruction_info >> 23) & 0xf;
7011 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
7014 kvm_queue_exception(vcpu, UD_VECTOR);
7018 /* Addr = segment_base + offset */
7019 /* offset = base + [index * scale] + displacement */
7020 off = exit_qualification; /* holds the displacement */
7022 off = (gva_t)sign_extend64(off, 31);
7023 else if (addr_size == 0)
7024 off = (gva_t)sign_extend64(off, 15);
7026 off += kvm_register_read(vcpu, base_reg);
7028 off += kvm_register_read(vcpu, index_reg)<<scaling;
7029 vmx_get_segment(vcpu, &s, seg_reg);
7030 *ret = s.base + off;
7032 if (addr_size == 1) /* 32 bit */
7035 /* Checks for #GP/#SS exceptions. */
7037 if (is_long_mode(vcpu)) {
7038 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
7039 * non-canonical form. This is the only check on the memory
7040 * destination for long mode!
7042 exn = is_noncanonical_address(*ret);
7043 } else if (is_protmode(vcpu)) {
7044 /* Protected mode: apply checks for segment validity in the
7046 * - segment type check (#GP(0) may be thrown)
7047 * - usability check (#GP(0)/#SS(0))
7048 * - limit check (#GP(0)/#SS(0))
7051 /* #GP(0) if the destination operand is located in a
7052 * read-only data segment or any code segment.
7054 exn = ((s.type & 0xa) == 0 || (s.type & 8));
7056 /* #GP(0) if the source operand is located in an
7057 * execute-only code segment
7059 exn = ((s.type & 0xa) == 8);
7061 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
7064 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
7066 exn = (s.unusable != 0);
7069 * Protected mode: #GP(0)/#SS(0) if the memory operand is
7070 * outside the segment limit. All CPUs that support VMX ignore
7071 * limit checks for flat segments, i.e. segments with base==0,
7072 * limit==0xffffffff and of type expand-up data or code.
7074 if (!(s.base == 0 && s.limit == 0xffffffff &&
7075 ((s.type & 8) || !(s.type & 4))))
7076 exn = exn || (off + sizeof(u64) > s.limit);
7079 kvm_queue_exception_e(vcpu,
7080 seg_reg == VCPU_SREG_SS ?
7081 SS_VECTOR : GP_VECTOR,
7090 * This function performs the various checks including
7091 * - if it's 4KB aligned
7092 * - No bits beyond the physical address width are set
7093 * - Returns 0 on success or else 1
7094 * (Intel SDM Section 30.3)
7096 static int nested_vmx_check_vmptr(struct kvm_vcpu *vcpu, int exit_reason,
7101 struct x86_exception e;
7103 struct vcpu_vmx *vmx = to_vmx(vcpu);
7104 int maxphyaddr = cpuid_maxphyaddr(vcpu);
7106 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7107 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
7110 if (kvm_read_guest_virt(vcpu, gva, &vmptr, sizeof(vmptr), &e)) {
7111 kvm_inject_page_fault(vcpu, &e);
7115 switch (exit_reason) {
7116 case EXIT_REASON_VMON:
7119 * The first 4 bytes of VMXON region contain the supported
7120 * VMCS revision identifier
7122 * Note - IA32_VMX_BASIC[48] will never be 1
7123 * for the nested case;
7124 * which replaces physical address width with 32
7127 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7128 nested_vmx_failInvalid(vcpu);
7129 skip_emulated_instruction(vcpu);
7133 page = nested_get_page(vcpu, vmptr);
7135 nested_vmx_failInvalid(vcpu);
7136 skip_emulated_instruction(vcpu);
7139 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
7141 nested_release_page_clean(page);
7142 nested_vmx_failInvalid(vcpu);
7143 skip_emulated_instruction(vcpu);
7147 nested_release_page_clean(page);
7148 vmx->nested.vmxon_ptr = vmptr;
7150 case EXIT_REASON_VMCLEAR:
7151 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7152 nested_vmx_failValid(vcpu,
7153 VMXERR_VMCLEAR_INVALID_ADDRESS);
7154 skip_emulated_instruction(vcpu);
7158 if (vmptr == vmx->nested.vmxon_ptr) {
7159 nested_vmx_failValid(vcpu,
7160 VMXERR_VMCLEAR_VMXON_POINTER);
7161 skip_emulated_instruction(vcpu);
7165 case EXIT_REASON_VMPTRLD:
7166 if (!PAGE_ALIGNED(vmptr) || (vmptr >> maxphyaddr)) {
7167 nested_vmx_failValid(vcpu,
7168 VMXERR_VMPTRLD_INVALID_ADDRESS);
7169 skip_emulated_instruction(vcpu);
7173 if (vmptr == vmx->nested.vmxon_ptr) {
7174 nested_vmx_failValid(vcpu,
7175 VMXERR_VMCLEAR_VMXON_POINTER);
7176 skip_emulated_instruction(vcpu);
7181 return 1; /* shouldn't happen */
7190 * Emulate the VMXON instruction.
7191 * Currently, we just remember that VMX is active, and do not save or even
7192 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
7193 * do not currently need to store anything in that guest-allocated memory
7194 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
7195 * argument is different from the VMXON pointer (which the spec says they do).
7197 static int handle_vmon(struct kvm_vcpu *vcpu)
7199 struct kvm_segment cs;
7200 struct vcpu_vmx *vmx = to_vmx(vcpu);
7201 struct vmcs *shadow_vmcs;
7202 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
7203 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
7206 /* The Intel VMX Instruction Reference lists a bunch of bits that
7207 * are prerequisite to running VMXON, most notably cr4.VMXE must be
7208 * set to 1 (see vmx_set_cr4() for when we allow the guest to set this).
7209 * Otherwise, we should fail with #UD. We test these now:
7211 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE) ||
7212 !kvm_read_cr0_bits(vcpu, X86_CR0_PE) ||
7213 (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
7214 kvm_queue_exception(vcpu, UD_VECTOR);
7218 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
7219 if (is_long_mode(vcpu) && !cs.l) {
7220 kvm_queue_exception(vcpu, UD_VECTOR);
7224 if (vmx_get_cpl(vcpu)) {
7225 kvm_inject_gp(vcpu, 0);
7229 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMON, NULL))
7232 if (vmx->nested.vmxon) {
7233 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
7234 skip_emulated_instruction(vcpu);
7238 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
7239 != VMXON_NEEDED_FEATURES) {
7240 kvm_inject_gp(vcpu, 0);
7244 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
7248 vmx->nested.cached_vmcs12 = kmalloc(VMCS12_SIZE, GFP_KERNEL);
7249 if (!vmx->nested.cached_vmcs12)
7250 goto out_cached_vmcs12;
7252 if (enable_shadow_vmcs) {
7253 shadow_vmcs = alloc_vmcs();
7255 goto out_shadow_vmcs;
7256 /* mark vmcs as shadow */
7257 shadow_vmcs->revision_id |= (1u << 31);
7258 /* init shadow vmcs */
7259 vmcs_clear(shadow_vmcs);
7260 vmx->vmcs01.shadow_vmcs = shadow_vmcs;
7263 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
7264 HRTIMER_MODE_REL_PINNED);
7265 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
7267 vmx->nested.vpid02 = allocate_vpid();
7269 vmx->nested.vmxon = true;
7271 skip_emulated_instruction(vcpu);
7272 nested_vmx_succeed(vcpu);
7276 kfree(vmx->nested.cached_vmcs12);
7279 free_loaded_vmcs(&vmx->nested.vmcs02);
7286 * Intel's VMX Instruction Reference specifies a common set of prerequisites
7287 * for running VMX instructions (except VMXON, whose prerequisites are
7288 * slightly different). It also specifies what exception to inject otherwise.
7290 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
7292 struct kvm_segment cs;
7293 struct vcpu_vmx *vmx = to_vmx(vcpu);
7295 if (!vmx->nested.vmxon) {
7296 kvm_queue_exception(vcpu, UD_VECTOR);
7300 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
7301 if ((vmx_get_rflags(vcpu) & X86_EFLAGS_VM) ||
7302 (is_long_mode(vcpu) && !cs.l)) {
7303 kvm_queue_exception(vcpu, UD_VECTOR);
7307 if (vmx_get_cpl(vcpu)) {
7308 kvm_inject_gp(vcpu, 0);
7315 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
7317 if (vmx->nested.current_vmptr == -1ull)
7320 /* current_vmptr and current_vmcs12 are always set/reset together */
7321 if (WARN_ON(vmx->nested.current_vmcs12 == NULL))
7324 if (enable_shadow_vmcs) {
7325 /* copy to memory all shadowed fields in case
7326 they were modified */
7327 copy_shadow_to_vmcs12(vmx);
7328 vmx->nested.sync_shadow_vmcs = false;
7329 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
7330 SECONDARY_EXEC_SHADOW_VMCS);
7331 vmcs_write64(VMCS_LINK_POINTER, -1ull);
7333 vmx->nested.posted_intr_nv = -1;
7335 /* Flush VMCS12 to guest memory */
7336 memcpy(vmx->nested.current_vmcs12, vmx->nested.cached_vmcs12,
7339 kunmap(vmx->nested.current_vmcs12_page);
7340 nested_release_page(vmx->nested.current_vmcs12_page);
7341 vmx->nested.current_vmptr = -1ull;
7342 vmx->nested.current_vmcs12 = NULL;
7346 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
7347 * just stops using VMX.
7349 static void free_nested(struct vcpu_vmx *vmx)
7351 if (!vmx->nested.vmxon)
7354 hrtimer_cancel(&vmx->nested.preemption_timer);
7355 vmx->nested.vmxon = false;
7356 free_vpid(vmx->nested.vpid02);
7357 nested_release_vmcs12(vmx);
7358 if (enable_shadow_vmcs) {
7359 vmcs_clear(vmx->vmcs01.shadow_vmcs);
7360 free_vmcs(vmx->vmcs01.shadow_vmcs);
7361 vmx->vmcs01.shadow_vmcs = NULL;
7363 kfree(vmx->nested.cached_vmcs12);
7364 /* Unpin physical memory we referred to in the vmcs02 */
7365 if (vmx->nested.apic_access_page) {
7366 nested_release_page(vmx->nested.apic_access_page);
7367 vmx->nested.apic_access_page = NULL;
7369 if (vmx->nested.virtual_apic_page) {
7370 nested_release_page(vmx->nested.virtual_apic_page);
7371 vmx->nested.virtual_apic_page = NULL;
7373 if (vmx->nested.pi_desc_page) {
7374 kunmap(vmx->nested.pi_desc_page);
7375 nested_release_page(vmx->nested.pi_desc_page);
7376 vmx->nested.pi_desc_page = NULL;
7377 vmx->nested.pi_desc = NULL;
7380 free_loaded_vmcs(&vmx->nested.vmcs02);
7383 /* Emulate the VMXOFF instruction */
7384 static int handle_vmoff(struct kvm_vcpu *vcpu)
7386 if (!nested_vmx_check_permission(vcpu))
7388 free_nested(to_vmx(vcpu));
7389 skip_emulated_instruction(vcpu);
7390 nested_vmx_succeed(vcpu);
7394 /* Emulate the VMCLEAR instruction */
7395 static int handle_vmclear(struct kvm_vcpu *vcpu)
7397 struct vcpu_vmx *vmx = to_vmx(vcpu);
7401 if (!nested_vmx_check_permission(vcpu))
7404 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMCLEAR, &vmptr))
7407 if (vmptr == vmx->nested.current_vmptr)
7408 nested_release_vmcs12(vmx);
7410 kvm_vcpu_write_guest(vcpu,
7411 vmptr + offsetof(struct vmcs12, launch_state),
7412 &zero, sizeof(zero));
7414 skip_emulated_instruction(vcpu);
7415 nested_vmx_succeed(vcpu);
7419 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
7421 /* Emulate the VMLAUNCH instruction */
7422 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
7424 return nested_vmx_run(vcpu, true);
7427 /* Emulate the VMRESUME instruction */
7428 static int handle_vmresume(struct kvm_vcpu *vcpu)
7431 return nested_vmx_run(vcpu, false);
7434 enum vmcs_field_type {
7435 VMCS_FIELD_TYPE_U16 = 0,
7436 VMCS_FIELD_TYPE_U64 = 1,
7437 VMCS_FIELD_TYPE_U32 = 2,
7438 VMCS_FIELD_TYPE_NATURAL_WIDTH = 3
7441 static inline int vmcs_field_type(unsigned long field)
7443 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
7444 return VMCS_FIELD_TYPE_U32;
7445 return (field >> 13) & 0x3 ;
7448 static inline int vmcs_field_readonly(unsigned long field)
7450 return (((field >> 10) & 0x3) == 1);
7454 * Read a vmcs12 field. Since these can have varying lengths and we return
7455 * one type, we chose the biggest type (u64) and zero-extend the return value
7456 * to that size. Note that the caller, handle_vmread, might need to use only
7457 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
7458 * 64-bit fields are to be returned).
7460 static inline int vmcs12_read_any(struct kvm_vcpu *vcpu,
7461 unsigned long field, u64 *ret)
7463 short offset = vmcs_field_to_offset(field);
7469 p = ((char *)(get_vmcs12(vcpu))) + offset;
7471 switch (vmcs_field_type(field)) {
7472 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7473 *ret = *((natural_width *)p);
7475 case VMCS_FIELD_TYPE_U16:
7478 case VMCS_FIELD_TYPE_U32:
7481 case VMCS_FIELD_TYPE_U64:
7491 static inline int vmcs12_write_any(struct kvm_vcpu *vcpu,
7492 unsigned long field, u64 field_value){
7493 short offset = vmcs_field_to_offset(field);
7494 char *p = ((char *) get_vmcs12(vcpu)) + offset;
7498 switch (vmcs_field_type(field)) {
7499 case VMCS_FIELD_TYPE_U16:
7500 *(u16 *)p = field_value;
7502 case VMCS_FIELD_TYPE_U32:
7503 *(u32 *)p = field_value;
7505 case VMCS_FIELD_TYPE_U64:
7506 *(u64 *)p = field_value;
7508 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7509 *(natural_width *)p = field_value;
7518 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
7521 unsigned long field;
7523 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7524 const unsigned long *fields = shadow_read_write_fields;
7525 const int num_fields = max_shadow_read_write_fields;
7529 vmcs_load(shadow_vmcs);
7531 for (i = 0; i < num_fields; i++) {
7533 switch (vmcs_field_type(field)) {
7534 case VMCS_FIELD_TYPE_U16:
7535 field_value = vmcs_read16(field);
7537 case VMCS_FIELD_TYPE_U32:
7538 field_value = vmcs_read32(field);
7540 case VMCS_FIELD_TYPE_U64:
7541 field_value = vmcs_read64(field);
7543 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7544 field_value = vmcs_readl(field);
7550 vmcs12_write_any(&vmx->vcpu, field, field_value);
7553 vmcs_clear(shadow_vmcs);
7554 vmcs_load(vmx->loaded_vmcs->vmcs);
7559 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
7561 const unsigned long *fields[] = {
7562 shadow_read_write_fields,
7563 shadow_read_only_fields
7565 const int max_fields[] = {
7566 max_shadow_read_write_fields,
7567 max_shadow_read_only_fields
7570 unsigned long field;
7571 u64 field_value = 0;
7572 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
7574 vmcs_load(shadow_vmcs);
7576 for (q = 0; q < ARRAY_SIZE(fields); q++) {
7577 for (i = 0; i < max_fields[q]; i++) {
7578 field = fields[q][i];
7579 vmcs12_read_any(&vmx->vcpu, field, &field_value);
7581 switch (vmcs_field_type(field)) {
7582 case VMCS_FIELD_TYPE_U16:
7583 vmcs_write16(field, (u16)field_value);
7585 case VMCS_FIELD_TYPE_U32:
7586 vmcs_write32(field, (u32)field_value);
7588 case VMCS_FIELD_TYPE_U64:
7589 vmcs_write64(field, (u64)field_value);
7591 case VMCS_FIELD_TYPE_NATURAL_WIDTH:
7592 vmcs_writel(field, (long)field_value);
7601 vmcs_clear(shadow_vmcs);
7602 vmcs_load(vmx->loaded_vmcs->vmcs);
7606 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
7607 * used before) all generate the same failure when it is missing.
7609 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
7611 struct vcpu_vmx *vmx = to_vmx(vcpu);
7612 if (vmx->nested.current_vmptr == -1ull) {
7613 nested_vmx_failInvalid(vcpu);
7614 skip_emulated_instruction(vcpu);
7620 static int handle_vmread(struct kvm_vcpu *vcpu)
7622 unsigned long field;
7624 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7625 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7627 struct x86_exception e;
7629 if (!nested_vmx_check_permission(vcpu) ||
7630 !nested_vmx_check_vmcs12(vcpu))
7633 /* Decode instruction info and find the field to read */
7634 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7635 /* Read the field, zero-extended to a u64 field_value */
7636 if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
7637 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7638 skip_emulated_instruction(vcpu);
7642 * Now copy part of this value to register or memory, as requested.
7643 * Note that the number of bits actually copied is 32 or 64 depending
7644 * on the guest's mode (32 or 64 bit), not on the given field's length.
7646 if (vmx_instruction_info & (1u << 10)) {
7647 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
7650 if (get_vmx_mem_address(vcpu, exit_qualification,
7651 vmx_instruction_info, true, &gva))
7653 /* _system ok, as nested_vmx_check_permission verified cpl=0 */
7654 if (kvm_write_guest_virt_system(vcpu, gva, &field_value,
7655 (is_long_mode(vcpu) ? 8 : 4),
7657 kvm_inject_page_fault(vcpu, &e);
7662 nested_vmx_succeed(vcpu);
7663 skip_emulated_instruction(vcpu);
7668 static int handle_vmwrite(struct kvm_vcpu *vcpu)
7670 unsigned long field;
7672 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7673 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7674 /* The value to write might be 32 or 64 bits, depending on L1's long
7675 * mode, and eventually we need to write that into a field of several
7676 * possible lengths. The code below first zero-extends the value to 64
7677 * bit (field_value), and then copies only the appropriate number of
7678 * bits into the vmcs12 field.
7680 u64 field_value = 0;
7681 struct x86_exception e;
7683 if (!nested_vmx_check_permission(vcpu) ||
7684 !nested_vmx_check_vmcs12(vcpu))
7687 if (vmx_instruction_info & (1u << 10))
7688 field_value = kvm_register_readl(vcpu,
7689 (((vmx_instruction_info) >> 3) & 0xf));
7691 if (get_vmx_mem_address(vcpu, exit_qualification,
7692 vmx_instruction_info, false, &gva))
7694 if (kvm_read_guest_virt(vcpu, gva, &field_value,
7695 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
7696 kvm_inject_page_fault(vcpu, &e);
7702 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
7703 if (vmcs_field_readonly(field)) {
7704 nested_vmx_failValid(vcpu,
7705 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
7706 skip_emulated_instruction(vcpu);
7710 if (vmcs12_write_any(vcpu, field, field_value) < 0) {
7711 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
7712 skip_emulated_instruction(vcpu);
7716 nested_vmx_succeed(vcpu);
7717 skip_emulated_instruction(vcpu);
7721 /* Emulate the VMPTRLD instruction */
7722 static int handle_vmptrld(struct kvm_vcpu *vcpu)
7724 struct vcpu_vmx *vmx = to_vmx(vcpu);
7727 if (!nested_vmx_check_permission(vcpu))
7730 if (nested_vmx_check_vmptr(vcpu, EXIT_REASON_VMPTRLD, &vmptr))
7733 if (vmx->nested.current_vmptr != vmptr) {
7734 struct vmcs12 *new_vmcs12;
7736 page = nested_get_page(vcpu, vmptr);
7738 nested_vmx_failInvalid(vcpu);
7739 skip_emulated_instruction(vcpu);
7742 new_vmcs12 = kmap(page);
7743 if (new_vmcs12->revision_id != VMCS12_REVISION) {
7745 nested_release_page_clean(page);
7746 nested_vmx_failValid(vcpu,
7747 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
7748 skip_emulated_instruction(vcpu);
7752 nested_release_vmcs12(vmx);
7753 vmx->nested.current_vmptr = vmptr;
7754 vmx->nested.current_vmcs12 = new_vmcs12;
7755 vmx->nested.current_vmcs12_page = page;
7757 * Load VMCS12 from guest memory since it is not already
7760 memcpy(vmx->nested.cached_vmcs12,
7761 vmx->nested.current_vmcs12, VMCS12_SIZE);
7763 if (enable_shadow_vmcs) {
7764 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
7765 SECONDARY_EXEC_SHADOW_VMCS);
7766 vmcs_write64(VMCS_LINK_POINTER,
7767 __pa(vmx->vmcs01.shadow_vmcs));
7768 vmx->nested.sync_shadow_vmcs = true;
7772 nested_vmx_succeed(vcpu);
7773 skip_emulated_instruction(vcpu);
7777 /* Emulate the VMPTRST instruction */
7778 static int handle_vmptrst(struct kvm_vcpu *vcpu)
7780 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7781 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7783 struct x86_exception e;
7785 if (!nested_vmx_check_permission(vcpu))
7788 if (get_vmx_mem_address(vcpu, exit_qualification,
7789 vmx_instruction_info, true, &vmcs_gva))
7791 /* ok to use *_system, as nested_vmx_check_permission verified cpl=0 */
7792 if (kvm_write_guest_virt_system(vcpu, vmcs_gva,
7793 (void *)&to_vmx(vcpu)->nested.current_vmptr,
7795 kvm_inject_page_fault(vcpu, &e);
7798 nested_vmx_succeed(vcpu);
7799 skip_emulated_instruction(vcpu);
7803 /* Emulate the INVEPT instruction */
7804 static int handle_invept(struct kvm_vcpu *vcpu)
7806 struct vcpu_vmx *vmx = to_vmx(vcpu);
7807 u32 vmx_instruction_info, types;
7810 struct x86_exception e;
7815 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7816 SECONDARY_EXEC_ENABLE_EPT) ||
7817 !(vmx->nested.nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) {
7818 kvm_queue_exception(vcpu, UD_VECTOR);
7822 if (!nested_vmx_check_permission(vcpu))
7825 if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) {
7826 kvm_queue_exception(vcpu, UD_VECTOR);
7830 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7831 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7833 types = (vmx->nested.nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
7835 if (type >= 32 || !(types & (1 << type))) {
7836 nested_vmx_failValid(vcpu,
7837 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7838 skip_emulated_instruction(vcpu);
7842 /* According to the Intel VMX instruction reference, the memory
7843 * operand is read even if it isn't needed (e.g., for type==global)
7845 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7846 vmx_instruction_info, false, &gva))
7848 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
7849 kvm_inject_page_fault(vcpu, &e);
7854 case VMX_EPT_EXTENT_GLOBAL:
7856 * TODO: track mappings and invalidate
7857 * single context requests appropriately
7859 case VMX_EPT_EXTENT_CONTEXT:
7860 kvm_mmu_sync_roots(vcpu);
7861 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
7862 nested_vmx_succeed(vcpu);
7869 skip_emulated_instruction(vcpu);
7873 static int handle_invvpid(struct kvm_vcpu *vcpu)
7875 struct vcpu_vmx *vmx = to_vmx(vcpu);
7876 u32 vmx_instruction_info;
7877 unsigned long type, types;
7879 struct x86_exception e;
7882 if (!(vmx->nested.nested_vmx_secondary_ctls_high &
7883 SECONDARY_EXEC_ENABLE_VPID) ||
7884 !(vmx->nested.nested_vmx_vpid_caps & VMX_VPID_INVVPID_BIT)) {
7885 kvm_queue_exception(vcpu, UD_VECTOR);
7889 if (!nested_vmx_check_permission(vcpu))
7892 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
7893 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
7895 types = (vmx->nested.nested_vmx_vpid_caps &
7896 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
7898 if (type >= 32 || !(types & (1 << type))) {
7899 nested_vmx_failValid(vcpu,
7900 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7901 skip_emulated_instruction(vcpu);
7905 /* according to the intel vmx instruction reference, the memory
7906 * operand is read even if it isn't needed (e.g., for type==global)
7908 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
7909 vmx_instruction_info, false, &gva))
7911 if (kvm_read_guest_virt(vcpu, gva, &vpid, sizeof(u32), &e)) {
7912 kvm_inject_page_fault(vcpu, &e);
7917 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
7918 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
7919 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
7921 nested_vmx_failValid(vcpu,
7922 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
7923 skip_emulated_instruction(vcpu);
7927 case VMX_VPID_EXTENT_ALL_CONTEXT:
7931 skip_emulated_instruction(vcpu);
7935 __vmx_flush_tlb(vcpu, vmx->nested.vpid02);
7936 nested_vmx_succeed(vcpu);
7938 skip_emulated_instruction(vcpu);
7942 static int handle_pml_full(struct kvm_vcpu *vcpu)
7944 unsigned long exit_qualification;
7946 trace_kvm_pml_full(vcpu->vcpu_id);
7948 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7951 * PML buffer FULL happened while executing iret from NMI,
7952 * "blocked by NMI" bit has to be set before next VM entry.
7954 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7955 cpu_has_virtual_nmis() &&
7956 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7957 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
7958 GUEST_INTR_STATE_NMI);
7961 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
7962 * here.., and there's no userspace involvement needed for PML.
7967 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
7969 kvm_lapic_expired_hv_timer(vcpu);
7974 * The exit handlers return 1 if the exit was handled fully and guest execution
7975 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
7976 * to be done to userspace and return 0.
7978 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
7979 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
7980 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
7981 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
7982 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
7983 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
7984 [EXIT_REASON_CR_ACCESS] = handle_cr,
7985 [EXIT_REASON_DR_ACCESS] = handle_dr,
7986 [EXIT_REASON_CPUID] = handle_cpuid,
7987 [EXIT_REASON_MSR_READ] = handle_rdmsr,
7988 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
7989 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
7990 [EXIT_REASON_HLT] = handle_halt,
7991 [EXIT_REASON_INVD] = handle_invd,
7992 [EXIT_REASON_INVLPG] = handle_invlpg,
7993 [EXIT_REASON_RDPMC] = handle_rdpmc,
7994 [EXIT_REASON_VMCALL] = handle_vmcall,
7995 [EXIT_REASON_VMCLEAR] = handle_vmclear,
7996 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
7997 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
7998 [EXIT_REASON_VMPTRST] = handle_vmptrst,
7999 [EXIT_REASON_VMREAD] = handle_vmread,
8000 [EXIT_REASON_VMRESUME] = handle_vmresume,
8001 [EXIT_REASON_VMWRITE] = handle_vmwrite,
8002 [EXIT_REASON_VMOFF] = handle_vmoff,
8003 [EXIT_REASON_VMON] = handle_vmon,
8004 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
8005 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
8006 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
8007 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
8008 [EXIT_REASON_WBINVD] = handle_wbinvd,
8009 [EXIT_REASON_XSETBV] = handle_xsetbv,
8010 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
8011 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
8012 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
8013 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
8014 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
8015 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
8016 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
8017 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
8018 [EXIT_REASON_INVEPT] = handle_invept,
8019 [EXIT_REASON_INVVPID] = handle_invvpid,
8020 [EXIT_REASON_XSAVES] = handle_xsaves,
8021 [EXIT_REASON_XRSTORS] = handle_xrstors,
8022 [EXIT_REASON_PML_FULL] = handle_pml_full,
8023 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
8026 static const int kvm_vmx_max_exit_handlers =
8027 ARRAY_SIZE(kvm_vmx_exit_handlers);
8029 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
8030 struct vmcs12 *vmcs12)
8032 unsigned long exit_qualification;
8033 gpa_t bitmap, last_bitmap;
8038 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
8039 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
8041 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8043 port = exit_qualification >> 16;
8044 size = (exit_qualification & 7) + 1;
8046 last_bitmap = (gpa_t)-1;
8051 bitmap = vmcs12->io_bitmap_a;
8052 else if (port < 0x10000)
8053 bitmap = vmcs12->io_bitmap_b;
8056 bitmap += (port & 0x7fff) / 8;
8058 if (last_bitmap != bitmap)
8059 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
8061 if (b & (1 << (port & 7)))
8066 last_bitmap = bitmap;
8073 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
8074 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
8075 * disinterest in the current event (read or write a specific MSR) by using an
8076 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
8078 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
8079 struct vmcs12 *vmcs12, u32 exit_reason)
8081 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
8084 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
8088 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
8089 * for the four combinations of read/write and low/high MSR numbers.
8090 * First we need to figure out which of the four to use:
8092 bitmap = vmcs12->msr_bitmap;
8093 if (exit_reason == EXIT_REASON_MSR_WRITE)
8095 if (msr_index >= 0xc0000000) {
8096 msr_index -= 0xc0000000;
8100 /* Then read the msr_index'th bit from this bitmap: */
8101 if (msr_index < 1024*8) {
8103 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
8105 return 1 & (b >> (msr_index & 7));
8107 return true; /* let L1 handle the wrong parameter */
8111 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
8112 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
8113 * intercept (via guest_host_mask etc.) the current event.
8115 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
8116 struct vmcs12 *vmcs12)
8118 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8119 int cr = exit_qualification & 15;
8123 switch ((exit_qualification >> 4) & 3) {
8124 case 0: /* mov to cr */
8125 reg = (exit_qualification >> 8) & 15;
8126 val = kvm_register_readl(vcpu, reg);
8129 if (vmcs12->cr0_guest_host_mask &
8130 (val ^ vmcs12->cr0_read_shadow))
8134 if ((vmcs12->cr3_target_count >= 1 &&
8135 vmcs12->cr3_target_value0 == val) ||
8136 (vmcs12->cr3_target_count >= 2 &&
8137 vmcs12->cr3_target_value1 == val) ||
8138 (vmcs12->cr3_target_count >= 3 &&
8139 vmcs12->cr3_target_value2 == val) ||
8140 (vmcs12->cr3_target_count >= 4 &&
8141 vmcs12->cr3_target_value3 == val))
8143 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
8147 if (vmcs12->cr4_guest_host_mask &
8148 (vmcs12->cr4_read_shadow ^ val))
8152 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
8158 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
8159 (vmcs12->cr0_read_shadow & X86_CR0_TS))
8162 case 1: /* mov from cr */
8165 if (vmcs12->cpu_based_vm_exec_control &
8166 CPU_BASED_CR3_STORE_EXITING)
8170 if (vmcs12->cpu_based_vm_exec_control &
8171 CPU_BASED_CR8_STORE_EXITING)
8178 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
8179 * cr0. Other attempted changes are ignored, with no exit.
8181 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
8182 if (vmcs12->cr0_guest_host_mask & 0xe &
8183 (val ^ vmcs12->cr0_read_shadow))
8185 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
8186 !(vmcs12->cr0_read_shadow & 0x1) &&
8195 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
8196 * should handle it ourselves in L0 (and then continue L2). Only call this
8197 * when in is_guest_mode (L2).
8199 static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu)
8201 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8202 struct vcpu_vmx *vmx = to_vmx(vcpu);
8203 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8204 u32 exit_reason = vmx->exit_reason;
8206 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
8207 vmcs_readl(EXIT_QUALIFICATION),
8208 vmx->idt_vectoring_info,
8210 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8214 * The host physical addresses of some pages of guest memory
8215 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
8216 * Page). The CPU may write to these pages via their host
8217 * physical address while L2 is running, bypassing any
8218 * address-translation-based dirty tracking (e.g. EPT write
8221 * Mark them dirty on every exit from L2 to prevent them from
8222 * getting out of sync with dirty tracking.
8224 nested_mark_vmcs12_pages_dirty(vcpu);
8226 if (vmx->nested.nested_run_pending)
8229 if (unlikely(vmx->fail)) {
8230 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
8231 vmcs_read32(VM_INSTRUCTION_ERROR));
8235 switch (exit_reason) {
8236 case EXIT_REASON_EXCEPTION_NMI:
8237 if (is_nmi(intr_info))
8239 else if (is_page_fault(intr_info))
8241 else if (is_no_device(intr_info) &&
8242 !(vmcs12->guest_cr0 & X86_CR0_TS))
8244 else if (is_debug(intr_info) &&
8246 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
8248 else if (is_breakpoint(intr_info) &&
8249 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
8251 return vmcs12->exception_bitmap &
8252 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
8253 case EXIT_REASON_EXTERNAL_INTERRUPT:
8255 case EXIT_REASON_TRIPLE_FAULT:
8257 case EXIT_REASON_PENDING_INTERRUPT:
8258 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
8259 case EXIT_REASON_NMI_WINDOW:
8260 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
8261 case EXIT_REASON_TASK_SWITCH:
8263 case EXIT_REASON_CPUID:
8265 case EXIT_REASON_HLT:
8266 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
8267 case EXIT_REASON_INVD:
8269 case EXIT_REASON_INVLPG:
8270 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
8271 case EXIT_REASON_RDPMC:
8272 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
8273 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
8274 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
8275 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
8276 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
8277 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD:
8278 case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE:
8279 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
8280 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
8282 * VMX instructions trap unconditionally. This allows L1 to
8283 * emulate them for its L2 guest, i.e., allows 3-level nesting!
8286 case EXIT_REASON_CR_ACCESS:
8287 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
8288 case EXIT_REASON_DR_ACCESS:
8289 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
8290 case EXIT_REASON_IO_INSTRUCTION:
8291 return nested_vmx_exit_handled_io(vcpu, vmcs12);
8292 case EXIT_REASON_MSR_READ:
8293 case EXIT_REASON_MSR_WRITE:
8294 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
8295 case EXIT_REASON_INVALID_STATE:
8297 case EXIT_REASON_MWAIT_INSTRUCTION:
8298 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
8299 case EXIT_REASON_MONITOR_TRAP_FLAG:
8300 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
8301 case EXIT_REASON_MONITOR_INSTRUCTION:
8302 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
8303 case EXIT_REASON_PAUSE_INSTRUCTION:
8304 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
8305 nested_cpu_has2(vmcs12,
8306 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
8307 case EXIT_REASON_MCE_DURING_VMENTRY:
8309 case EXIT_REASON_TPR_BELOW_THRESHOLD:
8310 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
8311 case EXIT_REASON_APIC_ACCESS:
8312 return nested_cpu_has2(vmcs12,
8313 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
8314 case EXIT_REASON_APIC_WRITE:
8315 case EXIT_REASON_EOI_INDUCED:
8316 /* apic_write and eoi_induced should exit unconditionally. */
8318 case EXIT_REASON_EPT_VIOLATION:
8320 * L0 always deals with the EPT violation. If nested EPT is
8321 * used, and the nested mmu code discovers that the address is
8322 * missing in the guest EPT table (EPT12), the EPT violation
8323 * will be injected with nested_ept_inject_page_fault()
8326 case EXIT_REASON_EPT_MISCONFIG:
8328 * L2 never uses directly L1's EPT, but rather L0's own EPT
8329 * table (shadow on EPT) or a merged EPT table that L0 built
8330 * (EPT on EPT). So any problems with the structure of the
8331 * table is L0's fault.
8334 case EXIT_REASON_WBINVD:
8335 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
8336 case EXIT_REASON_XSETBV:
8338 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
8340 * This should never happen, since it is not possible to
8341 * set XSS to a non-zero value---neither in L1 nor in L2.
8342 * If if it were, XSS would have to be checked against
8343 * the XSS exit bitmap in vmcs12.
8345 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
8346 case EXIT_REASON_PREEMPTION_TIMER:
8348 case EXIT_REASON_PML_FULL:
8349 /* We don't expose PML support to L1. */
8356 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
8358 *info1 = vmcs_readl(EXIT_QUALIFICATION);
8359 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
8362 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
8365 __free_page(vmx->pml_pg);
8370 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
8372 struct vcpu_vmx *vmx = to_vmx(vcpu);
8376 pml_idx = vmcs_read16(GUEST_PML_INDEX);
8378 /* Do nothing if PML buffer is empty */
8379 if (pml_idx == (PML_ENTITY_NUM - 1))
8382 /* PML index always points to next available PML buffer entity */
8383 if (pml_idx >= PML_ENTITY_NUM)
8388 pml_buf = page_address(vmx->pml_pg);
8389 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
8392 gpa = pml_buf[pml_idx];
8393 WARN_ON(gpa & (PAGE_SIZE - 1));
8394 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
8397 /* reset PML index */
8398 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
8402 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
8403 * Called before reporting dirty_bitmap to userspace.
8405 static void kvm_flush_pml_buffers(struct kvm *kvm)
8408 struct kvm_vcpu *vcpu;
8410 * We only need to kick vcpu out of guest mode here, as PML buffer
8411 * is flushed at beginning of all VMEXITs, and it's obvious that only
8412 * vcpus running in guest are possible to have unflushed GPAs in PML
8415 kvm_for_each_vcpu(i, vcpu, kvm)
8416 kvm_vcpu_kick(vcpu);
8419 static void vmx_dump_sel(char *name, uint32_t sel)
8421 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
8422 name, vmcs_read16(sel),
8423 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
8424 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
8425 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
8428 static void vmx_dump_dtsel(char *name, uint32_t limit)
8430 pr_err("%s limit=0x%08x, base=0x%016lx\n",
8431 name, vmcs_read32(limit),
8432 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
8435 static void dump_vmcs(void)
8437 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
8438 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
8439 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
8440 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
8441 u32 secondary_exec_control = 0;
8442 unsigned long cr4 = vmcs_readl(GUEST_CR4);
8443 u64 efer = vmcs_read64(GUEST_IA32_EFER);
8446 if (cpu_has_secondary_exec_ctrls())
8447 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8449 pr_err("*** Guest State ***\n");
8450 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8451 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
8452 vmcs_readl(CR0_GUEST_HOST_MASK));
8453 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
8454 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
8455 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
8456 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
8457 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
8459 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
8460 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
8461 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
8462 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
8464 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
8465 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
8466 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
8467 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
8468 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8469 vmcs_readl(GUEST_SYSENTER_ESP),
8470 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
8471 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
8472 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
8473 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
8474 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
8475 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
8476 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
8477 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
8478 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
8479 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
8480 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
8481 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
8482 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
8483 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8484 efer, vmcs_read64(GUEST_IA32_PAT));
8485 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
8486 vmcs_read64(GUEST_IA32_DEBUGCTL),
8487 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
8488 if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
8489 pr_err("PerfGlobCtl = 0x%016llx\n",
8490 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
8491 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
8492 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
8493 pr_err("Interruptibility = %08x ActivityState = %08x\n",
8494 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
8495 vmcs_read32(GUEST_ACTIVITY_STATE));
8496 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
8497 pr_err("InterruptStatus = %04x\n",
8498 vmcs_read16(GUEST_INTR_STATUS));
8500 pr_err("*** Host State ***\n");
8501 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
8502 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
8503 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
8504 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
8505 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
8506 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
8507 vmcs_read16(HOST_TR_SELECTOR));
8508 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
8509 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
8510 vmcs_readl(HOST_TR_BASE));
8511 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
8512 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
8513 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
8514 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
8515 vmcs_readl(HOST_CR4));
8516 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
8517 vmcs_readl(HOST_IA32_SYSENTER_ESP),
8518 vmcs_read32(HOST_IA32_SYSENTER_CS),
8519 vmcs_readl(HOST_IA32_SYSENTER_EIP));
8520 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
8521 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
8522 vmcs_read64(HOST_IA32_EFER),
8523 vmcs_read64(HOST_IA32_PAT));
8524 if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
8525 pr_err("PerfGlobCtl = 0x%016llx\n",
8526 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
8528 pr_err("*** Control State ***\n");
8529 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
8530 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
8531 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
8532 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
8533 vmcs_read32(EXCEPTION_BITMAP),
8534 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
8535 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
8536 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
8537 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
8538 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
8539 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
8540 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
8541 vmcs_read32(VM_EXIT_INTR_INFO),
8542 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
8543 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
8544 pr_err(" reason=%08x qualification=%016lx\n",
8545 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
8546 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
8547 vmcs_read32(IDT_VECTORING_INFO_FIELD),
8548 vmcs_read32(IDT_VECTORING_ERROR_CODE));
8549 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
8550 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
8551 pr_err("TSC Multiplier = 0x%016llx\n",
8552 vmcs_read64(TSC_MULTIPLIER));
8553 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
8554 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
8555 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
8556 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
8557 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
8558 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
8559 n = vmcs_read32(CR3_TARGET_COUNT);
8560 for (i = 0; i + 1 < n; i += 4)
8561 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
8562 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
8563 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
8565 pr_err("CR3 target%u=%016lx\n",
8566 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
8567 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
8568 pr_err("PLE Gap=%08x Window=%08x\n",
8569 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
8570 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
8571 pr_err("Virtual processor ID = 0x%04x\n",
8572 vmcs_read16(VIRTUAL_PROCESSOR_ID));
8576 * The guest has exited. See if we can fix it or if we need userspace
8579 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
8581 struct vcpu_vmx *vmx = to_vmx(vcpu);
8582 u32 exit_reason = vmx->exit_reason;
8583 u32 vectoring_info = vmx->idt_vectoring_info;
8585 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
8588 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
8589 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
8590 * querying dirty_bitmap, we only need to kick all vcpus out of guest
8591 * mode as if vcpus is in root mode, the PML buffer must has been
8595 vmx_flush_pml_buffer(vcpu);
8597 /* If guest state is invalid, start emulating */
8598 if (vmx->emulation_required)
8599 return handle_invalid_guest_state(vcpu);
8601 if (is_guest_mode(vcpu) && nested_vmx_exit_handled(vcpu)) {
8602 nested_vmx_vmexit(vcpu, exit_reason,
8603 vmcs_read32(VM_EXIT_INTR_INFO),
8604 vmcs_readl(EXIT_QUALIFICATION));
8608 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
8610 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8611 vcpu->run->fail_entry.hardware_entry_failure_reason
8616 if (unlikely(vmx->fail)) {
8617 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
8618 vcpu->run->fail_entry.hardware_entry_failure_reason
8619 = vmcs_read32(VM_INSTRUCTION_ERROR);
8625 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
8626 * delivery event since it indicates guest is accessing MMIO.
8627 * The vm-exit can be triggered again after return to guest that
8628 * will cause infinite loop.
8630 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
8631 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
8632 exit_reason != EXIT_REASON_EPT_VIOLATION &&
8633 exit_reason != EXIT_REASON_PML_FULL &&
8634 exit_reason != EXIT_REASON_TASK_SWITCH)) {
8635 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
8636 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
8637 vcpu->run->internal.ndata = 2;
8638 vcpu->run->internal.data[0] = vectoring_info;
8639 vcpu->run->internal.data[1] = exit_reason;
8643 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked &&
8644 !(is_guest_mode(vcpu) && nested_cpu_has_virtual_nmis(
8645 get_vmcs12(vcpu))))) {
8646 if (vmx_interrupt_allowed(vcpu)) {
8647 vmx->soft_vnmi_blocked = 0;
8648 } else if (vmx->vnmi_blocked_time > 1000000000LL &&
8649 vcpu->arch.nmi_pending) {
8651 * This CPU don't support us in finding the end of an
8652 * NMI-blocked window if the guest runs with IRQs
8653 * disabled. So we pull the trigger after 1 s of
8654 * futile waiting, but inform the user about this.
8656 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
8657 "state on VCPU %d after 1 s timeout\n",
8658 __func__, vcpu->vcpu_id);
8659 vmx->soft_vnmi_blocked = 0;
8663 if (exit_reason < kvm_vmx_max_exit_handlers
8664 && kvm_vmx_exit_handlers[exit_reason])
8665 return kvm_vmx_exit_handlers[exit_reason](vcpu);
8667 WARN_ONCE(1, "vmx: unexpected exit reason 0x%x\n", exit_reason);
8668 kvm_queue_exception(vcpu, UD_VECTOR);
8674 * Software based L1D cache flush which is used when microcode providing
8675 * the cache control MSR is not loaded.
8677 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
8678 * flush it is required to read in 64 KiB because the replacement algorithm
8679 * is not exactly LRU. This could be sized at runtime via topology
8680 * information but as all relevant affected CPUs have 32KiB L1D cache size
8681 * there is no point in doing so.
8683 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
8685 int size = PAGE_SIZE << L1D_CACHE_ORDER;
8688 * This code is only executed when the the flush mode is 'cond' or
8691 if (static_branch_likely(&vmx_l1d_flush_cond)) {
8695 * Clear the per-vcpu flush bit, it gets set again
8696 * either from vcpu_run() or from one of the unsafe
8699 flush_l1d = vcpu->arch.l1tf_flush_l1d;
8700 vcpu->arch.l1tf_flush_l1d = false;
8703 * Clear the per-cpu flush bit, it gets set again from
8704 * the interrupt handlers.
8706 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
8707 kvm_clear_cpu_l1tf_flush_l1d();
8713 vcpu->stat.l1d_flush++;
8715 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
8716 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
8721 /* First ensure the pages are in the TLB */
8722 "xorl %%eax, %%eax\n"
8723 ".Lpopulate_tlb:\n\t"
8724 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
8725 "addl $4096, %%eax\n\t"
8726 "cmpl %%eax, %[size]\n\t"
8727 "jne .Lpopulate_tlb\n\t"
8728 "xorl %%eax, %%eax\n\t"
8730 /* Now fill the cache */
8731 "xorl %%eax, %%eax\n"
8733 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
8734 "addl $64, %%eax\n\t"
8735 "cmpl %%eax, %[size]\n\t"
8736 "jne .Lfill_cache\n\t"
8738 :: [flush_pages] "r" (vmx_l1d_flush_pages),
8740 : "eax", "ebx", "ecx", "edx");
8743 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
8745 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
8747 if (is_guest_mode(vcpu) &&
8748 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
8751 if (irr == -1 || tpr < irr) {
8752 vmcs_write32(TPR_THRESHOLD, 0);
8756 vmcs_write32(TPR_THRESHOLD, irr);
8759 static void vmx_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
8761 u32 sec_exec_control;
8763 /* Postpone execution until vmcs01 is the current VMCS. */
8764 if (is_guest_mode(vcpu)) {
8765 to_vmx(vcpu)->nested.change_vmcs01_virtual_x2apic_mode = true;
8769 if (!cpu_has_vmx_virtualize_x2apic_mode())
8772 if (!cpu_need_tpr_shadow(vcpu))
8775 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
8778 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8779 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8781 sec_exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
8782 sec_exec_control |= SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
8783 vmx_flush_tlb_ept_only(vcpu);
8785 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
8787 vmx_update_msr_bitmap(vcpu);
8790 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
8792 struct vcpu_vmx *vmx = to_vmx(vcpu);
8795 * Currently we do not handle the nested case where L2 has an
8796 * APIC access page of its own; that page is still pinned.
8797 * Hence, we skip the case where the VCPU is in guest mode _and_
8798 * L1 prepared an APIC access page for L2.
8800 * For the case where L1 and L2 share the same APIC access page
8801 * (flexpriority=Y but SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES clear
8802 * in the vmcs12), this function will only update either the vmcs01
8803 * or the vmcs02. If the former, the vmcs02 will be updated by
8804 * prepare_vmcs02. If the latter, the vmcs01 will be updated in
8805 * the next L2->L1 exit.
8807 if (!is_guest_mode(vcpu) ||
8808 !nested_cpu_has2(get_vmcs12(&vmx->vcpu),
8809 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
8810 vmcs_write64(APIC_ACCESS_ADDR, hpa);
8811 vmx_flush_tlb_ept_only(vcpu);
8815 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
8823 status = vmcs_read16(GUEST_INTR_STATUS);
8825 if (max_isr != old) {
8827 status |= max_isr << 8;
8828 vmcs_write16(GUEST_INTR_STATUS, status);
8832 static void vmx_set_rvi(int vector)
8840 status = vmcs_read16(GUEST_INTR_STATUS);
8841 old = (u8)status & 0xff;
8842 if ((u8)vector != old) {
8844 status |= (u8)vector;
8845 vmcs_write16(GUEST_INTR_STATUS, status);
8849 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
8851 if (!is_guest_mode(vcpu)) {
8852 vmx_set_rvi(max_irr);
8860 * In guest mode. If a vmexit is needed, vmx_check_nested_events
8863 if (nested_exit_on_intr(vcpu))
8867 * Else, fall back to pre-APICv interrupt injection since L2
8868 * is run without virtual interrupt delivery.
8870 if (!kvm_event_needs_reinjection(vcpu) &&
8871 vmx_interrupt_allowed(vcpu)) {
8872 kvm_queue_interrupt(vcpu, max_irr, false);
8873 vmx_inject_irq(vcpu);
8877 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
8879 if (!kvm_vcpu_apicv_active(vcpu))
8882 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
8883 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
8884 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
8885 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
8888 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
8892 if (!(vmx->exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
8893 || vmx->exit_reason == EXIT_REASON_EXCEPTION_NMI))
8896 vmx->exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8897 exit_intr_info = vmx->exit_intr_info;
8899 /* Handle machine checks before interrupts are enabled */
8900 if (is_machine_check(exit_intr_info))
8901 kvm_machine_check();
8903 /* We need to handle NMIs before interrupts are enabled */
8904 if (is_nmi(exit_intr_info)) {
8905 kvm_before_handle_nmi(&vmx->vcpu);
8907 kvm_after_handle_nmi(&vmx->vcpu);
8911 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
8913 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
8916 * If external interrupt exists, IF bit is set in rflags/eflags on the
8917 * interrupt stack frame, and interrupt will be enabled on a return
8918 * from interrupt handler.
8920 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
8921 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
8922 unsigned int vector;
8923 unsigned long entry;
8925 struct vcpu_vmx *vmx = to_vmx(vcpu);
8926 #ifdef CONFIG_X86_64
8930 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
8931 desc = (gate_desc *)vmx->host_idt_base + vector;
8932 entry = gate_offset(*desc);
8934 #ifdef CONFIG_X86_64
8935 "mov %%" _ASM_SP ", %[sp]\n\t"
8936 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
8941 __ASM_SIZE(push) " $%c[cs]\n\t"
8944 #ifdef CONFIG_X86_64
8949 THUNK_TARGET(entry),
8950 [ss]"i"(__KERNEL_DS),
8951 [cs]"i"(__KERNEL_CS)
8955 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
8957 static bool vmx_has_emulated_msr(int index)
8960 case MSR_IA32_SMBASE:
8962 * We cannot do SMM unless we can run the guest in big
8965 return enable_unrestricted_guest || emulate_invalid_guest_state;
8966 case MSR_AMD64_VIRT_SPEC_CTRL:
8967 /* This is AMD only. */
8974 static bool vmx_mpx_supported(void)
8976 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
8977 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
8980 static bool vmx_xsaves_supported(void)
8982 return vmcs_config.cpu_based_2nd_exec_ctrl &
8983 SECONDARY_EXEC_XSAVES;
8986 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
8991 bool idtv_info_valid;
8993 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
8995 if (cpu_has_virtual_nmis()) {
8996 if (vmx->nmi_known_unmasked)
8999 * Can't use vmx->exit_intr_info since we're not sure what
9000 * the exit reason is.
9002 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9003 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
9004 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
9006 * SDM 3: 27.7.1.2 (September 2008)
9007 * Re-set bit "block by NMI" before VM entry if vmexit caused by
9008 * a guest IRET fault.
9009 * SDM 3: 23.2.2 (September 2008)
9010 * Bit 12 is undefined in any of the following cases:
9011 * If the VM exit sets the valid bit in the IDT-vectoring
9012 * information field.
9013 * If the VM exit is due to a double fault.
9015 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
9016 vector != DF_VECTOR && !idtv_info_valid)
9017 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9018 GUEST_INTR_STATE_NMI);
9020 vmx->nmi_known_unmasked =
9021 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
9022 & GUEST_INTR_STATE_NMI);
9023 } else if (unlikely(vmx->soft_vnmi_blocked))
9024 vmx->vnmi_blocked_time +=
9025 ktime_to_ns(ktime_sub(ktime_get(), vmx->entry_time));
9028 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
9029 u32 idt_vectoring_info,
9030 int instr_len_field,
9031 int error_code_field)
9035 bool idtv_info_valid;
9037 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
9039 vcpu->arch.nmi_injected = false;
9040 kvm_clear_exception_queue(vcpu);
9041 kvm_clear_interrupt_queue(vcpu);
9043 if (!idtv_info_valid)
9046 kvm_make_request(KVM_REQ_EVENT, vcpu);
9048 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
9049 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
9052 case INTR_TYPE_NMI_INTR:
9053 vcpu->arch.nmi_injected = true;
9055 * SDM 3: 27.7.1.2 (September 2008)
9056 * Clear bit "block by NMI" before VM entry if a NMI
9059 vmx_set_nmi_mask(vcpu, false);
9061 case INTR_TYPE_SOFT_EXCEPTION:
9062 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9064 case INTR_TYPE_HARD_EXCEPTION:
9065 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
9066 u32 err = vmcs_read32(error_code_field);
9067 kvm_requeue_exception_e(vcpu, vector, err);
9069 kvm_requeue_exception(vcpu, vector);
9071 case INTR_TYPE_SOFT_INTR:
9072 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
9074 case INTR_TYPE_EXT_INTR:
9075 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
9082 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
9084 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
9085 VM_EXIT_INSTRUCTION_LEN,
9086 IDT_VECTORING_ERROR_CODE);
9089 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
9091 __vmx_complete_interrupts(vcpu,
9092 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
9093 VM_ENTRY_INSTRUCTION_LEN,
9094 VM_ENTRY_EXCEPTION_ERROR_CODE);
9096 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
9099 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
9102 struct perf_guest_switch_msr *msrs;
9104 msrs = perf_guest_get_msrs(&nr_msrs);
9109 for (i = 0; i < nr_msrs; i++)
9110 if (msrs[i].host == msrs[i].guest)
9111 clear_atomic_switch_msr(vmx, msrs[i].msr);
9113 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
9114 msrs[i].host, false);
9117 void vmx_arm_hv_timer(struct kvm_vcpu *vcpu)
9119 struct vcpu_vmx *vmx = to_vmx(vcpu);
9123 if (vmx->hv_deadline_tsc == -1)
9127 if (vmx->hv_deadline_tsc > tscl)
9128 /* sure to be 32 bit only because checked on set_hv_timer */
9129 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
9130 cpu_preemption_timer_multi);
9134 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, delta_tsc);
9137 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
9139 struct vcpu_vmx *vmx = to_vmx(vcpu);
9140 unsigned long debugctlmsr, cr4;
9142 /* Record the guest's net vcpu time for enforced NMI injections. */
9143 if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked))
9144 vmx->entry_time = ktime_get();
9146 /* Don't enter VMX if guest state is invalid, let the exit handler
9147 start emulation until we arrive back to a valid state */
9148 if (vmx->emulation_required)
9151 if (vmx->ple_window_dirty) {
9152 vmx->ple_window_dirty = false;
9153 vmcs_write32(PLE_WINDOW, vmx->ple_window);
9156 if (vmx->nested.sync_shadow_vmcs) {
9157 copy_vmcs12_to_shadow(vmx);
9158 vmx->nested.sync_shadow_vmcs = false;
9161 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
9162 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
9163 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
9164 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
9166 cr4 = cr4_read_shadow();
9167 if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) {
9168 vmcs_writel(HOST_CR4, cr4);
9169 vmx->host_state.vmcs_host_cr4 = cr4;
9172 /* When single-stepping over STI and MOV SS, we must clear the
9173 * corresponding interruptibility bits in the guest state. Otherwise
9174 * vmentry fails as it then expects bit 14 (BS) in pending debug
9175 * exceptions being set, but that's not correct for the guest debugging
9177 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
9178 vmx_set_interrupt_shadow(vcpu, 0);
9180 if (vmx->guest_pkru_valid)
9181 __write_pkru(vmx->guest_pkru);
9183 atomic_switch_perf_msrs(vmx);
9184 debugctlmsr = get_debugctlmsr();
9186 vmx_arm_hv_timer(vcpu);
9189 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
9190 * it's non-zero. Since vmentry is serialising on affected CPUs, there
9191 * is no need to worry about the conditional branch over the wrmsr
9192 * being speculatively taken.
9194 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
9196 vmx->__launched = vmx->loaded_vmcs->launched;
9198 /* L1D Flush includes CPU buffer clear to mitigate MDS */
9199 if (static_branch_unlikely(&vmx_l1d_should_flush))
9200 vmx_l1d_flush(vcpu);
9201 else if (static_branch_unlikely(&mds_user_clear))
9202 mds_clear_cpu_buffers();
9205 /* Store host registers */
9206 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
9207 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
9208 "push %%" _ASM_CX " \n\t"
9209 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9211 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
9212 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
9214 /* Reload cr2 if changed */
9215 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
9216 "mov %%cr2, %%" _ASM_DX " \n\t"
9217 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
9219 "mov %%" _ASM_AX", %%cr2 \n\t"
9221 /* Check if vmlaunch of vmresume is needed */
9222 "cmpl $0, %c[launched](%0) \n\t"
9223 /* Load guest registers. Don't clobber flags. */
9224 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
9225 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
9226 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
9227 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
9228 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
9229 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
9230 #ifdef CONFIG_X86_64
9231 "mov %c[r8](%0), %%r8 \n\t"
9232 "mov %c[r9](%0), %%r9 \n\t"
9233 "mov %c[r10](%0), %%r10 \n\t"
9234 "mov %c[r11](%0), %%r11 \n\t"
9235 "mov %c[r12](%0), %%r12 \n\t"
9236 "mov %c[r13](%0), %%r13 \n\t"
9237 "mov %c[r14](%0), %%r14 \n\t"
9238 "mov %c[r15](%0), %%r15 \n\t"
9240 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
9242 /* Enter guest mode */
9244 __ex(ASM_VMX_VMLAUNCH) "\n\t"
9246 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
9248 /* Save guest registers, load host registers, keep flags */
9249 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
9251 "setbe %c[fail](%0)\n\t"
9252 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
9253 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
9254 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
9255 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
9256 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
9257 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
9258 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
9259 #ifdef CONFIG_X86_64
9260 "mov %%r8, %c[r8](%0) \n\t"
9261 "mov %%r9, %c[r9](%0) \n\t"
9262 "mov %%r10, %c[r10](%0) \n\t"
9263 "mov %%r11, %c[r11](%0) \n\t"
9264 "mov %%r12, %c[r12](%0) \n\t"
9265 "mov %%r13, %c[r13](%0) \n\t"
9266 "mov %%r14, %c[r14](%0) \n\t"
9267 "mov %%r15, %c[r15](%0) \n\t"
9268 "xor %%r8d, %%r8d \n\t"
9269 "xor %%r9d, %%r9d \n\t"
9270 "xor %%r10d, %%r10d \n\t"
9271 "xor %%r11d, %%r11d \n\t"
9272 "xor %%r12d, %%r12d \n\t"
9273 "xor %%r13d, %%r13d \n\t"
9274 "xor %%r14d, %%r14d \n\t"
9275 "xor %%r15d, %%r15d \n\t"
9277 "mov %%cr2, %%" _ASM_AX " \n\t"
9278 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
9280 "xor %%eax, %%eax \n\t"
9281 "xor %%ebx, %%ebx \n\t"
9282 "xor %%esi, %%esi \n\t"
9283 "xor %%edi, %%edi \n\t"
9284 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
9285 ".pushsection .rodata \n\t"
9286 ".global vmx_return \n\t"
9287 "vmx_return: " _ASM_PTR " 2b \n\t"
9289 : : "c"(vmx), "d"((unsigned long)HOST_RSP),
9290 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
9291 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
9292 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
9293 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
9294 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
9295 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
9296 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
9297 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
9298 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
9299 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
9300 #ifdef CONFIG_X86_64
9301 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
9302 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
9303 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
9304 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
9305 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
9306 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
9307 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
9308 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
9310 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
9311 [wordsize]"i"(sizeof(ulong))
9313 #ifdef CONFIG_X86_64
9314 , "rax", "rbx", "rdi", "rsi"
9315 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
9317 , "eax", "ebx", "edi", "esi"
9322 * We do not use IBRS in the kernel. If this vCPU has used the
9323 * SPEC_CTRL MSR it may have left it on; save the value and
9324 * turn it off. This is much more efficient than blindly adding
9325 * it to the atomic save/restore list. Especially as the former
9326 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
9328 * For non-nested case:
9329 * If the L01 MSR bitmap does not intercept the MSR, then we need to
9333 * If the L02 MSR bitmap does not intercept the MSR, then we need to
9336 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
9337 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
9339 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
9341 /* Eliminate branch target predictions from guest mode */
9344 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
9346 update_debugctlmsr(debugctlmsr);
9348 #ifndef CONFIG_X86_64
9350 * The sysexit path does not restore ds/es, so we must set them to
9351 * a reasonable value ourselves.
9353 * We can't defer this to vmx_load_host_state() since that function
9354 * may be executed in interrupt context, which saves and restore segments
9355 * around it, nullifying its effect.
9357 loadsegment(ds, __USER_DS);
9358 loadsegment(es, __USER_DS);
9361 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
9362 | (1 << VCPU_EXREG_RFLAGS)
9363 | (1 << VCPU_EXREG_PDPTR)
9364 | (1 << VCPU_EXREG_SEGMENTS)
9365 | (1 << VCPU_EXREG_CR3));
9366 vcpu->arch.regs_dirty = 0;
9368 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
9370 vmx->loaded_vmcs->launched = 1;
9372 vmx->exit_reason = vmcs_read32(VM_EXIT_REASON);
9375 * eager fpu is enabled if PKEY is supported and CR4 is switched
9376 * back on host, so it is safe to read guest PKRU from current
9379 if (boot_cpu_has(X86_FEATURE_OSPKE)) {
9380 vmx->guest_pkru = __read_pkru();
9381 if (vmx->guest_pkru != vmx->host_pkru) {
9382 vmx->guest_pkru_valid = true;
9383 __write_pkru(vmx->host_pkru);
9385 vmx->guest_pkru_valid = false;
9389 * the KVM_REQ_EVENT optimization bit is only on for one entry, and if
9390 * we did not inject a still-pending event to L1 now because of
9391 * nested_run_pending, we need to re-enable this bit.
9393 if (vmx->nested.nested_run_pending)
9394 kvm_make_request(KVM_REQ_EVENT, vcpu);
9396 vmx->nested.nested_run_pending = 0;
9398 vmx_complete_atomic_exit(vmx);
9399 vmx_recover_nmi_blocking(vmx);
9400 vmx_complete_interrupts(vmx);
9402 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
9404 static void vmx_load_vmcs01(struct kvm_vcpu *vcpu)
9406 struct vcpu_vmx *vmx = to_vmx(vcpu);
9409 if (vmx->loaded_vmcs == &vmx->vmcs01)
9413 vmx->loaded_vmcs = &vmx->vmcs01;
9415 vmx_vcpu_load(vcpu, cpu);
9421 * Ensure that the current vmcs of the logical processor is the
9422 * vmcs01 of the vcpu before calling free_nested().
9424 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
9426 struct vcpu_vmx *vmx = to_vmx(vcpu);
9429 r = vcpu_load(vcpu);
9431 vmx_load_vmcs01(vcpu);
9436 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
9438 struct vcpu_vmx *vmx = to_vmx(vcpu);
9441 vmx_destroy_pml_buffer(vmx);
9442 free_vpid(vmx->vpid);
9443 leave_guest_mode(vcpu);
9444 vmx_free_vcpu_nested(vcpu);
9445 free_loaded_vmcs(vmx->loaded_vmcs);
9446 kfree(vmx->guest_msrs);
9447 kvm_vcpu_uninit(vcpu);
9448 kmem_cache_free(kvm_vcpu_cache, vmx);
9451 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
9454 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
9455 unsigned long *msr_bitmap;
9459 return ERR_PTR(-ENOMEM);
9461 vmx->vpid = allocate_vpid();
9463 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
9470 * If PML is turned on, failure on enabling PML just results in failure
9471 * of creating the vcpu, therefore we can simplify PML logic (by
9472 * avoiding dealing with cases, such as enabling PML partially on vcpus
9473 * for the guest, etc.
9476 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
9481 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
9482 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
9485 if (!vmx->guest_msrs)
9489 kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id())));
9490 err = alloc_loaded_vmcs(&vmx->vmcs01);
9496 msr_bitmap = vmx->vmcs01.msr_bitmap;
9497 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
9498 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
9499 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
9500 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
9501 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
9502 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
9503 vmx->msr_bitmap_mode = 0;
9505 vmx->loaded_vmcs = &vmx->vmcs01;
9507 vmx_vcpu_load(&vmx->vcpu, cpu);
9508 vmx->vcpu.cpu = cpu;
9509 err = vmx_vcpu_setup(vmx);
9510 vmx_vcpu_put(&vmx->vcpu);
9514 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
9515 err = alloc_apic_access_page(kvm);
9521 if (!kvm->arch.ept_identity_map_addr)
9522 kvm->arch.ept_identity_map_addr =
9523 VMX_EPT_IDENTITY_PAGETABLE_ADDR;
9524 err = init_rmode_identity_map(kvm);
9530 nested_vmx_setup_ctls_msrs(vmx);
9532 vmx->nested.posted_intr_nv = -1;
9533 vmx->nested.current_vmptr = -1ull;
9534 vmx->nested.current_vmcs12 = NULL;
9536 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
9539 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
9540 * or POSTED_INTR_WAKEUP_VECTOR.
9542 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
9543 vmx->pi_desc.sn = 1;
9548 free_loaded_vmcs(vmx->loaded_vmcs);
9550 kfree(vmx->guest_msrs);
9552 vmx_destroy_pml_buffer(vmx);
9554 kvm_vcpu_uninit(&vmx->vcpu);
9556 free_vpid(vmx->vpid);
9557 kmem_cache_free(kvm_vcpu_cache, vmx);
9558 return ERR_PTR(err);
9561 #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"
9562 #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"
9564 static int vmx_vm_init(struct kvm *kvm)
9566 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
9567 switch (l1tf_mitigation) {
9568 case L1TF_MITIGATION_OFF:
9569 case L1TF_MITIGATION_FLUSH_NOWARN:
9570 /* 'I explicitly don't care' is set */
9572 case L1TF_MITIGATION_FLUSH:
9573 case L1TF_MITIGATION_FLUSH_NOSMT:
9574 case L1TF_MITIGATION_FULL:
9576 * Warn upon starting the first VM in a potentially
9577 * insecure environment.
9579 if (cpu_smt_control == CPU_SMT_ENABLED)
9580 pr_warn_once(L1TF_MSG_SMT);
9581 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
9582 pr_warn_once(L1TF_MSG_L1D);
9584 case L1TF_MITIGATION_FULL_FORCE:
9585 /* Flush is enforced */
9592 static void __init vmx_check_processor_compat(void *rtn)
9594 struct vmcs_config vmcs_conf;
9597 if (setup_vmcs_config(&vmcs_conf) < 0)
9599 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
9600 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
9601 smp_processor_id());
9606 static int get_ept_level(void)
9608 return VMX_EPT_DEFAULT_GAW + 1;
9611 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
9616 /* For VT-d and EPT combination
9617 * 1. MMIO: always map as UC
9619 * a. VT-d without snooping control feature: can't guarantee the
9620 * result, try to trust guest.
9621 * b. VT-d with snooping control feature: snooping control feature of
9622 * VT-d engine can guarantee the cache correctness. Just set it
9623 * to WB to keep consistent with host. So the same as item 3.
9624 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
9625 * consistent with host MTRR
9628 cache = MTRR_TYPE_UNCACHABLE;
9632 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
9633 ipat = VMX_EPT_IPAT_BIT;
9634 cache = MTRR_TYPE_WRBACK;
9638 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
9639 ipat = VMX_EPT_IPAT_BIT;
9640 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
9641 cache = MTRR_TYPE_WRBACK;
9643 cache = MTRR_TYPE_UNCACHABLE;
9647 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
9650 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
9653 static int vmx_get_lpage_level(void)
9655 if (enable_ept && !cpu_has_vmx_ept_1g_page())
9656 return PT_DIRECTORY_LEVEL;
9658 /* For shadow and EPT supported 1GB page */
9659 return PT_PDPE_LEVEL;
9662 static void vmcs_set_secondary_exec_control(u32 new_ctl)
9665 * These bits in the secondary execution controls field
9666 * are dynamic, the others are mostly based on the hypervisor
9667 * architecture and the guest's CPUID. Do not touch the
9671 SECONDARY_EXEC_SHADOW_VMCS |
9672 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
9673 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
9675 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9677 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
9678 (new_ctl & ~mask) | (cur_ctl & mask));
9681 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
9683 struct kvm_cpuid_entry2 *best;
9684 struct vcpu_vmx *vmx = to_vmx(vcpu);
9685 u32 secondary_exec_ctl = vmx_secondary_exec_control(vmx);
9687 if (vmx_rdtscp_supported()) {
9688 bool rdtscp_enabled = guest_cpuid_has_rdtscp(vcpu);
9689 if (!rdtscp_enabled)
9690 secondary_exec_ctl &= ~SECONDARY_EXEC_RDTSCP;
9694 vmx->nested.nested_vmx_secondary_ctls_high |=
9695 SECONDARY_EXEC_RDTSCP;
9697 vmx->nested.nested_vmx_secondary_ctls_high &=
9698 ~SECONDARY_EXEC_RDTSCP;
9702 /* Exposing INVPCID only when PCID is exposed */
9703 best = kvm_find_cpuid_entry(vcpu, 0x7, 0);
9704 if (vmx_invpcid_supported() &&
9705 (!best || !(best->ebx & bit(X86_FEATURE_INVPCID)) ||
9706 !guest_cpuid_has_pcid(vcpu))) {
9707 secondary_exec_ctl &= ~SECONDARY_EXEC_ENABLE_INVPCID;
9710 best->ebx &= ~bit(X86_FEATURE_INVPCID);
9713 if (cpu_has_secondary_exec_ctrls())
9714 vmcs_set_secondary_exec_control(secondary_exec_ctl);
9716 if (nested_vmx_allowed(vcpu))
9717 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
9718 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9720 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
9721 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
9724 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
9726 if (func == 1 && nested)
9727 entry->ecx |= bit(X86_FEATURE_VMX);
9730 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
9731 struct x86_exception *fault)
9733 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9736 if (fault->error_code & PFERR_RSVD_MASK)
9737 exit_reason = EXIT_REASON_EPT_MISCONFIG;
9739 exit_reason = EXIT_REASON_EPT_VIOLATION;
9740 nested_vmx_vmexit(vcpu, exit_reason, 0, vcpu->arch.exit_qualification);
9741 vmcs12->guest_physical_address = fault->address;
9744 /* Callbacks for nested_ept_init_mmu_context: */
9746 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
9748 /* return the page table to be shadowed - in our case, EPT12 */
9749 return get_vmcs12(vcpu)->ept_pointer;
9752 static void nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
9754 WARN_ON(mmu_is_nested(vcpu));
9755 kvm_init_shadow_ept_mmu(vcpu,
9756 to_vmx(vcpu)->nested.nested_vmx_ept_caps &
9757 VMX_EPT_EXECUTE_ONLY_BIT);
9758 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
9759 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
9760 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
9762 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
9765 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
9767 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
9770 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
9773 bool inequality, bit;
9775 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
9777 (error_code & vmcs12->page_fault_error_code_mask) !=
9778 vmcs12->page_fault_error_code_match;
9779 return inequality ^ bit;
9782 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
9783 struct x86_exception *fault)
9785 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9787 WARN_ON(!is_guest_mode(vcpu));
9789 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code))
9790 nested_vmx_vmexit(vcpu, to_vmx(vcpu)->exit_reason,
9791 vmcs_read32(VM_EXIT_INTR_INFO),
9792 vmcs_readl(EXIT_QUALIFICATION));
9794 kvm_inject_page_fault(vcpu, fault);
9797 static bool nested_get_vmcs12_pages(struct kvm_vcpu *vcpu,
9798 struct vmcs12 *vmcs12)
9800 struct vcpu_vmx *vmx = to_vmx(vcpu);
9801 int maxphyaddr = cpuid_maxphyaddr(vcpu);
9803 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
9804 if (!PAGE_ALIGNED(vmcs12->apic_access_addr) ||
9805 vmcs12->apic_access_addr >> maxphyaddr)
9809 * Translate L1 physical address to host physical
9810 * address for vmcs02. Keep the page pinned, so this
9811 * physical address remains valid. We keep a reference
9812 * to it so we can release it later.
9814 if (vmx->nested.apic_access_page) /* shouldn't happen */
9815 nested_release_page(vmx->nested.apic_access_page);
9816 vmx->nested.apic_access_page =
9817 nested_get_page(vcpu, vmcs12->apic_access_addr);
9820 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
9821 if (!PAGE_ALIGNED(vmcs12->virtual_apic_page_addr) ||
9822 vmcs12->virtual_apic_page_addr >> maxphyaddr)
9825 if (vmx->nested.virtual_apic_page) /* shouldn't happen */
9826 nested_release_page(vmx->nested.virtual_apic_page);
9827 vmx->nested.virtual_apic_page =
9828 nested_get_page(vcpu, vmcs12->virtual_apic_page_addr);
9831 * Failing the vm entry is _not_ what the processor does
9832 * but it's basically the only possibility we have.
9833 * We could still enter the guest if CR8 load exits are
9834 * enabled, CR8 store exits are enabled, and virtualize APIC
9835 * access is disabled; in this case the processor would never
9836 * use the TPR shadow and we could simply clear the bit from
9837 * the execution control. But such a configuration is useless,
9838 * so let's keep the code simple.
9840 if (!vmx->nested.virtual_apic_page)
9844 if (nested_cpu_has_posted_intr(vmcs12)) {
9845 if (!IS_ALIGNED(vmcs12->posted_intr_desc_addr, 64) ||
9846 vmcs12->posted_intr_desc_addr >> maxphyaddr)
9849 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
9850 kunmap(vmx->nested.pi_desc_page);
9851 nested_release_page(vmx->nested.pi_desc_page);
9853 vmx->nested.pi_desc_page =
9854 nested_get_page(vcpu, vmcs12->posted_intr_desc_addr);
9855 if (!vmx->nested.pi_desc_page)
9858 vmx->nested.pi_desc =
9859 (struct pi_desc *)kmap(vmx->nested.pi_desc_page);
9860 if (!vmx->nested.pi_desc) {
9861 nested_release_page_clean(vmx->nested.pi_desc_page);
9864 vmx->nested.pi_desc =
9865 (struct pi_desc *)((void *)vmx->nested.pi_desc +
9866 (unsigned long)(vmcs12->posted_intr_desc_addr &
9873 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
9875 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
9876 struct vcpu_vmx *vmx = to_vmx(vcpu);
9878 if (vcpu->arch.virtual_tsc_khz == 0)
9881 /* Make sure short timeouts reliably trigger an immediate vmexit.
9882 * hrtimer_start does not guarantee this. */
9883 if (preemption_timeout <= 1) {
9884 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
9888 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
9889 preemption_timeout *= 1000000;
9890 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
9891 hrtimer_start(&vmx->nested.preemption_timer,
9892 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
9895 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
9896 struct vmcs12 *vmcs12)
9901 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9904 if (vmcs12_read_any(vcpu, MSR_BITMAP, &addr)) {
9908 maxphyaddr = cpuid_maxphyaddr(vcpu);
9910 if (!PAGE_ALIGNED(vmcs12->msr_bitmap) ||
9911 ((addr + PAGE_SIZE) >> maxphyaddr))
9918 * Merge L0's and L1's MSR bitmap, return false to indicate that
9919 * we do not use the hardware.
9921 static inline bool nested_vmx_merge_msr_bitmap(struct kvm_vcpu *vcpu,
9922 struct vmcs12 *vmcs12)
9926 unsigned long *msr_bitmap_l1;
9927 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
9929 * pred_cmd & spec_ctrl are trying to verify two things:
9931 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
9932 * ensures that we do not accidentally generate an L02 MSR bitmap
9933 * from the L12 MSR bitmap that is too permissive.
9934 * 2. That L1 or L2s have actually used the MSR. This avoids
9935 * unnecessarily merging of the bitmap if the MSR is unused. This
9936 * works properly because we only update the L01 MSR bitmap lazily.
9937 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
9938 * updated to reflect this when L1 (or its L2s) actually write to
9941 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
9942 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
9944 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
9945 !pred_cmd && !spec_ctrl)
9948 page = nested_get_page(vcpu, vmcs12->msr_bitmap);
9951 msr_bitmap_l1 = (unsigned long *)kmap(page);
9953 memset(msr_bitmap_l0, 0xff, PAGE_SIZE);
9955 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
9956 if (nested_cpu_has_apic_reg_virt(vmcs12))
9957 for (msr = 0x800; msr <= 0x8ff; msr++)
9958 nested_vmx_disable_intercept_for_msr(
9959 msr_bitmap_l1, msr_bitmap_l0,
9962 nested_vmx_disable_intercept_for_msr(
9963 msr_bitmap_l1, msr_bitmap_l0,
9964 APIC_BASE_MSR + (APIC_TASKPRI >> 4),
9965 MSR_TYPE_R | MSR_TYPE_W);
9967 if (nested_cpu_has_vid(vmcs12)) {
9968 nested_vmx_disable_intercept_for_msr(
9969 msr_bitmap_l1, msr_bitmap_l0,
9970 APIC_BASE_MSR + (APIC_EOI >> 4),
9972 nested_vmx_disable_intercept_for_msr(
9973 msr_bitmap_l1, msr_bitmap_l0,
9974 APIC_BASE_MSR + (APIC_SELF_IPI >> 4),
9980 nested_vmx_disable_intercept_for_msr(
9981 msr_bitmap_l1, msr_bitmap_l0,
9983 MSR_TYPE_R | MSR_TYPE_W);
9986 nested_vmx_disable_intercept_for_msr(
9987 msr_bitmap_l1, msr_bitmap_l0,
9992 nested_release_page_clean(page);
9997 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
9998 struct vmcs12 *vmcs12)
10000 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10001 !nested_cpu_has_apic_reg_virt(vmcs12) &&
10002 !nested_cpu_has_vid(vmcs12) &&
10003 !nested_cpu_has_posted_intr(vmcs12))
10007 * If virtualize x2apic mode is enabled,
10008 * virtualize apic access must be disabled.
10010 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
10011 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
10015 * If virtual interrupt delivery is enabled,
10016 * we must exit on external interrupts.
10018 if (nested_cpu_has_vid(vmcs12) &&
10019 !nested_exit_on_intr(vcpu))
10023 * bits 15:8 should be zero in posted_intr_nv,
10024 * the descriptor address has been already checked
10025 * in nested_get_vmcs12_pages.
10027 if (nested_cpu_has_posted_intr(vmcs12) &&
10028 (!nested_cpu_has_vid(vmcs12) ||
10029 !nested_exit_intr_ack_set(vcpu) ||
10030 vmcs12->posted_intr_nv & 0xff00))
10033 /* tpr shadow is needed by all apicv features. */
10034 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10040 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
10041 unsigned long count_field,
10042 unsigned long addr_field)
10047 if (vmcs12_read_any(vcpu, count_field, &count) ||
10048 vmcs12_read_any(vcpu, addr_field, &addr)) {
10054 maxphyaddr = cpuid_maxphyaddr(vcpu);
10055 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
10056 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
10057 pr_debug_ratelimited(
10058 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
10059 addr_field, maxphyaddr, count, addr);
10065 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
10066 struct vmcs12 *vmcs12)
10068 if (vmcs12->vm_exit_msr_load_count == 0 &&
10069 vmcs12->vm_exit_msr_store_count == 0 &&
10070 vmcs12->vm_entry_msr_load_count == 0)
10071 return 0; /* Fast path */
10072 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
10073 VM_EXIT_MSR_LOAD_ADDR) ||
10074 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
10075 VM_EXIT_MSR_STORE_ADDR) ||
10076 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
10077 VM_ENTRY_MSR_LOAD_ADDR))
10082 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
10083 struct vmx_msr_entry *e)
10085 /* x2APIC MSR accesses are not allowed */
10086 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
10088 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
10089 e->index == MSR_IA32_UCODE_REV)
10091 if (e->reserved != 0)
10096 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
10097 struct vmx_msr_entry *e)
10099 if (e->index == MSR_FS_BASE ||
10100 e->index == MSR_GS_BASE ||
10101 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
10102 nested_vmx_msr_check_common(vcpu, e))
10107 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
10108 struct vmx_msr_entry *e)
10110 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
10111 nested_vmx_msr_check_common(vcpu, e))
10117 * Load guest's/host's msr at nested entry/exit.
10118 * return 0 for success, entry index for failure.
10120 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10123 struct vmx_msr_entry e;
10124 struct msr_data msr;
10126 msr.host_initiated = false;
10127 for (i = 0; i < count; i++) {
10128 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
10130 pr_debug_ratelimited(
10131 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10132 __func__, i, gpa + i * sizeof(e));
10135 if (nested_vmx_load_msr_check(vcpu, &e)) {
10136 pr_debug_ratelimited(
10137 "%s check failed (%u, 0x%x, 0x%x)\n",
10138 __func__, i, e.index, e.reserved);
10141 msr.index = e.index;
10142 msr.data = e.value;
10143 if (kvm_set_msr(vcpu, &msr)) {
10144 pr_debug_ratelimited(
10145 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10146 __func__, i, e.index, e.value);
10155 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
10158 struct vmx_msr_entry e;
10160 for (i = 0; i < count; i++) {
10161 struct msr_data msr_info;
10162 if (kvm_vcpu_read_guest(vcpu,
10163 gpa + i * sizeof(e),
10164 &e, 2 * sizeof(u32))) {
10165 pr_debug_ratelimited(
10166 "%s cannot read MSR entry (%u, 0x%08llx)\n",
10167 __func__, i, gpa + i * sizeof(e));
10170 if (nested_vmx_store_msr_check(vcpu, &e)) {
10171 pr_debug_ratelimited(
10172 "%s check failed (%u, 0x%x, 0x%x)\n",
10173 __func__, i, e.index, e.reserved);
10176 msr_info.host_initiated = false;
10177 msr_info.index = e.index;
10178 if (kvm_get_msr(vcpu, &msr_info)) {
10179 pr_debug_ratelimited(
10180 "%s cannot read MSR (%u, 0x%x)\n",
10181 __func__, i, e.index);
10184 if (kvm_vcpu_write_guest(vcpu,
10185 gpa + i * sizeof(e) +
10186 offsetof(struct vmx_msr_entry, value),
10187 &msr_info.data, sizeof(msr_info.data))) {
10188 pr_debug_ratelimited(
10189 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
10190 __func__, i, e.index, msr_info.data);
10198 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
10199 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
10200 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
10201 * guest in a way that will both be appropriate to L1's requests, and our
10202 * needs. In addition to modifying the active vmcs (which is vmcs02), this
10203 * function also has additional necessary side-effects, like setting various
10204 * vcpu->arch fields.
10206 static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10208 struct vcpu_vmx *vmx = to_vmx(vcpu);
10211 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
10212 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
10213 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
10214 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
10215 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
10216 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
10217 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
10218 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
10219 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
10220 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
10221 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
10222 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
10223 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
10224 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
10225 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
10226 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
10227 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
10228 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
10229 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
10230 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
10231 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
10232 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
10233 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
10234 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
10235 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
10236 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
10237 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
10238 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
10239 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
10240 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
10241 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
10242 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
10243 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
10244 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
10245 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
10246 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
10248 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
10249 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
10250 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
10252 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
10253 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
10255 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
10256 vmcs12->vm_entry_intr_info_field);
10257 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
10258 vmcs12->vm_entry_exception_error_code);
10259 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
10260 vmcs12->vm_entry_instruction_len);
10261 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
10262 vmcs12->guest_interruptibility_info);
10263 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
10264 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
10265 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
10266 vmcs12->guest_pending_dbg_exceptions);
10267 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
10268 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
10270 if (nested_cpu_has_xsaves(vmcs12))
10271 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
10272 vmcs_write64(VMCS_LINK_POINTER, -1ull);
10274 exec_control = vmcs12->pin_based_vm_exec_control;
10276 /* Preemption timer setting is only taken from vmcs01. */
10277 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10278 exec_control |= vmcs_config.pin_based_exec_ctrl;
10279 if (vmx->hv_deadline_tsc == -1)
10280 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
10282 /* Posted interrupts setting is only taken from vmcs12. */
10283 if (nested_cpu_has_posted_intr(vmcs12)) {
10285 * Note that we use L0's vector here and in
10286 * vmx_deliver_nested_posted_interrupt.
10288 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
10289 vmx->nested.pi_pending = false;
10290 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
10291 vmcs_write64(POSTED_INTR_DESC_ADDR,
10292 page_to_phys(vmx->nested.pi_desc_page) +
10293 (unsigned long)(vmcs12->posted_intr_desc_addr &
10296 exec_control &= ~PIN_BASED_POSTED_INTR;
10298 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
10300 vmx->nested.preemption_timer_expired = false;
10301 if (nested_cpu_has_preemption_timer(vmcs12))
10302 vmx_start_preemption_timer(vcpu);
10305 * Whether page-faults are trapped is determined by a combination of
10306 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
10307 * If enable_ept, L0 doesn't care about page faults and we should
10308 * set all of these to L1's desires. However, if !enable_ept, L0 does
10309 * care about (at least some) page faults, and because it is not easy
10310 * (if at all possible?) to merge L0 and L1's desires, we simply ask
10311 * to exit on each and every L2 page fault. This is done by setting
10312 * MASK=MATCH=0 and (see below) EB.PF=1.
10313 * Note that below we don't need special code to set EB.PF beyond the
10314 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
10315 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
10316 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
10318 * A problem with this approach (when !enable_ept) is that L1 may be
10319 * injected with more page faults than it asked for. This could have
10320 * caused problems, but in practice existing hypervisors don't care.
10321 * To fix this, we will need to emulate the PFEC checking (on the L1
10322 * page tables), using walk_addr(), when injecting PFs to L1.
10324 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
10325 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
10326 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
10327 enable_ept ? vmcs12->page_fault_error_code_match : 0);
10329 if (cpu_has_secondary_exec_ctrls()) {
10330 exec_control = vmx_secondary_exec_control(vmx);
10332 /* Take the following fields only from vmcs12 */
10333 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10334 SECONDARY_EXEC_RDTSCP |
10335 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
10336 SECONDARY_EXEC_APIC_REGISTER_VIRT);
10337 if (nested_cpu_has(vmcs12,
10338 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS))
10339 exec_control |= vmcs12->secondary_vm_exec_control;
10341 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) {
10343 * If translation failed, no matter: This feature asks
10344 * to exit when accessing the given address, and if it
10345 * can never be accessed, this feature won't do
10348 if (!vmx->nested.apic_access_page)
10350 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10352 vmcs_write64(APIC_ACCESS_ADDR,
10353 page_to_phys(vmx->nested.apic_access_page));
10354 } else if (!(nested_cpu_has_virt_x2apic_mode(vmcs12)) &&
10355 cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
10357 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10358 kvm_vcpu_reload_apic_access_page(vcpu);
10361 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) {
10362 vmcs_write64(EOI_EXIT_BITMAP0,
10363 vmcs12->eoi_exit_bitmap0);
10364 vmcs_write64(EOI_EXIT_BITMAP1,
10365 vmcs12->eoi_exit_bitmap1);
10366 vmcs_write64(EOI_EXIT_BITMAP2,
10367 vmcs12->eoi_exit_bitmap2);
10368 vmcs_write64(EOI_EXIT_BITMAP3,
10369 vmcs12->eoi_exit_bitmap3);
10370 vmcs_write16(GUEST_INTR_STATUS,
10371 vmcs12->guest_intr_status);
10374 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
10379 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
10380 * Some constant fields are set here by vmx_set_constant_host_state().
10381 * Other fields are different per CPU, and will be set later when
10382 * vmx_vcpu_load() is called, and when vmx_save_host_state() is called.
10384 vmx_set_constant_host_state(vmx);
10387 * Set the MSR load/store lists to match L0's settings.
10389 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
10390 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
10391 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
10392 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
10393 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
10396 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
10397 * entry, but only if the current (host) sp changed from the value
10398 * we wrote last (vmx->host_rsp). This cache is no longer relevant
10399 * if we switch vmcs, and rather than hold a separate cache per vmcs,
10400 * here we just force the write to happen on entry.
10404 exec_control = vmx_exec_control(vmx); /* L0's desires */
10405 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
10406 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
10407 exec_control &= ~CPU_BASED_TPR_SHADOW;
10408 exec_control |= vmcs12->cpu_based_vm_exec_control;
10410 if (exec_control & CPU_BASED_TPR_SHADOW) {
10411 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
10412 page_to_phys(vmx->nested.virtual_apic_page));
10413 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
10415 #ifdef CONFIG_X86_64
10416 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
10417 CPU_BASED_CR8_STORE_EXITING;
10421 if (cpu_has_vmx_msr_bitmap() &&
10422 exec_control & CPU_BASED_USE_MSR_BITMAPS &&
10423 nested_vmx_merge_msr_bitmap(vcpu, vmcs12))
10424 ; /* MSR_BITMAP will be set by following vmx_set_efer. */
10426 exec_control &= ~CPU_BASED_USE_MSR_BITMAPS;
10429 * Merging of IO bitmap not currently supported.
10430 * Rather, exit every time.
10432 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
10433 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
10435 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
10437 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
10438 * bitwise-or of what L1 wants to trap for L2, and what we want to
10439 * trap. Note that CR0.TS also needs updating - we do this later.
10441 update_exception_bitmap(vcpu);
10442 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
10443 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
10445 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
10446 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
10447 * bits are further modified by vmx_set_efer() below.
10449 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
10451 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
10452 * emulated by vmx_set_efer(), below.
10454 vm_entry_controls_init(vmx,
10455 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
10456 ~VM_ENTRY_IA32E_MODE) |
10457 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
10459 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) {
10460 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
10461 vcpu->arch.pat = vmcs12->guest_ia32_pat;
10462 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
10463 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
10466 set_cr4_guest_host_mask(vmx);
10468 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS)
10469 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
10471 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
10472 vmcs_write64(TSC_OFFSET,
10473 vcpu->arch.tsc_offset + vmcs12->tsc_offset);
10475 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
10476 if (kvm_has_tsc_control)
10477 decache_tsc_multiplier(vmx);
10479 if (cpu_has_vmx_msr_bitmap())
10480 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
10484 * There is no direct mapping between vpid02 and vpid12, the
10485 * vpid02 is per-vCPU for L0 and reused while the value of
10486 * vpid12 is changed w/ one invvpid during nested vmentry.
10487 * The vpid12 is allocated by L1 for L2, so it will not
10488 * influence global bitmap(for vpid01 and vpid02 allocation)
10489 * even if spawn a lot of nested vCPUs.
10491 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
10492 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
10493 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
10494 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
10495 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->nested.vpid02);
10498 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
10499 vmx_flush_tlb(vcpu);
10506 * Conceptually we want to copy the PML address and index from
10507 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
10508 * since we always flush the log on each vmexit, this happens
10509 * to be equivalent to simply resetting the fields in vmcs02.
10511 ASSERT(vmx->pml_pg);
10512 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
10513 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
10516 if (nested_cpu_has_ept(vmcs12)) {
10517 kvm_mmu_unload(vcpu);
10518 nested_ept_init_mmu_context(vcpu);
10519 } else if (nested_cpu_has2(vmcs12,
10520 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
10521 vmx_flush_tlb_ept_only(vcpu);
10524 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)
10525 vcpu->arch.efer = vmcs12->guest_ia32_efer;
10526 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
10527 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
10529 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
10530 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
10531 vmx_set_efer(vcpu, vcpu->arch.efer);
10534 * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified
10535 * TS bit (for lazy fpu) and bits which we consider mandatory enabled.
10536 * The CR0_READ_SHADOW is what L2 should have expected to read given
10537 * the specifications by L1; It's not enough to take
10538 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
10539 * have more bits than L1 expected.
10541 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
10542 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
10544 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
10545 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
10547 /* shadow page tables on either EPT or shadow page tables */
10548 kvm_set_cr3(vcpu, vmcs12->guest_cr3);
10549 kvm_mmu_reset_context(vcpu);
10552 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
10555 * L1 may access the L2's PDPTR, so save them to construct vmcs12
10558 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
10559 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
10560 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
10561 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
10564 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
10565 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
10569 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
10570 * for running an L2 nested guest.
10572 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
10574 struct vmcs12 *vmcs12;
10575 struct vcpu_vmx *vmx = to_vmx(vcpu);
10580 if (!nested_vmx_check_permission(vcpu) ||
10581 !nested_vmx_check_vmcs12(vcpu))
10584 skip_emulated_instruction(vcpu);
10585 vmcs12 = get_vmcs12(vcpu);
10587 if (enable_shadow_vmcs)
10588 copy_shadow_to_vmcs12(vmx);
10591 * The nested entry process starts with enforcing various prerequisites
10592 * on vmcs12 as required by the Intel SDM, and act appropriately when
10593 * they fail: As the SDM explains, some conditions should cause the
10594 * instruction to fail, while others will cause the instruction to seem
10595 * to succeed, but return an EXIT_REASON_INVALID_STATE.
10596 * To speed up the normal (success) code path, we should avoid checking
10597 * for misconfigurations which will anyway be caught by the processor
10598 * when using the merged vmcs02.
10600 if (vmcs12->launch_state == launch) {
10601 nested_vmx_failValid(vcpu,
10602 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
10603 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
10607 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
10608 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT) {
10609 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10613 if (!nested_get_vmcs12_pages(vcpu, vmcs12)) {
10614 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10618 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12)) {
10619 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10623 if (nested_vmx_check_apicv_controls(vcpu, vmcs12)) {
10624 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10628 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12)) {
10629 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10633 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
10634 vmx->nested.nested_vmx_true_procbased_ctls_low,
10635 vmx->nested.nested_vmx_procbased_ctls_high) ||
10636 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
10637 vmx->nested.nested_vmx_secondary_ctls_low,
10638 vmx->nested.nested_vmx_secondary_ctls_high) ||
10639 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
10640 vmx->nested.nested_vmx_pinbased_ctls_low,
10641 vmx->nested.nested_vmx_pinbased_ctls_high) ||
10642 !vmx_control_verify(vmcs12->vm_exit_controls,
10643 vmx->nested.nested_vmx_true_exit_ctls_low,
10644 vmx->nested.nested_vmx_exit_ctls_high) ||
10645 !vmx_control_verify(vmcs12->vm_entry_controls,
10646 vmx->nested.nested_vmx_true_entry_ctls_low,
10647 vmx->nested.nested_vmx_entry_ctls_high))
10649 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
10653 if (((vmcs12->host_cr0 & VMXON_CR0_ALWAYSON) != VMXON_CR0_ALWAYSON) ||
10654 ((vmcs12->host_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
10655 nested_vmx_failValid(vcpu,
10656 VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
10660 if (!nested_cr0_valid(vcpu, vmcs12->guest_cr0) ||
10661 ((vmcs12->guest_cr4 & VMXON_CR4_ALWAYSON) != VMXON_CR4_ALWAYSON)) {
10662 nested_vmx_entry_failure(vcpu, vmcs12,
10663 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10666 if (vmcs12->vmcs_link_pointer != -1ull) {
10667 nested_vmx_entry_failure(vcpu, vmcs12,
10668 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_VMCS_LINK_PTR);
10673 * If the load IA32_EFER VM-entry control is 1, the following checks
10674 * are performed on the field for the IA32_EFER MSR:
10675 * - Bits reserved in the IA32_EFER MSR must be 0.
10676 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
10677 * the IA-32e mode guest VM-exit control. It must also be identical
10678 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
10681 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) {
10682 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
10683 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
10684 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
10685 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
10686 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME))) {
10687 nested_vmx_entry_failure(vcpu, vmcs12,
10688 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10694 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
10695 * IA32_EFER MSR must be 0 in the field for that register. In addition,
10696 * the values of the LMA and LME bits in the field must each be that of
10697 * the host address-space size VM-exit control.
10699 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
10700 ia32e = (vmcs12->vm_exit_controls &
10701 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
10702 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
10703 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
10704 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME)) {
10705 nested_vmx_entry_failure(vcpu, vmcs12,
10706 EXIT_REASON_INVALID_STATE, ENTRY_FAIL_DEFAULT);
10712 * We're finally done with prerequisite checking, and can start with
10713 * the nested entry.
10716 enter_guest_mode(vcpu);
10718 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
10719 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
10722 vmx->loaded_vmcs = &vmx->nested.vmcs02;
10723 vmx_vcpu_put(vcpu);
10724 vmx_vcpu_load(vcpu, cpu);
10728 vmx_segment_cache_clear(vmx);
10730 prepare_vmcs02(vcpu, vmcs12);
10732 msr_entry_idx = nested_vmx_load_msr(vcpu,
10733 vmcs12->vm_entry_msr_load_addr,
10734 vmcs12->vm_entry_msr_load_count);
10735 if (msr_entry_idx) {
10736 leave_guest_mode(vcpu);
10737 vmx_load_vmcs01(vcpu);
10738 nested_vmx_entry_failure(vcpu, vmcs12,
10739 EXIT_REASON_MSR_LOAD_FAIL, msr_entry_idx);
10743 vmcs12->launch_state = 1;
10745 /* Hide L1D cache contents from the nested guest. */
10746 vmx->vcpu.arch.l1tf_flush_l1d = true;
10748 if (vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT)
10749 return kvm_vcpu_halt(vcpu);
10751 vmx->nested.nested_run_pending = 1;
10754 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
10755 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
10756 * returned as far as L1 is concerned. It will only return (and set
10757 * the success flag) when L2 exits (see nested_vmx_vmexit()).
10763 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
10764 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
10765 * This function returns the new value we should put in vmcs12.guest_cr0.
10766 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
10767 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
10768 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
10769 * didn't trap the bit, because if L1 did, so would L0).
10770 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
10771 * been modified by L2, and L1 knows it. So just leave the old value of
10772 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
10773 * isn't relevant, because if L0 traps this bit it can set it to anything.
10774 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
10775 * changed these bits, and therefore they need to be updated, but L0
10776 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
10777 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
10779 static inline unsigned long
10780 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10783 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
10784 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
10785 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
10786 vcpu->arch.cr0_guest_owned_bits));
10789 static inline unsigned long
10790 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
10793 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
10794 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
10795 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
10796 vcpu->arch.cr4_guest_owned_bits));
10799 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
10800 struct vmcs12 *vmcs12)
10805 if (vcpu->arch.exception.pending && vcpu->arch.exception.reinject) {
10806 nr = vcpu->arch.exception.nr;
10807 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
10809 if (kvm_exception_is_soft(nr)) {
10810 vmcs12->vm_exit_instruction_len =
10811 vcpu->arch.event_exit_inst_len;
10812 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
10814 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
10816 if (vcpu->arch.exception.has_error_code) {
10817 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
10818 vmcs12->idt_vectoring_error_code =
10819 vcpu->arch.exception.error_code;
10822 vmcs12->idt_vectoring_info_field = idt_vectoring;
10823 } else if (vcpu->arch.nmi_injected) {
10824 vmcs12->idt_vectoring_info_field =
10825 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
10826 } else if (vcpu->arch.interrupt.pending) {
10827 nr = vcpu->arch.interrupt.nr;
10828 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
10830 if (vcpu->arch.interrupt.soft) {
10831 idt_vectoring |= INTR_TYPE_SOFT_INTR;
10832 vmcs12->vm_entry_instruction_len =
10833 vcpu->arch.event_exit_inst_len;
10835 idt_vectoring |= INTR_TYPE_EXT_INTR;
10837 vmcs12->idt_vectoring_info_field = idt_vectoring;
10841 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
10843 struct vcpu_vmx *vmx = to_vmx(vcpu);
10845 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
10846 vmx->nested.preemption_timer_expired) {
10847 if (vmx->nested.nested_run_pending)
10849 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
10853 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
10854 if (vmx->nested.nested_run_pending ||
10855 vcpu->arch.interrupt.pending)
10857 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
10858 NMI_VECTOR | INTR_TYPE_NMI_INTR |
10859 INTR_INFO_VALID_MASK, 0);
10861 * The NMI-triggered VM exit counts as injection:
10862 * clear this one and block further NMIs.
10864 vcpu->arch.nmi_pending = 0;
10865 vmx_set_nmi_mask(vcpu, true);
10869 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
10870 nested_exit_on_intr(vcpu)) {
10871 if (vmx->nested.nested_run_pending)
10873 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
10877 vmx_complete_nested_posted_interrupt(vcpu);
10881 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
10883 ktime_t remaining =
10884 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
10887 if (ktime_to_ns(remaining) <= 0)
10890 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
10891 do_div(value, 1000000);
10892 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
10896 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
10897 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
10898 * and this function updates it to reflect the changes to the guest state while
10899 * L2 was running (and perhaps made some exits which were handled directly by L0
10900 * without going back to L1), and to reflect the exit reason.
10901 * Note that we do not have to copy here all VMCS fields, just those that
10902 * could have changed by the L2 guest or the exit - i.e., the guest-state and
10903 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
10904 * which already writes to vmcs12 directly.
10906 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
10907 u32 exit_reason, u32 exit_intr_info,
10908 unsigned long exit_qualification)
10910 /* update guest state fields: */
10911 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
10912 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
10914 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
10915 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
10916 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
10918 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
10919 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
10920 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
10921 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
10922 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
10923 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
10924 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
10925 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
10926 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
10927 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
10928 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
10929 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
10930 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
10931 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
10932 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
10933 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
10934 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
10935 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
10936 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
10937 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
10938 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
10939 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
10940 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
10941 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
10942 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
10943 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
10944 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
10945 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
10946 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
10947 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
10948 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
10949 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
10950 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
10951 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
10952 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
10953 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
10955 vmcs12->guest_interruptibility_info =
10956 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
10957 vmcs12->guest_pending_dbg_exceptions =
10958 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
10959 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
10960 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
10962 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
10964 if (nested_cpu_has_preemption_timer(vmcs12)) {
10965 if (vmcs12->vm_exit_controls &
10966 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
10967 vmcs12->vmx_preemption_timer_value =
10968 vmx_get_preemption_timer_value(vcpu);
10969 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
10973 * In some cases (usually, nested EPT), L2 is allowed to change its
10974 * own CR3 without exiting. If it has changed it, we must keep it.
10975 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
10976 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
10978 * Additionally, restore L2's PDPTR to vmcs12.
10981 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
10982 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
10983 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
10984 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
10985 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
10988 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
10990 if (nested_cpu_has_vid(vmcs12))
10991 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
10993 vmcs12->vm_entry_controls =
10994 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
10995 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
10997 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
10998 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
10999 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
11002 /* TODO: These cannot have changed unless we have MSR bitmaps and
11003 * the relevant bit asks not to trap the change */
11004 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
11005 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
11006 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
11007 vmcs12->guest_ia32_efer = vcpu->arch.efer;
11008 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
11009 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
11010 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
11011 if (kvm_mpx_supported())
11012 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
11013 if (nested_cpu_has_xsaves(vmcs12))
11014 vmcs12->xss_exit_bitmap = vmcs_read64(XSS_EXIT_BITMAP);
11016 /* update exit information fields: */
11018 vmcs12->vm_exit_reason = exit_reason;
11019 vmcs12->exit_qualification = exit_qualification;
11021 vmcs12->vm_exit_intr_info = exit_intr_info;
11022 if ((vmcs12->vm_exit_intr_info &
11023 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
11024 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK))
11025 vmcs12->vm_exit_intr_error_code =
11026 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
11027 vmcs12->idt_vectoring_info_field = 0;
11028 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
11029 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
11031 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
11032 /* vm_entry_intr_info_field is cleared on exit. Emulate this
11033 * instead of reading the real value. */
11034 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
11037 * Transfer the event that L0 or L1 may wanted to inject into
11038 * L2 to IDT_VECTORING_INFO_FIELD.
11040 vmcs12_save_pending_event(vcpu, vmcs12);
11044 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
11045 * preserved above and would only end up incorrectly in L1.
11047 vcpu->arch.nmi_injected = false;
11048 kvm_clear_exception_queue(vcpu);
11049 kvm_clear_interrupt_queue(vcpu);
11053 * A part of what we need to when the nested L2 guest exits and we want to
11054 * run its L1 parent, is to reset L1's guest state to the host state specified
11056 * This function is to be called not only on normal nested exit, but also on
11057 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
11058 * Failures During or After Loading Guest State").
11059 * This function should be called when the active VMCS is L1's (vmcs01).
11061 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
11062 struct vmcs12 *vmcs12)
11064 struct kvm_segment seg;
11066 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
11067 vcpu->arch.efer = vmcs12->host_ia32_efer;
11068 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11069 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
11071 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
11072 vmx_set_efer(vcpu, vcpu->arch.efer);
11074 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
11075 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
11076 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
11078 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
11079 * actually changed, because it depends on the current state of
11080 * fpu_active (which may have changed).
11081 * Note that vmx_set_cr0 refers to efer set above.
11083 vmx_set_cr0(vcpu, vmcs12->host_cr0);
11085 * If we did fpu_activate()/fpu_deactivate() during L2's run, we need
11086 * to apply the same changes to L1's vmcs. We just set cr0 correctly,
11087 * but we also need to update cr0_guest_host_mask and exception_bitmap.
11089 update_exception_bitmap(vcpu);
11090 vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0);
11091 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
11094 * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01
11095 * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask();
11097 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
11098 vmx_set_cr4(vcpu, vmcs12->host_cr4);
11100 nested_ept_uninit_mmu_context(vcpu);
11102 kvm_set_cr3(vcpu, vmcs12->host_cr3);
11103 kvm_mmu_reset_context(vcpu);
11106 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
11110 * Trivially support vpid by letting L2s share their parent
11111 * L1's vpid. TODO: move to a more elaborate solution, giving
11112 * each L2 its own vpid and exposing the vpid feature to L1.
11114 vmx_flush_tlb(vcpu);
11118 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
11119 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
11120 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
11121 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
11122 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
11123 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
11124 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
11126 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
11127 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
11128 vmcs_write64(GUEST_BNDCFGS, 0);
11130 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
11131 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
11132 vcpu->arch.pat = vmcs12->host_ia32_pat;
11134 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
11135 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
11136 vmcs12->host_ia32_perf_global_ctrl);
11138 /* Set L1 segment info according to Intel SDM
11139 27.5.2 Loading Host Segment and Descriptor-Table Registers */
11140 seg = (struct kvm_segment) {
11142 .limit = 0xFFFFFFFF,
11143 .selector = vmcs12->host_cs_selector,
11149 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
11153 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
11154 seg = (struct kvm_segment) {
11156 .limit = 0xFFFFFFFF,
11163 seg.selector = vmcs12->host_ds_selector;
11164 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
11165 seg.selector = vmcs12->host_es_selector;
11166 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
11167 seg.selector = vmcs12->host_ss_selector;
11168 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
11169 seg.selector = vmcs12->host_fs_selector;
11170 seg.base = vmcs12->host_fs_base;
11171 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
11172 seg.selector = vmcs12->host_gs_selector;
11173 seg.base = vmcs12->host_gs_base;
11174 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
11175 seg = (struct kvm_segment) {
11176 .base = vmcs12->host_tr_base,
11178 .selector = vmcs12->host_tr_selector,
11182 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
11184 kvm_set_dr(vcpu, 7, 0x400);
11185 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
11187 if (cpu_has_vmx_msr_bitmap())
11188 vmx_update_msr_bitmap(vcpu);
11190 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
11191 vmcs12->vm_exit_msr_load_count))
11192 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
11196 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
11197 * and modify vmcs12 to make it see what it would expect to see there if
11198 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
11200 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
11201 u32 exit_intr_info,
11202 unsigned long exit_qualification)
11204 struct vcpu_vmx *vmx = to_vmx(vcpu);
11205 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11207 /* trying to cancel vmlaunch/vmresume is a bug */
11208 WARN_ON_ONCE(vmx->nested.nested_run_pending);
11210 leave_guest_mode(vcpu);
11211 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
11212 exit_qualification);
11214 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
11215 vmcs12->vm_exit_msr_store_count))
11216 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
11218 vmx_load_vmcs01(vcpu);
11220 if ((exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT)
11221 && nested_exit_intr_ack_set(vcpu)) {
11222 int irq = kvm_cpu_get_interrupt(vcpu);
11224 vmcs12->vm_exit_intr_info = irq |
11225 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
11228 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
11229 vmcs12->exit_qualification,
11230 vmcs12->idt_vectoring_info_field,
11231 vmcs12->vm_exit_intr_info,
11232 vmcs12->vm_exit_intr_error_code,
11235 vm_entry_controls_reset_shadow(vmx);
11236 vm_exit_controls_reset_shadow(vmx);
11237 vmx_segment_cache_clear(vmx);
11239 load_vmcs12_host_state(vcpu, vmcs12);
11241 /* Update any VMCS fields that might have changed while L2 ran */
11242 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
11243 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
11244 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
11245 if (vmx->hv_deadline_tsc == -1)
11246 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11247 PIN_BASED_VMX_PREEMPTION_TIMER);
11249 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11250 PIN_BASED_VMX_PREEMPTION_TIMER);
11251 if (kvm_has_tsc_control)
11252 decache_tsc_multiplier(vmx);
11254 if (vmx->nested.change_vmcs01_virtual_x2apic_mode) {
11255 vmx->nested.change_vmcs01_virtual_x2apic_mode = false;
11256 vmx_set_virtual_x2apic_mode(vcpu,
11257 vcpu->arch.apic_base & X2APIC_ENABLE);
11258 } else if (!nested_cpu_has_ept(vmcs12) &&
11259 nested_cpu_has2(vmcs12,
11260 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11261 vmx_flush_tlb_ept_only(vcpu);
11264 /* This is needed for same reason as it was needed in prepare_vmcs02 */
11267 /* Unpin physical memory we referred to in vmcs02 */
11268 if (vmx->nested.apic_access_page) {
11269 nested_release_page(vmx->nested.apic_access_page);
11270 vmx->nested.apic_access_page = NULL;
11272 if (vmx->nested.virtual_apic_page) {
11273 nested_release_page(vmx->nested.virtual_apic_page);
11274 vmx->nested.virtual_apic_page = NULL;
11276 if (vmx->nested.pi_desc_page) {
11277 kunmap(vmx->nested.pi_desc_page);
11278 nested_release_page(vmx->nested.pi_desc_page);
11279 vmx->nested.pi_desc_page = NULL;
11280 vmx->nested.pi_desc = NULL;
11284 * We are now running in L2, mmu_notifier will force to reload the
11285 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
11287 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
11290 * Exiting from L2 to L1, we're now back to L1 which thinks it just
11291 * finished a VMLAUNCH or VMRESUME instruction, so we need to set the
11292 * success or failure flag accordingly.
11294 if (unlikely(vmx->fail)) {
11296 nested_vmx_failValid(vcpu, vmcs_read32(VM_INSTRUCTION_ERROR));
11298 nested_vmx_succeed(vcpu);
11299 if (enable_shadow_vmcs)
11300 vmx->nested.sync_shadow_vmcs = true;
11302 /* in case we halted in L2 */
11303 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
11307 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
11309 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
11311 if (is_guest_mode(vcpu)) {
11312 to_vmx(vcpu)->nested.nested_run_pending = 0;
11313 nested_vmx_vmexit(vcpu, -1, 0, 0);
11315 free_nested(to_vmx(vcpu));
11319 * L1's failure to enter L2 is a subset of a normal exit, as explained in
11320 * 23.7 "VM-entry failures during or after loading guest state" (this also
11321 * lists the acceptable exit-reason and exit-qualification parameters).
11322 * It should only be called before L2 actually succeeded to run, and when
11323 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
11325 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
11326 struct vmcs12 *vmcs12,
11327 u32 reason, unsigned long qualification)
11329 load_vmcs12_host_state(vcpu, vmcs12);
11330 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
11331 vmcs12->exit_qualification = qualification;
11332 nested_vmx_succeed(vcpu);
11333 if (enable_shadow_vmcs)
11334 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
11337 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
11338 struct x86_instruction_info *info,
11339 enum x86_intercept_stage stage)
11341 return X86EMUL_CONTINUE;
11344 #ifdef CONFIG_X86_64
11345 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
11346 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
11347 u64 divisor, u64 *result)
11349 u64 low = a << shift, high = a >> (64 - shift);
11351 /* To avoid the overflow on divq */
11352 if (high >= divisor)
11355 /* Low hold the result, high hold rem which is discarded */
11356 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
11357 "rm" (divisor), "0" (low), "1" (high));
11363 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
11365 struct vcpu_vmx *vmx = to_vmx(vcpu);
11366 u64 tscl = rdtsc();
11367 u64 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
11368 u64 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
11370 /* Convert to host delta tsc if tsc scaling is enabled */
11371 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
11372 u64_shl_div_u64(delta_tsc,
11373 kvm_tsc_scaling_ratio_frac_bits,
11374 vcpu->arch.tsc_scaling_ratio,
11379 * If the delta tsc can't fit in the 32 bit after the multi shift,
11380 * we can't use the preemption timer.
11381 * It's possible that it fits on later vmentries, but checking
11382 * on every vmentry is costly so we just use an hrtimer.
11384 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
11387 vmx->hv_deadline_tsc = tscl + delta_tsc;
11388 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
11389 PIN_BASED_VMX_PREEMPTION_TIMER);
11393 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
11395 struct vcpu_vmx *vmx = to_vmx(vcpu);
11396 vmx->hv_deadline_tsc = -1;
11397 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
11398 PIN_BASED_VMX_PREEMPTION_TIMER);
11402 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
11405 shrink_ple_window(vcpu);
11408 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
11409 struct kvm_memory_slot *slot)
11411 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
11412 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
11415 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
11416 struct kvm_memory_slot *slot)
11418 kvm_mmu_slot_set_dirty(kvm, slot);
11421 static void vmx_flush_log_dirty(struct kvm *kvm)
11423 kvm_flush_pml_buffers(kvm);
11426 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
11427 struct kvm_memory_slot *memslot,
11428 gfn_t offset, unsigned long mask)
11430 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
11433 static void __pi_post_block(struct kvm_vcpu *vcpu)
11435 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11436 struct pi_desc old, new;
11440 old.control = new.control = pi_desc->control;
11441 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
11442 "Wakeup handler not enabled while the VCPU is blocked\n");
11444 dest = cpu_physical_id(vcpu->cpu);
11446 if (x2apic_enabled())
11449 new.ndst = (dest << 8) & 0xFF00;
11451 /* set 'NV' to 'notification vector' */
11452 new.nv = POSTED_INTR_VECTOR;
11453 } while (cmpxchg64(&pi_desc->control, old.control,
11454 new.control) != old.control);
11456 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
11457 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11458 list_del(&vcpu->blocked_vcpu_list);
11459 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11460 vcpu->pre_pcpu = -1;
11465 * This routine does the following things for vCPU which is going
11466 * to be blocked if VT-d PI is enabled.
11467 * - Store the vCPU to the wakeup list, so when interrupts happen
11468 * we can find the right vCPU to wake up.
11469 * - Change the Posted-interrupt descriptor as below:
11470 * 'NDST' <-- vcpu->pre_pcpu
11471 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
11472 * - If 'ON' is set during this process, which means at least one
11473 * interrupt is posted for this vCPU, we cannot block it, in
11474 * this case, return 1, otherwise, return 0.
11477 static int pi_pre_block(struct kvm_vcpu *vcpu)
11480 struct pi_desc old, new;
11481 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
11483 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
11484 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11485 !kvm_vcpu_apicv_active(vcpu))
11488 WARN_ON(irqs_disabled());
11489 local_irq_disable();
11490 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
11491 vcpu->pre_pcpu = vcpu->cpu;
11492 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11493 list_add_tail(&vcpu->blocked_vcpu_list,
11494 &per_cpu(blocked_vcpu_on_cpu,
11496 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
11500 old.control = new.control = pi_desc->control;
11502 WARN((pi_desc->sn == 1),
11503 "Warning: SN field of posted-interrupts "
11504 "is set before blocking\n");
11507 * Since vCPU can be preempted during this process,
11508 * vcpu->cpu could be different with pre_pcpu, we
11509 * need to set pre_pcpu as the destination of wakeup
11510 * notification event, then we can find the right vCPU
11511 * to wakeup in wakeup handler if interrupts happen
11512 * when the vCPU is in blocked state.
11514 dest = cpu_physical_id(vcpu->pre_pcpu);
11516 if (x2apic_enabled())
11519 new.ndst = (dest << 8) & 0xFF00;
11521 /* set 'NV' to 'wakeup vector' */
11522 new.nv = POSTED_INTR_WAKEUP_VECTOR;
11523 } while (cmpxchg64(&pi_desc->control, old.control,
11524 new.control) != old.control);
11526 /* We should not block the vCPU if an interrupt is posted for it. */
11527 if (pi_test_on(pi_desc) == 1)
11528 __pi_post_block(vcpu);
11530 local_irq_enable();
11531 return (vcpu->pre_pcpu == -1);
11534 static int vmx_pre_block(struct kvm_vcpu *vcpu)
11536 if (pi_pre_block(vcpu))
11539 if (kvm_lapic_hv_timer_in_use(vcpu))
11540 kvm_lapic_switch_to_sw_timer(vcpu);
11545 static void pi_post_block(struct kvm_vcpu *vcpu)
11547 if (vcpu->pre_pcpu == -1)
11550 WARN_ON(irqs_disabled());
11551 local_irq_disable();
11552 __pi_post_block(vcpu);
11553 local_irq_enable();
11556 static void vmx_post_block(struct kvm_vcpu *vcpu)
11558 if (kvm_x86_ops->set_hv_timer)
11559 kvm_lapic_switch_to_hv_timer(vcpu);
11561 pi_post_block(vcpu);
11565 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
11568 * @host_irq: host irq of the interrupt
11569 * @guest_irq: gsi of the interrupt
11570 * @set: set or unset PI
11571 * returns 0 on success, < 0 on failure
11573 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
11574 uint32_t guest_irq, bool set)
11576 struct kvm_kernel_irq_routing_entry *e;
11577 struct kvm_irq_routing_table *irq_rt;
11578 struct kvm_lapic_irq irq;
11579 struct kvm_vcpu *vcpu;
11580 struct vcpu_data vcpu_info;
11583 if (!kvm_arch_has_assigned_device(kvm) ||
11584 !irq_remapping_cap(IRQ_POSTING_CAP) ||
11585 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
11588 idx = srcu_read_lock(&kvm->irq_srcu);
11589 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
11590 if (guest_irq >= irq_rt->nr_rt_entries ||
11591 hlist_empty(&irq_rt->map[guest_irq])) {
11592 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
11593 guest_irq, irq_rt->nr_rt_entries);
11597 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
11598 if (e->type != KVM_IRQ_ROUTING_MSI)
11601 * VT-d PI cannot support posting multicast/broadcast
11602 * interrupts to a vCPU, we still use interrupt remapping
11603 * for these kind of interrupts.
11605 * For lowest-priority interrupts, we only support
11606 * those with single CPU as the destination, e.g. user
11607 * configures the interrupts via /proc/irq or uses
11608 * irqbalance to make the interrupts single-CPU.
11610 * We will support full lowest-priority interrupt later.
11613 kvm_set_msi_irq(kvm, e, &irq);
11614 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
11616 * Make sure the IRTE is in remapped mode if
11617 * we don't handle it in posted mode.
11619 ret = irq_set_vcpu_affinity(host_irq, NULL);
11622 "failed to back to remapped mode, irq: %u\n",
11630 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
11631 vcpu_info.vector = irq.vector;
11633 trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
11634 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
11637 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
11639 ret = irq_set_vcpu_affinity(host_irq, NULL);
11642 printk(KERN_INFO "%s: failed to update PI IRTE\n",
11650 srcu_read_unlock(&kvm->irq_srcu, idx);
11654 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
11656 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
11657 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11658 FEATURE_CONTROL_LMCE;
11660 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11661 ~FEATURE_CONTROL_LMCE;
11664 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
11665 .cpu_has_kvm_support = cpu_has_kvm_support,
11666 .disabled_by_bios = vmx_disabled_by_bios,
11667 .hardware_setup = hardware_setup,
11668 .hardware_unsetup = hardware_unsetup,
11669 .check_processor_compatibility = vmx_check_processor_compat,
11670 .hardware_enable = hardware_enable,
11671 .hardware_disable = hardware_disable,
11672 .cpu_has_accelerated_tpr = report_flexpriority,
11673 .has_emulated_msr = vmx_has_emulated_msr,
11675 .vm_init = vmx_vm_init,
11677 .vcpu_create = vmx_create_vcpu,
11678 .vcpu_free = vmx_free_vcpu,
11679 .vcpu_reset = vmx_vcpu_reset,
11681 .prepare_guest_switch = vmx_save_host_state,
11682 .vcpu_load = vmx_vcpu_load,
11683 .vcpu_put = vmx_vcpu_put,
11685 .update_bp_intercept = update_exception_bitmap,
11686 .get_msr_feature = vmx_get_msr_feature,
11687 .get_msr = vmx_get_msr,
11688 .set_msr = vmx_set_msr,
11689 .get_segment_base = vmx_get_segment_base,
11690 .get_segment = vmx_get_segment,
11691 .set_segment = vmx_set_segment,
11692 .get_cpl = vmx_get_cpl,
11693 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
11694 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
11695 .decache_cr3 = vmx_decache_cr3,
11696 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
11697 .set_cr0 = vmx_set_cr0,
11698 .set_cr3 = vmx_set_cr3,
11699 .set_cr4 = vmx_set_cr4,
11700 .set_efer = vmx_set_efer,
11701 .get_idt = vmx_get_idt,
11702 .set_idt = vmx_set_idt,
11703 .get_gdt = vmx_get_gdt,
11704 .set_gdt = vmx_set_gdt,
11705 .get_dr6 = vmx_get_dr6,
11706 .set_dr6 = vmx_set_dr6,
11707 .set_dr7 = vmx_set_dr7,
11708 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
11709 .cache_reg = vmx_cache_reg,
11710 .get_rflags = vmx_get_rflags,
11711 .set_rflags = vmx_set_rflags,
11713 .get_pkru = vmx_get_pkru,
11715 .fpu_activate = vmx_fpu_activate,
11716 .fpu_deactivate = vmx_fpu_deactivate,
11718 .tlb_flush = vmx_flush_tlb,
11720 .run = vmx_vcpu_run,
11721 .handle_exit = vmx_handle_exit,
11722 .skip_emulated_instruction = skip_emulated_instruction,
11723 .set_interrupt_shadow = vmx_set_interrupt_shadow,
11724 .get_interrupt_shadow = vmx_get_interrupt_shadow,
11725 .patch_hypercall = vmx_patch_hypercall,
11726 .set_irq = vmx_inject_irq,
11727 .set_nmi = vmx_inject_nmi,
11728 .queue_exception = vmx_queue_exception,
11729 .cancel_injection = vmx_cancel_injection,
11730 .interrupt_allowed = vmx_interrupt_allowed,
11731 .nmi_allowed = vmx_nmi_allowed,
11732 .get_nmi_mask = vmx_get_nmi_mask,
11733 .set_nmi_mask = vmx_set_nmi_mask,
11734 .enable_nmi_window = enable_nmi_window,
11735 .enable_irq_window = enable_irq_window,
11736 .update_cr8_intercept = update_cr8_intercept,
11737 .set_virtual_x2apic_mode = vmx_set_virtual_x2apic_mode,
11738 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
11739 .get_enable_apicv = vmx_get_enable_apicv,
11740 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
11741 .load_eoi_exitmap = vmx_load_eoi_exitmap,
11742 .hwapic_irr_update = vmx_hwapic_irr_update,
11743 .hwapic_isr_update = vmx_hwapic_isr_update,
11744 .sync_pir_to_irr = vmx_sync_pir_to_irr,
11745 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
11747 .set_tss_addr = vmx_set_tss_addr,
11748 .get_tdp_level = get_ept_level,
11749 .get_mt_mask = vmx_get_mt_mask,
11751 .get_exit_info = vmx_get_exit_info,
11753 .get_lpage_level = vmx_get_lpage_level,
11755 .cpuid_update = vmx_cpuid_update,
11757 .rdtscp_supported = vmx_rdtscp_supported,
11758 .invpcid_supported = vmx_invpcid_supported,
11760 .set_supported_cpuid = vmx_set_supported_cpuid,
11762 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
11764 .write_tsc_offset = vmx_write_tsc_offset,
11766 .set_tdp_cr3 = vmx_set_cr3,
11768 .check_intercept = vmx_check_intercept,
11769 .handle_external_intr = vmx_handle_external_intr,
11770 .mpx_supported = vmx_mpx_supported,
11771 .xsaves_supported = vmx_xsaves_supported,
11773 .check_nested_events = vmx_check_nested_events,
11775 .sched_in = vmx_sched_in,
11777 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
11778 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
11779 .flush_log_dirty = vmx_flush_log_dirty,
11780 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
11782 .pre_block = vmx_pre_block,
11783 .post_block = vmx_post_block,
11785 .pmu_ops = &intel_pmu_ops,
11787 .update_pi_irte = vmx_update_pi_irte,
11789 #ifdef CONFIG_X86_64
11790 .set_hv_timer = vmx_set_hv_timer,
11791 .cancel_hv_timer = vmx_cancel_hv_timer,
11794 .setup_mce = vmx_setup_mce,
11797 static void vmx_cleanup_l1d_flush(void)
11799 if (vmx_l1d_flush_pages) {
11800 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
11801 vmx_l1d_flush_pages = NULL;
11803 /* Restore state so sysfs ignores VMX */
11804 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
11808 static void vmx_exit(void)
11810 #ifdef CONFIG_KEXEC_CORE
11811 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
11817 vmx_cleanup_l1d_flush();
11819 module_exit(vmx_exit)
11821 static int __init vmx_init(void)
11825 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
11826 __alignof__(struct vcpu_vmx), THIS_MODULE);
11831 * Must be called after kvm_init() so enable_ept is properly set
11832 * up. Hand the parameter mitigation value in which was stored in
11833 * the pre module init parser. If no parameter was given, it will
11834 * contain 'auto' which will be turned into the default 'cond'
11837 if (boot_cpu_has(X86_BUG_L1TF)) {
11838 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
11845 #ifdef CONFIG_KEXEC_CORE
11846 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
11847 crash_vmclear_local_loaded_vmcss);
11852 module_init(vmx_init)