iwlwifi: mvm: fix version check for GEO_TX_POWER_LIMIT support
[linux/fpc-iii.git] / arch / x86 / kvm / vmx.c
blob2e310ea62d609e53a2c9442a376093ea593c69c8
1 /*
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.
10 * Authors:
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.
19 #include "irq.h"
20 #include "mmu.h"
21 #include "cpuid.h"
22 #include "lapic.h"
24 #include <linux/kvm_host.h>
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/mm.h>
28 #include <linux/highmem.h>
29 #include <linux/sched.h>
30 #include <linux/sched/smt.h>
31 #include <linux/moduleparam.h>
32 #include <linux/mod_devicetable.h>
33 #include <linux/trace_events.h>
34 #include <linux/slab.h>
35 #include <linux/tboot.h>
36 #include <linux/hrtimer.h>
37 #include <linux/frame.h>
38 #include <linux/nospec.h>
39 #include "kvm_cache_regs.h"
40 #include "x86.h"
42 #include <asm/asm.h>
43 #include <asm/cpu.h>
44 #include <asm/io.h>
45 #include <asm/desc.h>
46 #include <asm/vmx.h>
47 #include <asm/virtext.h>
48 #include <asm/mce.h>
49 #include <asm/fpu/internal.h>
50 #include <asm/perf_event.h>
51 #include <asm/debugreg.h>
52 #include <asm/kexec.h>
53 #include <asm/apic.h>
54 #include <asm/irq_remapping.h>
55 #include <asm/mmu_context.h>
56 #include <asm/spec-ctrl.h>
57 #include <asm/mshyperv.h>
59 #include "trace.h"
60 #include "pmu.h"
61 #include "vmx_evmcs.h"
63 #define __ex(x) __kvm_handle_fault_on_reboot(x)
64 #define __ex_clear(x, reg) \
65 ____kvm_handle_fault_on_reboot(x, "xor " reg " , " reg)
67 MODULE_AUTHOR("Qumranet");
68 MODULE_LICENSE("GPL");
70 static const struct x86_cpu_id vmx_cpu_id[] = {
71 X86_FEATURE_MATCH(X86_FEATURE_VMX),
74 MODULE_DEVICE_TABLE(x86cpu, vmx_cpu_id);
76 static bool __read_mostly enable_vpid = 1;
77 module_param_named(vpid, enable_vpid, bool, 0444);
79 static bool __read_mostly enable_vnmi = 1;
80 module_param_named(vnmi, enable_vnmi, bool, S_IRUGO);
82 static bool __read_mostly flexpriority_enabled = 1;
83 module_param_named(flexpriority, flexpriority_enabled, bool, S_IRUGO);
85 static bool __read_mostly enable_ept = 1;
86 module_param_named(ept, enable_ept, bool, S_IRUGO);
88 static bool __read_mostly enable_unrestricted_guest = 1;
89 module_param_named(unrestricted_guest,
90 enable_unrestricted_guest, bool, S_IRUGO);
92 static bool __read_mostly enable_ept_ad_bits = 1;
93 module_param_named(eptad, enable_ept_ad_bits, bool, S_IRUGO);
95 static bool __read_mostly emulate_invalid_guest_state = true;
96 module_param(emulate_invalid_guest_state, bool, S_IRUGO);
98 static bool __read_mostly fasteoi = 1;
99 module_param(fasteoi, bool, S_IRUGO);
101 static bool __read_mostly enable_apicv = 1;
102 module_param(enable_apicv, bool, S_IRUGO);
104 static bool __read_mostly enable_shadow_vmcs = 1;
105 module_param_named(enable_shadow_vmcs, enable_shadow_vmcs, bool, S_IRUGO);
107 * If nested=1, nested virtualization is supported, i.e., guests may use
108 * VMX and be a hypervisor for its own guests. If nested=0, guests may not
109 * use VMX instructions.
111 static bool __read_mostly nested = 0;
112 module_param(nested, bool, S_IRUGO);
114 static u64 __read_mostly host_xss;
116 static bool __read_mostly enable_pml = 1;
117 module_param_named(pml, enable_pml, bool, S_IRUGO);
119 #define MSR_TYPE_R 1
120 #define MSR_TYPE_W 2
121 #define MSR_TYPE_RW 3
123 #define MSR_BITMAP_MODE_X2APIC 1
124 #define MSR_BITMAP_MODE_X2APIC_APICV 2
126 #define KVM_VMX_TSC_MULTIPLIER_MAX 0xffffffffffffffffULL
128 /* Guest_tsc -> host_tsc conversion requires 64-bit division. */
129 static int __read_mostly cpu_preemption_timer_multi;
130 static bool __read_mostly enable_preemption_timer = 1;
131 #ifdef CONFIG_X86_64
132 module_param_named(preemption_timer, enable_preemption_timer, bool, S_IRUGO);
133 #endif
135 #define KVM_GUEST_CR0_MASK (X86_CR0_NW | X86_CR0_CD)
136 #define KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR0_NE
137 #define KVM_VM_CR0_ALWAYS_ON \
138 (KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST | \
139 X86_CR0_WP | X86_CR0_PG | X86_CR0_PE)
140 #define KVM_CR4_GUEST_OWNED_BITS \
141 (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \
142 | X86_CR4_OSXMMEXCPT | X86_CR4_LA57 | X86_CR4_TSD)
144 #define KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST X86_CR4_VMXE
145 #define KVM_PMODE_VM_CR4_ALWAYS_ON (X86_CR4_PAE | X86_CR4_VMXE)
146 #define KVM_RMODE_VM_CR4_ALWAYS_ON (X86_CR4_VME | X86_CR4_PAE | X86_CR4_VMXE)
148 #define RMODE_GUEST_OWNED_EFLAGS_BITS (~(X86_EFLAGS_IOPL | X86_EFLAGS_VM))
150 #define VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE 5
153 * Hyper-V requires all of these, so mark them as supported even though
154 * they are just treated the same as all-context.
156 #define VMX_VPID_EXTENT_SUPPORTED_MASK \
157 (VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT | \
158 VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT | \
159 VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT | \
160 VMX_VPID_EXTENT_SINGLE_NON_GLOBAL_BIT)
163 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
164 * ple_gap: upper bound on the amount of time between two successive
165 * executions of PAUSE in a loop. Also indicate if ple enabled.
166 * According to test, this time is usually smaller than 128 cycles.
167 * ple_window: upper bound on the amount of time a guest is allowed to execute
168 * in a PAUSE loop. Tests indicate that most spinlocks are held for
169 * less than 2^12 cycles
170 * Time is measured based on a counter that runs at the same rate as the TSC,
171 * refer SDM volume 3b section 21.6.13 & 22.1.3.
173 static unsigned int ple_gap = KVM_DEFAULT_PLE_GAP;
174 module_param(ple_gap, uint, 0444);
176 static unsigned int ple_window = KVM_VMX_DEFAULT_PLE_WINDOW;
177 module_param(ple_window, uint, 0444);
179 /* Default doubles per-vcpu window every exit. */
180 static unsigned int ple_window_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
181 module_param(ple_window_grow, uint, 0444);
183 /* Default resets per-vcpu window every exit to ple_window. */
184 static unsigned int ple_window_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
185 module_param(ple_window_shrink, uint, 0444);
187 /* Default is to compute the maximum so we can never overflow. */
188 static unsigned int ple_window_max = KVM_VMX_DEFAULT_PLE_WINDOW_MAX;
189 module_param(ple_window_max, uint, 0444);
191 extern const ulong vmx_return;
193 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_should_flush);
194 static DEFINE_STATIC_KEY_FALSE(vmx_l1d_flush_cond);
195 static DEFINE_MUTEX(vmx_l1d_flush_mutex);
197 /* Storage for pre module init parameter parsing */
198 static enum vmx_l1d_flush_state __read_mostly vmentry_l1d_flush_param = VMENTER_L1D_FLUSH_AUTO;
200 static const struct {
201 const char *option;
202 bool for_parse;
203 } vmentry_l1d_param[] = {
204 [VMENTER_L1D_FLUSH_AUTO] = {"auto", true},
205 [VMENTER_L1D_FLUSH_NEVER] = {"never", true},
206 [VMENTER_L1D_FLUSH_COND] = {"cond", true},
207 [VMENTER_L1D_FLUSH_ALWAYS] = {"always", true},
208 [VMENTER_L1D_FLUSH_EPT_DISABLED] = {"EPT disabled", false},
209 [VMENTER_L1D_FLUSH_NOT_REQUIRED] = {"not required", false},
212 #define L1D_CACHE_ORDER 4
213 static void *vmx_l1d_flush_pages;
215 static int vmx_setup_l1d_flush(enum vmx_l1d_flush_state l1tf)
217 struct page *page;
218 unsigned int i;
220 if (!enable_ept) {
221 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_EPT_DISABLED;
222 return 0;
225 if (boot_cpu_has(X86_FEATURE_ARCH_CAPABILITIES)) {
226 u64 msr;
228 rdmsrl(MSR_IA32_ARCH_CAPABILITIES, msr);
229 if (msr & ARCH_CAP_SKIP_VMENTRY_L1DFLUSH) {
230 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_NOT_REQUIRED;
231 return 0;
235 /* If set to auto use the default l1tf mitigation method */
236 if (l1tf == VMENTER_L1D_FLUSH_AUTO) {
237 switch (l1tf_mitigation) {
238 case L1TF_MITIGATION_OFF:
239 l1tf = VMENTER_L1D_FLUSH_NEVER;
240 break;
241 case L1TF_MITIGATION_FLUSH_NOWARN:
242 case L1TF_MITIGATION_FLUSH:
243 case L1TF_MITIGATION_FLUSH_NOSMT:
244 l1tf = VMENTER_L1D_FLUSH_COND;
245 break;
246 case L1TF_MITIGATION_FULL:
247 case L1TF_MITIGATION_FULL_FORCE:
248 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
249 break;
251 } else if (l1tf_mitigation == L1TF_MITIGATION_FULL_FORCE) {
252 l1tf = VMENTER_L1D_FLUSH_ALWAYS;
255 if (l1tf != VMENTER_L1D_FLUSH_NEVER && !vmx_l1d_flush_pages &&
256 !boot_cpu_has(X86_FEATURE_FLUSH_L1D)) {
257 page = alloc_pages(GFP_KERNEL, L1D_CACHE_ORDER);
258 if (!page)
259 return -ENOMEM;
260 vmx_l1d_flush_pages = page_address(page);
263 * Initialize each page with a different pattern in
264 * order to protect against KSM in the nested
265 * virtualization case.
267 for (i = 0; i < 1u << L1D_CACHE_ORDER; ++i) {
268 memset(vmx_l1d_flush_pages + i * PAGE_SIZE, i + 1,
269 PAGE_SIZE);
273 l1tf_vmx_mitigation = l1tf;
275 if (l1tf != VMENTER_L1D_FLUSH_NEVER)
276 static_branch_enable(&vmx_l1d_should_flush);
277 else
278 static_branch_disable(&vmx_l1d_should_flush);
280 if (l1tf == VMENTER_L1D_FLUSH_COND)
281 static_branch_enable(&vmx_l1d_flush_cond);
282 else
283 static_branch_disable(&vmx_l1d_flush_cond);
284 return 0;
287 static int vmentry_l1d_flush_parse(const char *s)
289 unsigned int i;
291 if (s) {
292 for (i = 0; i < ARRAY_SIZE(vmentry_l1d_param); i++) {
293 if (vmentry_l1d_param[i].for_parse &&
294 sysfs_streq(s, vmentry_l1d_param[i].option))
295 return i;
298 return -EINVAL;
301 static int vmentry_l1d_flush_set(const char *s, const struct kernel_param *kp)
303 int l1tf, ret;
305 l1tf = vmentry_l1d_flush_parse(s);
306 if (l1tf < 0)
307 return l1tf;
309 if (!boot_cpu_has(X86_BUG_L1TF))
310 return 0;
313 * Has vmx_init() run already? If not then this is the pre init
314 * parameter parsing. In that case just store the value and let
315 * vmx_init() do the proper setup after enable_ept has been
316 * established.
318 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_AUTO) {
319 vmentry_l1d_flush_param = l1tf;
320 return 0;
323 mutex_lock(&vmx_l1d_flush_mutex);
324 ret = vmx_setup_l1d_flush(l1tf);
325 mutex_unlock(&vmx_l1d_flush_mutex);
326 return ret;
329 static int vmentry_l1d_flush_get(char *s, const struct kernel_param *kp)
331 if (WARN_ON_ONCE(l1tf_vmx_mitigation >= ARRAY_SIZE(vmentry_l1d_param)))
332 return sprintf(s, "???\n");
334 return sprintf(s, "%s\n", vmentry_l1d_param[l1tf_vmx_mitigation].option);
337 static const struct kernel_param_ops vmentry_l1d_flush_ops = {
338 .set = vmentry_l1d_flush_set,
339 .get = vmentry_l1d_flush_get,
341 module_param_cb(vmentry_l1d_flush, &vmentry_l1d_flush_ops, NULL, 0644);
343 enum ept_pointers_status {
344 EPT_POINTERS_CHECK = 0,
345 EPT_POINTERS_MATCH = 1,
346 EPT_POINTERS_MISMATCH = 2
349 struct kvm_vmx {
350 struct kvm kvm;
352 unsigned int tss_addr;
353 bool ept_identity_pagetable_done;
354 gpa_t ept_identity_map_addr;
356 enum ept_pointers_status ept_pointers_match;
357 spinlock_t ept_pointer_lock;
360 #define NR_AUTOLOAD_MSRS 8
362 struct vmcs_hdr {
363 u32 revision_id:31;
364 u32 shadow_vmcs:1;
367 struct vmcs {
368 struct vmcs_hdr hdr;
369 u32 abort;
370 char data[0];
374 * vmcs_host_state tracks registers that are loaded from the VMCS on VMEXIT
375 * and whose values change infrequently, but are not constant. I.e. this is
376 * used as a write-through cache of the corresponding VMCS fields.
378 struct vmcs_host_state {
379 unsigned long cr3; /* May not match real cr3 */
380 unsigned long cr4; /* May not match real cr4 */
381 unsigned long gs_base;
382 unsigned long fs_base;
384 u16 fs_sel, gs_sel, ldt_sel;
385 #ifdef CONFIG_X86_64
386 u16 ds_sel, es_sel;
387 #endif
391 * Track a VMCS that may be loaded on a certain CPU. If it is (cpu!=-1), also
392 * remember whether it was VMLAUNCHed, and maintain a linked list of all VMCSs
393 * loaded on this CPU (so we can clear them if the CPU goes down).
395 struct loaded_vmcs {
396 struct vmcs *vmcs;
397 struct vmcs *shadow_vmcs;
398 int cpu;
399 bool launched;
400 bool nmi_known_unmasked;
401 bool hv_timer_armed;
402 /* Support for vnmi-less CPUs */
403 int soft_vnmi_blocked;
404 ktime_t entry_time;
405 s64 vnmi_blocked_time;
406 unsigned long *msr_bitmap;
407 struct list_head loaded_vmcss_on_cpu_link;
408 struct vmcs_host_state host_state;
411 struct shared_msr_entry {
412 unsigned index;
413 u64 data;
414 u64 mask;
418 * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
419 * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
420 * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
421 * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
422 * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
423 * More than one of these structures may exist, if L1 runs multiple L2 guests.
424 * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
425 * underlying hardware which will be used to run L2.
426 * This structure is packed to ensure that its layout is identical across
427 * machines (necessary for live migration).
429 * IMPORTANT: Changing the layout of existing fields in this structure
430 * will break save/restore compatibility with older kvm releases. When
431 * adding new fields, either use space in the reserved padding* arrays
432 * or add the new fields to the end of the structure.
434 typedef u64 natural_width;
435 struct __packed vmcs12 {
436 /* According to the Intel spec, a VMCS region must start with the
437 * following two fields. Then follow implementation-specific data.
439 struct vmcs_hdr hdr;
440 u32 abort;
442 u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
443 u32 padding[7]; /* room for future expansion */
445 u64 io_bitmap_a;
446 u64 io_bitmap_b;
447 u64 msr_bitmap;
448 u64 vm_exit_msr_store_addr;
449 u64 vm_exit_msr_load_addr;
450 u64 vm_entry_msr_load_addr;
451 u64 tsc_offset;
452 u64 virtual_apic_page_addr;
453 u64 apic_access_addr;
454 u64 posted_intr_desc_addr;
455 u64 ept_pointer;
456 u64 eoi_exit_bitmap0;
457 u64 eoi_exit_bitmap1;
458 u64 eoi_exit_bitmap2;
459 u64 eoi_exit_bitmap3;
460 u64 xss_exit_bitmap;
461 u64 guest_physical_address;
462 u64 vmcs_link_pointer;
463 u64 guest_ia32_debugctl;
464 u64 guest_ia32_pat;
465 u64 guest_ia32_efer;
466 u64 guest_ia32_perf_global_ctrl;
467 u64 guest_pdptr0;
468 u64 guest_pdptr1;
469 u64 guest_pdptr2;
470 u64 guest_pdptr3;
471 u64 guest_bndcfgs;
472 u64 host_ia32_pat;
473 u64 host_ia32_efer;
474 u64 host_ia32_perf_global_ctrl;
475 u64 vmread_bitmap;
476 u64 vmwrite_bitmap;
477 u64 vm_function_control;
478 u64 eptp_list_address;
479 u64 pml_address;
480 u64 padding64[3]; /* room for future expansion */
482 * To allow migration of L1 (complete with its L2 guests) between
483 * machines of different natural widths (32 or 64 bit), we cannot have
484 * unsigned long fields with no explict size. We use u64 (aliased
485 * natural_width) instead. Luckily, x86 is little-endian.
487 natural_width cr0_guest_host_mask;
488 natural_width cr4_guest_host_mask;
489 natural_width cr0_read_shadow;
490 natural_width cr4_read_shadow;
491 natural_width cr3_target_value0;
492 natural_width cr3_target_value1;
493 natural_width cr3_target_value2;
494 natural_width cr3_target_value3;
495 natural_width exit_qualification;
496 natural_width guest_linear_address;
497 natural_width guest_cr0;
498 natural_width guest_cr3;
499 natural_width guest_cr4;
500 natural_width guest_es_base;
501 natural_width guest_cs_base;
502 natural_width guest_ss_base;
503 natural_width guest_ds_base;
504 natural_width guest_fs_base;
505 natural_width guest_gs_base;
506 natural_width guest_ldtr_base;
507 natural_width guest_tr_base;
508 natural_width guest_gdtr_base;
509 natural_width guest_idtr_base;
510 natural_width guest_dr7;
511 natural_width guest_rsp;
512 natural_width guest_rip;
513 natural_width guest_rflags;
514 natural_width guest_pending_dbg_exceptions;
515 natural_width guest_sysenter_esp;
516 natural_width guest_sysenter_eip;
517 natural_width host_cr0;
518 natural_width host_cr3;
519 natural_width host_cr4;
520 natural_width host_fs_base;
521 natural_width host_gs_base;
522 natural_width host_tr_base;
523 natural_width host_gdtr_base;
524 natural_width host_idtr_base;
525 natural_width host_ia32_sysenter_esp;
526 natural_width host_ia32_sysenter_eip;
527 natural_width host_rsp;
528 natural_width host_rip;
529 natural_width paddingl[8]; /* room for future expansion */
530 u32 pin_based_vm_exec_control;
531 u32 cpu_based_vm_exec_control;
532 u32 exception_bitmap;
533 u32 page_fault_error_code_mask;
534 u32 page_fault_error_code_match;
535 u32 cr3_target_count;
536 u32 vm_exit_controls;
537 u32 vm_exit_msr_store_count;
538 u32 vm_exit_msr_load_count;
539 u32 vm_entry_controls;
540 u32 vm_entry_msr_load_count;
541 u32 vm_entry_intr_info_field;
542 u32 vm_entry_exception_error_code;
543 u32 vm_entry_instruction_len;
544 u32 tpr_threshold;
545 u32 secondary_vm_exec_control;
546 u32 vm_instruction_error;
547 u32 vm_exit_reason;
548 u32 vm_exit_intr_info;
549 u32 vm_exit_intr_error_code;
550 u32 idt_vectoring_info_field;
551 u32 idt_vectoring_error_code;
552 u32 vm_exit_instruction_len;
553 u32 vmx_instruction_info;
554 u32 guest_es_limit;
555 u32 guest_cs_limit;
556 u32 guest_ss_limit;
557 u32 guest_ds_limit;
558 u32 guest_fs_limit;
559 u32 guest_gs_limit;
560 u32 guest_ldtr_limit;
561 u32 guest_tr_limit;
562 u32 guest_gdtr_limit;
563 u32 guest_idtr_limit;
564 u32 guest_es_ar_bytes;
565 u32 guest_cs_ar_bytes;
566 u32 guest_ss_ar_bytes;
567 u32 guest_ds_ar_bytes;
568 u32 guest_fs_ar_bytes;
569 u32 guest_gs_ar_bytes;
570 u32 guest_ldtr_ar_bytes;
571 u32 guest_tr_ar_bytes;
572 u32 guest_interruptibility_info;
573 u32 guest_activity_state;
574 u32 guest_sysenter_cs;
575 u32 host_ia32_sysenter_cs;
576 u32 vmx_preemption_timer_value;
577 u32 padding32[7]; /* room for future expansion */
578 u16 virtual_processor_id;
579 u16 posted_intr_nv;
580 u16 guest_es_selector;
581 u16 guest_cs_selector;
582 u16 guest_ss_selector;
583 u16 guest_ds_selector;
584 u16 guest_fs_selector;
585 u16 guest_gs_selector;
586 u16 guest_ldtr_selector;
587 u16 guest_tr_selector;
588 u16 guest_intr_status;
589 u16 host_es_selector;
590 u16 host_cs_selector;
591 u16 host_ss_selector;
592 u16 host_ds_selector;
593 u16 host_fs_selector;
594 u16 host_gs_selector;
595 u16 host_tr_selector;
596 u16 guest_pml_index;
600 * For save/restore compatibility, the vmcs12 field offsets must not change.
602 #define CHECK_OFFSET(field, loc) \
603 BUILD_BUG_ON_MSG(offsetof(struct vmcs12, field) != (loc), \
604 "Offset of " #field " in struct vmcs12 has changed.")
606 static inline void vmx_check_vmcs12_offsets(void) {
607 CHECK_OFFSET(hdr, 0);
608 CHECK_OFFSET(abort, 4);
609 CHECK_OFFSET(launch_state, 8);
610 CHECK_OFFSET(io_bitmap_a, 40);
611 CHECK_OFFSET(io_bitmap_b, 48);
612 CHECK_OFFSET(msr_bitmap, 56);
613 CHECK_OFFSET(vm_exit_msr_store_addr, 64);
614 CHECK_OFFSET(vm_exit_msr_load_addr, 72);
615 CHECK_OFFSET(vm_entry_msr_load_addr, 80);
616 CHECK_OFFSET(tsc_offset, 88);
617 CHECK_OFFSET(virtual_apic_page_addr, 96);
618 CHECK_OFFSET(apic_access_addr, 104);
619 CHECK_OFFSET(posted_intr_desc_addr, 112);
620 CHECK_OFFSET(ept_pointer, 120);
621 CHECK_OFFSET(eoi_exit_bitmap0, 128);
622 CHECK_OFFSET(eoi_exit_bitmap1, 136);
623 CHECK_OFFSET(eoi_exit_bitmap2, 144);
624 CHECK_OFFSET(eoi_exit_bitmap3, 152);
625 CHECK_OFFSET(xss_exit_bitmap, 160);
626 CHECK_OFFSET(guest_physical_address, 168);
627 CHECK_OFFSET(vmcs_link_pointer, 176);
628 CHECK_OFFSET(guest_ia32_debugctl, 184);
629 CHECK_OFFSET(guest_ia32_pat, 192);
630 CHECK_OFFSET(guest_ia32_efer, 200);
631 CHECK_OFFSET(guest_ia32_perf_global_ctrl, 208);
632 CHECK_OFFSET(guest_pdptr0, 216);
633 CHECK_OFFSET(guest_pdptr1, 224);
634 CHECK_OFFSET(guest_pdptr2, 232);
635 CHECK_OFFSET(guest_pdptr3, 240);
636 CHECK_OFFSET(guest_bndcfgs, 248);
637 CHECK_OFFSET(host_ia32_pat, 256);
638 CHECK_OFFSET(host_ia32_efer, 264);
639 CHECK_OFFSET(host_ia32_perf_global_ctrl, 272);
640 CHECK_OFFSET(vmread_bitmap, 280);
641 CHECK_OFFSET(vmwrite_bitmap, 288);
642 CHECK_OFFSET(vm_function_control, 296);
643 CHECK_OFFSET(eptp_list_address, 304);
644 CHECK_OFFSET(pml_address, 312);
645 CHECK_OFFSET(cr0_guest_host_mask, 344);
646 CHECK_OFFSET(cr4_guest_host_mask, 352);
647 CHECK_OFFSET(cr0_read_shadow, 360);
648 CHECK_OFFSET(cr4_read_shadow, 368);
649 CHECK_OFFSET(cr3_target_value0, 376);
650 CHECK_OFFSET(cr3_target_value1, 384);
651 CHECK_OFFSET(cr3_target_value2, 392);
652 CHECK_OFFSET(cr3_target_value3, 400);
653 CHECK_OFFSET(exit_qualification, 408);
654 CHECK_OFFSET(guest_linear_address, 416);
655 CHECK_OFFSET(guest_cr0, 424);
656 CHECK_OFFSET(guest_cr3, 432);
657 CHECK_OFFSET(guest_cr4, 440);
658 CHECK_OFFSET(guest_es_base, 448);
659 CHECK_OFFSET(guest_cs_base, 456);
660 CHECK_OFFSET(guest_ss_base, 464);
661 CHECK_OFFSET(guest_ds_base, 472);
662 CHECK_OFFSET(guest_fs_base, 480);
663 CHECK_OFFSET(guest_gs_base, 488);
664 CHECK_OFFSET(guest_ldtr_base, 496);
665 CHECK_OFFSET(guest_tr_base, 504);
666 CHECK_OFFSET(guest_gdtr_base, 512);
667 CHECK_OFFSET(guest_idtr_base, 520);
668 CHECK_OFFSET(guest_dr7, 528);
669 CHECK_OFFSET(guest_rsp, 536);
670 CHECK_OFFSET(guest_rip, 544);
671 CHECK_OFFSET(guest_rflags, 552);
672 CHECK_OFFSET(guest_pending_dbg_exceptions, 560);
673 CHECK_OFFSET(guest_sysenter_esp, 568);
674 CHECK_OFFSET(guest_sysenter_eip, 576);
675 CHECK_OFFSET(host_cr0, 584);
676 CHECK_OFFSET(host_cr3, 592);
677 CHECK_OFFSET(host_cr4, 600);
678 CHECK_OFFSET(host_fs_base, 608);
679 CHECK_OFFSET(host_gs_base, 616);
680 CHECK_OFFSET(host_tr_base, 624);
681 CHECK_OFFSET(host_gdtr_base, 632);
682 CHECK_OFFSET(host_idtr_base, 640);
683 CHECK_OFFSET(host_ia32_sysenter_esp, 648);
684 CHECK_OFFSET(host_ia32_sysenter_eip, 656);
685 CHECK_OFFSET(host_rsp, 664);
686 CHECK_OFFSET(host_rip, 672);
687 CHECK_OFFSET(pin_based_vm_exec_control, 744);
688 CHECK_OFFSET(cpu_based_vm_exec_control, 748);
689 CHECK_OFFSET(exception_bitmap, 752);
690 CHECK_OFFSET(page_fault_error_code_mask, 756);
691 CHECK_OFFSET(page_fault_error_code_match, 760);
692 CHECK_OFFSET(cr3_target_count, 764);
693 CHECK_OFFSET(vm_exit_controls, 768);
694 CHECK_OFFSET(vm_exit_msr_store_count, 772);
695 CHECK_OFFSET(vm_exit_msr_load_count, 776);
696 CHECK_OFFSET(vm_entry_controls, 780);
697 CHECK_OFFSET(vm_entry_msr_load_count, 784);
698 CHECK_OFFSET(vm_entry_intr_info_field, 788);
699 CHECK_OFFSET(vm_entry_exception_error_code, 792);
700 CHECK_OFFSET(vm_entry_instruction_len, 796);
701 CHECK_OFFSET(tpr_threshold, 800);
702 CHECK_OFFSET(secondary_vm_exec_control, 804);
703 CHECK_OFFSET(vm_instruction_error, 808);
704 CHECK_OFFSET(vm_exit_reason, 812);
705 CHECK_OFFSET(vm_exit_intr_info, 816);
706 CHECK_OFFSET(vm_exit_intr_error_code, 820);
707 CHECK_OFFSET(idt_vectoring_info_field, 824);
708 CHECK_OFFSET(idt_vectoring_error_code, 828);
709 CHECK_OFFSET(vm_exit_instruction_len, 832);
710 CHECK_OFFSET(vmx_instruction_info, 836);
711 CHECK_OFFSET(guest_es_limit, 840);
712 CHECK_OFFSET(guest_cs_limit, 844);
713 CHECK_OFFSET(guest_ss_limit, 848);
714 CHECK_OFFSET(guest_ds_limit, 852);
715 CHECK_OFFSET(guest_fs_limit, 856);
716 CHECK_OFFSET(guest_gs_limit, 860);
717 CHECK_OFFSET(guest_ldtr_limit, 864);
718 CHECK_OFFSET(guest_tr_limit, 868);
719 CHECK_OFFSET(guest_gdtr_limit, 872);
720 CHECK_OFFSET(guest_idtr_limit, 876);
721 CHECK_OFFSET(guest_es_ar_bytes, 880);
722 CHECK_OFFSET(guest_cs_ar_bytes, 884);
723 CHECK_OFFSET(guest_ss_ar_bytes, 888);
724 CHECK_OFFSET(guest_ds_ar_bytes, 892);
725 CHECK_OFFSET(guest_fs_ar_bytes, 896);
726 CHECK_OFFSET(guest_gs_ar_bytes, 900);
727 CHECK_OFFSET(guest_ldtr_ar_bytes, 904);
728 CHECK_OFFSET(guest_tr_ar_bytes, 908);
729 CHECK_OFFSET(guest_interruptibility_info, 912);
730 CHECK_OFFSET(guest_activity_state, 916);
731 CHECK_OFFSET(guest_sysenter_cs, 920);
732 CHECK_OFFSET(host_ia32_sysenter_cs, 924);
733 CHECK_OFFSET(vmx_preemption_timer_value, 928);
734 CHECK_OFFSET(virtual_processor_id, 960);
735 CHECK_OFFSET(posted_intr_nv, 962);
736 CHECK_OFFSET(guest_es_selector, 964);
737 CHECK_OFFSET(guest_cs_selector, 966);
738 CHECK_OFFSET(guest_ss_selector, 968);
739 CHECK_OFFSET(guest_ds_selector, 970);
740 CHECK_OFFSET(guest_fs_selector, 972);
741 CHECK_OFFSET(guest_gs_selector, 974);
742 CHECK_OFFSET(guest_ldtr_selector, 976);
743 CHECK_OFFSET(guest_tr_selector, 978);
744 CHECK_OFFSET(guest_intr_status, 980);
745 CHECK_OFFSET(host_es_selector, 982);
746 CHECK_OFFSET(host_cs_selector, 984);
747 CHECK_OFFSET(host_ss_selector, 986);
748 CHECK_OFFSET(host_ds_selector, 988);
749 CHECK_OFFSET(host_fs_selector, 990);
750 CHECK_OFFSET(host_gs_selector, 992);
751 CHECK_OFFSET(host_tr_selector, 994);
752 CHECK_OFFSET(guest_pml_index, 996);
756 * VMCS12_REVISION is an arbitrary id that should be changed if the content or
757 * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
758 * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
760 * IMPORTANT: Changing this value will break save/restore compatibility with
761 * older kvm releases.
763 #define VMCS12_REVISION 0x11e57ed0
766 * VMCS12_SIZE is the number of bytes L1 should allocate for the VMXON region
767 * and any VMCS region. Although only sizeof(struct vmcs12) are used by the
768 * current implementation, 4K are reserved to avoid future complications.
770 #define VMCS12_SIZE 0x1000
773 * VMCS12_MAX_FIELD_INDEX is the highest index value used in any
774 * supported VMCS12 field encoding.
776 #define VMCS12_MAX_FIELD_INDEX 0x17
778 struct nested_vmx_msrs {
780 * We only store the "true" versions of the VMX capability MSRs. We
781 * generate the "non-true" versions by setting the must-be-1 bits
782 * according to the SDM.
784 u32 procbased_ctls_low;
785 u32 procbased_ctls_high;
786 u32 secondary_ctls_low;
787 u32 secondary_ctls_high;
788 u32 pinbased_ctls_low;
789 u32 pinbased_ctls_high;
790 u32 exit_ctls_low;
791 u32 exit_ctls_high;
792 u32 entry_ctls_low;
793 u32 entry_ctls_high;
794 u32 misc_low;
795 u32 misc_high;
796 u32 ept_caps;
797 u32 vpid_caps;
798 u64 basic;
799 u64 cr0_fixed0;
800 u64 cr0_fixed1;
801 u64 cr4_fixed0;
802 u64 cr4_fixed1;
803 u64 vmcs_enum;
804 u64 vmfunc_controls;
808 * The nested_vmx structure is part of vcpu_vmx, and holds information we need
809 * for correct emulation of VMX (i.e., nested VMX) on this vcpu.
811 struct nested_vmx {
812 /* Has the level1 guest done vmxon? */
813 bool vmxon;
814 gpa_t vmxon_ptr;
815 bool pml_full;
817 /* The guest-physical address of the current VMCS L1 keeps for L2 */
818 gpa_t current_vmptr;
820 * Cache of the guest's VMCS, existing outside of guest memory.
821 * Loaded from guest memory during VMPTRLD. Flushed to guest
822 * memory during VMCLEAR and VMPTRLD.
824 struct vmcs12 *cached_vmcs12;
826 * Cache of the guest's shadow VMCS, existing outside of guest
827 * memory. Loaded from guest memory during VM entry. Flushed
828 * to guest memory during VM exit.
830 struct vmcs12 *cached_shadow_vmcs12;
832 * Indicates if the shadow vmcs must be updated with the
833 * data hold by vmcs12
835 bool sync_shadow_vmcs;
836 bool dirty_vmcs12;
838 bool change_vmcs01_virtual_apic_mode;
840 /* L2 must run next, and mustn't decide to exit to L1. */
841 bool nested_run_pending;
843 struct loaded_vmcs vmcs02;
846 * Guest pages referred to in the vmcs02 with host-physical
847 * pointers, so we must keep them pinned while L2 runs.
849 struct page *apic_access_page;
850 struct page *virtual_apic_page;
851 struct page *pi_desc_page;
852 struct pi_desc *pi_desc;
853 bool pi_pending;
854 u16 posted_intr_nv;
856 struct hrtimer preemption_timer;
857 bool preemption_timer_expired;
859 /* to migrate it to L2 if VM_ENTRY_LOAD_DEBUG_CONTROLS is off */
860 u64 vmcs01_debugctl;
861 u64 vmcs01_guest_bndcfgs;
863 u16 vpid02;
864 u16 last_vpid;
866 struct nested_vmx_msrs msrs;
868 /* SMM related state */
869 struct {
870 /* in VMX operation on SMM entry? */
871 bool vmxon;
872 /* in guest mode on SMM entry? */
873 bool guest_mode;
874 } smm;
877 #define POSTED_INTR_ON 0
878 #define POSTED_INTR_SN 1
880 /* Posted-Interrupt Descriptor */
881 struct pi_desc {
882 u32 pir[8]; /* Posted interrupt requested */
883 union {
884 struct {
885 /* bit 256 - Outstanding Notification */
886 u16 on : 1,
887 /* bit 257 - Suppress Notification */
888 sn : 1,
889 /* bit 271:258 - Reserved */
890 rsvd_1 : 14;
891 /* bit 279:272 - Notification Vector */
892 u8 nv;
893 /* bit 287:280 - Reserved */
894 u8 rsvd_2;
895 /* bit 319:288 - Notification Destination */
896 u32 ndst;
898 u64 control;
900 u32 rsvd[6];
901 } __aligned(64);
903 static bool pi_test_and_set_on(struct pi_desc *pi_desc)
905 return test_and_set_bit(POSTED_INTR_ON,
906 (unsigned long *)&pi_desc->control);
909 static bool pi_test_and_clear_on(struct pi_desc *pi_desc)
911 return test_and_clear_bit(POSTED_INTR_ON,
912 (unsigned long *)&pi_desc->control);
915 static int pi_test_and_set_pir(int vector, struct pi_desc *pi_desc)
917 return test_and_set_bit(vector, (unsigned long *)pi_desc->pir);
920 static inline void pi_clear_sn(struct pi_desc *pi_desc)
922 return clear_bit(POSTED_INTR_SN,
923 (unsigned long *)&pi_desc->control);
926 static inline void pi_set_sn(struct pi_desc *pi_desc)
928 return set_bit(POSTED_INTR_SN,
929 (unsigned long *)&pi_desc->control);
932 static inline void pi_clear_on(struct pi_desc *pi_desc)
934 clear_bit(POSTED_INTR_ON,
935 (unsigned long *)&pi_desc->control);
938 static inline int pi_test_on(struct pi_desc *pi_desc)
940 return test_bit(POSTED_INTR_ON,
941 (unsigned long *)&pi_desc->control);
944 static inline int pi_test_sn(struct pi_desc *pi_desc)
946 return test_bit(POSTED_INTR_SN,
947 (unsigned long *)&pi_desc->control);
950 struct vmx_msrs {
951 unsigned int nr;
952 struct vmx_msr_entry val[NR_AUTOLOAD_MSRS];
955 struct vcpu_vmx {
956 struct kvm_vcpu vcpu;
957 unsigned long host_rsp;
958 u8 fail;
959 u8 msr_bitmap_mode;
960 u32 exit_intr_info;
961 u32 idt_vectoring_info;
962 ulong rflags;
963 struct shared_msr_entry *guest_msrs;
964 int nmsrs;
965 int save_nmsrs;
966 bool guest_msrs_dirty;
967 unsigned long host_idt_base;
968 #ifdef CONFIG_X86_64
969 u64 msr_host_kernel_gs_base;
970 u64 msr_guest_kernel_gs_base;
971 #endif
973 u64 spec_ctrl;
975 u32 vm_entry_controls_shadow;
976 u32 vm_exit_controls_shadow;
977 u32 secondary_exec_control;
980 * loaded_vmcs points to the VMCS currently used in this vcpu. For a
981 * non-nested (L1) guest, it always points to vmcs01. For a nested
982 * guest (L2), it points to a different VMCS. loaded_cpu_state points
983 * to the VMCS whose state is loaded into the CPU registers that only
984 * need to be switched when transitioning to/from the kernel; a NULL
985 * value indicates that host state is loaded.
987 struct loaded_vmcs vmcs01;
988 struct loaded_vmcs *loaded_vmcs;
989 struct loaded_vmcs *loaded_cpu_state;
990 bool __launched; /* temporary, used in vmx_vcpu_run */
991 struct msr_autoload {
992 struct vmx_msrs guest;
993 struct vmx_msrs host;
994 } msr_autoload;
996 struct {
997 int vm86_active;
998 ulong save_rflags;
999 struct kvm_segment segs[8];
1000 } rmode;
1001 struct {
1002 u32 bitmask; /* 4 bits per segment (1 bit per field) */
1003 struct kvm_save_segment {
1004 u16 selector;
1005 unsigned long base;
1006 u32 limit;
1007 u32 ar;
1008 } seg[8];
1009 } segment_cache;
1010 int vpid;
1011 bool emulation_required;
1013 u32 exit_reason;
1015 /* Posted interrupt descriptor */
1016 struct pi_desc pi_desc;
1018 /* Support for a guest hypervisor (nested VMX) */
1019 struct nested_vmx nested;
1021 /* Dynamic PLE window. */
1022 int ple_window;
1023 bool ple_window_dirty;
1025 bool req_immediate_exit;
1027 /* Support for PML */
1028 #define PML_ENTITY_NUM 512
1029 struct page *pml_pg;
1031 /* apic deadline value in host tsc */
1032 u64 hv_deadline_tsc;
1034 u64 current_tsc_ratio;
1036 u32 host_pkru;
1038 unsigned long host_debugctlmsr;
1041 * Only bits masked by msr_ia32_feature_control_valid_bits can be set in
1042 * msr_ia32_feature_control. FEATURE_CONTROL_LOCKED is always included
1043 * in msr_ia32_feature_control_valid_bits.
1045 u64 msr_ia32_feature_control;
1046 u64 msr_ia32_feature_control_valid_bits;
1047 u64 ept_pointer;
1050 enum segment_cache_field {
1051 SEG_FIELD_SEL = 0,
1052 SEG_FIELD_BASE = 1,
1053 SEG_FIELD_LIMIT = 2,
1054 SEG_FIELD_AR = 3,
1056 SEG_FIELD_NR = 4
1059 static inline struct kvm_vmx *to_kvm_vmx(struct kvm *kvm)
1061 return container_of(kvm, struct kvm_vmx, kvm);
1064 static inline struct vcpu_vmx *to_vmx(struct kvm_vcpu *vcpu)
1066 return container_of(vcpu, struct vcpu_vmx, vcpu);
1069 static struct pi_desc *vcpu_to_pi_desc(struct kvm_vcpu *vcpu)
1071 return &(to_vmx(vcpu)->pi_desc);
1074 #define ROL16(val, n) ((u16)(((u16)(val) << (n)) | ((u16)(val) >> (16 - (n)))))
1075 #define VMCS12_OFFSET(x) offsetof(struct vmcs12, x)
1076 #define FIELD(number, name) [ROL16(number, 6)] = VMCS12_OFFSET(name)
1077 #define FIELD64(number, name) \
1078 FIELD(number, name), \
1079 [ROL16(number##_HIGH, 6)] = VMCS12_OFFSET(name) + sizeof(u32)
1082 static u16 shadow_read_only_fields[] = {
1083 #define SHADOW_FIELD_RO(x) x,
1084 #include "vmx_shadow_fields.h"
1086 static int max_shadow_read_only_fields =
1087 ARRAY_SIZE(shadow_read_only_fields);
1089 static u16 shadow_read_write_fields[] = {
1090 #define SHADOW_FIELD_RW(x) x,
1091 #include "vmx_shadow_fields.h"
1093 static int max_shadow_read_write_fields =
1094 ARRAY_SIZE(shadow_read_write_fields);
1096 static const unsigned short vmcs_field_to_offset_table[] = {
1097 FIELD(VIRTUAL_PROCESSOR_ID, virtual_processor_id),
1098 FIELD(POSTED_INTR_NV, posted_intr_nv),
1099 FIELD(GUEST_ES_SELECTOR, guest_es_selector),
1100 FIELD(GUEST_CS_SELECTOR, guest_cs_selector),
1101 FIELD(GUEST_SS_SELECTOR, guest_ss_selector),
1102 FIELD(GUEST_DS_SELECTOR, guest_ds_selector),
1103 FIELD(GUEST_FS_SELECTOR, guest_fs_selector),
1104 FIELD(GUEST_GS_SELECTOR, guest_gs_selector),
1105 FIELD(GUEST_LDTR_SELECTOR, guest_ldtr_selector),
1106 FIELD(GUEST_TR_SELECTOR, guest_tr_selector),
1107 FIELD(GUEST_INTR_STATUS, guest_intr_status),
1108 FIELD(GUEST_PML_INDEX, guest_pml_index),
1109 FIELD(HOST_ES_SELECTOR, host_es_selector),
1110 FIELD(HOST_CS_SELECTOR, host_cs_selector),
1111 FIELD(HOST_SS_SELECTOR, host_ss_selector),
1112 FIELD(HOST_DS_SELECTOR, host_ds_selector),
1113 FIELD(HOST_FS_SELECTOR, host_fs_selector),
1114 FIELD(HOST_GS_SELECTOR, host_gs_selector),
1115 FIELD(HOST_TR_SELECTOR, host_tr_selector),
1116 FIELD64(IO_BITMAP_A, io_bitmap_a),
1117 FIELD64(IO_BITMAP_B, io_bitmap_b),
1118 FIELD64(MSR_BITMAP, msr_bitmap),
1119 FIELD64(VM_EXIT_MSR_STORE_ADDR, vm_exit_msr_store_addr),
1120 FIELD64(VM_EXIT_MSR_LOAD_ADDR, vm_exit_msr_load_addr),
1121 FIELD64(VM_ENTRY_MSR_LOAD_ADDR, vm_entry_msr_load_addr),
1122 FIELD64(PML_ADDRESS, pml_address),
1123 FIELD64(TSC_OFFSET, tsc_offset),
1124 FIELD64(VIRTUAL_APIC_PAGE_ADDR, virtual_apic_page_addr),
1125 FIELD64(APIC_ACCESS_ADDR, apic_access_addr),
1126 FIELD64(POSTED_INTR_DESC_ADDR, posted_intr_desc_addr),
1127 FIELD64(VM_FUNCTION_CONTROL, vm_function_control),
1128 FIELD64(EPT_POINTER, ept_pointer),
1129 FIELD64(EOI_EXIT_BITMAP0, eoi_exit_bitmap0),
1130 FIELD64(EOI_EXIT_BITMAP1, eoi_exit_bitmap1),
1131 FIELD64(EOI_EXIT_BITMAP2, eoi_exit_bitmap2),
1132 FIELD64(EOI_EXIT_BITMAP3, eoi_exit_bitmap3),
1133 FIELD64(EPTP_LIST_ADDRESS, eptp_list_address),
1134 FIELD64(VMREAD_BITMAP, vmread_bitmap),
1135 FIELD64(VMWRITE_BITMAP, vmwrite_bitmap),
1136 FIELD64(XSS_EXIT_BITMAP, xss_exit_bitmap),
1137 FIELD64(GUEST_PHYSICAL_ADDRESS, guest_physical_address),
1138 FIELD64(VMCS_LINK_POINTER, vmcs_link_pointer),
1139 FIELD64(GUEST_IA32_DEBUGCTL, guest_ia32_debugctl),
1140 FIELD64(GUEST_IA32_PAT, guest_ia32_pat),
1141 FIELD64(GUEST_IA32_EFER, guest_ia32_efer),
1142 FIELD64(GUEST_IA32_PERF_GLOBAL_CTRL, guest_ia32_perf_global_ctrl),
1143 FIELD64(GUEST_PDPTR0, guest_pdptr0),
1144 FIELD64(GUEST_PDPTR1, guest_pdptr1),
1145 FIELD64(GUEST_PDPTR2, guest_pdptr2),
1146 FIELD64(GUEST_PDPTR3, guest_pdptr3),
1147 FIELD64(GUEST_BNDCFGS, guest_bndcfgs),
1148 FIELD64(HOST_IA32_PAT, host_ia32_pat),
1149 FIELD64(HOST_IA32_EFER, host_ia32_efer),
1150 FIELD64(HOST_IA32_PERF_GLOBAL_CTRL, host_ia32_perf_global_ctrl),
1151 FIELD(PIN_BASED_VM_EXEC_CONTROL, pin_based_vm_exec_control),
1152 FIELD(CPU_BASED_VM_EXEC_CONTROL, cpu_based_vm_exec_control),
1153 FIELD(EXCEPTION_BITMAP, exception_bitmap),
1154 FIELD(PAGE_FAULT_ERROR_CODE_MASK, page_fault_error_code_mask),
1155 FIELD(PAGE_FAULT_ERROR_CODE_MATCH, page_fault_error_code_match),
1156 FIELD(CR3_TARGET_COUNT, cr3_target_count),
1157 FIELD(VM_EXIT_CONTROLS, vm_exit_controls),
1158 FIELD(VM_EXIT_MSR_STORE_COUNT, vm_exit_msr_store_count),
1159 FIELD(VM_EXIT_MSR_LOAD_COUNT, vm_exit_msr_load_count),
1160 FIELD(VM_ENTRY_CONTROLS, vm_entry_controls),
1161 FIELD(VM_ENTRY_MSR_LOAD_COUNT, vm_entry_msr_load_count),
1162 FIELD(VM_ENTRY_INTR_INFO_FIELD, vm_entry_intr_info_field),
1163 FIELD(VM_ENTRY_EXCEPTION_ERROR_CODE, vm_entry_exception_error_code),
1164 FIELD(VM_ENTRY_INSTRUCTION_LEN, vm_entry_instruction_len),
1165 FIELD(TPR_THRESHOLD, tpr_threshold),
1166 FIELD(SECONDARY_VM_EXEC_CONTROL, secondary_vm_exec_control),
1167 FIELD(VM_INSTRUCTION_ERROR, vm_instruction_error),
1168 FIELD(VM_EXIT_REASON, vm_exit_reason),
1169 FIELD(VM_EXIT_INTR_INFO, vm_exit_intr_info),
1170 FIELD(VM_EXIT_INTR_ERROR_CODE, vm_exit_intr_error_code),
1171 FIELD(IDT_VECTORING_INFO_FIELD, idt_vectoring_info_field),
1172 FIELD(IDT_VECTORING_ERROR_CODE, idt_vectoring_error_code),
1173 FIELD(VM_EXIT_INSTRUCTION_LEN, vm_exit_instruction_len),
1174 FIELD(VMX_INSTRUCTION_INFO, vmx_instruction_info),
1175 FIELD(GUEST_ES_LIMIT, guest_es_limit),
1176 FIELD(GUEST_CS_LIMIT, guest_cs_limit),
1177 FIELD(GUEST_SS_LIMIT, guest_ss_limit),
1178 FIELD(GUEST_DS_LIMIT, guest_ds_limit),
1179 FIELD(GUEST_FS_LIMIT, guest_fs_limit),
1180 FIELD(GUEST_GS_LIMIT, guest_gs_limit),
1181 FIELD(GUEST_LDTR_LIMIT, guest_ldtr_limit),
1182 FIELD(GUEST_TR_LIMIT, guest_tr_limit),
1183 FIELD(GUEST_GDTR_LIMIT, guest_gdtr_limit),
1184 FIELD(GUEST_IDTR_LIMIT, guest_idtr_limit),
1185 FIELD(GUEST_ES_AR_BYTES, guest_es_ar_bytes),
1186 FIELD(GUEST_CS_AR_BYTES, guest_cs_ar_bytes),
1187 FIELD(GUEST_SS_AR_BYTES, guest_ss_ar_bytes),
1188 FIELD(GUEST_DS_AR_BYTES, guest_ds_ar_bytes),
1189 FIELD(GUEST_FS_AR_BYTES, guest_fs_ar_bytes),
1190 FIELD(GUEST_GS_AR_BYTES, guest_gs_ar_bytes),
1191 FIELD(GUEST_LDTR_AR_BYTES, guest_ldtr_ar_bytes),
1192 FIELD(GUEST_TR_AR_BYTES, guest_tr_ar_bytes),
1193 FIELD(GUEST_INTERRUPTIBILITY_INFO, guest_interruptibility_info),
1194 FIELD(GUEST_ACTIVITY_STATE, guest_activity_state),
1195 FIELD(GUEST_SYSENTER_CS, guest_sysenter_cs),
1196 FIELD(HOST_IA32_SYSENTER_CS, host_ia32_sysenter_cs),
1197 FIELD(VMX_PREEMPTION_TIMER_VALUE, vmx_preemption_timer_value),
1198 FIELD(CR0_GUEST_HOST_MASK, cr0_guest_host_mask),
1199 FIELD(CR4_GUEST_HOST_MASK, cr4_guest_host_mask),
1200 FIELD(CR0_READ_SHADOW, cr0_read_shadow),
1201 FIELD(CR4_READ_SHADOW, cr4_read_shadow),
1202 FIELD(CR3_TARGET_VALUE0, cr3_target_value0),
1203 FIELD(CR3_TARGET_VALUE1, cr3_target_value1),
1204 FIELD(CR3_TARGET_VALUE2, cr3_target_value2),
1205 FIELD(CR3_TARGET_VALUE3, cr3_target_value3),
1206 FIELD(EXIT_QUALIFICATION, exit_qualification),
1207 FIELD(GUEST_LINEAR_ADDRESS, guest_linear_address),
1208 FIELD(GUEST_CR0, guest_cr0),
1209 FIELD(GUEST_CR3, guest_cr3),
1210 FIELD(GUEST_CR4, guest_cr4),
1211 FIELD(GUEST_ES_BASE, guest_es_base),
1212 FIELD(GUEST_CS_BASE, guest_cs_base),
1213 FIELD(GUEST_SS_BASE, guest_ss_base),
1214 FIELD(GUEST_DS_BASE, guest_ds_base),
1215 FIELD(GUEST_FS_BASE, guest_fs_base),
1216 FIELD(GUEST_GS_BASE, guest_gs_base),
1217 FIELD(GUEST_LDTR_BASE, guest_ldtr_base),
1218 FIELD(GUEST_TR_BASE, guest_tr_base),
1219 FIELD(GUEST_GDTR_BASE, guest_gdtr_base),
1220 FIELD(GUEST_IDTR_BASE, guest_idtr_base),
1221 FIELD(GUEST_DR7, guest_dr7),
1222 FIELD(GUEST_RSP, guest_rsp),
1223 FIELD(GUEST_RIP, guest_rip),
1224 FIELD(GUEST_RFLAGS, guest_rflags),
1225 FIELD(GUEST_PENDING_DBG_EXCEPTIONS, guest_pending_dbg_exceptions),
1226 FIELD(GUEST_SYSENTER_ESP, guest_sysenter_esp),
1227 FIELD(GUEST_SYSENTER_EIP, guest_sysenter_eip),
1228 FIELD(HOST_CR0, host_cr0),
1229 FIELD(HOST_CR3, host_cr3),
1230 FIELD(HOST_CR4, host_cr4),
1231 FIELD(HOST_FS_BASE, host_fs_base),
1232 FIELD(HOST_GS_BASE, host_gs_base),
1233 FIELD(HOST_TR_BASE, host_tr_base),
1234 FIELD(HOST_GDTR_BASE, host_gdtr_base),
1235 FIELD(HOST_IDTR_BASE, host_idtr_base),
1236 FIELD(HOST_IA32_SYSENTER_ESP, host_ia32_sysenter_esp),
1237 FIELD(HOST_IA32_SYSENTER_EIP, host_ia32_sysenter_eip),
1238 FIELD(HOST_RSP, host_rsp),
1239 FIELD(HOST_RIP, host_rip),
1242 static inline short vmcs_field_to_offset(unsigned long field)
1244 const size_t size = ARRAY_SIZE(vmcs_field_to_offset_table);
1245 unsigned short offset;
1246 unsigned index;
1248 if (field >> 15)
1249 return -ENOENT;
1251 index = ROL16(field, 6);
1252 if (index >= size)
1253 return -ENOENT;
1255 index = array_index_nospec(index, size);
1256 offset = vmcs_field_to_offset_table[index];
1257 if (offset == 0)
1258 return -ENOENT;
1259 return offset;
1262 static inline struct vmcs12 *get_vmcs12(struct kvm_vcpu *vcpu)
1264 return to_vmx(vcpu)->nested.cached_vmcs12;
1267 static inline struct vmcs12 *get_shadow_vmcs12(struct kvm_vcpu *vcpu)
1269 return to_vmx(vcpu)->nested.cached_shadow_vmcs12;
1272 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu);
1273 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu);
1274 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa);
1275 static bool vmx_xsaves_supported(void);
1276 static void vmx_set_segment(struct kvm_vcpu *vcpu,
1277 struct kvm_segment *var, int seg);
1278 static void vmx_get_segment(struct kvm_vcpu *vcpu,
1279 struct kvm_segment *var, int seg);
1280 static bool guest_state_valid(struct kvm_vcpu *vcpu);
1281 static u32 vmx_segment_access_rights(struct kvm_segment *var);
1282 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx);
1283 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu);
1284 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked);
1285 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
1286 u16 error_code);
1287 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu);
1288 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
1289 u32 msr, int type);
1291 static DEFINE_PER_CPU(struct vmcs *, vmxarea);
1292 static DEFINE_PER_CPU(struct vmcs *, current_vmcs);
1294 * We maintain a per-CPU linked-list of VMCS loaded on that CPU. This is needed
1295 * when a CPU is brought down, and we need to VMCLEAR all VMCSs loaded on it.
1297 static DEFINE_PER_CPU(struct list_head, loaded_vmcss_on_cpu);
1300 * We maintian a per-CPU linked-list of vCPU, so in wakeup_handler() we
1301 * can find which vCPU should be waken up.
1303 static DEFINE_PER_CPU(struct list_head, blocked_vcpu_on_cpu);
1304 static DEFINE_PER_CPU(spinlock_t, blocked_vcpu_on_cpu_lock);
1306 enum {
1307 VMX_VMREAD_BITMAP,
1308 VMX_VMWRITE_BITMAP,
1309 VMX_BITMAP_NR
1312 static unsigned long *vmx_bitmap[VMX_BITMAP_NR];
1314 #define vmx_vmread_bitmap (vmx_bitmap[VMX_VMREAD_BITMAP])
1315 #define vmx_vmwrite_bitmap (vmx_bitmap[VMX_VMWRITE_BITMAP])
1317 static bool cpu_has_load_ia32_efer;
1318 static bool cpu_has_load_perf_global_ctrl;
1320 static DECLARE_BITMAP(vmx_vpid_bitmap, VMX_NR_VPIDS);
1321 static DEFINE_SPINLOCK(vmx_vpid_lock);
1323 static struct vmcs_config {
1324 int size;
1325 int order;
1326 u32 basic_cap;
1327 u32 revision_id;
1328 u32 pin_based_exec_ctrl;
1329 u32 cpu_based_exec_ctrl;
1330 u32 cpu_based_2nd_exec_ctrl;
1331 u32 vmexit_ctrl;
1332 u32 vmentry_ctrl;
1333 struct nested_vmx_msrs nested;
1334 } vmcs_config;
1336 static struct vmx_capability {
1337 u32 ept;
1338 u32 vpid;
1339 } vmx_capability;
1341 #define VMX_SEGMENT_FIELD(seg) \
1342 [VCPU_SREG_##seg] = { \
1343 .selector = GUEST_##seg##_SELECTOR, \
1344 .base = GUEST_##seg##_BASE, \
1345 .limit = GUEST_##seg##_LIMIT, \
1346 .ar_bytes = GUEST_##seg##_AR_BYTES, \
1349 static const struct kvm_vmx_segment_field {
1350 unsigned selector;
1351 unsigned base;
1352 unsigned limit;
1353 unsigned ar_bytes;
1354 } kvm_vmx_segment_fields[] = {
1355 VMX_SEGMENT_FIELD(CS),
1356 VMX_SEGMENT_FIELD(DS),
1357 VMX_SEGMENT_FIELD(ES),
1358 VMX_SEGMENT_FIELD(FS),
1359 VMX_SEGMENT_FIELD(GS),
1360 VMX_SEGMENT_FIELD(SS),
1361 VMX_SEGMENT_FIELD(TR),
1362 VMX_SEGMENT_FIELD(LDTR),
1365 static u64 host_efer;
1367 static void ept_save_pdptrs(struct kvm_vcpu *vcpu);
1370 * Keep MSR_STAR at the end, as setup_msrs() will try to optimize it
1371 * away by decrementing the array size.
1373 static const u32 vmx_msr_index[] = {
1374 #ifdef CONFIG_X86_64
1375 MSR_SYSCALL_MASK, MSR_LSTAR, MSR_CSTAR,
1376 #endif
1377 MSR_EFER, MSR_TSC_AUX, MSR_STAR,
1380 DEFINE_STATIC_KEY_FALSE(enable_evmcs);
1382 #define current_evmcs ((struct hv_enlightened_vmcs *)this_cpu_read(current_vmcs))
1384 #define KVM_EVMCS_VERSION 1
1386 #if IS_ENABLED(CONFIG_HYPERV)
1387 static bool __read_mostly enlightened_vmcs = true;
1388 module_param(enlightened_vmcs, bool, 0444);
1390 static inline void evmcs_write64(unsigned long field, u64 value)
1392 u16 clean_field;
1393 int offset = get_evmcs_offset(field, &clean_field);
1395 if (offset < 0)
1396 return;
1398 *(u64 *)((char *)current_evmcs + offset) = value;
1400 current_evmcs->hv_clean_fields &= ~clean_field;
1403 static inline void evmcs_write32(unsigned long field, u32 value)
1405 u16 clean_field;
1406 int offset = get_evmcs_offset(field, &clean_field);
1408 if (offset < 0)
1409 return;
1411 *(u32 *)((char *)current_evmcs + offset) = value;
1412 current_evmcs->hv_clean_fields &= ~clean_field;
1415 static inline void evmcs_write16(unsigned long field, u16 value)
1417 u16 clean_field;
1418 int offset = get_evmcs_offset(field, &clean_field);
1420 if (offset < 0)
1421 return;
1423 *(u16 *)((char *)current_evmcs + offset) = value;
1424 current_evmcs->hv_clean_fields &= ~clean_field;
1427 static inline u64 evmcs_read64(unsigned long field)
1429 int offset = get_evmcs_offset(field, NULL);
1431 if (offset < 0)
1432 return 0;
1434 return *(u64 *)((char *)current_evmcs + offset);
1437 static inline u32 evmcs_read32(unsigned long field)
1439 int offset = get_evmcs_offset(field, NULL);
1441 if (offset < 0)
1442 return 0;
1444 return *(u32 *)((char *)current_evmcs + offset);
1447 static inline u16 evmcs_read16(unsigned long field)
1449 int offset = get_evmcs_offset(field, NULL);
1451 if (offset < 0)
1452 return 0;
1454 return *(u16 *)((char *)current_evmcs + offset);
1457 static inline void evmcs_touch_msr_bitmap(void)
1459 if (unlikely(!current_evmcs))
1460 return;
1462 if (current_evmcs->hv_enlightenments_control.msr_bitmap)
1463 current_evmcs->hv_clean_fields &=
1464 ~HV_VMX_ENLIGHTENED_CLEAN_FIELD_MSR_BITMAP;
1467 static void evmcs_load(u64 phys_addr)
1469 struct hv_vp_assist_page *vp_ap =
1470 hv_get_vp_assist_page(smp_processor_id());
1472 vp_ap->current_nested_vmcs = phys_addr;
1473 vp_ap->enlighten_vmentry = 1;
1476 static void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf)
1479 * Enlightened VMCSv1 doesn't support these:
1481 * POSTED_INTR_NV = 0x00000002,
1482 * GUEST_INTR_STATUS = 0x00000810,
1483 * APIC_ACCESS_ADDR = 0x00002014,
1484 * POSTED_INTR_DESC_ADDR = 0x00002016,
1485 * EOI_EXIT_BITMAP0 = 0x0000201c,
1486 * EOI_EXIT_BITMAP1 = 0x0000201e,
1487 * EOI_EXIT_BITMAP2 = 0x00002020,
1488 * EOI_EXIT_BITMAP3 = 0x00002022,
1490 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
1491 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1492 ~SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1493 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1494 ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1495 vmcs_conf->cpu_based_2nd_exec_ctrl &=
1496 ~SECONDARY_EXEC_APIC_REGISTER_VIRT;
1499 * GUEST_PML_INDEX = 0x00000812,
1500 * PML_ADDRESS = 0x0000200e,
1502 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_PML;
1504 /* VM_FUNCTION_CONTROL = 0x00002018, */
1505 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_ENABLE_VMFUNC;
1508 * EPTP_LIST_ADDRESS = 0x00002024,
1509 * VMREAD_BITMAP = 0x00002026,
1510 * VMWRITE_BITMAP = 0x00002028,
1512 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_SHADOW_VMCS;
1515 * TSC_MULTIPLIER = 0x00002032,
1517 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_TSC_SCALING;
1520 * PLE_GAP = 0x00004020,
1521 * PLE_WINDOW = 0x00004022,
1523 vmcs_conf->cpu_based_2nd_exec_ctrl &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1526 * VMX_PREEMPTION_TIMER_VALUE = 0x0000482E,
1528 vmcs_conf->pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
1531 * GUEST_IA32_PERF_GLOBAL_CTRL = 0x00002808,
1532 * HOST_IA32_PERF_GLOBAL_CTRL = 0x00002c04,
1534 vmcs_conf->vmexit_ctrl &= ~VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL;
1535 vmcs_conf->vmentry_ctrl &= ~VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL;
1538 * Currently unsupported in KVM:
1539 * GUEST_IA32_RTIT_CTL = 0x00002814,
1543 /* check_ept_pointer() should be under protection of ept_pointer_lock. */
1544 static void check_ept_pointer_match(struct kvm *kvm)
1546 struct kvm_vcpu *vcpu;
1547 u64 tmp_eptp = INVALID_PAGE;
1548 int i;
1550 kvm_for_each_vcpu(i, vcpu, kvm) {
1551 if (!VALID_PAGE(tmp_eptp)) {
1552 tmp_eptp = to_vmx(vcpu)->ept_pointer;
1553 } else if (tmp_eptp != to_vmx(vcpu)->ept_pointer) {
1554 to_kvm_vmx(kvm)->ept_pointers_match
1555 = EPT_POINTERS_MISMATCH;
1556 return;
1560 to_kvm_vmx(kvm)->ept_pointers_match = EPT_POINTERS_MATCH;
1563 static int vmx_hv_remote_flush_tlb(struct kvm *kvm)
1565 int ret;
1567 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1569 if (to_kvm_vmx(kvm)->ept_pointers_match == EPT_POINTERS_CHECK)
1570 check_ept_pointer_match(kvm);
1572 if (to_kvm_vmx(kvm)->ept_pointers_match != EPT_POINTERS_MATCH) {
1573 ret = -ENOTSUPP;
1574 goto out;
1578 * FLUSH_GUEST_PHYSICAL_ADDRESS_SPACE hypercall needs the address of the
1579 * base of EPT PML4 table, strip off EPT configuration information.
1581 ret = hyperv_flush_guest_mapping(
1582 to_vmx(kvm_get_vcpu(kvm, 0))->ept_pointer & PAGE_MASK);
1584 out:
1585 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
1586 return ret;
1588 #else /* !IS_ENABLED(CONFIG_HYPERV) */
1589 static inline void evmcs_write64(unsigned long field, u64 value) {}
1590 static inline void evmcs_write32(unsigned long field, u32 value) {}
1591 static inline void evmcs_write16(unsigned long field, u16 value) {}
1592 static inline u64 evmcs_read64(unsigned long field) { return 0; }
1593 static inline u32 evmcs_read32(unsigned long field) { return 0; }
1594 static inline u16 evmcs_read16(unsigned long field) { return 0; }
1595 static inline void evmcs_load(u64 phys_addr) {}
1596 static inline void evmcs_sanitize_exec_ctrls(struct vmcs_config *vmcs_conf) {}
1597 static inline void evmcs_touch_msr_bitmap(void) {}
1598 #endif /* IS_ENABLED(CONFIG_HYPERV) */
1600 static inline bool is_exception_n(u32 intr_info, u8 vector)
1602 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1603 INTR_INFO_VALID_MASK)) ==
1604 (INTR_TYPE_HARD_EXCEPTION | vector | INTR_INFO_VALID_MASK);
1607 static inline bool is_debug(u32 intr_info)
1609 return is_exception_n(intr_info, DB_VECTOR);
1612 static inline bool is_breakpoint(u32 intr_info)
1614 return is_exception_n(intr_info, BP_VECTOR);
1617 static inline bool is_page_fault(u32 intr_info)
1619 return is_exception_n(intr_info, PF_VECTOR);
1622 static inline bool is_no_device(u32 intr_info)
1624 return is_exception_n(intr_info, NM_VECTOR);
1627 static inline bool is_invalid_opcode(u32 intr_info)
1629 return is_exception_n(intr_info, UD_VECTOR);
1632 static inline bool is_gp_fault(u32 intr_info)
1634 return is_exception_n(intr_info, GP_VECTOR);
1637 static inline bool is_external_interrupt(u32 intr_info)
1639 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1640 == (INTR_TYPE_EXT_INTR | INTR_INFO_VALID_MASK);
1643 static inline bool is_machine_check(u32 intr_info)
1645 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VECTOR_MASK |
1646 INTR_INFO_VALID_MASK)) ==
1647 (INTR_TYPE_HARD_EXCEPTION | MC_VECTOR | INTR_INFO_VALID_MASK);
1650 /* Undocumented: icebp/int1 */
1651 static inline bool is_icebp(u32 intr_info)
1653 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
1654 == (INTR_TYPE_PRIV_SW_EXCEPTION | INTR_INFO_VALID_MASK);
1657 static inline bool cpu_has_vmx_msr_bitmap(void)
1659 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_USE_MSR_BITMAPS;
1662 static inline bool cpu_has_vmx_tpr_shadow(void)
1664 return vmcs_config.cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW;
1667 static inline bool cpu_need_tpr_shadow(struct kvm_vcpu *vcpu)
1669 return cpu_has_vmx_tpr_shadow() && lapic_in_kernel(vcpu);
1672 static inline bool cpu_has_secondary_exec_ctrls(void)
1674 return vmcs_config.cpu_based_exec_ctrl &
1675 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
1678 static inline bool cpu_has_vmx_virtualize_apic_accesses(void)
1680 return vmcs_config.cpu_based_2nd_exec_ctrl &
1681 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
1684 static inline bool cpu_has_vmx_virtualize_x2apic_mode(void)
1686 return vmcs_config.cpu_based_2nd_exec_ctrl &
1687 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
1690 static inline bool cpu_has_vmx_apic_register_virt(void)
1692 return vmcs_config.cpu_based_2nd_exec_ctrl &
1693 SECONDARY_EXEC_APIC_REGISTER_VIRT;
1696 static inline bool cpu_has_vmx_virtual_intr_delivery(void)
1698 return vmcs_config.cpu_based_2nd_exec_ctrl &
1699 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY;
1702 static inline bool cpu_has_vmx_encls_vmexit(void)
1704 return vmcs_config.cpu_based_2nd_exec_ctrl &
1705 SECONDARY_EXEC_ENCLS_EXITING;
1709 * Comment's format: document - errata name - stepping - processor name.
1710 * Refer from
1711 * https://www.virtualbox.org/svn/vbox/trunk/src/VBox/VMM/VMMR0/HMR0.cpp
1713 static u32 vmx_preemption_cpu_tfms[] = {
1714 /* 323344.pdf - BA86 - D0 - Xeon 7500 Series */
1715 0x000206E6,
1716 /* 323056.pdf - AAX65 - C2 - Xeon L3406 */
1717 /* 322814.pdf - AAT59 - C2 - i7-600, i5-500, i5-400 and i3-300 Mobile */
1718 /* 322911.pdf - AAU65 - C2 - i5-600, i3-500 Desktop and Pentium G6950 */
1719 0x00020652,
1720 /* 322911.pdf - AAU65 - K0 - i5-600, i3-500 Desktop and Pentium G6950 */
1721 0x00020655,
1722 /* 322373.pdf - AAO95 - B1 - Xeon 3400 Series */
1723 /* 322166.pdf - AAN92 - B1 - i7-800 and i5-700 Desktop */
1725 * 320767.pdf - AAP86 - B1 -
1726 * i7-900 Mobile Extreme, i7-800 and i7-700 Mobile
1728 0x000106E5,
1729 /* 321333.pdf - AAM126 - C0 - Xeon 3500 */
1730 0x000106A0,
1731 /* 321333.pdf - AAM126 - C1 - Xeon 3500 */
1732 0x000106A1,
1733 /* 320836.pdf - AAJ124 - C0 - i7-900 Desktop Extreme and i7-900 Desktop */
1734 0x000106A4,
1735 /* 321333.pdf - AAM126 - D0 - Xeon 3500 */
1736 /* 321324.pdf - AAK139 - D0 - Xeon 5500 */
1737 /* 320836.pdf - AAJ124 - D0 - i7-900 Extreme and i7-900 Desktop */
1738 0x000106A5,
1741 static inline bool cpu_has_broken_vmx_preemption_timer(void)
1743 u32 eax = cpuid_eax(0x00000001), i;
1745 /* Clear the reserved bits */
1746 eax &= ~(0x3U << 14 | 0xfU << 28);
1747 for (i = 0; i < ARRAY_SIZE(vmx_preemption_cpu_tfms); i++)
1748 if (eax == vmx_preemption_cpu_tfms[i])
1749 return true;
1751 return false;
1754 static inline bool cpu_has_vmx_preemption_timer(void)
1756 return vmcs_config.pin_based_exec_ctrl &
1757 PIN_BASED_VMX_PREEMPTION_TIMER;
1760 static inline bool cpu_has_vmx_posted_intr(void)
1762 return IS_ENABLED(CONFIG_X86_LOCAL_APIC) &&
1763 vmcs_config.pin_based_exec_ctrl & PIN_BASED_POSTED_INTR;
1766 static inline bool cpu_has_vmx_apicv(void)
1768 return cpu_has_vmx_apic_register_virt() &&
1769 cpu_has_vmx_virtual_intr_delivery() &&
1770 cpu_has_vmx_posted_intr();
1773 static inline bool cpu_has_vmx_flexpriority(void)
1775 return cpu_has_vmx_tpr_shadow() &&
1776 cpu_has_vmx_virtualize_apic_accesses();
1779 static inline bool cpu_has_vmx_ept_execute_only(void)
1781 return vmx_capability.ept & VMX_EPT_EXECUTE_ONLY_BIT;
1784 static inline bool cpu_has_vmx_ept_2m_page(void)
1786 return vmx_capability.ept & VMX_EPT_2MB_PAGE_BIT;
1789 static inline bool cpu_has_vmx_ept_1g_page(void)
1791 return vmx_capability.ept & VMX_EPT_1GB_PAGE_BIT;
1794 static inline bool cpu_has_vmx_ept_4levels(void)
1796 return vmx_capability.ept & VMX_EPT_PAGE_WALK_4_BIT;
1799 static inline bool cpu_has_vmx_ept_mt_wb(void)
1801 return vmx_capability.ept & VMX_EPTP_WB_BIT;
1804 static inline bool cpu_has_vmx_ept_5levels(void)
1806 return vmx_capability.ept & VMX_EPT_PAGE_WALK_5_BIT;
1809 static inline bool cpu_has_vmx_ept_ad_bits(void)
1811 return vmx_capability.ept & VMX_EPT_AD_BIT;
1814 static inline bool cpu_has_vmx_invept_context(void)
1816 return vmx_capability.ept & VMX_EPT_EXTENT_CONTEXT_BIT;
1819 static inline bool cpu_has_vmx_invept_global(void)
1821 return vmx_capability.ept & VMX_EPT_EXTENT_GLOBAL_BIT;
1824 static inline bool cpu_has_vmx_invvpid_individual_addr(void)
1826 return vmx_capability.vpid & VMX_VPID_EXTENT_INDIVIDUAL_ADDR_BIT;
1829 static inline bool cpu_has_vmx_invvpid_single(void)
1831 return vmx_capability.vpid & VMX_VPID_EXTENT_SINGLE_CONTEXT_BIT;
1834 static inline bool cpu_has_vmx_invvpid_global(void)
1836 return vmx_capability.vpid & VMX_VPID_EXTENT_GLOBAL_CONTEXT_BIT;
1839 static inline bool cpu_has_vmx_invvpid(void)
1841 return vmx_capability.vpid & VMX_VPID_INVVPID_BIT;
1844 static inline bool cpu_has_vmx_ept(void)
1846 return vmcs_config.cpu_based_2nd_exec_ctrl &
1847 SECONDARY_EXEC_ENABLE_EPT;
1850 static inline bool cpu_has_vmx_unrestricted_guest(void)
1852 return vmcs_config.cpu_based_2nd_exec_ctrl &
1853 SECONDARY_EXEC_UNRESTRICTED_GUEST;
1856 static inline bool cpu_has_vmx_ple(void)
1858 return vmcs_config.cpu_based_2nd_exec_ctrl &
1859 SECONDARY_EXEC_PAUSE_LOOP_EXITING;
1862 static inline bool cpu_has_vmx_basic_inout(void)
1864 return (((u64)vmcs_config.basic_cap << 32) & VMX_BASIC_INOUT);
1867 static inline bool cpu_need_virtualize_apic_accesses(struct kvm_vcpu *vcpu)
1869 return flexpriority_enabled && lapic_in_kernel(vcpu);
1872 static inline bool cpu_has_vmx_vpid(void)
1874 return vmcs_config.cpu_based_2nd_exec_ctrl &
1875 SECONDARY_EXEC_ENABLE_VPID;
1878 static inline bool cpu_has_vmx_rdtscp(void)
1880 return vmcs_config.cpu_based_2nd_exec_ctrl &
1881 SECONDARY_EXEC_RDTSCP;
1884 static inline bool cpu_has_vmx_invpcid(void)
1886 return vmcs_config.cpu_based_2nd_exec_ctrl &
1887 SECONDARY_EXEC_ENABLE_INVPCID;
1890 static inline bool cpu_has_virtual_nmis(void)
1892 return vmcs_config.pin_based_exec_ctrl & PIN_BASED_VIRTUAL_NMIS;
1895 static inline bool cpu_has_vmx_wbinvd_exit(void)
1897 return vmcs_config.cpu_based_2nd_exec_ctrl &
1898 SECONDARY_EXEC_WBINVD_EXITING;
1901 static inline bool cpu_has_vmx_shadow_vmcs(void)
1903 u64 vmx_msr;
1904 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
1905 /* check if the cpu supports writing r/o exit information fields */
1906 if (!(vmx_msr & MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS))
1907 return false;
1909 return vmcs_config.cpu_based_2nd_exec_ctrl &
1910 SECONDARY_EXEC_SHADOW_VMCS;
1913 static inline bool cpu_has_vmx_pml(void)
1915 return vmcs_config.cpu_based_2nd_exec_ctrl & SECONDARY_EXEC_ENABLE_PML;
1918 static inline bool cpu_has_vmx_tsc_scaling(void)
1920 return vmcs_config.cpu_based_2nd_exec_ctrl &
1921 SECONDARY_EXEC_TSC_SCALING;
1924 static inline bool cpu_has_vmx_vmfunc(void)
1926 return vmcs_config.cpu_based_2nd_exec_ctrl &
1927 SECONDARY_EXEC_ENABLE_VMFUNC;
1930 static bool vmx_umip_emulated(void)
1932 return vmcs_config.cpu_based_2nd_exec_ctrl &
1933 SECONDARY_EXEC_DESC;
1936 static inline bool report_flexpriority(void)
1938 return flexpriority_enabled;
1941 static inline unsigned nested_cpu_vmx_misc_cr3_count(struct kvm_vcpu *vcpu)
1943 return vmx_misc_cr3_count(to_vmx(vcpu)->nested.msrs.misc_low);
1947 * Do the virtual VMX capability MSRs specify that L1 can use VMWRITE
1948 * to modify any valid field of the VMCS, or are the VM-exit
1949 * information fields read-only?
1951 static inline bool nested_cpu_has_vmwrite_any_field(struct kvm_vcpu *vcpu)
1953 return to_vmx(vcpu)->nested.msrs.misc_low &
1954 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS;
1957 static inline bool nested_cpu_has_zero_length_injection(struct kvm_vcpu *vcpu)
1959 return to_vmx(vcpu)->nested.msrs.misc_low & VMX_MISC_ZERO_LEN_INS;
1962 static inline bool nested_cpu_supports_monitor_trap_flag(struct kvm_vcpu *vcpu)
1964 return to_vmx(vcpu)->nested.msrs.procbased_ctls_high &
1965 CPU_BASED_MONITOR_TRAP_FLAG;
1968 static inline bool nested_cpu_has_vmx_shadow_vmcs(struct kvm_vcpu *vcpu)
1970 return to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
1971 SECONDARY_EXEC_SHADOW_VMCS;
1974 static inline bool nested_cpu_has(struct vmcs12 *vmcs12, u32 bit)
1976 return vmcs12->cpu_based_vm_exec_control & bit;
1979 static inline bool nested_cpu_has2(struct vmcs12 *vmcs12, u32 bit)
1981 return (vmcs12->cpu_based_vm_exec_control &
1982 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
1983 (vmcs12->secondary_vm_exec_control & bit);
1986 static inline bool nested_cpu_has_preemption_timer(struct vmcs12 *vmcs12)
1988 return vmcs12->pin_based_vm_exec_control &
1989 PIN_BASED_VMX_PREEMPTION_TIMER;
1992 static inline bool nested_cpu_has_nmi_exiting(struct vmcs12 *vmcs12)
1994 return vmcs12->pin_based_vm_exec_control & PIN_BASED_NMI_EXITING;
1997 static inline bool nested_cpu_has_virtual_nmis(struct vmcs12 *vmcs12)
1999 return vmcs12->pin_based_vm_exec_control & PIN_BASED_VIRTUAL_NMIS;
2002 static inline int nested_cpu_has_ept(struct vmcs12 *vmcs12)
2004 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_EPT);
2007 static inline bool nested_cpu_has_xsaves(struct vmcs12 *vmcs12)
2009 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
2012 static inline bool nested_cpu_has_pml(struct vmcs12 *vmcs12)
2014 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML);
2017 static inline bool nested_cpu_has_virt_x2apic_mode(struct vmcs12 *vmcs12)
2019 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
2022 static inline bool nested_cpu_has_vpid(struct vmcs12 *vmcs12)
2024 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VPID);
2027 static inline bool nested_cpu_has_apic_reg_virt(struct vmcs12 *vmcs12)
2029 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_APIC_REGISTER_VIRT);
2032 static inline bool nested_cpu_has_vid(struct vmcs12 *vmcs12)
2034 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
2037 static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12)
2039 return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR;
2042 static inline bool nested_cpu_has_vmfunc(struct vmcs12 *vmcs12)
2044 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_VMFUNC);
2047 static inline bool nested_cpu_has_eptp_switching(struct vmcs12 *vmcs12)
2049 return nested_cpu_has_vmfunc(vmcs12) &&
2050 (vmcs12->vm_function_control &
2051 VMX_VMFUNC_EPTP_SWITCHING);
2054 static inline bool nested_cpu_has_shadow_vmcs(struct vmcs12 *vmcs12)
2056 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_SHADOW_VMCS);
2059 static inline bool is_nmi(u32 intr_info)
2061 return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK))
2062 == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK);
2065 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
2066 u32 exit_intr_info,
2067 unsigned long exit_qualification);
2068 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
2069 struct vmcs12 *vmcs12,
2070 u32 reason, unsigned long qualification);
2072 static int __find_msr_index(struct vcpu_vmx *vmx, u32 msr)
2074 int i;
2076 for (i = 0; i < vmx->nmsrs; ++i)
2077 if (vmx_msr_index[vmx->guest_msrs[i].index] == msr)
2078 return i;
2079 return -1;
2082 static inline void __invvpid(int ext, u16 vpid, gva_t gva)
2084 struct {
2085 u64 vpid : 16;
2086 u64 rsvd : 48;
2087 u64 gva;
2088 } operand = { vpid, 0, gva };
2089 bool error;
2091 asm volatile (__ex(ASM_VMX_INVVPID) CC_SET(na)
2092 : CC_OUT(na) (error) : "a"(&operand), "c"(ext)
2093 : "memory");
2094 BUG_ON(error);
2097 static inline void __invept(int ext, u64 eptp, gpa_t gpa)
2099 struct {
2100 u64 eptp, gpa;
2101 } operand = {eptp, gpa};
2102 bool error;
2104 asm volatile (__ex(ASM_VMX_INVEPT) CC_SET(na)
2105 : CC_OUT(na) (error) : "a" (&operand), "c" (ext)
2106 : "memory");
2107 BUG_ON(error);
2110 static struct shared_msr_entry *find_msr_entry(struct vcpu_vmx *vmx, u32 msr)
2112 int i;
2114 i = __find_msr_index(vmx, msr);
2115 if (i >= 0)
2116 return &vmx->guest_msrs[i];
2117 return NULL;
2120 static void vmcs_clear(struct vmcs *vmcs)
2122 u64 phys_addr = __pa(vmcs);
2123 bool error;
2125 asm volatile (__ex(ASM_VMX_VMCLEAR_RAX) CC_SET(na)
2126 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2127 : "memory");
2128 if (unlikely(error))
2129 printk(KERN_ERR "kvm: vmclear fail: %p/%llx\n",
2130 vmcs, phys_addr);
2133 static inline void loaded_vmcs_init(struct loaded_vmcs *loaded_vmcs)
2135 vmcs_clear(loaded_vmcs->vmcs);
2136 if (loaded_vmcs->shadow_vmcs && loaded_vmcs->launched)
2137 vmcs_clear(loaded_vmcs->shadow_vmcs);
2138 loaded_vmcs->cpu = -1;
2139 loaded_vmcs->launched = 0;
2142 static void vmcs_load(struct vmcs *vmcs)
2144 u64 phys_addr = __pa(vmcs);
2145 bool error;
2147 if (static_branch_unlikely(&enable_evmcs))
2148 return evmcs_load(phys_addr);
2150 asm volatile (__ex(ASM_VMX_VMPTRLD_RAX) CC_SET(na)
2151 : CC_OUT(na) (error) : "a"(&phys_addr), "m"(phys_addr)
2152 : "memory");
2153 if (unlikely(error))
2154 printk(KERN_ERR "kvm: vmptrld %p/%llx failed\n",
2155 vmcs, phys_addr);
2158 #ifdef CONFIG_KEXEC_CORE
2160 * This bitmap is used to indicate whether the vmclear
2161 * operation is enabled on all cpus. All disabled by
2162 * default.
2164 static cpumask_t crash_vmclear_enabled_bitmap = CPU_MASK_NONE;
2166 static inline void crash_enable_local_vmclear(int cpu)
2168 cpumask_set_cpu(cpu, &crash_vmclear_enabled_bitmap);
2171 static inline void crash_disable_local_vmclear(int cpu)
2173 cpumask_clear_cpu(cpu, &crash_vmclear_enabled_bitmap);
2176 static inline int crash_local_vmclear_enabled(int cpu)
2178 return cpumask_test_cpu(cpu, &crash_vmclear_enabled_bitmap);
2181 static void crash_vmclear_local_loaded_vmcss(void)
2183 int cpu = raw_smp_processor_id();
2184 struct loaded_vmcs *v;
2186 if (!crash_local_vmclear_enabled(cpu))
2187 return;
2189 list_for_each_entry(v, &per_cpu(loaded_vmcss_on_cpu, cpu),
2190 loaded_vmcss_on_cpu_link)
2191 vmcs_clear(v->vmcs);
2193 #else
2194 static inline void crash_enable_local_vmclear(int cpu) { }
2195 static inline void crash_disable_local_vmclear(int cpu) { }
2196 #endif /* CONFIG_KEXEC_CORE */
2198 static void __loaded_vmcs_clear(void *arg)
2200 struct loaded_vmcs *loaded_vmcs = arg;
2201 int cpu = raw_smp_processor_id();
2203 if (loaded_vmcs->cpu != cpu)
2204 return; /* vcpu migration can race with cpu offline */
2205 if (per_cpu(current_vmcs, cpu) == loaded_vmcs->vmcs)
2206 per_cpu(current_vmcs, cpu) = NULL;
2207 crash_disable_local_vmclear(cpu);
2208 list_del(&loaded_vmcs->loaded_vmcss_on_cpu_link);
2211 * we should ensure updating loaded_vmcs->loaded_vmcss_on_cpu_link
2212 * is before setting loaded_vmcs->vcpu to -1 which is done in
2213 * loaded_vmcs_init. Otherwise, other cpu can see vcpu = -1 fist
2214 * then adds the vmcs into percpu list before it is deleted.
2216 smp_wmb();
2218 loaded_vmcs_init(loaded_vmcs);
2219 crash_enable_local_vmclear(cpu);
2222 static void loaded_vmcs_clear(struct loaded_vmcs *loaded_vmcs)
2224 int cpu = loaded_vmcs->cpu;
2226 if (cpu != -1)
2227 smp_call_function_single(cpu,
2228 __loaded_vmcs_clear, loaded_vmcs, 1);
2231 static inline bool vpid_sync_vcpu_addr(int vpid, gva_t addr)
2233 if (vpid == 0)
2234 return true;
2236 if (cpu_has_vmx_invvpid_individual_addr()) {
2237 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR, vpid, addr);
2238 return true;
2241 return false;
2244 static inline void vpid_sync_vcpu_single(int vpid)
2246 if (vpid == 0)
2247 return;
2249 if (cpu_has_vmx_invvpid_single())
2250 __invvpid(VMX_VPID_EXTENT_SINGLE_CONTEXT, vpid, 0);
2253 static inline void vpid_sync_vcpu_global(void)
2255 if (cpu_has_vmx_invvpid_global())
2256 __invvpid(VMX_VPID_EXTENT_ALL_CONTEXT, 0, 0);
2259 static inline void vpid_sync_context(int vpid)
2261 if (cpu_has_vmx_invvpid_single())
2262 vpid_sync_vcpu_single(vpid);
2263 else
2264 vpid_sync_vcpu_global();
2267 static inline void ept_sync_global(void)
2269 __invept(VMX_EPT_EXTENT_GLOBAL, 0, 0);
2272 static inline void ept_sync_context(u64 eptp)
2274 if (cpu_has_vmx_invept_context())
2275 __invept(VMX_EPT_EXTENT_CONTEXT, eptp, 0);
2276 else
2277 ept_sync_global();
2280 static __always_inline void vmcs_check16(unsigned long field)
2282 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2283 "16-bit accessor invalid for 64-bit field");
2284 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2285 "16-bit accessor invalid for 64-bit high field");
2286 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2287 "16-bit accessor invalid for 32-bit high field");
2288 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2289 "16-bit accessor invalid for natural width field");
2292 static __always_inline void vmcs_check32(unsigned long field)
2294 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2295 "32-bit accessor invalid for 16-bit field");
2296 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2297 "32-bit accessor invalid for natural width field");
2300 static __always_inline void vmcs_check64(unsigned long field)
2302 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2303 "64-bit accessor invalid for 16-bit field");
2304 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2305 "64-bit accessor invalid for 64-bit high field");
2306 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2307 "64-bit accessor invalid for 32-bit field");
2308 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x6000,
2309 "64-bit accessor invalid for natural width field");
2312 static __always_inline void vmcs_checkl(unsigned long field)
2314 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0,
2315 "Natural width accessor invalid for 16-bit field");
2316 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2000,
2317 "Natural width accessor invalid for 64-bit field");
2318 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6001) == 0x2001,
2319 "Natural width accessor invalid for 64-bit high field");
2320 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x4000,
2321 "Natural width accessor invalid for 32-bit field");
2324 static __always_inline unsigned long __vmcs_readl(unsigned long field)
2326 unsigned long value;
2328 asm volatile (__ex_clear(ASM_VMX_VMREAD_RDX_RAX, "%0")
2329 : "=a"(value) : "d"(field) : "cc");
2330 return value;
2333 static __always_inline u16 vmcs_read16(unsigned long field)
2335 vmcs_check16(field);
2336 if (static_branch_unlikely(&enable_evmcs))
2337 return evmcs_read16(field);
2338 return __vmcs_readl(field);
2341 static __always_inline u32 vmcs_read32(unsigned long field)
2343 vmcs_check32(field);
2344 if (static_branch_unlikely(&enable_evmcs))
2345 return evmcs_read32(field);
2346 return __vmcs_readl(field);
2349 static __always_inline u64 vmcs_read64(unsigned long field)
2351 vmcs_check64(field);
2352 if (static_branch_unlikely(&enable_evmcs))
2353 return evmcs_read64(field);
2354 #ifdef CONFIG_X86_64
2355 return __vmcs_readl(field);
2356 #else
2357 return __vmcs_readl(field) | ((u64)__vmcs_readl(field+1) << 32);
2358 #endif
2361 static __always_inline unsigned long vmcs_readl(unsigned long field)
2363 vmcs_checkl(field);
2364 if (static_branch_unlikely(&enable_evmcs))
2365 return evmcs_read64(field);
2366 return __vmcs_readl(field);
2369 static noinline void vmwrite_error(unsigned long field, unsigned long value)
2371 printk(KERN_ERR "vmwrite error: reg %lx value %lx (err %d)\n",
2372 field, value, vmcs_read32(VM_INSTRUCTION_ERROR));
2373 dump_stack();
2376 static __always_inline void __vmcs_writel(unsigned long field, unsigned long value)
2378 bool error;
2380 asm volatile (__ex(ASM_VMX_VMWRITE_RAX_RDX) CC_SET(na)
2381 : CC_OUT(na) (error) : "a"(value), "d"(field));
2382 if (unlikely(error))
2383 vmwrite_error(field, value);
2386 static __always_inline void vmcs_write16(unsigned long field, u16 value)
2388 vmcs_check16(field);
2389 if (static_branch_unlikely(&enable_evmcs))
2390 return evmcs_write16(field, value);
2392 __vmcs_writel(field, value);
2395 static __always_inline void vmcs_write32(unsigned long field, u32 value)
2397 vmcs_check32(field);
2398 if (static_branch_unlikely(&enable_evmcs))
2399 return evmcs_write32(field, value);
2401 __vmcs_writel(field, value);
2404 static __always_inline void vmcs_write64(unsigned long field, u64 value)
2406 vmcs_check64(field);
2407 if (static_branch_unlikely(&enable_evmcs))
2408 return evmcs_write64(field, value);
2410 __vmcs_writel(field, value);
2411 #ifndef CONFIG_X86_64
2412 asm volatile ("");
2413 __vmcs_writel(field+1, value >> 32);
2414 #endif
2417 static __always_inline void vmcs_writel(unsigned long field, unsigned long value)
2419 vmcs_checkl(field);
2420 if (static_branch_unlikely(&enable_evmcs))
2421 return evmcs_write64(field, value);
2423 __vmcs_writel(field, value);
2426 static __always_inline void vmcs_clear_bits(unsigned long field, u32 mask)
2428 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2429 "vmcs_clear_bits does not support 64-bit fields");
2430 if (static_branch_unlikely(&enable_evmcs))
2431 return evmcs_write32(field, evmcs_read32(field) & ~mask);
2433 __vmcs_writel(field, __vmcs_readl(field) & ~mask);
2436 static __always_inline void vmcs_set_bits(unsigned long field, u32 mask)
2438 BUILD_BUG_ON_MSG(__builtin_constant_p(field) && ((field) & 0x6000) == 0x2000,
2439 "vmcs_set_bits does not support 64-bit fields");
2440 if (static_branch_unlikely(&enable_evmcs))
2441 return evmcs_write32(field, evmcs_read32(field) | mask);
2443 __vmcs_writel(field, __vmcs_readl(field) | mask);
2446 static inline void vm_entry_controls_reset_shadow(struct vcpu_vmx *vmx)
2448 vmx->vm_entry_controls_shadow = vmcs_read32(VM_ENTRY_CONTROLS);
2451 static inline void vm_entry_controls_init(struct vcpu_vmx *vmx, u32 val)
2453 vmcs_write32(VM_ENTRY_CONTROLS, val);
2454 vmx->vm_entry_controls_shadow = val;
2457 static inline void vm_entry_controls_set(struct vcpu_vmx *vmx, u32 val)
2459 if (vmx->vm_entry_controls_shadow != val)
2460 vm_entry_controls_init(vmx, val);
2463 static inline u32 vm_entry_controls_get(struct vcpu_vmx *vmx)
2465 return vmx->vm_entry_controls_shadow;
2469 static inline void vm_entry_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2471 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) | val);
2474 static inline void vm_entry_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2476 vm_entry_controls_set(vmx, vm_entry_controls_get(vmx) & ~val);
2479 static inline void vm_exit_controls_reset_shadow(struct vcpu_vmx *vmx)
2481 vmx->vm_exit_controls_shadow = vmcs_read32(VM_EXIT_CONTROLS);
2484 static inline void vm_exit_controls_init(struct vcpu_vmx *vmx, u32 val)
2486 vmcs_write32(VM_EXIT_CONTROLS, val);
2487 vmx->vm_exit_controls_shadow = val;
2490 static inline void vm_exit_controls_set(struct vcpu_vmx *vmx, u32 val)
2492 if (vmx->vm_exit_controls_shadow != val)
2493 vm_exit_controls_init(vmx, val);
2496 static inline u32 vm_exit_controls_get(struct vcpu_vmx *vmx)
2498 return vmx->vm_exit_controls_shadow;
2502 static inline void vm_exit_controls_setbit(struct vcpu_vmx *vmx, u32 val)
2504 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) | val);
2507 static inline void vm_exit_controls_clearbit(struct vcpu_vmx *vmx, u32 val)
2509 vm_exit_controls_set(vmx, vm_exit_controls_get(vmx) & ~val);
2512 static void vmx_segment_cache_clear(struct vcpu_vmx *vmx)
2514 vmx->segment_cache.bitmask = 0;
2517 static bool vmx_segment_cache_test_set(struct vcpu_vmx *vmx, unsigned seg,
2518 unsigned field)
2520 bool ret;
2521 u32 mask = 1 << (seg * SEG_FIELD_NR + field);
2523 if (!(vmx->vcpu.arch.regs_avail & (1 << VCPU_EXREG_SEGMENTS))) {
2524 vmx->vcpu.arch.regs_avail |= (1 << VCPU_EXREG_SEGMENTS);
2525 vmx->segment_cache.bitmask = 0;
2527 ret = vmx->segment_cache.bitmask & mask;
2528 vmx->segment_cache.bitmask |= mask;
2529 return ret;
2532 static u16 vmx_read_guest_seg_selector(struct vcpu_vmx *vmx, unsigned seg)
2534 u16 *p = &vmx->segment_cache.seg[seg].selector;
2536 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_SEL))
2537 *p = vmcs_read16(kvm_vmx_segment_fields[seg].selector);
2538 return *p;
2541 static ulong vmx_read_guest_seg_base(struct vcpu_vmx *vmx, unsigned seg)
2543 ulong *p = &vmx->segment_cache.seg[seg].base;
2545 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_BASE))
2546 *p = vmcs_readl(kvm_vmx_segment_fields[seg].base);
2547 return *p;
2550 static u32 vmx_read_guest_seg_limit(struct vcpu_vmx *vmx, unsigned seg)
2552 u32 *p = &vmx->segment_cache.seg[seg].limit;
2554 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_LIMIT))
2555 *p = vmcs_read32(kvm_vmx_segment_fields[seg].limit);
2556 return *p;
2559 static u32 vmx_read_guest_seg_ar(struct vcpu_vmx *vmx, unsigned seg)
2561 u32 *p = &vmx->segment_cache.seg[seg].ar;
2563 if (!vmx_segment_cache_test_set(vmx, seg, SEG_FIELD_AR))
2564 *p = vmcs_read32(kvm_vmx_segment_fields[seg].ar_bytes);
2565 return *p;
2568 static void update_exception_bitmap(struct kvm_vcpu *vcpu)
2570 u32 eb;
2572 eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) |
2573 (1u << DB_VECTOR) | (1u << AC_VECTOR);
2575 * Guest access to VMware backdoor ports could legitimately
2576 * trigger #GP because of TSS I/O permission bitmap.
2577 * We intercept those #GP and allow access to them anyway
2578 * as VMware does.
2580 if (enable_vmware_backdoor)
2581 eb |= (1u << GP_VECTOR);
2582 if ((vcpu->guest_debug &
2583 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) ==
2584 (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP))
2585 eb |= 1u << BP_VECTOR;
2586 if (to_vmx(vcpu)->rmode.vm86_active)
2587 eb = ~0;
2588 if (enable_ept)
2589 eb &= ~(1u << PF_VECTOR); /* bypass_guest_pf = 0 */
2591 /* When we are running a nested L2 guest and L1 specified for it a
2592 * certain exception bitmap, we must trap the same exceptions and pass
2593 * them to L1. When running L2, we will only handle the exceptions
2594 * specified above if L1 did not want them.
2596 if (is_guest_mode(vcpu))
2597 eb |= get_vmcs12(vcpu)->exception_bitmap;
2599 vmcs_write32(EXCEPTION_BITMAP, eb);
2603 * Check if MSR is intercepted for currently loaded MSR bitmap.
2605 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, u32 msr)
2607 unsigned long *msr_bitmap;
2608 int f = sizeof(unsigned long);
2610 if (!cpu_has_vmx_msr_bitmap())
2611 return true;
2613 msr_bitmap = to_vmx(vcpu)->loaded_vmcs->msr_bitmap;
2615 if (msr <= 0x1fff) {
2616 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2617 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2618 msr &= 0x1fff;
2619 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2622 return true;
2626 * Check if MSR is intercepted for L01 MSR bitmap.
2628 static bool msr_write_intercepted_l01(struct kvm_vcpu *vcpu, u32 msr)
2630 unsigned long *msr_bitmap;
2631 int f = sizeof(unsigned long);
2633 if (!cpu_has_vmx_msr_bitmap())
2634 return true;
2636 msr_bitmap = to_vmx(vcpu)->vmcs01.msr_bitmap;
2638 if (msr <= 0x1fff) {
2639 return !!test_bit(msr, msr_bitmap + 0x800 / f);
2640 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
2641 msr &= 0x1fff;
2642 return !!test_bit(msr, msr_bitmap + 0xc00 / f);
2645 return true;
2648 static void clear_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2649 unsigned long entry, unsigned long exit)
2651 vm_entry_controls_clearbit(vmx, entry);
2652 vm_exit_controls_clearbit(vmx, exit);
2655 static int find_msr(struct vmx_msrs *m, unsigned int msr)
2657 unsigned int i;
2659 for (i = 0; i < m->nr; ++i) {
2660 if (m->val[i].index == msr)
2661 return i;
2663 return -ENOENT;
2666 static void clear_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr)
2668 int i;
2669 struct msr_autoload *m = &vmx->msr_autoload;
2671 switch (msr) {
2672 case MSR_EFER:
2673 if (cpu_has_load_ia32_efer) {
2674 clear_atomic_switch_msr_special(vmx,
2675 VM_ENTRY_LOAD_IA32_EFER,
2676 VM_EXIT_LOAD_IA32_EFER);
2677 return;
2679 break;
2680 case MSR_CORE_PERF_GLOBAL_CTRL:
2681 if (cpu_has_load_perf_global_ctrl) {
2682 clear_atomic_switch_msr_special(vmx,
2683 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2684 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
2685 return;
2687 break;
2689 i = find_msr(&m->guest, msr);
2690 if (i < 0)
2691 goto skip_guest;
2692 --m->guest.nr;
2693 m->guest.val[i] = m->guest.val[m->guest.nr];
2694 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2696 skip_guest:
2697 i = find_msr(&m->host, msr);
2698 if (i < 0)
2699 return;
2701 --m->host.nr;
2702 m->host.val[i] = m->host.val[m->host.nr];
2703 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2706 static void add_atomic_switch_msr_special(struct vcpu_vmx *vmx,
2707 unsigned long entry, unsigned long exit,
2708 unsigned long guest_val_vmcs, unsigned long host_val_vmcs,
2709 u64 guest_val, u64 host_val)
2711 vmcs_write64(guest_val_vmcs, guest_val);
2712 vmcs_write64(host_val_vmcs, host_val);
2713 vm_entry_controls_setbit(vmx, entry);
2714 vm_exit_controls_setbit(vmx, exit);
2717 static void add_atomic_switch_msr(struct vcpu_vmx *vmx, unsigned msr,
2718 u64 guest_val, u64 host_val, bool entry_only)
2720 int i, j = 0;
2721 struct msr_autoload *m = &vmx->msr_autoload;
2723 switch (msr) {
2724 case MSR_EFER:
2725 if (cpu_has_load_ia32_efer) {
2726 add_atomic_switch_msr_special(vmx,
2727 VM_ENTRY_LOAD_IA32_EFER,
2728 VM_EXIT_LOAD_IA32_EFER,
2729 GUEST_IA32_EFER,
2730 HOST_IA32_EFER,
2731 guest_val, host_val);
2732 return;
2734 break;
2735 case MSR_CORE_PERF_GLOBAL_CTRL:
2736 if (cpu_has_load_perf_global_ctrl) {
2737 add_atomic_switch_msr_special(vmx,
2738 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL,
2739 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL,
2740 GUEST_IA32_PERF_GLOBAL_CTRL,
2741 HOST_IA32_PERF_GLOBAL_CTRL,
2742 guest_val, host_val);
2743 return;
2745 break;
2746 case MSR_IA32_PEBS_ENABLE:
2747 /* PEBS needs a quiescent period after being disabled (to write
2748 * a record). Disabling PEBS through VMX MSR swapping doesn't
2749 * provide that period, so a CPU could write host's record into
2750 * guest's memory.
2752 wrmsrl(MSR_IA32_PEBS_ENABLE, 0);
2755 i = find_msr(&m->guest, msr);
2756 if (!entry_only)
2757 j = find_msr(&m->host, msr);
2759 if ((i < 0 && m->guest.nr == NR_AUTOLOAD_MSRS) ||
2760 (j < 0 && m->host.nr == NR_AUTOLOAD_MSRS)) {
2761 printk_once(KERN_WARNING "Not enough msr switch entries. "
2762 "Can't add msr %x\n", msr);
2763 return;
2765 if (i < 0) {
2766 i = m->guest.nr++;
2767 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, m->guest.nr);
2769 m->guest.val[i].index = msr;
2770 m->guest.val[i].value = guest_val;
2772 if (entry_only)
2773 return;
2775 if (j < 0) {
2776 j = m->host.nr++;
2777 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, m->host.nr);
2779 m->host.val[j].index = msr;
2780 m->host.val[j].value = host_val;
2783 static bool update_transition_efer(struct vcpu_vmx *vmx, int efer_offset)
2785 u64 guest_efer = vmx->vcpu.arch.efer;
2786 u64 ignore_bits = 0;
2788 if (!enable_ept) {
2790 * NX is needed to handle CR0.WP=1, CR4.SMEP=1. Testing
2791 * host CPUID is more efficient than testing guest CPUID
2792 * or CR4. Host SMEP is anyway a requirement for guest SMEP.
2794 if (boot_cpu_has(X86_FEATURE_SMEP))
2795 guest_efer |= EFER_NX;
2796 else if (!(guest_efer & EFER_NX))
2797 ignore_bits |= EFER_NX;
2801 * LMA and LME handled by hardware; SCE meaningless outside long mode.
2803 ignore_bits |= EFER_SCE;
2804 #ifdef CONFIG_X86_64
2805 ignore_bits |= EFER_LMA | EFER_LME;
2806 /* SCE is meaningful only in long mode on Intel */
2807 if (guest_efer & EFER_LMA)
2808 ignore_bits &= ~(u64)EFER_SCE;
2809 #endif
2811 clear_atomic_switch_msr(vmx, MSR_EFER);
2814 * On EPT, we can't emulate NX, so we must switch EFER atomically.
2815 * On CPUs that support "load IA32_EFER", always switch EFER
2816 * atomically, since it's faster than switching it manually.
2818 if (cpu_has_load_ia32_efer ||
2819 (enable_ept && ((vmx->vcpu.arch.efer ^ host_efer) & EFER_NX))) {
2820 if (!(guest_efer & EFER_LMA))
2821 guest_efer &= ~EFER_LME;
2822 if (guest_efer != host_efer)
2823 add_atomic_switch_msr(vmx, MSR_EFER,
2824 guest_efer, host_efer, false);
2825 return false;
2826 } else {
2827 guest_efer &= ~ignore_bits;
2828 guest_efer |= host_efer & ignore_bits;
2830 vmx->guest_msrs[efer_offset].data = guest_efer;
2831 vmx->guest_msrs[efer_offset].mask = ~ignore_bits;
2833 return true;
2837 #ifdef CONFIG_X86_32
2839 * On 32-bit kernels, VM exits still load the FS and GS bases from the
2840 * VMCS rather than the segment table. KVM uses this helper to figure
2841 * out the current bases to poke them into the VMCS before entry.
2843 static unsigned long segment_base(u16 selector)
2845 struct desc_struct *table;
2846 unsigned long v;
2848 if (!(selector & ~SEGMENT_RPL_MASK))
2849 return 0;
2851 table = get_current_gdt_ro();
2853 if ((selector & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2854 u16 ldt_selector = kvm_read_ldt();
2856 if (!(ldt_selector & ~SEGMENT_RPL_MASK))
2857 return 0;
2859 table = (struct desc_struct *)segment_base(ldt_selector);
2861 v = get_desc_base(&table[selector >> 3]);
2862 return v;
2864 #endif
2866 static void vmx_prepare_switch_to_guest(struct kvm_vcpu *vcpu)
2868 struct vcpu_vmx *vmx = to_vmx(vcpu);
2869 struct vmcs_host_state *host_state;
2870 #ifdef CONFIG_X86_64
2871 int cpu = raw_smp_processor_id();
2872 #endif
2873 unsigned long fs_base, gs_base;
2874 u16 fs_sel, gs_sel;
2875 int i;
2877 vmx->req_immediate_exit = false;
2880 * Note that guest MSRs to be saved/restored can also be changed
2881 * when guest state is loaded. This happens when guest transitions
2882 * to/from long-mode by setting MSR_EFER.LMA.
2884 if (!vmx->loaded_cpu_state || vmx->guest_msrs_dirty) {
2885 vmx->guest_msrs_dirty = false;
2886 for (i = 0; i < vmx->save_nmsrs; ++i)
2887 kvm_set_shared_msr(vmx->guest_msrs[i].index,
2888 vmx->guest_msrs[i].data,
2889 vmx->guest_msrs[i].mask);
2893 if (vmx->loaded_cpu_state)
2894 return;
2896 vmx->loaded_cpu_state = vmx->loaded_vmcs;
2897 host_state = &vmx->loaded_cpu_state->host_state;
2900 * Set host fs and gs selectors. Unfortunately, 22.2.3 does not
2901 * allow segment selectors with cpl > 0 or ti == 1.
2903 host_state->ldt_sel = kvm_read_ldt();
2905 #ifdef CONFIG_X86_64
2906 savesegment(ds, host_state->ds_sel);
2907 savesegment(es, host_state->es_sel);
2909 gs_base = cpu_kernelmode_gs_base(cpu);
2910 if (likely(is_64bit_mm(current->mm))) {
2911 save_fsgs_for_kvm();
2912 fs_sel = current->thread.fsindex;
2913 gs_sel = current->thread.gsindex;
2914 fs_base = current->thread.fsbase;
2915 vmx->msr_host_kernel_gs_base = current->thread.gsbase;
2916 } else {
2917 savesegment(fs, fs_sel);
2918 savesegment(gs, gs_sel);
2919 fs_base = read_msr(MSR_FS_BASE);
2920 vmx->msr_host_kernel_gs_base = read_msr(MSR_KERNEL_GS_BASE);
2923 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2924 #else
2925 savesegment(fs, fs_sel);
2926 savesegment(gs, gs_sel);
2927 fs_base = segment_base(fs_sel);
2928 gs_base = segment_base(gs_sel);
2929 #endif
2931 if (unlikely(fs_sel != host_state->fs_sel)) {
2932 if (!(fs_sel & 7))
2933 vmcs_write16(HOST_FS_SELECTOR, fs_sel);
2934 else
2935 vmcs_write16(HOST_FS_SELECTOR, 0);
2936 host_state->fs_sel = fs_sel;
2938 if (unlikely(gs_sel != host_state->gs_sel)) {
2939 if (!(gs_sel & 7))
2940 vmcs_write16(HOST_GS_SELECTOR, gs_sel);
2941 else
2942 vmcs_write16(HOST_GS_SELECTOR, 0);
2943 host_state->gs_sel = gs_sel;
2945 if (unlikely(fs_base != host_state->fs_base)) {
2946 vmcs_writel(HOST_FS_BASE, fs_base);
2947 host_state->fs_base = fs_base;
2949 if (unlikely(gs_base != host_state->gs_base)) {
2950 vmcs_writel(HOST_GS_BASE, gs_base);
2951 host_state->gs_base = gs_base;
2955 static void vmx_prepare_switch_to_host(struct vcpu_vmx *vmx)
2957 struct vmcs_host_state *host_state;
2959 if (!vmx->loaded_cpu_state)
2960 return;
2962 WARN_ON_ONCE(vmx->loaded_cpu_state != vmx->loaded_vmcs);
2963 host_state = &vmx->loaded_cpu_state->host_state;
2965 ++vmx->vcpu.stat.host_state_reload;
2966 vmx->loaded_cpu_state = NULL;
2968 #ifdef CONFIG_X86_64
2969 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
2970 #endif
2971 if (host_state->ldt_sel || (host_state->gs_sel & 7)) {
2972 kvm_load_ldt(host_state->ldt_sel);
2973 #ifdef CONFIG_X86_64
2974 load_gs_index(host_state->gs_sel);
2975 #else
2976 loadsegment(gs, host_state->gs_sel);
2977 #endif
2979 if (host_state->fs_sel & 7)
2980 loadsegment(fs, host_state->fs_sel);
2981 #ifdef CONFIG_X86_64
2982 if (unlikely(host_state->ds_sel | host_state->es_sel)) {
2983 loadsegment(ds, host_state->ds_sel);
2984 loadsegment(es, host_state->es_sel);
2986 #endif
2987 invalidate_tss_limit();
2988 #ifdef CONFIG_X86_64
2989 wrmsrl(MSR_KERNEL_GS_BASE, vmx->msr_host_kernel_gs_base);
2990 #endif
2991 load_fixmap_gdt(raw_smp_processor_id());
2994 #ifdef CONFIG_X86_64
2995 static u64 vmx_read_guest_kernel_gs_base(struct vcpu_vmx *vmx)
2997 preempt_disable();
2998 if (vmx->loaded_cpu_state)
2999 rdmsrl(MSR_KERNEL_GS_BASE, vmx->msr_guest_kernel_gs_base);
3000 preempt_enable();
3001 return vmx->msr_guest_kernel_gs_base;
3004 static void vmx_write_guest_kernel_gs_base(struct vcpu_vmx *vmx, u64 data)
3006 preempt_disable();
3007 if (vmx->loaded_cpu_state)
3008 wrmsrl(MSR_KERNEL_GS_BASE, data);
3009 preempt_enable();
3010 vmx->msr_guest_kernel_gs_base = data;
3012 #endif
3014 static void vmx_vcpu_pi_load(struct kvm_vcpu *vcpu, int cpu)
3016 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3017 struct pi_desc old, new;
3018 unsigned int dest;
3021 * In case of hot-plug or hot-unplug, we may have to undo
3022 * vmx_vcpu_pi_put even if there is no assigned device. And we
3023 * always keep PI.NDST up to date for simplicity: it makes the
3024 * code easier, and CPU migration is not a fast path.
3026 if (!pi_test_sn(pi_desc) && vcpu->cpu == cpu)
3027 return;
3030 * First handle the simple case where no cmpxchg is necessary; just
3031 * allow posting non-urgent interrupts.
3033 * If the 'nv' field is POSTED_INTR_WAKEUP_VECTOR, do not change
3034 * PI.NDST: pi_post_block will do it for us and the wakeup_handler
3035 * expects the VCPU to be on the blocked_vcpu_list that matches
3036 * PI.NDST.
3038 if (pi_desc->nv == POSTED_INTR_WAKEUP_VECTOR ||
3039 vcpu->cpu == cpu) {
3040 pi_clear_sn(pi_desc);
3041 return;
3044 /* The full case. */
3045 do {
3046 old.control = new.control = pi_desc->control;
3048 dest = cpu_physical_id(cpu);
3050 if (x2apic_enabled())
3051 new.ndst = dest;
3052 else
3053 new.ndst = (dest << 8) & 0xFF00;
3055 new.sn = 0;
3056 } while (cmpxchg64(&pi_desc->control, old.control,
3057 new.control) != old.control);
3060 static void decache_tsc_multiplier(struct vcpu_vmx *vmx)
3062 vmx->current_tsc_ratio = vmx->vcpu.arch.tsc_scaling_ratio;
3063 vmcs_write64(TSC_MULTIPLIER, vmx->current_tsc_ratio);
3067 * Switches to specified vcpu, until a matching vcpu_put(), but assumes
3068 * vcpu mutex is already taken.
3070 static void vmx_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
3072 struct vcpu_vmx *vmx = to_vmx(vcpu);
3073 bool already_loaded = vmx->loaded_vmcs->cpu == cpu;
3075 if (!already_loaded) {
3076 loaded_vmcs_clear(vmx->loaded_vmcs);
3077 local_irq_disable();
3078 crash_disable_local_vmclear(cpu);
3081 * Read loaded_vmcs->cpu should be before fetching
3082 * loaded_vmcs->loaded_vmcss_on_cpu_link.
3083 * See the comments in __loaded_vmcs_clear().
3085 smp_rmb();
3087 list_add(&vmx->loaded_vmcs->loaded_vmcss_on_cpu_link,
3088 &per_cpu(loaded_vmcss_on_cpu, cpu));
3089 crash_enable_local_vmclear(cpu);
3090 local_irq_enable();
3093 if (per_cpu(current_vmcs, cpu) != vmx->loaded_vmcs->vmcs) {
3094 per_cpu(current_vmcs, cpu) = vmx->loaded_vmcs->vmcs;
3095 vmcs_load(vmx->loaded_vmcs->vmcs);
3096 indirect_branch_prediction_barrier();
3099 if (!already_loaded) {
3100 void *gdt = get_current_gdt_ro();
3101 unsigned long sysenter_esp;
3103 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3106 * Linux uses per-cpu TSS and GDT, so set these when switching
3107 * processors. See 22.2.4.
3109 vmcs_writel(HOST_TR_BASE,
3110 (unsigned long)&get_cpu_entry_area(cpu)->tss.x86_tss);
3111 vmcs_writel(HOST_GDTR_BASE, (unsigned long)gdt); /* 22.2.4 */
3114 * VM exits change the host TR limit to 0x67 after a VM
3115 * exit. This is okay, since 0x67 covers everything except
3116 * the IO bitmap and have have code to handle the IO bitmap
3117 * being lost after a VM exit.
3119 BUILD_BUG_ON(IO_BITMAP_OFFSET - 1 != 0x67);
3121 rdmsrl(MSR_IA32_SYSENTER_ESP, sysenter_esp);
3122 vmcs_writel(HOST_IA32_SYSENTER_ESP, sysenter_esp); /* 22.2.3 */
3124 vmx->loaded_vmcs->cpu = cpu;
3127 /* Setup TSC multiplier */
3128 if (kvm_has_tsc_control &&
3129 vmx->current_tsc_ratio != vcpu->arch.tsc_scaling_ratio)
3130 decache_tsc_multiplier(vmx);
3132 vmx_vcpu_pi_load(vcpu, cpu);
3133 vmx->host_pkru = read_pkru();
3134 vmx->host_debugctlmsr = get_debugctlmsr();
3137 static void vmx_vcpu_pi_put(struct kvm_vcpu *vcpu)
3139 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
3141 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
3142 !irq_remapping_cap(IRQ_POSTING_CAP) ||
3143 !kvm_vcpu_apicv_active(vcpu))
3144 return;
3146 /* Set SN when the vCPU is preempted */
3147 if (vcpu->preempted)
3148 pi_set_sn(pi_desc);
3151 static void vmx_vcpu_put(struct kvm_vcpu *vcpu)
3153 vmx_vcpu_pi_put(vcpu);
3155 vmx_prepare_switch_to_host(to_vmx(vcpu));
3158 static bool emulation_required(struct kvm_vcpu *vcpu)
3160 return emulate_invalid_guest_state && !guest_state_valid(vcpu);
3163 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu);
3166 * Return the cr0 value that a nested guest would read. This is a combination
3167 * of the real cr0 used to run the guest (guest_cr0), and the bits shadowed by
3168 * its hypervisor (cr0_read_shadow).
3170 static inline unsigned long nested_read_cr0(struct vmcs12 *fields)
3172 return (fields->guest_cr0 & ~fields->cr0_guest_host_mask) |
3173 (fields->cr0_read_shadow & fields->cr0_guest_host_mask);
3175 static inline unsigned long nested_read_cr4(struct vmcs12 *fields)
3177 return (fields->guest_cr4 & ~fields->cr4_guest_host_mask) |
3178 (fields->cr4_read_shadow & fields->cr4_guest_host_mask);
3181 static unsigned long vmx_get_rflags(struct kvm_vcpu *vcpu)
3183 unsigned long rflags, save_rflags;
3185 if (!test_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail)) {
3186 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3187 rflags = vmcs_readl(GUEST_RFLAGS);
3188 if (to_vmx(vcpu)->rmode.vm86_active) {
3189 rflags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
3190 save_rflags = to_vmx(vcpu)->rmode.save_rflags;
3191 rflags |= save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
3193 to_vmx(vcpu)->rflags = rflags;
3195 return to_vmx(vcpu)->rflags;
3198 static void vmx_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
3200 unsigned long old_rflags = vmx_get_rflags(vcpu);
3202 __set_bit(VCPU_EXREG_RFLAGS, (ulong *)&vcpu->arch.regs_avail);
3203 to_vmx(vcpu)->rflags = rflags;
3204 if (to_vmx(vcpu)->rmode.vm86_active) {
3205 to_vmx(vcpu)->rmode.save_rflags = rflags;
3206 rflags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
3208 vmcs_writel(GUEST_RFLAGS, rflags);
3210 if ((old_rflags ^ to_vmx(vcpu)->rflags) & X86_EFLAGS_VM)
3211 to_vmx(vcpu)->emulation_required = emulation_required(vcpu);
3214 static u32 vmx_get_interrupt_shadow(struct kvm_vcpu *vcpu)
3216 u32 interruptibility = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3217 int ret = 0;
3219 if (interruptibility & GUEST_INTR_STATE_STI)
3220 ret |= KVM_X86_SHADOW_INT_STI;
3221 if (interruptibility & GUEST_INTR_STATE_MOV_SS)
3222 ret |= KVM_X86_SHADOW_INT_MOV_SS;
3224 return ret;
3227 static void vmx_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
3229 u32 interruptibility_old = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
3230 u32 interruptibility = interruptibility_old;
3232 interruptibility &= ~(GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS);
3234 if (mask & KVM_X86_SHADOW_INT_MOV_SS)
3235 interruptibility |= GUEST_INTR_STATE_MOV_SS;
3236 else if (mask & KVM_X86_SHADOW_INT_STI)
3237 interruptibility |= GUEST_INTR_STATE_STI;
3239 if ((interruptibility != interruptibility_old))
3240 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, interruptibility);
3243 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
3245 unsigned long rip;
3247 rip = kvm_rip_read(vcpu);
3248 rip += vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
3249 kvm_rip_write(vcpu, rip);
3251 /* skipping an emulated instruction also counts */
3252 vmx_set_interrupt_shadow(vcpu, 0);
3255 static void nested_vmx_inject_exception_vmexit(struct kvm_vcpu *vcpu,
3256 unsigned long exit_qual)
3258 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3259 unsigned int nr = vcpu->arch.exception.nr;
3260 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3262 if (vcpu->arch.exception.has_error_code) {
3263 vmcs12->vm_exit_intr_error_code = vcpu->arch.exception.error_code;
3264 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3267 if (kvm_exception_is_soft(nr))
3268 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3269 else
3270 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3272 if (!(vmcs12->idt_vectoring_info_field & VECTORING_INFO_VALID_MASK) &&
3273 vmx_get_nmi_mask(vcpu))
3274 intr_info |= INTR_INFO_UNBLOCK_NMI;
3276 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI, intr_info, exit_qual);
3280 * KVM wants to inject page-faults which it got to the guest. This function
3281 * checks whether in a nested guest, we need to inject them to L1 or L2.
3283 static int nested_vmx_check_exception(struct kvm_vcpu *vcpu, unsigned long *exit_qual)
3285 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3286 unsigned int nr = vcpu->arch.exception.nr;
3288 if (nr == PF_VECTOR) {
3289 if (vcpu->arch.exception.nested_apf) {
3290 *exit_qual = vcpu->arch.apf.nested_apf_token;
3291 return 1;
3294 * FIXME: we must not write CR2 when L1 intercepts an L2 #PF exception.
3295 * The fix is to add the ancillary datum (CR2 or DR6) to structs
3296 * kvm_queued_exception and kvm_vcpu_events, so that CR2 and DR6
3297 * can be written only when inject_pending_event runs. This should be
3298 * conditional on a new capability---if the capability is disabled,
3299 * kvm_multiple_exception would write the ancillary information to
3300 * CR2 or DR6, for backwards ABI-compatibility.
3302 if (nested_vmx_is_page_fault_vmexit(vmcs12,
3303 vcpu->arch.exception.error_code)) {
3304 *exit_qual = vcpu->arch.cr2;
3305 return 1;
3307 } else {
3308 if (vmcs12->exception_bitmap & (1u << nr)) {
3309 if (nr == DB_VECTOR) {
3310 *exit_qual = vcpu->arch.dr6;
3311 *exit_qual &= ~(DR6_FIXED_1 | DR6_BT);
3312 *exit_qual ^= DR6_RTM;
3313 } else {
3314 *exit_qual = 0;
3316 return 1;
3320 return 0;
3323 static void vmx_clear_hlt(struct kvm_vcpu *vcpu)
3326 * Ensure that we clear the HLT state in the VMCS. We don't need to
3327 * explicitly skip the instruction because if the HLT state is set,
3328 * then the instruction is already executing and RIP has already been
3329 * advanced.
3331 if (kvm_hlt_in_guest(vcpu->kvm) &&
3332 vmcs_read32(GUEST_ACTIVITY_STATE) == GUEST_ACTIVITY_HLT)
3333 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
3336 static void vmx_queue_exception(struct kvm_vcpu *vcpu)
3338 struct vcpu_vmx *vmx = to_vmx(vcpu);
3339 unsigned nr = vcpu->arch.exception.nr;
3340 bool has_error_code = vcpu->arch.exception.has_error_code;
3341 u32 error_code = vcpu->arch.exception.error_code;
3342 u32 intr_info = nr | INTR_INFO_VALID_MASK;
3344 if (has_error_code) {
3345 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, error_code);
3346 intr_info |= INTR_INFO_DELIVER_CODE_MASK;
3349 if (vmx->rmode.vm86_active) {
3350 int inc_eip = 0;
3351 if (kvm_exception_is_soft(nr))
3352 inc_eip = vcpu->arch.event_exit_inst_len;
3353 if (kvm_inject_realmode_interrupt(vcpu, nr, inc_eip) != EMULATE_DONE)
3354 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3355 return;
3358 WARN_ON_ONCE(vmx->emulation_required);
3360 if (kvm_exception_is_soft(nr)) {
3361 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
3362 vmx->vcpu.arch.event_exit_inst_len);
3363 intr_info |= INTR_TYPE_SOFT_EXCEPTION;
3364 } else
3365 intr_info |= INTR_TYPE_HARD_EXCEPTION;
3367 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr_info);
3369 vmx_clear_hlt(vcpu);
3372 static bool vmx_rdtscp_supported(void)
3374 return cpu_has_vmx_rdtscp();
3377 static bool vmx_invpcid_supported(void)
3379 return cpu_has_vmx_invpcid();
3383 * Swap MSR entry in host/guest MSR entry array.
3385 static void move_msr_up(struct vcpu_vmx *vmx, int from, int to)
3387 struct shared_msr_entry tmp;
3389 tmp = vmx->guest_msrs[to];
3390 vmx->guest_msrs[to] = vmx->guest_msrs[from];
3391 vmx->guest_msrs[from] = tmp;
3395 * Set up the vmcs to automatically save and restore system
3396 * msrs. Don't touch the 64-bit msrs if the guest is in legacy
3397 * mode, as fiddling with msrs is very expensive.
3399 static void setup_msrs(struct vcpu_vmx *vmx)
3401 int save_nmsrs, index;
3403 save_nmsrs = 0;
3404 #ifdef CONFIG_X86_64
3405 if (is_long_mode(&vmx->vcpu)) {
3406 index = __find_msr_index(vmx, MSR_SYSCALL_MASK);
3407 if (index >= 0)
3408 move_msr_up(vmx, index, save_nmsrs++);
3409 index = __find_msr_index(vmx, MSR_LSTAR);
3410 if (index >= 0)
3411 move_msr_up(vmx, index, save_nmsrs++);
3412 index = __find_msr_index(vmx, MSR_CSTAR);
3413 if (index >= 0)
3414 move_msr_up(vmx, index, save_nmsrs++);
3415 index = __find_msr_index(vmx, MSR_TSC_AUX);
3416 if (index >= 0 && guest_cpuid_has(&vmx->vcpu, X86_FEATURE_RDTSCP))
3417 move_msr_up(vmx, index, save_nmsrs++);
3419 * MSR_STAR is only needed on long mode guests, and only
3420 * if efer.sce is enabled.
3422 index = __find_msr_index(vmx, MSR_STAR);
3423 if ((index >= 0) && (vmx->vcpu.arch.efer & EFER_SCE))
3424 move_msr_up(vmx, index, save_nmsrs++);
3426 #endif
3427 index = __find_msr_index(vmx, MSR_EFER);
3428 if (index >= 0 && update_transition_efer(vmx, index))
3429 move_msr_up(vmx, index, save_nmsrs++);
3431 vmx->save_nmsrs = save_nmsrs;
3432 vmx->guest_msrs_dirty = true;
3434 if (cpu_has_vmx_msr_bitmap())
3435 vmx_update_msr_bitmap(&vmx->vcpu);
3438 static u64 vmx_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
3440 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3442 if (is_guest_mode(vcpu) &&
3443 (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING))
3444 return vcpu->arch.tsc_offset - vmcs12->tsc_offset;
3446 return vcpu->arch.tsc_offset;
3449 static u64 vmx_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
3451 u64 active_offset = offset;
3452 if (is_guest_mode(vcpu)) {
3454 * We're here if L1 chose not to trap WRMSR to TSC. According
3455 * to the spec, this should set L1's TSC; The offset that L1
3456 * set for L2 remains unchanged, and still needs to be added
3457 * to the newly set TSC to get L2's TSC.
3459 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
3460 if (nested_cpu_has(vmcs12, CPU_BASED_USE_TSC_OFFSETING))
3461 active_offset += vmcs12->tsc_offset;
3462 } else {
3463 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
3464 vmcs_read64(TSC_OFFSET), offset);
3467 vmcs_write64(TSC_OFFSET, active_offset);
3468 return active_offset;
3472 * nested_vmx_allowed() checks whether a guest should be allowed to use VMX
3473 * instructions and MSRs (i.e., nested VMX). Nested VMX is disabled for
3474 * all guests if the "nested" module option is off, and can also be disabled
3475 * for a single guest by disabling its VMX cpuid bit.
3477 static inline bool nested_vmx_allowed(struct kvm_vcpu *vcpu)
3479 return nested && guest_cpuid_has(vcpu, X86_FEATURE_VMX);
3483 * nested_vmx_setup_ctls_msrs() sets up variables containing the values to be
3484 * returned for the various VMX controls MSRs when nested VMX is enabled.
3485 * The same values should also be used to verify that vmcs12 control fields are
3486 * valid during nested entry from L1 to L2.
3487 * Each of these control msrs has a low and high 32-bit half: A low bit is on
3488 * if the corresponding bit in the (32-bit) control field *must* be on, and a
3489 * bit in the high half is on if the corresponding bit in the control field
3490 * may be on. See also vmx_control_verify().
3492 static void nested_vmx_setup_ctls_msrs(struct nested_vmx_msrs *msrs, bool apicv)
3494 if (!nested) {
3495 memset(msrs, 0, sizeof(*msrs));
3496 return;
3500 * Note that as a general rule, the high half of the MSRs (bits in
3501 * the control fields which may be 1) should be initialized by the
3502 * intersection of the underlying hardware's MSR (i.e., features which
3503 * can be supported) and the list of features we want to expose -
3504 * because they are known to be properly supported in our code.
3505 * Also, usually, the low half of the MSRs (bits which must be 1) can
3506 * be set to 0, meaning that L1 may turn off any of these bits. The
3507 * reason is that if one of these bits is necessary, it will appear
3508 * in vmcs01 and prepare_vmcs02, when it bitwise-or's the control
3509 * fields of vmcs01 and vmcs02, will turn these bits off - and
3510 * nested_vmx_exit_reflected() will not pass related exits to L1.
3511 * These rules have exceptions below.
3514 /* pin-based controls */
3515 rdmsr(MSR_IA32_VMX_PINBASED_CTLS,
3516 msrs->pinbased_ctls_low,
3517 msrs->pinbased_ctls_high);
3518 msrs->pinbased_ctls_low |=
3519 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3520 msrs->pinbased_ctls_high &=
3521 PIN_BASED_EXT_INTR_MASK |
3522 PIN_BASED_NMI_EXITING |
3523 PIN_BASED_VIRTUAL_NMIS |
3524 (apicv ? PIN_BASED_POSTED_INTR : 0);
3525 msrs->pinbased_ctls_high |=
3526 PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3527 PIN_BASED_VMX_PREEMPTION_TIMER;
3529 /* exit controls */
3530 rdmsr(MSR_IA32_VMX_EXIT_CTLS,
3531 msrs->exit_ctls_low,
3532 msrs->exit_ctls_high);
3533 msrs->exit_ctls_low =
3534 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
3536 msrs->exit_ctls_high &=
3537 #ifdef CONFIG_X86_64
3538 VM_EXIT_HOST_ADDR_SPACE_SIZE |
3539 #endif
3540 VM_EXIT_LOAD_IA32_PAT | VM_EXIT_SAVE_IA32_PAT;
3541 msrs->exit_ctls_high |=
3542 VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR |
3543 VM_EXIT_LOAD_IA32_EFER | VM_EXIT_SAVE_IA32_EFER |
3544 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER | VM_EXIT_ACK_INTR_ON_EXIT;
3546 /* We support free control of debug control saving. */
3547 msrs->exit_ctls_low &= ~VM_EXIT_SAVE_DEBUG_CONTROLS;
3549 /* entry controls */
3550 rdmsr(MSR_IA32_VMX_ENTRY_CTLS,
3551 msrs->entry_ctls_low,
3552 msrs->entry_ctls_high);
3553 msrs->entry_ctls_low =
3554 VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
3555 msrs->entry_ctls_high &=
3556 #ifdef CONFIG_X86_64
3557 VM_ENTRY_IA32E_MODE |
3558 #endif
3559 VM_ENTRY_LOAD_IA32_PAT;
3560 msrs->entry_ctls_high |=
3561 (VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR | VM_ENTRY_LOAD_IA32_EFER);
3563 /* We support free control of debug control loading. */
3564 msrs->entry_ctls_low &= ~VM_ENTRY_LOAD_DEBUG_CONTROLS;
3566 /* cpu-based controls */
3567 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS,
3568 msrs->procbased_ctls_low,
3569 msrs->procbased_ctls_high);
3570 msrs->procbased_ctls_low =
3571 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3572 msrs->procbased_ctls_high &=
3573 CPU_BASED_VIRTUAL_INTR_PENDING |
3574 CPU_BASED_VIRTUAL_NMI_PENDING | CPU_BASED_USE_TSC_OFFSETING |
3575 CPU_BASED_HLT_EXITING | CPU_BASED_INVLPG_EXITING |
3576 CPU_BASED_MWAIT_EXITING | CPU_BASED_CR3_LOAD_EXITING |
3577 CPU_BASED_CR3_STORE_EXITING |
3578 #ifdef CONFIG_X86_64
3579 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING |
3580 #endif
3581 CPU_BASED_MOV_DR_EXITING | CPU_BASED_UNCOND_IO_EXITING |
3582 CPU_BASED_USE_IO_BITMAPS | CPU_BASED_MONITOR_TRAP_FLAG |
3583 CPU_BASED_MONITOR_EXITING | CPU_BASED_RDPMC_EXITING |
3584 CPU_BASED_RDTSC_EXITING | CPU_BASED_PAUSE_EXITING |
3585 CPU_BASED_TPR_SHADOW | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
3587 * We can allow some features even when not supported by the
3588 * hardware. For example, L1 can specify an MSR bitmap - and we
3589 * can use it to avoid exits to L1 - even when L0 runs L2
3590 * without MSR bitmaps.
3592 msrs->procbased_ctls_high |=
3593 CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR |
3594 CPU_BASED_USE_MSR_BITMAPS;
3596 /* We support free control of CR3 access interception. */
3597 msrs->procbased_ctls_low &=
3598 ~(CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING);
3601 * secondary cpu-based controls. Do not include those that
3602 * depend on CPUID bits, they are added later by vmx_cpuid_update.
3604 if (msrs->procbased_ctls_high & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)
3605 rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2,
3606 msrs->secondary_ctls_low,
3607 msrs->secondary_ctls_high);
3609 msrs->secondary_ctls_low = 0;
3610 msrs->secondary_ctls_high &=
3611 SECONDARY_EXEC_DESC |
3612 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
3613 SECONDARY_EXEC_APIC_REGISTER_VIRT |
3614 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
3615 SECONDARY_EXEC_WBINVD_EXITING;
3618 * We can emulate "VMCS shadowing," even if the hardware
3619 * doesn't support it.
3621 msrs->secondary_ctls_high |=
3622 SECONDARY_EXEC_SHADOW_VMCS;
3624 if (enable_ept) {
3625 /* nested EPT: emulate EPT also to L1 */
3626 msrs->secondary_ctls_high |=
3627 SECONDARY_EXEC_ENABLE_EPT;
3628 msrs->ept_caps = VMX_EPT_PAGE_WALK_4_BIT |
3629 VMX_EPTP_WB_BIT | VMX_EPT_INVEPT_BIT;
3630 if (cpu_has_vmx_ept_execute_only())
3631 msrs->ept_caps |=
3632 VMX_EPT_EXECUTE_ONLY_BIT;
3633 msrs->ept_caps &= vmx_capability.ept;
3634 msrs->ept_caps |= VMX_EPT_EXTENT_GLOBAL_BIT |
3635 VMX_EPT_EXTENT_CONTEXT_BIT | VMX_EPT_2MB_PAGE_BIT |
3636 VMX_EPT_1GB_PAGE_BIT;
3637 if (enable_ept_ad_bits) {
3638 msrs->secondary_ctls_high |=
3639 SECONDARY_EXEC_ENABLE_PML;
3640 msrs->ept_caps |= VMX_EPT_AD_BIT;
3644 if (cpu_has_vmx_vmfunc()) {
3645 msrs->secondary_ctls_high |=
3646 SECONDARY_EXEC_ENABLE_VMFUNC;
3648 * Advertise EPTP switching unconditionally
3649 * since we emulate it
3651 if (enable_ept)
3652 msrs->vmfunc_controls =
3653 VMX_VMFUNC_EPTP_SWITCHING;
3657 * Old versions of KVM use the single-context version without
3658 * checking for support, so declare that it is supported even
3659 * though it is treated as global context. The alternative is
3660 * not failing the single-context invvpid, and it is worse.
3662 if (enable_vpid) {
3663 msrs->secondary_ctls_high |=
3664 SECONDARY_EXEC_ENABLE_VPID;
3665 msrs->vpid_caps = VMX_VPID_INVVPID_BIT |
3666 VMX_VPID_EXTENT_SUPPORTED_MASK;
3669 if (enable_unrestricted_guest)
3670 msrs->secondary_ctls_high |=
3671 SECONDARY_EXEC_UNRESTRICTED_GUEST;
3673 if (flexpriority_enabled)
3674 msrs->secondary_ctls_high |=
3675 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
3677 /* miscellaneous data */
3678 rdmsr(MSR_IA32_VMX_MISC,
3679 msrs->misc_low,
3680 msrs->misc_high);
3681 msrs->misc_low &= VMX_MISC_SAVE_EFER_LMA;
3682 msrs->misc_low |=
3683 MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS |
3684 VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE |
3685 VMX_MISC_ACTIVITY_HLT;
3686 msrs->misc_high = 0;
3689 * This MSR reports some information about VMX support. We
3690 * should return information about the VMX we emulate for the
3691 * guest, and the VMCS structure we give it - not about the
3692 * VMX support of the underlying hardware.
3694 msrs->basic =
3695 VMCS12_REVISION |
3696 VMX_BASIC_TRUE_CTLS |
3697 ((u64)VMCS12_SIZE << VMX_BASIC_VMCS_SIZE_SHIFT) |
3698 (VMX_BASIC_MEM_TYPE_WB << VMX_BASIC_MEM_TYPE_SHIFT);
3700 if (cpu_has_vmx_basic_inout())
3701 msrs->basic |= VMX_BASIC_INOUT;
3704 * These MSRs specify bits which the guest must keep fixed on
3705 * while L1 is in VMXON mode (in L1's root mode, or running an L2).
3706 * We picked the standard core2 setting.
3708 #define VMXON_CR0_ALWAYSON (X86_CR0_PE | X86_CR0_PG | X86_CR0_NE)
3709 #define VMXON_CR4_ALWAYSON X86_CR4_VMXE
3710 msrs->cr0_fixed0 = VMXON_CR0_ALWAYSON;
3711 msrs->cr4_fixed0 = VMXON_CR4_ALWAYSON;
3713 /* These MSRs specify bits which the guest must keep fixed off. */
3714 rdmsrl(MSR_IA32_VMX_CR0_FIXED1, msrs->cr0_fixed1);
3715 rdmsrl(MSR_IA32_VMX_CR4_FIXED1, msrs->cr4_fixed1);
3717 /* highest index: VMX_PREEMPTION_TIMER_VALUE */
3718 msrs->vmcs_enum = VMCS12_MAX_FIELD_INDEX << 1;
3722 * if fixed0[i] == 1: val[i] must be 1
3723 * if fixed1[i] == 0: val[i] must be 0
3725 static inline bool fixed_bits_valid(u64 val, u64 fixed0, u64 fixed1)
3727 return ((val & fixed1) | fixed0) == val;
3730 static inline bool vmx_control_verify(u32 control, u32 low, u32 high)
3732 return fixed_bits_valid(control, low, high);
3735 static inline u64 vmx_control_msr(u32 low, u32 high)
3737 return low | ((u64)high << 32);
3740 static bool is_bitwise_subset(u64 superset, u64 subset, u64 mask)
3742 superset &= mask;
3743 subset &= mask;
3745 return (superset | subset) == superset;
3748 static int vmx_restore_vmx_basic(struct vcpu_vmx *vmx, u64 data)
3750 const u64 feature_and_reserved =
3751 /* feature (except bit 48; see below) */
3752 BIT_ULL(49) | BIT_ULL(54) | BIT_ULL(55) |
3753 /* reserved */
3754 BIT_ULL(31) | GENMASK_ULL(47, 45) | GENMASK_ULL(63, 56);
3755 u64 vmx_basic = vmx->nested.msrs.basic;
3757 if (!is_bitwise_subset(vmx_basic, data, feature_and_reserved))
3758 return -EINVAL;
3761 * KVM does not emulate a version of VMX that constrains physical
3762 * addresses of VMX structures (e.g. VMCS) to 32-bits.
3764 if (data & BIT_ULL(48))
3765 return -EINVAL;
3767 if (vmx_basic_vmcs_revision_id(vmx_basic) !=
3768 vmx_basic_vmcs_revision_id(data))
3769 return -EINVAL;
3771 if (vmx_basic_vmcs_size(vmx_basic) > vmx_basic_vmcs_size(data))
3772 return -EINVAL;
3774 vmx->nested.msrs.basic = data;
3775 return 0;
3778 static int
3779 vmx_restore_control_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3781 u64 supported;
3782 u32 *lowp, *highp;
3784 switch (msr_index) {
3785 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3786 lowp = &vmx->nested.msrs.pinbased_ctls_low;
3787 highp = &vmx->nested.msrs.pinbased_ctls_high;
3788 break;
3789 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3790 lowp = &vmx->nested.msrs.procbased_ctls_low;
3791 highp = &vmx->nested.msrs.procbased_ctls_high;
3792 break;
3793 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3794 lowp = &vmx->nested.msrs.exit_ctls_low;
3795 highp = &vmx->nested.msrs.exit_ctls_high;
3796 break;
3797 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3798 lowp = &vmx->nested.msrs.entry_ctls_low;
3799 highp = &vmx->nested.msrs.entry_ctls_high;
3800 break;
3801 case MSR_IA32_VMX_PROCBASED_CTLS2:
3802 lowp = &vmx->nested.msrs.secondary_ctls_low;
3803 highp = &vmx->nested.msrs.secondary_ctls_high;
3804 break;
3805 default:
3806 BUG();
3809 supported = vmx_control_msr(*lowp, *highp);
3811 /* Check must-be-1 bits are still 1. */
3812 if (!is_bitwise_subset(data, supported, GENMASK_ULL(31, 0)))
3813 return -EINVAL;
3815 /* Check must-be-0 bits are still 0. */
3816 if (!is_bitwise_subset(supported, data, GENMASK_ULL(63, 32)))
3817 return -EINVAL;
3819 *lowp = data;
3820 *highp = data >> 32;
3821 return 0;
3824 static int vmx_restore_vmx_misc(struct vcpu_vmx *vmx, u64 data)
3826 const u64 feature_and_reserved_bits =
3827 /* feature */
3828 BIT_ULL(5) | GENMASK_ULL(8, 6) | BIT_ULL(14) | BIT_ULL(15) |
3829 BIT_ULL(28) | BIT_ULL(29) | BIT_ULL(30) |
3830 /* reserved */
3831 GENMASK_ULL(13, 9) | BIT_ULL(31);
3832 u64 vmx_misc;
3834 vmx_misc = vmx_control_msr(vmx->nested.msrs.misc_low,
3835 vmx->nested.msrs.misc_high);
3837 if (!is_bitwise_subset(vmx_misc, data, feature_and_reserved_bits))
3838 return -EINVAL;
3840 if ((vmx->nested.msrs.pinbased_ctls_high &
3841 PIN_BASED_VMX_PREEMPTION_TIMER) &&
3842 vmx_misc_preemption_timer_rate(data) !=
3843 vmx_misc_preemption_timer_rate(vmx_misc))
3844 return -EINVAL;
3846 if (vmx_misc_cr3_count(data) > vmx_misc_cr3_count(vmx_misc))
3847 return -EINVAL;
3849 if (vmx_misc_max_msr(data) > vmx_misc_max_msr(vmx_misc))
3850 return -EINVAL;
3852 if (vmx_misc_mseg_revid(data) != vmx_misc_mseg_revid(vmx_misc))
3853 return -EINVAL;
3855 vmx->nested.msrs.misc_low = data;
3856 vmx->nested.msrs.misc_high = data >> 32;
3859 * If L1 has read-only VM-exit information fields, use the
3860 * less permissive vmx_vmwrite_bitmap to specify write
3861 * permissions for the shadow VMCS.
3863 if (enable_shadow_vmcs && !nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
3864 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmwrite_bitmap));
3866 return 0;
3869 static int vmx_restore_vmx_ept_vpid_cap(struct vcpu_vmx *vmx, u64 data)
3871 u64 vmx_ept_vpid_cap;
3873 vmx_ept_vpid_cap = vmx_control_msr(vmx->nested.msrs.ept_caps,
3874 vmx->nested.msrs.vpid_caps);
3876 /* Every bit is either reserved or a feature bit. */
3877 if (!is_bitwise_subset(vmx_ept_vpid_cap, data, -1ULL))
3878 return -EINVAL;
3880 vmx->nested.msrs.ept_caps = data;
3881 vmx->nested.msrs.vpid_caps = data >> 32;
3882 return 0;
3885 static int vmx_restore_fixed0_msr(struct vcpu_vmx *vmx, u32 msr_index, u64 data)
3887 u64 *msr;
3889 switch (msr_index) {
3890 case MSR_IA32_VMX_CR0_FIXED0:
3891 msr = &vmx->nested.msrs.cr0_fixed0;
3892 break;
3893 case MSR_IA32_VMX_CR4_FIXED0:
3894 msr = &vmx->nested.msrs.cr4_fixed0;
3895 break;
3896 default:
3897 BUG();
3901 * 1 bits (which indicates bits which "must-be-1" during VMX operation)
3902 * must be 1 in the restored value.
3904 if (!is_bitwise_subset(data, *msr, -1ULL))
3905 return -EINVAL;
3907 *msr = data;
3908 return 0;
3912 * Called when userspace is restoring VMX MSRs.
3914 * Returns 0 on success, non-0 otherwise.
3916 static int vmx_set_vmx_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 data)
3918 struct vcpu_vmx *vmx = to_vmx(vcpu);
3921 * Don't allow changes to the VMX capability MSRs while the vCPU
3922 * is in VMX operation.
3924 if (vmx->nested.vmxon)
3925 return -EBUSY;
3927 switch (msr_index) {
3928 case MSR_IA32_VMX_BASIC:
3929 return vmx_restore_vmx_basic(vmx, data);
3930 case MSR_IA32_VMX_PINBASED_CTLS:
3931 case MSR_IA32_VMX_PROCBASED_CTLS:
3932 case MSR_IA32_VMX_EXIT_CTLS:
3933 case MSR_IA32_VMX_ENTRY_CTLS:
3935 * The "non-true" VMX capability MSRs are generated from the
3936 * "true" MSRs, so we do not support restoring them directly.
3938 * If userspace wants to emulate VMX_BASIC[55]=0, userspace
3939 * should restore the "true" MSRs with the must-be-1 bits
3940 * set according to the SDM Vol 3. A.2 "RESERVED CONTROLS AND
3941 * DEFAULT SETTINGS".
3943 return -EINVAL;
3944 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3945 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3946 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3947 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
3948 case MSR_IA32_VMX_PROCBASED_CTLS2:
3949 return vmx_restore_control_msr(vmx, msr_index, data);
3950 case MSR_IA32_VMX_MISC:
3951 return vmx_restore_vmx_misc(vmx, data);
3952 case MSR_IA32_VMX_CR0_FIXED0:
3953 case MSR_IA32_VMX_CR4_FIXED0:
3954 return vmx_restore_fixed0_msr(vmx, msr_index, data);
3955 case MSR_IA32_VMX_CR0_FIXED1:
3956 case MSR_IA32_VMX_CR4_FIXED1:
3958 * These MSRs are generated based on the vCPU's CPUID, so we
3959 * do not support restoring them directly.
3961 return -EINVAL;
3962 case MSR_IA32_VMX_EPT_VPID_CAP:
3963 return vmx_restore_vmx_ept_vpid_cap(vmx, data);
3964 case MSR_IA32_VMX_VMCS_ENUM:
3965 vmx->nested.msrs.vmcs_enum = data;
3966 return 0;
3967 default:
3969 * The rest of the VMX capability MSRs do not support restore.
3971 return -EINVAL;
3975 /* Returns 0 on success, non-0 otherwise. */
3976 static int vmx_get_vmx_msr(struct nested_vmx_msrs *msrs, u32 msr_index, u64 *pdata)
3978 switch (msr_index) {
3979 case MSR_IA32_VMX_BASIC:
3980 *pdata = msrs->basic;
3981 break;
3982 case MSR_IA32_VMX_TRUE_PINBASED_CTLS:
3983 case MSR_IA32_VMX_PINBASED_CTLS:
3984 *pdata = vmx_control_msr(
3985 msrs->pinbased_ctls_low,
3986 msrs->pinbased_ctls_high);
3987 if (msr_index == MSR_IA32_VMX_PINBASED_CTLS)
3988 *pdata |= PIN_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3989 break;
3990 case MSR_IA32_VMX_TRUE_PROCBASED_CTLS:
3991 case MSR_IA32_VMX_PROCBASED_CTLS:
3992 *pdata = vmx_control_msr(
3993 msrs->procbased_ctls_low,
3994 msrs->procbased_ctls_high);
3995 if (msr_index == MSR_IA32_VMX_PROCBASED_CTLS)
3996 *pdata |= CPU_BASED_ALWAYSON_WITHOUT_TRUE_MSR;
3997 break;
3998 case MSR_IA32_VMX_TRUE_EXIT_CTLS:
3999 case MSR_IA32_VMX_EXIT_CTLS:
4000 *pdata = vmx_control_msr(
4001 msrs->exit_ctls_low,
4002 msrs->exit_ctls_high);
4003 if (msr_index == MSR_IA32_VMX_EXIT_CTLS)
4004 *pdata |= VM_EXIT_ALWAYSON_WITHOUT_TRUE_MSR;
4005 break;
4006 case MSR_IA32_VMX_TRUE_ENTRY_CTLS:
4007 case MSR_IA32_VMX_ENTRY_CTLS:
4008 *pdata = vmx_control_msr(
4009 msrs->entry_ctls_low,
4010 msrs->entry_ctls_high);
4011 if (msr_index == MSR_IA32_VMX_ENTRY_CTLS)
4012 *pdata |= VM_ENTRY_ALWAYSON_WITHOUT_TRUE_MSR;
4013 break;
4014 case MSR_IA32_VMX_MISC:
4015 *pdata = vmx_control_msr(
4016 msrs->misc_low,
4017 msrs->misc_high);
4018 break;
4019 case MSR_IA32_VMX_CR0_FIXED0:
4020 *pdata = msrs->cr0_fixed0;
4021 break;
4022 case MSR_IA32_VMX_CR0_FIXED1:
4023 *pdata = msrs->cr0_fixed1;
4024 break;
4025 case MSR_IA32_VMX_CR4_FIXED0:
4026 *pdata = msrs->cr4_fixed0;
4027 break;
4028 case MSR_IA32_VMX_CR4_FIXED1:
4029 *pdata = msrs->cr4_fixed1;
4030 break;
4031 case MSR_IA32_VMX_VMCS_ENUM:
4032 *pdata = msrs->vmcs_enum;
4033 break;
4034 case MSR_IA32_VMX_PROCBASED_CTLS2:
4035 *pdata = vmx_control_msr(
4036 msrs->secondary_ctls_low,
4037 msrs->secondary_ctls_high);
4038 break;
4039 case MSR_IA32_VMX_EPT_VPID_CAP:
4040 *pdata = msrs->ept_caps |
4041 ((u64)msrs->vpid_caps << 32);
4042 break;
4043 case MSR_IA32_VMX_VMFUNC:
4044 *pdata = msrs->vmfunc_controls;
4045 break;
4046 default:
4047 return 1;
4050 return 0;
4053 static inline bool vmx_feature_control_msr_valid(struct kvm_vcpu *vcpu,
4054 uint64_t val)
4056 uint64_t valid_bits = to_vmx(vcpu)->msr_ia32_feature_control_valid_bits;
4058 return !(val & ~valid_bits);
4061 static int vmx_get_msr_feature(struct kvm_msr_entry *msr)
4063 switch (msr->index) {
4064 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4065 if (!nested)
4066 return 1;
4067 return vmx_get_vmx_msr(&vmcs_config.nested, msr->index, &msr->data);
4068 default:
4069 return 1;
4072 return 0;
4076 * Reads an msr value (of 'msr_index') into 'pdata'.
4077 * Returns 0 on success, non-0 otherwise.
4078 * Assumes vcpu_load() was already called.
4080 static int vmx_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4082 struct vcpu_vmx *vmx = to_vmx(vcpu);
4083 struct shared_msr_entry *msr;
4085 switch (msr_info->index) {
4086 #ifdef CONFIG_X86_64
4087 case MSR_FS_BASE:
4088 msr_info->data = vmcs_readl(GUEST_FS_BASE);
4089 break;
4090 case MSR_GS_BASE:
4091 msr_info->data = vmcs_readl(GUEST_GS_BASE);
4092 break;
4093 case MSR_KERNEL_GS_BASE:
4094 msr_info->data = vmx_read_guest_kernel_gs_base(vmx);
4095 break;
4096 #endif
4097 case MSR_EFER:
4098 return kvm_get_msr_common(vcpu, msr_info);
4099 case MSR_IA32_SPEC_CTRL:
4100 if (!msr_info->host_initiated &&
4101 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4102 return 1;
4104 msr_info->data = to_vmx(vcpu)->spec_ctrl;
4105 break;
4106 case MSR_IA32_SYSENTER_CS:
4107 msr_info->data = vmcs_read32(GUEST_SYSENTER_CS);
4108 break;
4109 case MSR_IA32_SYSENTER_EIP:
4110 msr_info->data = vmcs_readl(GUEST_SYSENTER_EIP);
4111 break;
4112 case MSR_IA32_SYSENTER_ESP:
4113 msr_info->data = vmcs_readl(GUEST_SYSENTER_ESP);
4114 break;
4115 case MSR_IA32_BNDCFGS:
4116 if (!kvm_mpx_supported() ||
4117 (!msr_info->host_initiated &&
4118 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4119 return 1;
4120 msr_info->data = vmcs_read64(GUEST_BNDCFGS);
4121 break;
4122 case MSR_IA32_MCG_EXT_CTL:
4123 if (!msr_info->host_initiated &&
4124 !(vmx->msr_ia32_feature_control &
4125 FEATURE_CONTROL_LMCE))
4126 return 1;
4127 msr_info->data = vcpu->arch.mcg_ext_ctl;
4128 break;
4129 case MSR_IA32_FEATURE_CONTROL:
4130 msr_info->data = vmx->msr_ia32_feature_control;
4131 break;
4132 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4133 if (!nested_vmx_allowed(vcpu))
4134 return 1;
4135 return vmx_get_vmx_msr(&vmx->nested.msrs, msr_info->index,
4136 &msr_info->data);
4137 case MSR_IA32_XSS:
4138 if (!vmx_xsaves_supported())
4139 return 1;
4140 msr_info->data = vcpu->arch.ia32_xss;
4141 break;
4142 case MSR_TSC_AUX:
4143 if (!msr_info->host_initiated &&
4144 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4145 return 1;
4146 /* Otherwise falls through */
4147 default:
4148 msr = find_msr_entry(vmx, msr_info->index);
4149 if (msr) {
4150 msr_info->data = msr->data;
4151 break;
4153 return kvm_get_msr_common(vcpu, msr_info);
4156 return 0;
4159 static void vmx_leave_nested(struct kvm_vcpu *vcpu);
4162 * Writes msr value into into the appropriate "register".
4163 * Returns 0 on success, non-0 otherwise.
4164 * Assumes vcpu_load() was already called.
4166 static int vmx_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4168 struct vcpu_vmx *vmx = to_vmx(vcpu);
4169 struct shared_msr_entry *msr;
4170 int ret = 0;
4171 u32 msr_index = msr_info->index;
4172 u64 data = msr_info->data;
4174 switch (msr_index) {
4175 case MSR_EFER:
4176 ret = kvm_set_msr_common(vcpu, msr_info);
4177 break;
4178 #ifdef CONFIG_X86_64
4179 case MSR_FS_BASE:
4180 vmx_segment_cache_clear(vmx);
4181 vmcs_writel(GUEST_FS_BASE, data);
4182 break;
4183 case MSR_GS_BASE:
4184 vmx_segment_cache_clear(vmx);
4185 vmcs_writel(GUEST_GS_BASE, data);
4186 break;
4187 case MSR_KERNEL_GS_BASE:
4188 vmx_write_guest_kernel_gs_base(vmx, data);
4189 break;
4190 #endif
4191 case MSR_IA32_SYSENTER_CS:
4192 vmcs_write32(GUEST_SYSENTER_CS, data);
4193 break;
4194 case MSR_IA32_SYSENTER_EIP:
4195 vmcs_writel(GUEST_SYSENTER_EIP, data);
4196 break;
4197 case MSR_IA32_SYSENTER_ESP:
4198 vmcs_writel(GUEST_SYSENTER_ESP, data);
4199 break;
4200 case MSR_IA32_BNDCFGS:
4201 if (!kvm_mpx_supported() ||
4202 (!msr_info->host_initiated &&
4203 !guest_cpuid_has(vcpu, X86_FEATURE_MPX)))
4204 return 1;
4205 if (is_noncanonical_address(data & PAGE_MASK, vcpu) ||
4206 (data & MSR_IA32_BNDCFGS_RSVD))
4207 return 1;
4208 vmcs_write64(GUEST_BNDCFGS, data);
4209 break;
4210 case MSR_IA32_SPEC_CTRL:
4211 if (!msr_info->host_initiated &&
4212 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4213 return 1;
4215 /* The STIBP bit doesn't fault even if it's not advertised */
4216 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4217 return 1;
4219 vmx->spec_ctrl = data;
4221 if (!data)
4222 break;
4225 * For non-nested:
4226 * When it's written (to non-zero) for the first time, pass
4227 * it through.
4229 * For nested:
4230 * The handling of the MSR bitmap for L2 guests is done in
4231 * nested_vmx_merge_msr_bitmap. We should not touch the
4232 * vmcs02.msr_bitmap here since it gets completely overwritten
4233 * in the merging. We update the vmcs01 here for L1 as well
4234 * since it will end up touching the MSR anyway now.
4236 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap,
4237 MSR_IA32_SPEC_CTRL,
4238 MSR_TYPE_RW);
4239 break;
4240 case MSR_IA32_PRED_CMD:
4241 if (!msr_info->host_initiated &&
4242 !guest_cpuid_has(vcpu, X86_FEATURE_SPEC_CTRL))
4243 return 1;
4245 if (data & ~PRED_CMD_IBPB)
4246 return 1;
4248 if (!data)
4249 break;
4251 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4254 * For non-nested:
4255 * When it's written (to non-zero) for the first time, pass
4256 * it through.
4258 * For nested:
4259 * The handling of the MSR bitmap for L2 guests is done in
4260 * nested_vmx_merge_msr_bitmap. We should not touch the
4261 * vmcs02.msr_bitmap here since it gets completely overwritten
4262 * in the merging.
4264 vmx_disable_intercept_for_msr(vmx->vmcs01.msr_bitmap, MSR_IA32_PRED_CMD,
4265 MSR_TYPE_W);
4266 break;
4267 case MSR_IA32_CR_PAT:
4268 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
4269 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4270 return 1;
4271 vmcs_write64(GUEST_IA32_PAT, data);
4272 vcpu->arch.pat = data;
4273 break;
4275 ret = kvm_set_msr_common(vcpu, msr_info);
4276 break;
4277 case MSR_IA32_TSC_ADJUST:
4278 ret = kvm_set_msr_common(vcpu, msr_info);
4279 break;
4280 case MSR_IA32_MCG_EXT_CTL:
4281 if ((!msr_info->host_initiated &&
4282 !(to_vmx(vcpu)->msr_ia32_feature_control &
4283 FEATURE_CONTROL_LMCE)) ||
4284 (data & ~MCG_EXT_CTL_LMCE_EN))
4285 return 1;
4286 vcpu->arch.mcg_ext_ctl = data;
4287 break;
4288 case MSR_IA32_FEATURE_CONTROL:
4289 if (!vmx_feature_control_msr_valid(vcpu, data) ||
4290 (to_vmx(vcpu)->msr_ia32_feature_control &
4291 FEATURE_CONTROL_LOCKED && !msr_info->host_initiated))
4292 return 1;
4293 vmx->msr_ia32_feature_control = data;
4294 if (msr_info->host_initiated && data == 0)
4295 vmx_leave_nested(vcpu);
4296 break;
4297 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
4298 if (!msr_info->host_initiated)
4299 return 1; /* they are read-only */
4300 if (!nested_vmx_allowed(vcpu))
4301 return 1;
4302 return vmx_set_vmx_msr(vcpu, msr_index, data);
4303 case MSR_IA32_XSS:
4304 if (!vmx_xsaves_supported())
4305 return 1;
4307 * The only supported bit as of Skylake is bit 8, but
4308 * it is not supported on KVM.
4310 if (data != 0)
4311 return 1;
4312 vcpu->arch.ia32_xss = data;
4313 if (vcpu->arch.ia32_xss != host_xss)
4314 add_atomic_switch_msr(vmx, MSR_IA32_XSS,
4315 vcpu->arch.ia32_xss, host_xss, false);
4316 else
4317 clear_atomic_switch_msr(vmx, MSR_IA32_XSS);
4318 break;
4319 case MSR_TSC_AUX:
4320 if (!msr_info->host_initiated &&
4321 !guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP))
4322 return 1;
4323 /* Check reserved bit, higher 32 bits should be zero */
4324 if ((data >> 32) != 0)
4325 return 1;
4326 /* Otherwise falls through */
4327 default:
4328 msr = find_msr_entry(vmx, msr_index);
4329 if (msr) {
4330 u64 old_msr_data = msr->data;
4331 msr->data = data;
4332 if (msr - vmx->guest_msrs < vmx->save_nmsrs) {
4333 preempt_disable();
4334 ret = kvm_set_shared_msr(msr->index, msr->data,
4335 msr->mask);
4336 preempt_enable();
4337 if (ret)
4338 msr->data = old_msr_data;
4340 break;
4342 ret = kvm_set_msr_common(vcpu, msr_info);
4345 return ret;
4348 static void vmx_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
4350 __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail);
4351 switch (reg) {
4352 case VCPU_REGS_RSP:
4353 vcpu->arch.regs[VCPU_REGS_RSP] = vmcs_readl(GUEST_RSP);
4354 break;
4355 case VCPU_REGS_RIP:
4356 vcpu->arch.regs[VCPU_REGS_RIP] = vmcs_readl(GUEST_RIP);
4357 break;
4358 case VCPU_EXREG_PDPTR:
4359 if (enable_ept)
4360 ept_save_pdptrs(vcpu);
4361 break;
4362 default:
4363 break;
4367 static __init int cpu_has_kvm_support(void)
4369 return cpu_has_vmx();
4372 static __init int vmx_disabled_by_bios(void)
4374 u64 msr;
4376 rdmsrl(MSR_IA32_FEATURE_CONTROL, msr);
4377 if (msr & FEATURE_CONTROL_LOCKED) {
4378 /* launched w/ TXT and VMX disabled */
4379 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4380 && tboot_enabled())
4381 return 1;
4382 /* launched w/o TXT and VMX only enabled w/ TXT */
4383 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4384 && (msr & FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX)
4385 && !tboot_enabled()) {
4386 printk(KERN_WARNING "kvm: disable TXT in the BIOS or "
4387 "activate TXT before enabling KVM\n");
4388 return 1;
4390 /* launched w/o TXT and VMX disabled */
4391 if (!(msr & FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX)
4392 && !tboot_enabled())
4393 return 1;
4396 return 0;
4399 static void kvm_cpu_vmxon(u64 addr)
4401 cr4_set_bits(X86_CR4_VMXE);
4402 intel_pt_handle_vmx(1);
4404 asm volatile (ASM_VMX_VMXON_RAX
4405 : : "a"(&addr), "m"(addr)
4406 : "memory", "cc");
4409 static int hardware_enable(void)
4411 int cpu = raw_smp_processor_id();
4412 u64 phys_addr = __pa(per_cpu(vmxarea, cpu));
4413 u64 old, test_bits;
4415 if (cr4_read_shadow() & X86_CR4_VMXE)
4416 return -EBUSY;
4419 * This can happen if we hot-added a CPU but failed to allocate
4420 * VP assist page for it.
4422 if (static_branch_unlikely(&enable_evmcs) &&
4423 !hv_get_vp_assist_page(cpu))
4424 return -EFAULT;
4426 INIT_LIST_HEAD(&per_cpu(loaded_vmcss_on_cpu, cpu));
4427 INIT_LIST_HEAD(&per_cpu(blocked_vcpu_on_cpu, cpu));
4428 spin_lock_init(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
4431 * Now we can enable the vmclear operation in kdump
4432 * since the loaded_vmcss_on_cpu list on this cpu
4433 * has been initialized.
4435 * Though the cpu is not in VMX operation now, there
4436 * is no problem to enable the vmclear operation
4437 * for the loaded_vmcss_on_cpu list is empty!
4439 crash_enable_local_vmclear(cpu);
4441 rdmsrl(MSR_IA32_FEATURE_CONTROL, old);
4443 test_bits = FEATURE_CONTROL_LOCKED;
4444 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
4445 if (tboot_enabled())
4446 test_bits |= FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX;
4448 if ((old & test_bits) != test_bits) {
4449 /* enable and lock */
4450 wrmsrl(MSR_IA32_FEATURE_CONTROL, old | test_bits);
4452 kvm_cpu_vmxon(phys_addr);
4453 if (enable_ept)
4454 ept_sync_global();
4456 return 0;
4459 static void vmclear_local_loaded_vmcss(void)
4461 int cpu = raw_smp_processor_id();
4462 struct loaded_vmcs *v, *n;
4464 list_for_each_entry_safe(v, n, &per_cpu(loaded_vmcss_on_cpu, cpu),
4465 loaded_vmcss_on_cpu_link)
4466 __loaded_vmcs_clear(v);
4470 /* Just like cpu_vmxoff(), but with the __kvm_handle_fault_on_reboot()
4471 * tricks.
4473 static void kvm_cpu_vmxoff(void)
4475 asm volatile (__ex(ASM_VMX_VMXOFF) : : : "cc");
4477 intel_pt_handle_vmx(0);
4478 cr4_clear_bits(X86_CR4_VMXE);
4481 static void hardware_disable(void)
4483 vmclear_local_loaded_vmcss();
4484 kvm_cpu_vmxoff();
4487 static __init int adjust_vmx_controls(u32 ctl_min, u32 ctl_opt,
4488 u32 msr, u32 *result)
4490 u32 vmx_msr_low, vmx_msr_high;
4491 u32 ctl = ctl_min | ctl_opt;
4493 rdmsr(msr, vmx_msr_low, vmx_msr_high);
4495 ctl &= vmx_msr_high; /* bit == 0 in high word ==> must be zero */
4496 ctl |= vmx_msr_low; /* bit == 1 in low word ==> must be one */
4498 /* Ensure minimum (required) set of control bits are supported. */
4499 if (ctl_min & ~ctl)
4500 return -EIO;
4502 *result = ctl;
4503 return 0;
4506 static __init bool allow_1_setting(u32 msr, u32 ctl)
4508 u32 vmx_msr_low, vmx_msr_high;
4510 rdmsr(msr, vmx_msr_low, vmx_msr_high);
4511 return vmx_msr_high & ctl;
4514 static __init int setup_vmcs_config(struct vmcs_config *vmcs_conf)
4516 u32 vmx_msr_low, vmx_msr_high;
4517 u32 min, opt, min2, opt2;
4518 u32 _pin_based_exec_control = 0;
4519 u32 _cpu_based_exec_control = 0;
4520 u32 _cpu_based_2nd_exec_control = 0;
4521 u32 _vmexit_control = 0;
4522 u32 _vmentry_control = 0;
4524 memset(vmcs_conf, 0, sizeof(*vmcs_conf));
4525 min = CPU_BASED_HLT_EXITING |
4526 #ifdef CONFIG_X86_64
4527 CPU_BASED_CR8_LOAD_EXITING |
4528 CPU_BASED_CR8_STORE_EXITING |
4529 #endif
4530 CPU_BASED_CR3_LOAD_EXITING |
4531 CPU_BASED_CR3_STORE_EXITING |
4532 CPU_BASED_UNCOND_IO_EXITING |
4533 CPU_BASED_MOV_DR_EXITING |
4534 CPU_BASED_USE_TSC_OFFSETING |
4535 CPU_BASED_MWAIT_EXITING |
4536 CPU_BASED_MONITOR_EXITING |
4537 CPU_BASED_INVLPG_EXITING |
4538 CPU_BASED_RDPMC_EXITING;
4540 opt = CPU_BASED_TPR_SHADOW |
4541 CPU_BASED_USE_MSR_BITMAPS |
4542 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS;
4543 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS,
4544 &_cpu_based_exec_control) < 0)
4545 return -EIO;
4546 #ifdef CONFIG_X86_64
4547 if ((_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4548 _cpu_based_exec_control &= ~CPU_BASED_CR8_LOAD_EXITING &
4549 ~CPU_BASED_CR8_STORE_EXITING;
4550 #endif
4551 if (_cpu_based_exec_control & CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) {
4552 min2 = 0;
4553 opt2 = SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
4554 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4555 SECONDARY_EXEC_WBINVD_EXITING |
4556 SECONDARY_EXEC_ENABLE_VPID |
4557 SECONDARY_EXEC_ENABLE_EPT |
4558 SECONDARY_EXEC_UNRESTRICTED_GUEST |
4559 SECONDARY_EXEC_PAUSE_LOOP_EXITING |
4560 SECONDARY_EXEC_DESC |
4561 SECONDARY_EXEC_RDTSCP |
4562 SECONDARY_EXEC_ENABLE_INVPCID |
4563 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4564 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
4565 SECONDARY_EXEC_SHADOW_VMCS |
4566 SECONDARY_EXEC_XSAVES |
4567 SECONDARY_EXEC_RDSEED_EXITING |
4568 SECONDARY_EXEC_RDRAND_EXITING |
4569 SECONDARY_EXEC_ENABLE_PML |
4570 SECONDARY_EXEC_TSC_SCALING |
4571 SECONDARY_EXEC_ENABLE_VMFUNC |
4572 SECONDARY_EXEC_ENCLS_EXITING;
4573 if (adjust_vmx_controls(min2, opt2,
4574 MSR_IA32_VMX_PROCBASED_CTLS2,
4575 &_cpu_based_2nd_exec_control) < 0)
4576 return -EIO;
4578 #ifndef CONFIG_X86_64
4579 if (!(_cpu_based_2nd_exec_control &
4580 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
4581 _cpu_based_exec_control &= ~CPU_BASED_TPR_SHADOW;
4582 #endif
4584 if (!(_cpu_based_exec_control & CPU_BASED_TPR_SHADOW))
4585 _cpu_based_2nd_exec_control &= ~(
4586 SECONDARY_EXEC_APIC_REGISTER_VIRT |
4587 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
4588 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
4590 rdmsr_safe(MSR_IA32_VMX_EPT_VPID_CAP,
4591 &vmx_capability.ept, &vmx_capability.vpid);
4593 if (_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_EPT) {
4594 /* CR3 accesses and invlpg don't need to cause VM Exits when EPT
4595 enabled */
4596 _cpu_based_exec_control &= ~(CPU_BASED_CR3_LOAD_EXITING |
4597 CPU_BASED_CR3_STORE_EXITING |
4598 CPU_BASED_INVLPG_EXITING);
4599 } else if (vmx_capability.ept) {
4600 vmx_capability.ept = 0;
4601 pr_warn_once("EPT CAP should not exist if not support "
4602 "1-setting enable EPT VM-execution control\n");
4604 if (!(_cpu_based_2nd_exec_control & SECONDARY_EXEC_ENABLE_VPID) &&
4605 vmx_capability.vpid) {
4606 vmx_capability.vpid = 0;
4607 pr_warn_once("VPID CAP should not exist if not support "
4608 "1-setting enable VPID VM-execution control\n");
4611 min = VM_EXIT_SAVE_DEBUG_CONTROLS | VM_EXIT_ACK_INTR_ON_EXIT;
4612 #ifdef CONFIG_X86_64
4613 min |= VM_EXIT_HOST_ADDR_SPACE_SIZE;
4614 #endif
4615 opt = VM_EXIT_SAVE_IA32_PAT | VM_EXIT_LOAD_IA32_PAT |
4616 VM_EXIT_CLEAR_BNDCFGS;
4617 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_EXIT_CTLS,
4618 &_vmexit_control) < 0)
4619 return -EIO;
4621 min = PIN_BASED_EXT_INTR_MASK | PIN_BASED_NMI_EXITING;
4622 opt = PIN_BASED_VIRTUAL_NMIS | PIN_BASED_POSTED_INTR |
4623 PIN_BASED_VMX_PREEMPTION_TIMER;
4624 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PINBASED_CTLS,
4625 &_pin_based_exec_control) < 0)
4626 return -EIO;
4628 if (cpu_has_broken_vmx_preemption_timer())
4629 _pin_based_exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
4630 if (!(_cpu_based_2nd_exec_control &
4631 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY))
4632 _pin_based_exec_control &= ~PIN_BASED_POSTED_INTR;
4634 min = VM_ENTRY_LOAD_DEBUG_CONTROLS;
4635 opt = VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_BNDCFGS;
4636 if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_ENTRY_CTLS,
4637 &_vmentry_control) < 0)
4638 return -EIO;
4640 rdmsr(MSR_IA32_VMX_BASIC, vmx_msr_low, vmx_msr_high);
4642 /* IA-32 SDM Vol 3B: VMCS size is never greater than 4kB. */
4643 if ((vmx_msr_high & 0x1fff) > PAGE_SIZE)
4644 return -EIO;
4646 #ifdef CONFIG_X86_64
4647 /* IA-32 SDM Vol 3B: 64-bit CPUs always have VMX_BASIC_MSR[48]==0. */
4648 if (vmx_msr_high & (1u<<16))
4649 return -EIO;
4650 #endif
4652 /* Require Write-Back (WB) memory type for VMCS accesses. */
4653 if (((vmx_msr_high >> 18) & 15) != 6)
4654 return -EIO;
4656 vmcs_conf->size = vmx_msr_high & 0x1fff;
4657 vmcs_conf->order = get_order(vmcs_conf->size);
4658 vmcs_conf->basic_cap = vmx_msr_high & ~0x1fff;
4660 vmcs_conf->revision_id = vmx_msr_low;
4662 vmcs_conf->pin_based_exec_ctrl = _pin_based_exec_control;
4663 vmcs_conf->cpu_based_exec_ctrl = _cpu_based_exec_control;
4664 vmcs_conf->cpu_based_2nd_exec_ctrl = _cpu_based_2nd_exec_control;
4665 vmcs_conf->vmexit_ctrl = _vmexit_control;
4666 vmcs_conf->vmentry_ctrl = _vmentry_control;
4668 if (static_branch_unlikely(&enable_evmcs))
4669 evmcs_sanitize_exec_ctrls(vmcs_conf);
4671 cpu_has_load_ia32_efer =
4672 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4673 VM_ENTRY_LOAD_IA32_EFER)
4674 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4675 VM_EXIT_LOAD_IA32_EFER);
4677 cpu_has_load_perf_global_ctrl =
4678 allow_1_setting(MSR_IA32_VMX_ENTRY_CTLS,
4679 VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
4680 && allow_1_setting(MSR_IA32_VMX_EXIT_CTLS,
4681 VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL);
4684 * Some cpus support VM_ENTRY_(LOAD|SAVE)_IA32_PERF_GLOBAL_CTRL
4685 * but due to errata below it can't be used. Workaround is to use
4686 * msr load mechanism to switch IA32_PERF_GLOBAL_CTRL.
4688 * VM Exit May Incorrectly Clear IA32_PERF_GLOBAL_CTRL [34:32]
4690 * AAK155 (model 26)
4691 * AAP115 (model 30)
4692 * AAT100 (model 37)
4693 * BC86,AAY89,BD102 (model 44)
4694 * BA97 (model 46)
4697 if (cpu_has_load_perf_global_ctrl && boot_cpu_data.x86 == 0x6) {
4698 switch (boot_cpu_data.x86_model) {
4699 case 26:
4700 case 30:
4701 case 37:
4702 case 44:
4703 case 46:
4704 cpu_has_load_perf_global_ctrl = false;
4705 printk_once(KERN_WARNING"kvm: VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL "
4706 "does not work properly. Using workaround\n");
4707 break;
4708 default:
4709 break;
4713 if (boot_cpu_has(X86_FEATURE_XSAVES))
4714 rdmsrl(MSR_IA32_XSS, host_xss);
4716 return 0;
4719 static struct vmcs *alloc_vmcs_cpu(bool shadow, int cpu)
4721 int node = cpu_to_node(cpu);
4722 struct page *pages;
4723 struct vmcs *vmcs;
4725 pages = __alloc_pages_node(node, GFP_KERNEL, vmcs_config.order);
4726 if (!pages)
4727 return NULL;
4728 vmcs = page_address(pages);
4729 memset(vmcs, 0, vmcs_config.size);
4731 /* KVM supports Enlightened VMCS v1 only */
4732 if (static_branch_unlikely(&enable_evmcs))
4733 vmcs->hdr.revision_id = KVM_EVMCS_VERSION;
4734 else
4735 vmcs->hdr.revision_id = vmcs_config.revision_id;
4737 if (shadow)
4738 vmcs->hdr.shadow_vmcs = 1;
4739 return vmcs;
4742 static void free_vmcs(struct vmcs *vmcs)
4744 free_pages((unsigned long)vmcs, vmcs_config.order);
4748 * Free a VMCS, but before that VMCLEAR it on the CPU where it was last loaded
4750 static void free_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4752 if (!loaded_vmcs->vmcs)
4753 return;
4754 loaded_vmcs_clear(loaded_vmcs);
4755 free_vmcs(loaded_vmcs->vmcs);
4756 loaded_vmcs->vmcs = NULL;
4757 if (loaded_vmcs->msr_bitmap)
4758 free_page((unsigned long)loaded_vmcs->msr_bitmap);
4759 WARN_ON(loaded_vmcs->shadow_vmcs != NULL);
4762 static struct vmcs *alloc_vmcs(bool shadow)
4764 return alloc_vmcs_cpu(shadow, raw_smp_processor_id());
4767 static int alloc_loaded_vmcs(struct loaded_vmcs *loaded_vmcs)
4769 loaded_vmcs->vmcs = alloc_vmcs(false);
4770 if (!loaded_vmcs->vmcs)
4771 return -ENOMEM;
4773 loaded_vmcs->shadow_vmcs = NULL;
4774 loaded_vmcs_init(loaded_vmcs);
4776 if (cpu_has_vmx_msr_bitmap()) {
4777 loaded_vmcs->msr_bitmap = (unsigned long *)__get_free_page(GFP_KERNEL);
4778 if (!loaded_vmcs->msr_bitmap)
4779 goto out_vmcs;
4780 memset(loaded_vmcs->msr_bitmap, 0xff, PAGE_SIZE);
4782 if (IS_ENABLED(CONFIG_HYPERV) &&
4783 static_branch_unlikely(&enable_evmcs) &&
4784 (ms_hyperv.nested_features & HV_X64_NESTED_MSR_BITMAP)) {
4785 struct hv_enlightened_vmcs *evmcs =
4786 (struct hv_enlightened_vmcs *)loaded_vmcs->vmcs;
4788 evmcs->hv_enlightenments_control.msr_bitmap = 1;
4792 memset(&loaded_vmcs->host_state, 0, sizeof(struct vmcs_host_state));
4794 return 0;
4796 out_vmcs:
4797 free_loaded_vmcs(loaded_vmcs);
4798 return -ENOMEM;
4801 static void free_kvm_area(void)
4803 int cpu;
4805 for_each_possible_cpu(cpu) {
4806 free_vmcs(per_cpu(vmxarea, cpu));
4807 per_cpu(vmxarea, cpu) = NULL;
4811 enum vmcs_field_width {
4812 VMCS_FIELD_WIDTH_U16 = 0,
4813 VMCS_FIELD_WIDTH_U64 = 1,
4814 VMCS_FIELD_WIDTH_U32 = 2,
4815 VMCS_FIELD_WIDTH_NATURAL_WIDTH = 3
4818 static inline int vmcs_field_width(unsigned long field)
4820 if (0x1 & field) /* the *_HIGH fields are all 32 bit */
4821 return VMCS_FIELD_WIDTH_U32;
4822 return (field >> 13) & 0x3 ;
4825 static inline int vmcs_field_readonly(unsigned long field)
4827 return (((field >> 10) & 0x3) == 1);
4830 static void init_vmcs_shadow_fields(void)
4832 int i, j;
4834 for (i = j = 0; i < max_shadow_read_only_fields; i++) {
4835 u16 field = shadow_read_only_fields[i];
4836 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4837 (i + 1 == max_shadow_read_only_fields ||
4838 shadow_read_only_fields[i + 1] != field + 1))
4839 pr_err("Missing field from shadow_read_only_field %x\n",
4840 field + 1);
4842 clear_bit(field, vmx_vmread_bitmap);
4843 #ifdef CONFIG_X86_64
4844 if (field & 1)
4845 continue;
4846 #endif
4847 if (j < i)
4848 shadow_read_only_fields[j] = field;
4849 j++;
4851 max_shadow_read_only_fields = j;
4853 for (i = j = 0; i < max_shadow_read_write_fields; i++) {
4854 u16 field = shadow_read_write_fields[i];
4855 if (vmcs_field_width(field) == VMCS_FIELD_WIDTH_U64 &&
4856 (i + 1 == max_shadow_read_write_fields ||
4857 shadow_read_write_fields[i + 1] != field + 1))
4858 pr_err("Missing field from shadow_read_write_field %x\n",
4859 field + 1);
4862 * PML and the preemption timer can be emulated, but the
4863 * processor cannot vmwrite to fields that don't exist
4864 * on bare metal.
4866 switch (field) {
4867 case GUEST_PML_INDEX:
4868 if (!cpu_has_vmx_pml())
4869 continue;
4870 break;
4871 case VMX_PREEMPTION_TIMER_VALUE:
4872 if (!cpu_has_vmx_preemption_timer())
4873 continue;
4874 break;
4875 case GUEST_INTR_STATUS:
4876 if (!cpu_has_vmx_apicv())
4877 continue;
4878 break;
4879 default:
4880 break;
4883 clear_bit(field, vmx_vmwrite_bitmap);
4884 clear_bit(field, vmx_vmread_bitmap);
4885 #ifdef CONFIG_X86_64
4886 if (field & 1)
4887 continue;
4888 #endif
4889 if (j < i)
4890 shadow_read_write_fields[j] = field;
4891 j++;
4893 max_shadow_read_write_fields = j;
4896 static __init int alloc_kvm_area(void)
4898 int cpu;
4900 for_each_possible_cpu(cpu) {
4901 struct vmcs *vmcs;
4903 vmcs = alloc_vmcs_cpu(false, cpu);
4904 if (!vmcs) {
4905 free_kvm_area();
4906 return -ENOMEM;
4910 * When eVMCS is enabled, alloc_vmcs_cpu() sets
4911 * vmcs->revision_id to KVM_EVMCS_VERSION instead of
4912 * revision_id reported by MSR_IA32_VMX_BASIC.
4914 * However, even though not explictly documented by
4915 * TLFS, VMXArea passed as VMXON argument should
4916 * still be marked with revision_id reported by
4917 * physical CPU.
4919 if (static_branch_unlikely(&enable_evmcs))
4920 vmcs->hdr.revision_id = vmcs_config.revision_id;
4922 per_cpu(vmxarea, cpu) = vmcs;
4924 return 0;
4927 static void fix_pmode_seg(struct kvm_vcpu *vcpu, int seg,
4928 struct kvm_segment *save)
4930 if (!emulate_invalid_guest_state) {
4932 * CS and SS RPL should be equal during guest entry according
4933 * to VMX spec, but in reality it is not always so. Since vcpu
4934 * is in the middle of the transition from real mode to
4935 * protected mode it is safe to assume that RPL 0 is a good
4936 * default value.
4938 if (seg == VCPU_SREG_CS || seg == VCPU_SREG_SS)
4939 save->selector &= ~SEGMENT_RPL_MASK;
4940 save->dpl = save->selector & SEGMENT_RPL_MASK;
4941 save->s = 1;
4943 vmx_set_segment(vcpu, save, seg);
4946 static void enter_pmode(struct kvm_vcpu *vcpu)
4948 unsigned long flags;
4949 struct vcpu_vmx *vmx = to_vmx(vcpu);
4952 * Update real mode segment cache. It may be not up-to-date if sement
4953 * register was written while vcpu was in a guest mode.
4955 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
4956 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
4957 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
4958 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
4959 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
4960 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
4962 vmx->rmode.vm86_active = 0;
4964 vmx_segment_cache_clear(vmx);
4966 vmx_set_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
4968 flags = vmcs_readl(GUEST_RFLAGS);
4969 flags &= RMODE_GUEST_OWNED_EFLAGS_BITS;
4970 flags |= vmx->rmode.save_rflags & ~RMODE_GUEST_OWNED_EFLAGS_BITS;
4971 vmcs_writel(GUEST_RFLAGS, flags);
4973 vmcs_writel(GUEST_CR4, (vmcs_readl(GUEST_CR4) & ~X86_CR4_VME) |
4974 (vmcs_readl(CR4_READ_SHADOW) & X86_CR4_VME));
4976 update_exception_bitmap(vcpu);
4978 fix_pmode_seg(vcpu, VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
4979 fix_pmode_seg(vcpu, VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
4980 fix_pmode_seg(vcpu, VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
4981 fix_pmode_seg(vcpu, VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
4982 fix_pmode_seg(vcpu, VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
4983 fix_pmode_seg(vcpu, VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
4986 static void fix_rmode_seg(int seg, struct kvm_segment *save)
4988 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
4989 struct kvm_segment var = *save;
4991 var.dpl = 0x3;
4992 if (seg == VCPU_SREG_CS)
4993 var.type = 0x3;
4995 if (!emulate_invalid_guest_state) {
4996 var.selector = var.base >> 4;
4997 var.base = var.base & 0xffff0;
4998 var.limit = 0xffff;
4999 var.g = 0;
5000 var.db = 0;
5001 var.present = 1;
5002 var.s = 1;
5003 var.l = 0;
5004 var.unusable = 0;
5005 var.type = 0x3;
5006 var.avl = 0;
5007 if (save->base & 0xf)
5008 printk_once(KERN_WARNING "kvm: segment base is not "
5009 "paragraph aligned when entering "
5010 "protected mode (seg=%d)", seg);
5013 vmcs_write16(sf->selector, var.selector);
5014 vmcs_writel(sf->base, var.base);
5015 vmcs_write32(sf->limit, var.limit);
5016 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(&var));
5019 static void enter_rmode(struct kvm_vcpu *vcpu)
5021 unsigned long flags;
5022 struct vcpu_vmx *vmx = to_vmx(vcpu);
5023 struct kvm_vmx *kvm_vmx = to_kvm_vmx(vcpu->kvm);
5025 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_TR], VCPU_SREG_TR);
5026 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_ES], VCPU_SREG_ES);
5027 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_DS], VCPU_SREG_DS);
5028 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_FS], VCPU_SREG_FS);
5029 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_GS], VCPU_SREG_GS);
5030 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_SS], VCPU_SREG_SS);
5031 vmx_get_segment(vcpu, &vmx->rmode.segs[VCPU_SREG_CS], VCPU_SREG_CS);
5033 vmx->rmode.vm86_active = 1;
5036 * Very old userspace does not call KVM_SET_TSS_ADDR before entering
5037 * vcpu. Warn the user that an update is overdue.
5039 if (!kvm_vmx->tss_addr)
5040 printk_once(KERN_WARNING "kvm: KVM_SET_TSS_ADDR need to be "
5041 "called before entering vcpu\n");
5043 vmx_segment_cache_clear(vmx);
5045 vmcs_writel(GUEST_TR_BASE, kvm_vmx->tss_addr);
5046 vmcs_write32(GUEST_TR_LIMIT, RMODE_TSS_SIZE - 1);
5047 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
5049 flags = vmcs_readl(GUEST_RFLAGS);
5050 vmx->rmode.save_rflags = flags;
5052 flags |= X86_EFLAGS_IOPL | X86_EFLAGS_VM;
5054 vmcs_writel(GUEST_RFLAGS, flags);
5055 vmcs_writel(GUEST_CR4, vmcs_readl(GUEST_CR4) | X86_CR4_VME);
5056 update_exception_bitmap(vcpu);
5058 fix_rmode_seg(VCPU_SREG_SS, &vmx->rmode.segs[VCPU_SREG_SS]);
5059 fix_rmode_seg(VCPU_SREG_CS, &vmx->rmode.segs[VCPU_SREG_CS]);
5060 fix_rmode_seg(VCPU_SREG_ES, &vmx->rmode.segs[VCPU_SREG_ES]);
5061 fix_rmode_seg(VCPU_SREG_DS, &vmx->rmode.segs[VCPU_SREG_DS]);
5062 fix_rmode_seg(VCPU_SREG_GS, &vmx->rmode.segs[VCPU_SREG_GS]);
5063 fix_rmode_seg(VCPU_SREG_FS, &vmx->rmode.segs[VCPU_SREG_FS]);
5065 kvm_mmu_reset_context(vcpu);
5068 static void vmx_set_efer(struct kvm_vcpu *vcpu, u64 efer)
5070 struct vcpu_vmx *vmx = to_vmx(vcpu);
5071 struct shared_msr_entry *msr = find_msr_entry(vmx, MSR_EFER);
5073 if (!msr)
5074 return;
5076 vcpu->arch.efer = efer;
5077 if (efer & EFER_LMA) {
5078 vm_entry_controls_setbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5079 msr->data = efer;
5080 } else {
5081 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5083 msr->data = efer & ~EFER_LME;
5085 setup_msrs(vmx);
5088 #ifdef CONFIG_X86_64
5090 static void enter_lmode(struct kvm_vcpu *vcpu)
5092 u32 guest_tr_ar;
5094 vmx_segment_cache_clear(to_vmx(vcpu));
5096 guest_tr_ar = vmcs_read32(GUEST_TR_AR_BYTES);
5097 if ((guest_tr_ar & VMX_AR_TYPE_MASK) != VMX_AR_TYPE_BUSY_64_TSS) {
5098 pr_debug_ratelimited("%s: tss fixup for long mode. \n",
5099 __func__);
5100 vmcs_write32(GUEST_TR_AR_BYTES,
5101 (guest_tr_ar & ~VMX_AR_TYPE_MASK)
5102 | VMX_AR_TYPE_BUSY_64_TSS);
5104 vmx_set_efer(vcpu, vcpu->arch.efer | EFER_LMA);
5107 static void exit_lmode(struct kvm_vcpu *vcpu)
5109 vm_entry_controls_clearbit(to_vmx(vcpu), VM_ENTRY_IA32E_MODE);
5110 vmx_set_efer(vcpu, vcpu->arch.efer & ~EFER_LMA);
5113 #endif
5115 static inline void __vmx_flush_tlb(struct kvm_vcpu *vcpu, int vpid,
5116 bool invalidate_gpa)
5118 if (enable_ept && (invalidate_gpa || !enable_vpid)) {
5119 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
5120 return;
5121 ept_sync_context(construct_eptp(vcpu, vcpu->arch.mmu.root_hpa));
5122 } else {
5123 vpid_sync_context(vpid);
5127 static void vmx_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5129 __vmx_flush_tlb(vcpu, to_vmx(vcpu)->vpid, invalidate_gpa);
5132 static void vmx_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t addr)
5134 int vpid = to_vmx(vcpu)->vpid;
5136 if (!vpid_sync_vcpu_addr(vpid, addr))
5137 vpid_sync_context(vpid);
5140 * If VPIDs are not supported or enabled, then the above is a no-op.
5141 * But we don't really need a TLB flush in that case anyway, because
5142 * each VM entry/exit includes an implicit flush when VPID is 0.
5146 static void vmx_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
5148 ulong cr0_guest_owned_bits = vcpu->arch.cr0_guest_owned_bits;
5150 vcpu->arch.cr0 &= ~cr0_guest_owned_bits;
5151 vcpu->arch.cr0 |= vmcs_readl(GUEST_CR0) & cr0_guest_owned_bits;
5154 static void vmx_decache_cr3(struct kvm_vcpu *vcpu)
5156 if (enable_unrestricted_guest || (enable_ept && is_paging(vcpu)))
5157 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
5158 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
5161 static void vmx_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
5163 ulong cr4_guest_owned_bits = vcpu->arch.cr4_guest_owned_bits;
5165 vcpu->arch.cr4 &= ~cr4_guest_owned_bits;
5166 vcpu->arch.cr4 |= vmcs_readl(GUEST_CR4) & cr4_guest_owned_bits;
5169 static void ept_load_pdptrs(struct kvm_vcpu *vcpu)
5171 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5173 if (!test_bit(VCPU_EXREG_PDPTR,
5174 (unsigned long *)&vcpu->arch.regs_dirty))
5175 return;
5177 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5178 vmcs_write64(GUEST_PDPTR0, mmu->pdptrs[0]);
5179 vmcs_write64(GUEST_PDPTR1, mmu->pdptrs[1]);
5180 vmcs_write64(GUEST_PDPTR2, mmu->pdptrs[2]);
5181 vmcs_write64(GUEST_PDPTR3, mmu->pdptrs[3]);
5185 static void ept_save_pdptrs(struct kvm_vcpu *vcpu)
5187 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
5189 if (is_paging(vcpu) && is_pae(vcpu) && !is_long_mode(vcpu)) {
5190 mmu->pdptrs[0] = vmcs_read64(GUEST_PDPTR0);
5191 mmu->pdptrs[1] = vmcs_read64(GUEST_PDPTR1);
5192 mmu->pdptrs[2] = vmcs_read64(GUEST_PDPTR2);
5193 mmu->pdptrs[3] = vmcs_read64(GUEST_PDPTR3);
5196 __set_bit(VCPU_EXREG_PDPTR,
5197 (unsigned long *)&vcpu->arch.regs_avail);
5198 __set_bit(VCPU_EXREG_PDPTR,
5199 (unsigned long *)&vcpu->arch.regs_dirty);
5202 static bool nested_guest_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5204 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5205 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5206 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
5208 if (to_vmx(vcpu)->nested.msrs.secondary_ctls_high &
5209 SECONDARY_EXEC_UNRESTRICTED_GUEST &&
5210 nested_cpu_has2(vmcs12, SECONDARY_EXEC_UNRESTRICTED_GUEST))
5211 fixed0 &= ~(X86_CR0_PE | X86_CR0_PG);
5213 return fixed_bits_valid(val, fixed0, fixed1);
5216 static bool nested_host_cr0_valid(struct kvm_vcpu *vcpu, unsigned long val)
5218 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr0_fixed0;
5219 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr0_fixed1;
5221 return fixed_bits_valid(val, fixed0, fixed1);
5224 static bool nested_cr4_valid(struct kvm_vcpu *vcpu, unsigned long val)
5226 u64 fixed0 = to_vmx(vcpu)->nested.msrs.cr4_fixed0;
5227 u64 fixed1 = to_vmx(vcpu)->nested.msrs.cr4_fixed1;
5229 return fixed_bits_valid(val, fixed0, fixed1);
5232 /* No difference in the restrictions on guest and host CR4 in VMX operation. */
5233 #define nested_guest_cr4_valid nested_cr4_valid
5234 #define nested_host_cr4_valid nested_cr4_valid
5236 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4);
5238 static void ept_update_paging_mode_cr0(unsigned long *hw_cr0,
5239 unsigned long cr0,
5240 struct kvm_vcpu *vcpu)
5242 if (!test_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail))
5243 vmx_decache_cr3(vcpu);
5244 if (!(cr0 & X86_CR0_PG)) {
5245 /* From paging/starting to nonpaging */
5246 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5247 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) |
5248 (CPU_BASED_CR3_LOAD_EXITING |
5249 CPU_BASED_CR3_STORE_EXITING));
5250 vcpu->arch.cr0 = cr0;
5251 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5252 } else if (!is_paging(vcpu)) {
5253 /* From nonpaging to paging */
5254 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL,
5255 vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
5256 ~(CPU_BASED_CR3_LOAD_EXITING |
5257 CPU_BASED_CR3_STORE_EXITING));
5258 vcpu->arch.cr0 = cr0;
5259 vmx_set_cr4(vcpu, kvm_read_cr4(vcpu));
5262 if (!(cr0 & X86_CR0_WP))
5263 *hw_cr0 &= ~X86_CR0_WP;
5266 static void vmx_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
5268 struct vcpu_vmx *vmx = to_vmx(vcpu);
5269 unsigned long hw_cr0;
5271 hw_cr0 = (cr0 & ~KVM_GUEST_CR0_MASK);
5272 if (enable_unrestricted_guest)
5273 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON_UNRESTRICTED_GUEST;
5274 else {
5275 hw_cr0 |= KVM_VM_CR0_ALWAYS_ON;
5277 if (vmx->rmode.vm86_active && (cr0 & X86_CR0_PE))
5278 enter_pmode(vcpu);
5280 if (!vmx->rmode.vm86_active && !(cr0 & X86_CR0_PE))
5281 enter_rmode(vcpu);
5284 #ifdef CONFIG_X86_64
5285 if (vcpu->arch.efer & EFER_LME) {
5286 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG))
5287 enter_lmode(vcpu);
5288 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG))
5289 exit_lmode(vcpu);
5291 #endif
5293 if (enable_ept && !enable_unrestricted_guest)
5294 ept_update_paging_mode_cr0(&hw_cr0, cr0, vcpu);
5296 vmcs_writel(CR0_READ_SHADOW, cr0);
5297 vmcs_writel(GUEST_CR0, hw_cr0);
5298 vcpu->arch.cr0 = cr0;
5300 /* depends on vcpu->arch.cr0 to be set to a new value */
5301 vmx->emulation_required = emulation_required(vcpu);
5304 static int get_ept_level(struct kvm_vcpu *vcpu)
5306 if (cpu_has_vmx_ept_5levels() && (cpuid_maxphyaddr(vcpu) > 48))
5307 return 5;
5308 return 4;
5311 static u64 construct_eptp(struct kvm_vcpu *vcpu, unsigned long root_hpa)
5313 u64 eptp = VMX_EPTP_MT_WB;
5315 eptp |= (get_ept_level(vcpu) == 5) ? VMX_EPTP_PWL_5 : VMX_EPTP_PWL_4;
5317 if (enable_ept_ad_bits &&
5318 (!is_guest_mode(vcpu) || nested_ept_ad_enabled(vcpu)))
5319 eptp |= VMX_EPTP_AD_ENABLE_BIT;
5320 eptp |= (root_hpa & PAGE_MASK);
5322 return eptp;
5325 static void vmx_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
5327 struct kvm *kvm = vcpu->kvm;
5328 unsigned long guest_cr3;
5329 u64 eptp;
5331 guest_cr3 = cr3;
5332 if (enable_ept) {
5333 eptp = construct_eptp(vcpu, cr3);
5334 vmcs_write64(EPT_POINTER, eptp);
5336 if (kvm_x86_ops->tlb_remote_flush) {
5337 spin_lock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5338 to_vmx(vcpu)->ept_pointer = eptp;
5339 to_kvm_vmx(kvm)->ept_pointers_match
5340 = EPT_POINTERS_CHECK;
5341 spin_unlock(&to_kvm_vmx(kvm)->ept_pointer_lock);
5344 if (enable_unrestricted_guest || is_paging(vcpu) ||
5345 is_guest_mode(vcpu))
5346 guest_cr3 = kvm_read_cr3(vcpu);
5347 else
5348 guest_cr3 = to_kvm_vmx(kvm)->ept_identity_map_addr;
5349 ept_load_pdptrs(vcpu);
5352 vmcs_writel(GUEST_CR3, guest_cr3);
5355 static int vmx_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
5358 * Pass through host's Machine Check Enable value to hw_cr4, which
5359 * is in force while we are in guest mode. Do not let guests control
5360 * this bit, even if host CR4.MCE == 0.
5362 unsigned long hw_cr4;
5364 hw_cr4 = (cr4_read_shadow() & X86_CR4_MCE) | (cr4 & ~X86_CR4_MCE);
5365 if (enable_unrestricted_guest)
5366 hw_cr4 |= KVM_VM_CR4_ALWAYS_ON_UNRESTRICTED_GUEST;
5367 else if (to_vmx(vcpu)->rmode.vm86_active)
5368 hw_cr4 |= KVM_RMODE_VM_CR4_ALWAYS_ON;
5369 else
5370 hw_cr4 |= KVM_PMODE_VM_CR4_ALWAYS_ON;
5372 if (!boot_cpu_has(X86_FEATURE_UMIP) && vmx_umip_emulated()) {
5373 if (cr4 & X86_CR4_UMIP) {
5374 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
5375 SECONDARY_EXEC_DESC);
5376 hw_cr4 &= ~X86_CR4_UMIP;
5377 } else if (!is_guest_mode(vcpu) ||
5378 !nested_cpu_has2(get_vmcs12(vcpu), SECONDARY_EXEC_DESC))
5379 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
5380 SECONDARY_EXEC_DESC);
5383 if (cr4 & X86_CR4_VMXE) {
5385 * To use VMXON (and later other VMX instructions), a guest
5386 * must first be able to turn on cr4.VMXE (see handle_vmon()).
5387 * So basically the check on whether to allow nested VMX
5388 * is here. We operate under the default treatment of SMM,
5389 * so VMX cannot be enabled under SMM.
5391 if (!nested_vmx_allowed(vcpu) || is_smm(vcpu))
5392 return 1;
5395 if (to_vmx(vcpu)->nested.vmxon && !nested_cr4_valid(vcpu, cr4))
5396 return 1;
5398 vcpu->arch.cr4 = cr4;
5400 if (!enable_unrestricted_guest) {
5401 if (enable_ept) {
5402 if (!is_paging(vcpu)) {
5403 hw_cr4 &= ~X86_CR4_PAE;
5404 hw_cr4 |= X86_CR4_PSE;
5405 } else if (!(cr4 & X86_CR4_PAE)) {
5406 hw_cr4 &= ~X86_CR4_PAE;
5411 * SMEP/SMAP/PKU is disabled if CPU is in non-paging mode in
5412 * hardware. To emulate this behavior, SMEP/SMAP/PKU needs
5413 * to be manually disabled when guest switches to non-paging
5414 * mode.
5416 * If !enable_unrestricted_guest, the CPU is always running
5417 * with CR0.PG=1 and CR4 needs to be modified.
5418 * If enable_unrestricted_guest, the CPU automatically
5419 * disables SMEP/SMAP/PKU when the guest sets CR0.PG=0.
5421 if (!is_paging(vcpu))
5422 hw_cr4 &= ~(X86_CR4_SMEP | X86_CR4_SMAP | X86_CR4_PKE);
5425 vmcs_writel(CR4_READ_SHADOW, cr4);
5426 vmcs_writel(GUEST_CR4, hw_cr4);
5427 return 0;
5430 static void vmx_get_segment(struct kvm_vcpu *vcpu,
5431 struct kvm_segment *var, int seg)
5433 struct vcpu_vmx *vmx = to_vmx(vcpu);
5434 u32 ar;
5436 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5437 *var = vmx->rmode.segs[seg];
5438 if (seg == VCPU_SREG_TR
5439 || var->selector == vmx_read_guest_seg_selector(vmx, seg))
5440 return;
5441 var->base = vmx_read_guest_seg_base(vmx, seg);
5442 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5443 return;
5445 var->base = vmx_read_guest_seg_base(vmx, seg);
5446 var->limit = vmx_read_guest_seg_limit(vmx, seg);
5447 var->selector = vmx_read_guest_seg_selector(vmx, seg);
5448 ar = vmx_read_guest_seg_ar(vmx, seg);
5449 var->unusable = (ar >> 16) & 1;
5450 var->type = ar & 15;
5451 var->s = (ar >> 4) & 1;
5452 var->dpl = (ar >> 5) & 3;
5454 * Some userspaces do not preserve unusable property. Since usable
5455 * segment has to be present according to VMX spec we can use present
5456 * property to amend userspace bug by making unusable segment always
5457 * nonpresent. vmx_segment_access_rights() already marks nonpresent
5458 * segment as unusable.
5460 var->present = !var->unusable;
5461 var->avl = (ar >> 12) & 1;
5462 var->l = (ar >> 13) & 1;
5463 var->db = (ar >> 14) & 1;
5464 var->g = (ar >> 15) & 1;
5467 static u64 vmx_get_segment_base(struct kvm_vcpu *vcpu, int seg)
5469 struct kvm_segment s;
5471 if (to_vmx(vcpu)->rmode.vm86_active) {
5472 vmx_get_segment(vcpu, &s, seg);
5473 return s.base;
5475 return vmx_read_guest_seg_base(to_vmx(vcpu), seg);
5478 static int vmx_get_cpl(struct kvm_vcpu *vcpu)
5480 struct vcpu_vmx *vmx = to_vmx(vcpu);
5482 if (unlikely(vmx->rmode.vm86_active))
5483 return 0;
5484 else {
5485 int ar = vmx_read_guest_seg_ar(vmx, VCPU_SREG_SS);
5486 return VMX_AR_DPL(ar);
5490 static u32 vmx_segment_access_rights(struct kvm_segment *var)
5492 u32 ar;
5494 if (var->unusable || !var->present)
5495 ar = 1 << 16;
5496 else {
5497 ar = var->type & 15;
5498 ar |= (var->s & 1) << 4;
5499 ar |= (var->dpl & 3) << 5;
5500 ar |= (var->present & 1) << 7;
5501 ar |= (var->avl & 1) << 12;
5502 ar |= (var->l & 1) << 13;
5503 ar |= (var->db & 1) << 14;
5504 ar |= (var->g & 1) << 15;
5507 return ar;
5510 static void vmx_set_segment(struct kvm_vcpu *vcpu,
5511 struct kvm_segment *var, int seg)
5513 struct vcpu_vmx *vmx = to_vmx(vcpu);
5514 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5516 vmx_segment_cache_clear(vmx);
5518 if (vmx->rmode.vm86_active && seg != VCPU_SREG_LDTR) {
5519 vmx->rmode.segs[seg] = *var;
5520 if (seg == VCPU_SREG_TR)
5521 vmcs_write16(sf->selector, var->selector);
5522 else if (var->s)
5523 fix_rmode_seg(seg, &vmx->rmode.segs[seg]);
5524 goto out;
5527 vmcs_writel(sf->base, var->base);
5528 vmcs_write32(sf->limit, var->limit);
5529 vmcs_write16(sf->selector, var->selector);
5532 * Fix the "Accessed" bit in AR field of segment registers for older
5533 * qemu binaries.
5534 * IA32 arch specifies that at the time of processor reset the
5535 * "Accessed" bit in the AR field of segment registers is 1. And qemu
5536 * is setting it to 0 in the userland code. This causes invalid guest
5537 * state vmexit when "unrestricted guest" mode is turned on.
5538 * Fix for this setup issue in cpu_reset is being pushed in the qemu
5539 * tree. Newer qemu binaries with that qemu fix would not need this
5540 * kvm hack.
5542 if (enable_unrestricted_guest && (seg != VCPU_SREG_LDTR))
5543 var->type |= 0x1; /* Accessed */
5545 vmcs_write32(sf->ar_bytes, vmx_segment_access_rights(var));
5547 out:
5548 vmx->emulation_required = emulation_required(vcpu);
5551 static void vmx_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
5553 u32 ar = vmx_read_guest_seg_ar(to_vmx(vcpu), VCPU_SREG_CS);
5555 *db = (ar >> 14) & 1;
5556 *l = (ar >> 13) & 1;
5559 static void vmx_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5561 dt->size = vmcs_read32(GUEST_IDTR_LIMIT);
5562 dt->address = vmcs_readl(GUEST_IDTR_BASE);
5565 static void vmx_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5567 vmcs_write32(GUEST_IDTR_LIMIT, dt->size);
5568 vmcs_writel(GUEST_IDTR_BASE, dt->address);
5571 static void vmx_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5573 dt->size = vmcs_read32(GUEST_GDTR_LIMIT);
5574 dt->address = vmcs_readl(GUEST_GDTR_BASE);
5577 static void vmx_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
5579 vmcs_write32(GUEST_GDTR_LIMIT, dt->size);
5580 vmcs_writel(GUEST_GDTR_BASE, dt->address);
5583 static bool rmode_segment_valid(struct kvm_vcpu *vcpu, int seg)
5585 struct kvm_segment var;
5586 u32 ar;
5588 vmx_get_segment(vcpu, &var, seg);
5589 var.dpl = 0x3;
5590 if (seg == VCPU_SREG_CS)
5591 var.type = 0x3;
5592 ar = vmx_segment_access_rights(&var);
5594 if (var.base != (var.selector << 4))
5595 return false;
5596 if (var.limit != 0xffff)
5597 return false;
5598 if (ar != 0xf3)
5599 return false;
5601 return true;
5604 static bool code_segment_valid(struct kvm_vcpu *vcpu)
5606 struct kvm_segment cs;
5607 unsigned int cs_rpl;
5609 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5610 cs_rpl = cs.selector & SEGMENT_RPL_MASK;
5612 if (cs.unusable)
5613 return false;
5614 if (~cs.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_ACCESSES_MASK))
5615 return false;
5616 if (!cs.s)
5617 return false;
5618 if (cs.type & VMX_AR_TYPE_WRITEABLE_MASK) {
5619 if (cs.dpl > cs_rpl)
5620 return false;
5621 } else {
5622 if (cs.dpl != cs_rpl)
5623 return false;
5625 if (!cs.present)
5626 return false;
5628 /* TODO: Add Reserved field check, this'll require a new member in the kvm_segment_field structure */
5629 return true;
5632 static bool stack_segment_valid(struct kvm_vcpu *vcpu)
5634 struct kvm_segment ss;
5635 unsigned int ss_rpl;
5637 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5638 ss_rpl = ss.selector & SEGMENT_RPL_MASK;
5640 if (ss.unusable)
5641 return true;
5642 if (ss.type != 3 && ss.type != 7)
5643 return false;
5644 if (!ss.s)
5645 return false;
5646 if (ss.dpl != ss_rpl) /* DPL != RPL */
5647 return false;
5648 if (!ss.present)
5649 return false;
5651 return true;
5654 static bool data_segment_valid(struct kvm_vcpu *vcpu, int seg)
5656 struct kvm_segment var;
5657 unsigned int rpl;
5659 vmx_get_segment(vcpu, &var, seg);
5660 rpl = var.selector & SEGMENT_RPL_MASK;
5662 if (var.unusable)
5663 return true;
5664 if (!var.s)
5665 return false;
5666 if (!var.present)
5667 return false;
5668 if (~var.type & (VMX_AR_TYPE_CODE_MASK|VMX_AR_TYPE_WRITEABLE_MASK)) {
5669 if (var.dpl < rpl) /* DPL < RPL */
5670 return false;
5673 /* TODO: Add other members to kvm_segment_field to allow checking for other access
5674 * rights flags
5676 return true;
5679 static bool tr_valid(struct kvm_vcpu *vcpu)
5681 struct kvm_segment tr;
5683 vmx_get_segment(vcpu, &tr, VCPU_SREG_TR);
5685 if (tr.unusable)
5686 return false;
5687 if (tr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5688 return false;
5689 if (tr.type != 3 && tr.type != 11) /* TODO: Check if guest is in IA32e mode */
5690 return false;
5691 if (!tr.present)
5692 return false;
5694 return true;
5697 static bool ldtr_valid(struct kvm_vcpu *vcpu)
5699 struct kvm_segment ldtr;
5701 vmx_get_segment(vcpu, &ldtr, VCPU_SREG_LDTR);
5703 if (ldtr.unusable)
5704 return true;
5705 if (ldtr.selector & SEGMENT_TI_MASK) /* TI = 1 */
5706 return false;
5707 if (ldtr.type != 2)
5708 return false;
5709 if (!ldtr.present)
5710 return false;
5712 return true;
5715 static bool cs_ss_rpl_check(struct kvm_vcpu *vcpu)
5717 struct kvm_segment cs, ss;
5719 vmx_get_segment(vcpu, &cs, VCPU_SREG_CS);
5720 vmx_get_segment(vcpu, &ss, VCPU_SREG_SS);
5722 return ((cs.selector & SEGMENT_RPL_MASK) ==
5723 (ss.selector & SEGMENT_RPL_MASK));
5727 * Check if guest state is valid. Returns true if valid, false if
5728 * not.
5729 * We assume that registers are always usable
5731 static bool guest_state_valid(struct kvm_vcpu *vcpu)
5733 if (enable_unrestricted_guest)
5734 return true;
5736 /* real mode guest state checks */
5737 if (!is_protmode(vcpu) || (vmx_get_rflags(vcpu) & X86_EFLAGS_VM)) {
5738 if (!rmode_segment_valid(vcpu, VCPU_SREG_CS))
5739 return false;
5740 if (!rmode_segment_valid(vcpu, VCPU_SREG_SS))
5741 return false;
5742 if (!rmode_segment_valid(vcpu, VCPU_SREG_DS))
5743 return false;
5744 if (!rmode_segment_valid(vcpu, VCPU_SREG_ES))
5745 return false;
5746 if (!rmode_segment_valid(vcpu, VCPU_SREG_FS))
5747 return false;
5748 if (!rmode_segment_valid(vcpu, VCPU_SREG_GS))
5749 return false;
5750 } else {
5751 /* protected mode guest state checks */
5752 if (!cs_ss_rpl_check(vcpu))
5753 return false;
5754 if (!code_segment_valid(vcpu))
5755 return false;
5756 if (!stack_segment_valid(vcpu))
5757 return false;
5758 if (!data_segment_valid(vcpu, VCPU_SREG_DS))
5759 return false;
5760 if (!data_segment_valid(vcpu, VCPU_SREG_ES))
5761 return false;
5762 if (!data_segment_valid(vcpu, VCPU_SREG_FS))
5763 return false;
5764 if (!data_segment_valid(vcpu, VCPU_SREG_GS))
5765 return false;
5766 if (!tr_valid(vcpu))
5767 return false;
5768 if (!ldtr_valid(vcpu))
5769 return false;
5771 /* TODO:
5772 * - Add checks on RIP
5773 * - Add checks on RFLAGS
5776 return true;
5779 static bool page_address_valid(struct kvm_vcpu *vcpu, gpa_t gpa)
5781 return PAGE_ALIGNED(gpa) && !(gpa >> cpuid_maxphyaddr(vcpu));
5784 static int init_rmode_tss(struct kvm *kvm)
5786 gfn_t fn;
5787 u16 data = 0;
5788 int idx, r;
5790 idx = srcu_read_lock(&kvm->srcu);
5791 fn = to_kvm_vmx(kvm)->tss_addr >> PAGE_SHIFT;
5792 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5793 if (r < 0)
5794 goto out;
5795 data = TSS_BASE_SIZE + TSS_REDIRECTION_SIZE;
5796 r = kvm_write_guest_page(kvm, fn++, &data,
5797 TSS_IOPB_BASE_OFFSET, sizeof(u16));
5798 if (r < 0)
5799 goto out;
5800 r = kvm_clear_guest_page(kvm, fn++, 0, PAGE_SIZE);
5801 if (r < 0)
5802 goto out;
5803 r = kvm_clear_guest_page(kvm, fn, 0, PAGE_SIZE);
5804 if (r < 0)
5805 goto out;
5806 data = ~0;
5807 r = kvm_write_guest_page(kvm, fn, &data,
5808 RMODE_TSS_SIZE - 2 * PAGE_SIZE - 1,
5809 sizeof(u8));
5810 out:
5811 srcu_read_unlock(&kvm->srcu, idx);
5812 return r;
5815 static int init_rmode_identity_map(struct kvm *kvm)
5817 struct kvm_vmx *kvm_vmx = to_kvm_vmx(kvm);
5818 int i, idx, r = 0;
5819 kvm_pfn_t identity_map_pfn;
5820 u32 tmp;
5822 /* Protect kvm_vmx->ept_identity_pagetable_done. */
5823 mutex_lock(&kvm->slots_lock);
5825 if (likely(kvm_vmx->ept_identity_pagetable_done))
5826 goto out2;
5828 if (!kvm_vmx->ept_identity_map_addr)
5829 kvm_vmx->ept_identity_map_addr = VMX_EPT_IDENTITY_PAGETABLE_ADDR;
5830 identity_map_pfn = kvm_vmx->ept_identity_map_addr >> PAGE_SHIFT;
5832 r = __x86_set_memory_region(kvm, IDENTITY_PAGETABLE_PRIVATE_MEMSLOT,
5833 kvm_vmx->ept_identity_map_addr, PAGE_SIZE);
5834 if (r < 0)
5835 goto out2;
5837 idx = srcu_read_lock(&kvm->srcu);
5838 r = kvm_clear_guest_page(kvm, identity_map_pfn, 0, PAGE_SIZE);
5839 if (r < 0)
5840 goto out;
5841 /* Set up identity-mapping pagetable for EPT in real mode */
5842 for (i = 0; i < PT32_ENT_PER_PAGE; i++) {
5843 tmp = (i << 22) + (_PAGE_PRESENT | _PAGE_RW | _PAGE_USER |
5844 _PAGE_ACCESSED | _PAGE_DIRTY | _PAGE_PSE);
5845 r = kvm_write_guest_page(kvm, identity_map_pfn,
5846 &tmp, i * sizeof(tmp), sizeof(tmp));
5847 if (r < 0)
5848 goto out;
5850 kvm_vmx->ept_identity_pagetable_done = true;
5852 out:
5853 srcu_read_unlock(&kvm->srcu, idx);
5855 out2:
5856 mutex_unlock(&kvm->slots_lock);
5857 return r;
5860 static void seg_setup(int seg)
5862 const struct kvm_vmx_segment_field *sf = &kvm_vmx_segment_fields[seg];
5863 unsigned int ar;
5865 vmcs_write16(sf->selector, 0);
5866 vmcs_writel(sf->base, 0);
5867 vmcs_write32(sf->limit, 0xffff);
5868 ar = 0x93;
5869 if (seg == VCPU_SREG_CS)
5870 ar |= 0x08; /* code segment */
5872 vmcs_write32(sf->ar_bytes, ar);
5875 static int alloc_apic_access_page(struct kvm *kvm)
5877 struct page *page;
5878 int r = 0;
5880 mutex_lock(&kvm->slots_lock);
5881 if (kvm->arch.apic_access_page_done)
5882 goto out;
5883 r = __x86_set_memory_region(kvm, APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
5884 APIC_DEFAULT_PHYS_BASE, PAGE_SIZE);
5885 if (r)
5886 goto out;
5888 page = gfn_to_page(kvm, APIC_DEFAULT_PHYS_BASE >> PAGE_SHIFT);
5889 if (is_error_page(page)) {
5890 r = -EFAULT;
5891 goto out;
5895 * Do not pin the page in memory, so that memory hot-unplug
5896 * is able to migrate it.
5898 put_page(page);
5899 kvm->arch.apic_access_page_done = true;
5900 out:
5901 mutex_unlock(&kvm->slots_lock);
5902 return r;
5905 static int allocate_vpid(void)
5907 int vpid;
5909 if (!enable_vpid)
5910 return 0;
5911 spin_lock(&vmx_vpid_lock);
5912 vpid = find_first_zero_bit(vmx_vpid_bitmap, VMX_NR_VPIDS);
5913 if (vpid < VMX_NR_VPIDS)
5914 __set_bit(vpid, vmx_vpid_bitmap);
5915 else
5916 vpid = 0;
5917 spin_unlock(&vmx_vpid_lock);
5918 return vpid;
5921 static void free_vpid(int vpid)
5923 if (!enable_vpid || vpid == 0)
5924 return;
5925 spin_lock(&vmx_vpid_lock);
5926 __clear_bit(vpid, vmx_vpid_bitmap);
5927 spin_unlock(&vmx_vpid_lock);
5930 static __always_inline void vmx_disable_intercept_for_msr(unsigned long *msr_bitmap,
5931 u32 msr, int type)
5933 int f = sizeof(unsigned long);
5935 if (!cpu_has_vmx_msr_bitmap())
5936 return;
5938 if (static_branch_unlikely(&enable_evmcs))
5939 evmcs_touch_msr_bitmap();
5942 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5943 * have the write-low and read-high bitmap offsets the wrong way round.
5944 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5946 if (msr <= 0x1fff) {
5947 if (type & MSR_TYPE_R)
5948 /* read-low */
5949 __clear_bit(msr, msr_bitmap + 0x000 / f);
5951 if (type & MSR_TYPE_W)
5952 /* write-low */
5953 __clear_bit(msr, msr_bitmap + 0x800 / f);
5955 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5956 msr &= 0x1fff;
5957 if (type & MSR_TYPE_R)
5958 /* read-high */
5959 __clear_bit(msr, msr_bitmap + 0x400 / f);
5961 if (type & MSR_TYPE_W)
5962 /* write-high */
5963 __clear_bit(msr, msr_bitmap + 0xc00 / f);
5968 static __always_inline void vmx_enable_intercept_for_msr(unsigned long *msr_bitmap,
5969 u32 msr, int type)
5971 int f = sizeof(unsigned long);
5973 if (!cpu_has_vmx_msr_bitmap())
5974 return;
5976 if (static_branch_unlikely(&enable_evmcs))
5977 evmcs_touch_msr_bitmap();
5980 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
5981 * have the write-low and read-high bitmap offsets the wrong way round.
5982 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
5984 if (msr <= 0x1fff) {
5985 if (type & MSR_TYPE_R)
5986 /* read-low */
5987 __set_bit(msr, msr_bitmap + 0x000 / f);
5989 if (type & MSR_TYPE_W)
5990 /* write-low */
5991 __set_bit(msr, msr_bitmap + 0x800 / f);
5993 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
5994 msr &= 0x1fff;
5995 if (type & MSR_TYPE_R)
5996 /* read-high */
5997 __set_bit(msr, msr_bitmap + 0x400 / f);
5999 if (type & MSR_TYPE_W)
6000 /* write-high */
6001 __set_bit(msr, msr_bitmap + 0xc00 / f);
6006 static __always_inline void vmx_set_intercept_for_msr(unsigned long *msr_bitmap,
6007 u32 msr, int type, bool value)
6009 if (value)
6010 vmx_enable_intercept_for_msr(msr_bitmap, msr, type);
6011 else
6012 vmx_disable_intercept_for_msr(msr_bitmap, msr, type);
6016 * If a msr is allowed by L0, we should check whether it is allowed by L1.
6017 * The corresponding bit will be cleared unless both of L0 and L1 allow it.
6019 static void nested_vmx_disable_intercept_for_msr(unsigned long *msr_bitmap_l1,
6020 unsigned long *msr_bitmap_nested,
6021 u32 msr, int type)
6023 int f = sizeof(unsigned long);
6026 * See Intel PRM Vol. 3, 20.6.9 (MSR-Bitmap Address). Early manuals
6027 * have the write-low and read-high bitmap offsets the wrong way round.
6028 * We can control MSRs 0x00000000-0x00001fff and 0xc0000000-0xc0001fff.
6030 if (msr <= 0x1fff) {
6031 if (type & MSR_TYPE_R &&
6032 !test_bit(msr, msr_bitmap_l1 + 0x000 / f))
6033 /* read-low */
6034 __clear_bit(msr, msr_bitmap_nested + 0x000 / f);
6036 if (type & MSR_TYPE_W &&
6037 !test_bit(msr, msr_bitmap_l1 + 0x800 / f))
6038 /* write-low */
6039 __clear_bit(msr, msr_bitmap_nested + 0x800 / f);
6041 } else if ((msr >= 0xc0000000) && (msr <= 0xc0001fff)) {
6042 msr &= 0x1fff;
6043 if (type & MSR_TYPE_R &&
6044 !test_bit(msr, msr_bitmap_l1 + 0x400 / f))
6045 /* read-high */
6046 __clear_bit(msr, msr_bitmap_nested + 0x400 / f);
6048 if (type & MSR_TYPE_W &&
6049 !test_bit(msr, msr_bitmap_l1 + 0xc00 / f))
6050 /* write-high */
6051 __clear_bit(msr, msr_bitmap_nested + 0xc00 / f);
6056 static u8 vmx_msr_bitmap_mode(struct kvm_vcpu *vcpu)
6058 u8 mode = 0;
6060 if (cpu_has_secondary_exec_ctrls() &&
6061 (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) &
6062 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) {
6063 mode |= MSR_BITMAP_MODE_X2APIC;
6064 if (enable_apicv && kvm_vcpu_apicv_active(vcpu))
6065 mode |= MSR_BITMAP_MODE_X2APIC_APICV;
6068 return mode;
6071 #define X2APIC_MSR(r) (APIC_BASE_MSR + ((r) >> 4))
6073 static void vmx_update_msr_bitmap_x2apic(unsigned long *msr_bitmap,
6074 u8 mode)
6076 int msr;
6078 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
6079 unsigned word = msr / BITS_PER_LONG;
6080 msr_bitmap[word] = (mode & MSR_BITMAP_MODE_X2APIC_APICV) ? 0 : ~0;
6081 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
6084 if (mode & MSR_BITMAP_MODE_X2APIC) {
6086 * TPR reads and writes can be virtualized even if virtual interrupt
6087 * delivery is not in use.
6089 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TASKPRI), MSR_TYPE_RW);
6090 if (mode & MSR_BITMAP_MODE_X2APIC_APICV) {
6091 vmx_enable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_TMCCT), MSR_TYPE_R);
6092 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_EOI), MSR_TYPE_W);
6093 vmx_disable_intercept_for_msr(msr_bitmap, X2APIC_MSR(APIC_SELF_IPI), MSR_TYPE_W);
6098 static void vmx_update_msr_bitmap(struct kvm_vcpu *vcpu)
6100 struct vcpu_vmx *vmx = to_vmx(vcpu);
6101 unsigned long *msr_bitmap = vmx->vmcs01.msr_bitmap;
6102 u8 mode = vmx_msr_bitmap_mode(vcpu);
6103 u8 changed = mode ^ vmx->msr_bitmap_mode;
6105 if (!changed)
6106 return;
6108 if (changed & (MSR_BITMAP_MODE_X2APIC | MSR_BITMAP_MODE_X2APIC_APICV))
6109 vmx_update_msr_bitmap_x2apic(msr_bitmap, mode);
6111 vmx->msr_bitmap_mode = mode;
6114 static bool vmx_get_enable_apicv(struct kvm_vcpu *vcpu)
6116 return enable_apicv;
6119 static void nested_mark_vmcs12_pages_dirty(struct kvm_vcpu *vcpu)
6121 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
6122 gfn_t gfn;
6125 * Don't need to mark the APIC access page dirty; it is never
6126 * written to by the CPU during APIC virtualization.
6129 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
6130 gfn = vmcs12->virtual_apic_page_addr >> PAGE_SHIFT;
6131 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6134 if (nested_cpu_has_posted_intr(vmcs12)) {
6135 gfn = vmcs12->posted_intr_desc_addr >> PAGE_SHIFT;
6136 kvm_vcpu_mark_page_dirty(vcpu, gfn);
6141 static void vmx_complete_nested_posted_interrupt(struct kvm_vcpu *vcpu)
6143 struct vcpu_vmx *vmx = to_vmx(vcpu);
6144 int max_irr;
6145 void *vapic_page;
6146 u16 status;
6148 if (!vmx->nested.pi_desc || !vmx->nested.pi_pending)
6149 return;
6151 vmx->nested.pi_pending = false;
6152 if (!pi_test_and_clear_on(vmx->nested.pi_desc))
6153 return;
6155 max_irr = find_last_bit((unsigned long *)vmx->nested.pi_desc->pir, 256);
6156 if (max_irr != 256) {
6157 vapic_page = kmap(vmx->nested.virtual_apic_page);
6158 __kvm_apic_update_irr(vmx->nested.pi_desc->pir,
6159 vapic_page, &max_irr);
6160 kunmap(vmx->nested.virtual_apic_page);
6162 status = vmcs_read16(GUEST_INTR_STATUS);
6163 if ((u8)max_irr > ((u8)status & 0xff)) {
6164 status &= ~0xff;
6165 status |= (u8)max_irr;
6166 vmcs_write16(GUEST_INTR_STATUS, status);
6170 nested_mark_vmcs12_pages_dirty(vcpu);
6173 static u8 vmx_get_rvi(void)
6175 return vmcs_read16(GUEST_INTR_STATUS) & 0xff;
6178 static bool vmx_guest_apic_has_interrupt(struct kvm_vcpu *vcpu)
6180 struct vcpu_vmx *vmx = to_vmx(vcpu);
6181 void *vapic_page;
6182 u32 vppr;
6183 int rvi;
6185 if (WARN_ON_ONCE(!is_guest_mode(vcpu)) ||
6186 !nested_cpu_has_vid(get_vmcs12(vcpu)) ||
6187 WARN_ON_ONCE(!vmx->nested.virtual_apic_page))
6188 return false;
6190 rvi = vmx_get_rvi();
6192 vapic_page = kmap(vmx->nested.virtual_apic_page);
6193 vppr = *((u32 *)(vapic_page + APIC_PROCPRI));
6194 kunmap(vmx->nested.virtual_apic_page);
6196 return ((rvi & 0xf0) > (vppr & 0xf0));
6199 static inline bool kvm_vcpu_trigger_posted_interrupt(struct kvm_vcpu *vcpu,
6200 bool nested)
6202 #ifdef CONFIG_SMP
6203 int pi_vec = nested ? POSTED_INTR_NESTED_VECTOR : POSTED_INTR_VECTOR;
6205 if (vcpu->mode == IN_GUEST_MODE) {
6207 * The vector of interrupt to be delivered to vcpu had
6208 * been set in PIR before this function.
6210 * Following cases will be reached in this block, and
6211 * we always send a notification event in all cases as
6212 * explained below.
6214 * Case 1: vcpu keeps in non-root mode. Sending a
6215 * notification event posts the interrupt to vcpu.
6217 * Case 2: vcpu exits to root mode and is still
6218 * runnable. PIR will be synced to vIRR before the
6219 * next vcpu entry. Sending a notification event in
6220 * this case has no effect, as vcpu is not in root
6221 * mode.
6223 * Case 3: vcpu exits to root mode and is blocked.
6224 * vcpu_block() has already synced PIR to vIRR and
6225 * never blocks vcpu if vIRR is not cleared. Therefore,
6226 * a blocked vcpu here does not wait for any requested
6227 * interrupts in PIR, and sending a notification event
6228 * which has no effect is safe here.
6231 apic->send_IPI_mask(get_cpu_mask(vcpu->cpu), pi_vec);
6232 return true;
6234 #endif
6235 return false;
6238 static int vmx_deliver_nested_posted_interrupt(struct kvm_vcpu *vcpu,
6239 int vector)
6241 struct vcpu_vmx *vmx = to_vmx(vcpu);
6243 if (is_guest_mode(vcpu) &&
6244 vector == vmx->nested.posted_intr_nv) {
6246 * If a posted intr is not recognized by hardware,
6247 * we will accomplish it in the next vmentry.
6249 vmx->nested.pi_pending = true;
6250 kvm_make_request(KVM_REQ_EVENT, vcpu);
6251 /* the PIR and ON have been set by L1. */
6252 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, true))
6253 kvm_vcpu_kick(vcpu);
6254 return 0;
6256 return -1;
6259 * Send interrupt to vcpu via posted interrupt way.
6260 * 1. If target vcpu is running(non-root mode), send posted interrupt
6261 * notification to vcpu and hardware will sync PIR to vIRR atomically.
6262 * 2. If target vcpu isn't running(root mode), kick it to pick up the
6263 * interrupt from PIR in next vmentry.
6265 static void vmx_deliver_posted_interrupt(struct kvm_vcpu *vcpu, int vector)
6267 struct vcpu_vmx *vmx = to_vmx(vcpu);
6268 int r;
6270 r = vmx_deliver_nested_posted_interrupt(vcpu, vector);
6271 if (!r)
6272 return;
6274 if (pi_test_and_set_pir(vector, &vmx->pi_desc))
6275 return;
6277 /* If a previous notification has sent the IPI, nothing to do. */
6278 if (pi_test_and_set_on(&vmx->pi_desc))
6279 return;
6281 if (!kvm_vcpu_trigger_posted_interrupt(vcpu, false))
6282 kvm_vcpu_kick(vcpu);
6286 * Set up the vmcs's constant host-state fields, i.e., host-state fields that
6287 * will not change in the lifetime of the guest.
6288 * Note that host-state that does change is set elsewhere. E.g., host-state
6289 * that is set differently for each CPU is set in vmx_vcpu_load(), not here.
6291 static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
6293 u32 low32, high32;
6294 unsigned long tmpl;
6295 struct desc_ptr dt;
6296 unsigned long cr0, cr3, cr4;
6298 cr0 = read_cr0();
6299 WARN_ON(cr0 & X86_CR0_TS);
6300 vmcs_writel(HOST_CR0, cr0); /* 22.2.3 */
6303 * Save the most likely value for this task's CR3 in the VMCS.
6304 * We can't use __get_current_cr3_fast() because we're not atomic.
6306 cr3 = __read_cr3();
6307 vmcs_writel(HOST_CR3, cr3); /* 22.2.3 FIXME: shadow tables */
6308 vmx->loaded_vmcs->host_state.cr3 = cr3;
6310 /* Save the most likely value for this task's CR4 in the VMCS. */
6311 cr4 = cr4_read_shadow();
6312 vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
6313 vmx->loaded_vmcs->host_state.cr4 = cr4;
6315 vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
6316 #ifdef CONFIG_X86_64
6318 * Load null selectors, so we can avoid reloading them in
6319 * vmx_prepare_switch_to_host(), in case userspace uses
6320 * the null selectors too (the expected case).
6322 vmcs_write16(HOST_DS_SELECTOR, 0);
6323 vmcs_write16(HOST_ES_SELECTOR, 0);
6324 #else
6325 vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6326 vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6327 #endif
6328 vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
6329 vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
6331 store_idt(&dt);
6332 vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
6333 vmx->host_idt_base = dt.address;
6335 vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
6337 rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
6338 vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
6339 rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
6340 vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
6342 if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
6343 rdmsr(MSR_IA32_CR_PAT, low32, high32);
6344 vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
6348 static void set_cr4_guest_host_mask(struct vcpu_vmx *vmx)
6350 vmx->vcpu.arch.cr4_guest_owned_bits = KVM_CR4_GUEST_OWNED_BITS;
6351 if (enable_ept)
6352 vmx->vcpu.arch.cr4_guest_owned_bits |= X86_CR4_PGE;
6353 if (is_guest_mode(&vmx->vcpu))
6354 vmx->vcpu.arch.cr4_guest_owned_bits &=
6355 ~get_vmcs12(&vmx->vcpu)->cr4_guest_host_mask;
6356 vmcs_writel(CR4_GUEST_HOST_MASK, ~vmx->vcpu.arch.cr4_guest_owned_bits);
6359 static u32 vmx_pin_based_exec_ctrl(struct vcpu_vmx *vmx)
6361 u32 pin_based_exec_ctrl = vmcs_config.pin_based_exec_ctrl;
6363 if (!kvm_vcpu_apicv_active(&vmx->vcpu))
6364 pin_based_exec_ctrl &= ~PIN_BASED_POSTED_INTR;
6366 if (!enable_vnmi)
6367 pin_based_exec_ctrl &= ~PIN_BASED_VIRTUAL_NMIS;
6369 /* Enable the preemption timer dynamically */
6370 pin_based_exec_ctrl &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
6371 return pin_based_exec_ctrl;
6374 static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
6376 struct vcpu_vmx *vmx = to_vmx(vcpu);
6378 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6379 if (cpu_has_secondary_exec_ctrls()) {
6380 if (kvm_vcpu_apicv_active(vcpu))
6381 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
6382 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6383 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6384 else
6385 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
6386 SECONDARY_EXEC_APIC_REGISTER_VIRT |
6387 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6390 if (cpu_has_vmx_msr_bitmap())
6391 vmx_update_msr_bitmap(vcpu);
6394 static u32 vmx_exec_control(struct vcpu_vmx *vmx)
6396 u32 exec_control = vmcs_config.cpu_based_exec_ctrl;
6398 if (vmx->vcpu.arch.switch_db_regs & KVM_DEBUGREG_WONT_EXIT)
6399 exec_control &= ~CPU_BASED_MOV_DR_EXITING;
6401 if (!cpu_need_tpr_shadow(&vmx->vcpu)) {
6402 exec_control &= ~CPU_BASED_TPR_SHADOW;
6403 #ifdef CONFIG_X86_64
6404 exec_control |= CPU_BASED_CR8_STORE_EXITING |
6405 CPU_BASED_CR8_LOAD_EXITING;
6406 #endif
6408 if (!enable_ept)
6409 exec_control |= CPU_BASED_CR3_STORE_EXITING |
6410 CPU_BASED_CR3_LOAD_EXITING |
6411 CPU_BASED_INVLPG_EXITING;
6412 if (kvm_mwait_in_guest(vmx->vcpu.kvm))
6413 exec_control &= ~(CPU_BASED_MWAIT_EXITING |
6414 CPU_BASED_MONITOR_EXITING);
6415 if (kvm_hlt_in_guest(vmx->vcpu.kvm))
6416 exec_control &= ~CPU_BASED_HLT_EXITING;
6417 return exec_control;
6420 static bool vmx_rdrand_supported(void)
6422 return vmcs_config.cpu_based_2nd_exec_ctrl &
6423 SECONDARY_EXEC_RDRAND_EXITING;
6426 static bool vmx_rdseed_supported(void)
6428 return vmcs_config.cpu_based_2nd_exec_ctrl &
6429 SECONDARY_EXEC_RDSEED_EXITING;
6432 static void vmx_compute_secondary_exec_control(struct vcpu_vmx *vmx)
6434 struct kvm_vcpu *vcpu = &vmx->vcpu;
6436 u32 exec_control = vmcs_config.cpu_based_2nd_exec_ctrl;
6438 if (!cpu_need_virtualize_apic_accesses(vcpu))
6439 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
6440 if (vmx->vpid == 0)
6441 exec_control &= ~SECONDARY_EXEC_ENABLE_VPID;
6442 if (!enable_ept) {
6443 exec_control &= ~SECONDARY_EXEC_ENABLE_EPT;
6444 enable_unrestricted_guest = 0;
6446 if (!enable_unrestricted_guest)
6447 exec_control &= ~SECONDARY_EXEC_UNRESTRICTED_GUEST;
6448 if (kvm_pause_in_guest(vmx->vcpu.kvm))
6449 exec_control &= ~SECONDARY_EXEC_PAUSE_LOOP_EXITING;
6450 if (!kvm_vcpu_apicv_active(vcpu))
6451 exec_control &= ~(SECONDARY_EXEC_APIC_REGISTER_VIRT |
6452 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
6453 exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
6455 /* SECONDARY_EXEC_DESC is enabled/disabled on writes to CR4.UMIP,
6456 * in vmx_set_cr4. */
6457 exec_control &= ~SECONDARY_EXEC_DESC;
6459 /* SECONDARY_EXEC_SHADOW_VMCS is enabled when L1 executes VMPTRLD
6460 (handle_vmptrld).
6461 We can NOT enable shadow_vmcs here because we don't have yet
6462 a current VMCS12
6464 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
6466 if (!enable_pml)
6467 exec_control &= ~SECONDARY_EXEC_ENABLE_PML;
6469 if (vmx_xsaves_supported()) {
6470 /* Exposing XSAVES only when XSAVE is exposed */
6471 bool xsaves_enabled =
6472 guest_cpuid_has(vcpu, X86_FEATURE_XSAVE) &&
6473 guest_cpuid_has(vcpu, X86_FEATURE_XSAVES);
6475 if (!xsaves_enabled)
6476 exec_control &= ~SECONDARY_EXEC_XSAVES;
6478 if (nested) {
6479 if (xsaves_enabled)
6480 vmx->nested.msrs.secondary_ctls_high |=
6481 SECONDARY_EXEC_XSAVES;
6482 else
6483 vmx->nested.msrs.secondary_ctls_high &=
6484 ~SECONDARY_EXEC_XSAVES;
6488 if (vmx_rdtscp_supported()) {
6489 bool rdtscp_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDTSCP);
6490 if (!rdtscp_enabled)
6491 exec_control &= ~SECONDARY_EXEC_RDTSCP;
6493 if (nested) {
6494 if (rdtscp_enabled)
6495 vmx->nested.msrs.secondary_ctls_high |=
6496 SECONDARY_EXEC_RDTSCP;
6497 else
6498 vmx->nested.msrs.secondary_ctls_high &=
6499 ~SECONDARY_EXEC_RDTSCP;
6503 if (vmx_invpcid_supported()) {
6504 /* Exposing INVPCID only when PCID is exposed */
6505 bool invpcid_enabled =
6506 guest_cpuid_has(vcpu, X86_FEATURE_INVPCID) &&
6507 guest_cpuid_has(vcpu, X86_FEATURE_PCID);
6509 if (!invpcid_enabled) {
6510 exec_control &= ~SECONDARY_EXEC_ENABLE_INVPCID;
6511 guest_cpuid_clear(vcpu, X86_FEATURE_INVPCID);
6514 if (nested) {
6515 if (invpcid_enabled)
6516 vmx->nested.msrs.secondary_ctls_high |=
6517 SECONDARY_EXEC_ENABLE_INVPCID;
6518 else
6519 vmx->nested.msrs.secondary_ctls_high &=
6520 ~SECONDARY_EXEC_ENABLE_INVPCID;
6524 if (vmx_rdrand_supported()) {
6525 bool rdrand_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDRAND);
6526 if (rdrand_enabled)
6527 exec_control &= ~SECONDARY_EXEC_RDRAND_EXITING;
6529 if (nested) {
6530 if (rdrand_enabled)
6531 vmx->nested.msrs.secondary_ctls_high |=
6532 SECONDARY_EXEC_RDRAND_EXITING;
6533 else
6534 vmx->nested.msrs.secondary_ctls_high &=
6535 ~SECONDARY_EXEC_RDRAND_EXITING;
6539 if (vmx_rdseed_supported()) {
6540 bool rdseed_enabled = guest_cpuid_has(vcpu, X86_FEATURE_RDSEED);
6541 if (rdseed_enabled)
6542 exec_control &= ~SECONDARY_EXEC_RDSEED_EXITING;
6544 if (nested) {
6545 if (rdseed_enabled)
6546 vmx->nested.msrs.secondary_ctls_high |=
6547 SECONDARY_EXEC_RDSEED_EXITING;
6548 else
6549 vmx->nested.msrs.secondary_ctls_high &=
6550 ~SECONDARY_EXEC_RDSEED_EXITING;
6554 vmx->secondary_exec_control = exec_control;
6557 static void ept_set_mmio_spte_mask(void)
6560 * EPT Misconfigurations can be generated if the value of bits 2:0
6561 * of an EPT paging-structure entry is 110b (write/execute).
6563 kvm_mmu_set_mmio_spte_mask(VMX_EPT_RWX_MASK,
6564 VMX_EPT_MISCONFIG_WX_VALUE);
6567 #define VMX_XSS_EXIT_BITMAP 0
6569 * Sets up the vmcs for emulated real mode.
6571 static void vmx_vcpu_setup(struct vcpu_vmx *vmx)
6573 int i;
6575 if (enable_shadow_vmcs) {
6577 * At vCPU creation, "VMWRITE to any supported field
6578 * in the VMCS" is supported, so use the more
6579 * permissive vmx_vmread_bitmap to specify both read
6580 * and write permissions for the shadow VMCS.
6582 vmcs_write64(VMREAD_BITMAP, __pa(vmx_vmread_bitmap));
6583 vmcs_write64(VMWRITE_BITMAP, __pa(vmx_vmread_bitmap));
6585 if (cpu_has_vmx_msr_bitmap())
6586 vmcs_write64(MSR_BITMAP, __pa(vmx->vmcs01.msr_bitmap));
6588 vmcs_write64(VMCS_LINK_POINTER, -1ull); /* 22.3.1.5 */
6590 /* Control */
6591 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
6592 vmx->hv_deadline_tsc = -1;
6594 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, vmx_exec_control(vmx));
6596 if (cpu_has_secondary_exec_ctrls()) {
6597 vmx_compute_secondary_exec_control(vmx);
6598 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
6599 vmx->secondary_exec_control);
6602 if (kvm_vcpu_apicv_active(&vmx->vcpu)) {
6603 vmcs_write64(EOI_EXIT_BITMAP0, 0);
6604 vmcs_write64(EOI_EXIT_BITMAP1, 0);
6605 vmcs_write64(EOI_EXIT_BITMAP2, 0);
6606 vmcs_write64(EOI_EXIT_BITMAP3, 0);
6608 vmcs_write16(GUEST_INTR_STATUS, 0);
6610 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_VECTOR);
6611 vmcs_write64(POSTED_INTR_DESC_ADDR, __pa((&vmx->pi_desc)));
6614 if (!kvm_pause_in_guest(vmx->vcpu.kvm)) {
6615 vmcs_write32(PLE_GAP, ple_gap);
6616 vmx->ple_window = ple_window;
6617 vmx->ple_window_dirty = true;
6620 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, 0);
6621 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, 0);
6622 vmcs_write32(CR3_TARGET_COUNT, 0); /* 22.2.1 */
6624 vmcs_write16(HOST_FS_SELECTOR, 0); /* 22.2.4 */
6625 vmcs_write16(HOST_GS_SELECTOR, 0); /* 22.2.4 */
6626 vmx_set_constant_host_state(vmx);
6627 vmcs_writel(HOST_FS_BASE, 0); /* 22.2.4 */
6628 vmcs_writel(HOST_GS_BASE, 0); /* 22.2.4 */
6630 if (cpu_has_vmx_vmfunc())
6631 vmcs_write64(VM_FUNCTION_CONTROL, 0);
6633 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
6634 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, 0);
6635 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
6636 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, 0);
6637 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
6639 if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT)
6640 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
6642 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) {
6643 u32 index = vmx_msr_index[i];
6644 u32 data_low, data_high;
6645 int j = vmx->nmsrs;
6647 if (rdmsr_safe(index, &data_low, &data_high) < 0)
6648 continue;
6649 if (wrmsr_safe(index, data_low, data_high) < 0)
6650 continue;
6651 vmx->guest_msrs[j].index = i;
6652 vmx->guest_msrs[j].data = 0;
6653 vmx->guest_msrs[j].mask = -1ull;
6654 ++vmx->nmsrs;
6657 vm_exit_controls_init(vmx, vmcs_config.vmexit_ctrl);
6659 /* 22.2.1, 20.8.1 */
6660 vm_entry_controls_init(vmx, vmcs_config.vmentry_ctrl);
6662 vmx->vcpu.arch.cr0_guest_owned_bits = X86_CR0_TS;
6663 vmcs_writel(CR0_GUEST_HOST_MASK, ~X86_CR0_TS);
6665 set_cr4_guest_host_mask(vmx);
6667 if (vmx_xsaves_supported())
6668 vmcs_write64(XSS_EXIT_BITMAP, VMX_XSS_EXIT_BITMAP);
6670 if (enable_pml) {
6671 ASSERT(vmx->pml_pg);
6672 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
6673 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
6676 if (cpu_has_vmx_encls_vmexit())
6677 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
6680 static void vmx_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
6682 struct vcpu_vmx *vmx = to_vmx(vcpu);
6683 struct msr_data apic_base_msr;
6684 u64 cr0;
6686 vmx->rmode.vm86_active = 0;
6687 vmx->spec_ctrl = 0;
6689 vcpu->arch.microcode_version = 0x100000000ULL;
6690 vmx->vcpu.arch.regs[VCPU_REGS_RDX] = get_rdx_init_val();
6691 kvm_set_cr8(vcpu, 0);
6693 if (!init_event) {
6694 apic_base_msr.data = APIC_DEFAULT_PHYS_BASE |
6695 MSR_IA32_APICBASE_ENABLE;
6696 if (kvm_vcpu_is_reset_bsp(vcpu))
6697 apic_base_msr.data |= MSR_IA32_APICBASE_BSP;
6698 apic_base_msr.host_initiated = true;
6699 kvm_set_apic_base(vcpu, &apic_base_msr);
6702 vmx_segment_cache_clear(vmx);
6704 seg_setup(VCPU_SREG_CS);
6705 vmcs_write16(GUEST_CS_SELECTOR, 0xf000);
6706 vmcs_writel(GUEST_CS_BASE, 0xffff0000ul);
6708 seg_setup(VCPU_SREG_DS);
6709 seg_setup(VCPU_SREG_ES);
6710 seg_setup(VCPU_SREG_FS);
6711 seg_setup(VCPU_SREG_GS);
6712 seg_setup(VCPU_SREG_SS);
6714 vmcs_write16(GUEST_TR_SELECTOR, 0);
6715 vmcs_writel(GUEST_TR_BASE, 0);
6716 vmcs_write32(GUEST_TR_LIMIT, 0xffff);
6717 vmcs_write32(GUEST_TR_AR_BYTES, 0x008b);
6719 vmcs_write16(GUEST_LDTR_SELECTOR, 0);
6720 vmcs_writel(GUEST_LDTR_BASE, 0);
6721 vmcs_write32(GUEST_LDTR_LIMIT, 0xffff);
6722 vmcs_write32(GUEST_LDTR_AR_BYTES, 0x00082);
6724 if (!init_event) {
6725 vmcs_write32(GUEST_SYSENTER_CS, 0);
6726 vmcs_writel(GUEST_SYSENTER_ESP, 0);
6727 vmcs_writel(GUEST_SYSENTER_EIP, 0);
6728 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
6731 kvm_set_rflags(vcpu, X86_EFLAGS_FIXED);
6732 kvm_rip_write(vcpu, 0xfff0);
6734 vmcs_writel(GUEST_GDTR_BASE, 0);
6735 vmcs_write32(GUEST_GDTR_LIMIT, 0xffff);
6737 vmcs_writel(GUEST_IDTR_BASE, 0);
6738 vmcs_write32(GUEST_IDTR_LIMIT, 0xffff);
6740 vmcs_write32(GUEST_ACTIVITY_STATE, GUEST_ACTIVITY_ACTIVE);
6741 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, 0);
6742 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, 0);
6743 if (kvm_mpx_supported())
6744 vmcs_write64(GUEST_BNDCFGS, 0);
6746 setup_msrs(vmx);
6748 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0); /* 22.2.1 */
6750 if (cpu_has_vmx_tpr_shadow() && !init_event) {
6751 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, 0);
6752 if (cpu_need_tpr_shadow(vcpu))
6753 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR,
6754 __pa(vcpu->arch.apic->regs));
6755 vmcs_write32(TPR_THRESHOLD, 0);
6758 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
6760 if (vmx->vpid != 0)
6761 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
6763 cr0 = X86_CR0_NW | X86_CR0_CD | X86_CR0_ET;
6764 vmx->vcpu.arch.cr0 = cr0;
6765 vmx_set_cr0(vcpu, cr0); /* enter rmode */
6766 vmx_set_cr4(vcpu, 0);
6767 vmx_set_efer(vcpu, 0);
6769 update_exception_bitmap(vcpu);
6771 vpid_sync_context(vmx->vpid);
6772 if (init_event)
6773 vmx_clear_hlt(vcpu);
6777 * In nested virtualization, check if L1 asked to exit on external interrupts.
6778 * For most existing hypervisors, this will always return true.
6780 static bool nested_exit_on_intr(struct kvm_vcpu *vcpu)
6782 return get_vmcs12(vcpu)->pin_based_vm_exec_control &
6783 PIN_BASED_EXT_INTR_MASK;
6787 * In nested virtualization, check if L1 has set
6788 * VM_EXIT_ACK_INTR_ON_EXIT
6790 static bool nested_exit_intr_ack_set(struct kvm_vcpu *vcpu)
6792 return get_vmcs12(vcpu)->vm_exit_controls &
6793 VM_EXIT_ACK_INTR_ON_EXIT;
6796 static bool nested_exit_on_nmi(struct kvm_vcpu *vcpu)
6798 return nested_cpu_has_nmi_exiting(get_vmcs12(vcpu));
6801 static void enable_irq_window(struct kvm_vcpu *vcpu)
6803 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6804 CPU_BASED_VIRTUAL_INTR_PENDING);
6807 static void enable_nmi_window(struct kvm_vcpu *vcpu)
6809 if (!enable_vnmi ||
6810 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_STI) {
6811 enable_irq_window(vcpu);
6812 return;
6815 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
6816 CPU_BASED_VIRTUAL_NMI_PENDING);
6819 static void vmx_inject_irq(struct kvm_vcpu *vcpu)
6821 struct vcpu_vmx *vmx = to_vmx(vcpu);
6822 uint32_t intr;
6823 int irq = vcpu->arch.interrupt.nr;
6825 trace_kvm_inj_virq(irq);
6827 ++vcpu->stat.irq_injections;
6828 if (vmx->rmode.vm86_active) {
6829 int inc_eip = 0;
6830 if (vcpu->arch.interrupt.soft)
6831 inc_eip = vcpu->arch.event_exit_inst_len;
6832 if (kvm_inject_realmode_interrupt(vcpu, irq, inc_eip) != EMULATE_DONE)
6833 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6834 return;
6836 intr = irq | INTR_INFO_VALID_MASK;
6837 if (vcpu->arch.interrupt.soft) {
6838 intr |= INTR_TYPE_SOFT_INTR;
6839 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
6840 vmx->vcpu.arch.event_exit_inst_len);
6841 } else
6842 intr |= INTR_TYPE_EXT_INTR;
6843 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, intr);
6845 vmx_clear_hlt(vcpu);
6848 static void vmx_inject_nmi(struct kvm_vcpu *vcpu)
6850 struct vcpu_vmx *vmx = to_vmx(vcpu);
6852 if (!enable_vnmi) {
6854 * Tracking the NMI-blocked state in software is built upon
6855 * finding the next open IRQ window. This, in turn, depends on
6856 * well-behaving guests: They have to keep IRQs disabled at
6857 * least as long as the NMI handler runs. Otherwise we may
6858 * cause NMI nesting, maybe breaking the guest. But as this is
6859 * highly unlikely, we can live with the residual risk.
6861 vmx->loaded_vmcs->soft_vnmi_blocked = 1;
6862 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6865 ++vcpu->stat.nmi_injections;
6866 vmx->loaded_vmcs->nmi_known_unmasked = false;
6868 if (vmx->rmode.vm86_active) {
6869 if (kvm_inject_realmode_interrupt(vcpu, NMI_VECTOR, 0) != EMULATE_DONE)
6870 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
6871 return;
6874 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
6875 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR);
6877 vmx_clear_hlt(vcpu);
6880 static bool vmx_get_nmi_mask(struct kvm_vcpu *vcpu)
6882 struct vcpu_vmx *vmx = to_vmx(vcpu);
6883 bool masked;
6885 if (!enable_vnmi)
6886 return vmx->loaded_vmcs->soft_vnmi_blocked;
6887 if (vmx->loaded_vmcs->nmi_known_unmasked)
6888 return false;
6889 masked = vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) & GUEST_INTR_STATE_NMI;
6890 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6891 return masked;
6894 static void vmx_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
6896 struct vcpu_vmx *vmx = to_vmx(vcpu);
6898 if (!enable_vnmi) {
6899 if (vmx->loaded_vmcs->soft_vnmi_blocked != masked) {
6900 vmx->loaded_vmcs->soft_vnmi_blocked = masked;
6901 vmx->loaded_vmcs->vnmi_blocked_time = 0;
6903 } else {
6904 vmx->loaded_vmcs->nmi_known_unmasked = !masked;
6905 if (masked)
6906 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
6907 GUEST_INTR_STATE_NMI);
6908 else
6909 vmcs_clear_bits(GUEST_INTERRUPTIBILITY_INFO,
6910 GUEST_INTR_STATE_NMI);
6914 static int vmx_nmi_allowed(struct kvm_vcpu *vcpu)
6916 if (to_vmx(vcpu)->nested.nested_run_pending)
6917 return 0;
6919 if (!enable_vnmi &&
6920 to_vmx(vcpu)->loaded_vmcs->soft_vnmi_blocked)
6921 return 0;
6923 return !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6924 (GUEST_INTR_STATE_MOV_SS | GUEST_INTR_STATE_STI
6925 | GUEST_INTR_STATE_NMI));
6928 static int vmx_interrupt_allowed(struct kvm_vcpu *vcpu)
6930 return (!to_vmx(vcpu)->nested.nested_run_pending &&
6931 vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF) &&
6932 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO) &
6933 (GUEST_INTR_STATE_STI | GUEST_INTR_STATE_MOV_SS));
6936 static int vmx_set_tss_addr(struct kvm *kvm, unsigned int addr)
6938 int ret;
6940 if (enable_unrestricted_guest)
6941 return 0;
6943 ret = x86_set_memory_region(kvm, TSS_PRIVATE_MEMSLOT, addr,
6944 PAGE_SIZE * 3);
6945 if (ret)
6946 return ret;
6947 to_kvm_vmx(kvm)->tss_addr = addr;
6948 return init_rmode_tss(kvm);
6951 static int vmx_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
6953 to_kvm_vmx(kvm)->ept_identity_map_addr = ident_addr;
6954 return 0;
6957 static bool rmode_exception(struct kvm_vcpu *vcpu, int vec)
6959 switch (vec) {
6960 case BP_VECTOR:
6962 * Update instruction length as we may reinject the exception
6963 * from user space while in guest debugging mode.
6965 to_vmx(vcpu)->vcpu.arch.event_exit_inst_len =
6966 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
6967 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
6968 return false;
6969 /* fall through */
6970 case DB_VECTOR:
6971 if (vcpu->guest_debug &
6972 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
6973 return false;
6974 /* fall through */
6975 case DE_VECTOR:
6976 case OF_VECTOR:
6977 case BR_VECTOR:
6978 case UD_VECTOR:
6979 case DF_VECTOR:
6980 case SS_VECTOR:
6981 case GP_VECTOR:
6982 case MF_VECTOR:
6983 return true;
6984 break;
6986 return false;
6989 static int handle_rmode_exception(struct kvm_vcpu *vcpu,
6990 int vec, u32 err_code)
6993 * Instruction with address size override prefix opcode 0x67
6994 * Cause the #SS fault with 0 error code in VM86 mode.
6996 if (((vec == GP_VECTOR) || (vec == SS_VECTOR)) && err_code == 0) {
6997 if (kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE) {
6998 if (vcpu->arch.halt_request) {
6999 vcpu->arch.halt_request = 0;
7000 return kvm_vcpu_halt(vcpu);
7002 return 1;
7004 return 0;
7008 * Forward all other exceptions that are valid in real mode.
7009 * FIXME: Breaks guest debugging in real mode, needs to be fixed with
7010 * the required debugging infrastructure rework.
7012 kvm_queue_exception(vcpu, vec);
7013 return 1;
7017 * Trigger machine check on the host. We assume all the MSRs are already set up
7018 * by the CPU and that we still run on the same CPU as the MCE occurred on.
7019 * We pass a fake environment to the machine check handler because we want
7020 * the guest to be always treated like user space, no matter what context
7021 * it used internally.
7023 static void kvm_machine_check(void)
7025 #if defined(CONFIG_X86_MCE) && defined(CONFIG_X86_64)
7026 struct pt_regs regs = {
7027 .cs = 3, /* Fake ring 3 no matter what the guest ran on */
7028 .flags = X86_EFLAGS_IF,
7031 do_machine_check(&regs, 0);
7032 #endif
7035 static int handle_machine_check(struct kvm_vcpu *vcpu)
7037 /* already handled by vcpu_run */
7038 return 1;
7041 static int handle_exception(struct kvm_vcpu *vcpu)
7043 struct vcpu_vmx *vmx = to_vmx(vcpu);
7044 struct kvm_run *kvm_run = vcpu->run;
7045 u32 intr_info, ex_no, error_code;
7046 unsigned long cr2, rip, dr6;
7047 u32 vect_info;
7048 enum emulation_result er;
7050 vect_info = vmx->idt_vectoring_info;
7051 intr_info = vmx->exit_intr_info;
7053 if (is_machine_check(intr_info))
7054 return handle_machine_check(vcpu);
7056 if (is_nmi(intr_info))
7057 return 1; /* already handled by vmx_vcpu_run() */
7059 if (is_invalid_opcode(intr_info))
7060 return handle_ud(vcpu);
7062 error_code = 0;
7063 if (intr_info & INTR_INFO_DELIVER_CODE_MASK)
7064 error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
7066 if (!vmx->rmode.vm86_active && is_gp_fault(intr_info)) {
7067 WARN_ON_ONCE(!enable_vmware_backdoor);
7068 er = kvm_emulate_instruction(vcpu,
7069 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
7070 if (er == EMULATE_USER_EXIT)
7071 return 0;
7072 else if (er != EMULATE_DONE)
7073 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
7074 return 1;
7078 * The #PF with PFEC.RSVD = 1 indicates the guest is accessing
7079 * MMIO, it is better to report an internal error.
7080 * See the comments in vmx_handle_exit.
7082 if ((vect_info & VECTORING_INFO_VALID_MASK) &&
7083 !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) {
7084 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7085 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX;
7086 vcpu->run->internal.ndata = 3;
7087 vcpu->run->internal.data[0] = vect_info;
7088 vcpu->run->internal.data[1] = intr_info;
7089 vcpu->run->internal.data[2] = error_code;
7090 return 0;
7093 if (is_page_fault(intr_info)) {
7094 cr2 = vmcs_readl(EXIT_QUALIFICATION);
7095 /* EPT won't cause page fault directly */
7096 WARN_ON_ONCE(!vcpu->arch.apf.host_apf_reason && enable_ept);
7097 return kvm_handle_page_fault(vcpu, error_code, cr2, NULL, 0);
7100 ex_no = intr_info & INTR_INFO_VECTOR_MASK;
7102 if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no))
7103 return handle_rmode_exception(vcpu, ex_no, error_code);
7105 switch (ex_no) {
7106 case AC_VECTOR:
7107 kvm_queue_exception_e(vcpu, AC_VECTOR, error_code);
7108 return 1;
7109 case DB_VECTOR:
7110 dr6 = vmcs_readl(EXIT_QUALIFICATION);
7111 if (!(vcpu->guest_debug &
7112 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) {
7113 vcpu->arch.dr6 &= ~15;
7114 vcpu->arch.dr6 |= dr6 | DR6_RTM;
7115 if (is_icebp(intr_info))
7116 skip_emulated_instruction(vcpu);
7118 kvm_queue_exception(vcpu, DB_VECTOR);
7119 return 1;
7121 kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
7122 kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7);
7123 /* fall through */
7124 case BP_VECTOR:
7126 * Update instruction length as we may reinject #BP from
7127 * user space while in guest debugging mode. Reading it for
7128 * #DB as well causes no harm, it is not used in that case.
7130 vmx->vcpu.arch.event_exit_inst_len =
7131 vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
7132 kvm_run->exit_reason = KVM_EXIT_DEBUG;
7133 rip = kvm_rip_read(vcpu);
7134 kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip;
7135 kvm_run->debug.arch.exception = ex_no;
7136 break;
7137 default:
7138 kvm_run->exit_reason = KVM_EXIT_EXCEPTION;
7139 kvm_run->ex.exception = ex_no;
7140 kvm_run->ex.error_code = error_code;
7141 break;
7143 return 0;
7146 static int handle_external_interrupt(struct kvm_vcpu *vcpu)
7148 ++vcpu->stat.irq_exits;
7149 return 1;
7152 static int handle_triple_fault(struct kvm_vcpu *vcpu)
7154 vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
7155 vcpu->mmio_needed = 0;
7156 return 0;
7159 static int handle_io(struct kvm_vcpu *vcpu)
7161 unsigned long exit_qualification;
7162 int size, in, string;
7163 unsigned port;
7165 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7166 string = (exit_qualification & 16) != 0;
7168 ++vcpu->stat.io_exits;
7170 if (string)
7171 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7173 port = exit_qualification >> 16;
7174 size = (exit_qualification & 7) + 1;
7175 in = (exit_qualification & 8) != 0;
7177 return kvm_fast_pio(vcpu, size, port, in);
7180 static void
7181 vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
7184 * Patch in the VMCALL instruction:
7186 hypercall[0] = 0x0f;
7187 hypercall[1] = 0x01;
7188 hypercall[2] = 0xc1;
7191 /* called to set cr0 as appropriate for a mov-to-cr0 exit. */
7192 static int handle_set_cr0(struct kvm_vcpu *vcpu, unsigned long val)
7194 if (is_guest_mode(vcpu)) {
7195 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7196 unsigned long orig_val = val;
7199 * We get here when L2 changed cr0 in a way that did not change
7200 * any of L1's shadowed bits (see nested_vmx_exit_handled_cr),
7201 * but did change L0 shadowed bits. So we first calculate the
7202 * effective cr0 value that L1 would like to write into the
7203 * hardware. It consists of the L2-owned bits from the new
7204 * value combined with the L1-owned bits from L1's guest_cr0.
7206 val = (val & ~vmcs12->cr0_guest_host_mask) |
7207 (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask);
7209 if (!nested_guest_cr0_valid(vcpu, val))
7210 return 1;
7212 if (kvm_set_cr0(vcpu, val))
7213 return 1;
7214 vmcs_writel(CR0_READ_SHADOW, orig_val);
7215 return 0;
7216 } else {
7217 if (to_vmx(vcpu)->nested.vmxon &&
7218 !nested_host_cr0_valid(vcpu, val))
7219 return 1;
7221 return kvm_set_cr0(vcpu, val);
7225 static int handle_set_cr4(struct kvm_vcpu *vcpu, unsigned long val)
7227 if (is_guest_mode(vcpu)) {
7228 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
7229 unsigned long orig_val = val;
7231 /* analogously to handle_set_cr0 */
7232 val = (val & ~vmcs12->cr4_guest_host_mask) |
7233 (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask);
7234 if (kvm_set_cr4(vcpu, val))
7235 return 1;
7236 vmcs_writel(CR4_READ_SHADOW, orig_val);
7237 return 0;
7238 } else
7239 return kvm_set_cr4(vcpu, val);
7242 static int handle_desc(struct kvm_vcpu *vcpu)
7244 WARN_ON(!(vcpu->arch.cr4 & X86_CR4_UMIP));
7245 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7248 static int handle_cr(struct kvm_vcpu *vcpu)
7250 unsigned long exit_qualification, val;
7251 int cr;
7252 int reg;
7253 int err;
7254 int ret;
7256 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7257 cr = exit_qualification & 15;
7258 reg = (exit_qualification >> 8) & 15;
7259 switch ((exit_qualification >> 4) & 3) {
7260 case 0: /* mov to cr */
7261 val = kvm_register_readl(vcpu, reg);
7262 trace_kvm_cr_write(cr, val);
7263 switch (cr) {
7264 case 0:
7265 err = handle_set_cr0(vcpu, val);
7266 return kvm_complete_insn_gp(vcpu, err);
7267 case 3:
7268 WARN_ON_ONCE(enable_unrestricted_guest);
7269 err = kvm_set_cr3(vcpu, val);
7270 return kvm_complete_insn_gp(vcpu, err);
7271 case 4:
7272 err = handle_set_cr4(vcpu, val);
7273 return kvm_complete_insn_gp(vcpu, err);
7274 case 8: {
7275 u8 cr8_prev = kvm_get_cr8(vcpu);
7276 u8 cr8 = (u8)val;
7277 err = kvm_set_cr8(vcpu, cr8);
7278 ret = kvm_complete_insn_gp(vcpu, err);
7279 if (lapic_in_kernel(vcpu))
7280 return ret;
7281 if (cr8_prev <= cr8)
7282 return ret;
7284 * TODO: we might be squashing a
7285 * KVM_GUESTDBG_SINGLESTEP-triggered
7286 * KVM_EXIT_DEBUG here.
7288 vcpu->run->exit_reason = KVM_EXIT_SET_TPR;
7289 return 0;
7292 break;
7293 case 2: /* clts */
7294 WARN_ONCE(1, "Guest should always own CR0.TS");
7295 vmx_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~X86_CR0_TS));
7296 trace_kvm_cr_write(0, kvm_read_cr0(vcpu));
7297 return kvm_skip_emulated_instruction(vcpu);
7298 case 1: /*mov from cr*/
7299 switch (cr) {
7300 case 3:
7301 WARN_ON_ONCE(enable_unrestricted_guest);
7302 val = kvm_read_cr3(vcpu);
7303 kvm_register_write(vcpu, reg, val);
7304 trace_kvm_cr_read(cr, val);
7305 return kvm_skip_emulated_instruction(vcpu);
7306 case 8:
7307 val = kvm_get_cr8(vcpu);
7308 kvm_register_write(vcpu, reg, val);
7309 trace_kvm_cr_read(cr, val);
7310 return kvm_skip_emulated_instruction(vcpu);
7312 break;
7313 case 3: /* lmsw */
7314 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
7315 trace_kvm_cr_write(0, (kvm_read_cr0(vcpu) & ~0xful) | val);
7316 kvm_lmsw(vcpu, val);
7318 return kvm_skip_emulated_instruction(vcpu);
7319 default:
7320 break;
7322 vcpu->run->exit_reason = 0;
7323 vcpu_unimpl(vcpu, "unhandled control register: op %d cr %d\n",
7324 (int)(exit_qualification >> 4) & 3, cr);
7325 return 0;
7328 static int handle_dr(struct kvm_vcpu *vcpu)
7330 unsigned long exit_qualification;
7331 int dr, dr7, reg;
7333 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7334 dr = exit_qualification & DEBUG_REG_ACCESS_NUM;
7336 /* First, if DR does not exist, trigger UD */
7337 if (!kvm_require_dr(vcpu, dr))
7338 return 1;
7340 /* Do not handle if the CPL > 0, will trigger GP on re-entry */
7341 if (!kvm_require_cpl(vcpu, 0))
7342 return 1;
7343 dr7 = vmcs_readl(GUEST_DR7);
7344 if (dr7 & DR7_GD) {
7346 * As the vm-exit takes precedence over the debug trap, we
7347 * need to emulate the latter, either for the host or the
7348 * guest debugging itself.
7350 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
7351 vcpu->run->debug.arch.dr6 = vcpu->arch.dr6;
7352 vcpu->run->debug.arch.dr7 = dr7;
7353 vcpu->run->debug.arch.pc = kvm_get_linear_rip(vcpu);
7354 vcpu->run->debug.arch.exception = DB_VECTOR;
7355 vcpu->run->exit_reason = KVM_EXIT_DEBUG;
7356 return 0;
7357 } else {
7358 vcpu->arch.dr6 &= ~15;
7359 vcpu->arch.dr6 |= DR6_BD | DR6_RTM;
7360 kvm_queue_exception(vcpu, DB_VECTOR);
7361 return 1;
7365 if (vcpu->guest_debug == 0) {
7366 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7367 CPU_BASED_MOV_DR_EXITING);
7370 * No more DR vmexits; force a reload of the debug registers
7371 * and reenter on this instruction. The next vmexit will
7372 * retrieve the full state of the debug registers.
7374 vcpu->arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
7375 return 1;
7378 reg = DEBUG_REG_ACCESS_REG(exit_qualification);
7379 if (exit_qualification & TYPE_MOV_FROM_DR) {
7380 unsigned long val;
7382 if (kvm_get_dr(vcpu, dr, &val))
7383 return 1;
7384 kvm_register_write(vcpu, reg, val);
7385 } else
7386 if (kvm_set_dr(vcpu, dr, kvm_register_readl(vcpu, reg)))
7387 return 1;
7389 return kvm_skip_emulated_instruction(vcpu);
7392 static u64 vmx_get_dr6(struct kvm_vcpu *vcpu)
7394 return vcpu->arch.dr6;
7397 static void vmx_set_dr6(struct kvm_vcpu *vcpu, unsigned long val)
7401 static void vmx_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
7403 get_debugreg(vcpu->arch.db[0], 0);
7404 get_debugreg(vcpu->arch.db[1], 1);
7405 get_debugreg(vcpu->arch.db[2], 2);
7406 get_debugreg(vcpu->arch.db[3], 3);
7407 get_debugreg(vcpu->arch.dr6, 6);
7408 vcpu->arch.dr7 = vmcs_readl(GUEST_DR7);
7410 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
7411 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL, CPU_BASED_MOV_DR_EXITING);
7414 static void vmx_set_dr7(struct kvm_vcpu *vcpu, unsigned long val)
7416 vmcs_writel(GUEST_DR7, val);
7419 static int handle_cpuid(struct kvm_vcpu *vcpu)
7421 return kvm_emulate_cpuid(vcpu);
7424 static int handle_rdmsr(struct kvm_vcpu *vcpu)
7426 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7427 struct msr_data msr_info;
7429 msr_info.index = ecx;
7430 msr_info.host_initiated = false;
7431 if (vmx_get_msr(vcpu, &msr_info)) {
7432 trace_kvm_msr_read_ex(ecx);
7433 kvm_inject_gp(vcpu, 0);
7434 return 1;
7437 trace_kvm_msr_read(ecx, msr_info.data);
7439 /* FIXME: handling of bits 32:63 of rax, rdx */
7440 vcpu->arch.regs[VCPU_REGS_RAX] = msr_info.data & -1u;
7441 vcpu->arch.regs[VCPU_REGS_RDX] = (msr_info.data >> 32) & -1u;
7442 return kvm_skip_emulated_instruction(vcpu);
7445 static int handle_wrmsr(struct kvm_vcpu *vcpu)
7447 struct msr_data msr;
7448 u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX];
7449 u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u)
7450 | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32);
7452 msr.data = data;
7453 msr.index = ecx;
7454 msr.host_initiated = false;
7455 if (kvm_set_msr(vcpu, &msr) != 0) {
7456 trace_kvm_msr_write_ex(ecx, data);
7457 kvm_inject_gp(vcpu, 0);
7458 return 1;
7461 trace_kvm_msr_write(ecx, data);
7462 return kvm_skip_emulated_instruction(vcpu);
7465 static int handle_tpr_below_threshold(struct kvm_vcpu *vcpu)
7467 kvm_apic_update_ppr(vcpu);
7468 return 1;
7471 static int handle_interrupt_window(struct kvm_vcpu *vcpu)
7473 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7474 CPU_BASED_VIRTUAL_INTR_PENDING);
7476 kvm_make_request(KVM_REQ_EVENT, vcpu);
7478 ++vcpu->stat.irq_window_exits;
7479 return 1;
7482 static int handle_halt(struct kvm_vcpu *vcpu)
7484 return kvm_emulate_halt(vcpu);
7487 static int handle_vmcall(struct kvm_vcpu *vcpu)
7489 return kvm_emulate_hypercall(vcpu);
7492 static int handle_invd(struct kvm_vcpu *vcpu)
7494 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7497 static int handle_invlpg(struct kvm_vcpu *vcpu)
7499 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7501 kvm_mmu_invlpg(vcpu, exit_qualification);
7502 return kvm_skip_emulated_instruction(vcpu);
7505 static int handle_rdpmc(struct kvm_vcpu *vcpu)
7507 int err;
7509 err = kvm_rdpmc(vcpu);
7510 return kvm_complete_insn_gp(vcpu, err);
7513 static int handle_wbinvd(struct kvm_vcpu *vcpu)
7515 return kvm_emulate_wbinvd(vcpu);
7518 static int handle_xsetbv(struct kvm_vcpu *vcpu)
7520 u64 new_bv = kvm_read_edx_eax(vcpu);
7521 u32 index = kvm_register_read(vcpu, VCPU_REGS_RCX);
7523 if (kvm_set_xcr(vcpu, index, new_bv) == 0)
7524 return kvm_skip_emulated_instruction(vcpu);
7525 return 1;
7528 static int handle_xsaves(struct kvm_vcpu *vcpu)
7530 kvm_skip_emulated_instruction(vcpu);
7531 WARN(1, "this should never happen\n");
7532 return 1;
7535 static int handle_xrstors(struct kvm_vcpu *vcpu)
7537 kvm_skip_emulated_instruction(vcpu);
7538 WARN(1, "this should never happen\n");
7539 return 1;
7542 static int handle_apic_access(struct kvm_vcpu *vcpu)
7544 if (likely(fasteoi)) {
7545 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7546 int access_type, offset;
7548 access_type = exit_qualification & APIC_ACCESS_TYPE;
7549 offset = exit_qualification & APIC_ACCESS_OFFSET;
7551 * Sane guest uses MOV to write EOI, with written value
7552 * not cared. So make a short-circuit here by avoiding
7553 * heavy instruction emulation.
7555 if ((access_type == TYPE_LINEAR_APIC_INST_WRITE) &&
7556 (offset == APIC_EOI)) {
7557 kvm_lapic_set_eoi(vcpu);
7558 return kvm_skip_emulated_instruction(vcpu);
7561 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
7564 static int handle_apic_eoi_induced(struct kvm_vcpu *vcpu)
7566 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7567 int vector = exit_qualification & 0xff;
7569 /* EOI-induced VM exit is trap-like and thus no need to adjust IP */
7570 kvm_apic_set_eoi_accelerated(vcpu, vector);
7571 return 1;
7574 static int handle_apic_write(struct kvm_vcpu *vcpu)
7576 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7577 u32 offset = exit_qualification & 0xfff;
7579 /* APIC-write VM exit is trap-like and thus no need to adjust IP */
7580 kvm_apic_write_nodecode(vcpu, offset);
7581 return 1;
7584 static int handle_task_switch(struct kvm_vcpu *vcpu)
7586 struct vcpu_vmx *vmx = to_vmx(vcpu);
7587 unsigned long exit_qualification;
7588 bool has_error_code = false;
7589 u32 error_code = 0;
7590 u16 tss_selector;
7591 int reason, type, idt_v, idt_index;
7593 idt_v = (vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK);
7594 idt_index = (vmx->idt_vectoring_info & VECTORING_INFO_VECTOR_MASK);
7595 type = (vmx->idt_vectoring_info & VECTORING_INFO_TYPE_MASK);
7597 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7599 reason = (u32)exit_qualification >> 30;
7600 if (reason == TASK_SWITCH_GATE && idt_v) {
7601 switch (type) {
7602 case INTR_TYPE_NMI_INTR:
7603 vcpu->arch.nmi_injected = false;
7604 vmx_set_nmi_mask(vcpu, true);
7605 break;
7606 case INTR_TYPE_EXT_INTR:
7607 case INTR_TYPE_SOFT_INTR:
7608 kvm_clear_interrupt_queue(vcpu);
7609 break;
7610 case INTR_TYPE_HARD_EXCEPTION:
7611 if (vmx->idt_vectoring_info &
7612 VECTORING_INFO_DELIVER_CODE_MASK) {
7613 has_error_code = true;
7614 error_code =
7615 vmcs_read32(IDT_VECTORING_ERROR_CODE);
7617 /* fall through */
7618 case INTR_TYPE_SOFT_EXCEPTION:
7619 kvm_clear_exception_queue(vcpu);
7620 break;
7621 default:
7622 break;
7625 tss_selector = exit_qualification;
7627 if (!idt_v || (type != INTR_TYPE_HARD_EXCEPTION &&
7628 type != INTR_TYPE_EXT_INTR &&
7629 type != INTR_TYPE_NMI_INTR))
7630 skip_emulated_instruction(vcpu);
7632 if (kvm_task_switch(vcpu, tss_selector,
7633 type == INTR_TYPE_SOFT_INTR ? idt_index : -1, reason,
7634 has_error_code, error_code) == EMULATE_FAIL) {
7635 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7636 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7637 vcpu->run->internal.ndata = 0;
7638 return 0;
7642 * TODO: What about debug traps on tss switch?
7643 * Are we supposed to inject them and update dr6?
7646 return 1;
7649 static int handle_ept_violation(struct kvm_vcpu *vcpu)
7651 unsigned long exit_qualification;
7652 gpa_t gpa;
7653 u64 error_code;
7655 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
7658 * EPT violation happened while executing iret from NMI,
7659 * "blocked by NMI" bit has to be set before next VM entry.
7660 * There are errata that may cause this bit to not be set:
7661 * AAK134, BY25.
7663 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
7664 enable_vnmi &&
7665 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
7666 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO, GUEST_INTR_STATE_NMI);
7668 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7669 trace_kvm_page_fault(gpa, exit_qualification);
7671 /* Is it a read fault? */
7672 error_code = (exit_qualification & EPT_VIOLATION_ACC_READ)
7673 ? PFERR_USER_MASK : 0;
7674 /* Is it a write fault? */
7675 error_code |= (exit_qualification & EPT_VIOLATION_ACC_WRITE)
7676 ? PFERR_WRITE_MASK : 0;
7677 /* Is it a fetch fault? */
7678 error_code |= (exit_qualification & EPT_VIOLATION_ACC_INSTR)
7679 ? PFERR_FETCH_MASK : 0;
7680 /* ept page table entry is present? */
7681 error_code |= (exit_qualification &
7682 (EPT_VIOLATION_READABLE | EPT_VIOLATION_WRITABLE |
7683 EPT_VIOLATION_EXECUTABLE))
7684 ? PFERR_PRESENT_MASK : 0;
7686 error_code |= (exit_qualification & 0x100) != 0 ?
7687 PFERR_GUEST_FINAL_MASK : PFERR_GUEST_PAGE_MASK;
7689 vcpu->arch.exit_qualification = exit_qualification;
7690 return kvm_mmu_page_fault(vcpu, gpa, error_code, NULL, 0);
7693 static int handle_ept_misconfig(struct kvm_vcpu *vcpu)
7695 gpa_t gpa;
7698 * A nested guest cannot optimize MMIO vmexits, because we have an
7699 * nGPA here instead of the required GPA.
7701 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS);
7702 if (!is_guest_mode(vcpu) &&
7703 !kvm_io_bus_write(vcpu, KVM_FAST_MMIO_BUS, gpa, 0, NULL)) {
7704 trace_kvm_fast_mmio(gpa);
7706 * Doing kvm_skip_emulated_instruction() depends on undefined
7707 * behavior: Intel's manual doesn't mandate
7708 * VM_EXIT_INSTRUCTION_LEN to be set in VMCS when EPT MISCONFIG
7709 * occurs and while on real hardware it was observed to be set,
7710 * other hypervisors (namely Hyper-V) don't set it, we end up
7711 * advancing IP with some random value. Disable fast mmio when
7712 * running nested and keep it for real hardware in hope that
7713 * VM_EXIT_INSTRUCTION_LEN will always be set correctly.
7715 if (!static_cpu_has(X86_FEATURE_HYPERVISOR))
7716 return kvm_skip_emulated_instruction(vcpu);
7717 else
7718 return kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) ==
7719 EMULATE_DONE;
7722 return kvm_mmu_page_fault(vcpu, gpa, PFERR_RSVD_MASK, NULL, 0);
7725 static int handle_nmi_window(struct kvm_vcpu *vcpu)
7727 WARN_ON_ONCE(!enable_vnmi);
7728 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
7729 CPU_BASED_VIRTUAL_NMI_PENDING);
7730 ++vcpu->stat.nmi_window_exits;
7731 kvm_make_request(KVM_REQ_EVENT, vcpu);
7733 return 1;
7736 static int handle_invalid_guest_state(struct kvm_vcpu *vcpu)
7738 struct vcpu_vmx *vmx = to_vmx(vcpu);
7739 enum emulation_result err = EMULATE_DONE;
7740 int ret = 1;
7741 u32 cpu_exec_ctrl;
7742 bool intr_window_requested;
7743 unsigned count = 130;
7746 * We should never reach the point where we are emulating L2
7747 * due to invalid guest state as that means we incorrectly
7748 * allowed a nested VMEntry with an invalid vmcs12.
7750 WARN_ON_ONCE(vmx->emulation_required && vmx->nested.nested_run_pending);
7752 cpu_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
7753 intr_window_requested = cpu_exec_ctrl & CPU_BASED_VIRTUAL_INTR_PENDING;
7755 while (vmx->emulation_required && count-- != 0) {
7756 if (intr_window_requested && vmx_interrupt_allowed(vcpu))
7757 return handle_interrupt_window(&vmx->vcpu);
7759 if (kvm_test_request(KVM_REQ_EVENT, vcpu))
7760 return 1;
7762 err = kvm_emulate_instruction(vcpu, 0);
7764 if (err == EMULATE_USER_EXIT) {
7765 ++vcpu->stat.mmio_exits;
7766 ret = 0;
7767 goto out;
7770 if (err != EMULATE_DONE)
7771 goto emulation_error;
7773 if (vmx->emulation_required && !vmx->rmode.vm86_active &&
7774 vcpu->arch.exception.pending)
7775 goto emulation_error;
7777 if (vcpu->arch.halt_request) {
7778 vcpu->arch.halt_request = 0;
7779 ret = kvm_vcpu_halt(vcpu);
7780 goto out;
7783 if (signal_pending(current))
7784 goto out;
7785 if (need_resched())
7786 schedule();
7789 out:
7790 return ret;
7792 emulation_error:
7793 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
7794 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
7795 vcpu->run->internal.ndata = 0;
7796 return 0;
7799 static void grow_ple_window(struct kvm_vcpu *vcpu)
7801 struct vcpu_vmx *vmx = to_vmx(vcpu);
7802 int old = vmx->ple_window;
7804 vmx->ple_window = __grow_ple_window(old, ple_window,
7805 ple_window_grow,
7806 ple_window_max);
7808 if (vmx->ple_window != old)
7809 vmx->ple_window_dirty = true;
7811 trace_kvm_ple_window_grow(vcpu->vcpu_id, vmx->ple_window, old);
7814 static void shrink_ple_window(struct kvm_vcpu *vcpu)
7816 struct vcpu_vmx *vmx = to_vmx(vcpu);
7817 int old = vmx->ple_window;
7819 vmx->ple_window = __shrink_ple_window(old, ple_window,
7820 ple_window_shrink,
7821 ple_window);
7823 if (vmx->ple_window != old)
7824 vmx->ple_window_dirty = true;
7826 trace_kvm_ple_window_shrink(vcpu->vcpu_id, vmx->ple_window, old);
7830 * Handler for POSTED_INTERRUPT_WAKEUP_VECTOR.
7832 static void wakeup_handler(void)
7834 struct kvm_vcpu *vcpu;
7835 int cpu = smp_processor_id();
7837 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7838 list_for_each_entry(vcpu, &per_cpu(blocked_vcpu_on_cpu, cpu),
7839 blocked_vcpu_list) {
7840 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
7842 if (pi_test_on(pi_desc) == 1)
7843 kvm_vcpu_kick(vcpu);
7845 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, cpu));
7848 static void vmx_enable_tdp(void)
7850 kvm_mmu_set_mask_ptes(VMX_EPT_READABLE_MASK,
7851 enable_ept_ad_bits ? VMX_EPT_ACCESS_BIT : 0ull,
7852 enable_ept_ad_bits ? VMX_EPT_DIRTY_BIT : 0ull,
7853 0ull, VMX_EPT_EXECUTABLE_MASK,
7854 cpu_has_vmx_ept_execute_only() ? 0ull : VMX_EPT_READABLE_MASK,
7855 VMX_EPT_RWX_MASK, 0ull);
7857 ept_set_mmio_spte_mask();
7858 kvm_enable_tdp();
7861 static __init int hardware_setup(void)
7863 unsigned long host_bndcfgs;
7864 int r = -ENOMEM, i;
7866 rdmsrl_safe(MSR_EFER, &host_efer);
7868 for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i)
7869 kvm_define_shared_msr(i, vmx_msr_index[i]);
7871 for (i = 0; i < VMX_BITMAP_NR; i++) {
7872 vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL);
7873 if (!vmx_bitmap[i])
7874 goto out;
7877 memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE);
7878 memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE);
7880 if (setup_vmcs_config(&vmcs_config) < 0) {
7881 r = -EIO;
7882 goto out;
7885 if (boot_cpu_has(X86_FEATURE_NX))
7886 kvm_enable_efer_bits(EFER_NX);
7888 if (boot_cpu_has(X86_FEATURE_MPX)) {
7889 rdmsrl(MSR_IA32_BNDCFGS, host_bndcfgs);
7890 WARN_ONCE(host_bndcfgs, "KVM: BNDCFGS in host will be lost");
7893 if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() ||
7894 !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global()))
7895 enable_vpid = 0;
7897 if (!cpu_has_vmx_ept() ||
7898 !cpu_has_vmx_ept_4levels() ||
7899 !cpu_has_vmx_ept_mt_wb() ||
7900 !cpu_has_vmx_invept_global())
7901 enable_ept = 0;
7903 if (!cpu_has_vmx_ept_ad_bits() || !enable_ept)
7904 enable_ept_ad_bits = 0;
7906 if (!cpu_has_vmx_unrestricted_guest() || !enable_ept)
7907 enable_unrestricted_guest = 0;
7909 if (!cpu_has_vmx_flexpriority())
7910 flexpriority_enabled = 0;
7912 if (!cpu_has_virtual_nmis())
7913 enable_vnmi = 0;
7916 * set_apic_access_page_addr() is used to reload apic access
7917 * page upon invalidation. No need to do anything if not
7918 * using the APIC_ACCESS_ADDR VMCS field.
7920 if (!flexpriority_enabled)
7921 kvm_x86_ops->set_apic_access_page_addr = NULL;
7923 if (!cpu_has_vmx_tpr_shadow())
7924 kvm_x86_ops->update_cr8_intercept = NULL;
7926 if (enable_ept && !cpu_has_vmx_ept_2m_page())
7927 kvm_disable_largepages();
7929 #if IS_ENABLED(CONFIG_HYPERV)
7930 if (ms_hyperv.nested_features & HV_X64_NESTED_GUEST_MAPPING_FLUSH
7931 && enable_ept)
7932 kvm_x86_ops->tlb_remote_flush = vmx_hv_remote_flush_tlb;
7933 #endif
7935 if (!cpu_has_vmx_ple()) {
7936 ple_gap = 0;
7937 ple_window = 0;
7938 ple_window_grow = 0;
7939 ple_window_max = 0;
7940 ple_window_shrink = 0;
7943 if (!cpu_has_vmx_apicv()) {
7944 enable_apicv = 0;
7945 kvm_x86_ops->sync_pir_to_irr = NULL;
7948 if (cpu_has_vmx_tsc_scaling()) {
7949 kvm_has_tsc_control = true;
7950 kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX;
7951 kvm_tsc_scaling_ratio_frac_bits = 48;
7954 set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */
7956 if (enable_ept)
7957 vmx_enable_tdp();
7958 else
7959 kvm_disable_tdp();
7961 if (!nested) {
7962 kvm_x86_ops->get_nested_state = NULL;
7963 kvm_x86_ops->set_nested_state = NULL;
7967 * Only enable PML when hardware supports PML feature, and both EPT
7968 * and EPT A/D bit features are enabled -- PML depends on them to work.
7970 if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml())
7971 enable_pml = 0;
7973 if (!enable_pml) {
7974 kvm_x86_ops->slot_enable_log_dirty = NULL;
7975 kvm_x86_ops->slot_disable_log_dirty = NULL;
7976 kvm_x86_ops->flush_log_dirty = NULL;
7977 kvm_x86_ops->enable_log_dirty_pt_masked = NULL;
7980 if (!cpu_has_vmx_preemption_timer())
7981 kvm_x86_ops->request_immediate_exit = __kvm_request_immediate_exit;
7983 if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) {
7984 u64 vmx_msr;
7986 rdmsrl(MSR_IA32_VMX_MISC, vmx_msr);
7987 cpu_preemption_timer_multi =
7988 vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK;
7989 } else {
7990 kvm_x86_ops->set_hv_timer = NULL;
7991 kvm_x86_ops->cancel_hv_timer = NULL;
7994 if (!cpu_has_vmx_shadow_vmcs())
7995 enable_shadow_vmcs = 0;
7996 if (enable_shadow_vmcs)
7997 init_vmcs_shadow_fields();
7999 kvm_set_posted_intr_wakeup_handler(wakeup_handler);
8000 nested_vmx_setup_ctls_msrs(&vmcs_config.nested, enable_apicv);
8002 kvm_mce_cap_supported |= MCG_LMCE_P;
8004 r = alloc_kvm_area();
8005 if (r)
8006 goto out;
8007 return 0;
8009 out:
8010 for (i = 0; i < VMX_BITMAP_NR; i++)
8011 free_page((unsigned long)vmx_bitmap[i]);
8013 return r;
8016 static __exit void hardware_unsetup(void)
8018 int i;
8020 for (i = 0; i < VMX_BITMAP_NR; i++)
8021 free_page((unsigned long)vmx_bitmap[i]);
8023 free_kvm_area();
8027 * Indicate a busy-waiting vcpu in spinlock. We do not enable the PAUSE
8028 * exiting, so only get here on cpu with PAUSE-Loop-Exiting.
8030 static int handle_pause(struct kvm_vcpu *vcpu)
8032 if (!kvm_pause_in_guest(vcpu->kvm))
8033 grow_ple_window(vcpu);
8036 * Intel sdm vol3 ch-25.1.3 says: The "PAUSE-loop exiting"
8037 * VM-execution control is ignored if CPL > 0. OTOH, KVM
8038 * never set PAUSE_EXITING and just set PLE if supported,
8039 * so the vcpu must be CPL=0 if it gets a PAUSE exit.
8041 kvm_vcpu_on_spin(vcpu, true);
8042 return kvm_skip_emulated_instruction(vcpu);
8045 static int handle_nop(struct kvm_vcpu *vcpu)
8047 return kvm_skip_emulated_instruction(vcpu);
8050 static int handle_mwait(struct kvm_vcpu *vcpu)
8052 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
8053 return handle_nop(vcpu);
8056 static int handle_invalid_op(struct kvm_vcpu *vcpu)
8058 kvm_queue_exception(vcpu, UD_VECTOR);
8059 return 1;
8062 static int handle_monitor_trap(struct kvm_vcpu *vcpu)
8064 return 1;
8067 static int handle_monitor(struct kvm_vcpu *vcpu)
8069 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
8070 return handle_nop(vcpu);
8074 * The following 3 functions, nested_vmx_succeed()/failValid()/failInvalid(),
8075 * set the success or error code of an emulated VMX instruction, as specified
8076 * by Vol 2B, VMX Instruction Reference, "Conventions".
8078 static void nested_vmx_succeed(struct kvm_vcpu *vcpu)
8080 vmx_set_rflags(vcpu, vmx_get_rflags(vcpu)
8081 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8082 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF));
8085 static void nested_vmx_failInvalid(struct kvm_vcpu *vcpu)
8087 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8088 & ~(X86_EFLAGS_PF | X86_EFLAGS_AF | X86_EFLAGS_ZF |
8089 X86_EFLAGS_SF | X86_EFLAGS_OF))
8090 | X86_EFLAGS_CF);
8093 static void nested_vmx_failValid(struct kvm_vcpu *vcpu,
8094 u32 vm_instruction_error)
8096 if (to_vmx(vcpu)->nested.current_vmptr == -1ull) {
8098 * failValid writes the error number to the current VMCS, which
8099 * can't be done there isn't a current VMCS.
8101 nested_vmx_failInvalid(vcpu);
8102 return;
8104 vmx_set_rflags(vcpu, (vmx_get_rflags(vcpu)
8105 & ~(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF |
8106 X86_EFLAGS_SF | X86_EFLAGS_OF))
8107 | X86_EFLAGS_ZF);
8108 get_vmcs12(vcpu)->vm_instruction_error = vm_instruction_error;
8110 * We don't need to force a shadow sync because
8111 * VM_INSTRUCTION_ERROR is not shadowed
8115 static void nested_vmx_abort(struct kvm_vcpu *vcpu, u32 indicator)
8117 /* TODO: not to reset guest simply here. */
8118 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
8119 pr_debug_ratelimited("kvm: nested vmx abort, indicator %d\n", indicator);
8122 static enum hrtimer_restart vmx_preemption_timer_fn(struct hrtimer *timer)
8124 struct vcpu_vmx *vmx =
8125 container_of(timer, struct vcpu_vmx, nested.preemption_timer);
8127 vmx->nested.preemption_timer_expired = true;
8128 kvm_make_request(KVM_REQ_EVENT, &vmx->vcpu);
8129 kvm_vcpu_kick(&vmx->vcpu);
8131 return HRTIMER_NORESTART;
8135 * Decode the memory-address operand of a vmx instruction, as recorded on an
8136 * exit caused by such an instruction (run by a guest hypervisor).
8137 * On success, returns 0. When the operand is invalid, returns 1 and throws
8138 * #UD or #GP.
8140 static int get_vmx_mem_address(struct kvm_vcpu *vcpu,
8141 unsigned long exit_qualification,
8142 u32 vmx_instruction_info, bool wr, gva_t *ret)
8144 gva_t off;
8145 bool exn;
8146 struct kvm_segment s;
8149 * According to Vol. 3B, "Information for VM Exits Due to Instruction
8150 * Execution", on an exit, vmx_instruction_info holds most of the
8151 * addressing components of the operand. Only the displacement part
8152 * is put in exit_qualification (see 3B, "Basic VM-Exit Information").
8153 * For how an actual address is calculated from all these components,
8154 * refer to Vol. 1, "Operand Addressing".
8156 int scaling = vmx_instruction_info & 3;
8157 int addr_size = (vmx_instruction_info >> 7) & 7;
8158 bool is_reg = vmx_instruction_info & (1u << 10);
8159 int seg_reg = (vmx_instruction_info >> 15) & 7;
8160 int index_reg = (vmx_instruction_info >> 18) & 0xf;
8161 bool index_is_valid = !(vmx_instruction_info & (1u << 22));
8162 int base_reg = (vmx_instruction_info >> 23) & 0xf;
8163 bool base_is_valid = !(vmx_instruction_info & (1u << 27));
8165 if (is_reg) {
8166 kvm_queue_exception(vcpu, UD_VECTOR);
8167 return 1;
8170 /* Addr = segment_base + offset */
8171 /* offset = base + [index * scale] + displacement */
8172 off = exit_qualification; /* holds the displacement */
8173 if (addr_size == 1)
8174 off = (gva_t)sign_extend64(off, 31);
8175 else if (addr_size == 0)
8176 off = (gva_t)sign_extend64(off, 15);
8177 if (base_is_valid)
8178 off += kvm_register_read(vcpu, base_reg);
8179 if (index_is_valid)
8180 off += kvm_register_read(vcpu, index_reg)<<scaling;
8181 vmx_get_segment(vcpu, &s, seg_reg);
8184 * The effective address, i.e. @off, of a memory operand is truncated
8185 * based on the address size of the instruction. Note that this is
8186 * the *effective address*, i.e. the address prior to accounting for
8187 * the segment's base.
8189 if (addr_size == 1) /* 32 bit */
8190 off &= 0xffffffff;
8191 else if (addr_size == 0) /* 16 bit */
8192 off &= 0xffff;
8194 /* Checks for #GP/#SS exceptions. */
8195 exn = false;
8196 if (is_long_mode(vcpu)) {
8198 * The virtual/linear address is never truncated in 64-bit
8199 * mode, e.g. a 32-bit address size can yield a 64-bit virtual
8200 * address when using FS/GS with a non-zero base.
8202 *ret = s.base + off;
8204 /* Long mode: #GP(0)/#SS(0) if the memory address is in a
8205 * non-canonical form. This is the only check on the memory
8206 * destination for long mode!
8208 exn = is_noncanonical_address(*ret, vcpu);
8209 } else if (is_protmode(vcpu)) {
8211 * When not in long mode, the virtual/linear address is
8212 * unconditionally truncated to 32 bits regardless of the
8213 * address size.
8215 *ret = (s.base + off) & 0xffffffff;
8217 /* Protected mode: apply checks for segment validity in the
8218 * following order:
8219 * - segment type check (#GP(0) may be thrown)
8220 * - usability check (#GP(0)/#SS(0))
8221 * - limit check (#GP(0)/#SS(0))
8223 if (wr)
8224 /* #GP(0) if the destination operand is located in a
8225 * read-only data segment or any code segment.
8227 exn = ((s.type & 0xa) == 0 || (s.type & 8));
8228 else
8229 /* #GP(0) if the source operand is located in an
8230 * execute-only code segment
8232 exn = ((s.type & 0xa) == 8);
8233 if (exn) {
8234 kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
8235 return 1;
8237 /* Protected mode: #GP(0)/#SS(0) if the segment is unusable.
8239 exn = (s.unusable != 0);
8242 * Protected mode: #GP(0)/#SS(0) if the memory operand is
8243 * outside the segment limit. All CPUs that support VMX ignore
8244 * limit checks for flat segments, i.e. segments with base==0,
8245 * limit==0xffffffff and of type expand-up data or code.
8247 if (!(s.base == 0 && s.limit == 0xffffffff &&
8248 ((s.type & 8) || !(s.type & 4))))
8249 exn = exn || (off + sizeof(u64) > s.limit);
8251 if (exn) {
8252 kvm_queue_exception_e(vcpu,
8253 seg_reg == VCPU_SREG_SS ?
8254 SS_VECTOR : GP_VECTOR,
8256 return 1;
8259 return 0;
8262 static int nested_vmx_get_vmptr(struct kvm_vcpu *vcpu, gpa_t *vmpointer)
8264 gva_t gva;
8265 struct x86_exception e;
8267 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
8268 vmcs_read32(VMX_INSTRUCTION_INFO), false, &gva))
8269 return 1;
8271 if (kvm_read_guest_virt(vcpu, gva, vmpointer, sizeof(*vmpointer), &e)) {
8272 kvm_inject_page_fault(vcpu, &e);
8273 return 1;
8276 return 0;
8280 * Allocate a shadow VMCS and associate it with the currently loaded
8281 * VMCS, unless such a shadow VMCS already exists. The newly allocated
8282 * VMCS is also VMCLEARed, so that it is ready for use.
8284 static struct vmcs *alloc_shadow_vmcs(struct kvm_vcpu *vcpu)
8286 struct vcpu_vmx *vmx = to_vmx(vcpu);
8287 struct loaded_vmcs *loaded_vmcs = vmx->loaded_vmcs;
8290 * We should allocate a shadow vmcs for vmcs01 only when L1
8291 * executes VMXON and free it when L1 executes VMXOFF.
8292 * As it is invalid to execute VMXON twice, we shouldn't reach
8293 * here when vmcs01 already have an allocated shadow vmcs.
8295 WARN_ON(loaded_vmcs == &vmx->vmcs01 && loaded_vmcs->shadow_vmcs);
8297 if (!loaded_vmcs->shadow_vmcs) {
8298 loaded_vmcs->shadow_vmcs = alloc_vmcs(true);
8299 if (loaded_vmcs->shadow_vmcs)
8300 vmcs_clear(loaded_vmcs->shadow_vmcs);
8302 return loaded_vmcs->shadow_vmcs;
8305 static int enter_vmx_operation(struct kvm_vcpu *vcpu)
8307 struct vcpu_vmx *vmx = to_vmx(vcpu);
8308 int r;
8310 r = alloc_loaded_vmcs(&vmx->nested.vmcs02);
8311 if (r < 0)
8312 goto out_vmcs02;
8314 vmx->nested.cached_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL);
8315 if (!vmx->nested.cached_vmcs12)
8316 goto out_cached_vmcs12;
8318 vmx->nested.cached_shadow_vmcs12 = kzalloc(VMCS12_SIZE, GFP_KERNEL);
8319 if (!vmx->nested.cached_shadow_vmcs12)
8320 goto out_cached_shadow_vmcs12;
8322 if (enable_shadow_vmcs && !alloc_shadow_vmcs(vcpu))
8323 goto out_shadow_vmcs;
8325 hrtimer_init(&vmx->nested.preemption_timer, CLOCK_MONOTONIC,
8326 HRTIMER_MODE_REL_PINNED);
8327 vmx->nested.preemption_timer.function = vmx_preemption_timer_fn;
8329 vmx->nested.vpid02 = allocate_vpid();
8331 vmx->nested.vmxon = true;
8332 return 0;
8334 out_shadow_vmcs:
8335 kfree(vmx->nested.cached_shadow_vmcs12);
8337 out_cached_shadow_vmcs12:
8338 kfree(vmx->nested.cached_vmcs12);
8340 out_cached_vmcs12:
8341 free_loaded_vmcs(&vmx->nested.vmcs02);
8343 out_vmcs02:
8344 return -ENOMEM;
8348 * Emulate the VMXON instruction.
8349 * Currently, we just remember that VMX is active, and do not save or even
8350 * inspect the argument to VMXON (the so-called "VMXON pointer") because we
8351 * do not currently need to store anything in that guest-allocated memory
8352 * region. Consequently, VMCLEAR and VMPTRLD also do not verify that the their
8353 * argument is different from the VMXON pointer (which the spec says they do).
8355 static int handle_vmon(struct kvm_vcpu *vcpu)
8357 int ret;
8358 gpa_t vmptr;
8359 struct page *page;
8360 struct vcpu_vmx *vmx = to_vmx(vcpu);
8361 const u64 VMXON_NEEDED_FEATURES = FEATURE_CONTROL_LOCKED
8362 | FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
8365 * The Intel VMX Instruction Reference lists a bunch of bits that are
8366 * prerequisite to running VMXON, most notably cr4.VMXE must be set to
8367 * 1 (see vmx_set_cr4() for when we allow the guest to set this).
8368 * Otherwise, we should fail with #UD. But most faulting conditions
8369 * have already been checked by hardware, prior to the VM-exit for
8370 * VMXON. We do test guest cr4.VMXE because processor CR4 always has
8371 * that bit set to 1 in non-root mode.
8373 if (!kvm_read_cr4_bits(vcpu, X86_CR4_VMXE)) {
8374 kvm_queue_exception(vcpu, UD_VECTOR);
8375 return 1;
8378 /* CPL=0 must be checked manually. */
8379 if (vmx_get_cpl(vcpu)) {
8380 kvm_inject_gp(vcpu, 0);
8381 return 1;
8384 if (vmx->nested.vmxon) {
8385 nested_vmx_failValid(vcpu, VMXERR_VMXON_IN_VMX_ROOT_OPERATION);
8386 return kvm_skip_emulated_instruction(vcpu);
8389 if ((vmx->msr_ia32_feature_control & VMXON_NEEDED_FEATURES)
8390 != VMXON_NEEDED_FEATURES) {
8391 kvm_inject_gp(vcpu, 0);
8392 return 1;
8395 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8396 return 1;
8399 * SDM 3: 24.11.5
8400 * The first 4 bytes of VMXON region contain the supported
8401 * VMCS revision identifier
8403 * Note - IA32_VMX_BASIC[48] will never be 1 for the nested case;
8404 * which replaces physical address width with 32
8406 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8407 nested_vmx_failInvalid(vcpu);
8408 return kvm_skip_emulated_instruction(vcpu);
8411 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8412 if (is_error_page(page)) {
8413 nested_vmx_failInvalid(vcpu);
8414 return kvm_skip_emulated_instruction(vcpu);
8416 if (*(u32 *)kmap(page) != VMCS12_REVISION) {
8417 kunmap(page);
8418 kvm_release_page_clean(page);
8419 nested_vmx_failInvalid(vcpu);
8420 return kvm_skip_emulated_instruction(vcpu);
8422 kunmap(page);
8423 kvm_release_page_clean(page);
8425 vmx->nested.vmxon_ptr = vmptr;
8426 ret = enter_vmx_operation(vcpu);
8427 if (ret)
8428 return ret;
8430 nested_vmx_succeed(vcpu);
8431 return kvm_skip_emulated_instruction(vcpu);
8435 * Intel's VMX Instruction Reference specifies a common set of prerequisites
8436 * for running VMX instructions (except VMXON, whose prerequisites are
8437 * slightly different). It also specifies what exception to inject otherwise.
8438 * Note that many of these exceptions have priority over VM exits, so they
8439 * don't have to be checked again here.
8441 static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
8443 if (!to_vmx(vcpu)->nested.vmxon) {
8444 kvm_queue_exception(vcpu, UD_VECTOR);
8445 return 0;
8448 if (vmx_get_cpl(vcpu)) {
8449 kvm_inject_gp(vcpu, 0);
8450 return 0;
8453 return 1;
8456 static void vmx_disable_shadow_vmcs(struct vcpu_vmx *vmx)
8458 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL, SECONDARY_EXEC_SHADOW_VMCS);
8459 vmcs_write64(VMCS_LINK_POINTER, -1ull);
8460 vmx->nested.sync_shadow_vmcs = false;
8463 static inline void nested_release_vmcs12(struct vcpu_vmx *vmx)
8465 if (vmx->nested.current_vmptr == -1ull)
8466 return;
8468 if (enable_shadow_vmcs) {
8469 /* copy to memory all shadowed fields in case
8470 they were modified */
8471 copy_shadow_to_vmcs12(vmx);
8472 vmx_disable_shadow_vmcs(vmx);
8474 vmx->nested.posted_intr_nv = -1;
8476 /* Flush VMCS12 to guest memory */
8477 kvm_vcpu_write_guest_page(&vmx->vcpu,
8478 vmx->nested.current_vmptr >> PAGE_SHIFT,
8479 vmx->nested.cached_vmcs12, 0, VMCS12_SIZE);
8481 vmx->nested.current_vmptr = -1ull;
8485 * Free whatever needs to be freed from vmx->nested when L1 goes down, or
8486 * just stops using VMX.
8488 static void free_nested(struct vcpu_vmx *vmx)
8490 if (!vmx->nested.vmxon && !vmx->nested.smm.vmxon)
8491 return;
8493 kvm_clear_request(KVM_REQ_GET_VMCS12_PAGES, &vmx->vcpu);
8495 hrtimer_cancel(&vmx->nested.preemption_timer);
8496 vmx->nested.vmxon = false;
8497 vmx->nested.smm.vmxon = false;
8498 free_vpid(vmx->nested.vpid02);
8499 vmx->nested.posted_intr_nv = -1;
8500 vmx->nested.current_vmptr = -1ull;
8501 if (enable_shadow_vmcs) {
8502 vmx_disable_shadow_vmcs(vmx);
8503 vmcs_clear(vmx->vmcs01.shadow_vmcs);
8504 free_vmcs(vmx->vmcs01.shadow_vmcs);
8505 vmx->vmcs01.shadow_vmcs = NULL;
8507 kfree(vmx->nested.cached_vmcs12);
8508 kfree(vmx->nested.cached_shadow_vmcs12);
8509 /* Unpin physical memory we referred to in the vmcs02 */
8510 if (vmx->nested.apic_access_page) {
8511 kvm_release_page_dirty(vmx->nested.apic_access_page);
8512 vmx->nested.apic_access_page = NULL;
8514 if (vmx->nested.virtual_apic_page) {
8515 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
8516 vmx->nested.virtual_apic_page = NULL;
8518 if (vmx->nested.pi_desc_page) {
8519 kunmap(vmx->nested.pi_desc_page);
8520 kvm_release_page_dirty(vmx->nested.pi_desc_page);
8521 vmx->nested.pi_desc_page = NULL;
8522 vmx->nested.pi_desc = NULL;
8525 free_loaded_vmcs(&vmx->nested.vmcs02);
8528 /* Emulate the VMXOFF instruction */
8529 static int handle_vmoff(struct kvm_vcpu *vcpu)
8531 if (!nested_vmx_check_permission(vcpu))
8532 return 1;
8533 free_nested(to_vmx(vcpu));
8534 nested_vmx_succeed(vcpu);
8535 return kvm_skip_emulated_instruction(vcpu);
8538 /* Emulate the VMCLEAR instruction */
8539 static int handle_vmclear(struct kvm_vcpu *vcpu)
8541 struct vcpu_vmx *vmx = to_vmx(vcpu);
8542 u32 zero = 0;
8543 gpa_t vmptr;
8545 if (!nested_vmx_check_permission(vcpu))
8546 return 1;
8548 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8549 return 1;
8551 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8552 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_INVALID_ADDRESS);
8553 return kvm_skip_emulated_instruction(vcpu);
8556 if (vmptr == vmx->nested.vmxon_ptr) {
8557 nested_vmx_failValid(vcpu, VMXERR_VMCLEAR_VMXON_POINTER);
8558 return kvm_skip_emulated_instruction(vcpu);
8561 if (vmptr == vmx->nested.current_vmptr)
8562 nested_release_vmcs12(vmx);
8564 kvm_vcpu_write_guest(vcpu,
8565 vmptr + offsetof(struct vmcs12, launch_state),
8566 &zero, sizeof(zero));
8568 nested_vmx_succeed(vcpu);
8569 return kvm_skip_emulated_instruction(vcpu);
8572 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch);
8574 /* Emulate the VMLAUNCH instruction */
8575 static int handle_vmlaunch(struct kvm_vcpu *vcpu)
8577 return nested_vmx_run(vcpu, true);
8580 /* Emulate the VMRESUME instruction */
8581 static int handle_vmresume(struct kvm_vcpu *vcpu)
8584 return nested_vmx_run(vcpu, false);
8588 * Read a vmcs12 field. Since these can have varying lengths and we return
8589 * one type, we chose the biggest type (u64) and zero-extend the return value
8590 * to that size. Note that the caller, handle_vmread, might need to use only
8591 * some of the bits we return here (e.g., on 32-bit guests, only 32 bits of
8592 * 64-bit fields are to be returned).
8594 static inline int vmcs12_read_any(struct vmcs12 *vmcs12,
8595 unsigned long field, u64 *ret)
8597 short offset = vmcs_field_to_offset(field);
8598 char *p;
8600 if (offset < 0)
8601 return offset;
8603 p = (char *)vmcs12 + offset;
8605 switch (vmcs_field_width(field)) {
8606 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8607 *ret = *((natural_width *)p);
8608 return 0;
8609 case VMCS_FIELD_WIDTH_U16:
8610 *ret = *((u16 *)p);
8611 return 0;
8612 case VMCS_FIELD_WIDTH_U32:
8613 *ret = *((u32 *)p);
8614 return 0;
8615 case VMCS_FIELD_WIDTH_U64:
8616 *ret = *((u64 *)p);
8617 return 0;
8618 default:
8619 WARN_ON(1);
8620 return -ENOENT;
8625 static inline int vmcs12_write_any(struct vmcs12 *vmcs12,
8626 unsigned long field, u64 field_value){
8627 short offset = vmcs_field_to_offset(field);
8628 char *p = (char *)vmcs12 + offset;
8629 if (offset < 0)
8630 return offset;
8632 switch (vmcs_field_width(field)) {
8633 case VMCS_FIELD_WIDTH_U16:
8634 *(u16 *)p = field_value;
8635 return 0;
8636 case VMCS_FIELD_WIDTH_U32:
8637 *(u32 *)p = field_value;
8638 return 0;
8639 case VMCS_FIELD_WIDTH_U64:
8640 *(u64 *)p = field_value;
8641 return 0;
8642 case VMCS_FIELD_WIDTH_NATURAL_WIDTH:
8643 *(natural_width *)p = field_value;
8644 return 0;
8645 default:
8646 WARN_ON(1);
8647 return -ENOENT;
8653 * Copy the writable VMCS shadow fields back to the VMCS12, in case
8654 * they have been modified by the L1 guest. Note that the "read-only"
8655 * VM-exit information fields are actually writable if the vCPU is
8656 * configured to support "VMWRITE to any supported field in the VMCS."
8658 static void copy_shadow_to_vmcs12(struct vcpu_vmx *vmx)
8660 const u16 *fields[] = {
8661 shadow_read_write_fields,
8662 shadow_read_only_fields
8664 const int max_fields[] = {
8665 max_shadow_read_write_fields,
8666 max_shadow_read_only_fields
8668 int i, q;
8669 unsigned long field;
8670 u64 field_value;
8671 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8673 if (WARN_ON(!shadow_vmcs))
8674 return;
8676 preempt_disable();
8678 vmcs_load(shadow_vmcs);
8680 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8681 for (i = 0; i < max_fields[q]; i++) {
8682 field = fields[q][i];
8683 field_value = __vmcs_readl(field);
8684 vmcs12_write_any(get_vmcs12(&vmx->vcpu), field, field_value);
8687 * Skip the VM-exit information fields if they are read-only.
8689 if (!nested_cpu_has_vmwrite_any_field(&vmx->vcpu))
8690 break;
8693 vmcs_clear(shadow_vmcs);
8694 vmcs_load(vmx->loaded_vmcs->vmcs);
8696 preempt_enable();
8699 static void copy_vmcs12_to_shadow(struct vcpu_vmx *vmx)
8701 const u16 *fields[] = {
8702 shadow_read_write_fields,
8703 shadow_read_only_fields
8705 const int max_fields[] = {
8706 max_shadow_read_write_fields,
8707 max_shadow_read_only_fields
8709 int i, q;
8710 unsigned long field;
8711 u64 field_value = 0;
8712 struct vmcs *shadow_vmcs = vmx->vmcs01.shadow_vmcs;
8714 if (WARN_ON(!shadow_vmcs))
8715 return;
8717 vmcs_load(shadow_vmcs);
8719 for (q = 0; q < ARRAY_SIZE(fields); q++) {
8720 for (i = 0; i < max_fields[q]; i++) {
8721 field = fields[q][i];
8722 vmcs12_read_any(get_vmcs12(&vmx->vcpu), field, &field_value);
8723 __vmcs_writel(field, field_value);
8727 vmcs_clear(shadow_vmcs);
8728 vmcs_load(vmx->loaded_vmcs->vmcs);
8732 * VMX instructions which assume a current vmcs12 (i.e., that VMPTRLD was
8733 * used before) all generate the same failure when it is missing.
8735 static int nested_vmx_check_vmcs12(struct kvm_vcpu *vcpu)
8737 struct vcpu_vmx *vmx = to_vmx(vcpu);
8738 if (vmx->nested.current_vmptr == -1ull) {
8739 nested_vmx_failInvalid(vcpu);
8740 return 0;
8742 return 1;
8745 static int handle_vmread(struct kvm_vcpu *vcpu)
8747 unsigned long field;
8748 u64 field_value;
8749 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8750 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8751 gva_t gva = 0;
8752 struct vmcs12 *vmcs12;
8754 if (!nested_vmx_check_permission(vcpu))
8755 return 1;
8757 if (!nested_vmx_check_vmcs12(vcpu))
8758 return kvm_skip_emulated_instruction(vcpu);
8760 if (!is_guest_mode(vcpu))
8761 vmcs12 = get_vmcs12(vcpu);
8762 else {
8764 * When vmcs->vmcs_link_pointer is -1ull, any VMREAD
8765 * to shadowed-field sets the ALU flags for VMfailInvalid.
8767 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8768 nested_vmx_failInvalid(vcpu);
8769 return kvm_skip_emulated_instruction(vcpu);
8771 vmcs12 = get_shadow_vmcs12(vcpu);
8774 /* Decode instruction info and find the field to read */
8775 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8776 /* Read the field, zero-extended to a u64 field_value */
8777 if (vmcs12_read_any(vmcs12, field, &field_value) < 0) {
8778 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8779 return kvm_skip_emulated_instruction(vcpu);
8782 * Now copy part of this value to register or memory, as requested.
8783 * Note that the number of bits actually copied is 32 or 64 depending
8784 * on the guest's mode (32 or 64 bit), not on the given field's length.
8786 if (vmx_instruction_info & (1u << 10)) {
8787 kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
8788 field_value);
8789 } else {
8790 if (get_vmx_mem_address(vcpu, exit_qualification,
8791 vmx_instruction_info, true, &gva))
8792 return 1;
8793 /* _system ok, nested_vmx_check_permission has verified cpl=0 */
8794 kvm_write_guest_virt_system(vcpu, gva, &field_value,
8795 (is_long_mode(vcpu) ? 8 : 4), NULL);
8798 nested_vmx_succeed(vcpu);
8799 return kvm_skip_emulated_instruction(vcpu);
8803 static int handle_vmwrite(struct kvm_vcpu *vcpu)
8805 unsigned long field;
8806 gva_t gva;
8807 struct vcpu_vmx *vmx = to_vmx(vcpu);
8808 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
8809 u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8811 /* The value to write might be 32 or 64 bits, depending on L1's long
8812 * mode, and eventually we need to write that into a field of several
8813 * possible lengths. The code below first zero-extends the value to 64
8814 * bit (field_value), and then copies only the appropriate number of
8815 * bits into the vmcs12 field.
8817 u64 field_value = 0;
8818 struct x86_exception e;
8819 struct vmcs12 *vmcs12;
8821 if (!nested_vmx_check_permission(vcpu))
8822 return 1;
8824 if (!nested_vmx_check_vmcs12(vcpu))
8825 return kvm_skip_emulated_instruction(vcpu);
8827 if (vmx_instruction_info & (1u << 10))
8828 field_value = kvm_register_readl(vcpu,
8829 (((vmx_instruction_info) >> 3) & 0xf));
8830 else {
8831 if (get_vmx_mem_address(vcpu, exit_qualification,
8832 vmx_instruction_info, false, &gva))
8833 return 1;
8834 if (kvm_read_guest_virt(vcpu, gva, &field_value,
8835 (is_64_bit_mode(vcpu) ? 8 : 4), &e)) {
8836 kvm_inject_page_fault(vcpu, &e);
8837 return 1;
8842 field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
8844 * If the vCPU supports "VMWRITE to any supported field in the
8845 * VMCS," then the "read-only" fields are actually read/write.
8847 if (vmcs_field_readonly(field) &&
8848 !nested_cpu_has_vmwrite_any_field(vcpu)) {
8849 nested_vmx_failValid(vcpu,
8850 VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT);
8851 return kvm_skip_emulated_instruction(vcpu);
8854 if (!is_guest_mode(vcpu))
8855 vmcs12 = get_vmcs12(vcpu);
8856 else {
8858 * When vmcs->vmcs_link_pointer is -1ull, any VMWRITE
8859 * to shadowed-field sets the ALU flags for VMfailInvalid.
8861 if (get_vmcs12(vcpu)->vmcs_link_pointer == -1ull) {
8862 nested_vmx_failInvalid(vcpu);
8863 return kvm_skip_emulated_instruction(vcpu);
8865 vmcs12 = get_shadow_vmcs12(vcpu);
8869 if (vmcs12_write_any(vmcs12, field, field_value) < 0) {
8870 nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
8871 return kvm_skip_emulated_instruction(vcpu);
8875 * Do not track vmcs12 dirty-state if in guest-mode
8876 * as we actually dirty shadow vmcs12 instead of vmcs12.
8878 if (!is_guest_mode(vcpu)) {
8879 switch (field) {
8880 #define SHADOW_FIELD_RW(x) case x:
8881 #include "vmx_shadow_fields.h"
8883 * The fields that can be updated by L1 without a vmexit are
8884 * always updated in the vmcs02, the others go down the slow
8885 * path of prepare_vmcs02.
8887 break;
8888 default:
8889 vmx->nested.dirty_vmcs12 = true;
8890 break;
8894 nested_vmx_succeed(vcpu);
8895 return kvm_skip_emulated_instruction(vcpu);
8898 static void set_current_vmptr(struct vcpu_vmx *vmx, gpa_t vmptr)
8900 vmx->nested.current_vmptr = vmptr;
8901 if (enable_shadow_vmcs) {
8902 vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
8903 SECONDARY_EXEC_SHADOW_VMCS);
8904 vmcs_write64(VMCS_LINK_POINTER,
8905 __pa(vmx->vmcs01.shadow_vmcs));
8906 vmx->nested.sync_shadow_vmcs = true;
8908 vmx->nested.dirty_vmcs12 = true;
8911 /* Emulate the VMPTRLD instruction */
8912 static int handle_vmptrld(struct kvm_vcpu *vcpu)
8914 struct vcpu_vmx *vmx = to_vmx(vcpu);
8915 gpa_t vmptr;
8917 if (!nested_vmx_check_permission(vcpu))
8918 return 1;
8920 if (nested_vmx_get_vmptr(vcpu, &vmptr))
8921 return 1;
8923 if (!PAGE_ALIGNED(vmptr) || (vmptr >> cpuid_maxphyaddr(vcpu))) {
8924 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_INVALID_ADDRESS);
8925 return kvm_skip_emulated_instruction(vcpu);
8928 if (vmptr == vmx->nested.vmxon_ptr) {
8929 nested_vmx_failValid(vcpu, VMXERR_VMPTRLD_VMXON_POINTER);
8930 return kvm_skip_emulated_instruction(vcpu);
8933 if (vmx->nested.current_vmptr != vmptr) {
8934 struct vmcs12 *new_vmcs12;
8935 struct page *page;
8936 page = kvm_vcpu_gpa_to_page(vcpu, vmptr);
8937 if (is_error_page(page)) {
8938 nested_vmx_failInvalid(vcpu);
8939 return kvm_skip_emulated_instruction(vcpu);
8941 new_vmcs12 = kmap(page);
8942 if (new_vmcs12->hdr.revision_id != VMCS12_REVISION ||
8943 (new_vmcs12->hdr.shadow_vmcs &&
8944 !nested_cpu_has_vmx_shadow_vmcs(vcpu))) {
8945 kunmap(page);
8946 kvm_release_page_clean(page);
8947 nested_vmx_failValid(vcpu,
8948 VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID);
8949 return kvm_skip_emulated_instruction(vcpu);
8952 nested_release_vmcs12(vmx);
8954 * Load VMCS12 from guest memory since it is not already
8955 * cached.
8957 memcpy(vmx->nested.cached_vmcs12, new_vmcs12, VMCS12_SIZE);
8958 kunmap(page);
8959 kvm_release_page_clean(page);
8961 set_current_vmptr(vmx, vmptr);
8964 nested_vmx_succeed(vcpu);
8965 return kvm_skip_emulated_instruction(vcpu);
8968 /* Emulate the VMPTRST instruction */
8969 static int handle_vmptrst(struct kvm_vcpu *vcpu)
8971 unsigned long exit_qual = vmcs_readl(EXIT_QUALIFICATION);
8972 u32 instr_info = vmcs_read32(VMX_INSTRUCTION_INFO);
8973 gpa_t current_vmptr = to_vmx(vcpu)->nested.current_vmptr;
8974 struct x86_exception e;
8975 gva_t gva;
8977 if (!nested_vmx_check_permission(vcpu))
8978 return 1;
8980 if (get_vmx_mem_address(vcpu, exit_qual, instr_info, true, &gva))
8981 return 1;
8982 /* *_system ok, nested_vmx_check_permission has verified cpl=0 */
8983 if (kvm_write_guest_virt_system(vcpu, gva, (void *)&current_vmptr,
8984 sizeof(gpa_t), &e)) {
8985 kvm_inject_page_fault(vcpu, &e);
8986 return 1;
8988 nested_vmx_succeed(vcpu);
8989 return kvm_skip_emulated_instruction(vcpu);
8992 /* Emulate the INVEPT instruction */
8993 static int handle_invept(struct kvm_vcpu *vcpu)
8995 struct vcpu_vmx *vmx = to_vmx(vcpu);
8996 u32 vmx_instruction_info, types;
8997 unsigned long type;
8998 gva_t gva;
8999 struct x86_exception e;
9000 struct {
9001 u64 eptp, gpa;
9002 } operand;
9004 if (!(vmx->nested.msrs.secondary_ctls_high &
9005 SECONDARY_EXEC_ENABLE_EPT) ||
9006 !(vmx->nested.msrs.ept_caps & VMX_EPT_INVEPT_BIT)) {
9007 kvm_queue_exception(vcpu, UD_VECTOR);
9008 return 1;
9011 if (!nested_vmx_check_permission(vcpu))
9012 return 1;
9014 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9015 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9017 types = (vmx->nested.msrs.ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6;
9019 if (type >= 32 || !(types & (1 << type))) {
9020 nested_vmx_failValid(vcpu,
9021 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9022 return kvm_skip_emulated_instruction(vcpu);
9025 /* According to the Intel VMX instruction reference, the memory
9026 * operand is read even if it isn't needed (e.g., for type==global)
9028 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9029 vmx_instruction_info, false, &gva))
9030 return 1;
9031 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9032 kvm_inject_page_fault(vcpu, &e);
9033 return 1;
9036 switch (type) {
9037 case VMX_EPT_EXTENT_GLOBAL:
9039 * TODO: track mappings and invalidate
9040 * single context requests appropriately
9042 case VMX_EPT_EXTENT_CONTEXT:
9043 kvm_mmu_sync_roots(vcpu);
9044 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9045 nested_vmx_succeed(vcpu);
9046 break;
9047 default:
9048 BUG_ON(1);
9049 break;
9052 return kvm_skip_emulated_instruction(vcpu);
9055 static int handle_invvpid(struct kvm_vcpu *vcpu)
9057 struct vcpu_vmx *vmx = to_vmx(vcpu);
9058 u32 vmx_instruction_info;
9059 unsigned long type, types;
9060 gva_t gva;
9061 struct x86_exception e;
9062 struct {
9063 u64 vpid;
9064 u64 gla;
9065 } operand;
9067 if (!(vmx->nested.msrs.secondary_ctls_high &
9068 SECONDARY_EXEC_ENABLE_VPID) ||
9069 !(vmx->nested.msrs.vpid_caps & VMX_VPID_INVVPID_BIT)) {
9070 kvm_queue_exception(vcpu, UD_VECTOR);
9071 return 1;
9074 if (!nested_vmx_check_permission(vcpu))
9075 return 1;
9077 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9078 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9080 types = (vmx->nested.msrs.vpid_caps &
9081 VMX_VPID_EXTENT_SUPPORTED_MASK) >> 8;
9083 if (type >= 32 || !(types & (1 << type))) {
9084 nested_vmx_failValid(vcpu,
9085 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9086 return kvm_skip_emulated_instruction(vcpu);
9089 /* according to the intel vmx instruction reference, the memory
9090 * operand is read even if it isn't needed (e.g., for type==global)
9092 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9093 vmx_instruction_info, false, &gva))
9094 return 1;
9095 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9096 kvm_inject_page_fault(vcpu, &e);
9097 return 1;
9099 if (operand.vpid >> 16) {
9100 nested_vmx_failValid(vcpu,
9101 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9102 return kvm_skip_emulated_instruction(vcpu);
9105 switch (type) {
9106 case VMX_VPID_EXTENT_INDIVIDUAL_ADDR:
9107 if (!operand.vpid ||
9108 is_noncanonical_address(operand.gla, vcpu)) {
9109 nested_vmx_failValid(vcpu,
9110 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9111 return kvm_skip_emulated_instruction(vcpu);
9113 if (cpu_has_vmx_invvpid_individual_addr() &&
9114 vmx->nested.vpid02) {
9115 __invvpid(VMX_VPID_EXTENT_INDIVIDUAL_ADDR,
9116 vmx->nested.vpid02, operand.gla);
9117 } else
9118 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9119 break;
9120 case VMX_VPID_EXTENT_SINGLE_CONTEXT:
9121 case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL:
9122 if (!operand.vpid) {
9123 nested_vmx_failValid(vcpu,
9124 VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID);
9125 return kvm_skip_emulated_instruction(vcpu);
9127 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9128 break;
9129 case VMX_VPID_EXTENT_ALL_CONTEXT:
9130 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
9131 break;
9132 default:
9133 WARN_ON_ONCE(1);
9134 return kvm_skip_emulated_instruction(vcpu);
9137 nested_vmx_succeed(vcpu);
9139 return kvm_skip_emulated_instruction(vcpu);
9142 static int handle_invpcid(struct kvm_vcpu *vcpu)
9144 u32 vmx_instruction_info;
9145 unsigned long type;
9146 bool pcid_enabled;
9147 gva_t gva;
9148 struct x86_exception e;
9149 unsigned i;
9150 unsigned long roots_to_free = 0;
9151 struct {
9152 u64 pcid;
9153 u64 gla;
9154 } operand;
9156 if (!guest_cpuid_has(vcpu, X86_FEATURE_INVPCID)) {
9157 kvm_queue_exception(vcpu, UD_VECTOR);
9158 return 1;
9161 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9162 type = kvm_register_readl(vcpu, (vmx_instruction_info >> 28) & 0xf);
9164 if (type > 3) {
9165 kvm_inject_gp(vcpu, 0);
9166 return 1;
9169 /* According to the Intel instruction reference, the memory operand
9170 * is read even if it isn't needed (e.g., for type==all)
9172 if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION),
9173 vmx_instruction_info, false, &gva))
9174 return 1;
9176 if (kvm_read_guest_virt(vcpu, gva, &operand, sizeof(operand), &e)) {
9177 kvm_inject_page_fault(vcpu, &e);
9178 return 1;
9181 if (operand.pcid >> 12 != 0) {
9182 kvm_inject_gp(vcpu, 0);
9183 return 1;
9186 pcid_enabled = kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE);
9188 switch (type) {
9189 case INVPCID_TYPE_INDIV_ADDR:
9190 if ((!pcid_enabled && (operand.pcid != 0)) ||
9191 is_noncanonical_address(operand.gla, vcpu)) {
9192 kvm_inject_gp(vcpu, 0);
9193 return 1;
9195 kvm_mmu_invpcid_gva(vcpu, operand.gla, operand.pcid);
9196 return kvm_skip_emulated_instruction(vcpu);
9198 case INVPCID_TYPE_SINGLE_CTXT:
9199 if (!pcid_enabled && (operand.pcid != 0)) {
9200 kvm_inject_gp(vcpu, 0);
9201 return 1;
9204 if (kvm_get_active_pcid(vcpu) == operand.pcid) {
9205 kvm_mmu_sync_roots(vcpu);
9206 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
9209 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
9210 if (kvm_get_pcid(vcpu, vcpu->arch.mmu.prev_roots[i].cr3)
9211 == operand.pcid)
9212 roots_to_free |= KVM_MMU_ROOT_PREVIOUS(i);
9214 kvm_mmu_free_roots(vcpu, roots_to_free);
9216 * If neither the current cr3 nor any of the prev_roots use the
9217 * given PCID, then nothing needs to be done here because a
9218 * resync will happen anyway before switching to any other CR3.
9221 return kvm_skip_emulated_instruction(vcpu);
9223 case INVPCID_TYPE_ALL_NON_GLOBAL:
9225 * Currently, KVM doesn't mark global entries in the shadow
9226 * page tables, so a non-global flush just degenerates to a
9227 * global flush. If needed, we could optimize this later by
9228 * keeping track of global entries in shadow page tables.
9231 /* fall-through */
9232 case INVPCID_TYPE_ALL_INCL_GLOBAL:
9233 kvm_mmu_unload(vcpu);
9234 return kvm_skip_emulated_instruction(vcpu);
9236 default:
9237 BUG(); /* We have already checked above that type <= 3 */
9241 static int handle_pml_full(struct kvm_vcpu *vcpu)
9243 unsigned long exit_qualification;
9245 trace_kvm_pml_full(vcpu->vcpu_id);
9247 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9250 * PML buffer FULL happened while executing iret from NMI,
9251 * "blocked by NMI" bit has to be set before next VM entry.
9253 if (!(to_vmx(vcpu)->idt_vectoring_info & VECTORING_INFO_VALID_MASK) &&
9254 enable_vnmi &&
9255 (exit_qualification & INTR_INFO_UNBLOCK_NMI))
9256 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
9257 GUEST_INTR_STATE_NMI);
9260 * PML buffer already flushed at beginning of VMEXIT. Nothing to do
9261 * here.., and there's no userspace involvement needed for PML.
9263 return 1;
9266 static int handle_preemption_timer(struct kvm_vcpu *vcpu)
9268 if (!to_vmx(vcpu)->req_immediate_exit)
9269 kvm_lapic_expired_hv_timer(vcpu);
9270 return 1;
9273 static bool valid_ept_address(struct kvm_vcpu *vcpu, u64 address)
9275 struct vcpu_vmx *vmx = to_vmx(vcpu);
9276 int maxphyaddr = cpuid_maxphyaddr(vcpu);
9278 /* Check for memory type validity */
9279 switch (address & VMX_EPTP_MT_MASK) {
9280 case VMX_EPTP_MT_UC:
9281 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_UC_BIT))
9282 return false;
9283 break;
9284 case VMX_EPTP_MT_WB:
9285 if (!(vmx->nested.msrs.ept_caps & VMX_EPTP_WB_BIT))
9286 return false;
9287 break;
9288 default:
9289 return false;
9292 /* only 4 levels page-walk length are valid */
9293 if ((address & VMX_EPTP_PWL_MASK) != VMX_EPTP_PWL_4)
9294 return false;
9296 /* Reserved bits should not be set */
9297 if (address >> maxphyaddr || ((address >> 7) & 0x1f))
9298 return false;
9300 /* AD, if set, should be supported */
9301 if (address & VMX_EPTP_AD_ENABLE_BIT) {
9302 if (!(vmx->nested.msrs.ept_caps & VMX_EPT_AD_BIT))
9303 return false;
9306 return true;
9309 static int nested_vmx_eptp_switching(struct kvm_vcpu *vcpu,
9310 struct vmcs12 *vmcs12)
9312 u32 index = vcpu->arch.regs[VCPU_REGS_RCX];
9313 u64 address;
9314 bool accessed_dirty;
9315 struct kvm_mmu *mmu = vcpu->arch.walk_mmu;
9317 if (!nested_cpu_has_eptp_switching(vmcs12) ||
9318 !nested_cpu_has_ept(vmcs12))
9319 return 1;
9321 if (index >= VMFUNC_EPTP_ENTRIES)
9322 return 1;
9325 if (kvm_vcpu_read_guest_page(vcpu, vmcs12->eptp_list_address >> PAGE_SHIFT,
9326 &address, index * 8, 8))
9327 return 1;
9329 accessed_dirty = !!(address & VMX_EPTP_AD_ENABLE_BIT);
9332 * If the (L2) guest does a vmfunc to the currently
9333 * active ept pointer, we don't have to do anything else
9335 if (vmcs12->ept_pointer != address) {
9336 if (!valid_ept_address(vcpu, address))
9337 return 1;
9339 kvm_mmu_unload(vcpu);
9340 mmu->ept_ad = accessed_dirty;
9341 mmu->base_role.ad_disabled = !accessed_dirty;
9342 vmcs12->ept_pointer = address;
9344 * TODO: Check what's the correct approach in case
9345 * mmu reload fails. Currently, we just let the next
9346 * reload potentially fail
9348 kvm_mmu_reload(vcpu);
9351 return 0;
9354 static int handle_vmfunc(struct kvm_vcpu *vcpu)
9356 struct vcpu_vmx *vmx = to_vmx(vcpu);
9357 struct vmcs12 *vmcs12;
9358 u32 function = vcpu->arch.regs[VCPU_REGS_RAX];
9361 * VMFUNC is only supported for nested guests, but we always enable the
9362 * secondary control for simplicity; for non-nested mode, fake that we
9363 * didn't by injecting #UD.
9365 if (!is_guest_mode(vcpu)) {
9366 kvm_queue_exception(vcpu, UD_VECTOR);
9367 return 1;
9370 vmcs12 = get_vmcs12(vcpu);
9371 if ((vmcs12->vm_function_control & (1 << function)) == 0)
9372 goto fail;
9374 switch (function) {
9375 case 0:
9376 if (nested_vmx_eptp_switching(vcpu, vmcs12))
9377 goto fail;
9378 break;
9379 default:
9380 goto fail;
9382 return kvm_skip_emulated_instruction(vcpu);
9384 fail:
9385 nested_vmx_vmexit(vcpu, vmx->exit_reason,
9386 vmcs_read32(VM_EXIT_INTR_INFO),
9387 vmcs_readl(EXIT_QUALIFICATION));
9388 return 1;
9391 static int handle_encls(struct kvm_vcpu *vcpu)
9394 * SGX virtualization is not yet supported. There is no software
9395 * enable bit for SGX, so we have to trap ENCLS and inject a #UD
9396 * to prevent the guest from executing ENCLS.
9398 kvm_queue_exception(vcpu, UD_VECTOR);
9399 return 1;
9403 * The exit handlers return 1 if the exit was handled fully and guest execution
9404 * may resume. Otherwise they set the kvm_run parameter to indicate what needs
9405 * to be done to userspace and return 0.
9407 static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = {
9408 [EXIT_REASON_EXCEPTION_NMI] = handle_exception,
9409 [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt,
9410 [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault,
9411 [EXIT_REASON_NMI_WINDOW] = handle_nmi_window,
9412 [EXIT_REASON_IO_INSTRUCTION] = handle_io,
9413 [EXIT_REASON_CR_ACCESS] = handle_cr,
9414 [EXIT_REASON_DR_ACCESS] = handle_dr,
9415 [EXIT_REASON_CPUID] = handle_cpuid,
9416 [EXIT_REASON_MSR_READ] = handle_rdmsr,
9417 [EXIT_REASON_MSR_WRITE] = handle_wrmsr,
9418 [EXIT_REASON_PENDING_INTERRUPT] = handle_interrupt_window,
9419 [EXIT_REASON_HLT] = handle_halt,
9420 [EXIT_REASON_INVD] = handle_invd,
9421 [EXIT_REASON_INVLPG] = handle_invlpg,
9422 [EXIT_REASON_RDPMC] = handle_rdpmc,
9423 [EXIT_REASON_VMCALL] = handle_vmcall,
9424 [EXIT_REASON_VMCLEAR] = handle_vmclear,
9425 [EXIT_REASON_VMLAUNCH] = handle_vmlaunch,
9426 [EXIT_REASON_VMPTRLD] = handle_vmptrld,
9427 [EXIT_REASON_VMPTRST] = handle_vmptrst,
9428 [EXIT_REASON_VMREAD] = handle_vmread,
9429 [EXIT_REASON_VMRESUME] = handle_vmresume,
9430 [EXIT_REASON_VMWRITE] = handle_vmwrite,
9431 [EXIT_REASON_VMOFF] = handle_vmoff,
9432 [EXIT_REASON_VMON] = handle_vmon,
9433 [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold,
9434 [EXIT_REASON_APIC_ACCESS] = handle_apic_access,
9435 [EXIT_REASON_APIC_WRITE] = handle_apic_write,
9436 [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced,
9437 [EXIT_REASON_WBINVD] = handle_wbinvd,
9438 [EXIT_REASON_XSETBV] = handle_xsetbv,
9439 [EXIT_REASON_TASK_SWITCH] = handle_task_switch,
9440 [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check,
9441 [EXIT_REASON_GDTR_IDTR] = handle_desc,
9442 [EXIT_REASON_LDTR_TR] = handle_desc,
9443 [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation,
9444 [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig,
9445 [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause,
9446 [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait,
9447 [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap,
9448 [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor,
9449 [EXIT_REASON_INVEPT] = handle_invept,
9450 [EXIT_REASON_INVVPID] = handle_invvpid,
9451 [EXIT_REASON_RDRAND] = handle_invalid_op,
9452 [EXIT_REASON_RDSEED] = handle_invalid_op,
9453 [EXIT_REASON_XSAVES] = handle_xsaves,
9454 [EXIT_REASON_XRSTORS] = handle_xrstors,
9455 [EXIT_REASON_PML_FULL] = handle_pml_full,
9456 [EXIT_REASON_INVPCID] = handle_invpcid,
9457 [EXIT_REASON_VMFUNC] = handle_vmfunc,
9458 [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer,
9459 [EXIT_REASON_ENCLS] = handle_encls,
9462 static const int kvm_vmx_max_exit_handlers =
9463 ARRAY_SIZE(kvm_vmx_exit_handlers);
9465 static bool nested_vmx_exit_handled_io(struct kvm_vcpu *vcpu,
9466 struct vmcs12 *vmcs12)
9468 unsigned long exit_qualification;
9469 gpa_t bitmap, last_bitmap;
9470 unsigned int port;
9471 int size;
9472 u8 b;
9474 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
9475 return nested_cpu_has(vmcs12, CPU_BASED_UNCOND_IO_EXITING);
9477 exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9479 port = exit_qualification >> 16;
9480 size = (exit_qualification & 7) + 1;
9482 last_bitmap = (gpa_t)-1;
9483 b = -1;
9485 while (size > 0) {
9486 if (port < 0x8000)
9487 bitmap = vmcs12->io_bitmap_a;
9488 else if (port < 0x10000)
9489 bitmap = vmcs12->io_bitmap_b;
9490 else
9491 return true;
9492 bitmap += (port & 0x7fff) / 8;
9494 if (last_bitmap != bitmap)
9495 if (kvm_vcpu_read_guest(vcpu, bitmap, &b, 1))
9496 return true;
9497 if (b & (1 << (port & 7)))
9498 return true;
9500 port++;
9501 size--;
9502 last_bitmap = bitmap;
9505 return false;
9509 * Return 1 if we should exit from L2 to L1 to handle an MSR access access,
9510 * rather than handle it ourselves in L0. I.e., check whether L1 expressed
9511 * disinterest in the current event (read or write a specific MSR) by using an
9512 * MSR bitmap. This may be the case even when L0 doesn't use MSR bitmaps.
9514 static bool nested_vmx_exit_handled_msr(struct kvm_vcpu *vcpu,
9515 struct vmcs12 *vmcs12, u32 exit_reason)
9517 u32 msr_index = vcpu->arch.regs[VCPU_REGS_RCX];
9518 gpa_t bitmap;
9520 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
9521 return true;
9524 * The MSR_BITMAP page is divided into four 1024-byte bitmaps,
9525 * for the four combinations of read/write and low/high MSR numbers.
9526 * First we need to figure out which of the four to use:
9528 bitmap = vmcs12->msr_bitmap;
9529 if (exit_reason == EXIT_REASON_MSR_WRITE)
9530 bitmap += 2048;
9531 if (msr_index >= 0xc0000000) {
9532 msr_index -= 0xc0000000;
9533 bitmap += 1024;
9536 /* Then read the msr_index'th bit from this bitmap: */
9537 if (msr_index < 1024*8) {
9538 unsigned char b;
9539 if (kvm_vcpu_read_guest(vcpu, bitmap + msr_index/8, &b, 1))
9540 return true;
9541 return 1 & (b >> (msr_index & 7));
9542 } else
9543 return true; /* let L1 handle the wrong parameter */
9547 * Return 1 if we should exit from L2 to L1 to handle a CR access exit,
9548 * rather than handle it ourselves in L0. I.e., check if L1 wanted to
9549 * intercept (via guest_host_mask etc.) the current event.
9551 static bool nested_vmx_exit_handled_cr(struct kvm_vcpu *vcpu,
9552 struct vmcs12 *vmcs12)
9554 unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
9555 int cr = exit_qualification & 15;
9556 int reg;
9557 unsigned long val;
9559 switch ((exit_qualification >> 4) & 3) {
9560 case 0: /* mov to cr */
9561 reg = (exit_qualification >> 8) & 15;
9562 val = kvm_register_readl(vcpu, reg);
9563 switch (cr) {
9564 case 0:
9565 if (vmcs12->cr0_guest_host_mask &
9566 (val ^ vmcs12->cr0_read_shadow))
9567 return true;
9568 break;
9569 case 3:
9570 if ((vmcs12->cr3_target_count >= 1 &&
9571 vmcs12->cr3_target_value0 == val) ||
9572 (vmcs12->cr3_target_count >= 2 &&
9573 vmcs12->cr3_target_value1 == val) ||
9574 (vmcs12->cr3_target_count >= 3 &&
9575 vmcs12->cr3_target_value2 == val) ||
9576 (vmcs12->cr3_target_count >= 4 &&
9577 vmcs12->cr3_target_value3 == val))
9578 return false;
9579 if (nested_cpu_has(vmcs12, CPU_BASED_CR3_LOAD_EXITING))
9580 return true;
9581 break;
9582 case 4:
9583 if (vmcs12->cr4_guest_host_mask &
9584 (vmcs12->cr4_read_shadow ^ val))
9585 return true;
9586 break;
9587 case 8:
9588 if (nested_cpu_has(vmcs12, CPU_BASED_CR8_LOAD_EXITING))
9589 return true;
9590 break;
9592 break;
9593 case 2: /* clts */
9594 if ((vmcs12->cr0_guest_host_mask & X86_CR0_TS) &&
9595 (vmcs12->cr0_read_shadow & X86_CR0_TS))
9596 return true;
9597 break;
9598 case 1: /* mov from cr */
9599 switch (cr) {
9600 case 3:
9601 if (vmcs12->cpu_based_vm_exec_control &
9602 CPU_BASED_CR3_STORE_EXITING)
9603 return true;
9604 break;
9605 case 8:
9606 if (vmcs12->cpu_based_vm_exec_control &
9607 CPU_BASED_CR8_STORE_EXITING)
9608 return true;
9609 break;
9611 break;
9612 case 3: /* lmsw */
9614 * lmsw can change bits 1..3 of cr0, and only set bit 0 of
9615 * cr0. Other attempted changes are ignored, with no exit.
9617 val = (exit_qualification >> LMSW_SOURCE_DATA_SHIFT) & 0x0f;
9618 if (vmcs12->cr0_guest_host_mask & 0xe &
9619 (val ^ vmcs12->cr0_read_shadow))
9620 return true;
9621 if ((vmcs12->cr0_guest_host_mask & 0x1) &&
9622 !(vmcs12->cr0_read_shadow & 0x1) &&
9623 (val & 0x1))
9624 return true;
9625 break;
9627 return false;
9630 static bool nested_vmx_exit_handled_vmcs_access(struct kvm_vcpu *vcpu,
9631 struct vmcs12 *vmcs12, gpa_t bitmap)
9633 u32 vmx_instruction_info;
9634 unsigned long field;
9635 u8 b;
9637 if (!nested_cpu_has_shadow_vmcs(vmcs12))
9638 return true;
9640 /* Decode instruction info and find the field to access */
9641 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
9642 field = kvm_register_read(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
9644 /* Out-of-range fields always cause a VM exit from L2 to L1 */
9645 if (field >> 15)
9646 return true;
9648 if (kvm_vcpu_read_guest(vcpu, bitmap + field/8, &b, 1))
9649 return true;
9651 return 1 & (b >> (field & 7));
9655 * Return 1 if we should exit from L2 to L1 to handle an exit, or 0 if we
9656 * should handle it ourselves in L0 (and then continue L2). Only call this
9657 * when in is_guest_mode (L2).
9659 static bool nested_vmx_exit_reflected(struct kvm_vcpu *vcpu, u32 exit_reason)
9661 u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9662 struct vcpu_vmx *vmx = to_vmx(vcpu);
9663 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9665 if (vmx->nested.nested_run_pending)
9666 return false;
9668 if (unlikely(vmx->fail)) {
9669 pr_info_ratelimited("%s failed vm entry %x\n", __func__,
9670 vmcs_read32(VM_INSTRUCTION_ERROR));
9671 return true;
9675 * The host physical addresses of some pages of guest memory
9676 * are loaded into the vmcs02 (e.g. vmcs12's Virtual APIC
9677 * Page). The CPU may write to these pages via their host
9678 * physical address while L2 is running, bypassing any
9679 * address-translation-based dirty tracking (e.g. EPT write
9680 * protection).
9682 * Mark them dirty on every exit from L2 to prevent them from
9683 * getting out of sync with dirty tracking.
9685 nested_mark_vmcs12_pages_dirty(vcpu);
9687 trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason,
9688 vmcs_readl(EXIT_QUALIFICATION),
9689 vmx->idt_vectoring_info,
9690 intr_info,
9691 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
9692 KVM_ISA_VMX);
9694 switch (exit_reason) {
9695 case EXIT_REASON_EXCEPTION_NMI:
9696 if (is_nmi(intr_info))
9697 return false;
9698 else if (is_page_fault(intr_info))
9699 return !vmx->vcpu.arch.apf.host_apf_reason && enable_ept;
9700 else if (is_no_device(intr_info) &&
9701 !(vmcs12->guest_cr0 & X86_CR0_TS))
9702 return false;
9703 else if (is_debug(intr_info) &&
9704 vcpu->guest_debug &
9705 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))
9706 return false;
9707 else if (is_breakpoint(intr_info) &&
9708 vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
9709 return false;
9710 return vmcs12->exception_bitmap &
9711 (1u << (intr_info & INTR_INFO_VECTOR_MASK));
9712 case EXIT_REASON_EXTERNAL_INTERRUPT:
9713 return false;
9714 case EXIT_REASON_TRIPLE_FAULT:
9715 return true;
9716 case EXIT_REASON_PENDING_INTERRUPT:
9717 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING);
9718 case EXIT_REASON_NMI_WINDOW:
9719 return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING);
9720 case EXIT_REASON_TASK_SWITCH:
9721 return true;
9722 case EXIT_REASON_CPUID:
9723 return true;
9724 case EXIT_REASON_HLT:
9725 return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING);
9726 case EXIT_REASON_INVD:
9727 return true;
9728 case EXIT_REASON_INVLPG:
9729 return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9730 case EXIT_REASON_RDPMC:
9731 return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING);
9732 case EXIT_REASON_RDRAND:
9733 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDRAND_EXITING);
9734 case EXIT_REASON_RDSEED:
9735 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDSEED_EXITING);
9736 case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP:
9737 return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING);
9738 case EXIT_REASON_VMREAD:
9739 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9740 vmcs12->vmread_bitmap);
9741 case EXIT_REASON_VMWRITE:
9742 return nested_vmx_exit_handled_vmcs_access(vcpu, vmcs12,
9743 vmcs12->vmwrite_bitmap);
9744 case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR:
9745 case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD:
9746 case EXIT_REASON_VMPTRST: case EXIT_REASON_VMRESUME:
9747 case EXIT_REASON_VMOFF: case EXIT_REASON_VMON:
9748 case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID:
9750 * VMX instructions trap unconditionally. This allows L1 to
9751 * emulate them for its L2 guest, i.e., allows 3-level nesting!
9753 return true;
9754 case EXIT_REASON_CR_ACCESS:
9755 return nested_vmx_exit_handled_cr(vcpu, vmcs12);
9756 case EXIT_REASON_DR_ACCESS:
9757 return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING);
9758 case EXIT_REASON_IO_INSTRUCTION:
9759 return nested_vmx_exit_handled_io(vcpu, vmcs12);
9760 case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR:
9761 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC);
9762 case EXIT_REASON_MSR_READ:
9763 case EXIT_REASON_MSR_WRITE:
9764 return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason);
9765 case EXIT_REASON_INVALID_STATE:
9766 return true;
9767 case EXIT_REASON_MWAIT_INSTRUCTION:
9768 return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING);
9769 case EXIT_REASON_MONITOR_TRAP_FLAG:
9770 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG);
9771 case EXIT_REASON_MONITOR_INSTRUCTION:
9772 return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING);
9773 case EXIT_REASON_PAUSE_INSTRUCTION:
9774 return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) ||
9775 nested_cpu_has2(vmcs12,
9776 SECONDARY_EXEC_PAUSE_LOOP_EXITING);
9777 case EXIT_REASON_MCE_DURING_VMENTRY:
9778 return false;
9779 case EXIT_REASON_TPR_BELOW_THRESHOLD:
9780 return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW);
9781 case EXIT_REASON_APIC_ACCESS:
9782 case EXIT_REASON_APIC_WRITE:
9783 case EXIT_REASON_EOI_INDUCED:
9785 * The controls for "virtualize APIC accesses," "APIC-
9786 * register virtualization," and "virtual-interrupt
9787 * delivery" only come from vmcs12.
9789 return true;
9790 case EXIT_REASON_EPT_VIOLATION:
9792 * L0 always deals with the EPT violation. If nested EPT is
9793 * used, and the nested mmu code discovers that the address is
9794 * missing in the guest EPT table (EPT12), the EPT violation
9795 * will be injected with nested_ept_inject_page_fault()
9797 return false;
9798 case EXIT_REASON_EPT_MISCONFIG:
9800 * L2 never uses directly L1's EPT, but rather L0's own EPT
9801 * table (shadow on EPT) or a merged EPT table that L0 built
9802 * (EPT on EPT). So any problems with the structure of the
9803 * table is L0's fault.
9805 return false;
9806 case EXIT_REASON_INVPCID:
9807 return
9808 nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_INVPCID) &&
9809 nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING);
9810 case EXIT_REASON_WBINVD:
9811 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING);
9812 case EXIT_REASON_XSETBV:
9813 return true;
9814 case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS:
9816 * This should never happen, since it is not possible to
9817 * set XSS to a non-zero value---neither in L1 nor in L2.
9818 * If if it were, XSS would have to be checked against
9819 * the XSS exit bitmap in vmcs12.
9821 return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES);
9822 case EXIT_REASON_PREEMPTION_TIMER:
9823 return false;
9824 case EXIT_REASON_PML_FULL:
9825 /* We emulate PML support to L1. */
9826 return false;
9827 case EXIT_REASON_VMFUNC:
9828 /* VM functions are emulated through L2->L0 vmexits. */
9829 return false;
9830 case EXIT_REASON_ENCLS:
9831 /* SGX is never exposed to L1 */
9832 return false;
9833 default:
9834 return true;
9838 static int nested_vmx_reflect_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason)
9840 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
9843 * At this point, the exit interruption info in exit_intr_info
9844 * is only valid for EXCEPTION_NMI exits. For EXTERNAL_INTERRUPT
9845 * we need to query the in-kernel LAPIC.
9847 WARN_ON(exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT);
9848 if ((exit_intr_info &
9849 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) ==
9850 (INTR_INFO_VALID_MASK | INTR_INFO_DELIVER_CODE_MASK)) {
9851 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
9852 vmcs12->vm_exit_intr_error_code =
9853 vmcs_read32(VM_EXIT_INTR_ERROR_CODE);
9856 nested_vmx_vmexit(vcpu, exit_reason, exit_intr_info,
9857 vmcs_readl(EXIT_QUALIFICATION));
9858 return 1;
9861 static void vmx_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
9863 *info1 = vmcs_readl(EXIT_QUALIFICATION);
9864 *info2 = vmcs_read32(VM_EXIT_INTR_INFO);
9867 static void vmx_destroy_pml_buffer(struct vcpu_vmx *vmx)
9869 if (vmx->pml_pg) {
9870 __free_page(vmx->pml_pg);
9871 vmx->pml_pg = NULL;
9875 static void vmx_flush_pml_buffer(struct kvm_vcpu *vcpu)
9877 struct vcpu_vmx *vmx = to_vmx(vcpu);
9878 u64 *pml_buf;
9879 u16 pml_idx;
9881 pml_idx = vmcs_read16(GUEST_PML_INDEX);
9883 /* Do nothing if PML buffer is empty */
9884 if (pml_idx == (PML_ENTITY_NUM - 1))
9885 return;
9887 /* PML index always points to next available PML buffer entity */
9888 if (pml_idx >= PML_ENTITY_NUM)
9889 pml_idx = 0;
9890 else
9891 pml_idx++;
9893 pml_buf = page_address(vmx->pml_pg);
9894 for (; pml_idx < PML_ENTITY_NUM; pml_idx++) {
9895 u64 gpa;
9897 gpa = pml_buf[pml_idx];
9898 WARN_ON(gpa & (PAGE_SIZE - 1));
9899 kvm_vcpu_mark_page_dirty(vcpu, gpa >> PAGE_SHIFT);
9902 /* reset PML index */
9903 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
9907 * Flush all vcpus' PML buffer and update logged GPAs to dirty_bitmap.
9908 * Called before reporting dirty_bitmap to userspace.
9910 static void kvm_flush_pml_buffers(struct kvm *kvm)
9912 int i;
9913 struct kvm_vcpu *vcpu;
9915 * We only need to kick vcpu out of guest mode here, as PML buffer
9916 * is flushed at beginning of all VMEXITs, and it's obvious that only
9917 * vcpus running in guest are possible to have unflushed GPAs in PML
9918 * buffer.
9920 kvm_for_each_vcpu(i, vcpu, kvm)
9921 kvm_vcpu_kick(vcpu);
9924 static void vmx_dump_sel(char *name, uint32_t sel)
9926 pr_err("%s sel=0x%04x, attr=0x%05x, limit=0x%08x, base=0x%016lx\n",
9927 name, vmcs_read16(sel),
9928 vmcs_read32(sel + GUEST_ES_AR_BYTES - GUEST_ES_SELECTOR),
9929 vmcs_read32(sel + GUEST_ES_LIMIT - GUEST_ES_SELECTOR),
9930 vmcs_readl(sel + GUEST_ES_BASE - GUEST_ES_SELECTOR));
9933 static void vmx_dump_dtsel(char *name, uint32_t limit)
9935 pr_err("%s limit=0x%08x, base=0x%016lx\n",
9936 name, vmcs_read32(limit),
9937 vmcs_readl(limit + GUEST_GDTR_BASE - GUEST_GDTR_LIMIT));
9940 static void dump_vmcs(void)
9942 u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS);
9943 u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS);
9944 u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL);
9945 u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL);
9946 u32 secondary_exec_control = 0;
9947 unsigned long cr4 = vmcs_readl(GUEST_CR4);
9948 u64 efer = vmcs_read64(GUEST_IA32_EFER);
9949 int i, n;
9951 if (cpu_has_secondary_exec_ctrls())
9952 secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
9954 pr_err("*** Guest State ***\n");
9955 pr_err("CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9956 vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW),
9957 vmcs_readl(CR0_GUEST_HOST_MASK));
9958 pr_err("CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n",
9959 cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK));
9960 pr_err("CR3 = 0x%016lx\n", vmcs_readl(GUEST_CR3));
9961 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) &&
9962 (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA))
9964 pr_err("PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n",
9965 vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1));
9966 pr_err("PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n",
9967 vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3));
9969 pr_err("RSP = 0x%016lx RIP = 0x%016lx\n",
9970 vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP));
9971 pr_err("RFLAGS=0x%08lx DR7 = 0x%016lx\n",
9972 vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7));
9973 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
9974 vmcs_readl(GUEST_SYSENTER_ESP),
9975 vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP));
9976 vmx_dump_sel("CS: ", GUEST_CS_SELECTOR);
9977 vmx_dump_sel("DS: ", GUEST_DS_SELECTOR);
9978 vmx_dump_sel("SS: ", GUEST_SS_SELECTOR);
9979 vmx_dump_sel("ES: ", GUEST_ES_SELECTOR);
9980 vmx_dump_sel("FS: ", GUEST_FS_SELECTOR);
9981 vmx_dump_sel("GS: ", GUEST_GS_SELECTOR);
9982 vmx_dump_dtsel("GDTR:", GUEST_GDTR_LIMIT);
9983 vmx_dump_sel("LDTR:", GUEST_LDTR_SELECTOR);
9984 vmx_dump_dtsel("IDTR:", GUEST_IDTR_LIMIT);
9985 vmx_dump_sel("TR: ", GUEST_TR_SELECTOR);
9986 if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) ||
9987 (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER)))
9988 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
9989 efer, vmcs_read64(GUEST_IA32_PAT));
9990 pr_err("DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n",
9991 vmcs_read64(GUEST_IA32_DEBUGCTL),
9992 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS));
9993 if (cpu_has_load_perf_global_ctrl &&
9994 vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL)
9995 pr_err("PerfGlobCtl = 0x%016llx\n",
9996 vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL));
9997 if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS)
9998 pr_err("BndCfgS = 0x%016llx\n", vmcs_read64(GUEST_BNDCFGS));
9999 pr_err("Interruptibility = %08x ActivityState = %08x\n",
10000 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO),
10001 vmcs_read32(GUEST_ACTIVITY_STATE));
10002 if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
10003 pr_err("InterruptStatus = %04x\n",
10004 vmcs_read16(GUEST_INTR_STATUS));
10006 pr_err("*** Host State ***\n");
10007 pr_err("RIP = 0x%016lx RSP = 0x%016lx\n",
10008 vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP));
10009 pr_err("CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n",
10010 vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR),
10011 vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR),
10012 vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR),
10013 vmcs_read16(HOST_TR_SELECTOR));
10014 pr_err("FSBase=%016lx GSBase=%016lx TRBase=%016lx\n",
10015 vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE),
10016 vmcs_readl(HOST_TR_BASE));
10017 pr_err("GDTBase=%016lx IDTBase=%016lx\n",
10018 vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE));
10019 pr_err("CR0=%016lx CR3=%016lx CR4=%016lx\n",
10020 vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3),
10021 vmcs_readl(HOST_CR4));
10022 pr_err("Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n",
10023 vmcs_readl(HOST_IA32_SYSENTER_ESP),
10024 vmcs_read32(HOST_IA32_SYSENTER_CS),
10025 vmcs_readl(HOST_IA32_SYSENTER_EIP));
10026 if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER))
10027 pr_err("EFER = 0x%016llx PAT = 0x%016llx\n",
10028 vmcs_read64(HOST_IA32_EFER),
10029 vmcs_read64(HOST_IA32_PAT));
10030 if (cpu_has_load_perf_global_ctrl &&
10031 vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
10032 pr_err("PerfGlobCtl = 0x%016llx\n",
10033 vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL));
10035 pr_err("*** Control State ***\n");
10036 pr_err("PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n",
10037 pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control);
10038 pr_err("EntryControls=%08x ExitControls=%08x\n", vmentry_ctl, vmexit_ctl);
10039 pr_err("ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n",
10040 vmcs_read32(EXCEPTION_BITMAP),
10041 vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK),
10042 vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH));
10043 pr_err("VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n",
10044 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10045 vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE),
10046 vmcs_read32(VM_ENTRY_INSTRUCTION_LEN));
10047 pr_err("VMExit: intr_info=%08x errcode=%08x ilen=%08x\n",
10048 vmcs_read32(VM_EXIT_INTR_INFO),
10049 vmcs_read32(VM_EXIT_INTR_ERROR_CODE),
10050 vmcs_read32(VM_EXIT_INSTRUCTION_LEN));
10051 pr_err(" reason=%08x qualification=%016lx\n",
10052 vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION));
10053 pr_err("IDTVectoring: info=%08x errcode=%08x\n",
10054 vmcs_read32(IDT_VECTORING_INFO_FIELD),
10055 vmcs_read32(IDT_VECTORING_ERROR_CODE));
10056 pr_err("TSC Offset = 0x%016llx\n", vmcs_read64(TSC_OFFSET));
10057 if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING)
10058 pr_err("TSC Multiplier = 0x%016llx\n",
10059 vmcs_read64(TSC_MULTIPLIER));
10060 if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW)
10061 pr_err("TPR Threshold = 0x%02x\n", vmcs_read32(TPR_THRESHOLD));
10062 if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR)
10063 pr_err("PostedIntrVec = 0x%02x\n", vmcs_read16(POSTED_INTR_NV));
10064 if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT))
10065 pr_err("EPT pointer = 0x%016llx\n", vmcs_read64(EPT_POINTER));
10066 n = vmcs_read32(CR3_TARGET_COUNT);
10067 for (i = 0; i + 1 < n; i += 4)
10068 pr_err("CR3 target%u=%016lx target%u=%016lx\n",
10069 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2),
10070 i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2));
10071 if (i < n)
10072 pr_err("CR3 target%u=%016lx\n",
10073 i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2));
10074 if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING)
10075 pr_err("PLE Gap=%08x Window=%08x\n",
10076 vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW));
10077 if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID)
10078 pr_err("Virtual processor ID = 0x%04x\n",
10079 vmcs_read16(VIRTUAL_PROCESSOR_ID));
10083 * The guest has exited. See if we can fix it or if we need userspace
10084 * assistance.
10086 static int vmx_handle_exit(struct kvm_vcpu *vcpu)
10088 struct vcpu_vmx *vmx = to_vmx(vcpu);
10089 u32 exit_reason = vmx->exit_reason;
10090 u32 vectoring_info = vmx->idt_vectoring_info;
10092 trace_kvm_exit(exit_reason, vcpu, KVM_ISA_VMX);
10095 * Flush logged GPAs PML buffer, this will make dirty_bitmap more
10096 * updated. Another good is, in kvm_vm_ioctl_get_dirty_log, before
10097 * querying dirty_bitmap, we only need to kick all vcpus out of guest
10098 * mode as if vcpus is in root mode, the PML buffer must has been
10099 * flushed already.
10101 if (enable_pml)
10102 vmx_flush_pml_buffer(vcpu);
10104 /* If guest state is invalid, start emulating */
10105 if (vmx->emulation_required)
10106 return handle_invalid_guest_state(vcpu);
10108 if (is_guest_mode(vcpu) && nested_vmx_exit_reflected(vcpu, exit_reason))
10109 return nested_vmx_reflect_vmexit(vcpu, exit_reason);
10111 if (exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY) {
10112 dump_vmcs();
10113 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10114 vcpu->run->fail_entry.hardware_entry_failure_reason
10115 = exit_reason;
10116 return 0;
10119 if (unlikely(vmx->fail)) {
10120 vcpu->run->exit_reason = KVM_EXIT_FAIL_ENTRY;
10121 vcpu->run->fail_entry.hardware_entry_failure_reason
10122 = vmcs_read32(VM_INSTRUCTION_ERROR);
10123 return 0;
10127 * Note:
10128 * Do not try to fix EXIT_REASON_EPT_MISCONFIG if it caused by
10129 * delivery event since it indicates guest is accessing MMIO.
10130 * The vm-exit can be triggered again after return to guest that
10131 * will cause infinite loop.
10133 if ((vectoring_info & VECTORING_INFO_VALID_MASK) &&
10134 (exit_reason != EXIT_REASON_EXCEPTION_NMI &&
10135 exit_reason != EXIT_REASON_EPT_VIOLATION &&
10136 exit_reason != EXIT_REASON_PML_FULL &&
10137 exit_reason != EXIT_REASON_TASK_SWITCH)) {
10138 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
10139 vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_DELIVERY_EV;
10140 vcpu->run->internal.ndata = 3;
10141 vcpu->run->internal.data[0] = vectoring_info;
10142 vcpu->run->internal.data[1] = exit_reason;
10143 vcpu->run->internal.data[2] = vcpu->arch.exit_qualification;
10144 if (exit_reason == EXIT_REASON_EPT_MISCONFIG) {
10145 vcpu->run->internal.ndata++;
10146 vcpu->run->internal.data[3] =
10147 vmcs_read64(GUEST_PHYSICAL_ADDRESS);
10149 return 0;
10152 if (unlikely(!enable_vnmi &&
10153 vmx->loaded_vmcs->soft_vnmi_blocked)) {
10154 if (vmx_interrupt_allowed(vcpu)) {
10155 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10156 } else if (vmx->loaded_vmcs->vnmi_blocked_time > 1000000000LL &&
10157 vcpu->arch.nmi_pending) {
10159 * This CPU don't support us in finding the end of an
10160 * NMI-blocked window if the guest runs with IRQs
10161 * disabled. So we pull the trigger after 1 s of
10162 * futile waiting, but inform the user about this.
10164 printk(KERN_WARNING "%s: Breaking out of NMI-blocked "
10165 "state on VCPU %d after 1 s timeout\n",
10166 __func__, vcpu->vcpu_id);
10167 vmx->loaded_vmcs->soft_vnmi_blocked = 0;
10171 if (exit_reason < kvm_vmx_max_exit_handlers
10172 && kvm_vmx_exit_handlers[exit_reason])
10173 return kvm_vmx_exit_handlers[exit_reason](vcpu);
10174 else {
10175 vcpu_unimpl(vcpu, "vmx: unexpected exit reason 0x%x\n",
10176 exit_reason);
10177 kvm_queue_exception(vcpu, UD_VECTOR);
10178 return 1;
10183 * Software based L1D cache flush which is used when microcode providing
10184 * the cache control MSR is not loaded.
10186 * The L1D cache is 32 KiB on Nehalem and later microarchitectures, but to
10187 * flush it is required to read in 64 KiB because the replacement algorithm
10188 * is not exactly LRU. This could be sized at runtime via topology
10189 * information but as all relevant affected CPUs have 32KiB L1D cache size
10190 * there is no point in doing so.
10192 static void vmx_l1d_flush(struct kvm_vcpu *vcpu)
10194 int size = PAGE_SIZE << L1D_CACHE_ORDER;
10197 * This code is only executed when the the flush mode is 'cond' or
10198 * 'always'
10200 if (static_branch_likely(&vmx_l1d_flush_cond)) {
10201 bool flush_l1d;
10204 * Clear the per-vcpu flush bit, it gets set again
10205 * either from vcpu_run() or from one of the unsafe
10206 * VMEXIT handlers.
10208 flush_l1d = vcpu->arch.l1tf_flush_l1d;
10209 vcpu->arch.l1tf_flush_l1d = false;
10212 * Clear the per-cpu flush bit, it gets set again from
10213 * the interrupt handlers.
10215 flush_l1d |= kvm_get_cpu_l1tf_flush_l1d();
10216 kvm_clear_cpu_l1tf_flush_l1d();
10218 if (!flush_l1d)
10219 return;
10222 vcpu->stat.l1d_flush++;
10224 if (static_cpu_has(X86_FEATURE_FLUSH_L1D)) {
10225 wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
10226 return;
10229 asm volatile(
10230 /* First ensure the pages are in the TLB */
10231 "xorl %%eax, %%eax\n"
10232 ".Lpopulate_tlb:\n\t"
10233 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10234 "addl $4096, %%eax\n\t"
10235 "cmpl %%eax, %[size]\n\t"
10236 "jne .Lpopulate_tlb\n\t"
10237 "xorl %%eax, %%eax\n\t"
10238 "cpuid\n\t"
10239 /* Now fill the cache */
10240 "xorl %%eax, %%eax\n"
10241 ".Lfill_cache:\n"
10242 "movzbl (%[flush_pages], %%" _ASM_AX "), %%ecx\n\t"
10243 "addl $64, %%eax\n\t"
10244 "cmpl %%eax, %[size]\n\t"
10245 "jne .Lfill_cache\n\t"
10246 "lfence\n"
10247 :: [flush_pages] "r" (vmx_l1d_flush_pages),
10248 [size] "r" (size)
10249 : "eax", "ebx", "ecx", "edx");
10252 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
10254 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
10256 if (is_guest_mode(vcpu) &&
10257 nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
10258 return;
10260 if (irr == -1 || tpr < irr) {
10261 vmcs_write32(TPR_THRESHOLD, 0);
10262 return;
10265 vmcs_write32(TPR_THRESHOLD, irr);
10268 static void vmx_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
10270 u32 sec_exec_control;
10272 if (!lapic_in_kernel(vcpu))
10273 return;
10275 if (!flexpriority_enabled &&
10276 !cpu_has_vmx_virtualize_x2apic_mode())
10277 return;
10279 /* Postpone execution until vmcs01 is the current VMCS. */
10280 if (is_guest_mode(vcpu)) {
10281 to_vmx(vcpu)->nested.change_vmcs01_virtual_apic_mode = true;
10282 return;
10285 sec_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
10286 sec_exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
10287 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE);
10289 switch (kvm_get_apic_mode(vcpu)) {
10290 case LAPIC_MODE_INVALID:
10291 WARN_ONCE(true, "Invalid local APIC state");
10292 case LAPIC_MODE_DISABLED:
10293 break;
10294 case LAPIC_MODE_XAPIC:
10295 if (flexpriority_enabled) {
10296 sec_exec_control |=
10297 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES;
10298 vmx_flush_tlb(vcpu, true);
10300 break;
10301 case LAPIC_MODE_X2APIC:
10302 if (cpu_has_vmx_virtualize_x2apic_mode())
10303 sec_exec_control |=
10304 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE;
10305 break;
10307 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, sec_exec_control);
10309 vmx_update_msr_bitmap(vcpu);
10312 static void vmx_set_apic_access_page_addr(struct kvm_vcpu *vcpu, hpa_t hpa)
10314 if (!is_guest_mode(vcpu)) {
10315 vmcs_write64(APIC_ACCESS_ADDR, hpa);
10316 vmx_flush_tlb(vcpu, true);
10320 static void vmx_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
10322 u16 status;
10323 u8 old;
10325 if (max_isr == -1)
10326 max_isr = 0;
10328 status = vmcs_read16(GUEST_INTR_STATUS);
10329 old = status >> 8;
10330 if (max_isr != old) {
10331 status &= 0xff;
10332 status |= max_isr << 8;
10333 vmcs_write16(GUEST_INTR_STATUS, status);
10337 static void vmx_set_rvi(int vector)
10339 u16 status;
10340 u8 old;
10342 if (vector == -1)
10343 vector = 0;
10345 status = vmcs_read16(GUEST_INTR_STATUS);
10346 old = (u8)status & 0xff;
10347 if ((u8)vector != old) {
10348 status &= ~0xff;
10349 status |= (u8)vector;
10350 vmcs_write16(GUEST_INTR_STATUS, status);
10354 static void vmx_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
10357 * When running L2, updating RVI is only relevant when
10358 * vmcs12 virtual-interrupt-delivery enabled.
10359 * However, it can be enabled only when L1 also
10360 * intercepts external-interrupts and in that case
10361 * we should not update vmcs02 RVI but instead intercept
10362 * interrupt. Therefore, do nothing when running L2.
10364 if (!is_guest_mode(vcpu))
10365 vmx_set_rvi(max_irr);
10368 static int vmx_sync_pir_to_irr(struct kvm_vcpu *vcpu)
10370 struct vcpu_vmx *vmx = to_vmx(vcpu);
10371 int max_irr;
10372 bool max_irr_updated;
10374 WARN_ON(!vcpu->arch.apicv_active);
10375 if (pi_test_on(&vmx->pi_desc)) {
10376 pi_clear_on(&vmx->pi_desc);
10378 * IOMMU can write to PIR.ON, so the barrier matters even on UP.
10379 * But on x86 this is just a compiler barrier anyway.
10381 smp_mb__after_atomic();
10382 max_irr_updated =
10383 kvm_apic_update_irr(vcpu, vmx->pi_desc.pir, &max_irr);
10386 * If we are running L2 and L1 has a new pending interrupt
10387 * which can be injected, we should re-evaluate
10388 * what should be done with this new L1 interrupt.
10389 * If L1 intercepts external-interrupts, we should
10390 * exit from L2 to L1. Otherwise, interrupt should be
10391 * delivered directly to L2.
10393 if (is_guest_mode(vcpu) && max_irr_updated) {
10394 if (nested_exit_on_intr(vcpu))
10395 kvm_vcpu_exiting_guest_mode(vcpu);
10396 else
10397 kvm_make_request(KVM_REQ_EVENT, vcpu);
10399 } else {
10400 max_irr = kvm_lapic_find_highest_irr(vcpu);
10402 vmx_hwapic_irr_update(vcpu, max_irr);
10403 return max_irr;
10406 static u8 vmx_has_apicv_interrupt(struct kvm_vcpu *vcpu)
10408 u8 rvi = vmx_get_rvi();
10409 u8 vppr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_PROCPRI);
10411 return ((rvi & 0xf0) > (vppr & 0xf0));
10414 static bool vmx_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
10416 return pi_test_on(vcpu_to_pi_desc(vcpu));
10419 static void vmx_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
10421 if (!kvm_vcpu_apicv_active(vcpu))
10422 return;
10424 vmcs_write64(EOI_EXIT_BITMAP0, eoi_exit_bitmap[0]);
10425 vmcs_write64(EOI_EXIT_BITMAP1, eoi_exit_bitmap[1]);
10426 vmcs_write64(EOI_EXIT_BITMAP2, eoi_exit_bitmap[2]);
10427 vmcs_write64(EOI_EXIT_BITMAP3, eoi_exit_bitmap[3]);
10430 static void vmx_apicv_post_state_restore(struct kvm_vcpu *vcpu)
10432 struct vcpu_vmx *vmx = to_vmx(vcpu);
10434 pi_clear_on(&vmx->pi_desc);
10435 memset(vmx->pi_desc.pir, 0, sizeof(vmx->pi_desc.pir));
10438 static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)
10440 u32 exit_intr_info = 0;
10441 u16 basic_exit_reason = (u16)vmx->exit_reason;
10443 if (!(basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY
10444 || basic_exit_reason == EXIT_REASON_EXCEPTION_NMI))
10445 return;
10447 if (!(vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10448 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10449 vmx->exit_intr_info = exit_intr_info;
10451 /* if exit due to PF check for async PF */
10452 if (is_page_fault(exit_intr_info))
10453 vmx->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
10455 /* Handle machine checks before interrupts are enabled */
10456 if (basic_exit_reason == EXIT_REASON_MCE_DURING_VMENTRY ||
10457 is_machine_check(exit_intr_info))
10458 kvm_machine_check();
10460 /* We need to handle NMIs before interrupts are enabled */
10461 if (is_nmi(exit_intr_info)) {
10462 kvm_before_interrupt(&vmx->vcpu);
10463 asm("int $2");
10464 kvm_after_interrupt(&vmx->vcpu);
10468 static void vmx_handle_external_intr(struct kvm_vcpu *vcpu)
10470 u32 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10472 if ((exit_intr_info & (INTR_INFO_VALID_MASK | INTR_INFO_INTR_TYPE_MASK))
10473 == (INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR)) {
10474 unsigned int vector;
10475 unsigned long entry;
10476 gate_desc *desc;
10477 struct vcpu_vmx *vmx = to_vmx(vcpu);
10478 #ifdef CONFIG_X86_64
10479 unsigned long tmp;
10480 #endif
10482 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10483 desc = (gate_desc *)vmx->host_idt_base + vector;
10484 entry = gate_offset(desc);
10485 asm volatile(
10486 #ifdef CONFIG_X86_64
10487 "mov %%" _ASM_SP ", %[sp]\n\t"
10488 "and $0xfffffffffffffff0, %%" _ASM_SP "\n\t"
10489 "push $%c[ss]\n\t"
10490 "push %[sp]\n\t"
10491 #endif
10492 "pushf\n\t"
10493 __ASM_SIZE(push) " $%c[cs]\n\t"
10494 CALL_NOSPEC
10496 #ifdef CONFIG_X86_64
10497 [sp]"=&r"(tmp),
10498 #endif
10499 ASM_CALL_CONSTRAINT
10501 THUNK_TARGET(entry),
10502 [ss]"i"(__KERNEL_DS),
10503 [cs]"i"(__KERNEL_CS)
10507 STACK_FRAME_NON_STANDARD(vmx_handle_external_intr);
10509 static bool vmx_has_emulated_msr(int index)
10511 switch (index) {
10512 case MSR_IA32_SMBASE:
10514 * We cannot do SMM unless we can run the guest in big
10515 * real mode.
10517 return enable_unrestricted_guest || emulate_invalid_guest_state;
10518 case MSR_AMD64_VIRT_SPEC_CTRL:
10519 /* This is AMD only. */
10520 return false;
10521 default:
10522 return true;
10526 static bool vmx_mpx_supported(void)
10528 return (vmcs_config.vmexit_ctrl & VM_EXIT_CLEAR_BNDCFGS) &&
10529 (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_BNDCFGS);
10532 static bool vmx_xsaves_supported(void)
10534 return vmcs_config.cpu_based_2nd_exec_ctrl &
10535 SECONDARY_EXEC_XSAVES;
10538 static void vmx_recover_nmi_blocking(struct vcpu_vmx *vmx)
10540 u32 exit_intr_info;
10541 bool unblock_nmi;
10542 u8 vector;
10543 bool idtv_info_valid;
10545 idtv_info_valid = vmx->idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10547 if (enable_vnmi) {
10548 if (vmx->loaded_vmcs->nmi_known_unmasked)
10549 return;
10551 * Can't use vmx->exit_intr_info since we're not sure what
10552 * the exit reason is.
10554 exit_intr_info = vmcs_read32(VM_EXIT_INTR_INFO);
10555 unblock_nmi = (exit_intr_info & INTR_INFO_UNBLOCK_NMI) != 0;
10556 vector = exit_intr_info & INTR_INFO_VECTOR_MASK;
10558 * SDM 3: 27.7.1.2 (September 2008)
10559 * Re-set bit "block by NMI" before VM entry if vmexit caused by
10560 * a guest IRET fault.
10561 * SDM 3: 23.2.2 (September 2008)
10562 * Bit 12 is undefined in any of the following cases:
10563 * If the VM exit sets the valid bit in the IDT-vectoring
10564 * information field.
10565 * If the VM exit is due to a double fault.
10567 if ((exit_intr_info & INTR_INFO_VALID_MASK) && unblock_nmi &&
10568 vector != DF_VECTOR && !idtv_info_valid)
10569 vmcs_set_bits(GUEST_INTERRUPTIBILITY_INFO,
10570 GUEST_INTR_STATE_NMI);
10571 else
10572 vmx->loaded_vmcs->nmi_known_unmasked =
10573 !(vmcs_read32(GUEST_INTERRUPTIBILITY_INFO)
10574 & GUEST_INTR_STATE_NMI);
10575 } else if (unlikely(vmx->loaded_vmcs->soft_vnmi_blocked))
10576 vmx->loaded_vmcs->vnmi_blocked_time +=
10577 ktime_to_ns(ktime_sub(ktime_get(),
10578 vmx->loaded_vmcs->entry_time));
10581 static void __vmx_complete_interrupts(struct kvm_vcpu *vcpu,
10582 u32 idt_vectoring_info,
10583 int instr_len_field,
10584 int error_code_field)
10586 u8 vector;
10587 int type;
10588 bool idtv_info_valid;
10590 idtv_info_valid = idt_vectoring_info & VECTORING_INFO_VALID_MASK;
10592 vcpu->arch.nmi_injected = false;
10593 kvm_clear_exception_queue(vcpu);
10594 kvm_clear_interrupt_queue(vcpu);
10596 if (!idtv_info_valid)
10597 return;
10599 kvm_make_request(KVM_REQ_EVENT, vcpu);
10601 vector = idt_vectoring_info & VECTORING_INFO_VECTOR_MASK;
10602 type = idt_vectoring_info & VECTORING_INFO_TYPE_MASK;
10604 switch (type) {
10605 case INTR_TYPE_NMI_INTR:
10606 vcpu->arch.nmi_injected = true;
10608 * SDM 3: 27.7.1.2 (September 2008)
10609 * Clear bit "block by NMI" before VM entry if a NMI
10610 * delivery faulted.
10612 vmx_set_nmi_mask(vcpu, false);
10613 break;
10614 case INTR_TYPE_SOFT_EXCEPTION:
10615 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10616 /* fall through */
10617 case INTR_TYPE_HARD_EXCEPTION:
10618 if (idt_vectoring_info & VECTORING_INFO_DELIVER_CODE_MASK) {
10619 u32 err = vmcs_read32(error_code_field);
10620 kvm_requeue_exception_e(vcpu, vector, err);
10621 } else
10622 kvm_requeue_exception(vcpu, vector);
10623 break;
10624 case INTR_TYPE_SOFT_INTR:
10625 vcpu->arch.event_exit_inst_len = vmcs_read32(instr_len_field);
10626 /* fall through */
10627 case INTR_TYPE_EXT_INTR:
10628 kvm_queue_interrupt(vcpu, vector, type == INTR_TYPE_SOFT_INTR);
10629 break;
10630 default:
10631 break;
10635 static void vmx_complete_interrupts(struct vcpu_vmx *vmx)
10637 __vmx_complete_interrupts(&vmx->vcpu, vmx->idt_vectoring_info,
10638 VM_EXIT_INSTRUCTION_LEN,
10639 IDT_VECTORING_ERROR_CODE);
10642 static void vmx_cancel_injection(struct kvm_vcpu *vcpu)
10644 __vmx_complete_interrupts(vcpu,
10645 vmcs_read32(VM_ENTRY_INTR_INFO_FIELD),
10646 VM_ENTRY_INSTRUCTION_LEN,
10647 VM_ENTRY_EXCEPTION_ERROR_CODE);
10649 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
10652 static void atomic_switch_perf_msrs(struct vcpu_vmx *vmx)
10654 int i, nr_msrs;
10655 struct perf_guest_switch_msr *msrs;
10657 msrs = perf_guest_get_msrs(&nr_msrs);
10659 if (!msrs)
10660 return;
10662 for (i = 0; i < nr_msrs; i++)
10663 if (msrs[i].host == msrs[i].guest)
10664 clear_atomic_switch_msr(vmx, msrs[i].msr);
10665 else
10666 add_atomic_switch_msr(vmx, msrs[i].msr, msrs[i].guest,
10667 msrs[i].host, false);
10670 static void vmx_arm_hv_timer(struct vcpu_vmx *vmx, u32 val)
10672 vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, val);
10673 if (!vmx->loaded_vmcs->hv_timer_armed)
10674 vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL,
10675 PIN_BASED_VMX_PREEMPTION_TIMER);
10676 vmx->loaded_vmcs->hv_timer_armed = true;
10679 static void vmx_update_hv_timer(struct kvm_vcpu *vcpu)
10681 struct vcpu_vmx *vmx = to_vmx(vcpu);
10682 u64 tscl;
10683 u32 delta_tsc;
10685 if (vmx->req_immediate_exit) {
10686 vmx_arm_hv_timer(vmx, 0);
10687 return;
10690 if (vmx->hv_deadline_tsc != -1) {
10691 tscl = rdtsc();
10692 if (vmx->hv_deadline_tsc > tscl)
10693 /* set_hv_timer ensures the delta fits in 32-bits */
10694 delta_tsc = (u32)((vmx->hv_deadline_tsc - tscl) >>
10695 cpu_preemption_timer_multi);
10696 else
10697 delta_tsc = 0;
10699 vmx_arm_hv_timer(vmx, delta_tsc);
10700 return;
10703 if (vmx->loaded_vmcs->hv_timer_armed)
10704 vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL,
10705 PIN_BASED_VMX_PREEMPTION_TIMER);
10706 vmx->loaded_vmcs->hv_timer_armed = false;
10709 static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu)
10711 struct vcpu_vmx *vmx = to_vmx(vcpu);
10712 unsigned long cr3, cr4, evmcs_rsp;
10714 /* Record the guest's net vcpu time for enforced NMI injections. */
10715 if (unlikely(!enable_vnmi &&
10716 vmx->loaded_vmcs->soft_vnmi_blocked))
10717 vmx->loaded_vmcs->entry_time = ktime_get();
10719 /* Don't enter VMX if guest state is invalid, let the exit handler
10720 start emulation until we arrive back to a valid state */
10721 if (vmx->emulation_required)
10722 return;
10724 if (vmx->ple_window_dirty) {
10725 vmx->ple_window_dirty = false;
10726 vmcs_write32(PLE_WINDOW, vmx->ple_window);
10729 if (vmx->nested.sync_shadow_vmcs) {
10730 copy_vmcs12_to_shadow(vmx);
10731 vmx->nested.sync_shadow_vmcs = false;
10734 if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty))
10735 vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]);
10736 if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty))
10737 vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]);
10739 cr3 = __get_current_cr3_fast();
10740 if (unlikely(cr3 != vmx->loaded_vmcs->host_state.cr3)) {
10741 vmcs_writel(HOST_CR3, cr3);
10742 vmx->loaded_vmcs->host_state.cr3 = cr3;
10745 cr4 = cr4_read_shadow();
10746 if (unlikely(cr4 != vmx->loaded_vmcs->host_state.cr4)) {
10747 vmcs_writel(HOST_CR4, cr4);
10748 vmx->loaded_vmcs->host_state.cr4 = cr4;
10751 /* When single-stepping over STI and MOV SS, we must clear the
10752 * corresponding interruptibility bits in the guest state. Otherwise
10753 * vmentry fails as it then expects bit 14 (BS) in pending debug
10754 * exceptions being set, but that's not correct for the guest debugging
10755 * case. */
10756 if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
10757 vmx_set_interrupt_shadow(vcpu, 0);
10759 if (static_cpu_has(X86_FEATURE_PKU) &&
10760 kvm_read_cr4_bits(vcpu, X86_CR4_PKE) &&
10761 vcpu->arch.pkru != vmx->host_pkru)
10762 __write_pkru(vcpu->arch.pkru);
10764 atomic_switch_perf_msrs(vmx);
10766 vmx_update_hv_timer(vcpu);
10769 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
10770 * it's non-zero. Since vmentry is serialising on affected CPUs, there
10771 * is no need to worry about the conditional branch over the wrmsr
10772 * being speculatively taken.
10774 x86_spec_ctrl_set_guest(vmx->spec_ctrl, 0);
10776 vmx->__launched = vmx->loaded_vmcs->launched;
10778 evmcs_rsp = static_branch_unlikely(&enable_evmcs) ?
10779 (unsigned long)&current_evmcs->host_rsp : 0;
10781 /* L1D Flush includes CPU buffer clear to mitigate MDS */
10782 if (static_branch_unlikely(&vmx_l1d_should_flush))
10783 vmx_l1d_flush(vcpu);
10784 else if (static_branch_unlikely(&mds_user_clear))
10785 mds_clear_cpu_buffers();
10787 asm(
10788 /* Store host registers */
10789 "push %%" _ASM_DX "; push %%" _ASM_BP ";"
10790 "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */
10791 "push %%" _ASM_CX " \n\t"
10792 "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10793 "je 1f \n\t"
10794 "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t"
10795 /* Avoid VMWRITE when Enlightened VMCS is in use */
10796 "test %%" _ASM_SI ", %%" _ASM_SI " \n\t"
10797 "jz 2f \n\t"
10798 "mov %%" _ASM_SP ", (%%" _ASM_SI ") \n\t"
10799 "jmp 1f \n\t"
10800 "2: \n\t"
10801 __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t"
10802 "1: \n\t"
10803 /* Reload cr2 if changed */
10804 "mov %c[cr2](%0), %%" _ASM_AX " \n\t"
10805 "mov %%cr2, %%" _ASM_DX " \n\t"
10806 "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t"
10807 "je 3f \n\t"
10808 "mov %%" _ASM_AX", %%cr2 \n\t"
10809 "3: \n\t"
10810 /* Check if vmlaunch of vmresume is needed */
10811 "cmpl $0, %c[launched](%0) \n\t"
10812 /* Load guest registers. Don't clobber flags. */
10813 "mov %c[rax](%0), %%" _ASM_AX " \n\t"
10814 "mov %c[rbx](%0), %%" _ASM_BX " \n\t"
10815 "mov %c[rdx](%0), %%" _ASM_DX " \n\t"
10816 "mov %c[rsi](%0), %%" _ASM_SI " \n\t"
10817 "mov %c[rdi](%0), %%" _ASM_DI " \n\t"
10818 "mov %c[rbp](%0), %%" _ASM_BP " \n\t"
10819 #ifdef CONFIG_X86_64
10820 "mov %c[r8](%0), %%r8 \n\t"
10821 "mov %c[r9](%0), %%r9 \n\t"
10822 "mov %c[r10](%0), %%r10 \n\t"
10823 "mov %c[r11](%0), %%r11 \n\t"
10824 "mov %c[r12](%0), %%r12 \n\t"
10825 "mov %c[r13](%0), %%r13 \n\t"
10826 "mov %c[r14](%0), %%r14 \n\t"
10827 "mov %c[r15](%0), %%r15 \n\t"
10828 #endif
10829 "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */
10831 /* Enter guest mode */
10832 "jne 1f \n\t"
10833 __ex(ASM_VMX_VMLAUNCH) "\n\t"
10834 "jmp 2f \n\t"
10835 "1: " __ex(ASM_VMX_VMRESUME) "\n\t"
10836 "2: "
10837 /* Save guest registers, load host registers, keep flags */
10838 "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t"
10839 "pop %0 \n\t"
10840 "setbe %c[fail](%0)\n\t"
10841 "mov %%" _ASM_AX ", %c[rax](%0) \n\t"
10842 "mov %%" _ASM_BX ", %c[rbx](%0) \n\t"
10843 __ASM_SIZE(pop) " %c[rcx](%0) \n\t"
10844 "mov %%" _ASM_DX ", %c[rdx](%0) \n\t"
10845 "mov %%" _ASM_SI ", %c[rsi](%0) \n\t"
10846 "mov %%" _ASM_DI ", %c[rdi](%0) \n\t"
10847 "mov %%" _ASM_BP ", %c[rbp](%0) \n\t"
10848 #ifdef CONFIG_X86_64
10849 "mov %%r8, %c[r8](%0) \n\t"
10850 "mov %%r9, %c[r9](%0) \n\t"
10851 "mov %%r10, %c[r10](%0) \n\t"
10852 "mov %%r11, %c[r11](%0) \n\t"
10853 "mov %%r12, %c[r12](%0) \n\t"
10854 "mov %%r13, %c[r13](%0) \n\t"
10855 "mov %%r14, %c[r14](%0) \n\t"
10856 "mov %%r15, %c[r15](%0) \n\t"
10857 "xor %%r8d, %%r8d \n\t"
10858 "xor %%r9d, %%r9d \n\t"
10859 "xor %%r10d, %%r10d \n\t"
10860 "xor %%r11d, %%r11d \n\t"
10861 "xor %%r12d, %%r12d \n\t"
10862 "xor %%r13d, %%r13d \n\t"
10863 "xor %%r14d, %%r14d \n\t"
10864 "xor %%r15d, %%r15d \n\t"
10865 #endif
10866 "mov %%cr2, %%" _ASM_AX " \n\t"
10867 "mov %%" _ASM_AX ", %c[cr2](%0) \n\t"
10869 "xor %%eax, %%eax \n\t"
10870 "xor %%ebx, %%ebx \n\t"
10871 "xor %%esi, %%esi \n\t"
10872 "xor %%edi, %%edi \n\t"
10873 "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t"
10874 ".pushsection .rodata \n\t"
10875 ".global vmx_return \n\t"
10876 "vmx_return: " _ASM_PTR " 2b \n\t"
10877 ".popsection"
10878 : : "c"(vmx), "d"((unsigned long)HOST_RSP), "S"(evmcs_rsp),
10879 [launched]"i"(offsetof(struct vcpu_vmx, __launched)),
10880 [fail]"i"(offsetof(struct vcpu_vmx, fail)),
10881 [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)),
10882 [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])),
10883 [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])),
10884 [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])),
10885 [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])),
10886 [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])),
10887 [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])),
10888 [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])),
10889 #ifdef CONFIG_X86_64
10890 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])),
10891 [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])),
10892 [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])),
10893 [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])),
10894 [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])),
10895 [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])),
10896 [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])),
10897 [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])),
10898 #endif
10899 [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)),
10900 [wordsize]"i"(sizeof(ulong))
10901 : "cc", "memory"
10902 #ifdef CONFIG_X86_64
10903 , "rax", "rbx", "rdi"
10904 , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"
10905 #else
10906 , "eax", "ebx", "edi"
10907 #endif
10911 * We do not use IBRS in the kernel. If this vCPU has used the
10912 * SPEC_CTRL MSR it may have left it on; save the value and
10913 * turn it off. This is much more efficient than blindly adding
10914 * it to the atomic save/restore list. Especially as the former
10915 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
10917 * For non-nested case:
10918 * If the L01 MSR bitmap does not intercept the MSR, then we need to
10919 * save it.
10921 * For nested case:
10922 * If the L02 MSR bitmap does not intercept the MSR, then we need to
10923 * save it.
10925 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
10926 vmx->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
10928 x86_spec_ctrl_restore_host(vmx->spec_ctrl, 0);
10930 /* Eliminate branch target predictions from guest mode */
10931 vmexit_fill_RSB();
10933 /* All fields are clean at this point */
10934 if (static_branch_unlikely(&enable_evmcs))
10935 current_evmcs->hv_clean_fields |=
10936 HV_VMX_ENLIGHTENED_CLEAN_FIELD_ALL;
10938 /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */
10939 if (vmx->host_debugctlmsr)
10940 update_debugctlmsr(vmx->host_debugctlmsr);
10942 #ifndef CONFIG_X86_64
10944 * The sysexit path does not restore ds/es, so we must set them to
10945 * a reasonable value ourselves.
10947 * We can't defer this to vmx_prepare_switch_to_host() since that
10948 * function may be executed in interrupt context, which saves and
10949 * restore segments around it, nullifying its effect.
10951 loadsegment(ds, __USER_DS);
10952 loadsegment(es, __USER_DS);
10953 #endif
10955 vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP)
10956 | (1 << VCPU_EXREG_RFLAGS)
10957 | (1 << VCPU_EXREG_PDPTR)
10958 | (1 << VCPU_EXREG_SEGMENTS)
10959 | (1 << VCPU_EXREG_CR3));
10960 vcpu->arch.regs_dirty = 0;
10963 * eager fpu is enabled if PKEY is supported and CR4 is switched
10964 * back on host, so it is safe to read guest PKRU from current
10965 * XSAVE.
10967 if (static_cpu_has(X86_FEATURE_PKU) &&
10968 kvm_read_cr4_bits(vcpu, X86_CR4_PKE)) {
10969 vcpu->arch.pkru = __read_pkru();
10970 if (vcpu->arch.pkru != vmx->host_pkru)
10971 __write_pkru(vmx->host_pkru);
10974 vmx->nested.nested_run_pending = 0;
10975 vmx->idt_vectoring_info = 0;
10977 vmx->exit_reason = vmx->fail ? 0xdead : vmcs_read32(VM_EXIT_REASON);
10978 if (vmx->fail || (vmx->exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY))
10979 return;
10981 vmx->loaded_vmcs->launched = 1;
10982 vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD);
10984 vmx_complete_atomic_exit(vmx);
10985 vmx_recover_nmi_blocking(vmx);
10986 vmx_complete_interrupts(vmx);
10988 STACK_FRAME_NON_STANDARD(vmx_vcpu_run);
10990 static struct kvm *vmx_vm_alloc(void)
10992 struct kvm_vmx *kvm_vmx = vzalloc(sizeof(struct kvm_vmx));
10993 return &kvm_vmx->kvm;
10996 static void vmx_vm_free(struct kvm *kvm)
10998 vfree(to_kvm_vmx(kvm));
11001 static void vmx_switch_vmcs(struct kvm_vcpu *vcpu, struct loaded_vmcs *vmcs)
11003 struct vcpu_vmx *vmx = to_vmx(vcpu);
11004 int cpu;
11006 if (vmx->loaded_vmcs == vmcs)
11007 return;
11009 cpu = get_cpu();
11010 vmx_vcpu_put(vcpu);
11011 vmx->loaded_vmcs = vmcs;
11012 vmx_vcpu_load(vcpu, cpu);
11013 put_cpu();
11017 * Ensure that the current vmcs of the logical processor is the
11018 * vmcs01 of the vcpu before calling free_nested().
11020 static void vmx_free_vcpu_nested(struct kvm_vcpu *vcpu)
11022 struct vcpu_vmx *vmx = to_vmx(vcpu);
11024 vcpu_load(vcpu);
11025 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
11026 free_nested(vmx);
11027 vcpu_put(vcpu);
11030 static void vmx_free_vcpu(struct kvm_vcpu *vcpu)
11032 struct vcpu_vmx *vmx = to_vmx(vcpu);
11034 if (enable_pml)
11035 vmx_destroy_pml_buffer(vmx);
11036 free_vpid(vmx->vpid);
11037 leave_guest_mode(vcpu);
11038 vmx_free_vcpu_nested(vcpu);
11039 free_loaded_vmcs(vmx->loaded_vmcs);
11040 kfree(vmx->guest_msrs);
11041 kvm_vcpu_uninit(vcpu);
11042 kmem_cache_free(kvm_vcpu_cache, vmx);
11045 static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id)
11047 int err;
11048 struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
11049 unsigned long *msr_bitmap;
11050 int cpu;
11052 if (!vmx)
11053 return ERR_PTR(-ENOMEM);
11055 vmx->vpid = allocate_vpid();
11057 err = kvm_vcpu_init(&vmx->vcpu, kvm, id);
11058 if (err)
11059 goto free_vcpu;
11061 err = -ENOMEM;
11064 * If PML is turned on, failure on enabling PML just results in failure
11065 * of creating the vcpu, therefore we can simplify PML logic (by
11066 * avoiding dealing with cases, such as enabling PML partially on vcpus
11067 * for the guest, etc.
11069 if (enable_pml) {
11070 vmx->pml_pg = alloc_page(GFP_KERNEL | __GFP_ZERO);
11071 if (!vmx->pml_pg)
11072 goto uninit_vcpu;
11075 vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL);
11076 BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0])
11077 > PAGE_SIZE);
11079 if (!vmx->guest_msrs)
11080 goto free_pml;
11082 err = alloc_loaded_vmcs(&vmx->vmcs01);
11083 if (err < 0)
11084 goto free_msrs;
11086 msr_bitmap = vmx->vmcs01.msr_bitmap;
11087 vmx_disable_intercept_for_msr(msr_bitmap, MSR_FS_BASE, MSR_TYPE_RW);
11088 vmx_disable_intercept_for_msr(msr_bitmap, MSR_GS_BASE, MSR_TYPE_RW);
11089 vmx_disable_intercept_for_msr(msr_bitmap, MSR_KERNEL_GS_BASE, MSR_TYPE_RW);
11090 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_CS, MSR_TYPE_RW);
11091 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_ESP, MSR_TYPE_RW);
11092 vmx_disable_intercept_for_msr(msr_bitmap, MSR_IA32_SYSENTER_EIP, MSR_TYPE_RW);
11093 vmx->msr_bitmap_mode = 0;
11095 vmx->loaded_vmcs = &vmx->vmcs01;
11096 cpu = get_cpu();
11097 vmx_vcpu_load(&vmx->vcpu, cpu);
11098 vmx->vcpu.cpu = cpu;
11099 vmx_vcpu_setup(vmx);
11100 vmx_vcpu_put(&vmx->vcpu);
11101 put_cpu();
11102 if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) {
11103 err = alloc_apic_access_page(kvm);
11104 if (err)
11105 goto free_vmcs;
11108 if (enable_ept && !enable_unrestricted_guest) {
11109 err = init_rmode_identity_map(kvm);
11110 if (err)
11111 goto free_vmcs;
11114 if (nested)
11115 nested_vmx_setup_ctls_msrs(&vmx->nested.msrs,
11116 kvm_vcpu_apicv_active(&vmx->vcpu));
11118 vmx->nested.posted_intr_nv = -1;
11119 vmx->nested.current_vmptr = -1ull;
11121 vmx->msr_ia32_feature_control_valid_bits = FEATURE_CONTROL_LOCKED;
11124 * Enforce invariant: pi_desc.nv is always either POSTED_INTR_VECTOR
11125 * or POSTED_INTR_WAKEUP_VECTOR.
11127 vmx->pi_desc.nv = POSTED_INTR_VECTOR;
11128 vmx->pi_desc.sn = 1;
11130 return &vmx->vcpu;
11132 free_vmcs:
11133 free_loaded_vmcs(vmx->loaded_vmcs);
11134 free_msrs:
11135 kfree(vmx->guest_msrs);
11136 free_pml:
11137 vmx_destroy_pml_buffer(vmx);
11138 uninit_vcpu:
11139 kvm_vcpu_uninit(&vmx->vcpu);
11140 free_vcpu:
11141 free_vpid(vmx->vpid);
11142 kmem_cache_free(kvm_vcpu_cache, vmx);
11143 return ERR_PTR(err);
11146 #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"
11147 #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"
11149 static int vmx_vm_init(struct kvm *kvm)
11151 spin_lock_init(&to_kvm_vmx(kvm)->ept_pointer_lock);
11153 if (!ple_gap)
11154 kvm->arch.pause_in_guest = true;
11156 if (boot_cpu_has(X86_BUG_L1TF) && enable_ept) {
11157 switch (l1tf_mitigation) {
11158 case L1TF_MITIGATION_OFF:
11159 case L1TF_MITIGATION_FLUSH_NOWARN:
11160 /* 'I explicitly don't care' is set */
11161 break;
11162 case L1TF_MITIGATION_FLUSH:
11163 case L1TF_MITIGATION_FLUSH_NOSMT:
11164 case L1TF_MITIGATION_FULL:
11166 * Warn upon starting the first VM in a potentially
11167 * insecure environment.
11169 if (sched_smt_active())
11170 pr_warn_once(L1TF_MSG_SMT);
11171 if (l1tf_vmx_mitigation == VMENTER_L1D_FLUSH_NEVER)
11172 pr_warn_once(L1TF_MSG_L1D);
11173 break;
11174 case L1TF_MITIGATION_FULL_FORCE:
11175 /* Flush is enforced */
11176 break;
11179 return 0;
11182 static void __init vmx_check_processor_compat(void *rtn)
11184 struct vmcs_config vmcs_conf;
11186 *(int *)rtn = 0;
11187 if (setup_vmcs_config(&vmcs_conf) < 0)
11188 *(int *)rtn = -EIO;
11189 nested_vmx_setup_ctls_msrs(&vmcs_conf.nested, enable_apicv);
11190 if (memcmp(&vmcs_config, &vmcs_conf, sizeof(struct vmcs_config)) != 0) {
11191 printk(KERN_ERR "kvm: CPU %d feature inconsistency!\n",
11192 smp_processor_id());
11193 *(int *)rtn = -EIO;
11197 static u64 vmx_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
11199 u8 cache;
11200 u64 ipat = 0;
11202 /* For VT-d and EPT combination
11203 * 1. MMIO: always map as UC
11204 * 2. EPT with VT-d:
11205 * a. VT-d without snooping control feature: can't guarantee the
11206 * result, try to trust guest.
11207 * b. VT-d with snooping control feature: snooping control feature of
11208 * VT-d engine can guarantee the cache correctness. Just set it
11209 * to WB to keep consistent with host. So the same as item 3.
11210 * 3. EPT without VT-d: always map as WB and set IPAT=1 to keep
11211 * consistent with host MTRR
11213 if (is_mmio) {
11214 cache = MTRR_TYPE_UNCACHABLE;
11215 goto exit;
11218 if (!kvm_arch_has_noncoherent_dma(vcpu->kvm)) {
11219 ipat = VMX_EPT_IPAT_BIT;
11220 cache = MTRR_TYPE_WRBACK;
11221 goto exit;
11224 if (kvm_read_cr0(vcpu) & X86_CR0_CD) {
11225 ipat = VMX_EPT_IPAT_BIT;
11226 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
11227 cache = MTRR_TYPE_WRBACK;
11228 else
11229 cache = MTRR_TYPE_UNCACHABLE;
11230 goto exit;
11233 cache = kvm_mtrr_get_guest_memory_type(vcpu, gfn);
11235 exit:
11236 return (cache << VMX_EPT_MT_EPTE_SHIFT) | ipat;
11239 static int vmx_get_lpage_level(void)
11241 if (enable_ept && !cpu_has_vmx_ept_1g_page())
11242 return PT_DIRECTORY_LEVEL;
11243 else
11244 /* For shadow and EPT supported 1GB page */
11245 return PT_PDPE_LEVEL;
11248 static void vmcs_set_secondary_exec_control(u32 new_ctl)
11251 * These bits in the secondary execution controls field
11252 * are dynamic, the others are mostly based on the hypervisor
11253 * architecture and the guest's CPUID. Do not touch the
11254 * dynamic bits.
11256 u32 mask =
11257 SECONDARY_EXEC_SHADOW_VMCS |
11258 SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE |
11259 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
11260 SECONDARY_EXEC_DESC;
11262 u32 cur_ctl = vmcs_read32(SECONDARY_VM_EXEC_CONTROL);
11264 vmcs_write32(SECONDARY_VM_EXEC_CONTROL,
11265 (new_ctl & ~mask) | (cur_ctl & mask));
11269 * Generate MSR_IA32_VMX_CR{0,4}_FIXED1 according to CPUID. Only set bits
11270 * (indicating "allowed-1") if they are supported in the guest's CPUID.
11272 static void nested_vmx_cr_fixed1_bits_update(struct kvm_vcpu *vcpu)
11274 struct vcpu_vmx *vmx = to_vmx(vcpu);
11275 struct kvm_cpuid_entry2 *entry;
11277 vmx->nested.msrs.cr0_fixed1 = 0xffffffff;
11278 vmx->nested.msrs.cr4_fixed1 = X86_CR4_PCE;
11280 #define cr4_fixed1_update(_cr4_mask, _reg, _cpuid_mask) do { \
11281 if (entry && (entry->_reg & (_cpuid_mask))) \
11282 vmx->nested.msrs.cr4_fixed1 |= (_cr4_mask); \
11283 } while (0)
11285 entry = kvm_find_cpuid_entry(vcpu, 0x1, 0);
11286 cr4_fixed1_update(X86_CR4_VME, edx, bit(X86_FEATURE_VME));
11287 cr4_fixed1_update(X86_CR4_PVI, edx, bit(X86_FEATURE_VME));
11288 cr4_fixed1_update(X86_CR4_TSD, edx, bit(X86_FEATURE_TSC));
11289 cr4_fixed1_update(X86_CR4_DE, edx, bit(X86_FEATURE_DE));
11290 cr4_fixed1_update(X86_CR4_PSE, edx, bit(X86_FEATURE_PSE));
11291 cr4_fixed1_update(X86_CR4_PAE, edx, bit(X86_FEATURE_PAE));
11292 cr4_fixed1_update(X86_CR4_MCE, edx, bit(X86_FEATURE_MCE));
11293 cr4_fixed1_update(X86_CR4_PGE, edx, bit(X86_FEATURE_PGE));
11294 cr4_fixed1_update(X86_CR4_OSFXSR, edx, bit(X86_FEATURE_FXSR));
11295 cr4_fixed1_update(X86_CR4_OSXMMEXCPT, edx, bit(X86_FEATURE_XMM));
11296 cr4_fixed1_update(X86_CR4_VMXE, ecx, bit(X86_FEATURE_VMX));
11297 cr4_fixed1_update(X86_CR4_SMXE, ecx, bit(X86_FEATURE_SMX));
11298 cr4_fixed1_update(X86_CR4_PCIDE, ecx, bit(X86_FEATURE_PCID));
11299 cr4_fixed1_update(X86_CR4_OSXSAVE, ecx, bit(X86_FEATURE_XSAVE));
11301 entry = kvm_find_cpuid_entry(vcpu, 0x7, 0);
11302 cr4_fixed1_update(X86_CR4_FSGSBASE, ebx, bit(X86_FEATURE_FSGSBASE));
11303 cr4_fixed1_update(X86_CR4_SMEP, ebx, bit(X86_FEATURE_SMEP));
11304 cr4_fixed1_update(X86_CR4_SMAP, ebx, bit(X86_FEATURE_SMAP));
11305 cr4_fixed1_update(X86_CR4_PKE, ecx, bit(X86_FEATURE_PKU));
11306 cr4_fixed1_update(X86_CR4_UMIP, ecx, bit(X86_FEATURE_UMIP));
11308 #undef cr4_fixed1_update
11311 static void nested_vmx_entry_exit_ctls_update(struct kvm_vcpu *vcpu)
11313 struct vcpu_vmx *vmx = to_vmx(vcpu);
11315 if (kvm_mpx_supported()) {
11316 bool mpx_enabled = guest_cpuid_has(vcpu, X86_FEATURE_MPX);
11318 if (mpx_enabled) {
11319 vmx->nested.msrs.entry_ctls_high |= VM_ENTRY_LOAD_BNDCFGS;
11320 vmx->nested.msrs.exit_ctls_high |= VM_EXIT_CLEAR_BNDCFGS;
11321 } else {
11322 vmx->nested.msrs.entry_ctls_high &= ~VM_ENTRY_LOAD_BNDCFGS;
11323 vmx->nested.msrs.exit_ctls_high &= ~VM_EXIT_CLEAR_BNDCFGS;
11328 static void vmx_cpuid_update(struct kvm_vcpu *vcpu)
11330 struct vcpu_vmx *vmx = to_vmx(vcpu);
11332 if (cpu_has_secondary_exec_ctrls()) {
11333 vmx_compute_secondary_exec_control(vmx);
11334 vmcs_set_secondary_exec_control(vmx->secondary_exec_control);
11337 if (nested_vmx_allowed(vcpu))
11338 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
11339 FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11340 else
11341 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
11342 ~FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX;
11344 if (nested_vmx_allowed(vcpu)) {
11345 nested_vmx_cr_fixed1_bits_update(vcpu);
11346 nested_vmx_entry_exit_ctls_update(vcpu);
11350 static void vmx_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
11352 if (func == 1 && nested)
11353 entry->ecx |= bit(X86_FEATURE_VMX);
11356 static void nested_ept_inject_page_fault(struct kvm_vcpu *vcpu,
11357 struct x86_exception *fault)
11359 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11360 struct vcpu_vmx *vmx = to_vmx(vcpu);
11361 u32 exit_reason;
11362 unsigned long exit_qualification = vcpu->arch.exit_qualification;
11364 if (vmx->nested.pml_full) {
11365 exit_reason = EXIT_REASON_PML_FULL;
11366 vmx->nested.pml_full = false;
11367 exit_qualification &= INTR_INFO_UNBLOCK_NMI;
11368 } else if (fault->error_code & PFERR_RSVD_MASK)
11369 exit_reason = EXIT_REASON_EPT_MISCONFIG;
11370 else
11371 exit_reason = EXIT_REASON_EPT_VIOLATION;
11373 nested_vmx_vmexit(vcpu, exit_reason, 0, exit_qualification);
11374 vmcs12->guest_physical_address = fault->address;
11377 static bool nested_ept_ad_enabled(struct kvm_vcpu *vcpu)
11379 return nested_ept_get_cr3(vcpu) & VMX_EPTP_AD_ENABLE_BIT;
11382 /* Callbacks for nested_ept_init_mmu_context: */
11384 static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu)
11386 /* return the page table to be shadowed - in our case, EPT12 */
11387 return get_vmcs12(vcpu)->ept_pointer;
11390 static int nested_ept_init_mmu_context(struct kvm_vcpu *vcpu)
11392 WARN_ON(mmu_is_nested(vcpu));
11393 if (!valid_ept_address(vcpu, nested_ept_get_cr3(vcpu)))
11394 return 1;
11396 kvm_init_shadow_ept_mmu(vcpu,
11397 to_vmx(vcpu)->nested.msrs.ept_caps &
11398 VMX_EPT_EXECUTE_ONLY_BIT,
11399 nested_ept_ad_enabled(vcpu),
11400 nested_ept_get_cr3(vcpu));
11401 vcpu->arch.mmu.set_cr3 = vmx_set_cr3;
11402 vcpu->arch.mmu.get_cr3 = nested_ept_get_cr3;
11403 vcpu->arch.mmu.inject_page_fault = nested_ept_inject_page_fault;
11405 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
11406 return 0;
11409 static void nested_ept_uninit_mmu_context(struct kvm_vcpu *vcpu)
11411 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
11414 static bool nested_vmx_is_page_fault_vmexit(struct vmcs12 *vmcs12,
11415 u16 error_code)
11417 bool inequality, bit;
11419 bit = (vmcs12->exception_bitmap & (1u << PF_VECTOR)) != 0;
11420 inequality =
11421 (error_code & vmcs12->page_fault_error_code_mask) !=
11422 vmcs12->page_fault_error_code_match;
11423 return inequality ^ bit;
11426 static void vmx_inject_page_fault_nested(struct kvm_vcpu *vcpu,
11427 struct x86_exception *fault)
11429 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11431 WARN_ON(!is_guest_mode(vcpu));
11433 if (nested_vmx_is_page_fault_vmexit(vmcs12, fault->error_code) &&
11434 !to_vmx(vcpu)->nested.nested_run_pending) {
11435 vmcs12->vm_exit_intr_error_code = fault->error_code;
11436 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
11437 PF_VECTOR | INTR_TYPE_HARD_EXCEPTION |
11438 INTR_INFO_DELIVER_CODE_MASK | INTR_INFO_VALID_MASK,
11439 fault->address);
11440 } else {
11441 kvm_inject_page_fault(vcpu, fault);
11445 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11446 struct vmcs12 *vmcs12);
11448 static void nested_get_vmcs12_pages(struct kvm_vcpu *vcpu)
11450 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11451 struct vcpu_vmx *vmx = to_vmx(vcpu);
11452 struct page *page;
11453 u64 hpa;
11455 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
11457 * Translate L1 physical address to host physical
11458 * address for vmcs02. Keep the page pinned, so this
11459 * physical address remains valid. We keep a reference
11460 * to it so we can release it later.
11462 if (vmx->nested.apic_access_page) { /* shouldn't happen */
11463 kvm_release_page_dirty(vmx->nested.apic_access_page);
11464 vmx->nested.apic_access_page = NULL;
11466 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->apic_access_addr);
11468 * If translation failed, no matter: This feature asks
11469 * to exit when accessing the given address, and if it
11470 * can never be accessed, this feature won't do
11471 * anything anyway.
11473 if (!is_error_page(page)) {
11474 vmx->nested.apic_access_page = page;
11475 hpa = page_to_phys(vmx->nested.apic_access_page);
11476 vmcs_write64(APIC_ACCESS_ADDR, hpa);
11477 } else {
11478 vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
11479 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES);
11483 if (nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW)) {
11484 if (vmx->nested.virtual_apic_page) { /* shouldn't happen */
11485 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
11486 vmx->nested.virtual_apic_page = NULL;
11488 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->virtual_apic_page_addr);
11491 * If translation failed, VM entry will fail because
11492 * prepare_vmcs02 set VIRTUAL_APIC_PAGE_ADDR to -1ull.
11493 * Failing the vm entry is _not_ what the processor
11494 * does but it's basically the only possibility we
11495 * have. We could still enter the guest if CR8 load
11496 * exits are enabled, CR8 store exits are enabled, and
11497 * virtualize APIC access is disabled; in this case
11498 * the processor would never use the TPR shadow and we
11499 * could simply clear the bit from the execution
11500 * control. But such a configuration is useless, so
11501 * let's keep the code simple.
11503 if (!is_error_page(page)) {
11504 vmx->nested.virtual_apic_page = page;
11505 hpa = page_to_phys(vmx->nested.virtual_apic_page);
11506 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, hpa);
11510 if (nested_cpu_has_posted_intr(vmcs12)) {
11511 if (vmx->nested.pi_desc_page) { /* shouldn't happen */
11512 kunmap(vmx->nested.pi_desc_page);
11513 kvm_release_page_dirty(vmx->nested.pi_desc_page);
11514 vmx->nested.pi_desc_page = NULL;
11515 vmx->nested.pi_desc = NULL;
11516 vmcs_write64(POSTED_INTR_DESC_ADDR, -1ull);
11518 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->posted_intr_desc_addr);
11519 if (is_error_page(page))
11520 return;
11521 vmx->nested.pi_desc_page = page;
11522 vmx->nested.pi_desc = kmap(vmx->nested.pi_desc_page);
11523 vmx->nested.pi_desc =
11524 (struct pi_desc *)((void *)vmx->nested.pi_desc +
11525 (unsigned long)(vmcs12->posted_intr_desc_addr &
11526 (PAGE_SIZE - 1)));
11527 vmcs_write64(POSTED_INTR_DESC_ADDR,
11528 page_to_phys(vmx->nested.pi_desc_page) +
11529 (unsigned long)(vmcs12->posted_intr_desc_addr &
11530 (PAGE_SIZE - 1)));
11532 if (nested_vmx_prepare_msr_bitmap(vcpu, vmcs12))
11533 vmcs_set_bits(CPU_BASED_VM_EXEC_CONTROL,
11534 CPU_BASED_USE_MSR_BITMAPS);
11535 else
11536 vmcs_clear_bits(CPU_BASED_VM_EXEC_CONTROL,
11537 CPU_BASED_USE_MSR_BITMAPS);
11540 static void vmx_start_preemption_timer(struct kvm_vcpu *vcpu)
11542 u64 preemption_timeout = get_vmcs12(vcpu)->vmx_preemption_timer_value;
11543 struct vcpu_vmx *vmx = to_vmx(vcpu);
11546 * A timer value of zero is architecturally guaranteed to cause
11547 * a VMExit prior to executing any instructions in the guest.
11549 if (preemption_timeout == 0) {
11550 vmx_preemption_timer_fn(&vmx->nested.preemption_timer);
11551 return;
11554 if (vcpu->arch.virtual_tsc_khz == 0)
11555 return;
11557 preemption_timeout <<= VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
11558 preemption_timeout *= 1000000;
11559 do_div(preemption_timeout, vcpu->arch.virtual_tsc_khz);
11560 hrtimer_start(&vmx->nested.preemption_timer,
11561 ns_to_ktime(preemption_timeout), HRTIMER_MODE_REL);
11564 static int nested_vmx_check_io_bitmap_controls(struct kvm_vcpu *vcpu,
11565 struct vmcs12 *vmcs12)
11567 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_IO_BITMAPS))
11568 return 0;
11570 if (!page_address_valid(vcpu, vmcs12->io_bitmap_a) ||
11571 !page_address_valid(vcpu, vmcs12->io_bitmap_b))
11572 return -EINVAL;
11574 return 0;
11577 static int nested_vmx_check_msr_bitmap_controls(struct kvm_vcpu *vcpu,
11578 struct vmcs12 *vmcs12)
11580 if (!nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11581 return 0;
11583 if (!page_address_valid(vcpu, vmcs12->msr_bitmap))
11584 return -EINVAL;
11586 return 0;
11589 static int nested_vmx_check_tpr_shadow_controls(struct kvm_vcpu *vcpu,
11590 struct vmcs12 *vmcs12)
11592 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11593 return 0;
11595 if (!page_address_valid(vcpu, vmcs12->virtual_apic_page_addr))
11596 return -EINVAL;
11598 return 0;
11601 static inline void enable_x2apic_msr_intercepts(unsigned long *msr_bitmap) {
11602 int msr;
11604 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11605 unsigned word = msr / BITS_PER_LONG;
11607 msr_bitmap[word] = ~0;
11608 msr_bitmap[word + (0x800 / sizeof(long))] = ~0;
11613 * Merge L0's and L1's MSR bitmap, return false to indicate that
11614 * we do not use the hardware.
11616 static inline bool nested_vmx_prepare_msr_bitmap(struct kvm_vcpu *vcpu,
11617 struct vmcs12 *vmcs12)
11619 int msr;
11620 struct page *page;
11621 unsigned long *msr_bitmap_l1;
11622 unsigned long *msr_bitmap_l0 = to_vmx(vcpu)->nested.vmcs02.msr_bitmap;
11624 * pred_cmd & spec_ctrl are trying to verify two things:
11626 * 1. L0 gave a permission to L1 to actually passthrough the MSR. This
11627 * ensures that we do not accidentally generate an L02 MSR bitmap
11628 * from the L12 MSR bitmap that is too permissive.
11629 * 2. That L1 or L2s have actually used the MSR. This avoids
11630 * unnecessarily merging of the bitmap if the MSR is unused. This
11631 * works properly because we only update the L01 MSR bitmap lazily.
11632 * So even if L0 should pass L1 these MSRs, the L01 bitmap is only
11633 * updated to reflect this when L1 (or its L2s) actually write to
11634 * the MSR.
11636 bool pred_cmd = !msr_write_intercepted_l01(vcpu, MSR_IA32_PRED_CMD);
11637 bool spec_ctrl = !msr_write_intercepted_l01(vcpu, MSR_IA32_SPEC_CTRL);
11639 /* Nothing to do if the MSR bitmap is not in use. */
11640 if (!cpu_has_vmx_msr_bitmap() ||
11641 !nested_cpu_has(vmcs12, CPU_BASED_USE_MSR_BITMAPS))
11642 return false;
11644 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11645 !pred_cmd && !spec_ctrl)
11646 return false;
11648 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->msr_bitmap);
11649 if (is_error_page(page))
11650 return false;
11652 msr_bitmap_l1 = (unsigned long *)kmap(page);
11655 * To keep the control flow simple, pay eight 8-byte writes (sixteen
11656 * 4-byte writes on 32-bit systems) up front to enable intercepts for
11657 * the x2APIC MSR range and selectively disable them below.
11659 enable_x2apic_msr_intercepts(msr_bitmap_l0);
11661 if (nested_cpu_has_virt_x2apic_mode(vmcs12)) {
11662 if (nested_cpu_has_apic_reg_virt(vmcs12)) {
11664 * L0 need not intercept reads for MSRs between 0x800
11665 * and 0x8ff, it just lets the processor take the value
11666 * from the virtual-APIC page; take those 256 bits
11667 * directly from the L1 bitmap.
11669 for (msr = 0x800; msr <= 0x8ff; msr += BITS_PER_LONG) {
11670 unsigned word = msr / BITS_PER_LONG;
11672 msr_bitmap_l0[word] = msr_bitmap_l1[word];
11676 nested_vmx_disable_intercept_for_msr(
11677 msr_bitmap_l1, msr_bitmap_l0,
11678 X2APIC_MSR(APIC_TASKPRI),
11679 MSR_TYPE_R | MSR_TYPE_W);
11681 if (nested_cpu_has_vid(vmcs12)) {
11682 nested_vmx_disable_intercept_for_msr(
11683 msr_bitmap_l1, msr_bitmap_l0,
11684 X2APIC_MSR(APIC_EOI),
11685 MSR_TYPE_W);
11686 nested_vmx_disable_intercept_for_msr(
11687 msr_bitmap_l1, msr_bitmap_l0,
11688 X2APIC_MSR(APIC_SELF_IPI),
11689 MSR_TYPE_W);
11693 if (spec_ctrl)
11694 nested_vmx_disable_intercept_for_msr(
11695 msr_bitmap_l1, msr_bitmap_l0,
11696 MSR_IA32_SPEC_CTRL,
11697 MSR_TYPE_R | MSR_TYPE_W);
11699 if (pred_cmd)
11700 nested_vmx_disable_intercept_for_msr(
11701 msr_bitmap_l1, msr_bitmap_l0,
11702 MSR_IA32_PRED_CMD,
11703 MSR_TYPE_W);
11705 kunmap(page);
11706 kvm_release_page_clean(page);
11708 return true;
11711 static void nested_cache_shadow_vmcs12(struct kvm_vcpu *vcpu,
11712 struct vmcs12 *vmcs12)
11714 struct vmcs12 *shadow;
11715 struct page *page;
11717 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11718 vmcs12->vmcs_link_pointer == -1ull)
11719 return;
11721 shadow = get_shadow_vmcs12(vcpu);
11722 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
11724 memcpy(shadow, kmap(page), VMCS12_SIZE);
11726 kunmap(page);
11727 kvm_release_page_clean(page);
11730 static void nested_flush_cached_shadow_vmcs12(struct kvm_vcpu *vcpu,
11731 struct vmcs12 *vmcs12)
11733 struct vcpu_vmx *vmx = to_vmx(vcpu);
11735 if (!nested_cpu_has_shadow_vmcs(vmcs12) ||
11736 vmcs12->vmcs_link_pointer == -1ull)
11737 return;
11739 kvm_write_guest(vmx->vcpu.kvm, vmcs12->vmcs_link_pointer,
11740 get_shadow_vmcs12(vcpu), VMCS12_SIZE);
11743 static int nested_vmx_check_apic_access_controls(struct kvm_vcpu *vcpu,
11744 struct vmcs12 *vmcs12)
11746 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) &&
11747 !page_address_valid(vcpu, vmcs12->apic_access_addr))
11748 return -EINVAL;
11749 else
11750 return 0;
11753 static int nested_vmx_check_apicv_controls(struct kvm_vcpu *vcpu,
11754 struct vmcs12 *vmcs12)
11756 if (!nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11757 !nested_cpu_has_apic_reg_virt(vmcs12) &&
11758 !nested_cpu_has_vid(vmcs12) &&
11759 !nested_cpu_has_posted_intr(vmcs12))
11760 return 0;
11763 * If virtualize x2apic mode is enabled,
11764 * virtualize apic access must be disabled.
11766 if (nested_cpu_has_virt_x2apic_mode(vmcs12) &&
11767 nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES))
11768 return -EINVAL;
11771 * If virtual interrupt delivery is enabled,
11772 * we must exit on external interrupts.
11774 if (nested_cpu_has_vid(vmcs12) &&
11775 !nested_exit_on_intr(vcpu))
11776 return -EINVAL;
11779 * bits 15:8 should be zero in posted_intr_nv,
11780 * the descriptor address has been already checked
11781 * in nested_get_vmcs12_pages.
11783 * bits 5:0 of posted_intr_desc_addr should be zero.
11785 if (nested_cpu_has_posted_intr(vmcs12) &&
11786 (!nested_cpu_has_vid(vmcs12) ||
11787 !nested_exit_intr_ack_set(vcpu) ||
11788 (vmcs12->posted_intr_nv & 0xff00) ||
11789 (vmcs12->posted_intr_desc_addr & 0x3f) ||
11790 (vmcs12->posted_intr_desc_addr >> cpuid_maxphyaddr(vcpu))))
11791 return -EINVAL;
11793 /* tpr shadow is needed by all apicv features. */
11794 if (!nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW))
11795 return -EINVAL;
11797 return 0;
11800 static int nested_vmx_check_msr_switch(struct kvm_vcpu *vcpu,
11801 unsigned long count_field,
11802 unsigned long addr_field)
11804 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
11805 int maxphyaddr;
11806 u64 count, addr;
11808 if (vmcs12_read_any(vmcs12, count_field, &count) ||
11809 vmcs12_read_any(vmcs12, addr_field, &addr)) {
11810 WARN_ON(1);
11811 return -EINVAL;
11813 if (count == 0)
11814 return 0;
11815 maxphyaddr = cpuid_maxphyaddr(vcpu);
11816 if (!IS_ALIGNED(addr, 16) || addr >> maxphyaddr ||
11817 (addr + count * sizeof(struct vmx_msr_entry) - 1) >> maxphyaddr) {
11818 pr_debug_ratelimited(
11819 "nVMX: invalid MSR switch (0x%lx, %d, %llu, 0x%08llx)",
11820 addr_field, maxphyaddr, count, addr);
11821 return -EINVAL;
11823 return 0;
11826 static int nested_vmx_check_msr_switch_controls(struct kvm_vcpu *vcpu,
11827 struct vmcs12 *vmcs12)
11829 if (vmcs12->vm_exit_msr_load_count == 0 &&
11830 vmcs12->vm_exit_msr_store_count == 0 &&
11831 vmcs12->vm_entry_msr_load_count == 0)
11832 return 0; /* Fast path */
11833 if (nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_LOAD_COUNT,
11834 VM_EXIT_MSR_LOAD_ADDR) ||
11835 nested_vmx_check_msr_switch(vcpu, VM_EXIT_MSR_STORE_COUNT,
11836 VM_EXIT_MSR_STORE_ADDR) ||
11837 nested_vmx_check_msr_switch(vcpu, VM_ENTRY_MSR_LOAD_COUNT,
11838 VM_ENTRY_MSR_LOAD_ADDR))
11839 return -EINVAL;
11840 return 0;
11843 static int nested_vmx_check_pml_controls(struct kvm_vcpu *vcpu,
11844 struct vmcs12 *vmcs12)
11846 u64 address = vmcs12->pml_address;
11847 int maxphyaddr = cpuid_maxphyaddr(vcpu);
11849 if (nested_cpu_has2(vmcs12, SECONDARY_EXEC_ENABLE_PML)) {
11850 if (!nested_cpu_has_ept(vmcs12) ||
11851 !IS_ALIGNED(address, 4096) ||
11852 address >> maxphyaddr)
11853 return -EINVAL;
11856 return 0;
11859 static int nested_vmx_check_shadow_vmcs_controls(struct kvm_vcpu *vcpu,
11860 struct vmcs12 *vmcs12)
11862 if (!nested_cpu_has_shadow_vmcs(vmcs12))
11863 return 0;
11865 if (!page_address_valid(vcpu, vmcs12->vmread_bitmap) ||
11866 !page_address_valid(vcpu, vmcs12->vmwrite_bitmap))
11867 return -EINVAL;
11869 return 0;
11872 static int nested_vmx_msr_check_common(struct kvm_vcpu *vcpu,
11873 struct vmx_msr_entry *e)
11875 /* x2APIC MSR accesses are not allowed */
11876 if (vcpu->arch.apic_base & X2APIC_ENABLE && e->index >> 8 == 0x8)
11877 return -EINVAL;
11878 if (e->index == MSR_IA32_UCODE_WRITE || /* SDM Table 35-2 */
11879 e->index == MSR_IA32_UCODE_REV)
11880 return -EINVAL;
11881 if (e->reserved != 0)
11882 return -EINVAL;
11883 return 0;
11886 static int nested_vmx_load_msr_check(struct kvm_vcpu *vcpu,
11887 struct vmx_msr_entry *e)
11889 if (e->index == MSR_FS_BASE ||
11890 e->index == MSR_GS_BASE ||
11891 e->index == MSR_IA32_SMM_MONITOR_CTL || /* SMM is not supported */
11892 nested_vmx_msr_check_common(vcpu, e))
11893 return -EINVAL;
11894 return 0;
11897 static int nested_vmx_store_msr_check(struct kvm_vcpu *vcpu,
11898 struct vmx_msr_entry *e)
11900 if (e->index == MSR_IA32_SMBASE || /* SMM is not supported */
11901 nested_vmx_msr_check_common(vcpu, e))
11902 return -EINVAL;
11903 return 0;
11907 * Load guest's/host's msr at nested entry/exit.
11908 * return 0 for success, entry index for failure.
11910 static u32 nested_vmx_load_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11912 u32 i;
11913 struct vmx_msr_entry e;
11914 struct msr_data msr;
11916 msr.host_initiated = false;
11917 for (i = 0; i < count; i++) {
11918 if (kvm_vcpu_read_guest(vcpu, gpa + i * sizeof(e),
11919 &e, sizeof(e))) {
11920 pr_debug_ratelimited(
11921 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11922 __func__, i, gpa + i * sizeof(e));
11923 goto fail;
11925 if (nested_vmx_load_msr_check(vcpu, &e)) {
11926 pr_debug_ratelimited(
11927 "%s check failed (%u, 0x%x, 0x%x)\n",
11928 __func__, i, e.index, e.reserved);
11929 goto fail;
11931 msr.index = e.index;
11932 msr.data = e.value;
11933 if (kvm_set_msr(vcpu, &msr)) {
11934 pr_debug_ratelimited(
11935 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11936 __func__, i, e.index, e.value);
11937 goto fail;
11940 return 0;
11941 fail:
11942 return i + 1;
11945 static int nested_vmx_store_msr(struct kvm_vcpu *vcpu, u64 gpa, u32 count)
11947 u32 i;
11948 struct vmx_msr_entry e;
11950 for (i = 0; i < count; i++) {
11951 struct msr_data msr_info;
11952 if (kvm_vcpu_read_guest(vcpu,
11953 gpa + i * sizeof(e),
11954 &e, 2 * sizeof(u32))) {
11955 pr_debug_ratelimited(
11956 "%s cannot read MSR entry (%u, 0x%08llx)\n",
11957 __func__, i, gpa + i * sizeof(e));
11958 return -EINVAL;
11960 if (nested_vmx_store_msr_check(vcpu, &e)) {
11961 pr_debug_ratelimited(
11962 "%s check failed (%u, 0x%x, 0x%x)\n",
11963 __func__, i, e.index, e.reserved);
11964 return -EINVAL;
11966 msr_info.host_initiated = false;
11967 msr_info.index = e.index;
11968 if (kvm_get_msr(vcpu, &msr_info)) {
11969 pr_debug_ratelimited(
11970 "%s cannot read MSR (%u, 0x%x)\n",
11971 __func__, i, e.index);
11972 return -EINVAL;
11974 if (kvm_vcpu_write_guest(vcpu,
11975 gpa + i * sizeof(e) +
11976 offsetof(struct vmx_msr_entry, value),
11977 &msr_info.data, sizeof(msr_info.data))) {
11978 pr_debug_ratelimited(
11979 "%s cannot write MSR (%u, 0x%x, 0x%llx)\n",
11980 __func__, i, e.index, msr_info.data);
11981 return -EINVAL;
11984 return 0;
11987 static bool nested_cr3_valid(struct kvm_vcpu *vcpu, unsigned long val)
11989 unsigned long invalid_mask;
11991 invalid_mask = (~0ULL) << cpuid_maxphyaddr(vcpu);
11992 return (val & invalid_mask) == 0;
11996 * Load guest's/host's cr3 at nested entry/exit. nested_ept is true if we are
11997 * emulating VM entry into a guest with EPT enabled.
11998 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
11999 * is assigned to entry_failure_code on failure.
12001 static int nested_vmx_load_cr3(struct kvm_vcpu *vcpu, unsigned long cr3, bool nested_ept,
12002 u32 *entry_failure_code)
12004 if (cr3 != kvm_read_cr3(vcpu) || (!nested_ept && pdptrs_changed(vcpu))) {
12005 if (!nested_cr3_valid(vcpu, cr3)) {
12006 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12007 return 1;
12011 * If PAE paging and EPT are both on, CR3 is not used by the CPU and
12012 * must not be dereferenced.
12014 if (!is_long_mode(vcpu) && is_pae(vcpu) && is_paging(vcpu) &&
12015 !nested_ept) {
12016 if (!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3)) {
12017 *entry_failure_code = ENTRY_FAIL_PDPTE;
12018 return 1;
12023 if (!nested_ept)
12024 kvm_mmu_new_cr3(vcpu, cr3, false);
12026 vcpu->arch.cr3 = cr3;
12027 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
12029 kvm_init_mmu(vcpu, false);
12031 return 0;
12034 static void prepare_vmcs02_full(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12036 struct vcpu_vmx *vmx = to_vmx(vcpu);
12038 vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector);
12039 vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector);
12040 vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector);
12041 vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector);
12042 vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector);
12043 vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector);
12044 vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector);
12045 vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit);
12046 vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit);
12047 vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit);
12048 vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit);
12049 vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit);
12050 vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit);
12051 vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit);
12052 vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit);
12053 vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit);
12054 vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes);
12055 vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes);
12056 vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes);
12057 vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes);
12058 vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes);
12059 vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes);
12060 vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes);
12061 vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base);
12062 vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base);
12063 vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base);
12064 vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base);
12065 vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base);
12066 vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base);
12067 vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base);
12068 vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base);
12070 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs);
12071 vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS,
12072 vmcs12->guest_pending_dbg_exceptions);
12073 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp);
12074 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip);
12076 if (nested_cpu_has_xsaves(vmcs12))
12077 vmcs_write64(XSS_EXIT_BITMAP, vmcs12->xss_exit_bitmap);
12078 vmcs_write64(VMCS_LINK_POINTER, -1ull);
12080 if (cpu_has_vmx_posted_intr())
12081 vmcs_write16(POSTED_INTR_NV, POSTED_INTR_NESTED_VECTOR);
12084 * Whether page-faults are trapped is determined by a combination of
12085 * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF.
12086 * If enable_ept, L0 doesn't care about page faults and we should
12087 * set all of these to L1's desires. However, if !enable_ept, L0 does
12088 * care about (at least some) page faults, and because it is not easy
12089 * (if at all possible?) to merge L0 and L1's desires, we simply ask
12090 * to exit on each and every L2 page fault. This is done by setting
12091 * MASK=MATCH=0 and (see below) EB.PF=1.
12092 * Note that below we don't need special code to set EB.PF beyond the
12093 * "or"ing of the EB of vmcs01 and vmcs12, because when enable_ept,
12094 * vmcs01's EB.PF is 0 so the "or" will take vmcs12's value, and when
12095 * !enable_ept, EB.PF is 1, so the "or" will always be 1.
12097 vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK,
12098 enable_ept ? vmcs12->page_fault_error_code_mask : 0);
12099 vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH,
12100 enable_ept ? vmcs12->page_fault_error_code_match : 0);
12102 /* All VMFUNCs are currently emulated through L0 vmexits. */
12103 if (cpu_has_vmx_vmfunc())
12104 vmcs_write64(VM_FUNCTION_CONTROL, 0);
12106 if (cpu_has_vmx_apicv()) {
12107 vmcs_write64(EOI_EXIT_BITMAP0, vmcs12->eoi_exit_bitmap0);
12108 vmcs_write64(EOI_EXIT_BITMAP1, vmcs12->eoi_exit_bitmap1);
12109 vmcs_write64(EOI_EXIT_BITMAP2, vmcs12->eoi_exit_bitmap2);
12110 vmcs_write64(EOI_EXIT_BITMAP3, vmcs12->eoi_exit_bitmap3);
12114 * Set host-state according to L0's settings (vmcs12 is irrelevant here)
12115 * Some constant fields are set here by vmx_set_constant_host_state().
12116 * Other fields are different per CPU, and will be set later when
12117 * vmx_vcpu_load() is called, and when vmx_prepare_switch_to_guest()
12118 * is called.
12120 vmx_set_constant_host_state(vmx);
12123 * Set the MSR load/store lists to match L0's settings.
12125 vmcs_write32(VM_EXIT_MSR_STORE_COUNT, 0);
12126 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
12127 vmcs_write64(VM_EXIT_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.host.val));
12128 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
12129 vmcs_write64(VM_ENTRY_MSR_LOAD_ADDR, __pa(vmx->msr_autoload.guest.val));
12131 set_cr4_guest_host_mask(vmx);
12133 if (kvm_mpx_supported()) {
12134 if (vmx->nested.nested_run_pending &&
12135 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12136 vmcs_write64(GUEST_BNDCFGS, vmcs12->guest_bndcfgs);
12137 else
12138 vmcs_write64(GUEST_BNDCFGS, vmx->nested.vmcs01_guest_bndcfgs);
12141 if (enable_vpid) {
12142 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02)
12143 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->nested.vpid02);
12144 else
12145 vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid);
12149 * L1 may access the L2's PDPTR, so save them to construct vmcs12
12151 if (enable_ept) {
12152 vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0);
12153 vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1);
12154 vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2);
12155 vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3);
12158 if (cpu_has_vmx_msr_bitmap())
12159 vmcs_write64(MSR_BITMAP, __pa(vmx->nested.vmcs02.msr_bitmap));
12163 * prepare_vmcs02 is called when the L1 guest hypervisor runs its nested
12164 * L2 guest. L1 has a vmcs for L2 (vmcs12), and this function "merges" it
12165 * with L0's requirements for its guest (a.k.a. vmcs01), so we can run the L2
12166 * guest in a way that will both be appropriate to L1's requests, and our
12167 * needs. In addition to modifying the active vmcs (which is vmcs02), this
12168 * function also has additional necessary side-effects, like setting various
12169 * vcpu->arch fields.
12170 * Returns 0 on success, 1 on failure. Invalid state exit qualification code
12171 * is assigned to entry_failure_code on failure.
12173 static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12174 u32 *entry_failure_code)
12176 struct vcpu_vmx *vmx = to_vmx(vcpu);
12177 u32 exec_control, vmcs12_exec_ctrl;
12179 if (vmx->nested.dirty_vmcs12) {
12180 prepare_vmcs02_full(vcpu, vmcs12);
12181 vmx->nested.dirty_vmcs12 = false;
12185 * First, the fields that are shadowed. This must be kept in sync
12186 * with vmx_shadow_fields.h.
12189 vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector);
12190 vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit);
12191 vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes);
12192 vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base);
12193 vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base);
12195 if (vmx->nested.nested_run_pending &&
12196 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS)) {
12197 kvm_set_dr(vcpu, 7, vmcs12->guest_dr7);
12198 vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl);
12199 } else {
12200 kvm_set_dr(vcpu, 7, vcpu->arch.dr7);
12201 vmcs_write64(GUEST_IA32_DEBUGCTL, vmx->nested.vmcs01_debugctl);
12203 if (vmx->nested.nested_run_pending) {
12204 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD,
12205 vmcs12->vm_entry_intr_info_field);
12206 vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE,
12207 vmcs12->vm_entry_exception_error_code);
12208 vmcs_write32(VM_ENTRY_INSTRUCTION_LEN,
12209 vmcs12->vm_entry_instruction_len);
12210 vmcs_write32(GUEST_INTERRUPTIBILITY_INFO,
12211 vmcs12->guest_interruptibility_info);
12212 vmx->loaded_vmcs->nmi_known_unmasked =
12213 !(vmcs12->guest_interruptibility_info & GUEST_INTR_STATE_NMI);
12214 } else {
12215 vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, 0);
12217 vmx_set_rflags(vcpu, vmcs12->guest_rflags);
12219 exec_control = vmcs12->pin_based_vm_exec_control;
12221 /* Preemption timer setting is computed directly in vmx_vcpu_run. */
12222 exec_control |= vmcs_config.pin_based_exec_ctrl;
12223 exec_control &= ~PIN_BASED_VMX_PREEMPTION_TIMER;
12224 vmx->loaded_vmcs->hv_timer_armed = false;
12226 /* Posted interrupts setting is only taken from vmcs12. */
12227 if (nested_cpu_has_posted_intr(vmcs12)) {
12228 vmx->nested.posted_intr_nv = vmcs12->posted_intr_nv;
12229 vmx->nested.pi_pending = false;
12230 } else {
12231 exec_control &= ~PIN_BASED_POSTED_INTR;
12234 vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, exec_control);
12236 vmx->nested.preemption_timer_expired = false;
12237 if (nested_cpu_has_preemption_timer(vmcs12))
12238 vmx_start_preemption_timer(vcpu);
12240 if (cpu_has_secondary_exec_ctrls()) {
12241 exec_control = vmx->secondary_exec_control;
12243 /* Take the following fields only from vmcs12 */
12244 exec_control &= ~(SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES |
12245 SECONDARY_EXEC_ENABLE_INVPCID |
12246 SECONDARY_EXEC_RDTSCP |
12247 SECONDARY_EXEC_XSAVES |
12248 SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY |
12249 SECONDARY_EXEC_APIC_REGISTER_VIRT |
12250 SECONDARY_EXEC_ENABLE_VMFUNC);
12251 if (nested_cpu_has(vmcs12,
12252 CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) {
12253 vmcs12_exec_ctrl = vmcs12->secondary_vm_exec_control &
12254 ~SECONDARY_EXEC_ENABLE_PML;
12255 exec_control |= vmcs12_exec_ctrl;
12258 /* VMCS shadowing for L2 is emulated for now */
12259 exec_control &= ~SECONDARY_EXEC_SHADOW_VMCS;
12261 if (exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY)
12262 vmcs_write16(GUEST_INTR_STATUS,
12263 vmcs12->guest_intr_status);
12266 * Write an illegal value to APIC_ACCESS_ADDR. Later,
12267 * nested_get_vmcs12_pages will either fix it up or
12268 * remove the VM execution control.
12270 if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)
12271 vmcs_write64(APIC_ACCESS_ADDR, -1ull);
12273 if (exec_control & SECONDARY_EXEC_ENCLS_EXITING)
12274 vmcs_write64(ENCLS_EXITING_BITMAP, -1ull);
12276 vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control);
12280 * HOST_RSP is normally set correctly in vmx_vcpu_run() just before
12281 * entry, but only if the current (host) sp changed from the value
12282 * we wrote last (vmx->host_rsp). This cache is no longer relevant
12283 * if we switch vmcs, and rather than hold a separate cache per vmcs,
12284 * here we just force the write to happen on entry.
12286 vmx->host_rsp = 0;
12288 exec_control = vmx_exec_control(vmx); /* L0's desires */
12289 exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING;
12290 exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING;
12291 exec_control &= ~CPU_BASED_TPR_SHADOW;
12292 exec_control |= vmcs12->cpu_based_vm_exec_control;
12295 * Write an illegal value to VIRTUAL_APIC_PAGE_ADDR. Later, if
12296 * nested_get_vmcs12_pages can't fix it up, the illegal value
12297 * will result in a VM entry failure.
12299 if (exec_control & CPU_BASED_TPR_SHADOW) {
12300 vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull);
12301 vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold);
12302 } else {
12303 #ifdef CONFIG_X86_64
12304 exec_control |= CPU_BASED_CR8_LOAD_EXITING |
12305 CPU_BASED_CR8_STORE_EXITING;
12306 #endif
12310 * A vmexit (to either L1 hypervisor or L0 userspace) is always needed
12311 * for I/O port accesses.
12313 exec_control &= ~CPU_BASED_USE_IO_BITMAPS;
12314 exec_control |= CPU_BASED_UNCOND_IO_EXITING;
12316 vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control);
12318 /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the
12319 * bitwise-or of what L1 wants to trap for L2, and what we want to
12320 * trap. Note that CR0.TS also needs updating - we do this later.
12322 update_exception_bitmap(vcpu);
12323 vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask;
12324 vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits);
12326 /* L2->L1 exit controls are emulated - the hardware exit is to L0 so
12327 * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER
12328 * bits are further modified by vmx_set_efer() below.
12330 vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl);
12332 /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are
12333 * emulated by vmx_set_efer(), below.
12335 vm_entry_controls_init(vmx,
12336 (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER &
12337 ~VM_ENTRY_IA32E_MODE) |
12338 (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE));
12340 if (vmx->nested.nested_run_pending &&
12341 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT)) {
12342 vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat);
12343 vcpu->arch.pat = vmcs12->guest_ia32_pat;
12344 } else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) {
12345 vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat);
12348 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
12350 if (kvm_has_tsc_control)
12351 decache_tsc_multiplier(vmx);
12353 if (enable_vpid) {
12355 * There is no direct mapping between vpid02 and vpid12, the
12356 * vpid02 is per-vCPU for L0 and reused while the value of
12357 * vpid12 is changed w/ one invvpid during nested vmentry.
12358 * The vpid12 is allocated by L1 for L2, so it will not
12359 * influence global bitmap(for vpid01 and vpid02 allocation)
12360 * even if spawn a lot of nested vCPUs.
12362 if (nested_cpu_has_vpid(vmcs12) && vmx->nested.vpid02) {
12363 if (vmcs12->virtual_processor_id != vmx->nested.last_vpid) {
12364 vmx->nested.last_vpid = vmcs12->virtual_processor_id;
12365 __vmx_flush_tlb(vcpu, vmx->nested.vpid02, true);
12367 } else {
12368 vmx_flush_tlb(vcpu, true);
12372 if (enable_pml) {
12374 * Conceptually we want to copy the PML address and index from
12375 * vmcs01 here, and then back to vmcs01 on nested vmexit. But,
12376 * since we always flush the log on each vmexit, this happens
12377 * to be equivalent to simply resetting the fields in vmcs02.
12379 ASSERT(vmx->pml_pg);
12380 vmcs_write64(PML_ADDRESS, page_to_phys(vmx->pml_pg));
12381 vmcs_write16(GUEST_PML_INDEX, PML_ENTITY_NUM - 1);
12384 if (nested_cpu_has_ept(vmcs12)) {
12385 if (nested_ept_init_mmu_context(vcpu)) {
12386 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12387 return 1;
12389 } else if (nested_cpu_has2(vmcs12,
12390 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
12391 vmx_flush_tlb(vcpu, true);
12395 * This sets GUEST_CR0 to vmcs12->guest_cr0, possibly modifying those
12396 * bits which we consider mandatory enabled.
12397 * The CR0_READ_SHADOW is what L2 should have expected to read given
12398 * the specifications by L1; It's not enough to take
12399 * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we
12400 * have more bits than L1 expected.
12402 vmx_set_cr0(vcpu, vmcs12->guest_cr0);
12403 vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12));
12405 vmx_set_cr4(vcpu, vmcs12->guest_cr4);
12406 vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12));
12408 if (vmx->nested.nested_run_pending &&
12409 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER))
12410 vcpu->arch.efer = vmcs12->guest_ia32_efer;
12411 else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE)
12412 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
12413 else
12414 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
12415 /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */
12416 vmx_set_efer(vcpu, vcpu->arch.efer);
12419 * Guest state is invalid and unrestricted guest is disabled,
12420 * which means L1 attempted VMEntry to L2 with invalid state.
12421 * Fail the VMEntry.
12423 if (vmx->emulation_required) {
12424 *entry_failure_code = ENTRY_FAIL_DEFAULT;
12425 return 1;
12428 /* Shadow page tables on either EPT or shadow page tables. */
12429 if (nested_vmx_load_cr3(vcpu, vmcs12->guest_cr3, nested_cpu_has_ept(vmcs12),
12430 entry_failure_code))
12431 return 1;
12433 if (!enable_ept)
12434 vcpu->arch.walk_mmu->inject_page_fault = vmx_inject_page_fault_nested;
12436 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp);
12437 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip);
12438 return 0;
12441 static int nested_vmx_check_nmi_controls(struct vmcs12 *vmcs12)
12443 if (!nested_cpu_has_nmi_exiting(vmcs12) &&
12444 nested_cpu_has_virtual_nmis(vmcs12))
12445 return -EINVAL;
12447 if (!nested_cpu_has_virtual_nmis(vmcs12) &&
12448 nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING))
12449 return -EINVAL;
12451 return 0;
12454 static int check_vmentry_prereqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12456 struct vcpu_vmx *vmx = to_vmx(vcpu);
12458 if (vmcs12->guest_activity_state != GUEST_ACTIVITY_ACTIVE &&
12459 vmcs12->guest_activity_state != GUEST_ACTIVITY_HLT)
12460 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12462 if (nested_cpu_has_vpid(vmcs12) && !vmcs12->virtual_processor_id)
12463 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12465 if (nested_vmx_check_io_bitmap_controls(vcpu, vmcs12))
12466 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12468 if (nested_vmx_check_msr_bitmap_controls(vcpu, vmcs12))
12469 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12471 if (nested_vmx_check_apic_access_controls(vcpu, vmcs12))
12472 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12474 if (nested_vmx_check_tpr_shadow_controls(vcpu, vmcs12))
12475 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12477 if (nested_vmx_check_apicv_controls(vcpu, vmcs12))
12478 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12480 if (nested_vmx_check_msr_switch_controls(vcpu, vmcs12))
12481 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12483 if (nested_vmx_check_pml_controls(vcpu, vmcs12))
12484 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12486 if (nested_vmx_check_shadow_vmcs_controls(vcpu, vmcs12))
12487 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12489 if (!vmx_control_verify(vmcs12->cpu_based_vm_exec_control,
12490 vmx->nested.msrs.procbased_ctls_low,
12491 vmx->nested.msrs.procbased_ctls_high) ||
12492 (nested_cpu_has(vmcs12, CPU_BASED_ACTIVATE_SECONDARY_CONTROLS) &&
12493 !vmx_control_verify(vmcs12->secondary_vm_exec_control,
12494 vmx->nested.msrs.secondary_ctls_low,
12495 vmx->nested.msrs.secondary_ctls_high)) ||
12496 !vmx_control_verify(vmcs12->pin_based_vm_exec_control,
12497 vmx->nested.msrs.pinbased_ctls_low,
12498 vmx->nested.msrs.pinbased_ctls_high) ||
12499 !vmx_control_verify(vmcs12->vm_exit_controls,
12500 vmx->nested.msrs.exit_ctls_low,
12501 vmx->nested.msrs.exit_ctls_high) ||
12502 !vmx_control_verify(vmcs12->vm_entry_controls,
12503 vmx->nested.msrs.entry_ctls_low,
12504 vmx->nested.msrs.entry_ctls_high))
12505 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12507 if (nested_vmx_check_nmi_controls(vmcs12))
12508 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12510 if (nested_cpu_has_vmfunc(vmcs12)) {
12511 if (vmcs12->vm_function_control &
12512 ~vmx->nested.msrs.vmfunc_controls)
12513 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12515 if (nested_cpu_has_eptp_switching(vmcs12)) {
12516 if (!nested_cpu_has_ept(vmcs12) ||
12517 !page_address_valid(vcpu, vmcs12->eptp_list_address))
12518 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12522 if (vmcs12->cr3_target_count > nested_cpu_vmx_misc_cr3_count(vcpu))
12523 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12525 if (!nested_host_cr0_valid(vcpu, vmcs12->host_cr0) ||
12526 !nested_host_cr4_valid(vcpu, vmcs12->host_cr4) ||
12527 !nested_cr3_valid(vcpu, vmcs12->host_cr3))
12528 return VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
12531 * From the Intel SDM, volume 3:
12532 * Fields relevant to VM-entry event injection must be set properly.
12533 * These fields are the VM-entry interruption-information field, the
12534 * VM-entry exception error code, and the VM-entry instruction length.
12536 if (vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) {
12537 u32 intr_info = vmcs12->vm_entry_intr_info_field;
12538 u8 vector = intr_info & INTR_INFO_VECTOR_MASK;
12539 u32 intr_type = intr_info & INTR_INFO_INTR_TYPE_MASK;
12540 bool has_error_code = intr_info & INTR_INFO_DELIVER_CODE_MASK;
12541 bool should_have_error_code;
12542 bool urg = nested_cpu_has2(vmcs12,
12543 SECONDARY_EXEC_UNRESTRICTED_GUEST);
12544 bool prot_mode = !urg || vmcs12->guest_cr0 & X86_CR0_PE;
12546 /* VM-entry interruption-info field: interruption type */
12547 if (intr_type == INTR_TYPE_RESERVED ||
12548 (intr_type == INTR_TYPE_OTHER_EVENT &&
12549 !nested_cpu_supports_monitor_trap_flag(vcpu)))
12550 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12552 /* VM-entry interruption-info field: vector */
12553 if ((intr_type == INTR_TYPE_NMI_INTR && vector != NMI_VECTOR) ||
12554 (intr_type == INTR_TYPE_HARD_EXCEPTION && vector > 31) ||
12555 (intr_type == INTR_TYPE_OTHER_EVENT && vector != 0))
12556 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12558 /* VM-entry interruption-info field: deliver error code */
12559 should_have_error_code =
12560 intr_type == INTR_TYPE_HARD_EXCEPTION && prot_mode &&
12561 x86_exception_has_error_code(vector);
12562 if (has_error_code != should_have_error_code)
12563 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12565 /* VM-entry exception error code */
12566 if (has_error_code &&
12567 vmcs12->vm_entry_exception_error_code & GENMASK(31, 15))
12568 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12570 /* VM-entry interruption-info field: reserved bits */
12571 if (intr_info & INTR_INFO_RESVD_BITS_MASK)
12572 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12574 /* VM-entry instruction length */
12575 switch (intr_type) {
12576 case INTR_TYPE_SOFT_EXCEPTION:
12577 case INTR_TYPE_SOFT_INTR:
12578 case INTR_TYPE_PRIV_SW_EXCEPTION:
12579 if ((vmcs12->vm_entry_instruction_len > 15) ||
12580 (vmcs12->vm_entry_instruction_len == 0 &&
12581 !nested_cpu_has_zero_length_injection(vcpu)))
12582 return VMXERR_ENTRY_INVALID_CONTROL_FIELD;
12586 return 0;
12589 static int nested_vmx_check_vmcs_link_ptr(struct kvm_vcpu *vcpu,
12590 struct vmcs12 *vmcs12)
12592 int r;
12593 struct page *page;
12594 struct vmcs12 *shadow;
12596 if (vmcs12->vmcs_link_pointer == -1ull)
12597 return 0;
12599 if (!page_address_valid(vcpu, vmcs12->vmcs_link_pointer))
12600 return -EINVAL;
12602 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->vmcs_link_pointer);
12603 if (is_error_page(page))
12604 return -EINVAL;
12606 r = 0;
12607 shadow = kmap(page);
12608 if (shadow->hdr.revision_id != VMCS12_REVISION ||
12609 shadow->hdr.shadow_vmcs != nested_cpu_has_shadow_vmcs(vmcs12))
12610 r = -EINVAL;
12611 kunmap(page);
12612 kvm_release_page_clean(page);
12613 return r;
12616 static int check_vmentry_postreqs(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
12617 u32 *exit_qual)
12619 bool ia32e;
12621 *exit_qual = ENTRY_FAIL_DEFAULT;
12623 if (!nested_guest_cr0_valid(vcpu, vmcs12->guest_cr0) ||
12624 !nested_guest_cr4_valid(vcpu, vmcs12->guest_cr4))
12625 return 1;
12627 if (nested_vmx_check_vmcs_link_ptr(vcpu, vmcs12)) {
12628 *exit_qual = ENTRY_FAIL_VMCS_LINK_PTR;
12629 return 1;
12633 * If the load IA32_EFER VM-entry control is 1, the following checks
12634 * are performed on the field for the IA32_EFER MSR:
12635 * - Bits reserved in the IA32_EFER MSR must be 0.
12636 * - Bit 10 (corresponding to IA32_EFER.LMA) must equal the value of
12637 * the IA-32e mode guest VM-exit control. It must also be identical
12638 * to bit 8 (LME) if bit 31 in the CR0 field (corresponding to
12639 * CR0.PG) is 1.
12641 if (to_vmx(vcpu)->nested.nested_run_pending &&
12642 (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER)) {
12643 ia32e = (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) != 0;
12644 if (!kvm_valid_efer(vcpu, vmcs12->guest_ia32_efer) ||
12645 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LMA) ||
12646 ((vmcs12->guest_cr0 & X86_CR0_PG) &&
12647 ia32e != !!(vmcs12->guest_ia32_efer & EFER_LME)))
12648 return 1;
12652 * If the load IA32_EFER VM-exit control is 1, bits reserved in the
12653 * IA32_EFER MSR must be 0 in the field for that register. In addition,
12654 * the values of the LMA and LME bits in the field must each be that of
12655 * the host address-space size VM-exit control.
12657 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) {
12658 ia32e = (vmcs12->vm_exit_controls &
12659 VM_EXIT_HOST_ADDR_SPACE_SIZE) != 0;
12660 if (!kvm_valid_efer(vcpu, vmcs12->host_ia32_efer) ||
12661 ia32e != !!(vmcs12->host_ia32_efer & EFER_LMA) ||
12662 ia32e != !!(vmcs12->host_ia32_efer & EFER_LME))
12663 return 1;
12666 if ((vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS) &&
12667 (is_noncanonical_address(vmcs12->guest_bndcfgs & PAGE_MASK, vcpu) ||
12668 (vmcs12->guest_bndcfgs & MSR_IA32_BNDCFGS_RSVD)))
12669 return 1;
12671 return 0;
12675 * If exit_qual is NULL, this is being called from state restore (either RSM
12676 * or KVM_SET_NESTED_STATE). Otherwise it's called from vmlaunch/vmresume.
12678 static int enter_vmx_non_root_mode(struct kvm_vcpu *vcpu, u32 *exit_qual)
12680 struct vcpu_vmx *vmx = to_vmx(vcpu);
12681 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
12682 bool from_vmentry = !!exit_qual;
12683 u32 dummy_exit_qual;
12684 bool evaluate_pending_interrupts;
12685 int r = 0;
12687 evaluate_pending_interrupts = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL) &
12688 (CPU_BASED_VIRTUAL_INTR_PENDING | CPU_BASED_VIRTUAL_NMI_PENDING);
12689 if (likely(!evaluate_pending_interrupts) && kvm_vcpu_apicv_active(vcpu))
12690 evaluate_pending_interrupts |= vmx_has_apicv_interrupt(vcpu);
12692 enter_guest_mode(vcpu);
12694 if (!(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS))
12695 vmx->nested.vmcs01_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
12696 if (kvm_mpx_supported() &&
12697 !(vmcs12->vm_entry_controls & VM_ENTRY_LOAD_BNDCFGS))
12698 vmx->nested.vmcs01_guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
12700 vmx_switch_vmcs(vcpu, &vmx->nested.vmcs02);
12701 vmx_segment_cache_clear(vmx);
12703 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12704 vcpu->arch.tsc_offset += vmcs12->tsc_offset;
12706 r = EXIT_REASON_INVALID_STATE;
12707 if (prepare_vmcs02(vcpu, vmcs12, from_vmentry ? exit_qual : &dummy_exit_qual))
12708 goto fail;
12710 if (from_vmentry) {
12711 nested_get_vmcs12_pages(vcpu);
12713 r = EXIT_REASON_MSR_LOAD_FAIL;
12714 *exit_qual = nested_vmx_load_msr(vcpu,
12715 vmcs12->vm_entry_msr_load_addr,
12716 vmcs12->vm_entry_msr_load_count);
12717 if (*exit_qual)
12718 goto fail;
12719 } else {
12721 * The MMU is not initialized to point at the right entities yet and
12722 * "get pages" would need to read data from the guest (i.e. we will
12723 * need to perform gpa to hpa translation). Request a call
12724 * to nested_get_vmcs12_pages before the next VM-entry. The MSRs
12725 * have already been set at vmentry time and should not be reset.
12727 kvm_make_request(KVM_REQ_GET_VMCS12_PAGES, vcpu);
12731 * If L1 had a pending IRQ/NMI until it executed
12732 * VMLAUNCH/VMRESUME which wasn't delivered because it was
12733 * disallowed (e.g. interrupts disabled), L0 needs to
12734 * evaluate if this pending event should cause an exit from L2
12735 * to L1 or delivered directly to L2 (e.g. In case L1 don't
12736 * intercept EXTERNAL_INTERRUPT).
12738 * Usually this would be handled by the processor noticing an
12739 * IRQ/NMI window request, or checking RVI during evaluation of
12740 * pending virtual interrupts. However, this setting was done
12741 * on VMCS01 and now VMCS02 is active instead. Thus, we force L0
12742 * to perform pending event evaluation by requesting a KVM_REQ_EVENT.
12744 if (unlikely(evaluate_pending_interrupts))
12745 kvm_make_request(KVM_REQ_EVENT, vcpu);
12748 * Note no nested_vmx_succeed or nested_vmx_fail here. At this point
12749 * we are no longer running L1, and VMLAUNCH/VMRESUME has not yet
12750 * returned as far as L1 is concerned. It will only return (and set
12751 * the success flag) when L2 exits (see nested_vmx_vmexit()).
12753 return 0;
12755 fail:
12756 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
12757 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
12758 leave_guest_mode(vcpu);
12759 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
12760 return r;
12764 * nested_vmx_run() handles a nested entry, i.e., a VMLAUNCH or VMRESUME on L1
12765 * for running an L2 nested guest.
12767 static int nested_vmx_run(struct kvm_vcpu *vcpu, bool launch)
12769 struct vmcs12 *vmcs12;
12770 struct vcpu_vmx *vmx = to_vmx(vcpu);
12771 u32 interrupt_shadow = vmx_get_interrupt_shadow(vcpu);
12772 u32 exit_qual;
12773 int ret;
12775 if (!nested_vmx_check_permission(vcpu))
12776 return 1;
12778 if (!nested_vmx_check_vmcs12(vcpu))
12779 goto out;
12781 vmcs12 = get_vmcs12(vcpu);
12784 * Can't VMLAUNCH or VMRESUME a shadow VMCS. Despite the fact
12785 * that there *is* a valid VMCS pointer, RFLAGS.CF is set
12786 * rather than RFLAGS.ZF, and no error number is stored to the
12787 * VM-instruction error field.
12789 if (vmcs12->hdr.shadow_vmcs) {
12790 nested_vmx_failInvalid(vcpu);
12791 goto out;
12794 if (enable_shadow_vmcs)
12795 copy_shadow_to_vmcs12(vmx);
12798 * The nested entry process starts with enforcing various prerequisites
12799 * on vmcs12 as required by the Intel SDM, and act appropriately when
12800 * they fail: As the SDM explains, some conditions should cause the
12801 * instruction to fail, while others will cause the instruction to seem
12802 * to succeed, but return an EXIT_REASON_INVALID_STATE.
12803 * To speed up the normal (success) code path, we should avoid checking
12804 * for misconfigurations which will anyway be caught by the processor
12805 * when using the merged vmcs02.
12807 if (interrupt_shadow & KVM_X86_SHADOW_INT_MOV_SS) {
12808 nested_vmx_failValid(vcpu,
12809 VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS);
12810 goto out;
12813 if (vmcs12->launch_state == launch) {
12814 nested_vmx_failValid(vcpu,
12815 launch ? VMXERR_VMLAUNCH_NONCLEAR_VMCS
12816 : VMXERR_VMRESUME_NONLAUNCHED_VMCS);
12817 goto out;
12820 ret = check_vmentry_prereqs(vcpu, vmcs12);
12821 if (ret) {
12822 nested_vmx_failValid(vcpu, ret);
12823 goto out;
12827 * After this point, the trap flag no longer triggers a singlestep trap
12828 * on the vm entry instructions; don't call kvm_skip_emulated_instruction.
12829 * This is not 100% correct; for performance reasons, we delegate most
12830 * of the checks on host state to the processor. If those fail,
12831 * the singlestep trap is missed.
12833 skip_emulated_instruction(vcpu);
12835 ret = check_vmentry_postreqs(vcpu, vmcs12, &exit_qual);
12836 if (ret) {
12837 nested_vmx_entry_failure(vcpu, vmcs12,
12838 EXIT_REASON_INVALID_STATE, exit_qual);
12839 return 1;
12843 * We're finally done with prerequisite checking, and can start with
12844 * the nested entry.
12847 vmx->nested.nested_run_pending = 1;
12848 ret = enter_vmx_non_root_mode(vcpu, &exit_qual);
12849 if (ret) {
12850 nested_vmx_entry_failure(vcpu, vmcs12, ret, exit_qual);
12851 vmx->nested.nested_run_pending = 0;
12852 return 1;
12855 /* Hide L1D cache contents from the nested guest. */
12856 vmx->vcpu.arch.l1tf_flush_l1d = true;
12859 * Must happen outside of enter_vmx_non_root_mode() as it will
12860 * also be used as part of restoring nVMX state for
12861 * snapshot restore (migration).
12863 * In this flow, it is assumed that vmcs12 cache was
12864 * trasferred as part of captured nVMX state and should
12865 * therefore not be read from guest memory (which may not
12866 * exist on destination host yet).
12868 nested_cache_shadow_vmcs12(vcpu, vmcs12);
12871 * If we're entering a halted L2 vcpu and the L2 vcpu won't be
12872 * awakened by event injection or by an NMI-window VM-exit or
12873 * by an interrupt-window VM-exit, halt the vcpu.
12875 if ((vmcs12->guest_activity_state == GUEST_ACTIVITY_HLT) &&
12876 !(vmcs12->vm_entry_intr_info_field & INTR_INFO_VALID_MASK) &&
12877 !(vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_NMI_PENDING) &&
12878 !((vmcs12->cpu_based_vm_exec_control & CPU_BASED_VIRTUAL_INTR_PENDING) &&
12879 (vmcs12->guest_rflags & X86_EFLAGS_IF))) {
12880 vmx->nested.nested_run_pending = 0;
12881 return kvm_vcpu_halt(vcpu);
12883 return 1;
12885 out:
12886 return kvm_skip_emulated_instruction(vcpu);
12890 * On a nested exit from L2 to L1, vmcs12.guest_cr0 might not be up-to-date
12891 * because L2 may have changed some cr0 bits directly (CRO_GUEST_HOST_MASK).
12892 * This function returns the new value we should put in vmcs12.guest_cr0.
12893 * It's not enough to just return the vmcs02 GUEST_CR0. Rather,
12894 * 1. Bits that neither L0 nor L1 trapped, were set directly by L2 and are now
12895 * available in vmcs02 GUEST_CR0. (Note: It's enough to check that L0
12896 * didn't trap the bit, because if L1 did, so would L0).
12897 * 2. Bits that L1 asked to trap (and therefore L0 also did) could not have
12898 * been modified by L2, and L1 knows it. So just leave the old value of
12899 * the bit from vmcs12.guest_cr0. Note that the bit from vmcs02 GUEST_CR0
12900 * isn't relevant, because if L0 traps this bit it can set it to anything.
12901 * 3. Bits that L1 didn't trap, but L0 did. L1 believes the guest could have
12902 * changed these bits, and therefore they need to be updated, but L0
12903 * didn't necessarily allow them to be changed in GUEST_CR0 - and rather
12904 * put them in vmcs02 CR0_READ_SHADOW. So take these bits from there.
12906 static inline unsigned long
12907 vmcs12_guest_cr0(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12909 return
12910 /*1*/ (vmcs_readl(GUEST_CR0) & vcpu->arch.cr0_guest_owned_bits) |
12911 /*2*/ (vmcs12->guest_cr0 & vmcs12->cr0_guest_host_mask) |
12912 /*3*/ (vmcs_readl(CR0_READ_SHADOW) & ~(vmcs12->cr0_guest_host_mask |
12913 vcpu->arch.cr0_guest_owned_bits));
12916 static inline unsigned long
12917 vmcs12_guest_cr4(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
12919 return
12920 /*1*/ (vmcs_readl(GUEST_CR4) & vcpu->arch.cr4_guest_owned_bits) |
12921 /*2*/ (vmcs12->guest_cr4 & vmcs12->cr4_guest_host_mask) |
12922 /*3*/ (vmcs_readl(CR4_READ_SHADOW) & ~(vmcs12->cr4_guest_host_mask |
12923 vcpu->arch.cr4_guest_owned_bits));
12926 static void vmcs12_save_pending_event(struct kvm_vcpu *vcpu,
12927 struct vmcs12 *vmcs12)
12929 u32 idt_vectoring;
12930 unsigned int nr;
12932 if (vcpu->arch.exception.injected) {
12933 nr = vcpu->arch.exception.nr;
12934 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12936 if (kvm_exception_is_soft(nr)) {
12937 vmcs12->vm_exit_instruction_len =
12938 vcpu->arch.event_exit_inst_len;
12939 idt_vectoring |= INTR_TYPE_SOFT_EXCEPTION;
12940 } else
12941 idt_vectoring |= INTR_TYPE_HARD_EXCEPTION;
12943 if (vcpu->arch.exception.has_error_code) {
12944 idt_vectoring |= VECTORING_INFO_DELIVER_CODE_MASK;
12945 vmcs12->idt_vectoring_error_code =
12946 vcpu->arch.exception.error_code;
12949 vmcs12->idt_vectoring_info_field = idt_vectoring;
12950 } else if (vcpu->arch.nmi_injected) {
12951 vmcs12->idt_vectoring_info_field =
12952 INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK | NMI_VECTOR;
12953 } else if (vcpu->arch.interrupt.injected) {
12954 nr = vcpu->arch.interrupt.nr;
12955 idt_vectoring = nr | VECTORING_INFO_VALID_MASK;
12957 if (vcpu->arch.interrupt.soft) {
12958 idt_vectoring |= INTR_TYPE_SOFT_INTR;
12959 vmcs12->vm_entry_instruction_len =
12960 vcpu->arch.event_exit_inst_len;
12961 } else
12962 idt_vectoring |= INTR_TYPE_EXT_INTR;
12964 vmcs12->idt_vectoring_info_field = idt_vectoring;
12968 static int vmx_check_nested_events(struct kvm_vcpu *vcpu, bool external_intr)
12970 struct vcpu_vmx *vmx = to_vmx(vcpu);
12971 unsigned long exit_qual;
12972 bool block_nested_events =
12973 vmx->nested.nested_run_pending || kvm_event_needs_reinjection(vcpu);
12975 if (vcpu->arch.exception.pending &&
12976 nested_vmx_check_exception(vcpu, &exit_qual)) {
12977 if (block_nested_events)
12978 return -EBUSY;
12979 nested_vmx_inject_exception_vmexit(vcpu, exit_qual);
12980 return 0;
12983 if (nested_cpu_has_preemption_timer(get_vmcs12(vcpu)) &&
12984 vmx->nested.preemption_timer_expired) {
12985 if (block_nested_events)
12986 return -EBUSY;
12987 nested_vmx_vmexit(vcpu, EXIT_REASON_PREEMPTION_TIMER, 0, 0);
12988 return 0;
12991 if (vcpu->arch.nmi_pending && nested_exit_on_nmi(vcpu)) {
12992 if (block_nested_events)
12993 return -EBUSY;
12994 nested_vmx_vmexit(vcpu, EXIT_REASON_EXCEPTION_NMI,
12995 NMI_VECTOR | INTR_TYPE_NMI_INTR |
12996 INTR_INFO_VALID_MASK, 0);
12998 * The NMI-triggered VM exit counts as injection:
12999 * clear this one and block further NMIs.
13001 vcpu->arch.nmi_pending = 0;
13002 vmx_set_nmi_mask(vcpu, true);
13003 return 0;
13006 if ((kvm_cpu_has_interrupt(vcpu) || external_intr) &&
13007 nested_exit_on_intr(vcpu)) {
13008 if (block_nested_events)
13009 return -EBUSY;
13010 nested_vmx_vmexit(vcpu, EXIT_REASON_EXTERNAL_INTERRUPT, 0, 0);
13011 return 0;
13014 vmx_complete_nested_posted_interrupt(vcpu);
13015 return 0;
13018 static void vmx_request_immediate_exit(struct kvm_vcpu *vcpu)
13020 to_vmx(vcpu)->req_immediate_exit = true;
13023 static u32 vmx_get_preemption_timer_value(struct kvm_vcpu *vcpu)
13025 ktime_t remaining =
13026 hrtimer_get_remaining(&to_vmx(vcpu)->nested.preemption_timer);
13027 u64 value;
13029 if (ktime_to_ns(remaining) <= 0)
13030 return 0;
13032 value = ktime_to_ns(remaining) * vcpu->arch.virtual_tsc_khz;
13033 do_div(value, 1000000);
13034 return value >> VMX_MISC_EMULATED_PREEMPTION_TIMER_RATE;
13038 * Update the guest state fields of vmcs12 to reflect changes that
13039 * occurred while L2 was running. (The "IA-32e mode guest" bit of the
13040 * VM-entry controls is also updated, since this is really a guest
13041 * state bit.)
13043 static void sync_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12)
13045 vmcs12->guest_cr0 = vmcs12_guest_cr0(vcpu, vmcs12);
13046 vmcs12->guest_cr4 = vmcs12_guest_cr4(vcpu, vmcs12);
13048 vmcs12->guest_rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
13049 vmcs12->guest_rip = kvm_register_read(vcpu, VCPU_REGS_RIP);
13050 vmcs12->guest_rflags = vmcs_readl(GUEST_RFLAGS);
13052 vmcs12->guest_es_selector = vmcs_read16(GUEST_ES_SELECTOR);
13053 vmcs12->guest_cs_selector = vmcs_read16(GUEST_CS_SELECTOR);
13054 vmcs12->guest_ss_selector = vmcs_read16(GUEST_SS_SELECTOR);
13055 vmcs12->guest_ds_selector = vmcs_read16(GUEST_DS_SELECTOR);
13056 vmcs12->guest_fs_selector = vmcs_read16(GUEST_FS_SELECTOR);
13057 vmcs12->guest_gs_selector = vmcs_read16(GUEST_GS_SELECTOR);
13058 vmcs12->guest_ldtr_selector = vmcs_read16(GUEST_LDTR_SELECTOR);
13059 vmcs12->guest_tr_selector = vmcs_read16(GUEST_TR_SELECTOR);
13060 vmcs12->guest_es_limit = vmcs_read32(GUEST_ES_LIMIT);
13061 vmcs12->guest_cs_limit = vmcs_read32(GUEST_CS_LIMIT);
13062 vmcs12->guest_ss_limit = vmcs_read32(GUEST_SS_LIMIT);
13063 vmcs12->guest_ds_limit = vmcs_read32(GUEST_DS_LIMIT);
13064 vmcs12->guest_fs_limit = vmcs_read32(GUEST_FS_LIMIT);
13065 vmcs12->guest_gs_limit = vmcs_read32(GUEST_GS_LIMIT);
13066 vmcs12->guest_ldtr_limit = vmcs_read32(GUEST_LDTR_LIMIT);
13067 vmcs12->guest_tr_limit = vmcs_read32(GUEST_TR_LIMIT);
13068 vmcs12->guest_gdtr_limit = vmcs_read32(GUEST_GDTR_LIMIT);
13069 vmcs12->guest_idtr_limit = vmcs_read32(GUEST_IDTR_LIMIT);
13070 vmcs12->guest_es_ar_bytes = vmcs_read32(GUEST_ES_AR_BYTES);
13071 vmcs12->guest_cs_ar_bytes = vmcs_read32(GUEST_CS_AR_BYTES);
13072 vmcs12->guest_ss_ar_bytes = vmcs_read32(GUEST_SS_AR_BYTES);
13073 vmcs12->guest_ds_ar_bytes = vmcs_read32(GUEST_DS_AR_BYTES);
13074 vmcs12->guest_fs_ar_bytes = vmcs_read32(GUEST_FS_AR_BYTES);
13075 vmcs12->guest_gs_ar_bytes = vmcs_read32(GUEST_GS_AR_BYTES);
13076 vmcs12->guest_ldtr_ar_bytes = vmcs_read32(GUEST_LDTR_AR_BYTES);
13077 vmcs12->guest_tr_ar_bytes = vmcs_read32(GUEST_TR_AR_BYTES);
13078 vmcs12->guest_es_base = vmcs_readl(GUEST_ES_BASE);
13079 vmcs12->guest_cs_base = vmcs_readl(GUEST_CS_BASE);
13080 vmcs12->guest_ss_base = vmcs_readl(GUEST_SS_BASE);
13081 vmcs12->guest_ds_base = vmcs_readl(GUEST_DS_BASE);
13082 vmcs12->guest_fs_base = vmcs_readl(GUEST_FS_BASE);
13083 vmcs12->guest_gs_base = vmcs_readl(GUEST_GS_BASE);
13084 vmcs12->guest_ldtr_base = vmcs_readl(GUEST_LDTR_BASE);
13085 vmcs12->guest_tr_base = vmcs_readl(GUEST_TR_BASE);
13086 vmcs12->guest_gdtr_base = vmcs_readl(GUEST_GDTR_BASE);
13087 vmcs12->guest_idtr_base = vmcs_readl(GUEST_IDTR_BASE);
13089 vmcs12->guest_interruptibility_info =
13090 vmcs_read32(GUEST_INTERRUPTIBILITY_INFO);
13091 vmcs12->guest_pending_dbg_exceptions =
13092 vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS);
13093 if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED)
13094 vmcs12->guest_activity_state = GUEST_ACTIVITY_HLT;
13095 else
13096 vmcs12->guest_activity_state = GUEST_ACTIVITY_ACTIVE;
13098 if (nested_cpu_has_preemption_timer(vmcs12)) {
13099 if (vmcs12->vm_exit_controls &
13100 VM_EXIT_SAVE_VMX_PREEMPTION_TIMER)
13101 vmcs12->vmx_preemption_timer_value =
13102 vmx_get_preemption_timer_value(vcpu);
13103 hrtimer_cancel(&to_vmx(vcpu)->nested.preemption_timer);
13107 * In some cases (usually, nested EPT), L2 is allowed to change its
13108 * own CR3 without exiting. If it has changed it, we must keep it.
13109 * Of course, if L0 is using shadow page tables, GUEST_CR3 was defined
13110 * by L0, not L1 or L2, so we mustn't unconditionally copy it to vmcs12.
13112 * Additionally, restore L2's PDPTR to vmcs12.
13114 if (enable_ept) {
13115 vmcs12->guest_cr3 = vmcs_readl(GUEST_CR3);
13116 vmcs12->guest_pdptr0 = vmcs_read64(GUEST_PDPTR0);
13117 vmcs12->guest_pdptr1 = vmcs_read64(GUEST_PDPTR1);
13118 vmcs12->guest_pdptr2 = vmcs_read64(GUEST_PDPTR2);
13119 vmcs12->guest_pdptr3 = vmcs_read64(GUEST_PDPTR3);
13122 vmcs12->guest_linear_address = vmcs_readl(GUEST_LINEAR_ADDRESS);
13124 if (nested_cpu_has_vid(vmcs12))
13125 vmcs12->guest_intr_status = vmcs_read16(GUEST_INTR_STATUS);
13127 vmcs12->vm_entry_controls =
13128 (vmcs12->vm_entry_controls & ~VM_ENTRY_IA32E_MODE) |
13129 (vm_entry_controls_get(to_vmx(vcpu)) & VM_ENTRY_IA32E_MODE);
13131 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_DEBUG_CONTROLS) {
13132 kvm_get_dr(vcpu, 7, (unsigned long *)&vmcs12->guest_dr7);
13133 vmcs12->guest_ia32_debugctl = vmcs_read64(GUEST_IA32_DEBUGCTL);
13136 /* TODO: These cannot have changed unless we have MSR bitmaps and
13137 * the relevant bit asks not to trap the change */
13138 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_PAT)
13139 vmcs12->guest_ia32_pat = vmcs_read64(GUEST_IA32_PAT);
13140 if (vmcs12->vm_exit_controls & VM_EXIT_SAVE_IA32_EFER)
13141 vmcs12->guest_ia32_efer = vcpu->arch.efer;
13142 vmcs12->guest_sysenter_cs = vmcs_read32(GUEST_SYSENTER_CS);
13143 vmcs12->guest_sysenter_esp = vmcs_readl(GUEST_SYSENTER_ESP);
13144 vmcs12->guest_sysenter_eip = vmcs_readl(GUEST_SYSENTER_EIP);
13145 if (kvm_mpx_supported())
13146 vmcs12->guest_bndcfgs = vmcs_read64(GUEST_BNDCFGS);
13150 * prepare_vmcs12 is part of what we need to do when the nested L2 guest exits
13151 * and we want to prepare to run its L1 parent. L1 keeps a vmcs for L2 (vmcs12),
13152 * and this function updates it to reflect the changes to the guest state while
13153 * L2 was running (and perhaps made some exits which were handled directly by L0
13154 * without going back to L1), and to reflect the exit reason.
13155 * Note that we do not have to copy here all VMCS fields, just those that
13156 * could have changed by the L2 guest or the exit - i.e., the guest-state and
13157 * exit-information fields only. Other fields are modified by L1 with VMWRITE,
13158 * which already writes to vmcs12 directly.
13160 static void prepare_vmcs12(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12,
13161 u32 exit_reason, u32 exit_intr_info,
13162 unsigned long exit_qualification)
13164 /* update guest state fields: */
13165 sync_vmcs12(vcpu, vmcs12);
13167 /* update exit information fields: */
13169 vmcs12->vm_exit_reason = exit_reason;
13170 vmcs12->exit_qualification = exit_qualification;
13171 vmcs12->vm_exit_intr_info = exit_intr_info;
13173 vmcs12->idt_vectoring_info_field = 0;
13174 vmcs12->vm_exit_instruction_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN);
13175 vmcs12->vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
13177 if (!(vmcs12->vm_exit_reason & VMX_EXIT_REASONS_FAILED_VMENTRY)) {
13178 vmcs12->launch_state = 1;
13180 /* vm_entry_intr_info_field is cleared on exit. Emulate this
13181 * instead of reading the real value. */
13182 vmcs12->vm_entry_intr_info_field &= ~INTR_INFO_VALID_MASK;
13185 * Transfer the event that L0 or L1 may wanted to inject into
13186 * L2 to IDT_VECTORING_INFO_FIELD.
13188 vmcs12_save_pending_event(vcpu, vmcs12);
13192 * Drop what we picked up for L2 via vmx_complete_interrupts. It is
13193 * preserved above and would only end up incorrectly in L1.
13195 vcpu->arch.nmi_injected = false;
13196 kvm_clear_exception_queue(vcpu);
13197 kvm_clear_interrupt_queue(vcpu);
13201 * A part of what we need to when the nested L2 guest exits and we want to
13202 * run its L1 parent, is to reset L1's guest state to the host state specified
13203 * in vmcs12.
13204 * This function is to be called not only on normal nested exit, but also on
13205 * a nested entry failure, as explained in Intel's spec, 3B.23.7 ("VM-Entry
13206 * Failures During or After Loading Guest State").
13207 * This function should be called when the active VMCS is L1's (vmcs01).
13209 static void load_vmcs12_host_state(struct kvm_vcpu *vcpu,
13210 struct vmcs12 *vmcs12)
13212 struct kvm_segment seg;
13213 u32 entry_failure_code;
13215 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER)
13216 vcpu->arch.efer = vmcs12->host_ia32_efer;
13217 else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13218 vcpu->arch.efer |= (EFER_LMA | EFER_LME);
13219 else
13220 vcpu->arch.efer &= ~(EFER_LMA | EFER_LME);
13221 vmx_set_efer(vcpu, vcpu->arch.efer);
13223 kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp);
13224 kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip);
13225 vmx_set_rflags(vcpu, X86_EFLAGS_FIXED);
13227 * Note that calling vmx_set_cr0 is important, even if cr0 hasn't
13228 * actually changed, because vmx_set_cr0 refers to efer set above.
13230 * CR0_GUEST_HOST_MASK is already set in the original vmcs01
13231 * (KVM doesn't change it);
13233 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13234 vmx_set_cr0(vcpu, vmcs12->host_cr0);
13236 /* Same as above - no reason to call set_cr4_guest_host_mask(). */
13237 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13238 vmx_set_cr4(vcpu, vmcs12->host_cr4);
13240 nested_ept_uninit_mmu_context(vcpu);
13243 * Only PDPTE load can fail as the value of cr3 was checked on entry and
13244 * couldn't have changed.
13246 if (nested_vmx_load_cr3(vcpu, vmcs12->host_cr3, false, &entry_failure_code))
13247 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_PDPTE_FAIL);
13249 if (!enable_ept)
13250 vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
13253 * If vmcs01 don't use VPID, CPU flushes TLB on every
13254 * VMEntry/VMExit. Thus, no need to flush TLB.
13256 * If vmcs12 uses VPID, TLB entries populated by L2 are
13257 * tagged with vmx->nested.vpid02 while L1 entries are tagged
13258 * with vmx->vpid. Thus, no need to flush TLB.
13260 * Therefore, flush TLB only in case vmcs01 uses VPID and
13261 * vmcs12 don't use VPID as in this case L1 & L2 TLB entries
13262 * are both tagged with vmx->vpid.
13264 if (enable_vpid &&
13265 !(nested_cpu_has_vpid(vmcs12) && to_vmx(vcpu)->nested.vpid02)) {
13266 vmx_flush_tlb(vcpu, true);
13269 vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs);
13270 vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp);
13271 vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip);
13272 vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base);
13273 vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base);
13274 vmcs_write32(GUEST_IDTR_LIMIT, 0xFFFF);
13275 vmcs_write32(GUEST_GDTR_LIMIT, 0xFFFF);
13277 /* If not VM_EXIT_CLEAR_BNDCFGS, the L2 value propagates to L1. */
13278 if (vmcs12->vm_exit_controls & VM_EXIT_CLEAR_BNDCFGS)
13279 vmcs_write64(GUEST_BNDCFGS, 0);
13281 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) {
13282 vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat);
13283 vcpu->arch.pat = vmcs12->host_ia32_pat;
13285 if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL)
13286 vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL,
13287 vmcs12->host_ia32_perf_global_ctrl);
13289 /* Set L1 segment info according to Intel SDM
13290 27.5.2 Loading Host Segment and Descriptor-Table Registers */
13291 seg = (struct kvm_segment) {
13292 .base = 0,
13293 .limit = 0xFFFFFFFF,
13294 .selector = vmcs12->host_cs_selector,
13295 .type = 11,
13296 .present = 1,
13297 .s = 1,
13298 .g = 1
13300 if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE)
13301 seg.l = 1;
13302 else
13303 seg.db = 1;
13304 vmx_set_segment(vcpu, &seg, VCPU_SREG_CS);
13305 seg = (struct kvm_segment) {
13306 .base = 0,
13307 .limit = 0xFFFFFFFF,
13308 .type = 3,
13309 .present = 1,
13310 .s = 1,
13311 .db = 1,
13312 .g = 1
13314 seg.selector = vmcs12->host_ds_selector;
13315 vmx_set_segment(vcpu, &seg, VCPU_SREG_DS);
13316 seg.selector = vmcs12->host_es_selector;
13317 vmx_set_segment(vcpu, &seg, VCPU_SREG_ES);
13318 seg.selector = vmcs12->host_ss_selector;
13319 vmx_set_segment(vcpu, &seg, VCPU_SREG_SS);
13320 seg.selector = vmcs12->host_fs_selector;
13321 seg.base = vmcs12->host_fs_base;
13322 vmx_set_segment(vcpu, &seg, VCPU_SREG_FS);
13323 seg.selector = vmcs12->host_gs_selector;
13324 seg.base = vmcs12->host_gs_base;
13325 vmx_set_segment(vcpu, &seg, VCPU_SREG_GS);
13326 seg = (struct kvm_segment) {
13327 .base = vmcs12->host_tr_base,
13328 .limit = 0x67,
13329 .selector = vmcs12->host_tr_selector,
13330 .type = 11,
13331 .present = 1
13333 vmx_set_segment(vcpu, &seg, VCPU_SREG_TR);
13335 kvm_set_dr(vcpu, 7, 0x400);
13336 vmcs_write64(GUEST_IA32_DEBUGCTL, 0);
13338 if (cpu_has_vmx_msr_bitmap())
13339 vmx_update_msr_bitmap(vcpu);
13341 if (nested_vmx_load_msr(vcpu, vmcs12->vm_exit_msr_load_addr,
13342 vmcs12->vm_exit_msr_load_count))
13343 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13346 static inline u64 nested_vmx_get_vmcs01_guest_efer(struct vcpu_vmx *vmx)
13348 struct shared_msr_entry *efer_msr;
13349 unsigned int i;
13351 if (vm_entry_controls_get(vmx) & VM_ENTRY_LOAD_IA32_EFER)
13352 return vmcs_read64(GUEST_IA32_EFER);
13354 if (cpu_has_load_ia32_efer)
13355 return host_efer;
13357 for (i = 0; i < vmx->msr_autoload.guest.nr; ++i) {
13358 if (vmx->msr_autoload.guest.val[i].index == MSR_EFER)
13359 return vmx->msr_autoload.guest.val[i].value;
13362 efer_msr = find_msr_entry(vmx, MSR_EFER);
13363 if (efer_msr)
13364 return efer_msr->data;
13366 return host_efer;
13369 static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
13371 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13372 struct vcpu_vmx *vmx = to_vmx(vcpu);
13373 struct vmx_msr_entry g, h;
13374 struct msr_data msr;
13375 gpa_t gpa;
13376 u32 i, j;
13378 vcpu->arch.pat = vmcs_read64(GUEST_IA32_PAT);
13380 if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_DEBUG_CONTROLS) {
13382 * L1's host DR7 is lost if KVM_GUESTDBG_USE_HW_BP is set
13383 * as vmcs01.GUEST_DR7 contains a userspace defined value
13384 * and vcpu->arch.dr7 is not squirreled away before the
13385 * nested VMENTER (not worth adding a variable in nested_vmx).
13387 if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
13388 kvm_set_dr(vcpu, 7, DR7_FIXED_1);
13389 else
13390 WARN_ON(kvm_set_dr(vcpu, 7, vmcs_readl(GUEST_DR7)));
13394 * Note that calling vmx_set_{efer,cr0,cr4} is important as they
13395 * handle a variety of side effects to KVM's software model.
13397 vmx_set_efer(vcpu, nested_vmx_get_vmcs01_guest_efer(vmx));
13399 vcpu->arch.cr0_guest_owned_bits = X86_CR0_TS;
13400 vmx_set_cr0(vcpu, vmcs_readl(CR0_READ_SHADOW));
13402 vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK);
13403 vmx_set_cr4(vcpu, vmcs_readl(CR4_READ_SHADOW));
13405 nested_ept_uninit_mmu_context(vcpu);
13406 vcpu->arch.cr3 = vmcs_readl(GUEST_CR3);
13407 __set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
13410 * Use ept_save_pdptrs(vcpu) to load the MMU's cached PDPTRs
13411 * from vmcs01 (if necessary). The PDPTRs are not loaded on
13412 * VMFail, like everything else we just need to ensure our
13413 * software model is up-to-date.
13415 ept_save_pdptrs(vcpu);
13417 kvm_mmu_reset_context(vcpu);
13419 if (cpu_has_vmx_msr_bitmap())
13420 vmx_update_msr_bitmap(vcpu);
13423 * This nasty bit of open coding is a compromise between blindly
13424 * loading L1's MSRs using the exit load lists (incorrect emulation
13425 * of VMFail), leaving the nested VM's MSRs in the software model
13426 * (incorrect behavior) and snapshotting the modified MSRs (too
13427 * expensive since the lists are unbound by hardware). For each
13428 * MSR that was (prematurely) loaded from the nested VMEntry load
13429 * list, reload it from the exit load list if it exists and differs
13430 * from the guest value. The intent is to stuff host state as
13431 * silently as possible, not to fully process the exit load list.
13433 msr.host_initiated = false;
13434 for (i = 0; i < vmcs12->vm_entry_msr_load_count; i++) {
13435 gpa = vmcs12->vm_entry_msr_load_addr + (i * sizeof(g));
13436 if (kvm_vcpu_read_guest(vcpu, gpa, &g, sizeof(g))) {
13437 pr_debug_ratelimited(
13438 "%s read MSR index failed (%u, 0x%08llx)\n",
13439 __func__, i, gpa);
13440 goto vmabort;
13443 for (j = 0; j < vmcs12->vm_exit_msr_load_count; j++) {
13444 gpa = vmcs12->vm_exit_msr_load_addr + (j * sizeof(h));
13445 if (kvm_vcpu_read_guest(vcpu, gpa, &h, sizeof(h))) {
13446 pr_debug_ratelimited(
13447 "%s read MSR failed (%u, 0x%08llx)\n",
13448 __func__, j, gpa);
13449 goto vmabort;
13451 if (h.index != g.index)
13452 continue;
13453 if (h.value == g.value)
13454 break;
13456 if (nested_vmx_load_msr_check(vcpu, &h)) {
13457 pr_debug_ratelimited(
13458 "%s check failed (%u, 0x%x, 0x%x)\n",
13459 __func__, j, h.index, h.reserved);
13460 goto vmabort;
13463 msr.index = h.index;
13464 msr.data = h.value;
13465 if (kvm_set_msr(vcpu, &msr)) {
13466 pr_debug_ratelimited(
13467 "%s WRMSR failed (%u, 0x%x, 0x%llx)\n",
13468 __func__, j, h.index, h.value);
13469 goto vmabort;
13474 return;
13476 vmabort:
13477 nested_vmx_abort(vcpu, VMX_ABORT_LOAD_HOST_MSR_FAIL);
13481 * Emulate an exit from nested guest (L2) to L1, i.e., prepare to run L1
13482 * and modify vmcs12 to make it see what it would expect to see there if
13483 * L2 was its real guest. Must only be called when in L2 (is_guest_mode())
13485 static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason,
13486 u32 exit_intr_info,
13487 unsigned long exit_qualification)
13489 struct vcpu_vmx *vmx = to_vmx(vcpu);
13490 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13492 /* trying to cancel vmlaunch/vmresume is a bug */
13493 WARN_ON_ONCE(vmx->nested.nested_run_pending);
13496 * The only expected VM-instruction error is "VM entry with
13497 * invalid control field(s)." Anything else indicates a
13498 * problem with L0.
13500 WARN_ON_ONCE(vmx->fail && (vmcs_read32(VM_INSTRUCTION_ERROR) !=
13501 VMXERR_ENTRY_INVALID_CONTROL_FIELD));
13503 leave_guest_mode(vcpu);
13505 if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING)
13506 vcpu->arch.tsc_offset -= vmcs12->tsc_offset;
13508 if (likely(!vmx->fail)) {
13509 if (exit_reason == -1)
13510 sync_vmcs12(vcpu, vmcs12);
13511 else
13512 prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info,
13513 exit_qualification);
13516 * Must happen outside of sync_vmcs12() as it will
13517 * also be used to capture vmcs12 cache as part of
13518 * capturing nVMX state for snapshot (migration).
13520 * Otherwise, this flush will dirty guest memory at a
13521 * point it is already assumed by user-space to be
13522 * immutable.
13524 nested_flush_cached_shadow_vmcs12(vcpu, vmcs12);
13526 if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr,
13527 vmcs12->vm_exit_msr_store_count))
13528 nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL);
13531 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
13532 vm_entry_controls_reset_shadow(vmx);
13533 vm_exit_controls_reset_shadow(vmx);
13534 vmx_segment_cache_clear(vmx);
13536 /* Update any VMCS fields that might have changed while L2 ran */
13537 vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.host.nr);
13538 vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.guest.nr);
13539 vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset);
13541 if (kvm_has_tsc_control)
13542 decache_tsc_multiplier(vmx);
13544 if (vmx->nested.change_vmcs01_virtual_apic_mode) {
13545 vmx->nested.change_vmcs01_virtual_apic_mode = false;
13546 vmx_set_virtual_apic_mode(vcpu);
13547 } else if (!nested_cpu_has_ept(vmcs12) &&
13548 nested_cpu_has2(vmcs12,
13549 SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) {
13550 vmx_flush_tlb(vcpu, true);
13553 /* This is needed for same reason as it was needed in prepare_vmcs02 */
13554 vmx->host_rsp = 0;
13556 /* Unpin physical memory we referred to in vmcs02 */
13557 if (vmx->nested.apic_access_page) {
13558 kvm_release_page_dirty(vmx->nested.apic_access_page);
13559 vmx->nested.apic_access_page = NULL;
13561 if (vmx->nested.virtual_apic_page) {
13562 kvm_release_page_dirty(vmx->nested.virtual_apic_page);
13563 vmx->nested.virtual_apic_page = NULL;
13565 if (vmx->nested.pi_desc_page) {
13566 kunmap(vmx->nested.pi_desc_page);
13567 kvm_release_page_dirty(vmx->nested.pi_desc_page);
13568 vmx->nested.pi_desc_page = NULL;
13569 vmx->nested.pi_desc = NULL;
13573 * We are now running in L2, mmu_notifier will force to reload the
13574 * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1.
13576 kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu);
13578 if (enable_shadow_vmcs && exit_reason != -1)
13579 vmx->nested.sync_shadow_vmcs = true;
13581 /* in case we halted in L2 */
13582 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
13584 if (likely(!vmx->fail)) {
13586 * TODO: SDM says that with acknowledge interrupt on
13587 * exit, bit 31 of the VM-exit interrupt information
13588 * (valid interrupt) is always set to 1 on
13589 * EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't
13590 * need kvm_cpu_has_interrupt(). See the commit
13591 * message for details.
13593 if (nested_exit_intr_ack_set(vcpu) &&
13594 exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT &&
13595 kvm_cpu_has_interrupt(vcpu)) {
13596 int irq = kvm_cpu_get_interrupt(vcpu);
13597 WARN_ON(irq < 0);
13598 vmcs12->vm_exit_intr_info = irq |
13599 INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR;
13602 if (exit_reason != -1)
13603 trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason,
13604 vmcs12->exit_qualification,
13605 vmcs12->idt_vectoring_info_field,
13606 vmcs12->vm_exit_intr_info,
13607 vmcs12->vm_exit_intr_error_code,
13608 KVM_ISA_VMX);
13610 load_vmcs12_host_state(vcpu, vmcs12);
13612 return;
13616 * After an early L2 VM-entry failure, we're now back
13617 * in L1 which thinks it just finished a VMLAUNCH or
13618 * VMRESUME instruction, so we need to set the failure
13619 * flag and the VM-instruction error field of the VMCS
13620 * accordingly.
13622 nested_vmx_failValid(vcpu, VMXERR_ENTRY_INVALID_CONTROL_FIELD);
13625 * Restore L1's host state to KVM's software model. We're here
13626 * because a consistency check was caught by hardware, which
13627 * means some amount of guest state has been propagated to KVM's
13628 * model and needs to be unwound to the host's state.
13630 nested_vmx_restore_host_state(vcpu);
13633 * The emulated instruction was already skipped in
13634 * nested_vmx_run, but the updated RIP was never
13635 * written back to the vmcs01.
13637 skip_emulated_instruction(vcpu);
13638 vmx->fail = 0;
13642 * Forcibly leave nested mode in order to be able to reset the VCPU later on.
13644 static void vmx_leave_nested(struct kvm_vcpu *vcpu)
13646 if (is_guest_mode(vcpu)) {
13647 to_vmx(vcpu)->nested.nested_run_pending = 0;
13648 nested_vmx_vmexit(vcpu, -1, 0, 0);
13650 free_nested(to_vmx(vcpu));
13654 * L1's failure to enter L2 is a subset of a normal exit, as explained in
13655 * 23.7 "VM-entry failures during or after loading guest state" (this also
13656 * lists the acceptable exit-reason and exit-qualification parameters).
13657 * It should only be called before L2 actually succeeded to run, and when
13658 * vmcs01 is current (it doesn't leave_guest_mode() or switch vmcss).
13660 static void nested_vmx_entry_failure(struct kvm_vcpu *vcpu,
13661 struct vmcs12 *vmcs12,
13662 u32 reason, unsigned long qualification)
13664 load_vmcs12_host_state(vcpu, vmcs12);
13665 vmcs12->vm_exit_reason = reason | VMX_EXIT_REASONS_FAILED_VMENTRY;
13666 vmcs12->exit_qualification = qualification;
13667 nested_vmx_succeed(vcpu);
13668 if (enable_shadow_vmcs)
13669 to_vmx(vcpu)->nested.sync_shadow_vmcs = true;
13672 static int vmx_check_intercept(struct kvm_vcpu *vcpu,
13673 struct x86_instruction_info *info,
13674 enum x86_intercept_stage stage)
13676 struct vmcs12 *vmcs12 = get_vmcs12(vcpu);
13677 struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
13680 * RDPID causes #UD if disabled through secondary execution controls.
13681 * Because it is marked as EmulateOnUD, we need to intercept it here.
13683 if (info->intercept == x86_intercept_rdtscp &&
13684 !nested_cpu_has2(vmcs12, SECONDARY_EXEC_RDTSCP)) {
13685 ctxt->exception.vector = UD_VECTOR;
13686 ctxt->exception.error_code_valid = false;
13687 return X86EMUL_PROPAGATE_FAULT;
13690 /* TODO: check more intercepts... */
13691 return X86EMUL_CONTINUE;
13694 #ifdef CONFIG_X86_64
13695 /* (a << shift) / divisor, return 1 if overflow otherwise 0 */
13696 static inline int u64_shl_div_u64(u64 a, unsigned int shift,
13697 u64 divisor, u64 *result)
13699 u64 low = a << shift, high = a >> (64 - shift);
13701 /* To avoid the overflow on divq */
13702 if (high >= divisor)
13703 return 1;
13705 /* Low hold the result, high hold rem which is discarded */
13706 asm("divq %2\n\t" : "=a" (low), "=d" (high) :
13707 "rm" (divisor), "0" (low), "1" (high));
13708 *result = low;
13710 return 0;
13713 static int vmx_set_hv_timer(struct kvm_vcpu *vcpu, u64 guest_deadline_tsc)
13715 struct vcpu_vmx *vmx;
13716 u64 tscl, guest_tscl, delta_tsc, lapic_timer_advance_cycles;
13718 if (kvm_mwait_in_guest(vcpu->kvm))
13719 return -EOPNOTSUPP;
13721 vmx = to_vmx(vcpu);
13722 tscl = rdtsc();
13723 guest_tscl = kvm_read_l1_tsc(vcpu, tscl);
13724 delta_tsc = max(guest_deadline_tsc, guest_tscl) - guest_tscl;
13725 lapic_timer_advance_cycles = nsec_to_cycles(vcpu, lapic_timer_advance_ns);
13727 if (delta_tsc > lapic_timer_advance_cycles)
13728 delta_tsc -= lapic_timer_advance_cycles;
13729 else
13730 delta_tsc = 0;
13732 /* Convert to host delta tsc if tsc scaling is enabled */
13733 if (vcpu->arch.tsc_scaling_ratio != kvm_default_tsc_scaling_ratio &&
13734 u64_shl_div_u64(delta_tsc,
13735 kvm_tsc_scaling_ratio_frac_bits,
13736 vcpu->arch.tsc_scaling_ratio,
13737 &delta_tsc))
13738 return -ERANGE;
13741 * If the delta tsc can't fit in the 32 bit after the multi shift,
13742 * we can't use the preemption timer.
13743 * It's possible that it fits on later vmentries, but checking
13744 * on every vmentry is costly so we just use an hrtimer.
13746 if (delta_tsc >> (cpu_preemption_timer_multi + 32))
13747 return -ERANGE;
13749 vmx->hv_deadline_tsc = tscl + delta_tsc;
13750 return delta_tsc == 0;
13753 static void vmx_cancel_hv_timer(struct kvm_vcpu *vcpu)
13755 to_vmx(vcpu)->hv_deadline_tsc = -1;
13757 #endif
13759 static void vmx_sched_in(struct kvm_vcpu *vcpu, int cpu)
13761 if (!kvm_pause_in_guest(vcpu->kvm))
13762 shrink_ple_window(vcpu);
13765 static void vmx_slot_enable_log_dirty(struct kvm *kvm,
13766 struct kvm_memory_slot *slot)
13768 kvm_mmu_slot_leaf_clear_dirty(kvm, slot);
13769 kvm_mmu_slot_largepage_remove_write_access(kvm, slot);
13772 static void vmx_slot_disable_log_dirty(struct kvm *kvm,
13773 struct kvm_memory_slot *slot)
13775 kvm_mmu_slot_set_dirty(kvm, slot);
13778 static void vmx_flush_log_dirty(struct kvm *kvm)
13780 kvm_flush_pml_buffers(kvm);
13783 static int vmx_write_pml_buffer(struct kvm_vcpu *vcpu)
13785 struct vmcs12 *vmcs12;
13786 struct vcpu_vmx *vmx = to_vmx(vcpu);
13787 gpa_t gpa;
13788 struct page *page = NULL;
13789 u64 *pml_address;
13791 if (is_guest_mode(vcpu)) {
13792 WARN_ON_ONCE(vmx->nested.pml_full);
13795 * Check if PML is enabled for the nested guest.
13796 * Whether eptp bit 6 is set is already checked
13797 * as part of A/D emulation.
13799 vmcs12 = get_vmcs12(vcpu);
13800 if (!nested_cpu_has_pml(vmcs12))
13801 return 0;
13803 if (vmcs12->guest_pml_index >= PML_ENTITY_NUM) {
13804 vmx->nested.pml_full = true;
13805 return 1;
13808 gpa = vmcs_read64(GUEST_PHYSICAL_ADDRESS) & ~0xFFFull;
13810 page = kvm_vcpu_gpa_to_page(vcpu, vmcs12->pml_address);
13811 if (is_error_page(page))
13812 return 0;
13814 pml_address = kmap(page);
13815 pml_address[vmcs12->guest_pml_index--] = gpa;
13816 kunmap(page);
13817 kvm_release_page_clean(page);
13820 return 0;
13823 static void vmx_enable_log_dirty_pt_masked(struct kvm *kvm,
13824 struct kvm_memory_slot *memslot,
13825 gfn_t offset, unsigned long mask)
13827 kvm_mmu_clear_dirty_pt_masked(kvm, memslot, offset, mask);
13830 static void __pi_post_block(struct kvm_vcpu *vcpu)
13832 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13833 struct pi_desc old, new;
13834 unsigned int dest;
13836 do {
13837 old.control = new.control = pi_desc->control;
13838 WARN(old.nv != POSTED_INTR_WAKEUP_VECTOR,
13839 "Wakeup handler not enabled while the VCPU is blocked\n");
13841 dest = cpu_physical_id(vcpu->cpu);
13843 if (x2apic_enabled())
13844 new.ndst = dest;
13845 else
13846 new.ndst = (dest << 8) & 0xFF00;
13848 /* set 'NV' to 'notification vector' */
13849 new.nv = POSTED_INTR_VECTOR;
13850 } while (cmpxchg64(&pi_desc->control, old.control,
13851 new.control) != old.control);
13853 if (!WARN_ON_ONCE(vcpu->pre_pcpu == -1)) {
13854 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13855 list_del(&vcpu->blocked_vcpu_list);
13856 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13857 vcpu->pre_pcpu = -1;
13862 * This routine does the following things for vCPU which is going
13863 * to be blocked if VT-d PI is enabled.
13864 * - Store the vCPU to the wakeup list, so when interrupts happen
13865 * we can find the right vCPU to wake up.
13866 * - Change the Posted-interrupt descriptor as below:
13867 * 'NDST' <-- vcpu->pre_pcpu
13868 * 'NV' <-- POSTED_INTR_WAKEUP_VECTOR
13869 * - If 'ON' is set during this process, which means at least one
13870 * interrupt is posted for this vCPU, we cannot block it, in
13871 * this case, return 1, otherwise, return 0.
13874 static int pi_pre_block(struct kvm_vcpu *vcpu)
13876 unsigned int dest;
13877 struct pi_desc old, new;
13878 struct pi_desc *pi_desc = vcpu_to_pi_desc(vcpu);
13880 if (!kvm_arch_has_assigned_device(vcpu->kvm) ||
13881 !irq_remapping_cap(IRQ_POSTING_CAP) ||
13882 !kvm_vcpu_apicv_active(vcpu))
13883 return 0;
13885 WARN_ON(irqs_disabled());
13886 local_irq_disable();
13887 if (!WARN_ON_ONCE(vcpu->pre_pcpu != -1)) {
13888 vcpu->pre_pcpu = vcpu->cpu;
13889 spin_lock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13890 list_add_tail(&vcpu->blocked_vcpu_list,
13891 &per_cpu(blocked_vcpu_on_cpu,
13892 vcpu->pre_pcpu));
13893 spin_unlock(&per_cpu(blocked_vcpu_on_cpu_lock, vcpu->pre_pcpu));
13896 do {
13897 old.control = new.control = pi_desc->control;
13899 WARN((pi_desc->sn == 1),
13900 "Warning: SN field of posted-interrupts "
13901 "is set before blocking\n");
13904 * Since vCPU can be preempted during this process,
13905 * vcpu->cpu could be different with pre_pcpu, we
13906 * need to set pre_pcpu as the destination of wakeup
13907 * notification event, then we can find the right vCPU
13908 * to wakeup in wakeup handler if interrupts happen
13909 * when the vCPU is in blocked state.
13911 dest = cpu_physical_id(vcpu->pre_pcpu);
13913 if (x2apic_enabled())
13914 new.ndst = dest;
13915 else
13916 new.ndst = (dest << 8) & 0xFF00;
13918 /* set 'NV' to 'wakeup vector' */
13919 new.nv = POSTED_INTR_WAKEUP_VECTOR;
13920 } while (cmpxchg64(&pi_desc->control, old.control,
13921 new.control) != old.control);
13923 /* We should not block the vCPU if an interrupt is posted for it. */
13924 if (pi_test_on(pi_desc) == 1)
13925 __pi_post_block(vcpu);
13927 local_irq_enable();
13928 return (vcpu->pre_pcpu == -1);
13931 static int vmx_pre_block(struct kvm_vcpu *vcpu)
13933 if (pi_pre_block(vcpu))
13934 return 1;
13936 if (kvm_lapic_hv_timer_in_use(vcpu))
13937 kvm_lapic_switch_to_sw_timer(vcpu);
13939 return 0;
13942 static void pi_post_block(struct kvm_vcpu *vcpu)
13944 if (vcpu->pre_pcpu == -1)
13945 return;
13947 WARN_ON(irqs_disabled());
13948 local_irq_disable();
13949 __pi_post_block(vcpu);
13950 local_irq_enable();
13953 static void vmx_post_block(struct kvm_vcpu *vcpu)
13955 if (kvm_x86_ops->set_hv_timer)
13956 kvm_lapic_switch_to_hv_timer(vcpu);
13958 pi_post_block(vcpu);
13962 * vmx_update_pi_irte - set IRTE for Posted-Interrupts
13964 * @kvm: kvm
13965 * @host_irq: host irq of the interrupt
13966 * @guest_irq: gsi of the interrupt
13967 * @set: set or unset PI
13968 * returns 0 on success, < 0 on failure
13970 static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
13971 uint32_t guest_irq, bool set)
13973 struct kvm_kernel_irq_routing_entry *e;
13974 struct kvm_irq_routing_table *irq_rt;
13975 struct kvm_lapic_irq irq;
13976 struct kvm_vcpu *vcpu;
13977 struct vcpu_data vcpu_info;
13978 int idx, ret = 0;
13980 if (!kvm_arch_has_assigned_device(kvm) ||
13981 !irq_remapping_cap(IRQ_POSTING_CAP) ||
13982 !kvm_vcpu_apicv_active(kvm->vcpus[0]))
13983 return 0;
13985 idx = srcu_read_lock(&kvm->irq_srcu);
13986 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
13987 if (guest_irq >= irq_rt->nr_rt_entries ||
13988 hlist_empty(&irq_rt->map[guest_irq])) {
13989 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
13990 guest_irq, irq_rt->nr_rt_entries);
13991 goto out;
13994 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
13995 if (e->type != KVM_IRQ_ROUTING_MSI)
13996 continue;
13998 * VT-d PI cannot support posting multicast/broadcast
13999 * interrupts to a vCPU, we still use interrupt remapping
14000 * for these kind of interrupts.
14002 * For lowest-priority interrupts, we only support
14003 * those with single CPU as the destination, e.g. user
14004 * configures the interrupts via /proc/irq or uses
14005 * irqbalance to make the interrupts single-CPU.
14007 * We will support full lowest-priority interrupt later.
14010 kvm_set_msi_irq(kvm, e, &irq);
14011 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
14013 * Make sure the IRTE is in remapped mode if
14014 * we don't handle it in posted mode.
14016 ret = irq_set_vcpu_affinity(host_irq, NULL);
14017 if (ret < 0) {
14018 printk(KERN_INFO
14019 "failed to back to remapped mode, irq: %u\n",
14020 host_irq);
14021 goto out;
14024 continue;
14027 vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
14028 vcpu_info.vector = irq.vector;
14030 trace_kvm_pi_irte_update(host_irq, vcpu->vcpu_id, e->gsi,
14031 vcpu_info.vector, vcpu_info.pi_desc_addr, set);
14033 if (set)
14034 ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
14035 else
14036 ret = irq_set_vcpu_affinity(host_irq, NULL);
14038 if (ret < 0) {
14039 printk(KERN_INFO "%s: failed to update PI IRTE\n",
14040 __func__);
14041 goto out;
14045 ret = 0;
14046 out:
14047 srcu_read_unlock(&kvm->irq_srcu, idx);
14048 return ret;
14051 static void vmx_setup_mce(struct kvm_vcpu *vcpu)
14053 if (vcpu->arch.mcg_cap & MCG_LMCE_P)
14054 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits |=
14055 FEATURE_CONTROL_LMCE;
14056 else
14057 to_vmx(vcpu)->msr_ia32_feature_control_valid_bits &=
14058 ~FEATURE_CONTROL_LMCE;
14061 static int vmx_smi_allowed(struct kvm_vcpu *vcpu)
14063 /* we need a nested vmexit to enter SMM, postpone if run is pending */
14064 if (to_vmx(vcpu)->nested.nested_run_pending)
14065 return 0;
14066 return 1;
14069 static int vmx_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
14071 struct vcpu_vmx *vmx = to_vmx(vcpu);
14073 vmx->nested.smm.guest_mode = is_guest_mode(vcpu);
14074 if (vmx->nested.smm.guest_mode)
14075 nested_vmx_vmexit(vcpu, -1, 0, 0);
14077 vmx->nested.smm.vmxon = vmx->nested.vmxon;
14078 vmx->nested.vmxon = false;
14079 vmx_clear_hlt(vcpu);
14080 return 0;
14083 static int vmx_pre_leave_smm(struct kvm_vcpu *vcpu, u64 smbase)
14085 struct vcpu_vmx *vmx = to_vmx(vcpu);
14086 int ret;
14088 if (vmx->nested.smm.vmxon) {
14089 vmx->nested.vmxon = true;
14090 vmx->nested.smm.vmxon = false;
14093 if (vmx->nested.smm.guest_mode) {
14094 vcpu->arch.hflags &= ~HF_SMM_MASK;
14095 ret = enter_vmx_non_root_mode(vcpu, NULL);
14096 vcpu->arch.hflags |= HF_SMM_MASK;
14097 if (ret)
14098 return ret;
14100 vmx->nested.smm.guest_mode = false;
14102 return 0;
14105 static int enable_smi_window(struct kvm_vcpu *vcpu)
14107 return 0;
14110 static int vmx_get_nested_state(struct kvm_vcpu *vcpu,
14111 struct kvm_nested_state __user *user_kvm_nested_state,
14112 u32 user_data_size)
14114 struct vcpu_vmx *vmx;
14115 struct vmcs12 *vmcs12;
14116 struct kvm_nested_state kvm_state = {
14117 .flags = 0,
14118 .format = 0,
14119 .size = sizeof(kvm_state),
14120 .vmx.vmxon_pa = -1ull,
14121 .vmx.vmcs_pa = -1ull,
14124 if (!vcpu)
14125 return kvm_state.size + 2 * VMCS12_SIZE;
14127 vmx = to_vmx(vcpu);
14128 vmcs12 = get_vmcs12(vcpu);
14129 if (nested_vmx_allowed(vcpu) &&
14130 (vmx->nested.vmxon || vmx->nested.smm.vmxon)) {
14131 kvm_state.vmx.vmxon_pa = vmx->nested.vmxon_ptr;
14132 kvm_state.vmx.vmcs_pa = vmx->nested.current_vmptr;
14134 if (vmx->nested.current_vmptr != -1ull) {
14135 kvm_state.size += VMCS12_SIZE;
14137 if (is_guest_mode(vcpu) &&
14138 nested_cpu_has_shadow_vmcs(vmcs12) &&
14139 vmcs12->vmcs_link_pointer != -1ull)
14140 kvm_state.size += VMCS12_SIZE;
14143 if (vmx->nested.smm.vmxon)
14144 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_VMXON;
14146 if (vmx->nested.smm.guest_mode)
14147 kvm_state.vmx.smm.flags |= KVM_STATE_NESTED_SMM_GUEST_MODE;
14149 if (is_guest_mode(vcpu)) {
14150 kvm_state.flags |= KVM_STATE_NESTED_GUEST_MODE;
14152 if (vmx->nested.nested_run_pending)
14153 kvm_state.flags |= KVM_STATE_NESTED_RUN_PENDING;
14157 if (user_data_size < kvm_state.size)
14158 goto out;
14160 if (copy_to_user(user_kvm_nested_state, &kvm_state, sizeof(kvm_state)))
14161 return -EFAULT;
14163 if (vmx->nested.current_vmptr == -1ull)
14164 goto out;
14167 * When running L2, the authoritative vmcs12 state is in the
14168 * vmcs02. When running L1, the authoritative vmcs12 state is
14169 * in the shadow vmcs linked to vmcs01, unless
14170 * sync_shadow_vmcs is set, in which case, the authoritative
14171 * vmcs12 state is in the vmcs12 already.
14173 if (is_guest_mode(vcpu))
14174 sync_vmcs12(vcpu, vmcs12);
14175 else if (enable_shadow_vmcs && !vmx->nested.sync_shadow_vmcs)
14176 copy_shadow_to_vmcs12(vmx);
14179 * Copy over the full allocated size of vmcs12 rather than just the size
14180 * of the struct.
14182 if (copy_to_user(user_kvm_nested_state->data, vmcs12, VMCS12_SIZE))
14183 return -EFAULT;
14185 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14186 vmcs12->vmcs_link_pointer != -1ull) {
14187 if (copy_to_user(user_kvm_nested_state->data + VMCS12_SIZE,
14188 get_shadow_vmcs12(vcpu), VMCS12_SIZE))
14189 return -EFAULT;
14192 out:
14193 return kvm_state.size;
14196 static int vmx_set_nested_state(struct kvm_vcpu *vcpu,
14197 struct kvm_nested_state __user *user_kvm_nested_state,
14198 struct kvm_nested_state *kvm_state)
14200 struct vcpu_vmx *vmx = to_vmx(vcpu);
14201 struct vmcs12 *vmcs12;
14202 u32 exit_qual;
14203 int ret;
14205 if (kvm_state->format != 0)
14206 return -EINVAL;
14208 if (!nested_vmx_allowed(vcpu))
14209 return kvm_state->vmx.vmxon_pa == -1ull ? 0 : -EINVAL;
14211 if (kvm_state->vmx.vmxon_pa == -1ull) {
14212 if (kvm_state->vmx.smm.flags)
14213 return -EINVAL;
14215 if (kvm_state->vmx.vmcs_pa != -1ull)
14216 return -EINVAL;
14218 vmx_leave_nested(vcpu);
14219 return 0;
14222 if (!page_address_valid(vcpu, kvm_state->vmx.vmxon_pa))
14223 return -EINVAL;
14225 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14226 (kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14227 return -EINVAL;
14229 if (kvm_state->vmx.smm.flags &
14230 ~(KVM_STATE_NESTED_SMM_GUEST_MODE | KVM_STATE_NESTED_SMM_VMXON))
14231 return -EINVAL;
14234 * SMM temporarily disables VMX, so we cannot be in guest mode,
14235 * nor can VMLAUNCH/VMRESUME be pending. Outside SMM, SMM flags
14236 * must be zero.
14238 if (is_smm(vcpu) ? kvm_state->flags : kvm_state->vmx.smm.flags)
14239 return -EINVAL;
14241 if ((kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE) &&
14242 !(kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON))
14243 return -EINVAL;
14245 vmx_leave_nested(vcpu);
14246 if (kvm_state->vmx.vmxon_pa == -1ull)
14247 return 0;
14249 vmx->nested.vmxon_ptr = kvm_state->vmx.vmxon_pa;
14250 ret = enter_vmx_operation(vcpu);
14251 if (ret)
14252 return ret;
14254 /* Empty 'VMXON' state is permitted */
14255 if (kvm_state->size < sizeof(*kvm_state) + sizeof(*vmcs12))
14256 return 0;
14258 if (kvm_state->vmx.vmcs_pa == kvm_state->vmx.vmxon_pa ||
14259 !page_address_valid(vcpu, kvm_state->vmx.vmcs_pa))
14260 return -EINVAL;
14262 set_current_vmptr(vmx, kvm_state->vmx.vmcs_pa);
14264 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_VMXON) {
14265 vmx->nested.smm.vmxon = true;
14266 vmx->nested.vmxon = false;
14268 if (kvm_state->vmx.smm.flags & KVM_STATE_NESTED_SMM_GUEST_MODE)
14269 vmx->nested.smm.guest_mode = true;
14272 vmcs12 = get_vmcs12(vcpu);
14273 if (copy_from_user(vmcs12, user_kvm_nested_state->data, sizeof(*vmcs12)))
14274 return -EFAULT;
14276 if (vmcs12->hdr.revision_id != VMCS12_REVISION)
14277 return -EINVAL;
14279 if (!(kvm_state->flags & KVM_STATE_NESTED_GUEST_MODE))
14280 return 0;
14282 vmx->nested.nested_run_pending =
14283 !!(kvm_state->flags & KVM_STATE_NESTED_RUN_PENDING);
14285 if (nested_cpu_has_shadow_vmcs(vmcs12) &&
14286 vmcs12->vmcs_link_pointer != -1ull) {
14287 struct vmcs12 *shadow_vmcs12 = get_shadow_vmcs12(vcpu);
14288 if (kvm_state->size < sizeof(*kvm_state) + 2 * sizeof(*vmcs12))
14289 return -EINVAL;
14291 if (copy_from_user(shadow_vmcs12,
14292 user_kvm_nested_state->data + VMCS12_SIZE,
14293 sizeof(*vmcs12)))
14294 return -EFAULT;
14296 if (shadow_vmcs12->hdr.revision_id != VMCS12_REVISION ||
14297 !shadow_vmcs12->hdr.shadow_vmcs)
14298 return -EINVAL;
14301 if (check_vmentry_prereqs(vcpu, vmcs12) ||
14302 check_vmentry_postreqs(vcpu, vmcs12, &exit_qual))
14303 return -EINVAL;
14305 vmx->nested.dirty_vmcs12 = true;
14306 ret = enter_vmx_non_root_mode(vcpu, NULL);
14307 if (ret)
14308 return -EINVAL;
14310 return 0;
14313 static struct kvm_x86_ops vmx_x86_ops __ro_after_init = {
14314 .cpu_has_kvm_support = cpu_has_kvm_support,
14315 .disabled_by_bios = vmx_disabled_by_bios,
14316 .hardware_setup = hardware_setup,
14317 .hardware_unsetup = hardware_unsetup,
14318 .check_processor_compatibility = vmx_check_processor_compat,
14319 .hardware_enable = hardware_enable,
14320 .hardware_disable = hardware_disable,
14321 .cpu_has_accelerated_tpr = report_flexpriority,
14322 .has_emulated_msr = vmx_has_emulated_msr,
14324 .vm_init = vmx_vm_init,
14325 .vm_alloc = vmx_vm_alloc,
14326 .vm_free = vmx_vm_free,
14328 .vcpu_create = vmx_create_vcpu,
14329 .vcpu_free = vmx_free_vcpu,
14330 .vcpu_reset = vmx_vcpu_reset,
14332 .prepare_guest_switch = vmx_prepare_switch_to_guest,
14333 .vcpu_load = vmx_vcpu_load,
14334 .vcpu_put = vmx_vcpu_put,
14336 .update_bp_intercept = update_exception_bitmap,
14337 .get_msr_feature = vmx_get_msr_feature,
14338 .get_msr = vmx_get_msr,
14339 .set_msr = vmx_set_msr,
14340 .get_segment_base = vmx_get_segment_base,
14341 .get_segment = vmx_get_segment,
14342 .set_segment = vmx_set_segment,
14343 .get_cpl = vmx_get_cpl,
14344 .get_cs_db_l_bits = vmx_get_cs_db_l_bits,
14345 .decache_cr0_guest_bits = vmx_decache_cr0_guest_bits,
14346 .decache_cr3 = vmx_decache_cr3,
14347 .decache_cr4_guest_bits = vmx_decache_cr4_guest_bits,
14348 .set_cr0 = vmx_set_cr0,
14349 .set_cr3 = vmx_set_cr3,
14350 .set_cr4 = vmx_set_cr4,
14351 .set_efer = vmx_set_efer,
14352 .get_idt = vmx_get_idt,
14353 .set_idt = vmx_set_idt,
14354 .get_gdt = vmx_get_gdt,
14355 .set_gdt = vmx_set_gdt,
14356 .get_dr6 = vmx_get_dr6,
14357 .set_dr6 = vmx_set_dr6,
14358 .set_dr7 = vmx_set_dr7,
14359 .sync_dirty_debug_regs = vmx_sync_dirty_debug_regs,
14360 .cache_reg = vmx_cache_reg,
14361 .get_rflags = vmx_get_rflags,
14362 .set_rflags = vmx_set_rflags,
14364 .tlb_flush = vmx_flush_tlb,
14365 .tlb_flush_gva = vmx_flush_tlb_gva,
14367 .run = vmx_vcpu_run,
14368 .handle_exit = vmx_handle_exit,
14369 .skip_emulated_instruction = skip_emulated_instruction,
14370 .set_interrupt_shadow = vmx_set_interrupt_shadow,
14371 .get_interrupt_shadow = vmx_get_interrupt_shadow,
14372 .patch_hypercall = vmx_patch_hypercall,
14373 .set_irq = vmx_inject_irq,
14374 .set_nmi = vmx_inject_nmi,
14375 .queue_exception = vmx_queue_exception,
14376 .cancel_injection = vmx_cancel_injection,
14377 .interrupt_allowed = vmx_interrupt_allowed,
14378 .nmi_allowed = vmx_nmi_allowed,
14379 .get_nmi_mask = vmx_get_nmi_mask,
14380 .set_nmi_mask = vmx_set_nmi_mask,
14381 .enable_nmi_window = enable_nmi_window,
14382 .enable_irq_window = enable_irq_window,
14383 .update_cr8_intercept = update_cr8_intercept,
14384 .set_virtual_apic_mode = vmx_set_virtual_apic_mode,
14385 .set_apic_access_page_addr = vmx_set_apic_access_page_addr,
14386 .get_enable_apicv = vmx_get_enable_apicv,
14387 .refresh_apicv_exec_ctrl = vmx_refresh_apicv_exec_ctrl,
14388 .load_eoi_exitmap = vmx_load_eoi_exitmap,
14389 .apicv_post_state_restore = vmx_apicv_post_state_restore,
14390 .hwapic_irr_update = vmx_hwapic_irr_update,
14391 .hwapic_isr_update = vmx_hwapic_isr_update,
14392 .guest_apic_has_interrupt = vmx_guest_apic_has_interrupt,
14393 .sync_pir_to_irr = vmx_sync_pir_to_irr,
14394 .deliver_posted_interrupt = vmx_deliver_posted_interrupt,
14395 .dy_apicv_has_pending_interrupt = vmx_dy_apicv_has_pending_interrupt,
14397 .set_tss_addr = vmx_set_tss_addr,
14398 .set_identity_map_addr = vmx_set_identity_map_addr,
14399 .get_tdp_level = get_ept_level,
14400 .get_mt_mask = vmx_get_mt_mask,
14402 .get_exit_info = vmx_get_exit_info,
14404 .get_lpage_level = vmx_get_lpage_level,
14406 .cpuid_update = vmx_cpuid_update,
14408 .rdtscp_supported = vmx_rdtscp_supported,
14409 .invpcid_supported = vmx_invpcid_supported,
14411 .set_supported_cpuid = vmx_set_supported_cpuid,
14413 .has_wbinvd_exit = cpu_has_vmx_wbinvd_exit,
14415 .read_l1_tsc_offset = vmx_read_l1_tsc_offset,
14416 .write_l1_tsc_offset = vmx_write_l1_tsc_offset,
14418 .set_tdp_cr3 = vmx_set_cr3,
14420 .check_intercept = vmx_check_intercept,
14421 .handle_external_intr = vmx_handle_external_intr,
14422 .mpx_supported = vmx_mpx_supported,
14423 .xsaves_supported = vmx_xsaves_supported,
14424 .umip_emulated = vmx_umip_emulated,
14426 .check_nested_events = vmx_check_nested_events,
14427 .request_immediate_exit = vmx_request_immediate_exit,
14429 .sched_in = vmx_sched_in,
14431 .slot_enable_log_dirty = vmx_slot_enable_log_dirty,
14432 .slot_disable_log_dirty = vmx_slot_disable_log_dirty,
14433 .flush_log_dirty = vmx_flush_log_dirty,
14434 .enable_log_dirty_pt_masked = vmx_enable_log_dirty_pt_masked,
14435 .write_log_dirty = vmx_write_pml_buffer,
14437 .pre_block = vmx_pre_block,
14438 .post_block = vmx_post_block,
14440 .pmu_ops = &intel_pmu_ops,
14442 .update_pi_irte = vmx_update_pi_irte,
14444 #ifdef CONFIG_X86_64
14445 .set_hv_timer = vmx_set_hv_timer,
14446 .cancel_hv_timer = vmx_cancel_hv_timer,
14447 #endif
14449 .setup_mce = vmx_setup_mce,
14451 .get_nested_state = vmx_get_nested_state,
14452 .set_nested_state = vmx_set_nested_state,
14453 .get_vmcs12_pages = nested_get_vmcs12_pages,
14455 .smi_allowed = vmx_smi_allowed,
14456 .pre_enter_smm = vmx_pre_enter_smm,
14457 .pre_leave_smm = vmx_pre_leave_smm,
14458 .enable_smi_window = enable_smi_window,
14461 static void vmx_cleanup_l1d_flush(void)
14463 if (vmx_l1d_flush_pages) {
14464 free_pages((unsigned long)vmx_l1d_flush_pages, L1D_CACHE_ORDER);
14465 vmx_l1d_flush_pages = NULL;
14467 /* Restore state so sysfs ignores VMX */
14468 l1tf_vmx_mitigation = VMENTER_L1D_FLUSH_AUTO;
14471 static void vmx_exit(void)
14473 #ifdef CONFIG_KEXEC_CORE
14474 RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
14475 synchronize_rcu();
14476 #endif
14478 kvm_exit();
14480 #if IS_ENABLED(CONFIG_HYPERV)
14481 if (static_branch_unlikely(&enable_evmcs)) {
14482 int cpu;
14483 struct hv_vp_assist_page *vp_ap;
14485 * Reset everything to support using non-enlightened VMCS
14486 * access later (e.g. when we reload the module with
14487 * enlightened_vmcs=0)
14489 for_each_online_cpu(cpu) {
14490 vp_ap = hv_get_vp_assist_page(cpu);
14492 if (!vp_ap)
14493 continue;
14495 vp_ap->current_nested_vmcs = 0;
14496 vp_ap->enlighten_vmentry = 0;
14499 static_branch_disable(&enable_evmcs);
14501 #endif
14502 vmx_cleanup_l1d_flush();
14504 module_exit(vmx_exit);
14506 static int __init vmx_init(void)
14508 int r;
14510 #if IS_ENABLED(CONFIG_HYPERV)
14512 * Enlightened VMCS usage should be recommended and the host needs
14513 * to support eVMCS v1 or above. We can also disable eVMCS support
14514 * with module parameter.
14516 if (enlightened_vmcs &&
14517 ms_hyperv.hints & HV_X64_ENLIGHTENED_VMCS_RECOMMENDED &&
14518 (ms_hyperv.nested_features & HV_X64_ENLIGHTENED_VMCS_VERSION) >=
14519 KVM_EVMCS_VERSION) {
14520 int cpu;
14522 /* Check that we have assist pages on all online CPUs */
14523 for_each_online_cpu(cpu) {
14524 if (!hv_get_vp_assist_page(cpu)) {
14525 enlightened_vmcs = false;
14526 break;
14530 if (enlightened_vmcs) {
14531 pr_info("KVM: vmx: using Hyper-V Enlightened VMCS\n");
14532 static_branch_enable(&enable_evmcs);
14534 } else {
14535 enlightened_vmcs = false;
14537 #endif
14539 r = kvm_init(&vmx_x86_ops, sizeof(struct vcpu_vmx),
14540 __alignof__(struct vcpu_vmx), THIS_MODULE);
14541 if (r)
14542 return r;
14545 * Must be called after kvm_init() so enable_ept is properly set
14546 * up. Hand the parameter mitigation value in which was stored in
14547 * the pre module init parser. If no parameter was given, it will
14548 * contain 'auto' which will be turned into the default 'cond'
14549 * mitigation mode.
14551 if (boot_cpu_has(X86_BUG_L1TF)) {
14552 r = vmx_setup_l1d_flush(vmentry_l1d_flush_param);
14553 if (r) {
14554 vmx_exit();
14555 return r;
14559 #ifdef CONFIG_KEXEC_CORE
14560 rcu_assign_pointer(crash_vmclear_loaded_vmcss,
14561 crash_vmclear_local_loaded_vmcss);
14562 #endif
14563 vmx_check_vmcs12_offsets();
14565 return 0;
14567 module_init(vmx_init);